Swift - Getting Error while using replacingOccurrence - swift

So I'm taking Udacity's Swift for Developers course. I attempted to look at the forums for this question but oddly, they were quiet. This is the programming prompt:
var forwardString = "stressed"
var backwardsString = forwardString.characters.reversed()
print(backwardsString)
var lottaLikes = "If likeyou wanna learn Swift likeyou should build lots of small apps cuz it's likea good way to practice."
var noLikes = lottaLikes.replacingOccurrences(of:"like", with:"")
print(noLikes)
For whatever reason, I keep getting this error message:
Be sure that you have replaced all occurences of the word "like" and removed any extra spaces.
What am I missing here? If you need clarification on this I would be happy to provide it.
Thank you

It may be that your code gets the job done, but only because your variable lottaLikes is written in a weird way. You usually would have two spaces surrounding the word "like" so just removing the word would leave 2 spaces in a row. I would suggest writing the following line:
var noLikes = lottaLikes.replacingOccurrences(of:"like ", with:"")
It may be that Udacity is not checking the actual output, but the code itself. If so, It may be looking for something like I wrote above.
If this still does not work, you may want to write another line like so:
var noExtraSpaces = noLikes.replacingOccurences(of: " ", with: " ")

Related

Swift Print() not displaying results

I am new to learning Swift. I am currently taking a course through Udemy. I was attempting to use the following command, which did not yield a result.
print(inches_tall = (feet * 12) + inches)
I got back the following: "()\n"
I am posting to see, what I am missing, also to get back into the community as I continue my journey.
I was attempting to use the print() to display. I did not "need" to use print. I was looking for additional ways to solve the small building-block-task I was given.

When using OPT-2.7B or any other natural language model, is there a way to trick it into having a conversation/ give it a pre prompt in the code

Using this code, or a variant of, is there anything that can be added to "trick" opt into conversing as another user in a style more similar to a chatbot. As of now it will either start something more similar to an article or have a conversation with itself for a few lines as seen below.
val = input("Enter your value: ")
input_ids = tokenizer((val), return_tensors='pt').input_ids
output = model.generate(input_ids, min_length=1, max_length=1024, penalty_alpha=0.6, top_k=6)
print("Output:\n" + 100 * '-')
print(tokenizer.decode(output[0], skip_special_tokens=True))
print("" + 100 * '-')
with open("OutputText.txt", "w") as f:
f.write(tokenizer.decode(output[0], skip_special_tokens=True))
Here's an example of the current output:
*User Input:
Hello There.
Model Output:
Hello there. I have an egg that matches your TSV. Would you mind hatching it for me?
Sure, I'll add you now. Let me know when you're online.
Sorry for the late reply. I'm online now for the next few hours. Just send me a trade request whenever you're ready.
No probs, I'm in the middle of a battle at the moment, but I'll get you as soon as I'm done.
Thank you very much for the hatch. Have a nice day :D
*
I've attempted to add a prompt to the start and it hasn't made a difference.

SharePoint REST: Column does not exist error

