I am creating a project that displays the current weather of an area by name search. I fetch the API data from open weather: https://openweathermap.org/current?fbclid=IwAR1SVc9zn9uXaZWLmJA9lYEeZvUc1s_kR68RFadWuIwd8yBjIyJ7zsVMKkE
I have added all the parametres of the API to my code, but if you search some areas, they don't "return" all the weather API parameters. For example, when I search my city's weather at the moment, the parameter " Atmospheric pressure on the sea level" is displaying "undefined" because as Open Weather stated:
Because of that, I don't want the final project to display:
Atmospheric pressure on the sea level: undefined
I want it to return something among the lines of:
Atmospheric pressure on the sea level: not found
As you can see, the data type undefined is replaced with a string.
However, I have found a function here on this site that replaces undefined with "0" and it seems to work because it is marked as "solution". Due to my lack of knowledge tho, I cant get it to work.
The code I have found:
function replaceUndefined(displayWeather){
if(typeof(displayWeather) === "undefined"){
return "0"; // return 0 as replace, and end function execution
}
return displayWeather; // if the above state is false, functions continues and return original value
};
Now, here is my whole JAVASCRIPT code:
let weather = {
apiKey: "χχχχχχχχχχχχχχχ",
fetchWeather: function (city) {
fetch(
"https://api.openweathermap.org/data/2.5/weather?q=" +
city +
"&units=metric&lang=el&appid=" +
this.apiKey
)
.then((response) => {
if (!response.ok) {
alert("No weather found.");
throw new Error("No weather found.");
}
return response.json();
})
.then((data) => this.displayWeather(data));
},
displayWeather: function (data) {
const { name } = data;
const { lon } = data.coord;
const { lat } = data.coord;
const { icon, description } = data.weather[0];
const { temp, humidity } = data.main;
const {temp_min} = data.main;
const {temp_max} = data.main;
const { pressure } = data.main;
const { sea_level } = data.main;
const { speed } = data.wind;
const { deg } = data.wind;
const { sunrise } = data.sys;
const { sunset } = data.sys;
//getting the data from the JSON API file.
document.querySelector(".city").innerText = "Καιρός: " + name;
// (".city") is the class name from the DIV in HTML file.
document.querySelector(".lon").innerText = "Γεωγραφικό μήκος (longitude): " + lon;
document.querySelector(".lat").innerText = "Γεωγραφικό πλάτος (latitude): " + lat;
document.querySelector(".icon").src =
"https://openweathermap.org/img/wn/" + icon + ".png";
document.querySelector(".description").innerText = description;
document.querySelector(".temp").innerText = temp + "°C";
document.querySelector(".temp_min").innerText = "Ελάχιστη θερμοκρασία (αυτην την στιγμή): " + temp_min + "°C";
document.querySelector(".temp_max").innerText = "Μέγιστη θερμοκρασία (αυτην την στιγμή): " + temp_max + "°C";
document.querySelector(".humidity").innerText =
"Υγρασία: " + humidity + "%";
document.querySelector(".pressure").innerText = "Πιέση: " + pressure;
document.querySelector(".sea-pressure").innerText = "Ατμοσφαιρική πίεση στο επίπεδο της θάλασσας: " + sea_level;
document.querySelector(".wind").innerText =
"Ταχύτητα αέρα: " + speed + " km/h";
document.querySelector(".wind-deg").innerText = "Κατεύθυνση του αέρα (degrees): " + deg;
document.querySelector(".sunrise").innerText = "Ανατολή Ήλιου: " + window.moment(sunrise * 1000).format('HH:mm a');
document.querySelector(".sunset").innerText = "Δύση Ήλιου: " + window.moment(sunset * 1000).format('HH:mm a');
document.querySelector(".weather").classList.remove("loading");
document.body.style.backgroundImage =
"url('https://source.unsplash.com/1600x900/?')";
},
search: function () {
this.fetchWeather(document.querySelector(".search-bar").value);
},
};
document.querySelector(".search button").addEventListener("click", function () {
weather.search();
});
document
.querySelector(".search-bar")
.addEventListener("keyup", function (event) {
if (event.key == "Enter") {
weather.search();
}
});
weather.fetchWeather("London");
//Loads weather of London when the page opens
(some texts in the code are in greek because I want the text that is displayed on the page, to be in that language)
Thank you. Please I need solution.
document.querySelector(".sea-pressure").innerText = "Ατμοσφαιρική πίεση στο επίπεδο της θάλασσας: " + sea_level || 'not found';
Or just for hide all the line if data doesn't exist
if(seal_level){
document.querySelector(".sea-pressure").innerText = "Ατμοσφαιρική πίεση στο επίπεδο της θάλασσας: " + sea_level;
}
I am currently trying to replace the name of a file in the Mid Server after a scheduled export.
The idea here is that the file goes with the name in the format "file_name_datetime" and the customer needs "datetime_file_name" for the file to be correctly read by another system.
My main idea was to rename the file after the export to the correct format, but if there is a way of changing the file name to the required one I could do that also.
I would love to hear from you guys as I have no idea how can I do this.
Thanks in advance.
If anyone is interested in the answer, see below:
Script include:
initialize: function() {
this.filePath = gs.getProperty('directory_path');
this.midServer = gs.getProperty('midserver');
this.authMidServerBase64 = gs.getProperty('authmidserver');
},
nameChange: function(exportSetName) {
var exportGr = new GlideRecord("sys_export_set_run");
exportGr.addEncodedQuery("set.nameSTARTSWITH" + exportSetName);
exportGr.orderByDesc("completed");
exportGr.query();
if (exportGr.next()) {
var attachSysID = exportGr.ecc_agent_attachment.sys_id;
}
var attachGr = new GlideRecord("sys_attachment");
attachGr.addEncodedQuery("table_sys_idSTARTSWITH" + attachSysID);
attachGr.query();
if (attachGr.next()) {
var attachName = attachGr.file_name;
var attachDate = attachName.match((/\d+/));
var newName = attachDate + '_' + exportSetName + '.csv';
}
var jspr = new JavascriptProbe(this.midServer);
jspr.setName('FileNameChange'); // This can be any name
jspr.setJavascript('var ddr = new MidServer_script_include(); res = ddr.execute();');
jspr.addParameter("verbose", "true");
jspr.addParameter("skip_sensor", "true"); // prevent Discovery sensors running for the ECC input
jspr.addParameter("filename", this.filePath + "\\" + attachName);
jspr.addParameter("filePath", this.filePath);
jspr.addParameter("newName", this.filePath + "\\" + newName);
jspr.addParameter("operation", "rename");
return jspr.create();
},
Mid Server Script include:
initialize: function() {
/**
*** Set up the Packages references
**/
this.File = Packages.java.io.File;
this.FileOutputStream = Packages.java.io.FileOutputStream;
this.FileInputStream = Packages.java.io.FileInputStream;
this.Path = Packages.java.nio.file.Path;
this.Paths = Packages.java.nio.file.Paths;
this.Files = Packages.java.nio.file.Files;
this.StandardCopyOption = Packages.java.nio.file.StandardCopyOption;
/**
/* Set up the parameters
**/
this.verbose = probe.getParameter("verbose");
this.filePath = probe.getParameter("filePath");
this.filename = probe.getParameter("filename");
this.operation = probe.getParameter("operation");
this.newName = probe.getParameter("newName");
result = "initialize complete";
},
execute: function() {
if (this.operation == 'rename') {
this.fileRename(this.filename, this.newName);
}
return result;
},
fileRename: function(fileName, newName) {
result+= "\r\n Renaming file.";
this._debug(result);
try {
var res = this._moveFile(fileName, newName);
} catch (e) {
result += "\r\n Erro no renomeamento do ficheiro: " + e;
this._debug(result);
}
},
_moveFile: function(initialPath, targetPath) {
try {
this._debug("Initiating file move function");
var inPath = this.Paths.get(initialPath);
var tgPath = this.Paths.get(targetPath);
var res = this.Files.move(inPath, tgPath, this.StandardCopyOption.REPLACE_EXISTING);
result += "File successfully moved from: " + initialPath + " to: " + targetPath + " \r\n Result: " + res;
this._debug(result);
} catch (e) {
this._debug('Error:' + e);
}
},
_debug: function(m) {
if (this.verbose == "true") {
ms.log("::: Mid Server script include logger ::: " + m);
}
},
https://community.servicenow.com/community?id=community_question&sys_id=a56b38a6db326490fa192183ca961987
I am new to the IOT world and have been confused why I have not been able to use the Eclipse Paho JavaScript Client to connect to test.mosquitto.org.
I have used Port: 8080 and Path: /mqtt as has been suggested in other paho-mqtt questions, but am met with a Failed to connect: AMQJS0007E Socket error:undefined when using this Eclipse web client.
I have used the HiveMQ WebClient and have been able to connect, publish and subscribe to both test.mosquitto.org (Port 8080) and iot.eclipse.org (Port 443).
I have noticed that HiveMQ sources mqttws31.js compared to Paho Eclipse's paho-mqtt.js, but am unsure of the significance.
I would say there are two parts to this question:
What am I missing to get the Eclipse Paho JavaScript Client to connect to test.mosquitto.org ?
What is the difference between mqttws31.js and paho-mqtt.js that allows one to connect to test.mosquitto.org relatively painlessly compared to the other?
Thanks !
Relevant Code:
The code below is taken directly from the page source of https://www.eclipse.org/paho/clients/js/utility/
paho-mqtt.js: https://www.eclipse.org/paho/js/paho-mqtt.js
utility.js (handles button callbacks):
/*******************************************************************************
* Copyright (c) 2015 IBM Corp.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* James Sutton - Initial Contribution
*******************************************************************************/
/*
Eclipse Paho MQTT-JS Utility
This utility can be used to test the Eclipse Paho MQTT Javascript client.
*/
// Create a client instance
var client = null;
var connected = false;
logMessage("INFO", "Starting Eclipse Paho JavaScript Utility.");
// Things to do as soon as the page loads
document.getElementById("clientIdInput").value = "js-utility-" + makeid();
// called when the client connects
function onConnect(context) {
// Once a connection has been made, make a subscription and send a message.
var connectionString = context.invocationContext.host + ":" + context.invocationContext.port + context.invocationContext.path;
logMessage("INFO", "Connection Success ", "[URI: ", connectionString, ", ID: ", context.invocationContext.clientId, "]");
var statusSpan = document.getElementById("connectionStatus");
statusSpan.innerHTML = "Connected to: " + connectionString + " as " + context.invocationContext.clientId;
connected = true;
setFormEnabledState(true);
}
function onConnected(reconnect, uri) {
// Once a connection has been made, make a subscription and send a message.
logMessage("INFO", "Client Has now connected: [Reconnected: ", reconnect, ", URI: ", uri, "]");
connected = true;
}
function onFail(context) {
logMessage("ERROR", "Failed to connect. [Error Message: ", context.errorMessage, "]");
var statusSpan = document.getElementById("connectionStatus");
statusSpan.innerHTML = "Failed to connect: " + context.errorMessage;
connected = false;
setFormEnabledState(false);
}
// called when the client loses its connection
function onConnectionLost(responseObject) {
if (responseObject.errorCode !== 0) {
logMessage("INFO", "Connection Lost. [Error Message: ", responseObject.errorMessage, "]");
}
connected = false;
}
// called when a message arrives
function onMessageArrived(message) {
logMessage("INFO", "Message Recieved: [Topic: ", message.destinationName, ", Payload: ", message.payloadString, ", QoS: ", message.qos, ", Retained: ", message.retained, ", Duplicate: ", message.duplicate, "]");
var messageTime = new Date().toISOString();
// Insert into History Table
var table = document.getElementById("incomingMessageTable").getElementsByTagName("tbody")[0];
var row = table.insertRow(0);
row.insertCell(0).innerHTML = message.destinationName;
row.insertCell(1).innerHTML = safeTagsRegex(message.payloadString);
row.insertCell(2).innerHTML = messageTime;
row.insertCell(3).innerHTML = message.qos;
if (!document.getElementById(message.destinationName)) {
var lastMessageTable = document.getElementById("lastMessageTable").getElementsByTagName("tbody")[0];
var newlastMessageRow = lastMessageTable.insertRow(0);
newlastMessageRow.id = message.destinationName;
newlastMessageRow.insertCell(0).innerHTML = message.destinationName;
newlastMessageRow.insertCell(1).innerHTML = safeTagsRegex(message.payloadString);
newlastMessageRow.insertCell(2).innerHTML = messageTime;
newlastMessageRow.insertCell(3).innerHTML = message.qos;
} else {
// Update Last Message Table
var lastMessageRow = document.getElementById(message.destinationName);
lastMessageRow.id = message.destinationName;
lastMessageRow.cells[0].innerHTML = message.destinationName;
lastMessageRow.cells[1].innerHTML = safeTagsRegex(message.payloadString);
lastMessageRow.cells[2].innerHTML = messageTime;
lastMessageRow.cells[3].innerHTML = message.qos;
}
}
function connectionToggle() {
if (connected) {
disconnect();
} else {
connect();
}
}
function connect() {
var hostname = document.getElementById("hostInput").value;
var port = document.getElementById("portInput").value;
var clientId = document.getElementById("clientIdInput").value;
var path = document.getElementById("pathInput").value;
var user = document.getElementById("userInput").value;
var pass = document.getElementById("passInput").value;
var keepAlive = Number(document.getElementById("keepAliveInput").value);
var timeout = Number(document.getElementById("timeoutInput").value);
var tls = document.getElementById("tlsInput").checked;
var automaticReconnect = document.getElementById("automaticReconnectInput").checked;
var cleanSession = document.getElementById("cleanSessionInput").checked;
var lastWillTopic = document.getElementById("lwtInput").value;
var lastWillQos = Number(document.getElementById("lwQosInput").value);
var lastWillRetain = document.getElementById("lwRetainInput").checked;
var lastWillMessageVal = document.getElementById("lwMInput").value;
if (path.length > 0) {
client = new Paho.Client(hostname, Number(port), path, clientId);
} else {
client = new Paho.Client(hostname, Number(port), clientId);
}
logMessage("INFO", "Connecting to Server: [Host: ", hostname, ", Port: ", port, ", Path: ", client.path, ", ID: ", clientId, "]");
// set callback handlers
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
client.onConnected = onConnected;
var options = {
invocationContext: { host: hostname, port: port, path: client.path, clientId: clientId },
timeout: timeout,
keepAliveInterval: keepAlive,
cleanSession: cleanSession,
useSSL: tls,
reconnect: automaticReconnect,
onSuccess: onConnect,
onFailure: onFail
};
if (user.length > 0) {
options.userName = user;
}
if (pass.length > 0) {
options.password = pass;
}
if (lastWillTopic.length > 0) {
var lastWillMessage = new Paho.Message(lastWillMessageVal);
lastWillMessage.destinationName = lastWillTopic;
lastWillMessage.qos = lastWillQos;
lastWillMessage.retained = lastWillRetain;
options.willMessage = lastWillMessage;
}
// connect the client
client.connect(options);
var statusSpan = document.getElementById("connectionStatus");
statusSpan.innerHTML = "Connecting...";
}
function disconnect() {
logMessage("INFO", "Disconnecting from Server.");
client.disconnect();
var statusSpan = document.getElementById("connectionStatus");
statusSpan.innerHTML = "Connection - Disconnected.";
connected = false;
setFormEnabledState(false);
}
// Sets various form controls to either enabled or disabled
function setFormEnabledState(enabled) {
// Connection Panel Elements
if (enabled) {
document.getElementById("clientConnectButton").innerHTML = "Disconnect";
} else {
document.getElementById("clientConnectButton").innerHTML = "Connect";
}
document.getElementById("hostInput").disabled = enabled;
document.getElementById("portInput").disabled = enabled;
document.getElementById("clientIdInput").disabled = enabled;
document.getElementById("pathInput").disabled = enabled;
document.getElementById("userInput").disabled = enabled;
document.getElementById("passInput").disabled = enabled;
document.getElementById("keepAliveInput").disabled = enabled;
document.getElementById("timeoutInput").disabled = enabled;
document.getElementById("tlsInput").disabled = enabled;
document.getElementById("automaticReconnectInput").disabled = enabled;
document.getElementById("cleanSessionInput").disabled = enabled;
document.getElementById("lwtInput").disabled = enabled;
document.getElementById("lwQosInput").disabled = enabled;
document.getElementById("lwRetainInput").disabled = enabled;
document.getElementById("lwMInput").disabled = enabled;
// Publish Panel Elements
document.getElementById("publishTopicInput").disabled = !enabled;
document.getElementById("publishQosInput").disabled = !enabled;
document.getElementById("publishMessageInput").disabled = !enabled;
document.getElementById("publishButton").disabled = !enabled;
document.getElementById("publishRetainInput").disabled = !enabled;
// Subscription Panel Elements
document.getElementById("subscribeTopicInput").disabled = !enabled;
document.getElementById("subscribeQosInput").disabled = !enabled;
document.getElementById("subscribeButton").disabled = !enabled;
document.getElementById("unsubscribeButton").disabled = !enabled;
}
function publish() {
var topic = document.getElementById("publishTopicInput").value;
var qos = document.getElementById("publishQosInput").value;
var message = document.getElementById("publishMessageInput").value;
var retain = document.getElementById("publishRetainInput").checked;
logMessage("INFO", "Publishing Message: [Topic: ", topic, ", Payload: ", message, ", QoS: ", qos, ", Retain: ", retain, "]");
message = new Paho.Message(message);
message.destinationName = topic;
message.qos = Number(qos);
message.retained = retain;
client.send(message);
}
function subscribe() {
var topic = document.getElementById("subscribeTopicInput").value;
var qos = document.getElementById("subscribeQosInput").value;
logMessage("INFO", "Subscribing to: [Topic: ", topic, ", QoS: ", qos, "]");
client.subscribe(topic, { qos: Number(qos) });
}
function unsubscribe() {
var topic = document.getElementById("subscribeTopicInput").value;
logMessage("INFO", "Unsubscribing: [Topic: ", topic, "]");
client.unsubscribe(topic, {
onSuccess: unsubscribeSuccess,
onFailure: unsubscribeFailure,
invocationContext: { topic: topic }
});
}
function unsubscribeSuccess(context) {
logMessage("INFO", "Unsubscribed. [Topic: ", context.invocationContext.topic, "]");
}
function unsubscribeFailure(context) {
logMessage("ERROR", "Failed to unsubscribe. [Topic: ", context.invocationContext.topic, ", Error: ", context.errorMessage, "]");
}
function clearHistory() {
var table = document.getElementById("incomingMessageTable");
//or use : var table = document.all.tableid;
for (var i = table.rows.length - 1; i > 0; i--) {
table.deleteRow(i);
}
}
// Just in case someone sends html
function safeTagsRegex(str) {
return str.replace(/&/g, "&").replace(/</g, "<").
replace(/>/g, ">");
}
function makeid() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 5; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
function logMessage(type, ...content) {
var consolePre = document.getElementById("consolePre");
var date = new Date();
var timeString = date.toUTCString();
var logMessage = timeString + " - " + type + " - " + content.join("");
consolePre.innerHTML += logMessage + "\n";
if (type === "INFO") {
console.info(logMessage);
} else if (type === "ERROR") {
console.error(logMessage);
} else {
console.log(logMessage);
}
}
The code below is taken directly from the page source of http://www.hivemq.com/demos/websocket-client/
mqttws31.js: http://www.hivemq.com/demos/websocket-client/js/mqttws31.js
app.js (handles app callbacks):
/**
* Copyright 2013 dc-square GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* #author: Christoph Schäbel
*/
var websocketclient = {
'client': null,
'lastMessageId': 1,
'lastSubId': 1,
'subscriptions': [],
'messages': [],
'connected': false,
'connect': function () {
var host = $('#urlInput').val();
var port = parseInt($('#portInput').val(), 10);
var clientId = $('#clientIdInput').val();
var username = $('#userInput').val();
var password = $('#pwInput').val();
var keepAlive = parseInt($('#keepAliveInput').val());
var cleanSession = $('#cleanSessionInput').is(':checked');
var lwTopic = $('#lwTopicInput').val();
var lwQos = parseInt($('#lwQosInput').val());
var lwRetain = $('#LWRInput').is(':checked');
var lwMessage = $('#LWMInput').val();
var ssl = $('#sslInput').is(':checked');
this.client = new Messaging.Client(host, port, clientId);
this.client.onConnectionLost = this.onConnectionLost;
this.client.onMessageArrived = this.onMessageArrived;
var options = {
timeout: 3,
keepAliveInterval: keepAlive,
cleanSession: cleanSession,
useSSL: ssl,
onSuccess: this.onConnect,
onFailure: this.onFail
};
if (username.length > 0) {
options.userName = username;
}
if (password.length > 0) {
options.password = password;
}
if (lwTopic.length > 0) {
var willmsg = new Messaging.Message(lwMessage);
willmsg.qos = lwQos;
willmsg.destinationName = lwTopic;
willmsg.retained = lwRetain;
options.willMessage = willmsg;
}
this.client.connect(options);
},
'onConnect': function () {
websocketclient.connected = true;
console.log("connected");
var body = $('body').addClass('connected').removeClass('notconnected').removeClass('connectionbroke');
websocketclient.render.hide('conni');
websocketclient.render.show('publish');
websocketclient.render.show('sub');
websocketclient.render.show('messages');
},
'onFail': function (message) {
websocketclient.connected = false;
console.log("error: " + message.errorMessage);
websocketclient.render.showError('Connect failed: ' + message.errorMessage);
},
'onConnectionLost': function (responseObject) {
websocketclient.connected = false;
if (responseObject.errorCode !== 0) {
console.log("onConnectionLost:" + responseObject.errorMessage);
}
$('body.connected').removeClass('connected').addClass('notconnected').addClass('connectionbroke');
websocketclient.render.show('conni');
websocketclient.render.hide('publish');
websocketclient.render.hide('sub');
websocketclient.render.hide('messages');
//Cleanup messages
websocketclient.messages = [];
websocketclient.render.clearMessages();
//Cleanup subscriptions
websocketclient.subscriptions = [];
websocketclient.render.clearSubscriptions();
},
'onMessageArrived': function (message) {
// console.log("onMessageArrived:" + message.payloadString + " qos: " + message.qos);
var subscription = websocketclient.getSubscriptionForTopic(message.destinationName);
var messageObj = {
'topic': message.destinationName,
'retained': message.retained,
'qos': message.qos,
'payload': message.payloadString,
'timestamp': moment(),
'subscriptionId': subscription.id,
'color': websocketclient.getColorForSubscription(subscription.id)
};
console.log(messageObj);
messageObj.id = websocketclient.render.message(messageObj);
websocketclient.messages.push(messageObj);
},
'disconnect': function () {
this.client.disconnect();
},
'publish': function (topic, payload, qos, retain) {
if (!websocketclient.connected) {
websocketclient.render.showError("Not connected");
return false;
}
var message = new Messaging.Message(payload);
message.destinationName = topic;
message.qos = qos;
message.retained = retain;
this.client.send(message);
},
'subscribe': function (topic, qosNr, color) {
if (!websocketclient.connected) {
websocketclient.render.showError("Not connected");
return false;
}
if (topic.length < 1) {
websocketclient.render.showError("Topic cannot be empty");
return false;
}
if (_.find(this.subscriptions, { 'topic': topic })) {
websocketclient.render.showError('You are already subscribed to this topic');
return false;
}
this.client.subscribe(topic, {qos: qosNr});
if (color.length < 1) {
color = '999999';
}
var subscription = {'topic': topic, 'qos': qosNr, 'color': color};
subscription.id = websocketclient.render.subscription(subscription);
this.subscriptions.push(subscription);
return true;
},
'unsubscribe': function (id) {
var subs = _.find(websocketclient.subscriptions, {'id': id});
this.client.unsubscribe(subs.topic);
websocketclient.subscriptions = _.filter(websocketclient.subscriptions, function (item) {
return item.id != id;
});
websocketclient.render.removeSubscriptionsMessages(id);
},
'deleteSubscription': function (id) {
var elem = $("#sub" + id);
if (confirm('Are you sure ?')) {
elem.remove();
this.unsubscribe(id);
}
},
'getRandomColor': function () {
var r = (Math.round(Math.random() * 255)).toString(16);
var g = (Math.round(Math.random() * 255)).toString(16);
var b = (Math.round(Math.random() * 255)).toString(16);
return r + g + b;
},
'getSubscriptionForTopic': function (topic) {
var i;
for (i = 0; i < this.subscriptions.length; i++) {
if (this.compareTopics(topic, this.subscriptions[i].topic)) {
return this.subscriptions[i];
}
}
return false;
},
'getColorForPublishTopic': function (topic) {
var id = this.getSubscriptionForTopic(topic);
return this.getColorForSubscription(id);
},
'getColorForSubscription': function (id) {
try {
if (!id) {
return '99999';
}
var sub = _.find(this.subscriptions, { 'id': id });
if (!sub) {
return '999999';
} else {
return sub.color;
}
} catch (e) {
return '999999';
}
},
'compareTopics': function (topic, subTopic) {
var pattern = subTopic.replace("+", "(.*?)").replace("#", "(.*)");
var regex = new RegExp("^" + pattern + "$");
return regex.test(topic);
},
'render': {
'showError': function (message) {
alert(message);
},
'messages': function () {
websocketclient.render.clearMessages();
_.forEach(websocketclient.messages, function (message) {
message.id = websocketclient.render.message(message);
});
},
'message': function (message) {
var largest = websocketclient.lastMessageId++;
var html = '<li class="messLine id="' + largest + '">' +
' <div class="row large-12 mess' + largest + '" style="border-left: solid 10px #' + message.color + '; ">' +
' <div class="large-12 columns messageText">' +
' <div class="large-3 columns date">' + message.timestamp.format("YYYY-MM-DD HH:mm:ss") + '</div>' +
' <div class="large-5 columns topicM truncate" id="topicM' + largest + '" title="' + Encoder.htmlEncode(message.topic, 0) + '">Topic: ' + Encoder.htmlEncode(message.topic) + '</div>' +
' <div class="large-2 columns qos">Qos: ' + message.qos + '</div>' +
' <div class="large-2 columns retain">';
if (message.retained) {
html += 'Retained';
}
html += ' </div>' +
' <div class="large-12 columns message break-words">' + Encoder.htmlEncode(message.payload) + '</div>' +
' </div>' +
' </div>' +
'</li>';
$("#messEdit").prepend(html);
return largest;
},
'subscriptions': function () {
websocketclient.render.clearSubscriptions();
_.forEach(websocketclient.subscriptions, function (subs) {
subs.id = websocketclient.render.subscription(subs);
});
},
'subscription': function (subscription) {
var largest = websocketclient.lastSubId++;
$("#innerEdit").append(
'<li class="subLine" id="sub' + largest + '">' +
' <div class="row large-12 subs' + largest + '" style="border-left: solid 10px #' + subscription.color + '; background-color: #ffffff">' +
' <div class="large-12 columns subText">' +
' <div class="large-1 columns right closer">' +
' x' +
' </div>' +
' <div class="qos">Qos: ' + subscription.qos + '</div>' +
' <div class="topic truncate" id="topic' + largest + '" title="' + Encoder.htmlEncode(subscription.topic, 0) + '">' + Encoder.htmlEncode(subscription.topic) + '</div>' +
' </div>' +
' </div>' +
'</li>');
return largest;
},
'toggleAll': function () {
websocketclient.render.toggle('conni');
websocketclient.render.toggle('publish');
websocketclient.render.toggle('messages');
websocketclient.render.toggle('sub');
},
'toggle': function (name) {
$('.' + name + 'Arrow').toggleClass("closed");
$('.' + name + 'Top').toggleClass("closed");
var elem = $('#' + name + 'Main');
elem.slideToggle();
},
'hide': function (name) {
$('.' + name + 'Arrow').addClass("closed");
$('.' + name + 'Top').addClass("closed");
var elem = $('#' + name + 'Main');
elem.slideUp();
},
'show': function (name) {
$('.' + name + 'Arrow').removeClass("closed");
$('.' + name + 'Top').removeClass("closed");
var elem = $('#' + name + 'Main');
elem.slideDown();
},
'removeSubscriptionsMessages': function (id) {
websocketclient.messages = _.filter(websocketclient.messages, function (item) {
return item.subscriptionId != id;
});
websocketclient.render.messages();
},
'clearMessages': function () {
$("#messEdit").empty();
},
'clearSubscriptions': function () {
$("#innerEdit").empty();
}
}
};
I think I am a bit late...but I leave here for posterity.
The Paho JS library has undergo a series of changes before release 1.0.3 and the last one 1.1.0.
If you refer to a mqttws31.js probably you was using a version earlier than 1.0.3, because from 1.0.3 the main js file was renamed to paho-mqtt.js.
Can be the reason why something in your code was working differently from HiveMQ version.
I tried to sum the situation here
No idea why I'm getting this error here, I've used this exact type of function in other apps before. The only difference here is that I'm including this inside of an Angular Controller, could that possibly have anything to do with this error?
// Controller for Add Customer
app.controller('AddCustomerController', function($scope) {
$scope.deactivate_btn = false;
// Check all users:
this.checkAll = function() {
var checkboxes = document.getElementsByName('checkboxCustomer');
var checkAll = document.getElementsByName('checkboxAll');
for (var i = 0, n = checkboxes.length; i < n; i++) {
checkboxes[i].checked = checkAll[0].checked;
}
};
function buildAddedSiteRow(id, name, address, loc1, loc2, city, state, zip) {
id = id || " ";
name = name || " ";
address = address || " ";
loc1 = loc1 || " ";
loc2 = loc2 || " ";
city = city || " ";
state = state || " ";
zip = zip || " ";
var number = 1 + Math.floor(Math.random() * 6);
return "<tr class='added_sites_tbody'><td><div class='check-label'><input ng-click='deactivate_btn = !deactivate_btn' ng-class='{ active: deactivate_btn }' type='checkbox' name='checkAddSite' id='"+id"' class='css-checkbox' /><label for='"+id"' class='css-label radGroup1 clr'>"+id"</label></div></td><td>"+name"</td><td>"+address"</td><td><div class='add_sites_location'><p>"+loc1"</p> <p>"+loc2"</p></div></td><td>"+city"</td><td>"+state"</td><td>"+zip"</td><td></td></tr>";
};
});
return "<tr class='added_sites_tbody'><td><div class='check-label'><input ng-click='deactivate_btn = !deactivate_btn' ng-class='{ active: deactivate_btn }' type='checkbox' name='checkAddSite' id='"+id"' class='css-checkbox' /><label for='"+id"' class='css-label radGroup1 clr'>"+id"</label></div></td><td>"+name"</td><td>"+address"</td><td><div class='add_sites_location'><p>"+loc1"</p> <p>"+loc2"</p></div></td><td>"+city"</td><td>"+state"</td><td>"+zip"</td><td></td></tr>";
// The errors are here ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------^ and ------------------------------------^ and ---------------------------------^ and ------------------------^ and -------------^ and so on
You need + in each of those locations.
I have a landing page I'm working on, where I want the user to select a state, and then when the state is selected, the select dropdown below it will show the locations within that state. The list of locations comes from a json file where there is a list of store locations, with their attributes such as store name, state, etc. I've created an object, but I'm not sure how to populate the select based on the state. Also, the way I'm building the list of states may not be the best way either, so any help there would be great also. Thanks!
$(document).ready(function(){
var buildLocations = {
'settings': {
directoryListingItems : {},
directoryListingArray : [],
globalLatLong : null,
globalLatitude : geoip_latitude(),
globalLongitude : geoip_longitude(),
globalCity : geoip_city(),
globalState : geoip_region_name(),
locationRadius : 30,
NearbyLocationsCount : 0,
locationTotalPlaceholder: $('#location-number'),
locationNamePlaceholder : $('#location-name'),
stateDropdownArray : [],
stateDropdown : $('#state'),
locationDropdownArray : [],
locationDropdown : $('#location'),
},
init: function() {
bLs = this.settings;
buildLocations.getJSONLocations();
},
getJSONLocations: function() {
$.ajax({
url: "data/data.json",
dataType: "JSON",
success: buildLocations.getLocations
});
},
getLocations: function(results) {
// creating objects
for(var i = 0; i < results.locations.length; i++) {
bLs.directoryListingItems = {
store_id: results.locations[i].storeid,
title: results.locations[i].title,
latitude: results.locations[i].latitude,
longitude: results.locations[i].longitude,
state: results.locations[i].state,
distance: buildLocations.getLocationDistance(bLs.globalLatitude, bLs.globalLongitude, results.locations[i].latitude, results.locations[i].longitude)
};
bLs.directoryListingArray.push(bLs.directoryListingItems);
//Check if a state is already in the states array, if not, add it
if ($.inArray('<option value=\"' + bLs.directoryListingArray[i].state + '\">'+ bLs.directoryListingArray[i].state + '</option>', bLs.stateDropdownArray)==-1) {
bLs.stateDropdownArray.push('<option value=\"' + bLs.directoryListingArray[i].state + '\">'+ bLs.directoryListingArray[i].state + '</option>');
//alert("added"+ value.state);
}
//get selected state value
//if in state in bLs.directoryListingItems array matches this value, add item to array
//Add Each location to the locations dropdown
bLs.locationDropdownArray.push('<option value=\"' + bLs.directoryListingArray[i].storeid + '\">'+ bLs.directoryListingArray[i].title + '</option>');
//Count the number of locations that are within the set location radius of the users detected location
if (bLs.directoryListingArray[i].distance < bLs.locationRadius) {
bLs.NearbyLocationsCount++;
}
}
//Sort the states array in alphabetical order
bLs.stateDropdownArray.sort();
//run function to populate dropdowns
buildLocations.populateDOM();
},
compareDistances: function(a,b) {
if (a.distance < b.distance)
return -1;
if (a.distance > b.distance)
return 1;
return 0;
},
populateDOM: function() {
//populate the number inside the map marker
bLs.locationTotalPlaceholder.text(bLs.NearbyLocationsCount);
//populate the area next to the map marker with the users location and state
bLs.locationNamePlaceholder.text(bLs.globalCity + ", " + bLs.globalState);
//build state select dropdown
bLs.stateDropdown.html(bLs.stateDropdownArray);
buildLocations.populateDOMlocations();
},
populateDOMlocations: function() {
//$.each(bLs.directoryListingItems, function(index, value) {
//if (value.state="Florida") {
//alert(index)
///}
//});
//$.each(bLs.directoryListingItems, function(index, obj) {
//$.each(obj, function(attr, value) {
// console.log( attr + ' == ' + value );
//});
//});
//build locations select dropdown
bLs.locationDropdown.html(bLs.locationDropdownArray);
},
getLocationDistance : function(lat1,lon1,lat2,lon2) {
function deg2rad(deg) {
return deg * (Math.PI/180)
};
var R = 6371; // Radius of the earth in km
var dLat = deg2rad(lat2-lat1); // deg2rad below
var dLon = deg2rad(lon2-lon1);
var a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2)
;
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = (R * c) * 0.6214; // Distance in miles
return Math.round( d * 10 ) / 10
},
};
// ====================================================== //
// Populate Locations
buildLocations.init();
});
I figured it out,
populateDOMlocations: function() {
bLs.currState = bLs.stateDropdown.val();
bLs.locationDropdownArray = [];
for(var l = 0; l < bLs.directoryListingArray.length; l++) {
if (bLs.directoryListingArray[l].state == bLs.currState ) {
bLs.locationDropdownArray.push('<option value=\"' + bLs.directoryListingArray[l].storeid + '\">'+ bLs.directoryListingArray[l].title + '</option>');
}
}
bLs.locationDropdownArray.sort();
//build locations select dropdown
bLs.locationDropdown.html(bLs.locationDropdownArray);
},