text:
define([
  'dojo/_base/declare', 'dijit/_WidgetBase', 'dojo/on',
  'dojo/dom-class', 'dijit/_TemplatedMixin', 'dijit/_WidgetsInTemplateMixin',
  'dojo/text!./templates/AppLogin.html', 'dijit/form/Form', 'p3/widget/WorkspaceObjectSelector', 'dojo/topic', 'dojo/_base/lang',
  '../../util/PathJoin',
  'dijit/Dialog', 'dojo/request', 'dojo/dom-construct', 'dojo/query', 'dijit/TooltipDialog', 'dijit/popup', 'dijit/registry', 'dojo/dom'
], function (
  declare, WidgetBase, on,
  domClass, Templated, WidgetsInTemplate,
  Template, FormMixin, WorkspaceObjectSelector, Topic, lang,
  PathJoin,
  Dialog, xhr, domConstruct, query, TooltipDialog, popup, registry, dom
) {
  return declare([WidgetBase, FormMixin, Templated, WidgetsInTemplate], {
    baseClass: 'App Sleep',
    templateString: '',
    docsServiceURL: window.App.docsServiceURL,
    path: '',
    applicationName: 'Date',
    requireAuth: false,
    applicationLabel: '',
    applicationDescription: '',
    showCancel: false,
    activeWorkspace: '',
    activeWorkspacePath: '',
    help_doc: null,
    activeUploads: [],

    postMixInProperties: function () {
      // use AppLogin.html when requireAuth & user is not logged in
      if (this.requireAuth && (window.App.authorizationToken === null || window.App.authorizationToken === undefined)) {
        this.templateString = Template;
        return;
      }
      this.activeWorkspace = this.activeWorkspace || window.App.activeWorkspace;
      this.activeWorkspacePath = this.activeWorkspacePath || window.App.activeWorkspacePath;
      this.inherited(arguments);
    },

    _setValueAttr: function (val) {
      this.value = val || window.App.activeWorkspacePath;
    },

    gethelp: function () {

      if (this.applicationHelp) {
        var helprequest = xhr.get(PathJoin(this.docsServiceURL, this.applicationHelp), {
          handleAs: 'text'
        });
        helprequest.then(function (data) {
          data = data.replace('', '');
          this.help_doc = domConstruct.toDom(data);
          var ibuttons = query('.infobutton');
          ibuttons.forEach(function (item) {
            // var help_text= help_doc.getElementById(item.attributes.name.value) || "Help text missing";
            // basic flat child workaround for getting help in safari. will break if nested.
            var help_text = null;
            for (var i = 0; i < this.help_doc.childNodes.length; i++) {
              if (this.help_doc.childNodes[i].id == item.attributes.name.value) {
                help_text = this.help_doc.childNodes[i];
              }
            }
            help_text = help_text || dom.byId(item.attributes.name.value, this.help_doc) || domConstruct.toDom('
Help text missing
');
            help_text.style.overflowY = 'auto';
            help_text.style.maxHeight = '400px';
            if (domClass.contains(item, 'dialoginfo')) {
              item.info_dialog = new Dialog({
                content: help_text,
                'class': 'helpModal',
                draggable: true,
                style: 'max-width: 350px;'
              });
              item.open = false;
              on(item, 'click', function () {
                if (!item.open) {
                  item.open = true;
                  item.info_dialog.show();
                }
                else {
                  item.open = false;
                  item.info_dialog.hide();
                }
              });
            }
            else if (domClass.contains(item, 'tooltipinfo')) {
              item.info_dialog = new TooltipDialog({
                content: help_text,
                'class': 'helpTooltip',
                style: 'overflow-y: auto; max-width: 350px; max-height: 400px',
                onMouseLeave: function () {
                  popup.close(item.info_dialog);
                }
              });
              on(item, 'mouseover', function () {
                popup.open({
                  popup: item.info_dialog,
                  around: item
                });
              });
              on(item, 'mouseout', function () {
                popup.close(item.info_dialog);
              });
            }
          });
        });
      }

      var tutorials = query('.tutorialButton');
      var tutorialLink = PathJoin(this.docsServiceURL, (this.tutorialLink || 'tutorial/'));
      tutorials.forEach(function (item) {
        if (domClass.contains(item, 'tutorialInfo')) {
          on(item, 'click', function () {
            // console.log(tutorialLink)
            window.open(tutorialLink, 'Tutorials');
          });
        }
      });

    },

    onOutputPathChange: function (val) {
      registry.byClass('p3.widget.WorkspaceFilenameValidationTextBox').forEach(function (obj) {
        obj.set('path', val);
      });
    },

    startup: function () {
      if (this._started) {
        return;
      }
      if (this.requireAuth && (window.App.authorizationToken === null || window.App.authorizationToken === undefined)) {
        return;
      }
      this.inherited(arguments);
      var state = this.get('state');
      if ((state == 'Incomplete') || (state == 'Error')) {
        this.submitButton.set('disabled', true);
      }

      this.watch('state', function (prop, val, val2) {
        if (val2 == 'Incomplete' || val2 == 'Error') {
          this.submitButton.set('disabled', true);
        } else {
          this.submitButton.set('disabled', false);
        }
      });

      if (!this.showCancel && this.cancelButton) {
        domClass.add(this.cancelButton.domNode, 'dijitHidden');
      }

      if (this.pageTitle) {
        window.document.title = this.pageTitle;
      }

      this.gethelp();
      Topic.subscribe('/upload', lang.hitch(this, 'onUploadMessage'));
      Topic.subscribe('/UploaderDialog', lang.hitch(this, function (msg) {
        if (msg && msg.type == 'UploaderClose') {
          this.validate();
        }
      }));
      if (this.submitButton) {
        var uploadTolltip = new TooltipDialog({
          content: 'Upload in progress, please wait.',
          onMouseLeave: function () {
            popup.close(uploadTolltip);
          }
        });
        var a = this.submitButton.domNode;
        on(a, 'mouseover', lang.hitch(this, function () {
          if (this.activeUploads && this.activeUploads.length != 0)
          { popup.open({
            popup: uploadTolltip,
            around: a,
            orient: ['above-centered', 'below-centered']
          }); }
        }));
        on(a, 'mouseout', function () {
          popup.close(uploadTolltip);
        });
      }

      this._started = true;
    },

    onReset: function (evt) {
      domClass.remove(this.domNode, 'Working');
      domClass.remove(this.domNode, 'Error');
      domClass.remove(this.domNode, 'Submitted');
    },

    onUploadMessage: function (msg) {
      var path = msg.workspacePath;
      if (msg.workspacePath.substr(-1) != '/') {
        path += '/';
      }
      path += msg.filename;
      if (msg && msg.type == 'UploadStart' && this.activeUploads.indexOf(msg.workspacePath + msg.filename) == -1) {
        // add file this.activeUploads
        this.activeUploads.push(path);
        this.validate();
        return;
      }

      if (msg && msg.type == 'UploadProgress') {
        this.validate();
        return;
      }

      if (msg && msg.type == 'UploadComplete') {
        // remove file from this.activeUploads
        var i = this.activeUploads.indexOf(path);
        if (i != -1) {
          this.activeUploads.splice(i, 1);
        }
        this.validate();

      }
    },

    validate: function () {
      var valid = this.inherited(arguments);
      if (valid && this.activeUploads.length == 0) {
        if (this.submitButton) { this.submitButton.set('disabled', false); }
        return valid;
      }

      if (this.submitButton) { this.submitButton.set('disabled', true); }
      return false;

    },

    onSubmit: function (evt) {
      var _self = this;

      evt.preventDefault();
      evt.stopPropagation();
      if (this.validate()) {
        var values = this.getValues();

        domClass.add(this.domNode, 'Working');
        domClass.remove(this.domNode, 'Error');
        domClass.remove(this.domNode, 'Submitted');

        if (window.App.noJobSubmission) {
          var dlg = new Dialog({
            title: 'Job Submission Params: ',
            content: '
' + JSON.stringify(values, null, 4) + '
'
          });
          dlg.startup();
          dlg.show();
          return;
        }
        this.submitButton.set('disabled', true);
        window.App.api.service('AppService.start_app', [this.applicationName, values]).then(function (results) {
          console.log('Job Submission Results: ', results);

          if (window.gtag) {
            gtag('event', this.applicationName, { event_category: 'Services' });
          }

          domClass.remove(_self.domNode, 'Working');
          domClass.add(_self.domNode, 'Submitted');
          _self.submitButton.set('disabled', false);
          registry.byClass('p3.widget.WorkspaceFilenameValidationTextBox').forEach(function (obj) {
            obj.reset();
          });
        }, function (err) {
          console.log('Error:', err);
          domClass.remove(_self.domNode, 'Working');
          domClass.add(_self.domNode, 'Error');
          _self.errorMessage.innerHTML = err;
        });
      } else {
        console.log('Form is incomplete');
      }
    },

    onCancel: function (evt) {
      console.log('Cancel/Close Dialog', evt);
      on.emit(this.domNode, 'dialogAction', { action: 'close', bubbles: true });
    },

    checkOutputName: function () {
      var charError = document.getElementsByClassName('charError')[0];
      var label_value = this.output_file.get('value');
      // charError.innerHTML = ' ';
      if (label_value.indexOf('/') !== -1 || label_value.indexOf('\\') !== -1) {
        charError.innerHTML = 'slashes are not allowed';
        // console.log(this.output_file);
        this.output_file.set('value', '');
      } else {
        if (label_value !== '') {
          charError.innerHTML = ' ';
        }
      }
    }
  });
});


text:
package error

import (
	"github.com/realglobe-Inc/go-lib/rglog"
)

const logRoot = "github.com/realglobe-Inc"

var log = rglog.Logger(logRoot + "/edo-idp-selector/error")

redpajama_set_name: RedPajamaGithub


text:
from __future__ import unicode_literals

from django.core.exceptions import ImproperlyConfigured
from django.core.exceptions import ValidationError
from django.utils import six
from django.utils.encoding import force_text
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _

from rest_framework.reverse import reverse

from djangobmf.core.employee import Employee
from djangobmf.signals import activity_workflow

import inspect
from collections import OrderedDict

@python_2_unicode_compatible
class State(object):
    """

    Args:
        * name: Verbose name of the State
        * default: True if this is the default state
        * update: Update-View is available, when in this state (default: True)
        * delete: Delete-View is available, when in this state (default: True)
    """
    _creation_counter = 0

    def __init__(self, name, default=False, update=True, delete=True):
        self.name = name
        self.default = default
        self.update = update
        self.delete = delete

        self._order = State._creation_counter
        State._creation_counter += 1

    def __str__(self):
        return force_text(self.name)

    def __repr__(self):
        return force_text("<%s: '%s'>" % (self.__class__.__name__, str(self)))

@python_2_unicode_compatible
class Transition(object):
    """
    Args:
        * name: Verbose name of the Transition
        * sources: From state
        * target: To state(s) - can be either a list of state keys or a single state key
        * validate: Validate the model when changeing the state (default: True)
        * permissions: List of django permissions to check
        * condition: a function which is used to check user related conditions
    """
    _creation_counter = 0

    def __init__(self, name, sources, target, validate=True, permissions=[], condition=None):
        self.name = name

        if isinstance(sources, six.string_types):
            self.sources = [sources]
        elif hasattr(sources, '__iter__'):
            self.sources = list(sources)
        else:
            # LOOK: you may even add a non-interable object to this dont know why it may be used
            #       maybe it'll be better to raise an acception and accept only
            #       string objects (and even check the iterable object if it returns strings)
            self.sources = [sources]
        self.target = target

        # use object validation bevor object is changed
        self.validate = validate

        # list with permissions
        self.permissions = permissions

        # define a condition for this transition
        self.condition = condition

        if permissions or condition:
            self.conditioned = True
        else:
            self.conditioned = False

        self._order = Transition._creation_counter
        Transition._creation_counter += 1

    def __str__(self):
        return force_text(self.name)

    def __repr__(self):
        return force_text("<%s: '%s'>" % (self.__class__.__name__, str(self)))

    def affected_states(self):
        return self.sources + [self.target]

    def eval_condition(self, object, user):
        if self.condition:
            return user.has_perms(self.permissions) and self.condition(object, user)
        else:
            return user.has_perms(self.permissions)

class WorkflowMetaclass(type):
    def __new__(cls, name, bases, attrs):
        super_new = super(WorkflowMetaclass, cls).__new__
        parents = [
            b for b in bases if isinstance(b, WorkflowMetaclass) and
            not (b.__name__ == 'NewBase' and b.__mro__ == (b, object))
        ]
        if not parents:
            return super_new(cls, name, bases, attrs)

        # Create the class.
        new_cls = super_new(cls, name, bases, attrs)

        # validation
        if not hasattr(new_cls, 'States'):
            raise ImproperlyConfigured('No states defined in %s' % new_cls)
        if not hasattr(new_cls, 'Transitions'):
            raise ImproperlyConfigured('No transitions defined in %s' % new_cls)

        # set and check states
        new_cls._states = OrderedDict()
        for key, value in sorted(
                inspect.getmembers(
                    new_cls.States,
                    lambda o: isinstance(o, State)
                ), key=lambda i: i[1]._order):
            new_cls._states[key] = value
            if value.default:
                if hasattr(new_cls, '_default_state'):
                    raise ImproperlyConfigured('Two states are defined with an default value in %s' % new_cls)
                else:
                    new_cls._default_state = value
                    new_cls._default_state_key = key
        if len(new_cls._states) == 0:
            raise ImproperlyConfigured('No states defined in %s' % new_cls)
        if not hasattr(new_cls, '_default_state'):
            raise ImproperlyConfigured('You must define a default state in %s' % new_cls)

        # set and check transitions
        new_cls._transitions = OrderedDict()
        for key, value in sorted(
                inspect.getmembers(
                    new_cls.Transitions,
                    lambda o: isinstance(o, Transition)
                ), key=lambda i: i[1]._order):
            if key == "user":
                raise ImproperlyConfigured(
                    'The name "user" is reserved, please rename your transition defined in %s' % new_cls
                )
            if key == "instance":
                raise ImproperlyConfigured(
                    'The name "instance" is reserved, please rename your transition defined in %s' % new_cls
                )
            if key[0] == "_":
                raise ImproperlyConfigured('The keys can not start with an underscore in %s' % new_cls)
            for state in value.affected_states():
                if state not in new_cls._states:
                    raise ImproperlyConfigured('The state %s is not defined in %s' % (state, new_cls))
            new_cls._transitions[key] = value

        # autoset transition functions
        for key, value in new_cls._transitions.items():
            if hasattr(new_cls, key):
                continue

            # function template
            def f(self):
                """
                I'm a template-function. Please overwrite me and let me return either None or a (redirect) URL
                """
                pass
            setattr(new_cls, key, f)

        # return class
        return new_cls

@python_2_unicode_compatible
class Workflow(six.with_metaclass(WorkflowMetaclass, object)):
    """
    Example:

    .. code-block:: python

        class ExampleWorkflow(Workflow):
            class States:
                start = State(_('Start'), default=True, delete=False)
                deleted = State(_('Deleted'), update=False, delete=True)
                accepted = State(_('Accepted'), update=False, delete=True)

            class Transitions:
                accept = State(_('Accept'), 'start', 'accepted')
                delete = State(_('Delete'), ['start', 'accepted'], 'deleted', validate=False)
    """

    def __init__(self, state=None):
        self.instance = None

        if state:
            self._set_state(state)
        else:
            self._current_state = self._default_state
            self._current_state_key = self._default_state_key
        self._initial_state = self._current_state
        self._initial_state_key = self._current_state_key

    def __str__(self):
        return force_text(self._current_state)

    def _from_here(self, object=None, user=None):
        out = []
        for key, transition in self._transitions.items():
            if self._current_state_key in transition.sources:
                if object and user and not transition.eval_condition(object, user):
                    continue
                out.append((key, transition))
        return out

    def _set_state(self, key):
        if key not in self._states:
            raise ValidationError(_("The state %s is not valid") % key)
        self._current_state = self._states[key]
        self._current_state_key = key

    def _call(self, key, instance, user):

        # check if key is valid
        if self._current_state_key not in self._transitions[key].sources:
            raise ValidationError(_("This transition is not valid"))

        user.djangobmf = Employee(user)

        # update object with instance and user (they come in handy in user-defined functions)
        self.instance = instance
        self.user = user

        # normaly the instance attribute should only be unset during the tests
        if not self.instance:
            self._set_state(self._transitions[key].target)
            return getattr(self, key)()

        # validate the instance
        if self._transitions[key].validate and self._current_state.update:
            self.instance.full_clean()

        # check the conditions of the transition
        if self._transitions[key].conditioned:
            self._transitions[key].eval_condition(instance, user)

        # everything is valid, we can set the new state
        self._set_state(self._transitions[key].target)

        # call function
        url = getattr(self, key)()

        return url

@python_2_unicode_compatible
class WorkflowContainer(object):
    """
    This object is generated by the workflow-field and saved as it's value
    """

    def __init__(self, workspace, state=None):
        self.obj = workspace(state)
        self.model = None

    def set_django_object(self, obj):
        """
        internal function, which sets the instances object
        called by an post_init signal in djangobmf.models.base
        """
        self.django_object = obj

    @property
    def object(self):
        """
        Returns the current state object
        """
        return self.obj._current_state

    @property
    def name(self):
        """
        Returns the current states name
        """
        return self.obj._current_state.name

    @property
    def states(self):
        """
        """
        return self.obj._states

    @property
    def key(self):
        """
        Returns the current state key
        """
        return self.obj._current_state_key

    @property
    def initial(self):
        """
        Returns the current state key
        """
        return self.obj._initial_state_key

    @property
    def default(self):
        """
        Returns the default state key
        """
        return self.obj._default_state_key

    def serialize(self, request):
        """
        Return a serialized value of the workflow state for the api access
        """
        return OrderedDict([
            ('name', force_text(self.name)),
            ('transitions', list(
                [
                    OrderedDict((
                        ('name', force_text(s.name)),
                        ('action', k),
                        ('url', reverse(
                            'djangobmf:moduleapi_%s_%s:workflow' % (
                                self.django_object._meta.app_label,
                                self.django_object._meta.model_name,
                            ),
                            format=None,
                            request=request,
                            kwargs={'pk': self.django_object.pk, 'transition': k},
                        )),
                    ))
                    for k, s in self.transitions(request.user)
                ]
            )),
            ('update', self.object.update),
            ('delete', self.object.delete),
        ])

    def transitions(self, user):
        """
        Show all transitions
        """
        return self.obj._from_here(self.django_object, user)

    def transition(self, via, user, silent=False):
        """
        Make a state transition for this object
        """
        transitions = dict(self.transitions(user))
        if via not in transitions:
            raise ValidationError(_("This transition is not valid"))

        success_url = self.obj._call(via, self.django_object, user)
        self.django_object.modified_by = user
        self.django_object.save()

        if not silent:
            activity_workflow.send(
                sender=self.django_object.__class__,
                instance=self.django_object,
                initial=self.initial,
                final=self.key,
            )

        return success_url

    def __str__(self):
        return six.text_type(self.obj._current_state.name)


text:
import Morph from 'src/components/widgets/lively-morph.js';
import Filter from "src/external/ansi-to-html.js";
import Strings from "src/client/strings.js";

/*MD # Github Sync Tool
![](lively-sync.png){width=500px}

MD*/

export default class Sync extends Morph {

  initialize() {
    var container = this.get(".container");
    this.registerButtons();
    lively.html.registerInputs(this);
    lively.html.registerKeys(this);
    lively.html.registerAttributeObservers(this)

    this.updateLoginStatus();

    if (window.__karma__) {
      console.log("exit early... due to karma");
      return;
    }
    var repo = this.getAttribute("gitrepository") || lively4url.replace(/.*\//,"")
    this.get('#gitrepository').value = repo;
    this.get('#gitrepository').addEventListener("change", evt => this.onGitrepositoryInputChange(evt))
    this.get('#serverUrl').addEventListener("change", evt => this.onServerUrlInputChange(evt))

    this.updateWindowTitle()
    this.updateServerURL()
  }

  onKeyDown(evt) {
    const char = String.fromCharCode(evt.keyCode || evt.charCode);
    const ctrl = evt.ctrlKey || evt.metaKey;

    if (evt.repeated) {
      lively.notify("Key rep! " + char)
      return;
    }
    if (!ctrl) { return; }

    if (char === "S") {
      this.onSyncButton();
      evt.preventDefault();
      evt.stopPropagation();
      return;
    }

    if(char === "Q") {
      this.onSquashButton();

      evt.stopPropagation();
      evt.preventDefault();
      return;
    }
  }

  log(s) {
    this.get("#log").innerHTML += s
    // var editor = this.get("#log").editor;
    // if (editor) {
    //   editor.setValue(editor.getValue() + "\n" + s);
    //   // editor.session.setScrollTop(1000000); // #TODO find scroll to bottom method in ace
    // }
  }

  async loadCredentials() {
    // this.updateLoginStatus()
    var token = await this.loadValue("githubToken")
    this.get("#loginButton").innerHTML =
        token ? "logout" : "login";
    var login = token ? true : false;
    this.loggedin = login;

    this.get("#gitusername").value =
      await this.loadValue("githubUsername");
    this.get("#gitemail").value =
      await this.loadValue("githubEmail");

    var value = await this.loadValue("githubRepository")
    if (value) this.get("#gitrepository").value = value;
  }

  githubApi(path, token) {
    return fetch("https://api.github.com" + path, {headers: new Headers({
      Authorization: "token " + token
    })}).then(r => r.json());
  }

  async login() {
    this.loadValue("githubToken").then((result) => {
      if (result) return result;
      return new Promise((resolve, reject) => {
        lively.authGithub.challengeForAuth(Date.now(), async (token) => {
          console.log("authenticated");
          var user = await this.githubApi("/user", token);
          var username = user.login;
          var emails =  await this.githubApi("/user/emails", token);
          var email = emails.find(ea => ea.primary).email;

          console.log("username: " + username);
          console.log("email: " + email);

          this.storeValue("githubUsername", username);
          this.storeValue("githubEmail", email);
          this.storeValue("githubToken", token);
          this.updateLoginStatus();
          resolve(token);
    });
      });
    }).then((token) => {
      this.log("Logged in");
    });
  }

  /*MD ## Sync  MD*/

  async gitControl(cmd, eachCB, optHeaders={}) {
    this.clearLog()
    return new Promise(async (resolve) => {
      var headers =  await this.getHeaders()
      headers.append("command", cmd)
      for(var key in optHeaders) {
        headers.set(key, optHeaders[key])
      }
      let commandURL = this.getServerURL() +"/_git/" + cmd;
      lively.files.fetchChunks(fetch(commandURL, {
              headers: headers
            }), (eaChunk) => {
          if (eachCB)
            eachCB(eaChunk)
          else
            this.log(this.linkifyFiles(new Filter().toHtml(eaChunk.replace(/</g,"<"))))
        }, resolve)
    })
  }

  async sync() {
    var syncResult = await this.gitControl("sync");

    this.log("invalidate local caches")
    window.lively4invalidateFileCaches && window.lively4invalidateFileCaches() // global variable set in boot
  }

  logout() {
    this.clearLog()
    this.storeValue("githubToken", null)
    this.storeValue("githubUsername", null)
    this.storeValue("githubEmail", null)
    this.updateLoginStatus()
    window.lively4github = null // used by #Fetch proxy
    this.log("")
  }

  /*MD ## Getter / Setter MD*/

  get storagePrefix() {
    return "LivelySync_"
  }

  get repositoryBlacklist() {
    return ["lively4-core", "lively4-stable"]
  }

  async getHeaders() {
    return new Headers({
      "gitusername":          this.get("#gitusername").value,
      "gitpassword":          await this.loadValue("githubToken"),
      "gitemail":             this.get("#gitemail").value,
      "gitrepositoryurl":     this.get("#gitrepositoryurl").value,
      "gitrepository":        this.getRepository(),
      "gitrepositorybranch":  this.get("#gitrepositorybranch").value,
      "gitcommitmessage":     this.get("#gitcommitmessage").value,
      "dryrun":               this.get("#dryrun").checked
    })
  }

  defaultServerURL() {
    return lively4url.match(/(.*)\/([^\/]+$)/)[1]
  }

  getServerURL() {
    return this.getAttribute("serverurl") || this.defaultServerURL()
  }

  setServerURL(url) {
    this.setAttribute("serverurl", url)
    this.updateWindowTitle()
    this.updateRepositoryList()
    this.updateServerURL()
  }

  setRepository(name) {
    this.setAttribute("gitrepository", name)
    this.get("#gitrepository").value = name
  }

  getRepository() {
     return this.get("#gitrepository").value
  }

  getBranch() {
     return this.get("#gitrepositorybranch").value.replace(/^ */,"")
  }

  async getGitRepositoryNames() {
    var json = await lively.files.statFile(this.getServerURL()).then( JSON.parse)
    if (!json || !json.contents) return []
    return json.contents.filter(ea => ea.type == "directory").map(ea => ea.name)
  }

  /*MD ## Helper MD*/

  async storeValue(key, value) {
    return  lively.focalStorage.setItem(this.storagePrefix + key, value)
  }

  async loadValue(key) {
    return lively.focalStorage.getItem(this.storagePrefix + key)
  }

  linkifyFiles(htmlString) {
    var base = this.getServerURL() + "/" + this.getRepository() + "/"
    return htmlString
      // .replace(/((?:deleted\: *)?)([^<]*)(<\/span>)/g, (m,a,b,c) =>
      //     `${a}<a onclick="event.preventDefault(); fetch(this.href)" href="edit://${b}">${b}</a>${c}`)
      .replace(/(modified: *)([a-zA-Z0-9\-_/ .]*)/g, (m,a,b) =>
          `${a}<a onclick="event.preventDefault(); lively.openBrowser(this.href,true)" href="${base + b}">${b}</a>`)
      .replace(/((?:\+\+\+\s*b\/)|(?:\-\-\- a\/))([a-zA-Z-_0-9/ .]*)/g, (m,a,b) =>
          `${a}<a onclick="event.preventDefault(); lively.openBrowser(this.href,true)" href="${base + b}">${b}</a>`)
//
  }

  /*MD ## Events MD*/

  onSyncButton() {
    this.gitControl("status").then((status) => { if (!status.match("AUTO-COMMIT-")) {
        this.sync()
        // lively.notify("sync directly")
      } else {
        if (window.confirm("Contains auto commits. Forgot to squash? Push them anyway? ")) {
          this.sync()
          // lively.notify("sync anyway")
        } else {
          // lively.notify("sync canceled")
        }
      }
    })
  }

  async onLoginButton() {
    window.lively4github = null // fetch will getg new auth info
    this.clearLog()
    if (await this.loadValue("githubToken")) {
      this.logout()
    } else {
      this.login()
    }
  }

  getProtectedRepositories() {
    return ["lively4-jens", "lively4-core"]
  }

  onPullButton() {
    alert("hi")
  }

  onBranchButton() {
    if (this.getProtectedRepositories().includes(this.getRepository())) {
      return lively.warn("You are not allowed to branch on " + this.getRepository())
    }
    this.gitControl("branch")
  }

  onStatusButton() {
    this.gitControl("status")
  }

  onResetHardButton() {

    if (window.confirm("Do you want revert all local commits and reset to your current branch?")) {
      this.gitControl("reset-hard");
    }
  }

  onDiffButton() {
    this.get("#log").setAttribute('mode', "text/x-diff")
    // text/x-diff

    this.gitControl("diff")
  }

  async onCloneButton(){
    if (window.confirm("Do you want to clone into " +
        this.get("#gitrepository").value)) {
      this.get("#cloneButton").disabled= true
      await this.gitControl("clone")
      this.updateContextSensitiveButtons()
      this.updateRepositoryList()
    }
  }

  onNpmInstallButton() {
    this.gitControl("npminstall")
  }

  onNpmTestButton() {
    this.gitControl("npmtest")
  }

  async onResolveButton() {
    if (await lively.confirm("DANGER! Do you want to FORCE a resolve with a hammer? Please consider, going to all files and solve the conflict through editing there! This is not the button you want to use.")) {
        this.gitControl("resolve")
    }
  }

  onChangelogButton() {
   this.gitControl("graph");
  }

  onChangesgraphButton() {
    lively.openMarkdown(lively4url + "/doc/files/changesgraph.md",
      "Change Graph", {url: this.getServerURL() + "/" + this.getRepository() + "/"})
  }

  onCommitButton() {
    // return lively.notify("Commit is not implemented yet")
    this.gitControl("commit");
  }

  onDeleteButton() {
    if (window.confirm("Do you want to delete " + this.get("#gitrepository").value + " repository?")) {
      this.gitControl("delete");
    }
  }

  async onMergeButton() {
    if (this.getProtectedRepositories().includes(this.getRepository())) {
      return lively.warn("You are not allowed to merge on " + this.getRepository())
    }
    if (await lively.confirm("Do you want to merge "
      + this.get("#gitrepositorybranch").value
      +" into " + this.get("#gitrepository").value
      + " repository?
DANGER: Do not 'Squash' commit before a new 'Sync'")) {
      this.gitControl("merge");
    }
  }

  onSquashButton() {
    this.gitControl("squash");
  }

  async onResetButton(){
    const answer = await lively.confirm("This will hard reset to the current remote working index.");
    if(answer){
      this.gitControl("reset")
    }
  }

  onGitrepositoryInputChange(evt) {
    var value = this.getRepository()
    lively.notify("input changed:" + value)
    this.setAttribute("gitrepository", value)
  }

  async onServerUrlInputChange(evt) {
    var input = this.get("#serverUrl")
    var url = input.value
    try {
      var stats = await fetch(url, {
        method: "OPTIONS"
      }).then(r => r.json())
    } catch(e) {

    }

    // #TODO we could inform in the server that this is a proper base directory....
    if (stats && stats.type == "directory") {
      input.style.border = ""
      this.setServerURL(url)
    } else {
      input.style.border = "2px dashed red"
    }

    lively.notify("server url: " + url)

    this.get("#gitrepository").value = ""

    // var value = this.getRepository()
    // lively.notify("input changed:" + value)
    // this.setAttribute("gitrepository", value)
  }

  async onGitrepositoryChanged(value) {
    this.updateContextSensitiveButtons()
  }

  /*MD ## Update UI MD*/

  async updateRepositoryList() {
    var list = await this.getGitRepositoryNames()
    this.get("#gitrepository").setOptions(list)
  }

  async updateBranchesList() {
    var branches = await this.gitControl("branches", ()=>{})
    branches = branches.split("\n")
    var currentRegex = /^ *\*/
    var currentBranch = branches.find(ea => ea.match(currentRegex));
    if(!currentBranch) {
      return
    }
    currentBranch = currentBranch.replace(currentRegex,"")
    this.get("#gitrepositorybranch").value = currentBranch

    var remoteRegEx = /^remotes\/origin\//
    branches = branches
      .map(ea => ea.replace(/^\*? */,"")) // trim
      .filter(ea => ea.match(remoteRegEx))
      .filter(ea => ! ea.match("HEAD "))
      .map(ea => ea.replace(remoteRegEx,""))
    this.get("#gitrepositorybranch").setOptions(branches)
    // console.log("branches: " + branches)
  }

  async updateContextSensitiveButtons() {
    var repository = this.get("#gitrepository").value
    var list = await this.getGitRepositoryNames()
    var exists = list.includes(repository);

    // console.log("delete " + this.get("#deleteButton").disabled)

    if (exists) {

      await this.updateUpstreamURL()
      await this.updateBranchesList()
    }

    this.shadowRoot.querySelectorAll(".repo").forEach(ea =>
      ea.disabled= !this.loggedin || !exists)

    this.shadowRoot.querySelectorAll(".branch").forEach(ea =>
      ea.disabled= !this.loggedin)

    this.shadowRoot.querySelectorAll(".clone").forEach(ea =>
      ea.disabled= !this.loggedin || exists)

    this.shadowRoot.querySelectorAll(".login").forEach(ea =>
      ea.disabled= this.loggedin)

    if (this.repositoryBlacklist.includes(repository))
      this.get("#deleteButton").disabled = true
  }

  updateServerURL() {
    this.get("#serverUrl").value = this.getServerURL()
    this.get("#serverUrl").setOptions(lively.files.getKnownServers())
  }

  async updateUpstreamURL() {
    var url = await this.gitControl("remoteurl")
    url = url.replace(/\n/,"")
    this.get("#gitrepositoryurl").value = url
  }

  updateWindowTitle() {
    var serverURL = this.getServerURL()
    this.windowTitle = "GitHub Sync " + ((serverURL == this.defaultServerURL()) ? "" : serverURL );
  }

  async updateLoginStatus() {
    if (window.__karma__) return; // no lively4-server active

    await this.loadCredentials()

    await this.updateContextSensitiveButtons();
    await this.updateRepositoryList();
  }

    // #TODO into Morph or Tool
  clearLog(s) {
    this.get("#log").innerHTML = ""
    // var editor= this.get("#log").editor;
    // if (editor) editor.setValue("");
  }

}


text:
<?php

// composer require enqueue/amqp-bunny
require_once __DIR__.'/vendor/autoload.php';

use Enqueue\AmqpBunny\AmqpConnectionFactory;
use Interop\Amqp\AmqpTopic;

$config = [
    'host' => 'localhost',
    'port' => 5672,
    'user' => 'guest',
    'pass' => 'guest',
];

$connection = new AmqpConnectionFactory($config);
$context = $connection->createContext();

$topic = $context->createTopic('direct_logs');
$topic->setType(AmqpTopic::TYPE_DIRECT);

$context->declareTopic($topic);

$severity = isset($argv[1]) && !empty($argv[1]) ? $argv[1] : 'info';

$data = implode(' ', array_slice($argv, 2));
if (empty($data)) {
    $data = 'Hello World!';
}

$message = $context->createMessage($data);
$message->setRoutingKey($severity);

$context->createProducer()->send($topic, $message);

echo ' [x] Sent ',$severity,':',$data," \n";

$context->close();


text:
/// <autosync enabled="true" />
/// <reference path="js/site.js" />
/// <reference path="../node_modules/bootstrap/dist/js/bootstrap.js" />
/// <reference path="../node_modules/jquery/dist/jquery.js" />
/// <reference path="../node_modules/jquery-validation/dist/jquery.validate.js" />
/// <reference path="../node_modules/jquery-validation-unobtrusive/dist/jquery.validate.unobtrusive.js" />


text:
package net.bytebuddy.dynamic.scaffold.inline;

import net.bytebuddy.description.method.MethodDescription;
import net.bytebuddy.test.utility.MockitoRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
import org.mockito.Mock;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;

public class MethodRebaseResolverDisabledTest {

    @Rule
    public TestRule mockitoRule = new MockitoRule(this);

    @Mock
    private MethodDescription.InDefinedShape methodDescription;

    @Test
    public void testResolutionPreservesMethod() throws Exception {
        MethodRebaseResolver.Resolution resolution = MethodRebaseResolver.Disabled.INSTANCE.resolve(methodDescription);
        assertThat(resolution.isRebased(), is(false));
        assertThat(resolution.getResolvedMethod(), is(methodDescription));
    }

    @Test
    public void testNoAuxiliaryTypes() throws Exception {
        assertThat(MethodRebaseResolver.Disabled.INSTANCE.getAuxiliaryTypes().size(), is(0));
    }

    @Test
    public void testNoRebaseableMethods() throws Exception {
        assertThat(MethodRebaseResolver.Disabled.INSTANCE.asTokenMap().size(), is(0));
    }
}


text:
/*************************************************************************/
/*                                                                       */
/*                Centre for Speech Technology Research                  */
/*                 (University of Edinburgh, UK) and                     */
/*                           Korin Richmond                              */
/*                         Copyright (c) 2002                            */
/*                         All Rights Reserved.                          */
/*                                                                       */
/*  Permission is hereby granted, free of charge, to use and distribute  */
/*  this software and its documentation without restriction, including   */
/*  without limitation the rights to use, copy, modify, merge, publish,  */
/*  distribute, sublicense, and/or sell copies of this work, and to      */
/*  permit persons to whom this work is furnished to do so, subject to   */
/*  the following conditions:                                            */
/*                                                                       */
/*   1. The code must retain the above copyright notice, this list of    */
/*      conditions and the following disclaimer.                         */
/*   2. Any modifications must be clearly marked as such.                */
/*   3. Original authors' names are not deleted.                         */
/*   4. The authors' names are not used to endorse or promote products   */
/*      derived from this software without specific prior written        */
/*      permission.                                                      */
/*                                                                       */
/*  THE UNIVERSITY OF EDINBURGH AND THE CONTRIBUTORS TO THIS WORK        */
/*  DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING      */
/*  ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT   */
/*  SHALL THE UNIVERSITY OF EDINBURGH NOR THE CONTRIBUTORS BE LIABLE     */
/*  FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES    */
/*  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN   */
/*  AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,          */
/*  ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF       */
/*  THIS SOFTWARE.                                                       */
/*                                                                       */
/*************************************************************************/
/*                                                                       */
/*                          Author: Korin Richmond                       */
/*                            Date:  Aug  2002                           */
/* --------------------------------------------------------------------- */
/* A diphone unit selection "voice module"                               */
/* (implemented using a list of utterance objects)                       */
/*************************************************************************/

#include "DiphoneVoiceModule.h"
#include "EST_TargetCost.h"
#include "EST_viterbi.h"
#include "EST_rw_status.h"
#include "EST_Track.h"
#include "EST_track_aux.h"
#include "EST_Wave.h"
#include "EST_THash.h"
#include "EST_TList.h"
#include "EST_types.h"
#include "ling_class/EST_Utterance.h"
#include "siod.h"
#include "siod_est.h"
#include "safety.h"
#include <cstdlib>

#include "EST_Val.h"

// from src/modules/UniSyn_diphone/us_diphone.h
// this won't be staying here long...
void parse_diphone_times(EST_Relation &diphone_stream,
			 EST_Relation &source_lab);

SIOD_REGISTER_CLASS(du_voicemodule,DiphoneVoiceModule)
VAL_REGISTER_CLASS(du_voicemodule,DiphoneVoiceModule)

VAL_REGISTER_CLASS(diphonecandidate,DiphoneCandidate)

// defined in a single place to avoid inconsistency.
// Given a phone segment item, return the standard cut point
// time, calculated in the standard way.
float getJoinTime( const EST_Item *seg )
{
  float midt=0.0;

  // hack to avoid overhead of string creation and deletion
  // (EST feature access should really be changed to take
  // const char* instead of const EST_String& )
  static const EST_String cl_end_str( "cl_end" );
  static const EST_String dipth_str( "dipth" );
  static const EST_String start_str( "start" );

  // work out boundary for diphone join
  if( seg->f_present(cl_end_str) ) // join at cl_end point for stops
    midt = seg->features().val("cl_end").Float();
  else if( seg->f_present(dipth_str) ) // join at 25% through a diphthong
    midt = 0.75*seg->F(start_str)
      + 0.25*seg->features().val("end").Float();
  else
    midt = ( seg->F(start_str)
	     + seg->features().val("end").Float() ) / 2.0;

  return midt;
}

DiphoneVoiceModule::DiphoneVoiceModule( const EST_StrList& basenames,
					const EST_String& uttDir,
					const EST_String& wavDir,
					const EST_String& pmDir,
					const EST_String& coefDir,
					unsigned int sr,
					const EST_String& uttExt,
					const EST_String& wavExt,
					const EST_String& pmExt,
					const EST_String& coefExt )

  : fileList( basenames ),
    utt_dir ( uttDir  ),
    utt_ext ( uttExt  ),
    pm_dir( pmDir  ),
    pm_ext( pmExt  ),
    coef_dir( coefDir ),
    coef_ext( coefExt ),
    wave_dir( wavDir  ),
    wave_ext( wavExt  ),
    wav_srate( sr ),
    tcdatahash ( 0 ),
    utt_dbase( 0 ),
    catalogue( 0 )
{

}

void DiphoneVoiceModule::addCoefficients( EST_Relation *segs, const EST_Track& coefs )
{
  float startt, midt, endt;
  EST_FVector *startf, *midf, *endf;
  const int num_coefs = coefs.num_channels();

  // hack to avoid overhead of string creation and deletion
  // (EST feature access should really be changed to take
  // const char* instead of const EST_String& )
  static const EST_String startcoef_str("startcoef");
  static const EST_String midcoef_str("midcoef");
  static const EST_String endcoef_str("endcoef");
  static const EST_String start_str("start");

  EST_Item *seg=segs->head();
  startt = seg->F(start_str);

  startf = new EST_FVector(num_coefs);
  CHECK_PTR(startf);
  coefs.copy_frame_out(coefs.index(startt), *startf); //this one not shared

  for( ; seg!=0; seg=seg->next() ){

    // work out boundary for diphone join
    midt = getJoinTime( seg );

    // copy frames out and set as features
    seg->features().set_val( startcoef_str, est_val(startf) );

    midf = new EST_FVector(num_coefs);
    CHECK_PTR(midf);
    coefs.copy_frame_out(coefs.index(midt), *midf);
    seg->features().set_val( midcoef_str, est_val(midf) );

    endt = seg->features().val("end").Float();
    endf = new EST_FVector(num_coefs);
    CHECK_PTR(endf);
    coefs.copy_frame_out(coefs.index(endt), *endf);
    seg->features().set_val( endcoef_str, est_val(endf) );

    startf = endf; // phones share frame at phone boundary (reference counted in EST_Val)
  }
}

void DiphoneVoiceModule::flatPack( EST_Relation *segs,
				   const EST_TargetCost *tc ) const
{

  const EST_FlatTargetCost *ftc = (EST_FlatTargetCost *)tc;

  for( EST_Item *seg=segs->head(); seg->next() !=0; seg=seg->next() )
    tcdatahash->add_item(seg, ftc->flatpack(seg));

}

void DiphoneVoiceModule::initialise( const EST_TargetCost *tc, bool ignore_bad_tag )
{
  EST_Utterance *u=0;
  EST_Relation *segs=0;

  tcdatahash = new TCDataHash(500);

  utt_dbase = new EST_TList<EST_Utterance *>;
  CHECK_PTR(utt_dbase);

  catalogue = new EST_TStringHash<ItemList*>( 2500 );
  CHECK_PTR(catalogue);

  int numIgnoredPhones=0;

  if(ignore_bad_tag)
    EST_warning( "Looking for bad flags");
  else
    EST_warning( "Ignoring bad flags");

  for( EST_Litem *it=fileList.head(); it!=0 ; it=it->next() ){
    u = new EST_Utterance;
    CHECK_PTR(u);

    if( (u->load(utt_dir+fileList(it)+utt_ext)) != read_ok )
      EST_error( "Couldn't load utterance %s\n",
		 (const char*)fileList(it) );

    segs = u->relation( "Segment" );

    // add join cost coefficients (at middle of phones)
    EST_Track coefs;
    if( (coefs.load((coef_dir+fileList(it)+coef_ext))) != read_ok )
      EST_error( "Couldn't load data file %s",
		 (const char*) (coef_dir+fileList(it)+coef_ext) );

    addCoefficients( segs, coefs );

    if (tc->is_flatpack())
      {
	flatPack(segs,tc);
	u->remove_relation("Token");
	u->remove_relation("Word");
	u->remove_relation("Phrase");
	u->remove_relation("Syllable");
	u->remove_relation("SylStructure");
	u->remove_relation("IntEvent");
	u->remove_relation("Intonation");
      }

    addToCatalogue( u, &numIgnoredPhones, ignore_bad_tag );
    utt_dbase->append( u );
  }

  if(ignore_bad_tag)
    EST_warning( "Ignored %d phones with bad flag set\n", numIgnoredPhones );
}

DiphoneVoiceModule::~DiphoneVoiceModule()
{
  if( utt_dbase != 0 ){
    EST_Litem *it = utt_dbase->head();
    for( ; it!=0 ; it=it->next() )
      delete (*utt_dbase)(it);
    delete utt_dbase;
  }

  delete catalogue;

  if(tcdatahash)
    delete tcdatahash;

}

void DiphoneVoiceModule::addToCatalogue( const EST_Utterance *utt, int *num_ignored, bool ignore_bad )
{
  EST_Item *item, *next_item;
  ItemList *diphoneList;
  const EST_String *ph1, *ph2;
  int found=0;

  static const EST_String bad_str( "bad" );

  item = (utt->relation( "Segment" ))->tail();
  if( item!=0 ){
    ph2 = &(item->features().val("name").String());

    while( (item=item->prev()) != 0 ){

      next_item = item->next();

      // You'd think we need to check both item->f_present(bad_str) and
      // next_item->f_present(bad_str) like this:
      //if((item->f_present(bad_str) || next_item->f_present(bad_str)) && ignore_bad == true){
      // But experiment showed that then each time one diphone too many would be
      // ignored.  This was partly compensated by a bug pesent up to r1.14
      // (a iteration within "if(item=item->prev()!=0)" just before the "continue")
      // which caused the leftmost bad phone in a row of bad phones NOT to be ignored
      // when the length of the row was even (or when it was odd and ended in the
      // utterance-final phone, which is never checked for badness).
      if(item->f_present(bad_str) && ignore_bad == true){

	(*num_ignored)++;

 	EST_warning( "Ignoring diphone \"%s_%s\" (LEFT %s in %s at %fs, bad flag \"%s\")",
 		     item->S("name").str(),
 		     next_item->S("name").str(),
 		     item->S("name").str(),
 		     utt->f.S("fileid").str(),
 		     item->F("end"),
 		     item->S("bad").str() );

	if(item->prev() != 0){
	  continue;
	}
	else
	  break; //already at start of list, so finish up
      }

      ph1 = &(item->features().val("name").String());

//    EST_warning( "Adding phone \"%s\" (%s, %f) to diphoneList %s_%s",
//                item->S("name").str(),
//                utt->f.S("fileid").str(),
//                item->F("end"),
//                item->S("name").str(),
//                next_item->S("name").str());

      diphoneList = catalogue->val(EST_String::cat(*ph1,"_",*ph2), found);

      if( !found ){
	diphoneList = new ItemList;
	CHECK_PTR(diphoneList);
	catalogue->add_item(EST_String::cat(*ph1,"_",*ph2), diphoneList, 1); // no_search=1
      }

      diphoneList->append( item );

      ph2 = ph1;
    }
  }
}

void DiphoneVoiceModule::getDiphone( const EST_Item *phone1,
				     EST_Track* coef, EST_Wave* sig, int *midframe,
				     bool extendLeft, bool extendRight ) const
{
  EST_Item *phone2 = phone1->next();

  // load the relevant parts
  const EST_String &fname = phone1->relation()->utt()->f.val("fileid").String();

  static const EST_String start_str( "start" );

  float startt,midt,endt;

  if( extendLeft==true )
    startt = phone1->F(start_str);
  else
    startt = getJoinTime( phone1 );

  midt = phone1->features().val("end").Float();

  if( extendRight==true )
    endt = phone2->features().val("end").Float();
  else
    endt = getJoinTime( phone2 );

  // get pitchmarks for pitch synchronous synthesis
  EST_Track *tempcoef = new EST_Track;
  CHECK_PTR(tempcoef);
  if( (tempcoef->load((pm_dir+fname+pm_ext))) != read_ok )
    EST_error( "Couldn't load data file %s",
	       (const char*) (pm_dir+fname+pm_ext) );

  // following few lines effectively moves segment boundaries to
  // line up with pitch periods.
  int copy_start = tempcoef->index( startt );
  int copy_end   = tempcoef->index( endt );
  //copy_end -= 1; //so that adjacent units don't start and end with same frame

  int copy_len   = copy_end - copy_start;
  //int copy_len   = copy_end - copy_start + 1;

  startt = tempcoef->t( copy_start );
  endt = tempcoef->t( copy_end );

  if( copy_len == 0 ){
    EST_warning( "%s(%f->%f): %s_%s diphone length means 1 pitchmark will be duplicated",
		 fname.str(), startt, endt, phone1->S("name").str(), phone2->S("name").str() );
    copy_len=1;
  }
  else if( copy_len < 0 ){
    EST_error( "%s(%f->%f): %s_%s diphone length renders %d pitchmark",
	       fname.str(), startt, endt, phone1->S("name").str(), phone2->S("name").str(), copy_len );
  }

  tempcoef->copy_sub_track( *coef, copy_start, copy_len );

  *midframe = coef->index( midt );

  // adjust timing, which Festival synthesis code makes assumptions about
  // SPECIFICALLY, the unisyn module wants all units to start from
  // the first value above 0.0 (as the first pitch mark)
  float t_off = (copy_start!=0) ? tempcoef->t(copy_start-1) : 0.0;
  int nframes = coef->num_frames();
  for( int i=0; i<nframes; ++i )
    coef->t(i) -= t_off;

  //start waveform at previous pitchmark (this is period approximation used)
  int st_sample = (int)rint( t_off * (float) wav_srate );

  //preferably end waveform at following pitchmark (follows convention in UniSyn module)
  int end_sample;
  if( copy_end < tempcoef->num_frames() )
    end_sample = (int) rint( tempcoef->t(copy_end) * (float) wav_srate );
  //if( copy_end+1 < tempcoef->num_frames() )
  //  end_sample = (int) rint( tempcoef->t(copy_end+1) * (float) wav_srate );
  else{
    // estimate from previous pitch mark shift
    int pp_centre_sample = (int) rint( endt * (float) wav_srate );
    int pp_first_sample  = (int) rint( tempcoef->t(copy_end) * (float) wav_srate );
    //int pp_first_sample  = (int) rint( tempcoef->t(copy_end-1) * (float) wav_srate );
    end_sample           = (2*pp_centre_sample)-pp_first_sample;
  }

  // (obviously, we would want to load and cache any files         //
  // which haven't been loaded yet, rather than just load          //
  // the parts each and every time)                                //
  if( sig->load( wave_dir+fname+wave_ext,                          //
		 st_sample, end_sample-st_sample+1) != read_ok )   //
    EST_error( "Couldn't load data file %s",                       //
	       (const char*) (wave_dir+fname+wave_ext) );          //

  delete tempcoef;
}

inline EST_VTCandidate* makeCandidate( const EST_Item *target_ph1,
				       const EST_Item *cand_ph1,
				       const EST_TargetCost *tc,
				       const TCData *tcd,
				       const TCDataHash *tcdatahash,
				       float tc_weight,
				       const DiphoneVoiceModule *dvm_p )
{
  // hack to avoid overhead of string creation and deletion
  // (EST feature access should really be changed to take
  // const char* instead of const EST_String& )
  static const EST_String extendLeft_str("extendLeft");
  static const EST_String extendRight_str("extendRight");
  static const EST_String jccid_str("jccid");

  EST_VTCandidate *c = new EST_VTCandidate;
  CHECK_PTR(c);

  EST_Item *cand_ph2 = cand_ph1->next();

  // set up all the members we can here
  c->s = const_cast<EST_Item*>(cand_ph1);

  EST_FVector *left, *right;
  if( target_ph1->f_present( extendLeft_str ) )
    left = fvector( cand_ph1->features().val( "startcoef" ) );
  else
    left = fvector( cand_ph1->features().val( "midcoef" ) );

  if( target_ph1->next()->f_present( extendRight_str ) )
    right = fvector( cand_ph2->features().val( "endcoef" ) );
  else
    right = fvector( cand_ph2->features().val( "midcoef" ) );

  // an abuse of the "name" EST_Val member to store data we want instead
  // of what is intended to go there
  // (will become unnecessary with a more general candidate class)
  DiphoneCandidate *cand = new DiphoneCandidate( cand_ph1, dvm_p, left, right );
  CHECK_PTR(cand);
  c->name = est_val( cand ); //to get synthesis parameters (deleted by EST_Val c->name)

  if( cand_ph1->f_present( jccid_str ) ){
    cand->ph1_jccid = cand_ph1->features().val( "jccid" ).Int();
    cand->ph1_jccindex = cand_ph1->features().val( "jccindex" ).Int();
  }

  if( cand_ph2->f_present( jccid_str ) ){
    cand->ph1_jccid = cand_ph2->features().val( "jccid" ).Int();
    cand->ph1_jccindex = cand_ph2->features().val( "jccindex" ).Int();
  }

  if(tc->is_flatpack())
    c->score = tc_weight*
      ((const EST_FlatTargetCost *)tc)
      ->operator()( tcd,
		    tcdatahash->val( const_cast<EST_Item*>(cand_ph1) ) );
  else
    c->score = tc_weight*tc->operator()( target_ph1, cand_ph1 );

  return c;
}

inline void itemListToCandidateList( ItemList::Entries &it,
				     EST_VTCandidate **head,
				     EST_VTCandidate **tail,
				     const EST_Item *target_ph1,
				     const EST_TargetCost *tc,
				     const TCDataHash *tcdh,
				     const TCDataHash *tcdatahash,
				     float tc_weight,
				     int count,
				     const DiphoneVoiceModule *dvm_p )

{
  int i=0;

  if( count > 0 ){
    TCData *tcd = tcdh->val( const_cast<EST_Item*>(target_ph1) );
    EST_VTCandidate *nextc = 0;

    // make last one first
    EST_VTCandidate *c = makeCandidate( target_ph1, (*it), tc, tcd, tcdatahash, tc_weight, dvm_p );
    c->next = nextc;
    *tail = c;

    // then iterate back prepending to linked list
    // (order reversed because using c->next)
    nextc = c;
    it++; i++;
    for( ; (it && i<count); it++, i++ ){
      c = makeCandidate( target_ph1, (*it), tc, tcd, tcdatahash, tc_weight, dvm_p );
      c->next = nextc;
      nextc = c;
    }

    *head = c; // keep hold of last one set up
  }

  return;
}

int DiphoneVoiceModule::getCandidateList( const EST_Item& target,
					  const EST_TargetCost* tc,
					  const TCDataHash *tcdh,
					  float tc_weight,
					  EST_VTCandidate **head,
					  EST_VTCandidate **tail ) const
{
  int nfound = 0;
  const EST_Item *target_ph1 = item(target.f("ph1"));

  int found = 0;
  const ItemList *candidateItemList = catalogue->val( target.S("name"), found );
  if( found != 0 ){
    nfound = candidateItemList->length();

    ItemList::Entries it = ItemList::Entries(*candidateItemList);

    itemListToCandidateList( it,
			     head, tail,
			     target_ph1,
			     tc, tcdh, tcdatahash, tc_weight,
			     nfound, this );
  }

  return nfound;
}

int DiphoneVoiceModule::getPhoneList( const EST_String &phone, ItemList &list )
{
  unsigned int n=0;

  if( utt_dbase != 0 ){
    for( EST_Litem *it=utt_dbase->head(); it!=0 ; it=it->next() ){
      EST_Item *ph=(*utt_dbase)(it)->relation("Segment")->head();
      for( ; ph!=0; ph=ph->next() ){
	if( ph->S("name") == phone ){
	  list.append( ph );
	  n++;
	}
      }
    }
  }

  return n;
}

bool DiphoneVoiceModule::getUtterance( EST_Utterance** utt, int n ) const
{
  if( n<0 || n>(utt_dbase->length()-1) )
    EST_error( "Utterance index out of bounds" );

  if( utt == 0 )
    EST_error( "Invalid utterance" );

  // deep copy the utterance in question
  *utt = new EST_Utterance( *(utt_dbase->nth(n)) );
  CHECK_PTR(utt);

  return true;
}

bool DiphoneVoiceModule::getUtterance( EST_Utterance **utt,
				       const EST_String &feat_name,
				       const EST_Val &value ) const
{
  //search down list of utterance structures, comparing
  // fileid feature.  If find a match, return pointer to that
  // utterance.
  for( EST_Litem *it=utt_dbase->head(); it!=0 ; it=it->next() )
    if( (*utt_dbase)(it)->f.val(feat_name) == value ){
      *utt = (*utt_dbase)(it);
      return true;
    }

  return false;
}

void DiphoneVoiceModule::getDiphoneCoverageStats(EST_DiphoneCoverage *dc) const
{
  for( EST_Litem *it=utt_dbase->head(); it!=0 ; it=it->next() )
    dc->add_stats((*utt_dbase)(it));
}

unsigned int DiphoneVoiceModule::numUnitTypes() const
{
  return catalogue ? catalogue->num_entries() : 0;
}

unsigned int DiphoneVoiceModule::numModuleUnits() const
{
  unsigned int sum=0;

  if( catalogue != 0 ){
    EST_TStringHash<ItemList*>::Entries it;

    for( it.begin( *catalogue ); it; it++ )
      sum += it->v->length(); //EST_UList.length() counts the entries :(
  }

  return sum;
}

unsigned int DiphoneVoiceModule::numAvailableCandidates( const EST_String &unit ) const
{
  int number=0;

  int found=0;
  const ItemList *candidateItemList = catalogue->val( unit, found );

  if( found > 0 )
    number = candidateItemList->length();

  return number;
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!--<!DOCTYPE configuration SYSTEM "configuration.dtd">-->
<configuration>
    <!--配置名称-->
    <config-name>测试配置</config-name>

    <!--主公众号的配置-->
    <init-main>
        <appid>wx73e2dd423f007551</appid>
        <appsecret>d4624c36b6795d1d99dcf0547af5443d</appsecret>
        <token>zigui20120518</token>
    </init-main>

    <!--缓存配置-->
    <cache-config>
        <cache-name>FileCache</cache-name>
        <cache-class>org.ike.wechat.cache.DefaultFileCache</cache-class>
        <file-path>F:/Projects/IkeChat/token.conf</file-path>
        <description>文件方式</description>
    </cache-config>
    <!--数据库缓存方式
    <cache-config>
        <cache-name>DBCache</cache-name>
        <class-path>demo</class-path>
        <dbconfig>
            <driver></driver>
            <db-type></db-type>
            <url></url>
            <user></user>
            <password></password>
        </dbconfig>
        <description>数据库方式</description>
    </cache-config>
    -->

    <!--其他参数配置-->
    <init-param>
        <param-name>测试参数名称</param-name>
        <param-value>测试参数值</param-value>
    </init-param>

    <!--公众号群集配置(可选项)-->
    <cluster-config>
        <config-path>classpath:cluster-chat-config</config-path>
        <enable>false</enable>
    </cluster-config>

    <!--扩展的错误信息配置(可选项)-->
    <extend-err-config>
        <config-path>classpath:err-extention</config-path>
        <enable>true</enable>
    </extend-err-config>

    <response-filter>
        <filter-name>ResponseFilter</filter-name>
        <filter-class>org.ike.wechat.websupport.filter.ResponseListener</filter-class>
    </response-filter>
</configuration>


text:
#ifndef APREQ_H
#define APREQ_H

#ifdef APREQ_DEBUG
#include <assert.h>
#endif

#include "apr_tables.h"
#include <stddef.h>

#ifdef  __cplusplus
 extern "C" {
#endif

/**
 * @file apreq.h
 * @brief Main header file...
 * @ingroup libapreq2
 *
 * Define the generic APREQ_ macros and common data structures.
 */

#ifndef WIN32
/**
 * The public APREQ functions are declared with APREQ_DECLARE(), so they may
 * use the most appropriate calling convention.  Public APR functions with
 * variable arguments must use APR_DECLARE_NONSTD().
 *
 * @remark Both the declaration and implementations must use the same macro.
 */
/** APREQ_DECLARE(rettype) apeq_func(args)
 */
#define APREQ_DECLARE(d)                APR_DECLARE(d)
/**
 * The public APEQ functions using variable arguments are declared with
 * APEQ_DECLARE_NONSTD(), as they must follow the C language calling convention.
 * @see APEQ_DECLARE @see APEQ_DECLARE_DATA
 * @remark Both the declaration and implementations must use the same macro.
 * @example
 */
/** APEQ_DECLARE_NONSTD(rettype) apr_func(args, ...);
 */
#define APREQ_DECLARE_NONSTD(d)         APR_DECLARE_NONSTD(d)
/**
 * The public APREQ variables are declared with APREQ_DECLARE_DATA.
 * This assures the appropriate indirection is invoked at compile time.
 * @see APREQ_DECLARE @see APREQ_DECLARE_NONSTD
 * @remark Note that the declaration and implementations use different forms,
 * but both must include the macro.
 */
/** extern APREQ_DECLARE_DATA type apr_variable;\n
 * APREQ_DECLARE_DATA type apr_variable = value;
 */
#define APREQ_DECLARE_DATA
#elif defined (APREQ_DECLARE_STATIC)
#define APREQ_DECLARE(type)             type __stdcall
#define APREQ_DECLARE_NONSTD(type)      type
#define APREQ_DECLARE_DATA
#elif defined (APREQ_DECLARE_EXPORT)
#define APREQ_DECLARE(type)             __declspec(dllexport) type __stdcall
#define APREQ_DECLARE_NONSTD(type)      __declspec(dllexport) type
#define APREQ_DECLARE_DATA              __declspec(dllexport)
#else
#define APREQ_DECLARE(type)             __declspec(dllimport) type __stdcall
#define APREQ_DECLARE_NONSTD(type)      __declspec(dllimport) type
#define APREQ_DECLARE_DATA              __declspec(dllimport)
#endif

/**
 * Read chucks of data in 64k blocks from the request
 */

#define APREQ_DEFAULT_READ_BLOCK_SIZE   (64  * 1024)

/**
 * Maximum number of bytes mod_apreq2 will send off to libapreq2 for parsing.
 * mod_apreq2 will log this event and subsequently remove itself
 * from the filter chain.
 * @see ap_set_read_limit
 */
#define APREQ_DEFAULT_READ_LIMIT        (64 * 1024 * 1024)
/**
 * Maximum number of bytes mod_apreq2 will let accumulate within the
 * heap-buckets in a brigade. Excess data will be spooled to an
 * appended file bucket
 * @see ap_set_brigade_read_limit
 */
#define APREQ_DEFAULT_BRIGADE_LIMIT     (256 * 1024)

/**
 * Number of elements in the initial apr_table
 * @see apr_table_make
 */
#define APREQ_DEFAULT_NELTS              8

/**
 * Check to see if specified bit f is off in bitfield name
 */
#define APREQ_FLAGS_OFF(f, name) ((f) &= ~(name##_MASK << name##_BIT))
/**
 * Check to see if specified bit f is on in bitfield name
 */
#define APREQ_FLAGS_ON(f, name)  ((f) |=  (name##_MASK << name##_BIT))
/**
 *  Get specified bit f in bitfield name
 */
#define APREQ_FLAGS_GET(f, name) (((f) >> name##_BIT) & name##_MASK)
/**
 * Set specified bit f in bitfield name to value
 * Note the below BIT/Mask defines are used sans the
 * _BIT, _MASK because of the this define's \#\#_MASK, \#\#_BIT usage.
 * Each come in a pair
 */
#define APREQ_FLAGS_SET(f, name, value)                 \
    ((f) = (((f) & ~(name##_MASK << name##_BIT))        \
            | ((name##_MASK & (value)) << name##_BIT)))

/**
 * Charset Bit
 * @see APREQ_FLAGS_OFF @see APREQ_FLAGS_ON
 * @see APREQ_FLAGS_GET @see APREQ_FLAGS_SET
 */
#define APREQ_CHARSET_BIT           0

/**
 * Charset Mask
 * @see APREQ_FLAGS_OFF @see APREQ_FLAGS_ON
 * @see APREQ_FLAGS_GET @see APREQ_FLAGS_SET
 */
#define APREQ_CHARSET_MASK        255

/**
 * Tainted Bit
 * @see APREQ_FLAGS_OFF @see APREQ_FLAGS_ON
 * @see APREQ_FLAGS_GET @see APREQ_FLAGS_SET
 */
#define APREQ_TAINTED_BIT           8
/**
 * Tainted Mask
 * @see APREQ_FLAGS_OFF @see APREQ_FLAGS_ON
 * @see APREQ_FLAGS_GET @see APREQ_FLAGS_SET
 */
#define APREQ_TAINTED_MASK          1

/**
 * Cookier Version Bit
 * @see APREQ_FLAGS_OFF @see APREQ_FLAGS_ON
 * @see APREQ_FLAGS_GET @see APREQ_FLAGS_SET
 */

#define APREQ_COOKIE_VERSION_BIT   11
/**
 * Cookie Version Mask
 * @see APREQ_FLAGS_OFF @see APREQ_FLAGS_ON
 * @see APREQ_FLAGS_GET @see APREQ_FLAGS_SET
 */
#define APREQ_COOKIE_VERSION_MASK   3

/**
 * Cookie's Secure Bit
 * @see APREQ_FLAGS_OFF @see APREQ_FLAGS_ON
 * @see APREQ_FLAGS_GET @see APREQ_FLAGS_SET
 */
#define APREQ_COOKIE_SECURE_BIT    13
/**
 * Cookie's Secure Mask
 * @see APREQ_FLAGS_OFF @see APREQ_FLAGS_ON
 * @see APREQ_FLAGS_GET @see APREQ_FLAGS_SET
 */
#define APREQ_COOKIE_SECURE_MASK    1

/**
 * Cookie's HttpOnly Bit
 * @see APREQ_FLAGS_OFF @see APREQ_FLAGS_ON
 * @see APREQ_FLAGS_GET @see APREQ_FLAGS_SET
 */
#define APREQ_COOKIE_HTTPONLY_BIT    14
/**
 * Cookie's HttpOnly Mask
 * @see APREQ_FLAGS_OFF @see APREQ_FLAGS_ON
 * @see APREQ_FLAGS_GET @see APREQ_FLAGS_SET
 */
#define APREQ_COOKIE_HTTPONLY_MASK    1

/** Character encodings. */
typedef enum {
    APREQ_CHARSET_ASCII  =0,
    APREQ_CHARSET_LATIN1 =1, /* ISO-8859-1   */
    APREQ_CHARSET_CP1252 =2, /* Windows-1252 */
    APREQ_CHARSET_UTF8   =8
} apreq_charset_t;

/** @enum apreq_join_t Join type */
typedef enum {
    APREQ_JOIN_AS_IS,      /**< Join the strings without modification */
    APREQ_JOIN_ENCODE,     /**< Url-encode the strings before joining them */
    APREQ_JOIN_DECODE,     /**< Url-decode the strings before joining them */
    APREQ_JOIN_QUOTE       /**< Quote the strings, backslashing existing quote marks. */
} apreq_join_t;

/** @enum apreq_match_t Match type */
typedef enum {
    APREQ_MATCH_FULL,       /**< Full match only. */
    APREQ_MATCH_PARTIAL     /**< Partial matches are ok. */
} apreq_match_t;

/** @enum apreq_expires_t Expiration date format */
typedef enum {
    APREQ_EXPIRES_HTTP,       /**< Use date formatting consistent with RFC 2616 */
    APREQ_EXPIRES_NSCOOKIE    /**< Use format consistent with Netscape's Cookie Spec */
} apreq_expires_t;

/** @brief libapreq's pre-extensible string type */
typedef struct apreq_value_t {
    char             *name;    /**< value name */
    apr_size_t        nlen;    /**< length of name */
    apr_size_t        dlen;    /**< length of data */
    char              data[1]; /**< value data  */
} apreq_value_t;

/**
 * Adds the specified apreq_value_t to the apr_table_t.
 *
 * @param v value to add
 * @param t add v to this table
 *
 * @return void
 *
 * @ see apr_table_t @see apr_value_t
 */

static APR_INLINE
void apreq_value_table_add(const apreq_value_t *v, apr_table_t *t) {
    apr_table_addn(t, v->name, v->data);
}

/**
 * @param T type
 * @param A attribute
 * @param P
 *
 * XXX
 */
#define apreq_attr_to_type(T,A,P) ( (T*) ((char*)(P)-offsetof(T,A)) )

/**
 * Initialize libapreq2. Applications (except apache modules using
 * mod_apreq) should call this exactly once before they use any
 * libapreq2 modules.  If you want to modify the list of default parsers
 * with apreq_register_parser(), please use apreq_pre_initialize()
 * and apreq_post_initialize() instead.
 *
 * @param pool a base pool persisting while libapreq2 is used
 * @remarks after you detroy the pool, you have to call this function again
 *    with a new pool if you still plan to use libapreq2
 */
APREQ_DECLARE(apr_status_t) apreq_initialize(apr_pool_t *pool);

/**
 * Pre-initialize libapreq2. Applications (except apache modules using
 * mod_apreq2) should call this exactly once before they register custom
 * parsers with libapreq2. mod_apreq2 does this automatically during the
 * post-config phase, so modules that need call apreq_register_parser should
 * create a post-config hook using APR_HOOK_MIDDLE.
 *
 * @param pool a base pool persisting while libapreq2 is used
 * @remarks after you detroyed the pool, you have to call this function again
 *    with a new pool if you still plan to use libapreq2
 */
APREQ_DECLARE(apr_status_t) apreq_pre_initialize(apr_pool_t *pool);

/**
 * Post-initialize libapreq2. Applications (except apache modules using
 * mod_apreq2) should this exactly once before they use any
 * libapreq2 modules for parsing.
 *
 * @param pool the same pool that was used in apreq_pre_initialize().
 */
APREQ_DECLARE(apr_status_t) apreq_post_initialize(apr_pool_t *pool);

#ifdef __cplusplus
 }
#endif

#endif /* APREQ_H */


text:
package com.otaykalo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@SpringBootApplication
@EnableSwagger2
public class ConfigurableAppApplication {

	public static void main(String[] args) {
		SpringApplication.run(ConfigurableAppApplication.class, args);
	}
}


text:
namespace Bull
{
    namespace prv
    {
        Win32Error::Win32Error(const std::string& file, Uint64 line, const std::string& source, const std::string& description) :
                Exception(file, line, "Win32Error", source, description + " - " + createDescription())
        {
            /// Nothing
        }

        std::string Win32Error::createDescription() const
        {
            DWORD error = GetLastError();

            if(!error)
            {
                Throw(LogicError, "No error occurred");
            }

            char* messageBuffer = nullptr;
            size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
                                         nullptr, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR) &messageBuffer, 0, nullptr);

            std::string message(messageBuffer, size);

            LocalFree(messageBuffer);

            return message;
        }
    }
}


text:
using System;
using Utilities.Reflection.Emit.Interfaces;
using Xunit;

namespace UnitTests.Reflection.Emit
{
    public class PropertyBuilder
    {
        [Fact]
        public void Load()
        {
            Utilities.Reflection.Emit.Assembly Assembly = new Utilities.Reflection.Emit.Assembly("TestAssembly");
            Utilities.Reflection.Emit.TypeBuilder TestType = Assembly.CreateType("TestType");
            IMethodBuilder Method = TestType.CreateConstructor();
            Utilities.Reflection.Emit.PropertyBuilder TestProperty = (Utilities.Reflection.Emit.PropertyBuilder)TestType.CreateProperty("TestProperty", typeof(int));
            Assert.Throws<NullReferenceException>(() => TestProperty.Load(null));
            Assert.DoesNotThrow(() => TestProperty.Load(Method.Generator));
        }

        [Fact]
        public void Save()
        {
            Utilities.Reflection.Emit.Assembly Assembly = new Utilities.Reflection.Emit.Assembly("TestAssembly");
            Utilities.Reflection.Emit.TypeBuilder TestType = Assembly.CreateType("TestType");
            IMethodBuilder Method = TestType.CreateConstructor();
            Utilities.Reflection.Emit.PropertyBuilder TestProperty = (Utilities.Reflection.Emit.PropertyBuilder)TestType.CreateProperty("TestProperty", typeof(int));
            Assert.Throws<NullReferenceException>(() => TestProperty.Save(null));
            Assert.DoesNotThrow(() => TestProperty.Save(Method.Generator));
        }

        [Fact]
        public void PlusPlus()
        {
            Utilities.Reflection.Emit.Assembly Assembly = new Utilities.Reflection.Emit.Assembly("TestAssembly");
            Utilities.Reflection.Emit.TypeBuilder TestType = Assembly.CreateType("TestType");
            IMethodBuilder Method = TestType.CreateConstructor();
            Utilities.Reflection.Emit.PropertyBuilder TestProperty = (Utilities.Reflection.Emit.PropertyBuilder)TestType.CreateProperty("TestProperty", typeof(int));
            Assert.DoesNotThrow(() => ++TestProperty);
        }

        [Fact]
        public void MinusMinus()
        {
            Utilities.Reflection.Emit.Assembly Assembly = new Utilities.Reflection.Emit.Assembly("TestAssembly");
            Utilities.Reflection.Emit.TypeBuilder TestType = Assembly.CreateType("TestType");
            IMethodBuilder Method = TestType.CreateConstructor();
            Utilities.Reflection.Emit.PropertyBuilder TestProperty = (Utilities.Reflection.Emit.PropertyBuilder)TestType.CreateProperty("TestProperty", typeof(int));
            Assert.DoesNotThrow(() => --TestProperty);
        }
    }
}


text:
import * as simplegit from "simple-git/promise";
import * as fs from "fs";
import * as rimraf from "rimraf";
import * as path from "path";
import * as process from "process";
import { logWarning } from "./agentSpecific";
import { BranchSummary } from "simple-git/typings/response";

// A wrapper to make sure that directory delete is handled in sync
function rimrafPromise (localpath)  {
    return new Promise((resolve, reject) => {
        rimraf(localpath, () => {
            resolve();
        }, (error) => {
            reject(error);
        });
    });
}

function mkDirByPathSync(targetDir, { isRelativeToScript = false } = {}) {
    const sep = path.sep;
    const initDir = path.isAbsolute(targetDir) ? sep : "";
    const baseDir = isRelativeToScript ? __dirname : ".";

    return targetDir.split(sep).reduce((parentDir, childDir) => {
      const curDir = path.resolve(baseDir, parentDir, childDir);
      try {
        fs.mkdirSync(curDir);
      } catch (err) {
        if (err.code === "EEXIST") { // curDir already exists!
          return curDir;
        }

        // To avoid `EISDIR` error on Mac and `EACCES`-->`ENOENT` and `EPERM` on Windows.
        if (err.code === "ENOENT") { // Throw the original parentDir error on curDir `ENOENT` failure.
          throw new Error(`EACCES: permission denied, mkdir '${parentDir}'`);
        }

        const caughtErr = ["EACCES", "EPERM", "EISDIR"].indexOf(err.code) > -1;
        if (!caughtErr || caughtErr && curDir === path.resolve(targetDir)) {
          throw err; // Throw if it's just the last created dir.
        }
      }

      return curDir;
    }, initDir);
  }

export function GetWorkingFolder(localpath, filename, logInfo): any {
    var pathParts = path.parse(filename);
    if (pathParts.dir && pathParts.dir !== "/" && pathParts.dir !== "\\") {
        var targetPath = path.join(localpath, path.join(pathParts.dir));
        if (!fs.existsSync(targetPath)) {
            logInfo(`Creating the directory ${targetPath}`);
            mkDirByPathSync(targetPath);
        }
        return targetPath;
    } else {
        logInfo(`No sub-directory passed change to ${localpath}`);
        return localpath;
    }
}

export function GetWorkingFile(filename, logInfo): any {
    var pathParts = path.parse(filename);
    var name = pathParts.base;
    logInfo(`Working file name is ${name}`);
    return name;
}

export function GetProtocol(url: string, logInfo): string {
    var protocol = "https";
    logInfo(`The provided repo URL is ${url}`);
    if (url.indexOf("://") !== -1) {
        protocol = url.substr(0, url.indexOf("//") - 1 );
    }
    logInfo(`The protocol is ${protocol}`);
    return protocol;
}

export function GetTrimmedUrl(url: string, logInfo): string {
    var fixedUrl = url;
    logInfo(`The provided repo URL is ${fixedUrl}`);
    if (fixedUrl.indexOf("://") !== -1) {
        logInfo(`Removing leading http:// or https:// block`);
        fixedUrl = fixedUrl.substr(fixedUrl.indexOf("://") + 3);
    }
    if (fixedUrl.indexOf("@") !== -1) {
        logInfo(`Removing leading username@ block`);
        fixedUrl = fixedUrl.substr(fixedUrl.indexOf("@") + 1);
    }
    logInfo(`Trimmed the URL to ${fixedUrl}`);
    return fixedUrl;
}

export async function CloneWikiRepo(
    protocol,
    repo,
    localpath,
    user,
    password,
    logInfo,
    logError,
    injectExtraHeader,
    branch) {
    const git = simplegit();

    let remote = "";
    let logremote = ""; // used to make sure we hide the password in logs
    var extraHeaders = [];  // Add handling for #613

    if (injectExtraHeader) {
        remote = `${protocol}://${repo}`;
        logremote = remote;
        extraHeaders = [`-c http.extraheader=AUTHORIZATION: bearer ${password}`];
        logInfo (`Injecting the authentication via the clone command using paramter -c http.extraheader='AUTHORIZATION: bearer ***'`);
    } else {
        if (password === null) {
            remote = `${protocol}://${repo}`;
            logremote = remote;
        } else if (user === null) {
            remote = `${protocol}://${password}@${repo}`;
            logremote = `${protocol}://***@${repo}`;
        } else {
            remote = `${protocol}://${user}:${password}@${repo}`;
            logremote = `${protocol}://${user}:***@${repo}`;
        }
    }

    logInfo(`URL used ${logremote}`);

    try {
        if (fs.existsSync(localpath)) {
            await rimrafPromise(localpath);
        }
        logInfo(`Cleaned ${localpath}`);

        await git.silent(true).clone(remote, localpath, extraHeaders);
        logInfo(`Cloned ${repo} to ${localpath}`);

        await git.cwd(localpath);

        if (branch) {
            logInfo(`Checking out the requested branch ${branch}`);
            await git.checkout(branch);
        }

    } catch (error) {
        logError(error);
    }

}


text:
<?php

namespace Magento\User\Test\TestCase;

use Magento\User\Test\Fixture\Role;
use Magento\User\Test\Page\Adminhtml\UserRoleEditRole;
use Magento\User\Test\Page\Adminhtml\UserRoleIndex;
use Magento\Mtf\TestCase\Injectable;

/**
 * Test Flow:
 * 1. Log in as default admin user
 * 2. Go to System>Permissions>User Roles
 * 3. Press "+" button to start create New Role
 * 4. Fill in all data according to data set
 * 5. Save role
 * 6. Perform assertions
 *
 * @group ACL_(PS)
 * @ZephyrId MAGETWO-23413
 */
class CreateAdminUserRoleEntityTest extends Injectable
{
    /* tags */
    const MVP = 'no';
    const DOMAIN = 'PS';
    /* end tags */

    /**
     * UserRoleIndex page.
     *
     * @var UserRoleIndex
     */
    protected $userRoleIndex;

    /**
     * UserRoleEditRole page.
     *
     * @var UserRoleEditRole
     */
    protected $userRoleEditRole;

    /**
     * Setup data for test.
     *
     * @param UserRoleIndex $userRoleIndex
     * @param UserRoleEditRole $userRoleEditRole
     */
    public function __inject(UserRoleIndex $userRoleIndex, UserRoleEditRole $userRoleEditRole)
    {
        $this->userRoleIndex = $userRoleIndex;
        $this->userRoleEditRole = $userRoleEditRole;
    }

    /**
     * Runs Create Admin User Role Entity test.
     *
     * @param Role $role
     */
    public function testCreateUserRole(Role $role)
    {
        //Steps
        $this->userRoleIndex->open();
        $this->userRoleIndex->getRoleActions()->addNew();
        $this->userRoleEditRole->getRoleFormTabs()->fill($role);
        $this->userRoleEditRole->getPageActions()->save();
    }
}


text:
FAQ
---

#### What's the license?

These libraries are in the public domain (or the equivalent where that is not
possible). You can do anything you want with them. You have no legal obligation
to do anything else, although I appreciate attribution.

#### If I wrap an stb library in a new library, does the new library have to be public domain?

No.

#### A lot of these libraries seem redundant to existing open source libraries. Are they better somehow?

Generally they're only better in that they're easier to integrate,
easier to use, and easier to release (single file; good API; no
attribution requirement). They may be less featureful, slower,
and/or use more memory. If you're already using an equivalent
library, there's probably no good reason to switch.

#### Why single-file headers?

Windows doesn't have standard directories where libraries
live. That makes deploying libraries in Windows a lot more
painful than open source developers on Unix-derivates generally
realize. (It also makes library dependencies a lot worse in Windows.)

Making them a single file makes it very easy to just
drop them into a project that needs them. (Of course you can
still put them in a proper shared library tree if you want.)

The difference between 10 files and 9 files is not a big deal,
but the difference between 2 files and 1 file is a big deal.

#### Why "stb"? Is this something to do with Set-Top Boxes?

No, they are just the initials for my name, Sean T. Barrett.
This was not chosen out of egomania, but as a semi-robust
way of namespacing the filenames and source function names.

#### Will you add more image types to stb_image.c?

If people submit them, I generally add them, but the goal of stb_image
is less for applications like image viewer apps (which need to support
every type of image under the sun) and more for things like games which
can choose what images to use, so I may decline to add them if they're
too rare or if the size of implementation vs. apparent benefit is too low.

#### Are there other single-file public-domain libraries out there?

Yes. I'll put a list here when people remind me what they are.

#### Do you have any advice on how to create my own single-file library?

Yes. https://github.com/nothings/stb/blob/master/docs/stb_howto.txt

#### Why public domain?

Because more people will use it. Because it's not viral, people
are not obligated to give back, so you could argue that it hurts
the *development* of it, and then because it doesn't develop as
well it's not as good, and then because it's not as good, in the
long run maybe fewer people will use it. I have total respect for
that opinion, but I just don't believe it myself for most software.

#### Why C?

Primarily, because I use C, not C++. But it does also make it easier
for other people to use them from other languages.

#### Why not C99? stdint.h, declare-anywhere, etc.

I still use MSVC 6 (1998) as my IDE because it has better human factors
for me than later versions of MSVC.


text:
package com.sksamuel.scrimage

import org.scalatest.{FunSuite, Matchers}

/** @author Stephen Samuel */
class Issue54Test extends FunSuite with Matchers {

  test("image for issue 54 should load as expected") {
    Image(getClass.getResourceAsStream("/issue54.jpg")).width shouldBe 2560
    Image(getClass.getResourceAsStream("/issue54.jpg")).scaleToWidth(400) shouldBe
      Image(getClass.getResourceAsStream("/issue54.png"))
  }
}


text:
package main_test

import (
	"bytes"
	"encoding/json"
	"log"
	"net/http"
	"net/http/httptest"
	"os"
	"strconv"
	"testing"

	"."
)

var app main.App

func TestMain(m *testing.M) {
	app = main.App{}
	app.Initialize(
		os.Getenv("TEST_DB_USERNAME"),
		os.Getenv("TEST_DB_PASSWORD"),
		os.Getenv("TEST_DB_NAME"))

	ensureTableExists()
	code := m.Run()
	clearTable()
	os.Exit(code)
}

func ensureTableExists() {
	if _, err := app.DB.Exec(`
	CREATE TABLE IF NOT EXISTS products (
		id SERIAL,
		name TEXT NOT NULL,
		price NUMERIC(10,2) NOT NULL DEFAULT 0.00,
		CONSTRAINT products_pkey PRIMARY KEY (id))`); err != nil {
		log.Fatal(err)
	}
}

func clearTable() {
	app.DB.Exec("TRUNCATE TABLE products")
	app.DB.Exec("ALTER SEQUENCE products_id_seq RESTART WITH 1")
}

func executeRequest(req *http.Request) *httptest.ResponseRecorder {
	rr := httptest.NewRecorder()
	app.Router.ServeHTTP(rr, req)

	return rr
}

func checkResponseCode(t *testing.T, expected, actual int) {
	if expected != actual {
		t.Errorf("Expected response code %d. Got %d\n", expected, actual)
	}
}

func addProducts(count int) {
	if count < 1 {
		count = 1
	}

	for i := 0; i < count; i++ {
		app.DB.Exec(
			"INSERT INTO products(name, price) VALUES ($1, $2)",
			"Product #"+strconv.Itoa(i), (i+1.0)*10)
	}
	app.DB.Exec("COMMIT")
}

// TESTS:
func TestEmptyTable(t *testing.T) {
	clearTable()

	req, _ := http.NewRequest("GET", "/products", nil)
	resp := executeRequest(req)

	checkResponseCode(t, http.StatusOK, resp.Code)

	if body := resp.Body.String(); body != "[]" {
		t.Errorf("Expected an empty array. Got %q", body)
	}
}

func TestGetNonExistentProduct(t *testing.T) {
	clearTable()

	req, _ := http.NewRequest("GET", "/product/11", nil)
	resp := executeRequest(req)

	checkResponseCode(t, http.StatusNotFound, resp.Code)

	var m map[string]string
	json.Unmarshal(resp.Body.Bytes(), &m)
	if m["error"] != "Product not found" {
		t.Errorf("Expected the 'error' key of the respose to be set to 'Product not found'. Got %q", m["error"])
	}
}

func TestCreateProduct(t *testing.T) {
	clearTable()

	payload := []byte(`{"name":"test product","price":11.22}`)

	req, _ := http.NewRequest("POST", "/product", bytes.NewBuffer(payload))
	response := executeRequest(req)

	checkResponseCode(t, http.StatusCreated, response.Code)

	var m map[string]interface{}
	json.Unmarshal(response.Body.Bytes(), &m)

	if m["name"] != "test product" {
		t.Errorf("Expected product name to be 'test product'. Got '%v'", m["name"])
	}

	if m["price"] != 11.22 {
		t.Errorf("Expected product price to be '11.22'. Got '%v'", m["price"])
	}

	// the id is compared to 1.0 because JSON unmarshaling converts numbers to
	// floats, when the target is a map[string]interface{}
	if m["id"] != 1.0 {
		t.Errorf("Expected product ID to be '1'. Got '%v'", m["id"])
	}
}

func TestGetProduct(t *testing.T) {
	clearTable()
	addProducts(1)

	req, _ := http.NewRequest("GET", "/product/1", nil)
	response := executeRequest(req)

	checkResponseCode(t, http.StatusOK, response.Code)
}

func TestUpdateProduct(t *testing.T) {
	clearTable()
	addProducts(1)

	req, _ := http.NewRequest("GET", "/product/1", nil)
	response := executeRequest(req)
	var originalProduct map[string]interface{}
	json.Unmarshal(response.Body.Bytes(), &originalProduct)

	payload := []byte(`{"name":"test product - updated name","price":11.22}`)

	req, _ = http.NewRequest("PUT", "/product/1", bytes.NewBuffer(payload))
	response = executeRequest(req)

	checkResponseCode(t, http.StatusOK, response.Code)

	var m map[string]interface{}
	json.Unmarshal(response.Body.Bytes(), &m)

	if m["id"] != originalProduct["id"] {
		t.Errorf("Expected the id to remain the same (%v). Got %v", originalProduct["id"], m["id"])
	}

	if m["name"] == originalProduct["name"] {
		t.Errorf("Expected the name to change from '%v' to '%v'. Got '%v'", originalProduct["name"], m["name"], m["name"])
	}

	if m["price"] == originalProduct["price"] {
		t.Errorf("Expected the price to change from '%v' to '%v'. Got '%v'", originalProduct["price"], m["price"], m["price"])
	}
}

func TestDeleteProduct(t *testing.T) {
	clearTable()
	addProducts(1)

	req, _ := http.NewRequest("GET", "/product/1", nil)
	response := executeRequest(req)
	checkResponseCode(t, http.StatusOK, response.Code)

	req, _ = http.NewRequest("DELETE", "/product/1", nil)
	response = executeRequest(req)

	checkResponseCode(t, http.StatusOK, response.Code)

	req, _ = http.NewRequest("GET", "/product/1", nil)
	response = executeRequest(req)
	checkResponseCode(t, http.StatusNotFound, response.Code)
}

func TestProductDb(t *testing.T) {
	clearTable()
	addProducts(10)
	products, err := main.GetProducts(app.DB, 0, 100)
	if err != nil {
		t.Errorf("Something went wrong: %s", err)
	}
	if len(products) != 10 {
		t.Errorf("Expected 10 products, got: %s (%d)", products, len(products))
	}
}


text:
using System;
using System.Linq;
using Expressive.Exceptions;
using Expressive.Expressions;
using Expressive.Functions;
using Moq;
using NUnit.Framework;
using NUnit.Framework.Constraints;

namespace Expressive.Tests.Functions
{
    public static class FunctionBaseTests
    {
        [Test]
        public static void TestValidateParameterCountWithNull() =>
            Assert.That(
                () => new MockFunction().Validate(null, 0, 0),
                Throws.ArgumentNullException);

        [TestCase(0, 0, 0, false, TestName = "{m} - No parameters expected and none passed in.")]
        [TestCase(1, 0, 0, true, TestName = "{m} - No parameters expected but some passed in.")]
        [TestCase(0, 1, 0, true, TestName = "{m} - One parameter expected but none passed in.")]
        [TestCase(1, 1, 0, false, TestName = "{m} - One parameter expected and one passed in.")]
        [TestCase(2, 1, 0, true, TestName = "{m} - One parameter expected and two passed in.")]
        [TestCase(0, -1, 1, true, TestName = "{m} - One minimum expected but none passed in.")]
        [TestCase(1, -1, 1, false, TestName = "{m} - One minimum expected and one passed in.")]
        [TestCase(2, -1, 1, false, TestName = "{m} - One minimum expected and two passed in.")]
        public static void TestValidateParameterCount(int parameterCount, int expectedParameterCount, int expectedMinimumCount, bool shouldThrow)
        {
            var parameters = Enumerable.Repeat(Mock.Of<IExpression>(), parameterCount).ToArray();

            Assert.That(
                () => new MockFunction().Validate(parameters, expectedParameterCount, expectedMinimumCount),
                shouldThrow ? (Constraint)Throws.InstanceOf<ParameterCountMismatchException>() : Throws.Nothing);
        }

        private class MockFunction : FunctionBase
        {
            public override string Name => "Mock";

            public override object Evaluate(IExpression[] parameters, Context context) => throw new NotImplementedException();

            public void Validate(IExpression[] parameters, int expectedCount, int minimumCount) =>
                this.ValidateParameterCount(parameters, expectedCount, minimumCount);
        }
    }
}


text:
void run_tests();
int run_fast_tests();
int run_not_slow_tests();
int run_user_defined_tests(const std::vector<std::string> & tests_or_tags);

#endif


text:
import os

from cspark.Updater import Updater

ACCESS_TOKEN = os.environ['ACCESS_TOKEN']


text:
package org.n3r.validator.impl;

import org.apache.commons.lang3.StringUtils;
import org.n3r.validator.EasyValidator;
import org.n3r.validator.EasyValidatorParamAware;
import org.n3r.validator.EasyValidatorTag;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 日期校验器.
 *
 * @author wanglei
 * @since 14-9-6 下午3:25
 */
@EasyValidatorTag("date")
public class DateValidator implements EasyValidator, EasyValidatorParamAware {

    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public Object validate(Object value) {
        if (value == null) return null;

        return value instanceof Date ? (Date) value : validateStringFormat(value + "");
    }

    private Object validateStringFormat(String value) {
        if (StringUtils.isEmpty(value)) return null;

        try {
            return format.parse(value);
        } catch (ParseException e) {
            throw new RuntimeException(value + " can not parsed as " + format);
        }
    }

    @Override
    public void setParameter(String parameter) {
        if (StringUtils.isNotEmpty(parameter))
            format = new SimpleDateFormat(parameter);
    }
}