initialise timezoneJS with JSON files - javascript

I'm working with timezone-js: https://github.com/mde/timezone-js. I have a list of predefined timezones I want to work with. So I pre-parsed JSON Data of those timezones.
But how exactly am I supposed to use this data?
var _tz = timezoneJS.timezone;
_tz.loadingScheme = _tz.loadingSchemes.MANUAL_LOAD;
_tz.loadZoneJSONData('/major_cities.json', true);
I can read the data, like here. But how am I supposed to use the tz variable to initialise timezoneJS?
I'm thinking that I'm supposed to do something like this first:
timezoneJS.timezone.loadZoneDataFromObject(_tz);
And then initialise it... And then initialise timezoneJS, but if I initialise now, I'll get an error that it can't find the default timezone: Uncaught Error: Error retrieving "null/northamerica" zoneinfo files, probably because I've supplied the json data.
Can I'd like to know what to do to use the json file, so I can create timezoneJS.Date objects.

First of all, tz_ is just a short cut which prevents writing timezoneJS.timezone in the subsequent lines.
Now, there are two options. If you have your file major_cities.json on the server and you want to initialize timezoneJS you just have to do what you wrote:
var _tz = timezoneJS.timezone;
_tz.loadingScheme = _tz.loadingSchemes.MANUAL_LOAD;
_tz.loadZoneJSONData('/major_cities.json', true);
and you're all set. The second option is that you have an object containing data from that file. In such case you should use loadZoneDataFromObject instead of loadZoneJSONData, namely:
var _tz = timezoneJS.timezone;
_tz.loadingScheme = _tz.loadingSchemes.MANUAL_LOAD;
_tz.loadZoneDataFromObject(majorCitiesObject);
After that, you should not try calling the init function, hence timezoneJS is already initialized by the loadZoneJSONData. If you want to create a date, just call new timezoneJS.Date(). The following lines should give you a hint:
var timezoneName = 'Europe/London';
var newDate = new timezoneJS.Date(timezoneName);
console.log(newDate.toString());
console.log(newDate.toISOString());
Result should be sth like:
2013-04-08 11:56:33
2013-04-08T10:56:33.019Z

Related

NodeJS: Single object with all requires, or "standard" paths in code?

So, I'm a big fan of creating global namespaces in javascript. For example, if my app is named Xyz I normally have an object XYZ which I fill with properties and nested objects, for an example:
XYZ.Resources.ErrorMessage // = "An error while making request, please try again"
XYZ.DAL.City // = { getAll: function() { ... }, getById: function(id) { .. } }
XYZ.ViewModels.City // = { .... }
XYZ.Models.City // = { .... }
I sort of picked this up while working on a project with Knockout, and I really like it because there are no wild references to some objects declare in god-knows-where. Everything is in one place.
Now. This is ok for front-end, however, I'm currently developing a basic skeleton for a project which will start in a month, and it uses Node.
What I wanted was, instead of all the requires in .js files, I'd have a single object ('XYZ') which would hold all requires in one place. For example:
Instead of:
// route.js file
var cityModel = require('./models/city');
var cityService = require('./services/city');
app.get('/city', function() { ...........});
I would make an object:
XYZ.Models.City = require('./models/city');
XYZ.DAL.City = require('./services/city');
And use it like:
// route.js file
var cityModel = XYZ.Models.City;
var cityService = XYZ.DAL.City;
app.get('/city', function() { ...........});
I don't really have in-depth knowledge but all of the requires get cached and are served, if cached, from memory so re-requiring in multiple files isn't a problem.
Is this an ok workflow, or should I just stick to the standard procedure of referencing dependencies?
edit: I forgot to say, would this sort-of-factory pattern block the main thread, or delay the starting of the server? I just need to know what are the downsides... I don't mind the requires in code, but I just renamed a single folder and had to go through five files to change the paths... Which is really inconvenient.
I think that's a bad idea, because you are going to serve a ton of modules every single time, and you may not need them always. Your namespaced object will get quite monstrous. require will check the module cache first, so I'd use standard requires for each request / script that you need on the server.

Passing a currying function from Rails to JavaScript

