text:
namespace content {

FakeServiceWorkerContext::FakeServiceWorkerContext() {}
FakeServiceWorkerContext::~FakeServiceWorkerContext() {}

void FakeServiceWorkerContext::AddObserver(
    ServiceWorkerContextObserver* observer) {
  observers_.AddObserver(observer);
}
void FakeServiceWorkerContext::RemoveObserver(
    ServiceWorkerContextObserver* observer) {
  observers_.RemoveObserver(observer);
}
void FakeServiceWorkerContext::RegisterServiceWorker(
    const GURL& script_url,
    const blink::StorageKey& key,
    const blink::mojom::ServiceWorkerRegistrationOptions& options,
    StatusCodeCallback callback) {
  NOTREACHED();
}
void FakeServiceWorkerContext::UnregisterServiceWorker(
    const GURL& scope,
    const blink::StorageKey& key,
    ResultCallback callback) {
  NOTREACHED();
}
ServiceWorkerExternalRequestResult
FakeServiceWorkerContext::StartingExternalRequest(
    int64_t service_worker_version_id,
    ServiceWorkerExternalRequestTimeoutType timeout_type,
    const std::string& request_uuid) {
  NOTREACHED();
  return ServiceWorkerExternalRequestResult::kWorkerNotFound;
}
ServiceWorkerExternalRequestResult
FakeServiceWorkerContext::FinishedExternalRequest(
    int64_t service_worker_version_id,
    const std::string& request_uuid) {
  NOTREACHED();
  return ServiceWorkerExternalRequestResult::kWorkerNotFound;
}
size_t FakeServiceWorkerContext::CountExternalRequestsForTest(
    const blink::StorageKey& key) {
  NOTREACHED();
  return 0u;
}
bool FakeServiceWorkerContext::ExecuteScriptForTest(
    const std::string& script,
    int64_t version_id,
    ServiceWorkerScriptExecutionCallback callback) {
  NOTREACHED();
  return false;
}
bool FakeServiceWorkerContext::MaybeHasRegistrationForStorageKey(
    const blink::StorageKey& key) {
  return registered_storage_keys_.find(key) != registered_storage_keys_.end();
}
void FakeServiceWorkerContext::GetAllOriginsInfo(
    GetUsageInfoCallback callback) {
  NOTREACHED();
}
void FakeServiceWorkerContext::DeleteForStorageKey(const blink::StorageKey& key,
                                                   ResultCallback callback) {
  NOTREACHED();
}
void FakeServiceWorkerContext::CheckHasServiceWorker(
    const GURL& url,
    const blink::StorageKey& key,
    CheckHasServiceWorkerCallback callback) {
  NOTREACHED();
}
void FakeServiceWorkerContext::CheckOfflineCapability(
    const GURL& url,
    const blink::StorageKey& key,
    const ServiceWorkerContext::CheckOfflineCapabilityCallback callback) {
  NOTREACHED();
}
void FakeServiceWorkerContext::ClearAllServiceWorkersForTest(
    base::OnceClosure) {
  NOTREACHED();
}
void FakeServiceWorkerContext::StartWorkerForScope(
    const GURL& scope,
    const blink::StorageKey& key,
    ServiceWorkerContext::StartWorkerCallback info_callback,
    ServiceWorkerContext::StatusCodeCallback failure_callback) {
  NOTREACHED();
}

bool FakeServiceWorkerContext::IsLiveRunningServiceWorker(
    int64_t service_worker_version_id) {
  NOTREACHED();
  return false;
}

service_manager::InterfaceProvider&
FakeServiceWorkerContext::GetRemoteInterfaces(
    int64_t service_worker_version_id) {
  NOTREACHED();
  static service_manager::InterfaceProvider interface_provider(
      base::ThreadTaskRunnerHandle::Get());
  return interface_provider;
}

void FakeServiceWorkerContext::StartServiceWorkerForNavigationHint(
    const GURL& document_url,
    const blink::StorageKey& key,
    StartServiceWorkerForNavigationHintCallback callback) {
  start_service_worker_for_navigation_hint_called_ = true;
}

void FakeServiceWorkerContext::StartServiceWorkerAndDispatchMessage(
    const GURL& scope,
    const blink::StorageKey& key,
    blink::TransferableMessage message,
    ResultCallback result_callback) {
  start_service_worker_and_dispatch_message_calls_.push_back(
      std::make_tuple(scope, std::move(message), std::move(result_callback)));
}

void FakeServiceWorkerContext::StopAllServiceWorkersForStorageKey(
    const blink::StorageKey& key) {
  stop_all_service_workers_for_origin_calls_.push_back(key.origin());
}

void FakeServiceWorkerContext::StopAllServiceWorkers(base::OnceClosure) {
  NOTREACHED();
}

const base::flat_map<int64_t, ServiceWorkerRunningInfo>&
FakeServiceWorkerContext::GetRunningServiceWorkerInfos() {
  NOTREACHED();
  static const base::NoDestructor<
      base::flat_map<int64_t, ServiceWorkerRunningInfo>>
      empty_running_workers;
  return *empty_running_workers;
}

void FakeServiceWorkerContext::NotifyObserversOnVersionActivated(
    int64_t version_id,
    const GURL& scope) {
  for (auto& observer : observers_)
    observer.OnVersionActivated(version_id, scope);
}

void FakeServiceWorkerContext::NotifyObserversOnVersionRedundant(
    int64_t version_id,
    const GURL& scope) {
  for (auto& observer : observers_)
    observer.OnVersionRedundant(version_id, scope);
}

void FakeServiceWorkerContext::NotifyObserversOnNoControllees(
    int64_t version_id,
    const GURL& scope) {
  for (auto& observer : observers_)
    observer.OnNoControllees(version_id, scope);
}

void FakeServiceWorkerContext::AddRegistrationToRegisteredStorageKeys(
    const blink::StorageKey& key) {
  registered_storage_keys_.insert(key);
}

}  // namespace content


