I have a large amount of text from which I need to find the most recurring words. I was thinking of using a hash table for that.
Issue is, I obtain this text by using a JavaScript API and I am a newbie at that. Is it a good idea to create hash tables in JS and do all of this or will that be very inefficient?
I come from C++/Java, so it's fairly easy to do it there, but the API I'm using is easier in JS.
Use javascript objects.
var myHash = {};
var textArr = ["Mango","Apple","Orange","Grapes","Orange","Apple","Apple"];
textArr.forEach(function(fruit){
if(myHash.hasOwnProperty(fruit)){
myHash[fruit]++;
}
else {
myHash[fruit] = 1; }
});
alert(JSON.stringify(myHash));
Related
I am using IBM BPM 8.6
I have an input string as follows:
"\"RECORD_CONTACT\":\"Maram\" , \"DRUG\":\"Panadol\"
In a script on server side, I want to dynamically create a business object like this:
tw.local.recordContact = Maram;
tw.local.drug = Panadol;
How can I dynamically create the business object?
There are a few problems with your request. The first is that you are not creating a business object, you are creating variables. In IBM BPM the variables have to be declared at design time or you will get an error, so invoking attempting to call something like -
tw.local.myVariable = 'Bob';
Will throw an exception if tw.local.myVariable has not been declared. Base on your other question you asked here (link), I'm going to assume you actually have an ANY variable declared called "return" so that
tw.local.return.myVariable = 'Bob'
will work. Given that I based on Sven's answer I think something like the following will work (you will need to validate)
var str = "\"RECORD_CONTACT\":\"Maram\" , \"DRUG\":\"Panadol\"";
var jsonStr = "{" + str.replace(/\\\"/g,'\"') + "}";
var tempValue = JSON.parse(jsonStr);
var keyArray = Object.keys(tempValue);
var valueArray = Object.values(tempValue);
for(var keyCount=0; keyCount<keyArray.length; keyCount++{
var evalString = "tw.local.return."+keyArray[keyCount]+"="+valueArray[keyCount];
eval(evalString);
}
I'll note that doing this is a very bad idea as it would be very brittle code and that using eval() in this manner opens you up to all sorts of possible exploits. It will also fail badly if the value for one of the keys is not a simple type.
-Andrew Paier
One should know what you are going to do with dynamically created Business Objects (BO) to answer you better. Like a very generic way would be - creating JSON object instead of BO.
But if you want to stick with BO then this is only possible when you know all the BO structure (schema) beforehand during design time.
var str = "\"RECORD_CONTACT\":\"Maram\" , \"DRUG\":\"Panadol\"";
vat objArray = str.split("reg ex to split each object string")
foreach (obj in objArray ){
if(obj.indexOf( "RECORD_CONTACT")!=-1)
tw.local.recordContact = new tw.object.RECORD_CONTACT();
//below goes code get value of each attribute of BPM from string
}
else if(obj.indexOf( "DRUG")!=-1){
//similar code to create BO DRUG
}
Don't forget to create BO before using those :)
The following code is working but extremely slow. Up till the search function all goes well. First, the search function returns a sequence and not an array (why?!). Second, the array consists of nodes and I need URI's for the delete. And third, the deleteDocument function takes a string and not an array of URI's.
What would be the better way to do this? I need to delete year+ old documents.
Here I use xdmp.log in stead of document.delete just te be safe.
var now = new Date();
var yearBack = now.setDate(now.getDate() - 365);
var date = new Date(yearBack);
var b = cts.jsonPropertyRangeQuery("Dtm", "<", date);
var c = cts.search(b, ['unfiltered']).toArray();
for (i=0; i<fn.count(c); i++) {
xdmp.log(fn.documentUri(c[i]), "info");
};
Doing the same with cts.uris:
var now = new Date();
var yearBack = now.setDate(now.getDate() - 365);
var date = new Date(yearBack);
var b = cts.jsonPropertyRangeQuery("Dtm", "<", date);
var c = cts.uris("", [], b);
while (true) {
var uri = c.next();
if (uri.done == true){
break;
}
xdmp.log(uri.value, "info");
}
HTH!
Using toArray will work but is most likely were your slowness is. The cts.search() function returns an iterator. So All you have to do is loop over it and do your deleting until there is no more items in it. Also You might want to limit your search to 1,000 items. A transaction with a large number of deletes will take a while and might time out.
Here is an example of looping over the iterator
var now = new Date();
var yearBack = now.setDate(now.getDate() - 365);
var date = new Date(yearBack);
var b = cts.jsonPropertyRangeQuery("Dtm", "<", date);
var c = cts.search(b, ['unfiltered']);
while (true) {
var doc = c.next();
if (doc.done == true){
break;
}
xdmp.log(fn.documentUri(doc), "info");
}
here is an example if you wanted to limit to the first 1,000.
fn.subsequence(cts.search(b, ['unfiltered']), 1, 1000);
Several things to consider.
1) If you are searching for the purpose of deleting or anything that doesnt require the document body, using a search that returns URIs instead of nodes can be much faster. If that isnt convenient then getting the URI as close to the search expression can achieve similar results. You want to avoid having the server have to fetch and expand the document just to get the URI to delete it.
2) While there is full coverage in the JavaScript API's for all MarkLogic features, the JavaScript API's are based on the same underlying functions that the XQuery API's use. Its useful to understand that, and take a look at the equivalent XQuery API docs to get the big picture. For example Arrays vs Iterators - If the JS search API's returned Arrays it could be a huge performance problem because the underlying code is based on 'lazy evaluation' of sequences. For example a search could return 1 million rows but if you only look at the first one the server can often avoid accessing the remaining 999,999,999 documents. Similarly, as you iterate only the in scope referenced data needs to be in available. If they had to be put into an array then all results would have to be pre-fetched and put put in memory upfront.
3) Always keep in mind that operations which return lists of things may only be bounded by how big your database is. That is why cts.search() and other functions have built in 'pagination'. You should code for that from the start.
By reading the users guides you can get a better understanding of not only how to do something, but how to do it efficiently - or even at all - once your database becomes larger than memory. In general its a good idea to always code for paginated results - it is a lot more efficient and your code will still work just as well after you add 100 docs or a million.
4) take a look at xdmp.nodeUrl https://docs.marklogic.com/xdmp.nodeUri,
This function, unlike fn.documentUri(), will work on any node even if its not document node. If you can put this right next to the search instead of next to the delete then the system can optimize much better. The examples in the JavaScript guide are a good start https://docs.marklogic.com/guide/getting-started/javascript#chapter
In your case I suggest something like this to experiment with both pagination and extracting the URIs without having to expand the documents ..
var uris = []
for (var result of fn.subsequence(cts.search( ... ), 1 , 100 )
uris.push(xdmp.nodeUri(result))
for( i in uris )
xdmp.log( uris[i] )
I was curious to see if anyone knew a of a way to reduce this javascript code:
var channels;
channels = [];
$('li.suggestions article').each(function() {
return channels.push($(this).data('channel-id'));
});
It's really simple -- the snippet just initializes an array called "channels", iterates over some DOM elements and collects their "data-channel-id" attribute, adding it to that array.
It is something I do a lot and it would be great to have this snippet simplified further -- I'd accept a CoffeeScript answer too if there is a nice solution.
var channels = $('li.suggestions article').map(function() {
return $(this).data('channel-id');
}).get();
Basically Im working with Sharepoint, help me god!
Sharepoint does some crazy the things but Im hoping what I want to do can be achieved using jQuery.
Sharepoint is writing some image values into a table:
<script>
fNewItem = false;
InsertItem("http://dev_site/sites/Pictures/Waves.jpg",
"5",
"BlueWaves",
"jpg",
"1920",
"1080",
"/_layouts/images/icjpg.gif", fNewItem);
</script>
There are a number of these output by Sharepoint, this snippet is from a Sharepoint Gallery so I'd need to loop through the page to find all of these so that I can grab all of the images.
What I want to know is if there is anyway for me to grab these values using jQuery and then output them again?
You can use this code (LIVE DEMO) ... you may need to tweak the if() statement a bit to determine which <script>..</script> blocks you want to deal with or not.
$('script').each(function(){
var t = $(this).text();
if (t.indexOf('fNewItem')>0 && t.indexOf('CDATA')<=0){
var a = t.split(/[\r\n]+/); //Split on Line Break
for (var x = 0; x<a.length; x++){
$('#result').append(a[x] + '<br>');
}
$('#result').append('<hr>');
}
});
I hava a url like
mysite.net/home/index/page/XX
while XX is any number. I need to replace XX and remove everything that might be behind XX. So I would like to remove everything behind page/ by replacing it with a number.
There are a lot of methods for string manipulation http://www.w3schools.com/jsref/jsref_obj_string.asp
I know how to perform this but I am not sure which methods to use. So I ended with getting the lastIndexOf("page/"). So this +1 would give me the starting point for replacing the string. The entire length of the string would be the ending point.
Any ideas?
The following code will do the trick, by using regular expression:
"mysite.net/home/index/page/XX".replace(/\/page\/.*/, '/page/123')
var url = "mysite.net/home/index/page/XX"
return url.substr(-(url.length - (url.lastIndexOf("page/") + 5))))
I don't get your problem because you may have found everything you need...
var yourURI = "mysite.net/home/index/page/XX";
var theDelimiter = "page/";
var yourNewIndex = "42";
var yourNewURI = null;
var lastIndexOfDelimiter = yourURI.lastIndexOf(theDelimiter);
if (lastIndexOfDelimiter != -1)
{
yourNewURI = yourURI.substr(0, lastIndexOfDelimiter + theDelimiter.length) + yourNewIndex;
}
Is that what you want?
This isn't a direct answer to your question, but the way I solve this kind of problem is to have the server calculate a 'base url' (mysite.net/home/index/page/ in your case), and write it to a js variable at the time the page is built.
For two different ASP.NET MVC versions (there would be something similar you could do in any other framework) this looks like this:
var baseUrl = '#ViewBag.BaseUrl';
or
var baseUrl = '<%: ViewData["BaseUrl"] %>';
This has the big advantage that the page JS doesn't start to know about URL formation, so if you change your URL routing you don't find little breakages all over the place.
At least for ASP.NET MVC, you can use the frameworks routing API to generate the base URL at the server side.