text:
import sys

import googleapiclient

import gam
from gam.var import * # pylint: disable=unused-wildcard-import
from gam import controlflow
from gam import display
from gam import gapi
from gam import utils
from gam.gapi import errors as gapi_errors
from gam.gapi import cloudidentity as gapi_cloudidentity
from gam.gapi.directory import customer as gapi_directory_customer

# This allows easy switching between v1 and v1beta1
# v1
CIGROUP_API_BETA = 'cloudidentity'
CIGROUP_MEMBERKEY = 'preferredMemberKey'
# v1beta1
#CIGROUP_API_BETA = 'cloudidentity_beta'
#CIGROUP_MEMBERKEY = 'memberKey'

def create():
    ci = gapi_cloudidentity.build()
    initialGroupConfig = 'EMPTY'
    gapi_directory_customer.setTrueCustomerId()
    parent = f'customers/{GC_Values[GC_CUSTOMER_ID]}'
    body = {
        'groupKey': {
            'id': gam.normalizeEmailAddressOrUID(sys.argv[3], noUid=True)
        },
        'parent': parent,
        'labels': {
            'cloudidentity.googleapis.com/groups.discussion_forum': ''
        },
    }
    i = 4
    while i < len(sys.argv):
        myarg = sys.argv[i].lower().replace('_', '')
        if myarg == 'name':
            body['displayName'] = sys.argv[i + 1]
            i += 2
        elif myarg == 'description':
            body['description'] = sys.argv[i + 1]
            i += 2
        elif myarg in ['alias', 'aliases']:
            # As of 2020/06/25 this doesn't work (yet?)
            aliases = sys.argv[i + 1].split(' ')
            body['additionalGroupKeys'] = []
            for alias in aliases:
                body['additionalGroupKeys'].append({'id': alias})
            i += 2
        elif myarg in ['dynamic']:
            body['dynamicGroupMetadata'] = {
                'queries': [{
                    'query': sys.argv[i + 1],
                    'resourceType': 'USER'
                }]
            }
            i += 2
        elif myarg in ['makeowner']:
            initialGroupConfig = 'WITH_INITIAL_OWNER'
            i += 1
        else:
            print('should not get here')
            sys.exit(5)
    print(f'Creating group {body["groupKey"]["id"]}')
    gapi.call(ci.groups(),
              'create',
              initialGroupConfig=initialGroupConfig,
              body=body)

def delete():
    ci = gapi_cloudidentity.build()
    group = sys.argv[3]
    name = group_email_to_id(ci, group)
    print(f'Deleting group {group}')
    gapi.call(ci.groups(), 'delete', name=name)

def info():
    ci = gapi_cloudidentity.build(CIGROUP_API_BETA)
    group = gam.normalizeEmailAddressOrUID(sys.argv[3])
    getUsers = True
    getSecuritySettings = True
    showJoinDate = True
    showUpdateDate = False
    showMemberTree = False
    i = 4
    while i < len(sys.argv):
        myarg = sys.argv[i].lower().replace('_', '')
        if myarg == 'nousers':
            getUsers = False
            i += 1
        elif myarg == 'nojoindate':
            showJoinDate = False
            i += 1
        elif myarg == 'showupdatedate':
            showUpdateDate = True
            i += 1
        elif myarg == 'membertree':
            showMemberTree = True
            i += 1
        elif myarg in ['nosecurity', 'nosecuritysettings']:
            getSecuritySettings = False
        else:
            controlflow.invalid_argument_exit(myarg, 'gam info cigroup')
    name = group_email_to_id(ci, group)
    basic_info = gapi.call(ci.groups(), 'get', name=name)
    display.print_json(basic_info)
    if getSecuritySettings:
        sec_info = gapi.call(ci.groups(),
                             'getSecuritySettings',
                             name=f'{name}/securitySettings',
                             readMask='*')
        print(' Security settings:')
        display.print_json(sec_info, spacing=' ')
    if getUsers and not showMemberTree:
        if not showJoinDate and not showUpdateDate:
            view = 'BASIC'
            pageSize = 1000
        else:
            view = 'FULL'
            pageSize = 500
        members = gapi.get_all_pages(ci.groups().memberships(),
                                     'list',
                                     'memberships',
                                     parent=name,
                                     fields='*',
                                     pageSize=pageSize,
                                     view=view)
        print(' Members:')
        for member in members:
            role = get_single_role(member.get('roles', [])).lower()
            email = member.get(CIGROUP_MEMBERKEY, {}).get('id')
            member_type = member.get('type', 'USER').lower()
            jc_string = ''
            if showJoinDate:
                joined = member.get('createTime', 'Unknown')
                jc_string += f'  joined {joined}'
            if showUpdateDate:
                updated = member.get('updateTime', 'Unknown')
                jc_string += f'  updated {updated}'
            print(f'  {role}: {email} ({member_type}){jc_string}')
        print(f'Total {len(members)} users in group')
    elif showMemberTree:
        print(' Membership Tree:')
        cached_group_members = {}
        print_member_tree(ci, name, cached_group_members, 2, True)

def print_member_tree(ci, group_id, cached_group_members, spaces, show_role):
    if not group_id in cached_group_members:
        cached_group_members[group_id] = gapi.get_all_pages(ci.groups().memberships(),
                                                            'list',
                                                            'memberships',
                                                            parent=group_id,
                                                            view='FULL',
                                                            fields='*',
                                                            pageSize=1000)
    for member in cached_group_members[group_id]:
        member_id = member.get('name', '')
        member_id = member_id.split('/')[-1]
        email = member.get(CIGROUP_MEMBERKEY, {}).get('id')
        member_type = member.get('type', 'USER').lower()
        if show_role:
            role = get_single_role(member.get('roles', [])).lower()
            print(f'{" " * spaces}{role}: {email} ({member_type})')
        else:
            print(f'{" " * spaces}{email} ({member_type})')
        if member_type == 'group':
            print_member_tree(ci, f'groups/{member_id}', cached_group_members, spaces + 2, False)

def info_member():
    ci = gapi_cloudidentity.build()
    member = gam.normalizeEmailAddressOrUID(sys.argv[3])
    group = gam.normalizeEmailAddressOrUID(sys.argv[4])
    group_name = gapi.call(ci.groups(),
                           'lookup',
                           groupKey_id=group,
                           fields='name').get('name')
    member_name = gapi.call(ci.groups().memberships(),
                            'lookup',
                            parent=group_name,
                            memberKey_id=member,
                            fields='name').get('name')
    member_details = gapi.call(ci.groups().memberships(),
                               'get',
                               name=member_name)
    display.print_json(member_details)

UPDATE_GROUP_SUBCMDS = ['add', 'clear', 'delete', 'remove', 'sync', 'update']
GROUP_ROLES_MAP = {
    'owner': ROLE_OWNER,
    'owners': ROLE_OWNER,
    'manager': ROLE_MANAGER,
    'managers': ROLE_MANAGER,
    'member': ROLE_MEMBER,
    'members': ROLE_MEMBER,
}

def print_():
    ci = gapi_cloudidentity.build(CIGROUP_API_BETA)
    i = 3
    members = False
    membersCountOnly = False
    managers = False
    managersCountOnly = False
    owners = False
    ownersCountOnly = False
    memberRestrictions = False
    gapi_directory_customer.setTrueCustomerId()
    parent = f'customers/{GC_Values[GC_CUSTOMER_ID]}'
    usemember = None
    memberDelimiter = '\n'
    todrive = False
    titles = []
    csvRows = []
    roles = []
    sortHeaders = False
    while i < len(sys.argv):
        myarg = sys.argv[i].lower()
        if myarg == 'todrive':
            todrive = True
            i += 1
        elif myarg == 'enterprisemember':
            member = gam.convertUIDtoEmailAddress(sys.argv[i + 1], email_types=['user', 'group'])
            usemember = f"member_key_id == '{member}' && 'cloudidentity.googleapis.com/groups.discussion_forum' in labels"
            i += 2
        elif myarg == 'delimiter':
            memberDelimiter = sys.argv[i + 1]
            i += 2
        elif myarg == 'sortheaders':
            sortHeaders = True
            i += 1
        elif myarg in ['members', 'memberscount']:
            roles.append(ROLE_MEMBER)
            members = True
            if myarg == 'memberscount':
                membersCountOnly = True
            i += 1
        elif myarg in ['owners', 'ownerscount']:
            roles.append(ROLE_OWNER)
            owners = True
            if myarg == 'ownerscount':
                ownersCountOnly = True
            i += 1
        elif myarg in ['managers', 'managerscount']:
            roles.append(ROLE_MANAGER)
            managers = True
            if myarg == 'managerscount':
                managersCountOnly = True
            i += 1
        elif myarg in ['memberrestrictions']:
            memberRestrictions = True
            display.add_titles_to_csv_file(
                    ['memberRestrictionQuery',],
                    titles)
            display.add_titles_to_csv_file(
                    ['memberRestrictionEvaluation',],
                    titles)
            i += 1
        else:
            controlflow.invalid_argument_exit(sys.argv[i], 'gam print cigroups')
    if roles:
        if members:
            display.add_titles_to_csv_file([
                'MembersCount',
            ], titles)
            if not membersCountOnly:
                display.add_titles_to_csv_file([
                    'Members',
                ], titles)
        if managers:
            display.add_titles_to_csv_file([
                'ManagersCount',
            ], titles)
            if not managersCountOnly:
                display.add_titles_to_csv_file([
                    'Managers',
                ], titles)
        if owners:
            display.add_titles_to_csv_file([
                'OwnersCount',
            ], titles)
            if not ownersCountOnly:
                display.add_titles_to_csv_file([
                    'Owners',
                ], titles)
    gam.printGettingAllItems('Groups', usemember)
    page_message = gapi.got_total_items_first_last_msg('Groups')
    if usemember:
        try:
            result = gapi.get_all_pages(ci.groups().memberships(),
                                        'searchTransitiveGroups',
                                        'memberships',
                                        throw_reasons=[gapi_errors.ErrorReason.FOUR_O_O],
                                        page_message=page_message,
                                        message_attribute=['groupKey', 'id'],
                                        parent='groups/-', query=usemember,
                                        fields='nextPageToken,memberships(group,groupKey(id),relationType)',
                                        pageSize=1000)
        except googleapiclient.errors.HttpError:
            controlflow.system_error_exit(
                2,
                'enterprisemember requires Enterprise license')
        entityList = []
        for entity in result:
            if entity['relationType'] == 'DIRECT':
                entityList.append(gapi.call(ci.groups(), 'get', name=entity['group']))
    else:
        entityList = gapi.get_all_pages(ci.groups(),
                                        'list',
                                        'groups',
                                        page_message=page_message,
                                        message_attribute=['groupKey', 'id'],
                                        parent=parent,
                                        view='FULL',
                                        pageSize=500)
    i = 0
    count = len(entityList)
    for groupEntity in entityList:
        i += 1
        groupEmail = groupEntity['groupKey']['id']
        for k, v in iter(groupEntity.pop('labels', {}).items()):
            if v == '':
                groupEntity[f'labels.{k}'] = True
            else:
                groupEntity[f'labels.{k}'] = v
        group = utils.flatten_json(groupEntity)
        for a_key in group:
            if a_key not in titles:
                titles.append(a_key)
        groupKey_id = groupEntity['name']
        if roles:
            sys.stderr.write(
                f' Getting {roles} for {groupEmail}{gam.currentCountNL(i, count)}'
            )
            page_message = gapi.got_total_items_first_last_msg('Members')
            validRoles, _, _ = gam._getRoleVerification(
                ','.join(roles), 'nextPageToken,members(email,id,role)')
            groupMembers = gapi.get_all_pages(ci.groups().memberships(),
                                              'list',
                                              'memberships',
                                              page_message=page_message,
                                              message_attribute=[CIGROUP_MEMBERKEY, 'id'],
                                              soft_errors=True,
                                              parent=groupKey_id,
                                              view='BASIC')
            if members:
                membersList = []
                membersCount = 0
            if managers:
                managersList = []
                managersCount = 0
            if owners:
                ownersList = []
                ownersCount = 0
            for member in groupMembers:
                member_email = member[CIGROUP_MEMBERKEY]['id']
                role = get_single_role(member.get('roles', []))
                if not validRoles or role in validRoles:
                    if role == ROLE_MEMBER:
                        if members:
                            membersCount += 1
                            if not membersCountOnly:
                                membersList.append(member_email)
                    elif role == ROLE_MANAGER:
                        if managers:
                            managersCount += 1
                            if not managersCountOnly:
                                managersList.append(member_email)
                    elif role == ROLE_OWNER:
                        if owners:
                            ownersCount += 1
                            if not ownersCountOnly:
                                ownersList.append(member_email)
                    elif members:
                        membersCount += 1
                        if not membersCountOnly:
                            membersList.append(member_email)
            if members:
                group['MembersCount'] = membersCount
                if not membersCountOnly:
                    group['Members'] = memberDelimiter.join(membersList)
            if managers:
                group['ManagersCount'] = managersCount
                if not managersCountOnly:
                    group['Managers'] = memberDelimiter.join(managersList)
            if owners:
                group['OwnersCount'] = ownersCount
                if not ownersCountOnly:
                    group['Owners'] = memberDelimiter.join(ownersList)
        if memberRestrictions:
           name = f'{groupKey_id}/securitySettings'
           print(f'Getting member restrictions for {groupEmail} ({i}/{count}')
           sec_info = gapi.call(ci.groups(),
                                'getSecuritySettings',
                                name=name,
                                readMask='*')
           if 'memberRestriction' in sec_info:
               group['memberRestrictionQuery'] = sec_info['memberRestriction'].get('query', '')
               group['memberRestrictionEvaluation'] = sec_info['memberRestriction'].get('evaluation', {}).get('state', '')
        csvRows.append(group)
    if sortHeaders:
        display.sort_csv_titles([
            'name', 'groupKey.id'
        ], titles)
    display.write_csv_file(csvRows, titles, 'Groups', todrive)

