text:
package stroom.index.client.presenter;

import stroom.alert.client.event.AlertEvent;
import stroom.alert.client.event.ConfirmEvent;
import stroom.dispatch.client.Rest;
import stroom.dispatch.client.RestFactory;
import stroom.index.client.presenter.IndexVolumeEditPresenter.IndexVolumeEditView;
import stroom.index.shared.IndexVolume;
import stroom.index.shared.IndexVolume.VolumeUseState;
import stroom.index.shared.IndexVolumeResource;
import stroom.index.shared.ValidationResult;
import stroom.item.client.ItemListBox;
import stroom.node.client.NodeManager;
import stroom.util.shared.ModelStringUtil;
import stroom.widget.popup.client.event.HidePopupEvent;
import stroom.widget.popup.client.event.ShowPopupEvent;
import stroom.widget.popup.client.presenter.PopupSize;
import stroom.widget.popup.client.presenter.PopupType;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.ui.Focus;
import com.google.gwt.user.client.ui.HasText;
import com.google.inject.Inject;
import com.google.web.bindery.event.shared.EventBus;
import com.gwtplatform.mvp.client.MyPresenterWidget;
import com.gwtplatform.mvp.client.View;

import java.util.List;
import java.util.function.Consumer;

public class IndexVolumeEditPresenter extends MyPresenterWidget<IndexVolumeEditView> {

    private static final IndexVolumeResource INDEX_VOLUME_RESOURCE = GWT.create(IndexVolumeResource.class);

    private final RestFactory restFactory;
    private final NodeManager nodeManager;

    private IndexVolume volume;

    @Inject
    public IndexVolumeEditPresenter(final EventBus eventBus,
                                    final IndexVolumeEditView view,
                                    final RestFactory restFactory,
                                    final NodeManager nodeManager) {
        super(eventBus, view);
        this.restFactory = restFactory;
        this.nodeManager = nodeManager;
    }

    void show(final IndexVolume volume, final String caption, final Consumer<IndexVolume> consumer) {
        nodeManager.listAllNodes(
                nodeNames -> {
                    read(nodeNames, volume);

                    final PopupSize popupSize = PopupSize.resizableX();
                    ShowPopupEvent.builder(this)
                            .popupType(PopupType.OK_CANCEL_DIALOG)
                            .popupSize(popupSize)
                            .caption(caption)
                            .onShow(e -> getView().focus())
                            .onHideRequest(event -> {
                                if (event.isOk()) {
                                    try {
                                        write();
                                        if (volume.getId() != null) {
                                            doWithVolumeValidation(volume, () -> updateVolume(consumer, volume));
                                        } else {
                                            doWithVolumeValidation(volume, () -> createIndexVolume(consumer, volume));
                                        }

                                    } catch (final RuntimeException e) {
                                        AlertEvent.fireError(IndexVolumeEditPresenter.this, e.getMessage(), null);
                                    }
                                } else {
                                    consumer.accept(null);
                                }
                            })
                            .fire();
                },
                throwable -> {
                    AlertEvent.fireError(IndexVolumeEditPresenter.this, throwable.getMessage(), null);
                    consumer.accept(null);
                });
    }

    private void doWithVolumeValidation(final IndexVolume volume,
                                        final Runnable work) {

        final Rest<ValidationResult> rest = restFactory.create();
        rest
                .onSuccess(validationResult -> {
                    if (validationResult.isOk()) {
                        if (work != null) {
                            work.run();
                        }
                    } else if (validationResult.isWarning()) {
                        ConfirmEvent.fireWarn(
                                IndexVolumeEditPresenter.this,
                                validationResult.getMessage(),
                                confirmOk -> {
                                    if (confirmOk) {
                                        if (work != null) {
                                            work.run();
                                        }
                                    }
                                });
                    } else {
                        AlertEvent.fireError(
                                IndexVolumeEditPresenter.this,
                                validationResult.getMessage(),
                                null);
                    }
                })
                .onFailure(throwable -> {
                    AlertEvent.fireError(IndexVolumeEditPresenter.this, throwable.getMessage(), null);
                })
                .call(INDEX_VOLUME_RESOURCE)
                .validate(volume);
    }

    private void createIndexVolume(final Consumer<IndexVolume> savedVolumeConsumer, final IndexVolume volume) {
        final Rest<IndexVolume> rest = restFactory.create();
        rest
                .onSuccess(savedVolumeConsumer)
                .call(INDEX_VOLUME_RESOURCE)
                .create(volume);
    }

    private void updateVolume(final Consumer<IndexVolume> consumer,
                              final IndexVolume volume) {
        final Rest<IndexVolume> rest = restFactory.create();
        rest
                .onSuccess(consumer)
                .call(INDEX_VOLUME_RESOURCE)
                .update(volume.getId(), volume);
    }

    void hide() {
        HidePopupEvent.builder(this).fire();
    }

    private void read(final List<String> nodeNames, final IndexVolume volume) {
        this.volume = volume;

        getView().setNodeNames(nodeNames);
        getView().getNodeName().setText(volume.getNodeName());
        getView().getPath().setText(volume.getPath());
        getView().getState().addItems(VolumeUseState.values());
        getView().getState().setSelectedItem(volume.getState());

        if (volume.getBytesLimit() != null) {
            getView().getByteLimit().setText(ModelStringUtil.formatIECByteSizeString(volume.getBytesLimit()));
        } else {
            getView().getByteLimit().setText("");
        }
    }

    private void write() {
        volume.setNodeName(getView().getNodeName().getText());
        volume.setPath(getView().getPath().getText());
        volume.setState(getView().getState().getSelectedItem());

        Long bytesLimit = null;
        final String limit = getView().getByteLimit().getText().trim();
        if (limit.length() > 0) {
            bytesLimit = ModelStringUtil.parseIECByteSizeString(limit);
        }
        volume.setBytesLimit(bytesLimit);
    }

    public interface IndexVolumeEditView extends View, Focus {

        void setNodeNames(List<String> nodeNames);

        HasText getNodeName();

        HasText getPath();

        ItemListBox<VolumeUseState> getState();

        HasText getByteLimit();
    }
}


text:
package com.oculusinfo.sparktile.spark;

import org.apache.spark.SparkContext;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.sql.SQLContext;
import org.json.JSONObject;

/**
 * Very simple interface to provide a consistent spark context to anyone who needs it.
 *
 * @author nkronenfeld
 */
public interface SparkContextProvider {
	/**
	 * Get a usable spark context
	 */
	public SparkContext getSparkContext (JSONObject configuration);

	/**
	 * Get a usable spark context, in Java API form
	 */
	public JavaSparkContext getJavaSparkContext (JSONObject configuration);

	/**
	 * Get a usable spark SQL context
	 */
	public SQLContext getSQLContext (JSONObject configuration);

	/**
	 * Shut down the web server's spark context.
	 */
	public void shutdownSparkContext ();
}

redpajama_set_name: RedPajamaGithub


text:
package org.bremersee.web.reactive.function.client.proxy;

import static org.springframework.core.annotation.AnnotationUtils.findAnnotation;

import java.lang.reflect.Method;
import org.bremersee.exception.ServiceException;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClient.RequestHeadersUriSpec;

/**
 * The request uri spec builder.
 *
 * @author Christian Bremer
 */
public interface RequestUriSpecBuilder {

  /**
   * Build request headers uri spec.
   *
   * @param parameters the parameters
   * @param webClient the web client
   * @return the request headers uri spec
   */
  RequestHeadersUriSpec<?> build(InvocationParameters parameters, WebClient webClient);

  /**
   * Default request uri spec builder.
   *
   * @return the request uri spec builder
   */
  static RequestUriSpecBuilder defaultBuilder() {
    return new Default();
  }

  /**
   * The default request uri spec builder.
   */
  class Default implements RequestUriSpecBuilder {

    @Override
    public RequestHeadersUriSpec<?> build(
        final InvocationParameters parameters,
        final WebClient webClient) {

      final Method method = parameters.getMethod();
      final RequestMapping requestMapping = findAnnotation(method, RequestMapping.class);
      if (requestMapping != null && requestMapping.method().length > 0) {
        switch (requestMapping.method()[0]) {
          case GET:
            return webClient.get();
          case HEAD:
            return webClient.head();
          case POST:
            return webClient.post();
          case PUT:
            return webClient.put();
          case PATCH:
            return webClient.patch();
          case DELETE:
            return webClient.delete();
          case OPTIONS:
            return webClient.options();
          default:
        }
      }
      if (findAnnotation(method, GetMapping.class) != null) {
        return webClient.get();
      }
      if (findAnnotation(method, PostMapping.class) != null) {
        return webClient.post();
      }
      if (findAnnotation(method, PutMapping.class) != null) {
        return webClient.put();
      }
      if (findAnnotation(method, PatchMapping.class) != null) {
        return webClient.patch();
      }
      if (findAnnotation(method, DeleteMapping.class) != null) {
        return webClient.delete();
      }
      throw ServiceException.internalServerError("Cannot find request method on method '"
              + method.getName() + "'.",
          "org.bremersee:common-base-webflux:5222f2b4-1810-41bf-acfc-37988571304b");
    }
  }

}


text:
using System;
using System.Text;
using System.Collections;
using Alachisoft.NCache.Common.Net;
using System.Threading;

namespace Alachisoft.NCache.Common.Monitoring
{

    public class ServerMonitor
    {
        private static bool _monitor;
        private static Hashtable _clientActivity = Hashtable.Synchronized(new Hashtable());
        private static Hashtable _threadClientMap = Hashtable.Synchronized(new Hashtable());
        private static Hashtable _dataStructures = Hashtable.Synchronized(new Hashtable());
        private static Hashtable _dedicatedThreadsActivity = Hashtable.Synchronized(new Hashtable());
        private static DateTime _startTime;
        private static DateTime _endTime;
        private static object _sync = new object();

        public static DateTime StartTime
        {
            get { return _startTime; }
        }

        public static DateTime EndTime
        {
            get { return _endTime; }
        }

        public static bool MonitorActivity
        {
            get { return _monitor; }
        }

        public static void StartMonitoring()
        {
            lock (_sync)
            {
                if (_monitor) return; //already started.
                _monitor = true;
                _startTime = DateTime.Now;
            }
        }

        public static void StopMonitoring()
        {
            lock (_sync)
            {
                if (_monitor)
                {
                    _monitor = false;
                    _endTime = DateTime.Now;
                }
            }
        }

        public static void RegisterClient(string clientID, string address)
        {
            if (clientID == null) return;
            lock (_clientActivity.SyncRoot)
            {
                if (!_clientActivity.Contains(clientID))
                {
                    ClientMonitor clientActivity = new ClientMonitor(clientID, address);
                    _clientActivity.Add(clientID, clientActivity);
                }
            }
        }

        public static void UnregisterClient(string clientId)
        {
            if (clientId == null) return;
            lock (_clientActivity.SyncRoot)
            {
                if (_clientActivity.Contains(clientId))
                {
                    _clientActivity.Remove(clientId);
                }
            }
        }

