text:
// Generates a valid image path for a supplied src
// @param imgSrc Base url image can be found at
// @param size Optional desired size (s, m)
// @param profile Should a null src be replaced with the default profile image?
// @return Valid url for the given src and size
var cleanImageURL = function (imgSrc, size) {
    var imageSrc = '';

    if (imgSrc === null) {
        imageSrc = null;
    }
    else {
        // Replace back-slashes, and remove tilda from beginning of string
        imageSrc = imgSrc.replace(/\\/g, "/").substr(1);
        if (size === 's' || size === 'm') {
            imageSrc = imageSrc.replace(/\.([^.]+)$/, '_' + size + '.$1');
        }
    }

    return imageSrc;
}

// Triggers the actual file input type click event
var fileInputClick = function (data, event) {
    $(event.currentTarget).siblings('.file-input').click();
}

// Determines if a value n is a number
// @param n Unitless value to check
// @return boolean true/false
// From: http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric/1830844#1830844
var isNumber = function (n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}

// View model for the dynamic edit profile form
// @param data Initial user data
function EditProfileViewModel(data) {
    // Stored profile data for the user
    self.displayName = ko.observable(data.displayName);
    self.sixWordBio = ko.observable(data.sixWordBio);
    self.imageURL = ko.observable(cleanImageURL(data.image));
    self.imageFilePath = ko.observable('');
    self.fullBio = ko.observable(data.fullBio);

    // Hold
    self.displayNameEdit = ko.observable(data.displayName);
    self.sixWordBioEdit = ko.observable(data.sixWordBio);
    self.fullBioEdit = ko.observable(data.fullBio);

    // Form states
    self.editProfileFormVisible = ko.observable(false);
    self.editProfileFormSubmitting = ko.observable(false);
    self.editProfileFormError = ko.observable(false);

    // Reset the form to current saved data
    self.resetFormDefaults = function () {
        self.displayNameEdit(self.displayName());
        self.sixWordBioEdit(self.sixWordBio());
        self.fullBioEdit(self.fullBio());
        self.imageFilePath('');
    }

    // Display the edit profile form
    self.showEditProfileForm = function () {
        self.editProfileFormVisible(true);

        // Ensure bio input height is correct
        $('#input-full-bio').trigger('autosize.resize');
    }

    // Clears the edit profile form and hide
    // @param data The current form data (Not used)
    // @param event The calling event object
    self.cancelEditProfile = function (data, event) {
        self.resetFormDefaults();

        self.editProfileFormVisible(false);
    }

    // Extracts file input value and saves path stripped of dummy value
    // @param data The current form data (Not used)
    // @param event The calling event object
    self.updateFilePath = function (data, event) {
        self.imageFilePath(event.currentTarget.value.replace(/C:\\fakepath\\/i, ''));
    }

    // Submits the manage story form and handles response
    // @param d The current form data
    // @param e The calling event object
    self.saveProfile = function (d, e) {
        e.preventDefault();
        self.editProfileFormSubmitting(true);
        //self.editProfileFormVisible(false);

        var form = $(e.target).parents('form');

        form.ajaxSubmit({
            clearForm: false,
            success: function (responseObj) {
                self.editProfileFormSubmitting(false);

                if (responseObj.DisplayName != null)
                    self.displayName(responseObj.DisplayName);

                if (responseObj.SixWordBio != null)
                    self.sixWordBio(responseObj.SixWordBio);

                if (responseObj.FullBio != null)
                    self.fullBio(responseObj.FullBio);

                if (responseObj.Image != null)
                    self.imageURL(cleanImageURL(responseObj.Image));

                //form[0].reset();
                self.resetFormDefaults();
                self.editProfileFormVisible(false);
            },
            error: function () {
                self.editProfileFormSubmitting(false);
                self.editProfileFormError(true);
                self.resetFormDefaults();
            }
        });

        return true;
    }

}

// Builds an object containing all information relating to an earning instance
// @param data JSON data representing the earning
function Earning(data, baseURL) {
    var self = this;

    // Earning Details
    self.earningID = data.EarningID;
    self.templateID = data.TemplateID;
    self.title = data.Title;
    self.earningIsAchievement = data.EarningIsAchievement;
    self.shareURL = baseURL + (self.earningIsAchievement ? '/Achievements/' : '/Quests/') + self.templateID + '#' + self.earningID;
    if (!self.earningIsAchievement) self.shareURL += "-1";

    // Player Details
    self.playerID = data.PlayerID;
    self.displayName = data.DisplayName;
    self.image = cleanImageURL(data.Image, 'm');
    self.playerImage = cleanImageURL(data.PlayerImage, null);
    if (self.playerImage === null) self.playerImage = '/Content/Images/Jpp/defaultProfileAvatar.png';
    self.earnedDate = new Date(parseInt(data.EarnedDate.substr(6))).toLocaleDateString();

    // Earning content
    self.contentPhoto = ko.observable(cleanImageURL(data.ContentPhoto, null));
    self.contentText = data.ContentText;
    self.contentURL = data.ContentURL;
    self.storyText = ko.observable(data.StoryText);
    self.storyPhoto = ko.observable(cleanImageURL(data.StoryPhoto, null));
    self.storyPhotoCSS = ko.computed(function () {
        return 'url(' + (self.storyPhoto() == null ? '#' : self.storyPhoto()) + ')';
    });

    // Story
    self.manageStoryFocus = ko.observable(false);
    self.manageStoryVisible = ko.observable(false);
    self.manageStoryVisibleListener = ko.computed(function () {
        if (self.manageStoryFocus())
            self.manageStoryVisible(true);
    }, self);
    self.storyImageFile = ko.observable('');

    // Comments
    self.comments = ko.observableArray();
    if (data.Comments !== null)
    {
        for (var i = 0; i < data.Comments.length; i++) {
            self.comments.push(new Comment(data.Comments[i]));
        }
    }

    // States
    self.submitting = false;
    self.manageStoryFormVisible = ko.observable(true);
    self.manageStoryLoading = ko.observable(false);
    self.manageStoryError = ko.observable(false);

    // Permissions
    self.commentsDisabled = data.CommentsDisabled;
    self.currentUserCanAddStory = data.CurrentUserCanAddStory;
    self.currentUserCanEditStory = data.CurrentUserCanEditStory;

    // Clears the form and hides the buttons
    self.cancelManageStory = function (data, event) {
        $(event.currentTarget).parents('.manage-story-form')[0].reset();
        self.storyImageFile('');
        self.manageStoryVisible(false);
    }

    // Extracts file input value and saves path stripped of dummy value
    self.updateFilePath = function (data, event) {
        self.storyImageFile(event.currentTarget.value.replace(/C:\\fakepath\\/i, ''));
    }

    // Submits the manage story form and handles response
    self.saveStory = function (d, e) {
        e.preventDefault();
        self.manageStoryLoading(true);
        self.manageStoryFormVisible(false);

        var form = $(e.target).parents('form');

        form.ajaxSubmit({
            clearForm: true,
            success: function (responseObj) {
                self.manageStoryLoading(false);

                // Update view with story text
                if (responseObj.StoryText != null)
                    self.storyText(responseObj.StoryText);
                // Update view with story image
                if (responseObj.StoryImage != null)
                    self.storyPhoto(cleanImageURL(responseObj.StoryImage, null));
            },
            error: function () {
                self.manageStoryLoading(false);
                self.manageStoryError(true);
            }
        });

        return true;
    }

    // Sends a request to add a comment and adds to array if successful
    self.addComment = function (d, e) {
        // Submit when enter key is pressed without shift key
        if (e.keyCode == 13) {

            // Submit if shift key isn't currently held
            if (!e.shiftKey && !self.submitting) {
                self.submitting = true;
                var form = $(e.target).parents('form');
                form.children('input[name=text]').prop('disabled', true);

                form.ajaxSubmit({
                    clearForm: true,
                    success: function (responseObj) {
                        // If comment was successfully added, add it in the view
                        self.comments.push(new Comment(responseObj));
                        form.children('input[name=text]').prop('disabled', false);

                        // Enable submissions
                        self.submitting = false;
                    },
                    error: function () {
                        //TODO: Highlight input field
                        // Enable submissions
                        self.submitting = false;
                        console.log("ERROR: Comment Submission");
                    }

                })
            }
            return false;
        }

        // Allow key inputs
        return true;
    }

}

// Builds an empty earning object
function EmptyEarning() {
    var self = this;

    // Earning Details
    self.earningID = 0;
    self.templateID = 0;
    self.title = "";
    self.earningIsAchievement = false;
    self.shareURL = "";
    self.image = "";

    // Player Details
    self.playerID = 0;
    self.displayName = "";
    self.playerImage = '/Content/Images/Jpp/defaultProfileAvatar.png';
    self.earnedDate = 0;

    // Earning content
    self.contentPhoto = null;
    self.contentText = "";
    self.contentURL = "";
    self.storyText = ko.observable(false);
    self.storyPhoto = ko.observable(false);
    self.storyPhotoCSS = function () { return ''; }

    // Comments
    self.comments = ko.observableArray();

    // States
    self.submitting = false;
    self.manageStoryLoading = false;
    self.manageStoryError = false;
    self.manageStoryFormVisible = false;
    self.cancelManageStory = function () { return false; }
    self.saveStory = function () { return false; }
    self.updateFilePath = function () { return false; }
    self.fileInputClick = function () { return false; }

    // Permissions
    self.commentsDisabled = true;
    self.currentUserCanAddStory = false;
    self.currentUserCanEditStory = false;

}

// Data and functions for a comment
// @param data Initial data to build a comment with
function Comment(data) {
    var self = this;
    self.commentID = data.ID;
    self.deleted = ko.observable(data.Deleted);
    self.playerID = ko.observable(data.PlayerID);
    self.playerDisplayName = ko.observable(data.DisplayName);
    self.playerImage = ko.observable(cleanImageURL(data.PlayerImage, null));
    if (self.playerImage() === null) self.playerImage('/Content/Images/Jpp/defaultProfileAvatar.png');
    self.text = ko.observable(data.Text);
    self.currentUserCanDelete = ko.observable(data.CurrentUserCanDelete);
    self.currentUserCanEdit = ko.observable(data.CurrentUserCanEdit);
    self.editing = ko.observable(false);
    self.confirmDeleteState = ko.observable(false);
    self.commentDate = new Date(parseInt(data.CommentDate.substr(6))).toLocaleString();

    // Switches editing mode on call
    self.invertEditing = function () {
        self.editing(!self.editing());
        return true;
    }

    self.deleteComment = function (d, e) {
        e.stopPropagation(); // Prevent click event from jumping into event below
        self.confirmDeleteState(true); // Show confirm

        $(document).on('click.deleteComment', function (e) {
            var container = $('.confirmDelete');
            // Check for container and any elements inside container
            if (!container.is(e.target) && container.has(e.target).length == 0) {
                self.confirmDeleteState(false);
            }

            // Remove this event
            $(document).off('click.deleteComment');
        });
    }

    // Sends a request to delete a comment and removes comment data if successful
    self.confirmDelete = function (d, e) {
        var form = $(e.target).parents('form');

        form.ajaxSubmit({
            // TODO: Clear text faster
            clearForm: true,
            success: function (responseObj) {
                // Remove comment on success
                self.deleted(responseObj.Deleted);
                self.playerID(responseObj.PlayerID);
                self.playerDisplayName(responseObj.DisplayName);
                self.playerImage(null);
                self.text(responseObj.Text);
                self.currentUserCanDelete(responseObj.CurrentUserCanDelete);
                self.currentUserCanEdit(responseObj.CurrentUserCanEdit);
            },
            error: function () {
                //TODO: alert user
                console.log("ERROR: Comment deletion");
            }
        })
    }

    // Sends a request to edit a comment and updates comment if successful
    self.editComment = function (d, e) {
        var form = $(e.target).parents('form');
        self.text(form.children('input[name=text]').val());
        self.invertEditing();

        form.ajaxSubmit({
            clearForm: false,
            success: function (responseObj) {
                // Remove comment on success
                self.text(responseObj.Text);
            },
            error: function () {
                //TODO: alert user
                console.log("ERROR: Comment editing");
            }
        })
    }
}