def _get_groups_list(ci=None, member=None, parent=None):
    if not ci:
        ci = gapi_cloudidentity.build()
    if not parent:
            gapi_directory_customer.setTrueCustomerId()
            parent = f'customers/{GC_Values[GC_CUSTOMER_ID]}'
    gam.printGettingAllItems('Groups', member)
    page_message = gapi.got_total_items_first_last_msg('Groups')
    if member:
        fields = 'nextPageToken,memberships(groupKey(id),relationType)'
        try:
            groups_to_get = gapi.get_all_pages(ci.groups().memberships(),
                                               'searchTransitiveGroups',
                                               'memberships',
                                               throw_reasons=[gapi_errors.ErrorReason.FOUR_O_O],
                                               message_attribute=['groupKey', 'id'],
                                               page_message=page_message,
                                               parent='groups/-',
                                               query=member,
                                               pageSize=1000,
                                               fields=fields)
        except googleapiclient.errors.HttpError:
            controlflow.system_error_exit(
                    2,
                    'enterprisemember requires Enterprise license')
        return [group['groupKey']['id'] for group in groups_to_get if group['relationType'] == 'DIRECT']
    else:
        groups_to_get = gapi.get_all_pages(
            ci.groups(),
            'list',
            'groups',
            message_attribute=['groupKey', 'id'],
            page_message=page_message,
            parent=parent,
            view='BASIC',
            pageSize=1000,
            fields='nextPageToken,groups(groupKey(id))')
        return [group['groupKey']['id'] for group in groups_to_get]

def get_membership_graph(member):
    ci = gapi_cloudidentity.build(CIGROUP_API_BETA)
    query = f"member_key_id == '{member}' && 'cloudidentity.googleapis.com/groups.discussion_forum' in labels"
    result = gapi.call(ci.groups().memberships(),
                     'getMembershipGraph',
                     parent='groups/-',
                     query=query)
    return result.get('response')

def print_members():
    ci = gapi_cloudidentity.build(CIGROUP_API_BETA)
    todrive = False
    gapi_directory_customer.setTrueCustomerId()
    parent = f'customers/{GC_Values[GC_CUSTOMER_ID]}'
    usemember = None
    roles = []
    titles = ['group']
    csvRows = []
    groups_to_get = []
    i = 3
    while i < len(sys.argv):
        myarg = sys.argv[i].lower().replace('_', '')
        if myarg == 'todrive':
            todrive = True
            i += 1
        elif myarg in ['role', 'roles']:
            for role in sys.argv[i + 1].lower().replace(',', ' ').split():
                if role in GROUP_ROLES_MAP:
                    roles.append(GROUP_ROLES_MAP[role])
                else:
                    controlflow.system_error_exit(
                        2,
                        f'{role} is not a valid role for "gam print group-members {myarg}"'
                    )
            i += 2
        elif myarg == 'enterprisemember':
            member = gam.convertUIDtoEmailAddress(sys.argv[i + 1], email_types=['user', 'group'])
            usemember = f"member_key_id == '{member}' && 'cloudidentity.googleapis.com/groups.discussion_forum' in labels"
            i += 2
        elif myarg in ['cigroup', 'cigroups']:
            group_email = gam.normalizeEmailAddressOrUID(sys.argv[i + 1])
            groups_to_get = [group_email]
            i += 2
        else:
            controlflow.invalid_argument_exit(sys.argv[i],
                                              'gam print cigroup-members')
    if not groups_to_get:
        groups_to_get = _get_groups_list(ci, usemember, parent)
    i = 0
    count = len(groups_to_get)
    for group_email in groups_to_get:
        i += 1

        sys.stderr.write(
            f'Getting members for {group_email}{gam.currentCountNL(i, count)}')
        group_id = group_email_to_id(ci, group_email)
        print(f'Getting members of cigroup {group_email}...')
        page_message = f' {gapi.got_total_items_first_last_msg("Members")}'
        group_members = gapi.get_all_pages(
            ci.groups().memberships(),
            'list',
            'memberships',
            soft_errors=True,
            parent=group_id,
            view='FULL',
            pageSize=500,
            page_message=page_message,
            message_attribute=[CIGROUP_MEMBERKEY, 'id'])
        #fields=f'nextPageToken,memberships({CIGROUP_MEMBERKEY},roles,createTime,updateTime)')
        if roles:
            group_members = filter_members_to_roles(group_members, roles)
        for member in group_members:
            # reduce role to a single value
            member['role'] = get_single_role(member.pop('roles'))
            member = utils.flatten_json(member)
            for title in member:
                if title not in titles:
                    titles.append(title)
            member['group'] = group_email
            csvRows.append(member)
    display.write_csv_file(csvRows, titles, 'Group Members', todrive)

