text:
package com.renard.ocr.documents.creation.crop;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.widget.ImageView;

/**
 * 支持触摸操作的ImageView
 */
public abstract class ImageViewTouchBase extends ImageView {

    @SuppressWarnings("unused")
    private static final String TAG = "ImageViewTouchBase";
    public static final int TRANSITION_DURATION = 500;

    // This is the base transformation which is used to show the image
    // initially.  The current computation for this shows the image in
    // it's entirety, letterboxing as needed.  One could choose to
    // show the image as cropped instead.
    //
    // This matrix is recomputed when we go from the thumbnail image to
    // the full size image.
    protected Matrix mBaseMatrix = new Matrix();

    // This is the supplementary transformation which reflects what
    // the user has done in terms of zooming and panning.
    //
    // This matrix remains the same when we go from the thumbnail image
    // to the full size image.
    protected Matrix mSuppMatrix = new Matrix();//辅助作用的matrix

    // This is the final matrix which is computed as the concatentation
    // of the base matrix and the supplementary matrix.
    private final Matrix mDisplayMatrix = new Matrix();

    // Temporary buffer used for getting the values out of a matrix.
    private final float[] mMatrixValues = new float[9];

    // The current bitmap being displayed.
    final protected RotateBitmap mBitmapDisplayed = new RotateBitmap(null);//当前界面显示的bitmap,可能是发生了旋转

    int mThisWidth = -1, mThisHeight = -1;

    float mMaxZoom;
    int mLeft;
    int mRight;
    int mTop;
    int mBottom;

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        mLeft = left;
        mRight = right;
        mTop = top;
        mBottom = bottom;
        mThisWidth = right - left;
        mThisHeight = bottom - top;
        Runnable r = mOnLayoutRunnable;
        if (r != null) {
            mOnLayoutRunnable = null;
            r.run();
        }
        if (mBitmapDisplayed.getBitmap() != null) {
            getProperBaseMatrix(mBitmapDisplayed, mBaseMatrix);
            setImageMatrix(getImageViewMatrix());
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && getScale() > 1.0f) {
            // If we're zoomed in, pressing Back jumps out to show the entire
            // image, otherwise Back returns the user to the gallery.
            zoomTo(1.0f);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    protected Handler mHandler = new Handler();

    @Override
    public void setImageBitmap(Bitmap bitmap) {
        setImageBitmap(bitmap, 0);
    }

    private void setImageBitmap(final Bitmap bitmap, final int rotation) {
        final Bitmap old = mBitmapDisplayed.getBitmap();

        if (bitmap == null) {
            ImageViewTouchBase.super.setImageBitmap(null);
            clear();
            mBitmapDisplayed.setBitmap(null);
            return;
        }

        if (getDrawable() != null) {
            TransitionDrawable oldTransition = (TransitionDrawable) getDrawable();
            oldTransition.resetTransition();
            if (oldTransition.getNumberOfLayers() == 2) {
                BitmapDrawable layer0 = (BitmapDrawable) oldTransition.getDrawable(0);
                layer0.getBitmap().recycle();
            }
            if (old.getHeight() != bitmap.getHeight() || old.getWidth() != bitmap.getWidth() || mBitmapDisplayed.getRotation() != rotation) {
                if (oldTransition.getNumberOfLayers() == 2) {
                    BitmapDrawable layer1 = (BitmapDrawable) oldTransition.getDrawable(1);
                    layer1.getBitmap().recycle();
                }
                BitmapDrawable layers[] = new BitmapDrawable[]{new BitmapDrawable(getResources(), bitmap)};
                TransitionDrawable transitionDrawable = new TransitionDrawable(layers);
                setImageDrawable(transitionDrawable);
            } else {
                BitmapDrawable layers[] = new BitmapDrawable[]{new BitmapDrawable(getResources(), old), new BitmapDrawable(getResources(), bitmap)};
                TransitionDrawable transitionDrawable = new TransitionDrawable(layers);
                setImageDrawable(transitionDrawable);
                transitionDrawable.startTransition(TRANSITION_DURATION);
            }

        } else {
            BitmapDrawable layers[] = new BitmapDrawable[]{new BitmapDrawable(getResources(), bitmap)};
            TransitionDrawable transitionDrawable = new TransitionDrawable(layers);
            setImageDrawable(transitionDrawable);
        }
        mBitmapDisplayed.setBitmap(bitmap);
        mBitmapDisplayed.setRotation(rotation);

    }

    public void clear() {
        final Drawable drawable = getDrawable();
        if (drawable != null && drawable instanceof BitmapDrawable) {
            BitmapDrawable bd = (BitmapDrawable) getDrawable();
            if (bd.getBitmap() != null) {
                bd.getBitmap().recycle();
            }
        } else if (drawable != null && drawable instanceof TransitionDrawable) {
            for (int i = 0; i < ((TransitionDrawable) drawable).getNumberOfLayers(); i++) {
                BitmapDrawable layer = (BitmapDrawable) ((TransitionDrawable) drawable).getDrawable(i);
                if (layer.getBitmap() != null) {
                    layer.getBitmap().recycle();
                }
            }
        }
    }

    private Runnable mOnLayoutRunnable = null;

    // This function changes bitmap, reset base matrix according to the size
    // of the bitmap, and optionally reset the supplementary matrix.
    //图片发生了变化(比如native层已经修改了图片)所以要重置图片的matrix,甚至要重置图片的辅助matrix
    public void setImageBitmapResetBase(final Bitmap bitmap, final boolean resetSupp, int rotation) {
        setImageRotateBitmapResetBase(new RotateBitmap(bitmap, rotation), resetSupp);
    }

    public void setImageRotateBitmapResetBase(final RotateBitmap bitmap, final boolean resetSupp) {
        final int viewWidth = getWidth();

        if (viewWidth <= 0) {
            mOnLayoutRunnable = new Runnable() {
                public void run() {
                    setImageRotateBitmapResetBase(bitmap, resetSupp);
                }
            };
            return;
        }

        if (bitmap.getBitmap() != null) {
            getProperBaseMatrix(bitmap, mBaseMatrix);
            setImageBitmap(bitmap.getBitmap(), bitmap.getRotation());
        } else {
            mBaseMatrix.reset();
            setImageBitmap(null);
        }

        if (resetSupp) {
            mSuppMatrix.reset();
        }
        setImageMatrix(getImageViewMatrix());
        mMaxZoom = maxZoom();
    }

    // Center as much as possible in one or both axis.  Centering is
    // defined as follows:  if the image is scaled down below the
    // view's dimensions then center it (literally).  If the image
    // is scaled larger than the view and is translated out of view
    // then translate it back into view (i.e. eliminate black bars).
    protected void center(boolean horizontal, boolean vertical) {
        if (mBitmapDisplayed.getBitmap() == null) {
            return;
        }

        Matrix m = getImageViewMatrix();

        RectF rect = new RectF(0, 0,
                mBitmapDisplayed.getBitmap().getWidth(),
                mBitmapDisplayed.getBitmap().getHeight());

        m.mapRect(rect);

        float height = rect.height();
        float width = rect.width();

        float deltaX = 0, deltaY = 0;

        if (vertical) {
            int viewHeight = getHeight();
            if (height < viewHeight) {
                deltaY = (viewHeight - height) / 2 - rect.top;
            } else if (rect.top > 0) {
                deltaY = -rect.top;
            } else if (rect.bottom < viewHeight) {
                deltaY = getHeight() - rect.bottom;
            }
        }

        if (horizontal) {
            int viewWidth = getWidth();
            if (width < viewWidth) {
                deltaX = (viewWidth - width) / 2 - rect.left;
            } else if (rect.left > 0) {
                deltaX = -rect.left;
            } else if (rect.right < viewWidth) {
                deltaX = viewWidth - rect.right;
            }
        }

        postTranslate(deltaX, deltaY);
        setImageMatrix(getImageViewMatrix());
    }

    public ImageViewTouchBase(Context context) {
        super(context);
        init();
    }

    public ImageViewTouchBase(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        setScaleType(ImageView.ScaleType.MATRIX);
    }

    protected float getValue(Matrix matrix, int whichValue) {
        matrix.getValues(mMatrixValues);
        return mMatrixValues[whichValue];
    }

    // Get the scale factor out of the matrix.
    protected float getScale(Matrix matrix) {
        return getValue(matrix, Matrix.MSCALE_X);
    }

    protected float getScale() {
        return getScale(mSuppMatrix);
    }

    // Setup the base matrix so that the image is centered and scaled properly.
    private void getProperBaseMatrix(RotateBitmap bitmap, Matrix matrix) {
        float viewWidth = getWidth();
        float viewHeight = getHeight();

        float w = bitmap.getWidth();
        float h = bitmap.getHeight();
        //int rotation = bitmap.getRotation();

        matrix.reset();

        // We limit up-scaling to 2x otherwise the result may look bad if it's
        // a small icon.
        float widthScale = Math.min(viewWidth / w, 2.0f);
        float heightScale = Math.min(viewHeight / h, 2.0f);
        float scale = Math.min(widthScale, heightScale);

        matrix.postConcat(bitmap.getRotateMatrix());
        matrix.postScale(scale, scale);

        matrix.postTranslate(
                (viewWidth - w * scale) / 2F,
                (viewHeight - h * scale) / 2F);
    }

    // Combine the base matrix and the supp matrix to make the final matrix.
    protected Matrix getImageViewMatrix() {
        // The final matrix is computed as the concatenation of the base matrix
        // and the supplementary matrix.
        mDisplayMatrix.set(mBaseMatrix);
        mDisplayMatrix.postConcat(mSuppMatrix);
        return mDisplayMatrix;
    }

    static final float SCALE_RATE = 1.25F;

    // Sets the maximum zoom, which is a scale relative to the base matrix. It
    // is calculated to show the image at 400% zoom regardless of screen or
    // image orientation. If in the future we decode the full 3 megapixel image,
    // rather than the current 1024x768, this should be changed down to 200%.
    protected float maxZoom() {
        if (mBitmapDisplayed.getBitmap() == null) {
            return 1F;
        }

        float fw = (float) mBitmapDisplayed.getWidth() / (float) mThisWidth;
        float fh = (float) mBitmapDisplayed.getHeight() / (float) mThisHeight;
        return Math.max(fw, fh) * 2;
    }

    protected void zoomTo(float scale, float centerX, float centerY) {
        if (scale > mMaxZoom) {
            scale = mMaxZoom;
        }

        float oldScale = getScale();
        float deltaScale = scale / oldScale;

        mSuppMatrix.postScale(deltaScale, deltaScale, centerX, centerY);
        setImageMatrix(getImageViewMatrix());
        center(true, true);
    }

    protected void zoomTo(final float scale, final float centerX,
                          final float centerY, final float durationMs) {
        final float incrementPerMs = (scale - getScale()) / durationMs;
        final float oldScale = getScale();
        final long startTime = System.currentTimeMillis();

        mHandler.post(new Runnable() {
            public void run() {
                long now = System.currentTimeMillis();
                float currentMs = Math.min(durationMs, now - startTime);
                float target = oldScale + (incrementPerMs * currentMs);
                zoomTo(target, centerX, centerY);

                if (currentMs < durationMs) {
                    mHandler.post(this);
                } else {
                    onZoomFinished();
                }
            }
        });
    }

    public abstract void onZoomFinished();

    protected void zoomTo(float scale) {
        float cx = getWidth() / 2F;
        float cy = getHeight() / 2F;

        zoomTo(scale, cx, cy);
    }

    protected void zoomTo(float scale, final float durationMs) {
        float cx = getWidth() / 2F;
        float cy = getHeight() / 2F;

        zoomTo(scale, cx, cy, durationMs);
    }

    protected void zoomIn() {
        zoomIn(SCALE_RATE);
    }

    protected void zoomOut() {
        zoomOut(SCALE_RATE);
    }

    protected void zoomIn(float rate) {
        if (getScale() >= mMaxZoom) {
            return;     // Don't let the user zoom into the molecular level.
        }
        if (mBitmapDisplayed.getBitmap() == null) {
            return;
        }

        float cx = getWidth() / 2F;
        float cy = getHeight() / 2F;

        mSuppMatrix.postScale(rate, rate, cx, cy);
        setImageMatrix(getImageViewMatrix());
    }

    protected void zoomOut(float rate) {
        if (mBitmapDisplayed.getBitmap() == null) {
            return;
        }

        float cx = getWidth() / 2F;
        float cy = getHeight() / 2F;

        // Zoom out to at most 1x.
        Matrix tmp = new Matrix(mSuppMatrix);
        tmp.postScale(1F / rate, 1F / rate, cx, cy);

        if (getScale(tmp) < 1F) {
            mSuppMatrix.setScale(1F, 1F, cx, cy);
        } else {
            mSuppMatrix.postScale(1F / rate, 1F / rate, cx, cy);
        }
        setImageMatrix(getImageViewMatrix());
        center(true, true);
    }

    protected void postTranslate(float dx, float dy) {
        mSuppMatrix.postTranslate(dx, dy);
    }

    protected void panBy(float dx, float dy) {
        postTranslate(dx, dy);
        setImageMatrix(getImageViewMatrix());
    }
}


text: module.exports = require( "./lib/image-upload" );

redpajama_set_name: RedPajamaGithub


text: {{ product.category.name }}


text:
namespace audio {

namespace {

SoundsManager* g_instance = NULL;
bool g_initialized_for_testing = false;

// SoundsManagerImpl ---------------------------------------------------

class SoundsManagerImpl : public SoundsManager {
 public:
  SoundsManagerImpl(StreamFactoryBinder stream_factory_binder)
      : stream_factory_binder_(std::move(stream_factory_binder)) {}
  ~SoundsManagerImpl() override {
    DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  }

