text:
define(['mmirf/constants', 'mmirf/configurationManager', 'mmirf/commonUtils', 'mmirf/semanticInterpreter', 'mmirf/util/deferred', 'mmirf/util/loadFile', 'mmirf/logger', 'module'],

	/**
	 * A class for managing the language of the application.

	 * It's purpose is to load the controllers and their views / partials and provide functions to find controllers or
	 * perform actions or helper-actions.
	 *
	 * This "class" is structured as a singleton - so that only one instance is in use.

	 *
	 * @name LanguageManager
	 * @memberOf mmir
	 * @class
	 *
	 *
	 * @requires mmir.Constants
	 * @requires mmir.CommonUtils
	 * @requires mmir.SemanticInterpreter
	 *
	 */
	function(
			constants, configurationManager, commonUtils, semanticInterpreter, deferred, loadFile, Logger, module
){
			//the next comment enables JSDoc2 to map all functions etc. to the correct class description
			/** @scope mmir.LanguageManager.prototype */

		    /**
		     * Object containing the instance of the class
		     * {@link LanguageManager}
		     *
		     * @type Object
		     * @private
		     *
		     * @memberOf LanguageManager#
		     */
		    var instance = null;

		    /**
		     * @private
		     * @type Logger
		     * @memberOf LanguageManager#
		     */
		    var logger = Logger.create(module);

		    /**
		     * JSON object containing the contents of a dictionary file - which are
		     * found in 'config/languages/<language>/dictionary.json'.
		     *
		     * @type JSON
		     * @private
		     *
		     * @memberOf LanguageManager#
		     */
		    var dictionary = null;

		    /**
		     * A String holding the currently loaded language, e.g. "en".
		     *
		     * @type String
		     * @private
		     *
		     * @memberOf LanguageManager#
		     */
		    var currentLanguage = null;

		    /**
		     * A JSON-Object holding the speech-configuration for the currently loaded language.
		     *
		     * @type JSON-Object
		     * @private
		     *
		     * @memberOf LanguageManager#
		     */
		    var currentSpeechConfig = null;

		    /**
		     * An array of all available languages.
		     *
		     * @type Array
		     * @private
		     *
		     * @memberOf LanguageManager#
		     */
		    var languages = null;

		    /**
		     * A keyword which can be used in views (ehtml) to display the current
		     * language.

		     * If this keyword is used inside a view or partial, it is replaced by the
		     * current language string.
		     *
		     * @type String
		     * @private
		     * @example @localize('current_language')
		     *
		     * @memberOf LanguageManager#
		     */
		    var keyword_current_language = 'current_language';

		    /**
		     * Function to set a new language, but only, if the new language is
		     * different from the current language.
		     *
		     * @function
		     * @param {String}
		     *            lang The language of the dictionary which should be loaded.
		     * @returns {String} The (new) current language
		     * @private
		     *
		     * @memberOf LanguageManager#
		     */
		    function setLanguage(lang) {
		        if ((lang) && (currentLanguage != lang)) {
		            loadDictionary(lang);
		            loadSpeechConfig(lang);
		            requestGrammar(lang);
		        }
		        return currentLanguage;
		    }

		    /**
		     * @function
		     * @memberOf LanguageManager#
		     */
		    function doCheckExistsGrammar(lang) {
		        var langFiles = null;
		        var retValue = false;

		        if (lang != null) {
		            langFiles = commonUtils.listDir(constants.getLanguagePath() + lang);
		            if (langFiles != null) {
		                if (langFiles.indexOf(constants.getGrammarFileName()) > -1) {
		                    retValue = true;
		                }
		            }
		        }
		        return retValue;
		    }

		    /**
		     * Request grammar for the provided language.
		     *
		     * If there is no grammar available for the requested language, no new
		     * grammar is set.
		     *
		     * A grammar is available, if at least one of the following is true for the
		     * requested language
		     *

		     *
there exists a JSON grammar file (with correct name and at the
		     * 		correct location)

		     *
there exists a compiled JavaScript grammar file (with correct name
		     * 		and at the correct location)

		     *

		     *
		     * TODO document location for JSON and JavaScript grammar files
		     *
		     * @function
		     * @param {String}
		     *            lang The language of the grammar which should be loaded.
		     * @returns {String} The current grammar language
		     * @async
		     * @private
		     *
		     * @memberOf LanguageManager#
		     */
		    function requestGrammar(lang, doSetNextBestAlternative) {

		        if (semanticInterpreter.hasGrammar(lang) || doCheckExistsGrammar(lang)) {
		            semanticInterpreter.setCurrentGrammar(lang);
		            return lang;
		        }
				else if (doSetNextBestAlternative) {
		            // try to find a language, for which a grammar is available
		            var grammarLang = null;
		            if (languages.length > 0) {
		                // first: try to find a language with COMPILED grammar
		                for ( var i = 0, size = languages.length; i < size; ++i) {
		                    grammarLang = languages[i];
		                    if (semanticInterpreter.hasGrammar(grammarLang)) {
		                        break;
		                    }
							else {
		                        grammarLang = null;
		                    }
		                }

		                // ... otherwise: try to find a language with JSON grammar:
		                if (!grammarLang) {
		                    for ( var i = 0, size = languages.length; i < size; ++i) {
		                        grammarLang = languages[i];
		                        if (doCheckExistsGrammar(grammarLang)) {
		                            break;
		                        }
								else {
		                            grammarLang = null;
		                        }
		                    }
		                }
		            }

		            if (grammarLang) {
		                logger.warn('Could not find grammar for selected language ' + lang + ', using grammar for language ' + grammarLang + ' instead.');
		                semanticInterpreter.setCurrentGrammar(grammarLang);
		            }
					else {
		                logger.info('Could not find any grammar for one of [' + languages.join(', ') + '], disabling SemanticInterpret.');
		                semanticInterpreter.setEnabled(false);
		            }
		        }

		        return semanticInterpreter.getCurrentGrammar();
		    }
		    /**
		     * Loads the speech-configuration for the provided language and updates the current
		     * language.
		     *
		     * @function
		     * @param {String} lang
		     *            The language of the speech-configuration which should be loaded.
		     * @returns {String} The (new) current language
		     * @async
		     * @private
		     *
		     * @memberOf LanguageManager#
		     */
		    function loadSpeechConfig(lang) {

		        if (lang && currentLanguage != lang) {
		            currentLanguage = lang;
		        }
		        var path = constants.getLanguagePath() + lang + "/" + constants.getSpeechConfigFileName();
		        loadFile({
		            async : false,
		            dataType : "json",
		            url : path,
		            success : function(data) {

		            	if(logger.isVerbose()) logger.v("[LanguageManager] Success. " + data);

		            	currentSpeechConfig = data;

		                if(logger.isVerbose()) logger.v("[LanguageManager] " + JSON.stringify(dictionary));
		            },
		            error : function(xhr, statusStr, error) {
		                logger.error("[LanguageManager] Error loading speech configuration from \""+path+"\": " + error? error.stack? error.stack : error : ''); // error
		            }
		        });
		        return currentLanguage;
		    }

		    /**
		     * Loads the dictionary for the provided language and updates the current
		     * language.
		     *
		     * @function
		     * @param {String}
		     *            lang The language of the dictionary which should be loaded.
		     * @returns {String} The (new) current language
		     * @async
		     * @private
		     *
		     * @memberOf LanguageManager#
		     */
		    function loadDictionary(lang) {

		        if (lang && currentLanguage != lang) {
		            currentLanguage = lang;
		        }
		        var path = constants.getLanguagePath() + lang + "/" + constants.getDictionaryFileName();
		        loadFile({
		            async : false,
		            dataType : "json",
		            url : path,
		            success : function(data) {
		                dictionary = data;
		            },
		            error : function(xhr, statusStr, error) {
		                logger.error("[LanguageManager] Error loading language dictionary from \""+path+"\": " + error? error.stack? error.stack : error : ''); // error
		            }
		        });
		        return currentLanguage;
		    }
		    /**
		     * Translates a keyword using the current dictionary and returns the
		     * translation.
		     *
		     * @function
		     * @param {String}
		     *            textVarName The keyword which should be looked up
		     * @returns {String} the translation of the keyword
		     * @private
		     *
		     * @memberOf LanguageManager#
		     */
		    function internalGetText(textVarName) {
		        var translated = "";
		        if (dictionary[textVarName] && dictionary[textVarName].length > 0) {
		            translated = dictionary[textVarName];
		        }
				else if (textVarName === keyword_current_language){
		            translated = currentLanguage;
		        }
				else {
		            translated = "undefined";
		            logger.warn("[Dictionary] '" + textVarName + "' not found in " + JSON.stringify(dictionary));
		        }
		        return translated;
		    }

		    /**
		     * Constructor-Method of Singleton mmir.LanguageManager.

		     *
		     * @constructs LanguageManager
		     * @memberOf LanguageManager#
		     * @private
		     * @ignore
		     *
		     */
		    function constructor() {

		        var _isInitialized = false;

		        /** @lends LanguageManager.prototype */
		        return {

		        	/**
		        	 * @param {String} [lang] OPTIONAL
		        	 * 				a language code for setting the current language and
		        	 * 				selecting the corresponding language resources
		        	 *
		        	 * @returns {Promise}
		        	 * 				a deferred promise that gets resolved when the language manager is initialized
		        	 *
		        	 * @memberOf LanguageManager.prototype
		        	 */
		        	init: function(lang){

		        		if (!lang && !currentLanguage) {

		        			//try to retrieve language from configuration:
				            var appLang = configurationManager.get("language");
				            if (appLang) {

				                lang = appLang;
				                logger.info("[LanguageManager] No language argument specified: using language from configuration '" + appLang + "'.");

				            }
				            else {

					            appLang = constants.getLanguage();

				            	if (appLang) {

					                lang = appLang;
					                logger.info("[LanguageManager] No language argument specified: using language from mmir.constants '" + appLang + "'.");
					            }
				            	else {

					                if (languages.length > 0) {

					                	appLang = this.determineLanguage(lang);
					                	if(appLang){

					                		lang = appLang;

					                		logger.info("[LanguageManager] No language argument specified: used determinLanguage() for selecting language '" + appLang + "'.");
					                	}
					                }

					            }//END: else(consts::lang)

				            }//END: else(config::lang)

			        		if(!lang){
			        			logger.warn("[LanguageManager.init] No language specified. And no language could be read from directory '" + constants.getLanguagePath() + "'.");
			        		}

				        }//END: if(!lang && !currentLanguage)

				        // get all the languages/dictionaries by name
				        languages = commonUtils.listDir(constants.getLanguagePath());

				        if (logger.isDebug()) logger.debug("[LanguageManager] Found dictionaries for: " + JSON.stringify(languages));// debug

				        var defer = deferred();

				        loadDictionary(lang);
				        loadSpeechConfig(lang);
				        requestGrammar(lang, true);//2nd argument TRUE: if no grammar is available for lang, try to find/set any available grammar

				        _isInitialized = true;
				        defer.resolve(this);

				        return defer;
		        	},

		            /**
		             * Returns the dictionary of the currently used language.
		             *
		             * @function
		             * @returns {Object} The JSON object for the dictionary of the
		             *          currently used language
		             * @public
		             */
		            getDictionary : function() {
		                return dictionary;
		            },

		            /**
		             * If a dictionary exists for the given language, 'true' is
		             * returned. Else the method returns 'false'.
		             *
		             * @function
		             * @returns {Boolean} True if a dictionary exists for given
		             *          language.
		             * @param {String}
		             *            Language String, i.e.: en, de
		             * @public
		             */
		            existsDictionary : function(lang) {
		                var langFiles = null;
		                var retValue = false;

		                if (lang != null) {
		                    langFiles = commonUtils.listDir(constants.getLanguagePath() + lang);
		                    if (langFiles != null) {
		                        if (langFiles.indexOf(constants.getDictionaryFileName()) > -1) {
		                            retValue = true;
		                        }
		                    }
		                }
		                return retValue;
		            },

		            /**
		             * If a speech-configuration (file) exists for the given language.
		             *
		             * @function
		             * @returns {Boolean}
		             * 				trueif a speech-configuration exists for given language.
		             * 				Otherwise false.
		             *
		             * @param {String} lang
		             *            the language for which existence of the configuration should be checked, e.g. en, de
		             *
		             * @public
		             */
		            existsSpeechConfig : function(lang) {
		                var langFiles = null;
		                var retValue = false;

		                if (lang != null) {
		                    langFiles = commonUtils.listDir(constants.getLanguagePath() + lang);
		                    if (langFiles != null) {
		                        if (langFiles.indexOf(constants.getSpeechConfigFileName()) > -1) {
		                            retValue = true;
		                        }
		                    }
		                }
		                return retValue;
		            },

		            /**
		             * If a JSON grammar file exists for the given language, 'true' is
		             * returned. Else the method returns 'false'.
		             *
		             * @function
		             * @returns {Boolean} True if a grammar exists for given language.
		             * @param {String}
		             *            Language String, i.e.: en, de
		             * @public
		             */
		            existsGrammar : doCheckExistsGrammar,

		            /**
		             * Chooses a language for the application.
		             *
		             *

		             * The language selection is done as follows:
		             *

		             *
check if a default language exists

		             * if it does and if both (!) grammar and dictionary exist for this
		             * language, return this language

		             *
walk through all languages alphabetically
		             *

		             *
if for a language both (!) grammar and dictionary exist,
		             * return this language memorize the first language with a grammar
		             * (do not care, if a dictionary exists)

		             *

		             *
test if a grammar exists for the default language - do not
		             * care about dictionaries - if it does, return the default language
		             *

		             *
If a language was found (in Step 2.1) return this language
		             *

		             *
If still no language is returned take the default language
		             * if it has a dictionary

		             *
If a language exists, take it (the first one)

		             *
Take the default language - no matter what

		             *

		             *
		             * @function
		             * @returns {String} The determined language
		             * @public
		             */
		            determineLanguage : function(lang) {
		                var tempLanguage = lang;
		                var firstLanguageWithGrammar = null;

		                // first check, if language - given in parameter - exists
		                if (tempLanguage != null) {
		                    // check if both grammar and dictionary exist for given
		                    // language
		                    if (instance.existsGrammar(tempLanguage) && instance.existsDictionary(tempLanguage)) {
		                        return tempLanguage;
		                    }
		                }

		                tempLanguage = constants.getLanguage();
		                // then check, if default language exists
		                if (tempLanguage != null) {
		                    // check if both grammar and dictionary exist for default
		                    // language
		                    if (instance.existsGrammar(tempLanguage) && instance.existsDictionary(tempLanguage)) {
		                        return tempLanguage;
		                    }
		                }
		                // walk through the languages alphabetically
		                for ( var i = 0; i < languages.length; i++) {
		                    tempLanguage = languages[i];
		                    // check if a grammar and dictionary exists for every
		                    // language
		                    if (instance.existsGrammar(tempLanguage)) {

		                        // memorize the first language with a grammar (for
		                        // later)
		                        if (firstLanguageWithGrammar == null) {
		                            firstLanguageWithGrammar = tempLanguage;
		                        }

		                        if (instance.existsDictionary(tempLanguage)) {
		                            return tempLanguage;
		                        }
		                    }
		                }

		                // still no language found - take the default language and test
		                // if a grammar exists
		                tempLanguage = constants.getLanguage();
		                if (tempLanguage != null) {
		                    // check if both grammar and dictionary exist for default
		                    // language
		                    if (instance.existsGrammar(tempLanguage)) {
		                        return tempLanguage;
		                    } else if (firstLanguageWithGrammar != null) {
		                        return firstLanguageWithGrammar;
		                    } else if (instance.existsDictionary(tempLanguage)) {
		                        return tempLanguage;
		                    }
		                }

		                // still no language - take the first one
		                tempLanguage = languages[0];
		                if (tempLanguage != null) {
		                    return tempLanguage;
		                }

		                return constants.getLanguage();
		            },

		            /**
		             * Sets a new language, but only, if the new language is different
		             * from the current language.
		             *
		             * @function
		             * @returns {String} The (new) current language
		             * @public
		             */
		            setLanguage : function(lang) {
		                return setLanguage(lang);
		            },

		            /**
		             * Gets the language currently used for the translation.
		             *
		             * @function
		             * @returns {String} The current language
		             * @public
		             */
		            getLanguage : function() {
		                return currentLanguage;
		            },

		            /**
		             * Gets the default language.
		             *
		             * @function
		             * @returns {String} The default language
		             * @public
		             */
		            getDefaultLanguage : function() {
		                return constants.getLanguage();
		            },

		            /**
		             * Gets an array of all for the translation available languages.

		             *
		             * @function
		             * @returns {String} An array of all for the translation available
		             *          languages
		             * @public
		             */
		            getLanguages : function() {
		                return languages;
		            },

		            /**
		             * Cycles through the available languages.
		             *
		             * @function
		             * @returns {String} The (new) current language
		             * @public
		             * @deprecated unused
		             */
		            setNextLanguage : function() {
		                var indexCurrentLanguage = languages.indexOf(currentLanguage);

		                if (logger.isVerbose()) logger.v("[LanguageManager] Current language is " + currentLanguage);

		                if (indexCurrentLanguage > -1) {
		                    indexCurrentLanguage = indexCurrentLanguage + 1;
		                    if (indexCurrentLanguage > languages.length - 1) {
		                        indexCurrentLanguage = 0;
		                    }
		                    currentLanguage = languages[indexCurrentLanguage];

		                    if (logger.isVerbose()) logger.v("[LanguageManager] Next language is " + currentLanguage);

		                    loadSpeechConfig(currentLanguage);
		                    return loadDictionary(currentLanguage);
		                }
		                return currentLanguage;
		            },

		            /**
		             * Looks up a keyword in the current dictionary and returns the
		             * translation.
		             *
		             * @function
		             * @param {String}
		             *            textVarName The keyword which is to be translated
		             * @returns {String} The translation of the keyword
		             * @public
		             */
		            getText : function(textVarName) {
		                return internalGetText(textVarName);
		            },

		            /**
		             * Get the language code setting for a specific plugin.
		             *
		             * Returns the default setting, if no specific setting for the specified plugin was defined.
		             *
		             * @public
		             * @param {String} pluginId
		             * @param {String|Array<String>} [feature] OPTIONAL
		             * 				dot-separate path String or "path Array"
		             * 				This parameter may be omitted, if no separator parameter
		             * 				is used.
		             * 				DEFAULT: "language" (the language feature)
		             * @param {String} [separator] OPTIONAL
		             * 				the speparator-string that should be used for separating
		             * 				the country-part and the language-part of the code
		             * @returns {String} the language-setting/-code
		             */
		            getLanguageConfig : function(pluginId, feature, separator) {

		                //if nothing is specfied:
		            	//	return default language-setting
		                if(typeof pluginId === 'undefined'){
		                	return currentSpeechConfig.language; /////////// EARLY EXIT ///////////////
		                }

		                //ASSERT pluginId is defined

		                //default feature is language
		                if(typeof feature === 'undefined'){
		                	feature = 'language';
		                }

		                var value;
		                if(currentSpeechConfig.plugins && currentSpeechConfig.plugins[pluginId] && typeof currentSpeechConfig.plugins[pluginId][feature] !== 'undefined'){
		                	//if there is a plugin-specific setting for this feature
		                	value = currentSpeechConfig.plugins[pluginId][feature];
		                }
		                else if(feature !== 'plugins' && typeof currentSpeechConfig[feature] !== 'undefined'){
		                	//otherwise take the default setting (NOTE: the name "plugins" is not allowed for features!)
		                	value = currentSpeechConfig[feature];
		                }

		                //if there is a separator specified: replace default separator '-' with this one
		                if(value && typeof separator !== 'undefined'){
		                	value = value.replace(/-/, separator);
		                }

		                return value;
		            },

		            /**
		             * HELPER for dealing with specific language / country code quirks of speech services:
		             * Get the language code for a specific ASR or TTS service, that is if the service requires some
		             * specific codes/transformations, then the transformed code is retruned by this function
		             * (otherwise the unchanged langCode is returned).
		             *
		             * @public
		             * @param {String} providerName
		             * 					corrections for: "nuance" | "mary"
		             * @param {String} langCode
		             * 					the original language / country code
		             * @returns {String} the (possibly "fixed") language-setting/-code
		             */
		            fixLang : function(providerName, langCode) {

		            	if(providerName === 'nuance'){

		            		//QUIRK nuanceasr short-language code for the UK is UK instead of GB:
		            		//  replace en-GB with en-UK if necessary (preserving separator char)
		            		langCode = langCode.replace(/en(.)GB/i, 'en$1UK');

		            	} else if(providerName === 'mary'){

		            		//QUIRK marytts does not accept language+country code for German:
		        			//  must only be language code
		        			if(/de.DE/i.test(langCode)){
		        				langCode = 'de';
		        			}
		            	}

		            	return langCode;
		            }

		        };//END: return{}

		    }//END: construcor = function(){...

		    //FIXME as of now, the LanguageManager needs to be initialized,
		    //		by calling init()
		    //		-> should this be done explicitly (async-loading for dictionary and grammar? with returned Deferred?)
		    instance = new constructor();

		    return instance;

});


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>JSDoc: Module: sw-testing-helpers</title>

    <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
    <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">

