text:
var ControllerRef = require('../../controllers/cards');

module.exports = function(app) {
  var router = express.Router();
  var controller = new ControllerRef();

  router
  //  .get('/', controller.getAll);
    .get('/', function(req, res) { controller.getAll(req, res); });

  app.use('/api/cards', router);
};


text:
package edu.ucar.unidata.rosetta.repository.resources;

import edu.ucar.unidata.rosetta.domain.resources.CfType;
import java.util.List;
import org.springframework.dao.DataRetrievalFailureException;

/**
 * The data access object representing a CF type.
 *
 * @author oxelson@ucar.edu
 */
public interface CfTypeResourceDao {

  /**
   * Looks up and retrieves a list of persisted CfType objects.
   *
   * @return A List of all persisted file types.
   * @throws DataRetrievalFailureException If unable to retrieve persisted file types.
   */
  public List<CfType> getCfTypes() throws DataRetrievalFailureException;

  /**
   * Looks up and retrieves a persisted CfType object using the provided id.
   *
   * @param id The id of the file type to retrieve.
   * @return The CfType object matching the provided id.
   * @throws DataRetrievalFailureException If unable to retrieve persisted file type.
   */
  public CfType lookupCfTypeById(int id) throws DataRetrievalFailureException;

  /**
   * Looks up and retrieves a persisted CfType object using the provided name.
   *
   * @param name The name of the file type to retrieve.
   * @return The CfType object matching the provided name.
   * @throws DataRetrievalFailureException If unable to retrieve persisted file type.
   */
  public CfType lookupCfTypeByName(String name) throws DataRetrievalFailureException;
}

redpajama_set_name: RedPajamaGithub


text:
package org.xdi.oxauth.model.jwt;

/**
 * @author Javier Rojas Blum Date: 11.09.2012
 */
public final class JwtHeaderName {

    public static final String TYPE = "typ";
    public static final String ALGORITHM = "alg";
    public static final String KEY_ID = "kid";
    public static final String CONTENT_TYPE = "cty";
    public static final String ENCRYPTION_METHOD = "enc";
    public static final String EPHEMERAL_PUBLIC_KEY = "epk";
    public static final String COMPRESSION_ALGORITHM = "zip";
    public static final String AGREEMENT_PARTY_U_INFO = "apu";
    public static final String AGREEMENT_PARTY_V_INFO = "apv";
    public static final String ENCRYPTION_PARTY_U_INFO = "epu";
    public static final String ENCRYPTION_PARTY_V_INFO = "epv";

    /**
     * The caller references the constants using <tt>JwtClaimName.TYPE</tt>,
     * and so on. Thus, the caller should be prevented from constructing objects of
     * this class, by declaring this private constructor.
     */
    private JwtHeaderName() {
        // this prevents even the native class from calling this constructor as well
        throw new AssertionError();
    }
}


text:
package org.jasig.cas.services;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.jasig.cas.util.PublicKeyFactoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;

import java.security.PublicKey;

/**
 * Represents a public key for a CAS registered service.
 *
 * @author Misagh Moayyed
 * @since 4.1
 */
public class RegisteredServicePublicKeyImpl implements RegisteredServicePublicKey {
    private static final long serialVersionUID = -8497658523695695863L;

    private static final Logger LOGGER = LoggerFactory.getLogger(RegisteredServicePublicKeyImpl.class);

    private String location;

    private String algorithm;

    private Class<PublicKeyFactoryBean> publicKeyFactoryBeanClass = PublicKeyFactoryBean.class;

    /**
     * Instantiates a new Registered service public key impl.
     * Required for proper serialization.
     */
    public RegisteredServicePublicKeyImpl() {
    }

    /**
     * Instantiates a new Registered service public key impl.
     *
     * @param location  the location
     * @param algorithm the algorithm
     */
    public RegisteredServicePublicKeyImpl(final String location, final String algorithm) {
        this.location = location;
        this.algorithm = algorithm;
    }

    public void setLocation(final String location) {
        this.location = location;
    }

    public void setAlgorithm(final String algorithm) {
        this.algorithm = algorithm;
    }

    @Override
    public String getLocation() {
        return this.location;
    }

    @Override
    public String getAlgorithm() {
        return this.algorithm;
    }

    /**
     * Sets public key factory bean class.
     *
     * @param publicKeyFactoryBeanClass the public key factory bean class
     */
    public void setPublicKeyFactoryBeanClass(final Class<PublicKeyFactoryBean> publicKeyFactoryBeanClass) {
        this.publicKeyFactoryBeanClass = publicKeyFactoryBeanClass;
    }

