text:
WITH moved_rows AS ( DELETE FROM config_file RETURNING * ) INSERT INTO config_file_his SELECT * FROM moved_rows;

##将某天的记录由历史库插入到当前库
INSERT INTO config_file SELECT * FROM config_file_his where substring(store_path, 1,6)='150129';
INSERT INTO ot_level2 SELECT * FROM ot_level2_his where date_str='151218';
INSERT INTO ot_observe_record SELECT * FROM ot_observe_record_his where date_str='151218';
INSERT INTO fits_file_cut SELECT * FROM fits_file_cut_his where substring(store_path, 1,6)='151218';

##统计模板切图表中,某天切图未返回的数量
select dpm_id, count(ot_id) from fits_file_cut_ref where length(file_name)=21 and substring(store_path, 1, 6)='150129' group by dpm_id order by dpm_id;

##按照日期统计当天的一级OT数量
select date_str, count(oor_id) from ot_observe_record_his group by date_str order by count desc;

##按照出现次数统计出现该次数的OT的个数
select total, count(*) from ot_level2 where data_produce_method='8' group by total order by total asc;

##统计每天OT的个数
select date_str, count(*) total from ot_level2_his where data_produce_method='8' group by date_str order by total desc;

##统计OT的匹配个数
select ot_id, count(*) total from ot_level2_match group by ot_id order by total desc;

##删除有历史备份表的当前表的数据
delete from config_file;
delete from fits_file_cut;
delete from ot_observe_record;
delete from ot_level2;
delete from var_star_record;
delete from image_status_parameter;
update data_process_machine set first_record_number=0, cur_process_number=0;
##删除时注意
delete from upload_file_unstore;
delete from upload_file_record;

##删除历史表中某一条的记录
delete from config_file_his where substring(store_path, 1,6)='141224';
delete from ot_level2_his where date_str='141224';
delete from ot_observe_record_his where date_str='141224';
delete from fits_file_cut_his where substring(store_path, 1,6)='141224';

##归档
WITH moved_rows AS ( DELETE FROM ot_level2 RETURNING * ) INSERT INTO ot_level2_his SELECT * FROM moved_rows;
WITH moved_rows AS ( DELETE FROM fits_file_cut RETURNING * ) INSERT INTO fits_file_cut_his SELECT * FROM moved_rows;
WITH moved_rows AS ( DELETE FROM ot_observe_record RETURNING * ) INSERT INTO ot_observe_record_his SELECT * FROM moved_rows;
WITH moved_rows AS ( DELETE FROM config_file RETURNING * ) INSERT INTO config_file_his SELECT * FROM moved_rows;
WITH moved_rows AS ( DELETE FROM image_status_parameter RETURNING * ) INSERT INTO image_status_parameter_his SELECT * FROM moved_rows;
update data_process_machine set first_record_number=0, cur_process_number=0;
delete from upload_file_unstore;

##多表条件更新
update fits_file_cut
set ot_id=ot_observe_record.ot_id
from ot_observe_record
where ot_observe_record.ffc_id=fits_file_cut.ffc_id and ot_observe_record.ot_id=79737;

update ot_level2
set mag=ot_observe_record.mag_aper
from ot_observe_record
where ot_observe_record.ot_id=ot_level2.ot_id and ot_observe_record.ff_number=ot_level2.last_ff_number;

##计算ot2与匹配上usno的星等差
select ot.name, ot.mag, olm.mag, ot.mag-olm.mag
from ot_level2 ot
inner join ot_level2_match olm on olm.ot_id=ot.ot_id
where ot.usno_match=1 and olm.mag!=0 and abs(ot.mag-olm.mag)>1;

##upload_file_unstore去掉存储路径后面的/
update upload_file_unstore set store_path=substring(store_path, 0, 24) where file_type='9';

##按望远镜、图像编号统计一级OT的个数
select dpm_id, ff_number, count(ff_number) number from ot_observe_record group by dpm_id, ff_number order by number desc limit 20;

##对OT后随记录中多个目标用同一个fr_obj_id的数量进行统计排序
select fo_id, fu_serial_number, fr_obj_id, count(fr_id) count from follow_up_record group by fo_id, fu_serial_number, fr_obj_id order by count desc limit 20;
select fo_id, fu_serial_number, fr_obj_id, count(fr_id) count from follow_up_record where ot_type='MINIOT' group by fo_id, fu_serial_number, fr_obj_id order by count desc limit 20;
select f1.fu_serial_number, f1.fr_obj_id, count(f1.fr_id) num
from follow_up_record f1
inner join follow_up_record f2 USING(fr_id)
where f1.fo_id=331
group by f1.fu_serial_number, f1.fr_obj_id
order by f1.fu_serial_number, f1.fr_obj_id , num desc
HAVING count(f2.fr_id)=1
limit 20;

##miniGWAC中OT2与USNO库在不同匹配半径时不同星等的匹配成功与失败数量曲线
select DISTINCT ot_type from follow_up_record;

(select 71 mag, count(*) from ot_level2_120 where mag>6.8 and mag<8 and usno_match=0)
union
(select 72 mag, count(*) from ot_level2_120 where mag>6.8 and mag<8 and usno_match>0)
union
(select 81 mag, count(*) from ot_level2_120 where mag>=8 and mag<9 and usno_match=0)
union
(select 82 mag, count(*) from ot_level2_120 where mag>=8 and mag<9 and usno_match>0)
union
(select 91 mag, count(*) from ot_level2_120 where mag>=9 and mag<10 and usno_match=0)
union
(select 92 mag, count(*) from ot_level2_120 where mag>=9 and mag<10 and usno_match>0)
union
(select 101 mag, count(*) from ot_level2_120 where mag>=10 and mag<11 and usno_match=0)
union
(select 102 mag, count(*) from ot_level2_120 where mag>=10 and mag<11 and usno_match>0)
union
(select 111 mag, count(*) from ot_level2_120 where mag>=11 and mag<12 and usno_match=0)
union
(select 112 mag, count(*) from ot_level2_120 where mag>=11 and mag<12 and usno_match>0)
union
(select 121 mag, count(*) from ot_level2_120 where mag>=12 and mag<12.5 and usno_match=0)
union
(select 122 mag, count(*) from ot_level2_120 where mag>=12 and mag<12.5 and usno_match>0)
order by mag;

SELECT
	ot2. NAME,
	ot2.mag,
	ot2m.mag,
	ot2m.distance
FROM
	ot_level2 ot2
INNER JOIN ot_level2_match ot2m ON ot2m.ot_id = ot2.ot_id AND ot2m.mag<12
WHERE
	ot2.is_match = 2;

#找出所有为空场的ot2的切图文件名
SELECT ot2.name ot_name, ffc.file_name
FROM fits_file_cut ffc
INNER JOIN ot_level2 ot2 ON ot2.ot_id=ffc.ot_id AND ot2.ot_type=17
ORDER BY ot2.name, ffc.file_name;


text:
import mock
from nose.tools import *  # noqa

from framework.auth.core import Auth
from framework.exceptions import PermissionsError

from tests.base import OsfTestCase
from tests.factories import UserFactory, ProjectFactory
from website.addons.mendeley.tests.factories import (
    MendeleyAccountFactory,
    MendeleyUserSettingsFactory,
    ExternalAccountFactory,
)
from website.addons.mendeley.provider import MendeleyCitationsProvider

import datetime

from website.addons.mendeley import model

class MockFolder(object):

    @property
    def name(self):
        return 'somename'

    @property
    def json(self):
        return {'id': 'abc123', 'parent_id': 'cba321'}

class MendeleyProviderTestCase(OsfTestCase):

    def setUp(self):
        super(MendeleyProviderTestCase, self).setUp()
        self.provider = model.Mendeley()

    @mock.patch('website.addons.mendeley.model.Mendeley._get_client')
    def test_handle_callback(self, mock_get_client):
        # Must return provider_id and display_name
        mock_client = mock.Mock()
        mock_client.profiles.me = mock.Mock(id='testid', display_name='testdisplay')
        mock_get_client.return_value = mock_client
        res = self.provider.handle_callback('testresponse')
        mock_get_client.assert_called_with('testresponse')
        assert_equal(res.get('provider_id'), 'testid')
        assert_equal(res.get('display_name'), 'testdisplay')

    @mock.patch('website.addons.mendeley.model.Mendeley._get_client')
    def test_client_not_cached(self, mock_get_client):
        # The first call to .client returns a new client
        mock_account = mock.Mock()
        mock_account.expires_at = datetime.datetime.now()
        self.provider.account = mock_account
        self.provider.client
        mock_get_client.assert_called
        assert_true(mock_get_client.called)

    @mock.patch('website.addons.mendeley.model.Mendeley._get_client')
    def test_client_cached(self, mock_get_client):
        # Repeated calls to .client returns the same client
        self.provider._client = mock.Mock()
        res = self.provider.client
        assert_equal(res, self.provider._client)
        assert_false(mock_get_client.called)

    def test_citation_lists(self):
        mock_client = mock.Mock()
        mock_folders = [MockFolder()]
        mock_list = mock.Mock()
        mock_list.items = mock_folders
        mock_client.folders.list.return_value = mock_list
        self.provider._client = mock_client
        mock_account = mock.Mock()
        self.provider.account = mock_account
        res = self.provider.citation_lists(MendeleyCitationsProvider()._extract_folder)
        assert_equal(res[1]['name'], mock_folders[0].name)
        assert_equal(res[1]['id'], mock_folders[0].json['id'])

