SwiftUI - Adding locations to data model - mapkit

I currently have a data model that has an array of venues and I'm trying to add in location information for each venue. I'm running into a problem when I'm defining the struct. Here is an example of the data.
venues: [
Venue (
title: "Holiday",
venueImage: "defaultVenue",
venueDesc: "ipsum lorem",
venueArea: "World East",
coordinate: .init(latitude: -33.852222, longitude: 151.210556),
venueItems: [
venueItem (
id: 101,
title: "Potato Dumpling",
itemURL: "default.png",
productDescription: "Potato Dumpling with Mushroom Sauce",
productPrice: 4.50,
productType: "Food",
newStatus: false,
diningPlan: false,
kidFriendly: true,
vegetarian: false,
glutenFree: false,
featuredProduct: false,
containsAlcohol: false
)])]
And here is the struct
struct Venue: Identifiable {
let id = UUID()
let title : String
let venueImage: String
let venueDesc : String
let venueArea: String
let coordinate: CLLocationCoordinate2D
let venueItems: [venueItem]
init(title: String,
venueImage: String,
venueDesc: String,
venueArea: String,
coordinate: CLLocationCoordinate2D,
venueItems: Array<Any>) {
self.title = title
self.venueDesc = venueDesc
self.venueArea = venueArea
**self.venueItems = [venueItem]**
self.coordinate = coordinate
}
}
The error I'm getting is: Cannot assign value of type '[venueItem].Type' to type '[venueItem]'

struct VenueItem: Identifiable {
var id = UUID()
var title: String
var itemURL: String
var productDescription: String
var productPrice: Float
var productType: String
var newStatus: Bool
var diningPlan: Bool
var kidFriendly: Bool
var vegetarian: Bool
var glutenFree: Bool
var featuredProduct: Bool
var containsAlcohol: Bool
}
struct Venue: Identifiable {
var id = UUID()
var title: String
var venueImage: String
var venueDesc: String
var venueArea: String
var coordinate: CLLocationCoordinate2D
var venueItems: [VenueItem]
}
let venues = [
Venue(
title: "Holiday",
venueImage: "defaultVenue",
venueDesc: "ipsum lorem",
venueArea: "World East",
coordinate: .init(latitude: -33.852222, longitude: 151.210556),
venueItems: [
VenueItem(
title: "Potato Dumpling",
itemURL: "default.png",
productDescription: "Potato Dumpling with Mushroom Sauce",
productPrice: 4.50,
productType: "Food",
newStatus: false,
diningPlan: false,
kidFriendly: true,
vegetarian: false,
glutenFree: false,
featuredProduct: false,
containsAlcohol: false
)
]
)
]

Related

EIP712: ecrecover returns different address

I am trying to sign typed data via MetaMask "eth_signTypedData_v4". Recovering signer via recoverTypedSignature_v4 returns correct address that I signed my data with. But smart contract returns wrong address every time as ecrecover output. Can't understand what is wrong with the code.
js:
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();// 签名
const signerAddress = (await signer.getAddress()).toLowerCase();
const originalMessage = {
types: {
EIP712Domain: [
{ name: "name", type: "string" },
{ name: "version", type: "string" },
{ name: "chainId", type: "uint256" },
{ name: "verifyingContract", type: "address" }
],
Greeting: [
{ name: 'contents', type: 'string' },
{ name: "sender", type: "address" },
{ name: "x", type: "uint256" }
],
},
primaryType: 'Greeting',
domain: {
name: 'SignatureVerifyTest',
version: '1',
chainId: 31337,
verifyingContract: "0x5fbdb2315678afecb367f032d93f642f64180aa3"
},
message: {
contents: 'Hello',
sender: signerAddress,
x: 123
}
};
const signedMessage = await signer.provider.send("eth_signTypedData_v4", [signerAddress, JSON.stringify(originalMessage)]);
const { v, r, s } = ethers.utils.splitSignature(signedMessage);
console.log('signerAddress:', signerAddress)
console.log("r:", r);
console.log("s:", s);
console.log("v:", v);
bytes32 eip712DomainHash = keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes("SignatureVerifyTest")),
keccak256(bytes("1")),
block.chainid,
address(this)
)
);
bytes32 hashStruct = keccak256(
abi.encode(keccak256("Greeting(string contents,address sender,uint256 x)"), contents, sender, x)
);
bytes32 hash = ECDSA.toTypedDataHash(eip712DomainHash, hashStruct);
address signer = ECDSA.recover(hash, v, r, s);
console.log("sender", sender);
console.log("signer", signer);

Can't deserialize to pojo class (Kotlin) (RestAssured)