    @Override
    public PublicKey createInstance() throws Exception {
        try {
            final PublicKeyFactoryBean factory = publicKeyFactoryBeanClass.newInstance();
            if (this.location.startsWith("classpath:")) {
                factory.setLocation(new ClassPathResource(StringUtils.removeStart(this.location, "classpath:")));
            } else {
                factory.setLocation(new FileSystemResource(this.location));
            }
            factory.setAlgorithm(this.algorithm);
            factory.setSingleton(false);
            return factory.getObject();
        } catch (final Exception e) {
            LOGGER.warn(e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }

    @Override
    public String toString() {
        return new ToStringBuilder(this)
                .append("location", this.location)
                .append("algorithm", this.algorithm)
                .toString();
    }

    @Override
    public boolean equals(final Object obj) {
        if (obj == null) {
            return false;
        }
        if (obj == this) {
            return true;
        }
        if (obj.getClass() != getClass()) {
            return false;
        }
        final RegisteredServicePublicKeyImpl rhs = (RegisteredServicePublicKeyImpl) obj;
        return new EqualsBuilder()
                .append(this.location, rhs.location)
                .append(this.algorithm, rhs.algorithm)
                .isEquals();
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder()
                .append(location)
                .append(algorithm)
                .toHashCode();
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>dollar (Dollar Examples 0.4.5195 Test API)</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="date" content="2017-09-28">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../jquery/jquery-ui.css" title="Style">

dollar

Classes

DollarBasicTest

DollarLambdaTest

DollarParserTest

DollarSerializationTest

DollarTypeTest

TestPipe


text:
import { FlowRouter } from 'meteor/kadira:flow-router';
import { BlazeLayout } from 'meteor/kadira:blaze-layout';

FlowRouter.route('/', {
  name: 'Home_Page',
  action() {
    BlazeLayout.render('App_Body', { main: 'Home_Page' });
  },
});

FlowRouter.route('/list', {
  name: 'List_Stuff_Page',
  action() {
    BlazeLayout.render('App_Body', { main: 'List_Stuff_Page' });
  },
});

FlowRouter.route('/available-now', {
  name: 'Available_Now_Page',
  action() {
    BlazeLayout.render('App_Body', { main: 'Available_Now_Page' });
  },
});

FlowRouter.route('/top-picks', {
  name: 'Top_Picks_Page',
  action() {
    BlazeLayout.render('App_Body', { main: 'Top_Picks_Page' });
  },
});

FlowRouter.route('/vendors', {
  name: 'Vendors_Page',
  action() {
    BlazeLayout.render('App_Body', { main: 'Vendors_Page' });
  },
});

FlowRouter.route('/diners', {
  name: 'Diners_Page',
  action() {
    BlazeLayout.render('App_Body', { main: 'Diners_Page' });
  },
});

FlowRouter.route('/login', {
  name: 'Login_Page',
  action() {
    BlazeLayout.render('App_Body', { main: 'Login_Page' });
  },
});

FlowRouter.route('/add', {
  name: 'Add_Stuff_Page',
  action() {
    BlazeLayout.render('App_Body', { main: 'Add_Stuff_Page' });
  },
});

FlowRouter.route('/stuff/:_id', {
  name: 'Edit_Stuff_Page',
  action() {
    BlazeLayout.render('App_Body', { main: 'Edit_Stuff_Page' });
  },
});

FlowRouter.notFound = {
  action() {
    BlazeLayout.render('App_Body', { main: 'App_Not_Found' });
  },
};


text:
namespace CSJam2015
{
    class App final : public CSCore::Application
    {
    public:
        void CreateSystems() override;
        void OnInit() override;
        void PushInitialState() override;
        void OnDestroy() override;
    };
}

#endif


text:
package io.github.thatsmusic99.headsplus.api.rewards;

import io.github.thatsmusic99.configurationmaster.api.ConfigSection;
import io.github.thatsmusic99.headsplus.HeadsPlus;
import io.github.thatsmusic99.headsplus.api.Challenge;
import io.github.thatsmusic99.headsplus.api.Reward;
import io.github.thatsmusic99.headsplus.config.MessagesManager;
import net.milkbowl.vault.permission.Permission;
import org.bukkit.entity.Player;

public class AddGroupReward extends Reward {

    private final String group;

    public AddGroupReward(String group, long xp) {
        super(xp);
        this.group = group;
    }

    public static AddGroupReward fromConfigSection(String id, ConfigSection section) {
        if (!section.contains("base-value") && !section.contains("reward-value"))
            throw new IllegalStateException("Reward type ADD_GROUP for reward " + id + " must have a base-value " +
                    "option!");
        return new AddGroupReward(section.getString("base-value", section.getString("reward-value")),
                section.getLong("base-xp", 0));
    }

    @Override
    public void rewardPlayer(Challenge challenge, Player player) {
        super.rewardPlayer(challenge, player);
        Permission permissions = HeadsPlus.get().getPermissions();
        if (!permissions.isEnabled()) return;
        if (permissions.playerInGroup(player, group)) return;
        permissions.playerAddGroup(player, group);
    }

    @Override
    public String getDefaultRewardString(Player player) {
        return MessagesManager.get().getString("inventory.icon.reward.group-add", player)
                .replace("{group}", group);
    }
}


text:
<?php

namespace Magento\Wonderland\Api\Model;

/**
 * Customer attribute metadata class.
 */
class FakeAttributeMetadata extends \Magento\Framework\Api\AbstractSimpleObject implements
    \Magento\Wonderland\Api\Data\FakeAttributeMetadataInterface
{
    /**
     * {@inheritdoc}
     */
    public function getAttributeCode()
    {
        return $this->_get(self::ATTRIBUTE_CODE);
    }

    /**
     * {@inheritdoc}
     */
    public function getStoreLabel()
    {
        return $this->_get(self::STORE_LABEL);
    }

    /**
     * {@inheritdoc}
     */
    public function getFrontendLabel()
    {
        return $this->_get(self::FRONTEND_LABEL);
    }

    /**
     * {@inheritdoc}
     */
    public function getNote()
    {
        return $this->_get(self::NOTE);
    }

    /**
     * Set attribute code
     *
     * @param string $attributeCode
     * @return $this
     */
    public function setAttributeCode($attributeCode)
    {
        return $this->setData(self::ATTRIBUTE_CODE, $attributeCode);
    }

    /**
     * Set label of the store.
     *
     * @param string $storeLabel
     * @return $this
     */
    public function setStoreLabel($storeLabel)
    {
        return $this->setData(self::STORE_LABEL, $storeLabel);
    }

    /**
     * Set label which supposed to be displayed on frontend.
     *
     * @param string $frontendLabel
     * @return $this
     */
    public function setFrontendLabel($frontendLabel)
    {
        return $this->setData(self::FRONTEND_LABEL, $frontendLabel);
    }

    /**
     * Set the note attribute for the element.
     *
     * @param string $note
     * @return $this
     */
    public function setNote($note)
    {
        return $this->setData(self::NOTE, $note);
    }
}


text:
$(document).ready(function() {

    /* platform checkbox change */
    $("[id^='platform'].panel-footer :checkbox").change(function() {

        // get the game and platform id out of the checkbox id
        match = this.id.match("platform_([0-9]+)_([0-9]+)");
        // if ids found and checkbox checked
        if (match.length == 3) {
            $(this).prop('disabled', true); // disable checkbox
            var checkbox = this;
            if (this.checked) {
                // add platform
                $.ajax({
                    type: 'POST',
                    url: '/games/addPlatform',
                    dataType: 'json',
                    data: {
                        GBID: match[1],
                        platformID: match[2]
                    },
                    success: function(data) {
                        if (data.error === true) {
                            $(checkbox).prop('disabled', false); // enable checkbox
                            $(checkbox).prop('checked', false); // reset to unchecked as add failed
                            showErrorModal(data.errorMessage, data.errorProgressURL, data.errorProgressCTA);
                        } else {
                            $(checkbox).prop('disabled', false); // enable checkbox
                        }
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        $(checkbox).prop('disabled', false); // enable checkbox
                        $(checkbox).prop('checked', false); // reset to unchecked as add failed
                        showErrorModal('Well Platform: ' + +console.log(XMLHttpRequest.responseText));
                    }
                });
            } else {
                // remove platform
                $.ajax({
                    type: 'POST',
                    url: '/games/removePlatform',
                    dataType: 'json',
                    data: {
                        GBID: match[1],
                        platformID: match[2]
                    },
                    success: function(data) {
                        if (data.error === true) {
                            $(checkbox).prop('disabled', false); // enable checkbox
                            $(checkbox).prop('checked', true); // reset to checked as remove failed
                            showErrorModal(data.errorMessage);
                        } else {
                            $(checkbox).prop('disabled', false); // enable checkbox
                        }
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        $(checkbox).prop('disabled', false); // enable checkbox
                        $(checkbox).prop('checked', true); // reset to checked as remove failed
                        showErrorModal('Well 2. Some kind of error gone done happened. Please try again.');
                    }
                });
            }
        }
    });
});

/* add/update game status in collection */
function addGame(giantbombID, listID, reloadPage) {
    var MotivationID = 99;
    var StatusID = 0;
    var FutureID = 0;
    var ValueID = 0;

    if (listID == 1) {
        StatusID = 1;
        FutureID = 1;
        ValueID = 1;
    } else if (listID == 2) {
        StatusID = 6;
        FutureID = 1;
        ValueID = 1;
    } else {
        StatusID = 9;
        FutureID = 1;
        ValueID = 1;
    }

    $('#gameButton' + giantbombID).addClass('disabled').html('Saving...');
    $.ajax({
        type: 'POST',
        url: '/games/add',
        dataType: 'json',
        data: {
            GBID: giantbombID,
            listID: listID,
            statusID: StatusID
        },
        success: function(data) {
            console.log("addGame: " + data);
            if (data.error === true) {
                showErrorModal(data.errorMessage);
            } else {
                if (reloadPage) {
                    location.reload(); //need to make this not require reload
                } else {
                    // update list button label/colour
                    $('#gameButton' + giantbombID).html(data.listName + ' ').removeClass().addClass("btn btn-" + data.listStyle + " dropdown-toggle");
                    // display collection status button
                    $('#inCollectionControls' + giantbombID).removeClass("hidden");
                    // display collection status dropdown
                    $('#statusDropdown' + listID).removeClass("hidden");
                    // $('#concepts' + giantbombID).find('input[type=checkbox]').prop('checked', true);
                    // enable platform checkboxes
                    $('#platforms' + giantbombID).find('input[type=checkbox]').prop('readonly', false);
                    // if a platform was auto-selected, update checkbox
                    if (data.autoSelectPlatform != null) {
                        $('#platform_' + giantbombID + '_' + data.autoSelectPlatform).prop('checked', true);
                    }

                }
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            showErrorModal('addGame' + console.log(XMLHttpRequest.responseText));
        }
    });
}

/* update game played motivation */
function changeMotivation(giantbombID, motivationID) {
    $('#motivationButton' + giantbombID).addClass('disabled').html('Saving...');
    $.ajax({
        type: 'POST',
        url: '/games/changeMotivation',
        dataType: 'json',
        data: {
            GBID: giantbombID,
            motivationID: motivationID
        },
        success: function(data) {
            if (data.error === true) {
                console.log("changeMotivation: " + JSON.parse(JSON.stringify(data)));
                showErrorModal(data.errorMessage);
            } else {
                location.reload(); //need to make this not require reload
                $('#motivationButton' + giantbombID).html(data.motivationName + ' ').removeClass().addClass("btn btn-" + data.motivationStyle + " dropdown-toggle");
            }
        },
        error: function(XMLHttpRequest, textMotivation, errorThrown) {
            showErrorModal('changeMotivation' + console.log(XMLHttpRequest.responseText));
        }
    });
}

/* update game played status */
function changeStatus(giantbombID, statusID) {
    $('#statusButton' + giantbombID).addClass('disabled').html('Saving...');
    $.ajax({
        type: 'POST',
        url: '/games/changeStatus',
        dataType: 'json',
        data: {
            GBID: giantbombID,
            statusID: statusID
        },
        success: function(data) {
            console.log("changeStatus: " + JSON.parse(JSON.stringify(data)));
            if (data.error === true) {
                showErrorModal(data.errorMessage);
            } else {
                location.reload(); //need to make this not require reload
                $('#statusButton' + giantbombID).html(data.statusName + ' ').removeClass().addClass("btn btn-" + data.statusStyle + " dropdown-toggle");
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            showErrorModal('changeStatus' + console.log(XMLHttpRequest.responseText));
        }
    });
}

/* update game played future */
function changeFuture(giantbombID, futureID) {
    $('#futureButton' + giantbombID).addClass('disabled').html('Saving...');
    $.ajax({
        type: 'POST',
        url: '/games/changeFuture',
        dataType: 'json',
        data: {
            GBID: giantbombID,
            futureID: futureID
        },
        success: function(data) {
            console.log("changeFuture: " + JSON.parse(JSON.stringify(data)));
            if (data.error === true) {
                showErrorModal(data.errorMessage);
            } else {
                $('#futureButton' + giantbombID).html(data.futureName + ' ').removeClass().addClass("btn btn-" + data.futureStyle + " dropdown-toggle");
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            showErrorModal('changeFuture' + console.log(XMLHttpRequest.responseText));
        }
    });
}

/* update game played value */
function changeValue(giantbombID, valueID) {
    $('#valueButton' + giantbombID).addClass('disabled').html('Saving...');
    $.ajax({
        type: 'POST',
        url: '/games/changeValue',
        dataType: 'json',
        data: {
            GBID: giantbombID,
            valueID: valueID
        },
        success: function(data) {
            console.log("changeValue: " + JSON.parse(JSON.stringify(data)));
            if (data.error === true) {
                showErrorModal(data.errorMessage);
            } else {
                $('#valueButton' + giantbombID).html(data.valueName + ' ').removeClass().addClass("btn btn-" + data.valueStyle + " dropdown-toggle");
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            showErrorModal('changeValue' + console.log(XMLHttpRequest.responseText));
        }
    });
}

/* update game played value */
function setValue(giantbombID, statusID, futureID) {
    var valueID = 99;

    if ((statusID == 1 || statusID == 2) & futureID == 1) { valueID = 1 } else
    if (statusID == 1 & futureID == 2) { valueID = 2 };

    console.log("valueID: " + valueID);

    $('#valueButton' + giantbombID).addClass('disabled').html('Saving...');
    $.ajax({
        type: 'POST',
        url: '/games/changeValue',
        dataType: 'json',
        data: {
            GBID: giantbombID,
            valueID: valueID
        },
        success: function(data) {
            console.log("success setValue: " + JSON.parse(JSON.stringify(data)));
            if (data.error === true) {
                showErrorModal(data.errorMessage);
            } else {
                $('#valueButton' + giantbombID).html(data.valueName + ' ').removeClass().addClass("btn btn-" + data.valueStyle + " dropdown-toggle");
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            showErrorModal('setValue ' + console.log(XMLHttpRequest.responseText));
        }
    });
}

/* display warning modal for removing game */
function showRemoveGameWarning(giantbombID) {
    $('#removeGameButtonPlaceholder').html("Remove from Collection");
    $('#removeGameModal').modal();
}

/* remove game from collection */
function removeFromCollection(giantbombID) {
    $('#removeGameButton' + giantbombID).addClass('disabled').html('Removing...');
    $.ajax({
        type: 'POST',
        url: '/games/remove',
        dataType: 'json',
        data: {
            GBID: giantbombID
        },
        success: function(data) {
            if (data.error === true) {
                $('#removeGameModal').modal('hide');
                showErrorModal(data.errorMessage);
            } else {
                // reload page to refresh state
                location.reload();
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            $('#removeGameModal').modal('hide');
            showErrorModal('Well remove. Some kind of error gone done happened. Please try again.');
        }
    });
}

/* save progression information */
function saveProgression(giantbombID) {
    $('#progressionSaveButton').addClass('disabled').html('Saving...');
    $.ajax({
        type: 'POST',
        url: '/games/saveProgression',
        dataType: 'json',
        data: {
            GBID: giantbombID,
            currentlyPlaying: $('#currentlyPlayingInput').val(),
            hoursPlayed: $('#hoursPlayedInput').val(),
            dateCompleted: $('#dateCompletedInput').val()
        },
        success: function(data) {
            if (data.error === true) {
                showErrorModal(data.errorMessage);
            } else {
                $('#progressionSaveButton').removeClass('disabled').html('Saved');
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            showErrorModal('Well save. Some kind of error gone done happened. Please try again.');
        }
    });
}


text:
const fetchUISettings = require('../../../src/js/jquery/_fetchUISettings');

fixture.setBase('test/jquery/fetchUISettings');
$(fixture.load('forms.html')).appendTo('body');

describe('Fetch UI Settings', function () {

  it('Extract form by default', function () {
    const $el = $('#fetchUISettings1');
    const $fields = $el.find('input');
    const settings = fetchUISettings($el, $fields);
    const expected = {};

    delete settings.fields;
    assert.deepEqual(expected, settings);
  });

  it('Extract form boolean settings (part1)', function () {
    const $el = $('#fetchUISettings2');
    const $fields = $el.find('input');
    const settings = fetchUISettings($el, $fields);
    const expected = {
      disabled: true,
      disableHTML5Validation: true
    };

    delete settings.fields;
    assert.deepEqual(expected, settings);
  });

  it('Extract form boolean settings (part2)', function () {
    const $el = $('#fetchUISettings3');
    const $fields = $el.find('input');
    const settings = fetchUISettings($el, $fields);
    const expected = {
      intern: true,
      autostart: true
    };

    delete settings.fields;
    assert.deepEqual(expected, settings);
  });

  it('Extract form locale', function () {
    const $el = $('#fetchUISettings4');
    const $fields = $el.find('input');
    const settings = fetchUISettings($el, $fields);
    const expected = {
      locale: 'es'
    };

    delete settings.fields;
    assert.deepEqual(expected, settings);
  });

  describe('Extract field settings', function () {

    it('Field without settings', function () {
      const $el = $('#fetchUISettings5');
      const $fields = $el.find('input');
      const settings = fetchUISettings($el, $fields);
      const expected = {};

      assert.isArray(settings.fields);
      assert.lengthOf(settings.fields, 1);
      delete settings.fields[0].name;
      delete settings.fields[0].$el;
      assert.deepEqual(expected, settings.fields[0]);
    });

    it('Boolean properties (part1)', function () {
      const $el = $('#fetchUISettings6');
      const $fields = $el.find('input');
      const settings = fetchUISettings($el, $fields);

      assert.isTrue(settings.fields[0].disabled);
      assert.isTrue(settings.fields[0].required);
    });

    it('Boolean properties (part2)', function () {
      const $el = $('#fetchUISettings7');
      const $fields = $el.find('input');
      const settings = fetchUISettings($el, $fields);

      assert.isTrue(settings.fields[0].intern);
      assert.isTrue(settings.fields[0].autostart);
    });

    it('Display property', function () {
      const $el = $('#fetchUISettings8');
      const $fields = $el.find('input');
      const settings = fetchUISettings($el, $fields);

      assert.equal(settings.fields[0].display, '#selector');
    });

    it('minlength', function () {
      const $el = $('#fetchUISettings9');
      const $fields = $el.find('input');
      const settings = fetchUISettings($el, $fields);
      const validators = settings.fields[0].validators;

      assert.deepEqual(validators, { isLength: { min: 10 } });
    });

    it('maxlength', function () {
      const $el = $('#fetchUISettings10');
      const $fields = $el.find('input');
      const settings = fetchUISettings($el, $fields);
      const validators = settings.fields[0].validators;

      assert.deepEqual(validators, { isLength: { max: 70 } });
    });

    it('Input type number', function () {
      const $el = $('#fetchUISettings11');
      const $fields = $el.find('input');
      const settings = fetchUISettings($el, $fields);
      const validators = settings.fields[0].validators;

      assert.deepEqual(validators, { isFloat: true });
    });

    it('Input type number, min and max', function () {
      const $el = $('#fetchUISettings12');
      const $fields = $el.find('input');
      const settings = fetchUISettings($el, $fields);
      const validators = settings.fields[0].validators;

      assert.deepEqual(validators, { isFloat: { min: 4, max: 8 } });
    });

    it('Input type email', function () {
      const $el = $('#fetchUISettings13');
      const $fields = $el.find('input');
      const settings = fetchUISettings($el, $fields);
      const validators = settings.fields[0].validators;

      assert.deepEqual(validators, { isEmail: true });
    });

    it('Input type url', function () {
      const $el = $('#fetchUISettings14');
      const $fields = $el.find('input');
      const settings = fetchUISettings($el, $fields);
      const validators = settings.fields[0].validators;

      assert.deepEqual(validators, { isURL: true });
    });

    it('Input type datetime', function () {
      const $el = $('#fetchUISettings15');
      const $fields = $el.find('input');
      const settings = fetchUISettings($el, $fields);
      const validators = settings.fields[0].validators;

      assert.deepEqual(validators, { isDate: true });
    });

    it('Input pattern', function () {
      const $el = $('#fetchUISettings16');
      const $fields = $el.find('input');
      const settings = fetchUISettings($el, $fields);
      const validators = settings.fields[0].validators;

      assert.instanceOf(validators.matches, RegExp);
    });

    it('Input pattern with message', function () {
      const $el = $('#fetchUISettings17');
      const $fields = $el.find('input');
      const settings = fetchUISettings($el, $fields);
      const validators = settings.fields[0].validators;

      assert.instanceOf(validators.matches.pattern, RegExp);
      assert.isString(validators.matches.msgs);
    });
  });
});


text:
package io.quarkus.deployment.builditem.nativeimage;

import io.quarkus.builder.item.MultiBuildItem;

/**
 * If any build item of this type is produced, the native-image build tool
 * will run with {@literal --allow-incomplete-classpath} set for versions prior to 22.1 or
 * without {@literal --link-at-build-time} set for versions later than 22.0.
 *

 * This should be strongly discouraged as it makes diagnostics of any issue
 * much more complex, and we have seen it affect error messages of code
 * seemingly unrelated to the code which is having the broken classpath.
 *

 * Use of this build item will trigger a warning during build.
 *
 * @Deprecated Please don't use it unless there is general consensus that we can't practically find a better solution.
 */
@Deprecated
public final class NativeImageAllowIncompleteClasspathBuildItem extends MultiBuildItem {

    private final String extensionName;

    /**
     * @param extensionName Name the extension requiring this, so that it can be shamed appropriately during build.
     */
    public NativeImageAllowIncompleteClasspathBuildItem(String extensionName) {
        this.extensionName = extensionName;
    }

    public String getExtensionName() {
        return extensionName;
    }
}


text:
Lab: Reflection

Problems for exercises and homework for the "CSharp OOP Advanced" course @ SoftUni.

You can check your solutions here: https://judge.softuni.bg/Contests/710/Reflection-Lab

1.   Stealer

Add the Hacker class from the text file to your project. There is one really nasty hacker but not so wise though. He is trying to steal a big amount of money and transfer it to his own account. The police is after him but they need a proffessional… Correct - this is you!

                You have the information that this hacker is keeping some of his info in private fields. Create a new class named Spy and add inside a method called - StealFieldInfo which receives:

stirng - name of the class to investigate

array of string - names of the filds to investigate

After finding the fields you must print on the console:

“Class under investigation: {nameOfTheClass}”

On the next lines print info about each field in the current format:

“{filedName} = {fieldValue}”

Use StringBuilder to concatenate the answer. Don’t change anything in "Hacker" class!

In your main Method you should be able to check your program with the current piece of code.

Example

Output

Class under investigation: Hacker

username = securityGod82

password = mySuperSecretPassw0rd

2.   High Quality Mistakes

You are already expert of High Quality Code, so you know what kind of access modifiers must be set to members of class. You should have noticed our hacker is not familiar with these concepts.

Create a method inside your Spy class called - AnalyzeAcessModifiers(stirng className). Check all fields and methods access modifiers. Print on console all mistakes in format:

Fields

{fieldName} must be private!

Getters

{methodName} have to be public!

Setters

{methodName} have to be private!

Use StringBuilder to concatenate the answer. Don’t change anything in "Hacker" class!

In your main Method you should be able to check your program with the current piece of code.

Example

Output

username must be private!

get_Id have to be public!

set_Password have to be private!

3.   Mission Private Impossible

It’s time to see what this hacker you are dealing with aims to do.  Create a method inside your Spy class called - RevealPrivateMethods(stirng className). Print all private methods in the following format:

All Private Methods of Class: {className}

Base Class: {baseClassName}

On the next lines print found method’s names each on new line

Use StringBuilder to concatenate the answer. Don’t change anything in "Hacker" class!

In your main Method you should be able to check your program with the current piece of code.

Example

Output

All Private Methods of Class: Hacker

Base Class: Object

get_Id

set_Id

set_BankAccountBalance

Finalize

MemberwiseClone

4.   Collector

Using reflection to get all "Hacker" methods. Then prepare algorithm that will recognize, which methods are getters and setters.

Print to console each getter on new line in format:

{name} will return {Return Type}

Then print all setters in format:

{name} will set field of {Parameter Type}

Use StringBuilder to concatenate the answer. Don’t change anything in "Hacker" class!

In your main Method you should be able to check your program with the current piece of code.

Example

Output

get_Password will return System.String

get_Id will return System.Int32

get_BankAccountBalance will return System.Double

set_Password will set field of System.String

set_Id will set field of System.Int32

set_BankAccountBalance will set field of System.Double


text:
A JavaScript plugin for lazy-loading responsive Google Adsense ads.

## Usage and Demo
Read [how to use it](https://css-tricks.com/lazy-loading-responsive-adsense-ads).
Check the [demo](https://osvaldas.info/examples/lazy-loading-responsive-adsense-ads/) ([CodePen](http://codepen.io/osvaldas/pen/XNmNQN)).


text:
package forum.cute.mapper;

import org.apache.ibatis.annotations.Param;

import forum.cute.bean.UserBean;

public interface UserMapper
{
	UserBean selectUserById(int id);

	UserBean selectUserByAccount(String account);

	UserBean selectUserByName(String name);

	int createUser(@Param("p_account")String account, @Param("p_password")String password,
			@Param("p_name")String name, @Param("p_gender")int gender, @Param("p_desc")String desc);

	int updateUser(UserBean user);
}


text:
var connectModrewrite = require('connect-modrewrite');

module.exports = function() {
  return connectModrewrite([
    '^[^\\.]*$ /index.html [L]'
  ]);
};


text:
package org.apache.hyracks.examples.tpch.client;

import java.io.File;

import org.apache.hyracks.api.constraints.PartitionConstraintHelper;
import org.apache.hyracks.api.dataflow.IOperatorDescriptor;
import org.apache.hyracks.api.dataflow.value.ISerializerDeserializer;
import org.apache.hyracks.api.dataflow.value.RecordDescriptor;
import org.apache.hyracks.api.io.FileReference;
import org.apache.hyracks.api.job.JobSpecification;
import org.apache.hyracks.dataflow.common.data.marshalling.UTF8StringSerializerDeserializer;
import org.apache.hyracks.dataflow.common.data.parsers.IValueParserFactory;
import org.apache.hyracks.dataflow.common.data.parsers.UTF8StringParserFactory;
import org.apache.hyracks.dataflow.std.file.FileSplit;

public class Common {
    static RecordDescriptor custDesc = new RecordDescriptor(new ISerializerDeserializer[] {
            UTF8StringSerializerDeserializer.INSTANCE, UTF8StringSerializerDeserializer.INSTANCE,
            UTF8StringSerializerDeserializer.INSTANCE, UTF8StringSerializerDeserializer.INSTANCE,
            UTF8StringSerializerDeserializer.INSTANCE, UTF8StringSerializerDeserializer.INSTANCE,
            UTF8StringSerializerDeserializer.INSTANCE, UTF8StringSerializerDeserializer.INSTANCE });

    static RecordDescriptor ordersDesc = new RecordDescriptor(new ISerializerDeserializer[] {
            UTF8StringSerializerDeserializer.INSTANCE, UTF8StringSerializerDeserializer.INSTANCE,
            UTF8StringSerializerDeserializer.INSTANCE, UTF8StringSerializerDeserializer.INSTANCE,
            UTF8StringSerializerDeserializer.INSTANCE, UTF8StringSerializerDeserializer.INSTANCE,
            UTF8StringSerializerDeserializer.INSTANCE, UTF8StringSerializerDeserializer.INSTANCE,
            UTF8StringSerializerDeserializer.INSTANCE });
    static RecordDescriptor custOrderJoinDesc = new RecordDescriptor(new ISerializerDeserializer[] {
            UTF8StringSerializerDeserializer.INSTANCE, UTF8StringSerializerDeserializer.INSTANCE,
            UTF8StringSerializerDeserializer.INSTANCE, UTF8StringSerializerDeserializer.INSTANCE,
            UTF8StringSerializerDeserializer.INSTANCE, UTF8StringSerializerDeserializer.INSTANCE,
            UTF8StringSerializerDeserializer.INSTANCE, UTF8StringSerializerDeserializer.INSTANCE,
            UTF8StringSerializerDeserializer.INSTANCE, UTF8StringSerializerDeserializer.INSTANCE,
            UTF8StringSerializerDeserializer.INSTANCE, UTF8StringSerializerDeserializer.INSTANCE,
            UTF8StringSerializerDeserializer.INSTANCE, UTF8StringSerializerDeserializer.INSTANCE,
            UTF8StringSerializerDeserializer.INSTANCE, UTF8StringSerializerDeserializer.INSTANCE,
            UTF8StringSerializerDeserializer.INSTANCE });

    static IValueParserFactory[] orderParserFactories = new IValueParserFactory[] { UTF8StringParserFactory.INSTANCE,
                        UTF8StringParserFactory.INSTANCE, UTF8StringParserFactory.INSTANCE,
                        UTF8StringParserFactory.INSTANCE, UTF8StringParserFactory.INSTANCE,
                        UTF8StringParserFactory.INSTANCE, UTF8StringParserFactory.INSTANCE,
                        UTF8StringParserFactory.INSTANCE, UTF8StringParserFactory.INSTANCE };

    static FileSplit[] parseFileSplits(String fileSplits) {
        String[] splits = fileSplits.split(",");
        FileSplit[] fSplits = new FileSplit[splits.length];
        for (int i = 0; i < splits.length; ++i) {
            String s = splits[i].trim();
            int idx = s.indexOf(':');
            if (idx < 0) {
                throw new IllegalArgumentException("File split " + s + " not well formed");
            }
            fSplits[i] = new FileSplit(s.substring(0, idx), new FileReference(new File(s.substring(idx + 1))));
        }
        return fSplits;
    }

    static void createPartitionConstraint(JobSpecification spec, IOperatorDescriptor op, FileSplit[] splits) {
        String[] parts = new String[splits.length];
        for (int i = 0; i < splits.length; ++i) {
            parts[i] = splits[i].getNodeName();
        }
        PartitionConstraintHelper.addAbsoluteLocationConstraint(spec, op, parts);
    }
}


text:
namespace Exceptions_Homework
{
    using System;

    public class SimpleMathExam : Exam
    {
        private const int MinProblemsSolved = 0;
        private const int MaxProblemsSolved = 10;

        private int problemsSolved;

        public SimpleMathExam(int problemsSolved)
        {
            this.ProblemsSolved = problemsSolved;
        }

        public int ProblemsSolved
        {
            get
            {
                return this.problemsSolved;
            }

            private set
            {
                int checkedValue;

                if(value < 0)
                {
                    checkedValue = MinProblemsSolved;
                }
                else if(value > 10)
                {
                    checkedValue = MaxProblemsSolved;
                }
                else
                {
                    checkedValue = value;
                }

                this.problemsSolved = checkedValue;
            }
        }

        public override ExamResult Check()
        {
            if (ProblemsSolved == 0)
            {
                return new ExamResult(2, 2, 6, "Bad result: nothing done.");
            }
            else if (ProblemsSolved == 1)
            {
                return new ExamResult(4, 2, 6, "Average result: nothing done.");
            }
            else if(ProblemsSolved == 2)
            {
                return new ExamResult(6, 2, 6, "Average result: nothing done.");
            }
            else
            {
                throw new ArgumentException("Invalid number of problems solved!");
            }

            //return new ExamResult(0, 0, 1, "Invalid number of problems solved!");
        }
    }
}


text:
package main

import (
	"io"
	"log"
	"net"
)

type Protocol interface {
	// address to proxy to
	Address() string

	// identify protocol from header
	Identify(header []byte) bool
}

type Mux struct {
	Handlers []Protocol
}

// create a new Mux assignment
func NewMux() *Mux {
	return &Mux{}
}

// add a protocol to mux handler set
func (m *Mux) Handle(p Protocol) {
	m.Handlers = append(m.Handlers, p)
}

// match protocol to handler
// returns address to proxy to
func (m *Mux) Identify(header []byte) (address string) {
	if len(m.Handlers) < 1 {
		return ""
	}

	for _, handler := range m.Handlers {
		if handler.Identify(header) {
			return handler.Address()
		}
	}

	// return address of last handler, default
	return m.Handlers[len(m.Handlers)-1].Address()
}

// create a server on given address and handle incoming connections
func (m *Mux) ListenAndServe(addr string) error {
	server, err := net.Listen("tcp", addr)
	if err != nil {
		return err
	}

	for {
		conn, err := server.Accept()
		if err != nil {
			return err
		}

		go m.Serve(conn)
	}

	return nil
}

// serve takes an incomming connection, applies configured protocol
// handlers and proxies the connection based on result
func (m *Mux) Serve(conn net.Conn) error {
	defer conn.Close()

	// get first 3 bytes of connection as header
	header := make([]byte, 3)
	if _, err := io.ReadAtLeast(conn, header, 3); err != nil {
		return err
	}

	// identify protocol from header
	address := m.Identify(header)

	log.Printf("[INFO] proxy: from=%s to=%s\n", conn.RemoteAddr(), address)

	// connect to remote
	remote, err := net.Dial("tcp", address)
	if err != nil {
		log.Printf("[ERROR] remote: %s\n", err)
		return err
	}
	defer remote.Close()

	// write header we chopped back to remote
	remote.Write(header)

	// proxy between us and remote server
	err = Shovel(conn, remote)
	if err != nil {
		return err
	}

	return nil
}


text:
define ([
        'dojo/_base/declare',
        'dojo/_base/array',
        'dojo/_base/lang',
        'dojo/topic'
    ],
    function (
        declare,
        array,
        lang,
        topic
    ){
        // module:
        //		Sds/SubscribeMixin

        return declare (
            [],
            {
                // summary:
                //		Can be mixed into objects that need to subscribe to topics

                // _connects: array
                //		Array of connection handles
                _connects: [],
                _disconnect: function(/*object*/ handle) {
                    // summary:
                    //     Stop listening to a topic
                    //
                    // tags:
                    //     protected

                    var index = array.indexOf(this._connects, handle);
                    if (index != -1) {
                        handle.remove();
                        this._connects.splice(index, 1);
                    }
                },
                subscribe: function(/*string*/ topicName, /*string*/ method){
                    // summary:
                    //      Subscribe to a topic

                    var handle = topic.subscribe(topicName, lang.hitch(this, method));
                    this._connects.push(handle);
                    return handle;		// _Widget.Handle
                },
                unsubscribe: function(/*Object*/ handle) {
                    // summary:
                    //     Stop listening to a topic

                    this._disconnect(handle);
                }
            }
        );
    }
);


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>panda-microservice</artifactId>
        <groupId>org.openpanda.microservice</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>panda-microservice-cloud</artifactId>
    <packaging>pom</packaging>

    <name>Panda Microservice Cloud Module</name>
    <description>Panda Microservice Cloud云服务模块</description>
    <modules>
        <module>panda-microservice-cloud-api</module>
        <module>panda-microservice-cloud-etcd</module>
    </modules>

</project>


text:
<!DOCTYPE html>

<title th:text="#{error.notfound.title}">_Not found_</title>

_Not found_

_contact admins_


text:
<component name="ProjectRunConfigurationManager">
  <configuration default="false" name="TransitExampleIOS" type="AppleRunConfiguration" factoryName="Application" SCHEME_NAME="TransitExampleIOS" PROJECT_NAME="TransitExampleIOS" TARGET_NAME="TransitExampleIOS" CONFIG_NAME="Debug" WORKING_DIR="" PASS_PARENT_ENVS="FALSE" RUN_TARGET_PROJECT_NAME="TransitExampleIOS" RUN_TARGET_NAME="TransitExampleIOS" MAKE_ACTIVE="TRUE" WAIT_FOR="FALSE">
    <envs />
    <RunnerSettings RunnerId="AppRunner" />
    <ConfigurationWrapper RunnerId="AppRunner" />
    <method />
  </configuration>
</component>


text:
##Step 1: Files to Store in the GitHub Repository

The file appspec.yaml contains the instructions to transfer files from GitHub Source to AWS EC2 Destination.

The script directy contains some .sh files with some commands to execute before or after the file transfer
action.

The file appspec.yalm and the script directoy and its files should be store in the Github Repository at the
root level.

##Step 2:  AWS permission configuracion

Go to the IAM Management Console and Create 2 roles:

1) Role Name: CodeDeploy with the Policy Name: AWSCodeDeployRole add in the Trush Relationship this code:

        {
        "Version": "2012-10-17",
        "Statement": [
          {
            "Sid": "",
            "Effect": "Allow",
            "Principal": {
              "Service": "codedeploy.amazonaws.com"
            },
            "Action": "sts:AssumeRole"
          }
        ]
        }

2) Role Name: CodeDeploy-E2 with the Policy Name: AmazonS3ReadOnlyAccess.

##Step 3: Create an EC2 instance (Ubuntu / Linux)

- Input IAM Role as code-deploy-ec2
- Enable Protect against accidental termination
- Add a Tag Name for the Instance
- Configure Security Group (Open Ports)

##Step 4: Install the CodeDeploy Agent

      sudo apt-get install python-pip ruby wget
      cd /home/ubuntu
      wget https://aws-codedeploy-{set the instance region like us-south-1}.s3.amazonaws.com/latest/install
      chmod +x ./install
      sudo ./install auto
      sudo service codedeploy-agent start
      sudo service codedeploy-agent status

#II.-Make a Deploy from Github to AWS Manually

##1) Go to the AWS CodeDeploy Service and Create an Application:

- Input an Application Name, Deployment Group Name and Add the Instance for the Development Group.
- Select the Deployment Configuracion (Ex.OneAtATime).
- Select the Service Role "arn:aws:iam::....../DeployCode".
- Press the button Create Application.

##2) Deploy a New Revision / Commit

Go to your GitHub Repository and make any commit after that Deploy a New Revision with the AWS CodeDeploy Service and follow this instructions.

- Select the Deployment Group from the table.

- Select the Action "Deploy new revision" to display the Page Create a New Deploy.

Create Deploymenet Page
- Select the Application Name.
- Select the Deployment Group.
- Select the Revision Type: "MyApplication is sotred in GitHub"
- Press the button Connect to GitHub.
- Input the Github Repository Name.
- Input a CommitID (Found in the Github Commits History)
- Select Rollback Configuration.
- Press button Deploy Now

#III.- Autodeploy from Github to AWS EC2 instance

##Step 1: Create an IAM Policy

Create a IAM policy which give access to register and create a new deployment, also to create new revision
for a deployment group.

a) Select a create Your Own Policy and give a name like codedeploy-github-access

b) Paste this json objet in the Policy Document Field:

        {
          "Version": "2012-10-17",
          "Statement": [
            {
              "Effect": "Allow",
              "Action": "codedeploy:GetDeploymentConfig",
              "Resource": "arn:aws:codedeploy:ACCOUNT_REGION:ACCOUNT_ID:deploymentconfig:*"
            },
            {
              "Effect": "Allow",
              "Action": "codedeploy:RegisterApplicationRevision",
              "Resource": "arn:aws:codedeploy:ACCOUNT_REGION:ACCOUNT_ID:application:APPLICATION_NAME"
            },
            {
              "Effect": "Allow",
              "Action": "codedeploy:GetApplicationRevision",
              "Resource": "arn:aws:codedeploy:ACCOUNT_REGION:ACCOUNT_ID:application:APPLICATION_NAME"
            },
            {
              "Effect": "Allow",
              "Action": "codedeploy:CreateDeployment",
              "Resource": "arn:aws:codedeploy:ACCOUNT_REGION:ACCOUNT_ID:deploymentgroup:
              APPLICATION_NAME/DEPLOYMENT_GROUP"
            }
          ]
        }

c) Change in the Json Objet the words

- ACCESS_REGION with the E2 Instance Region (lIKE us-west-2).
- ACCOUNT_ID with the one found in My Account Page -> Congiguration Account.
- APPLICATION_NAME found in the CodeDeploy Console.
- DEPLOYMENT_GROUP found in the CodeDeploy Console.

##Step 2: Create an IAM User

- Give a Name to the User like CodeDeployUser
- Attach the Policy created in the Step 1
- Download/Copy the Access ID and the Secret Access Token and store in a secure place.

##Step 3: Github Integration

a) Generate a new personal aceess token in the Personal Setting Page -> Develop Settings -> Personal access tokens

- Input a Token Description like autodeploy-codedeploy
- Check repo:status and repo_deployment
- Press the button Regenerate Token
- Download/Copy the Github Token and store in a secure place, it will be need for the Github AutoDeployment integration.

b) Crete two integration services in Github

Go to Proyect Settings -> Integration and Services

Add a Service: AWS CodeDeploy

- Input the Application Name found in the ASW CodeDeploy Console.
- Input the Development Group found in the ASW CodeDeploy Console.
- Input the AWS Access Key from the user (codedeploy-github-user) created in the AWS CodeDeploy Console.
- Input the AWS Instance Region (like us-west 2).
- Input the AWS Secret Access Key from the user (codedeploy-github-user) created in the AWS CodeDeploy Console.
- Press the button Add Servie.

Other fields are optional.

Add a Service: Github Auto-Deployment

- Input the Github Token Generated above.
- Input the Enviromentment take it from the AWS CodDeploy Development Group.
- If you are using Continues Integration (CI) check Deploy on status

Other fields are optional.

Now when we edit file and commit on master branch or merge any pull request a new deployment will be created
on AWS CodeDeploy base on the appspec.yaml file.

Done!!!

##REFERENCES:

[Autodeploy from github using AWS CodeDeploy](http://crypt.codemancers.com/posts/2016-12-26-autodeploy-from-github-using-aws-codedeploy/), From: crypt.codemancers.com, Author: Revath S Kumar  Publish Date: December 26, 2016

[Automatically Deploy from GitHub Using AWS CodeDeploy](https://aws.amazon.com/es/blogs/devops/automatically-deploy-from-github-using-aws-codedeploy/) From aws.amazon.com, Author: Rob Brigham Publish Date: December 18, 2014


text:
package v1

import (
	"testing"
	"time"

	"github.com/google/go-cmp/cmp"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"knative.dev/pkg/apis"
	duckv1 "knative.dev/pkg/apis/duck/v1"
)

func TestPubSub_GetFullType(t *testing.T) {
	ps := &PubSub{}
	switch ps.GetFullType().(type) {
	case *PubSub:
		// expected
	default:
		t.Errorf("expected GetFullType to return *PubSub, got %T", ps.GetFullType())
	}
}

func TestPubSub_GetListType(t *testing.T) {
	ps := &PubSub{}
	switch ps.GetListType().(type) {
	case *PubSubList:
		// expected
	default:
		t.Errorf("expected GetListType to return *PubSubList, got %T", ps.GetListType())
	}
}

func TestPubSub_Populate(t *testing.T) {
	got := &PubSub{}

	want := &PubSub{
		Spec: PubSubSpec{
			SourceSpec: duckv1.SourceSpec{
				Sink: duckv1.Destination{
					URI: &apis.URL{
						Scheme:   "https",
						Host:     "tableflip.dev",
						RawQuery: "flip=mattmoor",
					},
				},
				CloudEventOverrides: &duckv1.CloudEventOverrides{
					Extensions: map[string]string{
						"boosh": "kakow",
					},
				},
			},
			Secret: &corev1.SecretKeySelector{
				LocalObjectReference: corev1.LocalObjectReference{Name: "secret"},
				Key:                  "secretkey",
			},
		},

		Status: PubSubStatus{
			IdentityStatus: IdentityStatus{
				Status: duckv1.Status{
					ObservedGeneration: 42,
					Conditions: duckv1.Conditions{
						{
							// Populate ALL fields
							Type:               duckv1.SourceConditionSinkProvided,
							Status:             corev1.ConditionTrue,
							LastTransitionTime: apis.VolatileTime{Inner: metav1.NewTime(time.Date(1984, 02, 28, 18, 52, 00, 00, time.UTC))},
						},
					},
				},
			},
			SinkURI: &apis.URL{
				Scheme:   "https",
				Host:     "tableflip.dev",
				RawQuery: "flip=mattmoor",
			},
			ProjectID:      "projectid",
			TopicID:        "topicid",
			SubscriptionID: "subscriptionid",
		},
	}

	got.Populate()

	if diff := cmp.Diff(want, got); diff != "" {
		t.Errorf("Unexpected difference (-want, +got): %v", diff)
	}
}


text:
import mongoose from "mongoose";

var UserSchema = mongoose.Schema({
    name: String,
    surname: String,
    eMail: String,
    username: String,
    password: String,
    registered: {
        type: Date,
        default: Date.now
    }
});

UserSchema.methods.getFullName = function () {
    return `${this.name} ${this.surname}`;
};

UserSchema.methods.getApproximateAge = function () {
    return Math.round(
        (Date.now() - this.registered.getTime() + this.age*1000*60*60*24*365.25)
        /1000/60/60/24/365.25
    );
};

module.exports.User = mongoose.model("User", UserSchema);


text:
typedef struct Sound {
	Resource res;
	char rel_file[MAX_PATH_SIZE];

	U32 ch_count;
	U32 frame_count; // sample_count/ch_count
	F32 samples[]; // Interleaved samples
} PACKED Sound;

REVOLC_API WARN_UNUSED
Sound *blobify_sound(struct WArchive *ar, Cson c, bool *err);
REVOLC_API void deblobify_sound(WCson *c, struct RArchive *ar);

#endif // REVOLC_SOUND_H


text:
/*****************************************************************************
* Script to create the Static Fan Effect
*****************************************************************************/

window.requestAnimFrame = (function(){
  return  window.requestAnimationFrame       ||
          window.webkitRequestAnimationFrame ||
          window.mozRequestAnimationFrame    ||
          function( callback ){
            window.setTimeout(callback, 1000 / 60);
          };
})();

fanGlobals = {
    fpsZone: {
        fps : "calculating",
        lastFPSTime: 0,
        framesDrawnFromLastCycle: 0
    },
    rps : 0
}

var calculateFPS = function(){
    var currentSecond = new Date().getUTCSeconds();
        lastSecond = fanGlobals.fpsZone.lastFPSTime;

    fanGlobals.fpsZone.framesDrawnFromLastCycle++;

    if(currentSecond - lastSecond === 1){
        fanGlobals.fpsZone.fps = fanGlobals.fpsZone.framesDrawnFromLastCycle;
        fanGlobals.fpsZone.framesDrawnFromLastCycle = 0;
    }else if(currentSecond - lastSecond > 1){
        fanGlobals.fpsZone.fps = "Calculating";
    }

    fanGlobals.fpsZone.lastFPSTime = currentSecond;

}

function drawFan(canvas,wings,position,rotationAngle){
    var ctx = canvas.getContext('2d'),
        wingCount = wings.length,
        wing,
        i;

    for(i = 0; i < wingCount; i++){
        wing = wings[i];
        ctx.beginPath();
        ctx.moveTo(position.x, position.y);
        ctx.arc(position.x, position.y, wing.radius, wing.startAngle + rotationAngle, wing.endAngle + rotationAngle, false);
        ctx.fillStyle = wing.fillStyle;
        ctx.fill();
        ctx.closePath();
    }
}

function renderInfo(canvas,position, infos){
    var ctx = canvas.getContext('2d'),
        i,
        textMatrix,
        fontHeightDelta = 0,
        info;

    ctx.beginPath();

    for(i = 0; i < infos.length; i++){
        info = infos[i];
        ctx.fillStyle = info.fillStyle || "#999";
        ctx.font="16px verdana";
        ctx.fillText(info,position.x, position.y + fontHeightDelta);
        fontHeightDelta = fontHeightDelta + 30;

    }
}

var generateWings = function(count){
    var wings = [],
        i,
        count = parseInt(count) > 0 ? parseInt(count) : 3,
        angularDistance = (2 * Math.PI)/count;

    for(i = 0; i < count; i++){
        wing = {
            fillStyle: 'rgb(' + Math.floor(256*Math.random()) + ',' + Math.floor(256*Math.random()) + ',' + Math.floor(256*Math.random()) + ')',
            startAngle: angularDistance * i,
            endAngle: angularDistance * i + (Math.PI/6),
            radius: 150,
        }

        wings.push(wing);
    }

    return wings;

};

var renderer = (function(){
    var rotationAngleFan = 0,
        canvas = document.getElementById('canvas-zone'),
        ctx = canvas.getContext('2d'),
        canvasHeight= canvas.height,
        canvasWidth = canvas.width,
        velocity = 0.01;
        wings = generateWings(3);
		pause = false;

    var render = function(){
		if(!pause){
			ctx.clearRect(0, 0, canvasWidth, canvasHeight);
			rotationAngleFan = rotationAngleFan + velocity;
			drawFan(canvas, wings, {x:300, y:200}, rotationAngleFan);
            renderInfo(canvas,{x:500,y:100},getFanInfo());
		}
    };

    var getVelocity = function(){
        return velocity;
    };

    var setVelocity = function(angVelocity){
        velocity = angVelocity;
    };

    var getScreenFPS = function(){

    }

	var togglePause = function(){
		pause = !pause;
	}

    var getFanInfo = function(){
        var textInfos = [],
            angularSpeed,
            rps,
            currentSecond = new Date().getMilliseconds(),
            lastSecond = fanGlobals.fpsZone.lastFPSTime;

        if(fanGlobals.fpsZone.fps >= 0){
            angularSpeed = (180 * velocity / Math.PI) * fanGlobals.fpsZone.fps;
        }

        fanGlobals.rps = angularSpeed/360;

        textInfos.push("Angular Speed: " + angularSpeed);
        textInfos.push("RPS: " + fanGlobals.rps);
        textInfos.push("FPS: " + fanGlobals.fpsZone.fps);

        return textInfos;
    }

    return {
        render: render,
        getVelocity: getVelocity,
        setVelocity: setVelocity,
		togglePause: togglePause
    }
})();

window.addEventListener('keydown',function(ev){
    var delta;

    if(fanGlobals.rps % 60 < 3 || fanGlobals.rps % 60 > 57)
    {
        delta = 0.001;
    }
    else {
        delta = 0.01;
    }

	switch(ev.which){
		case 40: renderer.setVelocity(renderer.getVelocity() - delta);
                 ev.preventDefault();
				 break;
		case 38: renderer.setVelocity(renderer.getVelocity() + delta);
                 ev.preventDefault();
			     break;
		case 80: renderer.togglePause();
			     break;
		default: ;
	}
});

(function animloop(){
  requestAnimFrame(animloop);
  calculateFPS();
  renderer.render();
})();


text:
Gromit is primarily an OAuth2 client for AngularJS.  It's focused on the [Micro Focus](https://www.microfocus.com/) OAuth2 implementation called OSP, but it should work with generic OAuth2 providers.

Along with OAuth2 support this library has support for other features like message handling in the UI, date formatting, and specialized CSS property handling.

There are two additional projects that support Gromit.

  * [Gromit Sample](https://github.com/Gromit-Soft/gromit-sample) - This project shows you how to use Gromit and contains a working example.
  * [Gromit Build](https://github.com/Gromit-Soft/gromit-build) - This project contains Gradle plugins to support Gromit.  These plugins aren't required, but they make things a little easier.

## Using Gromit

If you just want to download Gromit directly then you can get the latest from the [Sonatype Nexus server](https://oss.sonatype.org/#nexus-search;quick~gromit).

Gromit is available on Maven Central.  If you are using Maven you can include Gromit as a project dependency like this:

```xml
<dependency>
  <groupId>org.gromitsoft</groupId>
  <artifactId>gromit</artifactId>
  <version>1.0.4</version>
</dependency>
```

Include Gromit in a Gradle build environment like this:

```
api 'org.gromitsoft:gromit:1.0.4'
```

You can also include Gromit in your `package.json` file for an NPM based build.  There are specific [instructions for adding Gromit to an NPM and Gulp based project](https://github.com/MicroFocus/CX/blob/master/doc/gromit.md).

## OAuth2 Client

The Gromit OAuth2 client handles all logins, token validation and token refreshes seemlessly.  When you make an HTTP request with Gromit the library will handle any 401 responses or other responses indicating that you need a token.  It will then work with the OSP server to get a token and repeat your request.  You will never lose any state of your JavaScript application while this happens.

Gromit also has a request queue for handling multiple requests which all require a token.  In this case Gromit will suspend all the requests until the token is acquired and then replay any requests that happened during that process.

To use the Gromit OAuth2 client you must configure the following three properties:

```JavaScript
gromit.ClientId = 'myClientId';
gromit.AuthUrl = 'http://myserver/osp/a/idm/auth/oauth2/grant';
gromit.AuthLogoutUrl = 'http://myserver/osp/a/idm/auth/app/logout';
```

  * The `ClientId` is the OAuth2 client ID that you have configured.  You will set this client ID during the [configuration of your new SSO client](https://github.com/MicroFocus/CX/tree/master/token-validation#configuring-your-project).

  * The `AuthUrl` is the location of your OSP server.  This is the URL Gromit will redirect to when getting a token.

  * The `AuthLogoutUrl` is the location of your OSP server logout link.  Gromit redirects to this page for logging out.

Once you have configured your client you can make HTTP calls to your server with the following functions:  `gromit.get`, `gromit.post`, `gromit.put`, `gromit.del`.  These four functions support an HTTP GET, POST, PUT, and DELETE respectively.

### gromit.init

The `gromit.init` function must be called before making HTTP requests with Gromit.  This function has no parameters and does not return any values.

### gromit.get

The `gromit.get` function supports HTTP GET operations.  The arguments to this function are:

  * `url` - The URL to make the GET request to
  * `http` - The Angular HTTP object to use for this request
  * `successCallback` - The callback function if the call succeeds
  * `errorCallback` - The callback function if the call fails with a well formatted error
  * `unknownErrorCallback` - The callback function if the call fails with an unknown error

**Code example**

```
gromit.get('http://myserver/myapi', $http, function(data) {
    $scope.data = data;
});
```

### gromit.post

The `gromit.post` function supports HTTP POST operations.  The arguments to this function are:

  * `url` - The URL to make the get request to
  * `http` - The Angular HTTP object to use for this request
  * `data` - A JavaScript object to send as the post body
  * `successCallback` - The callback function if the call succeeds
  * `errorCallback` - The callback function if the call fails with a well formatted error
  * `unknownErrorCallback` - The callback function if the call fails with an unknown error
  * `headers` - A JavaScript object containing key and value pairs for additional HTTP headers

**Code example**

```
var dataToSend = {'some key', 'some value'};
gromit.post('http://myserver/myapi', $http, dataToSend, function(data) {
    $scope.data = data;
});
```

### gromit.put

The `gromit.put` function supports HTTP PUT operations.  The arguments to this function are:

  * `url` - The URL to make the get request to
  * `http` - The Angular HTTP object to use for this request
  * `data` - A JavaScript object to send as the post body
  * `successCallback` - The callback function if the call succeeds
  * `errorCallback` - The callback function if the call fails with a well formatted error
  * `unknownErrorCallback` - The callback function if the call fails with an unknown error

**Code example**

```
var dataToSend = {'some key', 'some value'};
gromit.put('http://myserver/myapi', $http, dataToSend, function(data) {
    $scope.data = data;
});
```

### gromit.del

The `gromit.del` function supports simple HTTP DELETE operations.  The arguments to this function are:

  * `url` - The URL to make the get request to
  * `http` - The Angular HTTP object to use for this request
  * `successCallback` - The callback function if the call succeeds
  * `errorCallback` - The callback function if the call fails with a well formatted error
  * `unknownErrorCallback` - The callback function if the call fails with an unknown error

**Code example**

```
gromit.del('http://myserver/myapi', $http, function(data) {
    $scope.data = data;
});
```

### Gromit callback functions

Gromit supports three callback functions.

`successCallback` handles successful HTTP requests.  This is called with a single argument containing any data that was returned from the server.  This argument may be null if the server didn't return any data.

`errorCallback` handles well formatted errors.  These errors have the following format:

```JavaScript
{
    "Fault": {
        "Code": {
            "Subcode": {
                "Value": "MyErrorSubCode"
            },
            "Value": "MyErrorCode"
        },
        "Reason": {
            "Text": "This is why my error happened"
        }
    }
}
```

This format is used by many of the Micro Focus REST APIs.

The `errorCallback` function is called with the following arguments:  The fault code, the fault subcode, and the fault reason text.  In this case the arguments would be `MyErrorCode`, `MyErrorSubCode`, and `This is why my error happened`.

`unknownErrorCallback` is called for all other errors.  This includes errors contacting the server and errors from the server that do not match the format sent to the `errorCallback` function.

The `unknownErrorCallback` function is called with the following arguments:

  * The data sent back from the server
  * The HTTP status code returned by the server
  * A JavaScript object containing the HTTP headers sent from the server

### gromit.doLogout

This function securely logs the client out.  This will remove any data in JavaScript memory as well as any cookies that contain token data.  It will then send the logout request to the OSP server to complete the process.  The last step is that it will refresh the current page to remove any data from JavaScript memory that might be hanging around from the previous session.

The `doLogout` function doesn't take any arguments.

```
gromit.doLogout();
```

### gromit.token

This is a property that has the current access token.  This property will be null until a REST call is made and the user logs in.

This property may also contain an expired token if the current access token has timed out.  The safest way to use this property is in the callback for another REST call to make sure the token is valid.

```
gromit.get('http://myserver/myapi', $http, function(data) {
    console.log('my token is: ' + gromit.token;
});
```

### gromit.tokenType

This property contains the token type of the access token.  This value is null until a REST call is made and the user logs in.

Once the property is set the value is almost always `Bearer`.

## Showing messages with Gromit

Gromit provides the ability to show transient and permanent messages in your application.

### gromit.showMessage

The `showMessage` function shows a transient message over the top of the page.  This message will disappear after five seconds.

**Code example**

```
gromit.showMessage('This is a transient information message');
```

![Transient message example](doc/msg.png)

### gromit.showWarningMessage

The `showWarningMessage` function shows a transient warning message over the top of the page.  This message will disappear after five seconds.

**Code example**

```
gromit.showWarningMessage('This is a transient warning message');
```

![Transient warning message example](doc/warn_msg.png)

### gromit.showErrorMessage

The `showErrorMessage` function shows a transient error message over the top of the page.  This message will disappear after five seconds.

**Code example**

```
gromit.showErrorMessage('This is a transient error message');
```

![Transient error message example](doc/err_msg.png)

### gromit.showFatalErrorMessage

The `showFatalErrorMessage` function shows an error message on the top of the page and scrolls the page to make that error visible.  This error message will stay until it is dismissed.

**Code example**

```
gromit.showErrorMessage('This is a transient error message');
```

![Fatal error message example](doc/err_fatal_msg.png)

## Date and time formatting

Gromit provides data and time formatting operations.  These operations are tied to the current locale and used for security checking during the login process.  Gromit provides this formatting through the [MomentJS](https://momentjs.com/) library.  You can use MomentJS directly, but Gromit also provides the following helper functions:

### gromit.setLocale

This function sets the locale for all future date formatting.

**Code example**

```
gromit.setLocale('en-US');
```

### gromit.fullDateTimeFormat

Format the full date and time.

**Code example**

```
var now = new Date().getTime();
console.log(gromit.fullDateTimeFormat(now));
```

**Result**

```
Wednesday, November 15, 2017 9:45 AM
```

### gromit.fullDateFormat

Format the full date.

**Code example**

```
var now = new Date().getTime();
console.log(gromit.fullDateFormat(now));
```

**Result**

```
Wednesday, November 15, 2017
```

### gromit.shortDateFormat

Format the short date.

**Code example**

```
var now = new Date().getTime();
console.log(gromit.shortDateFormat(now));
```

**Result**

```
11/15/2017
```

### gromit.shortDateTimeFormat

Format the short date and time.

**Code example**

```
var now = new Date().getTime();
console.log(gromit.shortDateTimeFormat(now));
```

**Result**

```
11/15/2017 9:45 AM
```

### gromit.fromNowFormat

Produce a string indicating the general timeframe between now and the specified date.

**Code example**

```
var newYears2016 = 1451606400000;
console.log(gromit.fromNowFormat(newYears2016));
```

**Result**

```
2 years ago
```

## Gromit options

Gromit also has the following options:

### gromit.addCSS

By default Gromit will add CSS supporting the Gromit UI features.  To disable this option set the `addCSS` property to `false` like this:

```
gromit.addCSS = false;
```

This must be set before calling the `gromit.init` function.

## Setting up the Gromit build environment

You don't need to build Gromit to use it, but setting the build is fast and easy.  Having the build running also gives you the chance to get a working example of Gromit up and running quickly.

Gromit builds with [Gradle](http://gradle.org/gradle-download/).  Download the latest and add it to your path.  I like to create an alias for the `gradle` command like this:

alias gr='~/bin/gradle-4.1/bin/gradle'

Gromit also uses JSHint for JavaScript checking.  You must install JSHint to run the build.  JSHint depends on Node.js so the first step is to [install Node.js](http://nodejs.org/download/).

Once you've installed Node.js you can run this command to install JSHint:

npm install jshint -g

Verify your setup by running the two following commands:

gradle -version
jshint -version

Get the Gromit source code:

git clone https://github.com/Gromit-Soft/gromit.git
git clone https://github.com/Gromit-Soft/gromit-sample.git

## Building Gromit

Gromit is made up of two projects:  the Gromit core (just called Gromit) and the Gromit sample application which contains documentation and a running sample of Gromit.  Start by building the Gromit core:

cd gromit
gradle

This build will create the Gromit core artifact and install it in your local Maven cache.

The Gromit sample application contains an embedded server so you can easily run the application.  You can start it like this:

cd gromit-sample
gradle

At this point your Gromit sample server will be running on [your local server](http://localhost:8081) on port 8081.  You can use this configuration to make live changes to the sample code.

## Verifying the gromit-sample build

If you are changing the Gromit code then you must run and extra step.  Make your change with the Gradle server running and do whatever testing you need to.

Once your change is complete you must run JSHint and verify the build.  You must run this command before you commit your changes to gromit-sample.

gradle clean war


text:
class CEntity
{
protected:
	unsigned int mID;
	std::unordered_map<std::string, CComponent*> mComponents;
public:
	CEntity(unsigned int);
	unsigned int getID();
	void addComponent(CComponent &c);
	void removeComponent(std::string);
	bool componentQuery(std::string);

	CComponent* getComponentAddress(std::string);
};

#endif ENTITY_H_


text:
package org.gradle.internal.build;

import org.gradle.api.Task;
import org.gradle.api.internal.GradleInternal;
import org.gradle.api.internal.SettingsInternal;
import org.gradle.execution.plan.BuildWorkPlan;
import org.gradle.execution.plan.Node;

import javax.annotation.Nullable;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * Controls the lifecycle of an individual build in the build tree.
 */
public interface BuildLifecycleController {
    /**
     * Returns the current state of the mutable model for this build.
     *
     * Note: You should avoid using this method, as no thread safety or lifecycling is applied to the return value.
     */
    GradleInternal getGradle();

    /**
     * Configures the settings for this build, if not already available.
     * Can be called multiple times.
     */
    void loadSettings();

    /**
     * Runs the given action against the loaded settings for this build.
     * This may fail with an error, if this build is loaded from cache rather than configured.
     *
     * @return The loaded settings instance.
     */
    <T> T withSettings(Function<? super SettingsInternal, T> action);

    /**
     * Configures the projects of the build, if not already done.
     * Can be called multiple times.
     */
    void configureProjects();

    /**
     * Runs the given action against the mutable state of this build after configuring the projects of the build.
     * This may fail with an error, if this build is loaded from cache rather than configured.
     *
     * @return The configured Gradle build instance.
     */
    <T> T withProjectsConfigured(Function<? super GradleInternal, T> action);

    /**
     * Configures the build, if not already done.
     * This may fail with an error, if this build is loaded from cache rather than configured.
     *
     * Note: You should not use this method as no thread safety is applied to the return value.
     *
     * @return The configured Gradle build instance.
     */
    GradleInternal getConfiguredBuild();

    /**
     * Prepares this build to schedule tasks. May configure the build, if required to later schedule the requested tasks. Can be called multiple times.
     */
    void prepareToScheduleTasks();

    /**
     * Creates a new work plan for this build.
     * Must call {@link #prepareToScheduleTasks()} prior to calling this method. This method can be called multiple times to create multiple plans.
     */
    BuildWorkPlan newWorkGraph();

    /**
     * Populates the given work plan with tasks and work from this build.
     */
    void populateWorkGraph(BuildWorkPlan plan, Consumer<? super WorkGraphBuilder> action);

    /**
     * Finalizes the work graph after it has not been populated.
     */
    void finalizeWorkGraph(BuildWorkPlan plan);

    /**
     * Executes the given work for this build. Does not automatically configure the build or schedule any tasks.
     * Must call {@link #finalizeWorkGraph(BuildWorkPlan)} prior to calling this method.
     */
    ExecutionResult<Void> executeTasks(BuildWorkPlan plan);

    /**
     * Runs an action against the tooling model creators of this build. May configure the build as required.
     */
    <T> T withToolingModels(Function<? super BuildToolingModelController, T> action);

    /**
     * Calls the `buildFinished` hooks and other user code clean up.
     * Failures to finish the build are passed to the given consumer rather than thrown.
     *
     * @param failure The build failure that should be reported to the buildFinished hooks. When null, this launcher may use whatever failure it has already collected.
     * @return a result containing any failures that happen while finishing the build.
     */
    ExecutionResult<Void> finishBuild(@Nullable Throwable failure);

    /**
     * <p>Adds a listener to this build instance. Receives events for this build only.
     */
    void addListener(Object listener);

    interface WorkGraphBuilder {
        /**
         * Adds requested tasks, as defined in the {@link org.gradle.StartParameter}, and their dependencies to the work graph for this build.
         */
        void addRequestedTasks();

        /**
         * Adds the given tasks and their dependencies to the work graph for this build.
         */
        void addEntryTasks(List<? extends Task> tasks);

        /**
         * Adds the given nodes to the work graph for this build.
         */
        void addNodes(List<? extends Node> nodes);
    }
}


text:
package org.bdgenomics.rice.cli

import java.io.File
import org.apache.spark.{ Logging, SparkContext }
import org.apache.spark.rdd.MetricsContext._
import org.bdgenomics.adam.rdd.ADAMContext._
import org.bdgenomics.adam.util.{ TwoBitFile, ReferenceFile }
import org.bdgenomics.rice.Timers._
import org.bdgenomics.rice.algorithms.{ Index => Indexer }
import org.bdgenomics.rice.avro._
import org.bdgenomics.utils.cli._
import org.bdgenomics.utils.io.{ LocalFileByteAccess }
import org.kohsuke.args4j.{ Argument, Option => Args4jOption }

object Index extends BDGCommandCompanion {
  val commandName = "index"
  val commandDescription = "Build an index from a description of transcripts and a reference genome"

  def apply(cmdLine: Array[String]) = {
    new Index(Args4j[IndexArgs](cmdLine))
  }
}

class IndexArgs extends Args4jBase {
  @Argument(required = true, metaVar = "GENOME", usage = "The reference genome to index.", index = 0)
  var genome: String = null

  @Argument(required = true, metaVar = "GENES", usage = "The gene description file to use.", index = 1)
  var genes: String = null

  @Argument(required = true, metaVar = "KMER_LENGTH", usage = "The k-mer length to use for indexing.", index = 2)
  var kmerLength: Int = 0

  @Argument(required = true, metaVar = "OUTPUT", usage = "The location to write the index to.", index = 3)
  var output: String = null
}

class Index(protected val args: IndexArgs) extends BDGSparkCommand[IndexArgs] with Logging {
  val companion = Index

  def run(sc: SparkContext) {
    // load genome
    val genome = LoadingTwoBit.time {
      new TwoBitFile(new LocalFileByteAccess(new File(args.genome)))
    }

    // load gene annotations and transform to transcripts
    val transcripts = LoadingGenes.time {
      sc.loadGenes(args.genes)
        .flatMap(_.transcripts)
        .instrument()
    }

    // run indexing
    val (kmerMap, classMap) = Indexing.time {
      Indexer(genome, transcripts, args.kmerLength)
    }

    // map to avro classes and save indices
    SavingKmers.time {
      kmerMap.map(kv => {
        KmerToClass.newBuilder()
          .setKmer(kv._1)
          .setEquivalenceClass(kv._2)
          .build()
      }).adamParquetSave(args.output + "_kmers")
    }

    SavingClasses.time {
      classMap.map(kv => {
        ClassContents.newBuilder()
          .setEquivalenceClass(kv._1)
          .setKmers(kv._2.toList)
          .build()
      }).adamParquetSave(args.output + "_classes")
    }
  }
}


text:
class ChangeMeetings < ActiveRecord::Migration[5.0]
  def change
    remove_column(:meetings, :status)
    remove_column(:meetings, :room)
    add_column(:meetings, :status, :integer, default: 0)
    add_column(:meetings, :room, :integer, default: 0)
  end
end


text:
<!doctype html>

<meta charset="utf-8">
<title>安卓离线文档 – My Stupid Blog</title>
<meta name="description" content="Custom written post descriptions are the way to go... if you're not lazy.">
<meta name="keywords" content="android, xmpp, IM">

<meta name="twitter:title" content="安卓离线文档">
<meta name="twitter:description" content="Custom written post descriptions are the way to go... if you're not lazy.">
<meta name="twitter:site" content="@chenhuazhaoao">
<meta name="twitter:creator" content="@chenhuazhaoao">

<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="/images/site-logo.png">

<meta property="og:locale" content="en_US">
<meta property="og:type" content="article">
<meta property="og:title" content="安卓离线文档">
<meta property="og:description" content="Custom written post descriptions are the way to go... if you're not lazy.">
<meta property="og:url" content="/android/offlineDocs/">
<meta property="og:site_name" content="My Stupid Blog">

<link rel="canonical" href="/android/offlineDocs/">
<link href="/feed.xml" type="application/atom+xml" rel="alternate" title="My Stupid Blog Feed">

<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<link rel="stylesheet" href="/assets/css/main.css">

<meta http-equiv="cleartype" content="on">

<link rel="shortcut icon" href="/favicon.ico">

<link rel="shortcut icon" href="/favicon.png">

<link rel="apple-touch-icon-precomposed" href="/images/apple-touch-icon-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="72x72" href="/images/apple-touch-icon-72x72-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="114x114" href="/images/apple-touch-icon-114x114-precomposed.png">

<link rel="apple-touch-icon-precomposed" sizes="144x144" href="/images/apple-touch-icon-144x144-precomposed.png">

Home

JS

Java

Android

Git

Python

Tools

ReadingNotes

Reflection

About

 Search

    <input type="text" class="search-field" placeholder="Search...">
    <button class="close-btn"></button>

My Stupid Blog

安卓离线文档

首先,在SDK目录下的doc就是离线的开发文档,但是其中有些语句依然访问挽留过,所以略卡,用一下代码可以让该文档离线访问变快。只需在代码中指定你的SDK路径。

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

public class AndroidDoc {

    private static final String ANDROID_SDK_HOME = "ANDROID_SDK_HOME";
    private static final String TAG = "<script src=\"http://www.google.com/jsapi\" type=\"text/javascript\"></script>";
    private static String androidSDKHome;

    public static void main(String[] args) {
        Map<String, String> map = System.getenv();
        androidSDKHome = "E:/android/androidsdk/android-sdk_r23.0.5-windows/android-sdk-windows";
        if (androidSDKHome != null) {
            System.out.println("Detected the Android SDK Installation path:"
                    + androidSDKHome);
            File docs = new File(androidSDKHome + "\\docs");
            System.out.println("It will take several minutes, please wait...");
            traverse(docs);
            System.out
                    .println("Operation Down!!! Now you can visit Android Doc without waiting...");
        } else {
            System.out
                    .println("Please configure the Android SDK Environment variable (ANDROID_SDK_HOME)!");
        }
    }

    /**
     * 遍历Android SDK安装目录下的docs目录
     *
     * @param dir
     */
    private static void traverse(File dir) {
        if (dir.isDirectory()) {
            File[] files = dir.listFiles(new FileFilter() {

                @Override
                public boolean accept(File file) {
                    if (file.isFile() && file.getName().endsWith(".html")) {
                        BufferedReader reader = null;
                        try {
                            reader = new BufferedReader(new FileReader(file));
                            String buffer;
                            while ((buffer = reader.readLine()) != null) {
                                if (buffer.trim().equalsIgnoreCase(TAG)) {
                                    return true;
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            try {
                                reader.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    } else if (file.isDirectory()) {
                        return true;
                    }
                    return false;
                }
            });
            for (File file : files) {
                if (file.isDirectory()) {
                    System.out.println("Scanning Folder:"
                            + file.getAbsolutePath());
                    traverse(file);
                } else {
                    doChange(file);
                }
            }
        }
    }

    /**
     * 注释html中的某行Javascript代码
     *
     * @param file
     * @return
     */
    private static boolean doChange(File file) {
        System.out.println("Extracting File:" + file.getAbsolutePath() + "...");
        String desPath = file.getParent() + "\\" + UUID.randomUUID().toString() + ".html";
        File des = new File(desPath);
        BufferedReader reader = null;
        BufferedWriter writer = null;
        try {
            des.createNewFile();
            reader = new BufferedReader(new FileReader(file));
            writer = new BufferedWriter(new FileWriter(des));
            String buffer;
            while ((buffer = reader.readLine()) != null) {
                if (buffer.trim().equalsIgnoreCase(TAG)) {
                    buffer = "<!--" + TAG + "-->";
                }
                writer.write(buffer + "\n");
                writer.flush();
            }
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
                writer.close();
                file.delete();
                des.renameTo(file);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

}

            Previous

            Next

-© 2016 Quinn Chen. Powered by Jekyll


text:
using System.Collections.Generic;
using System.Linq;

namespace Generator.Misc.Lua {
	sealed class DocComments {
		public readonly List<DocCommentSection> Sections = new();

		public void AddText(TextDocCommentSection text) {
			if (text.Lines.Length == 0)
				return;
			if (text.Lines.Length == 1 && text.Lines[0] == string.Empty)
				return;
			Sections.Add(text);
		}
	}

	abstract class DocCommentSection {
	}

	sealed class TextDocCommentSection : DocCommentSection {
		public readonly string[] Lines;

		public TextDocCommentSection(string[] lines) {
			int i;
			for (i = lines.Length - 1; i >= 0; i--) {
				if (!string.IsNullOrEmpty(lines[i]))
					break;
			}
			if (i + 1 != lines.Length)
				lines = lines.Take(i).ToArray();
			Lines = lines;
		}
	}

	sealed class LuaType {
		public readonly string[] Types;
		public LuaType(params string[] types) => Types = types;
    }

	sealed class LuaParamAnnot {
		public readonly string Name;
		public readonly LuaType Type;
		public readonly string Comment;
		public readonly bool IsOptional;
		public LuaParamAnnot(string name, LuaType type, string comment, bool isOptional) {
			Name = name;
			Type = type;
			Comment = comment;
			IsOptional = isOptional;
		}
    }

	sealed class LuaReturnAnnot {
		public readonly LuaType[] Types;
		public readonly string? Comment;
		public LuaReturnAnnot(string? comment, params LuaType[] types) {
			Types = types;
			Comment = comment;
		}
    }

	sealed class LuaClassAnnot {
		public readonly LuaType Type;
		public LuaClassAnnot(LuaType type) => Type = type;
    }

	sealed class LuaOverloadAnnot {
		public readonly string Function;
		public LuaOverloadAnnot(string function) => Function = function;
    }

	sealed class LuaAnnotationDocCommentSection : DocCommentSection {
		public readonly LuaParamAnnot[] Params;
		public readonly LuaReturnAnnot? Return;
		public readonly LuaOverloadAnnot[] Overloads;
		public readonly LuaClassAnnot? Class;
		public LuaAnnotationDocCommentSection(LuaClassAnnot? @class, LuaReturnAnnot? @return, LuaOverloadAnnot[] overloads, LuaParamAnnot[] @params) {
			Params = @params;
			Return = @return;
			Overloads = overloads;
			Class = @class;
		}
    }

	sealed class TestCodeDocCommentSection : DocCommentSection {
		public readonly string[] Lines;
		public TestCodeDocCommentSection(string[] lines) => Lines = lines;
    }

	readonly struct LuaMethodArg {
		public readonly string Name;
		public readonly string RustType;
		public readonly bool IsSelf;

		public LuaMethodArg(string name, string rustType, bool isSelf) {
			Name = name;
			RustType = rustType;
			IsSelf = isSelf;
		}
	}

	enum LuaMethodKind {
		Method,
		Function,
		Constructor,
	}

	sealed class LuaMethod {
		public readonly LuaMethodKind Kind;
		public readonly string Name;
		public readonly DocComments DocComments;
		public readonly uint ReturnValueCount;
		public readonly LuaMethodArg[] Args;

		public LuaMethod(LuaMethodKind kind, string name, DocComments docComments, uint returnValueCount, LuaMethodArg[] args) {
			Kind = kind;
			Name = name;
			DocComments = docComments;
			ReturnValueCount = returnValueCount;
			Args = args;
		}
	}

	readonly struct LuaModulePath {
		public readonly string[] Names;
		public LuaModulePath(string[] names) => Names = names;
	}

	sealed class LuaClass {
		public readonly string Name;
		public readonly LuaModulePath ModulePath;
		public readonly DocComments DocComments;
		public readonly LuaMethod[] Methods;
        public LuaClass(string name, LuaModulePath modulePath, DocComments docComments, LuaMethod[] methods) {
			Name = name;
			ModulePath = modulePath;
			DocComments = docComments;
			Methods = methods;
		}
    }
}


text:
//using System;
//using System.Collections.Generic;
//using System.Text;

//using Data;

//namespace Analysis
//{
//    /// <summary>
//    /// This class  takes the average of a number of TOF curves. It keeps track of
//    /// the mean and standard error for each point on the TOF. It keeps a running average
//    /// and variance, so adding a TOF does not increase the memory usage.
//    /// </summary>
//    public class TOFAccumulator : IAccumulator<TOFWithError>
//    {
//        private RunningStatistics[] stats;
//        private int gateStartTime;
//        private int clockPeriod;
//        private double calibration;
//        private bool initialised = false;

//        // Note well that the incoming errors are ignored by the accumulator. The reason it
//        // doesn't take a simple TOF is to keep the code structure more uniform (in
//        // particular it allows this class to implement IAccumulator).
//        public void Add(TOFWithError t)
//        {
//            if (!initialised)
//            {
//                // the first TOF to be added defines the parameters
//                gateStartTime = t.GateStartTime;
//                clockPeriod = t.ClockPeriod;
//                calibration = t.Calibration;
//                stats = new RunningStatistics[t.Length];
//                for (int i = 0; i < Length; i++) stats[i] = new RunningStatistics();
//                initialised = true;
//            }

//            // add the TOF data - very minimal error checking: just check the lengths
//            if (t.Length == Length) for (int i = 0; i < Length; i++) stats[i].Push(t.Data[i]);
//            else throw new TOFAccumulatorException();
//        }

//        public TOFWithError GetResult()
//        {
//                TOFWithError temp =  new TOFWithError();
//                temp.Calibration = calibration;
//                temp.ClockPeriod = clockPeriod;
//                temp.GateStartTime = gateStartTime;
//                temp.Data = Data;
//                temp.Errors = Errors;
//                return temp;
//        }

//        private int Length
//        {
//            get
//            {
//                return stats.Length;
//            }
//        }

//        private double[] Data
//        {
//            get
//            {
//                double[] temp = new double[Length];
//                for (int i = 0; i < Length; i++) temp[i] = stats[i].Mean;
//                return temp;
//            }
//        }

//        private double[] Errors
//        {
//            get
//            {
//                double[] temp = new double[Length];
//                for (int i = 0; i < Length; i++) temp[i] = stats[i].StandardErrorOfSampleMean;
//                return temp;
//            }
//        }

//        public class TOFAccumulatorException : Exception {};

//    }
//}