mercredi 6 mai 2015

How to use a set of characters in the javascript match method

How can I use all the following characters as a regular expression in the javascript match method and escape the characters that need to be escaped?

~!@#$%^&*()_-+={}[]|:;<>,./? and space

so that mysstring.match(REGEX) returns null only if mysstring does not contain any of the above set of characters

 "abc".match(REGEX) //should return null
 "abc@".match(REGEX) //should NOT return null (it has @)
 "ab c".match(REGEX) //should NOT return null (it has a space)
 "++abc".match(REGEX) //should NOT return null (it has +)

Limiting the jQuery search scope correctly?

I've stumbled up this code and I'm wondering if its just limiting the scope or selecting both of the elements at the same time.

container = jQuery("#test", parent.document);

jQuery("param[name=scale]", another.object)

Can anyone shed some light on this?

Submitting Values From a Jquery Slider

Hey guys I have this code here for a jquery slider. I want to take the value of the slider out and use an http post method to submit the value to a database. I have a processing form which I used successfully for textboxes and radio buttons. I was hoping to save the value of the slider in a hidden field and just post it. I know this gets the value from the slider.

    var selection = $( ".selector" ).slider( "value" );

Now how can I add this into the value in this submit form?

    <input type='hidden' class="mainForm" id="fieldBox_5" name="field_5" value=selection>

This is my whole code.

    <<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery UI Slider - Slider bound to select</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="style.css">
  <script>
  $(function() {
    var select = $( "#minbeds" );
    var slider = $( "<div id='slider'></div>" ).insertAfter( select ).slider({
      min: 1,
      max: 10,
      range: "min",
      value: select[ 0 ].selectedIndex + 1,
      slide: function( event, ui ) {
        select[ 0 ].selectedIndex = ui.value - 1;
      }
    });
    $( "#minbeds" ).change(function() {
      slider.slider( "value", this.selectedIndex + 1 );
    });
  });
  var selection = $( ".selector" ).slider( "value" );
  </script>
</head>
<body>

<form id="mainForm_1" class="MainForm" method=post enctype=multipart/form-data action=processorss.php onSubmit="return validatePage1();">



  <label for="minbeds" class="mainForm">Rate Your Prefence for Fish 1-10</label>
 <select name="minbeds" id="minbeds">
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>
    <option>6</option>
    <option>7</option>
    <option>8</option>
    <option>9</option>
    <option>10</option>
  </select>
  <li class="mainForm">



  <input type='hidden' class="mainForm" id="fieldBox_5" name="field_5" value=selection>

                    <input id="saveForm" class="mainForm" type="submit" value="Submit" />
                </li>
</form>


</body>
</html>

Randomly space characters throughout string?

To shuffle a string, I could use something like this

String.prototype.shuffle = function () {
    var arr = this.split("");
    var len = arr.length;
    for (var n = len - 1; n > 0; n--) {
        m = Math.floor(Math.random() * (n + 1));
        tmp = arr[n];
        arr[n] = arr[m];
        arr[m] = tmp;
    }
    return arr.join("");
}

But how could I randomly space it with n characters, while preserving the string order?

For example:

"test"   =>   "t-es--t"
"test"   =>   "-t-e-st"
"test"   =>   "te--st-"

I've thought about creating a list from the string, generating a random number to represent an index, and then shifting the list to the left, but is there a better way to do this?

Jquery Sortable retrieve hidden Id on change

i am using the jquery sortable arrange images in a certain order, all i want to do is on change get the hidden id of the image and the new current position number so i can run an ajax request to update the new position in my database, however when i change the image position the alert is not triggered(in below code) so i am wondering what i am doing wrong.

Jquery code

<script>
        $(function() {
            $("#sortable").sortable({
                stop: function(event, ui) {

                    $('input.imageHiddenImageId').each(function(idx) {

                        var imageId = (this).val();
                        alert("New position: " + ui.item.index() + "id:" + imageId);
                        //Run some AJAX code to server
                    });

                }
            });
            $( "#sortable" ).disableSelection();
        });
    </script>

HTML code

<ul id="sortable">
   <li class="ui-state-default">
      <img src="http://localhost/site/gallery/3.png" style="max-width: 100%; height: auto;">
      <input type="hidden" class="imageHiddenImageId" id="imageHiddenImageId" name="imageHiddenImageId" value="45">
      <input type="hidden" id="imageHiddenNo" name="imageHiddenNo" value="2">
    </li>
 </ul>

Thanks for the help

jstree custom node markup

Is there a way to have custom markup or add additional html elements to some of the nodes.

For example, we want to add an arrow (link) right after the node text for all the nodes under a path, and when user click on the arrow, open the context menu. I know the context menu can be opened using the right click, but the requirement is to have an arrow after the node and clicking on the arrow should open the context menu.

Is there a way to customize or add additional html elements to selective tree nodes, and programmatically open the context menu or link click event.

Can't return the response data using jQuery AJAX

I'm loading cross domain html page with jQuery AJAX.

My problem is to return or equal the response data (target's html code) .

var html = "";

get("http://google.com");

function get( url ){

    $.ajaxPrefilter( function (options) {
        if (options.crossDomain && jQuery.support.cors) {
            var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
            options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
        }
    });

    $.get(url,function (response) {

         // Here is the problem

     });    
}

In the $.get() method I tried to :

html = result ;

return result ;

Both tries didn't work.

Is there any similar way to 'export' the response data to a global scope var ?

P.S - I've tried to use a function with a parameter to return the response . It worked perfectly but that is not what I want at all.

Javascript. if else if else confusion

Why the else if condition still executes when the if condition is already true? I thought if the if condition is true anything under it like else if...else or else will be worthless. code:

for (i = 1; i <= 20; i++)
{
    if (i % 3 === 0 && i % 5 === 0)
    {
        console.log("FizzBuzz");
    }
    else if (i % 3 === 0)
    {
        console.log("Fizz");
    }
    else if (i % 5 === 0)
    {
        console.log("Buzz");
    }
    else
    {
        console.log(i);
    }
}

this is the output

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz

Display uploaded images on button click

On click of button preview i need the uploaded images to be shown ,the scripts it's working fine for changing event but not for the click one.

HTML

 <form action="test.php" enctype="multipart/form-data" id="mainform" method="post" name="mainform">
Imagine 1:<br>
 <input type="file" name="img1" id="img1"><br>
     <br><br>     
Imagine 2 :<br>
 <input type="file" name="img2" id="img2"><br>
     <br>
 Imagine 3 :<br>
 <input type="file" name="img3" id="img3"><br> 
     <br>
 Imagine 4 :<br>
 <input type="file" name="img4" id="img4"><br>    
     <br>
 Imagine 5 :<br>
 <input type="file" name="img5" id="img5"><br>   
     <br>
 Imagine 6 :<br>
 <input type="file" name="img6" id="img6"><br>   
     <br>
 Imagine 7 :<br>
 <input type="file" name="img7" id="img7"><br>    
     <br>
 Imagine 8 :<br>
 <input type="file" name="img8" id="img8"><br>    
     <br>
 Imagine 9 :<br>
 <input type="file" name="img9" id="img9"><br>   
     <br>
 Imagine 10 :<br>
 <input type="file" name="img10" id="img10"><br>    
     <br>
 Imagine 11 :<br>
 <input type="file" name="img11" id="img11"><br> 
     <br>
 Imagine 12 :<br>
 <input type="file" name="img12" id="img12"><br>    
     <br>
 Imagine 13 :<br>
 <input type="file" name="img13" id="img13"><br>    
     <br>
 Imagine 14 :<br>
 <input type="file" name="img14" id="img14"><br>     
     <br>
 Imagine 15 :<br>
 <input type="file" name="img15" id="img15"><br>    
     <br />
     Preview:
     <br />
     <input type="checkbox" id="previz" />Preview
</form>
<div id="#previzdiv">
<img src="" id="preview-img1">
<img src="" id="preview-img2">
<img src="" id="preview-img3">
<img src="" id="preview-img9">
<img src="" id="preview-img5">
</div>

Jquery:

$("#center2 #forme #previz").change(function(){
if(this.checked){
for(i=1;i<15;i++){
j = $("form#mainform #img"+i);
console.log(j);
readURL(j);
}
}

});
function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                imgId = '#preview-'+$(input).attr('id');
                $(imgId).attr('src', e.target.result);
            }

            reader.readAsDataURL(input.files[0]);
        }
      }


      $("form#mainform input[type='file']").change(function(){
        readURL(this);
        console.log(this);
      });

The console log from "j" should look like <input type="file" name="img1" id="img1"> yet it different from what change event is console logging.Is the approach correct? JSFIDDLE:http://ift.tt/1JrktCS

GwtExt EditableGridSample JavaScript Exception

I am trying out the EditableGridSample.java Demo from GwtExt.

The apllication compiles and deploys but the page is blank. I wrapped a try catch around this line

try {
        HttpProxy proxy = new HttpProxy("data/plants.xml", Connection.GET);
    } catch (Exception e) {
        Window.alert(" Exception " + e);
}

and get the error message Exception com.google.gwt.core.client.javaScriptException(TypeError): Cannot set property 'BLANK_IMAGE_URL' of undefined

