text:
'use strict'

const p  = require( 'path' )

const { LazyObject, Symbols } = require( 'lazyref' )

const Errors     = require( './errors' )
const Providers  = require( './providers' )
const Strategies = require( './strategies' )
const Types      = require( './types' )

const {
    getConstructor,
    getExternalCaller
} = require( './helpers' )

exports = module.exports = class Container {
    constructor( providers = [ Providers.CurrentDirectory ] ) {
        this.factoryCache  = new Map
        this.instanceCache = new Map
        this.providers     = [ ]

        this.provide( providers )

        if( process.env.DEBUG ) {
            const timed = require( './performance/timed' )
            this.create = timed( this.create )
        }
    }

    create( id ) {
        const { factoryCache, instanceCache } = this
        const dependencyTree = Array.from( this.getDependencyTree( id ) )

        for( const dep of dependencyTree.reverse( ) ) {
            const { factory, dependencies, type } = factoryCache.get( dep )
            const instances = dependencies.map( d => instanceCache.get( d ) )
            const instance  = instanceCache.get( dep )

            if( instance[ Symbols.constructor ] === LazyObject ) {
                const concrete = this.getInstance( instances, factory, type )
                instance[ Symbols.resolveAs ]( concrete )
            }
        }

        return instanceCache.get( id )
    }

    getDependencyTree( id ) {
        const { factoryCache, instanceCache } = this
        let dependencyTree = [ id ]
        const dependencyTreeIterable = new Set( dependencyTree )

        for( const dep of dependencyTreeIterable ) {
            if( ! factoryCache.has( dep ) ) {
                this.register( dep, this.resolve( dep ) )
            }

            const { dependencies, factory } = factoryCache.get( dep )
            if( this.isNodeModule( dep ) ) {
                instanceCache.set( dep, factory )
                continue
            }

            if( ! instanceCache.has( dep ) ) {
                const constructor = getConstructor( factory )
                instanceCache.set( dep, new LazyObject( constructor ) )
            }

            if( dependencies.length ) {
                const { size } = dependencyTreeIterable
                dependencies.forEach( d => {
                    dependencyTree.push( d )
                    dependencyTreeIterable.add( d )
                    // no size change for the Set => we had a duplicate
                    if( dependencyTreeIterable.size === size ) {
                        console.warn( Errors.CircularDependency( id ) )
                    }
                } )

                dependencyTree = [ ... new Set( dependencyTree.slice( ).reverse( ) ) ].reverse( )
            }
        }

        return dependencyTree
    }

    getFactoryMetadata( factory, strategy = Strategies.Parse ) {
        if( typeof factory === 'function' ) {
            return strategy.getMetadata( factory )
        }
        return { dependencies: [ ], factory, type: Types.Constant }
    }

    getInstance( dependencies, factory, type ) {
        switch( type ) {
            case Types.Constant:
                return factory
            case Types.Constructor:
                return new factory( ... dependencies )
            case Types.Factory:
            case Types.Singleton:
            default:
                return factory( ... dependencies )
        }
    }

    isNodeModule( id ) {
        const { location } = this.factoryCache.get( id )
        return location === id
    }

    load( path ) {
        return require( path )
    }

    provide( providers ) {
        const calleeDir = p.dirname( getExternalCaller( __filename ) )
        this.providers = this.providers.concat(
            [ ]
            .concat( providers )
            .map( provider => {
                if( provider === Providers.NodeModules ) {
                    return provider
                }
                return p.join( calleeDir, provider )
            } )
        )

        return this
    }

    register( id, factory ) {
        let location
        if( typeof factory === 'string' ) {
            location = factory
            factory  = this.load( location )
        }

        const { dependencies, type = Types.Singleton } =
            this.getFactoryMetadata( factory )

        const entry = { dependencies, factory, location, type }
        this.factoryCache.set( id, entry )

        return entry
    }

    resolve( id ) {
        for( const provider of this.providers ) {
            const location = p.join( provider, id )
            try {
                require.resolve( location )
                return location
            } catch( ex ) {
                continue
            }
        }

        throw( new Error( Errors.Resolve( id ) ) )
    }
}

redpajama_set_name: RedPajamaGithub


text:
Ext.define('KitchenSink.model.grid.Office', {
    extend: 'KitchenSink.model.Base',
    fields: ['city', 'totalEmployees', 'manager']
});


text:
<include target="_header.html" />
<form action="./" method="get" onsubmit="return procFilter(this, delete_trackback)" class="context_message">
	<input type="hidden" name="mid" value="{$mid}" />
	<input type="hidden" name="page" value="{$page}" />
	<input type="hidden" name="document_srl" value="{document_srl}" />
	<input type="hidden" name="trackback_srl" value="{$trackback_srl}" />

{$lang->confirm_delete}

		<input type="submit" class="btn" value="{$lang->cmd_delete}" />
		<button type="button" class="btn" onclick="history.back()">{$lang->cmd_cancel}</button>

</form>
<include target="_footer.html" />


text:
import pathlib
import shutil
from unittest import TestCase

import os
import subprocess
import unittest

from wopmars.utils.OptionManager import OptionManager
from wopmars import WopMars
from wopmars.Base import Base
from wopmars.SQLManager import SQLManager
from wopmars.models.Execution import Execution
from wopmars.models.TableModificationTime import TableModificationTime
from wopmars.utils.PathManager import PathManager
from wopmars.utils.various import get_current_time

