text:
//---------------------------------------------------------------------------

#ifndef uDrawerH
#define uDrawerH
#include <windows.h>
#include <vcl.h>
#include <list>
#include "config.h"
#include "uFormat.h"

namespace SHEdit
{
  class NSpan;
  class TSHEdit;
  class FontStyle;

  /*!
   * Drawer
   * ======
   * Drawer ensures drawing everything that it is told to draw. It is usually told by TSHEdit to move parts of already-painted information upwards or downwards, to update/repaint cursor and to update it's fontsize or linenumwidth parameters, while by Parser it is ordered to draw text, endlines and eof.
   *
   * When drawing text, the Drawer::x is incremented with width of drawn text waiting for endline to bleach the rest of screen and reset the x again to 0. Also information about length of longest line is kept for setting of horizontal scrollbar's parameters. Just highest 'ever reached' width is kept - in current structure there's no way to keep this parameter up to date (and it's just a visual glitch).
   *
   * Here is not much to document either, just to mention that everything that is not apparently pixel position is usually screen-line position (that means i.e. nth visible line).
   *
   * One more note - UpdateFontSize and updateLinenumWidth does not automatically repaint screen - screen repaint has to be triggered manually.
   * */
  //---------------------------------------------------------------------------
  class Drawer
  {
    private:
      TSHEdit * parent;

      TCanvas * canvas;
      TCanvas * drawcanvas;

      Graphics::TBitmap * bitmap;

      inline int RightBorder();
      inline int BottomBorder();

      int x, y;
      int cx, cy;
      bool con;   //cursorOn
      TColor cursorBGcolor;

      int fontsize;
      int linesize;
      int linenumwidth;
      int lastlinenumcount; //to be able to update lw automatically

      bool linenumsenabled;

      int debugtasks;
      int debugcount;

      int HPos, HMax;
      void __fastcall UpdateHBar();

#ifdef SHEDIT_DEBUG
      void Write(String message);
      void QueueDump();
      void StressTest();
#endif

      void DrawCursor();
      void __fastcall DrawText(String text, bool newline, short linenum, FontStyle format);
      void __fastcall DrawMove(int from, int to, int by);
      void __fastcall DrawEof(short linenum);
      void __fastcall UpdateCursor(int x, int y);
      void __fastcall DrawResize(int w, int h);
      void __fastcall DrawEndl(short linenum, FontStyle format);
      void __fastcall DrawLinenum(int from);
      void __fastcall Paint();

      friend class TSHEdit;
      friend class Parser;
    public:

      __fastcall Drawer(TCanvas * Canvas, TSHEdit * parent) ;
      virtual __fastcall ~Drawer();

      void __fastcall SetFontsize(int size);
      bool __fastcall UpdateLinenumWidth(int count);
      int __fastcall GetLinenumWidth();
      int __fastcall GetFontsize();
      int __fastcall GetLinesize();
      void __fastcall SetLinenumsEnabled(bool enable);
      bool __fastcall GetLinenumsEnabled();

    public:
      friend class TSHEdit;
  };
}
//---------------------------------------------------------------------------
#endif


text:
cask 'progressive-downloader' do
  version '4.1'
  sha256 '88e0979fc4c458601002e5083c0f3d7a67c7735b6f3a73544af946dbbb62baab'

  url "https://www.macpsd.net/update/#{version}/PSD.dmg"
  name 'Progressive Downloader'
  homepage 'https://www.macpsd.net/'

  depends_on macos: '>= :yosemite'

  app 'Progressive Downloader.app'

  zap trash: [
               '~/Library/Application Support/Progressive Downloader Data',
               '~/Library/Caches/com.PS.Downloader',
               '~/Library/Caches/com.PS.PSD',
               '~/Library/Preferences/com.PS.PSD.plist',
             ]
end

redpajama_set_name: RedPajamaGithub


text:
Playing around with implementing a Vim-like editor in Idris. At this stage,
it's merely a toy.

