text:
package org.redcross.openmapkit;

import com.spatialdev.osm.model.OSMColorConfig;
import com.spatialdev.osm.model.OSMElement;

import org.apache.commons.io.FileUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.redcross.openmapkit.odkcollect.ODKCollectHandler;
import org.redcross.openmapkit.odkcollect.tag.ODKTag;

import java.io.File;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class Constraints {

    private static Constraints instance;

    private JSONObject defaultConstraintsJson;
    private JSONObject formConstraintsJson;

    /**
     * Contains a map of constraint keys with the key value pairs of the
     * OSM Element conditions in which a tag view should be hidden.
     *
     * The key of the outer map is to the tag in question
     */
    private Map<String, Map<String, String>> hideMap = new HashMap<>();

    /**
     * This map is similar, but the key to the outer map is of tag keys
     * that will cause the inner Set of tag keys to be hidden.
     */
    private Map<String, Map<String, Set<String>>> causeHideMap = new HashMap<>();

    /**
     * Contains a map of constraint keys with the key value pairs of the
     * OSM Element conditions in which a tag view should be shown.
     *
     * The key of the outer map is to the tag in question.
     */
    private Map<String, Map<String, String>> showMap = new HashMap<>();

    /**
     * The key of the outer map is to the tag key that causes the inner
     * set of tag keys to be shown.
     */
    private Map<String, Map<String, Set<String>>> causeShowMap = new HashMap<>();

    private boolean active = true;

    public class TagAction {
        public Set<String> hide = new HashSet<>();
        public Set<String> show = new HashSet<>();
    }

    public static Constraints initialize() {
        instance = new Constraints();
        return instance;
    }

    public static Constraints singleton() {
        return instance;
    }

    /**
     * If there is no default.json constraints file, we have nothing to work with,
     * so the constraint functionality is disabled.
     *
     * @return boolean if the constraint is active
     */
    public boolean isActive() {
        return active;
    }

    public boolean tagIsHidden(String tagKey) {
        if(tagIsRequired(tagKey)) return false;//required tags cannot be hidden
        return cascadeBooleanTagConstraint(tagKey, "hide", false);
    }

    public boolean tagIsNumeric(String tagKey) {
        return cascadeBooleanTagConstraint(tagKey, "numeric", false);
    }

    public boolean tagAllowsCustomValue(String tagKey) {
        return cascadeBooleanTagConstraint(tagKey, "custom_value", false);
    }

    public boolean tagIsRequired(String tagKey) {
        return cascadeBooleanTagConstraint(tagKey, "required", false);
    }

    public boolean tagIsSelectMultiple(String tagKey) {
        return cascadeBooleanTagConstraint(tagKey, "select_multiple", false);
    }

    public Set<String> requiredTagsNotMet(OSMElement osmElement) {
        Set<String> missingTags = new HashSet<>();

        if (ODKCollectHandler.isODKCollectMode()) {
            Map<String, String> tags = osmElement.getTags();
            Collection<ODKTag> odkTags =  ODKCollectHandler.getODKCollectData().getRequiredTags();
            for (ODKTag odkTag : odkTags) {
                String odkTagKey = odkTag.getKey();
                if (cascadeBooleanTagConstraint(odkTagKey, "required", false)
                        && tagShouldBeShown(odkTagKey, osmElement)) {
                    String osmTagVal = tags.get(odkTagKey);
                    if (osmTagVal == null || osmTagVal.length() < 1) {
                        missingTags.add(odkTagKey);
                    }
                }
            }
        }

        return missingTags;
    }

    public String tagDefaultValue(String tagKey) {
        return cascadeStringTagConstraint(tagKey, "default", null);
    }

    public boolean tagShouldBeShown(String tagKey, OSMElement osmElement) {
        if (!isActive()) return true;

        //check hide constraint
        if(tagIsHidden(tagKey) == true) return false;

        //check if tag is a user location tag
        if(Settings.singleton().isUserLocationTag(tagKey)) {
            return false;
        }

        // Check showMap
        Map<String, String> showMapMap = showMap.get(tagKey);
        if (showMapMap != null && showMapMap.size() > 0) {
            Set<String> showMapMapKeys = showMapMap.keySet();
            for (String key : showMapMapKeys) {
                String val = showMapMap.get(key);
                // wildcard
                if (val.equals("true")) {
                    if (osmElement.getTags().keySet().contains(key)) {
                        // OSM Element has a tag key that is required (declared with true)
                        // by the show_if condition for the given tag_key.
                        return true;
                    }
                } else {
                    String osmElementTagVal = osmElement.getTags().get(key);
                    if (osmElementTagVal != null && osmElementTagVal.equals(val)) {
                        // OSM Element has a tag key and value that match the
                        // show_if condition for the given tagKey.
                        return true;
                    }
                }
            }
            // OSM Element has no tags that match the show_if condition for the given tagKey.
            return false;
        }

        // Check hideMap
        Map<String, String> hideMapMap = hideMap.get(tagKey);
        if (hideMapMap != null && hideMapMap.size() > 0) {
            Set<String> hideMapMapKeys = hideMapMap.keySet();
            for (String key : hideMapMapKeys) {
                String val = hideMapMap.get(key);
                // wildcard
                if (val.equals("true")) {
                    if (osmElement.getTags().keySet().contains(key)) {
                        return false;
                    }
                } else {
                    String osmElementTagVal = osmElement.getTags().get(key);
                    if (osmElementTagVal != null && osmElementTagVal.equals(val)) {
                        return false;
                    }
                }
            }
        }

        // If the tag isn't mentioned in the showMap or the hideMap, then we should show it!
        return true;
    }

    /**
     * This method returns the first OSM color configuration found, starting with the form constraints
     * file and finishing with the default constraints file
     *
     * @return  An OSMColorConfig matching the first color constraint found or a default OSMColorConfig
     *          that will trigger turning off color coding based on tag values
     */
    public OSMColorConfig getFirstColorConfig() {
        OSMColorConfig defaultConfig = OSMColorConfig.getDefaultConfig();
        //start with the form's constraints file
        if(formConstraintsJson != null) {
            OSMColorConfig formColorConfig = getFirstColorConfig(formConstraintsJson);
            if(formColorConfig != null) {
                return formColorConfig;
            }
        }

        if(defaultConstraintsJson != null) {
            OSMColorConfig defaultColorConfig = getFirstColorConfig(defaultConstraintsJson);
            if(defaultColorConfig != null) {
                return defaultColorConfig;
            }
        }

        //if search for color constraints in the default constraints file
        return defaultConfig;
    }

    private OSMColorConfig getFirstColorConfig(JSONObject constraintsJson) {
        if(constraintsJson != null) {
            Iterator<String> tagKeys = constraintsJson.keys();
            while (tagKeys.hasNext()) {
                String currentTag = tagKeys.next();
                JSONObject colors = cascadeJSONObjectTagConstraint(currentTag, "colors", null, constraintsJson);
                if(colors != null) {
                    HashMap<String, String> tagValueColors = new HashMap<>();
                    Iterator<String> tagValues = colors.keys();
                    while (tagValues.hasNext()) {
                        String currentValue = tagValues.next();
                        try {
                            String valueColor = colors.getString(currentValue);
                            tagValueColors.put(currentValue, valueColor);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    return new OSMColorConfig(true, currentTag, tagValueColors);
                }
            }
        }
        return null;
    }

    /**
     * If the tag has an implicit value, it returns it.
     * Otherwise, it returns null.
     *
     * This is how to test if the tag should be considered implicit.
     *
     * @param tagKey
     * @return implicit value or null
     */
    public String implicitVal(String tagKey) {
        return cascadeStringTagConstraint(tagKey, "implicit", null);
    }

    public TagAction tagAddedOrEdited(String key, String val) {
        TagAction tagAction = new TagAction();
        if (!isActive()) return tagAction;

        tagAction.hide = findTagsToBeHiddenFromUpdate(key, val);
        tagAction.show = findTagsToBeShownFromUpdate(key, val);

        return tagAction;
    }

    public TagAction tagDeleted(String key) {
        TagAction tagAction = new TagAction();
        if (!isActive()) return tagAction;

        tagAction.hide = findTagsToBeHiddenFromDelete(key);
        tagAction.show = findTagsToBeShownFromDelete(key);

        return tagAction;
    }

    private Constraints() {
        loadConstraintsJson();
        buildSkipLogic();
    }

    private void loadConstraintsJson() {
        try {
            File defaultConstraintsFile = ExternalStorage.fetchConstraintsFile("default");
            String defaultConstraintsStr = FileUtils.readFileToString(defaultConstraintsFile);
            defaultConstraintsJson = new JSONObject(defaultConstraintsStr);
        }
        // If there is no default.json constraints file,
        // we just turn off Constraints functionality.
        catch (Exception e) {
            active = false;
        }

        if (!ODKCollectHandler.isODKCollectMode()) return;

        String formFileName = ODKCollectHandler.getODKCollectData().getFormFileName();
        ExternalStorage.copyFormFileFromOdkMediaDir(formFileName, ExternalStorage.CONSTRAINTS_FILE_NAME_ON_ODK);
        try {
            File formConstraintsFile = ExternalStorage.fetchConstraintsFile(formFileName);
            String formConstraintsStr = FileUtils.readFileToString(formConstraintsFile);
            formConstraintsJson = new JSONObject(formConstraintsStr);
        } catch (Exception e) {
            // do nothing
            // We typically do not need a constraints specific to a given form,
            // so this is normal.
        }
    }

    private boolean cascadeBooleanTagConstraint(String tagKey, String tagConstraint, boolean defaultVal) {
        boolean val = defaultVal;
        if (!isActive()) return val;

        try {
            JSONObject tagConstraints = defaultConstraintsJson.getJSONObject(tagKey);
            val = tagConstraints.getBoolean(tagConstraint);
        } catch (JSONException e) {
            // do nothing
        }

        if (formConstraintsJson != null) {
            try {
                JSONObject tagConstraints = formConstraintsJson.getJSONObject(tagKey);
                val = tagConstraints.getBoolean(tagConstraint);
            } catch (JSONException e) {
                // do nothing
            }
        }

        return val;
    }

    private String cascadeStringTagConstraint(String tagKey, String tagConstraint, String defaultVal) {
        String val = defaultVal;
        if (!isActive()) return val;

        try {
            JSONObject tagConstraints = defaultConstraintsJson.getJSONObject(tagKey);
            val = tagConstraints.getString(tagConstraint);
        } catch (JSONException e) {
            // do nothing
        }

        if (formConstraintsJson != null) {
            try {
                JSONObject tagConstraints = formConstraintsJson.getJSONObject(tagKey);
                val = tagConstraints.getString(tagConstraint);
            } catch (JSONException e) {
                // do nothing
            }
        }

        return val;
    }

    private JSONObject cascadeJSONObjectTagConstraint(String tagKey, String tagConstraint, JSONObject defaultVal, JSONObject constraintsJson) {
        JSONObject val = defaultVal;
        if (!isActive()) {
            return val;
        }

        if (constraintsJson != null) {
            try {
                JSONObject tagConstraints = constraintsJson.getJSONObject(tagKey);
                val = tagConstraints.getJSONObject(tagConstraint);
            } catch (JSONException e) {
                // do nothing
            }
        }

        return val;
    }

    private void buildSkipLogic() {
        if (defaultConstraintsJson != null) {
            buildHideMaps(defaultConstraintsJson);
            buildShowMaps(defaultConstraintsJson);
        }
        if (formConstraintsJson != null) {
            buildHideMaps(formConstraintsJson);
            buildShowMaps(formConstraintsJson);
        }
    }

    private void buildHideMaps(JSONObject constraintsJson) {
        Iterator<String> tagKeys = constraintsJson.keys();
        // iterate through main tag keys
        while (tagKeys.hasNext()) {
            String tag = tagKeys.next();
            try {
                JSONObject constraints = constraintsJson.getJSONObject(tag);
                Map<String, String> hideMapMap = hideMap.get(tag);
                if (hideMapMap == null) {
                    hideMapMap = new HashMap<>();
                    hideMap.put(tag, hideMapMap);
                }
                JSONObject hideIf = constraints.getJSONObject("hide_if");
                Iterator<String> hideIfKeys = hideIf.keys();
                while (hideIfKeys.hasNext()) {
                    String hideIfKey = hideIfKeys.next();
                    String hideIfVal = hideIf.optString(hideIfKey);
                    Map<String, Set<String>> causeHideMapMap = causeHideMap.get(hideIfKey);
                    if (causeHideMapMap == null) {
                        causeHideMapMap = new HashMap<>();
                        causeHideMapMap.put(hideIfVal, new HashSet<String>());
                        causeHideMap.put(hideIfKey, causeHideMapMap);
                    } else if (causeHideMapMap.get(hideIfVal) == null) {
                        causeHideMapMap.put(hideIfVal, new HashSet<String>());
                    }
                    hideMapMap.put(hideIfKey, hideIfVal);
                    causeHideMapMap.get(hideIfVal).add(tag);
                }
            } catch (JSONException e) {
                // do nothing
            }
        }
    }

    private void buildShowMaps(JSONObject constraintsJson) {
        Iterator<String> tagKeys = constraintsJson.keys();
        // iterate through main tag keys
        while (tagKeys.hasNext()) {
            String tag = tagKeys.next();
            try {
                JSONObject constraints = constraintsJson.getJSONObject(tag);
                Map<String, String> showMapMap = showMap.get(tag);
                if (showMapMap == null) {
                    showMapMap = new HashMap<>();
                    showMap.put(tag, showMapMap);
                }
                JSONObject showIf = constraints.getJSONObject("show_if");
                Iterator<String> showIfKeys = showIf.keys();
                while (showIfKeys.hasNext()) {
                    String showIfKey = showIfKeys.next();
                    String showIfVal = showIf.optString(showIfKey);
                    Map<String, Set<String>> causeShowMapMap = causeShowMap.get(showIfKey);
                    if (causeShowMapMap == null) {
                        causeShowMapMap = new HashMap<>();
                        causeShowMapMap.put(showIfVal, new HashSet<String>());
                        causeShowMap.put(showIfKey, causeShowMapMap);
                    } else if (causeShowMapMap.get(showIfVal) == null) {
                        causeShowMapMap.put(showIfVal, new HashSet<String>());
                    }
                    showMapMap.put(showIfKey, showIfVal);
                    causeShowMapMap.get(showIfVal).add(tag);
                }
            } catch (JSONException e) {
                // do nothing
            }
        }
    }

    private Set<String> findTagsToBeHiddenFromUpdate(String key, String val) {
        Set<String> tags = new HashSet<>();

        Map<String, Set<String>> causeHideMapMap = causeHideMap.get(key);
        if (causeHideMapMap != null) {
            Set<String> set = causeHideMapMap.get("true");
            if (set != null) {
                tags.addAll(set);
            }
            set = causeHideMap.get(key).get(val);
            if (set != null) {
                tags.addAll(set);
            }
        }

        Map<String, Set<String>> causeShowMapMap = causeShowMap.get(key);
        if (causeShowMapMap != null) {
            Set<String> keys = causeShowMapMap.keySet();
            for (String k : keys) {
                // We should still show the keys that should be shown by
                // the key wildcard and the specific new value selected.
                if (k.equals("true") || k.equals(val)) continue;
                Set<String> tagsToHide = causeShowMapMap.get(k);
                tags.addAll(tagsToHide);
            }
        }
        return tags;
    }

    private Set<String> findTagsToBeShownFromUpdate(String key, String val) {
        Set<String> tags = new HashSet<>();

        Map<String, Set<String>> causeShowMapMap = causeShowMap.get(key);
        if (causeShowMapMap != null) {
            Set<String> set = causeShowMapMap.get("true");
            if (set != null) {
                tags.addAll(set);
            }
            set = causeShowMap.get(key).get(val);
            if (set != null) {
                tags.addAll(set);
            }
        }

        return tags;
    }

    private Set<String> findTagsToBeHiddenFromDelete(String key) {
        Set<String> tags = new HashSet<>();

        Map<String, Set<String>> allTags = causeShowMap.get(key);
        if (allTags != null && allTags.size() > 0) {
            Set<String> vals = allTags.keySet();
            for (String v : vals) {
                tags.addAll(allTags.get(v));
            }
        }

        return tags;
    }

    private Set<String> findTagsToBeShownFromDelete(String key) {
        Set<String> tags = new HashSet<>();

        Map<String, Set<String>> allTags = causeHideMap.get(key);
        if (allTags != null && allTags.size() > 0) {
            Set<String> vals = allTags.keySet();
            for (String v : vals) {
                tags.addAll(allTags.get(v));
            }
        }

        return tags;
    }
}


text:
[clappr](../../index.md) / [io.clappr.player.base](../index.md) / [UIObject](index.md) / [ensureView](./ensure-view.md)

# ensureView

`fun ensureView(): `[`Unit`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-unit/index.html)

redpajama_set_name: RedPajamaGithub


text:
/*eslint no-console: 0, no-unused-vars: 0, no-shadow:0 */
"use strict";

//Open Source Modules
var glob = require("glob");
var express = require("express");
var passport = require("passport");
var winston = require("winston");
var fs = require("fs");
var path = require("path");
//SAP Modules
var xsHdbConn = require("@sap/hdbext");
var xsenv = require("@sap/xsenv");
var xssec = require("@sap/xssec");

//Get Directories in a Source Path
function getDirectories(srcpath) {
	var files = glob.sync(srcpath + "*");
	var i = files.length;
	while (i--) {
		if (fs.statSync(files[i]).isFile()) {
			files.splice(i, 1);
		} else {
			files[i] = files[i].substring(__dirname.length);
			files[i] = files[i].substring(1);
			files[i] = files[i].replace(/\//g, ".");
		}
	}
	return files;
}

//Update or Insert a Workshop Record into the database
function upsertWorkshop(req, res) {
	var workshopID = req.params.workshopid;
	var json = req.body;
	console.log(json);
	var client = req.db;
	client.prepare(
		"upsert \"workshop.admin.data::exerciseMaster.workshop\" values(?,?) where WORKSHOP_ID = ?",
		function(err, statement) {
			statement.exec([workshopID, json, workshopID],
				function(err, results) {
					if (err) {
						res.type("text/plain").status(500).send("ERROR: " + err);
					} else {
						res.type("text/plain").status(200).send("Successful Upsert of Workshop");
					}
				}
			);
		}
	);
}

//Read files from a source path matching a pattern
function getFiles(srcpath, fileName) {
	return fs.readdirSync(srcpath).filter(function(file) {
		if (fileName.test(file)) {
			return fs.statSync(path.join(srcpath, file)).isFile();
		}
		return false;
	});
}
module.exports = function() {
	var app = express();

	//log level
	winston.level = process.env.winston_level || "error";

	passport.use("JWT", new xssec.JWTStrategy(xsenv.getServices({
		uaa: {
			tag: "xsuaa"
		}
	}).uaa));
	app.use(passport.initialize());
	/*
	 * use database connection pool provided by xsHdbConn
	 * provides a db property containing the connection
	 * object to the request object of all routes.
	 */
	app.use("/",
		passport.authenticate("JWT", {
			session: false
		}),
		xsHdbConn.middleware());

	//Allow Chunked request handling for file uploads
	app.use(function(req, res, next) {
		var data = "";
		req.setEncoding("utf8");
		req.on("data", function(chunk) {
			data += chunk;
		});

		req.on("end", function() {
			req.body = data;
			next();
		});
	});

	//Hello Route
	app.route("/hello")
		.get(function(req, res) {
			res.send("Hello World Node.js");
		});

	//Get Directories Route
	app.route("/directories/:dir")
		.get(function(req, res) {
			var dirInput = req.params.dir;
			if (dirInput === "*") {
				dirInput = "/";
			} else {
				dirInput = dirInput.replace(/\./g, "/");
			}

			try {
				var dirs = getDirectories(path.join(__dirname, dirInput));
				res.type("application/json").status(200).send(JSON.stringify(dirs));
			} catch (e) {
				res.type("application/json").status(200).send("[]");
			}
		});

	//Get All Files route
	app.route("/files/:dir/:file")
		.get(function(req, res) {
			var dirInput = req.params.dir;
			if (dirInput === "*") {
				dirInput = "/";
			} else {
				dirInput = dirInput.replace(/\./g, "/");
			}

			var fileInput = req.params.file;
			if (fileInput === "*") {
				fileInput = "";
			}
			var regEx = new RegExp("^" + fileInput + ".");
			try {
				var files = getFiles(path.join(__dirname, dirInput), regEx);
				res.type("application/json").status(200).send(JSON.stringify(files));
			} catch (e) {
				res.type("application/json").status(200).send("[]");
			}
		});

	//Get File Contents route
	app.route("/file/:dir/:file")
		.get(function(req, res) {
			var dirInput = req.params.dir;
			dirInput = dirInput.replace(/\./g, "/");
			var fileInput = req.params.file;
			try {
				res.type("application/json").status(200).send(
					fs.readFileSync(path.join(__dirname, dirInput) + "/" + fileInput, "utf8"));
			} catch (e) {
				res.type("application/json").status(404).send(e.toString());
			}
		});

	//Get All Workshops route
	app.route("/workshops")
		.get(function(req, res) {
			var client = req.db;
			client.prepare(
				"select WORKSHOP_ID from \"workshop.admin.data::exerciseMaster.workshop\" ORDER BY WORKSHOP_ID ",
				function(err, statement) {
					statement.exec([],
						function(err, results) {
							if (err) {
								res.type("text/plain").status(500).send("ERROR: " + err);
							} else {
								var result = JSON.stringify({
									Objects: results
								});
								res.type("application/json").status(200).send(result);
							}
						}
					);
				}
			);
		});

	//Get Details of a specific Workshop route
	app.route("/workshop/:workshopid")
		.get(function(req, res) {
			var workshopID = req.params.workshopid;
			var client = req.db;
			client.prepare(
				"select JSON_DATA from \"workshop.admin.data::exerciseMaster.workshop\" where WORKSHOP_ID = ?",
				function(err, statement) {
					statement.exec([workshopID],
						function(err, results) {
							if (err) {
								res.type("text/plain").status(500).send("ERROR: " + err);
							} else {
								if (results.length < 1 ) {
									res.type("text/plain").status(500).send("ERROR: " + "No data for this workshop yet");
								}else{
									res.type("application/json").status(200).send(results[0].JSON_DATA);
								}
							}
						}
					);
				}
			);
		});

	//Delete a specific Workshop route
	app.route("/workshop/:workshopid")
		.delete(function(req, res) {
			var workshopID = req.params.workshopid;
			var client = req.db;
			client.prepare(
				"delete from \"workshop.admin.data::exerciseMaster.workshop\" where WORKSHOP_ID = ?",
				function(err, statement) {
					statement.exec([workshopID],
						function(err, results) {
							if (err) {
								res.type("text/plain").status(500).send("ERROR: " + err);
							} else {
								res.type("text/plain").status(200).send("Sucessful Deletion");
							}
						}
					);
				}
			);
		});

	//Update/Insert a workshop route
	app.route("/workshop/:workshopid")
		.put(function(req, res) {
			upsertWorkshop(req, res);
		});
	app.route("/workshop/:workshopid")
		.post(function(req, res) {
			upsertWorkshop(req, res);
		});

	//Upload Workshop from Client Side
	app.route("/workshop/upload")
		.post(function(req, res) {
			var filename = req.files.displayImage.name;
			var workshopID = filename.substring(0, filename.length - 5);
			var JSON_DATA = fs.readFileSync(req.files.displayImage.path, "utf8");
			var client = req.db;
			client.prepare(
				"upsert \"workshop.admin.data::exerciseMaster.workshop\" values(?,?) where WORKSHOP_ID = ?",
				function(err, statement) {
					statement.exec([workshopID, JSON_DATA, workshopID],
						function(err, results) {
							if (err) {
								res.type("text/plain").status(500).send("ERROR: " + err);
							} else {
								res.type("text/plain").status(200).send("Successful Upsert of Workshop");
							}
						}
					);
				}
			);
		});

	//Get Details of a specific Workshop route
	app.route("/workshop/download/:workshopid")
		.get(function(req, res) {
			var workshopID = req.params.workshopid;
			var client = req.db;
			client.prepare(
				"select JSON_DATA from \"workshop.admin.data::exerciseMaster.workshop\" where WORKSHOP_ID = ?",
				function(err, statement) {
					statement.exec([workshopID],
						function(err, results) {
							if (err) {
								res.type("text/plain").status(500).send("ERROR: " + err);
							} else {
								res.setHeader("Content-Disposition", "attachment; filename=" + workshopID + ".json");
								res.type("application/json").status(200).send(results[0].JSON_DATA);
							}
						}
					);
				}
			);
		});

	return app;
};


text:
<?php
/**
 * Generic CSS Minification class
 *
 * @author Frederic BAYLE <contact (at) made-in-softland (dot) com>
 * @version 2017-08-03
 */

namespace EDP\Web\Bundles;

use EDP\EDPObject;
use EDP\IO\Directory;
use EDP\IO\File;
use EDP\Str;
use EDP\Web\Request;

/**
 * Generic CSS Minification class
 *
 * @property-read string $Command      Minification command
 * @property-read string $MinifierPath Path to the CSS minifier utility
 * @property-read string $Options      Command line options
 */
class CSSMinifier extends EDPObject
{
    /**
     * Minification command
     *
     * $minifier : Path to the CSS minifier utility

     * $options  : Command line options

     * $input    : Path to the input file

     * $output   : Path to the output file
     *
     * @var string
     */
    protected $_Command = '$minifier $options $input > $output';

    /**
     * Path to the CSS minifier utility
     *
     * @var string
     */
    protected $_MinifierPath = '';

    /**
     * Options supplémentaires à passer à la commande
     *
     * @var string
     */
    protected $_Options = '';

    /**
     * Class constructor
     *
     * @param string $pMinifierPath Path to the CSS minifier utility
     */
    public function __construct($pMinifierPath = '')
    {
        if(!Str::IsNullOrWhiteSpace($pMinifierPath))
        {
            $this->_MinifierPath = $pMinifierPath;
        }
        else
        {
            $this->_MinifierPath = 'cat';
        }
    }

    /**
     * Gets the minification command
     *
     * @return string Minification command
     */
    protected function &GetCommand()
    {
        return $this->_Command;
    }

    /**
     * Gets the path to the CSS minifier utility
     *
     * @return string Path to the CSS minifier utility
     */
    protected function &GetMinifierPath()
    {
        return $this->_MinifierPath;
    }

    /**
     * Gets the command line options
     *
     * @return string Command line options
     */
    protected function &GetOptions()
    {
        return $this->_Options;
    }

    /**
     * CSS bundle minification
     *
     * @param string $pBundleName Name of the bundle to minify
     */
    public function MinifyBundle($pBundleName)
    {
        // Computes command
        $Cmd = Str::Replace($this->_Command, '$minifier', $this->_MinifierPath);
        $Cmd = Str::Replace($Cmd, '$options', $this->_Options);
        $OutputFile = Request::MapPath($pBundleName);
        if(File::Exists($OutputFile))
        {
            // Output file already exists, deletes it
            File::Delete($OutputFile);
        }
        else if(!File::Exists(dirname($OutputFile)))
        {
            // Output directory doesn't exist, creates it
            Directory::CreateDirectory(dirname($OutputFile));
        }

        $Cmd = Str::Replace($Cmd, '$output', escapeshellarg($OutputFile));

        // Concatenates input file to a temporary file
        $BundleTmpFileName = sys_get_temp_dir() . '/bundle-' . date('YmdHis') . '-' . rand(0, 10000);
        if(File::Exists($BundleTmpFileName))
        {
            File::Delete($BundleTmpFileName);
        }
        $BundleTmpFile = fopen($BundleTmpFileName, 'a');
        foreach (Bundle::$CSSBundleTable[$pBundleName] as $InputFileItem)
        {
            fwrite($BundleTmpFile, File::ReadAllText(Request::MapPath($InputFileItem)));
        }
        fclose($BundleTmpFile);
        $Cmd = Str::Replace($Cmd, '$input', escapeshellarg($BundleTmpFileName));

        // Executes command
        exec($Cmd);

        // Cleanning
        File::Delete($BundleTmpFileName);
    }

    /**
     * Sets the minification command
     *
     * @param string $pValue Minification command
     */
    protected function SetCommand($pValue)
    {
        $this->_Command = $pValue;
    }

    /**
     * Sets the path to the CSS minifier utility
     *
     * @param string $pValue Path to the Javascript minifier utility
     */
    protected function SetMinifierPath($pValue)
    {
        $this->_MinifierPath = $pValue;
    }

    /**
     * Sets the command line options
     *
     * @param string $pValue Command line options
     */
    protected function SetOptions($pValue)
    {
        $this->_Options = $pValue;
    }
}


text:
<?php

namespace App\Http\Controllers\Api\V1;

use Illuminate\Http\Request;

trait LoadRelations
{
    private function loadRelations(Request $request)
    {
        if (property_exists($this, 'relationsAllowed')) {
            $relationsAllowed = collect($this->relationsAllowed);
        } elseif (method_exists($this, 'getRelationsAllowed')) {
            $relationsAllowed = $this->getRelationsAllowed();
        } else {
            $relationsAllowed = collect([]);
        }

        $relationsRequested = collect($request->query('with', []))
            ->map(function (string $relation): string {
                return trim(strtolower($relation));
            });

        $relationsAllowed->each(function (string $relation): void {
            $this->resource->unsetRelation($relation);
        })->intersect($relationsRequested)->each(function (string $relation): void {
            $this->resource->load($relation);
        });
    }
}


text:
<?php

namespace intrepion\PhoneBundle\Form;

use intrepion\PhoneBundle\Transformer\PhoneNumberTransformer;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class ContactInfoType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $transformer = new PhoneNumberTransformer();
        $builder
            ->add($builder->create('home', 'text')->addViewTransformer($transformer))
            ->add('cell')
            ->add('work')
            ->add('fax')
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'intrepion\PhoneBundle\Entity\ContactInfo'
        ));
    }

    public function getName()
    {
        return 'intrepion_phonebundle_contactinfotype';
    }
}