I need to pass an URL to a .js file. This URL is generated by Rails and accepts one argument.
#routes
get "my_super/:some_id" => "controller1#my_super",
#index.html.haml
:javascript
var myUrlFunc = "#{my_super_url}"; //my_super_url(...) expects one argument
And a .js file:
$.ajax({
url: myUrlFunc($("#active_user_id"));
})
//................
The point is I don't know some_id initially as it's dynamically chosen, it's chosen from a drop down list. So I have to a function myUrlFunc which takes one argument and returns the URL instead of the URL itself. I thought this would work that it didn't due to an error:
No route matches {:action=>"my_super", :controller=>"controller1"} missing required keys: [:some_id]
What do I do about this?
As you have found out, the routing helper won't let you call it with missing parameters. Further more ruby doesn't know how to serialize a ruby method into a javascript function.
One simple, if not particularly elegant would be to pass a dummy value to my_super_url. Your function would then be along the lines of
var myUrlFunc = function(id){
var base = #{my_super_url("--DUMMY--")};
return base.replace("--DUMMY--", id);
}

Having problems structuring Cheerio scraping

I think this may be just basic syntax. I'm coming from Java and very new to Javascript. For example, when I see a $ in all the examples, my mind goes blank.
Code for parsing the HTTP request (which contains a bunch of dog shows) looks like (using the request library):
function parseRequest1(error, response, body) {
// TODO should check for error...
var Cheerio = require('cheerio');
parser = Cheerio.load(body);
var table2 = parser('.qs_table[bgcolor="#71828A"]');
var showList = [];
// skip over a bunch of crap to find the table. Each row with this BG color represents a dog show
var trows = parser('tr[bgcolor="#FFFFFF"]', table2);
trows.each(function(i, tablerow) {
var show = parseShow(tablerow);
if (show) // returns a null if something went wrong
showList.push(show);
});
// then do something with showList...
}
which is called by
Request.get(URL, parseRequest1);
So far, so good. Where I'm stuck is in how to write the parseShow function. I'd like to go something like
function parseShow(tableRow) {
var tds = parser('td', tableRow);
//and then go through the tds scraping info...
}
but I get an error:
TypeError: Object #<Object> has no method 'find'
at new module.exports (C:\Users\Morgan\WebstormProjects\agility\node_modules\cheerio\lib\cheerio.js:76:18)
at exports.load.initialize (C:\Users\Morgan\WebstormProjects\agility\node_modules\cheerio\lib\static.js:19:12)
at parseShow (C:\Users\Morgan\WebstormProjects\agility\routes\akc.js:20:15)
Looking at the stack trace, it looks like Cheerio is creating a new one. How am I supposed to pass the Cheerio parser down to the second function? Right now parser is a global var in the file.
I've tried a bunch of random things like these but they don't work either:
var tds = tableRow('td');
var tds = Cheerio('td', tableRow);
What I'm forced to do instead is a bunch of disgusting, fragile code accessing tableRow.children[1], tableRow.children[3], etc... (the HTML has /r/ns all over creation so many of the children are whitespace)
I know what you mean about the $(..). The $ is just a function name. I think it was chosen as it's short and catches the eye.
Used with Cheerio, and more generally JQuery, it is used with css selectors:
var table2 = $('.qs_table[bgcolor="#71828A"]');
The advantage of this is that table2 is now a selector Object and will have a .find() method which can be called.
In Jquery (I'm not so sure about Cheerio), the selector Object is also a collection, so multiple elements can be matched (or none).
The object model in javascript is a lot more dynamic than Java which can lead to much shorter - if more confusing code.
The code to parse table rows:
$('tr[bgcolor="#FFFFFF"]').each(function(i, tablerow) {
var show = tablerow.text();
if (show) // returns a null if something went wrong
showList.push(show);
});
In your code above parser(..) is used rather than $(..). However once, the object has been loaded with the body you can just keep using it:
parser('tr[bgcolor="#FFFFFF"]').each(function(i, tablerow) {
or to just find the rows of the table you want the following:
parser('.qs_table[bgcolor="#71828A"] tr[bgcolor="#FFFFFF"]').each(function(i, tablerow) {
The selector is css so this will find all tr[bgcolor="#FFFFFF"] elements which are children of the .qs_table[bg="#71828A'] element.

Store and retrieve Google Dart objects in JavaScript library containers

Store and retrieve Google Dart objects in JavaScript library containers
In a Dart application I am using an external JavaScript library to do various matrix calculations.
The specific functionality of the library is not important, what it's important is that I need to store and retrieve Dart object that I put in the matrix.
Dart Class - Lets image i have a dart object that which has a parameter called name
MyDartClass mydc = new MyDartClass(something, something);
mydc.name;
// Everything works as planned
Storing
matrix = js.context.matrix
matrix.cell(1,1).store("thing", new MyDartClass(something, something));
Retrieving
matrix.cell(1,1).has_object_of_type("thing");
// true
MyDartClass mydc = matrix.cell(1,1).retrieve("thing");
Do something with the object
mydc.name;
// Exception: The null object does not have a getter 'name'.
// NoSuchMethodError : method not found: 'name'
// Receiver: null
// Arguments: []
Does the library really work?
Yes it does. I have done the exact same thing in pure javascript many times and there are plenty of test to test the behaviour ( in Javascript )
Is Dart Broken?
When I try to use a javascriptified Hash to do the same behavoiur it works like a charm.
var options = js.map({ 'dart' : new MyDartclass(something, something));
var y = options["dart"];
js.context.console.log(y.name);
// Name is printed
What do you get out from the retrieve?
It seems that I get some kind of Dart Proxy
MyDartClass mydc = matrix.cell(1,1). retrieve("thing");
js.context.console.log(mydc);
DartProxy {id: "dart-ref-20", port: DartSendPortSync}
id: "dart-ref-20"
port: DartSendPortSync
__proto__: DartProxy
I belive that the lib stores the objects, deep down, in a hash map. But it seems like when I retrieve the object into the Dart I get something, but not in a way that I can work with it. So i need help since I don't know how to make it work.
Do I need to de-proxify the object?
Perhaps it IS a Dart bug when you try to retrieve objects from hashes inside objects
Perhaps I missunderstod everything that this is not suppose to work.
Passing and retrieving Dart objects inside the same scope is working. There's the following test case in the tests of js-interop to proove it :
test('retrieve same dart Object', () {
final date = new DateTime.now();
js.context.dartDate = date;
expect(js.context.dartDate, equals(date));
});
However there seems to be an issue with multiple scopes (and multiple event loops as well). There is no way to retain a dart object for now. So your dart object reference goes away at the end of scope. Here's a simple test case that fails :
test('retrieve same dart Object', () {
final date = new DateTime.now();
js.scoped(() {
js.context.dartDate = date;
});
js.scoped(() {
expect(js.context.dartDate, equals(date));
});
});
Please file an issue.

Renaming files in an Alfresco script

I am struggling to write a script in Alfresco to rename file extension.
The file is saved as filename.bin. I am using content rules to say when filename equals *bin rename to *pdf.
I am struggling a bit with the script and would appreciate any help.
My script is as below:
// change the name of this document
document.properties.name = document.properties.name+".pdf";
// add a new property string
document.properties["cm:locale"] = mylocalenode;
// save the property modifications
document.save();
but doesn't seem to get me anywhere.
The script as written would take a document named "filename.bin" and rename it to "filename.bin.pdf". It would then set a property called "cm:locale" equal to the value of mylocalenode, which appears to be
undefined in this snippet. I don't know what you are going for with the cm:locale so I will ignore that and give you a script that will search for the document named filename.bin and change its name.
If you would rather iterate over the children in a folder, you should be able to look at the Alfresco JavaScript API to figure out how to modify the snippet below to do that.
var results = search.luceneSearch("#cm\\:name:filename.bin");
var doc = results[0]; // assumes there is only one result, which may not be what you want
var oldName = doc.properties.name;
var newName = oldName.replace('.bin', '.pdf');
doc.properties.name = newName;
doc.save();
Adding more in this,as you are using content-rule.There is no need to search document using lucene/solr service .We can directly access document object,it refers to document on which your rule is being executed.
So the code will be like below.
var oldName = document.properties.name;
var newName = oldName.replace('.bin', '.pdf');
document.properties.name = newName;
document.save();

Categories