text:
"use strict";

var assert = require("assert"),
    vows = require("vows"),
    Step = require("step"),
    _ = require("lodash"),
    OAuth = require("oauth-evanp").OAuth,
    httputil = require("./lib/http"),
    oauthutil = require("./lib/oauth"),
    apputil = require("./lib/app"),
    withAppSetup = apputil.withAppSetup,
    register = oauthutil.register,
    newCredentials = oauthutil.newCredentials,
    newPair = oauthutil.newPair,
    newClient = oauthutil.newClient;

var ignore = function(err) {};

var suite = vows.describe("Restricted post test");

var makeCred = function(cl, pair) {
    return {
        consumer_key: cl.client_id,
        consumer_secret: cl.client_secret,
        token: pair.token,
        token_secret: pair.token_secret
    };
};

var clientCred = function(cl) {
    return {
        consumer_key: cl.client_id,
        consumer_secret: cl.client_secret
    };
};

var pairOf = function(user) {
    return {token: user.token, token_secret: user.secret};
};

// A batch for testing the visibility of bcc and bto addressing

suite.addBatch(
    withAppSetup({
        "and we register a client": {
            topic: function() {
                newClient(this.callback);
            },
            "it works": function(err, cl) {
                assert.ifError(err);
                assert.isObject(cl);
            },
            "and a user posts a note to another user": {
                topic: function(cl) {
                    var cb = this.callback,
                        users = {
                            mrmoose: {
                                password: "ping*pong*balls"
                            },
                            mrbunnyrabbit: {
                                password: "i{heart}carrots"
                            },
                            townclown: {
                                password: "balloons?"
                            }

                        };
                    Step(
                        function() {
                            register(cl, "mrmoose", users.mrmoose.password, this.parallel());
                            register(cl, "mrbunnyrabbit", users.mrbunnyrabbit.password, this.parallel());
                            register(cl, "townclown", users.townclown.password, this.parallel());
                        },
                        function(err, user1, user2, user3) {
                            var url, cred, act;
                            if (err) throw err;
                            users.mrmoose.profile = user1.profile;
                            users.mrbunnyrabbit.profile   = user2.profile;
                            users.townclown.profile = user3.profile;

                            users.mrmoose.pair = pairOf(user1);
                            users.mrbunnyrabbit.pair = pairOf(user2);
                            users.townclown.pair = pairOf(user3);

                            cred = makeCred(cl, users.townclown.pair);

                            act = {
                                verb: "follow",
                                object: {
                                    objectType: "person",
                                    id: users.mrmoose.profile.id
                                }
                            };
                            url = "http://localhost:4815/api/user/townclown/feed";
                            httputil.postJSON(url, cred, act, this);
                        },
                        function(err, doc, resp) {
                            var url, cred, act;
                            if (err) throw err;
                            cred = makeCred(cl, users.mrmoose.pair);
                            act = {
                                verb: "post",
                                to: [{
                                    id: users.mrbunnyrabbit.profile.id,
                                    objectType: "person"
                                }],
                                object: {
                                    objectType: "note",
                                    content: "Knock knock!"
                                }
                            };
                            url = "http://localhost:4815/api/user/mrmoose/feed";
                            httputil.postJSON(url, cred, act, this);
                        },
                        function(err, doc, response) {
                            if (err) {
                                cb(err, null, null);
                            } else {
                                cb(null, doc, users);
                            }
                        }
                    );
                },
                "it works": function(err, doc, users) {
                    assert.ifError(err);
                },
                "and the author reads the activity": {
                    topic: function(doc, users, cl) {
                        var cred = makeCred(cl, users.mrmoose.pair),
                            cb = this.callback,
                            url = doc.links.self.href;

                        httputil.getJSON(url, cred, function(err, act, response) {
                            cb(err, doc, act);
                        });
                    },
                    "it works": function(err, orig, copy) {
                        assert.ifError(err);
                        assert.isObject(copy);
                        assert.equal(orig.id, copy.id);
                    }
                },
                "and the author reads the note": {
                    topic: function(doc, users, cl) {
                        var cred = makeCred(cl, users.mrmoose.pair),
                            cb = this.callback,
                            url = doc.object.id;

                        httputil.getJSON(url, cred, function(err, note, response) {
                            cb(err, doc.object, note);
                        });
                    },
                    "it works": function(err, orig, copy) {
                        assert.ifError(err);
                        assert.isObject(copy);
                        assert.equal(orig.id, copy.id);
                    }
                },
                "and the author reads the likes stream": {
                    topic: function(doc, users, cl) {
                        var cred = makeCred(cl, users.mrmoose.pair),
                            cb = this.callback,
                            url = doc.object.likes.url;

                        httputil.getJSON(url, cred, function(err, likes, response) {
                            cb(err, likes);
                        });
                    },
                    "it works": function(err, likes) {
                        assert.ifError(err);
                        assert.isObject(likes);
                    }
                },
                "and the author reads the replies stream": {
                    topic: function(doc, users, cl) {
                        var cred = makeCred(cl, users.mrmoose.pair),
                            cb = this.callback,
                            url = doc.object.replies.url;

                        httputil.getJSON(url, cred, function(err, replies, response) {
                            cb(err, replies);
                        });
                    },
                    "it works": function(err, replies) {
                        assert.ifError(err);
                        assert.isObject(replies);
                    }
                },
                "and the author reads their own feed": {
                    topic: function(doc, users, cl) {
                        var cred = makeCred(cl, users.mrmoose.pair),
                            cb = this.callback,
                            url = "http://localhost:4815/api/user/mrmoose/feed";

                        httputil.getJSON(url, cred, function(err, feed, response) {
                            cb(err, doc, feed);
                        });
                    },
                    "it works": function(err, act, feed) {
                        assert.ifError(err);
                    },
                    "it includes the private post-note activity": function(err, act, feed) {
                        assert.ifError(err);
                        assert.include(feed, "items");
                        assert.isArray(feed.items);
                        assert.ok(_.find(feed.items, function(item) { return item.id === act.id; }));
                    }
                },
                "and the author reads their own inbox": {
                    topic: function(doc, users, cl) {
                        var cred = makeCred(cl, users.mrmoose.pair),
                            cb = this.callback,
                            url = "http://localhost:4815/api/user/mrmoose/inbox";

                        httputil.getJSON(url, cred, function(err, inbox, response) {
                            cb(err, doc, inbox);
                        });
                    },
                    "it works": function(err, act, inbox) {
                        assert.ifError(err);
                    },
                    "it includes the private post-note activity": function(err, act, inbox) {
                        assert.ifError(err);
                        assert.include(inbox, "items");
                        assert.isArray(inbox.items);
                        assert.ok(_.find(inbox.items, function(item) { return item.id === act.id; }));
                    }
                },
                "and the recipient reads the activity": {
                    topic: function(doc, users, cl) {
                        var cred = makeCred(cl, users.mrbunnyrabbit.pair),
                            cb = this.callback,
                            url = doc.links.self.href;

                        httputil.getJSON(url, cred, function(err, act, response) {
                            cb(err, doc, act);
                        });
                    },
                    "it works": function(err, orig, copy) {
                        assert.ifError(err);
                        assert.isObject(copy);
                        assert.equal(orig.id, copy.id);
                    }
                },
                "and the recipient reads the note": {
                    topic: function(doc, users, cl) {
                        var cred = makeCred(cl, users.mrbunnyrabbit.pair),
                            cb = this.callback,
                            url = doc.object.id;

                        httputil.getJSON(url, cred, function(err, note, response) {
                            cb(err, doc.object, note);
                        });
                    },
                    "it works": function(err, orig, copy) {
                        assert.ifError(err);
                        assert.isObject(copy);
                        assert.equal(orig.id, copy.id);
                    }
                },
                "and the recipient reads the likes stream": {
                    topic: function(doc, users, cl) {
                        var cred = makeCred(cl, users.mrbunnyrabbit.pair),
                            cb = this.callback,
                            url = doc.object.likes.url;

                        Step(
                            function() {
                                setTimeout(this, 100);
                            },
                            function() {
                                httputil.getJSON(url, cred, function(err, likes, response) {
                                    cb(err, likes);
                                });
                            }
                        );
                    },
                    "it works": function(err, likes) {
                        assert.ifError(err);
                        assert.isObject(likes);
                    }
                },
                "and the recipient reads the replies stream": {
                    topic: function(doc, users, cl) {
                        var cred = makeCred(cl, users.mrbunnyrabbit.pair),
                            cb = this.callback,
                            url = doc.object.replies.url;

                        httputil.getJSON(url, cred, function(err, replies, response) {
                            cb(err, replies);
                        });
                    },
                    "it works": function(err, replies) {
                        assert.ifError(err);
                        assert.isObject(replies);
                    }
                },
                "and the recipient reads the author's feed": {
                    topic: function(doc, users, cl) {
                        var cred = makeCred(cl, users.mrbunnyrabbit.pair),
                            cb = this.callback,
                            url = "http://localhost:4815/api/user/mrmoose/feed";

                        httputil.getJSON(url, cred, function(err, feed, response) {
                            cb(err, doc, feed);
                        });
                    },
                    "it works": function(err, act, feed) {
                        assert.ifError(err);
                    },
                    "it includes the private post-note activity": function(err, act, feed) {
                        assert.ifError(err);
                        assert.include(feed, "items");
                        assert.isArray(feed.items);
                        assert.ok(_.find(feed.items, function(item) { return item.id === act.id; }));
                    }
                },
                "and the recipient reads their own inbox": {
                    topic: function(doc, users, cl) {
                        var cred = makeCred(cl, users.mrbunnyrabbit.pair),
                            cb = this.callback,
                            url = "http://localhost:4815/api/user/mrbunnyrabbit/inbox";

                        httputil.getJSON(url, cred, function(err, inbox, response) {
                            cb(err, doc, inbox);
                        });
                    },
                    "it works": function(err, act, inbox) {
                        assert.ifError(err);
                    },
                    "it includes the private post-note activity": function(err, act, inbox) {
                        assert.ifError(err);
                        assert.include(inbox, "items");
                        assert.isArray(inbox.items);
                        assert.ok(_.find(inbox.items, function(item) { return item.id === act.id; }));
                    }
                },
                "and a follower reads the activity": {
                    topic: function(doc, users, cl) {
                        var cred = makeCred(cl, users.townclown.pair),
                            cb = this.callback,
                            url = doc.links.self.href;

                        httputil.getJSON(url, cred, function(err, act, response) {
                            if (err && err.statusCode && err.statusCode === 403) {
                                cb(null);
                            } else if (err) {
                                cb(err);
                            } else {
                                cb(new Error("Unexpected success"));
                            }
                        });
                    },
                    "it fails with a 403 Forbidden": function(err) {
                        assert.ifError(err);
                    }
                },
                "and a follower reads the note": {
                    topic: function(doc, users, cl) {
                        var cred = makeCred(cl, users.townclown.pair),
                            cb = this.callback,
                            url = doc.object.id;

                        httputil.getJSON(url, cred, function(err, note, response) {
                            if (err && err.statusCode && err.statusCode === 403) {
                                cb(null);
                            } else if (err) {
                                cb(err);
                            } else {
                                cb(new Error("Unexpected success"));
                            }
                        });
                    },
                    "it fails with a 403 Forbidden": function(err) {
                        assert.ifError(err);
                    }
                },
                "and a follower reads the likes stream": {
                    topic: function(doc, users, cl) {
                        var cred = makeCred(cl, users.townclown.pair),
                            cb = this.callback,
                            url = doc.object.likes.url;

                        httputil.getJSON(url, cred, function(err, likes, response) {
                            if (err && err.statusCode && err.statusCode === 403) {
                                cb(null);
                            } else if (err) {
                                cb(err);
                            } else {
                                cb(new Error("Unexpected success"));
                            }
                        });
                    },
                    "it fails with a 403 Forbidden": function(err) {
                        assert.ifError(err);
                    }
                },
                "and a follower reads the replies stream": {
                    topic: function(doc, users, cl) {
                        var cred = makeCred(cl, users.townclown.pair),
                            cb = this.callback,
                            url = doc.object.replies.url;

                        httputil.getJSON(url, cred, function(err, replies, response) {
                            if (err && err.statusCode && err.statusCode === 403) {
                                cb(null);
                            } else if (err) {
                                cb(err);
                            } else {
                                cb(new Error("Unexpected success"));
                            }
                        });
                    },
                    "it fails with a 403 Forbidden": function(err) {
                        assert.ifError(err);
                    }
                },
                "and a follower reads the author's feed": {
                    topic: function(doc, users, cl) {
                        var cred = makeCred(cl, users.townclown.pair),
                            cb = this.callback,
                            url = "http://localhost:4815/api/user/mrmoose/feed";

                        httputil.getJSON(url, cred, function(err, feed, response) {
                            cb(err, doc, feed);
                        });
                    },
                    "it works": function(err, act, feed) {
                        assert.ifError(err);
                    },
                    "it does not include the private post-note activity": function(err, act, feed) {
                        assert.ifError(err);
                        assert.include(feed, "items");
                        assert.isArray(feed.items);
                        assert.isEmpty(_.filter(feed.items, {id: act.id}));
                    }
                },
                "and a follower reads their own inbox": {
                    topic: function(doc, users, cl) {
                        var cred = makeCred(cl, users.townclown.pair),
                            cb = this.callback,
                            url = "http://localhost:4815/api/user/townclown/inbox";

                        httputil.getJSON(url, cred, function(err, inbox, response) {
                            cb(err, doc, inbox);
                        });
                    },
                    "it works": function(err, act, inbox) {
                        assert.ifError(err);
                    },
                    "it doesn't include the private post-note activity": function(err, act, inbox) {
                        assert.ifError(err);
                        assert.include(inbox, "items");
                        assert.isArray(inbox.items);
                        // should be the follow activity, welcome note, reg activity
                        assert.isEmpty(_.filter(inbox.items, {id: act.id}));
                    }
                },
                "and an anonymous user reads the activity": {
                    topic: function(doc, users, cl) {
                        var cred = clientCred(cl),
                            cb = this.callback,
                            url = doc.links.self.href;

                        httputil.getJSON(url, cred, function(err, act, response) {
                            if (err && err.statusCode && err.statusCode === 403) {
                                cb(null);
                            } else if (err) {
                                cb(err);
                            } else {
                                cb(new Error("Unexpected success"));
                            }
                        });
                    },
                    "it fails with a 403 Forbidden": function(err) {
                        assert.ifError(err);
                    }
                },
                "and an anonymous user reads the note": {
                    topic: function(doc, users, cl) {
                        var cred = clientCred(cl),
                            cb = this.callback,
                            url = doc.object.id;

                        httputil.getJSON(url, cred, function(err, note, response) {
                            if (err && err.statusCode && err.statusCode === 403) {
                                cb(null);
                            } else if (err) {
                                cb(err);
                            } else {
                                cb(new Error("Unexpected success"));
                            }
                        });
                    },
                    "it fails with a 403 Forbidden": function(err) {
                        assert.ifError(err);
                    }
                },
                "and an anonymous user reads the likes stream": {
                    topic: function(doc, users, cl) {
                        var cred = clientCred(cl),
                            cb = this.callback,
                            url = doc.object.likes.url;

                        httputil.getJSON(url, cred, function(err, likes, response) {
                            if (err && err.statusCode && err.statusCode === 403) {
                                cb(null);
                            } else if (err) {
                                cb(err);
                            } else {
                                cb(new Error("Unexpected success"));
                            }
                        });
                    },
                    "it fails with a 403 Forbidden": function(err) {
                        assert.ifError(err);
                    }
                },
                "and an anonymous user reads the replies stream": {
                    topic: function(doc, users, cl) {
                        var cred = clientCred(cl),
                            cb = this.callback,
                            url = doc.object.replies.url;

                        httputil.getJSON(url, cred, function(err, replies, response) {
                            if (err && err.statusCode && err.statusCode === 403) {
                                cb(null);
                            } else if (err) {
                                cb(err);
                            } else {
                                cb(new Error("Unexpected success"));
                            }
                        });
                    },
                    "it fails with a 403 Forbidden": function(err) {
                        assert.ifError(err);
                    }
                },
                "and an anonymous user reads the author's feed": {
                    topic: function(doc, users, cl) {
                        var cred = clientCred(cl),
                            cb = this.callback,
                            url = "http://localhost:4815/api/user/mrmoose/feed";

                        httputil.getJSON(url, cred, function(err, feed, response) {
                            cb(err, doc, feed);
                        });
                    },
                    "it works": function(err, act, feed) {
                        assert.ifError(err);
                    },
                    "it does not include the private post-note activity": function(err, act, feed) {
                        assert.ifError(err);
                        assert.include(feed, "items");
                        assert.isArray(feed.items);
                        assert.isEmpty(_.filter(feed.items, {id: act.id}));
                    }
                }
            },
            "and a user posts a public note": {
                topic: function(cl) {
                    var cb = this.callback,
                        users = {
                            captain: {
                                password: "kangaroo!"
                            },
                            mrgreenjeans: {
                                password: "animals_are_great"
                            },
                            dancingbear: {
                                password: "hey*doll"
                            }

                        };
                    Step(
                        function() {
                            register(cl, "captain", users.captain.password, this.parallel());
                            register(cl, "mrgreenjeans", users.mrgreenjeans.password, this.parallel());
                            register(cl, "dancingbear", users.dancingbear.password, this.parallel());
                        },
                        function(err, user1, user2, user3) {
                            var url, cred, act;
                            if (err) throw err;
                            users.captain.profile = user1.profile;
                            users.mrgreenjeans.profile   = user2.profile;
                            users.dancingbear.profile = user3.profile;
                            users.captain.pair = pairOf(user1);
                            users.mrgreenjeans.pair = pairOf(user2);
                            users.dancingbear.pair = pairOf(user3);

                            cred = makeCred(cl, users.dancingbear.pair);
                            act = {
                                verb: "follow",
                                object: {
                                    objectType: "person",
                                    id: users.captain.profile.id
                                }
                            };
                            url = "http://localhost:4815/api/user/dancingbear/feed";
                            httputil.postJSON(url, cred, act, this);
                        },
                        function(err, doc, resp) {
                            var url, cred, act, Collection = require("../lib/model/collection").Collection;
                            if (err) throw err;
                            cred = makeCred(cl, users.captain.pair);
                            act = {
                                verb: "post",
                                to: [{
                                    id: Collection.PUBLIC,
                                    objectType: "collection"
                                }],
                                object: {
                                    objectType: "note",
                                    content: "Good morning!"
                                }
                            };
                            url = "http://localhost:4815/api/user/captain/feed";
                            httputil.postJSON(url, cred, act, this);
                        },
                        function(err, doc, response) {
                            if (err) {
                                cb(err, null, null);
                            } else {
                                cb(null, doc, users);
                            }
                        }
                    );
                },
                "it works": function(err, doc, users) {
                    assert.ifError(err);
                },
                "and the author reads the activity": {
                    topic: function(doc, users, cl) {
                        var cred = makeCred(cl, users.captain.pair),
                            cb = this.callback,
                            url = doc.links.self.href;

                        httputil.getJSON(url, cred, function(err, act, response) {
                            cb(err, doc, act);
                        });
                    },
                    "it works": function(err, orig, copy) {
                        assert.ifError(err);
                        assert.isObject(copy);
                        assert.equal(orig.id, copy.id);
                    }
                },
                "and the author reads the note": {
                    topic: function(doc, users, cl) {
                        var cred = makeCred(cl, users.captain.pair),
                            cb = this.callback,
                            url = doc.object.id;

                        httputil.getJSON(url, cred, function(err, note, response) {
                            cb(err, doc.object, note);
                        });
                    },
                    "it works": function(err, orig, copy) {
                        assert.ifError(err);
                        assert.isObject(copy);
                        assert.equal(orig.id, copy.id);
                    }
                },
                "and the author reads the likes stream": {
                    topic: function(doc, users, cl) {
                        var cred = makeCred(cl, users.captain.pair),
                            cb = this.callback,
                            url = doc.object.likes.url;

                        Step(
                            function() {
                                setTimeout(this, 100);
                            },
                            function() {
                                httputil.getJSON(url, cred, function(err, likes, response) {
                                    cb(err, likes);
                                });
                            }
                            );
                    },
                    "it works": function(err, likes) {
                        assert.ifError(err);
                        assert.isObject(likes);
                    }
                },
                "and the author reads the replies stream": {
                    topic: function(doc, users, cl) {
                        var cred = makeCred(cl, users.captain.pair),
                            cb = this.callback,
                            url = doc.object.replies.url;

                        httputil.getJSON(url, cred, function(err, replies, response) {
                            cb(err, replies);
                        });
                    },
                    "it works": function(err, replies) {
                        assert.ifError(err);
                        assert.isObject(replies);
                    }
                },
                "and the author reads their own feed": {
                    topic: function(doc, users, cl) {
                        var cred = makeCred(cl, users.captain.pair),
                            cb = this.callback,
                            url = "http://localhost:4815/api/user/captain/feed";

                        httputil.getJSON(url, cred, function(err, feed, response) {
                            cb(err, doc, feed);
                        });
                    },
                    "it works": function(err, act, feed) {
                        assert.ifError(err);
                    },
                    "it includes the public post-note activity": function(err, act, feed) {
                        assert.ifError(err);
                        assert.include(feed, "items");
                        assert.isArray(feed.items);
                        assert.ok(_.find(feed.items, function(item) { return item.id === act.id; }));
                    }
                },
                "and the author reads their own inbox": {
                    topic: function(doc, users, cl) {
                        var cred = makeCred(cl, users.captain.pair),
                            cb = this.callback,
                            url = "http://localhost:4815/api/user/captain/inbox";

                        httputil.getJSON(url, cred, function(err, inbox, response) {
                            cb(err, doc, inbox);
                        });
                    },
                    "it works": function(err, act, inbox) {
                        assert.ifError(err);
                    },
                    "it includes the public post-note activity": function(err, act, inbox) {
                        assert.ifError(err);
                        assert.include(inbox, "items");
                        assert.isArray(inbox.items);
                        assert.ok(_.find(inbox.items, function(item) { return item.id === act.id; }));
                    }
                },
                "and an unrelated user reads the activity": {
                    topic: function(doc, users, cl) {
                        var cred = makeCred(cl, users.mrgreenjeans.pair),
                            cb = this.callback,
                            url = doc.links.self.href;

                        httputil.getJSON(url, cred, function(err, act, response) {
                            cb(err, doc, act);
                        });
                    },
                    "it works": function(err, orig, copy) {
                        assert.ifError(err);
                        assert.isObject(copy);
                        assert.equal(orig.id, copy.id);
                    }
                },
                "and an unrelated user reads the note": {
                    topic: function(doc, users, cl) {
                        var cred = makeCred(cl, users.mrgreenjeans.pair),
                            cb = this.callback,
                            url = doc.object.id;

                        httputil.getJSON(url, cred, function(err, note, response) {
                            cb(err, doc.object, note);
                        });
                    },
                    "it works": function(err, orig, copy) {
                        assert.ifError(err);
                        assert.isObject(copy);
                        assert.equal(orig.id, copy.id);
                    }
                },
                "and an unrelated user reads the likes stream": {
                    topic: function(doc, users, cl) {
                        var cred = makeCred(cl, users.mrgreenjeans.pair),
                            cb = this.callback,
                            url = doc.object.likes.url;

                        httputil.getJSON(url, cred, function(err, likes, response) {
                            cb(err, likes);
                        });
                    },
                    "it works": function(err, likes) {
                        assert.ifError(err);
                        assert.isObject(likes);
                    }
                },
                "and an unrelated user reads the replies stream": {
                    topic: function(doc, users, cl) {
                        var cred = makeCred(cl, users.mrgreenjeans.pair),
                            cb = this.callback,
                            url = doc.object.replies.url;

                        httputil.getJSON(url, cred, function(err, replies, response) {
                            cb(err, replies);
                        });
                    },
                    "it works": function(err, replies) {
                        assert.ifError(err);
                        assert.isObject(replies);
                    }
                },
                "and an unrelated user reads the author's feed": {
                    topic: function(doc, users, cl) {
                        var cred = makeCred(cl, users.mrgreenjeans.pair),
                            cb = this.callback,
                            url = "http://localhost:4815/api/user/captain/feed";

                        httputil.getJSON(url, cred, function(err, feed, response) {
                            cb(err, doc, feed);
                        });
                    },
                    "it works": function(err, act, feed) {
                        assert.ifError(err);
                    },
                    "it includes the public post-note activity": function(err, act, feed) {
                        assert.ifError(err);
                        assert.include(feed, "items");
                        assert.isArray(feed.items);
                        assert.ok(_.find(feed.items, function(item) { return item.id === act.id; }));
                    }
                },
                "and an unrelated user reads their own inbox": {
                    topic: function(doc, users, cl) {
                        var cred = makeCred(cl, users.mrgreenjeans.pair),
                            cb = this.callback,
                            url = "http://localhost:4815/api/user/mrgreenjeans/inbox";

                        httputil.getJSON(url, cred, function(err, inbox, response) {
                            cb(err, doc, inbox);
                        });
                    },
                    "it works": function(err, act, inbox) {
                        assert.ifError(err);
                    },
                    "it does not include the public post-note activity": function(err, act, inbox) {
                        assert.ifError(err);
                        assert.include(inbox, "totalItems");
                        assert.isNumber(inbox.totalItems);
                        assert.isEmpty(_.filter(inbox.items, {id: act.id}));
                    }
                },
                "and a follower reads the activity": {
                    topic: function(doc, users, cl) {
                        var cred = makeCred(cl, users.dancingbear.pair),
                            cb = this.callback,
                            url = doc.links.self.href;

                        httputil.getJSON(url, cred, function(err, act, response) {
                            cb(err, doc, act);
                        });
                    },
                    "it works": function(err, orig, copy) {
                        assert.ifError(err);
                        assert.isObject(copy);
                        assert.equal(orig.id, copy.id);
                    }
                },
                "and a follower reads the note": {
                    topic: function(doc, users, cl) {
                        var cred = makeCred(cl, users.dancingbear.pair),
                            cb = this.callback,
                            url = doc.object.id;

                        httputil.getJSON(url, cred, function(err, note, response) {
                            cb(err, doc.object, note);
                        });
                    },
                    "it works": function(err, orig, copy) {
                        assert.ifError(err);
                        assert.isObject(copy);
                        assert.equal(orig.id, copy.id);
                    }
                },
                "and a follower reads the likes stream": {
                    topic: function(doc, users, cl) {
                        var cred = makeCred(cl, users.dancingbear.pair),
                            cb = this.callback,
                            url = doc.object.likes.url;

                        Step(
                            function() {
                                setTimeout(this, 100);
                            }, function() {
                                httputil.getJSON(url, cred, function(err, likes, response) {
                                    cb(err, likes);
                                });
                            }
                            );
                    },
                    "it works": function(err, likes) {
                        assert.ifError(err);
                        assert.isObject(likes);
                    }
                },
                "and a follower reads the replies stream": {
                    topic: function(doc, users, cl) {
                        var cred = makeCred(cl, users.dancingbear.pair),
                            cb = this.callback,
                            url = doc.object.replies.url;

                        httputil.getJSON(url, cred, function(err, replies, response) {
                            cb(err, replies);
                        });
                    },
                    "it works": function(err, replies) {
                        assert.ifError(err);
                        assert.isObject(replies);
                    }
                },
                "and a follower reads the author's feed": {
                    topic: function(doc, users, cl) {
                        var cred = makeCred(cl, users.dancingbear.pair),
                            cb = this.callback,
                            url = "http://localhost:4815/api/user/captain/feed";

                        httputil.getJSON(url, cred, function(err, feed, response) {
                            cb(err, doc, feed);
                        });
                    },
                    "it works": function(err, act, feed) {
                        assert.ifError(err);
                    },
                    "it includes the public post-note activity": function(err, act, feed) {
                        assert.ifError(err);
                        assert.include(feed, "items");
                        assert.isArray(feed.items);
                        assert.ok(_.find(feed.items, function(item) { return item.id === act.id; }));
                    }
                },
                "and a follower reads their own inbox": {
                    topic: function(doc, users, cl) {
                        var cred = makeCred(cl, users.dancingbear.pair),
                            cb = this.callback,
                            url = "http://localhost:4815/api/user/dancingbear/inbox";

                        httputil.getJSON(url, cred, function(err, inbox, response) {
                            cb(err, doc, inbox);
                        });
                    },
                    "it works": function(err, act, inbox) {
                        assert.ifError(err);
                    },
                    "it includes the public post-note activity": function(err, act, feed) {
                        assert.ifError(err);
                        assert.include(feed, "items");
                        assert.isArray(feed.items);
                        assert.ok(_.find(feed.items, function(item) { return item.id === act.id; }));
                    }
                },
                "and an anonymous user reads the activity": {
                    topic: function(doc, users, cl) {
                        var cred = clientCred(cl),
                            cb = this.callback,
                            url = doc.links.self.href;

                        httputil.getJSON(url, cred, function(err, act, response) {
                            cb(err, doc, act);
                        });
                    },
                    "it works": function(err, orig, copy) {
                        assert.ifError(err);
                        assert.isObject(copy);
                        assert.equal(orig.id, copy.id);
                    }
                },
                "and an anonymous user reads the note": {
                    topic: function(doc, users, cl) {
                        var cred = clientCred(cl),
                            cb = this.callback,
                            url = doc.object.id;

                        httputil.getJSON(url, cred, function(err, note, response) {
                            cb(err, doc.object, note);
                        });
                    },
                    "it works": function(err, orig, copy) {
                        assert.ifError(err);
                        assert.isObject(copy);
                        assert.equal(orig.id, copy.id);
                    }
                },
                "and an anonymous user reads the likes stream": {
                    topic: function(doc, users, cl) {
                        var cred = clientCred(cl),
                            cb = this.callback,
                            url = doc.object.likes.url;

                        Step(
                            function() {
                                setTimeout(this, 100);
                            },
                            function() {
                                httputil.getJSON(url, cred, function(err, likes, response) {
                                    cb(err, likes);
                                });
                            }
                        );
                    },
                    "it works": function(err, likes) {
                        assert.ifError(err);
                        assert.isObject(likes);
                    }
                },
                "and an anonymous user reads the replies stream": {
                    topic: function(doc, users, cl) {
                        var cred = makeCred(cl, users.dancingbear.pair),
                            cb = this.callback,
                            url = doc.object.replies.url;

                        httputil.getJSON(url, cred, function(err, replies, response) {
                            cb(err, replies);
                        });
                    },
                    "it works": function(err, replies) {
                        assert.ifError(err);
                        assert.isObject(replies);
                    }
                },
                "and an anonymous user reads the author's feed": {
                    topic: function(doc, users, cl) {
                        var cred = clientCred(cl),
                            cb = this.callback,
                            url = "http://localhost:4815/api/user/captain/feed";

                        httputil.getJSON(url, cred, function(err, feed, response) {
                            cb(err, doc, feed);
                        });
                    },
                    "it works": function(err, act, feed) {
                        assert.ifError(err);
                    },
                    "it includes the public post-note activity": function(err, act, feed) {
                        assert.ifError(err);
                        assert.include(feed, "items");
                        assert.isArray(feed.items);
                        assert.ok(_.find(feed.items, function(item) { return item.id === act.id; }));
                    }
                }
            }
        }
    })
);