text:
var fs = require('fs')
var path = require('path')
var yargs = require('yargs').argv

var processDir = function(rootPath) {
	fs.readdir(rootPath, function(err, files) {
		files.forEach(function(src) {
			src = path.join(rootPath, src)

			if (src.indexOf('.') == -1) {
				fs.stat(src, function(statErr, stat) {
					if (stat.isFile()) {
						console.log('%s --> %s', src, src + '.jpg')
						fs.renameSync(src, src + '.jpg')
					}
					else if (stat.isDirectory()) {
						console.log('Processing Directory: %s', src)
						processDir(src)
					}
				})
			}
			else {
				console.log('Ignoring: %s', src)
			}
		})
	})
}

processDir(yargs.path)


text:
var Aria = require("../Aria");

/**
 * Global class gathering information about current browser type and version A list of user agent string for mobile
 * phones could be find here: http://www.useragentstring.com/pages/Mobile%20Browserlist/
 */
module.exports = Aria.classDefinition({
    $classpath : 'aria.core.Browser',
    $singleton : true,
    $constructor : function () {
        var navigator = Aria.$global.navigator;
        var ua = navigator ? navigator.userAgent.toLowerCase() : "";

        /**
         * The user agent string.
         * @type String
         */
        this.ua = ua;

        /**
         * True if the browser is any version of Internet Explorer.
         * @type Boolean
         */
        this.isIE = false;

        /**
         * True if the browser is Internet Explorer 6.
         * @type Boolean
         */
        this.isIE6 = false;

        /**
         * True if the browser is Internet Explorer 7.
         * @type Boolean
         */
        this.isIE7 = false;

        /**
         * True if the browser is Internet Explorer 8.
         * @type Boolean
         */
        this.isIE8 = false;

        /**
         * True if the browser is Internet Explorer 9.
         * @type Boolean
         */
        this.isIE9 = false;

        /**
         * True if the browser is Internet Explorer 10.
         * @type Boolean
         */
        this.isIE10 = false;

        /**
         * True if the browser is Internet Explorer 10 or less.
         * @type Boolean
         */
        this.isOldIE = false;

        /**
         * True if the browser is Internet Explorer 11.
         * @type Boolean
         */
        this.isModernIE = false;

        /**
         * True if the browser is any version of Opera.
         * @type Boolean
         */
        this.isOpera = false;

        /**
         * True if the browser is any version of Chrome.
         * @type Boolean
         */
        this.isChrome = false;

        /**
         * True if the browser is any version of Safari.
         * @type Boolean
         */
        this.isSafari = false;

        /**
         * True if the browser is any version of Chrome or Safari.
         * @type Boolean
         */
        this.isWebkit = false;

        /**
         * True if the browser uses the Gecko engine.
         * @type Boolean
         */
        this.isGecko = false;

        /**
         * True if the browser is any version of Firefox.
         * @type Boolean
         */
        this.isFirefox = false;

        /**
         * Browser version.
         * @type String
         */
        this.version = "";

        /**
         * True if the operating systems is Windows.
         * @type Boolean
         */
        this.isWindows = false;

        /**
         * True if the operating systems is Mac.
         * @type Boolean
         */
        this.isMac = false;

        /**
         * Browser name.
         * @type String
         */
        this.name = "";

        /**
         * MacOS or Windows
         * @type String
         */
        this.environment = "";

        /**
         * Major version.
         * @type Integer
         */
        this.majorVersion = "";

        // For Mobile Browsers
        /**
         * True if the device is of type phone
         * @type Boolean
         */
        this.isPhone = false;

        /**
         * True if the device is of type tablet
         * @type Boolean
         */
        this.isTablet = false;

        /**
         * True if OS is iOS
         * @type Boolean
         */
        this.isIOS = false;

        /**
         * True if OS is Android
         * @type Boolean
         */
        this.isAndroid = false;

        /**
         * True if OS is Windows
         * @type Boolean
         */
        this.isWindowsPhone = false;

        /**
         * True if OS is BlackBerry
         * @type Boolean
         */
        this.isBlackBerry = false;

        /**
         * True if OS is Symbian
         * @type Boolean
         */
        this.isSymbian = false;

        /**
         * True if OS is some mobile OS
         * @type Boolean
         */
        this.isOtherMobile = false;

        // Only for Window Phone with IE+9
        /**
         * True if view type if Mobile
         * @type Boolean
         */
        this.isMobileView = false;

        /**
         * True if view type if Desktop
         * @type Boolean
         */
        this.DesktopView = false;

        // Check for browser Type

        /**
         * True if browser is of type FF http://hacks.mozilla.org/2010/09/final-user-agent-string-for-firefox-4/
         * @type Boolean
         */
        this.isFF = false;

        /**
         * True if browser type is blackberry
         * @type Boolean
         */
        this.isBlackBerryBrowser = false;

        /**
         * True if browser type is Android
         * @type Boolean
         */
        this.isAndroidBrowser = false;

        /**
         * True if browser type is Safari Mobile
         * @type Boolean
         */
        this.isSafariMobile = false;

        /**
         * True if browser type is Safari
         * @type Boolean
         */
        this.isSafari = false;

        /**
         * True if browser type is Chrome
         * @type Boolean
         */
        this.isChrome = false;

        /**
         * True if browser type is IE Mobile
         * @type Boolean
         */
        this.isIEMobile = false;

        /**
         * True if browser type is Opera Mobile
         * @type Boolean
         */
        this.isOperaMobile = false;

        /**
         * True if browser type is Opera Mini
         * @type Boolean
         */
        this.isOperaMini = false;

        /**
         * True if browser type is S60
         * @type Boolean
         */
        this.isS60 = false;

        /**
         * True if browser type is Phantomjs
         * @type Boolean
         */
        this.isPhantomJS = false;

        /**
         * True if browser type is S60
         * @type Boolean
         */
        this.isOtherBrowser = false;

        /**
         * OS running in Device
         * @type String
         */
        this.osName = "";

        /**
         * OS Version in Device
         * @type String
         */
        this.osVersion = "";

        /**
         * Browser Name
         * @type String
         */
        this.browserType = "";

        /**
         * Browser Version
         * @type String
         */
        this.browserVersion = "";

        /**
         * Device Name
         * @type String
         */
        this.deviceName = "";

        this._init();
    },
    $prototype : {
        /**
         * Returns browser name and version - ease debugging
         */
        toString : function () {
            return this.name + " " + this.version;
        },
        /**
         * Internal initialization function - automatically called when the object is created
         * @private
         */
        _init : function () {
            // browser determination
            var ua = this.ua;
            if (ua.indexOf('msie') > -1) {
                this.isIE = true;
                this.isOldIE = true;
                this.name = "IE";
                if (/msie[\/\s]((?:\d+\.?)+)/.test(ua)) {
                    this.version = RegExp.$1;
                    var ieVersion = parseInt(this.version, 10);

                    if (ieVersion == 6) {
                        this.isIE6 = true;
                    } else if (ieVersion >= 7) {
                        // PTR 05207453
                        // With compatibility view, it can become tricky to
                        // detect the version.
                        // What is important to detect here is the document mode
                        // (which defines how the browser really
                        // reacts), NOT the browser mode (how the browser says
                        // it reacts, through conditional comments
                        // and ua string).
                        //
                        // In IE7 document.documentMode is undefined. For IE8+
                        // (also in document modes emulating IE7) it is defined
                        // and readonly.

                        var document = Aria.$frameworkWindow.document;
                        var detectedIEVersion = document.documentMode || 7;
                        this["isIE" + detectedIEVersion] = true;
                        if (detectedIEVersion != ieVersion) {
                            // the browser is not what it claims to be!
                            // make sure this.version is consistent with isIE...
                            // variables
                            this.version = detectedIEVersion + ".0";
                        }
                    }
                }
            } else if (ua.indexOf('trident/7.0') > -1) {
                this.isIE = true;
                this.isModernIE = true;
                this.name = "IE";
                this.version = "11.0";
            } else if (ua.indexOf('opera') > -1) {
                this.isOpera = true;
                this.name = "Opera";
            } else if (ua.indexOf('chrome') > -1) {
                this.isChrome = true;
                this.name = "Chrome";
            } else if (ua.indexOf('phantomjs') > -1) {
                this.isPhantomJS = true;
                this.name = "PhantomJS";
            } else if (ua.indexOf('webkit') > -1) {
                this.isSafari = true;
                this.name = "Safari";
            } else {
                if (ua.indexOf('gecko') > -1) {
                    this.isGecko = true;
                }
                if (ua.indexOf('firefox') > -1) {
                    this.name = "Firefox";
                    this.isFirefox = true;
                }
            }

            // common group for webkit-based browsers
            this.isWebkit = this.isSafari || this.isChrome || this.isPhantomJS;

            if (ua.indexOf("windows") != -1 || ua.indexOf("win32") != -1) {
                this.isWindows = true;
                this.environment = "Windows";
            } else if (ua.indexOf("macintosh") != -1) {
                this.isMac = true;
                this.environment = "MacOS";
            }

            // version determination
            if (this.isIE) {
                // already determined
            } else if (this.isFirefox) {
                if (/firefox[\/\s]((?:\d+\.?)+)/.test(ua)) {
                    this.version = RegExp.$1;
                }
            } else if (this.isSafari) {
                if (/version[\/\s]((?:\d+\.?)+)/.test(ua)) {
                    this.version = RegExp.$1;
                }
            } else if (this.isChrome) {
                if (/chrome[\/\s]((?:\d+\.?)+)/.test(ua)) {
                    this.version = RegExp.$1;
                }
            } else if (this.isPhantomJS) {
                if (/phantomjs[\/\s]((?:\d+\.?)+)/.test(ua)) {
                    this.version = RegExp.$1;
                }
            } else if (this.isOpera) {
                if (/version[\/\s]((?:\d+\.?)+)/.test(ua)) {
                    this.version = RegExp.$1;
                }
            }
            if (this.version) {
                if (/(\d+)\./.test(this.version)) {
                    this.majorVersion = parseInt(RegExp.$1, 10);
                }
            }

            // for Mobile browsers check
            if (this.ua) {

                // To Match OS and its Version
                var osPattern = [{
                            pattern : /(android)[\/\s-]?([\w\.]+)*/i
                        }, {
                            pattern : /(ip[honead]+).*os\s*([\w]+)*\slike\smac/i
                        }, {
                            pattern : /(blackberry).+version\/([\w\.]+)/i
                        }, {
                            pattern : /(rim\stablet+).*os\s*([\w\.]+)*/i
                        }, {
                            pattern : /(windows\sphone\sos|windows\s?[mobile]*)[\s\/\;]?([ntwce\d\.\s]+\w)/i
                        }, {
                            pattern : /(symbian\s?os|symbos|s60(?=;))[\/\s-]?([\w\.]+)*/i
                        }, {
                            pattern : /(webos|palm\sos|bada|rim\sos|meego)[\/\s-]?([\w\.]+)*/i
                        }];
                // To Match Browser and its Version
                var browserPattern = [{
                            pattern : /(chrome|crios)\/((\d+)?[\w\.]+)/i
                        }, {
                            pattern : /(mobile\ssafari)\/((\d+)?[\w\.]+)/i
                        }, {
                            pattern : /(mobile)\/\w+\s(safari)\/([\w\.]+)/i
                        }, {
                            pattern : /(iemobile)[\/\s]?((\d+)?[\w\.]*)/i
                        }, {
                            pattern : /(safari)\/((\d+)?[\w\.]+)/i
                        }, {
                            pattern : /(series60.+(browserng))\/((\d+)?[\w\.]+)/i
                        }, {
                            pattern : /(firefox)\/([\w\.]+).+(fennec)\/\d+/i
                        }, {
                            pattern : /(opera\smobi)\/((\d+)?[\w\.-]+)/i
                        }, {
                            pattern : /(opera\smini)\/((\d+)?[\w\.-]+)/i
                        }, {
                            pattern : /(dolfin|Blazer|S40OviBrowser)\/((\d+)?[\w\.]+)/i
                        }];
                // To Match Device Name
                var devicerPattern = [{
                            pattern : /\(((ipad|playbook));/i
                        }, {
                            pattern : /\(((ip[honed]+));/i
                        }, {
                            pattern : /(blackberry[\s-]?\w+)/i
                        }, {
                            pattern : /(hp)\s([\w\s]+\w)/i
                        }, {
                            pattern : /(htc)[;_\s-]+([\w\s]+(?=\))|\w+)*/i
                        }, {
                            pattern : /(sam[sung]*)[\s-]*(\w+-?[\w-]*)*/i
                        }, {
                            pattern : /((s[cgp]h-\w+|gt-\w+|galaxy\snexus))/i
                        }, {
                            pattern : /sec-((sgh\w+))/i
                        }, {
                            pattern : /(maemo|nokia).*(\w|n900|lumia\s\d+)/i
                        }, {
                            pattern : /(lg)[e;\s\-\/]+(\w+)*/i
                        }, {
                            pattern : /(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|huawei|meizu|motorola)[\s_-]?([\w-]+)*/i
                        }];

                // for getting OS and Version
                this.__testUaMatch(osPattern, "OS");
                // for getting Browser and Version
                this.__testUaMatch(browserPattern, "BROWSER");
                // for getting the device
                this.__testUaMatch(devicerPattern, "DEVICE");
            }
        },
        /**
         * private function - To take the User Agents and match the patterns
         * @param {Array} pattern Array of User Agents
         * @param {String} type to match from user agents
         * @private
         */
        __testUaMatch : function (pattern, type) {
            var patternMatch;
            for (var i = 0, len = pattern.length; i < len; i++) {
                if (type === "OS") {
                    patternMatch = this.__checkNavigator(pattern[i].pattern, this.ua);
                    if (patternMatch) {
                        this.__setOs(patternMatch, i);
                        break;
                    }
                }
                if (type === "BROWSER") {
                    patternMatch = this.__checkNavigator(pattern[i].pattern, this.ua);
                    if (patternMatch) {
                        this.__setBrowser(patternMatch, i);
                        break;
                    }
                }

                if (type === "DEVICE") {
                    patternMatch = this.__checkNavigator(pattern[i].pattern, this.ua);
                    if (patternMatch) {
                        this.__setDevice(patternMatch);
                        break;
                    }
                }
            }

        },
        /**
         * private function - Returns the matched user agent
         * @param {String} pattern string
         * @param {String} userAgent user agent string
         * @return {Array} array of matched string for given pattern
         * @private
         */
        __checkNavigator : function (pattern, userAgent) {
            return pattern.exec(userAgent);
        },
        /**
         * private function - To set the Device Name
         * @param {Array} Array of matched string for given pattern
         * @private
         */
        __setDevice : function (patternMatch) {

            this.deviceName = patternMatch[1] || "";
        },
        /**
         * private function - To set the Browser Name and Version
         * @param {Array} Array of matched string for given pattern
         * @param {Integer} index of the matched pattern
         * @private
         */
        __setBrowser : function (patternMatch, index) {
            var browserName = ["Mobile Safari", "Chrome", "Other"];
            switch (index) {
                case 0 :
                    this.browserType = browserName[1];
                    this.browserVersion = patternMatch[2] || "";
                    this.isChrome = true;
                    break;
                case 1 :
                    this.browserType = patternMatch[1] || "";
                    this.browserVersion = patternMatch[2] || "";
                    if (this.isAndroid) {
                        this.isAndroidBrowser = true;
                    }
                    if (this.isBlackBerry) {
                        this.isBlackBerryBrowser = true;
                    }
                    break;
                case 2 :
                    this.browserType = browserName[0];
                    this.browserVersion = patternMatch[3] || "";
                    this.isSafariMobile = true;
                    break;
                case 3 :
                    this.browserType = patternMatch[1] || "";
                    this.browserVersion = patternMatch[2] || "";
                    if (patternMatch[0]
                            && (patternMatch[0].indexOf('XBLWP7') > -1 || patternMatch[0].indexOf('ZuneWP7') > -1)) {
                        this.DesktopView = true;

                    } else {
                        this.isMobileView = true;
                    }
                    this.isIEMobile = true;
                    break;
                case 4 :
                    this.browserType = patternMatch[1] || "";
                    this.browserVersion = patternMatch[2] || "";
                    this.isSafari = true;
                    break;
                case 5 :
                    this.browserType = patternMatch[2] || "";
                    this.browserVersion = patternMatch[3] || "";
                    this.isS60 = true;
                    break;
                case 6 :
                    this.browserType = patternMatch[1] || "";
                    this.browserVersion = patternMatch[2] || "";
                    this.isFF = true;
                    break;
                case 7 :
                    this.browserType = patternMatch[1] || "";
                    this.browserVersion = patternMatch[2] || "";
                    this.isFF = true;
                    break;
                case 8 :
                    this.browserType = patternMatch[1] || "";
                    this.browserVersion = patternMatch[2] || "";
                    this.isFF = true;
                    break;
                case 9 :
                    this.browserType = browserName[2];
                    this.browserVersion = patternMatch[2] || "";
                    this.isOtherBrowser = true;
                    break;

            }

        },
        /**
         * private function - To set the Device OS Name and Version
         * @param {Array} Array of matched string for given pattern
         * @param {Integer} index of the matched pattern
         * @private
         */
        __setOs : function (patternMatch, index) {
            var osName = ["Android", "IOS", "BlackBerry", "BlackBerry Tablet OS", "Windows", "Symbian", "Other"];
            switch (index) {
                case 0 :
                    this.isAndroid = true;
                    this.osName = osName[0];
                    this.osVersion = patternMatch[2] || "";
                    // since android version 3 specifically for tablet checking screen resolution make no sense
                    if (patternMatch[2] && patternMatch[2].match(/\d/) + "" == "3") {
                        this.isTablet = true;
                    } else {
                        this.isPhone = true;
                    }
                    break;
                case 1 :
                    this.isIOS = true;
                    this.osName = osName[1];
                    var osVer = patternMatch[2] || "";
                    this.osVersion = osVer.replace(/\_/g, ".");
                    if (patternMatch[1] == "iPad") {
                        this.isTablet = true;
                    } else {
                        this.isPhone = true;
                    }
                    break;
                case 2 :
                    this.isBlackBerry = true;
                    this.osName = osName[2];
                    this.osVersion = patternMatch[2] || "";
                    this.isPhone = true;
                    break;
                case 3 :
                    this.isBlackBerry = true;
                    this.osName = osName[3];
                    this.osVersion = patternMatch[2] || "";
                    this.isTablet = true;
                    break;
                case 4 :
                    this.isWindowsPhone = true;
                    this.osName = osName[4];
                    this.osVersion = patternMatch[2] || "";
                    this.isPhone = true;
                    break;
                case 5 :
                    this.isSymbian = true;
                    this.osName = osName[5];
                    this.osVersion = patternMatch[2] || "";
                    this.isPhone = true;
                    break;
                case 6 :
                    this.isOtherMobile = true;
                    this.osName = osName[6];
                    this.osVersion = patternMatch[2] || "";
                    this.isPhone = true;
                    break;

            }
            this.osVersion = this.osVersion.replace(/\s*/g, "");
        }
    }
});


text:
from app import db, bcrypt
from app.models.base import Base

class User(Base):
	__tablename__ = 'user_tbl'

	id = db.Column(db.Integer, db.ForeignKey('base_tbl.id'), primary_key=True)
	__mapper_args__ = {'polymorphic_identity': 'user'}
	username = db.Column(db.String(), unique=True, nullable=False)
	firstname = db.Column(db.String(), nullable=False)
	lastname = db.Column(db.String(), nullable=False)
	password = db.Column(db.String, nullable=False)
	email = db.Column(db.String, nullable=False)

	def __init__(self, username, firstname, lastname, password, email):
		self.username = username
		self.firstname = firstname
		self.lastname = lastname
		self.password = bcrypt.generate_password_hash(password)
		self.email = email

	def __repr__(self):
		return '<username: {}, name: {} {}>'.format(self.username, \
				self.firstname, self.lastname)

	def is_authenticated(self):
		return True

	def is_active(self):
		return True

	def is_anonymous(self):
		return False

	def get_id(self):
		return unicode(self.id)


text:
Ruboard::Engine.routes.draw do
  root :to => 'forums#index'

  resources :forums, :only => [ :index, :show ] do
    resources :topics, :only => [ :show ]
  end
end


text:
:- module(xfrefs,
        [ xfrefs/1,
          xflinks/1,
          quit/0
        ],
        [ assertions, regtypes
        ]).

:- use_module(library(davinci)).
:- use_module(library(xrefs),[ xrefs_lgraph/2, xrefs_ugraph/2, xref/1 ]).
:- reexport(library(xrefs),[ set_files/1, set_flag/1 ]).

:- comment(title,"Crossed-references between files").
:- comment(subtitle,"@bf{The CIAO System Documentation Series}").
:- comment(subtitle,"@em{Draft printed on:} @today{}").
:- comment(author,"Francisco Bueno").
:- comment(module,"This module allows displaying a graph of
        crossed-references between source code in different files.
        The graph is obtained using
	@tt{library(xrefs)} and is displayed using daVinci (a
        windows-based graphics graph displayer developed by U. of Bremen,
	Germany), via @tt{library(davinci)}.

        See the documentation of these libraries for details.").

:- comment(bug,"@tt{quit/0} does nothing. daVinci has to be exited
        from its own window.").

%-----------------------------------------------------------------------------
% entry points

:- pred xfrefs(Xrefs) : xref
        # "Displays a graph of crossed-references of type @var{Xrefs}
           for the current files.".

xfrefs(Xrefs):-
        xrefs_lgraph(Xrefs,Graph),
        ( davinci -> true ; true ),
        davinci_lgraph(Graph).

:- pred xflinks(Xrefs)
        # "Like @tt{xfrefs/1} but edges have no labels.".

xflinks(Xrefs):-
        xrefs_ugraph(Xrefs,Graph),
        ( davinci -> true ; true ),
        davinci_ugraph(Graph).

:- comment(quit/0,"Quits daVinci.").

quit:- davinci_quit.

:- comment(doinclude,set_files/1).
:- comment(doinclude,sourcename/1).
:- comment(sourcename/1,"See @tt{engine(streams_basic)}.").
:- comment(doinclude,set_flag/1).


text:
package org.jkiss.dbeaver.registry;

import org.eclipse.core.runtime.IConfigurationElement;
import org.jkiss.dbeaver.model.DBPImage;
import org.jkiss.dbeaver.model.impl.AbstractDescriptor;

/**
 * DataSourceViewDescriptor
 */
public class DataSourceViewDescriptor extends AbstractDescriptor
{
    private String id;
    private String targetID;
    private String label;
    private ObjectType viewType;
    private DBPImage icon;

    public DataSourceViewDescriptor(DataSourceProviderDescriptor provider, IConfigurationElement config)
    {
        super(provider.getPluginId());
        this.id = config.getAttribute(RegistryConstants.ATTR_ID);
        this.targetID = config.getAttribute(RegistryConstants.ATTR_TARGET_ID);
        this.label = config.getAttribute(RegistryConstants.ATTR_LABEL);
        this.viewType = new ObjectType(config.getAttribute(RegistryConstants.ATTR_CLASS));
        this.icon = iconToImage(config.getAttribute(RegistryConstants.ATTR_ICON));
    }

    public String getId()
    {
        return id;
    }

    public String getTargetID()
    {
        return targetID;
    }

    public String getLabel()
    {
        return label;
    }

    public DBPImage getIcon()
    {
        return icon;
    }

    public <T> T createView(Class<T> implementsClass)
    {
        try {
            return viewType.createInstance(implementsClass);
        }
        catch (Throwable ex) {
            throw new IllegalStateException("Can't create view '" + viewType.getImplName() + "'", ex);
        }
    }
}


text:
static const double kBufferSize = 1000*1000; // 1 MB
static const NSTimeInterval kDefaultRequestTimeout = 30;
static const NSInteger kNumberOfSamples = 5;

NSString * const TCBlobDownloadErrorDomain = @"com.thibaultcha.tcblobdownload";
NSString * const TCBlobDownloadErrorHTTPStatusKey = @"TCBlobDownloadErrorHTTPStatusKey";

#import "TCBlobDownloader.h"

@interface TCBlobDownloader ()
// Public
@property (nonatomic, strong, readwrite) NSMutableURLRequest *fileRequest;
@property (nonatomic, copy, readwrite) NSURL *downloadURL;
@property (nonatomic, copy, readwrite) NSString *pathToFile;
@property (nonatomic, copy, readwrite) NSString *pathToDownloadDirectory;
@property (nonatomic, assign, readwrite) TCBlobDownloadState state;
// Download
@property (nonatomic, strong) NSURLConnection *connection;
@property (nonatomic, strong) NSMutableData *receivedDataBuffer;
@property (nonatomic, strong) NSFileHandle *file;
// Speed rate and remaining time
@property (nonatomic, strong) NSTimer *speedTimer;
@property (nonatomic, strong) NSMutableArray *samplesOfDownloadedBytes;
@property (nonatomic, assign) uint64_t expectedDataLength;
@property (nonatomic, assign) uint64_t receivedDataLength;
@property (nonatomic, assign) uint64_t previousTotal;
@property (nonatomic, assign, readwrite) NSInteger speedRate;
@property (nonatomic, assign, readwrite) NSInteger remainingTime;
// Blocks
@property (nonatomic, copy) void (^firstResponseBlock)(NSURLResponse *response);
@property (nonatomic, copy) void (^progressBlock)(uint64_t receivedLength, uint64_t totalLength, NSInteger remainingTime, float progress);
@property (nonatomic, copy) void (^errorBlock)(NSError *error);
@property (nonatomic, copy) void (^completeBlock)(BOOL downloadFinished, NSString *pathToFile);

+ (NSNumber *)freeDiskSpace;

- (void)finishOperationWithState:(TCBlobDownloadState)state;
- (void)notifyFromCompletionWithError:(NSError *)error pathToFile:(NSString *)pathToFile;
- (void)updateTransferRate;
- (BOOL)removeFileWithError:(NSError *__autoreleasing *)error;
@end

@implementation TCBlobDownloader
@dynamic pathToFile;
@dynamic remainingTime;

#pragma mark - Dealloc

- (void)dealloc
{
    [self.speedTimer invalidate];
}

#pragma mark - Init

- (instancetype)initWithURL:(NSURL *)url
               downloadPath:(NSString *)pathToDL
                   delegate:(id<TCBlobDownloaderDelegate>)delegateOrNil
{
    self = [super init];
    if (self) {
        self.downloadURL = url;
        self.delegate = delegateOrNil;
        self.pathToDownloadDirectory = pathToDL;
        self.state = TCBlobDownloadStateReady;
        self.fileRequest = [NSMutableURLRequest requestWithURL:self.downloadURL
                                                   cachePolicy:NSURLRequestUseProtocolCachePolicy
                                               timeoutInterval:kDefaultRequestTimeout];
        self.bufferSize = kBufferSize;
    }
    return self;
}

- (instancetype)initWithURL:(NSURL *)url
               downloadPath:(NSString *)pathToDL
              firstResponse:(void (^)(NSURLResponse *response))firstResponseBlock
                   progress:(void (^)(uint64_t receivedLength, uint64_t totalLength, NSInteger remainingTime, float progress))progressBlock
                      error:(void (^)(NSError *error))errorBlock
                   complete:(void (^)(BOOL downloadFinished, NSString *pathToFile))completeBlock
{
    self = [self initWithURL:url downloadPath:pathToDL delegate:nil];
    if (self) {
        self.firstResponseBlock = firstResponseBlock;
        self.progressBlock = progressBlock;
        self.errorBlock = errorBlock;
        self.completeBlock = completeBlock;
    }
    return self;
}

#pragma mark - NSOperation Override

- (void)start
{
    // If we can't handle the request, better cancelling the operation right now
    if (![NSURLConnection canHandleRequest:self.fileRequest]) {
        NSError *error = [NSError errorWithDomain:TCBlobDownloadErrorDomain
                                             code:TCBlobDownloadErrorInvalidURL
                                         userInfo:@{ NSLocalizedDescriptionKey:
                                        [NSString stringWithFormat:@"Invalid URL provided: %@", self.fileRequest.URL] }];

        [self notifyFromCompletionWithError:error pathToFile:nil];
        return;
    }

    NSFileManager *fm = [NSFileManager defaultManager];

    // Create download directory
    NSError *createDirError = nil;
    if (![fm createDirectoryAtPath:self.pathToDownloadDirectory
       withIntermediateDirectories:YES
                        attributes:nil
                             error:&createDirError]) {
        [self notifyFromCompletionWithError:createDirError pathToFile:nil];
        return;
    }

    // Test if file already exists (partly downloaded) to set HTTP `bytes` header or not
    if (![fm fileExistsAtPath:self.pathToFile]) {
        [fm createFileAtPath:self.pathToFile
                    contents:nil
                  attributes:nil];
    }
    else {
        uint64_t fileSize = [[fm attributesOfItemAtPath:self.pathToFile error:nil] fileSize];
        NSString *range = [NSString stringWithFormat:@"bytes=%lld-", fileSize];
        [self.fileRequest setValue:range forHTTPHeaderField:@"Range"];
        // Allow progress to reflect what's already downloaded
        self.receivedDataLength += fileSize;
    }

    // Initialization of everything we'll need to download the file
    self.file = [NSFileHandle fileHandleForWritingAtPath:self.pathToFile];
    self.receivedDataBuffer = [[NSMutableData alloc] init];
    self.samplesOfDownloadedBytes = [[NSMutableArray alloc] init];
    self.connection = [[NSURLConnection alloc] initWithRequest:self.fileRequest
                                                  delegate:self
                                          startImmediately:NO];

    if (self.connection && ![self isCancelled]) {
        [self willChangeValueForKey:@"isExecuting"];
        self.state = TCBlobDownloadStateDownloading;
        [self didChangeValueForKey:@"isExecuting"];

        [self.file seekToEndOfFile];

        // Start the download
        NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
        [self.connection scheduleInRunLoop:runLoop
                                   forMode:NSDefaultRunLoopMode];
        [self.connection start];

        // Start the speed timer to schedule speed download on a periodic basis
        self.speedTimer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                           target:self
                                                         selector:@selector(updateTransferRate)
                                                         userInfo:nil
                                                          repeats:YES];
        [runLoop addTimer:self.speedTimer forMode:NSRunLoopCommonModes];
        [runLoop run];
    }
}

- (BOOL)isExecuting
{
    return self.state == TCBlobDownloadStateDownloading;
}

- (BOOL)isCancelled
{
    return self.state == TCBlobDownloadStateCancelled;
}

- (BOOL)isFinished
{
    return self.state == TCBlobDownloadStateCancelled || self.state == TCBlobDownloadStateDone || self.state == TCBlobDownloadStateFailed;
}

#pragma mark - NSURLConnection Delegate

- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError *)error
{
    [self notifyFromCompletionWithError:error pathToFile:self.pathToFile];
}

- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse *)response
{
    // If anything was previousy downloaded, add it to the total expected length for the progress property
    self.expectedDataLength = self.receivedDataLength + [response expectedContentLength];

    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
    NSError *error;
    if (httpResponse.statusCode >= 400) {
        error = [NSError errorWithDomain:TCBlobDownloadErrorDomain
                                    code:TCBlobDownloadErrorHTTPError
                                userInfo:@{ NSLocalizedDescriptionKey:[NSString stringWithFormat:@"Erroneous HTTP status code %ld (%@)",
                                                                       (long) httpResponse.statusCode,
                                                                       [NSHTTPURLResponse localizedStringForStatusCode:httpResponse.statusCode]],
                                            TCBlobDownloadErrorHTTPStatusKey: @(httpResponse.statusCode) }];
    }

    long long expected = @(self.expectedDataLength).longLongValue;
    if ([TCBlobDownloader freeDiskSpace].longLongValue < expected && expected != -1) {
        error = [NSError errorWithDomain:TCBlobDownloadErrorDomain
                                    code:TCBlobDownloadErrorNotEnoughFreeDiskSpace
                                userInfo:@{ NSLocalizedDescriptionKey:@"Not enough free disk space" }];
    }

    if (!error) {
        [self.receivedDataBuffer setData:nil];

        dispatch_async(dispatch_get_main_queue(), ^{
            if (self.firstResponseBlock) {
                self.firstResponseBlock(response);
            }
            if ([self.delegate respondsToSelector:@selector(download:didReceiveFirstResponse:)]) {
                [self.delegate download:self didReceiveFirstResponse:response];
            }
        });
    }
    else {
        [self notifyFromCompletionWithError:error pathToFile:self.pathToFile];
    }
}

- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData *)data
{
    [self.receivedDataBuffer appendData:data];
    self.receivedDataLength += [data length];

    TCLog(@"%@ | %.2f%% - Received: %ld - Total: %ld",
          self.pathToFile,
          (float) self.receivedDataLength / self.expectedDataLength * 100,
          (long) self.receivedDataLength, (long) self.expectedDataLength);

    if (self.receivedDataBuffer.length > self.bufferSize && [self isExecuting]) {
        [self.file writeData:self.receivedDataBuffer];
        [self.receivedDataBuffer setData:nil];
    }

    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.progressBlock) {
            self.progressBlock(self.receivedDataLength, self.expectedDataLength, self.remainingTime, self.progress);
        }
        if ([self.delegate respondsToSelector:@selector(download:didReceiveData:onTotal:progress:)]) {
            [self.delegate download:self
                     didReceiveData:self.receivedDataLength
                            onTotal:self.expectedDataLength
                           progress:self.progress];
        }
    });
}

- (void)connectionDidFinishLoading:(NSURLConnection*)connection
{
    if ([self isExecuting]) {
        [self.file writeData:self.receivedDataBuffer];
        [self.receivedDataBuffer setData:nil];

        [self notifyFromCompletionWithError:nil pathToFile:self.pathToFile];
    }
}