def update():

    # Convert foo@googlemail.com to foo@gmail.com; eliminate periods in name for foo.bar@gmail.com
    def _cleanConsumerAddress(emailAddress, mapCleanToOriginal):
        atLoc = emailAddress.find('@')
        if atLoc > 0:
            if emailAddress[atLoc + 1:] in ['gmail.com', 'googlemail.com']:
                cleanEmailAddress = emailAddress[:atLoc].replace(
                    '.', '') + '@gmail.com'
                if cleanEmailAddress != emailAddress:
                    mapCleanToOriginal[cleanEmailAddress] = emailAddress
                    return cleanEmailAddress
        return emailAddress

    def _getRoleAndUsers():
        checkSuspended = None
        role = ROLE_MEMBER
        expireTime = None
        i = 5
        if sys.argv[i].lower() in GROUP_ROLES_MAP:
            role = GROUP_ROLES_MAP[sys.argv[i].lower()]
            i += 1
        if sys.argv[i].lower() in ['suspended', 'notsuspended']:
            checkSuspended = sys.argv[i].lower() == 'suspended'
            i += 1
        if sys.argv[i].lower() in ['expire', 'expires']:
            if role != ROLE_MEMBER:
                controlflow.invalid_argument_exit(
                    sys.argv[i], f'role {role}')
            expireTime = utils.get_time_or_delta_from_now(sys.argv[i+1])
            i += 2
        if sys.argv[i].lower() in usergroup_types:
            users_email = gam.getUsersToModify(entity_type=sys.argv[i].lower(),
                                               entity=sys.argv[i + 1],
                                               checkSuspended=checkSuspended,
                                               groupUserMembersOnly=False)
        else:
            users_email = [
                gam.normalizeEmailAddressOrUID(sys.argv[i],
                                               checkForCustomerId=True)
            ]
        return (role, expireTime, users_email)

    ci = gapi_cloudidentity.build(CIGROUP_API_BETA)
    group = sys.argv[3]
    myarg = sys.argv[4].lower()
    items = []
    if myarg in UPDATE_GROUP_SUBCMDS:
        group = gam.normalizeEmailAddressOrUID(group)
        if group.startswith('groups/'):
            parent = group
        else:
            parent = group_email_to_id(ci, group)
        if not parent:
            return
        if myarg == 'add':
            role, expireTime, users_email = _getRoleAndUsers()
            if len(users_email) > 1:
                sys.stderr.write(
                    f'Group: {group}, Will add {len(users_email)} {role}s.\n')
                for user_email in users_email:
                    item = [
                        'gam', 'update', 'cigroup', f'id:{parent}', 'add', role,
                    ]
                    if expireTime:
                        item.extend(['expires', expireTime])
                    item.append(user_email)
                    items.append(item)
            elif len(users_email) > 0:
                body = {
                    CIGROUP_MEMBERKEY: {
                        'id': users_email[0]
                    },
                    'roles': [{
                        'name': ROLE_MEMBER
                    }]
                }
                if role != ROLE_MEMBER:
                    body['roles'].append({'name': role})
                elif expireTime not in {None, NEVER_TIME}:
                    for role in body['roles']:
                        if role['name'] == ROLE_MEMBER:
                            role['expiryDetail'] = {'expireTime': expireTime}
                add_text = [f'as {role}']
                for i in range(2):
                    try:
                        gapi.call(
                            ci.groups().memberships(),
                            'create',
                            throw_reasons=[
                                gapi_errors.ErrorReason.FOUR_O_NINE,
                                gapi_errors.ErrorReason.MEMBER_NOT_FOUND,
                                gapi_errors.ErrorReason.RESOURCE_NOT_FOUND,
                                gapi_errors.ErrorReason.INVALID_MEMBER,
                                gapi_errors.ErrorReason.
                                CYCLIC_MEMBERSHIPS_NOT_ALLOWED
                            ],
                            parent=parent,
                            body=body)
                        print(
                            f' Group: {group}, {users_email[0]} Added {" ".join(add_text)}'
                        )
                        break
                    except (gapi_errors.GapiMemberNotFoundError,
                            gapi_errors.GapiResourceNotFoundError,
                            gapi_errors.GapiInvalidMemberError,
                            gapi_errors.GapiCyclicMembershipsNotAllowedError
                           ) as e:
                        print(
                            f' Group: {group}, {users_email[0]} Add {" ".join(add_text)} Failed: {str(e)}'
                        )
                        break
        elif myarg == 'sync':
            syncMembersSet = set()
            syncMembersMap = {}
            role, expireTime, users_email = _getRoleAndUsers()
            for user_email in users_email:
                if user_email in ('*', GC_Values[GC_CUSTOMER_ID]):
                    syncMembersSet.add(GC_Values[GC_CUSTOMER_ID])
                else:
                    syncMembersSet.add(
                        _cleanConsumerAddress(user_email.lower(),
                                              syncMembersMap))
            currentMembersSet = set()
            currentMembersMap = {}
            for current_email in gam.getUsersToModify(
                    entity_type='cigroup',
                    entity=group,
                    member_type=role,
                    groupUserMembersOnly=False):
                if current_email == GC_Values[GC_CUSTOMER_ID]:
                    currentMembersSet.add(current_email)
                else:
                    currentMembersSet.add(
                        _cleanConsumerAddress(current_email.lower(),
                                              currentMembersMap))
            to_add = [
                syncMembersMap.get(emailAddress, emailAddress)
                for emailAddress in syncMembersSet - currentMembersSet
            ]
            to_remove = [
                currentMembersMap.get(emailAddress, emailAddress)
                for emailAddress in currentMembersSet - syncMembersSet
            ]
            sys.stderr.write(
                f'Group: {group}, Will add {len(to_add)} and remove {len(to_remove)} {role}s.\n'
            )
            for user in to_add:
                item = ['gam', 'update', 'cigroup', f'id:{parent}', 'add',
                        role,]
                if role == ROLE_MEMBER and expireTime not in {None, NEVER_TIME}:
                    item.extend(['expires', expireTime])
                item.append(user)
                items.append(item)
            for user in to_remove:
                items.append([
                    'gam', 'update', 'cigroup', f'id:{parent}', 'remove', user
                ])
        elif myarg in ['delete', 'remove']:
            _, _, users_email = _getRoleAndUsers()
            if len(users_email) > 1:
                sys.stderr.write(
                    f'Group: {group}, Will remove {len(users_email)} emails.\n')
                for user_email in users_email:
                    items.append([
                        'gam', 'update', 'cigroup', f'id:{parent}', 'remove',
                        user_email
                    ])
            elif len(users_email) == 1:
                name = membership_email_to_id(ci, parent, users_email[0])
                try:
                    gapi.call(ci.groups().memberships(),
                              'delete',
                              throw_reasons=[
                                  gapi_errors.ErrorReason.MEMBER_NOT_FOUND,
                                  gapi_errors.ErrorReason.INVALID_MEMBER
                              ],
                              name=name)
                    print(f' Group: {group}, {users_email[0]} Removed')
                except (gapi_errors.GapiMemberNotFoundError,
                        gapi_errors.GapiInvalidMemberError) as e:
                    print(
                        f' Group: {group}, {users_email[0]} Remove Failed: {str(e)}'
                    )
        elif myarg == 'update':
            role, expireTime, users_email = _getRoleAndUsers()
            if len(users_email) > 1:
                sys.stderr.write(
                    f'Group: {group}, Will update {len(users_email)} {role}s.\n'
                )
                for user_email in users_email:
                    item = [
                        'gam', 'update', 'cigroup', f'id:{parent}', 'update',
                        role,]
                    if expireTime:
                        item.extend(['expires', expireTime])
                    item.append(user_email)
                    items.append(item)
            elif len(users_email) > 0:
                name = membership_email_to_id(ci, parent, users_email[0])
                preUpdateRoles = []
                addRoles = []
                removeRoles = []
                postUpdateRoles = []
                member_roles = gapi.call(ci.groups().memberships(),
                                         'get',
                                         name=name,
                                         fields='roles').get('roles', [{'name': ROLE_MEMBER}])
                current_roles = [crole['name'] for crole in member_roles]
                # When upgrading role, strip any expiryDetail from member before role changes
                if role != ROLE_MEMBER:
                    for crole in member_roles:
                        if 'expiryDetail' in crole:
                            preUpdateRoles.append(
                                {'fieldMask': 'expiryDetail.expireTime',
                                 'membershipRole': {'name': ROLE_MEMBER,
                                                    'expiryDetail': {'expireTime': None}}})
                            break
                # When downgrading role or simply updating member expireTime, update expiryDetail after role changes
                elif expireTime:
                    postUpdateRoles.append(
                        {'fieldMask': 'expiryDetail.expireTime',
                         'membershipRole': {'name': role,
                                            'expiryDetail': {'expireTime':  expireTime if expireTime != NEVER_TIME else None}}})
                for crole in current_roles:
                    if crole not in {ROLE_MEMBER, role}:
                        removeRoles.append(crole)
                if role not in current_roles:
                    new_role = {'name': role}
                    if role == ROLE_MEMBER and expireTime not in {None, NEVER_TIME}:
                        new_role['expiryDetail'] = {'expireTime': expireTime}
                        postUpdateRoles = []
                    addRoles.append(new_role)
                bodys = []
                if preUpdateRoles:
                    bodys.append({'updateRolesParams': preUpdateRoles})
                if addRoles:
                    bodys.append({'addRoles': addRoles})
                if removeRoles:
                    bodys.append({'removeRoles': removeRoles})
                if postUpdateRoles:
                    bodys.append({'updateRolesParams': postUpdateRoles})
                for body in bodys:
                    try:
                        gapi.call(ci.groups().memberships(),
                                  'modifyMembershipRoles',
                                  throw_reasons=[
                                      gapi_errors.ErrorReason.MEMBER_NOT_FOUND,
                                      gapi_errors.ErrorReason.INVALID_MEMBER
                                  ],
                                  name=name,
                                  body=body)
                    except (gapi_errors.GapiMemberNotFoundError,
                            gapi_errors.GapiInvalidMemberError) as e:
                        print(
                            f' Group: {group}, {users_email[0]} Update to {role} Failed: {str(e)}'
                        )
                        break
                print(
                  f' Group: {group}, {users_email[0]} Updated to {role}'
                )

        else:  # clear
            roles = []
            i = 5
            while i < len(sys.argv):
                myarg = sys.argv[i].lower()
                if myarg.upper() in [ROLE_OWNER, ROLE_MANAGER, ROLE_MEMBER]:
                    roles.append(myarg.upper())
                    i += 1
                else:
                    controlflow.invalid_argument_exit(
                        sys.argv[i], 'gam update cigroup clear')
            if not roles:
                roles = [ROLE_MEMBER]
            group = gam.normalizeEmailAddressOrUID(group)
            member_type_message = f'{",".join(roles).lower()}s'
            sys.stderr.write(
                f'Getting {member_type_message} of {group} (may take some time for large groups)...\n'
            )
            page_message = gapi.got_total_items_msg(f'{member_type_message}',
                                                    '...')
            try:
                result = gapi.get_all_pages(
                    ci.groups().memberships(),
                    'list',
                    'memberships',
                    page_message=page_message,
                    throw_reasons=gapi_errors.MEMBERS_THROW_REASONS,
                    parent=parent,
                    fields=f'nextPageToken,memberships({CIGROUP_MEMBERKEY},roles)')
                result = filter_members_to_roles(result, roles)
                if not result:
                    print('Group already has 0 members')
                    return
                users_email = [member[CIGROUP_MEMBERKEY]['id'] for member in result]
                sys.stderr.write(
                    f'Group: {group}, Will remove {len(users_email)} {", ".join(roles).lower()}s.\n'
                )
                for user_email in users_email:
                    items.append([
                        'gam', 'update', 'cigroup', group, 'remove', user_email
                    ])
            except (gapi_errors.GapiGroupNotFoundError,
                    gapi_errors.GapiDomainNotFoundError,
                    gapi_errors.GapiInvalidError,
                    gapi_errors.GapiForbiddenError):
                gam.entityUnknownWarning('Group', group, 0, 0)
        if items:
            gam.run_batch(items)
    else:
        i = 4
        body = {}
        sec_body = {}
        while i < len(sys.argv):
            myarg = sys.argv[i].lower().replace('_', '')
            if myarg == 'name':
                body['displayName'] = sys.argv[i + 1]
                i += 2
            elif myarg == 'description':
                body['description'] = sys.argv[i + 1]
                i += 2
            elif myarg == 'security':
                body['labels'] = {
                    'cloudidentity.googleapis.com/groups.security': '',
                    'cloudidentity.googleapis.com/groups.discussion_forum': ''
                }
                i += 1
            elif myarg == 'dynamicsecurity':
                body['labels'] = {
                    'cloudidentity.googleapis.com/groups.dynamic': '',
                    'cloudidentity.googleapis.com/groups.security': '',
                    'cloudidentity.googleapis.com/groups.discussion_forum': ''
                }
                i += 1
            elif myarg in ['dynamic']:
                body['dynamicGroupMetadata'] = {
                    'queries': [{
                        'query': sys.argv[i + 1],
                        'resourceType': 'USER'
                    }]
                }
                i += 2
            elif myarg in ['memberrestriction', 'memberrestrictions']:
                query = sys.argv[i + 1]
                member_types = {
                  'USER': '1',
                  'SERVICE_ACCOUNT': '2',
                  'GROUP': '3',
                  }
                for key, val in member_types.items():
                    query = query.replace(key, val)
                sec_body['memberRestriction'] = {'query': query}
                i += 2
            else:
                controlflow.invalid_argument_exit(sys.argv[i],
                                                  'gam update cigroup')
        if body:
            updateMask = ','.join(body.keys())
            name = group_email_to_id(ci, group)
            print(f'Updating group {group}')
            gapi.call(ci.groups(),
                      'patch',
                      updateMask=updateMask,
                      name=name,
                      body=body)
        if sec_body:
            updateMask = 'member_restriction.query'
            # it seems like a bug that API requires /securitySettings
            # appended to name. We'll see if Google servers change this
            # at some point.
            name = f'{group_email_to_id(ci, group)}/securitySettings'
            print(f'Updating group {group} security settings')
            gapi.call(ci.groups(),
                    'updateSecuritySettings',
                    name=name,
                    updateMask=updateMask,
                    body=sec_body)

def group_email_to_id(ci, group, i=0, count=0):
    group = gam.normalizeEmailAddressOrUID(group)
    try:
        return gapi.call(ci.groups(),
                         'lookup',
                         throw_reasons=gapi_errors.GROUP_GET_THROW_REASONS,
                         retry_reasons=gapi_errors.GROUP_GET_RETRY_REASONS,
                         groupKey_id=group,
                         fields='name').get('name')
    except (gapi_errors.GapiGroupNotFoundError,
            gapi_errors.GapiDomainNotFoundError,
            gapi_errors.GapiDomainCannotUseApisError,
            gapi_errors.GapiForbiddenError, gapi_errors.GapiBadRequestError):
        gam.entityUnknownWarning('Group', group, i, count)
        return None

def group_id_to_email(ci, group_id):
    return gapi.call(ci.groups(),
                         'get',
                         fields='groupKey/id',
                         name=group_id).get('groupKey', {}).get('id')

def membership_email_to_id(ci, parent, membership, i=0, count=0):
    membership = gam.normalizeEmailAddressOrUID(membership)
    try:
        return gapi.call(ci.groups().memberships(),
                         'lookup',
                         throw_reasons=gapi_errors.GROUP_GET_THROW_REASONS,
                         retry_reasons=gapi_errors.GROUP_GET_RETRY_REASONS,
                         parent=parent,
                         memberKey_id=membership,
                         fields='name').get('name')
    except (gapi_errors.GapiGroupNotFoundError,
            gapi_errors.GapiDomainNotFoundError,
            gapi_errors.GapiDomainCannotUseApisError,
            gapi_errors.GapiForbiddenError, gapi_errors.GapiBadRequestError):
        gam.entityUnknownWarning('Membership', membership, i, count)
        return None

def get_single_role(roles):
    ''' returns the highest role of member '''
    roles = [role.get('name') for role in roles]
    if not roles:
        return ROLE_MEMBER
    for a_role in [ROLE_OWNER, ROLE_MANAGER, ROLE_MEMBER]:
        if a_role in roles:
            return a_role
    return roles[0]

def filter_members_to_roles(members, roles):
    filtered_members = []
    for member in members:
        role = get_single_role(member.get('roles', []))
        if role in roles:
            filtered_members.append(member)
    return filtered_members


text:
package debop4s.mongo.spring

trait MongoCachePrefix {
  def prefix(cacheName: String): String
}

object MongoCachePrefix {

  val DEFAULT_DELIMETER = ":"

  def apply(): MongoCachePrefix = new DefaultMongoCachePrefix()

  def apply(delimeter: Option[String]) = new DefaultMongoCachePrefix(delimeter)
}

