text:
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html

// *****************************************************************************
// This file was generated from the java source file BreakIterator.java
// *****************************************************************************

#include "unicode/utypes.h"

#if !UCONFIG_NO_BREAK_ITERATION

#include "unicode/rbbi.h"
#include "unicode/brkiter.h"
#include "unicode/udata.h"
#include "unicode/ures.h"
#include "unicode/ustring.h"
#include "unicode/filteredbrk.h"
#include "ucln_cmn.h"
#include "cstring.h"
#include "umutex.h"
#include "servloc.h"
#include "locbased.h"
#include "uresimp.h"
#include "uassert.h"
#include "ubrkimpl.h"
#include "utracimp.h"
#include "charstr.h"

// *****************************************************************************
// class BreakIterator
// This class implements methods for finding the location of boundaries in text.
// Instances of BreakIterator maintain a current position and scan over text
// returning the index of characters where boundaries occur.
// *****************************************************************************

U_NAMESPACE_BEGIN

// -------------------------------------

BreakIterator*
BreakIterator::buildInstance(const Locale& loc, const char *type, UErrorCode &status)
{
    char fnbuff[256];
    char ext[4]={'\0'};
    CharString actualLocale;
    int32_t size;
    const UChar* brkfname = NULL;
    UResourceBundle brkRulesStack;
    UResourceBundle brkNameStack;
    UResourceBundle *brkRules = &brkRulesStack;
    UResourceBundle *brkName  = &brkNameStack;
    RuleBasedBreakIterator *result = NULL;

    if (U_FAILURE(status))
        return NULL;

    ures_initStackObject(brkRules);
    ures_initStackObject(brkName);

    // Get the locale
    UResourceBundle *b = ures_openNoDefault(U_ICUDATA_BRKITR, loc.getName(), &status);

    // Get the "boundaries" array.
    if (U_SUCCESS(status)) {
        brkRules = ures_getByKeyWithFallback(b, "boundaries", brkRules, &status);
        // Get the string object naming the rules file
        brkName = ures_getByKeyWithFallback(brkRules, type, brkName, &status);
        // Get the actual string
        brkfname = ures_getString(brkName, &size, &status);
        U_ASSERT((size_t)size<sizeof(fnbuff));
        if ((size_t)size>=sizeof(fnbuff)) {
            size=0;
            if (U_SUCCESS(status)) {
                status = U_BUFFER_OVERFLOW_ERROR;
            }
        }

        // Use the string if we found it
        if (U_SUCCESS(status) && brkfname) {
            actualLocale.append(ures_getLocaleInternal(brkName, &status), -1, status);

            UChar* extStart=u_strchr(brkfname, 0x002e);
            int len = 0;
            if(extStart!=NULL){
                len = (int)(extStart-brkfname);
                u_UCharsToChars(extStart+1, ext, sizeof(ext)); // nul terminates the buff
                u_UCharsToChars(brkfname, fnbuff, len);
            }
            fnbuff[len]=0; // nul terminate
        }
    }

    ures_close(brkRules);
    ures_close(brkName);

    UDataMemory* file = udata_open(U_ICUDATA_BRKITR, ext, fnbuff, &status);
    if (U_FAILURE(status)) {
        ures_close(b);
        return NULL;
    }

    // Create a RuleBasedBreakIterator
    result = new RuleBasedBreakIterator(file, status);

    // If there is a result, set the valid locale and actual locale, and the kind
    if (U_SUCCESS(status) && result != NULL) {
        U_LOCALE_BASED(locBased, *(BreakIterator*)result);
        locBased.setLocaleIDs(ures_getLocaleByType(b, ULOC_VALID_LOCALE, &status),
                              actualLocale.data());
    }

    ures_close(b);

    if (U_FAILURE(status) && result != NULL) {  // Sometimes redundant check, but simple
        delete result;
        return NULL;
    }

    if (result == NULL) {
        udata_close(file);
        if (U_SUCCESS(status)) {
            status = U_MEMORY_ALLOCATION_ERROR;
        }
    }

    return result;
}

// Creates a break iterator for word breaks.
BreakIterator* U_EXPORT2
BreakIterator::createWordInstance(const Locale& key, UErrorCode& status)
{
    return createInstance(key, UBRK_WORD, status);
}

// -------------------------------------

// Creates a break iterator  for line breaks.
BreakIterator* U_EXPORT2
BreakIterator::createLineInstance(const Locale& key, UErrorCode& status)
{
    return createInstance(key, UBRK_LINE, status);
}

// -------------------------------------

// Creates a break iterator  for character breaks.
BreakIterator* U_EXPORT2
BreakIterator::createCharacterInstance(const Locale& key, UErrorCode& status)
{
    return createInstance(key, UBRK_CHARACTER, status);
}

// -------------------------------------

// Creates a break iterator  for sentence breaks.
BreakIterator* U_EXPORT2
BreakIterator::createSentenceInstance(const Locale& key, UErrorCode& status)
{
    return createInstance(key, UBRK_SENTENCE, status);
}

// -------------------------------------

// Creates a break iterator for title casing breaks.
BreakIterator* U_EXPORT2
BreakIterator::createTitleInstance(const Locale& key, UErrorCode& status)
{
    return createInstance(key, UBRK_TITLE, status);
}

// -------------------------------------

// Gets all the available locales that has localized text boundary data.
const Locale* U_EXPORT2
BreakIterator::getAvailableLocales(int32_t& count)
{
    return Locale::getAvailableLocales(count);
}

// ------------------------------------------
//
// Constructors, destructor and assignment operator
//
//-------------------------------------------

BreakIterator::BreakIterator()
{
    *validLocale = *actualLocale = 0;
}

BreakIterator::BreakIterator(const BreakIterator &other) : UObject(other) {
    uprv_strncpy(actualLocale, other.actualLocale, sizeof(actualLocale));
    uprv_strncpy(validLocale, other.validLocale, sizeof(validLocale));
}

BreakIterator &BreakIterator::operator =(const BreakIterator &other) {
    if (this != &other) {
        uprv_strncpy(actualLocale, other.actualLocale, sizeof(actualLocale));
        uprv_strncpy(validLocale, other.validLocale, sizeof(validLocale));
    }
    return *this;
}

BreakIterator::~BreakIterator()
{
}

// ------------------------------------------
//
// Registration
//
//-------------------------------------------
#if !UCONFIG_NO_SERVICE

// -------------------------------------

class ICUBreakIteratorFactory : public ICUResourceBundleFactory {
public:
    virtual ~ICUBreakIteratorFactory();
protected:
    virtual UObject* handleCreate(const Locale& loc, int32_t kind, const ICUService* /*service*/, UErrorCode& status) const {
        return BreakIterator::makeInstance(loc, kind, status);
    }
};

ICUBreakIteratorFactory::~ICUBreakIteratorFactory() {}

// -------------------------------------

class ICUBreakIteratorService : public ICULocaleService {
public:
    ICUBreakIteratorService()
        : ICULocaleService(UNICODE_STRING("Break Iterator", 14))
    {
        UErrorCode status = U_ZERO_ERROR;
        registerFactory(new ICUBreakIteratorFactory(), status);
    }

    virtual ~ICUBreakIteratorService();

    virtual UObject* cloneInstance(UObject* instance) const {
        return ((BreakIterator*)instance)->clone();
    }

    virtual UObject* handleDefault(const ICUServiceKey& key, UnicodeString* /*actualID*/, UErrorCode& status) const {
        LocaleKey& lkey = (LocaleKey&)key;
        int32_t kind = lkey.kind();
        Locale loc;
        lkey.currentLocale(loc);
        return BreakIterator::makeInstance(loc, kind, status);
    }

    virtual UBool isDefault() const {
        return countFactories() == 1;
    }
};

ICUBreakIteratorService::~ICUBreakIteratorService() {}

// -------------------------------------

// defined in ucln_cmn.h
U_NAMESPACE_END

static icu::UInitOnce gInitOnceBrkiter = U_INITONCE_INITIALIZER;
static icu::ICULocaleService* gService = NULL;

/**
 * Release all static memory held by breakiterator.
 */
U_CDECL_BEGIN
static UBool U_CALLCONV breakiterator_cleanup(void) {
#if !UCONFIG_NO_SERVICE
    if (gService) {
        delete gService;
        gService = NULL;
    }
    gInitOnceBrkiter.reset();
#endif
    return TRUE;
}
U_CDECL_END
U_NAMESPACE_BEGIN

static void U_CALLCONV
initService(void) {
    gService = new ICUBreakIteratorService();
    ucln_common_registerCleanup(UCLN_COMMON_BREAKITERATOR, breakiterator_cleanup);
}

static ICULocaleService*
getService(void)
{
    umtx_initOnce(gInitOnceBrkiter, &initService);
    return gService;
}

// -------------------------------------

static inline UBool
hasService(void)
{
    return !gInitOnceBrkiter.isReset() && getService() != NULL;
}

// -------------------------------------

URegistryKey U_EXPORT2
BreakIterator::registerInstance(BreakIterator* toAdopt, const Locale& locale, UBreakIteratorType kind, UErrorCode& status)
{
    ICULocaleService *service = getService();
    if (service == NULL) {
        status = U_MEMORY_ALLOCATION_ERROR;
        return NULL;
    }
    return service->registerInstance(toAdopt, locale, kind, status);
}

// -------------------------------------

UBool U_EXPORT2
BreakIterator::unregister(URegistryKey key, UErrorCode& status)
{
    if (U_SUCCESS(status)) {
        if (hasService()) {
            return gService->unregister(key, status);
        }
        status = U_MEMORY_ALLOCATION_ERROR;
    }
    return FALSE;
}

// -------------------------------------

StringEnumeration* U_EXPORT2
BreakIterator::getAvailableLocales(void)
{
    ICULocaleService *service = getService();
    if (service == NULL) {
        return NULL;
    }
    return service->getAvailableLocales();
}
#endif /* UCONFIG_NO_SERVICE */

// -------------------------------------

