How to customize autocomplete function of the CodeMirror - javascript

I want to customize an autocomplete function to Codemirror.
So I have build this code:
CodeMirror.commands.autocomplete = function (cm) {
var arrayTabNONDefault = new Array();
var stringaCampi = null;
var arrayTabellaCampo = null;
var textVal = cm.getValue();
textVal = textVal.toUpperCase();
var res = textVal.match("SELECT(.*)FROM");
if (res != null) {
stringaCampi = res[1];
arrayTabellaCampo = stringaCampi.split(",");
var nomeTab = null;
for (var i = 0; i < arrayTabellaCampo.length; i++) {
nomeTab = (arrayTabellaCampo[i].split(".")[0]).trim();
if (hintTables[nomeTab] == null)
hintTables[nomeTab] = new Array();
} //FINE FOR
} //FINE IF
CodeMirror.showHint(cm, CodeMirror.hint.sql, {
tables: hintTables
});
cm.on("beforeChange", function (cm, change) {
var before = cm.getRange({ line: 0, ch: 0 }, change.from);
var text = cm.getRange(change.from, change.to);
var after = cm.getRange(change.to, { line: cm.lineCount() + 1, ch: 0 });
if (before.indexOf("FROM") !== -1)
// alert("Ho scritto FROM");
console.log("before change", before, text, after);
});
cm.on("change", function (cm, change) {
var from = change.from;
var text = change.text.join("\n");
var removed = change.removed.join("\n");
var to = cm.posFromIndex(cm.indexFromPos(from) + text.length);
var before = cm.getRange({ line: 0, ch: 0 }, from);
var after = cm.getRange(to, { line: cm.lineCount() + 1, ch: 0 });
if (before.indexOf("FROM") !== -1)
console.log("after change", before, removed, text, after);
});
} //FINE ESTENSIONE
This is the content of hintTables
var hintTables = { "#T_TF_FilesList": ["FilesListHeaderID", "NumRecord", "FileTypeID", "FileID", "FilesListHeaderID", "NumRecord"],
"#T_TF_SelectedItems": ["EventHeaderID", "ItemType", "ItemID1", "ItemID2", "EventHeaderID", "ItemType", "ItemID1", "ItemID2"],
"#T_TFT_CacheSearchCriteriaHeaders": ["ID", "SyncDate", "FileTypeID", "CriteriaExpressionString", "CriteriaExpressionHash", "PageRecordsNumber", "PageNumber", "NumFiles"]
};
So I want that the system should propose a list of this table after I write FROM, or the system should to propose a list of stored procedures after I write EXECUTE.
It is possible to do this?