**Hello! Here is the request to the server **
var stories: Story? =
given().log().all()
.contentType(ContentType.JSON)
.body(body)
.`when`().log().all()
.post(baseURI)
.then().log().all()
.extract().`as`(Story::class.java)
println (Story().title)
println (Story().id)
println (Story().items)
Here is POJO class
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
#JsonIgnoreProperties(ignoreUnknown = true)
class Data {
var stories: String? = null
}
class Story() {
var id = 0
var title: String? = null
var description: String? = null
var imageUrl: String? = null
var imageUrlEco: String? = null
var images: String? = null
var style: String? = null
var styleWeb: String? = null
var link: String? = null
var linkWeb: String? = null
var linkEco: String? = null
var buttonText: String? = null
var dateFrom: String? = null
var dateTo: String? = null
var hidden: String? = null
var isAuth: String? = null
var onboardingType: String? = null
var sortOrder = 0
var type: String? = null
var items: String? = null
}
class Item {
var id = 0
var title: String? = null
var description: String? = null
var detailedDescription: String? = null
var imageUrl: String? = null
var imageUrlWeb: String? = null
var style: String? = null
var styleWeb: String? = null
var sortOrder = 0
}
**And here is the response itself **
{
"data": {
"stories": \[
{
"id": 1234,
"title": "AnyText",
"description": "AnyText",
"imageUrl": "AnyText",
"imageUrlEco": AnyText,
"images": \[
],
"style": "AnyText",
"styleWeb": "AnyText",
"link": AnyText,
"linkWeb": AnyText,
"linkEco": AnyText,
"buttonText": "AnyText",
"dateFrom": "2022-11-22T00:00:00Z",
"dateTo": "2023-01-08T00:00:00Z",
"hidden": AnyText,
"isAuth": AnyText,
"onboardingType": AnyText,
"sortOrder": 1234,
"type": "AnyText",
"items": [
{
"id": 1234,
"title": "AnyText",
"description": "AnyText",
"detailedDescription": "AnyText",
"imageUrl": "AnyText",
"imageUrlWeb": "AnyText",
"style": "AnyText",
"styleWeb": "AnyText",
"sortOrder": 1
}
]
}
]
}
}
So when I try this:
println (Story().title)
println (Story().id)
println (Story().items)
The result of running the program is:
null
0
null
What I did wrong?
I have not used RestAssured so I cannot comment on the syntax/correctness of that, but your error is incorrectly referencing the object you have deserialized from the GET request.
var stories: Story? =
this means assign the result to a variable named stories
Later you write
println (Story().title)
what this means it print the field title from a brand new Story object. You should be doing this:
println (stories.title)
println (stories.id)
println (stories.items)
(stories should be named story if it represents one)

Check null value in a quiz

I did a quiz with vue.js and i would like to check if a value is null before put it in the console.log. I Can't find how to do that...
I have a lot of questions to put in this quiz but some of them just need to be ignored in the final result. I just want to bypass all the questions with value:null.
"use strict";
window.onload = function() {
var quiz = {
title: 'Quizz',
questions: [{
text: "Question 1",
responses: [{
text: 'a',
value: null,
},
{
text: 'b',
value: null,
}
]
},
{
text: "Question 2",
responses: [{
text: 'a',
value: '1',
},
{
text: 'b',
value: '2',
}
]
}
]
};
var app = new Vue({
el: '#app',
data: {
quiz: quiz,
questionIndex: 0,
userResponses: Array(),
show: true
},
methods: {
// Go to next question
next: function() {
console.log(this.userResponses);
this.questionIndex++;
},
// Go to previous question
prev: function() {
this.questionIndex--;
},
score: function() {
//find the highest occurence in responses
var userResponses = Array.prototype.concat.apply([], this.userResponses);
var modeMap = {};
var maxEl = userResponses,
maxCount = 1;
for (var i = 0; i < userResponses.length; i++) {
var el = userResponses[i];
if (modeMap[el] == null)
modeMap[el] = 1;
else
modeMap[el]++;
if (modeMap[el] > maxCount) {
maxEl = el;
maxCount = modeMap[el];
}
}
return maxEl;
}
}
});
}
I find it, just add : var userResponses = this.userResponses.filter(Boolean);

Alamofire + Decodable - how turn responseJSON to NSData

