Best Python code snippet using localstack_python
ReactFiberPendingPriority.js
Source:ReactFiberPendingPriority.js
1/**2 * Copyright (c) Facebook, Inc. and its affiliates.3 *4 * This source code is licensed under the MIT license found in the5 * LICENSE file in the root directory of this source tree.6 *7 * @flow8 */9import type {FiberRoot} from './ReactFiberRoot';10import type {ExpirationTime} from './ReactFiberExpirationTime';11import {NoWork} from './ReactFiberExpirationTime';12// TODO: Offscreen updates should never suspend. However, a promise that13// suspended inside an offscreen subtree should be able to ping at the priority14// of the outer render.15export function markPendingPriorityLevel(16 root: FiberRoot,17 expirationTime: ExpirationTime,18): void {19 // If there's a gap between completing a failed root and retrying it,20 // additional updates may be scheduled. Clear `didError`, in case the update21 // is sufficient to fix the error.22 root.didError = false;23 // Update the latest and earliest pending times24 const earliestPendingTime = root.earliestPendingTime;25 if (earliestPendingTime === NoWork) {26 // No other pending updates.27 root.earliestPendingTime = root.latestPendingTime = expirationTime;28 } else {29 if (earliestPendingTime < expirationTime) {30 // This is the earliest pending update.31 root.earliestPendingTime = expirationTime;32 } else {33 const latestPendingTime = root.latestPendingTime;34 if (latestPendingTime > expirationTime) {35 // This is the latest pending update36 root.latestPendingTime = expirationTime;37 }38 }39 }40 findNextExpirationTimeToWorkOn(expirationTime, root);41}42export function markCommittedPriorityLevels(43 root: FiberRoot,44 earliestRemainingTime: ExpirationTime,45): void {46 root.didError = false;47 if (earliestRemainingTime === NoWork) {48 // Fast path. There's no remaining work. Clear everything.49 root.earliestPendingTime = NoWork;50 root.latestPendingTime = NoWork;51 root.earliestSuspendedTime = NoWork;52 root.latestSuspendedTime = NoWork;53 root.latestPingedTime = NoWork;54 findNextExpirationTimeToWorkOn(NoWork, root);55 return;56 }57 if (earliestRemainingTime < root.latestPingedTime) {58 root.latestPingedTime = NoWork;59 }60 // Let's see if the previous latest known pending level was just flushed.61 const latestPendingTime = root.latestPendingTime;62 if (latestPendingTime !== NoWork) {63 if (latestPendingTime > earliestRemainingTime) {64 // We've flushed all the known pending levels.65 root.earliestPendingTime = root.latestPendingTime = NoWork;66 } else {67 const earliestPendingTime = root.earliestPendingTime;68 if (earliestPendingTime > earliestRemainingTime) {69 // We've flushed the earliest known pending level. Set this to the70 // latest pending time.71 root.earliestPendingTime = root.latestPendingTime;72 }73 }74 }75 // Now let's handle the earliest remaining level in the whole tree. We need to76 // decide whether to treat it as a pending level or as suspended. Check77 // it falls within the range of known suspended levels.78 const earliestSuspendedTime = root.earliestSuspendedTime;79 if (earliestSuspendedTime === NoWork) {80 // There's no suspended work. Treat the earliest remaining level as a81 // pending level.82 markPendingPriorityLevel(root, earliestRemainingTime);83 findNextExpirationTimeToWorkOn(NoWork, root);84 return;85 }86 const latestSuspendedTime = root.latestSuspendedTime;87 if (earliestRemainingTime < latestSuspendedTime) {88 // The earliest remaining level is later than all the suspended work. That89 // means we've flushed all the suspended work.90 root.earliestSuspendedTime = NoWork;91 root.latestSuspendedTime = NoWork;92 root.latestPingedTime = NoWork;93 // There's no suspended work. Treat the earliest remaining level as a94 // pending level.95 markPendingPriorityLevel(root, earliestRemainingTime);96 findNextExpirationTimeToWorkOn(NoWork, root);97 return;98 }99 if (earliestRemainingTime > earliestSuspendedTime) {100 // The earliest remaining time is earlier than all the suspended work.101 // Treat it as a pending update.102 markPendingPriorityLevel(root, earliestRemainingTime);103 findNextExpirationTimeToWorkOn(NoWork, root);104 return;105 }106 // The earliest remaining time falls within the range of known suspended107 // levels. We should treat this as suspended work.108 findNextExpirationTimeToWorkOn(NoWork, root);109}110export function hasLowerPriorityWork(111 root: FiberRoot,112 erroredExpirationTime: ExpirationTime,113): boolean {114 const latestPendingTime = root.latestPendingTime;115 const latestSuspendedTime = root.latestSuspendedTime;116 const latestPingedTime = root.latestPingedTime;117 return (118 (latestPendingTime !== NoWork &&119 latestPendingTime < erroredExpirationTime) ||120 (latestSuspendedTime !== NoWork &&121 latestSuspendedTime < erroredExpirationTime) ||122 (latestPingedTime !== NoWork && latestPingedTime < erroredExpirationTime)123 );124}125export function isPriorityLevelSuspended(126 root: FiberRoot,127 expirationTime: ExpirationTime,128): boolean {129 const earliestSuspendedTime = root.earliestSuspendedTime;130 const latestSuspendedTime = root.latestSuspendedTime;131 return (132 earliestSuspendedTime !== NoWork &&133 expirationTime <= earliestSuspendedTime &&134 expirationTime >= latestSuspendedTime135 );136}137export function markSuspendedPriorityLevel(138 root: FiberRoot,139 suspendedTime: ExpirationTime,140): void {141 root.didError = false;142 clearPing(root, suspendedTime);143 // First, check the known pending levels and update them if needed.144 const earliestPendingTime = root.earliestPendingTime;145 const latestPendingTime = root.latestPendingTime;146 if (earliestPendingTime === suspendedTime) {147 if (latestPendingTime === suspendedTime) {148 // Both known pending levels were suspended. Clear them.149 root.earliestPendingTime = root.latestPendingTime = NoWork;150 } else {151 // The earliest pending level was suspended. Clear by setting it to the152 // latest pending level.153 root.earliestPendingTime = latestPendingTime;154 }155 } else if (latestPendingTime === suspendedTime) {156 // The latest pending level was suspended. Clear by setting it to the157 // latest pending level.158 root.latestPendingTime = earliestPendingTime;159 }160 // Finally, update the known suspended levels.161 const earliestSuspendedTime = root.earliestSuspendedTime;162 const latestSuspendedTime = root.latestSuspendedTime;163 if (earliestSuspendedTime === NoWork) {164 // No other suspended levels.165 root.earliestSuspendedTime = root.latestSuspendedTime = suspendedTime;166 } else {167 if (earliestSuspendedTime < suspendedTime) {168 // This is the earliest suspended level.169 root.earliestSuspendedTime = suspendedTime;170 } else if (latestSuspendedTime > suspendedTime) {171 // This is the latest suspended level172 root.latestSuspendedTime = suspendedTime;173 }174 }175 findNextExpirationTimeToWorkOn(suspendedTime, root);176}177export function markPingedPriorityLevel(178 root: FiberRoot,179 pingedTime: ExpirationTime,180): void {181 root.didError = false;182 // TODO: When we add back resuming, we need to ensure the progressed work183 // is thrown out and not reused during the restarted render. One way to184 // invalidate the progressed work is to restart at expirationTime + 1.185 const latestPingedTime = root.latestPingedTime;186 if (latestPingedTime === NoWork || latestPingedTime > pingedTime) {187 root.latestPingedTime = pingedTime;188 }189 findNextExpirationTimeToWorkOn(pingedTime, root);190}191function clearPing(root, completedTime) {192 const latestPingedTime = root.latestPingedTime;193 if (latestPingedTime >= completedTime) {194 root.latestPingedTime = NoWork;195 }196}197export function findEarliestOutstandingPriorityLevel(198 root: FiberRoot,199 renderExpirationTime: ExpirationTime,200): ExpirationTime {201 let earliestExpirationTime = renderExpirationTime;202 const earliestPendingTime = root.earliestPendingTime;203 const earliestSuspendedTime = root.earliestSuspendedTime;204 if (earliestPendingTime > earliestExpirationTime) {205 earliestExpirationTime = earliestPendingTime;206 }207 if (earliestSuspendedTime > earliestExpirationTime) {208 earliestExpirationTime = earliestSuspendedTime;209 }210 return earliestExpirationTime;211}212export function didExpireAtExpirationTime(213 root: FiberRoot,214 currentTime: ExpirationTime,215): void {216 const expirationTime = root.expirationTime;217 if (expirationTime !== NoWork && currentTime <= expirationTime) {218 // The root has expired. Flush all work up to the current time.219 root.nextExpirationTimeToWorkOn = currentTime;220 }221}222function findNextExpirationTimeToWorkOn(completedExpirationTime, root) {223 const earliestSuspendedTime = root.earliestSuspendedTime;224 const latestSuspendedTime = root.latestSuspendedTime;225 const earliestPendingTime = root.earliestPendingTime;226 const latestPingedTime = root.latestPingedTime;227 // Work on the earliest pending time. Failing that, work on the latest228 // pinged time.229 let nextExpirationTimeToWorkOn =230 earliestPendingTime !== NoWork ? earliestPendingTime : latestPingedTime;231 // If there is no pending or pinged work, check if there's suspended work232 // that's lower priority than what we just completed.233 if (234 nextExpirationTimeToWorkOn === NoWork &&235 (completedExpirationTime === NoWork ||236 latestSuspendedTime < completedExpirationTime)237 ) {238 // The lowest priority suspended work is the work most likely to be239 // committed next. Let's start rendering it again, so that if it times out,240 // it's ready to commit.241 nextExpirationTimeToWorkOn = latestSuspendedTime;242 }243 let expirationTime = nextExpirationTimeToWorkOn;244 if (expirationTime !== NoWork && earliestSuspendedTime > expirationTime) {245 // Expire using the earliest known expiration time.246 expirationTime = earliestSuspendedTime;247 }248 root.nextExpirationTimeToWorkOn = nextExpirationTimeToWorkOn;249 root.expirationTime = expirationTime;...
assembly.py
Source:assembly.py
1import sys2arrayCount = 0;3class Register:4 inUse = False5 alias = ''6registerTable = [Register() for i in range(15)]7latest_register = 08def assignRegister(alias):9 count = 010 #Register11 for register in registerTable:12 if register.inUse == False and register.alias == '':13 register.inUse = True14 register.alias = alias.rstrip('\n' + ' ')15 #print ("#Assigning Register " + str(count))16 return count17 count+= 118def findAlias(alias):19 count = 020 for register in registerTable:21 if register.alias == alias.rstrip('\n' + ' '):22 return count23 count+= 124def eliminateAlias(alias):25 count = 026 for register in registerTable:27 if register.alias == alias.rstrip('\n' + ' '):28 register.alias =''29 register.inUse = False30 #print ("#Removing Register " + str(count))31 count += 1 32#For Keeping track of variables33with open('threeAddressCode.txt') as f:34 input = f.readlines()35for line in input:36 if line[0] != '\t':37 MIPSInstruction = ""38 if 'goto' in line:39 instruction = line.split(' ')40 MIPSInstruction += str("j " + str(instruction[:][1]))41 elif 'Branch' in line:42 instruction = line.split(' ')43 MIPSInstruction += str("beq $t" + str(findAlias(latest_alias)) + ' $0 ' + str(instruction[:][4]))44 #IF Statement45 elif '_L' in line:46 MIPSInstruction += str(line)47 #Additive Expressions48 if '+' in line:49 instruction = line.split(' ')50 latest_register = assignRegister(instruction[:][0])51 latest_alias = str(instruction[:][0]).strip('\n')52 53 MIPSInstruction += str("add $t" + str(latest_register) + ', ')54 55 if '_' in instruction[:][2]:56 MIPSInstruction += str("$t" + str(findAlias(instruction[:][2])) + ', ')57 else:58 offset = instruction[:][2].split('(')59 offset = offset[1][:].split(')')60 latest_register = assignRegister(instruction[:][2])61 print("la $t"+ str(latest_register) + ", " + str(offset[0][:]) + "($sp)" )62 if '^' not in line:63 latest_register = assignRegister(instruction[:][2])64 print("lw $t"+ str(latest_register) + ", " + str(0) + "($t" + str(findAlias(instruction[:][2])) + ")" )65 else:66 arrayCount += 167 MIPSInstruction += str("$t" + str(latest_register) + ', ')68 if '_' in instruction[:][4]:69 MIPSInstruction += str("$t" + str(findAlias(instruction[:][4]))+ ' ')70 else:71 offset = instruction[:][4].split('(')72 offset = offset[1][:].split(')')73 latest_register = assignRegister(instruction[:][4])74 print("la $t"+ str(latest_register) + ", " + str(offset[0][:]) + "($sp)" )75 print("lw $t"+ str(latest_register) + ", " + str(0) + "($t" + str(latest_register) + ")" )76 MIPSInstruction += str("$t" + str(findAlias(instruction[:][4])) + ', ')77 eliminateAlias(instruction[:][2])78 eliminateAlias(instruction[:][4])79 #Additive Expressions80 #Additive Expressions81 elif '*' in line:82 instruction = line.split(' ')83 latest_register = assignRegister(instruction[:][0])84 latest_alias = str(instruction[:][0]).strip('\n')85 86 MIPSInstruction += str("mul $t" + str(latest_register) + ', ')87 if '_' in instruction[:][2]:88 MIPSInstruction += str("$t" + str(findAlias(instruction[:][2])) + ', ')89 else:90 offset = instruction[:][2].split('(')91 offset = offset[1][:].split(')')92 latest_register = assignRegister(instruction[:][2])93 print("la $t"+ str(latest_register) + ", " + str(offset[0][:]) + "($sp)" )94 if '^' not in line:95 latest_register = assignRegister(instruction[:][2])96 print("lw $t"+ str(latest_register) + ", " + str(0) + "($t" + str(findAlias(instruction[:][2])) + ")" )97 MIPSInstruction += str("$t" + str(latest_register) + ', ')98 if '_' in instruction[:][4]:99 MIPSInstruction += str("$t" + str(findAlias(instruction[:][4]))+ ' ')100 else:101 offset = instruction[:][4].split('(')102 offset = offset[1][:].split(')')103 latest_register = assignRegister(instruction[:][4])104 print("la $t"+ str(latest_register) + ", " + str(offset[0][:]) + "($sp)" )105 print("lw $t"+ str(latest_register) + ", " + str(0) + "($t" + str(latest_register) + ")" )106 MIPSInstruction += str("$t" + str(latest_register) + ' ')107 eliminateAlias(instruction[:][2])108 eliminateAlias(instruction[:][4])109 elif '-' in line:110 instruction = line.split(' ')111 latest_register = assignRegister(instruction[:][0])112 latest_alias = str(instruction[:][0]).strip('\n')113 114 MIPSInstruction += str("sub $t" + str(latest_register) + ', ')115 if '_' in instruction[:][2]:116 MIPSInstruction += str("$t" + str(findAlias(instruction[:][2])) + ', ')117 else:118 offset = instruction[:][2].split('(')119 offset = offset[1][:].split(')')120 latest_register = assignRegister(instruction[:][2])121 print("la $t"+ str(latest_register) + ", " + str(offset[0][:]) + "($sp)" )122 if '^' not in line:123 latest_register = assignRegister(instruction[:][2])124 print("lw $t"+ str(latest_register) + ", " + str(0) + "($t" + str(findAlias(instruction[:][2])) + ")" )125 MIPSInstruction += str("$t" + str(latest_register) + ', ')126 if '_' in instruction[:][4]:127 MIPSInstruction += str("$t" + str(findAlias(instruction[:][4]))+ ' ')128 else:129 offset = instruction[:][4].split('(')130 offset = offset[1][:].split(')')131 latest_register = assignRegister(instruction[:][4])132 print("la $t"+ str(latest_register) + ", " + str(offset[0][:]) + "($sp)" )133 print("lw $t"+ str(latest_register) + ", " + str(0) + "($t" + str(latest_register) + ")" )134 MIPSInstruction += str("$t" + str(latest_register) + ' ')135 eliminateAlias(instruction[:][2])136 eliminateAlias(instruction[:][4])137 elif '<' in line:138 instruction = line.split(' ')139 latest_register = assignRegister(instruction[:][0])140 latest_alias = str(instruction[:][0]).strip('\n')141 142 MIPSInstruction += str("slt $t" + str(latest_register) + ', ')143 144 if '_' in instruction[:][2]:145 MIPSInstruction += str("$t" + str(findAlias(instruction[:][2])) + ', ')146 else:147 offset = instruction[:][2].split('(')148 offset = offset[1][:].split(')')149 latest_register = assignRegister(instruction[:][2])150 print("la $t"+ str(latest_register) + ", " + str(offset[0][:]) + "($sp)" )151 if '^' not in line:152 latest_register = assignRegister(instruction[:][2])153 print("lw $t"+ str(latest_register) + ", " + str(0) + "($t" + str(findAlias(instruction[:][2])) + ")" )154 else:155 arrayCount += 1156 MIPSInstruction += str("$t" + str(latest_register) + ', ')157 if '_' in instruction[:][4]:158 MIPSInstruction += str("$t" + str(findAlias(instruction[:][4]))+ ' ')159 else:160 offset = instruction[:][4].split('(')161 offset = offset[1][:].split(')')162 latest_register = assignRegister(instruction[:][4])163 print("la $t"+ str(latest_register) + ", " + str(offset[0][:]) + "($sp)" )164 print("lw $t"+ str(latest_register) + ", " + str(0) + "($t" + str(latest_register) + ")" )165 MIPSInstruction += str("$t" + str(findAlias(instruction[:][4])) + ', ')166 eliminateAlias(instruction[:][2])167 eliminateAlias(instruction[:][4])168 #Assignment Expressions169 elif '=' in line:170 instruction = line.split('=')171 #Array172 if '&' in line:173 offset = instruction[:][0].split('(')174 offset = offset[1][:].split(')')175 if arrayCount == 2:176 print("lw $t"+ str(findAlias(latest_alias)) + ", 0($t" + str(findAlias(latest_alias)) + ")" )177 elif arrayCount == 3:178 print "here"179 arrayCount = 0180 print("sw $t"+ str(findAlias(latest_alias)) + ", 0($t" + str(findAlias(offset[0][:])) + ")" )181 eliminateAlias(latest_alias)182 183 # Constant Values184 elif '_' in instruction[:][0]:185 #print (instruction[:][0])186 latest_alias = str(instruction[:][0])187 latest_alias.strip(' ')188 latest_register = assignRegister(str(latest_alias))189 190 if '(' in instruction[:][1]:191 offset = instruction[:][1].split('(')192 offset = offset[1][:].split(')')193 print("sw $t"+ str(findAlias(latest_alias)) + ", " + str(offset[0][:]) + "($sp)" )194 195 else:196 MIPSInstruction += str('li $t' + str(latest_register) + ',')197 MIPSInstruction += str(instruction[:][1])198 # V = $tX199 else:200 #localVariables[str(instruction[:][0]).rstrip(' ' + '\n')] = instruction[:][1]201 #assignVariable(instruction[:][0], latest_register)202 offset = instruction[:][0].split('(')203 offset = offset[1][:].split(')')204 print("sw $t"+ str(findAlias(latest_alias)) + ", " + str(offset[0][:]) + "($sp)" )205 eliminateAlias(latest_alias)206 if MIPSInstruction is not "":207 print(MIPSInstruction.rstrip('\n'))208 ...
index.js
Source:index.js
1#!/usr/bin/env node2const Octokit = require("@octokit/core").Octokit3const yargs = require("yargs/yargs")4const hideBin = require("yargs/helpers").hideBin5require("dotenv").config()6const releaseType = "patch"7const patternRelease = /(?<prefix>[a-zA-Z]+)?(?<major>\d+)(\.)(?<minor>\d+)(\.)(?<patch>\d+)?(?<postfix>[a-zA-Z]+)?/g8const patternGithubRef = /(refs\/pull\/)(?<prnum>\d+)(\/merge)$/g9const owner = process.env.GITAC_OWNER10const repo = process.env.GITAC_REPO11const githubToken = process.env.GITAC_GITHUB_TOKEN12const octokit = new Octokit({ auth: githubToken });13const argv = yargs(hideBin(process.argv)).command('release', 'generate draft release tag')14 .option('github-ref', {15 description: 'PR merge branch refs/pull/:prNumber/merge',16 type: 'string',17 })18 .option('service', {19 description: 'service name matched with label on github repo',20 type: 'string',21 })22 .option('prefix', {23 description: 'group of charater before the version <prefix>0.0.0',24 type: 'string',25 })26 .option('postfix', {27 description: 'group of charater after the version 0.0.0<postfix>',28 type: 'string',29 })30 .help()31 .argv;32async function createRelease() {33 var result = patternGithubRef.exec(argv['github-ref'])34 if (result == null) {35 console.log("invalid github-ref value")36 return37 }38 const service = argv['service']39 if (service == ""){40 console.log("service name is required")41 return42 }43 const prefix = argv['prefix']44 const postfix = argv['postfix']45 46 try {47 var prnum = result.groups.prnum 48 response = await octokit.request(`GET /repos/${owner}/${repo}/pulls/${prnum}`, {49 owner: owner,50 repo: repo,51 })52 53 const { closed_at, merged_at, user, title, labels } = response.data54 var isCorrectService = false55 for (const label of labels) {56 isCorrectService = label.name == service57 if (isCorrectService) {58 console.log("service tag found: ", label.name)59 break60 }61 }62 if(!isCorrectService) {63 console.log("label service doesn't match with ", service)64 return65 }66 var isOpenPR = closed_at == null && merged_at == null67 if (isOpenPR) {68 console.log("Status: OPEN")69 return70 }71 var isClosePR = closed_at != null && merged_at == null72 if (isClosePR) {73 console.log("Status: CLOSE")74 return75 }76 var isMergePR = closed_at != null && merged_at != null77 if (isMergePR) {78 console.log("Status: MERGE")79 } 80 response = await octokit.request(`GET /repos/${owner}/${repo}/releases`, {81 owner: owner,82 repo: repo,83 })84 var isDraftExist = false85 var existingDraftID = 086 var latestRelease = ""87 var latestMajor = 088 var latestMinor = 089 var latestPatch = 0 90 for (const release of response.data) {91 var regexPattern = new RegExp(patternRelease, 'i')92 var result = regexPattern.exec(release.tag_name)93 var isMatchTagName = result == null94 if (isMatchTagName) {95 continue96 }97 var isMatchPrefixOrPostfix = prefix == result.groups['prefix'] || postfix == result.groups['postfix']98 if (isMatchPrefixOrPostfix) {99 var isLatestReleaseEmpty = latestRelease == ""100 if (isLatestReleaseEmpty) {101 latestRelease = release.tag_name102 latestMajor = parseInt(result.groups['major'])103 latestMinor = parseInt(result.groups['minor'])104 latestPatch = parseInt(result.groups['patch'])105 }106 isDraftExist = release.draft107 if (isDraftExist) {108 existingDraftID = release.id109 break110 }111 }112 }113 changesLog = `* ${title} #${prnum} @${user.login}`114 if(isDraftExist) { 115 console.log('existing latest release:', latestRelease)116 await appendChangesLog(latestRelease, existingDraftID, changesLog)117 return118 }119 var { latestMajor, latestMinor, latestPatch } = increaseVersion(releaseType, latestMajor, latestMinor, latestPatch)120 latestRelease = `${prefix}${latestMajor}.${latestMinor}.${latestPatch}${postfix}`121 console.log('new latest release:', latestRelease)122 await generateNewRelease(latestRelease, changesLog)123 } catch(err) {124 console.log("error ", err)125 }126}127createRelease()128function increaseVersion(releaseType, latestMajor, latestMinor, latestPatch) {129 switch (releaseType) {130 case 'major':131 latestMajor++132 break133 case 'minor':134 if (latestMinor < 100) {135 latestMinor++136 break137 }138 latestMinor = 0139 latestMajor++140 break141 default:142 if (latestPatch < 100) {143 latestPatch++144 break145 }146 latestPatch = 0147 if (latestMinor < 100) {148 latestMinor++149 break150 }151 latestMinor = 0152 latestMajor++153 break154 }155 return {latestMajor, latestMinor, latestPatch}156}157async function generateNewRelease(latestRelease, changesLog) {158 await octokit.request(`POST /repos/{owner}/{repo}/releases`, {159 owner: owner,160 repo: repo,161 tag_name: latestRelease,162 draft: true,163 prerelease: true,164 name: latestRelease,165 body: `Changes: \n${changesLog}`,166 })167 console.log('create new draft release')168}169async function appendChangesLog(latestRelease, existingDraftID, changesLog) {170 var response = await octokit.request(`GET /repos/{owner}/{repo}/releases/{asset_id}`, {171 owner: owner,172 repo: repo,173 asset_id: `${existingDraftID}`,174 })175 var newBody = `${response.data.body} \n${changesLog}`176 var response = await octokit.request(`PATCH /repos/{owner}/{repo}/releases/{asset_id}`, {177 owner: owner,178 repo: repo,179 asset_id: existingDraftID,180 draft: true,181 prerelease: true,182 tag_name: latestRelease,183 body: newBody,184 })185 console.log('update draft release')...
trainmodel.py
Source:trainmodel.py
1def build_model_1(vocab_size, embedding_dim, rnn_units, batch_size):2 model = tf.keras.models.Sequential()3 model.add(tf.keras.layers.Embedding(4 input_dim=vocab_size,5 output_dim=embedding_dim,6 batch_input_shape=[batch_size, None]7 ))8 model.add(tf.keras.layers.LSTM(9 units=rnn_units,10 return_sequences=True,11 stateful=True,12 recurrent_initializer=tf.keras.initializers.GlorotNormal()13 ))14 model.add(tf.keras.layers.Dense(vocab_size))15 16 return model17# An objective function.18# The function is any callable with the signature scalar_loss = fn(y_true, y_pred).19def loss(labels, logits):20 entropy = tf.keras.losses.sparse_categorical_crossentropy(21 y_true=labels,22 y_pred=logits,23 from_logits=True24 )25 26 return entropy27example_batch_loss = loss(target_example_batch, example_batch_predictions)28print("Prediction shape: ", example_batch_predictions.shape, " # (batch_size, sequence_length, vocab_size)")29print("scalar_loss.shape: ", example_batch_loss.shape)30print("scalar_loss: ", example_batch_loss.numpy().mean())31def download_latest_checkpoint(zip_only=True):32 latest_checkpoint_path = tf.train.latest_checkpoint(checkpoint_dir)33 latest_checkpoint_name = os.path.split(latest_checkpoint_path)[-1]34 latest_checkpoint_zip_name = latest_checkpoint_name + '.zip'35 36 print('latest_checkpoint_path: ', latest_checkpoint_path)37 print('latest_checkpoint_name: ', latest_checkpoint_name)38 print('---\n')39 print('Checkpoint files:')40 with zipfile.ZipFile(latest_checkpoint_zip_name, mode='w') as zip_obj:41 for folder_name, subfolders, filenames in os.walk(checkpoint_dir):42 for filename in filenames:43 if filename.startswith(latest_checkpoint_name):44 print(' - ' + filename)45 file_path = os.path.join(folder_name, filename)46 zip_obj.write(file_path, os.path.basename(file_path))47 print('---\n')48 print('Zipped to: ', latest_checkpoint_zip_name)49 if not zip_only:50 files.download(latest_checkpoint_zip_name)51def model_weights_from_latest_checkpoint(model):52 latest_checkpoint_path = tf.train.latest_checkpoint(checkpoint_dir)53 if not latest_checkpoint_path:54 print('Latest checkpoint was not found. Using model as is.')55 return model56 print('latest_checkpoint_path: ', latest_checkpoint_path)57 model.load_weights(latest_checkpoint_path)58 return model59def initial_epoch_from_latest_checkpoint():60 latest_checkpoint_path = tf.train.latest_checkpoint(checkpoint_dir)61 if not latest_checkpoint_path:62 print('Latest checkpoint was not found. Starting from epoch #0')63 return 064 print('latest_checkpoint_path: ', latest_checkpoint_path)65 latest_checkpoint_name = os.path.split(latest_checkpoint_path)[-1]66 print('latest_checkpoint_name: ', latest_checkpoint_name)67 latest_checkpoint_num = latest_checkpoint_name.split('_')[-1]68 print('latest_checkpoint_num: ', latest_checkpoint_num)69 return int(latest_checkpoint_num)70def train_model():71 INITIAL_EPOCH = initial_epoch_from_latest_checkpoint()72EPOCHS_DELTA = 173EPOCHS = INITIAL_EPOCH + EPOCHS_DELTA74STEPS_PER_EPOCH = 150075print('\n')76print('INITIAL_EPOCH: ', INITIAL_EPOCH)77print('EPOCHS_DELTA: ', EPOCHS_DELTA)78print('EPOCHS: ', EPOCHS)79print('STEPS_PER_EPOCH: ', STEPS_PER_EPOCH)80history_1[INITIAL_EPOCH] = model_1.fit(81 x=dataset_train,82 epochs=EPOCHS,83 steps_per_epoch=STEPS_PER_EPOCH,84 initial_epoch=INITIAL_EPOCH,85 callbacks=[86 checkpoint_callback,87 early_stopping_callback88 ]89)90model_name = 'recipe_generation_rnn_raw_' + str(INITIAL_EPOCH) + '.h5'91model_1.save(model_name, save_format='h5')92download_latest_checkpoint(zip_only=True)93def render_training_history(training_history):94 if 'history' in training_history:95 loss = training_history.history['loss']96 else:97 loss = []98 for initial_epoch in training_history:99 loss += training_history[initial_epoch].history['loss']100 plt.title('Loss')101 plt.xlabel('Epoch')102 plt.ylabel('Loss')103 plt.plot(loss, label='Training set')104 plt.legend()105 plt.grid(linestyle='--', linewidth=1, alpha=0.5)...
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!!