How to sort all the data by date in google apps script? - date

I have retrieved the data from REST API and inserted into google apps script but i am not sure how to sort the data based on the subscription date. I have used the sort() but it is only sorting one column instead of everything. This is my current code and screenshot so far:
function myFunction() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var mainSheet = ss.getSheetByName("test")
var apiKey = 'test';
var URL_STRING = "";
var url = URL_STRING + "?ApiKey=" + apiKey;
var response = UrlFetchApp.fetch(url);
var json = response.getContentText();
var data = JSON.parse(json);
var firstname = [];
var lastname = [];
var subscriptionDate = [];
for (var i=0;i<data.output.o1.length;i++){
fn=(data.output.o1[i].first_name);
firstname.push([fn]);
ln=(data.output.o1[i].last_name);
lastname.push([ln]);
sd=(data.output.o1[i].subscription_date);
subscriptionDate.push([sd]);
};
mainSheet.getRange(2, 1, firstname.length).setValues(firstname);
mainSheet.getRange(2, 2, lastname.length).setValues(lastname);
mainSheet.getRange(2, 3, subscriptionDate.length).setValues(subscriptionDate);
}

In this case, how about sorting the values when the array for putting to Spreadsheet is created? When this is reflected to your script, it becomes as follows.
From:
var firstname = [];
var lastname = [];
var subscriptionDate = [];
for (var i=0;i<data.output.o1.length;i++){
fn=(data.output.o1[i].first_name);
firstname.push([fn]);
ln=(data.output.o1[i].last_name);
lastname.push([ln]);
sd=(data.output.o1[i].subscription_date);
subscriptionDate.push([sd]);
};
mainSheet.getRange(2, 1, firstname.length).setValues(firstname);
mainSheet.getRange(2, 2, lastname.length).setValues(lastname);
mainSheet.getRange(2, 3, subscriptionDate.length).setValues(subscriptionDate);
To:
var values = data.output.o1.map(({first_name, last_name, subscription_date}) => [first_name, last_name, subscription_date]);
values.sort((a, b) => new Date(a[2]).getTime() > new Date(b[2]).getTime() ? 1 : -1);
mainSheet.getRange(2, 1, values.length, values[0].length).setValues(values);
When values.sort((a, b) => new Date(a[2]).getTime() > new Date(b[2]).getTime() ? 1 : -1); is modified to values.sort((a, b) => new Date(a[2]).getTime() > new Date(b[2]).getTime() ? -1 : 1);, the order of sort direction is changed.
Note:
As other method, when the following script to the bottom of your current script, the sort is run with the column "C".
mainSheet.getRange("A2:C").sort([{ column: 3, ascending: true }]);
In this answer, from your sample image, I supposed that your column "C" is the date object.
References:
map()
sort()
sort(sortSpecObj)

mainSheet.getRange(2,1,mainSheet.getLastRow()-1,3).sort({column:3,ascending:true});

Related

SqlKata Values for AsUpdate as column names

I have the following query generated by SqlKata:
UPDATE "temp"."dbe01_measures" SET "category2name" = 'category4name'.
The expected query is:
UPDATE "temp"."dbe01_measures" SET "category2name" = "category4name"
I want to use category4name as column name, not as value.
The code for this is:
var query = new Query(dimensionDataSource.Object)
var valuesToUpdateForQ1 = new Dictionary<string, object>
{
{toOptionDataSourceMetadata.NameColumn, fromDimension.DimensionDisplayName}
};
query.AsUpdate(new ReadOnlyDictionary<string, object>(valuesToUpdateForQ1));
var sqlQueryString1 = new QueryFactory { Compiler = new PostgresCompiler() }.Compiler.Compile(query1).ToString();
You have to use the UnsafeLiteral to instruct the compiler to consume the value without any processing.
var q = new Query("Table").AsUpdate(new Dictionary<string, object> {
{"Id", 1},
{"Value", Expressions.UnsafeLiteral("\"Col\"")}
});
This will produce the following:
UPDATE "Table" SET "Id" = 1, "Value" = "Col"

Axios: How to get data within axios