Please help

Tinymce editor becomes empty when ng-repeat list is reordered

This is a simplified example of a bug we faced in our project recently.

I have a list of objects with "name" and "position" properties and wanna use TinyMCE editor instead of textarea to display "name".

Besides, the list is ordered by "position" property which is editable.

Noticed that once "position" property is changed(list is reordered), TinyMCE editor becomes empty.

Anyone has any ideas why it happens and how to fix this?

Example code: JsFiddle

HTML

<script src="http://ift.tt/1DTrZWe"></script>
<script src="//tinymce.cachefly.net/4.1/tinymce.min.js"></script>
<body ng-app="myApp">
    <div ng-controller="MyCtrl">
        <p>List of activities:</p>
        <div ng-repeat="activity in model.activities | orderBy: 'position'">
             <label for="$index">Position</label>
            <input id="$index" type="number" ng-model="activity.position" style="width: 50px">
            <textarea ng-model="activity.name" rows="2" cols="10"></textarea>

            <hr>
        </div>
    </div>
</body>

JS

var myApp = angular.module('myApp', ['ui.tinymce']);
/**
 * Binds a TinyMCE widget to <textarea> elements.
 */
angular.module('ui.tinymce', [])
  .value('uiTinymceConfig', {})
  .directive('uiTinymce', ['uiTinymceConfig', function (uiTinymceConfig) {
    uiTinymceConfig = uiTinymceConfig || {};
    var generatedIds = 0;
    return {
      priority: 10,
      require: 'ngModel',
      link: function (scope, elm, attrs, ngModel) {
        var expression, options, tinyInstance,
          updateView = function () {
            ngModel.$setViewValue(elm.val());
            if (!scope.$root.$$phase) {
              scope.$apply();
            }
          };

        // generate an ID if not present
        if (!attrs.id) {
          attrs.$set('id', 'uiTinymce' + generatedIds++);
        }

        if (attrs.uiTinymce) {
          expression = scope.$eval(attrs.uiTinymce);
        } else {
          expression = {};
        }

        // make config'ed setup method available
        if (expression.setup) {
          var configSetup = expression.setup;
          delete expression.setup;
        }

        options = {
          // Update model when calling setContent (such as from the source editor popup)
          setup: function (ed) {
            var args;
            ed.on('init', function(args) {
              ngModel.$render();
              ngModel.$setPristine();
            });
            // Update model on button click
            ed.on('ExecCommand', function (e) {
              ed.save();
              updateView();
            });
            // Update model on keypress
            ed.on('KeyUp', function (e) {
              ed.save();
              updateView();
            });
            // Update model on change, i.e. copy/pasted text, plugins altering content
            ed.on('SetContent', function (e) {
              if (!e.initial && ngModel.$viewValue !== e.content) {
                ed.save();
                updateView();
              }
            });
            ed.on('blur', function(e) {
                elm.blur();
            });
            // Update model when an object has been resized (table, image)
            ed.on('ObjectResized', function (e) {
              ed.save();
              updateView();
            });
            if (configSetup) {
              configSetup(ed);
            }
          },
          mode: 'exact',
          elements: attrs.id
        };
        // extend options with initial uiTinymceConfig and options from directive attribute value
        angular.extend(options, uiTinymceConfig, expression);
        setTimeout(function () {
          tinymce.init(options);
        });

        ngModel.$render = function() {
          if (!tinyInstance) {
            tinyInstance = tinymce.get(attrs.id);
          }
          if (tinyInstance) {
            tinyInstance.setContent(ngModel.$viewValue || '');
          }
        };

        scope.$on('$destroy', function() {
          if (!tinyInstance) { tinyInstance = tinymce.get(attrs.id); }
          if (tinyInstance) {
            tinyInstance.remove();
            tinyInstance = null;
          }
        });
      }
    };
  }]);

myApp.controller("MyCtrl", ["$scope", function($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}
        ] 
    };
    $scope.tinyMceOptions = {
        selector: "textarea",
        theme: "modern",
        plugins: [
            "autolink lists link charmap print preview hr anchor pagebreak autoresize",//advlist
            "searchreplace visualblocks visualchars code",
            "insertdatetime nonbreaking save table directionality",
            "emoticons template paste textcolor colorpicker textpattern"
        ],
        toolbar1: "bold italic underline |  alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | forecolor backcolor | undo redo | link | pastetext",
        paste_auto_cleanup_on_paste: true,
        paste_strip_class_attributes: 'mso',
        paste_data_images: false,
        theme_advanced_buttons3_add: "pastetext,pasteword,selectall",
        image_advtab: true,
        //templates: [
        //    {title: 'Test template 1', content: 'Test 1'},
        //    {title: 'Test template 2', content: 'Test 2'}
        //],
        browser_spellcheck: true,
        menubar: false,
        //theme_advanced_disable: "bullist,numlist",
        target_list: [{ title: 'New page', value: '_blank' }],
        //advlist_number_styles: [
        //    {title : 'Standard', styles : {listStyleType : ''}},
        //    {title : 'a. b. c.', styles : {listStyleType : 'lower-alpha'}}
        //],
        //spellchecker_languages: "+English=en",
        //spellchecker_rpc_url: 'spellchecker.php',
        handle_event_callback: function (e) {
            // put logic here for keypress
        }
    };
}]);

How to inject services to monitor authentication and storage status?

I'm using Angular.js to build a client side application with Restangular. The problem is, I implemented a digest authentication with a wsse header which i have to generate at each request to my REST Server.

I saw that Restangular provide a function : addFullRequestInterceptor().

So now, i'm trying to use it inside my RestangularProvider to configure it in this file restangular.js :

'use strict';

// Config Restangular
app.config(function(RestangularProvider) {
  RestangularProvider.setBaseUrl(applicationConfig.SERVER_URL);
  RestangularProvider.setDefaultHeaders({'Content-Type': 'application/json'});
  RestangularProvider.addFullRequestInterceptor(function (element, operation, route, url, headers, params, httpConfig) {
    $http.defaults.headers.common['X-WSSE'] = TokenHandler.getCredentials(AuthHandler.authentication.user.username,AuthHandler.authentication.secret); // Here is my header generation.
    return {
      element: element,
      headers: headers,
      params: params,
      httpConfig: httpConfig
    };
  });
});

But i have an injection problem and i can't find out how to inject my TokenHandler service & my AuthHandler service to be able to know if the user is already loggedin or not and if he has localstroage or not.

Thanks for the help ;)

How to target the focused input dynamically

I have a Jquery code that will pop-up with a box saying "Today" only when a user focuses on an input field. When the user clicks on the box, this will populate the targeted input field with the current date. Currently my code is working but the problem is as follows:

Problem: When someone clicks on the Today button, it populates all the input fields on the page instead of the input being focused on.

I created a JSFiddle to give you the best representation of my site's structure and will give you an idea of what's happening. Im still learning a lot in with Jquery lately but this has stumped me. I tried to target the input itself by using $("input[id*=Next_Update]").val(now); but that just breaks the code.

Here is a quick sample of my code with the JSfiddle JSFiddle: http://ift.tt/1Jrktmo

$(document).ready(function() {
    $(".im_whiteboard [id*=Next_Update]").on('focusin', function() {
        var div = $('#now');
        var top = $('input').offset().top + $('input').height() + 5;
        var left = $('input').offset().left;
        $(div).css('top', top);
        $(div).css('left', left);
        $(div).fadeIn();
    });
    $('input').on('focusout', function() {
        $('#now').fadeOut();
    });
    $('#now').on('click', function() {
        var today = new Date();
        var dd = today.getDate();
        var mm = today.getMonth()+1; //January is 0!
        var yyyy = today.getFullYear();

        if(dd<10) {
            dd='0'+dd
        } 

        if(mm<10) {
            mm='0'+mm
        } 

        today = mm+'/'+dd+'/'+yyyy;
       $('input').val(today); 
    });
});

I would appreciate any support on this.

jQuery Flip front to 2 different backsides

I am having trouble getting a certain feature to work.

As you can see here: http://ift.tt/1F5JkhP

<div> CHECK CODE AT JSFIDDLE</div>

I am using the flip jquery plugin which made a flip, where you choose a category, and then gets sent to a certain login screen. My issue is, that I want the bottom one to flip to another backside. I have tried altering the jquery plugin, but without luck. Is there anyone who knows how I could make this work?

So the pink one goes to the pink login, and the blue one goes to the blue login.

Thank you in advance!

in case of rotation of object there are some "artifacts"

everybody. There is a textured 3d object. enter image description here In case of its rotation there are distortions. enter image description here To what it can be connected?

P.S. if to disconnect shadowing of object, will change nothing

Meteor Twitter/Facebook login callbacks

I'm working on an account system where in which a user can create their account with an email address, and a password, and they can then link their account to either twitter, or facebook, in order to pull in their profile image.

The thing I can't seem to figure out, is how to get either login to send a callback.

Im using the link-accounts package, and everything's working, but I'm not sure how to hook into the process. On linking the account, I'd like to be able to trigger an event, and I'd also like to allow users to unlink their accounts.

