text:
<?php

defined( '_JEXEC' ) or die( 'Restricted access' );
//Error_Reporting(E_ERROR);

jimport('joomla.plugin.plugin');
jimport( 'joomla.filesystem.folder' );
jimport( 'joomla.filesystem.file' );

if (!defined('DS')){
     define('DS',DIRECTORY_SEPARATOR);
}

class plgSystemjdownloads extends JPlugin
{

     private $caching = 0;

    /**
     * Constructor
     *
     * @access      protected
     * @param       object  $subject The object to observe
     * @param       array   $params An array that holds the plugin configuration
     */
     public function __construct(& $subject, $params)
     {
             parent::__construct($subject, $params);
             $this->loadLanguage();

            // get jD language admin file
            $language = JFactory::getLanguage();
            $language->load('com_jdownloads');
     }

     /**
     * This event is triggered after the framework has dispatched the application.
     *
     * @param none
     * @return none
     */
     public function onAfterDispatch() {

         // function to deactivate partially the Joomla 'cache option' for defined sections
         // inspired by cacheControl plugin from www.crosstec.de
         if( JFactory::getApplication()->isSite() && $this->checkCacheRules()){
            $plugin = JPluginHelper::getPlugin('system', 'jdownloads');
            jimport( 'joomla.html.parameter' );
            $pluginParams = $this->params;
            if($pluginParams->def('enable_again_after_dispatch', 0)){
                JFactory::getConfig()->set('caching', $this->caching);
            }
         }
     }

     /**
     * This event is triggered after the framework has loaded and the application initialise method has been called.
     *
     * @param none
     * @return none
     */
     public function onAfterInitialise() {

         $app = JFactory::getApplication();
         $database = JFactory::getDBO();

         // exist the tables?
         $prefix = $database->getPrefix();
         $prefix2 = strtolower($prefix);
         $tablelist = $database->getTableList();
         if ( !in_array ( $prefix.'jdownloads_files', $tablelist ) && !in_array ( $prefix2.'jdownloads_files', $tablelist ) ){
             return;
         }

         $plugin = JPluginHelper::getPlugin('system', 'jdownloads');
         jimport( 'joomla.utilities.utility' );
         // get params
         $params = $this->params;

         //$use_hider = $params->get( 'reduce_log_data_sets_to' );
         //if (!$use_hider) $return = true;

         // No need in admin
         //if( $app->isAdmin() ) return;

         $j = date('Y');
         $m = date('m');
         $d = date('d');
         $h = date('H');
         $min = date('i');
         $sec = date('s');

         $unpublish_time = date('Y-m-d H:i:s',mktime($h,$min,$sec,$m,$d-1,$j));
         $now = date('Y-m-d H:i:s');

         // get all published files with use the timeframe options
         $database->setQuery("SELECT file_id from #__jdownloads_files WHERE published = 1 AND use_timeframe = 1 AND publish_to != '0000-00-00 00:00:00' AND publish_to <= '$now'");
         $files = $database->loadColumn();
         if ($files){
                $fileslist = implode(',', $files);
                $database->setQuery("UPDATE #__jdownloads_files SET published = '0', use_timeframe = '0' WHERE file_id IN ('$fileslist')");
                $database->execute();
         }
         // get all unpublished files with use the timeframe options
         $database->setQuery("SELECT file_id from #__jdownloads_files WHERE published = 0 AND use_timeframe = 1 AND publish_from != '0000-00-00 00:00:00' AND publish_from <= '$now'");
         $files = $database->loadColumn();
         if ($files){
                $fileslist = implode(',', $files);
                $database->setQuery("UPDATE #__jdownloads_files SET published = '1' WHERE file_id IN ('$fileslist')");
                $database->execute();
         }
         return;
     }

     public function onJDUserGroupSettingsBeforeSave($type, $table) {
         return true;
     }

     public function onJDUserGroupSettingsAfterSave($type, $table) {
         global $jlistConfig;
         $app = JFactory::getApplication();
         $db  = JFactory::getDBO();
         $result = array();

         if ($table->use_private_area == 1) {
             if (is_writable($jlistConfig['files.uploaddir'].DS.$jlistConfig['private.area.folder.name'])){
                // get all user IDs from this user group
                $query = $db->getQuery(true);
                $db->setQuery("SELECT a.id FROM #__users as a LEFT JOIN #__user_usergroup_map AS map ON map.user_id = a.id WHERE map.group_id = '".(int)$table->group_id."'");
                $users = $db->loadObjectList();

                $error = $db->getErrorMsg();
                if ($error){
                    $this->setError($error);
                    return false;
                }

                if (count($users) > 0){
                    $rootfolder = $jlistConfig['files.uploaddir'].DS.$jlistConfig['private.area.folder.name'].DS;

                    // create the subfolder for every user when it not exist
                    foreach ($users as $user){
                       if (!JFolder::exists($rootfolder.(int)$user->id)){
                           $result = JFolder::create($rootfolder.(int)$user->id, 0755);
                           if ($result){
                               // copy index.html
                               JFile::copy($rootfolder.'index.html',$rootfolder.(int)$user->id.DS.'index.html');
                           }
                       }

                    }
                }

             } else {
                 // folder not writable
                 JError::raiseWarning( 100, JText::_('COM_JDOWNLOADS_USERGROUPS_PRIVATE_FILES_AREA_ERROR') );
                 return false;
             }
         }
         return true;
     }

     /**
     *   When we use the private area for jD users, we must add for every new user the private folder (when he has the correct usergroup)
     */

     public function onUserAfterSave($user, $isNew, $success) {
         $app = JFactory::getApplication();
         $db  = JFactory::getDBO();
         $groups = array();
         $x = null;

         // check at first that we use the private folder option
         $query = $db->getQuery(true);
         $db->setQuery("SELECT group_id FROM #__jdownloads_usergroups_limits a WHERE use_private_area = '1'");
         $groups = $db->loadRowList();
         if ($groups){
             // get folder path from config
             $db->setQuery("SELECT setting_value FROM #__jdownloads_config WHERE setting_name = 'files.uploaddir'");
             $root_dir = $db->loadResult();
             $db->setQuery("SELECT setting_value FROM #__jdownloads_config WHERE setting_name = 'private.area.folder.name'");
             $private_dir = $db->loadResult();
             // build array which usergroups are activated in jD usergroups_limits table
             foreach ($groups as $group){
                 $used_groups_for_private[] = $group[0];
             }
             // build array which usergroups are selected for the updated or new added user
             foreach ($user['groups'] as $usergroup){
                 $user_groups[] = $usergroup[0];
             }

             for ($i=0; $i < count($user_groups); $i++){
                 $x = array_search ( $user_groups[$i], $used_groups_for_private );
                 if ($x !== false){
                     $private_folder = $root_dir.DS.$private_dir.DS.$user['id'];
                     if (!JFolder::exists($private_folder)){
                         if (JFolder::create($private_folder, 0755)){
                             JFile::copy($root_dir.DS.'index.html',$private_folder.DS.'index.html');
                         }
                     }
                 }
             }
         }
     }

    /**
     *   When we use the private area for jD users, we must remove the users folder, when his user account is deleted
     */
     public function onUserAfterDelete($user, $isNew, $success) {
         $app = JFactory::getApplication();
         $db  = JFactory::getDBO();

         // get folder path from config
         $db->setQuery("SELECT setting_value FROM #__jdownloads_config WHERE setting_name = 'files.uploaddir'");
         $root_dir = $db->loadResult();
         $db->setQuery("SELECT setting_value FROM #__jdownloads_config WHERE setting_name = 'private.area.folder.name'");
         $private_dir = $db->loadResult();
         $private_folder = $root_dir.DS.$private_dir.DS.$user['id'];
         if (JFolder::exists($private_folder)){
             if (JFolder::delete($private_folder)){
                 JError::raiseNotice( 100, JText::_('COM_JDOWNLOADS_USERGROUPS_PRIVATE_FILES_FOLDER_REMOVED') );
             } else {
                 JError::raiseWarning( 100, JText::_('COM_JDOWNLOADS_USERGROUPS_PRIVATE_FILES_FOLDER_REMOVED_ERROR') );
             }

         }
     }

    /**
    * This event is triggered after the framework has rendered the application.
    * Rendering is the process of pushing the document buffers into the template placeholders, retrieving data from the document and pushing it into the JResponse buffer.
    * When this event is triggered the output of the application is available in the response buffer.
    *
    * @param none
    * @return none
    */
    public function onAfterRender() {
         $app = JFactory::getApplication();
         $database = JFactory::getDBO();
         $return = false;

         // exist the tables?
         $prefix = strtolower($database->getPrefix());
         $tablelist = $database->getTableList();
         if ( !in_array ( $prefix.'jdownloads_files', $tablelist ) ){
             $return = true;
         }
         $plugin = JPluginHelper::getPlugin('system', 'jdownloads');
         jimport( 'joomla.utilities.utility' );
         // get params
         $params = $this->params;;
         $use_hider = $params->get( 'use_hider' );
         if (!$use_hider) $return = true;

         // No need in admin
         if (!$app->isAdmin()) {
             $body = JResponse::getBody();
             if (!$return){

                function _getParameter( $name, $default='' ) {
                    $return = "";
                    $return = $this->params->get( $name, $default );
                }

                // define the regular expression
                $regex1 = "#{jdreg}(.*?){/jdreg}#s";
                $regex2 = "#{jdpub}(.*?){/jdpub}#s";

                $regex3 = "#{jdauthor}(.*?){/jdauthor}#s";
                $regex4 = "#{jdeditor}(.*?){/jdeditor}#s";
                $regex5 = "#{jdpublisher}(.*?){/jdpublisher}#s";
                $regex6 = "#{jdmanager}(.*?){/jdmanager}#s";
                $regex7 = "#{jdadmin}(.*?){/jdadmin}#s";
                $regex8 = "#{jdsuper}(.*?){/jdsuper}#s";
                $regex9 = "#{jdspecial}(.*?){/jdspecial}#s";

                // replacement for _reg
                $body = preg_replace_callback( $regex1, array('plgSystemjdownloads', '_reg'), $body );
                // replacement for _pub
                $body = preg_replace_callback( $regex2, array('plgSystemjdownloads', '_pub'), $body );
                // replacements for groups by name
                $body = preg_replace_callback( $regex9, array('plgSystemjdownloads', '_special'), $body );
                $body = preg_replace_callback( $regex3, array('plgSystemjdownloads', '_author'), $body );
                $body = preg_replace_callback( $regex4, array('plgSystemjdownloads', '_editor'), $body );
                $body = preg_replace_callback( $regex5, array('plgSystemjdownloads', '_publisher'), $body );
                $body = preg_replace_callback( $regex6, array('plgSystemjdownloads', '_manager'), $body );
                $body = preg_replace_callback( $regex7, array('plgSystemjdownloads', '_admin'), $body );
                $body = preg_replace_callback( $regex8, array('plgSystemjdownloads', '_super'), $body );

                JResponse::setBody($body);

             } else {
                // Hide option is deactivated - so we must remove maybe the prior inserted placeholder
                $body = str_replace('{jdreg}', '', $body);
                $body = str_replace('{/jdreg}', '', $body);
                $body = str_replace('{jdpub}', '', $body);
                $body = str_replace('{/jdpub}', '', $body);
                $body = str_replace('{jdauthor}', '', $body);
                $body = str_replace('{/jdauthor}', '', $body);
                $body = str_replace('{jdeditor}', '', $body);
                $body = str_replace('{/jdeditor}', '', $body);
                $body = str_replace('{jdpublisher}', '', $body);
                $body = str_replace('{/jdpublisher}', '', $body);
                $body = str_replace('{jdmanager}', '', $body);
                $body = str_replace('{/jdmanager}', '', $body);
                $body = str_replace('{jdadmin}', '', $body);
                $body = str_replace('{/jdadmin}', '', $body);
                $body = str_replace('{jdsuper}', '', $body);
                $body = str_replace('{/jdsuper}', '', $body);
                $body = str_replace('{jdspecial}', '', $body);
                $body = str_replace('{/jdspecial}', '', $body);

                JResponse::setBody($body);
             }
         }
    }