class MendeleyNodeSettingsTestCase(OsfTestCase):

    def setUp(self):
        super(MendeleyNodeSettingsTestCase, self).setUp()
        self.node = ProjectFactory()
        self.node_settings = model.MendeleyNodeSettings(owner=self.node)
        self.node_settings.save()
        self.user = self.node.creator
        self.user_settings = self.user.get_or_add_addon('mendeley')

    def tearDown(self):
        super(MendeleyNodeSettingsTestCase, self).tearDown()
        self.user_settings.remove()
        self.node_settings.remove()
        self.node.remove()
        self.user.remove()

    @mock.patch('website.addons.mendeley.model.Mendeley')
    def test_api_not_cached(self, mock_mendeley):
        # The first call to .api returns a new object
        api = self.node_settings.api
        mock_mendeley.assert_called_once()
        assert_equal(api, mock_mendeley())

    @mock.patch('website.addons.mendeley.model.Mendeley')
    def test_api_cached(self, mock_mendeley):
        # Repeated calls to .api returns the same object
        self.node_settings._api = 'testapi'
        api = self.node_settings.api
        assert_false(mock_mendeley.called)
        assert_equal(api, 'testapi')

    def test_set_auth(self):
        external_account = ExternalAccountFactory()
        self.user.external_accounts.append(external_account)
        self.user.save()

        # this should be reset after the call
        self.node_settings.mendeley_list_id = 'anything'

        self.node_settings.set_auth(
            external_account=external_account,
            user=self.user
        )

        # this instance is updated
        assert_equal(
            self.node_settings.external_account,
            external_account
        )
        assert_equal(
            self.node_settings.user_settings,
            self.user_settings
        )
        assert_is_none(
            self.node_settings.mendeley_list_id
        )

        # user_settings was updated
        # TODO: The call to grant_oauth_access in set_auth should be mocked
        assert_true(
            self.user_settings.verify_oauth_access(
                node=self.node,
                external_account=external_account,
            )
        )

    def test_set_auth_wrong_user(self):
        external_account = ExternalAccountFactory()
        self.user.external_accounts.append(external_account)
        self.user.save()

        with assert_raises(PermissionsError):
            self.node_settings.set_auth(
                external_account=external_account,
                user=UserFactory()
            )

    def test_clear_auth(self):
        self.node_settings.external_account = ExternalAccountFactory()
        self.node_settings.mendeley_list_id = 'something'
        self.node_settings.user_settings = self.user_settings
        self.node_settings.save()

        self.node_settings.clear_auth()

        assert_is_none(self.node_settings.external_account)
        assert_is_none(self.node_settings.mendeley_list_id)
        assert_is_none(self.node_settings.user_settings)

    def test_set_target_folder(self):
        folder_id = 'fake-folder-id'
        folder_name = 'fake-folder-name'

        external_account = ExternalAccountFactory()
        self.user.external_accounts.append(external_account)
        self.user.save()

        self.node_settings.set_auth(
            external_account=external_account,
            user=self.user,
        )

        assert_is_none(self.node_settings.mendeley_list_id)

        self.node_settings.set_target_folder(
            folder_id,
            folder_name,
            auth=Auth(user=self.user),
        )

        # instance was updated
        assert_equal(
            self.node_settings.mendeley_list_id,
            'fake-folder-id',
        )

        # user_settings was updated
        # TODO: the call to grant_oauth_access should be mocked
        assert_true(
            self.user_settings.verify_oauth_access(
                node=self.node,
                external_account=external_account,
                metadata={'folder': 'fake-folder-id'}
            )
        )

        log = self.node.logs[-1]
        assert_equal(log.action, 'mendeley_folder_selected')
        assert_equal(log.params['folder_id'], folder_id)
        assert_equal(log.params['folder_name'], folder_name)

    def test_has_auth_false(self):
        external_account = ExternalAccountFactory()

        assert_false(self.node_settings.has_auth)

        # both external_account and user_settings must be set to have auth
        self.node_settings.external_account = external_account
        assert_false(self.node_settings.has_auth)

        self.node_settings.external_account = None
        self.node_settings.user_settings = self.user_settings
        assert_false(self.node_settings.has_auth)

        # set_auth must be called to have auth
        self.node_settings.external_account = external_account
        self.node_settings.user_settings = self.user_settings
        assert_false(self.node_settings.has_auth)

    def test_has_auth_true(self):
        external_account = ExternalAccountFactory()
        self.user.external_accounts.append(external_account)

        self.node_settings.set_auth(external_account, self.user)

        # mendeley_list_id should have no effect
        self.node_settings.mendeley_list_id = None
        assert_true(self.node_settings.has_auth)

        # mendeley_list_id should have no effect
        self.node_settings.mendeley_list_id = 'totally fake ID'
        assert_true(self.node_settings.has_auth)

    def test_selected_folder_name_root(self):
        self.node_settings.mendeley_list_id = 'ROOT'

        assert_equal(
            self.node_settings.selected_folder_name,
            "All Documents"
        )

    def test_selected_folder_name_empty(self):
        self.node_settings.mendeley_list_id = None

        assert_equal(
            self.node_settings.selected_folder_name,
            ''
        )

    @mock.patch('website.addons.mendeley.model.Mendeley._folder_metadata')
    def test_selected_folder_name(self, mock_folder_metadata):
        # Mock the return from api call to get the folder's name
        mock_folder = mock.Mock()
        mock_folder.name = 'Fake Folder'

        # Add the mocked return object to the mocked api client
        mock_folder_metadata.return_value = mock_folder

        self.node_settings.mendeley_list_id = 'fake-list-id'

        assert_equal(
            self.node_settings.selected_folder_name,
            'Fake Folder'
        )

    # TODO: Make these tests generic and move to core

    @mock.patch('framework.status.push_status_message')
    def test_remove_contributor_authorizer(self, mock_push_status):
        external_account = ExternalAccountFactory()
        self.user.external_accounts.append(external_account)
        self.node_settings.set_auth(external_account, self.user)

        contributor = UserFactory()
        self.node.add_contributor(contributor)
        self.node.remove_contributor(self.node.creator, auth=Auth(user=contributor))

        assert_false(self.node_settings.has_auth)
        assert_false(self.user_settings.verify_oauth_access(self.node, external_account))

    def test_remove_contributor_not_authorizer(self):
        external_account = ExternalAccountFactory()
        self.user.external_accounts.append(external_account)
        self.node_settings.set_auth(external_account, self.user)

        contributor = UserFactory()
        self.node.add_contributor(contributor)
        self.node.remove_contributor(contributor, auth=Auth(user=self.node.creator))

        assert_true(self.node_settings.has_auth)
        assert_true(self.user_settings.verify_oauth_access(self.node, external_account))

    @mock.patch('framework.status.push_status_message')
    def test_fork_by_authorizer(self, mock_push_status):
        external_account = ExternalAccountFactory()
        self.user.external_accounts.append(external_account)
        self.node_settings.set_auth(external_account, self.user)

        fork = self.node.fork_node(auth=Auth(user=self.node.creator))

        assert_true(fork.get_addon('mendeley').has_auth)
        assert_true(self.user_settings.verify_oauth_access(fork, external_account))

    @mock.patch('framework.status.push_status_message')
    def test_fork_not_by_authorizer(self, mock_push_status):
        external_account = ExternalAccountFactory()
        self.user.external_accounts.append(external_account)
        self.node_settings.set_auth(external_account, self.user)

        contributor = UserFactory()
        self.node.add_contributor(contributor)
        fork = self.node.fork_node(auth=Auth(user=contributor))

        assert_false(fork.get_addon('mendeley').has_auth)
        assert_false(self.user_settings.verify_oauth_access(fork, external_account))

class MendeleyUserSettingsTestCase(OsfTestCase):

    def _prep_oauth_case(self):
        self.node = ProjectFactory()
        self.user = self.node.creator

        self.external_account = ExternalAccountFactory()

        self.user.external_accounts.append(self.external_account)
        self.user.save()

        self.user_settings = self.user.get_or_add_addon('mendeley')

    def test_grant_oauth_access_no_metadata(self):
        self._prep_oauth_case()

        self.user_settings.grant_oauth_access(
            node=self.node,
            external_account=self.external_account,
        )
        self.user_settings.save()

        assert_equal(
            self.user_settings.oauth_grants,
            {self.node._id: {self.external_account._id: {}}},
        )

    def test_grant_oauth_access_metadata(self):
        self._prep_oauth_case()

        self.user_settings.grant_oauth_access(
            node=self.node,
            external_account=self.external_account,
            metadata={'folder': 'fake_folder_id'}
        )
        self.user_settings.save()

        assert_equal(
            self.user_settings.oauth_grants,
            {
                self.node._id: {
                    self.external_account._id: {'folder': 'fake_folder_id'}
                },
            }
        )

    def test_verify_oauth_access_no_metadata(self):
        self._prep_oauth_case()

        self.user_settings.grant_oauth_access(
            node=self.node,
            external_account=self.external_account,
        )
        self.user_settings.save()

        assert_true(
            self.user_settings.verify_oauth_access(
                node=self.node,
                external_account=self.external_account
            )
        )

        assert_false(
            self.user_settings.verify_oauth_access(
                node=self.node,
                external_account=ExternalAccountFactory()
            )
        )

    def test_verify_oauth_access_metadata(self):
        self._prep_oauth_case()

        self.user_settings.grant_oauth_access(
            node=self.node,
            external_account=self.external_account,
            metadata={'folder': 'fake_folder_id'}
        )
        self.user_settings.save()

        assert_true(
            self.user_settings.verify_oauth_access(
                node=self.node,
                external_account=self.external_account,
                metadata={'folder': 'fake_folder_id'}
            )
        )

        assert_false(
            self.user_settings.verify_oauth_access(
                node=self.node,
                external_account=self.external_account,
                metadata={'folder': 'another_folder_id'}
            )
        )

redpajama_set_name: RedPajamaGithub


text:
/**
 *     This code was auto-generated by a Codezu.
 *
 *     Changes to this file may cause incorrect behavior and will be lost if
 *     the code is regenerated.
 */
package com.mozu.api.contracts.shippingruntime;

import java.util.List;
import org.joda.time.DateTime;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.joda.time.DateTime;
import com.mozu.api.contracts.shippingruntime.ProductSummary;
import com.mozu.api.contracts.shippingruntime.ItemMeasurements;

/**
 *	Properties of an item for which to calculate a shipping rate.
 */
@JsonIgnoreProperties(ignoreUnknown = true)
public class RateRequestItem implements Serializable
{
	// Default Serial Version UID
	private static final long serialVersionUID = 1L;

	/**
	 * Unique identifier of an item used to calculate or request a shipping rate.
	 */
	protected String itemId;

	public String getItemId() {
		return this.itemId;
	}

	public void setItemId(String itemId) {
		this.itemId = itemId;
	}

	/**
	 * The specified quantity of objects and items. This property is used for numerous object types including products, options, components within a product bundle, cart and order items, returned items, shipping line items, items in a digital product. and items associated with types and reservations.
	 */
	protected Integer quantity;

	public Integer getQuantity() {
		return this.quantity;
	}

	public void setQuantity(Integer quantity) {
		this.quantity = quantity;
	}

	/**
	 * If true, this item must ship separately from other items in a shipment.
	 */
	protected Boolean shipsByItself;

	public Boolean getShipsByItself() {
		return this.shipsByItself;
	}

	public void setShipsByItself(Boolean shipsByItself) {
		this.shipsByItself = shipsByItself;
	}

	/**
	 * Mozu.ShippingRuntime.Contracts.RateRequestItem data ApiTypeMember DOCUMENT_HERE
	 */
	protected com.fasterxml.jackson.databind.JsonNode data;