BreakIterator*
BreakIterator::createInstance(const Locale& loc, int32_t kind, UErrorCode& status)
{
    if (U_FAILURE(status)) {
        return NULL;
    }

#if !UCONFIG_NO_SERVICE
    if (hasService()) {
        Locale actualLoc("");
        BreakIterator *result = (BreakIterator*)gService->get(loc, kind, &actualLoc, status);
        // TODO: The way the service code works in ICU 2.8 is that if
        // there is a real registered break iterator, the actualLoc
        // will be populated, but if the handleDefault path is taken
        // (because nothing is registered that can handle the
        // requested locale) then the actualLoc comes back empty.  In
        // that case, the returned object already has its actual/valid
        // locale data populated (by makeInstance, which is what
        // handleDefault calls), so we don't touch it.  YES, A COMMENT
        // THIS LONG is a sign of bad code -- so the action item is to
        // revisit this in ICU 3.0 and clean it up/fix it/remove it.
        if (U_SUCCESS(status) && (result != NULL) && *actualLoc.getName() != 0) {
            U_LOCALE_BASED(locBased, *result);
            locBased.setLocaleIDs(actualLoc.getName(), actualLoc.getName());
        }
        return result;
    }
    else
#endif
    {
        return makeInstance(loc, kind, status);
    }
}

// -------------------------------------
enum { kKeyValueLenMax = 32 };

BreakIterator*
BreakIterator::makeInstance(const Locale& loc, int32_t kind, UErrorCode& status)
{

    if (U_FAILURE(status)) {
        return NULL;
    }
    char lbType[kKeyValueLenMax];

    BreakIterator *result = NULL;
    switch (kind) {
    case UBRK_CHARACTER:
        {
            UTRACE_ENTRY(UTRACE_UBRK_CREATE_CHARACTER);
            result = BreakIterator::buildInstance(loc, "grapheme", status);
            UTRACE_EXIT_STATUS(status);
        }
        break;
    case UBRK_WORD:
        {
            UTRACE_ENTRY(UTRACE_UBRK_CREATE_WORD);
            result = BreakIterator::buildInstance(loc, "word", status);
            UTRACE_EXIT_STATUS(status);
        }
        break;
    case UBRK_LINE:
        {
            UTRACE_ENTRY(UTRACE_UBRK_CREATE_LINE);
            uprv_strcpy(lbType, "line");
            char lbKeyValue[kKeyValueLenMax] = {0};
            UErrorCode kvStatus = U_ZERO_ERROR;
            int32_t kLen = loc.getKeywordValue("lb", lbKeyValue, kKeyValueLenMax, kvStatus);
            if (U_SUCCESS(kvStatus) && kLen > 0 && (uprv_strcmp(lbKeyValue,"strict")==0 || uprv_strcmp(lbKeyValue,"normal")==0 || uprv_strcmp(lbKeyValue,"loose")==0)) {
                uprv_strcat(lbType, "_");
                uprv_strcat(lbType, lbKeyValue);
            }
            result = BreakIterator::buildInstance(loc, lbType, status);

            UTRACE_DATA1(UTRACE_INFO, "lb=%s", lbKeyValue);
            UTRACE_EXIT_STATUS(status);
        }
        break;
    case UBRK_SENTENCE:
        {
            UTRACE_ENTRY(UTRACE_UBRK_CREATE_SENTENCE);
            result = BreakIterator::buildInstance(loc, "sentence", status);
#if !UCONFIG_NO_FILTERED_BREAK_ITERATION
            char ssKeyValue[kKeyValueLenMax] = {0};
            UErrorCode kvStatus = U_ZERO_ERROR;
            int32_t kLen = loc.getKeywordValue("ss", ssKeyValue, kKeyValueLenMax, kvStatus);
            if (U_SUCCESS(kvStatus) && kLen > 0 && uprv_strcmp(ssKeyValue,"standard")==0) {
                FilteredBreakIteratorBuilder* fbiBuilder = FilteredBreakIteratorBuilder::createInstance(loc, kvStatus);
                if (U_SUCCESS(kvStatus)) {
                    result = fbiBuilder->build(result, status);
                    delete fbiBuilder;
                }
            }
#endif
            UTRACE_EXIT_STATUS(status);
        }
        break;
    case UBRK_TITLE:
        {
            UTRACE_ENTRY(UTRACE_UBRK_CREATE_TITLE);
            result = BreakIterator::buildInstance(loc, "title", status);
            UTRACE_EXIT_STATUS(status);
        }
        break;
    default:
        status = U_ILLEGAL_ARGUMENT_ERROR;
    }

    if (U_FAILURE(status)) {
        return NULL;
    }

    return result;
}

Locale
BreakIterator::getLocale(ULocDataLocaleType type, UErrorCode& status) const {
    U_LOCALE_BASED(locBased, *this);
    return locBased.getLocale(type, status);
}

const char *
BreakIterator::getLocaleID(ULocDataLocaleType type, UErrorCode& status) const {
    U_LOCALE_BASED(locBased, *this);
    return locBased.getLocaleID(type, status);
}

// This implementation of getRuleStatus is a do-nothing stub, here to
// provide a default implementation for any derived BreakIterator classes that
// do not implement it themselves.
int32_t BreakIterator::getRuleStatus() const {
    return 0;
}

// This implementation of getRuleStatusVec is a do-nothing stub, here to
// provide a default implementation for any derived BreakIterator classes that
// do not implement it themselves.
int32_t BreakIterator::getRuleStatusVec(int32_t *fillInVec, int32_t capacity, UErrorCode &status) {
    if (U_FAILURE(status)) {
        return 0;
    }
    if (capacity < 1) {
        status = U_BUFFER_OVERFLOW_ERROR;
        return 1;
    }
    *fillInVec = 0;
    return 1;
}

BreakIterator::BreakIterator (const Locale& valid, const Locale& actual) {
  U_LOCALE_BASED(locBased, (*this));
  locBased.setLocaleIDs(valid, actual);
}

U_NAMESPACE_END

#endif /* #if !UCONFIG_NO_BREAK_ITERATION */

//eof


text:
// Copyright 2015 The Project Buendia Authors
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License.  You may obtain a copy
// of the License at: http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distrib-
// uted under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
// OR CONDITIONS OF ANY KIND, either express or implied.  See the License for
// specific language governing permissions and limitations under the License.

package org.projectbuendia.client.ui.lists;

import org.projectbuendia.client.R;
import org.projectbuendia.client.data.app.AppLocation;
import org.projectbuendia.client.data.app.AppPatient;
import org.projectbuendia.client.ui.FunctionalTestCase;

import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static org.hamcrest.Matchers.hasToString;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.core.StringStartsWith.startsWith;

/** Tests for {@link FilteredPatientListActivity}. */
public class FilteredPatientListActivityTest extends FunctionalTestCase {

    public void setUp() throws Exception {
        super.setUp();
        click(viewWithText("Guest User"));
    }

    /** Opens the patient list. */
    public void openPatientList() {
        waitForProgressFragment(); // Wait for tents.
        click(viewWithText("ALL PRESENT PATIENTS"));
        waitForProgressFragment(); // Wait for patients.
    }

    /** Looks for the filter menu. */
    public void testFilterMenu() {
        openPatientList();
        screenshot("Test Start");
        click(viewWithText("All Present Patients"));
        expectVisible(viewWithText("Triage"));
        expectVisible(viewWithText("Pregnant"));
        screenshot("In Filter Menu");
    }

    /** Looks for two zone headings and at least one patient. */
    public void testZoneAndPatientDisplayed() {
        openPatientList();
        screenshot("Test Start");
        // There should be patients in both Triage and S1.
        expectVisibleSoon(viewThat(hasTextMatchingRegex("Triage \\((No|[0-9]+) patients?\\)")));

        expectVisible(dataThat(is(AppLocation.class), hasToString(startsWith("S1")))
                .inAdapterView(withId(R.id.fragment_patient_list)));

        // Click the first patient
        click(dataThat(is(AppPatient.class))
                .inAdapterView(withId(R.id.fragment_patient_list))
                .atPosition(0));
        screenshot("After Patient Clicked");
    }
}

redpajama_set_name: RedPajamaGithub


text:
class Thrift < Formula
  desc "Framework for scalable cross-language services development"
  homepage "https://thrift.apache.org/"

  stable do
    url "https://www.apache.org/dyn/closer.cgi?path=thrift/0.9.2/thrift-0.9.2.tar.gz"
    sha256 "cef50d3934c41db5fa7724440cc6f10a732e7a77fe979b98c23ce45725349570"

    # Apply any necessary patches (none currently required)
    [
      # Example patch:
      #
      # Apply THRIFT-2201 fix from master to 0.9.1 branch (required for clang to compile with C++11 support)
      # %w{836d95f9f00be73c6936d407977796181d1a506c f8e14cbae1810ade4eab49d91e351459b055c81dba144c1ca3c5d6f4fe440925},
    ].each do |name, sha|
      patch do
        url "https://git-wip-us.apache.org/repos/asf?p=thrift.git;a=commitdiff_plain;h=#{name}"
        sha256 sha
      end
    end
  end

  bottle do
    cellar :any
    revision 2
    sha256 "4e6e392c6f93344c3f059c3967623aed6f5ea61fd44aaffb9b842c6a9aa033be" => :el_capitan
    sha256 "17c50eb2509a29e78f2e0bd402d015de4ea847c7173073e6829fef4daaf23123" => :yosemite
    sha256 "23829d79de301162576c53e51d16789dfa0584936b44bef8aa5cae2ff754aba7" => :mavericks
  end

  head do
    url "https://git-wip-us.apache.org/repos/asf/thrift.git"

    depends_on "autoconf" => :build
    depends_on "automake" => :build
    depends_on "libtool" => :build
    depends_on "pkg-config" => :build
  end

  option "with-haskell", "Install Haskell binding"
  option "with-erlang", "Install Erlang binding"
  option "with-java", "Install Java binding"
  option "with-perl", "Install Perl binding"
  option "with-php", "Install PHP binding"
  option "with-libevent", "Install nonblocking server libraries"

  depends_on "bison" => :build
  depends_on "boost"
  depends_on "openssl"
  depends_on "libevent" => :optional
  depends_on :python => :optional

  def install
    system "./bootstrap.sh" unless build.stable?

    exclusions = ["--without-ruby", "--disable-tests", "--without-php_extension"]

    exclusions << "--without-python" if build.without? "python"
    exclusions << "--without-haskell" if build.without? "haskell"
    exclusions << "--without-java" if build.without? "java"
    exclusions << "--without-perl" if build.without? "perl"
    exclusions << "--without-php" if build.without? "php"
    exclusions << "--without-erlang" if build.without? "erlang"

    ENV.cxx11 if MacOS.version >= :mavericks && ENV.compiler == :clang

    # Don't install extensions to /usr:
    ENV["PY_PREFIX"] = prefix
    ENV["PHP_PREFIX"] = prefix

    system "./configure", "--disable-debug",
                          "--prefix=#{prefix}",
                          "--libdir=#{lib}",
                          *exclusions
    ENV.j1
    system "make"
    system "make", "install"
  end

  def caveats; <<-EOS.undent
    To install Ruby binding:
      gem install thrift

    To install PHP extension for e.g. PHP 5.5:
      brew install homebrew/php/php55-thrift
  EOS
  end
