text:
package org.kabuki.actor;

import org.kabuki.queues.Queues;
import org.kabuki.queues.mpsc.MPSC_SlotType;
import org.kabuki.utils.concurrent.WaitType;

import java.util.HashSet;
import java.util.function.Consumer;
import java.util.stream.Collectors;

import static org.metaja.utils.ReflectionUtils.Modifier.PUBLIC;

public class ActorSystemMPSC_Static extends ActorSystemMPSC {

    private final HashSet<Class> classes;

    public ActorSystemMPSC_Static(WaitType waitType, int queueSize, String threadName, Consumer<Throwable> errorConsumer, Class ... classes) {
        super(threadName, errorConsumer);
        this.classes = new HashSet<>();
        for (Class i : classes) {
            if (!PUBLIC.isModified(i)) {
                throw new IllegalArgumentException(i.getCanonicalName() + " is not public!");
            }
            this.classes.add(i);
        }
        MPSC_SlotType slotType = this.classes.stream().collect(Collectors.reducing(MPSC_SlotType.ZERO, MPSC_SlotType::get, MPSC_SlotType::max));
        this.queue = Queues.mpsc(waitType, slotType, queueSize, errorConsumer);
    }

    @Override
    public synchronized <I> I asynchronize(Class<I> i, String commitMethodName, I object) {
        if (!i.isInterface() || !PUBLIC.isModified(i)) {
            throw new IllegalArgumentException(i.getCanonicalName() + " is not a public interface!");
        }

        if (!classes.contains(i)) {
            throw new IllegalArgumentException("Class '" + i.getCanonicalName() + "' is configured within actor system!");
        }
        return commitMethodName == null
            ? queue.asynchronize(i, object)
            : queue.asynchronize(i, commitMethodName, object)
        ;
    }

    // ----- some sugar ----

    public ActorSystemMPSC_Static(WaitType waitType, Class ... classes) {
        this(waitType, DEFAULT_QUEUE_SIZE, ActorSystemMPSC_Static.class.getName(), System.err::println, classes);
    }

    public ActorSystemMPSC_Static(Class ... classes) {
        this(WaitType.LOCK, classes);
    }

    public static <I> I startAsDaemon(WaitType waitType, int queueSize, String threadName, Consumer<Throwable> errorConsumer, Class<I> i, String commitMethodName, I object) {
        ActorSystemMPSC_Static as = new ActorSystemMPSC_Static(waitType, queueSize, threadName, errorConsumer, i);
        as.startAsDaemon();
        return as.asynchronize(i, commitMethodName, object);
    }

    public static <I> I startAsDaemon(WaitType waitType, Class<I> i, String commitMethodName, I object) {
        return startAsDaemon(waitType, DEFAULT_QUEUE_SIZE, ActorSystemMPSC_Static.class.getName(), System.err::println, i, commitMethodName, object);
    }

    public static <I> I startAsDaemon(WaitType waitType, Class<I> i, I object) {
        return startAsDaemon(waitType, i, null, object);
    }

    public static <I> I startAsDaemon(Class<I> i, I object) {
        return startAsDaemon(WaitType.LOCK, i, object);
    }
}


text:
#pragma once

//! Include the SDL2_Engine objects
#include "../__LibraryManagement.hpp"
#include "../Utilities/Bitmask.hpp"
#include "ScenesValues.hpp"

namespace SDL2_Engine {
	namespace Scenes {
		//! Define a type for rendering order
		typedef unsigned char renderOrder;

		//! Export the required Bitmask implementation
		template class SDL2_LIB_INC Utilities::Bitmask<ESceneProperties>;

		/*
		 *		Name: ISceneBase
		 *		Author: Mitchell Croft
		 *		Created: 11/10/2017
		 *		Modified: 11/10/2017
		 *
		 *		Purpose:
		 *		Provide an interface for Base Scenes to implement from
		**/
		class SDL2_LIB_INC ISceneBase {
		public:
			/////////////////////////////////////////////////////////////////////////////////////////////////////
			////////-------------------------------Implementable Interface-------------------------------////////
			/////////////////////////////////////////////////////////////////////////////////////////////////////

			/*
				ISceneBase : Constructor - Initialise with default values
				Created: 11/10/2017
				Modified: 11/10/2017
			*/
			ISceneBase();

			/*
				ISceneBase : Destructor - Override-able destructor to allow for memory cleanup
				Created: 11/10/2017
				Modified: 11/10/2017
			*/
			virtual ~ISceneBase() {}

			/*
				ISceneBase : createScene - Function to facilitate the setup and validation of a Scene
				Created: 11/10/2017
				Modified: 11/10/2017

				return bool - Returns true if the Scene was created successfully
			*/
			virtual bool createScene() = 0;

			/*
				ISceneBase : destroyScene - Function to facilitate the deallocation of resources for a Scene
				Created: 11/10/2017
				Modified: 11/10/2017
			*/
			virtual void destroyScene() = 0;

			/*
				ISceneBase : update - Function to facilitate the updating of values once per cycle
				Created: 11/10/2017
				Modified: 11/10/2017
			*/
			inline virtual void update() {}

			/*
				ISceneBase : render - Function to facilitate the rendering of images once per cycle
				Created: 11/10/2017
				Modified: 11/10/2017
			*/
			inline virtual void render() {}

			/////////////////////////////////////////////////////////////////////////////////////////////////////
			////////-----------------------------------Data Accessors------------------------------------////////
			/////////////////////////////////////////////////////////////////////////////////////////////////////

			/*
				ISceneBase : getRenderOrder - Retrieve the render order value for the Scene
				Created: 11/10/2017
				Modified: 11/10/2017

				return const renderOrder& - Returns a constant reference to the render order value
			*/
			inline const renderOrder& getRenderOrder() const { return mRenderOrder; }

			/*
				ISceneBase : getProperties - Retrieve the properties value for the Scene
				Created: 11/10/2017
				Modified: 11/10/2017

				return const Utilities::Bitmask<ESceneProperties>& - Returns a constant reference to the properties bitmask
			*/
			inline const Utilities::Bitmask<ESceneProperties>& getProperties() const { return mProperties; }

			/*
				ISceneBase : getTypeID - Retrieve the type ID of the Scene
				Created: 11/10/2017
				Modified: 11/10/2017

				return const size_t& - Returns a constant reference to the type ID value
			*/
			inline const size_t& getTypeID() const { return mTypeID; }

			/////////////////////////////////////////////////////////////////////////////////////////////////////
			////////---------------------------------Property Modifiers----------------------------------////////
			/////////////////////////////////////////////////////////////////////////////////////////////////////

			/*
				ISceneBase : shutdown - Flag the Scene for shutdown
				Created: 11/10/2017
				Modified: 11/10/2017
			*/
			void shutdown();

			/*
				ISceneBase : show - Flag the Scene to be rendered
				Created: 11/10/2017
				Modified: 11/10/2017
			*/
			void show();

			/*
				ISceneBase : hide - Flag the Scene to be hidden
				Created: 11/10/2017
				Modified: 11/10/2017
			*/
			void hide();

			/*
				ISceneBase : prioritise - Flag the scene to take priority
				Created: 11/10/2017
				Modified: 11/10/2017
			*/
			void prioritise();

			/*
				ISceneBase : deprioritise - Flag the scene to remove priority
				Created: 11/10/2017
				Modified: 11/10/2017
			*/
			void deprioritise();

		protected:
			//! Store the rendering order, 0 being the foreground and 255 being the background
			renderOrder mRenderOrder;

		private:
			//! Set as a friend of the Scene Manager
			friend class SceneManager;

			//! Store the current state of the Scene
			Utilities::Bitmask<ESceneProperties> mProperties;

			//! Store a type-specific unique identifying ID value
			size_t mTypeID;
		};
	}
}

redpajama_set_name: RedPajamaGithub


text:
from argparse import ArgumentParser
import os
import sys

import django
from django.conf import settings

from coverage import coverage
from termcolor import colored

TESTS_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
TESTS_THRESHOLD = 100

def main():
    parser = ArgumentParser(description='Run the dj-stripe Test Suite.')
    parser.add_argument("--skip-utc", action="store_true", help="Skip any tests that require the system timezone to be in UTC.")
    parser.add_argument("--no-coverage", action="store_true", help="Disable checking for 100% code coverage (Not advised).")
    parser.add_argument("--no-pep8", action="store_true", help="Disable checking for pep8 errors (Not advised).")
    args = parser.parse_args()

    run_test_suite(args)

