text:
layout: post
title: Creating an Overridable MVC3 Global Filter
tags: [ASP.NET MVC3]
redirect_from:
  - /blog/2011/04/creating-overridable-mvc3-global-action.html
---

The new global filters in MVC3 are a nice way to apply behavior globally. Sometimes though you'll want to opt out an action or controller from that behavior. Lets take authentication as an example; we want everything to be secure by default but we may have individual controllers or actions that will be public. The following authorize attribute enables us to create a global filter and then override the global behavior where we need to:

// Make sure we specify that this attribute should only be specified once.
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class SecureAttribute : AuthorizeAttribute
{
    private readonly bool _enabled;

    // Default constructor with security enabled, used as a global filter
    public SecureAttribute()
    {
        _enabled = true;
    }

    // Attribute constructor
    public SecureAttribute(bool enabled)
    {
        _enabled = enabled;
    }

    protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
    {
        return !_enabled || AuthenticationService.Authenticate();
    }
}

A few things to note. First we need to specify that this attribute should only be applied once with the AttributeUsageAttribute. Under the covers the FilterAttribute class looks for this attribute to determine if multiple instances of the filter can exist. In the default constructor we specify the default behavior; in this case security being enabled. In our authorization method we can check to see if authentication is enabled and proceed accordingly.

Here we can register the global default. This filter will have a scope of "Global" which is a lower priority scope:

public class MvcApplication : HttpApplication
{
    protected void Application_Start()
    {
        GlobalFilters.Filters.Add(new SecureAttribute());
        // ...
    }
}

We can then override the default behavior where appropriate. The action attribute has a scope of "Action" which is a higher priority scope. So this filter will take precedence over the globally added one:

public class SomeController : Controller
{
    [Secure(false)]
    public ActionResult SomePublicAction()
    {
        return View();
    }
}


text:
Template Base Classes
---------------------

.. automodule:: trump.templating.bases

.. autoclass:: trump.templating.bTags

.. autoclass:: trump.templating.bMunging

.. autoclass:: trump.templating.bSource

.. autoclass:: trump.templating.bFeed

.. autoclass:: trump.templating.bValidity

.. autoclass:: trump.templating.bIndex

Template Classes
----------------

Tag Templates
~~~~~~~~~~~~~

.. autoclass:: trump.templating.AssetTT

.. autoclass:: trump.templating.GenericTT

.. autoclass:: trump.templating.SimpleTT

.. autoclass:: trump.templating.SimpleTT

Munging Templates
~~~~~~~~~~~~~~~~~

.. autoclass:: trump.templating.AbsMT

.. autoclass:: trump.templating.AsFreqMT

.. autoclass:: trump.templating.RollingMeanMT

.. autoclass:: trump.templating.FFillRollingMeanMT

.. autoclass:: trump.templating.RollingMeanFFillMT

.. autoclass:: trump.templating.SimpleExampleMT

.. autoclass:: trump.templating.MultiExampleMT

Source Templates
~~~~~~~~~~~~~~~~

.. autoclass:: trump.templating.DBapiST

.. autoclass:: trump.templating.PyDataDataReaderST

.. autoclass:: trump.templating.PyDataCSVST

Feed Templates
~~~~~~~~~~~~~~

.. autoclass:: trump.templating.DBapiFT

.. autoclass:: trump.templating.SQLFT

.. autoclass:: trump.templating.QuandlFT

.. autoclass:: trump.templating.QuandlSecureFT

.. autoclass:: trump.templating.GoogleFinanceFT

.. autoclass:: trump.templating.YahooFinanceFT

.. autoclass:: trump.templating.StLouisFEDFT

.. autoclass:: trump.templating.CSVFT

Index Templates
~~~~~~~~~~~~~~~

.. autoclass:: trump.templating.FFillIT

Validity Templates
~~~~~~~~~~~~~~~~~~

.. autoclass:: trump.templating.FeedsMatchVT

.. autoclass:: trump.templating.DateExistsVT

redpajama_set_name: RedPajamaGithub


text:
#region License

#endregion

using Quartz.Util;

namespace Quartz
{
    /// <summary>
    /// Scheduler constants.
    /// </summary>
    /// <author>Marko Lahma (.NET)</author>
    public struct SchedulerConstants
    {
        /// <summary>
        /// A (possibly) useful constant that can be used for specifying the group
        /// that <see cref="IJob" /> and <see cref="ITrigger" /> instances belong to.
        /// </summary>
        public const string DefaultGroup = Key<string>.DefaultGroup;

        /// <summary>
        /// A constant <see cref="ITrigger" /> group name used internally by the
        /// scheduler - clients should not use the value of this constant
        /// ("RECOVERING_JOBS") for thename of a <see cref="ITrigger" />'s group.
        /// </summary>
        public const string DefaultRecoveryGroup = "RECOVERING_JOBS";

        /// <summary>
        /// A constant <see cref="ITrigger" /> group name used internally by the
        /// scheduler - clients should not use the value of this constant
        /// ("FAILED_OVER_JOBS") for thename of a <see cref="ITrigger" />'s group.
        /// </summary>
        public const string DefaultFailOverGroup = "FAILED_OVER_JOBS";

        /// <summary>
        ///  A constant <see cref="JobDataMap" /> key that can be used to retrieve the
        /// name of the original <see cref="ITrigger" /> from a recovery trigger's
        /// data map in the case of a job recovering after a failed scheduler
        /// instance.
        /// </summary>
        /// <seealso cref="IJobDetail.RequestsRecovery" />
        public const string FailedJobOriginalTriggerName = "QRTZ_FAILED_JOB_ORIG_TRIGGER_NAME";

        /// <summary>
        /// A constant <see cref="JobDataMap" /> key that can be used to retrieve the
        /// group of the original <see cref="ITrigger" /> from a recovery trigger's
        /// data map in the case of a job recovering after a failed scheduler
        /// instance.
        /// </summary>
        /// <seealso cref="IJobDetail.RequestsRecovery" />
        public const string FailedJobOriginalTriggerGroup = "QRTZ_FAILED_JOB_ORIG_TRIGGER_GROUP";

        /// <summary>
        /// A constant <see cref="JobDataMap" /> key that can be used to retrieve the
        /// fire time of the original <see cref="ITrigger" /> from a recovery
        /// trigger's data map in the case of a job recovering after a failed scheduler
        /// instance.
        /// </summary>
        /// <remarks>
        /// Note that this is the time the original firing actually occurred,
        /// which may be different from the scheduled fire time - as a trigger doesn't
        /// always fire exactly on time.
        /// </remarks>
        /// <seealso cref="IJobDetail.RequestsRecovery" />
        public const string FailedJobOriginalTriggerFiretimeInMillisecoonds = "QRTZ_FAILED_JOB_ORIG_TRIGGER_FIRETIME_IN_MILLISECONDS_AS_STRING";

    }
}


text:
/*
**  Include Files
*/
#include "common_types.h"
#include "osapi.h"

/*
** Types and prototypes for this module
*/
#include "utf_types.h"
#include "utf_cfe_psp.h"

#include <string.h>
#include <stdio.h>
#include <stdarg.h>

/*******************************************************************************
                                  Memory Access API
*******************************************************************************/
int32 CFE_PSP_MemRead8(uint32 Address, uint8 *Data)
{
    boolean Status;

    Status = UTF_read_sim_address(Address, 1, Data);

    if(Status == FALSE)
        return(CFE_PSP_ERROR);

    return(CFE_PSP_SUCCESS);
}

int32 CFE_PSP_MemWrite8(uint32 Address, uint8 Data)
{
    boolean Status;

    Status = UTF_write_sim_address(Address, 1, &Data);

    if(Status == FALSE)
        return(CFE_PSP_ERROR);

    return(CFE_PSP_SUCCESS);
}

int32 CFE_PSP_MemRead16(uint32 Address, uint16 *Data)
{
    int32 Status;

    /* Check that the address is on a 16 bit boundary; the flight code
       will return the CFE_PSP_ERROR_ADDRESS_MISALIGNED return code. */
    if ((Address % 2) != 0)
    {   /* Address is not on 16 bit boundary */
        UTF_put_text("Address Not On 16 Bit Boundary: 0x%08x\n", Address);
        return (CFE_PSP_ERROR);
    }
    else
    {   /* Address is on 16 bit boundary */
        Status = UTF_read_sim_address(Address, 2, Data);

        if(Status == FALSE)
            return(CFE_PSP_ERROR);
        else
            return(CFE_PSP_SUCCESS);
    }
}

int32 CFE_PSP_MemWrite16(uint32 Address, uint16 Data)
{
    int32 Status;

    /* Check that the address is on a 16 bit boundary; the flight code
       will return the CFE_PSP_ERROR_ADDRESS_MISALIGNED return code. */
    if ((Address % 2) != 0)
    {   /* Address is not on 16 bit boundary */
        UTF_put_text("Address Not On 16 Bit Boundary: 0x%08x\n", Address);
        return (CFE_PSP_ERROR);
    }
    else
    {   /* Address is on 16 bit boundary */
        Status = UTF_write_sim_address(Address, 2, &Data);
        if(Status == FALSE)
            return(CFE_PSP_ERROR);
        else
            return(CFE_PSP_SUCCESS);
    }
}

int32 CFE_PSP_MemRead32(uint32 Address, uint32 *Data)
{
    int32 Status;
    /* Check that the address is on a 32 bit boundary; the flight code
      will return the CFE_PSP_ERROR_ADDRESS_MISALIGNED return code. */
    if ((Address % 4) != 0)
    {   /* Address is not on 32 bit boundary */
        UTF_put_text("Address Not On 32 Bit Boundary: 0x%08x\n", Address);
        return (CFE_PSP_ERROR);
    }
    else
    {   /* Address is on 32 bit boundary */
        Status = UTF_read_sim_address(Address, 4, Data);

        if(Status == FALSE)
            return(CFE_PSP_ERROR);
        else
            return(CFE_PSP_SUCCESS);
    }
}

int32 CFE_PSP_MemWrite32(uint32 Address, uint32 Data)
{
    int32 Status;

    /* Check that the address is on a 32 bit boundary; the flight code
      will return the CFE_PSP_ERROR_ADDRESS_MISALIGNED return code. */
    if ((Address % 4) != 0)
    {   /* Address is not on 32 bit boundary */
        UTF_put_text("Address Not On 32 Bit Boundary: 0x%08x\n", Address);
        return (CFE_PSP_ERROR);
    }
    else
    {   /* Address is on 32 bit boundary */
        Status = UTF_write_sim_address(Address, 4, &Data);
        if(Status == FALSE)
            return(CFE_PSP_ERROR);
        else
            return(CFE_PSP_SUCCESS);
    }
}


text:
<?php
/**
 * DO NOT EDIT THIS FILE!
 *
 * This file was automatically generated from external sources.
 *
 * Any manual change here will be lost the next time the SDK
 * is updated. You've been warned!
 */

namespace DTS\eBaySDK\Trading\Types;