	public com.fasterxml.jackson.databind.JsonNode getData() {
		return this.data;
	}

	public void setData(com.fasterxml.jackson.databind.JsonNode data) {
		this.data = data;
	}

	/**
	 * If Product Summaries are populated, this information will be utilized in Product Rules (e.g. ProductCode eq "ABC" or (Weight.Unit eq "lbs" and Weight.Value ge 50)
	 */
	protected List<ProductSummary> productSummaries;
	public List<ProductSummary> getProductSummaries() {
		return this.productSummaries;
	}
	public void setProductSummaries(List<ProductSummary> productSummaries) {
		this.productSummaries = productSummaries;
	}

	/**
	 * Product specific dimensions used for shipping, used by product summary and rate request items.  The dimensions can differ between the two uses as a `RateRequestItem `package may contain one or more products.
	 */
	protected ItemMeasurements unitMeasurements;

	public ItemMeasurements getUnitMeasurements() {
		return this.unitMeasurements;
	}

	public void setUnitMeasurements(ItemMeasurements unitMeasurements) {
		this.unitMeasurements = unitMeasurements;
	}

}


text:
import mock

import shade
from shade.tests.unit import base
from shade.tests import fakes

domain_obj = fakes.FakeIdentityDomain(
    id='1',
    name='a-domain',
    description='A wonderful keystone domain',
    enabled=True,
)

class TestIdentityDomains(base.TestCase):

    def setUp(self):
        super(TestIdentityDomains, self).setUp()
        self.cloud = shade.operator_cloud()

    @mock.patch.object(shade.OpenStackCloud, 'keystone_client')
    def test_list_identity_domains(self, mock_keystone):
        self.cloud.list_identity_domains()
        self.assertTrue(mock_keystone.domains.list.called)

    @mock.patch.object(shade.OpenStackCloud, 'keystone_client')
    def test_get_identity_domain(self, mock_keystone):
        mock_keystone.domains.get.return_value = domain_obj
        domain = self.cloud.get_identity_domain(domain_id='1234')
        self.assertFalse(mock_keystone.domains.list.called)
        self.assertTrue(mock_keystone.domains.get.called)
        self.assertEqual(domain['name'], 'a-domain')


text:
@font-face {
  font-family: 'Open Sans';
  font-style: normal;
  font-weight: 400;
  src: url('OpenSansNormal400.woff') format('woff');
}


text:
package org.springframework.stereotype;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Indicates that an annotated class is a "Repository", originally defined by
 * Domain-Driven Design (Evans, 2003) as "a mechanism for encapsulating storage,
 * retrieval, and search behavior which emulates a collection of objects".
 *

 *
Teams implementing traditional Java EE patterns such as "Data Access Object"
 * may also apply this stereotype to DAO classes, though care should be taken to
 * understand the distinction between Data Access Object and DDD-style repositories
 * before doing so. This annotation is a general-purpose stereotype and individual teams
 * may narrow their semantics and use as appropriate.
 *

 *
A class thus annotated is eligible for Spring
 * to its role in the overall application architecture for the purpose of tooling,
 * aspects, etc.
 *

 *
As of Spring 2.5, this annotation also serves as a specialization of
 * {@link Component @Component}, allowing for implementation classes to be autodetected
 * through classpath scanning.
 *
 * @author Rod Johnson
 * @author Juergen Hoeller
 * @see Component
 * @see Service
 * @since 2.0
 */
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Repository {

    /**
     * The value may indicate a suggestion for a logical component name,
     * to be turned into a Spring bean in case of an autodetected component.
     *
     * @return the suggested component name, if any (or empty String otherwise)
     */
    String value() default "";

}


text:
package org.yu55.yagga.common.repository.annotate;

import static java.text.MessageFormat.format;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.yu55.yagga.common.model.annotate.AnnotateRequest;
import org.yu55.yagga.common.model.annotate.AnnotateResponse;
import org.yu55.yagga.common.repository.RepositoriesContainer;

@Component
public class AnnotateHandler {

    private RepositoriesContainer repositoriesContainer;

    @Autowired
    public AnnotateHandler(RepositoriesContainer repositoriesContainer) {
        this.repositoriesContainer = repositoriesContainer;
    }

    public AnnotateResponse annotate(AnnotateRequest annotateRequest) {
        return
                repositoriesContainer.getRepositoryByDirectoryName(annotateRequest.getRepository())
                        .map(repo -> repo.annotate(AnnotateParameters.fromRequest(annotateRequest)))
                        .orElseThrow(() -> new IllegalArgumentException(
                                format("Repository {0} not found", annotateRequest.getRepository())));
    }

}


text:
      <button class="navbar-toggle" type="button" data-toggle="collapse" data-target=".bs-navbar-collapse">
        Toggle navigation

      </button>
      Bootstrap Validator

          View on GitHub


text:
import PlayerWrapper from './player-wrapper.js';
import AdUi from './ad-ui.js';
import SdkImpl from './sdk-impl.js';

 /**
  * The grand coordinator of the plugin. Facilitates communication between all
  * other plugin classes.
  *
  * @param {Object} player Instance of the video.js player.
  * @param {Object} options Options provided by the implementation.
  * @constructor
  * @struct
  * @final
  */
const Controller = function(player, options) {
  /**
   * Stores user-provided settings.
   * @type {Object}
   */
  this.settings = {};

  /**
   * Content and ads ended listeners passed by the publisher to the plugin.
   * These will be called when the plugin detects that content *and all
   * ads* have completed. This differs from the contentEndedListeners in that
   * contentEndedListeners will fire between content ending and a post-roll
   * playing, whereas the contentAndAdsEndedListeners will fire after the
   * post-roll completes.
   */
  this.contentAndAdsEndedListeners = [];

  /**
   * Whether or not we are running on a mobile platform.
   */
  this.isMobile = (navigator.userAgent.match(/iPhone/i) ||
      navigator.userAgent.match(/iPad/i) ||
      navigator.userAgent.match(/Android/i));

  /**
   * Whether or not we are running on an iOS platform.
   */
  this.isIos = (navigator.userAgent.match(/iPhone/i) ||
      navigator.userAgent.match(/iPad/i));

  this.initWithSettings(options);

  /**
   * Stores contrib-ads default settings.
   */
  const contribAdsDefaults = {
    debug: this.settings.debug,
    timeout: this.settings.timeout,
    prerollTimeout: this.settings.prerollTimeout,
  };
  const adsPluginSettings = this.extend(
      {}, contribAdsDefaults, options.contribAdsSettings || {});

  this.playerWrapper = new PlayerWrapper(player, adsPluginSettings, this);
  this.adUi = new AdUi(this);
  this.sdkImpl = new SdkImpl(this);
};

Controller.IMA_DEFAULTS = {
  debug: false,
  timeout: 5000,
  prerollTimeout: 1000,
  adLabel: 'Advertisement',
  adLabelNofN: 'of',
  showControlsForJSAds: true,
};

/**
 * Extends the settings to include user-provided settings.
 *
 * @param {Object} options Options to be used in initialization.
 */
Controller.prototype.initWithSettings = function(options) {
  this.settings = this.extend({}, Controller.IMA_DEFAULTS, options || {});

  this.warnAboutDeprecatedSettings();

  // Default showing countdown timer to true.
  this.showCountdown = true;
  if (this.settings.showCountdown === false) {
    this.showCountdown = false;
  }
};

/**
 * Logs console warnings when deprecated settings are used.
 */
Controller.prototype.warnAboutDeprecatedSettings = function() {
  const deprecatedSettings = [
    'adWillAutoplay',
    'adsWillAutoplay',
    'adWillPlayMuted',
    'adsWillPlayMuted',
  ];
  deprecatedSettings.forEach((setting) => {
    if (this.settings[setting] !== undefined) {
      console.warn(
        'WARNING: videojs.ima setting ' + setting + ' is deprecated');
    }
  });
};

/**
 * Return the settings object.
 *
 * @return {Object} The settings object.
 */
Controller.prototype.getSettings = function() {
  return this.settings;
};

/**
 * Return whether or not we're in a mobile environment.
 *
 * @return {boolean} True if running on mobile, false otherwise.
 */
Controller.prototype.getIsMobile = function() {
  return this.isMobile;
};

/**
 * Return whether or not we're in an iOS environment.
 *
 * @return {boolean} True if running on iOS, false otherwise.
 */
Controller.prototype.getIsIos = function() {
  return this.isIos;
};

/**
 * Inject the ad container div into the DOM.
 *
 * @param{HTMLElement} adContainerDiv The ad container div.
 */
Controller.prototype.injectAdContainerDiv = function(adContainerDiv) {
  this.playerWrapper.injectAdContainerDiv(adContainerDiv);
};

/**
 * @return {HTMLElement} The div for the ad container.
 */
Controller.prototype.getAdContainerDiv = function() {
  return this.adUi.getAdContainerDiv();
};

/**
 * @return {Object} The content player.
 */
Controller.prototype.getContentPlayer = function() {
  return this.playerWrapper.getContentPlayer();
};

/**
 * Returns the content playhead tracker.
 *
 * @return {Object} The content playhead tracker.
 */
Controller.prototype.getContentPlayheadTracker = function() {
  return this.playerWrapper.getContentPlayheadTracker();
};

/**
 * Requests ads.
 */
Controller.prototype.requestAds = function() {
  this.sdkImpl.requestAds();
};

/**
 * Add or modify a setting.
 *
 * @param {string} key Key to modify
 * @param {Object} value Value to set at key.
 */
Controller.prototype.setSetting = function(key, value) {
  this.settings[key] = value;
};

/**
 * Called when there is an error loading ads.
 *
 * @param {Object} adErrorEvent The ad error event thrown by the IMA SDK.
 */
Controller.prototype.onErrorLoadingAds = function(adErrorEvent) {
  this.adUi.onAdError();
  this.playerWrapper.onAdError(adErrorEvent);
};

/**
 * Called by the ad UI when the play/pause button is clicked.
 */
Controller.prototype.onAdPlayPauseClick = function() {
  if (this.sdkImpl.isAdPlaying()) {
    this.adUi.onAdsPaused();
    this.sdkImpl.pauseAds();
  } else {
    this.adUi.onAdsPlaying();
    this.sdkImpl.resumeAds();
  }
};

/**
 * Called by the ad UI when the mute button is clicked.
 *
 */
Controller.prototype.onAdMuteClick = function() {
  if (this.sdkImpl.isAdMuted()) {
    this.playerWrapper.unmute();
    this.adUi.unmute();
    this.sdkImpl.unmute();
  } else {
    this.playerWrapper.mute();
    this.adUi.mute();
    this.sdkImpl.mute();
  }
};

