<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.12"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Tempest: Tempest::slot Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="style.css" rel="stylesheet" type="text/css"/>

Tempest

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Classes |
Protected Member Functions |
Friends |
List of all members

Tempest::slot Class Reference

Inheritance diagram for Tempest::slot:

  <map id="Tempest::slot_map" name="Tempest::slot_map">
<area href="class_tempest_1_1_list_delegate.html" title="The ListDelegate class provides items to display in list or other collection. " alt="Tempest::ListDelegate" shape="rect" coords="876,56,1304,80"/>
<area href="class_tempest_1_1_menu.html" alt="Tempest::Menu" shape="rect" coords="1314,56,1742,80"/>
<area href="class_tempest_1_1_widget.html" alt="Tempest::Widget" shape="rect" coords="1752,56,2180,80"/>
<area href="class_tempest_1_1signal.html" alt="Tempest::signal< bool >" shape="rect" coords="438,112,866,136"/>
<area href="class_tempest_1_1signal.html" alt="Tempest::signal< const std::u16string &>" shape="rect" coords="438,168,866,192"/>
<area href="class_tempest_1_1signal.html" alt="Tempest::signal< const std::u16string, const Tempest::Rect &>" shape="rect" coords="438,224,866,248"/>
<area href="class_tempest_1_1signal.html" alt="Tempest::signal< const Tempest::Menu::Declarator &, Tempest::Widget &>" shape="rect" coords="438,280,866,304"/>
<area href="class_tempest_1_1signal.html" alt="Tempest::signal< int >" shape="rect" coords="438,336,866,360"/>
<area href="class_tempest_1_1signal.html" alt="Tempest::signal< int, int >" shape="rect" coords="438,392,866,416"/>
<area href="class_tempest_1_1signal.html" alt="Tempest::signal< ShowMode >" shape="rect" coords="438,448,866,472"/>
<area href="class_tempest_1_1signal.html" alt="Tempest::signal< size_t >" shape="rect" coords="438,504,866,528"/>
<area href="class_tempest_1_1signal.html" alt="Tempest::signal< size_t, Tempest::Widget *>" shape="rect" coords="438,560,866,584"/>
<area href="class_tempest_1_1signal.html" alt="Tempest::signal< State >" shape="rect" coords="438,616,866,640"/>
<area href="class_tempest_1_1signal.html" alt="Tempest::signal< Tempest::Font >" shape="rect" coords="438,672,866,696"/>
<area href="class_tempest_1_1signal.html" alt="Tempest::signal< Tempest::Orientation >" shape="rect" coords="438,728,866,752"/>
<area href="class_tempest_1_1signal.html" alt="Tempest::signal< Tempest::UiMetrics >" shape="rect" coords="438,784,866,808"/>
<area href="class_tempest_1_1signal.html" alt="Tempest::signal< Tempest::Widget *>" shape="rect" coords="438,840,866,864"/>
<area href="class_tempest_1_1signal.html" title="signal class, for signals and slots system. " alt="Tempest::signal< Args >" shape="rect" coords="438,896,866,920"/>
<area href="class_tempest_1_1_abstract_list_delegate.html" alt="Tempest::AbstractListDelegate< T, std::vector< T >, Ctrl >" shape="rect" coords="1314,112,1742,136"/>
<area href="class_tempest_1_1_abstract_list_delegate.html" alt="Tempest::AbstractListDelegate< T, VT, Ctrl >" shape="rect" coords="1314,168,1742,192"/>
<area href="class_tempest_1_1_abstract_list_box.html" alt="Tempest::AbstractListBox" shape="rect" coords="2190,112,2618,136"/>
<area href="class_tempest_1_1_button.html" alt="Tempest::Button" shape="rect" coords="2190,168,2618,192"/>
<area href="class_tempest_1_1_image.html" alt="Tempest::Image< InTexture >" shape="rect" coords="2190,224,2618,248"/>
<area href="class_tempest_1_1_label.html" alt="Tempest::Label" shape="rect" coords="2190,280,2618,304"/>
<area href="class_tempest_1_1_line_edit.html" alt="Tempest::LineEdit" shape="rect" coords="2190,336,2618,360"/>
<area href="class_tempest_1_1_list_view.html" alt="Tempest::ListView" shape="rect" coords="2190,392,2618,416"/>
<area href="class_tempest_1_1_panel.html" alt="Tempest::Panel" shape="rect" coords="2190,448,2618,472"/>
<area href="class_tempest_1_1_scroll_bar.html" alt="Tempest::ScrollBar" shape="rect" coords="2190,504,2618,528"/>
<area href="struct_tempest_1_1_scroll_bar_1_1_central_widget.html" alt="Tempest::ScrollBar::CentralWidget" shape="rect" coords="2190,560,2618,584"/>
<area href="class_tempest_1_1_scroll_widget.html" alt="Tempest::ScrollWidget" shape="rect" coords="2190,616,2618,640"/>
<area href="class_tempest_1_1_stacked_widget.html" alt="Tempest::StackedWidget" shape="rect" coords="2190,672,2618,696"/>
<area href="class_tempest_1_1_surface.html" alt="Tempest::Surface" shape="rect" coords="2190,728,2618,752"/>
<area href="class_tempest_1_1_window.html" alt="Tempest::Window" shape="rect" coords="2190,784,2618,808"/>
<area href="class_tempest_1_1_window_overlay.html" alt="Tempest::WindowOverlay" shape="rect" coords="2190,840,2618,864"/>
</map>

Protected Member Functions

 	slot (const slot &other)

slot & 	operator= (slot &other)

Friends

class 	Detail::signalBase

template<class ... Args>

class 	Tempest::signal

The documentation for this class was generated from the following file:

signal_slot.h

Tempest

slot

Generated by

     1.8.12


module Spree
  class LoyaltyPointsDebitTransaction < LoyaltyPointsTransaction
    after_create :update_user_balance
    before_create :update_balance

    private

      def update_user_balance
        user.decrement(:loyalty_points_balance, loyalty_points)
        user.save!
      end

      def update_balance
        self.balance = user.loyalty_points_balance - loyalty_points
      end

  end
end


#ifndef QMITKXNATTREEMODEL_H
#define QMITKXNATTREEMODEL_H

// CTK includes
#include <ctkXnatTreeModel.h>

// MITK includes
#include "MitkXNATExports.h"

namespace mitk {
class DataNode;
}

class MITKXNAT_EXPORT QmitkXnatTreeModel : public ctkXnatTreeModel
{
  Q_OBJECT

public:
  QmitkXnatTreeModel();

  virtual QVariant data(const QModelIndex& index, int role) const;

  virtual bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent);

  using QAbstractItemModel::supportedDropActions;
  virtual Qt::DropActions supportedDropActions();

  virtual Qt::ItemFlags flags(const QModelIndex &index) const;

  ctkXnatObject* GetXnatObjectFromUrl(const QString&);

  signals:
  void ResourceDropped(const QList<mitk::DataNode*>&, ctkXnatObject*, const QModelIndex&);

private:
    ctkXnatObject *InternalGetXnatObjectFromUrl(const QString &xnatObjectType, const QString &url, ctkXnatObject *parent);

};

#endif // QMITKXNATTREEMODEL_H


/**
   @file
   @ingroup pgm
   @brief opengm extensions
*/

#ifndef PGMLINK_PGM_H
#define PGMLINK_PGM_H

#include <vector>

#include <pgmlink/ext_opengm/loss_hamming.hxx>
#include <opengm/graphicalmodel/graphicalmodel.hxx>
#include <pgmlink/ext_opengm/loglinearmodel.hxx>
#include <opengm/inference/inference.hxx>
#include <opengm/functions/explicit_function.hxx>
#include <pgmlink/ext_opengm/decorator_weighted.hxx>
#include <pgmlink/ext_opengm/indicator_function.hxx>
#include <opengm/operations/adder.hxx>
#include <opengm/utilities/metaprogramming.hxx>

#include "pgmlink/hypotheses.h"
#include "pgmlink/graph.h"
#include "pgmlink/util.h"

namespace pgmlink {
  namespace pgm {
    using boost::shared_ptr;

    //typedef opengm::GraphicalModel<double, opengm::Adder> OpengmModel;
    typedef opengm::ExplicitFunction<double> ExplicitFunction;
    typedef opengm::FunctionDecoratorWeighted< opengm::IndicatorFunction<double> > FeatureFunction;
    typedef opengm::HammingFunction<double> LossFunction;
    typedef opengm::LoglinearModel<double,
      opengm::meta::TypeList<ExplicitFunction,
      opengm::meta::TypeList<FeatureFunction,
      opengm::meta::TypeList<LossFunction, opengm::meta::ListEnd > > > > OpengmModel;

    template <typename OGM_FUNCTION>
      class OpengmFactor {
    public:
      typedef OGM_FUNCTION FunctionType;

      OpengmFactor( const FunctionType&, const std::vector<size_t>& ogm_var_indices );
      template <typename ITER>
	OpengmFactor( const FunctionType&, ITER first_ogm_idx, ITER last_ogm_idx );

      typename FunctionType::ValueType get_value( std::vector<size_t> coords ) const;
      template <typename OGM_GRAPHICAL_MODEL>
	void add_to( OGM_GRAPHICAL_MODEL& ) const;

      FunctionType& function() { return ogmfunction_; }
      const FunctionType& function() const { return ogmfunction_; }
      const std::vector<size_t>& var_indices() const { return vi_; }
      const std::vector<size_t>& var_order() const { return order_; }

    protected:
      FunctionType ogmfunction_;
      std::vector<size_t> vi_;
      std::vector<size_t> order_;
    };

    template <typename VALUE>
      class OpengmExplicitFactor : public OpengmFactor<opengm::ExplicitFunction<VALUE> > {
    public:
      typedef typename OpengmFactor<opengm::ExplicitFunction<VALUE> >::FunctionType FunctionType;

      OpengmExplicitFactor( const std::vector<size_t>& ogm_var_indices, VALUE init=0, size_t states_per_var=2 );
      template <typename ITER>
	OpengmExplicitFactor( ITER first_ogm_idx, ITER last_ogm_idx, VALUE init=0, size_t states_per_var=2 );

      void set_value( std::vector<size_t> coords, VALUE v);

    private:
      void init_( VALUE init, size_t states_per_var );
    };