Module: sw-testing-helpers

sw-testing-helpers can be used in node, a browser or in a service worker.
Different classes are exposed depending on what is imported and where.

When you require `sw-testing-helpers` you'll have access to a few
parameters

require('sw-testing-helpers').TestServer;
require('sw-testing-helpers').automatedBrowserTesting;
require('sw-testing-helpers').mochaUtils;

Properties:

        Name

        Type

        Description

                TestServer

TestServer

            The TestServer class
that can be extended and instantiated.

                automatedBrowserTesting

AutomatedBrowserTesting

            An instance of
the AutomatedBrowserTesting class.

                mochaUtils

MochaUtils

            An instance of
the MochaUtils class.

Source:

        index.js, line 26

Home

Modules

sw-testing-helpers

Classes

AutomatedBrowserTesting

MochaUtils

SWUtils

TestServer

WebDriverBrowser

Global

    Documentation generated by JSDoc 3.4.0 on Tue May 24 2016 19:06:46 GMT+0100 (BST)

redpajama_set_name: RedPajamaGithub


text:
<% if (isJekyll) { %>---
title: tns update
position: 16
---<% } %>

# tns update

### Description

Updates the project with the latest versions of iOS/Android runtimes, cross-platform modules and "nativescript-dev-webpack".
In order to get the latest development release instead, pass `next` as argument:
`tns update next`