/**
 * Set the volume of the player and ads. 0-1.
 *
 * @param {number} volume The new volume.
 */
Controller.prototype.setVolume = function(volume) {
  this.playerWrapper.setVolume(volume);
  this.sdkImpl.setVolume(volume);
};

/**
 * @return {number} The volume of the content player.
 */
Controller.prototype.getPlayerVolume = function() {
  return this.playerWrapper.getVolume();
};

/**
 * Toggle fullscreen state.
 */
Controller.prototype.toggleFullscreen = function() {
  this.playerWrapper.toggleFullscreen();
};

/**
 * Relays ad errors to the player wrapper.
 *
 * @param {Object} adErrorEvent The ad error event thrown by the IMA SDK.
 */
Controller.prototype.onAdError = function(adErrorEvent) {
  this.adUi.onAdError();
  this.playerWrapper.onAdError(adErrorEvent);
};

/**
 * Handles ad break starting.
 *
 * @param {Object} adEvent The event fired by the IMA SDK.
 */
Controller.prototype.onAdBreakStart = function(adEvent) {
  this.playerWrapper.onAdBreakStart(adEvent);
  this.adUi.onAdBreakStart(adEvent);
};

/**
 * Show the ad container.
 */
Controller.prototype.showAdContainer = function() {
  this.adUi.showAdContainer();
};

/**
 * Handles ad break ending.
 */
Controller.prototype.onAdBreakEnd = function() {
  this.playerWrapper.onAdBreakEnd();
  this.adUi.onAdBreakEnd();
};

/**
 * Handles when all ads have finished playing.
 */
Controller.prototype.onAllAdsCompleted = function() {
  this.adUi.onAllAdsCompleted();
  this.playerWrapper.onAllAdsCompleted();
};

/**
 * Handles the SDK firing an ad paused event.
 */
Controller.prototype.onAdsPaused = function() {
  this.adUi.onAdsPaused();
};

/**
 * Handles the SDK firing an ad resumed event.
 */
Controller.prototype.onAdsResumed = function() {
  this.adUi.onAdsResumed();
};

/**
 * Takes data from the sdk impl and passes it to the ad UI to update the UI.
 *
 * @param {number} currentTime Current time of the ad.
 * @param {number} remainingTime Remaining time of the ad.
 * @param {number} duration Duration of the ad.
 * @param {number} adPosition Index of the ad in the pod.
 * @param {number} totalAds Total number of ads in the pod.
 */
Controller.prototype.onAdPlayheadUpdated =
    function(currentTime, remainingTime, duration, adPosition, totalAds) {
  this.adUi.updateAdUi(
      currentTime, remainingTime, duration, adPosition, totalAds);
};

/**
 * @return {Object} The current ad.
 */
Controller.prototype.getCurrentAd = function() {
  return this.sdkImpl.getCurrentAd();
};

/**
 * Play content.
 */
Controller.prototype.playContent = function() {
  this.playerWrapper.play();
};

/**
 * Handles when a linear ad starts.
 */
Controller.prototype.onLinearAdStart = function() {
  this.adUi.onLinearAdStart();
  this.playerWrapper.onAdStart();
};

/**
 * Handles when a non-linear ad loads.
 */
Controller.prototype.onNonLinearAdLoad = function() {
  this.adUi.onNonLinearAdLoad();
};

/**
 * Handles when a non-linear ad starts.
 */
Controller.prototype.onNonLinearAdStart = function() {
  this.adUi.onNonLinearAdLoad();
  this.playerWrapper.onAdStart();
};

/**
 * Get the player width.
 *
 * @return {number} The width of the player.
 */
Controller.prototype.getPlayerWidth = function() {
  return this.playerWrapper.getPlayerWidth();
};

/**
 * Get the player height.
 *
 * @return {number} The height of the player.
 */
Controller.prototype.getPlayerHeight = function() {
  return this.playerWrapper.getPlayerHeight();
};

/**
 * Tells the player wrapper that ads are ready.
 */
Controller.prototype.onAdsReady = function() {
  this.playerWrapper.onAdsReady();
};

/**
 * Called when the player wrapper detects that the player has been resized.
 *
 * @param {number} width The post-resize width of the player.
 * @param {number} height The post-resize height of the player.
 */
Controller.prototype.onPlayerResize = function(width, height) {
  this.sdkImpl.onPlayerResize(width, height);
};

/**
 * Called by the player wrapper when content completes.
 */
Controller.prototype.onContentComplete = function() {
  this.sdkImpl.onContentComplete();
};

/**
 * Called by the player wrapper when it's time to play a post-roll but we don't
 * have one to play.
 */
Controller.prototype.onNoPostroll = function() {
  this.playerWrapper.onNoPostroll();
};

/**
 * Called when content and all ads have completed.
 */
Controller.prototype.onContentAndAdsCompleted = function() {
  for (let index in this.contentAndAdsEndedListeners) {
    if (typeof this.contentAndAdsEndedListeners[index] === 'function') {
      this.contentAndAdsEndedListeners[index]();
    }
  }
};

/**
 * Called when the player is disposed.
 */
Controller.prototype.onPlayerDisposed = function() {
  this.contentAndAdsEndedListeners = [];
  this.sdkImpl.onPlayerDisposed();
};

/**
 * Called when the player is ready to play a pre-roll.
 */
Controller.prototype.onPlayerReadyForPreroll = function() {
  this.sdkImpl.onPlayerReadyForPreroll();
};

/**
 * Called when the player enters fullscreen.
 */
Controller.prototype.onPlayerEnterFullscreen = function() {
  this.adUi.onPlayerEnterFullscreen();
  this.sdkImpl.onPlayerEnterFullscreen();
};

/**
 * Called when the player exits fullscreen.
 */
Controller.prototype.onPlayerExitFullscreen = function() {
  this.adUi.onPlayerExitFullscreen();
  this.sdkImpl.onPlayerExitFullscreen();
};

/**
 * Called when the player volume changes.
 *
 * @param {number} volume The new player volume.
 */
Controller.prototype.onPlayerVolumeChanged = function(volume) {
  this.adUi.onPlayerVolumeChanged(volume);
  this.sdkImpl.onPlayerVolumeChanged(volume);
};

/**
 * Sets the content of the video player. You should use this method instead
 * of setting the content src directly to ensure the proper ad tag is
 * requested when the video content is loaded.
 * @param {?string} contentSrc The URI for the content to be played. Leave
 *     blank to use the existing content.
 * @param {?string} adTag The ad tag to be requested when the content loads.
 *     Leave blank to use the existing ad tag.
 * @param {?boolean} playOnLoad True to play the content once it has loaded,
 *     false to only load the content but not start playback.
 */
Controller.prototype.setContentWithAdTag =
    function(contentSrc, adTag, playOnLoad) {
  this.reset();
  this.settings.adTagUrl = adTag ? adTag : this.settings.adTagUrl;
  this.playerWrapper.changeSource(contentSrc, playOnLoad);
};

/**
 * Sets the content of the video player. You should use this method instead
 * of setting the content src directly to ensure the proper ads response is
 * used when the video content is loaded.
 * @param {?string} contentSrc The URI for the content to be played. Leave
 *     blank to use the existing content.
 * @param {?string} adsResponse The ads response to be requested when the
 *     content loads. Leave blank to use the existing ads response.
 * @param {?boolean} playOnLoad True to play the content once it has loaded,
 *     false to only load the content but not start playback.
 */
Controller.prototype.setContentWithAdsResponse =
    function(contentSrc, adsResponse, playOnLoad) {
  this.reset();
  this.settings.adsResponse =
      adsResponse ? adsResponse : this.settings.adsResponse;
  this.playerWrapper.changeSource(contentSrc, playOnLoad);
};

/**
 * Resets the state of the plugin.
 */
Controller.prototype.reset = function() {
  this.sdkImpl.reset();
  this.playerWrapper.reset();
};

/**
 * Listener JSDoc for ESLint. This listener can be passed to
 * (add|remove)ContentEndedListener.
 * @callback listener
 */

/**
 * Adds a listener for the 'contentended' event of the video player. This should
 * be used instead of setting an 'contentended' listener directly to ensure that
 * the ima can do proper cleanup of the SDK before other event listeners are
 * called.
 * @param {listener} listener The listener to be called when content
 *     completes.
 */
Controller.prototype.addContentEndedListener = function(listener) {
  this.playerWrapper.addContentEndedListener(listener);
};

/**
 * Adds a listener that will be called when content and all ads have
 * finished playing.
 * @param {listener} listener The listener to be called when content and ads
 *     complete.
 */
Controller.prototype.addContentAndAdsEndedListener = function(listener) {
  this.contentAndAdsEndedListeners.push(listener);
};

/**
 * Sets the listener to be called to trigger manual ad break playback.
 * @param {listener} listener The listener to be called to trigger manual ad
 *     break playback.
 */
Controller.prototype.setAdBreakReadyListener = function(listener) {
  this.sdkImpl.setAdBreakReadyListener(listener);
};

/**
 * Changes the flag to show or hide the ad countdown timer.
 *
 * @param {boolean} showCountdownIn Show or hide the countdown timer.
 */
Controller.prototype.setShowCountdown = function(showCountdownIn) {
  this.adUi.setShowCountdown(showCountdownIn);
  this.showCountdown = showCountdownIn;
  this.countdownDiv.style.display = this.showCountdown ? 'block' : 'none';
};

/**
 * Initializes the AdDisplayContainer. On mobile, this must be done as a
 * result of user action.
 */
Controller.prototype.initializeAdDisplayContainer = function() {
  this.sdkImpl.initializeAdDisplayContainer();
};

/**
 * Called by publishers in manual ad break playback mode to start an ad
 * break.
 */
Controller.prototype.playAdBreak = function() {
  this.sdkImpl.playAdBreak();
};

/**
 * Callback JSDoc for ESLint. This callback can be passed to addEventListener.
 * @callback callback
 */

/**
 * Ads an EventListener to the AdsManager. For a list of available events,
 * see
 * https://developers.google.com/interactive-media-ads/docs/sdks/html5/v3/apis#ima.AdEvent.Type
 * @param {google.ima.AdEvent.Type} event The AdEvent.Type for which to
 *     listen.
 * @param {callback} callback The method to call when the event is fired.
 */
Controller.prototype.addEventListener = function(event, callback) {
  this.sdkImpl.addEventListener(event, callback);
};

/**
 * Returns the instance of the AdsManager.
 * @return {google.ima.AdsManager} The AdsManager being used by the plugin.
 */
Controller.prototype.getAdsManager = function() {
  return this.sdkImpl.getAdsManager();
};

