text:
<?php

	//importamos el módulo del "buscador"
	use app\modules\buscador\buscadorAssets;buscadorAssets::register($this);

	use app\modules\gestionstock\StockAsset;StockAsset::register($this);

	$this->title = 'Catálogo';
?>

Área de notificaciones

			<input id='Agregar' class='btn btn-success btn-xs' value='Nuevo' <?php if (!$Rango){echo "disabled='disabled'";} ?> type='button'>
			<input id='Modificar' class='btn btn-info btn-xs' value='Modificar' <?php if (!$Rango){echo "disabled='disabled'";} ?> type='button'>
			<?php
				if ($Rango){
					echo "<input id='Eliminar' class='btn btn-danger btn-xs' value='Eliminar' type='button'>";
				} else {
					echo "<input class='btn btn-danger btn-xs' value='Eliminar' type='button' disabled='disabled'>";
				}
			?>

Nombre: <input type="text" id="Nombre" class="form-control">

Descripción: <TEXTAREA rows="2" type="text" id="Descripcion" class="form-control"></TEXTAREA>

Autor: <input type="text" id="Autor" class="form-control">

Cantidad: <input type="text" id="Cantidad" class="form-control">

Ingresar cantidad a agregar: <input type="text" id="CantidadAAgregar" class="form-control">

    		<input id='Aceptar' class='btn btn-success btn-xs' value='Aceptar' type='button'>

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Reflection;

namespace InstallDirChanger.NMaier.GetOptNet
{
  internal sealed class IListArgumentHandler : MultipleArgumentHandler
  {
    private readonly object list;

    public IListArgumentHandler(Object aObj, MemberInfo aInfo, Type aType, int aMin, int aMax)
      : base(aObj, aInfo, aType, aMin, aMax)
    {
      switch (info.MemberType) {
        case MemberTypes.Field:
          list = (info as FieldInfo).GetValue(obj);
          break;
        case MemberTypes.Property:
          list = (info as PropertyInfo).GetValue(obj, null);
          break;
        default:
          throw new ProgrammingError("W00t?");
      }
      elementType = aType.GetGenericArguments()[0];
    }

    public override void Assign(string toAssign)
    {
      CheckAssign();
      type.GetMethod("Add").Invoke(list, new object[] { InternalConvert(toAssign, elementType) });
      added++;
      wasSet = true;
    }
  }
}


text:
package org.springframework.security.config.annotation.web.configurers;

import static org.mockito.Matchers.any;
import static org.mockito.Matchers.same;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.spy;
import static org.powermock.api.mockito.PowerMockito.verifyStatic;
import static org.powermock.api.mockito.PowerMockito.when;

import java.lang.reflect.Method;

import javax.servlet.Filter;
import javax.servlet.http.HttpServletRequest;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.web.context.HttpRequestResponseHolder;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
import org.springframework.util.ReflectionUtils;

/**
 *
 * @author Rob Winch
 */
@RunWith(PowerMockRunner.class)
@PrepareForTest({ReflectionUtils.class, Method.class})
public class SessionManagementConfigurerServlet31Tests {
    @Mock
    Method method;

    MockHttpServletRequest request;
    MockHttpServletResponse response;
    MockFilterChain chain;

    ConfigurableApplicationContext context;

    Filter springSecurityFilterChain;

    @Before
    public void setup() {
        request = new MockHttpServletRequest();
        response = new MockHttpServletResponse();
        chain = new MockFilterChain();
    }

    @After
    public void teardown() {
        if(context != null) {
            context.close();
        }
    }

    @Test
    public void changeSessionIdDefaultsInServlet31Plus() throws Exception {
        spy(ReflectionUtils.class);
        Method method = mock(Method.class);
        MockHttpServletRequest request = new MockHttpServletRequest();
        request.getSession();
        request.setServletPath("/login");
        request.setMethod("POST");
        request.setParameter("username", "user");
        request.setParameter("password", "password");
        HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
        CsrfToken token = repository.generateToken(request);
        repository.saveToken(token, request, response);
        request.setParameter(token.getParameterName(),token.getToken());
        when(ReflectionUtils.findMethod(HttpServletRequest.class, "changeSessionId")).thenReturn(method);

        loadConfig(SessionManagementDefaultSessionFixationServlet31Config.class);

        springSecurityFilterChain.doFilter(request,response,chain);

        verifyStatic();
        ReflectionUtils.invokeMethod(same(method), any(HttpServletRequest.class));
    }

    @EnableWebSecurity
    @Configuration
    static class SessionManagementDefaultSessionFixationServlet31Config extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .formLogin()
                    .and()
                .sessionManagement();
        }

        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth
                .inMemoryAuthentication()
                    .withUser("user").password("password").roles("USER");
        }
    }

    private void loadConfig(Class<?>...classes) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.register(classes);
        context.refresh();
        this.context = context;
        this.springSecurityFilterChain = this.context.getBean("springSecurityFilterChain",Filter.class);
    }

    private void login(Authentication auth) {
        HttpSessionSecurityContextRepository repo = new HttpSessionSecurityContextRepository();
        HttpRequestResponseHolder requestResponseHolder = new HttpRequestResponseHolder(request, response);
        repo.loadContext(requestResponseHolder);

        SecurityContextImpl securityContextImpl = new SecurityContextImpl();
        securityContextImpl.setAuthentication(auth);
        repo.saveContext(securityContextImpl, requestResponseHolder.getRequest(), requestResponseHolder.getResponse());
    }
}


text:
import os
import re
import json
import requests
import time
from pprint import pformat
from biokbase.workspace.client import Workspace as workspaceService  # @UnresolvedImport @IgnorePep8
from biokbase.workspace.client import ServerError as WorkspaceException  # @UnresolvedImport @IgnorePep8
import errno
import shutil
import gzip
import uuid

class ShockError(Exception):
    pass

class InvalidFileError(Exception):
    pass

#END_HEADER