#pragma mark - Public Methods

- (void)cancelDownloadAndRemoveFile:(BOOL)remove
{
    // Cancel the connection before deleting the file
    [self.connection cancel];

    if (remove) {
        NSError *error;
        if (![self removeFileWithError:&error]) {
            [self notifyFromCompletionWithError:error pathToFile:nil];
            return;
        }
    }

    [self cancel];
}

- (void)addDependentDownload:(TCBlobDownloader *)download
{
    [self addDependency:download];
}

#pragma mark - Internal Methods

- (void)finishOperationWithState:(TCBlobDownloadState)state
{
    // Cancel the connection in case cancel was called directly
    [self.connection cancel];
    [self.speedTimer invalidate];
    [self.file closeFile];

    // Let's finish the operation once and for all
    [self willChangeValueForKey:@"isFinished"];
    [self willChangeValueForKey:@"isExecuting"];
    self.state = state;
    [self didChangeValueForKey:@"isExecuting"];
    [self didChangeValueForKey:@"isFinished"];
}

- (void)cancel
{
    [self willChangeValueForKey:@"isCancelled"];
    [self finishOperationWithState:TCBlobDownloadStateCancelled];
    [self didChangeValueForKey:@"isCancelled"];
}

- (void)notifyFromCompletionWithError:(NSError *)error pathToFile:(NSString *)pathToFile
{
    BOOL success = error == nil;

    // Notify from error if any
    if (error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (self.errorBlock) {
                self.errorBlock(error);
            }
            if ([self.delegate respondsToSelector:@selector(download:didStopWithError:)]) {
                [self.delegate download:self didStopWithError:error];
            }
        });
    }

    // Notify from completion if the operation
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.completeBlock) {
            self.completeBlock(success, pathToFile);
        }
        if ([self.delegate respondsToSelector:@selector(download:didFinishWithSuccess:atPath:)]) {
            [self.delegate download:self didFinishWithSuccess:success atPath:pathToFile];
        }
    });

    // Finish the operation
    TCBlobDownloadState finalState = success ? TCBlobDownloadStateDone : TCBlobDownloadStateFailed;
    [self finishOperationWithState:finalState];
}

