text:
package com.yahoo.gondola.impl;

import com.yahoo.gondola.Config;
import com.yahoo.gondola.Gondola;
import com.yahoo.gondola.LogEntry;
import com.yahoo.gondola.Storage;
import com.yahoo.gondola.GondolaException;

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

import java.io.File;
import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * This is a hack of a storage implementation used to test performance.
 * It cannot be used to test HA.
 * It only stores the currentTerm, votedFor, lastTerm, and lastIndex values.
 * Everything else is just made up.
 */
public class FakeStorage implements Storage {
    Logger logger = LoggerFactory.getLogger(FakeStorage.class);
    Config config;

    Queue<LogEntry> pool = new ConcurrentLinkedQueue<>();
    Map<Integer, Member> members = new ConcurrentHashMap<>();

    File file;
    RandomAccessFile raFile;
    int avgCommandSize = 8;

    // Config variables
    int maxCommandSize;

    public FakeStorage(Gondola gondola, String hostId) throws GondolaException {
        logger.info("Initialize FakeStorage");
        this.config = gondola.getConfig();
        config.registerForUpdates(config1 -> {
            maxCommandSize = config1.getInt("raft.command_max_size");
        });

        // TODO: remove the hardcode. Need to figure out how to add properties to config, like JDBC.
        file = new File("/tmp/gondola-" + hostId + ".dat");

        // Read saved information
        if (file.exists()) {
            try {
                raFile = new RandomAccessFile(file, "rws");
                while (raFile.getFilePointer() < raFile.length()) {
                    String line = raFile.readUTF();
                    logger.info("FakeStorage {}: {}", file, line);
                    String[] parts = line.split(",");
                    Member m = new Member(Integer.parseInt(parts[0]),
                            Integer.parseInt(parts[1]),
                            Integer.parseInt(parts[2]),
                            Integer.parseInt(parts[3]),
                            Integer.parseInt(parts[4]),
                            Integer.parseInt(parts[5]));
                    members.put(m.id, m);
                }
            } catch (Exception e) {
                logger.warn("Ignoring error", e);
            }
        } else {
            try {
                raFile = new RandomAccessFile(file, "rws");
            } catch (FileNotFoundException e) {
                throw new GondolaException(e);
            }
        }
        new Writer().start();
    }

    @Override
    public boolean isOperational() {
        return true;
    }

    @Override
    public String getAddress(int memberId) throws GondolaException {
        return getMember(memberId).address;
    }

    @Override
    public void setAddress(int memberId, String address) throws GondolaException {
        Member member = getMember(memberId);
        member.address = address;
    }

    @Override
    public void saveVote(int memberId, int currentTerm, int votedFor) throws GondolaException {
        Member member = getMember(memberId);
        member.currentTerm = currentTerm;
        member.votedFor = votedFor;
    }

    @Override
    public int getCurrentTerm(int memberId) throws GondolaException {
        return getMember(memberId).currentTerm;
    }

    @Override
    public int getVotedFor(int memberId) throws GondolaException {
        return getMember(memberId).votedFor;
    }

    @Override
    public int getMaxGap(int memberId) throws GondolaException {
        return getMember(memberId).maxGap;
    }

    @Override
    public void setMaxGap(int memberId, int maxGap) throws GondolaException {
        getMember(memberId).maxGap = maxGap;
    }

    @Override
    public String getPid(int memberId) throws GondolaException {
        return getMember(memberId).pid;
    }

    @Override
    public void setPid(int memberId, String pid) throws GondolaException {
        getMember(memberId).pid = pid;
    }

    @Override
    public int count(int memberId) throws GondolaException {
        return getMember(memberId).lastIndex;
    }

    @Override
    public void appendLogEntry(int memberId, int term, int index,
                               byte[] buffer, int bufferOffset, int bufferLen) throws GondolaException {
        if (avgCommandSize == 0) {
            avgCommandSize = bufferLen;
        } else {
            avgCommandSize = (avgCommandSize + bufferLen) / 2;
        }
        Member m = getMember(memberId);
        m.lastTerm = term;
        m.lastIndex = Math.max(m.lastIndex, index);
    }

    @Override
    public void delete(int memberId, int index) throws GondolaException {
        Member m = getMember(memberId);
        m.lastIndex = Math.min(m.lastIndex, index - 1);
    }

    @Override
    public boolean hasLogEntry(int memberId, int term, int index) throws GondolaException {
        Member member = getMember(memberId);
        return index <= member.lastIndex;
    }

    @Override
    public LogEntry getLogEntry(int memberId, int index) throws GondolaException {
        Member m = getMember(memberId);
        if (index > m.lastIndex) {
            return null;
        }
        LogEntry le = checkout();
        le.term = 1;
        le.index = index;
        le.size = avgCommandSize;
        return le;
    }

    @Override
    public LogEntry getLastLogEntry(int memberId) throws GondolaException {
        Member m = getMember(memberId);
        LogEntry le = checkout();
        le.term = 1;
        le.index = m.lastIndex;
        le.size = avgCommandSize;
        return le;
    }

    @Override
    public void checkin(LogEntry entry) {
        pool.add(entry);
    }

    @Override
    public void start() {

    }

    @Override
    public boolean stop() {
        return true;
    }

    LogEntry checkout() {
        LogEntry le = pool.poll();
        if (le == null) {
            le = new LogEntry(this, maxCommandSize);
        }
        return le;
    }

    class Member {
        int id = -1;
        int currentTerm = 1;
        int votedFor = -1;
        int maxGap = 0;
        int lastTerm = 0;
        int lastIndex = 0;
        String address = null;
        String pid = null;

        Member(int id) {
            this.id = id;
        }

        Member(int id, int currentTerm, int votedFor, int maxGap, int lastTerm, int lastIndex) {
            this.id = id;
            this.currentTerm = currentTerm;
            this.votedFor = votedFor;
            this.maxGap = maxGap;
            this.lastTerm = lastTerm;
            this.lastIndex = lastIndex;
        }

        public String toString() {
            return String.format("%d,%d,%d,%d,%d,%d", id, currentTerm, votedFor, maxGap, lastTerm, lastIndex);
        }
    }

    Member getMember(int memberId) throws GondolaException {
        Member member = members.get(memberId);
        if (member == null) {
            member = new Member(memberId);
            members.putIfAbsent(memberId, member);
        }
        return member;
    }