class DefaultMongoCachePrefix(val delimeter: Option[String] = Some(MongoCachePrefix.DEFAULT_DELIMETER))
  extends MongoCachePrefix {

  override def prefix(cacheName: String): String = {
    delimeter.fold(cacheName) { d => cacheName.concat(d) }
  }
}

redpajama_set_name: RedPajamaGithub


text:
package edu.latrobe.blaze

import breeze.linalg.{*, DenseMatrix, DenseVector}
import edu.latrobe._
import edu.latrobe.blaze.gradientchecks._
import edu.latrobe.blaze.modules._
import edu.latrobe.sizes._
import org.scalatest._
import TestUtils._

final class TestSequence extends FlatSpec with Matchers {

  "FullyConnected + MSE" should "pass gradient checking" in {
    val x = RealArrayTensor(Size1(1, 3), 3, Array(
      1.0f, 2.0f, 3.0f, // sample 0
      4.0f, 5.0f, 6.0f, // sample 1
      8.0f, 9.0f, 0.0f  // sample 2
    ))
    val b = DenseVector(
      -10.0f, // neuron 0
      -20.0f  // neuron 1
    )
    val w = new DenseMatrix(3, 2, Array(
      0.1f, 0.2f, 0.3f, // neuron 0
      0.4f, 0.5f, 0.6f  // neuron 1
    ))
    val y = RealArrayTensor.derive(Size1(1, 2), {
      val tmp: DenseMatrix[Real] = w.t * x.valuesMatrix
      tmp(::, *) += b
      tmp
    })
    val r = RealArrayTensor.ones(Size1(1, 2), 3)

    // Build sequence and gradient checker.
    val seq = SequenceBuilder(
      LinearFilterBuilder(2),
      AddBiasBuilder(),
      SquaredErrorConstraintBuilder()
    ).build(BuildHints.derive(x))
    MatrixEx.copy(seq.weightBuffer(0, 0).values,            w)
    VectorEx.copy(seq.weightBuffer(0, 0).values, w.size, 1, b)

    val gc = ProbeEntireBufferBuilder().build()

    // Run tests.
    val prediction = seq.predict(Training(0L), x, r)
    similarity(y, prediction.output) should be < tolerance0
    val res = gc(0L, seq, x, r)
    res.rating should be < tolerance1
  }

}


text:
{% extends "Finpy/base.html" %}

{% load bootstrap3 %}
{% load i18n %}

{% block content %}

{% if validlink %}

{% trans "Please enter your new password twice so we can verify you typed it in correctly." %}

<form method="post" class="form" action="">
  {% csrf_token %}
  {% bootstrap_form form %}
  {% buttons %}
  <button type="submit" class="btn btn-primary">
    {% bootstrap_icon "star" %} {% trans 'Change my password' %}
  </button>
  {% endbuttons %}

</form>

{% else %}

{% trans "The password reset link was invalid, possibly because it has already been used.  Please request a new password reset." %}

{% endif %}

{% endblock %}


text:
<md-card md-theme="" md-theme-watch>
    <md-card-title>
        <md-card-title-text>
            Card with image
            Medium
        </md-card-title-text>
        <md-card-title-media>

        </md-card-title-media>
    </md-card-title>
    <md-card-actions layout="row" layout-align="end center">
        <md-button aria-label="button">Action 1</md-button>
        <md-button aria-label="button">Action 2</md-button>
    </md-card-actions>
</md-card>


text:
using ClosedXML.Excel;
using NUnit.Framework;
using System.IO;
using System.Linq;

namespace ClosedXML_Tests.Excel
{
    [TestFixture]
    public class HeaderFooterTests
    {
        [Test]
        public void CanChangeWorksheetHeader()
        {
            var wb = new XLWorkbook();
            IXLWorksheet ws = wb.AddWorksheet("Sheet1");

            ws.PageSetup.Header.Center.AddText("Initial page header", XLHFOccurrence.EvenPages);

            var ms = new MemoryStream();
            wb.SaveAs(ms, true);

            wb = new XLWorkbook(ms);
            ws = wb.Worksheets.First();

            ws.PageSetup.Header.Center.Clear();
            ws.PageSetup.Header.Center.AddText("Changed header", XLHFOccurrence.EvenPages);

            wb.SaveAs(ms, true);

            wb = new XLWorkbook(ms);
            ws = wb.Worksheets.First();

            var newHeader = ws.PageSetup.Header.Center.GetText(XLHFOccurrence.EvenPages);
            Assert.AreEqual("Changed header", newHeader);
        }
    }
}


text:
from pymisp import PyMISP
from keys import misp_url, misp_key,misp_verifycert
import argparse
import os
import json

def init(url, key):
    return PyMISP(url, key, misp_verifycert, 'json')

def search(m, quiet, url, controller, out=None, **kwargs):
    result = m.search(controller, **kwargs)
    if quiet:
        for e in result['response']:
            print('{}{}{}\n'.format(url, '/events/view/', e['Event']['id']))
    elif out is None:
        for e in result['response']:
            print(json.dumps(e) + '\n')
    else:
        with open(out, 'w') as f:
            for e in result['response']:
                f.write(json.dumps(e) + '\n')

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Get all the events matching a value for a given param.')
    parser.add_argument("-p", "--param", required=True, help="Parameter to search (e.g. category, org, etc.)")
    parser.add_argument("-s", "--search", required=True, help="String to search.")
    parser.add_argument("-a", "--attributes", action='store_true', help="Search attributes instead of events")
    parser.add_argument("-q", "--quiet", action='store_true', help="Only display URLs to MISP")
    parser.add_argument("-o", "--output", help="Output file")

    args = parser.parse_args()

    if args.output is not None and os.path.exists(args.output):
        print('Output file already exists, abort.')
        exit(0)

    misp = init(misp_url, misp_key)
    kwargs = {args.param: args.search}

    if args.attributes:
        controller='attributes'
    else:
        controller='events'

    search(misp, args.quiet, misp_url, controller, args.output, **kwargs)


text:
//
// CmsSignerTests.cs
//
// Author: Jeffrey Stedfast <jestedfa@microsoft.com>
//
// Copyright (c) 2013-2022 .NET Foundation and Contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

using System;
using System.IO;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;

using NUnit.Framework;

using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Security;

using MimeKit.Cryptography;

using X509Certificate = Org.BouncyCastle.X509.X509Certificate;
using X509KeyUsageFlags = MimeKit.Cryptography.X509KeyUsageFlags;

namespace UnitTests.Cryptography {
	[TestFixture]
	public class CmsSignerTests
	{
		[Test]
		public void TestArgumentExceptions ()
		{
			var signer = new CmsSigner (Path.Combine (TestHelper.ProjectDir, "TestData", "smime", "smime.pfx"), "no.secret");
			var certificate = new X509Certificate2 (signer.Certificate.GetEncoded ());
			var chain = new[] { DotNetUtilities.FromX509Certificate (certificate) };
			AsymmetricCipherKeyPair keyPair;

			using (var stream = new StreamReader (Path.Combine (TestHelper.ProjectDir, "TestData", "dkim", "example.pem"))) {
				var reader = new PemReader (stream);

				keyPair = reader.ReadObject () as AsymmetricCipherKeyPair;
			}

			Assert.Throws<ArgumentException> (() => new CmsSigner (certificate));
			Assert.Throws<ArgumentException> (() => new CmsSigner (chain, keyPair.Public));

			Assert.Throws<ArgumentNullException> (() => new CmsSigner ((IEnumerable<X509Certificate>) null, signer.PrivateKey));
			Assert.Throws<ArgumentException> (() => new CmsSigner (new X509Certificate[0], signer.PrivateKey));
			Assert.Throws<ArgumentException> (() => new CmsSigner (signer.CertificateChain, keyPair.Public));
			Assert.Throws<ArgumentNullException> (() => new CmsSigner (signer.CertificateChain, null));

			Assert.Throws<ArgumentNullException> (() => new CmsSigner ((X509Certificate) null, signer.PrivateKey));
			Assert.Throws<ArgumentException> (() => new CmsSigner (signer.Certificate, keyPair.Public));
			Assert.Throws<ArgumentNullException> (() => new CmsSigner (signer.Certificate, null));

			Assert.Throws<ArgumentNullException> (() => new CmsSigner ((X509Certificate2) null));

			Assert.Throws<ArgumentNullException> (() => new CmsSigner ((Stream) null, "password"));
			Assert.Throws<ArgumentNullException> (() => new CmsSigner (Stream.Null, null));

			Assert.Throws<ArgumentNullException> (() => new CmsSigner ((string) null, "password"));
			Assert.Throws<ArgumentNullException> (() => new CmsSigner ("fileName", null));
		}

		static void LoadPkcs12 (string path, string password, out List<X509Certificate> certificates, out AsymmetricKeyParameter privateKey)
		{
			certificates = null;
			privateKey = null;

			using (var stream = File.OpenRead (path)) {
				var pkcs12 = new Pkcs12Store (stream, password.ToCharArray ());

				foreach (string alias in pkcs12.Aliases) {
					if (!pkcs12.IsKeyEntry (alias))
						continue;

					var chain = pkcs12.GetCertificateChain (alias);
					var key = pkcs12.GetKey (alias);

					if (!key.Key.IsPrivate || chain.Length == 0)
						continue;

					var flags = chain[0].Certificate.GetKeyUsageFlags ();

					if (flags != X509KeyUsageFlags.None && (flags & SecureMimeContext.DigitalSignatureKeyUsageFlags) == 0)
						continue;

					certificates = new List<X509Certificate> ();
					certificates.Add (chain[0].Certificate);
					privateKey = key.Key;

					foreach (var entry in chain)
						certificates.Add (entry.Certificate);

					return;
				}
			}
		}

		[Test]
		public void TestConstructors ()
		{
			var path = Path.Combine (TestHelper.ProjectDir, "TestData", "smime", "smime.pfx");
			List<X509Certificate> certificates;
			AsymmetricKeyParameter key;
			var password = "no.secret";
			CmsSigner signer;

			try {
				signer = new CmsSigner (path, password);
			} catch (Exception ex) {
				Assert.Fail (".ctor (string, string): {0}", ex.Message);
			}

			try {
				using (var stream = File.OpenRead (path))
					signer = new CmsSigner (stream, password);
			} catch (Exception ex) {
				Assert.Fail (".ctor (Stream, string): {0}", ex.Message);
			}

			LoadPkcs12 (path, password, out certificates, out key);

			try {
				signer = new CmsSigner (certificates, key);
			} catch (Exception ex) {
				Assert.Fail (".ctor (IEnumerable<X509Certificate>, AsymmetricKeyParameter): {0}", ex.Message);
			}

			try {
				signer = new CmsSigner (certificates[0], key);
			} catch (Exception ex) {
				Assert.Fail (".ctor (X509Certificate, AsymmetricKeyParameter): {0}", ex.Message);
			}

			try {
				signer = new CmsSigner (new X509Certificate2 (path, password, X509KeyStorageFlags.Exportable));
			} catch (Exception ex) {
				Assert.Fail (".ctor (X509Certificate2): {0}", ex);
			}
		}