/**
 * Returns the instance of the player id.
 * @return {string} The player id.
 */
Controller.prototype.getPlayerId = function() {
  return this.playerWrapper.getPlayerId();
};

/**
 * Changes the ad tag. You will need to call requestAds after this method
 * for the new ads to be requested.
 * @param {?string} adTag The ad tag to be requested the next time
 *     requestAds is called.
 */
Controller.prototype.changeAdTag = function(adTag) {
  this.reset();
  this.settings.adTagUrl = adTag;
};

/**
 * Pauses the ad.
 */
Controller.prototype.pauseAd = function() {
  this.adUi.onAdsPaused();
  this.sdkImpl.pauseAds();
};

/**
 * Resumes the ad.
 */
Controller.prototype.resumeAd = function() {
  this.adUi.onAdsPlaying();
  this.sdkImpl.resumeAds();
};

/**
 * @return {boolean} true if we expect that ads will autoplay. false otherwise.
 */
Controller.prototype.adsWillAutoplay = function() {
  if (this.settings.adsWillAutoplay !== undefined) {
    return this.settings.adsWillAutoplay;
  } else if (this.settings.adWillAutoplay !== undefined) {
    return this.settings.adWillAutoplay;
  } else {
    return !!this.playerWrapper.getPlayerOptions().autoplay;
  }
};

/**
 * @return {boolean} true if we expect that ads will autoplay. false otherwise.
 */
Controller.prototype.adsWillPlayMuted = function() {
  if (this.settings.adsWillPlayMuted !== undefined) {
    return this.settings.adsWillPlayMuted;
  } else if (this.settings.adWillPlayMuted !== undefined) {
    return this.settings.adWillPlayMuted;
  } else if (this.playerWrapper.getPlayerOptions().muted !== undefined) {
    return this.playerWrapper.getPlayerOptions().muted;
  } else {
    return this.playerWrapper.getVolume() == 0;
  }
};

/**
 * Extends an object to include the contents of objects at parameters 2 onward.
 *
 * @param {Object} obj The object onto which the subsequent objects' parameters
 *     will be extended. This object will be modified.
 * @param {...Object} var_args The objects whose properties are to be extended
 *     onto obj.
 * @return {Object} The extended object.
 */
Controller.prototype.extend = function(obj, ...args) {
  let arg;
  let index;
  let key;
  for (index = 0; index < args.length; index++) {
    arg = args[index];
    for (key in arg) {
      if (arg.hasOwnProperty(key)) {
        obj[key] = arg[key];
      }
    }
  }
  return obj;
};

export default Controller;


text:
var sys = require('sys');
var path = require('path');

var sprintf = require('sprintf');

var misc = require('util/misc');

var config = {
  shortDescription: 'Bash completion',
  longDescription: 'Bash completion',
  requiredArguments: [],
  optionalArguments: [],
  options: []
};

/*
 * Get a list of all the available commands.
 *
 * @param {CommandParser} commandParser CommandParser instance.
 * @return {Array} Array where the first member is an array with the global
 *                 commands and the second one is an array with normal commands.
 */
function getCommands(commandParser) {
  var command, completionIndex;
  var globalCommands, normalCommands;

  globalCommands = commandParser.getGlobalCommands();

  completionIndex = globalCommands.indexOf('completion');

  if (completionIndex !== -1) {
    globalCommands.splice(completionIndex, 1);
  }

  normalCommands = Object.keys(commandParser.getNormalCommands());
  return [globalCommands, normalCommands];
}

/*
 * Return available options for a given command.
 *
 * @param {String} command Command name.
 * @param {String} subCommand Sub command name (optional).
 * @param {CommandParser} commandParser CommandParser instance.
 *
 * @return {Object} Object with the following keys: requiredArguments, optional
 *                  arguments, options
 */
function getCommandOptions(command, subCommand, commandParser) {
  var commandsPath, modulePath, commandModule;

  commandsPath = commandParser._commandsPath;

  if (!subCommand) {
    commandModule = path.join(commandsPath, command);
  }
  else {
    commandModule = path.join(commandsPath, command, subCommand);
  }

  commandModule = require(commandModule);

  return {
    requiredArguments: commandModule.config.requiredArguments,
    optionalArguments: commandModule.config.optionalArguments,
    options: commandModule.config.options
  };
}

/*
 * Output the completion string to standard output.
 *
 * @param {Array/String} value Completion value.
 */
function outputCompletion(value) {
  var toOutput;

  if (!value || ((value instanceof Array) && value.length === 0)) {
    return;
  }

  if (value instanceof Array) {
    toOutput = value.join(' ');
  }
  else {
    toOutput = value;
  }

  sys.puts(toOutput);
}

/*
 * Remove all the option values from the input array.
 *
 * @param {Array} inputArray Program arguments excluding the script name.
 */
function filterInput(inputArray) {
  inputArray = inputArray.map(function(input) {
    if (input.indexOf('=') !== -1) {
      return input.substr(0, input.indexOf('='));
    }

    return input;
  });

  return inputArray;
}

/*
 * Remove options which are already used or not applicable to the current input.
 *
 * @param {Array} input Array of input arguments (anything after the command
 *                      and sub command name)
 * @param {String} currentInput User input which is being completed
 * @param {Object} options Option object.
 */
function filterCompletionOptions(input, currentInput, options) {
  var i, optionNames, optionsLen, optionName, optionNameAlt, aliasName, optionOptions;
  var availableOptions = [];

  optionNames = Object.keys(options);
  optionsLen = optionNames.length;

  for (i = 0; i < optionsLen; i++) {
    optionName = optionNames[i];
    optionOptions = options[optionName];
    aliasName = optionOptions.alias;

    if (optionOptions.action === 'store' || optionOptions.action === 'append') {
      optionNameAlt = optionName + '=';
    }
    else {
      optionNameAlt = null;
    }

    if ((misc.inArray(optionName, input) || misc.inArray(aliasName, input)) &&
        (optionOptions.action !== 'append')) {
      // Note: Commands with action 'append' can be used multiple times
      continue;
    }

    if (optionName.indexOf(currentInput) !== 0) {
      // No match.
      continue;
    }

    if (optionNameAlt) {
      optionName = optionNameAlt;
    }

    availableOptions.push(optionName);
  }

  return availableOptions;
}

/*
 * Return an object with available options for a given command.
 *
 * @param {Object} options Options object with the following keys: requiredArguments,
 *                         optionalArguments, options
 * @return {Object} Object where the key is the option name (e.g. '--app', '-a')
 *                  and the value is option with the following keys: names, action
 */
function formatCommandOptions(options) {
  var i, j, optionsLen, option, optionObject, names, namesLen, name, alias;
  var optionsObject = {};

  options = options.options;

  if (!options) {
    return optionsObject;
  }

  optionsLen = options.length;
  for (i = 0; i < optionsLen; i++) {
    option = options[i];
    names = option.names;

    namesLen = names.length;
    for (j = 0; j < namesLen; j++) {
      // Storing separate object for a command and command alias takes extra space,
      // but the overhead is neglecatable
      name = names[j];

      if (namesLen === 2) {
        alias = (names.indexOf(name) === 0) ? names[1] : names[0];
      }
      else {
        alias = null;
      }

      optionObject = { 'action': option.action, 'alias': alias };
      optionsObject[name] = optionObject;
    }
  }

  return optionsObject;
}

/*
 * Complete the options for a given input.
 *
 * @param {Array} input Array of input arguments (anything after the command
 *                      and sub-command name)
 * @param {Object} options Option object with the following keys: requiredArguments,
 *                         optionalArguments, options
 */
function completeOptions(input, options) {
  var option, currentInput, optionsArray, availableOptions;
  var inputFiltered, inputLen = input.length;

  if (inputLen === 0) {
    return;
  }

  inputFiltered = filterInput(input);

  // User input which is being completed (a.k.a. the last argument)
  currentInput = input[input.length - 1];

  if (currentInput.indexOf('-') !== 0) {
    // Nothing to complete
    return;
  }

  // @TODO: option-aware completion
  optionsArray = formatCommandOptions(options);
  availableOptions = filterCompletionOptions(inputFiltered, currentInput, optionsArray);
  outputCompletion(availableOptions);
}

/*
 * Remove commads which do not match the current input string.
 *
 * @param {String} currentInput Current input string.
 * @param {Array} commands Array containing the available commands.
 */
function filterCompletionCommands(currentInput, commands) {
  var i, commandsLen;
  var availableCommands = [];

  availableCommands = commands.filter(function(command) {
    if ((command.indexOf(currentInput) !== 0) || command === currentInput) {
      return false;
    }

    return true;
  });

  return availableCommands;
}

/*
 * Complete the command.
 *
 * @param {Array} argv Program arguments excluding the script name.
 * @param {CommandParser} commandParser Command parser instance.
 */
function complete(argv, commandParser) {
  var commands, globalCommands, normalCommands, allCommands, subCommands;
  var inGlobal, inNormal, command, subCommand;
  var currentInput, options, completion;

  commands = getCommands(commandParser);
  globalCommands = commands[0];
  normalCommands = commands[1];
  allCommands = globalCommands.concat(normalCommands);

  if (argv.length === 0 || (argv.length === 1 && argv[0] === '')) {
    // Output all the commands
    outputCompletion(allCommands);
    return;
  }

  if (argv.length === 1) {
    // Complete the command name
    completion = filterCompletionCommands(argv[0], allCommands);

    if (completion.length > 0) {
      outputCompletion(completion);
      return;
    }
  }

  if (argv.length >= 1) {
    // Complete command
    command = argv[0];
    inGlobal = misc.inArray(command, globalCommands);
    inNormal = misc.inArray(command, normalCommands);

    if (!inGlobal && !inNormal) {
      return;
    }

    if (inGlobal) {
      options = getCommandOptions(command, null, commandParser);
      completeOptions(argv.slice(1), options, commandParser);
      return;
    }

    if (inNormal) {
      // Complete sub-command names and options
      subCommand = argv[1];
      subCommands = commandParser._normalCommands[command];

      if (argv.length <= 2) {
        completion = filterCompletionCommands(argv[argv.length - 1], subCommands);

        if (completion.length > 0) {
          outputCompletion(completion);
          return;
        }
      }

      if (!misc.inArray(subCommand, subCommands)) {
        return;
      }

      options = getCommandOptions(command, subCommand, commandParser);
      completeOptions(argv.slice(2), options, commandParser);
      return;
    }
  }
}

function handleCommand(args, commandParser) {
  var argv = process.argv;

  if (argv.length > 0 && argv[0].indexOf('cast') !== -1) {
    argv.splice(0, 1);
  }

  complete(argv, commandParser);
}