def run_test_suite(args):
    skip_utc = args.skip_utc
    enable_coverage = not args.no_coverage
    enable_pep8 = not args.no_pep8

    if enable_coverage:
        cov = coverage(config_file=True)
        cov.erase()
        cov.start()

    settings.configure(
        DJSTRIPE_TESTS_SKIP_UTC=skip_utc,
        TIME_ZONE='America/Los_Angeles',
        DEBUG=True,
        USE_TZ=True,
        DATABASES={
            "default": {
                "ENGINE": "django.db.backends.postgresql_psycopg2",
                "NAME": "djstripe",
                "USER": "",
                "PASSWORD": "",
                "HOST": "",
                "PORT": "",
            },
        },
        ROOT_URLCONF="tests.test_urls",
        INSTALLED_APPS=[
            "django.contrib.admin",
            "django.contrib.auth",
            "django.contrib.contenttypes",
            "django.contrib.sessions",
            "django.contrib.sites",
            "jsonfield",
            "djstripe",
            "tests",
            "tests.apps.testapp"
        ],
        MIDDLEWARE_CLASSES=(
            "django.contrib.sessions.middleware.SessionMiddleware",
            "django.contrib.auth.middleware.AuthenticationMiddleware",
            "django.contrib.messages.middleware.MessageMiddleware"
        ),
        SITE_ID=1,
        STRIPE_PUBLIC_KEY=os.environ.get("STRIPE_PUBLIC_KEY", ""),
        STRIPE_SECRET_KEY=os.environ.get("STRIPE_SECRET_KEY", ""),
        DJSTRIPE_PLANS={
            "test0": {
                "stripe_plan_id": "test_id_0",
                "name": "Test Plan 0",
                "description": "A test plan",
                "price": 1000,  # $10.00
                "currency": "usd",
                "interval": "month"
            },
            "test": {
                "stripe_plan_id": "test_id",
                "name": "Test Plan 1",
                "description": "Another test plan",
                "price": 2500,  # $25.00
                "currency": "usd",
                "interval": "month"
            },
            "test2": {
                "stripe_plan_id": "test_id_2",
                "name": "Test Plan 2",
                "description": "Yet Another test plan",
                "price": 5000,  # $50.00
                "currency": "usd",
                "interval": "month"
            },
            "test_deletion": {
                "stripe_plan_id": "test_id_3",
                "name": "Test Plan 3",
                "description": "Test plan for deletion.",
                "price": 5000,  # $50.00
                "currency": "usd",
                "interval": "month"
            },
            "test_trial": {
                "stripe_plan_id": "test_id_4",
                "name": "Test Plan 4",
                "description": "Test plan for trails.",
                "price": 7000,  # $70.00
                "currency": "usd",
                "interval": "month",
                "trial_period_days": 7
            },
            "unidentified_test_plan": {
                "name": "Unidentified Test Plan",
                "description": "A test plan with no ID.",
                "price": 2500,  # $25.00
                "currency": "usd",
                "interval": "month"
            }
        },
        DJSTRIPE_PLAN_HIERARCHY = {
            "bronze": {
                "level": 1,
                "plans": [
                    "test0",
                    "test",
                ]
            },
            "silver": {
                "level": 2,
                "plans": [
                    "test2",
                    "test_deletion",
                ]
            },
            "gold": {
                "level": 3,
                "plans": [
                    "test_trial",
                    "unidentified_test_plan",
                ]
            },
        },
        DJSTRIPE_SUBSCRIPTION_REQUIRED_EXCEPTION_URLS=(
            "(admin)",
            "test_url_name",
            "testapp_namespaced:test_url_namespaced",
        ),
    )

    # Avoid AppRegistryNotReady exception
    # http://stackoverflow.com/questions/24793351/django-appregistrynotready
    if hasattr(django, "setup"):
        django.setup()

    # Announce the test suite
    sys.stdout.write(colored(text="\nWelcome to the ", color="magenta", attrs=["bold"]))
    sys.stdout.write(colored(text="dj-stripe", color="green", attrs=["bold"]))
    sys.stdout.write(colored(text=" test suite.\n\n", color="magenta", attrs=["bold"]))

    # Announce test run
    sys.stdout.write(colored(text="Step 1: Running unit tests.\n\n", color="yellow", attrs=["bold"]))

    # Hack to reset the global argv before nose has a chance to grab it
    # http://stackoverflow.com/a/1718407/1834570
    args = sys.argv[1:]
    sys.argv = sys.argv[0:1]

    from django_nose import NoseTestSuiteRunner

    test_runner = NoseTestSuiteRunner(verbosity=1)
    failures = test_runner.run_tests(["."])

    if failures:
        sys.exit(failures)

    if enable_coverage:
        # Announce coverage run
        sys.stdout.write(colored(text="\nStep 2: Generating coverage results.\n\n", color="yellow", attrs=["bold"]))

        cov.stop()
        percentage = round(cov.report(show_missing=True), 2)
        cov.html_report(directory='cover')
        cov.save()

        if percentage < TESTS_THRESHOLD:
            sys.stderr.write(colored(text="YOUR CHANGES HAVE CAUSED TEST COVERAGE TO DROP. " +
                                     "WAS {old}%, IS NOW {new}%.\n\n".format(old=TESTS_THRESHOLD, new=percentage),
                                     color="red", attrs=["bold"]))
            sys.exit(1)
    else:
        # Announce disabled coverage run
        sys.stdout.write(colored(text="\nStep 2: Generating coverage results [SKIPPED].", color="yellow", attrs=["bold"]))

    if enable_pep8:
        # Announce flake8 run
        sys.stdout.write(colored(text="\nStep 3: Checking for pep8 errors.\n\n", color="yellow", attrs=["bold"]))

        print("pep8 errors:")
        print("----------------------------------------------------------------------")

        from subprocess import call
        flake_result = call(["flake8", ".", "--count"])
        if flake_result != 0:
            sys.stderr.write("pep8 errors detected.\n")
            sys.stderr.write(colored(text="\nYOUR CHANGES HAVE INTRODUCED PEP8 ERRORS!\n\n", color="red", attrs=["bold"]))
            sys.exit(flake_result)
        else:
            print("None")
    else:
        # Announce disabled coverage run
        sys.stdout.write(colored(text="\nStep 3: Checking for pep8 errors [SKIPPED].\n", color="yellow", attrs=["bold"]))

    # Announce success
    if enable_coverage and enable_pep8:
        sys.stdout.write(colored(text="\nTests completed successfully with no errors. Congrats!\n", color="green", attrs=["bold"]))
    else:
        sys.stdout.write(colored(text="\nTests completed successfully, but some step(s) were skipped!\n", color="green", attrs=["bold"]))
        sys.stdout.write(colored(text="Don't push without running the skipped step(s).\n", color="red", attrs=["bold"]))

if __name__ == "__main__":
    main()


text:
/*
 Blender Options:
 -b or --background <file>	Load <file> in background (often used for UI-less rendering)
 -a or --render-anim 	Render frames from start to end (inclusive)
 -S or --scene <name>	Set the active scene <name> for rendering
 -f or --render-frame <frame>	Render frame <frame> and save it.	+<frame> start frame relative, -<frame> end frame relative.
 -s or --frame-start <frame>	Set start to frame <frame> (use before the -a argument)
 -e or --frame-end <frame>	Set end to frame <frame> (use before the -a argument)
 -j or --frame-jump <frames>	Set number of frames to step forward after each rendered frame
 -o or --render-output <path>	Set the render path and file name.	Use // at the start of the path to
 render relative to the blend file.	The # characters are replaced by the frame number, and used to define zero padding.
 ani_##_test.png becomes ani_01_test.png
 test-######.png becomes test-000001.png
 When the filename does not contain #, The suffix #### is added to the filename	The frame number will be added at the end of the filename.
 eg: blender -b foobar.blend -o //render_ -F PNG -x 1 -a
 //render_ becomes //render_####, writing frames as //render_0001.png//
 -E or --engine <engine>	Specify the render engine	use -E help to list available engines

 Format Options:
 -F or --render-format <format>	Set the render format, Valid options are...
 TGA IRIS JPEG MOVIE IRIZ RAWTGA
 AVIRAW AVIJPEG PNG BMP FRAMESERVER	(formats that can be compiled into blender, not available on all systems)
 HDR TIFF EXR MULTILAYER MPEG AVICODEC QUICKTIME CINEON DPX DDS
 -x or --use-extension <bool>	Set option to add the file extension to the end of the file
 -t or --threads <threads>	Use amount of <threads> for rendering in background	[1-64], 0 for systems processor count.

 Animation Playback Options:
 -a <options> <file(s)>	Playback <file(s)>, only operates this way when not running in background.
 -p <sx> <sy>	Open with lower left corner at <sx>, <sy>
 -m		Read from disk (Don't buffer)
 -f <fps> <fps-base>		Specify FPS to start with
 -j <frame>	Set frame step to <frame>

 Window Options:
 -w or --window-border 	Force opening with borders (default)
 -W or --window-borderless 	Force opening without borders
 -p or --window-geometry <sx> <sy> <w> <h>	Open with lower left corner at <sx>, <sy> and width and height as <w>, <h>
 -con or --start-console 	Start with the console window open (ignored if -b is set)

 Game Engine Specific Options:
 -g Game Engine specific options
 -g fixedtime		Run on 50 hertz without dropping frames
 -g vertexarrays		Use Vertex Arrays for rendering (usually faster)
 -g nomipmap		No Texture Mipmapping
 -g linearmipmap		Linear Texture Mipmapping instead of Nearest (default)

 Misc Options:
 -d or --debug 	Turn debugging on
 * Prints every operator call and their arguments
 * Disables mouse grab (to interact with a debugger in some cases)
 * Keeps python sys.stdin rather than setting it to None
 --debug-fpe 	Enable floating point exceptions
 --debug-ffmpeg 	Enable debug messages from FFmpeg library
 --debug-libmv 	Enable debug messages from libmv library

 --factory-startup 	Skip reading the "startup.blend" in the users home directory

 --env-system-datafiles 	Set the BLENDER_SYSTEM_DATAFILES environment variable
 --env-system-scripts 	Set the BLENDER_SYSTEM_SCRIPTS environment variable
 --env-system-python 	Set the BLENDER_SYSTEM_PYTHON environment variable

 -nojoystick 	Disable joystick support
 -noglsl 	Disable GLSL shading
 -noaudio 	Force sound system to None
 -setaudio 	Force sound system to a specific device	NULL SDL OPENAL JACK

 -h or --help 	Print this help text and exit

 -y or --enable-autoexec 	Enable automatic python script execution, (default)
 -Y or --disable-autoexec 	Disable automatic python script execution (pydrivers & startup scripts)

 -P or --python <filename>	Run the given Python script (filename or Blender Text)
 --python-console 	Run blender with an interactive console
 --addons 	Comma separated list of addons (no spaces)
 -v or --version 	Print Blender version and exit
 -- 	Ends option processing, following arguments passed unchanged. Access via python's sys.argv
 Other Options:
 /? 	Print this help text and exit (windows only)
 --debug-python 	Enable debug messages for python
 --debug-events 	Enable debug messages for the event system
 --debug-wm 	Enable debug messages for the window manager
 --debug-all 	Enable all debug messages (excludes libmv)
 --debug-value <value>	Set debug value of <value> on startup

 --debug-jobs 	Enable time profiling for background jobs.
 --verbose <verbose>	Set logging verbosity level.
 -R 	Register .blend extension, then exit (Windows only)
 -r 	Silently register .blend extension, then exit (Windows only)
 Argument Parsing:	arguments must be separated by white space. eg
 "blender -ba test.blend"
 ...will ignore the 'a'
 "blender -b test.blend -f8"
 ...will ignore 8 because there is no space between the -f and the frame value
 Argument Order:
 Arguments are executed in the order they are given. eg
 "blender --background test.blend --render-frame 1 --render-output /tmp"
 ...will not render to /tmp because '--render-frame 1' renders before the output path is set
 "blender --background --render-output /tmp test.blend --render-frame 1"
 ...will not render to /tmp because loading the blend file overwrites the render output that was set
 "blender --background test.blend --render-output /tmp --render-frame 1" works as expected.

 Environment Variables:
 $BLENDER_USER_CONFIG      Directory for user configuration files.
 $BLENDER_USER_SCRIPTS     Directory for user scripts.
 $BLENDER_SYSTEM_SCRIPTS   Directory for system wide scripts.
 $Directory for user data files (icons, translations, ..).
 $BLENDER_SYSTEM_DATAFILES Directory for system wide data files.
 $BLENDER_SYSTEM_PYTHON    Directory for system python libraries.
 $TMP or $TMPDIR           Store temporary files here.
 $SDL_AUDIODRIVER          LibSDL audio driver - alsa, esd, dma.
 $PYTHONHOME               Path to the python directory, eg. /usr/lib/python.

 blender/config
 blender/scripts
 blender/userscripts
 */
package com.jme3.gde.blender;

import com.jme3.gde.blender.scripts.Scripts;
import java.awt.Frame;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.modules.InstalledFileLocator;
import org.openide.modules.Places;
import org.openide.util.Exceptions;
import org.openide.util.Utilities;
import org.openide.windows.WindowManager;

/**
 *
 * @author normenhansen
 */
public class BlenderTool {

    public static final String TEMP_SUFFIX = "blend";
    private static final String mainFolderName = "blender";
    private static final String configFolderName = mainFolderName + "/config";
    private static final String scriptsFolderName = mainFolderName + "/scripts";
    private static final String jmeScriptsFolderName = mainFolderName + "/jmescripts";
    private static final String userScriptsFolderName = mainFolderName + "/userscripts";
    private static final String tempFolderName = mainFolderName + "/temp";
    private static final Logger logger = Logger.getLogger(BlenderTool.class.getName());
    private static final AtomicBoolean blenderOpened = new AtomicBoolean(false);

    private static String getBlenderExeName() {
        if (Utilities.isWindows()) {
            return "blender.exe";
        } else {
            return "blender";
        }
    }

    private static String getBlenderOsPath() {
        if (Utilities.isMac()) {
            return "../blender/blender.app/Contents/MacOS";
        } else {
            return "../blender";
        }
    }