/**
 *
 * @property integer $FeedbackScore
 * @property \DateTime $RegistrationDate
 * @property boolean $SubscribeSA
 * @property boolean $SubscribeSAPro
 * @property boolean $SubscribeSM
 * @property boolean $SubscribeSMPro
 */
class ValidateTestUserRegistrationRequestType extends \DTS\eBaySDK\Trading\Types\AbstractRequestType
{
    /**
     * @var array Properties belonging to objects of this class.
     */
    private static $propertyTypes = [
        'FeedbackScore' => [
            'type' => 'integer',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'FeedbackScore'
        ],
        'RegistrationDate' => [
            'type' => 'DateTime',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'RegistrationDate'
        ],
        'SubscribeSA' => [
            'type' => 'boolean',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'SubscribeSA'
        ],
        'SubscribeSAPro' => [
            'type' => 'boolean',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'SubscribeSAPro'
        ],
        'SubscribeSM' => [
            'type' => 'boolean',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'SubscribeSM'
        ],
        'SubscribeSMPro' => [
            'type' => 'boolean',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'SubscribeSMPro'
        ]
    ];

    /**
     * @param array $values Optional properties and values to assign to the object.
     */
    public function __construct(array $values = [])
    {
        list($parentValues, $childValues) = self::getParentValues(self::$propertyTypes, $values);

        parent::__construct($parentValues);

        if (!array_key_exists(__CLASS__, self::$properties)) {
            self::$properties[__CLASS__] = array_merge(self::$properties[get_parent_class()], self::$propertyTypes);
        }

        if (!array_key_exists(__CLASS__, self::$xmlNamespaces)) {
            self::$xmlNamespaces[__CLASS__] = 'xmlns="urn:ebay:apis:eBLBaseComponents"';
        }

        if (!array_key_exists(__CLASS__, self::$requestXmlRootElementNames)) {
            self::$requestXmlRootElementNames[__CLASS__] = 'ValidateTestUserRegistrationRequest';
        }

        $this->setValues(__CLASS__, $childValues);
    }
}


text:
module HoldersHelper
end


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

package com.google.devtools.build.lib.buildeventservice.client;

import static com.google.common.base.Preconditions.checkState;
import static java.util.concurrent.TimeUnit.MILLISECONDS;

import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import com.google.devtools.build.v1.PublishBuildEventGrpc;
import com.google.devtools.build.v1.PublishBuildEventGrpc.PublishBuildEventBlockingStub;
import com.google.devtools.build.v1.PublishBuildEventGrpc.PublishBuildEventStub;
import com.google.devtools.build.v1.PublishBuildToolEventStreamRequest;
import com.google.devtools.build.v1.PublishBuildToolEventStreamResponse;
import com.google.devtools.build.v1.PublishLifecycleEventRequest;
import io.grpc.CallCredentials;
import io.grpc.Channel;
import io.grpc.Status;
import io.grpc.StatusException;
import io.grpc.StatusRuntimeException;
import io.grpc.stub.AbstractStub;
import io.grpc.stub.StreamObserver;
import java.time.Duration;
import java.util.function.Function;
import javax.annotation.Nullable;

/** Implementation of BuildEventServiceClient that uploads data using gRPC. */
public abstract class BuildEventServiceGrpcClient implements BuildEventServiceClient {
  /** Max wait time for a single non-streaming RPC to finish */
  private static final Duration RPC_TIMEOUT = Duration.ofSeconds(15);

  private final PublishBuildEventStub besAsync;
  private final PublishBuildEventBlockingStub besBlocking;
  private volatile StreamObserver<PublishBuildToolEventStreamRequest> stream;

  public BuildEventServiceGrpcClient(Channel channel, @Nullable CallCredentials callCredentials) {
    this.besAsync = withCallCredentials(PublishBuildEventGrpc.newStub(channel), callCredentials);
    this.besBlocking =
        withCallCredentials(PublishBuildEventGrpc.newBlockingStub(channel), callCredentials);
  }

  private static <T extends AbstractStub<T>> T withCallCredentials(
      T stub, @Nullable CallCredentials callCredentials) {
    stub = callCredentials != null ? stub.withCallCredentials(callCredentials) : stub;
    return stub;
  }

  @Override
  public void publish(PublishLifecycleEventRequest lifecycleEvent)
      throws StatusException, InterruptedException {
    try {
      besBlocking
          .withDeadlineAfter(RPC_TIMEOUT.toMillis(), MILLISECONDS)
          .publishLifecycleEvent(lifecycleEvent);
    } catch (StatusRuntimeException e) {
      Throwables.throwIfInstanceOf(Throwables.getRootCause(e), InterruptedException.class);
      throw e.getStatus().asException();
    }
  }

  @Override
  public ListenableFuture<Status> openStream(
      Function<PublishBuildToolEventStreamResponse, Void> ackCallback)
      throws StatusException, InterruptedException {
    Preconditions.checkState(
        stream == null, "Starting a new stream without closing the previous one");
    SettableFuture<Status> streamFinished = SettableFuture.create();
    stream = createStream(ackCallback, streamFinished);
    return streamFinished;
  }

  private StreamObserver<PublishBuildToolEventStreamRequest> createStream(
      final Function<PublishBuildToolEventStreamResponse, Void> ackCallback,
      final SettableFuture<Status> streamFinished)
      throws StatusException, InterruptedException {
    try {
      return besAsync.publishBuildToolEventStream(
          new StreamObserver<PublishBuildToolEventStreamResponse>() {
            @Override
            public void onNext(PublishBuildToolEventStreamResponse response) {
              ackCallback.apply(response);
            }

            @Override
            public void onError(Throwable t) {
              stream = null;
              streamFinished.set(Status.fromThrowable(t));
            }

            @Override
            public void onCompleted() {
              stream = null;
              streamFinished.set(Status.OK);
            }
          });
    } catch (StatusRuntimeException e) {
      Throwables.throwIfInstanceOf(Throwables.getRootCause(e), InterruptedException.class);
      throw e.getStatus().asException();
    }
  }

  @Override
  public void sendOverStream(PublishBuildToolEventStreamRequest buildEvent)
      throws StatusException, InterruptedException {
    StreamObserver<PublishBuildToolEventStreamRequest> stream0 = stream;
    checkState(stream0 != null, "Attempting to send over a closed stream");
    try {
      stream0.onNext(buildEvent);
    } catch (StatusRuntimeException e) {
      Throwables.throwIfInstanceOf(Throwables.getRootCause(e), InterruptedException.class);
      throw e.getStatus().asException();
    }
  }

  @Override
  public void closeStream() {
    StreamObserver<PublishBuildToolEventStreamRequest> stream0 = stream;
    if (stream0 != null) {
      stream0.onCompleted();
    }
  }

  @Override
  public void abortStream(Status status) {
    StreamObserver<PublishBuildToolEventStreamRequest> stream0 = stream;
    if (stream0 != null) {
      stream0.onError(status.asException());
    }
  }

  @Override
  public boolean isStreamActive() {
    return stream != null;
  }

  @Override
  public String userReadableError(Throwable t) {
    if (t instanceof StatusException) {
      Throwable rootCause = Throwables.getRootCause(t);
      String message = ((StatusException) t).getStatus().getCode().name();
      message += ": " + rootCause.getMessage();
      return message;
    } else {
      return t.getMessage();
    }
  }

  @Override
  public abstract void shutdown() throws InterruptedException;
}


text:
old_string = 'Ruby is cool'
old_string.reverse!
puts old_string

describe "old_string" do
  it 'is defined as a local variable' do
    expect(defined?(old_string)).to eq 'local-variable'
  end

  it "has the value 'Ruby is cool'" do
    expect(old_string).to eq "Ruby is cool"
  end
end

describe 'new_string' do
  it 'is defined as a local variable' do
    expect(defined?(new_string)).to eq 'local-variable'
  end

  it 'has the value "LOOC SI YBUR"' do
    expect(new_string).to eq "LOOC SI YBUR"
  end
end


text:
//
//  CMDocument.h
//  CocoaMarkdown
//
//  Created by Indragie on 1/12/15.
//  Copyright (c) 2015 Indragie Karunaratne. All rights reserved.
//

#import <Foundation/Foundation.h>

@class CMNode;

typedef NS_OPTIONS(NSInteger, CMDocumentOptions) {
    /**
     * Include a `data-sourcepos` attribute on all block elements.
     */
    CMDocumentOptionsSourcepos = (1 << 0),
    /**
     * Render `softbreak` elements as hard line breaks.
     */
    CMDocumentOptionsHardBreaks = (1 << 1),
    /**
     * Normalize tree by consolidating adjacent text nodes.
     */
    CMDocumentOptionsNormalize = (1 << 3),
    /**
     * Convert straight quotes to curly, --- to em dashes, -- to en dashes.
     */
    CMDocumentOptionsSmart = (1 << 4)
};

/**
 *  A Markdown document conforming to the CommonMark spec.
 */
@interface CMDocument : NSObject

/**
 *  Root node of the document.
 */
@property (nonatomic, readonly) CMNode *rootNode;

/**
 *  Initializes the receiver with data.
 *
 *  @param data Markdown document data.
 *  @param options Document options.
 *
 *  @return An initialized instance of the receiver.
 */
- (instancetype)initWithData:(NSData *)data options:(CMDocumentOptions)options;

/**
 *  Initializes the receiver with data read from a file.
 *
 *  @param path The file path to read from.
 *  @param options Document options.
 *
 *  @return An initialized instance of the receiver, or `nil` if the file
 *  could not be opened.
 */
- (instancetype)initWithContentsOfFile:(NSString *)path options:(CMDocumentOptions)options;

@end


text:
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.weblayer_private.payments;

import androidx.annotation.Nullable;

import org.chromium.components.payments.BrowserPaymentRequest;
import org.chromium.components.payments.JourneyLogger;
import org.chromium.components.payments.PaymentApp;
import org.chromium.components.payments.PaymentAppFactoryDelegate;
import org.chromium.components.payments.PaymentAppService;
import org.chromium.components.payments.PaymentAppType;
import org.chromium.components.payments.PaymentRequestService;
import org.chromium.components.payments.PaymentRequestService.Delegate;
import org.chromium.components.payments.PaymentRequestSpec;
import org.chromium.components.payments.PaymentResponseHelper;
import org.chromium.components.payments.PaymentResponseHelperInterface;
import org.chromium.payments.mojom.PaymentDetails;
import org.chromium.payments.mojom.PaymentErrorReason;
import org.chromium.payments.mojom.PaymentItem;
import org.chromium.payments.mojom.PaymentValidationErrors;

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

/** The WebLayer-specific part of the payment request service. */
public class WebLayerPaymentRequestService implements BrowserPaymentRequest {
    private final List<PaymentApp> mAvailableApps = new ArrayList<>();
    private final JourneyLogger mJourneyLogger;
    private PaymentRequestService mPaymentRequestService;
    private PaymentRequestSpec mSpec;
    private boolean mHasClosed;
    private boolean mShouldSkipAppSelector;
    private PaymentApp mSelectedApp;

