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); ```
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
0
Edit dataset card