    /**
    * This event is triggered after the framework has loaded and initialised and the router has routed the client request.
    * Routing is the process of examining the request environment to determine which component should receive the request. The component optional parameters are then set in the request object that will be processed when the application is being dispatched.
    * When this event triggers, the router has parsed the route and pushed the request parameters into JRequest to be retrieved by the application.
    *
    * @param none
    * @return none
    */
	public function onAfterRoute(){

         // deactivate Joomla caching when required
         if( JFactory::getApplication()->isSite() && $this->checkCacheRules()){
             $this->caching = JFactory::getConfig()->get('caching');
             JFactory::getConfig()->set('caching', 0);
         }

         // reduce download log data sets when a maximum value exists
         $database = JFactory::getDBO();
         // exist the table?
         $prefix = strtolower($database->getPrefix());
         $tablelist = $database->getTableList();
         if ( !in_array ( $prefix.'jdownloads_logs', $tablelist ) ){
             return;
         }

         $plugin = JPluginHelper::getPlugin('system', 'jdownloads');
         jimport( 'joomla.utilities.utility' );
         // get params
         $params = $this->params;;
         $reduce_data_to = (int)$params->get('reduce_log_data_sets_to');
         if ($reduce_data_to == 0) return;

         // reduce data
         $database->setQuery("SELECT COUNT(*) FROM #__jdownloads_logs");
         $sum = $database->loadResult();
         $sum_delete = $sum - $reduce_data_to;
         if ($sum_delete > 0){
            $database->setQuery("DELETE FROM #__jdownloads_logs ORDER BY id LIMIT $sum_delete");
            $database->execute();
         }

         return;
    }

     /**
     *
     *
     */
     function checkCacheRules(){

        $plugin = JPluginHelper::getPlugin('system', 'jdownloads');
        jimport( 'joomla.html.parameter' );
        $params = $this->params;
        $defs = trim(str_replace("\r","", $params->def('rules','')));
        $defs = explode("\n", $defs);

        foreach($defs as $def){
            if ($def != ''){
                $result = $this->parseQueryString($def);
                if(is_array($result)){
                    $found = 0;
                    $required = count($result);
                    foreach($result As $key => $value){
                        if( JRequest::getVar($key) == $value || ( JRequest::getVar($key, null) !== null && $value == '?' ) ){
                            $found++;
                        }
                    }
                    if($found == $required){
                        return true;
                    }
                }
            }
        }

        return false;
     }

     /**
     *
     *
     * @param mixed $str
     */
     function parseQueryString($str) {
        $op = array();
        $pairs = explode("&", $str);
        foreach ($pairs as $pair) {
            list($k, $v) = array_map("urldecode", explode("=", $pair));
            $op[$k] = $v;
        }
        return $op;
     }

    /**
    *  Functions for hide elements from output for special user groups
    *
    *  Inspired by the hider content plugin from Dioscouri Design
    *  Part of this functions are copyright by Dioscouri Design - www.dioscouri.com
    *
    *
    */

    function _reg( &$matches ) {
        $user = JFactory::getUser();
        $return = '';
        if ($user->id) { $return = $matches[1]; }
        return $return;
    }

    function _pub( &$matches ) {
        $user = JFactory::getUser();
        $return = $matches[1];
        if ($user->id) { $return = ''; }
        return $return;
    }

    function _author( &$matches ) {
        $user = JFactory::getUser();
        $coreUserGroups = $user->getAuthorisedGroups();
        $return = $matches[1];
        if (!in_array(3,$coreUserGroups) && !in_array(8,$coreUserGroups)){
            $return = '';
        }
        return $return;
    }

    function _editor( &$matches ) {
        $user = JFactory::getUser();
        $coreUserGroups = $user->getAuthorisedGroups();
        $return = $matches[1];
        if (!in_array(4,$coreUserGroups) && !in_array(8,$coreUserGroups)){
            $return = '';
        }
        return $return;
    }

    function _publisher( &$matches ) {
        $user = JFactory::getUser();
        $coreUserGroups = $user->getAuthorisedGroups();
        $return = $matches[1];
        if (!in_array(5,$coreUserGroups) && !in_array(8,$coreUserGroups)){
            $return = '';
        }
        return $return;
    }

    function _manager( &$matches ) {
        $user = JFactory::getUser();
        $coreUserGroups = $user->getAuthorisedGroups();
        $return = $matches[1];
        if (!in_array(6,$coreUserGroups) && !in_array(8,$coreUserGroups)){
            $return = '';
        }
        return $return;
    }

    function _admin( &$matches ) {
        $user = JFactory::getUser();
        $coreUserGroups = $user->getAuthorisedGroups();
        $return = $matches[1];
        if (!in_array(7,$coreUserGroups) && !in_array(8,$coreUserGroups)){
            $return = '';
        }
        return $return;
    }

    function _super( &$matches ) {
        $user = JFactory::getUser();
        $coreUserGroups = $user->getAuthorisedGroups();
        $return = $matches[1];
        if (!in_array(8,$coreUserGroups)){
            $return = '';
        }
        return $return;
    }

    function _special( &$matches ) {
        $user = JFactory::getUser();
        $aid = max ($user->getAuthorisedViewLevels());
        $return = $matches[1];
        if ($aid != 3){
            $return = '';
        }
        return $return;
    }

  }
?>


text:
import datetime

import telegram

from config import CUPS_OF

custom_keyboard = [['/login', '/hw', '/top']]
reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard,
                                            resize_keyboard=True)

# TODO: Исправить приветствие. Его могут видеть как студенты так и
def on_start(bot, update):
    update.message.reply_text("Велкам! Для начала залогиньтесь "
                              "(если вы ещё не)."
                              " Потом проверьте домашки. "
                              "/top покажет лидеров",
                              reply_markup=reply_markup)

def send_startup_greeting(bot, chat_id):
    now = datetime.datetime.now().strftime("%B %d, %H:%M")
    text_fmt = ('Successfully launched! '
                'Current time is:{} \n'
                ' Cups of tea: {}')
    bot.send_message(chat_id=chat_id,
                     text=text_fmt.format(now, CUPS_OF))

redpajama_set_name: RedPajamaGithub


text:
__author__ = 'Alex Dzul'
import traceback

class InvalidYQLQueryError(Exception):
    pass

class YQLRequestError(Exception):
    pass

class MultipleValueError(Exception):
    pass

def format_sys_errors(user_sys, with_traceback=False):
    """
    Formatea el error obtenido en una función o documento
    """
    if user_sys:
        etype, value, tb = user_sys.exc_info()
        tipo_error_name = etype.__name__
        error_args = value.args
        if with_traceback:
            mensaje = "{0} {1} {2}".format(tipo_error_name, error_args, traceback.extract_tb(tb))
        else:
            traceback.print_tb(tb)
            mensaje = "{0} {1}".format(tipo_error_name, error_args)
        return mensaje
    else:
        return ""


text:
package cluster

/**
* Configuration for Node group object type resource.
*/
type Clusternodegroup struct {
	/**
	* Name of the nodegroup. The name uniquely identifies the nodegroup on the cluster.
	*/
	Name string `json:"name,omitempty"`
	/**
	* Specifies whether cluster nodes, that are not part of the nodegroup, will be used as backup for the nodegroup.
		* Enabled - When one of the nodes goes down, no other cluster node is picked up to replace it. When the node comes up, it will continue being part of the nodegroup.
		* Disabled - When one of the nodes goes down, a non-nodegroup cluster node is picked up and acts as part of the nodegroup. When the original node of the nodegroup comes up, the backup node will be replaced.
	*/
	Strict string `json:"strict,omitempty"`
	/**
	* Only one node can be bound to nodegroup with this option enabled. It specifies whether to prempt the traffic for the entities bound to nodegroup when owner node goes down and rejoins the cluster.
		* Enabled - When owner node goes down, backup node will become the owner node and takes the traffic for the entities bound to the nodegroup. When bound node rejoins the cluster, traffic for the entities bound to nodegroup will not be steered back to this bound node. Current owner will have the ownership till it goes down.
		* Disabled - When one of the nodes goes down, a non-nodegroup cluster node is picked up and acts as part of the nodegroup. When the original node of the nodegroup comes up, the backup node will be replaced.
	*/
	Sticky string `json:"sticky,omitempty"`
	/**
	* State of the nodegroup. All the nodes binding to this nodegroup must have the same state. ACTIVE/SPARE/PASSIVE
	*/
	State string `json:"state,omitempty"`
	/**
	* Priority of Nodegroup. This priority is used for all the nodes bound to the nodegroup for Nodegroup selection
	*/
	Priority int `json:"priority,omitempty"`

	//------- Read only Parameter ---------;

	Currentnodemask string `json:"currentnodemask,omitempty"`
	Backupnodemask string `json:"backupnodemask,omitempty"`
	Boundedentitiescntfrompe string `json:"boundedentitiescntfrompe,omitempty"`
	Activelist string `json:"activelist,omitempty"`
	Backuplist string `json:"backuplist,omitempty"`

}