    /**
     * Create an instance of {@link WebLayerPaymentRequestService}.
     * @param paymentRequestService The payment request service.
     * @param delegate The delegate of the payment request service.
     */
    public WebLayerPaymentRequestService(
            PaymentRequestService paymentRequestService, Delegate delegate) {
        mPaymentRequestService = paymentRequestService;
        mJourneyLogger = mPaymentRequestService.getJourneyLogger();
    }

    // Implements BrowserPaymentRequest:
    @Override
    public void onPaymentDetailsUpdated(
            PaymentDetails details, boolean hasNotifiedInvokedPaymentApp) {}

    // Implements BrowserPaymentRequest:
    @Override
    public void onPaymentDetailsNotUpdated(String selectedShippingOptionError) {}

    @Override
    public boolean onPaymentAppCreated(PaymentApp paymentApp) {
        // Ignores the service worker payment apps in WebLayer until -
        // TODO(crbug.com/1224420): WebLayer supports Service worker payment apps.
        return paymentApp.getPaymentAppType() != PaymentAppType.SERVICE_WORKER_APP;
    }

    // Implements BrowserPaymentRequest:
    @Override
    public void complete(int result, Runnable onCompleteHandled) {
        onCompleteHandled.run();
    }

    // Implements BrowserPaymentRequest:
    @Override
    public void onRetry(PaymentValidationErrors errors) {}

    // Implements BrowserPaymentRequest:
    @Override
    public void close() {
        if (mHasClosed) return;
        mHasClosed = true;

        if (mPaymentRequestService != null) {
            mPaymentRequestService.close();
            mPaymentRequestService = null;
        }
    }

    // Implements BrowserPaymentRequest:
    @Override
    public boolean hasAvailableApps() {
        return !mAvailableApps.isEmpty();
    }

    // Implements BrowserPaymentRequest:
    @Override
    public void notifyPaymentUiOfPendingApps(List<PaymentApp> pendingApps) {
        assert mAvailableApps.isEmpty()
            : "notifyPaymentUiOfPendingApps() should be called at most once.";
        mAvailableApps.addAll(pendingApps);
        mSelectedApp = mAvailableApps.size() == 0 ? null : mAvailableApps.get(0);
    }

    // Implements BrowserPaymentRequest:
    @Override
    public void onSpecValidated(PaymentRequestSpec spec) {
        mSpec = spec;
    }

    // Implements BrowserPaymentRequest:
    @Override
    public void addPaymentAppFactories(
            PaymentAppService service, PaymentAppFactoryDelegate delegate) {
        // There's no WebLayer specific factories.
    }

    // Implements BrowserPaymentRequest:
    @Override
    @Nullable
    public String showOrSkipAppSelector(boolean isShowWaitingForUpdatedDetails, PaymentItem total,
            boolean shouldSkipAppSelector) {
        mShouldSkipAppSelector = shouldSkipAppSelector;
        if (!mShouldSkipAppSelector) {
            return "This request is not supported in Web Layer. Please try in Chrome, or make sure "
                    + "that: (1) show() is triggered by user gesture, or"
                    + "(2) do not request any contact information.";
        }
        return null;
    }

    // Implements BrowserPaymentRequest:
    @Override
    @Nullable
    public String onShowCalledAndAppsQueriedAndDetailsFinalized(boolean isUserGestureShow) {
        assert !mAvailableApps.isEmpty()
            : "triggerPaymentAppUiSkipIfApplicable() should be called only when there is any "
                + "available app.";
        PaymentApp selectedPaymentApp = mAvailableApps.get(0);
        if (mShouldSkipAppSelector) {
            mJourneyLogger.setSkippedShow();
            PaymentResponseHelperInterface paymentResponseHelper =
                    new PaymentResponseHelper(selectedPaymentApp, mSpec.getPaymentOptions());
            mPaymentRequestService.invokePaymentApp(selectedPaymentApp, paymentResponseHelper);
        }
        return null;
    }

    // Implements BrowserPaymentRequest:
    @Override
    public PaymentApp getSelectedPaymentApp() {
        return mAvailableApps.get(0);
    }

    // Implements BrowserPaymentRequest:
    @Override
    public List<PaymentApp> getPaymentApps() {
        return mAvailableApps;
    }

    // Implements BrowserPaymentRequest:
    @Override
    public boolean hasAnyCompleteApp() {
        return !mAvailableApps.isEmpty() && mAvailableApps.get(0).isComplete();
    }

    private void disconnectFromClientWithDebugMessage(String debugMessage) {
        if (mPaymentRequestService != null) {
            mPaymentRequestService.disconnectFromClientWithDebugMessage(
                    debugMessage, PaymentErrorReason.USER_CANCEL);
        }
        close();
    }
}


text:
title: Release notes for v4013
---

# Release notes for v4013

## Extended information about a floating license

The activation method from the [floating license tutorial](https://help.cryptolens.io/examples/key-verification) can be changed slightly to allow more details about the
license to be retrieved.

You only need add `Metadata = true`, which will allow you to call `Helpers.GetFloatingLicenseInformation`. This method has multiple overloads, we show the one that requires the
activation model and the activation result. If you don't have these objects, you can specify `MaxOverdraft`, `MaxNoOfMachines` and `UsedFloatingMachines` yourself.

Below is an example that show this method in action.

```cs
var activateModel = new ActivateModel()
{
    Key = "GEBNC-WZZJD-VJIHG-GCMVD",
    ProductId = 3349,
    Sign = true,
    MachineCode = Helpers.GetMachineCode(),
    Metadata = true, // <- add this
    FloatingTimeInterval = 100,
    MaxOverdraft = 1
};
var activateResult = Key.Activate(token: activateToken, parameters: activateModel);

if (activateResult != null && activateResult.Result == ResultType.Success)
{
    var info = Helpers.GetFloatingLicenseInformation(activateModel, activateResult);

    System.Diagnostics.Debug.WriteLine(info.AvailableDevices);
    System.Diagnostics.Debug.WriteLine(info.UsedDevices);
    System.Diagnostics.Debug.WriteLine(info.OverdraftDevices);
}
else
{
    Assert.Fail();
}
```

## Release a floating license

Normally, floating licenses will automatically be released in a certain period of time (specified by `FloatingTimeInterval`). However, you can manually release a floating license by
using `Key.Deactivate` with `Floating=True`, as shown below:

```cs
Key.Deactivate(activateToken, new DeactivateModel {
    Key = "GEBNC-WZZJD-VJIHG-GCMVD",
    ProductId = 3349,
    MachineCode = "test",
    Floating = true // <- add this
});

```


text:
CREATE TABLE api_resource
(
  name VARCHAR(255) PRIMARY KEY NOT NULL,
  url VARCHAR(255)
);
CREATE UNIQUE INDEX uk_8b997c6u8hjbpvjm8a3jea05n ON api_resource (url);


text:
package org.ode4j.ode;

import org.ode4j.math.DVector3;

/**
 * Describe the contact point between two geoms.
 *
 * If two bodies touch, or if a body touches a static feature in its
 * environment, the contact is represented by one or more "contact
 * points", described by dContactGeom.
 *
 * The convention is that if body 1 is moved along the normal vector by
 * a distance depth (or equivalently if body 2 is moved the same distance
 * in the opposite direction) then the contact depth will be reduced to
 * zero. This means that the normal vector points "in" to body 1.
 */
public class DContactGeom {

	DContactGeom() {
		// Non-public
	}

	/** contact position */
	public final DVector3 pos = new DVector3();
    /** normal vector */
	public final DVector3 normal = new DVector3();
    /** penetration depth */
	public double depth;
	/** the colliding geoms */
	public DGeom g1;
	public DGeom g2;
	/** (to be documented) */
	public int side1;
	public int side2;
}


text:
from __future__ import unicode_literals, print_function
import ssl
import socket
from contextlib import closing

from six.moves.urllib_parse import urlparse

from sideboard.lib import services, entry_point

def _check(url, **ssl_params):
    status = ['checking {}'.format(url)]

    try:
        parsed = urlparse(url)
    except Exception as e:
        return status + ['failed to parse url: {!s}'.format(e)]
    else:
        host = parsed.hostname
        port = parsed.port or (443 if parsed.scheme in ['https', 'wss'] else 80)
        status.append('using hostname {} and port {}'.format(host, port))

    try:
        ip = socket.gethostbyname(host)
    except Exception as e:
        return status + ['failed to resolve host with DNS: {!s}'.format(e)]
    else:
        status.append('successfully resolved host {} to {}'.format(host, ip))

    sock = None
    try:
        sock = socket.create_connection((host, port))
    except Exception as e:
        return status + ['failed to establish a socket connection to {} on port {}: {!s}'.format(host, port, e)]
    else:
        status.append('successfully opened socket connection to {}:{}'.format(host, port))

    if any(ssl_params.values()):
        try:
            wrapped = ssl.wrap_socket(sock, **ssl_params)
        except Exception as e:
            return status + ['failed to complete SSL handshake ({}): {!s}'.format(ssl_params, e)]
        else:
            status.append('succeeded at SSL handshake (without validating server cert)')
        finally:
            if sock:
                sock.close()

        try:
            with closing(socket.create_connection((host, port))) as sock:
                wrapped = ssl.wrap_socket(sock, **dict(ssl_params, cert_reqs=ssl.CERT_REQUIRED))
                status.append('succeeded at validating server cert')
        except Exception as e:
            return status + ['failed to validate server cert ({}): {!s}'.format(ssl_params, e)]

    status.append('everything seems to work')
    return status

def check_all():
    checks = {}
    for name, jservice in services._jsonrpc.items():
        jproxy = jservice._send.im_self  # ugly kludge to get the ServerProxy object
        url = '{}://{}/'.format(jproxy.type, jproxy.host)
        checks[name] = _check(url, **jproxy.ssl_opts)
    return checks

@entry_point
def check_connections():
    for service, results in sorted(check_all().items()):
        print(service)
        print('-' * len(service))
        print('\n'.join(results) + '\n')


text:
class AdminEmailController < ApplicationController
  before_action :restrict_to_admin

  def new
    @message = Message.new
  end

  def create
    @message = Message.new(message_params)
    if @message.valid?
      # let's parse here.
      email_list = @message.email_list
      logger.info "Found email list => " + email_list
      emails = []
      email_list.split.each do |email|
        logger.info "adding email " + email
        emails.push email
      end

      ContactMailer.admin_email(@message, emails).deliver_now
      redirect_to welcome_index_path, notice: "Your messages has been sent."
    else
      flash[:alert] = "An error occurred while delivering this message."
      render :new
    end
  end

  private
# Use callbacks to share common setup or constraints between actions.

  def message_params
    params.require(:message).permit(:email_list, :subject, :name, :content, :email)
  end

end


text:
class JsonException {
    const QString msg;
public:
    JsonException(const QString& msg) : msg(msg) { }
    QString what() const { return msg; }
};


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

import com.nortal.blaze.fhir.structure.api.ParseException;
import com.nortal.blaze.fhir.structure.api.ResourceContent;
import com.nortal.blaze.fhir.structure.api.ResourceRepresentation;
import com.nortal.blaze.fhir.structure.defs.JsonRepresentation;
import com.nortal.blaze.fhir.structure.defs.XmlRepresentation;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.ehcache.Cache;
import org.ehcache.CacheManager;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.config.builders.ExpiryPolicyBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
// import org.apache.felix.scr.annotations.Reference;
// import org.apache.felix.scr.annotations.ReferenceCardinality;
// import org.apache.felix.scr.annotations.ReferencePolicy;
import org.hl7.fhir.dstu3.model.Resource;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;

import java.time.Duration;
import java.util.Optional;
import java.util.stream.Stream;

@Component(immediate = true, service = ResourceFormatService.class)
public class ResourceFormatService {
  @Reference
  private JsonRepresentation jsonRepresentation;
  @Reference
  private XmlRepresentation xmlRepresentation;
  private Cache<String, ? extends Resource> cache;

  @Activate
  private void init() {
    CacheManager manager = CacheManagerBuilder.newCacheManagerBuilder().build();
    manager.init();
    CacheConfigurationBuilder<String, Resource> builder = CacheConfigurationBuilder
        .newCacheConfigurationBuilder(String.class, Resource.class, ResourcePoolsBuilder.heap(2048));
    builder.withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(32)));
    cache = manager.createCache("resources", builder.build());
  }

  public ResourceContent compose(Resource resource, String mime) {
    if (resource == null) {
      return null;
    }
    ResourceRepresentation presenter =
        findPresenter(mime).orElse(findPresenter("json").orElseThrow(() -> new ParseException("unknown format")));
    return new ResourceContent(presenter.compose(resource), presenter.getFhirFormat().getExtension());
  }

  public <R extends Resource> R parse(ResourceContent content) {
    return parse(content.getValue());
  }

  @SuppressWarnings("unchecked")
  public <R extends Resource> R parse(String input) {
    String key = DigestUtils.md5Hex(input);
    if (cache.get(key) == null) {
      cache.put(key,
                guessPresenter(input)
                    .orElseThrow(() -> new ParseException("unknown format: [" + StringUtils.left(input, 10) + "]"))
                    .parse(input));
    }
    return (R) cache.get(key).copy();
  }

  public Optional<ResourceRepresentation> findPresenter(String ct) {
    if (ct == null) {
      return Optional.empty();
    }
    String mime = StringUtils.substringBefore(ct, ";");
    return Stream.of(jsonRepresentation, xmlRepresentation).filter(c -> c.getMimeTypes().contains(mime)).findFirst();
    // return presenters.stream().filter(c -> c.getMimeTypes().contains(mime)).findFirst();
  }

  private Optional<ResourceRepresentation> guessPresenter(String content) {
    return Stream.of(jsonRepresentation, xmlRepresentation).filter(c -> c.isParsable(content)).findFirst();
    // return presenters.stream().filter(c -> c.isParsable(content)).findFirst();
  }

}


