text:
package org.zstack.network.service.virtualrouter;

import org.springframework.beans.factory.annotation.Autowire;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.zstack.appliancevm.*;
import org.zstack.appliancevm.ApplianceVmConstant.Params;
import org.zstack.core.db.SimpleQuery;
import org.zstack.core.db.SimpleQuery.Op;
import org.zstack.core.errorcode.ErrorFacade;
import org.zstack.core.thread.ChainTask;
import org.zstack.core.thread.SyncTaskChain;
import org.zstack.header.core.Completion;
import org.zstack.header.core.workflow.*;
import org.zstack.header.errorcode.ErrorCode;
import org.zstack.header.errorcode.SysErrors;
import org.zstack.header.message.APIMessage;
import org.zstack.header.message.Message;
import org.zstack.header.rest.JsonAsyncRESTCallback;
import org.zstack.header.rest.RESTFacade;
import org.zstack.header.vm.VmInstanceInventory;
import org.zstack.header.vm.VmInstanceState;
import org.zstack.network.service.virtualrouter.VirtualRouterCommands.PingCmd;
import org.zstack.network.service.virtualrouter.VirtualRouterCommands.PingRsp;
import org.zstack.network.service.virtualrouter.VirtualRouterConstant.Param;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 */
@Configurable(preConstruction = true, autowire = Autowire.BY_TYPE)
public class VirtualRouter extends ApplianceVmBase {

    static {
        allowedOperations.addState(VmInstanceState.Running, APIReconnectVirtualRouterMsg.class.getName());
        allowedOperations.addState(VmInstanceState.Running, ReconnectVirtualRouterVmMsg.class.getName());
    }

    @Autowired
    private VirtualRouterManager vrMgr;
    @Autowired
    private RESTFacade restf;
    @Autowired
    private ErrorFacade errf;

    private VirtualRouterVmInventory vr;

    public VirtualRouter(ApplianceVmVO vo) {
        super(vo);
    }

    public VirtualRouter(VirtualRouterVmVO vo) {
        super(vo);
        vr = new VirtualRouterVmInventory(vo);
    }

    @Override
    protected VmInstanceInventory getSelfInventory() {
        return VirtualRouterVmInventory.valueOf(getSelf());
    }

    @Override
    protected List<Flow> getPostCreateFlows() {
        return vrMgr.getPostCreateFlows();
    }

    @Override
    protected List<Flow> getPostStartFlows() {
        return vrMgr.getPostStartFlows();
    }

    @Override
    protected List<Flow> getPostStopFlows() {
        return vrMgr.getPostStopFlows();
    }

    @Override
    protected List<Flow> getPostRebootFlows() {
        return vrMgr.getPostRebootFlows();
    }

    @Override
    protected List<Flow> getPostDestroyFlows() {
        return vrMgr.getPostDestroyFlows();
    }

    @Override
    protected List<Flow> getPostMigrateFlows() {
        return vrMgr.getPostMigrateFlows();
    }

    @Override
    protected void handleApiMessage(APIMessage msg) {
        if (msg instanceof APIReconnectVirtualRouterMsg) {
            handle((APIReconnectVirtualRouterMsg) msg);
        } else {
            super.handleApiMessage(msg);
        }
    }

    @Override
    protected void handleLocalMessage(Message msg) {
        if (msg instanceof VirtualRouterAsyncHttpCallMsg) {
            handle((VirtualRouterAsyncHttpCallMsg) msg);
        } else if (msg instanceof ReconnectVirtualRouterVmMsg) {
            handle((ReconnectVirtualRouterVmMsg) msg);
        } else if (msg instanceof PingVirtualRouterVmMsg) {
            handle((PingVirtualRouterVmMsg) msg);
        } else {
            super.handleLocalMessage(msg);
        }
    }

    private void handle(final PingVirtualRouterVmMsg msg) {
        thdf.chainSubmit(new ChainTask(msg) {
            @Override
            public String getSyncSignature() {
                return syncThreadName;
            }

            @Override
            public void run(final SyncTaskChain chain) {
                final PingVirtualRouterVmReply reply = new PingVirtualRouterVmReply();
                if (VmInstanceState.Running != self.getState() || ApplianceVmStatus.Connecting == getSelf().getStatus()) {
                    reply.setDoReconnect(false);
                    bus.reply(msg, reply);
                    chain.next();
                    return;
                }

                PingCmd cmd = new PingCmd();
                cmd.setUuid(self.getUuid());
                restf.asyncJsonPost(vrMgr.buildUrl(vr.getManagementNic().getIp(), VirtualRouterConstant.VR_PING), cmd, new JsonAsyncRESTCallback<PingRsp>(msg, chain) {
                    @Override
                    public void fail(ErrorCode err) {
                        reply.setDoReconnect(true);
                        reply.setConnected(false);
                        logger.warn(String.format("failed to ping the virtual router vm[uuid:%s], %s. We will reconnect it soon", self.getUuid(), reply.getError()));
                        bus.reply(msg, reply);
                        chain.next();
                    }

                    @Override
                    public void success(PingRsp ret) {
                        reply.setDoReconnect(true);
                        if (!ret.isSuccess()) {
                            logger.warn(String.format("failed to ping the virtual router vm[uuid:%s], %s. We will reconnect it soon", self.getUuid(), ret.getError()));
                            reply.setConnected(false);
                        } else {
                            boolean connected = self.getUuid().equals(ret.getUuid());
                            if (!connected) {
                                logger.warn(String.format("a signature lost on the virtual router vm[uuid:%s] changed, it's probably caused by the agent restart. We will issue a reconnect soon", self.getUuid()));
                            }
                            reply.setConnected(connected);
                        }
                        bus.reply(msg, reply);
                        chain.next();
                    }

                    @Override
                    public Class<PingRsp> getReturnClass() {
                        return PingRsp.class;
                    }
                });
            }

            @Override
            public String getName() {
                return "ping-virtual-router";
            }
        });

    }

    private void handle(final ReconnectVirtualRouterVmMsg msg) {
        thdf.chainSubmit(new ChainTask(msg) {
            @Override
            public String getSyncSignature() {
                return syncThreadName;
            }

            @Override
            public void run(final SyncTaskChain chain) {
                final ReconnectVirtualRouterVmReply reply = new ReconnectVirtualRouterVmReply();

                refreshVO();
                ErrorCode allowed = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR);
                if (allowed != null) {
                    reply.setError(allowed);
                    bus.reply(msg, reply);
                    chain.next();
                    return;
                }

                reconnect(new Completion(msg, chain) {
                    @Override
                    public void success() {
                        bus.reply(msg, reply);
                        chain.next();
                    }

                    @Override
                    public void fail(ErrorCode errorCode) {
                        reply.setError(errorCode);
                        bus.reply(msg, reply);
                        chain.next();
                    }
                });
            }

            @Override
            public String getName() {
                return String.format("reconnect-virtual-router-%s", self.getUuid());
            }
        });
    }

    private void handle(final VirtualRouterAsyncHttpCallMsg msg) {
        thdf.chainSubmit(new ChainTask(msg) {
            @Override
            public String getSyncSignature() {
                return String.format("%s-commands", syncThreadName);
            }

            @Override
            public void run(final SyncTaskChain chain) {
                final VirtualRouterAsyncHttpCallReply reply = new VirtualRouterAsyncHttpCallReply();
                if (msg.isCheckStatus() && getSelf().getStatus() != ApplianceVmStatus.Connected) {
                    reply.setError(errf.stringToOperationError(String.format("virtual router[uuid:%s] is in status of %s that cannot make http call to %s",
                            self.getUuid(), getSelf().getStatus(), msg.getPath())));
                    bus.reply(msg, reply);
                    chain.next();
                    return;
                }

                restf.asyncJsonPost(vrMgr.buildUrl(vr.getManagementNic().getIp(), msg.getPath()), msg.getCommand(), new JsonAsyncRESTCallback<LinkedHashMap>(msg, chain) {
                    @Override
                    public void fail(ErrorCode err) {
                        reply.setError(err);
                        bus.reply(msg, reply);
                        chain.next();
                    }

                    @Override
                    public void success(LinkedHashMap ret) {
                        reply.setResponse(ret);
                        bus.reply(msg, reply);
                        chain.next();
                    }

                    @Override
                    public Class<LinkedHashMap> getReturnClass() {
                        return LinkedHashMap.class;
                    }
                }, TimeUnit.SECONDS, msg.getCommandTimeout());
            }

            @Override
            protected int getSyncLevel() {
                return vrMgr.getParallelismDegree(self.getUuid());
            }

            @Override
            public String getName() {
                return getSyncSignature();
            }
        });
    }

    private void handle(final APIReconnectVirtualRouterMsg msg) {
        thdf.chainSubmit(new ChainTask(msg) {
            @Override
            public String getSyncSignature() {
                return syncThreadName;
            }

            @Override
            public void run(final SyncTaskChain chain) {
                final APIReconnectVirtualRouterEvent evt = new APIReconnectVirtualRouterEvent(msg.getId());

                refreshVO();
                ErrorCode allowed = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR);
                if (allowed != null) {
                    evt.setErrorCode(allowed);
                    bus.publish(evt);
                    chain.next();
                    return;
                }

                reconnect(new Completion(msg, chain) {
                    @Override
                    public void success() {
                        evt.setInventory((ApplianceVmInventory) getSelfInventory());
                        bus.publish(evt);
                        chain.next();
                    }

                    @Override
                    public void fail(ErrorCode errorCode) {
                        evt.setErrorCode(errorCode);
                        bus.publish(evt);
                        chain.next();
                    }
                });
            }

            @Override
            public String getName() {
                return String.format("reconnect-virtual-router-%s", self.getUuid());
            }
        });
    }

    private void reconnect(final Completion completion) {
        FlowChain chain = vrMgr.getReconnectFlowChain();
        chain.setName(String.format("reconnect-virtual-router-%s", self.getUuid()));
        chain.getData().put(VirtualRouterConstant.Param.VR.toString(), vr);
        chain.getData().put(Param.IS_RECONNECT.toString(), Boolean.TRUE.toString());
        chain.getData().put(Params.isReconnect.toString(), Boolean.TRUE.toString());
        chain.getData().put(Params.managementNicIp.toString(), vr.getManagementNic().getIp());
        chain.getData().put(Params.applianceVmUuid.toString(), self.getUuid());

        SimpleQuery<ApplianceVmFirewallRuleVO> q = dbf.createQuery(ApplianceVmFirewallRuleVO.class);
        q.add(ApplianceVmFirewallRuleVO_.applianceVmUuid, Op.EQ, getSelf().getUuid());
        List<ApplianceVmFirewallRuleVO> vos = q.list();
        List<ApplianceVmFirewallRuleInventory> rules = ApplianceVmFirewallRuleInventory.valueOf(vos);
        chain.getData().put(ApplianceVmConstant.Params.applianceVmFirewallRules.toString(), rules);

        chain.insert(new Flow() {
            String __name__ = "change-appliancevm-status-to-connecting";

            @Override
            public void run(FlowTrigger trigger, Map data) {
                getSelf().setStatus(ApplianceVmStatus.Connecting);
                self = dbf.updateAndRefresh(self);
                trigger.next();
            }

            @Override
            public void rollback(FlowTrigger trigger, Map data) {
                self = dbf.reload(self);
                getSelf().setStatus(ApplianceVmStatus.Disconnected);
                self = dbf.updateAndRefresh(self);
                trigger.rollback();
            }
        }).then(new NoRollbackFlow() {
            String __name__ = "change-appliancevm-status-to-connected";

            @Override
            public void run(FlowTrigger trigger, Map data) {
                getSelf().setStatus(ApplianceVmStatus.Connected);
                self = dbf.updateAndRefresh(self);
                trigger.next();
            }
        }).done(new FlowDoneHandler(completion) {
            @Override
            public void handle(Map data) {
                self = dbf.reload(self);
                completion.success();
            }
        }).error(new FlowErrorHandler(completion) {
            @Override
            public void handle(ErrorCode errCode, Map data) {
                completion.fail(errCode);
            }
        }).start();
    }
}