You can also switch to specific version by passing it to the command:
`tns update 5.0.0`

**NOTE:** The provided version should be an existing version of the project template for this project type.

### Commands

Usage | Synopsis
------|-------
General | `$ tns update`

<% if(isHtml) { %>

### Related Commands

Command | Description
----------|----------
[usage-reporting](usage-reporting.html) | Configures anonymous usage reporting for the NativeScript CLI.
[error-reporting](error-reporting.html) | Configures anonymous error reporting for the NativeScript CLI.
[autocomplete](autocomplete.html) | Prints your current command-line completion settings. If disabled, prompts you to enable it.
[help](help.html) | Lists the available commands or shows information about the selected command.
[doctor](doctor.html) | Checks your system for configuration problems which might prevent the NativeScript CLI from working properly.
[proxy](proxy.html) | Displays proxy settings.
[proxy clear](proxy-clear.html) | Clears proxy settings.
[proxy set](proxy-set.html) | Sets proxy settings.
[update](update.html) | Updates the project with the latest versions of iOS/Android runtimes and cross-platform modules.
<% } %>


text:
package com.builtamont.cassandra.migration.internal.util.scanner.classpath;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

/**
 * Tests for ClassPathResource.
 */
public class ClassPathResourceSmallTest {
    @Test
    public void getFilename() throws Exception {
        assertEquals("Mig777__Test.cql", new ClassPathResource("Mig777__Test.cql", Thread.currentThread().getContextClassLoader()).getFilename());
        assertEquals("Mig777__Test.cql", new ClassPathResource("folder/Mig777__Test.cql", Thread.currentThread().getContextClassLoader()).getFilename());
    }

    @Test
    public void loadAsStringUtf8WithoutBOM() {
        assertEquals("SELECT * FROM contents;",
                new ClassPathResource("com/builtamont/cassandra/migration/internal/util/scanner/classpath/utf8.nofilter", Thread.currentThread().getContextClassLoader()).loadAsString("UTF-8"));
    }

    @Test
    public void loadAsStringUtf8WithBOM() {
        assertEquals("SELECT * FROM contents;",
                new ClassPathResource("com/builtamont/cassandra/migration/internal/util/scanner/classpath/utf8bom.nofilter", Thread.currentThread().getContextClassLoader()).loadAsString("UTF-8"));
    }
}


text:
from accounts.access_checkers import AccessChecker
from accounts.decorators import access_checker
from groups.models import Group, GroupCollaborator

@access_checker(Group)
class GroupAccessChecker(AccessChecker):
    """ """
    model = GroupCollaborator
    object_field_name = 'group'

    def has_access(self, user, obj, access_level):
        collaborator = self.get_object(user, obj)
        return bool(collaborator and collaborator.access_level >= access_level)

group_access_checker = GroupAccessChecker()


text:
<?php

namespace GSB\AndroidBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Offrir
 *
 * @ORM\Table(name="OFFRIR", indexes={@ORM\Index(name="FK_OFFRIR_MEDICAMENT", columns={"MED_DEPOTLEGAL"}), @ORM\Index(name="IDX_EDE68D5869F01356", columns={"COL_MATRICULE"})})
 * @ORM\Entity
 */
class Offrir
{
    /**
     * @var integer
     *
     * @ORM\Column(name="RAP_NUM", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="NONE")
     */
    private $rapNum = '0';

    /**
     * @var integer
     *
     * @ORM\Column(name="OFF_QTE", type="integer", nullable=true)
     */
    private $offQte;

    /**
     * @var \Collaborateur
     *
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="NONE")
     * @ORM\OneToOne(targetEntity="Collaborateur")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="COL_MATRICULE", referencedColumnName="COL_MATRICULE")
     * })
     */
    private $colMatricule;

    /**
     * @var \Medicament
     *
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="NONE")
     * @ORM\OneToOne(targetEntity="Medicament")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="MED_DEPOTLEGAL", referencedColumnName="MED_DEPOTLEGAL")
     * })
     */
    private $medDepotlegal;

    /**
     * Set rapNum
     *
     * @param integer $rapNum
     * @return Offrir
     */
    public function setRapNum($rapNum)
    {
        $this->rapNum = $rapNum;

        return $this;
    }

    /**
     * Get rapNum
     *
     * @return integer
     */
    public function getRapNum()
    {
        return $this->rapNum;
    }

    /**
     * Set offQte
     *
     * @param integer $offQte
     * @return Offrir
     */
    public function setOffQte($offQte)
    {
        $this->offQte = $offQte;

        return $this;
    }

    /**
     * Get offQte
     *
     * @return integer
     */
    public function getOffQte()
    {
        return $this->offQte;
    }

    /**
     * Set colMatricule
     *
     * @param \GSB\AndroidBundle\Entity\Collaborateur $colMatricule
     * @return Offrir
     */
    public function setColMatricule(\GSB\AndroidBundle\Entity\Collaborateur $colMatricule)
    {
        $this->colMatricule = $colMatricule;

        return $this;
    }

    /**
     * Get colMatricule
     *
     * @return \GSB\AndroidBundle\Entity\Collaborateur
     */
    public function getColMatricule()
    {
        return $this->colMatricule;
    }

    /**
     * Set medDepotlegal
     *
     * @param \GSB\AndroidBundle\Entity\Medicament $medDepotlegal
     * @return Offrir
     */
    public function setMedDepotlegal(\GSB\AndroidBundle\Entity\Medicament $medDepotlegal)
    {
        $this->medDepotlegal = $medDepotlegal;

        return $this;
    }

    /**
     * Get medDepotlegal
     *
     * @return \GSB\AndroidBundle\Entity\Medicament
     */
    public function getMedDepotlegal()
    {
        return $this->medDepotlegal;
    }
}


text:
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>
    <predicate lemma="rack">
        <note>
            Based on search-35.2.
        </note>

        <roleset id="rack.02" name="search" vncls="35.2">
            <roles>
                <role descr="searcher" n="0">
                    <vnrole vncls="35.2" vntheta="Agent"/>
                </role>

                <role descr="searched for" n="1">
                    <vnrole vncls="35.2" vntheta="Theme"/>
                </role>

            </roles>

            <example name="rack one's brain">
                <text>
                    I racked my brain for hours trying to recall her name.
                </text>
                <arg n="0">I</arg>
                <rel>racked</rel>
                <arg n="1">my brain</arg>
                <arg f="TMP" n="M">for hours</arg>
                <arg f="PRP" n="M">trying to recall her name</arg>
            </example>

            <note>
            </note>

        </roleset>
    </predicate>

    <predicate lemma="rack_up">
        <note>
            Frames file for 'rack up' based on sentences in financial subcorpus.
            No Verbnet entry.  Comparison with acquire verbs.
        </note>

        <roleset id="rack.01" name="get, acquire" vncls="-">
            <roles>
                <role descr="agent, entity acquiring something" n="0"/>
                <role descr="thing acquired" n="1"/>
                <role descr="seller" n="2"/>
                <role descr="price paid" n="3"/>
                <role descr="benefactive" n="4"/>
            </roles>

            <example name="just transitive">
                <inflection aspect="progressive" form="participle" person="third" tense="present" voice="active"/>
                <text>
                    Toyota's $35,000 Lexus automobile, a luxury model that it started
                    shipping to the U.S. only last month, is racking up orders at a
                    time when U.S.-made luxury-car sales are slow.
                </text>
                <arg n="0">Toyota's $35,000 Lexus automobile, a luxury model
                    that it started shipping to the U.S. only last month,
                </arg>
                <rel>[ racking] [ up]</rel>
                <arg n="1">orders</arg>
                <arg f="TMP" n="M">at a time when U.S.-made luxury-car sales
                    are slow
                </arg>
            </example>

            <note>
                Higher args are theoretically possible but unlikely, to my ear.
            </note>

        </roleset>
    </predicate>
</frameset>