        public static void StartClientActivity(string clientId)
        {
            if (clientId == null) return;
            if (_monitor)
            {
                ClientMonitor cMonitor = _clientActivity[clientId] as ClientMonitor;
                if (cMonitor != null)
                {
                    cMonitor.StartActivity();
                }
                int tId = Thread.CurrentThread.ManagedThreadId;

                lock (_threadClientMap.SyncRoot)
                {
                    _threadClientMap[tId] = cMonitor;
                }
            }
        }

        public static void StopClientActivity(string clientId)
        {
            if (_monitor)
            {
                ClientMonitor cMonitor = _clientActivity[clientId] as ClientMonitor;
                if (cMonitor != null)
                {
                    cMonitor.StopActivity();
                }
                int tId = Thread.CurrentThread.ManagedThreadId;

                lock (_threadClientMap.SyncRoot)
                {
                    _threadClientMap.Remove(tId);
                }
            }
       }

        public static void LogClientActivity(string method, string activity)
        {

            if (_monitor)
            {
                ClientMonitor cMonitor = _threadClientMap[Thread.CurrentThread.ManagedThreadId] as ClientMonitor;
                if (cMonitor != null)
                {
                    cMonitor.LogActivity(method,activity);
                }
            }
        }

        public static Hashtable GetCompletedClientActivity()
        {
            Hashtable activityTable = new Hashtable();
            lock (_clientActivity.SyncRoot)
            {
                IDictionaryEnumerator ide = _clientActivity.GetEnumerator();

                while (ide.MoveNext())
                {
                    ClientMonitor cMonitor = ide.Value as ClientMonitor;
                    activityTable.Add(cMonitor.Info, cMonitor.GetCompletedClientActivities());
                }
            }
            return activityTable;
        }

        public static Hashtable GetCurrentClientActivity()
        {
            Hashtable activityTable = new Hashtable();
            lock (_clientActivity.SyncRoot)
            {
                IDictionaryEnumerator ide = _clientActivity.GetEnumerator();

                while (ide.MoveNext())
                {
                    ClientMonitor cMonitor = ide.Value as ClientMonitor;
                    activityTable.Add(cMonitor.Info, cMonitor.GetCurrentClientActivities());
                }
            }
            return activityTable;
        }

        public static void Reset()
        {
            if (_clientActivity != null)
            {
                lock (_clientActivity.SyncRoot)
                {
                    _clientActivity.Clear();
                }
            }
            if (_dedicatedThreadsActivity != null)
            {
                lock (_dedicatedThreadsActivity.SyncRoot)
                {
                    _dedicatedThreadsActivity.Clear();
                }
            }
        }
    }
}


text:
package com.opoopress.maven.plugins.plugin;

import org.apache.commons.lang.StringUtils;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.opoo.press.SiteManager;
import org.opoo.press.impl.SiteConfigImpl;
import org.opoo.press.impl.SiteImpl;
import org.opoo.press.impl.SiteManagerImpl;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Alex Lin
 * @goal new
 * @execute phase="package"
 */
public class NewMojo extends AbstractOpooPressMojo{

    /**
     * @parameter expression="${op.new.skip}" default-value="false"
     */
    private boolean skipNew = false;

    /**
     * @parameter expression="${draft}" default-value="false"
     */
    private boolean draft = false;

    /**
     * The layout of new source file.
     * @parameter expression="${layout}" default-value="post"
     */
    private String layout;

    /**
     * File name without extension.
     * @parameter expression="${name}"
     */
    private String name;

    /**
     * The title of your new article.
     *
     * @parameter expression="${title}"
     * @required
     */
    private String title;

    /**
     * @parameter expression="${format}" default-value="markdown"
     */
    private String format;

    /**
     * @parameter expression="${permalink}"
     */
    private String permalink;

    /**
     * @parameter expression="${template}"
     */
    private String template;

    private SiteManager siteManager = new SiteManagerImpl();

    @Override
    protected void executeInternal(SiteConfigImpl config) throws MojoExecutionException, MojoFailureException {
        if (skipNew) {
            getLog().info("Skiping create new file.");
            return;
        }

        if(StringUtils.isBlank(title)){
            throw new MojoFailureException("'title' is required, use '-Dtitle=\"your article title\"'");
        }

        SiteImpl site = new SiteImpl(config);

        Map<String, Object> meta = new HashMap<String, Object>();
        meta.put("published", !draft);
        try {
            siteManager.createNewFile(site, layout, title, name, format, permalink, template, meta);
        } catch (Exception e) {
            throw new MojoFailureException(e.getMessage(), e);
        }
    }
}


text:
package bloombot;

import battlecode.common.GameActionException;
import battlecode.common.RobotController;
import battlecode.common.RobotType;

public abstract class Strategy {
	// this provides suggestions for build order choices
	// i'm not sure where that information should live, which is why it lives as static members of this class

	protected RobotController rc;

	public Strategy(RobotController rc) {
		this.rc = rc;
	}

	public static Strategy getStrategy(RobotController rc) throws GameActionException {
		return new LaunchAndScout(rc);
	}

	public abstract boolean shouldMakeTanks() throws GameActionException;

	public abstract boolean shouldMakeLaunchers() throws GameActionException;

	public abstract boolean shouldMakeSoldiers() throws GameActionException;

	public abstract boolean shouldMakeBashers() throws GameActionException;

	public abstract boolean shouldMakeDrones() throws GameActionException;

	public abstract boolean shouldAggroWithDrones() throws GameActionException;

	public abstract RobotType getBeaverBuildOrder() throws GameActionException;

	public abstract boolean shouldAttack() throws GameActionException;

	public abstract boolean shouldWithdraw() throws GameActionException;

	// the premise of this strategy is:
	// launcher can shoot missiles, which can scout void terrain. awesome! but they're really slow
	// on the flip side, soldies are really cheap, so we can scout with them. (TODO: or should we just scout with miners?)
	private static class LaunchAndScout extends Strategy {

		public LaunchAndScout(RobotController rc) {
			super(rc);
		}

		@Override
		public boolean shouldMakeTanks() throws GameActionException {
			return false;
		}

		private final double SOLDIERS_PER_LAUNCHER = 3;

		@Override
		public boolean shouldMakeLaunchers() throws GameActionException {
			int launcherCount = BroadcastInterface.getRobotCount(rc, RobotType.LAUNCHER, true);
			int soldiercount = BroadcastInterface.getRobotCount(rc, RobotType.SOLDIER, true);
			return launcherCount * SOLDIERS_PER_LAUNCHER <= soldiercount;
		}

		@Override
		public boolean shouldMakeSoldiers() throws GameActionException {
			int launcherCount = BroadcastInterface.getRobotCount(rc, RobotType.LAUNCHER, true);
			int soldiercount = BroadcastInterface.getRobotCount(rc, RobotType.SOLDIER, true);
			return launcherCount * SOLDIERS_PER_LAUNCHER >= soldiercount;
		}

		@Override
		public boolean shouldMakeBashers() throws GameActionException {
			return false;
		}

		@Override
		public boolean shouldMakeDrones() throws GameActionException {
			return false;
		}

		@Override
		public boolean shouldAggroWithDrones() throws GameActionException {
			return false;
		}

		@Override
		public RobotType getBeaverBuildOrder() throws GameActionException {
			int numMinerFactories = BroadcastInterface.getRobotCount(rc, RobotType.MINERFACTORY, true);
			if (numMinerFactories < 1) {
				return RobotType.MINERFACTORY;
			}
			int numHelipads = BroadcastInterface.getRobotCount(rc, RobotType.HELIPAD, true);
			if (numHelipads < 1) {
				return RobotType.HELIPAD;
			}
			int numAerospacelabs = BroadcastInterface.getRobotCount(rc, RobotType.AEROSPACELAB, true);
			if (numAerospacelabs < 1) {
				return RobotType.AEROSPACELAB;
			}
			int numBarracks = BroadcastInterface.getRobotCount(rc, RobotType.BARRACKS, true);
			if (numBarracks < 1) {
				return RobotType.BARRACKS;
			}
			int numTechnologyInstitutes = BroadcastInterface.getRobotCount(rc, RobotType.TECHNOLOGYINSTITUTE, true);
			if (numTechnologyInstitutes < 1) {
				return RobotType.TECHNOLOGYINSTITUTE;
			}
			int numTrainingFields = BroadcastInterface.getRobotCount(rc, RobotType.TRAININGFIELD, true);
			if (numTrainingFields < 1) {
				return RobotType.TRAININGFIELD;
			}

			if (shouldMakeLaunchers()) {
				return RobotType.AEROSPACELAB;
			} else {
				return RobotType.BARRACKS;
			}
		}

		@Override
		public boolean shouldAttack() throws GameActionException {
			return true;
		}

		@Override
		public boolean shouldWithdraw() throws GameActionException {
			return false;
		}

	}
}


text:
<?php

use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\Pjax;

/* @var $this yii\web\View */
/* @var $searchModel common\models\EventSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'Events';
$this->params['breadcrumbs'][] = $this->title;
?>

<?= Html::encode($this->title) ?>

    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

        <?= Html::a('Create Event', ['create'], ['class' => 'btn btn-success']) ?>

    <?php Pjax::begin(['id' => 'id', 'timeout' => false,
        'enablePushState' => false]); ?>
    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'rowOptions'=> function($modal) {

            if ($modal->is_active == '0') {
                return ['class' => 'danger'];
            } else
                return ['class' => 'success'];
        },

        'columns' => [
            'organiser.clubname',
            'interest.area_intrest',
            'title',
            'description:html',
            'location',
            //'is_active:boolean',
            //'created_date:datetime',
            // 'created_by',
            // 'updated_date',
            // 'updated_by',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>
<?php Pjax::end() ?>


text:
Generally, this is because the xen-blkfront.ko module is not loaded during the startup. You need to modify OS kernel startup parameters.  [Figure 1](#en-us_topic_0029124532_fb625ead0fbca4936a8a0b147e6719b71)  shows the startup screen after the login to the ECS.

**Figure  1**  Startup screen
![](figures/startup-screen.png "startup-screen")

## Solution

Perform the following operations to modify OS kernel boot parameters:

>![](/images/icon-note.gif) **NOTE:**
>These operations must be performed after the OS starts. You are advised to modify kernel boot parameters in the ECS used for creating the image.

1.  Run the following command to log in to the OS:

    **lsinitrd /boot/initramfs-_\`_**_uname_**_ _-r_\`_.img |grep -i xen**

    -   If the command output contains  **xen-blkfront.ko**, contact the customer service.
    -   If no command output is displayed, go to  [2](#li155801950404).

2.  Back up the GRUB configuration file.
    -   If the ECS runs CentOS 6, run the following command:

        **cp /boot/grub/grub.conf /boot/grub/grub.conf.bak**

    -   If the ECS runs CentOS 7, run the following command:

        **cp /boot/grub2/grub.cfg /boot/grub2/grub.cfg.bak**

3.  Use the vi editor to open the GRUB configuration file. Run the following command \(using CentOS 7 as an example\):

    **vi /boot/grub2/grub.cfg**

4.  Add  **xen\_emul\_unplug=all**  to the default boot kernel.

    >![](/images/icon-note.gif) **NOTE:**
    >Search for the line that contains  **root=UUID=**  and add  **xen\_emul\_unplug=all**  to the end of the line.

    ```
    menuentry 'CentOS Linux (3.10.0-229.el7.x86_64) 7 (Core) with debugging' --class centos --class gnu-linux --class gnu --class os --unrestricted $menuentry_id_option 'gnulinux-3.10.0-229.el7.x86_64-advanced-bf3cc825-7638-48d8-8222-cd2f412dd0de' {
            load_video
            set gfxpayload=keep
            insmod gzio
            insmod part_msdos
            insmod ext2
            set root='hd0,msdos1'
            if [ x$feature_platform_search_hint = xy ]; then
              search --no-floppy --fs-uuid --set=root --hint='hd0,msdos1'  bf3cc825-7638-48d8-8222-cd2f412dd0de
            else
              search --no-floppy --fs-uuid --set=root bf3cc825-7638-48d8-8222-cd2f412dd0de
            fi
            linux16 /boot/vmlinuz-3.10.0-229.el7.x86_64 root=UUID=bf3cc825-7638-48d8-8222-cd2f412dd0de xen_emul_unplug=all ro crashkernel=auto rhgb quiet  systemd.log_level=debug systemd.log_target=kmsg
            initrd16 /boot/initramfs-3.10.0-229.el7.x86_64.img
    }
    ```

5.  Press  **Esc**, enter  **:wq**, and press  **Enter**  to exit the vi editor.
6.  Create an image using the ECS, upload and register the image on the cloud platform.


text:
<?php

namespace League\Container;

trait ContainerAwareTrait
{
    /**
     * @var \League\Container\ContainerInterface
     */
    protected $container;

    /**
     * Set a container.
     *
     * @param  \League\Container\ContainerInterface $container
     * @return $this
     */
    public function setContainer(ContainerInterface $container)
    {
        $this->container = $container;

        return $this;
    }

    /**
     * Get the container.
     *
     * @return \League\Container\ContainerInterface
     */
    public function getContainer()
    {
        return $this->container;
    }
}