Are you trying to customize the SQL hint addon? If so, you should make changes inside sql-hint.js (under codemirror/addon/hint).
Basically what you should do is:
1.In your app.js (whatever js file for your main logic) call editor.showHint({hint: CodeMirror.hint.sql) on "change" event;
2.Inside sql-hint.js, return {list: hintTables, from: somePos, to: somePos} when the user types FROM or EXECUTE which can be detected by regular expression or inspecting the tokens at the line. I made up some code for your reference:
var cursor = editor.getCursor();
var tokenAtCursor = editor.getTokenAt(cursor);
if (tokenAtCursor.type == "FROM-and-EXECUTE")
return {list: hintTables,
from: CodeMirror.Pos(cur.line, tokenAtCursor.start),
to: CodeMirror.Pos(cur.line, tokenAtCursor.end)};
If I misunderstand your question and this answer is not helpful, please tell me and I will delete it.

Related

Google App Script - Add or Update Calendar Event

Updating previous question with detailed example. I have a google sheet with three used columns (A: Event Title, B: Event Description, and D: Event Date). I want to create a new all day event on Google Calendar if none exists, and update the existing one if it already exists.
Here is the code I tried: I am getting the error: TypeError: Cannot read property 'setDescription' of undefined
function updatecal(){
var cal = CalendarApp.getCalendarById('c_lmsj3r1ogsaafhc68gfalstdco#group.calendar.google.com');
var data = SpreadsheetApp.getActive().getSheetByName("Data For Calendar");
const rows = data.getDataRange().getValues();
rows.forEach(function(row, index){
if (index === 0) return;
var eventdate = data.getRange(index, 4, 1, 1).getValue();
var eventtitle = data.getRange(index,1,1,1).getValue();
var eventdescription = data.getRange(index,2,1,1).getValue();
console.log(eventdate + eventtitle + eventdescription)
const eventdate1 = new Date(eventdate)
const events = cal.getEventsForDay(eventdate1);
if (events.lenght == 0){
var newevent = cal.createAllDayEvent(eventtitle,eventdate1,
{description: eventdescription});
} else {
ev = events[0];
ev.setDescription(eventdescription)
}
})
}
There is a typo in line 13 inside the if statement. You wrote lenght instead of length If you fix that the code runs just fine and the calendar events are created without any problem.
function updatecal(){
var cal = CalendarApp.getCalendarById('c_lmsj3r1ogsaafhc68gfalstdco#group.calendar.google.com');
var data = SpreadsheetApp.getActive().getSheetByName("Data For Calendar");
const rows = data.getDataRange().getValues();
rows.forEach(function(row, index){
if (index === 0) return;
var eventdate = data.getRange(index, 4, 1, 1).getValue();
var eventtitle = data.getRange(index,1,1,1).getValue();
var eventdescription = data.getRange(index,2,1,1).getValue();
console.log(eventdate + eventtitle + eventdescription)
const eventdate1 = new Date(eventdate)
const events = cal.getEventsForDay(eventdate1);
if (events.length == 0){ //The error was in this line
var newevent = cal.createAllDayEvent(eventtitle,eventdate1,
{description: eventdescription});
} else {
ev = events[0];
ev.setDescription(eventdescription)
}
})
}
References:
length()

refresh drop down list after button click in web app

I have a web app with one drop down list and 2 buttons. The drop down list get values from a sheet. The buttons write back in the sheet. The script I have works fine with that:
<script>
$(function() {
$('#txt1').val('');
google.script.run
.withSuccessHandler(updateSelect)
.getSelectOptions();
});
function updateSelect(opt)
{
var select = document.getElementById("sel1");
select.options.length = 0;
for(var i=0;i<opt.length;i++)
{
select.options[i] = new Option(opt[i],opt[i]);
}
}
function listS() {
const selectElem = document.getElementById('sel1')
const index = selectElem.selectedIndex;
if (index > -1) {
const e = document.getElementById("sel1");
const value = e.options[index].value;
const body = { index: index, value: value };
google.script.run.withSuccessHandler(yourCallBack).yourServerSideFunc(body);
}
}
document.getElementById("but1").addEventListener("click",listS);
function yourCallBack(response) {
}
</script>
In Java script:
function getSelectOptions()
{
var ss=SpreadsheetApp.openById('1onuWoUKh1XmvEAmKktwJekD782BFIru-MDA0omqzHjw');
var sh=ss.getSheetByName('Database');
var rg=sh.getRange(2,1,sh.getLastRow()-1,8);
var vA=rg.getValues();
var useremail = Session.getActiveUser().getEmail();
var opt=[];
for(var i=0;i<vA.length;i++)
{
if(vA[i][1] == "Pending Approval"){
if(vA[i][7]+"#xxx.com" == useremail || vA[i][7]+"#xxx.com" == useremail) {
opt.push(vA[i][3]+" REQ ID: "+vA[i][0]);
}
}
};
if (opt.length == 0) {opt.push("You do not have pending requests")};
return opt;
}
function doGet() {
var output = HtmlService.createHtmlOutputFromFile('list');
return output;
}
function yourServerSideFunc(body) {
var value = body["value"];
var ss = SpreadsheetApp.openById('1onuWoUKh1XmvEAmKktwJekD782BFIru-MDA0omqzHjw');
var sh = ss.getSheetByName('Database');
var rg=sh.getRange(1,1,sh.getLastRow()-1,4);
var vA=rg.getValues();
var str = "Approved";
for(var i=0;i<vA.length;i++)
{
if(vA[i][3]+" REQ ID: "+vA[i][0] == value) {
sh.getRange(i+1, 2).setValue(str);
}
};
return ContentService.createTextOutput(JSON.stringify({message: "ok"})).setMimeType(ContentService.MimeType.JSON);
Now I am trying to regenerate the drop down list values after the button is clicked. I tried to add
var output = HtmlService.createHtmlOutputFromFile('list');
return output;
in yourServerSideFunc(body) function to regenerate the HTML but does not work. I have tried to force a HTML refresh, but also did not work.
How can I easily re-trigger the generation of the drop down list items? Worst case scenario it is ok to refresh the whole page, but it should be simple to regenerate the drop down list since I have already the code for it.
I ended up with this work around.
function listS() {
const selectElem = document.getElementById('sel1')
const index = selectElem.selectedIndex;
if (index > -1) {
const e = document.getElementById("sel1");
const value = e.options[index].value;
const body = { index: index, value: value };
google.script.run.withSuccessHandler(yourCallBack).yourServerSideFunc(body);
//ADDED:
var select = document.getElementById("sel1");
select.options[index] = new Option("Approved! Please refresh","Approved! Please refresh");
selectElem.selectedIndex = index;
}
}
It does not really meet the original goal to refresh the list from the sheet. It would be great if someone else posted a solution to call the server function. I tried to add google.script.run.doGet() and similar, but it seems that it does not call the server side functions properly.

Why searchbox become lagging when typing word to search data in CSV?

I developed the store locator using open street map and leaflet. The problem is when I want to type in searchbox it will become lagging to finish the word. That store locator read from the CSV file that has 300++ data. Below is the code for the searchbox:
var locationLat = [];
var locationLng = [];
var locMarker;
var infoDiv = document.getElementById('storeinfo');
var infoDivInner = document.getElementById('infoDivInner');
var toggleSearch = document.getElementById('searchIcon');
var hasCircle = 0;
var circle = [];
//close store infor when x is clicked
var userLocation;
$("#infoClose").click(function() {
$("#storeinfo").hide();
if (map.hasLayer(circle)) {
map.removeLayer(circle);
}
});
var listings = document.getElementById('listingDiv');
var stores = L.geoJson().addTo(map);
var storesData = omnivore.csv('assets/data/table_1.csv');
function setActive(el) {
var siblings = listings.getElementsByTagName('div');
for (var i = 0; i < siblings.length; i++) {
siblings[i].className = siblings[i].className
.replace(/active/, '').replace(/\s\s*$/, '');
}
el.className += ' active';
}
function sortGeojson(a,b,prop) {
return (a.properties.name.toUpperCase() < b.properties.name.toUpperCase()) ? -1 : ((a.properties.name.toUpperCase() > b.properties.name.toUpperCase()) ? 1 : 0);
}
storesData.on('ready', function() {
var storesSorted = storesData.toGeoJSON();
//console.log(storesSorted);
var sorted = (storesSorted.features).sort(sortGeojson)
//console.log(sorted);
storesSorted.features = sorted;
//console.log(storesSorted)
stores.addData(storesSorted);
map.fitBounds(stores.getBounds());
toggleSearch.onclick = function() {
//var s = document.getElementById('searchbox');
//if (s.style.display != 'none') {
//s.style.display = 'yes';
//toggleSearch.innerHTML = '<i class="fa fa-search"></i>';
//$("#search-input").val("");
//search.collapse();
//document.getElementById('storeinfo').style.display = 'none';
//$('.item').show();
//} else {
//toggleSearch.innerHTML = '<i class="fa fa-times"></i>';
//s.style.display = 'block';
//attempt to autofocus search input field when opened
//$('#search-input').focus();
//}
};
stores.eachLayer(function(layer) {
//New jquery search
$('#searchbox').on('change paste keyup', function() {
var txt = $('#search-input').val();
$('.item').each(function() {
if ($(this).text().toUpperCase().indexOf(txt.toUpperCase()) != -1) {
$(this).show();
} else {
$(this).hide();
}
});
});
I dont know what is the cause of the lag in the search box. It is something wrong in code or the csv file? Thank you
Every iteration of $('.item').each is causing a layout change because $(this).hide() or $(this).show() causes the item to removed/added to the DOM as the style is set to display:none back and forth. DOM manipulations and the corresponding layout changes are expensive.
You can consider accumulating the changes and doing one batch update to the DOM using a function like appendChild

NodeJS some modules not working

I'm making a game with socket.io and nodejs, and I'm making a module called rooms.js, this module require users.js module and fiveSocket.js module
but when I call Rooms.New from the main server file, it says that fiveSocket is undefined, same problem when Rooms.New calls a users.js function, I got TypeError: Cannot read property 'getSocketIDbyId' of undefined
rooms.js:
var mysql = require('../mysql/mysql.js');
var headers = require('./headers.js');
var users = require('./users.js');
var fiveSocket = require('./sockets.js');
var Rooms = {
Obj: {},
Room: function(data) {
var room = this;
this.name = data.name;
this.users = [];
this.floorCode = data.floor;
this.description = data.desc;
this.maxUsers = data.maxUsers;
this.owner = data.owner;
this.setTime = new Date().getTime();
this.dbID = data.dbID;
this.doorx = data.doorx;
this.doory = data.doory;
this.doordir = data.doordir;
},
New: function(socketID, roomID) {
var keys = Object.keys(Rooms.Obj).length;
var id = keys + 1;
var callback = function(row) {
fiveSocket.emitClient(socketID, headers.roomData, {
title: row.title,
desc: row.description,
mapStr: row.floorCode,
doorx: row.doorx,
doory: row.doory,
doordir: row.doordir
});
var uid = users.getIdBySocketID(socketID);
users.Obj[uid].curRoom = roomID;
var rid = Rooms.getIdByDbID(roomID);
Rooms.Obj[rid].users.push(uid);
}
if(Rooms.getIdByDbID(roomID) != false) {
var room = Rooms.getIdByDbID(roomID);
var row = { title: room.name, description: room.description, floorCode: room.foorCode, doorx: room.doorx, doory: room.doory, doordir: room.doordir };
callback(row);
} else {
mysql.Query('SELECT * FROM rooms WHERE id = ? LIMIT 1', roomID, function(rows) {
if(rows.length > 0) {
var row = rows[0];
Rooms.Obj[id] = new Rooms.Room({name: row.title, floorCode: row.floorCode, desc: row.description, maxUsers: row.maxUsers, owner: row.owner, dbID: row.id, doorx: row.doorx, doory: row.doory, doordir: row.doordir});
callback(row);
}
});
}
},
removeUser: function(DBroomID, userID) {
var rid = Rooms.getIdByDbID(DBroomID);
var room = Rooms.Obj[rid];
var index = room.indexOf(userID);
if (index > -1) array.splice(index, 1);
},
Listener: function(users) {
setInterval(function(){
for(var roomID in Rooms.Obj) {
var room = Rooms.Obj[roomID];
// send users coordinates
room.users.forEach(function(uid) {
var socketID = users.getSocketIDbyId(uid);
var data = Rooms.getUsersInRoomData(roomID);
fiveSocket.emitClient(socketID, headers.roomUsers, data);
});
// unload inactive rooms (no users after 10 seconds)
var activeUsers = room.users.length;
var timestamp = room.setTime;
var t = new Date(); t.setSeconds(t.getSeconds() + 10);
var time2 = t.getTime();
if(activeUsers <= 0 && timestamp < time2) {
Rooms.Remove(roomID);
}
}
}, 1);
},
getUsersInRoomData: function(roomID) {
var room = Rooms.Obj[roomID];
var obj = {};
room.users.forEach(function(uid) {
var user = users.Obj[uid];
obj[uid] = {
username: user.username,
position: user.position,
figure: user.figure
};
});
return obj;
},
Remove: function(id) {
delete Rooms.Obj[id];
},
getIdByDbID: function(dbID) {
var result = null;
for(var room in Rooms.Obj) {
var u = Rooms.Obj[room];
if(u.dbID == dbID) var result = room;
}
if(result == null) return false;
else return result;
},
getDbIDbyId: function(id) {
return Rooms.Obj[id].dbID;
}
}
Rooms.Listener();
module.exports = Rooms;
EDIT: (if it can be helpful)
When I console.log fiveSocket on the main file
When I console.log fiveSocket on the rooms.js file
EDIT2: When I've removed var users = require('./users.js'); from fiveSocket, when I console.log it in rooms.js it works, why ?
EDIT3: I still have the problem
If you need the others modules sources:
Users.JS: http://pastebin.com/Ynq9Qvi7
sockets.JS http://pastebin.com/wpmbKeAA
"Rooms" requires "Users" and vice versa, so you are trying to perform "circular dependency".
Quick search for node.js require circular dependencies gives a lot of stuff, for example :
"Circular Dependencies in modules can be tricky, and hard to debug in
node.js. If module A requires('B') before it has finished setting up
it's exports, and then module B requires('A'), it will get back an
empty object instead what A may have intended to export. It makes
logical sense that if the export of A wasn't setup, requiring it in B
results in an empty export object. All the same, it can be a pain to
debug, and not inherently obvious to developers used to having those
circular dependencies handled automatically. Fortunately, there are
rather simple approaches to resolving the issue."
or
How to deal with cyclic dependencies in Node.js

Split values by comma separated string in javascript

Here is my issue:
I have RadListBox and I'm trying to get the values and append them so the result would be displayed like that: '1,2,3,4' but I'm getting back : 1,2,3,4,
Does anyone know how can I achieve that?
Problem starts here:
var sbLocationsIDS = new StringBuilder();
for (i = 0; i < LocationIDS.get_items().get_count(); i++) {
sbLocationsIDS.append(LocationIDS.getItem(i).get_value()+ ",");
}
The result: sbLocationsIDS =1,2,3,4, instead of '1,2,3,4'
The Rest of the Code:
function openNewTab(url) {
var captureURL = url;
var win = window.open(captureURL, '_blank');
win.focus();
}
function GetComparisonsReport(sender, args) {
var isValid = Page_ClientValidate('validateComparisons');
if (isValid) { // If its true is going to fire the rest of the code
var SessionID = getUrlVars()["SessionID"];
var companyCodeVal = document.getElementById("<%=hfC.ClientID%>").value;
var LocationIDS = $find("<%=rlbSelectedLocation.ClientID %>");
var CategoriesIDS = $find("<%=rlbSelectedCategory.ClientID %>");
var fileType = $find("<%=rcbFileType.ClientID %>");
var fromFirstPeriod = $find("<%=rdpFromFirstPeriod.ClientID %>");
var toFirstPeriod = $find("<%=rdpToFirstPeriod.ClientID %>");
var fromSecondPeriod = $find("<%=rdpFromSecondPeriod.ClientID %>");
var toSecondPeriod = $find("<%=rdpToSecondPeriod.ClientID %>");;
if (LocationIDS.get_items().get_count() < 0) {
radalert("Please choose locations and select the Add button.<h3 style='color: #ff0000;'></h3>", 420, 170, "Case Global Alert");
return;
}
if (CategoriesIDS.get_items().get_count() < 0) {
radalert("Please choose categories and select the Add button.<h3 style='color: #ff0000;'></h3>", 420, 170, "Case Global Alert");
return;
}
var fromFirstPeriodDateValSelected = fromFirstPeriod.get_dateInput().get_selectedDate().format("yyyy/MM/dd");
var toFirstPeriodDateValSelected = toFirstPeriod.get_dateInput().get_selectedDate().format("yyyy/MM/dd");
var fromSecondPeriodDateValSelected = fromSecondPeriod.get_dateInput().get_selectedDate().format("yyyy/MM/dd");
var toSecondPeriodDateValSelected = toSecondPeriod.get_dateInput().get_selectedDate().format("yyyy/MM/dd");
var fileTypeValSelected = fileType.get_selectedItem().get_value();
var sbLocationsIDS = new StringBuilder();
for (i = 0; i < LocationIDS.get_items().get_count(); i++) {
sbLocationsIDS.append(LocationIDS.getItem(i).get_value()+ ","); // The problem is here!!!
}
var sbCategoriesIDS = new StringBuilder();
for (i = 0; i < CategoriesIDS.get_items().get_count(); i++) {
sbCategoriesIDS.append(CategoriesIDS.getItem(i).get_value() + ",");
}
var ComparisonsURL = (String.format("https://www.test.com/cgis/{0}/reports/ConnectTorptIncidentsCountByLocationInterval.asp?SessionID={1}&locString={2}&catString={3}&FromDate1={4}&&ToDate1={5}&FromDate2={6}&ToDate2={7}&ExportType={8}", companyCodeVal, SessionID, sbLocationsIDS, sbCategoriesIDS, fromFirstPeriodDateValSelected, toFirstPeriodDateValSelected, fromSecondPeriodDateValSelected, toSecondPeriodDateValSelected, fileTypeValSelected));
openNewTab(ComparisonsURL);
}
}
String.format = function () {
// The string containing the format items (e.g. "{0}")
// will and always has to be the first argument.
var theString = arguments[0];
// start with the second argument (i = 1)
for (var i = 1; i < arguments.length; i++) {
// "gm" = RegEx options for Global search (more than one instance)
// and for Multiline search
var regEx = new RegExp("\\{" + (i - 1) + "\\}", "gm");
theString = theString.replace(regEx, arguments[i]);
}
return theString;
}
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
vars[key] = value;
});
return vars;
}
// Initializes a new instance of the StringBuilder class
// and appends the given value if supplied
function StringBuilder(value) {
this.strings = new Array("");
this.append(value);
}
// Appends the given value to the end of this instance.
StringBuilder.prototype.append = function (value) {
if (value) {
this.strings.push(value);
}
}
// Clears the string buffer
StringBuilder.prototype.clear = function () {
this.strings.length = 1;
}
// Converts this instance to a String.
StringBuilder.prototype.toString = function () {
return this.strings.join("");
}
The problem is your loop is appending , always even for the last item in the loop.
You want to append only for all items other than the last. There are multiple ways to do that, simplest being: check if the current element is the last and if so, do not append ,
var sbLocationsIDS = new StringBuilder();
for (i = 0; i < LocationIDS.get_items().get_count(); i++) {
sbLocationsIDS.append(LocationIDS.getItem(i).get_value()); //append only value
if(i != (LocationIDS.get_items().get_count() -1)) { //if not last item in list
sbLocationsIDS.append(","); //append ,
}
}
There are other ways to do it, and depending on what you want to do with the values in the future, these may be pretty useful. (I see that the append in your code is actually a call to join, so this is actually a simpler version)
Add the values of the list to a array and use Array.join:
var select = document.getElementById("locationId");
var options = select.options;
var optionsArray = [];
if(options) {
for (var i=0; i<=options.length; i++) {
//text is the text displayed in the dropdown.
//You can also use value which is from the value attribute of >option>
optionsArray.push(options[i].text);
}
}
var sbLocationsIDS = optionsArray.join(",");
With JQuery, the above code becomes a bit more simple:
var optionsArray = [];
$("#locationId option").each(function(){
optionsArray.push(options[i].text);
});
var sbLocationsIDS = optionsArray.join(",");
Actually, if you decide yo use JQuery, you can use jquery.map:
(idea from Assigning select list values to array)
$(document).ready(function() {
$("#b").click(function() {
var sbLocationsIDS = jQuery.map($("#locationId option"), function(n, i) {
return (n.value);
}).join(",");
alert(sbLocationsIDS);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="locationId">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button id="b">Click</button>

Categories