// ViewModel for the Earning List
// @param settings JSON list of options for data retrieval
function EarningListViewModel(settings) {
    var self = this;

    // Options
    self.loadInterval = 6;
    self.loadCount = 0;
    self.scrollBuffer = 400;
    self.playerID = settings.playerID;
    self.achievementID = settings.achievementID;
    self.questID = settings.questID;
    self.friendsOf = ko.observable(null);
    self.isLoading = ko.observable(false);
    self.atEnd = ko.observable(false);
    self.isEmpty = ko.observable(false);
    self.shareURLBase = location.protocol + '//' + location.host;

    // Dynamic data
    self.earnings = ko.observableArray();

    // Functions
    // Retrieves earning data from server and appends it to the earning array
    self.loadEarnings = function () {
        // Only show the loading spinner if there is probably more stuff to load
        if (self.loadCount % self.loadInterval == 0) {
            self.isLoading(true);
        }
        else {
            self.atEnd(true);
        }

        // Ajax request
        $.get("/JSON/Earnings", {
                id: self.playerID,
                achievementID: self.achievementID,
                questID: self.questID,
                start: self.loadCount,
                count: self.loadInterval,
                friendsOf: self.friendsOf
        }).done(function (data) {

            var dataCount = data.Earnings.length;

            // Update loadCount
            self.loadCount += dataCount;

            if (self.loadCount === 0) {
                self.isLoading(false);
                self.isEmpty(true);
                return;
            }

            // Build earnings
            for (var i = 0; i < dataCount; i++) {
                self.earnings.push(new Earning(data.Earnings[i], self.shareURLBase));
            }

            // Bind scroll and textarea autoresize
            if (dataCount > 0) {
                $(window).bind('scroll', self.bindScroll);
                $('.story-text').autosize();
            }
            else {
                self.atEnd(true);
            }

            self.isLoading(false);
        });
    };

    // Callback for scroll event to handle additional loading
    //TODO: Bind scroll to parent to support multiple lists
    self.bindScroll = function () {
        // Check for a scroll to the bottom of the timelineFeed - scrollBuffer
        if ($(window).scrollTop() + $(window).height() >= $('.earningFeed')[0].scrollHeight + $('.earningFeed').offset().top - self.scrollBuffer) {
            $(window).unbind('scroll');
            self.loadEarnings();
        }
    };

    self.toggleFriends = function () {
        self.toggleFriendsOf(true);
    }

    self.togglePublic = function () {
        self.toggleFriendsOf(false);
    }

    // Toggle data to load into the list
    // @param toggle Boolean toggle for friendsOf filter
    self.toggleFriendsOf = function (toggle) {

        if (self.friendsOf() == toggle)
            return;

        self.friendsOf(toggle);
        self.resetList();
        self.loadEarnings();
    }

    // Clear loaded data and reset load count
    self.resetList = function () {
        self.loadCount = 0;
        self.isEmpty(false);
        self.atEnd(false);
        self.earnings.removeAll();
    }

    // Initial load
    //self.loadEarnings();
    self.togglePublic();
}

// ViewModel for fullscreen earning
function ShareEarningViewModel() {
    var self = this;

    // Earning object that will be displayed to user
    self.currentEarning = ko.observable(new EmptyEarning());
    // Vertical offset for earning
    self.scrolledHeight = ko.observable(0);

    self.fullscreenEarningVisible = ko.observable(false);
    self.loading = ko.observable(false);
    self.shareURLBase = location.protocol + '//' + location.host;

    self.loadEarning = function (eID, eIsA) {

        // Bind escape key to close fullscreen view
        $(document).on('keydown.escapeFullscreen', function (e) {
            if (e.keyCode == 27)
                self.closeFullscreenEarning();
        });

        self.fullscreenEarningVisible(true);
        self.loading(true);

        // Ajax request
        $.get("/JSON/Earning", {
            id: eID,
            isAchievement: eIsA
        }).done(function (data) {

            // TODO: Handle errors
            // 0. Invalid earning ID for URL
            // 1. Invalid permissions

            // Save into currentEarning field to update view
            self.currentEarning(new Earning(data, self.shareURLBase));

            self.loading(false);
        });
    }

    // On click event for 'X' and grey area
    self.closeFullscreenEarning = function () {
        // Clear hash
        var scrollV, scrollH, loc = window.location;
        if ("pushState" in history)
            history.pushState("", document.title, loc.pathname + loc.search);
        else {
            // Prevent scrolling by storing the page's current scroll offset
            scrollV = document.body.scrollTop;
            scrollH = document.body.scrollLeft;

            loc.hash = "";

            // Restore the scroll offset, should be flicker free
            document.body.scrollTop = scrollV;
            document.body.scrollLeft = scrollH;
        }

        // Hide earning
        self.fullscreenEarningVisible(false);
        $(document).off('keydown.escapeFullscreen');
    }

    // Window listener for hash changes
    self.bindHashChange = function () {
        // Listen for hash change
        $(window).on('hashchange', function () {

            if( !self.checkHash() )
                self.closeFullscreenEarning();
        });
    }

    // Validates any change in window hash
    self.checkHash = function () {
        if (location.hash.length > 1) {
            var eIsAchievement = true;
            var hash = location.hash.substring(1);
            var values = hash.split('-');
            if (values.length < 1) return false;

            // On change, validate hash value is a number
            if (isNumber(values[0])) {
                // If a second value of 1 was passed, the earning is a quest
                if (values.length > 1 && isNumber(values[1]) && values[1] == 1) eIsAchievement = false;

                // Move view to current scrolled height
                var scrollAmount = $("body").scrollTop();
                self.scrolledHeight(scrollAmount);

                // Load new earning
                self.loadEarning(values[0], eIsAchievement);

                return true;
            }
        }
    }

    self.checkHash();
    self.bindHashChange();
}

// Containing object for achievement list items
function Achievement(data) {
    var self = this;
    self.ID = data.ID;
    self.image = cleanImageURL(data.Image, 'm');
    self.pointsCreate = data.PointsCreate;
    self.pointsExplore = data.PointsExplore;
    self.pointsLearn = data.PointsLearn;
    self.pointsSocialize = data.PointsSocialize;
    self.title = data.Title;
    self.tokenizedTitle = self.title.toLowerCase().match(/\S+/g);
    self.visible = ko.observable(true);
}

// View Model for the achievement list
// @param settings JSON list of options for data retrieval
function AchievementListViewModel(settings) {
    var self = this;

    //
    // Options
    //

    // Base component of the query string
    self.queryStringBase = '/JSON/Achievements';
    // Lists user may select to query new data
    self.lists = ['All', 'Earned', 'Locked'];
    // Every option for list order
    self.orderOptions = [{ name: 'A-Z', value: 'az' }, { name: 'Z-A', value: 'za' }];
    // Passed in id of the currently logged user
    self.playerID = settings.playerID;
    // The currently selected list
    self.activeList = ko.observable();
    // User-entered string to filter
    self.searchText = ko.observable('');
    // Boolean flag for loading state
    self.loading = ko.observable(false);
    // Boolean flag for empty state
    self.empty = ko.observable(false);

    //
    // Data
    //

    // All achievement data returned from query
    self.listItems = ko.observableArray();
    // Filtered achievement data to display
    self.displayListItems = ko.computed(function () {
        // Filter checkbox options
        var itemArray = ko.utils.arrayFilter(self.listItems(), function (item) {
            return self.checkboxFilter(item);
        });

        // Filter search text (tokenized)
        var filterArray = self.searchText().toLowerCase().match(/\S+/g);
        if (filterArray !== null && filterArray.length > 0) {
            // Filter search text
            itemArray = ko.utils.arrayFilter(itemArray, function (item) {

                // Get tokenized title
                var tokenArray = item.tokenizedTitle;

                // Loop through each token
                for (var i = 0; i < tokenArray.length; i++) {

                    // If the search text is longer than the item title we don't have a match
                    if ((tokenArray.length - i) >= filterArray.length) {

                        var dummyCheck = true;

                        // The first j-1 tokens must match the first j-1 tokens starting at index i
                        for (var j = 0; j < filterArray.length-1; j++) {
                            if (filterArray[j] !== tokenArray[i + j]) {
                                dummyCheck = false;
                            }
                        }

                        // We only want to return true here, as a later token in the same title could match
                        if (dummyCheck && self.stringBeginsWith(filterArray[filterArray.length - 1], tokenArray[i + filterArray.length - 1]))
                            return true;
                    }

                }
                return false;

            });
        }

        //self.filterAlphabetical();

        // Display empty message if there are no items
        self.empty(itemArray.length <= 0);

        return itemArray;
    }, self);

    // List Filters
    self.listType = ko.observable('all');
    // List toggles may be null, true, or false
    self.listToggle = null;

    // Quad Filters
    self.createChecked = ko.observable(true);
    self.exploreChecked = ko.observable(true);
    self.learnChecked = ko.observable(true);
    self.socializeChecked = ko.observable(true);

    // Alphabetical Ordering
    /*
    self.order = ko.observable('az');
    self.order.subscribe(function (newData) {
        self.filterAlphabetical();
    }, self);
    */

    //
    // Functions
    //

    // Checks an item to determine if it should be shown
    // @param item The item to check
    // @returns true if item should be shown
    // @returns false if item should be removed
    self.checkboxFilter = function (item) {
        if (self.createChecked() && item.pointsCreate > 0) {
            return true;
        }
        else if (self.exploreChecked() && item.pointsExplore > 0) {
            return true;
        }
        else if (self.learnChecked() && item.pointsLearn > 0) {
            return true;
        }
        else if (self.socializeChecked() && item.pointsSocialize > 0) {
            return true;
        }
        else {
            return false;
        }
    }

    // Retrieves achievement data from server and appends it to the earning array
    // TODO: Load 28 and then the rest to speed up load
    self.loadItems = function () {

        // Clear current list
        self.listItems.removeAll();

        // Show loading spinner
        self.loading(true);

        // Hide empty message
        self.empty(false);

        // Ajax request
        $.get(self.queryStringBase, {
            userID: self.playerID,
            //start: 0,
            //count: 6,
            achievementsEarned: self.listToggle
        }).done(function (data) {

            var dataCount = data.Achievements.length;

            // Build new achievements
            for (var i = 0; i < dataCount; i++) {
                self.listItems.push(new Achievement(data.Achievements[i]));
            }

            // Ensure alphabetical ordering
            self.filterAtoZ();

            // Empty message
            if (dataCount == 0) {
                self.empty(true);
            }

            // Hide loading icon
            self.loading(false);
        });
    };

    // Listens for a change in listType and invokes loadItems
    self.listChange = ko.computed(function () {
        if (self.listType() === 'all') self.listToggle = null;
        else if (self.listType() === 'achieved') self.listToggle = true;
        else self.listToggle = false;

        self.loadItems();
        return true;
    }, self);

    // Filters items based on selected ordering
    self.filterAlphabetical = function () {
        if (self.order() === 'az') self.filterAtoZ();
        else self.filterZtoA();
    }

    // Filters items A to Z
    self.filterAtoZ = function () {
        self.listItems.sort(function (left, right) { return left.title == right.title ? 0 : (left.title < right.title ? -1 : 1) });
    }

    // Filters items Z to A
    self.filterZtoA = function () {
        self.listItems.sort(function (left, right) { return left.title == right.title ? 0 : (right.title < left.title ? -1 : 1) });
    }

    // Checks a string to see if it begins with another
    self.stringBeginsWith = function (needle, haystack) {
        return (haystack.substr(0, needle.length) == needle);
    }

    // Initial load
    //self.loadItems();
}