		[Test]
		public void TestDefaultValues ()
		{
			var path = Path.Combine (TestHelper.ProjectDir, "TestData", "smime", "smime.pfx");
			List<X509Certificate> certificates;
			AsymmetricKeyParameter key;
			var password = "no.secret";
			CmsSigner signer;

			signer = new CmsSigner (path, password);
			Assert.AreEqual (SubjectIdentifierType.IssuerAndSerialNumber, signer.SignerIdentifierType, "new CmsSigner (string, string)");
			Assert.IsNull (signer.RsaSignaturePadding, "RsaSignaturePadding");

			using (var stream = File.OpenRead (path))
				signer = new CmsSigner (stream, password);
			Assert.AreEqual (SubjectIdentifierType.IssuerAndSerialNumber, signer.SignerIdentifierType, "new CmsSigner (Stream, string)");
			Assert.IsNull (signer.RsaSignaturePadding, "RsaSignaturePadding");

			LoadPkcs12 (path, password, out certificates, out key);

			signer = new CmsSigner (certificates, key);
			Assert.AreEqual (SubjectIdentifierType.IssuerAndSerialNumber, signer.SignerIdentifierType, "new CmsSigner (chain, key)");
			Assert.IsNull (signer.RsaSignaturePadding, "RsaSignaturePadding");

			signer = new CmsSigner (certificates[0], key);
			Assert.AreEqual (SubjectIdentifierType.IssuerAndSerialNumber, signer.SignerIdentifierType, "new CmsSigner (certificate, key)");
			Assert.IsNull (signer.RsaSignaturePadding, "RsaSignaturePadding");

			signer = new CmsSigner (new X509Certificate2 (path, password, X509KeyStorageFlags.Exportable));
			Assert.AreEqual (SubjectIdentifierType.IssuerAndSerialNumber, signer.SignerIdentifierType, "new CmsSigner (X509Certificate2)");
			Assert.IsNull (signer.RsaSignaturePadding, "RsaSignaturePadding");
		}

		[Test]
		public void TestSignerIdentifierType ()
		{
			var path = Path.Combine (TestHelper.ProjectDir, "TestData", "smime", "smime.pfx");
			List<X509Certificate> certificates;
			AsymmetricKeyParameter key;
			var password = "no.secret";
			CmsSigner signer;

			signer = new CmsSigner (path, password, SubjectIdentifierType.SubjectKeyIdentifier);
			Assert.AreEqual (SubjectIdentifierType.SubjectKeyIdentifier, signer.SignerIdentifierType, "new CmsSigner (string, string)");
			Assert.IsNull (signer.RsaSignaturePadding, "RsaSignaturePadding");

			using (var stream = File.OpenRead (path))
				signer = new CmsSigner (stream, password, SubjectIdentifierType.SubjectKeyIdentifier);
			Assert.AreEqual (SubjectIdentifierType.SubjectKeyIdentifier, signer.SignerIdentifierType, "new CmsSigner (Stream, string)");
			Assert.IsNull (signer.RsaSignaturePadding, "RsaSignaturePadding");

			LoadPkcs12 (path, password, out certificates, out key);

			signer = new CmsSigner (certificates, key, SubjectIdentifierType.SubjectKeyIdentifier);
			Assert.AreEqual (SubjectIdentifierType.SubjectKeyIdentifier, signer.SignerIdentifierType, "new CmsSigner (chain, key)");
			Assert.IsNull (signer.RsaSignaturePadding, "RsaSignaturePadding");

			signer = new CmsSigner (certificates[0], key, SubjectIdentifierType.SubjectKeyIdentifier);
			Assert.AreEqual (SubjectIdentifierType.SubjectKeyIdentifier, signer.SignerIdentifierType, "new CmsSigner (certificate, key)");
			Assert.IsNull (signer.RsaSignaturePadding, "RsaSignaturePadding");

			signer = new CmsSigner (new X509Certificate2 (path, password, X509KeyStorageFlags.Exportable), SubjectIdentifierType.SubjectKeyIdentifier);
			Assert.AreEqual (SubjectIdentifierType.SubjectKeyIdentifier, signer.SignerIdentifierType, "new CmsSigner (X509Certificate2)");
			Assert.IsNull (signer.RsaSignaturePadding, "RsaSignaturePadding");
		}

		[Test]
		public void TestRsaSignaturePadding ()
		{
			var path = Path.Combine (TestHelper.ProjectDir, "TestData", "smime", "smime.pfx");
			var signer = new CmsSigner (path, "no.secret");

			Assert.IsNull (signer.RsaSignaturePadding, "Default RsaSignaturePadding");

			signer.RsaSignaturePadding = RsaSignaturePadding.Pkcs1;
			Assert.AreEqual (RsaSignaturePadding.Pkcs1, signer.RsaSignaturePadding, "RsaSignaturePadding #1");

			signer.RsaSignaturePadding = RsaSignaturePadding.Pss;
			Assert.AreEqual (RsaSignaturePadding.Pss, signer.RsaSignaturePadding, "RsaSignaturePadding #2");

			signer.RsaSignaturePadding = RsaSignaturePadding.Pkcs1;
			Assert.AreEqual (RsaSignaturePadding.Pkcs1, signer.RsaSignaturePadding, "RsaSignaturePadding #3");

			signer.RsaSignaturePadding = RsaSignaturePadding.Pss;
			Assert.AreEqual (RsaSignaturePadding.Pss, signer.RsaSignaturePadding, "RsaSignaturePadding #4");
		}
	}
}


text:
'use strict';

// This sample uses the UUID library to generate the output filename.
const uuid = require('uuid');
const functions = require('firebase-functions');

const googleCloudProject = process.env.GOOGLE_CLOUD_PROJECT;
// The supportedLanguageCodes and outputBucket parameters take the value from
// environment variables by default.
const firebaseConfigured = typeof functions.config().playchat !== 'undefined';
const languageCodesParam = firebaseConfigured
  ? functions.config().playchat.supported_language_codes
  : process.env.SUPPORTED_LANGUAGE_CODES;
const supportedLanguageCodes = languageCodesParam.split(',');
const outputBucket = firebaseConfigured
  ? functions.config().playchat.output_bucket
  : process.env.OUTPUT_BUCKET;
const outputAudioEncoding = 'MP3';
const voiceSsmlGender = 'NEUTRAL';

// Declare the API clients as global variables to allow them to initiaze at cold start.
const {SpeechClient} = require('@google-cloud/speech');
const {Translate} = require('@google-cloud/translate').v2;
const {TextToSpeechClient} = require('@google-cloud/text-to-speech');
const {Storage} = require('@google-cloud/storage');

const speechToTextClient = new SpeechClient();
const textTranslationClient = new Translate({projectId: googleCloudProject});
const textToSpeechClient = new TextToSpeechClient();
const storageClient = new Storage({projectId: googleCloudProject});

exports.speechTranslate = functions.https.onRequest(
  async (request, response) => {
    const responseBody = {};

    try {
      await validateRequest(request);

      const inputEncoding = request.body.encoding;
      const inputSampleRateHertz = request.body.sampleRateHertz;
      const inputLanguageCode = request.body.languageCode;
      const inputAudioContent = request.body.audioContent;

      console.log(`Input encoding: ${inputEncoding}`);
      console.log(`Input sample rate hertz: ${inputSampleRateHertz}`);
      console.log(`Input language code: ${inputLanguageCode}`);

      // [START chain_cloud_calls]
      const [sttResponse] = await callSpeechToText(
        inputAudioContent,
        inputEncoding,
        inputSampleRateHertz,
        inputLanguageCode
      );

      // The data object contains one or more recognition
      // alternatives ordered by accuracy.
      const transcription = sttResponse.results
        .map(result => result.alternatives[0].transcript)
        .join('\n');
      responseBody.transcription = transcription;
      responseBody.gcsBucket = outputBucket;

      const translations = [];
      supportedLanguageCodes.forEach(async languageCode => {
        const translation = {languageCode: languageCode};
        const outputFilename =
          request.body.outputFilename ||
          `${uuid.v4()}.${outputAudioEncoding.toLowerCase()}`;

        try {
          const [textTranslation] = await callTextTranslation(
            languageCode,
            transcription
          );
          translation.text = textTranslation;

          const [{audioContent}] = await callTextToSpeech(
            languageCode,
            textTranslation
          );
          const path = `${languageCode}/${outputFilename}`;

          console.log('zzx', audioContent);

          await uploadToCloudStorage(path, audioContent);

          console.log(`Successfully translated input to ${languageCode}.`);
          translation.gcsPath = path;
          translations.push(translation);
          if (translations.length === supportedLanguageCodes.length) {
            responseBody.translations = translations;
            console.log(`Response: ${JSON.stringify(responseBody)}`);
            response.status(200).send(responseBody);
          }
        } catch (error) {
          console.error(
            `Partial error in translation to ${languageCode}: ${error}`
          );
          translation.error = error.message;
          translations.push(translation);
          if (translations.length === supportedLanguageCodes.length) {
            responseBody.translations = translations;
            console.log(`Response: ${JSON.stringify(responseBody)}`);
            response.status(200).send(responseBody);
          }
        }
      });
      // [END chain_cloud_calls]
    } catch (error) {
      console.error(error);
      response.status(400).send(error.message);
    }
  }
);

// [START call_speech_to_text]
const callSpeechToText = (
  audioContent,
  encoding,
  sampleRateHertz,
  languageCode
) => {
  console.log(`Processing speech from audio content in ${languageCode}.`);

  const request = {
    config: {
      encoding: encoding,
      sampleRateHertz: sampleRateHertz,
      languageCode: languageCode,
    },
    audio: {content: audioContent},
  };

  return speechToTextClient.recognize(request);
};
// [END call_speech_to_text]

// [START call_text_translation]
const callTextTranslation = (targetLangCode, data) => {
  console.log(`Translating text to ${targetLangCode}: ${data}`);

  return textTranslationClient.translate(data, targetLangCode);
};
// [END call_text_translation]

// [START call_text_to_speech]
const callTextToSpeech = (targetLocale, data) => {
  console.log(`Converting to speech in ${targetLocale}: ${data}`);

  const request = {
    input: {text: data},
    voice: {languageCode: targetLocale, ssmlGender: voiceSsmlGender},
    audioConfig: {audioEncoding: outputAudioEncoding},
  };

  return textToSpeechClient.synthesizeSpeech(request);
};
// [END call_text_to_speech]

// [START upload_to_cloud_storage]
const uploadToCloudStorage = (path, contents) => {
  console.log(`Uploading audio file to ${path}`);

  return storageClient.bucket(outputBucket).file(path).save(contents);
};
// [END upload_to_cloud_storage]

// [START validate_request]
const validateRequest = request => {
  return new Promise((resolve, reject) => {
    if (!request.body.encoding) {
      reject(new Error('Invalid encoding.'));
    }
    if (!request.body.sampleRateHertz || isNaN(request.body.sampleRateHertz)) {
      reject(new Error('Sample rate hertz must be numeric.'));
    }
    if (!request.body.languageCode) {
      reject(new Error('Invalid language code.'));
    }
    if (!request.body.audioContent) {
      reject(new Error('Invalid audio content.'));
    }

    resolve();
  });
};
// [END validate_request]


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet href="latest_ob.xsl" type="text/xsl"?>
<current_observation version="1.0"
	 xmlns:xsd="http://www.w3.org/2001/XMLSchema"
	 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	 xsi:noNamespaceSchemaLocation="http://www.weather.gov/view/current_observation.xsd">
	<credit>NOAA's National Weather Service</credit>
	<credit_URL>http://weather.gov/</credit_URL>
	<image>
		<url>http://weather.gov/images/xml_logo.gif</url>
		<title>NOAA's National Weather Service</title>
		<link>http://weather.gov</link>
	</image>
	<suggested_pickup>15 minutes after the hour</suggested_pickup>
	<suggested_pickup_period>60</suggested_pickup_period>
	<location>Monterey, Monterey Peninsula Airport, CA</location>
	<station_id>KMRY</station_id>
	<latitude>36.59056</latitude>
	<longitude>-121.8475</longitude>
	<observation_time>Last Updated on Jan 4 2016, 6:54 pm PST</observation_time>
        <observation_time_rfc822>Mon, 04 Jan 2016 18:54:00 -0800</observation_time_rfc822>
	<weather>Overcast</weather>
	<temperature_string>57.0 F (13.9 C)</temperature_string>
	<temp_f>57.0</temp_f>
	<temp_c>13.9</temp_c>
	<relative_humidity>67</relative_humidity>
	<wind_string>Southeast at 4.6 MPH (4 KT)</wind_string>
	<wind_dir>Southeast</wind_dir>
	<wind_degrees>130</wind_degrees>
	<wind_mph>4.6</wind_mph>
	<wind_kt>4</wind_kt>
	<pressure_string>1008.2 mb</pressure_string>
	<pressure_mb>1008.2</pressure_mb>
	<pressure_in>29.74</pressure_in>
	<dewpoint_string>46.0 F (7.8 C)</dewpoint_string>
	<dewpoint_f>46.0</dewpoint_f>
	<dewpoint_c>7.8</dewpoint_c>
	<windchill_string>57 F (14 C)</windchill_string>
      	<windchill_f>57</windchill_f>
      	<windchill_c>14</windchill_c>
	<visibility_mi>10.00</visibility_mi>
 	<icon_url_base>http://forecast.weather.gov/images/wtf/small/</icon_url_base>
	<two_day_history_url>http://www.weather.gov/data/obhistory/KMRY.html</two_day_history_url>
	<icon_url_name>ovc.png</icon_url_name>
	<ob_url>http://www.weather.gov/data/METAR/KMRY.1.txt</ob_url>
	<disclaimer_url>http://weather.gov/disclaimer.html</disclaimer_url>
	<copyright_url>http://weather.gov/disclaimer.html</copyright_url>
	<privacy_policy_url>http://weather.gov/notice.html</privacy_policy_url>