text:
namespace _2.Japanese_Roulette
{
    using System;
    using System.Linq;

    class Program
    {
        static void Main(string[] args)
        {
            int[] bullets = Console.ReadLine().Split().Select(int.Parse).ToArray();
            string[] commands = Console.ReadLine().Split();

            int bulletPosition = 0;

            for (int i = 0; i < bullets.Length; i++)
            {
                if (bullets[i] == 1)
                {
                    bulletPosition = i;
                    break;
                }
            }

            for (int player = 0; player < commands.Length; player++)
            {
                string[] currentCommands = commands[player].Split(',');
                int muzzle = 2;

                int playerPower = int.Parse(currentCommands[0]);
                string playerDirection = currentCommands[1];

                if (playerDirection == "Right")
                {
                    for (int i = 0; i < playerPower; i++)
                    {
                        bulletPosition = MoveRight(bullets, bulletPosition);
                    }

                    if (bullets[muzzle] == 1)
                    {
                        Console.WriteLine($"Game over! Player {player} is dead.");
                        return;
                    }
                }

                else if (playerDirection == "Left")
                {
                    for (int i = 0; i < playerPower; i++)
                    {
                        bulletPosition = MoveLeft(bullets, bulletPosition);
                    }

                    if (bullets[muzzle] == 1)
                    {
                        Console.WriteLine($"Game over! Player {player} is dead.");
                        return;
                    }
                }

                bulletPosition = MoveRight(bullets, bulletPosition);
            }

            Console.WriteLine("Everybody got lucky!");
        }

        private static int MoveRight(int[] bullets, int bulletPosition)
        {
            if (bullets[bullets.Length - 1] == 1)
            {
                bullets[bullets.Length - 1] = 0;
                bullets[0] = 1;
            }
            else
            {
                int temporal = bullets[bulletPosition + 1];
                bullets[bulletPosition + 1] = bullets[bulletPosition];
                bullets[bulletPosition] = temporal;
            }

            for (int i = 0; i < bullets.Length; i++)
            {
                if (bullets[i] == 1)
                {
                    bulletPosition = i;
                    break;
                }
            }

            return bulletPosition;
        }

