Chaining methods/functions after initialisation in Swift - initialization

When I look at answers on Stack Overflow, I often will see something like the following (this is just a snippet, I know the code isn't truly complete):
let data = try Data(contentsOf: url)
let decoder = JSONDecoder()
let jsonData = try decoder.decode(ResponseData.self, from: data)
return jsonData.person
Why would you declare decoder = JSONDecoder() and then use decoder. on the next line? Wouldn't it be simpler to just do:
let jsonData = try JSONDecoder().decode(ResponseData.self, from: data)
Is this a stylistic thing or is there a technical reason for this?
(Sorry for asking this as a whole question. I tried to just ask it as a comment, but you have to have 50 rep to put a comment which makes it hard to ask simple questions like this, even though that is described as a valid thing to do in the comments).

Related

Retrieve and display last entry indatabase

Frank ยท 2 hours ago
Using Ionic 2, I am unsuccessfully trying to retrieve and display the newGoalWt, newMaxReps, newMinReps, repsToday, and wtToday shown at the bottom of the firebase data image. I do not want to retrieve the other data. I thought I found the answer to this several times, but I haven't. I am not trying to get others to do work I should be doing but I am new to coding and need help at this point. If you have another course that covers this by example please let me know. sample database
I hope this makes sense/is clear.
First thing is to create a provider which gets the details. So in the provider there will be a function like this :
public getRequiredObject(objectKey : String){
return this.database.object('wideGripBPTwo-list/'+ objectKey)
}
Then in the controller/typescript file i would have a variable assigned to the return value of the provider :
this.variableName = this.Provider.getRequiredObject(objectKey);
this.variableName.subscribe(snapshot => {
this.newGoalWt = snapshot.newGoalWt;
this.newMaxReps = snapshot.newMaxReps;
//add other variables here
Lastly in the html file just bind the data :
<ion-label>{{newGoalWt}}</ion-label>
Note I have not added entire provider, .ts file and html file.
Please advise if this makes sense and if you need more assistance.

Retrofit errorBody() should return Optional

Let's say I have a test with following assertion:
assertThat(response.isSuccess()).as(response.errorBody().string()).isTrue();
it will throw NullPointerException when response is success therefore test never passes.
I needed to make soemthing like this:
String errorDescription = response.errorBody() == null ? "" : response.errorBody().string();
assertThat(response.isSuccess()).as(errorDescription).isTrue();
which is ugly. Is it possible for errorBody to be wrapped in optional or maybe there is a better way for doing this?
Someone deleted my answer to that saying that I provided only url to github where it was answered. This was my answer to post:
Answered on github of Retrofit: https://github.com/square/retrofit/issues/1304
Optionals are not available on Android.
This time I emphasized actual answer so it will not be deleted again.

Firebase and Angularfire nightmare migration for Update

I am new to firebase and I am having a bit of a nightmare trying to adapt old code to what is now deprecated and what is not. I am trying to write a function which updates one "single" record in my datasource using the now approved $save()promise but it is doing some really strange stuff to my data source.
My function (should) enables you to modify a single record then update the posts json array. However, instead of doing this, it deletes the whole datasource on the firebase server and it is lucky that I am only working with testdata at this point because everything would be gone.
$scope.update = function() {
var fb = new Firebase("https://mysource.firebaseio.com/Articles/" + $scope.postToUpdate.$id);
var article = $firebaseObject(ref);
article.$save({
Title: $scope.postToUpdate.Title,
Body: $scope.postToUpdate.Body
}).then(function(ref) {
$('#editModal').modal('hide');
console.log($scope.postToUpdate);
}, function(error) {
console.log("Error:", error);
});
}
Funnily enough I then get a warning in the console "after" I click the button:
Storing data using array indices in Firebase can result in unexpected behavior. See https://www.firebase.com/docs/web/guide/understanding-data.html#section-arrays-in-firebase for more information. Also note that you probably wanted $firebaseArray and not $firebaseObject.
(No shit?) I am assuming here that $save() is not the right call, so what is the equivalent of $routeParams/$firebase $update()to do a simple binding of the modified data and my source? I have been spending hours on this and really don't know what is the right solution.
Unless there's additional code that you've left out, your article $firebaseObject should most likely use the fb variable you created just before it.
var article = $firebaseObject(fb);
Additionally, the way in which you're using $save() is incorrect. You need to modify the properties on the $firebaseObject directly and then call $save() with no arguments. See the docs for more.
article.Title = $scope.postToUpdate.Title;
article.Body = $scope.postToUpdate.Body;
article.$save().then(...

How to get inserted row ID with WebMatrix

There is a GetLastInsertId method in WebMatrix. However, using Reflector, I can see that it's implemented like this:
[return: Dynamic]
public object GetLastInsertId()
{
return this.QueryValue("SELECT ##Identity", new object[0]);
}
Which, as far as I can see, is a very bad way of doing it, because ##Identity returns the last insert considering every table and every session. I need this restricted to the scope and session I'm working with, so I was expecting this to use SELECT SCOPE_IDENTITY(), since that also seems to be what is most often used according to my reading.
My questions are:
Do the WebMatrix wrappers do something that makes this ok to use in my case?
If not, is there a simple way to get the inserted ID of an insert query using WebMatrix classes, or should I fall back on stuff like SqlClient for this?
I am interested in answers for SQL Server (not compact) if that makes a difference.
I had the same problem, and I read these answers but still couldn't get the code to work correctly. I possibly was misreading the solutions above, but what seemed to work for me was as follows:
var db=Database.Open(...);
var lastInsertID = db.QueryValue("INSERT name into Names; SELECT SCOPE_IDENTITY()");
To quote David Fowler, one of the devs on the Data APIs in WebMatrix: "[SCOPE_IDENITTY] doesn't work on ce". Since we wanted a data API that would work on both CE and regular SQL Server, we used ##Identity. So if you want to use SCOPE_IDENTITY specifically, you should use db.QueryValue method:
var db = Database.Open(...);
db.Insert(...);
var lastInsertId = db.QueryValue("SELECT SCOPE_IDENTITY()")
here is my solution
var db.Database.open('..');
var lastId = db.GetLastInsertId();

How can I implement a "Related questions" feature like the one on Stack Overflow?

I want to implement a feature similar to the "Related Questions" list shown when asking a question on Stack Overflow. I like how the related questions populated when the Title is filled in.
I am using ASP.NET and jQuery. How might I implement something like this? Can anyone point to examples?
I looked at the source of the ask question page and I don't see any onblur or focus calls.
As a matter of fact there is a call. This bit of code is responsible for the GET request which is sent to the server ob 'blur' of the #title input element (it's in the source of the page, close to the top):
$().ready(function() {
$("#title").blur(function() { QuestionSuggestions(); });
});
function QuestionSuggestions() {
var s = $("#title").val();
if (s.length > 2) {
document.title = s + " - Stack Overflow";
$("#question-suggestions").load("/search/titles?like="
+ escape(s));
}
}
I was thinking of implementing something similar, although this may not be an answer to your question, here is what I was planning to do:
When a question is saved parse it and create a topic word to uniqueid (of the post) mapping and save in database indexed by word.
When a new question is typed and the focus go out of the title, make an AJAX call with all the relevant words from the database and match all the similar ids that is common (so that at least two words have the same id)
Populate with div that is dynamically made visible.
I am interested to know if anyone has more insight on this...

Resources