text:
<?php

namespace Ilios\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;

/**
 * Removes the mesh_user_selection table from the db schema.
 *
 * @link https://github.com/ilios/ilios/issues/935
 */
class Version20150819000940 extends AbstractMigration
{
    /**
     * @param Schema $schema
     */
    public function up(Schema $schema)
    {
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('DROP TABLE mesh_user_selection');
    }

    /**
     * @param Schema $schema
     */
    public function down(Schema $schema)
    {
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('CREATE TABLE mesh_user_selection (mesh_user_selection_id INT AUTO_INCREMENT NOT NULL, mesh_descriptor_uid VARCHAR(9) NOT NULL COLLATE utf8_unicode_ci, search_phrase VARCHAR(127) NOT NULL COLLATE utf8_unicode_ci, INDEX IDX_650D32BFCDB3C93B (mesh_descriptor_uid), PRIMARY KEY(mesh_user_selection_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB');
        $this->addSql('ALTER TABLE mesh_user_selection ADD CONSTRAINT FK_650D32BFCDB3C93B FOREIGN KEY (mesh_descriptor_uid) REFERENCES mesh_descriptor (mesh_descriptor_uid) ON DELETE CASCADE');
    }
}

redpajama_set_name: RedPajamaGithub


text:
@media all {
    .skinLayoutGuide {
        font-size: 14px;
        font-family: helvetica, sans-serif;
        background: #222;
    }
}

@media print {
    .skinLayoutGuide {
        background-color: #FFF;
    }
}


text:
class Api::PicturesController < Api::ApiController

  def index
    ad = Ad.find(params[:ad_id])
    @pictures = ad.pictures
  end

  def create
    ad = Ad.find(params[:ad_id])
    if params[:pictures].present?
      params[:pictures].each do |picture|
        if ad.pictures.size < 6
          @picture = ad.pictures.new(image: picture)
          render :create, status: 500 unless @picture.save
        end
      end
    end
    Ad.send_latest_ads_to_pusher
  end

  def destroy
    if pic = Picture.find(params[:id])
      ad = Ad.find(pic.ad_id)
      pic.destroy
      Ad.send_latest_ads_to_pusher
      head 200
    else
      head 500
    end
  end

end


text:
var moment          = require('moment'),
    date;

date = function (context, options) {
    if (!options && context.hasOwnProperty('hash')) {
        options = context;
        context = undefined;

        // set to published_at by default, if it's available
        // otherwise, this will print the current date
        if (this.published_at) {
            context = this.published_at;
        }
    }

    // ensure that context is undefined, not null, as that can cause errors
    context = context === null ? undefined : context;
    moment.lang("zh-cn");
    var f = options.hash.format || 'MMM Do, YYYY',
        timeago = options.hash.timeago,
        date;

    if (timeago) {
        date = moment(context).fromNow();
    } else {
        date = moment(context).format(f);
    }
    moment.lang("en");
    return date;
};

module.exports = date;


text:
package org.apache.asterix.om.typecomputer.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.asterix.om.base.AString;
import org.apache.asterix.om.base.IAObject;
import org.apache.asterix.om.constants.AsterixConstantValue;
import org.apache.asterix.om.typecomputer.base.IResultTypeComputer;
import org.apache.asterix.om.types.AOrderedListType;
import org.apache.asterix.om.types.ARecordType;
import org.apache.asterix.om.types.ATypeTag;
import org.apache.asterix.om.types.AUnionType;
import org.apache.asterix.om.types.IAType;
import org.apache.asterix.om.types.TypeHelper;
import org.apache.commons.lang3.mutable.Mutable;
import org.apache.hyracks.algebricks.common.exceptions.AlgebricksException;
import org.apache.hyracks.algebricks.core.algebra.base.ILogicalExpression;
import org.apache.hyracks.algebricks.core.algebra.base.LogicalExpressionTag;
import org.apache.hyracks.algebricks.core.algebra.expressions.AbstractFunctionCallExpression;
import org.apache.hyracks.algebricks.core.algebra.expressions.AbstractLogicalExpression;
import org.apache.hyracks.algebricks.core.algebra.expressions.ConstantExpression;
import org.apache.hyracks.algebricks.core.algebra.expressions.IVariableTypeEnvironment;
import org.apache.hyracks.algebricks.core.algebra.metadata.IMetadataProvider;