    private static boolean checkBlenderFolders() {
        String jmpDir = Places.getUserDirectory().getAbsolutePath();
        FileObject fileObject = FileUtil.toFileObject(new File(jmpDir));
        if (fileObject != null) {
            FileObject configFileObject = fileObject.getFileObject(configFolderName);
            //TODO: using installed blender scripts folder, make more flexible by moving
            //to updateable folder
            FileObject scriptsFileObject = fileObject.getFileObject(scriptsFolderName);
            FileObject jmeScriptsFileObject = fileObject.getFileObject(jmeScriptsFolderName);
            FileObject userScriptsFileObject = fileObject.getFileObject(userScriptsFolderName);
            if (configFileObject == null) {
                try {
                    configFileObject = FileUtil.createFolder(fileObject, configFolderName);
                } catch (IOException ex) {
                    Exceptions.printStackTrace(ex);
                    return false;
                }
            }
            if (scriptsFileObject == null) {
                try {
                    scriptsFileObject = FileUtil.createFolder(fileObject, scriptsFolderName);
                } catch (IOException ex) {
                    Exceptions.printStackTrace(ex);
                    return false;
                }
            }
            if (jmeScriptsFileObject == null) {
                try {
                    jmeScriptsFileObject = FileUtil.createFolder(fileObject, jmeScriptsFolderName);
                } catch (IOException ex) {
                    Exceptions.printStackTrace(ex);
                    return false;
                }
            }
            if (userScriptsFileObject == null) {
                try {
                    userScriptsFileObject = FileUtil.createFolder(fileObject, userScriptsFolderName);
                } catch (IOException ex) {
                    Exceptions.printStackTrace(ex);
                    return false;
                }
            }
            Scripts.copyToFolder(jmeScriptsFileObject);
        } else {
            logger.log(Level.SEVERE, "No global settings folder found!");
            return false;
        }
        return true;
    }

    private static String getConfigEnv() {
        String ret = Places.getUserDirectory().getAbsolutePath() + "/" + configFolderName;
        ret = ret.replace("/", File.separator);
        return ret;
    }

    private static String getScriptsEnv() {
        //TODO: using installed blender scripts folder
        String ret = getBlenderSettingsFolder().getAbsolutePath();
//        String ret = System.getProperty("netbeans.user") + "/" + scriptsFolderName;
        ret = ret.replace("/", File.separator);
        return ret;
    }

    private static String getUserScriptsEnv() {
        String ret = Places.getUserDirectory().getAbsolutePath() + "/" + userScriptsFolderName;
        ret = ret.replace("/", File.separator);
        return ret;
    }

    private static String getScriptPath(String scriptName, String prefix) {
        String ret = Places.getUserDirectory().getAbsolutePath() + "/" + jmeScriptsFolderName + "/" + prefix + "_" + scriptName + ".py";
        ret = ret.replace("/", File.separator);
        return ret;
    }

    private static File getBlenderExecutable() {
        File blender = InstalledFileLocator.getDefault().locate(getBlenderOsPath() + "/" + getBlenderExeName(), null, false);
        if (blender == null) {
            DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message("Error finding Blender executable"));
            logger.log(Level.SEVERE, "Error finding Blender executable");
        }
        return blender;
    }

    private static File getBlenderSettingsFolder() {
        File blender = InstalledFileLocator.getDefault().locate(getBlenderOsPath() + "/2.69", null, false);
        if (blender == null) {
            blender = InstalledFileLocator.getDefault().locate(getBlenderOsPath() + "/2.67", null, false);
        }
        if (blender == null) {
            DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message("Error finding Blender settings"));
            logger.log(Level.SEVERE, "Error finding Blender settings");
        }
        return blender;
    }

    private static File getBlenderRootFolder() {
        File blender = InstalledFileLocator.getDefault().locate(getBlenderOsPath(), null, false);
        if (blender == null) {
            DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message("Error finding Blender root folder"));
            logger.log(Level.SEVERE, "Error finding Blender root folder");
        }
        return blender;
    }

    public static boolean runConversionScript(String type, FileObject input) {
        if (!checkBlenderFolders()) {
            logger.log(Level.SEVERE, "Could not create blender settings folders!");
            return false;
        }
        final File exe = getBlenderExecutable();
        if (exe == null) {
            logger.log(Level.SEVERE, "Could not find blender executable!");
            return false;
        }
        logger.log(Level.INFO, "Running blender as converter for file {0}", input.getPath());
        String scriptPath = getScriptPath(type, "import");
        String inputPath = input.getPath().replace("/", File.separator);
        String inputFolder = input.getParent().getPath().replace("/", File.separator) + File.separator;
        String outputPath = inputFolder + input.getName() + "." + TEMP_SUFFIX;
        try {
            String command = exe.getAbsolutePath();
            ProcessBuilder buildr = new ProcessBuilder(command, "-b",
                    "--factory-startup",
                    "-P", scriptPath,
                    "--",
                    "-i", inputPath,
                    "-o", outputPath);
            buildr.directory(getBlenderRootFolder());
            buildr.environment().put("BLENDER_USER_CONFIG", getConfigEnv());
            buildr.environment().put("BLENDER_SYSTEM_SCRIPTS", getScriptsEnv());
            buildr.environment().put("BLENDER_USER_SCRIPTS", getUserScriptsEnv());
            Process proc = buildr.start();
            OutputReader outReader = new OutputReader(proc.getInputStream());
            OutputReader errReader = new OutputReader(proc.getErrorStream());
            outReader.start();
            errReader.start();
            try {
                proc.waitFor();
            } catch (InterruptedException ex) {
                Exceptions.printStackTrace(ex);
            }
            if (proc.exitValue() != 0) {
                logger.log(Level.SEVERE, "Error running blender!");
                return false;
            }
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }
        return true;
    }

    public static boolean runToolScript(String toolName, FileObject input) {
        if (!checkBlenderFolders()) {
            logger.log(Level.SEVERE, "Could not create blender settings folders!");
            return false;
        }
        final File exe = getBlenderExecutable();
        if (exe == null) {
            logger.log(Level.SEVERE, "Could not find blender executable!");
            return false;
        }
        logger.log(Level.INFO, "Running blender as {0} tool for file {1}", new Object[]{toolName, input.getPath()});
        String scriptPath = getScriptPath(toolName, "tool");
        String inputPath = input.getPath().replace("/", File.separator);
        try {
            String command = exe.getAbsolutePath();
            ProcessBuilder buildr = new ProcessBuilder(command, "-b",
                    "--factory-startup",
                    "-P", scriptPath,
                    "--",
                    "-i", inputPath);
            buildr.directory(getBlenderRootFolder());
            buildr.environment().put("BLENDER_USER_CONFIG", getConfigEnv());
            buildr.environment().put("BLENDER_SYSTEM_SCRIPTS", getScriptsEnv());
            buildr.environment().put("BLENDER_USER_SCRIPTS", getUserScriptsEnv());
            Process proc = buildr.start();
            OutputReader outReader = new OutputReader(proc.getInputStream());
            OutputReader errReader = new OutputReader(proc.getErrorStream());
            outReader.start();
            errReader.start();
            try {
                proc.waitFor();
            } catch (InterruptedException ex) {
                Exceptions.printStackTrace(ex);
            }
            if (proc.exitValue() != 0) {
                logger.log(Level.SEVERE, "Error running blender!");
                return false;
            }
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }
        return true;
    }

    private static boolean runBlender(final String file, boolean async) {
        if (!checkBlenderFolders()) {
            logger.log(Level.SEVERE, "Could not create blender settings folders!");
            return false;
        }
        logger.log(Level.INFO, "Running blender with options {0}", file);
        if (blenderOpened.getAndSet(true)) {
            logger.log(Level.WARNING, "Blender seems to be running already.");
            return false;
        }
        final AtomicBoolean successful = new AtomicBoolean(true);
        final File exe = getBlenderExecutable();
        if (exe == null) {
            logger.log(Level.SEVERE, "Could not find blender executable!");
            blenderOpened.set(false);
            return false;
        }
        final Frame mainWin = WindowManager.getDefault().getMainWindow();
        assert (mainWin != null);
        mainWin.setExtendedState(Frame.ICONIFIED);
        Runnable r = new Runnable() {
            public void run() {
                try {
                    String command = exe.getAbsolutePath();
                    ProcessBuilder buildr = new ProcessBuilder(command, file);
                    buildr.directory(getBlenderRootFolder());
                    buildr.environment().put("BLENDER_USER_CONFIG", getConfigEnv());
                    buildr.environment().put("BLENDER_SYSTEM_SCRIPTS", getScriptsEnv());
                    buildr.environment().put("BLENDER_USER_SCRIPTS", getUserScriptsEnv());
                    Process proc = buildr.start();
                    OutputReader outReader = new OutputReader(proc.getInputStream());
                    OutputReader errReader = new OutputReader(proc.getErrorStream());
                    outReader.start();
                    errReader.start();
                    try {
                        proc.waitFor();
                    } catch (InterruptedException ex) {
                        Exceptions.printStackTrace(ex);
                    }
                    if (proc.exitValue() == 0) {
                        successful.set(true);
                    }
                } catch (Exception ex) {
                    Exceptions.printStackTrace(ex);
                    successful.set(false);
                } finally {
                    blenderOpened.set(false);
                    java.awt.EventQueue.invokeLater(new Runnable() {
                        public void run() {
                            mainWin.setExtendedState(Frame.NORMAL);
                            mainWin.requestFocus();
                        }
                    });
                }
            }
        };
        if (async) {
            new Thread(r).start();
        } else {
            r.run();
        }
        return successful.get();
    }

    public static boolean openInBlender(FileObject file) {
        String path = file.getPath().replace("/", File.separator);
        return runBlender(path, true);
    }

    public static void runBlender() {
        if (!runBlender(null, true)) {
            logger.log(Level.INFO, "Could not run blender, already running? Trying to focus window.");
            DialogDisplayer.getDefault().notifyLater(new NotifyDescriptor.Message("Blender is already running!"));
        }
    }
}


text:
function [stateDot,setPriority] = flowMap(SYSTEM_NAMEObj,time,state,input,flowTime,jumpCount)
% The "flowMap" method sets the continuous time dynamics of the system.
%
% SYNTAX:
%   [stateDot,setPriority] = SYSTEM_NAMEObj.flowMap()
%   [stateDot,setPriority] = SYSTEM_NAMEObj.flowMap(time)
%   [stateDot,setPriority] = SYSTEM_NAMEObj.flowMap(time,state)
%   [stateDot,setPriority] = SYSTEM_NAMEObj.flowMap(time,state,input)
%   [stateDot,setPriority] = SYSTEM_NAMEObj.flowMap(time,state,input,flowTime)
%   [stateDot,setPriority] = SYSTEM_NAMEObj.flowMap(time,state,input,flowTime,jumpCount)
%
% INPUTS:
%   SYSTEM_NAMEObj - (1 x 1 PACKAGE_NAME_D_SYSTEM_NAME)
%       An instance of the "PACKAGE_NAME_D_SYSTEM_NAME" class.
%
%   time - (1 x 1 real number) [SYSTEM_NAMEObj.time]
%       Current time.
%
%   state - (? x 1 number) [SYSTEM_NAMEObj.state]
%       Current state. Must be a "SYSTEM_NAMEObj.nStates" x 1 vector.
%
%   input - (? x 1 number) [SYSTEM_NAMEObj.input]
%       Current input value. Must be a "SYSTEM_NAMEObj.nInputs" x 1 vector.
%
%   flowTime - (1 x 1 semi-positive real number) [SYSTEM_NAMEObj.flowTime]
%       Current flow time value.
%
%   jumpCount - (1 x 1 semi-positive integer) [SYSTEM_NAMEObj.jumpCount]
%       Current jump count value.
%
% OUTPUTS:
%   stateDot - (? x 1 number)
%       Updated state derivatives. A "SYSTEM_NAMEObj.nStates" x 1 vector.
%
%   setPriority - ('flow','jump', or 'random')
%       Sets the priority to what takes place if the state is in both
%       the flow set and the jump set.
%
% NOTES:
%
% NECESSARY FILES AND/OR PACKAGES:
%   NECESSARY_PACKAGE+simulate
%
% AUTHOR:
%    FULL_NAME
%
% VERSION:
%   Created DD-MMM-YYYY
%-------------------------------------------------------------------------------