suite["export"](module);


text:
package dns01

import (
	"errors"
	"fmt"
	"net"
	"strings"
	"sync"
	"time"

	"github.com/miekg/dns"
)

const defaultResolvConf = "/etc/resolv.conf"

// dnsTimeout is used to override the default DNS timeout of 10 seconds.
var dnsTimeout = 10 * time.Second

var (
	fqdnSoaCache   = map[string]*soaCacheEntry{}
	muFqdnSoaCache sync.Mutex
)

var defaultNameservers = []string{
	"google-public-dns-a.google.com:53",
	"google-public-dns-b.google.com:53",
}

// recursiveNameservers are used to pre-check DNS propagation.
var recursiveNameservers = getNameservers(defaultResolvConf, defaultNameservers)

// soaCacheEntry holds a cached SOA record (only selected fields).
type soaCacheEntry struct {
	zone      string    // zone apex (a domain name)
	primaryNs string    // primary nameserver for the zone apex
	expires   time.Time // time when this cache entry should be evicted
}

func newSoaCacheEntry(soa *dns.SOA) *soaCacheEntry {
	return &soaCacheEntry{
		zone:      soa.Hdr.Name,
		primaryNs: soa.Ns,
		expires:   time.Now().Add(time.Duration(soa.Refresh) * time.Second),
	}
}