class kb_read_library_to_file:
    '''
    Module Name:
    kb_read_library_to_file

    Module Description:
    A KBase module: kb_read_library_to_file

Takes KBaseFile/KBaseAssembly PairedEndLibrary/SingleEndLibrary reads library
workspace object IDs as input and produces a FASTQ files along with file
metadata.

Operational notes:
- The file type and suffixes for the reads files are determined from, in order
    of precedence:
  - the lib?/type field in KBaseFile types
  - the lib?/file/filename or handle?/filename field
  - the shock filename
- All reads files must be in fastq format, and thus the file suffix must have a
  case-insensitive .fq or .fastq suffix.
- Reads files are optionally gzipped, and if so must have a case-insensitive
  .gz suffix after the fastq suffix.
- If the file types / suffixes do not match the previous rules, the converter
  raises an error.
- If a file downloaded from Shock has a .gz suffix, it is assumed to be
  gzipped.
- Files are assumed to be in correct fastq format.
    '''

    ######## WARNING FOR GEVENT USERS #######
    # Since asynchronous IO can lead to methods - even the same method -
    # interrupting each other, you must be *very* careful when using global
    # state. A method could easily clobber the state set by another while
    # the latter method is running.
    #########################################
    VERSION = "0.0.1"
    GIT_URL = "https://github.com/mrcreosote/kb_read_library_to_file"
    GIT_COMMIT_HASH = "6709a2cf4a19a5b72b533e6cd57489256ca90dc6"

    #BEGIN_CLASS_HEADER
    # Class variables and functions can be defined in this block
    SINGLE_END_TYPE = 'SingleEndLibrary'
    PAIRED_END_TYPE = 'PairedEndLibrary'
    # one of these should be deprecated
    KBASE_FILE = 'KBaseFile'
    KBASE_ASSEMBLY = 'KBaseAssembly'
    MODULE_NAMES = [KBASE_FILE, KBASE_ASSEMBLY]
    TYPE_NAMES = [SINGLE_END_TYPE, PAIRED_END_TYPE]

    PARAM_IN_WS = 'workspace_name'
    PARAM_IN_LIB = 'read_libraries'
    PARAM_IN_GZIP = 'gzip'
    PARAM_IN_INTERLEAVED = 'interleaved'

    GZIP = '.gz'

    TRUE = 'true'
    FALSE = 'false'

    URL_WS = 'workspace-url'
    URL_SHOCK = 'shock-url'

    SUPPORTED_FILES = ['.fq',
                       '.fastq',
                       # '.bam',
                       # '.fa',
                       # '.fasta',
                       '.fq' + GZIP,
                       '.fastq' + GZIP,
                       # '.bam.gz',
                       # '.fa.gz',
                       # '.fasta.gz'
                       ]

    SHOCK_TEMP = 'shock_tmp'

    def log(self, message, prefix_newline=False):
        print(('\n' if prefix_newline else '') +
              str(time.time()) + ': ' + message)

    def file_extension_ok(self, filename):
        for okext in self.SUPPORTED_FILES:
            if filename.lower().endswith(okext):
                if okext.endswith(self.GZIP):
                    return okext, True
                return okext, False
        return None, None

    def check_shock_response(self, response):
        if not response.ok:
            try:
                err = json.loads(response.content)['error'][0]
            except:
                # this means shock is down or not responding.
                self.log("Couldn't parse response error content from Shock: " +
                         response.content)
                response.raise_for_status()
            raise ShockError(str(err))

    def shock_download(self, token, handle, file_type=None):
        # Could keep a record of files downloaded to prevent duplicate
        # downloads if 2 ws objects point to the same shock node, but that
        # seems rare enough that it's not worth the extra code complexity and
        # maintenance burden
        self.log('Downloading from shock via handle:\n' + pformat(handle))

        headers = {'Authorization': 'OAuth ' + token}
        node_url = handle['url'] + '/node/' + handle['id']
        r = requests.get(node_url, headers=headers)
        self.check_shock_response(r)

        node_fn = r.json()['data']['file']['name']

        handle_fn = handle['file_name'] if 'file_name' in handle else None

        if file_type:
            file_type = ('' if file_type.startswith('.') else '.') + file_type
        fileok = None
        for txt, fn in zip(['file type', 'handle filename', 'shock filename'],
                           [file_type, handle_fn, node_fn]):
            if fn:
                fileok, gzipped = self.file_extension_ok(fn)
                if fileok:
                    self.log(('Found acceptable file extension in {}: {}. ' +
                             'File {} gzipped.').format(
                        txt, fn, 'is' if gzipped else 'is not'))
                break
            else:
                self.log('File extension cannot be determined from {}: {}'
                         .format(txt, fn))
        if not fileok:
            raise InvalidFileError(
                ('A valid file extension could not be determined for the ' +
                 'reads file. In order of precedence:\n' +
                 'File type is: {}\n' +
                 'Handle file name is: {}\n' +
                 'Shock file name is: {}\n' +
                 'Acceptable extensions: {}').format(
                    file_type, handle_fn, node_fn,
                    ' '.join(self.SUPPORTED_FILES)))

        file_path = os.path.join(self.shock_temp, handle['id'] +
                                 (self.GZIP if gzipped else ''))
        with open(file_path, 'w') as fhandle:
            self.log('downloading reads file: ' + str(file_path))
            r = requests.get(node_url + '?download', stream=True,
                             headers=headers)
            self.check_shock_response(r)
            for chunk in r.iter_content(1024):
                if not chunk:
                    break
                fhandle.write(chunk)
        return file_path, gzipped

    def make_ref(self, object_info):
        return str(object_info[6]) + '/' + str(object_info[0]) + \
            '/' + str(object_info[4])

    def check_reads(self, reads):
        info = reads['info']
        obj_ref = self.make_ref(info)
        obj_name = info[1]

        # Might need to do version checking here.
        module_name, type_name = info[2].split('-')[0].split('.')
        if (module_name not in self.MODULE_NAMES or
                type_name not in self.TYPE_NAMES):
            types = []
            for mod in self.MODULE_NAMES:
                for type_ in self.TYPE_NAMES:
                    types.append(mod + '.' + type_)
            raise ValueError(('Invalid type for object {} ({}). Supported ' +
                              'types: {}').format(obj_ref, obj_name,
                                                  ' '.join(types)))
        return (type_name == self.SINGLE_END_TYPE,
                module_name == self.KBASE_FILE)

    def copy_field(self, source, field, target):
        target[field] = source.get(field)

    # this assumes that the FASTQ file is properly formatted, which it should
    # be if it's in KBase. Credit:
    # https://www.biostars.org/p/19446/#117160
    def deinterleave(self, filepath, fwdpath, revpath):
        self.log('Deinterleaving file {} to files {} and {}'.format(
            filepath, fwdpath, revpath))
        with open(filepath, 'r') as s:
            with open(fwdpath, 'w') as f, open(revpath, 'w') as r:
                for i, line in enumerate(s):
                    if i % 8 < 4:
                        f.write(line)
                    else:
                        r.write(line)

    # this assumes that the FASTQ files are properly formatted and matched,
    # which they should be if they're in KBase. Credit:
    # https://sourceforge.net/p/denovoassembler/ray-testsuite/ci/master/tree/scripts/interleave-fastq.py
    def interleave(self, fwdpath, revpath, targetpath):
        self.log('Interleaving files {} and {} to {}'.format(
            fwdpath, revpath, targetpath))
        with open(targetpath, 'w') as t:
            with open(fwdpath, 'r') as f, open(revpath, 'r') as r:
                while True:
                    line = f.readline()
                    # since FASTQ cannot contain blank lines
                    if not line or not line.strip():
                        break
                    t.write(line.strip() + '\n')

                    for _ in xrange(3):
                        t.write(f.readline().strip() + '\n')

                    for _ in xrange(4):
                        t.write(r.readline().strip() + '\n')

    def set_up_reads_return(self, single, kbasefile, reads):
        data = reads['data']
        info = reads['info']

        ret = {}
        ret['ref'] = self.make_ref(info)

        sg = 'single_genome'
        if kbasefile:
            if sg not in data or data[sg]:
                ret[sg] = self.TRUE
            else:
                ret[sg] = self.FALSE
        else:
            ret[sg] = None

        roo = 'read_orientation_outward'
        if single:
            ret[roo] = None
        elif roo in data:
            ret[roo] = self.TRUE if data[roo] else self.FALSE
        else:
            ret[roo] = self.FALSE if kbasefile else None

        # these fields are only possible in KBaseFile/Assy paired end, but the
        # logic is still fine for single end, will just force a null
        self.copy_field(data, 'insert_size_mean', ret)
        self.copy_field(data, 'insert_size_std_dev', ret)
        # these fields are in KBaseFile single end and paired end only
        self.copy_field(data, 'source', ret)
        self.copy_field(data, 'strain', ret)
        self.copy_field(data, 'sequencing_tech', ret)
        self.copy_field(data, 'read_count', ret)
        self.copy_field(data, 'read_size', ret)
        self.copy_field(data, 'gc_content', ret)

        return ret

    def bool_outgoing(self, boolean):
        return self.TRUE if boolean else self.FALSE

    def get_file_prefix(self):
        return os.path.join(self.scratch, str(uuid.uuid4()))

    def get_shock_data_and_handle_errors(
            self, source_obj_ref, source_obj_name, token, handle, file_type):
        try:
            return self.shock_download(token, handle, file_type)
        except (ShockError, InvalidFileError) as e:
            msg = ('Error downloading reads for object {} ({}) from ' +
                   'Shock node {}: ').format(
                   source_obj_ref, source_obj_name, handle['id'])
            e.args = (msg + e.args[0],) + e.args[1:]
            # py 3 exceptions have no message field
            if hasattr(e, 'message'):  # changing args doesn't change message
                e.message = msg + e.message
            raise

    # there's got to be better way to do this than these processing methods.
    # make some input classes for starters to fix these gross method sigs

    def process_interleaved(self, source_obj_ref, source_obj_name, token,
                            handle, gzip, interleave, file_type=None):

        shockfile, isgz = self.get_shock_data_and_handle_errors(
            source_obj_ref, source_obj_name, token, handle, file_type)

        ret = {}
        if interleave is not False:  # e.g. True or None
            ret['inter'], ret['inter_gz'] = self.handle_gzip(
                shockfile, gzip, isgz, self.get_file_prefix() + '.inter.fastq')
        else:
            if isgz:
                # we expect the job runner to clean up for us
                shockfile = self.gunzip(shockfile)
            fwdpath = os.path.join(self.scratch, self.get_file_prefix() +
                                   '.fwd.fastq')
            revpath = os.path.join(self.scratch, self.get_file_prefix() +
                                   '.rev.fastq')
            self.deinterleave(shockfile, fwdpath, revpath)
            if gzip:
                fwdpath = self.gzip(fwdpath)
                revpath = self.gzip(revpath)
            gzip = self.bool_outgoing(gzip)
            ret['fwd'] = fwdpath
            ret['fwd_gz'] = gzip
            ret['rev'] = revpath
            ret['rev_gz'] = gzip
        return ret

    def process_paired(self, source_obj_ref, source_obj_name, token,
                       fwdhandle, revhandle, gzip, interleave,
                       fwd_file_type=None, rev_file_type=None):

        fwdshock, fwdisgz = self.get_shock_data_and_handle_errors(
            source_obj_ref, source_obj_name, token, fwdhandle, fwd_file_type)
        revshock, revisgz = self.get_shock_data_and_handle_errors(
            source_obj_ref, source_obj_name, token, revhandle, rev_file_type)

        ret = {}
        if interleave:
            # we expect the job runner to clean up for us
            if fwdisgz:
                fwdshock = self.gunzip(fwdshock)
            if revisgz:
                revshock = self.gunzip(revshock)
            intpath = os.path.join(self.scratch, self.get_file_prefix() +
                                   '.inter.fastq')
            self.interleave(fwdshock, revshock, intpath)
            if gzip:
                intpath = self.gzip(intpath)
            ret['inter'] = intpath
            ret['inter_gz'] = self.bool_outgoing(gzip)
        else:
            ret['fwd'], ret['fwd_gz'] = self.handle_gzip(
                fwdshock, gzip, fwdisgz, self.get_file_prefix() + '.fwd.fastq')

            ret['rev'], ret['rev_gz'] = self.handle_gzip(
                revshock, gzip, revisgz, self.get_file_prefix() + '.rev.fastq')
        return ret

    def process_single_end(self, source_obj_ref, source_obj_name, token,
                           handle, gzip, file_type=None):

        shockfile, isgz = self.get_shock_data_and_handle_errors(
            source_obj_ref, source_obj_name, token, handle, file_type)
        f, iszip = self.handle_gzip(shockfile, gzip, isgz,
                                    self.get_file_prefix() + '.sing.fastq')
        return {'sing': f, 'sing_gz': iszip}

    # there's almost certainly a better way to do this
    def handle_gzip(self, oldfile, shouldzip, iszip, prefix):
        zipped = False
        if shouldzip:
            prefix += self.GZIP
            zipped = True
            if iszip:
                self.mv(oldfile, os.path.join(self.scratch, prefix))
            else:
                self.gzip(oldfile, os.path.join(self.scratch, prefix))
        elif shouldzip is None:
            if iszip:
                prefix += self.GZIP
                zipped = True
            self.mv(oldfile, os.path.join(self.scratch, prefix))
        else:
            if iszip:
                self.gunzip(oldfile, os.path.join(self.scratch, prefix))
            else:
                self.mv(oldfile, os.path.join(self.scratch, prefix))
        return prefix, self.bool_outgoing(zipped)

    def mv(self, oldfile, newfile):
        self.log('Moving {} to {}'.format(oldfile, newfile))
        shutil.move(oldfile, newfile)

    def gzip(self, oldfile, newfile=None):
        if oldfile.lower().endswith(self.GZIP):
            raise ValueError('File {} is already gzipped'.format(oldfile))
        if not newfile:
            newfile = oldfile + self.GZIP
        self.log('gzipping {} to {}'.format(oldfile, newfile))
        with open(oldfile, 'rb') as s, gzip.open(newfile, 'wb') as t:
            shutil.copyfileobj(s, t)
        return newfile

    def gunzip(self, oldfile, newfile=None):
        if not oldfile.lower().endswith(self.GZIP):
            raise ValueError('File {} is not gzipped'.format(oldfile))
        if not newfile:
            newfile = oldfile[: -len(self.GZIP)]
        self.log('gunzipping {} to {}'.format(oldfile, newfile))
        with gzip.open(oldfile, 'rb') as s, open(newfile, 'wb') as t:
            shutil.copyfileobj(s, t)
        return newfile

    def process_reads(self, reads, gzip, interleave, token):
        data = reads['data']
        info = reads['info']
        # Object Info Contents
        # 0 - obj_id objid
        # 1 - obj_name name
        # 2 - type_string type
        # 3 - timestamp save_date
        # 4 - int version
        # 5 - username saved_by
        # 6 - ws_id wsid
        # 7 - ws_name workspace
        # 8 - string chsum
        # 9 - int size
        # 10 - usermeta meta

        single, kbasefile = self.check_reads(reads)
        ret = self.set_up_reads_return(single, kbasefile, reads)
        obj_name = info[1]
        ref = ret['ref']
        self.log('Type: ' + info[2])

        # lib1 = KBaseFile, handle_1 = KBaseAssembly
        if kbasefile:
            if single:
                reads = data['lib']['file']
                type_ = data['lib']['type']
                ret['files'] = self.process_single_end(
                    ref, obj_name, token, reads, gzip, type_)
            else:
                fwd_reads = data['lib1']['file']
                fwd_type = data['lib1']['type']
                if 'lib2' in data:  # not interleaved
                    rev_reads = data['lib2']['file']
                    rev_type = data['lib2']['type']
                    ret['files'] = self.process_paired(
                        ref, obj_name, token, fwd_reads, rev_reads, gzip,
                        interleave, fwd_type, rev_type)
                else:
                    ret['files'] = self.process_interleaved(
                        ref, obj_name, token, fwd_reads, gzip, interleave,
                        fwd_type)
        else:  # KBaseAssembly
            if single:
                ret['files'] = self.process_single_end(
                    ref, obj_name, token, data['handle'], gzip)
            else:
                if 'handle_2' in data:  # not interleaved
                    ret['files'] = self.process_paired(
                        ref, obj_name, token, data['handle_1'],
                        data['handle_2'], gzip, interleave)
                else:
                    ret['files'] = self.process_interleaved(
                        ref, obj_name, token, data['handle_1'], gzip,
                        interleave)

        return ret

    def process_ternary(self, params, boolname):
        if boolname not in params or params[boolname] is None:
            params[boolname] = None
        elif params[boolname] == 'true':
            params[boolname] = True
        elif params[boolname] == 'false':
            params[boolname] = False
        else:
            raise ValueError(('Illegal value for ternary parameter {}: {}. ' +
                              'Allowed values are "true", "false", and null.')
                             .format(boolname, params[boolname]))

    def process_params(self, params):
        if self.PARAM_IN_LIB not in params:
            raise ValueError(self.PARAM_IN_LIB + ' parameter is required')
        reads = params[self.PARAM_IN_LIB]
        if type(reads) != list:
            raise ValueError(self.PARAM_IN_LIB + ' must be a list')
        if not reads:
            raise ValueError('At least one reads library must be provided')
        reads = list(set(reads))
        for read_name in reads:
            if not read_name:
                raise ValueError('Invalid workspace object name ' + read_name)
        params[self.PARAM_IN_LIB] = reads

        self.process_ternary(params, self.PARAM_IN_GZIP)
        self.process_ternary(params, self.PARAM_IN_INTERLEAVED)

    def mkdir_p(self, path):
        try:
            os.makedirs(path)
        except OSError as exc:  # Python >2.5
            if exc.errno == errno.EEXIST and os.path.isdir(path):
                pass
            else:
                raise

    #END_CLASS_HEADER

    # config contains contents of config file in a hash or None if it couldn't
    # be found
    def __init__(self, config):
        #BEGIN_CONSTRUCTOR
        self.workspaceURL = config[self.URL_WS]
        self.shockURL = config[self.URL_SHOCK]
        self.scratch = os.path.abspath(config['scratch'])
        self.mkdir_p(self.scratch)
        self.shock_temp = os.path.join(self.scratch, self.SHOCK_TEMP)
        self.mkdir_p(self.shock_temp)
        #END_CONSTRUCTOR
        pass

    def convert_read_library_to_file(self, ctx, params):
        """
        Convert read libraries to files
        :param params: instance of type "ConvertReadLibraryParams" (Input
           parameters for converting libraries to files. list<read_lib>
           read_libraries - the names of the workspace read library objects
           to convert. tern gzip - if true, gzip any unzipped files. If
           false, gunzip any zipped files. If null or missing, leave files as
           is unless unzipping is required for interleaving or
           deinterleaving, in which case the files will be left unzipped.
           tern interleaved - if true, provide the files in interleaved
           format if they are not already. If false, provide forward and
           reverse reads files. If null or missing, leave files as is.) ->
           structure: parameter "read_libraries" of list of type "read_lib"
           (A reference to a read library stored in the workspace service,
           whether of the KBaseAssembly or KBaseFile type. Usage of absolute
           references (e.g. 256/3/6) is strongly encouraged to avoid race
           conditions, although any valid reference is allowed.), parameter
           "gzip" of type "tern" (A ternary. Allowed values are 'false',
           'true', or null. Any other value is invalid.), parameter
           "interleaved" of type "tern" (A ternary. Allowed values are
           'false', 'true', or null. Any other value is invalid.)
        :returns: instance of type "ConvertReadLibraryOutput" (The output of
           the convert method. mapping<read_lib, ConvertedReadLibrary> files
           - a mapping of the read library workspace references to
           information about the converted data for each library.) ->
           structure: parameter "files" of mapping from type "read_lib" (A
           reference to a read library stored in the workspace service,
           whether of the KBaseAssembly or KBaseFile type. Usage of absolute
           references (e.g. 256/3/6) is strongly encouraged to avoid race
           conditions, although any valid reference is allowed.) to type
           "ConvertedReadLibrary" (Information about each set of reads.
           ReadsFiles files - the reads files. string ref - the absolute
           workspace reference of the reads file, e.g
           workspace_id/object_id/version. tern single_genome - whether the
           reads are from a single genome or a metagenome. null if unknown.
           tern read_orientation_outward - whether the read orientation is
           outward from the set of primers. null if unknown or single ended
           reads. string sequencing_tech - the sequencing technology used to
           produce the reads. null if unknown. KBaseCommon.StrainInfo strain
           - information about the organism strain that was sequenced. null
           if unavailable. KBaseCommon.SourceInfo source - information about
           the organism source. null if unavailable. float insert_size_mean -
           the mean size of the genetic fragments. null if unavailable or
           single end reads. float insert_size_std_dev - the standard
           deviation of the size of the genetic fragments. null if
           unavailable or single end reads. int read_count - the number of
           reads in the this dataset. null if unavailable. int read_size -
           the total size of the reads, in bases. null if unavailable. float
           gc_content - the GC content of the reads. null if unavailable.) ->
           structure: parameter "files" of type "ReadsFiles" (Reads file
           locations and gzip status. Only the relevant fields will be
           present in the structure. string fwd - the path to the forward /
           left reads. string rev - the path to the reverse / right reads.
           string inter - the path to the interleaved reads. string sing -
           the path to the single end reads. bool fwd_gz - whether the
           forward / left reads are gzipped. bool rev_gz - whether the
           reverse / right reads are gzipped. bool inter_gz - whether the
           interleaved reads are gzipped. bool sing_gz - whether the single
           reads are gzipped.) -> structure: parameter "fwd" of String,
           parameter "rev" of String, parameter "inter" of String, parameter
           "sing" of String, parameter "fwd_gz" of type "bool" (A boolean.
           Allowed values are 'false' or 'true'. Any other value is
           invalid.), parameter "rev_gz" of type "bool" (A boolean. Allowed
           values are 'false' or 'true'. Any other value is invalid.),
           parameter "inter_gz" of type "bool" (A boolean. Allowed values are
           'false' or 'true'. Any other value is invalid.), parameter
           "sing_gz" of type "bool" (A boolean. Allowed values are 'false' or
           'true'. Any other value is invalid.), parameter "ref" of String,
           parameter "single_genome" of type "tern" (A ternary. Allowed
           values are 'false', 'true', or null. Any other value is invalid.),
           parameter "read_orientation_outward" of type "tern" (A ternary.
           Allowed values are 'false', 'true', or null. Any other value is
           invalid.), parameter "sequencing_tech" of String, parameter
           "strain" of type "StrainInfo" (Information about a strain.
           genetic_code - the genetic code of the strain. See
           http://www.ncbi.nlm.nih.gov/Taxonomy/Utils/wprintgc.cgi?mode=c
           genus - the genus of the strain species - the species of the
           strain strain - the identifier for the strain source - information
           about the source of the strain organelle - the organelle of
           interest for the related data (e.g. mitochondria) ncbi_taxid - the
           NCBI taxonomy ID of the strain location - the location from which
           the strain was collected @optional genetic_code source ncbi_taxid
           organelle location) -> structure: parameter "genetic_code" of
           Long, parameter "genus" of String, parameter "species" of String,
           parameter "strain" of String, parameter "organelle" of String,
           parameter "source" of type "SourceInfo" (Information about the
           source of a piece of data. source - the name of the source (e.g.
           NCBI, JGI, Swiss-Prot) source_id - the ID of the data at the
           source project_id - the ID of a project encompassing the data at
           the source @optional source source_id project_id) -> structure:
           parameter "source" of String, parameter "source_id" of type
           "source_id" (An ID used for a piece of data at its source. @id
           external), parameter "project_id" of type "project_id" (An ID used
           for a project encompassing a piece of data at its source. @id
           external), parameter "ncbi_taxid" of Long, parameter "location" of
           type "Location" (Information about a location. lat - latitude of
           the site, recorded as a decimal number. North latitudes are
           positive values and south latitudes are negative numbers. lon -
           longitude of the site, recorded as a decimal number. West
           longitudes are positive values and east longitudes are negative
           numbers. elevation - elevation of the site, expressed in meters
           above sea level. Negative values are allowed. date - date of an
           event at this location (for example, sample collection), expressed
           in the format YYYY-MM-DDThh:mm:ss.SSSZ description - a free text
           description of the location and, if applicable, the associated
           event. @optional date description) -> structure: parameter "lat"
           of Double, parameter "lon" of Double, parameter "elevation" of
           Double, parameter "date" of String, parameter "description" of
           String, parameter "source" of type "SourceInfo" (Information about
           the source of a piece of data. source - the name of the source
           (e.g. NCBI, JGI, Swiss-Prot) source_id - the ID of the data at the
           source project_id - the ID of a project encompassing the data at
           the source @optional source source_id project_id) -> structure:
           parameter "source" of String, parameter "source_id" of type
           "source_id" (An ID used for a piece of data at its source. @id
           external), parameter "project_id" of type "project_id" (An ID used
           for a project encompassing a piece of data at its source. @id
           external), parameter "insert_size_mean" of Double, parameter
           "insert_size_std_dev" of Double, parameter "read_count" of Long,
           parameter "read_size" of Long, parameter "gc_content" of Double
        """
        # ctx is the context object
        # return variables are: output
        #BEGIN convert_read_library_to_file
        ''' potential improvements:
            Add continue_on_failure mode that reports errors for each failed
                conversion rather than failing completely.
            Parallelize - probably not worth it, this is all IO bound. Try if
                there's nothing better to do. If so, each process/thread needs
                its own shock_tmp folder.
            Add user specified failure conditions - e.g. fail if is/is not
                metagenome, outwards reads, etc.
        '''

        self.log('Running convert_read_library_to_file with params:\n' +
                 pformat(params))

        token = ctx['token']

        self.process_params(params)
