text:
"""
General repo metrics like provides general overview data about repositories, including things like lines of code change, licenses, stars, CII best practices badging, and more
"""

import datetime
import sqlalchemy as s
import pandas as pd
import math
import logging

from augur.util import register_metric

logger = logging.getLogger("augur")

@register_metric()
def code_changes(self, repo_group_id, repo_id=None, period='week', begin_date=None, end_date=None):
    """
    Returns a timeseries of the count of commits.

    :param repo_group_id: The repository's repo_group_id
    :param repo_id: The repository's repo_id, defaults to None
    :param period: To set the periodicity to 'day', 'week', 'month' or 'year', defaults to 'day'
    :param begin_date: Specifies the begin date, defaults to '1970-1-1 00:00:00'
    :param end_date: Specifies the end date, defaults to datetime.now()
    :return: DataFrame of commits/period
    """
    if not begin_date:
        begin_date = '1970-1-1 00:00:00'
    if not end_date:
        end_date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

    code_changes_SQL = ''

    if not repo_id:
        code_changes_SQL = s.sql.text("""
            SELECT
                repo_name,
                week,
                YEAR,
                SUM(patches) AS commit_count
            FROM dm_repo_weekly JOIN repo ON dm_repo_weekly.repo_id = repo.repo_id
            WHERE dm_repo_weekly.repo_id IN (SELECT repo_id FROM repo WHERE repo_group_id = :repo_group_id)
            GROUP BY repo_name, week, YEAR
            ORDER BY week
        """)

        results = pd.read_sql(code_changes_SQL, self.database, params={'repo_group_id': repo_group_id, 'period': period,
                                                                 'begin_date': begin_date, 'end_date': end_date})
        results['week'] = results['week'].apply(lambda x: x - 1)
        results['date'] = results['year'].astype(str) + ' ' + results['week'].astype(str) + ' 0'
        results['date'] = results['date'].apply(lambda x: datetime.datetime.strptime(x, "%Y %W %w"))
        results = results[(results['date'] >= begin_date) & (results['date'] <= end_date)]
        return results

    else:
        code_changes_SQL = s.sql.text("""
            SELECT
                repo_name,
                week,
                YEAR,
                SUM(patches) AS commit_count
            FROM dm_repo_weekly JOIN repo ON dm_repo_weekly.repo_id = repo.repo_id
            WHERE dm_repo_weekly.repo_id = :repo_id
            GROUP BY repo_name, week, YEAR
            ORDER BY week
        """)

        results = pd.read_sql(code_changes_SQL, self.database, params={'repo_id': repo_id, 'period': period,
                                                                 'begin_date': begin_date, 'end_date': end_date})

        results['week'] = results['week'].apply(lambda x: x - 1)
        results['date'] = results['year'].astype(str) + ' ' + results['week'].astype(str) + ' 0'
        results['date'] = results['date'].apply(lambda x: datetime.datetime.strptime(x, "%Y %W %w"))
        results = results[(results['date'] >= begin_date) & (results['date'] <= end_date)]
        return results

@register_metric()
def code_changes_lines(self, repo_group_id, repo_id=None, period='day', begin_date=None, end_date=None):
    """Returns a timeseries of code changes added and removed.

    :param repo_group_id: The repository's repo_group_id
    :param repo_id: The repository's repo_id, defaults to None
    :param period: To set the periodicity to 'day', 'week', 'month' or 'year', defaults to 'day'
    :param begin_date: Specifies the begin date, defaults to '1970-1-1 00:00:00'
    :param end_date: Specifies the end date, defaults to datetime.now()
    :return: DataFrame of code changes added and removed/period
    """
    if not begin_date:
        begin_date = '1970-1-1 00:00:00'
    if not end_date:
        end_date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

    code_changes_lines_SQL = ''

    if not repo_id:
        code_changes_lines_SQL = s.sql.text("""
            SELECT
                commits.repo_id,
                repo_name,
                date_trunc(:period, cmt_author_date::DATE) as date,
                SUM(cmt_added) as added,
                SUM(cmt_removed) as removed
            FROM commits JOIN repo ON commits.repo_id = repo.repo_id
            WHERE commits.repo_id IN (SELECT repo_id FROM repo WHERE repo_group_id = :repo_group_id)
            AND cmt_author_date BETWEEN :begin_date AND :end_date
            GROUP BY commits.repo_id, date, repo_name
            ORDER BY commits.repo_id, date
        """)

        results = pd.read_sql(code_changes_lines_SQL, self.database, params={'repo_group_id': repo_group_id, 'period': period,
                                                                       'begin_date': begin_date, 'end_date': end_date})

        return results

    else:
        code_changes_lines_SQL = s.sql.text("""
            SELECT
                repo_name,
                date_trunc(:period, cmt_author_date::DATE) as date,
                SUM(cmt_added) AS added,
                SUM(cmt_removed) as removed
            FROM commits JOIN repo ON commits.repo_id = repo.repo_id
            WHERE commits.repo_id = :repo_id
            AND cmt_author_date BETWEEN :begin_date AND :end_date
            GROUP BY date, repo_name
            ORDER BY date;
        """)

        results = pd.read_sql(code_changes_lines_SQL, self.database, params={'repo_id': repo_id, 'period': period,
                                                                       'begin_date': begin_date, 'end_date': end_date})
        return results

@register_metric()
def sub_projects(self, repo_group_id, repo_id=None, begin_date=None, end_date=None):
    """
    Returns number of sub-projects
    :param repo_id: The repository's id
    :param repo_group_id: The repository's group id
    :param begin_date: Specifies the begin date, defaults to '1970-1-1 00:00:00'
    :param end_date: Specifies the end date, defaults to datetime.now()
    """
    if not begin_date:
        begin_date = '1970-1-1 00:00:01'
    if not end_date:
        end_date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

    if repo_id:
        sub_projectsSQL = s.sql.text("""
            SELECT COUNT(*)  AS sub_project_count
            FROM repo
            WHERE repo_group_id = (
            SELECT repo_group_id
            FROM repo
            WHERE  repo_id = :repo_id)
            AND repo_added BETWEEN :begin_date AND :end_date
        """)

        results = pd.read_sql(sub_projectsSQL, self.database, params={'repo_id': repo_id,
                                                                'begin_date': begin_date, 'end_date': end_date})
    else:
        sub_projectsSQL = s.sql.text("""
            SELECT COUNT(*) AS sub_project_count
            FROM repo
            WHERE repo_group_id = :repo_group_id
            AND repo_added BETWEEN :begin_date AND :end_date
        """)

        results = pd.read_sql(sub_projectsSQL, self.database, params={'repo_group_id': repo_group_id,
                                                                'begin_date': begin_date, 'end_date': end_date})
    return results

@register_metric()
def sbom_download(self, repo_group_id, repo_id=None):
    """REQUIRES SBOMS TO BE PRESENT IN THE DATABASE

    :param repo_id: The repository's repo_id, defaults to None
    :return: dosocs sbom
    """
    dosocs_SQL = s.sql.text("""
        select * from augur_data.repo_sbom_scans
        where repo_id = :repo_id;
    """)

    logger.debug(dosocs_SQL)
    params = {'repo_id': repo_id}

    return pd.read_sql(dosocs_SQL, self.database, params=params)
    #return [json.dumps(license_information)]

@register_metric()
def cii_best_practices_badge(self, repo_group_id, repo_id=None):
    """Returns the CII best practices badge level

    :param repo_group_id: The repository's repo_group_id
    :param repo_id: The repository's repo_id, defaults to None
    :return: CII best parctices badge level
    """
    cii_best_practices_badge_SQL = s.sql.text("""
        SELECT data
        FROM augur_data.repo_badging
        WHERE repo_id = :repo_id
        ORDER BY created_at DESC
        LIMIT 1
    """)

    raw_df = pd.read_sql(cii_best_practices_badge_SQL, self.database, params={'repo_id': repo_id})

    badging_data = raw_df.iloc[0,0][0]

    result = {
        "repo_name": badging_data['name'],
    }

    for item in badging_data.items():
        if item[0] in ["badge_level", "achieve_passing_status", "achieve_silver_status", "tiered_percentage", "repo_url", "id"]:
            result[item[0]] = item[1]

    return pd.DataFrame(result, index=[0])

@register_metric()
def forks(self, repo_group_id, repo_id=None):
    """
    Returns a time series of the fork count

    :param repo_group_id: The repository's repo_group_id
    :param repo_id: The repository's repo_id, defaults to None
    :return: Time series of fork count
    """
    if not repo_id:
        forks_SQL = s.sql.text("""
            SELECT
                repo_info.repo_id,
                repo_name,
                repo_info.data_collection_date as date,
                fork_count AS forks
            FROM repo_info JOIN repo ON repo_info.repo_id = repo.repo_id
            WHERE repo_info.repo_id IN
                (SELECT repo_id FROM repo
                 WHERE  repo_group_id = :repo_group_id)
            ORDER BY repo_info.repo_id, date
        """)

        results = pd.read_sql(forks_SQL, self.database, params={'repo_group_id': repo_group_id})
        return results

    else:
        forks_SQL = s.sql.text("""
            SELECT
                repo_name,
                repo_info.data_collection_date as date,
                fork_count AS forks
            FROM repo_info JOIN repo ON repo_info.repo_id = repo.repo_id
            WHERE repo_info.repo_id = :repo_id
            ORDER BY date
        """)

        results = pd.read_sql(forks_SQL, self.database, params={'repo_id': repo_id})
        return results

@register_metric()
def fork_count(self, repo_group_id, repo_id=None):
    """
    Returns the latest fork count

    :param repo_group_id: The repository's repo_group_id
    :param repo_id: The repository's repo_id, defaults to None
    :return: Fork count
    """
    if not repo_id:
        fork_count_SQL = s.sql.text("""
            SELECT a.repo_id, repo_name, a.fork_count AS forks
            FROM repo_info a LEFT JOIN repo_info b
            ON (a.repo_id = b.repo_id AND a.repo_info_id < b.repo_info_id), repo
            WHERE b.repo_info_id IS NULL
            AND a.repo_id = repo.repo_id
            AND a.repo_id IN
                (SELECT repo_id FROM repo
                 WHERE  repo_group_id = :repo_group_id)
        """)

        results = pd.read_sql(fork_count_SQL, self.database, params={'repo_group_id': repo_group_id})
        return results
    else:
        fork_count_SQL = s.sql.text("""
            SELECT repo_name, fork_count AS forks
            FROM repo_info JOIN repo ON repo_info.repo_id = repo.repo_id
            WHERE repo_info.repo_id = :repo_id
            ORDER BY repo_info.data_collection_date DESC
            LIMIT 1
        """)

        results = pd.read_sql(fork_count_SQL, self.database, params={'repo_id': repo_id})
        return results