</current_observation>


text:
package org.jetbrains.plugins.gradle.model;

import com.google.common.base.Objects;

import java.io.File;

/**
 * @author Vladislav.Soroka
 * @since 12/24/2014
 */
public class DefaultExternalLibraryDependency extends AbstractExternalDependency implements ExternalLibraryDependency {

  private static final long serialVersionUID = 1L;

  private File file;
  private File source;
  private File javadoc;

  public DefaultExternalLibraryDependency() {
  }

  public DefaultExternalLibraryDependency(ExternalLibraryDependency dependency) {
    super(dependency);
    file = dependency.getFile();
    source = dependency.getSource();
    javadoc = dependency.getJavadoc();
  }

  @Override
  public File getFile() {
    return file;
  }

  public void setFile(File file) {
    this.file = file;
  }

  @Override
  public File getSource() {
    return source;
  }

  public void setSource(File source) {
    this.source = source;
  }

  @Override
  public File getJavadoc() {
    return javadoc;
  }

  public void setJavadoc(File javadoc) {
    this.javadoc = javadoc;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof DefaultExternalLibraryDependency)) return false;
    if (!super.equals(o)) return false;
    DefaultExternalLibraryDependency that = (DefaultExternalLibraryDependency)o;
    return Objects.equal(file, that.file);
  }

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

  @Override
  public String toString() {
    return "library '" + file + '\'';
  }
}


text:
layout: post
title: "GraphQL in ASP.NET Core with EF Core"
subtitle: "This post is about GraphQL in ASP.NET Core with EF Core. In the earlier post I discussed about integrating GraphQL in ASP.NET Core with HotChocolate. In this post I will discuss about how to use GraphQL on top EF Core."
date: 2021-11-16 00:00:00
categories: [AspNetCore,GraphQL,DotNet6,EFCore]
tags: [AspNetCore,GraphQL,DotNet6,EFCore]
author: "Anuraj"
image: /assets/images/2021/11/graphql_with_efcore1.png
---
This post is about GraphQL in ASP.NET Core with EF Core. In the earlier post I discussed about integrating GraphQL in ASP.NET Core with HotChocolate. In this post I will discuss about how to use GraphQL on top EF Core.

First I will be adding nuget packages required to work with EF Core - `Microsoft.EntityFrameworkCore.SqlServer` and `Microsoft.EntityFrameworkCore.Design` - this optional, since I am running migrations this package is required. Next I am modifying the code - adding `DbContext` and wiring the the DbContext to the application. Here is the DbContext code and updated Query class.

{% highlight CSharp %}
{% raw %}
public class Link
{
    public int Id { get; set; }
    public string Url { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public string ImageUrl { get; set; }
    public DateTime CreatedOn { get; set; }
    public ICollection<Tag> Tags { get; set; } = new List<Tag>();
}

public class Tag
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int LinkId { get; set; }
    public Link Link { get; set; }
}

public class BookmarkDbContext : DbContext
{
    public BookmarkDbContext(DbContextOptions options) : base(options)
    {
    }
    public DbSet<Link> Links { get; set; }
    public DbSet<Tag> Tags { get; set; }
}
{% endraw %}
{% endhighlight %}

I wrote the `OnModelCreating` method to seed the database. And I modified the code of the Program.cs and added the DbCotext class.

{% highlight CSharp %}
{% raw %}
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<BookmarkDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("BookmarkDbConnection")));
builder.Services.AddGraphQLServer().AddQueryType<Query>();
var app = builder.Build();

app.MapGet("/", () => "Hello World!");
app.UseRouting();
app.UseEndpoints(endpoints =>
{
    endpoints.MapGraphQL();
});
app.Run();
{% endraw %}
{% endhighlight %}

And `Query` class modified like this.

{% highlight CSharp %}
{% raw %}
public class Query
{
    public IQueryable<Link> Links([Service] BookmarkDbContext bookmarkDbContext)
        => bookmarkDbContext.Links;
}
{% endraw %}
{% endhighlight %}

In this code the `Service` attribute will help to inject the DbContext to the method. Next lets run the application and execute query.

{% highlight Javascript %}
{% raw %}
query {
  links{
    id
    url
    title
    imageUrl
    description
    createdOn
  }
}
{% endraw %}
{% endhighlight %}

We will be able to see result like this.

![Graph QL endpoint - Entity Framework Core]({{ site.url }}/assets/images/2021/11/graphql_with_efcore1.png)

Next let us remove some parameters in the query and run it again.

{% highlight Javascript %}
{% raw %}
query {
  links{
    title
    imageUrl
  }
}
{% endraw %}
{% endhighlight %}

We can see the result like this.

![Graph QL endpoint - Entity Framework Core]({{ site.url }}/assets/images/2021/11/graphql_with_efcore2.png)

And when we look into the EF Core log, we will be able to see the EF Core SQL Log like this.

![Entity Framework Core Log]({{ site.url }}/assets/images/2021/11/graphql_efcore_log.png)

In the Log, even though we are querying only two fields it is querying all the fields. We can fix this issue by adding a new nuget package `HotChocolate.Data.EntityFramework`. And modify the code like this.

{% highlight CSharp %}
{% raw %}
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<BookmarkDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("BookmarkDbConnection")));
builder.Services.AddGraphQLServer().AddQueryType<Query>().AddProjections().AddFiltering().AddSorting();
var app = builder.Build();

app.MapGet("/", () => "Hello World!");
app.UseRouting();
app.UseEndpoints(endpoints =>
{
    endpoints.MapGraphQL();
});
app.Run();
{% endraw %}
{% endhighlight %}

And modify the query class as well, decorate with the HotChocolate attributes for Projections, Filtering and Sorting.

{% highlight CSharp %}
{% raw %}
public class Query
{
    [UseProjection]
    [UseFiltering]
    [UseSorting]
    public IQueryable<Link> Links([Service] BookmarkDbContext bookmarkDbContext)
            => bookmarkDbContext.Links;
}
{% endraw %}
{% endhighlight %}

Now lets run the query again and check the logs.

![Entity Framework Core Log]({{ site.url }}/assets/images/2021/11/graphql_efcore_log_with_fix.png)

We can see only the required fields are queried. Not every fields in the table.

This way you can configure GraphQL in ASP.NET Core with EF Core. This code will fail, if you try to execute the GraphQL query with alias. We can use the `DbContextFactory` class to fix this issue. We will look into it in the next blog post.

Happy Programming :)


text:
/************************************************************************
*
* Flood Project © (2008-201x)
* Licensed under the simplified BSD license. All rights reserved.
*
************************************************************************/

#pragma once

#include "Graphics/API.h"
#include "Core/Math/Color.h"
#include "Core/Math/Vector.h"
#include "Core/Math/Matrix4x3.h"
#include "Core/Math/Matrix4x4.h"

NAMESPACE_GRAPHICS_BEGIN

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

class RenderTarget;

/**
 * A view is a region in a render target that can be rendered into.
 * It has an associated renderer that will render into the view.
 */

class API_GRAPHICS RenderView
{
	DECLARE_UNCOPYABLE(RenderView)

public:

	RenderView();
	~RenderView();

	// Gets/sets the render target of the view.
	ACCESSOR(RenderTarget, RenderTarget*, target)

	// Gets/sets the origin of the view.
	ACCESSOR(Origin, Vector2i, origin)

	// Gets/sets the size of the view.
	ACCESSOR(Size, Vector2i, size)

	// Gets/sets the clear color of the view.
	FLD_IGNORE ACCESSOR(ClearColor, const Color&, clearColor)

	// Gets/sets the depth (Z-order) priority of the view.
	ACCESSOR(DepthPriority, int, depthPriority)

	// Gets the aspect ratio of the view.
	float getAspectRatio() const;

	// Returns if a view has more priority than another.
	bool operator < (RenderView& view);

	// Handles render target resize.
	void handleRenderTargetResize();

public:

	// Origin of the view.
	Vector2i origin;

	// Size of the view.
	Vector2i size;

	// Render target.
	RenderTarget* target;

	// Background color.
	Color clearColor;

	// Depth priority.
	int depthPriority;

	// Projection matrix.
	Matrix4x4 projectionMatrix;

	// View matrix.
	Matrix4x3 viewMatrix;
};

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

NAMESPACE_GRAPHICS_END


text:
using UnityEngine;

public class PlayerInput : MonoBehaviour
{
    public void OnClickFromPrefabModification()
    {
     Debug.Log("OnClickFromPrefabModification");
    }

    public void OnClickFromPrefab()
    {
        Debug.Log("OnClickFromPrefab");
    }
}


text:
<?php declare(strict_types=1);

namespace Star\Component\DomainEvent\Serialization;

/**
 * Class implementing this interface will be allowed to being serialized in the payload.
 */
interface SerializableAttribute
{
    /**
     * @return string
     */
    public function toSerializableString(): string;
}


text:
package com.burgstaller.okhttp.basic;

import com.burgstaller.okhttp.digest.CachingAuthenticator;
import com.burgstaller.okhttp.digest.Credentials;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.Route;
import okhttp3.internal.platform.Platform;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

import static java.net.HttpURLConnection.HTTP_PROXY_AUTH;

/**
 * Standard HTTP basic authenticator.
 */
public class BasicAuthenticator implements CachingAuthenticator {
    private final Credentials credentials;
    private final Charset credentialCharset;
    private boolean proxy;

    public BasicAuthenticator(Credentials credentials, Charset credentialsCharset) {
        this.credentials = credentials;
        this.credentialCharset = credentialsCharset != null ? credentialsCharset : StandardCharsets.ISO_8859_1;
    }

    public BasicAuthenticator(Credentials credentials) {
        this(credentials, StandardCharsets.ISO_8859_1);
    }

    @Override
    public Request authenticate(Route route, Response response) throws IOException {
        final Request request = response.request();
        proxy = response.code() == HTTP_PROXY_AUTH;
        return authFromRequest(request);
    }

    private Request authFromRequest(Request request) {
        // prevent infinite loops when the password is wrong
        String header = proxy ? "Proxy-Authorization" : "Authorization";

        final String authorizationHeader = request.header(header);
        if (authorizationHeader != null && authorizationHeader.startsWith("Basic")) {
            Platform.get().log( "Previous basic authentication failed, returning null", Platform.WARN,null);
            return null;
        }
        String authValue = okhttp3.Credentials.basic(credentials.getUserName(), credentials.getPassword(), credentialCharset);
        return request.newBuilder()
                .header(header, authValue)
                .build();
    }

    @Override
    public Request authenticateWithState(Route route, Request request) throws IOException {
        return authFromRequest(request);
    }
}