I'm calling a REST API with a SharePoint Designer workflow on SharePoint online. I'm setting the column name with a variable, and when i put the variable into my URL to call it it says "Column [name] does not exist".
Annoying part is when I call just /items? I can see the column in the result, but if I try select it or filter by it I get 'does not exist'. I have alot of these columns similarly named, and I get the error for all of them.
I am using the internal name, I have tried adding "OData_" to the front. I've tried typing the url manually in the browser and entering values (incase the variable was causing issues) but I get the same error, column does not exist. but i can see it them I call all items. :(
so I have quite a few columns with naming convention "[Q#] Score [#]" eg "Q4 Score 2". The internal name that's clearly appearing in the full items results is "Q4_x0020_Score_x0020_2".
This works:
https://MYSITE.sharepoint.com/sites/portal/intranet/CorpServices/QSR/_api/web/lists/GetbyTitle('Audit')/Items?
and I get big full normal REST results that includes the line:
0
However if I try:
https://MYSITE.sharepoint.com/sites/portal/intranet/CorpServices/QSR/_api/web/lists/GetbyTitle('Audit')/Items?$Select=Q4_x0020_Score_x0020_2
Then I get:
-2146232832, Microsoft.SharePoint.SPExceptionColumn 'Q4_x0020_Score_x0020_2' does not exist. It may have been deleted by another user.
I expect to be able to select that column (and the dozens like it) but none work. I've searched all similar problems on the forum and they've usually got a spelling mistake or forgot the ODATA_ but i cant seem to get the problem. Please help.
It seemed to be working intermittently.... So it was in fact just a naming error...... Half of the columns were [Q#]_x0020_Score_x0020_[#] and half were [Q#]_x0020_score_x0020_[#]. The word "Score" was capitalized on some and not others. I Didn't realize the HTTP Calls were case sensitive. Now I have added a bunch of if statements to handle the different variations haha. Thanks for reading.
Judging by the naming convention you are on an older version of SharePoint. The x0020 is the value for a space. Ideally when you first create the column you would name it without the spacing. For example UserInformation. Then come in and edit the name after the fact and call it User Information. If you click on the title name and look at the URL, you will see what the actual name of the column is at the end of the URL. It is case sensitive because you can have a column named score and Score which is ultimately why it wasn't working.
Must load all fields like this
var lists = context.Web.Lists;
context.Load(lists);
context.ExecuteQuery();
CamlQuery query = new CamlQuery();
query.ViewXml = #"";
var list = lists.GetById("file.guid");
var listitems = list.GetItems(query);
context.Load(listitems);
context.ExecuteQuery();
var creationInformation = new ListItemCreationInformation();
var newItem=list.AddItem(creationInformation);
var fields = list.Fields;
context.Load(fields);
context.ExecuteQuery();

Autocomplete with Firebase

How does one use Firebase to do basic auto-completion/text preview?
For example, imagine a blog backed by Firebase where the blogger can tag posts with tags. As the blogger is tagging a new post, it would be helpful if they could see all currently-existing tags that matched the first few keystrokes they've entered. So if "blog," "black," "blazing saddles," and "bulldogs" were tags, if the user types "bl" they get the first three but not "bulldogs."
My initial thought was that we could set the tag with the priority of the tag, and use startAt, such that our query would look something like:
fb.child('tags').startAt('bl').limitToFirst(5).once('value', function(snap) {
console.log(snap.val())
});
But this would also return "bulldog" as one of the results (not the end of the world, but not the best either). Using startAt('bl').endAt('bl') returns no results. Is there another way to accomplish this?
(I know that one option is that this is something we could use a search server, like ElasticSearch, for -- see https://www.firebase.com/blog/2014-01-02-queries-part-two.html -- but I'd love to keep as much in Firebase as possible.)
Edit
As Kato suggested, here's a concrete example. We have 20,000 users, with their names stored as such:
/users/$userId/name
Oftentimes, users will be looking up another user by name. As a user is looking up their buddy, we'd like a drop-down to populate a list of users whose names start with the letters that the searcher has inputted. So if I typed in "Ja" I would expect to see "Jake Heller," "jake gyllenhaal," "Jack Donaghy," etc. in the drop-down.
I know this is an old topic, but it's still relevant. Based on Neil's answer above, you more easily search doing the following:
fb.child('tags').startAt(queryString).endAt(queryString + '\uf8ff').limit(5)
See Firebase Retrieving Data.
The \uf8ff character used in the query above is a very high code point
in the Unicode range. Because it is after most regular characters in
Unicode, the query matches all values that start with queryString.
As inspired by Kato's comments -- one way to approach this problem is to set the priority to the field you want to search on for your autocomplete and use startAt(), limit(), and client-side filtering to return only the results that you want. You'll want to make sure that the priority and the search term is lower-cased, since Firebase is case-sensitive.
This is a crude example to demonstrate this using the Users example I laid out in the question:
For a search for "ja", assuming all users have their priority set to the lowercased version of the user's name:
fb.child('users').
startAt('ja'). // The user-inputted search
limitToFirst(20).
once('value', function(snap) {
for(key in snap.val()){
if(snap.val()[key].indexOf('ja') === 0) {
console.log(snap.val()[key];
}
}
});
This should only return the names that actually begin with "ja" (even if Firebase actually returns names alphabetically after "ja").
I choose to use limitToFirst(20) to keep the response size small and because, realistically, you'll never need more than 20 for the autocomplete drop-down. There are probably better ways to do the filtering, but this should at least demonstrate the concept.
Hope this helps someone! And it's quite possible the Firebase guys have a better answer.
(Note that this is very limited -- if someone searches for the last name, it won't return what they're looking for. Hence the "best" answer is probably to use a search backend with something like Kato's Flashlight.)
It strikes me that there's a much simpler and more elegant way of achieving this than client side filtering or hacking Elastic.
By converting the search key into its' Unicode value and storing that as the priority, you can search by startAt() and endAt() by incrementing the value by one.
var start = "ABA";
var pad = "AAAAAAAAAA";
start += pad.substring(0, pad.length - start.length);
var blob = new Blob([start]);
var reader = new FileReader();
reader.onload = function(e) {
var typedArray = new Uint8Array(e.target.result);
var array = Array.prototype.slice.call(typedArray);
var priority = parseInt(array.join(""));
console.log("Priority of", start, "is:", priority);
}
reader.readAsArrayBuffer(blob);
You can then limit your search priority to the key "ABB" by incrementing the last charCode by one and doing the same conversion:
var limit = String.fromCharCode(start.charCodeAt(start.length -1) +1);
limit = start.substring(0, start.length -1) +limit;
"ABA..." to "ABB..." ends up with priorities of:
Start: 65666565656565650000
End: 65666665656565650000
Simples!
Based on Jake and Matt's answer, updated version for sdk 3.1. '.limit' no longer works:
firebaseDb.ref('users')
.orderByChild('name')
.startAt(query)
.endAt(`${query}\uf8ff`)
.limitToFirst(5)
.on('child_added', (child) => {
console.log(
{
id: child.key,
name: child.val().name
}
)
})

How do I Benchmark RESTful Service with Variable Parameters?

I'm currently working on benchmarking a RESTful service I've made, and part of that is making sure it runs in a reasonable amount of times for a large array of parameters. For example, let's say I have RESTful API of the form some_site.com/item?item_id=y. In that case to be sure my service is working as fast as I'd like it to work, I'd want to try out many values for y one by one, preferably coming from some text file. I can't figure out any way of doing this in ab or httperf. I'm open to using a different benchmarking program if I have, but would prefer something simple and light. What I want to do seems like something pretty standard, so I'm guessing there must already be a program that let's me do it, but an hour or so of googling hasn't gotten me an answer. Ideas?
Answer: Jmeter (which is apparently awesome). This faq explains how to do it. Hopefully this helps someone else, as it took me like a day of searching to figure this out.
I have just had some good experience with using JavaScript (via BSF/Rhino) in JMeter.
I have put one thread group in my test plan and stick a 'Simple Controller' with two elements under it - 'HTTP Request' sampler and 'BSF PreProcessor'.
Set BSF language to 'javascript' and either type the code into the text box or point it to a file (use full path or relative to CWD of JMeter process).
/* Since `Math.random()` gives us float, we use `java.util.Random()`
* see: http://docs.oracle.com/javase/7/docs/api/java/util/Random.html */
var Random = new Packages.java.util.Random();
var min = 10-1;
var max = 2;
var maxLines = (min)+Random.nextInt(max-min);
var s = '';
for (var d = 0; d <= maxLines; d++) {
s += d.toString()+','+Random.nextInt(1000).toString()+'\n';
}
// s => '0,312\n1,104\n2,608\n'
vars.put('PAYLOAD', s);
Now I can refer to ${PAYLOAD} in the HTTP request!
You can generate JSON, but you will need to upgrade jakarta-jmeter-2.5.1/lib/js-1.6R5.jar with the newest version of Rhino to get JSON.stringify and JSON.parse. That worked perfectly for me also, though I thought I'd put a simple example here.
You can use BSF pre-processor for URL params as well, just set another variable with vars.put('X', 'some value') and pass it as ${X} in the request parameter.
This blog post helped quite a bit, by the way.