@register_metric()
def languages(self, repo_group_id, repo_id=None):
    """Returns the implementation languages

    :param repo_group_id: The repository's repo_group_id
    :param repo_id: The repository's repo_id, defaults to None
    :return: Implementation languages
    """
    if not repo_id:
        languages_SQL = s.sql.text("""
            SELECT repo_name, repo_id, primary_language
            FROM repo
            WHERE repo_id IN (SELECT repo_id FROM repo WHERE repo_group_id = :repo_group_id)
        """)

        results = pd.read_sql(languages_SQL, self.database, params={'repo_group_id': repo_group_id})
        return results

    else:
        languages_SQL = s.sql.text("""
            SELECT repo_name, primary_language
            FROM repo
            WHERE repo_id = :repo_id
        """)

        results = pd.read_sql(languages_SQL, self.database, params={'repo_id': repo_id})
        return results

@register_metric(type="license")
def license_files(self, license_id, spdx_binary, repo_group_id, repo_id=None,):
        """Returns the files related to a license

        :param repo_group_id: The repository's repo_group_id
        :param repo_id: The repository's repo_id, defaults to None
        :return: Declared License
        """
        license_data_SQL = None
        repo_id_SQL = None
        repo_name_list = None

        license_data_SQL = s.sql.text("""
        SELECT DISTINCT
            A.license_id as the_license_id,    b.short_name as short_name,    f.file_name
        FROM
            files_licenses A,    licenses b,    augur_repo_map C,    packages d,    files e,
            packages_files f
        WHERE
            A.license_id = b.license_id
            AND d.package_id = C.dosocs_pkg_id
            AND e.file_id = A.file_id
            AND e.package_id = d.package_id
            AND C.repo_id = :repo_id
            AND e.file_id = f.file_id
            AND b.is_spdx_official = :spdx_binary
            AND
                (
                b.license_id = :license_id
                OR
                b.license_id in ( 369,323,324,325,326,327,328,329,330,331,332,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,362,363,364,365,366,367,368,370,371,372,373,374,375,376,377,378,379,380,381,382,383,384,385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426,427,428,429,430,431,432,433,434,435,436,437,438,439,440,441,442,443,444,445,446,447,448,449,450,451,452,453,454,455,456,457,458,459,460,461,462,463,464,465,466,467,468,469,470,471,472,473,474,475,476,477,478,479,480,481,482));
                """)

        results = pd.read_sql(license_data_SQL, self.spdx_db, params={'repo_id': repo_id, 'spdx_binary': spdx_binary, 'license_id': license_id})
        return results

@register_metric()
def license_declared(self, repo_group_id, repo_id=None):
    """Returns the declared license

    :param repo_group_id: The repository's repo_group_id
    :param repo_id: The repository's repo_id, defaults to None
    :return: Declared License
    """
    license_declared_SQL = None
    repo_id_SQL = None
    repo_name_list = None

    license_declared_SQL = s.sql.text("""
    select the_license_id as license_id, short_name, sum(count) as count from
        (SELECT A
        .license_id as the_license_id,
        b.short_name as short_name,
        COUNT ( DISTINCT f.file_name )
        FROM
        files_licenses A,
        licenses b,
        augur_repo_map C,
        packages d,
        files e,
		packages_files f
        WHERE
        A.license_id = b.license_id
        AND d.package_id = C.dosocs_pkg_id
        AND e.file_id = A.file_id
		AND e.file_id = f.file_id
        AND e.package_id = d.package_id
        AND C.repo_id = :repo_id
        AND b.is_spdx_official = 'True'
        GROUP BY
        the_license_id,
        b.short_name
        UNION
        SELECT
        500 as the_license_id,
        'No Assertion' as short_name,
        COUNT ( DISTINCT f.file_name )
        FROM
        files_licenses A,
        licenses b,
        augur_repo_map C,
        packages d,
        files e,
		packages_files f
        WHERE
        A.license_id = b.license_id
        AND d.package_id = C.dosocs_pkg_id
        AND e.file_id = A.file_id
		AND e.file_id = f.file_id
        AND e.package_id = d.package_id
        AND C.repo_id = :repo_id
        AND b.is_spdx_official = 'False'
        GROUP BY
        the_license_id,
        short_name) L
    GROUP BY
    the_license_id,
    short_name
    ORDER BY
    short_name;
    """)

    results = pd.read_sql(license_declared_SQL, self.spdx_db, params={'repo_id': repo_id})
    return results

@register_metric()
def license_coverage(self, repo_group_id, repo_id=None):
    """Returns the declared license

    :param repo_group_id: The repository's repo_group_id
    :param repo_id: The repository's repo_id, defaults to None
    :return: Declared License
    """
    license_declared_SQL = None

    if repo_id:
        license_declared_SQL = s.sql.text("""
            SELECT a.name, b.total as total_files, a.licensed as license_declared_files, round(a.licensed/b.total::numeric, 3) as coverage
            FROM (
            SELECT packages.name as name, count(file_license_id) as licensed
            FROM packages,
                files_licenses,
                packages_files,
                repo
            WHERE packages.name = repo.repo_name
            and repo_id = :repo_id
            and packages.package_id = packages_files.package_id
            and packages_files.file_id = files_licenses.file_id
            GROUP BY packages.name) a, (SELECT packages.name as name, count(packages_files.file_id) as total
            FROm packages, repo, packages_files
            WHERE packages.name = repo.repo_name
            and repo_id = :repo_id
            AND packages.package_id = packages_files.package_id
            GROUP BY packages.name
            )b
            WHERE a.name = b.name
            GROUP BY a.name, a.licensed, a.licensed, b.total
        """)
    else:
        license_declared_SQL = s.sql.text("""
            SELECT a.name, b.total as total_files, a.licensed as license_declared_files, round(a.licensed/b.total::numeric, 3) as coverage
            FROM (
            SELECT packages.name as name, count(file_license_id) as licensed
            FROM packages,
                files_licenses,
                packages_files,
                repo
            WHERE packages.name = repo.repo_name
            and repo_group_id = :repo_group_id
            and packages.package_id = packages_files.package_id
            and packages_files.file_id = files_licenses.file_id
            GROUP BY packages.name) a, (SELECT packages.name as name, count(packages_files.file_id) as total
            FROm packages, repo, packages_files
            WHERE packages.name = repo.repo_name
            and repo_group_id = :repo_group_id
            AND packages.package_id = packages_files.package_id
            GROUP BY packages.name
            )b
            WHERE a.name = b.name
            GROUP BY a.name, a.licensed, a.licensed, b.total
        """)

    results = pd.read_sql(license_declared_SQL, self.spdx_db, params={'repo_id': repo_id, 'repo_group_id':repo_group_id})

    return results

@register_metric()
def license_count(self, repo_group_id, repo_id=None):
    """Returns the declared license

    :param repo_group_id: The repository's repo_group_id
    :param repo_id: The repository's repo_id, defaults to None
    :return: Declared License
    """
    license_declared_SQL = None

    if repo_id:
        license_declared_SQL = s.sql.text("""
            SELECT a.name, a.number_of_license, b.total > a.licensed as file_without_licenses
            FROM (
            SELECT packages.name as name, count (DISTINCT (files_licenses.license_id)) as number_of_license, count(file_license_id) as licensed
            FROM packages,
                files_licenses,
                packages_files,
                repo
            WHERE packages.name = repo.repo_name
            and repo_id = :repo_id
            and packages.package_id = packages_files.package_id
            and packages_files.file_id = files_licenses.file_id
            GROUP BY packages.name) a, (SELECT packages.name as name, count(packages_files.file_id) as total
            FROm packages, repo, packages_files
            WHERE packages.name = repo.repo_name
            and repo_id = :repo_id
            AND packages.package_id = packages_files.package_id
            GROUP BY packages.name
            )b
            WHERE a.name = b.name
            GROUP BY a.name, a.number_of_license, a.licensed, b.total
        """)
    else:
        license_declared_SQL = s.sql.text("""
            SELECT a.name, a.number_of_license, b.total > a.licensed as file_without_licenses
            FROM (
            SELECT packages.name as name, count (DISTINCT (files_licenses.license_id)) as number_of_license, count(file_license_id) as licensed
            FROM packages,
                files_licenses,
                packages_files,
                repo
            WHERE packages.name = repo.repo_name
            and repo_group_id = :repo_group_id
            and packages.package_id = packages_files.package_id
            and packages_files.file_id = files_licenses.file_id
            GROUP BY packages.name) a, (SELECT packages.name as name, count(packages_files.file_id) as total
            FROm packages, repo, packages_files
            WHERE packages.name = repo.repo_name
            and repo_group_id = :repo_group_id
            AND packages.package_id = packages_files.package_id
            GROUP BY packages.name
            )b
            WHERE a.name = b.name
            GROUP BY a.name, a.number_of_license, a.licensed, b.total
        """)

    results = pd.read_sql(license_declared_SQL, self.spdx_db, params={'repo_id': repo_id, 'repo_group_id':repo_group_id})

    return results

@register_metric()
def stars(self, repo_group_id, repo_id=None):
    """
    Returns a time series of the stars count

    :param repo_group_id: The repository's repo_group_id
    :param repo_id: The repository's repo_id, defaults to None
    :return: Time series of stars count
    """
    if not repo_id:
        stars_SQL = s.sql.text("""
            SELECT
                repo_info.repo_id,
                repo_name,
                repo_info.data_collection_date as date,
                stars_count AS stars
            FROM repo_info JOIN repo ON repo_info.repo_id = repo.repo_id
            WHERE repo_info.repo_id IN
                (SELECT repo_id FROM repo
                 WHERE  repo_group_id = :repo_group_id)
            ORDER BY repo_info.repo_id, date
        """)

        results = pd.read_sql(stars_SQL, self.database, params={'repo_group_id': repo_group_id})
        return results

    else:
        stars_SQL = s.sql.text("""
            SELECT
                repo_name,
                repo_info.data_collection_date as date,
                stars_count AS stars
            FROM repo_info JOIN repo ON repo_info.repo_id = repo.repo_id
            WHERE repo_info.repo_id = :repo_id
            ORDER BY date
        """)

        results = pd.read_sql(stars_SQL, self.database, params={'repo_id': repo_id})
        return results

@register_metric()
def stars_count(self, repo_group_id, repo_id=None):
    """
    Returns the latest stars count

    :param repo_group_id: The repository's repo_group_id
    :param repo_id: The repository's repo_id, defaults to None
    :return: stars count
    """
    if not repo_id:
        stars_count_SQL = s.sql.text("""
            SELECT a.repo_id, repo_name, a.stars_count AS stars
            FROM repo_info a LEFT JOIN repo_info b
            ON (a.repo_id = b.repo_id AND a.repo_info_id < b.repo_info_id), repo
            WHERE b.repo_info_id IS NULL
            AND a.repo_id = repo.repo_id
            AND a.repo_id IN
                (SELECT repo_id FROM repo
                 WHERE  repo_group_id = :repo_group_id)
        """)

        results = pd.read_sql(stars_count_SQL, self.database, params={'repo_group_id': repo_group_id})
        return results
    else:
        stars_count_SQL = s.sql.text("""
            SELECT repo_name, stars_count AS stars
            FROM repo_info JOIN repo ON repo_info.repo_id = repo.repo_id
            WHERE repo_info.repo_id = :repo_id
            ORDER BY repo_info.data_collection_date DESC
            LIMIT 1
        """)

        results = pd.read_sql(stars_count_SQL, self.database, params={'repo_id': repo_id})
        return results