end


text:
var { helperMongo, helperResp } = require("../../toppings")

module.exports = function (collName) {
    return (req, res) => {
        helperMongo.remove(collName, req.params.id, true, helperResp.handleResult(res));
    }
}


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('portals', '0001_initial'),
        ('clients', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='ClientTeamsAll',
            fields=[
                ('cta_id', models.BigIntegerField(primary_key=True, serialize=False)),
                ('created_at', models.DateTimeField()),
                ('created_by', models.CharField(max_length=30)),
                ('modified_at', models.DateTimeField()),
                ('modified_by', models.CharField(max_length=30)),
                ('cta_code', models.CharField(max_length=30)),
                ('cta_name', models.CharField(max_length=128)),
                ('pca', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='portals.PortalClientsAll')),
            ],
            options={
                'db_table': 'client_teams_all',
                'managed': True,
            },
        ),
        migrations.CreateModel(
            name='ClientUsersAll',
            fields=[
                ('cua_id', models.BigIntegerField(primary_key=True, serialize=False)),
                ('created_at', models.DateTimeField()),
                ('created_by', models.CharField(max_length=30)),
                ('modified_at', models.DateTimeField()),
                ('modified_by', models.CharField(max_length=30)),
                ('cua_username', models.CharField(max_length=30)),
                ('cua_email', models.CharField(max_length=128)),
                ('cua_fname', models.CharField(max_length=45)),
                ('cua_lname', models.CharField(max_length=45)),
                ('cua_mname', models.CharField(blank=True, max_length=45, null=True)),
                ('pca', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='portals.PortalClientsAll')),
            ],
            options={
                'db_table': 'client_users_all',
                'managed': True,
            },
        ),
        migrations.CreateModel(
            name='TeamUsersAll',
            fields=[
                ('tua_id', models.BigIntegerField(primary_key=True, serialize=False)),
                ('created_at', models.DateTimeField()),
                ('created_by', models.CharField(max_length=30)),
                ('modified_at', models.DateTimeField()),
                ('modified_by', models.CharField(max_length=30)),
                ('tua_active', models.BooleanField()),
                ('tua_role', models.CharField(max_length=45)),
                ('cta', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='clients.ClientTeamsAll')),
                ('cua', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='clients.ClientUsersAll')),
            ],
            options={
                'db_table': 'team_users_all',
                'managed': True,
            },
        ),
        migrations.AddField(
            model_name='clientteamsall',
            name='team_users',
            field=models.ManyToManyField(through='clients.TeamUsersAll', to='clients.ClientUsersAll'),
        ),
        migrations.AlterUniqueTogether(
            name='teamusersall',
            unique_together=set([('cta', 'cua')]),
        ),
        migrations.AlterUniqueTogether(
            name='clientusersall',
            unique_together=set([('pca', 'cua_email')]),
        ),
        migrations.AlterUniqueTogether(
            name='clientteamsall',
            unique_together=set([('pca', 'cta_code')]),
        ),
    ]


text:
set -euxo pipefail

function check_version_gt() {
  local required="$1"
  local input lowest
  input="$(grep -Eo '[0-9]+\.[0-9]+' /dev/stdin | head -n 1)"
  lowest="$(printf "${required}\n${input}" | sort -V | head -n 1)"
  [[ "${lowest}" == "${required}" ]]
}

function check_setup() {
  echo -e "\nChecking OS is Linux or macOS..."
  [[ "$(uname -s)" =~ (Linux|Darwin) ]]

  echo -e "\nChecking python version..."
  python --version | check_version_gt '3.9'

  echo -e "\nChecking pip version..."
  pip --version | check_version_gt '20.3'

  echo -e "\nChecking gcc version ..."
  gcc --version | check_version_gt '8'

  echo -e "\nChecking bazel version..."
  bazel --version | check_version_gt '5.2'
}

function install_dmlab2d() {
  echo -e "\nCloning dmlab2d..."
  git clone https://github.com/deepmind/lab2d

  echo -e "\nInstalling dmlab2d requirements..."
  pip install --upgrade pip packaging

  echo -e "\nBuilding dmlab2d wheel..."
  if [[ "$(uname -s)" == 'Linux' ]]; then
    local -r LUA_VERSION=luajit
  elif [[ "$(uname -s)" == 'Darwin' ]]; then
    # luajit not available on macOS
    # lua5_2 leads to continuous integration test failures.
    local -r LUA_VERSION=lua5_1
  else
    exit 1
  fi
  pushd lab2d
  C=clang CXX=clang++ bazel build \
      --compilation_mode=opt \
      --dynamic_mode=off \
      --config="${LUA_VERSION}" \
      --subcommands \
      --verbose_failures \
      --experimental_ui_max_stdouterr_bytes=-1 \
      --sandbox_debug \
      //dmlab2d:dmlab2d_wheel
  popd

  echo -e "\nInstalling dmlab2d..."
  pip install --find-links=lab2d/bazel-bin/dmlab2d dmlab2d
}

function test_dmlab2d() {
  echo -e "\nTesting dmlab2d..."
  python lab2d/dmlab2d/dmlab2d_test.py
}

function install_meltingpot() {
  echo -e "\nDownloading assets..."
  curl -L https://storage.googleapis.com/dm-meltingpot/meltingpot-assets-2.0.0.tar.gz \
      | tar -xz --directory=meltingpot

  echo -e "\nInstalling meltingpot..."
  pip install --upgrade pip setuptools
  pip install .
}

function test_meltingpot() {
  echo -e "\nTesting meltingpot..."
  pip install pytest-xdist
  pytest -n auto -rax --durations=10 meltingpot
}

function main() {
  check_setup
  install_dmlab2d
  test_dmlab2d
  install_meltingpot
  test_meltingpot
}

main "$@"


text:
FROM ubuntu:14.04