For the F# version of Void see
[this repo](https://github.com/PolyglotSymposium/void).


text:
create table favorite (
  id                        bigint auto_increment not null,
  surfer_id                 bigint,
  user_info_id              bigint,
  constraint pk_favorite primary key (id))
;

create table rating (
  id                        bigint auto_increment not null,
  rating                    integer,
  rating_count              integer,
  user_plus_rating          varchar(255),
  surfer_id                 bigint,
  constraint pk_rating primary key (id))
;

create table surfer (
  id                        bigint auto_increment not null,
  name                      varchar(255),
  hometown                  varchar(255),
  awards                    varchar(255),
  carousel_url              varchar(255),
  bio_url                   varchar(255),
  bio                       longtext,
  slug                      varchar(255),
  type                      varchar(255),
  slug_defined              tinyint(1) default 0,
  footstyle                 varchar(255),
  country                   varchar(255),
  constraint pk_surfer primary key (id))
;

create table surfer_update (
  id                        bigint auto_increment not null,
  date                      varchar(255),
  type                      varchar(255),
  target                    varchar(255),
  constraint pk_surfer_update primary key (id))
;

create table user_info (
  id                        bigint auto_increment not null,
  name                      varchar(255),
  email                     varchar(255),
  password                  varchar(255),
  admin                     tinyint(1) default 0,
  constraint pk_user_info primary key (id))
;

create table rating_user_info (
  rating_id                      bigint not null,
  user_info_id                   bigint not null,
  constraint pk_rating_user_info primary key (rating_id, user_info_id))
;
alter table favorite add constraint fk_favorite_surfer_1 foreign key (surfer_id) references surfer (id) on delete restrict on update restrict;
create index ix_favorite_surfer_1 on favorite (surfer_id);
alter table favorite add constraint fk_favorite_userInfo_2 foreign key (user_info_id) references user_info (id) on delete restrict on update restrict;
create index ix_favorite_userInfo_2 on favorite (user_info_id);
alter table rating add constraint fk_rating_surfer_3 foreign key (surfer_id) references surfer (id) on delete restrict on update restrict;
create index ix_rating_surfer_3 on rating (surfer_id);

alter table rating_user_info add constraint fk_rating_user_info_rating_01 foreign key (rating_id) references rating (id) on delete restrict on update restrict;

alter table rating_user_info add constraint fk_rating_user_info_user_info_02 foreign key (user_info_id) references user_info (id) on delete restrict on update restrict;

# --- !Downs

SET FOREIGN_KEY_CHECKS=0;

drop table favorite;

drop table rating;

drop table rating_user_info;

drop table surfer;

drop table surfer_update;

drop table user_info;

SET FOREIGN_KEY_CHECKS=1;


text:
package io.reactivex.rxjava3.internal.operators.parallel;

import org.reactivestreams.*;

import io.reactivex.rxjava3.core.FlowableSubscriber;
import io.reactivex.rxjava3.exceptions.Exceptions;
import io.reactivex.rxjava3.functions.Function;
import io.reactivex.rxjava3.internal.subscriptions.SubscriptionHelper;
import io.reactivex.rxjava3.operators.ConditionalSubscriber;
import io.reactivex.rxjava3.parallel.ParallelFlowable;
import io.reactivex.rxjava3.plugins.RxJavaPlugins;

import java.util.Objects;

/**
 * Maps each 'rail' of the source ParallelFlowable with a mapper function.
 *
 * @param <T> the input value type
 * @param <R> the output value type
 */
public final class ParallelMap<T, R> extends ParallelFlowable<R> {

    final ParallelFlowable<T> source;

    final Function<? super T, ? extends R> mapper;

    public ParallelMap(ParallelFlowable<T> source, Function<? super T, ? extends R> mapper) {
        this.source = source;
        this.mapper = mapper;
    }

    @Override
    public void subscribe(Subscriber<? super R>[] subscribers) {
        subscribers = RxJavaPlugins.onSubscribe(this, subscribers);

        if (!validate(subscribers)) {
            return;
        }

        int n = subscribers.length;
        @SuppressWarnings("unchecked")
        Subscriber<? super T>[] parents = new Subscriber[n];

        for (int i = 0; i < n; i++) {
            Subscriber<? super R> a = subscribers[i];
            if (a instanceof ConditionalSubscriber) {
                parents[i] = new ParallelMapConditionalSubscriber<T, R>((ConditionalSubscriber<? super R>)a, mapper);
            } else {
                parents[i] = new ParallelMapSubscriber<T, R>(a, mapper);
            }
        }

        source.subscribe(parents);
    }

    @Override
    public int parallelism() {
        return source.parallelism();
    }

    static final class ParallelMapSubscriber<T, R> implements FlowableSubscriber<T>, Subscription {

        final Subscriber<? super R> downstream;

        final Function<? super T, ? extends R> mapper;

        Subscription upstream;

        boolean done;

        ParallelMapSubscriber(Subscriber<? super R> actual, Function<? super T, ? extends R> mapper) {
            this.downstream = actual;
            this.mapper = mapper;
        }

        @Override
        public void request(long n) {
            upstream.request(n);
        }

        @Override
        public void cancel() {
            upstream.cancel();
        }

        @Override
        public void onSubscribe(Subscription s) {
            if (SubscriptionHelper.validate(this.upstream, s)) {
                this.upstream = s;

                downstream.onSubscribe(this);
            }
        }

        @Override
        public void onNext(T t) {
            if (done) {
                return;
            }
            R v;

            try {
                v = Objects.requireNonNull(mapper.apply(t), "The mapper returned a null value");
            } catch (Throwable ex) {
                Exceptions.throwIfFatal(ex);
                cancel();
                onError(ex);
                return;
            }

            downstream.onNext(v);
        }

        @Override
        public void onError(Throwable t) {
            if (done) {
                RxJavaPlugins.onError(t);
                return;
            }
            done = true;
            downstream.onError(t);
        }

        @Override
        public void onComplete() {
            if (done) {
                return;
            }
            done = true;
            downstream.onComplete();
        }

    }
    static final class ParallelMapConditionalSubscriber<T, R> implements ConditionalSubscriber<T>, Subscription {

        final ConditionalSubscriber<? super R> downstream;

        final Function<? super T, ? extends R> mapper;

        Subscription upstream;

        boolean done;

        ParallelMapConditionalSubscriber(ConditionalSubscriber<? super R> actual, Function<? super T, ? extends R> mapper) {
            this.downstream = actual;
            this.mapper = mapper;
        }

        @Override
        public void request(long n) {
            upstream.request(n);
        }

        @Override
        public void cancel() {
            upstream.cancel();
        }

        @Override
        public void onSubscribe(Subscription s) {
            if (SubscriptionHelper.validate(this.upstream, s)) {
                this.upstream = s;

                downstream.onSubscribe(this);
            }
        }

        @Override
        public void onNext(T t) {
            if (done) {
                return;
            }
            R v;

            try {
                v = Objects.requireNonNull(mapper.apply(t), "The mapper returned a null value");
            } catch (Throwable ex) {
                Exceptions.throwIfFatal(ex);
                cancel();
                onError(ex);
                return;
            }

            downstream.onNext(v);
        }

        @Override
        public boolean tryOnNext(T t) {
            if (done) {
                return false;
            }
            R v;

            try {
                v = Objects.requireNonNull(mapper.apply(t), "The mapper returned a null value");
            } catch (Throwable ex) {
                Exceptions.throwIfFatal(ex);
                cancel();
                onError(ex);
                return false;
            }

            return downstream.tryOnNext(v);
        }

        @Override
        public void onError(Throwable t) {
            if (done) {
                RxJavaPlugins.onError(t);
                return;
            }
            done = true;
            downstream.onError(t);
        }

        @Override
        public void onComplete() {
            if (done) {
                return;
            }
            done = true;
            downstream.onComplete();
        }

    }
}


text:
var globalValue;
if (globalValue === undefined) {
    globalValue = command in defaultValues ? defaultValues[command] : "";
}
var keyPrefix = globalValue == ""
    ? "manualtest-" + command + "-"
    : "manualtest-" + command + "-" + globalValue + "-";
(function(){
    var manualTests = tests[command]
        .map(function(test) { return normalizeTest(command, test) })
        .filter(function(test) { return test[1][1] == globalValue });
    var relevantMultiTests = tests.multitest
        .map(function(test) { return normalizeTest("multitest", test) })
        .filter(function(test) {
            // We only want multitests if there's exactly one occurrence of the
            // command we're testing for, and the value is correct, and that's
            // the last command we're testing.  Some of these limitations could
            // be removed in the future.
            return test[test.length - 1][0] === command
                && test[test.length - 1][1] === globalValue;
        });

    tests = manualTests.concat(relevantMultiTests);
})();
//@}

function clearCachedResults() {
//@{
    for (var key in localStorage) {
        if (key.indexOf(keyPrefix) === 0) {
            localStorage.removeItem(key);
        }
    }
}
//@}

var numManualTests = 0;
var currentTestIdx = null;

// Make sure styleWithCss is always reset to false at the start of a test run
// (I'm looking at you, Firefox)
try { document.execCommand("stylewithcss", false, "false") } catch(e) {}

function runTests() {
//@{
    // We don't ask the user to hit a key on all tests, so make sure not to
    // claim more tests are going to be run than actually are.
    for (var i = 0; i < tests.length; i++) {
        if (localStorage.getItem(keyPrefix + JSON.stringify(tests[i])) === null) {
            numManualTests++;
        }
    }

    currentTestIdx = 0;

    var runTestsButton = document.querySelector("#tests input[type=button]");
    runTestsButton.parentNode.removeChild(runTestsButton);

    var addTestButton = document.querySelector("#tests input[type=button]");
    var input = document.querySelector("#tests label input");
    // This code actually focuses and clicks everything because for some
    // reason, anything else doesn't work in IE9 . . .
    input.value = JSON.stringify(tests[0]);
    input.focus();
    addTestButton.click();
}
//@}

function addTest() {
//@{
    var tr = doSetup("#tests table", 0);
    var input = document.querySelector("#tests label input");
    var test = JSON.parse(input.value);
    doInputCell(tr, test, test.length == 2 ? command : "multitest");
    doSpecCell(tr, test, test.length == 2 ? command : "multitest");
    if (localStorage.getItem(keyPrefix + JSON.stringify(test)) !== null) {
        // Yay, I get to cheat.  Remove the overlay div so the user doesn't
        // keep hitting the key, in case it takes a while.
        var browserCell = document.createElement("td");
        tr.appendChild(browserCell);
        browserCell.innerHTML = localStorage[keyPrefix + JSON.stringify(test)];
        doBrowserCellButton(browserCell, test);
        document.getElementById("overlay").style.display = "";
        doSameCell(tr);
        runNextTest(test);
    } else {
        doBrowserCell(tr, test, function() {
            doSameCell(tr);
            runNextTest();
        });
    }
}
//@}

function runNextTest() {
//@{
    doTearDown();
    var input = document.querySelector("#tests label input");
    if (currentTestIdx === null
    || currentTestIdx + 1 >= tests.length) {
        currentTestIdx = null;
        document.getElementById("overlay").style.display = "";
        input.value = "";
        return;
    }
    currentTestIdx++;
    input.value = JSON.stringify(tests[currentTestIdx]);
    input.focus();
    addTest();
}
//@}

function doBrowserCell(tr, test, callback) {
//@{
    var browserCell = document.createElement("td");
    tr.appendChild(browserCell);

    try {
        var points = setupCell(browserCell, test[0]);

        var testDiv = browserCell.firstChild;
        // Work around weird Firefox bug:
        // https://bugzilla.mozilla.org/show_bug.cgi?id=649138
        document.body.appendChild(testDiv);
        testDiv.onkeyup = function() {
            continueBrowserCell(test, testDiv, browserCell);
            callback();
        };
        testDiv.contentEditable = "true";
        testDiv.spellcheck = false;
        if (currentTestIdx === null) {
            document.getElementById("testcount").style.display = "none";
        } else {
            document.getElementById("testcount").style.display = "";
            document.querySelector("#testcount > span").textContent = numManualTests;
            numManualTests--;
        }
        document.getElementById("overlay").style.display = "block";
        testDiv.focus();
        setSelection(points[0], points[1], points[2], points[3]);
        // Execute any extra commands beforehand, for multitests
        for (var i = 1; i < test.length - 1; i++) {
            document.execCommand(test[i][0], false, test[i][1]);
        }
    } catch (e) {
        browserCellException(e, testDiv, browserCell);
        callback();
    }
}
//@}

function continueBrowserCell(test, testDiv, browserCell) {
//@{
    try {
        testDiv.contentEditable = "inherit";
        testDiv.removeAttribute("spellcheck");
        var compareDiv1 = testDiv.cloneNode(true);

        if (getSelection().rangeCount) {
            addBrackets(getSelection().getRangeAt(0));
        }
        browserCell.insertBefore(testDiv, browserCell.firstChild);

        if (!browserCell.childNodes.length == 2) {
            throw "The cell didn't have two children.  Did something spill outside the test div?";
        }

        compareDiv1.normalize();
        // Sigh, Gecko is crazy
        var treeWalker = document.createTreeWalker(compareDiv1, NodeFilter.SHOW_ELEMENT, null, null);
        while (treeWalker.nextNode()) {
            var remove = [].filter.call(treeWalker.currentNode.attributes, function(attrib) {
                return /^_moz_/.test(attrib.name) || attrib.value == "_moz";
            });
            for (var i = 0; i < remove.length; i++) {
                treeWalker.currentNode.removeAttribute(remove[i].name);
            }
        }
        var compareDiv2 = compareDiv1.cloneNode(false);
        compareDiv2.innerHTML = compareDiv1.innerHTML;
        if (!compareDiv1.isEqualNode(compareDiv2)
        && compareDiv1.innerHTML != compareDiv2.innerHTML) {
            throw "DOM does not round-trip through serialization!  "
                + compareDiv1.innerHTML + " vs. " + compareDiv2.innerHTML;
        }
        if (!compareDiv1.isEqualNode(compareDiv2)) {
            throw "DOM does not round-trip through serialization (although innerHTML is the same)!  "
                + compareDiv1.innerHTML;
        }

        browserCell.lastChild.textContent = browserCell.firstChild.innerHTML;
    } catch (e) {
        browserCellException(e, testDiv, browserCell);
    }

    localStorage[keyPrefix + JSON.stringify(test)] = browserCell.innerHTML;

    doBrowserCellButton(browserCell, test);
}
//@}

function doBrowserCellButton(browserCell, test) {
//@{
    var button = document.createElement("button");
    browserCell.lastChild.appendChild(button);
    button.textContent = "Redo browser output";
    button.onclick = function() {
        localStorage.removeItem(keyPrefix + JSON.stringify(test));
        var tr = browserCell.parentNode;
        while (browserCell.nextSibling) {
            tr.removeChild(browserCell.nextSibling);
        }
        tr.removeChild(browserCell);
        doBrowserCell(tr, test, function() {
            doSameCell(tr);
            doTearDown();
            document.getElementById("overlay").style.display = "";
            tr.scrollIntoView();
        });
    };
}
//@}
// vim: foldmarker=@{,@} foldmethod=marker


text:
package org.duracloud.s3storageprovider.dto;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.junit.matchers.JUnitMatchers.containsString;

import org.duracloud.error.TaskDataException;
import org.junit.Test;

/**
 * @author Bill Branan
 * Date: Aug 16, 2018
 */
public class GetSignedCookiesUrlTaskParametersTest {

    private final String spaceId = "space-id";
    private final int minutesToExpire = 60;
    private final String ipAddress = "ip-address";
    private final String redirectUrl = "redirect.url";

    @Test
    public void testSerialize() {
        GetSignedCookiesUrlTaskParameters taskParams =
            new GetSignedCookiesUrlTaskParameters();
        taskParams.setSpaceId(spaceId);
        taskParams.setMinutesToExpire(minutesToExpire);
        taskParams.setIpAddress(ipAddress);
        taskParams.setRedirectUrl(redirectUrl);

        String result = taskParams.serialize();
        String cleanResult = result.replaceAll("\\s+", "");
        assertThat(cleanResult, containsString("\"spaceId\":\"" + spaceId + "\""));
        assertThat(cleanResult, containsString("\"minutesToExpire\":" + minutesToExpire));
        assertThat(cleanResult, containsString("\"ipAddress\":\"" + ipAddress + "\""));
        assertThat(cleanResult, containsString("\"redirectUrl\":\"" + redirectUrl + "\""));
    }

    @Test
    public void testDeserialize() {
        // Verify valid params
        String taskParamsSerialized =
            "{\"spaceId\" : \"" + spaceId + "\"," +
            " \"minutesToExpire\" : " + minutesToExpire + "," +
            " \"ipAddress\" : \"" + ipAddress + "\"," +
            " \"redirectUrl\" : \"" + redirectUrl + "\"}";

        GetSignedCookiesUrlTaskParameters taskParams =
            GetSignedCookiesUrlTaskParameters.deserialize(taskParamsSerialized);
        assertEquals(spaceId, taskParams.getSpaceId());
        assertEquals(minutesToExpire, taskParams.getMinutesToExpire());
        assertEquals(ipAddress, taskParams.getIpAddress());
        assertEquals(redirectUrl, taskParams.getRedirectUrl());

        // Verify that empty spaceId will throw
        taskParamsSerialized =
            "{\"spaceId\" : \"\"," +
            " \"minutesToExpire\" : " + minutesToExpire + "," +
            " \"ipAddress\" : \"" + ipAddress + "\"," +
            " \"redirectUrl\" : \"" + redirectUrl + "\"}";

        try {
            GetSignedCookiesUrlTaskParameters.deserialize(taskParamsSerialized);
            fail("Exception expected: Invalid params");
        } catch (TaskDataException e) {
            // Expected exception
        }

        // Verify that empty redirectUrl will throw
        taskParamsSerialized =
            "{\"spaceId\" : \"" + spaceId + "\"," +
            " \"minutesToExpire\" : " + minutesToExpire + "," +
            " \"ipAddress\" : \"" + ipAddress + "\"," +
            " \"redirectUrl\" : \"\"}";

        try {
            GetSignedCookiesUrlTaskParameters.deserialize(taskParamsSerialized);
            fail("Exception expected: Invalid params");
        } catch (TaskDataException e) {
            // Expected exception
        }

        // Verify that empty params throw
        taskParamsSerialized =
            "{\"spaceId\" : \"\"," +
            " \"minutesToExpire\" : \"\"," +
            " \"ipAddress\" : \"\"," +
            " \"redirectUrl\" : \"\"}";

        try {
            GetSignedCookiesUrlTaskParameters.deserialize(taskParamsSerialized);
            fail("Exception expected: Invalid params");
        } catch (TaskDataException e) {
            // Expected exception
        }

        // Verify that empty params throw
        try {
            GetSignedCookiesUrlTaskParameters.deserialize("");
            fail("Exception expected: Invalid params");
        } catch (TaskDataException e) {
            // Expected exception
        }
    }

}


text:
package org.red5.client.net.rtmp;

import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.mina.core.future.CloseFuture;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.future.IoFutureListener;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.transport.socket.SocketConnector;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * RTMP client implementation supporting "rtmp" and "rtmpe" protocols.
 *
 * @author The Red5 Project
 * @author Christian Eckerle (ce@publishing-etc.de)
 * @author Joachim Bauch (jojo@struktur.de)
 * @author Paul Gregoire (mondain@gmail.com)
 * @author Steven Gong (steven.gong@gmail.com)
 * @author Anton Lebedevich (mabrek@gmail.com)
 * @author Tiago Daniel Jacobs (tiago@imdt.com.br)
 * @author Jon Valliere
 */
public class RTMPClient extends BaseRTMPClientHandler {
    private static final Logger log = LoggerFactory.getLogger(RTMPClient.class);

    protected static final int CONNECTOR_WORKER_TIMEOUT = 7000; // milliseconds

    // I/O handler
    protected final RTMPMinaIoHandler ioHandler;

    // Socket connector, disposed on disconnect
    protected SocketConnector socketConnector;

    // ConnectFuture
    protected ConnectFuture future;

    // Connected IoSession
    protected IoSession session;

    /** Constructs a new RTMPClient. */
    public RTMPClient() {
        ioHandler = new RTMPMinaIoHandler();
        ioHandler.setHandler(this);
    }

    /** {@inheritDoc} */
    @Override
    public Map<String, Object> makeDefaultConnectionParams(String server, int port, String application) {
        Map<String, Object> params = super.makeDefaultConnectionParams(server, port, application);
        if (!params.containsKey("tcUrl")) {
            params.put("tcUrl", String.format("%s://%s:%s/%s", protocol, server, port, application));
        }
        return params;
    }

    /** {@inheritDoc} */
    @Override
    protected void startConnector(String server, int port) {
        log.debug("startConnector - server: {} port: {}", server, port);
        socketConnector = new NioSocketConnector();
        socketConnector.setHandler(ioHandler);
        future = socketConnector.connect(new InetSocketAddress(server, port));
        future.addListener(new IoFutureListener<ConnectFuture>() {
            @Override
            public void operationComplete(ConnectFuture future) {
                try {
                    // will throw RuntimeException after connection error
                    session = future.getSession();
                } catch (Throwable e) {
                    log.warn("Exception in startConnector", e);
                    // disconnect this
                    disconnect();
                    // if there isn't an ClientExceptionHandler set, a RuntimeException may be thrown in handleException
                    handleException(e);
                }
            }
        });
        // Now wait for the connect to be completed
        future.awaitUninterruptibly(CONNECTOR_WORKER_TIMEOUT);
        log.debug("startConnector {} done", Thread.currentThread().getName());
    }

    /** {@inheritDoc} */
    @Override
    public void disconnect() {
        if (future != null) {
            try {
                // session will be null if connect failed
                if (session != null) {
                    // close, now
                    CloseFuture closeFuture = session.closeNow();
                    // now wait for the close to be completed
                    if (closeFuture.await(1000, TimeUnit.MILLISECONDS)) {
                        if (!future.isCanceled()) {
                            if (future.cancel()) {
                                log.debug("Connect future cancelled after close future");
                            }
                        }
                    }
                } else if (future.cancel()) {
                    log.debug("Connect future cancelled");
                }
            } catch (Exception e) {
                log.warn("Exception during disconnect", e);
            } finally {
                // we can now dispose the connector
                socketConnector.dispose(false);
            }
        }
        super.disconnect();
    }

    /**
     * Sets the RTMP protocol, the default is "rtmp". If "rtmps" or "rtmpt" are required, the appropriate client type should be selected.
     *
     * @param protocol
     *            the protocol to set
     * @throws Exception thrown
     */
    @Override
    public void setProtocol(String protocol) throws Exception {
        this.protocol = protocol;
        if ("rtmps".equals(protocol) || "rtmpt".equals(protocol) || "rtmpte".equals(protocol) || "rtmfp".equals(protocol)) {
            throw new Exception("Unsupported protocol specified, please use the correct client for the intended protocol.");
        }
    }
}


text:
package org.wikipedia.analytics;

import android.support.annotation.NonNull;

import org.wikipedia.WikipediaApp;

public class SearchFunnel extends Funnel {
    private static final String SCHEMA_NAME = "MobileWikiAppSearch";
    private static final int REVISION = 10641988;

    public SearchFunnel(WikipediaApp app) {
        super(app, SCHEMA_NAME, REVISION, Funnel.SAMPLE_LOG_100);
    }

    public void searchStart() {
        log(
                "action", "start"
        );
    }

    public void searchCancel() {
        log(
                "action", "cancel"
        );
    }

    public void searchClick() {
        log(
                "action", "click"
        );
    }

    public void searchDidYouMean() {
        log(
                "action", "didyoumean"
        );
    }

    public void searchResults(boolean fullText, int numResults, int delayMillis) {
        log(
                "action", "results",
                "typeOfSearch", fullText ? "full" : "prefix",
                "numberOfResults", numResults,
                "timeToDisplayResults", delayMillis
        );
    }

    public void searchError(boolean fullText, int delayMillis) {
        log(
                "action", "error",
                "typeOfSearch", fullText ? "full" : "prefix",
                "timeToDisplayResults", delayMillis
        );
    }

    @NonNull
    @Override
    protected String getSessionTokenField() {
        return "searchSessionToken";
    }
}


text:
const yup = require('yup');

const bookings = []; //TODO: get bookings from DB
const CHANNEL = 'CHANNEL';

const dateInputSchema = yup.string().matches(/^\d\d\d\d-\d\d-\d\d$/, 'bad date format, expected `yyyy-mm-dd`');

const bookingInputSchema = yup.object().shape({
  title: yup.string().required().oneOf(['Mr', 'Ms', 'Miss', 'Mrs']),
  firstName: yup.string().trim().max(20).required(),
  lastName: yup.string().trim().max(20).required(),
  date: dateInputSchema.required(),
  time: yup.string().required().matches(/^\d\d(:|.)\d\d$/, 'bad time format, expected `hh:mm`'),
  partySize: yup.number().required(),
  notes: yup.string().trim().notRequired().max(250).ensure(),
  seated: yup.boolean().notRequired().default(false),
  cancelled: yup.boolean().notRequired().default(false),
});

const idInputSchema = yup.string().required();

module.exports = {
  Query: {
    bookings: (parent, { date }, { db }) => new Promise((resolve, reject) => {

      dateInputSchema.validate(date)
        .then(date => {
          db.find({ date }, (error, data) => {
            if (error) {
              reject(error);
            } else {
              resolve(data);
            }
          });
        })
        .catch(reject);

    }),
    booking: (parent, { _id }, { db }) => new Promise((resolve, reject) => {

      idInputSchema.validate(_id)
        .then(_id => {
          db.findOne({ _id }, (error, data) => {
            if (error) {
              reject(error);
            } else {
              resolve(data);
            }
          });
        })
        .catch(reject);

    }),
  },

  Mutation: {
    updateBooking: (root, { _id, booking }, { db }) => new Promise((resolve, reject) => {

      bookingInputSchema.validate(booking, { abortEarly: false })
        .then(booking => {
          return idInputSchema.validate(_id)
            .then(_id => {
              db.update(
                { _id },
                { $set: booking },
                {returnUpdatedDocs: true},
                (error, numUpdated, data) => {
                  if (error) {
                    reject(error);
                  } else {
                    resolve(data);
                  }
                });
            });
        })
        .catch(reject);

    }),

    newBooking: (root, { booking }, { db/* , pubsub */ }) => new Promise((resolve, reject) => {

      bookingInputSchema.validate(booking, { abortEarly: false })
        .then(booking => {
          db.insert(booking, (error, result) => {
          // pubsub.publish(CHANNEL, { bookings });
            if (error) {
              reject(error);
            } else {
              resolve(result);
            }
          });
        })
        .catch(reject);
    }),
  },

  // TODO: implement subscriptions
  Subscription: {
    bookings: {
      subscribe: (root, args, { pubsub }) => {
        setTimeout(() => pubsub.publish(CHANNEL, { bookings }), 1);
        return pubsub.asyncIterator(CHANNEL);
      },
    },
  },
};


text:
(function (deps, factory) {
    if (typeof module === 'object' && typeof module.exports === 'object') {
        var v = factory(require, exports); if (v !== undefined) module.exports = v;
    }
    else if (typeof define === 'function' && define.amd) {
        define(deps, factory);
    }
})(["require", "exports"], function (require, exports) {
    function noop() { }
    function addListener(target, type, listener, capture) {
        if (target.addEventListener) {
            target.addEventListener(type, listener, capture);
            return {
                remove: function () {
                    this.remove = noop;
                    target.removeEventListener(type, listener, capture);
                    target = listener = null;
                }
            };
        }
        throw new Error('Target must be an event emitter');
    }
    var on = function (target, type, listener, capture) {
        if (typeof target.on === 'function' && typeof type !== 'function' && !target.nodeType) {
            return target.on(type, listener, capture);
        }
        return on.parse(target, type, listener, this, addListener, capture);
    };
    on.parse = function (target, type, listener, context, addListener, capture) {
        if (type.call) {
            return type.call(context, target, listener, capture);
        }
        if (type.indexOf(',') > -1) {
            var events = type.split(/\s*,\s*/);
            var handles = events.map(function (type) {
                return addListener(target, type, listener, capture);
            });
            return {
                remove: function () {
                    this.remove = noop;
                    var handle;
                    while ((handle = handles.pop())) {
                        handle.remove();
                    }
                }
            };
        }
        return addListener(target, type, listener, capture);
    };
    on.emit = function (target, type, event) {
        if (typeof target.emit === 'function' && !target.nodeType) {
            return target.emit(type, event);
        }
        if (target.dispatchEvent && target.ownerDocument && target.ownerDocument.createEvent) {
            var nativeEvent = target.ownerDocument.createEvent('HTMLEvents');
            nativeEvent.initEvent(type, Boolean(event.bubbles), Boolean(event.cancelable));
            for (var key in event) {
                if (!(key in nativeEvent)) {
                    nativeEvent[key] = event[key];
                }
            }
            return target.dispatchEvent(nativeEvent);
        }
        throw new Error('Target must be an event emitter');
    };
    return on;
});
//# sourceMappingURL=_debug/on.js.map


text:
"""
Script which attempts to identify journals, applications and provenance records which show an inconsistent state:

1. All suggestions where there are provenance records from a later time

2. All accepted suggestions where the journal hasn't been created

3. All journals for which the created_date is inconsistent with the application's last_updated date, and for which there are edit and/or accepted provenance records

4. All journals for which the related account is missing

5. All journals which were published earlier than their related application was last updated (suggesting a failure to reapply)
"""

from copy import deepcopy
from datetime import datetime, timedelta

import csv
import esprit

from portality import constants
from portality.core import es_connection
from portality.util import ipt_prefix
from portality.models import Suggestion, Provenance, Journal, Account

APP_TIMEZONE_CUTOFF = datetime.strptime("2017-05-18T14:02:08Z", "%Y-%m-%dT%H:%M:%SZ")
JOURNAL_TIMEZONE_CUTOFF = datetime.strptime("2017-09-21T08:54:05Z", "%Y-%m-%dT%H:%M:%SZ")
THRESHOLD = 20.0

local = es_connection

#live = esprit.raw.Connection(app.config.get("DOAJGATE_URL"), "doaj", auth=requests.auth.HTTPBasicAuth(app.config.get("DOAJGATE_UN"), app.config.get("DOAJGATE_PW")), verify_ssl=False, port=app.config.get("DOAJGATE_PORT"))

def adjust_timestamp(stamp, cutoff):
    if stamp < cutoff:
        return stamp + timedelta(seconds=3600)
    return stamp

# looks for applications where the provenance dates are later than the last updated dates
# also looks for applications where there is not a corresponding journal (in_doaj=True)
def applications_inconsistencies(outfile_later, outfile_missing, conn):
    with open(outfile_later, "w", encoding="utf-8") as f, open(outfile_missing, "w", encoding="utf-8") as g:

        out_later = csv.writer(f)
        out_later.writerow(["Application ID", "Application Last Updated", "Latest Provenance Recorded", "Difference"])

        out_missing = csv.writer(g)
        out_missing.writerow(["Application ID", "Application Last Manual Update", "Latest Provenance Record", "ISSNs", "Title"])

        counter = 0
        for result in esprit.tasks.scroll(conn, "suggestion", keepalive="45m"):
            counter += 1
            application = Suggestion(**result)
            print(counter, application.id)

            # Part 1 - later provenance records exist
            latest_prov = Provenance.get_latest_by_resource_id(application.id)
            if latest_prov is not None:
                lustamp = adjust_timestamp(application.last_updated_timestamp, APP_TIMEZONE_CUTOFF)
                created = latest_prov.created_date
                pstamp = latest_prov.created_timestamp
                td = pstamp - lustamp
                diff = td.total_seconds()

                if diff > THRESHOLD:
                    out_later.writerow([application.id, application.last_updated, created, diff])

            # Part 2 - missing journals
            if application.application_status == constants.APPLICATION_STATUS_ACCEPTED:
                missing = False

                # find the matching journals by issn or by title
                matching_journals = Journal.find_by_issn(application.bibjson().issns())
                if len(matching_journals) == 0:
                    # Have another go, find by title
                    matching_journals = Journal.find_by_title(application.bibjson().title)

                # if there are no matching journals, it is missing.
                if len(matching_journals) == 0:
                    missing = True
                else:
                    # if there are matching journals, find out if any of them are in the doaj.  If none, then journal is still missing
                    those_in_doaj = len([j for j in matching_journals if j.is_in_doaj()])
                    if those_in_doaj == 0:
                        missing = True

                # if the journal is missing, record it
                if missing:
                    created = ""
                    if latest_prov is not None:
                        created = latest_prov.created_date
                    out_missing.writerow([application.id, application.last_manual_update, created, " ".join(application.bibjson().issns()), application.bibjson().title])

        print("processed", counter, "suggestions")

# looks for journals that were created after the last update on an application, implying the application was not updated
# also looks for missing accounts
# also looks for journals created (or reapplied) significantly before the last manual update on an application
def journals_applications_provenance(outfile_applications, outfile_accounts, outfile_reapps, conn):
    with open(outfile_applications, "w", encoding="utf-8") as f, open(outfile_accounts, "w", encoding="utf-8") as g, open(outfile_reapps, "w", encoding="utf-8") as h:
        out_applications = csv.writer(f)
        out_applications.writerow(["Journal ID", "Journal Created", "Journal Reapplied", "Application ID", "Application Last Updated", "Application Status", "Published Diff", "Latest Edit Recorded", "Latest Accepted Recorded"])

        out_accounts = csv.writer(g)
        out_accounts.writerow(["Journal ID", "Journal Created", "Journal Reapplied", "In DOAJ", "Missing Account ID"])

        out_reapps = csv.writer(h)
        out_reapps.writerow(["Journal ID", "Journal Created", "Journal Reapplied", "Application ID", "Application Created", "Application Last Updated", "Application Last Manual Update", "Application Status", "Published Diff"])

        counter = 0
        for result in esprit.tasks.scroll(conn, ipt_prefix("journal"), keepalive="45m"):
            counter += 1
            journal = Journal(**result)
            print(counter, journal.id)

            # first figure out if there is a broken related application
            issns = journal.bibjson().issns()
            applications = Suggestion.find_by_issn(issns)
            latest = None
            for application in applications:
                if latest is None:
                    latest = application
                if application.last_updated_timestamp > latest.last_updated_timestamp:
                    latest = application

            if latest is None:
                continue

            jcreated = journal.created_timestamp
            reapp = journal.last_update_request
            print(counter, journal.id, reapp)
            if reapp is not None:
                jcreated = datetime.strptime(reapp, "%Y-%m-%dT%H:%M:%SZ")
            jcreated = adjust_timestamp(jcreated, JOURNAL_TIMEZONE_CUTOFF)

            app_lustamp = adjust_timestamp(latest.last_updated_timestamp, APP_TIMEZONE_CUTOFF)
            # app_man_lustamp = latest.last_manual_update_timestamp # no need to adjust this one
            app_man_lustamp = adjust_timestamp(latest.last_manual_update_timestamp, APP_TIMEZONE_CUTOFF)
            td = jcreated - app_lustamp
            mtd = jcreated - app_man_lustamp
            diff = td.total_seconds()
            mdiff = mtd.total_seconds()

            # was the journal created after the application by greater than the threshold?
            if diff > THRESHOLD:
                last_edit = ""
                last_accept = ""

                edit_query = deepcopy(PROV_QUERY)
                edit_query["query"]["bool"]["must"][0]["term"]["resource_id.exact"] = latest.id
                edit_query["query"]["bool"]["must"][1]["term"]["action.exact"] = "edit"
                provs = Provenance.q2obj(q=edit_query)
                if len(provs) > 0:
                    last_edit = provs[0].last_updated

                accept_query = deepcopy(PROV_QUERY)
                accept_query["query"]["bool"]["must"][0]["term"]["resource_id.exact"] = latest.id
                accept_query["query"]["bool"]["must"][1]["term"]["action.exact"] = "status:accepted"
                provs = Provenance.q2obj(q=accept_query)
                if len(provs) > 0:
                    last_accept = provs[0].last_updated

                out_applications.writerow([journal.id, journal.created_date, journal.last_update_request, latest.id, latest.last_updated, latest.application_status, diff, last_edit, last_accept])

            # was the journal (in doaj) created before the application by greater than the threshold, and is it in a state other than rejected
            if mdiff < -1 * THRESHOLD and latest.application_status != constants.APPLICATION_STATUS_REJECTED and journal.is_in_doaj():
                out_reapps.writerow([journal.id, journal.created_date, journal.last_update_request, latest.id, latest.created_date, latest.last_updated, latest.last_manual_update, latest.application_status, mdiff])

            # now figure out if the account is missing
            owner = journal.owner
            if owner is None:
                out_accounts.writerow([journal.id, journal.created_date, journal.last_update_request, str(journal.is_in_doaj()), "NO OWNER"])
            else:
                acc = Account.pull(owner)
                if acc is None:
                    out_accounts.writerow([journal.id, journal.created_date, journal.last_update_request, str(journal.is_in_doaj()), owner])

        print("processed", counter, "journals")

PROV_QUERY = {
    "query": {
        "bool": {
            "must": [
                {"term": {"resource_id.exact": None}},
                {"term": {"action.exact": None}}
            ]
        }
    },
    "sort": [{"created_date": {"order": "desc"}}]
}

if __name__ == "__main__":
    print('Starting {0}.'.format(datetime.now()))
    applications_inconsistencies("apps_with_prov.csv", "apps_accepted_without_journals.csv", local)
    journals_applications_provenance("journals_applications_provenance.csv", "journals_no_accounts.csv", "journals_reapp_fails.csv", local)
    print('Finished {0}.'.format(datetime.now()))


text:
<?php

defined('JPATH_BASE') or die;

use Joomla\Utilities\ArrayHelper;

JLoader::register('AssociationsHelper', JPATH_ADMINISTRATOR . '/components/com_associations/helpers/associations.php');
JFormHelper::loadFieldClass('list');

/**
 * Field listing item languages
 *
 * @since  3.7.0
 */
class JFormFieldItemLanguage extends JFormFieldList
{
	/**
	 * The form field type.
	 *
	 * @var    string
	 * @since  3.7.0
	 */
	protected $type = 'ItemLanguage';

	/**
	 * Method to get the field options.
	 *
	 * @return  array  The field option objects.
	 *
	 * @since   3.7.0
	 */
	protected function getOptions()
	{
		$input = JFactory::getApplication()->input;

		list($extensionName, $typeName) = explode('.', $input->get('itemtype', '', 'string'));

		// Get the extension specific helper method
		$helper = AssociationsHelper::getExtensionHelper($extensionName);

		$languageField = $helper->getTypeFieldName($typeName, 'language');
		$referenceId   = $input->get('id', 0, 'int');
		$reference     = ArrayHelper::fromObject(AssociationsHelper::getItem($extensionName, $typeName, $referenceId));
		$referenceLang = $reference[$languageField];

		// Get item associations given ID and item type
		$associations = AssociationsHelper::getAssociationList($extensionName, $typeName, $referenceId);

		// Check if user can create items in this component item type.
		$canCreate = AssociationsHelper::allowAdd($extensionName, $typeName);

		// Gets existing languages.
		$existingLanguages = AssociationsHelper::getContentLanguages();

		$options = array();

		// Each option has the format "<lang>|<id>", example: "en-GB|1"
		foreach ($existingLanguages as $langCode => $language)
		{
			// If language code is equal to reference language we don't need it.
			if ($language->lang_code == $referenceLang)
			{
				continue;
			}

			$options[$langCode]       = new stdClass;
			$options[$langCode]->text = $language->title;

			// If association exists in this language.
			if (isset($associations[$language->lang_code]))
			{
				$itemId                    = (int) $associations[$language->lang_code]['id'];
				$options[$langCode]->value = $language->lang_code . ':' . $itemId . ':edit';

				 // Check if user does have permission to edit the associated item.
				$canEdit = AssociationsHelper::allowEdit($extensionName, $typeName, $itemId);

				// Check if item can be checked out
				$canCheckout = AssociationsHelper::canCheckinItem($extensionName, $typeName, $itemId);

				// Disable language if user is not allowed to edit the item associated to it.
				$options[$langCode]->disable = !($canEdit && $canCheckout);
			}
			else
			{
				// New item, id = 0 and disabled if user is not allowed to create new items.
				$options[$langCode]->value = $language->lang_code . ':0:add';

				// Disable language if user is not allowed to create items.
				$options[$langCode]->disable = !$canCreate;
			}
		}

		return array_merge(parent::getOptions(), $options);
	}
}


text:
%Makes, and cleans up mask, then makes serial edge measurements and plots them.
%Uses one source image (try to make it somewhat clean).
load('C:\Users\D\Documents\MATLAB\whiteCMap','whiteCMap','lifescale')

clearex('whiteCMap','lifescale')%Clear everything except variables for plots
close all
name= input('Cell number?: ');
layers= 30;
load(['cell' name '.mat'],'thrLife2','alignInt','bright')

%%=Find cell and make/clean mask=
%[cb2Data,finalMask,smoothPerim]= cellBound2(thrLife2);%Finds cell (largest object) and cleans up mask
[cb2Data,finalMask,smoothPerim]= cellBound4(bright);%Uses cellBound3 which uses brightfield image for mask
%This also saves all of the metadata for the original mask (ie. perimeter,
%centroid,area,ellipsicity etc)

eccentricity= cb2Data.stats(1,1).Eccentricity;
perimeter0= cb2Data.stats(1,1).Perimeter;
area= cb2Data.stats(1,1).Area;
Centroid= cb2Data.stats(1,1).Centroid;
MajorAxisLength= cb2Data.stats(1,1).MajorAxisLength;
MinorAxisLength= cb2Data.stats(1,1).MinorAxisLength;
Orientation= cb2Data.stats(1,1).Orientation;

[xEllipse,yEllipse]= ellips(Centroid,MajorAxisLength+MajorAxisLength*0.2,MinorAxisLength+MinorAxisLength*0.2,Orientation);%Gives coord for ellipse from given regionprops
%[xEllipse,yEllipse]= ellips(Centroid,MajorAxisLength,MinorAxisLength,Orientation);%Gives coord for ellipse from given regionprops
%The above now tells is to expand the width of the ellipse by 20% to make
%sure we include as many pixels as possible
ellipMask= poly2mask(xEllipse,yEllipse,512,512);%Takes coords and fills in area to make a mask

gcf
close
figure
imagesc(finalMask)
hold
plot(xEllipse,yEllipse,'.g')
plot(Centroid(1),Centroid(2),'og')

figure
close
figure
maskPerimPlot= gcf;%%-----------fig

ringData= struct();

perimsMask= [];%Initialize variables to store edge masks and their lifetime values
perimsLife= [];
perimsInt= [];

%hold on

perimeter= perimeter0;
counter0= 1;
counter= counter0;
%%==Make concentric edge masks and apply to lifetime image
while perimeter >= 0.1*perimeter0 %Will isolate 30 rings from peripery
    [erodMask,x,y]= concentric(ellipMask,counter);%Changed this to ellipmask
    edgeMask= edge(erodMask);

    perimLife= thrLife2.*(edge(erodMask));
    perimInt= alignInt.*(edge(erodMask));

    imagesc(perimLife,[1000 1500])

    pause(0.01)

    perimsMask= [perimsMask,edgeMask(:)];%Adds masks as column in matrix
    perimsLife= [perimsLife,perimLife(:)];
    perimsInt= [perimsInt,perimInt(:)];

    perimeter= regionprops(erodMask,'Perimeter');%This is a structure, need next line to get perimeter.
    perimeter= perimeter.Perimeter;
    counter= counter+1;

end

ringList= 1:counter-1;
newfig

%%=Select positions for measurements and map specific layers

[posRing,posRingIndex]= find(nansum(perimsLife)>0);%Find all edges whose perimeter lifetime > 0, store index in posRingIndex

ring1= posRingIndex(1);%First, most outer edge mask
ring2= ring1+10;
ring3= ring1+20;
ring4= posRingIndex(end);%Last, most inner edge mask

completeTemp= zeros(512,512);%Initialize zero image matrix (same as our perimsLife matrices) to which you'll add lifetime perimeters
complete= completeTemp(:);%Vectorizes to give same dimensions as columns we made for perimsLife et al.
complete= complete+ perimsLife(:,ring1)+perimsLife(:,ring2)+perimsLife(:,ring3)+perimsLife(:,ring4);%Adds specific layers to them (should be no overlap since they're different layers)
complete2= reshape(complete,512,512);%Reassembles into a matrix (image)

%%=Find median (0.5 on cdf) for each edge and use as value for image of
%%edge

[midRing1]= cdfPt5(perimsLife(:,ring1),'green');
[midRing2]= cdfPt5(perimsLife(:,ring2),'green');
[midRing3]= cdfPt5(perimsLife(:,ring3),'green');
[midRing4]= cdfPt5(perimsLife(:,ring4),'green');

midRingFour= [midRing1;midRing2;midRing3;midRing4];
% midLayers= 1:30;
% midLayers(layers)= midLayers(:,cdfPt5(perimsLife(:,layers),'green'));

close%Closes last figure from cdfPt5 fxns above

ring1MidMask= perimsMask(:,ring1)*midRing1;%Multiply median ring value by particular mask
ring2MidMask= perimsMask(:,ring2)*midRing2;
ring3MidMask= perimsMask(:,ring3)*midRing3;
ring4MidMask= perimsMask(:,ring4)*midRing4;

completeMidRings= completeTemp(:)+ring1MidMask+ring2MidMask+ring3MidMask+ring4MidMask;%Add values to make new image
completeMidRings= reshape(completeMidRings,512,512);

newfig%%---------------fig
plotRings= gcf;
col1= rand(1,3);
col2= rand(1,3);
col3= rand(1,3);
col4= rand(1,3);

plot(perimsLife(:,1),'.','color',col1)
hold on
plot(perimsLife(:,10),'.','color',col2)
plot(perimsLife(:,20),'.','color',col3)
plot(perimsLife(:,30),'.','color',col4)

xlabel('Pixel index','FontWeight','bold','FontSize',14)
ylabel('Lifetime (ps)','FontWeight','bold','FontSize',14)

newfig%%--------------fig
cdfRings= gcf;
sortCdf2(perimsLife(:,1),col1);
hold
sortCdf2(perimsLife(:,10),col2);
sortCdf2(perimsLife(:,20),col3);
sortCdf2(perimsLife(:,30),col4);

xlabel('Lifetime (ps)', 'FontWeight','bold','FontSize',14)
ylabel('Probability','FontWeight','bold','FontSize',14)

newfig%%------------fig
mapRings= gcf;
imagesc(thrLife2,[1000 2300])
pause(2)
imagesc(complete2,lifescale)
colorbar

newfig%%----------fig
mapRingsMid= gcf;
imagesc(completeMidRings,[1600 1800])
colorbar

ringData.perimsLife= perimsLife;
ringData.perimsMask= perimsMask;
ringData.complete2= complete2;
ringData.perimsInt= perimsInt;

scriptUsed= importdata('rings6.m');%Saves content of script I used

% xlim([100 400])
% ylim([100 400])

%Uncomment if you want it to go faster
saveas(smoothPerim,['cell ' name ' plot smoothPerim.fig'])
saveas(plotRings,['cell ' name ' plot ringsPixels.fig'])
saveas(cdfRings,['cell ' name ' cdf rings.fig'])
saveas(mapRings,['cell ' name ' imagesc mapRingsLife.fig'])
saveas(mapRingsMid,['cell ' name ' imagesc mapRingsLifeMed.fig'])

newfig
midLifeLayers= [];
midIntLayers= [];
for layers= 1:counter-1% Number of rings
 singleLifeLayer= cdfPt5(perimsLife(:,layers),'green');%Finding pt5 for each
 singleIntLayer= cdfPt5(perimsInt(:,layers),'green');%Finding pt5 for each

 midLifeLayers= [midLifeLayers;singleLifeLayer];
 midIntLayers= [midIntLayers;singleIntLayer];

end

plotMidRings= plot(midLifeLayers,'LineWidth',2);
hold
plot(midIntLayers,'r','LineWidth',2)

xlabel('Ring Index (pixel)','FontWeight','bold','FontSize',14)
ylabel('Median Lifetime (ps)','FontWeight','bold','FontSize',14)
title(['cell ' name ' rings'])

figure
lifeIntPlot= plotyy(1:length(midLifeLayers),midLifeLayers,1:length(midIntLayers),midIntLayers);

%Comment out below if you want it to go faster
title(['cell ' name ' Int vs Life'])

saveas(plotMidRings,['cell ' name ' plot midRings.fig'])
%saveas(lifeIntPlot,['cell ' name ' plot lifeIntRings.fig'])

save(['cell' name ' ellipRings.mat'])


text:
'use strict';

var flow = require('lodash/fp/flow');
var get = require('lodash/get');
var set = require('lodash/set');
var common = require('./common');

module.exports = function (source) {
  var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};

  function db(path, defaultValue) {
    function getValue(funcs) {
      var result = get(db.getState(), path, defaultValue);
      return flow(funcs)(result);
    }

    getValue.write = function () {
      var result = getValue.apply(undefined, arguments);
      set(db.getState(), path, result);
      return db.write(source, result);
    };

    return getValue;
  }

  return common.init(db, '__state__', source, opts);
};


text:
/**
 * @ngdoc module
 * @name material.components.content
 *
 * @description
 * Scrollable content
 */
angular.module('material.components.content', [
  'material.core'
])
  .directive('mdContent', mdContentDirective);

/**
 * @ngdoc directive
 * @name mdContent
 * @module material.components.content
 *
 * @restrict E
 *
 * @description
 *
 * The `<md-content>` directive is a container element useful for scrollable content. It achieves
 * this by setting the CSS `overflow` property to `auto` so that content can properly scroll.
 *
 * In general, `<md-content>` components are not designed to be nested inside one another. If
 * possible, it is better to make them siblings. This often results in a better user experience as
 * having nested scrollbars may confuse the user.
 *
 * ## Troubleshooting
 *
 * In some cases, you may wish to apply the `md-no-momentum` class to ensure that Safari's
 * momentum scrolling is disabled. Momentum scrolling can cause flickering issues while scrolling
 * SVG icons and some other components.
 *
 * @usage
 *
 * Add the `[layout-padding]` attribute to make the content padded.
 *
 * <hljs lang="html">
 *  <md-content layout-padding>
 *      Lorem ipsum dolor sit amet, ne quod novum mei.
 *  </md-content>
 * </hljs>
 *
 */

function mdContentDirective($mdTheming) {
  return {
    restrict: 'E',
    controller: ['$scope', '$element', ContentController],
    link: function(scope, element) {
      element.addClass('_md');     // private md component indicator for styling

      $mdTheming(element);
      scope.$broadcast('$mdContentLoaded', element);

      iosScrollFix(element[0]);
    }
  };

  function ContentController($scope, $element) {
    this.$scope = $scope;
    this.$element = $element;
  }
}

function iosScrollFix(node) {
  // IOS FIX:
  // If we scroll where there is no more room for the webview to scroll,
  // by default the webview itself will scroll up and down, this looks really
  // bad.  So if we are scrolling to the very top or bottom, add/subtract one
  angular.element(node).on('$md.pressdown', function(ev) {
    // Only touch events
    if (ev.pointer.type !== 't') return;
    // Don't let a child content's touchstart ruin it for us.
    if (ev.$materialScrollFixed) return;
    ev.$materialScrollFixed = true;

    if (node.scrollTop === 0) {
      node.scrollTop = 1;
    } else if (node.scrollHeight === node.scrollTop + node.offsetHeight) {
      node.scrollTop -= 1;
    }
  });
}


text:
module HomePageSteps

  step 'ми відкрили початкову сторінку' do
    visit '/'
  end

  step 'в навігаційному меню я хочу бачити посилання на розділи:' do |categories|
    categories.each do |category|
      within('.main-menu') do
        find_link(category[0]) != nil
      end
    end
  end

  step 'ми маємо бачити кількість елементів у відповідному розділі' do
    Category.all.each do |category|
      within('.main-menu') do
        if category.count > 0
          expect(page).to have_content category.count.to_s
        end
      end
    end
  end

end

RSpec.configure { |c| c.include HomePageSteps }


text:
{% extends "layout.html" %}

{% from "macros/_util.html" import render_pagination, render_term %}
{% from "macros/_forms.html" import render_field %}

{% block title %}{{ super() }}{% if q %}{{ _('Search results') }}{% else %}{{ _('Advanced search') }}{% endif %}{% endblock %}

{% block intro_title %}{% if q %}{{ q }}{% else %}{{ _('Advanced search') }}{% endif %}{% endblock %}
{% block intro_text %}{% if q %}{{ ngettext('Your search returned %(num)d result.', 'Your search returned %(num)d results.', page.total ) }}{% else %}{{ _('Search the needle on the haystack.') }}{% endif %}{% endblock %}

{% block content %}
<form class="f1 advancedSearch" action="" method="GET">
    {% include "search/core.html" %}

[arrow]{{ _("Search options") }}

{{ _('General') }}

            {{ render_field(form.mode, tag_class="singleLine") }}
            {{ render_field(form.field, class="input") }}
            {{ render_field(form.pp, class="input") }}

{{ _('Classification') }}

            {{ render_field(form.subject_field, class="input") }}
            {{ render_field(form.product_subset, class="input") }}
            {{ render_field(form.concept_origin, class="input") }}

{{ _('Linguistic information') }}

            {{ render_field(form.na, class="input") }}
            {{ render_field(form.na_org, class="input") }}
            {{ render_field(form.pos, class="input") }}
            {{ render_field(form.tt, class="input") }}

</form>

{% if page and page.items %}

    {% for term in page.items %}

{{ render_term(term) }}

    {% endfor %}

{{ render_pagination(page, 'search.results') }}
{% elif q %}

{{ _('No terms found.') }}

{% endif %}
{% endblock %}


text:
<?php

/**
 * Store attribute backend
 *
 * @category   Mage
 * @package    Mage_Customer
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_Customer_Model_Customer_Attribute_Backend_Store extends Mage_Eav_Model_Entity_Attribute_Backend_Abstract
{
    public function beforeSave($object)
    {
        if ($object->getId()) {
            return $this;
        }

        if (!$object->hasStoreId()) {
            $object->setStoreId(Mage::app()->getStore()->getId());
        }

        if (!$object->hasData('created_in')) {
            $object->setData('created_in', Mage::app()->getStore($object->getStoreId())->getName());
        }
        return $this;
    }
}


text:
<Alloy>
	<Window>
		<Label>This app runs only on iOS or Android</Label>
	</Window>
</Alloy>


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});

var _vue = require('vue');

var _vue2 = _interopRequireDefault(_vue);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

exports.default = _vue2.default.extend({
    name: 'sizeable',
    props: {
        large: Boolean,
        medium: Boolean,
        size: {
            type: [Number, String]
        },
        small: Boolean,
        xLarge: Boolean
    }
});
//# sourceMappingURL=sizeable.js.map


text:
using Xunit;

namespace LiveStream.Samples.Tests
{
    [Collection(nameof(LiveStreamFixture))]
    public class CreateChannelEventTest
    {
        private LiveStreamFixture _fixture;
        private readonly CreateChannelEventSample _createChannelEventSample;
        private string _eventId;

        public CreateChannelEventTest(LiveStreamFixture fixture)
        {
            _fixture = fixture;
            _createChannelEventSample = new CreateChannelEventSample();
            _eventId = $"{_fixture.EventIdPrefix}-{_fixture.RandomId()}";
        }

        [Fact]
        public void CreatesChannelEvent()
        {
            var result = _createChannelEventSample.CreateChannelEvent(
                _fixture.ProjectId, _fixture.LocationId, _fixture.TestChannelForCreateEventId, _eventId);

            Assert.Equal(_fixture.ProjectId, result.EventName.ProjectId);
            Assert.Equal(_fixture.LocationId, result.EventName.LocationId);
            Assert.Equal(_eventId, result.EventName.EventId);
        }
    }
}


text:
	<meta charset="UTF-8">
	<title>Home Screen</title>

	<link rel="stylesheet" href="homescreen.css">

Hello Velocity!


text:
<?php

namespace Lunr\Spawn\Tests;

use Lunr\Spawn\Tests\ResqueJobDispatcherTest;

/**
 * This class contains test methods for the ResqueJobDispatcher class.
 *
 * @covers Lunr\Spawn\ResqueJobDispatcher
 */
class ResqueJobDispatcherDispatchTest extends ResqueJobDispatcherTest
{

    /**
     * Test that dispatch() sets a token string if queue is set.
     *
     * @covers Lunr\Spawn\ResqueJobDispatcher::dispatch
     */
    public function testDispatchUpdateToken()
    {
        $this->mock_method([ $this->resque, 'enqueue' ], 'return "TOKEN";');

        $this->class->dispatch('job', []);

        $value = $this->get_reflection_property_value('token');

        $this->assertNotNull($value);

        $this->unmock_method([ $this->resque, 'enqueue' ]);
    }

    /**
     * Test dispatch_in().
     *
     * @covers Lunr\Spawn\ResqueJobDispatcher::dispatch_in
     */
    public function testDispatchIn()
    {
        $this->mock_method([ $this->scheduler, 'enqueueIn' ], 'return NULL;');

        $value = $this->class->dispatch_in(30, 'job', []);

        $this->assertNull($value);

        $this->unmock_method([ $this->resque, 'enqueueIn' ]);
    }

    /**
     * Test dispatch_at().
     *
     * @covers Lunr\Spawn\ResqueJobDispatcher::dispatch_in
     */
    public function testDispatchAt()
    {
        $this->mock_method([ $this->scheduler, 'enqueueAt' ], 'return NULL;');

        $value = $this->class->dispatch_at(time(), 'job', []);

        $this->assertNull($value);

        $this->unmock_method([ $this->resque, 'enqueueAt' ]);
    }

}

?>


text:
function ind = fixSeedIndex(m, ind)

if is(m, 'Integration')
    % Create a fake model
    [m.Seeds(1:numel(m.s_names)).Name] = deal(m.s_names{:});
end

if ischar(ind) || iscellstr(ind)
    ind = nameToSeedIndex(m, ind, false);
end


text:
package io.ddf.flink.content

import java.util

import io.ddf.DDF
import io.ddf.content.Schema
import io.ddf.content.ViewHandler.{Column, Expression, OperationName, Operator}
import io.ddf.flink.utils.Samples
import org.apache.flink.api.scala.DataSet

import scala.collection.JavaConversions._

class ViewHandler(ddf: DDF) extends io.ddf.content.ViewHandler(ddf) {
  private val arrObjTypeSpecs: String = RepresentationHandler.DATASET_ARR_OBJECT.getTypeSpecsString

  override def getRandomSample(numSamples: Int, withReplacement: Boolean, seed: Int): util.List[Array[AnyRef]] = {
    val dataSet:DataSet[Array[Object]] = ddf.getRepresentationHandler.get(arrObjTypeSpecs).asInstanceOf[DataSet[Array[Object]]]
    val count = dataSet.count
    val fraction = Samples.computeFractionForSampleSize(numSamples, count,withReplacement)
    seqAsJavaList(Samples.randomSample(dataSet,withReplacement,fraction,seed).collect())
  }

  override def getRandomSample(percent: Double, withReplacement: Boolean, seed: Int): DDF = {
    if (percent > 1 || percent < 0) {
      throw new IllegalArgumentException("Sampling fraction must be from 0 to 1")
    } else {
      val dataSet: DataSet[Array[Object]] = ddf.getRepresentationHandler.get(arrObjTypeSpecs).asInstanceOf[DataSet[Array[Object]]]
      val newDS: DataSet[Array[Object]] = Samples.randomSample(dataSet, withReplacement, percent, seed)
      val manager = ddf.getManager
      val columns = ddf.getSchema.getColumns
      val tableName: String = ddf.getSchemaHandler.newTableName()
      val schema = new Schema(tableName, columns)
      val typeSpecs: Array[Class[_]] = Array(classOf[DataSet[_]], classOf[Array[Object]])
      val sampleDDF = manager.newDDF(manager, newDS, typeSpecs, tableName, schema)
      mLog.info(">>>>>>> adding ddf to DDFManager " + sampleDDF.getName)
      manager.addDDF(sampleDDF)
      sampleDDF.getMetaDataHandler.copyFactor(this.getDDF)
      sampleDDF
    }
  }

  override def subset(columnExpr: util.List[Column], filter: Expression): DDF = {
    filter match {
      case op:Operator if (op.getName == OperationName.grep || op.getName == OperationName.grep_ic) =>
          throw new UnsupportedOperationException("Grep and Grep_IC are not supported in Flink DDF")
      case _=>
        super.subset(columnExpr, filter)
    }
  }

}


text:
import socket

host = socket.gethostname()

boilerplate = """
JAVA:=$(shell echo $(JAVA_HOME)/bin/java)
JOPT:=-ea -Xmx7G
JAR:='extract-dataset/target/extract-dataset-1.0-SNAPSHOT.jar'
"""
print(boilerplate)

if host == 'sydney.cs.umass.edu':
    print("PREFIX=qsub -b y -cwd -sync y -l mem_free=8G -l mem_token=8G -o $@.out -e $@.err ")
else:
    print("PREFIX:=")

# default rule
print(".PHONY: default")
print(".DEFAULT: default")
print("default:")
print("\t@echo ${PREFIX} ${JAVA}")
print

indexingRule = """
%.galago: %.trectext.gz
	${PREFIX} ${JAVA} ${JOPT} -cp ${JAR} org.lemurproject.galago.core.tools.App build --inputPath=$< --indexPath=$@
"""
print(indexingRule)

#cat_indexing_methods = [
#    "n100", "n10", "n5",
#    "p10", "p5",
#    "c10", "c5",
#    "title-only"]
cat_indexing_methods = [
    "title-only",
    "c5", "p5"
    ]

indexes = []
for method in cat_indexing_methods:
    indexes += ["cat.%s.galago" % method]
    print("cat.%s.trectext.gz:" % method)
    print("\t${PREFIX} ${JAVA} ${JOPT} -cp ${JAR} wikicat.extract.catgraph.BuildCategoryIndex --method=%s --output=$@" % method)
    print

print(".PHONY: indexes")
print("indexes: " + ' '.join(indexes))

#galago_operator_methods = [
#    "combine",
#    "sdm"
#]
galago_operator_methods = [
    "sdm"
]

# only need to run the *full* settings on the classifier train/validate
classifier_splits = [0,1,2,3,4]

runs = []
evals = []
for method in ["direct"]:
    for qm in galago_operator_methods:
        for split in classifier_splits:
            for cat_index_m in cat_indexing_methods:
                output = "split%d.%s.%s.%s.trecrun" % (split, method, cat_index_m, qm)
                runs += [output]
                cat_index = "cat.%s.galago" % (cat_index_m)
                print(output+":")
                print("\t${PREFIX} ${JAVA} ${JOPT} -cp ${JAR} wikicat.extract.experiments.ExperimentHarness --experiment=%s --split=%d --cat-galago-op=%s --cat-index=%s --output=$@" %(method, split, qm, cat_index))
                print

                eval_output = "split%d.%s.%s.%s.eval" % (split, method, cat_index_m, qm)
                print(eval_output+": "+output)
                print("\t${PREFIX} ${JAVA} ${JOPT} -cp ${JAR} org.lemurproject.galago.core.tools.App eval --comparisons=false --metrics+map --metrics+ndcg --metrics+p1 --metrics+p10 --judgments=split%d.qrel --runs+$< > $@" % (split))
                print
                evals += [eval_output]

rlfiles = []
for split in classifier_splits:
    trecruns = []
    for method in ["direct"]:
        for qm in galago_operator_methods:
            for cat_index_m in cat_indexing_methods:
                trecruns += [("split%d.%s.%s.%s.trecrun" % (split, method, cat_index_m, qm))]
    rlfile = "splits%d.rlinput" % (split)
    rlfiles += [rlfile]
    print("%s: %s" % (rlfile, ' '.join(trecruns)))
    print("\t${PREFIX} ${JAVA} ${JOPT} -cp ${JAR} wikicat.extract.experiments.TrecRunReranker --judgments=split%d.qrel --output=$@ %s" % (split, ' '.join(['--input+'+x for x in trecruns])))
    print

models = []

for ranker_type in [0,3,4,8,9]:
  (trainSplit, validateSplit) = (0,1)
  model_output = "ranklib.r%d.model" % (ranker_type)
  models += [model_output]
  inputs = [rlfiles[trainSplit], rlfiles[validateSplit]]
  print("%s: %s" % (model_output, ' '.join(inputs)))
  print("\t${PREFIX} ${JAVA} ${JOPT} -cp ${JAR} ciir.umass.edu.eval.Evaluator -train %s -validate %s -ranker %d -metric2t map -save $@" % (inputs[0], inputs[1], ranker_type))
  print

print(".PHONY: runs")
print("runs: " + ' '.join(runs))
print
print(".PHONY: evals")
print("evals: " + ' '.join(evals))
print
print(".PHONY: models")
print("models: " + ' '.join(models))
print


text:
"""
 SlipStream Client
 =====
 Copyright (C) 2014 SixSq Sarl (sixsq.com)
 =====
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
"""

from slipstream.ConfigHolder import ConfigHolder
from slipstream.executors.MachineExecutor import MachineExecutor
from slipstream import util
from slipstream.exceptions.Exceptions import ExecutionException, AbortException, \
    InconsistentScaleStateError
from slipstream.util import append_ssh_pubkey_to_authorized_keys, override
from slipstream.NodeDecorator import NodeDecorator

def getExecutor(wrapper, configHolder):
    return NodeDeploymentExecutor(wrapper, configHolder)

class NodeDeploymentExecutor(MachineExecutor):

    def __init__(self, wrapper, config_holder=ConfigHolder()):
        self.verboseLevel = 0
        super(NodeDeploymentExecutor, self).__init__(wrapper, config_holder)

        self.SCALE_ACTION_TO_TARGET = \
            {self.wrapper.SCALE_ACTION_CREATION: 'onvmadd',
             self.wrapper.SCALE_ACTION_REMOVAL: 'onvmremove'}

        self._skip_execute_due_to_vertical_scaling = False

    @override
    def onProvisioning(self):
        super(NodeDeploymentExecutor, self).onProvisioning()

        if self.wrapper.is_scale_state_creating():
            self._add_ssh_pubkey(self.node_instance.get_username())
            self.wrapper.set_scale_state_created()
        elif self._is_vertical_scaling():
            if not self._is_pre_scale_done():
                self._execute_pre_scale_action_target()
                self.wrapper.set_pre_scale_done()

            # Orchestrator applies IaaS action on the node instance.

            self.wrapper.wait_scale_iaas_done()
            self.wrapper.unset_pre_scale_done()
            self._execute_post_scale_action_target()
            self.wrapper.set_scale_action_done()
            self._skip_execute_due_to_vertical_scaling = True
        elif self._is_horizontal_scale_down():
            self._execute_pre_scale_action_target()
            self._execute_report_target_and_send_reports()
            self.wrapper.set_pre_scale_done()
            # We are ready to be terminated.

    @override
    def onExecuting(self):
        util.printAction('Executing')

        self._get_recovery_mode()
        if self._is_recovery_mode():
            util.printDetail("Recovery mode enabled, recipes will not be executed.",
                             verboseThreshold=util.VERBOSE_LEVEL_QUIET)
            return

        if self._skip_execute_due_to_vertical_scaling:
            util.printDetail("Vertical scaling: skipping execution of execute targets.",
                             verboseThreshold=util.VERBOSE_LEVEL_QUIET)
            self._skip_execute_due_to_vertical_scaling = False
            return

        if not self.wrapper.is_scale_state_operational():
            self._execute_build_recipes()
            self._execute_execute_target()
        else:
            self._execute_scale_action_target()

    def _execute_build_recipes(self):
        util.printDetail('Executing build recipes')

        self._execute_target(NodeDecorator.NODE_PRERECIPE, abort_on_err=True)
        self._install_user_packages()
        self._execute_target(NodeDecorator.NODE_RECIPE, abort_on_err=True)

    def _install_user_packages(self):
        util.printAndFlush('Installing packages')

        if self.is_image_built():
            util.printAndFlush('Component already built. No packages to install')
            return

        packages = self.node_instance.get_packages()
        if packages:
            message = 'Installing packages: %s' % ', '.join(packages)
            fail_msg = "Failed installing packages on '%s'" % self._get_node_instance_name()
            util.printStep(message)
            self.wrapper.set_statecustom(message)
            cmd = util.get_packages_install_command(self.node_instance.get_platform(), packages)
            self._launch_script('#!/bin/sh -xe\n%s' % cmd, fail_msg=fail_msg, name='Install packages')
        else:
            util.printAndFlush('No packages to install')

    @override
    def onSendingReports(self):
        util.printAction('Sending report')

        if self._need_to_send_reports():
            self._execute_report_target_and_send_reports()
            self._unset_need_to_send_reports()
        else:
            util.printDetail('INFO: Conditionally skipped sending reports.',
                             verboseThreshold=util.VERBOSE_LEVEL_QUIET)
        self.wrapper.set_scale_state_operational()

    def _execute_report_target_and_send_reports(self):
        exports = {'SLIPSTREAM_REPORT_DIR': util.get_platform_reports_dir()}
        try:
            self._execute_target('report', exports=exports, ssdisplay=False, ignore_abort=True)
        except ExecutionException as ex:
            util.printDetail("Failed executing 'report' with: \n%s" % str(ex),
                             verboseLevel=self.verboseLevel,
                             verboseThreshold=util.VERBOSE_LEVEL_NORMAL)
            raise
        finally:
            super(NodeDeploymentExecutor, self).onSendingReports()

    @override
    def onReady(self):
        super(NodeDeploymentExecutor, self).onReady()

    def _get_target_on_scale_action(self, action):
        return self.SCALE_ACTION_TO_TARGET.get(action, None)

    def _execute_pre_scale_action_target(self):
        exports = self._get_scaling_exports()
        self._execute_target('prescale', exports)
        self._set_need_to_send_reports()

    def _execute_post_scale_action_target(self):
        exports = self._get_scaling_exports()
        self._execute_target('postscale', exports)
        self._set_need_to_send_reports()

    def _execute_scale_action_target(self):
        scale_action = self._get_global_scale_action()
        if scale_action:
            target = self._get_target_on_scale_action(scale_action)
            if target:
                exports = self._get_scaling_exports()
                self._execute_target(target, exports)
                self._set_need_to_send_reports()
            else:
                util.printDetail("Deployment is scaling. No target to "
                                 "execute on action %s" % scale_action)
        else:
            util.printDetail("WARNING: deployment is scaling, but no "
                             "scaling action defined.")

    def _get_scaling_exports(self):
        node_name, node_instance_names = \
            self.wrapper.get_scaling_node_and_instance_names()
        exports = {'SLIPSTREAM_SCALING_NODE': node_name,
                   'SLIPSTREAM_SCALING_VMS': ' '.join(node_instance_names),
                   'SLIPSTREAM_SCALING_ACTION': self._get_scale_action()}
        return exports

    def _add_ssh_pubkey(self, login_user):
        if not util.is_windows():
            util.printStep('Adding the public keys')
            append_ssh_pubkey_to_authorized_keys(self._get_user_ssh_pubkey(), login_user)

    def _get_user_ssh_pubkey(self):
        return self.wrapper.get_user_ssh_pubkey()

    def _unset_need_to_send_reports(self):
        self._send_reports = False

    def _need_to_send_reports(self):
        return self._send_reports or not self.wrapper.is_scale_state_operational()

    def _get_scale_action(self):
        return self.wrapper.get_scale_action()

    def _get_global_scale_action(self):
        return self.wrapper.get_global_scale_action()

    def _is_pre_scale_done(self):
        return self.wrapper.is_pre_scale_done()

    def _is_vertical_scaling(self):
        return self.wrapper.is_vertical_scaling_vm()

    def _is_horizontal_scale_down(self):
        try:
            return self.wrapper.is_horizontal_scale_down_vm()
        except InconsistentScaleStateError as ex:
            util.printDetail("Machine Executor. Ignoring exception: %s" % str(ex))
            return False


text:
<?php
/**
 * Definition of the BaseObjectChangedEventType type
 *
 * @package php-ews
 * @subpackage Types
 */

/**
 * Definition of the BaseObjectChangedEventType type
 */
class EWSType_BaseObjectChangedEventType extends EWSType
{
    /**
     * TimeStamp property
     *
     * @var EWSType_dateTime
     */
    public $TimeStamp;

    /**
     * FolderId property
     *
     * @var EWSType_FolderIdType
     */
    public $FolderId;

    /**
     * ItemId property
     *
     * @var EWSType_ItemIdType
     */
    public $ItemId;

    /**
     * ParentFolderId property
     *
     * @var EWSType_FolderIdType
     */
    public $ParentFolderId;
}


text:
/**
 * Support classes for integrating a JSR-303 Bean Validation provider
 * (such as Hibernate Validator 4.0) into a Spring ApplicationContext
 * and in particular with Spring's data binding and validation APIs.
 *
 * <p>The central class is {@link
 * org.springframework.validation.beanvalidation.LocalValidatorFactoryBean}
 * which defines a shared ValidatorFactory/Validator setup for availability
 * to other Spring components.
 */
package org.springframework.validation.beanvalidation;


text:
package br.gov.servicos.editor.conteudo;

import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;

import static br.gov.servicos.editor.conteudo.TipoPagina.SERVICO;
import static java.lang.String.format;
import static org.springframework.http.MediaType.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;

@AllArgsConstructor
public class MockMvcEditorAPI {

    private MockMvc mvc;

    @SneakyThrows
    public ResultActions editarCarta(String id) {
        return mvc.perform(get("/editar/api/pagina/servico/" + id)
                .accept(ALL));
    }

    public ResultActions editarNovaCarta() {
        return editarCarta("novo");
    }

    @SneakyThrows
    public ResultActions renomearCarta(String id, String novoNome) {
        return mvc.perform(patch(format("/editar/api/pagina/servico/%s", id))
                .contentType(APPLICATION_JSON)
                .content(novoNome)
                .accept(ALL));
    }

    @SneakyThrows
    public ResultActions salvarCarta(String id, String conteudo) {
        return salvarPagina(SERVICO, id, conteudo);
    }

    @SneakyThrows
    public ResultActions salvarPagina(TipoPagina tipo, String id, String conteudo) {
        return mvc.perform(
                post("/editar/api/pagina/" + tipo.getNome() + '/' + id)
                        .content(conteudo)
                        .accept(ALL)
                        .contentType(APPLICATION_XML));
    }

    @SneakyThrows
    public ResultActions publicarPagina(TipoPagina tipo, String id) {
        return mvc.perform(put("/editar/api/pagina/" + tipo.getNome() + '/' + id)
                .accept(ALL));
    }

    @SneakyThrows
    public ResultActions publicarCarta(String id) {
        return publicarPagina(SERVICO, id);
    }

    @SneakyThrows
    public ResultActions descartarPagina(TipoPagina tipo, String id) {
        String url = format("/editar/api/pagina/%s/%s/descartar", tipo.getNome(), id);
        return mvc.perform(post(url)
                .accept(ALL));
    }

    @SneakyThrows
    public ResultActions descartarCarta(String id) {
        return descartarPagina(SERVICO, id);
    }

    @SneakyThrows
    public ResultActions despublicarCarta(String id) {
        return despublicarPagina(SERVICO, id);
    }

    @SneakyThrows
    public ResultActions despublicarPagina(TipoPagina tipo, String id) {
        String url = format("/editar/api/pagina/" + tipo.getNome() + "/%s/despublicar", id);
        return mvc.perform(post(url)
                .accept(ALL));
    }

    @SneakyThrows
    public ResultActions listar() {
        return mvc.perform(get("/editar/api/conteudos")
                .accept(ALL));
    }

    @SneakyThrows
    public ResultActions excluirPagina(TipoPagina tipo, String id) {
        return mvc.perform(delete("/editar/api/pagina/" + tipo.getNome() + '/' + id)
                .accept(ALL));
    }

    @SneakyThrows
    public ResultActions editarPagina(TipoPagina tipo, String id) {
        return mvc.perform(get("/editar/api/pagina/" + tipo.getNome() + '/' + id)
                .accept(ALL));
    }

    @SneakyThrows
    public ResultActions editarPaginaNova(TipoPagina tipo) {
        return mvc.perform(get("/editar/api/pagina/" + tipo.getNome() + "/novo")
                .accept(ALL));
    }
}


text:
package org.ambraproject.rhino.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.util.Properties;

public class GitInfo {
  private static final Logger log = LoggerFactory.getLogger(GitInfo.class);

  private final String branch;
  private final String describe;
  private final String commitId;
  private final String commitIdAbbrev;
  private final String commitUserName;
  private final String commitUserEmail;
  private final String commitMessageFull;
  private final String commitMessageShort;
  private final String commitTime;
  private final String buildUserName;
  private final String buildUserEmail;
  private final String buildTime;

  public GitInfo() {
    Resource resource = new ClassPathResource("/git.properties");
    Properties props = new Properties();
    try {
      props = PropertiesLoaderUtils.loadProperties(resource);
    } catch (Exception e) {
      log.warn("Could not get the git commit info", e);
    }

    this.branch = getPropertyValue(props, "git.branch");

    this.describe = getPropertyValue(props, "git.commit.id.describe");
    this.commitId = getPropertyValue(props, "git.commit.id");
    this.commitIdAbbrev = getPropertyValue(props, "git.commit.id.abbrev");
    this.commitUserName = getPropertyValue(props, "git.commit.user.name");
    this.commitUserEmail = getPropertyValue(props, "git.commit.user.email");
    this.commitMessageFull = getPropertyValue(props, "git.commit.message.full");
    this.commitMessageShort = getPropertyValue(props, "git.commit.message.short");
    this.commitTime = getPropertyValue(props, "git.commit.time");

    this.buildUserName = getPropertyValue(props, "git.build.user.name");
    this.buildUserEmail = getPropertyValue(props, "git.build.user.email");
    this.buildTime = getPropertyValue(props, "git.build.time");
  }

  /**
   * This is to handle a situation where git folder isn't available
   * @param properties Properties object that contains the git.properties info
   * @param key key
   * @return value, default value is an empty string
   */
  private String getPropertyValue(Properties properties, String key) {
    String value = properties.getProperty(key);
    if (value != null && !value.startsWith("${")) {
      return value;
    } else {
      return "";
    }
  }

  public String getBranch() {
    return branch;
  }

  public String getDescribe() {
    return describe;
  }

  public String getCommitId() {
    return commitId;
  }

  public String getCommitIdAbbrev() {
    return commitIdAbbrev;
  }

  public String getCommitUserName() {
    return commitUserName;
  }

  public String getCommitUserEmail() {
    return commitUserEmail;
  }

  public String getCommitMessageFull() {
    return commitMessageFull;
  }

  public String getCommitMessageShort() {
    return commitMessageShort;
  }

  public String getCommitTime() {
    return commitTime;
  }

  public String getBuildUserName() {
    return buildUserName;
  }

  public String getBuildUserEmail() {
    return buildUserEmail;
  }

  public String getBuildTime() {
    return buildTime;
  }
}


text:
export const webNavigation = {
  onCompleted: {
    addListener: jest.fn(),
  },
  onHistoryStateUpdated: {
    addListener: jest.fn(),
  },
};


text:
package IF::Component::SwitchComponent;
use strict;
use base qw(IF::Component);

use IF::Log;

sub resetValues {
    my ($self) = @_;

    $self->SUPER::resetValues();
    # clean up the component since it'll get re-used over and over
    if (exists $self->{_subcomponents}->{SWITCH_COMPONENT}) {
        delete $self->{_subcomponents}->{SWITCH_COMPONENT};
    };
    $self->setSwitchComponentName();
}

# this switches out the current component and returns the content of the switched one
# but is quite a bit of a hack because it builds a "fake" binding (which allows us to
# do this run-time binding stuff) and passes it into "componentResponseForBinding()"

sub appendToResponse {
    my ($self, $response, $context) = @_;

    if ($self->_switchComponent()) {
        my $fakeBinding = {
            type => $self->_switchComponent()->componentNameRelativeToSiteClassifier(),
            _NAME => "SWITCH_COMPONENT",
        };

        IF::Log::debug("+++++++++++ ".$self->_switchComponent()->componentNameRelativeToSiteClassifier()." ++++++++");
        my $content = $self->componentResponseForBinding($fakeBinding);
        $response->appendContentString($content);
        # This somehow was not being called on iterations, so the
        # switch component would retain previous values (eeek).
        # This solves it... but not the mystery of why resetValues()
        # was not being called properly.
        $self->resetValues();
        return; # ?
    }
    return $self->SUPER::appendToResponse($response, $context);
}

# ISSUE: 2453
# Think it makes more sense to return undef if the switch component
# doesn't exist.  Otherwise the binding sync code gets confused.
sub _switchComponent {
    my ($self) = @_;
    unless ($self->{_subcomponents}->{SWITCH_COMPONENT}) {
        if ($self->switchComponentName()) {
            my $sc = $self->pageWithName($self->switchComponentName());

            if (IF::Log::assert($sc, "Run-time component instantiated")) {
                # Make the new component pretend to be this one in the hierarchy,
                # which should be sufficient to allow for binding synchronisation
                # in both directions during tvfr() and a2r().
                $sc->setPageContextNumberRoot($self->pageContextNumber());
                $sc->setParentBindingName($self->parentBindingName());
                $self->{_subcomponents}->{SWITCH_COMPONENT} = $sc;
            }
        }
    }
    return $self->{_subcomponents}->{SWITCH_COMPONENT};
}

sub componentName {
    my ($self) = @_;
    return $self->switchComponentName() || $self->SUPER::componentName();
}

sub switchComponentName {
    my $self = shift;
    return $self->{switchComponentName};
}

sub setSwitchComponentName {
    my ($self, $value) = @_;
    $self->{switchComponentName} = $value;
}

# override this to proxy the binding values from the parent to the grandchild...
sub pullValuesFromParent {
    my $self = shift;
    return unless ($self->parent() && $self->parent()->synchronizesBindingsWithChildren()
                                && $self->synchronizesBindingsWithParent());

    my $binding = $self->parent()->bindingForKey($self->parentBindingName());

    # we need to first evaluate the binding that specifies the class of the
    # switch component, and set the component name on this component, which is
    # enough so that when _switchComponent() is first invoked, it instantiates
    # the correct component.
    my $value = IF::Utility::evaluateExpressionInComponentContext($binding->{bindings}->{switchComponentName}, $self->parent(), $self->context());
    $self->setSwitchComponentName($value);
    if ($value) {
        IF::Log::debug("SwitchComponent: allowing grandparent ".
            $self->parent()." to push bind values to child ".$self->_switchComponent());
        if ($binding->{bindings}->{switchComponentBindings}) {
            my $switchBindings = IF::Utility::evaluateExpressionInComponentContext(
                    $binding->{bindings}->{switchComponentBindings}, $self->parent(), $self->context());
            $self->parent()->pushValuesToComponentUsingBindings($self->_switchComponent(), $switchBindings);
        } else {
            $self->parent()->pushValuesToComponent($self->_switchComponent());
        }
    }
}

sub pushValuesToParent {
    my $self = shift;
    return unless ($self->parent() && $self->parent()->synchronizesBindingsWithChildren()
                                && $self->synchronizesBindingsWithParent());

    # The switch component should already exist by now.  If not,
    # there's something wrong (but we can fail quietly)
    if ($self->_switchComponent()) {
        IF::Log::debug("SwitchComponent: allowing grandparent ".
            $self->parent()." to pull bind values from child ".$self->_switchComponent());
        $self->parent()->pullValuesFromComponent($self->_switchComponent());
    }
}

# We need these so a SwitchComponent can respond to a direct action.
sub actionMethodForAction {
    my ($self, $action) = @_;
    return unless $self->_switchComponent();
    return $self->_switchComponent()->actionMethodForAction($action);
}

sub invokeDirectActionNamed {
    my ($self, $directAction, $context) = @_;

    return unless $self->_switchComponent();
    return if ($self->_switchComponent() == $self);
    $self->_switchComponent()->setParent($self);
    my $rv = $self->_switchComponent()->invokeDirectActionNamed($directAction, $context);
    $self->_switchComponent()->setParent();
    return $rv;
}

sub hasValidFormValues {
    my ($self, $context) = @_;
    return unless $self->_switchComponent();
    return if ($self->_switchComponent() == $self);
    return $self->_switchComponent()->hasValidFormValues($context);
}

1;


text:
namespace Eureka.Infra.Migrations
{
    using Domain;
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

    //internal sealed class Configuration : DbMigrationsConfiguration<Eureka.Infra.Context.MyDatabase>
    //{
    //    public Configuration()
    //    {
    //        AutomaticMigrationsEnabled = false;
    //    }

    //    protected override void Seed(Eureka.Infra.Context.MyDatabase context)
    //    {
    //        var ideia = new Ideia() { IdeiaID = 1, Titulo = "Eureka", Descricao = "asd a sd asd as d as d ad a d", Avaliacao = 0, Tag = "teste;fluentAPI;" };
    //        var ideia2 = new Ideia() { IdeiaID = 2, Titulo = "Autofac", Descricao = "Inverse of Control", Avaliacao = 10, Tag = "ioc;autofac" };

    //        var comentario = new Comentario() { ComentarioID = 1, Descricao = "dlkajdsasd ad adawelqjweoiquwoj qwjquweioqu eoiuqoweu qoeuoqueoq", Avaliacao = 0 };

    //        ideia.Comentarios.Add(comentario);

    //        context.Ideias.AddOrUpdate(i => i.IdeiaID, ideia, ideia2);
    //        //  This method will be called after migrating to the latest version.

    //        //  You can use the DbSet<T>.AddOrUpdate() helper extension method
    //        //  to avoid creating duplicate seed data. E.g.
    //        //
    //        //    context.People.AddOrUpdate(
    //        //      p => p.FullName,
    //        //      new Person { FullName = "Andrew Peters" },
    //        //      new Person { FullName = "Brice Lambson" },
    //        //      new Person { FullName = "Rowan Miller" }
    //        //    );
    //        //
    //    }
    //}
}


text:
<?php

namespace hipanel\modules\client\models\query;

use hiqdev\hiart\ActiveQuery;

class ArticleQuery extends ActiveQuery
{
    public function ticketTemplates()
    {
        $this->andWhere([
            'realm' => 'ticket_template',
            'with_data' => true,
        ]);

        return $this;
    }
}