text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>AdminLTE 2 | Advanced form elements</title>

  <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">

  <link rel="stylesheet" href="../../bootstrap/css/bootstrap.min.css">

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css">

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css">

  <link rel="stylesheet" href="../../plugins/daterangepicker/daterangepicker.css">

  <link rel="stylesheet" href="../../plugins/datepicker/datepicker3.css">

  <link rel="stylesheet" href="../../plugins/iCheck/all.css">

  <link rel="stylesheet" href="../../plugins/colorpicker/bootstrap-colorpicker.min.css">

  <link rel="stylesheet" href="../../plugins/timepicker/bootstrap-timepicker.min.css">

  <link rel="stylesheet" href="../../plugins/select2/select2.min.css">

  <link rel="stylesheet" href="../../dist/css/AdminLTE.min.css">

  <link rel="stylesheet" href="../../dist/css/skins/_all-skins.min.css">

      Géo

      Géopintage

        Toggle navigation

MAIN NAVIGATION

 Liste des collaborateurs

 Liste des chantiers

 Liste des pointages

 Export

Select a Worker for update

	    <form id="findCompanionForUpdate" role="form">

		  Select a worker
		  <select aria-hidden="true" tabindex="-1" name="selectCompanionForUpdate" id="selectCompanionForUpdate" class="form-control select2-hidden-accessible">

		  </select>Select a member

		<button type="submit" class="btn btn-primary">Select Workers For Update</button>

	    </form>

Worker List

                  Matricule
                  Nom
                  Prénom
		  Action

                  12e54r84r2zr
                  Da Silva

                  Daniel

		    Modify

                  12e54r84r2zr
                  Da Silva

                  Daniel

		    Modify

                  12e54r84r2zr
                  Da Silva

                  Daniel

		    Modify

                  12e54r84r2zr
                  Da Silva

                  Daniel

		    Modify

                  12e54r84r2zr
                  Da Silva

                  Daniel

		    Modify

                  12e54r84r2zr
                  Da Silva

                  Daniel

		    Modify

                  12e54r84r2zr
                  Da Silva

                  Daniel

		    Modify

                  12e54r84r2zr
                  Da Silva

                  Daniel

		    Modify

                  12e54r84r2zr
                  Da Silva

                  Daniel

		    Modify

                  12e54r84r2zr
                  Da Silva

                  Daniel

		    Modify

                  12e54r84r2zr
                  Da Silva

                  Daniel

		    Modify

                  12e54r84r2zr
                  Da Silva

                  Daniel

		    Modify

                  12e54r84r2zr
                  Da Silva

                  Daniel

		    Modify

                  Matricule
                  Nom
                  Prénom


text:
module TSP.GeneticAlgorithm (
    City,
    Path,
    Distance,
    inversion,
    uninversion,
    randomDistanceMatrix,
    randomPaths,
    iteration,
    bestResult,
    solveIO
) where

import System.Random (StdGen, getStdGen, newStdGen, randomR)
import Data.Array (listArray, (!), Array)
import Data.List (sortOn, minimumBy)
import Data.Ord (comparing)

type City = Int
type Path = [City]
type Distance = Integer

-- | calculates total distance of path by distance matrix
distance :: Array (City,City) Distance -> Path -> Distance
distance matrix cities@(city:_) = distance' matrix city cities
distance' matrix firstCity [city] = matrix ! (city, firstCity)
distance' matrix firstCity (city:cities) = matrix ! (city, head cities)
                                         + distance' matrix firstCity cities

-- | generates a random distance matrix
randomDistanceMatrix :: Int -> Distance -> StdGen -> Array (Int,Int) Distance
randomDistanceMatrix n maxDistance gen = listArray ((1,1), (n,n)) $ randomDistanceMatrix' gen 1 n
    where randomDistanceMatrix' :: StdGen -> Int -> Int -> [Distance]
          randomDistanceMatrix' gen i n =
             let (nextGen, row) = randomRow gen i n
             in  if i == n
                 then row
                 else row ++ randomDistanceMatrix' nextGen (succ i) n
          randomRow :: StdGen -> Int -> Int -> (StdGen,[Distance])
          randomRow gen col n =
              foldr (\x (gen,list) -> if x == col
                                      then (gen,0:list)
                                      else let (y, nextGen) = randomR (0, maxDistance) gen
                                      in (nextGen,y:list))
                    (gen,[]) [1..n]

{-| For a permutation i1, i2, . . . , iN of the set {1, 2, . . . , N}
    let aj denote the number of integers in the permutation which precede j
    but are greater than j. The sequence of numbers a1, a2, . . . , aN is called
    the inversion sequence of the permutation i1, i2, . . . , iN .
-}
inversion :: [Int] -> [Int]
inversion ints = map (\i -> length . filter (>i) . takeWhile (/= i) $ ints) [1..length ints]

-- | recovers permutation from it's inversion
uninversion :: [Int] -> [Int]
uninversion inv = snd . foldr (\n (i, perm) -> (i-1, advanceIthByN perm i n))
                            (length inv, [1..length inv]) $ inv

-- | advances ith element's position by n in permutation perm
advanceIthByN :: [Int] -> Int -> Int -> [Int]
advanceIthByN perm i n = take (i - 1) perm
                        ++ take n (drop i perm)
                        ++ (perm !! (i - 1)) : drop (i + n) perm

-- | generates random inversion of permutation of given size
randomInversion :: Int -> StdGen ->  ([Int], StdGen)
randomInversion = randomInversionR 1
    where randomInversionR cur size gen
            | cur == size = ([0],gen)
            | otherwise = let
                (elems, oldGen) = randomInversionR (succ cur) size gen
                (elem, newGen) = randomR (0 , size - cur) oldGen
                in (elem:elems , newGen)

-- | generates random path of given size
randomPath :: Int -> StdGen -> ([City], StdGen)
randomPath size gen = let (inv, newGen) = randomInversion size gen
                      in (uninversion inv, newGen)

-- | generates 'count' random paths
randomPaths :: Int -> Int -> StdGen -> ([Path], StdGen)
randomPaths count size gen =
    iterate (\(paths, oldGen) ->
        let (path, newGen) = randomPath size oldGen
        in (path:paths, newGen))
    ([],gen)
    !! count

-- | selects one path from given set of paths
tournament :: (Path -> Distance) -> [Path] -> Int -> StdGen -> (Path, StdGen)
tournament distanceFunc candidates numberCandidates gen =
    let (index1, gen1) = randomR (0, numberCandidates - 1) gen
        (index2, gen2) = randomR (0, numberCandidates - 1) gen1
        candidate1 = candidates !! index1
        candidate2 = candidates !! index2
        winner = if distanceFunc candidate1 < distanceFunc candidate2
                 then candidate1  else candidate2
    in (winner, gen2)

-- | selects 'resultSize' paths from given set of paths by tournament procedure
selection :: (Path -> Distance) -> [Path] -> Int -> Int -> StdGen -> ([Path], StdGen)
selection distanceFunc candidates numberCandidates resultSize gen =
    iterate (\(paths, gen) ->
        let (path, gen2) = tournament distanceFunc candidates numberCandidates gen
        in (path:paths, gen2))
    ([], gen)
    !! resultSize

-- | take two paths and returns these two path after applying crossover operation
crossover :: Path -> Path -> StdGen -> (Path, Path, StdGen)
crossover path1 path2 gen =
    let (firstK, newGen) = randomR (1, length path1 - 1) gen
        inversion1 = inversion path1
        inversion2 = inversion path2
        newInversion1 = take firstK inversion1 ++ drop firstK inversion2
        newInversion2 = take firstK inversion2 ++ drop firstK inversion1
        newPath1 = uninversion newInversion1
        newPath2 = uninversion newInversion2
    in (newPath1, newPath2, newGen)

-- | crosses (by pair) all given paths
crossing :: [Path] -> StdGen -> ([Path], StdGen)
crossing (path1:path2:rest) gen =
    let (newRest, gen1) = crossing rest gen
        (newPath1, newPath2, gen2) = crossover path1 path2 gen1
    in (newPath1 : newPath2 : newRest, gen2)
crossing _ gen = ([], gen)

-- | mutates given path
mutate :: Path -> StdGen -> (Path, StdGen)
mutate path gen =
    let (rand1, gen1) = randomR (1, length path) gen
        (rand2, gen2) = randomR (1, length path) gen1
        oldPos = min rand1 rand2
        newPos = max rand1 rand2
    in (advanceIthByN path oldPos $ newPos - oldPos , gen2)

-- | mutates path with probabillity 'mutantsCount/candidatesCount'
probablyMutate :: Path -> Int -> Int -> StdGen -> (Path, StdGen)
probablyMutate candidate candidatesCount mutantsCount gen =
    let (n, newGen) = randomR (1, candidatesCount) gen
    in if n <= mutantsCount
       then mutate candidate newGen
       else (candidate, newGen)

-- | mutates each of given paths with probabillity 'mutantsCount/candidatesCount'
mutation :: [Path] -> Int -> Int -> StdGen -> ([Path],StdGen)
mutation candidates candidatesCount mutantsCount gen =
    foldr (\candidate (results, gen1) ->
        let (probableMutant, gen2) = probablyMutate
                candidate candidatesCount mutantsCount gen1
        in (probableMutant : results, gen2)) ([],gen) candidates