I created a search for a unique barcode. Therefore the result will be 0 or 1 because it is unique. If barcode is found, I need to get the ID of that record. How do we do this?
axios.get("api/findpatronbarcode?q=" + query)
.then(({data}) => {
this.loanpatrons = data.data;
//COUNT RECORDS
this.countPatrons = this.loanpatrons.length;
console.log(this.countPatrons);
//THE PROBLEM IS THE CODE BELOW. IT RETURNS "Undefined"
// Get the ID of the record
var getID = this.loanpatrons.id;
console.log(getID)
});
You can try like this:
axios.get("api/findpatronbarcode?q=" + query)
.then(({data}) => {
this.loanpatrons = data.data;
//COUNT RECORDS
this.countPatrons = this.loanpatrons.length;
console.log(this.countPatrons);
// KEEP IN MIND THAT "loanpatrons" is Array
// so first get the first member of the Array
// and only then Get the ID of the record
var getID = (this.loanpatrons[0] || {}).id || '';
console.log(getID)
});

MongoDB Inserting audio

I have inserted one million documents containing text into mongodb database through javascript and php. I would like to know how to insert one million documents related to audio/image into the database.
The script I used for inserting text :
var minDate = new Date(2012, 0, 1, 0, 0, 0, 0);
var maxDate = new Date(2013, 0, 1, 0, 0, 0, 0);
var delta = maxDate.getTime() - minDate.getTime();
var job_id = arg2;
var documentNumber = arg1;
var batchNumber = 5 * 1000;
var job_name = 'Job#' + job_id
var start = new Date();
var batchDocuments = new Array();
var index = 0;
while(index < documentNumber) {
var date = new Date(minDate.getTime() + Math.random() * delta);
var value = Math.random();
var document = {
created_on : date,
value : value
};
batchDocuments[index % batchNumber] = document;
if((index + 1) % batchNumber == 0) {
db.randomData.insert(batchDocuments);
}
index++;
if(index % 100000 == 0) {
print(job_name + ' inserted ' + index + ' documents.');
}
}
print(job_name + ' inserted ' + documentNumber + ' in ' + (new Date() - start)/1000.0 + 's');
Can a similar script be used to insert Audio/Image as well?
Thanks.
Yes, but you'll need a powerful interpreter to accomplish this. It is possible to insert binary data into MongoDB using BinData, which needs a base64 string and cat() doesn't convert binary to string besides it fails reading binary data.
A quick workaround could be get the base64 string, save to a file, then read with cat() in your script. Example in node.js:
var fs = require('fs');
var b64Str = fs.readFileSync('file.mp3','base64');
fs.writeFileSync('base64ContentFile',b64Str);
Do it for every file you want to put in the database, then run your script changing the following:
var document = {
created_on : date,
value : new BinData(0,cat('base64ContentFile'))
};
A better solution would be use another language, a mongodb driver and do everything there. Read one file, parse it to a base64 string then insert into db, loop.
https://docs.mongodb.org/manual/reference/mongodb-extended-json/#binary

How to fliter the filtered items in sap.m.list