- (void)updateTransferRate
{
    if (self.samplesOfDownloadedBytes.count > kNumberOfSamples) {
        [self.samplesOfDownloadedBytes removeObjectAtIndex:0];
    }

    // Add the sample
    [self.samplesOfDownloadedBytes addObject:[NSNumber numberWithUnsignedLongLong:self.receivedDataLength - self.previousTotal]];
    self.previousTotal = self.receivedDataLength;
    // Compute the speed rate on the average of the last seconds samples
    self.speedRate = [[self.samplesOfDownloadedBytes valueForKeyPath:@"@avg.longValue"] longValue];
}

- (BOOL)removeFileWithError:(NSError *__autoreleasing *)error
{
    NSFileManager *fm = [NSFileManager defaultManager];
    if ([fm fileExistsAtPath:self.pathToFile]) {
        return [fm removeItemAtPath:self.pathToFile error:error];
    }

    return YES;
}

+ (NSNumber *)freeDiskSpace
{
    NSDictionary *fattributes = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:nil];
    return [fattributes objectForKey:NSFileSystemFreeSize];
}

#pragma mark - Custom Getters

- (NSString *)fileName
{
    return _fileName ? _fileName : [[NSURL URLWithString:[self.downloadURL absoluteString]] lastPathComponent];
}