text:
// CSim - (c) 2014-17 Baltasar MIT License <jbgarcia@uvigo.es>

namespace CSim.Core.Opcodes {
	using CSim.Core.Literals;
	using CSim.Core.Exceptions;

	/// <summary>
	/// Mul opcode, allowing operations such as 5*3.
	/// </summary>
	public class MulOpcode: Opcode {
		/// <summary>The opcode's representing value.</summary>
		public const byte OpcodeValue = 0xEA;

		/// <summary>
		/// Initializes a new instance of the <see cref="T:CSim.Core.Opcodes.MulOpcode"/> class.
		/// </summary>
		/// <param name="m">The <see cref="Machine"/> this opcode will be executed in.</param>
		public MulOpcode(Machine m)
			:base(m)
		{
		}

		/// <summary>
		/// Returns the result of a * b
		/// </summary>
		public override void Execute()
		{
			// Check arguments in stack
			if ( this.Machine.ExecutionStack.Count < 2 ) {
				throw new RuntimeException( L10n.Get( L10n.Id.ErrMissingArguments ) );
			}

			// Take ops
			Variable op1 = this.Machine.ExecutionStack.Pop().SolveToVariable();
			Variable op2 = this.Machine.ExecutionStack.Pop().SolveToVariable();

            ChkTypeCompatibility( op1, op2 );

			// Now yes, do it
			Literal litResult;

			if ( op1.Type is Types.Primitives.Double
		      || op2.Type is Types.Primitives.Double )
			{
				litResult = new DoubleLiteral( this.Machine,
				                              op1.LiteralValue.ToDouble()
				                              * op2.LiteralValue.ToDouble() );
			} else {
				litResult = new IntLiteral( this.Machine,
				                           op1.LiteralValue.GetValueAsInteger()
				                           * op2.LiteralValue.GetValueAsInteger() );
			}

			// Store in the temp vble and end
			Variable result = Variable.CreateTempVariable( litResult );
			this.Machine.ExecutionStack.Push( result );
			return;
		}

        /// <summary>
        /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:CSim.Core.Opcodes.MulOpcode"/>.
        /// </summary>
        /// <returns>A <see cref="T:System.String"/> that represents the current <see cref="T:CSim.Core.Opcodes.MulOpcode"/>.</returns>
        public override string ToString()
        {
            return string.Format( "[MulOpcode (0x{0,2:X}): rvalue(POP) * rvalue(POP)]",
                                    OpcodeValue );
        }
	}
}


text:
@interface DKActionConfigurationTableCellView : NSTableCellView

@property (weak) IBOutlet NSPopUpButton *typeMenu;
@property (weak) IBOutlet NSView *actionConfigContainer;

-(IBAction)typeMenuDidChange:(id)sender;

@end


text:
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

defined('MOODLE_INTERNAL') || die();
require_once($CFG->libdir.'/oauthlib.php');

/**
 * Authentication class to access Dropbox API
 *
 * @package    repository_dropbox
 * @copyright  2010 Dongsheng Cai
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
class dropbox extends oauth_helper {
    /** @var string dropbox access type, can be dropbox or sandbox */
    private $mode = 'dropbox';
    /** @var string dropbox api url*/
    private $dropbox_api = 'https://api.dropbox.com/1';
    /** @var string dropbox content api url*/
    private $dropbox_content_api = 'https://api-content.dropbox.com/1';

    /**
     * Constructor for dropbox class
     *
     * @param array $args
     */
    function __construct($args) {
        parent::__construct($args);
    }

    /**
     * Get file listing from dropbox
     *
     * @param string $path
     * @param string $token
     * @param string $secret
     * @return array
     */
    public function get_listing($path='/', $token='', $secret='') {
        $url = $this->dropbox_api.'/metadata/'.$this->mode.$path;
        $content = $this->get($url, array(), $token, $secret);
        $data = json_decode($content);
        return $data;
    }

    /**
     * Prepares the filename to pass to Dropbox API as part of URL
     *
     * @param string $filepath
     * @return string
     */
    protected function prepare_filepath($filepath) {
        $info = pathinfo($filepath);
        $dirname = $info['dirname'];
        $basename = $info['basename'];
        $filepath = $dirname . rawurlencode($basename);
        if ($dirname != '/') {
            $filepath = $dirname . '/' . $basename;
            $filepath = str_replace("%2F", "/", rawurlencode($filepath));
        }
        return $filepath;
    }

    /**
     * Retrieves the default (64x64) thumbnail for dropbox file
     *
     * @throws moodle_exception when file could not be downloaded
     *
     * @param string $filepath local path in Dropbox
     * @param string $saveas path to file to save the result
     * @param int $timeout request timeout in seconds, 0 means no timeout
     * @return array with attributes 'path' and 'url'
     */
    public function get_thumbnail($filepath, $saveas, $timeout = 0) {
        $url = $this->dropbox_content_api.'/thumbnails/'.$this->mode.$this->prepare_filepath($filepath);
        if (!($fp = fopen($saveas, 'w'))) {
            throw new moodle_exception('cannotwritefile', 'error', '', $saveas);
        }
        $this->setup_oauth_http_options(array('timeout' => $timeout, 'file' => $fp, 'BINARYTRANSFER' => true));
        $result = $this->get($url);
        fclose($fp);
        if ($result === true) {
            return array('path'=>$saveas, 'url'=>$url);
        } else {
            unlink($saveas);
            throw new moodle_exception('errorwhiledownload', 'repository', '', $result);
        }
    }

    /**
     * Downloads a file from Dropbox and saves it locally
     *
     * @throws moodle_exception when file could not be downloaded
     *
     * @param string $filepath local path in Dropbox
     * @param string $saveas path to file to save the result
     * @param int $timeout request timeout in seconds, 0 means no timeout
     * @return array with attributes 'path' and 'url'
     */
    public function get_file($filepath, $saveas, $timeout = 0) {
        $url = $this->dropbox_content_api.'/files/'.$this->mode.$this->prepare_filepath($filepath);
        if (!($fp = fopen($saveas, 'w'))) {
            throw new moodle_exception('cannotwritefile', 'error', '', $saveas);
        }
        $this->setup_oauth_http_options(array('timeout' => $timeout, 'file' => $fp, 'BINARYTRANSFER' => true));
        $result = $this->get($url);
        fclose($fp);
        if ($result === true) {
            return array('path'=>$saveas, 'url'=>$url);
        } else {
            unlink($saveas);
            throw new moodle_exception('errorwhiledownload', 'repository', '', $result);
        }
    }

    /**
     * Returns direct link to Dropbox file
     *
     * @param string $filepath local path in Dropbox
     * @param int $timeout request timeout in seconds, 0 means no timeout
     * @return string|null information object or null if request failed with an error
     */
    public function get_file_share_link($filepath, $timeout = 0) {
        $url = $this->dropbox_api.'/shares/'.$this->mode.$this->prepare_filepath($filepath);
        $this->setup_oauth_http_options(array('timeout' => $timeout));
        $result = $this->post($url, array('short_url'=>0));
        if (!$this->http->get_errno()) {
            $data = json_decode($result);
            if (isset($data->url)) {
                return $data->url;
            }
        }
        return null;
    }

    /**
     * Sets Dropbox API mode (dropbox or sandbox, default dropbox)
     *
     * @param string $mode
     */
    public function set_mode($mode) {
        $this->mode = $mode;
    }
}


text:
from google.appengine.ext import db
from django.views.generic.simple import direct_to_template
from django.http import HttpResponseRedirect
from authority.decorators import permission_required_or_403
from livecenter.utils import default_location, redirect
import counter
from .models import Finance
from .forms import FinanceForm
#from livecenter.models import MicroFinance, LivelihoodLocation, Location
#from livecenter.utils import migrate_photo
#from .models import Container

def index(request):
    return direct_to_template(request, 'microfinance/index.html', {
        'finances': Finance.objects.all(),
        'count': Finance.counter_value(),
        'lokasi': default_location(),
        })

def show(request, mid):
    mf = Finance.objects.get(pk=mid)

    kontak = [
        ['Nama', mf.contact_name],
        ['Telepon selular', mf.mobile],
        ['Alamat', mf.address],
        ['Kabupaten', mf.district.name],
        ['Kecamatan', mf.sub_district.name],
        ]

    keuangan = [
        ['Tipe LKM', mf.kind_lkm],
        ['Total aset', '%d Rupiah' % mf.total_asset],
        ['Total penyediaan dana pinjaman', '%d Rupiah' % mf.total_sedia_dana_pinjaman],
        ['Total pencairan', '%d Rupiah' % mf.total_penyaluran],
        ['Sektor usaha', mf.sektor_usaha],
        ['Persyaratan pinjaman', mf.persyaratan_pinjaman],
        ['Persyaratan agunan', mf.persyaratan_agunan],
        ['Jangkauan wilayah usaha', mf.jangkauan_wilayah_usaha],
        ['Nilai pinjaman maksimum', mf.nilai_maks_pinjaman],
        ['Jangka waktu pinjaman', mf.jangka_wkt_pinjaman],
        ['Bunga pinjaman', '%s %%' % mf.margin_bunga],
        ['Bantuan untuk penerima manfaat JFPR', mf.bantuan_penerima_manfaat_jfpr],
        ['Pelatihan', '<none>'],
        ['Pengelolaan usaha', '%d kali' % mf.manajemen_usaha],
        ['Pembukuan', '%d kali' % mf.pembukuan],
        ['Akses pasar', '%d kali' % mf.akses_pasar],
        ['Keuangan mikro', '%d kali' % mf.keuangan_mikro],
        ['Penguatan pelayanan', '<none>'],
        ['Petugas akun', '%d kali' % mf.ao],
        ['Layanan pelanggan', '%d kali' % mf.cs],
        ['Kasir', '%d kali' % mf.tl],
        ['Kelayakan usaha', '%d kali' % mf.kelayakan_usaha],
        ]

    return direct_to_template(request, 'microfinance/show.html', {
        'microfinance': mf,
        'kontak': kontak,
        'keuangan': keuangan,
        'lokasi': default_location(mf.geo_pos),
        })

