Best Python code snippet using localstack_python
parse_doc_string.py
Source:parse_doc_string.py
1import re2import copy3from .element import Element4from .utils import isSelfCloser, mergeDict, representElementAsString, seqIdtoDict, getTagBySeqId5from .html_data import global_attributes, css_properties, html_tags_incl_attributes, html_tags_stripped6def addGlobalAttributes():7 attributes = {}8 for g in global_attributes:9 if g == 'style':10 attributes[g] = {}11 for prop in css_properties:12 attributes[g][prop] = ""13 14 else:15 attributes[g] = ""16 return attributes17def addSpecificAttributes(meta_tag):18 attributes = {}19 for a in html_tags_incl_attributes[meta_tag['as_tag_identifier']]:20 attributes[a] = ""21 return attributes22def sortTags(tags):23 return sorted(tags, key = lambda i: i['start_idx'])24def getInnerContents(tags_up, input):25 for t in tags_up:26 if t['tag_role'] == 'open_close' or t['tag_role'] == 'open_close_alt':27 continue28 else:29 t['innerHTML'] = input[t['end_idx']+1:t['closer']['start_idx']]30 31 t['outerHTML'] = input[t['start_idx']:t['closer']['end_idx']]32 return tags_up33def hasClosingTags(collected):34 result = False35 for no, c in enumerate(collected): 36 if c['tag_role'] == 'close' and no != 1:37 result = True38 return result39def identifyTags(input):40 collected_tags = []41 for tag in html_tags_stripped:42 as_open = re.findall(f'<{tag}(?=\s)', input)43 as_close = re.findall(f'</{tag}', input)44 ##handle openers45 current_idx = 046 for o in as_open:47 meta_tag = {}48 meta_tag['tag_type'] = tag49 matcher = f"<{tag} />"50 meta_tag['start_idx'] = input.index(o, current_idx)51 meta_tag['end_idx'] = input.index('>', meta_tag['start_idx']) 52 meta_tag['with_attributes'] = input[meta_tag['start_idx']:meta_tag['end_idx'] +1]53 if isSelfCloser(matcher):54 meta_tag['tag_role'] = 'open_close'55 meta_tag['as_tag_identifier'] = matcher56 else:57 meta_tag['as_tag_identifier'] = f"<{tag}>"58 if meta_tag['end_idx'] > input.index('/', meta_tag['start_idx']):59 meta_tag['tag_role'] = 'open_close_alt'60 else:61 meta_tag['tag_role'] = 'open'62 specific = addSpecificAttributes(meta_tag)63 globals = addGlobalAttributes()64 meta_tag['allowed_attributes'] = mergeDict([globals, specific])65 meta_tag['rest_string'] = input[meta_tag['end_idx'] + 1:] 66 current_idx = meta_tag['end_idx']67 collected_tags.append(meta_tag)68 ##handle closers69 current_idx = 070 for c in as_close:71 meta_tag = {}72 meta_tag['tag_type'] = tag73 meta_tag['tag_role'] = 'close'74 meta_tag['as_tag_identifier'] = f"{o}>"75 meta_tag['start_idx'] = input.index(c, current_idx)76 meta_tag['end_idx'] = input.index('>', meta_tag['start_idx'])77 meta_tag['with_attributes'] = ""78 meta_tag['rest_string'] = input[meta_tag['end_idx'] + 1:] 79 collected_tags.append(meta_tag) 80 current_idx = meta_tag['end_idx'] +181 return collected_tags82def parseStyleString(styles_, tag_styles):83 for val in styles_.split(";"):84 if (val == ""):85 continue86 else: 87 idx = val.index(":")88 kee = val[:idx].strip()89 value = val[idx+1:].strip()90 tag_styles[kee] = value91 return tag_styles92def parseAttributes(tags):93 for tag in tags: 94 #loop through the attribute keys95 for kee in tag['allowed_attributes'].keys():96 tag_with = tag['with_attributes']97 if f"{kee}=" not in tag_with:98 continue99 100 else:101 idx = tag_with.index(f"{kee}=")102 idx_equ = tag_with.index("=", idx)103 quot_type = tag_with[idx_equ + 1]104 idx_end = tag_with.index(quot_type, idx_equ + 2)105 if kee == 'style':106 tag['allowed_attributes'][kee] = parseStyleString(tag_with[idx_equ+2:idx_end], tag['allowed_attributes'][kee])107 else:108 tag['allowed_attributes'][kee] = tag_with[idx_equ+2:idx_end]109 return tags110def createSequence(sorted_tags):111 sequence = []112 for i, t in enumerate(sorted_tags):113 t['seq_id'] = f"{str(i)}-$$_{t['tag_type']}"114 sequence.append(t['seq_id'])115 return (sequence, sorted_tags)116def matchTokens(tags_collected):117 tags = sortTags(tags_collected)118 (seq, tags) = createSequence(tags)119 updated_tags = [] 120 to_remove = []121 no_of_open = 0122 for t in tags:123 if t['tag_role'] == 'open':124 no_of_open += 1125 if t['tag_role'] == 'open_close':126 s = t['seq_id']127 t['seq_id'] = s.replace('$$', "3")128 s_idx = seq.index(s)129 seq[s_idx] = t['seq_id']130 updated_tags.append(t)131 to_remove.append(t)132 if t['tag_role'] == 'open_close_alt':133 s = t['seq_id']134 t['seq_id'] = s.replace('$$', "3")135 s_idx = seq.index(s)136 seq[s_idx] = t['seq_id']137 updated_tags.append(t)138 to_remove.append(t)139 for item in to_remove:140 tags.remove(item)141 #count open tags?142 current_length = len(tags)143 while no_of_open > 0:144 for i in reversed(range(0, current_length)):145 open = {}146 close = {}147 if tags[i]['tag_role'] == 'open':148 open = tags[i]149 open_s = tags[i]['seq_id']150 open['seq_id'] = open['seq_id'].replace('$$', "1")151 seq[seq.index(open_s)] = open['seq_id']152 open_seq = seqIdtoDict(open['seq_id'])153 for f in range(i, len(tags)):154 if tags[f]['tag_role'] == 'close':155 close = tags[f]156 close_s = tags[f]['seq_id']157 close['seq_id'] = f"{open_seq['seq_unique']}-2_{open_seq['seq_tag_type']}"158 seq[seq.index(close_s)] = close['seq_id']159 break160 # wrong - needs to be a copy of the unfinished seq ID161 open['closer'] = close162 updated_tags.append(open)163 tags.remove(open)164 tags.remove(close)165 break166 current_length = len(tags)167 no_of_open -= 1168 return (seq, updated_tags) 169# lifts style, id, class attributes to top level170def liftAttributes(tags):171 rel_attr = ['id', 'style', 'class']172 for tag in tags:173 for att in rel_attr:174 tag[att] = tag['allowed_attributes'][att]175 tag['allowed_attributes'].pop(att)176 return tags177def getText(seq_id, next_tag, tags):178 179 element = getTagBySeqId(tags, seq_id['seq_id'])180 text_after = element['rest_string']181 idx = -1182 next = next_tag['seq_tag_type']183 if next_tag['seq_tag_role'] == '2':184 idx = text_after.find(f'</{next}')185 else:186 idx = text_after.find(f'<{next}')187 if idx == -1:188 return ''189 else:190 return '$_text_$_' + text_after[0:idx]191 192def handleTexts(sqs, tgs):193 items = []194 for s in range(0, len(sqs) - 1):195 item = {}196 seq_current = seqIdtoDict(sqs[s])197 seq_next = seqIdtoDict(sqs[s+1])198 item['after'] = sqs[s]199 item['text'] = getText(seq_current, seq_next, tgs)200 items.append(item)201 for i in items:202 if i['text'] != '$_text_$':203 idx = sqs.index(i['after'])204 sqs.insert(idx+1, i['text'])205 return sqs206#find a way to represent dom as dictionary with levels of nesting (irrelevant of text, just to have it ready)207#e.g: 208#body: {209# div: {210# text: ...211# p: {},212# p: {},213# p: {214# img: {}215# } 216# }217# div: {}218# }219#220#221#222#223 224def mapHTMLString(input):225 tags = identifyTags(input)226 (seq, tags) = matchTokens(tags)227 tags = getInnerContents(tags, input)228 tags = parseAttributes(tags)229 tags = liftAttributes(tags)230 seq = handleTexts(seq, tags)231 tags_asClass = []232 for e in tags:233 element = Element(e)234 tags_asClass.append(element)...
commands.py
Source:commands.py
...8async def delete_all(ctx: commands.Context):9 if not await has_commands_permission(ctx.guild, ctx.message.author):10 await ctx.send(INSUFFICIENT_PERMISSION_MESSAGE)11 return12 tag_role = await get_channel_tag_role(ctx.guild)13 for channel in ctx.guild.channels:14 if tag_role in channel.overwrites:15 await remove_voice_text_channel(ctx.guild, channel.name, channel.name)16 if channel.category is not None and len(channel.category.channels) == 0:17 await channel.category.delete()18 await tag_role.delete()19 await ctx.send("All channels and roles deleted")20@bot.command(name="dd")21async def delete_duplicates(ctx: commands.Context):22 if not await has_commands_permission(ctx.guild, ctx.message.author):23 await ctx.send(INSUFFICIENT_PERMISSION_MESSAGE)24 return25 tag_role = await get_channel_tag_role(ctx.guild)26 found_names = set()27 for channel in ctx.guild.channels:28 if tag_role in channel.overwrites:29 if channel.name in found_names:30 await channel.delete()31 if channel.category is not None and len(channel.category.channels) == 0:32 await channel.category.delete()33 else:34 found_names.add(channel.name)35 await tag_role.delete()36 await ctx.send("All duplicate channels deleted")37@bot.command(name="listall")38async def list_all(ctx: commands.Context):39 if not await has_commands_permission(ctx.guild, ctx.message.author):40 await ctx.send(INSUFFICIENT_PERMISSION_MESSAGE)41 return42 tag_role = await get_channel_tag_role(ctx.guild)43 channel_names = [channel.name for channel in ctx.guild.channels44 if tag_role in channel.overwrites]45 channel_list_text = "\n".join(channel_names)46 await ctx.send(f"Channels created by bot:\n{channel_list_text}")47@bot.command(name="resetroles")48async def reset_roles(ctx: commands.Context):49 if not await has_commands_permission(ctx.guild, ctx.message.author):50 await ctx.send(INSUFFICIENT_PERMISSION_MESSAGE)51 return52 tag_role = await get_channel_tag_role(ctx.guild)53 channel_names = [channel.name for channel in ctx.guild.channels54 if tag_role in channel.overwrites]55 roles = [get_role_by_name(ctx.guild, name) for name in channel_names]56 async for member in ctx.guild.fetch_members(limit=None):57 await member.remove_roles(*roles)58 await ctx.send("All roles reset")59@bot.command(name="clearafter")60async def clear_messages(ctx: commands.Context, after_date: str, after_time: str):61 if not await has_commands_permission(ctx.guild, ctx.message.author):62 await ctx.send(INSUFFICIENT_PERMISSION_MESSAGE)63 return64 tag_role = await get_channel_tag_role(ctx.guild)65 if tag_role not in ctx.channel.overwrites:66 await ctx.send(f"Channel was not created by {BOT_NAME}")67 return68 after_datetime = datetime.strptime(f"{after_date} {after_time}", '%d-%m-%Y %H:%M')69 if after_date is None:70 await ctx.send("Invalid date")71 return72 delete_queue = [message async for message in ctx.channel.history(limit=200)73 if message.created_at > after_datetime]74 await ctx.channel.delete_messages(delete_queue)...
tag_role.py
Source:tag_role.py
...33 }34]3536try:37 response = iam.tag_role(38 Tags=tags,39 RoleName=role_name40 )41 print(response)42except Exception as e:43 print(e)44 45# snippet-end:[iam.python.tag_role.complete]46# snippet-comment:[These are tags for the AWS doc team's sample catalog. Do not remove.]47# snippet-sourcedescription:[tag_role.py demonstrates how to Tag an IAM Role.]48# snippet-keyword:[Python]49# snippet-sourcesyntax:[python]50# snippet-sourcesyntax:[python]51# snippet-keyword:[AWS SDK for Python (Boto3)]
...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!