    template <typename VALUE>
      class OpengmWeightedFeature
      : public OpengmFactor< opengm::FunctionDecoratorWeighted< opengm::IndicatorFunction<VALUE> > >
    {
    public:
      typedef typename opengm::FunctionDecoratorWeighted< opengm::IndicatorFunction<VALUE> > FunctionType;

      template<class IT1, class IT2>
	OpengmWeightedFeature(const std::vector<size_t>& ogm_var_indices,
			      IT1 shapeBegin, IT1 shapeEnd,
			      IT2 indicate,
			      VALUE indicate_value = 1.,
			      VALUE weight = 1.,
			      VALUE default_value = 0);

      template <typename OGM_LOGLINEARMODEL>
	void add_as_feature_to( OGM_LOGLINEARMODEL&, typename OGM_LOGLINEARMODEL::IndexType weight_index ) const;

      void weight( VALUE w );
      VALUE weight() const;

      void indicate_value( VALUE v );
      VALUE indicate_value() const;

      void default_value( VALUE v );
      VALUE default_value() const;
    };

    /**
       @brief Accessing entries of a Factor/Function that was already added to a graphical model.

       Manages a pointer to an element of an array-like opengm function (usually opengm::ExplicitFunction).
       Validity of the pointer is ensured by owning a smart pointer to the full model.

       Use this class to modify factor elements of an already instantiated opengm graphical model.
    */
    class FactorEntry {
    public:
    FactorEntry() : entry_(NULL) {}
    FactorEntry( shared_ptr<OpengmModel> m, /**< has to be valid */
		 OpengmModel::ValueType* entry /**< has to point into the opengm model to ensure the same lifetime */
		 ) :
      m_(m), entry_(entry) {}

      void set( OpengmModel::ValueType );
      OpengmModel::ValueType get() const;

      shared_ptr<OpengmModel> model() const { return m_; }

    private:
      shared_ptr<OpengmModel> m_;
      OpengmModel::ValueType* entry_;
    };

/******************/
/* Implementation */
/******************/

////
//// class OpengmFactor
////
 template <typename OGM_FUNCTION>
   OpengmFactor<OGM_FUNCTION>::OpengmFactor( const FunctionType& f, const std::vector<size_t>& ogm_var_indices )
   : ogmfunction_(f), vi_(ogm_var_indices) {
  // store sorted order of indices
  indexsorter::sort_indices( vi_.begin(), vi_.end(), order_ );
}

 template <typename OGM_FUNCTION>
   template< typename ITER >
   OpengmFactor<OGM_FUNCTION>::OpengmFactor( const FunctionType& f, ITER first_ogm_idx, ITER last_ogm_idx )
   : ogmfunction_(f), vi_(first_ogm_idx, last_ogm_idx) {
  // store sorted order of indices
  indexsorter::sort_indices( vi_.begin(), vi_.end(), order_ );
 }

 template <typename OGM_FUNCTION>
   typename OpengmFactor<OGM_FUNCTION>::FunctionType::ValueType OpengmFactor<OGM_FUNCTION>::get_value( std::vector<size_t> coords ) const {
   if( coords.size() != vi_.size() ) {
     throw std::invalid_argument("OpengmFactor::get_value(): coordinate dimension differs from factor dimension");
   }
   indexsorter::reorder( coords, order_ );
   return ogmfunction_(coords.begin());
 }

 template <typename OGM_FUNCTION>
   template <typename OGM_GRAPHICAL_MODEL>
   void OpengmFactor<OGM_FUNCTION>::add_to( OGM_GRAPHICAL_MODEL& m ) const {
   std::vector<size_t> sorted_vi(vi_);
   std::sort(sorted_vi.begin(), sorted_vi.end());
   // opengm expects a monotonic increasing sequence
   if(!(m.isValidIndexSequence(sorted_vi.begin(), sorted_vi.end()))) {
     throw std::runtime_error("OpengmExplicitFactor::add_to(): invalid index sequence");
   }

   typename OGM_GRAPHICAL_MODEL::FunctionIdentifier id=m.addFunction( ogmfunction_ );
   m.addFactor(id, sorted_vi.begin(), sorted_vi.end());
 }

////
//// class OpengmExplicitFactor
////
 template <typename VALUE>
   OpengmExplicitFactor<VALUE>::OpengmExplicitFactor( const std::vector<size_t>& ogm_var_indices, VALUE init, size_t states_per_var )
   : OpengmFactor<opengm::ExplicitFunction<VALUE> >(opengm::ExplicitFunction<VALUE>(), ogm_var_indices) {
  init_( init, states_per_var );
}
 template <typename VALUE>
   template< typename ITER >
   OpengmExplicitFactor<VALUE>::OpengmExplicitFactor( ITER first_ogm_idx, ITER last_ogm_idx, VALUE init, size_t states_per_var )
   : OpengmFactor<opengm::ExplicitFunction<VALUE> >(opengm::ExplicitFunction<VALUE>(),first_ogm_idx, last_ogm_idx) {
  init_( init, states_per_var );
 }

 template <typename VALUE>
   void OpengmExplicitFactor<VALUE>::set_value( std::vector<size_t> coords, VALUE v) {
   if( coords.size() != this->vi_.size() ) {
     throw std::invalid_argument("OpengmExplicitFactor::set_value(): coordinate dimension differs from factor dimension");
   }
   typename opengm::ExplicitFunction<VALUE>::iterator element( this->ogmfunction_ );
   size_t index;

   indexsorter::reorder( coords, this->order_ );
   this->ogmfunction_.coordinatesToIndex(coords.begin(), index);
   element[index] = v;
 }

 template <typename VALUE>
   void OpengmExplicitFactor<VALUE>::init_( VALUE init, size_t states_per_var ) {
   std::vector<size_t> shape( this->vi_.size(), states_per_var );
   this->ogmfunction_ = opengm::ExplicitFunction<VALUE>( shape.begin(), shape.end(), init );
 }

////
//// class OpengmWeightedFeature
////
template<class VALUE>
  template<class IT1, class IT2>
  OpengmWeightedFeature<VALUE>::OpengmWeightedFeature(
			  const std::vector<size_t>& ogm_var_indices,
		          IT1 shapeBegin, IT1 shapeEnd,
			  IT2 indicate,
			  VALUE indicate_value,
			  VALUE weight,
			  VALUE default_value)
  : OpengmFactor<FunctionType >(FunctionType(new opengm::IndicatorFunction<VALUE>( shapeBegin,
										   shapeEnd,
										   indicate,
										   indicate_value,
										   default_value),
					     weight)
				, ogm_var_indices) {
   // replace function with a sorted variant
   std::vector<size_t> sorted_shape( shapeBegin, shapeEnd );
   indexsorter::reorder( sorted_shape, this->order_ );
   std::vector<size_t> sorted_indicate( this->ogmfunction_.innerFunction()->indicate() );
   indexsorter::reorder( sorted_indicate, this->order_ );

   this->ogmfunction_ = FunctionType(new opengm::IndicatorFunction<VALUE>( sorted_shape.begin(),
									   sorted_shape.end(),
									   sorted_indicate.begin(),
									   indicate_value,
									   default_value),
				     weight);
 }

template<class VALUE>
  template <typename OGM_LOGLINEARMODEL>
  void OpengmWeightedFeature<VALUE>::add_as_feature_to( OGM_LOGLINEARMODEL& m, typename OGM_LOGLINEARMODEL::IndexType weight_index ) const {
  std::vector<size_t> sorted_vi(this->vi_);
  std::sort(sorted_vi.begin(), sorted_vi.end());
  // opengm expects a monotonic increasing sequence
  if(!(m.isValidIndexSequence(sorted_vi.begin(), sorted_vi.end()))) {
    throw std::runtime_error("OpengmExplicitFactor::add_to(): invalid index sequence");
  }

  typename OGM_LOGLINEARMODEL::FunctionIdentifier id=m.addFeature( this->ogmfunction_, weight_index );
  m.addFactor(id, sorted_vi.begin(), sorted_vi.end());
 }

template<class VALUE>
  void OpengmWeightedFeature<VALUE>::weight( VALUE w ) {
  this->ogmfunction_.weight(w);
 }

template<class VALUE>
  VALUE OpengmWeightedFeature<VALUE>::weight() const {
  return this->ogmfunction_.weight();
 }

template<class VALUE>
  void OpengmWeightedFeature<VALUE>::indicate_value( VALUE v ) {
  this->ogmfunction_.innerFunction()->indicate_value(v);
 }

template<class VALUE>
  VALUE OpengmWeightedFeature<VALUE>::indicate_value() const {
  return this->ogmfunction_.innerFunction()->indicate_value();
 }

template<class VALUE>
  void OpengmWeightedFeature<VALUE>::default_value( VALUE v ) {
  this->ogmfunction_.innerFunction()->default_value(v);
 }

template<class VALUE>
  VALUE OpengmWeightedFeature<VALUE>::default_value() const {
  return this->ogmfunction_.innerFunction()->default_value();
 }

} /* namespace pgm */
} /* namespace pgmlink */

#endif /* PGMLINK_PGM_H */


<!DOCTYPE html>

		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no"/>
		<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500" rel="stylesheet">
		<link href="https://fonts.googleapis.com/css?family=Chelsea+Market|Harmattan|Rancho" rel="stylesheet">
		<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
      rel="stylesheet">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
		<link rel="stylesheet" href="/style/style.css">
		<link rel="apple-touch-icon" sizes="180x180" href="/src/img/icons/trailTracker_icon-180.png" />
		<link rel="manifest" href=“/src/img/icons/manifest.json” />
		<link rel="icon" type="image/png" href="/src/img/icons/trailTracker_icon-32.png" sizes="32x32" />
		<link rel="icon" type="image/png" href="/src/img/icons/trailTracker_icon-16.png" sizes="16x16" />


module Carto
  module OauthProvider
    module Scopes
      class DataservicesScope < DefaultScope
        def initialize(service, description)
          super('dataservices', service, CATEGORY_MONEY, description)
          @grant_key = :services
        end

        def add_to_api_key_grants(grants, _user = nil)
          super(grants)
          ensure_includes_apis(grants, ['sql'])
        end
      end
    end
  end
end


import isAngle from './isAngle'
import isColor from './isColor'
import isCubicBezier from './isCubicBezier'
import isFrames from './isFrames'
import isGlobal from './isGlobal'
import isImage from './isImage'
import isLength from './isLength'
import isLengthPercentage from './isLengthPercentage'
import isNumber from './isNumber'
import isOpacity from './isOpacity'
import isPercentage from './isPercentage'
import isPosition from './isPosition'
import isRepeat from './isRepeat'
import isSize from './isSize'
import isSteps from './isSteps'
import isSvgLength from './isSvgLength'
import isTime from './isTime'