exports.config = config;
exports.handleCommand = handleCommand;


text:
#pragma once

#include "dbmain.h"
#include "acgimaterial.h"

#pragma pack (push, 8)

class AcDbMaterial : public AcDbObject
{
public:
    ACDB_DECLARE_MEMBERS(AcDbMaterial);

    AcDbMaterial();
    virtual ~AcDbMaterial();

    // AcDbMaterial protocol
    //
    virtual Acad::ErrorStatus   setName (const ACHAR * pName);
    virtual const ACHAR *       name    (void) const;

    virtual Acad::ErrorStatus   setDescription(const ACHAR * pDescription);
    virtual const ACHAR *       description(void) const;

    virtual void setAmbient     (const AcGiMaterialColor & color);
    virtual void ambient        (AcGiMaterialColor & color) const;

    virtual void setDiffuse     (const AcGiMaterialColor & color,
                                 const AcGiMaterialMap & map);
    virtual void diffuse        (AcGiMaterialColor & color,
                                 AcGiMaterialMap & map) const;

    virtual void setSpecular    (const AcGiMaterialColor & color,
                                 const AcGiMaterialMap & map,
                                 double dGloss);
    virtual void specular       (AcGiMaterialColor & color,
                                 AcGiMaterialMap & map,
                                 double & dGloss) const;

    virtual void setReflection  (const AcGiMaterialMap & map);
    virtual void reflection     (AcGiMaterialMap & map) const;

    virtual void setOpacity     (double dPercentage,
                                 const AcGiMaterialMap & map);
    virtual void opacity        (double & dPercentage,
                                 AcGiMaterialMap & map) const;

    virtual void setBump        (const AcGiMaterialMap & map);
    virtual void bump           (AcGiMaterialMap & map) const;

    virtual void setRefraction  (double dIndex,
                                 const AcGiMaterialMap & map);
    virtual void refraction     (double & dIndex,
                                 AcGiMaterialMap & map) const;

    virtual double translucence() const;
    virtual Acad::ErrorStatus setTranslucence(double value);

    virtual double selfIllumination() const;
    virtual Acad::ErrorStatus setSelfIllumination(double value);

    virtual double reflectivity() const;
    virtual Acad::ErrorStatus setReflectivity(double value);

    virtual AcGiMaterialTraits::IlluminationModel illuminationModel() const;
    virtual Acad::ErrorStatus setIlluminationModel(AcGiMaterialTraits::IlluminationModel model);

    virtual AcGiMaterialTraits::ChannelFlags channelFlags() const;
    virtual Acad::ErrorStatus setChannelFlags(AcGiMaterialTraits::ChannelFlags value);

    virtual AcGiMaterialTraits::Mode mode() const;
    virtual Acad::ErrorStatus setMode(AcGiMaterialTraits::Mode value);

    // AcDbObject protocol
    //
    virtual Acad::ErrorStatus dwgInFields  (AcDbDwgFiler* pFiler);
    virtual Acad::ErrorStatus dwgOutFields (AcDbDwgFiler* pFiler) const;
    virtual Acad::ErrorStatus dxfInFields  (AcDbDxfFiler* pFiler);
    virtual Acad::ErrorStatus dxfOutFields (AcDbDxfFiler* pFiler) const;
    virtual AcGiDrawable*     drawable     (void);

    // AcDbMaterial protocol, new material properties for Spago
    double              colorBleedScale         () const;
    Acad::ErrorStatus   setColorBleedScale      (double value);

    double              indirectBumpScale       () const;
    Acad::ErrorStatus   setIndirectBumpScale    (double value);

    double              reflectanceScale        () const;
    Acad::ErrorStatus   setReflectanceScale     (double value);

    double              transmittanceScale      () const;
    Acad::ErrorStatus   setTransmittanceScale   (double value);

    Adesk::Boolean      twoSided                () const;
    Acad::ErrorStatus   setTwoSided             (Adesk::Boolean value);

    AcGiMaterialTraits::LuminanceMode luminanceMode () const;
    Acad::ErrorStatus   setLuminanceMode        (AcGiMaterialTraits::LuminanceMode value);

    double              luminance               () const;
    Acad::ErrorStatus   setLuminance            (double value);

    double              shininess               () const;
    Acad::ErrorStatus   setShininess            (double value);

    Acad::ErrorStatus   normalMap               (AcGiMaterialMap & map,
                                                 AcGiMaterialTraits::NormalMapMethod & method,
                                                 double & strength) const;
    Acad::ErrorStatus   setNormalMap            (const AcGiMaterialMap & map,
                                                 AcGiMaterialTraits::NormalMapMethod method,
                                                 double strength);

    Adesk::Boolean      isAnonymous             () const;
    Acad::ErrorStatus   setAnonymous            (Adesk::Boolean isAnonymous);

    AcGiMaterialTraits::GlobalIlluminationMode globalIllumination() const;
    void                setGlobalIllumination   (AcGiMaterialTraits::GlobalIlluminationMode mode);

    AcGiMaterialTraits::FinalGatherMode        finalGather() const;
    void                setFinalGather          (AcGiMaterialTraits::FinalGatherMode mode);

    bool                isRenamable             () const;

    // WARNING: Caller must **NOT** delete the returned pointer.
    //
#ifdef _ADESK_MAC_
     void* getAdskMaterialData();
#else
    void* getAdskMaterialData() const;
#endif

    // WARNING: If bCacheIt == true, then AcDbMaterial takes over responsibility for
    //          deleting pMatObj and caller must ensure that nothing else deletes it.
    //
    Acad::ErrorStatus setAdskMaterialData(const void* pMatObj, bool bCacheIt = false);

    void clearAdskMaterialCache();

    enum MaterialFlags {
        kNone               = 0,
        kIsLegacy           = 0x1,
        kIsModifiedIsValid  = 0x2,
        kIsModified         = 0x4,
        kIsModifiedAndValid = 0x6  // kIsModifiedIsValid | kIsModified
    };

    Acad::ErrorStatus getAdskMaterialFlags(MaterialFlags& flags) const;
    Acad::ErrorStatus setAdskMaterialFlags(MaterialFlags flags);

protected:
    virtual Acad::ErrorStatus subGetClassID(CLSID* pClsid) const;
};

#pragma pack (pop)


text:
package com.suscipio_solutions.consecro_mud.WebMacros;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Vector;

import com.suscipio_solutions.consecro_mud.Common.interfaces.Clan;
import com.suscipio_solutions.consecro_mud.Common.interfaces.Clan.Authority;
import com.suscipio_solutions.consecro_mud.Common.interfaces.ClanGovernment;
import com.suscipio_solutions.consecro_mud.Common.interfaces.ClanPosition;
import com.suscipio_solutions.consecro_mud.core.CMClass;
import com.suscipio_solutions.consecro_mud.core.CMLib;
import com.suscipio_solutions.consecro_mud.core.CMath;
import com.suscipio_solutions.consecro_web.interfaces.HTTPRequest;