text:
using System;
using Microsoft.WindowsAzure.Storage.Table;

namespace Common.TableModels
{
    public class Pr : TableEntity
    {
        public Pr()
        {
        }

        public Pr(string owner)
        {
            // reverse chronological order
            RowKey = (new DateTime(3000, 1, 1).Ticks - DateTime.UtcNow.Ticks).ToString();
            PartitionKey = owner;
            Owner = owner;
        }

        public string RepoName { get; set; }

        public string Owner { get; set; }

        public long Id { get; set; }

        public int Number { get; set; }

        public int NumImages { get; set; }

        public double SizeBefore { get; set; }

        public double SizeAfter { get; set; }

        public double PercentReduced { get; set; }

        public double SpaceReduced => SizeBefore - SizeAfter;
    }
}


text:
package org.ms2ms.data.ms;

import org.expasy.mzjava.core.ms.AbsoluteTolerance;
import org.ms2ms.Disposable;
import org.ms2ms.algo.Peaks;
import org.ms2ms.algo.Peptides;
import org.ms2ms.math.Stats;
import org.ms2ms.nosql.ms.HBasePeakList;
import org.ms2ms.utils.Tools;

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

/**
 // http://www.matrixscience.com/help/search_field_help.html
 // http://www.matrixscience.com/blog/ion-series-for-ethcd.html

 * Created by yuw on 8/20/16.
 */
public class ModSetting implements Disposable
{
  public enum eFrag { hcd, cid, ethcd }

  public double[]          masses;
  public char[]            charges, sumZ, sumH2O, sumNH3;
  public List<ModLocation> mods;

  public static final MsSettings LTQ  = new MsSettings(HBasePeakList.SPEC_TRAP_CID, new AbsoluteTolerance(0.5d), new AbsoluteTolerance(0.5d),  Peaks.CID);

  public static final NLoss L43 = new NLoss("Neutral loss due to citrullination",-43.005814d, 0.7d);

  @Deprecated
  public ModSetting(double[] m, List<ModLocation> mod)           { masses=m; mods=mod; }
  public ModSetting(int size, int loc, double increment)         { init(size,loc,increment); }
  public ModSetting(double[] m, char[] z, List<ModLocation> mod) { masses=m; charges=z; mods=mod; }

  // produce the mass ladder considering the AA residue, existing mods and incremental mass at loc
  public ModSetting(char[] peptide, Map<Integer, Double> Mods, int loc, double increment, ResidueBase base)
  {
    // other ion series? 20180317.
    if (peptide!=null && peptide.length>0)
    {
      Float incre_z = 0f;
      init(peptide.length, loc, increment);

      if (increment!=0 && base.getModCharge()!=null)
      {
        Map<Double, Float> slice = base.getModCharge().subMap(increment-0.01, increment+0.01);
        if (Tools.isSet(slice)) incre_z = Stats.sumFloats(slice.values())*10f;
      }
      char h2o=0, nh3=0, z=0;
      for (int i=0; i<peptide.length; i++)
      {
        Double dM = (Mods!=null&&Mods.containsKey(i)?Mods.get(i):0d);
        h2o += "STED".indexOf(peptide[i]>=0?1:0); nh3 += "RKNQ".indexOf(peptide[i]>=0?1:0);
        z += "RK".indexOf(peptide[i]>=0?10:0); z += "H".indexOf(peptide[i]>=0?5:0);
        masses[ i] = base.getAAs()[peptide[i]] + (i==loc?increment:0d) + dM;
        sumH2O[ i] = h2o; sumNH3[i] = nh3; sumZ[i]=z;
        charges[i] = (char )Math.round(("KR".indexOf(peptide[i])>=0?10:("H".indexOf(peptide[i])>=0?5:0)) +
            (i==loc?incre_z:0) + (base.getModCharge().containsKey(dM)?base.getModCharge().get(dM)*10f:0f));
      }
    }
//    Float incre_z = 0f;
//    ModSetting mm = new ModSetting(key.length, loc, increment);
//
//    if (increment!=0 && getBase().getModCharge()!=null)
//    {
//      Map<Double, Float> slice = getBase().getModCharge().subMap(increment-0.01, increment+0.01);
//      if (Tools.isSet(slice)) incre_z = Stats.sumFloats(slice.values())*10f;
//    }
//    for (int i=0; i<key.length; i++)
//    {
//      Double dM = (mods!=null&&mods.containsKey(i)?mods.get(i):0d);
//      mm.masses[ i] = AAs[key[i]] + (i==loc?increment:0d) + dM;
//      mm.charges[i] = (char )Math.round(("KR".indexOf(key[i])>=0?10:("H".indexOf(key[i])>=0?5:0)) +
//          (i==loc?incre_z:0) + (getBase().getModCharge().containsKey(dM)?getBase().getModCharge().get(dM)*10f:0f));
//    }
  }
  // calc the y and other c-term series from a prev stop
  public double[] calcYs(int i, boolean multiZ, double prev)
  {
    int  x=masses.length-1, k=x-i;
    prev +=masses[k];
    // add other series if necessary
    double[] mm = new double[] {
        prev,                                      // simple y-series
        sumH2O[x]-sumH2O[k]>0?prev-Peptides.H2O:0, // loss of 18 (H2O) if STED in the fragment
        sumNH3[x]-sumNH3[k]>0?prev-Peptides.NH3:0  // loss of 17 (NH3) if RKNQ in the fragment
    };
    return multiZ&&sumZ[x]>sumZ[k]?Peaks.MH2Mzs(1,Math.round(0.1f*(sumZ[x]-sumZ[k]))):mm;
  }
  public double[] calcBs(int i, boolean multiZ, double prev)
  {
    prev +=masses[i];
    // add other series if necessary
    double[] mm = new double[] {
        prev,                                      // simple b-series
        prev-Peptides.CO,                          // a-series
        sumH2O[i]>0?prev-Peptides.H2O:0,           // loss of 18 (H2O) if STED in the fragment
        sumNH3[i]>0?prev-Peptides.NH3:0            // loss of 17 (NH3) if RKNQ in the fragment
    };
    return multiZ&&sumZ[i]>0?Peaks.MH2Mzs(1,Math.round(0.1f*(sumZ[i]))):mm;
  }
//  public double[] calcInternals(int i, boolean multiZ)
//  {
//    prev +=masses[i];
//    // add other series if necessary
//    double[] mm = new double[] {
//        prev,                                      // simple b-series
//        prev-Peptides.CO,                          // a-series
//        sumH2O[i]>0?prev-Peptides.H2O:0,           // loss of 18 (H2O) if STED in the fragment
//        sumNH3[i]>0?prev-Peptides.NH3:0            // loss of 17 (NH3) if RKNQ in the fragment
//    };
//    return multiZ&&sumZ[i]>0?Peaks.MH2Mzs(1,Math.round(0.1f*(sumZ[i]))):mm;
//  }
  private void init(int size, int loc, double increment)
  {
    masses = new double[size];
    charges= new char[  size];
    sumZ   = new char[  size];
    sumH2O = new char[  size];
    sumNH3 = new char[  size];

    mods = new ArrayList<>(); mods.add(new ModLocation(loc, increment));
  }

  @Override
  public void dispose()
  {
    masses = null;
    charges= null;
    sumZ   = null;
    sumH2O = null;
    sumNH3 = null;

    mods = (List )Tools.dispose(mods);
  }
}


