vendredi 8 mai 2015

Gives Error no token Id while using stripe in angular js

I have problem while using stripe with angular js.I have Successfully generate the token with Stripe.but when I post that token to the api it gives error:

{"errors":"There is no token with ID tok_160BQoCgr0gFKoypElkitdl6.

Here is My Controller code:

$scope.card =function()
{

    var number = document.getElementById('number').value;
    var expiry = document.getElementById('exp').value;
    var res = expiry.split("/"); 
    var month = res[0];
    var year = res[1];

    var cvv = document.getElementById('cvc').value;




        $scope.stripeCallback = function (code, result) {


            if (result.error) {
                $scope.stripeError = result.error.message;
            } else {
                $scope.stripeToken = result.id;
            }

            var api_token=storageService.get("api_token");
    $scope.orginal.api_token =JSON.parse(api_token);



//var data = {'number':number,'exp-month':month,'exp-year':year,'stripeToken':$scope.stripeToken,'api_token':$scope.orginal.api_token};
    var data = 'number='+number+'&exp-month='+month+'&exp-year='+year+'&stripeToken='+$scope.stripeToken+'&api_token='+$scope.orginal.api_token;

    console.log(data);

    HomeOwners.NewCard(data).then(function(response){

            console.log(response);



        })  
    };

Here is My service:

NewCard:function(data){

           var Url = baseurl+'card/create';

           var defer = $q.defer();

           $http.post(Url,data).
              success(function (data, status, headers, config) {
                  defer.resolve(data);
              }).
              error(function (data, status, headers, config) {
                  defer.reject();
              });

            return defer.promise;
    },

Please help

CKEditor setData() changes content but throws error

I have the following text area defined in my JSP page:

<textarea id="edit_subtaskstep_notes" name="edit_subtaskstep_notes" rows="15" cols="50"></textarea>

In my js file I am setting the content data as such:

CKEDITOR.instances.edit_subtaskstep_notes.setData("Hello World");

This successfully sets the ckeditor text box to contain "Hello World" when run but after this line is executed the following error is thrown in my output window:

Uncaught TypeError: undefined is not a function (14:21:03:488 | error, javascript)
at (anonymous function) (:197:29)

If I remove that line the error goes away but the data is no longer set. As it "seems" to work since the data is getting set is this some kind of bug with CKEditor v4? I'm trying to trouble shoot a key event focus bug having to do with Bootstrap modals but need to try and eliminate this one before proceeding.

How to make an accept condition for droppable td to accept only the class within the same row?

I have this droppable td.

$('#ScrumTable td').droppable({
    hoverClass: 'ondrop',
    accept: '.card',
    drop: function(event, ui){
        $(this).append($(ui.draggable));
        ui.draggable.css("top",$(this).css("top"))
        ui.draggable.css("left",$(this).css("left"))
        if(  parseInt( $(this).index() ) + 1 == 1){
            ui.draggable.addClass('backlog-card');
            ui.draggable.removeClass('inprogress-card');
            ui.draggable.removeClass('tovalidate-card');
        }
        else if(  parseInt( $(this).index() ) + 1 == 2){
            ui.draggable.addClass('inprogress-card');
            ui.draggable.removeClass('backlog-card');
            ui.draggable.removeClass('tovalidate-card');
        }
        else if(  parseInt( $(this).index() ) + 1 == 3){
            ui.draggable.addClass('tovalidate-card');
            ui.draggable.removeClass('inprogress-card');
            ui.draggable.removeClass('backlog-card');
        }
    }
});

The droppable td above must only accept the class that is within the same row. What condition can I put to the accept attribute of the droppable td?

jquery post call not working with slash at end of the url

example url:
Target is not to show .php extension, but content stop working when page/url is open with a slash at the end.
http://ift.tt/1F9Oyt6 - form is working with this url
http://ift.tt/1EnOLSI - form is not working with this url

Folder & files:
|
| /js/custom.js
| /manager/create.php
| /manager/creategetpostdata.php
| /manager/.htaccess

Content on custom.js

$(window).load(function() {
    // get post code data
    $('.contentfinder').on('keyup', function(e){
        var xyz = $(this).closest('.contentRow');
        //alert( "success" );
        $.post("../manager/creategetpostdata.php", xyz.find('.contentfinder').serialize(),  function(response) {
            //alert( "success" );
            xyz.children('.showPostData').html(response);
            xyz.children('.showPostData').show();
        });

    });

});

input form on create.php file:

                    <div class="contentRow">
                        <input type="text" name="inputdata" class="form-control contentfinder" placeholder="" />
                        <div class="showPostData"></div>
                    </div>

content on creategetpostdata.php

<?php echo 'hello, what the hell wrong with you. just show content now!'; ?>

content on .htaccess file

Options +FollowSymLinks -MultiViews
RewriteEngine On

RewriteCond %{THE_REQUEST} \s/+(.+?)\.php\?([^=]+)=([^\s&]+) [NC]
RewriteRule ^ /%1/%2/%3? [R=302,L,NE]

RewriteCond %{THE_REQUEST} \s/+(.+?)\.php\s [NC]
RewriteRule ^ /%1 [R=302,L,NE]

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [L]

any help? thanks in advance.

knockout-postbox and knockout components can you syncWith observable arrays?

I have two components that I want to sync an observable array between them. It works find with an observable, but with an array it never syncs. Can you syncWith an observable array?

If I convert the array to string and then sync the observable it passes, but then I have to reconstruct the observable array on the other vm. Can it be done with just a syncWith?

vm1

  self.offers = ko.observableArray([]).syncWith("offersLink");


            var mappedLogs = $.map(allData, function (item) { return new model.offerList(item) });
            self.offers(mappedLogs);

vm2

 self.offers = ko.observableArray([]).syncWith("offersLink");

json data that have location ,date, (lunch/ dinner) and meal value that changes on every order . plz tell me how to convert this into html table

cart:{   
      Gurgaon_2015-5-6_Lunch_-Meal42:{  
                                      chefMobile:"9268211346",
                                      chefName:"Vijaya",
                                      path:"-JmtUcV4v9k50dlO9n41/Gurgaon/2015-5-6/Lunch",
                                      price:200,
                                      quantity:1,
                                      stock:8,
                                      timeslot:1430901000000
                                     }
}

Uncaught ReferenceError: RSVP is not defined , error while using require.js with rsvp

I am working on a demo showing the error handling in promises using rsvp.js. Everything seemed fine, till I used the CDN url for rsvp.js in a tag. Now since I have require.js for module loading in my application, I tried loading the rsvp.js module via require js syntax. In the Chrome network tab, I see the rsvp.js module getting loaded properly as well, but I get the below error in console,

Uncaught ReferenceError: RSVP is not defined.

require(["bootstrap","js/rsvp"], function(bootstrap,rsvp) { 
$(document).ready(function () {
    function getEmployeeDetails() {
        var radioValue1 = $("input[name='option1']:checked").val();
        var requrl;
        if (radioValue1 == "fail") {
            requrl = "../../../testservice/getEmployeeIdss";
        } else {
            requrl = "../../../testservice/getEmployeeId";
        }
        return new RSVP.Promise(function (resolve, reject) {
            $.ajax({
                url: requrl,
                success: function (response) {
                    try {
                        $('#successBoard').append("<b> <i> Ajax Call 1 Succeeded! </i>  </b><br/>" + "Employee ID:" + response.stuId + "<br/>");
                        resolve(response.stuId);
                    } catch (e) {
                        reject(e);
                    }
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    console.log('Ajax 1 failed : Rejecting Promise 1');
                    $('#errorBoard').append("<b> <i> Ajax 1 failed : Rejecting Promise 1</i>  </b><br/>");
                    reject(thrownError);
                }
            });

        });
    }

400 Bad Request when calling wcf from html using XDomainRequest

I'm on this problem since more than one week and all I have tried haven't work so well. I started with Jquery to find out that Ie9 was different from the other browsers and requires its own way for calling wcf. It is simple enough and I did all the required, but it still doesn't work! Both adresses are http://localhost on IIS. I also renamed My html file so it becomes an aspx file. I added a Custom ContentTypeMapper so I dont get conflicts with the content types. I won't add all I have tried here, because I could write a book with it. You got the best I have found so far. I got the error message from Fiddler. Here goes the code:

Javascript:

    function CallService() {
        var xdr;

        function err() {
            alert('Error');
        }
        function timeo() {
            alert('Time off');
        }
        function loadd() {
            alert('Response: ' +xdr.responseText);
        }
        function stopdata() {
            xdr.abort();
        }   
        xdr = new XDomainRequest();
        if (xdr) {
            xdr.onerror = err;
            xdr.ontimeout = timeo;
            xdr.onload = loadd;
            xdr.timeout = 10000;
            xdr.open('POST','http://localhost/Path/Service.svc/AjaxEndpoint' + '/FunctionName');
            xdr.send()
        } else {
            alert('XDR undefined');
        }             
    }

Service (vb.net)

<ServiceContract()>
Public Interface IService

    <OperationContract()> _
    <WebInvoke(Method:="POST")> _
    Function FunctionName() As String

End Interface

Public Class Service
    Implements IService

    Public Function FunctionName() As String Implements IService.FunctionName
        Return "test"
    End Function
End Class

Public Class CustomContentTypeMapper
    Inherits WebContentTypeMapper
    Public Overrides Function GetMessageFormatForContentType(contentType As String) As WebContentFormat
        If contentType = "application/octet-stream" Then
            Return WebContentFormat.Json
        Else
            Return WebContentFormat.Default
        End If
    End Function
End Class

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
      <section name="AppName.My.MySettings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    </sectionGroup>
  </configSections>
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
    <!--Generate via 16 caractères http://ift.tt/1G9b55h -->
    <add key="envRnd" value="w6pgpNTDke3fpAd1" />
  </appSettings>
  <system.web>
    <compilation debug="true" strict="false" explicit="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.serviceModel>
    <bindings>
      <customBinding>
        <binding name="CustomMapper">
          <webMessageEncoding webContentTypeMapperType="AppName.CustomContentTypeMapper, AppName" />
          <httpTransport manualAddressing="true" />
        </binding>
      </customBinding>
      <webHttpBinding>
        <binding name="AjaxBinding"/>
      </webHttpBinding>
    </bindings>
    <client>
    <behaviors>
      <endpointBehaviors>
        <behavior name="AjaxBehavior">
          <enableWebScript />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
          <behavior name="ServiceBehaviors">
            <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
            <serviceDebug includeExceptionDetailInFaults="true"/>
          </behavior>
        </serviceBehaviors>
    </behaviors>
    <services>
      <service name="AppName.Service" behaviorConfiguration="ServiceBehaviors" >
        <endpoint address="AjaxEndpoint" behaviorConfiguration="AjaxBehavior" binding="customBinding"
            contract="AppName.IService" bindingConfiguration="CustomMapper"/>
      </service>
    </services>
  </system.serviceModel>
  <system.webServer>
    <!--<httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*"/>
        <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
      </customHeaders>
    </httpProtocol>-->
    <modules runAllManagedModulesForAllRequests="true"/>
    <directoryBrowse enabled="true"/>
  </system.webServer>

  <location path="Service.svc">
    <system.web>
      <authorization>
        <allow roles="prd" />
        <deny users="*" />
      </authorization>
    </system.web>
  </location>
  <applicationSettings>    
  </applicationSettings>
</configuration>

EDIT : I looked at both httperr1.log and files in inetpub\logs\LogFiles\W3SVC1 but none would give more informations than Fiddler that have been the best tool so far. I still don't have a clue.

getUserMedia Not working when inside a function

Why is this code not working:

videoCallButton.onclick = function()
{navigator.getUserMedia(mediaConstraints, handleUserMedia, handleUserMediaError);
};

but this one It is:

videoCallButton.onclick = navigator.getUserMedia(
mediaConstraints, handleUserMedia, handleUserMediaError
);

and the event onclick works everytime page is loaded, without clicking

 videoCallButton.onclick = alert("yes");

Facebook graph API help out please

Can some one help me in coding with graph api.

What I want is simple I want a page which asks the user's permission to give my app his details.

I want the following details and they must be at last put into a variable as belows:

------------------+------------------------------------------------+
Details to get    |   Variable to be put into                      |
------------------+------------------------------------------------+
First Name        |    first_name_for_signup                       |
------------------+------------------------------------------------+
Last Name         |    last_name_for_signup                        |
------------------+------------------------------------------------+
Date of Birth     |    dob_for_signup                              |
------------------+------------------------------------------------+
Country           |    national_identity_for_signup                |
------------------+------------------------------------------------+
Mobile No/Email   |   jaktherover_ran                              |
------------------+------------------------------------------------+
Gender            |         healllooooo                            |
------------------+------------------------------------------------+

And also my app wants to post on their behave as follows:"Helloooo boys and girls"

Conditions are as belows:

1.) Must be Javascript and not php or any other language.

2.) Full html page should be given in the answer

Put the app id as app id I will replace it manualy

And remember

Full html code including div's and javascript should be given. If you want more please comment.

Lastly Thanks....

Sending video captured with the computer camera from a website to a server

I am trying to have a computer or an android device record video from the camera and send it to a server that will store it. The system has to be web-based and needs to send clips of video continuously.

Here is the code in javascript:

var camera = (function() {
    var options;
    var video, canvas, context;
    var renderTimer;

    function initVideoStream() {
        video = document.createElement("video");
        video.setAttribute('width', options.width);
        video.setAttribute('height', options.height);

        navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
        window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;

        if (navigator.getUserMedia) {
            navigator.getUserMedia({
                video: true
            }, function(stream) {
                options.onSuccess();

                if (video.mozSrcObject !== undefined) { // hack for Firefox < 19
                    video.mozSrcObject = stream;
                } else {
                    video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
                }

                initCanvas();
            }, options.onError);
        } else {
            options.onNotSupported();
        }
    }

    function initCanvas() {
        canvas = document.getElementById("canvas");//options.targetCanvas || document.createElement("canvas");
        canvas.setAttribute('width', options.width);
        canvas.setAttribute('height', options.height);

        context = canvas.getContext('2d');

        // mirror video
        if (options.mirror) {
            context.translate(canvas.width, 0);
            context.scale(-1, 1);
        }

        startCapture();
    }

    function startCapture() {
        video.play();

        renderTimer = setInterval(function() {
            try {
                context.drawImage(video, 0, 0, video.width, video.height);
                options.onFrame(canvas);
            } catch (e) {
                // TODO
            }
        }, Math.round(1000 / options.fps));
    }

    function stopCapture() {
        pauseCapture();

        if (video.mozSrcObject !== undefined) {
            video.mozSrcObject = null;
        } else {
            video.src = "";
        }
    }

    function pauseCapture() {
        if (renderTimer) clearInterval(renderTimer);
        video.pause();
    }

    return {
        init: function(captureOptions) {
            var doNothing = function(){};

            options = captureOptions || {};

            options.fps = options.fps || 30;
            options.width = options.width || 640;
            options.height = options.height || 480;
            options.mirror = options.mirror || false;
            options.targetCanvas = options.targetCanvas || null; // TODO: is the element actually a <canvas> ?

            initVideoStream();
        },

        start: startCapture,

        pause: pauseCapture,

        stop: stopCapture
    };
})();

var imgSender = (function() {
    function imgsFromCanvas(canvas, options) {
        var context = canvas.getContext("2d");
        var canvasWidth = canvas.width; //# pixels horizontally
        var canvasHeight = canvas.height; //# pixels vertically
        var imageData = context.getImageData(0, 0, canvasWidth, canvasHeight); //Vector of all pixels
        options.callback(canvasWidth, canvasHeight, imageData.data);
    }

    return {
        fromCanvas: function(canvas, options) {
            options = options || {};
            options.callback = options.callback || doNothing;
            return imgsFromCanvas(canvas, options);
        }
    };
})();

var FPS = 30; //fps
var minVideoTime = 5; //Seconds that every video clip sent will take
var arrayImgs = []; //Array with all the images that will be sent to the server
var videoTime = 0; //Number of seconds of video stored in videoTime
(function() {
    var capturing = false;

    camera.init({
        width: 160,
        height: 120,
        fps: FPS,
        mirror: true,

        onFrame: function(canvas) {
            imgSender.fromCanvas(canvas, {
                callback: function(w,h,image) {
                    arrayImgs.push(image);
                    videoTime += 1/FPS;
                    if (minVideoTime <= videoTime) {
                        sendToPhp(w,h,videoTime*FPS);
                        arrayImgs = [];
                        videoTime = 0;

                        function sendToPhp(width,height,numFrames) {
                            $.ajax({
                                type: "POST",
                                url: "sendToServer.php",
                                data: {
                                    arrayImgs: arrayImgs,
                                    width: w,
                                    height: h,
                                    nframes: numFrames
                                },

                                async: true, // If set to non-async, browser shows page as "Loading.."
                                cache: false,
                                timeout:500, // Timeout in ms (0.5s)

                                success: function(answer){
                                    console.log("SUCCESS: ", answer);
                                },
                                error: function(XMLHttpRequest, textStatus, errorThrown){
                                    console.log("ERROR: ", textStatus, " , ", errorThrown);                             }
                            });
                        }
                    }
                }
            });
        },

        onSuccess: function() {
            document.getElementById("info").style.display = "none";

            capturing = true;
            document.getElementById("pause").style.display = "block";
            document.getElementById("pause").onclick = function() {
                if (capturing) {
                    camera.pause();
                } else {
                    camera.start();
                }
                capturing = !capturing;
            };
        },

        onError: function(error) {
            // TODO: log error
        },

        onNotSupported: function() {
            document.getElementById("info").style.display = "none";
            document.getElementById("notSupported").style.display = "block";
        }
    });
})();

As you can see, I am using getUserMedia to get the video, and I am sampling the images in an array until I have 5 seconds of video, then I send that to a php file that will send it to the server.

My problem: there is A LOT of lag in all the ajax requests, and I also have size problems, the ajax requests don't accept so much data at the same time, so I have to reduce the fps and the length of the videos sent.

Is there any better way to do this? By now, I lose more than 50% of the video! Maybe through WebRTC? Help please

Thank you!

How to validate Phone number using mask?

I am using http://ift.tt/1ci78g3. How to validate phone number using mask(maxlength), my code is

<input class="form-control" 
       type="text"
       data-parsley-errors-container="#homephoneid"
       data-parsley-required-message="Please enter Homephone"
       masked=""
       data-inputmask="'mask': '(999) 999-9999'"
       placeholder="Phone number"
       ng-model="patient.homephoneNumber"
       required
/>

Click event canvas/javascript

Hey everyone I was trying to make my rectangles clickable. After it worked i whanted , that when i click on a rectangle that it shows data in the div's. At this moment the data in the canvas div's are manual. Is it possible with the script i have to do what i whant or should I start again but make it completly different ???

for (var i = 0; i < rects.length; i++) {
    if (x > rects[i][0] && x < rects[i][0] + rects[i][2] && y > rects[i][1] && y < rects[i][1] + rects[i][3]) 
    {
        alert('Rectangle ' + i + ' clicked');
    }
}

This is what i had. I don't know how to change the alert into what i whant.

(For the whole html page )

http://ift.tt/1KLBMj8

How do you make changes from a new windowManager window?

I'm fairly new to JavaScript, so I'm learning as I'm doing things. On my internship I was asked to adjust a WYSIWYG html editor so it can be used with e-mails. I'm using placeholders to later be replaced by the user.

My question: How do I detect the input in the textbox and replace it in the editor?

I had a look at other posts, like this one, but I still can't get it to work.

My code so far:

setup: function(ed) {
    // on mouse up gets selected text
        ed.on('mouseup', function(ed, e) {
            var highlighted = tinyMCE.activeEditor.selection.getContent();
            // Checks if highlighted texts contains a placeholder
            if (highlighted.indexOf("[!") > -1) {
                //alert(highlighted);
                tinyMCE.activeEditor.windowManager.open({
                    title: 'replace',
                    width: 320,
                    height: 240,
                    body: [
                        {type: 'textbox'}
                    ]
                })
            }
        });
    }

Thanks in advance!

How to draw a sparkline inside a kendo template?

I have

<script type="text/x-kendo-template" id="items-template">
<div id='sparklineItemlist'> </div>

</script>

in my java-script i have

function loadSparkline(ItemSN){

   console.log('spark line loaded ' + document.getElementById('sparklineItemlist'));

     $("#sparklineItemlist") .sparkline([5,2,5,3,2,2,4,2,4,6,7,5,6,7,9,6,7,9,9,5,3,9,6,7  ], {
                                   type: 'line',
                                fillColor: null });

}

console.log('spark line loaded ' + document.getElementById('sparklineItemlist')) returns null and I cannot seem to access the spark line Item list div. How can I show the spark line?

autocomplete in bootstrap modal

I want to show the last input data filled by user in bootstrap modal, i tried using HTML autocomplete="on" attribute but failed, like done in this fiddle. once user click on submit, on the second time it shows the hints according to previous filled input values.

http://ift.tt/1EnL13D


http://ift.tt/1RknMkY

Now I'm using jquery autocomplete method but in that we have to pass an array as source. See following example

http://ift.tt/1yOgWhm

Suppose i save the text input using ng-model or something and save data in $rootScope or scope and then i refresh the browser, then scope will get vanish.

Plz help me to resolve this.

Why is this behavious strangely in iOS, but better in desktops?

I'm trying to create the same effect as http://ift.tt/1RknJpl - but my version seems to have some pretty awful bugs, that I need some help with.

I have a page at this URL: http://ift.tt/1FTyEBQ

This is using a combination of the twentytwenty image comparison slider (http://ift.tt/14c15aB) and Owl Carousel for the thumbnails (http://ift.tt/13yJsO1).

My issue is, whereas on the desktop, clicking on thumbnail will change the div above, and show the corresponding twentytwenty container. However on a mobile (I'm testing in iOS), when the page loads up, the initial slider is shown, but then when clicking on a thumbnail, the slider above disappears, and is not shown.

There's also another issue where as sometimes even on the desktop, the main divs won't be displayed, until the window is resized.. which I have no idea why.

Is there any way I can find out why this is happening? Any help is greatly appreciated!

I think this is the JS that corresponds to changing the main div when a thumbnail is clicked:

// TwentyTwenty comparison
function showSlide(slideNumber)
{  
    $(".image-compare-set").hide();
    $('.image-compare-set[data-image-num="' + slideNumber + '"]').show();
}
$(".twentytwenty").twentytwenty();
$(".image-compare-nav img").click(function() {
    showSlide( $(this).attr('data-image-num') );
});
showSlide(1);

UPDATE

It seems that within each main div, the height element of the slider containers is being set inline to 0, which is causing them to disappear. Maybe this needs to be added to the JS code that sets the parent div to display block?

Or maybe to set the height of the div to the same height of the images, when it is clicked? Does that seem to be how Mya have done theirs, as it seems to work perfectly, regardless of resizing, and loading.

Anyone?

Jquery script to call Servlet - can't get corret URL of Servlet

Below, there is jquery script which calls Servlet by URL. At first i need to say that i have 2 separate projects. First is Dynamic Web Project which contains servlets etc. Second is simple Ratchet HTML-CSS-JS Project which of course contains some pages, scripts and css.

        <script>
            $(document).ready(function() {                        // When the HTML DOM is ready loading, then execute the following function...
                $('#button').click(function() {               // Locate HTML DOM element with ID "somebutton" and assign the following function to its "click" event...
                    $.get('http://localhost:8080/testuje/text', function(responseText) { // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response text...
                        $('#div').text(responseText);         // Locate HTML DOM element with ID "somediv" and set its text content with the response text.
                    });
                });
            });
        </script>

Here is my Servlet code:

package pl.javastart.servlets;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/text")
public class HelloWorldServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String text = "some text";

        response.setContentType("text/plain");  // Set content type of the response so that jQuery knows what it can expect.
        response.setCharacterEncoding("UTF-8"); // You want world domination, huh?
        response.getWriter().write(text);
        // Write response body.
    }
}

The problem is, what should i put in $.get('http://localhost:8080/testuje/text', function(responseText)

to get servlet content after button click.

How to pass data from one page to other page in angular js

I have created a new blog project using angular-js. Here I have one page listing all the blogs and if I click on the edit button or delete button, I want to move to next page and show that data in the form from where I updated the blog.

My blog list page: listblog.html

<!DOCTYPE html>
<html lang="en">

<head>



    <title>My First AngularJs Blog</title>

 <script type="text/javascript" src="http://ift.tt/196KcQm"></script>

    <!-- Bootstrap Core CSS -->
    <link href="css/bootstrap.min.css" rel="stylesheet">

    <!-- Custom CSS -->
    <link href="css/blog-home.css" rel="stylesheet">

    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
        <script src="http://ift.tt/1fK4qT1"></script>
        <script src="http://ift.tt/1knl5gY"></script>
    <![endif]-->

</head>

<body ng-app="blogapp">

    <!-- Navigation -->
   <div ng-include="'includes/header.html'">                    
</div>

    <!-- Page Content -->



       <div class="container">
 <div ng-controller="blogcontroller">
  <h2>Blog List</h2>
  <p>Here is the awsome blog list</p>            
  <table class="table">
    <thead>
      <tr>
        <th>Title</th>
        <th>Blog</th>
        <th>Posted On</th>
        <th>Action</th>
      </tr>
    </thead>
    <tbody>
      <tr  ng-repeat="blg in allblog">
        <td>{{blg.title}}</td>
        <td>{{blg.description}}</td>
        <td>{{blg.created_on }}</td>
        <td><a href="">Edit</a> || <a href="">Delete</a></td>
      </tr>

    </tbody>
  </table>

  </div>
</div>


        <hr>

        <!-- Footer -->

 <div ng-include="'includes/footer.html'">                    
</div>

    <!-- /.container -->

    <!-- jQuery -->
    <script src="js/jquery.js"></script>

    <!-- Bootstrap Core JavaScript -->
    <script src="js/bootstrap.min.js"></script>
<script src="controller.js"></script>
</body>

</html>


I want to create a controller for edit. My Controller file: controller.js

var myApp = angular.module("blogapp", []);

  myApp.controller('blogcontroller',function ($scope,$http){

    $http({method: 'GET' , url: 'getallblog.php'}).success(function(data){
        $scope.allblog = data;
    });


    $scope.new_post =function(){



    $http.post("addblog.php" ,{'title' : $scope.title ,'description' : $scope.description }).success(function(data,status,headers,config){
        window.location='index.html';
        console.log("inserted Successfully");
    });
  } ;


  $scope.editpost = function(index){

    $http.post('allscript.php?action=edit_post', { 'id' : index})
    .success(function (data, status, headers, config){


    }) 
    .error(function (data, status, headers, config){
           console.log(status);
        });


  }

  });


And my php script page where all operations are performed allscript.php

<?php 

$user ="root";
$pass ="m2n1shlko";

$dbh = new PDO('mysql:host=localhost;dbname=blog_db', $user, $pass);


switch($_GET['action']){

    case 'edit_post':
        edit_post();
    break;





function edit_post(){

  $data = json_decode(file_get_contents("php://input"));     
    $index = $data->id; 

$query = $dbh->prepare("SELECT * FROM blog_list where id='$index'") ;
$da = $query->execute();
$getre = $da->fetch(PDO::FETCH_ASSOC);

print_r(json_encode($getre));
return $getre;


}



}
?>

I am new in angular-js. I don't know how to get the ID of that record and to take to the next page for edit/update/delete.

Any help is appreciated. Thanks.

Google Script not Appending Spreadsheet

I'm trying to write a little script to make my coworkers and mine lives easier. I am trying to append lines to a spreadsheet based on information entered into a custom form. The code posted below just the doPost block which should be appending the google spreadsheet.

function doPost(form) { 
  var PN = form.PartNumber;
  var REV = form.Revision;
  var DATE = form.RevisionDate;
  var DESC = form.Description;
  var NOTE = form.PartNotes;
  var URL = form.myFile.getURL();  
  var ss = SpreadsheetApp.openById("ID HERE"); // removed ID for sake of safety (let me be paranoid)
  var sheet = ss.getSheetName('Uploads');
  sheet.appendRow([PN,REV,DATE,DESC,NOTE,URL]);
}

I am unsure why it isn't writing to the spreadsheet but it isn't throwing me any errors. If you can offer any insight as to what is wrong I would greatly appreciate it; there are many guides online but most seem to be based on deprecated functions/code/etc.

Thanks for your time.

Transfer the context of `this.data` to other templates in Blaze/Meteor?

I have a route gathering some data.

Router.map(function () {
  this.route('Players.guild', {
    path: '/players/guild/:guildId',
    template: 'GuildPlayerList',
    waitOn: function () {
      return Meteor.subscribe('guild_players', this.params.guildId);
    },
    data: function () {
      return Players.find({ guildId: this.params.guildId });
    }
  });
});

Then, I have a simple template

template(name="GuildPlayerList")
  +ionList
    +each this
      +ionItem avatar=true ion-data-modal="_playerModalView"
        img(src="{{ imageId store='PlayerThumbnails' }}" alt="{{ name }}")
        h2 {{ name }}

template(name="_playerModalView")
  // I want the current player in the +each to push its context of this here
  +ionModal title="{{ name }}"

The problem, however, is it seems that the context of this changes when I load the modal. In other cases, I have used _.bind to push the context of this, but how can this be done with blaze templates?

Equivalent of _byteswap_ulong in JavaScript/Node.js?

What is the equivalent of _byteswap_ulong in JavaScript?

I'm currently using the following C++ code:

int tag = 2832779;
tag = _byteswap_ulong(tag) >> 8;

The result of tag is 9124193.

I tried doing the same in JavaScript:

var tag = 2832779;
tag = (((tag >> 24) & 0x000000FF) | ((tag >> 8) & 0x0000FF00) | ((tag << 8) & 0x00FF0000) | ((tag << 24) & 0xFF000000)) >> 8;

However, the result of tag (in JS) is -7653077.

Is it possible to swap bytes in JavaScript the same way it's possible in C++?

Thanks a lot!

Telerik Kendo UI grid loses custom command event handler after persisting (and restoring) its state

I've isolated the issue, see and try the full source here:

http://ift.tt/1RknM4u

Steps to reproduce:

  1. Press Ctrl+Enter to run the snippet

  2. Click on 'Say Hello' custom command button, and check if the event handler runs

  3. Click on top left 'Save State' button 3) Click on 'Load State' button, and restore the previous state.

  4. Now click again on 'Say Hello' button and demonstrate the event handle will not run, instead something weird is happening.

Notes: Please do not search for the solution around the localStorage. The issue can be reproduced by using different server side state persisting solution. (as my original app does)

Any idea where to patch? ... or workaround?

AngularJS [$injector:unpr] Unknown provider: dataProvider <- data <- PageCtrl

I have seen the other answers and so far nothing has helped me. I get this error with the following code in a file:

   angular.module('myApp.page', ['ngRoute'])
        .config(['$routeProvider', function($routeProvider) {
            $routeProvider.when('/page/:pageId', {
                templateUrl: 'page/view.html',
                controller: 'PageCtrl',
                resolve: {
                    data: function($q, $http, $routeParams) {
                        var deferred = $q.defer();
                        $http({method: 'GET', url: 'http://....' + $routeParams.pageId})
                            .then(function(data) {
                            deferred.resolve(data);


       });
                    return deferred.promise;
                }
            }
        })
    }])
    .controller('PageCtrl', function ($scope, $rootScope, data) {
//do stuff
}

And in the app.js I have this:

angular.module('myApp', [
    'ui.bootstrap',
    'ngRoute',
    'ngTouch',
    'ngResource',
    'myApp.page'
]).
config(['$routeProvider', function($routeProvider) {
  $routeProvider.otherwise({redirectTo: '/'});
}]).
config(['$provide', Decorate])

Everything was working correctly and I fetched the data with the HTTP method with no problems, until I started using the Q library and moved the data fetching into the config section. Any tips? None of the other answers seem to work. Thanks in advance!

Selecting bootstrap drop down with jquery not working

I have a twitter-bootstrap select that I am trying to iterate with jquery to build a list of google-maps markers(latitude/longitude/building-id is stored with list). on document ready I want to iterate the list and extract the lat/long from each li item and create a marker with that location:

        <select id="buildings" class="selectpicker" data-width="100%" data-live-search="true"><!-- style="border-radius:0px;" -->
            {% for category in buildings %}
                <optgroup label="{{ category.category.asBuildingCategory }}">
                    {% for building in category.buildings %}
                        <option data-content="<span data-latitude='{{building.fLatitude}}' data-longitude='{{building.fLongitude}}' data-build-id='{{building.ixBuilding}}'>{{building.asBuildingName}}</span>"></option>
                    {% endfor %}
                </optgroup>
            {% endfor %}
        </select>

This is what the code generated looks like in the browser: enter image description here

I can successfully attach an onclick for each menu item, but I can't seem to iterate the select list via jquery.

Thus far I have tried this:

$(document).ready(function () {
    $(".dropdown-menu.inner.selectpicker li").each(function () {
        alert($(this));
    });
});

but it doesn't seem to hit anything. However This code works for adding the click listener:

$(document.body).on('click', '.dropdown-menu.inner.selectpicker li', function () {
    debugger;
    var latitude = $(this).find("span").data('latitude');
    var longitude = $(this).find("span").data('longitude');
    var buildingID = $(this).find("span").data('build-id');
});

EDIT This is what my jquery finds using this code: enter image description here

var test = $(".dropdown-menu.inner.selectpicker li");

It just gets the entire document instead of the list elements

Get variable object dynamically in javascript [duplicate]

This question already has an answer here:

I have the following variable:

country = {
  city: {
    code: {
      area: '',
      prefix: '',
    },
  }
}

To access area I can do:

country.city.code.area 

or

country['city']['code']['area']

But now I have a variable named path which is:

var path = 'city.code.area';

I know the following won't work:

country[path]

How can I get the area value using path?

Note: Path can be 'city.code.area', 'city.code' or anything else. I need a generic way to do this ...

How to run multi javascript functions onPageFinished android

I m coding a WebView application that should call some javascript functions everytime a page is loaded

This is what I ve done but it doesn't work.

public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    WebView view = (WebView) findViewById(R.id.webView);
    WebSettings faller = view.getSettings();
    String url = "http://ift.tt/1csYSzJ";
   faller.setJavaScriptEnabled(true);
   view.loadUrl(url);
    view.setWebViewClient(new WebViewClient() {
        public void onPageFinished(WebView view, String url) {
            view.loadUrl("javascript:clickFunction()");
            view.setWebViewClient(new WebViewClient() {
               public void onPageFinished(WebView view, String url) {
               view.loadUrl("javascript:clickFunction2()");
          }
        }
    });

}
}

Everything goes well Untill i reach the clickfunction2(). I can't call this second function Where I m wrong??

appendChild function not working

//I am creating dynamic form using java script

,Here is my js file ,i want to know logic behind below code with comment

  var element=document.createElement("input");
    element.setAttribute("type","text");
    element.setAttribute("placeholder","*Name");
    element.setAttribute("name","name");
    var namefield=document.getElementById("namefield");
    namefield.appendChild(element);

    var element11=document.createElement("br");
    var br=document.getElementById("namefield");
    br.appendChild(element11);//not working
    br.appendChild(element11);//not working`enter code here`

    br.appendChild(document.createElement("br"));
    br.appendChild(document.createElement("br"));//its working,i cant understand reason behind it, i want to know actual reason behind it                                                         

strtus2 I18N application using radio buttons

I'm trying to change the language using radio buttons but it is not working. Here is the code which I have tried

settings.jsp:

<div>
    <s:iterator value="languages">
        <span class="languages"> <s:radio list="#{Value:Name }"
            id="language" name="request_locale"
            onclick="changeLanguage(this.value)" value="%{language}" />
        </span>
    </s:iterator>
</div>

script:

function changeLanguage(locale) {
//      alert(locale);
         $.ajax({
            async: false,
            url: '../login/userProfile_changeLanguage.action?language='+locale,
            success: function(data, status, xhr) {
                if(xhr.getResponseHeader('sessionStatus') == 701){
                    window.location.href = window.location.pathname.substring(0,window.location.pathname.substring(1).indexOf("/")+1);
                }
                else{
                    $('#main').html(data);
                }
            }
        }); 
    } 

enter image description here

where I went wrong?

How to check a number inside a span and change its color based on the value?

Here is what I have. It isn't reading the value correctly.

http://ift.tt/1JTDscG

HTML:

<a class="InterestLink">Click me</a>

<div id="InterestExpander">
            <div id="InterestExpanderX">
                &times;
            </div>

            <br><br>

            General Rating: 
            <span class="RatingGeneralNumber">80%</span>
</div>

CSS:

<a class="InterestLink">Click me</a>

<div id="InterestExpander">
            <div id="InterestExpanderX">
                &times;
            </div>

            <br><br>

            General Rating: 
            <span class="RatingGeneralNumber">80%</span>
</div>

jQuery:

$('.InterestLink').click(function() {
    $('#InterestExpander').fadeIn(450);

    if (parseInt($('.RatingGeneralNumber').val()) > 50 ) {
        $('.RatingGeneralNumber').css({"color":"green"});
    }

}); 



$('#InterestExpanderX').click(function() {
    $('#InterestExpander').fadeOut(250);
});

Also, another question while I'm here. This site will have links to multiple different movies. Each time they click on a movie link, the same div will pop up, but with a rating unique to the movie based on what the database says.

Would the span be containing the movie rating be more appropriate as an "ID" or "Class" type, or neither?

Fetch a data from a string

I have this as a string. I have get this using jquery and parsing it from a web page.

I tried using jQuery.parseJSON and got the error Uncaught SyntaxError: Unexpected token n.

I need to get "surl" and "imgurl" how can I get this?

{
    ns:"images",
    k:"5061",
    mid:"172E23D582B8C2A90F3FE9DC2B04A3ECD1D4F70F",
    surl:"http://ift.tt/1JTDu4d",
    imgurl:"http://ift.tt/1ceVfwD",
    ow:"480",
    docid:"608038082569896450",
    oh:"301",
    tft:"117",
    dls:"images,5487"
}

How to controll Pagedlistpager button in mvc with javascipt

I have a bug about using pagedlistpager in mvc such as:

@Html.PagedListPager(Model, page => Url.Action("Index", new { page = page }), PagedListRenderOptions.OnlyShowFivePagesAtATime)

when I click to the "2" button in the pagedlistpager, it will redirect to controller with method index, but now, I want to it redirect to a function of javascript, how can I do??

JQuery: How to callback each loop after completion of ajax call?

How to callback each loop after completion of ajax call.

Please find my code as follows.

Story:

Let us assume I have 3 values X,Y,Z. Firstly, I am taking X value, sending to django views and their using requests module for getting some info and pushing to the div class push_new_info_here, in the next Iteration I have to take Y value. How to do ? please note: Previous ajax call should be succeeded .

Final word: I am collecting all the info of (X,Y,Z), then merging using python and pushing to the div class push_new_info_here

window.onload = function() {

  $.each(["X","Y","Z"], function( index, value ) {

      $.post('/find/'+value+'/',{},function(data){
          $('.push_new_info_here').empty();
          $('.push_new_info_here').html(data);
      });

  });

};

Javascript input code

Here is html code.

<div data-block="true" data-offset-key="7cq06-0-0" class="_209g _2vxa" data-reactid=".c.1:3.0.$right.0.0.0.0.1.0.0.1.0.0.$7cq06"><span data-offset-key="7cq06-0-0" data-reactid=".c.1:3.0.$right.0.0.0.0.1.0.0.1.0.0.$7cq06.0:$7cq06-0-0"><br data-reactid=".c.1:3.0.$right.0.0.0.0.1.0.0.1.0.0.$7cq06.0:$7cq06-0-0.0"></span></div>

I want to enter a input automaticaly by javascript code. After enter "MESSAGE HERE !!!" the html code changes like this(I entered by hand) :

<div data-block="true" data-offset-key="2s0n6-0-0" class="_209g _2vxa" data-reactid=".h.1:3.0.$right.0.0.0.0.1.0.0.1.0.0.$2s0n6"><span data-offset-key="2s0n6-0-0" data-reactid=".h.1:3.0.$right.0.0.0.0.1.0.0.1.0.0.$2s0n6.0:$2s0n6-0-0"><span data-reactid=".h.1:3.0.$right.0.0.0.0.1.0.0.1.0.0.$2s0n6.0:$2s0n6-0-0.0">MESSAGE HERE !!!</span></span></div>

What is the javascript code that I am looking for ?

How to check an input words against several arrays in Javascript

I need to test all the words entered into an input against 3 objects and determine which array they belong to so I can output a URL to an API. I want to achieve this with Javascript/jQuery.

For example if the input had these words: keyword1 keyword2 keyword3 keyword5

All keyword entries will be added from a autocomplete plugin.

I then need to test them against 3 arrays.

var array1 = ["keyword2", "keyword6"];
var array2 = ["keyword3", "keyword4"];
var array3 = ["keyword1", "keyword5"];

I need to determine what array they came from so I can output a URL and add the values to specific keys in a URL.

Example:

http://ift.tt/1ceVdFc [insert keyword(s)] &array2= [insert keyword(s)] &array3= [insert keyword(s)]

The keywords need to be sent as an array and must have spaces replaced with dashes.

I am using jQuery to perform a GET request with the URL generated.

How to hide css while clicking another

I want to hide black arrow while clicking green arrow.. without using jquery

My fiddle:

enter code here

http://ift.tt/1JTDrWk

Please anyone help

One page website with navigational sections [on hold]

So i was wondering if anyone could direct me in the right path for designing a one page website with sections. As you scroll down, you move down to the next section of the website. I want to have one page where I can scroll down through many different sections.

$controller is not a function in Angular/Jasmine

I am pulling my hair out with testing Angular. I am trying to instantiate a controller and jasmine complains that $controller is not a function. Below is my test.

describe "MyCtrl test", () ->
  beforeEach module('ngRoute')
  beforeEach module('myControllers')

  $controller = undefined
  $scope = undefined
  $routeParams = undefined
  mySvc = undefined

  beforeEach inject (_$controller_, $rootScope, _$routeParams_,_mySvc_) ->
    $controller = _$controller_
    $scope = $rootScope.$new()
    mySvc = _mySvc_

  describe "MyCtrl", () ->
    beforeEach () ->
      MyCtrl = $controller('MyCtrl', {$scope:$scope,$routeParams:$routeParams,mySvc:mySvc})
    it "should be defined", () ->
      expect(MyCtrl).toBeDefined()

I have defined $controller at the top level scope, I have injected the controller service and assigned it to the global variable. How is it not a function?

How do I build a carousel image slider using MVC cshtml?

I am trying to code a carousel image slider in MVC using cshtml, the pictures are only displaying in one vertical row and isn't populating into the Carousel slider itself? here is what I have attempted so far :

Html.Raw("<link href='../../Content/Site.css' rel='stylesheet'>")
@Html.Raw("<script src='../../Scripts/jquery-1.5.1.min.js'></script>")

Products

<script src="Scripts/jquery.cycle.all.js"></script>
<script src="Scripts/jquery.cycle.all.js"></script>
<script type="text/javascript"> $('#slider').cycle({ fx: 'fade', speed: 'fast', timeout: 0, next: '#next2', prev: '#prev2' });
</script>

<link rel="stylesheet" href="Content/css/feature-carousel.css" charset="utf-8" />

    <meta http-equiv="Content-type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" href="Content/css/feature-carousel.css" charset="utf-8" />
    <script src="~/Scripts/jquery-1.10.2.js" type="text/javascript" charset="utf-8"></script>
    <script src="Content/js/jquery-1.7.min.js"></script>
    <script src="Content/js/jquery.featureCarousel.min.js" type="text/javascript" charset="utf-8"></script>
    <script type="text/javascript">

        $(document).ready(function ()
        {
            var carousel = $("#carousel").featureCarousel({


                // include options like this:
                // (use quotes only for string values, and no trailing comma after last option)
                // option: value,
                // option: value
            });

            $("#but_prev").click(function () {
                carousel.prev();
            });
            $("#but_pause").click(function () {
                carousel.pause();
            });
            $("#but_start").click(function () {
                carousel.start();
            });
            $("#but_next").click(function () {
                carousel.next();
            });
        });
    </script>


          <center>



                    <div class="carousel-container"></div>

                        <div id="carousel">
                            <div class="carousel-feature">
                                <a href="#"><img class="carousel-image" alt="Image Caption" src="~/Images/1.jpg" /></a>
                                <div class="carousel-caption">

                                </div>
                            </div>

                            <div class="carousel-feature">
                                <a href="#"><img class="carousel-image" alt="Image Caption" src="~/Images/2.jpg"></a>
                                <div class="carousel-caption">

                                </div>
                            </div>

                            <div class="carousel-feature">
                                <a href="#"><img class="carousel-image" alt="Image Caption" src="~/Images/3.jpg"></a>
                            </div>

                            <div class="carousel-feature">
                                <a href="#"><img class="carousel-image" alt="Image Caption" src="~/Images/4.jpg"></a>
                                <div class="carousel-caption">
                                </div>
                            </div>

                            <div class="carousel-feature">
                                <a href="#"><img class="carousel-image" alt="Image Caption" src="~/Images/5.jpg"></a>
                                <div class="carousel-caption">
                                </div>
                            </div>

                            <div id="carousel-left"><img src="~/Content/images/arrow-left.png" /></div>
                            <div id="carousel-right"><img src="~/Content/images/arrow-right.png" /></div>
                        </div>

           </center>

amqplib - How many consumers on a queue?

Using amqplib module for Node JS and RabbitMQ,

1) is there any way to tell how many subscribers there are on a queue?

2) How can i make each queue should have one consumer key?

Thanks!

GAE Channel Api vs Socket

I have a Google app that runs using GO on the server side and Javascript on the client side. The client generate every certain timestep a javascript object (that could be "stringified") that needs to be sent back to the server and saved as json file. Based on the google app engine documentation it seems that this could achieved with both:

  1. channel api
  2. socket service

but I couldn't find any examples for both of these and also it is not clear to me which one is the best to accomplish the goal. Can anyone help me? Thanks a lot.

Vue JS Watching deep nested object

Disclaimer: This is my first attempt at building an MVVM app I have also not worked with vue.js before, so it could well be that my issue is a result of a more fundamental problem.

In my view I have two types of blocks with checkboxes:

  • Type 1: block/checkboxes
  • Type 2: block/headers/checkboxes

The underlying object is structured like this:

{
  "someTopLevelSetting": "someValue",
  "blocks": [
    {
      "name": "someBlockName",
      "categryLevel": "false",
      "variables": [
        {
          "name": "someVarName",
          "value": "someVarValue",
          "selected": false,
          "disabled": false
        }
      ]
    },
    {
      "name": "someOtherBlockName",
      "categryLevel": "true",
      "variables": [
        {
          "name": "someVarName",
          "value": "someVarValue",
          "categories": [
            {
              "name": "SomeCatName",
              "value": "someCatValue",
              "selected": false,
              "disabled": false
            }
          ]
        }
      ]
    }
  ]
}

My objectives

Selecting checkboxes:

  1. User clicks on checkbox, checkbox is selected (selected=true)
  2. A method is fired to check if any other checkboxes need to be disabled (disabled=true). (If this method has indeed disabled anything, it also calls itself again, because other items could be in turn dependent on the disabled item)
  3. Another method updates some other things, like icons etc

Clearing checkboxes

A user can clicks on clear button, which unchecks (selected=false) all checkboxes in a list. This action should also trigger the methods that optionally disables checkboxes and updates icons etc.

My current method (which doesn't seem quite right)

  • The selected attribute of the data-model is bound to the checked state of the checkbox element via the v-model directive.
  • The disabled attribute (from the model) is bound to the element's class and disabled attribute. This state is set by the aforementioned method.
  • To initialize the methods that disable checkboxes and change some icons, I am using a v-on="change: checkboxChange(this)" directive. I think I need to do this part differently
  • The clearList method is called via v-on="click: clearList(this)"

The problems with my current setup is that the change event is not firing when the checkboxes are cleared programatically (i.e. not by user interaction).

What I would like instead
To me the most logical thing to do would be to use this.$watch and keep track of changes in the model, instead of listening for DOM events.

Once there is a change I would then need to identify which exact item changed, and act on that. I have tried to create a $watch function that observes the blocks array. This seems to pick up on the changes fine, but it is returning the full object, as opposed to the individual attribute that has changed. Also this object lacks some convenient helper attributes, like $parent.

I can think of quite a few hacky ways to make this work, but my use case seems pretty standard, so I expect there should be a much more elegant way to handle this.

How to save zip file with file extension in Safari 8 using jszip?

I want to save zip file on client side using jszip library.

Here is my code:

function zipDownload(){
    var fileName ="test.zip",
        zip = new JSZip(),
        content,
        img,
        data;

    zip.file("hello.txt", "Hello World\n");
    data = zip.generate({type: $.isFunction(window.Blob) ? "blob" : "base64"});
    fileLoader.saveAs(fileName, "application/zip", data);
}

It works fine in all modern browsers except Safari 8.

Safari 8 can't save file with file extension.

This is a sample http://ift.tt/1ceVdoE that shows this issue in action.

How to find dual monitor (secondary monitor) screen width and height?

How to find dual monitor (secondary monitor) screen width and height? Using javascript or jquery. Can anybody help?

Thanks,

Pandiyan

Upload Json Array from GAE to Cloud Storage in GO

I trying to upload to google cloud storage a json array which is posted by an app engine application using the following code:

saveData : function saveData() {
  var _this = this,
      save = this.shadowRoot.querySelector('#save-data'),
      subData = JSON.stringify(_this.app.userSession);

  save.url="url";
  save.body = subData;
  save.go();
}

The posted message is handled in go with the code posted below. With this code I'm able to create a folder on the cloud storage bucket which is named with the user ID. What I would love to do is to copy into the folder the entire json array -i.e. the variable f in the code below. I tried with io.Copy(wc, f) but it gives me the following error:

cannot use content (type userData) as type io.Reader in argument to io.Copy: userData does not implement io.Reader (missing Read method)

Obviously I'm doing something wrong, but I'm quite new to go and I'm totally stuck. Can someone help me?

package expt

import (
    "bytes"
    "encoding/json"
    "io/ioutil"
    "log"
    "net/http"
    "http://ift.tt/1salFH3"
    "golang.org/x/oauth2"
    "http://ift.tt/1rLuirs"
    "http://ift.tt/1HDShL0"
    "http://ift.tt/1ceVckz"
    "http://ift.tt/1JTDrW6"
    "http://ift.tt/1ceVckC"
    "http://ift.tt/1JTDrW8"
)

var bucket = "expt"

func init() {
    http.HandleFunc("/", handleStatic)
    http.HandleFunc("/save", saveJson)
}

func handleStatic(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Cache-Control", "no-cache")
    http.ServeFile(w, r, "static/"+r.URL.Path)
}

type Result map[string]interface {
}

type userData struct {
    id     string
    age    string
    gender string
}

func testA(r *http.Request) userData {
    defer r.Body.Close()
    body, err := ioutil.ReadAll(r.Body)
    var userDataCurr userData
    if err != nil {
        log.Printf("Couldn't read request body: %s", err)
    } else {
        var f Result
        err := json.Unmarshal(body, &f)
        if err != nil {
            log.Println("Error: %s", err)
        } else {
            user := f["user"].(map[string]interface{})
            userDataCurr.id = user["id"].(string)
        }
    }
    return userDataCurr
}

// saveData struct holds information needed to run the various saving functions.
type saveData struct {
    c   context.Context
    r   *http.Request
    w   http.ResponseWriter
    ctx context.Context
    // cleanUp is a list of filenames that need cleaning up at the end of the saving.
    cleanUp []string
    // failed indicates that one or more of the saving steps failed.
    failed bool
}

func (d *saveData) errorf(format string, args ...interface{}) {
    d.failed = true
    // log.Errorf(d.c, format, args...)
}

// testSave is the main saving entry point that calls the GCS operations.
func saveJson(w http.ResponseWriter, r *http.Request) {

    c := appengine.NewContext(r)
    if bucket == "" {
        var err error
        if bucket, err = file.DefaultBucketName(c); err != nil {
            // log.Errorf(c, "failed to get default GCS bucket name: %v", err)
            return
        }
    }
    hc := &http.Client{
        Transport: &oauth2.Transport{
            Source: google.AppEngineTokenSource(c, storage.ScopeFullControl),
            Base:   &urlfetch.Transport{Context: c},
        },
    }
    ctx := cloud.NewContext(appengine.AppID(c), hc)

    d := &saveData{
        c:   c,
        r:   r,
        w:   w,
        ctx: ctx,
    }

    d.createUserFolder()

}

// createFile creates a file in Google Cloud Storage.
func (d *saveData) createFile(fileName string) {

    wc := storage.NewWriter(d.ctx, bucket, fileName)
    wc.ContentType = "text/plain"
    d.cleanUp = append(d.cleanUp, fileName)

    if err := wc.Close(); err != nil {
        d.errorf("createFile: unable to close bucket %q, file %q: %v", bucket, fileName, err)
        return
    }
}

//create files that will be used by listBucket.
func (d *saveData) createUserFolder() {
    var (
        content = testA(d.r)
        buffer  bytes.Buffer
    )

    buffer.WriteString(content.id)
    buffer.WriteString("/")
    d.createFile(buffer.String())
}

Mandrill emails sent to Hotmail go to the spam

THE SITUATION:

Hello guys. I am registered with Mandrillapp and everything is working fine. I can send and receive emails from my app.

I have just this issue: The emails sent to Hotmail end up in the spam.

THE QUESTION:

How can make sure that the emails directed towards Hotmail go properly to the inbox? Did somebody encounter this issue before?

Thank you very much!

How to set a cookie based on URL when site visitor manually changes the URL

I am working on a site redesign going from Joomla to MODX, and would like to duplicate something from the current site, but can't find where the code is that manages this. Basically, when a user comes to the site their location is determined by IP, and it sets the URL to something like example.com/dc-metro and sets a cookie called "market" to "dc-metro". There is a dropdown on the site for a visitor to change their location, so if they select "Chicago" for example, the URL becomes example.com/chicago and the market cookie is updated to a value of "chicago". That part works great, the issue I am having is, if a user is on http://ift.tt/1JtUs68, and instead of using the dropdown to change location, they manually change the URL to http://ift.tt/1F7Zqrl, the page refreshes, but the cookie is not updated.

Is there a way to do something like $SERVER['REQUEST_URI'] (or something like that) to pull from the URL and set the cookie when the page reloads. I have several places on the site that show a variable based on the market cookie, and these are not updating (for example, on my dropdown the default value is the current market location).

Thank you very much in advance for any help.

Symfony2 is refreshing a twigs block with ajax possible?

Lets say I have a block in my layout:

{% block sidebar %} {% render url( 'sidebar' ) %} {% endblock %}

Is it possible to refresh the block with ajax without making a div around it? In my example I cant make a div, because it crashes my whole template so I need to know is that even possible?

For example I can refresh a div like this(.test is the class of the table):

$('.test').load(" .test");

Can I make something like this to refresh the block?

$('sidebar').load(" sidebar");

Any ideas?

Email sending system is not working

I am working on a project in which a client enters his name in the HTML form and clicks send and then the name is sent through the AJAX post function and received at the server side with KOA.js and then using nodemailer, is emailed to a predefined email-id.I am having a problem that all the pieces of code are not coordinating with each other (some pieces of code are malfunctioning or not working too) and so the system just doesn't work. I am posting all the code below, that I have used to make this program. I would really appreciate some help on this matter.

Thanks

The HTML code:-

1.This is the code for the textbox, to take the name of the client as an input.

    <input type="text" class="form-control" ng-model="name" id="supporter"                placeholder="Please Type In your Name Here.">

2.This is the code for the button,that triggers the AJAX function to send the input name to the server.

    <div class="btn">
    <button type="button" class="btn btn-lg btn-success" style="background-color: yellow;font-size:150%;" onclick="send()">Send the E-mail</button>
    </div>

3.This is the HTML code for the display of the status of the submit action, when the send button is clicked ( more details of this function does can be easily found in the AJAX piece of code ).

    <div id="myDiv"></div>
    <div id="myGraphics"></div>

4.The AJAX code:-

1.This AJAX code not just sends the clients name to the server but also controls a bootstrap progress bar that shows up at the client side, showing him if his data is sent or not (it shows the status of the submit action).

AJAX Code:-

    function send()
    {
    var xmlhttp;
    var name;
    name = document.getElementById("supporter").value;
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttp.onreadystatechange=function()
      {
        if (xmlhttp.readyState==0 && xmlhttp.status==200)
        {
        document.getElementById("myDiv").innerHTML="request not initialized";
        document.getElementById("myGraphics").write("<div class="progress">
                        <div class="progress-bar progress-bar-danger" style="width: 20%">
                        <span class="sr-only">20% Complete (danger)</span>
                        </div>
                        </div>");
        }
        else if (xmlhttp.readyState==1 && xmlhttp.status==200)
        {
        document.getElementById("myDiv").innerHTML="server connection established";
        document.getElementById("myGraphics").write("<div class="progress">
                        <div class="progress-bar progress-bar-danger" style="width: 20%">
                        <span class="sr-only">20% Complete (danger)</span>
                        </div>
                        <div class="progress-bar progress-bar-warning progress-bar-striped" style="width: 20%">
                        <span class="sr-only">20% Complete (warning)</span>
                        </div>
                        </div>");
        }
        else if (xmlhttp.readyState==2 && xmlhttp.status==200)
        {
        document.getElementById("myDiv").innerHTML="request received";
        document.getElementById("myGraphics").write("<div class="progress">
                        <div class="progress-bar progress-bar-danger" style="width: 20%">
                        <span class="sr-only">20% Complete (danger)</span>
                        </div>
                        <div class="progress-bar progress-bar-warning progress-bar-striped" style="width: 20%">
                        <span class="sr-only">20% Complete (warning)</span>
                        </div>
                        <div class="progress-bar progress-bar-info progress-bar-striped" style="width: 20%">
                        <span class="sr-only">20% Complete (info)</span>
                        </div>
                        </div>");
        }
        else if (xmlhttp.readyState==3 && xmlhttp.status==200)
        {
        document.getElementById("myText").innerHTML="processing request";
        document.getElementById("myGraphics").write("<div class="progress">
                        <div class="progress-bar progress-bar-danger" style="width: 20%">
                        <span class="sr-only">20% Complete (danger)</span>
                        </div>
                        <div class="progress-bar progress-bar-warning progress-bar-striped" style="width: 20%">
                        <span class="sr-only">20% Complete (warning)</span>
                        </div>
                        <div class="progress-bar progress-bar-info progress-bar-striped" style="width: 20%">
                        <span class="sr-only">20% Complete (info)</span>
                        </div>
                        <div class="progress-bar progress-bar-primary progress-bar-striped" style="width: 20%">
                        <span class="sr-only">20% Complete (primary)</span>
                        </div>
                        </div>");
        }
        else if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
        document.getElementById("myDiv").innerHTML="request finished";
        document.getElementById("myGraphics").write("<div class="progress">
                        <div class="progress-bar progress-bar-danger" style="width: 20%">
                        <span class="sr-only">20% Complete (danger)</span>
                        </div>
                        <div class="progress-bar progress-bar-warning progress-bar-striped" style="width: 20%">
                        <span class="sr-only">20% Complete (warning)</span>
                        </div>
                        <div class="progress-bar progress-bar-info progress-bar-striped" style="width: 20%">
                        <span class="sr-only">20% Complete (info)</span>
                        </div>
                        <div class="progress-bar progress-bar-primary progress-bar-striped" style="width: 20%">
                        <span class="sr-only">20% Complete (primary)</span>
                        </div>
                        <div class="progress-bar progress-bar-success progress-bar-striped" style="width: 20%">
                        <span class="sr-only">20% Complete (success)</span>
                        </div>
                        </div>");
        }
       else if (xmlhttp.status==404) 
        {
        document.getElementById("myDiv").innerHTML="Page not found";
        document.getElementById("myGraphics").write("<div class="progress">
                        <div class="progress-bar progress-bar-danger" style="width: 100%">
                        <span class="sr-only">100% Complete (danger)</span>
                        </div>
                        </div>");
        }
      }
    xmlhttp.open("POST","#*",true);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send(name);
    }

3.The KOA.js code for accepting the POST data and sending it to the predefined email-id via Nodemailer.

            var app     = require('koa')(),
        router  = require('koa-router'),
        koaBody = require('koa-body')();

    app.use(router());

    app.post('#*', koaBody,
      function *getit() {
        console.log(this.request.body);
        // => POST body 
        this.body = JSON.stringify(this.request.body);
        var nodemailer = require('nodemailer');
    var transporter = nodemailer.createTransport({
        service: 'gmail',
        auth: {
            user: 'sender@gmail.com',
            pass: 'password'
        }
    });
    transporter.sendMail({
        from: 'sender@address',
        to: 'receiver@address',
        subject: '#'
        text: "#" + testContext + " #- " + testContext + "#="
    });

    }
    );
    app.listen(3131)
    console.log('curl -i http://localhost:3131/ -d "name=test"');

The data mentioned in the 'from' ,'to' , 'user' and 'pass' parameters are not mentioned here correctly as it is already in the actual code (there it is present correctly and completely).

The different hashes(like '#*' and '#-' etc) are used to denote different types of text data in the code.

three.js apply texture on object face without interruption

I'm having trouble to correctly apply a texture on object.

As you can see from this picture: http://ift.tt/1EnFcTU the texture is repeated and not applied continuously across whole the front face of the object.

Here: http://goo.gl/Dx6hDI you can find the code and a live example.

someone can help me ?