Related
I have below Payload.
Here if points are not divisible by 5, then round up to the nearest 5. So, if the points are 250.2, the resulting number would be 250 and that is divisible by 5
so 250 would be the value returned.
If the resulting value was 251.2, then the resulting whole number would be 251 and that is not divisible by 5 and would be rounded up to 155
{
"referenceID": "1001",
"Year": "2023",
"Type": "BK",
"contracts": [
{
"contractId": "1",
"contractType": "Booking",
"Points": "250.2",
"Reservations": {
"reservations": [
],
"reservationPoints": ""
}
},
{
"contractId": "1",
"contractType": "Booking",
"Points": "251.2",
"Reservations": {
"reservations": [
],
"reservationPoints": ""
}
}
]
}
Based on above conditions, output payload should be like below
{
"referenceID": "1001",
"Year": "2023",
"Type": "BK",
"contracts": [
{
"contractId": "1",
"contractType": "Booking",
"Points": "250",
"Reservations": {
"reservations": [
],
"reservationPoints": ""
}
},
{
"contractId": "1",
"contractType": "Booking",
"Points": "255",
"Reservations": {
"reservations": [
],
"reservationPoints": ""
}
}
]
}
With regards to this rounding up Points to nearest number divisible by 5, I am using below logic
if (((payload.contracts[0].Points as Number mod 5))<1)
(round((payload.contracts[0].Points as Number)/5)*5)
else
(ceil((payload.contracts[0].Points as Number)/5)*5)
This gets the updated value based on condition but I am not able to update the Payload.
Make use of update operator just to update Points value in the payload Object. Try like below:
%dw 2.0
output application/json
---
payload update {
case c at .contracts -> c map ($ update{
case p at .Points -> if((p mod 5) <1) round((p/5))*5
else ceil((p/5))*5
})
}
Based on the above suggestion, I updated payload like below
%dw 2.0
output application/json
---
payload.contracts map ((item,index)-> item update {
case Points at .Points -> if (((Points as Number mod 5))<1) (round((Points as Number)/5)*5)
else (ceil((Points as Number)/5)*5)
})
I am trying to delete some number of hashes from an array if the particular keys in the hash contain or include some certain words. Find array below:
BANNED_WORDS = ['Hacked', 'hack', 'fraud', 'hacked']
data = [
{
"news_url": "https://www.benzinga.com/markets/cryptocurrency/21/10/23391043/north-vancouver-to-heat-buildings-with-bitcoin-mining",
"image_url": "https://crypto.snapi.dev/images/v1/m/v/fw-69939.jpeg",
"title": "North Vancouver To Heat Buildings With Bitcoin Mining",
"text": "Canadian hack Bitcoin (CRYPTO: BTC) mining firm MintGreen has partnered with state-owned Lonsdale Energy Corporation (LEC) to heat 100 residential and commercial buildings in North Vancouver with recovered energy from crypto mining.",
"source_name": "Benzinga",
"date": "Fri, 15 Oct 2021 12:16:19 -0400",
"topics": [
"mining"
],
"sentiment": "Neutral",
"type": "Article",
"tickers": [
"BTC"
]
},
{
"news_url": "https://u.today/ethereum-20-next-steps-to-mainnet-shared-by-ethereum-foundation",
"image_url": "https://crypto.snapi.dev/images/v1/b/t/10169-69937.jpg",
"title": "Ethereum 2.0 Next Steps to Mainnet Shared by Ethereum Foundation",
"text": "Ethereum (ETH) developers have entered final phase of testing before hotly anticipated ETH1-ETH2 transition",
"source_name": "UToday",
"date": "Fri, 15 Oct 2021 12:11:00 -0400",
"topics": [],
"sentiment": "Neutral",
"type": "Article",
"tickers": [
"ETH"
]
}
]
I am trying to delete any hash that either the text or title contains/include any word in the BANNED_WORDS array above.
I have tried the below and some other variations but none seem to be working. I am new to ruby, can someone please point me to what I am doing wrong, thanks.
data.select{|coin| coin[:text].split(" ").select{ |word| !BANNED_WORDS.include?(word) || coin[:title].split(" ").select{ |word| !BANNED_WORDS.include?(word)}}
So the result should be:
filtered_result = [
{
"news_url": "https://u.today/ethereum-20-next-steps-to-mainnet-shared-by-ethereum-foundation",
"image_url": "https://crypto.snapi.dev/images/v1/b/t/10169-69937.jpg",
"title": "Ethereum 2.0 Next Steps to Mainnet Shared by Ethereum Foundation",
"text": "Ethereum (ETH) developers have entered final phase of testing before hotly anticipated ETH1-ETH2 transition",
"source_name": "UToday",
"date": "Fri, 15 Oct 2021 12:11:00 -0400",
"topics": [],
"sentiment": "Neutral",
"type": "Article",
"tickers": [
"ETH"
]
}
]
This is a job for a regular expression.
R = /\b(?:#{BANNED_WORDS.join('|')})\b/
#=> /\b(?:Hacked|hack|fraud|hacked)\b/
data.reject { |h| h[:title].match?(R) || h[:text].match?(R) }
#=> [{:news_url=>"https://u.today/ethereum-20-next-steps...,
# ...
# :tickers=>["ETH"]}]
See Regexp#match?.
\b in the regular expression is a word boundary. They are there to prevent matches of, say, 'haskintosh' and 'defraud'.
I am working on a food delivery app, which uses parse as its backend. I am facing a problem while calling the placeOrder API through
PFCloud.callFunction(inBackground: PlaceOrder, withParameters: params) { (data, err) in}
Please have a look at the JSON which I need to post below.
{
"source": "card_1EVYuOEynlyM6L4SHgBMJYRQ",
"userId": "YjSZYSXEp7",
"data": {
"menuItems": [{
"id": "QSYa2JDcIm",
"title": "Rice With Tibss(Beef)",
"menuTitle": "Rice With Tibss",
"submenuItem": [{
"id": "zaOo6G4KSV",
"name": "Beef",
"price": 12,
"desc": "Fillings?"
}],
"price": 24,
"qty": 1,
"storeId": "yqBCDmzaDP",
"storeName": "Ibex Ethiopian Cusine and Bar",
"orderType": "takeout",
"taxState": 0.0925,
"storeInfo": {
"cart_storeId": "yqBCDmzaDP",
"cart_storeName": "Ibex Ethiopian Cusine and Bar",
"cart_storeImage": "https://res.cloudinary.com/http-get-tolofood-com/image/upload/c_scale,h_199,q_auto,w_270/v1461575640/Ibex_lopx38.jpg",
"cart_storeCuisine": "Ethiopian",
"cart_storeDescription": "We always serve a quality food. We always serve a quality food. We always serve a quality food. We always serve a quality food.",
"cart_storeRating": 3.33,
"cart_storeDelivery": false,
"takeout": true,
"address": "12255 Greenville Ave,Dallas, TX 75243",
"slugname": "TX_DAL_ibex_ethiopian_cuisine_and_bar",
"multiple_location": false,
"cart_storeDeliveryFee": 15,
"cart_storeServes": "Lunch,Dinner",
"busy": false,
"cart_storeSeoSlug": "ibex-ethiopian-cusine-and-bar"
},
"enable": true,
"voice_read_mi_label": "fbgcb",
"voice_read_mi_option": false,
"menuTypeName": "Standard"
}],
"lastOrderType": "takeout",
"searchedAddress": "takeout",
"timeData": {
"day": "06-05-2019",
"time": "12:55 am",
"tz": "America/Los_Angeles"
}
},
"unavailable_option": "restaurant_recommendation"
}
And below is the Swift code which I have used to make pass it.
let storeInfo: Dictionary = [CartStoreId: self.cartStoreId, CartStoreName: self.cartRestaurantName, CartStoreImage: self.cartStoreImage, CartStoreCuisine: self.cartStoreCuisine, CartStoreDescription: self.cartStoreDescription, CartStoreRating: self.cartStoreRating, CartStoreDelivery: self.cartStoreDelivery, Takeout: self.takeOut, Address: self.address, Slugname: self.slugName, MultipleLocation: self.multipleLocation, CartStoreDeliveryFee: self.cartStoreDelivery, CartStoreServes: self.cartStoreServes, Busy: self.busy, CartStoreSeoSlug: self.cartStoreSeoSlug] as Dictionary
let subMenuItem = ["id": "zaOo6G4KSV", "name": "Beef", "price": 12, "desc": "Fillings?", "voice_read_submi_label":"bf", "voice_read_submi_option":false, "disabled": false] as [String: Any]
let ordersDictionary = [
"id" : "1234",
"title" : "Test",
"menuTitle" : "MenuName",
"price" : 23,
"qty" : 2,
"storeId" : 23,
"orderType" : "standard",
"taxState" : 0.22,
"enable" : true,
"menuTypeName" : "Type Name",
"voice_read_mi_label":"fdfs",
"voice_read_mi_option":"false",
"submenuitem": subMenuItem,
"storeInfo": storeInfo
] as Dictionary
let timeData = ["day" : 17-06-2019, "time": "11:00 AM", "tz": "America/Los_Angeles"] as Dictionary
let data = ["menuItems": ordersDictionary, "lastOrderType": "takeout", "searchedAddress": "takeout", "timeData" : timeData] as Dictionary
let params = [UserId: self.userId, "source":"card_1EVYuOEynlyM6L4SHgBMJYRQ", "data": data, "unavailable_option":"restaurant_recommendation","_ApplicationId":"6EuadToYoFGJhI1sX8XnuFBz9tp9l3yH6HxzzXZO", "_JavaScriptKey":"rQkALu9saFtF2oq9yCibyw6mEcs3PVqct3uuP6vg", "_ClientVersion":"js1.6.14", "_InstallationId":"444ec64d-5fcc-7b8e-596e-6be627892c2a",
"_SessionToken":"r:c966376120c8eca77aa63c29d5bebe1a"] as Dictionary
After all this is done I call the parse function like below.
PFCloud.callFunction(inBackground: PlaceOrder, withParameters: params) { (data, err) in
if err != nil {
print(err!)
} else {
print(data!)
}
}
But this gives me error after a few seconds saying
"Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}"
I have searched the web with the error and made fixes accordingly but still no success. Please help me guys.
I noticed that your params var is not compatible with the JSON you sent, there are more fields and also missing fields. Moreover, menuItems and submenuItem are an Array in your JSON and an Object in your code. It is probably making the cloud code function to fail and you are therefore not receiving back a valid JSON. Try the following and check if it works. In the case it works, just replace the values by your vars.
let params = [
"source": "card_1EVYuOEynlyM6L4SHgBMJYRQ",
"userId": "YjSZYSXEp7",
"data": [
"menuItems": [[
"id": "QSYa2JDcIm",
"title": "Rice With Tibss(Beef)",
"menuTitle": "Rice With Tibss",
"submenuItem": [[
"id": "zaOo6G4KSV",
"name": "Beef",
"price": 12,
"desc": "Fillings?"
]],
"price": 24,
"qty": 1,
"storeId": "yqBCDmzaDP",
"storeName": "Ibex Ethiopian Cusine and Bar",
"orderType": "takeout",
"taxState": 0.0925,
"storeInfo": [
"cart_storeId": "yqBCDmzaDP",
"cart_storeName": "Ibex Ethiopian Cusine and Bar",
"cart_storeImage": "https://res.cloudinary.com/http-get-tolofood-com/image/upload/c_scale,h_199,q_auto,w_270/v1461575640/Ibex_lopx38.jpg",
"cart_storeCuisine": "Ethiopian",
"cart_storeDescription": "We always serve a quality food. We always serve a quality food. We always serve a quality food. We always serve a quality food.",
"cart_storeRating": 3.33,
"cart_storeDelivery": false,
"takeout": true,
"address": "12255 Greenville Ave,Dallas, TX 75243",
"slugname": "TX_DAL_ibex_ethiopian_cuisine_and_bar",
"multiple_location": false,
"cart_storeDeliveryFee": 15,
"cart_storeServes": "Lunch,Dinner",
"busy": false,
"cart_storeSeoSlug": "ibex-ethiopian-cusine-and-bar"
],
"enable": true,
"voice_read_mi_label": "fbgcb",
"voice_read_mi_option": false,
"menuTypeName": "Standard"
]],
"lastOrderType": "takeout",
"searchedAddress": "takeout",
"timeData": [
"day": "06-05-2019",
"time": "12:55 am",
"tz": "America/Los_Angeles"
]
],
"unavailable_option": "restaurant_recommendation"
]
I am tring to create a line graph by taking values from json file for x-axis and y-axis, but i am not able to fill the labels and series, can anyone please provide any inputs.
sample code :
<chartist class="ct-chart ct-major-twelfth" chartist-chart-type="Line"
chartist-data="View.lineData" chartist-chart-options="View.lineOptions">
</chartist>
ctrl.lineData = {
labels: [],
series: []
};
function data(data, cb) {
cb({
labels: getLabels(),
series: getSeries()
});
function getLabels() {
return [
ctrl.result[0] // i have to get the date values from json (1997,1999)
];
}
function getSeries() {
return [
ctrl.result[0] // have to fetch count values from json
];
}
sample json:
[ results :
count: 6
{
"year": 1997,
"make": "Ford",
"model": "E350",
"description": "ac, abs, moon",
"price": 3000
},
{
"year": 1999,
"make": "Chevy",
"model": "Venture \"Extended Edition\"",
"description": "",
"price": 4900
}
]
The following data is being used to load and display a grid dynamically. The only difference between the two grids is that the first reader takes in the data below as is, but the second grid only knows about the data and the metaData will be generated on the fly. I placed stubs for the fields and columns as this is not the issue and I haven't decided on how I will generate the data yet.
Both of the readers eventually pass the data below to the JsonReader's readRecords()' function via this.callParent([data]);, but the second one does not display the data. The data is there, but I am not sure why it does not display?
There are two links to demos below. The first is a JSFiddle that loads from memory and the second is a Sencha Fiddle that loads through AJAX.
Snippet
var rawFields = [
{ "name": "year", "type": "int" },
{ "name": "standard", "type": "string" },
{ "name": "bitRate", "type": "float" }
];
var rawColumns = [
{ "text" : "Year", "dataIndex" : "year", "flex" : 1 },
{ "text" : "Standard", "dataIndex" : "standard", "flex" : 1 },
{ "text" : "Bit/Sec", "dataIndex" : "bitRate", "flex" : 1 }
];
Ext.define('Example.reader.DynamicReader', {
extend : 'Ext.data.reader.Json',
alias : 'reader.dynamicReader',
readRecords : function(data) {
var response = {
data: data,
metaData : this.createMetaData(data),
success: true
};
console.log(response);
return this.callParent([response]);
},
createMetaData : function(data) {
return {
idProperty : "id",
fields : rawFields, // These will eventually be generated...
columns : rawColumns // These will eventually be generated...
};
}
});
Data
{
"data": [
{
"id": 0,
"year": 1997,
"standard": "802.11",
"bitRate": 2000000
},
{
"id": 1,
"year": 1999,
"standard": "802.11b",
"bitRate": 11000000
},
{
"id": 2,
"year": 1999,
"standard": "802.11a",
"bitRate": 54000000
},
{
"id": 3,
"year": 2003,
"standard": "802.11g",
"bitRate": 54000000
},
{
"id": 4,
"year": 2007,
"standard": "802.11n",
"bitRate": 600000000
},
{
"id": 5,
"year": 2012,
"standard": "802.11ac",
"bitRate": 1000000000
}
],
"metaData": {
"idProperty": "id",
"fields": [
{
"name": "year",
"type": "int"
},
{
"name": "standard",
"type": "string"
},
{
"name": "bitRate",
"type": "float"
}
],
"columns": [
{
"text": "Year",
"dataIndex": "year",
"flex": 1
},
{
"text": "Standard",
"dataIndex": "standard",
"flex": 1
},
{
"text": "Bit/Sec",
"dataIndex": "bitRate",
"flex": 1
}
],
"success": true
}
}
Demos
The following examples both achieve the same thing, so the only difference is the loading of the data.
Loading from Memory
http://jsfiddle.net/MrPolywhirl/zy4z5z8a/
Loading from AJAX
https://fiddle.sencha.com/#fiddle/d3l
I figured out the answer. I needed to specify a root value for the reader so that the data can be mapped properly.
Ext.onReady(function() {
Ext.widget("dynamicGrid", {
title: 'WiFi LAN Data Rates [Dynamic]',
renderTo: Ext.get('example-grid-dynamic'),
readerType: 'dynamicReader',
// This need to match the 'data' key specified in the `response` object
// that was created in readRecords().
readerRoot: 'data',
data : rawData
});
});
The documentation for root notes that the root property has to map to the data portion of the response.
Documentation for Json.root:
Ext.data.reader.Json.root
root : String
The name of the property which contains the data items corresponding to the Model(s) for which this Reader is configured. For JSON reader it's a property name (or a dot-separated list of property names if the root is nested). For XML reader it's a CSS selector. For Array reader the root is not applicable since the data is assumed to be a single-level array of arrays.