export {
  isAngle,
  isColor,
  isCubicBezier,
  isFrames,
  isGlobal,
  isImage,
  isLength,
  isLengthPercentage,
  isNumber,
  isOpacity,
  isPercentage,
  isPosition,
  isRepeat,
  isSize,
  isSteps,
  isSvgLength,
  isTime,
}


/*-------------------------------------------------------------------------
 * Script contains key operations for the Remote Control.
 *
 * DEPENDENCIES
 *  - Logger.js
 *-------------------------------------------------------------------------*/

/** Flag to indicate whether the remote button is pressed or not.*/
var isMouseDown = false;

/** Latest key to be send.*/
var latest_key;

/** Latest key event which is to be send. */
var latest_event;

/** Function invoked when the DOM is ready.*/
$(function() {
    $("#skeyboard,#shard-power,#skeyhelp").tooltip({
          show: {
            effect: "slideDown",
            delay: 2000
        },
        hide: {
            effect: "puff",
        }
    });

    /* Captures mouse out event for the DOM body and if holdkey action is in-progress (isMouseDown = true), it will generate
     * a mouseup event on the latest key to complete the hold action.*/
    $('body').mouseout(function() {
        if (isMouseDown) {
            clickRemoteButton(latest_event, latest_key, false);
        }
    });

    /* Creates a tabbed interface for trace and event logs. */
    $('.traceTab').tabs({

        /* Invoked when a tab widget is selected. */
        activate : function(event, ui) {
            var container;
            var index = ui.newTab.index();

            if( index === 0) {
                container = $(getVisibleTraceContainer()+' .traceDisp');
            } else if(index === 1) {
                container = $(getVisibleTraceContainer()+' .eventDisp');
            }
            doAutoScrolling(container);
        }
    });

});

/** Constant regex pattern for Non blinking keys. Applicable for hold actions. */
var non_blinking_key_pattern = /VOL(UP|DN)|CH(UP|DN)/;

/**
 * Sends a key to the server to be forwarded to the stb
 * @param key The name of the key to send
 */
function sendKey(key) {
    if ($('#faded').css('display') == 'none') {
        var deviceIds = LayoutUtil.getCheckedDevices();
        var keyPattern = "Key:"+ key;
        updateEventLog("Pressed remote key ["+ keyPattern +", Action:SENDKEY]", deviceIds);
        var remoteType = HTMLUtil.getParameterByName("remoteType");
        remoteType = (remoteType != null) ? remoteType.toUpperCase() : null;
        var keyPayload = {
                deviceIds : deviceIds,
                key : key,
                remoteType : remoteType
        };
        var posting = $.post(CXT_PATH + '/sendKey', keyPayload);
        validatePostEvent(posting, keyPattern);
    }
}

/**
 * Called when a key is clicked. This will blink the image and then send the key to the stb
 * @param image The image that was clicked and will blink
 * @param key The key to send to the stb
 */
function clickKey(image, key) {
    if(isBlinkAllowed(key)) {
        blink(image);
    }
    sendKey(key);
}

/**
 * Called when a key is holded for a duration. The image for the key will blink and then send the key along with
 * hold duration to the stb.
 *
 * @param image The image that was clicked and will blink
 * @param key The key to send to the stb
 * @param holdTime time in milliseconds the key is pressed.
 */
function holdIRKey(image, key, holdTime) {
    if(isBlinkAllowed(key)) {
        blink(image);
    }
    holdKey(key, holdTime);
}

/**
 * Blink keys only for key patterns which are NOT defined by
 * 'non_blinking_key_pattern' variable. For those keys flashing of button is
 * handled separately. Unlike other remote types BCM-7437-1 remote has separate
 * image for Chup, Chdn, Volup and Voldn. So these key patterns are also handled
 * here (ignoring non_blinking_key_pattern) if the remote type is BCM-7437-1.
 * Since the blinking of GENERIC remote is handled separately, isBlinkingAllowed
 * should return false, if remote type is GENERIC.
 *
 * @param keyName
 *            currently sending key name.
 * @returns true if flashing of button is allowed. False otherwise.
 */
function isBlinkAllowed(keyName) {
    var remoteType = StandardRemote.getRemoteName();
    var isBlinkingKey = non_blinking_key_pattern.test(keyName) ? false : true;
    var status = isBlinkingKey;
    if ('BCM-7437-1' == remoteType) {
        status = true;
    } else if ('GENERIC' == remoteType) {
        status = false;
    }
    return status;
}

/**
 * Sends a key to the server to be forwarded to the stb
 * @param key The name of the key to send
 * @param holdTime time in milliseconds the key is holded
 */
function holdKey(key, holdTime) {
    var deviceIds = LayoutUtil.getCheckedDevices();
    var keyPattern = "Key:"+ key;
    updateEventLog("Pressed remote key ["+ keyPattern +", Action:HOLDKEY, TimeInMillis:"+ holdTime+"]", deviceIds)
    var remoteType = HTMLUtil.getParameterByName("remoteType");
    remoteType = (remoteType != null) ? remoteType.toUpperCase() : null;
    if ($('#faded').css('display') == 'none') {
        var keyPayload = {
                deviceIds : deviceIds,
                key : key,
                holdTime : holdTime,
                remoteType : remoteType
        };
        var posting  = $.post(CXT_PATH + '/holdKey', keyPayload);
        validatePostEvent(posting, keyPattern);
    }
}

function sendKeyFromList() {
    var key = $('#keySelection').find(":selected").text();
    sendKey(key);
}

/**
 * Since chup and chdn and volup and voldn share an image then this method is called and determines which region is clicked.
 * @param img The image that was clicked
 * @param key The name of the key to send (VOL or CH)
 * @param clickY user clicked position(from top) in the page
 * @param isMouseDown flag to indicate whether key pressed or not. The button will blink only during the
 * release of the key.
 * @returns key pattern to be sent to the Rack.
 */
function getKeyForVolCh(img, key, clickY, isMouseDown) {
    var iconHeight = $(img).height()/2;

    // Actual image mid pixel in the page.
    var boundary = $(img).offset().top + iconHeight;

    var clickedTop = clickY < boundary;
    var top =  clickedTop ? 0 : iconHeight;

    var keySuffix = clickedTop ? 'UP' : 'DN';

    if(!isMouseDown) {
        blinkRegion($(img)[0], 0, top, $(img).width(), iconHeight);
    }
    return (key + keySuffix);
}

var keyMap = new Array();
keyMap[13] = 'SELECT'; // enter
keyMap[38] = 'UP'; // up
keyMap[40] = 'DOWN'; // down
keyMap[37] = 'LEFT'; // left
keyMap[39] = 'RIGHT'; // right
keyMap[65] = 'A'; // a
keyMap[66] = 'B'; // b
keyMap[67] = 'C'; // c
keyMap[68] = 'D'; // d
keyMap[8] = 'LAST'; // backspace
keyMap[189] = 'CHDN'; // +
keyMap[187] = 'CHUP'; // -
keyMap[33] = 'PGUP'; // Page Up
keyMap[34] = 'PGDN'; // Page Down
keyMap[71] = 'GUIDE'; // g
keyMap[77] = 'MENU'; // m
keyMap[73] = 'INFO'; // i
keyMap[27] = 'EXIT'; // esc
keyMap[48] = 'ZERO'; // 0
keyMap[49] = 'ONE'; // 1
keyMap[50] = 'TWO'; // 2
keyMap[51] = 'THREE'; // 3
keyMap[52] = 'FOUR'; // 4
keyMap[53] = 'FIVE'; // 5
keyMap[54] = 'SIX'; // 6
keyMap[55] = 'SEVEN'; // 7
keyMap[56] = 'EIGHT'; // 8
keyMap[57] = 'NINE'; // 9
keyMap[112] = 'FAV_1'; // Fav 1
keyMap[113] = 'FAV_2'; // Fav 2
keyMap[114] = 'FAV_3'; // Fav 3
keyMap[115] = 'FAV_4'; // Fav 4

/** Key code for '=' which is mapped to CHUP  */
var CHUP_KEY_CODE = 187;

/** Key code for '-' which is mapped to CHDN  */
var CHDN_KEY_CODE = 189;

/** Key codes of Fav1, Fav2,Fav3 and Fav4 which are mapped to FAV_1, FAV_2, FAV_3, FAV_4 */
var FAV_CHANNEL_CODES = [112, 113, 114, 115];

/** Key codes of buttons that are not available in BCM-7437-1 remote (PGUP, PGDN, A, B, C, D) */
var KEY_CODES_NOT_SUPPORTED_BY_BCM_7437_1_REMOTE = [33, 34, 65, 66, 67, 68];

$(window).keydown(function(event) {
    var editingText = $(document.activeElement).attr("type") == "text" || $(document.activeElement).attr("type") == "textarea";
    if (!editingText && hotKeysOn && !event.ctrlKey) {
        var keyCode = event.which;
        var key = keyMap[keyCode];
        if (key != null) {
            var rem = $('#standardRemoteDiv').is(':hidden') ? 'm' : 's';
            var remoteType = StandardRemote.getRemoteName();

            /** For CHUP and CHDN, one single image is used. So blink the proper area in UI depends on the Pressed key.*/
            if((keyCode === CHUP_KEY_CODE || keyCode === CHDN_KEY_CODE) && (remoteType != 'BCM-7437-1')) {
                var chElement = $("#sch")[0];
                var iconHeight = $(chElement).height()/2;
                var iconWidth = $(chElement).width();

                if(keyCode === CHUP_KEY_CODE) {
                    blinkRegion($(chElement)[0], 0, 0, iconWidth, iconHeight);
                } else {
                    blinkRegion($(chElement)[0], 0, iconHeight, iconWidth, iconHeight);
                }
            }

            validateClickedKey(rem, key, keyCode, remoteType);
            event.preventDefault();
        }
    }
});

function validateClickedKey (rem, key, keyCode, remoteType){
    if ((FAV_CHANNEL_CODES.indexOf(keyCode) > -1) && remoteType != 'BCM-7437-1') {
        // Do nothing, do not send key press
    } else if ((KEY_CODES_NOT_SUPPORTED_BY_BCM_7437_1_REMOTE.indexOf(keyCode) > -1) && remoteType =='BCM-7437-1'){
        // Do nothing, do not send key press
    } else {
        clickKey(document.getElementById(rem + key.toLowerCase()), key);
    }
}

var hotKeysOn = true;

function clickKeyboard(img) {
    hotKeysOn = !hotKeysOn;
    img.src = CXT_PATH + "/images/keyboard" + (hotKeysOn ? "Sel" : "") + ".png";
    updateKeyboardQHelp(hotKeysOn);
}

/** Constant to store the time in milliseconds for a single key press. */
var single_keypress_time = 100;