// Containing object for quest list items
function Quest(data) {
    var self = this;
    self.ID = data.ID;
    self.image = cleanImageURL(data.Image, 'm');
    self.title = data.Title;
    self.tokenizedTitle = self.title.toLowerCase().match(/\S+/g);
}

// View Model for the quest list
// @param settings JSON list of options for data retrieval
function QuestListViewModel(settings) {
    var self = this;

    //
    // Options
    //

    // Base component of the query string
    self.queryStringBase = '/JSON/Quests';
    // List Filters
    self.listType = ko.observable("0");
    // List toggles may be null, true, or false
    self.listToggle = null;
    // Every option for list order
    self.orderOptions = [{ name: 'A-Z', value: 'az' }, { name: 'Z-A', value: 'za' }];
    // Passed in id of the currently logged user
    self.playerID = settings.playerID;
    // The currently selected list
    self.activeList = ko.observable();
    // User-entered string to filter
    self.searchText = ko.observable('');
    // Boolean flag for loading state
    self.loading = ko.observable(false);
    // Boolean flag for empty state
    self.empty = ko.observable(false);

    //
    // Data
    //

    // All achievement data returned from query
    self.listItems = ko.observableArray();
    // Filtered achievement data to display
    self.displayListItems = ko.computed(function () {
        // Filter checkbox options
        var itemArray = ko.utils.arrayFilter(self.listItems(), function (item) {
            return self.checkboxFilter(item);
        });

        // Filter search text (tokenized)
        var filterArray = self.searchText().toLowerCase().match(/\S+/g);
        if (filterArray !== null && filterArray.length > 0) {
            // Filter search text
            itemArray = ko.utils.arrayFilter(itemArray, function (item) {

                // Get tokenized title
                var tokenArray = item.tokenizedTitle;

                // Loop through each token
                for (var i = 0; i < tokenArray.length; i++) {

                    // If the search text is longer than the item title we don't have a match
                    if ((tokenArray.length - i) >= filterArray.length) {

                        var dummyCheck = true;

                        // The first j-1 tokens must match the first j-1 tokens starting at index i
                        for (var j = 0; j < filterArray.length - 1; j++) {
                            if (filterArray[j] !== tokenArray[i + j]) {
                                dummyCheck = false;
                            }
                        }

                        // We only want to return true here, as a later token in the same title could match
                        if (dummyCheck && self.stringBeginsWith(filterArray[filterArray.length - 1], tokenArray[i + filterArray.length - 1]))
                            return true;
                    }

                }
                return false;

            });
        }

        // Display empty message if there are no items
        self.empty(itemArray.length <= 0);

        return itemArray;
    }, self);

    // Quad Filters
    self.systemChecked = ko.observable(true);
    self.communityChecked = ko.observable(true);

    // Alphabetical Ordering
    self.order = ko.observable('az');
    self.order.subscribe(function (newData) {
        self.filterAlphabetical();
    }, self);

    //
    // Functions
    //

    // Checks an item to determine if it should be shown
    // @param item The item to check
    // @returns true if item should be shown
    // @returns false if item should be removed
    self.checkboxFilter = function (item) {
        /*
        if (self.systemChecked() && item.system) {
            return true;
        }
        else if (self.communityChecked() && item.community) {
            return true;
        }
        else {
            return false;
        }
        */

        return true;
    }

    // Retrieves achievement data from server and appends it to the earning array
    // TODO: Load 28 and then the rest to speed up load
    self.loadItems = function () {

        // Clear current list
        self.listItems.removeAll();

        // Show loading spinner
        self.loading(true);

        // Hide empty message
        self.empty(false);

        var queryOptions = {
            userID: self.playerID
            //start: 0,
            //count: self.loadInterval
        }
        switch (self.listToggle) {
            // Completed Quests
            case 1:
                queryOptions.completedQuests = true;
                break;
            // Partially Competed Quests
            case 2:
                queryOptions.partiallyCompletedQuests = true;
                break;
            // Incomplete Quests
            case 3:
                queryOptions.incompleteQuests = true;
                break;
            // Tracked Quests
            case 4:
                queryOptions.trackedQuests = true;
                break;
            // User Generated Quests
            case 5:
                queryOptions.userGeneratedQuests = true;
                break;
            // No query; grab all
            default:
                break;
        }

        // Ajax request
        $.get(self.queryStringBase, queryOptions).done(function (data) {

            var dataCount = data.Quests.length;

            // Build new achievements
            for (var i = 0; i < dataCount; i++) {
                self.listItems.push(new Quest(data.Quests[i]));
            }

            // Ensure alphabetical ordering
            self.filterAlphabetical();

            // Empty message
            if (dataCount == 0) {
                self.empty(true);
            }

            // Hide loading icon
            self.loading(false);
        });
    };

    // Listens for a change in listType and invokes loadItems
    self.listChange = ko.computed(function () {
        /*if (self.listType() === 'all') self.listToggle = 1;
        else if (self.listType() === 'completed') self.listToggle = 2;
        else self.listToggle = 3;*/

        self.listToggle = parseInt(self.listType());

        self.loadItems();
        return true;
    }, self);

    // Filters items based on selected ordering
    self.filterAlphabetical = function () {
        if (self.order() === 'az') self.filterAtoZ();
        else self.filterZtoA();
    }

    // Filters items A to Z
    self.filterAtoZ = function () {
        self.listItems.sort(function (left, right) { return left.title == right.title ? 0 : (left.title < right.title ? -1 : 1) });
    }

    // Filters items Z to A
    self.filterZtoA = function () {
        self.listItems.sort(function (left, right) { return left.title == right.title ? 0 : (right.title < left.title ? -1 : 1) });
    }

    // Checks a string to see if it begins with another
    self.stringBeginsWith = function (needle, haystack) {
        return (haystack.substr(0, needle.length) == needle);
    }

    // Initial load
    //self.loadList('All');
}

// Containing object for player list items
function Player(data) {
    var self = this;
    self.ID = data.ID;
    self.displayName = data.DisplayName;
    self.firstName = data.FirstName;
    self.middleName = data.MiddleName;
    self.lastName = data.LastName;
    self.image = cleanImageURL(data.Image, null);
    if (self.image === null) self.image = '/Content/Images/Jpp/defaultProfileAvatar.png';
}

// View Model for the player list
// @param settings JSON list of options for data retrieval
function PlayerListViewModel(settings) {
    var self = this;

    //
    // Options
    //

    // Base component of the query string
    self.queryStringBase = '/JSON/Players';
    // Lists user may select to query new data
    self.lists = ['All', 'Friends', 'Non-Friends'];
    // List toggles may be null, true, or false
    self.listToggle = true;
    // List Filters
    self.listType = ko.observable('friends');
    // Every option for list order
    self.orderOptions = [{ name: 'A-Z', value: 'az' }, { name: 'Z-A', value: 'za' }];
    // Passed in id of the currently logged user
    self.playerID = settings.playerID;
    // The currently selected list
    self.activeList = ko.observable();
    // User-entered string to filter
    self.searchText = ko.observable('');
    // Boolean flag for loading state
    self.loading = ko.observable(false);
    // Boolean flag for empty state
    self.empty = ko.observable(false);

    //
    // Data
    //

    // All data returned from query
    self.listItems = ko.observableArray();
    // Filtered data to display
    self.displayListItems = ko.computed(function () {
        // Filter checkbox options
        var itemArray = ko.utils.arrayFilter(self.listItems(), function (item) {
            return self.checkboxFilter(item);
        });

        // Filter search text
        var filter = self.searchText().toLowerCase();
        if (filter) {
            // Filter search text
            itemArray = ko.utils.arrayFilter(itemArray, function (item) {
                return  self.stringBeginsWith(filter, item.displayName.toLowerCase()) ||
                        self.stringBeginsWith(filter, item.firstName.toLowerCase()) ||
                        self.stringBeginsWith(filter, item.lastName.toLowerCase());
            });
        }

        // Display empty message if there are no items
        self.empty(itemArray.length <= 0);

        return itemArray;
    }, self);

    // Live Filters
    self.systemChecked = ko.observable(true);
    self.communityChecked = ko.observable(true);

    // Alphabetical Ordering
    self.order = ko.observable('az');
    self.order.subscribe(function (newData) {
        self.filterAlphabetical();
    }, self);

    //
    // Functions
    //

    // Checks an item to determine if it should be shown
    // @param item The item to check
    // @returns true if item should be shown
    // @returns false if item should be removed
    self.checkboxFilter = function (item) {
        /*
        if (self.systemChecked() && item.system) {
            return true;
        }
        else if (self.communityChecked() && item.community) {
            return true;
        }
        else {
            return false;
        }
        */

        return true;
    }

    // Retrieves achievement data from server and appends it to the earning array
    // TODO: Load 28 and then the rest to speed up load
    self.loadItems = function () {

        // Clear current list
        self.listItems.removeAll();

        // Show loading spinner
        self.loading(true);

        // Hide empty message
        self.empty(false);

        // Ajax request
        $.get(self.queryStringBase, {
            userID: self.playerID,
            //start: 0,
            //count: 6,
            friendsWith: self.listToggle
        }).done(function (data) {

            var dataCount = data.People.length;

            // Build new achievements
            for (var i = 0; i < dataCount; i++) {
                self.listItems.push(new Player(data.People[i]));
            }

            // Ensure alphabetical ordering
            self.filterAlphabetical();

            // Empty message
            if (dataCount == 0) {
                self.empty(true);
            }

            // Hide loading icon
            self.loading(false);
        });
    };

    // Listens for a change in listType and invokes loadItems
    self.listChange = ko.computed(function () {
        if (self.listType() === 'everyone') self.listToggle = null;
        else if (self.listType() === 'friends') self.listToggle = true;
        else self.listToggle = false;

        self.loadItems();
        return true;
    }, self);

    // Filters items based on selected ordering
    self.filterAlphabetical = function () {
        if (self.order() === 'az') self.filterAtoZ();
        else self.filterZtoA();
    }

    // Filters items A to Z
    self.filterAtoZ = function () {
        self.listItems.sort(function (left, right) { return left.displayName == right.displayName ? 0 : (left.displayName < right.displayName ? -1 : 1) });
    }

    // Filters items Z to A
    self.filterZtoA = function () {
        self.listItems.sort(function (left, right) { return left.displayName == right.displayName ? 0 : (right.displayName < left.displayName ? -1 : 1) });
    }

    // Checks a string to see if it begins with another
    self.stringBeginsWith = function (needle, haystack) {
        return (haystack.substr(0, needle.length) == needle);
    }

    // Initial load
    //self.loadList('Friends');
}