#         self.log('\n' + pformat(params))

        # Get the reads library
        ws = workspaceService(self.workspaceURL, token=token)
        ws_reads_ids = []
        for read_name in params[self.PARAM_IN_LIB]:
            ws_reads_ids.append({'ref': read_name})
        try:
            reads = ws.get_objects(ws_reads_ids)
        except WorkspaceException as e:
            self.log('Logging stacktrace from workspace exception:\n' + e.data)
            raise

        output = {}
        for read_name, read in zip(params[self.PARAM_IN_LIB], reads):
            self.log('=== processing read library ' + read_name + '===\n',
                     prefix_newline=True)
            output[read_name] = self.process_reads(
                read, params[self.PARAM_IN_GZIP],
                params[self.PARAM_IN_INTERLEAVED], token)
        output = {'files': output}
        #END convert_read_library_to_file

        # At some point might do deeper type checking...
        if not isinstance(output, dict):
            raise ValueError('Method convert_read_library_to_file return value ' +
                             'output is not type dict as required.')
        # return the results
        return [output]

    def status(self, ctx):
        #BEGIN_STATUS
        returnVal = {'state': 'OK',
                     'message': '',
                     'version': self.VERSION,
                     'git_url': self.GIT_URL,
                     'git_commit_hash': self.GIT_COMMIT_HASH}
        ctx['token']  # shut up pep8
        #END_STATUS
        return [returnVal]