  // SoundsManager implementation:
  bool Initialize(SoundKey key, const base::StringPiece& data) override;
  bool Play(SoundKey key) override;
  bool Stop(SoundKey key) override;
  base::TimeDelta GetDuration(SoundKey key) override;

 private:
  AudioStreamHandler* GetHandler(SoundKey key);

  // There's only a handful of sounds, so a vector is sufficient.
  struct StreamEntry {
    SoundKey key;
    std::unique_ptr<AudioStreamHandler> handler;
  };
  std::vector<StreamEntry> handlers_;
  StreamFactoryBinder stream_factory_binder_;

  DISALLOW_COPY_AND_ASSIGN(SoundsManagerImpl);
};

bool SoundsManagerImpl::Initialize(SoundKey key,
                                   const base::StringPiece& data) {
  if (AudioStreamHandler* handler = GetHandler(key)) {
    DCHECK(handler->IsInitialized());
    return true;
  }

  std::unique_ptr<AudioStreamHandler> handler(
      new AudioStreamHandler(stream_factory_binder_, data));
  if (!handler->IsInitialized()) {
    LOG(WARNING) << "Can't initialize AudioStreamHandler for key=" << key;
    return false;
  }

  handlers_.push_back({key, std::move(handler)});
  return true;
}

bool SoundsManagerImpl::Play(SoundKey key) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  AudioStreamHandler* handler = GetHandler(key);
  return handler && handler->Play();
}

bool SoundsManagerImpl::Stop(SoundKey key) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  AudioStreamHandler* handler = GetHandler(key);
  if (!handler)
    return false;
  handler->Stop();
  return true;
}

base::TimeDelta SoundsManagerImpl::GetDuration(SoundKey key) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  AudioStreamHandler* handler = GetHandler(key);
  return !handler ? base::TimeDelta() : handler->duration();
}

AudioStreamHandler* SoundsManagerImpl::GetHandler(SoundKey key) {
  for (auto& entry : handlers_) {
    if (entry.key == key)
      return entry.handler.get();
  }
  return nullptr;
}

}  // namespace

SoundsManager::SoundsManager() = default;

SoundsManager::~SoundsManager() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
}

// static
void SoundsManager::Create(StreamFactoryBinder stream_factory_binder) {
  CHECK(!g_instance || g_initialized_for_testing)
      << "SoundsManager::Create() is called twice";
  if (g_initialized_for_testing)
    return;
  g_instance = new SoundsManagerImpl(std::move(stream_factory_binder));
}

// static
void SoundsManager::Shutdown() {
  CHECK(g_instance) << "SoundsManager::Shutdown() is called "
                    << "without previous call to Create()";
  delete g_instance;
  g_instance = NULL;
}

// static
SoundsManager* SoundsManager::Get() {
  CHECK(g_instance) << "SoundsManager::Get() is called before Create()";
  return g_instance;
}

// static
void SoundsManager::InitializeForTesting(SoundsManager* manager) {
  CHECK(!g_instance) << "SoundsManager is already initialized.";
  CHECK(manager);
  g_instance = manager;
  g_initialized_for_testing = true;
}

}  // namespace audio