text:
package com.bustiblelemons.cthulhator.character.portrait.ui;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Spinner;
import android.widget.TextView;

import com.bustiblelemons.cthulhator.R;
import com.bustiblelemons.cthulhator.adapters.GenderSpinnerAdapter;
import com.bustiblelemons.cthulhator.adapters.PeriodSpinnerAdapter;
import com.bustiblelemons.cthulhator.character.history.model.YearsPeriod;
import com.bustiblelemons.cthulhator.character.portrait.logic.OnBroadcastOnlineSearchSettings;
import com.bustiblelemons.cthulhator.character.portrait.logic.OnOpenSearchSettings;
import com.bustiblelemons.cthulhator.character.portrait.model.OnlineSearchUISettings;
import com.bustiblelemons.cthulhator.fragments.AbsFragmentWithSerializable;
import com.bustiblelemons.cthulhator.settings.Settings;
import com.bustiblelemons.cthulhator.settings.character.CharacterSettings;
import com.bustiblelemons.cthulhator.settings.character.CharacterSettingsImpl;
import com.bustiblelemons.google.apis.GoogleSearchGender;
import com.bustiblelemons.google.apis.search.params.GoogleImageSearch;
import com.bustiblelemons.views.TitledSeekBar;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

/**
 * Created by bhm on 23.07.14.
 */
public class PortraitsSettingsFragment extends AbsFragmentWithSerializable<CharacterSettings>
        implements View.OnClickListener,
                   GenderSpinnerAdapter.GenderSelected,
                   TitledSeekBar.onValueChanged,
                   PeriodSpinnerAdapter.OnYearsPeriodSelected {

    @InjectView(R.id.action_settings)
    View          settingsButton;
    @InjectView(R.id.gender_spinner)
    Spinner       genderSpinner;
    @InjectView(R.id.year_spinner)
    Spinner       periodSpinner;
    @InjectView(R.id.year_seekbar)
    TitledSeekBar yearSeekbar;
    @InjectView(android.R.id.custom)
    View          content;
    @InjectView(android.R.id.title)
    TextView      titleView;

    private Context mContext;

    private boolean mFoldedOnly = false;
    private GoogleSearchOptsListener        mSearchOptionsChanged;
    private OnBroadcastOnlineSearchSettings mBroadcastSearchSettings;
    private GenderSpinnerAdapter            genderAdapter;
    private PeriodSpinnerAdapter            periodSpinnerAdapter;
    private GoogleImageSearch.Options       searchOptions;
    private OnOpenSearchSettings            onOpenSearchSettings;
    private CharacterSettings               mCharacterSettings;
    private OnlineSearchUISettings          mOnlineSearchUISettings;
    private GoogleSearchGender              mGoogleSearchGender;
    private int                             mSelectedYear;

    public static PortraitsSettingsFragment newInstance(CharacterSettings searchOptions) {
        PortraitsSettingsFragment r = new PortraitsSettingsFragment();
        r.setNewInstanceArgument(searchOptions);
        return r;
    }

    public void setOnBroadcastOnlineSearchSettings(OnBroadcastOnlineSearchSettings onBroadcastOnlineSearchSettings) {
        this.mBroadcastSearchSettings = onBroadcastOnlineSearchSettings;
    }

    public void setFoldedOnly(boolean foldedOnly) {
        this.mFoldedOnly = foldedOnly;
        if (content != null) {
            content.setVisibility(foldedOnly ? View.GONE : View.VISIBLE);
        }
    }

    public void setOnOpenSearchSettings(OnOpenSearchSettings onOpenSearchSettings) {
        this.onOpenSearchSettings = onOpenSearchSettings;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        readLastSettings();
        if (activity instanceof GoogleSearchOptsListener) {
            mSearchOptionsChanged = (GoogleSearchOptsListener) activity;
        }
        if (activity instanceof OnBroadcastOnlineSearchSettings) {
            mBroadcastSearchSettings = (OnBroadcastOnlineSearchSettings) activity;
        }
    }

    public void readLastSettings() {
        mCharacterSettings = Settings.getLastPortraitSettings(getActivity());
        if (mCharacterSettings != null) {
            mSelectedYear = mCharacterSettings.getYear();
            mGoogleSearchGender = mCharacterSettings.getGender();
            mOnlineSearchUISettings = OnlineSearchUISettings.from(mCharacterSettings);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_portraits_settings, container, false);
        ButterKnife.inject(this, rootView);
        yearSeekbar.setValueChangedCallback(this);
        return rootView;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mOnlineSearchUISettings = Settings.getLastKnownPhotoSearchUISettings(view.getContext());
        mContext = view.getContext();
        setupViewForSettings();
    }

    private void setupViewForSettings() {
        if (genderSpinner != null) {
            setupGenderSpinner();
        }
        if (periodSpinner != null) {
            setupPeriodSpinner();
        }
        if (yearSeekbar != null) {
            int progress = mOnlineSearchUISettings.getSeekbarPosition();
            yearSeekbar.setProgress(progress);
        }
        setTitle();
    }

    public void setupPeriodSpinner() {
        periodSpinnerAdapter = new PeriodSpinnerAdapter(mContext, this);
        periodSpinner.setOnItemSelectedListener(periodSpinnerAdapter);
        periodSpinner.setAdapter(periodSpinnerAdapter);
        periodSpinner.setSelection(mOnlineSearchUISettings.getPeriodSpinnerPosition());
    }

    @Override
    protected void onInstanceArgumentRead(CharacterSettings settings) {
        mCharacterSettings = settings;
        mOnlineSearchUISettings = OnlineSearchUISettings.from(settings);
        setupViewForSettings();

    }

    private void setupGenderSpinner() {
        genderAdapter = new GenderSpinnerAdapter(getActivity(), this);
        genderSpinner.setAdapter(genderAdapter);
        genderSpinner.setOnItemSelectedListener(genderAdapter);
    }

    @OnClick(R.id.action_settings)
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
        case R.id.action_settings:
            handleSettingsButton(view);
            break;
        }
    }

    public void handleSettingsButton(View view) {
        if (!mFoldedOnly) {
            boolean expand = !view.isSelected();
            expandSettings(expand);
            manageTitleVisibility(expand);
            view.setSelected(expand);
            if (!expand && mBroadcastSearchSettings != null) {
                mBroadcastSearchSettings.onSettingsChanged(mCharacterSettings, true);
            }
        } else {
            if (onOpenSearchSettings != null) {
                int year = yearSeekbar.getIntValue();
                mCharacterSettings = CharacterSettingsImpl.create(year, mGoogleSearchGender);
                onOpenSearchSettings.onOpenSettings(mCharacterSettings);
            }
        }
    }

    private void manageTitleVisibility(boolean expand) {
        if (titleView != null) {
            titleView.setVisibility(!expand ? View.VISIBLE : View.INVISIBLE);
        }
    }

    public void expandSettings(boolean expand) {
        if (content != null) {
            content.setVisibility(expand ? View.VISIBLE : View.GONE);
        }
    }

    @Override
    public boolean onGenderSelected(GoogleSearchGender selectedGender) {
        if (searchOptions != null) {
            mGoogleSearchGender = selectedGender;
            mCharacterSettings = CharacterSettingsImpl.create(mSelectedYear, mGoogleSearchGender);
            searchOptions.setQuery(mCharacterSettings.getQuery());
            publishNewOptions(searchOptions);
        }
        return false;
    }

    private void publishNewOptions(GoogleImageSearch.Options searchOptions) {
        if (mSearchOptionsChanged != null) {
            mSearchOptionsChanged.onGoogleSearchOptionsChanged(searchOptions);
        }
        if (mBroadcastSearchSettings != null) {
            mBroadcastSearchSettings.onSettingsChanged(mCharacterSettings, true);
        }
        setTitle();
    }

    private void setTitle() {
        if (titleView != null && mCharacterSettings != null) {
            titleView.setText(mCharacterSettings.toString());
        }
    }

    @Override
    public void onTitledSeekBarChanged(TitledSeekBar seekBar) {
        mSelectedYear = seekBar.getIntValue();
        mCharacterSettings = CharacterSettingsImpl.create(mSelectedYear, mGoogleSearchGender);
        searchOptions.setQuery(mCharacterSettings.getQuery());
        publishNewOptions(searchOptions);
    }

    @Override
    public void onYearsPeriodSelected(YearsPeriod period) {
        if (yearSeekbar != null) {
            yearSeekbar.setMinValue(period.getMinYear());
            yearSeekbar.setJumpValue(period.getYearJump());
            yearSeekbar.setMaxValue(period.getMaxYear());
            yearSeekbar.setProgress(period.getDefaultYearJumpPosition());
        }
    }

    public interface GoogleSearchOptsListener {
        boolean onGoogleSearchOptionsChanged(GoogleImageSearch.Options newOptions);
    }

}


text:
namespace OakIdeas.Schema.Core.Events.UserInteractions
{
    /// <summary>
    /// User interaction: Like an item.
    /// </summary>
    /// <see cref="http://www.schema.org/UserLikes"/>
    public class UserLikes : UserInteraction
    {
    }
}


text:
function application_body_onload() {
  // body onload code
}

function application_body_onunload() {
  // body onunload code
}

// coding here

function merge() {
  var text_template = StringUtil.trim($value("text_template"));
  var text_vars = StringUtil.trim($value("text_vars"));

  if (StringUtil.isEmpty(text_template)) {
    alarmMsg("text_template");
    return;
  }
  if (!StringUtil.contains(text_template, "$VAR$")) {
    alarmMsg("text_template");
    return;
  }
  if (StringUtil.isEmpty(text_vars)) {
    alarmMsg("text_vars");
    return;
  }
  var vars = text_vars.split(/(?:\r\n)|(?:\r)|(?:\n)/g);
  var noneEmptyVars = [];
  for (var i = 0; i < vars.length; i++) {
    var l = StringUtil.trim(vars[i]);
    if (StringUtil.isNotEmpty(l)) {
      noneEmptyVars.push(l);
    }
  }
  if (noneEmptyVars.length == 0) {
    alarmMsg("text_vars");
    return;
  }

  var results = [];
  for (var i = 0; i < noneEmptyVars.length; i++) {
    results.push(text_template.replace(/\$VAR\$/g, noneEmptyVars[i]));
  }

  $value("text_output", results.join("\n"));
}