    class Writer extends Thread {
        public void run() {
            while (true) {
                int i = 0;
                try {
                    raFile.seek(0);
                    for (Map.Entry<Integer, Member> e : members.entrySet()) {
                        Member m = e.getValue();
                        raFile.writeUTF(m.toString());
                    }
                    Thread.sleep(100);
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
    }
}


text:
namespace BalloonsPop.Game.Commands
{
    using BalloonsPop.Game.Commands.Contracts;

    public abstract class Command : ICommand
    {
        public abstract void Execute();
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

class Google_Service_Compute_SignedUrlKey extends Google_Model
{
  public $keyName;
  public $keyValue;

  public function setKeyName($keyName)
  {
    $this->keyName = $keyName;
  }
  public function getKeyName()
  {
    return $this->keyName;
  }
  public function setKeyValue($keyValue)
  {
    $this->keyValue = $keyValue;
  }
  public function getKeyValue()
  {
    return $this->keyValue;
  }
}


text:
dojo.provide("dwa.lv.eventQueue");

dojo.require("dwa.lv.widgetListener");

dojo.declare(
	"dwa.lv.eventQueue",
	null,
{
	soQueue: 0,

	constructor: function(){
		this.oQueue = {};
	},
	attach: function(oWidget, sType, fStopPropagation){
		var oElem = dojo.doc.getElementById(oWidget.sId);
		var sTarget = oElem.getAttribute('com_ibm_dwa_ui_widget_eventQueueTarget');
		var asTarget = sTarget ? sTarget.split(' ') : [oWidget.sId];
		var sClass = oElem.getAttribute('com_ibm_dwa_ui_widget_class');
		var asClass = sClass ? sClass.split(' ') : [];
		var sName = oWidget.sId + ':' + sClass;
		var oQueue = this.oQueue;

		function dojo_ui_eventQueue_handleEvent(ev){
		 if( dojo.isIE ){
			var oEvent = document.createEventObject(ev);
			oQueue[sName] = [oEvent].concat(oQueue[sName] ? oQueue[sName] : []);
		 }else{ // I
			var oEvent = document.createEvent('MouseEvents');
			oEvent.initMouseEvent(ev.type, ev.bubbles, ev.cancelable, window, ev.detail, ev.screenX, ev.screenY,
			 ev.clientX, ev.clientY, ev.ctrlKey, ev.altKey, ev.shiftKey, ev.metaKey, ev.button, null);
			oQueue[sName] = [oEvent, ev.target].concat(oQueue[sName] ? oQueue[sName] : []);
		 } // end - GS
			for(var i=0;i<asClass.length;i++)
				new dwa.lv.widgetListener(oWidget.sId, asClass[i] + ':handleEvent');
			if (fStopPropagation) {
				(dojo.isIE ? (ev.cancelBubble = true) : (dojo.isMozilla ? (ev.stopPropagation()) : (ev.stopPropagation()) ) );
		// #XMXL7Z65M6: Firefox 3.6 also needs this to avoid default context menu.
		 if(dojo.isMozilla || dojo.isWebKit){
				(dojo.isIE ? (ev.returnValue = false) : (dojo.isMozilla ? (ev.preventDefault()) : (ev.preventDefault()) ) );
		 } // end - S
				return false;
			}
		}

		for (var i = 0; i < asTarget.length; i++)
			(dojo.isIE ? (dojo.doc.getElementById(asTarget[i]).attachEvent("on" + sType, dojo_ui_eventQueue_handleEvent)) : (dojo.isMozilla ? (dojo.doc.getElementById(asTarget[i]).addEventListener(sType, dojo_ui_eventQueue_handleEvent, false)) : (dojo.doc.getElementById(asTarget[i]).addEventListener(sType, dojo_ui_eventQueue_handleEvent, false)) ) );
	}
});

dwa.lv.eventQueue.get = function(){
	if( dwa.lv.eventQueue.prototype.soQueue === 0 ){
		dwa.lv.eventQueue.prototype.soQueue = new dwa.lv.eventQueue;
	}
	return dwa.lv.eventQueue.prototype.soQueue
};


text:
package display;

import javax.swing.*;
import java.awt.*;

public class Display {
    private String name;
    private int width;
    private int height;

    public JFrame frame;
    private Canvas canvas;

    // public JTextField playerName;

    public Display (String name , int width , int height ) {
        this.name = name;
        this.width = width;
        this.height = height;

        createDisplay();
    }

    private void createDisplay() {
        this.frame = new JFrame(name);
        this.frame.setPreferredSize(new Dimension(width, height));
        this.frame.setMinimumSize(new Dimension(width, height));
        this.frame.setMaximumSize(new Dimension(width, height));
        this.frame.setVisible(true);
        this.frame.setFocusable(true);
        this.frame.setResizable(false);
        this.frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        this.frame.setLocationRelativeTo(null);

        this.canvas = new Canvas();
        this.canvas.setPreferredSize(new Dimension(width, height));
        this.canvas.setMinimumSize(new Dimension(width, height));
        this.canvas.setMaximumSize(new Dimension(width, height));
        this.canvas.setFocusable(true);
        // playerName = new JTextField(30);
        // playerName.setBounds(200, 200, 100, 10);
        // playerName.setEditable(true);
        // playerName.setVisible(false);
        // frame.add(playerName);
        this.frame.add(this.canvas);
        this.frame.pack();

    }

    // public void hideTextField(){
    //     playerName.setVisible(false);
    // }

    public Canvas getCanvas() {
        return canvas;
    }
}


text:
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
using Aop.Api.Domain;

namespace Aop.Api.Response
{
    /// <summary>
    /// AlipayEcapiprodDrawndnRepaymentrecordQueryResponse.
    /// </summary>
    public class AlipayEcapiprodDrawndnRepaymentrecordQueryResponse : AopResponse
    {
        /// <summary>
        /// 还款流水
        /// </summary>
        [XmlArray("repayment_records")]
        [XmlArrayItem("repayment_records")]
        public List<RepaymentRecords> RepaymentRecords { get; set; }

        /// <summary>
        /// 唯一标识这次请求
        /// </summary>
        [XmlElement("request_id")]
        public string RequestId { get; set; }
    }
}


text:
package org.springframework.boot.autoconfigure.data;

import java.lang.annotation.Annotation;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.boot.autoconfigure.AutoConfigurationPackages;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.StandardAnnotationMetadata;
import org.springframework.data.repository.config.AnnotationRepositoryConfigurationSource;
import org.springframework.data.repository.config.RepositoryConfigurationDelegate;
import org.springframework.data.repository.config.RepositoryConfigurationExtension;
import org.springframework.data.util.Streamable;

/**
 * Base {@link ImportBeanDefinitionRegistrar} used to auto-configure Spring Data
 * Repositories.
 *
 * @author Phillip Webb
 * @author Dave Syer
 * @author Oliver Gierke
 */
public abstract class AbstractRepositoryConfigurationSourceSupport
		implements BeanFactoryAware, ImportBeanDefinitionRegistrar, ResourceLoaderAware,
		EnvironmentAware {

	private ResourceLoader resourceLoader;

	private BeanFactory beanFactory;

	private Environment environment;

	@Override
	public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata,
			BeanDefinitionRegistry registry) {
		new RepositoryConfigurationDelegate(getConfigurationSource(registry),
				this.resourceLoader, this.environment).registerRepositoriesIn(registry,
						getRepositoryConfigurationExtension());
	}

	private AnnotationRepositoryConfigurationSource getConfigurationSource(
			BeanDefinitionRegistry beanDefinitionRegistry) {
		StandardAnnotationMetadata metadata = new StandardAnnotationMetadata(
				getConfiguration(), true);
		return new AnnotationRepositoryConfigurationSource(metadata, getAnnotation(),
				this.resourceLoader, this.environment, beanDefinitionRegistry) {
			@Override
			public Streamable<String> getBasePackages() {
				return AbstractRepositoryConfigurationSourceSupport.this
						.getBasePackages();
			}
		};
	}

	protected Streamable<String> getBasePackages() {
		return Streamable.of(AutoConfigurationPackages.get(this.beanFactory));
	}

	/**
	 * The Spring Data annotation used to enable the particular repository support.
	 * @return the annotation class
	 */
	protected abstract Class<? extends Annotation> getAnnotation();

	/**
	 * The configuration class that will be used by Spring Boot as a template.
	 * @return the configuration class
	 */
	protected abstract Class<?> getConfiguration();

	/**
	 * The {@link RepositoryConfigurationExtension} for the particular repository support.
	 * @return the repository configuration extension
	 */
	protected abstract RepositoryConfigurationExtension getRepositoryConfigurationExtension();

	@Override
	public void setResourceLoader(ResourceLoader resourceLoader) {
		this.resourceLoader = resourceLoader;
	}

	@Override
	public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
		this.beanFactory = beanFactory;
	}

	@Override
	public void setEnvironment(Environment environment) {
		this.environment = environment;
	}

}


text:
<?php

/*
 * This file is part of the overtrue/wechat.
 *
 * (c) overtrue <i@overtrue.me>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

/**
 * QRCodeServiceProvider.php.
 *
 * Part of Overtrue\WeChat.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @author    overtrue <i@overtrue.me>
 * @copyright 2015
 *
 * @link      https://github.com/overtrue/wechat
 * @link      http://overtrue.me
 */
namespace EasyWeChat\Foundation\ServiceProviders;

use EasyWeChat\QRCode\QRCode;
use Pimple\Container;
use Pimple\ServiceProviderInterface;

/**
 * Class QRCodeServiceProvider.
 */
class QRCodeServiceProvider implements ServiceProviderInterface
{
    /**
     * Registers services on the given container.
     *
     * This method should only be used to configure services and parameters.
     * It should not get services.
     *
     * @param Container $pimple A container instance
     */
    public function register(Container $pimple)
    {
        $pimple['qrcode'] = function ($pimple) {
            return new QRCode($pimple['access_token']);
        };
    }
}


text:
JS
==

js hints and hacks

stringToColor.js

`stringToColor` function returns the same color for the same string.

Can be used as a background color for avatar with white text on it, because it does not return too much light colors.

onload-event.js

Little script for run event after all images loaded.

jquery.creditСardFormat.js

jQuery plugin for checking input field by Credit Card Format like [xxxx-xxxx-xxxx-xxxx], which add and delete hyphen.

2 unnecessary options:

positionArray - array of hyphen after specified numeral

lengthArray length of credit card number without hyphen

By default:

positionArray : [4, 8, 12]
lengthArray   : 16

Call:

$('input').creditСardFormat();

jquery.currencyFormat.js

jQuery plugin for making Currency field with "$" and commas like: $12,345.

It is wrapping input in <div> and adding hidden input with same name (for sending to server just a number).

Call:

$('input').currencyFormat();

ellipsis.js

jQuery plugin for cutting text and adding ellipsis at the end.

Require DIV with "overflow: hidden" style and fixed height and tag P inside.

Call:

$('.ellipsis').addEllipsis();

jquery.popup.js

jQuery plugin for creating popup near element target: by showing hidden popup or loading by ajax.

Use:

[data-popup-link='name'] - use for target with name as identifier

[data-popup-content='name'] - popup content, be default should be hidden

[data-popup-url='url'] - set url for ajax or 'href'

[data-popup-close='name'] - add close button on popup

Call:

$('[data-popup-link]').popup();


text:
#!/bin/sh

# /*!
#     Utilitaire de base de données
#     @author Adrien Desfourneaux <adrien.desfourneaux@gmail.com>
#  */

DBNAME=suiviprojet

# /*!
#     Change de répertoire vers le répertoire du module
#  */
cdmodulepath () {
  if [ -z $SCRIPTPATH ]; then
    SCRIPTPATH=$( cd "$(dirname "$0")" ; pwd -P )
    cd $SCRIPTPATH/..
  fi
}

# /*!
#     Affiche un message de confirmation
#  */
confirm () {
  while true; do
      read -p "Continuer ? " on
      case $on in
          [Oo]* ) break;;
          [Nn]* ) exit;;
          * ) echo "Repondre par oui ou non.";;
      esac
  done
}

# /*!
#     Cré les bases de données de test et de développement du module
#  */
create () {
  cdmodulepath

  if [ -f data/$DBNAME.sqlite ]; then
    printf "Attention! Lancer ce script va supprimer la base de données de développement $DBNAME ainsi que tout son contenu.\n"
    confirm
    rm data/$DBNAME.sqlite
  fi

  cat data/zfcuser.sqlite.sql \
      data/bjyauthorize.sqlite.sql \
      data/dzuser.sqlite.sql \
      data/dzproject.sqlite.sql \
      data/dztask.sqlite.sql \
      data/suiviprojet.sqlite.sql \
      | sqlite3 data/suiviprojet.sqlite

  chmod g+w data/$DBNAME.sqlite

  if [ ! -f tests/_data/$DBNAME.sqlite ]; then
    sqlite3 tests/_data/$DBNAME.sqlite ""
    chmod g+w tests/_data/$DBNAME.sqlite
  fi

  cat data/zfcuser.sqlite.sql \
      data/bjyauthorize.sqlite.sql \
      data/dzuser.sqlite.sql \
      data/dzproject.sqlite.sql \
      data/dztask.sqlite.sql \
      data/suiviprojet.sqlite.sql \
      > tests/_data/dump.sql
}

# /*!
#     Remplit la base de données de développement du module
#     avec des données de test
#  */
dump () {
  create
  cat data/dzuser.dump.sqlite.sql \
      data/dzproject.dump.sqlite.sql \
      data/dztask.dump.sqlite.sql \
      data/suiviprojet.dump.sqlite.sql \
      | sqlite3 data/suiviprojet.sqlite;
}

# /*!
#     Restaure les permissions des base de données
#     de test et de développement du module
#     ainsi que celle de production
#  */
perm () {
    cdmodulepath

    chmod 770 data
    if [ -f data/$DBNAME.sqlite ]; then chmod 660 data/$DBNAME.sqlite; fi
    if [ -d tests/_data ]; then chmod 770 tests/_data; fi
    if [ -f tests/_data/$DBNAME.sqlite ]; then chmod 660 tests/_data/$DBNAME.sqlite; fi
    if [ -d ../../data ]; then chmod 770 ../../data; fi
    if [ -f ../../data/suivi-projet.sqlite ]; then chmod 660 ../../data/suivi-projet.sqlite; fi
}

# /*!
#     Copie la base de données de développement du module
#     en base de données de production de l'application
#  */
prod ()
{
    cdmodulepath;

    if [ -f ../../data/suivi-projet.sqlite ]; then
        printf "Attention! Vous êtes sur le point de supprimer la base de données de production de l'application suivi-projet!\n";
        confirm;

        timestamp=$(date +%s)

        cp ../../data/suivi-projet.sqlite ../../data/suivi-projet_$timestamp.sqlite
        printf "Un copie de sauvegarde de la base de données de production a été faite.\n"
        printf "/data/suivi-projet_$timestamp.sqlite";
    fi

    cp data/suiviprojet.sqlite ../../data/suivi-projet.sqlite
    chmod g+w ../../data/suivi-projet.sqlite
}

# /*!
#     Affiche un message d'aide
#  */
help () {
  printf "Usage: db.sh [action]\n"
  printf "help\taffiche cette aide\n"
  printf "create\tcre la base de donnees\n"
  printf "dump\tcre la base de donnees et y met les données de développement\n"
  printf "perm\trestaure les permissions des bases de données de test, développement et production\n"
  printf "prod\tcopie la bdd de développement du module en bdd de production de l'application\n"
}