class TestWopmars(TestCase):

    def setUp(self):
        self.test_path = PathManager.get_test_path()  # Get tests path
        OptionManager.initial_test_setup()  # Set tests arguments
        self.__db_url = OptionManager.instance()["--database"]

        self.__example_def_file1 = os.path.join(self.test_path, "resource/wopfile/example_def_file1.yml")
        self.__example_def_file1_only_database = \
            os.path.join(self.test_path, "resource/wopfile/example_def_file1_only_database.yml")
        self.__example_def_file2_only_files = os.path.join(self.test_path, "resource/wopfile/example_def_file2_only_files.yml")
        self.__example_def_file4 = os.path.join(self.test_path, "resource/wopfile/example_def_file4.yml")
        self.__example_def_file5_never_ready = os.path.join(self.test_path, "resource/wopfile/example_def_file5_never_ready.yml")
        self.__example_def_file_input_not_ready = os.path.join(self.test_path, "resource/wopfile/example_def_file_input_not_ready.yml")

    def tearDown(self):
        SQLManager.instance().get_session().close()
        SQLManager.instance().drop_all()
        shutil.rmtree(os.path.join(self.test_path, "outdir"), ignore_errors=True)
        OptionManager._drop()
        SQLManager._drop()

    def test_run(self):
        cmd_line = ["python", "-D", self.__db_url, "-w", self.__example_def_file1, "-v", "-d", self.test_path]
        with self.assertRaises(SystemExit) as se:
            WopMars().run(cmd_line)
        self.assertTrue(os.path.exists(os.path.join(self.test_path, 'outdir/output_file1.txt')))
        self.assertTrue(os.path.exists(os.path.join(self.test_path, 'outdir/output_file2.txt')))
        self.assertTrue(os.path.exists(os.path.join(self.test_path, 'outdir/output_file7.txt')))
        # self.assertEqual(se.exception.code, 0)

    def test_run_touch(self):

        """This is a tests for the touch function"""

        ################################################################################################################
        #
        # Normal run until rule 2
        #
        ################################################################################################################

        cmd_line = ["python", "-D", self.__db_url, "-w", self.__example_def_file1, "-v", "-d", self.test_path, "-U", "rule2"]
        with self.assertRaises(SystemExit) as se:
            WopMars().run(cmd_line)
        # self.assertTrue(os.path.exists(os.path.join(self.test_path, 'outdir/output_file1.txt')))
        # self.assertEqual(se.exception.code, 0)
        output_file1_mtime = os.path.getmtime(os.path.join(self.test_path, 'outdir/output_file1.txt'))
        foobase_mtime = SQLManager.instance().get_session().query(TableModificationTime)\
            .filter_by(table_name='FooBase').first().mtime_epoch_millis

        ################################################################################################################
        #
        # Dry-run
        #
        ################################################################################################################

        cmd_line = ["python", "-D", self.__db_url, "-w", self.__example_def_file1, "-v",
                    "-d", self.test_path, "-U", "rule2 --dry-run"]
        with self.assertRaises(SystemExit) as se:
            WopMars().run(cmd_line)
        # self.assertTrue(os.path.exists(os.path.join(self.test_path, 'outdir/output_file1.txt')))
        # self.assertEqual(se.exception.code, 0)
        output_file1_mtime_after_dry = os.path.getmtime(os.path.join(self.test_path, 'outdir/output_file1.txt'))
        foobase_mtime_after_dry = SQLManager.instance().get_session().query(TableModificationTime)\
            .filter_by(table_name='FooBase').first().mtime_epoch_millis

        ################################################################################################################
        #
        # Touch output files
        #
        ################################################################################################################

        cmd_line = ["python", "-D", self.__db_url, "-w", self.__example_def_file1, "-v", "-d", self.test_path,
                    "-U", "rule2", "--touch"]
        with self.assertRaises(SystemExit) as se:
            WopMars().run(cmd_line)
        output_file1_mtime_after_touch = os.path.getmtime(os.path.join(self.test_path, 'outdir/output_file1.txt'))
        foobase_mtime_after_touch = SQLManager.instance().get_session().query(TableModificationTime)\
            .filter_by(table_name='FooBase').first().mtime_epoch_millis

        ################################################################################################################
        #
        # Assert that modification times have been updated
        #
        ################################################################################################################

        self.assertEqual(output_file1_mtime, output_file1_mtime_after_dry)
        self.assertEqual(foobase_mtime, foobase_mtime_after_dry)

        self.assertLess(output_file1_mtime, output_file1_mtime_after_touch)
        self.assertLess(foobase_mtime, foobase_mtime_after_touch)

    def test_db_forceall(self):
        """Tests the forceall option in the database. Will carry out different runs in either default or forceall mode
        that will either increase or keep same the number of rows of the FooBase table"""

        pathlib.Path(os.path.join(self.test_path, "outdir/output_file1.txt")).touch()

        ################################################################################################################
        #
        # Run 1: normal mode. Results in 1000 rows
        #
        ################################################################################################################

        cmd_line = ["python", "-D", self.__db_url, "-w", self.__example_def_file1_only_database, "-v",
                    "-d", self.test_path]
        with self.assertRaises(SystemExit) as se:
            WopMars().run(cmd_line)
        foobase_model = Base.metadata.tables['FooBase']
        row_count = SQLManager.instance().get_session().query(foobase_model).count()
        self.assertTrue(row_count == 1000)
        self.assertEqual(se.exception.code, 0)

        ################################################################################################################
        #
        # Run 2: normal mode. Still 1000 rows, because it does not execute
        #
        ################################################################################################################

        cmd_line = ["python", "-D", self.__db_url, "-w", self.__example_def_file1_only_database, "-v",
                    "-d", self.test_path]
        with self.assertRaises(SystemExit) as se:
            WopMars().run(cmd_line)
        row_count = SQLManager.instance().get_session().query(foobase_model).count()
        self.assertTrue(row_count == 1000)
        self.assertEqual(se.exception.code, 0)

        ################################################################################################################
        #
        # Run 3: forceall mode. Now 2000 rows, because it is forced to execute
        #
        ################################################################################################################

        cmd_line = ["python", "-D", self.__db_url, "-w", self.__example_def_file1_only_database, "-v",
                    "-d", self.test_path, "--forceall"]
        with self.assertRaises(SystemExit) as se:
            WopMars().run(cmd_line)
        row_count = SQLManager.instance().get_session().query(foobase_model).count()
        self.assertTrue(row_count == 2000)
        self.assertEqual(se.exception.code, 0)

        ################################################################################################################
        #
        # Run 4: normal mode. Again 2000 rows, because it does not execute
        #
        ################################################################################################################

        cmd_line = ["python", "-D", self.__db_url, "-w", self.__example_def_file1_only_database, "-v",
                    "-d", self.test_path]
        with self.assertRaises(SystemExit) as se:
            WopMars().run(cmd_line)
        row_count = SQLManager.instance().get_session().query(foobase_model).count()
        self.assertTrue(row_count == 2000)
        self.assertEqual(se.exception.code, 0)

    def test_forceall_dryrun(self):
        """This tests carries out a normal a forceall and a dryrun and stores the modification times.
        Then it will tests that the modification time of the two first outputs are different and the
         second and third equal"""
        cmd_line = ["python", "-D", self.__db_url, "-w", self.__example_def_file1, "-v", "-d", self.test_path]
        with self.assertRaises(SystemExit) as se:
            WopMars().run(cmd_line)
        # Test that modification date of first run is different from second forced run
        mtime1 = os.path.getmtime(os.path.join(self.test_path, 'outdir/output_file7.txt'))
        # Run forceall
        cmd_line_force = ["python", "-D", self.__db_url, "-w", self.__example_def_file1, "-v",
                    "-d", self.test_path, "--forceall"]
        with self.assertRaises(SystemExit) as se:
            WopMars().run(cmd_line_force)
        mtime2 = os.path.getmtime(os.path.join(self.test_path, 'outdir/output_file7.txt'))
        # Run dry-run
        cmd_line_dry_run = ["python", "-D", self.__db_url, "-w", self.__example_def_file1, "-v",
                    "-d", self.test_path, "--dry-run"]
        with self.assertRaises(SystemExit) as se:
            WopMars().run(cmd_line_dry_run)
        mtime3 = os.path.getmtime(os.path.join(self.test_path, 'outdir/output_file7.txt'))
        # Assert first two modification times are different
        # Assert second and third modification times same
        self.assertTrue(mtime1 != mtime2)
        self.assertTrue(mtime2 == mtime3)
        self.assertEqual(se.exception.code, 0)

    def test_dry_run(self):
        cmd_line = ["python", "--dry-run", "-D", self.__db_url, "-w", self.__example_def_file1, "-v", "-d",
                    self.test_path]
        with self.assertRaises(SystemExit) as se:
            WopMars().run(cmd_line)
        # The tests is that these files do not exist
        self.assertFalse(os.path.exists(os.path.join(self.test_path, 'outdir/output_file1.txt')))
        self.assertFalse(os.path.exists(os.path.join(self.test_path, 'outdir/output_file2.txt')))
        self.assertFalse(os.path.exists(os.path.join(self.test_path, 'outdir/output_file7.txt')))
        self.assertEqual(se.exception.code, 0)

    def test_run_that_fails(self):
        cmd_line = ["python", "-D", self.__db_url, "-w", self.__example_def_file5_never_ready, "-vv", "-d",
                    self.test_path]
        with self.assertRaises(SystemExit) as se:
            WopMars().run(cmd_line)
        self.assertFalse(os.path.exists(os.path.join(self.test_path, 'resources/never_done.txt')))
        self.assertEqual(se.exception.code, 1)

    def test_run_sourcerule_fail(self):
        cmd_line = ["python", "-D", self.__db_url, "-w", self.__example_def_file1, "-v", "--since", "failure"]
        with self.assertRaises(SystemExit) as se:
            WopMars().run(cmd_line)
        self.assertFalse(os.path.exists(os.path.join(self.test_path, 'outdir/output_file1.txt')))
        self.assertEqual(se.exception.code, 1)

    def test_run_sourcerule_succeed(self):
        p=subprocess.Popen(["touch", os.path.join(self.test_path, "outdir/output_file1.txt")])
        p.wait()
        p=subprocess.Popen(["touch", os.path.join(self.test_path, "outdir/output_file2.txt")])
        p.wait()
        p=subprocess.Popen(["touch", os.path.join(self.test_path, "outdir/output_file3.txt")])
        p.wait()
        p=subprocess.Popen(["touch", os.path.join(self.test_path, "outdir/output_file4.txt")])
        p.wait()
        cmd_line = ["python", "-D", self.__db_url, "-w", self.__example_def_file1, "-d", self.test_path, "-v", "--since", "rule2"]
        with self.assertRaises(SystemExit) as se:
            WopMars().run(cmd_line)
        self.assertEqual(se.exception.code, 0)

    def test_run_skipping_steps_time_check(self):
        cmd_line = ["python", "-D", self.__db_url, "-w", self.__example_def_file2_only_files, "-v"]
        time_unix_ms, time_human = get_current_time()
        start = time_unix_ms
        with self.assertRaises(SystemExit):
           WopMars().run(cmd_line)
        time_unix_ms, time_human = get_current_time()
        end = time_unix_ms
        runtime1 = end - start
        time_unix_ms, time_human = get_current_time()
        start = time_unix_ms
        with self.assertRaises(SystemExit):
           WopMars().run(cmd_line)
        time_unix_ms, time_human = get_current_time()
        end = time_unix_ms
        runtime2 = end - start
        self.assertGreater(runtime1 * 1.5, runtime2)
        # pathlib.Path('outdir/output_file1.txt').unlink()
        PathManager.unlink("outdir/output_file1.txt")

    def test_dry_drun_skipping(self):
        cmd_line = ["python", "-D", self.__db_url, "-w", self.__example_def_file2_only_files, "-v"]
        with self.assertRaises(SystemExit):
           WopMars().run(cmd_line)

        with self.assertRaises(SystemExit):
           WopMars().run(cmd_line + ["-n"])

    def test_dry_drun_skipping_all_but_one(self):
        cmd_line = ["python", "-D", self.__db_url, "-w", self.__example_def_file1, "-v"]
        with self.assertRaises(SystemExit):
           WopMars().run(cmd_line)
        PathManager.unlink("outdir/output_file7.txt")
        with self.assertRaises(SystemExit):
           WopMars().run(cmd_line + ["-n"])

    def test_run_rerun_runtime(self):

        # Slow run
        cmd_line = ["python", "-D", self.__db_url, "-w", self.__example_def_file1, "-v"]
        time_unix_ms, time_human = get_current_time()
        start = time_unix_ms
        with self.assertRaises(SystemExit):
            WopMars().run(cmd_line)
        time_unix_ms, time_human = get_current_time()
        end = time_unix_ms
        runtime1 = end - start

        # Fast run run2<run1
        time_unix_ms, time_human = get_current_time()
        start = time_unix_ms
        with self.assertRaises(SystemExit):
            WopMars().run(cmd_line)
        time_unix_ms, time_human = get_current_time()
        end = time_unix_ms
        runtime2 = end - start
        self.assertGreater(runtime1 * 1.5, runtime2)

        # Middle run: run3>run2
        PathManager.unlink("outdir/output_file1.txt")
        time_unix_ms, time_human = get_current_time()
        start = time_unix_ms
        with self.assertRaises(SystemExit):
            WopMars().run(cmd_line)
        time_unix_ms, time_human = get_current_time()
        end = time_unix_ms
        runtime3 = end - start
        self.assertLess(runtime2, runtime3)

    def get_best_factor(self, full_exec_time, rule_count, maximum_ratio=1):
        average_rule_time = full_exec_time / rule_count
        return 1 + (maximum_ratio * average_rule_time / (1.5 + average_rule_time))

    def test_run_error_in_command_line(self):
        cmd_line = ["python", "-D", self.__db_url, "-w", self.__example_def_file1, "--dot", "/usr/"]
        with self.assertRaises(SystemExit) as SE:
            WopMars().run(cmd_line)
        self.assertEqual(SE.exception.code, 2)

        cmd_line = ["python", "-D", self.__db_url, "-w", self.__example_def_file1, "--not-known"]
        with self.assertRaises(SystemExit) as SE:
            WopMars().run(cmd_line)
        self.assertEqual(SE.exception.code, 2)

    def test_run_packaged_wrappers(self):
        cmd_line = ["python", "-D", self.__db_url, "-w", self.__example_def_file4, "-v", "-d",
                    self.test_path]
        with self.assertRaises(SystemExit) as se:
            WopMars().run(cmd_line)
        self.assertEqual(se.exception.code, 0)

    def test_run_one_tool(self):
        cmd_line = ["python", "tool", "wopmars.tests.resource.wrapper.FooWrapper4",
                  "-i", "{'file': {'input1': 'resource/input_files/input_file1.txt'}}",
                  "-o", "{'file': {'output1': 'outdir/output1.txt'}}", "-D", self.__db_url, "-v", "-d",
                    self.test_path]
        with self.assertRaises(SystemExit) as se:
            WopMars().run(cmd_line)
        self.assertEqual(se.exception.code, 0)

    # AG Do not know why but it is not working
    # def test_core(self):
    #     cmd_line = ["python", "tool", "tests.resource.wrapper.FooWrapperCore",
    #               "-o", "{'table': {'FooBase7': 'tests.resource.model.FooBase7'}}",
    #               "-v", "-D", self.db, "-d", self.test_path]
    #     with self.assertRaises(SystemExit) as se:
    #        WopMars().run(cmd_line)
    #     self.assertEqual(se.exception.code, 0)

    def test_clear_history(self):
        cmd_line = ["python", "-D", self.__db_url, "-w", self.__example_def_file1, "-v",
                    "-d", self.test_path]
        cmd_line_clear_history = ["python", "-D", self.__db_url, "-w", self.__example_def_file1, "-v",
                    "-d", self.test_path, "--cleanup-metadata"]
        with self.assertRaises(SystemExit):
            WopMars().run(cmd_line)
        with self.assertRaises(SystemExit):
            WopMars().run(cmd_line_clear_history)
        session = SQLManager.instance().get_session()
        self.assertEqual(session.query(Execution).count(), 0)

    def test_run_target_rule(self):
        # SQLManager.instance().create_all()
        cmd_line = ["python", "-D", self.__db_url, "-w", self.__example_def_file1, "-v", "--until", "rule3"]
        with self.assertRaises(SystemExit) as se:
           WopMars().run(cmd_line)
        self.assertEqual(se.exception.code, 0)

    def test_run_input_file_not_ready(self):
        # SQLManager.instance().create_all()
        cmd_line = ["python", "-D", self.__db_url, "-w", self.__example_def_file_input_not_ready, "-v"]
        with self.assertRaises(SystemExit) as se:
           WopMars().run(cmd_line)
        self.assertEqual(se.exception.code, 1)

