qid
int64
2
74.7M
question
stringlengths
31
65.1k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
4
63.3k
response_k
stringlengths
4
60.5k
26,032,205
Below the code of my view (the javascript code is in the view, just temp just for testing). I'd like assign the ASP.NET MVC model (`@Model`) to the AngularJS scope (`$scope.person`) How can I do this ? Thanks, The view ``` @model MyApp.Person <script> var myApp = angular.module('myApp', []); myApp.controller('personController', ['$scope', '$http', function ($scope, $http) { $scope.person = ????? }]); </script> ``` **Update 1 :** I tried this code, in the JS file : ``` var myApp = angular.module('myApp', []); myApp.controller('personController', ['$scope', '$http', function ($scope, $http) { $scope.person = @Html.Raw(window.person); }]); ``` In the view file : ``` <script> @{ var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); } window.person = serializer.Serialize(Model); </script> ``` I get 2 errors : ``` ReferenceError: serializer is not defined (on windows) window.person = serializer.Serialize(Model); SyntaxError: illegal character (it's the @) $scope.person = @Html.Raw(window.person); ```
2014/09/25
[ "https://Stackoverflow.com/questions/26032205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/118584/" ]
``` <script> @{ var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); var json = serializer.Serialize(Model); } var myApp = angular.module('myApp', []); myApp.controller('personController', ['$scope', '$http', function ($scope, $http) { $scope.person = @Html.Raw(json); }]); </script> ```
I am not sure if this will work with Angular. You can use [**Json.Encode**](http://msdn.microsoft.com/en-us/library/system.web.helpers.json.encode%28v=vs.111%29.aspx) Method converts a data object to a string that is in the JavaScript Object Notation (JSON) format. ``` window.person = @Html.Raw(Json.Encode(Model)); //Store data in global variable. ``` In Your angular code use, ``` $scope.person = window.person ``` However, Best solution will be to create a service and fetch the person data using the service. *Complete Code* ``` @model MyApp.Person <script> window.person = @Html.Raw(Json.Encode(Model)); //Store data in global variable. var myApp = angular.module('myApp', []); myApp.controller('personController', ['$scope', '$http', function ($scope, $http) { $scope.person = window.person }]); </script> ```
26,032,205
Below the code of my view (the javascript code is in the view, just temp just for testing). I'd like assign the ASP.NET MVC model (`@Model`) to the AngularJS scope (`$scope.person`) How can I do this ? Thanks, The view ``` @model MyApp.Person <script> var myApp = angular.module('myApp', []); myApp.controller('personController', ['$scope', '$http', function ($scope, $http) { $scope.person = ????? }]); </script> ``` **Update 1 :** I tried this code, in the JS file : ``` var myApp = angular.module('myApp', []); myApp.controller('personController', ['$scope', '$http', function ($scope, $http) { $scope.person = @Html.Raw(window.person); }]); ``` In the view file : ``` <script> @{ var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); } window.person = serializer.Serialize(Model); </script> ``` I get 2 errors : ``` ReferenceError: serializer is not defined (on windows) window.person = serializer.Serialize(Model); SyntaxError: illegal character (it's the @) $scope.person = @Html.Raw(window.person); ```
2014/09/25
[ "https://Stackoverflow.com/questions/26032205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/118584/" ]
I am not sure if this will work with Angular. You can use [**Json.Encode**](http://msdn.microsoft.com/en-us/library/system.web.helpers.json.encode%28v=vs.111%29.aspx) Method converts a data object to a string that is in the JavaScript Object Notation (JSON) format. ``` window.person = @Html.Raw(Json.Encode(Model)); //Store data in global variable. ``` In Your angular code use, ``` $scope.person = window.person ``` However, Best solution will be to create a service and fetch the person data using the service. *Complete Code* ``` @model MyApp.Person <script> window.person = @Html.Raw(Json.Encode(Model)); //Store data in global variable. var myApp = angular.module('myApp', []); myApp.controller('personController', ['$scope', '$http', function ($scope, $http) { $scope.person = window.person }]); </script> ```
i had the same problem. this will work. in your view: ``` <script> myApp.value('person', @Html.Raw(Model)); </script> ``` and in your (angular) controller: ``` myApp.controller('personController', ['$scope', '$http', 'person' function ($scope, $http, person) { console.log(person); }]); ``` If you "inject" your json value on your controller, you are sorted.
26,032,205
Below the code of my view (the javascript code is in the view, just temp just for testing). I'd like assign the ASP.NET MVC model (`@Model`) to the AngularJS scope (`$scope.person`) How can I do this ? Thanks, The view ``` @model MyApp.Person <script> var myApp = angular.module('myApp', []); myApp.controller('personController', ['$scope', '$http', function ($scope, $http) { $scope.person = ????? }]); </script> ``` **Update 1 :** I tried this code, in the JS file : ``` var myApp = angular.module('myApp', []); myApp.controller('personController', ['$scope', '$http', function ($scope, $http) { $scope.person = @Html.Raw(window.person); }]); ``` In the view file : ``` <script> @{ var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); } window.person = serializer.Serialize(Model); </script> ``` I get 2 errors : ``` ReferenceError: serializer is not defined (on windows) window.person = serializer.Serialize(Model); SyntaxError: illegal character (it's the @) $scope.person = @Html.Raw(window.person); ```
2014/09/25
[ "https://Stackoverflow.com/questions/26032205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/118584/" ]
I am not sure if this will work with Angular. You can use [**Json.Encode**](http://msdn.microsoft.com/en-us/library/system.web.helpers.json.encode%28v=vs.111%29.aspx) Method converts a data object to a string that is in the JavaScript Object Notation (JSON) format. ``` window.person = @Html.Raw(Json.Encode(Model)); //Store data in global variable. ``` In Your angular code use, ``` $scope.person = window.person ``` However, Best solution will be to create a service and fetch the person data using the service. *Complete Code* ``` @model MyApp.Person <script> window.person = @Html.Raw(Json.Encode(Model)); //Store data in global variable. var myApp = angular.module('myApp', []); myApp.controller('personController', ['$scope', '$http', function ($scope, $http) { $scope.person = window.person }]); </script> ```
At first assign value in global java script variable then use it in your separate angular file ```js <script> var obj = '@Html.Raw(Model)'; </script> ``` now in your angular page ```js $scope.person = obj; ```
26,032,205
Below the code of my view (the javascript code is in the view, just temp just for testing). I'd like assign the ASP.NET MVC model (`@Model`) to the AngularJS scope (`$scope.person`) How can I do this ? Thanks, The view ``` @model MyApp.Person <script> var myApp = angular.module('myApp', []); myApp.controller('personController', ['$scope', '$http', function ($scope, $http) { $scope.person = ????? }]); </script> ``` **Update 1 :** I tried this code, in the JS file : ``` var myApp = angular.module('myApp', []); myApp.controller('personController', ['$scope', '$http', function ($scope, $http) { $scope.person = @Html.Raw(window.person); }]); ``` In the view file : ``` <script> @{ var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); } window.person = serializer.Serialize(Model); </script> ``` I get 2 errors : ``` ReferenceError: serializer is not defined (on windows) window.person = serializer.Serialize(Model); SyntaxError: illegal character (it's the @) $scope.person = @Html.Raw(window.person); ```
2014/09/25
[ "https://Stackoverflow.com/questions/26032205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/118584/" ]
``` <script> @{ var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); var json = serializer.Serialize(Model); } var myApp = angular.module('myApp', []); myApp.controller('personController', ['$scope', '$http', function ($scope, $http) { $scope.person = @Html.Raw(json); }]); </script> ```
i had the same problem. this will work. in your view: ``` <script> myApp.value('person', @Html.Raw(Model)); </script> ``` and in your (angular) controller: ``` myApp.controller('personController', ['$scope', '$http', 'person' function ($scope, $http, person) { console.log(person); }]); ``` If you "inject" your json value on your controller, you are sorted.
26,032,205
Below the code of my view (the javascript code is in the view, just temp just for testing). I'd like assign the ASP.NET MVC model (`@Model`) to the AngularJS scope (`$scope.person`) How can I do this ? Thanks, The view ``` @model MyApp.Person <script> var myApp = angular.module('myApp', []); myApp.controller('personController', ['$scope', '$http', function ($scope, $http) { $scope.person = ????? }]); </script> ``` **Update 1 :** I tried this code, in the JS file : ``` var myApp = angular.module('myApp', []); myApp.controller('personController', ['$scope', '$http', function ($scope, $http) { $scope.person = @Html.Raw(window.person); }]); ``` In the view file : ``` <script> @{ var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); } window.person = serializer.Serialize(Model); </script> ``` I get 2 errors : ``` ReferenceError: serializer is not defined (on windows) window.person = serializer.Serialize(Model); SyntaxError: illegal character (it's the @) $scope.person = @Html.Raw(window.person); ```
2014/09/25
[ "https://Stackoverflow.com/questions/26032205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/118584/" ]
``` <script> @{ var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); var json = serializer.Serialize(Model); } var myApp = angular.module('myApp', []); myApp.controller('personController', ['$scope', '$http', function ($scope, $http) { $scope.person = @Html.Raw(json); }]); </script> ```
At first assign value in global java script variable then use it in your separate angular file ```js <script> var obj = '@Html.Raw(Model)'; </script> ``` now in your angular page ```js $scope.person = obj; ```
8,702,567
Imagine we have a page with a form where users can create their own discussion forum by inserting some data. Inside each forum anyone will be able to post different threads and topics. **Scenario 1:** Use PHP to create a new HTML file every time a user creates his own forum. This would lead to hundreds maybe thousands of different html files. **Scenario 2:** We only have one html file in which contents change depending on the ID received (so it will display the contents for "discussion1", "discussion2" or any other discussion depending on the variable ID). This would mean having just one HTML file but a huge table in our SQL server. I have seen examples of both scenarios for very large websites. For example, Wikipedia uses Scenario 1 while I believe other more dynamic websites use Scenario 2. **What are the main pros & cons of each scenario?** I would love to know the pros & cons that matter most and also the ones related with: - SEO - Server response time & server load - Site maintenance - User experience (for bookmarks assume the ID is sent via the GET method)
2012/01/02
[ "https://Stackoverflow.com/questions/8702567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/949388/" ]
Scenario 2 is certainly the way to go, keeping pages dynamic allows for editing far less files and means everything will always be the same. With good MySQL tables and relationships the queries to the database shouldn't be that server heavy and your site will still perform a lot better than with hundreds of .html files. I don't think many, if any sites use scenario 1, they will just .htaccess to alter the url and make them look like .html pages.
I actually believe Wikipedia uses a database as well. They are just parsing the URL to get the variables instead of using a query string in the URL. And I would have to believe the database would be the way to go. It's still going to be smaller because you'll have a lot less code. If you use HTML, you will be reproducing a lot of code that you just don't need to reproduce. SEO-wise, as long as you do something like Wikipedia does and parse your URL with maybe an .htaccess file, google will be none-the-wiser. It just doesn't really matter if your content is hard coded or not as long as you set it up right.
8,702,567
Imagine we have a page with a form where users can create their own discussion forum by inserting some data. Inside each forum anyone will be able to post different threads and topics. **Scenario 1:** Use PHP to create a new HTML file every time a user creates his own forum. This would lead to hundreds maybe thousands of different html files. **Scenario 2:** We only have one html file in which contents change depending on the ID received (so it will display the contents for "discussion1", "discussion2" or any other discussion depending on the variable ID). This would mean having just one HTML file but a huge table in our SQL server. I have seen examples of both scenarios for very large websites. For example, Wikipedia uses Scenario 1 while I believe other more dynamic websites use Scenario 2. **What are the main pros & cons of each scenario?** I would love to know the pros & cons that matter most and also the ones related with: - SEO - Server response time & server load - Site maintenance - User experience (for bookmarks assume the ID is sent via the GET method)
2012/01/02
[ "https://Stackoverflow.com/questions/8702567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/949388/" ]
Scenario 2 is certainly the way to go, keeping pages dynamic allows for editing far less files and means everything will always be the same. With good MySQL tables and relationships the queries to the database shouldn't be that server heavy and your site will still perform a lot better than with hundreds of .html files. I don't think many, if any sites use scenario 1, they will just .htaccess to alter the url and make them look like .html pages.
The best case scenario would be a combination of the two, in this manner: Use one template (scenario 2) to generate these pages on the fly, this way you can have millions of forums, with only one html. With this, you should add a caching feature, which caches (creates a temporary html file) all the forums, so that users will not need to access the database every single page visit, but rather get the cached HTML from the server.
18,222,853
I have a section on my site I would like to show some alerts or news on. I want to show the first news for x seconds, then move on to the second news for x seconds and not show the first news anymore, and then unto the third and not show the second .. etc. I am just starting with javascript and the code I was making worked only for one run and then stopped I would like this to go on infinitely or a very high number so that the person can see the news alerts while they are on the page. One after the other. I appreciate any help I can get. Please show me a thorough code because I'm a bit noobish when it comes to this since I started about 2 weeks ago. Thanks! Html: ``` <div id="news1">Here are some news! 1111</div> <div id="news2">Here are some news! 2222</div> <div id="news3">Here are some news! 3333</div> ``` CSS: ``` #news1, #news2, #news3{ visibility:hidden; } ``` Javascript: ``` function showIt() { document.getElementById("news1").style.visibility = "visible"; document.getElementById("news3").style.visibility = "hidden"; document.getElementById("news2").style.visibility = "hidden"; } setInterval("showIt()", 3000); function showIt2(){ document.getElementById("news2").style.visibility = "visible"; document.getElementById("news1").style.visibility = "hidden"; document.getElementById("news3").style.visibility = "hidden"; } setInterval("showIt2()", 6000) function showIt2(){ document.getElementById("news2").style.visibility = "visible"; document.getElementById("news1").style.visibility = "hidden"; document.getElementById("news3").style.visibility = "hidden"; setInterval("showIt3()", 3000); } ```
2013/08/14
[ "https://Stackoverflow.com/questions/18222853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2680861/" ]
Without changing your CSS/HTML, the code below will handle any number of elements, all you have to do is send their IDs as parameter: ``` function showAlternate(ids, interval, currentVisible) { if (currentVisible === undefined) currentVisible = ids.length-1; // last one document.getElementById(ids[currentVisible]).style.visibility = "hidden"; var idToShow = ++currentVisible % ids.length; document.getElementById(ids[idToShow]).style.visibility = "visible"; setTimeout(function() { showAlternate(ids, interval, idToShow); }, interval); } // example usage: showAlternate(["news1", "news2", "news3", "news4", "news5"], 3000); ``` **[Demo jsfiddle here](http://jsfiddle.net/acdcjunior/JFBhC/7/)**:
This Pure-JS example will work with any number of divs with your current pattern, so you can have id "news4", "news5", "news6", etc. Also, you can change how frequently the news changes that is shown by changing the INTERVAL variable, in this example the news will change every 1 second. **JSFIDDLE -- <http://jsfiddle.net/g9YRb/3/>** **JS** ``` var INTERVAL = 1000; var myprefix = "news"; var maxnewsnumber = document.getElementsByTagName("div").length; var myindex = 0; function alternatenews(idx) { idx++; myindex = idx; function retrigger() { setTimeout(function() { alternatenews(myindex); },INTERVAL); } if(myindex > maxnewsnumber) { document.getElementById(myprefix + parseInt(myindex-1)).style.visibility = "hidden"; myindex = 0; alternatenews(myindex); } else if(myindex == 1) { document.getElementById(myprefix + myindex).style.visibility = "visible"; retrigger(); } else { document.getElementById(myprefix + parseInt(myindex-1) ).style.visibility = "hidden"; document.getElementById(myprefix + myindex).style.visibility = "visible"; retrigger(); } } alternatenews(myindex); ``` **HTML** ``` <div id="news1">Here are some news! 1111</div> <div id="news2">Here are some news! 2222</div> <div id="news3">Here are some news! 3333</div> <div id="news4">Here are some news! 4444</div> <div id="news5">Here are some news! 5555</div> ``` **CSS** ``` div { visibility: hidden } ```
18,222,853
I have a section on my site I would like to show some alerts or news on. I want to show the first news for x seconds, then move on to the second news for x seconds and not show the first news anymore, and then unto the third and not show the second .. etc. I am just starting with javascript and the code I was making worked only for one run and then stopped I would like this to go on infinitely or a very high number so that the person can see the news alerts while they are on the page. One after the other. I appreciate any help I can get. Please show me a thorough code because I'm a bit noobish when it comes to this since I started about 2 weeks ago. Thanks! Html: ``` <div id="news1">Here are some news! 1111</div> <div id="news2">Here are some news! 2222</div> <div id="news3">Here are some news! 3333</div> ``` CSS: ``` #news1, #news2, #news3{ visibility:hidden; } ``` Javascript: ``` function showIt() { document.getElementById("news1").style.visibility = "visible"; document.getElementById("news3").style.visibility = "hidden"; document.getElementById("news2").style.visibility = "hidden"; } setInterval("showIt()", 3000); function showIt2(){ document.getElementById("news2").style.visibility = "visible"; document.getElementById("news1").style.visibility = "hidden"; document.getElementById("news3").style.visibility = "hidden"; } setInterval("showIt2()", 6000) function showIt2(){ document.getElementById("news2").style.visibility = "visible"; document.getElementById("news1").style.visibility = "hidden"; document.getElementById("news3").style.visibility = "hidden"; setInterval("showIt3()", 3000); } ```
2013/08/14
[ "https://Stackoverflow.com/questions/18222853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2680861/" ]
First understand what how to use **setInterval()**. You specify 2 paramaters as **function** to call and **delay** which specify how long time to wait between two calls. Then in your example: * setInterval("showIt()", 3000); // will call showIt() each 3000 ms * setInterval("showIt2()", 6000); // will call showIt2() each 6000 ms * setInterval("showIt3()", 3000); // will call showIt3() each 3000 ms (after waiting 6000ms cause in showIt2()) put that on timeline : * 0 ms: nothing * 3000 ms: showIt() is called * 6000 ms: showIt() is called and showIt2() is called * 9000 ms: showIt() is called and showIt3() is called * 12000 ms: showIt() is called, showIt2() is called and showIt3() is called * 15000 ms: showIt() is called and *showIt3() is called twice* * ... You should try to work with only one setInterval() and variable which select next function should be called. ``` var myIndex = 0; setInterval(updateFunction, 3000); function updateFunction(){ switch(myIndex) { case 0: showIt(); break; case 1: showIt2(); break; case 2: showIt3(); break; } ++ myIndex; if (myIndex > 2) myIndex = 0; } ``` EDIT add to: <http://jsfiddle.net/fA4cu/>
This Pure-JS example will work with any number of divs with your current pattern, so you can have id "news4", "news5", "news6", etc. Also, you can change how frequently the news changes that is shown by changing the INTERVAL variable, in this example the news will change every 1 second. **JSFIDDLE -- <http://jsfiddle.net/g9YRb/3/>** **JS** ``` var INTERVAL = 1000; var myprefix = "news"; var maxnewsnumber = document.getElementsByTagName("div").length; var myindex = 0; function alternatenews(idx) { idx++; myindex = idx; function retrigger() { setTimeout(function() { alternatenews(myindex); },INTERVAL); } if(myindex > maxnewsnumber) { document.getElementById(myprefix + parseInt(myindex-1)).style.visibility = "hidden"; myindex = 0; alternatenews(myindex); } else if(myindex == 1) { document.getElementById(myprefix + myindex).style.visibility = "visible"; retrigger(); } else { document.getElementById(myprefix + parseInt(myindex-1) ).style.visibility = "hidden"; document.getElementById(myprefix + myindex).style.visibility = "visible"; retrigger(); } } alternatenews(myindex); ``` **HTML** ``` <div id="news1">Here are some news! 1111</div> <div id="news2">Here are some news! 2222</div> <div id="news3">Here are some news! 3333</div> <div id="news4">Here are some news! 4444</div> <div id="news5">Here are some news! 5555</div> ``` **CSS** ``` div { visibility: hidden } ```
18,222,853
I have a section on my site I would like to show some alerts or news on. I want to show the first news for x seconds, then move on to the second news for x seconds and not show the first news anymore, and then unto the third and not show the second .. etc. I am just starting with javascript and the code I was making worked only for one run and then stopped I would like this to go on infinitely or a very high number so that the person can see the news alerts while they are on the page. One after the other. I appreciate any help I can get. Please show me a thorough code because I'm a bit noobish when it comes to this since I started about 2 weeks ago. Thanks! Html: ``` <div id="news1">Here are some news! 1111</div> <div id="news2">Here are some news! 2222</div> <div id="news3">Here are some news! 3333</div> ``` CSS: ``` #news1, #news2, #news3{ visibility:hidden; } ``` Javascript: ``` function showIt() { document.getElementById("news1").style.visibility = "visible"; document.getElementById("news3").style.visibility = "hidden"; document.getElementById("news2").style.visibility = "hidden"; } setInterval("showIt()", 3000); function showIt2(){ document.getElementById("news2").style.visibility = "visible"; document.getElementById("news1").style.visibility = "hidden"; document.getElementById("news3").style.visibility = "hidden"; } setInterval("showIt2()", 6000) function showIt2(){ document.getElementById("news2").style.visibility = "visible"; document.getElementById("news1").style.visibility = "hidden"; document.getElementById("news3").style.visibility = "hidden"; setInterval("showIt3()", 3000); } ```
2013/08/14
[ "https://Stackoverflow.com/questions/18222853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2680861/" ]
I have changed logic of the javascript code like below, ``` var newsList = ["news1","news2","news3"]; var currIndex = newsList.length-1; var timeoutObj; function showNext() { document.getElementById(newsList[currIndex]).style.visibility = "hidden"; if(currIndex >= newsList.length-1) currIndex = 0; else currIndex += 1; document.getElementById(newsList[currIndex]).style.visibility = "visible"; timeoutObj = setTimeout(showNext,3000); } showNext(); ``` Check if it helps you.. Here's the jsfiddle <http://jsfiddle.net/m63Up/>
This Pure-JS example will work with any number of divs with your current pattern, so you can have id "news4", "news5", "news6", etc. Also, you can change how frequently the news changes that is shown by changing the INTERVAL variable, in this example the news will change every 1 second. **JSFIDDLE -- <http://jsfiddle.net/g9YRb/3/>** **JS** ``` var INTERVAL = 1000; var myprefix = "news"; var maxnewsnumber = document.getElementsByTagName("div").length; var myindex = 0; function alternatenews(idx) { idx++; myindex = idx; function retrigger() { setTimeout(function() { alternatenews(myindex); },INTERVAL); } if(myindex > maxnewsnumber) { document.getElementById(myprefix + parseInt(myindex-1)).style.visibility = "hidden"; myindex = 0; alternatenews(myindex); } else if(myindex == 1) { document.getElementById(myprefix + myindex).style.visibility = "visible"; retrigger(); } else { document.getElementById(myprefix + parseInt(myindex-1) ).style.visibility = "hidden"; document.getElementById(myprefix + myindex).style.visibility = "visible"; retrigger(); } } alternatenews(myindex); ``` **HTML** ``` <div id="news1">Here are some news! 1111</div> <div id="news2">Here are some news! 2222</div> <div id="news3">Here are some news! 3333</div> <div id="news4">Here are some news! 4444</div> <div id="news5">Here are some news! 5555</div> ``` **CSS** ``` div { visibility: hidden } ```
51,579,410
I am using AWS CLI for scheduling the project build. I have successfully executed Test Cases using the AWS CLI using Device Pool(All Android devices) Now I want only one device in my device pool, So I have tried to get the Device ARN. To get ARN for All Devices under Project using: ``` aws devicefarm list-devices --arn arn:aws:devicefarm:us-west-2:871290565691:project:8edf9575-3290-45f6-90d0-cb36edc0c2c0 ``` I have tried below command in order to create Device pool for only one device(Google Pixel2 8.1): ``` aws devicefarm create-device-pool --project-arn arn:aws:devicefarm:us-west-2:871290565691:project:8edf9575-3290-45f6-90d0-cb36edc0c2c0 --name pixel2_81 --rules '[{"attribute": "INSTANCE_ARN", "operator": "IN", "value": "[arn:aws:devicefarm:us-west-2::device:4B2B87829E99484DBCD853D82A883BF5]"}]' aws devicefarm create-device-pool --project-arn arn:aws:devicefarm:us-west-2:871290565691:project:8edf9575-3290-45f6-90d0-cb36edc0c2c0 --name pixel2_81 --rules '[{"attribute": "INSTANCE_ARN", "operator": "EQUALS", "value": "arn:aws:devicefarm:us-west-2::device:4B2B87829E99484DBCD853D82A883BF5"}]' aws devicefarm create-device-pool --project-arn arn:aws:devicefarm:us-west-2:871290565691:project:8edf9575-3290-45f6-90d0-cb36edc0c2c0 --name pixel2_81 --rules '[{"attribute": "INSTANCE_ARN", "operator": "EQUALS", "value": "\"arn:aws:devicefarm:us-west-2::device:4B2B87829E99484DBCD853D82A883BF5\""}]' aws devicefarm create-device-pool --project-arn arn:aws:devicefarm:us-west-2:871290565691:project:8edf9575-3290-45f6-90d0-cb36edc0c2c0 --name pixel2_81 --rules '[{"attribute": "ARN", "operator": "IN", "value": "[arn:aws:devicefarm:us-west-2::device:4B2B87829E99484DBCD853D82A883BF5]"}]' aws devicefarm create-device-pool --project-arn arn:aws:devicefarm:us-west-2:871290565691:project:8edf9575-3290-45f6-90d0-cb36edc0c2c0 --name pixel2_81 --rules '[{"attribute": "ARN", "operator": "EQUALS", "value": "arn:aws:devicefarm:us-west-2::device:4B2B87829E99484DBCD853D82A883BF5"}]' aws devicefarm create-device-pool --project-arn arn:aws:devicefarm:us-west-2:871290565691:project:8edf9575-3290-45f6-90d0-cb36edc0c2c0 --name pixel2_81 --rules '[{"attribute": "ARN", "operator": "EQUALS", "value": "\"arn:aws:devicefarm:us-west-2::device:4B2B87829E99484DBCD853D82A883BF5\""}]' ``` But all of them giving same error: > > An error occurred (ArgumentException) when calling the CreateDevicePool operation: Invalid request, please check the arn and the device pool rule > > > I think I am missing small thing here. Really appreciate the help on this or Please provide me an alternate way to create the Device Pool for Single Google Pixel2 8.1 device. Thank you.
2018/07/29
[ "https://Stackoverflow.com/questions/51579410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5944123/" ]
Here is an example that I had in my notes but it's not for the Google pixel. However, its arn can be found using the [list devices](https://docs.aws.amazon.com/devicefarm/latest/APIReference/API_ListDevices.html) API **Single device** `aws devicefarm create-device-pool --project-arn arn:aws:devicefarm:us-west-2:111122223333:project:fb906e56-a39f-4976-9583-8c520bb534cb --name testOfCli --rules '[{"attribute": "ARN","operator":"IN","value":"[\"arn:aws:devicefarm:us-west-2::device:B494940EA8AA4DA4B4DC45CE4E47D760\"]"}]' --region us-west-2` Hth -James
Provide a more detailed answer based on James. `aws devicefarm create-device-pool --project-arn arn:aws:devicefarm:us-west-2: 111122223333:project:bb8c132f-9c75-4ac2-98fc-59c5e71adbbd --name pixel2_81 --rules '[{"attribute": "ARN","operator":"IN","value":"[\"arn:aws:devicefarm:us-west-2::device:4B2B87829E99484DBCD853D82A883BF5\"]"}]' --region us-west-2`
772,509
I've used the commands from [this gist](https://gist.github.com/jacobmarshall/77d6b3ba7c6c50de22eb) (duplicated below) to create a Docker Swarm using Consul. ``` docker-machine create \ --driver=digitalocean \ --digitalocean-access-token=$DO_TOKEN \ --digitalocean-size=512mb \ --digitalocean-region=nyc3 \ --digitalocean-private-networking=true \ --digitalocean-image=ubuntu-15-04-x64 \ docker-swarm-kv-store docker $(docker-machine config docker-swarm-kv-store) run -d \ --net=host progrium/consul --server -bootstrap-expect 1 kvip=$(docker-machine ip docker-swarm-kv-store) docker-machine create \ --driver=digitalocean \ --digitalocean-access-token=$DO_TOKEN \ --digitalocean-size=2gb \ --digitalocean-region=nyc3 \ --digitalocean-private-networking=true \ --digitalocean-image=ubuntu-15-04-x64 \ --swarm \ --swarm-master \ --swarm-discovery consul://${kvip}:8500 \ --engine-opt "cluster-store consul://${kvip}:8500" \ --engine-opt "cluster-advertise eth1:2376" \ docker-swarm-master docker-machine create \ --driver=digitalocean \ --digitalocean-access-token=$DO_TOKEN \ --digitalocean-size=2gb \ --digitalocean-region=nyc3 \ --digitalocean-private-networking=true \ --digitalocean-image=ubuntu-15-04-x64 \ --swarm \ --swarm-discovery consul://${kvip}:8500 \ --engine-opt "cluster-store consul://${kvip}:8500" \ --engine-opt "cluster-advertise eth1:2376" \ docker-swarm-agent-1 eval $(docker-machine env --swarm docker-swarm-master) docker info ``` Does Docker Machine ensure that the swarm is secure (perhaps by managing SSL certs under-the-covers), or can anyone join my Consul cluster by pointing at `${kvip}:8500`?
2016/04/24
[ "https://serverfault.com/questions/772509", "https://serverfault.com", "https://serverfault.com/users/167024/" ]
You have an incorrect setting in your `php.ini` file: The `session.cache_limiter` value is set to `nocache` in the default `php.ini` file and needs to be changed. `session.cache_limiter` should be defined and set, either to `public` which inserts public cache-control headers, or to `''` (blank), which doesn't insert any cache-control headers, and the headers sent by your application will then be used, if any.
I've found that with Wordpress (some themes) and other PHP applications sometimes it's near to impossible to get the headers set correctly using PHP. My solution is that I just ignore the headers the application sets and override them with what I want in Nginx. I find this much simpler, much faster, and much more reliable. If you can work out how to do it from your application and PHP, great, but this way gives you lots of control and it's easy. Building nginx with the required module is easier than you might think, it can probably done in 30 minutes based on a guide I link to below. I have a guide how to set up Nginx and Cloudflare. * [Nginx](https://www.photographerstechsupport.com/tutorials/hosting-wordpress-on-aws-tutorial-part-4-wordpress-website-optimization/#ccheaders) * [CloudFlare](https://www.photographerstechsupport.com/tutorials/hosting-wordpress-on-aws-tutorial-part-6-setting-up-cloudflare-caching-security/) * [Downloadable config files.](https://www.photographerstechsupport.com/tutorials/hosting-wordpress-on-aws-tutorial-part-2-setting-up-aws-for-wordpress-with-rds-nginx-hhvm-php-ssmtp/#nginx) Short version of caching header: * You want cache-control * You don't want pragma For images use something like this in your location - you need headers-more module compiled into nginx. See part 1 of my tutorial for that. ``` add_header Cache-Control "public, max-age=691200, s-maxage=691200"; more_clear_headers Server; more_clear_headers "Pragma"; more_clear_headers "Expires"; ``` For pages I don't cache on CloudFlare, but I do use nginx fast\_cgi page cache, which is in my tutorial. For CloudFlare you may need to use page rules if you need anything tricky, but in general the default settings will cache images but not pages.
772,509
I've used the commands from [this gist](https://gist.github.com/jacobmarshall/77d6b3ba7c6c50de22eb) (duplicated below) to create a Docker Swarm using Consul. ``` docker-machine create \ --driver=digitalocean \ --digitalocean-access-token=$DO_TOKEN \ --digitalocean-size=512mb \ --digitalocean-region=nyc3 \ --digitalocean-private-networking=true \ --digitalocean-image=ubuntu-15-04-x64 \ docker-swarm-kv-store docker $(docker-machine config docker-swarm-kv-store) run -d \ --net=host progrium/consul --server -bootstrap-expect 1 kvip=$(docker-machine ip docker-swarm-kv-store) docker-machine create \ --driver=digitalocean \ --digitalocean-access-token=$DO_TOKEN \ --digitalocean-size=2gb \ --digitalocean-region=nyc3 \ --digitalocean-private-networking=true \ --digitalocean-image=ubuntu-15-04-x64 \ --swarm \ --swarm-master \ --swarm-discovery consul://${kvip}:8500 \ --engine-opt "cluster-store consul://${kvip}:8500" \ --engine-opt "cluster-advertise eth1:2376" \ docker-swarm-master docker-machine create \ --driver=digitalocean \ --digitalocean-access-token=$DO_TOKEN \ --digitalocean-size=2gb \ --digitalocean-region=nyc3 \ --digitalocean-private-networking=true \ --digitalocean-image=ubuntu-15-04-x64 \ --swarm \ --swarm-discovery consul://${kvip}:8500 \ --engine-opt "cluster-store consul://${kvip}:8500" \ --engine-opt "cluster-advertise eth1:2376" \ docker-swarm-agent-1 eval $(docker-machine env --swarm docker-swarm-master) docker info ``` Does Docker Machine ensure that the swarm is secure (perhaps by managing SSL certs under-the-covers), or can anyone join my Consul cluster by pointing at `${kvip}:8500`?
2016/04/24
[ "https://serverfault.com/questions/772509", "https://serverfault.com", "https://serverfault.com/users/167024/" ]
You have an incorrect setting in your `php.ini` file: The `session.cache_limiter` value is set to `nocache` in the default `php.ini` file and needs to be changed. `session.cache_limiter` should be defined and set, either to `public` which inserts public cache-control headers, or to `''` (blank), which doesn't insert any cache-control headers, and the headers sent by your application will then be used, if any.
Most cloud servers using PHP and Nginx these days are going to be using PHP-FPM (or should be)... for cleaner configuration I recommend keeping `session.cache_limiter = nocache` in your `php.ini` and then overwriting HTTP headers using Nginx instead, it's more reliable. For [SlickStack](https://github.com/littlebizzy/slickstack/blob/master/modules/nginx/sites/production.txt), my open source LEMP script, we go even farther by universally disabling certain cache headers in the `nginx.conf` file like this: ``` more_clear_headers "Pragma Expires"; ``` ...this ensures random WordPress plugins (etc) can't mess with our caching headers. And then in the Nginx server block, we enable only the `Cache-Control` header for static assets to ensure CDNs like Cloudflare will properly cache them at the edge: ``` location ~* \.(atom|bmp|bz2|css|doc|docx|eot|gif|gz|ico|jpeg|jpg|js|mid|midi|mp4|ogg|ogv|otf|png|ppt|rar|rss|rtf|svg|svgz|tar|tgz|ttc|ttf|wav|webp|woff|woff2|xls|zip)$ { add_header Cache-Control "public, max-age=691200"; } ``` This enables a TTL of around 1 week... but in Cloudflare, you can make this even longer by visiting the Caching tab and setting the "Browser Cache TTL" setting to something like 1 month. (For extra surety, you can also create a [Page Rule in Cloudflare](https://serverfault.com/a/1109549/144798) that forces an Edge Cache TTL of e.g. 1 month as well for any requests to your `/wp-content/*` directory where all your static assets should be loading from.) To lock things down even more, you can disable the `Cache-Control` header in the PHP routing server block to ensure pages don't get cached in the browser: ``` location ~ \.php$ { more_clear_headers "Cache-Control"; ... ``` If you have clients who love to mess with settings, this approach can be a life-saver.
772,509
I've used the commands from [this gist](https://gist.github.com/jacobmarshall/77d6b3ba7c6c50de22eb) (duplicated below) to create a Docker Swarm using Consul. ``` docker-machine create \ --driver=digitalocean \ --digitalocean-access-token=$DO_TOKEN \ --digitalocean-size=512mb \ --digitalocean-region=nyc3 \ --digitalocean-private-networking=true \ --digitalocean-image=ubuntu-15-04-x64 \ docker-swarm-kv-store docker $(docker-machine config docker-swarm-kv-store) run -d \ --net=host progrium/consul --server -bootstrap-expect 1 kvip=$(docker-machine ip docker-swarm-kv-store) docker-machine create \ --driver=digitalocean \ --digitalocean-access-token=$DO_TOKEN \ --digitalocean-size=2gb \ --digitalocean-region=nyc3 \ --digitalocean-private-networking=true \ --digitalocean-image=ubuntu-15-04-x64 \ --swarm \ --swarm-master \ --swarm-discovery consul://${kvip}:8500 \ --engine-opt "cluster-store consul://${kvip}:8500" \ --engine-opt "cluster-advertise eth1:2376" \ docker-swarm-master docker-machine create \ --driver=digitalocean \ --digitalocean-access-token=$DO_TOKEN \ --digitalocean-size=2gb \ --digitalocean-region=nyc3 \ --digitalocean-private-networking=true \ --digitalocean-image=ubuntu-15-04-x64 \ --swarm \ --swarm-discovery consul://${kvip}:8500 \ --engine-opt "cluster-store consul://${kvip}:8500" \ --engine-opt "cluster-advertise eth1:2376" \ docker-swarm-agent-1 eval $(docker-machine env --swarm docker-swarm-master) docker info ``` Does Docker Machine ensure that the swarm is secure (perhaps by managing SSL certs under-the-covers), or can anyone join my Consul cluster by pointing at `${kvip}:8500`?
2016/04/24
[ "https://serverfault.com/questions/772509", "https://serverfault.com", "https://serverfault.com/users/167024/" ]
I've found that with Wordpress (some themes) and other PHP applications sometimes it's near to impossible to get the headers set correctly using PHP. My solution is that I just ignore the headers the application sets and override them with what I want in Nginx. I find this much simpler, much faster, and much more reliable. If you can work out how to do it from your application and PHP, great, but this way gives you lots of control and it's easy. Building nginx with the required module is easier than you might think, it can probably done in 30 minutes based on a guide I link to below. I have a guide how to set up Nginx and Cloudflare. * [Nginx](https://www.photographerstechsupport.com/tutorials/hosting-wordpress-on-aws-tutorial-part-4-wordpress-website-optimization/#ccheaders) * [CloudFlare](https://www.photographerstechsupport.com/tutorials/hosting-wordpress-on-aws-tutorial-part-6-setting-up-cloudflare-caching-security/) * [Downloadable config files.](https://www.photographerstechsupport.com/tutorials/hosting-wordpress-on-aws-tutorial-part-2-setting-up-aws-for-wordpress-with-rds-nginx-hhvm-php-ssmtp/#nginx) Short version of caching header: * You want cache-control * You don't want pragma For images use something like this in your location - you need headers-more module compiled into nginx. See part 1 of my tutorial for that. ``` add_header Cache-Control "public, max-age=691200, s-maxage=691200"; more_clear_headers Server; more_clear_headers "Pragma"; more_clear_headers "Expires"; ``` For pages I don't cache on CloudFlare, but I do use nginx fast\_cgi page cache, which is in my tutorial. For CloudFlare you may need to use page rules if you need anything tricky, but in general the default settings will cache images but not pages.
Most cloud servers using PHP and Nginx these days are going to be using PHP-FPM (or should be)... for cleaner configuration I recommend keeping `session.cache_limiter = nocache` in your `php.ini` and then overwriting HTTP headers using Nginx instead, it's more reliable. For [SlickStack](https://github.com/littlebizzy/slickstack/blob/master/modules/nginx/sites/production.txt), my open source LEMP script, we go even farther by universally disabling certain cache headers in the `nginx.conf` file like this: ``` more_clear_headers "Pragma Expires"; ``` ...this ensures random WordPress plugins (etc) can't mess with our caching headers. And then in the Nginx server block, we enable only the `Cache-Control` header for static assets to ensure CDNs like Cloudflare will properly cache them at the edge: ``` location ~* \.(atom|bmp|bz2|css|doc|docx|eot|gif|gz|ico|jpeg|jpg|js|mid|midi|mp4|ogg|ogv|otf|png|ppt|rar|rss|rtf|svg|svgz|tar|tgz|ttc|ttf|wav|webp|woff|woff2|xls|zip)$ { add_header Cache-Control "public, max-age=691200"; } ``` This enables a TTL of around 1 week... but in Cloudflare, you can make this even longer by visiting the Caching tab and setting the "Browser Cache TTL" setting to something like 1 month. (For extra surety, you can also create a [Page Rule in Cloudflare](https://serverfault.com/a/1109549/144798) that forces an Edge Cache TTL of e.g. 1 month as well for any requests to your `/wp-content/*` directory where all your static assets should be loading from.) To lock things down even more, you can disable the `Cache-Control` header in the PHP routing server block to ensure pages don't get cached in the browser: ``` location ~ \.php$ { more_clear_headers "Cache-Control"; ... ``` If you have clients who love to mess with settings, this approach can be a life-saver.
70,398,031
I have a simple component here where I set a state variable called `input` to the value of an array of numbers. Then, within `useEffect` I call a function that randomizes the initial state array, and puts the results in a new state variable called `output`. I need my input array to stay in the same order. However, it is being mutated when I call the `shuffleArray` function. I thought there was no way to alter the value held by a variable passed as a parameter, which would be possible if JavaScript supported passing by reference. ```js const App = () => { const [input, setInput] = React.useState([90, 32, 28, 8, 21, 24, 64, 92, 45, 98, 22, 21, 6, 3, 27, 18, 11, 56, 16, 42, 36, 2, 60, 38, 24, 8, 16, 76, 62, 14, 84, 32, 24, 18, 8, 5, 25, 68, 65, 26, 22, 2, 52, 84, 30, 8, 2, 90, 5, 34, 56, 16, 42, 36]); const [output, setOutput] = React.useState([]); const shuffleArray = (array) => { for (let i = array.length - 1; i > 0; i--) { let j = Math.floor(Math.random() * (i + 1)); let temp = array[i]; array[i] = array[j]; array[j] = temp; } return array; } React.useEffect(() => { setOutput(shuffleArray(input)); }, []) return ( <div> [ { input.length > 0 ? input.map((n, i) => ( <span key={i}> { (i? ", " : "") + n } </span> )) : "No array..." } ] </div> ); }; ReactDOM.render(<App />, document.getElementById("root")); ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script> <div id="root"></div> ```
2021/12/17
[ "https://Stackoverflow.com/questions/70398031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9040866/" ]
Simple math tells us that this is not possible. The number of unique alphanumeric strings of length 4 (case-insensitive) is 36^4 = 1,679,616 while the number of non-negative unique floating point numbers with at most 3 fractional digits and less than 100 is 10^5 = 100,000. If the string were restricted to hexadecimal digits, there would only be 16^4 = 65,536 possibilities in which case a unique encoding would be possible. Slightly off-topic: when a mapping is needed into a domain which is too small to accommodate the result of a unique mapping, a [hash function](https://en.wikipedia.org/wiki/Hash_function) is the "standard tool", but collisions must be handled.
Your encoding is somewhat confusing, but here is a simple solution: * use 2 digits for the integral part * use 2 digits for fractional parts `00` to `99` * use a combination of 1 letter and 1 letter or digit for fractional parts `100` to `999`. There are 26\*36 = 936 such combinations, enough to cover the 900 possibilities. * all values from `00.00` to `99.999` can be encoded. * some 4 letter and digit combinations are not used. * the encoding is not unique. eg: `53A0` is `53.100`, the same number as `53.10` encoded as `5310`. Here is an implementation: ``` #include <stdib.h> double fdecode(const char *s) { char a[7]; a[0] = s[0]; a[1] = s[1]; a[2] = '.'; if (s[2] >= '0' && s[2] <= '9') { a[3] = s[3]; a[4] = s[4]; a[5] = '\0'; } else { // assuming uppercase letters int n = 100 + (s[3] - 'A') * 36; if (s[4] >= '0' && s[4] <= '9') { n += s[4] - '0'; } else { n += 10 + (s[4] - 'A') % 26; } snprintf(&a[3], 4, "%d", n); } return strtod(a, NULL); } int fencode(char *s, double d) { char a[7]; if (d >= 0 && snprintf(a, 7, "%06.3f", d) == 6) { s[0] = a[0]; s[1] = a[1]; if (a[5] == '0') { s[2] = a[3]; s[3] = a[4]; } else { int n = atoi(a + 3); s[2] = 'A' + (n / 36); n %= 36; if (n < 10) { s[3] = '0' + n; } else { s[3] = 'A' + n - 10; } } s[4] = '\0'; return 4; } else { s[0] = '\0'; return -1; } } ```
36,832,246
I understand the basics of sending a message via the Mailgun API using Python and requests from my site and all works fine. I would like to attach data from an HTML form using request.forms.get(''), but can't figure out the syntax to make it work. The link below is exactly what I need to do, except in Python instead of PHP. <http://www.formget.com/mailgun-send-email/> How can I send the following form data for example through via Mailgun? **HTML FORM (Parts of it to get the point across)** ``` <form action="/send" method="post"> <input name="name" placeholder="Name"> ... <button> ... ``` **ROUTE (Parts of it to get the point across)** ``` @route('/send', method='POST') def send_simple_message(): variable_I_need_to_send = request.forms.get('firstname') ... data={...", "to": "MyName <myname@gmail.com>", "subject": "Website Info Request", "text": "Testing some Mailgun awesomness!", "html": **variable_I_need_to_send**}) return ''' ``` Thank you
2016/04/25
[ "https://Stackoverflow.com/questions/36832246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4182445/" ]
Here's a scheme for doing request/response over socket.io. You could do this over plain webSocket, but you'd have to build a little more of the infrastructure yourself. This same library can be used in client and server: ``` function initRequestResponseSocket(socket, requestHandler) { var cntr = 0; var openResponses = {}; // send a request socket.sendRequestResponse = function(data, fn) { // put this data in a wrapper object that contains the request id // save the callback function for this id var id = cntr++; openResponses[id] = fn; socket.emit('requestMsg', {id: id, data: data}); } // process a response message that comes back from a request socket.on('responseMsg', function(wrapper) { var id = wrapper.id, fn; if (typeof id === "number" && typeof openResponses[id] === "function") { fn = openResponses[id]; delete openResponses[id]; fn(wrapper.data); } }); // process a requestMsg socket.on('requestMsg', function(wrapper) { if (requestHandler && wrapper.id) { requestHandler(wrapper.data, function(responseToSend) { socket.emit('responseMsg', {id: wrapper.id, data; responseToSend}); }); } }); } ``` This works by wrapping every message sent in a wrapper object that contains a unique id value. Then, when the other end sends it's response, it includes that same id value. That id value can then be matched up with a particular callback response handler for that specific message. It works both ways from client to server or server to client. You use this by calling `initRequestResponseSocket(socket, requestHandler)` once on a socket.io socket connection on each end. If you wish to receive requests, then you pass a requestHandler function which gets called each time there is a request. If you are only sending requests and receiving responses, then you don't have to pass in a requestHandler on that end of the connection. To send a message and wait for a response, you do this: ``` socket.sendRequestResponse(data, function(err, response) { if (!err) { // response is here } }); ``` If you're receiving requests and sending back responses, then you do this: ``` initRequestResponseSocket(socket, function(data, respondCallback) { // process the data here // send response respondCallback(null, yourResponseData); }); ``` As for error handling, you can monitor for a loss of connection and you could build a timeout into this code so that if a response doesn't arrive in a certain amount of time, then you'd get an error back. Here's an expanded version of the above code that implements a timeout for a response that does not come within some time period: ``` function initRequestResponseSocket(socket, requestHandler, timeout) { var cntr = 0; var openResponses = {}; // send a request socket.sendRequestResponse = function(data, fn) { // put this data in a wrapper object that contains the request id // save the callback function for this id var id = cntr++; openResponses[id] = {fn: fn}; socket.emit('requestMsg', {id: id, data: data}); if (timeout) { openResponses[id].timer = setTimeout(function() { delete openResponses[id]; if (fn) { fn("timeout"); } }, timeout); } } // process a response message that comes back from a request socket.on('responseMsg', function(wrapper) { var id = wrapper.id, requestInfo; if (typeof id === "number" && typeof openResponse[id] === "object") { requestInfo = openResponses[id]; delete openResponses[id]; if (requestInfo) { if (requestInfo.timer) { clearTimeout(requestInfo.timer); } if (requestInfo.fn) { requestInfo.fn(null, wrapper.data); } } } }); // process a requestMsg socket.on('requestMsg', function(wrapper) { if (requestHandler && wrapper.id) { requestHandler(wrapper.data, function(responseToSend) { socket.emit('responseMsg', {id: wrapper.id, data; responseToSend}); }); } }); } ```
There are a couple of interesting things in your question and your design, I prefer to ignore the implementation details and look at the high level architecture. You state that you are looking to a client that requests data and a server that responds with some stream of data. Two things to note here: 1. HTTP 1.1 has options to send streaming responses (*Chunked transfer encoding*). If your use-case is only the sending of streaming responses, this might be a better fit for you. This does not hold when you e.g. want to push messages to the client that are not responding to some sort of request (sometimes referred to as *Server side events*). 2. Websockets, contrary to HTTP, do not natively implement some sort of request-response cycle. You can use the protocol as such by implementing your own mechanism, something that e.g. the subprotocol [WAMP](http://wamp-proto.org) is doing. As you have found out, implementing your own mechanism comes with it's pitfalls, that is where HTTP has the clear advantage. Given the requirements stated in your question I would opt for the HTTP streaming method instead of implementing your own request/response mechanism.
19,347,430
This is my first attempt at using javscript with html/css. I have a button that when clicked shows a question, and three radio buttons. Everything so far so good, but I would like the radio buttons to be aligned with their actual button on the left (not the text). The content div is centered, so it seems like it is just centering the radio buttons to the page, but not relative to one another. I think if you take a look at my link you will understand: [Link to example page](http://boomgoesthecat.com/quiz/) Any ideas on how I can get the affect I am looking for here? Admittedly this is pretty clunky but baby steps :) **Here is my html:** ``` <!-- Here is the main content --> <div class="content"> <h1>Quiz With Javascript</h1> <p>This is a simple quiz leveraging javascript.</p> <div class="btn-group"> <input type="button" class="btn btn-primary btn-lg" onclick="showDiv()" value="Click Here For The Question" /> </div> <div id="question1"> <h3>Where Does Phil Work?</h3> <div> <form> <input type="radio" name="work" id="optionsRadios1" value="INTUIT">Intuit<br> <input type="radio" name="work" value="GOOGLE">Google<br> <input type="radio" name="work" value="AMAZON">Amazon<br> </form> </div> <script src="js/quiz.js"></script> <script type="text/javascript"> function showDiv() { document.getElementById('question1').style.display = "block"; } </script> </div> ``` **Here is a snippet from my CSS:** ``` body { margin: 50px 0px; padding: 0px; background-color: #7FFFD4; border-radius: 25px; } .content { text-align: center; } input[type='radio']{ vertical-align: baseline; padding: 10px; margin: 10px; } ```
2013/10/13
[ "https://Stackoverflow.com/questions/19347430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2873870/" ]
If `orig` and `pol1` are instances of `Polynomial` then this ``` if (orig.equals(pol1)) ``` would only work if you implement `Polynomial#equals()` as well; which would iterate the two `ArrayList`s and make sure individual `Pair`s are equal (using `Pair#equals()` of course).
Use the [Double.compare(double, double)](http://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#compare%28double,%20double%29) method instead of ==. Floating point comparison is "fuzzy" in Java.
19,347,430
This is my first attempt at using javscript with html/css. I have a button that when clicked shows a question, and three radio buttons. Everything so far so good, but I would like the radio buttons to be aligned with their actual button on the left (not the text). The content div is centered, so it seems like it is just centering the radio buttons to the page, but not relative to one another. I think if you take a look at my link you will understand: [Link to example page](http://boomgoesthecat.com/quiz/) Any ideas on how I can get the affect I am looking for here? Admittedly this is pretty clunky but baby steps :) **Here is my html:** ``` <!-- Here is the main content --> <div class="content"> <h1>Quiz With Javascript</h1> <p>This is a simple quiz leveraging javascript.</p> <div class="btn-group"> <input type="button" class="btn btn-primary btn-lg" onclick="showDiv()" value="Click Here For The Question" /> </div> <div id="question1"> <h3>Where Does Phil Work?</h3> <div> <form> <input type="radio" name="work" id="optionsRadios1" value="INTUIT">Intuit<br> <input type="radio" name="work" value="GOOGLE">Google<br> <input type="radio" name="work" value="AMAZON">Amazon<br> </form> </div> <script src="js/quiz.js"></script> <script type="text/javascript"> function showDiv() { document.getElementById('question1').style.display = "block"; } </script> </div> ``` **Here is a snippet from my CSS:** ``` body { margin: 50px 0px; padding: 0px; background-color: #7FFFD4; border-radius: 25px; } .content { text-align: center; } input[type='radio']{ vertical-align: baseline; padding: 10px; margin: 10px; } ```
2013/10/13
[ "https://Stackoverflow.com/questions/19347430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2873870/" ]
If `orig` and `pol1` are instances of `Polynomial` then this ``` if (orig.equals(pol1)) ``` would only work if you implement `Polynomial#equals()` as well; which would iterate the two `ArrayList`s and make sure individual `Pair`s are equal (using `Pair#equals()` of course).
Ok, thanks to Ravi Thapliyal I found the solution. After adding an custom equals method in my Polynominal class, the problem was fixed. ``` @Override public boolean equals(Object o) { if (!(o instanceof Polynomial)) return false; Polynomial that = (Polynomial) o; return that.terms.equals(terms); } ```
19,347,430
This is my first attempt at using javscript with html/css. I have a button that when clicked shows a question, and three radio buttons. Everything so far so good, but I would like the radio buttons to be aligned with their actual button on the left (not the text). The content div is centered, so it seems like it is just centering the radio buttons to the page, but not relative to one another. I think if you take a look at my link you will understand: [Link to example page](http://boomgoesthecat.com/quiz/) Any ideas on how I can get the affect I am looking for here? Admittedly this is pretty clunky but baby steps :) **Here is my html:** ``` <!-- Here is the main content --> <div class="content"> <h1>Quiz With Javascript</h1> <p>This is a simple quiz leveraging javascript.</p> <div class="btn-group"> <input type="button" class="btn btn-primary btn-lg" onclick="showDiv()" value="Click Here For The Question" /> </div> <div id="question1"> <h3>Where Does Phil Work?</h3> <div> <form> <input type="radio" name="work" id="optionsRadios1" value="INTUIT">Intuit<br> <input type="radio" name="work" value="GOOGLE">Google<br> <input type="radio" name="work" value="AMAZON">Amazon<br> </form> </div> <script src="js/quiz.js"></script> <script type="text/javascript"> function showDiv() { document.getElementById('question1').style.display = "block"; } </script> </div> ``` **Here is a snippet from my CSS:** ``` body { margin: 50px 0px; padding: 0px; background-color: #7FFFD4; border-radius: 25px; } .content { text-align: center; } input[type='radio']{ vertical-align: baseline; padding: 10px; margin: 10px; } ```
2013/10/13
[ "https://Stackoverflow.com/questions/19347430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2873870/" ]
If `orig` and `pol1` are instances of `Polynomial` then this ``` if (orig.equals(pol1)) ``` would only work if you implement `Polynomial#equals()` as well; which would iterate the two `ArrayList`s and make sure individual `Pair`s are equal (using `Pair#equals()` of course).
You would need to implement a Polynomail.equals() method something like the following: ``` public boolean equals(Object o) { if (!(o instanceof Polynomial)) return false; Polynomial other = (Polynomial) o; if (this.terms==null && other.terms==null) return true; // A suitable equals() method already exists for ArrayList, so we can use that // this will in turn use Pair.equals() which looks OK to me if (this.terms!=null && other.terms!=null) return this.terms.equals(other.terms); return false; } ```
19,347,430
This is my first attempt at using javscript with html/css. I have a button that when clicked shows a question, and three radio buttons. Everything so far so good, but I would like the radio buttons to be aligned with their actual button on the left (not the text). The content div is centered, so it seems like it is just centering the radio buttons to the page, but not relative to one another. I think if you take a look at my link you will understand: [Link to example page](http://boomgoesthecat.com/quiz/) Any ideas on how I can get the affect I am looking for here? Admittedly this is pretty clunky but baby steps :) **Here is my html:** ``` <!-- Here is the main content --> <div class="content"> <h1>Quiz With Javascript</h1> <p>This is a simple quiz leveraging javascript.</p> <div class="btn-group"> <input type="button" class="btn btn-primary btn-lg" onclick="showDiv()" value="Click Here For The Question" /> </div> <div id="question1"> <h3>Where Does Phil Work?</h3> <div> <form> <input type="radio" name="work" id="optionsRadios1" value="INTUIT">Intuit<br> <input type="radio" name="work" value="GOOGLE">Google<br> <input type="radio" name="work" value="AMAZON">Amazon<br> </form> </div> <script src="js/quiz.js"></script> <script type="text/javascript"> function showDiv() { document.getElementById('question1').style.display = "block"; } </script> </div> ``` **Here is a snippet from my CSS:** ``` body { margin: 50px 0px; padding: 0px; background-color: #7FFFD4; border-radius: 25px; } .content { text-align: center; } input[type='radio']{ vertical-align: baseline; padding: 10px; margin: 10px; } ```
2013/10/13
[ "https://Stackoverflow.com/questions/19347430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2873870/" ]
If `orig` and `pol1` are instances of `Polynomial` then this ``` if (orig.equals(pol1)) ``` would only work if you implement `Polynomial#equals()` as well; which would iterate the two `ArrayList`s and make sure individual `Pair`s are equal (using `Pair#equals()` of course).
Two issues come to mind: the first is that the default `hashCode()` method will seldom return the same value for any two distinct object instances, regardless of their contents. This is a good thing if the `equals()` method will never report two distinct object instances as equal, but is a bad thing if it will. *Every* object which overrides `Object.equals()` should also override `Object.hashCode()` so that if `x.equals(y)`, then `x.hashCode()==y.hashCode()`; this is important because even non-hashed generic collections may use objects' hash codes to expedite comparisons. *If you don't want to write a "real" hash function, simply pick some arbitrary integer and have your type's `hashCode()` method always return that*. Any hashed collection into which your type is stored will perform slowly, but all collections into which it is stored should behave correctly. The second issue you may be seeing is that floating-point comparisons are sometimes dodgy. Two numbers may be essentially equal but compare unequal. Worse, the IEEE decided for whatever reason that floating-point "not-a-number" values should compare unequal to everything--*even themselves*. Factoring both of these issues together, I would suggest that you might want to rewrite your `equals` method to chain to the `equals` method of `double`. Further, if neither field of your object will be modified while it's stored in a collection, have your `hashCode()` method compute the `hashCode` of the `int`, multiply it by some large odd number, and then add or xor that with the `hashCode` of the `double`. If your object might be modified while stored in a collection, have `hashCode()` return a constant. If you don't override `hashCode()` you cannot expect the `equals` methods of any objects which contain yours to work correctly.
19,347,430
This is my first attempt at using javscript with html/css. I have a button that when clicked shows a question, and three radio buttons. Everything so far so good, but I would like the radio buttons to be aligned with their actual button on the left (not the text). The content div is centered, so it seems like it is just centering the radio buttons to the page, but not relative to one another. I think if you take a look at my link you will understand: [Link to example page](http://boomgoesthecat.com/quiz/) Any ideas on how I can get the affect I am looking for here? Admittedly this is pretty clunky but baby steps :) **Here is my html:** ``` <!-- Here is the main content --> <div class="content"> <h1>Quiz With Javascript</h1> <p>This is a simple quiz leveraging javascript.</p> <div class="btn-group"> <input type="button" class="btn btn-primary btn-lg" onclick="showDiv()" value="Click Here For The Question" /> </div> <div id="question1"> <h3>Where Does Phil Work?</h3> <div> <form> <input type="radio" name="work" id="optionsRadios1" value="INTUIT">Intuit<br> <input type="radio" name="work" value="GOOGLE">Google<br> <input type="radio" name="work" value="AMAZON">Amazon<br> </form> </div> <script src="js/quiz.js"></script> <script type="text/javascript"> function showDiv() { document.getElementById('question1').style.display = "block"; } </script> </div> ``` **Here is a snippet from my CSS:** ``` body { margin: 50px 0px; padding: 0px; background-color: #7FFFD4; border-radius: 25px; } .content { text-align: center; } input[type='radio']{ vertical-align: baseline; padding: 10px; margin: 10px; } ```
2013/10/13
[ "https://Stackoverflow.com/questions/19347430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2873870/" ]
Ok, thanks to Ravi Thapliyal I found the solution. After adding an custom equals method in my Polynominal class, the problem was fixed. ``` @Override public boolean equals(Object o) { if (!(o instanceof Polynomial)) return false; Polynomial that = (Polynomial) o; return that.terms.equals(terms); } ```
Use the [Double.compare(double, double)](http://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#compare%28double,%20double%29) method instead of ==. Floating point comparison is "fuzzy" in Java.
19,347,430
This is my first attempt at using javscript with html/css. I have a button that when clicked shows a question, and three radio buttons. Everything so far so good, but I would like the radio buttons to be aligned with their actual button on the left (not the text). The content div is centered, so it seems like it is just centering the radio buttons to the page, but not relative to one another. I think if you take a look at my link you will understand: [Link to example page](http://boomgoesthecat.com/quiz/) Any ideas on how I can get the affect I am looking for here? Admittedly this is pretty clunky but baby steps :) **Here is my html:** ``` <!-- Here is the main content --> <div class="content"> <h1>Quiz With Javascript</h1> <p>This is a simple quiz leveraging javascript.</p> <div class="btn-group"> <input type="button" class="btn btn-primary btn-lg" onclick="showDiv()" value="Click Here For The Question" /> </div> <div id="question1"> <h3>Where Does Phil Work?</h3> <div> <form> <input type="radio" name="work" id="optionsRadios1" value="INTUIT">Intuit<br> <input type="radio" name="work" value="GOOGLE">Google<br> <input type="radio" name="work" value="AMAZON">Amazon<br> </form> </div> <script src="js/quiz.js"></script> <script type="text/javascript"> function showDiv() { document.getElementById('question1').style.display = "block"; } </script> </div> ``` **Here is a snippet from my CSS:** ``` body { margin: 50px 0px; padding: 0px; background-color: #7FFFD4; border-radius: 25px; } .content { text-align: center; } input[type='radio']{ vertical-align: baseline; padding: 10px; margin: 10px; } ```
2013/10/13
[ "https://Stackoverflow.com/questions/19347430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2873870/" ]
Ok, thanks to Ravi Thapliyal I found the solution. After adding an custom equals method in my Polynominal class, the problem was fixed. ``` @Override public boolean equals(Object o) { if (!(o instanceof Polynomial)) return false; Polynomial that = (Polynomial) o; return that.terms.equals(terms); } ```
You would need to implement a Polynomail.equals() method something like the following: ``` public boolean equals(Object o) { if (!(o instanceof Polynomial)) return false; Polynomial other = (Polynomial) o; if (this.terms==null && other.terms==null) return true; // A suitable equals() method already exists for ArrayList, so we can use that // this will in turn use Pair.equals() which looks OK to me if (this.terms!=null && other.terms!=null) return this.terms.equals(other.terms); return false; } ```
19,347,430
This is my first attempt at using javscript with html/css. I have a button that when clicked shows a question, and three radio buttons. Everything so far so good, but I would like the radio buttons to be aligned with their actual button on the left (not the text). The content div is centered, so it seems like it is just centering the radio buttons to the page, but not relative to one another. I think if you take a look at my link you will understand: [Link to example page](http://boomgoesthecat.com/quiz/) Any ideas on how I can get the affect I am looking for here? Admittedly this is pretty clunky but baby steps :) **Here is my html:** ``` <!-- Here is the main content --> <div class="content"> <h1>Quiz With Javascript</h1> <p>This is a simple quiz leveraging javascript.</p> <div class="btn-group"> <input type="button" class="btn btn-primary btn-lg" onclick="showDiv()" value="Click Here For The Question" /> </div> <div id="question1"> <h3>Where Does Phil Work?</h3> <div> <form> <input type="radio" name="work" id="optionsRadios1" value="INTUIT">Intuit<br> <input type="radio" name="work" value="GOOGLE">Google<br> <input type="radio" name="work" value="AMAZON">Amazon<br> </form> </div> <script src="js/quiz.js"></script> <script type="text/javascript"> function showDiv() { document.getElementById('question1').style.display = "block"; } </script> </div> ``` **Here is a snippet from my CSS:** ``` body { margin: 50px 0px; padding: 0px; background-color: #7FFFD4; border-radius: 25px; } .content { text-align: center; } input[type='radio']{ vertical-align: baseline; padding: 10px; margin: 10px; } ```
2013/10/13
[ "https://Stackoverflow.com/questions/19347430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2873870/" ]
Ok, thanks to Ravi Thapliyal I found the solution. After adding an custom equals method in my Polynominal class, the problem was fixed. ``` @Override public boolean equals(Object o) { if (!(o instanceof Polynomial)) return false; Polynomial that = (Polynomial) o; return that.terms.equals(terms); } ```
Two issues come to mind: the first is that the default `hashCode()` method will seldom return the same value for any two distinct object instances, regardless of their contents. This is a good thing if the `equals()` method will never report two distinct object instances as equal, but is a bad thing if it will. *Every* object which overrides `Object.equals()` should also override `Object.hashCode()` so that if `x.equals(y)`, then `x.hashCode()==y.hashCode()`; this is important because even non-hashed generic collections may use objects' hash codes to expedite comparisons. *If you don't want to write a "real" hash function, simply pick some arbitrary integer and have your type's `hashCode()` method always return that*. Any hashed collection into which your type is stored will perform slowly, but all collections into which it is stored should behave correctly. The second issue you may be seeing is that floating-point comparisons are sometimes dodgy. Two numbers may be essentially equal but compare unequal. Worse, the IEEE decided for whatever reason that floating-point "not-a-number" values should compare unequal to everything--*even themselves*. Factoring both of these issues together, I would suggest that you might want to rewrite your `equals` method to chain to the `equals` method of `double`. Further, if neither field of your object will be modified while it's stored in a collection, have your `hashCode()` method compute the `hashCode` of the `int`, multiply it by some large odd number, and then add or xor that with the `hashCode` of the `double`. If your object might be modified while stored in a collection, have `hashCode()` return a constant. If you don't override `hashCode()` you cannot expect the `equals` methods of any objects which contain yours to work correctly.
16,739,212
I need to fill a html webview with variables that I have stored in objective C. I believe that I need to use: ``` [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"John", firstName]; ``` but not sure what to put there and what my javascript needs to be to implement the passed variables. here is a little bit of my html to help get an idea: ``` <ul><li><span>First Name:</span> first name needs to go here</li> <li><span>Last Name:</span> last name needs to go here</li> ``` **Updated code:** ``` - (void)viewDidLoad { [super viewDidLoad]; [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"idcard" ofType:@"html"]isDirectory:NO]]]; } -(void)viewDidAppear:(BOOL)animated { NSString *str = @"John"; NSString *script = [NSString stringWithFormat:@"myFunc('%@')", str]; [self.webView stringByEvaluatingJavaScriptFromString:script]; } ``` **Update 2:** javascript/html: ``` <ul><li><span>Policy Number:</span> <script> function myFunc(str) { document.write(str) } </script> ```
2013/05/24
[ "https://Stackoverflow.com/questions/16739212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1455182/" ]
Basically you need a javascript method to add the data to the HTML string. Once you have the function, passing data to it is fairly straight forward, ``` NSString *script = [NSString stringWithFormat:@"methodName([%@])", data] [self.webView stringByEvaluatingJavaScriptFromString:script]; ``` And writing Javascript to place data in HTML string is [easy](http://www.w3schools.com/js/js_htmldom_html.asp).
Do you have access to the raw HTML string in your code? If so, can you do something like that? ``` UIWebView *webview = [[UIWebView alloc] initWithFrame:self.view.bounds]; [self.view addSubview:webview]; NSString *htmlString = [NSString stringWithFormat:@"<html>\ <ul><li><span>First Name:</span> %@</li>\ <li><span>Last Name:</span> %@</li>\ </html>", @"John", @"Smith"]; [webview loadHTMLString:htmlString baseURL:nil]; ``` If you want to use JavaScript, here's an example: [How to control UIWebView's javascript](https://stackoverflow.com/questions/8325841/how-to-control-uiwebviews-javascript)
16,739,212
I need to fill a html webview with variables that I have stored in objective C. I believe that I need to use: ``` [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"John", firstName]; ``` but not sure what to put there and what my javascript needs to be to implement the passed variables. here is a little bit of my html to help get an idea: ``` <ul><li><span>First Name:</span> first name needs to go here</li> <li><span>Last Name:</span> last name needs to go here</li> ``` **Updated code:** ``` - (void)viewDidLoad { [super viewDidLoad]; [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"idcard" ofType:@"html"]isDirectory:NO]]]; } -(void)viewDidAppear:(BOOL)animated { NSString *str = @"John"; NSString *script = [NSString stringWithFormat:@"myFunc('%@')", str]; [self.webView stringByEvaluatingJavaScriptFromString:script]; } ``` **Update 2:** javascript/html: ``` <ul><li><span>Policy Number:</span> <script> function myFunc(str) { document.write(str) } </script> ```
2013/05/24
[ "https://Stackoverflow.com/questions/16739212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1455182/" ]
I ended up using a different js approach and used, hopefully this is helpful to someone. obj c: ``` NSString *str = @"John"; NSString *script = [NSString stringWithFormat:@"document.getElementById('name').innerHTML = '%@';", str]; [self.webView stringByEvaluatingJavaScriptFromString:script]; ``` js: ``` <li><span>Name:</span> <span id = 'name'>name goes here</span> </li> ```
Basically you need a javascript method to add the data to the HTML string. Once you have the function, passing data to it is fairly straight forward, ``` NSString *script = [NSString stringWithFormat:@"methodName([%@])", data] [self.webView stringByEvaluatingJavaScriptFromString:script]; ``` And writing Javascript to place data in HTML string is [easy](http://www.w3schools.com/js/js_htmldom_html.asp).
16,739,212
I need to fill a html webview with variables that I have stored in objective C. I believe that I need to use: ``` [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"John", firstName]; ``` but not sure what to put there and what my javascript needs to be to implement the passed variables. here is a little bit of my html to help get an idea: ``` <ul><li><span>First Name:</span> first name needs to go here</li> <li><span>Last Name:</span> last name needs to go here</li> ``` **Updated code:** ``` - (void)viewDidLoad { [super viewDidLoad]; [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"idcard" ofType:@"html"]isDirectory:NO]]]; } -(void)viewDidAppear:(BOOL)animated { NSString *str = @"John"; NSString *script = [NSString stringWithFormat:@"myFunc('%@')", str]; [self.webView stringByEvaluatingJavaScriptFromString:script]; } ``` **Update 2:** javascript/html: ``` <ul><li><span>Policy Number:</span> <script> function myFunc(str) { document.write(str) } </script> ```
2013/05/24
[ "https://Stackoverflow.com/questions/16739212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1455182/" ]
I ended up using a different js approach and used, hopefully this is helpful to someone. obj c: ``` NSString *str = @"John"; NSString *script = [NSString stringWithFormat:@"document.getElementById('name').innerHTML = '%@';", str]; [self.webView stringByEvaluatingJavaScriptFromString:script]; ``` js: ``` <li><span>Name:</span> <span id = 'name'>name goes here</span> </li> ```
Do you have access to the raw HTML string in your code? If so, can you do something like that? ``` UIWebView *webview = [[UIWebView alloc] initWithFrame:self.view.bounds]; [self.view addSubview:webview]; NSString *htmlString = [NSString stringWithFormat:@"<html>\ <ul><li><span>First Name:</span> %@</li>\ <li><span>Last Name:</span> %@</li>\ </html>", @"John", @"Smith"]; [webview loadHTMLString:htmlString baseURL:nil]; ``` If you want to use JavaScript, here's an example: [How to control UIWebView's javascript](https://stackoverflow.com/questions/8325841/how-to-control-uiwebviews-javascript)
6,394,223
I think I've read just about everything out there on the topic of logging out of Facebook inside of a Desktop application. Nothing so far works. Specifically, I would like to log the user out so that they can switch identities, e.g. People sharing a computer at home could then use the software with their own Facebook accounts, but with no chance to switch accounts, it's quite messy. (Have not yet tested switching Windows users accounts as that is simply far too much to ask of the end user and should not be necessary.) Now, I should say that I have set the application to use these permissions: ``` string[] permissions = new string[] { "user_photos", "publish_stream", "offline_access" }; ``` So, "offline\_access" is included there. I do not know if this does/should affect logging out or not. Again, my purpose for logging out is merely to switch users. (If there's a better approach, please let me know.) The purported solutions seem to be: * Use the JavaScript SDK (FB.logout()) * Use "m.facebook.com" instead * Create your own URL (and possibly use m.facebook.com) * Create your own URL and use the session variable (in ASP.NET) The first is kind of silly. Why resort to JavaScript when you're using C#? It's kind of a step backwards and has a lot of additional overhead in a desktop application. (I have not tried this as it's simply disgustingly messy to do this in a desktop application.) If anyone can confirm that this is the only working method, please do so. I'm desperately trying to avoid it. The second doesn't work. Perhaps it worked in the past, but my umpteen attempts to get it to work have all failed. The third doesn't work. I've tried umpteen dozen variations with zero success. The last option there doesn't work for a desktop application because it's not ASP.NET and you don't have a session variable to work with. The Facebook C# SDK logout also no longer works. i.e. ``` public FacebookLoginDialog(string appId, string[] extendedPermissions, bool logout) { IDictionary<string, object> loginParameters = new Dictionary<string, object> { { "response_type", "token" }, { "display", "popup" } }; _navigateUri = FacebookOAuthClient.GetLoginUrl(appId, null, extendedPermissions, logout, loginParameters); InitializeComponent(); } ``` I remember it working in the past, but it no longer works now. (Which truly puzzles me...) It instead now directs the user to the Facebook mobile page, where the user must manually logout. Now, I could do browser automation to automatically click the logout link for the user, however, this is prone to breaking if Facebook updates the mobile UI. It is also messy, and possibly a worse solution than trying to use the JavaScript SDK FB.logout() method (though not by much). I have searched for some kind of documentation, however, I cannot find anything in the Facebook developer documentation that illustrates how to logout an application. Has anyone solved this problem, or seen any documentation that can be ported to work with the Facebook C# SDK? I am certainly open to using a WebClient or HttpClient/Response if anyone can point to some documentation that could work with it. I simply have not been able to find any low-level documentation that shows how this approach could work. Thank you in advance for any advice, pointers, or links.
2011/06/18
[ "https://Stackoverflow.com/questions/6394223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/804186/" ]
Well, I've turned up nothing that works, so I've resorted to a nasty hack. The FacebookOAuthClient.GetLogoutUrl() method URL does not log me out, however, it does return an "m.facebook.com" URL, e.g.: <http://m.facebook.com/logout.php?next=http://www.facebook.com/dialog/oauth/?response_type=token&display=popup&scope=user_about_me%252coffline_access&client_id=123456789012345&redirect_uri=http%253a%252f%252fwww.facebook.com%252fconnect%252flogin_success.html&confirm=1> The mobile page has a "Logout" link at the bottom of the page. Trying to catch the anchor tag: ``` HtmlElementCollection hec = wbrFacebookAuth.Document.GetElementsByTagName("a"); foreach (HtmlElement elem in hec) { // the logout link has a data-sigil="logout" attribute: string datasigil = elem.GetAttribute("data-sigil").ToLower(); if (datasigil == "logout") { wbrFacebookAuth.Navigate(elem.GetAttribute("href")); break; } } ``` In the Navigated WebBrowser event is unpredictable and unreliable. The actual method of catching it isn't relevant. e.g. This does not work either: ``` string logoutPattern = @"<a href=""(/logout.[^""]+)"""; Regex rx = new Regex(logoutPattern); if (rx.IsMatch(wbMain.DocumentText)) { MatchCollection mc = rx.Matches(wbMain.DocumentText); if (mc.Count > 0) { foreach (Match m in mc) { Console.WriteLine("*** " + m.ToString()); } } } ``` However, it can be caught reliably in the DocumentCompleted event handler. ``` private void wbrFacebookAuth_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { if (_logout) { HtmlElementCollection hec = wbrFacebookAuth.Document.GetElementsByTagName("a"); foreach (HtmlElement elem in hec) { // the logout link has a data-sigil="logout" attribute: string datasigil = elem.GetAttribute("data-sigil").ToLower(); if (datasigil == "logout") { wbrFacebookAuth.Navigate(elem.GetAttribute("href")); break; } } } } ``` The problem is that it is now loading 2 pages instead of 1, and it's still a bit messy. However, it works.
See this [blog post](http://blog.prabir.me/post/Facebook-CSharp-SDK-Logout.aspx) Get the logout url using FacebookOAuthClient() & send a http request to the url..
6,394,223
I think I've read just about everything out there on the topic of logging out of Facebook inside of a Desktop application. Nothing so far works. Specifically, I would like to log the user out so that they can switch identities, e.g. People sharing a computer at home could then use the software with their own Facebook accounts, but with no chance to switch accounts, it's quite messy. (Have not yet tested switching Windows users accounts as that is simply far too much to ask of the end user and should not be necessary.) Now, I should say that I have set the application to use these permissions: ``` string[] permissions = new string[] { "user_photos", "publish_stream", "offline_access" }; ``` So, "offline\_access" is included there. I do not know if this does/should affect logging out or not. Again, my purpose for logging out is merely to switch users. (If there's a better approach, please let me know.) The purported solutions seem to be: * Use the JavaScript SDK (FB.logout()) * Use "m.facebook.com" instead * Create your own URL (and possibly use m.facebook.com) * Create your own URL and use the session variable (in ASP.NET) The first is kind of silly. Why resort to JavaScript when you're using C#? It's kind of a step backwards and has a lot of additional overhead in a desktop application. (I have not tried this as it's simply disgustingly messy to do this in a desktop application.) If anyone can confirm that this is the only working method, please do so. I'm desperately trying to avoid it. The second doesn't work. Perhaps it worked in the past, but my umpteen attempts to get it to work have all failed. The third doesn't work. I've tried umpteen dozen variations with zero success. The last option there doesn't work for a desktop application because it's not ASP.NET and you don't have a session variable to work with. The Facebook C# SDK logout also no longer works. i.e. ``` public FacebookLoginDialog(string appId, string[] extendedPermissions, bool logout) { IDictionary<string, object> loginParameters = new Dictionary<string, object> { { "response_type", "token" }, { "display", "popup" } }; _navigateUri = FacebookOAuthClient.GetLoginUrl(appId, null, extendedPermissions, logout, loginParameters); InitializeComponent(); } ``` I remember it working in the past, but it no longer works now. (Which truly puzzles me...) It instead now directs the user to the Facebook mobile page, where the user must manually logout. Now, I could do browser automation to automatically click the logout link for the user, however, this is prone to breaking if Facebook updates the mobile UI. It is also messy, and possibly a worse solution than trying to use the JavaScript SDK FB.logout() method (though not by much). I have searched for some kind of documentation, however, I cannot find anything in the Facebook developer documentation that illustrates how to logout an application. Has anyone solved this problem, or seen any documentation that can be ported to work with the Facebook C# SDK? I am certainly open to using a WebClient or HttpClient/Response if anyone can point to some documentation that could work with it. I simply have not been able to find any low-level documentation that shows how this approach could work. Thank you in advance for any advice, pointers, or links.
2011/06/18
[ "https://Stackoverflow.com/questions/6394223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/804186/" ]
This question has been answered [here](https://stackoverflow.com/questions/6023908/facebook-logout-c-sdk), the suggestion is to use the url below to logout since facebook is apparently skipping the "next" parameter ``` https://www.facebook.com/logout.php?next=[redirect_uri]&access_token=[access_token] ```
See this [blog post](http://blog.prabir.me/post/Facebook-CSharp-SDK-Logout.aspx) Get the logout url using FacebookOAuthClient() & send a http request to the url..
6,394,223
I think I've read just about everything out there on the topic of logging out of Facebook inside of a Desktop application. Nothing so far works. Specifically, I would like to log the user out so that they can switch identities, e.g. People sharing a computer at home could then use the software with their own Facebook accounts, but with no chance to switch accounts, it's quite messy. (Have not yet tested switching Windows users accounts as that is simply far too much to ask of the end user and should not be necessary.) Now, I should say that I have set the application to use these permissions: ``` string[] permissions = new string[] { "user_photos", "publish_stream", "offline_access" }; ``` So, "offline\_access" is included there. I do not know if this does/should affect logging out or not. Again, my purpose for logging out is merely to switch users. (If there's a better approach, please let me know.) The purported solutions seem to be: * Use the JavaScript SDK (FB.logout()) * Use "m.facebook.com" instead * Create your own URL (and possibly use m.facebook.com) * Create your own URL and use the session variable (in ASP.NET) The first is kind of silly. Why resort to JavaScript when you're using C#? It's kind of a step backwards and has a lot of additional overhead in a desktop application. (I have not tried this as it's simply disgustingly messy to do this in a desktop application.) If anyone can confirm that this is the only working method, please do so. I'm desperately trying to avoid it. The second doesn't work. Perhaps it worked in the past, but my umpteen attempts to get it to work have all failed. The third doesn't work. I've tried umpteen dozen variations with zero success. The last option there doesn't work for a desktop application because it's not ASP.NET and you don't have a session variable to work with. The Facebook C# SDK logout also no longer works. i.e. ``` public FacebookLoginDialog(string appId, string[] extendedPermissions, bool logout) { IDictionary<string, object> loginParameters = new Dictionary<string, object> { { "response_type", "token" }, { "display", "popup" } }; _navigateUri = FacebookOAuthClient.GetLoginUrl(appId, null, extendedPermissions, logout, loginParameters); InitializeComponent(); } ``` I remember it working in the past, but it no longer works now. (Which truly puzzles me...) It instead now directs the user to the Facebook mobile page, where the user must manually logout. Now, I could do browser automation to automatically click the logout link for the user, however, this is prone to breaking if Facebook updates the mobile UI. It is also messy, and possibly a worse solution than trying to use the JavaScript SDK FB.logout() method (though not by much). I have searched for some kind of documentation, however, I cannot find anything in the Facebook developer documentation that illustrates how to logout an application. Has anyone solved this problem, or seen any documentation that can be ported to work with the Facebook C# SDK? I am certainly open to using a WebClient or HttpClient/Response if anyone can point to some documentation that could work with it. I simply have not been able to find any low-level documentation that shows how this approach could work. Thank you in advance for any advice, pointers, or links.
2011/06/18
[ "https://Stackoverflow.com/questions/6394223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/804186/" ]
I'm guessing you want to log the user out so you can log another account in. In which case I would suggest this approach using the WebAuthenticationBroker: After quite a while experimenting and having no luck with any of the examples above I have worked out that submitting a logout request with the redirect url to your login url works perfectly. Here's the code I used to chain the requests together: ``` var logIn = this.Client.GetLoginUrl( new { client_id = AppId, redirect_uri = App.FacebookAuthUri.AbsoluteUri, scope = AuthTokens.FACEBOOK_PERMISSIONS, display = "popup", response_type = "token" }); var logOut = this.Client.GetLogoutUrl(new { next = logIn, access_token = Settings.FacebookToken.Value }); if (Settings.FacebookToken.Value != null) WebAuthenticationBroker.AuthenticateAndContinue(logOut); ``` Now every time you direct the user to the WebAuthenticationBroker the user will be redirected to the sign in page.
See this [blog post](http://blog.prabir.me/post/Facebook-CSharp-SDK-Logout.aspx) Get the logout url using FacebookOAuthClient() & send a http request to the url..
6,394,223
I think I've read just about everything out there on the topic of logging out of Facebook inside of a Desktop application. Nothing so far works. Specifically, I would like to log the user out so that they can switch identities, e.g. People sharing a computer at home could then use the software with their own Facebook accounts, but with no chance to switch accounts, it's quite messy. (Have not yet tested switching Windows users accounts as that is simply far too much to ask of the end user and should not be necessary.) Now, I should say that I have set the application to use these permissions: ``` string[] permissions = new string[] { "user_photos", "publish_stream", "offline_access" }; ``` So, "offline\_access" is included there. I do not know if this does/should affect logging out or not. Again, my purpose for logging out is merely to switch users. (If there's a better approach, please let me know.) The purported solutions seem to be: * Use the JavaScript SDK (FB.logout()) * Use "m.facebook.com" instead * Create your own URL (and possibly use m.facebook.com) * Create your own URL and use the session variable (in ASP.NET) The first is kind of silly. Why resort to JavaScript when you're using C#? It's kind of a step backwards and has a lot of additional overhead in a desktop application. (I have not tried this as it's simply disgustingly messy to do this in a desktop application.) If anyone can confirm that this is the only working method, please do so. I'm desperately trying to avoid it. The second doesn't work. Perhaps it worked in the past, but my umpteen attempts to get it to work have all failed. The third doesn't work. I've tried umpteen dozen variations with zero success. The last option there doesn't work for a desktop application because it's not ASP.NET and you don't have a session variable to work with. The Facebook C# SDK logout also no longer works. i.e. ``` public FacebookLoginDialog(string appId, string[] extendedPermissions, bool logout) { IDictionary<string, object> loginParameters = new Dictionary<string, object> { { "response_type", "token" }, { "display", "popup" } }; _navigateUri = FacebookOAuthClient.GetLoginUrl(appId, null, extendedPermissions, logout, loginParameters); InitializeComponent(); } ``` I remember it working in the past, but it no longer works now. (Which truly puzzles me...) It instead now directs the user to the Facebook mobile page, where the user must manually logout. Now, I could do browser automation to automatically click the logout link for the user, however, this is prone to breaking if Facebook updates the mobile UI. It is also messy, and possibly a worse solution than trying to use the JavaScript SDK FB.logout() method (though not by much). I have searched for some kind of documentation, however, I cannot find anything in the Facebook developer documentation that illustrates how to logout an application. Has anyone solved this problem, or seen any documentation that can be ported to work with the Facebook C# SDK? I am certainly open to using a WebClient or HttpClient/Response if anyone can point to some documentation that could work with it. I simply have not been able to find any low-level documentation that shows how this approach could work. Thank you in advance for any advice, pointers, or links.
2011/06/18
[ "https://Stackoverflow.com/questions/6394223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/804186/" ]
This question has been answered [here](https://stackoverflow.com/questions/6023908/facebook-logout-c-sdk), the suggestion is to use the url below to logout since facebook is apparently skipping the "next" parameter ``` https://www.facebook.com/logout.php?next=[redirect_uri]&access_token=[access_token] ```
Well, I've turned up nothing that works, so I've resorted to a nasty hack. The FacebookOAuthClient.GetLogoutUrl() method URL does not log me out, however, it does return an "m.facebook.com" URL, e.g.: <http://m.facebook.com/logout.php?next=http://www.facebook.com/dialog/oauth/?response_type=token&display=popup&scope=user_about_me%252coffline_access&client_id=123456789012345&redirect_uri=http%253a%252f%252fwww.facebook.com%252fconnect%252flogin_success.html&confirm=1> The mobile page has a "Logout" link at the bottom of the page. Trying to catch the anchor tag: ``` HtmlElementCollection hec = wbrFacebookAuth.Document.GetElementsByTagName("a"); foreach (HtmlElement elem in hec) { // the logout link has a data-sigil="logout" attribute: string datasigil = elem.GetAttribute("data-sigil").ToLower(); if (datasigil == "logout") { wbrFacebookAuth.Navigate(elem.GetAttribute("href")); break; } } ``` In the Navigated WebBrowser event is unpredictable and unreliable. The actual method of catching it isn't relevant. e.g. This does not work either: ``` string logoutPattern = @"<a href=""(/logout.[^""]+)"""; Regex rx = new Regex(logoutPattern); if (rx.IsMatch(wbMain.DocumentText)) { MatchCollection mc = rx.Matches(wbMain.DocumentText); if (mc.Count > 0) { foreach (Match m in mc) { Console.WriteLine("*** " + m.ToString()); } } } ``` However, it can be caught reliably in the DocumentCompleted event handler. ``` private void wbrFacebookAuth_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { if (_logout) { HtmlElementCollection hec = wbrFacebookAuth.Document.GetElementsByTagName("a"); foreach (HtmlElement elem in hec) { // the logout link has a data-sigil="logout" attribute: string datasigil = elem.GetAttribute("data-sigil").ToLower(); if (datasigil == "logout") { wbrFacebookAuth.Navigate(elem.GetAttribute("href")); break; } } } } ``` The problem is that it is now loading 2 pages instead of 1, and it's still a bit messy. However, it works.
6,394,223
I think I've read just about everything out there on the topic of logging out of Facebook inside of a Desktop application. Nothing so far works. Specifically, I would like to log the user out so that they can switch identities, e.g. People sharing a computer at home could then use the software with their own Facebook accounts, but with no chance to switch accounts, it's quite messy. (Have not yet tested switching Windows users accounts as that is simply far too much to ask of the end user and should not be necessary.) Now, I should say that I have set the application to use these permissions: ``` string[] permissions = new string[] { "user_photos", "publish_stream", "offline_access" }; ``` So, "offline\_access" is included there. I do not know if this does/should affect logging out or not. Again, my purpose for logging out is merely to switch users. (If there's a better approach, please let me know.) The purported solutions seem to be: * Use the JavaScript SDK (FB.logout()) * Use "m.facebook.com" instead * Create your own URL (and possibly use m.facebook.com) * Create your own URL and use the session variable (in ASP.NET) The first is kind of silly. Why resort to JavaScript when you're using C#? It's kind of a step backwards and has a lot of additional overhead in a desktop application. (I have not tried this as it's simply disgustingly messy to do this in a desktop application.) If anyone can confirm that this is the only working method, please do so. I'm desperately trying to avoid it. The second doesn't work. Perhaps it worked in the past, but my umpteen attempts to get it to work have all failed. The third doesn't work. I've tried umpteen dozen variations with zero success. The last option there doesn't work for a desktop application because it's not ASP.NET and you don't have a session variable to work with. The Facebook C# SDK logout also no longer works. i.e. ``` public FacebookLoginDialog(string appId, string[] extendedPermissions, bool logout) { IDictionary<string, object> loginParameters = new Dictionary<string, object> { { "response_type", "token" }, { "display", "popup" } }; _navigateUri = FacebookOAuthClient.GetLoginUrl(appId, null, extendedPermissions, logout, loginParameters); InitializeComponent(); } ``` I remember it working in the past, but it no longer works now. (Which truly puzzles me...) It instead now directs the user to the Facebook mobile page, where the user must manually logout. Now, I could do browser automation to automatically click the logout link for the user, however, this is prone to breaking if Facebook updates the mobile UI. It is also messy, and possibly a worse solution than trying to use the JavaScript SDK FB.logout() method (though not by much). I have searched for some kind of documentation, however, I cannot find anything in the Facebook developer documentation that illustrates how to logout an application. Has anyone solved this problem, or seen any documentation that can be ported to work with the Facebook C# SDK? I am certainly open to using a WebClient or HttpClient/Response if anyone can point to some documentation that could work with it. I simply have not been able to find any low-level documentation that shows how this approach could work. Thank you in advance for any advice, pointers, or links.
2011/06/18
[ "https://Stackoverflow.com/questions/6394223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/804186/" ]
Well, I've turned up nothing that works, so I've resorted to a nasty hack. The FacebookOAuthClient.GetLogoutUrl() method URL does not log me out, however, it does return an "m.facebook.com" URL, e.g.: <http://m.facebook.com/logout.php?next=http://www.facebook.com/dialog/oauth/?response_type=token&display=popup&scope=user_about_me%252coffline_access&client_id=123456789012345&redirect_uri=http%253a%252f%252fwww.facebook.com%252fconnect%252flogin_success.html&confirm=1> The mobile page has a "Logout" link at the bottom of the page. Trying to catch the anchor tag: ``` HtmlElementCollection hec = wbrFacebookAuth.Document.GetElementsByTagName("a"); foreach (HtmlElement elem in hec) { // the logout link has a data-sigil="logout" attribute: string datasigil = elem.GetAttribute("data-sigil").ToLower(); if (datasigil == "logout") { wbrFacebookAuth.Navigate(elem.GetAttribute("href")); break; } } ``` In the Navigated WebBrowser event is unpredictable and unreliable. The actual method of catching it isn't relevant. e.g. This does not work either: ``` string logoutPattern = @"<a href=""(/logout.[^""]+)"""; Regex rx = new Regex(logoutPattern); if (rx.IsMatch(wbMain.DocumentText)) { MatchCollection mc = rx.Matches(wbMain.DocumentText); if (mc.Count > 0) { foreach (Match m in mc) { Console.WriteLine("*** " + m.ToString()); } } } ``` However, it can be caught reliably in the DocumentCompleted event handler. ``` private void wbrFacebookAuth_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { if (_logout) { HtmlElementCollection hec = wbrFacebookAuth.Document.GetElementsByTagName("a"); foreach (HtmlElement elem in hec) { // the logout link has a data-sigil="logout" attribute: string datasigil = elem.GetAttribute("data-sigil").ToLower(); if (datasigil == "logout") { wbrFacebookAuth.Navigate(elem.GetAttribute("href")); break; } } } } ``` The problem is that it is now loading 2 pages instead of 1, and it's still a bit messy. However, it works.
had the same problem with missing log out button and found via google this hint the other day: open <https://developers.facebook.com/?ref=pf> (called "facebook developers site") and there you can find the usual log in/out button again. dont ask me how it works and why it works, I only followed the instructions I found myself and it was working for me good luck, best wishes
6,394,223
I think I've read just about everything out there on the topic of logging out of Facebook inside of a Desktop application. Nothing so far works. Specifically, I would like to log the user out so that they can switch identities, e.g. People sharing a computer at home could then use the software with their own Facebook accounts, but with no chance to switch accounts, it's quite messy. (Have not yet tested switching Windows users accounts as that is simply far too much to ask of the end user and should not be necessary.) Now, I should say that I have set the application to use these permissions: ``` string[] permissions = new string[] { "user_photos", "publish_stream", "offline_access" }; ``` So, "offline\_access" is included there. I do not know if this does/should affect logging out or not. Again, my purpose for logging out is merely to switch users. (If there's a better approach, please let me know.) The purported solutions seem to be: * Use the JavaScript SDK (FB.logout()) * Use "m.facebook.com" instead * Create your own URL (and possibly use m.facebook.com) * Create your own URL and use the session variable (in ASP.NET) The first is kind of silly. Why resort to JavaScript when you're using C#? It's kind of a step backwards and has a lot of additional overhead in a desktop application. (I have not tried this as it's simply disgustingly messy to do this in a desktop application.) If anyone can confirm that this is the only working method, please do so. I'm desperately trying to avoid it. The second doesn't work. Perhaps it worked in the past, but my umpteen attempts to get it to work have all failed. The third doesn't work. I've tried umpteen dozen variations with zero success. The last option there doesn't work for a desktop application because it's not ASP.NET and you don't have a session variable to work with. The Facebook C# SDK logout also no longer works. i.e. ``` public FacebookLoginDialog(string appId, string[] extendedPermissions, bool logout) { IDictionary<string, object> loginParameters = new Dictionary<string, object> { { "response_type", "token" }, { "display", "popup" } }; _navigateUri = FacebookOAuthClient.GetLoginUrl(appId, null, extendedPermissions, logout, loginParameters); InitializeComponent(); } ``` I remember it working in the past, but it no longer works now. (Which truly puzzles me...) It instead now directs the user to the Facebook mobile page, where the user must manually logout. Now, I could do browser automation to automatically click the logout link for the user, however, this is prone to breaking if Facebook updates the mobile UI. It is also messy, and possibly a worse solution than trying to use the JavaScript SDK FB.logout() method (though not by much). I have searched for some kind of documentation, however, I cannot find anything in the Facebook developer documentation that illustrates how to logout an application. Has anyone solved this problem, or seen any documentation that can be ported to work with the Facebook C# SDK? I am certainly open to using a WebClient or HttpClient/Response if anyone can point to some documentation that could work with it. I simply have not been able to find any low-level documentation that shows how this approach could work. Thank you in advance for any advice, pointers, or links.
2011/06/18
[ "https://Stackoverflow.com/questions/6394223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/804186/" ]
This question has been answered [here](https://stackoverflow.com/questions/6023908/facebook-logout-c-sdk), the suggestion is to use the url below to logout since facebook is apparently skipping the "next" parameter ``` https://www.facebook.com/logout.php?next=[redirect_uri]&access_token=[access_token] ```
had the same problem with missing log out button and found via google this hint the other day: open <https://developers.facebook.com/?ref=pf> (called "facebook developers site") and there you can find the usual log in/out button again. dont ask me how it works and why it works, I only followed the instructions I found myself and it was working for me good luck, best wishes
6,394,223
I think I've read just about everything out there on the topic of logging out of Facebook inside of a Desktop application. Nothing so far works. Specifically, I would like to log the user out so that they can switch identities, e.g. People sharing a computer at home could then use the software with their own Facebook accounts, but with no chance to switch accounts, it's quite messy. (Have not yet tested switching Windows users accounts as that is simply far too much to ask of the end user and should not be necessary.) Now, I should say that I have set the application to use these permissions: ``` string[] permissions = new string[] { "user_photos", "publish_stream", "offline_access" }; ``` So, "offline\_access" is included there. I do not know if this does/should affect logging out or not. Again, my purpose for logging out is merely to switch users. (If there's a better approach, please let me know.) The purported solutions seem to be: * Use the JavaScript SDK (FB.logout()) * Use "m.facebook.com" instead * Create your own URL (and possibly use m.facebook.com) * Create your own URL and use the session variable (in ASP.NET) The first is kind of silly. Why resort to JavaScript when you're using C#? It's kind of a step backwards and has a lot of additional overhead in a desktop application. (I have not tried this as it's simply disgustingly messy to do this in a desktop application.) If anyone can confirm that this is the only working method, please do so. I'm desperately trying to avoid it. The second doesn't work. Perhaps it worked in the past, but my umpteen attempts to get it to work have all failed. The third doesn't work. I've tried umpteen dozen variations with zero success. The last option there doesn't work for a desktop application because it's not ASP.NET and you don't have a session variable to work with. The Facebook C# SDK logout also no longer works. i.e. ``` public FacebookLoginDialog(string appId, string[] extendedPermissions, bool logout) { IDictionary<string, object> loginParameters = new Dictionary<string, object> { { "response_type", "token" }, { "display", "popup" } }; _navigateUri = FacebookOAuthClient.GetLoginUrl(appId, null, extendedPermissions, logout, loginParameters); InitializeComponent(); } ``` I remember it working in the past, but it no longer works now. (Which truly puzzles me...) It instead now directs the user to the Facebook mobile page, where the user must manually logout. Now, I could do browser automation to automatically click the logout link for the user, however, this is prone to breaking if Facebook updates the mobile UI. It is also messy, and possibly a worse solution than trying to use the JavaScript SDK FB.logout() method (though not by much). I have searched for some kind of documentation, however, I cannot find anything in the Facebook developer documentation that illustrates how to logout an application. Has anyone solved this problem, or seen any documentation that can be ported to work with the Facebook C# SDK? I am certainly open to using a WebClient or HttpClient/Response if anyone can point to some documentation that could work with it. I simply have not been able to find any low-level documentation that shows how this approach could work. Thank you in advance for any advice, pointers, or links.
2011/06/18
[ "https://Stackoverflow.com/questions/6394223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/804186/" ]
This question has been answered [here](https://stackoverflow.com/questions/6023908/facebook-logout-c-sdk), the suggestion is to use the url below to logout since facebook is apparently skipping the "next" parameter ``` https://www.facebook.com/logout.php?next=[redirect_uri]&access_token=[access_token] ```
I'm guessing you want to log the user out so you can log another account in. In which case I would suggest this approach using the WebAuthenticationBroker: After quite a while experimenting and having no luck with any of the examples above I have worked out that submitting a logout request with the redirect url to your login url works perfectly. Here's the code I used to chain the requests together: ``` var logIn = this.Client.GetLoginUrl( new { client_id = AppId, redirect_uri = App.FacebookAuthUri.AbsoluteUri, scope = AuthTokens.FACEBOOK_PERMISSIONS, display = "popup", response_type = "token" }); var logOut = this.Client.GetLogoutUrl(new { next = logIn, access_token = Settings.FacebookToken.Value }); if (Settings.FacebookToken.Value != null) WebAuthenticationBroker.AuthenticateAndContinue(logOut); ``` Now every time you direct the user to the WebAuthenticationBroker the user will be redirected to the sign in page.
6,394,223
I think I've read just about everything out there on the topic of logging out of Facebook inside of a Desktop application. Nothing so far works. Specifically, I would like to log the user out so that they can switch identities, e.g. People sharing a computer at home could then use the software with their own Facebook accounts, but with no chance to switch accounts, it's quite messy. (Have not yet tested switching Windows users accounts as that is simply far too much to ask of the end user and should not be necessary.) Now, I should say that I have set the application to use these permissions: ``` string[] permissions = new string[] { "user_photos", "publish_stream", "offline_access" }; ``` So, "offline\_access" is included there. I do not know if this does/should affect logging out or not. Again, my purpose for logging out is merely to switch users. (If there's a better approach, please let me know.) The purported solutions seem to be: * Use the JavaScript SDK (FB.logout()) * Use "m.facebook.com" instead * Create your own URL (and possibly use m.facebook.com) * Create your own URL and use the session variable (in ASP.NET) The first is kind of silly. Why resort to JavaScript when you're using C#? It's kind of a step backwards and has a lot of additional overhead in a desktop application. (I have not tried this as it's simply disgustingly messy to do this in a desktop application.) If anyone can confirm that this is the only working method, please do so. I'm desperately trying to avoid it. The second doesn't work. Perhaps it worked in the past, but my umpteen attempts to get it to work have all failed. The third doesn't work. I've tried umpteen dozen variations with zero success. The last option there doesn't work for a desktop application because it's not ASP.NET and you don't have a session variable to work with. The Facebook C# SDK logout also no longer works. i.e. ``` public FacebookLoginDialog(string appId, string[] extendedPermissions, bool logout) { IDictionary<string, object> loginParameters = new Dictionary<string, object> { { "response_type", "token" }, { "display", "popup" } }; _navigateUri = FacebookOAuthClient.GetLoginUrl(appId, null, extendedPermissions, logout, loginParameters); InitializeComponent(); } ``` I remember it working in the past, but it no longer works now. (Which truly puzzles me...) It instead now directs the user to the Facebook mobile page, where the user must manually logout. Now, I could do browser automation to automatically click the logout link for the user, however, this is prone to breaking if Facebook updates the mobile UI. It is also messy, and possibly a worse solution than trying to use the JavaScript SDK FB.logout() method (though not by much). I have searched for some kind of documentation, however, I cannot find anything in the Facebook developer documentation that illustrates how to logout an application. Has anyone solved this problem, or seen any documentation that can be ported to work with the Facebook C# SDK? I am certainly open to using a WebClient or HttpClient/Response if anyone can point to some documentation that could work with it. I simply have not been able to find any low-level documentation that shows how this approach could work. Thank you in advance for any advice, pointers, or links.
2011/06/18
[ "https://Stackoverflow.com/questions/6394223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/804186/" ]
I'm guessing you want to log the user out so you can log another account in. In which case I would suggest this approach using the WebAuthenticationBroker: After quite a while experimenting and having no luck with any of the examples above I have worked out that submitting a logout request with the redirect url to your login url works perfectly. Here's the code I used to chain the requests together: ``` var logIn = this.Client.GetLoginUrl( new { client_id = AppId, redirect_uri = App.FacebookAuthUri.AbsoluteUri, scope = AuthTokens.FACEBOOK_PERMISSIONS, display = "popup", response_type = "token" }); var logOut = this.Client.GetLogoutUrl(new { next = logIn, access_token = Settings.FacebookToken.Value }); if (Settings.FacebookToken.Value != null) WebAuthenticationBroker.AuthenticateAndContinue(logOut); ``` Now every time you direct the user to the WebAuthenticationBroker the user will be redirected to the sign in page.
had the same problem with missing log out button and found via google this hint the other day: open <https://developers.facebook.com/?ref=pf> (called "facebook developers site") and there you can find the usual log in/out button again. dont ask me how it works and why it works, I only followed the instructions I found myself and it was working for me good luck, best wishes
71,878,186
Here is the error message > > JavaScript compilation error: Uncaught SyntaxError: Unexpected token '>' in HP\_SEARCHCBHMESSAGES at ' if (Fac123 <> "") ' position 1.. > > > Some reason SF doesn't like if condition (Fac123 <> "" ), have tried if (Fac123 <> '' ) but same error Please help! ``` CALL PROC1('param1' ) CREATE OR REPLACE PROCEDURE PROC1("param1" nvarchar(100) ) returns varchar language javascript AS $$ var Fac123 = param1 **if (Fac123 <> "" )** { sql12 = " AND " } return sql12 ; ```
2022/04/14
[ "https://Stackoverflow.com/questions/71878186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1810575/" ]
Inside a JavaScript procedure the only valid language to use is Javascript. Therefore you have to use a javascript "not equals" which is `!==` ``` CREATE OR REPLACE PROCEDURE PROC1("param1" nvarchar(100) ) returns varchar language javascript AS $$ var Fac123 = param1 if (Fac123 !== "" ) { sql12 = " AND " } return sql12 ; $$; ``` now it can be used ``` call PROC1('blar'); ``` gives: | PROC1 | | --- | | AND | but passing in an empty string.. ``` call PROC1(''); ``` gives an error, because your code doesn't handle that path yet. > > 100132 (P0000): JavaScript execution error: Uncaught ReferenceError: sql12 is not defined in PROC1 at 'return sql12 ;' position 0 > > > stackstrace: > > > PROC1 line: 8 > > >
Need to fix 'if' statement and put semi-colon after var declaration, please refer below - Error Code - ``` CREATE OR REPLACE PROCEDURE PROC1("param1" nvarchar(100) ) returns varchar language javascript AS $$ var Fac123 = param1 if (Fac123 <> "" ) { sql12 = " AND " } return sql12 ; $$ ; +--------------------------------------+ | status | |--------------------------------------| | Function PROC1 successfully created. | +--------------------------------------+ 1 Row(s) produced. Time Elapsed: 0.151s CALL PROC1('param1' ); 100131 (P0000): JavaScript compilation error: Uncaught SyntaxError: Unexpected token '>' in PROC1 at 'if (Fac123 <> "" )' position 12 ``` Fixed code - ``` CREATE OR REPLACE PROCEDURE PROC1("param1" nvarchar(100) ) returns varchar language javascript AS $$ var Fac123 = param1; if (Fac123 != "" ) { sql12 = " AND " } return sql12 ; $$ ; +--------------------------------------+ | status | |--------------------------------------| | Function PROC1 successfully created. | +--------------------------------------+ CALL PROC1('param1' ); +-------+ | PROC1 | |-------| | AND | +-------+ ```
71,878,186
Here is the error message > > JavaScript compilation error: Uncaught SyntaxError: Unexpected token '>' in HP\_SEARCHCBHMESSAGES at ' if (Fac123 <> "") ' position 1.. > > > Some reason SF doesn't like if condition (Fac123 <> "" ), have tried if (Fac123 <> '' ) but same error Please help! ``` CALL PROC1('param1' ) CREATE OR REPLACE PROCEDURE PROC1("param1" nvarchar(100) ) returns varchar language javascript AS $$ var Fac123 = param1 **if (Fac123 <> "" )** { sql12 = " AND " } return sql12 ; ```
2022/04/14
[ "https://Stackoverflow.com/questions/71878186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1810575/" ]
The provided code suggests a trial to build a code generator, a pattern called kitchen sink(i.e. if a parameter is provided it should be included otherwise removed from WHERE condion). Alternative approach is to simply use NULL safe comparison. If the missing value is passed as empty string then: ``` SELECT * FROM ... WHERE ... AND col IS NOT DISTINCT FROM COALESCE(NULLIF("param1", ''), col) ``` If the missing value is passed as NULL from the app then it is much simpler: ``` SELECT * FROM ... WHERE ... AND col IS NOT DISTINCT FROM COALESCE("param1", col) ``` --- This way all to stack the conditions in advance using `AND`: ``` SELECT * FROM ... WHERE ... AND col IS NOT DISTINCT FROM COALESCE("param1", col) AND col2 IS NOT DISTINCT FROM COALESCE("param2", col2) AND col3 IS NOT DISTINCT FROM COALESCE("param3", col3) -- ... ``` Params provided as NULL are defaulted to `colX` and `colX <=> colX` is always true.
Need to fix 'if' statement and put semi-colon after var declaration, please refer below - Error Code - ``` CREATE OR REPLACE PROCEDURE PROC1("param1" nvarchar(100) ) returns varchar language javascript AS $$ var Fac123 = param1 if (Fac123 <> "" ) { sql12 = " AND " } return sql12 ; $$ ; +--------------------------------------+ | status | |--------------------------------------| | Function PROC1 successfully created. | +--------------------------------------+ 1 Row(s) produced. Time Elapsed: 0.151s CALL PROC1('param1' ); 100131 (P0000): JavaScript compilation error: Uncaught SyntaxError: Unexpected token '>' in PROC1 at 'if (Fac123 <> "" )' position 12 ``` Fixed code - ``` CREATE OR REPLACE PROCEDURE PROC1("param1" nvarchar(100) ) returns varchar language javascript AS $$ var Fac123 = param1; if (Fac123 != "" ) { sql12 = " AND " } return sql12 ; $$ ; +--------------------------------------+ | status | |--------------------------------------| | Function PROC1 successfully created. | +--------------------------------------+ CALL PROC1('param1' ); +-------+ | PROC1 | |-------| | AND | +-------+ ```
71,878,186
Here is the error message > > JavaScript compilation error: Uncaught SyntaxError: Unexpected token '>' in HP\_SEARCHCBHMESSAGES at ' if (Fac123 <> "") ' position 1.. > > > Some reason SF doesn't like if condition (Fac123 <> "" ), have tried if (Fac123 <> '' ) but same error Please help! ``` CALL PROC1('param1' ) CREATE OR REPLACE PROCEDURE PROC1("param1" nvarchar(100) ) returns varchar language javascript AS $$ var Fac123 = param1 **if (Fac123 <> "" )** { sql12 = " AND " } return sql12 ; ```
2022/04/14
[ "https://Stackoverflow.com/questions/71878186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1810575/" ]
Inside a JavaScript procedure the only valid language to use is Javascript. Therefore you have to use a javascript "not equals" which is `!==` ``` CREATE OR REPLACE PROCEDURE PROC1("param1" nvarchar(100) ) returns varchar language javascript AS $$ var Fac123 = param1 if (Fac123 !== "" ) { sql12 = " AND " } return sql12 ; $$; ``` now it can be used ``` call PROC1('blar'); ``` gives: | PROC1 | | --- | | AND | but passing in an empty string.. ``` call PROC1(''); ``` gives an error, because your code doesn't handle that path yet. > > 100132 (P0000): JavaScript execution error: Uncaught ReferenceError: sql12 is not defined in PROC1 at 'return sql12 ;' position 0 > > > stackstrace: > > > PROC1 line: 8 > > >
The provided code suggests a trial to build a code generator, a pattern called kitchen sink(i.e. if a parameter is provided it should be included otherwise removed from WHERE condion). Alternative approach is to simply use NULL safe comparison. If the missing value is passed as empty string then: ``` SELECT * FROM ... WHERE ... AND col IS NOT DISTINCT FROM COALESCE(NULLIF("param1", ''), col) ``` If the missing value is passed as NULL from the app then it is much simpler: ``` SELECT * FROM ... WHERE ... AND col IS NOT DISTINCT FROM COALESCE("param1", col) ``` --- This way all to stack the conditions in advance using `AND`: ``` SELECT * FROM ... WHERE ... AND col IS NOT DISTINCT FROM COALESCE("param1", col) AND col2 IS NOT DISTINCT FROM COALESCE("param2", col2) AND col3 IS NOT DISTINCT FROM COALESCE("param3", col3) -- ... ``` Params provided as NULL are defaulted to `colX` and `colX <=> colX` is always true.
21,975,881
I'm wondering how to select an element that does not have a specific class using JavaScript, not jQuery. For example, I have this list: ``` <ul id="tasks"> <li class="completed selected">One Task</li> <li>Two Task</li> </ul> ``` and I select the completed task by: ``` var completeTask = document.querySelector("li.completed.selected"); ``` But then I'm not sure how to select the list item that does not have those classes.
2014/02/23
[ "https://Stackoverflow.com/questions/21975881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2741060/" ]
This selects the second `LI` element. ``` document.querySelector("li:not([class])") ``` or ``` document.querySelector("li:not(.completed):not(.selected)") ``` **Example:** ```js // select li which doesn't have a 'class' attribute... console.log(document.querySelector("li:not([class])")) // select li which doesn't have a '.completed' and a '.selected' class... console.log(document.querySelector("li:not(.completed):not(.selected)")) ``` ```html  <ul id="tasks"> <li class="completed selected">One Task</li> <li>Two Task</li> </ul> ```
``` document.querySelectorAll('[wf-body=details] input:not(.switch):not(.btn)').forEach(function(e){ // do whatever you want. with 'e' as element :P }); ```
21,975,881
I'm wondering how to select an element that does not have a specific class using JavaScript, not jQuery. For example, I have this list: ``` <ul id="tasks"> <li class="completed selected">One Task</li> <li>Two Task</li> </ul> ``` and I select the completed task by: ``` var completeTask = document.querySelector("li.completed.selected"); ``` But then I'm not sure how to select the list item that does not have those classes.
2014/02/23
[ "https://Stackoverflow.com/questions/21975881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2741060/" ]
This selects the second `LI` element. ``` document.querySelector("li:not([class])") ``` or ``` document.querySelector("li:not(.completed):not(.selected)") ``` **Example:** ```js // select li which doesn't have a 'class' attribute... console.log(document.querySelector("li:not([class])")) // select li which doesn't have a '.completed' and a '.selected' class... console.log(document.querySelector("li:not(.completed):not(.selected)")) ``` ```html  <ul id="tasks"> <li class="completed selected">One Task</li> <li>Two Task</li> </ul> ```
The `:not(*selector*)` selector also accepts commas (so does `querySelectorAll()`) <https://developer.mozilla.org/en-US/docs/Web/CSS/:not#syntax>: ```js let plainElements = document.querySelectorAll( ':not( .completed, .in-progress ) '); plainElements.forEach( ( item ) => { item.style.color = 'red'; } ); ``` ```css li { color: green; } ``` ```html <ul id="tasks"> <li class="completed selected">Task 1</li> <li>Task 2</li> <li class="in-progress">Task 3</li> </ul> ```
21,975,881
I'm wondering how to select an element that does not have a specific class using JavaScript, not jQuery. For example, I have this list: ``` <ul id="tasks"> <li class="completed selected">One Task</li> <li>Two Task</li> </ul> ``` and I select the completed task by: ``` var completeTask = document.querySelector("li.completed.selected"); ``` But then I'm not sure how to select the list item that does not have those classes.
2014/02/23
[ "https://Stackoverflow.com/questions/21975881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2741060/" ]
You can try the `:not()` selector ``` var completeTask = document.querySelector("li:not(.completed):not(.selected)"); ``` <http://jsfiddle.net/UM3j5/>
``` document.querySelectorAll('[wf-body=details] input:not(.switch):not(.btn)').forEach(function(e){ // do whatever you want. with 'e' as element :P }); ```
21,975,881
I'm wondering how to select an element that does not have a specific class using JavaScript, not jQuery. For example, I have this list: ``` <ul id="tasks"> <li class="completed selected">One Task</li> <li>Two Task</li> </ul> ``` and I select the completed task by: ``` var completeTask = document.querySelector("li.completed.selected"); ``` But then I'm not sure how to select the list item that does not have those classes.
2014/02/23
[ "https://Stackoverflow.com/questions/21975881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2741060/" ]
This selects the second `LI` element. ``` document.querySelector("li:not([class])") ``` or ``` document.querySelector("li:not(.completed):not(.selected)") ``` **Example:** ```js // select li which doesn't have a 'class' attribute... console.log(document.querySelector("li:not([class])")) // select li which doesn't have a '.completed' and a '.selected' class... console.log(document.querySelector("li:not(.completed):not(.selected)")) ``` ```html  <ul id="tasks"> <li class="completed selected">One Task</li> <li>Two Task</li> </ul> ```
To select the `<li>` that has not `completed` nor `selected` class: ``` document.querySelector("li:not(.completed):not(.selected)"); ``` **Fiddle** <http://jsfiddle.net/Z8djF/>
21,975,881
I'm wondering how to select an element that does not have a specific class using JavaScript, not jQuery. For example, I have this list: ``` <ul id="tasks"> <li class="completed selected">One Task</li> <li>Two Task</li> </ul> ``` and I select the completed task by: ``` var completeTask = document.querySelector("li.completed.selected"); ``` But then I'm not sure how to select the list item that does not have those classes.
2014/02/23
[ "https://Stackoverflow.com/questions/21975881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2741060/" ]
This selects the second `LI` element. ``` document.querySelector("li:not([class])") ``` or ``` document.querySelector("li:not(.completed):not(.selected)") ``` **Example:** ```js // select li which doesn't have a 'class' attribute... console.log(document.querySelector("li:not([class])")) // select li which doesn't have a '.completed' and a '.selected' class... console.log(document.querySelector("li:not(.completed):not(.selected)")) ``` ```html  <ul id="tasks"> <li class="completed selected">One Task</li> <li>Two Task</li> </ul> ```
Try getting an array of the parent's children instead: ``` var completeTask = document.querySelector("#tasks").childNodes; ``` Then loop/search them as necessary.
21,975,881
I'm wondering how to select an element that does not have a specific class using JavaScript, not jQuery. For example, I have this list: ``` <ul id="tasks"> <li class="completed selected">One Task</li> <li>Two Task</li> </ul> ``` and I select the completed task by: ``` var completeTask = document.querySelector("li.completed.selected"); ``` But then I'm not sure how to select the list item that does not have those classes.
2014/02/23
[ "https://Stackoverflow.com/questions/21975881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2741060/" ]
To select the `<li>` that has not `completed` nor `selected` class: ``` document.querySelector("li:not(.completed):not(.selected)"); ``` **Fiddle** <http://jsfiddle.net/Z8djF/>
You can try the `:not()` selector ``` var completeTask = document.querySelector("li:not(.completed):not(.selected)"); ``` <http://jsfiddle.net/UM3j5/>
21,975,881
I'm wondering how to select an element that does not have a specific class using JavaScript, not jQuery. For example, I have this list: ``` <ul id="tasks"> <li class="completed selected">One Task</li> <li>Two Task</li> </ul> ``` and I select the completed task by: ``` var completeTask = document.querySelector("li.completed.selected"); ``` But then I'm not sure how to select the list item that does not have those classes.
2014/02/23
[ "https://Stackoverflow.com/questions/21975881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2741060/" ]
The `:not(*selector*)` selector also accepts commas (so does `querySelectorAll()`) <https://developer.mozilla.org/en-US/docs/Web/CSS/:not#syntax>: ```js let plainElements = document.querySelectorAll( ':not( .completed, .in-progress ) '); plainElements.forEach( ( item ) => { item.style.color = 'red'; } ); ``` ```css li { color: green; } ``` ```html <ul id="tasks"> <li class="completed selected">Task 1</li> <li>Task 2</li> <li class="in-progress">Task 3</li> </ul> ```
Try getting an array of the parent's children instead: ``` var completeTask = document.querySelector("#tasks").childNodes; ``` Then loop/search them as necessary.
21,975,881
I'm wondering how to select an element that does not have a specific class using JavaScript, not jQuery. For example, I have this list: ``` <ul id="tasks"> <li class="completed selected">One Task</li> <li>Two Task</li> </ul> ``` and I select the completed task by: ``` var completeTask = document.querySelector("li.completed.selected"); ``` But then I'm not sure how to select the list item that does not have those classes.
2014/02/23
[ "https://Stackoverflow.com/questions/21975881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2741060/" ]
To select the `<li>` that has not `completed` nor `selected` class: ``` document.querySelector("li:not(.completed):not(.selected)"); ``` **Fiddle** <http://jsfiddle.net/Z8djF/>
``` document.querySelectorAll('[wf-body=details] input:not(.switch):not(.btn)').forEach(function(e){ // do whatever you want. with 'e' as element :P }); ```
21,975,881
I'm wondering how to select an element that does not have a specific class using JavaScript, not jQuery. For example, I have this list: ``` <ul id="tasks"> <li class="completed selected">One Task</li> <li>Two Task</li> </ul> ``` and I select the completed task by: ``` var completeTask = document.querySelector("li.completed.selected"); ``` But then I'm not sure how to select the list item that does not have those classes.
2014/02/23
[ "https://Stackoverflow.com/questions/21975881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2741060/" ]
This selects the second `LI` element. ``` document.querySelector("li:not([class])") ``` or ``` document.querySelector("li:not(.completed):not(.selected)") ``` **Example:** ```js // select li which doesn't have a 'class' attribute... console.log(document.querySelector("li:not([class])")) // select li which doesn't have a '.completed' and a '.selected' class... console.log(document.querySelector("li:not(.completed):not(.selected)")) ``` ```html  <ul id="tasks"> <li class="completed selected">One Task</li> <li>Two Task</li> </ul> ```
You can try the `:not()` selector ``` var completeTask = document.querySelector("li:not(.completed):not(.selected)"); ``` <http://jsfiddle.net/UM3j5/>
21,975,881
I'm wondering how to select an element that does not have a specific class using JavaScript, not jQuery. For example, I have this list: ``` <ul id="tasks"> <li class="completed selected">One Task</li> <li>Two Task</li> </ul> ``` and I select the completed task by: ``` var completeTask = document.querySelector("li.completed.selected"); ``` But then I'm not sure how to select the list item that does not have those classes.
2014/02/23
[ "https://Stackoverflow.com/questions/21975881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2741060/" ]
``` document.querySelectorAll('[wf-body=details] input:not(.switch):not(.btn)').forEach(function(e){ // do whatever you want. with 'e' as element :P }); ```
Try getting an array of the parent's children instead: ``` var completeTask = document.querySelector("#tasks").childNodes; ``` Then loop/search them as necessary.
34,529,557
I want to create a simple `Angular2` Application using `TypeScript`. Seems, pretty simple, but I am not able to achieve what I wanted to. I want to show a property value in the template. And I want to update the same after 1 second using setTimeout. Plunkr Code is here : [Code on Plunkr](http://plnkr.co/edit/RhYhVS84wnOdPuhYUG1E?p=preview) What I wrote is here : ``` import {Component} from 'angular2/core'; interface Hero { id: number; name: string; } @Component({ selector: 'my-app', template:`<h1>Number Increment</h1><p>{{n}}</p>` }) export class AppComponent { public n : number = 1; setTimeout(function() { n = n + 10; }, 1000); } ``` When I use this code I am getting following error : ``` Uncaught SyntaxError: Unexpected token ; ``` Why I am not able to access `n`, which is in the same scope as we used to do in JavaScript. If I am not wrong, we can use pure JavaScript too in TypeScript. I even tried ``` export class AppComponent { public n : number = 1; console.log(n); } ``` But I am not able to see the value of `n` in the console. When I tried ``` export class AppComponent { public n : number = 1; console.log(this); } ``` I am getting same error as above. Why cant we access this in this place. I guess, `this` refers to the current context as in JavaScript. Thanks in advance.
2015/12/30
[ "https://Stackoverflow.com/questions/34529557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3467552/" ]
This is not valid TypeScript code. You can not have method invocations in the body of a class. ```js // INVALID CODE export class AppComponent { public n: number = 1; setTimeout(function() { n = n + 10; }, 1000); } ``` Instead move the `setTimeout` call to the `constructor` of the class. Additionally, use the arrow function `=>` to gain access to `this`. ```js export class AppComponent { public n: number = 1; constructor() { setTimeout(() => { this.n = this.n + 10; }, 1000); } } ``` In TypeScript, you can only refer to class properties or methods via `this`. That's why the arrow function `=>` is important.
You should put your processing into the class constructor or an `OnInit` hook method.
5,892,956
I am trying to minimize my code by putting it into an array but nothing happens. I can't figure out what I am doing wrong. Here's the code ``` <html> <head> <title>test</title> <!-- JavaScript --> <script src="js/jquery-1.5.2.js" type="text/javascript"></script> <script type="text/javascript"> var phpfile = new Object(); phpfile["testselect"] = "zoomchange.php"; var elementID = new Object(); elementID["testselect"] = "#testdiv"; $(document).ready(function(){ $("select").change(function() { $.post( phpfile[$(this).id()], $(this).serialize(), function(data) { $(elementID[$(this).id()]).html(data) } ); }); }); </script> </head> <body> <select id="testselect"> <option value="1">1</option> <option value="2">2</option> </select> <div id="testdiv"></div> </body> </html> ``` here is the zoomchange.php: ``` <?PHP echo $_REQUEST['testselect'] ; ?> ```
2011/05/05
[ "https://Stackoverflow.com/questions/5892956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/729678/" ]
Your initializers shouldn't look like this: ``` var phpfile = new Array(); phpfile["testselect"] = "zoomchange.php"; var elementID = new Array(); elementID["testselect"] = "#testdiv"; ``` A JavaScript Array is indexed by numbers, not strings. You want simple object literals: ``` var phpfile = { testselect: 'zoomchange.php' }; var elementED = { testselect: '#testdiv' }; ``` Then, your POST callback is confused: ``` function(data) { $(elementID[$(this).id()]).html(data) } ``` `this` isn't what you think it is when that function is called. You want something more like this: ``` $("select").change(function() { var that = this; $.post( phpfile[that.id], $(this).serialize(), function(data) { $(elementID[that.id]).html(data); } ); }); ```
You should do `new Object()` instead of `new Array()`. **Edit**: There are other mistakes, your js code should be this: ``` <script type="text/javascript"> var phpfile = {}; phpfile["testselect"] = "zoomchange.php"; var elementID = {}; elementID["testselect"] = "#testdiv"; $(document).ready(function(){ $("select").change(function() { var $select = $(this); $.post( phpfile[$select.attr("id")], $select.serialize(), function(data) { $(elementID[$select.attr("id")]).html(data) } ); }); }); </script> ```
5,892,956
I am trying to minimize my code by putting it into an array but nothing happens. I can't figure out what I am doing wrong. Here's the code ``` <html> <head> <title>test</title> <!-- JavaScript --> <script src="js/jquery-1.5.2.js" type="text/javascript"></script> <script type="text/javascript"> var phpfile = new Object(); phpfile["testselect"] = "zoomchange.php"; var elementID = new Object(); elementID["testselect"] = "#testdiv"; $(document).ready(function(){ $("select").change(function() { $.post( phpfile[$(this).id()], $(this).serialize(), function(data) { $(elementID[$(this).id()]).html(data) } ); }); }); </script> </head> <body> <select id="testselect"> <option value="1">1</option> <option value="2">2</option> </select> <div id="testdiv"></div> </body> </html> ``` here is the zoomchange.php: ``` <?PHP echo $_REQUEST['testselect'] ; ?> ```
2011/05/05
[ "https://Stackoverflow.com/questions/5892956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/729678/" ]
Your initializers shouldn't look like this: ``` var phpfile = new Array(); phpfile["testselect"] = "zoomchange.php"; var elementID = new Array(); elementID["testselect"] = "#testdiv"; ``` A JavaScript Array is indexed by numbers, not strings. You want simple object literals: ``` var phpfile = { testselect: 'zoomchange.php' }; var elementED = { testselect: '#testdiv' }; ``` Then, your POST callback is confused: ``` function(data) { $(elementID[$(this).id()]).html(data) } ``` `this` isn't what you think it is when that function is called. You want something more like this: ``` $("select").change(function() { var that = this; $.post( phpfile[that.id], $(this).serialize(), function(data) { $(elementID[that.id]).html(data); } ); }); ```
This ``` function(data) { $(elementID[$(this).id()]).html(data); } ``` instead of this ``` function(data) { $(elementID[$(this).id()]).html(data) } ``` Is this the error ?
9,243,578
I am having the following problem in Java (I see some people are having a similar problem in JavaScript but I'm using Java) ``` System.out.println(new Date().getYear()); System.out.println(new GregorianCalendar().getTime().getYear()); System.out.println(this.sale.getSaleDate().getYear()); System.out.println(this.sale.getSaleDate().getMonth()); System.out.println(this.sale.getSaleDate().getDate()); ``` returns ``` I/System.out( 4274): 112 I/System.out( 4274): 112 I/System.out( 4274): 112 I/System.out( 4274): 1 I/System.out( 4274): 11 ``` I don't understand the 112 bit which I thought would have been 2012. What's going on? Is the `java.util.Date` class unusable? I am storing this as a field in several of my classes to store a date and time. What should I do?
2012/02/11
[ "https://Stackoverflow.com/questions/9243578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1139027/" ]
Don't use `Date`, use `Calendar`: ``` // Beware: months are zero-based and no out of range errors are reported Calendar date = new GregorianCalendar(2012, 9, 5); int year = date.get(Calendar.YEAR); // 2012 int month = date.get(Calendar.MONTH); // 9 - October!!! int day = date.get(Calendar.DAY_OF_MONTH); // 5 ``` It supports time as well: ``` Calendar dateTime = new GregorianCalendar(2012, 3, 4, 15, 16, 17); int hour = dateTime.get(Calendar.HOUR_OF_DAY); // 15 int minute = dateTime.get(Calendar.MINUTE); // 16 int second = dateTime.get(Calendar.SECOND); // 17 ```
``` try{ int year = Integer.parseInt(new Date().toString().split("-")[0]); } catch(NumberFormatException e){ } ``` Much of Date is deprecated.
9,243,578
I am having the following problem in Java (I see some people are having a similar problem in JavaScript but I'm using Java) ``` System.out.println(new Date().getYear()); System.out.println(new GregorianCalendar().getTime().getYear()); System.out.println(this.sale.getSaleDate().getYear()); System.out.println(this.sale.getSaleDate().getMonth()); System.out.println(this.sale.getSaleDate().getDate()); ``` returns ``` I/System.out( 4274): 112 I/System.out( 4274): 112 I/System.out( 4274): 112 I/System.out( 4274): 1 I/System.out( 4274): 11 ``` I don't understand the 112 bit which I thought would have been 2012. What's going on? Is the `java.util.Date` class unusable? I am storing this as a field in several of my classes to store a date and time. What should I do?
2012/02/11
[ "https://Stackoverflow.com/questions/9243578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1139027/" ]
tl;dr ===== ``` LocalDate.now() // Capture the date-only value current in the JVM’s current default time zone. .getYear() // Extract the year number from that date. ``` > > 2018 > > > java.time ========= Both the `java.util.Date` and `java.util.Calendar` classes are legacy, now supplanted by the java.time framework built into Java 8 and later. A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in [Paris France](https://en.wikipedia.org/wiki/Europe/Paris) is a new day while still “yesterday” in [Montréal Québec](https://en.wikipedia.org/wiki/America/Montreal). If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment, so your results may vary. Better to specify your desired/expected time zone explicitly as an argument. Specify a [proper time zone name](https://en.wikipedia.org/wiki/List_of_tz_zones_by_name) in the format of `continent/region`, such as [`America/Montreal`](https://en.wikipedia.org/wiki/America/Montreal), [`Africa/Casablanca`](https://en.wikipedia.org/wiki/Africa/Casablanca), or `Pacific/Auckland`. Never use the 3-4 letter abbreviation such as `EST` or `IST` as they are *not* true time zones, not standardized, and not even unique(!). ``` ZoneId z = ZoneId.of( "Africa/Tunis" ) ; ``` If you want only the date without time-of-day, use [`LocalDate`](https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html). This class lacks time zone info but you can specify a time zone to determine the current date. ``` ZoneId zoneId = ZoneId.of( "America/Montreal" ); LocalDate localDate = LocalDate.now( zoneId ); ``` You can get the various pieces of information with `getYear`, `getMonth`, and `getDayOfMonth`. You will actually get the year number with java.time! ``` int year = localDate.getYear(); ``` > > 2016 > > > If you want a date-time instead of just a date, use [`ZonedDateTime`](https://docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html) class. ``` ZonedDateTime zdt = ZonedDateTime.now( zoneId ) ; ``` --- About java.time =============== The [java.time](http://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/9/docs/api/java/util/Date.html), [`.Calendar`](https://docs.oracle.com/javase/9/docs/api/java/util/Calendar.html), & [`java.text.SimpleDateFormat`](http://docs.oracle.com/javase/9/docs/api/java/text/SimpleDateFormat.html). The [Joda-Time](http://www.joda.org/joda-time/) project, now in [maintenance mode](https://en.wikipedia.org/wiki/Maintenance_mode), advises migration to the [java.time](https://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) classes. To learn more, see the [Oracle Tutorial](http://docs.oracle.com/javase/tutorial/datetime/TOC.html). And search Stack Overflow for many examples and explanations. Much of the *java.time* functionality is back-ported to Java 6 & Java 7 in [ThreeTen-Backport](http://www.threeten.org/threetenbp/) and further adapted to [Android](https://en.wikipedia.org/wiki/Android_(operating_system)) in [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) (see [*How to use…*](http://stackoverflow.com/q/38922754/642706)). The [ThreeTen-Extra](http://www.threeten.org/threeten-extra/) project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as [`Interval`](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/Interval.html), [`YearWeek`](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearWeek.html), [`YearQuarter`](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearQuarter.html), and [more](http://www.threeten.org/threeten-extra/apidocs/index.html).
This behavior is documented in the [java.util.Date](http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Date.html#getYear%28%29) -class documentation: > > Returns a value that is the result of subtracting 1900 from the year > that contains or begins with the instant in time represented by this > Date object, as interpreted in the local time zone. > > > It is also marked as deprecated. Use [java.util.Calendar](http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html) instead.
9,243,578
I am having the following problem in Java (I see some people are having a similar problem in JavaScript but I'm using Java) ``` System.out.println(new Date().getYear()); System.out.println(new GregorianCalendar().getTime().getYear()); System.out.println(this.sale.getSaleDate().getYear()); System.out.println(this.sale.getSaleDate().getMonth()); System.out.println(this.sale.getSaleDate().getDate()); ``` returns ``` I/System.out( 4274): 112 I/System.out( 4274): 112 I/System.out( 4274): 112 I/System.out( 4274): 1 I/System.out( 4274): 11 ``` I don't understand the 112 bit which I thought would have been 2012. What's going on? Is the `java.util.Date` class unusable? I am storing this as a field in several of my classes to store a date and time. What should I do?
2012/02/11
[ "https://Stackoverflow.com/questions/9243578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1139027/" ]
Use date format ``` SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = format.parse(datetime); SimpleDateFormat df = new SimpleDateFormat("yyyy"); year = df.format(date); ```
Yup, this is in fact what's happening. See also the [Javadoc](http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#getYear%28%29): > > > ``` > Returns: > the year represented by this date, minus 1900. > > ``` > > The getYear method is deprecated for this reason. So, don't use it. Note also that getMonth returns a number between 0 and 11. Therefore, `this.sale.getSaleDate().getMonth()` returns 1 for February, instead of 2. While `java.util.Calendar` doesn't add 1900 to all years, it does suffer from the off-by-one-month problem. You're much better off using [JodaTime](http://joda-time.sourceforge.net/).
9,243,578
I am having the following problem in Java (I see some people are having a similar problem in JavaScript but I'm using Java) ``` System.out.println(new Date().getYear()); System.out.println(new GregorianCalendar().getTime().getYear()); System.out.println(this.sale.getSaleDate().getYear()); System.out.println(this.sale.getSaleDate().getMonth()); System.out.println(this.sale.getSaleDate().getDate()); ``` returns ``` I/System.out( 4274): 112 I/System.out( 4274): 112 I/System.out( 4274): 112 I/System.out( 4274): 1 I/System.out( 4274): 11 ``` I don't understand the 112 bit which I thought would have been 2012. What's going on? Is the `java.util.Date` class unusable? I am storing this as a field in several of my classes to store a date and time. What should I do?
2012/02/11
[ "https://Stackoverflow.com/questions/9243578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1139027/" ]
According to javadocs: ``` @Deprecated public int getYear() ``` **Deprecated**. As of JDK version 1.1, replaced by `Calendar.get(Calendar.YEAR) - 1900`. Returns a value that is the result of subtracting 1900 from the year that contains or begins with the instant in time represented by this Date object, as interpreted in the local time zone. **Returns:** the year represented by this date, minus 1900. **See Also:** [Calendar](http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html) So 112 is the correct output. I would follow the advice in the Javadoc or use JodaTime instead.
Java 8 LocalDate class is another option to get the year from a java.util.Date, ``` int year = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date)).getYear(); ``` Another option is, ``` int year = Integer.parseInt(new SimpleDateFormat("yyyy").format(date)); ```
9,243,578
I am having the following problem in Java (I see some people are having a similar problem in JavaScript but I'm using Java) ``` System.out.println(new Date().getYear()); System.out.println(new GregorianCalendar().getTime().getYear()); System.out.println(this.sale.getSaleDate().getYear()); System.out.println(this.sale.getSaleDate().getMonth()); System.out.println(this.sale.getSaleDate().getDate()); ``` returns ``` I/System.out( 4274): 112 I/System.out( 4274): 112 I/System.out( 4274): 112 I/System.out( 4274): 1 I/System.out( 4274): 11 ``` I don't understand the 112 bit which I thought would have been 2012. What's going on? Is the `java.util.Date` class unusable? I am storing this as a field in several of my classes to store a date and time. What should I do?
2012/02/11
[ "https://Stackoverflow.com/questions/9243578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1139027/" ]
Don't use `Date`, use `Calendar`: ``` // Beware: months are zero-based and no out of range errors are reported Calendar date = new GregorianCalendar(2012, 9, 5); int year = date.get(Calendar.YEAR); // 2012 int month = date.get(Calendar.MONTH); // 9 - October!!! int day = date.get(Calendar.DAY_OF_MONTH); // 5 ``` It supports time as well: ``` Calendar dateTime = new GregorianCalendar(2012, 3, 4, 15, 16, 17); int hour = dateTime.get(Calendar.HOUR_OF_DAY); // 15 int minute = dateTime.get(Calendar.MINUTE); // 16 int second = dateTime.get(Calendar.SECOND); // 17 ```
Yup, this is in fact what's happening. See also the [Javadoc](http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#getYear%28%29): > > > ``` > Returns: > the year represented by this date, minus 1900. > > ``` > > The getYear method is deprecated for this reason. So, don't use it. Note also that getMonth returns a number between 0 and 11. Therefore, `this.sale.getSaleDate().getMonth()` returns 1 for February, instead of 2. While `java.util.Calendar` doesn't add 1900 to all years, it does suffer from the off-by-one-month problem. You're much better off using [JodaTime](http://joda-time.sourceforge.net/).
9,243,578
I am having the following problem in Java (I see some people are having a similar problem in JavaScript but I'm using Java) ``` System.out.println(new Date().getYear()); System.out.println(new GregorianCalendar().getTime().getYear()); System.out.println(this.sale.getSaleDate().getYear()); System.out.println(this.sale.getSaleDate().getMonth()); System.out.println(this.sale.getSaleDate().getDate()); ``` returns ``` I/System.out( 4274): 112 I/System.out( 4274): 112 I/System.out( 4274): 112 I/System.out( 4274): 1 I/System.out( 4274): 11 ``` I don't understand the 112 bit which I thought would have been 2012. What's going on? Is the `java.util.Date` class unusable? I am storing this as a field in several of my classes to store a date and time. What should I do?
2012/02/11
[ "https://Stackoverflow.com/questions/9243578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1139027/" ]
tl;dr ===== ``` LocalDate.now() // Capture the date-only value current in the JVM’s current default time zone. .getYear() // Extract the year number from that date. ``` > > 2018 > > > java.time ========= Both the `java.util.Date` and `java.util.Calendar` classes are legacy, now supplanted by the java.time framework built into Java 8 and later. A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in [Paris France](https://en.wikipedia.org/wiki/Europe/Paris) is a new day while still “yesterday” in [Montréal Québec](https://en.wikipedia.org/wiki/America/Montreal). If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment, so your results may vary. Better to specify your desired/expected time zone explicitly as an argument. Specify a [proper time zone name](https://en.wikipedia.org/wiki/List_of_tz_zones_by_name) in the format of `continent/region`, such as [`America/Montreal`](https://en.wikipedia.org/wiki/America/Montreal), [`Africa/Casablanca`](https://en.wikipedia.org/wiki/Africa/Casablanca), or `Pacific/Auckland`. Never use the 3-4 letter abbreviation such as `EST` or `IST` as they are *not* true time zones, not standardized, and not even unique(!). ``` ZoneId z = ZoneId.of( "Africa/Tunis" ) ; ``` If you want only the date without time-of-day, use [`LocalDate`](https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html). This class lacks time zone info but you can specify a time zone to determine the current date. ``` ZoneId zoneId = ZoneId.of( "America/Montreal" ); LocalDate localDate = LocalDate.now( zoneId ); ``` You can get the various pieces of information with `getYear`, `getMonth`, and `getDayOfMonth`. You will actually get the year number with java.time! ``` int year = localDate.getYear(); ``` > > 2016 > > > If you want a date-time instead of just a date, use [`ZonedDateTime`](https://docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html) class. ``` ZonedDateTime zdt = ZonedDateTime.now( zoneId ) ; ``` --- About java.time =============== The [java.time](http://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/9/docs/api/java/util/Date.html), [`.Calendar`](https://docs.oracle.com/javase/9/docs/api/java/util/Calendar.html), & [`java.text.SimpleDateFormat`](http://docs.oracle.com/javase/9/docs/api/java/text/SimpleDateFormat.html). The [Joda-Time](http://www.joda.org/joda-time/) project, now in [maintenance mode](https://en.wikipedia.org/wiki/Maintenance_mode), advises migration to the [java.time](https://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) classes. To learn more, see the [Oracle Tutorial](http://docs.oracle.com/javase/tutorial/datetime/TOC.html). And search Stack Overflow for many examples and explanations. Much of the *java.time* functionality is back-ported to Java 6 & Java 7 in [ThreeTen-Backport](http://www.threeten.org/threetenbp/) and further adapted to [Android](https://en.wikipedia.org/wiki/Android_(operating_system)) in [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) (see [*How to use…*](http://stackoverflow.com/q/38922754/642706)). The [ThreeTen-Extra](http://www.threeten.org/threeten-extra/) project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as [`Interval`](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/Interval.html), [`YearWeek`](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearWeek.html), [`YearQuarter`](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearQuarter.html), and [more](http://www.threeten.org/threeten-extra/apidocs/index.html).
``` try{ int year = Integer.parseInt(new Date().toString().split("-")[0]); } catch(NumberFormatException e){ } ``` Much of Date is deprecated.
9,243,578
I am having the following problem in Java (I see some people are having a similar problem in JavaScript but I'm using Java) ``` System.out.println(new Date().getYear()); System.out.println(new GregorianCalendar().getTime().getYear()); System.out.println(this.sale.getSaleDate().getYear()); System.out.println(this.sale.getSaleDate().getMonth()); System.out.println(this.sale.getSaleDate().getDate()); ``` returns ``` I/System.out( 4274): 112 I/System.out( 4274): 112 I/System.out( 4274): 112 I/System.out( 4274): 1 I/System.out( 4274): 11 ``` I don't understand the 112 bit which I thought would have been 2012. What's going on? Is the `java.util.Date` class unusable? I am storing this as a field in several of my classes to store a date and time. What should I do?
2012/02/11
[ "https://Stackoverflow.com/questions/9243578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1139027/" ]
The java documentation suggests to make use of Calendar class instead of this deprecated way Here is the sample code to set up the calendar object ``` Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); ``` Here is the sample code to get the year, month, etc. ``` System.out.println(calendar.get(Calendar.YEAR)); System.out.println(calendar.get(Calendar.MONTH)); ``` Calendar also has support for many other useful information like, TIME, DAY\_OF\_MONTH, etc. Here the [documentation](https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html) listing all of them Please note that the month are 0 based. January is 0th month.
There are may ways of getting day, month and year in java. You may use any- ``` Date date1 = new Date(); String mmddyyyy1 = new SimpleDateFormat("MM-dd-yyyy").format(date1); System.out.println("Formatted Date 1: " + mmddyyyy1); Date date2 = new Date(); Calendar calendar1 = new GregorianCalendar(); calendar1.setTime(date2); int day1 = calendar1.get(Calendar.DAY_OF_MONTH); int month1 = calendar1.get(Calendar.MONTH) + 1; // {0 - 11} int year1 = calendar1.get(Calendar.YEAR); String mmddyyyy2 = ((month1<10)?"0"+month1:month1) + "-" + ((day1<10)?"0"+day1:day1) + "-" + (year1); System.out.println("Formatted Date 2: " + mmddyyyy2); LocalDateTime ldt1 = LocalDateTime.now(); DateTimeFormatter format1 = DateTimeFormatter.ofPattern("MM-dd-yyyy"); String mmddyyyy3 = ldt1.format(format1); System.out.println("Formatted Date 3: " + mmddyyyy3); LocalDateTime ldt2 = LocalDateTime.now(); int day2 = ldt2.getDayOfMonth(); int mont2= ldt2.getMonthValue(); int year2= ldt2.getYear(); String mmddyyyy4 = ((mont2<10)?"0"+mont2:mont2) + "-" + ((day2<10)?"0"+day2:day2) + "-" + (year2); System.out.println("Formatted Date 4: " + mmddyyyy4); LocalDateTime ldt3 = LocalDateTime.of(2020, 6, 11, 14, 30); // int year, int month, int dayOfMonth, int hour, int minute DateTimeFormatter format2 = DateTimeFormatter.ofPattern("MM-dd-yyyy"); String mmddyyyy5 = ldt3.format(format2); System.out.println("Formatted Date 5: " + mmddyyyy5); Calendar calendar2 = Calendar.getInstance(); calendar2.setTime(new Date()); int day3 = calendar2.get(Calendar.DAY_OF_MONTH); // OR Calendar.DATE int month3= calendar2.get(Calendar.MONTH) + 1; int year3 = calendar2.get(Calendar.YEAR); String mmddyyyy6 = ((month3<10)?"0"+month3:month3) + "-" + ((day3<10)?"0"+day3:day3) + "-" + (year3); System.out.println("Formatted Date 6: " + mmddyyyy6); Date date3 = new Date(); LocalDate ld1 = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date3)); // Accepts only yyyy-MM-dd int day4 = ld1.getDayOfMonth(); int month4= ld1.getMonthValue(); int year4 = ld1.getYear(); String mmddyyyy7 = ((month4<10)?"0"+month4:month4) + "-" + ((day4<10)?"0"+day4:day4) + "-" + (year4); System.out.println("Formatted Date 7: " + mmddyyyy7); Date date4 = new Date(); int day5 = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date4)).getDayOfMonth(); int month5 = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date4)).getMonthValue(); int year5 = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date4)).getYear(); String mmddyyyy8 = ((month5<10)?"0"+month5:month5) + "-" + ((day5<10)?"0"+day5:day5) + "-" + (year5); System.out.println("Formatted Date 8: " + mmddyyyy8); Date date5 = new Date(); int day6 = Integer.parseInt(new SimpleDateFormat("dd").format(date5)); int month6 = Integer.parseInt(new SimpleDateFormat("MM").format(date5)); int year6 = Integer.parseInt(new SimpleDateFormat("yyyy").format(date5)); String mmddyyyy9 = ((month6<10)?"0"+month6:month6) + "-" + ((day6<10)?"0"+day6:day6) + "-" + (year6); System.out.println("Formatted Date 9: " + mmddyyyy9); ```
9,243,578
I am having the following problem in Java (I see some people are having a similar problem in JavaScript but I'm using Java) ``` System.out.println(new Date().getYear()); System.out.println(new GregorianCalendar().getTime().getYear()); System.out.println(this.sale.getSaleDate().getYear()); System.out.println(this.sale.getSaleDate().getMonth()); System.out.println(this.sale.getSaleDate().getDate()); ``` returns ``` I/System.out( 4274): 112 I/System.out( 4274): 112 I/System.out( 4274): 112 I/System.out( 4274): 1 I/System.out( 4274): 11 ``` I don't understand the 112 bit which I thought would have been 2012. What's going on? Is the `java.util.Date` class unusable? I am storing this as a field in several of my classes to store a date and time. What should I do?
2012/02/11
[ "https://Stackoverflow.com/questions/9243578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1139027/" ]
Use date format ``` SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = format.parse(datetime); SimpleDateFormat df = new SimpleDateFormat("yyyy"); year = df.format(date); ```
There are may ways of getting day, month and year in java. You may use any- ``` Date date1 = new Date(); String mmddyyyy1 = new SimpleDateFormat("MM-dd-yyyy").format(date1); System.out.println("Formatted Date 1: " + mmddyyyy1); Date date2 = new Date(); Calendar calendar1 = new GregorianCalendar(); calendar1.setTime(date2); int day1 = calendar1.get(Calendar.DAY_OF_MONTH); int month1 = calendar1.get(Calendar.MONTH) + 1; // {0 - 11} int year1 = calendar1.get(Calendar.YEAR); String mmddyyyy2 = ((month1<10)?"0"+month1:month1) + "-" + ((day1<10)?"0"+day1:day1) + "-" + (year1); System.out.println("Formatted Date 2: " + mmddyyyy2); LocalDateTime ldt1 = LocalDateTime.now(); DateTimeFormatter format1 = DateTimeFormatter.ofPattern("MM-dd-yyyy"); String mmddyyyy3 = ldt1.format(format1); System.out.println("Formatted Date 3: " + mmddyyyy3); LocalDateTime ldt2 = LocalDateTime.now(); int day2 = ldt2.getDayOfMonth(); int mont2= ldt2.getMonthValue(); int year2= ldt2.getYear(); String mmddyyyy4 = ((mont2<10)?"0"+mont2:mont2) + "-" + ((day2<10)?"0"+day2:day2) + "-" + (year2); System.out.println("Formatted Date 4: " + mmddyyyy4); LocalDateTime ldt3 = LocalDateTime.of(2020, 6, 11, 14, 30); // int year, int month, int dayOfMonth, int hour, int minute DateTimeFormatter format2 = DateTimeFormatter.ofPattern("MM-dd-yyyy"); String mmddyyyy5 = ldt3.format(format2); System.out.println("Formatted Date 5: " + mmddyyyy5); Calendar calendar2 = Calendar.getInstance(); calendar2.setTime(new Date()); int day3 = calendar2.get(Calendar.DAY_OF_MONTH); // OR Calendar.DATE int month3= calendar2.get(Calendar.MONTH) + 1; int year3 = calendar2.get(Calendar.YEAR); String mmddyyyy6 = ((month3<10)?"0"+month3:month3) + "-" + ((day3<10)?"0"+day3:day3) + "-" + (year3); System.out.println("Formatted Date 6: " + mmddyyyy6); Date date3 = new Date(); LocalDate ld1 = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date3)); // Accepts only yyyy-MM-dd int day4 = ld1.getDayOfMonth(); int month4= ld1.getMonthValue(); int year4 = ld1.getYear(); String mmddyyyy7 = ((month4<10)?"0"+month4:month4) + "-" + ((day4<10)?"0"+day4:day4) + "-" + (year4); System.out.println("Formatted Date 7: " + mmddyyyy7); Date date4 = new Date(); int day5 = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date4)).getDayOfMonth(); int month5 = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date4)).getMonthValue(); int year5 = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date4)).getYear(); String mmddyyyy8 = ((month5<10)?"0"+month5:month5) + "-" + ((day5<10)?"0"+day5:day5) + "-" + (year5); System.out.println("Formatted Date 8: " + mmddyyyy8); Date date5 = new Date(); int day6 = Integer.parseInt(new SimpleDateFormat("dd").format(date5)); int month6 = Integer.parseInt(new SimpleDateFormat("MM").format(date5)); int year6 = Integer.parseInt(new SimpleDateFormat("yyyy").format(date5)); String mmddyyyy9 = ((month6<10)?"0"+month6:month6) + "-" + ((day6<10)?"0"+day6:day6) + "-" + (year6); System.out.println("Formatted Date 9: " + mmddyyyy9); ```
9,243,578
I am having the following problem in Java (I see some people are having a similar problem in JavaScript but I'm using Java) ``` System.out.println(new Date().getYear()); System.out.println(new GregorianCalendar().getTime().getYear()); System.out.println(this.sale.getSaleDate().getYear()); System.out.println(this.sale.getSaleDate().getMonth()); System.out.println(this.sale.getSaleDate().getDate()); ``` returns ``` I/System.out( 4274): 112 I/System.out( 4274): 112 I/System.out( 4274): 112 I/System.out( 4274): 1 I/System.out( 4274): 11 ``` I don't understand the 112 bit which I thought would have been 2012. What's going on? Is the `java.util.Date` class unusable? I am storing this as a field in several of my classes to store a date and time. What should I do?
2012/02/11
[ "https://Stackoverflow.com/questions/9243578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1139027/" ]
tl;dr ===== ``` LocalDate.now() // Capture the date-only value current in the JVM’s current default time zone. .getYear() // Extract the year number from that date. ``` > > 2018 > > > java.time ========= Both the `java.util.Date` and `java.util.Calendar` classes are legacy, now supplanted by the java.time framework built into Java 8 and later. A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in [Paris France](https://en.wikipedia.org/wiki/Europe/Paris) is a new day while still “yesterday” in [Montréal Québec](https://en.wikipedia.org/wiki/America/Montreal). If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment, so your results may vary. Better to specify your desired/expected time zone explicitly as an argument. Specify a [proper time zone name](https://en.wikipedia.org/wiki/List_of_tz_zones_by_name) in the format of `continent/region`, such as [`America/Montreal`](https://en.wikipedia.org/wiki/America/Montreal), [`Africa/Casablanca`](https://en.wikipedia.org/wiki/Africa/Casablanca), or `Pacific/Auckland`. Never use the 3-4 letter abbreviation such as `EST` or `IST` as they are *not* true time zones, not standardized, and not even unique(!). ``` ZoneId z = ZoneId.of( "Africa/Tunis" ) ; ``` If you want only the date without time-of-day, use [`LocalDate`](https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html). This class lacks time zone info but you can specify a time zone to determine the current date. ``` ZoneId zoneId = ZoneId.of( "America/Montreal" ); LocalDate localDate = LocalDate.now( zoneId ); ``` You can get the various pieces of information with `getYear`, `getMonth`, and `getDayOfMonth`. You will actually get the year number with java.time! ``` int year = localDate.getYear(); ``` > > 2016 > > > If you want a date-time instead of just a date, use [`ZonedDateTime`](https://docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html) class. ``` ZonedDateTime zdt = ZonedDateTime.now( zoneId ) ; ``` --- About java.time =============== The [java.time](http://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/9/docs/api/java/util/Date.html), [`.Calendar`](https://docs.oracle.com/javase/9/docs/api/java/util/Calendar.html), & [`java.text.SimpleDateFormat`](http://docs.oracle.com/javase/9/docs/api/java/text/SimpleDateFormat.html). The [Joda-Time](http://www.joda.org/joda-time/) project, now in [maintenance mode](https://en.wikipedia.org/wiki/Maintenance_mode), advises migration to the [java.time](https://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) classes. To learn more, see the [Oracle Tutorial](http://docs.oracle.com/javase/tutorial/datetime/TOC.html). And search Stack Overflow for many examples and explanations. Much of the *java.time* functionality is back-ported to Java 6 & Java 7 in [ThreeTen-Backport](http://www.threeten.org/threetenbp/) and further adapted to [Android](https://en.wikipedia.org/wiki/Android_(operating_system)) in [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) (see [*How to use…*](http://stackoverflow.com/q/38922754/642706)). The [ThreeTen-Extra](http://www.threeten.org/threeten-extra/) project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as [`Interval`](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/Interval.html), [`YearWeek`](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearWeek.html), [`YearQuarter`](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearQuarter.html), and [more](http://www.threeten.org/threeten-extra/apidocs/index.html).
Java 8 LocalDate class is another option to get the year from a java.util.Date, ``` int year = LocalDate.parse(new SimpleDateFormat("yyyy-MM-dd").format(date)).getYear(); ``` Another option is, ``` int year = Integer.parseInt(new SimpleDateFormat("yyyy").format(date)); ```
9,243,578
I am having the following problem in Java (I see some people are having a similar problem in JavaScript but I'm using Java) ``` System.out.println(new Date().getYear()); System.out.println(new GregorianCalendar().getTime().getYear()); System.out.println(this.sale.getSaleDate().getYear()); System.out.println(this.sale.getSaleDate().getMonth()); System.out.println(this.sale.getSaleDate().getDate()); ``` returns ``` I/System.out( 4274): 112 I/System.out( 4274): 112 I/System.out( 4274): 112 I/System.out( 4274): 1 I/System.out( 4274): 11 ``` I don't understand the 112 bit which I thought would have been 2012. What's going on? Is the `java.util.Date` class unusable? I am storing this as a field in several of my classes to store a date and time. What should I do?
2012/02/11
[ "https://Stackoverflow.com/questions/9243578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1139027/" ]
Yup, this is in fact what's happening. See also the [Javadoc](http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#getYear%28%29): > > > ``` > Returns: > the year represented by this date, minus 1900. > > ``` > > The getYear method is deprecated for this reason. So, don't use it. Note also that getMonth returns a number between 0 and 11. Therefore, `this.sale.getSaleDate().getMonth()` returns 1 for February, instead of 2. While `java.util.Calendar` doesn't add 1900 to all years, it does suffer from the off-by-one-month problem. You're much better off using [JodaTime](http://joda-time.sourceforge.net/).
``` try{ int year = Integer.parseInt(new Date().toString().split("-")[0]); } catch(NumberFormatException e){ } ``` Much of Date is deprecated.
25,345,701
I'm toying with promises in JavaScript and tried to promisify setTimeout function: ``` function timeout(ms) { return new Promise(function(resolve, reject) { setTimeout(function() { resolve('timeout done'); }, ms); }); } var myPromise=timeout(3000); myPromise.then(function(result) { console.log(result); // timeout done }) ``` Fairly straightforward but I was wondering how would I go about canceling my timeout before the promise resolves. `timeout` returns `Promise` object hence I loose access to value that `setTimeout` returns and cannot cancel timeout via `clearTimeout`. What woud be the best way to do it? BTW there is no real purpose for this, I just wonder how this would be approached. Also I plunked it here <http://plnkr.co/edit/NXFjs1dXWVFNEOeCV1BA?p=preview>
2014/08/17
[ "https://Stackoverflow.com/questions/25345701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/166343/" ]
**Edit 2021** all platforms have converged on AbortController as the cancellation primitive and there is some built in support for this. ### In Node.js ```js // import { setTimeout } from 'timers/promises' // in ESM const { setTimeout } = require('timers/promises'); const ac = new AbortController(); // cancellable timeout (async () => { await setTimeout(1000, null, { signal: ac.signal }); })(); // abort the timeout, rejects with an ERR_ABORT ac.abort(); ``` ### In Browsers You can polyfill this API and use the same as the example above: ```js function delay(ms, value, { signal } = {}) { return new Promise((resolve, reject) => { const listener = () => { clearTimeout(timer); reject(signal.reason); }; signal?.throwIfAborted(); const timer = setTimeout(() => { signal?.removeEventListener('abort', listener); resolve(value); }, ms); signal?.addEventListener('abort', listener); }); } ``` --- What you can do it that, you can return a canceller from your `timeout` function and invoke it when needed. This way you do not need to store the `timeoutid` globally (or on the outer scope) and also this can manage multiple calls to the function as well. Each instance of the object return by the function `timeout` will have its own canceler that can perform the cancellation. ``` function timeout(ms) { var timeout, promise; promise = new Promise(function(resolve, reject) { timeout = setTimeout(function() { resolve('timeout done'); }, ms); }); return { promise:promise, cancel:function(){clearTimeout(timeout );} //return a canceller as well }; } var timeOutObj =timeout(3000); timeOutObj.promise.then(function(result) { console.log(result); // timeout done }); //Cancel it. timeOutObj.cancel(); ``` **[Plnkr](http://plnkr.co/edit/tydVRb?p=preview)**
PSL's answer is right, however - there are a few caveats and I'd do it a bit differently. * A timeout being cleared means the code will not run - so we should reject the promise. * Returning two things isn't necessary in our case, we can monkey patch in JavaScript. Here: ``` function timeout(ms, value) { var p = new Promise(function(resolve, reject) { p._timeout = setTimeout(function() { resolve(value); }, ms); p.cancel = function(err) { reject(err || new Error("Timeout")); clearTimeout(p._timeout); // We actually don't need to do this since we // rejected - but it's well mannered to do so }; }); return p; } ``` Which would let us do: ``` var p = timeout(1500) p.then(function(){ console.log("This will never log"); }) p.catch(function(){ console.log("This will get logged so we can now handle timeouts!") }) p.cancel(Error("Timed out")); ``` One might be interested in full blown cancellation and indeed some libraries support this directly as a feature of the library. In fact I'd dare say most do. However, this causes interference problems. Quoting KrisKowal from [here](https://github.com/mxcl/PromiseKit/issues/18#issuecomment-51493764): > > My position on cancellation has evolved. I am now convinced that cancellation (**bg:** that propagates) is inherently impossible with the Promise abstraction because promises can multiple dependess and dependees can be introduced at any time. If any dependee cancels a promise, it would be able to interfere with future dependees. There are two ways to get around the problem. One is to introduce a separate cancellation "capability", perhaps passed as an argument. The other is to introduce a new abstraction, a perhaps thenable "Task", which in exchange for requiring that each task only have one observer (one then call, ever), can be canceled without fear of interference. Tasks would support a fork() method to create a new task, allowing another dependee to retain the task or postpone cancellation. > > >
25,345,701
I'm toying with promises in JavaScript and tried to promisify setTimeout function: ``` function timeout(ms) { return new Promise(function(resolve, reject) { setTimeout(function() { resolve('timeout done'); }, ms); }); } var myPromise=timeout(3000); myPromise.then(function(result) { console.log(result); // timeout done }) ``` Fairly straightforward but I was wondering how would I go about canceling my timeout before the promise resolves. `timeout` returns `Promise` object hence I loose access to value that `setTimeout` returns and cannot cancel timeout via `clearTimeout`. What woud be the best way to do it? BTW there is no real purpose for this, I just wonder how this would be approached. Also I plunked it here <http://plnkr.co/edit/NXFjs1dXWVFNEOeCV1BA?p=preview>
2014/08/17
[ "https://Stackoverflow.com/questions/25345701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/166343/" ]
**Edit 2021** all platforms have converged on AbortController as the cancellation primitive and there is some built in support for this. ### In Node.js ```js // import { setTimeout } from 'timers/promises' // in ESM const { setTimeout } = require('timers/promises'); const ac = new AbortController(); // cancellable timeout (async () => { await setTimeout(1000, null, { signal: ac.signal }); })(); // abort the timeout, rejects with an ERR_ABORT ac.abort(); ``` ### In Browsers You can polyfill this API and use the same as the example above: ```js function delay(ms, value, { signal } = {}) { return new Promise((resolve, reject) => { const listener = () => { clearTimeout(timer); reject(signal.reason); }; signal?.throwIfAborted(); const timer = setTimeout(() => { signal?.removeEventListener('abort', listener); resolve(value); }, ms); signal?.addEventListener('abort', listener); }); } ``` --- What you can do it that, you can return a canceller from your `timeout` function and invoke it when needed. This way you do not need to store the `timeoutid` globally (or on the outer scope) and also this can manage multiple calls to the function as well. Each instance of the object return by the function `timeout` will have its own canceler that can perform the cancellation. ``` function timeout(ms) { var timeout, promise; promise = new Promise(function(resolve, reject) { timeout = setTimeout(function() { resolve('timeout done'); }, ms); }); return { promise:promise, cancel:function(){clearTimeout(timeout );} //return a canceller as well }; } var timeOutObj =timeout(3000); timeOutObj.promise.then(function(result) { console.log(result); // timeout done }); //Cancel it. timeOutObj.cancel(); ``` **[Plnkr](http://plnkr.co/edit/tydVRb?p=preview)**
The above to answers by @Benjamin and @PSL work, but what if you need the cancelable timeout to be used by an outside source while being canceled internally? For example, the interaction might look somewhat like this: ``` // externally usage of timeout async function() { await timeout() // timeout promise } // internal handling of timeout timeout.cancel() ``` I needed this kind of implementation myself, so here's what I came up with: ``` /** * Cancelable Timer hack. * * @notes * - Super() does not have `this` context so we have to create the timer * via a factory function and use closures for the cancelation data. * - Methods outside the consctutor do not persist with the extended * promise object so we have to declare them via `this`. * @constructor Timer */ function createTimer(duration) { let timerId, endTimer class Timer extends Promise { constructor(duration) { // Promise Construction super(resolve => { endTimer = resolve timerId = setTimeout(endTimer, duration) }) // Timer Cancelation this.isCanceled = false this.cancel = function() { endTimer() clearTimeout(timerId) this.isCanceled = true } } } return new Timer(duration) } ``` Now you can use the timer like this: ``` let timeout = createTimer(100) ``` And have the promise canceled somewhere else: ``` if (typeof promise !== 'undefined' && typeof promise.cancel === 'function') { timeout.cancel() } ```
25,345,701
I'm toying with promises in JavaScript and tried to promisify setTimeout function: ``` function timeout(ms) { return new Promise(function(resolve, reject) { setTimeout(function() { resolve('timeout done'); }, ms); }); } var myPromise=timeout(3000); myPromise.then(function(result) { console.log(result); // timeout done }) ``` Fairly straightforward but I was wondering how would I go about canceling my timeout before the promise resolves. `timeout` returns `Promise` object hence I loose access to value that `setTimeout` returns and cannot cancel timeout via `clearTimeout`. What woud be the best way to do it? BTW there is no real purpose for this, I just wonder how this would be approached. Also I plunked it here <http://plnkr.co/edit/NXFjs1dXWVFNEOeCV1BA?p=preview>
2014/08/17
[ "https://Stackoverflow.com/questions/25345701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/166343/" ]
**Edit 2021** all platforms have converged on AbortController as the cancellation primitive and there is some built in support for this. ### In Node.js ```js // import { setTimeout } from 'timers/promises' // in ESM const { setTimeout } = require('timers/promises'); const ac = new AbortController(); // cancellable timeout (async () => { await setTimeout(1000, null, { signal: ac.signal }); })(); // abort the timeout, rejects with an ERR_ABORT ac.abort(); ``` ### In Browsers You can polyfill this API and use the same as the example above: ```js function delay(ms, value, { signal } = {}) { return new Promise((resolve, reject) => { const listener = () => { clearTimeout(timer); reject(signal.reason); }; signal?.throwIfAborted(); const timer = setTimeout(() => { signal?.removeEventListener('abort', listener); resolve(value); }, ms); signal?.addEventListener('abort', listener); }); } ``` --- What you can do it that, you can return a canceller from your `timeout` function and invoke it when needed. This way you do not need to store the `timeoutid` globally (or on the outer scope) and also this can manage multiple calls to the function as well. Each instance of the object return by the function `timeout` will have its own canceler that can perform the cancellation. ``` function timeout(ms) { var timeout, promise; promise = new Promise(function(resolve, reject) { timeout = setTimeout(function() { resolve('timeout done'); }, ms); }); return { promise:promise, cancel:function(){clearTimeout(timeout );} //return a canceller as well }; } var timeOutObj =timeout(3000); timeOutObj.promise.then(function(result) { console.log(result); // timeout done }); //Cancel it. timeOutObj.cancel(); ``` **[Plnkr](http://plnkr.co/edit/tydVRb?p=preview)**
This is my answer in TypeScript: ``` private sleep(ms) { let timerId, endTimer; class TimedPromise extends Promise<any> { isCanceled: boolean = false; cancel = () => { endTimer(); clearTimeout(timerId); this.isCanceled = true; }; constructor(fn) { super(fn); } } return new TimedPromise(resolve => { endTimer = resolve; timerId = setTimeout(endTimer, ms); }); } ``` Usage: ``` const wait = sleep(10*1000); setTimeout(() => { wait.cancel() },5 * 1000); await wait; ```
25,345,701
I'm toying with promises in JavaScript and tried to promisify setTimeout function: ``` function timeout(ms) { return new Promise(function(resolve, reject) { setTimeout(function() { resolve('timeout done'); }, ms); }); } var myPromise=timeout(3000); myPromise.then(function(result) { console.log(result); // timeout done }) ``` Fairly straightforward but I was wondering how would I go about canceling my timeout before the promise resolves. `timeout` returns `Promise` object hence I loose access to value that `setTimeout` returns and cannot cancel timeout via `clearTimeout`. What woud be the best way to do it? BTW there is no real purpose for this, I just wonder how this would be approached. Also I plunked it here <http://plnkr.co/edit/NXFjs1dXWVFNEOeCV1BA?p=preview>
2014/08/17
[ "https://Stackoverflow.com/questions/25345701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/166343/" ]
PSL's answer is right, however - there are a few caveats and I'd do it a bit differently. * A timeout being cleared means the code will not run - so we should reject the promise. * Returning two things isn't necessary in our case, we can monkey patch in JavaScript. Here: ``` function timeout(ms, value) { var p = new Promise(function(resolve, reject) { p._timeout = setTimeout(function() { resolve(value); }, ms); p.cancel = function(err) { reject(err || new Error("Timeout")); clearTimeout(p._timeout); // We actually don't need to do this since we // rejected - but it's well mannered to do so }; }); return p; } ``` Which would let us do: ``` var p = timeout(1500) p.then(function(){ console.log("This will never log"); }) p.catch(function(){ console.log("This will get logged so we can now handle timeouts!") }) p.cancel(Error("Timed out")); ``` One might be interested in full blown cancellation and indeed some libraries support this directly as a feature of the library. In fact I'd dare say most do. However, this causes interference problems. Quoting KrisKowal from [here](https://github.com/mxcl/PromiseKit/issues/18#issuecomment-51493764): > > My position on cancellation has evolved. I am now convinced that cancellation (**bg:** that propagates) is inherently impossible with the Promise abstraction because promises can multiple dependess and dependees can be introduced at any time. If any dependee cancels a promise, it would be able to interfere with future dependees. There are two ways to get around the problem. One is to introduce a separate cancellation "capability", perhaps passed as an argument. The other is to introduce a new abstraction, a perhaps thenable "Task", which in exchange for requiring that each task only have one observer (one then call, ever), can be canceled without fear of interference. Tasks would support a fork() method to create a new task, allowing another dependee to retain the task or postpone cancellation. > > >
The above to answers by @Benjamin and @PSL work, but what if you need the cancelable timeout to be used by an outside source while being canceled internally? For example, the interaction might look somewhat like this: ``` // externally usage of timeout async function() { await timeout() // timeout promise } // internal handling of timeout timeout.cancel() ``` I needed this kind of implementation myself, so here's what I came up with: ``` /** * Cancelable Timer hack. * * @notes * - Super() does not have `this` context so we have to create the timer * via a factory function and use closures for the cancelation data. * - Methods outside the consctutor do not persist with the extended * promise object so we have to declare them via `this`. * @constructor Timer */ function createTimer(duration) { let timerId, endTimer class Timer extends Promise { constructor(duration) { // Promise Construction super(resolve => { endTimer = resolve timerId = setTimeout(endTimer, duration) }) // Timer Cancelation this.isCanceled = false this.cancel = function() { endTimer() clearTimeout(timerId) this.isCanceled = true } } } return new Timer(duration) } ``` Now you can use the timer like this: ``` let timeout = createTimer(100) ``` And have the promise canceled somewhere else: ``` if (typeof promise !== 'undefined' && typeof promise.cancel === 'function') { timeout.cancel() } ```
25,345,701
I'm toying with promises in JavaScript and tried to promisify setTimeout function: ``` function timeout(ms) { return new Promise(function(resolve, reject) { setTimeout(function() { resolve('timeout done'); }, ms); }); } var myPromise=timeout(3000); myPromise.then(function(result) { console.log(result); // timeout done }) ``` Fairly straightforward but I was wondering how would I go about canceling my timeout before the promise resolves. `timeout` returns `Promise` object hence I loose access to value that `setTimeout` returns and cannot cancel timeout via `clearTimeout`. What woud be the best way to do it? BTW there is no real purpose for this, I just wonder how this would be approached. Also I plunked it here <http://plnkr.co/edit/NXFjs1dXWVFNEOeCV1BA?p=preview>
2014/08/17
[ "https://Stackoverflow.com/questions/25345701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/166343/" ]
PSL's answer is right, however - there are a few caveats and I'd do it a bit differently. * A timeout being cleared means the code will not run - so we should reject the promise. * Returning two things isn't necessary in our case, we can monkey patch in JavaScript. Here: ``` function timeout(ms, value) { var p = new Promise(function(resolve, reject) { p._timeout = setTimeout(function() { resolve(value); }, ms); p.cancel = function(err) { reject(err || new Error("Timeout")); clearTimeout(p._timeout); // We actually don't need to do this since we // rejected - but it's well mannered to do so }; }); return p; } ``` Which would let us do: ``` var p = timeout(1500) p.then(function(){ console.log("This will never log"); }) p.catch(function(){ console.log("This will get logged so we can now handle timeouts!") }) p.cancel(Error("Timed out")); ``` One might be interested in full blown cancellation and indeed some libraries support this directly as a feature of the library. In fact I'd dare say most do. However, this causes interference problems. Quoting KrisKowal from [here](https://github.com/mxcl/PromiseKit/issues/18#issuecomment-51493764): > > My position on cancellation has evolved. I am now convinced that cancellation (**bg:** that propagates) is inherently impossible with the Promise abstraction because promises can multiple dependess and dependees can be introduced at any time. If any dependee cancels a promise, it would be able to interfere with future dependees. There are two ways to get around the problem. One is to introduce a separate cancellation "capability", perhaps passed as an argument. The other is to introduce a new abstraction, a perhaps thenable "Task", which in exchange for requiring that each task only have one observer (one then call, ever), can be canceled without fear of interference. Tasks would support a fork() method to create a new task, allowing another dependee to retain the task or postpone cancellation. > > >
This is my answer in TypeScript: ``` private sleep(ms) { let timerId, endTimer; class TimedPromise extends Promise<any> { isCanceled: boolean = false; cancel = () => { endTimer(); clearTimeout(timerId); this.isCanceled = true; }; constructor(fn) { super(fn); } } return new TimedPromise(resolve => { endTimer = resolve; timerId = setTimeout(endTimer, ms); }); } ``` Usage: ``` const wait = sleep(10*1000); setTimeout(() => { wait.cancel() },5 * 1000); await wait; ```
25,345,701
I'm toying with promises in JavaScript and tried to promisify setTimeout function: ``` function timeout(ms) { return new Promise(function(resolve, reject) { setTimeout(function() { resolve('timeout done'); }, ms); }); } var myPromise=timeout(3000); myPromise.then(function(result) { console.log(result); // timeout done }) ``` Fairly straightforward but I was wondering how would I go about canceling my timeout before the promise resolves. `timeout` returns `Promise` object hence I loose access to value that `setTimeout` returns and cannot cancel timeout via `clearTimeout`. What woud be the best way to do it? BTW there is no real purpose for this, I just wonder how this would be approached. Also I plunked it here <http://plnkr.co/edit/NXFjs1dXWVFNEOeCV1BA?p=preview>
2014/08/17
[ "https://Stackoverflow.com/questions/25345701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/166343/" ]
The above to answers by @Benjamin and @PSL work, but what if you need the cancelable timeout to be used by an outside source while being canceled internally? For example, the interaction might look somewhat like this: ``` // externally usage of timeout async function() { await timeout() // timeout promise } // internal handling of timeout timeout.cancel() ``` I needed this kind of implementation myself, so here's what I came up with: ``` /** * Cancelable Timer hack. * * @notes * - Super() does not have `this` context so we have to create the timer * via a factory function and use closures for the cancelation data. * - Methods outside the consctutor do not persist with the extended * promise object so we have to declare them via `this`. * @constructor Timer */ function createTimer(duration) { let timerId, endTimer class Timer extends Promise { constructor(duration) { // Promise Construction super(resolve => { endTimer = resolve timerId = setTimeout(endTimer, duration) }) // Timer Cancelation this.isCanceled = false this.cancel = function() { endTimer() clearTimeout(timerId) this.isCanceled = true } } } return new Timer(duration) } ``` Now you can use the timer like this: ``` let timeout = createTimer(100) ``` And have the promise canceled somewhere else: ``` if (typeof promise !== 'undefined' && typeof promise.cancel === 'function') { timeout.cancel() } ```
This is my answer in TypeScript: ``` private sleep(ms) { let timerId, endTimer; class TimedPromise extends Promise<any> { isCanceled: boolean = false; cancel = () => { endTimer(); clearTimeout(timerId); this.isCanceled = true; }; constructor(fn) { super(fn); } } return new TimedPromise(resolve => { endTimer = resolve; timerId = setTimeout(endTimer, ms); }); } ``` Usage: ``` const wait = sleep(10*1000); setTimeout(() => { wait.cancel() },5 * 1000); await wait; ```
44,567,866
If I insert values into HTML inputs, the new values are not passed to the JavaScript function. If I define the input value attribute is passed and processed. ```html <!DOCTYPE html> <html> <body> Name: <input type="text" id="txtName" value="foo" /> Surname: <input type="text" id="txtSurname" value="bar" /> Year Born:<input type="number" id="txtYearborn" value="2000" /> Job: <input type="text" id="txtJob" value="work" /> <button type="button" onclick="document.getElementById('infoprinted').innerHTML = person1.printAll();">Click </button> <p id="infoprinted"> </p> <script type="text/javascript"> function personDescription(name, surname, yearborn, job) { this.name = name; this.surname = surname; this.yearborn = yearborn; this.job = job; this.printAll = function() { return this.name + " " + this.surname + " and he was born in " + this.yearborn + " and her job is " + this.job }; }; var firstName = document.getElementById("txtName").value; var lastName = document.getElementById('txtSurname').value; var born = parseInt(document.getElementById('txtYearborn').value); var theJob = document.getElementById('txtJob').value; var person1 = new personDescription(firstName, lastName, born, theJob); </script> </body> </html> ```
2017/06/15
[ "https://Stackoverflow.com/questions/44567866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6344882/" ]
As said by @NathanOliver, the warning means that there might be a possible case where your function might not return any value. To be more precise if a user inputs a value which is not 1 or 2, then your function does not return any value. You might be thinking that you are only going to input 1 or 2. But the compiler doesn't know this. What you can do is - 1. **Ignore the warning** - You can ignore the warning and go right ahead. But be careful that you only put 1 o 2 as the parameter in all cases. > > Though I would not recommend ignoring the warning. In general, it is better to pay heed to the warnings. In the long run, it saves you from many bugs in case you are working on big projects. > > > 2. **Add a default** - This condition will not actually execute ever, but the compiler will now stop giving the warnings. Here's the corrected code - ``` int Fct_name (int nb1, int * nb2) { switch (Dest) { case 1 : return Fct_1(nb1,nb2); case 2 : return -1; default: return 0; } } ``` Or you could do this - ``` int Fct_name (int nb1, int * nb2) { switch (Dest) { case 1 : return Fct_1(nb1,nb2); case 2 : return -1; } return 0; } ```
Add a return XXX at the end of the function which will then ensure that the compiler will not have anyway of getting to the end of the function without a return of value occurring.
44,567,866
If I insert values into HTML inputs, the new values are not passed to the JavaScript function. If I define the input value attribute is passed and processed. ```html <!DOCTYPE html> <html> <body> Name: <input type="text" id="txtName" value="foo" /> Surname: <input type="text" id="txtSurname" value="bar" /> Year Born:<input type="number" id="txtYearborn" value="2000" /> Job: <input type="text" id="txtJob" value="work" /> <button type="button" onclick="document.getElementById('infoprinted').innerHTML = person1.printAll();">Click </button> <p id="infoprinted"> </p> <script type="text/javascript"> function personDescription(name, surname, yearborn, job) { this.name = name; this.surname = surname; this.yearborn = yearborn; this.job = job; this.printAll = function() { return this.name + " " + this.surname + " and he was born in " + this.yearborn + " and her job is " + this.job }; }; var firstName = document.getElementById("txtName").value; var lastName = document.getElementById('txtSurname').value; var born = parseInt(document.getElementById('txtYearborn').value); var theJob = document.getElementById('txtJob').value; var person1 = new personDescription(firstName, lastName, born, theJob); </script> </body> </html> ```
2017/06/15
[ "https://Stackoverflow.com/questions/44567866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6344882/" ]
It's because, as the warning says, not all paths of your code return a value while the function has a distinct return type which tells the compiler "hey, I'm going to return something." but you don't actually do that if `Dest` is anything other than 1 or 2. --- You commented: > > Dest can only be 1 or 2 (it's an enum) > > > Yes okay but *only you* know that, your compiler doesn't, and it won't take your word for it. It can only see the static properties of your code, it can't predict how the runtime will go and thus it won't accept your code. For all it knows `Dest` can be changed by an external piece of code etc etc. --- You should add some sort of default value: ``` int Fct_name (int nb1, int * nb2) { switch (Dest) { case 1 : return Fct_1(nb1,nb2); case 2 : return -1; } return 0; } ```
As said by @NathanOliver, the warning means that there might be a possible case where your function might not return any value. To be more precise if a user inputs a value which is not 1 or 2, then your function does not return any value. You might be thinking that you are only going to input 1 or 2. But the compiler doesn't know this. What you can do is - 1. **Ignore the warning** - You can ignore the warning and go right ahead. But be careful that you only put 1 o 2 as the parameter in all cases. > > Though I would not recommend ignoring the warning. In general, it is better to pay heed to the warnings. In the long run, it saves you from many bugs in case you are working on big projects. > > > 2. **Add a default** - This condition will not actually execute ever, but the compiler will now stop giving the warnings. Here's the corrected code - ``` int Fct_name (int nb1, int * nb2) { switch (Dest) { case 1 : return Fct_1(nb1,nb2); case 2 : return -1; default: return 0; } } ``` Or you could do this - ``` int Fct_name (int nb1, int * nb2) { switch (Dest) { case 1 : return Fct_1(nb1,nb2); case 2 : return -1; } return 0; } ```
44,567,866
If I insert values into HTML inputs, the new values are not passed to the JavaScript function. If I define the input value attribute is passed and processed. ```html <!DOCTYPE html> <html> <body> Name: <input type="text" id="txtName" value="foo" /> Surname: <input type="text" id="txtSurname" value="bar" /> Year Born:<input type="number" id="txtYearborn" value="2000" /> Job: <input type="text" id="txtJob" value="work" /> <button type="button" onclick="document.getElementById('infoprinted').innerHTML = person1.printAll();">Click </button> <p id="infoprinted"> </p> <script type="text/javascript"> function personDescription(name, surname, yearborn, job) { this.name = name; this.surname = surname; this.yearborn = yearborn; this.job = job; this.printAll = function() { return this.name + " " + this.surname + " and he was born in " + this.yearborn + " and her job is " + this.job }; }; var firstName = document.getElementById("txtName").value; var lastName = document.getElementById('txtSurname').value; var born = parseInt(document.getElementById('txtYearborn').value); var theJob = document.getElementById('txtJob').value; var person1 = new personDescription(firstName, lastName, born, theJob); </script> </body> </html> ```
2017/06/15
[ "https://Stackoverflow.com/questions/44567866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6344882/" ]
It's because, as the warning says, not all paths of your code return a value while the function has a distinct return type which tells the compiler "hey, I'm going to return something." but you don't actually do that if `Dest` is anything other than 1 or 2. --- You commented: > > Dest can only be 1 or 2 (it's an enum) > > > Yes okay but *only you* know that, your compiler doesn't, and it won't take your word for it. It can only see the static properties of your code, it can't predict how the runtime will go and thus it won't accept your code. For all it knows `Dest` can be changed by an external piece of code etc etc. --- You should add some sort of default value: ``` int Fct_name (int nb1, int * nb2) { switch (Dest) { case 1 : return Fct_1(nb1,nb2); case 2 : return -1; } return 0; } ```
Add a return XXX at the end of the function which will then ensure that the compiler will not have anyway of getting to the end of the function without a return of value occurring.
44,567,866
If I insert values into HTML inputs, the new values are not passed to the JavaScript function. If I define the input value attribute is passed and processed. ```html <!DOCTYPE html> <html> <body> Name: <input type="text" id="txtName" value="foo" /> Surname: <input type="text" id="txtSurname" value="bar" /> Year Born:<input type="number" id="txtYearborn" value="2000" /> Job: <input type="text" id="txtJob" value="work" /> <button type="button" onclick="document.getElementById('infoprinted').innerHTML = person1.printAll();">Click </button> <p id="infoprinted"> </p> <script type="text/javascript"> function personDescription(name, surname, yearborn, job) { this.name = name; this.surname = surname; this.yearborn = yearborn; this.job = job; this.printAll = function() { return this.name + " " + this.surname + " and he was born in " + this.yearborn + " and her job is " + this.job }; }; var firstName = document.getElementById("txtName").value; var lastName = document.getElementById('txtSurname').value; var born = parseInt(document.getElementById('txtYearborn').value); var theJob = document.getElementById('txtJob').value; var person1 = new personDescription(firstName, lastName, born, theJob); </script> </body> </html> ```
2017/06/15
[ "https://Stackoverflow.com/questions/44567866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6344882/" ]
If `dest` is an enum with only two values, it is unnecessary complicated - `return Dest == 1 ? Fct_1(nb1,nb2) : -1;` is enough. Otherwise, replace `case 2:` with `default:`.
Add a return XXX at the end of the function which will then ensure that the compiler will not have anyway of getting to the end of the function without a return of value occurring.
44,567,866
If I insert values into HTML inputs, the new values are not passed to the JavaScript function. If I define the input value attribute is passed and processed. ```html <!DOCTYPE html> <html> <body> Name: <input type="text" id="txtName" value="foo" /> Surname: <input type="text" id="txtSurname" value="bar" /> Year Born:<input type="number" id="txtYearborn" value="2000" /> Job: <input type="text" id="txtJob" value="work" /> <button type="button" onclick="document.getElementById('infoprinted').innerHTML = person1.printAll();">Click </button> <p id="infoprinted"> </p> <script type="text/javascript"> function personDescription(name, surname, yearborn, job) { this.name = name; this.surname = surname; this.yearborn = yearborn; this.job = job; this.printAll = function() { return this.name + " " + this.surname + " and he was born in " + this.yearborn + " and her job is " + this.job }; }; var firstName = document.getElementById("txtName").value; var lastName = document.getElementById('txtSurname').value; var born = parseInt(document.getElementById('txtYearborn').value); var theJob = document.getElementById('txtJob').value; var person1 = new personDescription(firstName, lastName, born, theJob); </script> </body> </html> ```
2017/06/15
[ "https://Stackoverflow.com/questions/44567866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6344882/" ]
If `Dest` is really an enum as you said, the compiler should not issue a warning in your case. At least my compiler does not. So the following code compiles without warning/error: ``` enum { x = 1, y = 2 } Dest; int Fct_name (int nb1, int * nb2) { switch (Dest) { case 1 : return -5; //Fct_1(nb1,nb2); case 2 : return -1; } } int main() { } ``` However, if `Dest` is an integer or if the enum defines other values than `1` and `2`, then I get an error as well. This can then be fixed with a `default`-path: ``` enum { x = 1, y = 2, z = 3 } Dest; int Fct_name (int nb1, int * nb2) { switch (Dest) { case 1 : return -5; //Fct_1(nb1,nb2); case 2 : return -1; default: return 0; } } ```
Add a return XXX at the end of the function which will then ensure that the compiler will not have anyway of getting to the end of the function without a return of value occurring.
44,567,866
If I insert values into HTML inputs, the new values are not passed to the JavaScript function. If I define the input value attribute is passed and processed. ```html <!DOCTYPE html> <html> <body> Name: <input type="text" id="txtName" value="foo" /> Surname: <input type="text" id="txtSurname" value="bar" /> Year Born:<input type="number" id="txtYearborn" value="2000" /> Job: <input type="text" id="txtJob" value="work" /> <button type="button" onclick="document.getElementById('infoprinted').innerHTML = person1.printAll();">Click </button> <p id="infoprinted"> </p> <script type="text/javascript"> function personDescription(name, surname, yearborn, job) { this.name = name; this.surname = surname; this.yearborn = yearborn; this.job = job; this.printAll = function() { return this.name + " " + this.surname + " and he was born in " + this.yearborn + " and her job is " + this.job }; }; var firstName = document.getElementById("txtName").value; var lastName = document.getElementById('txtSurname').value; var born = parseInt(document.getElementById('txtYearborn').value); var theJob = document.getElementById('txtJob').value; var person1 = new personDescription(firstName, lastName, born, theJob); </script> </body> </html> ```
2017/06/15
[ "https://Stackoverflow.com/questions/44567866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6344882/" ]
If Dest can only be 1 or 2, you could rewrite like this ``` int Fct_name (int nb1, int * nb2) { if(Dest == 1) return Fct_1(nb1,nb2); return -1; } ```
Add a return XXX at the end of the function which will then ensure that the compiler will not have anyway of getting to the end of the function without a return of value occurring.
44,567,866
If I insert values into HTML inputs, the new values are not passed to the JavaScript function. If I define the input value attribute is passed and processed. ```html <!DOCTYPE html> <html> <body> Name: <input type="text" id="txtName" value="foo" /> Surname: <input type="text" id="txtSurname" value="bar" /> Year Born:<input type="number" id="txtYearborn" value="2000" /> Job: <input type="text" id="txtJob" value="work" /> <button type="button" onclick="document.getElementById('infoprinted').innerHTML = person1.printAll();">Click </button> <p id="infoprinted"> </p> <script type="text/javascript"> function personDescription(name, surname, yearborn, job) { this.name = name; this.surname = surname; this.yearborn = yearborn; this.job = job; this.printAll = function() { return this.name + " " + this.surname + " and he was born in " + this.yearborn + " and her job is " + this.job }; }; var firstName = document.getElementById("txtName").value; var lastName = document.getElementById('txtSurname').value; var born = parseInt(document.getElementById('txtYearborn').value); var theJob = document.getElementById('txtJob').value; var person1 = new personDescription(firstName, lastName, born, theJob); </script> </body> </html> ```
2017/06/15
[ "https://Stackoverflow.com/questions/44567866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6344882/" ]
It's because, as the warning says, not all paths of your code return a value while the function has a distinct return type which tells the compiler "hey, I'm going to return something." but you don't actually do that if `Dest` is anything other than 1 or 2. --- You commented: > > Dest can only be 1 or 2 (it's an enum) > > > Yes okay but *only you* know that, your compiler doesn't, and it won't take your word for it. It can only see the static properties of your code, it can't predict how the runtime will go and thus it won't accept your code. For all it knows `Dest` can be changed by an external piece of code etc etc. --- You should add some sort of default value: ``` int Fct_name (int nb1, int * nb2) { switch (Dest) { case 1 : return Fct_1(nb1,nb2); case 2 : return -1; } return 0; } ```
If `dest` is an enum with only two values, it is unnecessary complicated - `return Dest == 1 ? Fct_1(nb1,nb2) : -1;` is enough. Otherwise, replace `case 2:` with `default:`.
44,567,866
If I insert values into HTML inputs, the new values are not passed to the JavaScript function. If I define the input value attribute is passed and processed. ```html <!DOCTYPE html> <html> <body> Name: <input type="text" id="txtName" value="foo" /> Surname: <input type="text" id="txtSurname" value="bar" /> Year Born:<input type="number" id="txtYearborn" value="2000" /> Job: <input type="text" id="txtJob" value="work" /> <button type="button" onclick="document.getElementById('infoprinted').innerHTML = person1.printAll();">Click </button> <p id="infoprinted"> </p> <script type="text/javascript"> function personDescription(name, surname, yearborn, job) { this.name = name; this.surname = surname; this.yearborn = yearborn; this.job = job; this.printAll = function() { return this.name + " " + this.surname + " and he was born in " + this.yearborn + " and her job is " + this.job }; }; var firstName = document.getElementById("txtName").value; var lastName = document.getElementById('txtSurname').value; var born = parseInt(document.getElementById('txtYearborn').value); var theJob = document.getElementById('txtJob').value; var person1 = new personDescription(firstName, lastName, born, theJob); </script> </body> </html> ```
2017/06/15
[ "https://Stackoverflow.com/questions/44567866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6344882/" ]
It's because, as the warning says, not all paths of your code return a value while the function has a distinct return type which tells the compiler "hey, I'm going to return something." but you don't actually do that if `Dest` is anything other than 1 or 2. --- You commented: > > Dest can only be 1 or 2 (it's an enum) > > > Yes okay but *only you* know that, your compiler doesn't, and it won't take your word for it. It can only see the static properties of your code, it can't predict how the runtime will go and thus it won't accept your code. For all it knows `Dest` can be changed by an external piece of code etc etc. --- You should add some sort of default value: ``` int Fct_name (int nb1, int * nb2) { switch (Dest) { case 1 : return Fct_1(nb1,nb2); case 2 : return -1; } return 0; } ```
If `Dest` is really an enum as you said, the compiler should not issue a warning in your case. At least my compiler does not. So the following code compiles without warning/error: ``` enum { x = 1, y = 2 } Dest; int Fct_name (int nb1, int * nb2) { switch (Dest) { case 1 : return -5; //Fct_1(nb1,nb2); case 2 : return -1; } } int main() { } ``` However, if `Dest` is an integer or if the enum defines other values than `1` and `2`, then I get an error as well. This can then be fixed with a `default`-path: ``` enum { x = 1, y = 2, z = 3 } Dest; int Fct_name (int nb1, int * nb2) { switch (Dest) { case 1 : return -5; //Fct_1(nb1,nb2); case 2 : return -1; default: return 0; } } ```
44,567,866
If I insert values into HTML inputs, the new values are not passed to the JavaScript function. If I define the input value attribute is passed and processed. ```html <!DOCTYPE html> <html> <body> Name: <input type="text" id="txtName" value="foo" /> Surname: <input type="text" id="txtSurname" value="bar" /> Year Born:<input type="number" id="txtYearborn" value="2000" /> Job: <input type="text" id="txtJob" value="work" /> <button type="button" onclick="document.getElementById('infoprinted').innerHTML = person1.printAll();">Click </button> <p id="infoprinted"> </p> <script type="text/javascript"> function personDescription(name, surname, yearborn, job) { this.name = name; this.surname = surname; this.yearborn = yearborn; this.job = job; this.printAll = function() { return this.name + " " + this.surname + " and he was born in " + this.yearborn + " and her job is " + this.job }; }; var firstName = document.getElementById("txtName").value; var lastName = document.getElementById('txtSurname').value; var born = parseInt(document.getElementById('txtYearborn').value); var theJob = document.getElementById('txtJob').value; var person1 = new personDescription(firstName, lastName, born, theJob); </script> </body> </html> ```
2017/06/15
[ "https://Stackoverflow.com/questions/44567866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6344882/" ]
It's because, as the warning says, not all paths of your code return a value while the function has a distinct return type which tells the compiler "hey, I'm going to return something." but you don't actually do that if `Dest` is anything other than 1 or 2. --- You commented: > > Dest can only be 1 or 2 (it's an enum) > > > Yes okay but *only you* know that, your compiler doesn't, and it won't take your word for it. It can only see the static properties of your code, it can't predict how the runtime will go and thus it won't accept your code. For all it knows `Dest` can be changed by an external piece of code etc etc. --- You should add some sort of default value: ``` int Fct_name (int nb1, int * nb2) { switch (Dest) { case 1 : return Fct_1(nb1,nb2); case 2 : return -1; } return 0; } ```
If Dest can only be 1 or 2, you could rewrite like this ``` int Fct_name (int nb1, int * nb2) { if(Dest == 1) return Fct_1(nb1,nb2); return -1; } ```
14,513,790
I have two separate tables, the first one is 'blogs' which obviously holds posted blogs. The second table is 'b\_comments' which holds all the comments posted on the blogs. Each blog has a unique ID, which is stored with each comment accordingly. As of right now I am using 2 separate queries to grab both the full blog post and all the comments that go with it. Is there a way I can `JOIN` these two tables together to get an entire blog post and all of the comments that go with it in one query? I have never had to use the `JOIN` or `UNION` functions of MySQL so I am unsure if this is even possible. Here are my two queries if that helps any: ``` $getBlog = $link->query("SELECT * FROM blogs WHERE blog_id = '" .$blogID. "'"); $getComments = $link->query("SELECT * FROM b_comments WHERE blog_id = '".$blogID."' ORDER BY date DESC") ``` **EDIT: Here is more code to help you better understand what I am trying to do:** ``` //get blog posts $blogID = intval($_GET['id']); $sql = $link->query("SELECT * FROM blogs WHERE blog_id = '" .$blogID. "'"); $row = mysqli_fetch_assoc($sql); $blogTitle = $link->real_escape_string($row['blog_title']); $pubDate = $link->real_escape_string($row['pub_date']); $blogCat = $link->real_escape_string($row['category']); $blogAuthor = $link->real_escape_string($row['author']); $blogImage = $link->real_escape_string($row['image']); $blogContent = $link->real_escape_string($row['content']); //get comments $getComments = $link->query("SELECT * FROM b_comments WHERE blog_id = '".$blogID."' ORDER BY date DESC"); if(!($getComments->num_rows > 0)) { echo "<div id='commentArea' style='display: none;'>"; echo "</div>"; } else { echo "<div id='commentArea'>"; while($comRow = mysqli_fetch_assoc($getComments)) { $commentID = $link->real_escape_string($comRow['id']); $comAuthor = $link->real_escape_string($comRow['user_name']); $comDate = $link->real_escape_string($comRow['date']); $comContent = $link->real_escape_string($comRow['content']); $comDate = date("F jS, Y H:ia", strtotime($comDate)); ``` With those variables I am echoing out the data into an HTML page.
2013/01/25
[ "https://Stackoverflow.com/questions/14513790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1552948/" ]
Without knowing the table structure you can try something like: ``` SELECT * FROM blogs JOIN b_comments ON blogs.blog_id = b_comments.blog_id ``` You may want to use a `LEFT JOIN` if you want to return blogs that do not have comments. **Update** ``` //get blog posts $blogID = intval($_GET['id']); $blogTitle = null; $pubDate = null $blogCat = null; $blogAuthor = null; $blogImage = null; $blogContent = null; //get comments $getComments = $link->query("SELECT a.blog_title, a.pub_date, a.category, a.author, a.image, a.content AS blog_content, b.id, b.user_name, b.date, b.content FROM blogs a JOIN b_comments b ON a.blog_id = b.blog_id WHERE a.blog_id = " . $blogID . " ORDER BY b.date DESC"); if(!($getComments->num_rows > 0)) { echo "<div id='commentArea' style='display: none;'>"; echo "</div>"; } else { while($comRow = mysqli_fetch_assoc($getComments)) { if(empty($blogTitle)) $blogTitle = $link->real_escape_string($row['blog_title']); if(empty($pubDate)) $pubDate = $link->real_escape_string($row['pub_date']); if(empty($blogCat)) $blogCat = $link->real_escape_string($row['category']); if(empty($blogAuthor)) $blogAuthor = $link->real_escape_string($row['author']); if(empty($blogImage)) $blogImage = $link->real_escape_string($row['image']); if(empty($blogContent)) $blogContent = $link->real_escape_string($row['blog_content']); $commentID = $link->real_escape_string($comRow['id']); $comAuthor = $link->real_escape_string($comRow['user_name']); $comDate = $link->real_escape_string($comRow['date']); $comContent = $link->real_escape_string($comRow['content']); $comDate = date("F jS, Y H:ia", strtotime($comDate)); } } ```
You can do a `LEFT JOIN` to get the blog post and comments (or just the blog post if there are no comments): ``` $getBlogAndComments = $link->query("SELECT * FROM blogs b LEFT JOIN b_comments ON b.blog_id = c.blog_id WHERE b.blog_id = '" .$blogID. "'"); ``` Although in this instance two queries may be more efficient, since you'll be fetching the blog post along with every comment row.
15,937,619
I'm getting this error when I am trying to replace certain text with other certain text with javascript / jquery. Here is the error: > > Uncaught TypeError: Object [object HTMLAnchorElement] has no method 'html' > > > and here are the lines of javascript on the site: ``` $(document).ready({ var navigationLinks = $('.nav a'); for(var i=0; i < navigationLinks.length; i++){ var thisLink = navigationLinks[i]; switch(thisLink.html()){ case "About": thisLink.html().replace(/About/g,'&#xe00f;'); case "Work": thisLink.html().replace(/Work/g,'&#xe010'); case "CV": thisLink.html().replace(/CV/g,'&#xe00c'); case "Resume": thisLink.html().replace(/Resume/g,'&#xe00d;'); case "down": thisLink.html().replace(/down/g,'&#xe00d;'); case "Mail": thisLink.html().replace(/Mail/g,'&#xe011;'); case "Dribbble": thisLink.html().replace(/Dribbble/g,'&#xe015;'); case "GooglePlus": thisLink.html().replace(/GooglePlus/g,'&#xe012;'); case "Facebook": thisLink.html().replace(/Facebook/g,'&#xe013;'); case "Twitter": thisLink.html().replace(/Twitter/g,'&#xe014'); default: thisLink.html().replace(thisLink.html(),thisLink.html()); } } window.onscroll=scrollFunc; }); ```
2013/04/10
[ "https://Stackoverflow.com/questions/15937619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2105672/" ]
Change: ``` navigationLinks[i]; // DOM element which doesn't have an `html` function ``` To: ``` navigationLinks.eq(i);// jQuery wrapper which does have an `html` function ```
.html() is a jquery method. You want ``` $(thislink).html() ```
8,874,728
I have a text being returned from SQL that may have newlines in it. However, since I'm putting the value in between `<p></p>` tags, it's ignoring the newlines. For example if the text in SQL is actually this (with a CRLF between lines): ``` foobar car carbar foo ``` The HTML code becomes: ``` <p>foobar car carbar foo</p> ``` Which is just rendering as: ``` foobar car carbar foo ``` Ultimately it seems that I want to detect a newline then add the appropriate HTML such as: ``` <p>foobar car</p><p>carbar foo</p> ``` or even ``` <p>foobar car<br/><br/>carbar foo</p> ``` Should this be handled on the front end or in the SQL queries returning the data? It seems that it should be handled on the front end code (in my ASP.NET view) but if so, how? I noticed that there a function in PHP to handle exactly this case: `nl2br` (http://www.php.net/manual/en/function.nl2br.php) but unfortunately that doesn't help me :)
2012/01/16
[ "https://Stackoverflow.com/questions/8874728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/286791/" ]
It's generally better to perform this kind of logic is your presentation code then your DB or middle-tier. My Recommended approach would be to write some .net code to replace cr and lf with `<br/>` tags. The code itself is straightforward, here is an example that will emulate your php nl2br function: ``` string nl2br(string text) { return text.Replace("\r", "<br/>").Replace("\n", "<br/>"); } ``` You could also perform this transform in SQL using [REPLACE()](http://msdn.microsoft.com/en-us/library/ms186862.aspx) and [CHAR()](http://msdn.microsoft.com/en-us/library/ms187323.aspx) although it is preferable to perform this kind of transform in the presentation layer, not the database layer. The SQL approach would be: ``` SELECT REPLACE(REPLACE(myStr, char(13), '<br/>'), CHAR(10), '<br/>') ``` This would replace `CHAR(13)` and `CHAR(10)` (cr and lf) with `<br/>` tags. A third option would be to render your text at [preformatted text](http://www.w3schools.com/tags/tag_pre.asp) using the `<pre>` tags although this is really only suitable for a narrow set of use-cases (such as displaying code as used here on StackOverflow) e.g. ``` <pre> foobar car carbar foo </pre> ``` which would render like this: ``` foobar car carbar foo ``` keeping spaces and new lines intact.
If you want to do this in SQL Server then one way is to use the `replace` function to replace char(13) + char(10) with example ``` declare @s varchar(1000) select @s = 'line1 line2' select replace(@s,char(13) + char(10),'<br><br>') ``` output ------ ``` line1<br><br>line2 ``` so in your case ``` select replace(ColumnName,char(13) + char(10),'<br><br>') From SomeTable ```
8,874,728
I have a text being returned from SQL that may have newlines in it. However, since I'm putting the value in between `<p></p>` tags, it's ignoring the newlines. For example if the text in SQL is actually this (with a CRLF between lines): ``` foobar car carbar foo ``` The HTML code becomes: ``` <p>foobar car carbar foo</p> ``` Which is just rendering as: ``` foobar car carbar foo ``` Ultimately it seems that I want to detect a newline then add the appropriate HTML such as: ``` <p>foobar car</p><p>carbar foo</p> ``` or even ``` <p>foobar car<br/><br/>carbar foo</p> ``` Should this be handled on the front end or in the SQL queries returning the data? It seems that it should be handled on the front end code (in my ASP.NET view) but if so, how? I noticed that there a function in PHP to handle exactly this case: `nl2br` (http://www.php.net/manual/en/function.nl2br.php) but unfortunately that doesn't help me :)
2012/01/16
[ "https://Stackoverflow.com/questions/8874728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/286791/" ]
you can do this in sql server or in your application, to do this in sql server you can replace the carriage return char with this code: ``` select REPLACE(Comments,CHAR(13),' <br />') from Production.ProductReview ``` EDIT: You can do this in a more elegant form handling in .Net code, through SqlDataReader, and changing the text: ``` var target = "this is the line \r\n and this is another line"; Regex regex = new Regex(@"(\r\n|\r|\n)+"); string newText = regex.Replace(target, "<br />"); ```
If you want to do this in SQL Server then one way is to use the `replace` function to replace char(13) + char(10) with example ``` declare @s varchar(1000) select @s = 'line1 line2' select replace(@s,char(13) + char(10),'<br><br>') ``` output ------ ``` line1<br><br>line2 ``` so in your case ``` select replace(ColumnName,char(13) + char(10),'<br><br>') From SomeTable ```
8,874,728
I have a text being returned from SQL that may have newlines in it. However, since I'm putting the value in between `<p></p>` tags, it's ignoring the newlines. For example if the text in SQL is actually this (with a CRLF between lines): ``` foobar car carbar foo ``` The HTML code becomes: ``` <p>foobar car carbar foo</p> ``` Which is just rendering as: ``` foobar car carbar foo ``` Ultimately it seems that I want to detect a newline then add the appropriate HTML such as: ``` <p>foobar car</p><p>carbar foo</p> ``` or even ``` <p>foobar car<br/><br/>carbar foo</p> ``` Should this be handled on the front end or in the SQL queries returning the data? It seems that it should be handled on the front end code (in my ASP.NET view) but if so, how? I noticed that there a function in PHP to handle exactly this case: `nl2br` (http://www.php.net/manual/en/function.nl2br.php) but unfortunately that doesn't help me :)
2012/01/16
[ "https://Stackoverflow.com/questions/8874728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/286791/" ]
You should really be doing this in your web language (asp.net I guess), but if you must do it in SQL, here's how it's done: MySQL: ``` SELECT REPLACE(column_name, "\r\n", "<br/>"); ``` T-SQL (MS SQL Server): ``` SELECT REPLACE(REPLACE(column_name, CHAR(13), ''), CHAR(10), '<br/>'); ```
If you want to do this in SQL Server then one way is to use the `replace` function to replace char(13) + char(10) with example ``` declare @s varchar(1000) select @s = 'line1 line2' select replace(@s,char(13) + char(10),'<br><br>') ``` output ------ ``` line1<br><br>line2 ``` so in your case ``` select replace(ColumnName,char(13) + char(10),'<br><br>') From SomeTable ```
8,874,728
I have a text being returned from SQL that may have newlines in it. However, since I'm putting the value in between `<p></p>` tags, it's ignoring the newlines. For example if the text in SQL is actually this (with a CRLF between lines): ``` foobar car carbar foo ``` The HTML code becomes: ``` <p>foobar car carbar foo</p> ``` Which is just rendering as: ``` foobar car carbar foo ``` Ultimately it seems that I want to detect a newline then add the appropriate HTML such as: ``` <p>foobar car</p><p>carbar foo</p> ``` or even ``` <p>foobar car<br/><br/>carbar foo</p> ``` Should this be handled on the front end or in the SQL queries returning the data? It seems that it should be handled on the front end code (in my ASP.NET view) but if so, how? I noticed that there a function in PHP to handle exactly this case: `nl2br` (http://www.php.net/manual/en/function.nl2br.php) but unfortunately that doesn't help me :)
2012/01/16
[ "https://Stackoverflow.com/questions/8874728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/286791/" ]
It's generally better to perform this kind of logic is your presentation code then your DB or middle-tier. My Recommended approach would be to write some .net code to replace cr and lf with `<br/>` tags. The code itself is straightforward, here is an example that will emulate your php nl2br function: ``` string nl2br(string text) { return text.Replace("\r", "<br/>").Replace("\n", "<br/>"); } ``` You could also perform this transform in SQL using [REPLACE()](http://msdn.microsoft.com/en-us/library/ms186862.aspx) and [CHAR()](http://msdn.microsoft.com/en-us/library/ms187323.aspx) although it is preferable to perform this kind of transform in the presentation layer, not the database layer. The SQL approach would be: ``` SELECT REPLACE(REPLACE(myStr, char(13), '<br/>'), CHAR(10), '<br/>') ``` This would replace `CHAR(13)` and `CHAR(10)` (cr and lf) with `<br/>` tags. A third option would be to render your text at [preformatted text](http://www.w3schools.com/tags/tag_pre.asp) using the `<pre>` tags although this is really only suitable for a narrow set of use-cases (such as displaying code as used here on StackOverflow) e.g. ``` <pre> foobar car carbar foo </pre> ``` which would render like this: ``` foobar car carbar foo ``` keeping spaces and new lines intact.
you can do this in sql server or in your application, to do this in sql server you can replace the carriage return char with this code: ``` select REPLACE(Comments,CHAR(13),' <br />') from Production.ProductReview ``` EDIT: You can do this in a more elegant form handling in .Net code, through SqlDataReader, and changing the text: ``` var target = "this is the line \r\n and this is another line"; Regex regex = new Regex(@"(\r\n|\r|\n)+"); string newText = regex.Replace(target, "<br />"); ```
8,874,728
I have a text being returned from SQL that may have newlines in it. However, since I'm putting the value in between `<p></p>` tags, it's ignoring the newlines. For example if the text in SQL is actually this (with a CRLF between lines): ``` foobar car carbar foo ``` The HTML code becomes: ``` <p>foobar car carbar foo</p> ``` Which is just rendering as: ``` foobar car carbar foo ``` Ultimately it seems that I want to detect a newline then add the appropriate HTML such as: ``` <p>foobar car</p><p>carbar foo</p> ``` or even ``` <p>foobar car<br/><br/>carbar foo</p> ``` Should this be handled on the front end or in the SQL queries returning the data? It seems that it should be handled on the front end code (in my ASP.NET view) but if so, how? I noticed that there a function in PHP to handle exactly this case: `nl2br` (http://www.php.net/manual/en/function.nl2br.php) but unfortunately that doesn't help me :)
2012/01/16
[ "https://Stackoverflow.com/questions/8874728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/286791/" ]
It's generally better to perform this kind of logic is your presentation code then your DB or middle-tier. My Recommended approach would be to write some .net code to replace cr and lf with `<br/>` tags. The code itself is straightforward, here is an example that will emulate your php nl2br function: ``` string nl2br(string text) { return text.Replace("\r", "<br/>").Replace("\n", "<br/>"); } ``` You could also perform this transform in SQL using [REPLACE()](http://msdn.microsoft.com/en-us/library/ms186862.aspx) and [CHAR()](http://msdn.microsoft.com/en-us/library/ms187323.aspx) although it is preferable to perform this kind of transform in the presentation layer, not the database layer. The SQL approach would be: ``` SELECT REPLACE(REPLACE(myStr, char(13), '<br/>'), CHAR(10), '<br/>') ``` This would replace `CHAR(13)` and `CHAR(10)` (cr and lf) with `<br/>` tags. A third option would be to render your text at [preformatted text](http://www.w3schools.com/tags/tag_pre.asp) using the `<pre>` tags although this is really only suitable for a narrow set of use-cases (such as displaying code as used here on StackOverflow) e.g. ``` <pre> foobar car carbar foo </pre> ``` which would render like this: ``` foobar car carbar foo ``` keeping spaces and new lines intact.
You should really be doing this in your web language (asp.net I guess), but if you must do it in SQL, here's how it's done: MySQL: ``` SELECT REPLACE(column_name, "\r\n", "<br/>"); ``` T-SQL (MS SQL Server): ``` SELECT REPLACE(REPLACE(column_name, CHAR(13), ''), CHAR(10), '<br/>'); ```
8,874,728
I have a text being returned from SQL that may have newlines in it. However, since I'm putting the value in between `<p></p>` tags, it's ignoring the newlines. For example if the text in SQL is actually this (with a CRLF between lines): ``` foobar car carbar foo ``` The HTML code becomes: ``` <p>foobar car carbar foo</p> ``` Which is just rendering as: ``` foobar car carbar foo ``` Ultimately it seems that I want to detect a newline then add the appropriate HTML such as: ``` <p>foobar car</p><p>carbar foo</p> ``` or even ``` <p>foobar car<br/><br/>carbar foo</p> ``` Should this be handled on the front end or in the SQL queries returning the data? It seems that it should be handled on the front end code (in my ASP.NET view) but if so, how? I noticed that there a function in PHP to handle exactly this case: `nl2br` (http://www.php.net/manual/en/function.nl2br.php) but unfortunately that doesn't help me :)
2012/01/16
[ "https://Stackoverflow.com/questions/8874728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/286791/" ]
It's generally better to perform this kind of logic is your presentation code then your DB or middle-tier. My Recommended approach would be to write some .net code to replace cr and lf with `<br/>` tags. The code itself is straightforward, here is an example that will emulate your php nl2br function: ``` string nl2br(string text) { return text.Replace("\r", "<br/>").Replace("\n", "<br/>"); } ``` You could also perform this transform in SQL using [REPLACE()](http://msdn.microsoft.com/en-us/library/ms186862.aspx) and [CHAR()](http://msdn.microsoft.com/en-us/library/ms187323.aspx) although it is preferable to perform this kind of transform in the presentation layer, not the database layer. The SQL approach would be: ``` SELECT REPLACE(REPLACE(myStr, char(13), '<br/>'), CHAR(10), '<br/>') ``` This would replace `CHAR(13)` and `CHAR(10)` (cr and lf) with `<br/>` tags. A third option would be to render your text at [preformatted text](http://www.w3schools.com/tags/tag_pre.asp) using the `<pre>` tags although this is really only suitable for a narrow set of use-cases (such as displaying code as used here on StackOverflow) e.g. ``` <pre> foobar car carbar foo </pre> ``` which would render like this: ``` foobar car carbar foo ``` keeping spaces and new lines intact.
Just process your data in ASP.NET. There is no reason to put that workload on the SQL server. ``` text = text.Replace("\r", "</p>\n<p>").Replace("\n","</p>\n<p>"); text = "<p>" + text + "</p>"; ``` The above code will turn ``` foobar car carbar foo ``` Into ``` <p>foobar car</p> <p>carbar foo</p> ```
8,874,728
I have a text being returned from SQL that may have newlines in it. However, since I'm putting the value in between `<p></p>` tags, it's ignoring the newlines. For example if the text in SQL is actually this (with a CRLF between lines): ``` foobar car carbar foo ``` The HTML code becomes: ``` <p>foobar car carbar foo</p> ``` Which is just rendering as: ``` foobar car carbar foo ``` Ultimately it seems that I want to detect a newline then add the appropriate HTML such as: ``` <p>foobar car</p><p>carbar foo</p> ``` or even ``` <p>foobar car<br/><br/>carbar foo</p> ``` Should this be handled on the front end or in the SQL queries returning the data? It seems that it should be handled on the front end code (in my ASP.NET view) but if so, how? I noticed that there a function in PHP to handle exactly this case: `nl2br` (http://www.php.net/manual/en/function.nl2br.php) but unfortunately that doesn't help me :)
2012/01/16
[ "https://Stackoverflow.com/questions/8874728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/286791/" ]
you can do this in sql server or in your application, to do this in sql server you can replace the carriage return char with this code: ``` select REPLACE(Comments,CHAR(13),' <br />') from Production.ProductReview ``` EDIT: You can do this in a more elegant form handling in .Net code, through SqlDataReader, and changing the text: ``` var target = "this is the line \r\n and this is another line"; Regex regex = new Regex(@"(\r\n|\r|\n)+"); string newText = regex.Replace(target, "<br />"); ```
You should really be doing this in your web language (asp.net I guess), but if you must do it in SQL, here's how it's done: MySQL: ``` SELECT REPLACE(column_name, "\r\n", "<br/>"); ``` T-SQL (MS SQL Server): ``` SELECT REPLACE(REPLACE(column_name, CHAR(13), ''), CHAR(10), '<br/>'); ```
8,874,728
I have a text being returned from SQL that may have newlines in it. However, since I'm putting the value in between `<p></p>` tags, it's ignoring the newlines. For example if the text in SQL is actually this (with a CRLF between lines): ``` foobar car carbar foo ``` The HTML code becomes: ``` <p>foobar car carbar foo</p> ``` Which is just rendering as: ``` foobar car carbar foo ``` Ultimately it seems that I want to detect a newline then add the appropriate HTML such as: ``` <p>foobar car</p><p>carbar foo</p> ``` or even ``` <p>foobar car<br/><br/>carbar foo</p> ``` Should this be handled on the front end or in the SQL queries returning the data? It seems that it should be handled on the front end code (in my ASP.NET view) but if so, how? I noticed that there a function in PHP to handle exactly this case: `nl2br` (http://www.php.net/manual/en/function.nl2br.php) but unfortunately that doesn't help me :)
2012/01/16
[ "https://Stackoverflow.com/questions/8874728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/286791/" ]
you can do this in sql server or in your application, to do this in sql server you can replace the carriage return char with this code: ``` select REPLACE(Comments,CHAR(13),' <br />') from Production.ProductReview ``` EDIT: You can do this in a more elegant form handling in .Net code, through SqlDataReader, and changing the text: ``` var target = "this is the line \r\n and this is another line"; Regex regex = new Regex(@"(\r\n|\r|\n)+"); string newText = regex.Replace(target, "<br />"); ```
Just process your data in ASP.NET. There is no reason to put that workload on the SQL server. ``` text = text.Replace("\r", "</p>\n<p>").Replace("\n","</p>\n<p>"); text = "<p>" + text + "</p>"; ``` The above code will turn ``` foobar car carbar foo ``` Into ``` <p>foobar car</p> <p>carbar foo</p> ```
8,874,728
I have a text being returned from SQL that may have newlines in it. However, since I'm putting the value in between `<p></p>` tags, it's ignoring the newlines. For example if the text in SQL is actually this (with a CRLF between lines): ``` foobar car carbar foo ``` The HTML code becomes: ``` <p>foobar car carbar foo</p> ``` Which is just rendering as: ``` foobar car carbar foo ``` Ultimately it seems that I want to detect a newline then add the appropriate HTML such as: ``` <p>foobar car</p><p>carbar foo</p> ``` or even ``` <p>foobar car<br/><br/>carbar foo</p> ``` Should this be handled on the front end or in the SQL queries returning the data? It seems that it should be handled on the front end code (in my ASP.NET view) but if so, how? I noticed that there a function in PHP to handle exactly this case: `nl2br` (http://www.php.net/manual/en/function.nl2br.php) but unfortunately that doesn't help me :)
2012/01/16
[ "https://Stackoverflow.com/questions/8874728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/286791/" ]
You should really be doing this in your web language (asp.net I guess), but if you must do it in SQL, here's how it's done: MySQL: ``` SELECT REPLACE(column_name, "\r\n", "<br/>"); ``` T-SQL (MS SQL Server): ``` SELECT REPLACE(REPLACE(column_name, CHAR(13), ''), CHAR(10), '<br/>'); ```
Just process your data in ASP.NET. There is no reason to put that workload on the SQL server. ``` text = text.Replace("\r", "</p>\n<p>").Replace("\n","</p>\n<p>"); text = "<p>" + text + "</p>"; ``` The above code will turn ``` foobar car carbar foo ``` Into ``` <p>foobar car</p> <p>carbar foo</p> ```
29,796,925
I'm trying to follow this guide: [Google Sheets as a Database – INSERT with Apps Script using POST/GET methods (with ajax example)](https://mashe.hawksey.info/2014/07/google-sheets-as-a-database-insert-with-apps-script-using-postget-methods-with-ajax-example/) I know that I've to put 'Google Sheet/Apps Script Code' in a spreadsheet. But I don't know what I have to put in 'code.gs' and 'index.html' for Google Apps Script. Because the stackoverflow example brings with 'form.php'. **HTML** ```html <form id="foo"> <label for="bar">A bar</label> <input id="bar" name="bar" type="text" value="" /> <input type="submit" value="Send" /> </form> ``` **JavaScript** ```js // Variable to hold request var request; // Bind to the submit event of our form $("#foo").submit(function(event){ // Abort any pending request if (request) { request.abort(); } // setup some local variables var $form = $(this); // Let's select and cache all the fields var $inputs = $form.find("input, select, button, textarea"); // Serialize the data in the form var serializedData = $form.serialize(); // Let's disable the inputs for the duration of the Ajax request. // Note: we disable elements AFTER the form data has been serialized. // Disabled form elements will not be serialized. $inputs.prop("disabled", true); // Fire off the request to /form.php request = $.ajax({ url: "/form.php", type: "post", data: serializedData }); // Callback handler that will be called on success request.done(function (response, textStatus, jqXHR){ // Log a message to the console console.log("Hooray, it worked!"); }); // Callback handler that will be called on failure request.fail(function (jqXHR, textStatus, errorThrown){ // Log the error to the console console.error( "The following error occurred: "+ textStatus, errorThrown ); }); // Callback handler that will be called regardless // if the request failed or succeeded request.always(function () { // Reenable the inputs $inputs.prop("disabled", false); }); // Prevent default posting of form event.preventDefault(); }); ``` **form.php** ``` // You can access the values posted by jQuery.ajax // through the global variable $_POST, like this: $bar = $_POST['bar']; ``` **Change by Hawksey** ```js // fire off the request to /form.php request = $.ajax({ url: "https://script.google.com/macros/s/AKfycbzV--xTooSkBLufMs4AnrCTdwZxVNtycTE4JNtaCze2UijXAg8/exec", type: "post", data: serializedData }); ``` The end of the script is make a form and send data to a Google Spreadsheet via post using ajax. Thank you very much.
2015/04/22
[ "https://Stackoverflow.com/questions/29796925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4809946/" ]
Remember that short doesn't necessarily means better. Many times a longer method can be more readable and will be easier to understand and also maintain in the future. You will sometimes need to look at your code a year or 2 after you first wrote it and it ain't worth a thing if you can't understand it after you made it so short that you can't understand what you meant to do in that method. Of course that the other extreme is also something to be avoided and a too long method is not modular and can be difficult to understand if you want to change only a specific part of it. In my opinion, that method you wrote is at a good length and doesn't need to be shortened. But just to answer your question, you can always shorten your methods by dividing them to more methods. for example in your case: ``` public boolean[] validateTrueFalse(String[] checkBoxValues) { boolean[] answer = new boolean[checkBoxValues.length]; for (int i = 0; i < checkBoxValues.length; i++) { answer[i] = GetAnswer(checkBoxValues[i]); } return answer; } public bool GetAnswer(string aCheckBoxValue) { String[] values = aCheckBoxValue.split("_"); int configId = Integer.parseInt(values[0]); boolean isAns = Boolean.parseBoolean(values[1]); for (TrueFalseConfigurationModel tm : dt.getTfModelList()) { if (tm.getConfiguration_id() == configId) { return tm.isAnswer() == isAns; } } return false; } ``` Notice how I divided the one big action in the method to smaller actions which created shorter methods. You can then continue in that manner and divide the `GetAnswer` method itself into 2 methods if you can find a logical way to divide it.
You can reduce ``` if (tm.isAnswer() == isAns) { // are values from both true answer[i] = true; } else { answer[i] = false; } ``` By ``` answer[i] = tm.isAnswer() == isAns; ```
145,819
I am trying to connect to a PG instance hosted on AWS RDS using a secure SSL connection. Where do I store the public key on windows so that it is automatically applied to the connection? Please note that when I open PGAdmin it only lets me specify .crt and .key files. Is there a way to point it to .pem files? I downloaded the public key referenced here: <http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_PostgreSQL.html#PostgreSQL.Concepts.General.SSL> On Linux it is a simple matter of putting this key into the default OpenSSL directory and postgres seems to detect it and take care of the rest itself. On Windows I have not figured out how to do this or where to store the .pem file or how to point PGAdmin to a .pem file.
2016/08/03
[ "https://dba.stackexchange.com/questions/145819", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/99850/" ]
I found the answer! Turns out that the connection was encrypted all along, I just didn't realize it. Boy did that make me feel stupid. I ended up downloading Wireshark and sniffing my packets just to make sure. Note that this applies to ssl-mode "require", but in order to use ssl-mode "verify-full" you do still need a root cert. In this case I just took the `rds-combined-ca-bundle.pem` and renamed it from .pem to .crt. This allowed me to point to the file from the SSL tab of the connection properties window in PGAdmin. Doing this I was able to specify ssl-mode "verify-full" and connect to my instance. Edit: By default RDS Postgres WILL accept non-SSL connections. It just happens that PGAdmin was initiating an SSL connection by default. > > ... if you don't provide the ssl mode then postgres > connects with default mode as 'prefer' (please refer to documentation > mentioned above), according to which, it will prefer ssl connection, > but if not available, it will connect with non-ssl connection as well. > [Source](https://forums.aws.amazon.com/thread.jspa?threadID=236594) > > > To make sure you are always using SSL you can set the parameter `rds.force_ssl` to be 1 (on). [More details.](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_PostgreSQL.html#PostgreSQL.Concepts.General.SSL.Requiring)
If you are using PGAdmin, when you create a new connection there is a tab called `SSL`[1]. There you can input your pem file. If you are using `psql`, put your `pem`file on `%APPDATA%\postgresql\` directory. See more details at the documentation[2]. Hope it helps. References: 1. <https://www.pgadmin.org/docs/dev/connect.html?highlight=ssl> 2. <https://www.postgresql.org/docs/9.2/static/libpq-ssl.html>
145,819
I am trying to connect to a PG instance hosted on AWS RDS using a secure SSL connection. Where do I store the public key on windows so that it is automatically applied to the connection? Please note that when I open PGAdmin it only lets me specify .crt and .key files. Is there a way to point it to .pem files? I downloaded the public key referenced here: <http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_PostgreSQL.html#PostgreSQL.Concepts.General.SSL> On Linux it is a simple matter of putting this key into the default OpenSSL directory and postgres seems to detect it and take care of the rest itself. On Windows I have not figured out how to do this or where to store the .pem file or how to point PGAdmin to a .pem file.
2016/08/03
[ "https://dba.stackexchange.com/questions/145819", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/99850/" ]
If you are using PGAdmin, when you create a new connection there is a tab called `SSL`[1]. There you can input your pem file. If you are using `psql`, put your `pem`file on `%APPDATA%\postgresql\` directory. See more details at the documentation[2]. Hope it helps. References: 1. <https://www.pgadmin.org/docs/dev/connect.html?highlight=ssl> 2. <https://www.postgresql.org/docs/9.2/static/libpq-ssl.html>
In pgAdmin: Just load the `pem` file as the "Root certificate", in my case, it is a root certificate called `ca.pem`. Worked for me. *(Not sure about the SSL compression, I just clicked it as well, should work without it.)* [![enter image description here](https://i.stack.imgur.com/JWqIl.png)](https://i.stack.imgur.com/JWqIl.png) [![enter image description here](https://i.stack.imgur.com/LwILb.png)](https://i.stack.imgur.com/LwILb.png)
145,819
I am trying to connect to a PG instance hosted on AWS RDS using a secure SSL connection. Where do I store the public key on windows so that it is automatically applied to the connection? Please note that when I open PGAdmin it only lets me specify .crt and .key files. Is there a way to point it to .pem files? I downloaded the public key referenced here: <http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_PostgreSQL.html#PostgreSQL.Concepts.General.SSL> On Linux it is a simple matter of putting this key into the default OpenSSL directory and postgres seems to detect it and take care of the rest itself. On Windows I have not figured out how to do this or where to store the .pem file or how to point PGAdmin to a .pem file.
2016/08/03
[ "https://dba.stackexchange.com/questions/145819", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/99850/" ]
I found the answer! Turns out that the connection was encrypted all along, I just didn't realize it. Boy did that make me feel stupid. I ended up downloading Wireshark and sniffing my packets just to make sure. Note that this applies to ssl-mode "require", but in order to use ssl-mode "verify-full" you do still need a root cert. In this case I just took the `rds-combined-ca-bundle.pem` and renamed it from .pem to .crt. This allowed me to point to the file from the SSL tab of the connection properties window in PGAdmin. Doing this I was able to specify ssl-mode "verify-full" and connect to my instance. Edit: By default RDS Postgres WILL accept non-SSL connections. It just happens that PGAdmin was initiating an SSL connection by default. > > ... if you don't provide the ssl mode then postgres > connects with default mode as 'prefer' (please refer to documentation > mentioned above), according to which, it will prefer ssl connection, > but if not available, it will connect with non-ssl connection as well. > [Source](https://forums.aws.amazon.com/thread.jspa?threadID=236594) > > > To make sure you are always using SSL you can set the parameter `rds.force_ssl` to be 1 (on). [More details.](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_PostgreSQL.html#PostgreSQL.Concepts.General.SSL.Requiring)
In pgAdmin: Just load the `pem` file as the "Root certificate", in my case, it is a root certificate called `ca.pem`. Worked for me. *(Not sure about the SSL compression, I just clicked it as well, should work without it.)* [![enter image description here](https://i.stack.imgur.com/JWqIl.png)](https://i.stack.imgur.com/JWqIl.png) [![enter image description here](https://i.stack.imgur.com/LwILb.png)](https://i.stack.imgur.com/LwILb.png)
44,636,012
I have a somewhat complex case where I need to apply custom formatting to a JavaScript expression that calculates the value of a field inside a Grid. ``` <Grid records:bind="$page.data" columns={[ { field: 'seatbeltViolations', header: 'Seatbelt Violations', format:'n;0', aggregate: 'sum', aggregateField: 'seatbelts', align: 'right' },{ field: "distance", header: "Distance", format: "n;0", aggregate: "sum", aggregateField: "distance", align: "right" },{ field: 'seatbeltViolationsPer100Km', header: 'Seatbelts per 100km', format: 'n;1', footer: { expr: '0.1 * Math.round(10.0 * {$group.seatbelts}/{$group.distance})' }, align: 'right' }]} /> ``` Is there a way to use custom global functions, that perform the given operation, within the expression? Something like this: ``` // this does not work expr: 'Format.value({$group.seatbelts}/{$group.distance}, "n;1")' ``` I hope my question was clear enough :)
2017/06/19
[ "https://Stackoverflow.com/questions/44636012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4414022/" ]
**Don't hold me up on any of this.** It's not so simple. Consider the following: > > jQuery has a very nice built in $(selector).animate() function which allows for easy setup of these animations. However, jQuery's animate() does not support multiple keyframes > > > With that being said, you can include the [jQuery.Keyframes](https://github.com/Keyframes/jQuery.Keyframes) library which would assit you in achieving what you want. Just using the code you provided, you would be able to introduce the animation via jQuery -given that you add `jQuery.Keyframes` - with something like this: ```js $.keyframe.define([{ name: 'animation-name', '0%': { 'opacity': '0', 'transform': 'translate3d(0, -100%, 0)' }, '100%': { 'opacity': '1', 'transform': 'none' } }]); ```
Not sure why you would want to add keyframes using jQuery, but you can add CSS to the `head` like this: ```js $(function() { var keyframes = '.fadeInDown {' + '-webkit-animation-name: fadeInDown;' + 'animation-name: fadeInDown; }' + '@keyframes fadeInDown {' + '0% {' + 'opacity: 0;' + '-webkit-transform: translate3d(0, -100%, 0);' + 'transform: translate3d(0, -100%, 0);' + '}' + '100% {' + 'opacity: 1;' + '-webkit-transform: none;' + 'transform: none;' + '}' + '}'; $('<style type="text/css">' + keyframes + '</style>').appendTo($('head')); }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> ```
15,986,779
I am creating a Windows 8 HTML5 app, and implementing an app bar. When I access the appbar.winControl it is always null. So if for example I write appbar.winControl.show() I get an exception claiming that winControl is null. What I did was create a fixed layout app. Without doing anything else, I added the following markup in the document body: ``` <body> <div id="appbar" data-win-control="WinJS.UI.AppBar" aria-label="Command Bar"> <button id="btnBoardSizeUp" data-win-control="WinJS.UI.AppBarCommand" data-win-options="{label:'Larger', icon:'zoomout', section:'global', tooltip:'Increase the board size'}" /> <button id="btnBoardSizeDown" data-win-control="WinJS.UI.AppBarCommand" data-win-options="{label:'Smaller', icon:'zoomin', section:'global', tooltip:'Decrease the board size'}" /> <button id="btnAbortGame" data-win-control="WinJS.UI.AppBarCommand" data-win-options="{label:'Abort', icon:'cancel', section:'selection', tooltip:'Abort the current game'}" /> </div> <script type="text/javascript"> var appbar = document.getElementById("appbar"); var winControl = appbar.winControl; winControl.show(); </script> ``` The line winControl.show() produces the following error: 0x800a138f - JavaScript runtime error: Unable to get property 'show' of undefined or null reference As far as I can see I have implemented the appbar correctly on the page, so it should work. Any idea what is going wrong?
2013/04/13
[ "https://Stackoverflow.com/questions/15986779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2007420/" ]
Page Controls are not initialized yet and script is executing before that. There is two place this code can be placed. either in ``` // if the app bar is part of default.html, appbar show can be put in default.js // default.js already have a call to WinJS.UI.processAll under activated event handler WinJS.UI.processAll().then(function () { appbar.winControl.show(); }); ``` or ``` // if the appbar is part of mypage.html, need to have code like this in mypage.js WinJS.UI.Pages.define('/pages/mypage/mypage.html', { ready: function onready(element, options) { appbar.winControl.show(); } } ```
Whenever you use a winjs control (div with data-win-control attribute) to specify the control you want. You must also call the WinJS.UI.processAll function in your JavaScript code. WinJS.UI.processAll parses your markup and instantiates any Windows Library for JavaScript controls it finds. 1. If you aren't using the Blank Application template or if you're adding the control to a page that you created yourself, you might need to add a call to WinJS.UI.processAll. 2. If you added the control to your app's home page (which is usually the default.html file), add a call to WinJS.UI.processAll in your onactivated event handler, as shown in the previous example 3. If you added the control to a Page control, you don't need to add a call to WinJS.UI.processAll because the Page control does that for you automatically. 4. If you added the control to another page that is not your app's home page, handle the DOMContentLoaded event and use the handler to call WinJS.UI.processAll. function initialize() { ``` WinJS.UI.processAll(); ``` } document.addEventListener("DOMContentLoaded", initialize(), false);
5,262,389
I have a JavaScript code like that: ``` var faqOpener = { defaults: { idSelector: "#id", id: "2" }, ... if (options && !jQuery.isEmptyObject(options)) $.extend(this.defaults, options); ... ``` How can I convert that variable as an array of literal arrays something like: ``` var faqOpener = { defaults[]: { idSelector: "#id", id: "2" }, ... ``` **EDIT:** I will use that defaults variable from another javascript code. As shown in the example it has only one element at array of literal arrays however I should define it correctly and will able to pass variable length(for example array of literal arrays that has 3 array or 1 or more it depends) array of literal arrays.
2011/03/10
[ "https://Stackoverflow.com/questions/5262389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/453596/" ]
``` var faqOpener = { defaults: [{ idSelector: "#id1", id: "1" }, { idSelector: "#id2", id: "2" }], ... ``` or straight ``` var defaults = [{ idSelector: "#id1", id: "1" }, { idSelector: "#id2", id: "2" }]; ``` The question is rather unclear...
This is commonly known as JSON (JavaScript Object Notation): <http://www.json.org/example.html>
5,262,389
I have a JavaScript code like that: ``` var faqOpener = { defaults: { idSelector: "#id", id: "2" }, ... if (options && !jQuery.isEmptyObject(options)) $.extend(this.defaults, options); ... ``` How can I convert that variable as an array of literal arrays something like: ``` var faqOpener = { defaults[]: { idSelector: "#id", id: "2" }, ... ``` **EDIT:** I will use that defaults variable from another javascript code. As shown in the example it has only one element at array of literal arrays however I should define it correctly and will able to pass variable length(for example array of literal arrays that has 3 array or 1 or more it depends) array of literal arrays.
2011/03/10
[ "https://Stackoverflow.com/questions/5262389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/453596/" ]
``` var faqOpener = { defaults: [{ idSelector: "#id1", id: "1" }, { idSelector: "#id2", id: "2" }], ... ``` or straight ``` var defaults = [{ idSelector: "#id1", id: "1" }, { idSelector: "#id2", id: "2" }]; ``` The question is rather unclear...
Do you want faqOpener.defaults to be an array of objects { idSelector, id }? In JS, an array literal is delimited by square brackets, so it'd look like this: ``` var faqOpener = { defaults: [ { idSelector: "#id", id: "2" }, { idSelector: "#id3", id: "3" }, ] }; ``` That's not an array of arrays, exactly; it's an array of *associative* arrays. An "array" in JavaScript is a particular object type with some special characteristics. Any old JS object is an assocative array.
5,262,389
I have a JavaScript code like that: ``` var faqOpener = { defaults: { idSelector: "#id", id: "2" }, ... if (options && !jQuery.isEmptyObject(options)) $.extend(this.defaults, options); ... ``` How can I convert that variable as an array of literal arrays something like: ``` var faqOpener = { defaults[]: { idSelector: "#id", id: "2" }, ... ``` **EDIT:** I will use that defaults variable from another javascript code. As shown in the example it has only one element at array of literal arrays however I should define it correctly and will able to pass variable length(for example array of literal arrays that has 3 array or 1 or more it depends) array of literal arrays.
2011/03/10
[ "https://Stackoverflow.com/questions/5262389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/453596/" ]
``` var faqOpener = { defaults: [ { idSelector: "#id", id: "2" }, { idSelector: "#id1", id: "21" } ] }; ``` Then you can access the objects in defaults: ``` faqOpner.defaults[0] faqOpner.defaults[1] ```
This is commonly known as JSON (JavaScript Object Notation): <http://www.json.org/example.html>
5,262,389
I have a JavaScript code like that: ``` var faqOpener = { defaults: { idSelector: "#id", id: "2" }, ... if (options && !jQuery.isEmptyObject(options)) $.extend(this.defaults, options); ... ``` How can I convert that variable as an array of literal arrays something like: ``` var faqOpener = { defaults[]: { idSelector: "#id", id: "2" }, ... ``` **EDIT:** I will use that defaults variable from another javascript code. As shown in the example it has only one element at array of literal arrays however I should define it correctly and will able to pass variable length(for example array of literal arrays that has 3 array or 1 or more it depends) array of literal arrays.
2011/03/10
[ "https://Stackoverflow.com/questions/5262389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/453596/" ]
Do you want faqOpener.defaults to be an array of objects { idSelector, id }? In JS, an array literal is delimited by square brackets, so it'd look like this: ``` var faqOpener = { defaults: [ { idSelector: "#id", id: "2" }, { idSelector: "#id3", id: "3" }, ] }; ``` That's not an array of arrays, exactly; it's an array of *associative* arrays. An "array" in JavaScript is a particular object type with some special characteristics. Any old JS object is an assocative array.
This is commonly known as JSON (JavaScript Object Notation): <http://www.json.org/example.html>
5,262,389
I have a JavaScript code like that: ``` var faqOpener = { defaults: { idSelector: "#id", id: "2" }, ... if (options && !jQuery.isEmptyObject(options)) $.extend(this.defaults, options); ... ``` How can I convert that variable as an array of literal arrays something like: ``` var faqOpener = { defaults[]: { idSelector: "#id", id: "2" }, ... ``` **EDIT:** I will use that defaults variable from another javascript code. As shown in the example it has only one element at array of literal arrays however I should define it correctly and will able to pass variable length(for example array of literal arrays that has 3 array or 1 or more it depends) array of literal arrays.
2011/03/10
[ "https://Stackoverflow.com/questions/5262389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/453596/" ]
Try this: ``` var faqOpener = { defaults: [{ idSelector: "#id", id: "2" }], ... ``` Can be used like this: ``` faqOpener.defaults[0].id ```
This is commonly known as JSON (JavaScript Object Notation): <http://www.json.org/example.html>
5,262,389
I have a JavaScript code like that: ``` var faqOpener = { defaults: { idSelector: "#id", id: "2" }, ... if (options && !jQuery.isEmptyObject(options)) $.extend(this.defaults, options); ... ``` How can I convert that variable as an array of literal arrays something like: ``` var faqOpener = { defaults[]: { idSelector: "#id", id: "2" }, ... ``` **EDIT:** I will use that defaults variable from another javascript code. As shown in the example it has only one element at array of literal arrays however I should define it correctly and will able to pass variable length(for example array of literal arrays that has 3 array or 1 or more it depends) array of literal arrays.
2011/03/10
[ "https://Stackoverflow.com/questions/5262389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/453596/" ]
``` var faqOpener = { defaults: [ { idSelector: "#id", id: "2" }, { idSelector: "#id1", id: "21" } ] }; ``` Then you can access the objects in defaults: ``` faqOpner.defaults[0] faqOpner.defaults[1] ```
Do you want faqOpener.defaults to be an array of objects { idSelector, id }? In JS, an array literal is delimited by square brackets, so it'd look like this: ``` var faqOpener = { defaults: [ { idSelector: "#id", id: "2" }, { idSelector: "#id3", id: "3" }, ] }; ``` That's not an array of arrays, exactly; it's an array of *associative* arrays. An "array" in JavaScript is a particular object type with some special characteristics. Any old JS object is an assocative array.
5,262,389
I have a JavaScript code like that: ``` var faqOpener = { defaults: { idSelector: "#id", id: "2" }, ... if (options && !jQuery.isEmptyObject(options)) $.extend(this.defaults, options); ... ``` How can I convert that variable as an array of literal arrays something like: ``` var faqOpener = { defaults[]: { idSelector: "#id", id: "2" }, ... ``` **EDIT:** I will use that defaults variable from another javascript code. As shown in the example it has only one element at array of literal arrays however I should define it correctly and will able to pass variable length(for example array of literal arrays that has 3 array or 1 or more it depends) array of literal arrays.
2011/03/10
[ "https://Stackoverflow.com/questions/5262389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/453596/" ]
Try this: ``` var faqOpener = { defaults: [{ idSelector: "#id", id: "2" }], ... ``` Can be used like this: ``` faqOpener.defaults[0].id ```
Do you want faqOpener.defaults to be an array of objects { idSelector, id }? In JS, an array literal is delimited by square brackets, so it'd look like this: ``` var faqOpener = { defaults: [ { idSelector: "#id", id: "2" }, { idSelector: "#id3", id: "3" }, ] }; ``` That's not an array of arrays, exactly; it's an array of *associative* arrays. An "array" in JavaScript is a particular object type with some special characteristics. Any old JS object is an assocative array.
50,149,562
With old Jupyter notebooks, I could create interactive plots via: ``` import matplotlib.pyplot as plt %matplotlib notebook x = [1,2,3] y = [4,5,6] plt.figure() plt.plot(x,y) ``` However, in JupyterLab, this gives an error: ``` JavaScript output is disabled in JupyterLab ``` I have also tried the magic (with [`jupyter-matplotlib`](https://github.com/matplotlib/jupyter-matplotlib "jupyter-matplotlib") installed): ``` %matplotlib ipympl ``` But that just returns: ``` FigureCanvasNbAgg() ``` Inline plots work, but they are not interactive plots: ``` %matplotlib inline ```
2018/05/03
[ "https://Stackoverflow.com/questions/50149562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8233329/" ]
Steps for JupyterLab 3.\* ========================= I had previously used [Mateen](https://stackoverflow.com/users/365102/mateen-ulhaq)'s [answer](https://stackoverflow.com/a/55848505/10705616) several times, but when I tried them with JupyterLab 3.0.7 I found that `jupyter labextension install @jupyter-widgets/jupyterlab-manager` returned an error and I had broken widgets. After a lot of headaches and googling I thought I would post the solution for anyone else who finds themselves here. The steps are now simplified, and I was able to get back to working interactive plots with the following: 1. `pip install jupyterlab` 2. `pip install ipympl` 3. Decorate with `%matplotlib widget` Step 2 will automatically take care of the rest of the dependencies, including the replacements for (the now depreciated?) `@jupyter-widgets/jupyterlab-manager` Hope this saves someone else some time!
This [solution](https://www.allendowney.com/blog/2019/07/25/matplotlib-animation-in-jupyter/) works in jupyterlab ``` import numpy as np import matplotlib.pyplot as plt from IPython.display import clear_output n = 10 a = np.zeros((n, n)) plt.figure() for i in range(n): plt.imshow(a) plt.show() a[i, i] = 1 clear_output(wait=True) ```