%% Apply default values
if nargin < 2, time = SYSTEM_NAMEObj.time; end
if nargin < 3, state = SYSTEM_NAMEObj.state; end
if nargin < 4, input = SYSTEM_NAMEObj.input; end
if nargin < 5, flowTime = SYSTEM_NAMEObj.flowTime; end
if nargin < 6, jumpCount = SYSTEM_NAMEObj.jumpCount; end
setPriority = SYSTEM_NAMEObj.setPriority;

%% Parameters

%% Variables

%% Equations Of Motion

%% Output
stateDot(:,1) = zeros(SYSTEM_NAMEObj.nStates,1);

end


text:
(function() {
  var InformerJp2, InformerJp2Openjpeg, child_process,
    bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
    extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
    hasProp = {}.hasOwnProperty;

  child_process = require('child_process');

  InformerJp2 = require('./informer-jp2').InformerJp2;

  InformerJp2Openjpeg = (function(superClass) {
    extend(InformerJp2Openjpeg, superClass);

    function InformerJp2Openjpeg(path, final_callback) {
      this.path = path;
      this.final_callback = final_callback;
      this.inform = bind(this.inform, this);
      this.info = null;
    }

    InformerJp2Openjpeg.prototype.inform = function() {
      var cmd;
      cmd = "opj_dump -i " + this.path;
      return child_process.exec(cmd, (function(_this) {
        return function(err, out, stderr) {
          var height, height_match, i, level, levels, levels_match, ref, scale_factors, sizes, tiles_height, tiles_match_height, tiles_match_width, tiles_width, width, width_match;
          width_match = out.match(/x1=(.*),/);
          width = parseInt(width_match[1]);
          height_match = out.match(/, y1=(.*)/);
          height = parseInt(height_match[1]);
          levels_match = out.match(/numresolutions=(.*)/);
          levels = parseInt(levels_match[1]) - 1;
          tiles_match_width = out.match(/tdx=(.*),/);
          tiles_width = parseInt(tiles_match_width[1]);
          tiles_match_height = out.match(/tdy=(.*)/);
          tiles_height = parseInt(tiles_match_height[1]);
          _this.info = {
            width: width,
            height: height,
            levels: levels,
            tiles: [
              {
                width: tiles_width,
                height: tiles_height
              }
            ]
          };
          sizes = _this.calculate_sizes_for_levels();
          scale_factors = [];
          for (level = i = 0, ref = _this.info.levels; 0 <= ref ? i <= ref : i >= ref; level = 0 <= ref ? ++i : --i) {
            scale_factors.push(Math.pow(2, level));
          }
          _this.info.tiles[0]['scaleFactors'] = scale_factors;
          return _this.final_callback(_this.info);
        };
      })(this));
    };

    return InformerJp2Openjpeg;

  })(InformerJp2);

  exports.InformerJp2Openjpeg = InformerJp2Openjpeg;

}).call(this);


text:
from django.db import models

from taggit.managers import TaggableManager

class Library(models.Model):
    """
        A code library that implements some conceptual idea. For example,
        Django is an implementation of the web application framework
        concept.
    """
    name = models.CharField(max_length=250)
    slug = models.SlugField(max_length=64, unique=True)
    homepage_url = models.URLField(max_length=1024, blank=True, default="")
    package_url = models.URLField(max_length=2048, blank=True, default="")
    source_code_url = models.URLField(max_length=2048, blank=True,
                                      default="")
    summary = models.TextField()
    language = models.ForeignKey("Language")
    is_visible = models.BooleanField(default=False)

    tags = TaggableManager()

    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = "libraries"

class Language(models.Model):
    """
        A programming language, such as Python or C, and related
        information on it.
    """
    name = models.CharField(max_length=250)
    slug = models.SlugField(max_length=64, unique=True)
    homepage_url = models.URLField(max_length=1024, blank=True)
    summary = models.TextField()
    year_appeared = models.IntegerField(null=True, blank=True)
    source_code_url = models.URLField(max_length=2048, blank=True,
                                      default="")
    logo_url = models.URLField(max_length=2048, blank=True)
    is_visible = models.BooleanField(default=False)

    tags = TaggableManager()

    def __str__(self):
        return self.name

class Tutorial(models.Model):
    """
        An article or blog post with a tutorial for a specific
        language or framework.
    """
    name = models.CharField(max_length=1024)
    slug = models.SlugField(max_length=64, unique=True)
    tutorial_url = models.URLField(max_length=2048)
    language = models.ForeignKey("Language", related_name="tutorials",
                                 blank=True, null=True)
    libraries = models.ManyToManyField("Library", related_name="tutorials",
                                       blank=True)
    summary = models.TextField()
    is_visible = models.BooleanField(default=False)

    tags = TaggableManager()

    def __str__(self):
        return self.name


text:
package druzy.mvc;

import java.util.EventListener;

public interface AnotherChangeListener extends EventListener {

	public void anotherChange(AnotherChangeEvent event);
}


text:
  # a simple file renderer that allows setting of colors per line based on
  # regexps passed to +insert_mapping+. See +tasks.rb+ for example usage.
  #
  class DefaultFileRenderer < AbstractTextPadRenderer
    attr_accessor :default_colors
    attr_reader :hash

    def initialize source=nil
      @default_colors = [:white, :black, NORMAL]
      @pair = get_color($datacolor, @default_colors.first, @default_colors[1])
    end

    def color_mappings hash
      @hash = hash
    end
    # takes a regexp, and an array of color, bgcolor and attr
    def insert_mapping regex, dim
      @hash ||= {}
      @hash[regex] = dim
    end
    # matches given line with each regexp to determine color use
    # Internally used by render.
    def match_line line
      @hash.each_pair {| k , p|
        if line =~ k
          return p
        end
      }
      return @default_colors
    end
    # render given line in color configured using +insert_mapping+
    def render pad, lineno, text
      if @hash
        dim = match_line text
        fg = dim.first
        bg = dim[1] || @default_colors[1]
        if dim.size == 3
          att = dim.last
        else
          att = @default_colors.last
        end
        cp = get_color($datacolor, fg, bg)
      else
        cp = @pair
        att = @default_colors[2]
      end

      FFI::NCurses.wattron(pad,FFI::NCurses.COLOR_PAIR(cp) | att)
      FFI::NCurses.mvwaddstr(pad, lineno, 0, text)
      FFI::NCurses.wattroff(pad,FFI::NCurses.COLOR_PAIR(cp) | att)
    end
    #
  end


text:
package jo.vecmath;

/**
 * A 2-element point represented by signed integer x,y
 * coordinates.
 *
 * @since vecmath 1.4
 */
 public class Point2i extends Tuple2i implements java.io.Serializable {

    static final long serialVersionUID = 9208072376494084954L;

    /**
     * Constructs and initializes a Point2i from the specified
     * x and y coordinates.
     * @param x the x coordinate
     * @param y the y coordinate
     */
     public Point2i(int x, int y) {
      super(x, y);
    }

    /**
     * Constructs and initializes a Point2i from the array of length 2.
     * @param t the array of length 2 containing x and y in order.
     */
     public Point2i(int[] t) {
      super(t);
    }

    /**
     * Constructs and initializes a Point2i from the specified Tuple2i.
     * @param t1 the Tuple2i containing the initialization x and y
     * data.
     */
     public Point2i(Tuple2i t1) {
      super(t1);
    }

    /**
     * Constructs and initializes a Point2i to (0,0).
     */
     public Point2i() {
      super();
    }

}


text:
export default {
  keydown: event => {
    if (event.key === 'Escape') {
      document.activeElement.blur()
    }
    // firefox doesn't fire blur events if the active element is removed from
    // the DOM or its style is set to none. The following is hacky workaround
    // https://bugzilla.mozilla.org/show_bug.cgi?id=559561
    // TODO: return 'Same' on all platforms when firefox fixes the bug
    return SAKA_PLATFORM === 'firefox' ? 'Reset' : 'Same'
  },
  blur: () => 'Reset',
  focus: () => 'Reset'
}


text:
package lintflags

import (
	"fmt"
	"runtime"
	"sort"
	"strings"
	"time"

	"github.com/urfave/cli"
)

var (
	// defaults as gometalinter expects them
	defaultConcurrency    = 16
	defaultCycloOver      = 10
	defaultLineLength     = 80
	defaultMinConfidence  = 0.80
	defaultMinOccurrences = 3
	defaultMinConstLength = 3
	defaultDuplThreshold  = 50
	defaultDeadline       = 5 * time.Second
	defaultSort           = SortNone
	// defaultFormat         = "{{.Path}}:{{.Line}}:{{if .Col}}{{.Col}}{{end}}:{{.Severity}}: {{.Message}} ({{.Linter}})"
)

type Data struct {
	NoVendoredLinters bool
	Fast              bool
	Install           bool
	Update            bool
	Force             bool
	Debug             bool
	Concurrency       int
	Exclude           cli.StringSlice
	Include           cli.StringSlice
	Skip              cli.StringSlice
	// Vendor            bool
	CycloOver        int
	LineLength       int
	MinConfidence    float64
	MinOccurrences   int
	MinConstLength   int
	DuplThreshold    int
	Sort             SortKey
	NoTests          bool
	Deadline         time.Duration
	Errors           bool
	JSON             bool
	Checkstyle       bool
	EnableGC         bool
	Aggregate        bool
	Disable          cli.StringSlice
	Enable           cli.StringSlice
	Linter           cli.StringSlice
	MessageOverrides cli.StringSlice
	Severity         cli.StringSlice
	DisableAll       bool
	EnableAll        bool
	// Format           string
}