if __name__ == "__main__":
    unittest.main()


text:
<?php defined('BX_DOL') or die('hack attempt');

define('BX_SNIPCART_MODE_TEST', 'test');
define('BX_SNIPCART_MODE_LIVE', 'live');

/**
 * Snipcart module
 */
class BxSnipcartModule extends BxBaseModTextModule
{
    function __construct(&$aModule)
    {
        parent::__construct($aModule);

        $CNF = &$this->_oConfig->CNF;
        $this->_aSearchableNamesExcept = array_merge($this->_aSearchableNamesExcept, array(
             $CNF['FIELD_PRICE'],
             $CNF['FIELD_WEIGHT']
        ));
    }

    public function getSettings($iProfileId = 0)
    {
        if(empty($iProfileId))
            $iProfileId = bx_get_logged_profile_id();

        $aSettings = $this->_oDb->getSettings(array('type' => 'author', 'author' => $iProfileId));
        if(empty($aSettings) || !is_array($aSettings))
            return array();

        return $aSettings;
    }

    /**
     * @page service Service Calls
     * @section bx_snipcart Snipcart
     * @subsection bx_snipcart-other Other
     * @subsubsection bx_snipcart-get_searchable_fields get_searchable_fields
     *
     * @code bx_srv('bx_snipcart', 'get_searchable_fields', [...]); @endcode
     *
     * Get a list of searchable fields. Is used in common search engine.
     *
     * @return an array with a list of searchable fields.
     *
     * @see BxSnipcartModule::serviceGetSearchableFields
     */
    /**
     * @ref bx_snipcart-get_searchable_fields "get_searchable_fields"
     */
    public function serviceGetSearchableFields ()
    {
        $CNF = &$this->_oConfig->CNF;

        $aResult = parent::serviceGetSearchableFields();
        unset($aResult[$CNF['FIELD_PRICE']], $aResult[$CNF['FIELD_WEIGHT']]);

        return $aResult;
    }

    /**
     * @page service Service Calls
     * @section bx_snipcart Snipcart
     * @subsection bx_snipcart-integration Integration
     * @subsubsection bx_snipcart-include_css_js include_css_js
     *
     * @code bx_srv('bx_snipcart', 'include_css_js', [...]); @endcode
     *
     * Get integration code with all necessary CSS and JS includes.
     *
     * @return HTML sting with integration code to display on the site, all necessary CSS and JS files are automatically added to the HEAD section of the site HTML. Empty string is returned if there is no enough input data.
     *
     * @see BxSnipcartModule::serviceIncludeCssJs
     */
    /**
     * @ref bx_snipcart-include_css_js "include_css_js"
     */
    public function serviceIncludeCssJs($iProfileId = 0)
    {
        $iProfileId = !empty($iProfileId) ? $iProfileId : $this->_iProfileId;
        if(empty($iProfileId))
            return '';

        return $this->_oTemplate->getSctInclude($iProfileId);
    }

	/**
     * @page service Service Calls
     * @section bx_snipcart Snipcart
     * @subsection bx_snipcart-page_blocks Page Blocks
     * @subsubsection bx_snipcart-entity_create entity_create
     *
     * @code bx_srv('bx_snipcart', 'entity_create', [...]); @endcode
     *
     * Get page block with product creation form or an error message if something wasn't configured correctly.
     *
     * @param $sDisplay form display name to use
     * @return HTML string with block content to display on the site, all necessary CSS and JS files are automatically added to the HEAD section of the site HTML.
     *
     * @see BxSnipcartModule::serviceEntityCreate
     */
    /**
     * @ref bx_snipcart-entity_create "entity_create"
     */
    public function serviceEntityCreate ($sDisplay = false)
    {
        $CNF = &$this->_oConfig->CNF;

    	$aSettings = $this->_oDb->getSettings(array('type' => 'author', 'author' => $this->_iProfileId));
        if(empty($aSettings) || !is_array($aSettings))
    		return MsgBox(_t('_bx_snipcart_err_not_configured', BX_DOL_URL_ROOT . BxDolPermalinks::getInstance()->permalink($CNF['URL_SETTINGS'])));

    	return parent::serviceEntityCreate($sDisplay);
    }

    /**
     * @page service Service Calls
     * @section bx_snipcart Snipcart
     * @subsection bx_snipcart-page_blocks Page Blocks
     * @subsubsection bx_snipcart-settings settings
     *
     * @code bx_srv('bx_snipcart', 'settings', [...]); @endcode
     *
     * Get page block with configuration settings form.
     *
     * @return an array describing a block to display on the site. All necessary CSS and JS files are automatically added to the HEAD section of the site HTML.
     *
     * @see BxSnipcartModule::serviceSettings
     */
    /**
     * @ref bx_snipcart-settings "settings"
     */
    public function serviceSettings()
    {
        $CNF = &$this->_oConfig->CNF;

        if(!$this->_iProfileId)
            return MsgBox(_t('_Access denied'));

        $oForm = BxDolForm::getObjectInstance($CNF['OBJECT_FORM_SETTINGS'], $CNF['OBJECT_FORM_SETTINGS_DISPLAY_EDIT'], $this->_oTemplate);
        if(!$oForm)
            return MsgBox(_t('_sys_txt_error_occured'));

        $aSettings = $this->_oDb->getSettings(array('type' => 'author', 'author' => $this->_iProfileId));
        $bSettings = !empty($aSettings) && is_array($aSettings);

        $sResultTimer = 0;
        $sResultMessage = '';

        $oForm->initChecker($aSettings);
        if($oForm->isSubmittedAndValid()) {
            if(!$bSettings) {
                if((int)$oForm->insert(array('author' => $this->_iProfileId)) > 0) {
                    $sResultTimer = 3;
                    $sResultMessage = '_bx_snipcart_msg_save_settings';
                }
                else
                    $sResultMessage = '_bx_snipcart_err_save_settings';

            }
            else {
                if($oForm->update($aSettings['id']) !== false) {
                    $sResultTimer = 3;
                    $sResultMessage = '_bx_snipcart_msg_save_settings';
                }
                else
                    $sResultMessage = '_bx_snipcart_err_save_settings';
            }
        }

        return array(
        	'content' => (!empty($sResultMessage) ? MsgBox(_t($sResultMessage), $sResultTimer) : '') . $oForm->getCode()
        );
    }

    protected function _getContentForTimelinePost($aEvent, $aContentInfo, $aBrowseParams = array())
    {
        $aResult = parent::_getContentForTimelinePost($aEvent, $aContentInfo, $aBrowseParams);

        $aResult['raw'] = $this->_oTemplate->getBuyButton($aContentInfo);
        if(isset($aBrowseParams['dynamic_mode']) && (bool)$aBrowseParams['dynamic_mode'] === true)
            $aResult['raw'] .= $this->_oTemplate->addCss(array('timeline.css'), true);

        return $aResult;
    }
}

/** @} */


text:
export default () => {
  const TYPES = {
    String: 'string',
    Function: 'function'
  };

  /**
   *  HTMLElement.remove()
   *  Removes the element from the DOM.
   */
  if (!('remove' in HTMLElement.prototype)) {
    HTMLElement.prototype.remove = function() {
      if (this && this.parentElement
        && Object.prototype.isPrototypeOf.call(HTMLElement.prototype, this.parentElement)) {
        this.parentElement.removeChild(this);
      }
    };
  }

  /**
   * HTMLElement.empty()
   * Removes all children from this element.
   */
  if (!('empty' in HTMLElement.prototype)) {
    HTMLElement.prototype.empty = function() {
      while (this && this.firstChild) {
        this.firstChild.remove();
      }
    };
  }

  /**
   *  HTMLElement.trigger(event)
   *  Triggers an event on the element if the event is supported.
   *  @param {Event | string} event - the event to trigger. Supports both event
   *    name as string, or an Event object.
   */
  if (!('trigger' in HTMLElement.prototype)) {
    HTMLElement.prototype.trigger = function(event) {
      let _event = event;
      if (!(typeof event === TYPES.String
        || Object.prototype.isPrototypeOf.call(Event.prototype, event))) {
        return;
      }

      if (typeof event === TYPES.String) {
        let eventObj;
        if (document.createEvent) {
          try {
            eventObj = new Event(event, {
              bubbles: true,
              cancelable: true
            });
          } catch (e) {
            eventObj = document.createEvent('Event');
            eventObj.initEvent(event, true, true);
          }
        } else {
          eventObj = document.createEventObject();
          eventObj.eventType = event;
        }

        _event = eventObj;
      }

      if (document.createEvent) {
        this.dispatchEvent(_event);
      } else {
        this.fireEvent(`on${event.eventType}`, _event);
      }
    };
  }

  /**
   *  HTMLElement.removeClass(className)
   *  Removes a class from this element.
   *  @param {string} className - the class to remove.
   */
  if (!('removeClass' in HTMLElement.prototype)) {
    HTMLElement.prototype.removeClass = function(className) {
      if (typeof className !== TYPES.String) {
        return;
      }

      const classes = this.className.split(' ');
      const idx = classes.indexOf(className);
      if (idx > -1) {
        classes.splice(idx, 1);
      }

      this.className = classes.join(' ');
    };
  }

  /**
   *  HTMLElement.hasClass(className)
   *  Checks whether this element is assigned the given class.
   *  @param {string} className - the class to check for.
   *  @return {boolean} true if the HTMLElement is assigned the given class, false
   *    otherwise.
   */
  if (!('hasClass' in HTMLElement.prototype)) {
    HTMLElement.prototype.hasClass = function(className) {
      return this.className.indexOf(className) > -1;
    };
  }

  /**
   *  HTMLElement.addClass(className)
   *  Adds the given class to the element.
   *  @param {string} className - the class to add.
   */
  if (!('addClass' in HTMLElement.prototype)) {
    HTMLElement.prototype.addClass = function(className) {
      if (typeof className === TYPES.String) {
        const classNames = className.split(' ');
        for (let i = 0; i < classNames.length; i++) {
          if (!this.hasClass(className)) {
            if (!this.className || this.className.length === 0) {
              this.className = className;
            } else {
              this.className = `${this.className} ${className}`;
            }
          }
        }
      }
    };
  }

  /**
   *  HTMLElement.toggleClass(className)
   *  Either adds or removes the given class from the element, depending on its
   *  presence. If the class is not present, it is added, otherwise removed.
   *  @param {string} className - the class to toggle.
   */
  if (!('toggleClass' in HTMLElement.prototype)) {
    HTMLElement.prototype.toggleClass = function(className) {
      if (!this.hasClass(className)) {
        this.addClass(className);
      } else {
        this.removeClass(className);
      }
    };
  }

  /**
   *  HTMLElement.ancestor([selector])
   *  Returns the elements ancestor. If a selector is supplied, the element's
   *  ancestors are traversed until a matching ancestor is found. If none of
   *  the element's ancestors matches the selector, the element's immediate
   *  ancestor, i.e. parent, is returned. If the element has no ancestors,
   *  e.g. the root node, false is returned.
   *  @param {string} [selector] - a selector to filter ancestors by.
   *  @return {HTMLElement | false}
   */
  if (!('ancestor' in HTMLElement.prototype)) {
    HTMLElement.prototype.ancestor = function(selector) {
      const matchesSelector = this.matches
        || this.webkitMatchesSelector
        || this.mozMatchesSelector
        || this.msMatchesSelector;
      let elem = this.parentElement || false;
      if (!(selector && typeof selector === TYPES.String)) {
        return elem;
      }

      while (elem) {
        if (matchesSelector.bind(elem)(selector)) {
          return elem;
        } else {
          elem = elem.parentElement || false;
        }
      }

      return elem;
    };
  }

  /**
   *  HTMLElement.find(selector)
   *  Searches children matching the given selector.
   *  @param {string} selector - the css selector to search for.
   *  @param {boolean} [recursive] - if true recursively apply find() to
   *    descendants instead of searching only for direct children.
   *  @return {Array}
   */
  if (!('find' in HTMLElement.prototype)) {
    HTMLElement.prototype.find = function(selector, recursive = false) {
      let results = [];
      if (!(selector && typeof selector === TYPES.String)) {
        return results;
      }

      const matchesSelector = this.matches
        || this.webkitMatchesSelector
        || this.mozMatchesSelector
        || this.msMatchesSelector;

      for (let i = 0, elem; i < this.childNodes.length; i++) {
        elem = this.childNodes[i];
        if (elem.nodeType === Node.ELEMENT_NODE) {
          if (matchesSelector.bind(elem)(selector)) {
            results.push(elem);
          }

          if (recursive && elem.childNodes.length > 0) {
            results = results.concat(elem.find(selector, true));
          }
        }
      }

      return results;
    };
  }
};