text: This help icon opens a help key that is not based on page context:


text:
package apiserver

import (
	"io"
	"math/rand"
	"net/http"
	"net/http/httputil"
	"net/url"
	"path"
	"strings"
	"time"

	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/api/errors"
	"k8s.io/kubernetes/pkg/api/rest"
	"k8s.io/kubernetes/pkg/api/unversioned"
	"k8s.io/kubernetes/pkg/apiserver/metrics"
	"k8s.io/kubernetes/pkg/httplog"
	"k8s.io/kubernetes/pkg/runtime"
	"k8s.io/kubernetes/pkg/util/httpstream"
	"k8s.io/kubernetes/pkg/util/net"
	proxyutil "k8s.io/kubernetes/pkg/util/proxy"

	"github.com/golang/glog"
)

// ProxyHandler provides a http.Handler which will proxy traffic to locations
// specified by items implementing Redirector.
type ProxyHandler struct {
	prefix              string
	storage             map[string]rest.Storage
	serializer          runtime.NegotiatedSerializer
	context             api.RequestContextMapper
	requestInfoResolver *RequestInfoResolver
}

func (r *ProxyHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	proxyHandlerTraceID := rand.Int63()

	var verb string
	var apiResource string
	var httpCode int
	reqStart := time.Now()
	defer metrics.Monitor(&verb, &apiResource, net.GetHTTPClient(req), &httpCode, reqStart)

	requestInfo, err := r.requestInfoResolver.GetRequestInfo(req)
	if err != nil || !requestInfo.IsResourceRequest {
		notFound(w, req)
		httpCode = http.StatusNotFound
		return
	}
	verb = requestInfo.Verb
	namespace, resource, parts := requestInfo.Namespace, requestInfo.Resource, requestInfo.Parts

	ctx, ok := r.context.Get(req)
	if !ok {
		ctx = api.NewContext()
	}
	ctx = api.WithNamespace(ctx, namespace)
	if len(parts) < 2 {
		notFound(w, req)
		httpCode = http.StatusNotFound
		return
	}
	id := parts[1]
	remainder := ""
	if len(parts) > 2 {
		proxyParts := parts[2:]
		remainder = strings.Join(proxyParts, "/")
		if strings.HasSuffix(req.URL.Path, "/") {
			// The original path had a trailing slash, which has been stripped
			// by KindAndNamespace(). We should add it back because some
			// servers (like etcd) require it.
			remainder = remainder + "/"
		}
	}
	storage, ok := r.storage[resource]
	if !ok {
		httplog.LogOf(req, w).Addf("'%v' has no storage object", resource)
		notFound(w, req)
		httpCode = http.StatusNotFound
		return
	}
	apiResource = resource

	gv := unversioned.GroupVersion{Group: requestInfo.APIGroup, Version: requestInfo.APIVersion}

	redirector, ok := storage.(rest.Redirector)
	if !ok {
		httplog.LogOf(req, w).Addf("'%v' is not a redirector", resource)
		httpCode = errorNegotiated(errors.NewMethodNotSupported(api.Resource(resource), "proxy"), r.serializer, gv, w, req)
		return
	}

	location, roundTripper, err := redirector.ResourceLocation(ctx, id)
	if err != nil {
		httplog.LogOf(req, w).Addf("Error getting ResourceLocation: %v", err)
		httpCode = errorNegotiated(err, r.serializer, gv, w, req)
		return
	}
	if location == nil {
		httplog.LogOf(req, w).Addf("ResourceLocation for %v returned nil", id)
		notFound(w, req)
		httpCode = http.StatusNotFound
		return
	}

	if roundTripper != nil {
		glog.V(5).Infof("[%x: %v] using transport %T...", proxyHandlerTraceID, req.URL, roundTripper)
	}

	// Default to http
	if location.Scheme == "" {
		location.Scheme = "http"
	}
	// Add the subpath
	if len(remainder) > 0 {
		location.Path = singleJoiningSlash(location.Path, remainder)
	}
	// Start with anything returned from the storage, and add the original request's parameters
	values := location.Query()
	for k, vs := range req.URL.Query() {
		for _, v := range vs {
			values.Add(k, v)
		}
	}
	location.RawQuery = values.Encode()

	newReq, err := http.NewRequest(req.Method, location.String(), req.Body)
	if err != nil {
		httpCode = errorNegotiated(err, r.serializer, gv, w, req)
		return
	}
	httpCode = http.StatusOK
	newReq.Header = req.Header
	newReq.ContentLength = req.ContentLength
	// Copy the TransferEncoding is for future-proofing. Currently Go only supports "chunked" and
	// it can determine the TransferEncoding based on ContentLength and the Body.
	newReq.TransferEncoding = req.TransferEncoding

	// TODO convert this entire proxy to an UpgradeAwareProxy similar to
	// https://github.com/openshift/origin/blob/master/pkg/util/httpproxy/upgradeawareproxy.go.
	// That proxy needs to be modified to support multiple backends, not just 1.
	if r.tryUpgrade(w, req, newReq, location, roundTripper, gv) {
		return
	}

	// Redirect requests of the form "/{resource}/{name}" to "/{resource}/{name}/"
	// This is essentially a hack for http://issue.k8s.io/4958.
	// Note: Keep this code after tryUpgrade to not break that flow.
	if len(parts) == 2 && !strings.HasSuffix(req.URL.Path, "/") {
		var queryPart string
		if len(req.URL.RawQuery) > 0 {
			queryPart = "?" + req.URL.RawQuery
		}
		w.Header().Set("Location", req.URL.Path+"/"+queryPart)
		w.WriteHeader(http.StatusMovedPermanently)
		return
	}

	start := time.Now()
	glog.V(4).Infof("[%x] Beginning proxy %s...", proxyHandlerTraceID, req.URL)
	defer func() {
		glog.V(4).Infof("[%x] Proxy %v finished %v.", proxyHandlerTraceID, req.URL, time.Now().Sub(start))
	}()

	proxy := httputil.NewSingleHostReverseProxy(&url.URL{Scheme: location.Scheme, Host: location.Host})
	alreadyRewriting := false
	if roundTripper != nil {
		_, alreadyRewriting = roundTripper.(*proxyutil.Transport)
		glog.V(5).Infof("[%x] Not making a reriting transport for proxy %s...", proxyHandlerTraceID, req.URL)
	}
	if !alreadyRewriting {
		glog.V(5).Infof("[%x] making a transport for proxy %s...", proxyHandlerTraceID, req.URL)
		prepend := path.Join(r.prefix, resource, id)
		if len(namespace) > 0 {
			prepend = path.Join(r.prefix, "namespaces", namespace, resource, id)
		}
		pTransport := &proxyutil.Transport{
			Scheme:       req.URL.Scheme,
			Host:         req.URL.Host,
			PathPrepend:  prepend,
			RoundTripper: roundTripper,
		}
		roundTripper = pTransport
	}
	proxy.Transport = roundTripper
	proxy.FlushInterval = 200 * time.Millisecond
	proxy.ServeHTTP(w, newReq)
}

// tryUpgrade returns true if the request was handled.
func (r *ProxyHandler) tryUpgrade(w http.ResponseWriter, req, newReq *http.Request, location *url.URL, transport http.RoundTripper, gv unversioned.GroupVersion) bool {
	if !httpstream.IsUpgradeRequest(req) {
		return false
	}
	backendConn, err := proxyutil.DialURL(location, transport)
	if err != nil {
		errorNegotiated(err, r.serializer, gv, w, req)
		return true
	}
	defer backendConn.Close()

	// TODO should we use _ (a bufio.ReadWriter) instead of requestHijackedConn
	// when copying between the client and the backend? Docker doesn't when they
	// hijack, just for reference...
	requestHijackedConn, _, err := w.(http.Hijacker).Hijack()
	if err != nil {
		errorNegotiated(err, r.serializer, gv, w, req)
		return true
	}
	defer requestHijackedConn.Close()

	if err = newReq.Write(backendConn); err != nil {
		errorNegotiated(err, r.serializer, gv, w, req)
		return true
	}

	done := make(chan struct{}, 2)

	go func() {
		_, err := io.Copy(backendConn, requestHijackedConn)
		if err != nil && !strings.Contains(err.Error(), "use of closed network connection") {
			glog.Errorf("Error proxying data from client to backend: %v", err)
		}
		done <- struct{}{}
	}()

	go func() {
		_, err := io.Copy(requestHijackedConn, backendConn)
		if err != nil && !strings.Contains(err.Error(), "use of closed network connection") {
			glog.Errorf("Error proxying data from backend to client: %v", err)
		}
		done <- struct{}{}
	}()

	<-done
	return true
}

// borrowed from net/http/httputil/reverseproxy.go
func singleJoiningSlash(a, b string) string {
	aslash := strings.HasSuffix(a, "/")
	bslash := strings.HasPrefix(b, "/")
	switch {
	case aslash && bslash:
		return a + b[1:]
	case !aslash && !bslash:
		return a + "/" + b
	}
	return a + b
}


text:
import sys, os
import Image

def decode_image(image):
	"""Check the red portion of an image (r,g,b) tuple for hidden characters

	"""
        img = Image.open(image)

	width, height = img.size
	msg = ""

	index = 0

	for row in range(height):
		for col in range(width):
			r,g,b,a = img.getpixel((col, row))

			if row == 0 and col == 0:
				length = r
			elif index <= length:
				msg += chr(r)

			index += 1

        print str(msg)

if __name__ == "__main__":

    if sys.argv[1] == 'decode':
        decode_image(sys.argv[2])