func (f *Data) LintFlags() []cli.Flag {
	return []cli.Flag{
		cli.BoolFlag{
			Name:        "no-vendored-linters",
			Usage:       "Do not use vendored linters (not recommended).",
			Destination: &f.NoVendoredLinters,
		},
		cli.BoolFlag{
			Name:        "fast",
			Usage:       "Only run fast linters.",
			Destination: &f.Fast,
		},
		cli.BoolFlag{
			Name:        "install, i",
			Usage:       "Attempt to install all known linters.",
			Destination: &f.Install,
		},
		cli.BoolFlag{
			Name:        "update, u",
			Usage:       "Pass -u to go tool when installing.",
			Destination: &f.Update,
		},
		cli.BoolFlag{
			Name:        "force, f",
			Usage:       "Pass -f to go tool when installing. When linting treats all lint results as uncached.",
			Destination: &f.Force,
		},
		cli.BoolFlag{
			Name:        "debug, d",
			Usage:       "Display messages for failed linters, etc.",
			Destination: &f.Debug,
		},
		cli.IntFlag{
			Name:        "concurrency, j",
			Usage:       "Number of concurrent linters to run.",
			Value:       getConcurrency(),
			Destination: &f.Concurrency,
		},
		cli.StringSliceFlag{
			Name:  "exclude, e",
			Usage: "Exclude messages matching these regular expressions.",
			Value: &f.Exclude,
		},
		cli.StringSliceFlag{
			Name:  "include, I",
			Usage: "Include messages matching these regular expressions.",
			Value: &f.Include,
		},
		cli.StringSliceFlag{
			Name:  "skip, s",
			Usage: "Skip directories with this name when expanding '...'.",
			Value: &f.Skip,
		},
		// cli.BoolFlag{
		// 	Name:        "vendor",
		// 	Usage:       "Enable vendoring support (skips 'vendor' directories and sets GO15VENDOREXPERIMENT=1).",
		// 	Destination: &f.Vendor,
		// },
		cli.IntFlag{
			Name:        "cyclo-over",
			Usage:       "Report functions with cyclomatic complexity over N (using gocyclo).",
			Value:       defaultCycloOver,
			Destination: &f.CycloOver,
		},
		cli.IntFlag{
			Name:        "line-length",
			Usage:       "Report lines longer than N (using lll).",
			Value:       defaultLineLength,
			Destination: &f.LineLength,
		},
		cli.Float64Flag{
			Name:        "min-confidence",
			Usage:       "Minimum confidence interval to pass to golint.",
			Value:       defaultMinConfidence,
			Destination: &f.MinConfidence,
		},
		cli.IntFlag{
			Name:        "min-occurrences",
			Usage:       "Minimum occurrences to pass to goconst.",
			Value:       defaultMinOccurrences,
			Destination: &f.MinOccurrences,
		},
		cli.IntFlag{
			Name:        "min-const-length",
			Usage:       "Minimumum constant length.",
			Value:       defaultMinConstLength,
			Destination: &f.MinConstLength,
		},
		cli.IntFlag{
			Name:        "dupl-threshold",
			Usage:       "Minimum token sequence as a clone for dupl.",
			Value:       defaultDuplThreshold,
			Destination: &f.DuplThreshold,
		},
		cli.GenericFlag{
			Name:  "sort",
			Usage: fmt.Sprintf("Sort output by any of %s.", strings.Join(sortKeysStr, ", ")),
			Value: &f.Sort,
		},
		cli.BoolFlag{
			Name:        "no-tests",
			Usage:       "Do not include test files for linters that support this option",
			Destination: &f.NoTests,
		},
		cli.DurationFlag{
			Name:        "deadline",
			Usage:       "Cancel linters if they have not completed within this duration.",
			Value:       30 * time.Second,
			Destination: &f.Deadline,
		},
		cli.BoolFlag{
			Name:        "errors",
			Usage:       "Only show errors.",
			Destination: &f.Errors,
		},
		cli.BoolFlag{
			Name:        "json",
			Usage:       "Generate structured JSON rather than standard line-based output.",
			Destination: &f.JSON,
		},
		cli.BoolFlag{
			Name:        "checkstyle",
			Usage:       "Generate checkstyle XML rather than standard line-based output.",
			Destination: &f.Checkstyle,
		},
		cli.BoolFlag{
			Name:        "enable-gc",
			Usage:       "Do not enable GC for linters (useful on large repositories).",
			Destination: &f.EnableGC,
		},
		cli.BoolFlag{
			Name:        "aggregate",
			Usage:       "Aggregate issues reported by several linters.",
			Destination: &f.Aggregate,
		},
		cli.StringSliceFlag{
			Name:  "disable, D",
			Usage: fmt.Sprintf("List of linters to disable (%s).", strings.Join(disabledLinters, ",")),
			Value: &f.Disable,
		},
		cli.StringSliceFlag{
			Name:  "enable, E",
			Usage: fmt.Sprintf("Enable previously disabled linters (%s).", strings.Join(enabledLinters, ",")),
			Value: &f.Enable,
		},
		cli.StringSliceFlag{
			Name:  "linter",
			Usage: "Specify a linter.",
			Value: &f.Linter,
		},
		cli.StringSliceFlag{
			Name:  "message-overrides",
			Usage: "Override message from linter. {message} will be expanded to the original message.",
			Value: &f.MessageOverrides,
		},
		cli.StringSliceFlag{
			Name:  "severity",
			Usage: "Map of linter severities.",
			Value: &f.Severity,
		},
		cli.BoolFlag{
			Name:        "disable-all",
			Usage:       "Disable all linters.",
			Destination: &f.DisableAll,
		},
		cli.BoolFlag{
			Name:        "enable-all",
			Usage:       "Enable all linters.",
			Destination: &f.EnableAll,
		},
		// cli.StringFlag{
		// 	Name:        "format",
		// 	Usage:       "Output format.",
		// 	Value:       defaultFormat,
		// 	Destination: &f.Format,
		// },
	}
}

func getConcurrency() int {
	// return at least 1
	// the lesser of:
	// * if even number of cpus, 1 less than half that number
	// * if odd number of cpus, half that number rounded down (truncated)
	// * GOMAXPROCS
	n := runtime.NumCPU()
	var cpu int
	if n%2 == 0 { // even
		cpu = n/2 - 1
	} else { // odd
		cpu = n / 2
	}

	m := runtime.GOMAXPROCS(-1)

	r := m
	if cpu < m {
		r = cpu
	}

	if r <= 0 {
		r = 1
	}

	return r
}

// these are disabled in zb by default
var disabledLinters = []string{"aligncheck", "gocyclo"}

// these are enabled in zb by default
var enabledLinters = []string{"gofmt", "goimports", "misspell"}

const (
	disable = "-D"
	enable  = "-E"
)

func (f *Data) linters() []string {
	lm := map[string]string{}

	for _, linter := range disabledLinters {
		lm[linter] = disable
	}

	for _, linter := range enabledLinters {
		lm[linter] = enable
	}

	for _, v := range f.Disable {
		lm[v] = disable
	}

	for _, v := range f.Enable {
		lm[v] = enable
	}

	var disabled, enabled []string

	for l, f := range lm {
		if f == disable {
			disabled = append(disabled, l)
		} else {
			enabled = append(enabled, l)
		}
	}

	sort.Strings(disabled)
	sort.Strings(enabled)

	var args []string
	for _, v := range disabled {
		args = append(args, disable, v)
	}
	for _, v := range enabled {
		args = append(args, enable, v)
	}

	if f.Fast {
		args = append(args, "--fast")
	}

	if f.DisableAll {
		args = append(args, "--disable-all")
	}

	if f.EnableAll {
		args = append(args, "--enable-all")
	}

	return args
}

func (f *Data) LintArgs() []string {
	var args []string

	if f.NoVendoredLinters {
		args = append(args, "--no-vendored-linters")
	}

	if f.Install {
		args = append(args, "--install")

		if f.Update {
			args = append(args, "--update")
		}

		if f.Force {
			args = append(args, "--force")
		}
	}

	if f.Debug {
		args = append(args, "--debug")
	}

	if f.Concurrency != 0 && f.Concurrency != defaultConcurrency {
		args = append(args, "-j", fmt.Sprintf("%d", f.Concurrency))
	}

	for _, v := range f.Exclude {
		args = append(args, "--exclude", v)
	}

	for _, v := range f.Include {
		args = append(args, "--include", v)
	}

	for _, v := range f.Skip {
		args = append(args, "--skip", v)
	}

	// if f.Vendor {
	// 	args = append(args, "--vendor")
	// }

	if f.CycloOver != 0 && f.CycloOver != defaultCycloOver {
		args = append(args, "--cyclo-over", fmt.Sprintf("%d", f.CycloOver))
	}

	if f.LineLength != 0 && f.LineLength != defaultLineLength {
		args = append(args, "--line-length", fmt.Sprintf("%d", f.LineLength))
	}

	if f.MinConfidence != 0 && f.MinConfidence != defaultMinConfidence {
		args = append(args, "--min-confidence", fmt.Sprintf("%f", f.MinConfidence))
	}

	if f.MinOccurrences != 0 && f.MinOccurrences != defaultMinOccurrences {
		args = append(args, "--min-occurrences", fmt.Sprintf("%d", f.MinOccurrences))
	}

	if f.MinConstLength != 0 && f.MinConstLength != defaultMinConstLength {
		args = append(args, "--min-const-length", fmt.Sprintf("%d", f.MinConstLength))
	}

	if f.DuplThreshold != 0 && f.DuplThreshold != defaultDuplThreshold {
		args = append(args, "--dupl-threshold", fmt.Sprintf("%d", f.DuplThreshold))
	}

	if f.Sort != "" && f.Sort != defaultSort {
		args = append(args, "--sort", string(f.Sort))
	}

	if !f.NoTests {
		args = append(args, "--tests")
	}

	if f.Deadline != 0 && f.Deadline != defaultDeadline {
		args = append(args, "--deadline", f.Deadline.String())
	}

	if f.Errors {
		args = append(args, "--errors")
	}

	if f.JSON {
		args = append(args, "--json")
	}

	if f.Checkstyle {
		args = append(args, "--checkstyle")
	}

	if f.EnableGC {
		args = append(args, "--enable-gc")
	}

	if f.Aggregate {
		args = append(args, "--aggregate")
	}

	for _, v := range f.Linter {
		args = append(args, "--linter", v)
	}

	for _, v := range f.MessageOverrides {
		args = append(args, "--message-overrides", v)
	}

	for _, v := range f.Severity {
		args = append(args, "--severity", v)
	}

	// if f.Format != "" && f.Format != defaultFormat {
	// 	args = append(args, "--format", f.Format)
	// }

	return append(args, f.linters()...)
}


text:
package restclient

import (
	"bytes"
	"crypto/tls"
	"encoding/json"
	"io/ioutil"
	"net/http"
	"time"
)

var insecureHTTPSClient *http.Client = nil

func GetInsecureHTTPSClient() *http.Client {
	// Skip the server side certificate checking
	if insecureHTTPSClient == nil {
		transport := &http.Transport{
			TLSClientConfig: &tls.Config{
				InsecureSkipVerify: true,
			},
		}
		insecureHTTPSClient = &http.Client{
			Transport: transport,
		}
		return insecureHTTPSClient
	} else {
		return insecureHTTPSClient
	}
}

func HealthCheck(url string, headerMap map[string]string, timeout time.Duration) (returnedResult bool, returnedError error) {
	defer func() {
		if err := recover(); err != nil {
			returnedResult = false
			returnedError = err.(error)
		}
	}()
	transport := &http.Transport{
		TLSClientConfig: &tls.Config{
			InsecureSkipVerify: true,
		},
	}
	insecureHTTPSClient := &http.Client{
		Transport: transport,
		Timeout:   timeout,
	}

	request, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return false, err
	}

	for key, value := range headerMap {
		request.Header.Add(key, value)
	}

	response, err := insecureHTTPSClient.Do(request)
	if err != nil {
		return false, err
	} else {
		defer response.Body.Close()
		if response.StatusCode == 200 || response.StatusCode == 204 {
			return true, nil
		} else {
			return false, nil
		}
	}
}

type RequestError struct {
	Url           string
	StatusCode    int
	ResponseData  interface{}
	ResponseBody  *string
	ReturnedError error
}