text:
{% if blogs %}

Ostatnie relacje

	      {% for blog in blogs %}
	        {% include "demo/includes/blog_list_item.html" %}
	      {% endfor %}

{% endif %}


text:
package ua.com.fielden.platform.security.user;

import ua.com.fielden.platform.dao.IEntityDao;

/**
 * Companion object for entity {@link SecurityTokenInfo}.
 *
 * @author TG Team
 *
 */
public interface SecurityTokenInfoCo extends IEntityDao<SecurityTokenInfo> {

}


text:
export const name = 'pub'

export const collection = 'Pubs'


text:
"""
invent a quick version of pytest autouse fixtures as pytest's unacceptably slow
collection/high memory use in pytest 4.6.11, which is the highest version that
works in py2k.

by "too-slow" we mean the test suite can't even manage to be collected for a
single process in less than 70 seconds or so and memory use seems to be very
high as well.   for two or four workers the job just times out after ten
minutes.

so instead we have invented a very limited form of these fixtures, as our
current use of "autouse" fixtures are limited to those in fixtures.py.

assumptions for these fixtures:

1. we are only using "function" or "class" scope

2. the functions must be associated with a test class

3. the fixture functions cannot themselves use pytest fixtures

4. the fixture functions must use yield, not return

When py2k support is removed and we can stay on a modern pytest version, this
can all be removed.

"""
import collections

_py2k_fixture_fn_names = collections.defaultdict(set)
_py2k_class_fixtures = collections.defaultdict(
    lambda: collections.defaultdict(set)
)
_py2k_function_fixtures = collections.defaultdict(
    lambda: collections.defaultdict(set)
)

_py2k_cls_fixture_stack = []
_py2k_fn_fixture_stack = []

def add_fixture(fn, fixture):
    assert fixture.scope in ("class", "function")
    _py2k_fixture_fn_names[fn.__name__].add((fn, fixture.scope))

def scan_for_fixtures_to_use_for_class(item):
    test_class = item.parent.parent.obj

    for name in _py2k_fixture_fn_names:
        for fixture_fn, scope in _py2k_fixture_fn_names[name]:
            meth = getattr(test_class, name, None)
            if meth and meth.im_func is fixture_fn:
                for sup in test_class.__mro__:
                    if name in sup.__dict__:
                        if scope == "class":
                            _py2k_class_fixtures[test_class][sup].add(meth)
                        elif scope == "function":
                            _py2k_function_fixtures[test_class][sup].add(meth)
                        break
                break

def run_class_fixture_setup(request):

    cls = request.cls
    self = cls.__new__(cls)

    fixtures_for_this_class = _py2k_class_fixtures.get(cls)

    if fixtures_for_this_class:
        for sup_ in cls.__mro__:
            for fn in fixtures_for_this_class.get(sup_, ()):
                iter_ = fn(self)
                next(iter_)

                _py2k_cls_fixture_stack.append(iter_)

def run_class_fixture_teardown(request):
    while _py2k_cls_fixture_stack:
        iter_ = _py2k_cls_fixture_stack.pop(-1)
        try:
            next(iter_)
        except StopIteration:
            pass

def run_fn_fixture_setup(request):
    cls = request.cls
    self = request.instance

    fixtures_for_this_class = _py2k_function_fixtures.get(cls)

    if fixtures_for_this_class:
        for sup_ in reversed(cls.__mro__):
            for fn in fixtures_for_this_class.get(sup_, ()):
                iter_ = fn(self)
                next(iter_)

                _py2k_fn_fixture_stack.append(iter_)

def run_fn_fixture_teardown(request):
    while _py2k_fn_fixture_stack:
        iter_ = _py2k_fn_fixture_stack.pop(-1)
        try:
            next(iter_)
        except StopIteration:
            pass


text:
golang-websocket
================

Golang WebSocket chat sample


text:
"use strict";

import { characters } from "necessary";

import { EMPTY_STRING } from "../constants";

const { SPACE_CHARACTER } = characters;

export function paddingFromPaddingLength(paddingLength) {
  let padding = EMPTY_STRING;

  for (let position = 0; position < paddingLength; position++) {
    padding += SPACE_CHARACTER;
  }

  return padding;
}


text:
/**
 * UI.IconList Designer
 * @supperClass UI.ThumList_Designer
 */
UI.IconList_Designer = function(control) {
    arguments.callee.superClass.constructor.apply(this, arguments);
};

extend(UI.IconList_Designer, UI.ThumbList_Designer, {
   /* defaultWidth: 295,*/
   /* defaultHeight: 125*/
});

UI.IconList_Designer.prototype.meta = UI.extendMeta(UI.IconList_Designer.prototype.meta, {
    type: "UI.IconList",
    props: { },
    events: { },
    methods: {
        _getDetail: {alias: "getDetail", params: [], output: true},
        _setDetail: {alias: "setDetail", params: [
            {name: "detail", alias: "text"}
        ]},
        _updateDetail: {alias: "updateDetail", params: [
            {name: "myindex", alias: "序列号(index)"},
            {name: "mytext", alias: "detail"}
        ]},
        _getSubText: {alias: "getSubTitle", showable: false, params: [], output: true},
        _setSubText: {alias: "setSubTitle", showable: false, params: [
            {name: "subText", alias: "text"}
        ]},
        _updateSubText: {alias: "updateSubTitle", showable: false, params: [
            {name: "myindex", alias: "序列号(index)"},
            {name: "mytext", alias: "subText"}
        ]}
    },

    dataFormat: [{"imgUrl":"","name":"","url":"","detail":""}],

    defaultProperty: "",
    defaultEvent: "",
    defaultMethod: ""

});

UI.IconList.prototype.designerType = "UI.IconList_Designer";
MetaHub.register(UI.IconList_Designer.prototype.meta);


text:
layout: default
---

    {{ content }}


