text:
package com.clearspring.analytics.stream.cardinality;

import java.io.IOException;

public interface ICardinality
{
    /**
     * @param o stream element
     * @return false if the value returned by cardinality() is unaffected by the appearance of o in the stream.
     */
    boolean offer(Object o);

    /**
     * Offer the value as a hashed long value
     *
     * @param hashedLong - the hash of the item to offer to the estimator
     * @return false if the value returned by cardinality() is unaffected by the appearance of hashedLong in the stream
     */
    boolean offerHashed(long hashedLong);

    /**
     * Offer the value as a hashed long value
     *
     * @param hashedInt - the hash of the item to offer to the estimator
     * @return false if the value returned by cardinality() is unaffected by the appearance of hashedInt in the stream
     */
    boolean offerHashed(int hashedInt);

    /**
     * @return the number of unique elements in the stream or an estimate thereof
     */
    long cardinality();

    /**
     * @return size in bytes needed for serialization
     */
    int sizeof();

    /**
     * @return
     * @throws IOException
     */
    byte[] getBytes() throws IOException;

    /**
     * Merges estimators to produce an estimator for the combined streams
     * of this estimator and those passed as arguments
     *
     * @param estimators
     * @throws CardinalityMergeException
     */
    ICardinality merge(ICardinality... estimators) throws CardinalityMergeException;
}


text:
package org.apache.hadoop.yarn.server.nodemanager.containermanager.logaggregation;

import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

import org.apache.hadoop.security.token.SecretManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileContext;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.security.Credentials;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.service.AbstractService;
import org.apache.hadoop.util.concurrent.HadoopExecutors;
import org.apache.hadoop.yarn.api.records.ApplicationAccessType;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.ContainerId;
import org.apache.hadoop.yarn.api.records.LogAggregationContext;
import org.apache.hadoop.yarn.api.records.NodeId;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.event.Dispatcher;
import org.apache.hadoop.yarn.exceptions.YarnRuntimeException;
import org.apache.hadoop.yarn.logaggregation.filecontroller.LogAggregationFileController;
import org.apache.hadoop.yarn.logaggregation.filecontroller.LogAggregationFileControllerFactory;
import org.apache.hadoop.yarn.server.api.ContainerLogContext;
import org.apache.hadoop.yarn.server.api.ContainerType;
import org.apache.hadoop.yarn.server.nodemanager.Context;
import org.apache.hadoop.yarn.server.nodemanager.DeletionService;
import org.apache.hadoop.yarn.server.nodemanager.LocalDirsHandlerService;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.application.ApplicationEvent;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.application.ApplicationEventType;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.loghandler.LogHandler;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.loghandler.event.LogHandlerAppFinishedEvent;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.loghandler.event.LogHandlerAppStartedEvent;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.loghandler.event.LogHandlerContainerFinishedEvent;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.loghandler.event.LogHandlerEvent;

import org.apache.hadoop.classification.VisibleForTesting;
import org.apache.hadoop.thirdparty.com.google.common.util.concurrent.ThreadFactoryBuilder;