if [ $# -eq 0 ]; then help
elif [ "$1" = "help" ]; then help
elif [ "$1" = "create" ]; then create
elif [ "$1" = "dump" ]; then dump
elif [ "$1" = "perm" ]; then perm
elif [ "$1" = "prod" ]; then prod
fi


text:
/*
Language: Dust
Requires: xml.js
Author: Michael Allen <michael.allen@benefitfocus.com>
Description: Matcher for dust.js templates.
*/

function(hljs) {
  var EXPRESSION_KEYWORDS = 'if eq ne lt lte gt gte select default math sep';
  return {
    aliases: ['dst'],
    case_insensitive: true,
    subLanguage: 'xml', subLanguageMode: 'continuous',
    contains: [
      {
        className: 'expression',
        begin: '{', end: '}',
        relevance: 0,
        contains: [
          {
            className: 'begin-block', begin: '\#[a-zA-Z\-\ \.]+',
            keywords: EXPRESSION_KEYWORDS
          },
          {
            className: 'string',
            begin: '"', end: '"'
          },
          {
            className: 'end-block', begin: '\\\/[a-zA-Z\-\ \.]+',
            keywords: EXPRESSION_KEYWORDS
          },
          {
            className: 'variable', begin: '[a-zA-Z\-\.]+',
            keywords: EXPRESSION_KEYWORDS,
            relevance: 0
          }
        ]
      }
    ]
  };
}


text:
package emr

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

// EmrResourceInfoList is a nested struct in emr response
type EmrResourceInfoList struct {
	EmrResourceInfo []EmrResourceInfo `json:"EmrResourceInfo" xml:"EmrResourceInfo"`
}


text:
package org.gradle.api.artifacts.repositories;

import org.gradle.api.Action;

/**
 * A repository layout that uses user-supplied patterns. Each pattern will be appended to the base URI for the repository.
 * At least one artifact pattern must be specified. If no Ivy patterns are specified, then the artifact patterns will be used.
 * Optionally supports a Maven style layout for the 'organisation' part, replacing any dots with forward slashes.
 *
 * For examples see the reference for {@link org.gradle.api.artifacts.repositories.IvyArtifactRepository#patternLayout(Action)}.
 *
 * @since 2.3 (feature was already present in Groovy DSL, this type introduced in 2.3)
 */
public interface IvyPatternRepositoryLayout extends RepositoryLayout {

    /**
     * Adds an Ivy artifact pattern to define where artifacts are located in this repository.
     * @param pattern The ivy pattern
     */
    void artifact(String pattern);

    /**
     * Adds an Ivy pattern to define where ivy files are located in this repository.
     * @param pattern The ivy pattern
     */
    void ivy(String pattern);

    /**
     * Tells whether a Maven style layout is to be used for the 'organisation' part, replacing any dots with forward slashes.
     * Defaults to {@code false}.
     */
    boolean getM2Compatible();

    /**
     * Sets whether a Maven style layout is to be used for the 'organisation' part, replacing any dots with forward slashes.
     * Defaults to {@code false}.
     *
     * @param m2compatible whether a Maven style layout is to be used for the 'organisation' part
     */
    void setM2compatible(boolean m2compatible);
}


text:
using namespace v8;

Handle<Value> commit_create(void *ptr){
    Isolate* iso = Isolate::GetCurrent();
    EscapableHandleScope scope(iso);

    Local<Object> self = self_alloc(ptr);
    self->Set(String::NewFromUtf8(iso, "free"), wrap_func(commit_remove));

    return scope.Escape(self);
}

void commit_remove(const FunctionCallbackInfo<Value>& args){
    Isolate* iso = Isolate::GetCurrent();
    HandleScope scope(iso);

    git_commit *ptr = (git_commit*)self_get(args);
    git_libgit2_init();
    git_commit_free(ptr);
    self_free(args);
    git_libgit2_shutdown();

    args.GetReturnValue().Set(Number::New(iso, 0));
}


text:
from faps.draw_fathers import draw_fathers
import numpy as np
import faps as fp

def test_draw_fathers():
    np.random.seed(867)
    allele_freqs = np.random.uniform(0.3,0.5,50)
    adults = fp.make_parents(100, allele_freqs, family_name='a')
    progeny = fp.make_sibships(adults, 0, [1,2,3], 5, 'x')
    mothers = adults.subset(progeny.mothers)
    patlik  = fp.paternity_array(progeny, mothers, adults, mu = 0.0015, missing_parents=0.01)
    sc = fp.sibship_clustering(patlik)

    ndraws=1000
    dr = fp.draw_fathers(
        sc.mlpartition,
        genetic = sc.paternity_array,
        ndraws=ndraws)
    assert isinstance(dr, np.ndarray)
    assert len(dr) == ndraws
    assert all([x in [1,2,3] for x in dr])

    # Add a nonsense covariate
    cov = np.arange(0,adults.size)
    cov = np.log(cov/cov.sum())
    patlik.add_covariate(cov)
    sc2 = fp.sibship_clustering(patlik, use_covariates=True)
    dr2 = fp.draw_fathers(
        sc2.mlpartition,
        genetic = sc2.paternity_array,
        covariate = sc2.covariate,
        ndraws = ndraws,
        use_covariates=True
    )
    assert isinstance(dr2, np.ndarray)
    assert len(dr2) == ndraws
    # Check that using only the covariate samples more or less at random
    dr3 = fp.draw_fathers(
        sc2.mlpartition,
        genetic = sc2.paternity_array,
        covariate = sc2.covariate,
        covariates_only = True
        )
    assert isinstance(dr3, np.ndarray)
    assert not all([x in [1,2,3] for x in dr3])
    # Remove one of the real fathers.
    # Check that he doesn't appear, but the index for missing fathers (100 in
    # this case) does.
    patlik.purge = "a_1"
    sc3 = fp.sibship_clustering(patlik)
    dr4 = fp.draw_fathers(
        sc3.mlpartition,
        genetic = sc3.paternity_array
        )
    assert 1 not in dr4
    assert 100 in dr4


text:
FILE(REMOVE_RECURSE
  "CMakeFiles/pcl_ground_based_rgbd_people_detector.dir/apps/main_ground_based_people_detection.cpp.o"
  "../bin/pcl_ground_based_rgbd_people_detector.pdb"
  "../bin/pcl_ground_based_rgbd_people_detector"
)

# Per-language clean rules from dependency scanning.
FOREACH(lang CXX)
  INCLUDE(CMakeFiles/pcl_ground_based_rgbd_people_detector.dir/cmake_clean_${lang}.cmake OPTIONAL)
ENDFOREACH(lang)


text:
if(MITK_USE_SimpleITK)

 # Sanity checks
 if(DEFINED SimpleITK_DIR AND NOT EXISTS ${SimpleITK_DIR})
   message(FATAL_ERROR "SimpleITK_DIR variable is defined but corresponds to non-existing directory")
 endif()

  set(proj SimpleITK)
  set(proj_DEPENDENCIES ITK GDCM SWIG)

  if(MITK_USE_OpenCV)
    list(APPEND proj_DEPENDENCIES OpenCV)
  endif()

  set(SimpleITK_DEPENDS ${proj})

  if(NOT DEFINED SimpleITK_DIR)

    set(additional_cmake_args )

    list(APPEND additional_cmake_args
         -DWRAP_CSHARP:BOOL=OFF
         -DWRAP_TCL:BOOL=OFF
         -DWRAP_LUA:BOOL=OFF
         -DWRAP_PYTHON:BOOL=OFF
         -DWRAP_JAVA:BOOL=OFF
         -DWRAP_RUBY:BOOL=OFF
         -DWRAP_R:BOOL=OFF
        )

    if(MITK_USE_Python)
      list(APPEND additional_cmake_args
           -DWRAP_PYTHON:BOOL=ON
           -DPYTHON_EXECUTABLE:FILEPATH=${PYTHON_EXECUTABLE}
           -DPYTHON_INCLUDE_DIR:PATH=${PYTHON_INCLUDE_DIR}
           -DPYTHON_INCLUDE_DIR2:PATH=${PYTHON_INCLUDE_DIR2}
           -DPYTHON_LIBRARY:FILEPATH=${PYTHON_LIBRARY}
          )
      if(NOT MITK_USE_SYSTEM_PYTHON)
        list(APPEND proj_DEPENDENCIES Python)
      endif()
    endif()

    if(CTEST_USE_LAUNCHERS)
      list(APPEND additional_cmake_args
        "-DCMAKE_PROJECT_${proj}_INCLUDE:FILEPATH=${CMAKE_ROOT}/Modules/CTestUseLaunchers.cmake"
      )
    endif()

    #TODO: Installer and testing works only with static libs on MAC
    set(_build_shared ON)
    if(APPLE)
      set(_build_shared OFF)
    endif()

    ExternalProject_Add(${proj}
       LIST_SEPARATOR ${sep}
       URL ${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/SimpleITK-0.8.1.tar.gz
       URL_MD5 9126ab2eda9e88f598a962c02a705c43
       PATCH_COMMAND ${PATCH_COMMAND} -N -p1 -i ${CMAKE_CURRENT_LIST_DIR}/SimpleITK-0.8.1.patch
       CMAKE_ARGS
         ${ep_common_args}
         # -DCMAKE_BUILD_WITH_INSTALL_RPATH:BOOL=ON
      CMAKE_CACHE_ARGS
         ${ep_common_cache_args}
         ${additional_cmake_args}
         -DBUILD_SHARED_LIBS:BOOL=${_build_shared}
         -DSimpleITK_BUILD_DISTRIBUTE:BOOL=ON
         -DSimpleITK_PYTHON_THREADS:BOOL=ON
         -DUSE_SYSTEM_ITK:BOOL=ON
         -DBUILD_EXAMPLES:BOOL=OFF
         -DGDCM_DIR:PATH=${GDCM_DIR}
         -DITK_DIR:PATH=${ITK_DIR}
         -DSWIG_DIR:PATH=${SWIG_DIR}
         -DSWIG_EXECUTABLE:FILEPATH=${SWIG_EXECUTABLE}
       CMAKE_CACHE_DEFAULT_ARGS
         ${ep_common_cache_default_args}
       DEPENDS ${proj_DEPENDENCIES}
      )

    set(SimpleITK_DIR ${ep_prefix})

    if( MITK_USE_Python )
      set(_sitk_build_dir ${ep_prefix}/src/SimpleITK-build)
      # Build python distribution with easy install. If a own runtime is used
      # embedd the egg into the site-package folder of the runtime

      # Note: Userbase install could also be relevant in some cases Probably windows want's to
      # install to Lib/python2.7/
      # Build egg into custom user base folder and deploy it later into installer
      # https://pythonhosted.org/setuptools/easy_install.html#use-the-user-option-and-customize-pythonuserbase
      # PYTHONUSERBASE=${_install_dir} ${PYTHON_EXECUTABLE} setup.py --user

      # PythonDir needs to be fixed for the python interpreter by
      # changing dir delimiter for Windows
      if(MITK_USE_SYSTEM_PYTHON)
        set(_install_dir ${ep_prefix})
      else()
        set(_install_dir ${Python_DIR})
      endif()
      if(WIN32)
        STRING(REPLACE "/" "\\\\" _install_dir ${_install_dir})
      else()
        # escape spaces in the install path for linux
        STRING(REPLACE " " "\ " _install_dir ${_install_dir})
      endif()

      if( MITK_USE_SYSTEM_PYTHON )
        ExternalProject_Add_Step(${proj} sitk_python_install_step
          COMMAND PYTHONUSERBASE=${_install_dir} ${PYTHON_EXECUTABLE} setup.py install --prefix=${_install_dir}
          DEPENDEES install
          WORKING_DIRECTORY ${_sitk_build_dir}/Wrapping/PythonPackage
        )
      else()
        ExternalProject_Add_Step(${proj} sitk_python_install_step
          COMMAND ${PYTHON_EXECUTABLE} setup.py install --prefix=${_install_dir}
          DEPENDEES install
          WORKING_DIRECTORY ${_sitk_build_dir}/Wrapping/PythonPackage
        )
      endif()
    endif()

    mitkFunctionInstallExternalCMakeProject(${proj})
    # Still need to install the SimpleITK Python wrappings
  else()

    mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}")

  endif()

endif()


text:
package urlutil

import (
	"regexp"
	"strings"
)

var (
	validPrefixes = []string{
		"git://",
		"github.com/",
		"git@",
	}

	urlPathWithFragmentSuffix = regexp.MustCompile(".git(?:#.+)?$")
)

// IsGitURL returns true if the provided str is a git repository URL.
func IsGitURL(str string) bool {
	if IsURL(str) && urlPathWithFragmentSuffix.MatchString(str) {
		return true
	}
	for _, prefix := range validPrefixes {
		if strings.HasPrefix(str, prefix) {
			return true
		}
	}
	return false
}

// IsGitTransport returns true if the provided str is a git transport by inspecting
// the prefix of the string for known protocols used in git.
func IsGitTransport(str string) bool {
	return IsURL(str) || strings.HasPrefix(str, "git://") || strings.HasPrefix(str, "git@")
}


text:
package org.json;

import junit.framework.TestCase;

/**
 * This black box test was written without inspecting the non-free org.json sourcecode.
 */
public class JSONStringerTest extends TestCase {

    public void testEmptyStringer() {
        // why isn't this the empty string?
        assertNull(new JSONStringer().toString());
    }

    public void testValueJSONNull() throws JSONException {
        JSONStringer stringer = new JSONStringer();
        stringer.array();
        stringer.value(JSONObject.NULL);
        stringer.endArray();
        assertEquals("[null]", stringer.toString());
    }

    public void testEmptyObject() throws JSONException {
        JSONStringer stringer = new JSONStringer();
        stringer.object();
        stringer.endObject();
        assertEquals("{}", stringer.toString());
    }

    public void testEmptyArray() throws JSONException {
        JSONStringer stringer = new JSONStringer();
        stringer.array();
        stringer.endArray();
        assertEquals("[]", stringer.toString());
    }

    public void testArray() throws JSONException {
        JSONStringer stringer = new JSONStringer();
        stringer.array();
        stringer.value(false);
        stringer.value(5.0);
        stringer.value(5L);
        stringer.value("five");
        stringer.value(null);
        stringer.endArray();
        assertEquals("[false,5,5,\"five\",null]", stringer.toString());
    }

    public void testValueObjectMethods() throws JSONException {
        JSONStringer stringer = new JSONStringer();
        stringer.array();
        stringer.value(Boolean.FALSE);
        stringer.value(Double.valueOf(5.0));
        stringer.value(Long.valueOf(5L));
        stringer.endArray();
        assertEquals("[false,5,5]", stringer.toString());
    }

    public void testKeyValue() throws JSONException {
        JSONStringer stringer = new JSONStringer();
        stringer.object();
        stringer.key("a").value(false);
        stringer.key("b").value(5.0);
        stringer.key("c").value(5L);
        stringer.key("d").value("five");
        stringer.key("e").value(null);
        stringer.endObject();
        assertEquals("{\"a\":false," +
                "\"b\":5," +
                "\"c\":5," +
                "\"d\":\"five\"," +
                "\"e\":null}", stringer.toString());
    }

    /**
     * Test what happens when extreme values are emitted. Such values are likely
     * to be rounded during parsing.
     */
    public void testNumericRepresentations() throws JSONException {
        if (System.getProperty("os.arch").equals("armv7")) {
          // On armv7, MIN_VALUE is indistinguishable from zero.
          return;
        }
        JSONStringer stringer = new JSONStringer();
        stringer.array();
        stringer.value(Long.MAX_VALUE);
        stringer.value(Double.MIN_VALUE);
        stringer.endArray();
        assertEquals("[9223372036854775807,4.9E-324]", stringer.toString());
    }

    public void testWeirdNumbers() throws JSONException {
        try {
            new JSONStringer().array().value(Double.NaN);
            fail();
        } catch (JSONException e) {
        }
        try {
            new JSONStringer().array().value(Double.NEGATIVE_INFINITY);
            fail();
        } catch (JSONException e) {
        }
        try {
            new JSONStringer().array().value(Double.POSITIVE_INFINITY);
            fail();
        } catch (JSONException e) {
        }

        JSONStringer stringer = new JSONStringer();
        stringer.array();
        stringer.value(-0.0d);
        stringer.value(0.0d);
        stringer.endArray();
        assertEquals("[-0,0]", stringer.toString());
    }

    public void testMismatchedScopes() {
        try {
            new JSONStringer().key("a");
            fail();
        } catch (JSONException e) {
        }
        try {
            new JSONStringer().value("a");
            fail();
        } catch (JSONException e) {
        }
        try {
            new JSONStringer().endObject();
            fail();
        } catch (JSONException e) {
        }
        try {
            new JSONStringer().endArray();
            fail();
        } catch (JSONException e) {
        }
        try {
            new JSONStringer().array().endObject();
            fail();
        } catch (JSONException e) {
        }
        try {
            new JSONStringer().object().endArray();
            fail();
        } catch (JSONException e) {
        }
        try {
            new JSONStringer().object().key("a").key("a");
            fail();
        } catch (JSONException e) {
        }
        try {
            new JSONStringer().object().value(false);
            fail();
        } catch (JSONException e) {
        }
    }

    public void testNullKey() {
        try {
            new JSONStringer().object().key(null);
            fail();
        } catch (JSONException e) {
        }
    }

    public void testRepeatedKey() throws JSONException {
        JSONStringer stringer = new JSONStringer();
        stringer.object();
        stringer.key("a").value(true);
        stringer.key("a").value(false);
        stringer.endObject();
        // JSONStringer doesn't attempt to detect duplicates
        assertEquals("{\"a\":true,\"a\":false}", stringer.toString());
    }

    public void testEmptyKey() throws JSONException {
        JSONStringer stringer = new JSONStringer();
        stringer.object();
        stringer.key("").value(false);
        stringer.endObject();
        assertEquals("{\"\":false}", stringer.toString()); // legit behaviour!
    }

    public void testEscaping() throws JSONException {
        assertEscapedAllWays("a", "a");
        assertEscapedAllWays("a\\\"", "a\"");
        assertEscapedAllWays("\\\"", "\"");
        assertEscapedAllWays(":", ":");
        assertEscapedAllWays(",", ",");
        assertEscapedAllWays("\\b", "\b");
        assertEscapedAllWays("\\f", "\f");
        assertEscapedAllWays("\\n", "\n");
        assertEscapedAllWays("\\r", "\r");
        assertEscapedAllWays("\\t", "\t");
        assertEscapedAllWays(" ", " ");
        assertEscapedAllWays("\\\\", "\\");
        assertEscapedAllWays("{", "{");
        assertEscapedAllWays("}", "}");
        assertEscapedAllWays("[", "[");
        assertEscapedAllWays("]", "]");
        assertEscapedAllWays("\\u0000", "\0");
        assertEscapedAllWays("\\u0019", "\u0019");
        assertEscapedAllWays(" ", "\u0020");
    }

    private void assertEscapedAllWays(String escaped, String original) throws JSONException {
        assertEquals("{\"" + escaped + "\":false}",
                new JSONStringer().object().key(original).value(false).endObject().toString());
        assertEquals("{\"a\":\"" + escaped + "\"}",
                new JSONStringer().object().key("a").value(original).endObject().toString());
        assertEquals("[\"" + escaped + "\"]",
                new JSONStringer().array().value(original).endArray().toString());
        assertEquals("\"" + escaped + "\"", JSONObject.quote(original));
    }

    public void testJSONArrayAsValue() throws JSONException {
        JSONArray array = new JSONArray();
        array.put(false);
        JSONStringer stringer = new JSONStringer();
        stringer.array();
        stringer.value(array);
        stringer.endArray();
        assertEquals("[[false]]", stringer.toString());
    }

    public void testJSONObjectAsValue() throws JSONException {
        JSONObject object = new JSONObject();
        object.put("a", false);
        JSONStringer stringer = new JSONStringer();
        stringer.object();
        stringer.key("b").value(object);
        stringer.endObject();
        assertEquals("{\"b\":{\"a\":false}}", stringer.toString());
    }

    public void testArrayNestingMaxDepthSupports20() throws JSONException {
        JSONStringer stringer = new JSONStringer();
        for (int i = 0; i < 20; i++) {
            stringer.array();
        }
        for (int i = 0; i < 20; i++) {
            stringer.endArray();
        }
        assertEquals("[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]", stringer.toString());

        stringer = new JSONStringer();
        for (int i = 0; i < 20; i++) {
            stringer.array();
        }
    }

    public void testObjectNestingMaxDepthSupports20() throws JSONException {
        JSONStringer stringer = new JSONStringer();
        for (int i = 0; i < 20; i++) {
            stringer.object();
            stringer.key("a");
        }
        stringer.value(false);
        for (int i = 0; i < 20; i++) {
            stringer.endObject();
        }
        assertEquals("{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":" +
                "{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":{\"a\":false" +
                "}}}}}}}}}}}}}}}}}}}}", stringer.toString());

        stringer = new JSONStringer();
        for (int i = 0; i < 20; i++) {
            stringer.object();
            stringer.key("a");
        }
    }

    public void testMixedMaxDepthSupports20() throws JSONException {
        JSONStringer stringer = new JSONStringer();
        for (int i = 0; i < 20; i+=2) {
            stringer.array();
            stringer.object();
            stringer.key("a");
        }
        stringer.value(false);
        for (int i = 0; i < 20; i+=2) {
            stringer.endObject();
            stringer.endArray();
        }
        assertEquals("[{\"a\":[{\"a\":[{\"a\":[{\"a\":[{\"a\":" +
                "[{\"a\":[{\"a\":[{\"a\":[{\"a\":[{\"a\":false" +
                "}]}]}]}]}]}]}]}]}]}]", stringer.toString());

        stringer = new JSONStringer();
        for (int i = 0; i < 20; i+=2) {
            stringer.array();
            stringer.object();
            stringer.key("a");
        }
    }

    public void testMaxDepthWithArrayValue() throws JSONException {
        JSONArray array = new JSONArray();
        array.put(false);

        JSONStringer stringer = new JSONStringer();
        for (int i = 0; i < 20; i++) {
            stringer.array();
        }
        stringer.value(array);
        for (int i = 0; i < 20; i++) {
            stringer.endArray();
        }
        assertEquals("[[[[[[[[[[[[[[[[[[[[[false]]]]]]]]]]]]]]]]]]]]]", stringer.toString());
    }

    public void testMaxDepthWithObjectValue() throws JSONException {
        JSONObject object = new JSONObject();
        object.put("a", false);
        JSONStringer stringer = new JSONStringer();
        for (int i = 0; i < 20; i++) {
            stringer.object();
            stringer.key("b");
        }
        stringer.value(object);
        for (int i = 0; i < 20; i++) {
            stringer.endObject();
        }
        assertEquals("{\"b\":{\"b\":{\"b\":{\"b\":{\"b\":{\"b\":{\"b\":{\"b\":{\"b\":{\"b\":" +
                "{\"b\":{\"b\":{\"b\":{\"b\":{\"b\":{\"b\":{\"b\":{\"b\":{\"b\":{\"b\":" +
                "{\"a\":false}}}}}}}}}}}}}}}}}}}}}", stringer.toString());
    }

    public void testMultipleRoots() throws JSONException {
        JSONStringer stringer = new JSONStringer();
        stringer.array();
        stringer.endArray();
        try {
            stringer.object();
            fail();
        } catch (JSONException e) {
        }
    }
}


text:
package com.github.otbproject.otbproject.event;

public class ServiceChannelDisconnectEvent {
    private final String channel;

    public ServiceChannelDisconnectEvent(String channel) {
        this.channel = channel;
    }

    public String getChannel() {
        return channel;
    }
}


text:
package org.apache.hadoop.hbase.codec.prefixtree.scanner;

import org.apache.hadoop.hbase.classification.InterfaceAudience;
import org.apache.hadoop.hbase.Cell;

/**
 * Methods for seeking to a random {@link Cell} inside a sorted collection of cells. Indicates that
 * the implementation is able to navigate between cells without iterating through every cell.
 */
@InterfaceAudience.Private
public interface CellSearcher extends ReversibleCellScanner {
  /**
   * Reset any state in the scanner so it appears it was freshly opened.
   */
  void resetToBeforeFirstEntry();

  /**
   * Do everything within this scanner's power to find the key. Look forward and backwards.
   *

   * Abort as soon as we know it can't be found, possibly leaving the Searcher in an invalid state.
   *

   * @param key position the CellScanner exactly on this key
   * @return true if the cell existed and getCurrentCell() holds a valid cell
   */
  boolean positionAt(Cell key);

  /**
   * Same as positionAt(..), but go to the extra effort of finding the previous key if there's no
   * exact match.
   *

   * @param key position the CellScanner on this key or the closest cell before
   * @return AT if exact match

   *         BEFORE if on last cell before key

   *         BEFORE_FIRST if key was before the first cell in this scanner's scope
   */
  CellScannerPosition positionAtOrBefore(Cell key);

  /**
   * Same as positionAt(..), but go to the extra effort of finding the next key if there's no exact
   * match.
   *

   * @param key position the CellScanner on this key or the closest cell after
   * @return AT if exact match

   *         AFTER if on first cell after key

   *         AFTER_LAST if key was after the last cell in this scanner's scope
   */
  CellScannerPosition positionAtOrAfter(Cell key);

  /**
   * Note: Added for backwards compatibility with
   * {@link org.apache.hadoop.hbase.regionserver.KeyValueScanner#reseek}
   *

   * Look for the key, but only look after the current position. Probably not needed for an
   * efficient tree implementation, but is important for implementations without random access such
   * as unencoded KeyValue blocks.
   *

   * @param key position the CellScanner exactly on this key
   * @return true if getCurrent() holds a valid cell
   */
  boolean seekForwardTo(Cell key);

  /**
   * Same as seekForwardTo(..), but go to the extra effort of finding the next key if there's no
   * exact match.
   *

   * @param key
   * @return AT if exact match

   *         AFTER if on first cell after key

   *         AFTER_LAST if key was after the last cell in this scanner's scope
   */
  CellScannerPosition seekForwardToOrBefore(Cell key);

  /**
   * Same as seekForwardTo(..), but go to the extra effort of finding the next key if there's no
   * exact match.
   *

   * @param key
   * @return AT if exact match

   *         AFTER if on first cell after key

   *         AFTER_LAST if key was after the last cell in this scanner's scope
   */
  CellScannerPosition seekForwardToOrAfter(Cell key);

  /**
   * Note: This may not be appropriate to have in the interface.  Need to investigate.
   *

   * Position the scanner in an invalid state after the last cell: CellScannerPosition.AFTER_LAST.
   * This is used by tests and for handling certain edge cases.
   */
  void positionAfterLastCell();

}


text:
namespace Microsoft.Exchange.WebServices.Data
{
    using System;
    using System.Collections.Generic;
    using System.Text;

    /// <summary>
    /// Represents the options of a GetAvailability request.
    /// </summary>
    public sealed class AvailabilityOptions
    {
        private int mergedFreeBusyInterval = 30;
        private FreeBusyViewType requestedFreeBusyView = FreeBusyViewType.Detailed;
        private int goodSuggestionThreshold = 25;
        private int maximumSuggestionsPerDay = 10;
        private int maximumNonWorkHoursSuggestionsPerDay = 0;
        private int meetingDuration = 60;
        private SuggestionQuality minimumSuggestionQuality = SuggestionQuality.Fair;
        private TimeWindow detailedSuggestionsWindow;
        private DateTime? currentMeetingTime;
        private string globalObjectId;

        /// <summary>
        /// Validates this instance against the specified time window.
        /// </summary>
        /// <param name="timeWindow">The time window.</param>
        internal void Validate(TimeSpan timeWindow)
        {
            if (TimeSpan.FromMinutes(this.MergedFreeBusyInterval) > timeWindow)
            {
                throw new ArgumentException(Strings.MergedFreeBusyIntervalMustBeSmallerThanTimeWindow, "MergedFreeBusyInterval");
            }

            EwsUtilities.ValidateParamAllowNull(this.DetailedSuggestionsWindow, "DetailedSuggestionsWindow");
        }

        /// <summary>
        /// Writes to XML.
        /// </summary>
        /// <param name="writer">The writer.</param>
        /// <param name="request">The request being emitted.</param>
        internal void WriteToXml(EwsServiceXmlWriter writer, GetUserAvailabilityRequest request)
        {
            if (request.IsFreeBusyViewRequested)
            {
                writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.FreeBusyViewOptions);

                request.TimeWindow.WriteToXmlUnscopedDatesOnly(writer, XmlElementNames.TimeWindow);

                writer.WriteElementValue(
                    XmlNamespace.Types,
                    XmlElementNames.MergedFreeBusyIntervalInMinutes,
                    this.MergedFreeBusyInterval);

                writer.WriteElementValue(
                    XmlNamespace.Types,
                    XmlElementNames.RequestedView,
                    this.RequestedFreeBusyView);

                writer.WriteEndElement(); // FreeBusyViewOptions
            }

            if (request.IsSuggestionsViewRequested)
            {
                writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.SuggestionsViewOptions);

                writer.WriteElementValue(
                    XmlNamespace.Types,
                    XmlElementNames.GoodThreshold,
                    this.GoodSuggestionThreshold);

                writer.WriteElementValue(
                    XmlNamespace.Types,
                    XmlElementNames.MaximumResultsByDay,
                    this.MaximumSuggestionsPerDay);

                writer.WriteElementValue(
                    XmlNamespace.Types,
                    XmlElementNames.MaximumNonWorkHourResultsByDay,
                    this.MaximumNonWorkHoursSuggestionsPerDay);

                writer.WriteElementValue(
                    XmlNamespace.Types,
                    XmlElementNames.MeetingDurationInMinutes,
                    this.MeetingDuration);

                writer.WriteElementValue(
                    XmlNamespace.Types,
                    XmlElementNames.MinimumSuggestionQuality,
                    this.MinimumSuggestionQuality);

                TimeWindow timeWindowToSerialize = this.DetailedSuggestionsWindow == null ?
                    request.TimeWindow :
                    this.DetailedSuggestionsWindow;

                timeWindowToSerialize.WriteToXmlUnscopedDatesOnly(writer, XmlElementNames.DetailedSuggestionsWindow);

                if (this.CurrentMeetingTime.HasValue)
                {
                    writer.WriteElementValue(
                        XmlNamespace.Types,
                        XmlElementNames.CurrentMeetingTime,
                        this.CurrentMeetingTime.Value);
                }

                writer.WriteElementValue(
                    XmlNamespace.Types,
                    XmlElementNames.GlobalObjectId,
                    this.GlobalObjectId);

                writer.WriteEndElement(); // SuggestionsViewOptions
            }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="AvailabilityOptions"/> class.
        /// </summary>
        public AvailabilityOptions()
        {
        }

        /// <summary>
        /// Gets or sets the time difference between two successive slots in a FreeBusyMerged view.
        /// MergedFreeBusyInterval must be between 5 and 1440. The default value is 30.
        /// </summary>
        public int MergedFreeBusyInterval
        {
            get
            {
                return this.mergedFreeBusyInterval;
            }

            set
            {
                if (value < 5 || value > 1440)
                {
                    throw new ArgumentException(
                        string.Format(
                            Strings.InvalidPropertyValueNotInRange,
                            "MergedFreeBusyInterval",
                            5,
                            1440));
                }

                this.mergedFreeBusyInterval = value;
            }
        }

        /// <summary>
        /// Gets or sets the requested type of free/busy view. The default value is FreeBusyViewType.Detailed.
        /// </summary>
        public FreeBusyViewType RequestedFreeBusyView
        {
            get { return this.requestedFreeBusyView; }
            set { this.requestedFreeBusyView = value; }
        }

        /// <summary>
        /// Gets or sets the percentage of attendees that must have the time period open for the time period to qualify as a good suggested meeting time.
        /// GoodSuggestionThreshold must be between 1 and 49. The default value is 25.
        /// </summary>
        public int GoodSuggestionThreshold
        {
            get
            {
                return this.goodSuggestionThreshold;
            }

            set
            {
                if (value < 1 || value > 49)
                {
                    throw new ArgumentException(
                        string.Format(
                            Strings.InvalidPropertyValueNotInRange,
                            "GoodSuggestionThreshold",
                            1,
                            49));
                }

                this.goodSuggestionThreshold = value;
            }
        }

        /// <summary>
        /// Gets or sets the number of suggested meeting times that should be returned per day.
        /// MaximumSuggestionsPerDay must be between 0 and 48. The default value is 10.
        /// </summary>
        public int MaximumSuggestionsPerDay
        {
            get
            {
                return this.maximumSuggestionsPerDay;
            }

            set
            {
                if (value < 0 || value > 48)
                {
                    throw new ArgumentException(
                        string.Format(
                            Strings.InvalidPropertyValueNotInRange,
                            "MaximumSuggestionsPerDay",
                            0,
                            48));
                }

                this.maximumSuggestionsPerDay = value;
            }
        }

        /// <summary>
        /// Gets or sets the number of suggested meeting times outside regular working hours per day.
        /// MaximumNonWorkHoursSuggestionsPerDay must be between 0 and 48. The default value is 0.
        /// </summary>
        public int MaximumNonWorkHoursSuggestionsPerDay
        {
            get
            {
                return this.maximumNonWorkHoursSuggestionsPerDay;
            }

            set
            {
                if (value < 0 || value > 48)
                {
                    throw new ArgumentException(
                        string.Format(
                            Strings.InvalidPropertyValueNotInRange,
                            "MaximumNonWorkHoursSuggestionsPerDay",
                            0,
                            48));
                }

                this.maximumNonWorkHoursSuggestionsPerDay = value;
            }
        }

        /// <summary>
        /// Gets or sets the duration, in minutes, of the meeting for which to obtain suggestions.
        /// MeetingDuration must be between 30 and 1440. The default value is 60.
        /// </summary>
        public int MeetingDuration
        {
            get
            {
                return this.meetingDuration;
            }

            set
            {
                if (value < 30 || value > 1440)
                {
                    throw new ArgumentException(
                        string.Format(
                            Strings.InvalidPropertyValueNotInRange,
                            "MeetingDuration",
                            30,
                            1440));
                }

                this.meetingDuration = value;
            }
        }

        /// <summary>
        /// Gets or sets the minimum quality of suggestions that should be returned.
        /// The default is SuggestionQuality.Fair.
        /// </summary>
        public SuggestionQuality MinimumSuggestionQuality
        {
            get { return this.minimumSuggestionQuality; }
            set { this.minimumSuggestionQuality = value; }
        }

        /// <summary>
        /// Gets or sets the time window for which detailed information about suggested meeting times should be returned.
        /// </summary>
        public TimeWindow DetailedSuggestionsWindow
        {
            get { return this.detailedSuggestionsWindow; }
            set { this.detailedSuggestionsWindow = value; }
        }

        /// <summary>
        /// Gets or sets the start time of a meeting that you want to update with the suggested meeting times.
        /// </summary>
        public DateTime? CurrentMeetingTime
        {
            get { return this.currentMeetingTime; }
            set { this.currentMeetingTime = value; }
        }

        /// <summary>
        /// Gets or sets the global object Id of a meeting that will be modified based on the data returned by GetUserAvailability.
        /// </summary>
        public string GlobalObjectId
        {
            get { return this.globalObjectId; }
            set { this.globalObjectId = value; }
        }
    }
}


text:
package controllers.ajax.expert.requetes.calculs;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import com.avaje.ebean.Expr;

import controllers.ajax.expert.requetes.Calculs;
import models.Espece;
import models.FicheHasMembre;
import models.Groupe;
import models.InformationsComplementaires;
import models.Membre;
import models.Observation;
import models.SousGroupe;
import models.StadeSexe;
import models.UTMS;

public class TemoinsParPeriode implements Comparator<TemoinsParPeriode>{
	public Membre temoin;
	public int nombreDeTemoignages;

	public TemoinsParPeriode(Membre temoin, Integer nombreDeTemoignage){
		this.temoin=temoin;
		this.nombreDeTemoignages=nombreDeTemoignage;
	}

	@Override
	public String toString(){
		return temoin.membre_nom+" : "+nombreDeTemoignages;
	}

	/**
	 * Trie par ordre décroissant de nombre de témoignages
	 */
	@Override
	public int compare(TemoinsParPeriode t1, TemoinsParPeriode t2) {
		return t1.temoin.membre_nom.compareToIgnoreCase(t2.temoin.membre_nom);
	}
	private TemoinsParPeriode(){}

	public static List<TemoinsParPeriode> calculeTemoinsParPeriode(Map<String,String> info) throws ParseException {
		List<TemoinsParPeriode> temoins = new ArrayList<TemoinsParPeriode>();
		List<InformationsComplementaires> complements = TemoinsParPeriode.getObservations(info);
		//On commence la génération des témoins par période.
		for(InformationsComplementaires complement : complements){
			List<FicheHasMembre> fhms = FicheHasMembre.find.where().eq("fiche", complement.informations_complementaires_observation.getFiche()).findList();
			for(FicheHasMembre fhm : fhms){
				int position;
				if((position=position(fhm.membre,temoins))==-1){
					temoins.add(new TemoinsParPeriode(fhm.membre,1));
				}else{
					temoins.get(position).nombreDeTemoignages++;
				}
			}
		}
		Collections.sort(temoins,new TemoinsParPeriode());
		return temoins;
	}

	/**
	 * Renvoie la position du membre dans la liste temoins
	 * @param membre
	 * @param temoins
	 * @return
	 */
	private static int position(Membre membre, List<TemoinsParPeriode> temoins) {
		int i = 0;
		while(i<temoins.size()){
			if(temoins.get(i).temoin.equals(membre))
				return i;
			i++;
		}
		return -1;
	}

	/**
	 * Renvoie les observations pour afficher temoins par période
	 * @param info
	 * @return
	 * @throws ParseException
	 */
	public static List<InformationsComplementaires> getObservations(Map<String,String> info) throws ParseException{
		Espece espece = Espece.find.byId(Integer.parseInt(info.get("espece")));
		SousGroupe sous_groupe = SousGroupe.find.byId(Integer.parseInt(info.get("sous_groupe")));
		Groupe groupe = Groupe.find.byId(Integer.parseInt(info.get("groupe")));
		StadeSexe stade_sexe = StadeSexe.find.byId(Integer.parseInt(info.get("stade")));
		List<StadeSexe> stades_sexes;
		if(stade_sexe!=null){
			stades_sexes=new ArrayList<StadeSexe>();
			stades_sexes.add(stade_sexe);
			stades_sexes.addAll(stade_sexe.getStadeSexeFilsPourTelGroupe(groupe));
		}else{
			stades_sexes=StadeSexe.findAll();
		}
		List<UTMS> mailles = UTMS.parseMaille(info.get("maille"));
		Calendar date1 = Calculs.getDataDate1(info);
		Calendar date2 = Calculs.getDataDate2(info);
		List<InformationsComplementaires> complements;
		if(espece!=null){
			complements = InformationsComplementaires.find.where()
								.eq("informations_complementaires_observation.observation_espece",espece)
								.eq("informations_complementaires_observation.observation_validee", Observation.VALIDEE)
								.or(Expr.and(
										Expr.isNull("informations_complementaires_observation.observation_fiche.fiche_date_min"),
										Expr.between("informations_complementaires_observation.observation_fiche.fiche_date", date1.getTime(), date2.getTime())
										),
									Expr.and(
										Expr.ge("informations_complementaires_observation.observation_fiche.fiche_date_min", date1.getTime()),
										Expr.le("informations_complementaires_observation.observation_fiche.fiche_date", date2.getTime())
										)
									)
								.in("informations_complementaires_observation.observation_fiche.fiche_utm", mailles)
								.in("informations_complementaires_stade_sexe", stades_sexes)
								.findList();
		}else if(sous_groupe!=null){
			complements = InformationsComplementaires.find.where()
								.eq("informations_complementaires_observation.observation_espece.espece_sous_groupe",sous_groupe)
								.eq("informations_complementaires_observation.observation_validee", Observation.VALIDEE)
								.or(Expr.and(
										Expr.isNull("informations_complementaires_observation.observation_fiche.fiche_date_min"),
										Expr.between("informations_complementaires_observation.observation_fiche.fiche_date", date1.getTime(), date2.getTime())
										),
									Expr.and(
										Expr.ge("informations_complementaires_observation.observation_fiche.fiche_date_min", date1.getTime()),
										Expr.le("informations_complementaires_observation.observation_fiche.fiche_date", date2.getTime())
										)
									)
								.in("informations_complementaires_observation.observation_fiche.fiche_utm", mailles)
								.in("informations_complementaires_stade_sexe", stades_sexes)
								.findList();
		}else if(groupe!=null){
			complements = InformationsComplementaires.find.where()
								.eq("informations_complementaires_observation.observation_espece.espece_sous_groupe.sous_groupe_groupe",groupe)
								.eq("informations_complementaires_observation.observation_validee", Observation.VALIDEE)
								.or(Expr.and(
										Expr.isNull("informations_complementaires_observation.observation_fiche.fiche_date_min"),
										Expr.between("informations_complementaires_observation.observation_fiche.fiche_date", date1.getTime(), date2.getTime())
										),
									Expr.and(
										Expr.ge("informations_complementaires_observation.observation_fiche.fiche_date_min", date1.getTime()),
										Expr.le("informations_complementaires_observation.observation_fiche.fiche_date", date2.getTime())
										)
									)
								.in("informations_complementaires_observation.observation_fiche.fiche_utm", mailles)
								.in("informations_complementaires_stade_sexe", stades_sexes)
								.findList();
		}else{
			complements = InformationsComplementaires.find.where()
					.eq("informations_complementaires_observation.observation_validee", Observation.VALIDEE)
					.or(Expr.and(
							Expr.isNull("informations_complementaires_observation.observation_fiche.fiche_date_min"),
							Expr.between("informations_complementaires_observation.observation_fiche.fiche_date", date1.getTime(), date2.getTime())
							),
						Expr.and(
							Expr.ge("informations_complementaires_observation.observation_fiche.fiche_date_min", date1.getTime()),
							Expr.le("informations_complementaires_observation.observation_fiche.fiche_date", date2.getTime())
							)
						)
					.in("informations_complementaires_observation.observation_fiche.fiche_utm", mailles)
					.in("informations_complementaires_stade_sexe", stades_sexes)
					.findList();
		}
		return complements;
	}

	/**
	 * Renvoie le nombre total de témoignage
	 * @param tpps
	 * @return
	 */
	public static int getSomme(List<TemoinsParPeriode> tpps){
		int somme = 0;
		for(TemoinsParPeriode tpp : tpps){
			somme+=tpp.nombreDeTemoignages;
		}
		return somme;
	}
}


text:
'use strict';

Object.defineProperty(exports, '__esModule', {
	value: true
});
exports.login = login;

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

var _axios = require('axios');

var _axios2 = _interopRequireDefault(_axios);

var _configJs = require('./config.js');

function login(username, password) {

	return _axios2['default'].post(_configJs.baseURL + '/auth/login/', {
		username: username, password: password
	});
}

exports['default'] = {
	login: login
};


text:
exports.runFormlyConfig = ['formlyConfig', 'formlyValidationMessages',
 function(formlyConfig, formlyValidationMessages){

  formlyConfig.setType(require('./types/bindTag'));
  formlyConfig.setType(require('./types/countRange'));

}];


text:
.. _changes_0_8:

Version 0.8.0
=============

February 18, 2021

Changelog
---------

New features
............

- Add the the function
  :func:`imblearn.metrics.macro_averaged_mean_absolute_error` returning the
  average across class of the MAE. This metric is used in ordinal
  classification.
  :pr:`780` by :user:`Aurélien Massiot <AurelienMassiot>`.

- Add the class :class:`imblearn.metrics.pairwise.ValueDifferenceMetric` to
  compute pairwise distances between samples containing only categorical
  values.
  :pr:`796` by :user:`Guillaume Lemaitre <glemaitre>`.

- Add the class :class:`imblearn.over_sampling.SMOTEN` to over-sample data
  only containing categorical features.
  :pr:`802` by :user:`Guillaume Lemaitre <glemaitre>`.

- Add the possibility to pass any type of samplers in
  :class:`imblearn.ensemble.BalancedBaggingClassifier` unlocking the
  implementation of methods based on resampled bagging.
  :pr:`808` by :user:`Guillaume Lemaitre <glemaitre>`.

Enhancements
............

- Add option `output_dict` in
  :func:`imblearn.metrics.classification_report_imbalanced` to return a
  dictionary instead of a string.
  :pr:`770` by :user:`Guillaume Lemaitre <glemaitre>`.

- Added an option to generate smoothed bootstrap in
  :class:`imblearn.over_sampling.RandomOverSampler`. It is controls by the
  parameter `shrinkage`. This method is also known as Random Over-Sampling
  Examples (ROSE).
  :pr:`754` by :user:`Andrea Lorenzon <andrealorenzon>` and
  :user:`Guillaume Lemaitre <glemaitre>`.

Bug fixes
.........

- Fix a bug in :class:`imblearn.under_sampling.ClusterCentroids` where
  `voting="hard"` could have lead to select a sample from any class instead of
  the targeted class.
  :pr:`769` by :user:`Guillaume Lemaitre <glemaitre>`.

- Fix a bug in :class:`imblearn.FunctionSampler` where validation was performed
  even with `validate=False` when calling `fit`.
  :pr:`790` by :user:`Guillaume Lemaitre <glemaitre>`.

Maintenance
...........

- Remove requirements files in favour of adding the packages in the
  `extras_require` within the `setup.py` file.
  :pr:`816` by :user:`Guillaume Lemaitre <glemaitre>`.

- Change the website template to use `pydata-sphinx-theme`.
  :pr:`801` by :user:`Guillaume Lemaitre <glemaitre>`.

Deprecation
...........

- The context manager :func:`imblearn.utils.testing.warns` is deprecated in 0.8
  and will be removed 1.0.
  :pr:`815` by :user:`Guillaume Lemaitre <glemaitre>`.


text:
import { actions, actionTypes } from '../'

describe('robot actions', () => {
  it('CONNECT action', () => {
    const expected = {
      type: 'robot:CONNECT',
      payload: { name: 'ot' },
      meta: { robotCommand: true },
    }

    expect(actions.connect('ot')).toEqual(expected)
  })

  it('CONNECT_RESPONSE action', () => {
    const success = {
      type: 'robot:CONNECT_RESPONSE',
      payload: { error: null, sessionCapabilities: ['create'] },
    }
    const failure = {
      type: 'robot:CONNECT_RESPONSE',
      payload: { error: new Error('AH'), sessionCapabilities: [] },
    }

    expect(actions.connectResponse(null, ['create'])).toEqual(success)
    expect(actions.connectResponse(new Error('AH'))).toEqual(failure)
  })

  it('CLEAR_CONNECT_RESPONSE action', () => {
    const expected = { type: 'robot:CLEAR_CONNECT_RESPONSE' }

    expect(actions.clearConnectResponse()).toEqual(expected)
  })

  it('DISCONNECT action', () => {
    const expected = {
      type: 'robot:DISCONNECT',
      meta: { robotCommand: true },
    }

    expect(actions.disconnect()).toEqual(expected)
  })

  it('DISCONNECT_RESPONSE action', () => {
    const success = {
      type: 'robot:DISCONNECT_RESPONSE',
      payload: {},
    }

    expect(actions.disconnectResponse()).toEqual(success)
  })

  it('session response', () => {
    const session = { state: 'READY' }
    const error = new Error('AH')

    const success = {
      type: 'robot:SESSION_RESPONSE',
      payload: session,
      meta: { freshUpload: true },
    }
    const failure = {
      type: 'robot:SESSION_ERROR',
      payload: { error },
      meta: { freshUpload: false },
    }

    expect(actions.sessionResponse(null, session, true)).toEqual(success)
    expect(actions.sessionResponse(error, null, false)).toEqual(failure)
  })

  it('SESSION_UPDATE action', () => {
    const update = { state: 'running', startTime: 1 }
    const expected = {
      type: 'robot:SESSION_UPDATE',
      payload: update,
      meta: { now: 1234 },
    }

    expect(actions.sessionUpdate(update, 1234)).toEqual(expected)
  })

  it('set modules reviewed action', () => {
    expect(actions.setModulesReviewed(false)).toEqual({
      type: 'robot:SET_MODULES_REVIEWED',
      payload: false,
    })

    expect(actions.setModulesReviewed(true)).toEqual({
      type: 'robot:SET_MODULES_REVIEWED',
      payload: true,
    })
  })

  it('set deck populated action', () => {
    expect(actions.setDeckPopulated(false)).toEqual({
      type: actionTypes.SET_DECK_POPULATED,
      payload: false,
    })

    expect(actions.setDeckPopulated(true)).toEqual({
      type: actionTypes.SET_DECK_POPULATED,
      payload: true,
    })
  })

  it('move tip to front action', () => {
    const expected = {
      type: actionTypes.MOVE_TO_FRONT,
      payload: { mount: 'right' },
      meta: { robotCommand: true },
    }

    expect(actions.moveToFront('right')).toEqual(expected)
  })

  it('move tip to front response action', () => {
    const success = {
      type: actionTypes.MOVE_TO_FRONT_RESPONSE,
      error: false,
    }
    const failure = {
      type: actionTypes.MOVE_TO_FRONT_RESPONSE,
      error: true,
      payload: new Error('AH'),
    }

    expect(actions.moveToFrontResponse()).toEqual(success)
    expect(actions.moveToFrontResponse(new Error('AH'))).toEqual(failure)
  })

  it('PICKUP_AND_HOME action', () => {
    const action = {
      type: 'robot:PICKUP_AND_HOME',
      payload: { mount: 'left', slot: '5' },
      meta: { robotCommand: true },
    }

    expect(actions.pickupAndHome('left', '5')).toEqual(action)
  })

  it('PICKUP_AND_HOME response actions', () => {
    const success = {
      type: 'robot:PICKUP_AND_HOME_SUCCESS',
      payload: {},
    }
    const failure = {
      type: 'robot:PICKUP_AND_HOME_FAILURE',
      error: true,
      payload: new Error('AH'),
    }

    expect(actions.pickupAndHomeResponse()).toEqual(success)
    expect(actions.pickupAndHomeResponse(new Error('AH'))).toEqual(failure)
  })

  it('DROP_TIP_AND_HOME action', () => {
    const action = {
      type: 'robot:DROP_TIP_AND_HOME',
      payload: { mount: 'right', slot: '5' },
      meta: { robotCommand: true },
    }

    expect(actions.dropTipAndHome('right', '5')).toEqual(action)
  })

  it('DROP_TIP_AND_HOME response actions', () => {
    const success = {
      type: 'robot:DROP_TIP_AND_HOME_SUCCESS',
      payload: {},
    }

    const failure = {
      type: 'robot:DROP_TIP_AND_HOME_FAILURE',
      error: true,
      payload: new Error('AH'),
    }

    expect(actions.dropTipAndHomeResponse()).toEqual(success)
    expect(actions.dropTipAndHomeResponse(new Error('AH'))).toEqual(failure)
  })

  it('CONFIRM_TIPRACK action', () => {
    const action = {
      type: 'robot:CONFIRM_TIPRACK',
      payload: { mount: 'left', slot: '9' },
      meta: { robotCommand: true },
    }

    expect(actions.confirmTiprack('left', '9')).toEqual(action)
  })

  it('CONFIRM_TIPRACK response actions', () => {
    const success = {
      type: 'robot:CONFIRM_TIPRACK_SUCCESS',
      payload: { tipOn: true },
    }

    const failure = {
      type: 'robot:CONFIRM_TIPRACK_FAILURE',
      error: true,
      payload: new Error('AH'),
    }

    expect(actions.confirmTiprackResponse(null, true)).toEqual(success)
    expect(actions.confirmTiprackResponse(new Error('AH'))).toEqual(failure)
  })

  it('probe tip action', () => {
    const expected = {
      type: actionTypes.PROBE_TIP,
      payload: { mount: 'left' },
      meta: { robotCommand: true },
    }

    expect(actions.probeTip('left')).toEqual(expected)
  })

  it('probe tip response action', () => {
    const success = {
      type: actionTypes.PROBE_TIP_RESPONSE,
      error: false,
    }
    const failure = {
      type: actionTypes.PROBE_TIP_RESPONSE,
      error: true,
      payload: new Error('AH'),
    }

    expect(actions.probeTipResponse()).toEqual(success)
    expect(actions.probeTipResponse(new Error('AH'))).toEqual(failure)
  })

  it('CONFIRM_PROBED action', () => {
    const expected = {
      type: 'robot:CONFIRM_PROBED',
      payload: 'left',
      meta: { robotCommand: true },
    }

    expect(actions.confirmProbed('left')).toEqual(expected)
  })

  it('MOVE_TO action', () => {
    const expected = {
      type: 'robot:MOVE_TO',
      payload: { mount: 'left', slot: '3' },
      meta: { robotCommand: true },
    }

    expect(actions.moveTo('left', '3')).toEqual(expected)
  })

  it('MOVE_TO response actions', () => {
    const success = {
      type: 'robot:MOVE_TO_SUCCESS',
      payload: {},
    }
    const failure = {
      type: 'robot:MOVE_TO_FAILURE',
      error: true,
      payload: new Error('AH'),
    }

    expect(actions.moveToResponse()).toEqual(success)
    expect(actions.moveToResponse(new Error('AH'))).toEqual(failure)
  })

  it('JOG action', () => {
    const expected = {
      type: 'robot:JOG',
      payload: { mount: 'left', axis: 'x', direction: -1, step: 10 },
      meta: { robotCommand: true },
    }

    expect(actions.jog('left', 'x', -1, 10)).toEqual(expected)
  })

  it('jog response action', () => {
    const success = {
      type: 'robot:JOG_SUCCESS',
      payload: {},
    }
    const failure = {
      type: 'robot:JOG_FAILURE',
      error: true,
      payload: new Error('AH'),
    }

    expect(actions.jogResponse()).toEqual(success)
    expect(actions.jogResponse(new Error('AH'))).toEqual(failure)
  })

  it('UPDATE_OFFSET action', () => {
    const expected = {
      type: 'robot:UPDATE_OFFSET',
      payload: { mount: 'left', slot: '2' },
      meta: { robotCommand: true },
    }

    expect(actions.updateOffset('left', '2')).toEqual(expected)
  })

  it('UPDATE_OFFSET response actions', () => {
    const success = {
      type: 'robot:UPDATE_OFFSET_SUCCESS',
      payload: {},
    }
    const failure = {
      type: 'robot:UPDATE_OFFSET_FAILURE',
      error: true,
      payload: new Error('AH'),
    }

    expect(actions.updateOffsetResponse()).toEqual(success)
    expect(actions.updateOffsetResponse(new Error('AH'))).toEqual(failure)
  })

  it('confirm labware action', () => {
    const expected = {
      type: actionTypes.CONFIRM_LABWARE,
      payload: { labware: '2' },
    }

    expect(actions.confirmLabware('2')).toEqual(expected)
  })

  it('run action', () => {
    const expected = {
      type: actionTypes.RUN,
      meta: { robotCommand: true },
    }

    expect(actions.run()).toEqual(expected)
  })

  it('run response action', () => {
    const success = { type: actionTypes.RUN_RESPONSE, error: false }
    const failure = {
      type: actionTypes.RUN_RESPONSE,
      payload: new Error('AH'),
      error: true,
    }

    expect(actions.runResponse()).toEqual(success)
    expect(actions.runResponse(new Error('AH'))).toEqual(failure)
  })

  it('pause action', () => {
    const expected = {
      type: actionTypes.PAUSE,
      meta: { robotCommand: true },
    }

    expect(actions.pause()).toEqual(expected)
  })

  it('pause response action', () => {
    const success = { type: actionTypes.PAUSE_RESPONSE, error: false }
    const failure = {
      type: actionTypes.PAUSE_RESPONSE,
      payload: new Error('AH'),
      error: true,
    }

    expect(actions.pauseResponse()).toEqual(success)
    expect(actions.pauseResponse(new Error('AH'))).toEqual(failure)
  })

  it('resume action', () => {
    const expected = {
      type: actionTypes.RESUME,
      meta: { robotCommand: true },
    }

    expect(actions.resume()).toEqual(expected)
  })

  it('resume response action', () => {
    const success = { type: actionTypes.RESUME_RESPONSE, error: false }
    const failure = {
      type: actionTypes.RESUME_RESPONSE,
      payload: new Error('AHHH'),
      error: true,
    }

    expect(actions.resumeResponse()).toEqual(success)
    expect(actions.resumeResponse(new Error('AHHH'))).toEqual(failure)
  })

  it('cancel action', () => {
    const expected = {
      type: actionTypes.CANCEL,
      meta: { robotCommand: true },
    }

    expect(actions.cancel()).toEqual(expected)
  })

  it('cancel response action', () => {
    const success = { type: actionTypes.CANCEL_RESPONSE, error: false }
    const failure = {
      type: actionTypes.CANCEL_RESPONSE,
      payload: new Error('AHHH'),
      error: true,
    }

    expect(actions.cancelResponse()).toEqual(success)
    expect(actions.cancelResponse(new Error('AHHH'))).toEqual(failure)
  })

  it('robot:REFRESH_SESSION action', () => {
    expect(actions.refreshSession()).toEqual({
      type: 'robot:REFRESH_SESSION',
      meta: { robotCommand: true },
    })
  })

  it('tick run time action', () => {
    const expected = { type: actionTypes.TICK_RUN_TIME }

    expect(actions.tickRunTime()).toEqual(expected)
  })
})


text:
<?php

use app\core\helpers\Html;
use app\core\widgets\ActiveForm;

$this->params['current_menu'] = 'order/delay/index';
?>

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'order_id')->textInput() ?>

    <?= $form->field($model, 'user_id')->textInput() ?>

    <?= $form->field($model, 'price')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'pre_dt')->textInput() ?>

    <?= $form->field($model, 'pay_dt')->textInput() ?>

    <?= $form->field($model, 'note')->textarea(['rows' => 6]) ?>

    <?= $form->field($model, 'created_by')->textInput() ?>

    <?= $form->field($model, 'is_verified')->textInput() ?>

    <?= $form->field($model, 'verified_by')->textInput() ?>

    <?= $form->field($model, 'verified_at')->textInput() ?>

    <?= $form->field($model, 'created_at')->textInput() ?>

    <?= $form->field($model, 'updated_at')->textInput() ?>

    <?= $form->field($model, 'status')->textInput() ?>

            <?=  Html::submitButton('保 存', ['class' => 'btn btn-primary btn-block']) ?>

    <?php ActiveForm::end(); ?>