// View Model for paged profile lists
// @param type Type of list (0=Quests,1=Achievements,2=Players)
// @param settings JSON list of settings
function ProfileListViewModel(type, settings) {
    var self = this;

    // ID of the profile loaded
    self.playerID = settings.playerID;

    self.total = ko.observable(0);
    self.loadInterval = 12;
    self.loadCount = 0;
    self.pageCount = ko.observable(0);
    self.pageItemCount = self.loadInterval;
    self.currentPage = ko.observable(0);
    self.loading = ko.observable(false);
    self.empty = ko.observable(false);

    self.listItems = ko.observableArray();
    // Filtered achievement data to display
    self.displayListItems = ko.computed(function () {
        // Filter checkbox options
        //var itemArray = ko.utils.arrayFilter(self.listItems(), function (item) {
            //return self.checkboxFilter(item);
        //});

        var indexAtPage = (self.currentPage() - 1) * self.pageItemCount;
        var itemArray = self.listItems().slice(indexAtPage, indexAtPage + self.pageItemCount);

        // Filter search text (tokenized)
        //var filterArray = self.searchText().toLowerCase().match(/\S+/g);
        /*if (filterArray !== null && filterArray.length > 0) {
            // Filter search text
            itemArray = ko.utils.arrayFilter(itemArray, function (item) {

                // Get tokenized title
                var tokenArray = item.tokenizedTitle;

                // Loop through each token
                for (var i = 0; i < tokenArray.length; i++) {

                    // If the search text is longer than the item title we don't have a match
                    if ((tokenArray.length - i) >= filterArray.length) {

                        var dummyCheck = true;

                        // The first j-1 tokens must match the first j-1 tokens starting at index i
                        for (var j = 0; j < filterArray.length - 1; j++) {
                            if (filterArray[j] !== tokenArray[i + j]) {
                                dummyCheck = false;
                            }
                        }

                        // We only want to return true here, as a later token in the same title could match
                        if (dummyCheck && self.stringBeginsWith(filterArray[filterArray.length - 1], tokenArray[i + filterArray.length - 1]))
                            return true;
                    }

                }
                return false;

            });
        }*/

        //self.filterAlphabetical();

        // Display empty message if there are no items
        //self.empty(itemArray.length <= 0);

        return itemArray;
    }, self);

    // Save our query type
    self.queryStringBase = '';
    self.queryOptions = {
        userID: self.playerID
        //start: 0,
        //count: self.loadInterval
    }
    self.type = type;
    self.objType;
    switch (self.type) {
        case 0: // Quests
            self.queryStringBase = '/JSON/Quests';
            self.queryOptions.completedQuests = true;
            self.objType = Quest;
            break;
        case 1: // Achievements
            self.queryStringBase = '/JSON/Achievements';
            self.queryOptions.achievementsEarned = true;
            self.objType = Achievement;
            break;
        case 2: // Players
            self.queryStringBase = '/JSON/Players';
            self.queryOptions.friendsWith = true;
            self.objType = Player;
            break;
        default: // Quests
            self.queryStringBase = '/JSON/Quests';
            self.queryOptions.completedQuests = true;
            self.objType = Quest;
            break;
    }

    // Loads list data from server and appends it to the list
    self.loadItems = function () {

        // Show loading spinner
        self.loading(true);

        // Hide empty message
        self.empty(false);

        // Ajax request
        $.get(self.queryStringBase, self.queryOptions).done(function (data) {

            // Determine which object to access in returned JSON
            var dataList;
            switch (self.type) {
                case 0: // Quests
                    dataList = data.Quests;
                    break;
                case 1: // Achievements
                    dataList = data.Achievements;
                    break;
                case 2: // Players
                    dataList = data.People;
                    break;
            }

            self.total(data.Total);

            // Build new items
            for (var i = 0; i < self.total(); i++) {
                self.listItems.push(new self.objType(dataList[i]));
            }

            // Ensure alphabetical ordering
            self.filterAtoZ();

            // Hide loading icon
            self.loading(false);

            // Display empty message
            if (self.total() <= 0) {
                self.empty(true);
                return;
            }

            self.pageCount(Math.ceil(self.total() / self.pageItemCount));
            self.currentPage(1);
        });

    };

    self.nextPage = function () {
        self.currentPage(self.currentPage() + 1);
        if (self.currentPage() > self.pageCount())
            self.currentPage(1);
    }

    self.prevPage = function() {
        self.currentPage(self.currentPage() - 1);
        if (self.currentPage() < 1)
            self.currentPage(self.pageCount());
    }

    // Filters items A to Z
    self.filterAtoZ = function () {
        self.listItems.sort(function (left, right) { return left.title == right.title ? 0 : (left.title < right.title ? -1 : 1) });
    }

    self.loadItems();
}


text:
package com.hackfmi.sport.squad.service;

import java.util.List;

import org.springframework.data.domain.Sort;

import com.hackfmi.sport.squad.dto.GameFieldDto;

/**
 * Created by inakov on 14-11-8.
 */
public interface GameFieldService {
	public List<GameFieldDto> getGameFieldsPage(String city, int page, int size, Sort sort);
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>svfilter</title>
    <link rel="stylesheet" type="text/css" href="csound.css" />
    <meta name="generator" content="DocBook XSL Stylesheets V1.78.1" />
    <link rel="home" href="index.html" title="Manuel de référence canonique de Csound" />
    <link rel="up" href="OpcodesTop.html" title="Opcodes et opérateurs de l'orchestre" />
    <link rel="prev" href="sumarray.html" title="sumarray" />
    <link rel="next" href="syncgrain.html" title="syncgrain" />

          svfilter

          Précédent
          Opcodes et opérateurs de l'orchestre
           Suivant

          svfilter

svfilter —
      Un filtre à résonance du second ordre, avec sortie passe-bas, passe-haut
      et passe-bande simultanées.

Description

      Implémentation d'un filtre à résonance du second ordre, avec sortie
      passe-bas, passe-haut et passe-bande simultanées.

Syntaxe

alow, ahigh, aband svfilter  asig, kcf, kq [, iscl][, iskip]

Initialisation

      iscl -- facteur de pondération codé semblable à celui
      de reson. Une valeur
      différente de zéro signifie que la crête du facteur de réponse est 1, c-à-d.
      toutes les fréquences autres que kcf sont atténuées
      selon la courbe de réponse (normalisée). Une valeur de zéro signifie aucune
      pondération du signal, laissant cette tâche à un ajustement ultérieur (voir
      balance). La valeur
      par défaut est 0.

      iskip (facultatif, 0 par défaut) -- disposition
      initiale de l'espace de données internes. Comme le filtrage comprend une
      boucle de rétroaction, l'état initial de l'espace de stockage est
      significatif. La valeur zéro efface l'espace ; une valeur non nulle
      maintient l'information antérieure. La valeur par défaut est 0.

Exécution

      svfilter est un filtre à variable d'état du second
      ordre, avec contrôle au taux-k de la fréquence de coupure et de Q. Lorsque
      Q augmente, un pic de résonance se forme autour de la fréquence de coupure.
      svfilter a des sorties passe-bas, passe-haut et
      passe-bande simultanées ; en mélangeant les sorties, on peut générer des
      réponses en fréquence variées. Le filtre à variable d'état, ou filtre
      "multimodal", se rencontrait fréquemment dans les premiers
      synthétiseurs analogiques, en raison de la grande variété de sonorités
      produites par l'interaction entre la fréquence de coupure, la résonance
      et les rapports de mélange en sortie. svfilter est
      bien adapté à la simulation de sonorités "analogiques", ainsi
      que pour d'autres applications nécessitant des filtres à résonance.

      asig -- signal d'entrée à filtrer.

      kcf -- fréquence de coupure ou de résonance du filtre,
      mesurée en Hz.

      kq -- Q du filtre, défini (pour les filtres passe-bande)
      comme le rapport (largeur de bande)/(fréquence de coupure). kq
      doit être compris entre 1 et 500. Lorsque kq augmente,
      la résonance du filtre augmente, ce qui correspond à une augmentation de la
      magnitude et de la "raideur" du pic de résonance. Si l'on utilise
      svfilter sans pondération du signal (iscl
      absent ou nul), le volume du pic de résonance augmente en même temps
      que Q. Pour de grandes valeurs de Q, il est recommandé de donner à
      iscl une valeur différente de zéro, ou bien d'utiliser
      une fonction de mise à l'échelle externe telle que
      balance.

      svfilter est basé sur un algorithme du livre de Hal
      Chamberlin, Musical Applications of Microprocessors
      (Hayden Books, 1985).

Exemples

      Voici un exemple de l'opcode svfilter. Il utilise le fichier
      svfilter.csd.