text:
const _ = require("lodash");
const express = require("express");
const DynamicRecord = require("dynamic-record");

const router = express.Router();
const auth = require("../../utils/auth.js");
const restrict = require("../../utils/middlewares/restrict.js");
const CharError = require("../../utils/charError.js");
const Users = new DynamicRecord({
	tableSlug: "_users_auth"
});

// Route: {root}/api/users/...

// GET routes
// GET self

// Everything else should be restricted
// GET all users
router.get("/", restrict.toAdministrator, function(req, res){
	Users.all().then((users) => {
		_.each(users, function(el, i){
			delete el.data._id;
			delete el.data.hash;
		});

		res.json(users.data);
	});
});

// GET specific user
router.get("/:username", restrict.toAdministrator, function(req, res){
	Users.findBy({username: req.params.username}).then((user) => {
		// Remove internal ID and password hash, maybe split the db later
		delete user.data._id;
		delete user.data.hash;
		res.json(user.data);
	});
});

// POST routes
// POST to create a new user
router.post("/", restrict.toAdministrator, function(req, res, next){
	const reservedUsernames = ["Anonymous", "anonymous"];
	if(_.includes(reservedUsernames, req.body.username)){
		next(new CharError("Username not available", `"${req.body.username}" is a reserved username and cannot be registered`));
		return;
	}

	const data = req.body;
	auth.signup(data.username, data.password, "author").then((result) => {
		res.json({
			"message": `User "${result}" created`
		});
	}).catch((err) => {
		if(err.name == "MongoError" && err.code == 11000){
			// Duplicate username
			next(new CharError("Username not available", `Username "${req.body.username}" is already registered`, 409));
		}else{
			next(new CharError());
		}
	});
});

// POST to a user (edit existing user)
router.post("/:username", restrict.toAdministrator, function(req, res, next){
	if(req.params.username === req.body.username){
		if(req.body.role){
			const username = req.body.username;
			const newRole = req.body.role;
			Users.findBy({"username": username}).then((user) => {
				user.data.role = newRole;
				user.save().then((result) => {
					res.json({
						"message": `User "${user.data.username}" changed`
					});
				});
			});
		}else{
			next(new CharError("Request body missing field"));
		}
	}else{
		next(new CharError("Request body does not match route"));
	}
});

// DELETE routes
// DELETE specific user
router.delete("/:username", restrict.toAdministrator, function(req, res, next){
	const User = new DynamicRecord({
		tableSlug: "_users_auth"
	});

	User.findBy({"username": req.params.username}).then((user) => {
		return user.destroy();
	}).then((col) => {
		res.json({
			message: `User "${req.params.username}" deleted`
		});
	}).catch((err) => {
		if(err.message === "Model not saved in database yet."){
			next(new CharError("User does not exist", "The user to be deleted does not exist.", 404));
		}else{
			next(err);
		}
	});
});

module.exports = router;


text:
A collection of angularjs directives.

View on GitHub


text:
package com.management.service;

import java.util.List;

import com.management.bean.Book;
import com.management.dao.BookDao;
import com.management.factory.DaoFactory;

public class BookBusinessService {

	private BookDao dao = DaoFactory.getInstance().createDao(BookDao.class);

	/*
	 * 通过教师id查询
	 */
	public List<Book> findByTeacherId(int id) {
		return dao.findByTeacherId(id);
	}

	/*
	 * 增加
	 */
	public void add(Book book, int teacherId) {
		dao.add(book, teacherId);
	}

	public void addBooks(List<Book> books, int teacherId) {
		dao.addBooks(books, teacherId);
	}

	/*
	 * 更新
	 */
	public void update(Book book) {
		dao.update(book);
	}

	/*
	 * 删除
	 */
	public void delete(int id) {
		dao.delete(id);
	}
}


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

    <corners android:radius="100dp"/>
    <solid android:color="#D4D4D4"/>
</shape>