text:
require 'dm-core'
require 'dm-migrations'
require 'dm-timestamps'
require 'dm-types'
require 'rubycas/server/datamapper/model'
require "rubycas/server/datamapper/version"

module RubyCAS
  module Server
    module Core
      module Database
        extend self
        def setup(config_file)
          ::DataMapper.setup(:default, config_file)
        end
      end

      module DataMapper
        # Your code goes here...
      end
    end

  end
end


text:
/*
 * File: TControllerCellMarqueeHandler.java
 * 		This file is part of Tico, an application to create and	perform
 * 		interactive communication boards to be used by people with
 * 		severe motor disabilities.
 *
 * Authors: Carolina Palacio
 *
 * Date: Dec, 2009
 *
 * Company: Universidad de Zaragoza, CPS, DIIS
 *
 * License:
 * 		This program is free software: you can redistribute it and/or
 * 		modify it under the terms of the GNU General Public License
 * 		as published by the Free Software Foundation, either version 3
 * 		of the License, or (at your option) any later version.
 *
 * 		This program is distributed in the hope that it will be useful,
 * 		but WITHOUT ANY WARRANTY; without even the implied warranty of
 * 		MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * 		GNU General Public License for more details.
 *
 * 		You should have received a copy of the GNU General Public License
 *     	along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package tico.editor.handler;

import java.awt.geom.Rectangle2D;
import java.io.File;
import java.io.IOException;

import javax.swing.ImageIcon;

import tico.board.TBoardConstants;
import tico.board.components.TComponent;
import tico.board.components.TControllerCell;
import tico.configuration.TLanguage;
import tico.editor.TBoardContainer;
import tico.editor.TFileHandler;

/**
 * Marquee handler which allows to insert, in a boardContainer
 * board, a new controllerCell of the selected dimension.
 *
 * @author Carolina Palacio
 * @version e1.0 Dec, 2009
 */
public class TControllerCellMarqueeHandler extends TComponentMarqueeHandler {
	/**
	 * Creates a new TCellMarqueeHandler for the specified
	 * boardContainer.
	 *
	 * @param boardContainer The specified boardContainer
	 */
	public TControllerCellMarqueeHandler(TBoardContainer boardContainer) {
		super(boardContainer);
	}

	/* (non-Javadoc)
	 * @see tico.editor.handler.TComponentMarqueeHandler#createDefaultComponent(java.awt.geom.Rectangle2D)
	 */
	protected TComponent createDefaultComponent(Rectangle2D bounds) {
		TComponent controllerCell = new TControllerCell();

		controllerCell.getAttributes().applyMap(
				getBoardContainer().getEditor().getCurrentAttributes());

		TBoardConstants.setBounds(controllerCell.getAttributes(), bounds);

		//Default controller cell is Exit cell
		TBoardConstants.setText(controllerCell.getAttributes(), TLanguage.getString("TInterpreterExitAction.NAME"));
		TBoardConstants.setActionCode(controllerCell.getAttributes(), TBoardConstants.EXIT_ACTION_CODE);
		String currentDirectory = System.getProperty("user.dir");
		String exitFilePath = currentDirectory + File.separator + "controller-icons"+ File.separator + "controller-exit.png";
		ImageIcon exitIcon = null;
		try {
			File f = TFileHandler.importFile(exitFilePath);
			exitIcon = new ImageIcon(f.getAbsolutePath());
		} catch (IOException e) {
			e.printStackTrace();
		}
		TBoardConstants.setIcon(controllerCell.getAttributes(), exitIcon);

		return controllerCell;
	}
}


text:
/*
   The design goals of this code are:
      - Very fast algorithm
      - SIMD-friendly algorithm
      - Low memory requirement
      - Good *perceptual* quality (and not best SNR)

   Warning: This resampler is relatively new. Although I think I got rid of
   all the major bugs and I don't expect the API to change anymore, there
   may be something I've missed. So use with caution.

   This algorithm is based on this original resampling algorithm:
   Smith, Julius O. Digital Audio Resampling Home Page
   Center for Computer Research in Music and Acoustics (CCRMA),
   Stanford University, 2007.
   Web published at http://www-ccrma.stanford.edu/~jos/resample/.

   There is one main difference, though. This resampler uses cubic
   interpolation instead of linear interpolation in the above paper. This
   makes the table much smaller and makes it possible to compute that table
   on a per-stream basis. In turn, being able to tweak the table for each
   stream makes it possible to both reduce complexity on simple ratios
   (e.g. 2/3), and get rid of the rounding operations in the inner loop.
   The latter both reduces CPU time and makes the algorithm more SIMD-friendly.
*/

using Concentus.Celt;
using Concentus.Common.CPlusPlus;
using System;

namespace Concentus.Common
{
    /// <summary>
    /// Arbitrary-rate audio resampler originally implemented for the Speex codec.
    /// </summary>
    public class SpeexResampler
    {
        private const int FIXED_STACK_ALLOC = 8192;

        #region Encoder state

        private int in_rate = 0;
        private int out_rate = 0;
        private int num_rate = 0;
        private int den_rate = 0;

        private int quality = 0;
        private int nb_channels = 0;
        private int filt_len = 0;
        private int mem_alloc_size = 0;
        private int buffer_size = 0;
        private int int_advance = 0;
        private int frac_advance = 0;
        private float cutoff = 0;
        private int oversample = 0;
        private int initialised = 0;
        private int started = 0;

        /* These are per-channel */
        private int[] last_sample = null;
        private int[] samp_frac_num = null;
        private int[] magic_samples = null;

        private short[] mem = null;
        private short[] sinc_table = null;
        private int sinc_table_length = 0;
        private resampler_basic_func resampler_ptr = null;

        int in_stride = 0;
        int out_stride = 0;

        #endregion

        #region Helper classes and tables

        private class FuncDef
        {
            public FuncDef(double[] t, int os)
            {
                table = t;
                oversample = os;
            }

            public double[] table;
            public int oversample;

            public static readonly double[] kaiser12_table/*[68]*/ = {
                0.99859849, 1.00000000, 0.99859849, 0.99440475, 0.98745105, 0.97779076,
                0.96549770, 0.95066529, 0.93340547, 0.91384741, 0.89213598, 0.86843014,
                0.84290116, 0.81573067, 0.78710866, 0.75723148, 0.72629970, 0.69451601,
                0.66208321, 0.62920216, 0.59606986, 0.56287762, 0.52980938, 0.49704014,
                0.46473455, 0.43304576, 0.40211431, 0.37206735, 0.34301800, 0.31506490,
                0.28829195, 0.26276832, 0.23854851, 0.21567274, 0.19416736, 0.17404546,
                0.15530766, 0.13794294, 0.12192957, 0.10723616, 0.09382272, 0.08164178,
                0.07063950, 0.06075685, 0.05193064, 0.04409466, 0.03718069, 0.03111947,
                0.02584161, 0.02127838, 0.01736250, 0.01402878, 0.01121463, 0.00886058,
                0.00691064, 0.00531256, 0.00401805, 0.00298291, 0.00216702, 0.00153438,
                0.00105297, 0.00069463, 0.00043489, 0.00025272, 0.00013031, 0.0000527734,
                0.00001000, 0.00000000};
            /*
            static double kaiser12_table[36] = {
            0.99440475, 1.00000000, 0.99440475, 0.97779076, 0.95066529, 0.91384741,
            0.86843014, 0.81573067, 0.75723148, 0.69451601, 0.62920216, 0.56287762,
            0.49704014, 0.43304576, 0.37206735, 0.31506490, 0.26276832, 0.21567274,
            0.17404546, 0.13794294, 0.10723616, 0.08164178, 0.06075685, 0.04409466,
            0.03111947, 0.02127838, 0.01402878, 0.00886058, 0.00531256, 0.00298291,
            0.00153438, 0.00069463, 0.00025272, 0.0000527734, 0.00000500, 0.00000000};
            */
            public static readonly double[] kaiser10_table/*[36]*/ = {
                0.99537781, 1.00000000, 0.99537781, 0.98162644, 0.95908712, 0.92831446,
                0.89005583, 0.84522401, 0.79486424, 0.74011713, 0.68217934, 0.62226347,
                0.56155915, 0.50119680, 0.44221549, 0.38553619, 0.33194107, 0.28205962,
                0.23636152, 0.19515633, 0.15859932, 0.12670280, 0.09935205, 0.07632451,
                0.05731132, 0.04193980, 0.02979584, 0.02044510, 0.01345224, 0.00839739,
                0.00488951, 0.00257636, 0.00115101, 0.00035515, 0.00000000, 0.00000000};

            public static readonly double[] kaiser8_table/*[36]*/ = {
                0.99635258, 1.00000000, 0.99635258, 0.98548012, 0.96759014, 0.94302200,
                0.91223751, 0.87580811, 0.83439927, 0.78875245, 0.73966538, 0.68797126,
                0.63451750, 0.58014482, 0.52566725, 0.47185369, 0.41941150, 0.36897272,
                0.32108304, 0.27619388, 0.23465776, 0.19672670, 0.16255380, 0.13219758,
                0.10562887, 0.08273982, 0.06335451, 0.04724088, 0.03412321, 0.02369490,
                0.01563093, 0.00959968, 0.00527363, 0.00233883, 0.00050000, 0.00000000};

            public static readonly double[] kaiser6_table/*[36]*/ = {
                0.99733006, 1.00000000, 0.99733006, 0.98935595, 0.97618418, 0.95799003,
                0.93501423, 0.90755855, 0.87598009, 0.84068475, 0.80211977, 0.76076565,
                0.71712752, 0.67172623, 0.62508937, 0.57774224, 0.53019925, 0.48295561,
                0.43647969, 0.39120616, 0.34752997, 0.30580127, 0.26632152, 0.22934058,
                0.19505503, 0.16360756, 0.13508755, 0.10953262, 0.08693120, 0.06722600,
                0.05031820, 0.03607231, 0.02432151, 0.01487334, 0.00752000, 0.00000000};
        };

        private class QualityMapping
        {
            public int base_length = 0;
            public int oversample = 0;
            public float downsample_bandwidth = 0;
            public float upsample_bandwidth = 0;
            public FuncDef window_func = null;

            private QualityMapping(int bl, int os, float dsb, float usb, FuncDef wf)
            {
                base_length = bl;
                oversample = os;
                downsample_bandwidth = dsb;
                upsample_bandwidth = usb;
                window_func = wf;
            }