text:
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd" name="ehcache-2">
	<diskStore path="/tmp" />
	<!--
		In the tests we change the discoveryPort for each service. In reality this will be the same
		on all of the servers in the cluster, and discoveryServers will be set to a different host
		and the same port.
	-->
	<cacheManagerPeerProviderFactory
		class="com.xarixa.ehcache.aws.AwsSecurityGroupAwareCacheManagerPeerProviderFactory"
		properties="securityGroup=sg-12378-ag,securityGroupRefreshInterval=10000,discoveryServiceClass=com.xarixa.ehcache.aws.SimpleDiscoveryServiceFactory"
		propertySeparator=","/>

	<cacheManagerPeerListenerFactory
		class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"
		properties="port=61618,socketTimeoutMillis=10000"/>

	<defaultCache
		maxElementsInMemory="10000"
		eternal="false"
        timeToIdleSeconds="600"
		overflowToDisk="false">
        <cacheEventListenerFactory
			class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"
			properties="replicatePuts=true,replicateUpdatesViaCopy=true"
			propertySeparator=","/>
		<!-- Set up to bootstrap before the cache can be started -->
	    <bootstrapCacheLoaderFactory
	        class="net.sf.ehcache.distribution.RMIBootstrapCacheLoaderFactory"
	        properties="bootstrapAsynchronously=false, maximumChunkSizeBytes=5242880"/>
	</defaultCache>

	<cache
		name="com.xarixa.ehcache.aws.Testing"
		maxElementsInMemory="10000"
		eternal="false"
        timeToIdleSeconds="600"
		overflowToDisk="false">
        <cacheEventListenerFactory
			class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"
			properties="replicateAsynchronously=false,replicatePuts=true,replicateUpdatesViaCopy=true"
			propertySeparator=","/>
		<!-- Set up to bootstrap before the cache can be started -->
	    <bootstrapCacheLoaderFactory
	        class="net.sf.ehcache.distribution.RMIBootstrapCacheLoaderFactory"
	        properties="bootstrapAsynchronously=false, maximumChunkSizeBytes=5242880"/>
	</cache>
</ehcache>


text:
<?php

namespace Wilson\AtmBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class WilsonAtmBundle extends Bundle
{
}


text:
#ifdef _DEBUG
#include <cassert>
#include <vector>
#ifdef _WIN32
#include "mferror.h"
#include "windows.h"
#include "mmsystem.h"
#include "mmreg.h"
#endif
#include "wfxrawwriter.hpp"

namespace WebmMfVorbisDecLib
{

WfxRawWriter::WfxRawWriter() : closed_(true)
{
  ::memset(&wave_format_, 0, sizeof WAVEFORMATEX);
}

WfxRawWriter::~WfxRawWriter()
{
  Close();
}

int WfxRawWriter::Open(const WAVEFORMATEX* ptr_wave_format)
{
  if (!ptr_wave_format)
    return E_POINTER;

  file_name_ = "out.wfxpcm";
  using std::ios;
  file_stream_.open(file_name_.c_str(), ios::binary);

  int result = E_FAIL;
  closed_ = !file_stream_.is_open();
  if (!closed_)
  {
    file_stream_ << 'W' << 'F' << 'X';
    const UINT32 num_bytes_to_write =
      sizeof WAVEFORMATEX + ptr_wave_format->cbSize;
    const char* const ptr_wfx_data = (char*)ptr_wave_format;
    file_stream_.write(ptr_wfx_data, num_bytes_to_write);
    result = Close();
  }
  return result;
}

int WfxRawWriter::Write(const BYTE* const ptr_byte_buffer, UINT32 byte_count)
{
  assert(ptr_byte_buffer);
  assert(byte_count > 0);
  if (!ptr_byte_buffer)
    return E_POINTER;
  if (byte_count <= 0)
    return E_INVALIDARG;
  if (Reopen_() == S_OK)
  {
    const char* const ptr_char_buffer = (const char*)ptr_byte_buffer;
    file_stream_.write(ptr_char_buffer, byte_count);
    Close();
  }
  return S_OK;
}

int WfxRawWriter::Reopen_()
{
  using std::ios;
  file_stream_.open(file_name_.c_str(), ios::binary | ios::ate | ios::app);
  closed_ = !file_stream_.is_open();
  assert(!closed_);
  if (closed_)
    return E_FAIL;
  return S_OK;
}

int WfxRawWriter::Close()
{
  int result = S_FALSE;
  if (!closed_)
  {
    file_stream_.flush();
    file_stream_.close();
    closed_ = true;
    result = S_OK;
  }
  return result;
}

} // WebmMfVorbisDecLib

#endif // _DEBUG


text:
<resources>

    <string name="title_activity_settings">Settings</string>
    <string name="pref_header_connection">Connection</string>
    <string name="pref_header_backup">Backup</string>
    <string name="pref_header_restore">Restore</string>
    <string name="pref_header_advanced">Advanced</string>
    <string name="pref_title_cname">Client name</string>
    <string name="pref_title_server">Server address</string>
    <string name="pref_title_password">Password</string>
    <string name="pref_title_min_file_size">Minimum file size (MB)</string>
    <string name="pref_title_max_file_size">Maximum file size (MB)</string>
    <string name="pref_title_includes">Included folders and files</string>
    <string name="pref_title_excludes">Excluded folders and files</string>
    <string name="pref_title_port">Port</string>
    <string name="pref_title_ratelimit">Rate limit (MB/s)</string>
    <string name="pref_title_network_timeout">Network timeout (sec)</string>
    <string name="pref_title_ssl_key_password">SSL key password</string>
    <string name="pref_title_ssl_peer_cn">SSL peer CNAME</string>
    <string name="pref_title_autoupgrade">Enable auto-upgrade</string>

</resources>


text:
package com.musicg.fingerprint;

import com.musicg.properties.FingerprintProperties;

/**
 * A class for fingerprint's similarity
 *
 * @author jacquet
 *
 */
public class FingerprintSimilarity {

	private FingerprintProperties fingerprintProperties=FingerprintProperties.getInstance();
	private int mostSimilarFramePosition;
	private float score;
	private float similarity;

	/**
	 * Constructor
	 */
	public FingerprintSimilarity() {
		mostSimilarFramePosition = Integer.MIN_VALUE;
		score=-1;
		similarity = -1;
	}

	/**
	 * Get the most similar position in terms of frame number
	 *
	 * @return most similar frame position
	 */
	public int getMostSimilarFramePosition() {
		return mostSimilarFramePosition;
	}

	/**
	 * Set the most similar position in terms of frame number
	 *
	 * @param mostSimilarFramePosition
	 */
	public void setMostSimilarFramePosition(int mostSimilarFramePosition) {
		this.mostSimilarFramePosition = mostSimilarFramePosition;
	}

	/**
	 * Get the similarity of the fingerprints
	 * similarity from 0~1, which 0 means no similar feature is found and 1 means in average there is at least one match in every frame
	 *
	 * @return fingerprints similarity
	 */
	public float getSimilarity() {
		return similarity;
	}

	/**
	 * Set the similarity of the fingerprints
	 *
	 * @param fingerprints similarity
	 */
	public void setSimilarity(float similarity) {
		this.similarity = similarity;
	}

	/**
	 * Get the similarity score of the fingerprints
	 * Number of features found in the fingerprints per frame
	 *
	 * @return fingerprints similarity score
	 */
	public float getScore() {
		return score;
	}

	/**
	 * Set the similarity score of the fingerprints
	 *
	 * @param score
	 */
	public void setScore(float score) {
		this.score = score;
	}

	/**
	 * Get the most similar position in terms of time in second
	 *
	 * @return most similar starting time
	 */
	public float getsetMostSimilarTimePosition(){
		return (float)mostSimilarFramePosition/fingerprintProperties.getNumRobustPointsPerFrame()/fingerprintProperties.getFps();
	}
}


text:
"use strict";
var ko = require("knockout");
var infiniteScroll = require("folke-ko-infinite-scroll");
/**
 * Creates an observable array with the SearchArray extensions
 * @param options
 * @param value
 */
function grid(options, value) {
    return ko.observableArray(value).extend({ searchArray: options });
}
exports.grid = grid;
/**
 * Creates an observable array with the SearchArray extensions
 * Similar to the grid method, but the parameters implements the SearchArrayParameters interface.
 * @param options The options for the SearchArray (of type SearchArrayParameters<TU>)
 * @param value The initial values
 */
function searchArray(options, value) {
    return ko.observableArray(value).extend({ searchArray: options });
}
exports.searchArray = searchArray;
/**
 * Describes an extension to an observable array that adds a method to load more data
 * @param target The observable that is extended
 * @param options The options
 */
function searchArrayExtension(target, options) {
    target.sortColumn = ko.observable(options.parameters.sortColumn);
    target.subscription = target.sortColumn.subscribe(function (newValue) {
        options.parameters.sortColumn = newValue;
        target.refresh();
    });
    infiniteScroll.scrollableArrayExtension(target, options);
}
exports.searchArrayExtension = searchArrayExtension;
;
var ViewModel = (function () {
    function ViewModel(params, nodes) {
        var _this = this;
        this.columnClass = function (column) {
            var sortElement = column.sort;
            if (sortElement == null)
                return;
            return ko.pureComputed(function () {
                var value = _this.rows.sortColumn();
                if (value === sortElement + '-asc') {
                    return sortElement + ' asc';
                }
                else if (value === sortElement + '-desc') {
                    return sortElement + ' desc';
                }
                else {
                    return sortElement + ' asc-desc';
                }
            });
        };
        this.sort = function (column) {
            if (!column.sort)
                return;
            var value = _this.rows.sortColumn();
            if (value === column.sort + '-asc') {
                _this.rows.sortColumn(column.sort + '-desc');
            }
            else {
                _this.rows.sortColumn(column.sort + '-asc');
            }
        };
        this.rows = params['rows'];
        var emptyMessage = this.rows.options.emptyMessage;
        this.empty = ko.computed(function () { return !_this.rows.updating() && _this.rows().length === 0 ? emptyMessage : undefined; });
        this.columns = params['columns'] || this.rows.options.columns;
        this.nodes = nodes;
    }
    ViewModel.prototype.dispose = function () { };
    return ViewModel;
}());
exports.ViewModel = ViewModel;
var viewModel = {
    createViewModel: function (params, componentInfo) {
        var nodes = componentInfo.templateNodes;
        // Petite bidouille pour se débarrasser du tbody qui est rajouté automatiquement si on met un tr dans un table
        var tbody = nodes.filter(function (x) { return x.localName === 'tbody'; })[0];
        if (tbody) {
            nodes = [];
            var childNodes = tbody.childNodes;
            for (var i = 0; i < childNodes.length; i++)
                nodes.push(childNodes[i]);
        }
        return new ViewModel(params, nodes);
    }
};
var template = "\n

\n\n\n
\n
\n
\n        \n        \n        	\n        \n        \n        	\n        \n        \n
\n
\n
\n
\n
\n

\n";
/**
 * Register the extensions
 */
function register() {
    ko.extenders['searchArray'] = searchArrayExtension;
    ko.components.register('grid', {
        template: template,
        viewModel: viewModel
    });
}
exports.register = register;


text:
'use strict';

const fCache = require('file-entry-cache');
const path = require('path');
const { promises: fs, existsSync } = require('fs');

const hash = require('../utils/hash');
const replaceBackslashes = require('../testUtils/replaceBackslashes');
const removeFile = require('../testUtils/removeFile');
const safeChdir = require('../testUtils/safeChdir');
const standalone = require('../standalone');

const isChanged = (file, targetFilePath) => {
	return file.source === targetFilePath && !file.ignored;
};

const fixturesPath = path.join(__dirname, 'fixtures');
const invalidFile = path.join(fixturesPath, 'empty-block.css');
const syntaxErrorFile = path.join(fixturesPath, 'syntax_error.css');
const validFile = path.join(fixturesPath, 'cache', 'valid.css');
const newFileDest = path.join(fixturesPath, 'cache', 'newFile.css');