def create(request):
    mf = Finance()
    return show_edit(request, mf)

def edit(request, mid):
    mf = Finance.objects.get(pk=mid)
    return show_edit(request, mf)

@permission_required_or_403('microfinance.change_finance')
def show_edit(request, mf):
    form = FinanceForm(instance=mf)
    if request.POST:
        if 'delete' in request.POST:
            mf.delete()
            return redirect(request, '/microfinance')
        if form.is_valid():
            form.save()
            return redirect(request, '/microfinance/show/%d' % mf.id)
    return direct_to_template(request, 'microfinance/edit.html', {
        'form': form
        })

"""
def migrate(request):
    limit = 'limit' in request.GET and int(request.GET['limit']) or 20
    offset = len(Finance.objects.all())
    sources = MicroFinance.all().order('__key__')
    targets = []
    for source in sources.fetch(limit=limit, offset=offset):
        target = Container.objects.filter(microfinance=str(source.key()))
        if target:
            continue
        target = Finance(
            name_org=source.name_org,
            contact_name=source.contact_name,
            address=source.address,
            geo_pos=str(source.geo_pos) != 'nan,nan' and source.geo_pos or '',
            sub_district=source.sub_district and Location.objects.filter(lid=source.sub_district.dl_id)[0] or None,
            district=source.district and Location.objects.filter(lid=source.district.dl_id)[0] or None,
            mobile=source.mobile,
            kind_lkm=source.kind_lkm,
            total_asset=source.total_asset,
            total_sedia_dana_pinjaman=source.total_sedia_dana_pinjaman,
            total_penyaluran=source.total_penyaluran,
            sektor_usaha=source.sektor_usaha,
            persyaratan_pinjaman=source.persyaratan_pinjaman,
            persyaratan_agunan=source.persyaratan_agunan,
            jangkauan_wilayah_usaha=source.jangkauan_wilayah_usaha,
            nilai_maks_pinjaman=source.nilai_maks_pinjaman,
            jangka_wkt_pinjaman=source.jangka_wkt_pinjaman,
            margin_bunga=source.margin_bunga,
            bantuan_penerima_manfaat_jfpr=source.bantuan_penerima_mamfaat_jfpr,
            manajemen_usaha=source.manajemen_usaha,
            pembukuan=source.pembukuan,
            akses_pasar=source.akses_pasar,
            keuangan_mikro=source.keuangan_mikro,
            ao=source.ao,
            cs=source.cs,
            tl=source.tl,
            kelayakan_usaha=source.kelayakan_usaha,
            photo=migrate_photo(request, source))
        target.save()
        c = Container(finance=target, microfinance=str(source.key()))
        c.save()
        targets.append(target)
    return direct_to_template(request, 'microfinance/migrate.html', {
        'targets': targets,
        })

def migrate_delete(request): # danger
    limit = 20
    targets = []
    for target in Finance.objects.all()[:limit]:
        targets.append(target)
        target.delete()
    for c in Container.objects.all()[:limit]:
        c.delete()
    return direct_to_template(request, 'microfinance/migrate.html', {
        'targets': targets,
        })
"""


text:
#ifndef CLIF_TESTING_CONST_CHAR_PTR_H_
#define CLIF_TESTING_CONST_CHAR_PTR_H_

#include <string>

namespace clif_testing {

inline std::string PassConstCharPtr(const char* arg) {
  return std::string(arg);
}

inline const char* ReturnConstCharPtr() { return "string literal"; }

}  // namespace clif_testing

#endif  // CLIF_TESTING_CONST_CHAR_PTR_H_


text:
PATIENT RECORDS

        <form class="form-inline">

                <input type="text" ng-model="search" class="form-control" placeholder="Search">

            <input ng-if="((currentUser.role.indexOf('admin') > -1)||(currentUser.role.indexOf('super') > -1))" class="btn btn-primary" onclick="location.href='#/registerPatient';" role="button" value="Register New Patient">
        </form>

                    Id

                    First Name

                    Last Name

                    Date of Birth

                    Program

                    {{user.p_id}}
                    {{user.p_first_name}}
                    {{user.p_last_name}}
                    {{user.p_dob | date}}
                    {{user.p_program.join(', ')}}

                        <a style="font-size: 17px;"
                        id="info"
                        tabindex="0"
                        data-container="body"
                        class="glyphicon glyphicon-info-sign"
                        data-trigger="click"
                        data-placement="bottom"
                        data-html="true"
                        data-content=
                                    "

                                        Phone: {{user.p_mobile_contact}}

                                        Email: {{user.p_email}}

"
                        title="Contact Details"
                        data-toggle="popover">

                            New!

                            New!

        <dir-pagination-controls
            pagination-id="paginate1"
            max-size="150"
            direction-links="true"
            boundary-links="true" >
        </dir-pagination-controls>

De-Active Patient Profiles

                    Id

                    First Name

                    Last Name

                    Date of Birth

                    Program

                    {{user.p_id}}
                    {{user.p_first_name}}
                    {{user.p_last_name}}
                    {{user.p_dob | date}}
                    {{user.p_program.join(', ')}}

                        <a style="font-size: 17px;" id="info"
                        tabindex="0"
                        data-container="body"
                        class="glyphicon glyphicon-info-sign"
                        data-trigger="click"
                        data-placement="bottom"
                        data-html="true"
                        data-content=
                                    "

                                        Phone: {{user.p_mobile_contact}}

                                        Email: {{user.p_email}}

"
                        title="Contact Details"
                        data-toggle="popover">

        <dir-pagination-controls
            pagination-id="paginate2"
            max-size="15"
            direction-links="true"
            boundary-links="true" >
        </dir-pagination-controls>


text:
using System.Web;
using System.Web.Optimization;

namespace RentACar
{
    public class BundleConfig
    {
        // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.validate*"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include(
                "~/Scripts/jquery-ui-1.12.1.js"));

            // Use the development version of Modernizr to develop with and learn from. Then, when you're
            // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));

            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                      "~/Scripts/bootstrap.js",
                      "~/Scripts/respond.js",
                      "~/Scripts/bootstrap-datetimepicker.js"));

            bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap*",
                      "~/Content/site.css",
                      "~/Content/custom.css",
                      "~/Content/Datatables/datatables.min.css"));

            bundles.Add(new ScriptBundle("~/bundles/custom").Include(
                    "~/Scripts/Custom/Global/facebook-sdk.js",
                    "~/Scripts/Custom/Global/order-functions.js"
                ));

            bundles.Add(new ScriptBundle("~/bundles/modal").Include(
                    "~/Scripts/Custom/Modal/modal.js",
                    "~/Scripts/Custom/Modal/modal-submit.js"
                ));

            bundles.Add(new ScriptBundle("~/bundles/moment").Include(
                    "~/Scripts/moment.js",
                    "~/Scripts/moment-with-locales.js"
                ));

            bundles.Add(new ScriptBundle("~/bundles/datepicker").Include(
                    "~/Scripts/datepicker.js"
                ));

            bundles.Add(new ScriptBundle("~/bundles/fileprocess").Include(
                    "~/Scripts/Custom/Global/file-processing.js"
                ));

            bundles.Add(new ScriptBundle("~/bundles/datatables").Include(
                   "~/Scripts/Custom/Datatables/datatables.min.js",
                   "~/Scripts/Custom/Datatables/dataTables-global.js"
               ));
        }
    }
}


text:
var P = require('p-promise'),
    _ = require('lodash');

exports.waitFor = function waitFor(milliseconds)
{
    var deferred = P.defer();
    setTimeout(deferred.resolve, milliseconds);
    return deferred.promise;
};

exports.serializeArgument = function serializeArgument(argument)
{
    var value = String(argument),
        length = Buffer.byteLength(value);

    return '$' + length + '\r\n' + value + '\r\n';
};

exports.decodeBuffers = function decodeBuffers(reply)
{
    if (Buffer.isBuffer(reply))
        return String(reply);

    if (Array.isArray(reply))
        return _.map(reply, decodeBuffers);

    return reply;
};

exports.rejectQueueWith = function rejectQueueWith(queue, message)
{
    while (queue.length)
    {
        var command = queue.shift();
        command.isQueued = command.beginsQueue = command.endsQueue = command.discardsQueue = false;
        command.rejectWith(message);
    }
};


text:
package com.roche.sequencing.bioinformatics.common.sequence;

/**
 *
 * Enum representation of the four basic nucleotide codes
 *
 */
public enum NucleotideCode implements ICode {
	ADENINE("Adenine", "A", "T"), CYTOSINE("Cytosine", "C", "G"), GUANINE("Gaunine", "G", "C"), THYMINE("Thymine", "T", "A");

	private final String abbreviation;
	private final String name;
	private final String complimentAbbreviation;

	private NucleotideCode(String name, String abbreviation, String complimentAbbreviation) {
		this.name = name;
		this.abbreviation = abbreviation;
		this.complimentAbbreviation = complimentAbbreviation;
	}

	/**
	 * @return string abbreviation for this nucleotide code
	 */
	public String getAbbreviation() {
		return abbreviation;
	}

	/**
	 * @return the name of the nucleotide this code represents
	 */
	public String getName() {
		return name;
	}

	@Override
	public boolean matches(ICode nucleotide) {
		boolean matches = (nucleotide instanceof NucleotideCode) && this.abbreviation.equals(((NucleotideCode) nucleotide).abbreviation);
		if (!matches && nucleotide instanceof IupacNucleotideCode) {
			matches = nucleotide.matches(this);
		}
		return matches;
	}