text:
FROM docker.dever.cc/dev/nodejs:latest

MAINTAINER Rabin "https://github.com/shemic"

ENV APIDOC_HOME=/usr/lib/node_modules/npm/node_modules/apidoc
ENV PATH=$PATH:$APIDOC_HOME/bin

RUN cd /usr/lib/node_modules/npm && npm install apidoc && \
	mkdir -p /root/input && \
	mkdir -p /root/output && \
	mkdir -p /root/config


text:
package main

import "testing"

func TestParseParameters(t *testing.T) {

}


text:
@interface MHProfileInfoMoreCell ()
/// 箭头
@property (nonatomic, readwrite, strong) UIImageView *rightArrow;
/// 三条分割线
@property (nonatomic, readwrite, weak) UIImageView *divider0;
@property (nonatomic, readwrite, weak) UIImageView *divider1;
@property (nonatomic, readwrite, weak) UIImageView *divider2;

@end

@implementation MHProfileInfoMoreCell

+ (instancetype)cellWithTableView:(UITableView *)tableView{
    static NSString *ID = @"ProfileInfoMoreCell";
    MHProfileInfoMoreCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) cell = [self mh_viewFromXib];
    return cell;
}

- (void)setIndexPath:(NSIndexPath *)indexPath rowsInSection:(NSInteger)rows{
    self.divider0.hidden = NO;
    self.divider1.hidden = NO;
    self.divider2.hidden = NO;
    if (rows == 1) {                      /// 一段
        self.divider1.hidden = YES;
    }else if(indexPath.row == 0) {        /// 首行
        self.divider2.hidden = YES;
    }else if(indexPath.row == rows-1) {   /// 末行
        self.divider1.hidden = YES;
        self.divider0.hidden = YES;
    }else{ /// 中间行
        self.divider1.hidden = NO;
        self.divider0.hidden = YES;
        self.divider2.hidden = YES;
    }
}