@register_metric()
def watchers(self, repo_group_id, repo_id=None):
    """
    Returns a time series of the watchers count

    :param repo_group_id: The repository's repo_group_id
    :param repo_id: The repository's repo_id, defaults to None
    :return: Time series of watchers count
    """
    if not repo_id:
        watchers_SQL = s.sql.text("""
            SELECT
                repo_info.repo_id,
                repo_name,
                repo_info.data_collection_date as date,
                watchers_count AS watchers
            FROM repo_info JOIN repo ON repo_info.repo_id = repo.repo_id
            WHERE repo_info.repo_id IN
                (SELECT repo_id FROM repo
                 WHERE  repo_group_id = :repo_group_id)
            ORDER BY repo_info.repo_id, date
        """)

        results = pd.read_sql(watchers_SQL, self.database, params={'repo_group_id': repo_group_id})
        return results

    else:
        watchers_SQL = s.sql.text("""
            SELECT
                repo_name,
                repo_info.data_collection_date as date,
                watchers_count AS watchers
            FROM repo_info JOIN repo ON repo_info.repo_id = repo.repo_id
            WHERE repo_info.repo_id = :repo_id
            ORDER BY date
        """)

        results = pd.read_sql(watchers_SQL, self.database, params={'repo_id': repo_id})
        return results

@register_metric()
def watchers_count(self, repo_group_id, repo_id=None):
    """
    Returns the latest watchers count

    :param repo_group_id: The repository's repo_group_id
    :param repo_id: The repository's repo_id, defaults to None
    :return: watchers count
    """
    if not repo_id:
        watchers_count_SQL = s.sql.text("""
            SELECT a.repo_id, repo_name, a.watchers_count AS watchers
            FROM repo_info a LEFT JOIN repo_info b
            ON (a.repo_id = b.repo_id AND a.repo_info_id < b.repo_info_id), repo
            WHERE b.repo_info_id IS NULL
            AND a.repo_id = repo.repo_id
            AND a.repo_id IN
                (SELECT repo_id FROM repo
                 WHERE  repo_group_id = :repo_group_id)
        """)

        results = pd.read_sql(watchers_count_SQL, self.database, params={'repo_group_id': repo_group_id})
        return results
    else:
        watchers_count_SQL = s.sql.text("""
            SELECT repo_name, watchers_count AS watchers
            FROM repo_info JOIN repo ON repo_info.repo_id = repo.repo_id
            WHERE repo_info.repo_id = :repo_id
            ORDER BY repo_info.data_collection_date DESC
            LIMIT 1
        """)

        results = pd.read_sql(watchers_count_SQL, self.database, params={'repo_id': repo_id})
        return results

@register_metric()
def annual_lines_of_code_count_ranked_by_new_repo_in_repo_group(self, repo_group_id, repo_id = None, calendar_year=None):
    """
    For each repository in a collection of repositories being managed, each REPO that first appears in the parameterized
calendar year (a new repo in that year), show all commits for that year (total for year by repo).
    Result ranked from highest number of commits to lowest by default.

    :param repo_url: the repository's URL
    :param calendar_year: the calendar year a repo is created in to be considered "new"
    :param repo_group: the group of repositories to analyze
    """
    if calendar_year == None:
        calendar_year = datetime.datetime.now().strftime('%Y')

    cdRgNewrepRankedCommitsSQL = None

    if not repo_id:
        cdRgNewrepRankedCommitsSQL = s.sql.text("""
            SELECT repo.repo_id, sum(cast(added as INTEGER) - cast(removed as INTEGER) - cast(whitespace as INTEGER)) as net, patches, repo_name
            FROM dm_repo_annual, repo, repo_groups
            where  repo.repo_group_id = :repo_group_id
            and dm_repo_annual.repo_id = repo.repo_id
            and date_part('year', repo.repo_added) = :calendar_year
            and repo.repo_group_id = repo_groups.repo_group_id
            group by repo.repo_id, patches, rg_name
            ORDER BY net desc
            LIMIT 10
        """)
    else:
        cdRgNewrepRankedCommitsSQL = s.sql.text("""
            SELECT repo.repo_id, sum(cast(added as INTEGER) - cast(removed as INTEGER) - cast(whitespace as INTEGER)) as net, patches, repo_name
            FROM dm_repo_annual, repo, repo_groups
            where  repo.repo_group_id = (select repo.repo_group_id from repo where repo.repo_id = :repo_id)
            and dm_repo_annual.repo_id = repo.repo_id
            and date_part('year', repo.repo_added) = :calendar_year
            and repo.repo_group_id = repo_groups.repo_group_id
            group by repo.repo_id, patches, rg_name
            ORDER BY net desc
            LIMIT 10
        """)
    results = pd.read_sql(cdRgNewrepRankedCommitsSQL, self.database, params={ "repo_group_id": repo_group_id,
    "repo_id": repo_id, "calendar_year": calendar_year})
    return results

@register_metric()
def annual_lines_of_code_count_ranked_by_repo_in_repo_group(self, repo_group_id, repo_id=None, timeframe=None):
    """
    For each repository in a collection of repositories being managed, each REPO's total commits during the current Month,
    Year or Week. Result ranked from highest number of commits to lowest by default.
    :param repo_group_id: The repository's repo_group_id
    :param repo_id: The repository's repo_id, defaults to None
    :param calendar_year: the calendar year a repo is created in to be considered "new"
    """
    if timeframe == None:
        timeframe = 'all'

    cdRgTpRankedCommitsSQL = None

    if repo_id:
        if timeframe == 'all':
            cdRgTpRankedCommitsSQL = s.sql.text("""
                SELECT repo.repo_id, repo_name as name, SUM(added - removed - whitespace) as net, patches
                FROM dm_repo_annual, repo, repo_groups
                WHERE repo.repo_group_id = (select repo.repo_group_id from repo where repo.repo_id = :repo_id)
                AND repo.repo_group_id = repo_groups.repo_group_id
                AND dm_repo_annual.repo_id = repo.repo_id
                group by repo.repo_id, patches
                order by net desc
                LIMIT 10
            """)
        elif timeframe == 'year':
            cdRgTpRankedCommitsSQL = s.sql.text("""
                SELECT repo.repo_id, repo_name as name, SUM(added - removed - whitespace) as net, patches
                FROM dm_repo_annual, repo, repo_groups
                WHERE repo.repo_group_id = (select repo.repo_group_id from repo where repo.repo_id = :repo_id)
                AND repo.repo_group_id = repo_groups.repo_group_id
                AND dm_repo_annual.repo_id = repo.repo_id
                AND date_part('year', repo_added) = date_part('year', CURRENT_DATE)
                group by repo.repo_id, patches
                order by net desc
                LIMIT 10
            """)
        elif timeframe == 'month':
            cdRgTpRankedCommitsSQL = s.sql.text("""
                SELECT repo.repo_id, repo_name as name, SUM(added - removed - whitespace) as net, patches
                FROM dm_repo_monthly, repo, repo_groups
                WHERE repo.repo_group_id = (select repo.repo_group_id from repo where repo.repo_id = :repo_id)
                AND repo.repo_group_id = repo_groups.repo_group_id
                AND dm_repo_monthly.repo_id = repo.repo_id
                AND date_part('year', repo_added) = date_part('year', CURRENT_DATE)
                AND date_part('month', repo_added) = date_part('month', CURRENT_DATE)
                group by repo.repo_id, patches
                order by net desc
                LIMIT 10
            """)
    else:
        if timeframe == 'all':
            cdRgTpRankedCommitsSQL = s.sql.text("""
                SELECT repo.repo_id, repo_name as name, SUM(added - removed - whitespace) as net, patches
                FROM dm_repo_annual, repo, repo_groups
                WHERE repo.repo_group_id = :repo_group_id
                AND repo.repo_group_id = repo_groups.repo_group_id
                AND dm_repo_annual.repo_id = repo.repo_id
                group by repo.repo_id, patches
                order by net desc
                LIMIT 10
            """)
        elif timeframe == "year":
            cdRgTpRankedCommitsSQL = s.sql.text(
                """
                SELECT repo.repo_id, repo_name as name, SUM(added - removed - whitespace) as net, patches
                FROM dm_repo_annual, repo, repo_groups
                WHERE repo.repo_group_id = :repo_group_id
                AND repo.repo_group_id = repo_groups.repo_group_id
                AND dm_repo_annual.repo_id = repo.repo_id
                AND date_part('year', repo_added) = date_part('year', CURRENT_DATE)
                group by repo.repo_id, patches
                order by net desc
                LIMIT 10
                """
            )
        elif timeframe == 'month':
            cdRgTpRankedCommitsSQL = s.sql.text("""
                SELECT repo.repo_id, repo_name as name, SUM(added - removed - whitespace) as net, patches
                FROM dm_repo_annual, repo, repo_groups
                WHERE repo.repo_group_id = :repo_group_id
                AND repo.repo_group_id = repo_groups.repo_group_id
                AND dm_repo_annual.repo_id = repo.repo_id
                AND date_part('year', repo_added) = date_part('year', CURRENT_DATE)
                AND date_part('month', repo_added) = date_part('month', CURRENT_DATE)
                group by repo.repo_id, patches
                order by net desc
                LIMIT 10
            """)

    results = pd.read_sql(cdRgTpRankedCommitsSQL, self.database, params={ "repo_group_id": repo_group_id,
        "repo_id": repo_id})
    return results