	/**
	 * @param codeAsString
	 * @return returns null if no such string is found
	 */
	static NucleotideCode[] getNucleotidesFromString(String nucleotidesAsString) {
		nucleotidesAsString = nucleotidesAsString.toUpperCase();
		NucleotideCode[] nucleotides = new NucleotideCode[nucleotidesAsString.length()];

		for (int i = 0; i < nucleotidesAsString.length(); i++) {
			String characterToTranslate = nucleotidesAsString.substring(i, i + 1);
			NucleotideCode matchingNucleotide = getNucleotideFromString(characterToTranslate);

			if (matchingNucleotide != null) {
				nucleotides[i] = matchingNucleotide;
			} else {
				throw new IllegalArgumentException("Unable to translate character[" + characterToTranslate + "] from nucleotidesAsString[" + nucleotidesAsString + "].");
			}
		}

		return nucleotides;
	}

	/**
	 *
	 * @param nucleotideAsString
	 * @return the NucleotideCode associate with the provided string
	 */
	public static NucleotideCode getNucleotideFromString(String nucleotideAsString) {
		NucleotideCode matchingNucleotide = NucleotideCodeLookup.getInstance().getNucleotideCode(nucleotideAsString);

		return matchingNucleotide;
	}

	@Override
	public IupacNucleotideCode getIupaceNucleotideCodeEquivalent() {
		IupacNucleotideCode iupaceNucleotideCodeEquivalent = null;

		if (this == CYTOSINE) {
			iupaceNucleotideCodeEquivalent = IupacNucleotideCode.C;
		} else if (this == GUANINE) {
			iupaceNucleotideCodeEquivalent = IupacNucleotideCode.G;
		} else if (this == ADENINE) {
			iupaceNucleotideCodeEquivalent = IupacNucleotideCode.A;
		} else if (this == THYMINE) {
			iupaceNucleotideCodeEquivalent = IupacNucleotideCode.T;
		}

		return iupaceNucleotideCodeEquivalent;
	}

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

	@Override
	public NucleotideCode[] getNucleotides() {
		return new NucleotideCode[] { this };
	}

	@Override
	public ICode getComplimentCode() {
		return getNucleotideFromString(complimentAbbreviation);
	}

}


text:
package com.creedon.androidphotobrowser;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;

/**
 * _   _ _______   ________ _       _____   __
 * | \ | |_   _\ \ / /| ___ \ |     / _ \ \ / /
 * |  \| | | |  \ V / | |_/ / |    / /_\ \ V /
 * | . ` | | |  /   \ |  __/| |    |  _  |\ /
 * | |\  |_| |_/ /^\ \| |   | |____| | | || |
 * \_| \_/\___/\/   \/\_|   \_____/\_| |_/\_/
 * <p>
 * Created by jameskong on 21/4/2017.
 */

public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
    public interface OnItemClickListener {
        void onItemClick(View view, int position);

        void onItemLongClick(View view, int position);
    }

    private OnItemClickListener mListener;

    private GestureDetector mGestureDetector;

    public RecyclerItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener) {
        mListener = listener;

        mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                return true;
            }

            @Override
            public void onLongPress(MotionEvent e) {
                View childView = recyclerView.findChildViewUnder(e.getX(), e.getY());

                if (childView != null && mListener != null) {
                    mListener.onItemLongClick(childView, recyclerView.getChildAdapterPosition(childView));
                }
            }
        });
    }

    @Override
    public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
        View childView = view.findChildViewUnder(e.getX(), e.getY());

        if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
            mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
        }

        return false;
    }

    @Override
    public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {
    }

    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
    }
}


text:
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __MAIN_H
#define __MAIN_H

#ifdef __cplusplus
extern "C" {
#endif

/* Includes ------------------------------------------------------------------*/

#include "cube_hal.h"
#include "x_nucleo_iks01a1.h"
#include "x_nucleo_iks01a1_accelero.h"
#include "com.h"

/* Exported types ------------------------------------------------------------*/
/* Exported constants --------------------------------------------------------*/
/* Exported macro ------------------------------------------------------------*/
/* Exported variables --------------------------------------------------------*/
/* Exported functions ------------------------------------------------------- */

uint32_t user_currentTimeGetTick( void );
uint32_t user_currentTimeGetElapsedMS( uint32_t Tick1 );

void Error_Handler( void );
void RTC_TimeRegulate( uint8_t hh, uint8_t mm, uint8_t ss );

#ifdef __cplusplus
}
#endif

#endif /* __MAIN_H */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
foo


text:
/**
 * @author Homer Glascock <HopGlascock@gmail.com>
 * @update zhixin wen <wenzhixin2010@gmail.com>
 */

const Utils = $.fn.bootstrapTable.utils

$.extend($.fn.bootstrapTable.locales, {
  formatCopyRows () {
    return 'Copy Rows'
  }
})
$.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales)

$.extend($.fn.bootstrapTable.defaults.icons, {
  copy: {
    bootstrap3: 'glyphicon-copy icon-pencil',
    bootstrap5: 'bi-clipboard',
    materialize: 'content_copy',
    'bootstrap-table': 'icon-copy'
  }[$.fn.bootstrapTable.theme] || 'fa-copy'
})

const copyText = text => {
  const textField = document.createElement('textarea')

  $(textField).html(text)
  document.body.appendChild(textField)
  textField.select()

  try {
    document.execCommand('copy')
  } catch (e) {
    console.warn('Oops, unable to copy')
  }
  $(textField).remove()
}

$.extend($.fn.bootstrapTable.defaults, {
  showCopyRows: false,
  copyWithHidden: false,
  copyDelimiter: ', ',
  copyNewline: '\n'
})

$.extend($.fn.bootstrapTable.columnDefaults, {
  ignoreCopy: false,
  rawCopy: false
})

$.fn.bootstrapTable.methods.push(
  'copyColumnsToClipboard'
)

$.BootstrapTable = class extends $.BootstrapTable {

  initToolbar (...args) {
    if (this.options.showCopyRows && this.header.stateField) {
      this.buttons = Object.assign(this.buttons, {
        copyRows: {
          text: this.options.formatCopyRows(),
          icon: this.options.icons.copy,
          event: this.copyColumnsToClipboard,
          attributes: {
            'aria-label': this.options.formatCopyRows(),
            title: this.options.formatCopyRows()
          }
        }
      })
    }

    super.initToolbar(...args)
    this.$copyButton = this.$toolbar.find('>.columns [name="copyRows"]')

    if (this.options.showCopyRows && this.header.stateField) {
      this.updateCopyButton()
    }
  }

  copyColumnsToClipboard () {
    const rows = []

    $.each(this.getSelections(), (index, row) => {
      const cols = []

      $.each(this.options.columns[0], (indy, column) => {
        if (
          column.field !== this.header.stateField &&
          (!this.options.copyWithHidden || this.options.copyWithHidden && column.visible) &&
          !column.ignoreCopy
        ) {
          if (row[column.field] !== null) {
            const columnValue = column.rawCopy ? row[column.field] : Utils.calculateObjectValue(column, this.header.formatters[indy], [row[column.field], row, index], row[column.field])

            cols.push(columnValue)
          }
        }
      })
      rows.push(cols.join(this.options.copyDelimiter))
    })

    copyText(rows.join(this.options.copyNewline))
  }

  updateSelected () {
    super.updateSelected()
    this.updateCopyButton()
  }

  updateCopyButton () {
    if (this.options.showCopyRows && this.header.stateField && this.$copyButton) {
      this.$copyButton.prop('disabled', !this.getSelections().length)
    }
  }
}


text:
#pragma once
#include <aws/gamelift/GameLift_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/gamelift/model/FleetStatus.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace GameLift
{
namespace Model
{

  /**
   *
A fleet location and its life-cycle state. A location state object might be
   * used to describe a fleet's remote location or home Region. Life-cycle state
   * tracks the progress of launching the first instance in a new location and
   * preparing it for game hosting, and then removing all instances and deleting the
   * location from the fleet.

 Related actions

   * CreateFleet | CreateFleetLocations | DeleteFleetLocations
   *

See Also:
   AWS
   * API Reference

   */
  class AWS_GAMELIFT_API LocationState
  {
  public:
    LocationState();
    LocationState(Aws::Utils::Json::JsonView jsonValue);
    LocationState& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The fleet location, expressed as an Amazon Web Services Region code such as
     * us-west-2.

     */
    inline const Aws::String& GetLocation() const{ return m_location; }

    /**
     *
The fleet location, expressed as an Amazon Web Services Region code such as
     * us-west-2.

     */
    inline bool LocationHasBeenSet() const { return m_locationHasBeenSet; }

    /**
     *
The fleet location, expressed as an Amazon Web Services Region code such as
     * us-west-2.

     */
    inline void SetLocation(const Aws::String& value) { m_locationHasBeenSet = true; m_location = value; }

    /**
     *
The fleet location, expressed as an Amazon Web Services Region code such as
     * us-west-2.

     */
    inline void SetLocation(Aws::String&& value) { m_locationHasBeenSet = true; m_location = std::move(value); }

    /**
     *
The fleet location, expressed as an Amazon Web Services Region code such as
     * us-west-2.

     */
    inline void SetLocation(const char* value) { m_locationHasBeenSet = true; m_location.assign(value); }

    /**
     *
The fleet location, expressed as an Amazon Web Services Region code such as
     * us-west-2.

     */
    inline LocationState& WithLocation(const Aws::String& value) { SetLocation(value); return *this;}

    /**
     *
The fleet location, expressed as an Amazon Web Services Region code such as
     * us-west-2.

     */
    inline LocationState& WithLocation(Aws::String&& value) { SetLocation(std::move(value)); return *this;}

    /**
     *
The fleet location, expressed as an Amazon Web Services Region code such as
     * us-west-2.

     */
    inline LocationState& WithLocation(const char* value) { SetLocation(value); return *this;}

    /**
     *
The life-cycle status of a fleet location.

     */
    inline const FleetStatus& GetStatus() const{ return m_status; }

    /**
     *
The life-cycle status of a fleet location.

     */
    inline bool StatusHasBeenSet() const { return m_statusHasBeenSet; }

    /**
     *
The life-cycle status of a fleet location.

     */
    inline void SetStatus(const FleetStatus& value) { m_statusHasBeenSet = true; m_status = value; }

    /**
     *
The life-cycle status of a fleet location.

     */
    inline void SetStatus(FleetStatus&& value) { m_statusHasBeenSet = true; m_status = std::move(value); }

    /**
     *
The life-cycle status of a fleet location.

     */
    inline LocationState& WithStatus(const FleetStatus& value) { SetStatus(value); return *this;}

    /**
     *
The life-cycle status of a fleet location.

     */
    inline LocationState& WithStatus(FleetStatus&& value) { SetStatus(std::move(value)); return *this;}

  private:

    Aws::String m_location;
    bool m_locationHasBeenSet = false;

    FleetStatus m_status;
    bool m_statusHasBeenSet = false;
  };

} // namespace Model
} // namespace GameLift
} // namespace Aws