function alarmMsg(id) {
  var alarm = new Alarm(Alarm.ALARM_TYPE_MESSAGE | Alarm.ALARM_TYPE_BLINKCOLOR);
  alarm.setShowTime(3);
  alarm.setCancelLastMessage(true);
  alarm.setMessageAdapter(function(msg) {
  });
  alarm.setBlinkAdapter(function(msg) {
    if (msg == Alarm.ALARM_BLINK_ON) {
      $(id).style.background = "yellow";
    } else if (msg == Alarm.ALARM_BLINK_OFF) {
      $(id).style.background = "#ffffff";
    }
  });

  alarm.show("Imput not illegal!");
}


text:
package com.codestd.springstudy.log;

public class User {

	private String username;
	private String password;

	public User() {
		super();
	}

	public User(String username, String password) {
		super();
		this.username = username;
		this.password = password;
	}

	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}

}


text:
import pytest
from flask import json
from uuid import uuid4

from backend.util.response.order.order import OrderSchema
from backend.util.response.error import ErrorSchema
from backend.util.slug import uuid_to_slug
from webservices.willorders.backend.tests.factories import OrderFactory, ProductFactory, OrderProductFactory

@pytest.fixture(scope="function", autouse=True)
def factory_session(willorders_ws_db_session):
    OrderFactory._meta.sqlalchemy_session = willorders_ws_db_session
    ProductFactory._meta.sqlalchemy_session = willorders_ws_db_session
    OrderProductFactory._meta.sqlalchemy_session = willorders_ws_db_session

def test_select_by_slug_controller(flask_app, auth_user, es_create, willorders_ws_db_session):
    prod_list = es_create("products", 5)
    user_slug = auth_user.uuid_slug
    obj = OrderFactory.create(user_slug=user_slug)
    willorders_ws_db_session.commit()

    slug = obj.uuid_slug
    prod_id_list = [p.meta["id"] for p in prod_list]

    amount = 1
    for es_id in prod_id_list:
        product = ProductFactory.create(es_id=es_id)
        OrderProductFactory.create(order=obj, product=product, amount=amount)
        amount += 1

    willorders_ws_db_session.commit()

    with flask_app.test_client(user=auth_user) as client:
        response = client.get(
            "api/order/%s" % slug
        )

    data = json.loads(response.data)
    OrderSchema().load(data)
    assert response.status_code == 200
    assert data["slug"] == slug
    assert data["product_types"] == len(prod_list)
    assert data["items_amount"] == ((1 + len(prod_list)) * len(prod_list)) / 2
    assert len(data["products"]) == len(prod_list)

    for item in [item.to_dict() for item in obj.items]:
        product = next(p for p in data["products"] if p["id"] == item["item_id"])
        assert product["amount"] == item["amount"]

    with flask_app.test_client(user=auth_user) as client:
        response = client.get(
            "api/order/WILLrogerPEREIRAslugBR"
        )

    data = json.loads(response.data)
    assert data["error"] == {}
    assert response.status_code == 404

def test_select_by_slug_controller_wrong_user(flask_app, auth_user, es_create, willorders_ws_db_session):
    prod_list = es_create("products", 3)
    user_slug = uuid_to_slug(uuid4())
    obj = OrderFactory.create(user_slug=user_slug)
    willorders_ws_db_session.commit()

    slug = obj.uuid_slug
    prod_id_list = [p.meta["id"] for p in prod_list]

    amount = 1
    for es_id in prod_id_list:
        product = ProductFactory.create(es_id=es_id)
        OrderProductFactory.create(order=obj, product=product, amount=amount)
        amount += 1

    willorders_ws_db_session.commit()

    with flask_app.test_client(user=auth_user) as client:
        response = client.get(
            "api/order/%s" % slug
        )

    data = json.loads(response.data)
    assert data["error"] == {}
    assert response.status_code == 404

def test_select_by_slug_controller_unauthorized(flask_app):
    with flask_app.test_client() as client:
        response = client.get(
            "api/order/WILLrogerPEREIRAslugBR",
        )

    data = json.loads(response.data)
    ErrorSchema().load(data)
    assert response.status_code == 401


text:
package ganglia.gmetric;

/**
 * Implements the Ganglia gmetric command in java
 */
public class GMetric {
	public enum UDPAddressingMode {
		MULTICAST,
		UNICAST
	};

    private Protocol protocol ;

    /**
     * Constructs a GMetric
     * @param group the host/group to send the event to
     * @param port the port to send the event to
     * @param mode the mode
     */
    public GMetric( String group, int port, UDPAddressingMode mode) {
    	this( group, port, mode, false );
    }
    /**
     * Constructs a GMetric
     * @param group the host/group to send the event to
     * @param port the port to send the event to
     */
    public GMetric( String group, int port, UDPAddressingMode mode, boolean ganglia311) {
    	if ( ! ganglia311 )
    		this.protocol = new Protocolv30x( group, port, mode );
    	else
    		this.protocol = new Protocolv31x( group, port, mode, 5 );
    }
    /**
     * The Ganglia Metric Client (gmetric) announces a metric
     * @param name Name of the metric
     * @param value Value of the metric
     * @param type Type of the metric.  Either string|int8|uint8|int16|uint16|int32|uint32|float|double
     * @param units Unit of measure for the value
     * @param slope Either zero|positive|negative|both
     * @param tmax  The maximum time in seconds between gmetric calls
     * @param dmax The lifetime in seconds of this metric
     * @param group Group Name of the metric
     * @throws java.lang.Exception
     */
    public void announce( String name,
            String value,
            GMetricType type,
            String units,
            GMetricSlope slope,
            int tmax,
            int dmax,
            String group ) throws GangliaException {
        try {
        	protocol.announce( name, value, type,
        			units, slope, tmax, dmax, group);
        } catch ( Exception ex ) {
            throw new GangliaException( "Exception announcing metric", ex ) ;
        }
    }
    /**
     * Announces a metric
     * @param name Name of the metric
     * @param value Value of the metric
     * @param group Group Name of the metric
     * @throws ganglia.GangliaException
     */
    public void announce( String name,
            int value, String group ) throws GangliaException {
        this.announce(name, Integer.toString(value),GMetricType.INT32, "", GMetricSlope.BOTH, 60, 0, group);
    }
    /**
     * Announces a metric
     * @param name Name of the metric
     * @param value Value of the metric
     * @param group Group Name of the metric
     * @throws ganglia.GangliaException
     */
    public void announce( String name,
            long value, String group  ) throws GangliaException {
        this.announce(name, Long.toString(value),GMetricType.DOUBLE, "", GMetricSlope.BOTH, 60, 0, group );
    }
    /**
     * Announces a metric
     * @param name Name of the metric
     * @param value Value of the metric
     * @param group Group Name of the metric
     * @throws ganglia.GangliaException
     */
    public void announce( String name,
            float value, String group ) throws GangliaException {
        this.announce(name, Float.toString(value),GMetricType.FLOAT, "", GMetricSlope.BOTH, 60, 0, group);
    }
    /**
     * Announces a metric
     * @param name Name of the metric
     * @param value Value of the metric
     * @param group Group Name of the metric
     * @throws ganglia.GangliaException
     */
    public void announce( String name,
            double value, String group ) throws GangliaException {
        this.announce(name, Double.toString(value),GMetricType.DOUBLE, "", GMetricSlope.BOTH, 60, 0, group);
    }
    /**
     * Main method that sends a test metric
     * @param args
     */
    public static void main( String[] args ) {
        try {
            GMetric gm = new GMetric("127.0.0.1", 8649, UDPAddressingMode.MULTICAST) ;
            gm.announce("BOILINGPOINT", "100", GMetricType.STRING,
                    "CELSIUS", GMetricSlope.BOTH, 0,0, "TESTGROUP");
            gm.announce("INTTEST", (int)Integer.MAX_VALUE, "TESTGROUP" ) ;
            gm.announce("LONGTEST", (long)Long.MAX_VALUE, "TESTGROUP" );
            gm.announce("FLOATTEST", (float)Float.MAX_VALUE, "TESTGROUP" ) ;
            gm.announce("DOUBLETEST", (double)Double.MAX_VALUE, "TESTGROUP" ) ;
        } catch ( Exception ex ) {
            ex.printStackTrace() ;
        }
    }
}


text:
require_relative "../rails_helper.rb"

