text:
<?php

namespace sdk\Http\Flow;

use sdk\Base\Flow\FlowHandlerInterface;
use sdk\Base\Flow\FlowLayer;

/**
 * HTTP授权
 *
 * @package sdk\Mvc\Flow
 */
class HttpAuthorization extends FlowLayer implements FlowHandlerInterface
{

    /**
     * 每个请求层,最终被调用的方法
     *
     * @return mixed
     */
    public function handle()
    {
    }
}


text:
package config

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"os/user"
	"path/filepath"

	"golang.org/x/oauth2"
)

const configName = ".onedrive-sync"
const tokenName = "token"

func init() {
	configPath, err := getConfigPath()
	if err != nil {
		log.Fatal(err)
	}
	err = createIfNotExists(configPath)
	if err != nil {
		log.Fatal(err)
	}
}

// SaveToken saves the token on the disk
func SaveToken(token *oauth2.Token) error {
	content, err := json.Marshal(token)
	if err != nil {
		return err
	}
	tokenFile, err := getTokenPath()
	if err != nil {
		return err
	}
	log.Printf("Saving token in %s\n", tokenFile)
	return ioutil.WriteFile(tokenFile, content, 0644)
}

// ReadToken returns the token saved on the disk
func ReadToken() (*oauth2.Token, error) {
	tokenFile, err := getTokenPath()
	if err != nil {
		return nil, err
	}
	content, err := ioutil.ReadFile(tokenFile)
	if err != nil {
		return nil, err
	}
	var token *oauth2.Token
	err = json.Unmarshal(content, &token)
	return token, err
}

func getConfigPath() (string, error) {
	userHomeDir, err := getUserHomeDir()
	if err != nil {
		return "", err
	}
	return fmt.Sprintf("%s%s%s", userHomeDir, string(filepath.Separator), configName), nil
}

func getTokenPath() (string, error) {
	configPath, err := getConfigPath()
	if err != nil {
		return "", err
	}
	return fmt.Sprintf("%s%s%s", configPath, string(filepath.Separator), tokenName), nil
}

func getUserHomeDir() (string, error) {
	usr, err := user.Current()
	if err != nil {
		return "", err
	}
	return usr.HomeDir, nil
}

func createIfNotExists(dir string) error {
	exists, err := exists(dir)
	if err != nil || exists {
		return err
	}
	log.Printf("Creating folder %s\n", dir)
	err = os.Mkdir(dir, 0777)
	return err
}

func exists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace Home\Controller;
use Think\Controller;
class ContactController extends Controller {
	public function index(){
		if(isset($_SESSION["nickname"])&&isset($_SESSION["figureurl"])){
				$nickName = $_SESSION["nickname"];
				$figureUrl = $_SESSION["figureurl"];
		}
		if($_SESSION["isadmin"]){
			$isAdmin = $_SESSION["isadmin"];
		}
		$this->assign('nickname',$nickName);
		$this->assign('figure',$figureUrl);
		$this->assign('isadmin',$isAdmin);
		$this->display('contact');
	}
}


text:
module FormtasticFoundation
  module Actions
    class LinkAction < Formtastic::Actions::LinkAction
      include Base

      def to_html
        template.link_to(text, url, button_html)
      end
    end
  end
end


text:
extern int debug;

ACO::ACO(Graph *graph, ACOStrategy *strategy, ACOParameters *params)
: Metaheuristic()
, graph(graph)
, strategy(strategy)
, params(params) {
  strategy->set_colony(this);
  ants = strategy->create_ants(graph);
  ranking = new Ranking(params, ants);
}

ACO::~ACO() {
  delete strategy;
  if (get_best_solution()) { delete get_best_solution(); }
  delete ranking;
  for (unsigned i = 0, len = ants.size(); i < len; ++i) {
    delete ants[i];
  }
}

void ACO::optimize() {
  strategy->before_optimization();
  while (is_working()) {
    if (debug) {
      cout << "Iteration #" << strategy->get_no_iteration() << ":\tquality:\t";
      Solution *solution = get_best_solution();
      cout << (solution ? solution->print_header() : "0.0") << endl;
    }
    strategy->perform_iteration();
    finish_iteration();
  }
  strategy->finish_optimization();

  cout << "Best found solution:" << endl << *get_best_solution() << endl;
}

void ACO::finish_iteration() {
  ranking->update();
  update_pheromones();
  ranking->free_memory();
}

void ACO::update_pheromones() {
  ranking->prepare_pheromones();
  graph->iterate(params->get_ro(), params->get_max_pheromones());
}


text:
function add(num1, num2) {
  return num1 + num2
}

console.log(add(1, 2, 3));
var numberSample = [5, 2, 3, 1, 4]
console.log(numberSample.sort());
var answers = new Object();
// console.log(typeof)
console.log(typeof answers);

var answerBank = {
  optionOne: "Wrong!",
  optionTwo: "Wrong!",
  optionThree: "Correct",
};
console.log(answerBank. optionThree);
console.log(answerBank. optionThree);
console.log(answerBank["optionThree"]);


text:
from django.contrib.admin.sites import AdminSite

from apps.shells.admin import SpeciesAdmin, SpecimenAdmin, SpeciesRepresentationAdmin
from apps.shells.models import Species, Specimen, SpeciesRepresentation
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from django.contrib import admin
from django.contrib.sites.models import Site
from apps.botanycollection.admin import AccessionAdmin
from apps.botanycollection.models import Accession

refcollections_admin = AdminSite()

refcollections_admin.register(Species, SpeciesAdmin)
refcollections_admin.register(Specimen, SpecimenAdmin)
refcollections_admin.register(SpeciesRepresentation, SpeciesRepresentationAdmin)

refcollections_admin.register(Accession, AccessionAdmin)

######### DEFAULT APPS #############

refcollections_admin.register(User, UserAdmin)

class SiteAdmin(admin.ModelAdmin):
    list_display = ('domain', 'name')
    search_fields = ('domain', 'name')

refcollections_admin.register(Site, SiteAdmin)


text:
package gg.championmastery.highscoresService.api;

import com.google.common.collect.ImmutableMap;
import com.merakianalytics.orianna.types.common.OriannaException;
import com.merakianalytics.orianna.types.common.Platform;
import com.merakianalytics.orianna.types.dto.championmastery.ChampionMasteries;
import com.merakianalytics.orianna.types.dto.championmastery.ChampionMastery;
import com.merakianalytics.orianna.types.dto.summoner.Summoner;
import gg.championmastery.highscoresService.HighscoresService;
import gg.championmastery.highscoresService.persistence.MasteryScoreEntity;
import gg.championmastery.highscoresService.persistence.SummonerEntity;
import org.hibernate.LockMode;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.persistence.LockModeType;
import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import java.util.stream.Collectors;

public class HighscoresApi {

	private static final Logger logger = LoggerFactory.getLogger(HighscoresApi.class);

	/**
	 * Retrieves the champion mastery scores for the specified summoner, updates their summoner information in the
	 * database, and adds their scores to the highscores table if they're high enough to qualify. All database
	 * modifications occur asynchronously.
	 *
	 * @param summoner The summoner whose scores should be retrieved.
	 * @return The summoner's mastery scores for every champion.
	 * @throws OriannaException thrown if the Riot Games API returns an error.
	 */
	public ChampionMasteries getSummonerScores(Summoner summoner) throws OriannaException {
		ChampionMasteries masteries = HighscoresService.getOriannaPipeline().get(ChampionMasteries.class, ImmutableMap.of(
				"platform", Platform.withTag(summoner.getPlatform()),
				"summonerId", summoner.getId()
		));

		// Asynchronously check if the summoner is in the database, and add them if they're not.
		CompletableFuture.runAsync(() -> {
			Transaction tx = null;
			SummonerEntity.Key summonerKey = new SummonerEntity.Key(summoner.getPlatform(), summoner.getId());
			try (Session session = HighscoresService.getHibernateSessionFactory().openSession()) {
				tx = session.beginTransaction();
				SummonerEntity summonerEntity = session.get(SummonerEntity.class, summonerKey, LockMode.PESSIMISTIC_WRITE);
				// If the summoner doesn't already exist in the database, create a new entity
				if (summonerEntity == null) {
					summonerEntity = SummonerEntity.getInstantiator().acquireEntity(summonerKey);
					// If the summoner has already been instantiated by another thread, abort.
					if (summonerEntity == null) {
						return;
					}
				}

				// Update the summoner entity.
				summonerEntity.setSummonerName(summoner.getName());
				summonerEntity.setEncryptedAccountId(summoner.getAccountId());
				summonerEntity.setEncryptedPuuid(summoner.getPuuid());
				summonerEntity.setNameLastUpdatedInstant(Instant.now());
				summonerEntity.setRevisionDateInstant(Instant.ofEpochMilli(summoner.getRevisionDate()));
				summonerEntity.setMasteriesLastUpdatedInstant(Instant.now());
				session.saveOrUpdate(summonerEntity);

				// Update the summoner's mastery scores.
				List<MasteryScoreEntity> results = session
						.createQuery("FROM MasteryScoreEntity WHERE platform=:platform AND summoner=:id")
						.setParameter("platform", summonerEntity.getPlatform())
						.setParameter("id", summonerEntity)
						.setLockMode(LockModeType.PESSIMISTIC_WRITE)
						.getResultList();
				Map<Short, MasteryScoreEntity> scores = results.stream().collect(Collectors.toMap(MasteryScoreEntity::getChampionId, Function.identity()));

				// Consider saving each score and calculate total level/points.
				int totalPoints = 0;
				int totalLevel = 0;
				for (ChampionMastery score : masteries) {
					MasteryScoreEntity scoreEntity = getMasteryScoreEntity(scores, summonerEntity, (short) score.getChampionId(), score.getChampionPoints());
					considerSaveOrUpdate(scoreEntity, session);
					totalPoints += score.getChampionPoints();
					totalLevel += score.getChampionLevel();
				}
				considerSaveOrUpdate(getMasteryScoreEntity(scores, summonerEntity, (short) -1, totalPoints), session);
				considerSaveOrUpdate(getMasteryScoreEntity(scores, summonerEntity, (short) -2, totalLevel), session);

				tx.commit();
			} catch (Exception ex) {
				if (tx != null && tx.isActive()) {
					tx.setRollbackOnly();
				}

				logger.error(String.format("Error updating mastery scores for summoner '%s' (%s)", summoner.getName(), summoner.getPlatform()), ex);
			} finally {
				// Release the entity if it was locked by the instantiator.
				SummonerEntity.getInstantiator().persistEntity(summonerKey);
			}
		});

		return masteries;
	}

	/**
	 * Retrieves a list of the top 3 players for each champion (including total level/points).
	 *
	 * @return Lists of the top 3 players for each champion in descending order, mapped by champion ID.
	 */
	public Map<Short, List<MasteryScoreEntity>> getHighscoresSummary() {
		try (Session session = HighscoresService.getHibernateSessionFactory().openSession()) {
			List<Short> championIds = session.createQuery("SELECT DISTINCT(championId) FROM MasteryScoreEntity", Short.class).getResultList();

			HashMap<Short, List<MasteryScoreEntity>> highscoresSummary = new HashMap<>();
			for (short championId : championIds) {
				Query<MasteryScoreEntity> query = session.createQuery("FROM MasteryScoreEntity WHERE championId=:championId AND summoner.status != 1 ORDER BY masteryPoints DESC", MasteryScoreEntity.class)
						.setParameter("championId", championId)
						.setMaxResults(3);
				highscoresSummary.put(championId, query.getResultList());
			}

			return highscoresSummary;
		}
	}