text:
published: true
layout: portfolio
title: No Place Like Home
photo: home.jpg
---

For its December 2014 issue, the Hanford Gyre newspaper explored the
            issue of teen homelessness; I was asked to create this infographic
            examining the topic both in the local community and on the national level.

This piece later received a superior in the Visual Communications category
            at the 2015 Washington State Journalism Conference.


text:
package com.ams.pageobject;

import org.openqa.selenium.By;
import com.ams.testsetup.SetUpLogin;

public class LoginFunctionality extends SetUpLogin  {

public By logout = By.linkText("LOGOUT");

	//to check login functionality
	public boolean loginFunction() {

		String lgout = driver.findElement(logout).getText();
		String logged = "LOGOUT";
		if (lgout.equals(logged)) {
			return true;
		}
		return false;
	}

	@Override
	public void tearDown() {
	   driver.findElement(logout).click();
	   super.tearDown();
	}
}


text:
layout: publication
title: "Reinforcement Learning based Design of Linear Fixed Structure Controllers"
type: "conference"
order: 143
year: 2020
authors: "Nathan P. Lawrence, Gregory E. Stewart, Philip D. Loewen, Michael G. Forbes, Johan U. Backstrom, R. Bhushan Gopaluni"
journal: "In proceedings of IFAC World Congress (To Appear)"
video: "https://vimeo.com/455075443"
pdf: "IFAC_PID_RL_2020-8.pdf"
arxiv: "https://arxiv.org/abs/2005.04537"
---


text:
require 'spec_helper'

# Specs in this file have access to a helper object that includes
# the SnippetsHelper. For example:
#
# describe SnippetsHelper do
#   describe "string concat" do
#     it "concats two strings with spaces" do
#       helper.concat_strings("this","that").should == "this that"
#     end
#   end
# end
describe Context::ContextHelper do
  describe "context" do
    it "should find the Snippet by name and return it directly" do
      snippet=Context::Snippet.new(:name => 'sidebar')
      Context::Snippet.should_receive(:locate).with(:sidebar).and_return(snippet)
      helper.context(:sidebar).should == snippet
    end

    it "should return nil if the Snippet can't be found" do
      helper.context(:sidebar).should be_nil
    end

    context "with a block" do
      it "should provide the context as the first argument" do
        snippet=Context::Snippet.new(:name => 'sidebar')
        Context::Snippet.should_receive(:locate).with(:sidebar).and_return(snippet)
        helper.context(:sidebar) do |sidebar|
          sidebar.should == snippet
        end
      end

      it "should return nothing if the Snippet can't be found"
    end
  end

  describe "context_tag" do
    it "should find the Snippet by name and return it wrapped in the element" do
      snippet=Context::Snippet.new(:name => 'sidebar')
      snippet.should_receive(:to_s).and_return("Content")
      Context::Snippet.should_receive(:locate).with(:sidebar).and_return(snippet)
      helper.context_tag(:div, :sidebar).should == "
Content
"
    end

    it "should pass the HTML options through"

    it "should return an empty element if the Snippet can't be found" do
      helper.context_tag(:div, :sidebar).should == "

"
    end
  end
end


text:
#if DEVICE_SERIAL

// math.h required for floating point operations for baud rate calculation
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "device.h"
#include "serial_api.h"
#include "cmsis.h"
#include "pinmap.h"
#include "PinNames.h"
#include "mbed_error.h"
#include "gpio_api.h"

void (*dummy_uart_write_redirect)(int c);

// serial_baud
// set the baud rate, taking in to account the current SystemFrequency
static void dummy_serial_baud(void *obj, int baudrate)
{
}

static void dummy_serial_format(void *obj, int data_bits,
                                SerialParity parity, int stop_bits)
{
}

static void dummy_serial_irq_handler(void *obj, uart_irq_handler handler, uint32_t id)
{
}

static void dummy_serial_irq_set(void *obj, SerialIrq irq, uint32_t enable)
{
}

static int dummy_serial_readable(void *obj)
{
    return 0;
}

static int dummy_serial_writable(void *obj)
{
    return 1;
}

static int dummy_serial_getc(void *obj)

{

    return 0;
}

static void dummy_serial_putc(void *obj, int c)
{
    if (dummy_uart_write_redirect) {
        dummy_uart_write_redirect(c);
    }
}

#if DEVICE_SERIAL_FC
static void dummy_serial_set_flow_control(struct serial_s *obj, FlowControl type,
                                          PinName rxflow, PinName txflow)
{
    error("dummy flow control is not implenemted");
}
#endif

void dummy_serial_init(void *obj, PinName tx, PinName rx)
{
    struct serial_s *priv = (struct serial_s *)obj;

    switch ((int)priv->uart) {
        case UART_4:
            priv->index = DUMMY_UART0_ID;
            break;
        case UART_5 :
            priv->index = DUMMY_UART1_ID;
            break;
    }

    priv->ops.serial_baud = dummy_serial_baud;
    priv->ops.serial_format = dummy_serial_format;
    priv->ops.serial_irq_handler = dummy_serial_irq_handler;
    priv->ops.serial_irq_set = dummy_serial_irq_set;
    priv->ops.serial_putc =  dummy_serial_putc;
    priv->ops.serial_writable =  dummy_serial_writable;
    priv->ops.serial_getc = dummy_serial_getc;
    priv->ops.serial_readable = dummy_serial_readable;
#if DEVICE_SERIAL_FC
    priv->ops.serial_set_flow_control = dummy_serial_set_flow_control;
#endif
    dummy_uart_write_redirect = NULL;
}

#endif // DEVICE_SERIAL


text:
package co.cask.hydrator.plugin.batch;

import co.cask.cdap.api.annotation.Description;
import co.cask.cdap.api.annotation.Macro;
import co.cask.cdap.api.annotation.Name;
import co.cask.cdap.api.annotation.Plugin;
import co.cask.cdap.etl.api.PipelineConfigurer;
import co.cask.cdap.etl.api.batch.BatchActionContext;
import co.cask.cdap.etl.api.batch.PostAction;
import co.cask.hydrator.common.batch.action.Condition;
import co.cask.hydrator.common.batch.action.ConditionConfig;
import co.cask.hydrator.common.http.HTTPConfig;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
import javax.ws.rs.HttpMethod;

/**
 * Makes an HTTP call at the end of a pipeline run.
 */
@Plugin(type = PostAction.PLUGIN_TYPE)
@Name("HTTPCallback")
@Description("Makes an HTTP call at the end of a pipeline run.")
public class HTTPCallbackAction extends PostAction {
  private static final Logger LOG = LoggerFactory.getLogger(HTTPCallbackAction.class);
  private final HttpRequestConf conf;

  public HTTPCallbackAction(HttpRequestConf conf) {
    this.conf = conf;
  }

  @Override
  public void configurePipeline(PipelineConfigurer pipelineConfigurer) {
    conf.validate();
  }

  @SuppressWarnings("ConstantConditions")
  @Override
  public void run(BatchActionContext batchActionContext) throws Exception {
    conf.validate();
    if (!conf.shouldRun(batchActionContext)) {
      return;
    }

    int retries = 0;
    Exception exception = null;
    do {
      HttpURLConnection conn = null;
      Map<String, String> headers = conf.getRequestHeadersMap();
      try {
        URL url = new URL(conf.getUrl());
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod(conf.method.toUpperCase());
        conn.setConnectTimeout(conf.getConnectTimeout());
        for (Map.Entry<String, String> propertyEntry : headers.entrySet()) {
          conn.addRequestProperty(propertyEntry.getKey(), propertyEntry.getValue());
        }
        if (conf.body != null) {
          conn.setDoOutput(true);
          try (OutputStream outputStream = conn.getOutputStream()) {
            outputStream.write(conf.body.getBytes(Charsets.UTF_8));
          }
        }
        LOG.info("Request to {} resulted in response code {}.", conf.getUrl(), conn.getResponseCode());
        break;
      } catch (MalformedURLException | ProtocolException e) {
        // these should never happen because the url and request method are checked at configure time
        throw new IllegalStateException("Error opening url connection. Reason: " + e.getMessage(), e);
      } catch (Exception e) {
        LOG.warn("Error making {} request to url {} with headers {}.", conf.method, conf.getUrl(), headers);
        exception = e;
      } finally {
        if (conn != null) {
          conn.disconnect();
        }
      }
      retries++;
    } while (retries < conf.numRetries);

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

  /**
   * Config for the http callback action.
   */
  public static final class HttpRequestConf extends HTTPConfig {
    private static final Set<String> METHODS = ImmutableSet.of(HttpMethod.GET, HttpMethod.HEAD, HttpMethod.OPTIONS,
                                                               HttpMethod.PUT, HttpMethod.POST, HttpMethod.DELETE);

    @Nullable
    @Description("When to run the action. Must be 'completion', 'success', or 'failure'. Defaults to 'completion'. " +
      "If set to 'completion', the action will be executed regardless of whether " +
      "the pipeline run succeeded or failed. " +
      "If set to 'success', the action will only be executed if the pipeline run succeeded. " +
      "If set to 'failure', the action will only be executed if the pipeline run failed.")
    @Macro
    public String runCondition;

    @Description("The http request method.")
    @Macro
    private String method;

    @Nullable
    @Description("The http request body.")
    @Macro
    private String body;

    @Nullable
    @Description("The number of times the request should be retried if the request fails. Defaults to 0.")
    @Macro
    private Integer numRetries;

    public HttpRequestConf() {
      super();
      numRetries = 0;
      runCondition = Condition.COMPLETION.name();
    }

    @SuppressWarnings("ConstantConditions")
    public void validate() {
      super.validate();
      if (!containsMacro("method") && !METHODS.contains(method.toUpperCase())) {
        throw new IllegalArgumentException(String.format("Invalid request method %s, must be one of %s.",
                                                         method, Joiner.on(',').join(METHODS)));
      }
      if (!containsMacro("numRetries") && numRetries < 0) {
        throw new IllegalArgumentException(String.format(
          "Invalid numRetries %d. Retries cannot be a negative number.", numRetries));
      }
    }

    public boolean shouldRun(BatchActionContext context) {
      if (!containsMacro("runCondition")) {
        return new ConditionConfig(runCondition).shouldRun(context);
      } else {
        return false;
      }
    }
  }
}


text:
package kantan.codecs.export

import kantan.codecs.{Decoder, Encoder}
import kantan.codecs.export.DerivedCodecTests.{Just, Maybe, None}
import kantan.codecs.strings
import kantan.codecs.strings.{DecodeError, StringDecoder, StringEncoder, StringResult}
import org.scalatest.funsuite.AnyFunSuite
import org.scalatest.matchers.should.Matchers
import org.scalatestplus.scalacheck.ScalaCheckPropertyChecks

class DerivedCodecTests extends AnyFunSuite with ScalaCheckPropertyChecks with Matchers {
  val decode: String => StringResult[Maybe[Int]] = s =>
    if(s.trim.isEmpty) Right(None)
    else StringResult(Just(s.toInt))