// isExpired checks whether a cache entry should be considered expired.
func (cache *soaCacheEntry) isExpired() bool {
	return time.Now().After(cache.expires)
}

// ClearFqdnCache clears the cache of fqdn to zone mappings. Primarily used in testing.
func ClearFqdnCache() {
	muFqdnSoaCache.Lock()
	fqdnSoaCache = map[string]*soaCacheEntry{}
	muFqdnSoaCache.Unlock()
}

func AddDNSTimeout(timeout time.Duration) ChallengeOption {
	return func(_ *Challenge) error {
		dnsTimeout = timeout
		return nil
	}
}

func AddRecursiveNameservers(nameservers []string) ChallengeOption {
	return func(_ *Challenge) error {
		recursiveNameservers = ParseNameservers(nameservers)
		return nil
	}
}

// getNameservers attempts to get systems nameservers before falling back to the defaults.
func getNameservers(path string, defaults []string) []string {
	config, err := dns.ClientConfigFromFile(path)
	if err != nil || len(config.Servers) == 0 {
		return defaults
	}

	return ParseNameservers(config.Servers)
}

func ParseNameservers(servers []string) []string {
	var resolvers []string
	for _, resolver := range servers {
		// ensure all servers have a port number
		if _, _, err := net.SplitHostPort(resolver); err != nil {
			resolvers = append(resolvers, net.JoinHostPort(resolver, "53"))
		} else {
			resolvers = append(resolvers, resolver)
		}
	}
	return resolvers
}