- (NSString *)pathToFile
{
    return [self.pathToDownloadDirectory stringByAppendingPathComponent:self.fileName];
}

- (NSInteger)remainingTime
{
    return self.speedRate > 0 ? ((NSInteger) (self.expectedDataLength - self.receivedDataLength) / self.speedRate) : -1;
}

- (float)progress
{
    return (_expectedDataLength == 0) ? 0 : (float) self.receivedDataLength / (float) self.expectedDataLength;
}

@end


text:
'use strict';

/**
 * Module dependencies.
 */
var should = require('should'),
  mongoose = require('mongoose'),
  User = mongoose.model('User'),
  Dispositivo = mongoose.model('Dispositivo');

/**
 * Globals
 */
var user, dispositivo;

/**
 * Unit tests
 */
describe('Dispositivo Model Unit Tests:', function() {
  beforeEach(function(done) {
    user = new User({
      firstName: 'Full',
      lastName: 'Name',
      displayName: 'Full Name',
      email: 'test@test.com',
      username: 'username',
      password: 'password'
    });

    user.save(function() {
      dispositivo = new Dispositivo({
        name: 'Dispositivo Name',
        user: user
      });

      done();
    });
  });

  describe('Method Save', function() {
    it('should be able to save without problems', function(done) {
      this.timeout(0);
      return dispositivo.save(function(err) {
        should.not.exist(err);
        done();
      });
    });

    it('should be able to show an error when try to save without name', function(done) {
      dispositivo.name = '';

      return dispositivo.save(function(err) {
        should.exist(err);
        done();
      });
    });
  });

  afterEach(function(done) {
    Dispositivo.remove().exec(function(){
      User.remove().exec(function(){
        done();
      });
    });
  });
});