- (void)awakeFromNib {
    [super awakeFromNib];

    self.accessoryView = self.rightArrow;

    // 分割线
    UIImageView *divider0 = [[UIImageView alloc] init];
    self.divider0 = divider0;
    [self addSubview:divider0];
    UIImageView *divider1 = [[UIImageView alloc] init];
    self.divider1 = divider1;
    [self addSubview:divider1];
    UIImageView *divider2 = [[UIImageView alloc] init];
    self.divider2 = divider2;
    [self addSubview:divider2];
    divider0.backgroundColor = divider1.backgroundColor = divider2.backgroundColor = MH_MAIN_LINE_COLOR_1;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
}

#pragma mark - 布局
- (void)layoutSubviews
{
    [super layoutSubviews];

    /// 布局分割线
    self.divider0.frame = CGRectMake(0, 0, self.mh_width, MHGlobalBottomLineHeight);
    self.divider1.frame = CGRectMake(14, self.mh_height-MHGlobalBottomLineHeight, self.mh_width-14, MHGlobalBottomLineHeight);
    self.divider2.frame = CGRectMake(0, self.mh_height-MHGlobalBottomLineHeight, self.mh_width, MHGlobalBottomLineHeight);
}

#pragma mark - Setter Or Getter
- (UIImageView *)rightArrow{
    if (_rightArrow == nil) {
        _rightArrow = [[UIImageView alloc] initWithImage:MHImageNamed(@"tableview_arrow_8x13")];
    }
    return _rightArrow;
}

