Result of call to 'onReceive(_:perform:)' is unused - timer

The call to input is unused, I see some people use an _ but I get the same error. thank you
Text("Distance: \(self.travelDistance)").modifier(MainMenuModifier(trimColor: .green))
.onReceive(self.timer) { input in
self.latitude2 = location.coordinate.latitude
self.longitude2 = location.coordinate.longitude
self.travelDistance = self.calculateDistance(lat1: self.latitude1, lon1: self.longitude1, lat2: self.latitude2, lon2: self.longitude2)
print("travel distance: \(self.travelDistance)")
}

Related

caught TypeError: Cannot read properties of undefined

I can't figure out where I went wrong I keep getting the same error, I already defined i with let but it keeps saying I haven't defined i I am lost, I am very new to coding.
import { films } from '../data/films.js'
console.log(films[0].url)
function getLastNumber(url) {
const secondToLastLetterOfUrl = url[url.length - 2]
return secondToLastLetterOfUrl
let filmList = document.querySelector('#filmlist')
for (let i = 0; i < films.length; i++) { }
let figure = document.createElement('figure')
let figImage = document.createElement('img')
let figCaption = document.createElement('figcaption')
let filmNum = getLastNumber(films[i].url)
figImage.src = `https://starwars-visualguide.com/assets/img/films/${filmNum}.jpg`
figCaption.textContent = films[i].title
figure.appendChild(figImage)
figure.appendChild(figCaption)
filmList.appendChild(figure)
There are two problems with your code:
getLastNumber is missing the closing curly brace. It probably would go after the return.
The for loop is empty. The scope of i is limited to the for loop, so when you try to access i four lines later, it is undefined. You probably want to move the closing curly bracket of the for loop after filmList.append(figure) line.

How do I guard a pop?

I'm using strict mode. I've got the following code:
const a: string[] = [];
// something that fills `a`
while (a.length > 0) {
const i: string = a.pop(); // Error on this line
console.log(i);
// maybe add something else to `a`
}
In this case, I'm getting an error on the line, because pop has a return type of string | null. Which makes sense for a general use of the pop method, but I'm guarding against that case? Is there a more typescript way of doing this to get the proper typeguard?
I can't just loop over the array (e.g. using of), because sometimes a gets new items added to it during the loop and the semantics aren't the same.
Why don't you check pop data before you pop?
if (a[a.length -1]) {
const i: string = a.pop()
}
a.pop()

Getting "temporary value dropped while borrowed" when trying to update an Option<&str> in a loop

I'm trying to implement a commonly used pattern - using the result of a previous loop iteration in the next loop iteration. For example, to implement pagination where you need to give the id of the last value on the previous page.
struct Result {
str: String,
}
fn main() {
let times = 10;
let mut last: Option<&str> = None;
for i in 0..times {
let current = do_something(last);
last = match current {
Some(r) => Some(&r.str.to_owned()),
None => None,
};
}
}
fn do_something(o: Option<&str>) -> Option<Result> {
Some(Result {
str: "whatever string".to_string(),
})
}
However, I'm not sure how to actually get the value out of the loop. Currently, the compiler error is temporary value dropped while borrowed (at &r.str.to_owned()), though I made many other attempts, but to no avail.
The only way I found to actually get it working is to create some sort of local tmp_str variable and do a hack like this:
match current {
Some(r) => {
tmp_str.clone_from(&r.str);
last = Some(&tmp_str);
}
None => {
last = None;
}
}
But that doesn't feel like it's the way it's supposed to be done.
In your code, it remains unclear who the owner of the String referenced in last: Option<&str> is supposed to be. You could introduce an extra mutable local variable that owns the string. But then you would have two variables: the owner and the reference, which seems redundant. It would be much simpler to just make last the owner:
struct MyRes {
str: String,
}
fn main() {
let times = 10;
let mut last: Option<String> = None;
for _i in 0..times {
last = do_something(&last).map(|r| r.str);
}
}
fn do_something(_o: &Option<String>) -> Option<MyRes> {
Some(MyRes {
str: "whatever string".to_string(),
})
}
In do_something, you can just pass the whole argument by reference, this seems more likely to be what you wanted. Also note that naming your own struct Result is a bad idea, because Result is such a pervasive trait built deeply into the compiler (?-operator etc).
Follow-up question: Option<&str> or Option<String>?
Both Option<&str> and Option<String> have different trade-offs. One is better for passing string literals, other is better for passing owned Strings. I'd actually propose to use neither, and instead make the function generic over type S that implements AsRef<str>. Here is a comparison of various methods:
fn do_something(o: &Option<String>) {
let _a: Option<&str> = o.as_ref().map(|r| &**r);
let _b: Option<String> = o.clone();
}
fn do_something2(o: &Option<&str>) {
let _a: Option<&str> = o.clone(); // do you need it?
let _b: Option<String> = o.map(|r| r.to_string());
}
fn do_something3<S: AsRef<str>>(o: &Option<S>) {
let _a: Option<&str> = o.as_ref().map(|s| s.as_ref());
let _b: Option<String> = o.as_ref().map(|r| r.as_ref().to_string());
}
fn main() {
let x: Option<String> = None;
let y: Option<&str> = None;
do_something(&x); // nice
do_something(&y.map(|r| r.to_string())); // awkward & expensive
do_something2(&x.as_ref().map(|x| &**x)); // cheap but awkward
do_something2(&y); // nice
do_something3(&x); // nice
do_something3(&y); // nice, in both cases
}
Note that not all of the above combinations are very idiomatic, some are added just for completeness (e.g. asking for AsRef<str> and then building an owned String out of seems a bit strange).
r.str.to_owned() is a temporary value. You can take a reference to a temporary, but because the temporary value will usually be dropped (destroyed) at the end of the innermost enclosing statement, the reference becomes dangling at that point. In this case the "innermost enclosing statement" is either the last line of the loop, or the loop body itself -- I'm not sure exactly which one applies here, but it doesn't matter, because either way, you're trying to make last contain a reference to a String that will soon be dropped, making last unusable. The compiler is right to stop you from using it again in the next iteration of the loop.
The easiest fix is just to not make last a reference at all -- in the example, it's not necessary or desirable. Just use Option<String>:
fn main() {
let times = 10;
let mut last = None;
for _ in 0..times {
last = match do_something(last) {
Some(r) => Some(r.str),
None => None,
};
}
}
fn do_something(_: Option<String>) -> Option<Result> {
// ...
}
There are also ways to make the reference version work; here is one:
let mut current; // lift this declaration out of the loop so `current` will have
// a lifetime longer than one iteration
for _ in 0..times {
current = do_something(last);
last = match current {
Some(ref r) => Some(&r.str), // borrow from `current` in the loop instead
// of from a newly created String
None => None,
};
}
You might want to do this if your code is more complicated than the example and using String would mean a lot of potentially expensive .clone()s.

How to properly check if array contains an element inside if statement

I have this line of code:
if ((self.datasource?.contains((self.textField?.text)!)) != nil) {
if let _ = self.placeHolderWhileSelecting {
// some code
}
Is there more clear way to check if the element contains in array? I have Bool returned by contains function, I dont want to check if this Bool is nil
Edit: the solution is to change array to non-optional type.
You can use the if let where construct. This code prevent crashes if self.datasource or self.textField are nil
if let
list = self.datasource,
elm = self.textField?.text,
_ = self.placeHolderWhileSelecting
where list.contains(elm) {
// your code
}
Another possible solution, using optional chaining to get to self.textField.text and assuming datasource remains optional.
if let unwrappedArray = self.datasource, let unwrappedString = self.textField?.text {
if unwrappedArray.contains(unwrappedString) {
// Some code
}
}

Drupal site received url request embedding suspicious codes presuming attempt of hacking

I found a url request having suspicious code to one of my Drupal site. Will someone explain what will be the depth of this code and advise any precautions to be taken. Code:
function (){try{var _0x5757=["/x6C/x65/x6E/x67/x74/x68","/x72/x61/x6E/x64/x6F/x6D","/x66/x6C/x6F/x6F/x72"],_0xa438x1=this[_0x5757[0]],_0xa438x2,_0xa438x3;if(_0xa438x1==0){return};while(--_0xa438x1){_0xa438x2=Math[_0x5757[2]](Math[_0x5757[1]]()*(_0xa438x1 1));_0xa438x3=this[_0xa438x1];this[_0xa438x1]=this[_0xa438x2];this[_0xa438x2]=_0xa438x3;};}catch(e){}finally{return this}}
Site returned page not found error and I observed no issues.
Run this code through a beatifier and you will receive:
function () {
try {
var _0x5757 = ["/x6C/x65/x6E/x67/x74/x68", "/x72/x61/x6E/x64/x6F/x6D", "/x66/x6C/x6F/x6F/x72"],
_0xa438x1 = this[_0x5757[0]],
_0xa438x2, _0xa438x3;
if (_0xa438x1 == 0) {
return
};
while (--_0xa438x1) {
_0xa438x2 = Math[_0x5757[2]](Math[_0x5757[1]]() * (_0xa438x1 1));
_0xa438x3 = this[_0xa438x1];
this[_0xa438x1] = this[_0xa438x2];
this[_0xa438x2] = _0xa438x3;
};
} catch (e) {} finally {
return this
}
}
First, let's rename some variables and decrypt the array of strings in the third line. I've renamed _0x5757 to arr and escaped the hex-chars within the array. That gives you:
var arr = ["length", "random", "floor"],
So here we have a list of functions that will be used shortly. Substitute the strings in and rename the variables and you will receive:
function () {
try {
var arr = ["length", "random", "floor"],
length_func = "length",
rand_number, temp;
if (length_func == 0) {
return
};
while (--length_func) {
rand_number = Math["floor"](Math["random"]() * (length_func 1));
temp = this[length_func];
this[length_func] = this[rand_number];
this[rand_number] = temp;
};
} catch (e) {} finally {
return this
}
}
Notice how there is a syntax error in the script when generating a random number.
* (length_func 1)
with length_func = "length" is not valid JavaScript syntax, so the code is actually not functional. I can still make a guess on what it was supposed to do: If we remove the obfuscation of calling a function by doing Math["floor"] instead of Math.floor() the important lines are
while (--length_func) {
rand_number = Math.floor( Math.random() * ( length 1 ));
temp = this.length_func;
this.length_func = this.rand_number;
this.rand_number = temp;
};
It seems that it tries to compute a random integer using Math.random() and Math.floor(), then swaps the contents of the variables length_func and rand_numerber, all wrapped in a while(--length_func) loop. There's nothing functional here or anything that makes sense. An attempt at an infinte loop hanging the browser maybe? The code is, as it stands, non-functional. It even fails to generate a random number, because Math.floor() will always round-down the inputted float, and Math.rand() will generate a number within 0.0 to 1.0, so nearly always something slightly below 1.0, therefore rand_number = 0 for most of the time. The multiplication with the rand() output with the length_func 1 maybe should have made the number bigger, but the syntax is invalid. When I use my browser's console to execute length, it gives me 0, when I try to do length(1), then length is not a function, the only length that makes sense here is a string-length or array length, but then it would have to explicitly be "someString".length. Hope this helps you.

Resources