            /* This table maps conversion quality to private parameters. There are two
               reasons that explain why the up-sampling bandwidth is larger than the
               down-sampling bandwidth:
               1) When up-sampling, we can assume that the spectrum is already attenuated
                  close to the Nyquist rate (from an A/D or a previous resampling filter)
               2) Any aliasing that occurs very close to the Nyquist rate will be masked
                  by the sinusoids/noise just below the Nyquist rate (guaranteed only for
                  up-sampling).
            */
            public static readonly QualityMapping[] quality_map = {
                new QualityMapping(  8,  4, 0.830f, 0.860f, new FuncDef(FuncDef.kaiser6_table, 32) ), /* Q0 */
                new QualityMapping( 16,  4, 0.850f, 0.880f, new FuncDef(FuncDef.kaiser6_table, 32) ), /* Q1 */
                new QualityMapping( 32,  4, 0.882f, 0.910f, new FuncDef(FuncDef.kaiser6_table, 32) ), /* Q2 */  /* 82.3% cutoff ( ~60 dB stop) 6  */
                new QualityMapping( 48,  8, 0.895f, 0.917f, new FuncDef(FuncDef.kaiser8_table, 32) ), /* Q3 */  /* 84.9% cutoff ( ~80 dB stop) 8  */
                new QualityMapping( 64,  8, 0.921f, 0.940f, new FuncDef(FuncDef.kaiser8_table, 32) ), /* Q4 */  /* 88.7% cutoff ( ~80 dB stop) 8  */
                new QualityMapping( 80, 16, 0.922f, 0.940f, new FuncDef(FuncDef.kaiser10_table, 32)), /* Q5 */  /* 89.1% cutoff (~100 dB stop) 10 */
                new QualityMapping( 96, 16, 0.940f, 0.945f, new FuncDef(FuncDef.kaiser10_table, 32)), /* Q6 */  /* 91.5% cutoff (~100 dB stop) 10 */
                new QualityMapping(128, 16, 0.950f, 0.950f, new FuncDef(FuncDef.kaiser10_table, 32)), /* Q7 */  /* 93.1% cutoff (~100 dB stop) 10 */
                new QualityMapping(160, 16, 0.960f, 0.960f, new FuncDef(FuncDef.kaiser10_table, 32)), /* Q8 */  /* 94.5% cutoff (~100 dB stop) 10 */
                new QualityMapping(192, 32, 0.968f, 0.968f, new FuncDef(FuncDef.kaiser12_table, 64)), /* Q9 */  /* 95.5% cutoff (~100 dB stop) 10 */
                new QualityMapping(256, 32, 0.975f, 0.975f, new FuncDef(FuncDef.kaiser12_table, 64)), /* Q10 */ /* 96.6% cutoff (~100 dB stop) 10 */
            };
        }

        #endregion

        #region Private code

        /// <summary>
        /// typedef int (* resampler_basic_func)(SpeexResamplerState*, int , Pointer<short>, int *, Pointer<short>, Pointer<int>);
        /// </summary>
        private delegate int resampler_basic_func(int channel_index, short[] input, int input_ptr, ref int in_len, short[] output, int output_ptr, ref int out_len);

        private static short WORD2INT(float x)
        {
            return x < short.MinValue ? short.MinValue : (x > short.MaxValue ? short.MaxValue : (short)x);
        }

        /*8,24,40,56,80,104,128,160,200,256,320*/
        private static double compute_func(float x, FuncDef func)
        {
            float y, frac;
            double interp0, interp1, interp2, interp3;
            int ind;
            y = x * func.oversample;
            ind = (int)Math.Floor(y);
            frac = (y - ind);
            /* CSE with handle the repeated powers */
            interp3 = -0.1666666667 * frac + 0.1666666667 * (frac * frac * frac);
            interp2 = frac + 0.5 * (frac * frac) - 0.5 * (frac * frac * frac);
            /*interp[2] = 1.f - 0.5f*frac - frac*frac + 0.5f*frac*frac*frac;*/
            interp0 = -0.3333333333 * frac + 0.5 * (frac * frac) - 0.1666666667 * (frac * frac * frac);
            /* Just to make sure we don't have rounding problems */
            interp1 = 1.0f - interp3 - interp2 - interp0;

            /*sum = frac*accum[1] + (1-frac)*accum[2];*/
            return interp0 * func.table[ind] + interp1 * func.table[ind + 1] + interp2 * func.table[ind + 2] + interp3 * func.table[ind + 3];
        }

        /* The slow way of computing a sinc for the table. Should improve that some day */
        private static short sinc(float cutoff, float x, int N, FuncDef window_func)
        {
            /*fprintf (stderr, "%f ", x);*/
            float xx = x * cutoff;
            if (Math.Abs(x) < 1e-6f)
                return WORD2INT(32768.0f * cutoff);
            else if (Math.Abs(x) > .5f * N)
                return 0;
            /*FIXME: Can it really be any slower than this? */
            return WORD2INT(32768.0f * cutoff * (float)Math.Sin((float)Math.PI * xx) / ((float)Math.PI * xx) * (float)compute_func(Math.Abs(2.0f * x / N), window_func));
        }

        private static void cubic_coef(short x, out short interp0, out short interp1, out short interp2, out short interp3)
        {
            /* Compute interpolation coefficients. I'm not sure whether this corresponds to cubic interpolation
            but I know it's MMSE-optimal on a sinc */
            short x2, x3;
            x2 = Inlines.MULT16_16_P15(x, x);
            x3 = Inlines.MULT16_16_P15(x, x2);
            interp0 = (short)Inlines.PSHR32(Inlines.MULT16_16(Inlines.QCONST16(-0.16667f, 15), x) + Inlines.MULT16_16(Inlines.QCONST16(0.16667f, 15), x3), 15);
            interp1 = Inlines.EXTRACT16(Inlines.EXTEND32(x) + Inlines.SHR32(Inlines.SUB32(Inlines.EXTEND32(x2), Inlines.EXTEND32(x3)), 1));
            interp3 = (short)Inlines.PSHR32(Inlines.MULT16_16(Inlines.QCONST16(-0.33333f, 15), x) + Inlines.MULT16_16(Inlines.QCONST16(.5f, 15), x2) - Inlines.MULT16_16(Inlines.QCONST16(0.16667f, 15), x3), 15);
            /* Just to make sure we don't have rounding problems */
            interp2 = (short)(CeltConstants.Q15_ONE - interp0 - interp1 - interp3);
            if (interp2 < 32767)
                interp2 += 1;
        }

        private int resampler_basic_direct_single(int channel_index, short[] input, int input_ptr, ref int in_len, short[] output, int output_ptr, ref int out_len)
        {
            int N = this.filt_len;
            int out_sample = 0;
            int last_sample = this.last_sample[channel_index];
            int samp_frac_num = this.samp_frac_num[channel_index];

            int sum;

            while (!(last_sample >= in_len || out_sample >= out_len))
            {
                int sinct = (int)samp_frac_num * N;
                int iptr = input_ptr + last_sample;

                int j;
                sum = 0;
                for (j = 0; j < N; j++)
                {
                    sum += Inlines.MULT16_16(this.sinc_table[sinct + j], input[iptr + j]);
                }

                output[output_ptr + (this.out_stride * out_sample++)] = Inlines.SATURATE16(Inlines.PSHR32(sum, 15));
                last_sample += this.int_advance;
                samp_frac_num += (int)this.frac_advance;
                if (samp_frac_num >= this.den_rate)
                {
                    samp_frac_num -= this.den_rate;
                    last_sample++;
                }
            }

            this.last_sample[channel_index] = last_sample;
            this.samp_frac_num[channel_index] = samp_frac_num;
            return out_sample;
        }

        private int resampler_basic_interpolate_single(int channel_index, short[] input, int input_ptr, ref int in_len, short[] output, int output_ptr, ref int out_len)
        {
            int N = this.filt_len;
            int out_sample = 0;
            int last_sample = this.last_sample[channel_index];
            int samp_frac_num = this.samp_frac_num[channel_index];
            int sum;

            while (!(last_sample >= in_len || out_sample >= out_len))
            {
                int iptr = input_ptr + last_sample;

                int offset = samp_frac_num * this.oversample / this.den_rate;
                short frac = (short)Inlines.PDIV32(Inlines.SHL32((samp_frac_num * this.oversample) % this.den_rate, 15), this.den_rate);
                short interp0, interp1, interp2, interp3;

                int j;
                int accum0 = 0;
                int accum1 = 0;
                int accum2 = 0;
                int accum3 = 0;

                for (j = 0; j < N; j++)
                {
                    short curr_in = input[iptr + j];
                    accum0 += Inlines.MULT16_16(curr_in, this.sinc_table[4 + (j + 1) * (int)this.oversample - offset - 2]);
                    accum1 += Inlines.MULT16_16(curr_in, this.sinc_table[4 + (j + 1) * (int)this.oversample - offset - 1]);
                    accum2 += Inlines.MULT16_16(curr_in, this.sinc_table[4 + (j + 1) * (int)this.oversample - offset]);
                    accum3 += Inlines.MULT16_16(curr_in, this.sinc_table[4 + (j + 1) * (int)this.oversample - offset + 1]);
                }

                cubic_coef(frac, out interp0, out interp1, out interp2, out interp3);
                sum =   Inlines.MULT16_32_Q15(interp0, Inlines.SHR32(accum0, 1)) +
                        Inlines.MULT16_32_Q15(interp1, Inlines.SHR32(accum1, 1)) +
                        Inlines.MULT16_32_Q15(interp2, Inlines.SHR32(accum2, 1)) +
                        Inlines.MULT16_32_Q15(interp3, Inlines.SHR32(accum3, 1));

                output[output_ptr + (out_stride * out_sample++)] = Inlines.SATURATE16(Inlines.PSHR32(sum, 14));
                last_sample += int_advance;
                samp_frac_num += (int)frac_advance;
                if (samp_frac_num >= den_rate)
                {
                    samp_frac_num -= den_rate;
                    last_sample++;
                }
            }

            this.last_sample[channel_index] = last_sample;
            this.samp_frac_num[channel_index] = samp_frac_num;
            return out_sample;
        }