RUN echo "deb http://ppa.launchpad.net/openjdk-r/ppa/ubuntu trusty main" > /etc/apt/sources.list.d/openjdk.list && \
  apt-key adv --keyserver keyserver.ubuntu.com --recv 86F44E2A && \
  apt-get update && \
  apt-get -y install openjdk-8-jre-headless && \
  rm -rf /var/lib/apt/lists/*

RUN echo "deb http://repos.mesosphere.io/ubuntu/ trusty main" > /etc/apt/sources.list.d/mesosphere.list && \
  apt-key adv --keyserver keyserver.ubuntu.com --recv E56151BF && \
  apt-get -y update && \
  apt-get -y install mesos=0.22.1-1.0.ubuntu1404 && \
  rm -rf /var/lib/apt/lists/*


text:
import os
import zope
import oz.GuestFactory
import oz.TDL
import guestfs
import libxml2
import traceback
import json
import ConfigParser
import subprocess
import logging
from time import *
from tempfile import *
from imgfac.ApplicationConfiguration import ApplicationConfiguration
from imgfac.ImageFactoryException import ImageFactoryException
from imgfac.CloudDelegate import CloudDelegate
from imgfac.FactoryUtils import launch_inspect_and_mount, shutdown_and_close, remove_net_persist, create_cloud_info
from imgfac.FactoryUtils import check_qcow_size, qemu_convert_cmd
from xml.etree.ElementTree import fromstring
from RHEVMHelper import RHEVMHelper

def subprocess_check_output(*popenargs, **kwargs):
    if 'stdout' in kwargs:
        raise ValueError('stdout argument not allowed, it will be overridden.')

    process = subprocess.Popen(stdout=subprocess.PIPE, stderr=subprocess.STDOUT, *popenargs, **kwargs)
    stdout, stderr = process.communicate()
    retcode = process.poll()
    if retcode:
        cmd = ' '.join(*popenargs)
        raise ImageFactoryException("'%s' failed(%d): %s\nstdout: %s" % (cmd, retcode, stderr, stdout))
    return (stdout, stderr, retcode)

class RHEVM(object):
    zope.interface.implements(CloudDelegate)

    def __init__(self):
        super(RHEVM, self).__init__()
        self.app_config = ApplicationConfiguration().configuration
        self.log = logging.getLogger('%s.%s' % (__name__, self.__class__.__name__))

    def builder_should_create_target_image(self, builder, target, image_id, template, parameters):
        self.log.info('builder_should_create_target_image() called on RHEVM plugin - returning True')
        return True

    def builder_will_create_target_image(self, builder, target, image_id, template, parameters):
        # Nothing really to do here
        pass

    def activity(self, activity):
        # Simple helper function
        # Activity should be a one line human-readable string indicating the task in progress
        # We log it at DEBUG and also set it as the status_detail on our active image
        self.log.debug(activity)
        self.active_image.status_detail['activity'] = activity

    def log_exc(self):
        self.log.debug("Exception caught in ImageFactory")
        self.log.debug(traceback.format_exc())

    def build_image(self, build_id=None):
        try:
            self.build_upload(build_id)
        except:
            self.log_exc()
            self.status="FAILED"
            raise

    def builder_did_create_target_image(self, builder, target, image_id, template, parameters):
        self.log.info('builder_did_create_target_image() called in RHEVM plugin')
        self.status="BUILDING"

        # TODO: This is a convenience variable for refactoring - rename
        self.new_image_id = builder.target_image.identifier

        # TODO: More convenience vars - revisit
        self.template = template
        self.target = target
        self.builder = builder

        # This lets our logging helper know what image is being operated on
        self.active_image = self.builder.target_image

        self.tdlobj = oz.TDL.TDL(xmlstring=self.template.xml, rootpw_required=self.app_config["tdl_require_root_pw"])

        # Add in target specific content
        #TODO-URGENT: Work out how to do this in the new framework
        #self.add_target_content()

        # Oz assumes unique names - TDL built for multiple backends guarantees
        # they are not unique.  We don't really care about the name so just
        # force uniqueness
        #  Oz now uses the tdlobject name property directly in several places
        # so we must change it
        self.tdlobj.name = "factory-build-" + self.new_image_id

        # In contrast to our original builders, we enter the cloud plugins with a KVM file already
        # created as the base_image.  As a result, all the Oz building steps are gone (and can be found
        # in the OS plugin(s)

        # OS plugin has already provided the initial file for us to work with
        # which we can currently assume is a raw KVM compatible image
        self.image = builder.target_image.data

        # Add the cloud-info file
        self.modify_oz_filesystem()

        # Finally, if our format is qcow2, do the transformation here if needed
        if ("rhevm_image_format" in self.app_config) and  (self.app_config["rhevm_image_format"] == "qcow2") \
           and not check_qcow_size(self.image):
            self.log.debug("Converting RAW image to qcow2 format")
            # TODO: When RHEV adds support, use the -c option to compress these images to save space
            #       (at that point, remove the qcow check as we always want to compress)
            qemu_img_cmd = qemu_convert_cmd( self.image, self.image + ".tmp.qcow2" )
            (stdout, stderr, retcode) = subprocess_check_output(qemu_img_cmd)
            os.unlink(self.image)
            os.rename(self.image + ".tmp.qcow2", self.image)

        self.percent_complete=100
        self.status="COMPLETED"

    def modify_oz_filesystem(self):
        self.log.debug("Doing further Factory specific modification of Oz image")
        guestfs_handle = launch_inspect_and_mount(self.builder.target_image.data)
        remove_net_persist(guestfs_handle)
        create_cloud_info(guestfs_handle, self.target)
        shutdown_and_close(guestfs_handle)

    def push_image_to_provider(self, builder, provider, credentials, target, target_image, parameters):
        self.log.info('push_image_to_provider() called in RHEVM')

        # TODO: This is a convenience variable for refactoring - rename
        self.new_image_id = builder.provider_image.identifier

        self.tdlobj = oz.TDL.TDL(xmlstring=builder.target_image.template, rootpw_required=self.app_config["tdl_require_root_pw"])
        self.builder = builder
        self.active_image = self.builder.provider_image
        self.push_image(target_image, provider, credentials)

    def push_image(self, target_image_id, provider, credentials):
        try:
            self.status = "PUSHING"
            self.percent_complete = 0
            self.rhevm_push_image_upload(target_image_id, provider, credentials)
        except:
            self.log_exc()
            self.status="FAILED"
            raise
        self.status = "COMPLETED"

    def rhevm_push_image_upload(self, target_image_id, provider, credentials):
        provider_data = self.get_dynamic_provider_data(provider)
        if provider_data is None:
            raise ImageFactoryException("RHEV-M instance not found in XML or JSON provided")

        self.generic_decode_credentials(credentials, provider_data, "rhevm")

        self.log.debug("Username: %s" % (self.username))

        helper = RHEVMHelper(url=provider_data['api-url'], username=self.username, password=self.password)
        # Image is always here and it is the target_image datafile
        input_image = self.builder.target_image.data
        rhevm_uuid = helper.import_template(input_image, provider_data['nfs-host'], provider_data['nfs-path'],
                                            provider_data['nfs-dir'], provider_data['cluster'], ovf_name=str(self.new_image_id),
                                            ovf_desc = "Template name (%s) from base image (%s)" % (self.tdlobj.name, str(self.builder.base_image.identifier)) )

        if rhevm_uuid is None:
            raise ImageFactoryException("Failed to obtain RHEV-M UUID from helper")

        self.log.debug("New RHEVM Template UUID: %s " % (rhevm_uuid))

        self.builder.provider_image.identifier_on_provider = rhevm_uuid
        self.builder.provider_image.provider_account_identifier = self.username
        self.percent_complete = 100

    def delete_from_provider(self, builder, provider, credentials, target, parameters):
        self.log.debug("Deleting RHEVM template (%s)" % (self.builder.provider_image.identifier_on_provider))
        provider_data = self.get_dynamic_provider_data(provider)
        if provider_data is None:
            raise ImageFactoryException("RHEV-M instance not found in XML or JSON provided")

        self.generic_decode_credentials(credentials, provider_data, "rhevm")

        self.log.debug("Username: %s" % (self.username))

        helper = RHEVMHelper(url=provider_data['api-url'], username=self.username, password=self.password)
        if not helper.delete_template(self.builder.provider_image.identifier_on_provider):
            raise ImageFactoryException("Delete of template failed")

    def generic_decode_credentials(self, credentials, provider_data, target):
        # convenience function for simple creds (rhev-m and vmware currently)
        doc = libxml2.parseDoc(credentials)

        self.username = None
        _usernodes = doc.xpathEval("//provider_credentials/%s_credentials/username" % (target))
        if len(_usernodes) > 0:
            self.username = _usernodes[0].content
        else:
            try:
                self.username = provider_data['username']
            except KeyError:
                raise ImageFactoryException("No username specified in config file or in push call")
        self.provider_account_identifier = self.username

        _passnodes = doc.xpathEval("//provider_credentials/%s_credentials/password" % (target))
        if len(_passnodes) > 0:
            self.password = _passnodes[0].content
        else:
            try:
                self.password = provider_data['password']
            except KeyError:
                raise ImageFactoryException("No password specified in config file or in push call")

        doc.freeDoc()

    def get_dynamic_provider_data(self, provider):
        # Get provider details for RHEV-M or VSphere
        # First try to interpret this as an ad-hoc/dynamic provider def
        # If this fails, try to find it in one or the other of the config files
        # If this all fails return None
        # We use this in the builders as well so I have made it "public"

        try:
            xml_et = fromstring(provider)
            return xml_et.attrib
        except Exception as e:
            self.log.debug('Testing provider for XML: %s' % e)
            pass

        try:
            jload = json.loads(provider)
            return jload
        except ValueError as e:
            self.log.debug('Testing provider for JSON: %s' % e)
            pass

        return None

    def abort(self):
        pass


text:
namespace Google.Cloud.Dlp.V2.Snippets
{
    // [START dlp_v2_generated_DlpService_GetStoredInfoType_sync_flattened_resourceNames]
    using Google.Cloud.Dlp.V2;

    public sealed partial class GeneratedDlpServiceClientSnippets
    {
        /// <summary>Snippet for GetStoredInfoType</summary>
        /// <remarks>
        /// This snippet has been automatically generated and should be regarded as a code template only.
        /// It will require modifications to work:
        /// - It may require correct/in-range values for request initialization.
        /// - It may require specifying regional endpoints when creating the service client as shown in
        ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
        /// </remarks>
        public void GetStoredInfoTypeResourceNames()
        {
            // Create client
            DlpServiceClient dlpServiceClient = DlpServiceClient.Create();
            // Initialize request argument(s)
            StoredInfoTypeName name = StoredInfoTypeName.FromOrganizationStoredInfoType("[ORGANIZATION]", "[STORED_INFO_TYPE]");
            // Make the request
            StoredInfoType response = dlpServiceClient.GetStoredInfoType(name);
        }
    }
    // [END dlp_v2_generated_DlpService_GetStoredInfoType_sync_flattened_resourceNames]
}


text:
export class GetExamsList{
  jobId: string;
  jobTitle: string;
  jobDesc: string;
  examStartDate: string;
  examEndDate: string;
  seoKey: string;
  seoDesc: string;
  uploadDate: string;
  pageUrl: string;
  creatorId: string;
  userDTO: string[];
  active: string;
}


text:
namespace ui {
class Event;
class KeyEvent;
class LocatedEvent;
class PointerEvent;
}

namespace mus {
namespace ws {

class EventDispatcherDelegate;
class EventMatcher;
class ServerWindow;

namespace test {
class EventDispatcherTestApi;
}

// Handles dispatching events to the right location as well as updating focus.
class EventDispatcher : public ServerWindowObserver {
 public:
  explicit EventDispatcher(EventDispatcherDelegate* delegate);
  ~EventDispatcher() override;

  void set_root(ServerWindow* root) { root_ = root; }

  void set_surface_id(cc::SurfaceId surface_id) { surface_id_ = surface_id; }

  // Cancels capture and stops tracking any pointer events. This does not send
  // any events to the delegate.
  void Reset();

  void SetMousePointerScreenLocation(const gfx::Point& screen_location);
  const gfx::Point& mouse_pointer_last_location() const {
    return mouse_pointer_last_location_;
  }

  // |capture_window_| will receive all input. See window_tree.mojom for
  // details.
  ServerWindow* capture_window() { return capture_window_; }
  const ServerWindow* capture_window() const { return capture_window_; }
  // Setting capture can fail if the window is blocked by a modal window
  // (indicated by returning |false|).
  bool SetCaptureWindow(ServerWindow* capture_window, bool in_nonclient_area);

  // Retrieves the ServerWindow of the last mouse move.
  ServerWindow* mouse_cursor_source_window() const {
    return mouse_cursor_source_window_;
  }

  // Possibly updates the cursor. If we aren't in an implicit capture, we take
  // the last known location of the mouse pointer, and look for the
  // ServerWindow* under it.
  void UpdateCursorProviderByLastKnownLocation();

  // Adds an accelerator with the given id and event-matcher. If an accelerator
  // already exists with the same id or the same matcher, then the accelerator
  // is not added. Returns whether adding the accelerator was successful or not.
  bool AddAccelerator(uint32_t id, mojom::EventMatcherPtr event_matcher);
  void RemoveAccelerator(uint32_t id);

  // Processes the supplied event, informing the delegate as approriate. This
  // may result in generating any number of events.
  void ProcessEvent(const ui::Event& event);

 private:
  friend class test::EventDispatcherTestApi;

  // Keeps track of state associated with an active pointer.
  struct PointerTarget {
    PointerTarget()
        : window(nullptr),
          is_mouse_event(false),
          in_nonclient_area(false),
          is_pointer_down(false) {}

    // NOTE: this is set to null if the window is destroyed before a
    // corresponding release/cancel.
    ServerWindow* window;

    bool is_mouse_event;

    // Did the pointer event start in the non-client area.
    bool in_nonclient_area;

    bool is_pointer_down;
  };

  void ProcessKeyEvent(const ui::KeyEvent& event);

  bool IsTrackingPointer(int32_t pointer_id) const {
    return pointer_targets_.count(pointer_id) > 0;
  }

  // EventDispatcher provides the following logic for pointer events:
  // . wheel events go to the current target of the associated pointer. If
  //   there is no target, they go to the deepest window.
  // . move (not drag) events go to the deepest window.
  // . when a pointer goes down all events until the corresponding up or
  //   cancel go to the deepest target. For mouse events the up only occurs
  //   when no buttons on the mouse are down.
  // This also generates exit events as appropriate. For example, if the mouse
  // moves between one window to another an exit is generated on the first.
  void ProcessPointerEvent(const ui::PointerEvent& event);

  // Adds |pointer_target| to |pointer_targets_|.
  void StartTrackingPointer(int32_t pointer_id,
                            const PointerTarget& pointer_target);

  // Removes a PointerTarget from |pointer_targets_|.
  void StopTrackingPointer(int32_t pointer_id);

  // Starts tracking the pointer for |event|, or if already tracking the
  // pointer sends the appropriate event to the delegate and updates the
  // currently tracked PointerTarget appropriately.
  void UpdateTargetForPointer(const ui::PointerEvent& event);

  // Returns a PointerTarget from the supplied Event.
  PointerTarget PointerTargetForEvent(const ui::PointerEvent& event) const;

  // Returns true if any pointers are in the pressed/down state.
  bool AreAnyPointersDown() const;

  // If |target->window| is valid, then passes the event to the delegate.
  void DispatchToPointerTarget(const PointerTarget& target,
                               const ui::PointerEvent& event);

  // Stops sending pointer events to |window|. This does not remove the entry
  // for |window| from |pointer_targets_|, rather it nulls out the window. This
  // way we continue to eat events until the up/cancel is received.
  void CancelPointerEventsToTarget(ServerWindow* window);

  // Returns true if we're currently an observer for |window|. We are an
  // observer for a window if any pointer events are targeting it.
  bool IsObservingWindow(ServerWindow* window);

  // Looks to see if there is an accelerator bound to the specified code/flags,
  // and of the matching |phase|. If there is one, sets |accelerator_id| to the
  // id of the accelerator invoked and returns true. If there is none, returns
  // false so normal key event processing can continue.
  bool FindAccelerator(const ui::KeyEvent& event,
                       const mojom::AcceleratorPhase phase,
                       uint32_t* accelerator_id);

  // ServerWindowObserver:
  void OnWillChangeWindowHierarchy(ServerWindow* window,
                                   ServerWindow* new_parent,
                                   ServerWindow* old_parent) override;
  void OnWindowVisibilityChanged(ServerWindow* window) override;
  void OnWindowDestroyed(ServerWindow* window) override;

  EventDispatcherDelegate* delegate_;
  ServerWindow* root_;
  ServerWindow* capture_window_;

  bool capture_window_in_nonclient_area_;
  bool mouse_button_down_;
  ServerWindow* mouse_cursor_source_window_;

  // The on screen location of the mouse pointer. This can be outside the
  // bounds of |mouse_cursor_source_window_|, which can capture the cursor.
  gfx::Point mouse_pointer_last_location_;

  cc::SurfaceId surface_id_;

  using Entry = std::pair<uint32_t, EventMatcher>;
  std::map<uint32_t, EventMatcher> accelerators_;

  using PointerIdToTargetMap = std::map<int32_t, PointerTarget>;
  // |pointer_targets_| contains the active pointers. For a mouse based pointer
  // a PointerTarget is always active (and present in |pointer_targets_|). For
  // touch based pointers the pointer is active while down and removed on
  // cancel or up.
  PointerIdToTargetMap pointer_targets_;

  DISALLOW_COPY_AND_ASSIGN(EventDispatcher);
};

}  // namespace ws
}  // namespace mus

#endif  // COMPONENTS_MUS_WS_EVENT_DISPATCHER_H_


text:
package br.jus.trf2.balcaojus;

import com.crivano.swaggerservlet.PresentableUnloggedException;

import br.jus.trf2.balcaojus.AutenticarPost.Usuario;
import br.jus.trf2.balcaojus.AutenticarPost.UsuarioDetalhe;
import br.jus.trf2.balcaojus.IBalcaojus.IProcessoNumeroNotaIdDelete;
import br.jus.trf2.balcaojus.model.Nota;
import br.jus.trf2.balcaojus.model.Processo;

public class ProcessoNumeroNotaIdDelete implements IProcessoNumeroNotaIdDelete {

	@Override
	public void run(Request req, Response resp, BalcaojusContext ctx) throws Exception {
		Usuario u = BalcaojusServlet.getPrincipal();
		UsuarioDetalhe ud = u.usuarios.get(req.sistema.toLowerCase());

		if (ud == null)
			throw new PresentableUnloggedException("Usuário '" + u.usuario
					+ "' não pode fazer anotações porque não foi autenticado no órgão '" + req.sistema + "'.");

		try (Dao dao = new Dao()) {
			Nota nota = dao.find(Nota.class, Long.valueOf(req.id));
			if (nota == null)
				return;
			Processo p = dao.obtemProcesso(req.numero, req.sistema, false);
			if (p == null)
				throw new Exception("processo não encontrado");
			if (p != nota.getProcesso())
				throw new Exception("identificadores de processo inválidos");
			dao.beginTransaction();
			dao.remove(nota);
		} catch (Exception e) {
			Dao.rollbackCurrentTransaction();
			throw e;
		}
	}

	@Override
	public String getContext() {
		return "excluir nota";
	}

}


text:
function nordicicewrite(varargin)
%nordicicewrite  Writes a Nordic ICE ROI file
%
%   nordicicewrite(FILENAME,S) writes the ROI structure S contain the fields
%   'coordinates', 'size', and 'type' to the file specificied by the file
%   specified by the full file name FILENAME.
%
%   nordicicewrite(FILENAME,COOR,SIZE,TYPE) write the ROI specified by the array
%   of coordinates COOR, roi SIZE, and ROI type TYPE to the file specified by
%   the full file name FILENAME.
%
%   ROI Component       Description
%   -------------------------------
%   Coordinates         An array containing the x-y coordinates. Note that in
%                       MATLAB x-y coordinates are reversed (i.e. x=y and y=x).
%                       This utility automatically adjusts the coordinates and
%                       corrects for the 1-indexed arrays.
%
%      Type             A string specifying one of the following ROI types:
%                       'ellipse', 'polygon', 'rectangle', 'freehand'. Automatic
%                       conversions are made for 'imellipse', 'impoly',
%                       'imrect', and 'imspline', respectively, for
%                       compatability with built-in MATLAB ROIs.
%
%      Size             One of 'large', 'medium', or 'small'
%
%
%   See also nordiciceread

[fName,r,rSize,rType] = parse_inputs(varargin{:});

% Open file for writing
fid = fopen(fName,'w');
if fid==-1
    fprintf('Unable to write to file - %s',fName);
    return
end

% Format ROI information
 %rounds the coordinates and 0-indexes
switch rType
    case 'ellipse'
        r(1:2)=r(1:2)-1; r = round(r); r = r([3 4 1 2]);
    case 'polygon'
        r = round(r-1); r = permute(r,[2 1]);
    case 'rectangle'
        r(1:2)=r(1:2)-1; r = round(r); r = r([3 4 1 2]);
    case 'freehand'
        r = round(r-1); r = permute(unique(r,'rows'),[2 1]);
end

% Generate output
fprintf(fid,'%s\n%s\n',upper(rSize),rType);
fprintf(fid,'%u;%u\n',r);

% Close the file
fclose(fid);

%------------------------------------------
function varargout = parse_inputs(varargin)

% Prepare inputs for the parser
if nargin==2 && isstruct(varargin{2}) %roi structure syntax
    flds   = {'coordinates','size','type'};
    if any( ~isfield(varargin{2},flds) )
        error([mfilename ':inputChk'],['Missing fields in input structure.',...
                                       'Fields are case sensitive.']);
    end
    for idx = length(flds):-1:1 %order is important here
        varargin{idx+1} = varargin{2}.(flds{idx});
    end
elseif nargin~=4
    error([mfilename ':inputChk'],'Invalid input syntax. Type "help %s"\n',...
                                                                     mfilename);
end

% Perform conversions of ROI type strings
varargin{4} = strrep(lower(varargin{4}),'im','');
varargin{4} = strrep(varargin{4},'poly','polygon');
varargin{4} = strrep(varargin{4},'rect','rectangle');
varargin{4} = strrep(varargin{4},'spline','freehand');

% Prepare cells of valid strings
valid_sizes = {'small','medium','large'};
valid_types = {'ellipse','polygon','rectangle','freehand'};

% Parser setup
parser = inputParser;
parser.addRequired('File',@ischar);
parser.addRequired('Position',@isnumeric);
parser.addRequired('Size',@(x) any( strcmpi(x,valid_sizes) ));
parser.addRequired('Type',@(x) any( strcmpi(x,valid_types) ));

% Parse the inputs and deal
parser.parse(varargin{:});
varargout = struct2cell( parser.Results );


text:
package jlibs.jdbc.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author Santhosh Kumar T
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Insert{
}


text:
MODULE = cpu_efm32tg11b

# (file triggers compiler bug. see #5775)
SRC_NOLTO += vectors.c

include $(RIOTBASE)/Makefile.base


text:
<?php

namespace App\Providers;

use Hash;
use App\User;
use App\Staff;
use App\RaiseEquipment;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Schema::defaultStringLength(191);

        /*
         * 自動產生barcode
         */
        Staff::creating(function ($staff) {
            $staff->barcode = 'ST' . str_pad((((int) str_replace('ST', '', Staff::pluck('barcode')->last())) + 1), 3, '0', STR_PAD_LEFT);
        });

        RaiseEquipment::creating(function ($equipment) {
            $equipment->barcode = 'RE' . str_pad((((int) str_replace('RE', '', RaiseEquipment::pluck('barcode')->last())) + 1), 3, '0', STR_PAD_LEFT);
        });

        /*
         * 密碼加密
         */
        User::creating(function ($user) {
            if (Hash::needsRehash($user->password)) {
                $user->password = bcrypt($user->password);
            }
        });

        Collection::macro('plucks', function ($assoc) {
            return $this->map(function ($item) use ($assoc) {
                $list = [];
                foreach ($assoc as $key) {
                    $list[$key] = data_get($item, $key);
                }

                return $list;
            }, new static);
        });
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}