describe "Course Features", type: :feature do
  describe "Course#index", type: :feature do

    before :each do
      Course.create(
        name: "Augusta National GC",
        description: "Home of the Masters",
        location: "Augusta, GA"
      )
    end

    let(:course) {
      Course.first
    }

    it "displays with name and location" do
      visit courses_path
      expect(page).to have_content(course.name)
      expect(page).to have_content(course.location)
    end

    it "has links to course show pages" do
      visit courses_path
      click_link "Augusta National GC"
      expect(current_path).to eq(course_path(course))
    end

    it "has a link to Course#new" do
      visit_signin
      user_login
      visit courses_path
      click_link "Add New Course"
      expect(current_path).to eq(new_course_path)
    end

  end

  describe "Course#show", type: :feature do

    before :each do
      User.create(
        username: "tylerB",
        email: "tyler@gmail.com",
        password: "123456",
        password_confirmation: "123456"
      )
    end

    before :each do
      Course.create(
        name: "Augusta National GC",
        description: "Home of the Masters",
        location: "Augusta, GA"
      )
    end

    let(:user) {
      User.first
    }

    let(:course) {
      Course.first
    }

    # context "as admin" do
    #   it "has a link to Course#edit" do
    #     visit_signin
    #     admin_login
    #     visit course_path(course)
    #     expect(page).to have_content("Edit Course")
    #     click_link "Edit Course"
    #     expect(current_path).to eq(edit_course_path(course))
    #   end
    # end

    context "when logged in" do
      it "links to Course/TeeTime#new" do
        visit_signin
        user_login
        visit course_path(course)
        click_link("Create New Tee Time")
        expect(current_path).to eq(new_course_tee_time_path(course))
      end

      it "does not link to Course#edit if not an admin" do
        visit_signin
        user_login
        visit course_path(course)
        expect(page).to_not have_content("Edit Course")
      end
    end

    context "when logged out" do
      it "doesn't link to User/TeeTime#new" do
        visit course_path(course)
        expect(page).to_not have_content("Create New Tee Time")
      end
    end

    it "displays a course name" do
      visit course_path(course)
      expect(page).to have_content("Augusta National GC")
    end

    it "displays a course description" do
      visit course_path(course)
      expect(page).to have_content("Home of the Masters")
    end

    it "displays a course location" do
      visit course_path(course)
      expect(page).to have_content("Augusta, GA")
    end

    it "displays tee times scheduled for the course" do
      tee_time = course.tee_times.build(time: "Dec 1 2099")
      tee_time.add_user(user)
      visit course_path(course)
      expect(page).to have_content("Dec 1, 2099")
    end

    it "displays associated tee times as links to nested tee time show page" do
      tee_time = course.tee_times.build(time: "Dec 1 2099")
      tee_time.add_user(user)
      visit course_path(course)
      click_link(tee_time.time.year)
      expect(current_path).to eq(course_tee_time_path(course, tee_time))
    end

    it "defaults to displaying associated tee times in chronological order" do
      tee_time1 = course.tee_times.build(time: "Dec 1 2099")
      tee_time2 = course.tee_times.build(time: "Dec 1 2097")
      tee_time3 = course.tee_times.build(time: "Dec 1 2098")
      tee_time1.user_tee_times.build(user_id: user.id)
      tee_time2.user_tee_times.build(user_id: user.id)
      tee_time3.user_tee_times.build(user_id: user.id)
      course.save
      visit course_path(course)
      expect(page.body.index(tee_time2.time.year.to_s)).to be < page.body.index(tee_time1.time.year.to_s)
    end

    it "does not display tee times that have already taken place" do
      tee_time1 = course.tee_times.build(time: "Dec 1 2000")
      tee_time1.add_user(user)
      visit course_path(course)
      expect(page).to_not have_content("2000")
    end

  end

  describe "Course#edit", type: :feature do
    before :each do
      Course.create(
        name: "Augusta National GC",
        description: "Home of the Masters",
        location: "Augusta, GA"
      )
    end

    let(:course) {
      Course.first
    }

    context "as admin" do
      it "allows for the course to be updated" do
        visit_signin
        admin_login
        visit edit_course_path(course)
        fill_in("course[description]", with: "Madagascar")
        click_button "Update Course"
        expect(current_path).to eq(course_path(course))
        expect(page).to have_content("Madagascar")
      end

      it "has a link to destroy the course" do
        visit_signin
        admin_login
        visit edit_course_path(course)
        expect(page).to have_content("Delete Course")
      end
    end

    context "when not admin" do
      it "redirects to welcome page" do
        visit_signin
        user_login
        visit edit_course_path(course)
        expect(current_path).to eq(user_path(current_user))
      end
    end

  end

  # describe "Course#destroy", type: :feature do
  #
  #   before :each do
  #     User.create(
  #       username: "tylerB",
  #       email: "tyler@gmail.com",
  #       password: "123456",
  #       password_confirmation: "123456"
  #     )
  #   end
  #
  #   before :each do
  #     Course.create(
  #       name: "Augusta National GC",
  #       description: "Home of the Masters",
  #       location: "Augusta, GA"
  #     )
  #   end
  #
  #   let(:user) {
  #     User.first
  #   }
  #
  #   let(:course) {
  #     Course.first
  #   }
  #
  #   it "destroys course" do
  #     course_id = course.id
  #     visit_signin
  #     admin_login
  #     visit edit_course_path(course)
  #     click_button "Delete Course"
  #     expect(current_path).to eq(courses_path)
  #     expect(Course.find_by_id(course_id)).to be_nil
  #   end
  #
  #   it "destroys all course tee times" do
  #     tee_time = course.tee_times.build(time: "Dec 1 2098")
  #     tee_time_id = tee_time.id
  #     visit_signin
  #     admin_login
  #     visit edit_course_path(course)
  #     click_link "Delete Course"
  #     expect(current_path).to eq(courses_path)
  #     expect(TeeTime.find_by_id(tee_time_id)).to be_nil
  #   end
  #
  #   it "destroys all user tee times associated with course" do
  #     tee_time = course.tee_times.build(time: "Dec 1 2098")
  #     tee_time.add_user(user)
  #     user_tee_time_id = tee_time.user_tee_times.first.id
  #     visit_signin
  #     admin_login
  #     visit edit_course_path(course)
  #     click_link "Delete Course"
  #     expect(current_path).to eq(courses_path)
  #     expect(UserTeeTime.find_by_id(user_tee_time_id)).to be_nil
  #   end
  # end
end


text:
#region Nequeo Pty Ltd License
/*
    Permission is hereby granted, free of charge, to any person
    obtaining a copy of this software and associated documentation
    files (the "Software"), to deal in the Software without
    restriction, including without limitation the rights to use,
    copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the
    Software is furnished to do so, subject to the following
    conditions:

    The above copyright notice and this permission notice shall be
    included in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
    OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
    HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
    WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
    OTHER DEALINGS IN THE SOFTWARE.
*/
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Markup;
using System.Collections;
using System.Diagnostics;
using Nequeo.Wpf.Controls.Ribbon.Interfaces;

namespace Nequeo.Wpf.Controls
{
    public class RibbonWrapPanel : Panel
    {
        static RibbonWrapPanel()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(RibbonWrapPanel), new FrameworkPropertyMetadata(typeof(RibbonWrapPanel)));
        }

        const double smallHeight = 24;

        protected override Size MeasureOverride(Size availableSize)
        {
            foreach (UIElement e in Children) e.Measure(infiniteSize);
            return ArrangeOrMeasure(false);
        }

        private static Size infiniteSize = new Size(double.PositiveInfinity, double.PositiveInfinity);

        protected override Size ArrangeOverride(Size finalSize)
        {
            return ArrangeOrMeasure(true);
        }

        private Size ArrangeOrMeasure(bool arrange)
        {
            double left = 0;
            int rowIndex = 0;
            int maxRows = 3;

            List<UIElement> rowElements = new List<UIElement>(maxRows);

            foreach (UIElement e in Children)
            {
                if (e.Visibility != Visibility.Visible) continue;
                IRibbonControl ribbonControl = e as IRibbonControl;
                Size dsize = e.DesiredSize;
                if (dsize.Height > smallHeight)
                {
                    if (rowIndex > 0)
                    {
                        left += ArrangeRow(rowElements, left, arrange);
                        rowIndex = 0;
                    }
                    if (arrange)
                    {
                        Size size = e.DesiredSize;
                        double h = Math.Max(smallHeight, size.Height);
                        e.Arrange(new Rect(left, 0, size.Width, h));
                    }
                    left += e.DesiredSize.Width;
                }
                else
                {
                    RibbonSize size = RibbonBar.GetSize(e);
                    if (size != RibbonSize.Minimized)
                    {
                        rowElements.Add(e);
                        if (++rowIndex == maxRows)
                        {
                            left += ArrangeRow(rowElements, left, arrange);
                            rowIndex = 0;
                        }
                    }
                }
            }
            left += ArrangeRow(rowElements, left, arrange);

            left = Math.Max(32, left);
            return new Size(left, smallHeight * 3);
        }

        protected double ArrangeRow(List<UIElement> rowElements, double left, bool arrange)
        {
            double max = 0;

            double rowHeight = smallHeight + (rowElements.Count == 2 ? (smallHeight / 3) : 0);
            double topOffset = rowElements.Count == 2 ? smallHeight / 3 : 0;

            foreach (UIElement e in rowElements)
            {
                max = Math.Max(e.DesiredSize.Width, max);
            }
            foreach (UIElement e in rowElements)
            {
                if (arrange)
                {
                    double h = Math.Max(smallHeight, e.DesiredSize.Height);
                    double w = e is IRibbonStretch ? max : e.DesiredSize.Width;

                    FrameworkElement fe = e as FrameworkElement;
                    if (fe != null && fe.HorizontalAlignment != HorizontalAlignment.Left)
                    {
                        switch (fe.HorizontalAlignment)
                        {
                            case HorizontalAlignment.Right:
                                e.Arrange(new Rect(max - w + left, topOffset, w, h));
                                break;

                            case HorizontalAlignment.Center:
                                e.Arrange(new Rect((max - w) / 2 + left, topOffset, w, h));
                                break;

                            case HorizontalAlignment.Left:
                            case HorizontalAlignment.Stretch:
                                e.Arrange(new Rect(left, topOffset, w, h));
                                break;
                        }
                    }
                    else e.Arrange(new Rect(left, topOffset, w, h));
                }
                topOffset += rowHeight;
            }
            rowElements.Clear();
            return max;
        }

    }
}


text:
#import <IDELogNavigator/XCLogSectionAdapter.h>

@interface XCLogTargetHeadingAdapter : XCLogSectionAdapter
{
}

- (BOOL)dataNode:(id)arg1 doubleClickInColumn:(id)arg2;
- (id)targetHeadingBadgeForDataNode:(id)arg1;
- (id)secondRowStringForDataNode:(id)arg1;
- (id)titleFontForDataNode:(id)arg1;
- (id)titleForDataNode:(id)arg1;
- (id)imageForDataNode:(id)arg1;
- (id)_fallbackTargetDomainType;
- (double)_baseHeightOfRowForDataNode:(id)arg1;
- (BOOL)supportsTextExpansionAtSectionLevelForDataNode:(id)arg1;
- (BOOL)supportsTextExpansionForDataNode:(id)arg1;
- (BOOL)isTargetHeadingAdapter;

@end


text:
"""
Available and enabled assets bundles for this project

This use 'nested bundles' technic in the 'main available bundles' to regroup
app bundles into single files.
"""
from django_assets import Bundle, register