text:
import struct
import factor_graph_pb2
import random

NVAR = 100000

fo = open("lr_learn_dep/graph.variables.pb", "wb")
for i in range(0,NVAR):
	v = factor_graph_pb2.Variable()
	v.id = i
	v.initialValue = 1
	if random.random() < 0.8:
		v.initialValue = 0
	v.dataType = 0
	v.isEvidence = True
	v.cardinality = 1
	size = v.ByteSize()
	fo.write(struct.pack("i", size + 3))
	fo.write(v.SerializeToString())
for i in range(NVAR,2*NVAR):
	v = factor_graph_pb2.Variable()
	v.id = i
	v.initialValue = 0
	v.dataType = 0
	v.isEvidence = False
	v.cardinality = 1
	size = v.ByteSize()
	fo.write(struct.pack("i", size + 3))
	fo.write(v.SerializeToString())
	#break
fo.close()

fo = open("lr_learn_dep/graph.factors.pb", "wb")
for i in range(0,NVAR):
	f = factor_graph_pb2.Factor()
	f.id = i
	f.weightId = 0
	f.factorFunction = 0
	fo.write(struct.pack("i", f.ByteSize()+3))
	fo.write(f.SerializeToString())
fo.close()

fo = open("lr_learn_dep/graph.edges.pb", "wb")
for i in range(0,NVAR):
	e = factor_graph_pb2.GraphEdge()
	e.variableId = i
	e.factorId = i
	e.position = 1
	e.isPositive = True
	fo.write(struct.pack("i", e.ByteSize()+3))
	fo.write(e.SerializeToString())
	e = factor_graph_pb2.GraphEdge()
	e.variableId = i+NVAR
	e.factorId = i
	e.position = 0
	e.isPositive = True
	fo.write(struct.pack("i", e.ByteSize()+3))
	fo.write(e.SerializeToString())
fo.close()

fo = open("lr_learn_dep/graph.weights.pb", "wb")
w = factor_graph_pb2.Weight()
w.id = 0
w.initialValue = 0
w.isFixed = False
fo.write(struct.pack("i", w.ByteSize()+3))
fo.write(w.SerializeToString())
fo.close()


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyApp.Repository
{
    public interface IRepositoryIntegerKey<TValue> : IRepository<TValue, int>
        where TValue: class
    {
    }
}


text:
package algorithms.trees;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;

public class BreadthFirstSearch<T extends Comparable<T>> implements Iterator<Node<T>> {

  private final Queue<Node<T>> nodeQueue;

  BreadthFirstSearch(Node<T> rootNode) {
    nodeQueue = new LinkedList<>();
    nodeQueue.add(rootNode);
  }

  @Override
  public boolean hasNext() {
    return nodeQueue.size() > 0;
  }

  @Override
  public Node<T> next() {
    Node<T> resultNode = nodeQueue.poll();
    nodeQueue.addAll(resultNode.getDescendats());
    return resultNode;
  }
}


text:
Indent and colorize json input