Anyone familiar with doing this?

How to set specific action to f:selectItems in JSF2

I have with ajax

<h:selectOneMenu>
<f:selectItem itemLabel="please click"/>
<f:selectItem itemLabel="1"/>
<f:selectItem itemLabel="2"/>
<f:ajax onevent="click()" />
</h:selectOneMenu>

I have with onChange

<h:selectOneMenu onChange="click()>
<f:selectItem itemLabel="please click"/>
<f:selectItem itemLabel="1"/>
<f:selectItem itemLabel="2"/>    
</h:selectOneMenu>

if I try the same attributes to selectItem, it doesnt work. I think they dont exist.

I used ajax, onChange but it seem to wrok for selectonemenu but not in particular for selectItem.

Best practices for unit testing backend calls with Angular/Mongo

I am writing an Angular application that has a Scala/Play backend and a MongoDB. I'm new to unit testing and I'm trying to wrap my head around how to test the Mongo calls.

The app was designed by someone else and I've inherited it. The backend is very generic there are only four API services defined - save, find, delete, and generate newID. The angular calls take in a collection name and maybe an ID.

I have written tests to make sure a particular method processes data in the way that I expect, but I am lost when it comes to testing the Mongo part.

For example, let's say I have two objects - Apples and Oranges. I could have methods such as these

myAppleSvc.getApple: (id) ->
    myDataSvc.find "apples", {id:id}
myOrangeSvc.getOrange: (id) ->
    myDataSvc.find "oranges", {id: id}

The lower level data svc would do something like this:

myDataSvc.find: (collection, query) ->
    deferred=$q.defer()
    @doPost "/api/v1/findJson/#{collection}", query, deferred
    return deferred.promise

The @doPost function is a helper method that handles the success/failure

doPost: (path, data, deferred) ->
    $http.post path, data
    .success (result) -> deferred.resolve result
    .error (result) -> deferred.reject result

There are some other things going on in the codebase, but this is the basic pattern.

I am trying to understand the best way to test this code. Most of my calls just return a promise to be resolved. How would I test the getOrange and getApple calls? As far as I can tell, all I can do is make sure they are returning a promise. With the dataSvc.find call, it seems all I need to do is make sure that it calls the correct URL and also returns a promise. Am I missing something?

Leaflet popup closing immediately after function fires to open popup dynamically

I have a feature that allows the user to look up a marker and zoom to its location, at which point I want the popup to open. Everything is working fine, except that the popup closes after the function fires. I can't figure out what's making the popup close. Here's my relevant code:

var geoJsonDataFeatures = {
"type": "FeatureCollection",
"features":[]
};

//create popup content
var htmlString = "<div>popup html goes here....</div>";
var popupContent = L.popup().setContent(htmlString);

//create geoJson object for each marker
var geoJsonData = {
"type": "Feature",
"id": siteNo, //a string saved as a variable 
"properties": {
    "popupContent": popupContent,
    "icon": icon //an L.icon object
    },
"geometry": {
    "type": "Point",
    "coordinates": [longitude, latitude] //strings saved as variables
    }
}

//push the geoJson feature into the features object
geoJsonDataFeatures.features.push(geoJsonData);

//create the map layer that holds the markers
var geoJsonDataLayer = L.geoJson(geoJsonDataFeatures, {
    onEachFeature: function (feature, layer) {
    layer.bindPopup(feature.properties.popupContent);
    layer.setIcon(feature.properties.icon);
    }
}).addTo(map);

....

//when the user has selected a site from a dropdown select menu,
//we pass the site number (siteNo) to a function to zoom and open the
//marker popup:

zoomOpenPopup(siteNo);

function zoomOpenPopup(siteNo){
var marker = {};
var popup = {};
var layerObj = {};

    if(map.hasLayer(geoJsonDataLayer))
    {
    layerObj = geoJsonDataLayer;
    }

    jQuery.each(layerObj._layers, function(k){

        if(siteNo == layerObj._layers[k].feature.id)
        {
        marker = layerObj._layers[k];
        popup = layerObj._layers[k].feature.properties.popupContent;
        }  
    });

marker.openPopup();
//popup._isOpen = true; //doesn't work
//popup.openOn(map); //doesn't work
//map.openPopup(popup); //doesn't work
 alert("done!"); 
}

When the alert fires, you can see the popup open on the map, but once it closes the popup disappears. I do have a function that updates the position of the popup anchor on open if the content is too wide, but I have the same issue even if I comment out that function and reload the page. Has anyone run into something similar?

javascript match method with a closing square bracket character

How can I use a closing square bracket as a character in a javascript regular expression?

"Acb[".match('[\(, \), \[]')

returns:

["["]

But when I add the closing square bracket as a character it does not work :

"Acb[".match('[\(, \), \[, \]]')
null


"Acb]".match('[\(, \), \[, \]]')
null

Angular only loads first directive

I have declared two directives by the following design pattern:

var sampleDrtv = function () {
    return {
        restrict: 'E',
        replace: true,
        scope: false,
        templateUrl: 'app/views/partials/sample.html',
        link: function() {
            alert('sample');
        }
    }
};

angular
.module('app')
.directive('sampleDrtv', sampleDrtv);

If I add two directives following this pattern, only the first one gets loaded. Can someone explain me why?

Code Snippet: http://ift.tt/1JQz6mJ

Masonry layout for canvas

Can anyone suggest similar to http://ift.tt/1Ig6DpS solution, but for canvas?

I need masonry-like layout where image tiles with different sizes will be positioned properly without lots of whitespace.

P.S. Canvas chosen beacause of large data and better performance.

meteor template content fully loaded callback

I've a template like below