/** Delay in milliseconds used to distinguish between a normal click from the hold key event. If a key is
 * is pressed for more than 500ms, then it is assumed as a hold action.*/
var delay_for_hold_action = 500;

/** Interval timer variable for hold action */
var intervalTimer;

/** Timeout timer variable for hold action.*/
var timeOut;

/** Holds the time at which the key is pressed. */
var startTime = 0;

/** Holds the time at which the key is released. */
var endTime = 0;

/**
 * Method which handles the click events and distinguish between normal click and hold action.
 * If a key is pressed for < 500ms, then it is assumed as a normal single click action. If the click,
 * duration is more than 500ms then it will identify it as a hold event and compute the hold time in milliseconds.
 *
 * General rule for computation is : <b>For every 100ms there will be 1 key press.</b>
 *
 * @param e click event
 * @param key key value to be sent to the IRClient
 * @param isDown Flag to indicate whehter key press or key release.
 */

function clickRemoteButton(e, key, isDown) {
    latest_event = e;
    latest_key = key;

    var image = latest_event.target;

    if (isDown) {
        isMouseDown = true;
        startTime = Date.now();
        clearTimers();
        $('#hold_panel').text('');

        clickTime = Date.now() - startTime;

        // Setup a timeout timer to update the repeat count values.
        // The counter updation starts ONLY AFTER (500 - current clickTime)
            timeOut = setTimeout(function () {
                updateCounter(e);
            }, (delay_for_hold_action - clickTime));
    } // end of key down action
    else {

        // Trigger the key up action only if valid mouse down action exists.
        if(isMouseDown){
            isMouseDown = false;
            endTime = Date.now();

            // clear all timers which are asynchronously updating the repeat counts.
            clearTimers();

            // Compute the key hold time.
            var holdTimeInMillis = endTime - startTime;

            $('#hold_panel').hide("slow");

            if (holdTimeInMillis > delay_for_hold_action) {
                // Press and hold key
                holdIRKey(image, key, holdTimeInMillis);
            } else {
                // Normal click
                clickKey(image, key);
            }
            // reset starttime and endtime variables.
            startTime = 0;
            endTime = 0;
        }
    }
}

/**
 * Method to asynchronously update the repeat counter for the hold action.
 * @param e click event
 */

function updateCounter(e) {
    // Default repeat count value. In order to have a hold event there should be a minimum of
    // 500 ms. For every 100ms there will be 1 key. So setting 5 as default repeat count.
    repeatCount = 5;

    // Computing currently clicked position in the screen to draw the counter panel.
    posX = e.pageX;
    posY = e.pageY;

    // Increment counter in every 100ms, until the timers are cleared.
    intervalTimer = setInterval(function () {
        repeatCount++;
        drawOverlay(posX, posY, repeatCount);
    }, single_keypress_time);
}

/**
 * Draw the counter panel overlay.
 * @param posX currently clicked X position
 * @param posY currently clicked Y position
 * @param repeatCount repeat count for the key.
 */

function drawOverlay(posX, posY, repeatCount) {
    $('#hold_panel').css('left', posX + 10);
    $('#hold_panel').css('top', posY + 5);
    $('#hold_panel').show("fast");
    $('#hold_panel').text(repeatCount + ' repeats ');
}

/**
 * Clear all the previously existing timeout and interval timers.
 */

function clearTimers() {
    clearInterval(intervalTimer);
    clearTimeout(timeOut);
}

/**
 * Used to display or hide the keyboard to remote key mapping overlay
 * @param e click event
 * @param status determines whether to show or hide the overlay.
 */
function displayKeyMappingOverlay(e, status) {
    var image = e.target;
    if(status) {
        blink(image);
        $("#keymap_panel").show("slow")
    } else {
        $("#keymap_panel").hide("slow")
    }
}

/**
 * Display keyboard quick help button only if the keyboard mode is active.
 * @param isVisible indicate whether keyboard mode is currently active or not.
 */
function updateKeyboardQHelp(isVisible) {
    if(isVisible) {
        $("#skeyhelp").show();
    } else {
        $("#skeyhelp").hide();
    }
}

/**
 * Helper method to verify the post event response.
 * @param posting event response
 * @param keyPattern key pattern sent to the server.
 */
function validatePostEvent(posting, keyPattern) {
    posting.done(function( data ) {
        updateEventLog( "Successfully sent ["+ keyPattern +"]", null);
        });
    posting.fail(function(jqXHR, textStatus, errorThrown){
        updateEventLog( "Error while sending ["+ keyPattern + "]", null);
        updateEventLog( errorThrown +". Status: "+ jqXHR.status, null);
    });
}


//=================================================================================================

//=================================================================================================

//*************************************************************************************************
// Includes
//*************************************************************************************************

#include <cstdlib>
#include <iostream>
#include <blaze/math/CompressedVector.h>
#include <blaze/math/DynamicMatrix.h>
#include <blaze/math/StrictlyLowerMatrix.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/dmatsvecmult/OperationTest.h>
#include <blazetest/system/MathTest.h>

//=================================================================================================
//
//  MAIN FUNCTION
//
//=================================================================================================

//*************************************************************************************************
int main()
{
   std::cout << "   Running 'SLDbVCb'..." << std::endl;

   using blazetest::mathtest::TypeB;

   try
   {
      // Matrix type definitions
      typedef blaze::StrictlyLowerMatrix< blaze::DynamicMatrix<TypeB> >  SLDb;
      typedef blaze::CompressedVector<TypeB>                             VCb;

      // Creator type definitions
      typedef blazetest::Creator<SLDb>  CSLDb;
      typedef blazetest::Creator<VCb>   CVCb;

      // Running tests with large matrices and vectors
      for( size_t i=0UL; i<=6UL; ++i ) {
         for( size_t j=0UL; j<=i; ++j ) {
            RUN_DMATSVECMULT_OPERATION_TEST( CSLDb( i ), CVCb( i, j ) );
         }
      }

      // Running tests with large matrices and vectors
      RUN_DMATSVECMULT_OPERATION_TEST( CSLDb(  67UL ), CVCb(  67UL,  7UL ) );
      RUN_DMATSVECMULT_OPERATION_TEST( CSLDb( 127UL ), CVCb( 127UL, 13UL ) );
      RUN_DMATSVECMULT_OPERATION_TEST( CSLDb(  64UL ), CVCb(  64UL,  8UL ) );
      RUN_DMATSVECMULT_OPERATION_TEST( CSLDb( 128UL ), CVCb( 128UL, 16UL ) );
   }
   catch( std::exception& ex ) {
      std::cerr << "\n\n ERROR DETECTED during dense matrix/sparse vector multiplication:\n"
                << ex.what() << "\n";
      return EXIT_FAILURE;
   }

   return EXIT_SUCCESS;
}
//*************************************************************************************************


using System;
using UnityEngine;
using Vexe.Runtime.Extensions;
using Vexe.Runtime.Helpers;
using Vexe.Runtime.Types;
using Random = UnityEngine.Random;

namespace Vexe.Editor.Drawers
{
	public abstract class BetterVectorDrawer<T, A> : AttributeDrawer<T, A> where A : DrawnAttribute
	{
		private const string kBtnReset = "0";
		private const string kBtnNormalize = "1";
		private const string kBtnRandomize = "r";

		private Func<string, T, T> _getField;

		protected static float rand()
		{
			return Random.Range(-100, 100);
		}

		public override void OnGUI()
		{
			using (gui.Horizontal())
			{
				if (_getField == null)
					_getField = GetField();

				var current = memberValue;
				var newValue = _getField(displayText, current);
				{
					if (!VectorEquals(current, newValue))
						memberValue = newValue;
				}

				gui.Space(12f);
				Foldout();
				gui.Space(-10f);
			}

			if (foldout)
			{
				using (gui.Horizontal())
				{
					DoButtons();
					gui.Space(25f);
				}
			}
		}

		private void DoButtons()
		{
			gui.FlexibleSpace();
			var option = Layout.sHeight(13f);
			if (gui.MiniButton("Copy", "Copy vector value", option))
				Copy();
			if (gui.MiniButton("Paste", "Paste vector value", option))
				memberValue = Paste();
			if (gui.MiniButton(kBtnRandomize, "Randomize values between [-100, 100]", MiniButtonStyle.ModMid, option))
				memberValue = Randomize();
			if (gui.MiniButton(kBtnNormalize, "Normalize", MiniButtonStyle.ModMid, option))
				memberValue = Normalize();
			if (gui.MiniButton(kBtnReset, "Reset", MiniButtonStyle.ModRight, option))
				memberValue = Reset();
		}

		protected abstract Func<string, T, T> GetField();

		protected abstract bool VectorEquals(T left, T right);

		protected abstract T Reset();

		protected abstract T Normalize();

		protected abstract T Randomize();

		protected abstract T Paste();

		protected abstract void Copy();
	}

	public class BetterV2Drawer : BetterVectorDrawer<Vector2, BetterV2Attribute>
	{
		protected override void Copy()
		{
			int key = RuntimeHelper.CombineHashCodes(id, "Clip");
			prefs.SetV2(key, memberValue);
		}

		protected override Vector2 Paste()
		{
			int key = RuntimeHelper.CombineHashCodes(id, "Clip");
			return prefs.GetV2(key, memberValue);
		}

		protected override Vector2 Randomize()
		{
			return new Vector2(rand(), rand());
		}

		protected override Vector2 Normalize()
		{
			return Vector2.one;
		}

		protected override Vector2 Reset()
		{
			return Vector2.zero;
		}

		protected override Func<string, Vector2, Vector2> GetField()
		{
			return gui.Vector2Field;
		}

		protected override bool VectorEquals(Vector2 left, Vector2 right)
		{
			return left.ApproxEqual(right);
		}
	}

	public class BetterV3Drawer : BetterVectorDrawer<Vector3, BetterV3Attribute>
	{
		protected override void Copy()
		{
			int key = RuntimeHelper.CombineHashCodes(id, "Clip");
			prefs.SetV3(key, memberValue);
		}

		protected override Vector3 Paste()
		{
			int key = RuntimeHelper.CombineHashCodes(id, "Clip");
			return prefs.GetV3(key, memberValue);
		}

		protected override Vector3 Randomize()
		{
			return new Vector3(rand(), rand(), rand());
		}

		protected override Vector3 Normalize()
		{
			return Vector3.one;
		}

		protected override Vector3 Reset()
		{
			return Vector3.zero;
		}

		protected override Func<string, Vector3, Vector3> GetField()
		{
			return gui.Vector3Field;
		}

		protected override bool VectorEquals(Vector3 left, Vector3 right)
		{
			return left.ApproxEqual(right);
		}
	}
}