        private static int MoveLeft(int[] bullets, int bulletPosition)
        {
            if (bullets[0] == 1)
            {
                bullets[0] = 0;
                bullets[bullets.Length - 1] = 1;
            }

            else
            {
                int temporal = bullets[bulletPosition - 1];
                bullets[bulletPosition - 1] = bullets[bulletPosition];
                bullets[bulletPosition] = temporal;
            }

            for (int i = 0; i < bullets.Length; i++)
            {
                if (bullets[i] == 1)
                {
                    bulletPosition = i;
                    break;
                }
            }

            return bulletPosition;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package maintenance

import (
	"context"
	"sort"
	"time"

	"github.com/pkg/errors"

	"github.com/kopia/kopia/internal/clock"
	"github.com/kopia/kopia/internal/units"
	"github.com/kopia/kopia/repo"
	"github.com/kopia/kopia/repo/blob"
)

// LogRetentionOptions provides options for logs retention.
type LogRetentionOptions struct {
	MaxTotalSize int64            `json:"maxTotalSize"`
	MaxCount     int              `json:"maxCount"`
	MaxAge       time.Duration    `json:"maxAge"`
	DryRun       bool             `json:"-"`
	TimeFunc     func() time.Time `json:"-"`
}

// OrDefault returns default LogRetentionOptions.
func (o LogRetentionOptions) OrDefault() LogRetentionOptions {
	if o.MaxCount == 0 && o.MaxAge == 0 && o.MaxTotalSize == 0 {
		return defaultLogRetention()
	}

	return o
}

// defaultLogRetention returns CleanupLogsOptions applied by default during maintenance.
func defaultLogRetention() LogRetentionOptions {
	//nolint:gomnd
	return LogRetentionOptions{
		MaxTotalSize: 1 << 30,             // keep no more than 1 GiB logs
		MaxAge:       30 * 24 * time.Hour, // no more than 30 days of data
		MaxCount:     10000,               // no more than 10K logs
	}
}

// CleanupLogs deletes old logs blobs beyond certain age, total size or count.
func CleanupLogs(ctx context.Context, rep repo.DirectRepositoryWriter, opt LogRetentionOptions) ([]blob.Metadata, error) {
	if opt.TimeFunc == nil {
		opt.TimeFunc = clock.Now
	}

	allLogBlobs, err := blob.ListAllBlobs(ctx, rep.BlobStorage(), "_")
	if err != nil {
		return nil, errors.Wrap(err, "error listing logs")
	}

	// sort by time so that most recent are first
	sort.Slice(allLogBlobs, func(i, j int) bool {
		return allLogBlobs[i].Timestamp.After(allLogBlobs[j].Timestamp)
	})

	var totalSize int64

	deletePosition := len(allLogBlobs)

	for i, bm := range allLogBlobs {
		totalSize += bm.Length

		if totalSize > opt.MaxTotalSize && opt.MaxTotalSize > 0 {
			deletePosition = i
			break
		}

		if i >= opt.MaxCount && opt.MaxCount > 0 {
			deletePosition = i
			break
		}

		if age := opt.TimeFunc().Sub(bm.Timestamp); age > opt.MaxAge && opt.MaxAge != 0 {
			deletePosition = i
			break
		}
	}

	toDelete := allLogBlobs[deletePosition:]

	log(ctx).Debugf("Keeping %v logs of total size %v", deletePosition, units.BytesString(totalSize))

	if !opt.DryRun {
		for _, bm := range toDelete {
			if err := rep.BlobStorage().DeleteBlob(ctx, bm.BlobID); err != nil {
				return nil, errors.Wrapf(err, "error deleting log %v", bm.BlobID)
			}
		}
	}

	return toDelete, nil
}


text:
package com.manaldush.telnet.protocol;

import com.google.common.base.Preconditions;
import com.manaldush.telnet.Configuration;

/**
 * Created by Maxim.Melnikov on 29.06.2017.
 */
public final class ConfigurationWrapper implements Cloneable {
    private final Configuration conf;
    private final IServerSocketChannelFactory ssChannelFactory;
    private ConfigurationWrapper(final Configuration _conf, final IServerSocketChannelFactory _ssChannelFactory) {
        conf = _conf;
        ssChannelFactory = _ssChannelFactory;
    }

    /**
     * Config file wrapper build method.
     * @param _conf - configuration
     * @param _ssChannelFactory - socket factory
     * @throws NullPointerException - configuration is null
     * @return wrapper
     */
    public static ConfigurationWrapper build(final Configuration _conf,
                                             final IServerSocketChannelFactory _ssChannelFactory) {
        Preconditions.checkNotNull(_conf);
        if (_ssChannelFactory == null) {
            return new ConfigurationWrapper(_conf, new ImplServerSocketChannel());
        } else {
            return new ConfigurationWrapper(_conf, _ssChannelFactory);
        }
    }

    /**
     * Get configuration.
     * @return configuration object
     */
    public Configuration getConf() {
        return conf;
    }

    /**
     * Get server socket factory object.
     * @return factory
     */
    public IServerSocketChannelFactory getSsChannelFactory() {
        return ssChannelFactory;
    }

    @Override
    public Object clone() {
        return ConfigurationWrapper.build((Configuration) this.getConf().clone(), this.getSsChannelFactory());
    }
}


text:
/*
 * Jitsi, the OpenSource Java VoIP and Instant Messaging client.
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package net.java.sip.communicator.service.resources;

import java.util.*;

/**
 * Default Skin Pack interface.
 *
 * @author Adam Netocny
 */
public interface SkinPack
    extends ResourcePack
{
    /**
     * Default resource name.
     */
    public static final String RESOURCE_NAME_DEFAULT_VALUE = "SkinPack";

    /**
     * Returns a <tt>Map</tt>, containing all [key, value] pairs for image
     * resource pack.
     *
     * @return a <tt>Map</tt>, containing all [key, value] pairs for image
     * resource pack.
     */
    public Map<String, String> getImageResources();

    /**
     * Returns a <tt>Map</tt>, containing all [key, value] pairs for style
     * resource pack.
     *
     * @return a <tt>Map</tt>, containing all [key, value] pairs for style
     * resource pack.
     */
    public Map<String, String> getStyleResources();

    /**
     * Returns a <tt>Map</tt>, containing all [key, value] pairs for color
     * resource pack.
     *
     * @return a <tt>Map</tt>, containing all [key, value] pairs for color
     * resource pack.
     */
    public Map<String, String> getColorResources();

    /**
     * Returns a <tt>Map</tt>, containing all [key, value] pairs for settings
     * resource pack.
     *
     * @return a <tt>Map</tt>, containing all [key, value] pairs for settings
     * resource pack.
     */
    public Map<String, String> getSettingsResources();
}


text:
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.scopes;

import com.intellij.ide.scopeView.NamedScopeFilter;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.module.ModifiableModuleModel;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.packageDependencies.DependencyValidationManager;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiJavaFile;
import com.intellij.psi.PsiPlainTextFile;
import com.intellij.psi.search.scope.packageSet.NamedScope;
import com.intellij.psi.search.scope.packageSet.PackageSet;
import com.intellij.psi.search.scope.packageSet.PackageSetFactory;
import com.intellij.testFramework.TestSourceBasedTestCase;
import org.jetbrains.annotations.NotNull;

public class PackageSetTest extends TestSourceBasedTestCase {
  private String myModuleName;
  private DependencyValidationManager myHolder;
  private PackageSetFactory myPackageSetFactory;

  @Override
  protected void setUp() throws Exception {
    super.setUp();
    myHolder = DependencyValidationManager.getInstance(getProject());
    myPackageSetFactory = PackageSetFactory.getInstance();
    ApplicationManager.getApplication().runWriteAction(() -> {
      final ModifiableModuleModel moduleModel = ModuleManager.getInstance(getProject()).getModifiableModel();
      moduleModel.setModuleGroupPath(getModule(), new String[]{"GRP"});
      moduleModel.commit();
    });
    myModuleName = getModule().getName();
  }

  @Override
  protected void tearDown() throws Exception {
    myPackageSetFactory = null;
    myHolder = null;
    super.tearDown();
  }

  public void testResFilePattern() throws Exception {
    final PsiDirectory directory = getPackageDirectory("pack");
    final VirtualFile resources = getContentDirectory().getVirtualFile().findFileByRelativePath("resources");
    assert resources != null;
    final PsiDirectory resourcesDirectory = getPsiManager().findDirectory(resources);
    PackageSet packageSet = myPackageSetFactory.compile("file[" + myModuleName + "]:**.jsp");
    assert resourcesDirectory != null;
    PsiFile [] psiFiles = resourcesDirectory.getFiles();
    for (PsiFile psiFile : psiFiles) {
      assertFalse(packageSet.contains(psiFile, myHolder));
    }

    packageSet = myPackageSetFactory.compile("file[" + myModuleName + "]:*.jsp");
    psiFiles = assertAllFilesIncluded(resourcesDirectory,
                                      packageSet, myHolder) ;
    assertEquals(1, psiFiles.length);

    packageSet = myPackageSetFactory.compile("file[" + myModuleName + "]:*//*");
    assertAllFilesIncluded(directory, packageSet, myHolder);
    assertAllFilesIncluded(resourcesDirectory, packageSet, myHolder);

    packageSet = myPackageSetFactory.compile("file:*//*");
    assertAllFilesIncluded(directory, packageSet, myHolder);
    assertAllFilesIncluded(resourcesDirectory, packageSet, myHolder);

    packageSet = myPackageSetFactory.compile("file:*.txt");
    psiFiles = directory.getFiles();
    for (PsiFile psiFile : psiFiles) {
      if (psiFile instanceof PsiPlainTextFile){
        assertTrue(packageSet.contains(psiFile, myHolder));
      } else {
        assertFalse(packageSet.contains(psiFile, myHolder));
      }
    }
  }

  public void testDirWithSpacesFilePattern() throws Exception {
    final PackageSet packageSet = myPackageSetFactory.compile("file[" + myModuleName + "]:src/with space/**");
    final PsiDirectory withSpaceDirectory = getPackageDirectory("with space");
    final PsiFile [] psiFiles = assertAllFilesIncluded(withSpaceDirectory, packageSet, myHolder);
    assertEquals(1, psiFiles.length);
  }

  public void testDirWithDashesFilePattern() throws Exception {
    final PackageSet packageSet = myPackageSetFactory.compile("file[" + myModuleName + "]:src/with-dash/**");
    final PsiDirectory withSpaceDirectory = getPackageDirectory("with-dash");
    final PsiFile [] psiFiles = assertAllFilesIncluded(withSpaceDirectory, packageSet, myHolder);
    assertEquals(1, psiFiles.length);
  }

  public void testIncludeDirectoryItself() throws Exception {
    NamedScopeFilter filter = createFilter("file:src/pack//*");
    VirtualFile dir = getPackageDirectory("pack").getVirtualFile();
    for (VirtualFile file : dir.getChildren()) {
      assertTrue(filter.accept(file));
    }
    assertTrue(filter.accept(dir));
  }

  public void testExcludeDirectoryItself() throws Exception {
    NamedScopeFilter filter = createFilter("!file:src/pack//*");
    VirtualFile dir = getPackageDirectory("pack").getVirtualFile();
    for (VirtualFile file : dir.getChildren()) {
      assertFalse(filter.accept(file));
    }
    assertFalse(filter.accept(dir));
  }

  @NotNull
  private NamedScopeFilter createFilter(@NotNull String pattern) throws Exception {
    PackageSet set = myPackageSetFactory.compile(pattern);
    NamedScope scope = new NamedScope(pattern, set);
    return new NamedScopeFilter(myHolder, scope);
  }

  public void testModuleFilePattern() throws Exception {
    final PsiDirectory directory = getPackageDirectory("pack");

    PackageSet packageSet = myPackageSetFactory.compile("file[" + myModuleName + "]:src/pack/**.txt||file[" + myModuleName + "]:src/pack/**.java");
    PsiFile[] psiFiles = assertAllFilesIncluded(directory, packageSet, myHolder);

    packageSet = myPackageSetFactory.compile("file[" + myModuleName + "]:*.java");
    for (PsiFile psiFile : psiFiles) {
      if (psiFile instanceof PsiJavaFile){
        assertTrue(packageSet.contains(psiFile, myHolder));
      } else {
        assertFalse(packageSet.contains(psiFile, myHolder));
      }
    }
  }

  public void testNoModuleFilePattern() throws Exception {
    final PsiDirectory directory = getPackageDirectory("pack");
    final PackageSet packageSet = myPackageSetFactory.compile("file:src/pack/*");
    assertAllFilesIncluded(directory, packageSet, myHolder);
  }

  public void testAllInModuleMisc() throws Exception {

    PackageSet packageSet = myPackageSetFactory.compile("src[" + myModuleName + "]:*..*");
    PsiDirectory directory = getPackageDirectory("pack");
    PsiFile[] psiFiles = assertAllFilesIncluded(directory, packageSet, myHolder);
    assertEquals(4, psiFiles.length);

    packageSet = myPackageSetFactory.compile("src[" + myModuleName + "*]:*..*");
    assertAllFilesIncluded(directory, packageSet, myHolder);

    packageSet = myPackageSetFactory.compile("src[" + myModuleName + "]:*..*||file[" + myModuleName + "]:**/pack/**.java");
    assertAllFilesIncluded(directory,     packageSet, myHolder);

    packageSet = myPackageSetFactory.compile("(src[" + myModuleName + "]:*..*)||(file[" + myModuleName + "]:**/pack/**.java)");
    assertAllFilesIncluded(directory, packageSet, myHolder);

    packageSet = myPackageSetFactory.compile("((src[" + myModuleName + "]:*..*)&&(file[" + myModuleName + "]:*//*))");
    assertAllFilesIncluded(directory, packageSet, myHolder);

    packageSet = myPackageSetFactory.compile("file[" + myModuleName + "]:*//*");
    assertAllFilesIncluded(directory, packageSet, myHolder);
  }

  public void testModuleGroup() throws Exception {
    PackageSet packageSet = myPackageSetFactory.compile("src[group:GRP:" + myModuleName + "]:*..*");
    PsiDirectory directory = getPackageDirectory("pack");
    PsiFile[] psiFiles = assertAllFilesIncluded(directory, packageSet, myHolder);
    assertEquals(4, psiFiles.length);

    packageSet = myPackageSetFactory.compile("src[group:GRP]:*..*");
    assertAllFilesIncluded(directory, packageSet, myHolder);
  }

  public void testRecursivePattern() throws Exception {
    PackageSet packageSet = myPackageSetFactory.compile("src[" + myModuleName + "]:pack1..*");
    PsiDirectory directory = getPackageDirectory("pack1/pack2");
    assertAllFilesIncluded(directory, packageSet, myHolder);

    packageSet = myPackageSetFactory.compile("src[" + myModuleName + "]:pack1.*");
    directory = getPackageDirectory("pack1");
    assertAllFilesIncluded(directory, packageSet, myHolder);

    directory = getPackageDirectory("pack1/pack2");
    final PsiFile[] psiFiles = directory.getFiles();
    assertNotNull(psiFiles);
    assertEquals(1, psiFiles.length);
    assertFalse(packageSet.contains(psiFiles[0], myHolder));
  }

  private static PsiFile[] assertAllFilesIncluded(PsiDirectory directory,
                                                  PackageSet packageSet,
                                                  DependencyValidationManager holder) {
    PsiFile[] psiFiles = directory.getFiles();
    assertNotNull(psiFiles);

    for (PsiFile psiFile : psiFiles) {
      assertTrue(psiFile.getVirtualFile().getPath(), packageSet.contains(psiFile, holder));
    }
    return psiFiles;
  }

  @Override
  protected String getTestPath() {
    return "packageSet";
  }

  @NotNull
  @Override
  protected String getTestDirectoryName() {
    return "oneModuleStructure";
  }
}


text:
<idea-plugin version="2">
    <extensions defaultExtensionNs="ru.yole.jitwatch">
        <languageSupport language="kotlin" implementationClass="ru.yole.jitwatch.languages.JitWatchKotlinSupport"/>
    </extensions>

    <extensions defaultExtensionNs="com.intellij">
        <codeInsight.lineMarkerProvider language="kotlin" implementationClass="ru.yole.jitwatch.JitLineMarkerProvider"/>
        <externalAnnotator language="kotlin" implementationClass="ru.yole.jitwatch.JitSourceAnnotator"/>
    </extensions>
</idea-plugin>


text:
gms-net-StringSend
==================

Demo of sending a string over a network using GameMaker: Studio


text:
package com.wolkabout.wolkrestandroid.dto;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
public class ResetPasswordRequest {

    private String email;

    public ResetPasswordRequest() {
    }

    public ResetPasswordRequest(String email) {
        this.email = email;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "ResetPasswordRequest{" +
                "email='" + email + '\'' +
                '}';
    }
}


text:
title: Calvetica Redesign
date: 2014-12-27
tags:
- design
---

> Note: This is an older piece that I did for a previous site. Calvetica has since redesigned its app quite a bit!

![](/images/calvetica/1.png)

Here's the Calvetica home screen that I started with. The main thing I wanted to adjust was how much real estate/visual weight was given to the current year and the month picker (which is tappable — it changes the month displayed in the calendar below). I also wanted to add today's date and make a few other minor tweaks.

![](/images/calvetica/2.png)

Since I figure the frequency at which you need to look at a given month is inversely proportional to how close it is to today, I collapsed the month picker down to one line. The left and right edges are faded out slightly as an affordance that the list is horizontally scrollable.

![](/images/calvetica/3.png)

Next, since I wanted to add in today's date and the month picker change opened up some space, I decided to go with a more overtly header-y treatment at the top of the screen. Like the existing Calvetica detail pages, this section displays the full day and date, but I also swapped the Today shortcut with the settings icon so that all the "right now" stuff would be in the header. I also spelled out "Settings" on the bottom to be consistent with "Notifications."

![](/images/calvetica/4.png)

Finally, I added a badge to the "today" link in the header so that the user doesn't have to look to the detailed calendar for the relative "busy-ness" of the current day.

I played around with adding separate badges to the "Today" link for each calendar (for example, in this comp they would read 4 for the purple calendar and 1 for the grayish one), but ended up tossing that idea — it might work well for my own relatively light usage, but as the number of badges increased the design started to get really cramped. Plus, if we ever needed to localize the strings in the header there, we'd need the badge to occupy a small fixed space.


text:
package com.facebook.buck.android;

import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.step.ExecutionContext;
import com.facebook.buck.step.Step;

import java.io.IOException;
import java.nio.file.Path;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * This step writes the size of a .dex.jar file and the uncompressed size of its contained
 * classes.dex to the given metadata file.  We use this information during
 * dex file loading to estimate the amount of disk space we'll need.
 */
class DexJarAnalysisStep implements Step {

  private final Path dexPath;
  private final Path dexMetaPath;

  DexJarAnalysisStep(Path dexPath, Path dexMetaPath) {
    this.dexPath = dexPath;
    this.dexMetaPath = dexMetaPath;
  }

  @Override
  public int execute(ExecutionContext context) throws InterruptedException {

    ProjectFilesystem projectFilesystem = context.getProjectFilesystem();

    try (ZipFile zf = new ZipFile(projectFilesystem.resolve(dexPath).toFile())) {
      ZipEntry classesDexEntry = zf.getEntry("classes.dex");
      if (classesDexEntry == null) {
        throw new RuntimeException("could not find classes.dex in jar");
      }

      long uncompressedSize = classesDexEntry.getSize();
      if (uncompressedSize == -1) {
        throw new RuntimeException("classes.dex size should be known");
      }

      projectFilesystem.writeContentsToPath(
          String.format(
              "jar:%s dex:%s",
              projectFilesystem.getFileSize(dexPath),
              uncompressedSize),
          dexMetaPath);

      return 0;
    } catch (IOException e) {
      context.logError(e, "There was an error in smart dexing step.");
      return 1;
    }
  }

  @Override
  public String getShortName() {
    return "dex_meta";
  }

  @Override
  public String getDescription(ExecutionContext context) {
    return String.format("dex_meta dexPath:%s dexMetaPath:%s", dexPath, dexMetaPath);
  }
}


text:
package surge

import (
	"fmt"
	"math"
	"math/rand"
	"strings"
	"time"
)

func assert(cond bool, args ...interface{}) {
	if !config.DEBUG {
		return
	}
	if cond {
		return
	}
	sincestartup := Now.Sub(time.Time{})
	var message = fmt.Sprintf("%-12.10v:%s", "assertion failed", sincestartup)
	if len(args) > 0 {
		message += ": "
		for i := 0; i < len(args); i++ {
			message += fmt.Sprintf("%#v ", args[i])
		}
	}
	log(message)
	flushLog()
	panic(message)
}

func calcAvgStd(vec []int) (int, float64, float64) {
	total := 0
	l := len(vec)
	for i := 0; i < l; i++ {
		total += vec[i]
	}
	avg := float64(total) / float64(l)

	std := float64(0)
	for i := 0; i < l; i++ {
		x := float64(vec[i]) - avg
		std += x * x
	}
	std = math.Sqrt(std / float64(l-1))
	return total, avg, std
}

//
// random globally-unique 64bit and its logging (short) counterpart
// FIXME: rewrite using crypto
//
func uqrandom64(multiplier int) (int64, int64) {
	uqid := rand.Int63n(time.Now().UTC().UnixNano() / 10007 * int64(multiplier))
	return uqid, uqrand(uqid)
}

func uqrand(uqid int64) int64 {
	return uqid & 0xffff
}

func clusterTripPlusRandom() time.Duration {
	trip := config.timeClusterTrip
	at := rand.Int63n(int64(trip)) + int64(trip) + 1
	return time.Duration(at)
}

func sizeToDuration(size int, sizeunits string, bw int64, bwunits string) time.Duration {
	var sizebits, bwbitss int64
	switch {
	case strings.HasPrefix(sizeunits, "b"):
		sizebits = int64(size)
	case strings.HasPrefix(sizeunits, "B"):
		sizebits = int64(size) * int64(8)
	case strings.HasPrefix(sizeunits, "k") || strings.HasPrefix(sizeunits, "K"):
		sizebits = int64(size) * int64(1024*8)
	case strings.HasPrefix(sizeunits, "m") || strings.HasPrefix(sizeunits, "M"):
		sizebits = int64(size) * int64(1024*1024*8)
	case strings.HasPrefix(sizeunits, "g") || strings.HasPrefix(sizeunits, "G"):
		sizebits = int64(size) * int64(1024*1024*1024*8)
	default:
		assert(false, "invalid sizeunits: "+sizeunits)
	}
	switch {
	case strings.HasPrefix(bwunits, "b"):
		bwbitss = bw
	case strings.HasPrefix(bwunits, "B"):
		bwbitss = bw * int64(8)
	case strings.HasPrefix(bwunits, "KB"):
		bwbitss = bw * int64(1024*8)
	case strings.HasPrefix(bwunits, "Kb"):
		bwbitss = bw * int64(1024)
	case strings.HasPrefix(bwunits, "MB"):
		bwbitss = bw * int64(1024*1024*8)
	case strings.HasPrefix(bwunits, "Mb"):
		bwbitss = bw * int64(1024*1024)
	case strings.HasPrefix(bwunits, "GB"):
		bwbitss = bw * int64(1024*1024*1024*8)
	case strings.HasPrefix(bwunits, "Gb"):
		bwbitss = bw * int64(1024*1024*1024)
	default:
		assert(false, "invalid bwunits: "+bwunits)
	}
	return time.Duration(sizebits) * time.Second / time.Duration(bwbitss)
}

func bytesToKMG(bytes int64) string {
	x := float64(bytes)
	switch {
	case bytes < 1024:
		return fmt.Sprintf("%dB", bytes)
	case bytes < 1024*1024:
		return fmt.Sprintf("%.2fKB", x/1024.0)
	case bytes < 1024*1024*1024:
		return fmt.Sprintf("%.2fMB", x/1024.0/1024.0)
	default:
		return fmt.Sprintf("%.2fGB", x/1024.0/1024.0/1024.0)
	}
}

func bytesMillisToKMGseconds(bytesms float64) string {
	x := bytesms * 1000.0
	switch {
	case x < 1024:
		return fmt.Sprintf("%.0fB/s", x)
	case x < 1024*1024:
		return fmt.Sprintf("%.2fKB/s", x/1024.0)
	case x < 1024*1024*1024:
		return fmt.Sprintf("%.2fMB/s", x/1024.0/1024.0)
	default:
		return fmt.Sprintf("%.2fGB/s", x/1024.0/1024.0/1024.0)
	}
}

func bytesMillisToMseconds(bytesms float64) string {
	x := bytesms * 1000.0 / 1024.0 / 1024.0
	return fmt.Sprintf("%.2f", x)
}

//
// given netDelivered time (in the future) when a new complete chunk
// will have been delivered, compute the required disk queue delay
//
func diskdelay(netDelivered time.Time, diskIOdone time.Time) time.Duration {
	elapsed := Now.Sub(netDelivered) // negative
	thenIOdone := diskIOdone.Add(elapsed)
	if !thenIOdone.After(netDelivered) {
		return 0
	}
	diff := thenIOdone.Sub(netDelivered)
	d1 := configStorage.dskdurationDataChunk * time.Duration(configStorage.maxDiskQueueChunks-1)
	if diff <= d1 {
		return 0
	}
	// time to wait until there are (maxDiskQueueChunks-1) chunks in the queue
	return diff - d1
}


text:
package com.linecorp.armeria.internal.grpc;

import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.reactivestreams.Subscription;

import com.linecorp.armeria.common.HttpData;
import com.linecorp.armeria.common.HttpHeaders;
import com.linecorp.armeria.common.HttpStatus;

import io.grpc.DecompressorRegistry;
import io.grpc.Status;

public class HttpStreamReaderTest {

    private static final HttpHeaders HEADERS = HttpHeaders.of(HttpStatus.OK);
    private static final HttpHeaders TRAILERS = HttpHeaders.of().set(GrpcHeaderNames.GRPC_STATUS, "2");
    private static final HttpData DATA = HttpData.ofUtf8("foobarbaz");

    @Rule
    public MockitoRule mocks = MockitoJUnit.rule();

    @Mock
    private TransportStatusListener transportStatusListener;

    @Mock
    private ArmeriaMessageDeframer deframer;

    @Mock
    private Subscription subscription;

    private HttpStreamReader reader;

    @Before
    public void setUp() {
        reader = new HttpStreamReader(DecompressorRegistry.getDefaultInstance(), deframer,
                                      transportStatusListener);
    }

    @Test
    public void subscribe_noServerRequests() {
        reader.onSubscribe(subscription);
        verifyZeroInteractions(subscription);
    }

    @Test
    public void subscribe_hasServerRequests_subscribeFirst() {
        when(deframer.isStalled()).thenReturn(true);
        reader.onSubscribe(subscription);
        verifyZeroInteractions(subscription);
        reader.request(1);
        verify(subscription).request(1);
        verifyNoMoreInteractions(subscription);
    }

    @Test
    public void subscribe_hasServerRequests_requestFirst() {
        when(deframer.isStalled()).thenReturn(true);
        reader.request(1);
        reader.onSubscribe(subscription);
        verify(subscription).request(1);
        verifyNoMoreInteractions(subscription);
    }

    @Test
    public void onHeaders() {
        reader.onSubscribe(subscription);
        verifyZeroInteractions(subscription);
        when(deframer.isStalled()).thenReturn(true);
        reader.onNext(HEADERS);
        verify(subscription).request(1);
    }

    @Test
    public void onTrailers() {
        reader.onSubscribe(subscription);
        when(deframer.isStalled()).thenReturn(true);
        reader.onNext(TRAILERS);
        verifyZeroInteractions(subscription);
    }

    @Test
    public void onMessage_noServerRequests() {
        reader.onSubscribe(subscription);
        reader.onNext(DATA);
        verify(deframer).deframe(DATA, false);
        verifyZeroInteractions(subscription);
    }

    @Test
    public void onMessage_hasServerRequests() {
        reader.onSubscribe(subscription);
        when(deframer.isStalled()).thenReturn(true);
        reader.onNext(DATA);
        verify(deframer).deframe(DATA, false);
        verify(subscription).request(1);
    }

    @Test
    public void onMessage_deframeError() {
        doThrow(Status.INTERNAL.asRuntimeException())
                .when(deframer).deframe(isA(HttpData.class), anyBoolean());
        reader.onSubscribe(subscription);
        reader.onNext(DATA);
        verify(deframer).deframe(DATA, false);
        verify(transportStatusListener).transportReportStatus(Status.INTERNAL);
        verify(deframer).close();
    }

    @Test
    public void onMessage_deframeError_errorListenerThrows() {
        doThrow(Status.INTERNAL.asRuntimeException())
                .when(deframer).deframe(isA(HttpData.class), anyBoolean());
        doThrow(new IllegalStateException())
                .when(transportStatusListener).transportReportStatus(isA(Status.class));
        reader.onSubscribe(subscription);
        assertThatThrownBy(() -> reader.onNext(DATA)).isInstanceOf(IllegalStateException.class);
        verify(deframer).close();
    }

    @Test
    public void clientDone() {
        reader.onComplete();
        verify(deframer).deframe(HttpData.EMPTY_DATA, true);
        verify(deframer).close();
    }

    @Test
    public void serverCancelled() {
        reader.onSubscribe(subscription);
        reader.cancel();
        verify(subscription).cancel();
    }

    @Test
    public void httpNotOk() {
        reader.onSubscribe(subscription);
        verifyZeroInteractions(subscription);
        reader.onNext(HttpHeaders.of(HttpStatus.UNAUTHORIZED));
        verifyZeroInteractions(subscription);
        verifyZeroInteractions(deframer);

        verify(transportStatusListener).transportReportStatus(
                argThat(s -> s.getCode().equals(Status.UNAUTHENTICATED.getCode())));
    }
}


text:
import pytest
from thefuck.rules.cargo_no_command import match, get_new_command
from thefuck.types import Command

no_such_subcommand_old = """No such subcommand

        Did you mean `build`?
"""

no_such_subcommand = """error: no such subcommand

\tDid you mean `build`?
"""

@pytest.mark.parametrize('command', [
    Command('cargo buid', no_such_subcommand_old),
    Command('cargo buils', no_such_subcommand)])
def test_match(command):
    assert match(command)

@pytest.mark.parametrize('command, new_command', [
    (Command('cargo buid', no_such_subcommand_old), 'cargo build'),
    (Command('cargo buils', no_such_subcommand), 'cargo build')])
def test_get_new_command(command, new_command):
    assert get_new_command(command) == new_command


text:
package ee.pdfarve.common.posorder;

import org.apache.commons.lang.builder.ReflectionToStringBuilder;

public class LocationPointWithText {

	private final int x, y;
	private String text;

	public LocationPointWithText(final int x, final int y, final String text) {
		this.x = x;
		this.y = y;
		this.text = text;
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}

	public int getX() {
		return x;
	}

	public int getY() {
		return y;
	}

	@Override
	public String toString() {
		return ReflectionToStringBuilder.toString(this);
	}

	@Override
	public boolean equals(Object other) {
		if (other instanceof LocationPointWithText) {
			LocationPointWithText comp = (LocationPointWithText)other;
			if (comp.text != null && comp.text.equals(this.text)) {
				return true;
			}
		}
		return super.equals(other);
	}

}


text:
import styled, { css } from './styledComponent';
import { getTextColor, getColorWithAlpha, getOpacity } from './utils/';

const Heading3 = styled({
  component: 'h3',
  style: css`
    font-size: ${props => props.theme.h3.fontSize};
    font-weight: ${props => props.theme.h3.fontWeight};
    line-height: ${props => props.theme.h3.lineHeight};
    color: ${props => getColorWithAlpha(getTextColor(props), getOpacity(props, 0.54))};
  `,
});

export default Heading3;


text:
using System;
using System.Web.Mvc;
using Orchard.DisplayManagement;
using Orchard.Events;
using Orchard.Localization;
using Orchard.Tags.Services;

namespace Orchard.Tags.Projections {
    public interface IFormProvider : IEventHandler {
        void Describe(dynamic context);
    }

    public class TagsFilterForms : IFormProvider {
        private readonly ITagService _tagService;
        protected dynamic Shape { get; set; }
        public Localizer T { get; set; }

        public TagsFilterForms(
            IShapeFactory shapeFactory,
            ITagService tagService) {
            _tagService = tagService;
            Shape = shapeFactory;
            T = NullLocalizer.Instance;
        }

        public void Describe(dynamic context) {
            Func<IShapeFactory, dynamic> form =
                shape => {

                    var f = Shape.Form(
                        Id: "SelectTags",
                        _Tags: Shape.SelectList(
                            Id: "tagids", Name: "TagIds",
                            Title: T("Tags"),
                            Description: T("Select some tags."),
                            Size: 10,
                            Multiple: true
                            )
                        );

                    foreach (var tag in _tagService.GetTags()) {
                        f._Tags.Add(new SelectListItem { Value = tag.Id.ToString(), Text = tag.TagName });
                    }

                    return f;
                };

            context.Form("SelectTags", form);

        }
    }
}


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

function _helperPluginUtils() {
  const data = require("@babel/helper-plugin-utils");

  _helperPluginUtils = function () {
    return data;
  };

  return data;
}

var _default = (0, _helperPluginUtils().declare)(api => {
  api.assertVersion(7);
  return {
    name: "syntax-optional-catch-binding",

    manipulateOptions(opts, parserOpts) {
      parserOpts.plugins.push("optionalCatchBinding");
    }

  };
});

exports.default = _default;


text:
export {ClassListComponent} from './ClassListComponent';
export {ClassItem} from './ClassItem';


text:
// Functions for extracting the size and data of individual icons in a .ico
// file

// .ico file format reference: http://msdn.microsoft.com/en-us/library/ms997538.aspx
// and http://en.wikipedia.org/wiki/ICO_(file_format)

import collectionutil = require('../base/collectionutil');

/*
C struct definitions:

typedef struct
{
   WORD           idReserved;   // Reserved (must be 0)
   WORD           idType;       // Resource Type (1 for icons)
   WORD           idCount;      // How many images?
   ICONDIRENTRY   idEntries[1]; // An entry for each image (idCount of 'em)
} ICONDIR, *LPICONDIR;

typedef struct
{
    BYTE        bWidth;          // Width, in pixels, of the image
    BYTE        bHeight;         // Height, in pixels, of the image
    BYTE        bColorCount;     // Number of colors in image (0 if >=8bpp)
    BYTE        bReserved;       // Reserved ( must be 0)
    WORD        wPlanes;         // Color Planes
    WORD        wBitCount;       // Bits per pixel
    DWORD       dwBytesInRes;    // How many bytes in this resource?
    DWORD       dwImageOffset;   // Where in the file is this image?
} ICONDIRENTRY, *LPICONDIRENTRY;

*/

export interface Icon {
    /** The width of the icon in pixels */
    width: number;
    /** The height of the icon in pixels */
    height: number;
    /** The icon's data as a BMP or PNG file */
    data: Uint8Array;
}

// creates a BITMAPFILEHEADER struct for data from a .bmp file
// see http://en.wikipedia.org/wiki/BMP_file_format#Bitmap_file_header
//
// 'data' is the contents of a bitmap file, excluding the BITMAPFILEHEADER struct
// at the beginning
function bitmapFileHeader(data: Uint8Array): Uint8Array {
    var srcDataView = new DataView(data.buffer);
    var biSize = srcDataView.getUint32(
        data.byteOffset,
        true /* little-endian */
    );

    var HEADER_SIZE = 14;
    var header = new Uint8Array(HEADER_SIZE);
    var headerDataView = new DataView(header.buffer);

    // 'BM'
    headerDataView.setUint8(0, 0x42);
    headerDataView.setUint8(1, 0x4d);

    headerDataView.setUint32(
        2,
        data.byteLength + HEADER_SIZE,
        true /* little-endian */
    );

    // offset of bitmap data from start of file
    headerDataView.setUint32(
        10,
        HEADER_SIZE + biSize,
        true /* little-endian */
    );

    return header;
}

/** Returns true if the buffer contains a .ico file. */
export function isIco(data: Uint8Array): boolean {
    return (
        data.length > 4 &&
        data[0] === 0 &&
        data[1] === 0 &&
        data[2] === 1 &&
        data[3] === 0
    );
}

var ICON_DIR_SIZE = 6;
var ICON_DIR_ENTRY_SIZE = 16;

function readNthIcon(
    leData: collectionutil.LittleEndianDataView,
    index: number
): Icon {
    // read icon entry header
    var offset = ICON_DIR_SIZE + index * ICON_DIR_ENTRY_SIZE;

    var width = leData.getUint8(offset);
    var height = leData.getUint8(offset + 1);
    var imageDataLength = leData.getUint32(offset + 8);
    var imageDataOffset = leData.getUint32(offset + 12);

    if (width == 0 || height == 0) {
        throw new Error(`Invalid bitmap size (${width}x${height})`);
    }
    if (imageDataOffset + imageDataLength > leData.byteLength) {
        throw new Error(
            `Invalid bitmap data offset (${imageDataOffset}..${imageDataOffset +
                imageDataLength} of ${leData.byteLength})`
        );
    }

    // read bitmap data -
    // the bitmap data format is the same as a .bmp file except:
    //
    // 1) The BITMAPFILEHEADER struct is not present
    // 2) Following the normal bitmap data is a 1bpp mask image
    //    to be AND-ed with the destination before XOR-ing
    //    the bitmap color data
    // 3) The image height is given as the combined height of the
    //    color data and the mask - so 2x the height of the bitmap
    var sourceData = new Uint8Array(
        leData.buffer,
        imageDataOffset,
        imageDataLength
    );

    // check BITMAPFILEINFO header for the bitmap
    // see http://msdn.microsoft.com/en-gb/library/windows/desktop/dd183376%28v=vs.85%29.aspx
    var biSize = leData.getUint32(imageDataOffset);
    if (biSize != 40 /* sizeof(BITMAPINFOHEADER) */) {
        throw new Error(`Unsupported bitmap format. Header size ${biSize}`);
    }

    var biHeight = leData.getInt32(imageDataOffset + 8);
    if (biHeight != height * 2) {
        throw new Error(`Unexpected bitmap height (${biHeight}px)`);
    }

    var BI_RGB = 0;
    var biCompression = leData.getUint32(imageDataOffset + 16);
    if (biCompression != BI_RGB) {
        throw new Error(`Unsupported bitmap compression type ${biCompression}`);
    }

    var bmpFileHeader = bitmapFileHeader(sourceData);
    var imageData = new Uint8Array(bmpFileHeader.byteLength + imageDataLength);
    imageData.set(bmpFileHeader);
    imageData.set(sourceData, bmpFileHeader.byteLength);

    var leImageData = new collectionutil.LittleEndianDataView(
        new DataView(imageData.buffer)
    );

    // adjust the image height. In the original header it is the combined
    // height of the mask and the color data. In the exported BMP-format
    // data, the mask is not present
    leImageData.setInt32(bmpFileHeader.byteLength + 8, height);

    // set image data size to 0, it is inferred from the image size
    // and color depth
    leImageData.setUint32(bmpFileHeader.byteLength + 34, 0);

    return {
        width: width,
        height: height,
        data: imageData,
    };
}

/** Reads a .ico file containing one or more icons and returns
 * an array of the icons found.
 */
export function read(data: DataView): Icon[] {
    var leData = new collectionutil.LittleEndianDataView(data);

    if (leData.getUint16(0) !== 0 || leData.getUint16(2) !== 1) {
        throw new TypeError('Not a .ico file');
    }

    var icons: Icon[] = [];
    var imageCount = leData.getUint16(4);

    for (var i = 0; i < imageCount; i++) {
        try {
            icons.push(readNthIcon(leData, i));
        } catch (ex) {
            console.log('Skipping invalid icon: ', ex.message);
        }
    }

    return icons;
}


text:
layout: home
excerpt: "Jitendra Vyas. Digital UI Designer and Front-end Developer"
tags:
image:
  feature: sample-image-1.jpg
  credit: WeGraphics
  creditlink: http://wegraphics.net/downloads/free-ultimate-blurred-background-pack/
---


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

    <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=9"/>
    <meta name="generator" content="Doxygen 1.8.15"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <title>Generic Image Library: homogeneous_color_base< Element, Layout, 3 > Struct Template Reference</title>
    <link href="tabs.css" rel="stylesheet" type="text/css"/>

    <link href="doxygen.css" rel="stylesheet" type="text/css" />
    <link href="doxygen-boost.css" rel="stylesheet" type="text/css"/>

boost

gil

detail

homogeneous_color_base< Element, Layout, 3 >

Public Types |
Public Member Functions |
List of all members

homogeneous_color_base< Element, Layout, 3 > Struct Template Reference
ColorBase » Models » detail::homogeneous_color_base

A homogeneous color base holding three color elements. Models HomogeneousColorBaseConcept or HomogeneousColorBaseValueConcept.
 More...

#include <color_base.hpp>

Public Types

using 	layout_t = Layout

Public Member Functions

 	homogeneous_color_base (Element v)

 	homogeneous_color_base (Element v0, Element v1, Element v2)

template<typename E2 , typename L2 >

 	homogeneous_color_base (homogeneous_color_base< E2, L2, 3 > const &c)

template<typename E2 , typename L2 >

 	homogeneous_color_base (homogeneous_color_base< E2, L2, 3 > &c)

template<typename P >

 	homogeneous_color_base (P *p, bool)

template<typename Ptr >

 	homogeneous_color_base (Ptr const &ptr, std::ptrdiff_t diff)

template<typename Ref >

Ref 	deref () const

auto 	at (std::integral_constant< int, 0 >) -> typename element_reference_type< homogeneous_color_base >::type

auto 	at (std::integral_constant< int, 0 >) const -> typename element_const_reference_type< homogeneous_color_base >::type

auto 	at (std::integral_constant< int, 1 >) -> typename element_reference_type< homogeneous_color_base >::type

auto 	at (std::integral_constant< int, 1 >) const -> typename element_const_reference_type< homogeneous_color_base >::type

auto 	at (std::integral_constant< int, 2 >) -> typename element_reference_type< homogeneous_color_base >::type

auto 	at (std::integral_constant< int, 2 >) const -> typename element_const_reference_type< homogeneous_color_base >::type

Element 	at_c_dynamic (std::size_t i) const

Detailed Description

template<typename Element, typename Layout>

struct boost::gil::detail::homogeneous_color_base< Element, Layout, 3 >

A homogeneous color base holding three color elements. Models HomogeneousColorBaseConcept or HomogeneousColorBaseValueConcept.

The documentation for this struct was generated from the following file:

color_base.hpp

     <address class="footer">

        Generated by  doxygen 1.8.15

    </address>


text:
class EvidenceItemBrowseRowPresenter
  def initialize(evidence_item)
    @evidence_item = evidence_item
  end

  def as_json
    {
      id: @evidence_item.id,
      description: @evidence_item.description,
      gene_name: @evidence_item.gene_name,
      gene_id: @evidence_item.gene_id,
      gene_entrez_id: @evidence_item.gene_entrez_id,
      disease: @evidence_item.disease_name,
      drugs: @evidence_item.drug_names,
      drug_interaction_type: @evidence_item.drug_interaction_type,
      variant_name: @evidence_item.variant_name,
      variant_id: @evidence_item.variant_id,
      evidence_level: @evidence_item.evidence_level,
      evidence_type: @evidence_item.evidence_type,
      evidence_direction: @evidence_item.evidence_direction,
      clinical_significance: @evidence_item.clinical_significance,
      variant_origin: @evidence_item.variant_origin,
      phenotypes: @evidence_item.phenotype_hpo_classes,
      rating: @evidence_item.rating,
      source_title: @evidence_item.source_title,
      source_citation: @evidence_item.source_citation,
      status: @evidence_item.status,
      open_change_count: @evidence_item.open_changes.size,
      flagged: @evidence_item.flagged
    }
  end
end


text:
namespace mozc {
class EngineInterface;
#ifndef MOZC_DISABLE_SESSION_WATCHDOG
class SessionWatchDog;
#else  // MOZC_DISABLE_SESSION_WATCHDOG
// Session watch dog is not aviable from android mozc for now.
// TODO(kkojima): Remove this guard after
// enabling session watch dog for android.
#endif  // MOZC_DISABLE_SESSION_WATCHDOG
class Stopwatch;

namespace commands {
class Command;
class Request;
}  // namespace commands

namespace session {
class SessionInterface;
class SessionObserverHandler;
class SessionObserverInterface;
}  // namespace session

namespace user_dictionary {
class UserDictionarySessionHandler;
}  // namespace user_dictionary

class SessionHandler : public SessionHandlerInterface {
 public:
  // This class doesn't take an ownership of |engine|.
  explicit SessionHandler(EngineInterface *engine);
  virtual ~SessionHandler();

  // Returns true if SessionHandle is available.
  virtual bool IsAvailable() const;

  virtual bool EvalCommand(commands::Command *command);

  // Starts watch dog timer to cleanup sessions.
  virtual bool StartWatchDog();

  // NewSession returns new Sessoin.
  // Client needs to delete it properly
  session::SessionInterface *NewSession();

  virtual void AddObserver(session::SessionObserverInterface *observer);

 private:
  FRIEND_TEST(SessionHandlerTest, StorageTest);

  typedef mozc::storage::LRUCache<SessionID, session::SessionInterface *>
      SessionMap;
  typedef SessionMap::Element SessionElement;

  // Reload settings which are managed by SessionHandler
  void ReloadSession();
  // Reload the configurations on the current sessions.
  void ReloadConfig();

  bool CreateSession(commands::Command *command);
  bool DeleteSession(commands::Command *command);
  bool TestSendKey(commands::Command *command);
  bool SendKey(commands::Command *command);
  bool SendCommand(commands::Command *command);
  bool SyncData(commands::Command *command);
  bool ClearUserHistory(commands::Command *command);
  bool ClearUserPrediction(commands::Command *command);
  bool ClearUnusedUserPrediction(commands::Command *command);
  bool Shutdown(commands::Command *command);
  bool Reload(commands::Command *command);
  bool GetStoredConfig(commands::Command *command);
  bool SetStoredConfig(commands::Command *command);
  bool SetImposedConfig(commands::Command *command);
  bool SetRequest(commands::Command *command);

  bool InsertToStorage(commands::Command *command);
  bool ReadAllFromStorage(commands::Command *command);
  bool ClearStorage(commands::Command *command);
  bool Cleanup(commands::Command *command);
  bool SendUserDictionaryCommand(commands::Command *command);
  bool NoOperation(commands::Command *command);

  SessionID CreateNewSessionID();
  bool DeleteSessionID(SessionID id);

  scoped_ptr<SessionMap> session_map_;
#ifndef MOZC_DISABLE_SESSION_WATCHDOG
  scoped_ptr<SessionWatchDog> session_watch_dog_;
#else  // MOZC_DISABLE_SESSION_WATCHDOG
  // Session watch dog is not aviable from android mozc and nacl mozc for now.
  // TODO(kkojima): Remove this guard after
  // enabling session watch dog for android.
#endif  // MOZC_DISABLE_SESSION_WATCHDOG
  bool is_available_;
  uint32 max_session_size_;
  uint64 last_session_empty_time_;
  uint64 last_cleanup_time_;
  uint64 last_create_session_time_;

  EngineInterface *engine_;
  scoped_ptr<session::SessionObserverHandler> observer_handler_;
  scoped_ptr<Stopwatch> stopwatch_;
  scoped_ptr<user_dictionary::UserDictionarySessionHandler>
      user_dictionary_session_handler_;
  scoped_ptr<composer::TableManager> table_manager_;
  scoped_ptr<commands::Request> request_;

  DISALLOW_COPY_AND_ASSIGN(SessionHandler);
};

}  // namespace mozc
#endif  // MOZC_SESSION_SESSION_HANDLER_H_


text:
@interface sndfileIOS : NSObject

@end


text:
using System;

namespace hello
{
    class Class1
    {
        private static TestUtil.TestLog testLog;
        static Class1()
        {
            // Create test writer object to hold expected output
            System.IO.StringWriter expectedOut = new System.IO.StringWriter();

            // Write expected output to string writer object
            expectedOut.WriteLine("in finally");
            expectedOut.WriteLine("done");

            // Create and initialize test log object
            testLog = new TestUtil.TestLog(expectedOut);
        }

        static public int Main(string[] args)
        {
            //Start recording
            testLog.StartRecording();
            try
            {
                try
                {
                    if (args.Length == 0) goto done;
                    Console.WriteLine("in try");
                }
                finally
                {
                    Console.WriteLine("in finally");
                }
                Console.WriteLine("after finally");
            }
            catch
            {
                Console.WriteLine("caught in main");
            }
            done:
            Console.WriteLine("done");
            // stop recoding
            testLog.StopRecording();

            return testLog.VerifyOutput();
        }

    }
}


text:
'use strict';

angular.module('marvelApp.browse', [])

.controller('BrowseCtrl', [function() {

}]);


text:
/*
 * Generated by asn1c-0.9.29 (http://lionet.info/asn1c)
 * From ASN.1 module "IEEE1609dot2BaseTypes"
 * 	found in "1609dot2-base-types.asn"
 * 	`asn1c -gen-OER`
 */

#ifndef	_SequenceOfPsidSspRange_H_
#define	_SequenceOfPsidSspRange_H_

#include <asn_application.h>

/* Including external dependencies */
#include <asn_SEQUENCE_OF.h>
#include <constr_SEQUENCE_OF.h>

#ifdef __cplusplus
extern "C" {
#endif

/* Forward declarations */
struct PsidSspRange;

/* SequenceOfPsidSspRange */
typedef struct SequenceOfPsidSspRange {
	A_SEQUENCE_OF(struct PsidSspRange) list;

	/* Context for parsing across buffer boundaries */
	asn_struct_ctx_t _asn_ctx;
} SequenceOfPsidSspRange_t;

/* Implementation */
extern asn_TYPE_descriptor_t asn_DEF_SequenceOfPsidSspRange;
extern asn_SET_OF_specifics_t asn_SPC_SequenceOfPsidSspRange_specs_1;
extern asn_TYPE_member_t asn_MBR_SequenceOfPsidSspRange_1[1];

#ifdef __cplusplus
}
#endif

/* Referred external types */
#include "PsidSspRange.h"

#endif	/* _SequenceOfPsidSspRange_H_ */
#include <asn_internal.h>


text:
/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/mcbist/sim.H $  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2017                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file mcbist/sim.H
/// @brief MCBIST/memdiags functions for when we're in simulation mode
///
// *HWP HWP Owner: Stephen Glancy <sglancy@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: FSP:HB

#ifndef _MSS_MCBIST_SIM_H_
#define _MSS_MCBIST_SIM_H_

#include <fapi2.H>

namespace mss
{

namespace mcbist
{

namespace sim
{

///
/// @brief Perform a sim version of initializing memory
/// @param T a fapi2::TargetType
/// @param[in] i_target
/// @param[in] i_pattern an index representing a pattern to use to initize memory (defaults to 0)
/// @return FAPI2_RC_SUCCESS iff ok
///
template< fapi2::TargetType T >
fapi2::ReturnCode sf_init( const fapi2::Target<T>& i_target, const uint64_t i_pattern );

} // ns sim
} // ns mcbist
} // ns mss
#endif


text:
package uk.nhs.careconnect.ri.database.entity.conceptMap;

import javax.persistence.*;

import uk.nhs.careconnect.ri.database.entity.codeSystem.ConceptEntity;

import java.util.ArrayList;
import java.util.List;

@Entity
@Table(name="ConceptMapGroup", uniqueConstraints= @UniqueConstraint(name="PK_CONCEPT_MAP_GROUP", columnNames={"CONCEPT_MAP_GROUP_ID"})
		)
public class ConceptMapGroup  {

	public ConceptMapGroup() {

	}

	public ConceptMapGroup(ConceptMapEntity conceptmapEntity) {
		this.conceptMap = conceptmapEntity;
	}

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name= "CONCEPT_MAP_GROUP_ID")
	private Long groupId;

	@ManyToOne(fetch = FetchType.LAZY)
	@JoinColumn (name = "CONCEPT_MAP_ID",foreignKey= @ForeignKey(name="FK_CONCEPT_MAP_CONCEPT_MAP_GROUP"))
	private ConceptMapEntity conceptMap;

	@OneToMany(mappedBy="conceptMapGroup", targetEntity= ConceptMapGroupElement.class)
	private List<ConceptMapGroupElement> elements;

	@Column(name = "SOURCE")
	private String source;

	@Column(name = "SOURCE_VERSION")
	private String sourceVersion;

	@Column(name = "TARGET")
	private String target;

	@Column(name = "TARGET_VERSION")
	private String targetVersion;

	@ManyToOne(fetch = FetchType.LAZY)
	@JoinColumn(name="UNMAPPED_MODE_CONCEPT_ID")
	private ConceptEntity unmappedMode;

	@ManyToOne(fetch = FetchType.LAZY)
	@JoinColumn(name="UNMAPPED_CODE_CONCEPT_ID")
	private ConceptEntity unmappedCode;

	@Column(name = "UNMAPPED_DISPLAY")
	private String unmappedDisplay;

	@Column(name = "UNMAPPED_URL")
	private String unmappedUrl;

	public Long getGroupId() {
		return groupId;
	}

	public void setGroupId(Long groupId) {
		this.groupId = groupId;
	}

	public ConceptMapEntity getConceptMap() {
		return conceptMap;
	}

	public void setConceptMap(ConceptMapEntity conceptMap) {
		this.conceptMap = conceptMap;
	}

	public List<ConceptMapGroupElement> getElements() {
		if (elements == null) {
			this.elements = new ArrayList<>();
		}

		return elements;
	}

	public void setElements(List<ConceptMapGroupElement> elements) {
		this.elements = elements;
	}

	public String getSource() {
		return source;
	}

	public void setSource(String source) {
		this.source = source;
	}

	public String getSourceVersion() {
		return sourceVersion;
	}

	public void setSourceVersion(String sourceVersion) {
		this.sourceVersion = sourceVersion;
	}

	public String getTarget() {
		return target;
	}

	public void setTarget(String target) {
		this.target = target;
	}

	public String getTargetVersion() {
		return targetVersion;
	}

	public void setTargetVersion(String targetVersion) {
		this.targetVersion = targetVersion;
	}

	public ConceptEntity getUnmappedMode() {
		return unmappedMode;
	}

	public void setUnmappedMode(ConceptEntity unmappedMode) {
		this.unmappedMode = unmappedMode;
	}

	public ConceptEntity getUnmappedCode() {
		return unmappedCode;
	}

	public void setUnmappedCode(ConceptEntity unmappedCode) {
		this.unmappedCode = unmappedCode;
	}

	public String getUnmappedDisplay() {
		return unmappedDisplay;
	}

	public void setUnmappedDisplay(String unmappedDisplay) {
		this.unmappedDisplay = unmappedDisplay;
	}

	public String getUnmappedUrl() {
		return unmappedUrl;
	}

	public void setUnmappedUrl(String unmappedUrl) {
		this.unmappedUrl = unmappedUrl;
	}
}


text:
//
//  WeexTabbarController.h
//  mecymapweex
//
//  Created by zhangshupeng on 2016/11/13.
//  Copyright © 2016年 sym. All rights reserved.
//

#import "SPTabbarController.h"
#import "WeexViewController.h"
@interface WeexTabbarController : SPTabbarController

/**
 {
    jspath:path, //js 文件路径
    img:img,     //图片
    simg:simg,   //选中的图片
    title:title, //标题

 }
 */
@property (nonatomic, strong) NSArray *items;

@end


text:
<?php
namespace Crossjoin\Browscap\Updater;

class Local
extends AbstractUpdater
{
    /**
     * Name of the update method, used in the user agent for the request,
     * for browscap download statistics. Has to be overwritten by the
     * extending class.
     *
     * @var string
     */
    protected $updateMethod = 'local';

    public function __construct($options = null)
    {
        parent::__construct($options);

        // add additional options
        $this->options['LocalFile'] = null;
    }

    /**
     * Gets the current browscap version (time stamp)
     *
     * @return int
     * @throws \Exception
     */
    public function getBrowscapVersion()
    {
        $file = $this->getOption('LocalFile');
        if ($file === null) {
            throw new \Exception("Option 'LocalFile' not set.");
        }
        if (!is_readable($file)) {
            throw new \Exception("File '$file' set in option 'LocalFile' is not readable.");
        }
        return (int)filemtime($file);
    }

    /**
     * Gets the current browscap version number (if possible for the source)
     *
     * @return int|null
     */
    public function getBrowscapVersionNumber()
    {
        return null;
    }

    /**
     * Gets the browscap data of the used source type
     *
     * @return string|boolean
     * @throws \Exception
     */
    public function getBrowscapSource()
    {
        $file = $this->getOption('LocalFile');
        if ($file === null) {
            throw new \Exception("Option 'LocalFile' not set.");
        }
        if (!is_readable($file)) {
            throw new \Exception("File '$file' set in option 'LocalFile' is not readable.");
        }
        return file_get_contents($file);
    }
}


text:
<?php

if ( ! class_exists( 'WpSmushS3' ) ) {

	class WpSmushS3 {

		private $setup_notice = '';
		private $message_type = 'error';

		function __construct() {
			$this->init();

			//Hook at the end of setting row to output a error div
			add_action( 'smush_setting_column_right_end', array( $this, 's3_setup_message' ) );

		}

		function init() {

			global $WpSmush;

			//Filters the setting variable to add S3 setting title and description
			add_filter( 'wp_smush_settings', array( $this, 'register' ), 6 );

			//Filters the setting variable to add S3 setting in premium features
			add_filter( 'wp_smush_pro_settings', array( $this, 'add_setting' ), 6 );

			//return if not a pro user
			if ( ! $WpSmush->validate_install() ) {
				return;
			}

			//Check if the file exists for the given path and download
			add_action( 'smush_file_exists', array( $this, 'maybe_download_file' ), 10, 3 );

			//Check if the backup file exists
			add_filter( 'smush_backup_exists', array( $this, 'backup_exists_on_s3' ), 10, 3 );

		}

		/**
		 * Filters the setting variable to add S3 setting title and description
		 *
		 * @param $settings
		 *
		 * @return mixed
		 */
		function register( $settings ) {
			$plugin_url     = esc_url( "https://wordpress.org/plugins/amazon-s3-and-cloudfront/" );
			$settings['s3'] = array(
				'label'       => esc_html__( 'Enable Amazon S3 support', 'wp-smushit' ),
				'short_label' => esc_html__( 'Amazon S3', 'wp-smushit' ),
				'desc'        => sprintf( esc_html__( "Storing your image on S3 buckets using %sWP Offload S3%s? Smush can detect and smush those assets for you, including when you're removing files from your host server.", 'wp-smushit' ), "", "", "", "" )
			);

			return $settings;
		}

		/**
		 * Append S3 in pro feature list
		 *
		 * @param $pro_settings
		 *
		 * @return array
		 */
		function add_setting( $pro_settings ) {

			if ( ! isset( $pro_settings['s3'] ) ) {
				$pro_settings[] = 's3';
			}

			return $pro_settings;
		}

		/**
		 * Prints the message for S3 setup
		 *
		 * @param $setting_key
		 *
		 * @return null
		 */
		function s3_setup_message( $setting_key ) {

			//Return if not S3
			if( 's3' != $setting_key ) {
				return;
			}

			global $as3cf, $WpSmush, $wpsmush_settings;
			$show_error = false;

			//If S3 integration is not enabled, return
			$setting_val = $WpSmush->validate_install() ? $wpsmush_settings->settings['s3'] : 0;

			if ( ! $setting_val ) {
				return;
			}

			//Check if plugin is setup or not
			//In case for some reason, we couldn't find the function
			if ( ! is_object( $as3cf ) || ! method_exists( $as3cf, 'is_plugin_setup' ) ) {
				$show_error         = true;
				$support_url        = esc_url( "https://premium.wpmudev.org/contact" );
				$this->setup_notice = sprintf( esc_html__( "We are having trouble interacting with WP Offload S3, make sure the plugin is activated. Or you can %sreport a bug%s.", "wp-smushit" ), '', '' );
			}

			//Plugin is not setup, or some information is missing
			if ( ! $as3cf->is_plugin_setup() ) {
				$show_error         = true;
				$configure_url      = $as3cf->get_plugin_page_url();
				$this->setup_notice = sprintf( esc_html__( "It seems you haven't finished setting up WP Offload S3 yet. %sConfigure%s it now to enable Amazon S3 support.", "wp-smushit" ), "", "" );
			} else {

				$this->message_type = 'notice';
				$this->setup_notice = esc_html__( "Amazon S3 support is active.", "wp-smushit" );

			}

			//Return Early if we don't need to do anything
			if ( empty( $this->setup_notice ) ) {
				return;
			}

			$class      = 'error' == $this->message_type ? ' smush-s3-setup-error' : ' smush-s3-setup-message';
			$icon_class = 'error' == $this->message_type ? ' icon-fi-warning-alert' : ' icon-fi-check-tick';
			echo "

$this->setup_notice

";
		}

		/**
		 * Error message to show when S3 support is required.
		 *
		 * Show a error message to admins, if they need to enable S3 support. If "remove files from
		 * server" option is enabled in WP Offload S3 plugin, we need WP Smush Pro to enable S3 support.
		 *
		 * @return mixed
		 */
		function s3_support_required_notice() {

			global $wpsmushit_admin, $wpsmush_settings;

			// Do not display it for other users.
			// Do not display on network screens, if networkwide option is disabled.
			if ( ! current_user_can( 'manage_options' ) || ( is_network_admin() && ! $wpsmush_settings->settings['networkwide'] ) ) {
				return true;
			}

			// Do not display the notice on Bulk Smush Screen.
			global $current_screen;
			if ( ! empty( $current_screen->base ) && 'media_page_wp-smush-bulk' != $current_screen->base && 'gallery_page_wp-smush-nextgen-bulk' != $current_screen->base && 'settings_page_wp-smush-network' != $current_screen->base ) {
				return true;
			}

			// If already dismissed, do not show.
			if ( 1 == get_site_option( 'wp-smush-hide_s3support_alert' ) ) {
				return true;
			}

			// Return early, if support is not required.
			if ( ! $this->s3_support_required() ) {
				return true;
			}

			wp_enqueue_script( 'wp-smushit-notice-js' );
			// Settings link.
			$settings_link = is_multisite() && $wpsmush_settings->settings['networkwide'] ? network_admin_url( 'settings.php?page=wp-smush' ) : admin_url( 'upload.php?page=wp-smush-bulk' );

			if ( $wpsmushit_admin->validate_install() ) {
				// If premium user, but S3 support is not enabled.
				$message = sprintf( __( "We can see you have WP Offload S3 installed with the Remove Files From Server option activated. If you want to optimize your S3 images you'll need to enable the Amazon S3 Support feature in Smush's settings.", 'wp-smushit' ), $settings_link );
			} else {
				// If not a premium user.
				$message = sprintf( __( "We can see you have WP Offload S3 installed with the Remove Files From Server option activated. If you want to optimize your S3 images you'll need to upgrade to Smush Pro", 'wp-smushit' ), esc_url( 'https://premium.wpmudev.org/project/wp-smush-pro' ) );
			}

			echo '
' . $message . '
';
		}

		/**
		 * Check if S3 support is required for Smush.
		 *
		 * @return bool
		 */
		function s3_support_required() {

			global $wpsmush_settings, $wpsmushit_admin, $as3cf;

			// Check if S3 offload plugin is active and delete file from server option is enabled.
			if ( ! is_object( $as3cf ) || ! method_exists( $as3cf, 'get_setting' ) || ! $as3cf->get_setting( 'remove-local-file' ) ) {
				return false;
			}

			// If not Pro user or S3 support is disabled.
			return ( ! $wpsmushit_admin->validate_install() || ! $wpsmush_settings->settings['s3'] );
		}

		/**
		 * Checks if the given attachment is on S3 or not, Returns S3 URL or WP Error
		 *
		 * @param $attachment_id
		 *
		 * @return bool|false|string
		 *
		 */
		function is_image_on_s3( $attachment_id = '' ) {
			global $as3cf;
			if ( empty( $attachment_id ) ) {
				return false;
			}

			//If we only have the attachment id
			$full_url = $as3cf->is_attachment_served_by_s3( $attachment_id );
			//If the filepath contains S3, get the s3 URL for the file
			if ( ! empty( $full_url ) ) {
				$full_url = $as3cf->get_attachment_url( $attachment_id );
			} else {
				$full_url = false;
			}

			return $full_url;

		}

		/**
		 * Download a specified file to local server with respect to provided attachment id
		 *  and/or Attachment path
		 *
		 * @param $attachment_id
		 *
		 * @param array $size_details
		 *
		 * @param string $uf_file_path
		 *
		 * @return string|bool Returns file path or false
		 *
		 */
		function download_file( $attachment_id, $size_details = array(), $uf_file_path = '' ) {
			global $WpSmush, $wpsmush_settings;
			if ( empty( $attachment_id ) || ! $wpsmush_settings->settings['s3'] || ! $WpSmush->validate_install() ) {
				return false;
			}

			global $as3cf;
			$renamed = $s3_object = $s3_url = $file = false;

			//If file path wasn't specified in argument
			$uf_file_path = empty( $uf_file_path ) ? get_attached_file( $attachment_id, true ) : $uf_file_path;

			//If we have plugin method available, us that otherwise check it ourselves
			if ( method_exists( $as3cf, 'is_attachment_served_by_s3' ) ) {
				$s3_object        = $as3cf->is_attachment_served_by_s3( $attachment_id );
				$size_prefix      = dirname( $s3_object['key'] );
				$size_file_prefix = ( '.' === $size_prefix ) ? '' : $size_prefix . '/';
				if ( ! empty( $size_details ) && is_array( $size_details ) ) {
					$s3_object['key'] = path_join( $size_file_prefix, $size_details['file'] );
				} elseif ( ! empty( $uf_file_path ) ) {
					//Get the File path using basename for given attachment path
					$s3_object['key'] = path_join( $size_file_prefix, wp_basename( $uf_file_path ) );
				}

				//Try to download the attachment
				if ( $s3_object && is_object( $as3cf->plugin_compat ) && method_exists( $as3cf->plugin_compat, 'copy_s3_file_to_server' ) ) {
					//Download file
					$file = $as3cf->plugin_compat->copy_s3_file_to_server( $s3_object, $uf_file_path );
				}

				if ( $file ) {
					return $file;
				}
			}

			//If we don't have the file, Try it the basic way
			if ( ! $file ) {
				$s3_url = $this->is_image_on_s3( $attachment_id );

				//If we couldn't get the image URL, return false
				if ( is_wp_error( $s3_url ) || empty( $s3_url ) || ! $s3_url ) {
					return false;
				}

				if ( ! empty( $size_details ) ) {
					//If size details are available, Update the URL to get the image for the specified size
					$s3_url = str_replace( wp_basename( $s3_url ), $size_details['file'], $s3_url );
				} elseif ( ! empty( $uf_file_path ) ) {
					//Get the File path using basename for given attachment path
					$s3_url = str_replace( wp_basename( $s3_url ), wp_basename( $uf_file_path ), $s3_url );
				}

				//Download the file
				$temp_file = download_url( $s3_url );
				if ( ! is_wp_error( $temp_file ) ) {
					$renamed = @copy( $temp_file, $uf_file_path );
					unlink( $temp_file );
				}

				//If we were able to successfully rename the file, return file path
				if ( $renamed ) {

					return $uf_file_path;
				}
			}

			return false;
		}

		/**
		 * Check if file exists for the given path
		 *
		 * @param string $attachment_id
		 * @param string $file_path
		 *
		 * @return bool
		 */
		function does_image_exists( $attachment_id = '', $file_path = '' ) {
			global $as3cf;
			if ( empty( $attachment_id ) || empty( $file_path ) ) {
				return false;
			}
			//Return if method doesn't exists
			if ( ! method_exists( $as3cf, 'is_attachment_served_by_s3' ) ) {
				error_log( "Couldn't find method is_attachment_served_by_s3." );

				return false;
			}
			//Get s3 object for the file
			$s3_object = $as3cf->is_attachment_served_by_s3( $attachment_id );

			$size_prefix      = dirname( $s3_object['key'] );
			$size_file_prefix = ( '.' === $size_prefix ) ? '' : $size_prefix . '/';

			//Get the File path using basename for given attachment path
			$s3_object['key'] = path_join( $size_file_prefix, wp_basename( $file_path ) );

			//Get bucket details
			$bucket = $as3cf->get_setting( 'bucket' );
			$region = $as3cf->get_setting( 'region' );

			if ( is_wp_error( $region ) ) {
				return false;
			}

			$s3client = $as3cf->get_s3client( $region );

			$file_exists = $s3client->doesObjectExist( $bucket, $s3_object['key'] );

			return $file_exists;
		}

		/**
		 * Check if the file is served by S3 and download the file for given path
		 *
		 * @param string $file_path Full file path
		 * @param string $attachment_id
		 * @param array $size_details Array of width and height for the image
		 *
		 * @return bool|string False/ File Path
		 */
		function maybe_download_file( $file_path = '', $attachment_id = '', $size_details = array() ) {
			if ( empty( $file_path ) || empty( $attachment_id ) ) {
				return false;
			}
			//Download if file not exists and served by S3
			if ( ! file_exists( $file_path ) && $this->is_image_on_s3( $attachment_id ) ) {
				return $this->download_file( $attachment_id, $size_details, $file_path );
			}

			return false;
		}

		/**
		 * Checks if we've backup on S3 for the given attachment id and backup path
		 *
		 * @param string $attachment_id
		 * @param string $backup_path
		 *
		 * @return bool
		 */
		function backup_exists_on_s3( $exists, $attachment_id = '', $backup_path = '' ) {
			//If the file is on S3, Check if backup image object exists
			if ( $this->is_image_on_s3( $attachment_id ) ) {
				return $this->does_image_exists( $attachment_id, $backup_path );
			}

			return $exists;
		}
	}

	global $wpsmush_s3;
	$wpsmush_s3 = new WpSmushS3();

}

if ( class_exists( 'AS3CF_Plugin_Compatibility' ) && ! class_exists( 'wp_smush_s3_compat' ) ) {
	class wp_smush_s3_compat extends AS3CF_Plugin_Compatibility {

		function __construct() {
			$this->init();
		}

		function init() {
			//Plugin Compatibility with Amazon S3
			add_filter( 'as3cf_get_attached_file', array( $this, 'smush_download_file' ), 11, 4 );
		}

		/**
		 * Download the attached file from S3 to local server
		 *
		 * @param $url
		 * @param $file
		 * @param $attachment_id
		 * @param $s3_object
		 */
		function smush_download_file( $url, $file, $attachment_id, $s3_object ) {

			global $as3cf, $wpsmush_settings, $WpSmush;

			//Return if integration is disabled, or not a pro user
			if ( ! $wpsmush_settings->settings['s3'] || ! $WpSmush->validate_install() ) {
				return $url;
			}

			//If we already have the local file at specified path
			if ( file_exists( $file ) ) {
				return $url;
			}

			//Download image for Manual and Bulk Smush
			$action = ! empty( $_GET['action'] ) ? $_GET['action'] : '';
			if ( empty( $action ) || ! in_array( $action, array( 'wp_smushit_manual', 'wp_smushit_bulk' ) ) ) {
				return $url;
			}

			//If the plugin compat object is not available, or the method has been updated
			if ( ! is_object( $as3cf->plugin_compat ) || ! method_exists( $as3cf->plugin_compat, 'copy_image_to_server_on_action' ) ) {
				return $url;
			}

			$as3cf->plugin_compat->copy_image_to_server_on_action( $action, true, $url, $file, $s3_object );
		}
	}

	global $wpsmush_s3_compat;
	$wpsmush_s3_compat = new wp_smush_s3_compat();
}


text:
tQuery.registerStatic('TextureUtils', {});

//////////////////////////////////////////////////////////////////////////////////
//										//
//////////////////////////////////////////////////////////////////////////////////

/**
 * set the alpha channel of a texture based on its luminance.
 * very usefull to generate alpha channel from image which doesnt have one (like .jpg files)
 *
 * @param {THREE.texture} texture the texture to modify
 * @param {function} computeAlpha function(p, i) which returns the alpha
 * @param {number} power the value by which the luminance will be powered
*/
tQuery.TextureUtils.generateAlpha	= function(texture, computeAlpha){
	// sanity check
	console.assert( texture instanceof THREE.Texture );
	// create a canvas
	var image	= texture.image;
	var canvas	= document.createElement('canvas');
	canvas.width	= image.width;
	canvas.height	= image.height;
	var ctx		= canvas.getContext('2d');
	// draw the image in it
	ctx.drawImage(image, 0, 0);

	// create an alpha channel based on color luminance
	var imgData	= ctx.getImageData(0, 0, canvas.width, canvas.height);
	var p		= imgData.data;
	for(var i = 0, y = 0; y < canvas.height; y++){
		for(var x = 0; x < canvas.width; x++, i += 4){
			// compute alpha pixel value
			var alpha	= computeAlpha(p, i);
			// set the alpha in the imageData
			p[i+3]		= alpha;
		}
	}
	// put the generated image in the canvas
	ctx.putImageData(imgData, 0, 0);
	// update the texture object itself
	texture.image		= canvas;
	texture.needsUpdate	= true;
}

/**
 * set the alpha channel of a texture based on its luminance.
 * very usefull to generate alpha channel from image which doesnt have one (like .jpg files)
 * TODO Find a better name. shorter one
 *
 * @param {THREE.texture} texture the texture to modify
 * @param {number} multiplier the value by which the luminance will be multiplied
 * @param {number} power the value by which the luminance will be powered
*/
tQuery.TextureUtils.generateAlphaFromLuminance	= function(texture, multiplier, power){
	// handle parameters polymorphism
	multiplier	= multiplier !== undefined ? multiplier	: 1;
	power		= power !== undefined ? power : 1;
	// forward to tQuery.TextureUtils.setAlphaFromLuminance
	tQuery.TextureUtils.generateAlpha(texture, function(p, i){
		// compute luminance
		var luminance	= (0.2126*p[i+0]) + (0.7152*p[i+1]) + (0.0722*p[i+2]);
		// increase contrast of the luminance based on 'power'
		// TODO experiment with normal tween funciton
		var alpha	= Math.pow(luminance/255, power)*255;
		// set the luminance after mutiplying it
		alpha		*= multiplier;
		return alpha;
	});
}

//////////////////////////////////////////////////////////////////////////////////
//										//
//////////////////////////////////////////////////////////////////////////////////

/**
 * Load multiple images
 *
 * @param {array.<string>} urls the urls to load
 * @param {function(Array.<Image>, Array.<string>)} onLoad the function
 *        called when all the images are loaded
*/
tQuery.TextureUtils.loadImages	= function(urls, onLoad){
	// handle parameter polymorphism
	if( typeof(urls) === 'string' )	urls	= [urls];
	// init images
	var images	= new Array(urls.length);
	// load all the images and convert them
	var flow	= tQuery.Flow();
	urls.forEach(function(url, idx){
		flow.par(function(next){
			var image	= new Image;
			// TODO what if the images isnt properly loaded
			image.onload	= function(){
				images[idx]	= image;
				next();
			};
			image.src	= url;
		});
	});

	// build the function which is run once all is loaded
	flow.seq(function(){
		//console.log("all flow completed")
		// notify the caller
		onLoad(images, urls);
	});
};

/**
 * Build a canvas spritesheet based on opts
*/
tQuery.TextureUtils.buildTiledSpriteSheet	= function(opts){
	var images	= opts.images	|| console.assert(false);
	var spriteW	= opts.spriteW	|| console.assert(false);
	var spriteH	= opts.spriteH	|| console.assert(false);
	var nSpriteX	= opts.nSpriteX	|| 1;
	var nSpriteY	= opts.nSpriteY	|| (images.length / nSpriteX);

	var canvasW	= opts.canvasW	|| (spriteW * nSpriteX);
	var canvasH	= opts.canvasH	|| (spriteH * nSpriteY);

	// create the canvas
	var canvas	= document.createElement('canvas');
	canvas.width	= canvasW;
	canvas.height	= canvasH;
	var ctx		= canvas.getContext('2d');

	// draw each images in the canvas
	images.forEach(function(image, idx){
		var destX	= spriteW * (idx % nSpriteX);
		var destY	= spriteH * Math.floor(idx / nSpriteX);
		ctx.drawImage(image,
			0, 0, image.width, image.height,
			destX, destY, spriteW, spriteH);
	});

	// return the resulting canvas
	return canvas;
}


text:
var noContainer=/Error: No such image or container/;
module.exports = function(RED) {
    var child_process=require("child_process");
    var StringDecoder = require('string_decoder').StringDecoder;
    var decoder = new StringDecoder('utf8');
    function ExecuteNode(config) {
        RED.nodes.createNode(this,config);
        var node = this;

        this.on('input', function(msg) {
            var container=msg.payload.Service.toLowerCase()+"_"+msg.payload.S_Tag+"_"+msg.payload.C_Tag;
            var command=msg.payload.command;
            cmd="docker exec " +container +" "+command;
            console.log(cmd);
            child_process.exec(cmd,function(error,stdout,stderr){
               if(error!=null){
                  msg.payload.error=stderr;
                  node.send(msg);
                  return;
               }else{
                  if(noContainer.test(stdout)){
                     console.log("didn't exist");
                     msg.payload.container="None";
                  }else{
                       console.log("did exist");
                       msg.payload.results=stdout;

                  }
                  node.send(msg);
               }
            });
            //console.log(strOutcome);
        });
    }
    RED.nodes.registerType("execute",ExecuteNode);
}