	/**
	 * Retrieves a list of the top 50 players for the specified champion. This method does not attempt to verify that a
	 * champion with the specified ID actually exists, and will return an empty list if an invalid ID is specified.
	 *
	 * @return A list of the top 50 players for the specified champion.
	 */
	public List<MasteryScoreEntity> getChampionHighscores(short championId) {
		try (Session session = HighscoresService.getHibernateSessionFactory().openSession()) {
			Query<MasteryScoreEntity> query = session.createQuery("FROM MasteryScoreEntity WHERE championId=:championId AND summoner.status != 1 ORDER BY masteryPoints DESC", MasteryScoreEntity.class)
					.setParameter("championId", championId)
					.setMaxResults(50);

			return query.getResultList();
		}
	}

	/**
	 * Retrieves the {@link MasteryScoreEntity} for the specified summoner and champion from {@code scores} if it already
	 * contains it, or creates a new one if it does not.
	 *
	 * @param scores MasteryScoreEntities for this summoner that have already been persisted to the database, mapped by
	 * 		champion ID.
	 * @param summonerEntity The SummonerEntity who the score belongs to.
	 * @param championId The ID of the champion this score if for.
	 * @param points The points or level the summoner has on this champion.
	 */
	private static MasteryScoreEntity getMasteryScoreEntity(Map<Short, MasteryScoreEntity> scores, SummonerEntity summonerEntity, short championId, int points) {
		MasteryScoreEntity scoreEntity = scores.get(championId);
		if (scoreEntity == null) {
			// There's no need to use an EntityInstantiator since the SummonerEntity row will be locked, ensuring that only 1 thread can access this summoner's scores.
			scoreEntity = new MasteryScoreEntity();
			scoreEntity.setPlatform(summonerEntity.getPlatform());
			scoreEntity.setSummoner(summonerEntity);
			scoreEntity.setChampionId(championId);
		}

		scoreEntity.setMasteryPoints(points);
		return scoreEntity;
	}

	/**
	 * Saves scoreEntity to the database if the summoner has enough points to be in the highscores.
	 *
	 * @param scoreEntity The MasteryScoreEntity to consider saving.
	 * @param session The Hibernate session that should be used to save the entity.
	 */
	private static void considerSaveOrUpdate(MasteryScoreEntity scoreEntity, Session session) {
		if (scoreEntity.getChampionId() == -1) {
			// Only save total mastery points if it's at least 1m.
			if (scoreEntity.getMasteryPoints() < 1000000) {
				return;
			}
		} else if (scoreEntity.getChampionId() == -2) {
			// Only save total mastery level if it's at least 500.
			if (scoreEntity.getMasteryPoints() < 500) {
				return;
			}
		} else {
			// Only save champions with at least 100k mastery points.
			if (scoreEntity.getMasteryPoints() < 100000) {
				return;
			}
		}

		session.saveOrUpdate(scoreEntity);
	}
}


text:
<?
if (!isset($_GET['id']) || !is_number($_GET['id']) || !isset($_GET['torrentid']) || !is_number($_GET['torrentid'])) {
	error(0);
}
$GroupID = $_GET['id'];
$TorrentID = $_GET['torrentid'];