<template name="mainEvents">
    <section class="main-events-list events-list js-content-slider">
        {{#each events}}
            <div class="events-list-item">
                <figcaption>
                    <dl class="clearfix">
                        <dt>
                        <h3>{{name}}</h3></dt>
                    </dl>
                </figcaption>
                <figure class="ratioBox">
                    <div class="js-backstretch content"><img src="{{image}}"/></div>
                </figure>
                <a href="" class="full-link"></a>
            </div>
        {{/each}}
    </section>
</template>

a simple helper like below

Template.mainEvents.helpers({
   "events": function () {
       return Events.find({is_deleted:false})
   }
})

and lastly a simple iron-route like below:

Router.route('/slider', {
name: 'mainEn',
path: '/slider',
template: 'slider',
layoutTemplate: 'mainLayout',
yieldRegions: {
    'indexHeader': {to: 'header'},
    'footer': {to: 'footer'}
},
onBeforeAction: function () {
    //TAPi18n.setLanguage('en'); // set to english
    this.next();
},
action: function () {
    // render all templates and regions for this route
    this.render();
}
});

As you can guess i'm trying to generate a slider with the data came from the collection and trying to do it with Slick package.

Template.mainEvents.rendered .. function works well when roaming between routes. Suppose my slider is in /slider route and i load the meteor app by entering localhost:3000 and then click /slider button. everything works as it's should.

But when try to load the page with localhost:3000/slider route. rendered function triggers before the content fully loaded and slick fails. I manage to work it only by setTimeout function.

How can i get the all content in a template fully loaded and rendered callback in meteor ?

I need $('.selector').load(function () {}) like function.

or any other that can solve this issue.

Thanks in advance.

multiple user prompts node.js

I am trying to query the user twice (more than once in general), but everything gets printed out together and the first response get processed by both functions. I believe this has to do with the asynchronous nature of node.js. Can you please point me towards module that would take care of this for me or an implementation in prompt module? Thank you.

var prompt = require('prompt');
prompt.start();
console.log("Enter a number: ");
prompt.get(['number'], function(err, result) {
  if (!isNaN(result.number)) {
    console.log("You entered a number.");
  } else {
    console.log("You did not enter a number.");
  }
});


var prompt2 = require('prompt');
prompt2.start();
console.log("Enter a number again: ");
prompt2.get(['number1', 'number2'], function(err, result) {
  if (Number(result.number1) > Number(result.number2))
    console.log("The first input is bigger");
  else if (Number(result.number1) == Number(result.number2))
    console.log("Both inputs are equal");
  else
    console.log("The second input is bigger");
});

getting values from php dynamically created checkboxes with jquery

H Im trying to get the value of a check box to send in a ajax request to a php page, the checkboxes are dynamically created using php. So far my code allows me to show an instruction to the user telling the user to choose an admin to delete from the list dynamically created. Then when a checkbox is checked the instrcution hides and the delete admin button is shown. Next on clicking the delete button I'm trying to confirm the user wants to delete the admin chosen and click to confirm or cancel. The real problem I'having is getting the value of the chosen checked checkbox to pass to the php processing page, so far I have managed to get the value of the first checkbox to pass no matter which checkbox is checked

Jquery

<script type="text/javascript">

$(document).ready(function() {

    var checkboxes = $("input[type='checkbox']");

checkboxes.click(function() {
    $('.delete_admin_but').show();
    $('#adminDeleteNotice').hide();
    var deleteAdminName=$(this).attr('id');
});

    $(".delete_admin_but").click(function() {



//  if(confirm("Are you sure you want to delete the Admin")) {

    $("#deleteAdminError").html('<img src="image/ajax-loader.gif" width="16" height="16" alt=""/>');




$.post("includes/delete_admin.inc.php",{deleteAdminname:deleteAdminName},function(json)   {
    if(json.result === "success") {
        $("#deleteAdminError").html(json.message);
//  $('.add_intern').get(0).reset();
    }else{
        $("#deleteAdminError").html(json.message);
    }
});



});//submit click
});//doc ready
</script>

html form

<div id="deleteAdmin" style="display:none">

<form id="adminDelete">

          <div class="delete_admin_list">

            <?php while($row = mysqli_fetch_array($result1)) { ?>

              <input type="checkbox" id="<?php echo $row['name']; ?>" value="<?php echo $row['id']; ?>" name="delete[]" class="checkboxAdmin" />

              <div id="admin_db_detail"><?php echo $row['name']; ?> - <?php echo $row['email']; ?></div>

              <?php } ?>

      </div>        


<div id="adminDeleteNotice" style="display:block">Please Choose an Admin to Delete</div>

<input name="delete_admin_but" id="delete_admin_but" type="button" class="delete_admin_but" value="Delete Admin" style="display:none"/>

</form>

<div id="deleteAdminError"></div>

</div>

If anyone could help me figure this out I would be greatful

jQuery Attribute Equals Selector [name=”value”] issues passing a variable that ends with backslash

Humour me on this one.

In my code I am attempting to find all the divs that match a data-attribute value. Now this value is created by a user so the string could contain anything.

During my testing I ran into an error when the value contained a quote and ended with a backslash "\" (The javascript escape character).

Error: Syntax error, unrecognized expression: className[data-attributename="Mac"Mac\"]

Here is an example (please note in this example the double backslash escapes itself and the first backslash escapes the quote):

var value= "Mac\"Mac\\";
$('.className[data-attributename="'+value+'"]');

This error only occurs if the string contains a quote (") and has a backslash (\) at the end of the string. If there is a space after the backslash or if the backslash is in beginning or middle of the string there is no issue.

Is it possible to pass a variable that includes a quote or apostrophe ( " ' ) and ends with a backslash (\) into the jQuery Attribute Equals Selector?

One obvious solution would be just to prevent my users from using the backslash "\" character. If I do this is there any other characters that could be harmful using this jQuery selector?

Another solution would be:

var value= "Mac\"Mac\\";
$('.className').each(function(){
    if($(this).attr('data-attributename') === value){
      //perform action
    }
});

With this solution would it be less efficient because it would have to iterate through each element or does the Attribute Equals Selector essentially work the same way? If so, for safety should I always use this solution over the attribute equals selector?

Here is an example of the div I would be trying to select:

$('body').append("<div class='className' data-attributename='Mac\"Mac\\' ></div>")

Symfony2 using two different ajax scripts(failed to load response data)

So I have two ajax scripts. One that increases the value and one that decreases. The first scripts, that increases the value works, however the second script which is almost identical does not work and I am getting Failed to load response data in devTools. I dont know why, but maybe you cant use two ajax scripts like that? Maybe I need to create a new file for each script? I really dont know...

Well this is my script file :

$(document).ready(function () {
    $(document).on('click', '.plus', function (e) {
    $this = $(this);

    $.ajax({
        type: 'POST',
        url: 'add/quantity',
        dataType: 'JSON',
        data: {product: $this.parent('.input-append').find('input').data('id'),quantity: $this.parent('.input-append').find('input').val()},
        success: function (data) {      
          if(data.success == false){
           alert('error')
          }else{

           }
        }
    });
});

    $(document).on('click', '.minus', function (e) {
    $this = $(this);

    $.ajax({
        type: 'POST',
        url: 'remove/quantity',
        dataType: 'JSON',
        data: {product: $this.parent('.input-append').find('input').data('id'),quantity: $this.parent('.input-append').find('input').val()},
        success: function (data) {
          if(data.success == false){
           alert('error')
          }
        }
    });
});
});

And my controller for both scripts:

public function addQuantityAction( Request $request ) {
    $response = new JsonResponse();
    $requestData = $request->request->all();
    $productid     = $requestData['product'];
    $quantity = $requestData['quantity'];
    /** logic*/
    $em = $this->getDoctrine()->getManager();
    $product = $em->getRepository('MpShopBundle:Product')->find($productid);
    $qtyAvailable = $product->getStock();
    $session = $this->getRequest()->getSession();
    $cart = $session->get('cart', array());
    if ( $qtyAvailable > $cart[ $productid ] ) {
        $cart[ $productid ] = $cart[ $productid ] + 1;
        $response->setData(array('success'=>true,'message'=>'Qunatity increased'));
         $session->set('cart', $cart);
    } else {
        $response->setData(array('success'=>false,'message'=>'Out of stock'));
    }
    return $response;
}

public function removeQuantityAction( Request $request ) {
    $response = new JsonResponse();
    $requestData = $request->request->all();
    $productid     = $requestData['product'];
    $quantity = $requestData['quantity'];
    /** logic*/
    $em = $this->getDoctrine()->getManager();
    $product = $em->getRepository('MpShopBundle:Product')->find($productid);
    $qtyAvailable = $product->getStock();
    $session = $this->getRequest()->getSession();
    $cart = $session->get('cart', array());
    if ( $cart[ $productid] > 1 ) {
        $cart[ $productid ] = $cart[ $productid ] - 1;
        $response->setData(array('success'=>true,'message'=>'Qunatity decreased'));
         $session->set('cart', $cart);
    } else {
        $response->setData(array('success'=>false,'message'=>'Cant be lower than 1'));
    }
    return $response;
}

Routing.yml:

add_quantity:
  pattern:  /add/quantity
  defaults: { _controller: MpShopBundle:Homepage:addQuantity }

remove_quantity:
  pattern:  /remove/quantity
  defaults: { _controller: MpShopBundle:Homepage:removeQuantity }

As you can see the code is practically identical. It should work, but im not getting any response for the second script.. why?

When im trying to get the response i get status:302 and it redirects me back to the same page... Anyone know why?

Hide checkboxes on child nodes in a treepanel with selModel (selType:checkboxmodel)

In a ExtJs app i want to hide or delete the checkboxes in the parent node from a treepanel, i mean there are any way to hide the check of a principal categorie and only put in the child nodes? and put a radiobutton in these child nodes; I'm using extjs 5.1 and there is the code

    Ext.require([
    'Ext.data.*',
    'Ext.grid.*',
    'Ext.tip.*',
    'Ext.tree.*'
]);

Ext.define('Post', {
    extend: 'Ext.data.TreeModel',
    idProperty: 'postid',
    fields: [{
        name: "title",
        convert: undefined
    }, {
        name: "threadid",
        convert: undefined
    }, {
        name: "username",
        convert: undefined
    }, {
        name: "userid",
        convert: undefined
    },  {
        name: "dateline",
        type: 'date',
        dateFormat: 'timestamp'
    }, {
        name: "postid",
        convert: undefined
    }, {
        name: "forumtitle",
        convert: undefined
    }, {
        name: "forumid",
        convert: undefined
    }, {
        name: "replycount",
        type: 'int',
        convert: undefined
    }, {
        name: "lastpost",
        dateFormat: 'timestamp',
        convert: undefined
    }, {
        name: "excerpt",
        convert: undefined
    }]
});

Ext.onReady(function() {
    Ext.tip.QuickTipManager.init();

    function renderTitle(value, p, record) {
        return value ? Ext.String.format(
            '<a href="http://ift.tt/1JQz5PK}" target="_blank">{0}</a>',
            value,
            record.data.threadid
        ) : '';
    }

    function checkPrenderCapa() {

    }

    var store = Ext.create('Ext.data.TreeStore', {
        model: 'Post',
        proxy: {
            type: 'ajax',
            reader: 'json',
            url: 'forum-data.json'
        },
        lazyFill: false
    });

    var tree = Ext.create('Ext.tree.Panel', {
        title: 'Tabla de Contenido',
        width: 500,
        height: 400,
        renderTo: Ext.getBody(),
        reserveScrollbar: true,
        collapsible: true,
        collapseDirection: Ext.Component.DIRECTION_LEFT,
        loadMask: true,
        useArrows: true,
        draggable : true,
        rootVisible: false,
        store: store,
        animate: true,
        selModel: {
            selType: 'checkboxmodel'
        },
        columns: [{
            xtype: 'treecolumn', //this is so we know which column will show the tree
            text: 'Capa',
            flex: 2.5,
            sortable: true,
            dataIndex: 'forumtitle'
        },{
            text: 'Metadato',
            flex: 1,
            dataIndex: 'username',
            sortable: true
        }, {
            text: 'Activaci&oacute;n',
            flex: 2,
            dataIndex: 'title',
            renderer: renderTitle
        }],
        tbar: [{
            labelWidth: 130,
            xtype: 'triggerfield',
            fieldLabel: 'Nombre de la capa',
            triggerCls: 'x-form-clear-trigger',
            onTriggerClick: function() {
                this.reset();
                store.clearFilter();
                this.focus();
            },
            enableKeyEvents: true,
            listeners: {
                keyup: function() {
                    var field = tree.down('textfield'),
                        v;

                    try {
                        v = new RegExp(field.getValue(), 'i');
                        store.filter({
                            filterFn: function(node) {
                                var children = node.childNodes,
                                    len = children && children.length,

                                    // Visibility of leaf nodes is whether they pass the test.
                                    // Visibility of branch nodes depends on them having visible children.
                                    visible = node.isLeaf() ? v.test(node.get('title')) : false,
                                    i;

                                // We're visible if one of our child nodes is visible.
                                // No loop body here. We are looping only while the visible flag remains false.
                                // Child nodes are filtered before parents, so we can check them here.
                                // As soon as we find a visible child, this branch node must be visible.
                                for (i = 0; i < len && !(visible = children[i].get('visible')); i++);

                                return visible;
                            },
                            id: 'titleFilter'
                        });
                    } catch (e) {
                        field.markInvalid('Invalid regular expression');
                    }
                },
                buffer: 250
            }
        }]
    });
});

Javascript Functioncall Socket.io and Phaser

I have a problem with a function call with Phaser. I am a Javascript Noob and don´t know what I do wrong.

Here is the critical Part of my Code, all the code is in the same file.

BasicGame.Multiplayer = function (game) {
};

  BasicGame.Multiplayer.prototype = {

        create: function(){
            this.socket = io.connect('localhost:3010');
            this.socket.on('startGame', function () {
                console.log('ShouldStartGame');
                this.createActualGame();
            });
},

createActualGame: function(){
        // Define constants
       }
}

My problem is that the function this.createActualGame is not called with the error: "TypeError: this.createActualGame is not a function". But the console log works fine.

Without the socket.on(...) the code works fine and the function is called with the statement "this.createActualGame()", but wihtin the socket.on(...) it doesn´t work and i have no clue why and no idea how this could be solved. Thank you very much for your help.

With kind regards, SirSandmann

Adding search button and text box in ui-dialog-buttonpane

I am writing a greasemonkey script to manipulates the DOM, queries a server and displays the result on a separate jquery dialog. I want to add following two functionalities to it:

  1. Provide a search box which acts like a simple search on a browser (i.e. searches through the content of the jquery dialog only and highlights the text).
  2. Provide a text-box, the content of which should be stored permanently for all future use of the userscript unless the user changes it specifically.

The problem I am facing is that I want to include both of these in the ui-dialog-buttonpane area of the dialog, to the left of the close button, but I am not able to figure out how to do that.

What I do know is that I can use window.find() (as used here http://ift.tt/1snM0Ap) to enable the browser find functionality.

Can someone help me with this ? Following is the code for my existing greasemonkey script:

// ==UserScript==
// @name        Query for each URL Asynchronously
// @namespace   SupportScript
// @include     *
// @require     http://ift.tt/1yCEpkO
// @require     http://ift.tt/1zMTD8C
// @resource    jqUI_CSS  http://ift.tt/1JrgA0S
// @grant       GM_addStyle
// @grant       GM_getResourceText
// @grant       GM_getResourceURL
// @run-at      document-end
// allow pasting
// ==/UserScript==

var snapshotResults = document.evaluate('//a[contains(@href,"http")]/@href', document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
var windowWidth = $(window).width()-800;
var windowHeight = $(window).height();

var zNode = document.createElement ('input');
zNode.setAttribute ('id', 'SSButton');
zNode.setAttribute( 'type', 'image' );
zNode.setAttribute( 'src', 'http://ift.tt/1zMTB0q');
//zNode.setAttribute( 'src', 'http://ift.tt/1JrgA0U');
//zNode.setAttribute( 'src','http://ift.tt/1zMTB0s');
document.body.appendChild (zNode);

var batchSize = 10;
var urlsToUpsert = [];
var uniqueHostnameSet = new Set();
var uniqueURLArray = [];
uniqueHostnameSet.add(window.location.hostname);
var finalUrl = window.location.protocol + '//' + window.location.hostname;
uniqueURLArray.push(finalUrl);
for (var iterate = 0; iterate < snapshotResults.snapshotLength; iterate++)
{
    var hrefContent = snapshotResults.snapshotItem(iterate).textContent;
    var regex = /http.*/;
    var href = regex.exec(hrefContent);
    var a = document.createElement('a');
    a.href = href;
    if (!uniqueHostnameSet.has(a.hostname))
    {
        uniqueHostnameSet.add(a.hostname);
        finalUrl = a.protocol + '//' + a.hostname;
        uniqueURLArray.push(finalUrl);
    }
}

var divMain = '<div id="SSOverlayDialog"></div>';
$('body').append(divMain);

$.Coral = function (options) {
    $.extend(options, {
        url: "my URL",
        data: JSON.stringify(options.data),
        dataType: 'json',
        crossDomain: true,
        type: 'POST',
        contentType: 'application/json',
        processData: false,
        headers: {
            'Content-Encoding': 'abc',
            'X-Target': options.operation
        },

        dataFilter: function(data, type) {
            return data || "{}";
        }
    });
    return $.ajax(options);
};

$.GetOperation = function (options) {
    $.extend(options, {
        async: true,
        success: function(data) {
            handleData(data);
        },
        operation: 'opeartion1'
    });
    return $.Coral(options);
};

$.UpsertOperation = function (options) {
    $.extend(options, {
        async: true,
        operation: 'Operation2'
    });
    return $.Coral(options);
};


for (var iterateUniqueURLArray=0; iterateUniqueURLArray<uniqueURLArray.length; iterateUniqueURLArray+=batchSize) {
    var urlList = uniqueURLArray.slice(iterateUniqueURLArray,iterateUniqueURLArray+batchSize);
    try {
        var listOfURLs = {
            storeUrlList: urlList
        };
        var dataGetAttributes = {data: listOfURLs};
        $.GetOperation(dataGetAttributes);
    } catch(e) {
        console.log(e);
    }

}

function handleData (data) {
    var div = '<div id="SSOverlayDialog">';
    var response = JSON.stringify(data);
    var subString = "";
    var startIndex = response.indexOf('{',1);
    var endIndex = response.lastIndexOf('}');
    var responseText = response.substring(startIndex,endIndex);
    var subString = JSON.parse(responseText);
    $.each( subString, function( key, value ) {
        key = JSON.stringify(key);
        div+='<b><i><a style="color:#0645AD" href="'+key.substring(1,key.length-1)+'"><u>' + key.substring(1,key.length-1) + '</u></a></i></b><br><br>';
        if(JSON.stringify(value)==='{}') {
            console.log("Value for URL "+key+" is null.");
            div+='<p>This URL does not exist with Mobius.<span style="color:red" class="urlNotPresent" id ="'+key.substring(1,key.length-1)+'"><u>Click Here</u></span> to submit to Mobius.</p>';
        }
        $.each( value, function( ky, val ) {
            ky = JSON.stringify(ky);
            if (val==null) {
                div += '<p><b>'+ky.substring(1,ky.length-1)+': </b><i>'+val+'</i></p>';
            }
            else{
                val = JSON.stringify(val);
                div += '<p><b>'+ky.substring(1,ky.length-1)+': </b><i>'+val.substring(1,val.length-1)+'</i></p>';
            };
        });
        div+='<br>';
    });
    div += '</div>';
    $('#SSOverlayDialog').append(div);
    $(".urlNotPresent").off('click');
    $(".urlNotPresent").one('click', urlNotPresentFn);
    $(".urlNotPresent").hover(pointerToClick, pointerToDefault);
}

var urlNotPresentFn = function() {
    var url = jQuery(this).attr("id");
    if (urlsToUpsert.length == batchSize-1) {
        urlsToUpsert.push(url);
        var listOfURLs = {
            storeUrlList: urlsToUpsert
        };
        var myOptions = {data: listOfURLs};
        $.UpsertOperation(myOptions);
        urlsToUpsert.length = 0;
    } else {
        urlsToUpsert.push(url);
    };
    console.log(urlsToUpsert);
}

var pointerToClick = function() {
    $(".urlNotPresent").css("cursor", "pointer");
}

var pointerToDefault = function(){
    $(".urlNotPresent").css("cursor", "default");
}

$(window).bind('beforeunload', function() {
    if(urlsToUpsert.length>0) {
        var listOfURLs = {
            storeUrlList: urlsToUpsert
        };
        var myOptions = {data: listOfURLs};
        $.UpsertOperation(myOptions);
        urlsToUpsert.length = 0;
    };
    return ;
});

$('#SSOverlayDialog').dialog({

    autoOpen: false,
    modal: false,
    title: 'Discovered URLs (press "Esc" button to close)',
    position: {
        at: 'right top'
    },
    resizable: false,
    width: windowWidth,
    height: windowHeight,
    open: function(event, ui) { $(".ui-dialog-titlebar-close").hide(); },
    zIndex: 11111111,
    buttons: [
    {
        text: 'Close',
        click: function () {
            $(this).dialog('close');
        }
    }
    ]
});

$("#SSButton").click(function() {
    ($("#SSOverlayDialog").dialog("isOpen") == false) ? $("#SSOverlayDialog").dialog("open") : $("#SSOverlayDialog").dialog("close") ;
/*  if ($("#SSOverlayDialog").dialog("isOpen") == false) {
            $("#SSOverlayDialog").dialog("open"),
            $('#SSButton').css({
                'transform': 'rotate(180deg)',
                'transform': 'translate(-windowWidth)'
            });
    } else{
        $("#SSOverlayDialog").dialog("close"),
        $('#SSButton').css({
            'transform': 'initial'
        });
    };*/
});

var jqUI_CssSrc = GM_getResourceText('jqUI_CSS');
jqUI_CssSrc = jqUI_CssSrc.replace(/\.ui-front \{[\s]*z-index:\s100\;[\s]*\}/g,".ui-front \{\n z-index: 20000000 \; \n\}");
GM_addStyle(jqUI_CssSrc);

GM_addStyle ( multilineStr ( function () {/*!
  #SSButton {
    background: none repeat scroll 0% 0% ;
    background-image: none;
    background-repeat: repeat;
    background-attachment: scroll;
    background-position: 0% 0%;
    background-size: auto auto;
    overflow: hidden;
    position: absolute;
    top: 0;
    right: 0;
    z-index: 22222222;
    width: 40px;
    height: 40px;
}
*/} ) );

function multilineStr (multiLineStringFn) {
    var str = multiLineStringFn.toString ();
    str     = str.replace (/^[^\/]+\/\*!?/, '') // Strip function () { /*!
            .replace (/\s*\*\/\s*\}\s*$/, '')   // Strip */ }
            .replace (/\/\/.+$/gm, '') // Double-slash comments wreck CSS. Strip them.
            ;
            return str;
        }

jsTree plugin Inside Ember

I have used jsTree plugin to render large number of tree node in my product.

Now I am in the process of moving to Ember, and need to implement jsTree plugin within Ember.

I wrote a Ember component to render my folder structure using jsTree.

<script type="text/x-handlebars" data-template-name="components/temp-tree">
    <div id="treediv">Tree Data</div>
</script>

App.TempTreeComponent = Ember.Component.extend({
    didInsertElement: function(){
        var self = this;
        self.$().jstree({
        'plugins':["contextmenu", "dnd"],
        'core' : {
        'data' : [
            'Simple root node',
            { 
                'text' : 'Root node 2',
                'state' : {
                    'opened' : true,
                    'selected' : true
                 },
        'children' : [
         { 'text' : 'Child 1' },
         'Child 2'
        ]
    } 
], 
'check_callback': true
}
})
.on('rename_node.jstree', function(e, data) {
    alert('rename');
})
.on('delete_node.jstree', function(e, data) {
    alert('delete');
}); 
}, 
actions:{

} 
});

In my component for each action done on the tree, jsTree triggers an event respective to the event.

I used to listen to the events and do necessary action if required.

Basically jsTree updates the DOM and triggers the event.

But in Ember we will not update the DOM ,instead we need to update the underlying MODEL and by two way data-binding the DOM is updated by Ember.

Here I am going against the Ember Conventions.

Am I going in the right direction ?

Is there any other way to use jsTree with Ember.

Or is there any jsTree like component available in Ember to render large number of tree nodes with all features like context menu, drag & drop, search, unique plugin, checkbox, lazy loading, updating nodes ?

Doughnut chart updates with twice the data

Working with chart js and got it to do what I needed which is pull data from a webservice and use $interval to update it. When I update the chart using the built in update function it displays again as expected but with the old data in it as well. I thought I was clearing the data out of the array, I am newer to angular so maybe I overlooked something.

Here is the js for what is going on.

angular.module('myapp', [])
  .controller('MainCtrl', function($scope, $http, $interval) {
    $scope.doughnutData = [];
    var myDoughnut = '';
    onload = function() {
      $http.get('http://ift.tt/1JOZRb4').success(function(returnedData) {

        $scope.username = returnedData.name;
        $scope.totalscore = returnedData.totalScore.toFixed(3);

        returnedData.models.forEach(function(x) {
          var score = x.score.toFixed(3);
          console.debug(score);
          if (score >= 75) {
            $scope.doughnutData.push({
              'value': x.score,
              'color': '#F7464A',
              'highlight': '#FF5A5E',
              'label': x.name
            });
          } else if (score >= 50) {
            $scope.doughnutData.push({
              'value': x.score,
              'color': '#FDB45C',
              'highlight': '#FFC870',
              'label': x.name
            });
          } else {
            $scope.doughnutData.push({
              'value': x.score,
              'color': '#424242',
              'highlight': '#686868',
              'label': x.name
            });
          }
        });
        $scope.doughnutData = sortByKey($scope.doughnutData, 'value');
        var ctx = document.getElementById("chart-area").getContext("2d");
        myDoughnut = new Chart(ctx).Doughnut($scope.doughnutData, {
          responsive: true
        });
      });
      mainInterval = $interval(function() {
         doughnutData = '';
        $http.get('http://ift.tt/1JOZRb4').success(function(returnedData) {
          $scope.username = returnedData.name;
          $scope.totalscore = returnedData.totalScore.toFixed(3);

          returnedData.models.forEach(function(x) {
            var score = x.score.toFixed(3);
            console.debug(score);
            if (score >= 75) {
              $scope.doughnutData.push({
                'value': x.score,
                'color': '#F7464A',
                'highlight': '#FF5A5E',
                'label': x.name
              });
            } else if (score >= 50) {
              $scope.doughnutData.push({
                'value': x.score,
                'color': '#FDB45C',
                'highlight': '#FFC870',
                'label': x.name
              });
            } else {
              $scope.doughnutData.push({
                'value': x.score,
                'color': '#424242',
                'highlight': '#686868',
                'label': x.name
              });
            }
          });
          $scope.doughnutData = sortByKey($scope.doughnutData, 'value');
          myDoughnut.segments = doughnutData;
          myDoughnut.update();
        });
      }, 5000);
      $scope.$apply();
    };

    function sortByKey(array, key) {
      return array.sort(function(a, b) {
        var x = a[key];
        var y = b[key];
        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
      });
    }
  });

So it starts out with 9 values, and when it updates it has 18, etc.. There is nothing currently that will update (I just have it in there now for when I move it to my production webservice). I was thinking the doughnutData = ''; in the $interval section would clear it out?

Wanted to include the html as well to give a better idea of what is going on:

<html>

  <head>
    <script src="http://ift.tt/1Gufy1b"></script>
    <script src="../Chart.js"></script>
    <script src="../src/Chart.Doughnut.js"></script>
    <script src="http://ift.tt/198QQJG"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="../script.js"></script>
  </head>

  <body ng-app="myapp" ng-controller="MainCtrl">
    <div id="canvas-holder">
      <canvas id="chart-area" width="50" height="50"></canvas>
    </div>
  </body>

</html>

Improving full ajax website

I would like to try to improve a script that I use to make my ajax site. But after several attempts, no results. I need some help! ^^

This script was found on GitHub, and the author left a simple demo page. The author uses history.js. HERE

Here's the problem: 1- The back button works normally, but do not work when you have to return to the "index.php".

2- I would change the name of the created pages, but I can not win without breaking the script.

3- Finally I would like to add a function to load the div and use jqueryscrollto to make a transition effect.

I originally wanted to use this script (http://ift.tt/1lrQjVG) but I have not managed to implement. Having no single demo page using this script.

Thank you in advance if you look at the problem.

What is Object programming in node js?

Strictly speaking what is the OBJECT programming part of node.js ? is it :

  • express.js

  • Javascript

  • node.js itself

  • some component : what precisely ?

In theory how can we best DEFINE the object programming part of node.js ?

How can I create a new case in switch statement that depends on the previous case

Working fiddle of the what I am trying to do : http://ift.tt/1JreGgJ

The category and products drop down are working using a switch statement.

What I want to do is :

Add a new case called Wattage. The user selects a product and a respective wattage for that product is displayed everytime.

below is my attempt at pseudo code

// define wattage array
function configureDropDownLists(category, products) {

    var refrigerators = new Array('Artic King AEB', 'Artic King ATMA', 'Avanti Compact', 'Bosch SS');
    var dishWasher = new Array('Bosch - SHXUC', 'Asko DS', 'Blomberg', 'Amana');

    var wattage = newArray {
        Artic King AEB: 270,
        Artic King ATMA: 311,
        Avanti Compact: 340,
        Bosch SS: 214,
        Bosch - SHXUC: 200,
        Asko DS: 187,
        Blomberg: 236,
        Amana: 150
    };

    );

switch (category.value) {
    case 'refrigerators':
        products.options.length = 0;
        for (i = 0; i < refrigerators.length; i++) {
            createOption(products, refrigerators[i], refrigerators[i]);
        }
        break;
    case 'dishWasher':
        products.options.length = 0;
        for (i = 0; i < dishWasher.length; i++) {
            createOption(products, dishWasher[i], dishWasher[i]);
        }
        break;

    case 'wattage':
        // on change run through the dishWasher array to match wattage
        // products names matches then display the wattage

        // or

        // if(products.options == wattage.options)
        // display wattage
}
break;

default: products.options.length = 0;
break;
}
}

Also how do I keep my drop downs selected (once the user has completed selection of the product.)

Thanks

JavaScript Class Validation

So I'm making a JavaScript class that will be transferable with my Java one. It's all done but I want to make sure the right data type gets entered for the arguments.

For example, my Constructor:

function Table(header) {
    if (!Object.prototype.toString.call(header) === '[object Array]') {
        throw 'headers not array';
        return;
    }
    for (var i = 0; i < header.length; i++) {
        if (!typeof(header[i]) == 'string') {
            throw 'headers['+i+'] not string';
            return;
        }
    }
    this.header = header;
    this.rows = [];
}

When you create a new Table object, you have to pass in an array. Though you can pass in anything here and the object still gets created, just without the header and rows fields.

How can I destroy the object? The errors I've tried to throw don't do anything.

Iterate json data in javascript

Following JSON data comes from php,

Json format

I have tried following code. But console displays undefined error.

jQuery.each(result.address, function(obj) {
  console.log(obj.city);
});

How do I call live event with blur together

I have some question with these events.

My code is something like this:

dialogX.find('#inputExample').blur(function() { 
    var button = $(this).parent().find('#buttonExample');

    if(!(button.is(':clicked'))) //this doesn't work, just test
        button.hide();                                  
});

dialogX.find('#buttonExample').live('click', function() {
    alert('Test!');
    $(this).hide();
});

The question is, when I'm on input (#inputExample) and later click on button (#buttonExample), blur is called and live event is never called.

***I have to use live instead of on, because JQuery version.

Someone could help me?

Why Can't I get my google maps to update lat/lng on button click?

I am trying to get my center location to change on my google map based on a button click. I have more functionality to add later, but I can't get this basic update to work. I have a default value that loads on page load. The button should set a new location, but I see that it does update but then is quickly overridden by the default value because the page loads again.

I am new to google maps, and I am just trying to figure out how to load and interact with the map correctly.

Here is my code:

         <script src="http://ift.tt/13qgtmt"></script>                                                        
<script>

    var deanLat = 43.0843816;
    var deanLong = -89.5302394;
    var deanAddress = '1277 deming way, madison wi';

    var stmaryLat = 43.0592730;
    var stmaryLong = -89.4015130;
    var stmaryAddress = '700 S Park St, Madison, WI 53715';

    $("#FindDean").click(function() {
       refreshMap(deanLat, deanLong);
       });

    function alertme(message) {
          alert (message);
      }


    function refreshMap(ilat,ilong) {
       ilat = typeof ilat !== 'undefined' ? ilat : stmaryLat;
       ilong = typeof ilong !== 'undefined' ? ilong : stmaryLong;
        alertme(ilat);
        var mapOptions = {  
                zoom: 16,
                center: new google.maps.LatLng(ilat, ilong)
            };

        gmap = new google.maps.Map(document.getElementById('mapholder'),
          mapOptions);
    }


    function loadScript() {
      var script = document.createElement('script');
      script.type = 'text/javascript';
      script.src = 'http://ift.tt/1lrRXYd' +
          '&signed_in=true&callback=refreshMap';
      document.body.appendChild(script);
    }
   window.onload = loadScript;

how to remove the list of values from json object to another json object using jquery

for example I have two JSON Object. One of them is var A={'Header','Quotes','Returns','indent','Basic'.....,'Placing'.} another Object having Var B={Header','Quotes','Returns','indent'....}

in B having some Header,Quotes,Returns and Indent. So if A having same elements need to remove in jquery.

A's Final Output should be A={'Basic','Placing'.....}

Is there any way to turn a 'normal' string into ES6 Template string? [duplicate]

This question already has an answer here:

Is there any way to turn a 'normal' string into ES6 Template string?
I mean to make it using ES6 capabilities without tricky regexps or something.

I need it cause I'm getting string from db and want to use it as a template to produce output. Like this:

var message = db.getMyTemplate();//message holds `Yo, ${name}!`
var valueToPutIntoTemplate = 'Brendan';
console.log(message); 

the output is Yo, ${name}!. Is there any way to get "Yo, Brendan!" here?

Best regards, Eugene.

Javascript Animate Values as Percentages

I have a client project I inherited that uses javascript to create various animation effects while the user scrolls down through the site (sort of like a parallax site).

The problem with it is that it changes the values in pixels, and what we want it do now is user percentages.

For example, this code brings the #location-left div in from the left, by increasing its width from 0 to 750px, when user scrolls down 1800 pixels. It does this over a 200px interval. It achieves this by writing inline CSS into the DIV tag.:

{
                    selector: '#location-left',
                    startAt: 1800,
                    endAt: 2000,
                    onEndAnimate:function( anim ) {},
                    keyframes: [
                        { 
                            position: 0,
                            properties: {
                                "top" : 0,
                                "width" :  0
                            }

                        },
                        {
                            position: 1,
                            properties: {
                                "top" : 0,
                                "width" : 750
                            }
                        }
                    ]
                }

What I want it to do, instead, is go from 0% to 50%. My initial thought was to calculate up a set of var tags:

var a = $(document).width();
var a3= Math.floor(a * 0.3);  // 30% 
var a5= Math.floor(a * 0.5);  // 50%
var a8= Math.floor(a * 0.8);  // 80%
etc.

Before I got too far down that rabbit hole, though, I wanted to see if there was an easier approach that I was just missing.

Variable in routine is private - cannot call it outside of routine - Javascript

If I alert title like this, title is alerted correctly and has a value.

var myRequest = new Request('URL');
var title;
   fetch(myRequest).then(function(text) {
        return response.text().then(function(text) {
             title= text; 
             alert (title);

        });
   });

If I alert title like this - outside of the routine, the variable title is empty/undefined.

var myRequest = new Request('URL');
var title;
   fetch(myRequest).then(function(text) {
        return response.text().then(function(text) {
             title= text; 

        });
   });

 alert (title);

I need to alert title outside of the fetch routine.

I tried declaring the variable inside the routine and giving the variable the fetch routine title = fetch(myRequest)... Nothing worked.

What am I doing wrong? Where is the error?

Note: I've hidden the URL that is being fetched in this post. The fetching works fine.

Set color of nodes based on condition

I want to provide a color for each of the nodes based on its status. For instance, if status is 'completed', color of the node should be green. If it is 'pending' status should be blue and so on.

For this I have created these css classes. The class names exactly match with the status -

.completed {
    fill: green;
}
.pending {
    fill: blue;
}
.dormant {
    fill: purple;
}

When constructing the node, I am trying to apply the class whose name matches with the status

 .style("fill", function (d) { return d3.select(this).classed(d.status, true); })

However, this does not have any impact.

Below is the complete code

                var links = [
            {source: "Start", target: "Dept Approver", type: "approve", staus: "completed"},
                  {source: "Dept Approver", target: "Amount>20", type: "approve", staus: "completed"},
                  {source: "Amount>20", target: "Div Approver", type: "approve", staus: "completed"},
                  {source: "Amount>20", target: "Section Approver", type: "approve", staus: "completed"},
                  {source: "Amount>20", target: "Dept Approver", type: "reject", staus: "completed"},
                  {source: "Div Approver", target: "End", type: "approve", staus: "dormant"},
                  {source: "Section Approver", target: "End", type: "approve", staus: "pending"}
                ];
                
        
                var nodes = {};

                // Compute the distinct nodes from the links.
                links.forEach(function(link) {
                  link.source = nodes[link.source] || (nodes[link.source] = {name: link.source});
                  link.target = nodes[link.target] || (nodes[link.target] = {name: link.target});
                });

                var width = 960,
                        height = 500;

                var force = d3.layout.force()
                        .nodes(d3.values(nodes))
                        .links(links)
                        .size([width, height])
                        .linkDistance(80)
                        .charge(-300)
                        .on("tick", function(d) {
                                 path.attr("d", function(d) {
                                         var dx = d.target.x - d.source.x,
                                         dy = d.target.y - d.source.y,
                                         dr = 0;
                                         return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y;
                                 });
                                 circle.attr("transform", function(d) {
                                        return "translate(" + d.x + "," + d.y + ")";
                                 });
                                 text.attr("transform", function(d) {
                                        return "translate(" + d.x + "," + d.y + ")";
                                 });
                        })
                        .start();

                var svg = d3.select("#chart").append("svg")
                        .attr("width", width)
                        .attr("height", height);

                // Per-type markers, as they don't inherit styles.
                svg.append("defs").selectAll("marker")
                        .data(["approve", "reject"])
                  .enter().append("marker")
                        .attr("id", function(d) { return d; })
                        .attr("viewBox", "0 -5 10 10")
                        .attr("refX", 15)
                        .attr("refY", -1.5)
                        .attr("markerWidth", 8)
                        .attr("markerHeight", 8)
                        .attr("orient", "auto")
                  .append("path")
                        .attr("d", "M0,-5L10,0L0,5");

                var path = svg.append("g").selectAll("path")
                        .data(force.links())
                  .enter().append("path")
                        .attr("class", function(d) { return "link " + d.type; })
                        .attr("marker-end", function(d) { return "url(#" + d.type + ")"; });

                var circle = svg.append("g").selectAll("circle")
                        .data(force.nodes())
                  .enter().append("circle")
                        .attr("r", 8)
            .style("fill", function (d) { return d3.select(this).classed(d.status, true); })
                        .call(force.drag);

                var text = svg.append("g").selectAll("text")
                        .data(force.nodes())
                  .enter().append("text")
                        .attr("x", ".40em")
                        .attr("y", 12)
                        .text(function(d) { return d.name; });

        var drag = force.drag()
            .on("dragstart", function(d) {
                                         d3.select(this).classed("fixed", d.fixed = true);
                                 });
 .link {
  fill: none;
  stroke: #666;
  stroke-width: 1.5px;
}

#licensing {
  fill: green;
}

.link.licensing {
  stroke: green;
}

.link.reject {
  stroke-dasharray: 0,2 1;
    stroke: red;
}

circle {
  fill: #ccc;
  stroke: #333;
  stroke-width: 1.5px;
}

text {
  font: 11px sans-serif;
  pointer-events: none;
  text-shadow: 0 1px 0 #fff, 1px 0 0 #fff, 0 -1px 0 #fff, -1px 0 0 #fff;
}
.fixed {
 /* fill: #00B2EE; */
}
.completed {
    fill: green;
}
.pending {
    fill: blue;
}
.dormant {
    fill: purple;
}
<script src="http://ift.tt/1BU5qP2"></script>
<body>
    <div id="chart"></div>
</body>

Can someone please help me in correcting this?

glMatrix quaternion rotation

Can anyone explain to me why this doesn't work as I would expect.

Using a quaternion to rotate a vec3 [5,0,0] 180degree/Math.PI radians around the z axis.

I would think the result would be [-5,0,0]; Rotating [5,5,0] gives [-5,-5,0] as expected.

http://ift.tt/1RdjjQS

var q = quat.create();
quat.rotateZ(q, q, Math.PI);
console.log(q);

var v = vec3.fromValues(5, 0, 0);
vec3.transformQuat(v, v, q);
console.log(v);

/*
[0, 0, 1, 6.123234262925839e-17]
[-5, 6.123233998228043e-16, 0]
*/

var q2 = quat.create();
quat.rotateZ(q2, q2, Math.PI);
console.log(q2);

var v2 = vec3.fromValues(5, 5, 0);
vec3.transformQuat(v2, v2, q2);
console.log(v2);

/*
[0, 0, 1, 6.123234262925839e-17]
[-5, -5, 0]
*/

Function not defined error while using asp.net ajax

i am trying to call a web service through asp.net ajax by the following code

namespace MCTS70515AJAX
{
public static class HR
{
    public static int GetEmployeeCount(string department)
    {
        int count = 0;
        switch (department)
        {
            case "Sales":
                count = 10;
                break;
            case "Engineering":
                count = 28;
                break;
            case "Marketing":
                count = 44;
                break;
            case "HR":
                count = 7;
                break;
            default:
                break;
        }
        return count;
    }
}

this is the aspx page i am rendering

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AJAX2.aspx.cs" 

Inherits="MCTS70515AJAX.AJAX2" %>

<!DOCTYPE html>

<html xmlns="http://ift.tt/lH0Osb">
<head runat="server">

    <title></title>

</head>
<body>

    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server">
            <Services>
                <asp:ServiceReference Path="HRSer.asmx" />
            </Services>
            <Scripts>

            </Scripts>
        </asp:ScriptManager>


        <div>
            <select id="Departments" size="5">
                <option value="Engineering">Engineering</option>
                <option value="HR">Human Resources</option>
                <option value="Sales">Sales</option>
                <option value="Marketing">Marketing</option>

            </select>

        </div>
        <br />
        <div>
            <span id="employeeResults"></span>
            <span id="loading" style="display: none;">&nbsp;&nbsp;Loading ... 

            </span>

        </div>

    </form>
     <script type="text/javascript">

    var departments = null;
    Sys.Application.add_load(page_load);
    Sys.Application.add_unload(page_unload);
    function page_load(sender, e) {
        departments = $get("Departments");
        $addHandler(departments, "change", departments_onchange);
    }
    function page_unload(sender, e) {
        $removeHandler(departments, "change", departments_onchange);
    }
    function departments_onchange(sender, e) {
        $get("employeeResults").innerHTML = ""; $get("loading").style.display = "block";
        var selectedValue = departments.value;
        HRService.Getcount(selectedValue, onSuccess);
    }
    function onSuccess(result) {
        $get("loading").style.display = "none";
        $get("employeeResults").innerHTML = "Employee count: " + result;
    }


                </script>

</body>
</html>

this is the web service i am calling

namespace MCTS70515AJAX
{

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class HRService : System.Web.Services.WebService
{
    [ScriptMethod]
    [WebMethod]
    public int Getcount(string department)
    {
        return HR.GetEmployeeCount(department);
    }
}

} the page renders fine but whenever i change the list item value, it shows JavaScript runtime error: 'HRService' is undefined. why is this.

Sorry for such a long post ....

sending requests to my own API to make changes to DB which is not being updated. I would like the DB to be updated

Im having trouble understanding how to make request to an API that was set up with express to do CRUD methods. in the below code .get(/bears) renders a form and in the app.post('/bears') i'm using the nPmodule 'request' to send the request to the api/bears router by doing this i expect name attr of the text box which is the same field on the db to be added to the db (bear.save(function(err){ )It doesn't that is the problem.

someone please show me how to make calls from a route(page) to the api so the api could update the db from the form in the html from the view.

I think Angular has services for this but I want to see how to do this with express. Is there away to do it with out the npm request?

js fiddle with more of the code

app.get('/bears', function(req, res){
   res.render('index', {message : "You are rendered!"});     
})
app.post('/bears', function(req, res){
// request.post('http://localhost:8080/api/bears',function(error, response, body){
//  if(!error && response.statusCode == 200){
//      var info = JSON.parse(body)
//      res.send(info);
//  }else{
//      res.send(error);
//  }
// })
   request.post('http://localhost:8080/api/bears', function(error, response, body){
      console.log(body);
      console.log(response)
   })


})

router.route('/bears')
.post(function(req, res){
    var bear = new Bear();
    bear.name = req.body.name;

    bear.save(function(err){
        if(err)
            res.send(err);

        res.json({message : 'Bear created!'});
    })
})
.get(function(req, res){

    Bear.find(function(err, bears){
        if(err)
            res.send(err);
        res.json(bears);
        console.log(bears[0].id)
    })

})

Vimeo video works locally but not on live website: Uncaught Security Error: origin error with iframe

I am having a hard time figuring this one out. I have two videos on my website that I host at vimeo. With the embded code they provide, one video will display and playback and the other will playback locally but not once I upload it to bluehost.

The console reads: Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin "http://www.example.org" from accessing a frame with origin "http://example.org". Protocols, domains, and ports must match.

and it cites jquery.min.js.

I've found a few suggestions about how to work around this with document.domain but to no avail. Any help would be much appreciated. Thank you for your time

Triggering browser selection-scolling within an element, when selecting from outside

If we have a dom element whose content forces scrolling, selection within the element will trigger scrolling behaviour if the mouse moves outside the box. It's basic UI stuff.

The question is - can we trigger the same behaviour if selection begins outside the box without resorting to tracking the coordinates of the mouse through javascript and using scrollTo methods.

In other words, is there anything either in css (unlikely), or simple scripting events (I tried focusing on the containing element on mouse enter in order to 'capture' the selection but that didn't work) which would allow the ability to continue to scroll through the content of the constrained element?

    <div style="
      overflow: auto; 
      height: 300px; 
      width: 300px; 
      outline: solid 1px Red;
   ">... lots of content more than 300px high ... </div>

Plunker here. Thanks.

Why am I getting an Illegal Token error in my case statement boolean assignment?

I use the same syntax in other switch case statements which work. I basically create an empty object and start adding in key value pairs to it:

var vs = $scope;
vs.toggleTimeSpan = function(string) {

    vs.time.span = {};

    switch(string) {
        case '1h':
            // vs.time.span[1h] = true;
            vs.time.span.1h = true;
            break;

        case '1d':
            vs.time.span.1d = true;
            break;

        case '1m':
            vs.time.span.1mo = true;
            break;

        case '1y':
            vs.time.span.1yr = true;
            break;

        case 'max':
            vs.time.span.max = true;
            break;
    }
};

enter image description here

Here is where I intend on using the vs.time.span object:

<ul class="timescale">
    <li ng-class="{'active':time.span.1h}"
        ng-click="toggleTimeSpan('1h')">1 h</li>

    <li ng-class="{'active':time.span.1d}"
        ng-click="toggleTimeSpan('1d')">1 d</li>

    <li ng-class="{'active':time.span.1mo}"
        ng-click="toggleTimeSpan('1mo')">1 mo</li>

    <li ng-class="{'active':time.span.1yr}"
        ng-click="toggleTimeSpan('1yr')">1 yr</li>

    <li ng-class="{'active':time.span.max}"
        ng-click="toggleTimeSpan('max')">max</li>
</ul>