        private void update_filter()
        {
            int old_length;

            old_length = this.filt_len;
            this.oversample = QualityMapping.quality_map[this.quality].oversample;
            this.filt_len = QualityMapping.quality_map[this.quality].base_length;

            if (this.num_rate > this.den_rate)
            {
                /* down-sampling */
                this.cutoff = QualityMapping.quality_map[this.quality].downsample_bandwidth * this.den_rate / this.num_rate;
                /* FIXME: divide the numerator and denominator by a certain amount if they're too large */
                this.filt_len = this.filt_len * this.num_rate / this.den_rate;
                /* Round up to make sure we have a multiple of 8 */
                this.filt_len = ((this.filt_len - 1) & (~0x7)) + 8;
                if (2 * this.den_rate < this.num_rate)
                    this.oversample >>= 1;
                if (4 * this.den_rate < this.num_rate)
                    this.oversample >>= 1;
                if (8 * this.den_rate < this.num_rate)
                    this.oversample >>= 1;
                if (16 * this.den_rate < this.num_rate)
                    this.oversample >>= 1;
                if (this.oversample < 1)
                    this.oversample = 1;
            }
            else {
                /* up-sampling */
                this.cutoff = QualityMapping.quality_map[this.quality].upsample_bandwidth;
            }

            if (this.den_rate <= 16 * (this.oversample + 8))
            {
                int i;
                if (this.sinc_table == null)
                    this.sinc_table = new short[this.filt_len * this.den_rate];
                else if (this.sinc_table_length < this.filt_len * this.den_rate)
                {
                    this.sinc_table = new short[this.filt_len * this.den_rate];
                    this.sinc_table_length = this.filt_len * this.den_rate;
                }
                for (i = 0; i < this.den_rate; i++)
                {
                    int j;
                    for (j = 0; j < this.filt_len; j++)
                    {
                        this.sinc_table[i * this.filt_len + j] = sinc(this.cutoff, ((j - (int)this.filt_len / 2 + 1) - ((float)i) / this.den_rate), this.filt_len, QualityMapping.quality_map[this.quality].window_func);
                    }
                }
                this.resampler_ptr = resampler_basic_direct_single;
                /*fprintf (stderr, "resampler uses direct sinc table and normalised cutoff %f\n", cutoff);*/
            }
            else {
                int i;
                if (this.sinc_table == null)
                    this.sinc_table = new short[this.filt_len * this.oversample + 8];
                else if (this.sinc_table_length < this.filt_len * this.oversample + 8)
                {
                    this.sinc_table = new short[this.filt_len * this.oversample + 8];
                    this.sinc_table_length = this.filt_len * this.oversample + 8;
                }
                for (i = -4; i < (int)(this.oversample * this.filt_len + 4); i++)
                    this.sinc_table[i + 4] = sinc(this.cutoff, (i / (float)this.oversample - this.filt_len / 2), this.filt_len, QualityMapping.quality_map[this.quality].window_func);
                this.resampler_ptr = resampler_basic_interpolate_single;
                /*fprintf (stderr, "resampler uses interpolated sinc table and normalised cutoff %f\n", cutoff);*/
            }
            this.int_advance = this.num_rate / this.den_rate;
            this.frac_advance = this.num_rate % this.den_rate;

            /* Here's the place where we update the filter memory to take into account
               the change in filter length. It's probably the messiest part of the code
               due to handling of lots of corner cases. */
            if (this.mem == null)
            {
                int i;
                this.mem_alloc_size = this.filt_len - 1 + this.buffer_size;
                this.mem = new short[this.nb_channels * this.mem_alloc_size];
                for (i = 0; i < this.nb_channels * this.mem_alloc_size; i++)
                    this.mem[i] = 0;
                /*speex_warning("init filter");*/
            }
            else if (this.started == 0)
            {
                int i;
                this.mem_alloc_size = this.filt_len - 1 + this.buffer_size;
                this.mem = new short[this.nb_channels * this.mem_alloc_size];
                for (i = 0; i < this.nb_channels * this.mem_alloc_size; i++)
                    this.mem[i] = 0;
                /*speex_warning("reinit filter");*/
            }
            else if (this.filt_len > old_length)
            {
                int i;
                /* Increase the filter length */
                /*speex_warning("increase filter size");*/
                int old_alloc_size = this.mem_alloc_size;
                if ((this.filt_len - 1 + this.buffer_size) > this.mem_alloc_size)
                {
                    this.mem_alloc_size = this.filt_len - 1 + this.buffer_size;
                    this.mem = new short[this.nb_channels * this.mem_alloc_size];
                }
                for (i = this.nb_channels - 1; i >= 0; i--)
                {
                    int j;
                    int olen = old_length;
                    /*if (st.magic_samples[i])*/
                    {
                        /* Try and remove the magic samples as if nothing had happened */

                        /* FIXME: This is wrong but for now we need it to avoid going over the array bounds */
                        olen = old_length + 2 * this.magic_samples[i];
                        for (j = old_length - 2 + this.magic_samples[i]; j >= 0; j--)
                            this.mem[i * this.mem_alloc_size + j + this.magic_samples[i]] = this.mem[i * old_alloc_size + j];
                        for (j = 0; j < this.magic_samples[i]; j++)
                            this.mem[i * this.mem_alloc_size + j] = 0;
                        this.magic_samples[i] = 0;
                    }
                    if (this.filt_len > olen)
                    {
                        /* If the new filter length is still bigger than the "augmented" length */
                        /* Copy data going backward */
                        for (j = 0; j < olen - 1; j++)
                            this.mem[i * this.mem_alloc_size + (this.filt_len - 2 - j)] = this.mem[i * this.mem_alloc_size + (olen - 2 - j)];
                        /* Then put zeros for lack of anything better */
                        for (; j < this.filt_len - 1; j++)
                            this.mem[i * this.mem_alloc_size + (this.filt_len - 2 - j)] = 0;
                        /* Adjust last_sample */
                        this.last_sample[i] += (this.filt_len - olen) / 2;
                    }
                    else {
                        /* Put back some of the magic! */
                        this.magic_samples[i] = (olen - this.filt_len) / 2;
                        for (j = 0; j < this.filt_len - 1 + this.magic_samples[i]; j++)
                            this.mem[i * this.mem_alloc_size + j] = this.mem[i * this.mem_alloc_size + j + this.magic_samples[i]];
                    }
                }
            }
            else if (this.filt_len < old_length)
            {
                int i;
                /* Reduce filter length, this a bit tricky. We need to store some of the memory as "magic"
                   samples so they can be used directly as input the next time(s) */
                for (i = 0; i < this.nb_channels; i++)
                {
                    int j;
                    int old_magic = this.magic_samples[i];
                    this.magic_samples[i] = (old_length - this.filt_len) / 2;
                    /* We must copy some of the memory that's no longer used */
                    /* Copy data going backward */
                    for (j = 0; j < this.filt_len - 1 + this.magic_samples[i] + old_magic; j++)
                        this.mem[i * this.mem_alloc_size + j] = this.mem[i * this.mem_alloc_size + j + this.magic_samples[i]];
                    this.magic_samples[i] += old_magic;
                }
            }
        }

        private void speex_resampler_process_native(int channel_index, ref int in_len, short[] output, int output_ptr, ref int out_len)
        {
            int j = 0;
            int N = this.filt_len;
            int out_sample = 0;
            int mem_ptr = channel_index * this.mem_alloc_size;
            int ilen;

            this.started = 1;

            /* Call the right resampler through the function ptr */
            out_sample = this.resampler_ptr(channel_index, this.mem, mem_ptr, ref in_len, output, output_ptr, ref out_len);

            if (this.last_sample[channel_index] < (int)in_len)
                in_len = this.last_sample[channel_index];
            out_len = out_sample;
            this.last_sample[channel_index] -= in_len;

            ilen = in_len;

            for (j = mem_ptr; j < N - 1 + mem_ptr; ++j)
                this.mem[j] = this.mem[j + ilen];
        }

        private int speex_resampler_magic(int channel_index, short[] output, ref int output_ptr, int out_len)
        {
            int tmp_in_len = this.magic_samples[channel_index];
            int mem_ptr = channel_index * this.mem_alloc_size;
            int N = this.filt_len;

            this.speex_resampler_process_native(channel_index, ref tmp_in_len, output, output_ptr, ref out_len);

            this.magic_samples[channel_index] -= tmp_in_len;

            /* If we couldn't process all "magic" input samples, save the rest for next time */
            if (this.magic_samples[channel_index] != 0)
            {
                int i;
                for (i = mem_ptr; i < this.magic_samples[channel_index] + mem_ptr; i++)
                    this.mem[N - 1 + i] = this.mem[N - 1 + i + tmp_in_len];
            }
            output_ptr += out_len * this.out_stride;
            return out_len;
        }

        #endregion

        #region Public API

        /// <summary>
        /// Create a new resampler with integer input and output rates (in hertz).
        /// </summary>
        /// <param name="nb_channels">The number of channels to be processed</param>
        /// <param name="in_rate">Input sampling rate, in hertz</param>
        /// <param name="out_rate">Output sampling rate, in hertz</param>
        /// <param name="quality">Resampling quality, from 0 to 10</param>
        public SpeexResampler(int nb_channels, int in_rate, int out_rate, int quality) : this(nb_channels, in_rate, out_rate, in_rate, out_rate, quality)
        {
        }

        /// <summary>
        /// Create a new resampler with fractional input/output rates. The sampling
        /// rate ratio is an arbitrary rational number with both the numerator and
        /// denominator being 32-bit integers.
        /// </summary>
        /// <param name="nb_channels">The number of channels to be processed</param>
        /// <param name="ratio_num">Numerator of sampling rate ratio</param>
        /// <param name="ratio_den">Denominator of sampling rate ratio</param>
        /// <param name="in_rate">Input sample rate rounded to the nearest integer (in hz)</param>
        /// <param name="out_rate">Output sample rate rounded to the nearest integer (in hz)</param>
        /// <param name="quality">Resampling quality, from 0 to 10</param>
        /// <returns>A newly created restampler</returns>
        public SpeexResampler(int nb_channels, int ratio_num, int ratio_den, int in_rate, int out_rate, int quality)
        {
            int i;
            if (quality > 10 || quality < 0)
            {
                throw new ArgumentException("Quality must be between 0 and 10");
            }
            this.initialised = 0;
            this.started = 0;
            this.in_rate = 0;
            this.out_rate = 0;
            this.num_rate = 0;
            this.den_rate = 0;
            this.quality = -1;
            this.sinc_table_length = 0;
            this.mem_alloc_size = 0;
            this.filt_len = 0;
            this.mem = null;
            this.resampler_ptr = null;
            this.cutoff = 1.0f;
            this.nb_channels = nb_channels;
            this.in_stride = 1;
            this.out_stride = 1;
            this.buffer_size = 160;

            /* Per channel data */
            this.last_sample = new int[nb_channels];
            this.magic_samples = new int[nb_channels];
            this.samp_frac_num = new int[nb_channels];
            for (i = 0; i < nb_channels; i++)
            {
                this.last_sample[i] = 0;
                this.magic_samples[i] = 0;
                this.samp_frac_num[i] = 0;
            }

            this.Quality = quality;
            this.SetRateFraction(ratio_num, ratio_den, in_rate, out_rate);

            this.update_filter();

            this.initialised = 1;
        }

        public static SpeexResampler Create(int nb_channels, int in_rate, int out_rate, int quality)
        {
            return new SpeexResampler(nb_channels, in_rate, out_rate, in_rate, out_rate, quality);
        }

        /// <summary>
        /// DEPRECATED. Use the regular constructor instead.
        /// </summary>
        public static SpeexResampler Create(int nb_channels, int ratio_num, int ratio_den, int in_rate, int out_rate, int quality)
        {
            return new SpeexResampler(nb_channels, ratio_num, ratio_den, in_rate, out_rate, quality);
        }

        /// <summary>
        /// Resample an int array. The input and output buffers must *not* overlap
        /// </summary>
        /// <param name="channel_index">The index of the channel to process (for multichannel input, 0 otherwise)</param>
        /// <param name="input">Input buffer</param>
        /// <param name="input_ptr">Offset to start from when reading input</param>
        /// <param name="in_len">Number of input samples in the input buffer. After this function returns, this value
        /// will be set to the number of input samples actually processed</param>
        /// <param name="output">Output buffer</param>
        /// <param name="output_ptr">Offset to start from when writing output</param>
        /// <param name="out_len">Size of the output buffer. After this function returns, this value will be set to the number
        /// of output samples actually produced</param>
        public void Process(int channel_index, short[] input, int input_ptr, ref int in_len, short[] output, int output_ptr, ref int out_len)
        {
            int j;
            int ilen = in_len;
            int olen = out_len;
            int x = channel_index * this.mem_alloc_size;
            int filt_offs = this.filt_len - 1;
            int xlen = this.mem_alloc_size - filt_offs;
            int istride = this.in_stride;

            if (this.magic_samples[channel_index] != 0)
            {

                olen -= this.speex_resampler_magic(channel_index, output, ref output_ptr, olen);

            }
            if (this.magic_samples[channel_index] == 0)
            {
                while (ilen != 0 && olen != 0)
                {
                    int ichunk = (ilen > xlen) ? xlen : ilen;
                    int ochunk = olen;

                    if (input != null)
                    {
                        for (j = 0; j < ichunk; ++j)
                            this.mem[x + j + filt_offs] = input[input_ptr + j * istride];
                    }
                    else {
                        for (j = 0; j < ichunk; ++j)

                            this.mem[x + j + filt_offs] = 0;
                    }
                    this.speex_resampler_process_native(channel_index, ref ichunk, output, output_ptr, ref ochunk);
                    ilen -= ichunk;
                    olen -= ochunk;
                    output_ptr += ochunk * this.out_stride;
                    if (input != null)

                        input_ptr += ichunk * istride;
                }
            }
            in_len -= ilen;
            out_len -= olen;
        }