            Exemple 920. Exemple de l'opcode svfilter.

Voir les sections Audio en Temps Réel et
        Options de la Ligne de Commande pour
        plus d'information sur l'utilisation des options de la ligne de commande.

<CsoundSynthesizer>
<CsOptions>
; Select audio/midi flags here according to platform
; Audio out   Audio in    No messages
-odac           -iadc     -d     ;;;RT audio I/O
; For Non-realtime ouput leave only the line below:
; -o svfilter.wav -W ;;; for file output any platform
</CsOptions>
<CsInstruments>

; Orchestra file for resonant filter sweep of a sawtooth-like waveform.
; The seperate outputs of the filter are scaled by values from the score,
; and are mixed together.
sr = 44100
kr = 2205
ksmps = 20
nchnls = 1

instr 1

  idur     = p3
  ifreq    = p4
  iamp     = p5
  ilowamp  = p6              ; determines amount of lowpass output in signal
  ihighamp = p7              ; determines amount of highpass output in signal
  ibandamp = p8              ; determines amount of bandpass output in signal
  iq       = p9              ; value of q

  iharms   =        (sr*.4) / ifreq

  asig    gbuzz 1, ifreq, iharms, 1, .9, 1             ; Sawtooth-like waveform
  kfreq   linseg 1, idur * 0.5, 4000, idur * 0.5, 1     ; Envelope to control filter cutoff

  alow, ahigh, aband   svfilter asig, kfreq, iq

  aout1   =         alow * ilowamp
  aout2   =         ahigh * ihighamp
  aout3   =         aband * ibandamp
  asum    =         aout1 + aout2 + aout3
  kenv    linseg 0, .1, iamp, idur -.2, iamp, .1, 0     ; Simple amplitude envelope
          out asum * kenv

endin

</CsInstruments>
<CsScore>

f1 0 8192 9 1 1 .25

i1  0 5 100 1000 1 0 0  5  ; lowpass sweep
i1  5 5 200 1000 1 0 0 30  ; lowpass sweep, octave higher, higher q
i1 10 5 100 1000 0 1 0  5  ; highpass sweep
i1 15 5 200 1000 0 1 0 30  ; highpass sweep, octave higher, higher q
i1 20 5 100 1000 0 0 1  5  ; bandpass sweep
i1 25 5 200 1000 0 0 1 30  ; bandpass sweep, octave higher, higher q
i1 30 5 200 2000 .4 .6  0  ; notch sweep - notch formed by combining highpass and lowpass outputs
e

</CsScore>
</CsoundSynthesizer>

Crédits

            Auteur : Sean Costello

            Seattle, Washington

            1999

Nouveau dans la version 3.55 de Csound.

          Précédent

            Niveau supérieur

           Suivant

          sumarray

            Sommaire

           syncgrain


text:
import React, { Component } from 'react';

class Search extends Component {

    render() {

        const searchResults = this.props.searchResults;

        let resultsArray = [];
        for (let i = 0; i < searchResults.length; i++) {
            resultsArray.push(

                    {searchResults[i].name}
                    <button onClick={this.props.incrementScore} id={i}>Up</button>
                    <button onClick={this.props.decrementScore} id={i}>Down</button>
                    {searchResults[i].score}

            )
        }

        resultsArray.sort( (a,b) => {
            return this.props.searchResults[b.key].score - this.props.searchResults[a.key].score;
        })

        return (

                <form onSubmit={this.props.handleSearchSubmit}>

                        Tree Name:
                        <input type="text" onChange={this.props.handleSearchChange} />

                </form>
                {resultsArray}

        )
    }
}

export default Search;


text: dd if=/dev/urandom of=bench.dat bs=1024 count=102400


text:
package com.hazelcast.spi.properties;

import com.hazelcast.config.Config;
import com.hazelcast.internal.diagnostics.HealthMonitorLevel;
import com.hazelcast.test.HazelcastSerialClassRunner;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;

import java.util.Properties;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hazelcast.spi.properties.ClusterProperty.ENTERPRISE_LICENSE_KEY;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

@RunWith(HazelcastSerialClassRunner.class)
@Category(QuickTest.class)
public class HazelcastPropertiesTest {

    private final Config config = new Config();
    private final HazelcastProperties defaultProperties = new HazelcastProperties(config);

    @Test
    public void testNullProperties() {
        HazelcastProperties properties = new HazelcastProperties((Properties) null);

        assertTrue(properties.keySet().isEmpty());
    }

    @Test
    public void testKeySet_whenPropertiesAvailable() {
        Properties props = new Properties();
        props.setProperty("key1", "value1");
        props.setProperty("key2", "value2");
        HazelcastProperties properties = new HazelcastProperties(props);

        assertEquals(props.keySet(), properties.keySet());
    }

    @Test(expected = UnsupportedOperationException.class)
    public void testKeySet_isImmutable() {
        HazelcastProperties properties = new HazelcastProperties(config);

        properties.keySet().remove("foo");
    }

    @Test(expected = NullPointerException.class)
    public void testGet_whenKeyNull() {
        HazelcastProperties properties = new HazelcastProperties(config);

        properties.get(null);
    }

    @Test
    public void testGet_whenKeyNotExisting() {
        Properties props = new Properties();
        props.setProperty("key1", "value1");
        props.setProperty("key2", "value2");
        HazelcastProperties properties = new HazelcastProperties(props);

        assertNull(properties.get("nonExistingKey"));
    }

    @Test
    public void testGet_whenKeyExisting() {
        Properties props = new Properties();
        props.setProperty("key1", "value1");
        props.setProperty("key2", "value2");
        HazelcastProperties properties = new HazelcastProperties(props);

        assertEquals("value1", properties.get("key1"));
    }

    @Test
    public void testGet_whenFunctionAvailable_andNoOtherSettings() {
        Properties props = new Properties();
        HazelcastProperty p = new HazelcastProperty("key", new Function<HazelcastProperties, Integer>() {
            @Override
            public Integer apply(HazelcastProperties properties) {
                return 23;
            }
        });
        HazelcastProperties properties = new HazelcastProperties(props);

        assertEquals(23, properties.getInteger(p));
    }

    @Test
    public void testGet_whenFunctionAvailable_andPropertySet() {
        Properties props = new Properties();
        props.setProperty("key", "1");
        HazelcastProperty p = new HazelcastProperty("key", new Function<HazelcastProperties, Integer>() {
            @Override
            public Integer apply(HazelcastProperties properties) {
                return 23;
            }
        });
        HazelcastProperties properties = new HazelcastProperties(props);
        assertEquals(1, properties.getInteger(p));
    }

    @Test
    public void setProperty_ensureHighestPriorityOfConfig() {
        config.setProperty(ENTERPRISE_LICENSE_KEY.getName(), "configValue");
        ENTERPRISE_LICENSE_KEY.setSystemProperty("systemValue");

        HazelcastProperties properties = new HazelcastProperties(config);
        String value = properties.getString(ENTERPRISE_LICENSE_KEY);

        System.clearProperty(ENTERPRISE_LICENSE_KEY.getName());

        assertEquals("configValue", value);
    }

    @Test
    public void setProperty_ensureUsageOfSystemProperty() {
        ENTERPRISE_LICENSE_KEY.setSystemProperty("systemValue");

        HazelcastProperties hazelcastProperties = new HazelcastProperties(config);
        String value = hazelcastProperties.getString(ENTERPRISE_LICENSE_KEY);

        System.clearProperty(ENTERPRISE_LICENSE_KEY.getName());

        assertEquals("systemValue", value);
    }

    @Test
    public void setProperty_ensureUsageOfDefaultValue() {
        String value = defaultProperties.getString(ENTERPRISE_LICENSE_KEY);

        assertNull(value);
    }

    @Test
    public void setProperty_inheritDefaultValueOfParentProperty() {
        HazelcastProperty parent = new HazelcastProperty("parent", 1);
        HazelcastProperty child = new HazelcastProperty("child", parent);

        assertEquals(1, defaultProperties.getInteger(child));
    }

    @Test
    public void setProperty_inheritActualValueOfParentProperty() {
        config.setProperty(ClusterProperty.IO_THREAD_COUNT.getName(), "1");
        HazelcastProperties properties = new HazelcastProperties(config);

        String inputIOThreadCount = properties.getString(ClusterProperty.IO_INPUT_THREAD_COUNT);

        assertEquals("1", inputIOThreadCount);
        assertNotEquals(ClusterProperty.IO_THREAD_COUNT.getDefaultValue(), inputIOThreadCount);
    }

    @Test
    public void getSystemProperty() {
        ClusterProperty.WAIT_SECONDS_BEFORE_JOIN.setSystemProperty("12");

        assertEquals("12", ClusterProperty.WAIT_SECONDS_BEFORE_JOIN.getSystemProperty());

        System.clearProperty(ClusterProperty.WAIT_SECONDS_BEFORE_JOIN.getName());
    }

    @Test
    public void getBoolean() {
        HazelcastProperty property = new HazelcastProperty("foo", "true");

        boolean isHumanReadable = defaultProperties.getBoolean(property);

        assertTrue(isHumanReadable);
    }

    @Test
    public void getInteger() {
        HazelcastProperty property = new HazelcastProperty("key", 3);
        int ioThreadCount = defaultProperties.getInteger(property);

        assertEquals(3, ioThreadCount);
    }

    @Test
    public void getLong() {
        long lockMaxLeaseTimeSeconds = defaultProperties.getLong(ClusterProperty.LOCK_MAX_LEASE_TIME_SECONDS);

        assertEquals(Long.MAX_VALUE, lockMaxLeaseTimeSeconds);
    }

    @Test
    public void getFloat() {
        HazelcastProperty property = new HazelcastProperty("foo", 10.1F);

        float foo = defaultProperties.getFloat(property);

        assertEquals(10.1F, foo, 0.0001);
    }

    @Test
    public void getDouble() {
        HazelcastProperty property = new HazelcastProperty("foo", 10.1D);
        double foo = defaultProperties.getDouble(property);

        assertEquals(10.1D, foo, 0.0001);
    }

    @Test
    public void getPositiveMillisOrDefault() {
        String name = ClusterProperty.PARTITION_TABLE_SEND_INTERVAL.getName();
        config.setProperty(name, "-300");
        HazelcastProperty property = new HazelcastProperty(name, "20", TimeUnit.MILLISECONDS);

        long millis = defaultProperties.getPositiveMillisOrDefault(property);

        assertEquals(20, millis);
    }

    @Test
    public void getPositiveMillisOrDefaultWithManualDefault() {
        String name = ClusterProperty.PARTITION_TABLE_SEND_INTERVAL.getName();
        config.setProperty(name, "-300");
        HazelcastProperties properties = new HazelcastProperties(config);
        HazelcastProperty property = new HazelcastProperty(name, "20", TimeUnit.MILLISECONDS);

        long millis = properties.getPositiveMillisOrDefault(property, 50);

        assertEquals(50, millis);
    }

    @Test
    public void getTimeUnit() {
        config.setProperty(ClusterProperty.PARTITION_TABLE_SEND_INTERVAL.getName(), "300");
        HazelcastProperties properties = new HazelcastProperties(config);

        assertEquals(300, properties.getSeconds(ClusterProperty.PARTITION_TABLE_SEND_INTERVAL));
    }