/*
 * The Plaid API
 * The Plaid REST API. Please see https://plaid.com/docs/api for more details.
 *
 * The version of the OpenAPI document: 2020-09-14_1.205.3
 *
 *
 * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

package com.plaid.client.model;

import java.util.Objects;
import java.util.Arrays;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import com.plaid.client.model.Originator;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Defines the response schema for `/transfer/originator/list`
 */
@ApiModel(description = "Defines the response schema for `/transfer/originator/list`")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2022-11-17T17:52:41.932844Z[Etc/UTC]")
public class TransferOriginatorListResponse {
  public static final String SERIALIZED_NAME_ORIGINATORS = "originators";
  @SerializedName(SERIALIZED_NAME_ORIGINATORS)
  private List<Originator> originators = new ArrayList<>();

  public static final String SERIALIZED_NAME_REQUEST_ID = "request_id";
  @SerializedName(SERIALIZED_NAME_REQUEST_ID)
  private String requestId;

  public TransferOriginatorListResponse originators(List<Originator> originators) {

    this.originators = originators;
    return this;
  }

  public TransferOriginatorListResponse addOriginatorsItem(Originator originatorsItem) {
    this.originators.add(originatorsItem);
    return this;
  }

   /**
   * Get originators
   * @return originators
  **/
  @ApiModelProperty(required = true, value = "")

  public List<Originator> getOriginators() {
    return originators;
  }

  public void setOriginators(List<Originator> originators) {
    this.originators = originators;
  }

  public TransferOriginatorListResponse requestId(String requestId) {

    this.requestId = requestId;
    return this;
  }

   /**
   * A unique identifier for the request, which can be used for troubleshooting. This identifier, like all Plaid identifiers, is case sensitive.
   * @return requestId
  **/
  @ApiModelProperty(required = true, value = "A unique identifier for the request, which can be used for troubleshooting. This identifier, like all Plaid identifiers, is case sensitive.")

  public String getRequestId() {
    return requestId;
  }

  public void setRequestId(String requestId) {
    this.requestId = requestId;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    TransferOriginatorListResponse transferOriginatorListResponse = (TransferOriginatorListResponse) o;
    return Objects.equals(this.originators, transferOriginatorListResponse.originators) &&
        Objects.equals(this.requestId, transferOriginatorListResponse.requestId);
  }

  @Override
  public int hashCode() {
    return Objects.hash(originators, requestId);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("class TransferOriginatorListResponse {\n");
    sb.append("    originators: ").append(toIndentedString(originators)).append("\n");
    sb.append("    requestId: ").append(toIndentedString(requestId)).append("\n");
    sb.append("}");
    return sb.toString();
  }

  /**
   * Convert the given object to string with each line indented by 4 spaces
   * (except the first line).
   */
  private String toIndentedString(Object o) {
    if (o == null) {
      return "null";
    }
    return o.toString().replace("\n", "\n    ");
  }

}


require 'omniauth-github-team-member/version'
require 'omniauth/strategies/github_team_member'


TFJS uint8 quantized version of the YOLO model (with DarkNet 53 backbone) trained on the CPPE - 5 (Medical Personal Protective Equipment) dataset [1].

<!-- parent-model: rishit-dagli/yolo-cppe5-tfjs/1 -->
<!-- asset-path: https://storage.googleapis.com/cppe-5/trained_models/yolo/tfjs/yolo_uint8.tar.gz -->

### Overview
The YOLO model was proposed by Redmon et al. in their paper "Yolov3: An incremental improvement" [2]. The YOLO model is trained on the CPPE - 5 dataset we present in our paper "CPPE - 5: Medical Personal Protective Equipment Dataset" [1] which is a new challenging dataset with an aim to facilitate the study of subordinate categorization of medical personal protective equipments. This dataset mostly contains non-iconic images or non-canonical perspectives in their natural context. This allows models to be better at generalizing, being easily deployable to real-world scenarios and often contain other objects in an image as well.

We include the training code as well some tools for this model in our paper GitHub repository [3].