I alredy have an sap.m.list which is already filtered based on one property.Now I again need to apply filter for that list to implement live search.
filterList:function(evt){
debugger;
var filters = [];
var oFilter="";
var query = evt.oSource.mProperties.value;
if (query && query.length > 0) {
var filter = new sap.ui.model.Filter("CLTYPE", sap.ui.model.FilterOperator.Contains, query);
filters.push(filter);
var filter1 = new sap.ui.model.Filter("CLCAT", sap.ui.model.FilterOperator.Contains, query);
filters.push(filter1);
var filter2 = new sap.ui.model.Filter("CLNUM", sap.ui.model.FilterOperator.Contains, query);
filters.push(filter2);
oFilter = new sap.ui.model.Filter( filters, false );
}
// update list binding
var list = sap.ui.getCore().byId("List");
var binding = list.getBinding("items");
binding.filter(oFilter);
},
here my list is already filtered.here list.getBinding('items') will give me all the items not the filtered Items.I applied filter for my sap.m.list as follows
obj[filterParam] = context;
var contextClauses=_.where(clauses,obj);
sap.ui.getCore().getModel('ClauseModel').setProperty("/DATA/CURRENTCLAUSES",contextClauses);
// update list binding
var list = sap.ui.getCore().byId("List");
var binding = list.getBinding("items");
binding.filter(oFilter);
how to implement that??any suggestions?
Add livechange to your textfield and call a function to filter your list.
new sap.ui.commons.TextField({type:"Text",
value:"",
liveChange: function(oEvent){
//Now call a function to filter your list.
filterList(oEvent,oStorage.get("previousFilteredList"));
}});
filterList: function(oEvent,yourObj){
var like = oEvent.getParameter("liveValue");
var oFilter = new sap.ui.model.Filter("name",
sap.ui.model.FilterOperator.StartsWith,like);
var element = sap.ui.getCore().getElementById("sample");
var listBinding = element.getBinding("items");
listBinding.filter([oFilter]);
//Add the filtered object oStorage after every filter to access the previous filtered data
//oStorage.put("previousFilteredList","yourobj");
},
//Wherever you filter your data first.
oStorage = jQuery.sap.storage("session");
oStorage.put("previousFilteredList","yourobj");
I think you have 2 options:
Apply the original filter and then the additional filters.
Make a new instance of the initially filtered list:
// assumes you have declared lists (initialList and newList)
// values between <..> should be replaced
jQuery.each (initialList, function (index, item) {
if (item.<someField> == <somevalue>) {
// you could add an additional field to the new list item like so:
item["<newFieldName"] = <newValue>;
if (item.<someOtherField> >= <someOtherValue>) {
newList.push(item); // adds this item to the new array / list
}
}
newListModel.setData(newList); // assumes newListModel has been created
//bind to control
I solved it using the 'and' condition in filter
var mainFilter=new sap.ui.model.Filter(parameter,sap.ui.model.FilterOperator.Contains,context);
var query =evt.getParameter("newValue");
if (query && query.length > 0)var filter1= new sap.ui.model.Filter("CLNAME",sap.ui.model.FilterOperator.Contains,query);
filtersArr1.push(filter1);
filtersArr1.push(mainFilter);
var filter2 = new sap.ui.model.Filter("CLNUM",sap.ui.model.FilterOperator.Contains, query);
filtersArr2.push(filter2);
filtersArr2.push(mainFilter);oFilter1 = new sap.ui.model.Filter(filtersArr1,true);oFilter2 = new sap.ui.model.Filter(filtersArr2,true);filterGroup.push(oFilter1,oFilter2);oFilter4 = new sap.ui.model.Filter(filterGroup,false);
binding.filter(oFilter4);
WORKING FINE
var listFilter=new sap.ui.model.Filter(parameter,sap.ui.model.FilterOperator.Contains,context);
var query =evt.getParameter("newValue");
if (query && query.length > 0)
var filter1= new sap.ui.model.Filter({
new sap.ui.model.Filter("CLNAME",sap.ui.model.FilterOperator.Contains,query),
new sap.ui.model.Filter("CLNUM",sap.ui.model.FilterOperator.Contains, query)}, and:false),
var oFilter = new sap.ui.model.Filter( [filter1, listFilter], true)
binding.filter(oFilter);
});

How to insert an item if not exists the one with the same name?

I'm inserting a batch of names:
myCollection.InsertBatch(value.Split(',').Where(o=> !string.IsNullOrEmpty(o)).Select( o => new Client { Name = o.Trim() }));
How to insert only the ones, that don't have the same Name?
p.s. Are MongoInsertOptions useful in this case?
Make unique index on "Name"
for example, in shell: db.MyCollection.ensureIndex({"Name":1}, {unique = true})
Add InsertOptions
var options = new MongoInsertOptions (myCollection) { CheckElementNames = true, Flags = InsertFlags.ContinueOnError, SafeMode = SafeMode.True};
var res = myCollection.InsertBatch(value.Split(',').Where(o => !string.IsNullOrEmpty(o)).Select(o => new Client { Name = o.Trim() }), options);