text:
class AssetsController < ApplicationController

  force_ssl

  before_action :logged_in_user, only: [:new, :create, :edit, :destroy]
  before_action :correct_user,   only: :destroy

  # GET /assets
  # GET /assets.json
  def index
    if logged_in?
      @assets_all = current_user.assets
      .search(params[:search])
      .paginate(page: params[:page]).order('serial ASC')

      @owner = current_user
      @users = User.where("owner_id = ?", current_user).order('lastname ASC')
      @asset_locations = AssetLocation.where("owner_id = ?", current_user).order('name ASC')

      respond_to do |format|
        format.html { render @assets }
        format.json { render json: @assets }
        format.js
      end

    else
      flash[:red] = "Please sign in."
      redirect_to login_url
    end

  end

  # GET /assets/1
  # GET /assets/1.json
  def show
    if logged_in?
      @owner = current_user
      @users = User.where("owner_id = ?", current_user).order('name ASC')
      @asset_locations = AssetLocation.where("owner_id = ?", current_user).order('name ASC')
      @asset = current_user.assets.find(params[:id])

      @user_fullname  = "#{@asset.user.lastname}, #{@asset.user.firstname}"
      @owner_fullname = "#{@asset.owner.lastname}, #{@asset.owner.firstname}"

    else
      flash[:red] = "Please sign in."
      redirect_to login_url
    end
  end

  # GET /assets/new
  def new
    if logged_in?
      @owner = current_user
      @users = User.where("owner_id = ?", current_user).order('lastname ASC')
      @asset_locations = AssetLocation.where("owner_id = ?", current_user).order('name ASC')
      @asset = Asset.new
    else
      flash[:red] = "Please sign in."
      redirect_to login_url
    end
  end

  # GET /assets/1/edit
  def edit
    if logged_in?
      @assets_all = current_user.assets.order('serial ASC')

      @users = User.where("owner_id = ?", current_user).order('lastname ASC')
      @asset_locations = AssetLocation.where("owner_id = ?", current_user).order('name ASC')
      @asset = Asset.where("owner_id = ?", current_user).find(params[:id])
    else
      flash[:red] = "Please sign in."
      redirect_to login_url
    end
  end

  # POST /assets
  # POST /assets.json
  def create
    @asset_locations = AssetLocation.where("owner_id = ?", current_user).order('name ASC')
    @asset = current_user.assets.create(asset_params)
    @owner = current_user
    if @asset.persisted?
      flash[:green] = "Asset created!"
      redirect_to assets_path
    else
      render root_path
    end
  end

  # PATCH/PUT /assets/1
  # PATCH/PUT /assets/1.json
  def update
    @asset_locations = AssetLocation.where("owner_id = ?", current_user).order('name ASC')
    @users = User.where("owner_id = ?", current_user).order('lastname ASC')
    @asset = current_user.assets.find(params[:id])
    if @asset.update_attributes(asset_params)
      flash[:green] = "Asset was successfully updated."
      redirect_to @asset
    else
      render :edit
    end
  end

  # DELETE /assets/1
  # DELETE /assets/1.json
  def destroy
    @asset.destroy
    respond_to do |format|
      format.html { redirect_to assets_url, notice: 'Asset was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private

    def asset_params
      params.require(:asset).permit(
        :serial,
        :brand,
        :kind,
        :date_acquired,
        :user_id,
        :comment,
        :ware,
        :asset_location_id,
        :recycled,
        :owner_id
      )
    end

    def correct_user
      @asset = current_user.assets.find_by(id: params[:id])
      redirect_to root_url if @asset.nil?
    end

end


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Hedwigia 43: 143 (1904)

#### Original name
Yoshinagaia quercus Henn., 1904

### Remarks
null


text:
layout: post
title: "Oracle 18c"
category: Oracle
tags: Oracle 18c vagrant Box Linux
---

* content
{:toc}

Vagrant + Oracle Linux 7.4 + Oracle Database 18c + Create DB

How to install Database 18c in Oracle Linux 7.4?

Oracle Database 18c Enterprise Edition Release 18.0.0.0.0 - Production

![oracle18c_version]({{ "/files/Oracle/18c/18c.png"}})

#### Oracle Linux 7.4 Install

Use vagrant box to install

	http://yum.oracle.com/boxes/
	Oracle Linux 6.9 (8-FEB-2018) 367MB
	Oracle Linux 7.4 (26-JAN-2018) 425MB  ===========>Download this and Use this One.

#### Oracle Database 18c's Installation

Unitl now, regarding oracle 18c, only the exadata packages are available.

[Oracle Software Delivery Cloud](https://edelivery.oracle.com/)

	Oracle Database 18.0.0.0.0
		Oracle Database Client 18.0.0.0.0 (1.3 GB)
		Oracle Database (Exadata Only) 18.0.0.0.0 (3.5 GB)
		Oracle Database Grid Infrastructure 18.0.0.0.0 (3.3 GB)

#### Oracle Database 18c Create Database

The specific methods for creating a database are:
  ● With Database Configuration Assistant (DBCA), a graphical tool.
  ● With the CREATE DATABASE SQL statement.

This time, I use create database sql statement to create oracle 18c database.

#### All the works are done

Checking...

	[oracle@database18c ~]$
	[oracle@database18c ~]$ export ORACLE_SID=PRODCDB; sqlplus / as sysdba
	SQL*Plus: Release 18.0.0.0.0 Production on Thu Mar 1 17:28:53 2018
	Version 18.1.0.0.0
	Copyright (c) 1982, 2017, Oracle.  All rights reserved.
	Connected to:
	Oracle Database 18c Enterprise Edition Release 18.0.0.0.0 - Production
	Version 18.1.0.0.0
	SQL> select * from v$version;
	BANNER
	--------------------------------------------------------------------------------
	BANNER_FULL
	--------------------------------------------------------------------------------
	BANNER_LEGACY
	--------------------------------------------------------------------------------
		CON_ID
	----------
	Oracle Database 18c Enterprise Edition Release 18.0.0.0.0 - Production
	Oracle Database 18c Enterprise Edition Release 18.0.0.0.0 - Production
	Version 18.1.0.0.0
	Oracle Database 18c Enterprise Edition Release 18.0.0.0.0 - Production
	BANNER
	--------------------------------------------------------------------------------
	BANNER_FULL
	--------------------------------------------------------------------------------
	BANNER_LEGACY
	--------------------------------------------------------------------------------
		CON_ID
	----------
	SQL> show pdbs;
		CON_ID CON_NAME                       OPEN MODE  RESTRICTED
	---------- ------------------------------ ---------- ----------
			 2 PDB$SEED                       READ ONLY  NO
	SQL>

#### Detail install step

Please confirm with this pdf file.

[OracleDatabase18c](/files/Oracle/18c/Oracle18c.pdf)

++++++++++++++++ EOF LinHong ++++++++++++++++


text:
package org.apache.geronimo.main;

import java.io.File;
import java.net.URI;

public class ServerInfo {

    private File base;
    private URI baseURI;
    private File baseServer;
    private URI baseServerURI;

    public ServerInfo(File geronimoHome, File geronimoBase) {
        this.base = geronimoHome;
        this.baseURI = base.toURI();
        this.baseServer = geronimoBase;
        this.baseServerURI = baseServer.toURI();
    }

    public String resolvePath(String filename) {
        return resolve(filename).getAbsolutePath();
    }

    public String resolveServerPath(String filename) {
        return resolveServer(filename).getAbsolutePath();
    }

    public File resolve(String filename) {
        return resolveWithBase(base, filename);
    }

    public File resolveServer(String filename) {
        return resolveWithBase(baseServer, filename);
    }

    public URI resolve(URI uri) {
        return baseURI.resolve(uri);
    }

    public URI resolveServer(URI uri) {
        return baseServerURI.resolve(uri);
    }

    private File resolveWithBase(File baseDir, String filename) {
        File file = new File(filename);
        if (file.isAbsolute()) {
            return file;
        }
        return new File(baseDir, filename);
    }

    public File getBase() {
        return base;
    }

    public File getBaseServer() {
        return baseServer;
    }

}


text:
/* this ALWAYS GENERATED file contains the definitions for the interfaces */

 /* File created by MIDL compiler version 6.00.0361 */
/* Compiler settings for certmod.idl:
    Oicf, W1, Zp8, env=Win32 (32b run)
    protocol : dce , ms_ext, c_ext, robust
    error checks: allocation ref bounds_check enum stub_data
    VC __declspec() decoration level:
         __declspec(uuid()), __declspec(selectany), __declspec(novtable)
         DECLSPEC_UUID(), MIDL_INTERFACE()
*/
//@@MIDL_FILE_HEADING(  )

#pragma warning( disable: 4049 )  /* more than 64k source lines */

/* verify that the <rpcndr.h> version is high enough to compile this file*/
#ifndef __REQUIRED_RPCNDR_H_VERSION__
#define __REQUIRED_RPCNDR_H_VERSION__ 475
#endif

#include "rpc.h"
#include "rpcndr.h"

#ifndef __RPCNDR_H_VERSION__
#error this stub requires an updated version of <rpcndr.h>
#endif // __RPCNDR_H_VERSION__

#ifndef COM_NO_WINDOWS_H
#include "windows.h"
#include "ole2.h"
#endif /*COM_NO_WINDOWS_H*/

#ifndef __certmod_h__
#define __certmod_h__

#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif

/* Forward Declarations */

#ifndef __ICertManageModule_FWD_DEFINED__
#define __ICertManageModule_FWD_DEFINED__
typedef interface ICertManageModule ICertManageModule;
#endif 	/* __ICertManageModule_FWD_DEFINED__ */

/* header files for imported files */
#include "wtypes.h"
#include "oaidl.h"

#ifdef __cplusplus
extern "C"{
#endif

void * __RPC_USER MIDL_user_allocate(size_t);
void __RPC_USER MIDL_user_free( void * );

/* interface __MIDL_itf_certmod_0000 */
/* [local] */

#define	CMM_REFRESHONLY	( 0x1 )

#define	CMM_READONLY	( 0x2 )

const WCHAR wszCMM_PROP_NAME[  ]	=	L"Name";

const WCHAR wszCMM_PROP_DESCRIPTION[  ]	=	L"Description";

const WCHAR wszCMM_PROP_COPYRIGHT[  ]	=	L"Copyright";

const WCHAR wszCMM_PROP_FILEVER[  ]	=	L"File Version";

const WCHAR wszCMM_PROP_PRODUCTVER[  ]	=	L"Product Version";

const WCHAR wszCMM_PROP_DISPLAY_HWND[  ]	=	L"HWND";

const WCHAR wszCMM_PROP_ISMULTITHREADED[  ]	=	L"IsMultiThreaded";

extern RPC_IF_HANDLE __MIDL_itf_certmod_0000_v0_0_c_ifspec;
extern RPC_IF_HANDLE __MIDL_itf_certmod_0000_v0_0_s_ifspec;

#ifndef __ICertManageModule_INTERFACE_DEFINED__
#define __ICertManageModule_INTERFACE_DEFINED__

/* interface ICertManageModule */
/* [unique][helpstring][dual][uuid][object] */

EXTERN_C const IID IID_ICertManageModule;

#if defined(__cplusplus) && !defined(CINTERFACE)

    MIDL_INTERFACE("e7d7ad42-bd3d-11d1-9a4d-00c04fc297eb")
    ICertManageModule : public IDispatch
    {
    public:
        virtual HRESULT STDMETHODCALLTYPE GetProperty(
            /* [in] */ const BSTR strConfig,
            /* [in] */ BSTR strStorageLocation,
            /* [in] */ BSTR strPropertyName,
            /* [in] */ LONG Flags,
            /* [retval][out] */ VARIANT *pvarProperty) = 0;

        virtual HRESULT STDMETHODCALLTYPE SetProperty(
            /* [in] */ const BSTR strConfig,
            /* [in] */ BSTR strStorageLocation,
            /* [in] */ BSTR strPropertyName,
            /* [in] */ LONG Flags,
            /* [in] */ const VARIANT *pvarProperty) = 0;

        virtual HRESULT STDMETHODCALLTYPE Configure(
            /* [in] */ const BSTR strConfig,
            /* [in] */ BSTR strStorageLocation,
            /* [in] */ LONG Flags) = 0;

    };

#else 	/* C style interface */

    typedef struct ICertManageModuleVtbl
    {
        BEGIN_INTERFACE

        HRESULT ( STDMETHODCALLTYPE *QueryInterface )(
            ICertManageModule * This,
            /* [in] */ REFIID riid,
            /* [iid_is][out] */ void **ppvObject);

        ULONG ( STDMETHODCALLTYPE *AddRef )(
            ICertManageModule * This);

        ULONG ( STDMETHODCALLTYPE *Release )(
            ICertManageModule * This);

        HRESULT ( STDMETHODCALLTYPE *GetTypeInfoCount )(
            ICertManageModule * This,
            /* [out] */ UINT *pctinfo);

        HRESULT ( STDMETHODCALLTYPE *GetTypeInfo )(
            ICertManageModule * This,
            /* [in] */ UINT iTInfo,
            /* [in] */ LCID lcid,
            /* [out] */ ITypeInfo **ppTInfo);

        HRESULT ( STDMETHODCALLTYPE *GetIDsOfNames )(
            ICertManageModule * This,
            /* [in] */ REFIID riid,
            /* [size_is][in] */ LPOLESTR *rgszNames,
            /* [in] */ UINT cNames,
            /* [in] */ LCID lcid,
            /* [size_is][out] */ DISPID *rgDispId);

        /* [local] */ HRESULT ( STDMETHODCALLTYPE *Invoke )(
            ICertManageModule * This,
            /* [in] */ DISPID dispIdMember,
            /* [in] */ REFIID riid,
            /* [in] */ LCID lcid,
            /* [in] */ WORD wFlags,
            /* [out][in] */ DISPPARAMS *pDispParams,
            /* [out] */ VARIANT *pVarResult,
            /* [out] */ EXCEPINFO *pExcepInfo,
            /* [out] */ UINT *puArgErr);

        HRESULT ( STDMETHODCALLTYPE *GetProperty )(
            ICertManageModule * This,
            /* [in] */ const BSTR strConfig,
            /* [in] */ BSTR strStorageLocation,
            /* [in] */ BSTR strPropertyName,
            /* [in] */ LONG Flags,
            /* [retval][out] */ VARIANT *pvarProperty);

        HRESULT ( STDMETHODCALLTYPE *SetProperty )(
            ICertManageModule * This,
            /* [in] */ const BSTR strConfig,
            /* [in] */ BSTR strStorageLocation,
            /* [in] */ BSTR strPropertyName,
            /* [in] */ LONG Flags,
            /* [in] */ const VARIANT *pvarProperty);

        HRESULT ( STDMETHODCALLTYPE *Configure )(
            ICertManageModule * This,
            /* [in] */ const BSTR strConfig,
            /* [in] */ BSTR strStorageLocation,
            /* [in] */ LONG Flags);

        END_INTERFACE
    } ICertManageModuleVtbl;

    interface ICertManageModule
    {
        CONST_VTBL struct ICertManageModuleVtbl *lpVtbl;
    };

#ifdef COBJMACROS

#define ICertManageModule_QueryInterface(This,riid,ppvObject)	\
    (This)->lpVtbl -> QueryInterface(This,riid,ppvObject)

#define ICertManageModule_AddRef(This)	\
    (This)->lpVtbl -> AddRef(This)

#define ICertManageModule_Release(This)	\
    (This)->lpVtbl -> Release(This)

#define ICertManageModule_GetTypeInfoCount(This,pctinfo)	\
    (This)->lpVtbl -> GetTypeInfoCount(This,pctinfo)

#define ICertManageModule_GetTypeInfo(This,iTInfo,lcid,ppTInfo)	\
    (This)->lpVtbl -> GetTypeInfo(This,iTInfo,lcid,ppTInfo)

#define ICertManageModule_GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)	\
    (This)->lpVtbl -> GetIDsOfNames(This,riid,rgszNames,cNames,lcid,rgDispId)

#define ICertManageModule_Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)	\
    (This)->lpVtbl -> Invoke(This,dispIdMember,riid,lcid,wFlags,pDispParams,pVarResult,pExcepInfo,puArgErr)

#define ICertManageModule_GetProperty(This,strConfig,strStorageLocation,strPropertyName,Flags,pvarProperty)	\
    (This)->lpVtbl -> GetProperty(This,strConfig,strStorageLocation,strPropertyName,Flags,pvarProperty)

#define ICertManageModule_SetProperty(This,strConfig,strStorageLocation,strPropertyName,Flags,pvarProperty)	\
    (This)->lpVtbl -> SetProperty(This,strConfig,strStorageLocation,strPropertyName,Flags,pvarProperty)

#define ICertManageModule_Configure(This,strConfig,strStorageLocation,Flags)	\
    (This)->lpVtbl -> Configure(This,strConfig,strStorageLocation,Flags)

#endif /* COBJMACROS */

#endif 	/* C style interface */

HRESULT STDMETHODCALLTYPE ICertManageModule_GetProperty_Proxy(
    ICertManageModule * This,
    /* [in] */ const BSTR strConfig,
    /* [in] */ BSTR strStorageLocation,
    /* [in] */ BSTR strPropertyName,
    /* [in] */ LONG Flags,
    /* [retval][out] */ VARIANT *pvarProperty);

void __RPC_STUB ICertManageModule_GetProperty_Stub(
    IRpcStubBuffer *This,
    IRpcChannelBuffer *_pRpcChannelBuffer,
    PRPC_MESSAGE _pRpcMessage,
    DWORD *_pdwStubPhase);

HRESULT STDMETHODCALLTYPE ICertManageModule_SetProperty_Proxy(
    ICertManageModule * This,
    /* [in] */ const BSTR strConfig,
    /* [in] */ BSTR strStorageLocation,
    /* [in] */ BSTR strPropertyName,
    /* [in] */ LONG Flags,
    /* [in] */ const VARIANT *pvarProperty);

void __RPC_STUB ICertManageModule_SetProperty_Stub(
    IRpcStubBuffer *This,
    IRpcChannelBuffer *_pRpcChannelBuffer,
    PRPC_MESSAGE _pRpcMessage,
    DWORD *_pdwStubPhase);

HRESULT STDMETHODCALLTYPE ICertManageModule_Configure_Proxy(
    ICertManageModule * This,
    /* [in] */ const BSTR strConfig,
    /* [in] */ BSTR strStorageLocation,
    /* [in] */ LONG Flags);

void __RPC_STUB ICertManageModule_Configure_Stub(
    IRpcStubBuffer *This,
    IRpcChannelBuffer *_pRpcChannelBuffer,
    PRPC_MESSAGE _pRpcMessage,
    DWORD *_pdwStubPhase);

#endif 	/* __ICertManageModule_INTERFACE_DEFINED__ */

/* Additional Prototypes for ALL interfaces */

unsigned long             __RPC_USER  BSTR_UserSize(     unsigned long *, unsigned long            , BSTR * );
unsigned char * __RPC_USER  BSTR_UserMarshal(  unsigned long *, unsigned char *, BSTR * );
unsigned char * __RPC_USER  BSTR_UserUnmarshal(unsigned long *, unsigned char *, BSTR * );
void                      __RPC_USER  BSTR_UserFree(     unsigned long *, BSTR * );

unsigned long             __RPC_USER  VARIANT_UserSize(     unsigned long *, unsigned long            , VARIANT * );
unsigned char * __RPC_USER  VARIANT_UserMarshal(  unsigned long *, unsigned char *, VARIANT * );
unsigned char * __RPC_USER  VARIANT_UserUnmarshal(unsigned long *, unsigned char *, VARIANT * );
void                      __RPC_USER  VARIANT_UserFree(     unsigned long *, VARIANT * );

/* end of Additional Prototypes */

#ifdef __cplusplus
}
#endif

#endif