    @Test
    public void getTimeUnit_default() {
        long expectedSeconds = 15;

        long intervalNanos = defaultProperties.getNanos(ClusterProperty.PARTITION_TABLE_SEND_INTERVAL);
        long intervalMillis = defaultProperties.getMillis(ClusterProperty.PARTITION_TABLE_SEND_INTERVAL);
        long intervalSeconds = defaultProperties.getSeconds(ClusterProperty.PARTITION_TABLE_SEND_INTERVAL);

        assertEquals(TimeUnit.SECONDS.toNanos(expectedSeconds), intervalNanos);
        assertEquals(TimeUnit.SECONDS.toMillis(expectedSeconds), intervalMillis);
        assertEquals(expectedSeconds, intervalSeconds);
    }

    @Test(expected = IllegalArgumentException.class)
    public void getTimeUnit_noTimeUnitProperty() {
        defaultProperties.getMillis(ClusterProperty.EVENT_THREAD_COUNT);
    }

    @Test
    public void getEnum() {
        config.setProperty(ClusterProperty.HEALTH_MONITORING_LEVEL.getName(), "NOISY");
        HazelcastProperties properties = new HazelcastProperties(config.getProperties());
        HealthMonitorLevel healthMonitorLevel = properties
                .getEnum(ClusterProperty.HEALTH_MONITORING_LEVEL, HealthMonitorLevel.class);

        assertEquals(HealthMonitorLevel.NOISY, healthMonitorLevel);
    }

    @Test
    public void getEnum_default() {
        HazelcastProperties properties = new HazelcastProperties(config.getProperties());
        HealthMonitorLevel healthMonitorLevel = properties
                .getEnum(ClusterProperty.HEALTH_MONITORING_LEVEL, HealthMonitorLevel.class);

        assertEquals(HealthMonitorLevel.SILENT, healthMonitorLevel);
    }

    @Test
    public void getString_whenDeprecatedNameUsed() {
        Properties props = new Properties();
        props.setProperty("oldname", "10");
        HazelcastProperties properties = new HazelcastProperties(props);

        HazelcastProperty property = new HazelcastProperty("newname")
                .setDeprecatedName("oldname");
        String value = properties.getString(property);

        assertEquals("10", value);
    }
}


text:
FROM rust:1.34

# Create shell project
RUN USER=root cargo new --lib shell
WORKDIR /shell

# Install Linux dependencies
RUN apt-get update && \
  apt-get -y install \
  mysql-client \
  && echo "Linux dependencies installed!"

# Copy that define dependencies and build
COPY ./Cargo.lock ./Cargo.lock
COPY ./Cargo.toml ./Cargo.toml
#RUN echo "fn main() {}" > build.rs
RUN echo "fn main() {}" > src/main.rs
#RUN mkdir src/bin
#RUN echo "fn main() {}" > src/bin/load.rs

# Install dependencies
RUN cargo build --release

# Remove shell project source files
RUN rm src/*.rs

# Copy src to shell
COPY ./src ./src
#COPY ./build.rs ./build.rs

# Build project within shell
# RUN ls ./target/release/deps
RUN rm ./target/release/deps/legate*
RUN cargo build --release

# Fire up
RUN mkdir /tmp/legate
RUN touch /tmp/legate/log.txt
CMD ["./target/release/legate"]


text:
<?php
if ($_GET["suborigin"]) {
    header("Content-Security-Policy: suborigin " . $_GET["suborigin"]);
}
?>
<!DOCTYPE html>

<?php
if ($_GET["childsuborigin"]) {
    echo "";
} else {
    echo "";
}
?>


text:
StatelessFlowSample component:

    <span>
      <StatelessFlowSample
        required="Best component ever"
      />
    </span>


text:
package equipamiento;

import personaje.*;

public class ConMouseThermaltake extends PersonajeEquipado{
	public ConMouseThermaltake(Personaje personajeDecorado) {
		super(personajeDecorado);
	}

	@Override
	public int obtenerPuntosDeFuerza() {
		return super.obtenerPuntosDeFuerza() *2;
	}

}


text:
MnList *scanInput();

#endif


text:
/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/kv/ll.c $                                                 */
/*                                                                        */
/* IBM Data Engine for NoSQL - Power Systems Edition User Library Project */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2014,2015                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#include <stdlib.h>
#include "am.h"
#include "ll.h"
#include <errno.h>

LL *ll_cons(void *dat, LL *ll) {
  LL *ret = am_malloc(sizeof(LL));
  if (ret == NULL)
  {
    errno = ENOMEM;
  }
  ret->car = dat;
  ret->cdr = ll;
  return ret;
}

void *ll_car(LL *ll) {return ll->car; }
LL   *ll_cdr(LL *ll) {return ll->cdr; }

int ll_len(LL *ll) {
  int ret = 0;
  while (ll) {
    ret++;
    ll = ll->cdr;
  }
  return ret;
}


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: view.proto

package edu.kit.ipd.crowdcontrol.workerservice.proto;

public interface ViewOrBuilder extends
    // @@protoc_insertion_point(interface_extends:crowdcontrol.View)
    com.google.protobuf.MessageOrBuilder {

  /**
   * optional string authorization = 1;
   */
  java.lang.String getAuthorization();
  /**
   * optional string authorization = 1;
   */
  com.google.protobuf.ByteString
      getAuthorizationBytes();

  /**
   * optional .crowdcontrol.View.Type type = 2;
   */
  int getTypeValue();
  /**
   * optional .crowdcontrol.View.Type type = 2;
   */
  edu.kit.ipd.crowdcontrol.workerservice.proto.View.Type getType();

  /**
   * optional string title = 3;
   */
  java.lang.String getTitle();
  /**
   * optional string title = 3;
   */
  com.google.protobuf.ByteString
      getTitleBytes();

  /**
   * optional string description = 4;
   */
  java.lang.String getDescription();
  /**
   * optional string description = 4;
   */
  com.google.protobuf.ByteString
      getDescriptionBytes();

  /**
   * repeated int32 answer_reservations = 5;
   */
  java.util.List<java.lang.Integer> getAnswerReservationsList();
  /**
   * repeated int32 answer_reservations = 5;
   */
  int getAnswerReservationsCount();
  /**
   * repeated int32 answer_reservations = 5;
   */
  int getAnswerReservations(int index);

  /**
   * optional string answer_type = 6;
   */
  java.lang.String getAnswerType();
  /**
   * optional string answer_type = 6;
   */
  com.google.protobuf.ByteString
      getAnswerTypeBytes();

  /**
   * repeated .crowdcontrol.View.Answer answers_to_rate = 7;
   */
  java.util.List<edu.kit.ipd.crowdcontrol.workerservice.proto.View.Answer>
      getAnswersToRateList();
  /**
   * repeated .crowdcontrol.View.Answer answers_to_rate = 7;
   */
  edu.kit.ipd.crowdcontrol.workerservice.proto.View.Answer getAnswersToRate(int index);
  /**
   * repeated .crowdcontrol.View.Answer answers_to_rate = 7;
   */
  int getAnswersToRateCount();
  /**
   * repeated .crowdcontrol.View.Answer answers_to_rate = 7;
   */
  java.util.List<? extends edu.kit.ipd.crowdcontrol.workerservice.proto.View.AnswerOrBuilder>
      getAnswersToRateOrBuilderList();
  /**
   * repeated .crowdcontrol.View.Answer answers_to_rate = 7;
   */
  edu.kit.ipd.crowdcontrol.workerservice.proto.View.AnswerOrBuilder getAnswersToRateOrBuilder(
      int index);

  /**
   * repeated .crowdcontrol.View.RatingOption rating_options = 8;
   */
  java.util.List<edu.kit.ipd.crowdcontrol.workerservice.proto.View.RatingOption>
      getRatingOptionsList();
  /**
   * repeated .crowdcontrol.View.RatingOption rating_options = 8;
   */
  edu.kit.ipd.crowdcontrol.workerservice.proto.View.RatingOption getRatingOptions(int index);
  /**
   * repeated .crowdcontrol.View.RatingOption rating_options = 8;
   */
  int getRatingOptionsCount();
  /**
   * repeated .crowdcontrol.View.RatingOption rating_options = 8;
   */
  java.util.List<? extends edu.kit.ipd.crowdcontrol.workerservice.proto.View.RatingOptionOrBuilder>
      getRatingOptionsOrBuilderList();
  /**
   * repeated .crowdcontrol.View.RatingOption rating_options = 8;
   */
  edu.kit.ipd.crowdcontrol.workerservice.proto.View.RatingOptionOrBuilder getRatingOptionsOrBuilder(
      int index);

  /**
   * repeated .crowdcontrol.View.Constraint constraints = 9;
   */
  java.util.List<edu.kit.ipd.crowdcontrol.workerservice.proto.View.Constraint>
      getConstraintsList();
  /**
   * repeated .crowdcontrol.View.Constraint constraints = 9;
   */
  edu.kit.ipd.crowdcontrol.workerservice.proto.View.Constraint getConstraints(int index);
  /**
   * repeated .crowdcontrol.View.Constraint constraints = 9;
   */
  int getConstraintsCount();
  /**
   * repeated .crowdcontrol.View.Constraint constraints = 9;
   */
  java.util.List<? extends edu.kit.ipd.crowdcontrol.workerservice.proto.View.ConstraintOrBuilder>
      getConstraintsOrBuilderList();
  /**
   * repeated .crowdcontrol.View.Constraint constraints = 9;
   */
  edu.kit.ipd.crowdcontrol.workerservice.proto.View.ConstraintOrBuilder getConstraintsOrBuilder(
      int index);

  /**
   * repeated .crowdcontrol.View.Picture pictures = 10;
   */
  java.util.List<edu.kit.ipd.crowdcontrol.workerservice.proto.View.Picture>
      getPicturesList();
  /**
   * repeated .crowdcontrol.View.Picture pictures = 10;
   */
  edu.kit.ipd.crowdcontrol.workerservice.proto.View.Picture getPictures(int index);
  /**
   * repeated .crowdcontrol.View.Picture pictures = 10;
   */
  int getPicturesCount();
  /**
   * repeated .crowdcontrol.View.Picture pictures = 10;
   */
  java.util.List<? extends edu.kit.ipd.crowdcontrol.workerservice.proto.View.PictureOrBuilder>
      getPicturesOrBuilderList();
  /**
   * repeated .crowdcontrol.View.Picture pictures = 10;
   */
  edu.kit.ipd.crowdcontrol.workerservice.proto.View.PictureOrBuilder getPicturesOrBuilder(
      int index);

  /**
   * repeated .crowdcontrol.View.Calibration calibrations = 11;
   */
  java.util.List<edu.kit.ipd.crowdcontrol.workerservice.proto.View.Calibration>
      getCalibrationsList();
  /**
   * repeated .crowdcontrol.View.Calibration calibrations = 11;
   */
  edu.kit.ipd.crowdcontrol.workerservice.proto.View.Calibration getCalibrations(int index);
  /**
   * repeated .crowdcontrol.View.Calibration calibrations = 11;
   */
  int getCalibrationsCount();
  /**
   * repeated .crowdcontrol.View.Calibration calibrations = 11;
   */
  java.util.List<? extends edu.kit.ipd.crowdcontrol.workerservice.proto.View.CalibrationOrBuilder>
      getCalibrationsOrBuilderList();
  /**
   * repeated .crowdcontrol.View.Calibration calibrations = 11;
   */
  edu.kit.ipd.crowdcontrol.workerservice.proto.View.CalibrationOrBuilder getCalibrationsOrBuilder(
      int index);
}


text:
#pragma once
#include <aws/batch/Batch_EXPORTS.h>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace Batch
{
namespace Model
{

  /**
   *
The retry strategy associated with a job.

See Also:
   AWS
   * API Reference

   */
  class AWS_BATCH_API RetryStrategy
  {
  public:
    RetryStrategy();
    RetryStrategy(const Aws::Utils::Json::JsonValue& jsonValue);
    RetryStrategy& operator=(const Aws::Utils::Json::JsonValue& jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The number of times to move a job to the RUNNABLE status. You
     * may specify between 1 and 10 attempts. If attempts is greater than
     * one, the job is retried if it fails until it has moved to RUNNABLE
     * that many times.

     */
    inline int GetAttempts() const{ return m_attempts; }

    /**
     *
The number of times to move a job to the RUNNABLE status. You
     * may specify between 1 and 10 attempts. If attempts is greater than
     * one, the job is retried if it fails until it has moved to RUNNABLE
     * that many times.

     */
    inline void SetAttempts(int value) { m_attemptsHasBeenSet = true; m_attempts = value; }

    /**
     *
The number of times to move a job to the RUNNABLE status. You
     * may specify between 1 and 10 attempts. If attempts is greater than
     * one, the job is retried if it fails until it has moved to RUNNABLE
     * that many times.

     */
    inline RetryStrategy& WithAttempts(int value) { SetAttempts(value); return *this;}

  private:
    int m_attempts;
    bool m_attemptsHasBeenSet;
  };

} // namespace Model
} // namespace Batch
} // namespace Aws


text:
using SharpTracker.Repositories;
using System.Data.Entity;
using System.Data.Entity.Migrations;

namespace SharpTracker.Api
{
	public class MigrationConfig
	{
		public static void SetInitializer()
		{
			Database.SetInitializer(new MigrateDatabaseToLatestVersion<SharpTrackerContext, Configuration>());

			var configuration = new Configuration();
			var migrator = new DbMigrator(configuration);
			migrator.Update();
		}
	}