Note: In no case should this model be used to engage in any kind of high-risk activities, please [TF Hub Additional Terms of Service](https://tfhub.dev/terms#hra) for more information.

### Usage
The saved model can be loaded directly:

```js
const model = await tf.loadGraphModel("https://tfhub.dev/rishit-dagli/yolo-cppe5-tfjs/uint8/tfjs/1")
```

The inputs to the models should:

- have color values in the range `[0,1]`, following the [common image input](https://www.tensorflow.org/hub/common_signatures/images#input) conventions
- the expected size of the input images is height x width = 800 x 1216 pixels
- the images should in the `channels_first` format
- The shape of the input tensor would ths be `(1, 3, 800, 1216)`, the first dimension represents the batch size

The model outputs are:

- A tensor of shape `[batch_size, 100, 5]` with the bounding boxes in normalized coordinates.
- A tensor of shape `[batch_size, 100]` with the class labels for the bounding boxes.

### Note

- This model was quantized using `uint8` quantization.
- This model takes fixed-shaped (800 x 1216) inputs.
- This model has been converted using the [TensorFlow.js converter API](https://www.tensorflow.org/js/guide/conversion).

### Acknowledgements

This is joint work with Ali Mustufa Shaikh. The authors would like to thank Google for supporting this work by providing Google Cloud credits. The authors would also like to thank [Google TPU Research Cloud (TRC) program](https://sites.research.google/trc) for providing access to TPUs.

### References

[1] Dagli, Rishit, and Ali Mustufa Shaikh. ‘CPPE-5: Medical Personal Protective Equipment Dataset’. ArXiv:2112.09569 [Cs], Dec. 2021. arXiv.org, http://arxiv.org/abs/2112.09569.

[2] Redmon, Joseph, and Ali Farhadi. "Yolov3: An incremental improvement." arXiv preprint arXiv:1804.02767 (2018).

[3] https://github.com/Rishit-dagli/CPPE-Dataset


<?php
session_start();
require("../../MySQLconnect/config.php");

if(!isset($_SESSION['user_id']))
{
header('location:../../');
}
else
{
$userid = mysql_real_escape_string($_SESSION['user_id']);
}

$riskid = mysql_real_escape_string($_GET['risk_id']);
$projectid = mysql_real_escape_string($_GET['project_id']);
$riskinfo = htmlentities(stripslashes(stripslashes(mysql_real_escape_string($_GET['risk_info']))),ENT_QUOTES);
$consequence = htmlentities(stripslashes(stripslashes(mysql_real_escape_string($_GET['consequence']))),ENT_QUOTES);
$chance = mysql_real_escape_string($_GET['chance']);
$programme = mysql_real_escape_string($_GET['programme']);
$budget = mysql_real_escape_string($_GET['budget']);
$she = mysql_real_escape_string($_GET['she']);
$timeimpact = mysql_real_escape_string($_GET['impact_t']);
$cost = mysql_real_escape_string($_GET['cost']);
$costtbd = mysql_real_escape_string($_GET['cost_tbd']);
$owner = mysql_real_escape_string($_GET['owner']);
$mitigation = htmlentities(stripslashes(stripslashes(mysql_real_escape_string($_GET['mitigation']))),ENT_QUOTES);
$time=time();
$riskrating = $chance*max($programme,$budget);

$oldrecorddetails = mysql_fetch_array(mysql_query("SELECT * FROM risk_log WHERE risk_id='$riskid'"));

//check for the ID of the new owner and add them to the system if they do not exist
$results = mysql_query("SELECT * FROM users WHERE email='$owner'");
$countrows = mysql_num_rows($results);
if($countrows==0)
{
mysql_query("INSERT INTO users SET email='$owner'");
$results = mysql_query("SELECT * FROM users WHERE email='$owner'");
$ownerid = mysql_fetch_array($results);
$ownerid = $ownerid['user_id'];
}
else
{
$ownerid = mysql_fetch_array($results);
$ownerid = $ownerid['user_id'];
}

mysql_query("UPDATE risk_log
SET risk_info='$riskinfo', consequence='$consequence', chance='$chance', impact_p='$programme', impact_b='$budget', impact_she='$she', impact_t='$timeimpact', e_cost='$cost', e_cost_tbd='$costtbd', owner='$ownerid', mitigation='$mitigation', risk_rating='$riskrating'
WHERE risk_id='$riskid'");

$updatecomment1 = "";
$updatecomment2 = "";
$updatecomment3 = "";
$updatecomment4 = "";
$updatecomment5 = "";
$updatecomment6 = "";
$updatecomment7 = "";
$updatecomment8 = "";
$updatecomment9 = "";
$updatecomment10 = "";
$updatecomment11 = "";
$updatecomment12 = "";
$changed = 0;

if($oldrecorddetails['risk_info']<>$riskinfo)
{
$updatecomment1 = "
Risk info changed from: " . $oldrecorddetails['risk_info'];
$changed = 1;
}

if($oldrecorddetails['owner']<>$owner)
{
$updatecomment2 = "
Owner changed from: " . $oldrecorddetails['owner'];
$changed = 1;
}

if($oldrecorddetails['consequence']<>$consequence)
{
$updatecomment3 = "
Consequence changed from: " . $oldrecorddetails['consequence'];
$changed = 1;
}

if($oldrecorddetails['impact_p']<>$programme)
{
$updatecomment4 = "
Programme impact changed from: " . $oldrecorddetails['impact_p'];
$changed = 1;
}

if($oldrecorddetails['impact_b']<>$budget)
{
$updatecomment5 = "
Budget impact changed from: " . $oldrecorddetails['impact_b'];
$changed = 1;
}

if($oldrecorddetails['impact_she']<>$she)
{
$updatecomment6 = "
SHE impact changed from: " . $oldrecorddetails['impact_she'];
$changed = 1;
}

if($oldrecorddetails['chance']<>$chance)
{
$updatecomment7 = "
Likelihood changed from: " . $oldrecorddetails['chance'];
$changed = 1;
}

if($oldrecorddetails['risk_rating']<>$riskrating)
{
$updatecomment8 = "
Risk rating changed from: " . $oldrecorddetails['risk_rating'];
$changed = 1;
}

if($oldrecorddetails['impact_t']<>$timeimpact)
{
$updatecomment9 = "
Time impact changed from: " . $oldrecorddetails['impact_t'];
$changed = 1;
}

if($oldrecorddetails['e_cost']<>$cost)
{
$updatecomment10 = "
Estimated cost changed from: " . $oldrecorddetails['e_cost'];
$changed = 1;
}

if($oldrecorddetails['e_cost_tbd']<>$costtbd)
{
	if($costtbd==1)
	{
	$updatecomment11 = "
Costs to be determined changed to: confirmation needed";
	}
	else
	{
	$updatecomment11 = "
Costs to be determined changed to: costs confirmed";
	}
$changed = 1;
}

if($oldrecorddetails['mitigation']<>$mitigation)
{
$updatecomment12 = "
Mitigation measures changed from: " . $oldrecorddetails['mitigation'];
$changed = 1;
}

if($changed>0)
{
$updatecomment = $updatecomment1.$updatecomment2.$updatecomment3.$updatecomment4.$updatecomment5.$updatecomment6.$updatecomment7.$updatecomment8.$updatecomment9.$updatecomment10.$updatecomment11.$updatecomment12;
mysql_query("INSERT INTO audit_trail_risk_log (project_id, risk_id, comment, user_id) VALUES ('$projectid','$riskid','$updatecomment','$userid')");
}

//display the list of daily records
require("load_risk_records.php");
?>


//global variables
var countriesNeedIDNumber = [];
var countriesNeedZipCode = [];

$(document).ready(function(){
	setCountries();
	bindStateInputAndUpdate();
	bindUniform();
	bindPostcode();
	bindCheckbox();
	$(document).on('click', '#invoice_address', function(e){
		bindCheckbox();
	});
});

function setCountries()
{
	if (typeof countries !== 'undefined' && countries)
	{
		var countriesPS = [];
	    for (var i in countries)
		{
			var id_country = countries[i]['id_country'];
			if (typeof countries[i]['states'] !== 'undefined' && countries[i]['states'] && countries[i]['contains_states'])
			{
				countriesPS[id_country] = [];
	    		for (var j in countries[i]['states'])
					countriesPS[parseInt(id_country)].push({'id' : parseInt(countries[i]['states'][j]['id_state']), 'name' : countries[i]['states'][j]['name']});
			}
			if (typeof countries[i]['need_identification_number'] !== 'undefined' && parseInt(countries[i]['need_identification_number']) > 0)
				countriesNeedIDNumber.push(parseInt(countries[i]['id_country']));
			if (typeof countries[i]['need_zip_code'] !== 'undefined' && parseInt(countries[i]['need_zip_code']) > 0)
				countriesNeedZipCode[parseInt(countries[i]['id_country'])] = countries[i]['zip_code_format'];
		}
	}
	countries =  countriesPS;
}

function bindCheckbox()
{
	if ($('#invoice_address:checked').length > 0)
	{
		$('#opc_invoice_address').slideDown('slow');
		if ($('#company_invoice').val() == '')
			$('#vat_number_block_invoice').hide();
		bindUniform();
	}
	else
		$('#opc_invoice_address').slideUp('slow');
}

function bindUniform()
{
	$("select.form-control,input[type='radio'],input[type='checkbox']").uniform();
}

function bindPostcode()
{
	$(document).on('keyup', 'input[name=postcode]', function(e)
	{
		$(this).val($(this).val().toUpperCase());
	});
}

function bindStateInputAndUpdate()
{
	$('.id_state, .dni, .postcode').css({'display':'none'});
	updateState();
	updateNeedIDNumber();
	updateZipCode();

	$(document).on('change', '#id_country', function(e)
	{
		updateState();
		updateNeedIDNumber();
		updateZipCode();
	});

	if ($('#id_country_invoice').length !== 0)
	{
		$(document).on('change', '#id_country_invoice', function(e)
		{
			updateState('invoice');
			updateNeedIDNumber('invoice');
			updateZipCode('invoice');
		});
		updateState('invoice');
		updateNeedIDNumber('invoice');
		updateZipCode('invoice');
	}

	if (typeof idSelectedState !== 'undefined' && idSelectedState)
		$('.id_state option[value=' + idSelectedState + ']').prop('selected', true);
	if (typeof idSelectedStateInvoice !== 'undefined' && idSelectedStateInvoice)
		$('.id_state_invoice option[value=' + idSelectedStateInvoice + ']').prop('selected', true);
}

function updateState(suffix)
{
	$('#id_state' + (typeof suffix !== 'undefined' ? '_' + suffix : '')+' option:not(:first-child)').remove();
	if (typeof countries !== 'undefined')
		var states = countries[parseInt($('#id_country' + (typeof suffix !== 'undefined' ? '_' + suffix : '')).val())];
	if (typeof states !== 'undefined')
	{
		$(states).each(function(key, item){
			$('#id_state' + (typeof suffix !== 'undefined' ? '_' + suffix : '')).append('<option value="' + parseInt(item.id) + '">' + item.name + '</option>');
		});

		$('.id_state' + (typeof suffix !== 'undefined' ? '_' + suffix : '') + ':hidden').fadeIn('slow');
		$('#id_state, #id_state_invoice').uniform();
	}
	else
		$('.id_state' + (typeof suffix !== 'undefined' ? '_' + suffix : '')).fadeOut('fast');
}

function updateNeedIDNumber(suffix)
{
	var idCountry = parseInt($('#id_country' + (typeof suffix !== 'undefined' ? '_' + suffix : '')).val());
	if (typeof countriesNeedIDNumber !== 'undefined' && in_array(idCountry, countriesNeedIDNumber))
	{
		$('.dni' + (typeof suffix !== 'undefined' ? '_' + suffix : '') + ':hidden').fadeIn('slow');
		$('#dni').uniform();
	}
	else
		$('.dni' + (typeof suffix !== 'undefined' ? '_' + suffix : '')).fadeOut('fast');
}

function updateZipCode(suffix)
{
	var idCountry = parseInt($('#id_country' + (typeof suffix !== 'undefined' ? '_' + suffix : '')).val());
	if (typeof countriesNeedZipCode !== 'undefined' && typeof countriesNeedZipCode[idCountry] !== 'undefined')
	{
		$('.postcode' + (typeof suffix !== 'undefined' ? '_' + suffix : '') + ':hidden').fadeIn('slow');
		$('#postcode').uniform();
	}
	else
		$('.postcode'+(typeof suffix !== 'undefined' ? '_' + suffix : '')).fadeOut('fast');
}


webhookr
========

Go-lang HTTP multiplexer


package com.piggymetrics.statistics.service;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.piggymetrics.statistics.domain.Account;
import com.piggymetrics.statistics.domain.Currency;
import com.piggymetrics.statistics.domain.Item;
import com.piggymetrics.statistics.domain.Saving;
import com.piggymetrics.statistics.domain.TimePeriod;
import com.piggymetrics.statistics.domain.timeseries.DataPoint;
import com.piggymetrics.statistics.domain.timeseries.ItemMetric;
import com.piggymetrics.statistics.domain.timeseries.StatisticMetric;
import com.piggymetrics.statistics.repository.DataPointRepository;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.AdditionalAnswers.returnsFirstArg;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;

public class StatisticsServiceImplTest {

	@InjectMocks
	private StatisticsServiceImpl statisticsService;

	@Mock
	private ExchangeRatesServiceImpl ratesService;

	@Mock
	private DataPointRepository repository;

	@Before
	public void setup() {
		initMocks(this);
	}

	@Test
	public void shouldFindDataPointListByAccountName() {
		final List<DataPoint> list = ImmutableList.of(new DataPoint());
		when(repository.findByIdAccount("test")).thenReturn(list);

		List<DataPoint> result = statisticsService.findByAccountName("test");
		assertEquals(list, result);
	}

	@Test(expected = IllegalArgumentException.class)
	public void shouldFailToFindDataPointWhenAccountNameIsNull() {
		statisticsService.findByAccountName(null);
	}

	@Test(expected = IllegalArgumentException.class)
	public void shouldFailToFindDataPointWhenAccountNameIsEmpty() {
		statisticsService.findByAccountName("");
	}

	@Test
	public void shouldSaveDataPoint() {

		/**
		 * Given
		 */

		Item salary = new Item();
		salary.setTitle("Salary");
		salary.setAmount(new BigDecimal(9100));
		salary.setCurrency(Currency.USD);
		salary.setPeriod(TimePeriod.MONTH);

		Item grocery = new Item();
		grocery.setTitle("Grocery");
		grocery.setAmount(new BigDecimal(500));
		grocery.setCurrency(Currency.RUB);
		grocery.setPeriod(TimePeriod.DAY);

		Item vacation = new Item();
		vacation.setTitle("Vacation");
		vacation.setAmount(new BigDecimal(3400));
		vacation.setCurrency(Currency.EUR);
		vacation.setPeriod(TimePeriod.YEAR);

		Saving saving = new Saving();
		saving.setAmount(new BigDecimal(1000));
		saving.setCurrency(Currency.EUR);
		saving.setInterest(new BigDecimal(3.2));
		saving.setDeposit(true);
		saving.setCapitalization(false);

		Account account = new Account();
		account.setIncomes(ImmutableList.of(salary));
		account.setExpenses(ImmutableList.of(grocery, vacation));
		account.setSaving(saving);

		final Map<Currency, BigDecimal> rates = ImmutableMap.of(
				Currency.EUR, new BigDecimal("0.8"),
				Currency.RUB, new BigDecimal("80"),
				Currency.USD, BigDecimal.ONE
		);

		/**
		 * When
		 */

		when(ratesService.convert(any(Currency.class),any(Currency.class),any(BigDecimal.class)))
				.then(i -> ((BigDecimal)i.getArgument(2))
						.divide(rates.get(i.getArgument(0)), 4, RoundingMode.HALF_UP));

		when(ratesService.getCurrentRates()).thenReturn(rates);

		when(repository.save(any(DataPoint.class))).then(returnsFirstArg());

		DataPoint dataPoint = statisticsService.save("test", account);

		/**
		 * Then
		 */

		final BigDecimal expectedExpensesAmount = new BigDecimal("17.8861");
		final BigDecimal expectedIncomesAmount = new BigDecimal("298.9802");
		final BigDecimal expectedSavingAmount = new BigDecimal("1250");

		final BigDecimal expectedNormalizedSalaryAmount = new BigDecimal("298.9802");
		final BigDecimal expectedNormalizedVacationAmount = new BigDecimal("11.6361");
		final BigDecimal expectedNormalizedGroceryAmount = new BigDecimal("6.25");

		assertEquals(dataPoint.getId().getAccount(), "test");
		assertEquals(dataPoint.getId().getDate(), Date.from(LocalDate.now().atStartOfDay().atZone(ZoneId.systemDefault()).toInstant()));

		assertTrue(expectedExpensesAmount.compareTo(dataPoint.getStatistics().get(StatisticMetric.EXPENSES_AMOUNT)) == 0);
		assertTrue(expectedIncomesAmount.compareTo(dataPoint.getStatistics().get(StatisticMetric.INCOMES_AMOUNT)) == 0);
		assertTrue(expectedSavingAmount.compareTo(dataPoint.getStatistics().get(StatisticMetric.SAVING_AMOUNT)) == 0);

		ItemMetric salaryItemMetric = dataPoint.getIncomes().stream()
				.filter(i -> i.getTitle().equals(salary.getTitle()))
				.findFirst().get();

		ItemMetric vacationItemMetric = dataPoint.getExpenses().stream()
				.filter(i -> i.getTitle().equals(vacation.getTitle()))
				.findFirst().get();

		ItemMetric groceryItemMetric = dataPoint.getExpenses().stream()
				.filter(i -> i.getTitle().equals(grocery.getTitle()))
				.findFirst().get();

		assertTrue(expectedNormalizedSalaryAmount.compareTo(salaryItemMetric.getAmount()) == 0);
		assertTrue(expectedNormalizedVacationAmount.compareTo(vacationItemMetric.getAmount()) == 0);
		assertTrue(expectedNormalizedGroceryAmount.compareTo(groceryItemMetric.getAmount()) == 0);

		assertEquals(rates, dataPoint.getRates());

		verify(repository, times(1)).save(dataPoint);
	}
}


"""
Project Euler Problem 86: https://projecteuler.net/problem=86

A spider, S, sits in one corner of a cuboid room, measuring 6 by 5 by 3, and a fly, F,
sits in the opposite corner. By travelling on the surfaces of the room the shortest
"straight line" distance from S to F is 10 and the path is shown on the diagram.
￼
However, there are up to three "shortest" path candidates for any given cuboid and the
shortest route doesn't always have integer length.

It can be shown that there are exactly 2060 distinct cuboids, ignoring rotations, with
integer dimensions, up to a maximum size of M by M by M, for which the shortest route
has integer length when M = 100. This is the least value of M for which the number of
solutions first exceeds two thousand; the number of solutions when M = 99 is 1975.

Find the least value of M such that the number of solutions first exceeds one million.

Solution:
    Label the 3 side-lengths of the cuboid a,b,c such that 1 <= a <= b <= c <= M.
    By conceptually "opening up" the cuboid and laying out its faces on a plane,
    it can be seen that the shortest distance between 2 opposite corners is
    sqrt((a+b)^2 + c^2). This distance is an integer if and only if (a+b),c make up
    the first 2 sides of a pythagorean triplet.

    The second useful insight is rather than calculate the number of cuboids
    with integral shortest distance for each maximum cuboid side-length M,
    we can calculate this number iteratively each time we increase M, as follows.
    The set of cuboids satisfying this property with maximum side-length M-1 is a
    subset of the cuboids satisfying the property with maximum side-length M
    (since any cuboids with side lengths <= M-1 are also <= M). To calculate the
    number of cuboids in the larger set (corresponding to M) we need only consider
    the cuboids which have at least one side of length M. Since we have ordered the
    side lengths a <= b <= c, we can assume that c = M. Then we just need to count
    the number of pairs a,b satisfying the conditions:
        sqrt((a+b)^2 + M^2) is integer
        1 <= a <= b <= M

    To count the number of pairs (a,b) satisfying these conditions, write d = a+b.
    Now we have:
        1 <= a <= b <= M  =>  2 <= d <= 2*M
                                   we can actually make the second equality strict,
                                   since d = 2*M => d^2 + M^2 = 5M^2
                                              => shortest distance = M * sqrt(5)
                                              => not integral.
        a + b = d => b = d - a
                 and a <= b
                  => a <= d/2
                also a <= M
                  => a <= min(M, d//2)

        a + b = d => a = d - b
                 and b <= M
                  => a >= d - M
                also a >= 1
                  => a >= max(1, d - M)

        So a is in range(max(1, d - M), min(M, d // 2) + 1)

    For a given d, the number of cuboids satisfying the required property with c = M
    and a + b = d is the length of this range, which is
        min(M, d // 2) + 1 - max(1, d - M).

    In the code below, d is sum_shortest_sides
                   and M is max_cuboid_size.

"""

from math import sqrt

def solution(limit: int = 1000000) -> int:
    """
    Return the least value of M such that there are more than one million cuboids
    of side lengths 1 <= a,b,c <= M such that the shortest distance between two
    opposite vertices of the cuboid is integral.
    >>> solution(100)
    24
    >>> solution(1000)
    72
    >>> solution(2000)
    100
    >>> solution(20000)
    288
    """
    num_cuboids: int = 0
    max_cuboid_size: int = 0
    sum_shortest_sides: int

    while num_cuboids <= limit:
        max_cuboid_size += 1
        for sum_shortest_sides in range(2, 2 * max_cuboid_size + 1):
            if sqrt(sum_shortest_sides**2 + max_cuboid_size**2).is_integer():
                num_cuboids += (
                    min(max_cuboid_size, sum_shortest_sides // 2)
                    - max(1, sum_shortest_sides - max_cuboid_size)
                    + 1
                )

    return max_cuboid_size

if __name__ == "__main__":
    print(f"{solution() = }")


package gov.va.med.srcalc.web.view.admin;

import gov.va.med.srcalc.domain.model.MultiSelectOption;
import gov.va.med.srcalc.util.ValidationCodes;
import gov.va.med.srcalc.util.ValidationUtils2;

import org.springframework.validation.*;

import com.google.common.collect.ImmutableList;

/**
 * Validates an {@link EditMultiSelectVar} object.
 */
public class EditMultiSelectVarValidator implements Validator
{
    private final EditBaseVarValidator fBaseValidator = new EditBaseVarValidator();

    /**
     * Returns true if (and only if) the given class is {@link EditMultiSelectVar}
     * or a subclass.
     */
    @Override
    public boolean supports(final Class<?> clazz)
    {
        return EditMultiSelectVar.class.isAssignableFrom(clazz);
    }

    /**
     * Validates the given object, using error codes from {@link ValidationCodes}.
     * @param target the object to validate. Must be an instance of {@link
     * EditMultiSelectVar}.
     * @throws ClassCastException if the given object is not an EditMultiSelectVar
     */
    @Override
    public void validate(final Object target, final Errors errors)
    {
        final EditMultiSelectVar editVar = (EditMultiSelectVar)target;
        // First, delegate to EditBaseVarValidator for validating the basic
        // properties.
        fBaseValidator.validate(target, errors);

        // Validate displayType.
        ValidationUtils.rejectIfEmpty(
                errors, "displayType", ValidationCodes.NO_VALUE);

        // Validate options. Use the getTrimmedOptions since that is what
        // getMultiSelectOptions will ultimately use. (That is, trailing blanks
        // are omitted.)
        final ImmutableList<String> options = editVar.getTrimmedOptions();
        if (options.isEmpty())
        {
            errors.rejectValue(
                    "options",
                    ValidationCodes.NO_VALUE,
                    "No options specified.");
        }
        else if (options.size() > editVar.getMaxOptions())
        {
            errors.rejectValue(
                    "options",
                    ValidationCodes.TOO_LONG,
                    new Object[] { editVar.getMaxOptions() },
                    "too many options");
        }
        // Iterate using the index here because we need it to specify the field.
        for (int i = 0; i < options.size(); ++i)
        {
            final String fieldName = String.format("options[%d]", i);
            ValidationUtils.rejectIfEmpty(errors, fieldName, ValidationCodes.NO_VALUE);
            ValidationUtils2.rejectIfTooLong(errors, fieldName, MultiSelectOption.VALUE_MAX);
            ValidationUtils2.rejectIfDoesntMatch(
                    errors, fieldName, MultiSelectOption.VALID_VALUE_PATTERN,
                    new Object[] {MultiSelectOption.VALID_VALUE_CHARACTERS});
        }
    }

}


#import <UIKit/UIKit.h>

@interface UICollectionView (TML)

@end


<?php

namespace Plivo\Resources\Message;

use Plivo\Exceptions\PlivoValidationException;
use Plivo\Exceptions\PlivoRestException;
use Plivo\Exceptions\PlivoResponseException;
use Plivo\Util\ArrayOperations;
use Plivo\MessageClient;
use Plivo\Resources\ResourceInterface;

/**
 * Class MessageInterface
 * @package Plivo\Resources\Message
 */
class MessageInterface extends ResourceInterface
{
    /**
     * MessageInterface constructor.
     * @param MessageClient $plivoClient
     * @param $authId
     */
    public function __construct(MessageClient $plivoClient, $authId)
    {
        parent::__construct($plivoClient);
        $this->pathParams = [
            'authId' => $authId
        ];
        $this->uri = "Account/".$authId."/Message/";
    }

    /**
     * @param $messageUuid
     * @return Message
     * @throws PlivoValidationException
     */
    public function get($messageUuid)
    {
        if (ArrayOperations::checkNull([$messageUuid])) {
            throw
            new PlivoValidationException(
                'message uuid is mandatory');
        }

        $response = $this->client->fetch(
            $this->uri . $messageUuid .'/',
            []
        );
        // return the object for chain method
        if ($response->getStatusCode() == 200){
            return new Message(
            $this->client, $response->getContent(),
            $this->pathParams['authId'], $this->uri);
        }
        return json_encode($response->getContent(), JSON_FORCE_OBJECT);
    }

    /**
     * Return a list of messages
     * @param array $optionalArgs
     *   + Valid arguments
     *   + [string] :subaccount - The id of the subaccount, if message details of the subaccount is needed.
     *   + [string] :message_direction - Filter the results by message direction. The valid inputs are inbound and outbound.
     *   + [string] :message_time  - Filter out messages according to the time of completion. The filter can be used in the following five forms:
     *
 message_time: The format expected is YYYY-MM-DD HH:MM[:ss[.uuuuuu]]. Eg:- To get all messages that were sent/received at 2012-03-21 11:47[:30], use message_time=2012-03-21 11:47[:30]
     *
 message_time\__gt: gt stands for greater than. The format expected is YYYY-MM-DD HH:MM[:ss[.uuuuuu]]. Eg:- To get all messages that were sent/received after 2012-03-21 11:47, use message_time\__gt=2012-03-21 11:47
     *
 message_time\__gte: gte stands for greater than or equal. The format expected is YYYY-MM-DD HH:MM[:ss[.uuuuuu]]. Eg:- To get all messages that were sent/received after or exactly at 2012-03-21 11:47[:30], use message_time\__gte=2012-03-21 11:47[:30]
     *
 message_time\__lt: lt stands for lesser than. The format expected is YYYY-MM-DD HH:MM[:ss[.uuuuuu]]. Eg:- To get all messages that were sent/received before 2012-03-21 11:47, use message_time\__lt=2012-03-21 11:47
     *
 message_time\__lte: lte stands for lesser than or equal. The format expected is YYYY-MM-DD HH:MM[:ss[.uuuuuu]]. Eg:- To get all messages that were sent/received before or exactly at 2012-03-21 11:47[:30], use message_time\__lte=2012-03-21 11:47[:30]
     *
 Note: The above filters can be combined to get messages that were sent/received in a particular time range. The timestamps need to be UTC timestamps.
     *   + [string] :message_state Status value of the message, is one of "queued", "sent", "failed", "delivered", "undelivered" or "rejected"
     *   + [int] :limit Used to display the number of results per page. The maximum number of results that can be fetched is 20.
     *   + [int] :offset Denotes the number of value items by which the results should be offset. Eg:- If the result contains a 1000 values and limit is set to 10 and offset is set to 705, then values 706 through 715 are displayed in the results. This parameter is also used for pagination of the results.
     *   + [string] :error_code Delivery Response code returned by the carrier attempting the delivery. See Supported error codes {https://www.plivo.com/docs/api/message/#standard-plivo-error-codes}.
     *   + [string] : powerpack_id - Filter the results by Powerpack ID.
     * @return MessageList
     */
    protected function getList($optionalArgs = [])
    {
        $response = $this->client->fetch(
            $this->uri,
            $optionalArgs
        );
        if(!array_key_exists("error", $response->getContent())) {
            $messages = [];
            foreach ($response->getContent()['objects'] as $message) {
                $newMessage = new Message($this->client, $message, $this->pathParams['authId'], $this->uri);
                array_push($messages, $newMessage);
            }
            return new MessageList($this->client, $response->getContent()['meta'], $messages);
        } else {
            throw new PlivoResponseException(
                $response->getContent()['error'],
                0,
                null,
                $response->getContent(),
                $response->getStatusCode()
            );
        }
    }

    /**
     * Send a message
     *
     * @param string $src
     * @param array $dst
     * @param string $text
     * @param array $optionalArgs
     *   + Valid arguments
     *   + [string] :type - The type of message. Should be `sms` or `mms`. Defaults to `sms`.
     *   + [string] :url - The URL to which with the status of the message is sent. The following parameters are sent to the URL:
     *
 To - Phone number of the recipient
     *
 From - Phone number of the sender
     *
 Status - Status of the message including "queued", "sent", "failed", "delivered", "undelivered" or "rejected"
     *
 MessageUUID - The unique ID for the message
     *
 ParentMessageUUID - ID of the parent message (see notes about long SMS below)
     *
 PartInfo - Specifies the sequence of the message (useful for long messages split into multiple text messages; see notes about long SMS below)
     *
 TotalRate - Total rate per sms
     *
 TotalAmount - Total cost of sending the sms (TotalRate * Units)
     *
 Units - Number of units into which a long SMS was split
     *
 MCC - Mobile Country Code (see here {https://en.wikipedia.org/wiki/Mobile_country_code} for more details)
     *
 MNC - Mobile Network Code (see here {https://en.wikipedia.org/wiki/Mobile_country_code} for more details)
     *
 ErrorCode - Delivery Response code returned by the carrier attempting the delivery. See Supported error codes {https://www.plivo.com/docs/api/message/#standard-plivo-error-codes}.
     *   + [string] :method - The method used to call the url. Defaults to POST.
     *   + [string] :log - If set to false, the content of this message will not be logged on the Plivo infrastructure and the dst value will be masked (e.g., 141XXXXX528). Default is set to true.
     * [list] : media_urls - If your sending mms message, you can specify the media urls like ['https://yourmedia_urls/test.jpg','https://test.com/test.gif']
     * @return MessageCreateResponse output
     * @throws PlivoValidationException,PlivoResponseException
     */
    //
    public function create($src=null, $dst=null, $text=null,array $optionalArgs = [], $powerpackUUID = null)
    {
        if (is_array($src))
        {
            $optionalArgs = array_merge($src, $optionalArgs);
            $src = isset($optionalArgs['src']) ? $optionalArgs['src'] : null;
            $dst = isset($optionalArgs['dst']) ? $optionalArgs['dst'] : null;
            $text = isset($optionalArgs['text']) ? $optionalArgs['text'] : null;
            $powerpackUUID = isset($optionalArgs['powerpackUUID']) ? $optionalArgs['powerpackUUID'] : null;
        }
        if (is_array($dst)){
            $mandatoryArgs = [
                'dst' => implode('<', $dst),
            ];
        }
        else {
            $mandatoryArgs = ['dst' => $dst ];
        }

        if (ArrayOperations::checkNull($mandatoryArgs)) {
            throw new PlivoValidationException(
                "Mandatory parameters cannot be null");
        }

        if (is_null($src) &&  is_null($powerpackUUID)) {
            throw new PlivoValidationException(
                "Specify either powerpack_uuid or src in request params to send a message."
            );
        }

        if (!is_null($src) && !is_null($powerpackUUID)) {
            throw new PlivoValidationException(
                "Both powerpack_uuid and src cannot be specified. Specify either powerpack_uuid or src in request params to send a message."
            );
        }

        $response = $this->client->update(
            $this->uri,
            array_merge($mandatoryArgs, $optionalArgs, ['src' => $src, 'powerpack_uuid' => $powerpackUUID, 'text' => $text])
        );

        $responseContents = $response->getContent();

        if(!array_key_exists("error",$responseContents)){
            if(array_key_exists("invalid_number", $responseContents)){
                return new MessageCreateResponse(
                    $responseContents['message'],
                    $responseContents['message_uuid'],
                    $responseContents['api_id'],
                    $response->getStatusCode(),
                    $responseContents['invalid_number']
                );
            }
            else{
                return new MessageCreateResponse(
                    $responseContents['message'],
                    $responseContents['message_uuid'],
                    $responseContents['api_id'],
                    $response->getStatusCode(),
                    []
                );
            }
        } else {
            throw new PlivoResponseException(
                $responseContents['error'],
                0,
                null,
                $response->getContent(),
                $response->getStatusCode()

            );
        }
    }

}


using System;
using System.Collections.Generic;
using System.Linq;
using SlimsteMens.Model.Entities;
using SlimsteMens.Model.Repositories;

namespace SlimsteMens.Model.Services
{
    public class GalleryRoundService
    {
        private readonly IRepository<Gallery> _galleryRepository;
        private readonly Game _game;
        protected int GalleryNr;
        public int Correct { get; set; }
        public IList<Gallery> Galleries { get; set; }
        public int SecondsOnCorrect { get; set; }
        public IList<TurnType> PlayedAGallery { get; set; }
        public IList<TurnType> PlayedCurrentGallery { get; set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="GalleryRoundService" /> class.
        /// </summary>
        /// <param name="secondsOnCorrect">The seconds on correct.</param>
        /// <param name="galleryRepository">The gallery repository.</param>
        /// <param name="game">The game.</param>
        /// <exception cref="System.ArgumentNullException">
        /// galleryRepository
        /// or
        /// game
        /// </exception>
        /// <exception cref="System.ArgumentException"></exception>
        public GalleryRoundService(int secondsOnCorrect, IRepository<Gallery> galleryRepository, Game game)
        {
            if (galleryRepository == null) throw new ArgumentNullException("galleryRepository");
            if (game == null) throw new ArgumentNullException("game");

            SecondsOnCorrect = secondsOnCorrect;
            _galleryRepository = galleryRepository;
            _game = game;
            PlayedAGallery = new List<TurnType>();
            PlayedCurrentGallery = new List<TurnType>();
            GalleryNr = 0;
            InitializeGalleries();
        }

        /// <summary>
        /// Retrieves the Next gallery.
        /// </summary>
        /// <returns></returns>
        public Gallery NextGallery()
        {
            if (GalleryNr >= Galleries.Count)
                return null;

            TurnType turn = _game.NextAndSetTurnByLowestTime(PlayedAGallery);
            Correct = 0;
            if (Galleries.Count == 0)
                return null;

            PlayedCurrentGallery = new List<TurnType>();
            PlayedAGallery.Add(turn);
            GalleryNr++;

            return Galleries[GalleryNr - 1];
        }

        private void InitializeGalleries()
        {
            List<long> ids;

            if (_galleryRepository.AsQueryable().Count(c => c.GalleryQuestions.All(g => !g.Played)) >= 3)
            {
                ids = _galleryRepository.AsQueryable().Where(c => c.GalleryQuestions.All(g => !g.Played)).Select(s => s.Id).Shuffle().Take(3).ToList();
            }
            else
            {
                ids = _galleryRepository.AsQueryable().Select(s => s.Id).Shuffle().Take(3).ToList();
            }

            Galleries = _galleryRepository.Query(g => ids.Any(id => id == g.Id)).Shuffle().ToList();

            if (Galleries.Count < 3)
                throw new InvalidOperationException("Need 3 galleries to continue");

            Galleries.ToList().ForEach(g => g.GalleryQuestions.ToList().ForEach(gq => gq.Played = true));
        }
    }
}


Reflectors
==========

[![documentation](http://img.ateliers-pierrot-static.fr/read-the-doc.svg)](http://docs.ateliers-pierrot.fr/reflectors/)
[![Code Climate](http://codeclimate.com/github/atelierspierrot/reflectors/badges/gpa.svg)](http://codeclimate.com/github/atelierspierrot/reflectors)

Some PHP Reflectors objects to complete the [internal Reflection](http://php.net/manual/book.reflection.php).
All objects defined in this package implement the [\Reflector interface](http://php.net/manual/class.reflector.php)
and generate a simple output to keep compliant with existing internal reflection objects.

Installation
------------

For a complete information about how to install this package and load its namespace,
please have a look at [our *USAGE* documentation](http://github.com/atelierspierrot/atelierspierrot/blob/master/USAGE.md).

If you are a [Composer](http://getcomposer.org/) user, just add the package to the
requirements of your project's `composer.json` manifest file:

```json
"atelierspierrot/reflectors": "dev-master"
```

You can use a specific release or the latest release of a major version using the appropriate
[version constraint](http://getcomposer.org/doc/01-basic-usage.md#package-versions).

Author & License
----------------

>    Reflectors

>    http://github.com/atelierspierrot/reflectors

>    Copyright (c) 2015-2016 Pierre Cassat and contributors

>    Licensed under the Apache 2 license.

>    http://www.apache.org/licenses/LICENSE-2.0

>    ----

>    Les Ateliers Pierrot - Paris, France

>    <http://www.ateliers-pierrot.fr/> - <contact@ateliers-pierrot.fr>