![example](http://i.imgur.com/LbkORju.png)

## Installing

    go install github.com/luizbranco/prettyjson

## Prettifying

### Using unix pipes

    cat file.json | prettyjson

### Reading files

    prettyjson file.json

### Adding colors

    prettyjson --color file.json // -c for short


text:
package org.apache.camel.core.osgi;

import org.apache.camel.spi.ClassResolver;
import org.apache.camel.spi.FactoryFinder;
import org.apache.camel.spi.FactoryFinderResolver;
import org.osgi.framework.BundleContext;

public class OsgiFactoryFinderResolver implements FactoryFinderResolver {

    private final BundleContext bundleContext;

    public OsgiFactoryFinderResolver(BundleContext bundleContext) {
        this.bundleContext = bundleContext;
    }

    @Override
    public FactoryFinder resolveDefaultFactoryFinder(ClassResolver classResolver) {
        return resolveFactoryFinder(classResolver, "META-INF/services/org/apache/camel/");
    }

    @Override
    public FactoryFinder resolveFactoryFinder(ClassResolver classResolver, String resourcePath) {
        return new OsgiFactoryFinder(bundleContext, classResolver, resourcePath);
    }

}


text:
<?php

namespace Centipede\Extractor;

class UrlExtractor implements ExtractorInterface
{
    public function extract($value)
    {
        $urls = [];

        $document = new \DOMDocument();

        libxml_use_internal_errors(true);
        $document->loadHTML($value);
        libxml_use_internal_errors(false);

        foreach ($document->getElementsByTagName('a') as $node) {
            $urls[] = $node->getAttribute('href');
        }

        return $urls;
    }
}


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Javascript implementation of Steven Fortune's algorithm to compute Voronoi diagrams: Demo 1</title>
<meta name="Keywords" lang="en" content="voronoi, fortune, javascript, raymond hill"/>

Javascript implementation of Steven Fortune's algorithm to compute Voronoi diagrams
Demo 1: measuring peformance

< Back to main page

Demo 1: measuring peformance

Demo 2: a bit of interactivity

Demo 3: Fancy tiling

Demo 4: Looking up a Voronoi cell using a quadtree

Demo 5: Lloyd's relaxation

Comments

Sites generator

<input type="button" value="Generate" onclick="VoronoiDemo.randomSites(parseInt(document.getElementById('voronoiNumberSites').value,10),true);VoronoiDemo.render();"/> or <input type="button" value="Add" onclick="VoronoiDemo.randomSites(parseInt(document.getElementById('voronoiNumberSites').value,10),false);VoronoiDemo.render();"/><input id="voronoiNumberSites" type="text" value="100" size="5" maxlength="5"/> sites randomly (Warning: performance might suffer the more sites you add.)

<input id="voronoiClearSites" type="button" value="Clear all sites" onclick="VoronoiDemo.clearSites();VoronoiDemo.render();"/>

Canvas

You need to enable Javascript in your browser for this page to display properly.
<canvas id="voronoiCanvas" width="800" height="600" onclick="VoronoiDemo.recompute();"></canvas>

Your browser doesn't support the HTML5 <canvas> element technology.

See Wikipedia for information on which browsers support the HTML5 <canvas> technology.

Javascript source code for this page

<script type="text/javascript" src="rhill-voronoi-core.js"></script>
...

...


text:
namespace MakerJsPlayground {

    //classes

    class QueryStringParams {

        constructor(querystring: string = document.location.search.substring(1)) {
            if (querystring) {
                var pairs = querystring.split('&');
                for (var i = 0; i < pairs.length; i++) {
                    var pair = pairs[i].split('=');
                    this[pair[0]] = decodeURIComponent(pair[1]);
                }
            }
        }
    }

    //interfaces

    interface ILockedPath {
        route: string[];
        notes: string;
    }

    interface IProcessedResult {
        html: string;
        kit: MakerJs.IKit;
        model: MakerJs.IModel;
        measurement: MakerJs.IMeasure;
        paramValues: any[],
        lockedPath?: ILockedPath;
        error?: string;
    }

    interface RuntimeError {
        stack: string;
    }

    export interface IJavaScriptErrorDetails {
        colno: number;
        lineno: number;
        message: string;
        name: string;
    }

    //private members
    var minDockSideBySide = 1024;
    var pixelsPerInch = 100;
    var iframe: HTMLIFrameElement;
    var customizeMenu: HTMLDivElement;
    var view: HTMLDivElement;
    var viewSvgContainer: HTMLDivElement;
    var gridPattern: Element;
    var gridPatternFill: Element;
    var paramsDiv: HTMLDivElement;
    var measurementDiv: HTMLDivElement;
    var progress: HTMLDivElement;
    var preview: HTMLTextAreaElement;
    var checkFitToScreen: HTMLInputElement;
    var checkShowGrid: HTMLInputElement;
    var checkNotes: HTMLInputElement;
    var margin: MakerJs.IPoint;
    var processed: IProcessedResult = {
        error: '',
        html: '',
        kit: null,
        model: null,
        measurement: null,
        paramValues: []
    };
    var init = true;
    var errorMarker: CodeMirror.TextMarker;
    var exportWorker: Worker = null;
    var paramActiveTimeout: NodeJS.Timer;
    var longHoldTimeout: NodeJS.Timer;
    var viewModelRootSelector = 'svg#drawing > g > g > g';
    var viewOrigin: MakerJs.IPoint;
    var viewPanOffset: MakerJs.IPoint = [0, 0];
    var keepEventElement: HTMLElement = null;
    var renderInWorker = {
        requestId: 0,
        worker: <Worker>null,
        hasKit: false
    };
    var setParamTimeoutId: NodeJS.Timer;
    var setProcessedModelTimer: NodeJS.Timer;
    var animationTimeoutId: NodeJS.Timer;
    var dockModes = {
        None: '',
        SideBySide: 'side-by-side',
        FullScreen: 'full-screen'
    }

    function isLandscapeOrientation() {
        return (Math.abs(<number>window.orientation) == 90) || window.orientation == 'landscape';
    }

    function isHttp(url: string): boolean {
        return "http" === url.substr(0, 4);
    }

    function isIJavaScriptErrorDetails(result: any) {
        if (!result) return false;

        var sample: IJavaScriptErrorDetails = {
            colno: 0,
            lineno: 0,
            message: '',
            name: ''
        };

        for (var key in sample) {
            if (!(key in result)) {
                return false;
            }
        }

        return true;
    }

    function populateParams(metaParameters: MakerJs.IMetaParameter[]) {

        var paramValues = [];
        var paramHtml: string[] = [];

        if (metaParameters) {

            var sliders = 0;

            for (var i = 0; i < metaParameters.length; i++) {
                var attrs = makerjs.cloneObject(metaParameters[i]);

                var id = 'input_param_' + i;
                var prepend = false;
                var input: MakerJs.exporter.XmlTag = null;
                var numberBox: MakerJs.exporter.XmlTag = null;

                switch (attrs.type) {

                    case 'range':
                        sliders++;

                        attrs['id'] = id;
                        attrs['onchange'] = 'MakerJsPlayground.setParam(' + i + ', makerjs.round(this.valueAsNumber, .001)); if (MakerJsPlayground.isSmallDevice()) { MakerJsPlayground.activateParam(this); MakerJsPlayground.deActivateParam(this, 1000); }';
                        attrs['ontouchstart'] = 'MakerJsPlayground.activateParam(this)';
                        attrs['ontouchend'] = 'MakerJsPlayground.deActivateParam(this, 1000)';
                        attrs['onmousedown'] = 'if (MakerJsPlayground.isSmallDevice()) { MakerJsPlayground.activateParam(this); }';
                        attrs['onmouseup'] = 'if (MakerJsPlayground.isSmallDevice()) { MakerJsPlayground.deActivateParam(this, 1000); }';

                        input = new makerjs.exporter.XmlTag('input', attrs);

                        //note: we could also apply the min and max of the range to the number field. however, the useage of the textbox is to deliberately "go out of bounds" when the example range is insufficient.
                        var numberBoxAttrs = {
                            "id": 'numberbox_' + i,
                            "type": 'number',
                            "step": 'any',
                            "value": attrs.value,
                            "onfocus": 'if (MakerJsPlayground.isSmallDevice()) { MakerJsPlayground.activateParam(this.parentElement); }',
                            "onblur": 'if (MakerJsPlayground.isSmallDevice()) { MakerJsPlayground.deActivateParam(this.parentElement, 0); }',
                            "onchange": 'MakerJsPlayground.setParam(' + i + ', makerjs.round(this.value, .001))'
                        };

                        var formAttrs = {
                            "action": 'javascript:void(0);',
                            "onsubmit": 'MakerJsPlayground.setParam(' + i + ', makerjs.round(this.elements[0].value, .001))'
                        };

                        numberBox = new makerjs.exporter.XmlTag('form', formAttrs);
                        numberBox.innerText = new makerjs.exporter.XmlTag('input', numberBoxAttrs).toString();
                        numberBox.innerTextEscaped = true;

                        paramValues.push(attrs.value);

                        break;

                    case 'bool':

                        var checkboxAttrs = {
                            type: 'checkbox',
                            onchange: 'MakerJsPlayground.setParam(' + i + ', this.checked)'
                        };

                        if (attrs.value) {
                            checkboxAttrs['checked'] = true;
                        }

                        input = new makerjs.exporter.XmlTag('input', checkboxAttrs);

                        paramValues.push(attrs.value);

                        prepend = true;

                        break;

                    case 'font':

                        var selectFontAttrs = {
                            id: id,
                            onchange: 'MakerJsPlayground.setParam(' + i + ', this.options[this.selectedIndex].value)'
                        };

                        input = new makerjs.exporter.XmlTag('select', selectFontAttrs);
                        var fontOptions = '';

                        var added = false;

                        for (var fontId in fonts) {
                            var font = fonts[fontId];

                            if (!FontLoader.fontMatches(font, attrs.value)) continue;

                            if (!added) {
                                paramValues.push(fontId);
                                added = true;
                            }
                            var option = new makerjs.exporter.XmlTag('option', { value: fontId });
                            option.innerText = font.displayName;
                            options += option.toString();
                        }

                        input.innerText = options;
                        input.innerTextEscaped = true;

                        break;

                    case 'select':

                        var selectAttrs = {
                            id: id,
                            onchange: 'MakerJsPlayground.setParam(' + i + ', JSON.parse(this.options[this.selectedIndex].innerText))'
                        };

                        input = new makerjs.exporter.XmlTag('select', selectAttrs);
                        var options = '';

                        for (var j = 0; j < attrs.value.length; j++) {
                            var option = new makerjs.exporter.XmlTag('option');
                            option.innerText = JSON.stringify(attrs.value[j]);

                            options += option.toString();
                        }

                        input.innerText = options;
                        input.innerTextEscaped = true;

                        paramValues.push(attrs.value[0]);

                        break;

                    case 'text':

                        attrs['id'] = id;
                        attrs['onchange'] = 'MakerJsPlayground.setParam(' + i + ', this.value)';

                        input = new makerjs.exporter.XmlTag('input', attrs);

                        paramValues.push(attrs.value);

                        break;
                }

                if (!input) continue;

                var div = new makerjs.exporter.XmlTag('div');
                var label = new makerjs.exporter.XmlTag('label');
                label.innerText = attrs.title;

                if (prepend) {
                    var innerText = input.toString() + ' ' + label.getInnerText();
                    label.innerText = innerText;
                    label.innerTextEscaped = true;
                    div.innerText = label.toString();
                } else {
                    label.attrs = { "for": id };
                    label.innerText += ': ';
                    div.innerText = label.toString() + input.toString();
                }

                if (numberBox) {
                    div.innerText += numberBox.toString();
                }

                div.innerTextEscaped = true;
                paramHtml.push(div.toString());
            }

            //if (sliders) {
            //var button = new makerjs.exporter.XmlTag('input', { type: 'button', onclick:'MakerJsPlayground.animate()', value: 'animate'});
            //paramHtml.push(button.toString());
            //}
        }

        processed.paramValues = paramValues;

        if (paramHtml.length) {
            document.body.classList.add('show-params-link');
        } else {
            document.body.classList.remove('show-params-link');
        }

        paramsDiv.innerHTML = paramHtml.join('');

        saveParamsLink();

        paramsDiv.setAttribute('disabled', 'true');
    }

    function generateCodeFromKit(id: string, kit: MakerJs.IKit, paramValues: any[]): string {
        var values: string[] = [];
        var comment: string[] = [];
        var code: string[] = [];

        var firstComment = "//" + id + " parameters: ";

        for (var i in kit.metaParameters) {
            comment.push(firstComment + kit.metaParameters[i].title);
            firstComment = "";

            var value: any;

            if (kit.metaParameters[i].type === 'font') {
                value = 'font';

            } else {
                value = kit.metaParameters[i].value;

                if (kit.metaParameters[i].type === 'select') {
                    value = value[0];
                }

                value = JSON.stringify(value);
            }

            values.push(value);

            if (paramValues && paramValues.length >= values.length) {
                values[values.length - 1] = paramValues[values.length - 1];
            }
        }

        code.push("var makerjs = require('makerjs');");
        code.push("");
        code.push("/* Example:");
        code.push("");
        code.push(comment.join(", "));
        code.push("var my" + id + " = new makerjs.models." + id + "(" + values.join(', ') + ");");
        code.push("");
        code.push("*/");
        code.push("");
        code.push("module.exports = makerjs.models." + id + ";");

        return code.join('\n');
    }

    function resetDownload() {
        cancelExport();
        document.body.classList.remove('download-ready');
    }

    class Frown implements MakerJs.IModel {
        public paths: MakerJs.IPathMap;

        constructor() {
            this.paths = {
                head: new makerjs.paths.Circle([0, 0], 85),
                eye1: new makerjs.paths.Circle([-25, 25], 10),
                eye2: new makerjs.paths.Circle([25, 25], 10),
                frown: new makerjs.paths.Arc([0, -75], 50, 45, 135)
            };
        }
    }

    class StraightFace implements MakerJs.IModel {
        public paths: MakerJs.IPathMap;

        constructor() {
            this.paths = {
                head: new makerjs.paths.Circle([0, 0], 85),
                eye1: new makerjs.paths.Circle([-25, 25], 10),
                eye2: new makerjs.paths.Circle([25, 25], 10),
                mouth: new makerjs.paths.Line([-30, -30], [30, -30])
            };
        }
    }

    class Wait implements MakerJs.IModel {
        public models: MakerJs.IModelMap;

        constructor() {
            var wireFrame: MakerJs.IModel = {
                paths: {
                    rim: new makerjs.paths.Circle([0, 0], 85),
                    hand1: new makerjs.paths.Line([0, 0], [40, 30]),
                    hand2: new makerjs.paths.Line([0, 0], [0, 60])
                }
            };

            this.models = {
                x: makerjs.model.expandPaths(wireFrame, 5)
            }
        }
    }

    function highlightCodeError(error: IJavaScriptErrorDetails) {

        var notes = '';

        if (error.lineno || error.colno) {
            notes = error.name + ' at line ' + error.lineno + ' column ' + error.colno + ' : ' + error.message;

            var editorLine = error.lineno - 1;

            var from: CodeMirror.Position = {
                line: editorLine, ch: error.colno - 1
            };

            var line = codeMirrorEditor.getDoc().getLine(editorLine);

            var to: CodeMirror.Position = {
                line: editorLine, ch: line ? line.length : 0
            };

            errorMarker = codeMirrorEditor.getDoc().markText(from, to, { title: error.message, clearOnEnter: true, className: 'code-error' });

        } else {
            notes = error.name + ' : ' + error.message;
        }

        viewScale = null;

        setProcessedModel(new Frown(), notes);
    }

    function dockEditor(newDockMode: string) {

        for (var modeId in dockModes) {
            var dm = dockModes[modeId];
            if (!dm) continue;
            if (newDockMode === dm) {
                document.body.classList.add(dm);
            } else {
                document.body.classList.remove(dm);
            }
        }

        if (newDockMode === dockModes.SideBySide) {

            var sectionEditor = document.querySelector('section.editor') as HTMLElement;
            var codeHeader = document.querySelector('.code-header') as HTMLElement;

            codeMirrorEditor.setSize(null, sectionEditor.offsetHeight - codeHeader.offsetHeight);
        } else {

            codeMirrorEditor.setSize(null, 'auto');
            codeMirrorEditor.refresh();
        }

        dockMode = newDockMode;
    }

    function arraysEqual(a, b) {
        if (!a || !b) return false;
        if (a.length != b.length) return false;

        for (var i = 0; i < a.length; ++i) {
            if (a[i] !== b[i]) return false;
        }
        return true;
    }

    function lockToPath(path: Node) {

        //trace back to root
        var root = viewSvgContainer.querySelector(viewModelRootSelector) as SVGGElement;
        var route: string[] = [];
        var element = path;

        while (element !== root) {
            var id = element.attributes.getNamedItem('id').value

            route.unshift(id);

            if (element.nodeName == 'g') {
                route.unshift('models');
            } else {
                route.unshift('paths');
            }
            element = element.parentNode;
        }

        if (processed.lockedPath && arraysEqual(processed.lockedPath.route, route)) {

            processed.lockedPath = null;
            setNotesFromModelOrKit();

        } else {

            var crumb = 'this';
            for (var i = 0; i < route.length; i++) {
                if (i % 2 == 0) {
                    crumb += "." + route[i];
                } else {
                    crumb += '["' + route[i] + '"]';
                }
            }

            processed.lockedPath = {
                route: route,
                notes: "Path Info|\n---|---\nRoute|``` " + crumb + " ```\nJSON|"
            };

            updateLockedPathNotes();
        }

        render();

        if (onViewportChange) {
            onViewportChange();
        }

    }

    function getLockedPathSvgElement() {
        var root = viewSvgContainer.querySelector(viewModelRootSelector) as SVGGElement;
        var selector = '';

        for (var i = 0; i < processed.lockedPath.route.length - 2; i += 2) {
            selector += " g[id='" + processed.lockedPath.route[i + 1] + "']";
        }

        selector += " [id='" + processed.lockedPath.route[processed.lockedPath.route.length - 1] + "']";

        return root.querySelector(selector) as HTMLElement;
    }

    function getLockedPathAndOffset() {
        if (!processed.lockedPath) return null;

        var ref = processed.model;
        var origin = processed.model.origin || [0, 0];

        var route = processed.lockedPath.route.slice();

        while (route.length) {
            var prop = route.shift();
            ref = ref[prop];

            if (!ref) return null;

            if (ref.origin && route.length) {
                origin = makerjs.point.add(origin, ref.origin);
            }
        }

        return {
            path: <MakerJs.IPath>ref,
            offset: origin
        };
    }

    function updateLockedPathNotes() {
        if (processed.model && processed.lockedPath) {
            var pathAndOffset = getLockedPathAndOffset();
            if (pathAndOffset) {
                setNotes(processed.lockedPath.notes + "``` " + JSON.stringify(pathAndOffset.path) + "```\nOffset|```" + JSON.stringify(pathAndOffset.offset) + "```");
            } else {
                setNotesFromModelOrKit();
            }
            return true;
        }
        return false;
    }

    function measureLockedPath(): MakerJs.IMeasure {
        var pathAndOffset = getLockedPathAndOffset();
        if (!pathAndOffset) return null;

        var measure = makerjs.measure.pathExtents(pathAndOffset.path);
        measure.high = makerjs.point.add(measure.high, pathAndOffset.offset);
        measure.low = makerjs.point.add(measure.low, pathAndOffset.offset);

        return measure;
    }

    function getModelNaturalSize(): MakerJs.IPoint {
        var measure = processed.measurement;
        var modelWidthNatural = measure.high[0] - measure.low[0];
        var modelHeightNatural = measure.high[1] - measure.low[1];
        return [modelWidthNatural, modelHeightNatural];
    }

    function getViewSize(): MakerJs.IPoint {
        var viewHeight = view.offsetHeight - 2 * margin[1];
        var viewWidth = view.offsetWidth - 2 * margin[0];
        var menuLeft = customizeMenu.offsetLeft - 2 * margin[0];

        var width = viewWidth;

        //view mode - left of menu
        if (!document.body.classList.contains('collapse-rendering-options') && menuLeft > 100) {
            width = menuLeft;
        }

        return [width, viewHeight];
    }

    function areSameHeightMeasurement(a: MakerJs.IMeasure, b: MakerJs.IMeasure) {
        return a.high[1] == b.high[1] && a.low[1] == b.low[1];
    }

    function initialize() {

        window.addEventListener('resize', onWindowResize);
        window.addEventListener('orientationchange', onWindowResize);

        pointers = new Pointer.Manager(view, '#pointers', margin, getZoom, setZoom, onPointerClick, onPointerReset);

        if (onInit) {
            onInit();
        }
    }

    function onPointerClick(srcElement: Element) {
        if (!keepEventElement && srcElement && srcElement.tagName && srcElement.tagName == 'text') {

            var text = srcElement as SVGTextElement;
            var path = text.previousSibling;

            lockToPath(path);
        }
    }

    function onPointerReset() {

        if (keepEventElement) {
            view.removeChild(keepEventElement);
        }

        keepEventElement = null;
    }

    function getZoom(): Pointer.IPanZoom {

        return {
            origin: viewOrigin,
            pan: viewPanOffset,
            zoom: viewScale
        };
    }

    function setZoom(panZoom: Pointer.IPanZoom) {

        if (document.body.classList.contains('wait')) return;

        var svgElement = viewSvgContainer.children[0] as HTMLElement;
        if (!svgElement) return;

        checkFitToScreen.checked = false;

        viewPanOffset = panZoom.pan;

        if (panZoom.zoom == viewScale) {
            //just pan

            //no need to re-render, just move the margin
            svgElement.style.marginLeft = viewPanOffset[0] + 'px';
            svgElement.style.marginTop = viewPanOffset[1] + 'px';

            panGrid();

        } else {
            //zoom and pan

            if (!keepEventElement) {
                keepEventElement = svgElement;
                viewSvgContainer.removeChild(keepEventElement);
                keepEventElement.style.visibility = 'hidden';
                this.view.appendChild(keepEventElement);
            }

            viewScale = panZoom.zoom;

            updateZoomScale();

            render();
        }
    }

    function getGridScale() {
        var gridScale = 1;

        while (viewScale * gridScale < 6) {
            gridScale *= 10;
        }

        while (viewScale * gridScale > 60) {
            gridScale /= 10;
        }

        return gridScale;
    }

    function zoomGrid() {
        var gridScale = (getGridScale() * 10 * viewScale).toString();

        gridPattern.setAttribute('width', gridScale);
        gridPattern.setAttribute('height', gridScale);

        gridPatternFill.setAttribute('width', gridScale);
        gridPatternFill.setAttribute('height', gridScale);
    }

    function panGrid() {
        var p = makerjs.point.add(viewPanOffset, viewOrigin);
        gridPattern.setAttribute('patternTransform', 'translate(' + p[0] + ',' + p[1] + ')');
    }

    function getUnits() {
        if (processed.model && processed.model.units) {
            return processed.model.units;
        }
        return null;
    }

    function isMeasurementEqual(m1: MakerJs.IMeasure, m2: MakerJs.IMeasure): boolean {
        if (!m1 && !m2) return true;
        if (!m1 || !m2) return false;
        if (!makerjs.measure.isPointEqual(m1.low, m2.low)) return false;
        if (!makerjs.measure.isPointEqual(m1.high, m2.high)) return false;
        return true;
    }

    function setProcessedModel(model: MakerJs.IModel, error?: string) {
        clearTimeout(setProcessedModelTimer);

        var oldUnits = getUnits();
        var oldMeasurement = processed.measurement;

        processed.model = model;
        processed.measurement = null;
        processed.error = error;

        var newUnits = getUnits();

        if (!error) {
            if (errorMarker) {
                errorMarker.clear();
                errorMarker = null;
            }
        }

        if (!processed.model) return;

        //now safe to render, so register a resize listener
        if (init && model) {
            init = false;

            initialize();
        }

        //todo: find minimum viewScale

        var newMeasurement = makerjs.measure.modelExtents(processed.model);
        processed.measurement = newMeasurement;

        if (!processed.measurement) {
            setProcessedModelTimer = setTimeout(function () {
                setProcessedModel(new StraightFace(), 'Your model code was processed, but it resulted in a model with no measurement. It probably does not have any paths. Here is the JSON representation: \n\n```' + JSON.stringify(processed.model) + '```');
            }, 2500);
            return;
        }

        if ((!viewScale || oldUnits != newUnits) || (!isMeasurementEqual(oldMeasurement, newMeasurement) && checkFitToScreen.checked)) {
            fitOnScreen();
        }

        document.body.classList.remove('wait');

        if (newUnits)
            document.body.classList.add('has-units');
        else {
            document.body.classList.remove('has-units');
        }

        render();

        var measureText: string;

        if (processed.error) {
            setNotes(processed.error);

            //sync notes and checkbox
            if (checkNotes) checkNotes.checked = true;
            document.body.classList.remove('collapse-notes');

            measureText = '';

        } else {
            var size = getModelNaturalSize();
            measureText = size[0].toFixed(2) + ' x ' + size[1].toFixed(2) + ' ' + (newUnits || 'units');

            if (!updateLockedPathNotes()) {
                setNotesFromModelOrKit();
            }
        }

        if (measurementDiv) {
            measurementDiv.innerText = measureText;
        }

        if (onViewportChange) {
            onViewportChange();
        }

    }

    function constructOnMainThread(successCb?: Function) {
        var fontLoader = new FontLoader(opentype, processed.kit.metaParameters, processed.paramValues);

        fontLoader.successCb = function (realValues: any[]) {
            constructOnMainThreadReal(realValues, successCb);
        };

        fontLoader.failureCb = function (id) {
            var errorDetails: MakerJsPlayground.IJavaScriptErrorDetails = {
                colno: 0,
                lineno: 0,
                message: 'error loading font' + fonts[id].path,
                name: 'Network error'
            };

            processResult({ result: errorDetails });
        }

        fontLoader.load();
    }

    function constructOnMainThreadReal(realValues: any[], successCb?: Function) {

        try {
            var model = makerjs.kit.construct(processed.kit, realValues);
            setProcessedModel(model);

            if (successCb) {
                successCb();
            }

        } catch (e) {
            var error = e as RuntimeError;

            var errorDetails: MakerJsPlayground.IJavaScriptErrorDetails = {
                colno: 0,
                lineno: 0,
                message: 'Parameters=' + JSON.stringify(processed.paramValues),
                name: e.toString()
            };

            //try to get column number and line number from stack
            var re = /([0-9]{1,9999})\:([0-9]{1,9999})/;
            var matches = re.exec(error.stack);
            if (matches && matches.length == 3) {
                errorDetails.lineno = parseInt(matches[1]);
                errorDetails.colno = parseInt(matches[2]);
            }

            processResult({ result: errorDetails });
        }
    }

    function constructInWorker(javaScript: string, orderedDependencies: string[], successHandler: (model: MakerJs.IModel) => void, errorHandler: () => void) {

        var idToUrlMap: { [id: string]: string };

        renderInWorker.hasKit = false;

        if (renderInWorker.worker) {
            renderInWorker.worker.terminate();
        }

        renderInWorker.worker = new Worker('worker/render-worker.js');
        renderInWorker.worker.onmessage = function (ev: MessageEvent) {
            var response = ev.data as MakerJsPlaygroundRender.IRenderResponse;
            if (response.error) {
                errorHandler();
            } else {
                renderInWorker.hasKit = true;
                processed.html = response.html;
                successHandler(response.model);
            }
        };

        idToUrlMap = {};
        for (var i = 0; i < orderedDependencies.length; i++) {
            //add extra path traversal for worker subfolder
            idToUrlMap[orderedDependencies[i]] = '../' + filenameFromRequireId(orderedDependencies[i], true);
        }

        var options: MakerJsPlaygroundRender.IRenderRequest = {
            requestId: 0,
            javaScript: javaScript,
            orderedDependencies: orderedDependencies,
            dependencyUrls: idToUrlMap,
            paramValues: processed.paramValues
        }

        //tell the worker to process the job
        renderInWorker.worker.postMessage(options);
    }

    function reConstructInWorker(successHandler: (model: MakerJs.IModel) => void, errorHandler: () => void) {

        if (!renderInWorker.hasKit) return;

        renderInWorker.worker.onmessage = function (ev: MessageEvent) {
            var response = ev.data as MakerJsPlaygroundRender.IRenderResponse;
            if (response.requestId == renderInWorker.requestId) {

                if (response.error) {
                    errorHandler();
                } else if (response.model) {
                    processed.html = response.html;
                    successHandler(response.model);
                }
            }
        };

        renderInWorker.requestId = new Date().valueOf();

        var options: MakerJsPlaygroundRender.IRenderRequest = {
            requestId: renderInWorker.requestId,
            paramValues: processed.paramValues
        }

        //tell the worker to process the job
        renderInWorker.worker.postMessage(options);
    }

    function getParamUIControl(index: number) {
        var div = document.querySelectorAll('#params > div')[index];
        if (!div) return;

        var checkbox = div.querySelector('input[type=checkbox]') as HTMLInputElement;
        var textbox = div.querySelector('input[type=text]') as HTMLInputElement;
        var select = div.querySelector('select') as HTMLSelectElement;
        var slider = div.querySelector('input[type=range]') as HTMLInputElement;
        var numberBox = div.querySelector('input[type=number]') as HTMLInputElement;

        return {
            classList: div.classList,
            range: slider,
            rangeText: numberBox,
            select: select,
            text: textbox,
            bool: checkbox
        };
    }

    function saveParamsLink() {
        var a = document.querySelector('#params-link') as HTMLAnchorElement;
        if (!a) return;

        a.hash = 'params=' + JSON.stringify(processed.paramValues);
    }

    function getHashParams() {
        var paramValues: any[];

        if (document.location.hash) {
            var hashParams = new QueryStringParams(document.location.hash.substring(1));
            var paramString = hashParams['params'];
            if (paramString) {
                paramValues = JSON.parse(paramString);
            }
        }

        return paramValues;
    }

    window.onhashchange = function () {
        var paramValues: any[];

        if (document.location.hash && document.location.hash.length > 1) {
            paramValues = getHashParams();
        } else if (processed.kit) {

            var fontLoader = new FontLoader(null, processed.kit.metaParameters, makerjs.kit.getParameterValues(processed.kit));
            paramValues = fontLoader.getParamValuesWithFontSpec();
        }

        setParamValues(paramValues, true);
    }

    function setParamValues(paramValues: any[], fit: boolean) {

        if (paramValues && paramValues.length) {

            for (var i = 0; i < paramValues.length; i++) {
                setParamIndex(i, paramValues[i], false);
            }

            finalizeSetParam(fit);
        }
    }

    function setParamIndex(index: number, value: any, fromUI: boolean) {

        //sync slider / numberbox
        var div = getParamUIControl(index);

        if (fromUI) {

            if (div.range && div.rangeText) {
                    div.range.value = value;
                    div.rangeText.value = value;
            }

        } else {

            if (div.range && div.rangeText) {
                div.rangeText.value = value;
                div.range.value = value;

            } else if (div.bool) {
                div.bool.checked = !!value;

            } else if (div.text) {
                div.text.value = value;

            } else if (div.select) {
                var select = div.select;
                for (var i = 0; i < select.options.length; i++) {
                    var optionValue = select.options[i].getAttribute('value');
                    if (optionValue == value) {
                        select.selectedIndex = i;
                        break;
                    }
                }
            }
        }

        processed.paramValues[index] = value;
    }

    function throttledSetParam(index: number, value: any) {

        setParamIndex(index, value, true);
        finalizeSetParam(false);
    }

    function finalizeSetParam(fit: boolean) {

        resetDownload();
        saveParamsLink();

        if (fit) {
            viewScale = null;
        }

        if (renderOnWorkerThread && Worker) {

            reConstructInWorker(
                setProcessedModel,
                constructOnMainThread
            );

        } else {
            constructOnMainThread();
        }
    }

    function setNotesFromModelOrKit() {
        setNotes(processed.model.notes || (processed.kit ? processed.kit.notes : ''));
    }

    //public members

    export var onInit: Function;
    export var onViewportChange: Function;
    export var fullScreen: boolean
    export var dockMode: string;
    export var codeMirrorEditor: CodeMirror.Editor;
    export var codeMirrorOptions: CodeMirror.EditorConfiguration = {
        lineNumbers: true,
        theme: 'twilight',
        viewportMargin: Infinity
    };
    export var relativePath = '';
    export var svgStrokeWidth = 2;
    export var svgFontSize = 14;
    export var viewScale: number;
    export var querystringParams: QueryStringParams;
    export var pointers: Pointer.Manager;
    export var renderOnWorkerThread = true;

    export function runCodeFromEditor(paramValues?: any[]) {

        document.body.classList.add('wait');

        processed.kit = null;
        populateParams(null);

        if (iframe) {
            document.body.removeChild(iframe);
        }

        iframe = document.createElement('iframe');
        iframe.style.display = 'none';

        document.body.appendChild(iframe);

        var scripts = ['../require-iframe.js', '../../external/bezier-js/bezier.js', '../../external/opentype/opentype.js'];

        iframe.contentWindow.document.open();
        iframe.contentWindow.document.write('<html><head>' + scripts.map(function (src) { return '<script src="' + src + '"></script>'; }).join() + '<script>var paramValues=' + JSON.stringify(paramValues) + ';</script></head><body></body></html>');
        iframe.contentWindow.document.close();
    }

    export function setNotes(obj: Object);
    export function setNotes(markdown: string);
    export function setNotes(value: any) {
        var markdown = '';

        if (typeof value === 'string') {
            markdown = value;
        } else {
            markdown = JSON.stringify(value);
        }

        var html = '';
        if (markdown) {
            html = marked(markdown);
        }

        html += cleanHtml(processed.html)

        setNotesHtml(html);
    }

    function setNotesHtml(html: string) {
        var className = 'no-notes';
        if (html) {
            document.body.classList.remove(className);
        } else {
            document.body.classList.add(className);
        }
        document.getElementById('notes').innerHTML = html;
    }

    export function updateZoomScale() {
        var unitScale = viewScale;

        if (processed.model.units) {
            //pixels to inch
            unitScale /= pixelsPerInch;

            //inch to units
            unitScale *= makerjs.units.conversionScale(makerjs.unitType.Inch, processed.model.units);
        }

        var z = document.getElementById('zoom-display');
        z.innerText = '[' + (unitScale * 100).toFixed(0) + '%]';

        var g = document.getElementById('grid-unit');
        if (checkShowGrid.checked) {
            var gridScale = makerjs.round(getGridScale());
            g.innerText = '[' + gridScale + ' ' + (processed.model.units || ('unit' + (gridScale < 10 ? '' : 's'))) + ']';
        } else {
            g.innerText = '';
        }
    }

    export interface IProcessResult {
        html?: string;
        result: any;
        orderedDependencies?: string[];
        paramValues?: any[];
    }

    export function processResult(value: IProcessResult) {

        var result = value.result;

        resetDownload();

        processed.html = value.html || '';

        setProcessedModel(null);

        //see if output is either a Node module, or a MakerJs.IModel
        if (typeof result === 'function') {

            processed.kit = result;
            populateParams(processed.kit.metaParameters);

            if (value.paramValues) {
                setParamValues(value.paramValues, false);
            }

            function enableKit() {
                paramsDiv.removeAttribute('disabled');
            }

            function setKitOnMainThread() {
                constructOnMainThread(enableKit);
            }

            if (renderOnWorkerThread && Worker) {

                constructInWorker(
                    codeMirrorEditor.getDoc().getValue(),
                    value.orderedDependencies,
                    function (model: MakerJs.IModel) {
                        enableKit();
                        setProcessedModel(model);
                    },
                    setKitOnMainThread
                );

            } else {
                setKitOnMainThread();
            }

        } else if (makerjs.isModel(result)) {
            processed.kit = null;
            populateParams(null);

            setProcessedModel(result);

        } else if (isIJavaScriptErrorDetails(result)) {

            //render script error
            highlightCodeError(result as IJavaScriptErrorDetails);

            if (onViewportChange) {
                onViewportChange();
            }
        } else {
            render();

            if (onViewportChange) {
                onViewportChange();
            }
        }

    }

    export function setParam(index: number, value: any) {
        clearTimeout(setParamTimeoutId);
        setParamTimeoutId = setTimeout(function () {
            throttledSetParam(index, value);
        }, 50);
    }

    export function animate(paramIndex: number = 0, milliSeconds: number = 150, steps = 20) {
        clearInterval(animationTimeoutId);

        var div = getParamUIControl(paramIndex);
        if (!div) return;
        if (!div.range) {
            animate(paramIndex + 1);
            return;
        }

        var max = parseFloat(div.range.max);
        var min = parseFloat(div.range.min);

        do {
            var step = Math.floor((max - min) / steps);
            steps /= 2;
        } while (step === 0)

        div.range.value = min.toString();

        animationTimeoutId = setInterval(function () {

            var currValue = parseFloat(div.range.value);

            if (currValue < max) {
                var newValue = currValue + step;
                div.range.value = newValue.toString();
                throttledSetParam(paramIndex, newValue);
            } else {
                animate(paramIndex + 1);
            }

        }, milliSeconds);
    }

    export function activateParam(input: HTMLInputElement, onLongHold: boolean = false) {

        function activate() {
            document.body.classList.add('param-active');
            input.parentElement.classList.add('active');
            clearTimeout(paramActiveTimeout);
        }

        if (onLongHold) {
            longHoldTimeout = setTimeout(activate, 200);
        } else {
            activate();
        }
    }

    export function deActivateParam(input: HTMLInputElement, delay: number) {

        clearTimeout(longHoldTimeout);
        clearTimeout(paramActiveTimeout);

        paramActiveTimeout = setTimeout(function () {
            document.body.classList.remove('param-active');
            input.parentElement.classList.remove('active');
        }, delay);
    }

    export function fitNatural() {

        if (pointers) pointers.reset();

        if (!processed.measurement) return;

        var size = getViewSize();
        var halfWidth = size[0] / 2;
        var modelNaturalSize = getModelNaturalSize();

        viewScale = 1;
        viewPanOffset = [0, 0];

        checkFitToScreen.checked = false;

        if (processed.model.units) {
            //convert from units to Inch
            viewScale = makerjs.units.conversionScale(processed.model.units, makerjs.unitType.Inch);

            //from inch to pixel
            viewScale *= pixelsPerInch;
        }

        halfWidth -= (modelNaturalSize[0] / 2 + processed.measurement.low[0]) * viewScale;

        viewOrigin = [halfWidth, processed.measurement.high[1] * viewScale];

        updateZoomScale();
    }

    export function fitOnScreen() {

        if (pointers) pointers.reset();

        if (!processed.measurement) return;

        var size = getViewSize();
        var halfWidth = size[0] / 2;
        var modelNaturalSize = getModelNaturalSize();

        viewScale = 1;
        viewPanOffset = [0, 0];

        checkFitToScreen.checked = true;

        var scaleHeight = size[1] / modelNaturalSize[1];
        var scaleWidth = size[0] / modelNaturalSize[0];

        viewScale *= Math.min(scaleWidth, scaleHeight);

        halfWidth -= (modelNaturalSize[0] / 2 + processed.measurement.low[0]) * viewScale;

        viewOrigin = [halfWidth, processed.measurement.high[1] * viewScale];

        updateZoomScale();
    }

    export function browserIsMicrosoft() {
        var clues = ['Edge/', 'Trident/'];

        for (var i = 0; i < clues.length; i++) {
            if (navigator.userAgent.indexOf(clues[i]) > 0) {
                return true;
            }
        }
        return false;
    }

    function cleanHtml(html: string) {
        if (!html) return '';

        var div = document.createElement('div');
        div.innerHTML = html;

        var svg = div.querySelector('svg');
        if (svg) {
            div.removeChild(svg);
            return div.innerHTML;
        }

        return html;
    }

    export function render() {

        viewSvgContainer.innerHTML = '';

        var html = '';

        var strokeWidth = svgStrokeWidth;

        if (processed.model) {

            var fontSize = svgFontSize;

            var renderOptions: MakerJs.exporter.ISVGRenderOptions = {
                origin: viewOrigin,
                annotate: true,
                svgAttrs: {
                    "id": 'drawing',
                    "style": 'margin-left:' + viewPanOffset[0] + 'px; margin-top:' + viewPanOffset[1] + 'px'
                },
                strokeWidth: strokeWidth + 'px',
                fontSize: fontSize + 'px',
                scale: viewScale,
                useSvgPathOnly: false
            };

            var renderModel: MakerJs.IModel = {
                models: {
                    ROOT: processed.model
                }
            };

            var size = getModelNaturalSize();
            var multiplier = 10;

            panGrid();
            zoomGrid();

            renderModel.paths = {
                'crosshairs-vertical': new makerjs.paths.Line([0, size[1] * multiplier], [0, -size[1] * multiplier]),
                'crosshairs-horizontal': new makerjs.paths.Line([size[0] * multiplier, 0], [- size[0] * multiplier, 0])
            };

            html += makerjs.exporter.toSVG(renderModel, renderOptions);
        }

        viewSvgContainer.innerHTML = html;

        if (processed.lockedPath) {
            var path = getLockedPathSvgElement();
            if (path) {
                path.setAttribute('class', 'locked');
                path.style.strokeWidth = (2 * strokeWidth) + 'px';
            }
        }

    }

    export function filenameFromRequireId(id: string, bustCache?: boolean): string {
        var filename = relativePath + id + '.js';
        if (bustCache) {
            filename += '?' + new Date().valueOf();
        }
        return filename;
    }

    export function downloadScript(url: string, callback: (download: string) => void) {

        var timeout = setTimeout(function () {
            x.onreadystatechange = null;

            var errorDetails: MakerJsPlayground.IJavaScriptErrorDetails = {
                colno: 0,
                lineno: 0,
                message: 'Could not load script "' + url + '". Possibly a network error, or the file does not exist.',
                name: 'Load module failure'
            };

            processResult({ result: errorDetails });

        }, 5000);

        var x = new XMLHttpRequest();
        x.open('GET', url, true);
        x.onreadystatechange = function () {
            if (x.readyState == 4 && x.status == 200) {
                clearTimeout(timeout);
                callback(x.responseText);
            }
        };
        x.send();
    }

    export function toggleClassAndResize(name: string) {
        toggleClass(name);
        onWindowResize();
    }

    export function toggleClass(name: string, element: HTMLElement = document.body): boolean {
        var c = element.classList;
        var result: boolean;

        if (c.contains(name)) {
            c.remove(name);
            result = true;
        } else {
            c.add(name);
            result = false;
        }

        return result;
    }

    function getExport(ev: MessageEvent) {
        var response = ev.data as MakerJsPlaygroundExport.IExportResponse;

        progress.style.width = response.percentComplete + '%';

        if (response.percentComplete == 100 && response.text) {

            //allow progress bar to render
            setTimeout(function () {
                var fe = MakerJsPlaygroundExport.formatMap[response.request.format];

                var encoded = encodeURIComponent(response.text);
                var uriPrefix = 'data:' + fe.mediaType + ',';
                var filename = (querystringParams['script'] || 'my-drawing') + '.' + fe.fileExtension;
                var dataUri = uriPrefix + encoded;

                //create a download link
                var a = new makerjs.exporter.XmlTag('a', { href: dataUri, download: filename });
                a.innerText = 'download ' + response.request.formatTitle;
                document.getElementById('download-link-container').innerHTML = a.toString();

                preview.value = response.text;

                (<HTMLSpanElement>document.getElementById('download-filename')).innerText = filename;

                //put the download ui into ready mode
                toggleClass('download-generating');
                toggleClass('download-ready');
            }, 300);

        }
    }

    export function downloadClick(a: HTMLAnchorElement, format: MakerJsPlaygroundExport.ExportFormat) {

        //TODO: show options
        //TODO: get options

        var request: MakerJsPlaygroundExport.IExportRequest = {
            format: format,
            formatTitle: a.innerText,
            model: processed.model,
            options: {}
        };

        _downloadClick(request);
    }

    function _downloadClick(request: MakerJsPlaygroundExport.IExportRequest) {

        //initialize a worker - this will download scripts into the worker
        if (!exportWorker) {
            exportWorker = new Worker('worker/export-worker.js?' + new Date().valueOf());
            exportWorker.onmessage = getExport;
        }

        //put the download ui into generation mode
        progress.style.width = '0';
        toggleClass('download-generating');

        //tell the worker to process the job
        exportWorker.postMessage(request);
    }

    export function copyToClipboard() {
        preview.select();
        document.execCommand('copy');
    }

    export function cancelExport() {
        if (exportWorker) {
            exportWorker.terminate();
            exportWorker = null;
        }
        document.body.classList.remove('download-generating');
    }

    export function isSmallDevice(): boolean {
        return document.body.clientWidth < 540;
    }

    export function onWindowResize() {
        if (checkFitToScreen.checked) {
            fitOnScreen();
            render();
        }

        if (fullScreen) {
            dockEditor(dockModes.FullScreen);
        } else if (document.body.offsetWidth < minDockSideBySide) {
            dockEditor(dockModes.None);
        } else {
            dockEditor(dockModes.SideBySide);
        }

    }

    //execution

    window.onload = function (ev) {

        if (window.orientation === void 0) {
            window.orientation = 'landscape';
        }

        //hide the customize menu when booting on small screens
        //if (document.body.clientWidth < 540) {
        //    document.body.classList.add('collapse-rendering-options');
        //}

        customizeMenu = document.getElementById('rendering-options-menu') as HTMLDivElement;
        view = document.getElementById('view') as HTMLDivElement;
        paramsDiv = document.getElementById('params') as HTMLDivElement;
        measurementDiv = document.getElementById('measurement') as HTMLDivElement;
        progress = document.getElementById('download-progress') as HTMLDivElement;
        preview = document.getElementById('download-preview') as HTMLTextAreaElement;
        checkFitToScreen = document.getElementById('check-fit-on-screen') as HTMLInputElement;
        checkShowGrid = document.getElementById('check-show-origin') as HTMLInputElement;
        checkNotes = document.getElementById('check-notes') as HTMLInputElement;
        viewSvgContainer = document.getElementById('view-svg-container') as HTMLDivElement;
        gridPattern = document.getElementById('gridPattern');
        gridPatternFill = document.getElementById('gridPatternFill');

        margin = [viewSvgContainer.offsetLeft, viewSvgContainer.offsetTop];

        gridPattern.setAttribute('x', margin[0].toString());
        gridPattern.setAttribute('y', margin[1].toString());

        var pre = document.getElementById('init-javascript-code') as HTMLPreElement;
        codeMirrorOptions.value = pre.innerText;
        codeMirrorEditor = CodeMirror(
            function (elt) {
                pre.parentNode.replaceChild(elt, pre);
            },
            codeMirrorOptions
        );

        if (fullScreen) {
            dockEditor(dockModes.FullScreen);
        } else if (document.body.offsetWidth >= minDockSideBySide) {
            dockEditor(dockModes.SideBySide);
        }

        document.body.classList.add('wait');

        querystringParams = new QueryStringParams();
        var parentLoad = querystringParams['parentload'] as string;
        if (parentLoad) {

            var fn: Function = parent[parentLoad];
            var loadCode = fn();
            codeMirrorEditor.getDoc().setValue(loadCode);
            runCodeFromEditor();

        } else {
            var scriptname = querystringParams['script'] as string;

            if (scriptname && !isHttp(scriptname)) {

                var paramValues = getHashParams();

                if (scriptname in makerjs.models) {

                    var code = generateCodeFromKit(scriptname, makerjs.models[scriptname], paramValues);
                    codeMirrorEditor.getDoc().setValue(code);
                    runCodeFromEditor(paramValues);

                } else {
                    downloadScript(filenameFromRequireId(scriptname), function (download: string) {
                        codeMirrorEditor.getDoc().setValue(download);
                        runCodeFromEditor(paramValues);
                    });
                }
            } else {
                runCodeFromEditor();
            }
        }
    };

}


text:
<!DOCTYPE html>
<html>

  {% include header.html %}

  <body>

    {% include navbar.html %}

    {{ content }}

    {% include footer.html %}

    {%include scripts.html %}

  </body>

</html>


text:
'use strict';

angular.module('myconfig', ['adf', 'myModule'])
.config(function(dashboardProvider, helloWorldProvider){

  helloWorldProvider.setName('Daniels');

  dashboardProvider
    .myconfig('mySimpleConfig', {
      test: "TestMexx1"
    });

});


text:
'use strict';

import { createDecorator } from 'vs/platform/instantiation/common/instantiation';

export const IThreadService = createDecorator<IThreadService>('threadService');

export interface IThreadService {
	_serviceBrand: any;

	/**
	 * Always returns a proxy.
	 */
	get<T>(identifier: ProxyIdentifier<T>): T;

	/**
	 * Register instance.
	 */
	set<T>(identifier: ProxyIdentifier<T>, value: T): void;
}

export class ProxyIdentifier<T> {
	_proxyIdentifierBrand: void;

	isMain: boolean;
	id: string;
	methodNames: string[];

	constructor(isMain: boolean, id: string, ctor: Function) {
		this.isMain = isMain;
		this.id = id;

		this.methodNames = [];
		for (let prop in ctor.prototype) {
			if (typeof ctor.prototype[prop] === 'function') {
				this.methodNames.push(prop);
			}
		}
	}
}

export function createMainContextProxyIdentifier<T>(identifier: string, ctor: Function): ProxyIdentifier<T> {
	return new ProxyIdentifier(true, 'm' + identifier, ctor);
}

export function createExtHostContextProxyIdentifier<T>(identifier: string, ctor: Function): ProxyIdentifier<T> {
	return new ProxyIdentifier(false, 'e' + identifier, ctor);
}


text:
<?php

namespace Google\Service\Bigquery;

class TransactionInfo extends \Google\Model
{
  /**
   * @var string
   */
  public $transactionId;

  /**
   * @param string
   */
  public function setTransactionId($transactionId)
  {
    $this->transactionId = $transactionId;
  }
  /**
   * @return string
   */
  public function getTransactionId()
  {
    return $this->transactionId;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(TransactionInfo::class, 'Google_Service_Bigquery_TransactionInfo');