// lookupNameservers returns the authoritative nameservers for the given fqdn.
func lookupNameservers(fqdn string) ([]string, error) {
	var authoritativeNss []string

	zone, err := FindZoneByFqdn(fqdn)
	if err != nil {
		return nil, fmt.Errorf("could not determine the zone: %w", err)
	}

	r, err := dnsQuery(zone, dns.TypeNS, recursiveNameservers, true)
	if err != nil {
		return nil, err
	}

	for _, rr := range r.Answer {
		if ns, ok := rr.(*dns.NS); ok {
			authoritativeNss = append(authoritativeNss, strings.ToLower(ns.Ns))
		}
	}

	if len(authoritativeNss) > 0 {
		return authoritativeNss, nil
	}
	return nil, errors.New("could not determine authoritative nameservers")
}

// FindPrimaryNsByFqdn determines the primary nameserver of the zone apex for the given fqdn
// by recursing up the domain labels until the nameserver returns a SOA record in the answer section.
func FindPrimaryNsByFqdn(fqdn string) (string, error) {
	return FindPrimaryNsByFqdnCustom(fqdn, recursiveNameservers)
}

// FindPrimaryNsByFqdnCustom determines the primary nameserver of the zone apex for the given fqdn
// by recursing up the domain labels until the nameserver returns a SOA record in the answer section.
func FindPrimaryNsByFqdnCustom(fqdn string, nameservers []string) (string, error) {
	soa, err := lookupSoaByFqdn(fqdn, nameservers)
	if err != nil {
		return "", err
	}
	return soa.primaryNs, nil
}

// FindZoneByFqdn determines the zone apex for the given fqdn
// by recursing up the domain labels until the nameserver returns a SOA record in the answer section.
func FindZoneByFqdn(fqdn string) (string, error) {
	return FindZoneByFqdnCustom(fqdn, recursiveNameservers)
}

// FindZoneByFqdnCustom determines the zone apex for the given fqdn
// by recursing up the domain labels until the nameserver returns a SOA record in the answer section.
func FindZoneByFqdnCustom(fqdn string, nameservers []string) (string, error) {
	soa, err := lookupSoaByFqdn(fqdn, nameservers)
	if err != nil {
		return "", err
	}
	return soa.zone, nil
}

func lookupSoaByFqdn(fqdn string, nameservers []string) (*soaCacheEntry, error) {
	muFqdnSoaCache.Lock()
	defer muFqdnSoaCache.Unlock()

	// Do we have it cached and is it still fresh?
	if ent := fqdnSoaCache[fqdn]; ent != nil && !ent.isExpired() {
		return ent, nil
	}

	ent, err := fetchSoaByFqdn(fqdn, nameservers)
	if err != nil {
		return nil, err
	}

	fqdnSoaCache[fqdn] = ent
	return ent, nil
}

func fetchSoaByFqdn(fqdn string, nameservers []string) (*soaCacheEntry, error) {
	var err error
	var in *dns.Msg

	labelIndexes := dns.Split(fqdn)
	for _, index := range labelIndexes {
		domain := fqdn[index:]

		in, err = dnsQuery(domain, dns.TypeSOA, nameservers, true)
		if err != nil {
			continue
		}

		if in == nil {
			continue
		}

		switch in.Rcode {
		case dns.RcodeSuccess:
			// Check if we got a SOA RR in the answer section
			if len(in.Answer) == 0 {
				continue
			}

			// CNAME records cannot/should not exist at the root of a zone.
			// So we skip a domain when a CNAME is found.
			if dnsMsgContainsCNAME(in) {
				continue
			}

			for _, ans := range in.Answer {
				if soa, ok := ans.(*dns.SOA); ok {
					return newSoaCacheEntry(soa), nil
				}
			}
		case dns.RcodeNameError:
			// NXDOMAIN
		default:
			// Any response code other than NOERROR and NXDOMAIN is treated as error
			return nil, fmt.Errorf("unexpected response code '%s' for %s", dns.RcodeToString[in.Rcode], domain)
		}
	}

	return nil, fmt.Errorf("could not find the start of authority for %s%s", fqdn, formatDNSError(in, err))
}

// dnsMsgContainsCNAME checks for a CNAME answer in msg.
func dnsMsgContainsCNAME(msg *dns.Msg) bool {
	for _, ans := range msg.Answer {
		if _, ok := ans.(*dns.CNAME); ok {
			return true
		}
	}
	return false
}

func dnsQuery(fqdn string, rtype uint16, nameservers []string, recursive bool) (*dns.Msg, error) {
	m := createDNSMsg(fqdn, rtype, recursive)

	var in *dns.Msg
	var err error

	for _, ns := range nameservers {
		in, err = sendDNSQuery(m, ns)
		if err == nil && len(in.Answer) > 0 {
			break
		}
	}
	return in, err
}

func createDNSMsg(fqdn string, rtype uint16, recursive bool) *dns.Msg {
	m := new(dns.Msg)
	m.SetQuestion(fqdn, rtype)
	m.SetEdns0(4096, false)

	if !recursive {
		m.RecursionDesired = false
	}

	return m
}

func sendDNSQuery(m *dns.Msg, ns string) (*dns.Msg, error) {
	udp := &dns.Client{Net: "udp", Timeout: dnsTimeout}
	in, _, err := udp.Exchange(m, ns)

	if in != nil && in.Truncated {
		tcp := &dns.Client{Net: "tcp", Timeout: dnsTimeout}
		// If the TCP request succeeds, the err will reset to nil
		in, _, err = tcp.Exchange(m, ns)
	}

	return in, err
}

func formatDNSError(msg *dns.Msg, err error) string {
	var parts []string

	if msg != nil {
		parts = append(parts, dns.RcodeToString[msg.Rcode])
	}

	if err != nil {
		parts = append(parts, err.Error())
	}

	if len(parts) > 0 {
		return ": " + strings.Join(parts, " ")
	}

	return ""
}

redpajama_set_name: RedPajamaGithub


text:
#import <Foundation/NSObject.h>

@class NSData, NSDictionary, NSError, NSHost, NSInputStream, NSOutputStream, NSRunLoop, NSString, NSURL;
@protocol NSStreamDelegate;

typedef NS_ENUM(NSUInteger, NSStreamStatus) {
    NSStreamStatusNotOpen = 0,
    NSStreamStatusOpening = 1,
    NSStreamStatusOpen = 2,
    NSStreamStatusReading = 3,
    NSStreamStatusWriting = 4,
    NSStreamStatusAtEnd = 5,
    NSStreamStatusClosed = 6,
    NSStreamStatusError = 7
};