text:
function export_env_vars {
	if [[ -n $BATS_TEST_DIRNAME ]]; then
		export TESTDIR=$(cd "${BATS_TEST_DIRNAME}/.."; printf "$(pwd)")
	else
		export TESTDIR=$(cd "${SCRIPTDIR}"; printf "$(pwd)")
	fi
	export _TMPDIR=$(mktemp -d 2>/dev/null || mktemp -d -t homeshick)
	export REPO_FIXTURES="${_TMPDIR}/repos"
	export HOME="${_TMPDIR}/home"
	export NOTHOME="${_TMPDIR}/nothome"
	export HOMESICK="$HOME/.homesick"

	export HOMESHICK_FN="homeshick"
	export HOMESHICK_DIR=${HOMESHICK_DIR:-$(dirname "${TESTDIR}")}
	export HOMESHICK_FN_SRC="$HOMESHICK_DIR/homeshick.sh"
	export HOMESHICK_BIN="$HOMESHICK_DIR/bin/homeshick"

	# Check if expect is installed
	run type expect >/dev/null 2>&1
	if [[ $status != 0 ]]; then
		export EXPECT_INSTALLED=false
	else
		export EXPECT_INSTALLED=true
	fi
}

function remove_coreutils_from_path {
	# Check if coreutils is in PATH
	system=$(uname -a)
	if [[ $system =~ "Darwin" && ! $system =~ "AppleTV" ]]; then
		run type brew >/dev/null 2>&1
		if [[ $status = 0 ]]; then
			coreutils_path=$(brew --prefix coreutils 2>/dev/null)/libexec/gnubin
			if [[ -d $coreutils_path && $PATH == *$coreutils_path* ]]; then
				if [[ -z $HOMESHICK_KEEP_PATH || $HOMESHICK_KEEP_PATH == false ]]; then
					export PATH=${PATH//$coreutils_path/''}
					export PATH=${PATH//'::'/':'} # Remove any left over colons
				fi
			fi
		fi
	fi
}

function mk_structure {
	mkdir "$REPO_FIXTURES" "$HOME" "$NOTHOME"
}

function rm_structure {
	# Make sure _TMPDIR wasn't unset
	[[ -n $_TMPDIR ]] && rm -rf $_TMPDIR
}

function setup_env {
	remove_coreutils_from_path
	export_env_vars
	mk_structure
	source $HOMESHICK_FN_SRC
}

function setup {
	setup_env
}

function teardown {
	rm_structure
}

function fixture {
	local name=$1
	[[ -e "${REPO_FIXTURES}/$name" ]] || source "${TESTDIR}/fixtures/${name}.sh"
}

function castle {
	local fixture_name=$1
	fixture "$fixture_name"
	$HOMESHICK_FN --batch clone "${REPO_FIXTURES}/${fixture_name}" > /dev/null
}

function is_symlink {
	expected=$1
	path=$2
	target=$(readlink "$path")
	[ "$expected" = "$target" ]
}

function get_inode_no {
	stat -c %i $1 2>/dev/null || stat -f %i $1
}

# Snatched from http://stackoverflow.com/questions/4023830/bash-how-compare-two-strings-in-version-format
function version_compare {
	if [[ $1 == $2 ]]; then
		return 0
	fi
	local IFS=.
	local i ver1=($1) ver2=($2)
	# fill empty fields in ver1 with zeros
	for ((i=${#ver1[@]}; i<${#ver2[@]}; i++)); do
		ver1[i]=0
	done
	for ((i=0; i<${#ver1[@]}; i++)); do
		if [[ -z ${ver2[i]} ]]; then
			# fill empty fields in ver2 with zeros
			ver2[i]=0
		fi
		if ((10#${ver1[i]} > 10#${ver2[i]})); then
			return 1
		fi
		if ((10#${ver1[i]} < 10#${ver2[i]})); then
			return 2
		fi
	done
	return 0
}

function get_git_version {
	GIT_VERSION=$(git --version | grep 'git version' | cut -d ' ' -f 3)
	[[ ! $GIT_VERSION =~ ([0-9]+)(\.[0-9]+){0,3} ]] && skip 'could not detect git version'
	printf $GIT_VERSION
}

function mock_git_version {
	# To mock a git version we simply create a function wrapper for it
	# and forward all calls to git except `git --version`
	local real_git=$(which git)
	eval "
		function git {
			if [[ \$1 == '--version' ]]; then
					echo "git version $1"
					return 0
				else
					local res
					# Some variable expansions used by git internally may break,
					# if we just forward the arguments with '\$@',
					# so we unset this function until the execution is completed.
					unset git
					$real_git "\$@"
					res=\$?
					mock_git_version $1
					return \$res
			fi
		}
	"
	# The functions need to be exported for them to work in child processes
	export -f git
	export -f mock_git_version
}

function commit_repo_state {
	local repo=$1
	(
		cd $repo
		git config user.name "Homeshick user"
		git config user.email "homeshick@example.com"
		git add -A
		git commit -m "Commiting Repo State from test helper.bash."
	)
}


text:
'''
Author: Jason.Parks
Created: April 25, 2012
Module: core.moBuFile
Purpose: File convenience class
'''
from pyfbsdk import *
from common.core import globalVariables as gv
from common.diagnostic.pcsLogger import moBuLogger
from common.fileIO.parser_schema import ParseSchema
from common.fileIO.pcsPath import Path
from moBu.core.moBuCore import MoBuCore #@UnresolvedImport
#import P4
import getpass
import os
import re
import shutil

schemaObj = ParseSchema(mobu=1)

# eclipseSyntax
if False: from pyfbsdk_gen_doc import * #@UndefinedVariable @UnusedWildImport

class MoBuFile(MoBuCore):

	def __init__(self):
		""" MoBuFile.__init__():  set initial parameters """
		super(MoBuFile, self).__init__()

	def cleanDirs(self, folderPath='', dirExtension='.fbm'):
		''' Cleans viral .bck/.fbm folders from given folderPath
			Params:
				folderPath: director to clean
				dirExtension: extension to look for on end of dir
			Returns: True if cleaned any
			'''
		deleted = False
		if not folderPath:
			moBuLogger.error("No folderPath arg passed.")
			return False

		for root, dirs, unused in os.walk(folderPath):
			for _dir in dirs:
				dirPath = os.path.join(root, _dir)
				if Path(dirPath).isdir:
					if re.search(dirExtension, dirPath):
						try:
							shutil.rmtree(dirPath)
							deleted = True
						except WindowsError:
							moBuLogger.info("Failed to remove '%s'" % dirPath)
		return deleted

	def customFBFbxOptions(self, pLoad=False, saveAllTakes=True, allElements=True, selection=False, **kwargs):
		''' create save/load options
		Params:
			pLoad: True if loading, False if saving
			saveAllTakes: Set to False if save current take only
			allElements: Set to False and pass kwargs to save/load/merge specific elements
			selection: True to save selected only
		Returns: FBFbxOptions object
		'''
		if self.mobuVer == 2010:
			moBuLogger.warning("FBFbxOptions are not valid for 2010")
			return None

		elif self.mobuVer == 2012 or self.mobuVer == 2013 or self.mobuVer == 2014:
			# create object
			pFbxOptions = FBFbxOptions(pLoad)

			if not allElements:
				# set all ElementActions and Base properties to false
				pFbxOptions.SetAll(FBElementAction.kFBElementActionDiscard, False)
				baseProperties = ['BaseCameras',
								'CameraSwitcher', 'CameraSwitcherSettings',
								'CurrentCamera', 'CurrentCameraSettings',
								'GlobalLighting', 'GlobalLightingSettings',
								'Transport', 'TransportSettings',
								'EmbedMedia', 'SaveSelectedModelsOnly', ]
				for bProperty in baseProperties:
					exec('pFbxOptions.%s=False' % bProperty)

				# process kwargs
				for key in kwargs:
					# check for non-strings passed in
					if not isinstance(kwargs[key], str):
						moBuLogger.error("A non-string type arg was passed in: '%s'" % kwargs[key])
					if 'kFBElementAction' in kwargs[key]:
						# FBPropertyElementAction
						exec('pFbxOptions.%s = FBElementAction.%s' % (key, kwargs[key]))
					else:
						# FBPropertyBase
						exec('pFbxOptions.%s=%s' % (key, kwargs[key]))

			# save selected for saves
			if not pLoad and selection:
				pFbxOptions.SaveSelectedModelsOnly = True

			# skip takes
			if not saveAllTakes:
				currentTake = self.system.CurrentTake

				pTakeIndex = 0
				for take in self.scene.Takes:
					# save current take only
					if not pLoad:
						if not take.Name == currentTake.Name:
							pFbxOptions.SetTakeSelect(pTakeIndex, False)
					# merge no takes
					else:
						pFbxOptions.SetTakeSelect(pTakeIndex, False)
					pTakeIndex += 1

			# save ASCII
			pFbxOptions.UseASCIIFormat = True

			return pFbxOptions
		else:
			moBuLogger.error("Wrong version of MotionBuilder '%s'" % self.mobuVer)

	def fixThis(self, message=''):
		''' sends scene and email to T.A.
			Params:
				message: passed message for email
			Returns: True/False
		'''
		successes = 0

		#1. Note currentScene name for reload
		currentScene = self.sceneName

		#2. Enter notes
		if not message:
			result = FBMessageBoxGetUserValue("Send Message", "Can you tell me what you were doing?", "Nothing to say", FBPopupInputType.kFBPopupString, "Send scene", "Cancel")
			if result[0] == 1:
				message = result[1]
			elif result[0] == 2:
				moBuLogger.info("Cancelled mbCore.fixThis()")
				return False

		#3. Save to network location
		savePath = Path('%s/data/%s/fixThis' % (gv.schemaLocation, getpass.getuser()))
		saveFilePath = '%s/%s' % (savePath, Path(currentScene).basename())

		# make dir
		if not os.path.exists(savePath):
			os.makedirs(savePath)

		if self.savePCSoptions(pathFile=saveFilePath, quiet=True, pOptions=None, p4=False):
			moBuLogger.info("Saved scene to: '%s'" % saveFilePath)
			successes += 1
		else:
			moBuLogger.info("Failed to save scene to: '%s'" % saveFilePath)
			return False

		#4. Email TechArtist
		#TODO: email message
		_file = open(saveFilePath.replace('.fbx', '.txt'), "w")
		_file.write(message)
		_file.close()

		#5. Reload original scene
		if self.loadPCSoptions(pathFile=currentScene, quiet=False, pOptions=None):
			successes += 1
		else:
			moBuLogger.info("Failed to reload original scene: '%s'" % currentScene)

		if successes == 2:
			return True
		else:
			return False

	def loadPCSoptions(self, pathFile=None, quiet=False, pOptions=None):
		''' saves with customFBFbxOptions
		Params:
			pathFile: complete file path to save
			quiet: suppress messages
			pOptions: pre-made options
		Returns: True/False
		'''

		# pick file if not passed
		if not pathFile:
			pathFile = self.openFileDialog(openSave='open')

#		# Check for binary
#		lFbp = FBProgress()
#		lFbp.ProgressBegin()
#		lFbp.Caption = "Checking binary on %s" % pathFile.basename
#		lFbp.Percent = 50
#		if Path(pathFile).isbin:
#			moBuLogger.warning("Skipping file '%s' because detected binary" % pathFile)
#			lFbp.ProgressDone()
#			return False
#		moBuLogger.debug("Checked '%s' for binary, passed." % pathFile)
#
#		lFbp.ProgressDone()

		# check for cancel
		if not pathFile:
			moBuLogger.info("Cancelled open via loadPCSoptions()")
			return False

		if not pOptions:
			pOptions = self.customFBFbxOptions(pLoad=True)

		# by default, load all takes
		success = self.app.FileOpen(str(pathFile), 1 - quiet, self.customFBFbxOptions(pLoad=1, saveAllTakes=1, allElements=1))
		if success:
			moBuLogger.info("Success opening '%s'" % pathFile)
		else:
			moBuLogger.error("Failed to open '%s'" % pathFile)

#		# check for hips
#		ref = self.getObject("Reference")
#		if ref:
#			if len(ref.Children) > 0:
#				if not ref.Children[0].Name == 'Hips':
#					moBuLogger.infoDialog("WARNING: No Hips found in scene. Check your joint names.", "Joints Missing")

		return success

	def mergePCSoptions(self, pathFile='', quiet=True, pOptions=None):
		''' merges with customFBFbxOptions
		Params:
			pathFile: complete file path to merge
			quiet: suppress messages
			pOptions: pre-made options
		Returns: True/False
		'''
		if not pathFile:
			pathFile = self.openFileDialog()

		if not pOptions:
			pOptions = self.customFBFbxOptions(pLoad=True, saveAllTakes=True, allElements=True)

		# by default, do NOT merge takes
		if self.app.FileMerge(str(pathFile), 1 - quiet, pOptions):
			# report
			if not quiet:
				moBuLogger.info("Merged %s with PCSoptions" % pathFile)
			return True
		else:
			moBuLogger.error("Failed to merge '%s'" % pathFile)
			return False

	def openFileDialog(self, openSave='open', startPath=''):
		''' opens dialog box to select a file
		Params:
			openSave: open or save file type
			startPath: start in path
		Returns: path and fileName/False
		'''
		lFp = FBFilePopup()
		lFp.Caption = "Select a file"
		if openSave == 'open':
			lFp.Style = FBFilePopupStyle.kFBFilePopupOpen
		elif openSave == 'save':
			lFp.Style = FBFilePopupStyle.kFBFilePopupSave
		else:
			moBuLogger.error("Illegal arg passed. openSave=%s" % openSave)

		# BUG: If we do not set the filter, we will have an exception.
		lFp.Filter = "*"

		if not startPath:
			if not self.sceneName == 'Untitled':
				lFp.Path = str(self.sceneName.parent)
			else:
				lFp.Path = str(schemaObj.artRoot.replace('/', "\\"))
		else:
			lFp.Path = str(Path(startPath).makePretty(lastSlash=False, backward=True))

		# open window
		lRes = lFp.Execute()

		if lRes:
			return lFp.FullFilename
		else:
			return False

	def openFolderDialog(self):
		''' opens dialog box to select a folder
		Params: none
		Returns: path to folder/False
		'''

		lFp = FBFolderPopup()
		lFp.Caption = "Select a folder"

		self.app = FBApplication()
		if not self.sceneName == 'Untitled':
			lFp.Path = str(self.sceneName.parent)
		else:
			lFp.Path = str(schemaObj.artRoot)
		lRes = lFp.Execute()

		if lRes:
			return lFp.Path
		else:
			return False

	def savePCSoptions(self, pathFile=None, quiet=True, pOptions=None, p4=True):
		''' saves with customFBFbxOptions
		Params:
			pathFile: complete file path to save
			quiet: suppress messages
			pOptions: pre-made options
			p4: markForAdd/checkout or not
		Returns: True/False
		'''

		text = 'Saved with PCSoptions'

		# pick file if not passed
		if not pathFile:
			if not quiet:
				pathFile = self.openFileDialog(openSave='save')
			else:
				moBuLogger.error("No pathFile passed and quiet=True")
				return False
		if not pathFile:
			moBuLogger.info("Cancelled")
			return False

		# add extension if they didn't type it
		if not Path(pathFile).ext:
			pathFile = '%s.fbx' % pathFile

#		# checkout from perforce
#		if p4:
#			if self.pcsParseObj.isp4Active:
#				self.p4.fileName = pathFile
#				if self.p4.isP4Connected:
#					try:
#						self.p4.p4CheckOut(desc=text)
##					except P4.P4Exception:
#					except:
#						moBuLogger.warning("Failed to checkout: '%s'" % pathFile)
#			else:
#				if not quiet:
#					moBuLogger.warning('P4Active setting FALSE, not checking out.')
#		else:
#			if not quiet:
#				moBuLogger.warning("p4 arg passed as False, not checking out for file: '%s'." % pathFile)

		if not pOptions:
			pOptions = self.customFBFbxOptions(pLoad=False, saveAllTakes=True)

		# 2010 save process
		currentTakeObject = FBSystem().CurrentTake
		if self.mobuVer == 2010:
			lMgr = FBFbxManager() #@UndefinedVariable
			lMgr.SaveBegin(str(pathFile))
			lMgr.Selected = True
			for strEach in lMgr.Takes:
				if strEach.Name != currentTakeObject.Name:
					strEach.Import = False
			lMgr.EmbedMedia = False
			lMgr.BaseCameras = False
			lMgr.CameraSwitcherSettings = False
			lMgr.CurrentCameraSettings = False
			lMgr.GlobalLightingSettings = False
			lMgr.TransportSettings = False
			if not lMgr.Save():
				moBuLogger.errorDialog('There is a problem saving the file', 'Cannot Save')
			if not lMgr.SaveEnd():
				moBuLogger.errorDialog('There is a problem saving the file', 'Cannot Save')

		# 2012 save process
		elif self.mobuVer == 2012 or self.mobuVer == 2013 or self.mobuVer == 2014:
			alreadyExists = False
			if Path(pathFile).exists():
				alreadyExists = True
			if not self.app.FileSave(str(pathFile), pOptions):
				# cancelled?
				moBuLogger.warning("Cancelled")
				return False
			if not alreadyExists:
				# check to see if new file is there
				res = os.path.exists(str(pathFile))
				if res:
					if not quiet:
						moBuLogger.info("%s, '%s'" % (text, str(pathFile)))
					return True
				else:
					moBuLogger.errorDialog("Failed to save '%s'" % str(pathFile))
					return False
			else:
				#TODO: check to see if different?
				if not quiet:
					moBuLogger.info("%s, '%s'" % (text, str(pathFile)))
				return True

mbFile = MoBuFile()

print "core.moBuFile imported"


text:
  </> The theme by Jackpon.
  © {{ site.time | date: '%Y' }} {{ site.author_name }}


text:
package com.zandero.utils.test;

/**
 *
 */
public final class NotPrivateTwo {
}


text:
import { combineReducers } from 'redux';
import config from './config';
import history from './history';

export default combineReducers({
    config,
    history,
})


text:
package ru.surfstudio.codegenerator.plugin;

import org.eclipse.jface.preference.BooleanFieldEditor;
import org.eclipse.jface.preference.FieldEditorPreferencePage;
import org.eclipse.jface.preference.StringFieldEditor;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;

/**
 * Preference for program used by ContextMenuPlugin
 */
public class PreferencePage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage {

	public static final String P_AUTO_TYPE_RECOGNITION = "autoTypeRecognition";

	public PreferencePage() {
		super(GRID);
		setPreferenceStore(Activator.getDefault().getPreferenceStore());
		setDescription("Set up your file context menu application.");
	}

	/**
	 * Creates the field editors. Field editors are abstractions of the common
	 * GUI blocks needed to manipulate various types of preferences. Each field
	 * editor knows how to save and restore itself.
	 */
	@Override
	public void createFieldEditors() {

		addField(new BooleanFieldEditor(P_AUTO_TYPE_RECOGNITION, "&Allow automatic type recognition:", getFieldEditorParent()));
	}

	public void init(IWorkbench arg0) {
		// TODO Auto-generated method stub

	}
}


text:
package org.drools.benchmarks.turtle.buildtime;

import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Setup;

/**
 * Tests how long it takes to create knowledge base from DSL and DSLR files.
 */
public class KBaseCreationFromDslAndDslrBenchmark extends AbstractBuildtimeBenchmark {

    @Setup
    public void addResources() {
        addClassPathResource("kbase-creation/dsl-kbase-creation.dsl");
        addClassPathResource("kbase-creation/dslr-kbase-creation.dslr");
    }

    @Benchmark
    public int timeBaseCreationFromSimpleDslrAndDsl() {

        return actuallyCreateTheKBase();
    }

}


text:
function AMa = pvl_absoluteairmass(AMrelative,pressure)
% PVL_ABSOLUTEAIRMASS Determine absolute (pressure corrected) airmass from relative airmass and pressure
%
% Syntax
% AMa = pvl_absoluteairmass(AMrelative, pressure)
%
% Description
%
%   Gives the airmass for locations not at sea-level (i.e. not at standard
%   pressure). The input argument "AMrelative" is the relative airmass. The
%   input argument "pressure" is the pressure (in Pascals) at the location
%   of interest and must be greater than 0. The calculation for
%   absolute airmass is:
%   absolute airmass = (relative airmass)*pressure/101325
%
% Inputs:
%   AMrelative - The airmass at sea-level.  This can be calculated using the
%     PV_LIB function pvl_relativeairmass.
%   pressure - a scalar or vector of values providing the site pressure in
%     Pascal. If pressure is a vector it must be of the same size as all
%     other vector inputs. pressure must be >=0. Pressure may be measured
%     or an average pressure may be calculated from site altitude.
%
% Output:
%   AMa - Absolute (pressure corrected) airmass
%
% References
%   [1] C. Gueymard, "Critical analysis and performance assessment of
%   clear sky solar irradiance models using theoretical and measured data,"
%   Solar Energy, vol. 51, pp. 121-138, 1993.
%
% See also PVL_RELATIVEAIRMASS

p=inputParser;
p.addRequired('AMrelative', @(x) all(isnumeric(x) | isnan(x)));
p.addRequired('pressure', @(x) all(isnumeric(x) & x>=0));
p.parse(AMrelative,pressure);

AMa = AMrelative.*pressure/101325;


text:
'use strict';

// Middleware for error handling
var errorHandler = function(err, req, res, next) {
    var message = err.message;
    var error = err.error || err;
    var status = err.status || 500;

    res.status(status).json({
        message: message,
        error: error
    });
};

module.exports = errorHandler;


text:
using System;

namespace Belikov.GenuineChannels.Logbook
{
	/// <summary>
	/// The category of the log record.
	/// </summary>
	public enum LogCategory
	{
		/// <summary>
		/// Information about connections.
		/// </summary>
		Connection = 0,

		/// <summary>
		/// Information about raised channel events.
		/// </summary>
		ChannelEvent = 1,

		/// <summary>
		/// Message processing.
		/// </summary>
		MessageProcessing = 2,

		/// <summary>
		/// Implementation warning.
		/// </summary>
		ImplementationWarning = 3,

		/// <summary>
		/// Security events.
		/// </summary>
		Security = 4,

		/// <summary>
		/// A Broadcast Engine messages.
		/// </summary>
		BroadcastEngine = 5,

		/// <summary>
		/// Information which is sent by a specific transport.
		/// </summary>
		Transport = 6,

		/// <summary>
		/// A DXM Usage message.
		/// </summary>
		DXM = 7,

		/// <summary>
		/// HostInformation lifetime stages.
		/// </summary>
		HostInformation = 8,

		/// <summary>
		/// Connection accepting.
		/// </summary>
		AcceptingConnection = 9,

		/// <summary>
		/// Debugging messages.
		/// </summary>
		Debugging = 10,

		/// <summary>
		/// The version of Genuine Channels and environment.
		/// </summary>
		Version = 11,

		/// <summary>
		/// The low-level transport notification.
		/// </summary>
		LowLevelTransport = 12,

		/// <summary>
		/// Represents records exposing buffer pool/thread pool usage information.
		/// </summary>
		StatisticCounters = 13,

		/// <summary>
		/// Indicates the total number of log categories.
		/// </summary>
		TotalCategories = 14,
	}
}


text:
<!DOCTYPE html>

		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<meta name="description" content="Personal website of Constance">
		<meta name="author" content="Constance M. Chen, conschen@wharton.upenn.edu">
		<meta name="keywords" content="constance,ymtsai,Yi-Min Tsai,Yi-Min,home,website">
		<meta name="google-site-verification" content="AP6I04ejevrawWYuTA4K1AY3LJoBzKj6qpSvZ5xvuRc" />

		<title>Constance M. Chen | Home</title>

		<link rel="shortcut icon" href="img/Wharton-logo.png">

		<link href="css/bootstrap.min.css" rel="stylesheet">

		<link href="css/freelancer.css" rel="stylesheet">
		<link href="css/component.css" rel="stylesheet">
		<link href="css/owl.carousel.css" rel="stylesheet">
		<link href="css/owl.theme.css" rel="stylesheet">

		<link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
		<link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
		<link href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css">

					<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
						Toggle navigation

					</button>
					Constance M. Chen

							Resume

							Honor

							Skill

							NPO

							Project

							PUBS.

							Contact

								Constance M. Chen

									Business Development Manager

									Product Manager

									Electronics Engineer

									Computer Science Engineer

About

							Hi! I am Constance MaryAnn Chen, a first year Wharton MBA, candidate of WG'17.
							I am a professional and passionate technology person!
							I was the Business Development Manager and Product Manager at a camera IC startup before here.
							My interests are bio-medical signal processing, image/video signal processing and algorithm.
							I was also an IC design engineer and research designer for 4 years.
							Now I bring all my expertise in technology to Wharton, sharpen my business skills and finance knowledge,
							 and contribute unique value to technology industry.

							  Download Resume

Resume

								<time class="cbp_tmtime">
									2015
								</time>

MBA, class of 2017

Wharton MBA Program | The Wharton School, University of Pennsylvania

								<time class="cbp_tmtime">
									2013-2015
								</time>

Business Development Manager/ Product Manager

AUGENETIX Inc., Taiwan (previous Multi-Tek Inc.)

Startup focusing on chip design in IP cam and smart surveillance

										 Related Projects

												Design product spectrums, develope product roadmap to 2016, and found potential customers

												Negotiate with design service company for licensing fee, and reduced project cost by $500K

												Lead the business diligence and evaluation for $1M acquisition of a surveillance system company.

								<time class="cbp_tmtime">
									2013-2015
								</time>

Engineer

Multimedia Dept., MediaTek Inc., Taiwan

										 Related Projects

												Initiate verification methodology that increased coverage to 99.5% and became new standard

												Analyze options for system design; convinced manager to adopt flexible design, implementation now adopted in 6 projects with 200 million production output;

												Manage training programs and supervised 4 junior engineers; 1st non-senior engineer in charge

												Consulte for newly-launched biomedical healthcare project; directe lectures and build out of demo system;

								<time class="cbp_tmtime">
									2013-2015
								</time>

Founder and Director

LIFE VITALITY LOHAS ASSOCIATION, Taiwan

								<time class="cbp_tmtime">
									2007-2013
								</time>

M.S.

Graduate Institute of Electronics Engineering, National Taiwan University (NTU-GIEE)

										 Proficient Knowledge Field

												Video/image signal processing

												Bio medical signal processing: EEG, ECG, spike sorting

												Machine learning

												Computer vision

												Digital circuit and system design

										 Related Projects

												Seizure prediction device, issued patent in Taiwan and U.S.

												EEG based brain computer interface, IoT and smart home

												Spike sorting

												Motion and gesture recognition

								<time class="cbp_tmtime">
									2015
								</time>

B.S.

Dept. of Electrical Engineering, National Taiwan University (NTUEE)

Honor

2012 V Award

									(started by MTK founder to recognize special and exemplary contribution)

									Awarded by initiating verification methodology that increased coverage to 99.5%

2010 National Chip Implementation Center IC Design Contest Chip Award

National representative of International Physics Olympia

Winner of TFG math competition

Skill

C / C++

Python

Verilog

Matlab

Verdi

Prime Power

Design Vision

SoC Encounter

LIFE VITALITY LOHAS ASSOCIATION

(NPO promoting handy bikes for the disabled and elderly by improving environment accessibility)

Founder and Director

Conference

A little bit about me and the NPO

                            •	Raised funds for 137 handy bikes from 5 companies and associations, including Rotary Club Association; donated 60 to Taipei City and 40 to New Taipei City, with 18,000 users by Dec.2014.
                            •	Awarded Daja Park from Taipei City for association use by launching collaboration program; reduced lease expense by 95%.
                            •	Winner of Innovation in NPO Plan Competition, earned 7% (upper bound) annual profit of used clothes recycling from Social Welfare Dept., which covered 90% of personnel expenses.
                            •	Held world's first international handy bike cycling event in Yunnan by building partnership with China government, airline company, and Ministry of Foreign Affairs.

Project

Machine Learning Based Brain Computer Interface

Spike Sorting

Seizure Prediction Device

Advanced ISP

Motion Recognition

Chip Design

Publication

Conference

								Tung-Chien Chen,Tsung-Chuan Ma, Yun-Yu Chen and Liang-Gee Chen, "Low Power and High Accuracy Spike Sorting Microprocessor with On-line Interpolation and Re-alignment in 90nm CMOS Process", in Proceedings of IEEE Conference of Engineering in Medicine and Biology Society (EMBC 2012), San Diego, California, USA, Aug-Sep. 2012.

								Yun-Yu Chen, Yi-Min Tsai and Liang-Gee Chen, "Algorithm and Implementation of Multi-channel Spike Sorting using GPU in a Home-care Surveillance System", in IEEE International Conference on Multimedia and Expo (ICME), Barcelona, Spain, July 2011.

								Tung-Chien Chen, Yun-Yu Chen, Tsung-Chuan Ma and Liang-Gee Chen, "Design and Implementation of Cubic Spline Interpolation for Spike Sorting Microsystems", in Proceedings of IEEE International Conference on Acoustics, Speech, and Signal Processing (ICASSP 2011), Prague, Czech Republic, May 2011.

								Yun-Yu Chen, Tung-Chien Chen and Liang-Gee Chen, "Accuracy and Power Tradeoff in Spike Sorting Microsystems with Cubic Spline Interpolation", in IEEE International Symposium on Circuits and Systems (ISCAS 2010), 2010, Paris, France.

								Yun-Yu Chen, Tung-Chien Chen, Chien-Chung Chen, Hsin-I Liao, Luk-Ting Sio, and Liang-Gee Chen,
								"Exploration of reusing the pre-recorded training data set to improve the supervised classifier for EEG-based motor-imagery brain computer interfaces", in IEEE International Symposium on Circuits and Systems (ISCAS 2012), 2012, Seoul, Korea.

Contact

						<form name="sentMessage" id="contactForm" novalidate>

									Name
									<input type="text" name="name" class="form-control" placeholder="Your Name *" id="name" required data-validation-required-message="Please enter your name.">

									Email
									<input type="email" name="email" class="form-control" placeholder="Your Email *" id="email" required data-validation-required-message="Please enter your email address.">

									Phone Number
									<input type="tel" name="phone" class="form-control" placeholder="Your Phone Number" id="phone">

									Subject
									<input type="text" name="subject" class="form-control" placeholder="Subject" id="subject">

									Message
									<textarea rows="5" name="message" class="form-control" placeholder="Message *" id="message" required data-validation-required-message="Please enter a message."></textarea>

									<button type="submit" class="btn btn-success btn-lg">
										Send
									</button>

						</form>

My Email

								conschen@wharton.upenn.edu

My Phone Number

								+1(267)3192021

Around the Web

							Copyright © Yi-Min Tsai 2015

Compressive Sensing and Sparse Representation

									Compressive sensing is a new signal processing paradigm that can acquire a sparse signal representation with linear random projections. It allows encoding a signal with sparsity constraints and recovering the signal with only few compressed measurements. An object pattern can be represented by a small set of atoms of an over-complete dictionary through sparse approximation. The sparsity constraint enforces such efficient expressions of visual patterns. In this project, we apply compressive sensing and sparse representation for visual recognition tasks.

										Project Date: March 2011 – June 2013 (National Taiwan University)

Video Stabilization

									Video camera becomes smaller and eventually portable in many applications. However, the captured video may be blurred and shaky owing to unstable camera platforms. Many real-time applications need on-the-fly video stabilization to provide steady video inputs for further processing. We develop both feature-based and motion-based real-time video stabilization frameworks in this project.

										Project Date: January 2009 – June 2011 (National Taiwan University), October 2013 – December 2013 (Quanta Computer Inc.)

Intelligent Vehicle

									Owing to the maturity of vision sensors, vision-based systems play an essential role in many vehicular applications. Intelligent Cruise Control (ICC) provides semi-automatic driving mechanism. Collision Warning Systems (CWS) prevent vehicles from sudden crashes. These applications require detection and tracking of on-road vehicles to estimate distance between host and preceding vehicles or to monitor vehicles' behaviors on different lanes. We develop an intelligent vision-based on-road preceding vehicle detection-and-tracking system based on computer vision and machine learning techniques.

										Project Date: April 2009 – July 2011 (National Taiwan University)

Intelligent Vision Analysis

									In this project, we develop intelligent vision/video analysis (IVA) techniques for IP cameras in smart home and smart retail applications. Motion detection is used to find motions from environment. Region-of-interest can be set according to user scenarios. Object detection such as face and people detection provides recognition capabilities and space information. Object tracking is applied to record moving histories. These IVA techniques can then be applied to applications such as video synopsis and surveillance. We also implement our IVA in embedded systems for real-time requirements.

										Project Date: October 2013 – Present (Quanta Computer Inc.)

Advanced ISP

Pixim Chart (HDR)

iPhone 5S (SONY IMX 145, Native)

Samsung S5 (SONY IMX 240, Native)

Advanced ISP V1.2 (OV4689, Staggered)

Low-light (HDR)

iPhone 6 (SONY Series, Native)

Samsung S5 (SONY IMX 240, Native)

Advanced ISP V1.2 (OV13850, Interlaced)

Low-light (LDR)

iPhone 5S (SONY IMX 145, Native)

Samsung S5 (SONY IMX 240, Native)

Advanced ISP V2.0 (OV13850, Interlaced)

									In this project, we develop an advanced ISP (AISP) pipeline for HDR video/image. AISP supports various HDR sensors, including native, interlaced, and staggered sensors. The features of AISP include texture-aware noise reduction, adaptive exposure fusion, perceptual local tone-mapping, saturation adjustment, and region-based AE/AWB. The AISP dynamically adjusts low-light exposure curve and outperforms other ISP in low-light details. The AISP IP is also verified through FPGA implementation.

										Project Date: October 2013 – Present (Quanta Computer Inc.)

										Project Site: AISP V2.0

Smart Interface

									Augmented reality (AR) is a technique trying to build a bridge connecting the real world and the virtual world. AR adds the information from the virtual world to the real world in a perceptual way. By equipping a camera with a micro-projector, a mobile AR system is constructed. Users therefore can access the information from the digital world anywhere in a natural way.

									Unfortunately, the projection area is fixed, but the objects in our daily life are possible with any shapes and any size. Under such uncontrolled environments, if the surface is smaller than the projection area, dramatic information loss occurs. Similarly, a non-rectangular surface causes the same loss. To deal with these issues, a surface adaptation technique is applied to warp the content into the surface region before the content is projected.

									Owing to the diversity of projection surfaces, an effective mobile display system must be adaptive to the surface to avoid introducing a clipped scene. We propose a smart mobile display system which automatically adapts to the location and motion of a surface.

										Project Date: September 2010 – February 2011 (National Taiwan University)

Chip Design

Decoding Chip for Compressive Sensing and Sparse Representation

											A versatile signal reconstruction platform designed in a 40nm CMOS process is presented. The chip supports high-dimensional sparse signal reconstruction for compressed sensing and sparse representation. A 4G entries/s (8Gbps) high-throughput sensing matrix generation engine is proposed. It reduces over 75% external bandwidth and 77% processing cycles. The chip achieves 401GFlops/W power efficiency with 16 multi-processing cores. The chip also yields over 1000× improvement of computing time compared to software implementations.

Intelligent Vision SoC for Versatile Automotive Applications

											A machine-learning based intelligent vision SoC implemented on a 9.3 mm2 die in a 40nm CMOS process is presented. The architecture realizes 140 meters active distance at 60fps and 60 meters at 300fps under Quad-VGA (1280×960) resolution while maintaining above 90% detection rate for versatile automotive applications. The system supports 64 object tracking and prediction. It raises 1.62× improvement on power efficiency and at least 1.79× increase on frame rate with the proposed knowledge-based tracking processor. The chip achieves 354.2fps/W and 3.01TOPS/W power efficiency with 69mW average power consumption.

Intelligent Vehicle Tracking Engine

											We exploit a vision-based intelligent vehicle cruise control system via chip design. The knowledge-based vehicle tracking processor is implemented in an UMC 90nm Low-K SP CMOS process. The chip size is 2.2×2.2mm2. The throughput is 5× to 10× compared to software implementation. Chip power dissipation has relations with number of targets. It consumes about 645mW for maximum 5 tracking tasks and 23mW for single-target tracking. For 4096×2160 specification, two memory banks are combined to support an object with maximum height 400 pixels. The chip operates at 100MHz frequency with 2.5V core voltage.


text:
package net.blay09.mods.eirairc.command;

import net.blay09.mods.eirairc.ConnectionManager;
import net.blay09.mods.eirairc.api.SubCommand;
import net.blay09.mods.eirairc.api.irc.IRCChannel;
import net.blay09.mods.eirairc.api.irc.IRCConnection;
import net.blay09.mods.eirairc.api.irc.IRCContext;
import net.blay09.mods.eirairc.util.ChatComponentBuilder;
import net.blay09.mods.eirairc.util.Utils;
import net.minecraft.command.ICommandSender;
import net.minecraft.util.ChatComponentText;

import java.util.List;

public class CommandList implements SubCommand {

	@Override
	public String getCommandName() {
		return "list";
	}

	@Override
	public String getCommandUsage(ICommandSender sender) {
		return "eirairc:commands.list.usage";
	}

	@Override
	public String[] getAliases() {
		return null;
	}

	@Override
	public boolean processCommand(ICommandSender sender, IRCContext context, String[] args, boolean serverSide) {
		if(ConnectionManager.getConnectionCount() == 0) {
			Utils.sendLocalizedMessage(sender, "error.notConnectedToIRC");
			return true;
		}
		ChatComponentBuilder.create().color('e').lang("eirairc:commands.list.activeConnections").send(sender);
		for(IRCConnection connection : ConnectionManager.getConnections()) {
			StringBuilder sb = new StringBuilder();
			for(IRCChannel channel : connection.getChannels()) {
				if(sb.length() > 0) {
					sb.append(", ");
				}
				sb.append(channel.getName());
			}
			sender.addChatMessage(new ChatComponentText(" * " + connection.getHost() + " (" + sb.toString() + ")"));
		}
		return true;
	}

	@Override
	public boolean canCommandSenderUseCommand(ICommandSender sender) {
		return true;
	}

	@Override
	public void addTabCompletionOptions(List<String> list, ICommandSender sender, String[] args) {
	}

	@Override
	public boolean isUsernameIndex(String[] args, int idx) {
		return false;
	}

	@Override
	public boolean hasQuickCommand() {
		return false;
	}

}


text:
package com.google.gerrit.sshd.commands;

import com.google.gerrit.extensions.restapi.ResourceNotFoundException;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.client.PatchSet;
import com.google.gerrit.reviewdb.client.RevId;
import com.google.gerrit.reviewdb.server.ReviewDb;
import com.google.gerrit.server.change.ChangeResource;
import com.google.gerrit.server.change.DeleteReviewer;
import com.google.gerrit.server.change.PostReviewers;
import com.google.gerrit.server.change.ReviewerResource;
import com.google.gerrit.server.project.ChangeControl;
import com.google.gerrit.server.project.NoSuchChangeException;
import com.google.gerrit.server.project.ProjectControl;
import com.google.gerrit.sshd.CommandMetaData;
import com.google.gerrit.sshd.SshCommand;
import com.google.gwtorm.server.OrmException;
import com.google.gwtorm.server.ResultSet;
import com.google.inject.Inject;
import com.google.inject.Provider;

import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.Option;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@CommandMetaData(name = "set-reviewers", description = "Add or remove reviewers on a change")
public class SetReviewersCommand extends SshCommand {
  private static final Logger log =
      LoggerFactory.getLogger(SetReviewersCommand.class);

  @Option(name = "--project", aliases = "-p", usage = "project containing the change")
  private ProjectControl projectControl;

  @Option(name = "--add", aliases = {"-a"}, metaVar = "REVIEWER", usage = "user or group that should be added as reviewer")
  private List<String> toAdd = new ArrayList<String>();

  @Option(name = "--remove", aliases = {"-r"}, metaVar = "REVIEWER", usage = "user that should be removed from the reviewer list")
  void optionRemove(Account.Id who) {
    toRemove.add(who);
  }

  @Argument(index = 0, required = true, multiValued = true, metaVar = "COMMIT", usage = "changes to modify")
  void addChange(String token) {
    try {
      changes.addAll(parseChangeId(token));
    } catch (UnloggedFailure e) {
      throw new IllegalArgumentException(e.getMessage(), e);
    } catch (OrmException e) {
      throw new IllegalArgumentException("database is down", e);
    }
  }

  @Inject
  private ReviewDb db;

  @Inject
  private ReviewerResource.Factory reviewerFactory;

  @Inject
  private Provider<PostReviewers> postReviewersProvider;

  @Inject
  private Provider<DeleteReviewer> deleteReviewerProvider;

  @Inject
  private ChangeControl.Factory changeControlFactory;

  private Set<Account.Id> toRemove = new HashSet<Account.Id>();
  private Set<Change.Id> changes = new HashSet<Change.Id>();

  @Override
  protected void run() throws UnloggedFailure {
    boolean ok = true;
    for (Change.Id changeId : changes) {
      try {
        ok &= modifyOne(changeId);
      } catch (Exception err) {
        ok = false;
        log.error("Error updating reviewers on change " + changeId, err);
        writeError("fatal", "internal error while updating " + changeId);
      }
    }

    if (!ok) {
      throw error("fatal: one or more updates failed; review output above");
    }
  }

  private boolean modifyOne(Change.Id changeId) throws Exception {
    ChangeResource changeRsrc =
        new ChangeResource(changeControlFactory.validateFor(changeId));
    boolean ok = true;

    // Remove reviewers
    //
    DeleteReviewer delete = deleteReviewerProvider.get();
    for (Account.Id reviewer : toRemove) {
      ReviewerResource rsrc = reviewerFactory.create(changeRsrc, reviewer);
      String error = null;;
      try {
        delete.apply(rsrc, new DeleteReviewer.Input());
      } catch (ResourceNotFoundException e) {
        error = String.format("could not remove %s: not found", reviewer);
      } catch (Exception e) {
        error = String.format("could not remove %s: %s",
            reviewer, e.getMessage());
      }
      if (error != null) {
        ok = false;
        writeError("error", error);
      }
    }

    // Add reviewers
    //
    PostReviewers post = postReviewersProvider.get();
    for (String reviewer : toAdd) {
      PostReviewers.Input input = new PostReviewers.Input();
      input.reviewer = reviewer;
      String error;
      try {
        error = post.apply(changeRsrc, input).error;
      } catch (ResourceNotFoundException e) {
        error = String.format("could not add %s: not found", reviewer);
      } catch (Exception e) {
        error = String.format("could not add %s: %s", reviewer, e.getMessage());
      }
      if (error != null) {
        ok = false;
        writeError("error", error);
      }
    }

    return ok;
  }

  private Set<Change.Id> parseChangeId(String idstr)
      throws UnloggedFailure, OrmException {
    Set<Change.Id> matched = new HashSet<Change.Id>(4);
    boolean isCommit = idstr.matches("^([0-9a-fA-F]{4," + RevId.LEN + "})$");

    // By newer style changeKey?
    //
    boolean changeKeyParses = false;
    if (idstr.matches("^I[0-9a-fA-F]*$")) {
      Change.Key key;
      try {
        key = Change.Key.parse(idstr);
        changeKeyParses = true;
      } catch (IllegalArgumentException e) {
        key = null;
        changeKeyParses = false;
      }

      if (changeKeyParses) {
        for (Change change : db.changes().byKeyRange(key, key.max())) {
          matchChange(matched, change);
        }
      }
    }

    // By commit?
    //
    if (isCommit) {
      RevId id = new RevId(idstr);
      ResultSet<PatchSet> patches;
      if (id.isComplete()) {
        patches = db.patchSets().byRevision(id);
      } else {
        patches = db.patchSets().byRevisionRange(id, id.max());
      }

      for (PatchSet ps : patches) {
        matchChange(matched, ps.getId().getParentKey());
      }
    }

    // By older style changeId?
    //
    boolean changeIdParses = false;
    if (idstr.matches("^[1-9][0-9]*$")) {
      Change.Id id;
      try {
        id = Change.Id.parse(idstr);
        changeIdParses = true;
      } catch (IllegalArgumentException e) {
        id = null;
        changeIdParses = false;
      }

      if (changeIdParses) {
        matchChange(matched, id);
      }
    }

    if (!changeKeyParses && !isCommit && !changeIdParses) {
      throw error("\"" + idstr + "\" is not a valid change");
    }

    switch (matched.size()) {
      case 0:
        throw error("\"" + idstr + "\" no such change");

      case 1:
        return matched;

      default:
        throw error("\"" + idstr + "\" matches multiple changes");
    }
  }

  private void matchChange(Set<Change.Id> matched, Change.Id changeId) {
    if (changeId != null && !matched.contains(changeId)) {
      try {
        matchChange(matched, db.changes().get(changeId));
      } catch (OrmException e) {
        log.warn("Error reading change " + changeId, e);
      }
    }
  }

  private void matchChange(Set<Change.Id> matched, Change change) {
    try {
      if (change != null
          && inProject(change)
          && changeControlFactory.controlFor(change).isVisible(db)) {
        matched.add(change.getId());
      }
    } catch (NoSuchChangeException e) {
      // Ignore this change.
    } catch (OrmException e) {
      log.warn("Error reading change " + change.getId(), e);
    }
  }

  private boolean inProject(Change change) {
    if (projectControl != null) {
      return projectControl.getProject().getNameKey().equals(change.getProject());
    } else {
      // No --project option, so they want every project.
      return true;
    }
  }

  private void writeError(String type, String msg) {
    try {
      err.write((type + ": " + msg + "\n").getBytes(ENC));
    } catch (IOException e) {
    }
  }

  private static UnloggedFailure error(String msg) {
    return new UnloggedFailure(1, msg);
  }
}


text:
* [Description](#description)
* [Function Index](#index)
* [Function Details](#functions)

.
Copyright (c) (C) 2013, HIROE Shin

__Authors:__ HIROE Shin ([`shin@HIROE-no-MacBook-Pro.local`](mailto:shin@HIROE-no-MacBook-Pro.local)).

## Function Index ##

bar/1	Debug function.

foo/1	Debug function.

init/1	Initialize and goto receive loop.

pulldown/1	Pull down pin.

pullnone/1	Disable pullup and pulldown.

pullup/1	Pull up pin.

start_link/0	Starts the server.

start_poll/2	Start Polling to pin (exec poll system call in port driver).

stop/0	Stop server.

## Function Details ##

### bar/1 ###

bar(Y::number()) -> number()

Debug function

### foo/1 ###

foo(X::number()) -> number()

Debug function

### init/1 ###

init(Args) -> no_return()

Args = list()

Initialize and goto receive loop.

### pulldown/1 ###

pulldown(PinNo) -> ok

PinNo = non_neg_integer()

Pull down pin.

### pullnone/1 ###

pullnone(PinNo) -> ok

PinNo = non_neg_integer()

Disable pullup and pulldown.

### pullup/1 ###

pullup(PinNo) -> ok

PinNo = non_neg_integer()

Pull up pin.

### start_link/0 ###

start_link() -> term() | {error, Reason}

Reason = term()

Starts the server

### start_poll/2 ###

start_poll(PinNo, Mode) -> ok | {error, start_poll_failed}

PinNo = non_neg_integer()

Mode = rising | falling | both

Start Polling to pin (exec poll system call in port driver).

### stop/0 ###

stop() -> ok

Stop server.


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using CefSharp.Example.Properties;

namespace CefSharp.Example
{
    internal class CefSharpSchemeHandler : ISchemeHandler
    {
        private static readonly IDictionary<string, string> ResourceDictionary;

        private string mimeType;
        private MemoryStream stream;

        static CefSharpSchemeHandler()
        {
            ResourceDictionary = new Dictionary<string, string>
            {
                { "/home.html", Resources.home_html },

                { "/assets/css/shCore.css", Resources.assets_css_shCore_css },
                { "/assets/css/shCoreDefault.css", Resources.assets_css_shCoreDefault_css },
                { "/assets/css/docs.css", Resources.assets_css_docs_css },
                { "/assets/js/application.js", Resources.assets_js_application_js },
                { "/assets/js/jquery.js", Resources.assets_js_jquery_js },
                { "/assets/js/shBrushCSharp.js", Resources.assets_js_shBrushCSharp_js },
                { "/assets/js/shCore.js", Resources.assets_js_shCore_js },

                { "/bootstrap/bootstrap-theme.min.css", Resources.bootstrap_theme_min_css },
                { "/bootstrap/bootstrap.min.css", Resources.bootstrap_min_css },
                { "/bootstrap/bootstrap.min.js", Resources.bootstrap_min_js },

                { "/BindingTest.html", Resources.BindingTest },
                { "/PopupTest.html", Resources.PopupTest },
                { "/SchemeTest.html", Resources.SchemeTest },
                { "/TooltipTest.html", Resources.TooltipTest },
            };
        }

        public bool ProcessRequestAsync(IRequest request, ICallback callback)
        {
            // The 'host' portion is entirely ignored by this scheme handler.
            var uri = new Uri(request.Url);
            var fileName = uri.AbsolutePath;

            string resource;
            if (ResourceDictionary.TryGetValue(fileName, out resource) && !string.IsNullOrEmpty(resource))
            {
                Task.Run(() =>
                {
                    var bytes = Encoding.UTF8.GetBytes(resource);
                    stream = new MemoryStream(bytes);

                    var fileExtension = Path.GetExtension(fileName);
                    mimeType = ResourceHandler.GetMimeType(fileExtension);

                    callback.Continue();
                });

                return true;
            }

            return false;
        }

        public Stream GetResponse(IResponse response, out long responseLength, out string redirectUrl)
        {
            responseLength = stream.Length;
            redirectUrl = null;

            response.StatusCode = (int)HttpStatusCode.OK;
            response.StatusText = "OK";
            response.MimeType = mimeType;

            return stream;
        }
    }
}