"""
BASE BUNDLES, contains common app/components bundles, do not register your
main bundles here. However you can comment/uncomment some app files for your
needs.
"""
AVALAIBLE_BUNDLES = {
    # App bundle for Modernizr, compatible for all Foundation releases
    'app_modernizr_js': Bundle(
        "js/foundation5/vendor/modernizr.js",
        filters='yui_js',
        output='js/modernizr.%(version)s.js'
    ),

    # App bundle for Foundation5
    'app_foundation5_js': Bundle(
        "js/foundation5/vendor/jquery.js",
        #"js/foundation5/vendor/fastclick.js", # for Foundation development
        #"js/foundation5/vendor/lodash.js", # for Foundation development
        #"js/foundation5/vendor/jquery.placeholder.js", # for Foundation development
        "js/foundation5/vendor/jquery.cookie.js",
        "js/foundation5/foundation/foundation.js",
        "js/foundation5/foundation/foundation.abide.js",
        "js/foundation5/foundation/foundation.accordion.js",
        "js/foundation5/foundation/foundation.alert.js",
        "js/foundation5/foundation/foundation.clearing.js",
        "js/foundation5/foundation/foundation.dropdown.js",
        #"js/foundation5/foundation/foundation.equalizer.js",
        "js/foundation5/foundation/foundation.interchange.js",
        "js/foundation5/foundation/foundation.joyride.js",
        "js/foundation5/foundation/foundation.magellan.js",
        "js/foundation5/foundation/foundation.offcanvas.js",
        "js/foundation5/foundation/foundation.reveal.js",
        "js/foundation5/foundation/foundation.slider.js",
        "js/foundation5/foundation/foundation.tab.js",
        "js/foundation5/foundation/foundation.tooltip.js",
        "js/foundation5/foundation/foundation.topbar.js",
        # For Orbit Slider (default used)
        "js/foundation5/foundation/foundation.orbit.js",
        filters='yui_js',
        output='js/app_foundation5.%(version)s.js'
    ),

    # App bundle for RoyalSlider instead of Orbit (remember to enable its foundation
    # component in your js app')
    'app_royalslider_js': Bundle(
        "js/royalslider/dev/jquery.royalslider.js",
        "js/royalslider/dev/modules/jquery.rs.video.js",
        "js/royalslider/dev/modules/jquery.rs.thumbnails.js",
        "js/royalslider/dev/modules/jquery.rs.auto-height.js",
        "js/royalslider/dev/modules/jquery.rs.deeplinking.js",
        "js/royalslider/dev/modules/jquery.rs.fullscreen.js",
        "js/royalslider/dev/modules/jquery.rs.animated-blocks.js",
        "js/royalslider/dev/modules/jquery.rs.autoplay.js",
        "js/royalslider/dev/modules/jquery.rs.global-caption.js",
        "js/royalslider/dev/modules/jquery.rs.visible-nearby.js",
        "js/royalslider/dev/modules/jquery.rs.tabs.js",
        "js/royalslider/dev/modules/jquery.rs.nav-auto-hide.js",
        "js/royalslider/dev/modules/jquery.rs.autoplay.js",
        "js/royalslider/dev/modules/jquery.rs.bullets.js",
        "js/royalslider/dev/modules/jquery.rs.active-class.js",
        filters='yui_js',
        output='js/app_royalslider.%(version)s.js'
    ),

    # App bundle for SocialAggregator
    'app_socialaggregator_js': Bundle(
        "js/masonry/masonry.pkgd.js",
        "js/socialaggregator.js",
        filters='yui_js',
        output='js/app_socialaggregator.%(version)s.js'
    ),

    # App bundle for Pikaday jquery plugin (a datepicker)
    'app_pikaday_js': Bundle(
        "js/pikaday.js",
        "js/jquery/pikaday.jquery.js",
        filters='yui_js',
        output='js/app_pikaday.%(version)s.js'
    ),
}

"""
MAIN AVAILABLE BUNDLES, this is where you will register main bundles
"""
AVALAIBLE_BUNDLES.update({
    # CSS bundle For Foundation5
    'main_css': Bundle(
        'css/flags.css',
        'css/app.css',
        filters='yui_css',
        output='css/app.%(version)s.css'
    ),

    # Javascript bundle For Foundation5
    'main_js': Bundle(
        AVALAIBLE_BUNDLES['app_foundation5_js'],
        "js/jquery/equalize.js",
        #AVALAIBLE_BUNDLES['app_royalslider_js'],
        #"js/moment.js",
        "js/jquery/magnific-popup.js", # Magnific popup (modal window/pop-in)
        AVALAIBLE_BUNDLES['app_socialaggregator_js'],
        #AVALAIBLE_BUNDLES['app_pikaday_js'],
        "js/jquery/addons.js",
        "js/app.js",
        filters='yui_js',
        output='js/app.%(version)s.js'
    ),
})

"""
ENABLE NEEDED BUNDLE HERE, only these bundles will be used
"""
ENABLED_BUNDLES = [
    'app_modernizr_js',
    'main_css',
    'main_js',
]

# Registering your enabled bundles, don't matter about this
for item in ENABLED_BUNDLES:
    register(item, AVALAIBLE_BUNDLES[item])


text:
package model

import model.EvaluationResults._
import org.scalatest.prop.TableDrivenPropertyChecks
import org.scalatest.prop.TableDrivenPropertyChecks.forAll
import testkit.UnitSpec

class EvaluationResultsSpec extends UnitSpec with TableDrivenPropertyChecks {

  "Evaluation results" must {

    "be returned for a string value" in {
      EvaluationResults.Result.apply("Green") mustBe Green
      EvaluationResults.Result.apply("Amber") mustBe Amber
      EvaluationResults.Result.apply("Red") mustBe Red
      EvaluationResults.Result.apply("Withdrawn") mustBe Withdrawn
    }

    "add withdrawn" in {
      val table = Table(
        ("addend", "sum"),
        (Red, Withdrawn),
        (Amber, Withdrawn),
        (Green, Withdrawn),
        (Withdrawn, Withdrawn)
      )

      forAll (table) { (addend: Result, sum: Result) =>
        Withdrawn + addend mustBe sum
      }
    }

    "add red" in {
      val table = Table(
        ("addend", "sum"),
        (Red, Red),
        (Amber, Red),
        (Green, Red),
        (Withdrawn, Withdrawn)
      )

      forAll (table) { (addend: Result, sum: Result) =>
        Red + addend mustBe sum
      }
    }

    "add amber" in {
      val table = Table(
        ("addend", "sum"),
        (Red, Red),
        (Amber, Amber),
        (Green, Green),
        (Withdrawn, Withdrawn)
      )

      forAll (table) { (addend: Result, sum: Result) =>
        Amber + addend mustBe sum
      }
    }

    "add Green" in {
      val table = Table(
        ("addend", "sum"),
        (Red, Red),
        (Amber, Amber),
        (Green, Green),
        (Withdrawn, Withdrawn)
      )

      forAll (table) { (addend: Result, sum: Result) =>
        Green + addend mustBe sum
      }
    }
  }

  "EvaluationResults.Result.fromPassFail" must {
    "return Green for Pass" in {
     EvaluationResults.Result.fromPassFail("Pass") mustBe Green
    }

    "return Red for Fail" in {
      EvaluationResults.Result.fromPassFail("Fail") mustBe Red
    }
  }

}


text:
// Code generated by protoc-gen-go.
// source: common/lines.proto
// DO NOT EDIT!

/*
Package common is a generated protocol buffer package.

It is generated from these files:
	common/lines.proto

It has these top-level messages:
	LogLines
*/
package common

import proto "github.com/golang/protobuf/proto"
import math "math"

// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = math.Inf

type LogLines struct {
	FileName         *string  `protobuf:"bytes,1,req" json:"FileName,omitempty"`
	Offset           *int64   `protobuf:"varint,2,req" json:"Offset,omitempty"`
	Inode            *uint64  `protobuf:"varint,3,req" json:"Inode,omitempty"`
	Lines            []string `protobuf:"bytes,4,rep" json:"Lines,omitempty"`
	XXX_unrecognized []byte   `json:"-"`
}

func (m *LogLines) Reset()         { *m = LogLines{} }
func (m *LogLines) String() string { return proto.CompactTextString(m) }
func (*LogLines) ProtoMessage()    {}

func (m *LogLines) GetFileName() string {
	if m != nil && m.FileName != nil {
		return *m.FileName
	}
	return ""
}

func (m *LogLines) GetOffset() int64 {
	if m != nil && m.Offset != nil {
		return *m.Offset
	}
	return 0
}

func (m *LogLines) GetInode() uint64 {
	if m != nil && m.Inode != nil {
		return *m.Inode
	}
	return 0
}

func (m *LogLines) GetLines() []string {
	if m != nil {
		return m.Lines
	}
	return nil
}

func init() {
}


text:
require 'simplecov'
require 'coveralls'

SimpleCov.formatters = [SimpleCov::Formatter::HTMLFormatter, Coveralls::SimpleCov::Formatter]

SimpleCov.start do
  add_filter '/bundle/'
  add_filter '/test/'
  minimum_coverage(87)
end

gem 'minitest' if defined? Bundler
require 'minitest/autorun'

require File.expand_path('../../lib/faraday', __FILE__)

require 'stringio'
require 'uri'

module Faraday
  module LiveServerConfig
    def live_server=(value)
      @@live_server = case value
      when /^http/
        URI(value)
      when /./
        URI('http://127.0.0.1:4567')
      end
    end

    def live_server?
      defined? @@live_server
    end

    # Returns an object that responds to `host` and `port`.
    def live_server
      live_server? and @@live_server
    end
  end

  class TestCase < MiniTest::Test
    extend LiveServerConfig
    self.live_server = ENV['LIVE']

    def test_default
      assert true
    end unless defined? ::MiniTest

    def capture_warnings
      old, $stderr = $stderr, StringIO.new
      begin
        yield
        $stderr.string
      ensure
        $stderr = old
      end
    end

    def self.jruby?
      defined? RUBY_ENGINE and 'jruby' == RUBY_ENGINE
    end

    def self.rbx?
      defined? RUBY_ENGINE and 'rbx' == RUBY_ENGINE
    end

    def self.ruby_22_plus?
      RUBY_VERSION > '2.2'
    end

    def self.ssl_mode?
      ENV['SSL'] == 'yes'
    end
  end
end


text:
<!DOCTYPE html>

        <meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="referrer" content="no-referrer">
<meta name="description" content="From the whiteboard to the keyboard">
<title>
Create a Custom Object With . N E T Using the Force.com Metadata a P I ... and No Proxy Classes! - Wade Wegner
</title>

        <meta property="og:title" content="Create a Custom Object with .NET using the Force.com Metadata API … and No Proxy Classes! - Wade Wegner" />