typedef NS_OPTIONS(NSUInteger, NSStreamEvent) {
    NSStreamEventNone = 0,
    NSStreamEventOpenCompleted = 1UL << 0,
    NSStreamEventHasBytesAvailable = 1UL << 1,
    NSStreamEventHasSpaceAvailable = 1UL << 2,
    NSStreamEventErrorOccurred = 1UL << 3,
    NSStreamEventEndEncountered = 1UL << 4
};

// NSStream is an abstract class encapsulating the common API to NSInputStream and NSOutputStream.
// Subclassers of NSInputStream and NSOutputStream must also implement these methods.
@interface NSStream : NSObject
- (void)open;
- (void)close;

- (id <NSStreamDelegate>)delegate;
- (void)setDelegate:(id <NSStreamDelegate>)delegate;
    // By default, a stream is its own delegate, and subclassers of NSInputStream and NSOutputStream must maintain this contract. [someStream setDelegate:nil] must restore this behavior. As usual, delegates are not retained.

- (id)propertyForKey:(NSString *)key;
- (BOOL)setProperty:(id)property forKey:(NSString *)key;

- (void)scheduleInRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode;
- (void)removeFromRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode;

- (NSStreamStatus)streamStatus;
- (NSError *)streamError;
@end

// NSInputStream is an abstract class representing the base functionality of a read stream.
// Subclassers are required to implement these methods.
@interface NSInputStream : NSStream
- (NSInteger)read:(uint8_t *)buffer maxLength:(NSUInteger)len;
    // reads up to length bytes into the supplied buffer, which must be at least of size len. Returns the actual number of bytes read.

- (BOOL)getBuffer:(uint8_t **)buffer length:(NSUInteger *)len;
    // returns in O(1) a pointer to the buffer in 'buffer' and by reference in 'len' how many bytes are available. This buffer is only valid until the next stream operation. Subclassers may return NO for this if it is not appropriate for the stream type. This may return NO if the buffer is not available.

- (BOOL)hasBytesAvailable;
    // returns YES if the stream has bytes available or if it impossible to tell without actually doing the read.
@end

// NSOutputStream is an abstract class representing the base functionality of a write stream.
// Subclassers are required to implement these methods.
@interface NSOutputStream : NSStream
- (NSInteger)write:(const uint8_t *)buffer maxLength:(NSUInteger)len;
    // writes the bytes from the specified buffer to the stream up to len bytes. Returns the number of bytes actually written.

- (BOOL)hasSpaceAvailable;
    // returns YES if the stream can be written to or if it is impossible to tell without actually doing the write.
@end

#if (TARGET_OS_MAC && !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE))
@interface NSStream (NSSocketStreamCreationExtensions)
+ (void)getStreamsToHost:(NSHost *)host port:(NSInteger)port inputStream:(NSInputStream **)inputStream outputStream:(NSOutputStream **)outputStream;
@end
#endif

// The NSInputStreamExtensions category contains additional initializers and convenience routines for dealing with NSInputStreams.
@interface NSInputStream (NSInputStreamExtensions)
- (id)initWithData:(NSData *)data;
- (id)initWithFileAtPath:(NSString *)path;
- (id)initWithURL:(NSURL *)url NS_AVAILABLE(10_6, 4_0);

+ (id)inputStreamWithData:(NSData *)data;
+ (id)inputStreamWithFileAtPath:(NSString *)path;
+ (id)inputStreamWithURL:(NSURL *)url NS_AVAILABLE(10_6, 4_0);
@end

// The NSOutputStreamExtensions category contains additional initializers and convenience routines for dealing with NSOutputStreams.
@interface NSOutputStream (NSOutputStreamExtensions)
- (id)initToMemory;
- (id)initToBuffer:(uint8_t *)buffer capacity:(NSUInteger)capacity;
- (id)initToFileAtPath:(NSString *)path append:(BOOL)shouldAppend;
- (id)initWithURL:(NSURL *)url append:(BOOL)shouldAppend NS_AVAILABLE(10_6, 4_0);

+ (id)outputStreamToMemory;
+ (id)outputStreamToBuffer:(uint8_t *)buffer capacity:(NSUInteger)capacity;
+ (id)outputStreamToFileAtPath:(NSString *)path append:(BOOL)shouldAppend;
+ (id)outputStreamWithURL:(NSURL *)url append:(BOOL)shouldAppend NS_AVAILABLE(10_6, 4_0);
@end

@protocol NSStreamDelegate <NSObject>
@optional
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode;
@end

// NSString constants for the propertyForKey/setProperty:forKey: API
// String constants for the setting of the socket security level.
FOUNDATION_EXPORT NSString * const NSStreamSocketSecurityLevelKey		NS_AVAILABLE(10_3, 2_0);	// use this as the key for setting one of the following values for the security level of the target stream.

FOUNDATION_EXPORT NSString * const NSStreamSocketSecurityLevelNone		NS_AVAILABLE(10_3, 2_0);
FOUNDATION_EXPORT NSString * const NSStreamSocketSecurityLevelSSLv2		NS_AVAILABLE(10_3, 2_0);
FOUNDATION_EXPORT NSString * const NSStreamSocketSecurityLevelSSLv3		NS_AVAILABLE(10_3, 2_0);
FOUNDATION_EXPORT NSString * const NSStreamSocketSecurityLevelTLSv1		NS_AVAILABLE(10_3, 2_0);
FOUNDATION_EXPORT NSString * const NSStreamSocketSecurityLevelNegotiatedSSL	NS_AVAILABLE(10_3, 2_0);

FOUNDATION_EXPORT NSString * const NSStreamSOCKSProxyConfigurationKey		NS_AVAILABLE(10_3, 2_0);	// Value is an NSDictionary containing the key/value pairs below. The dictionary returned from SystemConfiguration for SOCKS proxies will work without alteration.

FOUNDATION_EXPORT NSString * const NSStreamSOCKSProxyHostKey			NS_AVAILABLE(10_3, 2_0);
    // Value is an NSString
FOUNDATION_EXPORT NSString * const NSStreamSOCKSProxyPortKey			NS_AVAILABLE(10_3, 2_0);
    // Value is an NSNumber
FOUNDATION_EXPORT NSString * const NSStreamSOCKSProxyVersionKey		NS_AVAILABLE(10_3, 2_0);
    // Value is one of NSStreamSOCKSProxyVersion4 or NSStreamSOCKSProxyVersion5
FOUNDATION_EXPORT NSString * const NSStreamSOCKSProxyUserKey			NS_AVAILABLE(10_3, 2_0);
    // Value is an NSString
FOUNDATION_EXPORT NSString * const NSStreamSOCKSProxyPasswordKey		NS_AVAILABLE(10_3, 2_0);
    // Value is an NSString

FOUNDATION_EXPORT NSString * const NSStreamSOCKSProxyVersion4			NS_AVAILABLE(10_3, 2_0);
    // Value for NSStreamSOCKProxyVersionKey
FOUNDATION_EXPORT NSString * const NSStreamSOCKSProxyVersion5			NS_AVAILABLE(10_3, 2_0);
    // Value for NSStreamSOCKProxyVersionKey

FOUNDATION_EXPORT NSString * const NSStreamDataWrittenToMemoryStreamKey	NS_AVAILABLE(10_3, 2_0);
    // Key for obtaining the data written to a memory stream.

FOUNDATION_EXPORT NSString * const NSStreamFileCurrentOffsetKey		NS_AVAILABLE(10_3, 2_0);
    // Value is an NSNumber representing the current absolute offset of the stream.

// NSString constants for error domains.
FOUNDATION_EXPORT NSString * const NSStreamSocketSSLErrorDomain			NS_AVAILABLE(10_3, 2_0);
    // SSL errors are to be interpreted via <Security/SecureTransport.h>
FOUNDATION_EXPORT NSString * const NSStreamSOCKSErrorDomain			NS_AVAILABLE(10_3, 2_0);

// Property key to specify the type of service for the stream.  This
// allows the system to properly handle the request with respect to
// routing, suspension behavior and other networking related attributes
// appropriate for the given service type.  The service types supported
// are documented below.
FOUNDATION_EXPORT NSString * const NSStreamNetworkServiceType		    NS_AVAILABLE(10_7, 4_0);
// Supported network service types:
FOUNDATION_EXPORT NSString * const NSStreamNetworkServiceTypeVoIP	    NS_AVAILABLE(10_7, 4_0);
FOUNDATION_EXPORT NSString * const NSStreamNetworkServiceTypeVideo	    NS_AVAILABLE(10_7, 5_0);
FOUNDATION_EXPORT NSString * const NSStreamNetworkServiceTypeBackground	    NS_AVAILABLE(10_7, 5_0);
FOUNDATION_EXPORT NSString * const NSStreamNetworkServiceTypeVoice	    NS_AVAILABLE(10_7, 5_0);


text:
var dataViews = require('../');

/**
 *
 * @constructor
 * @implements {IDataView}
 */
var Radio = function(data) {
	goog.base(this, data);
};
goog.inherits(Radio, dataViews.Abstract);

/**
 * @return {Promise.<Array.<Main>>}
 */
Radio.prototype.getChildren = function() {
	return app.service.radio.parse('http://2kom.tv/channels/radio.m3u');
};

/**
 * @return {string}
 */
Radio.prototype.toString = function() {
	return 'Radio';
};

module.exports = Radio;


text:
using System;
using Xamarin.Forms;

namespace AiForms.Renderers
{
    /// <summary>
    /// Checkbox cell.
    /// </summary>
    public class CheckboxCell:CellBase
    {
        /// <summary>
        /// The checked property.
        /// </summary>
        public static BindableProperty CheckedProperty =
            BindableProperty.Create(
                nameof(Checked),
                typeof(bool),
                typeof(CheckboxCell),
                default(bool),
                defaultBindingMode: BindingMode.TwoWay
            );

        /// <summary>
        /// Gets or sets a value indicating whether this <see cref="T:AiForms.Renderers.CheckboxCell"/> is checked.
        /// </summary>
        /// <value><c>true</c> if checked; otherwise, <c>false</c>.</value>
        public bool Checked {
            get { return (bool)GetValue(CheckedProperty); }
            set { SetValue(CheckedProperty, value); }
        }