public class LogAggregationService extends AbstractService implements
    LogHandler {

  private static final Logger LOG =
       LoggerFactory.getLogger(LogAggregationService.class);
  // This configuration is for debug and test purpose. By setting
  // this configuration as true. We can break the lower bound of
  // NM_LOG_AGGREGATION_ROLL_MONITORING_INTERVAL_SECONDS.
  private static final String NM_LOG_AGGREGATION_DEBUG_ENABLED
      = YarnConfiguration.NM_PREFIX + "log-aggregation.debug-enabled";
  private long rollingMonitorInterval;

  private final Context context;
  private final DeletionService deletionService;
  private final Dispatcher dispatcher;

  private LocalDirsHandlerService dirsHandler;
  private NodeId nodeId;

  private final ConcurrentMap<ApplicationId, AppLogAggregator> appLogAggregators;

  // Holds applications whose aggregation is disable due to invalid Token
  private final Set<ApplicationId> invalidTokenApps;

  @VisibleForTesting
  ExecutorService threadPool;

  public LogAggregationService(Dispatcher dispatcher, Context context,
      DeletionService deletionService, LocalDirsHandlerService dirsHandler) {
    super(LogAggregationService.class.getName());
    this.dispatcher = dispatcher;
    this.context = context;
    this.deletionService = deletionService;
    this.dirsHandler = dirsHandler;
    this.appLogAggregators =
        new ConcurrentHashMap<ApplicationId, AppLogAggregator>();
    this.invalidTokenApps = ConcurrentHashMap.newKeySet();
  }

  private static long calculateRollingMonitorInterval(Configuration conf) {
    long interval = conf.getLong(
        YarnConfiguration.NM_LOG_AGGREGATION_ROLL_MONITORING_INTERVAL_SECONDS,
        YarnConfiguration.
            DEFAULT_NM_LOG_AGGREGATION_ROLL_MONITORING_INTERVAL_SECONDS);

    if (interval <= 0) {
      LOG.info("rollingMonitorInterval is set as " + interval
          + ". The log rolling monitoring interval is disabled. "
          + "The logs will be aggregated after this application is finished.");
    } else {
      boolean logAggregationDebugMode =
          conf.getBoolean(NM_LOG_AGGREGATION_DEBUG_ENABLED, false);
      long minRollingMonitorInterval = conf.getLong(
          YarnConfiguration.MIN_LOG_ROLLING_INTERVAL_SECONDS,
          YarnConfiguration.MIN_LOG_ROLLING_INTERVAL_SECONDS_DEFAULT);

      boolean warnHardMinLimitLowerThanDefault = minRollingMonitorInterval <
          YarnConfiguration.MIN_LOG_ROLLING_INTERVAL_SECONDS_DEFAULT &&
          !logAggregationDebugMode;
      if (warnHardMinLimitLowerThanDefault) {
        LOG.warn("{} has been set to {}, which is less than the default "
            + "minimum value {}. This may impact NodeManager's performance.",
            YarnConfiguration.MIN_LOG_ROLLING_INTERVAL_SECONDS,
            minRollingMonitorInterval,
            YarnConfiguration.MIN_LOG_ROLLING_INTERVAL_SECONDS_DEFAULT);
      }
      boolean lowerThanHardLimit = interval < minRollingMonitorInterval;
      if (lowerThanHardLimit) {
        if (logAggregationDebugMode) {
          LOG.info("Log aggregation debug mode enabled. " +
              "Skipped checking minimum limit.");
        } else {
          LOG.warn("rollingMonitorInterval should be more than " +
              "or equal to {} seconds. Using {} seconds instead.",
              minRollingMonitorInterval, minRollingMonitorInterval);
          interval = minRollingMonitorInterval;
        }
      }
    }
    return interval;
  }

  protected void serviceInit(Configuration conf) throws Exception {
    int threadPoolSize = getAggregatorThreadPoolSize(conf);
    this.threadPool = HadoopExecutors.newFixedThreadPool(threadPoolSize,
        new ThreadFactoryBuilder()
            .setNameFormat("LogAggregationService #%d")
            .build());

    rollingMonitorInterval = calculateRollingMonitorInterval(conf);
    LOG.info("rollingMonitorInterval is set as {}. The logs will be " +
        "aggregated every {} seconds", rollingMonitorInterval,
        rollingMonitorInterval);

    super.serviceInit(conf);
  }

  @Override
  protected void serviceStart() throws Exception {
    // NodeId is only available during start, the following cannot be moved
    // anywhere else.
    this.nodeId = this.context.getNodeId();
    super.serviceStart();
  }

  @Override
  protected void serviceStop() throws Exception {
    LOG.info(this.getName() + " waiting for pending aggregation during exit");
    stopAggregators();
    super.serviceStop();
  }

  private void stopAggregators() {
    threadPool.shutdown();
    boolean supervised = getConfig().getBoolean(
        YarnConfiguration.NM_RECOVERY_SUPERVISED,
        YarnConfiguration.DEFAULT_NM_RECOVERY_SUPERVISED);
    // if recovery on restart is supported then leave outstanding aggregations
    // to the next restart
    boolean shouldAbort = context.getNMStateStore().canRecover()
        && !context.getDecommissioned() && supervised;
    // politely ask to finish
    for (AppLogAggregator aggregator : appLogAggregators.values()) {
      if (shouldAbort) {
        aggregator.abortLogAggregation();
      } else {
        aggregator.finishLogAggregation();
      }
    }
    while (!threadPool.isTerminated()) { // wait for all threads to finish
      for (ApplicationId appId : appLogAggregators.keySet()) {
        LOG.info("Waiting for aggregation to complete for " + appId);
      }
      try {
        if (!threadPool.awaitTermination(30, TimeUnit.SECONDS)) {
          threadPool.shutdownNow(); // send interrupt to hurry them along
        }
      } catch (InterruptedException e) {
        LOG.warn("Aggregation stop interrupted!");
        break;
      }
    }
    for (ApplicationId appId : appLogAggregators.keySet()) {
      LOG.warn("Some logs may not have been aggregated for " + appId);
    }
  }

  @SuppressWarnings("unchecked")
  private void initApp(final ApplicationId appId, String user,
      Credentials credentials, Map<ApplicationAccessType, String> appAcls,
      LogAggregationContext logAggregationContext,
      long recoveredLogInitedTime) {
    ApplicationEvent eventResponse;
    try {
      initAppAggregator(appId, user, credentials, appAcls,
          logAggregationContext, recoveredLogInitedTime);
      eventResponse = new ApplicationEvent(appId,
          ApplicationEventType.APPLICATION_LOG_HANDLING_INITED);
    } catch (YarnRuntimeException e) {
      LOG.warn("Application failed to init aggregation", e);
      eventResponse = new ApplicationEvent(appId,
          ApplicationEventType.APPLICATION_LOG_HANDLING_FAILED);
    }
    this.dispatcher.getEventHandler().handle(eventResponse);
  }

  FileContext getLocalFileContext(Configuration conf) {
    try {
      return FileContext.getLocalFSFileContext(conf);
    } catch (IOException e) {
      throw new YarnRuntimeException("Failed to access local fs");
    }
  }

  protected void initAppAggregator(final ApplicationId appId, String user,
      Credentials credentials, Map<ApplicationAccessType, String> appAcls,
      LogAggregationContext logAggregationContext,
      long recoveredLogInitedTime) {

    // Get user's FileSystem credentials
    final UserGroupInformation userUgi =
        UserGroupInformation.createRemoteUser(user);
    if (credentials != null) {
      userUgi.addCredentials(credentials);
    }

    LogAggregationFileController logAggregationFileController =
        getLogAggregationFileController(getConfig());
    logAggregationFileController.verifyAndCreateRemoteLogDir();
    // New application
    final AppLogAggregator appLogAggregator =
        new AppLogAggregatorImpl(this.dispatcher, this.deletionService,
            getConfig(), appId, userUgi, this.nodeId, dirsHandler,
            logAggregationFileController.getRemoteNodeLogFileForApp(appId,
            user, nodeId), appAcls, logAggregationContext, this.context,
            getLocalFileContext(getConfig()), this.rollingMonitorInterval,
            recoveredLogInitedTime, logAggregationFileController);
    if (this.appLogAggregators.putIfAbsent(appId, appLogAggregator) != null) {
      throw new YarnRuntimeException("Duplicate initApp for " + appId);
    }
    // wait until check for existing aggregator to create dirs
    YarnRuntimeException appDirException = null;
    try {
      // Create the app dir
      logAggregationFileController.createAppDir(user, appId, userUgi);
    } catch (Exception e) {
      appLogAggregator.disableLogAggregation();

      // add to disabled aggregators if due to InvalidToken
      if (e.getCause() instanceof SecretManager.InvalidToken) {
        invalidTokenApps.add(appId);
      }
      if (!(e instanceof YarnRuntimeException)) {
        appDirException = new YarnRuntimeException(e);
      } else {
        appDirException = (YarnRuntimeException)e;
      }
    }

    // TODO Get the user configuration for the list of containers that need log
    // aggregation.

    // Schedule the aggregator.
    Runnable aggregatorWrapper = new Runnable() {
      public void run() {
        try {
          appLogAggregator.run();
        } finally {
          appLogAggregators.remove(appId);
          closeFileSystems(userUgi);
        }
      }
    };
    this.threadPool.execute(aggregatorWrapper);

    if (appDirException != null) {
      throw appDirException;
    }
  }

  protected void closeFileSystems(final UserGroupInformation userUgi) {
    try {
      FileSystem.closeAllForUGI(userUgi);
    } catch (IOException e) {
      LOG.warn("Failed to close filesystems: ", e);
    }
  }

  // for testing only
  @Private
  int getNumAggregators() {
    return this.appLogAggregators.size();
  }

  private void stopContainer(ContainerId containerId,
      ContainerType containerType, int exitCode) {

    // A container is complete. Put this containers' logs up for aggregation if
    // this containers' logs are needed.
    AppLogAggregator aggregator = this.appLogAggregators.get(
        containerId.getApplicationAttemptId().getApplicationId());
    if (aggregator == null) {
      LOG.warn("Log aggregation is not initialized for " + containerId
          + ", did it fail to start?");
      return;
    }
    aggregator.startContainerLogAggregation(
        new ContainerLogContext(containerId, containerType, exitCode));
  }

  @SuppressWarnings("unchecked")
  private void stopApp(ApplicationId appId) {

    // App is complete. Finish up any containers' pending log aggregation and
    // close the application specific logFile.
    try {
      AppLogAggregator aggregator = this.appLogAggregators.get(appId);
      if (aggregator == null) {
        LOG.warn("Log aggregation is not initialized for " + appId
            + ", did it fail to start?");
        this.dispatcher.getEventHandler().handle(new ApplicationEvent(appId,
            ApplicationEventType.APPLICATION_LOG_HANDLING_FAILED));
        return;
      }
      aggregator.finishLogAggregation();
    } finally {
      // Remove invalid Token Apps
      invalidTokenApps.remove(appId);
    }
  }

  @Override
  public void handle(LogHandlerEvent event) {
    switch (event.getType()) {
      case APPLICATION_STARTED:
        LogHandlerAppStartedEvent appStartEvent =
            (LogHandlerAppStartedEvent) event;
        initApp(appStartEvent.getApplicationId(), appStartEvent.getUser(),
            appStartEvent.getCredentials(),
            appStartEvent.getApplicationAcls(),
            appStartEvent.getLogAggregationContext(),
            appStartEvent.getRecoveredAppLogInitedTime());
        break;
      case CONTAINER_FINISHED:
        LogHandlerContainerFinishedEvent containerFinishEvent =
            (LogHandlerContainerFinishedEvent) event;
        stopContainer(containerFinishEvent.getContainerId(),
            containerFinishEvent.getContainerType(),
            containerFinishEvent.getExitCode());
        break;
      case APPLICATION_FINISHED:
        LogHandlerAppFinishedEvent appFinishedEvent =
            (LogHandlerAppFinishedEvent) event;
        stopApp(appFinishedEvent.getApplicationId());
        break;
      case LOG_AGG_TOKEN_UPDATE:
        checkAndEnableAppAggregators();
        break;
      default:
        ; // Ignore
    }

  }

  private void checkAndEnableAppAggregators() {
    for (ApplicationId appId : invalidTokenApps) {
      try {
        AppLogAggregator aggregator = appLogAggregators.get(appId);
        if (aggregator != null) {
          Credentials credentials =
              context.getSystemCredentialsForApps().get(appId);
          if (credentials != null) {
            // Create the app dir again with
            LogAggregationFileController logAggregationFileController =
                getLogAggregationFileController(getConfig());
            UserGroupInformation userUgi =
                aggregator.updateCredentials(credentials);
            logAggregationFileController
                .createAppDir(userUgi.getShortUserName(), appId, userUgi);
            aggregator.enableLogAggregation();
          }
          invalidTokenApps.remove(appId);
          LOG.info("LogAggregation enabled for application {}", appId);
        }
      } catch (Exception e) {
        //Ignore exception
        LOG.warn("Enable aggregators failed {}", appId);
      }
    }
  }

  @Override
  public Set<ApplicationId> getInvalidTokenApps() {
    return invalidTokenApps;
  }

  @VisibleForTesting
  public ConcurrentMap<ApplicationId, AppLogAggregator> getAppLogAggregators() {
    return this.appLogAggregators;
  }

  @VisibleForTesting
  public NodeId getNodeId() {
    return this.nodeId;
  }

  @VisibleForTesting
  public long getRollingMonitorInterval() {
    return rollingMonitorInterval;
  }

  private int getAggregatorThreadPoolSize(Configuration conf) {
    int threadPoolSize;
    try {
      threadPoolSize = conf.getInt(YarnConfiguration
          .NM_LOG_AGGREGATION_THREAD_POOL_SIZE,
          YarnConfiguration.DEFAULT_NM_LOG_AGGREGATION_THREAD_POOL_SIZE);
    } catch (NumberFormatException ex) {
      LOG.warn("Invalid thread pool size. Setting it to the default value " +
          "in YarnConfiguration");
      threadPoolSize = YarnConfiguration.
          DEFAULT_NM_LOG_AGGREGATION_THREAD_POOL_SIZE;
    }
    if(threadPoolSize <= 0) {
      LOG.warn("Invalid thread pool size. Setting it to the default value " +
          "in YarnConfiguration");
      threadPoolSize = YarnConfiguration.
          DEFAULT_NM_LOG_AGGREGATION_THREAD_POOL_SIZE;
    }
    return threadPoolSize;
  }

  @VisibleForTesting
  public LogAggregationFileController getLogAggregationFileController(
      Configuration conf) {
    LogAggregationFileControllerFactory factory
        = new LogAggregationFileControllerFactory(conf);
    LogAggregationFileController logAggregationFileController = factory
        .getFileControllerForWrite();
    return logAggregationFileController;
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

class Google_Service_PubsubLite_DeliveryConfig extends Google_Model
{
  public $deliveryRequirement;

  public function setDeliveryRequirement($deliveryRequirement)
  {
    $this->deliveryRequirement = $deliveryRequirement;
  }
  public function getDeliveryRequirement()
  {
    return $this->deliveryRequirement;
  }
}


text:
package org.realityforge.gwt.appcache.server.mgwt;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import org.realityforge.gwt.appcache.server.BindingProperty;
import org.realityforge.gwt.appcache.server.propertyprovider.PropertyProvider;

public final class MgwtOsPropertyProvider
  implements PropertyProvider
{
  static final BindingProperty iPhone = new BindingProperty( "mgwt.os", "iphone" );
  static final BindingProperty retina = new BindingProperty( "mgwt.os", "retina" );
  static final BindingProperty iPhone_undefined = new BindingProperty( "mgwt.os", "iphone_undefined" );

  static final BindingProperty iPad = new BindingProperty( "mgwt.os", "ipad" );
  static final BindingProperty iPad_retina = new BindingProperty( "mgwt.os", "ipad_retina" );
  static final BindingProperty iPad_undefined = new BindingProperty( "mgwt.os", "ipad_undefined" );

  @Nonnull
  @Override
  public String getPropertyName()
  {
    return "mgwt.os";
  }

  @Override
  @Nullable
  public String getPropertyValue( @Nonnull HttpServletRequest request )
  {
    final String userAgent = request.getHeader( "User-Agent" ).toLowerCase();

    if ( userAgent.contains( "android" ) )
    {
      if ( userAgent.contains( "mobile" ) )
      {
        return "android";
      }
      else
      {
        return "android_tablet";
      }
    }
    else if ( userAgent.contains( "ipad" ) )
    {
      final String value = getRetinaCookieValue( request );
      if ( "0".equals( value ) )
      {
        return "ipad";
      }
      else if ( "1".equals( value ) )
      {
        return "ipad_retina";
      }
      else
      {
        return "ipad_undefined";
      }
    }
    else if ( userAgent.contains( "iphone" ) )
    {
      final String value = getRetinaCookieValue( request );
      if ( "0".equals( value ) )
      {
        return "iphone";
      }
      else if ( "1".equals( value ) )
      {
        return "retina";
      }
      else
      {
        return "iphone_undefined";
      }
    }
    else if ( userAgent.contains( "blackberry" ) )
    {
      return "blackberry";
    }
    else
    {
      return "desktop";
    }
  }

  final String getRetinaCookieValue( final HttpServletRequest request )
  {
    final Cookie[] cookies = request.getCookies();
    if ( null != cookies )
    {
      for ( final Cookie cookie : cookies )
      {
        if ( "mgwt_ios_retina".equals( cookie.getName() ) )
        {
          return cookie.getValue();
        }
      }
    }
    return null;
  }
}


text:
/**
 * \file dinucleotide_machine.hpp
 *
 * Defines a nondeterministic finite automaton over dinucleotides
 *
 */
#ifndef VG_DINUCLEOTIDE_MACHINE_GRAPH_HPP_INCLUDED
#define VG_DINUCLEOTIDE_MACHINE_GRAPH_HPP_INCLUDED

#include <string>
#include <limits>
#include <cstdint>
#include <iostream>

namespace vg {

using namespace std;

/*
 * Represents a non-deterministic finite automaton whose states
 * correspond to dinucleotides
 */
class DinucleotideMachine {
public:
    DinucleotideMachine();
    ~DinucleotideMachine() = default;

    /// Return an empty dinucleotide set
    uint32_t init_state() const;

    /// Get the dinucleotide set that results from extending the set by the given character
    /// Ns are valid, but will result in no matches
    uint32_t update_state(uint32_t state, char next) const;

    /// Get the union of two dinucleotide sets
    uint32_t merge_state(uint32_t state_1, uint32_t state_2) const;

    /// Return true if the set includes this dinucleotide. Only valid for dinucleotides of ACGT (never N).
    bool matches(uint32_t state, const char* dinucleotide) const;

    /// Same semantics as above
    bool matches(uint32_t state, const string& dinucleotide) const;

private:

    // lookup table for transitions
    uint32_t transition_table[256];
    // ASCII-indexed conversion from char to table index
    uint32_t nt_table[256];
};

}

#endif


text:
        // * accepts bets - integer
        // * based on matches, returns money

        // GUN STORE: players can exchange winnings for guns

// Pseudocode
// 3 cowboy players are established each with their own purse and guns
//
//
//
//

// Initial Code
//
//

var diamondJim = {
  moneyCount: 1547.5,
  age: 47,
  heat: "Colt",
  bet: 15,
};

var virgil = {
  moneyCount: 76.89,
  age: 38,
  heat: "Lonestar",
  bet: 10,
};

var marcoVegas = {
  moneyCount: 89.27,
  age: 33,
  heat: "Remington",
  bet: 20,
};

// console.log(diamondJim.bet)
//
// function throwdown(player) {
//   var player = player;
//   var bet = player.bet;
//   var winnings = null;
var num1 = null;
var num2 = null;
var num3 = null;
var win = 0

  function lucky7s(bet) {

  var player = player;

  var bet = bet;
  var win = 0;
  // setTimeout(lucky7s, 3000);
  console.log("The lever has been pulled...")

              function number1() {
                  var x = Math.floor((Math.random() * 10) + 1);
                return x;

              };
              // setTimeout(number1, 3000);
              num1 = number1();
              // console.log(num1);
               console.log('The first number is ' + num1);

            function number2() {
                  var y = Math.floor((Math.random() * 10) + 1);
                 return y;
              };
              // setTimeout(number2, 3000);
              num2 = number2();
              // console.log(num2);
              console.log('The second number is ' + num2);

              function number3() {
                  var z = Math.floor((Math.random() * 10) + 1);
                  return z;
              };
            // setTimeout(number3, 3000);
              num3 = number3();
               console.log('The third number is ' + num3);

    // console.log('*************');
    //   console.log(num1);
    //   console.log(num2);
    //   console.log(num3);
              //sevens

              if  (num1==7 && num2==7 && num3==7)
              {
                    win = (bet * 1000);
                    return win;
              }

               //  3s
              if (num1==num2 && num1==num3 && num2==num3)
              {
                    win = (bet * 100);
                    return win;
              }

               // 2s
              if (num1==num2 || num1==num3 || num2==num3)
              {

                      if (num1==7 && num2==7){
                        win = (bet * 10);
                        return win;
                      }
                      else if (num2==7 && num3==7){
                        win = (bet * 10);
                        return win;
                      }
                     else if (num1==7 && num3==7){
                        win = (bet * 10);
                        return win;
                      }
                    else
                      {
                        win = (bet * 5);
                        return win;
                      }
                }
              else {
                win = (bet * 0)
                return win;
              }

// console.log(number1 + number2 + number3)

 };

//   winnings =
//   return winnings;

// console.log(throwdown(diamondJim))
// console.log('####################');
// console.log(num1 + num2 + num3)

console.log("The player wins $" + lucky7s(diamondJim.bet))

// win = lucky7s(diamondJim.bet))
//
// pickUp (diamondJim, win)

// Reflection
//
//
//
//
//
//
//

// Refactored Code

// Reflection
//
//What was the most difficult part of this challenge?
// * conditional looping syntax with Javascript after weeks of ruby worksWhat did you learn about creating objects and functions that interact with one another?
//
// Did you learn about any new built-in methods you could use in your refactored solution? If so, what were they and how do they work?
// * i did not - i spent most of my time trying to effectively loop each PLAYER through the slot machine itself and return their winnings to the purse
// for future bets.  I would be interested in some feedback as to how to do this effectively.  I would like each player to bet continual PERCENTAGES of their purse
// and have winnings or losings automatically update their moneyCount stashes - how might I go about delivering this result and / or looping
// each player through the slot machine game 100x or until they lose all of their money?d

// How can you access and manipulate properties of objects?
// accessing was east - i called the entire game with the 'bet' value of each player.  HOWEVER i was unable to effectively manitpulate
// the property values IE: the purse of each player with their winnings.

// ***** I REALLY WANT TO FIGURE THIS OUT:  ultimately, beyond a simple slot machine game I'd like to design an algorithm of sorts that determines
//  the the success of 3 different betting strategies: aggressive, moderate, and conservative.  To do this i need the nested functions within Lucky7s
// to amend each character's moneyCount property with the winnings for a successful or advantagious invocation of the slot machine.
//
//
//
//
//


text:
using System;
using System.CodeDom;
using System.IO;
using Xunit;

namespace System.Management.Tests
{
    public class ManagementClassTests
    {
        [ConditionalTheory(typeof(WmiTestHelper), nameof(WmiTestHelper.IsWmiSupported))]
        [InlineData(false, false)]
        [InlineData(false, true)]
        [InlineData(true, false)]
        [InlineData(true, true)]
        public void Get_CodeTypeDeclaration_For_Win32_LogicalDisk(bool includeSystemClassInClassDef, bool systemPropertyClass)
        {
            using (var managementClass = new ManagementClass(null, "Win32_LogicalDisk", null))
            {
                CodeTypeDeclaration classDom = managementClass.GetStronglyTypedClassCode(includeSystemClassInClassDef, systemPropertyClass);
                Assert.Equal(systemPropertyClass ? "ManagementSystemProperties" : "LogicalDisk", classDom.Name);
            }
        }

        [ConditionalTheory(typeof(WmiTestHelper), nameof(WmiTestHelper.IsWmiSupported))]
        [InlineData(CodeLanguage.CSharp)]
        [InlineData(CodeLanguage.VB)]
        public void Get_SourceFile_For_Win32_Processor(CodeLanguage lang)
        {
            var tempFilePath = Path.GetTempFileName();
            var passed = false;
            try
            {
                using (var managementClass = new ManagementClass(null, "Win32_Processor", null))
                    Assert.True(managementClass.GetStronglyTypedClassCode(lang, tempFilePath, "Wmi.Test.CoreFx"));

                passed = true;
            }
            finally
            {
                if (passed && tempFilePath != null)
                    File.Delete(tempFilePath);
            }
        }

        [ConditionalTheory(typeof(WmiTestHelper), nameof(WmiTestHelper.IsWmiSupported))]
        [InlineData(CodeLanguage.JScript)]
        [InlineData(CodeLanguage.Mcpp)]
        [InlineData(CodeLanguage.VJSharp)]
        public void Throw_On_Unsupported_Languages(CodeLanguage lang)
        {
            // On full framework JScript is supported and no exception raised
            if (lang == CodeLanguage.JScript && PlatformDetection.IsFullFramework)
                return;

            var tempFilePath = Path.GetTempFileName();
            var managementClass = new ManagementClass(null, "Win32_Processor", null);

            try
            {
                Assert.Throws<ArgumentOutOfRangeException>(() => managementClass.GetStronglyTypedClassCode(lang, tempFilePath, "Wmi.Test.CoreFx"));
            }
            finally
            {
                managementClass = null;
                GC.Collect(2);
                GC.WaitForPendingFinalizers();
                if (tempFilePath != null)
                    File.Delete(tempFilePath);
            }
        }

        [ConditionalFact(typeof(WmiTestHelper), nameof(WmiTestHelper.IsWmiSupported))]
        public void ClassMembers_For_Win32_LogicalDisk()
        {
            var managementClass = new ManagementClass(new ManagementPath("Win32_LogicalDisk"));

            MethodDataCollection methods = managementClass.Methods;
            Assert.True(methods.Count > 0);
            foreach (MethodData method in methods)
                Assert.False(string.IsNullOrWhiteSpace(method.Name));

            PropertyDataCollection properties = managementClass.Properties;
            Assert.True(properties.Count > 0);
            foreach (PropertyData property in properties)
                Assert.False(string.IsNullOrWhiteSpace(property.Name));

            QualifierDataCollection qualifiers = managementClass.Qualifiers;
            foreach (QualifierData qualifier in qualifiers)
                Assert.False(string.IsNullOrWhiteSpace(qualifier.Name));
        }

        [ConditionalFact(typeof(WmiTestHelper), nameof(WmiTestHelper.IsWmiSupported))]
        public void EnumerateInstances_For_Win32_LogicalDisk()
        {
            using (var managementClass = new ManagementClass(new ManagementPath("Win32_LogicalDisk")))
            using (ManagementObjectCollection instances = managementClass.GetInstances())
            using (ManagementObjectCollection.ManagementObjectEnumerator instancesEnumerator = instances.GetEnumerator())
            {
                while (instancesEnumerator.MoveNext())
                {
                    ManagementObject instance = (ManagementObject)instancesEnumerator.Current;
                    Assert.NotNull(instance);
                    var clone = instance.Clone();
                    Assert.NotNull(clone);
                    Assert.False(ReferenceEquals(instance, clone));
                }
            }
        }

        [ConditionalFact(typeof(WmiTestHelper), nameof(WmiTestHelper.IsElevatedAndSupportsWmi))]
        public void Create_Delete_Namespace()
        {
            using (var rootNamespace = new ManagementClass("root:__namespace"))
            using (ManagementObject newNamespace = rootNamespace.CreateInstance())
            {
                const string NewNamespace = "CoreFx_Create_Delete_Namespace_Test";
                newNamespace["Name"] = NewNamespace;
                newNamespace.Put();

                ManagementObject targetNamespace = new ManagementObject($"root:__namespace.Name='{NewNamespace}'");
                Assert.Equal(NewNamespace, targetNamespace["Name"]);

                // If any of the steps below fail it is likely that the new namespace was not deleted, likely it will have to
                // be deleted via a tool like wbemtest.
                targetNamespace.Delete();
                ManagementException managementException = Assert.Throws<ManagementException>(() => targetNamespace.Get());
                Assert.Equal(ManagementStatus.NotFound, managementException.ErrorCode);
            }
        }
    }
}


text:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace Formall.Persistence
{
    using Formall.Navigation;
    using Formall.Reflection;
    using Raven.Abstractions.Data;
    using Raven.Abstractions.Linq;
    using Raven.Client;
    using Raven.Client.Document;
    using Raven.Client.Embedded;
    using Raven.Client.Indexes;
    using Raven.Imports.Newtonsoft.Json;
    using Raven.Imports.Newtonsoft.Json.Serialization;
    using Raven.Json.Linq;

    public class RavenDocumentContext : IDataContext
    {
        private readonly object _lock = new object();

        private readonly DocumentStoreConfig _config;
        private readonly string _name;
        private DocumentStoreBase _store;
        private readonly Schema _schema;
        private readonly string _host;
        private readonly ConcurrentDictionary<string, Repository> _repositories;

        private RavenDocumentContext(Schema schema, string host)
        {
            _schema = schema;
            _host = host;
            _repositories = new ConcurrentDictionary<string, Repository>();
        }

        public RavenDocumentContext(string name, string host, Schema schema)
            : this(schema, host)
        {
            _name = name;

            var segment = schema.Query(name, host);

            if (segment == null)
            {
                // log error
            }
            else
            {
                var entity = segment as IEntity;

                if (entity == null)
                {
                    // log error
                }
                else
                {
                    _config = entity.Get<DocumentStoreConfig>();
                }
            }
        }

        public RavenDocumentContext(string host, Schema schema, object config)
            : this(schema, host)
        {
            var serializer = new JsonSerializer
            {
                DateParseHandling = DateParseHandling.None,
                ContractResolver = new DefaultContractResolver()
            };

            _config = (DocumentStoreConfig)serializer.Deserialize(new RavenJTokenReader(RavenJObject.FromObject(config)), typeof(DocumentStoreConfig));
            _name = _config.Name;
        }

        internal protected IDocumentStore DocumentStore
        {
            get
            {
                var store = _store;

                if (store == null)
                {
                    //
                    // lock and check again

                    lock (_lock)
                    {
                        store = _store;

                        if (store == null)
                        {
                            if (_config == null)
                            {
                                // error already logged
                            }
                            else try
                                {
                                    //
                                    // create new instance if doesn't exist

                                    var apiKey = _config.ApiKey + '/' + _config.Secret;

                                    if (_config.Embeddable)
                                    {
                                        store = new EmbeddableDocumentStore
                                        {
                                            //ApiKey = apiKey,
                                            //ConnectionStringName = _config.Name,
                                            DataDirectory = _config.DataDirectory
                                        };
                                    }
                                    else
                                    {
                                        store = new DocumentStore
                                        {
                                            //ApiKey = apiKey,
                                            //ConnectionStringName = _config.Name,
                                            Url = _config.Url
                                        };
                                    }

                                    if (store != null)
                                    {
                                        //
                                        // define store conventions

                                        //store.Conventions.IdentityPartsSeparator = "/";
                                        store.Conventions.SaveEnumsAsIntegers = false;

                                        //
                                        // initialize store instance

                                        store.Initialize();

                                        //
                                        // create index by entity name

                                        new RavenDocumentsByEntityName().Execute(store);
                                    }
                                }
                                catch (Exception)
                                {
                                    // log exception
                                }
                                finally
                                {
                                    // save store instance
                                    _store = store;
                                }
                        }
                    }
                }

                return store;
            }
        }

        IRepository IDataContext.CreateRepository(string name)
        {
            return this.Repository(name);
        }

        internal Entity Import(RavenJObject data, Metadata metadata)
        {
            Guid id;
            var key = metadata.Key;
            var type = key.Exclude(1, '/');

            Guid.TryParse(key.Split('/').Last(), out id);

            var entity = new Entity(id, data, metadata.FromMetadata(), Repository(type));

            return Store(entity);
        }

        internal Entity Import(IDocument document)
        {
            RavenJObject data;

            var serializer = new JsonSerializer
            {
                DateParseHandling = DateParseHandling.None,
                ContractResolver = new DefaultContractResolver()
            };

            using (var reader = new StreamReader(document.Content))
            {
                data = RavenJObject.Load(new JsonTextReader(reader));
            }

            return Import(data, document.Metadata);
        }

        IEntity IDataContext.Import(IEntity entity)
        {
            return Store(Import(entity));
        }

        private Entity Store(Entity entity)
        {
            var result = DocumentStore.DatabaseCommands.Put(entity.Key, null, entity.Data, entity.Metadata);

            /*return new SuccessResult
            {
                Data = new { Key = result.Key, Etag = result.ETag }
            };*/

            return entity;
        }

        #region - IDocumentContext -

        public IResult Delete(string key)
        {
            DocumentStore.DatabaseCommands.Delete(key, null);
            return null;
        }

        public IDocument Import(Stream stream, MediaType type, Metadata metadata)
        {
            IDocument document;

            using (var reader = new StreamReader(stream))
            {
                document = Import(reader, type, metadata);
            }

            return document;
        }

        public IDocument Import(TextReader reader, MediaType type, Metadata metadata)
        {
            RavenJObject data;

            if (type == MediaType.Json)
            {
                data = RavenJObject.Load(new JsonTextReader(reader));
            }
            else
            {
                // TODO: support import of other content types like XML
                throw new NotImplementedException("RavenDocumentContext doesnt support importing other content type than JSON.");
            }

            return Import(data, metadata);
        }

        IDocument IDocumentContext.Import(IDocument document)
        {
            return Import(document);
        }

        public IDocument[] Read(int skip, int take)
        {
            var documents = DocumentStore.DatabaseCommands.GetDocuments(skip, take);

            return documents.Select(o => new Entity(Entity.ParseId(o.Key), o.DataAsJson, o.Metadata, Repository(o.Metadata.Value<string>("Raven-Entity-Name")))).OfType<IDocument>().ToArray();
        }

        public IDocument Read(string key)
        {
            Entity entity = null;

            var document = DocumentStore.DatabaseCommands.Get(key);

            if (document != null)
            {
                var data = document.DataAsJson;
                var metadata = document.Metadata;
                entity = new Entity(Entity.ParseId(key), data, metadata, Repository(metadata.Value<string>("Raven-Entity-Name")));
            }

            return entity;
        }

        public IDocument[] Read(string keyPrefix, int skip, int take)
        {
            var documents = DocumentStore.DatabaseCommands.StartsWith(keyPrefix, null, skip, take);

            return documents.Select(o => new Entity(Entity.ParseId(o.Key), o.DataAsJson, o.Metadata, Repository(o.Metadata.Value<string>("Raven-Entity-Name")))).OfType<IDocument>().ToArray();
        }

        internal Repository Repository(string name)
        {
            var keyPrefix = name + '/';

            Repository repository;

            if (!_repositories.TryGetValue(name, out repository))
            {
                var segment = _schema.Query(name, _host).FirstOrDefault();

                //string keyPrefix = null;
                Model model = null;

                if (segment != null)
                {
                    var entity = segment as Entity<Model>;
                    if (entity != null)
                    {
                        model = (Model)entity;

                        //keyPrefix = model.Name + '/';

                        /*for (var baseType = model.BaseType; baseType != null; )
                        {
                            segment = segment.Parent;
                            if (segment != null)
                            {
                                entity = segment as Entity<Model>;
                                var baseModel = (Model)entity;
                                //keyPrefix = baseModel.Name + '/' + keyPrefix;
                            }

                        }*/
                    }
                }

                repository = _repositories.AddOrUpdate(name, new Repository(keyPrefix, model, this), (key, previous) =>
                {
                    // log info to track worst cases
                    return previous;
                });
            }

            return repository;
        }

        #endregion - IDocumentContext -
    }
}


text:
namespace Google.Cloud.SecurityCenter.V1.Snippets
{
    // [START securitycenter_v1_generated_SecurityCenter_SetFindingState_async]
    using Google.Cloud.SecurityCenter.V1;
    using Google.Protobuf.WellKnownTypes;
    using System.Threading.Tasks;

    public sealed partial class GeneratedSecurityCenterClientSnippets
    {
        /// <summary>Snippet for SetFindingStateAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task SetFindingStateRequestObjectAsync()
        {
            // Create client
            SecurityCenterClient securityCenterClient = await SecurityCenterClient.CreateAsync();
            // Initialize request argument(s)
            SetFindingStateRequest request = new SetFindingStateRequest
            {
                FindingName = FindingName.FromOrganizationSourceFinding("[ORGANIZATION]", "[SOURCE]", "[FINDING]"),
                State = Finding.Types.State.Unspecified,
                StartTime = new Timestamp(),
            };
            // Make the request
            Finding response = await securityCenterClient.SetFindingStateAsync(request);
        }
    }
    // [END securitycenter_v1_generated_SecurityCenter_SetFindingState_async]
}


text:
/////////////////////////////////////////////////////////////////////////////
// Name:        src/msw/mediactrl_qt.cpp
// Purpose:     QuickTime Media Backend for Windows
// Author:      Ryan Norton <wxprojects@comcast.net>
// Modified by: Robin Dunn (moved QT code from mediactrl.cpp)
//
// Created:     11/07/04
// RCS-ID:      $Id: mediactrl_qt.cpp 45498 2007-04-16 13:03:05Z VZ $
// Copyright:   (c) Ryan Norton
// Licence:     wxWindows licence
/////////////////////////////////////////////////////////////////////////////

//===========================================================================
//  DECLARATIONS
//===========================================================================

//---------------------------------------------------------------------------
// Pre-compiled header stuff
//---------------------------------------------------------------------------

// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"

#ifdef __BORLANDC__
    #pragma hdrstop
#endif

#if wxUSE_MEDIACTRL

#include "wx/mediactrl.h"

#ifndef WX_PRECOMP
    #include "wx/log.h"
    #include "wx/dcclient.h"
    #include "wx/timer.h"
    #include "wx/math.h"        // log10 & pow
#endif

#include "wx/msw/private.h" // user info and wndproc setting/getting
#include "wx/dynlib.h"

//---------------------------------------------------------------------------
// Externals (somewhere in src/msw/app.cpp and src/msw/window.cpp)
//---------------------------------------------------------------------------
extern "C" WXDLLIMPEXP_BASE HINSTANCE wxGetInstance(void);
#ifdef __WXWINCE__
extern WXDLLIMPEXP_CORE       wxChar *wxCanvasClassName;
#else
extern WXDLLIMPEXP_CORE const wxChar *wxCanvasClassName;
#endif

LRESULT WXDLLIMPEXP_CORE APIENTRY _EXPORT wxWndProc(HWND hWnd, UINT message,
                                   WPARAM wParam, LPARAM lParam);

//---------------------------------------------------------------------------
// Killed MSVC warnings
//---------------------------------------------------------------------------
//disable "cast truncates constant value" for VARIANT_BOOL values
//passed as parameters in VC5 and up
#ifdef _MSC_VER
#pragma warning (disable:4310)
#endif

//---------------------------------------------------------------------------
//  wxQTMediaBackend
//
// We don't include Quicktime headers here and define all the types
// ourselves because looking for the quicktime libaries etc. would
// be tricky to do and making this a dependency for the MSVC projects
// would be unrealistic.
//
// Thanks to Robert Roebling for the wxDL macro/library idea
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
//  QT Includes
//---------------------------------------------------------------------------
//#include <qtml.h>                   // Windoze QT include
//#include <QuickTimeComponents.h>    // Standard QT stuff
#include "wx/dynlib.h"

//---------------------------------------------------------------------------
//  QT Types
//---------------------------------------------------------------------------
typedef struct MovieRecord* Movie;
typedef wxInt16 OSErr;
typedef wxInt32 OSStatus;
#define noErr 0
#define fsRdPerm 1
typedef unsigned char                   Str255[256];
#define StringPtr unsigned char*
#define newMovieActive 1
#define newMovieAsyncOK (1 << 8)
#define Ptr char*
#define Handle Ptr*
#define Fixed long
#define OSType unsigned long
#define CGrafPtr struct GrafPort *
#define TimeScale long
#define TimeBase struct TimeBaseRecord *
typedef struct ComponentInstanceRecord * ComponentInstance;
#define kMovieLoadStatePlayable 10000
#define Boolean int
#define MovieController ComponentInstance

#ifndef URLDataHandlerSubType
#if defined(__WATCOMC__) || defined(__MINGW32__)
// use magic numbers for compilers which complain about multicharacter integers
const OSType URLDataHandlerSubType     = 1970433056;
const OSType VisualMediaCharacteristic = 1702454643;
#else
const OSType URLDataHandlerSubType     = 'url ';
const OSType VisualMediaCharacteristic = 'eyes';
#endif
#endif

struct FSSpec
{
    short      vRefNum;
    long       parID;
    Str255     name;  // Str63 on mac, Str255 on msw
};

struct Rect
{
    short      top;
    short      left;
    short      bottom;
    short      right;
};

struct wide
{
    wxInt32    hi;
    wxUint32   lo;
};

struct TimeRecord
{
    wide       value; // units
    TimeScale  scale; // units per second
    TimeBase   base;
};

struct Point
{
    short                           v;
    short                           h;
};

struct EventRecord
{
    wxUint16                       what;
    wxUint32                          message;
    wxUint32                          when;
    Point                           where;
    wxUint16                  modifiers;
};

enum
{
    mcTopLeftMovie              = 1,
    mcScaleMovieToFit           = 2,
    mcWithBadge                 = 4,
    mcNotVisible                = 8,
    mcWithFrame                 = 16
};

//---------------------------------------------------------------------------
//  QT Library
//---------------------------------------------------------------------------
#define wxDL_METHOD_DEFINE( rettype, name, args, shortargs, defret ) \
    typedef rettype (* name ## Type) args ; \
    name ## Type pfn_ ## name; \
    rettype name args \
    { if (m_ok) return pfn_ ## name shortargs ; return defret; }

#define wxDL_VOIDMETHOD_DEFINE( name, args, shortargs ) \
    typedef void (* name ## Type) args ; \
    name ## Type pfn_ ## name; \
    void name args \
    { if (m_ok) pfn_ ## name shortargs ; }

#define wxDL_METHOD_LOAD( lib, name, success ) \
    pfn_ ## name = (name ## Type) lib.GetSymbol( wxT(#name), &success ); \
    if (!success) return false

class WXDLLIMPEXP_MEDIA wxQuickTimeLibrary
{
public:
    ~wxQuickTimeLibrary()
    {
        if (m_dll.IsLoaded())
            m_dll.Unload();
    }

    bool Initialize();
    bool IsOk() const {return m_ok;}

protected:
    wxDynamicLibrary m_dll;
    bool m_ok;

public:
    wxDL_VOIDMETHOD_DEFINE( StartMovie, (Movie m), (m) )
    wxDL_VOIDMETHOD_DEFINE( StopMovie, (Movie m), (m) )
    wxDL_METHOD_DEFINE( bool, IsMovieDone, (Movie m), (m), false)
    wxDL_VOIDMETHOD_DEFINE( GoToBeginningOfMovie, (Movie m), (m) )
    wxDL_METHOD_DEFINE( OSErr, GetMoviesError, (), (), -1)
    wxDL_METHOD_DEFINE( OSErr, EnterMovies, (), (), -1)
    wxDL_VOIDMETHOD_DEFINE( ExitMovies, (), () )
    wxDL_METHOD_DEFINE( OSErr, InitializeQTML, (long flags), (flags), -1)
    wxDL_VOIDMETHOD_DEFINE( TerminateQTML, (), () )

    wxDL_METHOD_DEFINE( OSErr, NativePathNameToFSSpec,
                        (char* inName, FSSpec* outFile, long flags),
                        (inName, outFile, flags), -1)

    wxDL_METHOD_DEFINE( OSErr, OpenMovieFile,
                        (const FSSpec * fileSpec, short * resRefNum, wxInt8 permission),
                        (fileSpec, resRefNum, permission), -1 )

    wxDL_METHOD_DEFINE( OSErr, CloseMovieFile,
                        (short resRefNum), (resRefNum), -1)

    wxDL_METHOD_DEFINE( OSErr, NewMovieFromFile,
                            (Movie * theMovie, short resRefNum, short *  resId,
                             StringPtr resName, short newMovieFlags,
                             bool * dataRefWasChanged),
                             (theMovie, resRefNum, resId, resName, newMovieFlags,
                              dataRefWasChanged), -1)

    wxDL_VOIDMETHOD_DEFINE( SetMovieRate, (Movie m, Fixed rate), (m, rate) )
    wxDL_METHOD_DEFINE( Fixed, GetMovieRate, (Movie m), (m), 0)
    wxDL_VOIDMETHOD_DEFINE( MoviesTask, (Movie m, long maxms), (m, maxms) )
    wxDL_VOIDMETHOD_DEFINE( BlockMove,
        (const char* p1, const char* p2, long s), (p1,p2,s) )
    wxDL_METHOD_DEFINE( Handle, NewHandleClear, (long s), (s), NULL )

    wxDL_METHOD_DEFINE( OSErr, NewMovieFromDataRef,
                           (Movie * m, short flags, short * id,
                            Handle  dataRef, OSType  dataRefType),
                            (m,flags,id,dataRef,dataRefType), -1 )

    wxDL_VOIDMETHOD_DEFINE( DisposeHandle, (Handle h), (h) )
    wxDL_VOIDMETHOD_DEFINE( GetMovieNaturalBoundsRect, (Movie m, Rect* r), (m,r) )
    wxDL_METHOD_DEFINE( void*, GetMovieIndTrackType,
                        (Movie m, long index, OSType type, long flags),
                        (m,index,type,flags), NULL )
    wxDL_VOIDMETHOD_DEFINE( CreatePortAssociation,
            (void* hWnd, void* junk, long morejunk), (hWnd, junk, morejunk) )
    wxDL_METHOD_DEFINE(void*, GetNativeWindowPort, (void* hWnd), (hWnd), NULL)
    wxDL_VOIDMETHOD_DEFINE(SetMovieGWorld, (Movie m, CGrafPtr port, void* whatever),
                            (m, port, whatever) )
    wxDL_VOIDMETHOD_DEFINE(DisposeMovie, (Movie m), (m) )
    wxDL_VOIDMETHOD_DEFINE(SetMovieBox, (Movie m, Rect* r), (m,r))
    wxDL_VOIDMETHOD_DEFINE(SetMovieTimeScale, (Movie m, long s), (m,s))
    wxDL_METHOD_DEFINE(long, GetMovieDuration, (Movie m), (m), 0)
    wxDL_METHOD_DEFINE(TimeBase, GetMovieTimeBase, (Movie m), (m), 0)
    wxDL_METHOD_DEFINE(TimeScale, GetMovieTimeScale, (Movie m), (m), 0)
    wxDL_METHOD_DEFINE(long, GetMovieTime, (Movie m, void* cruft), (m,cruft), 0)
    wxDL_VOIDMETHOD_DEFINE(SetMovieTime, (Movie m, TimeRecord* tr), (m,tr) )
    wxDL_METHOD_DEFINE(short, GetMovieVolume, (Movie m), (m), 0)
    wxDL_VOIDMETHOD_DEFINE(SetMovieVolume, (Movie m, short sVolume), (m,sVolume) )
    wxDL_VOIDMETHOD_DEFINE(SetMovieTimeValue, (Movie m, long s), (m,s))
    wxDL_METHOD_DEFINE(ComponentInstance, NewMovieController, (Movie m, const Rect* mr, long fl), (m,mr,fl), 0)
    wxDL_VOIDMETHOD_DEFINE(DisposeMovieController, (ComponentInstance ci), (ci))
    wxDL_METHOD_DEFINE(int, MCSetVisible, (ComponentInstance m, int b), (m, b), 0)

    wxDL_VOIDMETHOD_DEFINE(PrePrerollMovie, (Movie m, long t, Fixed r, WXFARPROC p1, void* p2), (m,t,r,p1,p2) )
    wxDL_VOIDMETHOD_DEFINE(PrerollMovie, (Movie m, long t, Fixed r), (m,t,r) )
    wxDL_METHOD_DEFINE(Fixed, GetMoviePreferredRate, (Movie m), (m), 0)
    wxDL_METHOD_DEFINE(long, GetMovieLoadState, (Movie m), (m), 0)
    wxDL_METHOD_DEFINE(void*, NewRoutineDescriptor, (WXFARPROC f, int l, void* junk), (f, l, junk), 0)
    wxDL_VOIDMETHOD_DEFINE(DisposeRoutineDescriptor, (void* f), (f))
    wxDL_METHOD_DEFINE(void*, GetCurrentArchitecture, (), (), 0)
    wxDL_METHOD_DEFINE(int, MCDoAction, (ComponentInstance ci, long f, void* p), (ci,f,p), 0)
    wxDL_VOIDMETHOD_DEFINE(MCSetControllerBoundsRect, (ComponentInstance ci, Rect* r), (ci,r))
    wxDL_VOIDMETHOD_DEFINE(DestroyPortAssociation, (CGrafPtr g), (g))
    wxDL_VOIDMETHOD_DEFINE(NativeEventToMacEvent, (MSG* p1, EventRecord* p2), (p1,p2))
    wxDL_VOIDMETHOD_DEFINE(MCIsPlayerEvent, (ComponentInstance ci, EventRecord* p2), (ci, p2))
    wxDL_METHOD_DEFINE(int, MCSetMovie, (ComponentInstance ci, Movie m, void* p1, Point w),
                          (ci,m,p1,w),0)
    wxDL_VOIDMETHOD_DEFINE(MCPositionController,
        (ComponentInstance ci, Rect* r, void* junk, void* morejunk), (ci,r,junk,morejunk))
    wxDL_VOIDMETHOD_DEFINE(MCSetActionFilterWithRefCon,
        (ComponentInstance ci, WXFARPROC cb, void* ref), (ci,cb,ref))
    wxDL_VOIDMETHOD_DEFINE(MCGetControllerInfo, (MovieController mc, long* flags), (mc,flags))
    wxDL_VOIDMETHOD_DEFINE(BeginUpdate, (CGrafPtr port), (port))
    wxDL_VOIDMETHOD_DEFINE(UpdateMovie, (Movie m), (m))
    wxDL_VOIDMETHOD_DEFINE(EndUpdate, (CGrafPtr port), (port))
    wxDL_METHOD_DEFINE( OSErr, GetMoviesStickyError, (), (), -1)
};

bool wxQuickTimeLibrary::Initialize()
{
    m_ok = false;

    // Turn off the wxDynamicLibrary logging as we're prepared to handle the
    // errors
    wxLogNull nolog;

    if (!m_dll.Load(wxT("qtmlClient.dll")))
    {
        return false;
    }

    wxDL_METHOD_LOAD( m_dll, StartMovie, m_ok );
    wxDL_METHOD_LOAD( m_dll, StopMovie, m_ok );
    wxDL_METHOD_LOAD( m_dll, IsMovieDone, m_ok );
    wxDL_METHOD_LOAD( m_dll, GoToBeginningOfMovie, m_ok );
    wxDL_METHOD_LOAD( m_dll, GetMoviesError, m_ok );
    wxDL_METHOD_LOAD( m_dll, EnterMovies, m_ok );
    wxDL_METHOD_LOAD( m_dll, ExitMovies, m_ok );
    wxDL_METHOD_LOAD( m_dll, InitializeQTML, m_ok );
    wxDL_METHOD_LOAD( m_dll, TerminateQTML, m_ok );
    wxDL_METHOD_LOAD( m_dll, NativePathNameToFSSpec, m_ok );
    wxDL_METHOD_LOAD( m_dll, OpenMovieFile, m_ok );
    wxDL_METHOD_LOAD( m_dll, CloseMovieFile, m_ok );
    wxDL_METHOD_LOAD( m_dll, NewMovieFromFile, m_ok );
    wxDL_METHOD_LOAD( m_dll, GetMovieRate, m_ok );
    wxDL_METHOD_LOAD( m_dll, SetMovieRate, m_ok );
    wxDL_METHOD_LOAD( m_dll, MoviesTask, m_ok );
    wxDL_METHOD_LOAD( m_dll, BlockMove, m_ok );
    wxDL_METHOD_LOAD( m_dll, NewHandleClear, m_ok );
    wxDL_METHOD_LOAD( m_dll, NewMovieFromDataRef, m_ok );
    wxDL_METHOD_LOAD( m_dll, DisposeHandle, m_ok );
    wxDL_METHOD_LOAD( m_dll, GetMovieNaturalBoundsRect, m_ok );
    wxDL_METHOD_LOAD( m_dll, GetMovieIndTrackType, m_ok );
    wxDL_METHOD_LOAD( m_dll, CreatePortAssociation, m_ok );
    wxDL_METHOD_LOAD( m_dll, DestroyPortAssociation, m_ok );
    wxDL_METHOD_LOAD( m_dll, GetNativeWindowPort, m_ok );
    wxDL_METHOD_LOAD( m_dll, SetMovieGWorld, m_ok );
    wxDL_METHOD_LOAD( m_dll, DisposeMovie, m_ok );
    wxDL_METHOD_LOAD( m_dll, SetMovieBox, m_ok );
    wxDL_METHOD_LOAD( m_dll, SetMovieTimeScale, m_ok );
    wxDL_METHOD_LOAD( m_dll, GetMovieDuration, m_ok );
    wxDL_METHOD_LOAD( m_dll, GetMovieTimeBase, m_ok );
    wxDL_METHOD_LOAD( m_dll, GetMovieTimeScale, m_ok );
    wxDL_METHOD_LOAD( m_dll, GetMovieTime, m_ok );
    wxDL_METHOD_LOAD( m_dll, SetMovieTime, m_ok );
    wxDL_METHOD_LOAD( m_dll, GetMovieVolume, m_ok );
    wxDL_METHOD_LOAD( m_dll, SetMovieVolume, m_ok );
    wxDL_METHOD_LOAD( m_dll, SetMovieTimeValue, m_ok );
    wxDL_METHOD_LOAD( m_dll, NewMovieController, m_ok );
    wxDL_METHOD_LOAD( m_dll, DisposeMovieController, m_ok );
    wxDL_METHOD_LOAD( m_dll, MCSetVisible, m_ok );
    wxDL_METHOD_LOAD( m_dll, PrePrerollMovie, m_ok );
    wxDL_METHOD_LOAD( m_dll, PrerollMovie, m_ok );
    wxDL_METHOD_LOAD( m_dll, GetMoviePreferredRate, m_ok );
    wxDL_METHOD_LOAD( m_dll, GetMovieLoadState, m_ok );
    wxDL_METHOD_LOAD( m_dll, MCDoAction, m_ok );
    wxDL_METHOD_LOAD( m_dll, MCSetControllerBoundsRect, m_ok );
    wxDL_METHOD_LOAD( m_dll, NativeEventToMacEvent, m_ok );
    wxDL_METHOD_LOAD( m_dll, MCIsPlayerEvent, m_ok );
    wxDL_METHOD_LOAD( m_dll, MCSetMovie, m_ok );
    wxDL_METHOD_LOAD( m_dll, MCSetActionFilterWithRefCon, m_ok );
    wxDL_METHOD_LOAD( m_dll, MCGetControllerInfo, m_ok );
    wxDL_METHOD_LOAD( m_dll, BeginUpdate, m_ok );
    wxDL_METHOD_LOAD( m_dll, UpdateMovie, m_ok );
    wxDL_METHOD_LOAD( m_dll, EndUpdate, m_ok );
    wxDL_METHOD_LOAD( m_dll, GetMoviesStickyError, m_ok );

    m_ok = true;

    return true;
}

class WXDLLIMPEXP_MEDIA wxQTMediaBackend : public wxMediaBackendCommonBase
{
public:
    wxQTMediaBackend();
    virtual ~wxQTMediaBackend();

    virtual bool CreateControl(wxControl* ctrl, wxWindow* parent,
                                     wxWindowID id,
                                     const wxPoint& pos,
                                     const wxSize& size,
                                     long style,
                                     const wxValidator& validator,
                                     const wxString& name);

    virtual bool Play();
    virtual bool Pause();
    virtual bool Stop();

    virtual bool Load(const wxURI& location,
                      const wxURI& proxy)
    { return wxMediaBackend::Load(location, proxy); }

    virtual bool Load(const wxString& fileName);
    virtual bool Load(const wxURI& location);

    virtual wxMediaState GetState();

    virtual bool SetPosition(wxLongLong where);
    virtual wxLongLong GetPosition();
    virtual wxLongLong GetDuration();

    virtual void Move(int x, int y, int w, int h);
    wxSize GetVideoSize() const;

    virtual double GetPlaybackRate();
    virtual bool SetPlaybackRate(double dRate);

    virtual double GetVolume();
    virtual bool SetVolume(double);

    void Cleanup();
    void FinishLoad();

    static void PPRMProc (Movie theMovie, OSErr theErr, void* theRefCon);

    // TODO: Last param actually long - does this work on 64bit machines?
    static Boolean MCFilterProc(MovieController theController,
        short action, void *params, LONG_PTR refCon);

    static LRESULT CALLBACK QTWndProc(HWND, UINT, WPARAM, LPARAM);

    virtual bool ShowPlayerControls(wxMediaCtrlPlayerControls flags);

    wxSize m_bestSize;              // Original movie size
    Movie m_movie;    // QT Movie handle/instance
    bool m_bVideo;                  // Whether or not we have video
    bool m_bPlaying;                // Whether or not movie is playing
    wxTimer* m_timer;               // Load or Play timer
    wxQuickTimeLibrary m_lib;       // DLL to load functions from
    ComponentInstance m_pMC;        // Movie Controller

    friend class wxQTMediaEvtHandler;

    DECLARE_DYNAMIC_CLASS(wxQTMediaBackend)
};

// helper to hijack background erasing for the QT window
class WXDLLIMPEXP_MEDIA wxQTMediaEvtHandler : public wxEvtHandler
{
public:
    wxQTMediaEvtHandler(wxQTMediaBackend *qtb, WXHWND hwnd)
    {
        m_qtb = qtb;
        m_hwnd = hwnd;

        m_qtb->m_ctrl->Connect(m_qtb->m_ctrl->GetId(),
            wxEVT_ERASE_BACKGROUND,
            wxEraseEventHandler(wxQTMediaEvtHandler::OnEraseBackground),
            NULL, this);
    }

    void OnEraseBackground(wxEraseEvent& event);

private:
    wxQTMediaBackend *m_qtb;
    WXHWND m_hwnd;

    DECLARE_NO_COPY_CLASS(wxQTMediaEvtHandler)
};

//===========================================================================
//  IMPLEMENTATION
//===========================================================================

//---------------------------------------------------------------------------
// wxQTMediaBackend
//
// TODO: Use a less kludgy way to pause/get state/set state
// FIXME: Greg Hazel reports that sometimes files that cannot be played
// with this backend are treated as playable anyway - not verified though.
//---------------------------------------------------------------------------

IMPLEMENT_DYNAMIC_CLASS(wxQTMediaBackend, wxMediaBackend)

// Time between timer calls - this is the Apple recommendation to the TCL
// team I believe
#define MOVIE_DELAY 20

//---------------------------------------------------------------------------
// wxQTLoadTimer
//
//  QT, esp. QT for Windows is very picky about how you go about
//  async loading.  If you were to go through a Windows message loop
//  or a MoviesTask or both and then check the movie load state
//  it would still return 1000 (loading)... even (pre)prerolling doesn't
//  help.  However, making a load timer like this works
//---------------------------------------------------------------------------
class wxQTLoadTimer : public wxTimer
{
public:
    wxQTLoadTimer(Movie movie, wxQTMediaBackend* parent, wxQuickTimeLibrary* pLib) :
      m_movie(movie), m_parent(parent), m_pLib(pLib) {}

    void Notify()
    {
        m_pLib->MoviesTask(m_movie, 0);
        // kMovieLoadStatePlayable
        if (m_pLib->GetMovieLoadState(m_movie) >= 10000)
        {
            m_parent->FinishLoad();
            delete this;
        }
    }

protected:
    Movie m_movie;                  //Our movie instance
    wxQTMediaBackend* m_parent;     //Backend pointer
    wxQuickTimeLibrary* m_pLib;     //Interfaces
};

// --------------------------------------------------------------------------
// wxQTPlayTimer - Handle Asyncronous Playing
//
// 1) Checks to see if the movie is done, and if not continues
//    streaming the movie
// 2) Sends the wxEVT_MEDIA_STOP event if we have reached the end of
//    the movie.
// --------------------------------------------------------------------------
class wxQTPlayTimer : public wxTimer
{
public:
    wxQTPlayTimer(Movie movie, wxQTMediaBackend* parent,
                  wxQuickTimeLibrary* pLib) :
        m_movie(movie), m_parent(parent), m_pLib(pLib) {}

    void Notify()
    {
        //
        //  OK, a little explaining - basically originally
        //  we only called MoviesTask if the movie was actually
        //  playing (not paused or stopped)... this was before
        //  we realized MoviesTask actually handles repainting
        //  of the current frame - so if you were to resize
        //  or something it would previously not redraw that
        //  portion of the movie.
        //
        //  So now we call MoviesTask always so that it repaints
        //  correctly.
        //
        m_pLib->MoviesTask(m_movie, 0);

        //
        // Handle the stop event - if the movie has reached
        // the end, notify our handler
        //
        //  m_bPlaying == !(Stopped | Paused)
        //
        if (m_parent->m_bPlaying)
        {
            if (m_pLib->IsMovieDone(m_movie))
            {
                if ( m_parent->SendStopEvent() )
                {
                    m_parent->Stop();
                    wxASSERT(m_pLib->GetMoviesError() == noErr);

                    m_parent->QueueFinishEvent();
                }
            }
        }
    }

protected:
    Movie m_movie;                  // Our movie instance
    wxQTMediaBackend* m_parent;     //Backend pointer
    wxQuickTimeLibrary* m_pLib;         //Interfaces
};

//---------------------------------------------------------------------------
// wxQTMediaBackend::QTWndProc
//
// Forwards events to the Movie Controller so that it can
// redraw itself/process messages etc..
//---------------------------------------------------------------------------
LRESULT CALLBACK wxQTMediaBackend::QTWndProc(HWND hWnd, UINT nMsg,
                                             WPARAM wParam, LPARAM lParam)
{
    wxQTMediaBackend* pThis = (wxQTMediaBackend*)wxGetWindowUserData(hWnd);

    MSG msg;
    msg.hwnd = hWnd;
    msg.message = nMsg;
    msg.wParam = wParam;
    msg.lParam = lParam;
    msg.time = 0;
    msg.pt.x = 0;
    msg.pt.y = 0;
    EventRecord theEvent;
    pThis->m_lib.NativeEventToMacEvent(&msg, &theEvent);
    pThis->m_lib.MCIsPlayerEvent(pThis->m_pMC, &theEvent);

    return pThis->m_ctrl->MSWWindowProc(nMsg, wParam, lParam);
}

//---------------------------------------------------------------------------
// wxQTMediaBackend Destructor
//
// Sets m_timer to NULL signifying we havn't loaded anything yet
//---------------------------------------------------------------------------
wxQTMediaBackend::wxQTMediaBackend()
: m_movie(NULL), m_bPlaying(false), m_timer(NULL), m_pMC(NULL)
{
}

//---------------------------------------------------------------------------
// wxQTMediaBackend Destructor
//
// 1) Cleans up the QuickTime movie instance
// 2) Decrements the QuickTime reference counter - if this reaches
//    0, QuickTime shuts down
// 3) Decrements the QuickTime Windows Media Layer reference counter -
//    if this reaches 0, QuickTime shuts down the Windows Media Layer
//---------------------------------------------------------------------------
wxQTMediaBackend::~wxQTMediaBackend()
{
    if (m_movie)
        Cleanup();

    if (m_lib.IsOk())
    {
        if (m_pMC)
        {
            m_lib.DisposeMovieController(m_pMC);
            // m_pMC = NULL;
        }

        // destroy wxQTMediaEvtHandler we pushed on it
        m_ctrl->PopEventHandler(true);

        m_lib.DestroyPortAssociation(
            (CGrafPtr)m_lib.GetNativeWindowPort(m_ctrl->GetHWND()));

        //Note that ExitMovies() is not necessary, but
        //the docs are fuzzy on whether or not TerminateQTML is
        m_lib.ExitMovies();
        m_lib.TerminateQTML();
    }
}

//---------------------------------------------------------------------------
// wxQTMediaBackend::CreateControl
//
// 1) Intializes QuickTime
// 2) Creates the control window
//---------------------------------------------------------------------------
bool wxQTMediaBackend::CreateControl(wxControl* ctrl, wxWindow* parent,
                                     wxWindowID id,
                                     const wxPoint& pos,
                                     const wxSize& size,
                                     long style,
                                     const wxValidator& validator,
                                     const wxString& name)
{
    if (!m_lib.Initialize())
        return false;

    int nError = m_lib.InitializeQTML(0);
    if (nError != noErr)    //-2093 no dll
    {
        wxFAIL_MSG(wxString::Format(wxT("Couldn't Initialize Quicktime-%i"), nError));
        return false;
    }

    m_lib.EnterMovies();

    // Create window
    // By default wxWindow(s) is created with a border -
    // so we need to get rid of those
    //
    // Since we don't have a child window like most other
    // backends, we don't need wxCLIP_CHILDREN
    if ( !ctrl->wxControl::Create(parent, id, pos, size,
                            (style & ~wxBORDER_MASK) | wxBORDER_NONE,
                            validator, name) )
    {
        return false;
    }

    m_ctrl = wxStaticCast(ctrl, wxMediaCtrl);

    // Create a port association for our window so we
    // can use it as a WindowRef
    m_lib.CreatePortAssociation(m_ctrl->GetHWND(), NULL, 0L);

    // Part of a suggestion from Greg Hazel
    // to repaint movie when idle
    m_ctrl->PushEventHandler(new wxQTMediaEvtHandler(this, m_ctrl->GetHWND()));

    // done
    return true;
}

//---------------------------------------------------------------------------
// wxQTMediaBackend::Load (file version)
//
// 1) Get an FSSpec from the Windows path name
// 2) Open the movie
// 3) Obtain the movie instance from the movie resource
// 4) Close the movie resource
// 5) Finish loading
//---------------------------------------------------------------------------
bool wxQTMediaBackend::Load(const wxString& fileName)
{
    if (m_movie)
        Cleanup();

    bool result = true;
    OSErr err = noErr;
    short movieResFile = 0; //= 0 because of annoying VC6 warning
    FSSpec sfFile;

    err = m_lib.NativePathNameToFSSpec(
        (char*) (const char*) fileName.mb_str(),
        &sfFile, 0);
    result = (err == noErr);

    if (result)
    {
        err = m_lib.OpenMovieFile(&sfFile, &movieResFile, fsRdPerm);
        result = (err == noErr);
    }

    if (result)
    {
        short movieResID = 0;
        Str255 movieName;

        err = m_lib.NewMovieFromFile(
                   &m_movie,
                   movieResFile,
                   &movieResID,
                   movieName,
                   newMovieActive,
                   NULL ); // wasChanged
        result = (err == noErr /*&& m_lib.GetMoviesStickyError() == noErr*/);

        // check m_lib.GetMoviesStickyError() because it may not find the
        // proper codec and play black video and other strange effects,
        // not to mention mess up the dynamic backend loading scheme
        // of wxMediaCtrl - so it just does what the QuickTime player does
        if (result)
        {
            m_lib.CloseMovieFile(movieResFile);
            FinishLoad();
        }
    }

    return result;
}

//---------------------------------------------------------------------------
// wxQTMediaBackend::PPRMProc (static)
//
// Called when done PrePrerolling the movie.
// Note that in 99% of the cases this does nothing...
// Anyway we set up the loading timer here to tell us when the movie is done
//---------------------------------------------------------------------------
void wxQTMediaBackend::PPRMProc (Movie theMovie,
                                 OSErr WXUNUSED_UNLESS_DEBUG(theErr),
                                 void* theRefCon)
{
    wxASSERT( theMovie );
    wxASSERT( theRefCon );
    wxASSERT( theErr == noErr );

    wxQTMediaBackend* pBE = (wxQTMediaBackend*) theRefCon;

    long lTime = pBE->m_lib.GetMovieTime(theMovie,NULL);
    Fixed rate = pBE->m_lib.GetMoviePreferredRate(theMovie);
    pBE->m_lib.PrerollMovie(theMovie, lTime, rate);
    pBE->m_timer = new wxQTLoadTimer(pBE->m_movie, pBE, &pBE->m_lib);
    pBE->m_timer->Start(MOVIE_DELAY);
}

//---------------------------------------------------------------------------
// wxQTMediaBackend::Load (URL Version)
//
// 1) Build an escaped URI from location
// 2) Create a handle to store the URI string
// 3) Put the URI string inside the handle
// 4) Make a QuickTime URL data ref from the handle with the URI in it
// 5) Clean up the URI string handle
// 6) Do some prerolling
// 7) Finish Loading
//---------------------------------------------------------------------------
bool wxQTMediaBackend::Load(const wxURI& location)
{
    if (m_movie)
        Cleanup();

    wxString theURI = location.BuildURI();

    Handle theHandle = m_lib.NewHandleClear(theURI.length() + 1);
    wxASSERT(theHandle);

    m_lib.BlockMove(theURI.mb_str(), *theHandle, theURI.length() + 1);

    // create the movie from the handle that refers to the URI
    OSErr err = m_lib.NewMovieFromDataRef(&m_movie, newMovieActive |
                                                    newMovieAsyncOK
                                                    /* | newMovieIdleImportOK */,
                                NULL, theHandle,
                                URLDataHandlerSubType);

    m_lib.DisposeHandle(theHandle);

    if (err == noErr)
    {
        long timeNow;
        Fixed playRate;

        timeNow = m_lib.GetMovieTime(m_movie, NULL);
        wxASSERT(m_lib.GetMoviesError() == noErr);

        playRate = m_lib.GetMoviePreferredRate(m_movie);
        wxASSERT(m_lib.GetMoviesError() == noErr);

        // Note that the callback here is optional,
        // but without it PrePrerollMovie can be buggy
        // (see Apple ml).  Also, some may wonder
        // why we need this at all - this is because
        // Apple docs say QuickTime streamed movies
        // require it if you don't use a Movie Controller,
        // which we don't by default.
        //
        m_lib.PrePrerollMovie(m_movie, timeNow, playRate,
                              (WXFARPROC)wxQTMediaBackend::PPRMProc,
                              (void*)this);

        return true;
    }
    else
        return false;
}

//---------------------------------------------------------------------------
// wxQTMediaBackend::FinishLoad
//
// 1) Create the movie timer
// 2) Get real size of movie for GetBestSize/sizers
// 3) Set the movie time scale to something usable so that seeking
//    etc.  will work correctly
// 4) Set our Movie Controller to display the movie if it exists,
//    otherwise set the bounds of the Movie
// 5) Refresh parent window
//---------------------------------------------------------------------------
void wxQTMediaBackend::FinishLoad()
{
    // Create the playing/streaming timer
    m_timer = new wxQTPlayTimer(m_movie, (wxQTMediaBackend*) this, &m_lib);
    wxASSERT(m_timer);

    m_timer->Start(MOVIE_DELAY, wxTIMER_CONTINUOUS);

    // get the real size of the movie
    Rect outRect;
    memset(&outRect, 0, sizeof(Rect)); // suppress annoying VC6 warning
    m_lib.GetMovieNaturalBoundsRect (m_movie, &outRect);
    wxASSERT(m_lib.GetMoviesError() == noErr);

    m_bestSize.x = outRect.right - outRect.left;
    m_bestSize.y = outRect.bottom - outRect.top;

    // Handle the movie GWorld
    if (m_pMC)
    {
        Point thePoint;
        thePoint.h = thePoint.v = 0;
        m_lib.MCSetMovie(m_pMC, m_movie,
               m_lib.GetNativeWindowPort(m_ctrl->GetHandle()),
               thePoint);
        m_lib.MCSetVisible(m_pMC, true);
        m_bestSize.y += 16;
    }
    else
    {
        m_lib.SetMovieGWorld(m_movie,
                       (CGrafPtr) m_lib.GetNativeWindowPort(m_ctrl->GetHWND()),
                       NULL);
    }

    // Set the movie to millisecond precision
    m_lib.SetMovieTimeScale(m_movie, 1000);
    wxASSERT(m_lib.GetMoviesError() == noErr);

    NotifyMovieLoaded();
}

//---------------------------------------------------------------------------
// wxQTMediaBackend::Play
//
// 1) Start the QT movie
// 2) Start the movie loading timer
//
// NOTE:  This will still return success even when
// the movie is still loading, and as mentioned in wxQTLoadTimer
// I don't know of a way to force this to be sync - so if its
// still loading the function will return true but the movie will
// still be in the stopped state
//---------------------------------------------------------------------------
bool wxQTMediaBackend::Play()
{
    m_lib.StartMovie(m_movie);
    m_bPlaying = true;

    return m_lib.GetMoviesError() == noErr;
}

//---------------------------------------------------------------------------
// wxQTMediaBackend::Pause
//
// 1) Stop the movie
// 2) Stop the movie timer
//---------------------------------------------------------------------------
bool wxQTMediaBackend::Pause()
{
    m_bPlaying = false;
    m_lib.StopMovie(m_movie);

    return m_lib.GetMoviesError() == noErr;
}

//---------------------------------------------------------------------------
// wxQTMediaBackend::Stop
//
// 1) Stop the movie
// 2) Stop the movie timer
// 3) Seek to the beginning of the movie
//---------------------------------------------------------------------------
bool wxQTMediaBackend::Stop()
{
    m_bPlaying = false;

    m_lib.StopMovie(m_movie);
    if (m_lib.GetMoviesError() == noErr)
        m_lib.GoToBeginningOfMovie(m_movie);

    return m_lib.GetMoviesError() == noErr;
}

//---------------------------------------------------------------------------
// wxQTMediaBackend::GetPlaybackRate
//
// Get the movie playback rate from ::GetMovieRate
//---------------------------------------------------------------------------
double wxQTMediaBackend::GetPlaybackRate()
{
    return ( ((double)m_lib.GetMovieRate(m_movie)) / 0x10000);
}

//---------------------------------------------------------------------------
// wxQTMediaBackend::SetPlaybackRate
//
// Convert dRate to Fixed and Set the movie rate through SetMovieRate
//---------------------------------------------------------------------------
bool wxQTMediaBackend::SetPlaybackRate(double dRate)
{
    m_lib.SetMovieRate(m_movie, (Fixed) (dRate * 0x10000));

    return m_lib.GetMoviesError() == noErr;
}

//---------------------------------------------------------------------------
// wxQTMediaBackend::SetPosition
//
// 1) Create a time record struct (TimeRecord) with appropriate values
// 2) Pass struct to SetMovieTime
//---------------------------------------------------------------------------
bool wxQTMediaBackend::SetPosition(wxLongLong where)
{
    // NB:  For some reason SetMovieTime does not work
    // correctly with the Quicktime Windows SDK (6)
    // From Muskelkatermann at the wxForum
    // http://www.solidsteel.nl/users/wxwidgets/viewtopic.php?t=2957
    // RN - note that I have not verified this but there
    // is no harm in calling SetMovieTimeValue instead
#if 0
    TimeRecord theTimeRecord;
    memset(&theTimeRecord, 0, sizeof(TimeRecord));
    theTimeRecord.value.lo = where.GetLo();
    theTimeRecord.scale = m_lib.GetMovieTimeScale(m_movie);
    theTimeRecord.base = m_lib.GetMovieTimeBase(m_movie);
    m_lib.SetMovieTime(m_movie, &theTimeRecord);
#else
    m_lib.SetMovieTimeValue(m_movie, where.GetLo());
#endif

    return (m_lib.GetMoviesError() == noErr);
}

//---------------------------------------------------------------------------
// wxQTMediaBackend::GetPosition
//
// 1) Calls GetMovieTime to get the position we are in in the movie
// in milliseconds (we called
//---------------------------------------------------------------------------
wxLongLong wxQTMediaBackend::GetPosition()
{
    return m_lib.GetMovieTime(m_movie, NULL);
}

//---------------------------------------------------------------------------
// wxQTMediaBackend::GetVolume
//
// Gets the volume through GetMovieVolume - which returns a 16 bit short -
//
// +--------+--------+
// +   (1)  +   (2)  +
// +--------+--------+
//
// (1) first 8 bits are value before decimal
// (2) second 8 bits are value after decimal
//
// Volume ranges from -1.0 (gain but no sound), 0 (no sound and no gain) to
// 1 (full gain and sound)
//---------------------------------------------------------------------------
double wxQTMediaBackend::GetVolume()
{
    short sVolume = m_lib.GetMovieVolume(m_movie);
    wxASSERT(m_lib.GetMoviesError() == noErr);

    if (sVolume & (128 << 8)) //negative - no sound
        return 0.0;

    return sVolume / 256.0;
}

//---------------------------------------------------------------------------
// wxQTMediaBackend::SetVolume
//
// Sets the volume through SetMovieVolume - which takes a 16 bit short -
//
// +--------+--------+
// +   (1)  +   (2)  +
// +--------+--------+
//
// (1) first 8 bits are value before decimal
// (2) second 8 bits are value after decimal
//
// Volume ranges from -1.0 (gain but no sound), 0 (no sound and no gain) to
// 1 (full gain and sound)
//---------------------------------------------------------------------------
bool wxQTMediaBackend::SetVolume(double dVolume)
{
    m_lib.SetMovieVolume(m_movie, (short) (dVolume * 256));
    return m_lib.GetMoviesError() == noErr;
}

//---------------------------------------------------------------------------
// wxQTMediaBackend::GetDuration
//
// Calls GetMovieDuration
//---------------------------------------------------------------------------
wxLongLong wxQTMediaBackend::GetDuration()
{
    return m_lib.GetMovieDuration(m_movie);
}

//---------------------------------------------------------------------------
// wxQTMediaBackend::GetState
//
// Determines the current state:
// if we are at the beginning, then we are stopped
//---------------------------------------------------------------------------
wxMediaState wxQTMediaBackend::GetState()
{
    if (m_bPlaying)
        return wxMEDIASTATE_PLAYING;
    else if ( !m_movie || wxQTMediaBackend::GetPosition() == 0 )
        return wxMEDIASTATE_STOPPED;
    else
        return wxMEDIASTATE_PAUSED;
}

//---------------------------------------------------------------------------
// wxQTMediaBackend::Cleanup
//
// Diposes of the movie timer, Disassociates the Movie Controller with
// movie and hides it if it exists, and stops and disposes
// of the QT movie
//---------------------------------------------------------------------------
void wxQTMediaBackend::Cleanup()
{
    m_bPlaying = false;

    if (m_timer)
    {
        delete m_timer;
        m_timer = NULL;
    }

    m_lib.StopMovie(m_movie);

    if (m_pMC)
    {
        Point thePoint;
        thePoint.h = thePoint.v = 0;
        m_lib.MCSetVisible(m_pMC, false);
        m_lib.MCSetMovie(m_pMC, NULL, NULL, thePoint);
    }

    m_lib.DisposeMovie(m_movie);
    m_movie = NULL;
}

//---------------------------------------------------------------------------
// wxQTMediaBackend::ShowPlayerControls
//
// Creates a movie controller for the Movie if the user wants it
//---------------------------------------------------------------------------
bool wxQTMediaBackend::ShowPlayerControls(wxMediaCtrlPlayerControls flags)
{
    if (m_pMC)
    {
        // restore old wndproc
        wxSetWindowProc((HWND)m_ctrl->GetHWND(), wxWndProc);
        m_lib.DisposeMovieController(m_pMC);
        m_pMC = NULL;

        // movie controller height
        m_bestSize.y -= 16;
    }

    if (flags && m_movie)
    {
        Rect rect;
        wxRect wxrect = m_ctrl->GetClientRect();

        // make room for controller
        if (wxrect.width < 320)
            wxrect.width = 320;

        rect.top = (short)wxrect.y;
        rect.left = (short)wxrect.x;
        rect.right = (short)(rect.left + wxrect.width);
        rect.bottom = (short)(rect.top + wxrect.height);

        if (!m_pMC)
        {
            m_pMC = m_lib.NewMovieController(m_movie, &rect, mcTopLeftMovie |
                                //                        mcScaleMovieToFit |
                                //                        mcWithBadge |
                                                        mcWithFrame);
            m_lib.MCDoAction(m_pMC, 32, (void*)true); // mcActionSetKeysEnabled
            m_lib.MCSetActionFilterWithRefCon(m_pMC,
                (WXFARPROC)wxQTMediaBackend::MCFilterProc, (void*)this);
            m_bestSize.y += 16; // movie controller height

            // By default the movie controller uses its own colour palette
            // for the movie which can be bad on some files, so turn it off.
            // Also turn off its frame / border for the movie
            // Also take care of a couple of the interface flags here
            long mcFlags = 0;
            m_lib.MCDoAction(m_pMC, 39/*mcActionGetFlags*/, (void*)&mcFlags);

            mcFlags |=
                // (1<< 0) /*mcFlagSuppressMovieFrame*/ |
                (1<< 3) /*mcFlagsUseWindowPalette*/
                | ((flags & wxMEDIACTRLPLAYERCONTROLS_STEP)
                      ? 0 : (1<< 1) /*mcFlagSuppressStepButtons*/)
                | ((flags & wxMEDIACTRLPLAYERCONTROLS_VOLUME)
                      ? 0 : (1<< 2) /*mcFlagSuppressSpeakerButton*/)
//              | (1<< 4) /*mcFlagDontInvalidate*/ // if we take care of repainting ourselves
                      ;

            m_lib.MCDoAction(m_pMC, 38/*mcActionSetFlags*/, (void*)mcFlags);

            // intercept the wndproc of our control window
            wxSetWindowProc((HWND)m_ctrl->GetHWND(), wxQTMediaBackend::QTWndProc);

            // set the user data of our window
            wxSetWindowUserData((HWND)m_ctrl->GetHWND(), this);
        }
    }

    NotifyMovieSizeChanged();

    return m_lib.GetMoviesError() == noErr;
}

//---------------------------------------------------------------------------
// wxQTMediaBackend::MCFilterProc (static)
//
// Callback for when the movie controller recieves a message
//---------------------------------------------------------------------------
Boolean wxQTMediaBackend::MCFilterProc(MovieController WXUNUSED(theController),
                               short action,
                               void * WXUNUSED(params),
                               LONG_PTR refCon)
{
// NB: potential optimisation
//    if (action == 1)
//        return 0;

    wxQTMediaBackend* pThis = (wxQTMediaBackend*)refCon;

    switch (action)
    {
    case 1:
        // don't process idle events
        break;

    case 8:
        // play button triggered - MC will set movie to opposite state
        // of current - playing ? paused : playing
        if (pThis)
            pThis->m_bPlaying = !(pThis->m_bPlaying);

        // NB: Sometimes it doesn't redraw properly -
        // if you click on the button but don't move the mouse
        // the button will not change its state until you move
        // mcActionDraw and Refresh/Update combo do nothing
        // to help this unfortunately
        break;

    default:
        break;
    }

    return 0;
}

//---------------------------------------------------------------------------
// wxQTMediaBackend::GetVideoSize
//
// Returns the actual size of the QT movie
//---------------------------------------------------------------------------
wxSize wxQTMediaBackend::GetVideoSize() const
{
    return m_bestSize;
}

//---------------------------------------------------------------------------
// wxQTMediaBackend::Move
//
// Sets the bounds of either the Movie or Movie Controller
//---------------------------------------------------------------------------
void wxQTMediaBackend::Move(int WXUNUSED(x), int WXUNUSED(y), int w, int h)
{
    if (m_movie)
    {
        // make room for controller
        if (m_pMC)
        {
            if (w < 320)
                w = 320;

            Rect theRect = {0, 0, (short)h, (short)w};
            m_lib.MCSetControllerBoundsRect(m_pMC, &theRect);
        }
        else
        {
            Rect theRect = {0, 0, (short)h, (short)w};
            m_lib.SetMovieBox(m_movie, &theRect);
        }

        wxASSERT(m_lib.GetMoviesError() == noErr);
    }
}

//---------------------------------------------------------------------------
// wxQTMediaBackend::OnEraseBackground
//
// Suggestion from Greg Hazel to repaint the movie when idle
// (on pause also)
//
// TODO: We may be repainting too much here - under what exact circumstances
// do we need this? I think Move also repaints correctly for the Movie
// Controller, so in that instance we don't need this either
//---------------------------------------------------------------------------
void wxQTMediaEvtHandler::OnEraseBackground(wxEraseEvent& evt)
{
    wxQuickTimeLibrary& m_pLib = m_qtb->m_lib;

    if ( m_qtb->m_pMC )
    {
        // repaint movie controller
        m_pLib.MCDoAction(m_qtb->m_pMC, 2 /*mcActionDraw*/,
                            m_pLib.GetNativeWindowPort(m_hwnd));
    }
    else if ( m_qtb->m_movie )
    {
        // no movie controller
        CGrafPtr port = (CGrafPtr)m_pLib.GetNativeWindowPort(m_hwnd);

        m_pLib.BeginUpdate(port);
        m_pLib.UpdateMovie(m_qtb->m_movie);
        wxASSERT(m_pLib.GetMoviesError() == noErr);
        m_pLib.EndUpdate(port);
    }
    else
    {
        // no movie
        // let the system repaint the window
        evt.Skip();
    }
}

//---------------------------------------------------------------------------
//  End QT Backend
//---------------------------------------------------------------------------

// in source file that contains stuff you don't directly use
#include "wx/html/forcelnk.h"
FORCE_LINK_ME(wxmediabackend_qt)

#endif // wxUSE_MEDIACTRL && wxUSE_ACTIVEX


text:
vows-batch-retry
================

[![Build Status](https://travis-ci.org/bpaquet/vows-batch-retry.png?branch=master)](https://travis-ci.org/bpaquet/vows-batch-retry)

Add a ``addBatchRetry`` command to [vows](http://vowsjs.org/), for tests which involved lot of external components, and which can failed
sometimes.

## How to use it ?

```js
var vows = require('vows-batch-retry'),
    assert = require('assert');

vows.describe('test if').addBatchRetry({
  'random number': {
    topic: function() {
      return Math.random();
    },
    'is upper 0.7': function(x) {
      assert(x > 0.7);
    }
  }
}, 10).export(module);

```

10 is the number of retry. When the test is ok, next try are ignored.

Example of output
```
$ node_modules/.bin/vows  random.js --spec

  ♢ test if

Test failed 'random number' with exception, retrying. { name: 'AssertionError',
  actual: false,
  expected: true,
  operator: '==',
  message: 'false == true' }
  random number[try 1/10]
    ✓ is upper 0.7
Test failed 'random number' with exception, retrying. { name: 'AssertionError',
  actual: false,
  expected: true,
  operator: '==',
  message: 'false == true' }
  random number[try 2/10]
    ✓ is upper 0.7
Test failed 'random number' with exception, retrying. { name: 'AssertionError',
  actual: false,
  expected: true,
  operator: '==',
  message: 'false == true' }
  random number[try 3/10]
    ✓ is upper 0.7
  random number[try 4/10]
    ✓ is upper 0.7
  random number[try 5/10]
    ✓ is upper 0.7
  random number[try 6/10]
    ✓ is upper 0.7
  random number[try 7/10]
    ✓ is upper 0.7
  random number[try 8/10]
    ✓ is upper 0.7
  random number[try 9/10]
    ✓ is upper 0.7
  random number[try 10/10]
    ✓ is upper 0.7

✓ OK » 10 honored (0.011s)

```

This test is ok after 3 tries.

## Async tests

After the number of tries, you can specify the test timeout. Default value is 2000 ms.

Example :
```js
var vows = require('vows-batch-retry'),
    assert = require('assert');

vows.describe('test if').addBatchRetry({
  'random number': {
    topic: function() {
      var callback = this.callback;
      setTimeout(function() {
        callback(null, "value");
      }, Math.random() * 500)
    },
    'is lower than 0.5, with a setTimeout call': function(x) {
      assert.equal("value", x);
    }
  }
}, 10, 250).export(module);

```

Example of output :
```
node_modules/.bin/vows  random-async.js --spec

  ♢ test if

Test failed 'random number' with topic timeout, retrying.
  random number[try 1/10]
    ✓ is lower than 0.5, with a setTimeout call
Test failed 'random number' with topic timeout, retrying.
  random number[try 2/10]
    ✓ is lower than 0.5, with a setTimeout call
  random number[try 3/10]
    ✓ is lower than 0.5, with a setTimeout call
  random number[try 4/10]
    ✓ is lower than 0.5, with a setTimeout call
  random number[try 5/10]
    ✓ is lower than 0.5, with a setTimeout call
  random number[try 6/10]
    ✓ is lower than 0.5, with a setTimeout call
  random number[try 7/10]
    ✓ is lower than 0.5, with a setTimeout call
  random number[try 8/10]
    ✓ is lower than 0.5, with a setTimeout call
  random number[try 9/10]
    ✓ is lower than 0.5, with a setTimeout call
  random number[try 10/10]
    ✓ is lower than 0.5, with a setTimeout call

✓ OK » 10 honored (0.820s)
```

This test is ok after 2 tries.