text:
package com.brotherjing.client.Class;

import android.content.Context;
import android.hardware.Camera;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import java.io.IOException;
import java.util.List;

/**
 * Created by apple on 10/14/15.
 */
public class CameraPreview extends SurfaceView {

    private SurfaceHolder mSurfaceHolder;
    @SuppressWarnings("deprecation")
    private Camera mCamera;

    @SuppressWarnings("deprecation")
    public CameraPreview(Context context, Camera camera) {
        super(context);
        mCamera = camera;

        mSurfaceHolder = getHolder();
        mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        mSurfaceHolder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder surfaceHolder) {
                //the surface has been created, now tell the camera where to draw the preview
                try {
                    mCamera.setPreviewDisplay(surfaceHolder);//链接camera和surface
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
                if (mCamera == null)
                    return;

                Camera.Parameters parameters = mCamera.getParameters();
                Camera.Size size = getBestSupportedSize(parameters.getSupportedPreviewSizes(), i1, i2);
                parameters.setPreviewSize(size.width, size.height);
                size = getBestSupportedSize(parameters.getSupportedPictureSizes(), i1, i2);
                parameters.setPictureSize(size.width, size.height);
                mCamera.setParameters(parameters);

                try {
                    mCamera.startPreview();
                } catch (Exception e) {
                    mCamera.release();
                    mCamera = null;
                }
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
                if (mCamera != null) {
                    //stops capturing and drawing preview frames to the surface and
                    //rests the camera for a future call to startPreview
                    mCamera.stopPreview();
                }
            }
        });
    }

    @SuppressWarnings("deprecation")
    private Camera.Size getBestSupportedSize(List<Camera.Size> sizes, int width, int height) {
        Camera.Size bestSize = sizes.get(0);
        int largestArea = bestSize.width * bestSize.height;
        for (Camera.Size size : sizes) {
            int area = size.width * size.height;
            if (area > largestArea) {
                largestArea = area;
                bestSize = size;
            }
        }
        return bestSize;
    }
}