// Config object is getting mutated internally.
// Return new object of the same structure to
// make sure config doesn't change between runs.
function getConfig(additional = {}) {
	return {
		files: replaceBackslashes(path.join(fixturesPath, 'cache', '*.css')),
		config: {
			rules: { 'block-no-empty': true, 'color-no-invalid-hex': true },
		},
		cache: true,
		...additional,
	};
}

describe('standalone cache', () => {
	const cwd = path.join(__dirname, 'tmp', 'standalone-cache');

	safeChdir(cwd);

	const expectedCacheFilePath = path.join(cwd, '.stylelintcache');

	beforeEach(async () => {
		// Initial run to warm up the cache
		await standalone(getConfig());
	});

	afterEach(async () => {
		// Clean up after each test case
		await removeFile(expectedCacheFilePath);
		await removeFile(newFileDest);
	});

	it('cache file is created at $CWD/.stylelintcache', async () => {
		// Ensure cache file exists
		expect(existsSync(expectedCacheFilePath)).toBe(true);

		const { cache } = fCache.createFromFile(expectedCacheFilePath);

		// Ensure cache file contains only linted css file
		expect(typeof cache.getKey(validFile)).toBe('object');
		expect(cache.getKey(validFile)).toBeTruthy();
		expect(cache.getKey(newFileDest)).toBeUndefined();
	});

	it('only changed files are linted', async () => {
		// Add "changed" file
		await fs.copyFile(validFile, newFileDest);

		// Next run should lint only changed files
		const { results } = await standalone(getConfig());

		// Ensure only changed files are linted
		expect(results.some((file) => isChanged(file, validFile))).toBe(false);
		expect(results.some((file) => isChanged(file, newFileDest))).toBe(true);

		const { cache } = fCache.createFromFile(expectedCacheFilePath);

		expect(typeof cache.getKey(validFile)).toBe('object');
		expect(cache.getKey(validFile)).toBeTruthy();
		expect(typeof cache.getKey(newFileDest)).toBe('object');
		expect(cache.getKey(newFileDest)).toBeTruthy();
	});

	it('all files are linted on config change', async () => {
		await fs.copyFile(validFile, newFileDest);

		// All file should be re-linted as config has changed
		const { results } = await standalone(
			getConfig({
				config: {
					rules: { 'block-no-empty': false },
				},
			}),
		);

		// Ensure all files are re-linted
		expect(results.some((file) => isChanged(file, validFile))).toBe(true);
		expect(results.some((file) => isChanged(file, newFileDest))).toBe(true);
	});

	it('invalid files are not cached', async () => {
		await fs.copyFile(invalidFile, newFileDest);

		// Should lint only changed files
		const { errored, results } = await standalone(getConfig());

		expect(errored).toBe(true);

		// Ensure only changed files are linted
		expect(results.some((file) => isChanged(file, validFile))).toBe(false);
		expect(results.some((file) => isChanged(file, newFileDest))).toBe(true);

		const { cache } = fCache.createFromFile(expectedCacheFilePath);

		expect(typeof cache.getKey(validFile)).toBe('object');
		expect(cache.getKey(validFile)).toBeTruthy();
		expect(cache.getKey(newFileDest)).toBeUndefined();
	});

	it('warning files are not cached', async () => {
		await fs.copyFile(invalidFile, newFileDest);

		const { errored, results } = await standalone(
			getConfig({
				config: {
					rules: { 'block-no-empty': [true, { severity: 'warning' }] },
				},
			}),
		);

		expect(errored).toBe(false);

		// cache is discarded because config changed
		expect(results.some((file) => isChanged(file, validFile))).toBe(true);
		expect(results.some((file) => isChanged(file, newFileDest))).toBe(true);

		const { cache } = fCache.createFromFile(expectedCacheFilePath);

		expect(typeof cache.getKey(validFile)).toBe('object');
		expect(cache.getKey(validFile)).toBeTruthy();
		expect(cache.getKey(newFileDest)).toBeUndefined();
	});

	it('files with syntax errors are not cached', async () => {
		await fs.copyFile(syntaxErrorFile, newFileDest);

		// Should lint only changed files
		await standalone(getConfig());

		const { cache } = fCache.createFromFile(expectedCacheFilePath);

		expect(typeof cache.getKey(validFile)).toBe('object');
		expect(cache.getKey(validFile)).toBeTruthy();
		expect(cache.getKey(newFileDest)).toBeUndefined();
	});

	it('cache file is removed when cache is disabled', async () => {
		await standalone(getConfig({ cache: false }));
		expect(existsSync(expectedCacheFilePath)).toBe(false);
	});

	it("cache doesn't do anything if string is passed", async () => {
		// Ensure no cache file
		await removeFile(expectedCacheFilePath);

		const config = {
			code: '.foo {}',
			codeFilename: 'foo.css',
			cache: true,
			config: {
				rules: {
					'color-no-invalid-hex': true,
				},
			},
		};

		const lintResults = await standalone(config);

		expect(lintResults.errored).toBe(false);
		expect(existsSync(expectedCacheFilePath)).toBe(false);
	});
});

describe('standalone cache uses cacheLocation', () => {
	const cwd = path.join(__dirname, 'tmp', 'standalone-cache-uses-cacheLocation');

	safeChdir(cwd);

	const cacheLocationFile = path.join(fixturesPath, 'cache', '.cachefile');
	const cacheLocationDir = path.join(fixturesPath, 'cache');
	const expectedCacheFilePath = path.join(cacheLocationDir, `.stylelintcache_${hash(cwd)}`);

	afterEach(async () => {
		// clean up after each test
		await removeFile(expectedCacheFilePath);
		await removeFile(cacheLocationFile);
	});

	it('cacheLocation is a file', async () => {
		await standalone(getConfig({ cacheLocation: cacheLocationFile }));

		// Ensure cache file is created
		expect(existsSync(cacheLocationFile)).toBe(true);

		const { cache } = fCache.createFromFile(cacheLocationFile);

		expect(typeof cache.getKey(validFile)).toBe('object');
		expect(cache.getKey(validFile)).toBeTruthy();
	});

	it('cacheLocation is a directory', async () => {
		await standalone(getConfig({ cacheLocation: cacheLocationDir }));

		// Ensure cache file is created
		expect(existsSync(expectedCacheFilePath)).toBe(true);

		const { cache } = fCache.createFromFile(expectedCacheFilePath);

		expect(typeof cache.getKey(validFile)).toBe('object');
		expect(cache.getKey(validFile)).toBeTruthy();
	});
});

describe('standalone cache uses a config file', () => {
	const cwd = path.join(__dirname, 'tmp', 'standalone-cache-use-config-file');

	safeChdir(cwd);

	const configFile = path.join(cwd, '.stylelintrc.json');
	const lintedFile = path.join(cwd, 'a.css');

	beforeEach(async () => {
		await fs.writeFile(lintedFile, 'a {}');
	});

	afterEach(async () => {
		await removeFile(configFile);
		await removeFile(lintedFile);
	});

	it('cache is discarded when a config file is changed', async () => {
		const config = { files: [lintedFile], config: undefined, cache: true };

		// No warnings when a rule is disabled.
		await fs.writeFile(
			configFile,
			JSON.stringify({
				rules: { 'block-no-empty': null },
			}),
		);
		const { results } = await standalone(config);

		expect(results[0].warnings).toHaveLength(0);

		// Some warnings when a rule becomes enabled by changing the config.
		await fs.writeFile(
			configFile,
			JSON.stringify({
				rules: { 'block-no-empty': true },
			}),
		);
		const { results: resultsNew } = await standalone(config);

		expect(resultsNew[0].warnings).toHaveLength(1);
	});
});

describe('standalone cache uses cacheStrategy', () => {
	const cwd = path.join(__dirname, 'tmp', 'standalone-cache-uses-cacheStrategy');

	safeChdir(cwd);

	const expectedCacheFilePath = path.join(cwd, '.stylelintcache');

	afterEach(async () => {
		// clean up after each test
		await removeFile(expectedCacheFilePath);
		await removeFile(newFileDest);
	});

	it('cacheStrategy is invalid', async () => {
		await expect(standalone(getConfig({ cacheStrategy: 'foo' }))).rejects.toThrow(
			'"foo" cache strategy is unsupported. Specify either "metadata" or "content"',
		);
	});

	it('cacheStrategy is "metadata"', async () => {
		const cacheStrategy = 'metadata';

		await fs.copyFile(validFile, newFileDest);
		const { results } = await standalone(getConfig({ cacheStrategy }));

		expect(results.some((file) => isChanged(file, newFileDest))).toBe(true);

		// No content change, but file metadata id changed
		await fs.utimes(newFileDest, new Date(), new Date());
		const { results: resultsCached } = await standalone(getConfig({ cacheStrategy }));

		expect(resultsCached.some((file) => isChanged(file, newFileDest))).toBe(true);
	});

	it('cacheStrategy is "content"', async () => {
		const cacheStrategy = 'content';

		await fs.copyFile(validFile, newFileDest);
		const { results } = await standalone(getConfig({ cacheStrategy }));

		expect(results.some((file) => isChanged(file, newFileDest))).toBe(true);

		// No content change, but file metadata id changed
		await fs.utimes(newFileDest, new Date(), new Date());
		const { results: resultsCached } = await standalone(getConfig({ cacheStrategy }));

		expect(resultsCached.some((file) => isChanged(file, newFileDest))).toBe(false);
	});
});


text:
import Ember from 'ember';
import NotifyUser from '../../mixins/notify-user';
import ErrorHandler from '../../mixins/handle-errors';
import SessionService from 'ember-simple-auth/services/session';