public class RecordAddFieldsTypeComputer implements IResultTypeComputer {
    public static final RecordAddFieldsTypeComputer INSTANCE = new RecordAddFieldsTypeComputer();

    private static final String FIELD_NAME_NAME = "field-name";
    private static final String FIELD_VALUE_VALUE = "field-value";

    private RecordAddFieldsTypeComputer() {
    }

    @Override
    public IAType computeType(ILogicalExpression expression, IVariableTypeEnvironment env,
            IMetadataProvider<?, ?> metadataProvider) throws AlgebricksException {

        AbstractFunctionCallExpression funcExpr = (AbstractFunctionCallExpression) expression;
        IAType type0 = (IAType) env.getType(funcExpr.getArguments().get(0).getValue());

        ARecordType inputRecordType = TypeComputerUtils.extractRecordType(type0);
        if (inputRecordType == null) {
            throw new AlgebricksException("Input record cannot be null");
        }

        AbstractLogicalExpression arg1 = (AbstractLogicalExpression) funcExpr.getArguments().get(1).getValue();
        IAType type1 = (IAType) env.getType(arg1);
        AOrderedListType inputOrderedListType = TypeComputerUtils.extractOrderedListType(type1);
        if (inputOrderedListType == null) {
            return inputRecordType;
        }

        boolean nullable = TypeHelper.canBeNull(type0) || TypeHelper.canBeNull(type1);
        Map<String, IAType> additionalFields = new HashMap<>();
        List<String> resultFieldNames = new ArrayList<>();
        List<IAType> resultFieldTypes = new ArrayList<>();

        resultFieldNames.addAll(Arrays.asList(inputRecordType.getFieldNames()));
        Collections.sort(resultFieldNames);

        for (String fieldName : resultFieldNames) {
            if (inputRecordType.getFieldType(fieldName).getTypeTag() == ATypeTag.RECORD) {
                ARecordType nestedType = (ARecordType) inputRecordType.getFieldType(fieldName);
                //Deep Copy prevents altering of input types
                resultFieldTypes.add(nestedType.deepCopy(nestedType));
            } else {
                resultFieldTypes.add(inputRecordType.getFieldType(fieldName));
            }
        }

        if (!containsVariable(arg1)) {
            AbstractFunctionCallExpression f = (AbstractFunctionCallExpression) arg1;
            List<Mutable<ILogicalExpression>> args = f.getArguments();

            AString fieldName = null;
            IAType fieldType = null;

            // Iterating through the orderlist input
            for (Mutable<ILogicalExpression> arg : args) {
                AbstractFunctionCallExpression recConsExpr = (AbstractFunctionCallExpression) arg.getValue();
                ARecordType rtype = TypeComputerUtils.extractRecordType((IAType) env.getType(recConsExpr));
                if (rtype != null) {
                    String[] fn = rtype.getFieldNames();
                    IAType[] ft = rtype.getFieldTypes();
                    for (int j = 0; j < fn.length; j++) {
                        if (fn[j].equals(FIELD_NAME_NAME)) {
                            ILogicalExpression fieldNameExpr = recConsExpr.getArguments().get(j).getValue();
                            switch (fieldNameExpr.getExpressionTag()) {
                                case CONSTANT: // Top fields only
                                    IAObject object = ((AsterixConstantValue) ((ConstantExpression) fieldNameExpr)
                                            .getValue()).getObject();
                                    if (object.getType().getTypeTag() == ATypeTag.STRING) {
                                        // Get the actual "field-name" string
                                        ILogicalExpression recFieldExpr = recConsExpr.getArguments().get(j + 1)
                                                .getValue();
                                        if (recFieldExpr.getExpressionTag() == LogicalExpressionTag.CONSTANT) {
                                            fieldName = (AString) ((AsterixConstantValue) ((ConstantExpression) recFieldExpr)
                                                    .getValue()).getObject();
                                        }
                                    }
                                    break;
                                default:
                                    throw new AlgebricksException(fieldNameExpr + " is not supported.");
                            }
                        } else if (fn[j].equals(FIELD_VALUE_VALUE)) {
                            fieldType = ft[j];
                        }
                    }
                    if (fieldName != null) {
                        additionalFields.put(fieldName.getStringValue(), fieldType);
                    }
                }
            }

            if (!additionalFields.isEmpty()) {
                Iterator<Map.Entry<String, IAType>> it = additionalFields.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry<String, IAType> entry = it.next();
                    resultFieldNames.add(entry.getKey());
                    resultFieldTypes.add(entry.getValue());
                }
            }
        } // If variable ignore, deal with the addition at runtime