@end


text:
"""Test Keysmith."""

import subprocess
import sys

import keysmith

def test_script():
    """Test a full run when directly invoking."""
    subprocess.check_call([sys.executable, keysmith.__file__])

def test_python_m():
    """Test python -m."""
    command = [sys.executable, '-m', keysmith.__name__]
    assert subprocess.run(command).returncode == 0

def test_main_stats():
    """Test a full run with statistics."""
    assert keysmith.main(['--stats']) == 0

def test_main_population():
    """Test a population file that does not exist."""
    assert keysmith.main(['--population', 'nonexistent']) == 1


text:
using System.Threading.Tasks;
using Caliburn.Micro;
using Murmade.Core.Events;
using Murmade.Core.Managers;
using Murmade.Model;

namespace Murmade.Core.Dialog
{
    public abstract class Dialog<TEntity> : Screen, IDialog<TEntity> where TEntity : IEntity
    {
        protected Dialog(IStateManager<TEntity> state)
        {
            State = state;
            State.Initialize();
        }

        public IStateManager<TEntity> State { get; }

        public IDataContext<TEntity> DataContext { get; }

        public abstract void Load();

        public abstract Task LoadAsync();

        public void Handle(DialogLoadedEvent<TEntity> message)
        {
            OnLoaded();
        }