        /// <summary>
        /// Resample a float array array. The input and output buffers must *not* overlap
        /// </summary>
        /// <param name="channel_index">The index of the channel to process (for multichannel input, 0 otherwise)</param>
        /// <param name="input">Input buffer</param>
        /// <param name="input_ptr">Offset to start from when reading input</param>
        /// <param name="in_len">Number of input samples in the input buffer. After this function returns, this value
        /// will be set to the number of input samples actually processed</param>
        /// <param name="output">Output buffer</param>
        /// <param name="output_ptr">Offset to start from when writing output</param>
        /// <param name="out_len">Size of the output buffer. After this function returns, this value will be set to the number
        /// of output samples actually produced</param>
        public void Process(int channel_index, float[] input, int input_ptr, ref int in_len, float[] output, int output_ptr, ref int out_len)
        {
            int j;
            int istride_save = this.in_stride;
            int ostride_save = this.out_stride;
            int ilen = in_len;
            int olen = out_len;
            int x = channel_index * this.mem_alloc_size;
            int xlen = this.mem_alloc_size - (this.filt_len - 1);
            int ylen = (olen < FIXED_STACK_ALLOC) ? olen : FIXED_STACK_ALLOC;
            short[] ystack = new short[ylen];

            this.out_stride = 1;

            while (ilen != 0 && olen != 0)
            {

                int y = 0;
                int ichunk = (ilen > xlen) ? xlen : ilen;
                int ochunk = (olen > ylen) ? ylen : olen;
                int omagic = 0;

                if (this.magic_samples[channel_index] != 0)
                {

                    omagic = this.speex_resampler_magic(channel_index, ystack, ref y, ochunk);

                    ochunk -= omagic;
                    olen -= omagic;
                }
                if (this.magic_samples[channel_index] == 0)
                {
                    if (input != null)
                    {
                        for (j = 0; j < ichunk; ++j)
                            this.mem[x + j + this.filt_len - 1] = WORD2INT(input[input_ptr + j * istride_save]);
                    }
                    else {
                        for (j = 0; j < ichunk; ++j)
                            this.mem[x + j + this.filt_len - 1] = 0;
                    }

                    this.speex_resampler_process_native(channel_index, ref ichunk, ystack, y, ref ochunk);
                }
                else {
                    ichunk = 0;
                    ochunk = 0;
                }

                for (j = 0; j < ochunk + omagic; ++j)
                    output[output_ptr + j * ostride_save] = ystack[j];

                ilen -= ichunk;
                olen -= ochunk;
                output_ptr += ((ochunk + omagic) * ostride_save);
                if (input != null)
                    input_ptr += ichunk * istride_save;
            }
            this.out_stride = ostride_save;
            in_len -= ilen;
            out_len -= olen;
        }

        /// <summary>
        /// Resamples an interleaved int array. The stride is automatically determined by the number of channels of the resampler.
        /// </summary>
        /// <param name="input">Input buffer</param>
        /// <param name="input_ptr">Offset to start from when reading input</param>
        /// <param name="in_len">The number of samples *PER-CHANNEL* in the input buffer. After this function returns, this
        /// value will be set to the number of input samples actually processed</param>
        /// <param name="output">Output buffer</param>
        /// <param name="output_ptr">Offset to start from when writing output</param>
        /// <param name="out_len">The size of the output buffer in samples-per-channel. After this function returns, this value
        /// will be set to the number of samples per channel actually produced</param>
        public void ProcessInterleaved(float[] input, int input_ptr, ref int in_len, float[] output, int output_ptr, ref int out_len)
        {
            int i;
            int istride_save, ostride_save;
            int bak_out_len = out_len;
            int bak_in_len = in_len;
            istride_save = this.in_stride;
            ostride_save = this.out_stride;
            this.in_stride = this.out_stride = this.nb_channels;
            for (i = 0; i < this.nb_channels; i++)
            {
                out_len = bak_out_len;
                in_len = bak_in_len;
                if (input != null)
                    this.Process(i, input, input_ptr + i, ref in_len, output, output_ptr + i, ref out_len);
                else
                    this.Process(i, null, 0, ref in_len, output, output_ptr + i, ref out_len);
            }
            this.in_stride = istride_save;
            this.out_stride = ostride_save;
        }

        /// <summary>
        /// Resamples an interleaved float array. The stride is automatically determined by the number of channels of the resampler.
        /// </summary>
        /// <param name="input">Input buffer</param>
        /// <param name="input_ptr">Offset to start from when reading input</param>
        /// <param name="in_len">The number of samples *PER-CHANNEL* in the input buffer. After this function returns, this
        /// value will be set to the number of input samples actually processed</param>
        /// <param name="output">Output buffer</param>
        /// <param name="output_ptr">Offset to start from when writing output</param>
        /// <param name="out_len">The size of the output buffer in samples-per-channel. After this function returns, this value
        /// will be set to the number of samples per channel actually produced</param>
        public void ProcessInterleaved(short[] input, int input_ptr, ref int in_len, short[] output, int output_ptr, ref int out_len)
        {
            int i;
            int istride_save, ostride_save;
            int bak_out_len = out_len;
            int bak_in_len = in_len;
            istride_save = this.in_stride;
            ostride_save = this.out_stride;
            this.in_stride = this.out_stride = this.nb_channels;
            for (i = 0; i < this.nb_channels; i++)
            {
                out_len = bak_out_len;
                in_len = bak_in_len;
                if (input != null)
                    this.Process(i, input, input_ptr + i, ref in_len, output, output_ptr + i, ref out_len);
                else
                    this.Process(i, null, 0, ref in_len, output, output_ptr + i, ref out_len);
            }
            this.in_stride = istride_save;
            this.out_stride = ostride_save;
        }

        /// <summary>
        /// Make sure that the first samples to go out of the resamplers don't have
        /// leading zeros. This is only useful before starting to use a newly created
        /// resampler. It is recommended to use that when resampling an audio file, as
        /// it will generate a file with the same length.For real-time processing,
        /// it is probably easier not to use this call (so that the output duration
        /// is the same for the first frame).
        /// </summary>
        public void SkipZeroes()
        {
            int i;
            for (i = 0; i < this.nb_channels; i++)
                this.last_sample[i] = this.filt_len / 2;
        }

        /// <summary>
        /// Clears the resampler buffers so a new (unrelated) stream can be processed.
        /// </summary>
        public void ResetMem()
        {
            int i;
            for (i = 0; i < this.nb_channels; i++)
            {
                this.last_sample[i] = 0;
                this.magic_samples[i] = 0;
                this.samp_frac_num[i] = 0;
            }
            for (i = 0; i < this.nb_channels * (this.filt_len - 1); i++)
                this.mem[i] = 0;
        }

        #endregion

        #region Getters and Setters

        /// <summary>
        /// Sets the input and output rates
        /// </summary>
        /// <param name="in_rate">Input sampling rate, in hertz</param>
        /// <param name="out_rate">Output sampling rate, in hertz</param>
        public void SetRates(int in_rate, int out_rate)
        {
            this.SetRateFraction(in_rate, out_rate, in_rate, out_rate);
        }

        /// <summary>
        /// Get the current input/output sampling rates (integer value).
        /// </summary>
        /// <param name="in_rate">(Output) Sampling rate of input</param>
        /// <param name="out_rate">(Output) Sampling rate of output</param>
        public void GetRates(out int in_rate, out int out_rate)
        {
            in_rate = this.in_rate;
            out_rate = this.out_rate;
        }

        /// <summary>
        /// Sets the input/output sampling rates and resampling ration (fractional values in Hz supported)
        /// </summary>
        /// <param name="ratio_num">Numerator of the sampling rate ratio</param>
        /// <param name="ratio_den">Denominator of the sampling rate ratio</param>
        /// <param name="in_rate">Input sampling rate rounded to the nearest integer (in Hz)</param>
        /// <param name="out_rate">Output sampling rate rounded to the nearest integer (in Hz)</param>
        public void SetRateFraction(int ratio_num, int ratio_den, int in_rate, int out_rate)
        {
            int fact;
            int old_den;
            int i;
            if (this.in_rate == in_rate && this.out_rate == out_rate && this.num_rate == ratio_num && this.den_rate == ratio_den)
                return;

            old_den = this.den_rate;
            this.in_rate = in_rate;
            this.out_rate = out_rate;
            this.num_rate = ratio_num;
            this.den_rate = ratio_den;
            /* FIXME: This is terribly inefficient, but who cares (at least for now)? */
            for (fact = 2; fact <= Inlines.IMIN(this.num_rate, this.den_rate); fact++)
            {
                while ((this.num_rate % fact == 0) && (this.den_rate % fact == 0))
                {
                    this.num_rate /= fact;
                    this.den_rate /= fact;
                }
            }

            if (old_den > 0)
            {
                for (i = 0; i < this.nb_channels; i++)
                {
                    this.samp_frac_num[i] = this.samp_frac_num[i] * this.den_rate / old_den;
                    /* Safety net */
                    if (this.samp_frac_num[i] >= this.den_rate)
                        this.samp_frac_num[i] = this.den_rate - 1;
                }
            }

            if (this.initialised != 0)
                this.update_filter();
        }

        /// <summary>
        /// Gets the current resampling ratio. This will be reduced to the least common denominator
        /// </summary>
        /// <param name="ratio_num">(Output) numerator of the sampling rate ratio</param>
        /// <param name="ratio_den">(Output) denominator of the sampling rate ratio</param>
        public void GetRateFraction(out int ratio_num, out int ratio_den)
        {
            ratio_num = this.num_rate;
            ratio_den = this.den_rate;
        }

        /// <summary>
        /// Gets or sets the resampling quality between 0 and 10, where 0 has poor
        /// quality and 10 has very high quality.
        /// </summary>
        public int Quality
        {
            get
            {
                return this.quality;
            }
            set
            {
                if (value > 10 || value < 0)
                    throw new ArgumentException("Quality must be between 0 and 10");
                if (this.quality == value)
                    return;
                this.quality = value;
                if (this.initialised != 0)
                    this.update_filter();
            }
        }

        /// <summary>
        /// Gets or sets the input stride
        /// </summary>
        public int InputStride
        {
            get
            {
                return this.in_stride;
            }
            set
            {
                this.in_stride = value;
            }
        }

        /// <summary>
        /// Gets or sets the output stride
        /// </summary>
        public int OutputStride
        {
            get
            {
                return this.out_stride;
            }
            set
            {
                this.out_stride = value;
            }
        }