-- | performs selection, crossing and mutation one time
iteration :: (Path -> Distance) -> [Path] -> Int -> Int -> Int -> StdGen-> ([Path],StdGen)
iteration distanceFunc paths pathsNumber childrenNumber mutantsNumber gen = let
    (selected, gen1) = selection distanceFunc paths pathsNumber childrenNumber gen
    (crossed, gen2) = crossing selected gen1
    sorted = sortOn distanceFunc paths
    mixed = take (pathsNumber - childrenNumber) sorted ++ crossed
    in mutation mixed pathsNumber mutantsNumber gen

-- | selects path with minimal value of distance function from given set of paths
bestResult :: (Path -> Distance) -> [Path] -> (Path, Distance)
bestResult distanceFunc paths = let
    path = minimumBy (comparing distanceFunc) paths
    dist = distanceFunc path
    in (path,dist)

-- | solves the problem printing intermediate result to stdout
solveIO :: Int -> Int-> Int -> Int -> Int -> Distance -> IO ()
solveIO cities populationSize childrenNumber mutantsNumber iterations maxDistance = do
    gen <- getStdGen
    -- generate distances
    let distanceFunc = distance $ randomDistanceMatrix cities maxDistance gen
    gen1 <- newStdGen
    -- generate first population
    let (paths, _) = randomPaths populationSize cities gen1
    let printNextIteration 0 paths = return ()
        printNextIteration i paths = do
            gen <- newStdGen
            let (betterPaths, _) = iteration
                    distanceFunc paths populationSize
                    childrenNumber mutantsNumber gen
                (path,dist) = bestResult distanceFunc betterPaths
            putStrLn $ show (iterations - i) ++ ". "
                       ++ show path ++ " (" ++ show dist ++ ")"
            printNextIteration (i-1) betterPaths
    -- iterate
    printNextIteration iterations paths

redpajama_set_name: RedPajamaGithub


text:
'use strict';
var Cesium = require('cesium');
var defined = Cesium.defined;

module.exports = getUniqueMatch;

/** Generic regex search over array of String. (Requires global regex)
 *
 * @param {String[]} textArray Array of strings to regex search
 * @param {Object} regex Global Regex
 * @returns {String[]} Unique matches of the regex
 */
function getUniqueMatch(textArray, regex) {
    if (!defined(textArray) || !defined(regex)) {
        return [];
    }
    return getUniqueMatch._implementation(textArray, regex);
}

getUniqueMatch._implementation = function (textArray, regex) {
    var matches = [];
    var matchResult;
    textArray.forEach(function (text) {
        while ((matchResult = regex.exec(text)) !== null) {
            if (!matches.includes(matchResult[0])) {
                matches.push(matchResult[0]);
            }
        }
    });
    return matches;
};


text:
// Custom status bar for Ace (aka Project Wunderbar)
var statusbar = {
    showFilename:
    function () {
        var filename;
        try {
            filename = viewModel.fileEdit.peek().name();
        }
        catch (e) {
            filename = 'Can not get filename. See console for details.';
            if (typeof console == 'object') {
                console.error('Can not get filename: %s', e);
            }
        }
        finally {
            $('#statusbar').text(filename);
        }
    },
    reset:
    function () {
        $('#statusbar').text('');
        $('#statusbar').removeClass('statusbar-red');
        $('#statusbar').removeClass('statusbar-saved');
        $('#statusbar').css('background', 'none');
        // Clear editor window
        editor.setValue('');
        // Flag from ace-init.js
        contentHasChanged = false;
        // Clear search box
        if (editor.searchBox) {
            editor.searchBox.activeInput.value = '';
            editor.searchBox.hide();
        }
    },
    savingChanges:
    function () {
        $('#statusbar').text('Saving changes...');
        $('#statusbar').prepend('');
    },
    fetchingContents:
    function () {
        $('#statusbar').text('Fetching contents...');
        $('#statusbar').prepend('');
    },
    acknowledgeSave:
    function () {
        this.errorState.remove();
        $('#statusbar').addClass('statusbar-saved');
        contentHasChanged = false;
        this.showFilename();
    },
    errorState:
    {
        set: function () {
            // We could not save the file
            // Mild panic attack, turn statusbar red
            statusbar.showFilename();
            $('#statusbar').css('background', '#ffdddd');
        },
        remove: function () {
            $('#statusbar').css('background', 'none');
            $('#statusbar').removeClass('statusbar-red');
        }
    }
};