	internal sealed class Configuration : DbMigrationsConfiguration<SharpTrackerContext>
	{
		public Configuration()
		{
			AutomaticMigrationsEnabled = true;
		}
	}
}


text:
package com.rohitshampur.glue;

import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface StickToResource {
  int value();
}


text:
using System.Collections.Generic;
using System.Threading.Tasks;
using Algolia.Search.Clients;
using Algolia.Search.Iterators;
using Algolia.Search.Models.Batch;
using Algolia.Search.Models.Common;
using Algolia.Search.Models.Enums;
using NUnit.Framework;

namespace Algolia.Search.Test.EndToEnd.Index
{
    [TestFixture]
    [Parallelizable]
    public class BatchingTest
    {
        private SearchIndex _index;

        [OneTimeSetUp]
        public void Init()
        {
            _index = BaseTest.SearchClient.InitIndex(TestHelper.GetTestIndexName("index_batching"));
        }

        [Test]
        public async Task TestBatching()
        {
            List<ObjectToBatch> batchOne = new List<ObjectToBatch>
            {
                new ObjectToBatch { ObjectID = "one", Key = "value" },
                new ObjectToBatch { ObjectID = "two", Key = "value" },
                new ObjectToBatch { ObjectID = "three", Key = "value" },
                new ObjectToBatch { ObjectID = "four", Key = "value" },
                new ObjectToBatch { ObjectID = "five", Key = "value" }
            };

            var batchOneResponse = await _index.SaveObjectsAsync(batchOne);
            batchOneResponse.Wait();

            List<BatchOperation<ObjectToBatch>> operations = new List<BatchOperation<ObjectToBatch>>
            {
                new BatchOperation<ObjectToBatch>
                {
                    Action = BatchActionType.AddObject,
                    Body = new ObjectToBatch { ObjectID = "zero", Key = "value" }
                },
                new BatchOperation<ObjectToBatch>
                {
                    Action = BatchActionType.UpdateObject, Body = new ObjectToBatch { ObjectID = "one", Key = "v" }
                },
                new BatchOperation<ObjectToBatch>
                {
                    Action = BatchActionType.PartialUpdateObject,
                    Body = new ObjectToBatch { ObjectID = "two", Key = "v" }
                },
                new BatchOperation<ObjectToBatch>
                {
                    Action = BatchActionType.PartialUpdateObject,
                    Body = new ObjectToBatch { ObjectID = "two_bis", Key = "value" }
                },
                new BatchOperation<ObjectToBatch>
                {
                    Action = BatchActionType.PartialUpdateObjectNoCreate,
                    Body = new ObjectToBatch { ObjectID = "three", Key = "v" }
                },
                new BatchOperation<ObjectToBatch>
                {
                    Action = BatchActionType.DeleteObject, Body = new ObjectToBatch { ObjectID = "four" }
                },
            };

            var batchTwoResponse = await _index.BatchAsync(operations);
            batchTwoResponse.Wait();

            List<ObjectToBatch> objectsFromIterator = new List<ObjectToBatch>();
            IndexIterator<ObjectToBatch> iterator = new IndexIterator<ObjectToBatch>(_index, new BrowseIndexQuery());

            foreach (var item in iterator)
            {
                objectsFromIterator.Add(item);
            }

            Assert.That(objectsFromIterator, Has.Exactly(6).Items);
            Assert.True(TestHelper.AreObjectsEqual(objectsFromIterator.Find(r => r.ObjectID.Equals("zero")),
                operations.Find(r => r.Body.ObjectID.Equals("zero")).Body));
            Assert.True(TestHelper.AreObjectsEqual(objectsFromIterator.Find(r => r.ObjectID.Equals("one")),
                operations.Find(r => r.Body.ObjectID.Equals("one")).Body));
            Assert.True(TestHelper.AreObjectsEqual(objectsFromIterator.Find(r => r.ObjectID.Equals("two")),
                operations.Find(r => r.Body.ObjectID.Equals("two")).Body));
            Assert.True(TestHelper.AreObjectsEqual(objectsFromIterator.Find(r => r.ObjectID.Equals("two_bis")),
                operations.Find(r => r.Body.ObjectID.Equals("two_bis")).Body));
            Assert.True(TestHelper.AreObjectsEqual(objectsFromIterator.Find(r => r.ObjectID.Equals("three")),
                operations.Find(r => r.Body.ObjectID.Equals("three")).Body));
            Assert.True(TestHelper.AreObjectsEqual(objectsFromIterator.Find(r => r.ObjectID.Equals("five")),
                batchOne.Find(r => r.ObjectID.Equals("five"))));
            Assert.False(objectsFromIterator.Exists(x => x.ObjectID.Equals("four")));
        }

        public class ObjectToBatch
        {
            public string ObjectID { get; set; }
            public string Key { get; set; }
        }
    }
}


text:
// Copyright (c) 2012 Ecma International.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
es5id: 15.2.3.6-4-421
description: >
    ES5 Attributes - Inherited property whose [[Enumerable]] attribute
    is set to false is non-enumerable (Function.prototype.bind)
---*/

        var foo = function () { };

            Object.defineProperty(Function.prototype, "prop", {
                value: 1001,
                writable: false,
                enumerable: false,
                configurable: true
            });