        String resultTypeName = "appended(" + inputRecordType.getTypeName() + ")";
        int n = resultFieldNames.size();
        IAType resultType = new ARecordType(resultTypeName, resultFieldNames.toArray(new String[n]),
                resultFieldTypes.toArray(new IAType[n]), true);
        if (nullable) {
            resultType = AUnionType.createNullableType(resultType);
        }
        return resultType;
    }

    // Handle variable as input
    private boolean containsVariable(ILogicalExpression expression) {
        if (expression.getExpressionTag() == LogicalExpressionTag.FUNCTION_CALL) {
            AbstractFunctionCallExpression f = (AbstractFunctionCallExpression) expression;
            List<Mutable<ILogicalExpression>> args = f.getArguments();
            for (Mutable<ILogicalExpression> arg : args) {
                ILogicalExpression subExpression = arg.getValue();
                switch (subExpression.getExpressionTag()) {
                    case VARIABLE:
                        return true;
                    case CONSTANT:
                        return false;
                    default: //FUNCTION_CALL
                        return containsVariable(subExpression);
                }
            }
        }
        return true;
    }

}


text:
title: Checked Exceptions Rollback Transactions Since GORM 6.0.0
date: June 27, 2017
description: Learn about the changes to exceptions rollback behaviour introduced in GORM 6.
author: Sergio Del Amo Caballero
image: 2017-06-27.jpg
CSS: [%url]/stylesheets/prism.css
JAVASCRIPT: [%url]/javascripts/prism.js
---

# [%title]

[%author]

[%date]

Tags: #gorm