export default Ember.Component.extend(NotifyUser, ErrorHandler, {
  tableClassNames:'table table-striped table-bordered table-hover table-responsive table-condensed',

  /**
   * Session service injection
   *
   * @property session
   * @type SessionService
   */
  session: Ember.inject.service('session'),

  options: {
    token: '',
    selector: 'textarea',
    height: 500,
    theme: 'modern',
    plugins: 'print preview fullpage searchreplace autolink directionality visualblocks visualchars fullscreen image link media template codesample table charmap hr pagebreak nonbreaking anchor toc insertdatetime advlist lists textcolor wordcount imagetools contextmenu colorpicker textpattern help',
    toolbar1: 'formatselect | bold italic strikethrough forecolor backcolor | image | alignleft aligncenter alignright alignjustify  | numlist bullist outdent indent  | removeformat',
    image_advtab: true,
    // without images_upload_url set, Upload tab won't show up
    images_upload_url: 'http://localhost:80/employees/imageupload',
    images_upload_credentials: true,
    // enable title field in the Image dialog
    image_title: true,
    images_upload_handler: function (blobInfo, success, failure) {
          var xhr, formData;
          xhr = new XMLHttpRequest();
          xhr.withCredentials = false;
          xhr.open('POST', 'http://localhost:80/employees/imageupload');
          xhr.setRequestHeader("Authorization",  tinyMCE.settings.token);
          xhr.onload = function() {
              var json;
              if (xhr.status != 200) {
                  failure('HTTP Error: ' + xhr.status);
                  return;
              }
              json = JSON.parse(xhr.responseText);
              if (!json || typeof json.location != 'string') {
                  failure('Invalid JSON: ' + xhr.responseText);
                  return;
              }
              success(json.location);
          };
          formData = new FormData();
          formData.append('file', blobInfo.blob(), blobInfo.filename());
          xhr.send(formData);
      },
    // enable automatic uploads of images represented by blob or data URIs
    // automatic_uploads: true,
    // file_picker_types: 'image',
    // init_instance_callback: function (ed) {
    //   ed.execCommand('mceImage');
    // }
  },

  init() {
    this._super(...arguments);

    const token = this.get('session.session.content.authenticated.access_token');
    this.set('options.token', token);
  },

  showModal: '',

  /**
   * Reset all inputs when click 'Hide' button.
   *
   * @method _discardDetail
   * @param {Object} news
   * @private
   */
  _discardDetail(news) {
    if (news.get('hasDirtyAttributes')) {
      news.rollbackAttributes();
    }
    this.set('rowIndexToShowDetail', null);
    this.set('showModal', false);
  },

  /**
   * Setup modal diaog texts.
   *
   * @method _setModalText
   * @param {String} action
   * @private
   */
  _setModalText(action) {
    if (action == 'saveChanges') {
      this.set('modalTitle', 'Save News');
      this.set('modalBody', 'Are you sure that you want to save all news changes?');
    }
    if (action == 'discardChanges') {
      this.set('modalTitle', 'Unsaved Changes');
      this.set('modalBody', 'Are you sure that you want to discard all news changes?');
    }
    if (action == 'deleteNews') {
      this.set('modalTitle', 'Delete News');
      this.set('modalBody', 'Are you sure that you want to permanently delete that news?');
    }
  },

  actions: {
    /**
     *  When click 'Show' button will show or discard all news details.
     *
     * @method toggleDetail
     * @param {String} rowIndex
     */
    toggleDetail(rowIndex) {
      const allNews = this.get('data').toArray();
      const currentNews = allNews[rowIndex];

      if (this.get('rowIndexToShowDetail') === rowIndex) {
        this._discardDetail(currentNews);
      } else {
        const news = Object.keys(currentNews.data);

        this.set('rowIndexToShowDetail', rowIndex);
        news.forEach(property => {
          this.set(property, currentNews.data[property]);
        });
      }
    },

    /**
     *  Delete news.
     *
     * @method deleteNews
     */
    deleteNews() {
      const news = this.get('news');
      news.deleteRecord();

      news.save()
      .then(() => {
        this.notifyUser('The news has been deleted successfully', "success");
        this.set('rowIndexToShowDetail', null);

      })
      .catch((error) => {
        this.handleErrors(error);
        this.set('rowIndexToShowDetail', null);
      });
    },

  /**
   *  Discard all changes.
   *
   * @method discardChanges
   */
    discardChanges() {
      const news = this.get('news');
      this.notifyUser('All changes have not been saved', "error");
      this._discardDetail(news);
    },

  /**
   *  Save all changes.
   *
   * @method saveChanges
   */
    saveChanges() {
      const news = this.get('news');

      news.save()
      .then(() => {
        this.notifyUser('Member has been saved successfully', "success");
        this._discardDetail(news);
      })
      .catch((error) => {
        this.handleErrors(error);
        this._discardDetail(news);
      });
    },

    /**
     *  Show modal dialog. Setup modal action and action target.
     *
     * @method showModalDialog
     * @param {Object} news
     */
    showModalDialog(news, action) {
      this.set('news', news)
      this.set('action', action);
      this._setModalText(action);
      this.set('showModal', true);
    },

    /**
     *  Close modal dialog.
     *
     * @method closeModalDialog
     */
    closeModalDialog() {
      this.set('news', null)
      this.set('showModal', false);
    },

    /**
     *  Trigger modal dialog action.
     *
     * @method actionModalDialog
     */
    actionModalDialog() {
      this.send(this.get('action'));
      this.set('showModal', false);
    }
  }
});


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('player', '0004_auto_20151226_1927'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='player',
            name='damage',
        ),
        migrations.AddField(
            model_name='player',
            name='status',
            field=models.CharField(choices=[(b'p', b'Passive'), (b'c', b'Combat'), (b'v', b'Victory')], default=b'p', max_length=1),
        ),
    ]


text:
Returns `true` if passed an "empty" value and `false` for everything else.

Empty is defined as:
- empty objects: `{}`
- empty arrays: `[]`
- empty string: `''`
- `undefined`
- `null`
- `NaN`
- the number zero: `0`


text:
/*
 * This used to have a license header that it was licensed by Gatespace in the year 2000. However, this was licensed
 * to the OSGi Alliance. A member donated this as ASL 2.0 licensed matching this project's default license.
 */
package aQute.lib.filter;

import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Collection;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.Map;

public class Filter {
	final char			WILDCARD	= 65535;

	final static int	EQ			= 0;
	final static int	LE			= 1;
	final static int	GE			= 2;
	final static int	APPROX		= 3;

	String				filter;

	abstract class Query {
		static final String	GARBAGE		= "Trailing garbage";
		static final String	MALFORMED	= "Malformed query";
		static final String	EMPTY		= "Empty list";
		static final String	SUBEXPR		= "No subexpression";
		static final String	OPERATOR	= "Undefined operator";
		static final String	TRUNCATED	= "Truncated expression";
		static final String	EQUALITY	= "Only equality supported";

		private String		tail;

		boolean match() throws IllegalArgumentException {
			tail = filter;
			boolean val = doQuery();
			if (tail.length() > 0)
				error(GARBAGE);
			return val;
		}

		private boolean doQuery() throws IllegalArgumentException {
			if (tail.length() < 3 || !prefix("("))
				error(MALFORMED);
			boolean val;

			switch (tail.charAt(0)) {
				case '&' :
					val = doAnd();
					break;
				case '|' :
					val = doOr();
					break;
				case '!' :
					val = doNot();
					break;
				default :
					val = doSimple();
					break;
			}

			if (!prefix(")"))
				error(MALFORMED);
			return val;
		}

		private boolean doAnd() throws IllegalArgumentException {
			tail = tail.substring(1);
			boolean val = true;
			if (!tail.startsWith("("))
				error(EMPTY);
			do {
				if (!doQuery())
					val = false;
			} while (tail.startsWith("("));
			return val;
		}

		private boolean doOr() throws IllegalArgumentException {
			tail = tail.substring(1);
			boolean val = false;
			if (!tail.startsWith("("))
				error(EMPTY);
			do {
				if (doQuery())
					val = true;
			} while (tail.startsWith("("));
			return val;
		}

		private boolean doNot() throws IllegalArgumentException {
			tail = tail.substring(1);
			if (!tail.startsWith("("))
				error(SUBEXPR);
			return !doQuery();
		}

		private boolean doSimple() throws IllegalArgumentException {
			int op = 0;
			Object attr = getAttr();

			if (prefix("="))
				op = EQ;
			else if (prefix("<="))
				op = LE;
			else if (prefix(">="))
				op = GE;
			else if (prefix("~="))
				op = APPROX;
			else
				error(OPERATOR);

			return compare(attr, op, getValue());
		}

		private boolean prefix(String pre) {
			if (!tail.startsWith(pre))
				return false;
			tail = tail.substring(pre.length());
			return true;
		}

		private Object getAttr() {
			int len = tail.length();
			int ix = 0;
			label: for (; ix < len; ix++) {
				switch (tail.charAt(ix)) {
					case '(' :
					case ')' :
					case '<' :
					case '>' :
					case '=' :
					case '~' :
					case '*' :
					case '\\' :
						break label;
				}
			}
			String attr = tail.substring(0, ix);
			tail = tail.substring(ix);
			return getProp(attr);
		}

		abstract Object getProp(String key);

		private String getValue() {
			StringBuilder sb = new StringBuilder();
			int len = tail.length();
			int ix = 0;
			label: for (; ix < len; ix++) {
				char c = tail.charAt(ix);
				switch (c) {
					case '(' :
					case ')' :
						break label;
					case '*' :
						sb.append(WILDCARD);
						break;
					case '\\' :
						if (ix == len - 1)
							break label;
						sb.append(tail.charAt(++ix));
						break;
					default :
						sb.append(c);
						break;
				}
			}
			tail = tail.substring(ix);
			return sb.toString();
		}

		private void error(String m) throws IllegalArgumentException {
			throw new IllegalArgumentException(m + " " + tail);
		}

		@SuppressWarnings("unchecked")
		private <T> boolean compare(T obj, int op, String s) {
			if (obj == null)
				return false;
			try {
				Class<T> numClass = (Class<T>) obj.getClass();
				if (numClass == String.class) {
					return compareString((String) obj, op, s);
				} else if (numClass == Character.class) {
					return compareString(obj.toString(), op, s);
				} else if (numClass == Long.class) {
					return compareSign(op, Long.valueOf(s).compareTo((Long) obj));
				} else if (numClass == Integer.class) {
					return compareSign(op, Integer.valueOf(s).compareTo((Integer) obj));
				} else if (numClass == Short.class) {
					return compareSign(op, Short.valueOf(s).compareTo((Short) obj));
				} else if (numClass == Byte.class) {
					return compareSign(op, Byte.valueOf(s).compareTo((Byte) obj));
				} else if (numClass == Double.class) {
					return compareSign(op, Double.valueOf(s).compareTo((Double) obj));
				} else if (numClass == Float.class) {
					return compareSign(op, Float.valueOf(s).compareTo((Float) obj));
				} else if (numClass == Boolean.class) {
					if (op != EQ)
						return false;
					int a = Boolean.valueOf(s).booleanValue() ? 1 : 0;
					int b = ((Boolean) obj).booleanValue() ? 1 : 0;
					return compareSign(op, a - b);
				} else if (numClass == BigInteger.class) {
					return compareSign(op, new BigInteger(s).compareTo((BigInteger) obj));
				} else if (numClass == BigDecimal.class) {
					return compareSign(op, new BigDecimal(s).compareTo((BigDecimal) obj));
				} else if (obj instanceof Collection< ? >) {
					for (Object x : (Collection< ? >) obj)
						if (compare(x, op, s))
							return true;
				} else if (numClass.isArray()) {
					int len = Array.getLength(obj);
					for (int i = 0; i < len; i++)
						if (compare(Array.get(obj, i), op, s))
							return true;
				} else {
					Constructor<T> constructor = numClass.getConstructor(String.class);
					T source = constructor.newInstance(s);
					if (op == EQ)
						return source.equals(obj);
					Comparable<T> a = Comparable.class.cast(source);
					Comparable<T> b = Comparable.class.cast(obj);
					return compareSign(op, a.compareTo((T) b));
				}
			} catch (Exception e) {}
			return false;
		}
	}