            var obj = foo.bind({});
            var verifyEnumerable = false;
            for (var p in obj) {
                if (p === "prop") {
                    verifyEnumerable = true;
                }
            }

assert.sameValue(obj.hasOwnProperty("prop"), false, 'obj.hasOwnProperty("prop")');
assert.sameValue(verifyEnumerable, false, 'verifyEnumerable');


text:
/*
Room management
*/

function Room(roomid) {
	this.members = {};
	this.run = 0;
	this.roomid = roomid;
	this.used = false; // did a player join the room
}

var _ = require('lodash');
var Game = require('../game');
/*
Create a room
Return: room instance or undefined
*/
Room.prototype.create = function (name) {
	var rooms = Room.prototype.rooms;
	var max = Room.prototype.max_id;
	for (var i = 0; i < max; i++) {
		if (rooms[i] === undefined) {
			rooms[i] = new Room(i);
			return rooms[i];
		}
	}
	return undefined;
}

/*
Get a room
Side effect: create a new room at room id
Return:
*/

Room.prototype.get = function (roomid) {
	var rooms = Room.prototype.rooms;
	var r = rooms[roomid];
	return r;
}

Room.prototype.join = function (client) {
	this.members[client.id] = client;
	this.broadcast('join', {room_id: this.getId(), join: client.id}, client.id);
}

Room.prototype.leave = function (client_id) {
	delete this.members[client_id];
	this.broadcast('leave', {player_id: client_id}, client_id);
	if (this.isEmpty()) {
		this.free();
	}
}

var game_config = require('../../config/game');

Room.prototype.set_board = function (board) {
	return this.board = board || game_config.board;
}

Room.prototype.play = function (client_id, move) {
	return this.game.play(client_id, move);
}

Room.prototype.newGame = function () {
	_.invoke(this.members, 'startGame');
	this.game = new Game(this.getMembers(), this.board);
	return {
		board: this.game.getBoard(),
		first: this.game.firstPlayer()
	};
}

/*******************************************************/

Room.prototype.broadcast = function (action, msg, not_send) {
	_.forEach(this.members, function (client) {
		if (client.id !== not_send)	{
			client.send_success(action, msg);
		}
	});
}

/* Player */
Room.prototype.isFull = function () {
	return this.members.length === 2;
}

Room.prototype.isEmpty = function () {
	return Object.keys(this.members).length === 0;
}

Room.prototype.free = function () {
	// free up resources
	delete Room.prototype.rooms[this.roomid];
	delete this;
}

/*******************************************************/
Room.prototype.rooms = {};
Room.prototype.max_id = 1000;
Room.prototype.getId = function () { return this.roomid; };
Room.prototype.getMembers = function () {
	return _.pluck(this.members, 'id');
}
Room.prototype.isReady = function () {
	return _.every(this.members, function (m) {
		return m.isReady();
	});
}
Room.prototype.getAll = function () {
	return _.pluck(Room.prototype.rooms, 'roomid');
}

module.exports = Room;


text:
/*
 * File:   MenuHandle.cpp
 * Author: tziegler
 *
 * Created on 5. November 2015, 16:14
 */

#include "MenuHandle.h"
#include "StringWorker.h"

MenuHandle::MenuHandle() {
	this->prompt = "";
	this->endCommand = "q";
	this->currentCommand = "";
	this->nextUsage = "";
	this->commandLenght = 3;
	this->DescriptionLentgh = 15;

	if (this->Screen.getHeight() < 1 || this->Screen.getWidth() < 1) {
		this->simpleOutput = true;
	} else {
		this->simpleOutput = false;
	}
	this->simpleOutput = true;
}

MenuHandle::MenuHandle(const MenuHandle& orig) {
}

MenuHandle::~MenuHandle() {
}

void MenuHandle::console(string message) {
	if (this->simpleOutput) {
		//cout << message << endl;
		ScreenHandle::outln(message, ScreenHandle::WHITE);
	} else {
		cursor(this->Screen.getHeight() - 2, 2);
		ScreenHandle::outln(message, ScreenHandle::WHITE);
		cout << message << endl;
	}
}

void MenuHandle::setPromot(string prmt) {
	this->prompt = prmt;
}

void MenuHandle::addMenu(TMenuEntry entry) {
	this->MenuEntires.push_back(entry);
}

void MenuHandle::fitLenght(string name, string option) {
	if (name.length() > this->DescriptionLentgh) {
		this->DescriptionLentgh = name.length();
	}
	if (option.length() > this->commandLenght) {
		this->commandLenght = option.length();
	}

	if (this->Screen.getWidth() > 0) {
		if (this->commandLenght + this->DescriptionLentgh + 6 > this->Screen.getWidth()) {
			this->DescriptionLentgh = this->Screen.getWidth() - 6 - this->commandLenght;
			if (this->DescriptionLentgh < 1) {
				this->DescriptionLentgh = 4;
				this->commandLenght = 3;
			}
		}
	}
}

void MenuHandle::addMenu(string name, string option) {

	this->fitLenght(name, option);

	TMenuEntry tmpAdd;
	tmpAdd.name = name;
	tmpAdd.cmd = option;
	tmpAdd.show = true;
	this->MenuEntires.push_back(tmpAdd);
}

void MenuHandle::setCommandString(string cmd) {
	string limiter = ";";
	StringWorker strHelper;
	this->commandList = strHelper.split(cmd, limiter);
}

string MenuHandle::showMenu() {

	if (this->commandList.empty() && this->commandList.size() < 1) {
		viewMenu();
		if (!this->simpleOutput) {
			cursor(this->Screen.getHeight() - 2, 5);
		}
		ScreenHandle::out("[", ScreenHandle::LIGHT_BLUE);
		ScreenHandle::out(this->prompt, ScreenHandle::LIGHT_CYAN);
		ScreenHandle::out("] | enter command:", ScreenHandle::LIGHT_BLUE);
		string inputCommand;
		string limiter = ";";
		cin >> inputCommand;

		StringWorker strHelper;
		this->commandList = strHelper.split(inputCommand, limiter);
	}

	if (commandList.size() > 0) {
		this->currentCommand = this->commandList[0];
		ScreenHandle::out("command ", ScreenHandle::BROWN);
		ScreenHandle::outln(this->currentCommand, ScreenHandle::MAGENTA);
		vector<string> buff = this->commandList;
		this->commandList.clear();
		for (int i = 1; i < buff.size(); i++) {
			this->commandList.push_back(buff[i]);
		}

	}
	this->currentCommand = this->getCmdParam(this->currentCommand);

	ScreenHandle::outln("", ScreenHandle::NORMAL);

	TMenuEntry assignedCmd = this->getCommandByInput(this->currentCommand);
	if (assignedCmd.cmd != "#") {
		ScreenHandle::out("executing ", ScreenHandle::LIGHT_BLUE);
		ScreenHandle::outln(assignedCmd.name, ScreenHandle::BLUE);
	} else {
		if (this->currentCommand == this->endCommand) {

			ScreenHandle::outln("Bye bye ...have a nice day....", ScreenHandle::NORMAL);
		} else {
			ScreenHandle::out("unknow command ", ScreenHandle::RED);
			ScreenHandle::outln(this->currentCommand, ScreenHandle::LIGHT_RED);
		}
	}

	return this->currentCommand;
}

string MenuHandle::getCmdParam(string cmd) {
	string result;
	string splitby = "=";

	StringWorker strHelp;
	vector<string> strBuff = strHelp.split(cmd, splitby);
	if (strBuff.size() > 1) {
		result = strBuff[0];
		this->nextUsage = strBuff[1];
	} else {
		result = cmd;
	}
	return result;
}

string MenuHandle::getInputString(string label) {
	string result;

	if (this->nextUsage != "") {
		result = this->nextUsage;
		this->nextUsage = "";
	} else {
		string getCommand;
		string splitby = "=";
		ScreenHandle::out(">>.... " + label + ":", ScreenHandle::YELLOW);
		cin >> getCommand;

		StringWorker strHelp;
		vector<string> strBuff = strHelp.split(getCommand, splitby);
		if (strBuff.size() > 1) {
			result = strBuff[0];
			this->nextUsage = strBuff[1];
		} else {
			result = getCommand;
		}

		ScreenHandle::outln("", ScreenHandle::NORMAL);
	}
	return result;
}

string MenuHandle::getCurrentCommand() {
	return this->currentCommand;

}

bool MenuHandle::done() {
	return this->currentCommand == this->endCommand;
}

bool MenuHandle::notDone() {
	return this->currentCommand != this->endCommand;
}

void MenuHandle::setMenuVisibile(string command, bool state) {
	for (int t = 0; t < this->MenuEntires.size(); t++) {
		TMenuEntry current = this->MenuEntires.at(t);
		if (current.cmd == command) {
			this->MenuEntires.at(t).show = state;
		}
	}
}

void MenuHandle::updateMenu(string command, string label) {

	for (int t = 0; t < this->MenuEntires.size(); t++) {
		TMenuEntry current = this->MenuEntires.at(t);
		if (current.cmd == command) {
			this->fitLenght(label, command);
			this->MenuEntires.at(t).name = label;
		}
	}
}

TMenuEntry MenuHandle::getCommandByInput(string cmd) {
	for (int t = 0; t < this->MenuEntires.size(); t++) {
		TMenuEntry current = this->MenuEntires.at(t);
		if (current.cmd == cmd) {
			return current;
		}
	}
	TMenuEntry dummy;
	dummy.cmd = "#";
	dummy.name = "ERROR";

	return dummy;
}

void MenuHandle::viewMenu() {
	StringWorker strHelper;
	if (this->simpleOutput) {
		int strWidth = this->commandLenght + this->DescriptionLentgh + 4;
		ScreenHandle::outln("+" + strHelper.fillString("-", strWidth) + "+", ScreenHandle::BLUE);
		for (int t = 0; t < this->MenuEntires.size(); t++) {
			TMenuEntry current = this->MenuEntires.at(t);
			if (current.show == true) {
				ScreenHandle::out("|  ", ScreenHandle::BLUE);
				ScreenHandle::out(strHelper.strFitRight(current.cmd, this->commandLenght), ScreenHandle::YELLOW);
				ScreenHandle::out("|", ScreenHandle::BLUE);
				ScreenHandle::out(strHelper.strFit(" " + current.name, this->DescriptionLentgh), ScreenHandle::WHITE);
				ScreenHandle::outln("|", ScreenHandle::BLUE);

			}

		}
		ScreenHandle::outln("+" + strHelper.fillString("-", strWidth) + "+", ScreenHandle::BLUE);

		ScreenHandle::out("| ", ScreenHandle::BLUE);
		ScreenHandle::out("type ", ScreenHandle::LIGHT_BLUE);
		ScreenHandle::out(this->endCommand, ScreenHandle::YELLOW);
		ScreenHandle::outln(" to exit menu ", ScreenHandle::LIGHT_BLUE);
		ScreenHandle::outln("+" + strHelper.fillString("-", strWidth), ScreenHandle::BLUE);

	} else {
		int Top = 4;
		int Left = 3;
		this->Screen.clearScreen();

		int w = 10;
		int h = 0;
		for (int t = 0; t < this->MenuEntires.size(); t++) {
			TMenuEntry current = this->MenuEntires.at(t);
			if (current.show == true) {
				this->Screen.print(current.cmd, Left + 5, Top + h, 2);
				this->Screen.print(current.name, Left + 15, Top + h, 3);

				if (w < current.name.length()) {
					w = current.name.length();
				}
				h++;
			}
		}
		this->Screen.printBox(Top, Left, Left + w + 20, h + 1);

		this->Screen.printScreen();
	}

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Uses of Class datechooser.beans.DateChooserVisual (DateChooser javadoc)
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
datechooser.beans.DateChooserVisual

Packages that use DateChooserVisual

datechooser.beans
Beans and service classes.

Uses of DateChooserVisual in datechooser.beans

Subclasses of DateChooserVisual in datechooser.beans

 class
DateChooserCombo

          Bean "Combo date editor".

 class
DateChooserPanel

          Bean: date selection panel.

Methods in datechooser.beans that return DateChooserVisual

 DateChooserVisual
DateChooserVisual.clone()

Methods in datechooser.beans with parameters of type DateChooserVisual

static datechooser.beans.BeanTableCellEditor
DateChooserVisual.createTableCellEditor(DateChooserVisual bean)

          Bean mutates into TableCellEditor object.

static datechooser.beans.BeanTableCellRenderer
DateChooserVisual.createTableCellRenderer(DateChooserVisual bean)

          Bean mutates into TableCellRenderer object.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
FOUNDATION_EXPORT double FunctionalUtilsVersionNumber;
FOUNDATION_EXPORT const unsigned char FunctionalUtilsVersionString[];


text:
from tornado.wsgi import WSGIContainer
from tornado.ioloop import IOLoop
from tornado.web import FallbackHandler, RequestHandler, Application
from api  import app
import tornado.httpserver
import tornado.options

tornado.options.parse_command_line()

class MainHandler(RequestHandler):
  def get(self):
    self.write("Tornado")

tr = WSGIContainer(app)

application = Application([
(r"/tornado", MainHandler),
(r".*", FallbackHandler, dict(fallback=tr)),
],debug=True)

http_server = tornado.httpserver.HTTPServer(application, ssl_options = {"certfile": "/etc/letsencrypt/live/gyani.xyz/cert.pem", "keyfile": "/etc/letsencrypt/live/gyani.xyz/privkey.pem"})

if __name__ == "__main__":
  http_server.listen(443)
  IOLoop.instance().start()


text:
require 'simplecov'
SimpleCov.start { add_filter '/spec/' }

require 'rspec'
require 'vend'
require 'awesome_print'
require 'webmock/rspec'