        protected virtual void OnLoaded()
        {
        }
    }
}


text:
import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule }   from '@angular/forms';
import { HttpModule }    from '@angular/http';
import './rxjs-extensions';

import { AppComponent }  from './app.component';
import { DashboardComponent }  from './dashboard.component';

import { LoginComponent }  from './login/login.component';
import { LoginService } from "./login/login.service";
import { ProfileComponent }  from './profile/profile.component';
import { ProfileService } from "./profile/profile.service";
import { StorageService } from "./common/storage.service";
import { AuthService } from "./common/auth.service";
import { ConstantsService } from "./common/constants.service";

import { AppRoutingModule }  from './app-routing.module';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    AppRoutingModule
  ],
  declarations: [
    AppComponent,
    DashboardComponent,
    ProfileComponent,
    LoginComponent
  ],
  providers: [
    AuthService,
    LoginService,
    ProfileService,
    StorageService,
    ConstantsService
  ],
  bootstrap: [AppComponent]
})
export class AppModule {
}


text:
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8"/>
	<title>List Operations</title>
	<meta name="description" content="" />
	<script type="text/javascript">
		var FnLight = new function() {

			// first compose
/*			this.compose = function(...fns) {
				return function composed(result){
					// copy the array of functions
					var list = fns.slice();

					while (list.length > 0) {
						// take the last function off the end of the list
						// and execute it
						result = list.pop()( result );
					}

					return result;
				};
			}
*/

			// compose with reduce
/*			this.compose = function(...fns) {
				return function composed(result){
					return fns.reverse().reduce( function reducer(result,fn){
						return fn( result );
					}, result );
				};
			}
*/

			// compose with first function with multiple arguments
			this.compose = function(...fns) {
				return fns.reverse().reduce( function reducer(fn1,fn2){
					return function composed(...args){
						return fn2( fn1( ...args ) );
					};
				} );
			}

			// compose with recursion
/*			this.compose = function(...fns) {
				// pull off the last two arguments
				var [ fn1, fn2, ...rest ] = fns.reverse();

				var composedFn = function composed(...args){
					return fn2( fn1( ...args ) );
				};

				if (rest.length == 0) return composedFn;

				return compose( ...rest.reverse(), composedFn );
			}
*/

			this.curry = function(fn,arity = fn.length) {
				return (function nextCurried(prevArgs){
					return function curried(nextArg){
						var args = prevArgs.concat( [nextArg] );

						if (args.length >= arity) {
							return fn( ...args );
						}
						else {
							return nextCurried( args );
						}
					};
				})( [] );
			}

			this.looseCurry = function(fn,arity = fn.length) {
				return (function nextCurried(prevArgs){
					return function curried(...nextArgs){
						var args = prevArgs.concat( nextArgs );

						if (args.length >= arity) {
							return fn( ...args );
						}
						else {
							return nextCurried( args );
						}
					};
				})( [] );
			}

			this.not = function (predicate) {
				return function negated(...args){
					return !predicate( ...args );
				};
			}

			this.partial = function(fn,...presetArgs) {
				return function partiallyApplied(...laterArgs){
					return fn( ...presetArgs, ...laterArgs );
				};
			}

			this.partialRight = function(fn, ...presetArgs) {
				return this.reverseArgs(
					this.partial( this.reverseArgs(fn), ...presetArgs.reverse() )
				);
			}

			// pipe
			this.pipe = function(...fns) {
				return function piped(result){
					var list = fns.slice();

					while (list.length > 0) {
						// take the first function from the list
						// and execute it
						result = list.shift()( result );
					}

					return result;
				};
			}

			this.reverseArgs = function(fn) {
				return function argsReversed(...args){
					return fn( ...args.reverse() );
				};
			}

			// pipe as arguments-reversal of compose
			// not working
			//var this.pipe = this.reverseArgs( this.compose );

			this.sum = function(...args) {
				var sum = 0;
				for (let i = 0; i < args.length; i++) {
					sum += args[i];
				}
				return sum;
			}

			this.unary = function(fn) {
				return function onlyOneArg(arg) {
					return fn( arg );
				}
			}

			this.uncurry = function(fn) {
				return function uncurried(...args){
					var ret = fn;

					for (let i = 0; i < args.length; i++) {
						ret = ret( args[i] );
					}

					return ret;
				};
			}

			this.when = function(predicate,fn) {
				return function conditional(...args){
					if (predicate( ...args )) {
						return fn( ...args );
					}
				};
			}

		}
	</script>
</head>
<body>

	<script src="list_operations.js"></script>
</body>
</html>


text:
% SIG.DEFAULTS class
%
% Copyright (C) 2014, Olivier Lartillot
% All rights reserved.
% License: New BSD License. See full text of the license in LICENSE.txt in
% the main folder of the MiningSuite distribution.
%
% For any reuse of the code below, please mention the following
% publication:
% Olivier Lartillot, "The MiningSuite: ?MIRtoolbox 2.0? + ?MIDItoolbox 2.0?
% + pattern mining + ...", AES 53RD INTERNATIONAL CONFERENCE, London, UK,
% 2014

classdef defaults < handle
    properties
        signal = struct('Mix',0,'Center',0);
        Sequence = struct('Mix',0);
    end
    methods (Access = private)
        function obj = defaults
        end
    end
    methods (Static)
        function single = getInstance
            persistent local
            if isempty(local) || ~isvalid(local)
                local = sig.defaults;
            end
            single = local;
        end
        function d = get(class,field)
            h = sig.defaults.getInstance;
            d = h.(class);
            if nargin>1
                d = d.(field);
            end
        end
        function d = set(class,field,val)
            h = sig.defaults.getInstance;
            h.(class).(field) = val;
            d = h.(class);
        end
    end
end