text:
{% include 'header.html' %}

	<form action="" method="post" >{% csrf_token %}

	{% block preamble %}{% endblock  %}

    {% if errmsg %}

    	{{errmsg }}

    {% endif %}

	{% if theForm.errors %}

			Please correct the error{{ theForm.errors|pluralize }} below.

	{% endif %}

		{% if field_style == 'as_table' %}

	{% autoescape off %}
				{{theForm.as_table}}
	{% endautoescape %}

		{% elif field_style == 'as_p' %}
	{% autoescape off %}
			{{theForm.as_p }}
	{% endautoescape %}
		{% elif field_style == 'as_ul' %}

	{% autoescape off %}
				{{theForm.as_ul}}
	{% endautoescape %}

		{% elif field_style == 'no_style'%}
	{% autoescape off %}
				{{theForm}}
	{% endautoescape %}
		{% endif %}
	{% block postamble %}{% endblock  %}

	{% block pageImage %}{% endblock  %}

	{% if not buttons_not_enabled %}
	{% if not back_not_enabled %}
	<input class="ctlbtn" type="submit" name="submitButton" value="Back">
	{% endif %}
	<input  class="ctlbtn" type="submit" name="submitButton" value="Next">
	{% endif %}
	</form>
{% include 'footer.html' %}
{% if debugOn %}
Page tag: "{{thisPageTag}}", record number: {{thisPageRecNum}}
{% endif %}


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>org.jruyi.common Class Hierarchy (JRuyi API 1.2.0)</title>
<meta name="date" content="2014-02-20">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package org.jruyi.common

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

java.util.AbstractCollection<E> (implements java.util.Collection<E>)

java.util.AbstractSet<E> (implements java.util.Set<E>)

java.util.HashSet<E> (implements java.lang.Cloneable, java.io.Serializable, java.util.Set<E>)

org.jruyi.common.HashSet (implements org.jruyi.common.ICloseable)

org.jruyi.common.ArgList

org.jruyi.common.BiListNode<E> (implements org.jruyi.common.ICloseable)

org.jruyi.common.Blob (implements org.jruyi.common.ICloseable, org.jruyi.common.IDumpable)

org.jruyi.common.ByteKmp

org.jruyi.common.BytesBuilder (implements org.jruyi.common.IByteSequence, org.jruyi.common.ICloseable, java.io.Serializable)

org.jruyi.common.CharKmp

org.jruyi.common.CharsetCodec

java.util.Dictionary<K,V>

org.jruyi.common.Properties (implements java.lang.Cloneable, org.jruyi.common.IDumpable, java.util.Map<K,V>, java.io.Serializable)

org.jruyi.common.IntStack (implements org.jruyi.common.ICloseable)

org.jruyi.common.ListNode<E> (implements org.jruyi.common.ICloseable)

org.jruyi.common.Service (implements org.jruyi.common.IService)

org.jruyi.common.ServiceHolderManager

org.jruyi.common.StringBuilder (implements java.lang.Appendable, java.lang.CharSequence, org.jruyi.common.ICloseable, java.io.Serializable)

org.jruyi.common.StrUtil

org.jruyi.common.ThreadLocalCache

Interface Hierarchy

org.jruyi.common.ArgList.IFactory

java.lang.AutoCloseable

java.io.Closeable

org.jruyi.common.ICloseable

org.jruyi.common.IArgList (also extends org.jruyi.common.IDumpable)

org.jruyi.common.CharsetCodec.IFactory

org.jruyi.common.IByteSequence

org.jruyi.common.ICharsetCodec

org.jruyi.common.IDumpable

org.jruyi.common.IArgList (also extends org.jruyi.common.ICloseable)

org.jruyi.common.IService

org.jruyi.common.IServiceHolder<T>

org.jruyi.common.IServiceHolderManager<T>

org.jruyi.common.IThreadLocalCache<E>

org.jruyi.common.ServiceHolderManager.IFactory

org.jruyi.common.ThreadLocalCache.IFactory

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2014 JRuyi.org. All rights reserved.


text:
@interface PanelView : NSVisualEffectView
@property (nonatomic, readonly) DVTChooserView *chooserView;
@property (nonatomic, retain) NSView               *contentView;
@property (nonatomic, assign) NSWindow          *mainWindow;
@end


text:
$(document).ready(function() {

    function toggleSidebar() {
        $(".button").toggleClass("active");
        $("main").toggleClass("move-to-left");
        $(".sidebar-item").toggleClass("active");
    }

    $(".button").on("click tap", function() {
        toggleSidebar();
    });

    $(document).keyup(function(e) {
        if (e.keyCode === 27) {
            toggleSidebar();
        }
    });

});


text:
package net.akehurst.requirements.management.technology.gui.vertx.test;

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

import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;

import net.akehurst.application.framework.common.ApplicationFrameworkException;
import net.akehurst.application.framework.common.IService;
import net.akehurst.application.framework.common.interfaceUser.UserSession;
import net.akehurst.application.framework.common.test.TestConfigurationService;
import net.akehurst.application.framework.common.test.TestFramework;
import net.akehurst.application.framework.technology.interfaceGui.GuiException;
import net.akehurst.application.framework.technology.interfaceGui.IGuiRequest;
import net.akehurst.application.framework.technology.interfaceGui.SceneIdentity;
import net.akehurst.application.framework.technology.interfaceGui.StageIdentity;

public class test_oauthAuthorise {

    testContext_VertxWebsite testContext;

    @Ignore
    @Test
    public void test() throws ApplicationFrameworkException, GuiException {
        final TestFramework tf = new TestFramework("af", "af");
        final TestConfigurationService configuration = tf.createServiceInstance("configuration", TestConfigurationService.class, "test.configuration");
        configuration.set("sut.libClassPath", "");

        final Map<String, IService> services = new HashMap<>();
        services.put("configuration", configuration);
        this.testContext = tf.createTestEnvironment(testContext_VertxWebsite.class, services, new String[0]);
        this.testContext.afStart();

        final UserSession session = new UserSession("testId", null, null);
        final String clientId = "425940381741-pucip8u310q19abnnp3t8lfurjs5tse6.apps.googleusercontent.com";
        final String clientSecret = "_1256nHEyTKiumHCqvKg1m62";
        final String site = "https://accounts.google.com";
        final String tokenPath = "https://www.googleapis.com/oauth2/v3/token";
        final String authorisationPath = "/o/oauth2/auth";
        final String scopes = "";

        final StageIdentity stageId = new StageIdentity("xxx");
        final SceneIdentity sceneId = new SceneIdentity("home");
        this.testContext.sut.portGui().in(IGuiRequest.class).createStage(stageId, "/af", null, null, true);
        this.testContext.sut.portGui().in(IGuiRequest.class).createScene(stageId, sceneId, ITestScene.class, null);

        this.testContext.sut.portGui().in(IGuiRequest.class).oauthAuthorise(session, clientId, clientSecret, site, tokenPath, authorisationPath, scopes);

        Assert.assertTrue(true);
    }

}


text:
const { ipcRenderer } = require('electron')

const layout = require('dw-layout')

const logger = require('dw-log')

const settingsFile = require('path').join(__dirname, '..', 'settings.json')

let entryInputs = {}

let activeContextMenuKey = null

layout.contextMenu.add('reset-single', [
    {
        label: 'Reset this',
        value: 'reset'
    }
])
layout.contextMenu.add(
    'reset-all',
    [
        {
            label: 'Reset All',
            value: 'reset'
        }
    ],
    true
)

function checkKeyWarning() {
    for (let aKey in entryInputs) {
        if (entryInputs[aKey].type === 'key') {
            let overlaps = []

            for (let bKey in entryInputs) {
                if (
                    entryInputs[bKey].type === 'key' &&
                    aKey !== bKey &&
                    entryInputs[aKey].input.value ===
                        entryInputs[bKey].input.value
                ) {
                    overlaps.push(bKey)
                }
            }

            if (overlaps.length === 0) {
                entryInputs[aKey].warning.visible = false
            } else {
                let text = 'Warning: '
                if (overlaps.length === 1) {
                    text += "'" + entryInputs[overlaps[0]].description + "' has"
                } else if (overlaps.length === 2) {
                    text +=
                        "'" +
                        entryInputs[overlaps[0]].description +
                        "' and '" +
                        entryInputs[overlaps[1]].description +
                        "' have"
                } else {
                    text +=
                        "'" +
                        entryInputs[overlaps[0]].description +
                        "' and " +
                        (overlaps.length - 1).toString() +
                        ' other actions have'
                }

                text += ' the same shortcut!'
                entryInputs[aKey].warning.text = text

                entryInputs[aKey].warning.visible = true
            }
        }
    }
}

