Cannot read property 'decode' of undefined - javascript

I have been playing around with the General Transit Feed Specification - Realtime, and I am following exactly the example given on google's documentation:
https://developers.google.com/transit/gtfs-realtime/examples/nodejs-sample
for JavaScript, using my cities local transit feed, however I keep encountering the following error:
var feed = GtfsRealtimeBindings.FeedMessage.decode(body);
^
TypeError: Cannot read property 'decode' of undefined
I have a working implementation in python that follows their example for that, so I can verify with certainty that the feed is the correct format.
I am running the code using the instruction:
node index.js
My package.json includes all the relevant dependencies, and I have installed using npm the required packages.
I have searched far and wide for a solution to this error but have had no luck. Any advice?

Looking at the current example code on GitHub
(https://github.com/MobilityData/gtfs-realtime-bindings/tree/master/nodejs#example-code)
it seems you're missing transit_realtime in between:
GtfsRealtimeBindings.transit_realtime.FeedMessage.decode(body);

On the example there is a link to the github of the Javascript language binding. The github example differs from the documentation example. I figure the documentation is simply out of date.
the line in the google documentation example
var feed = GtfsRealtimeBindings.FeedMessage.decode(body);
should be var feed = GtfsRealtimeBindings.transit_realtime.FeedMessage.decode(body); note the inclusion of .transit_realtime.
Alternatively this could be expressed in the line:
var GtfsRealtimeBindings = require('gtfs-realtime-bindings');
as var GtfsRealtimeBindings = require('gtfs-realtime-bindings').transit_realtime;
and the google documentation example code beyond that line would remain as it is.

You need to import gtfs-realtime-bindings by referencing the transit_realtime property. It's a change from the old protobuf.js bindings generator, but this is done to separate namespaces.
It won't work
cont GtfsRealtimeBindings = require('gtfs-realtime-bindings');
It will:
const GtfsRealtimeBindings = require('gtfs-realtime-bindings').transit_realtime;
Now you can get feedMessage and decode it.
const { FeedMessage, FeedHeader, FeedEntity, VehiclePosition } = GtfsRealtimeBindings;

Related

React-Native Simple Store Error: Unable to load RocksDB, SQLite, or AsyncLocalStorage

When running a basic app that uses react-native-simple-store I get the following error (the same as this unsolved question):
undefined is not an object (evaluating 'RCTAsyncStorage.multimerge')
<unkown>
AsyncStorage.js:325:21
...
Digging into AsyncStorage.js I find that the issue is here:
// Not all native implementations support merge.
if (!RCTAsyncStorage.multiMerge) {
delete AsyncStorage.mergeItem;
delete AsyncStorage.multiMerge;
}
RCTAsyncStorage is not undefined. The attempt to define RCTAsyncStorage comes at the beginning of the same file.
const NativeModules = require('../BatchedBridge/NativeModules');
// Use RocksDB if available, then SQLite, then file storage.
const RCTAsyncStorage = NativeModules.AsyncRocksDBStorage ||
NativeModules.AsyncSQLiteDBStorage ||
NativeModules.AsyncLocalStorage;
Finally, I checked NativeModules.AsyncRocksDBStorage, NativeModules.AsyncSQLiteDBStorage, and NativeModules.AsyncLocalStorage—surely enough, all of them were undefined. The file from which they are supposed to be loaded (NativeModules) is a bit difficult to understand, so I stopped tracing there.
Please let me know if you know what I could be doing wrong!

How to use d3-jetpack with d3v4?

I am trying to recreate this You Draw It graph:https://bl.ocks.org/1wheel/07d9040c3422dac16bd5be741433ff1e
It requires d3.conventions function which is in d3-jetpack which I found here: https://github.com/gka/d3-jetpack
raw d3v4 version is here: https://raw.githubusercontent.com/gka/d3-jetpack/master/build/d3v4%2Bjetpack.js
^I saved this file in the same folder as my index.html.
How do I import it into my index.html for my project?
ATTEMPT 1
Here is what I tried:
<script>
var d3 = Object.assign({}, require('d3v4+jetpack.js'));
</script>
This is the error I get: Uncaught ReferenceError: require is not defined
ATTEMPT 2
Added <script src="d3v4+jetpack.js"></script> in the header of the html file.
Says d3.conventions still not found.
If you choose to go down the d3 and jetpack route together, as it seems to be the case by your references to d3v4+jetpack.js, you must not load vanilla d3 in your script.
const d3j = require('d3-jetpack/build/d3v4+jetpack');
The line above does it for me. Note that it exposes d3j instead of d3, so you will of course need to adapt your code to something like:
const x = d3j.scaleLinear();
Hope this helps you!

Firefox add-on. How to really dowload image/file?

I'm getting more and more downhearted. For the last three days, I've been trying to add to my simple Firefox add-on a 'download image' feature.
The following is an add-on that creates a right-click contextual menu with a sub-menu:
var contextMenu = require("sdk/context-menu");
var clipboard = require("sdk/clipboard");
var data = require("sdk/self").data;
var myApp_cm = contextMenu.Menu({
label: "Send to myApp",
context: contextMenu.SelectorContext("body"),
items: [
contextMenu.Item({
label: "Send image to MyApp",
context: contextMenu.SelectorContext("img"),
contentScript: 'self.on("click", function (node, data) { ' +
' var link = node.src; ' +
' self.postMessage(link); ' +
'});',
onMessage: function(link) {
//
// Download image from 'link' and run 'myApp.exe' with
// downloaded image as parameter
//
}
})
]
});
I would like to add to the above code a simple download feature as the "Save as..." option of Firefox that downloads the image from the selected URL and runs an EXE with the downloaded image as a parameter.
I read everything I found about this argument starting from Mozilla MDN to all the questions asked at Stackoverflow. But, I never managed to make a single line of code work. I really don't understand why it's so complicated to download a file when this is the browser's job.
For example, I know that from Firefox 26+ I need to use downloads.jsm. So, I copied the following code from MDN.
Components.utils.import("resource://gre/modules/Downloads.jsm");
Components.utils.import("resource://gre/modules/osfile.jsm")
Components.utils.import("resource://gre/modules/Task.jsm");
Task.spawn(function () {
yield Downloads.fetch("http://www.mozilla.org/",OS.Path.join(OS.Constants.Path.tmpDir,"example-download.html"));
console.log("example-download.html has been downloaded.");
}).then(null, Components.utils.reportError);
But, I keep getting the error below:
So I added the string let {Cu, Ci, CC} = require('chrome') but nothing changes.
I'm 43 years old and I'm still learning JavaScript. I'm aware I don't have the same flexibility I had 2 decades ago. But, I remember that programming was much more straightforward. I still love programming but now I often find it quite frustrating.
I have not actually tried it, but I would not not expect the destructuring assignment
let {Cu, Ci, Cc} = require('chrome');
[Note: your CC should be Cc.]
to provide your Add-on SDK code to have access to the complete Components object through referencing it as Components, but only to have the properties (sub-objects) which you have assigned to "aliases" be available through the objects that you have defined using let:
Object ("alias") now available Object full name normally available
to your SDK add-on to Overlay and Restartless add-ons
Cu = Components.utils
Ci = Components.interfaces
Cc = Components.classes
The destructuring assignment should have extracted just the properties (sub-objects) referred to as Cu, Ci, and Cc within requre('chrome').
The code you copied from MDN would need to change to:
Cu.import("resource://gre/modules/Downloads.jsm");
Cu.import("resource://gre/modules/osfile.jsm")
Cu.import("resource://gre/modules/Task.jsm");
Task.spawn(function () {
yield Downloads.fetch("http://www.mozilla.org/",
OS.Path.join(OS.Constants.Path.tmpDir,"example-download.html"));
console.log("example-download.html has been downloaded.");
}).then(null, Cu.reportError);
If you wanted to use Components without using the Cc, Ci, Cu, Cr, and Cm aliases, you would need to use:
let {components} = require('chrome'); // note the lowercase "components"
let Components = components;
With that you could then use your original code:
Components.utils.import("resource://gre/modules/Downloads.jsm");
Components.utils.import("resource://gre/modules/osfile.jsm")
Components.utils.import("resource://gre/modules/Task.jsm");
Task.spawn(function () {
yield Downloads.fetch("http://www.mozilla.org/",
OS.Path.join(OS.Constants.Path.tmpDir,"example-download.html"));
console.log("example-download.html has been downloaded.");
}).then(null, Components.utils.reportError);
For more information, you can see the Chrome Authority page on MDN.
So, I copied the following code from MDN.
This is a big part of your problem. You're copying code without reasoning about it. Code snippets generally have prerequisites and assumptions that must be fulfilled, i.e. they must be evaluated on specific contexts - npm modules won't run in a browser for example.
Those code snippets too have dependencies, e.g. the Components object. The error message warns you about that, so that might be a good hint to read the documentation on require("chrome") and Components.
The second issue is that you're trying to use JSMs in an SDK addon without looking for equivalent SDK APIs first. Note that the top-level MDN Addon page distinguishes several types of extensions, especially SDK and legacy extensions. You're writing an SDK extension.
So for the purpose of downloading images instead of going through the file download manager (Downloads.jsm) you can simply use the request and IO SDK modules to download the file and then child_process to spawn the exe.
Task.spawn(function () {
yield Downloads.fetch("http://www.mozilla.org/",
That's using yield outside a generator function, which is legacy syntax and should not be used.
For chaining you probably should use ES6 promises instead.

react-highcharts: Cannot set property 'HighchartsAdapter' of undefined

Trying to run next example http://kirjs.github.io/react-highcharts
Stuck with line:
global.HighchartsAdapter = require('exports?HighchartsAdapter!highcharts-standalone-adapter');
Without it, get error
Uncaught TypeError: Cannot set property 'HighchartsAdapter' of undefined
With it, obviously get
Cannot find module 'exports?HighchartsAdapter!highcharts-standalone-adapter'
So, the real question is how to include HighchartsAdapter.
P.S. The title of this question is different because it was my original google request. And I am not alone https://github.com/kirjs/react-highcharts/search?q=Cannot+set+property+%27HighchartsAdapter%27+of+undefined&type=Issues&utf8=%E2%9C%93
The original example should be bundled using webpack. Then I suppose it works fine.
If you want to use Browserify, then instead of using:
global.HighchartsAdapter = require('exports?HighchartsAdapter!highcharts-standalone-adapter');
var Highcharts = require("highcharts");
use next:
var Highcharts = require('highcharts-browserify');

Make Closure Compiler strip log function usages

I have a logging API I want to expose to some internal JS code. I want to be able to use this API to log, but only when I am making a debug build. Right now, I have it partially working. It only logs on debug builds, but the calls to this API are still in the code when there is a regular build. I would like the closure-compiler to remove this essentially dead code when I compiler with goog.DEBUG = false.
Log definition:
goog.provide('com.foo.android.Log');
com.foo.Log.e = function(message){
goog.DEBUG && AndroidLog.e(message);
}
goog.export(com.foo.Log, "e", com.foo.Log.e);
AndroidLog is a Java object provided to the webview this will run in, and properly externed like this:
var AndroidLog = {};
/**
* Log out to the error console
*
* #param {string} message The message to log
*/
AndroidLog.e = function(message) {};
Then, in my code, I can use:
com.foo.Log.e("Hello!"); // I want these stripped in production builds
My question is this: How can I provide this API, use this API all over my code, but then have any calls to this API removed when not compiled with goog.DEBUG = true? Right now, my code base is getting bloated with a bunch of calls to the Log API that are never called. I want the removed.
Thanks!
The Closure Compiler provides four options in CompilerOptions.java to strip code: 1) stripTypes, 2) stripNameSuffixes, 3) stripNamePrefixes and 4) stripTypePrefixes. The Closure build tool plovr, exposes stripNameSuffixes and stripTypePrefixes through its JSON configuration file options name-suffixes-to-strip and type-prefixes-to-strip.
There are excellent examples of how these options work in Closure: The Definitive Guide on pages 442 to 444. The following lines are provided as common use cases:
options.stripTypePrefixes = ImmutableSet.of(“goog.debug”, “goog.asserts”);
options.stripNameSuffixes = ImmutableSet.of(“logger”, “logger_”);
To understand the nuances of these options and avoid potential pitfalls, I highly recommend reading the complete examples in Closure: The Definitive Guide.
Instead of running your own script as jfriend00 suggested I would look at the define api of the compiler (which is where goog.DEBUG comes from as well), you have DEBUG, COMPILED by default, but there you can roll your own.
OK, it turns out this is easy to do if I stop exporting com.foo.Log() and its methods. If I really want to be able to log in some specific cases, but still strip out the log calls in my internal code, I can just declare two classes for this:
// This will get inlined and stripped, since its not exported.
goog.provide('com.foo.android.Log');
com.foo.Log.e = function(message){
goog.DEBUG && AndroidLog.e(message);
}
// Don't export.
// This be available to use after closure compiler runs, since it's exported.
goog.provide('com.foo.android.production.Log');
goog.exportSymbol("ProductionLog", com.foo.android.production.Log);
com.foo.android.production.Log.log = function(message){
goog.DEBUG && AndroidLog.e(message);
}
// Export.
goog.exportProperty(com.foo.android.production.Log, "log", com.foo.android.production.Log.log);
I have modified a compiler and packaged it as an npm package.
You can get it here: https://github.com/thanpolas/superstartup-closure-compiler#readme
It will strip all logging messages during compilation

Categories