	class DictQuery extends Query {
		private Dictionary< ? , ? > dict;

		DictQuery(Dictionary< ? , ? > dict) {
			this.dict = dict;
		}

		@Override
		Object getProp(String key) {
			return dict.get(key);
		}
	}

	class MapQuery extends Query {
		private Map< ? , ? > map;

		MapQuery(Map< ? , ? > dict) {
			this.map = dict;
		}

		@Override
		Object getProp(String key) {
			return map.get(key);
		}
	}

	public Filter(String filter) throws IllegalArgumentException {
		// NYI: Normalize the filter string?
		this.filter = filter;
		if (filter == null || filter.length() == 0)
			throw new IllegalArgumentException("Null query");
	}

	public boolean match(Dictionary< ? , ? > dict) {
		try {
			return new DictQuery(dict).match();
		} catch (IllegalArgumentException e) {
			return false;
		}
	}

	public boolean matchMap(Map< ? , ? > dict) {
		try {
			return new MapQuery(dict).match();
		} catch (IllegalArgumentException e) {
			return false;
		}
	}

	public String verify() {
		try {
			new DictQuery(new Hashtable<Object,Object>()).match();
		} catch (IllegalArgumentException e) {
			return e.getMessage();
		}
		return null;
	}

	@Override
	public String toString() {
		return filter;
	}

	@Override
	public boolean equals(Object obj) {
		return obj != null && obj instanceof Filter && filter.equals(((Filter) obj).filter);
	}

	@Override
	public int hashCode() {
		return filter.hashCode();
	}

	boolean compareString(String s1, int op, String s2) {
		switch (op) {
			case EQ :
				return patSubstr(s1, s2);
			case APPROX :
				return fixupString(s2).equals(fixupString(s1));
			default :
				return compareSign(op, s2.compareTo(s1));
		}
	}

	boolean compareSign(int op, int cmp) {
		switch (op) {
			case LE :
				return cmp >= 0;
			case GE :
				return cmp <= 0;
			case EQ :
				return cmp == 0;
			default : /* APPROX */
				return cmp == 0;
		}
	}

	String fixupString(String s) {
		StringBuilder sb = new StringBuilder();
		int len = s.length();
		boolean isStart = true;
		boolean isWhite = false;
		for (int i = 0; i < len; i++) {
			char c = s.charAt(i);
			if (Character.isWhitespace(c)) {
				isWhite = true;
			} else {
				if (!isStart && isWhite)
					sb.append(' ');
				if (Character.isUpperCase(c))
					c = Character.toLowerCase(c);
				sb.append(c);
				isStart = false;
				isWhite = false;
			}
		}
		return sb.toString();
	}

	boolean patSubstr(String s, String pat) {
		if (s == null)
			return false;
		if (pat.length() == 0)
			return s.length() == 0;
		if (pat.charAt(0) == WILDCARD) {
			pat = pat.substring(1);
			for (;;) {
				if (patSubstr(s, pat))
					return true;
				if (s.length() == 0)
					return false;
				s = s.substring(1);
			}
		}
		if (s.length() == 0 || s.charAt(0) != pat.charAt(0))
			return false;
		return patSubstr(s.substring(1), pat.substring(1));
	}
}


text:
class unable_to_find_executable_path {};

std::string executable_path();

#endif //SDL_CPP_WIDGETS_EXECUTABLE_PATH_H


text:
using System.Collections.Generic;

namespace Smartling.Api.Model
{
  public class AuditLogList<T>
  {
    public int totalCount { get; set; }
    public List<T> items { get; set; }
  }
}


text:
"""Methods for performing repairs that will Stabilize genomes.

These methods perform repair to keep chromosomes from drifting too far in
any direction -- ie. bring them back to a stabilizing center. This may be
useful in cases where fitness functions alone won't keep chromosomes in
check.
"""
# standard library
import random

class AmbiguousRepair(object):
    """Perform repair to reduce the number of Ambiguous genes in a genome.

    In cases where ambiguous genes are allowed in a genome (for example,
    where you have a wild card character like '*' that will match
    anything), these can come to dominate a genome since, really, the
    best fitness is someting like '*******'. This repair protects against
    that by changing ambiguous characters into some non-ambiguous gene.
    """
    def __init__(self, ambig_finder, num_ambiguous):
        """Initialize the repair class.

        Arguments:

        o ambig_finder - A class implementing the function find_ambiguous
        which will return a list of all ambiguous positions in a sequence.
        It also must have the function all_unambiguous, which will return
        all allowed unambiguous letters.

        o num_ambiguous - The minimum number of ambiguous items that are
        allowed in a genome. If there are more than this present, repair
        will be performed.
        """
        self._ambig_finder = ambig_finder
        self._num_ambiguous = num_ambiguous
        self._alphabet_letters = ambig_finder.all_unambiguous()

    def repair(self, organism):
        """Perform a repair to remove excess ambiguous genes.
        """
        new_org = organism.copy()

        # start getting rid of ambiguous items
        while True:
            # first find all of the ambigous items
            seq_genome = new_org.genome.toseq()
            all_ambiguous = self._ambig_finder.find_ambiguous(str(seq_genome))

            # if we have less then the number of ambiguous allowed, stop
            if len(all_ambiguous) <= self._num_ambiguous:
                break

            # remove an ambiguous item and replace it with a non-ambiguous
            to_change = random.choice(all_ambiguous)
            new_gene = random.choice(self._alphabet_letters)
            new_org.genome[to_change] = new_gene

        return new_org


text:
package cmdimpl

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
	"sort"
	"strings"
	"text/tabwriter"
	"time"

	"go.ligato.io/cn-infra/v2/db/keyval/etcd"
	"go.ligato.io/cn-infra/v2/health/statuscheck/model/status"

	"github.com/contiv/vpp/plugins/netctl/remote"
)

// PrintNodes will print out all of the cmdimpl in a network in a table format.
func PrintNodes(client *remote.HTTPClient, db *etcd.BytesConnectionEtcd) {
	nodes := make([]string, 0)
	for k := range getClusterNodeInfo(db) {
		nodes = append(nodes, k)
	}
	sort.Strings(nodes)

	w := tabwriter.NewWriter(os.Stdout, 0, 8, 2, ' ', 0)
	fmt.Fprintf(w, "ID\tNODE-NAME\tVPP-IP\tHOST-IP\tSTART-TIME\tSTATE\tBUILD-VERSION\tBUILD-DATE\n")

	for _, n := range nodes {
		nodeInfo := nodeInfo[n]
		// Get liveness data which contains image version / build date
		bytes, err := getNodeInfo(client, nodeInfo.mgmtIPAddress, "liveness")
		if err != nil {
			fmt.Printf("Could not get liveness data for node '%s'\n", nodeInfo.name)
			continue
		}

		// Reformat the image build date to the common format
		buildDate := "Not Available"
		buildVersion := "Not Available"
		var liveness status.AgentStatus
		if err = json.Unmarshal(bytes, &liveness); err == nil {
			buildVersion = liveness.BuildVersion
			buildDate = liveness.BuildDate
			bd, err1 := time.Parse("2006-01-02T15:04Z07:00", buildDate)
			if err1 == nil {
				buildDate = bd.Format(timeLayout)
			}
		}

		fmt.Fprintf(w, "%d\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n",
			nodeInfo.id,
			nodeInfo.name,
			strings.Split(nodeInfo.vppIPAddress, "/")[0],
			nodeInfo.mgmtIPAddress,
			time.Unix(int64(liveness.StartTime), 0).Format(timeLayout),
			status.OperationalState_name[int32(liveness.State)],
			buildVersion,
			buildDate)
	}

	w.Flush()
}

// getNodeInfo will make an http request for the given command and return an indented slice of bytes.
func getNodeInfo(client *remote.HTTPClient, base string, cmd string) ([]byte, error) {
	res, err := client.Get(base, cmd)
	if err != nil {
		err := fmt.Errorf("getNodeInfo: url: %s Get Error: %s", cmd, err.Error())
		fmt.Printf("http get error: %s ", err.Error())
		return nil, err
	}
	defer res.Body.Close()
	if res.StatusCode < 200 || res.StatusCode > 299 {
		err := fmt.Errorf("getNodeInfo: url: %s HTTP res.Status: %s", cmd, res.Status)
		fmt.Printf("http get error: %s ", err.Error())
		return nil, err
	}

	b, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return nil, err
	}

	var out bytes.Buffer
	err = json.Indent(&out, b, "", "  ")
	return out.Bytes(), err
}

// setNodeInfo will make an http json post request to get the vpp cli command output
func setNodeInfo(client *remote.HTTPClient, base string, cmd string, body string) error {
	res, err := client.Post(base, cmd, body)
	defer res.Body.Close()
	if err != nil {
		err := fmt.Errorf("setNodeInfo: url: %s Get Error: %s", cmd, err.Error())
		return err
	} else if res.StatusCode < 200 || res.StatusCode > 299 {
		err := fmt.Errorf("setNodeInfo: url: %s HTTP res.Status: %s", cmd, res.Status)
		return err
	}

	b, _ := ioutil.ReadAll(res.Body)
	fmt.Println(strings.Replace(string(b), "\\n", "\n", -1))
	return nil

}


text:
export function isString(v: any): boolean {
  return typeof v === 'string';
}


text:
This Qt repository was developed using OpenCV. The main goal was to play with Qt and to experiment / implement computer vision algorithms.

* SLIC superpixel algorithm (http://ivrl.epfl.ch/research/superpixels) was implemented.

* Several images transition algorithms were implemented. They support gray scale images and three channel images.

* GPU support and CPU only super resolution were experimented.

* A Qt interface was implemented. It supports opening a file, invoking the image transition algorithms and SLIC superpixel algorithm in the opened image.


text:
<?php

namespace lithium\core;

$message  = "lithium\core\Object has been deprecated.";
$message .= "The old class and methods continue to work and redirect calls. ";
$message .= "It is possible to use this class as `ObjectDeprecated` with PHP >=7.2.";
trigger_error($message, E_USER_DEPRECATED);

if (PHP_VERSION_ID < 70200) {
	class_alias('ObjectDeprecated', 'Object');
}

?>


text:
package com.github.ddth.queue.test.universal.idstr.mongodb;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

@RunWith(Suite.class)

@Suite.SuiteClasses({
    TestMongodbQueue.class,
    TestMongodbQueueLong.class,
    TestMongodbQueueLongBoundEphemeralSize.class,
    TestMongodbQueueLongEphemeralDisabled.class,
    TestMongodbQueueMT.class,
    TestMongodbQueueMTBoundEphemeralSize.class,
    TestMongodbQueueMTEphemeralDisabled.class
})

/*
 * mvn test -DskipTests=false -Dtest=com.github.ddth.queue.test.universal.idstr.mongodb.MySuiteTest -DenableTestsMongo=true
 */

public class MySuiteTest {
}


text:
Originally published: 2013-10-23 15:55:04
Last updated: 2013-10-23 15:55:05
Author: greg zakharov

Current month calendar. The smallest realization, I suppose.