@register_metric()
def lines_of_code_commit_counts_by_calendar_year_grouped(self, repo_url, calendar_year=None, interval=None):
    """
    For a single repository, all the commits and lines of code occuring for the specified year, grouped by the specified interval (week or month)

    :param repo_url: the repository's URL
    :param calendar_year: the calendar year a repo is created in to be considered "new"
    :param interval: Month or week. The periodocity of which to examine data within the given calendar_year
    """

    if calendar_year == None:
        calendar_year = datetime.datetime.now().strftime('%Y')

    if interval == None:
        interval = 'month'

    cdRepTpIntervalLocCommitsSQL = None

    if interval == "month":
        cdRepTpIntervalLocCommitsSQL = s.sql.text("""
            SELECT sum(cast(IFNULL(added, 0) as signed) - cast(IFNULL(removed, 0) as signed) - cast(IFNULL(whitespace, 0) as signed)) as net_lines_minus_whitespace,
            sum(IFNULL(added, 0)) as added, sum(IFNULL(removed, 0)) as removed, sum(IFNULL(whitespace, 0)) as whitespace,
            IFNULL(patches, 0) as commits, a.month, IFNULL(year, :calendar_year) as year
            FROM (select month from repo_monthly_cache group by month) a
            LEFT JOIN (SELECT name, repo_monthly_cache.added, removed, whitespace, patches, month, IFNULL(year, :calendar_year) as year
            FROM repo_monthly_cache, repos
            WHERE repos_id = (SELECT id FROM repos WHERE git LIKE :repourl LIMIT 1)
            AND year = :calendar_year
            AND repos.id = repos_id
            GROUP BY month) b
            ON a.month = b.month
            GROUP BY month
        """)
    elif interval == "week":
        cdRepTpIntervalLocCommitsSQL = s.sql.text("""
            SELECT  sum(cast(IFNULL(added, 0) as signed) - cast(IFNULL(removed, 0) as signed) - cast(IFNULL(whitespace, 0) as signed)) as net_lines_minus_whitespace,
            sum(IFNULL(added, 0)) as added, sum(IFNULL(removed, 0)) as removed, sum(IFNULL(whitespace, 0)) as whitespace,
            IFNULL(patches, 0) as commits, a.week, IFNULL(year, :calendar_year) as year
            FROM (select week from repo_weekly_cache group by week) a
            LEFT JOIN (SELECT name, repo_weekly_cache.added, removed, whitespace, patches, week, IFNULL(year, :calendar_year) as year
            FROM repo_weekly_cache, repos
            WHERE repos_id = (SELECT id FROM repos WHERE git LIKE :repourl LIMIT 1)
            AND year = :calendar_year
            AND repos.id = repos_id
            GROUP BY week) b
            ON a.week = b.week
            GROUP BY week
        """)

    results = pd.read_sql(cdRepTpIntervalLocCommitsSQL, self.database, params={"repourl": '%{}%'.format(repo_url), 'calendar_year': calendar_year})
    return results

@register_metric()
def average_weekly_commits(self, repo_group_id=None, repo_id=None, calendar_year=None):

    if calendar_year == None:
        calendar_year = datetime.datetime.now().strftime('%Y')

    extra_and = "AND repo.repo_group_id = :repo_group_id" if repo_group_id and not repo_id else "AND repo.repo_id = :repo_id" if repo_group_id and repo_id else ""
    average_weekly_commits_sql = s.sql.text("""
        SELECT repo.repo_id, repo.repo_name, year, sum(patches)/52 AS average_weekly_commits
        FROM dm_repo_annual, repo
        WHERE YEAR = :calendar_year -- or other year
        AND dm_repo_annual.repo_id = repo.repo_id
        {}
        GROUP BY repo.repo_id, repo.repo_name, YEAR
        ORDER BY repo_name
    """.format(extra_and))

    results = pd.read_sql(average_weekly_commits_sql, self.database, params={"repo_group_id": repo_group_id,
        "repo_id": repo_id, "calendar_year": calendar_year})
    return results

@register_metric()
def aggregate_summary(self, repo_group_id, repo_id=None, begin_date=None, end_date=None):

    if not begin_date:
        begin_date = datetime.datetime.now()
        # Subtract 1 year and leap year check
        try:
            begin_date = begin_date.replace(year=begin_date.year-1)
        except ValueError:
            begin_date = begin_date.replace(year=begin_date.year-1, day=begin_date.day-1)
        begin_date = begin_date.strftime('%Y-%m-%d')
    if not end_date:
        end_date = datetime.datetime.now().strftime('%Y-%m-%d')

    if not repo_id:
        summarySQL = s.sql.text("""
            SELECT
            (
                SELECT watchers_count AS watcher_count
                FROM repo_info JOIN repo ON repo_info.repo_id = repo.repo_id
                WHERE repo_group_id = :repo_group_id
                ORDER BY last_updated DESC
                LIMIT 1
            ) - (
                SELECT watchers_count AS watcher_count
                FROM repo_info JOIN repo ON repo_info.repo_id = repo.repo_id
                WHERE repo_group_id = :repo_group_id
                AND last_updated >= date_trunc('day', NOW() - INTERVAL '1 year')
                ORDER BY last_updated ASC
                LIMIT 1
            ) AS watcher_count,
            (
                SELECT stars_count AS stars_count
                FROM repo_info JOIN repo ON repo_info.repo_id = repo.repo_id
                WHERE repo_group_id = :repo_group_id
                ORDER BY last_updated DESC
                LIMIT 1
            ) - (
                SELECT stars_count AS stars_count
                FROM repo_info JOIN repo ON repo_info.repo_id = repo.repo_id
                WHERE repo_group_id = :repo_group_id
                AND last_updated >= date_trunc('day', NOW() - INTERVAL '1 year')
                ORDER BY last_updated ASC
                LIMIT 1
            ) AS stars_count,
            (
                SELECT fork_count AS fork_count
                FROM repo_info JOIN repo ON repo_info.repo_id = repo.repo_id
                WHERE repo_group_id = :repo_group_id
                ORDER BY last_updated DESC
                LIMIT 1
            ) - (
                SELECT fork_count AS fork_count
                FROM repo_info JOIN repo ON repo_info.repo_id = repo.repo_id
                WHERE repo_group_id = :repo_group_id
                AND last_updated >= date_trunc('day', NOW() - INTERVAL '1 year')
                ORDER BY last_updated ASC
                LIMIT 1
            ) AS fork_count,
            (
                SELECT count(*) AS merged_count
                FROM (
                    SELECT DISTINCT issue_events.issue_id
                    FROM issue_events JOIN issues ON issues.issue_id = issue_events.issue_id JOIN repo ON issues.repo_id = repo.repo_id
                    WHERE action = 'merged'
                    AND repo_group_id = :repo_group_id
                    AND issue_events.created_at BETWEEN :begin_date AND :end_date
                ) a
            ) AS merged_count,
            committer_count, commit_count FROM (
                SELECT count(cmt_author_name) AS committer_count, sum(commit_count) AS commit_count
                FROM (
                    SELECT DISTINCT cmt_author_name, COUNT(cmt_id) AS commit_count FROM commits JOIN repo ON commits.repo_id = repo.repo_id
                    WHERE repo_group_id = :repo_group_id
                    AND commits.cmt_committer_date BETWEEN :begin_date AND :end_date
                    GROUP BY cmt_author_name
                ) temp
            ) commit_data
        """)
        results = pd.read_sql(summarySQL, self.database, params={'repo_group_id': repo_group_id,
                                                        'begin_date': begin_date, 'end_date': end_date})
        return results
    else:
        summarySQL = s.sql.text("""
            SELECT
            (
                SELECT watchers_count AS watcher_count
                FROM repo_info
                WHERE repo_id = :repo_id
                ORDER BY last_updated DESC
                LIMIT 1
            ) - (
                SELECT watchers_count AS watcher_count
                FROM repo_info
                WHERE repo_id = :repo_id
                AND last_updated >= date_trunc('day', NOW() - INTERVAL '1 year')
                ORDER BY last_updated ASC
                LIMIT 1
            ) AS watcher_count,
            (
                SELECT stars_count AS stars_count
                FROM repo_info
                WHERE repo_id = :repo_id
                ORDER BY last_updated DESC
                LIMIT 1
            ) - (
                SELECT stars_count AS stars_count
                FROM repo_info
                WHERE repo_id = :repo_id
                AND last_updated >= date_trunc('day', NOW() - INTERVAL '1 year')
                ORDER BY last_updated ASC
                LIMIT 1
            ) AS stars_count,
            (
                SELECT fork_count AS fork_count
                FROM repo_info
                WHERE repo_id = :repo_id
                ORDER BY last_updated DESC
                LIMIT 1
            ) - (
                SELECT fork_count AS fork_count
                FROM repo_info
                WHERE repo_id = :repo_id
                AND last_updated >= date_trunc('day', NOW() - INTERVAL '1 year')
                ORDER BY last_updated ASC
                LIMIT 1
            ) AS fork_count,
            (
                SELECT count(*) AS merged_count
                FROM (
                    SELECT DISTINCT issue_events.issue_id
                    FROM issue_events JOIN issues ON issues.issue_id = issue_events.issue_id
                    WHERE action = 'merged'
                    AND repo_id = :repo_id
                    AND issue_events.created_at BETWEEN :begin_date AND :end_date
                ) a
            ) AS merged_count,
            committer_count, commit_count FROM (
                SELECT count(cmt_author_name) AS committer_count, sum(commit_count) AS commit_count
                FROM (
                    SELECT DISTINCT cmt_author_name, COUNT(cmt_id) AS commit_count FROM commits
                    WHERE repo_id = :repo_id
                    AND commits.cmt_committer_date BETWEEN :begin_date AND :end_date
                    GROUP BY cmt_author_name
                ) temp
            ) commit_data
        """)
        results = pd.read_sql(summarySQL, self.database, params={'repo_id': repo_id,
                                                        'begin_date': begin_date, 'end_date': end_date})
        return results


text:
using System.Collections.Generic;

namespace System.Linq.Expressions
{
    public class ListInitExpression : Expression
    {
        public NewExpression NewExpression { get; private set; }
        public List<ElementInit> Initializers { get; private set; }

        public ListInitExpression(NewExpression newExpression, List<ElementInit> initializers) : base(ExpressionType.ListInit)
        {
            NewExpression = newExpression;
            Initializers = initializers;
        }

        public override Expression Accept(ExpressionVisitor visitor)
        {
            return visitor.VisitListInit(this);
        }

        public override Type Type
        {
            get { return NewExpression.Type; }
        }