public class ClanGovernmentData extends StdWebMacro
{
	@Override public String name() { return "ClanGovernmentData"; }
	@Override
	public String runMacro(HTTPRequest httpReq, String parm)
	{
		final java.util.Map<String,String> parms=parseParms(parm);
		final String last=httpReq.getUrlParameter("GOVERNMENT");
		if(last==null) return " @break@";
		if(last.length()>0)
		{
			ClanGovernment G=null;
			if(CMath.isInteger(last))
			{
				final int lastID=CMath.s_int(last);
				G=CMLib.clans().getStockGovernment(lastID);
			}
			if(G==null)
			{
				final Set<Integer> usedTypeIDs=new HashSet<Integer>();
				for(final ClanGovernment G2 : CMLib.clans().getStockGovernments())
					usedTypeIDs.add(Integer.valueOf(G2.getID()));
				G=CMLib.clans().createSampleGovernment();
				G.setName(httpReq.getUrlParameter("NAME"));
				G.setCategory(httpReq.getUrlParameter("CATEGORY"));
				for(int i=0;i<CMLib.clans().getStockGovernments().length;i++)
					if(!usedTypeIDs.contains(Integer.valueOf(i)))
					{
						G.setID(i);
						break;
					}
			}
			final StringBuffer str=new StringBuffer("");

			// ******************************************************************************************
			// do govt positions FIRST!
			// ******************************************************************************************
			final List<ClanPosition> posList=new Vector<ClanPosition>();
			String posDexStr="0";
			int posDex=0;
			final Set<Integer> usedRoleIDs=new HashSet<Integer>();
			if(!httpReq.isUrlParameter("GPOSID_"+posDexStr))
			{
				for(final ClanPosition P : G.getPositions())
				{
					posList.add(P);
					usedRoleIDs.add(Integer.valueOf(P.getRoleID()));
				}
			}
			else
			while(httpReq.isUrlParameter("GPOSID_"+posDexStr) && httpReq.getUrlParameter("GPOSID_"+posDexStr).trim().length()>0)
			{
				final String oldID=httpReq.getUrlParameter("GPOSID_"+posDexStr);
				final String oldName=httpReq.getUrlParameter("GPOSNAME_"+posDexStr);
				final String oldPluralName=httpReq.getUrlParameter("GPOSPLURALNAME_"+posDexStr);
				final int oldRoleID=CMath.s_int(httpReq.getUrlParameter("GPOSROLEID_"+posDexStr));
				usedRoleIDs.add(Integer.valueOf(oldRoleID));
				final int oldRank=CMath.s_int(httpReq.getUrlParameter("GPOSRANK_"+posDexStr));
				final int oldMax=CMath.s_int(httpReq.getUrlParameter("GPOSMAX_"+posDexStr));
				final String oldMask=httpReq.getUrlParameter("GPOSINNERMASK_"+posDexStr);
				final String oldIsPublicStr=httpReq.getUrlParameter("GPOSISPUBLIC_"+posDexStr);
				final boolean oldIsPublic=oldIsPublicStr==null?false:oldIsPublicStr.equalsIgnoreCase("on");
				final Clan.Authority powerFuncs[]=new Clan.Authority[Clan.Function.values().length];
				for(int f=0;f<Clan.Function.values().length;f++)
					powerFuncs[f]=Clan.Authority.CAN_NOT_DO;
				String authDexStr="";
				int authDex=0;
				while(httpReq.getUrlParameter("GPOSPOWER_"+posDexStr+"_"+authDexStr)!=null)
				{
					final Clan.Function auth = (Clan.Function)CMath.s_valueOf(Clan.Function.values(),httpReq.getUrlParameter("GPOSPOWER_"+posDexStr+"_"+authDexStr));
					powerFuncs[auth.ordinal()]=Clan.Authority.CAN_DO;
					authDex++;
					authDexStr=Integer.toString(authDex);
				}
				final ClanPosition P=(ClanPosition)CMClass.getCommon("DefaultClanPosition");
				P.setID(oldID);
				P.setRoleID(oldRoleID);
				P.setRank(oldRank);
				P.setName(oldName);
				P.setPluralName(oldPluralName);
				P.setMax(oldMax);
				P.setInnerMaskStr(oldMask);
				P.setFunctionChart(powerFuncs);
				P.setPublic(oldIsPublic);
				posList.add(P);
				posDex++;
				posDexStr=Integer.toString(posDex);
			}

			final String cmpos=httpReq.getUrlParameter("GOVTPOSITION");
			ClanPosition gPos = null;
			if((cmpos!=null)&&(cmpos.length()>0)&&(CMath.s_int(cmpos)>=0)&&(CMath.s_int(cmpos)<posList.size()))
				gPos=posList.get(CMath.s_int(cmpos));

			if((gPos!=null)&&parms.containsKey("GPOSID_"+cmpos))
				str.append(gPos.getID()+", ");
			if((gPos!=null)&&parms.containsKey("GPOSROLEID_"+cmpos))
				str.append(gPos.getRoleID()+", ");
			if((gPos!=null)&&parms.containsKey("GPOSNAME_"+cmpos))
				str.append(gPos.getName()+", ");
			if((gPos!=null)&&parms.containsKey("GPOSPLURALNAME_"+cmpos))
				str.append(gPos.getPluralName()+", ");
			if((gPos!=null)&&parms.containsKey("GPOSRANK_"+cmpos))
				str.append(gPos.getRank()+", ");
			if((gPos!=null)&&parms.containsKey("GPOSMAX_"+cmpos))
				str.append(gPos.getMax()+", ");
			if((gPos!=null)&&parms.containsKey("GPOSINNERMASK_"+cmpos))
				str.append(gPos.getInnerMaskStr()+", ");
			if((gPos!=null)&&parms.containsKey("GPOSISPUBLIC_"+cmpos))
				str.append(gPos.isPublic()?"checked, ":"");
			if((gPos!=null)&&parms.containsKey("GPOSPOWER_"+cmpos+"_"))
			{
				for(final Clan.Function func : Clan.Function.values())
				{
					str.append("<OPTION VALUE=\""+func.toString()+"\"");
					if(gPos.getFunctionChart()[func.ordinal()]==Authority.CAN_DO)
						str.append(" SELECTED");
					str.append(">"+func.toString());
				}
			}
			if(parms.containsKey("GPOSPOWERLIST"))
				for(final Clan.Function func : Clan.Function.values())
					str.append("<OPTION VALUE=\""+func.toString()+"\">"+func.toString());

			if(parms.containsKey("NEXTPOSITIONID"))
			{
				for(int i=0;i<posList.size()+10;i++)
					if(!usedRoleIDs.contains(Integer.valueOf(i)))
					{
						str.append(i+", ");
						break;
					}
			}

			// iterators
				if(parms.containsKey("POSITIONSTART"))
				{
					if(httpReq.getUrlParameter("GOVTPOSITION")!=null)
						httpReq.removeUrlParameter("GOVTPOSITION");
					return "";
				}
				if(parms.containsKey("POSITIONNEXT"))
				{
					String lastPos="";
					for(int p=0;p<posList.size();p++)
					{
						if((cmpos==null)||((cmpos.length()>0)&&(cmpos.equals(lastPos))&&(!(""+p).equals(lastPos))))
						{
							httpReq.addFakeUrlParameter("GOVTPOSITION",(""+p));
							return "";
						}
						lastPos=(""+p);
					}
					httpReq.addFakeUrlParameter("LASTGOVTPOSITION",""+posList.size());
					httpReq.addFakeUrlParameter("GOVTPOSITION","");
					if(parms.containsKey("EMPTYOK"))
						return "<!--EMPTY-->";
					return " @break@";
				}

			if(parms.containsKey("NAME"))
			{
				String old=httpReq.getUrlParameter("NAME");
				if(old==null) old=G.getName();
				str.append(old+", ");
			}
			if(parms.containsKey("AUTOROLE"))
			{
				String old=httpReq.getUrlParameter("AUTOROLE");
				if(old==null) old=""+G.getAutoRole();
				final int autoPos=CMath.s_int(old);
				for(final ClanPosition pos : posList)
					str.append("<OPTION VALUE="+pos.getRoleID()+" "+((autoPos==pos.getRoleID())?"SELECTED":"")+">"+pos.getName());
			}
			if(parms.containsKey("ACCEPTPOS"))
			{
				String old=httpReq.getUrlParameter("ACCEPTPOS");
				if(old==null) old=""+G.getAcceptPos();
				final int autoPos=CMath.s_int(old);
				for(final ClanPosition pos : posList)
					str.append("<OPTION VALUE="+pos.getRoleID()+" "+((autoPos==pos.getRoleID())?"SELECTED":"")+">"+pos.getName());
			}
			if(parms.containsKey("SHORTDESC"))
			{
				String old=httpReq.getUrlParameter("SHORTDESC");
				if(old==null) old=G.getShortDesc();
				str.append(old+", ");
			}
			if(parms.containsKey("CATEGORY"))
			{
				String old=httpReq.getUrlParameter("CATEGORY");
				if(old==null) old=G.getCategory();
				str.append(old+", ");
			}
			if(parms.containsKey("REQUIREDMASK"))
			{
				String old=httpReq.getUrlParameter("REQUIREDMASK");
				if(old==null) old=G.getRequiredMaskStr();
				str.append(old+", ");
			}
			if(parms.containsKey("ENTRYSCRIPT"))
			{
				String old=httpReq.getUrlParameter("ENTRYSCRIPT");
				if(old==null) old=G.getEntryScript();
				str.append(old+", ");
			}
			if(parms.containsKey("EXITSCRIPT"))
			{
				String old=httpReq.getUrlParameter("EXITSCRIPT");
				if(old==null) old=G.getExitScript();
				str.append(old+", ");
			}
			if(parms.containsKey("ISPUBLIC"))
			{
				String old=httpReq.getUrlParameter("ISPUBLIC");
				if(old==null) old=G.isPublic()?"on":"";
				str.append(old.equalsIgnoreCase("on")?"checked, ":"");
			}
			if(parms.containsKey("ISDEFAULT"))
			{
				String old=httpReq.getUrlParameter("ISDEFAULT");
				if(old==null) old=G.isDefault()?"on":"";
				str.append(old.equalsIgnoreCase("on")?"checked, ":"");
			}
			if(parms.containsKey("ISFAMILYONLY"))
			{
				String old=httpReq.getUrlParameter("ISFAMILYONLY");
				if(old==null) old=G.isFamilyOnly()?"on":"";
				str.append(old.equalsIgnoreCase("on")?"checked, ":"");
			}
			if(parms.containsKey("OVERRIDEMINMEMBERS"))
			{
				String old=httpReq.getUrlParameter("OVERRIDEMINMEMBERS");
				if(old==null) old=G.getOverrideMinMembers()==null?"":G.getOverrideMinMembers().toString();
				str.append(old+", ");
			}
			if(parms.containsKey("CONQUESTENABLED"))
			{
				String old=httpReq.getUrlParameter("CONQUESTENABLED");
				if(old==null) old=G.isConquestEnabled()?"on":"";
				str.append(old.equalsIgnoreCase("on")?"checked, ":"");
			}
			if(parms.containsKey("CONQUESTITEMLOYALTY"))
			{
				String old=httpReq.getUrlParameter("CONQUESTITEMLOYALTY");
				if(old==null) old=G.isConquestItemLoyalty()?"on":"";
				str.append(old.equalsIgnoreCase("on")?"checked, ":"");
			}
			if(parms.containsKey("CONQUESTDEITYBASIS"))
			{
				String old=httpReq.getUrlParameter("CONQUESTDEITYBASIS");
				if(old==null) old=G.isConquestByWorship()?"on":"";
				str.append(old.equalsIgnoreCase("on")?"checked, ":"");
			}
			if(parms.containsKey("ISRIVALROUS"))
			{
				String old=httpReq.getUrlParameter("ISRIVALROUS");
				if(old==null) old=G.isRivalrous()?"on":"";
				str.append(old.equalsIgnoreCase("on")?"checked, ":"");
			}
			if(parms.containsKey("MAXVOTEDAYS"))
			{
				String old=httpReq.getUrlParameter("MAXVOTEDAYS");
				if(old==null) old=Integer.toString(G.getMaxVoteDays());
				str.append(CMath.s_int(old)+", ");
			}
			if(parms.containsKey("XPLEVELFORMULA"))
			{
				String old=httpReq.getUrlParameter("XPLEVELFORMULA");
				if(old==null) old=G.getXpCalculationFormulaStr();
				str.append(CMath.s_int(old)+", ");
			}
			if(parms.containsKey("VOTEQUORUMPCT"))
			{
				String old=httpReq.getUrlParameter("VOTEQUORUMPCT");
				if(old==null) old=Integer.toString(G.getVoteQuorumPct());
				str.append(CMath.s_int(old)+", ");
			}
			if(parms.containsKey("AUTOPROMOTEBY"))
			{
				String old=httpReq.getUrlParameter("AUTOPROMOTEBY");
				if(old==null) old=""+G.getAutoPromoteBy().toString();
				for(final Clan.AutoPromoteFlag flag : Clan.AutoPromoteFlag.values())
					str.append("<OPTION VALUE="+flag.toString()+" "+((old.equals(flag.toString()))?"SELECTED":"")+">"+flag.toString());
			}
			if(parms.containsKey("VOTEFUNCS"))
			{
				final String old=httpReq.getUrlParameter("VOTEFUNCS");
				final Set<String> voteFuncs=new HashSet<String>();
				if(old==null)
				{
					if(posList.size()>0)
					{
						final ClanPosition P=posList.get(0);
						for(final Clan.Function func : Clan.Function.values())
							if(P.getFunctionChart()[func.ordinal()]==Clan.Authority.MUST_VOTE_ON)
								voteFuncs.add(func.toString());
					}
				}
				else
				{
					voteFuncs.add(old);
					int x=1;
					while(httpReq.getUrlParameter("VOTEFUNCS"+x)!=null)
					{
						voteFuncs.add(httpReq.getUrlParameter("VOTEFUNCS"+x));
						x++;
					}
				}
				for(final Clan.Function func : Clan.Function.values())
				{
					str.append("<OPTION VALUE=\""+func.toString()+"\"");
					if(voteFuncs.contains(func.toString())) str.append(" SELECTED");
					str.append(">"+func.toString());
				}
			}
			if(parms.containsKey("LONGDESC"))
			{
				String old=httpReq.getUrlParameter("LONGDESC");
				if(old==null) old=G.getLongDesc();
				str.append(old+", ");
			}
			if(parms.containsKey("RABLE"))
			{
				str.append(RaceData.dynAbilities(G.getClanLevelAbilities(null,null,Integer.valueOf(Integer.MAX_VALUE)),G.getName(),G,httpReq,parms,1,parms.get("FONT"))+", ");
			}
			if(parms.containsKey("REFFS"))
				str.append(RaceData.dynEffects(G.getName(),G,httpReq,parms,1,parms.get("FONT"))+", ");

			String strstr=str.toString();
			if(strstr.endsWith(", "))
				strstr=strstr.substring(0,strstr.length()-2);
			return clearWebMacros(strstr);
		}
		return "";
	}
}