func (requestError RequestError) AllData() string {
	jsonMap := make(map[string]interface{})
	jsonMap["Url"] = requestError.Url
	jsonMap["StatusCode"] = requestError.StatusCode
	jsonMap["ResponseData"] = requestError.ResponseData
	if requestError.ResponseBody != nil {
		jsonMap["ResponseBody"] = *requestError.ResponseBody
	} else {
		jsonMap["ResponseBody"] = ""
	}
	if requestError.ReturnedError != nil {
		jsonMap["ReturnedError"] = requestError.ReturnedError.Error()
	} else {
		jsonMap["ReturnedError"] = nil
	}
	byteSlice, _ := json.Marshal(jsonMap)
	return string(byteSlice)
}

func (requestError RequestError) Error() string {
	if requestError.ResponseData != nil {
		byteSlice, err := json.Marshal(requestError.ResponseData)
		if err != nil {
			if requestError.ResponseBody != nil {
				return *requestError.ResponseBody
			} else {
				return ""
			}
		} else {
			return string(byteSlice)
		}
	} else {
		if requestError.ResponseBody != nil {
			return *requestError.ResponseBody
		} else {
			return ""
		}
	}
}

func Request(method string, url string, body interface{}, headerMap map[string]string, useJsonNumberInsteadFloat64ForResultJson bool) (returnedStatusCode int, returnedJsonMapOrJsonSlice interface{}, returnedResponseBody *string, returnedError error) {
	defer func() {
		if err := recover(); err != nil {
			returnedStatusCode = 500
			returnedJsonMapOrJsonSlice = nil
			returnedResponseBody = nil
			returnedError = err.(error)
		}
	}()

	byteSlice, err := json.Marshal(body)
	if err != nil {
		return 500, nil, nil, err
	} else {
		var request *http.Request
		if body == nil {
			request, err = http.NewRequest(method, url, nil)
		} else {
			request, err = http.NewRequest(method, url, bytes.NewReader(byteSlice))
			request.Header.Add("Content-Type", "application/json")
		}

		for key, value := range headerMap {
			request.Header.Add(key, value)
		}

		if err != nil {
			return 500, nil, nil, err
		} else {
			response, err := GetInsecureHTTPSClient().Do(request)
			if err != nil {
				return 500, nil, nil, err
			} else {
				defer response.Body.Close()
				if response.ContentLength == 0 {
					return response.StatusCode, nil, nil, nil
				}
				responseBody, err := ioutil.ReadAll(response.Body)
				responseBodyText := string(responseBody)
				if err != nil {
					return 500, nil, &responseBodyText, err
				} else {
					var jsonMapOrJsonSlice interface{}
					if useJsonNumberInsteadFloat64ForResultJson {
						decoder := json.NewDecoder(bytes.NewReader(responseBody))
						decoder.UseNumber()
						err := decoder.Decode(&jsonMapOrJsonSlice)
						if err != nil {
							return response.StatusCode, nil, &responseBodyText, err
						} else {
							return response.StatusCode, jsonMapOrJsonSlice, &responseBodyText, nil
						}
					} else {
						err := json.Unmarshal(responseBody, &jsonMapOrJsonSlice)
						if err != nil {
							return response.StatusCode, nil, &responseBodyText, err
						} else {
							return response.StatusCode, jsonMapOrJsonSlice, &responseBodyText, nil
						}
					}
				}
			}
		}
	}
}

func RequestGet(url string, headerMap map[string]string, useJsonNumberInsteadFloat64ForResultJson bool) (interface{}, error) {
	statusCode, jsonMapOrJsonSlice, responseBody, err := Request("GET", url, nil, headerMap, useJsonNumberInsteadFloat64ForResultJson)
	if err != nil {
		return jsonMapOrJsonSlice, RequestError{url, statusCode, jsonMapOrJsonSlice, responseBody, err}
	} else if statusCode == 200 || statusCode == 204 {
		return jsonMapOrJsonSlice, nil
	} else {
		return jsonMapOrJsonSlice, RequestError{url, statusCode, jsonMapOrJsonSlice, responseBody, nil}
	}
}

func RequestPost(url string, body interface{}, headerMap map[string]string, useJsonNumberInsteadFloat64ForResultJson bool) (interface{}, error) {
	statusCode, jsonMapOrJsonSlice, responseBody, err := Request("POST", url, body, headerMap, useJsonNumberInsteadFloat64ForResultJson)
	if err != nil {
		return jsonMapOrJsonSlice, RequestError{url, statusCode, jsonMapOrJsonSlice, responseBody, err}
	} else if statusCode == 200 || statusCode == 201 || statusCode == 202 {
		return jsonMapOrJsonSlice, nil
	} else {
		return jsonMapOrJsonSlice, RequestError{url, statusCode, jsonMapOrJsonSlice, responseBody, nil}
	}
}

func RequestPut(url string, body interface{}, headerMap map[string]string, useJsonNumberInsteadFloat64ForResultJson bool) (interface{}, error) {
	statusCode, jsonMapOrJsonSlice, responseBody, err := Request("PUT", url, body, headerMap, useJsonNumberInsteadFloat64ForResultJson)
	if err != nil {
		return jsonMapOrJsonSlice, RequestError{url, statusCode, jsonMapOrJsonSlice, responseBody, err}
	} else if statusCode == 200 || statusCode == 202 || statusCode == 204 {
		return jsonMapOrJsonSlice, nil
	} else {
		return jsonMapOrJsonSlice, RequestError{url, statusCode, jsonMapOrJsonSlice, responseBody, nil}
	}
}

func RequestDelete(url string, body interface{}, headerMap map[string]string, useJsonNumberInsteadFloat64ForResultJson bool) (interface{}, error) {
	statusCode, jsonMapOrJsonSlice, responseBody, err := Request("DELETE", url, body, headerMap, useJsonNumberInsteadFloat64ForResultJson)
	if err != nil {
		return jsonMapOrJsonSlice, RequestError{url, statusCode, jsonMapOrJsonSlice, responseBody, err}
	} else if statusCode == 200 || statusCode == 202 || statusCode == 204 {
		return jsonMapOrJsonSlice, nil
	} else {
		return jsonMapOrJsonSlice, RequestError{url, statusCode, jsonMapOrJsonSlice, responseBody, nil}
	}
}

func RequestWithStructure(method string, url string, body interface{}, returnedStructure interface{}, headerMap map[string]string) (returnedStatusCode int, returnedJsonMapOrJsonSlice interface{}, returnedResponseBody *string, returnedError error) {
	defer func() {
		if err := recover(); err != nil {
			returnedStatusCode = 500
			returnedJsonMapOrJsonSlice = nil
			returnedError = err.(error)
			returnedResponseBody = nil
		}
	}()

	byteSlice, err := json.Marshal(body)
	if err != nil {
		return 500, nil, nil, err
	} else {
		request, err := http.NewRequest(method, url, bytes.NewReader(byteSlice))
		request.Header.Add("Content-Type", "application/json")

		for key, value := range headerMap {
			request.Header.Add(key, value)
		}

		if err != nil {
			return 500, nil, nil, err
		} else {
			response, err := GetInsecureHTTPSClient().Do(request)
			if err != nil {
				return 500, nil, nil, err
			} else {
				defer response.Body.Close()
				if response.ContentLength == 0 {
					return response.StatusCode, nil, nil, nil
				}
				responseBody, err := ioutil.ReadAll(response.Body)
				responseBodyText := string(responseBody)
				if err != nil {
					return 500, returnedJsonMapOrJsonSlice, nil, err
				} else {
					var jsonMapOrJsonSlice interface{}
					err := json.Unmarshal(responseBody, &jsonMapOrJsonSlice)
					if err != nil {
						jsonMapOrJsonSlice = nil
					}

					err = json.Unmarshal(responseBody, &returnedStructure)
					if err != nil {
						return response.StatusCode, jsonMapOrJsonSlice, &responseBodyText, err
					} else {
						return response.StatusCode, jsonMapOrJsonSlice, &responseBodyText, nil
					}
				}
			}
		}
	}
}

func RequestGetWithStructure(url string, returnedStrucutre interface{}, headerMap map[string]string) (interface{}, error) {
	statusCode, jsonMapOrJsonSlice, responseBody, err := RequestWithStructure("GET", url, nil, returnedStrucutre, headerMap)
	if err != nil {
		return jsonMapOrJsonSlice, RequestError{url, statusCode, jsonMapOrJsonSlice, responseBody, err}
	} else if statusCode == 200 || statusCode == 204 {
		return jsonMapOrJsonSlice, nil
	} else {
		return jsonMapOrJsonSlice, RequestError{url, statusCode, jsonMapOrJsonSlice, responseBody, nil}
	}
}

func RequestPostWithStructure(url string, body interface{}, returnedStrucutre interface{}, headerMap map[string]string) (interface{}, error) {
	statusCode, jsonMapOrJsonSlice, responseBody, err := RequestWithStructure("POST", url, body, returnedStrucutre, headerMap)
	if err != nil {
		return jsonMapOrJsonSlice, RequestError{url, statusCode, jsonMapOrJsonSlice, responseBody, err}
	} else if statusCode == 200 || statusCode == 201 || statusCode == 202 {
		return jsonMapOrJsonSlice, nil
	} else {
		return jsonMapOrJsonSlice, RequestError{url, statusCode, jsonMapOrJsonSlice, responseBody, nil}
	}
}

func RequestPutWithStructure(url string, body interface{}, returnedStrucutre interface{}, headerMap map[string]string) (interface{}, error) {
	statusCode, jsonMapOrJsonSlice, responseBody, err := RequestWithStructure("PUT", url, body, returnedStrucutre, headerMap)
	if err != nil {
		return jsonMapOrJsonSlice, RequestError{url, statusCode, jsonMapOrJsonSlice, responseBody, err}
	} else if statusCode == 200 || statusCode == 202 || statusCode == 204 {
		return jsonMapOrJsonSlice, nil
	} else {
		return jsonMapOrJsonSlice, RequestError{url, statusCode, jsonMapOrJsonSlice, responseBody, nil}
	}
}

func RequestDeleteWithStructure(url string, body interface{}, returnedStrucutre interface{}, headerMap map[string]string) (interface{}, error) {
	statusCode, jsonMapOrJsonSlice, responseBody, err := RequestWithStructure("DELETE", url, body, returnedStrucutre, headerMap)
	if err != nil {
		return jsonMapOrJsonSlice, RequestError{url, statusCode, jsonMapOrJsonSlice, responseBody, err}
	} else if statusCode == 200 || statusCode == 202 || statusCode == 204 {
		return jsonMapOrJsonSlice, nil
	} else {
		return jsonMapOrJsonSlice, RequestError{url, statusCode, jsonMapOrJsonSlice, responseBody, nil}
	}
}

func RequestByteSliceResult(method string, url string, body map[string]interface{}, headerMap map[string]string) (returnedStatusCode int, returnedByteSlice []byte, returnedError error) {
	defer func() {
		if err := recover(); err != nil {
			returnedStatusCode = 500
			returnedByteSlice = nil
			returnedError = err.(error)
		}
	}()

	byteSlice, err := json.Marshal(body)
	if err != nil {
		return 500, nil, err
	} else {
		request, err := http.NewRequest(method, url, bytes.NewReader(byteSlice))
		request.Header.Add("Content-Type", "application/json")

		for key, value := range headerMap {
			request.Header.Add(key, value)
		}

		if err != nil {
			return 500, nil, err
		} else {
			response, err := GetInsecureHTTPSClient().Do(request)
			if err != nil {
				return 500, nil, err
			} else {
				defer response.Body.Close()
				if response.ContentLength == 0 {
					return response.StatusCode, nil, nil
				}
				responseBody, err := ioutil.ReadAll(response.Body)
				if err != nil {
					return 500, nil, err
				} else {
					return response.StatusCode, responseBody, nil
				}
			}
		}
	}
}