        public ListInitExpression Update(NewExpression NewExpression, List<ElementInit> initializers)
        {
            return this;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="action_definition.xsl"?>

<!--
   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to You under the Apache License, Version 2.0
   (the "License"); you may not use this file except in compliance with
   the License.  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
-->

<actionDefinitions>
  <actionDefinition>
    <actionName>check_host</actionName>
    <actionType>SYSTEM</actionType>
    <inputs/>
    <targetService/>
    <targetComponent/>
    <defaultTimeout>60</defaultTimeout>
    <description>General check for host</description>
    <targetType>ANY</targetType>
  </actionDefinition>
  <actionDefinition>
    <actionName>validate_configs</actionName>
    <actionType>SYSTEM</actionType>
    <inputs/>
    <targetService/>
    <targetComponent/>
    <defaultTimeout>60</defaultTimeout>
    <description>Validate if provided service config can be applied to specified hosts</description>
    <targetType>ALL</targetType>
  </actionDefinition>
  <actionDefinition>
    <actionName>install_packages</actionName>
    <actionType>SYSTEM</actionType>
    <inputs>base_urls, package_list</inputs>
    <targetService/>
    <targetComponent/>
    <defaultTimeout>60</defaultTimeout>
    <description>Distribute repositories and install packages</description>
    <targetType>ALL</targetType>
  </actionDefinition>
  <actionDefinition>
    <actionName>ru_execute_tasks</actionName>
    <actionType>SYSTEM</actionType>
    <inputs>tasks</inputs>
    <targetService/>
    <targetComponent/>
    <description>Perform upgrade action</description>
    <targetType>ANY</targetType>
  </actionDefinition>
</actionDefinitions>


text:
using UnityEngine;
using System;
using LuaInterface;
using SLua;
using System.Collections.Generic;
public class Lua_UnityEngine_EventSystems_Physics2DRaycaster : LuaObject {
	[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
	static public int Raycast(IntPtr l) {
		try {
			UnityEngine.EventSystems.Physics2DRaycaster self=(UnityEngine.EventSystems.Physics2DRaycaster)checkSelf(l);
			UnityEngine.EventSystems.PointerEventData a1;
			checkType(l,2,out a1);
			System.Collections.Generic.List<UnityEngine.EventSystems.RaycastResult> a2;
			checkType(l,3,out a2);
			self.Raycast(a1,a2);
			pushValue(l,true);
			return 1;
		}
		catch(Exception e) {
			return error(l,e);
		}
	}
	static public void reg(IntPtr l) {
		getTypeTable(l,"UnityEngine.EventSystems.Physics2DRaycaster");
		addMember(l,Raycast);
		createTypeMetatable(l,null, typeof(UnityEngine.EventSystems.Physics2DRaycaster),typeof(UnityEngine.EventSystems.PhysicsRaycaster));
	}
}


text:
title: Using Passwordless Authentication on iOS
---

<%= include('./_introduction', { withFingerprint: true }) %>

## Tutorials for iOS

 - [Authenticate users with a one-time code via SMS](ios-sms-swift)
 - [Authenticate users with a one-time code via e-mail](ios-email-swift)
 - [Authenticate users with Touch ID](ios-touch-id-swift)


text:
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;

// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108

namespace System.Text
{
  abstract public partial class Decoder
  {
    #region Methods and constructors
    public virtual new void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed)
    {
      bytesUsed = default(int);
      charsUsed = default(int);
      completed = default(bool);
    }

    unsafe public virtual new void Convert(byte* bytes, int byteCount, char* chars, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed)
    {
      bytesUsed = default(int);
      charsUsed = default(int);
      completed = default(bool);
    }

    protected Decoder()
    {
    }

    public virtual new int GetCharCount(byte[] bytes, int index, int count, bool flush)
    {
      return default(int);
    }

    public abstract int GetCharCount(byte[] bytes, int index, int count);

    unsafe public virtual new int GetCharCount(byte* bytes, int count, bool flush)
    {
      return default(int);
    }

    public abstract int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex);

    unsafe public virtual new int GetChars(byte* bytes, int byteCount, char* chars, int charCount, bool flush)
    {
      return default(int);
    }

    public virtual new int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, bool flush)
    {
      return default(int);
    }

    public virtual new void Reset()
    {
    }
    #endregion

    #region Properties and indexers
    public DecoderFallback Fallback
    {
      get
      {
        return default(DecoderFallback);
      }
      set
      {
      }
    }

    public DecoderFallbackBuffer FallbackBuffer
    {
      get
      {
        return default(DecoderFallbackBuffer);
      }
    }
    #endregion
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

using System.Windows.Forms;
using System.Collections.ObjectModel;

namespace KUtility.Utilities
{
    public static class WPFUtility
    {

        /// <summary>
        /// set height and width of a window for wpf apps
        /// </summary>
        /// <param name="window"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        public static void SetWindowSize(this Window window, double width, double height)
        {
            if (window == null) return;
            window.Height = height;
            window.Width = width;
        }

        /// <summary>
        /// Set window's size based on a percentage of height and a percentage of width to the screen size.
        /// </summary>
        /// <param name="window"></param>
        /// <param name="widthRatio"></param>
        /// <param name="heightRatio"></param>
        public static void SetWindowSizeBasedOnScreen(this Window window, double widthRatio, double heightRatio)
        {
            var width = SystemParameters.PrimaryScreenWidth * widthRatio;
            var height = SystemParameters.PrimaryScreenHeight * heightRatio;
            window.SetWindowSize(width, height);
        }

        public static Point GetMousePosition()
        {
            System.Drawing.Point point = Control.MousePosition;
            return new Point(point.X, point.Y);
        }

        /// <summary>
        /// Add items in a list to the observableCollection
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="colletion"></param>
        /// <param name="items"></param>
        public static void AddRange<T>(this ObservableCollection<T> colletion, List<T> items)
        {
            foreach (var item in items)
            {
                colletion.Add(item);
            }
        }
    }
}


text:
using MahApps.Metro.Controls;
using PasswordFormat;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;

namespace JPassword
{
    public partial class SiteCard : MetroWindow
    {
        Dictionary<string, string> OpenedSite { get; set; }
        MainWindow window;
        Group group;
        Site site;

        public SiteCard(MainWindow window, Site site, Group group)
        {
            InitializeComponent();

            this.window = window;
            this.group = group;
            this.site = site;

            Title = site.Name;
            OpenedSite = new Dictionary<string, string>();

            if (!string.IsNullOrWhiteSpace(site.Name)) OpenedSite.Add(TryFindResource("lang_siteName").ToString(), site.Name);
            if (!string.IsNullOrWhiteSpace(site.Address)) OpenedSite.Add(TryFindResource("lang_siteAddress").ToString(), site.Address);
            if (!string.IsNullOrWhiteSpace(site.Login)) OpenedSite.Add(TryFindResource("lang_siteLogin").ToString(), site.Login);
            if (!string.IsNullOrWhiteSpace(site.Password)) OpenedSite.Add(TryFindResource("lang_sitePassword").ToString(), site.Password);
            if (!string.IsNullOrWhiteSpace(site.Mail)) OpenedSite.Add(TryFindResource("lang_siteMail").ToString(), site.Mail);
            OpenedSite.Add(TryFindResource("lang_siteGroup").ToString(), group.Name);
            if (site.CustomFields != null)
                foreach (var item in site.CustomFields)
                    OpenedSite.Add(item.Key, item.Value);

            lbOpenedSite.ItemsSource = OpenedSite;
        }

        private void lbOpenedSiteClick(object sender, SelectionChangedEventArgs e)
        {
            if (lbOpenedSite.SelectedIndex != -1)
            {
                dynamic d = lbOpenedSite.SelectedItem;
                Clipboard.SetText(d.Value);
            }
        }
        private void btnEditClick(object sender, RoutedEventArgs e)
        {
            if (window.IsHiden)
                window.WindowShow();
            window.tbiAddNew.IsSelected = true;
            window.CurrentGroup = group;
            window.CurrentSite = site;
            window.EditSite();
            window.EditFromCard = true;
            window.siteList.IsOpen = false;
            window.siteOpen.IsOpen = false;
            Close();
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">

	<!-- LIST -->

	<style name="UITableView">
		<item name="android:layout_width">fill_parent</item>
		<item name="android:layout_height">fill_parent</item>
	</style>

	<style name="list_container">
		<item name="android:background">@drawable/background_view_rounded_container</item>
	</style>

	<style name="list_item_top">
		<item name="android:clickable">true</item>
		<item name="android:focusable">true</item>
		<item name="android:paddingTop">10dip</item>
		<item name="android:paddingBottom">10dip</item>
		<item name="android:paddingLeft">10dip</item>
    	<item name="android:paddingRight">10dip</item>
    	<item name="android:gravity">center_vertical</item>
    	<item name="android:background">@drawable/background_view_rounded_top</item>
	</style>

	<style name="list_item_middle">
		<item name="android:clickable">true</item>
		<item name="android:paddingTop">10dip</item>
		<item name="android:paddingBottom">10dip</item>
		<item name="android:paddingLeft">10dip</item>
    	<item name="android:paddingRight">10dip</item>
    	<item name="android:gravity">center_vertical</item>
    	<item name="android:background">@drawable/background_view_rounded_middle</item>
	</style>

	<style name="list_item_bottom">
		<item name="android:clickable">true</item>
		<item name="android:paddingTop">10dip</item>
		<item name="android:paddingBottom">10dip</item>
		<item name="android:paddingLeft">10dip</item>
    	<item name="android:paddingRight">10dip</item>
    	<item name="android:gravity">center_vertical</item>
    	<item name="android:background">@drawable/background_view_rounded_bottom</item>
	</style>

	<style name="list_item_single">
		<item name="android:clickable">true</item>
		<item name="android:paddingTop">10dip</item>
		<item name="android:paddingBottom">10dip</item>
		<item name="android:paddingLeft">10dip</item>
    	<item name="android:paddingRight">10dip</item>
    	<item name="android:gravity">center_vertical</item>
    	<item name="android:background">@drawable/background_view_rounded_single</item>
	</style>

	<style name="list_item_chevron">
        <item name="android:paddingLeft">4.0dip</item>
        <item name="android:paddingTop">2.0dip</item>
        <item name="android:paddingRight">4.0dip</item>
        <item name="android:paddingBottom">2.0dip</item>
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:src">@drawable/chevron</item>
        <item name="android:duplicateParentState">true</item>
    </style>

	<!-- TEXT -->
	<style name="content_page_large_text">
		<item name="android:duplicateParentState">true</item>
        <item name="android:textSize">16sp</item>
        <item name="android:typeface">sans</item>
        <item name="android:textColor">@color/text_color_selector</item>
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:ellipsize">end</item>
        <item name="android:singleLine">true</item>
    </style>

	<style name="content_page_small_text">
		<item name="android:duplicateParentState">true</item>
        <item name="android:textSize">16sp</item>
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:textColor">@color/text_color_selector</item>
        <item name="android:ellipsize">end</item>
        <item name="android:singleLine">true</item>

    </style>

    <style name="content_page_large_count_text">
        <item name="android:textSize">16sp</item>
        <item name="android:textColor">#ff8295bf</item>
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:layout_marginRight">8.0dip</item>
    </style>

</resources>


text:
layout: post
title: "Using ROS1 rosbag with ROS2"
author: "Timothy Shan"
tags: ros2
---

This post will cover the process for using ROS1 rosbag for ROS2. Specifically, the ROS1 version is `neotic` and the ROS2 is `galactic` with the Rust wrapper.

The tool we need is [Rosbags](https://ternaris.gitlab.io/rosbags/), which provides the reader and writer and both ROS1 and ROS2. The installation step is `pip install rosbags`. Firstly, we deserialize the topics from the ros1 bag. Secondly, use the writer from `from rosbags.rosbag2 import Writer` to serialize the topics to ros2 bag.

One thing to note is how to convert the compressed image to raw image. I tried `image_transport`, but it's not supported by conda version of ROS1 installed via [robostack](https://robostack.github.io/noetic.html).
It turns out that we can construct the raw image type using `rosbags`, i.e. `msg = Image(msg.header, msg_raw.height, msg_raw.width, msg_raw.encoding, msg_raw.is_bigendian, msg_raw.step, msg.data)`, where `msg` is the compressed image from ros1 bag, and `msg_raw` is the converted raw image.
The output size of raw image is confusing, as it is not something like `848x480x3` format. Based on [this](https://gist.github.com/awesomebytes/958a5ef9e63821a28dc05775840c34d9), I found that we need to use `cv2.imdecode` to decode the raw image data.
In Rust, we could do
```rust
pub fn cv_bridge(img: &r2r::sensor_msgs::msg::Image) -> cv2::core::Mat {
    let buf = img.data.as_slice();
    let src = Mat::from_slice::<u8>(buf).unwrap();
    let img_rgb: Mat = cv2::imgcodecs::imdecode(&src, cv2::imgcodecs::IMREAD_COLOR).unwrap();
    return img_rgb;
}
```

So far I have outlined the steps for the rosbags. If we want to convert the messages online, we need to use [ros1_bridge](https://github.com/ros2/ros1_bridge), which seems to take some time to compile. Some examples of using ros1 bridge can be found [here](https://github.com/mabelzhang/ros1_bridge_sandbox).

The github repo for this post is [here](https://github.com/shanmo/ros2_ros1_bridge).


text:
/**
 * \file include/shg/pcfg.h
 * Probabilistic context free grammar.
 */

#ifndef SHG_PCFG_H
#define SHG_PCFG_H

#include <map>
#include <limits>
#include <tuple>
#include <shg/cfg.h>
#include <shg/tree.h>
#include <shg/rng.h>

namespace SHG::PLP {

struct S_production {
     Production prod{};
     double prob{};
};

std::ostream& operator<<(std::ostream& stream,
                         S_production const& sp);

using Vecsprod = std::vector<S_production>;

/**
 * Splits Vecsprod into Vecprod and vector of probabilities.
 */
std::pair<Vecprod, std::vector<double>> split(Vecsprod const& vsp);

std::ostream& operator<<(std::ostream& stream, Vecsprod const& vsp);

/**
 * Probabilistic context free grammar.
 *
 * Written according to \cite manning-schutze-2003.
 *
 * \implementation
 *
 * There are \f$n\f$ nonterminals numbered from \f$0\f$ to \f$n - 1\f$
 * and \f$V\f$ terminals numbered from \f$0\f$ to \f$V - 1\f$.
 * Original names of terminals are stored in #nonterminal_names_ and
 * #terminal_names_. #nmap_ and #tmap_ map names to numbers. Binary
 * and unary productions are stored in #bp_ and #up_.
 *
 */
class PCFG {
public:
     using Index = std::size_t;
     struct Parse_node {
          std::string symbol{};  ///< Nonterminal or terminal name.
          double prob{};         ///< Probability for nonterminals.
          bool is_terminal{false};
          std::string to_string() const;
     };
     using Parse_tree = Tree<Parse_node>;

     PCFG() = default;
     PCFG(PCFG const& other);
     PCFG(PCFG&& other) noexcept;
     PCFG& operator=(PCFG const& other);
     PCFG& operator=(PCFG&& other);

     /**
      * Sets the grammar. \c vp must be in Chomsky normal form. \c
      * prob must contain probabilities such that the production \c
      * vp[i] has probability \c prob[i].
      */
     void set(Vecprod const& vp, std::vector<double> const& prob,
              double tol = 100.0 *
                           std::numeric_limits<double>::epsilon());

     void clear();
     bool is_valid() const;
     Vecsprod vecsprod() const;

     /**
      * Calculates probability of the string \c w using inside
      * probabilities according to formulas
      * \cite manning-schutze-2003, (11.16), (11.17) on page 392.
      */
     double prob(Sentence const& w);

     /**
      * Calculates logarithm of probability of all the strings in \c
      * vs as if they were independent. The vector \c vs must not be
      * empty.
      */
     double log_prob(Vecsent const& vs);

     /**
      * Calculates probability of the string \c w using outside
      * probabilities according to formulas
      * \cite manning-schutze-2003, (11.18), (11.19) on page 394.
      * This function is added for easy testing alpha().
      */
     double prob_outside(Sentence const& w, Index k);

     /**
      * Finds the most probable parse for the sentence \f$w\f$. See
      * \cite manning-schutze-2003, section 11.3.3 on pages 396 - 398.
      */
     void cyk(Sentence const& w, double& prob, Parse_tree& t);

     int inside_outside(Vecsent const& vs, double accuracy,
                        double tol, int max_iter, int& iter,
                        double& logp);

     /**
      * Removes productions with probabilities less than or equal to
      * \f$\varepsilon \in [0, 1)\f$.
      *
      * \todo This function does not remove useless variables. Adopt
      * algorithm from \cite hopcroft-ullman-2003, section 4.4, pages
      * 106-109.
      */
     void remove_productions(double eps);

private:
     using Binary = std::map<std::pair<Index, Index>, double>;
     using Unary = std::map<Index, double>;
     using Prob_table = std::vector<std::vector<std::vector<double>>>;
     struct Backtrace {
          Index j;
          Index k;
          Index r;
     };
     using Backtrace_table =
          std::vector<std::vector<std::vector<Backtrace>>>;
     using F_table = std::vector<std::vector<std::vector<
          std::vector<std::vector<std::vector<double>>>>>>;
     using GH_table =
          std::vector<std::vector<std::vector<std::vector<double>>>>;

     Index n_{};  ///< Number of nonterminals \f$n\f$.
     Index V_{};  ///< Number of terminals \f$V\f$.

     /**
      * %Vector of binary productions. \f$\var{bp\_}[j]\f$ contains
      * pairs \f$((r, s), \var{prob})\f$ such that
      * \f$\Pr(N^j \rightarrow N^r N^s) = \var{prob}\f$.
      */
     std::vector<Binary> bp_{};
     /**
      * %Vector of unary productions. \f$\var{up\_}[j]\f$ contains
      * pairs \f$(k, \var{prob})\f$ such that \f$\Pr(N^j \rightarrow
      * w_k) = \var{prob}\f$.
      */
     std::vector<Unary> up_{};

     /** Pointers to names of nonterminals. */
     std::vector<std::string const*> nonterminal_names_{};
     /** Pointers to names of terminals. */
     std::vector<std::string const*> terminal_names_{};
     /// Maps nonterminal names to numbers.
     std::map<std::string, Index> nmap_{};
     /// Maps terminal names to numbers.
     std::map<std::string, Index> tmap_{};

     std::vector<Index> w_{};  ///< Current sentence \f$w\f$.
     Index m_{};  ///< Length \f$m\f$ of current sentence \f$w\f$.

     /**
      * Table of inside probabilities \cite manning-schutze-2003,
      * pages 392-393. \f$\var{beta\_}(j, p, q) = \beta_j(p, q), \quad
      * 0 \leq j < n, \quad 0 \leq p \leq q < m\f$.
      */
     Prob_table beta_{};
     /**
      * Table of outside probabilities \cite manning-schutze-2003,
      * pages 394-396. \f$\var{alpha\_}(j, p, q) = \alpha_j(p, q),
      * \quad 0 \leq j < n, \quad 0 \leq p \leq q < m\f$.
      */
     Prob_table alpha_{};

     /**
      * \name Tables used in %CYK algorithm.
      *  \{
      */
     /**
      * Table of the greatest inside probabilities
      * \cite manning-schutze-2003, pages 396-398. \f$\var{delta\_}(i,
      * p, q) = \delta_i(p, q), \quad 0 \leq i < n, \quad 0 \leq p
      * \leq q < m\f$.
      */
     Prob_table delta_{};
     /**
      * Table of backtrace information for %CYK algorithm
      * \cite manning-schutze-2003, pages 397-398. \f$\var{psi\_}(i,
      * p, q) = \psi_i(p, q), \quad 0 \leq i < n, \quad 0 \leq p \leq
      * q < m\f$.
      */
     Backtrace_table psi_{};
     /** \} */

     /**
      * \name Tables used in inside-outside algorithm.
      *  \{
      */
     /**
      * The table 11.28 for \f$f_i(p, q, j, r, s)\f$,
      * \cite manning-schutze-2003, page 400.
      */
     F_table ftab_{};
     /**
      * The table 11.28 for \f$g_i(h, j, k)\f$,
      * \cite manning-schutze-2003, page 400.
      */
     GH_table gtab_{};
     /**
      * The table 11.28 for \f$h_i(p, q, j)\f$,
      * \cite manning-schutze-2003, page 400.
      */
     GH_table htab_{};
     /** \} */

     void check() const;

     /**
      * Returns true if probabilities are valid.
      */
     bool probs_valid(double tol) const;

     /// Returns \f$\Pr(N^j \rightarrow N^r N^s)\f$.
     double prob(Index j, Index r, Index s);
     /// Returns \f$\Pr(N^j \rightarrow w_k)\f$.
     double prob(Index j, Index k);

     double log_prob(Vecsent const& vs, bool& ok);

     /**
      * Translates terminals in \c w into terminal numbers and puts
      * them in \c w_.
      */
     void set(Sentence const& w);

     void add_node(Index i, Index p, Index q, Parse_tree& t);

     /**
      * Calculates \f$\beta_j(p, q)\f$ according to formulas
      * \cite manning-schutze-2003, pages 392, 393.
      */
     void fill_beta();

     /**
      * Calculates \f$\alpha_j(p, q)\f$ according to formulas
      * \cite manning-schutze-2003, pages 394 - 396.
      *
      * \todo What about rules \f$N^j \rightarrow N^j N^j\f$? Should
      * they be counted twice? Check this on grammar having such a
      * production and compoare with probability counted with beta.
      */
     void fill_alpha();

     /**
      * Calculates \f$\delta_i(p, q)\f$ according to formulas
      * \cite manning-schutze-2003, page 397.
      */
     void fill_delta();

     void init_tables(Vecsent const& vs);
     void fill_names();
     int one_iteration(Vecsent const& vs);

     friend bool operator==(Backtrace const& a, Backtrace const& b);
     friend bool operator!=(Backtrace const& a, Backtrace const& b);
     friend bool operator==(PCFG const& a, PCFG const& b);
     friend std::ostream& operator<<(std::ostream& stream,
                                     PCFG const& g);
};

bool operator==(PCFG const& a, PCFG const& b);
bool operator!=(PCFG const& a, PCFG const& b);

std::ostream& operator<<(std::ostream& stream, PCFG const& g);

/**
 * Given context free grammar in Chomsky normal form, generates random
 * probability for each production so as the grammar and probabilities
 * could be used in PCFG::set(Vecprod const&, std::vector<double>
 * const&). Probabilities are put into \f$\var{prob}\f$.
 * \f$\var{rng}\f$ is used to generate probabilities.
 */
void add_probabilities(Vecprod const& vp, std::vector<double>& prob,
                       RNG& rng);

}  // namespace SHG::PLP

#endif


text:
package cieloecommerce.sdk.ecommerce;

import com.google.gson.annotations.SerializedName;

public class RecurrentSale {
    @SerializedName("Customer")
    private Customer customer;

    @SerializedName("RecurrentPayment")
    private RecurrentPayment recurrentPayment;

    public Customer getCustomer() {
        return customer;
    }

    public RecurrentSale setCustomer(Customer customer) {
        this.customer = customer;
        return this;
    }

    public RecurrentPayment getRecurrentPayment() {
        return recurrentPayment;
    }

    public RecurrentSale setRecurrentPayment(RecurrentPayment recurrentPayment) {
        this.recurrentPayment = recurrentPayment;
        return this;
    }
}


text:
package org.apache.activemq.artemis.tests.integration.amqp;

import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.core.server.RoutingType;
import org.apache.activemq.artemis.core.server.impl.AddressInfo;
import org.apache.activemq.artemis.core.server.impl.QueueImpl;
import org.apache.activemq.transport.amqp.client.AmqpClient;
import org.apache.activemq.transport.amqp.client.AmqpConnection;
import org.apache.activemq.transport.amqp.client.AmqpMessage;
import org.apache.activemq.transport.amqp.client.AmqpReceiver;
import org.apache.activemq.transport.amqp.client.AmqpSession;
import org.apache.qpid.proton.amqp.messaging.Source;
import org.apache.qpid.proton.amqp.messaging.TerminusDurability;
import org.junit.Test;

import java.util.concurrent.TimeUnit;

import static org.apache.qpid.jms.provider.amqp.message.AmqpDestinationHelper.TOPIC_CAPABILITY;

public class ClientDefinedMultiConsumerTest extends AmqpClientTestSupport  {

   SimpleString address = new SimpleString("testAddress");

   @Test(timeout = 60000)
   public void test2ConsumersOnSharedVolatileAddress() throws Exception {
      AddressInfo addressInfo = new AddressInfo(address);
      addressInfo.getRoutingTypes().add(RoutingType.MULTICAST);
      server.addAddressInfo(addressInfo);
      AmqpClient client = createAmqpClient();

      AmqpConnection connection = addConnection(client.connect("myClientId"));
      AmqpSession session = connection.createSession();
      Source source = createSharedSource(TerminusDurability.NONE);
      AmqpReceiver receiver = session.createMulticastReceiver(source, "myReceiverID", "mySub");
      AmqpReceiver receiver2 = session.createMulticastReceiver(source, "myReceiverID", "mySub|2");
      receiver.flow(1);
      receiver2.flow(1);
      sendMessages(2, address.toString());
      AmqpMessage amqpMessage = receiver.receive(5, TimeUnit.SECONDS);
      assertNotNull(amqpMessage);
      amqpMessage = receiver2.receive(5, TimeUnit.SECONDS);
      assertNotNull(amqpMessage);
      assertEquals(2, ((QueueImpl)server.getPostOffice().getBinding(SimpleString.toSimpleString("myClientId.mySub:shared-volatile")).getBindable()).getConsumerCount());
      receiver.close();
      assertNotNull(server.getPostOffice().getBinding(SimpleString.toSimpleString("myClientId.mySub:shared-volatile")));
      receiver2.close();
      //check its been deleted
      assertNull(server.getPostOffice().getBinding(SimpleString.toSimpleString("myClientId.mySub:shared-volatile")));
      connection.close();
   }

   @Test(timeout = 60000)
   public void test2ConsumersOnSharedVolatileAddressBrokerDefined() throws Exception {
      AddressInfo addressInfo = new AddressInfo(address);
      addressInfo.getRoutingTypes().add(RoutingType.MULTICAST);
      server.addAddressInfo(addressInfo);
      server.createQueue(address, RoutingType.MULTICAST, SimpleString.toSimpleString("myClientId.mySub:shared-volatile"), null, true, false, -1, false, false);
      AmqpClient client = createAmqpClient();

      AmqpConnection connection = addConnection(client.connect("myClientId"));
      AmqpSession session = connection.createSession();
      Source source = createSharedSource(TerminusDurability.NONE);
      AmqpReceiver receiver = session.createMulticastReceiver(source, "myReceiverID", "mySub");
      AmqpReceiver receiver2 = session.createMulticastReceiver(source, "myReceiverID", "mySub|1");
      receiver.flow(1);
      receiver2.flow(1);
      sendMessages(2, address.toString());
      AmqpMessage amqpMessage = receiver.receive(5, TimeUnit.SECONDS);
      assertNotNull(amqpMessage);
      amqpMessage = receiver2.receive(5, TimeUnit.SECONDS);
      assertNotNull(amqpMessage);
      assertEquals(2, ((QueueImpl)server.getPostOffice().getBinding(SimpleString.toSimpleString("myClientId.mySub:shared-volatile")).getBindable()).getConsumerCount());
      receiver.close();
      assertNotNull(server.getPostOffice().getBinding(SimpleString.toSimpleString("myClientId.mySub:shared-volatile")));
      receiver2.close();
      //check its **Hasn't** been deleted
      assertNotNull(server.getPostOffice().getBinding(SimpleString.toSimpleString("myClientId.mySub:shared-volatile")));
      connection.close();
   }

   @Test(timeout = 60000)
   public void test2ConsumersOnSharedVolatileAddressNoReceiverClose() throws Exception {
      AddressInfo addressInfo = new AddressInfo(address);
      addressInfo.getRoutingTypes().add(RoutingType.MULTICAST);
      server.addAddressInfo(addressInfo);
      AmqpClient client = createAmqpClient();

      AmqpConnection connection = addConnection(client.connect("myClientId"));
      AmqpSession session = connection.createSession();
      Source source = createSharedSource(TerminusDurability.NONE);
      AmqpReceiver receiver = session.createMulticastReceiver(source, "myReceiverID", "mySub");
      AmqpReceiver receiver2 = session.createMulticastReceiver(source, "myReceiverID", "mySub|2");
      receiver.flow(1);
      receiver2.flow(1);
      sendMessages(2, address.toString());
      AmqpMessage amqpMessage = receiver.receive(5, TimeUnit.SECONDS);
      assertNotNull(amqpMessage);
      amqpMessage = receiver2.receive(5, TimeUnit.SECONDS);
      assertNotNull(amqpMessage);
      assertEquals(2, ((QueueImpl)server.getPostOffice().getBinding(SimpleString.toSimpleString("myClientId.mySub:shared-volatile")).getBindable()).getConsumerCount());
      assertNotNull(server.getPostOffice().getBinding(SimpleString.toSimpleString("myClientId.mySub:shared-volatile")));
      //check its been deleted
      connection.close();
      assertNull(server.getPostOffice().getBinding(SimpleString.toSimpleString("myClientId.mySub:shared-volatile")));
   }

   @Test(timeout = 60000)
   public void test2ConsumersOnSharedVolatileAddressGlobal() throws Exception {
      AddressInfo addressInfo = new AddressInfo(address);
      addressInfo.getRoutingTypes().add(RoutingType.MULTICAST);
      server.addAddressInfo(addressInfo);
      AmqpClient client = createAmqpClient();

      AmqpConnection connection = addConnection(client.connect(false));
      AmqpSession session = connection.createSession();
      Source source = createSharedGlobalSource(TerminusDurability.NONE);
      AmqpReceiver receiver = session.createMulticastReceiver(source, "myReceiverID", "mySub");
      AmqpReceiver receiver2 = session.createMulticastReceiver(source, "myReceiverID", "mySub|2");
      receiver.flow(1);
      receiver2.flow(1);
      sendMessages(2, address.toString());
      AmqpMessage amqpMessage = receiver.receive(5, TimeUnit.SECONDS);
      assertNotNull(amqpMessage);
      amqpMessage = receiver2.receive(5, TimeUnit.SECONDS);
      assertNotNull(amqpMessage);
      assertEquals(2, ((QueueImpl)server.getPostOffice().getBinding(SimpleString.toSimpleString("mySub:shared-volatile:global")).getBindable()).getConsumerCount());
      receiver.close();
      assertNotNull(server.getPostOffice().getBinding(SimpleString.toSimpleString("mySub:shared-volatile:global")));
      receiver2.close();
      //check its been deleted
      assertNull(server.getPostOffice().getBinding(SimpleString.toSimpleString("mySub:shared-volatile:global")));
      connection.close();
   }

   @Test(timeout = 60000)
   public void test2ConsumersOnSharedDurableAddress() throws Exception {
      AddressInfo addressInfo = new AddressInfo(address);
      addressInfo.getRoutingTypes().add(RoutingType.MULTICAST);
      server.addAddressInfo(addressInfo);
      AmqpClient client = createAmqpClient();

      AmqpConnection connection = addConnection(client.connect("myClientId"));
      AmqpSession session = connection.createSession();
      Source source = createSharedSource(TerminusDurability.CONFIGURATION);
      AmqpReceiver receiver = session.createMulticastReceiver(source, "myReceiverID", "mySub");
      AmqpReceiver receiver2 = session.createMulticastReceiver(source, "myReceiverID", "mySub|2");
      receiver.flow(1);
      receiver2.flow(1);
      sendMessages(2, address.toString());
      AmqpMessage amqpMessage = receiver.receive(5, TimeUnit.SECONDS);
      assertNotNull(amqpMessage);
      amqpMessage = receiver2.receive(5, TimeUnit.SECONDS);
      assertNotNull(amqpMessage);
      assertEquals(2, ((QueueImpl)server.getPostOffice().getBinding(SimpleString.toSimpleString("myClientId.mySub")).getBindable()).getConsumerCount());
      receiver.close();
      assertNotNull(server.getPostOffice().getBinding(SimpleString.toSimpleString("myClientId.mySub")));
      receiver2.close();
      //check its been deleted
      assertNull(server.getPostOffice().getBinding(SimpleString.toSimpleString("myClientId.mySub")));
      connection.close();
   }

   @Test(timeout = 60000)
   public void test2ConsumersOnSharedDurableAddressReconnect() throws Exception {
      AddressInfo addressInfo = new AddressInfo(address);
      addressInfo.getRoutingTypes().add(RoutingType.MULTICAST);
      server.addAddressInfo(addressInfo);
      AmqpClient client = createAmqpClient();

      AmqpConnection connection = addConnection(client.connect("myClientId"));
      AmqpSession session = connection.createSession();
      Source source = createSharedSource(TerminusDurability.CONFIGURATION);
      AmqpReceiver receiver = session.createMulticastReceiver(source, "myReceiverID", "mySub");
      AmqpReceiver receiver2 = session.createMulticastReceiver(source, "myReceiverID", "mySub|2");
      receiver.flow(1);
      receiver2.flow(1);
      sendMessages(2, address.toString());
      AmqpMessage amqpMessage = receiver.receive(5, TimeUnit.SECONDS);
      assertNotNull(amqpMessage);
      amqpMessage = receiver2.receive(5, TimeUnit.SECONDS);
      assertNotNull(amqpMessage);
      assertEquals(2, ((QueueImpl)server.getPostOffice().getBinding(SimpleString.toSimpleString("myClientId.mySub")).getBindable()).getConsumerCount());

      connection.close();

      connection = addConnection(client.connect("myClientId"));
      session = connection.createSession();

      assertNotNull(server.getPostOffice().getBinding(SimpleString.toSimpleString("myClientId.mySub")));
      receiver = session.createMulticastReceiver(source, "myReceiverID", "mySub");
      receiver2 = session.createMulticastReceiver(source, "myReceiverID", "mySub|2");

      receiver.close();
      assertNotNull(server.getPostOffice().getBinding(SimpleString.toSimpleString("myClientId.mySub")));
      receiver2.close();
      //check its been deleted
      assertNull(server.getPostOffice().getBinding(SimpleString.toSimpleString("myClientId.mySub")));
      connection.close();
   }

   @Test(timeout = 60000)
   public void test2ConsumersOnSharedDurableAddressReconnectwithNull() throws Exception {
      AddressInfo addressInfo = new AddressInfo(address);
      addressInfo.getRoutingTypes().add(RoutingType.MULTICAST);
      server.addAddressInfo(addressInfo);
      AmqpClient client = createAmqpClient();

      AmqpConnection connection = addConnection(client.connect("myClientId"));
      AmqpSession session = connection.createSession();
      Source source = createSharedSource(TerminusDurability.CONFIGURATION);
      AmqpReceiver receiver = session.createMulticastReceiver(source, "myReceiverID", "mySub");
      AmqpReceiver receiver2 = session.createMulticastReceiver(source, "myReceiverID", "mySub|2");
      receiver.flow(1);
      receiver2.flow(1);
      sendMessages(2, address.toString());
      AmqpMessage amqpMessage = receiver.receive(5, TimeUnit.SECONDS);
      assertNotNull(amqpMessage);
      amqpMessage = receiver2.receive(5, TimeUnit.SECONDS);
      assertNotNull(amqpMessage);
      assertEquals(2, ((QueueImpl)server.getPostOffice().getBinding(SimpleString.toSimpleString("myClientId.mySub")).getBindable()).getConsumerCount());

      connection.close();

      connection = addConnection(client.connect("myClientId"));
      session = connection.createSession();

      assertNotNull(server.getPostOffice().getBinding(SimpleString.toSimpleString("myClientId.mySub")));
      receiver = session.createDurableReceiver(null, "mySub");
      receiver2 = session.createDurableReceiver(null, "mySub|2");

      receiver.close();
      assertNotNull(server.getPostOffice().getBinding(SimpleString.toSimpleString("myClientId.mySub")));
      receiver2.close();
      //check its been deleted
      assertNull(server.getPostOffice().getBinding(SimpleString.toSimpleString("myClientId.mySub")));
      connection.close();
   }

   @Test(timeout = 60000)
   public void test2ConsumersOnSharedDurableAddressGlobal() throws Exception {
      AddressInfo addressInfo = new AddressInfo(address);
      addressInfo.getRoutingTypes().add(RoutingType.MULTICAST);
      server.addAddressInfo(addressInfo);
      AmqpClient client = createAmqpClient();

      AmqpConnection connection = addConnection(client.connect(false));
      AmqpSession session = connection.createSession();
      Source source = createSharedGlobalSource(TerminusDurability.CONFIGURATION);
      AmqpReceiver receiver = session.createMulticastReceiver(source, "myReceiverID", "mySub");
      AmqpReceiver receiver2 = session.createMulticastReceiver(source, "myReceiverID", "mySub|2");
      receiver.flow(1);
      receiver2.flow(1);
      sendMessages(2, address.toString());
      AmqpMessage amqpMessage = receiver.receive(5, TimeUnit.SECONDS);
      assertNotNull(amqpMessage);
      amqpMessage = receiver2.receive(5, TimeUnit.SECONDS);
      assertNotNull(amqpMessage);
      assertEquals(2, ((QueueImpl)server.getPostOffice().getBinding(SimpleString.toSimpleString("mySub:global")).getBindable()).getConsumerCount());
      receiver.close();
      assertNotNull(server.getPostOffice().getBinding(SimpleString.toSimpleString("mySub:global")));
      receiver2.close();
      //check its been deleted
      assertNull(server.getPostOffice().getBinding(SimpleString.toSimpleString("mySub:global")));
      connection.close();
   }

   @Test(timeout = 60000)
   public void test2ConsumersOnNonSharedDurableAddress() throws Exception {
      AddressInfo addressInfo = new AddressInfo(address);
      addressInfo.getRoutingTypes().add(RoutingType.MULTICAST);
      server.addAddressInfo(addressInfo);
      AmqpClient client = createAmqpClient();

      AmqpConnection connection = addConnection(client.connect("myClientId"));
      AmqpSession session = connection.createSession();
      Source source = createNonSharedSource(TerminusDurability.CONFIGURATION);
      Source source1 = createSharedSource(TerminusDurability.CONFIGURATION);
      AmqpReceiver receiver = session.createMulticastReceiver(source, "myReceiverID", "mySub");
      try {
         session.createMulticastReceiver(source1, "myReceiverID", "mySub|2");
         fail("Exception expected");
      } catch (Exception e) {
         //expected
      }
      connection.close();
   }

   @Test(timeout = 60000)
   public void testAddressDoesntExist() throws Exception {
      AmqpClient client = createAmqpClient();

      AmqpConnection connection = addConnection(client.connect("myClientId"));
      AmqpSession session = connection.createSession();
      Source source = createNonSharedSource(TerminusDurability.CONFIGURATION);
      Source source1 = createSharedSource(TerminusDurability.CONFIGURATION);
      AmqpReceiver receiver = session.createMulticastReceiver(source, "myReceiverID", "mySub");
      try {
         session.createMulticastReceiver(source1, "myReceiverID", "mySub|2");
         fail("Exception expected");
      } catch (Exception e) {
         //expected
      }
      connection.close();
   }

   private Source createNonSharedSource(TerminusDurability terminusDurability) {
      Source source = new Source();
      source.setAddress(address.toString());
      source.setCapabilities(TOPIC_CAPABILITY);
      source.setDurable(terminusDurability);
      return source;
   }

   private Source createSharedSource(TerminusDurability terminusDurability) {
      Source source = new Source();
      source.setAddress(address.toString());
      source.setCapabilities(TOPIC_CAPABILITY, SHARED);
      source.setDurable(terminusDurability);
      return source;
   }

   private Source createSharedGlobalSource(TerminusDurability terminusDurability) {
      Source source = new Source();
      source.setAddress(address.toString());
      source.setCapabilities(TOPIC_CAPABILITY, SHARED, GLOBAL);
      source.setDurable(terminusDurability);
      return source;
   }
}


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

<title>R-Index</title>
<meta name="date" content="2014-04-28">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D E F G I L M N O P R S T U

R

register() - Method in class com.hv15.aperi.AperiMainActivity

Callback to register the AperiBroadcastReceiver to the Activity

REQUEST - Static variable in class com.hv15.aperi.network.NetPackage

Used to indicate that the packet is a request, meaning that the sender
 wishes for the receiver to respond

resetViews() - Method in class com.hv15.aperi.DeviceDetailFragment

Clears the UI fields after a disconnect or direct mode disable operation.

RESPOND - Static variable in class com.hv15.aperi.network.NetPackage

Indicates that the packet is a response to a request.

A B C D E F G I L M N O P R S T U

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
//-----------------------------------------------------------------------
// <copyright file="ClassAttribute.cs" company="NMock2">
//
//   http://www.sourceforge.net/projects/NMock2
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
// </copyright>
// This is the easiest way to ignore StyleCop rules on this file, even if we shouldn't use this tag:
// <auto-generated />
//-----------------------------------------------------------------------
using NUnit.Framework;

namespace NMocha.AcceptanceTests {
    /// <summary>
    /// Tests in this category perform mocking of classes.
    /// </summary>
    public class ClassAttribute : CategoryAttribute {
    }
}


text:
layout: leetcode
title: "51. N-Queens"
categories: [leetcode]
---

[Leetcode Link](https://leetcode.com/problems/n-queens)
| [Backtrack template](/template/backtrack)

The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.

Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively.

```
Example 1:
Input: n = 4
Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above

Example 2:
Input: n = 1
Output: [["Q"]]
```

Solution:

* Backtrack, Time: O(N!), Space: O(N)

```python
def solveNQueens(self, n: int) -> List[List[str]]:
  def is_valid(row, col):
    if cols[col] or diag_l[row + col] \
      or diag_r[col - row + n - 1]:
      return False
    return True

  def make_solution(grid):
    res = []
    for row in grid:
        res.append("".join(row))
    return res

  def backtrack(row):
    if row == n:
    # print(f"found a result: {grid}")
      result.append(make_solution(grid))
      return
    for col in range(len(grid[row])):
      if is_valid(row, col):
        # set new path
        cols[col] = True
        diag_l[row + col] = True
        diag_r[col - row + n - 1] = True
        grid[row][col] = "Q"
        backtrack(row + 1)
        # undo change
        grid[row][col] = "."
        cols[col] = False
        diag_l[row + col] = False
        diag_r[col - row + n - 1] = False

  result = []
  grid = [['.'] * n for _ in range(n)]
  cols = [False] * n
  m = n * 2 - 1
  diag_l = [False] * m
  diag_r = [False] * m
  backtrack(0)
  return result
```


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

.. _to-api-v3-cdns-domains:

****************
``cdns/domains``
****************

``GET``
=======
Gets a list of domains and their related Traffic Router :term:`Profiles` for all CDNs.

:Auth. Required: Yes
:Roles Required: None
:Response Type:  Array

Request Structure
-----------------
No parameters available.

Response Structure
------------------
:domainName:         The :abbr:`TLD (Top-Level Domain)` assigned to this CDN
:parameterId:        The :ref:`parameter-id` for the :term:`Parameter` that sets this :abbr:`TLD (Top-Level Domain)` on the Traffic Router
:profileDescription: A short, human-readable description of the Traffic Router's profile
:profileId:          The :ref:`profile-id` of the :term:`Profile` assigned to the Traffic Router responsible for serving ``domainName``
:profileName:        The :ref:`profile-name` of the :term:`Profile` assigned to the Traffic Router responsible for serving ``domainName``

.. code-block:: json
	:caption: Response Example

	{ "response": [
		{
			"profileId": 12,
			"parameterId": -1,
			"profileName": "CCR_CIAB",
			"profileDescription": "Traffic Router for CDN-In-A-Box",
			"domainName": "mycdn.ciab.test"
		}
	]}


text:
'use strict'

/** @ignore */
const CiscoSpark = require('./CiscoSpark')

/**
 * Spark People
 * @see https://developer.webex.com/docs/api/v1/people
 */
class People extends CiscoSpark {
  /**
   * @constructor
   * @param {string} [accessToken] - Your Cisco Spark accesstoken
   * @param {string} [userAgent] - User Agent request header
   */
  constructor (accessToken, userAgent) {
    super(accessToken, userAgent, 'https://api.ciscospark.com/v1/people')
    /** @private */
    this.idName = 'personId'
  }

  /**
   * List People
   * List people in your organization. For most users, either the email or a Display Name parameters are required.
   * Admin users can omit these fields and list all users in their organization.
   *
   * @override
   * @param {Object} params - see https://developer.webex.com/docs/api/v1/people/list-people
   * @param {requestCallback} callback
   */
  list (params, callback) {
    if (typeof params === 'string') {
      params = { email: params }
    } else if (!params || !params.email || !params.displayName) {
      return callback(new Error('Invalid Params. Require email or displayName'))
    }
    return super.list(params, callback)
  }

  /**
   * Get my own details
   * @param {requestCallback} callback
   */
  me (callback) {
    return this.get('me', callback)
  }
}

module.exports = People