dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def count_valid_patches(self, buggy_methods): valid_patches = [] for buggy_method in buggy_methods: patch = self.patch_selection(buggy_method) if patch is not None: valid_patches.append(patch) return valid_patches def get_submissions(self, patch): ...
This code processes each directory in `self.patches_path` to count and apply valid patches. It checks for subdirectories (buggy methods), counts valid patches, applies them individually or in bulk, handles conflicts with multiple patches by prompting manual resolution, and removes directories with no valid patches. The...
def launcher(self): count_patches = 0 for patches in self.patches_path.iterdir(): if patches.is_dir(): buggy_methods = [method for method in patches.iterdir() if method.is_dir()] valid_patches = self.count_valid_patches(buggy_methods) if len(va...
def rearrange(self, s): '''rearrange anagrams of input word''' if s == "": #base case: empty string return [s] else: ans = [] for w in self.rearrange(s[1:]): #iterate through each anagram of the tail of s for pos in range(le...
The code initializes a class to find anagrams of a given input word from a provided dictionary. It stores the dictionary, input word, and rearranged anagram versions of the word. The `read_dict()` method populates a list of dictionary words, while `check_anagrams()` identifies valid anagrams by comparing rearranged wor...
def __init__(self, dictionary, inputWord): ''' constructor method''' self.dict = dictionary #define dictionary self.check_word = inputWord #define input word self.anagrams = self.rearrange(self.check_word) #define rearranged ver of input word self.alt...
def play_program1(gwin): gwin_bg = Image(Point(200,200), "pinkbg.gif") #background using Image object gwin_bg.draw(gwin) p2_title = Text(Point(200,110), "Exponent Calculator") #title using Text object p2_title.setFace("times roman") p2_title.setFill(color_rgb(255,153,153)) p2_titl...
The code creates a graphical user interface (GUI) for a math program, displaying buttons for three arithmetic calculators (exponent calculator, base conversion, and combinations/permutations). It uses images and text for the interface, opens new windows when buttons are clicked, and includes an exit option. The main lo...
def main(): win = GraphWin("MATH PROGRAM", 800, 800) win.setBackground("white") intro = Image(Point(400,400),"mathh.gif") #background using Image object intro.draw(win) search = Image(Point(400,350),"searchBox.gif") #search bar using Image object search.draw(win) title = Text(P...
def _recv(self, timeout=1): ready, _, _ = select.select([self.sock], [], [], timeout) if not ready: return None, None, None, None data, addr = self.sock.recvfrom(1024) if len(data) < 4: logger.error("Received a packet that's too short: %s", repr(data)) ...
This function processes network packets by receiving data, determining their type (e.g., POLL, ACK, DMX), and routing them to corresponding callback functions. It handles POLL requests by invoking poll_cb or generating replies via poll_reply_data_cb, sends ACKs for unrecognized types, triggers DMX data handling, and pr...
def process_packet(self, *, poll_cb=None, poll_reply_cb=None, poll_reply_data_cb=None, ack_cb=None, dmx_cb=None, reset_cb=None, timeout=1): addr, type_, args, crc = self._recv(timeout) if type_ is None: return if type_ not in ('ACK', 'POLL'): self.send_ack(address=addr, ...
def make_info_dict(prefix, label_groups=None, bin_edges=None, faf=False, popmax=False, age_hist_data=None): ''' Generate dictionary of Number and Description attributes to be used in the VCF header :param str prefix: Subset of gnomAD :param dict label_groups: Dictionary containing an entry for each labe...
This function prepares a Hail Table for export by updating INFO annotations with subset-specific data, renaming fields, annotating nested structures, selecting relevant columns (info, filters, rsid, qual), and adding a header dictionary mapping field names to descriptions.
def prepare_ht_export(ht: hl.Table) -> hl.Table: subset_list = ['gnomad'] for subset in subset_list: INFO_DICT.update(make_info_dict(subset, dict(group=GROUPS))) INFO_DICT.update(make_info_dict(subset, dict(group=GROUPS, pop=POPS))) new_info_dict = {i.replace('gnomad_', '').replace('_adj'...
def get_group(): group_xpath = '//*[@id="main-content"]/ms-main/ms-column/div[1]/ms-competition-navigation/ms-competition-tree/ms-item-tree[2]/ms-item-tree/ms-item-tree/ms-item[1]/a/div[3]' return int(driver.find_element_by_xpath(group_xpath).text) def press_button(group): button_xpath = '//*[@id="main-view...
The code's main task is to collect and categorize data from multiple groups by checking titles for 'Men' or 'Women', appending structured winner lists to respective keys in a dictionary, then printing and converting this data into a JSON file. It iterates through groups, presses a button to load data, handles exception...
def run(): data = {'men_data': [], 'women_data': []} for group in range(1,get_group()+1): press_button(group) try: if 'Men' in get_title(group): men_dict = {'title': get_title(group), 'winner_list': get_data(group,get_title(group))} data['men_data'].ap...
def run_hlda(self, hype_names, hype_ranges, hype_vals, defaults_dict, temp_path, dat_path, order_path, log=False): self.make_settings(hype_names, hype_ranges, hype_vals, defaults_dict, temp_path, log = log) result = subprocess.run(['hlda-master/main', 'gibbs', dat_path, '{}/settings.txt'.format(temp_pa...
The code performs Bayesian Optimization (BO) for hyperparameter tuning. It initializes with random sampling, evaluates hyperparameters using `run_hlda`, builds a Gaussian Process (GP) model with a Matern52 kernel, trains it, and iteratively selects optimal hyperparameters via BO. Results are transformed back to origina...
def run_BO(self, hyp_names, hyp_ranges, defaults_dict, num_random, num_BO, temp_path, dat_path, order_path, out_path, seed=None, log=False): if seed is not None: np.random.seed(seed) pyro.set_rng_seed(seed) X = torch.tensor(np.random.rand(num_random, len(hyp_name...
def getHour(self): return int(time.strftime("%H", time.localtime(time.time()))) def getYear(self): return int(time.strftime("%Y", time.localtime(time.time()))) def getDayOfYear(self): return self.__N() def convertToRadians(self, Degrees): Radians = Degrees * (self.pi/180) return Radians
This function calculates a fractional year value in radians, adjusting for leap years. It converts the day of the year and hour into a fraction of the year (365 or 366 days), then maps this to radians using a 2π cycle. Special handling ensures midnight (0 hours) is treated as the end of the day (24 hours) for accurate ...
def getFractionalYear(self): hour = self.getHour() denominator = 365 if((self.getYear()) % 4 == 0): denominator = 366 if(hour == 0): hour = 24 Y = ((2*self.pi)/(denominator) * (self.getDayOfYear() - 1 + ((hour - 12)/12))) return self.convertToRadians(Y)
def BaseWrite(self,columns,position):#value we insert #Columns is the array of all values in a record #Position Use?? if position == None: base_page = (self.num_base_record) // 512 base_page_position = self.num_base_record % 512 if base_page_position == 0: ...
This code deletes an entry in a data structure by overwriting the specified position with a zeroed array, then traversing and updating subsequent entries via indirection pointers until reaching the end of the chain. The loop risks infinite recursion if indirection never reaches zero, which requires validation.
def Delete(self,position): array = [None]*self.num_columns array[1] = 0 self.BaseWrite(array,position) indirection = self.BaseRead(position,0) while indirection != 0:#Might lead to an infinte bug #CHECK!!!!!!!!!!!!!!! self.TailWrite(array,indirectio...
def BaseRead(self,position,column): #This is Base READ *...* base_page = (position-1) // 512 #index of base page base_page_position = ((position-1) % 512)+1 #position inside base page we are reading ret = self.base_pages[base_page].read(base_page_position,column) i...
This code updates a record by integrating a bit array (BA) with existing data. It calculates a numeric value from BA and the current schema, writes it back, constructs metadata (including record count and timestamp), merges it with column data (filling gaps with existing values), and writes the updated metadata and dat...
def Update(self, position, columns, BA):#BA = bit array of updated columns #AB = BA #Converting the Bit array num = 0 CurrSchema = self.BaseRead(position,3) CurrSchema = [CurrSchema >> i & 1 for i in range(self.num_columns-1,-1,-1)] for i in range(0, self.num_colum...
def assign_samples_to_bins(samples, centroids, codebook_length, channel_error_probability, channel_type, delta): bins = [[] for _ in range(codebook_length)] for sample in samples: distortion = -1 index = 0 # bin to place a sample into for i in range(0, codebook_length): new_distortion = 0 ...
The code implements the Lloyds algorithm for vector quantization, iteratively refining codebook centroids and bin assignments to minimize distortion. It initializes centroids, assigns samples to bins, recalculates centroids, and repeats until distortion changes by ≤1% between iterations. The function returns final cent...
def general_lloyds_algorithm(samples, num_samples, channel_error_probability, codebook_length, channel_type, delta): distortion = [] centroids = np.linspace(-1, 1, codebook_length) bins = assign_samples_to_bins(samples, centroids, codebook_length, channel_error_probability, channel_type, delta) distortion.ap...
def create_quantizers(channel_error_probabilities, channel_type, delta): num_samples = 10**3 mean = 0 variance = 1 # Create Zero mean, Unit variance laplace and normal sources. normal_source_samples = np.random.normal(0, variance, num_samples) laplacian_source_samples = np.random.laplace(mean, variance /...
The main task of the code is to compress and reconstruct a grayscale image using DCT-based quantization, simulating a noisy channel (Polya) with error probabilities. It processes an image by resizing, translating, DCT transforming, quantizing, channel simulation, decoding, and inverse DCT to reconstruct the image, then...
def main(): # ************************ PICK YOUR CHANNEL TYPE HERE ************************** # channel_type = 'bsc' channel_type = 'polya' dir = "elephants" images = Path(dir).glob('*.jpg') training_images = [] for image in images: training_images.append(cv2.resize(cv2.imread(str(dir+"/"+image....
def isValidMove(self, piece : Piece, newPosition): if newPosition[0] > 8 or newPosition[0] < 0 or newPosition[1] > 8 or newPosition[1] < 0: return False if self.piece_list[newPosition[0]][newPosition[1]] != "--" and self.piece_list[newPosition[0]][newPosition[1]][0] == piece.color[0]: ...
This function moves a game piece to a new position if valid, checks for threats to the opponent's king, captures enemy pieces if applicable, updates the board state, and switches turns. It simulates the move, verifies legality, handles captures, tracks piece counts, and ensures turn-based progression in a board game li...
def move_piece(self, piece : Piece, pos): if self.isValidMove(piece, pos) and self.turn == piece.color: piece_list = self.piece_list.copy() piece_list[pos[0]][pos[1]] = piece_list[piece.position[0]][piece.position[1]] piece_list[piece.position[0]][piece.position[1]] = "--" ...
def draw_cell_labels(self, window, row_index, column_index, piece): label_color = self.settings.theme[1] if piece else self.settings.theme[0] font = pygame.font.SysFont(FONT, 20) if row_index == 0: label = font.render(self.notation[row_index][column_index][0], True, label_color) ...
The main task of the code is to render a game board with cells, pieces, and UI elements. It draws colored cells based on piece presence and selection, displays the current turn, shows captured pieces, positions game pieces using sprites, and highlights available moves for the selected piece.
def draw_board(self, window): # Draw the board cells for row_index, row in enumerate(self.checker): for column_index, piece in enumerate(row): cell_color = self.settings.theme[0] if piece else self.settings.theme[1] if [row_index,column_index] == self.selected...
def load(filename: str) -> Tuple[np.ndarray, np.ndarray]: """Loads filename as a dataset. Assumes the last column is classes, and observations are organized as rows. Args: filename: file to read Returns: A tuple D=(X,y), where X is a list or numpy ndarray of observation attributes ...
The main task of the code is to execute three classifiers (Information Gain, CART, and Gini Index) on a dataset, log their accuracy results, and compare them against actual test labels. It loads training/test data, runs each classifier, stores outcomes in a list, and prints results via logging. The incomplete code at t...
def main(): """This portion of the program will run when run only when main() is called. This is good practice in python, which doesn't have a general entry point unlike C, Java, etc. This way, when you <import HW2>, no code is run - only the functions you explicitly call. """ contents = loa...
def _get_endpoint_url( self, entity: Union[Entity, Type[Entity]], id: Optional[int] = None ) -> str: e_id = entity.id if hasattr(entity, "id") else None if not id: id = e_id endpoint = get_endpoint_from_entity(entity) return f"{self.url}/{endpoint}({id})" if id ...
This function posts an entity to a server, ensuring no duplicate entities (by name) if 'strict' is True. It sends the entity's data (excluding ID) via POST, validates the response, and assigns the server-assigned ID to the entity upon successful creation.
def post(self, entity: Entity, strict: Optional[bool] = True) -> Optional[Entity]: """Post an entity to the server Args: entity: entity instance strict: don't allow double entry of entities (determined by name attr) Returns: Posted entity including assigned ...
def all_license_types(): df = load_data() lst = [] all_occurrences_lst = [] for ind, row in df.iterrows(): all_occurrences_lst.append(row["license_type"]) if row["license_type"] not in lst: lst.append(row["license_type"]) lst = sorted(lst, key=lambda x: all_occurrences_l...
The code creates an interactive Streamlit dashboard for visualizing Massachusetts medicine license data. Users filter data via sidebar options (license types, cities, payment limits) and select visualizations (map, pie chart, bar chart) to display filtered results. An additional button generates a chart showing cities ...
def main(): st.title("# Data Visualisation with Python 📈") st.write('View the data on Medicine Establishment License and Applications - Approved in Massachusetts!') st.write('Open the **:green[sidebar]** to start!') st.sidebar.write("Please select your options to display data") # Streamlit Checkbo...
def iic_init(self): ctrl = 0 prescale = 0 prescale_hi = 0 prescale_lo = 0 print("Info: Disable IIC device") ctrl = self.io_device.io_read(self.io_device, self.CTR) ctrl &= ~(IIC_CORE_EN_MASK | IIC_CORE_IRQ_EN_MASK) if(self.Debug): print('Info: ...
This function reads a single byte from an I2C device at a specified 16-bit address. It splits the address into two bytes, initializes the I2C bus, sends the address with a repeated start condition, receives one byte of data, and returns the received byte.
def iic_read_A16D8(self, addr): data = [] address = [] address.append((addr >> 8) & 0xff) address.append(addr & 0xff) self.iic_init() self.iic_send(0, 0, address, 2, REPEATED_START_OPTIONS) data = self.iic_recv(1) return data[0]
def find_big_contour(contours): biggest_cntr = contours[0] bigt_area =50 for i in contours: area = cv2.contourArea(i) if area > bigt_area : bigt_area = area biggest_cntr = i return biggest_cntr def reorder_points(points): new_points = np.zeros((4,...
This code processes an image of a Sudoku puzzle to extract and prepare individual digit blocks for recognition. It reads the image, applies thresholding and contour detection to identify the Sudoku grid, corrects the perspective to create a square grid, segments the grid into individual cells, and recognizes digits wit...
def extract_sudoku_blocks(image_path): sudoku = cv2.imread(image_path) gray = cv2.cvtColor(sudoku,cv2.COLOR_BGR2GRAY) blur = cv2.blur(gray,(3,3)) thresh = cv2.adaptiveThreshold(gray,255,1,1,11,2) contours,h = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) biggest_cntr = find_...
def find_masked_words(input_sent='',top_k=5, useSpacy=True,stop_words=None,spacy_model=None,pred_model=None,tokenizer=None): """ Based on the cleaned text, mask out interested words for BERT prediction and get the BERT prediction Two ways to split the sentence, by Spacy or NLTk (Spacy is more advanced and t...
The function predicts keywords from a sentence using a BERT model and evaluates their network relevance. It generates scores based on network metrics like authority, modularity class, and centrality, combining BERT predictions with network analysis to assess keyword significance.
def key_word_predict_with_network_from_sent(input_sent=None,top_k=None, filter_NA_pred=True,network_input=None,stop_words=None,spacy_model=None,tokenizer=None,bert_model=None): # print(input_sent) keyword_pred_from_bert_output = find_masked_words(input_sent = input_sent, top_k=top_k,stop_words=stop_words,spacy_...
def intersectarea(p1, p2, size): x1, y1 = p1 x2, y2 = p2 ix1, iy1 = max(x1, x2), max(y1, y2) ix2, iy2 = min(x1+size, x2+size), min(y1+size, y2+size) iarea = abs(ix2-ix1)*abs(iy2-iy1) if iy2 < iy1 or ix2 < ix1: iarea = 0 return iarea def Dist(p1, p2): x1, y1 = p1 x2, y2 = p2 ...
The main task of the code is to cluster spatial coordinates (parts) into groups based on overlapping areas and block length thresholds, then filter out small or non-identical clusters. It sorts parts, assigns them to existing clusters if overlapping sufficiently, merges overlapping clusters, and removes clusters that a...
def clusterparts(parts, block_len, opt): parts = sorted(parts, key=op.itemgetter(-1)) clusters = [[parts[0][-1]]] # assign all parts to clusters for i in range(1, len(parts)): x, y = parts[i][-1] # detect box already in cluster fc = [] for k, cl in enumerate(clusters): ...
def getparts(image, block_len, opt): img = image.convert('L') if image.mode != 'L' else image w, h = img.size parts = [] # Bluring image for abandoning image details and noise. for n in range(int(opt.imblev)): img = img.filter(ImageFilter.SMOOTH_MORE) # Converting image to custom palette...
The code detects and marks identical regions in an image to identify potential copy-move forgeries by splitting the image into blocks, finding similar blocks, clustering them, and returning the count of detected identical regions.
def detect(path, opt, args): block_len = 15 im = Image.open(path) lparts = getparts(im, block_len, opt) dparts = similarparts(lparts, opt) cparts = clusterparts(dparts, block_len, opt) if int( opt.imauto) else [[elem[-1] for elem in dparts]] im = marksimilar(im, cparts, block_len, opt) ...
def DMSG(msg): if DEBUG: print(msg) def DMSG_HEX(char): if DEBUG: print('%x' % char) def writeCommand( header: bytearray, body: bytearray = bytearray()): global _command _command = header[0] data_out = [PN532_PREAMBLE, PN532_STARTCODE1, PN532_STARTCODE2] length = len(header) + ...
The function `writeGPIO` writes an 8-bit value to configure the PN532's P3 GPIO pins, ensuring safety by enforcing reserved pins (P32, P34) to remain high (1). It constructs a command header with the validated pinstate, sends it via `writeCommand`, and checks the response. Reserved pins are forced to 1 to prevent syste...
def writeGPIO( pinstate: int): """ Writes an 8-bit value that sets the state of the PN532's GPIO (P3) :warning: This function is provided exclusively for board testing and is dangerous since it will throw an error if any pin other than the ones marked "Can be used as GPIO" are m...
def writeCommand( header: bytearray, body: bytearray = bytearray()): global _command _command = header[0] data_out = [PN532_PREAMBLE, PN532_STARTCODE1, PN532_STARTCODE2] length = len(header) + len(body) + 1 # length of data field: TFI + DATA data_out.append(length) data_out.append((~length & 0...
The function reads the state of the PN532's P3 GPIO pins by sending a READGPIO command. It returns an 8-bit value representing P30–P35 states, extracted from the response. It also logs P7 GPIO and interface mode pin values from the response.
def readGPIO(): """ Reads the state of the PN532's GPIO pins (P3) :returns: An 8-bit value containing the pin state where: pinState[0] = P30 pinState[1] = P31 pinState[2] = P32 pinState[3] = P33 pinState[4] = P34 pi...
def DMSG(msg): if DEBUG: print(msg) def writeCommand( header: bytearray, body: bytearray = bytearray()): global _command _command = header[0] data_out = [PN532_PREAMBLE, PN532_STARTCODE1, PN532_STARTCODE2] length = len(header) + len(body) + 1 # length of data field: TFI + DATA data_out...
The code configures the Secure Access Module (SAM) by sending a specific command to a PN532 device, setting parameters like mode, timeout, and IRQ pin usage. It writes the command, reads the response, and returns True if successful (status ≥ 0), otherwise False.
def SAMConfig(): """ Configures the SAM (Secure Access Module) :returns: True if success, False if error """ header = bytearray([PN532_COMMAND_SAMCONFIGURATION, 0x01, # normal mode 0x14, # timeout 50ms * 20 = 1 second 0x01])...
def writeCommand( header: bytearray, body: bytearray = bytearray()): global _command _command = header[0] data_out = [PN532_PREAMBLE, PN532_STARTCODE1, PN532_STARTCODE2] length = len(header) + len(body) + 1 # length of data field: TFI + DATA data_out.append(length) data_out.append((~length & 0...
This function waits for an ISO14443A RFID tag to enter the PN532 reader's field, sends an INLISTPASSIVETARGET command with specified baud rate, processes the response to extract the tag's UID and other data (SENS_RES, SAK), and returns the UID if successful. It handles timeout errors and optionally stores the tag numbe...
def readPassiveTargetID( cardbaudrate: int, timeout: int = 1000, inlist: bool = False): # -> (bool, bytearray): global inListedTag """ Waits for an ISO14443A target to enter the field :param cardBaudRate: Baud rate of the card :param timeout: The number of tries before timing out :par...
def writeCommand( header: bytearray, body: bytearray = bytearray()): global _command _command = header[0] data_out = [PN532_PREAMBLE, PN532_STARTCODE1, PN532_STARTCODE2] length = len(header) + len(body) + 1 # length of data field: TFI + DATA data_out.append(length) data_out.append((~length & 0...
This function authenticates a MIFARE card's memory block using the INDATAEXCHANGE command. It sends authentication data including the UID, block number, and key type (A/B) to the card, then checks the response for success (specific byte sequence). Returns True if authentication succeeds, False otherwise.
def mifareclassic_AuthenticateBlock( uid: bytearray, blockNumber: int, keyNumber: int, keyData: bytearray): global _key global _uid """ Tries to authenticate a block of memory on a MIFARE card using the INDATAEXCHANGE command. See section 7.3.8 of the PN532 User Manual for more informat...
def DMSG(msg): if DEBUG: print(msg) def writeCommand( header: bytearray, body: bytearray = bytearray()): global _command _command = header[0] data_out = [PN532_PREAMBLE, PN532_STARTCODE1, PN532_STARTCODE2] length = len(header) + len(body) + 1 # length of data field: TFI + DATA data_out...
The function reads a 16-byte data block from a MIFARE Classic card at the specified block address. It sends a read command, checks for errors in the response, and returns a tuple indicating success/failure and the retrieved data bytes (if valid). The block number must be within card-specific ranges (0–63 for 1KB, 0–255...
def mifareclassic_ReadDataBlock ( blockNumber: int): # -> (bool, bytearray): """ Tries to read an entire 16-bytes data block at the specified block address. :param blockNumber: The block number to authenticate. (0..63 for 1KB cards, and 0..255 for 4KB cards). :param d...
def writeCommand( header: bytearray, body: bytearray = bytearray()): global _command _command = header[0] data_out = [PN532_PREAMBLE, PN532_STARTCODE1, PN532_STARTCODE2] length = len(header) + len(body) + 1 # length of data field: TFI + DATA data_out.append(length) data_out.append((~length & 0...
This function reads a 4-byte page from a Mifare Ultralight card. It constructs a read command with the page number, sends it, checks for errors in the response, and returns the extracted 4 data bytes if successful. If the response indicates an error, it returns False and an empty bytearray.
def mifareultralight_ReadPage( page: int): # -> (bool, bytearray): """ Tries to read an entire 4-bytes page at the specified address. :param page: The page number (0..63 in most cases) :returns: (result, data) result: bool True if successful, False if error data:...
def writeCommand( header: bytearray, body: bytearray = bytearray()): global _command _command = header[0] data_out = [PN532_PREAMBLE, PN532_STARTCODE1, PN532_STARTCODE2] length = len(header) + len(body) + 1 # length of data field: TFI + DATA data_out.append(length) data_out.append((~length & 0...
The function `inDataExchange` exchanges an APDU (Application Protocol Data Unit) with a currently inlisted peer. It sends a command header and data, checks for transmission success, reads the response, verifies the status code for errors, and returns the processed response data or an error indication. The task involves...
def inDataExchange( send: bytearray): # -> (bool, bytearray): global inListedTag """ Exchanges an APDU with the currently inlisted peer :param send: Pointer to data to send :param response: Pointer to response data :param responseLength: Pointer to the response dat...
def DMSG(msg): if DEBUG: print(msg) def writeCommand( header: bytearray, body: bytearray = bytearray()): global _command _command = header[0] data_out = [PN532_PREAMBLE, PN532_STARTCODE1, PN532_STARTCODE2] length = len(header) + len(body) + 1 # length of data field: TFI + DATA data_out...
This function communicates with a passive NFC tag using the PN532 reader, sending an 'INLISTPASSIVETARGET' command to initiate communication. It checks the response: if successful, it stores the tag's data in the global variable `inListedTag` and returns `True`; otherwise, it returns `False`. The process involves sendi...
def inListPassiveTarget(): global inListedTag """ 'InLists' a passive target. PN532 acting as reader/initiator, peer acting as card/responder. :returns: True if command succeeded, False otherwise """ header = bytearray([ PN532_COMMAND_INLISTPASSIVETARGET, 1, ...
def writeCommand( header: bytearray, body: bytearray = bytearray()): global _command _command = header[0] data_out = [PN532_PREAMBLE, PN532_STARTCODE1, PN532_STARTCODE2] length = len(header) + len(body) + 1 # length of data field: TFI + DATA data_out.append(length) data_out.append((~length & 0...
The main task of the code is to send a command to retrieve data from a PN532 device, validate the response status, and return the data length and payload if successful. It checks for write and read errors, logs issues, and returns error codes with empty data on failure.
def tgGetData(): # -> (int, bytearray): header = bytearray([PN532_COMMAND_TGGETDATA]) if (writeCommand(header)): return -1, bytearray() status, response = readResponse() if (0 >= status): return status, bytearray() length = status - 1 if (response[0] != 0): DMSG...
def writeCommand( header: bytearray, body: bytearray = bytearray()): global _command _command = header[0] data_out = [PN532_PREAMBLE, PN532_STARTCODE1, PN532_STARTCODE2] length = len(header) + len(body) + 1 # length of data field: TFI + DATA data_out.append(length) data_out.append((~length & 0...
This function polls for FeliCa cards using a PN532 reader, detecting cards and retrieving their IDm (8 bytes), PMm (8 bytes), and optional System Code (2 bytes). It sends a polling command with specified parameters, checks responses for errors, and returns status codes (success/error) along with card data.
def felica_Polling( systemCode: int, requestCode: int, timeout: int = 1000): # -> (int, bytearray, bytearray, int): global inListedTag """ Poll FeliCa card. PN532 acting as reader/initiator, peer acting as card/responder. :param timeout: :param systemCode: Designatio...
def DMSG(msg): if DEBUG: print(msg) def writeCommand( header: bytearray, body: bytearray = bytearray()): global _command _command = header[0] data_out = [PN532_PREAMBLE, PN532_STARTCODE1, PN532_STARTCODE2] length = len(header) + len(body) + 1 # length of data field: TFI + DATA data_out...
The main task of the code is to send a FeliCa command to an inlisted peer and return the response data along with a status indicating success or error. It constructs a command header, sends the command, checks for errors during transmission, validates the response length and status, and returns the parsed response data...
def felica_SendCommand( command: bytearray): # -> (int, bytearray): """ Sends FeliCa command to the currently inlisted peer :param command: FeliCa command packet. (e.g. 00 FF FF 00 00 for Polling command) :returns: (status, response) status 1: Success, < 0: er...
def DMSG(msg): if DEBUG: print(msg) def writeCommand( header: bytearray, body: bytearray = bytearray()): global _command _command = header[0] data_out = [PN532_PREAMBLE, PN532_STARTCODE1, PN532_STARTCODE2] length = len(header) + len(body) + 1 # length of data field: TFI + DATA data_out...
This function releases all FeliCa targets by sending an INRELEASE command. It checks for ACK confirmation, waits for a response, validates the status code, and returns 1 on success or negative values (-1, -2, -3) for errors like no ACK, missing response, or invalid status.
def felica_Release(): """ Release FeliCa card :returns: 1: Success, < 0: error """ # InRelease header = bytearray([ PN532_COMMAND_INRELEASE, 0x00, # All target ]) DMSG("Release all FeliCa target\n") if (writeCommand(header)): DMSG("No ACK\n") ret...
def set_col_addr( col_start, col_end ): setpin(led, 0) D0 = 0x21 D1 = col_start & 0x7f D2 = col_end & 0x7f myData = [D0, D1, D2] spi.writebytes( myData ) def set_page_addr( page_start, page_end ): setpin(led, 0) D0 = 0x22 D1 = page_start & 0x3 D2 = page_end & 0x3 myData = [D0...
This code displays ASCII characters on an OLED screen using a 7x14 font. It loops through 32 characters per page, maps each character to a 12-byte array from a font table, and sends the data to the display via SPI. It manages column and page addresses to render text in two-page segments, updates the display with delays...
def oledascii(): for k in range(3): start_col = 0 for j in range(32): # 16 characters per two pages mychar = [None] * 12 tmp = j + (k << 5) tmp1 = (tmp << 3) + (tmp << 2) # tmp x 12 for i in range(12): mychar[i] = font7x14...
def initpin(pinnum, mode): ''' pinnum: pin number, eg. 172, 175 etc. mode: pin mode, valid values: in or out ''' if not check_already_exported(pinnum): with open('/sys/class/gpio/export', 'w') as f: f.write(str(pinnum)) with open('/sys/class/gpio/gpio' + str(pinnum) + '/d...
This code tests the SSD1306 OLED display by initializing it via SPI, configuring display settings, drawing patterns using pixel data, displaying ASCII art and text messages, then clearing the display and closing resources. The main task is verifying OLED functionality with visual output and hardware communication.
def ssd1306_test(): initpin(led, 'out') setpin(led, 1) spi.open(2, 0) spi.max_speed_hz = 5000000 ssd1306_init() # set_page_mode() set_horizontal_mode() set_col_addr( 0, 127 ) set_page_addr( 0, 3 ) setpin(led, 1) for j in range(4): i = 0 while i < 128: ...
def waitUntilLoaded(): loading = (driver.find_element('xpath', '//*[@id="divQuestionOptionsMain_Loading"]').value_of_css_property('display') == 'block') while loading == True: loading = (driver.find_element('xpath', '//*[@id="divQuestionOptionsMain_Loading"]').value_of_css_property('display') == 'block'...
The main task of the code is to automate answering questions by reading a CSV file containing responses. It iterates through a specified number of questions, clicks each question in a web interface, waits for it to load, and submits the corresponding answer from the CSV using either text-based or image-based handling m...
def submitAnswers(question_count, file_name): # read the csv file user = os.path.expanduser('~') df = pd.read_csv(user + '\Documents\\' + file_name + '.csv') # looping through each question and answering for i in range(0, question_count): # click on the question number driver....
def _get_keywords(self) -> list: path1 = PROJ_FILE + "/config/places_age.json" path2 = PROJ_FILE + "/config/places_sentiment.json" with open(path1, "rb") as f: age = json.load(f) with open(path2, "rb") as f: sentiment = json.load(f) age_list = age[self.age...
The code gathers and filters search results based on keywords and locations from storage points, aggregating valid results into a list to return.
def get_place(self) -> list: final_res = [] # Final Result to be returned keywords = self._get_keywords() self._points_in_between() for storage in self.store: search_res = self.search(location=(storage[0],storage[1]), keywords=keywords) res = self._filter(search_r...
def geometries(vector, layer = 0): """ Vector spatial data. Vector spatial from layer geometry as type and coordinates. Parameters ---------- vector : str Vector filename. layer : int or str Vector layer index or layer name (the default is 0 for the first layer). Yield...
This function crops multiple raster files based on vector features, using a specified pattern to find input rasters. It processes each raster by clipping it to all features in the vector, naming output files with values from a specified vector column. The cropped rasters are saved in the output path with a format defin...
def multiples(vector, column, pattern, input_path, output_path, driver = 'GTiff'): """ Crop the multiples rasters for each vector features. Find the rasters files by pattern and crops these by all features of the vector. The vector column name defines the property value to connect the raster output fil...
def log(*text): global prefix1, prefix2, _prev_prefix if prefix1 != _prev_prefix: prefix = prefix1 _prev_prefix = prefix1 else: prefix = prefix2 print(prefix, *text, file=args.errf) def ignore(*args): if len(args) == 1 and hasattr(args[0], '__call__'): func = args[0] ...
The code defines a function `latex_newcommand` to handle LaTeX macro creation. It checks if a command name is provided, verifies if the command should be ignored, and either creates a new macro or redefines an existing one. It logs warnings for redefinitions and ensures proper macro registration, returning the command ...
def latex_newcommand(name=None, definition=None, redefine=False): if name is None: if args.verbose >= 3: log(r'Ignoring \newcommand, not on standard form (no proper argument)') ignore() # Check if the command is one that is explicitly ignored by user if get_macro(name[1:]) == ign...
def get_scope(x=None): global main_parser_scope, parser_scopes if not x: return main_parser_scope if not parser_scopes: parser_scopes[x] = main_parser_scope if not x in parser_scopes: new_scope = main_parser_scope.copy() remove_macros_from(new_scope) new_scope['__...
This code defines a function `set_print_mode` that replaces the print behavior of a specified command (`cmd`) with a LaTeX-formatted print function. It searches for `cmd` in different scopes (macro, current scope, built-ins) and replaces its definition with a new function generated by `latex_print`, using the provided ...
def set_print_mode(cmd, n=None, format='%s'): args.output = False scope = get_scope() if hasattr(get_macro(), cmd): where = get_macro().__dict__ elif cmd in scope: where = scope elif hasattr(scope['__builtin__'], cmd): where = scope['__builtin__'].__dict__ else: w...
def include(fname): with open(fname) as f: code = map(fixup_line, f.readlines()) exec_block(''.join(code)) def fixup_line(l): for replace_re, replace_with in replacers: l = replace_re.sub(replace_with, l) return l def exec_block(lines): if args.verbose >= 3: debuglines = ...
This function parses command-line arguments to configure processing parameters. It handles options like output file handling, verbosity, macro/block display, inclusion of files, expression execution, and parsing modes. It updates global `args` object properties based on flags and sets `args.infiles` to remaining argume...
def parse_args(): global args if len(sys.argv) <= 1: print(__doc__) sys.exit(1) idx = 1 while idx < len(sys.argv): arg = sys.argv[idx] if arg in ['-o', '--output']: idx += 1 args.outf_name = sys.argv[idx] args.base_name, ext = os.path...
def parse_args(): global args if len(sys.argv) <= 1: print(__doc__) sys.exit(1) idx = 1 while idx < len(sys.argv): arg = sys.argv[idx] if arg in ['-o', '--output']: idx += 1 args.outf_name = sys.argv[idx] args.base_name, ext = os.path...
The main task of the code is to process input files based on command-line arguments, handling two-pass parsing if enabled, writing parsed lines to an output file when specified, and optionally executing tasks like displaying macros or building LaTeX documents. It manages file operations, argument parsing, and condition...
def main(): global args parse_args() with closing(args.errf): if args.two_pass: for inf in args.infiles: parse(inf) args.two_pass = 2 with closing(args.outf): for inf in args.infiles: lines = parse(inf) if a...
def extract_json_from_script(all_scripts, start_split, end_split, trim_length=None): parts = [] for script in all_scripts: try: scriptstr = str(script) parts = scriptstr.split(start_split) except ValueError as e: print('Error in extract_json_from_script: {}'.f...
The code scrapes YouTube channel video data by parsing HTML, extracting JSON from scripts, handling pagination via continuation URLs, and optionally saving results to a CSV file.
def scrape(channel, write=None, path=None): if not path: path = Path('youtube-{}.csv'.format(channel)) else: path = Path(path) with httpx.Client(http2=True) as session: headers = {'User-Agent': USER_AGENT} r = session.get(url=URL.format(channel), headers=headers) sou...
def setP(self, p): if(not self.__checkParams(p)): self.p = p def setQ(self, q): if(not self.__checkParams(q)): self.q = q def __setN(self): self.n = self.p * self.q def __setSeed(self): while(not coprime(self.n, self.seed) and self.seed < 1): self.seed...
The code initializes an object with parameters p and q, validates they are positive, and sets internal attributes N and a seed for subsequent operations, likely for cryptographic or mathematical processing.
def __init__(self, p, q): self.setP(p) self.setQ(q) if(self.p > 0 and self.q > 0): self.__setN() self.__setSeed()
def to_underscores(name, num_pass = 0): r = re.compile(r'([A-Za-z][0-9]|[0-9][A-z]|[a-z][A-Z]|[A-Z][A-Z][a-z]|[_\/:][A-z])') ret = '' tokens = r.split(name, 1) while True: if len(tokens) > 1: if tokens[1][0] == '/' or tokens[1][0] == ':' or tokens[1][0] == '_' or tokens[1][1] == '_':...
The code generates a C++ header file for an initializer class, dynamically creating a class with constructors, methods, and includes based on input parameters. It constructs a class template with namespace-specific naming, handles default constructors, and includes user-defined data fields and validation logic. The out...
def construct(namespace, calss_name_orig, data, include): class_name = calss_name_orig + "Initializer" ret = """// This file was automatically generated. Do not edit this file! #ifndef INITIALIZER_""" + namespace.upper() + "_" + to_underscores(class_name).upper() + """_H #define INITIALIZER_""" + namespace.uppe...
def parse_file(file_name): with open(file_name) as f: lines = f.readlines() data = [] include = [] extends = [] names = [] i = 0 optionalOnly = False for l in lines: i = i + 1 d = parse_line(l, i, file_name) if d != None: if 'Required' in d: ...
This function collects and aggregates extension, data, and include information from input files and their dependencies. It recursively processes extension files, merges data entries by class name, and ensures unique includes. The result is a consolidated content dictionary with class name, extended elements, data recor...
def collect_extensions(input_files, search_dirs, content): file_content = parse_file(input_files) class_name = file_content['ClassName'] if 'Extends' in file_content: for e in file_content['Extends']: if not contains_extends(e, content['Extends']): file_name = None ...
def collect_extensions(input_files, search_dirs, content): file_content = parse_file(input_files) class_name = file_content['ClassName'] if 'Extends' in file_content: for e in file_content['Extends']: if not contains_extends(e, content['Extends']): file_name = None ...
The main task of the code is to generate output files by collecting extension data from input files, constructing formatted content using a namespace and sorted data, creating necessary directories, writing the generated text to the output file, and returning the class name from the processed content.
def generate(input_files, output_files, namespace, search_dirs, devel_dir): print("Generating " + output_files) content = collect_extensions(input_files, search_dirs, {'Data' : [], 'Include' : [], 'Extends' : []}) txt = construct(namespace, content['ClassName'], sort_data(content['Data']), content['Include'...
def get_primary_key(self, table_name: str) -> str or None: """Get primary key from table. :param table_name: Target table. :type table_name: str :return: Column name has primary key if it exists. :rtype: str or None """ cursor = self._execute(f"PRAGMA table_info(...
The main task of the code is to either add new data to a database table or update existing data based on the presence of a primary key in the provided dictionary. If the primary key exists in the input data, it updates the record; otherwise, it inserts a new record. This function simplifies database operations by handl...
def add_or_update(self, table_name: str, data: dict) -> None: """Add new data if there is no data that has same primary key, or update data. :param table_name: target table :type table_name: str :param data: data typed column to value :type data: dict """ ...
def maxlloyd(germs,griddimensions,iterations): ''' Actual implementation of Max-Lloyd algorithm. Regions delimiters are a set of variables [a1,a2,...an,b] , which are parameters of the equation a1*x1 + a2*x2 + ... + an*xn + b <= 0 griddimensions indicates the number of points on eac...
The code generates figures for a paper by applying the maxlloyd algorithm to randomly initialized germs, computing the Mean Squared Error (MSE) between regions and germs on a high-resolution grid, and visualizing the resulting regions. It uses 16 random germs, iterates maxlloyd 30 times on a 100x100 grid, evaluates MSE...
def performance(): '''generate figures with maxlloyd function for the paper''' #germs = np.array([[0.,-1.],[0.,1.]])#2 #germs = np.array([[0.,-1.],[-0.75,0.25],[0.75,0.25]])#3 #germs = np.array([[0.5,-0.5],[-0.75,-0.75],[-0.25,0.]])#3bis #germs = np.array([[0.,1.],[-1.,0.],[1.,0.],[0.,-1.]])#4 #...
def maxlloyd(germs,griddimensions,iterations): ''' Actual implementation of Max-Lloyd algorithm. Regions delimiters are a set of variables [a1,a2,...an,b] , which are parameters of the equation a1*x1 + a2*x2 + ... + an*xn + b <= 0 griddimensions indicates the number of points on eac...
The code tests the `maxlloyd` function by initializing germ points, applying the algorithm with specified grid dimensions and iterations, visualizing resulting regions, calculating mean squared error between regions and germs, and returning updated germs and regions for validation.
def test_maxlloyd(): '''Test for maxlloyd function''' germs = np.array([[1.,1.],[-1.,2.] ,[0.,0.],[2.,1.],[1.,-1.],[-1.,-2.],[3.,-2.],[3.,1.]]) grid_dim = [60,60] iterations = 20 germs,regions = maxlloyd(germs,grid_dim,iterations) displayregions(grid_dim,regions) MSE(regions,germs,grid_dim) ...
def remove_id_from_roster(self, student): # When a student is removed from the roster, this function searches the queue and removes them first_remove = True student = int(student) # added this line while student in self.front_bag: self.front_bag.remove(student) if...
This function updates the student queue by identifying and removing students no longer in the updated roster, while adding newly included students. It compares old and new roster lists, then applies changes to the queue through dedicated methods, followed by updating student data.
def update_roster_and_queue(self): # Updates the queue by adding or removing IDs from students added or removed to the roster when editing old_list = self.data_repo.newqueue() remove_list = [] add_list = [] if self.data_repo.editterm() == "roster successfully updated": ...
def toggle_window(self): if not self.VISIBLE: #Show self.VISIBLE = True if self.ICON: self.ICON.stop() del self.ICON gc.collect() self.ICON = None self.deiconify() else: #Hide ...
The code updates the application's state by checking visibility, updating the title with key count and version, resetting weekly totals on the start of the week, tracking user activity, calculating average keys per hour/minute, updating UI elements like notify dots, and scheduling the next update. It also toggles windo...
def update(self): #Check Visibility and Iconify if not visible if self.INITIAL_UPDATE: #once the app updates once if not self.winfo_viewable() and not self.ICON: self.toggle_window() #Update ICON Title if self.ICON: self.ICON._title = f'{self.tota...
def preprocess(data): data = convert_lower_case(data) data = remove_punctuation(data) #remove comma seperately data = remove_apostrophe(data) data = remove_stop_words(data) data = convert_numbers(data) data = stemming(data) data = remove_punctuation(data) data = convert_numbers(data) ...
The function `rochchio` optimizes a query vector for information retrieval using either a standard or fast method based on the `choice` parameter. It tokenizes and preprocesses the input query, generates a weighted vector, and adjusts it using relevant (`reldoc_ids`) and non-relevant (`nonreldoc_ids`) documents. If `ch...
def rochchio(query,reldoc_ids,nonreldoc_ids,choice): analyzed_query = word_tokenize(str(preprocess(query))) query_vector=weights_norms(analyzed_query) if(choice==0): return queryoptimizer(query_vector,reldoc_ids,nonreldoc_ids) else: return queryoptimizer_fast(query_vector,reldoc_ids,nonr...
def show_menu(): keyboard_count = requests.get(HOSTNAME + 'get_use_count/', timeout=10).text os.system('clear') print(' Keylogger '.center(50, '-')) print(f'Today: {date.today()}'.ljust(24), f'Counted keys: {keyboard_count}'.rjust(25)) print('-'*50) print( "1. Show the most used keys\...
The main task of the code is to run a command-line interface (CLI) menu loop that repeatedly displays options for users to select actions: viewing most-used keys, retrieving log files, displaying weekly graphics, or exiting. The loop continues until the user chooses to terminate it by selecting option 4, which sets `ru...
def main(): run_cli = True while run_cli: option = show_menu() match option: case 1: show_most_used_keys() case 2: get_log_file() case 3: show_weekly_graphic() case 4: run_cli = Fals...
def module_to_json(m): varnames = [ v for v in dir(m) if not v.startswith('__') ] return json.dumps(prepare_for_json({ v: getattr(m, v) for v in varnames })) def set_up_model_table(conn, cur): create_query = """ CREATE TABLE IF NOT EXISTS {SCHEMA}.{MODEL_TABLENAM...
The main task of the code is to train a neural network model for a specified number of epochs, using batched training data, while logging performance metrics. It either creates a new model or loads an existing one, evaluates the model on test data after each epoch, saves the trained model with a timestamp, and stores i...
def main(): # for recordkeeping constants_json = module_to_json(c) logger.debug('Constants JSON: %s' % constants_json) fetcher = TrainFetcher() conn = get_pg_conn() cur=conn.cursor() set_up_model_table(conn, cur) os.makedirs(c.MODEL_DIRECTORY, exist_ok=True) if len(sys.argv) ...
def flipX(count): # fliping the cube on the x-axis for x in range(count): flipperMotor.run_to_position(flipperHold) flipperMotor.run_to_position(flipperFlip) wait_for_seconds(.5) def scanFace(face): # center flipperMotor.run_to_position(flipperScanCenter) scanTile(face, 5)...
The main task of the code is to scan all six faces of a Rubik's cube by rotating and flipping it systematically using motors, capture color data from each face, reorient the cube to its original position, compile the scan results into a string, and transmit the cube's state via JSON-RPC to a Raspberry Pi for solving.
def scanCube(): # scaning the whole cube flipperMotor.run_to_position(flipperHold) flipX(1) scanFace(Face.U) flipX(1) scanFace(Face.F) flipX(1) scanFace(Face.D) flipX(1) rotateY(2) scanFace(Face.B) rotateY(1, prime) flipX(1) rotateY(1) scanFace(Face.R) fli...
def main(self): print(f"building ... version:{self.get_develop_version()}") parent = Path(__file__).parent self.read_me_file() file_name = Path() / parent / package_name / "__version__.py" print(file_name) self.write(file_name, f"#{self.get_develop_version()}") def get_t...
The code defines a `__post_init__` method that initializes the object by calling `self.main()`, then conditionally generates a run command via `self.create_run_command()` if `get_test_env()` returns true, handling environment-specific setup during object creation.
def __post_init__(self): self.main() if get_test_env(): self.create_run_command()
def flow_to_unit(flow): flow_unit = flow.copy() for row in range(len(flow_unit)): for col in range(len(flow_unit[0])): dx = flow[row][col][0] dy = flow[row][col][1] dx, dy = unitize_xy(dx, dy) flow_unit[row][col][0] = dx flow_unit[row][col][1] = dy return flow_unit def flow_to_bins(flow, bin_num):...
The main task of the code is to process a video using optical flow (Lucas-Kanade method) to compute and visualize motion vectors, binning directions, and weighted histograms over a sliding window. It tracks timing for each processing stage, generates visualizations of raw flow, unit flow, bin histograms, and weighted h...
def main(video, outpath, height, window_size, grid_size, bin_size, wave_dir): # init dict to track time for every stage at each iteration timers = { "full pipeline": [], "reading": [], "pre-process": [], "optical flow": [], "post-process": [], } print("reading ", video) filename = os.path.splitext(os...
def _mina_enabled(context: Context) -> bool: tool_mina = context.config.data.get("tool", {}).get("mina", {}) return bool(tool_mina.get("enabled")) def _get_build_target(context: Context) -> str | None: tool_mina = context.config.data.get("tool", {}).get("mina", {}) return ( context.config_settin...
This function initializes a build process for the Mina framework by checking if it's enabled, retrieving the build target, and updating the configuration with the target if valid.
def pdm_build_initialize(context: Context) -> None: if not _mina_enabled(context): return mina_target = _get_build_target(context) if mina_target is None: return _update_config(context.config, mina_target)
def __createDataSet(restype, img_num): print("------------------+++++++++++++============FOR %s SET==============++++++++++++++---------------------- \n" % restype.upper()) if (((pathlib.Path('dataset.npz')).exists() == True) & ((pathlib.Path('dataset.npz')).is_file() == True)): dset, featnames = (np.lo...
The main task of the code is to provide a menu-driven interface for melanoma-skin-lesion detection using image processing and machine learning. It allows users to create training/test datasets, train classifiers/regressors, predict results, analyze features, plot graphs, and manage project files. The system leverages O...
def main_menu(): print("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^_______WELCOME TO THE MELANOMA-PREDICTION PROGRAM_______^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ \n") print("\t This is a nascent approach towards detecting Melanoma-Skin-Lesion, using OpenCV, NumPY, Matplotlib and SciKit in Pytho...
def get_input(): while True: try: p0 = tuple(map(float, input("Koordinat titik p0 (x y): ").split())) p1 = tuple(map(float, input("Koordinat titik p1 (x y): ").split())) p2 = tuple(map(float, input("Koordinat titik p2 (x y): ").split())) iteration = int(input(...
The main task of the code is to implement a divide-and-conquer algorithm for generating Bezier curves using three control points and a specified number of iterations. It measures execution time, plots the resulting curve, control polygon, and control points, then displays the visualization with a legend. The code empha...
def main(): p0, p1, p2, iteration = get_input() # Start time start_time = time.time() points = [p0,p1,p2] # Devide Conquer result(p0, p1, p2, iteration) end_time = time.time() # end time setelah dnc # # Plot Bezier Curves plot_curve(curve_points, 'Bezier Curves', 'orange', ...
def is_nearby(self, position1: Position, position2: Position, distance_threshold: int = 1): """Check if two positions are nearby within a given distance threshold.""" distance = abs(position1.x - position2.x) + abs(position1.y - position2.y) return distance <= distance_threshold def calculate_di...
The code determines the next move for a bot by prioritizing: attacking nearby enemy bots carrying diamonds, returning to its base if carrying 5 diamonds, or searching for the nearest diamond otherwise. It calculates direction deltas to reach the goal position, handling enemy engagement, resource collection, and base re...
def next_move(self, board_bot: GameObject, board: Board): props = board_bot.properties current_position = board_bot.position # Check if there are nearby enemy bots nearby_enemy_bots = [enemy_bot for enemy_bot in board.bots if enemy_bot != board_bot and self.is_nearby(current_position, e...
def input_instance(json_file): if os.path.exists(path=json_file): with io.open(json_file, 'rt', newline='') as file_object: return load(file_object) return None def route_cost(individual, instance, unit_cost=1): total_cost = 0 route_updated = route_subroute(individual, instance) ...
The code tests and compares the cost and fitness of two sample routes (individuals) for a given problem instance. It loads data, generates a random permutation of a predefined route, calculates their route costs using `route_cost()`, and evaluates fitness via `evaluate_fitness()`, printing results for analysis.
def testcosts(): # Sample instance test_instance = input_instance('./data/json/Input_Data.json') # Sample individual sample_individual = [19, 5, 24, 7, 16, 23, 22, 2, 12, 8, 20, 25, 21, 18, 11, 15, 1, 14, 17, 6, 4, 13, 10, 3, 9] # Sample individual 2 sample_ind_2 = random.sample(sample_individ...
def getRandomPrimes(self,length): minLength = 3 # Since the two primes must be in a certain range the min and max values for both can be calculated: # Min value for primes is still set by the blocksize if length < minLength: print("\nWARNING: Length chosen is smaller than m...
This code initializes an RSA cryptosystem by generating or using provided prime numbers (p, q) to compute the modulus n = p*q. It calculates the public key exponent e and private key exponent d using Euler's Totient Function (ETF) of n, ensuring e is coprime with ETF(n). If primes are not provided, it uses a Blum-Blum-...
def __init__(self,primeDigits,p=None,q=None,e=None,d=None): self.BBS = PRNG_BBS() if p is None: pq = self.getRandomPrimes(primeDigits) # 1st prime number self.p = pq[0] # 2nd prime number self.q = pq[1] self.n = self.p * self.q ...
def send_string_expect_response(client, message): # client.send(message+u"\u0003".encode()) print(f'Sending this string to client: {message}. Response expected') client.send((message+"\u2404").encode()) def receive_string_from_client(client): # (NEED TO TEST IF RECV SIZE OF 1024 IS SUFICIENT FOR ALL STRING SIZE...
This function provides a client-server menu interface allowing users to display information, add points, purchase tickets, cancel events, or exit. It loops to handle user input, routing choices to corresponding functions like display_user_information or purchase_tickets. Exiting triggers a shutdown sequence, sending a ...
def client_server_main_menu(socket, client, user): main_menu = "\n1.Display User Information\n2.Add Points\n3.Purchase Tickets\n4.Cancel Event\n5.Exit" continue_displaying_menu = True while continue_displaying_menu: send_string_expect_response(client, main_menu) client_input = receive_string_from_client(c...
def server_setup(): s = socket.socket() print("Socket successfully created") port = 52222 s.bind(('', port)) s.listen(5) c, addr = s.accept() return s, c def client_server_login_menu(socket, client): print('Executing client_server_login_menu') #this was for testing login_menu = "\n1.Sign-Up\n2.Log-I...
The code's main task is to initialize a server connection, authenticate a user, and navigate to the main menu. It starts by setting up a server socket and client connection, then prompts the user for login credentials. Upon successful authentication, it transitions to the main menu interface, which likely provides opti...
def main(): socket, client = server_setup() user = client_server_login_menu(socket, client) client_server_main_menu(socket, client, user)
def load_free_play(self): # Load dance party free-play level self.driver.get('{origin}s/dance-2019/stage/1/puzzle/10?noautoplay=true'.format(origin=self.origin)) # Enter age and dismiss dialog, which causes a page reload self.bypass_age_dialog() # Wait for the page to load agai...
The main task of the code is to execute a specified program multiple times for a defined duration, capturing timing data after each run. It initializes the program setup, runs it repeatedly with pauses, records performance metrics, and takes a final screenshot after the last execution. The function manages program exec...
def run_program(self, block_xml, program_name, run_duration=15, repeat_runs=1): print('-- Running {program_name} for {run_duration} seconds {repeat_runs} times --'.format( program_name=program_name, run_duration=run_duration, repeat_runs=repeat_runs )) self.load_free_play() ...
def get_valid_start_number(): while True: try: start_number = int(input( "Type in the first number and press enter to start the generation...\nStart number: ")) if start_number > 0: return start_number else: print("\nERROR: ...
The code generates TeachPos files (`.src` and `.dat`) from a `pos.csv` input. It reads and parses CSV data, processes hierarchical folding information, and writes structured output files. Key steps include validating input parameters, parsing header mappings, handling errors, and generating program files for teaching p...
def main(): print('''********************************* | Welcome to TeachPos Generator | ********************************* Create your pos.csv in the same folder as this script For more information visit: https://github.com/zserub/TeachPos-Generator ''') start_number = get_valid_start_num...
def parse_result(result): result = result.decode("utf-8") result = result.split("\n") heap = {} for var in result[result.index("HEAP:")+1:]: if "=" not in var: continue [id, v] = var.split(" = ") heap[id] = v parsed_result = {} for var in result[2:result.index("HEAP:")]: [id, v] = var.split(" = ") pa...
The code tests if the output of a system under test (SUT) when run with a specific test case matches an expected result. It executes the SUT, parses its output, compares it to a pre-defined expected value from a file, and reports success or failure accordingly.
def test_correctnes(sut, test, expected): result = subprocess.run([sut, test], stdout=subprocess.PIPE) actual_result = parse_result(result.stdout) expected_result = eval(open(expected).read()) if actual_result == expected_result: passed(test) else: failed(test)
def login(self): with requests.Session() as session: post = session.post('https://talar.sfb833.uni-tuebingen.de/erdora/login', data = {"username": self.username, "password": self.password}) self.session = session def connect_to_URL(self, url, file=False): for i i...
This code validates CMDI files from an OAI-PMH repository by parsing XML, checking URLs for 404 errors, and validating resource links. It tracks errors, counts records, and returns a dictionary of validation issues.
def validate_oai(self, xml): self.cmdi_counter = 0 self.resource_counter = 0 self.profiles = {} self.person_set = set() self.errors = {} tree = etree.parse(xml) self.login() all_cmdis = tree.xpath("//*[local-name()='record']") # retri...
def login(self): with requests.Session() as session: post = session.post('https://talar.sfb833.uni-tuebingen.de/erdora/login', data = {"username": self.username, "password": self.password}) self.session = session def add_error(self, error, cmdi): if self.errors.g...
The main task of the code is to validate Access Control Lists (ACLs) for resources listed in an OAI-PMH XML file. It parses the XML, extracts resource handles, performs HEAD requests to check redirects, and stores ACL validation results in a dictionary. The code processes each record's ResourceProxy entries, identifies...
def validate_oai(self, xml): self.acl_dict = {} self.login() tree = ET.parse(xml) root = tree.getroot() all_cmdis = root.findall(".//{http://www.openarchives.org/OAI/2.0/}record") for cmdi in all_cmdis: # get the correct component namespace; ...
def is_valid_directional_move(self, row: int, col: int, rowdelta: int, coldelta: int, turn: str) -> bool: current_row = row + rowdelta current_col = col + coldelta last_cell_color = self.opposite_turn(turn) while True: if not self.is_valid_cell(current_row, current_col): ...
This function flips adjacent cells in a specified direction during a game, starting from a given cell, as long as those cells belong to the opponent's color. It checks validity first, then iteratively moves and flips cells until reaching a boundary or a cell of the same color.
def convert_adjacent_cells_in_direction(self, row: int, col: int,rowdelta: int, coldelta: int, turn: str): if self.is_valid_directional_move(row, col, rowdelta, coldelta, turn): current_row = row + rowdelta current_col = col + coldelta while self.cell_color(curre...
def require_valid_empty_space_to_move(self, row: int, col: int) -> bool: if self.is_valid_cell(row, col) and self.cell_color(row, col) != NONE: raise InvalidMoveException() def adjacent_opposite_color_directions(self, row: int, col: int, turn: str) -> [tuple]: dir_list = [] for rowde...
This code handles a player's move in a turn-based board game by validating the move, flipping adjacent opponent pieces in valid directions, and switching turns if the move changes the turn state. It checks for valid empty spaces, identifies possible directions, executes flips, and raises an exception if the move is inv...
def move(self, row: int, col: int): self.require_valid_empty_space_to_move(row, col) possible_directions = self.adjacent_opposite_color_directions(row, col, self.turn) next_turn = self.turn for direction in possible_directions: if self.is_valid_directional_move(row, ...
def consume_kv_pair(lexer: Lexer) -> Tuple[str, str]: key = consume_lvalue(lexer) lexer.consume(":") value = consume_rvalue(lexer) return (key, value) def consume_space(lexer: Lexer) -> bool: c = lexer.get() return c in SPACE_CHARS
The main task of the code is to parse a passport by consuming key-value pairs from a lexer. It first consumes a single key-value pair, then checks if additional pairs can be consumed based on spacing and character validity. If valid, it recursively continues parsing and concatenates the results into a list of key-value...
def consume_passport(lexer: Lexer) -> Passport: kv_pair = consume_kv_pair(lexer) if not consume_space(lexer) or lexer.peek() not in LVALUE_CHARS: return [kv_pair] else: return [kv_pair] + consume_passport(lexer)
def __blockify(self, image): len_rounded = int(image.shape[0]/8) width_rounded = int(image.shape[1]/8) return_array = np.zeros(shape=(len_rounded*8, width_rounded*8)) for i in range(len_rounded): for j in range(width_rounded): image_block = np.array(image[i*8...
The code's main task is to build a training set from images in a specified directory. It processes each image by either sequentially generating training data from all blocks (when `random=False`) or randomly sampling 100 blocks per image (when `random=True`). The function collects these blocks into a list called `self....
def import_training_set(self, image_path, random = False): self.training_set = [] files = [f for f in os.listdir(image_path)] #files = files[:20] if '.DS_Store' in files: files.remove('.DS_Store') if not random: count = 0 for image_name in file...
def save_slice(self, slice: typing.Tuple[RawAudio, int, int]) -> None: audio, start, end = slice date = datetime.utcnow().strftime("%Y-%m-%d-%H:%M:%S") prefix = date if self.interest_name is None else self.interest_name filename = os.path.join(self.slices_dir, f'{prefix}_slice_{self.to_...
This code evaluates audio slices to detect interesting segments using a model. It updates a sliding window with probabilities, triggers interest states based on thresholds, generates visual progress indicators, and logs details like timestamps and confidence levels. It returns the window's summed probability and normal...
def evaluate_slice(self, slice: typing.Tuple[RawAudio, int, int]) -> typing.Tuple[int, int]: audio, start, end = slice probability = self.model.evaluate_array(audio.T) if probability >= 0.5: self.save_slice(slice) self.floating_window[self.window_in...
def process_audio(self, sig: np.ndarray, sr: int) -> RawAudio: # Convert to stereo if sig.ndim == 1: sig = np.repeat(np.expand_dims(sig, axis=0), 2, axis=0) if sig.ndim != 2 or 2 not in sig.shape: tqdm.write(F'Audio chunk array has wrong dimensions: {sig.shape}') ...
The main task of the code is to process and analyze audio data to detect burps. It resamples/transposes input audio, appends it to a buffer, generates slices, evaluates each slice with a model using vote thresholds, counts detected burps, and trims the buffer. It returns the number of detected burps or None if no slice...
def add_audio_from_array(self, sig: np.ndarray, sr: int): # Resample and transpose if necessary audio = self.process_audio(sig, sr) if audio is None: return None # Append to buffer self.append_data(audio) # Generate slices if enough data slices = se...
def class_proposal(self, imgs: List[Tensor]) -> List[Tuple[int, List[int]]]: """Algorithm 1: Class proposal. Args: imgs (List[Tensor]): List of image tensors, shape=[1, C, H, W]. Returns: List[Tuple[int, List[int]]]: List of proposals, containing primar...
The function generates class proposals and masks for input images, then evaluates them against test images to compute fooling results and average confidence scores, returning both as lists.
def obtain_features(self, imgs: List[Tensor], test_imgs: List[Tensor]) -> Tuple[List[int], List[float]]: self.logger.info(f'Class proposal for {len(imgs)} images...') cls_proposals = self.class_proposal(imgs) self.logger.info(f'Mask generation for {len(imgs)} images...') masks = self.mas...
def _log_config(self): save_path = os.path.join(self.log_path, 'sentinet-config.json') with open(save_path, 'w') as f: f.write(json.dumps(self.cfg.__dict__, indent=1)) self.logger.info(f'Config file saved into {save_path}') def train_on_benign(self, benign_imgs: List[Tensor], test_im...
The code's main task is to detect adversarial examples by training a model on benign images and testing it on adversarial samples. It loads test and benign images, trains the model, evaluates it on adversarial images, logs results, and returns training/test data, predictions, and metrics in a dictionary.
def detect(self) -> dict: self._log_config() test_imgs = load_image_tensor( self.test_imgs[:self.cfg.test_img_num], size=self.input_size, device=self.device) assert len(test_imgs) != 0 self.logger.info(f'{len(test_imgs)} test images loaded.') # Train model sel...
def chooseSecretWord(self): """ Chooses the secret word that will be guessed """ randomWord = random.choice(list(self.wordDic.keys())) self.secretWord.setWord(randomWord) def setGuessAmount(self): dist = self.editDistance(self.secretWord, self.secretWord.sort()) if dist in range(...
The code's main task is to execute a Word Guess game by selecting a secret word, allowing the player a set number of guesses, and iterating until the word is solved or guesses are exhausted. It tracks progress, displays remaining guesses, collects user input, and announces the result, revealing the secret word at the e...
def play(self): """ Plays out a single full game of Word Guess """ self.chooseSecretWord() self.setGuessAmount() print('A secret word has been randomly chosen!') while not self.secretWord.isSolved() and self.allotedGuesses != 0: print('You have %d guesses remaining' ...
def fitSpectralClusters(img, numClusters, subsamplePcnt, imgNullVal, fixedKMeansInit): """ First step of Shepherd segmentation. Use K-means clustering to create a set of "seed" segments, labelled only with their spectral cluster number. The img array has shape (nBands, nRows, nCols). n...
This function performs Shepherd segmentation on a multi-band image array by clustering spectral data with KMeans, merging regions via clumping (4/8-connected), eliminating small segments, and returning a SegmentationResult object containing the segmented image and metadata. It allows customization of clustering paramet...
def doShepherdSegmentation(img, numClusters=60, clusterSubsamplePcnt=1, minSegmentSize=50, maxSpectralDiff='auto', imgNullVal=None, fourConnected=True, verbose=False, fixedKMeansInit=False, kmeansObj=None, spectDistPcntile=50): """ Perform Shepherd segmentation in memory, on the given ...
def fitSpectralClustersWholeFile(inDs, bandNumbers, numClusters=60, subsamplePcnt=None, imgNullVal=None, fixedKMeansInit=False): """ Given a raster filename, read a selected sample of pixels and use these to fit a spectral cluster model. Uses GDAL to read the pixels, and shepseg.fitSpe...
This function performs memory-efficient Shepherd segmentation on large raster images by dividing them into overlapping tiles, applying spectral clustering on a subsampled whole-raster to generate consistent cluster seeds, segmenting each tile individually, and stitching results into a unified output. It handles tile ov...
def doTiledShepherdSegmentation(infile, outfile, tileSize=DFLT_TILESIZE, overlapSize=DFLT_OVERLAPSIZE, minSegmentSize=50, numClusters=60, bandNumbers=None, subsamplePcnt=None, maxSpectralDiff='auto', imgNullVal=None, fixedKMeansInit=False, fourConnected=True, verbose=False, simpleTil...
def equal_temperament(midi_number): return ( np.power(OCTAVE_FREQUENCY_RATIO, (midi_number - REF_NOTE) / NB_NOTES_IN_SCALE) * REF_FREQUENCY, 0, ) def pythagorean_tuning(midi_number): note = int((midi_number - REF_NOTE) % NB_NOTES_IN_SCALE) octave = (midi_number - REF_NOTE - note)...
This function converts a MIDI note number to its corresponding frequency using different musical temperaments (equal temperament, Pythagorean tuning, or just intonation) based on the TEMPERAMENT setting. It returns the calculated frequency and optionally prints debug information if enabled.
def midi_to_frequency(midi_number, memory): result = 0 if TEMPERAMENT == 0: result = equal_temperament(midi_number) elif TEMPERAMENT == 1: result = pythagorean_tuning(midi_number) elif TEMPERAMENT == 2: result = just_intonation(midi_number, memory) if DEBUG: print("k...
def _add_to_dialog(self, message): """ Add a message to the dialog history. The method adds a message to the dialog history and removes the oldest message if the history exceeds a certain length. Args: message (str): The message to add to the dialog history. ...
The main task of the code is to generate a response based on user input by retrieving relevant knowledge from a document store, combining it with the dialog history, and updating the conversation with the generated response.
def chat(self, user_input): """ Generate a response based on user input and relevant knowledge. This method searches for relevant knowledge in the document store, generates a response using the retrieved knowledge and dialog history, and adds the response to the dialog history. ...
def declare_ros_parameter(self, name, default, descriptor): # When the automatically_declare_parameters_from_overrides parameter to # rclpy.create_node() is True, then any parameters passed in on the # command-line are automatically declared. In that case, calling # node.declare_paramet...
This code initializes a ROS2 node for publishing joint states. It declares parameters for configuration, loads a URDF file or subscribes to the robot_description topic, processes joint dependencies, and sets up publishers/subscribers to generate and broadcast joint state messages at a specified rate.
def __init__(self, urdf_file): super().__init__('joint_state_publisher', automatically_declare_parameters_from_overrides=True) self.declare_ros_parameter('publish_default_efforts', False, ParameterDescriptor(type=ParameterType.PARAMETER_BOOL)) self.declare_ros_parameter('publish_default_positio...
def _build_url(self, *path: str) -> str: return f"{self.base_url}/{'/'.join(path)}" def _request(self, url: str, *, params: Optional[Dict[str, str]] = None) -> dict: logger.trace("url = {}", url) delay = DELAY_BASE for attempt in range(MAX_REQUEST_ATTEMPTS): self._ensure_auth...
The code's main task is to retrieve podcast or episode stream data (starts/completions) within a specified date range. It constructs a URL based on whether an episode ID is provided, handles date parameters, and returns the result as a dictionary. If no episode is specified, data for all episodes is fetched.
def streams( self, start: dt.date, end: Optional[dt.date] = None, episode=None, ) -> dict: """Loads podcast/episode stream data, which includes the number of starts and completions for each episode. Args: start (dt.date): Earliest date to request ...
def _build_url(self, *path: str) -> str: return f"{self.base_url}/{'/'.join(path)}" def _request(self, url: str, *, params: Optional[Dict[str, str]] = None) -> dict: logger.trace("url = {}", url) delay = DELAY_BASE for attempt in range(MAX_REQUEST_ATTEMPTS): self._ensure_auth...
The code retrieves podcast listener data for a specified date range and optionally filters by an episode. It constructs a URL based on whether an episode ID is provided, handles date parameters, and returns the result as a dictionary.
def listeners( self, start: dt.date, end: Optional[dt.date] = None, episode=None, ) -> dict: """Loads podcast listener data, which includes the number of listeners for each episode. Args: start (dt.date): Earliest date to request data for. ...
def _build_url(self, *path: str) -> str: return f"{self.base_url}/{'/'.join(path)}" def _request(self, url: str, *, params: Optional[Dict[str, str]] = None) -> dict: logger.trace("url = {}", url) delay = DELAY_BASE for attempt in range(MAX_REQUEST_ATTEMPTS): self._ensure_auth...
The code retrieves podcast follower data between specified start and end dates by constructing an API request URL, defaulting the end date to the start date if unspecified. It uses internal methods to build the URL and handle date parameters, returning the fetched data as a dictionary.
def followers( self, start: dt.date, end: Optional[dt.date] = None, ) -> dict: """Loads podcast follower data. Args: start (dt.date): Earliest date to request data for. end (Optional[dt.date], optional): Most recent date to request data for. ...
def _build_url(self, *path: str) -> str: return f"{self.base_url}/{'/'.join(path)}" def _request(self, url: str, *, params: Optional[Dict[str, str]] = None) -> dict: logger.trace("url = {}", url) delay = DELAY_BASE for attempt in range(MAX_REQUEST_ATTEMPTS): self._ensure_auth...
The main task of the code is to retrieve aggregated podcast data, including episode starts and completions, for a specified date range. It fetches data for all episodes or a specific episode based on the input parameters, constructs the appropriate API URL, and returns the results as a dictionary.
def aggregate( self, start: dt.date, end: Optional[dt.date] = None, episode=None, ) -> dict: """Loads podcast aggregate data, which includes the number of starts and completions for each episode. Args: start (dt.date): Earliest date to request dat...
def _build_url(self, *path: str) -> str: return f"{self.base_url}/{'/'.join(path)}" def _date_params(start: dt.date, end: dt.date) -> Dict[str, str]: # Only format the date, not the time return { "start": start.strftime("%Y-%m-%d"), "end": end.strftime("%Y-%m-%d"), ...
This function retrieves podcast episode data (including starts/completions) within a specified date range, applying filters and sorting. It paginates results, yielding each episode iteratively until all pages are processed.
def episodes( self, start: dt.date, end: Optional[dt.date] = None, page: int = 1, size: int = 50, sortBy: str = "releaseDate", sortOrder: str = "descending", filter: str = "", ) -> dict: """Loads podcast episode data, which includes the number ...
def parse_subject(self): skip(self.SentenceToken, 'stop') next_word = peek(self.SentenceToken) if next_word == 'noun': return match(self.SentenceToken, 'noun') elif next_word == 'verb': return ('noun', 'player') else: raise ParseError("Expecte...
The main task of the code is to parse a sentence into its subject, verb, and object components by calling respective parsing methods, then return a structured `Sentence` object composed of these parsed elements.
def parse_sentence(self): subj = self.parse_subject() verb = self.parse_verb() obj = self.parse_object() return Sentence(subj, verb, obj)
def parse_subject(word_list): skip(word_list, 'stop') next_word = peek(word_list) if next_word == 'noun': return match(word_list, 'noun') elif next_word == 'verb': return ('noun', 'player') else: raise ParseError("Expected a verb next.") def parse_verb(word_list): """ ...
The code parses a sentence by extracting its subject, verb, and object from a word list using helper functions, then returns a `Sentence` object composed of these parsed components.
def parse_sentence(word_list): subj = parse_subject(word_list) verb = parse_verb(word_list) obj = parse_object(word_list) return Sentence(subj, verb, obj)
def is_mine(self, piece): if self.side == "b" and piece.isupper(): return True elif self.side == "w" and piece.islower(): return True else: return False def evaluate(self, curr_board): """ Given the hypothetical state of the board and hypotheti...
The code implements the minimax algorithm with alpha-beta pruning to determine the optimal move for a board game. It evaluates all valid moves recursively up to a specified depth, alternating between MAX (AI's turn) and MIN (opponent's turn) levels. The function generates pseudo-legal moves, sorts them by heuristic sco...
def minimax(self, board, max_depth, depth, alpha, beta, turn): """ Implementation of the vanilla minimax algorithm TODO: Implement Alpha-Beta Pruning (see below) TODO: Implement ordering to optimise Alpha-Beta Pruning (see below) TODO: Optional extension: Implement multi-threadi...
def conv_model(): #Using a hybird approach of both downsized frames and open cv data. Implements the model initilisation, training loop and model update loop, implementes Q update function within the model training loop. frame_input = Input(sha...
The main task of the code is to train a reinforcement learning agent using a Double DQN algorithm with experience replay to navigate the Super Mario Bros environment. It initializes Q-networks and target networks, employs epsilon-greedy exploration, and updates policies via replay buffer samples, aiming to maximize cum...
def train_agent(): # Initialize the environment env = gym.make("SuperMarioBros-v0", apply_api_compatibility=True, render_mode="human") env = JoypadSpace(env, SIMPLE_MOVEMENT) next_state = None done = True env.reset() # Create two pairs of Q-networks: one for action selection (online) a...
def preprocess_and_tokenize(sentence, stopwords=True, words_to_exclude=[]): cleaned_sentence = [] words = sentence.lower().split() for word in words: if word in words_to_exclude: cleaned_sentence.append(word) elif stopwords and word not in sw: cleaned_sentence.append...
The main task of the code is to process user input by preprocessing and tokenizing it, compare it with preprocessed questions using cosine similarity, identify relevant documents via a rule-based method, generate an answer, and render the result in a web template. It functions as a question-answering or document retrie...
def hasil(): if request.method == 'POST': user_input = request.form['user_input'] cleaned_user_input = preprocess_and_tokenize(user_input, stopwords=True, words_to_exclude=excluded_words) cleaned_sentences = data['Question'].apply(lambda x: preprocess_and_tokenize(x, stopwords=True, words_to...
def show_mine(self): self.cell_btn_obj.configure(bg='red') def neighbours_mines_count(self): count = 0 for cell in self.neighbours(): if cell.is_mine: count += 1 return count def neighbours(self): surrounding_cells = [ self.get_cell_by_pos(...
The code handles a left-click event in a Minesweeper-like game. If the cell contains a mine, it reveals the mine. Otherwise, if the cell has no neighboring mines, it reveals all adjacent cells. Finally, it reveals the current cell, updating the game state accordingly.
def left_click(self, event): if self.is_mine: self.show_mine() else: if self.neighbours_mines_count() == 0: for cell_obj in self.neighbours(): cell_obj.show_cell() self.show_cell()
def __train_step_initial(self, data): with tf.GradientTape() as tape: type_1_embeddings_contrastive = self.call_contrastive(data[0]) type_2_embeddings_contrastive = self.call_contrastive(data[1]) contrastive_loss = self.contrastive_loss.compute_loss( type_1_e...
The code trains a model in two stages: first, it performs initial training with a specified number of epochs, logging losses and generating embeddings to determine cluster centers. Then, it conducts further training over additional epochs, logging detailed losses and clustering information, using both contrastive and c...
def fit(self, dataset): logger.logger_single_write( f"logs/loss_logs {self.time_stamp}.txt", 'w', " starting ") logger.logger_single_write( f"logs/contrastive_logs {self.time_stamp}.txt", "w", "writing losses : \n") logger.logger_single_write( f"logs/clusteri...
def get_elements(self, cursor): line = self.lines[cursor.cursor] return line.strip().split() def read_rollto(self, cursor): elements = self.get_elements(cursor) target_frame = int(elements[1]) target_checksum = elements[2] cursor.advance() def read_sync_recv(self, cursor): # read the SYNC_RE...
This function reads and processes a sequence of log lines starting with 'STARTF' to construct a Tick object. It processes subsequent commands like ROLLTO, SYNC_RECV/SEND, SIM, or ENDGAME, returning the Tick upon encountering 'TICK' or 'ENDGAME'. The loop continues until reaching 'ENDTICK', at which point it advances th...
def read_tick(self, cursor): # read the STARTF line elements = self.get_elements(cursor) frame_index = int(elements[1]) checksum = elements[2] tick = Tick(frame_index, checksum) cursor.advance() line = self.lines[cursor.cursor] while (not line.startswith('ENDTICK')): # todo: make ...