<meta property="og:type" content="website" />
<meta property="og:description" content="Ever want to create a custom object or field in Salesforce using the APIs? Tired of having to generate massive WSDLs to perform simple operations? In this post we'll look at how we can create custom objects and fields by managing the SOAP requests ourselves."/>
<meta property="og:url" content="https://www.wadewegner.com/2014/03/create-a-custom-object-with-.net-using-the-force.com-metadata-api-...-and-no-proxy-classes/"/>
<meta property="og:site_name" content="Wade Wegner"/>

<meta property="og:image" content="https://www.wadewegner.com/home/favicon.ico"/>

<link rel="shortcut icon" href="/home/favicon.ico">

<link rel="stylesheet" href="/css/main.min.7234953717df3eaff5f4783a8c545c65897f4ac5d802aa4deabcf2538ec29449.css" integrity="sha256-cjSVNxffPq/19Hg6jFRcZYl/SsXYAqpN6rzyU47ClEk=" crossorigin="anonymous" media="screen">

    <link rel="stylesheet" href="/css/screen.css" integrity="" crossorigin="anonymous" media="screen">

Blog

                Home

                All Posts

                About

        Create a Custom Object with .NET using the Force.com Metadata API … and No Proxy Classes!

        Mar 1, 2014 |
        9 minutes read

         Tags:

Update 2/24/14

Over the weekend I took much of what I wrote below and packaged it up in a NuGet package. You can use the NuGet to accomplish everything I wrote below with fewer lines of code. Full details are available on the WadeWegner.Salesforce.SOAPHelpers Github repository and you can get the NuGet package with the following command:

    Install-Package WadeWegner.Salesforce.SOAPHelpers

Enjoy!

Recently I’ve written a lot about using the Force.com REST API with .NET. I’ve also created a Force.com Toolkit for .NET, a Chatter Toolkit for .NET, and a set of sample applications that make it easier for developers to interact with these APIs. Using the REST API you can write custom integrations with your applications in Salesforce, interacting with all of your metadata through simple HTTP calls using JSON.

There are, however, a few limits to what the REST API can accomplish. In particular, one of the requests and/or questions I see over and over is how to create custom objects and fields using the APIs. If you look at the Developer Forum you'll see lots of people (especially .NET developers) ask these questions.

The answer is relatively simple: use the Metadata API.

Of course, the reality is that there's more to it. In particular, if you've only used the REST APIs (or it's been years since you've had to use SOAP as was the case with yours truly), this may present a challenge as the Metadata API is SOAP-based.

But not to fear! The utility of these APIs is worth the few extra minutes and lines of code.

When starting with these SOAP APIs, most developers will typically download the WSDL files, generate class proxies, and code against them. This is a fine approach and there's a healthy amount of examples that show how this works.

That said, generating full class proxies against the WSDLs can be a bit heavy-handed when we want to simply do a few basic operations, like create a custom object with some fields. Furthermore, if you're like me, you may desire more insight into what's happening in the code and the HTTP requests, and don't want to rely on all the code that's automatically generated for me. Personally, I have no problem writing a little more code if it means I have more control and insight.

In this post, I plan to discuss the following through narrative, raw HTTP requests/responses examples, and (of course) code:

Demystify the Enterprise and Partner APIs.

Explain and demonstrate the SOAP login process.

Explain and demonstrate how to use the Metadata API to create a custom object and field.

All this without generating proxy classes using the WSDLs.

Ready to get started? Let's first look at the Enterprise or Partner APIs.

SOAP API: Enterprise and Partner WSDLs

The SOAP API lets you create, retrieve, update, or delete records within Salesforce. There are over 20 different API calls that let you perform a number of important tasks and operations. In many ways, it's similar to the REST APIs (except it's SOAP … sorry for the obvious).

As part of the SOAP API, there are two different web services you can use, referred to as Enterprise and Partner. They are functionality equivalent and share the same operations yet differ in how developers interact with them. Each allows you to generate  WSDL file to simplify your interactions. Understanding the differences between these two web services and WSDLs is important.

The Enterprise WSDL is a strongly typed version of the API, meaning that an object in Force.com will have an equivalent object in Java, .NET, or whatever environment is accessing the API. The benefit of this model, where your code is compiled against a specific schema, is that coding is generally easier and more straightforward (as you don’t need to deal with any underlying XML structures) and safer in the sense that data and schema dependencies are resolved at compile time, not at runtime. The downside of that strongly typed model is that it only works on a single Force.com account’s schema, as it is bound to all of the unique objects and fields that exist in that account’s data model. This means that when the metadata in your organization changes you'll need to update your WSDL and regenerate your proxy classes.

What if you create a solution that you want to work across multiple accounts from different customers? In that case, you need a weakly typed representation of the data. This is is precisely what the Partner WSDL provides.

With the Partner WSDL, the developer is responsible for marshaling data in the correct object representation (which typically involves diving into the XML), but is freed from being dependent on any particular data model or Force.com account.

Put simply, if you are a company using the API exclusively on your own account, you’ll typically want the Enterprise WSDL. If you are an ISV using the API across many accounts, you’ll typically want the Partner WSDL.

Regardless of which path you use, you'll have to use the SOAP API to authenticate and use the Metadata API. If this is your only goal, it doesn't really matter if you use the Enterprise or Partner web service.

For a detailed account of the SOAP APIs please refer to the SOAP API developer documentation.

Authenticating with the SOAP API

To use the SOAP or Metadata APIs you need to login and start a client session. To do this, you must login and obtain a sessionId and and server URL. The sessionId is used in subsequent calls to the web services to identify your session and the server URL identifies the appropriate URI with which you make your subsequent requests.

Note: don't forget to append your security token to your password if logging in from a location unknown to Salesforce. You will be blocked!

There are two different URIs for logging in, depending on whather you're using the Enterprise or Partner web service.

Enterprise: https://login.salesforce.com/services/Soap/c/[version]/[organizationId]

Partner: https://login.salesforce.com/services/Soap/u/[version]/[organizationId]

Here's an example of what a raw login request looks like for the Enterprise web service:

The request is nearly identical for the Partner webservice:

I'm sharing the raw requests in this post as I think it is profoundly more useful than just showing how to create the request in a single language. The reality is you can use any language that supports HTTP communication and, even if you do just need the .NET code, you'll have a better understanding of the process if you know what the raw request looks like.

That said, how do we create these requests in code without using the proxy classes generated by the WSDLs? Let's see.

I wanted to write a single method that worked against both the Enterprise and Partner API. Required? Absolutely not. If you just want to use one you can easily refactor the following code.

When you make the request you'll get a response. Whether you use the Enterprise or Partner webservice you'll get loginResponse that pretty much looks like this:

The only difference between the Enterprise and Partner web service is that the Enterprise web service will give a response with the following namespace …

    xmlns=“urn:enterprise.soap.sforce.com”

… whereas the Partner web service will give a response with this namespace …

    xmlns=“urn:partner.soap.sforce.com”

Again, let me reiterate that the loginResponse information you receive is identical, so which one you use doesn't matter; there's no material difference when it comes to logging in.

There's a lot of information in these responses. For our purposes in this post, we really only need the sessionId and metadataServerUrl. As previously mentioned, the sessionId allows us to authenticate when making a call to the various SOAP APIs and the metadataServerUri is the URL we need to use when interacting with the metadata API during subsequent calls.

So, let's look at what's required in order to deserialize all this information into .NET objects and then grab the information.

First, we need to define these objects. This is a little tricky in .NET, as we need to attribute our classes with the XML namespace in order to appropriately deserialize. I took an approach of defining two classes that are nearly identical yet live in different namespaces.

If you choose an approach where you simply use either the Enterprise or Partner web service you can simply choose one or the other.

The code for serializing and returning the response is pretty straightforward.

At this point we now have all the information required in order to interact with the Metadata API and create our custom objects and fields.

Creating a Custom Object using the Metadata API

It sure has taken us a long time to get here. However, using the above, you now have the ability to easily authenticate to the SOAP APIs. Throw these methods into a library and save them - I'm sure you'll use them over and over.

What does the SOAP look like for creating a custom object?

For SOAP this is pretty standard. We have a SOAP envelope and, within the body, we're passing in the metadata used to create our custom object.

We'll get the following response from the Metadata API:

One thing to point out is that this SOAP request only created the custom object. We don't have any fields yet! We need to issue another request in order to create the fields.

Here's how we add an additional field (you'll see it's unsurprisingly similar):

The surrounding SOAP envelope when creating a custom field is identical to the SOAP envelope used for creating a custom object. What changes is the metadata in the body.

So, what's an efficient way to approach this in code? Here's the approach I've taken.

Let's first create a method that handles the surrounding SOAP envelope, makes the HTTP request, and then returns the raw result.

You can see that this approach lets us easily pass in the metadata required to either create an object or field, and will build our SOAP envelope appropriately.

From here, let's create a method for creating the custom object metadata, call our Create method above, and then deserialize the response into an appropriate .NET object.

We can do the same for a custom field.

Both methods above are extremely similar. With a little more refactoring we might easily simplify this some more, but I'll leave that to you. (You need something to work on, right?)

Now, given everything we've created above, how might we run this?

Pretty slick. As you can see, the only things you need to bring to this approach are your username, password, and organization id. The first two should be easy for you to get. How do you get your organization id? Easy. Click on Setup | Company Profile | Company Information, and in the right hand column towards the bottom you'll find your Organization ID.

Conclusion

So, how can we confirm that this work?

Log into your Salesforce organization. Under recent items you should see the custom object and fields you've created. Go ahead and click on the custom object and you can confirm that it has the custom field.

<INSERT SCREENSHOT>

There you have it! A reasonably simple approach to establishing a session with the Enterprise and/or Partner APIs and using the Metadata API … all without having to generate class proxies from the WSDL!

You can grab all the code on Github: https://github.com/wadewegner/CustomObjectsUsingSOAP

I hope you found this useful.

Please enable JavaScript to view the comments powered by Disqus.
comments powered by Disqus

            Introduction theme for Hugo. Made with  and  by open source contributors.