[Programming Groovy 2](https://pragprog.com/book/vslg2/programming-groovy-2):
 > Groovy has less ceremony than Java. That's crystal-clear in exception handling. Java forces us to handle checked exceptions. Groovy does not force us to handle exceptions that we don't want to handle or that are inappropriate at the current level of code. Any exception we don't handle is automatically passed on to a higher level.

Although the distinction between checked exceptions and runtime exceptions in Groovy is blurred, **GORM versions before 6.0.0 did not roll back transactions for checked `Exceptions`**. However, they rollbacked transactions for runtime exceptions.

Grails<sup>®</sup> 3.2.0 shipped with GORM 6.0.0. One of the changes introduced by GORM 6.0.0 is that if a transactional method throws an `Exception` (both checked or runtime exception), the transaction will automatically be rolled back. Thus, same behavior for checked and runtime exceptions as you may expect in Groovy.

The previous behavior is better illustrated  with an example:

Given a Checked Exception

```groovy
package demo

import groovy.transform.CompileStatic

@CompileStatic
class CustomCheckedException extends Exception {
}
```

and a RuntimeException

```groovy
package demo

import groovy.transform.CompileStatic

@CompileStatic
class CustomRuntimeException extends RuntimeException {
}
```

and the next service:

```groovy
package demo

import grails.transaction.Transactional
import groovy.transform.CompileStatic

@CompileStatic
@Transactional
class BookService {

    void addNewBookChecked() {
        def book = new Book(name: 'The definitive guide to grails 3')
        book.save()
        throw new CustomCheckedException()
    }

    void addNewBookRuntime() {
        def book = new Book(name: 'The definitive guide to grails 3')
        book.save()
        throw new CustomRuntimeException()
    }

    void addNewBookRegular() {
        def book = new Book(name: 'The definitive guide to grails 2')
        book.save()
    }

    @Transactional(readOnly = true)
    int count() {
        Book.where { }.count() as int
    }
}
```

The next specification passes for versions of GORM 6.0.0 or beyond.

```groovy
package demo

import spock.lang.Specification
import spock.lang.Subject
import grails.test.mixin.integration.Integration

@Integration
class BookServiceIntegrationSpec extends Specification {

    @Subject
    BookService bookService

    def "calling a service method which does not throw any exception results in adding a new book"() {
        when:
        bookService.addNewBookRegular()

        then:
        bookService.count() == old(bookService.count()) + 1
    }

    def "calling a service method which throws a runtime exception, rollback transaction and it does not add a new book"() {
        when:
        bookService.addNewBookRuntime()

        then:
        thrown CustomRuntimeException
        bookService.count() == old(bookService.count())
    }

	// Fails with GORM versions < 6.0.0
    def "calling a service method which throws a Checked exception, rollback transaction and it does not add a new book"() {
        when:
        bookService.addNewBookChecked()

        then:
        thrown CustomCheckedException
        bookService.count() == old(bookService.count())
    }
}
```


text: ALTER TABLE foo ADD COLUMN b INT64;


text: TextBreaker in C#


text:
<?php

namespace Stripe\Service;

/**
 * @internal
 * @covers \Stripe\Service\OAuthService
 */
final class OAuthServiceTest extends \Stripe\TestCase
{
    use \Stripe\TestHelper;

    /** @var \Stripe\StripeClient */
    private $client;

    /** @var OAuthService */
    private $service;

    protected function setUpService()
    {
        $this->client = new \Stripe\StripeClient(['api_key' => 'sk_test_123', 'api_base' => MOCK_URL, 'client_id' => 'ca_123']);
        $this->service = new OAuthService($this->client);
    }

    protected function setUpServiceWithNoClientId()
    {
        $this->client = new \Stripe\StripeClient(['api_key' => 'sk_test_123', 'api_base' => MOCK_URL]);
        $this->service = new OAuthService($this->client);
    }

    public function testAuthorizeUrl()
    {
        $this->setUpService();
        $uriStr = $this->service->authorizeUrl([
            'scope' => 'read_write',
            'state' => 'csrf_token',
            'stripe_user' => [
                'email' => 'test@example.com',
                'url' => 'https://example.com/profile/test',
                'country' => 'US',
            ],
        ]);

        $uri = \parse_url($uriStr);
        \parse_str($uri['query'], $params);

        static::assertSame('https', $uri['scheme']);
        static::assertSame('connect.stripe.com', $uri['host']);
        static::assertSame('/oauth/authorize', $uri['path']);

        static::assertSame('ca_123', $params['client_id']);
        static::assertSame('read_write', $params['scope']);
        static::assertSame('test@example.com', $params['stripe_user']['email']);
        static::assertSame('https://example.com/profile/test', $params['stripe_user']['url']);
        static::assertSame('US', $params['stripe_user']['country']);
    }

    public function testAuthorizeUrlRaisesAuthenticationErrorWhenNoClientId()
    {
        $this->setUpServiceWithNoClientId();
        $this->expectException(\Stripe\Exception\AuthenticationException::class);
        $this->compatExpectExceptionMessageMatches('#No client_id provided#');
        $uriStr = $this->service->authorizeUrl();
    }

    public function testAuthorizeUrlRaisesInvalidArgumentExceptionWhenConnectBase()
    {
        $this->setUpService();
        $this->expectException(\Stripe\Exception\InvalidArgumentException::class);
        $this->compatExpectExceptionMessageMatches('#Use `api_base`#');
        $uriStr = $this->service->authorizeUrl(null, ['connect_base' => 'foo']);
    }

    public function testDeauthorizeRaisesAuthenticationErrorWhenNoClientId()
    {
        $this->setUpServiceWithNoClientId();
        $this->expectException(\Stripe\Exception\AuthenticationException::class);
        $this->compatExpectExceptionMessageMatches('#No client_id provided#');
        $this->service->deauthorize();
    }

    public function testToken()
    {
        $this->setUpService();
        $this->stubRequest(
            'POST',
            '/oauth/token',
            [
                'grant_type' => 'authorization_code',
                'code' => 'this_is_an_authorization_code',
                'client_secret' => 'sk_test_123',
            ],
            null,
            false,
            [
                'access_token' => 'sk_access_token',
                'scope' => 'read_only',
                'livemode' => false,
                'token_type' => 'bearer',
                'refresh_token' => 'sk_refresh_token',
                'stripe_user_id' => 'acct_test',
                'stripe_publishable_key' => 'pk_test',
            ],
            200,
            $this->client->getConnectBase()
        );

        $resp = $this->client->oauth->token([
            'grant_type' => 'authorization_code',
            'code' => 'this_is_an_authorization_code',
        ]);
        static::assertSame('sk_access_token', $resp->access_token);
    }

    public function testDeauthorize()
    {
        $this->setUpService();
        $this->stubRequest(
            'POST',
            '/oauth/deauthorize',
            [
                'client_id' => 'ca_123',
                'stripe_user_id' => 'acct_test',
            ],
            null,
            false,
            [
                'stripe_user_id' => 'acct_test',
            ],
            200,
            $this->client->getConnectBase()
        );

        $resp = $this->client->oauth->deauthorize([
            'client_id' => 'ca_123',
            'stripe_user_id' => 'acct_test',
        ]);
        static::assertSame('acct_test', $resp->stripe_user_id);
    }
}


text:
function smp = mtc_SmoothnessSMP(hfile, srf)
% MTC::SmoothnessSMP  - compute inherent smoothness in (residual) data
%
% FORMAT:       smp = mtc.SmoothnessSMP(srf)
%
% Input fields:
%
%       srf         object containing the vertices information
%
% Output fields:
%
%       smp         SMP with estimated smoothness map

% Version:  v0.9d
% Build:    14061710
% Date:     Jun-17 2014, 10:30 AM EST
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://neuroelf.net/
%
% Copyright (c) 2012, 2014, Jochen Weber
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
%     * Redistributions of source code must retain the above copyright
%       notice, this list of conditions and the following disclaimer.
%     * Redistributions in binary form must reproduce the above copyright
%       notice, this list of conditions and the following disclaimer in the
%       documentation and/or other materials provided with the distribution.
%     * Neither the name of Columbia University nor the
%       names of its contributors may be used to endorse or promote products
%       derived from this software without specific prior written permission.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
% ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
% WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
% DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
% DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
% (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
% LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
% ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
% (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
% SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

% argument check
if nargin < 2 || ...
    numel(hfile) ~= 1 || ...
   ~xffisobject(hfile, true, 'mtc') || ...
    numel(srf) ~= 1 || ...
   ~xffisobject(srf, true, 'srf')
    error( ...
        'xff:BadArgument', ...
        'Invalid call to %s.', ...
        mfilename ...
    );
end

% get object data
mtcsc = xffgetscont(hfile.L);
mtcc = mtcsc.C;
mtcd = mtcc.MTCData;
srfsc = xffgetscont(srf.L);
srfc = srfsc.C;

% get neighbors array from surface
na = mesh_neighborsarray(srfc.Neighbors, 1);

% get numbers
nv = size(na, 1);
nn = size(na, 2);
nt = size(mtcd, 1);

% create array for correlation data
cr = zeros(nv, nn);

% process in 100MB steps
vs = ceil(2.5e7 / (nn * nt));
ntc = zeros(vs, nn, nt);
for vc = 1:vs:nv

    % get end index and number of indices
    ve = min(vc + vs - 1, nv);
    nve = 1 + ve - vc;
    if nve < vs
        ntc = zeros(nve, nn, nt);
    end

    % fill time course array with neighbors' time courses
    for nc = 1:nn
        ntc(:, nc, :) = reshape(mtcd(:, na(vc:ve, nc))', [nve, 1, nt]);
    end

    % compute correlation of each vertex with all (direct) neighbors
    [cv, crp] = cov_nd( ...
        repmat(double(reshape(mtcd(:, vc:ve)', [nve, 1, nt])), 1, nn), ntc);
    cr(vc:ve, :) = crp;
end

% remove illegal values
cr(isnan(cr) | isinf(cr)) = 0;

% create array for coordinates of neighbors (to compute distances)
crd = srfc.VertexCoordinate;
ccrd = zeros(nv, 3, nn);

% get neighbors' coordinates
for nc = 1:nn
    ccrd(:, :, nc) = crd(na(:, nc), :);
end

% compute distances
dcrd = squeeze(sqrt(sum((repmat(crd, [1, 1, nn]) - ccrd) .^ 2, 2)));

% compute smoothness in mm, compare resestsmooth code and link
% http://www.fmrib.ox.ac.uk/analysis/techrep/tr00df1/tr00df1/node6.html
sef = sqrt(8 * log(2));
fwhm = sef .* dcrd .* sqrt(-1 ./ (4 .* log(cr)));
fwhm(isinf(fwhm) | isnan(fwhm)) = 0;

% compute distance-weighted average for each vertex
idist = 1 ./ dcrd;
idist(isinf(idist) | isnan(idist)) = 0;
vfwhm = sum(idist .* fwhm, 2) ./ sum(idist, 2);
mfwhm = minmaxmean(vfwhm(vfwhm > 0), 5);

% create map
smp = bless(xff('new:smp'));
smpc = xffgetcont(smp.L);
smpc.NameOfOriginalSRF = srfsc.F;
smpc.Map(:) = [];
smpc.Map(1).Type = 1;
smpc.Map.ClusterSize = 25;
smpc.Map.EnableClusterCheck = 0;
smpc.Map.LowerThreshold = mfwhm(3) - 3 * sqrt(mfwhm(6));
smpc.Map.UpperThreshold = mfwhm(3) + 3 * sqrt(mfwhm(6));
smpc.Map.UseValuesAboveThresh = 1;
smpc.Map.DF1 = nt - 1;
smpc.Map.DF2 = 0;
smpc.Map.ShowPositiveNegativeFlag = 3;
smpc.Map.BonferroniValue = 40962;
smpc.Map.RGBLowerThreshPos = [192 0 0];
smpc.Map.RGBUpperThreshPos = [255 192 0];
smpc.Map.RGBLowerThreshNeg = [0 0 128];
smpc.Map.RGBUpperThreshNeg = [0 128 255];
smpc.Map.UseRGBColor = 1;
smpc.Map.LUTName = '<default>';
smpc.Map.TransColorFactor = 1;
smpc.Map.Name = sprintf('Smoothness of %s (%s)', mtcsc.F, srfsc.F);
smpc.Map.SMPData = single(vfwhm);
xffsetcont(smp.L, smpc);


text:
package gcewing.sg;

public interface ITickable {
    void update();
}


text:
from task.celery_app import app, logger
from .gspread import GoogleSpreadSheetsTasks

gs_tasks = GoogleSpreadSheetsTasks()

@app.task(bind=True, rate_limit='1/s', retry_kwargs={'max_retries': 3})
def send2ws(self, data, **kwargs):
    logger.debug("send2ws")
    try:
        result = gs_tasks.send2ws(data, **kwargs)
    except Exception as e:
        logger.error("gspread task error:{}".format(e))
        raise self.retry(exc=e, countdown=30)
    return result


text:
package steps;

import org.jbehave.core.annotations.AfterStories;
import org.jbehave.core.annotations.Named;
import org.jbehave.core.annotations.When;

public class UtilSteps {
    @When("waiting for synchronization '$seconds' seconds")
    public void waiting(@Named("seconds") int seconds) {
    }

    @AfterStories
    public void tearDown() {
    }
}


text:
var Record = require("./Record.js");
var Level = require("./Level.js");

module.exports = function(name, add_record_closure){
	this.register = function(level, msg){
		add_record_closure(new Record(name, level, msg));
	};

	this.trace = function(msg){
		add_record_closure(new Record(name, Level.trace, msg));
	}

	this.log = function(msg){
		add_record_closure(new Record(name, Level.log, msg));
	}

	this.info = function(msg){
		add_record_closure(new Record(name, Level.info, msg));
	}

	this.warn = function(msg){
		add_record_closure(new Record(name, Level.warn, msg));
	}

	this.error = function(msg){
		add_record_closure(new Record(name, Level.error, msg));
	}

	return this;
}


text:
(function () {
  'use strict';

  angular
    .module('core')
    .factory('menuService', menuService);

  function menuService() {
    var shouldRender;
    var service = {
      addMenu: addMenu,
      addMenuItem: addMenuItem,
      addSubMenuItem: addSubMenuItem,
      defaultRoles: ['user', 'admin'],
      getMenu: getMenu,
      getMenus: getMenus,
      menus: [],
      removeMenu: removeMenu,
      removeMenuItem: removeMenuItem,
      removeSubMenuItem: removeSubMenuItem,
      validateMenuExistence: validateMenuExistence
    };

    init();

    return service;

    // Add new menu object by menu id
    function addMenu(menuId, options) {
      options = options || {};

      // Create the new menu
      service.menus.push({
        id: menuId,
        caption: options.caption,
        roles: options.roles || service.defaultRoles,
        items: options.items || [],
        shouldRender: shouldRender
      });

      // Return the menu object
      return service.menus[service.menus.length-1];
    }

    // Add menu item object
    function addMenuItem(menuId, options) {
      options = options || {};

      // Validate that the menu exists
      service.validateMenuExistence(menuId);

      var menu = service.validateMenuExistence(menuId);

      // Push new menu item
      menu.items.push({
        title: options.title || '',
        icon: options.icon || '',
        state: options.state || '',
        type: options.type || 'item',
        class: options.class,
        roles: ((options.roles === null || typeof options.roles === 'undefined') ? service.defaultRoles : options.roles),
        position: options.position || 0,
        items: [],
        shouldRender: shouldRender
      });

      // Add submenu items
      if (options.items) {
        for (var i in options.items) {
          if (options.items.hasOwnProperty(i)) {
            service.addSubMenuItem(menuId, options.state, options.items[i]);
          }
        }
      }

      // Return the menu object
      return menu;
    }

    // Add submenu item object
    function addSubMenuItem(menuId, parentItemState, options) {
      options = options || {};

      // Validate that the menu exists
      var menu = service.validateMenuExistence(menuId);

      // Search for menu item
      for (var itemIndex in menu.items) {
        if (menu.items[itemIndex].state === parentItemState) {
          // Push new submenu item
          menu.items[itemIndex].items.push({
            title: options.title || '',
            state: options.state || '',
            params: options.params || {},
            roles: ((options.roles === null || typeof options.roles === 'undefined') ? menu.items[itemIndex].roles : options.roles),
            position: options.position || 0,
            shouldRender: shouldRender
          });
        }
      }

      // Return the menu object
      return menu;
    }

    // Get the menu object by menu id
    function getMenu(menuId) {

      // Return the menu object
      return service.validateMenuExistence(menuId);
    }

    // Get all menus
    function getMenus(){
      return service.menus;
    }

    function init() {
      // A private function for rendering decision
      shouldRender = function (user) {
        if (this.roles.indexOf('*') !== -1) {
          return true;
        } else {
          if (!user) {
            return false;
          }

          for (var userRoleIndex in user.roles) {
            if (user.roles.hasOwnProperty(userRoleIndex)) {
              for (var roleIndex in this.roles) {
                if (this.roles.hasOwnProperty(roleIndex) && this.roles[roleIndex] === user.roles[userRoleIndex]) {
                  return true;
                }
              }
            }
          }
        }

        return false;
      };

      // Adding the topbar menu
      addMenu('topbar', {
        roles: ['*'],
        caption: 'Application'
      });
    }

    // Remove existing menu object by menu id
    function removeMenu(menuId) {
      // Validate that the menu exists
      var menu= service.validateMenuExistence(menuId);

      //delete menu;
    }

    // Remove existing menu object by menu id
    function removeMenuItem(menuId, menuItemState) {
      // Validate that the menu exists
      var menu = service.validateMenuExistence(menuId);

      // Search for menu item to remove
      for (var itemIndex in menu.items) {
        if (menu.items.hasOwnProperty(itemIndex) && menu.items[itemIndex].state === menuItemState) {
          menu.items.splice(itemIndex, 1);
        }
      }

      // Return the menu object
      return menu;
    }

    // Remove existing menu object by menu id
    function removeSubMenuItem(menuId, submenuItemState) {
      // Validate that the menu exists
      var menu= service.validateMenuExistence(menuId);

      // Search for menu item to remove
      for (var itemIndex in menu.items) {
        if (menu.items.hasOwnProperty(itemIndex)) {
          for (var subitemIndex in menu.items[itemIndex].items) {
            if (menu.items[itemIndex].items.hasOwnProperty(subitemIndex) && menu.items[itemIndex].items[subitemIndex].state === submenuItemState) {
              menu.items[itemIndex].items.splice(subitemIndex, 1);
            }
          }
        }
      }

      // Return the menu object
      return menu;
    }

    // Validate menu existance
    function validateMenuExistence(menuId) {
      if (menuId && menuId.length) {
        var menu = _.find(service.menus,function(search){
          return search.id == menuId;
        });

        if (menu) {
          return menu;
        } else {
          throw new Error('Menu does not exist');
        }
      } else {
        throw new Error('MenuId was not provided');
      }
    }
  }
}());


text:
import React from 'react';
import Utils from '../utils/utils';
import Mixins from '../utils/mixins';
import __reactComponentDispatchEvent from '../runtime-helpers/react-component-dispatch-event.js';
import __reactComponentSlots from '../runtime-helpers/react-component-slots.js';
import __reactComponentSetProps from '../runtime-helpers/react-component-set-props.js';

class F7MessagebarSheetImage extends React.Component {
  constructor(props, context) {
    super(props, context);

    (() => {
      this.onChangeBound = this.onChange.bind(this);
    })();
  }

  onChange(e) {
    if (this.props.checked) this.dispatchEvent('checked', e);else this.dispatchEvent('unchecked', e);
    this.dispatchEvent('change', e);
  }

  render() {
    const self = this;
    const props = self.props;
    const {
      image,
      checked,
      id,
      className,
      style
    } = props;
    const classes = Utils.classNames(className, 'messagebar-sheet-image', 'checkbox', Mixins.colorClasses(props));
    const styles = Utils.extend({
      backgroundImage: image && `url(${image})`
    }, style || {});
    let inputEl;
    {
      inputEl = React.createElement('input', {
        type: 'checkbox',
        checked: checked,
        onChange: self.onChangeBound
      });
    }
    return React.createElement('label', {
      id: id,
      className: classes,
      style: styles
    }, inputEl, React.createElement('i', {
      className: 'icon icon-checkbox'
    }), this.slots['default']);
  }

  get slots() {
    return __reactComponentSlots(this.props);
  }

  dispatchEvent(events, ...args) {
    return __reactComponentDispatchEvent(this, events, ...args);
  }

}

__reactComponentSetProps(F7MessagebarSheetImage, Object.assign({
  id: [String, Number],
  image: String,
  checked: Boolean
}, Mixins.colorProps));

F7MessagebarSheetImage.displayName = 'f7-messagebar-sheet-image';
export default F7MessagebarSheetImage;


text:
#import "SNRSearchWindow.h"
#import "SNRSearchWindowController.h"
#import <Carbon/Carbon.h>

#define kNoModifierFlagsMask 256
#define kLayoutResultsInset 5.f
#define kBackgroundOpacity 0.95f
#define kBackgroundCornerRadius 4.f

static NSString* const kImageSearchBox = @"search-box";

@implementation SNRSearchWindow
@synthesize drawBackground = _drawBackground;

- (id)initWithContentRect:(NSRect)contentRect
                styleMask:(NSUInteger)windowStyle
                  backing:(NSBackingStoreType)bufferingType
                    defer:(BOOL)deferCreation
{
    if (self = [super
                initWithContentRect:contentRect
                styleMask:NSBorderlessWindowMask
                backing:bufferingType
                defer:deferCreation]) {
        [self setOpaque:NO];
        [self setBackgroundColor:[NSColor clearColor]];
        [self setMovableByWindowBackground:YES];
        [self setMovable:YES];

    }
    return self;
}

- (BOOL)canBecomeKeyWindow
{
    return YES;
}

- (void)sendEvent:(NSEvent *)theEvent
{
    // Detect Command + W to close window
    if ([theEvent type] == NSKeyDown) {
        NSUInteger modifierFlags = [theEvent modifierFlags];
        unsigned short keyCode = [theEvent keyCode];
        BOOL commandW = (modifierFlags & NSCommandKeyMask) == NSCommandKeyMask && keyCode == kVK_ANSI_W;
        BOOL escape = !(modifierFlags & NSDeviceIndependentModifierFlagsMask) && keyCode == kVK_Escape;
        if (commandW || escape) {
            [self.windowController hideWindow:nil];
            return;
        }
    }
    [super sendEvent:theEvent];
}
@end

@implementation SNRSearchWindowContentView

- (void)drawRect:(NSRect)dirtyRect
{
    if ([(SNRSearchWindow*)[self window] drawBackground]) {
        [[NSColor colorWithDeviceWhite:1.f alpha:kBackgroundOpacity] set];
        NSRect resultsRect = NSMakeRect(kLayoutResultsInset, 0.f, self.bounds.size.width - (kLayoutResultsInset * 2.f), self.bounds.size.height - kLayoutResultsInset);
        NSBezierPath *path = [NSBezierPath bezierPathWithRoundedRect:resultsRect xRadius:kBackgroundCornerRadius yRadius:kBackgroundCornerRadius];
        [path fill];
    }
    NSImage *box = [NSImage imageNamed:kImageSearchBox];
    NSSize size = box.size;
    NSRect boxRect = NSMakeRect(0.f, NSMaxY(self.bounds) - size.height, size.width, size.height);
    [box drawInRect:boxRect fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.f];
}
@end