        /// <summary>
        /// Get the latency introduced by the resampler measured in input samples.
        /// </summary>
        public int InputLatency
        {
            get
            {
                return this.filt_len / 2;
            }
        }

        /// <summary>
        /// Gets the latency introduced by the resampler measured in output samples.
        /// </summary>
        public int OutputLatency
        {
            get
            {
                return ((this.filt_len / 2) * this.den_rate + (this.num_rate >> 1)) / this.num_rate;
            }
        }

        #endregion
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_hello_wold"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.mcodegeeks.tutorial.T01_HelloWold.T01MainActivity">

    <TextView
        android:id="@+id/titleView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/t01_title"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:textSize="20dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world" />

</RelativeLayout>


text:
'use strict';

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

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

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

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

var factory = function factory(Checkbox) {
  var TableHead = function TableHead(_ref) {
    var model = _ref.model,
        onSelect = _ref.onSelect,
        selectable = _ref.selectable,
        multiSelectable = _ref.multiSelectable,
        selected = _ref.selected,
        theme = _ref.theme;

    var selectCell = void 0;
    var contentCells = Object.keys(model).map(function (key) {
      var name = model[key].title || key;
      return _react2.default.createElement(
        'th',
        { key: key },
        name
      );
    });

    if (selectable && multiSelectable) {
      selectCell = _react2.default.createElement(
        'th',
        { key: 'select', className: theme.selectable },
        _react2.default.createElement(Checkbox, { onChange: onSelect, checked: selected })
      );
    } else if (selectable) {
      selectCell = _react2.default.createElement('th', { key: 'select', className: theme.selectable });
    }
    return _react2.default.createElement(
      'thead',
      null,
      _react2.default.createElement(
        'tr',
        null,
        [selectCell].concat(_toConsumableArray(contentCells))
      )
    );
  };

  TableHead.propTypes = {
    className: _react.PropTypes.string,
    model: _react.PropTypes.object,
    multiSelectable: _react.PropTypes.bool,
    onSelect: _react.PropTypes.func,
    selectable: _react.PropTypes.bool,
    selected: _react.PropTypes.bool,
    theme: _react.PropTypes.shape({
      selectable: _react.PropTypes.string
    })
  };

  TableHead.defaultProps = {
    className: '',
    model: {},
    selected: false
  };

  return TableHead;
};

exports.default = factory;


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                "http://www.w3.org/TR/REC-html40/loose.dtd">

  <title>Description of plx_ad</title>
  <meta name="keywords" content="plx_ad">
  <meta name="description" content="plx_ad(filename, channel): Read a/d data from a .plx file">
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  <meta name="generator" content="m2html © 2003 Guillaume Flandin">
  <meta name="robots" content="index, follow">
  <link type="text/css" rel="stylesheet" href="../../../m2html.css">

Home >  chronux_2_00 > dataio > ReadingPLXandDDTfilesinMatlab > plx_ad.m

plx_ad

PURPOSE

plx_ad(filename, channel): Read a/d data from a .plx file

SYNOPSIS

function [adfreq, n, ts, fn, ad] = plx_ad(filename, ch)

DESCRIPTION

 plx_ad(filename, channel): Read a/d data from a .plx file

 [adfreq, n, ts, fn, ad] = plx_ad(filename, ch)

 INPUT:
   filename - if empty string, will use File Open dialog
   channel - 0 - based channel number

           a/d data come in fragments. Each fragment has a timestamp
           and a number of a/d data points. The timestamp corresponds to
           the time of recording of the first a/d value in this fragment.
           All the data values stored in the vector ad.
 OUTPUT:
   n - total number of data points
   ts - array of fragment timestamps (one timestamp for fragment, in seconds)
   fn - number of data points in each fragment
   ad - array of raw a/d values

CROSS-REFERENCE INFORMATION

This function calls:

This function is called by:

SOURCE CODE

0001 function [adfreq, n, ts, fn, ad] = plx_ad(filename, ch)
0002 % plx_ad(filename, channel): Read a/d data from a .plx file
0003 %
0004 % [adfreq, n, ts, fn, ad] = plx_ad(filename, ch)
0005 %
0006 % INPUT:
0007 %   filename - if empty string, will use File Open dialog
0008 %   channel - 0 - based channel number
0009 %
0010 %           a/d data come in fragments. Each fragment has a timestamp
0011 %           and a number of a/d data points. The timestamp corresponds to
0012 %           the time of recording of the first a/d value in this fragment.
0013 %           All the data values stored in the vector ad.
0014 % OUTPUT:
0015 %   n - total number of data points
0016 %   ts - array of fragment timestamps (one timestamp for fragment, in seconds)
0017 %   fn - number of data points in each fragment
0018 %   ad - array of raw a/d values
0019
0020 if(nargin ~= 2)
0021    disp('2 input arguments are required')
0022    return
0023 end
0024
0025 i = 0;
0026 n = 0;
0027 ts = 0;
0028 fn = 0;
0029 ad = 0;
0030
0031 if(isempty(filename))
0032    [fname, pathname] = uigetfile('*.plx', 'Select a plx file');
0033     filename = strcat(pathname, fname);
0034 end
0035
0036 fid = fopen(filename, 'r');
0037 if(fid == -1)
0038     disp('cannot open file');
0039    return
0040 end
0041
0042 % calculate file size
0043 fseek(fid, 0, 'eof');
0044 fsize = ftell(fid);
0045 fseek(fid, 0, 'bof');
0046
0047
0048 disp(strcat('file = ', filename));
0049
0050 % read file header
0051 header = fread(fid, 64, 'int32');
0052 freq = header(35);  % frequency
0053 ndsp = header(36);  % number of dsp channels
0054 nevents = header(37); % number of external events
0055 nslow = header(38);  % number of slow channels
0056 npw = header(39);  % number of points in wave
0057 npr = header(40);  % number of points before threshold
0058 tscounts = fread(fid, [5, 130], 'int32');
0059 wfcounts = fread(fid, [5, 130], 'int32');
0060 evcounts = fread(fid, [1, 512], 'int32');
0061
0062 % A/D counts are stored in evcounts (301, 302, etc.)
0063 count = 0;
0064 if evcounts(301+ch) > 0
0065     count = evcounts(301+ch);
0066     ad = 1:count;
0067 end
0068
0069 % skip DSP and Event headers
0070 fseek(fid, 1020*ndsp + 296*nevents, 'cof');
0071
0072 % read one A/D header and get the frequency
0073 adheader = fread(fid, 74, 'int32');
0074 adfreq = adheader(10);
0075
0076 % skip all other a/d headers
0077 fseek(fid, 296*(nslow-1), 'cof');
0078
0079 record = 0;
0080
0081 wf = zeros(1, npw);
0082 adpos = 1;
0083
0084 while feof(fid) == 0
0085    type = fread(fid, 1, 'int16');
0086     upperbyte = fread(fid, 1, 'int16');
0087     timestamp = fread(fid, 1, 'int32');
0088     channel = fread(fid, 1, 'int16');
0089    unit = fread(fid, 1, 'int16');
0090    nwf = fread(fid, 1, 'int16');
0091    nwords = fread(fid, 1, 'int16');
0092    if nwords > 0
0093       wf = fread(fid, [1 nwords], 'int16');
0094    end
0095    if nwords > 0
0096       if type == 5
0097          if channel == ch
0098             i = i + 1;
0099             n = n + nwords;
0100              ts(i) = timestamp/freq;
0101             fn(i) = nwords;
0102             if count > 0
0103                 if adpos+nwords-1 <= count
0104                     ad(adpos:adpos+nwords-1) = wf(1:nwords);
0105                     adpos = adpos + nwords;
0106                 else
0107                     for i=1:nwords
0108                         ad(adpos) = wf(i); adpos = adpos + 1;
0109                     end
0110                 end
0111             else
0112                 ad = [ad wf(1, 1:nwords)];
0113             end
0114            end
0115       end
0116    end
0117
0118    record = record + 1;
0119    if mod(record, 1000) == 0
0120        disp(sprintf('records %d points %d (%.1f%%)', record, n, 100*ftell(fid)/fsize));
0121    end
0122
0123    if feof(fid) == 1
0124       break
0125    end
0126
0127 end
0128
0129 if adpos-1 < count
0130    ad = ad(1:adpos-1);
0131 end
0132
0133 disp(strcat('number of data points = ', num2str(n)));
0134
0135 fclose(fid);

<address>Generated on Fri 15-Aug-2008 11:35:42 by m2html © 2003</address>


text:
#ifndef __PING_H__
#define __PING_H__
#include "lwip/ip_addr.h"
#include "lwip/icmp.h"
/**
 * PING_USE_SOCKETS: Set to 1 to use sockets, otherwise the raw api is used
 */
#ifndef PING_USE_SOCKETS
#define PING_USE_SOCKETS    LWIP_SOCKET
#endif

/**
 * PING_DEBUG: Enable debugging for PING.
 */
#ifndef PING_DEBUG
#define PING_DEBUG     LWIP_DBG_OFF
#endif

/** ping receive timeout - in milliseconds */
#ifndef PING_RCV_TIMEO
#define PING_RCV_TIMEO 1000
#endif

/** ping delay - in milliseconds */
#ifndef PING_COARSE
#define PING_COARSE     1000
#endif

/** ping identifier - must fit on a u16_t */
#ifndef PING_ID
#define PING_ID        0xAFAF
#endif

/** ping additional data size to include in the packet */
#ifndef PING_DATA_SIZE
#define PING_DATA_SIZE 32
#endif

/** ping result action - no default action */
#ifndef PING_RESULT
#define PING_RESULT(ping_ok)
#endif

#define DEFAULT_PING_MAX_COUNT 4
#define PING_TIMEOUT_MS 1000

typedef void (* ping_recv_function)(void* arg, void *pdata);
typedef void (* ping_sent_function)(void* arg, void *pdata);

struct ping_option{
	uint32 count;
	uint32 ip;
	uint32 coarse_time;
	ping_recv_function recv_function;
	ping_sent_function sent_function;
	void* reverse;
};

struct ping_msg{
	struct ping_option *ping_opt;
	struct raw_pcb *ping_pcb;
	uint32 ping_start;
	uint32 ping_sent;
	uint32 timeout_count;
	uint32 max_count;
	uint32 sent_count;
	uint32 coarse_time;
};

struct ping_resp{
	uint32 total_count;
	uint32 resp_time;
	uint32 seqno;
	uint32 timeout_count;
	uint32 bytes;
	uint32 total_bytes;
	uint32 total_time;
	sint8  ping_err;
};

bool ping_start(struct ping_option *ping_opt);
bool ping_regist_recv(struct ping_option *ping_opt, ping_recv_function ping_recv);
bool ping_regist_sent(struct ping_option *ping_opt, ping_sent_function ping_sent);

#endif /* __PING_H__ */


text:
package utils;

import java.util.ArrayList;
import java.util.HashSet;

import structure.DPoint;
import utils.ConvexHull;

public class DPolygon {

	public ArrayList<DPoint> polygon;

	public DPolygon(ArrayList<DPoint> set){
		polygon=ConvexHull.getPolygon(set);
	}
	public String toString(){
		return polygon.toString();
	}
}