func RequestGetByteSliceResult(url string, headerMap map[string]string) ([]byte, error) {
	statusCode, byteSlice, err := RequestByteSliceResult("GET", url, nil, headerMap)
	text := string(byteSlice)
	if err != nil {
		return byteSlice, RequestError{url, statusCode, byteSlice, &text, err}
	} else if statusCode == 200 || statusCode == 204 {
		return byteSlice, nil
	} else {
		return byteSlice, RequestError{url, statusCode, byteSlice, &text, nil}
	}
}

func RequestPostByteSliceResult(url string, body map[string]interface{}, headerMap map[string]string) ([]byte, error) {
	statusCode, byteSlice, err := RequestByteSliceResult("POST", url, body, headerMap)
	text := string(byteSlice)
	if err != nil {
		return byteSlice, RequestError{url, statusCode, byteSlice, &text, err}
	} else if statusCode == 200 || statusCode == 201 || statusCode == 202 {
		return byteSlice, nil
	} else {
		return byteSlice, RequestError{url, statusCode, byteSlice, &text, nil}
	}
}

func RequestPutByteSliceResult(url string, body map[string]interface{}, headerMap map[string]string) ([]byte, error) {
	statusCode, byteSlice, err := RequestByteSliceResult("PUT", url, body, headerMap)
	text := string(byteSlice)
	if err != nil {
		return byteSlice, RequestError{url, statusCode, byteSlice, &text, err}
	} else if statusCode == 200 || statusCode == 202 || statusCode == 204 {
		return byteSlice, nil
	} else {
		return byteSlice, RequestError{url, statusCode, byteSlice, &text, nil}
	}
}

func RequestDeleteByteSliceResult(url string, body map[string]interface{}, headerMap map[string]string) ([]byte, error) {
	statusCode, byteSlice, err := RequestByteSliceResult("DELETE", url, body, headerMap)
	text := string(byteSlice)
	if err != nil {
		return byteSlice, RequestError{url, statusCode, byteSlice, &text, err}
	} else if statusCode == 200 || statusCode == 202 || statusCode == 204 {
		return byteSlice, nil
	} else {
		return byteSlice, RequestError{url, statusCode, byteSlice, &text, nil}
	}
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Getting Started with Mock — Mock 1.0.1 documentation</title>

    <link rel="stylesheet" href="_static/nature.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="top" title="Mock 1.0.1 documentation" href="index.html" />
    <link rel="next" title="Further Examples" href="examples.html" />
    <link rel="prev" title="Mocking Magic Methods" href="magicmock.html" />

Navigation

          index

          next |

          previous |

Mock 1.0.1 documentation »

Getting Started with Mock¶

Using Mock¶

Mock Patching Methods¶

Common uses for <tt class="xref py py-class docutils literal">Mock</tt> objects include:

Patching methods

Recording method calls on objects

You might want to replace a method on an object to check that
it is called with the correct arguments by another part of the system:

>>> real = SomeClass()
>>> real.method = MagicMock(name='method')
>>> real.method(3, 4, 5, key='value')
<MagicMock name='method()' id='...'>

Once our mock has been used (real.method in this example) it has methods
and attributes that allow you to make assertions about how it has been used.

Note

In most of these examples the <tt class="xref py py-class docutils literal">Mock</tt> and <tt class="xref py py-class docutils literal">MagicMock</tt> classes
are interchangeable. As the MagicMock is the more capable class it makes
a sensible one to use by default.

Once the mock has been called its <tt class="xref py py-attr docutils literal">called</tt> attribute is set to
True. More importantly we can use the <tt class="xref py py-meth docutils literal">assert_called_with()</tt> or
<tt class="xref py py-meth docutils literal">assert_called_once_with()</tt> method to check that it was called with
the correct arguments.

This example tests that calling ProductionClass().method results in a call to
the something method:

>>> from mock import MagicMock
>>> class ProductionClass(object):
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)

Mock for Method Calls on an Object¶

In the last example we patched a method directly on an object to check that it
was called correctly. Another common use case is to pass an object into a
method (or some part of the system under test) and then check that it is used
in the correct way.

The simple ProductionClass below has a closer method. If it is called with
an object then it calls close on it.

>>> class ProductionClass(object):
...     def closer(self, something):
...         something.close()
...

So to test it we need to pass in an object with a close method and check
that it was called correctly.

>>> real = ProductionClass()
>>> mock = Mock()
>>> real.closer(mock)
>>> mock.close.assert_called_with()

We don’t have to do any work to provide the ‘close’ method on our mock.
Accessing close creates it. So, if ‘close’ hasn’t already been called then
accessing it in the test will create it, but <tt class="xref py py-meth docutils literal">assert_called_with()</tt>
will raise a failure exception.

Mocking Classes¶

A common use case is to mock out classes instantiated by your code under test.
When you patch a class, then that class is replaced with a mock. Instances
are created by calling the class. This means you access the “mock instance”
by looking at the return value of the mocked class.

In the example below we have a function some_function that instantiates Foo
and calls a method on it. The call to patch replaces the class Foo with a
mock. The Foo instance is the result of calling the mock, so it is configured
by modifying the mock <tt class="xref py py-attr docutils literal">return_value</tt>.

>>> def some_function():
...     instance = module.Foo()
...     return instance.method()
...
>>> with patch('module.Foo') as mock:
...     instance = mock.return_value
...     instance.method.return_value = 'the result'
...     result = some_function()
...     assert result == 'the result'

Naming your mocks¶

It can be useful to give your mocks a name. The name is shown in the repr of
the mock and can be helpful when the mock appears in test failure messages. The
name is also propagated to attributes or methods of the mock:

>>> mock = MagicMock(name='foo')
>>> mock
<MagicMock name='foo' id='...'>
>>> mock.method
<MagicMock name='foo.method' id='...'>

Tracking all Calls¶

Often you want to track more than a single call to a method. The
<tt class="xref py py-attr docutils literal">mock_calls</tt> attribute records all calls
to child attributes of the mock - and also to their children.

>>> mock = MagicMock()
>>> mock.method()
<MagicMock name='mock.method()' id='...'>
>>> mock.attribute.method(10, x=53)
<MagicMock name='mock.attribute.method()' id='...'>
>>> mock.mock_calls
[call.method(), call.attribute.method(10, x=53)]

If you make an assertion about mock_calls and any unexpected methods
have been called, then the assertion will fail. This is useful because as well
as asserting that the calls you expected have been made, you are also checking
that they were made in the right order and with no additional calls:

You use the <tt class="xref py py-data docutils literal">call</tt> object to construct lists for comparing with
mock_calls:

>>> expected = [call.method(), call.attribute.method(10, x=53)]
>>> mock.mock_calls == expected
True

Setting Return Values and Attributes¶

Setting the return values on a mock object is trivially easy:

>>> mock = Mock()
>>> mock.return_value = 3
>>> mock()
3

Of course you can do the same for methods on the mock:

>>> mock = Mock()
>>> mock.method.return_value = 3
>>> mock.method()
3

The return value can also be set in the constructor:

>>> mock = Mock(return_value=3)
>>> mock()
3

If you need an attribute setting on your mock, just do it:

>>> mock = Mock()
>>> mock.x = 3
>>> mock.x
3

Sometimes you want to mock up a more complex situation, like for example
mock.connection.cursor().execute(“SELECT 1”). If we wanted this call to
return a list, then we have to configure the result of the nested call.

We can use <tt class="xref py py-data docutils literal">call</tt> to construct the set of calls in a “chained call” like
this for easy assertion afterwards:

>>> mock = Mock()
>>> cursor = mock.connection.cursor.return_value
>>> cursor.execute.return_value = ['foo']
>>> mock.connection.cursor().execute("SELECT 1")
['foo']
>>> expected = call.connection.cursor().execute("SELECT 1").call_list()
>>> mock.mock_calls
[call.connection.cursor(), call.connection.cursor().execute('SELECT 1')]
>>> mock.mock_calls == expected
True

It is the call to .call_list() that turns our call object into a list of
calls representing the chained calls.

Raising exceptions with mocks¶

A useful attribute is <tt class="xref py py-attr docutils literal">side_effect</tt>. If you set this to an
exception class or instance then the exception will be raised when the mock
is called.

>>> mock = Mock(side_effect=Exception('Boom!'))
>>> mock()
Traceback (most recent call last):
  ...
Exception: Boom!

Side effect functions and iterables¶

side_effect can also be set to a function or an iterable. The use case for
side_effect as an iterable is where your mock is going to be called several
times, and you want each call to return a different value. When you set
side_effect to an iterable every call to the mock returns the next value
from the iterable:

>>> mock = MagicMock(side_effect=[4, 5, 6])
>>> mock()
4
>>> mock()
5
>>> mock()
6

For more advanced use cases, like dynamically varying the return values
depending on what the mock is called with, side_effect can be a function.
The function will be called with the same arguments as the mock. Whatever the
function returns is what the call returns:

>>> vals = {(1, 2): 1, (2, 3): 2}
>>> def side_effect(*args):
...     return vals[args]
...
>>> mock = MagicMock(side_effect=side_effect)
>>> mock(1, 2)
1
>>> mock(2, 3)
2

Creating a Mock from an Existing Object¶

One problem with over use of mocking is that it couples your tests to the
implementation of your mocks rather than your real code. Suppose you have a
class that implements some_method. In a test for another class, you
provide a mock of this object that also provides some_method. If later
you refactor the first class, so that it no longer has some_method - then
your tests will continue to pass even though your code is now broken!

Mock allows you to provide an object as a specification for the mock,
using the spec keyword argument. Accessing methods / attributes on the
mock that don’t exist on your specification object will immediately raise an
attribute error. If you change the implementation of your specification, then
tests that use that class will start failing immediately without you having to
instantiate the class in those tests.

>>> mock = Mock(spec=SomeClass)
>>> mock.old_method()
Traceback (most recent call last):
   ...
AttributeError: object has no attribute 'old_method'

If you want a stronger form of specification that prevents the setting
of arbitrary attributes as well as the getting of them then you can use
spec_set instead of spec.

Patch Decorators¶

Note

With patch it matters that you patch objects in the namespace where they
are looked up. This is normally straightforward, but for a quick guide
read where to patch.

A common need in tests is to patch a class attribute or a module attribute,
for example patching a builtin or patching a class in a module to test that it
is instantiated. Modules and classes are effectively global, so patching on
them has to be undone after the test or the patch will persist into other
tests and cause hard to diagnose problems.

mock provides three convenient decorators for this: patch, patch.object and
patch.dict. patch takes a single string, of the form
package.module.Class.attribute to specify the attribute you are patching. It
also optionally takes a value that you want the attribute (or class or
whatever) to be replaced with. ‘patch.object’ takes an object and the name of
the attribute you would like patched, plus optionally the value to patch it
with.

patch.object:

>>> original = SomeClass.attribute
>>> @patch.object(SomeClass, 'attribute', sentinel.attribute)
... def test():
...     assert SomeClass.attribute == sentinel.attribute
...
>>> test()
>>> assert SomeClass.attribute == original

>>> @patch('package.module.attribute', sentinel.attribute)
... def test():
...     from package.module import attribute
...     assert attribute is sentinel.attribute
...
>>> test()

If you are patching a module (including __builtin__) then use patch
instead of patch.object:

>>> mock = MagicMock(return_value = sentinel.file_handle)
>>> with patch('__builtin__.open', mock):
...     handle = open('filename', 'r')
...
>>> mock.assert_called_with('filename', 'r')
>>> assert handle == sentinel.file_handle, "incorrect file handle returned"

The module name can be ‘dotted’, in the form package.module if needed:

>>> @patch('package.module.ClassName.attribute', sentinel.attribute)
... def test():
...     from package.module import ClassName
...     assert ClassName.attribute == sentinel.attribute
...
>>> test()

A nice pattern is to actually decorate test methods themselves:

>>> class MyTest(unittest2.TestCase):
...     @patch.object(SomeClass, 'attribute', sentinel.attribute)
...     def test_something(self):
...         self.assertEqual(SomeClass.attribute, sentinel.attribute)
...
>>> original = SomeClass.attribute
>>> MyTest('test_something').test_something()
>>> assert SomeClass.attribute == original

If you want to patch with a Mock, you can use patch with only one argument
(or patch.object with two arguments). The mock will be created for you and
passed into the test function / method:

>>> class MyTest(unittest2.TestCase):
...     @patch.object(SomeClass, 'static_method')
...     def test_something(self, mock_method):
...         SomeClass.static_method()
...         mock_method.assert_called_with()
...
>>> MyTest('test_something').test_something()

You can stack up multiple patch decorators using this pattern:

>>> class MyTest(unittest2.TestCase):
...     @patch('package.module.ClassName1')
...     @patch('package.module.ClassName2')
...     def test_something(self, MockClass2, MockClass1):
...         self.assertTrue(package.module.ClassName1 is MockClass1)
...         self.assertTrue(package.module.ClassName2 is MockClass2)
...
>>> MyTest('test_something').test_something()

When you nest patch decorators the mocks are passed in to the decorated
function in the same order they applied (the normal python order that
decorators are applied). This means from the bottom up, so in the example
above the mock for test_module.ClassName2 is passed in first.

There is also <tt class="xref py py-func docutils literal">patch.dict()</tt> for setting values in a dictionary just
during a scope and restoring the dictionary to its original state when the test
ends:

>>> foo = {'key': 'value'}
>>> original = foo.copy()
>>> with patch.dict(foo, {'newkey': 'newvalue'}, clear=True):
...     assert foo == {'newkey': 'newvalue'}
...
>>> assert foo == original

patch, patch.object and patch.dict can all be used as context managers.

Where you use patch to create a mock for you, you can get a reference to the
mock using the “as” form of the with statement:

>>> class ProductionClass(object):
...     def method(self):
...         pass
...
>>> with patch.object(ProductionClass, 'method') as mock_method:
...     mock_method.return_value = None
...     real = ProductionClass()
...     real.method(1, 2, 3)
...
>>> mock_method.assert_called_with(1, 2, 3)

As an alternative patch, patch.object and patch.dict can be used as
class decorators. When used in this way it is the same as applying the
decorator indvidually to every method whose name starts with “test”.

For some more advanced examples, see the Further Examples page.

Table Of Contents

Getting Started with Mock

Using Mock

Mock Patching Methods

Mock for Method Calls on an Object

Mocking Classes

Naming your mocks

Tracking all Calls

Setting Return Values and Attributes

Raising exceptions with mocks

Side effect functions and iterables

Creating a Mock from an Existing Object

Patch Decorators

Previous topic

Mocking Magic Methods

Next topic

Further Examples

This Page

Show Source

Quick search

    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          next |

          previous |

Mock 1.0.1 documentation »

        © Copyright 2007-2012, Michael Foord & the mock team.
      Last updated on Aug 30, 2013.
      Created using Sphinx 1.2b1.


text:
$(document).ready(function(){
		$('table.offerTable tr').each(function() {
			var input = $(this).find('input.reservedCheckBox:checked');
			if(input.length > 0) {
	      		$(this).addClass('reserved');
			}
		});
		$('table.attractionTable tr').each(function() {
			var input = $(this).find('span.alreadyReserved');
			if(input.length > 0) {
	      		$(this).addClass('reserved');
			}
		});
	});


text:
<?php

// Check phar.readonly ini setting
if (ini_get('phar.readonly') == '1') {
    throw new \RuntimeException("Your php.ini has phar.readonly enabled. Phar cannot be created. Please alter your php.ini first.\n");
}

// You can optionally use arguments to enable compression and whitespace/comment stripping.
// Example: "php buildphar.php -s 1 -c 1"
// -c with a value of 1 enables compression, multiple phars will be created
// -s with a value of 1 enables stripping
$options = getopt('s:c:');
$compress = (isset($options['c']) && $options['c'] == '1');
$strip = (isset($options['s']) && $options['s'] == '1');

$start = microtime(true);

// Create a new Solarium PHAR file.
@unlink('solarium.phar');
$phar = new Phar('solarium.phar', 0, 'solarium.phar');
$phar->setStub(file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . 'stub.php'));
$phar->setSignatureAlgorithm(Phar::SHA1);

// Add files to the PHAR.
$basePath = dirname(__DIR__);
$directoryIterator = new AppendIterator();
$directoryIterator->append(
    new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($basePath . DIRECTORY_SEPARATOR . 'library'),
        RecursiveIteratorIterator::SELF_FIRST
    )
);
$directoryIterator->append(
    new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($basePath . DIRECTORY_SEPARATOR . 'vendor'),
        RecursiveIteratorIterator::SELF_FIRST
    )
);

if ($strip) {
    foreach ($directoryIterator as $file) {
        if (0 !== preg_match('/\\.php$/i', $file)) {
            $phar->addFromString(substr($file, strlen($basePath) + 1), php_strip_whitespace($file));
        }
    }
} else {
    $phar->buildFromIterator($directoryIterator, $basePath);
}

// Create compressed versions
if ($compress) {
    $phar->compress(Phar::BZ2);
    $phar->compress(Phar::GZ);
}

$time = round(microtime(true)-$start, 5);
echo "\nDONE ($time seconds)\nsolarium.phar has been created.\n\n";


text:
namespace Zu.ChromeDevTools.WebAudio
{
    using Newtonsoft.Json;

    /// <summary>
    /// Notifies that AudioNodes are disconnected. The destination can be null, and it means all the outgoing connections from the source are disconnected.
    /// </summary>
    public sealed class NodesDisconnectedEvent : IEvent
    {
        /// <summary>
        /// Gets or sets the contextId
        /// </summary>
        [JsonProperty("contextId")]
        public string ContextId
        {
            get;
            set;
        }
        /// <summary>
        /// Gets or sets the sourceId
        /// </summary>
        [JsonProperty("sourceId")]
        public string SourceId
        {
            get;
            set;
        }
        /// <summary>
        /// Gets or sets the destinationId
        /// </summary>
        [JsonProperty("destinationId")]
        public string DestinationId
        {
            get;
            set;
        }
        /// <summary>
        /// Gets or sets the sourceOutputIndex
        /// </summary>
        [JsonProperty("sourceOutputIndex", DefaultValueHandling = DefaultValueHandling.Ignore)]
        public double? SourceOutputIndex
        {
            get;
            set;
        }
        /// <summary>
        /// Gets or sets the destinationInputIndex
        /// </summary>
        [JsonProperty("destinationInputIndex", DefaultValueHandling = DefaultValueHandling.Ignore)]
        public double? DestinationInputIndex
        {
            get;
            set;
        }
    }
}


text:
/*
  This file is part of libXMLRPC - a C library for xml-encoded function calls.

  Author: Dan Libby (dan@libby.com)
  Epinions.com may be contacted at feedback@epinions-inc.com
*/

/*
  Copyright 2000 Epinions, Inc.

  Subject to the following 3 conditions, Epinions, Inc.  permits you, free
  of charge, to (a) use, copy, distribute, modify, perform and display this
  software and associated documentation files (the "Software"), and (b)
  permit others to whom the Software is furnished to do so as well.

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

  2) THE SOFTWARE IS PROVIDED "AS IS", WITHOUT ANY WARRANTY OR CONDITION OF
  ANY KIND, EXPRESS, IMPLIED OR STATUTORY, INCLUDING WITHOUT LIMITATION ANY
  IMPLIED WARRANTIES OF ACCURACY, MERCHANTABILITY, FITNESS FOR A PARTICULAR
  PURPOSE OR NONINFRINGEMENT.

  3) IN NO EVENT SHALL EPINIONS, INC. BE LIABLE FOR ANY DIRECT, INDIRECT,
  SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES OR LOST PROFITS ARISING OUT
  OF OR IN CONNECTION WITH THE SOFTWARE (HOWEVER ARISING, INCLUDING
  NEGLIGENCE), EVEN IF EPINIONS, INC.  IS AWARE OF THE POSSIBILITY OF SUCH
  DAMAGES.

*/

/* IMPORTANT!
 *
 * only public (official API) things should be in this file. Anything else
 * should go in <group>_private.h, or in the appropriate .c file.
 */

#ifndef __XI_INTROSPECTION_H
/*
 * Avoid include redundancy.
 */
#define __XI_INTROSPECTION_H

/*----------------------------------------------------------------------------
 * xmlrpc_introspection.h
 *
 * Purpose:
 *   define public introspection API
 * Comments:
 */

/*----------------------------------------------------------------------------
 * Constants
 */
 #define xi_token_params "params"
 #define xi_token_returns "returns"
 #define xi_token_related "related"
 #define xi_token_sub "sub"

/*----------------------------------------------------------------------------
 * Includes
 */

/*----------------------------------------------------------------------------
 * Structures
 */

 /****d* VALUE/XMLRPC_IntrospectionCallback
 * NAME
 *   XMLRPC_IntrospectionCallback
 * NOTES
 *   Function prototype for lazy documentation generation (not generated until requested).
 * SOURCE
 */
typedef void (*XMLRPC_IntrospectionCallback)(XMLRPC_SERVER server, void* userData);
/******/

/*----------------------------------------------------------------------------
 * Globals
 */

/*----------------------------------------------------------------------------
 * Functions
 */
XMLRPC_VALUE XMLRPC_IntrospectionCreateDescription(const char* xml, XMLRPC_ERROR error);
int XMLRPC_ServerAddIntrospectionData(XMLRPC_SERVER server, XMLRPC_VALUE desc);
int XMLRPC_ServerRegisterIntrospectionCallback(XMLRPC_SERVER server, XMLRPC_IntrospectionCallback cb);

/*----------------------------------------------------------------------------
 * Macros
 */

#endif /* __XI_INTROSPECTION_H */


text:
#include "slang-ir.h"

namespace Slang
{
    struct IRModule;
    class DiagnosticSink;
    class TargetRequest;

    /// Lower generic and interface-based code to ordinary types and functions using
    /// dynamic dispatch mechanisms.
    void lowerGenerics(
        TargetRequest*          targetReq,
        IRModule*               module,
        DiagnosticSink*         sink);

}


text:
<!DOCTYPE html>

		<meta charset="utf-8">
		<title>MaaS - Meta-as-a-Service | @sanketsaurav</title>
		<meta name="description" content="MaaS - Meta-as-a-Service">
		<meta name="author" content="@sanketsaurav">
		<link rel="stylesheet" href="/static/app.css">

<meta>

as-a-service

Just give me the website's address like this, and I'll give you JSON with all the
			metadata I find:

http://maas.dfth.in/meta/campushash.com

Or you can specify any particular metadata you need:

http://maas.dfth.in/meta/description/campushash.com

			Follow @pizzahackers

Made with ♥ by Sanket at PizzaHackers