text:
Since symbolic execution explores all paths through a program,
the results of symbolically executing a program have an inherent tree
structure. Each point at which the execution branches defines a node
of the tree (that's why we call it "branching"), and the results
define the leaves. We call this tree a trace.

Our evaluator initially just returned a list of values and their
associated path constraints. In order to reconstruct the trace, we
needed to accumulate some more information during evaluation.

One approach would have been to restructure the evaluator to construct
and return the entire tree. However, this would be an invasive change
and prone to error.

Instead, we chose to simply accumulate a linear trace for each
result---a list of the branch points encountered on the path to the
result, along with a record of the decision made at each branch point.
After accumulating a linear trace for each result, we were able to
merge all of the linear traces together to create the tree trace with
a simple structurally recursive algorithm.

One potential issue with this strategy is that the branch points are
not unique. For instance, a recursive procedure application or a
simple loop might repeatedly lead to the same branch point. However,
the *sequence* of branch points encountered will be unique for each
path through the program, so we are safe. From this perspective,
constructing the tree trace from the linear traces is much like
constructing a prefix tree from a set of strings.

We then tried outputting these tree traces with regular printing, but
the trees were so large that the format quickly became unreadable.
Instead, we decided to print out the traces in DOT format (a format
for describing graphs) and then visualize them using Graphviz.


text:
'use strict';

/**
 * @summary Specifies details of a Job Manager Task.
  *
 * The Job Manager Task is automatically started when the Job is created. The
 * Batch service tries to schedule the Job Manager Task before any other Tasks
 * in the Job. When shrinking a Pool, the Batch service tries to preserve Nodes
 * where Job Manager Tasks are running for as long as possible (that is,
 * Compute Nodes running 'normal' Tasks are removed before Compute Nodes
 * running Job Manager Tasks). When a Job Manager Task fails and needs to be
 * restarted, the system tries to schedule it at the highest priority. If there
 * are no idle Compute Nodes available, the system may terminate one of the
 * running Tasks in the Pool and return it to the queue in order to make room
 * for the Job Manager Task to restart. Note that a Job Manager Task in one Job
 * does not have priority over Tasks in other Jobs. Across Jobs, only Job level
 * priorities are observed. For example, if a Job Manager in a priority 0 Job
 * needs to be restarted, it will not displace Tasks of a priority 1 Job. Batch
 * will retry Tasks when a recovery operation is triggered on a Node. Examples
 * of recovery operations include (but are not limited to) when an unhealthy
 * Node is rebooted or a Compute Node disappeared due to host failure. Retries
 * due to recovery operations are independent of and are not counted against
 * the maxTaskRetryCount. Even if the maxTaskRetryCount is 0, an internal retry
 * due to a recovery operation may occur. Because of this, all Tasks should be
 * idempotent. This means Tasks need to tolerate being interrupted and
 * restarted without causing any corruption or duplicate data. The best
 * practice for long running Tasks is to use some form of checkpointing.
 *
 */
class JobManagerTask {
  /**
   * Create a JobManagerTask.
   * @property {string} id A string that uniquely identifies the Job Manager
   * Task within the Job. The ID can contain any combination of alphanumeric
   * characters including hyphens and underscores and cannot contain more than
   * 64 characters.
   * @property {string} [displayName] The display name of the Job Manager Task.
   * It need not be unique and can contain any Unicode characters up to a
   * maximum length of 1024.
   * @property {string} commandLine The command line of the Job Manager Task.
   * The command line does not run under a shell, and therefore cannot take
   * advantage of shell features such as environment variable expansion. If you
   * want to take advantage of such features, you should invoke the shell in
   * the command line, for example using "cmd /c MyCommand" in Windows or
   * "/bin/sh -c MyCommand" in Linux. If the command line refers to file paths,
   * it should use a relative path (relative to the Task working directory), or
   * use the Batch provided environment variable
   * (https://docs.microsoft.com/en-us/azure/batch/batch-compute-node-environment-variables).
   * @property {object} [containerSettings] The settings for the container
   * under which the Job Manager Task runs. If the Pool that will run this Task
   * has containerConfiguration set, this must be set as well. If the Pool that
   * will run this Task doesn't have containerConfiguration set, this must not
   * be set. When this is specified, all directories recursively below the
   * AZ_BATCH_NODE_ROOT_DIR (the root of Azure Batch directories on the node)
   * are mapped into the container, all Task environment variables are mapped
   * into the container, and the Task command line is executed in the
   * container. Files produced in the container outside of
   * AZ_BATCH_NODE_ROOT_DIR might not be reflected to the host disk, meaning
   * that Batch file APIs will not be able to access those files.
   * @property {string} [containerSettings.containerRunOptions] These
   * additional options are supplied as arguments to the "docker create"
   * command, in addition to those controlled by the Batch Service.
   * @property {string} [containerSettings.imageName] This is the full Image
   * reference, as would be specified to "docker pull". If no tag is provided
   * as part of the Image name, the tag ":latest" is used as a default.
   * @property {object} [containerSettings.registry] This setting can be
   * omitted if was already provided at Pool creation.
   * @property {string} [containerSettings.registry.registryServer] If omitted,
   * the default is "docker.io".
   * @property {string} [containerSettings.registry.userName]
   * @property {string} [containerSettings.registry.password]
   * @property {string} [containerSettings.workingDirectory] The default is
   * 'taskWorkingDirectory'. Possible values include: 'taskWorkingDirectory',
   * 'containerImageDefault'
   * @property {array} [resourceFiles] A list of files that the Batch service
   * will download to the Compute Node before running the command line. Files
   * listed under this element are located in the Task's working directory.
   * There is a maximum size for the list of resource files.  When the max size
   * is exceeded, the request will fail and the response error code will be
   * RequestEntityTooLarge. If this occurs, the collection of ResourceFiles
   * must be reduced in size. This can be achieved using .zip files,
   * Application Packages, or Docker Containers.
   * @property {array} [outputFiles] A list of files that the Batch service
   * will upload from the Compute Node after running the command line. For
   * multi-instance Tasks, the files will only be uploaded from the Compute
   * Node on which the primary Task is executed.
   * @property {array} [environmentSettings] A list of environment variable
   * settings for the Job Manager Task.
   * @property {object} [constraints] Constraints that apply to the Job Manager
   * Task.
   * @property {moment.duration} [constraints.maxWallClockTime] If this is not
   * specified, there is no time limit on how long the Task may run.
   * @property {moment.duration} [constraints.retentionTime] The default is 7
   * days, i.e. the Task directory will be retained for 7 days unless the
   * Compute Node is removed or the Job is deleted.
   * @property {number} [constraints.maxTaskRetryCount] Note that this value
   * specifically controls the number of retries for the Task executable due to
   * a nonzero exit code. The Batch service will try the Task once, and may
   * then retry up to this limit. For example, if the maximum retry count is 3,
   * Batch tries the Task up to 4 times (one initial try and 3 retries). If the
   * maximum retry count is 0, the Batch service does not retry the Task after
   * the first attempt. If the maximum retry count is -1, the Batch service
   * retries the Task without limit.
   * @property {number} [requiredSlots] The number of scheduling slots that the
   * Task requires to run. The default is 1. A Task can only be scheduled to
   * run on a compute node if the node has enough free scheduling slots
   * available. For multi-instance Tasks, this must be 1.
   * @property {boolean} [killJobOnCompletion] Whether completion of the Job
   * Manager Task signifies completion of the entire Job. If true, when the Job
   * Manager Task completes, the Batch service marks the Job as complete. If
   * any Tasks are still running at this time (other than Job Release), those
   * Tasks are terminated. If false, the completion of the Job Manager Task
   * does not affect the Job status. In this case, you should either use the
   * onAllTasksComplete attribute to terminate the Job, or have a client or
   * user terminate the Job explicitly. An example of this is if the Job
   * Manager creates a set of Tasks but then takes no further role in their
   * execution. The default value is true. If you are using the
   * onAllTasksComplete and onTaskFailure attributes to control Job lifetime,
   * and using the Job Manager Task only to create the Tasks for the Job (not
   * to monitor progress), then it is important to set killJobOnCompletion to
   * false.
   * @property {object} [userIdentity] The user identity under which the Job
   * Manager Task runs. If omitted, the Task runs as a non-administrative user
   * unique to the Task.
   * @property {string} [userIdentity.userName] The userName and autoUser
   * properties are mutually exclusive; you must specify one but not both.
   * @property {object} [userIdentity.autoUser] The userName and autoUser
   * properties are mutually exclusive; you must specify one but not both.
   * @property {string} [userIdentity.autoUser.scope] The default value is
   * pool. If the pool is running Windows a value of Task should be specified
   * if stricter isolation between tasks is required. For example, if the task
   * mutates the registry in a way which could impact other tasks, or if
   * certificates have been specified on the pool which should not be
   * accessible by normal tasks but should be accessible by StartTasks.
   * Possible values include: 'task', 'pool'
   * @property {string} [userIdentity.autoUser.elevationLevel] The default
   * value is nonAdmin. Possible values include: 'nonAdmin', 'admin'
   * @property {boolean} [runExclusive] Whether the Job Manager Task requires
   * exclusive use of the Compute Node where it runs. If true, no other Tasks
   * will run on the same Node for as long as the Job Manager is running. If
   * false, other Tasks can run simultaneously with the Job Manager on a
   * Compute Node. The Job Manager Task counts normally against the Compute
   * Node's concurrent Task limit, so this is only relevant if the Compute Node
   * allows multiple concurrent Tasks. The default value is true.
   * @property {array} [applicationPackageReferences] A list of Application
   * Packages that the Batch service will deploy to the Compute Node before
   * running the command line. Application Packages are downloaded and deployed
   * to a shared directory, not the Task working directory. Therefore, if a
   * referenced Application Package is already on the Compute Node, and is up
   * to date, then it is not re-downloaded; the existing copy on the Compute
   * Node is used. If a referenced Application Package cannot be installed, for
   * example because the package has been deleted or because download failed,
   * the Task fails.
   * @property {object} [authenticationTokenSettings] The settings for an
   * authentication token that the Task can use to perform Batch service
   * operations. If this property is set, the Batch service provides the Task
   * with an authentication token which can be used to authenticate Batch
   * service operations without requiring an Account access key. The token is
   * provided via the AZ_BATCH_AUTHENTICATION_TOKEN environment variable. The
   * operations that the Task can carry out using the token depend on the
   * settings. For example, a Task can request Job permissions in order to add
   * other Tasks to the Job, or check the status of the Job or of other Tasks
   * under the Job.
   * @property {array} [authenticationTokenSettings.access] The authentication
   * token grants access to a limited set of Batch service operations.
   * Currently the only supported value for the access property is 'job', which
   * grants access to all operations related to the Job which contains the
   * Task.
   * @property {boolean} [allowLowPriorityNode] Whether the Job Manager Task
   * may run on a low-priority Compute Node. The default value is true.
   */
  constructor() {
  }

  /**
   * Defines the metadata of JobManagerTask
   *
   * @returns {object} metadata of JobManagerTask
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'JobManagerTask',
      type: {
        name: 'Composite',
        className: 'JobManagerTask',
        modelProperties: {
          id: {
            required: true,
            serializedName: 'id',
            type: {
              name: 'String'
            }
          },
          displayName: {
            required: false,
            serializedName: 'displayName',
            type: {
              name: 'String'
            }
          },
          commandLine: {
            required: true,
            serializedName: 'commandLine',
            type: {
              name: 'String'
            }
          },
          containerSettings: {
            required: false,
            serializedName: 'containerSettings',
            type: {
              name: 'Composite',
              className: 'TaskContainerSettings'
            }
          },
          resourceFiles: {
            required: false,
            serializedName: 'resourceFiles',
            type: {
              name: 'Sequence',
              element: {
                  required: false,
                  serializedName: 'ResourceFileElementType',
                  type: {
                    name: 'Composite',
                    className: 'ResourceFile'
                  }
              }
            }
          },
          outputFiles: {
            required: false,
            serializedName: 'outputFiles',
            type: {
              name: 'Sequence',
              element: {
                  required: false,
                  serializedName: 'OutputFileElementType',
                  type: {
                    name: 'Composite',
                    className: 'OutputFile'
                  }
              }
            }
          },
          environmentSettings: {
            required: false,
            serializedName: 'environmentSettings',
            type: {
              name: 'Sequence',
              element: {
                  required: false,
                  serializedName: 'EnvironmentSettingElementType',
                  type: {
                    name: 'Composite',
                    className: 'EnvironmentSetting'
                  }
              }
            }
          },
          constraints: {
            required: false,
            serializedName: 'constraints',
            type: {
              name: 'Composite',
              className: 'TaskConstraints'
            }
          },
          requiredSlots: {
            required: false,
            serializedName: 'requiredSlots',
            type: {
              name: 'Number'
            }
          },
          killJobOnCompletion: {
            required: false,
            serializedName: 'killJobOnCompletion',
            type: {
              name: 'Boolean'
            }
          },
          userIdentity: {
            required: false,
            serializedName: 'userIdentity',
            type: {
              name: 'Composite',
              className: 'UserIdentity'
            }
          },
          runExclusive: {
            required: false,
            serializedName: 'runExclusive',
            type: {
              name: 'Boolean'
            }
          },
          applicationPackageReferences: {
            required: false,
            serializedName: 'applicationPackageReferences',
            type: {
              name: 'Sequence',
              element: {
                  required: false,
                  serializedName: 'ApplicationPackageReferenceElementType',
                  type: {
                    name: 'Composite',
                    className: 'ApplicationPackageReference'
                  }
              }
            }
          },
          authenticationTokenSettings: {
            required: false,
            serializedName: 'authenticationTokenSettings',
            type: {
              name: 'Composite',
              className: 'AuthenticationTokenSettings'
            }
          },
          allowLowPriorityNode: {
            required: false,
            serializedName: 'allowLowPriorityNode',
            type: {
              name: 'Boolean'
            }
          }
        }
      }
    };
  }
}

module.exports = JobManagerTask;


text:
package com.androidhuman.circlerefreshlayout.sample;

import com.androidhuman.circlerefreshlayout.SwipeRefreshLayout;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

public class RefreshLayoutActivity extends AppCompatActivity
        implements SwipeRefreshLayout.OnRefreshListener {

    public static final String KEY_TITLE = "title";

    public static final String KEY_REFRESH_DRAWABLE_STYLE = "refresh_drawable_style";

    public static final String KEY_PULL_POSITION = "pull_position";

    SwipeRefreshLayout swlRefresh;

    RecyclerView rlList;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_refreshlayout);

        String title = getIntent().getStringExtra(KEY_TITLE);
        if (null != title) {
            setTitle(title);
        }

        swlRefresh = (SwipeRefreshLayout) findViewById(R.id.srl_activity_refreshlayout_refresh);
        rlList = (RecyclerView) findViewById(R.id.rv_list);

        setupSwipeRefreshLayout(swlRefresh, getIntent().getExtras());

        rlList.setLayoutManager(new LinearLayoutManager(this));
        rlList.setAdapter(new ItemAdapter());
    }

    private void setupSwipeRefreshLayout(SwipeRefreshLayout view, @Nullable Bundle extras) {
        view.setColorSchemeResources(R.color.colorAccent);
        view.setOnRefreshListener(this);

        if (null == extras) {
            return;
        }

        @SwipeRefreshLayout.RefreshDrawableStyle
        int style = extras.getInt(KEY_REFRESH_DRAWABLE_STYLE, SwipeRefreshLayout.CIRCLE);
        view.setRefreshDrawableStyle(style);

        @SwipeRefreshLayout.PullPosition
        int position = extras.getInt(KEY_PULL_POSITION, Gravity.TOP);
        view.setPullPosition(position);
    }

    @Override
    public void onRefresh() {
        Toast.makeText(getApplicationContext(), "Refreshing...", Toast.LENGTH_SHORT).show();
    }

    class ItemAdapter extends RecyclerView.Adapter<ItemHolder> {

        @Override
        public ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new ItemHolder(parent);
        }

        @Override
        public void onBindViewHolder(ItemHolder holder, int position) {
            holder.text.setText("Item " + position);
        }

        @Override
        public int getItemCount() {
            return 30;
        }
    }

    class ItemHolder extends RecyclerView.ViewHolder {

        public TextView text;

        public ItemHolder(ViewGroup parent) {
            super(LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_simple, parent, false));
            text = (TextView) itemView.findViewById(R.id.tv_item_simple);
        }
    }
}


text:
using strange.extensions.command.api;
using strange.extensions.injector.api;
using strange.extensions.mediation.api;
using UnityEngine;

public class ChatServerManager : StrangePackage
{
    public override void MapBindings(ICommandBinder commandBinder, ICrossContextInjectionBinder injectionBinder,
        IMediationBinder mediationBinder)
    {
        //Bind chatServerData Object
        var chatServerData = Object.FindObjectOfType<ChatServerData>();
        injectionBinder.Bind<ChatServerData>().To(chatServerData).ToSingleton().CrossContext();

        //Bind Mediators to Views
        mediationBinder.Bind<ChatServerListenerView>().To<ChatServerListener>();

        commandBinder.Bind<CreateChannelSignal>().To<CreateChannelCommand>();
        commandBinder.Bind<JoinChannelSignal>().To<JoinChannelCommand>();
        commandBinder.Bind<LeaveChannelSignal>().To<LeaveChannelCommand>();
        commandBinder.Bind<SendMessageSignal>().To<SendMessageCommand>();
        commandBinder.Bind<SendJoinedReponseSignal>().To<SendJoinedReponseCommand>();
        commandBinder.Bind<SendCreateChannelReponseSignal>().To<SendCreateChannelReponseCommand>();
    }

    public override void PostBindings(ICommandBinder commandBinder, ICrossContextInjectionBinder injectionBinder,
        IMediationBinder mediationBinder)
    {

    }
}


text:
export IDENT_STRING=$USER

# Where log files are stored.  /var/log by default.
export LOG_DIR=/tmp/tephra-$IDENT_STRING

# The directory where pid files are stored. /var/run by default.
export PID_DIR=/tmp

# Add any extra classes to the classpath
# export EXTRA_CLASSPATH

# Set the JVM heap size
# export JAVA_HEAPMAX=-Xmx2048m

# Additional runtime options
#
# GC logging options.
# Uncomment the following two lines, making any desired changes, to enable GC logging output
# export GC_LOG_OPTS="-verbose:gc -XX:+PrintGCDetails -XX:+PrintGCDateStamps -Xloggc:server-gc.log -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=2 -XX:GCLogFileSize=50M"
# export OPTS="$OPTS $GC_LOG_OPTS"
#
# JMX options.
# Uncomment the following two lines, making any desired changes, to enable remote JMX connectivity
# export JMX_OPTS="-Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.port=13001"
# export OPTS="$OPTS $JMX_OPTS"

# Extra Java runtime options.
# Below are what we set by default.  May only work with SUN JVM.
# For more on why as well as other possible settings,
# see http://wiki.apache.org/hadoop/PerformanceTuning
export OPTS="$OPTS -XX:+UseConcMarkSweepGC"


text:
// Copyright 2011-2016 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.Module;

import com.google.common.base.Preconditions;
import com.google.security.zynamics.binnavi.CMain;
import com.google.security.zynamics.binnavi.Database.Interfaces.IDatabase;
import com.google.security.zynamics.binnavi.Gui.MainWindow.Implementations.CModuleFunctions;
import com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.CAbstractLazyComponent;
import com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.CAbstractNodeComponent;
import com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.CProjectTreeNode;
import com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.Module.Component.CModuleNodeComponent;
import com.google.security.zynamics.binnavi.disassembly.CProjectContainer;
import com.google.security.zynamics.binnavi.disassembly.INaviAddressSpace;
import com.google.security.zynamics.binnavi.disassembly.INaviModule;
import com.google.security.zynamics.binnavi.disassembly.Modules.CModuleContainer;
import com.google.security.zynamics.binnavi.disassembly.Modules.CModuleListenerAdapter;
import com.google.security.zynamics.binnavi.disassembly.views.INaviView;
import com.google.security.zynamics.binnavi.disassembly.views.IViewContainer;
import com.google.security.zynamics.zylib.gui.SwingInvoker;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;

/**
 * Represents module nodes in the project tree.
 */
public final class CModuleNode extends CProjectTreeNode<INaviModule> {
  /**
   * Used for serialization.
   */
  private static final long serialVersionUID = -5643276356053733957L;

  /**
   * Icon used for loaded modules in the project tree.
   */
  private static final ImageIcon ICON_MODULE =
      new ImageIcon(CMain.class.getResource("data/projecttreeicons/project_module.png"));

  /**
   * Icon used for unloaded modules in the project tree.
   */
  private static final ImageIcon ICON_MODULE_GRAY =
      new ImageIcon(CMain.class.getResource("data/projecttreeicons/project_module_gray.png"));

  /**
   * Icon used for incomplete modules in the project tree.
   */
  private static final ImageIcon ICON_MODULE_BROKEN =
      new ImageIcon(CMain.class.getResource("data/projecttreeicons/project_module_broken.png"));

  /**
   * Icon used for not yet converted modules in the project tree.
   */
  private static final ImageIcon ICON_MODULE_UNCONVERTED =
      new ImageIcon(CMain.class.getResource("data/projecttreeicons/project_module_light_gray.png"));

  /**
   * The module described by the node.
   */
  private final INaviModule m_module;

  /**
   * Context in which views of the represented module are opened.
   */
  private final IViewContainer m_contextContainer;

  /**
   * Updates the node on important changes in the represented module.
   */
  private final InternalModuleListener m_listener;

  /**
   * Constructor for modules inside projects.
   *
   * @param projectTree Project tree of the main window.
   * @param parentNode Parent node of this node.
   * @param database Database the module belongs to.
   * @param addressSpace The address space the module belongs to.
   * @param module Module represented by this node.
   * @param contextContainer The container in whose context the views are opened.
   */
  public CModuleNode(final JTree projectTree,
      final DefaultMutableTreeNode parentNode,
      final IDatabase database,
      final INaviAddressSpace addressSpace,
      final INaviModule module,
      final CProjectContainer contextContainer) {
    super(projectTree, new CAbstractLazyComponent() {
      @Override
      protected CAbstractNodeComponent createComponent() {
        return new CModuleNodeComponent(projectTree, database, addressSpace, module,
            contextContainer);
      }
    }, new CModuleNodeMenuBuilder(projectTree,
        parentNode,
        database,
        addressSpace,
        new INaviModule[] {module},
        null), module);

    Preconditions.checkNotNull(database, "IE01972: Database argument can't be null");
    Preconditions.checkNotNull(addressSpace, "IE01973: Address space can't be null");
    m_module = Preconditions.checkNotNull(module, "IE01974: Module can't be null");

    m_contextContainer = contextContainer;

    createChildren();

    m_listener = new InternalModuleListener();
    m_module.addListener(m_listener);
  }

  /**
   * Constructor for modules outside projects.
   *
   * @param projectTree Project tree of the main window.
   * @param parentNode Parent node of this node.
   * @param database Database the module belongs to.
   * @param module Module represented by this node.
   * @param contextContainer The container in whose context the views are opened.
   */
  public CModuleNode(final JTree projectTree, final DefaultMutableTreeNode parentNode,
      final IDatabase database, final INaviModule module, final CModuleContainer contextContainer) {
    super(projectTree, new CAbstractLazyComponent() {
      @Override
      protected CAbstractNodeComponent createComponent() {
        return new CModuleNodeComponent(projectTree, database, null, module, contextContainer);
      }
    }, new CModuleNodeMenuBuilder(projectTree,
        parentNode,
        database,
        null,
        new INaviModule[] {module},
        null), module);

    Preconditions.checkNotNull(database, "IE01970: Database can't be null");

    m_module = Preconditions.checkNotNull(module, "IE01971: Module can't be null");
    m_contextContainer = contextContainer;

    createChildren();

    m_listener = new InternalModuleListener();
    m_module.addListener(m_listener);
  }

  /**
   * Creates the child nodes of the module node. One node is added for the native Call graph of the
   * module, another node is added that contains all native Flow graph views of the module.
   */
  @Override
  protected void createChildren() {}

  @Override
  public void dispose() {
    super.dispose();

    m_contextContainer.dispose();
    m_module.removeListener(m_listener);

    deleteChildren();
  }

  @Override
  public void doubleClicked() {
    if (m_module.getConfiguration().getRawModule().isComplete() && !m_module.isLoaded()) {
      CModuleFunctions.loadModules(getProjectTree(), new INaviModule[] {m_module});
    }
  }

  @Override
  public CModuleNodeComponent getComponent() {
    return (CModuleNodeComponent) super.getComponent();
  }

  @Override
  public Icon getIcon() {
    if (m_module.getConfiguration().getRawModule().isComplete() && m_module.isInitialized()) {
      return m_module.isLoaded() ? ICON_MODULE : ICON_MODULE_GRAY;
    } else if (m_module.getConfiguration().getRawModule().isComplete()
        && !m_module.isInitialized()) {
      return ICON_MODULE_UNCONVERTED;
    } else {
      return ICON_MODULE_BROKEN;
    }
  }

  @Override
  public String toString() {
    return m_module.getConfiguration().getName() + " (" + m_module.getFunctionCount() + "/"
        + m_module.getCustomViewCount() + ")";
  }

  /**
   * Updates the node on important changes in the represented module.
   */
  private class InternalModuleListener extends CModuleListenerAdapter {
    @Override
    public void addedView(final INaviModule module, final INaviView view) {
      getTreeModel().nodeChanged(CModuleNode.this);
    }

    @Override
    public void changedName(final INaviModule module, final String name) {
      getTreeModel().nodeChanged(CModuleNode.this);
    }

    @Override
    public void deletedView(final INaviModule module, final INaviView view) {
      getTreeModel().nodeChanged(CModuleNode.this);
    }

    /**
     * When the module is loaded, create the child nodes.
     */
    @Override
    public void loadedModule(final INaviModule module) {
      new SwingInvoker() {
        @Override
        protected void operation() {
          createChildren();

          getTreeModel().nodeStructureChanged(CModuleNode.this);
        }
      }.invokeAndWait();
    }
  }
}


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>Installation — scraps 0.4.0 documentation</title>
    <link rel="stylesheet" href="_static/alabaster.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="next" title="Example 1: Load one file into the Resonator class" href="Example1_LoadAndPlot.html" />
    <link rel="prev" title="scraps: SuperConducting Resonator Analysis and Plotting Software" href="index.html" />

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

  <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" />

Installation¶

Required packages¶

Scraps is written in Python 3.6 (compatible with 2.7) and requires the following packages:

numpy

pandas

scipy

lmfit

emcee (optional)

matplotlib

Downloading and installing¶

The latest stable version of scraps is hosted at PyPi.

If you like pip, you can install with:

pip install scraps

Or, alternatively, download and extract the tarball from the above link and then
install from source with:

cd directory_you_unpacked_scraps_into
python setup.py install

Development¶

Development happens at github. You can
clone the repo with:

git clone http://github.com/FaustinCarter/scraps

And you can install it in developer mode with pip:

pip install -e /directory/where/you/cloned/scraps

or from source:

cd /directory/where/you/cloned/scraps
python setup.py develop

For the bleeding edge version checkout the develop branch:

cd /directory/where/you/cloned/scraps
git checkout develop

If you like this project and want to contribute, send a message over at the
github repo and you can be added as a collaborator!

Table Of Contents

Installation

Required packages

Downloading and installing

Development

Related Topics

Documentation overview

Previous: scraps: SuperConducting Resonator Analysis and Plotting Software

Next: Example 1: Load one file into the Resonator class

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>

      ©2016, Faustin W. Carter.

      |
      Powered by Sphinx 1.6.3
      & Alabaster 0.7.10

      |
      Page source


text:
[parsnipblue](http://grandmafunk.github.io/parsnipblue) is a simple, mobile-friendly browser game made using HTML, CSS, and JavaScript.
The goal is to be responsive and mobile friendly.

Swing back and forth avoiding the falling rectangles.
Click or press the spacebar to give a nudge in the opposite direction.

![demo gameplay](gameplaydemo.gif)

parsnipblue is licensed under the  [MIT License](https://github.com/GrandmaFunk/parsnipblue/blob/gh-pages/LICENSE)


text:
import Ember from 'ember';

export function d3AttrTween([attr, callback]) {
  return function (d3sel) {
    return d3sel.attrTween(attr, callback);
  };
}

export default Ember.Helper.helper(d3AttrTween);


text:
package uvm

// This package describes the external interface for utility VMs.

import (
	"context"
	"net"
	"sync"

	"github.com/Microsoft/go-winio/pkg/guid"
	"github.com/Microsoft/hcsshim/internal/gcs"
	"github.com/Microsoft/hcsshim/internal/hcs"
	"github.com/Microsoft/hcsshim/internal/hns"
	"github.com/Microsoft/hcsshim/internal/schema1"
)

//                    | WCOW | LCOW
// Container scratch  | SCSI | SCSI
// Scratch space      | ---- | SCSI   // For file system utilities. /tmp/scratch
// Read-Only Layer    | VSMB | VPMEM
// Mapped Directory   | VSMB | PLAN9

// vsmbShare is an internal structure used for ref-counting VSMB shares mapped to a Windows utility VM.
type vsmbShare struct {
	refCount     uint32
	name         string
	guestRequest interface{}
}

// scsiInfo is an internal structure used for determining what is mapped to a utility VM.
// hostPath is required. uvmPath may be blank.
type scsiInfo struct {
	hostPath string
	uvmPath  string

	// While most VHDs attached to SCSI are scratch spaces, in the case of LCOW
	// when the size is over the size possible to attach to PMEM, we use SCSI for
	// read-only layers. As RO layers are shared, we perform ref-counting.
	isLayer  bool
	refCount uint32
}

// vpmemInfo is an internal structure used for determining VPMem devices mapped to
// a Linux utility VM.
type vpmemInfo struct {
	hostPath string
	uvmPath  string
	refCount uint32
}

type nicInfo struct {
	ID       guid.GUID
	Endpoint *hns.HNSEndpoint
}

type namespaceInfo struct {
	nics map[string]*nicInfo
}

// UtilityVM is the object used by clients representing a utility VM
type UtilityVM struct {
	id              string               // Identifier for the utility VM (user supplied or generated)
	runtimeID       guid.GUID            // Hyper-V VM ID
	owner           string               // Owner for the utility VM (user supplied or generated)
	operatingSystem string               // "windows" or "linux"
	hcsSystem       *hcs.System          // The handle to the compute system
	gcListener      net.Listener         // The GCS connection listener
	gc              *gcs.GuestConnection // The GCS connection
	processorCount  int32
	m               sync.Mutex // Lock for adding/removing devices

	exitErr error
	exitCh  chan struct{}

	// GCS bridge protocol and capabilities
	protocol  uint32
	guestCaps schema1.GuestDefinedCapabilities

	// containerCounter is the current number of containers that have been
	// created. This is never decremented in the life of the UVM.
	//
	// NOTE: All accesses to this MUST be done atomically.
	containerCounter uint64

	// VSMB shares that are mapped into a Windows UVM. These are used for read-only
	// layers and mapped directories
	vsmbShares  map[string]*vsmbShare
	vsmbCounter uint64 // Counter to generate a unique share name for each VSMB share.

	// VPMEM devices that are mapped into a Linux UVM. These are used for read-only layers, or for
	// booting from VHD.
	vpmemDevices      [MaxVPMEMCount]vpmemInfo // Limited by ACPI size.
	vpmemMaxCount     uint32                   // Actual number of VPMem devices
	vpmemMaxSizeBytes uint64                   // Actual size of VPMem devices

	// SCSI devices that are mapped into a Windows or Linux utility VM
	scsiLocations       [4][64]scsiInfo // Hyper-V supports 4 controllers, 64 slots per controller. Limited to 1 controller for now though.
	scsiControllerCount uint32          // Number of SCSI controllers in the utility VM

	// Plan9 are directories mapped into a Linux utility VM
	plan9Counter uint64 // Each newly-added plan9 share has a counter used as its ID in the ResourceURI and for the name

	namespaces map[string]*namespaceInfo

	outputListener         net.Listener
	outputProcessingDone   chan struct{}
	outputHandler          OutputHandler
	outputProcessingCancel context.CancelFunc
}


text:
<?php

namespace Application\Model;

/**
 * @pattern-notes
 *
 * - This is an entity class, it also aggregates object: Artist & Album
 */
class Track
{
    protected $id;
    protected $title;
    protected $number;
    protected $length;
    protected $albumId;
    protected $album;
    protected $artistId;
    protected $artist;

    public function setId($id)
    {
        $this->id = $id;
    }

    public function getId()
    {
        return $this->id;
    }

    public function setTitle($title)
    {
        $this->title = $title;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function setNumber($number)
    {
        $this->number = $number;
    }

    public function getNumber()
    {
        return $this->number;
    }

    public function setLength($length)
    {
        $this->length = $length;
    }

    public function getLength()
    {
        return $this->length;
    }

    public function setAlbum($album)
    {
        $this->album = $album;
    }

    /**
     * @return Album
     */
    public function getAlbum()
    {
        return $this->album;
    }

    public function setArtist($artist)
    {
        $this->artist = $artist;
    }

    /**
     * @return Artist
     */
    public function getArtist()
    {
        return $this->artist;
    }

    /**
     * @param mixed $albumId
     */
    public function setAlbumId($albumId)
    {
        $this->albumId = $albumId;
    }

    /**
     * @return mixed
     */
    public function getAlbumId()
    {
        return $this->albumId;
    }

    /**
     * @param mixed $artistId
     */
    public function setArtistId($artistId)
    {
        $this->artistId = $artistId;
    }

    /**
     * @return mixed
     */
    public function getArtistId()
    {
        return $this->artistId;
    }

}


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/talent/v4beta1/common.proto

package com.google.cloud.talent.v4beta1;

/**
 *
 *
 *

 * Educational degree level defined in International Standard Classification
 * of Education (ISCED).
 *

 *
 * Protobuf enum {@code google.cloud.talent.v4beta1.DegreeType}
 */
public enum DegreeType implements com.google.protobuf.ProtocolMessageEnum {
  /**
   *
   *
   *

   * Default value. Represents no degree, or early childhood education.
   * Maps to ISCED code 0.
   * Ex) Kindergarten
   *

   *
   * DEGREE_TYPE_UNSPECIFIED = 0;
   */
  DEGREE_TYPE_UNSPECIFIED(0),
  /**
   *
   *
   *

   * Primary education which is typically the first stage of compulsory
   * education. ISCED code 1.
   * Ex) Elementary school
   *

   *
   * PRIMARY_EDUCATION = 1;
   */
  PRIMARY_EDUCATION(1),
  /**
   *
   *
   *

   * Lower secondary education; First stage of secondary education building on
   * primary education, typically with a more subject-oriented curriculum.
   * ISCED code 2.
   * Ex) Middle school
   *

   *
   * LOWER_SECONDARY_EDUCATION = 2;
   */
  LOWER_SECONDARY_EDUCATION(2),
  /**
   *
   *
   *

   * Middle education; Second/final stage of secondary education preparing for
   * tertiary education and/or providing skills relevant to employment.
   * Usually with an increased range of subject options and streams. ISCED
   * code 3.
   * Ex) High school
   *

   *
   * UPPER_SECONDARY_EDUCATION = 3;
   */
  UPPER_SECONDARY_EDUCATION(3),
  /**
   *
   *
   *

   * Adult Remedial Education; Programmes providing learning experiences that
   * build on secondary education and prepare for labour market entry and/or
   * tertiary education. The content is broader than secondary but not as
   * complex as tertiary education. ISCED code 4.
   *

   *
   * ADULT_REMEDIAL_EDUCATION = 4;
   */
  ADULT_REMEDIAL_EDUCATION(4),
  /**
   *
   *
   *

   * Associate's or equivalent; Short first tertiary programmes that are
   * typically practically-based, occupationally-specific and prepare for
   * labour market entry. These programmes may also provide a pathway to other
   * tertiary programmes. ISCED code 5.
   *

   *
   * ASSOCIATES_OR_EQUIVALENT = 5;
   */
  ASSOCIATES_OR_EQUIVALENT(5),
  /**
   *
   *
   *

   * Bachelor's or equivalent; Programmes designed to provide intermediate
   * academic and/or professional knowledge, skills and competencies leading
   * to a first tertiary degree or equivalent qualification. ISCED code 6.
   *

   *
   * BACHELORS_OR_EQUIVALENT = 6;
   */
  BACHELORS_OR_EQUIVALENT(6),
  /**
   *
   *
   *

   * Master's or equivalent; Programmes designed to provide advanced academic
   * and/or professional knowledge, skills and competencies leading to a
   * second tertiary degree or equivalent qualification. ISCED code 7.
   *

   *
   * MASTERS_OR_EQUIVALENT = 7;
   */
  MASTERS_OR_EQUIVALENT(7),
  /**
   *
   *
   *

   * Doctoral or equivalent; Programmes designed primarily to lead to an
   * advanced research qualification, usually concluding with the submission
   * and defense of a substantive dissertation of publishable quality based on
   * original research. ISCED code 8.
   *

   *
   * DOCTORAL_OR_EQUIVALENT = 8;
   */
  DOCTORAL_OR_EQUIVALENT(8),
  UNRECOGNIZED(-1),
  ;

  /**
   *
   *
   *

   * Default value. Represents no degree, or early childhood education.
   * Maps to ISCED code 0.
   * Ex) Kindergarten
   *

   *
   * DEGREE_TYPE_UNSPECIFIED = 0;
   */
  public static final int DEGREE_TYPE_UNSPECIFIED_VALUE = 0;
  /**
   *
   *
   *

   * Primary education which is typically the first stage of compulsory
   * education. ISCED code 1.
   * Ex) Elementary school
   *

   *
   * PRIMARY_EDUCATION = 1;
   */
  public static final int PRIMARY_EDUCATION_VALUE = 1;
  /**
   *
   *
   *

   * Lower secondary education; First stage of secondary education building on
   * primary education, typically with a more subject-oriented curriculum.
   * ISCED code 2.
   * Ex) Middle school
   *

   *
   * LOWER_SECONDARY_EDUCATION = 2;
   */
  public static final int LOWER_SECONDARY_EDUCATION_VALUE = 2;
  /**
   *
   *
   *

   * Middle education; Second/final stage of secondary education preparing for
   * tertiary education and/or providing skills relevant to employment.
   * Usually with an increased range of subject options and streams. ISCED
   * code 3.
   * Ex) High school
   *

   *
   * UPPER_SECONDARY_EDUCATION = 3;
   */
  public static final int UPPER_SECONDARY_EDUCATION_VALUE = 3;
  /**
   *
   *
   *

   * Adult Remedial Education; Programmes providing learning experiences that
   * build on secondary education and prepare for labour market entry and/or
   * tertiary education. The content is broader than secondary but not as
   * complex as tertiary education. ISCED code 4.
   *

   *
   * ADULT_REMEDIAL_EDUCATION = 4;
   */
  public static final int ADULT_REMEDIAL_EDUCATION_VALUE = 4;
  /**
   *
   *
   *

   * Associate's or equivalent; Short first tertiary programmes that are
   * typically practically-based, occupationally-specific and prepare for
   * labour market entry. These programmes may also provide a pathway to other
   * tertiary programmes. ISCED code 5.
   *

   *
   * ASSOCIATES_OR_EQUIVALENT = 5;
   */
  public static final int ASSOCIATES_OR_EQUIVALENT_VALUE = 5;
  /**
   *
   *
   *

   * Bachelor's or equivalent; Programmes designed to provide intermediate
   * academic and/or professional knowledge, skills and competencies leading
   * to a first tertiary degree or equivalent qualification. ISCED code 6.
   *

   *
   * BACHELORS_OR_EQUIVALENT = 6;
   */
  public static final int BACHELORS_OR_EQUIVALENT_VALUE = 6;
  /**
   *
   *
   *

   * Master's or equivalent; Programmes designed to provide advanced academic
   * and/or professional knowledge, skills and competencies leading to a
   * second tertiary degree or equivalent qualification. ISCED code 7.
   *

   *
   * MASTERS_OR_EQUIVALENT = 7;
   */
  public static final int MASTERS_OR_EQUIVALENT_VALUE = 7;
  /**
   *
   *
   *

   * Doctoral or equivalent; Programmes designed primarily to lead to an
   * advanced research qualification, usually concluding with the submission
   * and defense of a substantive dissertation of publishable quality based on
   * original research. ISCED code 8.
   *

   *
   * DOCTORAL_OR_EQUIVALENT = 8;
   */
  public static final int DOCTORAL_OR_EQUIVALENT_VALUE = 8;

  public final int getNumber() {
    if (this == UNRECOGNIZED) {
      throw new java.lang.IllegalArgumentException(
          "Can't get the number of an unknown enum value.");
    }
    return value;
  }

  /**
   * @param value The numeric wire value of the corresponding enum entry.
   * @return The enum associated with the given numeric wire value.
   * @deprecated Use {@link #forNumber(int)} instead.
   */
  @java.lang.Deprecated
  public static DegreeType valueOf(int value) {
    return forNumber(value);
  }

  /**
   * @param value The numeric wire value of the corresponding enum entry.
   * @return The enum associated with the given numeric wire value.
   */
  public static DegreeType forNumber(int value) {
    switch (value) {
      case 0:
        return DEGREE_TYPE_UNSPECIFIED;
      case 1:
        return PRIMARY_EDUCATION;
      case 2:
        return LOWER_SECONDARY_EDUCATION;
      case 3:
        return UPPER_SECONDARY_EDUCATION;
      case 4:
        return ADULT_REMEDIAL_EDUCATION;
      case 5:
        return ASSOCIATES_OR_EQUIVALENT;
      case 6:
        return BACHELORS_OR_EQUIVALENT;
      case 7:
        return MASTERS_OR_EQUIVALENT;
      case 8:
        return DOCTORAL_OR_EQUIVALENT;
      default:
        return null;
    }
  }

  public static com.google.protobuf.Internal.EnumLiteMap<DegreeType> internalGetValueMap() {
    return internalValueMap;
  }

  private static final com.google.protobuf.Internal.EnumLiteMap<DegreeType> internalValueMap =
      new com.google.protobuf.Internal.EnumLiteMap<DegreeType>() {
        public DegreeType findValueByNumber(int number) {
          return DegreeType.forNumber(number);
        }
      };

  public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() {
    if (this == UNRECOGNIZED) {
      throw new java.lang.IllegalStateException(
          "Can't get the descriptor of an unrecognized enum value.");
    }
    return getDescriptor().getValues().get(ordinal());
  }

  public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() {
    return getDescriptor();
  }

  public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() {
    return com.google.cloud.talent.v4beta1.CommonProto.getDescriptor().getEnumTypes().get(2);
  }

  private static final DegreeType[] VALUES = values();

  public static DegreeType valueOf(com.google.protobuf.Descriptors.EnumValueDescriptor desc) {
    if (desc.getType() != getDescriptor()) {
      throw new java.lang.IllegalArgumentException("EnumValueDescriptor is not for this type.");
    }
    if (desc.getIndex() == -1) {
      return UNRECOGNIZED;
    }
    return VALUES[desc.getIndex()];
  }

  private final int value;

  private DegreeType(int value) {
    this.value = value;
  }

  // @@protoc_insertion_point(enum_scope:google.cloud.talent.v4beta1.DegreeType)
}


text:
id: 5e7b9f170b6c005b0e76f087
title: Object Lifecycle
challengeType: 11
videoId: p1r3h_AMMIM
dashedName: object-lifecycle
---

# --question--

## --text--

What will the following program print?:

```python
class PartyAnimal:
    x = 0
    name = ''
    def __init__(self, nam):
        self.name = nam
        print(self.name,'constructed')
    def party(self):
        self.x = self.x + 1
        print(self.name,'party count',self.x)

q = PartyAnimal('Quincy')
m = PartyAnimal('Miya')

q.party()
m.party()
q.party()
```

## --answers--

Quincy constructed
Miya constructed
Quincy party count 1
Miya party count 2
Quincy party count 3

---

Quincy constructed
Miya constructed
Quincy party count 1
Miya party count 1
Quincy party count 2

---

Quincy constructed
Quincy party count 1
Quincy party count 2
Miya constructed
Miya party count 1

## --video-solution--

2


text:
#ifndef __OBJECT_REGISTRY__
#define __OBJECT_REGISTRY__

#include <map>
#include <string>

#include "misc.h"

BBC_AUDIOTOOLBOX_START

class RegisteredObjectFactory
{
public:
  RegisteredObjectFactory(const char *_name);
  virtual ~RegisteredObjectFactory();

  /*--------------------------------------------------------------------------------*/
  /** Get name for the object this factory creates
   */
  /*--------------------------------------------------------------------------------*/
  const std::string& GetName() const {return name;}

  /*--------------------------------------------------------------------------------*/
  /** Return relative priority of this factory
   */
  /*--------------------------------------------------------------------------------*/
  virtual int GetPriority() const = 0;

protected:
  /*--------------------------------------------------------------------------------*/
  /** Register this object with object registry (MUST be called AFTER construction is complete!)
   */
  /*--------------------------------------------------------------------------------*/
  virtual void Register();

protected:
  std::string name;
};

class ObjectRegistry {
public:
  ~ObjectRegistry() {}

  /*--------------------------------------------------------------------------------*/
  /** Register a factory with this registry
   */
  /*--------------------------------------------------------------------------------*/
  void Register(RegisteredObjectFactory *factory);

  /*--------------------------------------------------------------------------------*/
  /** Return the factory for the specified type name or NULL
   */
  /*--------------------------------------------------------------------------------*/
  RegisteredObjectFactory *GetFactory(const char *name);

  /*--------------------------------------------------------------------------------*/
  /** Typedefs
   */
  /*--------------------------------------------------------------------------------*/
  typedef const std::map<std::string,RegisteredObjectFactory *> map;
  typedef map::const_iterator iterator;

  /*--------------------------------------------------------------------------------*/
  /** Return map of objects
   */
  /*--------------------------------------------------------------------------------*/
  map& GetObjects() const {return objects;}

  /*--------------------------------------------------------------------------------*/
  /** Return ObjectRegistry singleton
   */
  /*--------------------------------------------------------------------------------*/
  static ObjectRegistry& Get();

protected:
  ObjectRegistry() {}     // can only be created by a member function -> enforces singleton

protected:
  std::map<std::string,RegisteredObjectFactory *> objects;
};

BBC_AUDIOTOOLBOX_END

#endif