function onSettingChange(event) {
    if (!event.fromUser) {
        return false
    }

    if (
        entryInputs[entryInputs[event.from.key]] &&
        entryInputs[entryInputs[event.from.key]].type === 'key'
    ) {
        checkKeyWarning()
    }

    ipcRenderer.send('set-setting', event.from.key, event.value)
}
ipcRenderer.on('setting', (event, key, value) => {
    if (entryInputs.hasOwnProperty(key)) {
        entryInputs[key].input.value = value

        if (entryInputs[key].type === 'key') {
            checkKeyWarning()
        }
    }
})

function getEntryBlock(key, data) {
    let input = false

    data.tooltip = data.description

    switch (data.type) {
        case 'boolean':
            data.label = 'Enabled'
            input = new layout.CheckboxInput(data)
            break
        case 'number':
            input = new layout.NumberInput(data)
            break
        case 'color':
            input = new layout.ColorInput(data)
            break
        case 'select':
            input = new layout.SelectInput(data)

            let maxChars = 5

            for (let i = 0; i < data.options.length; i++) {
                maxChars = Math.max(maxChars, data.options[i].length)
            }

            maxChars /= 1.8

            layout.change(input, {
                width: maxChars + 'em'
            })
            break
        case 'font':
            input = new layout.FontInput(data)
            break
        case 'key':
            data.text = data.description
            input = new layout.KeyInput(data)
    }

    let warningElement = null
    if (data.type === 'key') {
        warningElement = new layout.Text(
            {
                text: 'Warning: key'
            },
            {
                maxWidth: '70ch',

                margin: 4,
                padding: 2,
                paddingLeft: 6,
                paddingRight: 6,

                background: 'hsl(0, 60%, 75%)'
            }
        )
    }

    let block = new layout.Block(
        {
            items: [
                new layout.Text({ text: data.description }),
                new layout.Filler(),
                warningElement,
                input
            ],
            childSpacing: 6
        },
        {
            direction: 'horizontal',
            grow: false,
            shrink: false,

            borderTop: true
        }
    )

    if (!input) {
        let text = 'Invalid type!'
        if (typeof data.type === 'string') {
            text += ' (' + data.type + ')'
        }

        input = new layout.Button({
            text: text
        })

        logger.error('Error: invalid type for entry:', data.type)
    }

    input.key = key

    entryInputs[key] = {
        input: input,
        type: data.type,
        description: data.description,
        warning: warningElement
    }

    input.onEvent('change', onSettingChange)

    if (typeof data.default !== 'undefined') {
        ipcRenderer.send('get-setting', key, data.default)

        block.onEvent('contextmenu', () => {
            activeContextMenuKey = key

            layout.contextMenu.enable('reset-single')
        })

        function reset() {
            input.value = data.default

            onSettingChange({
                fromUser: true,
                from: { key: key },
                value: data.default
            })
        }

        layout.contextMenu.onEvent('reset-single', event => {
            if (activeContextMenuKey === key) {
                if (event.value === 'reset') {
                    reset()
                }
            }
        })
        layout.contextMenu.onEvent('reset-all', event => {
            if (event.value === 'reset') {
                reset()
            }
        })
    } else {
        ipcRenderer.send('get-setting', key)
    }

    return block
}

function getSectionBlock(key, data) {
    if (typeof data !== 'object') {
        return false
    }

    let block = new layout.Block(
        {},
        {
            direction: 'vertical',
            align: 'stretch',
            grow: false,
            shrink: false,

            maxWidth: '100ch',

            marginTop: 8,
            marginLeft: 16
        }
    )

    for (let entry in data.entries) {
        block.add(getEntryBlock(key + '.' + entry, data.entries[entry]))
    }

    return new layout.Block(
        {
            items: [
                data.description
                    ? new layout.Text({ text: data.description })
                    : false,
                block
            ],
            childSpacing: 16
        },
        {
            direction: 'vertical',
            grow: false,
            shrink: false,

            borderBottom: true
        }
    )
}

function displaySettings(data) {
    let tabs = []

    for (let section in data) {
        if (Object.keys(data[section]).length > 0) {
            let name = data[section].name ? data[section].name : section

            let currentTab = {
                name: name,
                content: new layout.Block(
                    {},
                    {
                        direction: 'vertical',
                        overflowY: 'auto'
                    }
                )
            }

            for (let subSection in data[section]) {
                currentTab.content.add(
                    getSectionBlock(
                        typeof data[section][subSection].map === 'string'
                            ? data[section][subSection].map
                            : section + '.' + subSection,
                        data[section][subSection]
                    )
                )
            }

            layout.change(
                currentTab.content.items[currentTab.content.items.length - 1],
                {
                    borderBottom: false
                }
            )

            tabs.push(currentTab)
        }
    }

    layout.body.add(
        new layout.TabBlock({
            tabs: tabs
        })
    )
}

require('fs').readFile(settingsFile, (error, data) => {
    if (error) {
        logger.error('Unable to read settings display file:', error)

        layout.dialog.showError({
            title: 'Error loading preferences!',
            message: 'Unable to load preferences!',
            detail: error.message || error.toString()
        })
        return false
    }

    try {
        data = JSON.parse(data)

        displaySettings(data)
    } catch (error) {
        logger.error('Unable to load settings display file:', error)

        layout.dialog.showError({
            title: 'Error loading preferences!',
            message: 'Unable to load preferences!',
            detail: error.message || error.toString()
        })
    }
})


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package jp.co.kokou.sample.lifegame;

import jp.co.kokou.sample.lifegame.exceptions.InvalidSizeException;
import net.avh4.test.junit.Nested;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;

/**
 *
 * @author kozaki
 */
@RunWith(Nested.class)
public class BoardTest {

    public class 指定した縦横幅が不正の場合 {

        @Rule
        public ExpectedException exception = ExpectedException.none();

        @Test
        public void 指定した横幅がゼロの場合_InvalidSizeExceptionが発生する() {
            exception.expect(InvalidSizeException.class);
            new Board(0, 10);
        }

        @Test
        public void 指定した横幅がマイナス値の場合_InvalidSizeExceptionが発生する() {
            exception.expect(InvalidSizeException.class);
            new Board(-1, 10);
        }

        @Test
        public void 指定した縦幅がゼロの場合_InvalidSizeExceptionが発生する() {
            exception.expect(InvalidSizeException.class);
            new Board(10, 0);
        }

        @Test
        public void 指定した縦幅がマイナス値の場合_InvalidSizeExceptionが発生する() {
            exception.expect(InvalidSizeException.class);
            new Board(10, -1);
        }

    }

    public class 縦横2x3のボードを生成した場合 {

        private Board board;

        @Before
        public void setUp() {
            board = new Board(3, 2);
        }

        public class 初期状態 {
            @Test
            public void 表示すると世界はまっ白() {
                assertThat(board.toString(), is("□□□\n□□□\n"));
            }

            @Test
            public void 生存しているセルはいない() {
                assertFalse(board.hasSurvior());
            }
        }

        public class ボード内に生きているセルを配置する {

            @Before
            public void setUp() {
                board.initialize(new Position(1, 1));
            }

            @Test
            public void 生存しているセルが1x1に存在している世界となる() {
                assertThat(board.toString(), is("□□□\n□■□\n"));
            }

            @Test
            public void 生存しているセルがいる() {
                assertTrue(board.hasSurvior());
            }
        }

        public class ボード内に一度に複数のセルを配置した場合 {

            @Before
            public void setUp() {
                board.initialize(
                        new Position(1, 1),
                        new Position(2, 0)
                );
            }

            @Test
            public void 生存しているセルが複数存在している世界となる() {
                assertThat(board.toString(), is("□□■\n□■□\n"));
            }

            @Test
            public void 生存しているセルがいる() {
                assertTrue(board.hasSurvior());
            }
        }

        public class ボードの外にセルを配置した場合 {

            @Before
            public void setUp() {
                board.initialize(new Position(1, 2));
            }

            @Test
            public void 表示される世界は白いまま() {
                assertThat(board.toString(), is("□□□\n□□□\n"));
            }

            @Test
            public void 生存しているセルはいない() {
                assertFalse(board.hasSurvior());
            }
        }
    }

    public class 周辺のセルを数える {

        private Board board;

        //
        //  ■■□
        //  ■□□
        //  □□□
        //
        @Before
        public void setUp() {
            board = new Board(3, 3);
            board.initialize(new Position(0, 0), new Position(1, 0), new Position(0, 1));
        }

        @Test
        public void 隅0x0の周りにはには生きているセルが2つある() {
            assertThat(board.aroundCount(new Position(0, 0)), is(2));
            }

        @Test
        public void 中央1x1の周りには生きているセルが3つある() {
            assertThat(board.aroundCount(new Position(1, 1)), is(3));
            }

            @Test
        public void 反対の隅2x2には生きているセルはいない() {
            assertThat(board.aroundCount(new Position(2, 2)), is(0));
        }

    }
}


text:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <bean id="serviceExecuteInterceptor" class="com.bplow.netconn.newcms.intercaptor.RepositoryExecuteResultInterceptor">
    </bean>

	<bean
		class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
		<property name="beanNames" value="*Sevice*,*Repository*,*Directive*" />
		<property name="interceptorNames">
			<list>
				<value>serviceExecuteInterceptor</value>
			</list>
		</property>
	</bean>

</beans>


text:
package user

import (
	"errors"
	"go2o/core/domain/interface/merchant/user"
)

var _ user.IPerson = new(Person)

type Person struct {
	value *user.PersonValue
	rep   user.IUserRepo
}

func newPerson(v *user.PersonValue, rep user.IUserRepo) user.IPerson {
	return &Person{
		value: v,
		rep:   rep,
	}
}

func (p *Person) GetDomainId() int32 {
	return p.value.Id
}

func (p *Person) GetValue() user.PersonValue {
	return *p.value
}

func (p *Person) SetValue(v *user.PersonValue) error {
	if v.Id == p.value.Id && v.Id > 0 {
		p.value = v
		return nil
	}
	return errors.New("no such value")
}

func (p *Person) Save() (int32, error) {
	return p.rep.SavePerson(p.value)
}