        /// <summary>
        /// The accent color property.
        /// </summary>
        public static BindableProperty AccentColorProperty =
            BindableProperty.Create(
                nameof(AccentColor),
                typeof(Color),
                typeof(CheckboxCell),
                default(Color),
                defaultBindingMode: BindingMode.OneWay
            );

        /// <summary>
        /// Gets or sets the color of the accent.
        /// </summary>
        /// <value>The color of the accent.</value>
        public Color AccentColor {
            get { return (Color)GetValue(AccentColorProperty); }
            set { SetValue(AccentColorProperty, value); }
        }
    }
}


text:
export class HM {
    private _minutes: number;

    static Now(): HM {
        let now = new Date();
        let hour = now.getHours();
        let min = now.getMinutes();
        return new HM(hour, min);
    }

    constructor(hoursminutes: HM);
    constructor(minutes: number);
    constructor(strValue: string);
    constructor(hour: number, min: number);
    constructor(param1: (string | number | HM), param2?: number) {
        if (param2 !== undefined) {
            this._minutes = this._toMinutes(<number>param1, param2);
        } else if (typeof param1 === 'number') {
            this._minutes = param1;
        } else if (typeof param1 === 'string') {
            this.parse(<string>param1);
        } else {
            this._minutes = (<HM>param1).minutes;
        }
    }

    get minutes(): number {
        return this._minutes;
    }

    equals(other: HM): boolean {
        return (this.minutes === other.minutes);
    }

    toString(pos = '', neg = '-'): string {
        let sign = Math.sign(this._minutes);
        let hours = this.hours();
        let minutes = this.min();

        let s = (sign < 0) ? neg : pos;
        if (this._minutes === 0) {
            s = '';
        }
        let minstr = ('00' + minutes).substr(-2);
        return s + hours + ':' + minstr;
    }

    add(add2: HM): HM {
        return new HM(this._minutes + add2._minutes);
    }

    sub(sub2: HM): HM {
        return new HM(this._minutes - sub2._minutes);
    }

    private parse(value: string) {
        let sign: number;
        if (/^[\+\-]?\d{1,2}:\d{2}$/.test(value)) {
            if (value[0] === '-') {
                sign = -1;
                value = value.substr(1);
            } else if (value[0] === '+') {
                sign = 1;
                value = value.substr(1);
            } else {
                sign = 1;
            }
            let parts = value.split(':');
            this._minutes = this._toMinutes(sign * parseFloat(parts[0]),
                sign * parseFloat(parts[1]));
        } else {
            throw new Error('Invalid time string.');
        }
    }

    private hours(): number {
        return Math.floor(Math.abs(this._minutes) / 60);
    }

    private min(): number {
        return Math.abs(this._minutes) % 60;
    }

    private _toMinutes(hour: number, min: number) {
        let sign: number;

        if (hour !== 0) {
            sign = Math.sign(hour);
        } else {
            sign = Math.sign(min);
        }

        hour = Math.abs(hour);
        min = Math.abs(min);

        return sign * ((hour * 60) + min);
    }
}


text:
<template name="mugenRoleGroupsUpdate">

Home

Mugen Role Groups

update

Update Mugen Role Groups

            {{> mugenRoleGroups_form model}}

</template>


text:
/**
 * Consumes the Seniority Table
 */

(function (){
    angular.module('Humanity')
        .factory("SeniorityFactory", seniorityApi);

    var seniorityEndPoint = globalConfig.apiEndpoint + "/seniority/:id";

    function seniorityApi (r) {
        return r(seniorityEndPoint, {id:'@id', sort:'name'}, { update: {method:'PUT' }});
    }
    seniorityApi.$inject = ['$resource'];
})();


text:
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.md in the project root for license information.

using System;
using System.Globalization;

namespace Microsoft.AspNet.SignalR.Utils
{
    internal class UninstallPerformanceCountersCommand : Command
    {
        public UninstallPerformanceCountersCommand(Action<string> info, Action<string> success, Action<string> warning, Action<string> error)
            : base(info, success, warning, error)
        {

        }

        public override string DisplayName
        {
            get { return String.Format(CultureInfo.CurrentCulture, Resources.Notify_UninstallPerformanceCounters); }
        }

        public override string Help
        {
            get { return String.Format(CultureInfo.CurrentCulture, Resources.Notify_UninstallSignalRPerformanceCounters); }
        }

        public override string[] Names
        {
            get { return new[] { "upc" }; }
        }

        public override void Execute(string[] args)
        {
            var installer = new PerformanceCounterInstaller();
            installer.UninstallCounters();

            Success(String.Format(CultureInfo.CurrentCulture, Resources.Notify_PerformanceCountersUninstalled));
        }
    }
}


text:
var CircuitBreakerZookeeper = require("./CircuitBreakerZookeeper");
var CircuitBreakerZookeeperMiddleware = require("./CircuitBreakerZookeeperMiddleware");
var _express_ = require("express");

var cbz = new CircuitBreakerZookeeper(process.argv[2], "/foo");

var app = _express_();
app.use(CircuitBreakerZookeeperMiddleware(cbz));
app.get("/", function (err, res) {
	res.send(200, "Hello, world!");
	res.end();
});
app.listen(8080);