text:
Writing Assignment
==================

.. slug: writing-assignment
.. date: 2015-08-16 19:55:23 UTC-07:00
.. tags: grammar, assignment
.. category:
.. link:
.. description:
.. type: text

What is expected from this writing assignment?

300 page essay, which is referred to as blog post which uses the concepts mentioned in this course.

Rubric for Peer Assessment
--------------------------

* Content

Is this blog an imaginative, interesting and engaging post that relates to the point of grammar?

* Structure

Is this a cohesive, coherent post?

* Style

Does this post have a clever and appropriate use of words?

* Grammar

Does this post show an excellent command of grammar?

* Punctuation

Does this post have an excellent command of punctuation?

**Why I can write a sentence, but I can't tell you how I wrote it?**

	<I thought I knew how to use nouns, verbs and adjectives.

	>I thought I knew how to use nouns, verbs, and adjectives.

Oxford commas or serial commas are emphasized as part of this writing.

Grammatical knowledge is concerned with sentence formation, whereas grammatical
ability regards the complete text as the object of focus.

In the 1970s, it was thought that the tradional forms of intruction bored
students, stifled creativity, and, frankly, did not improve the quality of their
writing.

Question: What is meant by avoiding passive voice?

**Shall I compare a colon to a semicolon.**

One announces or introduces and the other links.


text:
"""
.. moduleauthor:: Jonas Berg

"""

__author__ = "Jonas Berg"
__license__ = "Apache License, Version 2.0"


text:
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ISBoxer EVE Launcher")]
[assembly: AssemblyDescription("An EVE Launcher for ISBoxer. Special thanks to open source EVE Launcher projects CliLauncher and IsBridgeUp, and users logical and HunterAlvi")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Lavish Software LLC")]
[assembly: AssemblyProduct("ISBoxer EVE Launcher")]
[assembly: AssemblyCopyright("Copyright © 2016-2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>.  For example, if you are using US english
//in your source files, set the <UICulture> to en-US.  Then uncomment
//the NeutralResourceLanguage attribute below.  Update the "en-US" in
//the line below to match the UICulture setting in the project file.

//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]

[assembly: ThemeInfo(
    ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
                                     //(used if a resource is not found in the page,
                                     // or application resource dictionaries)
    ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
                                              //(used if a resource is not found in the page,
                                              // app, or any theme specific resource dictionaries)
)]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.35")]
[assembly: AssemblyFileVersion("1.0.0.35")]


text:
name: DnsProvider
parameters:
  - name
  - nsCount
---

DnsProvider indicates that the specifid provider should be used to manage
records for this domain. The name must match the name used with [NewDnsProvider](#NewDnsProvider).

The nsCount parameter determines how the nameservers will be managed from this provider.

Leaving the parameter out means "fetch and use all nameservers from this provider as authoritative". ie: `DnsProvider("name")`

Using `0` for nsCount means "do not fetch nameservers from this domain, or give them to the registrar".

Using a different number, ie: `DnsProvider("name",2)`, means "fetch all nameservers from this provider,
but limit it to this many.

See [this page]({{site.github.url}}/nameservers) for a detailed explanation of how DNSControl handles nameservers and NS records.


text:
package voogasalad_GucciGames.helpers;

import java.util.List;

import javafx.scene.image.Image;
import javafx.scene.paint.Color;
import voogasalad.util.fxsprite.Sprite;

public interface GameResourceManagerToGAE {

	public List<String> getImages();

	public List<String> getImages(String directory);

	public List<String> listImageDirectories();

	public Image getImage(String URI);

	/**
	 * Returns the average color of the request image.
	 *
	 * @param URI
	 * @return
	 */
	public Color getImageColor(String URI);

	/**
	 * If set to true, copies all resources to the Game Directory on access.
	 * MUST BE SET IN GAE.
	 *
	 * @param copy
	 */
	public void toggleCopyOnAccess(boolean copy);

	public void changeGameName(String newName);

	/**
	 * Returns a sprite with the requested URI
	 *
	 * @param URI
	 * @return
	 */
	public Sprite getSprite(String URI);

	/**
	 * Returns a list of sprites available.
	 *
	 * @return
	 */
	public List<String> getSprites();

	/**
	 * Loads game into the resource manager
	 *
	 * @param gameName
	 */
	public void loadGame(String gameName);

	public void copySpriteToGame(String URI);

	public void copyImageToGame(String URI);

	// NOTE: ted will implement this if needed
	// public void copyImageToGame(String imagePath);
}


text:
module Azure::Network::Mgmt::V2020_05_01
  #
  # VpnSitesConfiguration
  #
  class VpnSitesConfiguration
    include MsRestAzure

    #
    # Creates and initializes a new instance of the VpnSitesConfiguration class.
    # @param client service class for accessing basic functionality.
    #
    def initialize(client)
      @client = client
    end

    # @return [NetworkManagementClient] reference to the NetworkManagementClient
    attr_reader :client

    #
    # Gives the sas-url to download the configurations for vpn-sites in a resource
    # group.
    #
    # @param resource_group_name [String] The resource group name.
    # @param virtual_wanname [String] The name of the VirtualWAN for which
    # configuration of all vpn-sites is needed.
    # @param request [GetVpnSitesConfigurationRequest] Parameters supplied to
    # download vpn-sites configuration.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    def download(resource_group_name, virtual_wanname, request, custom_headers:nil)
      response = download_async(resource_group_name, virtual_wanname, request, custom_headers:custom_headers).value!
      nil
    end

    #
    # @param resource_group_name [String] The resource group name.
    # @param virtual_wanname [String] The name of the VirtualWAN for which
    # configuration of all vpn-sites is needed.
    # @param request [GetVpnSitesConfigurationRequest] Parameters supplied to
    # download vpn-sites configuration.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [Concurrent::Promise] promise which provides async access to http
    # response.
    #
    def download_async(resource_group_name, virtual_wanname, request, custom_headers:nil)
      # Send request
      promise = begin_download_async(resource_group_name, virtual_wanname, request, custom_headers:custom_headers)

      promise = promise.then do |response|
        # Defining deserialization method.
        deserialize_method = lambda do |parsed_response|
        end

        # Waiting for response.
        @client.get_long_running_operation_result(response, deserialize_method, FinalStateVia::LOCATION)
      end

      promise
    end

    #
    # Gives the sas-url to download the configurations for vpn-sites in a resource
    # group.
    #
    # @param resource_group_name [String] The resource group name.
    # @param virtual_wanname [String] The name of the VirtualWAN for which
    # configuration of all vpn-sites is needed.
    # @param request [GetVpnSitesConfigurationRequest] Parameters supplied to
    # download vpn-sites configuration.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    #
    def begin_download(resource_group_name, virtual_wanname, request, custom_headers:nil)
      response = begin_download_async(resource_group_name, virtual_wanname, request, custom_headers:custom_headers).value!
      nil
    end

    #
    # Gives the sas-url to download the configurations for vpn-sites in a resource
    # group.
    #
    # @param resource_group_name [String] The resource group name.
    # @param virtual_wanname [String] The name of the VirtualWAN for which
    # configuration of all vpn-sites is needed.
    # @param request [GetVpnSitesConfigurationRequest] Parameters supplied to
    # download vpn-sites configuration.
    # @param custom_headers [Hash{String => String}] A hash of custom headers that
    # will be added to the HTTP request.
    #
    # @return [MsRestAzure::AzureOperationResponse] HTTP response information.
    #
    def begin_download_with_http_info(resource_group_name, virtual_wanname, request, custom_headers:nil)
      begin_download_async(resource_group_name, virtual_wanname, request, custom_headers:custom_headers).value!
    end

    #
    # Gives the sas-url to download the configurations for vpn-sites in a resource
    # group.
    #
    # @param resource_group_name [String] The resource group name.
    # @param virtual_wanname [String] The name of the VirtualWAN for which
    # configuration of all vpn-sites is needed.
    # @param request [GetVpnSitesConfigurationRequest] Parameters supplied to
    # download vpn-sites configuration.
    # @param [Hash{String => String}] A hash of custom headers that will be added
    # to the HTTP request.
    #
    # @return [Concurrent::Promise] Promise object which holds the HTTP response.
    #
    def begin_download_async(resource_group_name, virtual_wanname, request, custom_headers:nil)
      fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil?
      fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil?
      fail ArgumentError, 'virtual_wanname is nil' if virtual_wanname.nil?
      fail ArgumentError, 'request is nil' if request.nil?
      fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil?

      request_headers = {}
      request_headers['Content-Type'] = 'application/json; charset=utf-8'

      # Set Headers
      request_headers['x-ms-client-request-id'] = SecureRandom.uuid
      request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil?

      # Serialize Request
      request_mapper = Azure::Network::Mgmt::V2020_05_01::Models::GetVpnSitesConfigurationRequest.mapper()
      request_content = @client.serialize(request_mapper,  request)
      request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil

      path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualWans/{virtualWANName}/vpnConfiguration'

      request_url = @base_url || @client.base_url

      options = {
          middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]],
          path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'virtualWANName' => virtual_wanname},
          query_params: {'api-version' => @client.api_version},
          body: request_content,
          headers: request_headers.merge(custom_headers || {}),
          base_url: request_url
      }
      promise = @client.make_request_async(:post, path_template, options)

      promise = promise.then do |result|
        http_response = result.response
        status_code = http_response.status
        response_content = http_response.body
        unless status_code == 200 || status_code == 202
          error_model = JSON.load(response_content)
          fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model)
        end

        result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil?
        result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil?
        result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil?

        result
      end

      promise.execute
    end

  end
end