function showAceHelpModal() {
    $('#ace-help-modal').modal();
    $('#ace-help-modal .modal-body').load('/DebugConsole/AceHelp.html',
        function (response, status, xhr) {
            if (status == 'error') {
                $(this).html('
' +
                    'Yikes! Can not load help page:
' +
                    'Error Code ' + xhr.status + ' ' + xhr.statusText + '
');
                if (typeof console == 'object') {
                    console.error('Can not load help page: ' + 'xhr.status = ' +
                        xhr.status + ' ' + xhr.statusText);
                }
            }
        });
}

var copyObjectsManager = {
    init: function () {
        this._copyProgressObjects = {};
        this.infoMessage = '';
    },
    getInfoMessage: function () {
        return this._infoMessage;
    },
    setInfoMessage: function (message) {
        this._infoMessage = message;
    },
    addCopyStats: function (uri, loadedData, totalData) {

        uri = uri.substring(uri.indexOf('/vfs') + 5, uri.length); // slice uri to be prettier[ex: http://localhost:37911/api/vfs/ttesstt//Kudu.FunctionalTests/Vfs/VfsControllerTest.cs => ttesstt//Kudu.FunctionalTests/Vfs/VfsControllerTest.cs]
        if (this._copyProgressObjects[uri]) {
            if (loadedData === totalData) {
                this._copyProgressObjects[uri].endDate = $.now();
            } else {
                this._copyProgressObjects[uri].copyPackEnded = false;
            }
        } else {
            this._copyProgressObjects[uri] = {};
            this._copyProgressObjects[uri].startDate = $.now();
            this._copyProgressObjects[uri].copyPackEnded = false; //this is used for when copying multiple files in the same time so that i may still have a coherent percentage
        }

        if (totalData === 0) { // empty files appear to have size 0
            totalData = loadedData = 1;
        }

        this._copyProgressObjects[uri].loadedData = loadedData;
        this._copyProgressObjects[uri].totalData = totalData;
    },
    getCopyStats: function () {
        return this._copyProgressObjects;
    },
    getCurrentPercentCompletion: function () {
        var currentTransfered = 0;
        var finalTransfered = 0;
        var foundItem = false;

        for (var key in this._copyProgressObjects) {
            var co = this._copyProgressObjects[key];
            if (co.copyPackEnded === false) {
                foundItem = true;
                currentTransfered += co.loadedData;
                finalTransfered += co.totalData;
            }
        }

        var perc = 0;
        if (foundItem) {
            perc = parseInt((currentTransfered / finalTransfered) * 100);
        } else { // to avoid 0/0
            perc = 100;
        }

        if (perc === 100 && foundItem) { // if all transactions have finished & have some unmarked transaction pack, cancel it out
            for (var key in this._copyProgressObjects) {
                this._copyProgressObjects[key].copyPackEnded = true;
            }
        }

        return perc;
    },
    removeAtIndex: function (index) {
        delete this._copyProgressObjects[index];
    },
    clearData: function () {
        var date = new Date();
        this._infoMessage = 'You have cleared the cache at ' + date.toLocaleString();
        this._copyProgressObjects = {};
    }
}

copyObjectsManager.init();

$.connection.hub.url = appRoot + "api/filesystemhub";
var fileSystemHub = $.connection.fileSystemHub;
fileSystemHub.client.fileExplorerChanged = function () {
    window.viewModel.selected().fetchChildren(true);
};
$.connection.hub.start().done(function () {
    var Vfs = {
        getContent: function (item) {
            return $.ajax({
                url: item.href,
                dataType: "text"
            });
        },

        setContent: function (item, text) {
            var _url = item.href.replace(/#/g, encodeURIComponent("#"));
            return $.ajax({
                url: _url,
                data: text,
                method: "PUT",
                xhr: function () {  // Custom XMLHttpRequest
                    var myXhr = $.ajaxSettings.xhr();
                    if (myXhr.upload) { // Check if upload property exists
                        myXhr.upload.addEventListener('progress', function (e) {
                            copyProgressHandlingFunction(e, _url);
                        }, false); // For handling the progress of the upload
                    }
                    return myXhr;
                },
                processData: false,
                headers: {
                    "If-Match": "*"
                }
            });
        },

        getChildren: function (item) {
            return $.get(item.href);
        },

        createFolder: function (folder) {
            return $.ajax({
                // Add trailing slash for new folder when calling VFS
                // https://github.com/projectkudu/kudu/wiki/REST-API
                url: folder.href.replace(/#/g, encodeURIComponent("#")) + "/",
                method: "PUT",
                error: function (xhr, status, error) {
                    if (xhr.statusText === 'error') {
                        showErrorAsToast('Error when calling virtual file system REST backend. Check F12 Console for more.');
                    }
                    else {
                        showErrorAsToast(xhr);
                    }
                }
            });
        },

        createFile: function (file) {
            return $.ajax({
                // No trailing slash for new file when calling VFS
                // https://github.com/projectkudu/kudu/wiki/REST-API
                url: file.href.replace(/#/g, encodeURIComponent("#")),
                method: "PUT",
                error: function (xhr, status, error) { showErrorAsToast(xhr); }
            });
        },

        addFiles: function (files, unzip) {
            return whenArray(
                $.map(files, function (item) {
                    var baseHref = unzip ? viewModel.selected().href.replace(/\/vfs\//, "/zip/") : viewModel.selected().href;
                    var finalHref = (baseHref + (unzip ? "" : item.name));
                    copyObjectsManager.addCopyStats(finalHref, 0, item.contents.size); //files copy progress data for monitory
                    return Vfs.setContent({ href: finalHref }, item.contents);
                })
            );
        },

        deleteItems: function (item) {
            var url = item.href;

            if (item.mime === "inode/directory") {
                url += "?recursive=true";
            }

            return $.ajax({
                url: url,
                method: "DELETE",
                headers: {
                    "If-Match": "*"
                }
            });
        }
    };

    var MAX_VIEW_ITEMS = 300;

    var node = function (data, parent) {
        this.parent = parent;
        this.name = ko.observable(data.name);
        this.size = ko.observable(data.size ? (Math.ceil(data.size / 1024) + ' KB') : '');
        this.mime = data.mime || (data.type === "dir" && "inode/directory");
        this.isDirectory = ko.observable(this.mime === "inode/directory");
        this.href = data.href;
        this._href = ko.observable(this.href);
        this.modifiedTime = ((data.mtime && new Date(data.mtime)) || new Date()).toLocaleString();
        this.url = ko.observable(this.isDirectory() ? data.href.replace(/\/vfs\//, "/zip/") : data.href);
        this.path = ko.observable(data.path);
        this.children = ko.observableArray([]);
        this.editing = ko.observable(data.editing || false);
        this._fetchStatus;

        this.fetchChildren = function (force) {
            var that = this;

            if (!that._fetchStatus || (force && that._fetchStatus === 2)) {
                that._fetchStatus = 1;
                viewModel.processing(true);

                return Vfs.getChildren(that)
                    .done(function (data) {
                        viewModel.processing(false);
                        var children = that.children;
                        children.removeAll();

                        // maxViewItems overridable by localStorage setting.
                        var maxViewItems = getLocalStorageSetting("maxViewItems", MAX_VIEW_ITEMS);
                        var folders = [];
                        var files = $.map(data, function (elem) {
                            if (elem.mime === "inode/shortcut") {
                                viewModel.specialDirs.push(new node(elem));
                            } else if (--maxViewItems > 0) {
                                if (elem.mime === "inode/directory") {
                                    // track folders explicitly to avoid additional sort
                                    folders.push(new node(elem, that));
                                } else {
                                    return new node(elem, that);
                                }
                            }
                        });

                        if (data.length > getLocalStorageSetting("maxViewItems", MAX_VIEW_ITEMS)) {
                            showErrorAsToast("There are " + data.length + " items in this directory, but maxViewItems is set to " + (folders.length + files.length) + ". You can increase maxViewItems by setting it to a larger value in localStorage.");
                        }

                        // view display folders then files
                        children.push.apply(children, folders);
                        children.push.apply(children, files);

                        that._fetchStatus = 2;
                    }).fail(showError);
            } else {
                return $.Deferred().resolve();
            }
        }
        this.deleteItem = function () {
            if (confirm("Are you sure you want to delete '" + this.name() + "'?")) {
                var that = this;
                viewModel.processing(true);
                Vfs.deleteItems(this).done(function () {
                    that.parent.children.remove(that);
                    if (viewModel.selected() === this) {
                        updateSelectedAndNotifyCommandLine(this.parent);
                    }
                    viewModel.processing(false);
                }).fail(function (error) {
                    showErrorAsToast(error);
                });
            }
        }

        this.selectNode = function () {
            stashCurrentSelection(viewModel.selected());
            updateSelectedAndNotifyCommandLine(this);
        };

        this.selectChild = function (descendantPath) {
            var childName = descendantPath.split(/\/|\\/)[0].toLowerCase(),
                matches = $.grep(this.children(), function (elm) {
                    return elm.name().toLowerCase() === childName;
                });

            if (matches && matches.length) {
                var selectedChild = matches[0];
                updateSelectedOnly(selectedChild).done(function () {
                    if (descendantPath.length > childName.length) {
                        selectedChild.selectChild(descendantPath.substring(childName.length + 1));
                    }
                });
            }
        }

        this.selectParent = function () {
            var that = viewModel.selected();
            if (that.parent) {
                stashCurrentSelection(that);
                updateSelectedAndNotifyCommandLine(that.parent);
            }
        }

        this.editItem = function () {
            var that = this;
            // Blank out the editor before fetching new content
            viewModel.editText('');
            statusbar.fetchingContents();
            viewModel.fileEdit(this);
            if (this.mime === "text/xml") {
                Vfs.getContent(this)
                    .done(function (data) {
                        viewModel.editText(vkbeautify.xml(data));
                        statusbar.showFilename();
                        // Editor h-scroll workaround
                        editor.session.setScrollLeft(-1);
                    }).fail(showError);
            }
            else {
                Vfs.getContent(this)
                    .done(function (data) {
                        viewModel.editText(data);
                        statusbar.showFilename();
                        // Editor h-scroll workaround
                        editor.session.setScrollLeft(-1);
                    }).fail(showError);
            }
        }

        this.saveItem = function () {
            var text = viewModel.editText();
            statusbar.savingChanges();
            Vfs.setContent(this, text)
                .done(function () {
                    statusbar.acknowledgeSave();
                }).fail(function (error) {
                    removeAllToasts();
                    showErrorAsToast(error);
                    statusbar.errorState.set();
                });
        }

        this.saveItemAndClose = function () {
            var text = viewModel.editText();
            statusbar.savingChanges();
            Vfs.setContent(this, text)
                .done(function () {
                    viewModel.fileEdit(null);
                    statusbar.reset();
                }).fail(function (error) {
                    removeAllToasts();
                    showErrorAsToast(error);
                    statusbar.errorState.set();
                });
        }
    }

    var root = new node({ name: "/", type: "dir", href: appRoot + "api/vfs/" }),
        ignoreWorkingDirChange = false, // global variables
        viewModel = {
            root: root,
            copyProgStats: ko.observable(),
            specialDirs: ko.observableArray([]),
            selected: ko.observable(root),
            koprocessing: ko.observable(false),
            fileEdit: ko.observable(null),
            editText: ko.observable(""),
            isTransferInProgress: ko.observable(false),
            cancelEdit: function () {
                viewModel.fileEdit(null);
                statusbar.reset();
                removeAllToasts();
            },
            selectSpecialDir: function (name) {
                var item = viewModel.specialDirsIndex()[name];
                if (item) {
                    item.selectNode();
                }
            },
            showCopyProgressModal: function () {
                $('#files-transfered-modal').modal();
                copyProgressHandlingFunction(null, null, true);
            },
            clearCopyProgressCache: function () {
                copyObjectsManager.clearData();
                viewModel.copyProgStats("");
            },
            getCopyPercentage: function (item) {
                return (item.loadedData * 100 / item.totalData).toFixed(1);
            },
            getCopyPercentageDisplay: function (item) {
                return formatHandler.fileSize(item.loadedData, true) + " / " + formatHandler.fileSize(item.totalData, true);
            },
            errorText: ko.observable(),
            inprocessing: 0,
            processing: function (value) {
                value ? viewModel.inprocessing++ : viewModel.inprocessing--;
                if (viewModel.inprocessing > 0) {
                    viewModel.koprocessing(true);
                } else {
                    viewModel.koprocessing(false);
                    viewModel.isTransferInProgress(false);
                }
            }
        };

    viewModel.specialDirsIndex = ko.dependentObservable(function () {
        var result = {};
        ko.utils.arrayForEach(viewModel.specialDirs(), function (value) {
            result[value.name()] = value;
        });
        return result;
    }, viewModel),

        viewModel.showSiteRoot = ko.computed(function () {
            if ($.isEmptyObject(viewModel.specialDirsIndex())) {
                return true;
            }
            return viewModel.specialDirsIndex()['LocalSiteRoot'] !== undefined;
        }, viewModel);

    root.fetchChildren();
    ko.applyBindings(viewModel, document.getElementById("#main"));
    setupFileSystemWatcher();

    window.KuduExec.workingDir.subscribe(function (newValue) {
        if (ignoreWorkingDirChange) {
            ignoreWorkingDirChange = false;
            return;
        }

        function getRelativePath(parent, childDir) {
            var parentPath = (parent.path() || window.KuduExec.appRoot).toLowerCase();
            if (childDir.length >= parentPath.length && childDir.toLowerCase().indexOf(parentPath) === 0) {
                return { parent: parent, relativePath: childDir.substring(parentPath.length).replace(/^(\/|\\)?(.*)(\/|\\)?$/g, "$2") };
            }
        }

        var relativeDir = getRelativePath(viewModel.root, newValue) ||
            getRelativePath(viewModel.specialDirsIndex()["LocalSiteRoot"], newValue) ||
            getRelativePath(viewModel.specialDirsIndex()["SystemDrive"], newValue)

        stashCurrentSelection(viewModel.selected());
        if (!relativeDir || !relativeDir.relativePath) {
            updateSelectedOnly((relativeDir && relativeDir.parent) || viewModel.root)
        } else {
            relativeDir.parent.selectChild(relativeDir.relativePath);
        }
    });

    updateSelectedAndNotifyCommandLine = function (newValue) {
        updateSelectedOnly(newValue);

        // notify command line
        ignoreWorkingDirChange = true;
        window.KuduExec.changeDir(newValue.path());
    }

    // updateSelectedOnly return a promise since it also update its children
    updateSelectedOnly = function (newValue) {
        viewModel.selected(newValue); // update selected
        updateFileSystemWatcher(newValue.path()); // update the filesystem watcher, always accompany selected(newValue)
        // in old code, children are ONLY FORCE update if navigate using File Explorer, in NEW CODE, we standardize them
        return newValue.fetchChildren(/* force */ true); // update children of selected
    }

    window.KuduExec.completePath = function (value, dirOnly) {
        var subDirs = value.toLowerCase().split(/\/|\\/),
            cur = viewModel.selected(),
            curToken = "";

        while (subDirs.length && cur) {
            curToken = subDirs.shift();
            if (curToken === ".." && cur && cur.parent) {
                cur = cur.parent;
                continue;
            }

            if (!cur.children || !cur.children().length) {
                cur = null;
                break;
            }

            cur = $.grep(cur.children(), function (elm) {
                if (dirOnly && !elm.isDirectory()) {
                    return false;
                }

                return subDirs.length ? (elm.name().toLowerCase() === curToken) : elm.name().toLowerCase().indexOf(curToken) === 0;
            });

            if (cur && cur.length === 1 && subDirs.length) {
                // If there's more path to traverse and we have exactly one match, return
                cur = cur[0];
            }
        }
        if (cur) {
            return $.map(cur, function (elm) { return elm.name(); });
        }
    };

    //monitor file upload progress
    function copyProgressHandlingFunction(e, uniqueUrl, forceUpdateModal) {
        if (e && uniqueUrl && e.lengthComputable) {
            copyObjectsManager.addCopyStats(uniqueUrl, e.loaded, e.total); //add/update stats
        }
        var perc = copyObjectsManager.getCurrentPercentCompletion(); // perc-per-total transaction
        var copyObjs = copyObjectsManager.getCopyStats();

        $('#copy-percentage').text(perc + "%");

        if (perc != 100 && perc != 0) {
            viewModel.isTransferInProgress(true);
        }

        //handler for clearing out cache once it gets too large
        var currentObjCount = Object.keys(copyObjs).length;
        if (currentObjCount > 2000) {
            for (var i = 0; i < 1000; i++) { //delete oldest 1000 copy prog objects
                copyObjectsManager.removeAtIndex(0);
            }
            var date = new Date();
            copyObjectsManager.setInfoMessage('Cache was partially auto-cleared at ' + date.toLocaleString() + ' for performance improvements');
        }

        if ($('#files-transfered-modal').is(':visible') || forceUpdateModal) { // update if modal visible
            viewModel.copyProgStats(copyObjs); // update viewmodel

            var modalHeaderText = '';
            if (perc < 100) {
                modalHeaderText = 'Transferred Files (' + perc + '%).';
            } else {
                modalHeaderText = ' Transferred Files (' + perc + '%).';
            }
            modalHeaderText += ' ' + ((_temp = copyObjectsManager.getInfoMessage()) ? _temp : "");
            $('#files-transfered-modal .modal-header').html(modalHeaderText);
        }

    }

    function setupFileSystemWatcher() {
        updateFileSystemWatcher(null);
    }

    function updateFileSystemWatcher(newValue) {
        window.viewModel = viewModel;
        fileSystemHub.server.register(newValue);
    }

    window.KuduExec.updateFileSystemWatcher = updateFileSystemWatcher;

    function stashCurrentSelection(selected) {
        if (window.history && window.history.pushState) {
            // shunTODO, onpopstate does not care about this value
            window.history.pushState(selected.path(), selected.name());
        }
    }

    function getLocalStorageSetting(name, defaultValue) {
        try {
            var value = window.localStorage[name];
            if (value === undefined) {
                return defaultValue;
            }

            if (typeof (defaultValue) === "number") {
                return parseInt(value);
            } else if (typeof (defaultValue) === "boolean") {
                return !!value;
            } else {
                return value;
            }
        } catch (e) {
            return defaultValue;
        }
    }

    window.onpopstate = function (evt) {
        if (viewModel.fileEdit()) {
            // If we're editing, exit the editing.
            viewModel.fileEdit(null);
        } else {
            var selected = viewModel.selected();
            if (selected.parent) {
                updateSelectedAndNotifyCommandLine(selected.parent);
            }
        }
    };

    $("#fileList").on("keydown", "input[type=text]", function (evt) {
        var context = ko.contextFor(this),
            data = context.$data;

        if (evt.which === 27) { // Cancel if Esc is pressed.
            data.parent.children.remove(data);
            return false;
        }
    });

    $("#createFolder").click(function (evt) {
        evt.preventDefault();

        var newFolder = new node({ name: "", type: "dir", href: "", editing: true }, viewModel.selected());
        $(this).prop("disabled", true);
        viewModel.selected().children.unshift(newFolder);
        $("#fileList input[type='text']").focus();

        newFolder.name.subscribe(function (value) {
            newFolder.href = trimTrailingSlash(newFolder.parent.href) + "/" + value + "/";
            newFolder._href(newFolder.href);
            newFolder.editing(false);
            Vfs.createFolder(newFolder).fail(function () {
                viewModel.selected().children.remove(newFolder);
            });
            $("#createFolder").prop("disabled", false);
        });
    });

    $("#createFile").click(function (evt) {
        evt.preventDefault();

        var newFile = new node({ name: "", type: "", href: "", editing: true }, viewModel.selected());
        $(this).prop("disabled", true);
        viewModel.selected().children.unshift(newFile);
        $("#fileList input[type='text']").focus();

        newFile.name.subscribe(function (value) {
            newFile.href = trimTrailingSlash(newFile.parent.href) + "/" + value;
            newFile._href(newFile.href);
            newFile.editing(false);
            Vfs.createFile(newFile).fail(function () {
                viewModel.selected().children.remove(newFile);
            });
            $("#createFile").prop("disabled", false);
        });
    });

    // Drag and drop
    $("#fileList")
        .on("dragenter dragover", function (e) {
            e.preventDefault();
            e.stopPropagation();
            if (_isZipFile(e)) {
                $(".show-on-hover").addClass('upload-unzip-show');
            }
        })
        .on("drop", function (evt) {
            evt.preventDefault();
            evt.stopPropagation();

            $(".show-on-hover").removeClass('upload-unzip-show');
            $(".show-on-hover").removeClass('upload-unzip-hover');
            $("#copy-percentage").text("");
            var dir = viewModel.selected();
            viewModel.processing(true);
            _getInputFiles(evt).done(function (files) {
                Vfs.addFiles(files).always(function () {
                    dir.fetchChildren( /* force */ true);
                    viewModel.processing(false);
                    $("#copy-percentage").text("");
                });
            });
        }).on("dragleave", function (e) {
            $(".show-on-hover").removeClass('upload-unzip-show');
        });

    $("#upload-unzip")
        .on("dragenter dragover", function (e) {
            $(".show-on-hover").addClass('upload-unzip-hover');
        })
        .on("drop", function (evt) {
            evt.preventDefault();
            evt.stopPropagation();

            $(".show-on-hover").removeClass('upload-unzip-show');
            $(".show-on-hover").removeClass('upload-unzip-hover');
            var dir = viewModel.selected();
            viewModel.processing(true);
            _getInputFiles(evt).done(function (files) {
                Vfs.addFiles(files, _isZipFile(evt)).always(function () {
                    dir.fetchChildren( /* force */ true);
                    viewModel.processing(false);
                });
            });
        }).on("dragleave", function (e) {
            $(".show-on-hover").removeClass('upload-unzip-hover');
        });

    var defaults = { fileList: '40%', console: '45%' };
    $('#resizeHandle .down')
        .on('click', function (e) {
            var fileList = $('#fileList'),
                console = window.$KuduExecConsole;
            if (!console.is(':visible')) {
                return;
            } else if (fileList.is(":visible")) {
                console.slideDown(function () {
                    console.hide();
                    fileList.css('height', '85%');
                });
            } else {
                console.css('height', defaults.console);
                fileList.css('height', defaults.fileList);
                fileList.show();
            }
        });

    $('#resizeHandle .up')
        .on('click', function (e) {
            var fileList = $('#fileList'),
                console = window.$KuduExecConsole;
            if (!fileList.is(':visible')) {
                return;
            } else if (console.is(':visible')) {
                fileList.slideUp(function () {
                    fileList.hide();
                    console.css('height', '85%');
                });
            } else {
                fileList.css('height', defaults.fileList);
                console.css('height', defaults.console);
                console.show();
            }
        });

    function _getInputFiles(evt) {
        var dt = evt.originalEvent.dataTransfer,
            items = evt.originalEvent.dataTransfer.items,
            isSupportedGetAsEntry = typeof DataTransferItem !== "undefined" && !!(DataTransferItem.prototype.webkitGetAsEntry || DataTransferItem.prototype.getAsEntry);

        if (items && items.length && isSupportedGetAsEntry) {
            return whenArray($.map(items, function (item) {
                if (item.kind === 'file') {
                    var entry = (item.webkitGetAsEntry || item.getAsEntry).apply(item);
                    return _processEntry(entry);
                }
            })).pipe(function () {
                return Array.prototype.concat.apply([], arguments);
            })
        } else {
            return $.Deferred().resolveWith(null, [$.map(dt.files, function (e) {
                return { name: e.name, contents: e };
            })]);
        }
    }

    function _isZipFile(evt) {
        if (evt.originalEvent.dataTransfer === null) {
            //dataTransfer is null in Edge / IE. Assume a zip file. Unzip will no-op
            return true;
        }
        var items = evt.originalEvent.dataTransfer.items || evt.originalEvent.dataTransfer.files;
        if (items) {
            var filesArray = $.map(items, function (item) {
                if (item.type === 'application/x-zip-compressed' || item.type === 'application/zip' || item.type === '')
                    return item;
            });
            if (filesArray && filesArray.length === items.length) {
                return true;
            } else {
                return false;
            }
        } else {
            //if both items and files are undefined, that means the browser (IE, FF)
            //doesn't support showing files on dragging, only on dropping, then assume a zip file.
            //Extracting will no-op if it's not a zip file anyway.
            return true;
        }
    }

    function _processEntry(entry, parentPath) {
        parentPath = parentPath || '';
        var deferred = $.Deferred();
        if (entry.isFile) {
            entry.file(function (file) {
                deferred.resolveWith(null, [{ name: parentPath + '/' + entry.name, contents: file }]);
            });
        } else {
            var dirReader = entry.createReader();
            var totalEntriesInDir = [];
            var directoryCallback = function (entries) {
                if (entries.length) {
                    totalEntriesInDir = totalEntriesInDir.concat(entries);
                    // keep reading
                    dirReader.readEntries(directoryCallback);
                } else {
                    // finished reading, process totalEntriesInDir
                    var directoryPath = parentPath + '/' + entry.name;
                    whenArray($.map(totalEntriesInDir, function (e) {
                        return _processEntry(e, directoryPath);
                    })).done(function () {
                        deferred.resolveWith(null, [Array.prototype.concat.apply([], arguments)]);
                    });
                }
            }
            dirReader.readEntries(directoryCallback);
        }
        return deferred.promise();
    }

    function whenArray(deferreds) {
        return $.when.apply($, deferreds);
    }

    function trimTrailingSlash(input) {
        return input.replace(/(\/|\\)$/, '');
    }

    function showError(error) {
        if (error.status === 403) {
            $('#403-error-modal').modal();
        }
        viewModel.processing(false);
        // Should we also display a '403 Forbidden' toast? It's probably too much.
        // showErrorAsToast(error);
    }

    function showErrorAsToast(error) {
        viewModel.processing(false);
        // Check if 'error' has a status property.
        // If true, treat as xhr response, otherwise string.
        if (error.status) {
            try {
                var message = JSON.parse(error.responseText).Message;
            }
            catch (e) {
                // error.responseText may be poisoned with HTML
                // (i.e. session expires and the 403 Forbidden response from App Service contains tons of markup)
                // Let's just ignore it if that's the case. We would need Cortana or something to parse that and
                // extract a meaningful message.
                if (!(/\/i.test(error.responseText))) {
                    var message = error.responseText;
                }
            }
            var status = error.status;
            var statusText = error.statusText;
            var textToRender = status + ' ' + statusText + (typeof message !== 'undefined' ? ': ' + message : '');
            toast(textToRender);
        }
        // 'error' is a string
        else toast(error);
    }

});

// Toast notifications for backend errors
function toast(errorMsg) {
    var scaffold = '\

\

\
                \

\

\

ERROR
' +
        errorMsg +
        '
\

';
    var item = $(scaffold);
    $('#toast').append($(item));
    $(item).animate({ 'right': '12px' }, 'fast');
    $('#toast').on('click', '#toast-close', function () {
        var notification = $(this).parent();
        notification.animate({ 'right': '-400px' }, function () {
            notification.remove();
        });
    });
}

function removeAllToasts() {
    $('.notification').remove();
}


text:
<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace CF\gavoters;

/**
 * Description of BuildLatestVoters
 *
 * @author james
 */
class BuildLatestVoters {
    //put your code here
    public function getNativeSQL() {
        return <<<EOT
DROP TABLE if exists georgia_matched_voters;
CREATE TABLE georgia_matched_voters
SELECT vtrs.* FROM (
	SELECT v2.RegistrationNbr,MAX(v2.ExportDate) as ExportDate FROM (
		SELECT v.* FROM georgia_matches g
		JOIN Voters AS v ON g.ga_voter_id_2 = v.RegistrationNbr
	) AS v2 GROUP BY v2.RegistrationNbr
) AS v3
JOIN Voters AS vtrs ON v3.RegistrationNbr = vtrs.RegistrationNbr AND v3.ExportDate = vtrs.ExportDate
EOT;
    }
}


text:
package org.camunda.bpm.engine.impl.runtime;

import java.util.ArrayList;
import java.util.List;

import org.camunda.bpm.engine.impl.ProcessEngineLogger;
import org.camunda.bpm.engine.impl.bpmn.helper.BpmnProperties;
import org.camunda.bpm.engine.impl.bpmn.parser.ConditionalEventDefinition;
import org.camunda.bpm.engine.impl.bpmn.parser.EventSubscriptionDeclaration;
import org.camunda.bpm.engine.impl.cmd.CommandLogger;
import org.camunda.bpm.engine.impl.event.EventType;
import org.camunda.bpm.engine.impl.interceptor.CommandContext;
import org.camunda.bpm.engine.impl.persistence.deploy.cache.DeploymentCache;
import org.camunda.bpm.engine.impl.persistence.entity.EventSubscriptionEntity;
import org.camunda.bpm.engine.impl.persistence.entity.EventSubscriptionManager;
import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity;
import org.camunda.bpm.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.camunda.bpm.engine.impl.pvm.process.ActivityImpl;

/**
 * @author Yana Vasileva
 *
 */
public class DefaultConditionHandler implements ConditionHandler {

  private final static CommandLogger LOG = ProcessEngineLogger.CMD_LOGGER;

  @Override
  public List<ConditionHandlerResult> evaluateStartCondition(CommandContext commandContext, ConditionSet conditionSet) {
    if (conditionSet.getProcessDefinitionId() == null) {
      return evaluateConditionStartByEventSubscription(commandContext, conditionSet);
    } else {
      return evaluateConditionStartByProcessDefinitionId(commandContext, conditionSet, conditionSet.getProcessDefinitionId());
    }
  }

  protected List<ConditionHandlerResult> evaluateConditionStartByEventSubscription(CommandContext commandContext, ConditionSet conditionSet) {
    List<EventSubscriptionEntity> subscriptions = findConditionalStartEventSubscriptions(commandContext, conditionSet);
    if (subscriptions.isEmpty()) {
      throw LOG.exceptionWhenEvaluatingConditionalStartEvent();
    }
    List<ConditionHandlerResult> results = new ArrayList<ConditionHandlerResult>();
    for (EventSubscriptionEntity subscription : subscriptions) {

      ProcessDefinitionEntity processDefinition = subscription.getProcessDefinition();
      if (!processDefinition.isSuspended()) {

        ActivityImpl activity = subscription.getActivity();

        if (evaluateCondition(conditionSet, activity)) {
          results.add(new ConditionHandlerResult(processDefinition, activity));
        }

      }
    }

    return results;
  }

  protected List<EventSubscriptionEntity> findConditionalStartEventSubscriptions(CommandContext commandContext, ConditionSet conditionSet) {
    EventSubscriptionManager eventSubscriptionManager = commandContext.getEventSubscriptionManager();

    if (conditionSet.isTenantIdSet) {
      return eventSubscriptionManager.findConditionalStartEventSubscriptionByTenantId(conditionSet.getTenantId());
    } else {
      return eventSubscriptionManager.findConditionalStartEventSubscription();
    }
  }

  protected List<ConditionHandlerResult> evaluateConditionStartByProcessDefinitionId(CommandContext commandContext, ConditionSet conditionSet,
      String processDefinitionId) {
    DeploymentCache deploymentCache = commandContext.getProcessEngineConfiguration().getDeploymentCache();
    ProcessDefinitionEntity processDefinition = deploymentCache.findDeployedProcessDefinitionById(processDefinitionId);

    List<ConditionHandlerResult> results = new ArrayList<ConditionHandlerResult>();

    if (processDefinition != null && !processDefinition.isSuspended()) {
      List<ActivityImpl> activities = findConditionalStartEventActivities(processDefinition);
      if (activities.isEmpty()) {
        throw LOG.exceptionWhenEvaluatingConditionalStartEventByProcessDefinition(processDefinitionId);
      }
      for (ActivityImpl activity : activities) {
        if (evaluateCondition(conditionSet, activity)) {
          results.add(new ConditionHandlerResult(processDefinition, activity));
        }
      }
    }
    return results;
  }

  protected List<ActivityImpl> findConditionalStartEventActivities(ProcessDefinitionEntity processDefinition) {
    List<ActivityImpl> activities = new ArrayList<ActivityImpl>();
    for (EventSubscriptionDeclaration declaration : ConditionalEventDefinition.getDeclarationsForScope(processDefinition).values()) {
      if (isConditionStartEvent(declaration)) {
        activities.add(((ConditionalEventDefinition) declaration).getConditionalActivity());
      }
    }
    return activities;
  }

  protected boolean isConditionStartEvent(EventSubscriptionDeclaration declaration) {
    return EventType.CONDITONAL.name().equals(declaration.getEventType()) && declaration.isStartEvent();
  }

  protected boolean evaluateCondition(ConditionSet conditionSet, ActivityImpl activity) {
    ExecutionEntity temporaryExecution = new ExecutionEntity();
    if (conditionSet.getVariables() != null) {
      temporaryExecution.initializeVariableStore(conditionSet.getVariables());
    }
    temporaryExecution.setProcessDefinition(activity.getProcessDefinition());

    ConditionalEventDefinition conditionalEventDefinition = activity.getProperties().get(BpmnProperties.CONDITIONAL_EVENT_DEFINITION);
    if (conditionalEventDefinition.getVariableName() == null || conditionSet.getVariables().containsKey(conditionalEventDefinition.getVariableName())) {
      return conditionalEventDefinition.tryEvaluate(temporaryExecution);
    } else {
      return false;
    }
  }

}


text:
@implementation UIView (LGHelper)

#pragma mark - Frame

- (void)setFrame:(CGRect)frame integral:(BOOL)integral
{
    self.frame = (integral && kLGHelperPlusUIViewIsNotRetina ? CGRectIntegral(frame) : frame);
}

#pragma mark - Origin

- (void)setOrigin:(CGPoint)origin
{
    [self setOrigin:origin integral:NO];
}

- (void)setOrigin:(CGPoint)origin integral:(BOOL)integral
{
    CGRect newFrame = self.frame;
    newFrame.origin = origin;
    self.frame = (integral && kLGHelperPlusUIViewIsNotRetina ? CGRectIntegral(newFrame) : newFrame);
}

- (CGPoint)origin
{
    return self.frame.origin;
}

#pragma mark - Origin X

- (void)setOriginX:(CGFloat)x
{
    [self setOriginX:x integral:NO];
}

- (void)setOriginX:(CGFloat)x integral:(BOOL)integral
{
    CGRect newFrame = self.frame;
    newFrame.origin.x = x;
    self.frame = (integral && kLGHelperPlusUIViewIsNotRetina ? CGRectIntegral(newFrame) : newFrame);
}

- (CGFloat)originX
{
    return self.frame.origin.x;
}

#pragma mark - Origin Y

- (void)setOriginY:(CGFloat)y
{
    [self setOriginY:y integral:NO];
}

- (void)setOriginY:(CGFloat)y integral:(BOOL)integral
{
    CGRect newFrame = self.frame;
    newFrame.origin.y = y;
    self.frame = (integral && kLGHelperPlusUIViewIsNotRetina ? CGRectIntegral(newFrame) : newFrame);
}

- (CGFloat)originY
{
    return self.frame.origin.y;
}

#pragma mark - Size

- (void)setSize:(CGSize)size
{
    [self setSize:size integral:NO];
}

- (void)setSize:(CGSize)size integral:(BOOL)integral
{
    CGRect newFrame = self.frame;
    newFrame.size = size;
    self.frame = (integral && kLGHelperPlusUIViewIsNotRetina ? CGRectIntegral(newFrame) : newFrame);
}

- (CGSize)size
{
    return self.frame.size;
}

#pragma mark - Width

- (void)setWidth:(CGFloat)width
{
    [self setWidth:width integral:NO];
}

- (void)setWidth:(CGFloat)width integral:(BOOL)integral
{
    CGRect newFrame = self.frame;
    newFrame.size.width = width;
    self.frame = (integral && kLGHelperPlusUIViewIsNotRetina ? CGRectIntegral(newFrame) : newFrame);
}

- (CGFloat)width
{
    return self.frame.size.width;
}

#pragma mark - Height

- (void)setHeight:(CGFloat)height
{
    [self setHeight:height integral:NO];
}

- (void)setHeight:(CGFloat)height integral:(BOOL)integral
{
    CGRect newFrame = self.frame;
    newFrame.size.height = height;
    self.frame = (integral && kLGHelperPlusUIViewIsNotRetina ? CGRectIntegral(newFrame) : newFrame);
}

- (CGFloat)height
{
    return self.frame.size.height;
}

#pragma mark - Center

- (void)setCenter:(CGPoint)center integral:(BOOL)integral
{
    self.center = center;
    if (integral && kLGHelperPlusUIViewIsNotRetina) self.frame = CGRectIntegral(self.frame);
}

#pragma mark - Center X

- (void)setCenterX:(CGFloat)centerX
{
    [self setCenterX:centerX integral:NO];
}

- (void)setCenterX:(CGFloat)centerX integral:(BOOL)integral
{
    self.center = CGPointMake(centerX, self.center.y);
    if (integral && kLGHelperPlusUIViewIsNotRetina) self.frame = CGRectIntegral(self.frame);
}

- (CGFloat)centerX
{
    return self.center.x;
}

#pragma mark - Center Y

- (void)setCenterY:(CGFloat)centerY
{
    [self setCenterY:centerY integral:NO];
}

- (void)setCenterY:(CGFloat)centerY integral:(BOOL)integral
{
    self.center = CGPointMake(self.center.x, centerY);
    if (integral && kLGHelperPlusUIViewIsNotRetina) self.frame = CGRectIntegral(self.frame);
}

- (CGFloat)centerY
{
    return self.center.y;
}

#pragma mark -

- (CGFloat)bottomY
{
    return self.frame.origin.y+self.frame.size.height;
}

- (CGFloat)rightX
{
    return self.frame.origin.x+self.frame.size.width;
}

#pragma mark -

- (void)makeIntegral
{
    self.frame = CGRectIntegral(self.frame);
}

- (void)sizeInvalidate
{
    [self sizeToFit];
    [self layoutIfNeeded];
}

- (void)setAllSubviewsHidden:(BOOL)hidden exept:(NSArray *)viewsArray
{
    if (!self.subviews.count) return;

    for (UIView *view in self.subviews)
        if (![viewsArray containsObject:view])
            view.hidden = hidden;
}

- (void)setAllSubviewsAlpha:(CGFloat)alpha exept:(NSArray *)viewsArray
{
    if (!self.subviews.count) return;

    for (UIView *view in self.subviews)
        if (![viewsArray containsObject:view])
            view.alpha = alpha;
}

#pragma mark -

- (UIView *)firstResponder
{
    return [LGHelper firstResponderInView:self];
}

@end


text:
package cmd

import (
	"fmt"
	"agenda/service"
	"github.com/spf13/cobra"
)

// exit_meetingCmd represents the exit_meeting command
var exit_meetingCmd = &cobra.Command{
	Use:   "exit_meeting -t [meeting title]",
	Short: "exit a meeting, if the paticipator of the meeting is none, we will delete the meeting",
	Long: `Input command mode like : exit_meeting -t Golang`,
	Run: func(cmd *cobra.Command, args []string) {
		// TODO: Work your own magic here
		tmp_t, _ := cmd.Flags().GetString("title")
		if service.GetFlag() == true {
			service.Exit_meeting(tmp_t)
		} else {
			fmt.Println("You don't log in!")
		}

	},
}

func init() {
	RootCmd.AddCommand(exit_meetingCmd)
	// Here you will define your flags and configuration settings.

	// Cobra supports Persistent Flags which will work for this command
	// and all subcommands, e.g.:
	// exit_meetingCmd.PersistentFlags().String("foo", "", "A help for foo")

	// Cobra supports local flags which will only run when this command
	// is called directly, e.g.:
	// exit_meetingCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
	exit_meetingCmd.Flags().StringP("title", "t", "", "meeting title")

}


text:
import Gulp from 'gulp';
import GulpLoadPlugins from 'gulp-load-plugins';

const _ = GulpLoadPlugins();

Gulp.task('build:scripts',
  () => Gulp.src('react-chartist-tooltip.babel.js')
            .pipe(_.rename('react-chartist-tooltip.js'))
            .pipe(_.babel({
              stage: 0,
              loose: 'all'
            }))
            .pipe(Gulp.dest('.'))
);


text:
<?php

/*

This shows a cursory list of running VMs managed by libvirt and their stats.
Requires libvirt php extension (http://libvirt.org/php/):
  sudo apt-get install php5-libvirt-php

To enable this extension, add/tweak the following to your config.inc.php

$settings['extensions']['libvirt'] = true;
$settings['libvirt_connection'] = array(
    'url' => 'qemu:///system', // For xen do 'xen:///' instead
    'credentials' => NULL
);

*/

/* Linfo
 *
 * Copyright (c) 2018 Joe Gillotti
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

namespace Linfo\Extension;

use Linfo\Linfo;
use Linfo\Common;
use Linfo\Meta\Errors;
use Linfo\Meta\Timer;

/**
 * Get status on libvirt VMs.
 */
class Libvirt implements Extension
{
    private
        $VMs = [],
        $connection = false,
        $connectionSettings = [],
        $hypervisor = false,
        $res = false;

    public function __construct(Linfo $linfo)
    {
        $settings = $linfo->getSettings();

        $this->connectionSettings = $settings['libvirt_connection'];
    }

    private function connect()
    {
        if (!($this->connection =
            @libvirt_connect($this->connectionSettings['url'], true))) {
            Errors::add('libvirt extension', 'Error connecting');
            $this->res = false;

            return false;
        }

        return true;
    }

    public function work()
    {
        $t = new Timer('libvirt extension');

        if (!extension_loaded('libvirt')) {
            Errors::add('libvirt extension', 'Libvirt PHP extension not installed');
            $this->res = false;

            return;
        }

        if (!$this->connect()) {
            Errors::add('libvirt extension', 'Failed connecting');
            return;
        }

        if ($hypervisor = libvirt_connect_get_hypervisor($this->connection)) {
          if (isset($hypervisor['hypervisor_string']) && $hypervisor['hypervisor_string'] != '') {
              $this->hypervisor = $hypervisor['hypervisor_string'];
          } else if (isset($hypervisor['hypervisor']) && $hypervisor['hypervisor'] != '') {
              $this->hypervisor = $hypervisor['hypervisor'];
          }
        }

        if (!($doms = libvirt_list_domains($this->connection))) {
            Errors::add('libvirt extension', 'Failed getting domain list');
            $this->res = false;
            return;
        }

        foreach ($doms as $name) {
            if (!($domain = libvirt_domain_lookup_by_name($this->connection, $name))) {
                continue;
            }

            if (!($info = libvirt_domain_get_info($domain)) || !is_array($info)) {
                continue;
            }

            $info['autostart'] = libvirt_domain_get_autostart($domain);

            if ($info['autostart'] == 1) {
                $info['autostart'] = 'Yes';
            } elseif ($info['autostart'] == 0) {
                $info['autostart'] = 'No';
            } else {
                $info['autostart'] = 'N/A';
            }

            $info['nets'] = [];

            $nets = @libvirt_domain_get_interface_devices($domain);

            foreach ($nets as $key => $net) {
                if (!is_numeric($key)) {
                    continue;
                }
                $info['nets'][] = $net;
            }

            $info['storage'] = [];

            foreach ((array) @libvirt_domain_get_disk_devices($domain) as $blockName) {
                if (!is_string($blockName)) {
                    continue;
                }

                // Sometime device exists but libvirt fails to get more docs. just settle for device name
                if (!($blockInfo = @libvirt_domain_get_block_info($domain, $blockName)) || !is_array($blockInfo)) {
                    $info['storage'][] = array(
                        'device' => $blockName,
                    );
                    continue;
                }

                if ($stats = @libvirt_domain_block_stats($domain, $blockName)) {
                    $blockInfo['stats'] = $stats;
                }

                if (isset($blockInfo['partition']) && !isset($blockInfo['file'])) {
                    $blockInfo['file'] = $blockInfo['partition'];
                }

                $info['storage'][] = $blockInfo;
            }

            $this->VMs[$name] = $info;
        }

        $this->res = true;
    }

    public function result()
    {
        if (!$this->res) {
            return false;
        }

        $rows[] = array(
            'type' => 'header',
            'columns' => array(
                'VM Name',
                'Status',
                'RAM Allocation',
                'CPUs',
                'CPU Time',
                'Autostart',
                'Block Storage',
                'Network Devices',
            ),
        );

        $running = 0;
        $allram = 0;

        foreach ($this->VMs as $name => $info) {
            $disks = [];

            foreach ($info['storage'] as $disk) {
                $extra_info = [];

                if (isset($disk['capacity'])) {
                    $extra_info[] = Common::byteConvert($disk['capacity'], 2) . ' size';
                }

                if (isset($disk['stats']) && is_array($disk['stats'])) {
                    $extra_info[] = Common::byteConvert($disk['stats']['rd_bytes'], 2) . ' read';
                    $extra_info[] = Common::byteConvert($disk['stats']['wr_bytes'], 2) . ' written';
                }

                $line = $disk['device'];

                if (isset($disk['file'])) {
                    $line .= ': ' . $disk['file'];
                }

                if (count($extra_info) > 0) {
                    $line .= ' ('.implode(', ', $extra_info).')';
                }

                $disks[] = $line;
            }

            $rows[] = array(
                'type' => 'values',
                'columns' => array(
                    $name,
                    $info['state'] == 1 ? 'On' : 'Off',
                    Common::byteConvert($info['memory'] * 1024, 2),
                    $info['nrVirtCpu'],
                    $info['cpuUsed'] ? $info['cpuUsed'] : 'N/A',
                    $info['autostart'],
                    $disks ? implode('
', $disks) : 'None',
                    $info['nets'] ? implode('
', $info['nets']) : 'None',
                ),
            );

            if ($info['state'] == 1) {
                $running++;
                $allram += $info['memory'];
            }

        }

        // Give it off
        return array(
            'root_title' => 'libvirt Virtual Machines '.($this->hypervisor ? ' ('.$this->hypervisor.') ' : '').
                            '('.$running.' running - using '.Common::byteConvert($allram * 1024, 2).' RAM)',
            'rows' => $rows,
        );
    }
}


text:
<?php

namespace backend\controllers;

use Yii;
use common\models\Ticket;
use backend\models\TicketSearch;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * TicketController implements the CRUD actions for Ticket model.
 */
class TicketController extends PreventguestController
{
    public function behaviors()
    {
        return array_merge([
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ], parent::behaviors());
    }

    /**
     * Lists all Ticket models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new TicketSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Ticket model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Ticket model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Ticket();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Ticket model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post())) {
            if ($model->isAttributeChanged('board_id')) {
                $model->setAttribute('column_id', 0);
            }
            if ($model->save()) {
                return $this->redirect(['view', 'id' => $model->id]);
            }
        }
        return $this->render('update', [
            'model' => $model,
        ]);
    }

    /**
     * Deletes an existing Ticket model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Ticket model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Ticket the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Ticket::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<sem:triples uri="http://www.lds.org/vrl/specific-reproductions/liahona-poster-set-2-picture" xmlns:sem="http://marklogic.com/semantics">
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/specific-reproductions/liahona-poster-set-2-picture</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#prefLabel</sem:predicate>
    <sem:object datatype="xsd:string" xml:lang="eng">Liahona Poster Set 2 (Picture)</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/specific-reproductions/liahona-poster-set-2-picture</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#inScheme</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept-scheme/vrl</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/vrl/specific-reproductions/liahona-poster-set-2-picture</sem:subject>
    <sem:predicate>http://www.lds.org/core#entityType</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/Topic</sem:object>
  </sem:triple>
</sem:triples>


text:
TemplateStats = {};

ResetStats = function ResetStats(layoutName) {
  TemplateStats[layoutName] = {
    rendered: 0,
    destroyed: 0
  };
}

ResetStats('layout1');

Template.layout1.rendered = function() {
  TemplateStats.layout1.rendered++;
};

Template.layout1.destroyed = function() {
  TemplateStats.layout1.destroyed++;
};


text:
<?php
namespace Dahl;

class Autoload
{
    /**
     * Holds basedirs for namespaces.
     *
     * @var array
     * @access protected
     */
    static protected $_baseDirs = array();

    /**
     * Register a namespace base dir for autoloading.
     *
     * @param string $namespace
     * @param string $dir
     * @static
     * @access public
     * @return void
     */
    static public function registerBase($namespace, $dir)
    {
        $nameArr = explode('\\', $namespace);
        $currentDir = &self::$_baseDirs;
        foreach ($nameArr as $name) {
            if (!isset($currentDir[$name])) {
                $currentDir[$name] = array();
            }
            $currentDir = &$currentDir[$name];
        }

        $currentDir = $dir;
    }

    /**
     * Register spl autoload function.
     *
     * @static
     * @access public
     * @return void
     */
    static public function register()
    {
        spl_autoload_register(array('Dahl\\Autoload', 'autoload'), true, true);
    }

    /**
     * Autoload function.
     *
     * @param string $class
     * @static
     * @access public
     * @return boolean
     */
    static public function autoload($class)
    {
        $classArr   = explode('\\', $class);
        $currentDir = self::$_baseDirs;
        $filename   = '';
        $isFound    = false;
        foreach ($classArr as $name) {
            if ($isFound) {
                $filename .= DIRECTORY_SEPARATOR . $name;
                continue;
            }
            if (isset($currentDir[$name])) {
                $currentDir = $currentDir[$name];
            } elseif (isset($currentDir['*'])) {
                $currentDir = $currentDir['*'];
                $filename .= DIRECTORY_SEPARATOR . $name;
            }
            if (is_string($currentDir)) {
                $isFound = true;
            }
        }
        if (is_string($currentDir)) {
            $file = $currentDir . $filename . '.php';
            include $file;

            return true;
        }

        return false;
    }
}

Autoload::registerBase('Dahl\\PhpTerm', dirname(__file__));
Autoload::register();


text:
module OData
  module Model
    # Provides the methods that make up the query interface for OData::Model.
    module Query
      extend ActiveSupport::Concern

      included do
        # ...
      end

      # Methods mixed in at the class level.
      module ClassMethods
        # Gives you a handle to get at everything as an Enumerable
        # @return [OData::Model::Query]
        def all
          OData::Model::QueryProxy.new(self)
        end

        # Starts a query chain with a filter for a given property's name.
        # @param property_name [Hash,to_sym]
        # @return [OData::Model::Query]
        def where(arguments)
          query_proxy = OData::Model::QueryProxy.new(self)
          query_proxy.where(arguments)
        end

        # Starts a query chain with a limit to entities returned.
        # @param value [to_i]
        # @return [OData::Model::Query]
        def limit(value)
          query_proxy = OData::Model::QueryProxy.new(self)
          query_proxy.limit(value.to_i)
        end

        # Starts a query chain with the number of entities to skip.
        # @param value [to_i]
        # @return [OData::Model::Query]
        def skip(value)
          query_proxy = OData::Model::QueryProxy.new(self)
          query_proxy.skip(value.to_i)
        end

        # Starts a query chain with a order operator for a given property's name.
        # @param property_name [to_sym]
        # @return [OData::Model::Query]
        def order_by(property_name)
          query_proxy = OData::Model::QueryProxy.new(self)
          query_proxy.order_by(property_name.to_sym)
        end

        # Starts a query chain with a list of properties to select.
        # @param property_name [to_sym]
        # @return [OData::Model::Query]
        def select(property_name)
          query_proxy = OData::Model::QueryProxy.new(self)
          query_proxy.select(property_name.to_sym)
        end

        # Enables lookup of model entities by their primary key.
        # @param primary_key_value [to_s] primary key value to lookup
        # @return [OData::Model,nil]
        def [](primary_key_value)
          entity = odata_entity_set[primary_key_value]
          return entity if entity.nil?
          model = self.new
          model.instance_variable_set(:@odata_entity, entity)
          model
        end
        alias_method :find, :[]
      end
    end
  end
end


text:
import abc
import abjad
import collections
from abjad.tools import abctools
from abjad.tools import lilypondfiletools
from abjad.tools import metertools
from abjad.tools import markuptools

class TimespanMaker(abctools.AbjadValueObject):
    r'''Abstract base class for timespan makers.
    '''

    ### CLASS VARIABLES ###

    __slots__ = (
        '_output_masks',
        '_padding',
        '_seed',
        '_timespan_specifier',
        )

    ### INITIALIZER ###

    @abc.abstractmethod
    def __init__(
        self,
        division_masks=None,
        padding=None,
        seed=None,
        timespan_specifier=None,
        ):
        import consort
        if division_masks is not None:
            if isinstance(division_masks, abjad.Pattern):
                division_masks = (division_masks,)
            division_masks = abjad.PatternList(
                items=division_masks,
                )
        self._output_masks = division_masks
        if padding is not None:
            padding = abjad.Duration(padding)
        self._padding = padding
        if seed is not None:
            seed = int(seed)
        self._seed = seed
        if timespan_specifier is not None:
            assert isinstance(timespan_specifier, consort.TimespanSpecifier)
        self._timespan_specifier = timespan_specifier

    ### SPECIAL METHODS ###

    def __call__(
        self,
        layer=None,
        music_specifiers=None,
        rotation=None,
        silenced_context_names=None,
        target_timespan=None,
        timespan_inventory=None,
        ):
        if not isinstance(timespan_inventory, abjad.TimespanList):
            timespan_inventory = abjad.TimespanList(
                timespan_inventory,
                )
        if target_timespan is None:
            if timespan_inventory:
                target_timespan = timespan_inventory.timespan
            else:
                raise TypeError
        assert isinstance(timespan_inventory, abjad.TimespanList)
        if not music_specifiers:
            return timespan_inventory
        music_specifiers = self._coerce_music_specifiers(music_specifiers)
        new_timespans = self._make_timespans(
            layer=layer,
            music_specifiers=music_specifiers,
            target_timespan=target_timespan,
            timespan_inventory=timespan_inventory,
            )
        self._cleanup_silent_timespans(
            layer=layer,
            silenced_context_names=silenced_context_names,
            timespans=new_timespans,
            )
        timespan_inventory.extend(new_timespans)
        timespan_inventory.sort()
        return timespan_inventory

    def __illustrate__(self, scale=None, target_timespan=None, **kwargs):
        target_timespan = target_timespan or abjad.Timespan(0, 16)
        assert isinstance(target_timespan, abjad.Timespan)
        assert 0 < target_timespan.duration
        scale = scale or 1.5
        music_specifiers = collections.OrderedDict([
            ('A', 'A music'),
            ('B', 'B music'),
            ('C', 'C music'),
            ('D', 'D music'),
            ('E', 'E music'),
            ('F', 'F music'),
            ('G', 'G music'),
            ('H', 'H music'),
            ('I', 'I music'),
            ('J', 'J music'),
            ])
        timespan_inventory = self(
            layer=0,
            music_specifiers=music_specifiers,
            target_timespan=target_timespan,
            )
        ti_lilypond_file = timespan_inventory.__illustrate__(
            key='voice_name',
            range_=target_timespan,
            scale=scale,
            )
        ti_markup = ti_lilypond_file.items[-1]
        offset_counter = metertools.OffsetCounter(timespan_inventory)
        oc_lilypond_file = offset_counter.__illustrate__(
            range_=target_timespan,
            scale=scale,
            )
        oc_markup = oc_lilypond_file.items[-1]
        lilypond_file = lilypondfiletools.LilyPondFile.new(
            default_paper_size=['tabloid', 'landscape'],
            date_time_token=False,
            )
        lilypond_file.items.extend([
            abjad.String.normalize('''
            % Backport for pre 2.19.20 versions of LilyPond
            #(define-markup-command (overlay layout props args)
                (markup-list?)
                (apply ly:stencil-add (interpret-markup-list layout props args)))
            '''),
            ti_markup,
            markuptools.Markup.null().pad_around(2),
            oc_markup,
            ])
        lilypond_file.header_block.tagline = False
        return lilypond_file

    ### PRIVATE METHODS ###

    @staticmethod
    def _coerce_music_specifiers(music_specifiers):
        import consort
        result = collections.OrderedDict()
        prototype = (
            consort.MusicSpecifierSequence,
            consort.CompositeMusicSpecifier,
            )
        for context_name, music_specifier in music_specifiers.items():
            if music_specifier is None:
                music_specifier = [None]
            if not isinstance(music_specifier, prototype):
                music_specifier = consort.MusicSpecifierSequence(
                    music_specifiers=music_specifier,
                    )
            result[context_name] = music_specifier
        return result

    def _cleanup_silent_timespans(
        self,
        layer,
        silenced_context_names,
        timespans,
        ):
        import consort
        if not silenced_context_names or not timespans:
            return

        silent_timespans_by_context = {}
        for context_name in silenced_context_names:
            if context_name not in silent_timespans_by_context:
                silent_timespans_by_context[context_name] = \
                    abjad.TimespanList()

        sounding_timespans_by_context = {}
        sounding_timespans = abjad.TimespanList()

        for timespan in timespans:
            voice_name = timespan.voice_name
            if isinstance(timespan, consort.PerformedTimespan):
                if voice_name not in sounding_timespans_by_context:
                    sounding_timespans_by_context[voice_name] = \
                        abjad.TimespanList()
                sounding_timespans_by_context[voice_name].append(timespan)
                sounding_timespans.append(timespan)
            else:
                if voice_name not in silent_timespans_by_context:
                    silent_timespans_by_context[voice_name] = \
                        abjad.TimespanList()
                silent_timespans_by_context[voice_name].append(timespan)

        sounding_timespans.sort()
        sounding_timespans.compute_logical_or()

        # Create silences.
        for shard in sounding_timespans.partition(True):
            for context_name in silenced_context_names:
                timespan = consort.SilentTimespan(
                    layer=layer,
                    voice_name=context_name,
                    start_offset=shard.start_offset,
                    stop_offset=shard.stop_offset,
                    )
                silent_timespans_by_context[context_name].append(timespan)

        # Remove any overlap between performed and silent timespans.
        # Then add the silent timespans into the original timespan inventory.
        for context_name, silent_timespans in \
            sorted(silent_timespans_by_context.items()):
            silent_timespans.sort()
            if context_name in sounding_timespans_by_context:
                for timespan in sounding_timespans_by_context[context_name]:
                    silent_timespans - timespan
            timespans.extend(silent_timespans)

    ### PUBLIC METHODS ###

    def rotate(self, rotation):
        seed = self.seed or 0
        seed = seed + rotation
        return abjad.new(self, seed=seed)

    ### PUBLIC PROPERTIES ###

    @property
    def is_dependent(self):
        return False

    @property
    def division_masks(self):
        return self._output_masks

    @property
    def padding(self):
        return self._padding

    @property
    def seed(self):
        return self._seed

    @property
    def timespan_specifier(self):
        return self._timespan_specifier


text:
import Em from 'ember';

export default Em.Mixin.create({
  classNameBindings: ['isInput:form-control'],
  hasValue: Em.computed('value', function() {
    return this.get('value');
  }),
  isInput: true,
  attributeBindings: ['placeholder', 'required', 'autofocus', 'disabled', 'name'],
  placeholder: Em.computed.alias('parentView.placeholder'),
  required: Em.computed.alias('parentView.required'),
  autofocus: Em.computed.alias('parentView.autofocus'),
  disabled: Em.computed.alias('parentView.disabled'),
  type: Em.computed.alias('parentView.type'),
  model: Em.computed.alias('parentView.model'),
  propertyName: Em.computed.alias('parentView.propertyName'),
  'name': Em.computed.alias('propertyName'),

  isControl: true,

  init: function() {
    this._super();
    Em.Binding.from("model." + this.get('propertyName')).to('value').connect(this);
  }
});