text:
RubyDoc.info is the next generation Ruby doc server, replacing
[http://rdoc.info](http://rdoc.info) and
[http://yardoc.org/docs](http://yardoc.org/docs).
This doc server uses YARD to generate project documentation on the fly, for
both published RubyGems as well as GitHub projects.

The public doc server is hosted at [http://www.rubydoc.info](http://www.rubydoc.info)

## Getting Started

This site is a public service and is community-supported. Patches and
enhancements are welcome.

Running the doc server locally is easy:

```sh
git clone git://github.com/lsegal/rubydoc.info
cd rubydoc.info
bundle install
cp config/config.yaml.sample config/config.yaml
bundle exec rake gems:update
bundle exec rake server:start
```

This will start a daemonized process, you can stop the server with:

```sh
bundle exec rake server:stop
```

### Running With Docker

If you have Docker installed, you can get started using `docker-compose`:

```sh
docker-compose up
```

Add `-d` to daemonize the process. To stop the server in daemonized mode,
run `docker-compose down`.

## Thanks

RubyDoc.info was created by Loren Segal (YARD) and Nick Plante (rdoc.info) and is a project of DOCMETA, LLC.
Additional help was provided by [our friendly developer community](https://github.com/lsegal/rubydoc.info/graphs/contributors).
Pull requests welcome!

(c) 2019 DOCMETA LLC. This code is distributed under the MIT license.


text:
"""
Implementation of the C{@property} value handling.

RDFa 1.0 and RDFa 1.1 are fairly different. RDFa 1.0 generates only literals, see
U{RDFa Task Force's wiki page<http://www.w3.org/2006/07/SWD/wiki/RDFa/LiteralObject>} for the details.
On the other hand, RDFa 1.1, beyond literals, can also generate URI references. Hence the duplicate method in the L{ProcessProperty} class, one for RDFa 1.0 and the other for RDFa 1.1.

@summary: RDFa Literal generation
@requires: U{RDFLib package<http://rdflib.net>}
@organization: U{World Wide Web Consortium<http://www.w3.org>}
@author: U{Ivan Herman<a href="http://www.w3.org/People/Ivan/">}
@license: This software is available for use under the
U{W3C® SOFTWARE NOTICE AND LICENSE<href="http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231">}
"""

"""
$Id: property.py,v 1.11 2012/06/12 11:47:11 ivan Exp $
$Date: 2012/06/12 11:47:11 $
"""

import re, sys

import rdflib
from rdflib	import BNode
from rdflib	import Literal, URIRef, Namespace
if rdflib.__version__ >= "3.0.0" :
	from rdflib	     import RDF as ns_rdf
	from rdflib.term import XSDToPython
else :
	from rdflib.RDF	    import RDFNS as ns_rdf
	from rdflib.Literal import XSDToPython

from .	         import IncorrectBlankNodeUsage, IncorrectLiteral, err_no_blank_node, ns_xsd
from .utils      import has_one_of_attributes, return_XML
from .host.html5 import handled_time_types

XMLLiteral  = ns_rdf["XMLLiteral"]
HTMLLiteral = URIRef("http://www.w3.org/1999/02/22-rdf-syntax-ns#HTML")

class ProcessProperty :
	"""Generate the value for C{@property} taking into account datatype, etc.
	Note: this class is created only if the C{@property} is indeed present, no need to check.

	@ivar node: DOM element node
	@ivar graph: the (RDF) graph to add the properies to
	@ivar subject: the RDFLib URIRef serving as a subject for the generated triples
	@ivar state: the current state to be used for the CURIE-s
	@type state: L{state.ExecutionContext}
	@ivar typed_resource: Typically the bnode generated by a @typeof
	"""
	def __init__(self, node, graph, subject, state, typed_resource = None) :
		"""
		@param node: DOM element node
		@param graph: the (RDF) graph to add the properies to
		@param subject: the RDFLib URIRef serving as a subject for the generated triples
		@param state: the current state to be used for the CURIE-s
		@param state: L{state.ExecutionContext}
		@param typed_resource: Typically the bnode generated by a @typeof; in RDFa 1.1, that becomes the object for C{@property}
		"""
		self.node           = node
		self.graph          = graph
		self.subject        = subject
		self.state          = state
		self.typed_resource = typed_resource

	def generate(self) :
		"""
		Common entry point for the RDFa 1.0 and RDFa 1.1 versions; bifurcates based on the RDFa version, as retrieved from the state object.
		"""
		if self.state.rdfa_version >= "1.1" :
			self.generate_1_1()
		else :
			self.generate_1_0()

	def generate_1_1(self) :
		"""Generate the property object, 1.1 version"""

		#########################################################################
		# See if the target is _not_ a literal
		irirefs      = ("resource", "href", "src")
		noiri        = ("content", "datatype", "rel", "rev")
		notypediri   = ("content", "datatype", "rel", "rev", "about", "about_pruned")
		if has_one_of_attributes(self.node, irirefs) and not has_one_of_attributes(self.node, noiri) :
			# @href/@resource/@src takes the lead here...
			object = self.state.getResource(irirefs)
		elif self.node.hasAttribute("typeof") and not has_one_of_attributes(self.node, notypediri) and self.typed_resource != None :
				# a @typeof creates a special branch in case the typed resource was set during parsing
				object = self.typed_resource
		else :
			# We have to generate a literal

			# Get, if exists, the value of @datatype
			datatype = ''
			dtset    = False
			if self.node.hasAttribute("datatype") :
				dtset = True
				dt = self.node.getAttribute("datatype")
				if dt != "" :
					datatype = self.state.getURI("datatype")

			# Supress lange is set in case some elements explicitly want to supress the effect of language
			# There were discussions, for example, that the <time> element should do so. Although,
			# after all, this was reversed, the functionality is kept in the code in case another
			# element might need it...
			if self.state.lang != None and self.state.supress_lang == False :
				lang = self.state.lang
			else :
				lang = ''

			# The simple case: separate @content attribute
			if self.node.hasAttribute("content") :
				val = self.node.getAttribute("content")
				# Handling the automatic uri conversion case
				if dtset == False :
					object = Literal(val, lang=lang)
				else :
					object = self._create_Literal(val, datatype=datatype, lang=lang)
				# The value of datatype has been set, and the keyword parameters take care of the rest
			else :
				# see if there *is* a datatype (even if it is empty!)
				if dtset :
					if datatype == XMLLiteral :
						litval = self._get_XML_literal(self.node)
						object = Literal(litval,datatype=XMLLiteral)
					elif datatype == HTMLLiteral :
						# I am not sure why this hack is necessary, but otherwise an encoding error occurs
						# In Python3 all this should become moot, due to the unicode everywhere approach...
						if sys.version_info[0] >= 3 :
							object = Literal(self._get_HTML_literal(self.node), datatype=HTMLLiteral)
						else :
							litval = self._get_HTML_literal(self.node)
							o = Literal(litval, datatype=XMLLiteral)
							object = Literal(o, datatype=HTMLLiteral)
					else :
						object = self._create_Literal(self._get_literal(self.node), datatype=datatype, lang=lang)
				else :
					object = self._create_Literal(self._get_literal(self.node), lang=lang)

		if object != None :
			for prop in self.state.getURI("property") :
				if not isinstance(prop, BNode) :
					if self.node.hasAttribute("inlist") :
						self.state.add_to_list_mapping(prop, object)
					else :
						self.graph.add( (self.subject, prop, object) )
				else :
					self.state.options.add_warning(err_no_blank_node % "property", warning_type=IncorrectBlankNodeUsage, node=self.node.nodeName)

		# return

	def generate_1_0(self) :
		"""Generate the property object, 1.0 version"""

		#########################################################################
		# We have to generate a literal indeed.
		# Get, if exists, the value of @datatype
		datatype = ''
		dtset    = False
		if self.node.hasAttribute("datatype") :
			dtset = True
			dt = self.node.getAttribute("datatype")
			if dt != "" :
				datatype = self.state.getURI("datatype")

		if self.state.lang != None :
			lang = self.state.lang
		else :
			lang = ''

		# The simple case: separate @content attribute
		if self.node.hasAttribute("content") :
			val = self.node.getAttribute("content")
			# Handling the automatic uri conversion case
			if dtset == False :
				object = Literal(val, lang=lang)
			else :
				object = self._create_Literal(val, datatype=datatype, lang=lang)
			# The value of datatype has been set, and the keyword parameters take care of the rest
		else :
			# see if there *is* a datatype (even if it is empty!)
			if dtset :
				# yep. The Literal content is the pure text part of the current element:
				# We have to check whether the specified datatype is, in fact, an
				# explicit XML Literal
				if datatype == XMLLiteral :
					litval = self._get_XML_literal(self.node)
					object = Literal(litval,datatype=XMLLiteral)
				elif datatype == HTMLLiteral :
					# I am not sure why this hack is necessary, but otherwise an encoding error occurs
					# In Python3 all this should become moot, due to the unicode everywhere approach...
					if sys.version_info[0] >= 3 :
						object = Literal(self._get_HTML_literal(self.node), datatype=HTMLLiteral)
					else :
						litval = self._get_HTML_literal(self.node)
						o = Literal(litval, datatype=XMLLiteral)
						object = Literal(o, datatype=HTMLLiteral)
				else :
					object = self._create_Literal(self._get_literal(self.node), datatype=datatype, lang=lang)
			else :
				# no controlling @datatype. We have to see if there is markup in the contained
				# element
				if True in [ n.nodeType == self.node.ELEMENT_NODE for n in self.node.childNodes ] :
					# yep, and XML Literal should be generated
					object = self._create_Literal(self._get_XML_literal(self.node), datatype=XMLLiteral)
				else :
					# At this point, there might be entities in the string that are returned as real characters by the dom
					# implementation. That should be turned back
					object = self._create_Literal(self._get_literal(self.node), lang=lang)

		for prop in self.state.getURI("property") :
			if not isinstance(prop,BNode) :
				self.graph.add( (self.subject,prop,object) )
			else :
				self.state.options.add_warning(err_no_blank_node % "property", warning_type=IncorrectBlankNodeUsage, node=self.node.nodeName)

		# return

	######################################################################################################################################

	def _putBackEntities(self, str) :
		"""Put 'back' entities for the '&','<', and '>' characters, to produce a proper XML string.
		Used by the XML Literal extraction.
		@param str: string to be converted
		@return: string with entities
		@rtype: string
		"""
		return str.replace('&','&').replace('<','<').replace('>','>')

	def _get_literal(self, Pnode):
		"""
		Get (recursively) the full text from a DOM Node.

		@param Pnode: DOM Node
		@return: string
		"""
		rc = ""
		for node in Pnode.childNodes:
			if node.nodeType == node.TEXT_NODE:
				rc = rc + node.data
			elif node.nodeType == node.ELEMENT_NODE :
				rc = rc + self._get_literal(node)

		# The decision of the group in February 2008 is not to normalize the result by default.
		# This is reflected in the default value of the option

		if self.state.options.space_preserve :
			return rc
		else :
			return re.sub(r'(\r| |\n|\t)+'," ",rc).strip()
	# end getLiteral

	def _get_XML_literal(self, Pnode) :
		"""
		Get (recursively) the XML Literal content of a DOM Node.

		@param Pnode: DOM Node
		@return: string
		"""
		rc = ""
		for node in Pnode.childNodes:
			if node.nodeType == node.TEXT_NODE:
				rc = rc + self._putBackEntities(node.data)
			elif node.nodeType == node.ELEMENT_NODE :
				rc = rc + return_XML(self.state, node, base = False)
		return rc
	# end getXMLLiteral

	def _get_HTML_literal(self, Pnode) :
		"""
		Get (recursively) the XML Literal content of a DOM Node.

		@param Pnode: DOM Node
		@return: string
		"""
		rc = ""
		for node in Pnode.childNodes:
			if node.nodeType == node.TEXT_NODE:
				rc = rc + self._putBackEntities(node.data)
			elif node.nodeType == node.ELEMENT_NODE :
				rc = rc + return_XML(self.state, node, base = False, xmlns = False )
		return rc
	# end getXMLLiteral

	def _create_Literal(self, val, datatype = '', lang = '') :
		"""
		Create a literal, taking into account the datatype and language.
		@return: Literal
		"""
		if datatype == None or datatype == '' :
			return Literal(val, lang=lang)
		#elif datatype == ns_xsd["string"] :
		#	return Literal(val)
		else :
			# This is a bit convoluted... the default setup of rdflib does not gracefully react if the
			# datatype cannot properly be converted to Python. I have to copy and reuse some of the
			# rdflib code to get this working...
			# To make things worse: rdlib 3.1.0 does not handle the various xsd date types properly, ie,
			# the conversion function below will generate errors. Ie, the check should be skipped for those
			if ("%s" % datatype) in handled_time_types and rdflib.__version__ < "3.2.0" :
				convFunc = False
			else :
				convFunc = XSDToPython.get(datatype, None)
			if convFunc :
				try :
					pv = convFunc(val)
					# If we got there the literal value and its datatype match
				except :
					self.state.options.add_warning("Incompatible value (%s) and datatype (%s) in Literal definition." % (val, datatype), warning_type=IncorrectLiteral, node=self.node.nodeName)
			return Literal(val, datatype=datatype)


text:
//
//  main.m
//  PdTest02
//
//  Created by Richard Lawler on 11/22/10.

#import <UIKit/UIKit.h>

int main(int argc, char *argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    int retVal = UIApplicationMain(argc, argv, nil, nil);
    [pool release];
    return retVal;
}


text:
/*
 * This software is distributed under BSD 3-clause license (see LICENSE file).
 *
 * Authors: Thoralf Klein, Heiko Strathmann, Viktor Gal
 */

#include <shogun/labels/BinaryLabels.h>
#include <shogun/evaluation/ROCEvaluation.h>
#include <gtest/gtest.h>

using namespace shogun;

TEST(ROCEvaluation,one)
{
	index_t num_labels=10;
	auto gt=std::make_shared<BinaryLabels>(num_labels);
	auto roc=std::make_shared<ROCEvaluation>();

	for (index_t i=0; i<num_labels; i++)
	{
		float64_t l=i%2==0 ? -1 : 1;
		gt->set_value(l, i);
		gt->set_label(i, l);
	}

	float64_t auc=roc->evaluate(gt, gt);
	EXPECT_EQ(auc, 1);

}


text:
<?php namespace Projacked\Http\Controllers\Auth;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Projacked\Http\Controllers\Controller;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Facades\JWTAuth;

/**
 * Description of JWTController
 *
 * @author martijn
 */
class JWTController extends Controller {
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest', ['except' => 'logout']);
    }

    public function login(Request $request) {
        // grab credentials from the request
        $credentials = $request->only('email', 'password');

        try {
            // attempt to verify the credentials and create a token for the user
            if (! $token = JWTAuth::attempt($credentials)) {
                return new JsonResponse(['error' => 'invalid_credentials'], 401);
            }
        } catch (JWTException $e) {
            // something went wrong whilst attempting to encode the token
            return new JsonResponse(['error' => 'could_not_create_token'], 500);
        }
        $user = JWTAuth::authenticate($token);
        // all good so return the token
        return new JsonResponse(compact('token', 'user'));
    }
}


text:
from .basics import *

YOUTUBE_API= os.environ['YOUTUBE_API']

# pre: gets a keyword
# post: returns the resutlts it's search (in yt)
def ytSearch(keyword,limit=10):
    url = "https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults={}&order=relevance&q={}&type=video&key={}".format(limit, keyword, YOUTUBE_API)
    return getJson(url)

def getYtPlaylist(playlistId, limit=25):
    print('getting playlist https://www.youtube.com/playlist?list={}'.format(playlistId))
    url = 'https://www.googleapis.com/youtube/v3/playlistItems?part=snippet,contentDetails&maxResults={}&playlistId={}&key={}'.format(limit, playlistId, YOUTUBE_API)
    return getJson(url)

# search for videos in a specific channel
def ytSearchChannel(keyword, limit, channelId):
    url = "https://www.googleapis.com/youtube/v3/search?part=snippet&channelId={}&maxResults={}&order=relevance&q={}&safeSearch=strict&type=video&key={}".format(channelId, limit, keyword, YOUTUBE_API)
    return getJson(url)

def ytSearchPlaylists(keyword, limit=10):
    url = "https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults={}&order=relevance&q={}&type=playlist&key={}".format(limit, keyword, YOUTUBE_API)
    return getJson(url)['items']


text:
<?php

namespace MultiTenant\Error;

class DataScopeViolationException extends MultiTenantException {

/**
 * Constructor
 *
 * @param string $message If no message is given 'DataScopeViolation' will be the message
 * @param int $code Status code, defaults to 400
 */
	public function __construct($message = null, $code=null) {
		if (empty($message)) {
			$message = 'DataScopeViolation';
		}
		parent::__construct($message, $code);
	}

}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.gbif.registry.domain.ws;

import org.gbif.api.annotation.Generated;
import org.gbif.api.annotation.ParamName;
import org.gbif.api.model.registry.Endpoint;
import org.gbif.api.vocabulary.EndpointType;
import org.gbif.registry.domain.ws.util.LegacyResourceConstants;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.UUID;

import javax.annotation.Nullable;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Objects;
import com.google.common.base.Strings;

/**
 * Class used to create or update an Endpoint for legacy (GBRDS/IPT) API. Previously known as a
 * Service in the GBRDS. A set of HTTP Form parameters coming from a POST request are injected.
 * </br> Its fields are injected using the @ParamName. It is assumed the following parameters exist
 * in the HTTP request: 'resourceKey', 'description', 'descriptionLanguage', 'type',
 * 'accessPointURL'. </br> JAXB annotations allow the class to be converted into an XML document,
 * that gets included in the Response following a successful registration or update. @XmlElement is
 * used to specify element names that consumers of legacy services expect to find.
 */
@XmlRootElement(name = "service")
public class LegacyEndpoint extends Endpoint implements LegacyEntity {

  private static final Logger LOG = LoggerFactory.getLogger(LegacyEndpoint.class);

  // injected from HTTP form parameters
  private UUID datasetKey;

  /**
   * Set the endpoint's dataset key. Mandatory field, injected on both create and update requests.
   *
   * @param resourceKey dataset key as UUID
   */
  @ParamName(value = LegacyResourceConstants.RESOURCE_KEY_PARAM)
  public void setDatasetKey(String resourceKey) {
    try {
      datasetKey = UUID.fromString(Strings.nullToEmpty(resourceKey));
    } catch (IllegalArgumentException e) {
      LOG.error("Dataset key is not a valid UUID: {}", Strings.nullToEmpty(resourceKey));
    }
  }

  /**
   * Get the endpoint's dataset key.
   *
   * @return dataset key
   */
  @XmlElement(name = LegacyResourceConstants.RESOURCE_KEY_PARAM)
  @NotNull
  public UUID getDatasetKey() {
    return datasetKey;
  }

  /**
   * Set the endpoint description.
   *
   * @param description of the endpoint
   */
  @ParamName(value = LegacyResourceConstants.DESCRIPTION_PARAM)
  @Override
  public void setDescription(String description) {
    super.setDescription(validateField(description, 10));
  }

  /**
   * Get the endpoint description. This method is not used but it is needed otherwise this Object
   * can't be converted into an XML document via JAXB.
   *
   * @return description of the endpoint
   */
  @XmlElement(name = LegacyResourceConstants.DESCRIPTION_PARAM)
  @Nullable
  public String getEndpointDescription() {
    return getDescription();
  }

  /**
   * Set endpoint type. First, check if it is not null or empty. The incoming type always comes from
   * the GBRDS Service Type vocabulary. Note: this field is required, and the old web services would
   * throw 400 response if not found.
   *
   * @param type endpoint type
   */
  @ParamName(value = LegacyResourceConstants.TYPE_PARAM)
  public void setType(String type) {
    String injected = Strings.nullToEmpty(type);
    EndpointType lookup = EndpointType.fromString(injected);
    if (lookup == null) {
      // try to match some endpoints with their variant name
      if (injected.equalsIgnoreCase(LegacyResourceConstants.CHECKLIST_SERVICE_TYPE_1)
          || injected.equalsIgnoreCase(LegacyResourceConstants.CHECKLIST_SERVICE_TYPE_2)
          || injected.equalsIgnoreCase(LegacyResourceConstants.OCCURRENCE_SERVICE_TYPE_1)
          || injected.equalsIgnoreCase(LegacyResourceConstants.OCCURRENCE_SERVICE_TYPE_2)
          || injected.equalsIgnoreCase(LegacyResourceConstants.SAMPLING_EVENT_SERVICE_TYPE)) {
        setType(EndpointType.DWC_ARCHIVE);
      } else {
        LOG.error("Endpoint type could not be interpreted: {}", injected);
      }
    } else {
      setType(lookup);
    }
  }

  /**
   * Get endpoint type. This method is not used but it is needed otherwise this Object can't be
   * converted into an XML document via JAXB.
   *
   * @return primary contact type
   */
  @XmlElement(name = LegacyResourceConstants.TYPE_PARAM)
  @NotNull
  public EndpointType getEndpointType() {
    return getType();
  }

  /**
   * Set the endpoint URL.
   *
   * @param url of the endpoint
   */
  @ParamName(value = LegacyResourceConstants.ACCESS_POINT_URL_PARAM)
  public void setEndpointUrl(String url) {
    if (!Strings.isNullOrEmpty(url)) {
      try {
        URI uri = new URI(url);
        setUrl(uri);
      } catch (URISyntaxException e) {
        LOG.warn("Endpoint URL was invalid: {}", Strings.nullToEmpty(url));
      }
    }
  }

  /**
   * Get the endpoint URL. This method is not used but it is needed otherwise this Object can't be
   * converted into an XML document via JAXB.
   *
   * @return url of the endpoint
   */
  @XmlElement(name = LegacyResourceConstants.ACCESS_POINT_URL_PARAM)
  @NotNull
  public String getEndpointUrl() {
    if (getUrl() == null) {
      throw new IllegalStateException("Null is not acceptable");
    }
    return getUrl().toASCIIString();
  }

  @Generated
  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    if (!super.equals(o)) {
      return false;
    }
    LegacyEndpoint that = (LegacyEndpoint) o;
    return Objects.equal(datasetKey, that.datasetKey);
  }

  @Generated
  @Override
  public int hashCode() {
    return Objects.hashCode(super.hashCode(), datasetKey);
  }

  @Generated
  @Override
  public String toString() {
    return Objects.toStringHelper(this).add("datasetKey", datasetKey).toString();
  }
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Cerastium grandiflorum var. banaticum Rochel

### Remarks
null


text:
/*jslint browser: true, plusplus: true */
/*global jQuery, UWCanvas */
(function ($) {
    'use strict';

    var zoom_info = 'Zoom meeting access: When copying all content from a Canvas course, calendar events for Zoom meetings scheduled using the Zoom app in Canvas are also copied. To prevent students from accessing previous Zoom meeting links you can:

Delete individual calendar events containing previous Zoom meeting links, or

Select specific content to copy, and exclude all calendar events from being copied

',
        panopto_info = '
Access to Panopto recordings: When copying any Canvas content from one course to another, students in the new course will be granted access to the Panopto recordings in the original course. You may remove access to recordings.
';

    // Custom text for migrating course content
    $('#content').whenExists(function () {
        $(this).prepend(panopto_info);
        $(this).prepend(zoom_info);
    });
}(jQuery));


text:
package jenkins.model.lazy;

import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * {@link List} decorator that provides a number of binary-search related methods
 * by assuming that the array is sorted in the ascending order.
 *
 * @author Kohsuke Kawaguchi
 */
class SortedList<T extends Comparable<T>> extends AbstractList<T> {
    private List<T> data;

    SortedList(List<T> data) {
        this.data = new ArrayList<>(data);
        assert isSorted();
    }

    /**
     * Binary search to find the position of the given string.
     *
     * @return
     *      -(insertionPoint+1) if the exact string isn't found.
     *      That is, -1 means the probe would be inserted at the very beginning.
     */
    public int find(T probe) {
        return Collections.binarySearch(data, probe);
    }

    @Override
    public boolean contains(Object o) {
        return find((T) o) >= 0;
    }

    @Override
    public T get(int idx) {
        return data.get(idx);
    }

    @Override
    public int size() {
        return data.size();
    }

    @Override
    public T remove(int index) {
        return data.remove(index);
    }

    @Override
    public boolean remove(Object o) {
        return data.remove(o);
    }

    /**
     * Finds the index of the entry lower than v.
     *
     * @return
     *      return value will be in the [-1,size) range
     */
    public int lower(T v) {
        return Boundary.LOWER.apply(find(v));
    }

    /**
     * Finds the index of the entry greater than v.
     *
     * @return
     *      return value will be in the [0,size] range
     */
    public int higher(T v) {
        return Boundary.HIGHER.apply(find(v));
    }

    /**
     * Finds the index of the entry lower or equal to v.
     *
     * @return
     *      return value will be in the [-1,size) range
     */
    public int floor(T v) {
        return Boundary.FLOOR.apply(find(v));
    }

    /**
     * Finds the index of the entry greater or equal to v.
     *
     * @return
     *      return value will be in the [0,size] range
     */
    public int ceil(T v) {
        return Boundary.CEIL.apply(find(v));
    }

    public boolean isInRange(int idx) {
        return 0 <= idx && idx < data.size();
    }

    private boolean isSorted() {
        for (int i = 1; i < data.size(); i++) {
            if (data.get(i).compareTo(data.get(i - 1)) < 0) {
                return false;
            }
        }
        return true;
    }

}