text:
var path = require('path');
var config = require('./webpack.config.js');

var libMainFile = path.resolve(__dirname, 'lib', 'index');
var buildPath = path.resolve(__dirname, 'dist');

config.entry = [libMainFile];

config.output = {
    path: buildPath,
    filename: 'all.min.js',
    libraryTarget: 'umd'
};

module.exports = config;


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Enchir. fung. (Paris) 111 (1886)

#### Original name
Agaricus squamosus Schaeff., 1774

### Remarks
null


text:
package br.org.itai.amqpservice.proxy;

import java.lang.reflect.Proxy;

import br.org.itai.amqpservice.connection.interfaces.ConnectionFactory;
import br.org.itai.amqpservice.connection.interfaces.DestinationFactory;
import br.org.itai.amqpservice.convertion.interfaces.ConverterFactory;
import br.org.itai.amqpservice.proxy.annotations.service.ServiceAddress;
import br.org.itai.amqpservice.proxy.annotations.service.ServiceQueue;
import br.org.itai.amqpservice.proxy.services.impl.AnnotatedServiceImpl;

public class AMQPService {

	private ConnectionFactory connectionFactory;
	private DestinationFactory destinationFactory;
	private ConverterFactory converterFactory;

	public AMQPService(ConnectionFactory cf, DestinationFactory qf,
			ConverterFactory cvf) {
		this.connectionFactory = cf;
		this.destinationFactory = qf;
		this.converterFactory = cvf;
	}

	public <T> T create(Class<T> clazz) throws Exception {

		// create proxy to the interface
		@SuppressWarnings("unchecked")
		T object = (T) Proxy.newProxyInstance(
				clazz.getClassLoader(),
				new Class[] { clazz },
				new AnnotatedServiceImpl(clazz, clazz
						.getAnnotation(ServiceAddress.class), clazz
						.getAnnotation(ServiceQueue.class), connectionFactory,
						destinationFactory, converterFactory));

		return object;
	}
}


text:
<?xml version='1.0' encoding='utf-8'?>
<manifest android:hardwareAccelerated="true" android:versionCode="1" android:versionName="0.1.0" package="com.KitsuneGaming.ImpromptuTopicGenerator" xmlns:android="http://schemas.android.com/apk/res/android">
    <supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:resizeable="true" android:smallScreens="true" android:xlargeScreens="true" />
    <uses-permission android:name="android.permission.INTERNET" />
    <application android:hardwareAccelerated="true" android:icon="@drawable/icon" android:label="@string/app_name" android:supportsRtl="true">
        <activity android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale" android:label="@string/activity_name" android:launchMode="singleTop" android:name="MainActivity" android:theme="@android:style/Theme.DeviceDefault.NoActionBar" android:windowSoftInputMode="adjustResize">
            <intent-filter android:label="@string/launcher_name">
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    <uses-sdk android:minSdkVersion="10" android:targetSdkVersion="15" />
</manifest>