  val encode: Maybe[Int] => String = _ match {
    case Just(i) => i.toString
    case None    => ""
  }

  test("Derived decoders should have a lower priority than bespoke ones") {
    implicit val bespoke: StringDecoder[Maybe[Int]] = StringDecoder.from(decode)
    implicit val derived: DerivedDecoder[String, Maybe[Int], DecodeError, strings.codecs.type] =
      DerivedDecoder.from[String, Maybe[Int], DecodeError, strings.codecs.type](decode)

    implicitly[Decoder[String, Maybe[Int], DecodeError, strings.codecs.type]] should be(bespoke)
    derived // Allows this to compile - otherwise the compiler detects correctly that derived isn't used and fails.
  }

  test("Derived encoders should have a lower priority than bespoke ones") {
    implicit val bespoke: StringEncoder[Maybe[Int]] = StringEncoder.from(encode)
    implicit val derived: DerivedEncoder[String, Maybe[Int], strings.codecs.type] =
      DerivedEncoder.from[String, Maybe[Int], strings.codecs.type](encode)

    implicitly[Encoder[String, Maybe[Int], strings.codecs.type]] should be(bespoke)
    derived // Allows this to compile - otherwise the compiler detects correctly that derived isn't used and fails.
  }

  test("Derived decoders should be picked up when no other is available") {
    implicit val derived: DerivedDecoder[String, Maybe[Int], Throwable, strings.codecs.type] =
      DerivedDecoder.from[String, Maybe[Int], Throwable, strings.codecs.type](decode)

    implicitly[Decoder[String, Maybe[Int], Throwable, strings.codecs.type]] should be(derived.value)
  }

  test("Derived encoders should be picked up when no other is available") {
    implicit val derived: DerivedEncoder[String, Maybe[Int], strings.codecs.type] =
      DerivedEncoder.from[String, Maybe[Int], strings.codecs.type](encode)

    implicitly[Encoder[String, Maybe[Int], strings.codecs.type]] should be(derived.value)
  }
}

object DerivedCodecTests {
  sealed abstract class Maybe[+A]    extends Product with Serializable
  final case class Just[A](value: A) extends Maybe[A]
  final case object None             extends Maybe[Nothing]
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!--

    Copyright 2004-2014 The Kuali Foundation

    Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php

    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.

-->
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
                   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                   xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd">

    <changeSet id="1-oracle" author="npadharia" dbms="oracle" context="kpme-client-bootstrap">
        <comment>KPME-1207 : npadharia : created Leave Donation maint doc.</comment>
        <createSequence sequenceName="LM_LEAVE_DONATION_S" startValue="10000" />
    </changeSet>
    <changeSet id="1-mysql" author="npadharia" dbms="mysql" context="kpme-client-bootstrap">
        <comment>KPME-1207 : npadharia : created Leave Donation maint doc.</comment>
        <sql>
            CREATE TABLE LM_LEAVE_DONATION_S (
                ID BIGINT NOT NULL AUTO_INCREMENT, PRIMARY KEY (ID)
            ) ENGINE MyISAM;
            ALTER TABLE LM_LEAVE_DONATION_S AUTO_INCREMENT = 10000;
        </sql>
    </changeSet>