text:
/*
 * This file is part of FFmpeg.
 *
 * FFmpeg is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * FFmpeg 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with FFmpeg; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include "libavutil/x86/cpu.h"

#include "libavfilter/limiter.h"

void ff_limiter_8bit_sse2(const uint8_t *src, uint8_t *dst,
                          ptrdiff_t slinesize, ptrdiff_t dlinesize,
                          int w, int h, int min, int max);
void ff_limiter_16bit_sse4(const uint8_t *src, uint8_t *dst,
                           ptrdiff_t slinesize, ptrdiff_t dlinesize,
                           int w, int h, int min, int max);

void ff_limiter_init_x86(LimiterDSPContext *dsp, int bpp)
{
    int cpu_flags = av_get_cpu_flags();

    if (EXTERNAL_SSE2(cpu_flags)) {
        if (bpp <= 8) {
            dsp->limiter = ff_limiter_8bit_sse2;
        }
    }
    if (EXTERNAL_SSE4(cpu_flags)) {
        if (bpp > 8) {
            dsp->limiter = ff_limiter_16bit_sse4;
        }
    }
}


text:
namespace
{
using namespace routing::turns::sound;

template <class TIter> string DistToTextId(TIter begin, TIter end, uint32_t dist)
{
  using TValue = typename iterator_traits<TIter>::value_type;

  TIter distToSound = lower_bound(begin, end, dist, [](TValue const & p1, uint32_t p2)
                      {
                        return p1.first < p2;
                      });
  if (distToSound == end)
  {
    ASSERT(false, ("notification.m_distanceUnits is not correct."));
    return string();
  }
  return distToSound->second;
}
}  //  namespace

namespace routing
{
namespace turns
{
namespace sound
{
void GetTtsText::SetLocale(string const & locale)
{
  m_getCurLang = platform::GetTextByIdFactory(platform::TextSource::TtsSound, locale);
}

void GetTtsText::ForTestingSetLocaleWithJson(string const & jsonBuffer, string const & locale)
{
  m_getCurLang = platform::ForTestingGetTextByIdFactory(jsonBuffer, locale);
}

string GetTtsText::operator()(Notification const & notification, const string & fallbackInstr) const
{
  if (notification.m_distanceUnits == 0 && !notification.m_useThenInsteadOfDistance)
    return fallbackInstr.length() > 0 ? fallbackInstr : GetTextById(GetDirectionTextId(notification));
  if (notification.m_useThenInsteadOfDistance && notification.m_turnDir == TurnDirection::NoTurn)
    return string();

  string const dirStr = fallbackInstr.length() > 0 ? fallbackInstr : GetTextById(GetDirectionTextId(notification));
  if (dirStr.empty())
    return string();

  string const distStr = GetTextById(GetDistanceTextId(notification));
  return distStr + " " + dirStr;
}

string GetTtsText::GetLocale() const
{
  if (m_getCurLang == nullptr)
  {
    ASSERT(false, ());
    return string();
  }
  return m_getCurLang->GetLocale();
}

string GetTtsText::GetTextById(string const & textId) const
{
  ASSERT(!textId.empty(), ());

  if (m_getCurLang == nullptr)
  {
    ASSERT(false, ());
    return string();
  }
  return (*m_getCurLang)(textId);
}

string GetDistanceTextId(Notification const & notification)
{
  if (notification.m_useThenInsteadOfDistance)
    return "then";

  switch (notification.m_lengthUnits)
  {
  case measurement_utils::Units::Metric:
    return DistToTextId(GetAllSoundedDistMeters().cbegin(), GetAllSoundedDistMeters().cend(),
                        notification.m_distanceUnits);
  case measurement_utils::Units::Imperial:
    return DistToTextId(GetAllSoundedDistFeet().cbegin(), GetAllSoundedDistFeet().cend(),
                        notification.m_distanceUnits);
  }
  ASSERT(false, ());
  return string();
}

string GetRoundaboutTextId(Notification const & notification)
{
  if (notification.m_turnDir != TurnDirection::LeaveRoundAbout)
  {
    ASSERT(false, ());
    return string();
  }
  if (!notification.m_useThenInsteadOfDistance)
    return "leave_the_roundabout"; // Notification just before leaving a roundabout.

  static const uint8_t kMaxSoundedExit = 11;
  if (notification.m_exitNum == 0 || notification.m_exitNum > kMaxSoundedExit)
    return "leave_the_roundabout";

  return "take_the_" + strings::to_string(static_cast<int>(notification.m_exitNum)) + "_exit";
}

string GetYouArriveTextId(Notification const & notification)
{
  if (notification.m_turnDir != TurnDirection::ReachedYourDestination)
  {
    ASSERT(false, ());
    return string();
  }

  if (notification.m_distanceUnits != 0 || notification.m_useThenInsteadOfDistance)
    return "destination";
  return "you_have_reached_the_destination";
}

string GetDirectionTextId(Notification const & notification)
{
  switch (notification.m_turnDir)
  {
    case TurnDirection::GoStraight:
      return "go_straight";
    case TurnDirection::TurnRight:
      return "make_a_right_turn";
    case TurnDirection::TurnSharpRight:
      return "make_a_sharp_right_turn";
    case TurnDirection::TurnSlightRight:
      return "make_a_slight_right_turn";
    case TurnDirection::TurnLeft:
      return "make_a_left_turn";
    case TurnDirection::TurnSharpLeft:
      return "make_a_sharp_left_turn";
    case TurnDirection::TurnSlightLeft:
      return "make_a_slight_left_turn";
    case TurnDirection::UTurnLeft:
    case TurnDirection::UTurnRight:
      return "make_a_u_turn";
    case TurnDirection::EnterRoundAbout:
      return "enter_the_roundabout";
    case TurnDirection::LeaveRoundAbout:
      return GetRoundaboutTextId(notification);
    case TurnDirection::ReachedYourDestination:
      return GetYouArriveTextId(notification);
    case TurnDirection::StayOnRoundAbout:
    case TurnDirection::StartAtEndOfStreet:
    case TurnDirection::TakeTheExit:
    case TurnDirection::NoTurn:
    case TurnDirection::Count:
      ASSERT(false, ());
      return string();
  }
  ASSERT(false, ());
  return string();
}
}  // namespace sound
}  // namespace turns
}  // namespace routing


text:
#ifdef __cplusplus
extern "C"
{
#endif

#ifdef __DEFINE_WPRINT_PLATFORM_TYPES__
#ifndef EXCLUDE_JPEG
#include "jpeglib.h"
#endif /* EXCLUDE_JPEG */
#ifndef EXCLUDE_PNG
#include "png.h"
#endif /* EXCLUDE_PNG */
#include <setjmp.h>

#ifndef EXCLUDE_JPEG
typedef struct
{
    struct jpeg_error_mgr pub;
    jmp_buf env;
} jpeg_error_handler_t;
#endif /* EXCLUDE_JPEG */

typedef struct
{
    union {
        /* PPM data */
        struct
        {
            unsigned int data_offset;
            unsigned char **ppm_data;
        } ppm_info;

#ifndef EXCLUDE_JPEG
        /* JPEG data */
        struct
        {
            struct jpeg_decompress_struct cinfo;
            jpeg_error_handler_t jerr;
            JSAMPARRAY *buff;
        } jpg_info;
#endif /* EXCLUDE_JPEG */

#ifndef EXCLUDE_PNG
        /* PNG data */
        struct
        {
            png_structp png_ptr;
            png_infop info_ptr;
            png_bytep *rowp;
        } png_info;
#endif /* EXCLUDE_PNG */

        struct
        {
            void *param;
            unsigned char **data_ptr;
        } osimg_info;
    };

} decoder_data_t;
#endif /* __DEFINE_WPRINT_PLATFORM_TYPES__ */

#ifdef __DEFINE_WPRINT_PLATFORM_METHODS__
int wprint_image_init(wprint_image_info_t *image_info);
#endif /* __DEFINE_WPRINT_PLATFORM_METHODS__ */

#ifdef __cplusplus
}
#endif


text:
<?php
namespace russellzhi\utility;
class SysInfo {
	private $gd;
	private $serverEnv;
	private $domainName;
	private $phpVersion;
	private $gdInfo;
	private $freeType;
	private $mysqlVersion;
	private $allowUrl;
	private $fileUpload;
	private $dbSize;
	private $maxExeTime;

	function __construct(){
		$db=D();
		$this->serverEnv =$this->getServerEnv();
		$this->domainName = $_SERVER['SERVER_NAME'];
		$this->phpVersion = PHP_VERSION;
		$this->gdInfo = $this->getGdInfo();
		$this->freeType = $this->getFreeType();
		$this->mysqlVersion =$db->dbVersion();
		$this->allowUrl = $this->getAllowUrl();
		$this->fileUpload = $this->getFileUpload();
		$this->dbSize = $db->dbSize();
		$this->maxExeTime = $this->getMaxExeTime();
	}

	private function getServerEnv() {
		return PHP_OS.' | '.$_SERVER['SERVER_SOFTWARE'];
	}

	private function getGdInfo() {
		if(function_exists('gd_info')){
			$this->gd = gd_info();
			$gdInfo = $this->gd['GD Version'];
		}else {
			$gdInfo = '未知';
		}
		return $gdInfo;
	}

	private function getFreeType() {
		if($this->gd["FreeType Support"])
			return '支持';
		else
			return '不支持';
	}

	private function getAllowUrl() {
		if(@ini_get('allow_url_fopen'))
			return '支持';
			else
			return '不支持';
	}

	private function getFileUpload() {
		if(@ini_get('file_uploads')){
			$umfs = ini_get('upload_max_filesize');
			$pms = ini_get('post_max_size');
			return '允许 | 文件:'.$umfs.' | 表单:'.$pms;
		}else{
			return '禁止';
		}
	}

	private function getMaxExeTime() {
		return ini_get('max_execution_time').'秒';
	}

	public function getSysInfos() {
		$infos=array(
			"服务器环境:" => $this->serverEnv,
			"域名:" => $this->domainName,
			"PHP版本:" => $this->phpVersion,
			"GD库版本:" => $this->gdInfo,
			"FreeType:" => $this->freeType,
			"MYSQL版本:" => $this->mysqlVersion,
			"远程文件获取:" => $this->allowUrl,
			"文件上传:" => $this->fileUpload,
			"数据库使用:" => $this->dbSize,
			"脚本最大执行时间"=> $this->maxExeTime
		);
		return $infos;
	}
}