I'm pretty sure that my problem is easy solving, but I can't find any solution.
So I have Alamofire request and have a trouble with handling data types. I have so many 'printing out' just to check what data I've got step by step.
Alamofire.request(URL, method: .get, headers: headers).responseJSON { response in
switch responseJSON.result {
case .success(let value):
print(type(of: value)) //__NSDictionaryI
print(value)
print(type(of:responseJSON)) //DataResponse<Any>
print(responseJSON) . //SUCCESS: {"billing_addresses" = (...
print(responseJSON.value as Any) . //Optional({...
//print(responseJSON.value as! [[String:Any]]) . //Could not cast value of type '__NSDictionaryI' (0x10b9fb508) to 'NSArray' (0x10b9fb008).
do {
let decoder = JSONDecoder()
let model = try decoder.decode(Info.self, from: value as! Data) //Decode JSON Response Data
print(model.id)
} catch let parsingError {
print("Error", parsingError)
}
Now I have an error: **Could not cast value of type '__NSSingleEntryDictionaryI' (0x10d240f78) to 'NSData' (0x10d241090).**
value of responseJSON is:
(I'm not sure that this value is correct, because when I've check in Postman all strings is doublequoted, and value of "is_default" is true/false, not 0/1. But in the Xcode I've got this in the console. So maybe problem in the responseJSON?..)
And there could be zero address, or several ones.
{
"id": 40128,
"username": "test6",
"email": "test6#on.com",
"billing_addresses": [
{
"address_name": null,
"country_code": "US",
"first_name": "Ted",
"last_name": "Qqqq",
"company_name": "",
"address_line1": "308 Sea Lane",
"address_line2": "",
"city": "QQQQ",
"state": "FL",
"postcode": "32000",
"email_address": "test6#on.com",
"phone_number": "11111111",
"is_default_for_billing": true
}
],
"shipping_addresses": [
{
"address_name": null,
"country_code": "US",
"first_name": "Ted",
"last_name": "Qqqq",
"company_name": "",
"address_line1": "308 Sea Lane",
"address_line2": "",
"city": "QQQQ",
"state": "FL",
"postcode": "32000",
"is_default_for_shipping": true
}
]
}
And here is model
struct Info : Decodable {
let id: Int
let email: String
let username: String
let billing_addresses: Billings
let shipping_addresses: Shippings
}
struct Billings: Decodable{
let address_name: String
let country_code: String
let first_name: String
let last_name: String
let company_name: String
let address_line1: String
let address_line2: String
let city: String
let state: String
let postcode: String
let email_address: String
let phone_number: String
let is_default_for_billing: Bool
}
struct Shippings:Decodable{
let address_name: String
let country_code: String
let first_name: String
let last_name: String
let company_name: String
let address_line1: String
let address_line2: String
let city: String
let state: String
let postcode: String
let is_default_for_shipping: Bool
}
If I try to use SwiftyJSON with value as parameter I have an error that Any couldn't be Data and I really don't know what should I do.
responseJSON.result.value returns the deserialized collection type, in your case a dictionary [String:Any]
To use JSONDecoder you need the raw data which is in response.data
let model = try decoder.decode(Info.self, from: response.data) //Decode JSON Response Data
Consider that you will run into decoding errors: billing_addresses and shipping_addresses are arrays
let billing_addresses: [Billings]
let shipping_addresses: [Shippings] // better name both structs in singular form (Billing, Shipping)
and a few values could be numbers rather than strings.
Anyway it's recommended to use the convertFromSnakeCase key decoding strategy to get rid of the ugly snake_case names.
Edit:
Here are your structs with camelCased names and singular forms, you have to add
decoder.keyDecodingStrategy = .convertFromSnakeCase
struct Info : Decodable {
let id: Int
let email: String
let username: String
let billingAddresses: [Billing]
let shippingAddresses: [Shipping]
}
struct Billing : Decodable {
let addressName: String?
let countryCode, firstName, lastName, companyName: String
let addressLine1, addressLine2, city, state, postcode: String
let emailAddress, phoneNumber: String
let isDefaultForBilling: Bool
}
struct Shipping : Decodable {
let addressName: String?
let countryCode, firstName, lastName, companyName: String
let addressLine1, addressLine2, city, state, postcode: String
let isDefaultForShipping: Bool
}

MyOrder in Express.js

How to create order model and ordersRoute in express.js ?
var globalConfig = require('../../public/js/globalConfig'),
_ = require('underscore'),
mongoosePaginate = require('mongoose-paginate');
module.exports = function(mongoose) {
var Schema = mongoose.Schema,
deepPopulate = require('mongoose-deep-populate')(mongoose);
var OrderSchema = new Schema({
code : String,
date : { type: Date, default: Date.now },
status : { type: String, enum: _.keys(globalConfig.orderStatus)},
_products : [{
//product : {type: Schema.Types.ObjectId, ref: 'Product'},
product : {},
quantity : Number
}],
user : {type: Schema.Types.ObjectId, ref: 'User'},
totalOrder : Number,
_addresses : {
billing : {
name : String,
address : String,
zipCode : String,
city : String,
country : String
},
// Times
createdAt : { type: Date, default: Date.now },
updatedAt : { type: Date, default: Date.now }
});
OrderSchema.plugin(mongoosePaginate);
OrderSchema.plugin(deepPopulate, {});
module.exports = mongoose.model('Order', OrderSchema);
}