	<changeSet id="2" author="npadharia" context="kpme-client-bootstrap">
        <comment>KPME-1207 : npadharia : created Leave Donation maint doc.</comment>
        <createTable tableName="LM_LEAVE_DONATION_T">
            <column name="LM_LEAVE_DONATION_ID" type="VARCHAR(60)">
                <constraints nullable="false" primaryKey="true" />
            </column>
            <column name="DONATED_ACC_CAT" type="VARCHAR(15)">
                <constraints nullable="false" />
            </column>
            <column name="RECIPIENTS_ACC_CAT" type="VARCHAR(15)">
                <constraints nullable="false" />
            </column>
            <column name="AMOUNT_DONATED" type="DECIMAL(18,2)">
                <constraints nullable="false" />
            </column>
            <column name="AMOUNT_RECEIVED" type="DECIMAL(18,2)">
                <constraints nullable="false" />
            </column>
            <column name="DONOR" type="VARCHAR(40)">
                <constraints nullable="false" />
            </column>
            <column name="RECEPIENT" type="VARCHAR(40)">
                <constraints nullable="false" />
            </column>
            <column name="DESCR" type="VARCHAR(50)">
                <constraints nullable="false" />
            </column>
            <column name="EFFDT" type="DATE">
                <constraints nullable="false" />
            </column>
            <column name="OBJ_ID" type="VARCHAR(36)" />
            <column name="VER_NBR" type="BIGINT" defaultValueNumeric="1">
                <constraints nullable="false" />
            </column>
            <column name="ACTIVE" type="VARCHAR(1)" defaultValue="N" />
            <column name="TIMESTAMP" type="DATETIME" defaultValueDate="1970-01-01 00:00:00" />
        </createTable>
		<modifySql dbms="mysql">
			<append value=" ENGINE INNODB" />
		</modifySql>
    </changeSet>

</databaseChangeLog>


text:
layout: post
date: 2017-05-14
title: "J. Mendel bridal-2015-collection Style 24 Sleeveless Floor-Length Sheath/Column"
category: J. Mendel
tags: [J. Mendel,Sheath/Column,Strapless,Floor-Length,Sleeveless]
---
### J. Mendel bridal-2015-collection Style 24
Just **$369.99**
###   Sleeveless Floor-Length Sheath/Column

BRANDS	J. Mendel

Silhouette	Sheath/Column

Neckline	Strapless

Hemline/Train	Floor-Length

Sleeve	Sleeveless

Buy it: [https://www.readybrides.com/en/j-mendel/44388-j-mendel-bridal-2015-collection-style-24.html](https://www.readybrides.com/en/j-mendel/44388-j-mendel-bridal-2015-collection-style-24.html)


text:
from dartsense import List_C
from dartsense import db

import dartsense.event
import dartsense.player

class Competition:

    def __init__(self, id=0, name='',):
        self.id = id
        self.name = name

        if id and not name:
            sql = """
                SELECT competition_id, competition_name
                FROM competition where competition_id=%s
                LIMIT 1
            """
            res = db.exec_select(sql, [id])

            if(len(res) > 0):
                self.name = res[0]['competition_name']
            else:
                # id not found? get outta here!
                self.id = -1

    def save(self):
        if self.id:
            # update
            pass
        elif not self.id and self.name:
            # insert new
            sql = '''
                INSERT INTO `competition` ( `competition_name`, `competition_type` )
                VALUES ( %s, 'league' )
            '''

            new_id = db.exec_insert(sql, [self.name])
            self.id = new_id

        return self.id

    def delete(self):
        if self.id:
            # delete from db
            sql = " DELETE FROM `competition` WHERE `competition_id` = %s "
            db.exec_sql(sql, [self.id])

        self.id = 0
        self.name = ''

    def __bool__(self):
        return self.id > 0

    def _get_players(self):
        player_list = dartsense.player.PlayerList(
            filters={'competition': self.id})
        return player_list

    players = property(_get_players)

    def _get_events(self):
        event_list = dartsense.event.EventList()
        return event_list

    events = property(_get_events)

class CompetitionList(List_C):

    def __init__(self, filters={}):
        List_C.__init__(self)
        self.filters = filters

    def _search(self, force=False):
        if force or self._elements == []:
            self._elements = []
            args = []

            sql = '''
                SELECT DISTINCT c.competition_id, c.competition_name
                FROM
                    competition c
                    LEFT JOIN competition_player cp ON cp.competition_id=c.competition_id
                WHERE c.competition_id > 0
            '''

            if len(self.filters) > 0:
                if 'player' in self.filters:
                    sql += 'AND cp.player_id=%s '
                    args.append(self.filters['player'])
                if 'organisation' in self.filters:
                    sql += 'AND c.organisation_id=%s '
                    args.append(self.filters['organisation'])

            res = db.exec_select(sql, args)

            for r in res:
                self._elements.append(
                    Competition(id=r['competition_id'], name=r['competition_name']))

    def _get_competitions(self):
        return self.elements

    competitions = property(_get_competitions)

#


text:
package prototypev.PermissiveFov.Tests.LevelGeneration.Generators;

import org.junit.Before;
import org.junit.Test;
import prototypev.PermissiveFov.LevelGeneration.DirectionType;
import prototypev.PermissiveFov.LevelGeneration.Entities.Cell;
import prototypev.PermissiveFov.LevelGeneration.Entities.Room;
import prototypev.PermissiveFov.LevelGeneration.Generators.MazeGenerator;
import prototypev.PermissiveFov.Randomizer;
import prototypev.PermissiveFov.Tests.TestBase;

import java.text.MessageFormat;
import java.util.List;

import static org.junit.Assert.*;

public class MazeGeneratorTests extends TestBase {
    private int left;
    private int top;

    @Test
    public void generate_VarySparseness_ExpectsMatchingPercentCellsAsSolidRock() {
        for (int sparseness = 0; sparseness <= 100; sparseness++) {
            Room room = generateRoom(50, sparseness);

            int currentRockCellCount = 0;

            for (int y = 0; y < room.height; y++) {
                for (int x = 0; x < room.width; x++) {
                    Cell cell = room.getCellAt(left + x, top + y);

                    if (cell.getWallCount() == DirectionType.size) {
                        currentRockCellCount++;
                    }
                }
            }

            int targetRockCellCount = (int) Math.ceil(sparseness * room.width * room.height / 100f);
            assertEquals(MessageFormat.format("In a {0}% sparse map, {0}% of the cells should have all sides as walls!", sparseness), targetRockCellCount, currentRockCellCount);
        }
    }

    @Test
    public void newMazeGenerator_InvalidArguments_ExpectsException() {
        exception.expect(IllegalArgumentException.class);
        new MazeGenerator(-1, -1);
    }

    @Test
    public void removeDeadEnds_WithMaxModifier_ExpectsAllDeadEndsRemoved() {
        MazeGenerator generator = new MazeGenerator(30, 70);

        Room room = generator.generate(top, left, 15, 15);
        assertTrue("All cells should be visited after generating the maze!", room.isAllCellsVisited());

        List<Cell> deadEndCells = room.getDeadEndCells();
        assertFalse("No dead ends generated!", deadEndCells.isEmpty());

        // Remove the dead-ends with a deadEndRemovalModifier of 100
        generator.removeDeadEnds(room, 100);

        // We expect the map to have no dead ends when we're done
        deadEndCells = room.getDeadEndCells();
        assertTrue("All dead ends should have been removed!", deadEndCells.isEmpty());
    }

    @Before
    public void testSetup() {
        top = Randomizer.getInstance().nextInt(2, 10);
        left = Randomizer.getInstance().nextInt(2, 10);
    }

    /**
     * @param randomness A value between 0 - 100 indicating the degree of randomness.
     * @param sparseness A value between 0 - 100 indicating the degree of sparseness.
     * @return The generated room.
     */
    private Room generateRoom(int randomness, int sparseness) {
        MazeGenerator generator = new MazeGenerator(randomness, sparseness);

        Room room = generator.generate(top, left, 15, 15);
        assertTrue("All cells should be visited after generating the maze!", room.isAllCellsVisited());

        System.out.print("randomness=");
        System.out.println(randomness);
        System.out.print("sparseness=");
        System.out.println(sparseness);
        System.out.println(room);

        return room;
    }
}


text:
<?xml version="1.0"?>
<Document>

	<Sentence>
		<value>Hyphema is most often caused by trauma to the eye.</value>
		<pattern_crowdsource> [[Hyphema|C0020581]] is most often caused by [[trauma|C0043251]] to the eye.		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>Hyphema</surface-form>
				<RDF-ID>C0020581</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>most</surface-form>
				<RDF-ID>C0205393</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>often</surface-form>
				<RDF-ID>C0332183</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>trauma</surface-form>
				<RDF-ID>C0043251</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>eye</surface-form>
				<RDF-ID>C0015392</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0020581 ISA C0043251</triple>
			<triple>C0043251 CAUSES C0020581</triple>
			<triple>C0020581 CAUSES C0020581</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>Other causes of bleeding in the front chamber of the eye include:  - Blood vessel abnormality  - Cancer of the eye  - Severe inflammation of the iris  - Advanced diabetes  - Blood disorders such as sickle cell anemia</value>
		<pattern_crowdsource> Other causes of [[bleeding|C0019080]] in the front [[chamber|C0935616]] of the [[eye|C0015392]] include:  - Blood vessel abnormality  - Cancer of the eye  - Severe inflammation of the iris  - Advanced diabetes  - Blood disorders such as sickle cell anemia		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>causes</surface-form>
				<RDF-ID>C0015127</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>bleeding</surface-form>
				<RDF-ID>C0019080</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>front</surface-form>
				<RDF-ID>C0205123</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>chamber</surface-form>
				<RDF-ID>C0935616</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>eye</surface-form>
				<RDF-ID>C0015392</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Blood vessel abnormality</surface-form>
				<RDF-ID>C0241657</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Cancer</surface-form>
				<RDF-ID>C0006826</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>eye</surface-form>
				<RDF-ID>C0015392</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Severe inflammation</surface-form>
				<RDF-ID>C0522569</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>diabetes</surface-form>
				<RDF-ID>C0011847</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>iris  - Advanced diabetes  - Blood disorders</surface-form>
				<RDF-ID>C0854284</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>sickle cell anemia</surface-form>
				<RDF-ID>C0002895</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0935616 LOCATION_OF C0019080</triple>
			<triple>C0935616 PART_OF C0015392</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>Symptoms include:  - Bleeding in the anterior chamber of the eye  - Eye pain  - Light sensitivity  - Vision abnormalities   You may not be able to see a small hyphema when looking at your eye in the mirror.</value>
		<pattern_crowdsource> Symptoms include:  - [[Bleeding|C0019080]] in the anterior [[chamber|C0935616]] of the eye  - Eye pain  - Light sensitivity  - Vision abnormalities   You may not be able to see a small [[hyphema|C0020581]] when looking at your [[eye|C0015392]] in the mirror.		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>Symptoms</surface-form>
				<RDF-ID>C1457887</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Bleeding</surface-form>
				<RDF-ID>C0019080</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>anterior</surface-form>
				<RDF-ID>C0205094</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>chamber</surface-form>
				<RDF-ID>C0935616</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>eye  - Eye pain</surface-form>
				<RDF-ID>C0151827</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Light sensitivity</surface-form>
				<RDF-ID>C0085636</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Vision</surface-form>
				<RDF-ID>C0042789</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>not</surface-form>
				<RDF-ID>C1518422</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>able</surface-form>
				<RDF-ID>C1299581</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>small</surface-form>
				<RDF-ID>C0700321</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>hyphema</surface-form>
				<RDF-ID>C0020581</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>eye</surface-form>
				<RDF-ID>C0015392</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>mirror</surface-form>
				<RDF-ID>C0181868</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0935616 LOCATION_OF C0019080</triple>
			<triple>C0015392 LOCATION_OF C0020581</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>The health care provider may recommend the following to cut down the chance that there will be more bleeding:  - Bed rest  - Eye patching  - Sedating medicines    You may need to use eye drops to decrease the inflammation or lower the pressure in your eye.</value>
		<pattern_crowdsource> The health care provider may recommend the following to cut down the chance that there will be more [[bleeding|C0019080]]:  - Bed rest  - Eye patching  - Sedating [[medicines|C0013227]]    You may need to use eye drops to decrease the [[inflammation|C0021368]] or lower the pressure in your [[eye|C0015392]].		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>health care provider</surface-form>
				<RDF-ID>C0018724</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>cut</surface-form>
				<RDF-ID>C0000925</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>down</surface-form>
				<RDF-ID>C0023032</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>chance</surface-form>
				<RDF-ID>C0237506</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>more</surface-form>
				<RDF-ID>C0205172</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>bleeding</surface-form>
				<RDF-ID>C0019080</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Bed rest</surface-form>
				<RDF-ID>C0277816</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>Eye patching</surface-form>
				<RDF-ID>C0776981</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>medicines</surface-form>
				<RDF-ID>C0013227</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>eye drops</surface-form>
				<RDF-ID>C0015399</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>inflammation</surface-form>
				<RDF-ID>C0021368</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>pressure</surface-form>
				<RDF-ID>C0234222</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>eye</surface-form>
				<RDF-ID>C0015392</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0013227 PREVENTS C0021368</triple>
			<triple>C0015392 LOCATION_OF C0019080</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>People with sickle cell disease are more likely to have eye complications and must be watched closely.</value>
		<pattern_crowdsource> [[People|C0027361]] with [[sickle cell disease|C0002895]] are more likely to have [[eye|C0015392]] [[complications|C0009566]] and must be watched closely.		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>People</surface-form>
				<RDF-ID>C0027361</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>sickle cell disease</surface-form>
				<RDF-ID>C0002895</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>more</surface-form>
				<RDF-ID>C0205172</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>likely</surface-form>
				<RDF-ID>C0332148</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>eye</surface-form>
				<RDF-ID>C0015392</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>complications</surface-form>
				<RDF-ID>C0009566</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0002895 ISA C0009566</triple>
			<triple>C0002895 PROCESS_OF C0027361</triple>
			<triple>C0009566 PROCESS_OF C0027361</triple>
			<triple>C0015392 LOCATION_OF C0009566</triple>
			<triple>C0002895 PROCESS_OF C0027361</triple>
			<triple>C0015392 LOCATION_OF C0002895</triple>
		</triples>
	</Sentence>
	<Sentence>
		<value>Call your health care provider if you notice blood in the front of the eye or if you have an eye injury.</value>
		<pattern_crowdsource> Call your [[health care provider|C0018724]] if you notice blood in the front of the eye or if you have an [[eye injury|C0015408]].		</pattern_crowdsource>
		<annotations>
			<annotation>
				<surface-form>health care provider</surface-form>
				<RDF-ID>C0018724</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>blood</surface-form>
				<RDF-ID>C0005767</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>front</surface-form>
				<RDF-ID>C0205123</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>eye</surface-form>
				<RDF-ID>C0015392</RDF-ID>
			</annotation>
			<annotation>
				<surface-form>eye injury</surface-form>
				<RDF-ID>C0015408</RDF-ID>
			</annotation>
		</annotations>
		<triples>
			<triple>C0015408 PROCESS_OF C0018724</triple>
		</triples>
	</Sentence>

</Document>