text:
"""reggae/venues/views.py."""
from braces.views import LoginRequiredMixin

from django.contrib import messages
from django.urls import reverse
from django.views.generic import (CreateView, DeleteView,
                                  DetailView, ListView, UpdateView)

from .forms import VenueForm
from .models import Venue

class FormActionMixin(object):
    """Custom functionality for data-manipulation views.

    1. display success messages
    2. make the cancel button work
    """

    @property
    def success_msg(self):  # noqa: D102
        return NotImplemented  # pragma: no cover

    def form_valid(self, form):
        """Display success message when form validated."""
        messages.success(self.request, self.success_msg)
        return super(FormActionMixin, self).form_valid(form)

    # def post(self, request, *args, **kwargs):
    #     """Add 'Cancel' button redirect."""
    #     if "cancel" in request.POST:
    #         return HttpResponseRedirect(self.get_success_url())
    #     else:
    #         return super(FormActionMixin, self).post(request, *args, **kwargs)

class VenueListView(LoginRequiredMixin, ListView):
    """ListView for the Venue model."""

    model = Venue
    template_name = 'venues/venue_list.html'
    context_object_name = 'venues'
    ordering = 'name'

class VenueDetailView(LoginRequiredMixin, DetailView):
    """DetailView for the Venue model."""

    model = Venue
    context_object_name = 'venue'

class VenueCreateView(LoginRequiredMixin, FormActionMixin, CreateView):
    """CreateView for the Venue model."""

    model = Venue
    form_class = VenueForm
    template_name = 'model_form.html'
    success_msg = 'Venue created'

    def get_success_url(self):
        """Return the venue list."""
        return reverse('venues:list')

class VenueUpdateView(LoginRequiredMixin, FormActionMixin, UpdateView):
    """UpdateView for the Venue model."""

    model = Venue
    form_class = VenueForm
    template_name = 'model_form.html'
    success_msg = 'Venue updated'

    def get_success_url(self):
        """Return the venue list."""
        return reverse('venues:list')

class VenueDeleteView(LoginRequiredMixin, FormActionMixin, DeleteView):
    """DeleteView for the Venue model."""

    model = Venue
    template_name = 'model_delete.html'
    success_msg = 'Venue deleted'

    def get_success_url(self):
        """Return the home page."""
        return reverse('venues:list')

    def delete(self, request, *args, **kwargs):
        """Display success message on delete."""
        messages.success(self.request, self.success_msg)
        return super(VenueDeleteView, self).delete(request, *args, **kwargs)


text:
using System;

public class Stack<T>
{
    private const int INITIAL_SIZE = 4;
    private T[] InnerArray { get; set; }
    private int StackTop { get; set; }
    public int Count
    {
        get
        {
            return this.StackTop;
        }
    }

    public Stack()
    {
        this.InnerArray = new T[INITIAL_SIZE];
        this.StackTop = 0;
    }

    public T Pop()
    {
        if (this.StackTop == 0) throw new InvalidOperationException("Stack is empty!");
        this.StackTop--;
        return this.InnerArray[this.StackTop];
    }

    public void Push(T item)
    {
        if(this.StackTop == this.InnerArray.Length)
        {
            T[] resizedArray = new T[this.InnerArray.Length * 2];
            Array.Copy(this.InnerArray, resizedArray, this.InnerArray.Length);
            this.InnerArray = resizedArray;
        }
        this.InnerArray[this.StackTop] = item;
        this.StackTop++;
    }

    public T Peek()
    {
        if (this.StackTop == 0) throw new InvalidOperationException("Stack is empty!");
        return this.InnerArray[this.StackTop - 1];
    }

    public void Clear()
    {
        this.StackTop = 0;
        this.InnerArray = new T[4];
    }

    public T[] ToArray()
    {
        var result = new T[this.StackTop];
        Array.Copy(this.InnerArray, result, result.Length);
        return result;
    }
}


text:
/**
 * Tests that using the $set update modifier to change only the type of a field will actually update
 * the document, including any relevant indices.
 */

load("jstests/libs/analyze_plan.js");  // For 'isIndexOnly'.

(function() {
    "use strict";

    var coll = db.set_type_change;
    coll.drop();
    assert.commandWorked(coll.ensureIndex({a: 1}));

    assert.writeOK(coll.insert({a: 2}));

    var newVal = new NumberLong(2);
    var res = coll.update({}, {$set: {a: newVal}});
    assert.eq(res.nMatched, 1);
    if (coll.getMongo().writeMode() == "commands")
        assert.eq(res.nModified, 1);

    // Make sure it actually changed the type.
    var updated = coll.findOne();
    assert(updated.a instanceof NumberLong, "$set did not update type of value: " + updated.a);
})();


text:
namespace image_codec_compression {

// Sets color0 and color1 to the best end point colors to use to represent the
// constant block color, target_color.  Returns the 2-bit value to use to encode
// the pixels in the block.
// If always_4_color_case is false, will also use 1/2-way interpolation rules
// to reduce errors further.
int GetBestDxtcConstColors(const RgbInt& target_color,
                           Rgb565* color0, Rgb565* color1,
                           bool always_4_color_case);

}  // namespace image_codec_compression

#endif  // IMAGE_COMPRESSION_INTERNAL_DXTC_CONST_COLOR_TABLE_H_


text:
RFM96::RFM96(Module* mod) : SX1278(mod) {

}

int16_t RFM96::begin(float freq, float bw, uint8_t sf, uint8_t cr, uint8_t syncWord, int8_t power, uint8_t currentLimit, uint16_t preambleLength, uint8_t gain) {
  // execute common part
  int16_t state = SX127x::begin(RFM9X_CHIP_VERSION, syncWord, currentLimit, preambleLength);
  if(state != ERR_NONE) {
    return(state);
  }

  // configure settings not accessible by API
  state = config();
  if(state != ERR_NONE) {
    return(state);
  }

  // configure publicly accessible settings
  state = setFrequency(freq);
  if(state != ERR_NONE) {
    return(state);
  }

  state = setBandwidth(bw);
  if(state != ERR_NONE) {
    return(state);
  }

  state = setSpreadingFactor(sf);
  if(state != ERR_NONE) {
    return(state);
  }

  state = setCodingRate(cr);
  if(state != ERR_NONE) {
    return(state);
  }

  state = setOutputPower(power);
  if(state != ERR_NONE) {
    return(state);
  }

  state = setGain(gain);
  if(state != ERR_NONE) {
    return(state);
  }

  return(state);
}

int16_t RFM96::setFrequency(float freq) {
  // check frequency range
  if((freq < 433.0) || (freq > 470.0)) {
    return(ERR_INVALID_FREQUENCY);
  }

  // set frequency
  return(SX127x::setFrequencyRaw(freq));
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright 2015 Daniel Sawano
  ~
  ~ 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.
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.0.RELEASE</version>
        <relativePath />
        <!-- lookup parent from repository -->
    </parent>

    <groupId>se.sawano.eureka</groupId>
    <artifactId>legacy-registrar</artifactId>
    <version>0.0.7-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>eureka-legacy-registrar</name>
    <description>Lib for registering legacy applications with Eureka service discovery</description>

    <url>https://github.com/sawano/eureka-legacy-registrar</url>
    <licenses>
        <license>
            <name>Apache License, Version 2.0</name>
            <url>http://www.apache.org/licenses/LICENSE-2.0</url>
            <distribution>repo</distribution>
        </license>
    </licenses>
    <scm>
        <url>git@github.com:sawano/eureka-legacy-registrar.git</url>
        <connection>scm:git:git@github.com:sawano/eureka-legacy-registrar.git</connection>
        <developerConnection>scm:git:git@github.com:sawano/eureka-legacy-registrar.git</developerConnection>
        <tag>HEAD</tag>
    </scm>

    <developers>
        <developer>
            <name>Daniel Sawano</name>
        </developer>
    </developers>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.netflix.eureka</groupId>
            <artifactId>eureka-client</artifactId>
            <version>1.4.12</version>
            <exclusions>
                <exclusion>
                    <!-- Exclude this since it can cause problems as a transitive dependency -->
                    <groupId>javax.servlet</groupId>
                    <artifactId>servlet-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.netflix.archaius</groupId>
            <artifactId>archaius-core</artifactId>
            <version>0.7.4</version>
        </dependency>
        <dependency>
            <groupId>se.sawano.java</groupId>
            <artifactId>commons</artifactId>
            <version>1.3</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <version>2.4</version>
                <executions>
                    <execution>
                        <id>attach-sources</id>
                        <goals>
                            <goal>jar-no-fork</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>2.10.3</version>
                <executions>
                    <execution>
                        <id>attach-javadocs</id>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-release-plugin</artifactId>
                <version>2.5.3</version>
                <configuration>
                    <autoVersionSubmodules>true</autoVersionSubmodules>
                    <useReleaseProfile>false</useReleaseProfile>
                    <releaseProfiles>release</releaseProfiles>
                    <goals>deploy</goals>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <profiles>
        <profile>
            <id>release</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.sonatype.plugins</groupId>
                        <artifactId>nexus-staging-maven-plugin</artifactId>
                        <version>1.6.6</version>
                        <extensions>true</extensions>
                        <configuration>
                            <serverId>ossrh</serverId>
                            <nexusUrl>https://oss.sonatype.org/</nexusUrl>
                            <autoReleaseAfterClose>true</autoReleaseAfterClose>
                        </configuration>
                    </plugin>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-gpg-plugin</artifactId>
                        <version>1.6</version>
                        <executions>
                            <execution>
                                <id>sign-artifacts</id>
                                <phase>verify</phase>
                                <goals>
                                    <goal>sign</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
            <distributionManagement>
                <snapshotRepository>
                    <id>ossrh</id>
                    <url>https://oss.sonatype.org/content/repositories/snapshots</url>
                </snapshotRepository>
                <repository>
                    <id>ossrh</id>
                    <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
                </repository>
            </distributionManagement>
        </profile>
    </profiles>

</project>