$DB->query("
	SELECT
		t.Media,
		t.Format,
		t.Encoding AS Bitrate,
		t.RemasterYear,
		t.Remastered,
		t.RemasterTitle,
		t.Scene,
		t.FreeTorrent,
		t.Description AS TorrentDescription,
		tg.CategoryID,
		tg.Name AS Title,
		tg.Year,
		tg.ArtistID,
		ag.Name AS ArtistName,
		t.GroupID,
		t.UserID,
		t.FreeTorrent
	FROM torrents AS t
		JOIN torrents_group AS tg ON tg.ID=t.GroupID
		LEFT JOIN artists_group AS ag ON ag.ArtistID=tg.ArtistID
	WHERE t.ID='$TorrentID'");

list($Properties) = $DB->to_array(false,MYSQLI_BOTH);

if (!$Properties) {
	error(404);
}

View::show_header('Edit torrent', 'upload');

if (!check_perms('site_moderate_requests')) {
	error(403);
}

?>

Send PM To All Snatchers Of "<?=$Properties['ArtistName']?> - <?=$Properties['Title']?>"

	<form class="send_form" name="mass_message" action="torrents.php" method="post">
		<input type="hidden" name="action" value="takemasspm" />
		<input type="hidden" name="auth" value="<?=$LoggedUser['AuthKey']?>" />
		<input type="hidden" name="torrentid" value="<?=$TorrentID?>" />
		<input type="hidden" name="groupid" value="<?=$GroupID?>" />

				Subject

					<input type="text" name="subject" value="" size="60" />

				Message

					<textarea name="message" id="message" cols="60" rows="8"></textarea>

					<input type="submit" value="Send Mass PM" />

	</form>

<? View::show_footer(); ?>


text:
package io.opensec.oval.model.linux;

import io.opensec.oval.model.ComponentType;
import io.opensec.oval.model.ElementRef;
import io.opensec.oval.model.Family;
import io.opensec.oval.model.definitions.EntityStateAnySimpleType;
import io.opensec.oval.model.definitions.EntityStateBoolType;
import io.opensec.oval.model.definitions.EntityStateStringType;
import io.opensec.oval.model.definitions.StateType;

import java.util.ArrayList;
import java.util.Collection;

/**
 * The rpmverifyfile_state defines the different information that can be used to determine
 * if a set of files within a set of RPMs passed verification.
 *
 * @author  Akihito Nakamura, AIST
 * @see OVAL Language
 */
public class RpmVerifyFileState
    extends StateType
{

    //{0..1}
    private EntityStateStringType           name;
    private EntityStateAnySimpleType        epoch;
    private EntityStateAnySimpleType        version;
    private EntityStateAnySimpleType        release;
    private EntityStateStringType           arch;
    private EntityStateStringType           filepath;
    private EntityStateStringType           extended_name;

    private EntityStateRpmVerifyResultType  size_differs;
    private EntityStateRpmVerifyResultType  mode_differs;
    private EntityStateRpmVerifyResultType  md5_differs;
    private EntityStateRpmVerifyResultType  device_differs;
    private EntityStateRpmVerifyResultType  link_mismatch;
    private EntityStateRpmVerifyResultType  ownership_differs;
    private EntityStateRpmVerifyResultType  group_differs;
    private EntityStateRpmVerifyResultType  mtime_differs;
    private EntityStateRpmVerifyResultType  capabilities_differ;

    private EntityStateBoolType             configuration_file;
    private EntityStateBoolType             documentation_file;
    private EntityStateBoolType             ghost_file;
    private EntityStateBoolType             license_file;
    private EntityStateBoolType             readme_file;

    /**
     * Constructor.
     */
    public RpmVerifyFileState()
    {
        this( null, 0 );
    }

    public RpmVerifyFileState(
                    final String id,
                    final int version
                    )
    {
        super( id, version );

        _oval_family = Family.LINUX;
        _oval_component = ComponentType.RPMVERIFYFILE;
    }

    /**
     */
    public void setName(
                    final EntityStateStringType name
                    )
    {
        this.name = name;
    }

    public EntityStateStringType getName()
    {
        return name;
    }

    /**
     */
    public void setEpoch(
                    final EntityStateAnySimpleType epoch
                    )
    {
        this.epoch = epoch;
    }

    public EntityStateAnySimpleType getEpoch()
    {
        return epoch;
    }

    /**
     */
    public void setVersion(
                    final EntityStateAnySimpleType version
                    )
    {
        this.version = version;
    }

    public EntityStateAnySimpleType getVersion()
    {
        return version;
    }

    /**
     */
    public void setRelease(
                    final EntityStateAnySimpleType release
                    )
    {
        this.release = release;
    }

    public EntityStateAnySimpleType getRelease()
    {
        return release;
    }

    /**
     */
    public void setArch(
                    final EntityStateStringType arch
                    )
    {
        this.arch = arch;
    }

    public EntityStateStringType getArch()
    {
        return arch;
    }

    /**
     */
    public void setFilepath(
                    final EntityStateStringType filepath
                    )
    {
        this.filepath = filepath;
    }

    public EntityStateStringType getFilepath()
    {
        return filepath;
    }

    /**
     */
    public void setExtendedName(
                    final EntityStateStringType extended_name
                    )
    {
        this.extended_name = extended_name;
    }

    public EntityStateStringType getExtendedName()
    {
        return extended_name;
    }

    /**
     */
    public void setSizeDiffers(
                    final EntityStateRpmVerifyResultType size_differs
                    )
    {
        this.size_differs = size_differs;
    }

    public EntityStateRpmVerifyResultType getSizeDiffers()
    {
        return size_differs;
    }

    /**
     */
    public void setModeDiffers(
                    final EntityStateRpmVerifyResultType mode_differs
                    )
    {
        this.mode_differs = mode_differs;
    }

    public EntityStateRpmVerifyResultType getModeDiffers()
    {
        return mode_differs;
    }

    /**
     */
    public void setMd5Differs(
                    final EntityStateRpmVerifyResultType md5_differs
                    )
    {
        this.md5_differs = md5_differs;
    }

    public EntityStateRpmVerifyResultType getMd5Differs()
    {
        return md5_differs;
    }

    /**
     */
    public void setDeviceDiffers(
                    final EntityStateRpmVerifyResultType device_differs
                    )
    {
        this.device_differs = device_differs;
    }

    public EntityStateRpmVerifyResultType getDeviceDiffers()
    {
        return device_differs;
    }

    /**
     */
    public void setLinkMismatch(
                    final EntityStateRpmVerifyResultType link_mismatch
                    )
    {
        this.link_mismatch = link_mismatch;
    }

    public EntityStateRpmVerifyResultType getLinkMismatch()
    {
        return link_mismatch;
    }

    /**
     */
    public void setOwnershipDiffers(
                    final EntityStateRpmVerifyResultType ownership_differs
                    )
    {
        this.ownership_differs = ownership_differs;
    }

    public EntityStateRpmVerifyResultType getOwnershipDiffers()
    {
        return ownership_differs;
    }

    /**
     */
    public void setGroupDiffers(
                    final EntityStateRpmVerifyResultType group_differs
                    )
    {
        this.group_differs = group_differs;
    }

    public EntityStateRpmVerifyResultType getGroupDiffers()
    {
        return group_differs;
    }

    /**
     */
    public void setMtimeDiffers(
                    final EntityStateRpmVerifyResultType mtime_differs
                    )
    {
        this.mtime_differs = mtime_differs;
    }

    public EntityStateRpmVerifyResultType getMtimeDiffers()
    {
        return mtime_differs;
    }

    /**
     */
    public void setCapabilitiesDiffer(
                    final EntityStateRpmVerifyResultType capabilities_differ
                    )
    {
        this.capabilities_differ = capabilities_differ;
    }

    public EntityStateRpmVerifyResultType getCapabilitiesDiffer()
    {
        return capabilities_differ;
    }

    /**
     */
    public void setConfigurationFile(
                    final EntityStateBoolType configuration_file
                    )
    {
        this.configuration_file = configuration_file;
    }

    public EntityStateBoolType getConfigurationFile()
    {
        return configuration_file;
    }

    /**
     */
    public void setDocumentationFile(
                    final EntityStateBoolType documentation_file
                    )
    {
        this.documentation_file = documentation_file;
    }

    public EntityStateBoolType getDocumentationFile()
    {
        return documentation_file;
    }

    /**
     */
    public void setGhostFile(
                    final EntityStateBoolType ghost_file
                    )
    {
        this.ghost_file = ghost_file;
    }

    public EntityStateBoolType getGhostFile()
    {
        return ghost_file;
    }

    /**
     */
    public void setLicenseFile(
                    final EntityStateBoolType license_file
                    )
    {
        this.license_file = license_file;
    }

    public EntityStateBoolType getLicenseFile()
    {
        return license_file;
    }

    /**
     */
    public void setReadmeFile(
                    final EntityStateBoolType readme_file
                    )
    {
        this.readme_file = readme_file;
    }

    public EntityStateBoolType getReadmeFile()
    {
        return readme_file;
    }

    //*********************************************************************
    //  DefinitionsElement
    //*********************************************************************

    @Override
    public Collection<ElementRef> ovalGetElementRef()
    {
        Collection<ElementRef>  ref_list = new ArrayList<ElementRef>();
        ref_list.add( getName() );
        ref_list.add( getEpoch() );
        ref_list.add( getVersion() );
        ref_list.add( getRelease() );
        ref_list.add( getArch() );
        ref_list.add( getFilepath() );
        ref_list.add( getExtendedName() );

        ref_list.add( getSizeDiffers() );
        ref_list.add( getModeDiffers() );
        ref_list.add( getMd5Differs() );
        ref_list.add( getDeviceDiffers() );
        ref_list.add( getLinkMismatch() );
        ref_list.add( getOwnershipDiffers() );
        ref_list.add( getGroupDiffers() );
        ref_list.add( getMtimeDiffers() );
        ref_list.add( getCapabilitiesDiffer() );

        ref_list.add( getConfigurationFile() );
        ref_list.add( getDocumentationFile() );
        ref_list.add( getGhostFile() );
        ref_list.add( getLicenseFile() );
        ref_list.add( getReadmeFile() );

        return ref_list;
    }

    // **************************************************************
    // java.lang.Object
    // **************************************************************

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

    @Override
    public boolean equals(
                    final Object obj
                    )
    {
        if (!(obj instanceof RpmVerifyFileState)) {
            return false;
        }

        return super.equals( obj );
    }

    @Override
    public String toString()
    {
        return "rpmverifyfile_state[" + super.toString()
                        + ", name="                 + getName()
                        + ", epoch="                + getEpoch()
                        + ", version="              + getVersion()
                        + ", release="              + getRelease()
                        + ", arch="                 + getArch()
                        + ", filepath="             + getFilepath()
                        + ", extended_name="        + getExtendedName()
                        + ", size_differs="         + getSizeDiffers()
                        + ", mode_differs="         + getModeDiffers()
                        + ", md5_differs="          + getMd5Differs()
                        + ", device_differs="       + getDeviceDiffers()
                        + ", link_mismatch="        + getLinkMismatch()
                        + ", ownership_differs="    + getOwnershipDiffers()
                        + ", group_differs="        + getGroupDiffers()
                        + ", mtime_differs="        + getMtimeDiffers()
                        + ", capabilities_differ="  + getCapabilitiesDiffer()
                        + ", configuration_file="   + getConfigurationFile()
                        + ", documentation_file="   + getDocumentationFile()
                        + ", ghost_file="           + getGhostFile()
                        + ", license_file="         + getLicenseFile()
                        + ", readme_file="          + getReadmeFile()
                        + "]";
    }

}
//


text:
import sys
import shutil
import subprocess
import os
import time
import tempfile
import optparse
import tarfile
import re
import shutil
import math

progname = os.path.split(sys.argv[0])[1]
myversion = 'V001.1 March 2014'
verbose = False
debug = False
toolFactoryURL = 'https://bitbucket.org/fubar/galaxytoolfactory'

# if we do html we need these dependencies specified in a tool_dependencies.xml file and referred to in the generated
# tool xml
toolhtmldepskel = """<?xml version="1.0"?>
<tool_dependency>
    <package name="ghostscript" version="9.10">
        <repository name="package_ghostscript_9_10" owner="devteam" prior_installation_required="True" />
    </package>
    <package name="graphicsmagick" version="1.3.18">
        <repository name="package_graphicsmagick_1_3" owner="iuc" prior_installation_required="True" />
    </package>
        <readme>
           %s
       </readme>
</tool_dependency>
"""

protorequirements = """<requirements>
      <requirement type="package" version="9.10">ghostscript</requirement>
      <requirement type="package" version="1.3.18">graphicsmagick</requirement>
  </requirements>"""

def timenow():
    """return current time as a string
    """
    return time.strftime('%d/%m/%Y %H:%M:%S', time.localtime(time.time()))

html_escape_table = {
     "&": "&",
     ">": ">",
     "<": "<",
     "$": "\$"
     }

def html_escape(text):
     """Produce entities within text."""
     return "".join(html_escape_table.get(c,c) for c in text)

def cmd_exists(cmd):
     return subprocess.call("type " + cmd, shell=True,
           stdout=subprocess.PIPE, stderr=subprocess.PIPE) == 0

def parse_citations(citations_text):
    """
    """
    citations = [c for c in citations_text.split("**ENTRY**") if c.strip()]
    citation_tuples = []
    for citation in citations:
        if citation.startswith("doi"):
            citation_tuples.append( ("doi", citation[len("doi"):].strip() ) )
        else:
            citation_tuples.append( ("bibtex", citation[len("bibtex"):].strip() ) )
    return citation_tuples

class ScriptRunner:
    """class is a wrapper for an arbitrary script
    """

    def __init__(self,opts=None,treatbashSpecial=True):
        """
        cleanup inputs, setup some outputs

        """
        self.useGM = cmd_exists('gm')
        self.useIM = cmd_exists('convert')
        self.useGS = cmd_exists('gs')
        self.temp_warned = False # we want only one warning if $TMP not set
        self.treatbashSpecial = treatbashSpecial
        if opts.output_dir: # simplify for the tool tarball
            os.chdir(opts.output_dir)
        self.thumbformat = 'png'
        self.opts = opts
        self.toolname = re.sub('[^a-zA-Z0-9_]+', '', opts.tool_name) # a sanitizer now does this but..
        self.toolid = self.toolname
        self.myname = sys.argv[0] # get our name because we write ourselves out as a tool later
        self.pyfile = self.myname # crude but efficient - the cruft won't hurt much
        self.xmlfile = '%s.xml' % self.toolname
        s = open(self.opts.script_path,'r').readlines()
        s = [x.rstrip() for x in s] # remove pesky dos line endings if needed
        self.script = '\n'.join(s)
        fhandle,self.sfile = tempfile.mkstemp(prefix=self.toolname,suffix=".%s" % (opts.interpreter))
        tscript = open(self.sfile,'w') # use self.sfile as script source for Popen
        tscript.write(self.script)
        tscript.close()
        self.indentedScript = '\n'.join([' %s' % html_escape(x) for x in s]) # for restructured text in help
        self.escapedScript = '\n'.join([html_escape(x) for x in s])
        self.elog = os.path.join(self.opts.output_dir,"%s_error.log" % self.toolname)
        if opts.output_dir: # may not want these complexities
            self.tlog = os.path.join(self.opts.output_dir,"%s_runner.log" % self.toolname)
            art = '%s.%s' % (self.toolname,opts.interpreter)
            artpath = os.path.join(self.opts.output_dir,art) # need full path
            artifact = open(artpath,'w') # use self.sfile as script source for Popen
            artifact.write(self.script)
            artifact.close()
        self.cl = []
        self.html = []
        a = self.cl.append
        a(opts.interpreter)
        if self.treatbashSpecial and opts.interpreter in ['bash','sh']:
            a(self.sfile)
        else:
            a('-') # stdin
        a(opts.input_tab)
        a(opts.input_int)
        a(opts.output_tab)
        self.outputFormat = self.opts.output_format
        self.inputFormats = self.opts.input_formats
        self.test1Input = '%s_test1_input.xls' % self.toolname
        self.test1Output = '%s_test1_output.xls' % self.toolname
        self.test1HTML = '%s_test1_output.html' % self.toolname

    def makeXML(self):
        """
        Create a Galaxy xml tool wrapper for the new script as a string to write out
        fixme - use templating or something less fugly than this example of what we produce

        <tool id="reverse" name="reverse" version="0.01">
            <description>a tabular file</description>
            <command interpreter="python">
            reverse.py --script_path "$runMe" --interpreter "python"
            --tool_name "reverse" --input_tab "$input1" --output_tab "$tab_file"
            </command>
            <inputs>
            <param name="input1"  type="data" format="tabular" label="Select a suitable input file from your history"/><param name="job_name" type="text" label="Supply a name for the outputs to remind you what they contain" value="reverse"/>

            </inputs>
            <outputs>
            <data format="tabular" name="tab_file" label="${job_name}"/>

            </outputs>
            <help>

**What it Does**

Reverse the columns in a tabular file

            </help>
            <configfiles>
            <configfile name="runMe">

# reverse order of columns in a tabular file
import sys
inp = sys.argv[1]
outp = sys.argv[2]
i = open(inp,'r')
o = open(outp,'w')
for row in i:
     rs = row.rstrip().split('\t')
     rs.reverse()
     o.write('\t'.join(rs))
     o.write('\n')
i.close()
o.close()

            </configfile>
            </configfiles>
            </tool>

        """
        newXML="""<tool id="%(toolid)s" name="%(toolname)s" version="%(tool_version)s">
%(tooldesc)s
%(requirements)s
<command interpreter="python">
%(command)s
</command>
<inputs>
%(inputs)s
</inputs>
<outputs>
%(outputs)s
</outputs>
<configfiles>
<configfile name="runMe">
%(script)s
</configfile>
</configfiles>

%(tooltests)s

<help>

%(help)s

</help>
<citations>
    %(citations)s
    <citation type="doi">10.1093/bioinformatics/bts573</citation>
</citations>
</tool>""" # needs a dict with toolname, toolid, interpreter, scriptname, command, inputs as a multi line string ready to write, outputs ditto, help ditto

        newCommand="""
        %(toolname)s.py --script_path "$runMe" --interpreter "%(interpreter)s"
            --tool_name "%(toolname)s" %(command_inputs)s %(command_outputs)s """
        # may NOT be an input or htmlout - appended later
        tooltestsTabOnly = """
        <tests>
        <test>
        <param name="input1" value="%(test1Input)s" ftype="%(inputFormats)s"/>
        <param name="job_name" value="test1"/>
        <param name="runMe" value="$runMe"/>
        <output name="tab_file" file="%(test1Output)s" ftype="%(outputFormat)s"/>
        </test>
        </tests>
        """
        tooltestsHTMLOnly = """
        <tests>
        <test>
        <param name="input1" value="%(test1Input)s" ftype="%(inputFormats)s"/>
        <param name="job_name" value="test1"/>
        <param name="runMe" value="$runMe"/>
        <output name="html_file" file="%(test1HTML)s" ftype="html" lines_diff="5"/>
        </test>
        </tests>
        """
        tooltestsBoth = """<tests>
        <test>
        <param name="input1" value="%(test1Input)s" ftype="%(inputFormats)s"/>
        <param name="job_name" value="test1"/>
        <param name="runMe" value="$runMe"/>
        <output name="tab_file" file="%(test1Output)s" ftype="%(outputFormat)s" />
        <output name="html_file" file="%(test1HTML)s" ftype="html" lines_diff="10"/>
        </test>
        </tests>
        """
        xdict = {}
        xdict['outputFormat'] = self.outputFormat
        xdict['inputFormats'] = self.inputFormats
        xdict['requirements'] = ''
        if self.opts.make_HTML:
            if self.opts.include_dependencies == "yes":
                xdict['requirements'] = protorequirements
        xdict['tool_version'] = self.opts.tool_version
        xdict['test1Input'] = self.test1Input
        xdict['test1HTML'] = self.test1HTML
        xdict['test1Output'] = self.test1Output
        if self.opts.make_HTML and self.opts.output_tab <> 'None':
            xdict['tooltests'] = tooltestsBoth % xdict
        elif self.opts.make_HTML:
            xdict['tooltests'] = tooltestsHTMLOnly % xdict
        else:
            xdict['tooltests'] = tooltestsTabOnly % xdict
        xdict['script'] = self.escapedScript
        # configfile is least painful way to embed script to avoid external dependencies
        # but requires escaping of <, > and $ to avoid Mako parsing
        if self.opts.help_text:
            helptext = open(self.opts.help_text,'r').readlines()
            helptext = [html_escape(x) for x in helptext] # must html escape here too - thanks to Marius van den Beek
            xdict['help'] = ''.join([x for x in helptext])
        else:
            xdict['help'] = 'Please ask the tool author (%s) for help as none was supplied at tool generation\n' % (self.opts.user_email)
        if self.opts.citations:
            citationstext = open(self.opts.citations,'r').read()
            citation_tuples = parse_citations(citationstext)
            citations_xml = ""
            for citation_type, citation_content in citation_tuples:
                citation_xml = """<citation type="%s">%s</citation>""" % (citation_type, html_escape(citation_content))
                citations_xml += citation_xml
            xdict['citations'] = citations_xml
        else:
            xdict['citations'] = ""
        coda = ['**Script**','Pressing execute will run the following code over your input file and generate some outputs in your history::']
        coda.append('\n')
        coda.append(self.indentedScript)
        coda.append('\n**Attribution**\nThis Galaxy tool was created by %s at %s\nusing the Galaxy Tool Factory.\n' % (self.opts.user_email,timenow()))
        coda.append('See %s for details of that project' % (toolFactoryURL))
        coda.append('Please cite: Creating re-usable tools from scripts: The Galaxy Tool Factory. Ross Lazarus; Antony Kaspi; Mark Ziemann; The Galaxy Team. ')
        coda.append('Bioinformatics 2012; doi: 10.1093/bioinformatics/bts573\n')
        xdict['help'] = '%s\n%s' % (xdict['help'],'\n'.join(coda))
        if self.opts.tool_desc:
            xdict['tooldesc'] = '<description>%s</description>' % self.opts.tool_desc
        else:
            xdict['tooldesc'] = ''
        xdict['command_outputs'] = ''
        xdict['outputs'] = ''
        if self.opts.input_tab <> 'None':
            xdict['command_inputs'] = '--input_tab "$input1" ' # the space may matter a lot if we append something
            xdict['inputs'] = '<param name="input1"  type="data" format="%s" label="Select a suitable input file from your history"/> \n' % self.inputFormats
        else:
            xdict['command_inputs'] = '' # assume no input - eg a random data generator
            xdict['inputs'] = ''
        xdict['inputs'] += '<param name="job_name" type="text" label="Supply a name for the outputs to remind you what they contain" value="%s"/> \n' % self.toolname
        xdict['toolname'] = self.toolname
        xdict['toolid'] = self.toolid
        xdict['interpreter'] = self.opts.interpreter
        xdict['scriptname'] = self.sfile
        if self.opts.make_HTML:
            xdict['command_outputs'] += ' --output_dir "$html_file.files_path" --output_html "$html_file" --make_HTML "yes"'
            xdict['outputs'] +=  ' <data format="html" name="html_file" label="${job_name}.html"/>\n'
        else:
            xdict['command_outputs'] += ' --output_dir "./"'
        if self.opts.output_tab <> 'None':
            xdict['command_outputs'] += ' --output_tab "$tab_file"'
            xdict['outputs'] += ' <data format="%s" name="tab_file" label="${job_name}"/>\n' % self.outputFormat
        xdict['command'] = newCommand % xdict
        xmls = newXML % xdict
        xf = open(self.xmlfile,'w')
        xf.write(xmls)
        xf.write('\n')
        xf.close()
        # ready for the tarball

    def makeTooltar(self):
        """
        a tool is a gz tarball with eg
        /toolname/tool.xml /toolname/tool.py /toolname/test-data/test1_in.foo ...
        """
        retval = self.run()
        if retval:
            print >> sys.stderr,'## Run failed. Cannot build yet. Please fix and retry'
            sys.exit(1)
        tdir = self.toolname
        os.mkdir(tdir)
        self.makeXML()
        if self.opts.make_HTML:
            if self.opts.help_text:
                hlp = open(self.opts.help_text,'r').read()
            else:
                hlp = 'Please ask the tool author for help as none was supplied at tool generation\n'
            if self.opts.include_dependencies:
                tooldepcontent = toolhtmldepskel  % hlp
                depf = open(os.path.join(tdir,'tool_dependencies.xml'),'w')
                depf.write(tooldepcontent)
                depf.write('\n')
                depf.close()
        if self.opts.input_tab <> 'None': # no reproducible test otherwise? TODO: maybe..
            testdir = os.path.join(tdir,'test-data')
            os.mkdir(testdir) # make tests directory
            shutil.copyfile(self.opts.input_tab,os.path.join(testdir,self.test1Input))
            if self.opts.output_tab <> 'None':
                shutil.copyfile(self.opts.output_tab,os.path.join(testdir,self.test1Output))
            if self.opts.make_HTML:
                shutil.copyfile(self.opts.output_html,os.path.join(testdir,self.test1HTML))
            if self.opts.output_dir:
                shutil.copyfile(self.tlog,os.path.join(testdir,'test1_out.log'))
        outpif = '%s.py' % self.toolname # new name
        outpiname = os.path.join(tdir,outpif) # path for the tool tarball
        pyin = os.path.basename(self.pyfile) # our name - we rewrite ourselves (TM)
        notes = ['# %s - a self annotated version of %s generated by running %s\n' % (outpiname,pyin,pyin),]
        notes.append('# to make a new Galaxy tool called %s\n' % self.toolname)
        notes.append('# User %s at %s\n' % (self.opts.user_email,timenow()))
        pi = open(self.pyfile,'r').readlines() # our code becomes new tool wrapper (!) - first Galaxy worm
        notes += pi
        outpi = open(outpiname,'w')
        outpi.write(''.join(notes))
        outpi.write('\n')
        outpi.close()
        stname = os.path.join(tdir,self.sfile)
        if not os.path.exists(stname):
            shutil.copyfile(self.sfile, stname)
        xtname = os.path.join(tdir,self.xmlfile)
        if not os.path.exists(xtname):
            shutil.copyfile(self.xmlfile,xtname)
        tarpath = "%s.gz" % self.toolname
        tar = tarfile.open(tarpath, "w:gz")
        tar.add(tdir,arcname=self.toolname)
        tar.close()
        shutil.copyfile(tarpath,self.opts.new_tool)
        shutil.rmtree(tdir)
        ## TODO: replace with optional direct upload to local toolshed?
        return retval

    def compressPDF(self,inpdf=None,thumbformat='png'):
        """need absolute path to pdf
           note that GS gets confoozled if no $TMP or $TEMP
           so we set it
        """
        assert os.path.isfile(inpdf), "## Input %s supplied to %s compressPDF not found" % (inpdf,self.myName)
        hlog = os.path.join(self.opts.output_dir,"compress_%s.txt" % os.path.basename(inpdf))
        sto = open(hlog,'a')
        our_env = os.environ.copy()
        our_tmp = our_env.get('TMP',None)
        if not our_tmp:
            our_tmp = our_env.get('TEMP',None)
        if not (our_tmp and os.path.exists(our_tmp)):
            newtmp = os.path.join(self.opts.output_dir,'tmp')
            try:
                os.mkdir(newtmp)
            except:
                sto.write('## WARNING - cannot make %s - it may exist or permissions need fixing\n' % newtmp)
            our_env['TEMP'] = newtmp
            if not self.temp_warned:
               sto.write('## WARNING - no $TMP or $TEMP!!! Please fix - using %s temporarily\n' % newtmp)
               self.temp_warned = True
        outpdf = '%s_compressed' % inpdf
        cl = ["gs", "-sDEVICE=pdfwrite", "-dNOPAUSE", "-dUseCIEColor", "-dBATCH","-dPDFSETTINGS=/printer", "-sOutputFile=%s" % outpdf,inpdf]
        x = subprocess.Popen(cl,stdout=sto,stderr=sto,cwd=self.opts.output_dir,env=our_env)
        retval1 = x.wait()
        sto.close()
        if retval1 == 0:
            os.unlink(inpdf)
            shutil.move(outpdf,inpdf)
            os.unlink(hlog)
        hlog = os.path.join(self.opts.output_dir,"thumbnail_%s.txt" % os.path.basename(inpdf))
        sto = open(hlog,'w')
        outpng = '%s.%s' % (os.path.splitext(inpdf)[0],thumbformat)
        if self.useGM:
            cl2 = ['gm', 'convert', inpdf, outpng]
        else: # assume imagemagick
            cl2 = ['convert', inpdf, outpng]
        x = subprocess.Popen(cl2,stdout=sto,stderr=sto,cwd=self.opts.output_dir,env=our_env)
        retval2 = x.wait()
        sto.close()
        if retval2 == 0:
             os.unlink(hlog)
        retval = retval1 or retval2
        return retval

    def getfSize(self,fpath,outpath):
        """
        format a nice file size string
        """
        size = ''
        fp = os.path.join(outpath,fpath)
        if os.path.isfile(fp):
            size = '0 B'
            n = float(os.path.getsize(fp))
            if n > 2**20:
                size = '%1.1f MB' % (n/2**20)
            elif n > 2**10:
                size = '%1.1f KB' % (n/2**10)
            elif n > 0:
                size = '%d B' % (int(n))
        return size

    def makeHtml(self):
        """ Create an HTML file content to list all the artifacts found in the output_dir
        """

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

         <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta name="generator" content="Galaxy %s tool output - see http://g2.trac.bx.psu.edu/" />
        <title></title>
        <link rel="stylesheet" href="/static/style/base.css" type="text/css" />

        """
        galhtmlattr = """

This tool (%s) was generated by the Galaxy Tool Factory

"""
        galhtmlpostfix = """
\n"""

        flist = os.listdir(self.opts.output_dir)
        flist = [x for x in flist if x <> 'Rplots.pdf']
        flist.sort()
        html = []
        html.append(galhtmlprefix % progname)
        html.append('
Galaxy Tool "%s" run at %s

' % (self.toolname,timenow()))
        fhtml = []
        if len(flist) > 0:
            logfiles = [x for x in flist if x.lower().endswith('.log')] # log file names determine sections
            logfiles.sort()
            logfiles = [x for x in logfiles if os.path.abspath(x) <> os.path.abspath(self.tlog)]
            logfiles.append(os.path.abspath(self.tlog)) # make it the last one
            pdflist = []
            npdf = len([x for x in flist if os.path.splitext(x)[-1].lower() == '.pdf'])
            for rownum,fname in enumerate(flist):
                dname,e = os.path.splitext(fname)
                sfsize = self.getfSize(fname,self.opts.output_dir)
                if e.lower() == '.pdf' : # compress and make a thumbnail
                    thumb = '%s.%s' % (dname,self.thumbformat)
                    pdff = os.path.join(self.opts.output_dir,fname)
                    retval = self.compressPDF(inpdf=pdff,thumbformat=self.thumbformat)
                    if retval == 0:
                        pdflist.append((fname,thumb))
                    else:
                        pdflist.append((fname,fname))
                if (rownum+1) % 2 == 0:
                    fhtml.append('
%s	%s
' % (fname,fname,sfsize))
                else:
                    fhtml.append('
%s	%s
' % (fname,fname,sfsize))
            for logfname in logfiles: # expect at least tlog - if more
                if os.path.abspath(logfname) == os.path.abspath(self.tlog): # handled later
                    sectionname = 'All tool run'
                    if (len(logfiles) > 1):
                        sectionname = 'Other'
                    ourpdfs = pdflist
                else:
                    realname = os.path.basename(logfname)
                    sectionname = os.path.splitext(realname)[0].split('_')[0] # break in case _ added to log
                    ourpdfs = [x for x in pdflist if os.path.basename(x[0]).split('_')[0] == sectionname]
                    pdflist = [x for x in pdflist if os.path.basename(x[0]).split('_')[0] <> sectionname] # remove
                nacross = 1
                npdf = len(ourpdfs)

                if npdf > 0:
                    nacross = math.sqrt(npdf) ## int(round(math.log(npdf,2)))
                    if int(nacross)**2 != npdf:
                        nacross += 1
                    nacross = int(nacross)
                    width = min(400,int(1200/nacross))
                    html.append('
%s images and outputs
' % sectionname)
                    html.append('(Click on a thumbnail image to download the corresponding original PDF image)
')
                    ntogo = nacross # counter for table row padding with empty cells
                    html.append('

\n
')
                    for i,paths in enumerate(ourpdfs):
                        fname,thumb = paths
                        s= """	\n""" % (fname,thumb,fname,width,fname)
                        if ((i+1) % nacross == 0):
                            s += '
\n'
                            ntogo = 0
                            if i < (npdf - 1): # more to come
                               s += '
'
                               ntogo = nacross
                        else:
                            ntogo -= 1
                        html.append(s)
                    if html[-1].strip().endswith('
'):
                        html.append('

\n')
                    else:
                        if ntogo > 0: # pad
                           html.append(' 	'*ntogo)
                        html.append('

\n')
                logt = open(logfname,'r').readlines()
                logtext = [x for x in logt if x.strip() > '']
                html.append('
%s log output
' % sectionname)
                if len(logtext) > 1:
                    html.append('\n
\n')
                    html += logtext
                    html.append('\n
\n')
                else:
                    html.append('%s is empty
' % logfname)
        if len(fhtml) > 0:
           fhtml.insert(0,'

Output File Name (click to view)	Size
\n')
           fhtml.append('

')
           html.append('
All output files available for downloading
\n')
           html += fhtml # add all non-pdf files to the end of the display
        else:
            html.append('
### Error - %s returned no files - please confirm that parameters are sane
' % self.opts.interpreter)
        html.append(galhtmlpostfix)
        htmlf = file(self.opts.output_html,'w')
        htmlf.write('\n'.join(html))
        htmlf.write('\n')
        htmlf.close()
        self.html = html

    def run(self):
        """
        scripts must be small enough not to fill the pipe!
        """
        if self.treatbashSpecial and self.opts.interpreter in ['bash','sh']:
          retval = self.runBash()
        else:
            if self.opts.output_dir:
                ste = open(self.elog,'w')
                sto = open(self.tlog,'w')
                sto.write('## Toolfactory generated command line = %s\n' % ' '.join(self.cl))
                sto.flush()
                #p = subprocess.Popen(self.cl,shell=False,stdout=sto,stderr=ste,stdin=subprocess.PIPE,cwd=self.opts.output_dir)
                p = subprocess.Popen(self.cl,shell=False,stdout=subprocess.PIPE,stderr=subprocess.PIPE,stdin=subprocess.PIPE,cwd=self.opts.output_dir)
            else:
                p = subprocess.Popen(self.cl,shell=False,stdin=subprocess.PIPE)
            p.stdin.write(self.script)
            stdout_data, stderr_data = p.communicate()
            p.stdin.close()
            retval = p.returncode
            #retval = p.wait()
            if self.opts.output_dir:
                sto.close()
                ste.close()
                err = stderr_data
                #err = open(self.elog,'r').readlines()
            print >> sys.stdout,stdout_data
            if retval <> 0 and err: # problem
                print >> sys.stderr,err
            if self.opts.make_HTML:
                self.makeHtml()
        return retval

    def runBash(self):
        """
        cannot use - for bash so use self.sfile
        """
        if self.opts.output_dir:
            s = '## Toolfactory generated command line = %s\n' % ' '.join(self.cl)
            sto = open(self.tlog,'w')
            sto.write(s)
            sto.flush()
            p = subprocess.Popen(self.cl,shell=False,stdout=sto,stderr=sto,cwd=self.opts.output_dir)
        else:
            p = subprocess.Popen(self.cl,shell=False)
        retval = p.wait()
        if self.opts.output_dir:
            sto.close()
        if self.opts.make_HTML:
            self.makeHtml()
        return retval

def main():
    u = """
    This is a Galaxy wrapper. It expects to be called by a special purpose tool.xml as:
    <command interpreter="python">rgBaseScriptWrapper.py --script_path "$scriptPath" --tool_name "foo" --interpreter "Rscript"
    </command>
    """
    op = optparse.OptionParser()
    a = op.add_option
    a('--script_path',default=None)
    a('--tool_name',default=None)
    a('--interpreter',default=None)
    a('--output_dir',default='./')
    a('--output_html',default=None)
    a('--input_tab',default="None")
    a('--input_int',default="None")
    a('--input_formats',default="tabular,text")
    a('--output_tab',default="None")
    a('--output_format',default="tabular")
    a('--user_email',default='Unknown')
    a('--bad_user',default=None)
    a('--make_Tool',default=None)
    a('--make_HTML',default=None)
    a('--help_text',default=None)
    a('--citations',default=None)
    a('--tool_desc',default=None)
    a('--new_tool',default=None)
    a('--tool_version',default=None)
    a('--include_dependencies',default=None)
    opts, args = op.parse_args()
    assert not opts.bad_user,'UNAUTHORISED: %s is NOT authorized to use this tool until Galaxy admin adds %s to admin_users in universe_wsgi.ini' % (opts.bad_user,opts.bad_user)
    assert opts.tool_name,'## Tool Factory expects a tool name - eg --tool_name=DESeq'
    assert opts.interpreter,'## Tool Factory wrapper expects an interpreter - eg --interpreter=Rscript'
    assert os.path.isfile(opts.script_path),'## Tool Factory wrapper expects a script path - eg --script_path=foo.R'
    if opts.output_dir:
        try:
            os.makedirs(opts.output_dir)
        except:
            pass
    r = ScriptRunner(opts)
    if opts.make_Tool:
        retcode = r.makeTooltar()
    else:
        retcode = r.run()
    os.unlink(r.sfile)
    if retcode:
        sys.exit(retcode) # indicate failure to job runner

if __name__ == "__main__":
    main()


text:
core.get_post default
--FILE--
<?php

require_once 'HTTP/Client.php';
$http = new HTTP_Client();
$http->get('http://wordpress.test/?json=core.get_post&slug=markup-html-tags-and-formatting&dev=1');
$response = $http->currentResponse();
$response = json_decode($response['body']);

echo "Response status: $response->status\n";
echo "post title: {$response->post->title}\n";

?>
--EXPECT--
Response status: ok
post title: Markup: HTML Tags and Formatting


text:
/**
 * DebugLogPanel.java
 * created: 19.01.2008 09:09:18
 * (c) 2008 by Wolschon Softwaredesign und Beratung
 * This file is part of jGnucash by Marcus Wolschon Marcus@Wolscon.biz.
 * You can purchase support for a sensible hourly rate or
 * a commercial license of this file (unless modified by others) by contacting him directly.
 *
 *  jGnucash-RO 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.
 *
 *  jGnucash-RO 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 traveling_salesman.  If not, see <http://www.gnu.org/licenses/>.
 *
 ***********************************
 * Editing this file:
 *  -For consistent code-quality this file should be checked with the
 *   checkstyle-ruleset enclosed in this project.
 *  -After the design of this file has settled it should get it's own
 *   JUnit-Test that shall be executed regularly. It is best to write
 *   the test-case BEFORE writing this class and to run it on every build
 *   as a regression-test.
 */
package biz.wolschon.finance.jgnucash.panels;

//other imports

//automatically created logger for debug and error -output
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;

//automatically created propertyChangeListener-Support
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.PrintWriter;
import java.io.StringWriter;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;

import org.apache.log4j.Appender;
import org.apache.log4j.Layout;
import org.apache.log4j.SimpleLayout;
import org.apache.log4j.spi.ErrorHandler;
import org.apache.log4j.spi.Filter;
import org.apache.log4j.spi.LoggingEvent;

/**
 * (c) 2008 by Wolschon Softwaredesign und Beratung.

 * Project: traveling_salesman

 * DebugLogPanel.java

 * created: 19.01.2008 09:09:18

 *

 * This panel is to show the logging-output for debugging.
 * @author Marcus Wolschon
 */
public class DebugLogPanel extends JPanel {

    /**
     * Automatically created logger for debug and error-output.
     */
    private static final Logger LOG = Logger.getLogger(
                                            DebugLogPanel.class.getName());

    /**
     * The area we are logging to.
     */
    private JTextPane myLogArea = new JTextPane();

    /**
     * Initialize the panel.
     */
    public DebugLogPanel() {
        this.setLayout(new BorderLayout());
        this.myLogArea.setText("");
        this.myLogArea.setStyledDocument(new DefaultStyledDocument());
        this.myLogArea.setPreferredSize(new Dimension(1000, 400));
        this.add(new JScrollPane(this.myLogArea), BorderLayout.CENTER);

        initializeLog4JLogging();

        // Display log-messages of Java-Logging
        initializeForJavaLogging();
    }

	/**
	 *
	 */
	private void initializeLog4JLogging() {
		org.apache.log4j.Logger.getRootLogger().addAppender(new Appender() {

        	private Layout layout = null;
        	private ErrorHandler errorHandler = null;
        	private String name = "DebugLogPanel";
        	private Filter filter = null;

			@Override
			public void addFilter(Filter arg0) {
				this.filter = arg0;
			}

			@Override
			public void clearFilters() {
				this.filter = null;
			}

			@Override
			public void close() {

			}

			@Override
			public void doAppend(final LoggingEvent aRecord) {

				//getLayout().format(aRecord);
				try {
                    // decide color or message
                    SimpleAttributeSet attrs = new SimpleAttributeSet();
                    if (aRecord.getLevel() == org.apache.log4j.Level.ALL)
                        StyleConstants.setForeground(attrs, Color.LIGHT_GRAY);
                    if (aRecord.getLevel() == org.apache.log4j.Level.DEBUG)
                        StyleConstants.setForeground(attrs, Color.LIGHT_GRAY);
                    if (aRecord.getLevel() == org.apache.log4j.Level.INFO)
                        StyleConstants.setForeground(attrs, Color.GRAY);
                    if (aRecord.getLevel() == org.apache.log4j.Level.TRACE)
                        StyleConstants.setForeground(attrs, Color.GRAY);
                    if (aRecord.getLevel() == org.apache.log4j.Level.WARN)
                        StyleConstants.setForeground(attrs, Color.ORANGE);
                    if (aRecord.getLevel() == org.apache.log4j.Level.ERROR)
                        StyleConstants.setForeground(attrs, Color.RED);
                    if (aRecord.getLevel() == org.apache.log4j.Level.FATAL)
                          StyleConstants.setForeground(attrs, Color.RED);

                    // print message
                    myLogArea.getDocument().insertString(
                            myLogArea.getDocument().getLength(),
                            "\n" + aRecord.getLevel().toString() + " "
                            + "in " + aRecord.getLocationInformation().getClassName() + ":" + aRecord.getLocationInformation().getMethodName() + "(...) :" + aRecord.getLocationInformation().getLineNumber()
                            + aRecord.getMessage(), attrs);

                    // print stack-trace
                    if (aRecord.getThrowableInformation() != null) {
                        StringWriter sw = new StringWriter();
                        PrintWriter pw = new PrintWriter(sw);
                        aRecord.getThrowableInformation().getThrowable().printStackTrace(pw);
                        myLogArea.getDocument().insertString(
                                myLogArea.getDocument().getLength(),
                                "\n" + sw.getBuffer(), attrs);
                    }
                } catch (BadLocationException e) {
                    LOG.log(Level.SEVERE, "[BadLocationException] Problem in "
                               + getClass().getName(),
                                 e);
                }
			}

			@Override
			public ErrorHandler getErrorHandler() {
				return errorHandler;
			}

			@Override
			public Filter getFilter() {
				return filter;
			}

			@Override
			public Layout getLayout() {
				return layout;
			}

			@Override
			public String getName() {
				return name;
			}

			@Override
			public boolean requiresLayout() {
				return false;
			}

			@Override
			public void setErrorHandler(ErrorHandler arg0) {
				this.errorHandler = arg0;
			}

			@Override
			public void setLayout(final Layout arg0) {
				this.layout = arg0;
			}

			@Override
			public void setName(String arg0) {
				this.name = arg0;
			}

        });
	}

	/**
	 *
	 */
	private void initializeForJavaLogging() {
		Logger.getLogger("").addHandler(new Handler() {

            @Override
            public void close() {
                try {
                    myLogArea.getDocument().insertString(myLogArea.getDocument().getLength(), "\n***LOGGING STOPPED***", null);
                } catch (BadLocationException e) {
                    LOG.log(Level.SEVERE, "[BadLocationException] Problem in "
                               + getClass().getName(),
                                 e);
                }
            }

            @Override
            public void flush() {
            }

            @Override
            public void publish(final LogRecord aRecord) {
                try {
                    // decide color or message
                    SimpleAttributeSet attrs = new SimpleAttributeSet();
                    if (aRecord.getLevel() == Level.FINEST)
                        StyleConstants.setForeground(attrs, Color.LIGHT_GRAY);
                    if (aRecord.getLevel() == Level.FINER)
                        StyleConstants.setForeground(attrs, Color.GRAY);
                    if (aRecord.getLevel() == Level.FINE)
                        StyleConstants.setForeground(attrs, Color.GRAY);
                    if (aRecord.getLevel() == Level.WARNING)
                        StyleConstants.setForeground(attrs, Color.ORANGE);
                    if (aRecord.getLevel() == Level.SEVERE)
                          StyleConstants.setForeground(attrs, Color.RED);

                    // print message
                    myLogArea.getDocument().insertString(
                            myLogArea.getDocument().getLength(),
                            "\n" + aRecord.getLevel() + " "
                            + "in " + aRecord.getSourceClassName() + ":" + aRecord.getSourceMethodName() + "(...) "
                            + aRecord.getMessage(), attrs);

                    // print stack-trace
                    if (aRecord.getThrown() != null) {
                        StringWriter sw = new StringWriter();
                        PrintWriter pw = new PrintWriter(sw);
                        aRecord.getThrown().printStackTrace(pw);
                        myLogArea.getDocument().insertString(
                                myLogArea.getDocument().getLength(),
                                "\n" + sw.getBuffer(), attrs);
                    }
                } catch (BadLocationException e) {
                    LOG.log(Level.SEVERE, "[BadLocationException] Problem in "
                               + getClass().getName(),
                                 e);
                }
            }
            });
	}

    //------------------------ support for propertyChangeListeners ------------------

    /**
     * support for firing PropertyChangeEvents.
     * (gets initialized only if we really have listeners)
     */
    private volatile PropertyChangeSupport myPropertyChange = null;

    /**
     * Returned value may be null if we never had listeners.
     * @return Our support for firing PropertyChangeEvents
     */
    protected PropertyChangeSupport getPropertyChangeSupport() {
        return myPropertyChange;
    }

    /**
     * Add a PropertyChangeListener to the listener list.
     * The listener is registered for all properties.
     *
     * @param listener  The PropertyChangeListener to be added
     */
    public final void addPropertyChangeListener(
            final PropertyChangeListener listener) {
        if (myPropertyChange == null) {
            myPropertyChange = new PropertyChangeSupport(this);
        }
        myPropertyChange.addPropertyChangeListener(listener);
    }

    /**
     * Add a PropertyChangeListener for a specific property.  The listener
     * will be invoked only when a call on firePropertyChange names that
     * specific property.
     *
     * @param propertyName  The name of the property to listen on.
     * @param listener  The PropertyChangeListener to be added
     */
    public final void addPropertyChangeListener(final String propertyName,
            final PropertyChangeListener listener) {
        if (myPropertyChange == null) {
            myPropertyChange = new PropertyChangeSupport(this);
        }
        myPropertyChange.addPropertyChangeListener(propertyName, listener);
    }

    /**
     * Remove a PropertyChangeListener for a specific property.
     *
     * @param propertyName  The name of the property that was listened on.
     * @param listener  The PropertyChangeListener to be removed
     */
    public final void removePropertyChangeListener(final String propertyName,
            final PropertyChangeListener listener) {
        if (myPropertyChange != null) {
            myPropertyChange.removePropertyChangeListener(propertyName,
                    listener);
        }
    }

    /**
     * Remove a PropertyChangeListener from the listener list.
     * This removes a PropertyChangeListener that was registered
     * for all properties.
     *
     * @param listener  The PropertyChangeListener to be removed
     */
    public synchronized void removePropertyChangeListener(
            final PropertyChangeListener listener) {
        if (myPropertyChange != null) {
            myPropertyChange.removePropertyChangeListener(listener);
        }
    }

    //-------------------------------------------------------

    /**
     * Just an overridden ToString to return this classe's name
     * and hashCode.
     * @return className and hashCode
     */
    public String toString() {
        return "DebugLogPanel@" + hashCode();
    }
}


text:
layout: post
title: Graduation Project
date: 2012-06-27
categories: [GIS]
tags: [ArcGIS, Adobe Flex]
---

ArcGIS Viewer for Flex from Ye Huang on Vimeo.

PS: This video evokes many memories and has some deep imprints of that era. I put it here not because I want to show a fantastic app, instead, I want to tell how I start an amazing journey of web design. I was a beginner at that time, more amateur than what you could imagine, but I still developed a good-looking one with Windows XP, Adobe Flex and my coolest IBM T60P.


text:
function search(event) {
    if(event.keyCode == 13) {
        var searchTerm = document.getElementById('search-field').value;
        var colors = {
            'black':document.getElementById('search-black').checked ? 1 : 0,
            'blue':document.getElementById('search-blue').checked ? 1 : 0,
            'green':document.getElementById('search-green').checked ? 1 : 0,
            'red':document.getElementById('search-red').checked ? 1 : 0,
            'white':document.getElementById('search-white').checked ? 1 : 0
        }
        window.location.href = '/results?term='+searchTerm+'&colors='+JSON.stringify(colors);
    }
}


text:
Espaço para aprender e compartilhar conhecimento, sempre que possível publicarei experimentos utilizando bibliotecas e tendências do mundo web  que me chamam a atenção e que possam enriquecer os trabalhos oferecidos aos nossos clientes.

Space to learn and share knowledge, whenever possible, I'll publish experiments using libraries and following trends on web development that strikes me and may enhance the work offered to our customers.


text:
module Mongo
  module Auth
    class SCRAM

      # Defines behavior around a single SCRAM-SHA-1/256 conversation between
      # the client and server.
      #
      # @since 2.0.0
      # @api private
      class Conversation

        # The base client continue message.
        #
        # @since 2.0.0
        CLIENT_CONTINUE_MESSAGE = { saslContinue: 1 }.freeze

        # The base client first message.
        #
        # @since 2.0.0
        CLIENT_FIRST_MESSAGE = { saslStart: 1, autoAuthorize: 1 }.freeze

        # The client key string.
        #
        # @since 2.0.0
        # @deprecated
        CLIENT_KEY = 'Client Key'.freeze

        # The key for the done field in the responses.
        #
        # @since 2.0.0
        DONE = 'done'.freeze

        # The conversation id field.
        #
        # @since 2.0.0
        ID = 'conversationId'.freeze

        # The iterations key in the responses.
        #
        # @since 2.0.0
        ITERATIONS = /i=(\d+)/.freeze

        # The minimum iteration count for SCRAM-SHA-256.
        #
        # @api private
        #
        # @since 2.6.0
        MIN_ITER_COUNT = 4096

        # The payload field.
        #
        # @since 2.0.0
        PAYLOAD = 'payload'.freeze

        # The rnonce key in the responses.
        #
        # @since 2.0.0
        RNONCE = /r=([^,]*)/.freeze

        # The salt key in the responses.
        #
        # @since 2.0.0
        SALT = /s=([^,]*)/.freeze

        # The server key string.
        #
        # @since 2.0.0
        # @deprecated
        SERVER_KEY = 'Server Key'.freeze

        # The server signature verifier in the response.
        #
        # @since 2.0.0
        VERIFIER = /v=([^,]*)/.freeze

        # @return [ String ] nonce The initial user nonce.
        attr_reader :nonce

        # @return [ Protocol::Message ] reply The current reply in the
        #   conversation.
        attr_reader :reply

        # @return [ User ] user The user for the conversation.
        attr_reader :user

        # Continue the SCRAM conversation. This sends the client final message
        # to the server after setting the reply from the previous server
        # communication.
        #
        # @example Continue the conversation.
        #   conversation.continue(reply)
        #
        # @param [ Protocol::Message ] reply The reply of the previous
        #   message.
        # @param [ Server::Connection ] connection The connection being
        #   authenticated.
        #
        # @return [ Protocol::Message ] The next message to send.
        #
        # @since 2.0.0
        def continue(reply, connection)
          validate_first_message!(reply, connection.server)

          if connection && connection.features.op_msg_enabled?
            selector = CLIENT_CONTINUE_MESSAGE.merge(
              payload: client_final_message,
              conversationId: id,
            )
            selector[Protocol::Msg::DATABASE_IDENTIFIER] = user.auth_source
            cluster_time = connection.mongos? && connection.cluster_time
            selector[Operation::CLUSTER_TIME] = cluster_time if cluster_time
            Protocol::Msg.new([], {}, selector)
          else
            Protocol::Query.new(
              user.auth_source,
              Database::COMMAND,
              CLIENT_CONTINUE_MESSAGE.merge(
                payload: client_final_message,
                conversationId: id,
              ),
              limit: -1,
            )
          end
        end

        # Finalize the SCRAM conversation. This is meant to be iterated until
        # the provided reply indicates the conversation is finished.
        #
        # @param [ Protocol::Message ] reply The reply of the previous
        #   message.
        # @param [ Server::Connection ] connection The connection being authenticated.
        #
        # @return [ Protocol::Query ] The next message to send.
        #
        # @since 2.0.0
        def finalize(reply, connection)
          validate_final_message!(reply, connection.server)
          if connection && connection.features.op_msg_enabled?
            selector = CLIENT_CONTINUE_MESSAGE.merge(
              payload: client_empty_message,
              conversationId: id,
            )
            selector[Protocol::Msg::DATABASE_IDENTIFIER] = user.auth_source
            cluster_time = connection.mongos? && connection.cluster_time
            selector[Operation::CLUSTER_TIME] = cluster_time if cluster_time
            Protocol::Msg.new([], {}, selector)
          else
            Protocol::Query.new(
              user.auth_source,
              Database::COMMAND,
              CLIENT_CONTINUE_MESSAGE.merge(
                payload: client_empty_message,
                conversationId: id,
              ),
              limit: -1,
            )
          end
        end

        # Start the SCRAM conversation. This returns the first message that
        # needs to be sent to the server.
        #
        # @param [ Server::Connection ] connection The connection being authenticated.
        #
        # @return [ Protocol::Query ] The first SCRAM conversation message.
        #
        # @since 2.0.0
        def start(connection)
          if connection && connection.features.op_msg_enabled?
            selector = CLIENT_FIRST_MESSAGE.merge(
              payload: client_first_message, mechanism: full_mechanism)
            selector[Protocol::Msg::DATABASE_IDENTIFIER] = user.auth_source
            cluster_time = connection.mongos? && connection.cluster_time
            selector[Operation::CLUSTER_TIME] = cluster_time if cluster_time
            Protocol::Msg.new([], {}, selector)
          else
            Protocol::Query.new(
              user.auth_source,
              Database::COMMAND,
              CLIENT_FIRST_MESSAGE.merge(
                payload: client_first_message, mechanism: full_mechanism),
              limit: -1,
            )
          end
        end

        def full_mechanism
          MECHANISMS[@mechanism]
        end

        # Get the id of the conversation.
        #
        # @example Get the id of the conversation.
        #   conversation.id
        #
        # @return [ Integer ] The conversation id.
        #
        # @since 2.0.0
        def id
          reply.documents[0][ID]
        end

        # Create the new conversation.
        #
        # @example Create the new conversation.
        #   Conversation.new(user, mechanism)
        #
        # @param [ Auth::User ] user The user to converse about.
        # @param [ Symbol ] mechanism Authentication mechanism.
        #
        # @since 2.0.0
        def initialize(user, mechanism)
          unless [:scram, :scram256].include?(mechanism)
            raise InvalidMechanism.new(mechanism)
          end

          @user = user
          @nonce = SecureRandom.base64
          @mechanism = mechanism
        end

        private

        # Auth message algorithm implementation.
        #
        # @api private
        #
        # @see http://tools.ietf.org/html/rfc5802#section-3
        #
        # @since 2.0.0
        def auth_message
          @auth_message ||= "#{first_bare},#{reply.documents[0][PAYLOAD].data},#{without_proof}"
        end

        # Get the empty client message.
        #
        # @api private
        #
        # @since 2.0.0
        def client_empty_message
          BSON::Binary.new('')
        end

        # Get the final client message.
        #
        # @api private
        #
        # @see http://tools.ietf.org/html/rfc5802#section-3
        #
        # @since 2.0.0
        def client_final_message
          BSON::Binary.new("#{without_proof},p=#{client_final}")
        end

        # Get the client first message
        #
        # @api private
        #
        # @see http://tools.ietf.org/html/rfc5802#section-3
        #
        # @since 2.0.0
        def client_first_message
          BSON::Binary.new("n,,#{first_bare}")
        end

        # Client final implementation.
        #
        # @api private
        #
        # @see http://tools.ietf.org/html/rfc5802#section-7
        #
        # @since 2.0.0
        def client_final
          @client_final ||= client_proof(client_key, client_signature(stored_key(client_key), auth_message))
        end

        # Client key algorithm implementation.
        #
        # @api private
        #
        # @see http://tools.ietf.org/html/rfc5802#section-3
        #
        # @since 2.0.0
        def client_key
          @client_key ||= CredentialCache.cache(cache_key(:client_key)) do
            hmac(salted_password, 'Client Key')
          end
        end

        # Client proof algorithm implementation.
        #
        # @api private
        #
        # @see http://tools.ietf.org/html/rfc5802#section-3
        #
        # @since 2.0.0
        def client_proof(key, signature)
          @client_proof ||= Base64.strict_encode64(xor(key, signature))
        end

        # Client signature algorithm implementation.
        #
        # @api private
        #
        # @see http://tools.ietf.org/html/rfc5802#section-3
        #
        # @since 2.0.0
        def client_signature(key, message)
          @client_signature ||= hmac(key, message)
        end

        # First bare implementation.
        #
        # @api private
        #
        # @see http://tools.ietf.org/html/rfc5802#section-7
        #
        # @since 2.0.0
        def first_bare
          @first_bare ||= "n=#{user.encoded_name},r=#{nonce}"
        end

        # H algorithm implementation.
        #
        # @api private
        #
        # @see http://tools.ietf.org/html/rfc5802#section-2.2
        #
        # @since 2.0.0
        def h(string)
          digest.digest(string)
        end

        # HI algorithm implementation.
        #
        # @api private
        #
        # @see http://tools.ietf.org/html/rfc5802#section-2.2
        #
        # @since 2.0.0
        def hi(data)
          case @mechanism
          when :scram256
            OpenSSL::PKCS5.pbkdf2_hmac(
              data,
              Base64.strict_decode64(salt),
              iterations,
              digest.size,
              digest
            )
          else
            OpenSSL::PKCS5.pbkdf2_hmac_sha1(
              data,
              Base64.strict_decode64(salt),
              iterations,
              digest.size
            )
          end
        end

        # HMAC algorithm implementation.
        #
        # @api private
        #
        # @see http://tools.ietf.org/html/rfc5802#section-2.2
        #
        # @since 2.0.0
        def hmac(data, key)
          OpenSSL::HMAC.digest(digest, data, key)
        end

        # Get the iterations from the server response.
        #
        # @api private
        #
        # @since 2.0.0
        def iterations
          @iterations ||= payload_data.match(ITERATIONS)[1].to_i.tap do |i|
            if i < MIN_ITER_COUNT
              raise Error::InsufficientIterationCount.new(
                Error::InsufficientIterationCount.message(MIN_ITER_COUNT, i))
            end
          end
        end

        # Get the data from the returned payload.
        #
        # @api private
        #
        # @since 2.0.0
        def payload_data
          reply.documents[0][PAYLOAD].data
        end

        # Get the server nonce from the payload.
        #
        # @api private
        #
        # @since 2.0.0
        def rnonce
          @rnonce ||= payload_data.match(RNONCE)[1]
        end

        # Gets the salt from the server response.
        #
        # @api private
        #
        # @since 2.0.0
        def salt
          @salt ||= payload_data.match(SALT)[1]
        end

        # @api private
        def cache_key(*extra)
          [user.password, salt, iterations, @mechanism] + extra
        end

        # Salted password algorithm implementation.
        #
        # @api private
        #
        # @see http://tools.ietf.org/html/rfc5802#section-3
        #
        # @since 2.0.0
        def salted_password
          @salted_password ||= CredentialCache.cache(cache_key(:salted_password)) do
            case @mechanism
            when :scram256
              hi(user.sasl_prepped_password)
            else
              hi(user.hashed_password)
            end
          end
        end

        # Server key algorithm implementation.
        #
        # @api private
        #
        # @see http://tools.ietf.org/html/rfc5802#section-3
        #
        # @since 2.0.0
        def server_key
          @server_key ||= CredentialCache.cache(cache_key(:server_key)) do
            hmac(salted_password, 'Server Key')
          end
        end

        # Server signature algorithm implementation.
        #
        # @api private
        #
        # @see http://tools.ietf.org/html/rfc5802#section-3
        #
        # @since 2.0.0
        def server_signature
          @server_signature ||= Base64.strict_encode64(hmac(server_key, auth_message))
        end

        # Stored key algorithm implementation.
        #
        # @api private
        #
        # @see http://tools.ietf.org/html/rfc5802#section-3
        #
        # @since 2.0.0
        def stored_key(key)
          h(key)
        end

        # Get the verifier token from the server response.
        #
        # @api private
        #
        # @since 2.0.0
        def verifier
          @verifier ||= payload_data.match(VERIFIER)[1]
        end

        # Get the without proof message.
        #
        # @api private
        #
        # @see http://tools.ietf.org/html/rfc5802#section-7
        #
        # @since 2.0.0
        def without_proof
          @without_proof ||= "c=biws,r=#{rnonce}"
        end

        # XOR operation for two strings.
        #
        # @api private
        #
        # @since 2.0.0
        def xor(first, second)
          first.bytes.zip(second.bytes).map{ |(a,b)| (a ^ b).chr }.join('')
        end

        def compare_digest(a, b)
          check = a.bytesize ^ b.bytesize
          a.bytes.zip(b.bytes){ |x, y| check |= x ^ y.to_i }
          check == 0
        end

        def validate_final_message!(reply, server)
          validate!(reply, server)
          unless compare_digest(verifier, server_signature)
            raise Error::InvalidSignature.new(verifier, server_signature)
          end
        end

        def validate_first_message!(reply, server)
          validate!(reply, server)
          raise Error::InvalidNonce.new(nonce, rnonce) unless rnonce.start_with?(nonce)
        end

        def validate!(reply, server)
          if reply.documents[0][Operation::Result::OK] != 1
            raise Unauthorized.new(user,
              used_mechanism: full_mechanism,
              message: reply.documents[0]['errmsg'],
              server: server,
            )
          end
          @reply = reply
        end

        private

        def digest
          @digest ||= case @mechanism
                      when :scram256
                        OpenSSL::Digest::SHA256.new.freeze
                      else
                        OpenSSL::Digest::SHA1.new.freeze
                      end
        end
      end
    end
  end
end


text:
package com.facebook.stetho.server.http;

import com.facebook.stetho.server.SocketLike;

import java.io.IOException;

public interface HttpHandler {
    boolean handleRequest(SocketLike socket, LightHttpRequest request, LightHttpResponse response) throws IOException;
}


text:
/**
 * Custom logging function like console.log
 * @param app
 * @returns {module}
 */

var _ = require('lodash');
var Shared = require('./../../shared');
var Util = require('util');

function thisModule() {

    var self = this;

    /**
     * Write logging information
     * @param level => 'none', 'fatal', 'error', 'warn', 'info', 'debug', 'trace'
     * @param message = >Error message
     * @param tag => Tags of log info i.e. database, request. Default is 'default' or empty
     * @param data => Any data object
     * @private
     */
    var _logEvent = function (level, message, tag, data) {

        var env = Shared.config('environment');
        var levels = ['fatal', 'error', 'warn', 'info', 'debug', 'trace'];
        var logLevelConfig = env.logLevel || "info";

        if (logLevelConfig == "none") {
            return;
        }

        var logLevel = levels.indexOf(logLevelConfig) >= 0 ? logLevelConfig : 'info';

        // Set default error logging
        if (_.isObject(message) && _.isEmpty(data)) {
            if (message.message && _.isString(message.message)) {
                data = message.stack || "";
                message = message.message;
            }
            else {
                data = message;
                message = null;
            }
        }

        //Output
        if (levels.indexOf(level) <= levels.indexOf(logLevel)) {
            var logString = "";

            if (env.logFormat === 'json') {
                logString = JSON.stringify({
                    timestamp: new Date().toISOString(),
                    level,
                    tag,
                    message,
                    data,
                    hostname: Shared.getCurrentHostId(),
                    pid: process.pid,
                    mode: env.mode
                });
            } else {
                if (_.isObject(data)) {
                    data = Util.inspect(data, {showHidden: false, depth: null});
                }

                logString += new Date().toISOString() + ' ';
                logString += '[' + level + ']';
                logString += tag == "default" ? "" : ' [' + tag + ']';
                logString += !_.isString(message) ? "" : ': ' + message;
                logString += data ? ' --> ' + data : "";
            }

            if (["error", "fatal"].indexOf(level) >= 0) {
                _outputLog("error", logString);
            } else if (level == "warn") {
                _outputLog("warn", logString);
            } else {
                _outputLog("info", logString);
            }
        }
    };

    /**
     * Writes log event to console
     * @param level
     * @param obj
     * @private
     */
    var _outputLog = function (level, message) {
        console[level](message);
    };

    /**
     * Provide log methods
     * @param obj
     * @param tag
     * @returns {*}
     */
    var createLogger = function (obj, tag) {
        tag = _.isArray(tag) ? tag.join(',') : tag;
        tag = !_.isEmpty(tag) ? tag.toLowerCase() : 'default';

        obj.trace = function (message, data) {
            _logEvent("trace", message, tag, data);
        };

        obj.debug = function (message, data) {
            _logEvent("debug", message, tag, data);
        };

        obj.info = function (message, data) {
            _logEvent("info", message, tag, data);
        };

        obj.warn = function (message, data) {
            _logEvent("warn", message, tag, data);
        };

        obj.error = function (message, data) {
            _logEvent("error", message, tag, data);
        };

        obj.fatal = function (message, data) {
            _logEvent("fatal", message, tag, data);
        };

        return obj;
    };

    createLogger(self);

    /**
     * Provide tag method with log methods
     * @param tag
     * @returns {*}
     */
    self.tag = function (tag) {
        tag = _.toArray(arguments);
        return createLogger({}, tag);
    };

    return self;
}

module.exports = thisModule();


text:
/* This basic layout borrows heavily from Matthew Levine's "In Search of the Holy Grail"
 * http://www.alistapart.com/articles/holygrail
 * Refer to the article for detailed step-by-step explanation of the layout
 */

html, body, #container{
	height: 100%;
}

#container {
	min-width: 950px;		/* 2 x nav-menu width + right-notification-widget width, to prevent
												 the layout from being broken on browser resizing */
}

#header {
	height: 100px;
	position: relative;
}

#logo-wrapper{
	width: 100%;
	height: 100%;
	position: relative;
}

#banner-text {
	position: absolute;
	width: 100%;
	top: 15%;
}

#club-logo{
	top: 8%;
	position: absolute;
	height: 80px;
	width: 80px;
	left: 30%;
	background: url('images/lug_logo_hd_small.png');
}

#college-logo{
	top: 8%;
	position: absolute;
	height: 80px;
	width: 80px;
	right: 30%;
	background: url('images/clg_logo_hd_small.png');
}

#login-button {
	top: 30px;
	position: absolute;
	height: 32px;
	width: 32px;
	right: 20px;
	background: url('images/signin.png');
	opacity: 0.7;
}

#login-button:hover {
	opacity: 1;
	cursor: pointer;
}

#loginwrapper {
	z-index: 9;
}

#login-dialog {
	display: none;
	width: 300px;
	/*height: 300px;*/
	top: 70px;
	right: 20px;
	position: fixed;
	z-index: 10;
	padding: 20px 20px 20px 20px;
}

#login-dialog div {
	position: relative;
	width: 100%;
}

#wrapper {
	padding-left: 400px;
	padding-right: 50px;    /* Should be reset back to 250px when the notification widget is implemented */

	height: 444px;
}

.wrapper-column {
	position: relative;
	float: left;
}

#content {
	width: 100%;
	height: 100%;
	padding-right: 50px;
}

#content-body-wrapper {
	height: 350px;
	overflow-y: auto;
}

#nav-menu {
	width: 400px;
	margin-left: -105%;
	right: 400px;
	height: 400px;
}

#right-notification-widget {
	width: 250px;
	margin-right: -250px;
}

#footer {
	clear: both;							/* Needed to prevent footer from floating as well */

	padding-top: 14px;
	height: 125px;
}

* html #nav-menu {					/* This is a hack for IE6, just remember that the offset is the
															 size of the right-notification-widget */
	left: 350px;
}

.nav-menu-list {
	position: relative;
	top: 50%;
	left: 50%;
}

.nav-menu-list li{
	margin-left: -63px;				/* Magnitude should be equal to radius of node */
	margin-top: -63px;
	cursor: pointer;
}

#footer-wrapper {
	width: 900px;
	margin: 0 auto;
}

.footer-column {
	float: left;
	width: 550px;
	margin: 0 50px 0 0;
}

.footer-column:first-child {
	width: 250px;
}

.footer-column h4{
	margin: 0 0 20px;
}

#footer-follow {
	float: left;
}

#footer-follow li {
	width: 58px;
	height: 58px;
	float: left;
	margin: 0 10px 10px 0;
}

#footer a {
	text-decoration: none;
	display: block;
	position: relative;
	top: 25px;
	font-size: 0.75em;
}

#footer-follow span {
	background: url(images/social-media-sprite.png);
	height: 58px;
	width: 58px;
	display: block;
	position: absolute;
	top: -25px;
	left: 0;
	cursor: pointer;
	background-color: white;
	border-radius: 50%;
}

#facebook span {
	background-position: 0 0;
}

#facebook span:hover {
	background-position: -62px 0;
	background-color: #233678;
}

#twitter span {
	background-position: -124px 0;
}

#twitter span:hover {
	background-position: -187px 0;
	background-color: #00aced;
}

#googleplus span {
	background-position: -255px 0;
}

/* Create the '+' sign since the PNG contains only the 'g' sybmbol */
#googleplus span:after {
	left: 1.3em;
	top: 0.1em;
	position: absolute;
	display: block;
	content: "+";
	font-size: 2.2em;
	font-weight: bold;
	color: #cf3717;
	font-family: georgia;
}

#googleplus span:hover {
	background-position: -317px 0;
	background-color: #cf3717;
}

/* Change color of '+' on hover( Be careful about the syntax.
 * :hover is a class selector while :after is an element selector ) */
#googleplus span:hover:after {
	color: white;
}

#mailing-list {
	margin-top: 10px;
}

#mailing-list div{
	float: left;
}


text:
<!doctype html>
<html>
  <head>
    <title>Notifications: NotificationEvent exposure in a Service Worker.</title>
    <script src="../resources/testharness.js"></script>
    <script src="../resources/testharnessreport.js"></script>
    <script src="../serviceworker/resources/test-helpers.js"></script>
    <script src="resources/test-helpers.js"></script>
  </head>
  <body>
    <script>
      // Tests that the NotificationEvent object is exposed in a ServiceWorker
      // and exposes the "notification", "action" and "waitUntil" members.
      //
      // Because the NotificationEvent must be created with a notification, a
      // notification is shown and clicked on prior to running the actual test
      // in the Service Worker (serviceworker-notification-event.js).
      async_test(function(test) {
          var scope = 'resources/scope/' + location.pathname,
              script = 'resources/serviceworker-notification-event.js';

          testRunner.setPermission('notifications', 'granted', location.origin, location.origin);

          var workerInfo = null;
          getActiveServiceWorkerWithMessagePort(test, script, scope).then(function(info) {
              workerInfo = info;

              // (1) Display a Web Notification from the document.
              assert_inherits(workerInfo.registration, 'showNotification', 'showNotification() must be exposed.');
              return workerInfo.registration.showNotification(scope, {
                  body: 'Hello, world!',
                  icon: '/icon.png'
              });
          }).then(function() {
              // (2) Simulate a click on the notification that has been displayed.
              testRunner.simulateWebNotificationClick(scope, -1 /* action_index */);

              workerInfo.port.addEventListener('message', function(event) {
                  if (typeof event.data != 'boolean') {
                      assert_unreached('Received an invalid message from the Service Worker.');
                      return;
                  }

                  // (3) Verify that the tests were successful in the Service Worker.
                  assert_true(event.data);

                  test.done();
              });
          }).catch(unreached_rejection(test));

      }, 'The NotificationEvent exposes the expected semantics in a Service Worker.');
    </script>
  </body>
</html>


text:
name: Bug report
about: Create a report to help us improve
title: 'bug: '
labels: bug
assignees: ''

---

**Describe the bug**
<!-- A clear and concise description of what the bug is. -->

**To Reproduce**
<!-- Steps to reproduce the behavior: -->
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error

**Expected behavior**
<!-- A clear and concise description of what you expected to happen. -->

**Screenshots**
<!-- If applicable, add screenshots to help explain your problem. -->

---

<!-- Delete the irrelevant sections -->

**Keyman for Windows/macOS/Linux:**
 - OS: <!-- e.g. Windows 7 x64, Windows 10 2004 x64, macOS Big Sur, Ubuntu 20.04 -->
 - Keyman version: <!-- e.g. 14.0.192-alpha -->
 - Target Application: <!-- e.g. Firefox 55 -->

**Keyman for iPhone/iPad/Android:**
 - Device: <!-- e.g. iPhone 6 -->
 - OS: <!-- e.g. iOS 8.1 -->
 - Keyman version <!-- e.g. 14.0.192-alpha -->
 - Target application: <!-- e.g. Notes, Keyman -->

**KeymanWeb:**
 - OS: <!-- e.g. Windows 7, Windows 10 2004 x64, macOS Big Sur, Ubuntu 20.04, Android 10 -->
 - Browser: <!-- e.g. Chrome, Firefox -->
 - KeymanWeb Version: <!-- e.g. 10.0.201 -->
 - URL: <!-- e.g. https://example.com/web_keyboard/ -->

**Keyman Developer:**
 - OS: <!-- e.g. Windows 7, Windows 10 2004 x64 -->
 - Keyman Developer version: <!-- e.g. 14.0.192-alpha -->

---

**Keyboard**
 - Keyboard name: <!-- e.g. khmer_angkor -->
 - Keyboard version: <!-- e.g. 1.0.1 -->
 - Language name: <!-- e.g. Khmer -->

**Additional context**
<!-- Add any other context about the problem here. -->