seed
stringlengths
1
14k
source
stringclasses
2 values
def string_list_handler(option_value=None): """Split a comma-separated string into a list of strings.""" result = None if option_value is not None: result = option_value.split(',') return result
bigcode/self-oss-instruct-sc2-concepts
def IsImageFile(ext): """IsImageFile(ext) -> bool Determines if the given extension corresponds to an image file (jpg, bmp, or png). arguments: ext string corresponding to extension to check. returns: bool corresponding to whether it is an image file. """ return (ext == "jpg") or (ext == "bmp") or (ext == "png")
bigcode/self-oss-instruct-sc2-concepts
def ensure_support_staging_jobs_have_correct_keys( support_and_staging_matrix_jobs: list, prod_hub_matrix_jobs: list ) -> list: """This function ensures that all entries in support_and_staging_matrix_jobs have the expected upgrade_staging and eason_for_staging_redeploy keys, even if they are set to false/empty. Args: support_and_staging_matrix_jobs (list[dict]): A list of dictionaries representing jobs to upgrade the support chart and staging hub on clusters that require it. prod_hub_matrix_jobs (list[dict]): A list of dictionaries representing jobs to upgrade production hubs that require it. Returns: support_and_staging_matrix_jobs (list[dict]): Updated to ensure each entry has the upgrade_staging and reason_for_staging_redeploy keys, even if they are false/empty. """ # For each job listed in support_and_staging_matrix_jobs, ensure it has the # upgrade_staging key present, even if we just set it to False for job in support_and_staging_matrix_jobs: if "upgrade_staging" not in job.keys(): # Get a list of prod hubs running on the same cluster this staging job will # run on hubs_on_this_cluster = [ hub["hub_name"] for hub in prod_hub_matrix_jobs if hub["cluster_name"] == job["cluster_name"] ] if hubs_on_this_cluster: # There are prod hubs on this cluster that require an upgrade, and so we # also upgrade staging job["upgrade_staging"] = "true" job[ "reason_for_staging_redeploy" ] = "Following prod hubs require redeploy: " + ", ".join( hubs_on_this_cluster ) else: # There are no prod hubs on this cluster that require an upgrade, so we # do not upgrade staging job["upgrade_staging"] = "false" job["reason_for_staging_redeploy"] = "" return support_and_staging_matrix_jobs
bigcode/self-oss-instruct-sc2-concepts
def readlines_with_strip(filename): """Reads lines from specified file with whitespaced removed on both sides. The function reads each line in the specified file and applies string.strip() function to each line which results in removing all whitespaces on both ends of each string. Also removes the newline symbol which is usually present after the lines wre read using readlines() function. Parameters ---------- filename : string Full path to the root of PASCAL VOC dataset. Returns ------- clean_lines : array of strings Strings that were read from the file and cleaned up. """ # Get raw filnames from the file with open(filename, 'r') as f: lines = f.readlines() # Clean filenames from whitespaces and newline symbols clean_lines = map(lambda x: x.strip(), lines) return clean_lines
bigcode/self-oss-instruct-sc2-concepts
from typing import Counter def most_frequent(List): """Counts the most_frequent element in list""" occurence_count = Counter(List) return occurence_count.most_common(1)[0][0]
bigcode/self-oss-instruct-sc2-concepts
def CountBenchmarks(benchmark_runs): """Counts the number of iterations for each benchmark in benchmark_runs.""" # Example input for benchmark_runs: # {"bench": [[run1, run2, run3], [run1, run2, run3, run4]]} def _MaxLen(results): return 0 if not results else max(len(r) for r in results) return [(name, _MaxLen(results)) for name, results in benchmark_runs.iteritems()]
bigcode/self-oss-instruct-sc2-concepts
def window(x, win_len, win_stride, win_fn): """ Apply a window function to an array with window size win_len, advancing at win_stride. :param x: Array :param win_len: Number of samples per window :param win_stride: Stride to advance current window :param win_fn: Callable window function. Takes the slice of the array as input :return: List of windowed values """ n = x.shape[0] n_win = ((n - win_len)//win_stride)+1 x_win = [win_fn(x[i*win_stride:(i*win_stride)+win_len]) for i in range(n_win)] return x_win
bigcode/self-oss-instruct-sc2-concepts
def iswritable(f): """ Returns True if the file-like object can be written to. This is a common- sense approximation of io.IOBase.writable. """ if hasattr(f, 'writable'): return f.writable() if hasattr(f, 'closed') and f.closed: # This mimics the behavior of io.IOBase.writable raise ValueError('I/O operation on closed file') if not hasattr(f, 'write'): return False if hasattr(f, 'mode') and not any(c in f.mode for c in 'wa+'): return False # Note closed, has a 'write()' method, and either has no known mode or a # mode that supports writing--should be good enough to assume 'writable' return True
bigcode/self-oss-instruct-sc2-concepts
from typing import List def batch_inference_result_split(results: List, keys: List): """ Split inference result into a dict with provided key and result dicts. The length of results and keys must match :param results: :param keys: :return: """ ret = {} for result, key in zip(results, keys): ret[key] = result return ret
bigcode/self-oss-instruct-sc2-concepts
def read_ip_config(filename): """Read network configuration information of kvstore from file. The format of configuration file should be: [ip] [base_port] [server_count] 172.31.40.143 30050 2 172.31.36.140 30050 2 172.31.47.147 30050 2 172.31.30.180 30050 2 Note that, DGL KVStore supports multiple servers that can share data with each other on the same machine via shared-tensor. So the server_count should be >= 1. Parameters ---------- filename : str name of configuration file. Returns ------- dict server namebook. e.g., [server_id]:[machine_id, ip, port, group_count] {0:[0, '172.31.40.143', 30050, 2], 1:[0, '172.31.40.143', 30051, 2], 2:[1, '172.31.36.140', 30050, 2], 3:[1, '172.31.36.140', 30051, 2], 4:[2, '172.31.47.147', 30050, 2], 5:[2, '172.31.47.147', 30051, 2], 6:[3, '172.31.30.180', 30050, 2], 7:[3, '172.31.30.180', 30051, 2]} """ assert len(filename) > 0, 'filename cannot be empty.' server_namebook = {} try: server_id = 0 machine_id = 0 lines = [line.rstrip('\n') for line in open(filename)] for line in lines: ip, port, server_count = line.split(' ') for s_count in range(int(server_count)): server_namebook[server_id] = [int(machine_id), ip, int(port)+s_count, int(server_count)] server_id += 1 machine_id += 1 except: print("Error: data format on each line should be: [ip] [base_port] [server_count]") return server_namebook
bigcode/self-oss-instruct-sc2-concepts
def get_table_row(table, td_text): """ Find a row in a table that has td_text as one column's text """ td = table.find('td', string=td_text) if td is None: return None return td.find_parent('tr')
bigcode/self-oss-instruct-sc2-concepts
def breakpoint_callback(frame, bp_loc, dict): """This callback is registered with every breakpoint and makes sure that the frame containing the breakpoint location is selected """ # HACK(eddyb) print a newline to avoid continuing an unfinished line. print("") print("Hit breakpoint " + str(bp_loc)) # Select the frame and the thread containing it frame.thread.process.SetSelectedThread(frame.thread) frame.thread.SetSelectedFrame(frame.idx) # Returning True means that we actually want to stop at this breakpoint return True
bigcode/self-oss-instruct-sc2-concepts
import pathlib def _stringify_path(path_or_buffer): """Convert path like object to string Args: path_or_buffer: object to be converted Returns: string_path_or_buffer: maybe string version of path_or_buffer """ try: _PATHLIB_INSTALLED = True except ImportError: _PATHLIB_INSTALLED = False if hasattr(path_or_buffer, "__fspath__"): return path_or_buffer.__fspath__() if _PATHLIB_INSTALLED and isinstance(path_or_buffer, pathlib.Path): return str(path_or_buffer) return path_or_buffer
bigcode/self-oss-instruct-sc2-concepts
def _get_gmt_dict(filename): """Parse gmt files and get gene sets.""" with open(filename, 'r') as f: content = [line.strip().split('\t') for line in f] return {pathway[0]: pathway[2:] for pathway in content}
bigcode/self-oss-instruct-sc2-concepts
def EqualSpacedColmunTable(items, table_width=80, table_indent=2, column_pad=2): """Construct a table of equal-spaced columns from items in a string array. The number of columns is determined by the data. The table will contain at least one column, even if the resulting table is wider than table_width. Args: items: [str], The column data, one element per column. table_width: int, The total table width in characters. table_indent: int, The left indent space count. column_pad: int, The column pad space count. Returns: str, Formatted table. """ # determine the max width of all items -- this is the (minimum) column width column_width = len(max(items, key=len)) # adjust the column width to include the column pad column_width += column_pad # determine the number of columns that fit the indent and pad constraints columns = (table_width - table_indent) / column_width # one more pass through the items to construct the table row by row table = '' # the table col = 0 # the current column index, col==0 => start of new row pad = ' ' * table_indent # the left-padding for the next column for item in items: table += pad + item col += 1 if col >= columns: # the next column starts a new row col = 0 table += '\n' # the leftmost column is padded by the table indent pad = ' ' * table_indent else: # this pad aligns the next column pad = ' ' * (column_width - len(item)) # a partial last row needs a line terminator if col > 0: table += '\n' return table
bigcode/self-oss-instruct-sc2-concepts
def make_voc_seed_func(entry_rate, start_time, seed_duration): """ Create a simple step function to allow seeding of the VoC strain at a particular point in time. """ def voc_seed_func(time, computed_values): return entry_rate if 0. < time - start_time < seed_duration else 0. return voc_seed_func
bigcode/self-oss-instruct-sc2-concepts
import socket def init_socket(port): """ Init socket at specified port. Listen for connections. Return socket obj. Keyword arguments: port -- port at whicch to init socket (int) """ connection_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) connection_socket.bind(('', port)) connection_socket.listen(1) return connection_socket
bigcode/self-oss-instruct-sc2-concepts
from typing import List def _split_list(string: str) -> List[str]: """Assumes an input of the form `[s1, s2, s3, ..., sn]`, where each si may itself contain lists.""" assert string[0] == "[" and string[-1] == "]" nesting_depth = 0 all_strings = [] current_string = "" for character in string[1:-1]: if character == "," and nesting_depth == 0: all_strings.append(current_string) current_string = "" continue if character == "[": nesting_depth += 1 elif character == "]": nesting_depth -= 1 current_string += character if current_string != "": all_strings.append(current_string) return [string.strip() for string in all_strings]
bigcode/self-oss-instruct-sc2-concepts
def get_model_state_dict(model): """Get model state dict.""" return {k: v for k, v in model.state_dict().items()}
bigcode/self-oss-instruct-sc2-concepts
import ast def calculate_issues_count(issues: str) -> int: """ Parse issues list and calculate number of issues. """ return len(ast.literal_eval(issues))
bigcode/self-oss-instruct-sc2-concepts
def _contains_isolated_cores(label, cluster, min_cores): """Check if the cluster has at least ``min_cores`` of cores that belong to no other cluster.""" return sum([neighboring_labels == {label} for neighboring_labels in cluster.neighboring_labels]) >= min_cores
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional def upper(value) -> Optional[str]: """Converter to change a string to uppercase, if applicable""" return value.upper() if isinstance(value, str) else None
bigcode/self-oss-instruct-sc2-concepts
def _call_member(obj, name, args=None, failfast=True): """ Calls the specified method, property or attribute of the given object Parameters ---------- obj : object The object that will be used name : str Name of method, property or attribute args : dict, optional, default=None Arguments to be passed to the method (if any) failfast : bool If True, will raise an exception when trying a method that doesn't exist. If False, will simply return None in that case """ try: method = getattr(obj, name) except AttributeError as e: if failfast: raise e else: return None if str(type(method)) == '<type \'instancemethod\'>': # call function if args is None: return method() else: return method(*args) elif str(type(method)) == '<type \'property\'>': # call property return method else: # now it's an Attribute, so we can just return its value return method
bigcode/self-oss-instruct-sc2-concepts
def doc_view(request): """View for documentation route.""" return { 'page': 'Documentation' }
bigcode/self-oss-instruct-sc2-concepts
from typing import List def bounding_box_to_polygon( left: float, bottom: float, right: float, top: float ) -> List[List[float]]: """ Transform bounding box to polygon :param left: left bound :param bottom: bottom bound :param right: right bound :param top: top bound :return: polygon """ polygon = [ [left, bottom], [right, bottom], [right, top], [left, top], [left, bottom], ] return polygon
bigcode/self-oss-instruct-sc2-concepts
def strnum(prefix: str, num: int, suffix: str = "") -> str: """ Makes a string of the format ``<prefix><number><suffix>``. """ return f"{prefix}{num}{suffix}"
bigcode/self-oss-instruct-sc2-concepts
def get_region_dict(region, maxRegionSize=None, tilesource=None): """Return a dict corresponding to region, checking the region size if maxRegionSize is provided. The intended use is to be passed via **kwargs, and so either {} is returned (for the special region -1,-1,-1,-1) or {'region': region_dict}. Params ------ region: list 4 elements -- left, top, width, height -- or all -1, meaning the whole slide. maxRegionSize: int, optional Maximum size permitted of any single dimension tilesource: tilesource, optional A `large_image` tilesource (or anything with `.sizeX` and `.sizeY` properties) that is used to determine the size of the whole slide if necessary. Must be provided if `maxRegionSize` is. Returns ------- region_dict: dict Either {} (for the special region -1,-1,-1,-1) or {'region': region_subdict} """ if len(region) != 4: raise ValueError('Exactly four values required for --region') useWholeImage = region == [-1] * 4 if maxRegionSize is not None: if tilesource is None: raise ValueError('tilesource must be provided if maxRegionSize is') if maxRegionSize != -1: if useWholeImage: size = max(tilesource.sizeX, tilesource.sizeY) else: size = max(region[-2:]) if size > maxRegionSize: raise ValueError('Requested region is too large! ' 'Please see --maxRegionSize') return {} if useWholeImage else dict( region=dict(zip(['left', 'top', 'width', 'height'], region)))
bigcode/self-oss-instruct-sc2-concepts
def initialize_back_prop(AL, Y, AL_prime, Y_prime): """ Initialize backward propagation Arguments: :param AL -- output of the forward propagation L_model_forward()... i.e. neural net predictions (if regression) i.e. neural net probabilities (if classification) >> a numpy array of shape (n_y, m) where n_y = no. outputs, m = no. examples :param Y -- true "label" (classification) or "value" (regression) >> a numpy array of shape (n_y, m) where n_y = no. outputs, m = no. examples :param AL_prime -- the derivative of the last layer's activation output(s) w.r.t. the inputs x: AL' = d(AL)/dX >> a numpy array of size (n_y, n_x, m) where n_y = no. outputs, n_x = no. inputs, m = no. examples :param Y_prime -- the true derivative of the output(s) w.r.t. the inputs x: Y' = d(Y)/dX >> a numpy array of shape (n_y, n_x, m) where n_y = no. outputs, n_x = no. inputs, m = no. examples Returns: :return dAL -- gradient of the loss function w.r.t. last layer activations: d(L)/dAL >> a numpy array of shape (n_y, m) :return dAL_prime -- gradient of the loss function w.r.t. last layer activations derivatives: d(L)/dAL' where AL' = d(AL)/dX >> a numpy array of shape (n_y, n_x, m) """ n_y, _ = AL.shape # number layers, number examples Y = Y.reshape(AL.shape) dAL = AL - Y # derivative of loss function w.r.t. to activations: dAL = d(L)/dAL dAL_prime = AL_prime - Y_prime # derivative of loss function w.r.t. to partials: dAL_prime = d(L)/d(AL_prime) return dAL, dAL_prime
bigcode/self-oss-instruct-sc2-concepts
def replaceline(f, match, lines): """Replace matching line in file with lines.""" for i in range(len(f)): if match in f[i]: return f[:i] + lines + f[i+1:] return f
bigcode/self-oss-instruct-sc2-concepts
import requests def http_get(url, fout=None): """Download a file from http. Save it in a file named by fout""" print('requests.get({URL}, stream=True)'.format(URL=url)) rsp = requests.get(url, stream=True) if rsp.status_code == 200 and fout is not None: with open(fout, 'wb') as prt: for chunk in rsp: # .iter_content(chunk_size=128): prt.write(chunk) print(' WROTE: {F}\n'.format(F=fout)) else: print(rsp.status_code, rsp.reason, url) print(rsp.content) return rsp
bigcode/self-oss-instruct-sc2-concepts
import yaml def read_yaml(yaml_file): """Read a yaml file. Args: yaml_file (str): Full path of the yaml file. Returns: data (dict): Dictionary of yaml_file contents. None is returned if an error occurs while reading. """ data = None with open(yaml_file) as f: # use safe_load instead load data = yaml.safe_load(f) return data
bigcode/self-oss-instruct-sc2-concepts
def c_escaped_string(data: bytes): """Generates a C byte string representation for a byte array For example, given a byte sequence of [0x12, 0x34, 0x56]. The function generates the following byte string code: {"\x12\x34\x56", 3} """ body = ''.join([f'\\x{b:02x}' for b in data]) return f'{{\"{body}\", {len(data)}}}'
bigcode/self-oss-instruct-sc2-concepts
def test_object_type(obj: object, thetype: type): """Tests if the given object is of the specified type. Returns a Boolean True or False. Examples: >>> myint = 34 >>> test_object_type(myint, int) True >>> isinstance(myint, int) True >>> test_object_type(myint, str) False """ return isinstance(obj, thetype)
bigcode/self-oss-instruct-sc2-concepts
import re def remove_leading_space(string: str) -> str: """ Remove the leading space of a string at every line. :param string: String to be processed :type string: str :return: Result string :rtype: str **Example:** .. code-block:: python string = " Hello \\nWorld!" result = remove_trailing_space(string) # "Hello \\nWorld!" """ return re.sub(r"^[ \t]*", "", string, flags=re.MULTILINE)
bigcode/self-oss-instruct-sc2-concepts
def qb_account(item_title): """ Given an item title, returns the appropriate QuickBooks class and account Parameter: item_title Returns: item_class, item_account Note that this is only guaranteed to work for Ticketleap sales, not PayPal invoices. """ if 'Northern' in item_title or 'NLC' in item_title: item_class = 'NLC' else: item_class = 'CCC' if 'Competitor' in item_title: item_account = ('Competition Income:Competitors:' 'Amateur Registration Fees') else: item_account = 'Competition Income:Sales:Tickets:Advance Tickets' return item_class, item_account
bigcode/self-oss-instruct-sc2-concepts
def bottom_row(matrix): """ Return the last (bottom) row of a matrix. Returns a tuple (immutable). """ return tuple(matrix[-1])
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def success_of_action_dict(**messages) -> Dict: """Parses the overall success of a dictionary of actions, where the key is an action name and the value is a dictionarised Misty2pyResponse. `overall_success` is only true if all actions were successful. Returns: Dict: The dictionary of the keys `"overall_success"` (bool) and action names that contain the dictionarised Misty2pyResponses. """ status_dict = {} overall_success = True for name, message in messages.items(): status_dict[name] = message if not message.get("overall_success"): overall_success = False status_dict["overall_success"] = overall_success return status_dict
bigcode/self-oss-instruct-sc2-concepts
def clip(value, min, max): """Clips (limits) the value to the given limits. The output is at least `min`, at most `max` and `value` if that value is between the `min` and `max`. Args: value: to be limited to [min, max] min: smallest acceptable value max: greatest acceptable value Returns: the given value if within [min, max] or min if value is smaller than min or max if value is greater than max. """ if value < min: return min elif value > max: return max else: return value
bigcode/self-oss-instruct-sc2-concepts
def is_variable_geometry(xmldoc): """ Tries to guess whether the calculation involves changes in geometry. """ itemlist = xmldoc.getElementsByTagName('module') for item in itemlist: # Check there is a step which is a "geometry optimization" one if 'dictRef' in list(item.attributes.keys()): if item.attributes['dictRef'].value == "Geom. Optim": return True return False
bigcode/self-oss-instruct-sc2-concepts
def convertConfigDict(origDict, sep="."): """ For each key in the dictionary of the form <section>.<option>, a separate dictionary for is formed for every "key" - <section>, while the <option>s become the keys for the inner dictionary. Returns a dictionary of dictionary. """ result = {} for keys in origDict: tempResult = result parts = keys.split(sep) for part in parts[:-1]: tempResult = tempResult.setdefault(part, {}) tempResult[parts[-1]] = origDict[keys] return result
bigcode/self-oss-instruct-sc2-concepts
def parse_csv_data(csv_filename: str) -> list[str]: """Returns a list of strings representing each row in a given file""" file = open("data/" + csv_filename, "r", encoding="utf-8") lstrows = [] for line in file: lstrows.append(line.rstrip()) file.close() return lstrows
bigcode/self-oss-instruct-sc2-concepts
def merge_means(mu1, mu2, n1, n2): """Merges means. Requires n1 + n2 > 0.""" total = n1 + n2 return (n1 * mu1 + n2 * mu2) / total
bigcode/self-oss-instruct-sc2-concepts
import six def get_comparable_revisits(query_metadata_table): """Return a dict location -> set of revisit locations for that starting location.""" revisit_origins = { query_metadata_table.get_revisit_origin(location) for location, _ in query_metadata_table.registered_locations } intermediate_result = { location: set(query_metadata_table.get_all_revisits(location)) for location in revisit_origins } return { location: revisits for location, revisits in six.iteritems(intermediate_result) if revisits }
bigcode/self-oss-instruct-sc2-concepts
def torch_to_np(images): """Transforms the unnormalized output of a gan into a numpy array Args: images (torch.tensor): unnormalized output of a gan Returns: (numpy.array) """ return ((images.clamp(min=-1, max=1) + 1) / 2).permute(0, 2, 3, 1).cpu().detach().numpy()
bigcode/self-oss-instruct-sc2-concepts
def lookup_dunder_prop(obj, props, multi=False): """ Take an obj and lookup the value of a related attribute using __ notation. For example if Obj.a.b.c == "foo" then lookup_dunder (Obj, "a__b__c") == "foo" """ try: if "__" in props: head, tail = props.split("__", 1) obj = getattr(obj, head) return lookup_dunder_prop(obj, tail, multi=multi) if multi: return [getattr(o, props) for o in obj.all()] return getattr(obj, props) except AttributeError: return None
bigcode/self-oss-instruct-sc2-concepts
import operator def filter_prefix(candidates: set[str], prefix: str = '', ones_operator=operator.ge) -> int: """Filter a set of binary number strings by prefix, returning a single int. This function considers a set of candidate strings, which must encode valid binary numbers. They are iteratively filtered by prefix, selecting each bit by whether it is the more common or less common place value for each successive bit (MSB first), until only a single value remains with that prefix, which is returned as an int. Specific behavior is determined by the ones_operator parameter: `ge`: Select the more common value for prefix, ties resolved to '1' `gt`: Select the more common value for prefix, ties resolved to '0' `le`: Select the less common value for prefix, ties resolved to '1' `lt`: Select the less common value for prefix, ties resolved to '0' """ # Base case; when we're down to just one option, pop it and # return it as an int: if len(candidates) == 1: return int(candidates.pop(), base=2) # The sets of candidates with a '1' vs '0' in the next bit to consider: ones = set() zeroes = set() candidate_count = len(candidates) # Consider each candidate binary number and sort it into the ones or zeroes # sets based on the value in the next bit place under consideration # (which corresponds to len(prefix)): while len(candidates): candidate = candidates.pop() if candidate[len(prefix)] == '1': ones.add(candidate) else: zeroes.add(candidate) # Use the supplied operator (less-than or greater-equal) to compare # the ones and zeroes sets, selecting the ones set if the operation # supplied returns True, and the zeroes set if the operation returns # False. if ones_operator(len(ones), candidate_count/2.0): return filter_prefix(ones, prefix + '1', ones_operator) else: return filter_prefix(zeroes, prefix + '0', ones_operator)
bigcode/self-oss-instruct-sc2-concepts
import torch def precisionk(actual, predicted, topk=(1, 5)): """ Computes the precision@k for the specified values of k. # Parameters actual : `Sequence[Sequence[int]]`, required Actual labels for a batch sized input. predicted : `Sequence[Sequence[int]]`, required Predicted labels for a batch sized input. topk : `Tuple`, optional (default = `(1,5)`) Values of k to be computed. # Returns accuracy : `Sequence[float]` Accuracy result for given value of k in the given order. """ actual = torch.LongTensor(actual) pred = torch.LongTensor(predicted) batch_size = pred.size(0) assert batch_size == actual.size(0) pred = pred.t() correct = pred.eq(actual.view(1, -1).expand_as(pred)) res = [] for k in topk: correct_k = correct[:k].any(dim=0).view(-1).float().sum() res.append((correct_k * 1.0 / batch_size).item()) return res
bigcode/self-oss-instruct-sc2-concepts
def image_size(img): """ Gets the size of an image eg. 350x350 """ return tuple(img.shape[1:: -1])
bigcode/self-oss-instruct-sc2-concepts
def revcomp(s): """Returns the reverse compliment of a sequence""" t = s[:] t.reverse() rc = {'A':'T', 'C':'G', 'G':'C', 'T':'A', 'N':'N'} t = [rc[x] for x in t] return t
bigcode/self-oss-instruct-sc2-concepts
def relu(x, c = 0): """ Compute the value of the relu function with parameter c, for a given point x. :param x: (float) input coordinate :param c: (float) shifting parameter :return: (float) the value of the relu function """ return c + max(0.0, x)
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def is_notebook(path: Path) -> bool: """ Checks whether the given file path is Jupyter Notebook or not. Parameters ---------- path: Path Path of the file to check whether it is Jupyter Notebook or not. Returns ------ Returns True when file is Jupyter Notebook, False otherwise. """ if path.suffix == ".ipynb": return True return False
bigcode/self-oss-instruct-sc2-concepts
def is_highlighted_ins(e): """Returns True if e matches the following pattern: <ins>highlighted</ins> text: See `fragment_chunks` comment for the details """ if len(e) != 0: return False if not e.text: return False if e.text != 'highlighted': return False if not e.tail: return False if not e.tail.startswith(' text:'): return False return True
bigcode/self-oss-instruct-sc2-concepts
async def admin(mixer): """Generate an admin user.""" admin = mixer.blend('example.models.User', email='admin@example.com', is_super=True) admin.password = admin.generate_password('pass') return await admin.save(force_insert=True)
bigcode/self-oss-instruct-sc2-concepts
def bw24(x): """Return the bit weight of the lowest 24 bits of x""" x = (x & 0x555555) + ((x & 0xaaaaaa) >> 1) x = (x & 0x333333) + ((x & 0xcccccc) >> 2) x = (x + (x >> 4)) & 0xf0f0f return (x + (x >> 8) + (x >> 16)) & 0x1f
bigcode/self-oss-instruct-sc2-concepts
def project_data(samples, U, K): """ Computes the reduced data representation when projecting only on to the top "K" eigenvectors """ # Reduced U is the first "K" columns in U reduced_U = U[:, :K] return samples.dot(reduced_U)
bigcode/self-oss-instruct-sc2-concepts
def ROStime_to_NTP64(ROStime): """ Convert rospy.Time object to a 64bit NTP timestamp @param ROStime: timestamp @type ROStime: rospy.Time @return: 64bit NTP representation of the input @rtype: int """ NTPtime = ROStime.secs << 32 # NTPtime |= nanoseconds * 2^31 / 1x10^9 NTPtime |= int((ROStime.nsecs * 0x100000000) / 0x3b9aca00) return NTPtime
bigcode/self-oss-instruct-sc2-concepts
def reverse_dict(dictionary): """Reverse a dictionary. Keys become values and vice versa. Parameters ---------- dictionary : dict Dictionary to reverse Returns ------- dict Reversed dictionary Raises ------ TypeError If there is a value which is unhashable, therefore cannot be a dictionary key. """ return {i: value for value, i in dictionary.items()}
bigcode/self-oss-instruct-sc2-concepts
def expp_xor_indep(p1, p2): """ Probability of term t1 XOR t2 being 1 if t1 is 1 with p1 and t2 is 1 with p2. t1 and t2 has to be independent (no common sub-term). Due to associativity can be computed on multiple terms: t1 ^ t2 ^ t3 ^ t4 = (((t1 ^ t2) ^ t3) ^ t4) - zipping. XOR: a b | r ----+--- 1 1 | 0 1 0 | 1 = p1 * (1-p2) 0 1 | 1 = (1-p1)* p2 0 0 | 0 :param p1: :param p2: :return: """ return p1*(1-p2)+(1-p1)*p2
bigcode/self-oss-instruct-sc2-concepts
def noOut(_): """Outputs nothing.""" return None
bigcode/self-oss-instruct-sc2-concepts
import torch def conv3x3(in_channel, out_channel, stride=1, padding=1,dilation=1, bias=True): """3x3 convolution with padding""" return torch.nn.Conv2d(in_channel, out_channel, kernel_size=(3,3), stride=(stride,stride), padding=padding, dilation=(dilation,dilation), bias=bias,)
bigcode/self-oss-instruct-sc2-concepts
def length_of_range(range): """Helper- returns the length of a range from start to finish in ms""" return range[1] - range[0]
bigcode/self-oss-instruct-sc2-concepts
def listify(x, none_value=[]): """Make a list of the argument if it is not a list.""" if isinstance(x, list): return x elif isinstance(x, tuple): return list(x) elif x is None: return none_value else: return [x]
bigcode/self-oss-instruct-sc2-concepts
def unique(iterable): """Return an iterable of the same type which contains unique items. This function assumes that: type(iterable)(list(iterable)) == iterable which is true for tuples, lists and deques (but not for strings) >>> unique([1, 2, 3, 1, 2, 3, 4, 2, 3, 4, 1, 1, 2]) [1, 2, 3, 4] >>> unique(('w', 't', 't', 'f', 't', 'w')) ('w', 't', 'f') """ already_seen = [] for item in iterable: if item not in already_seen: already_seen.append(item) return type(iterable)(already_seen)
bigcode/self-oss-instruct-sc2-concepts
def qc_syntax_test(self): """ It verifies that wf.data contains the recomentated data structure to pass the rest of the QC test. Each parameter (for example, TEMP) and each index (for example, TIME) must have a column with the flags of the values (for example, TEMP_QC and TIME_QC). Returns ------- success: bool The test has been successfully passed. """ # Get all columns and indices all_columns = list(self.data.keys()) all_columns += list(self.data.index.names) # Get only the names without _QC columns_no_qc = [column_name for column_name in all_columns if '_QC' not in column_name] success = True for column_no_qc in columns_no_qc: if f'{column_no_qc}_QC' not in all_columns: success = False return success
bigcode/self-oss-instruct-sc2-concepts
def modified(number, percent): """return the amount (or any other number) with added margin given by percent parameter (result has type float) """ if percent: return number * (100 + percent) / 100. else: return float(number)
bigcode/self-oss-instruct-sc2-concepts
def print_bytearray(array: bytearray) -> str: """Outputs string of all bytes in HEX without any formatting. Parameters ---------- array : byte array The byte array to be printed. Returns ------- str A string representation of the byte array in HEX format. """ strings = ["{:02X}".format(byte) for byte in array] output = "".join(strings) return output
bigcode/self-oss-instruct-sc2-concepts
def get_row_nnz(mat, row): """Return the number of nonzeros in row. """ return mat.indptr[row+1] - mat.indptr[row]
bigcode/self-oss-instruct-sc2-concepts
import torch def zero_out_col_span(xfft, col, start_row, end_row=None): """ Zero out values for all data points, channels, in the given column and row span. :param xfft: input complex tensor :param col: the col number to zero out value :param start_row: the start row (inclusive, it is zeroed out) :param end_row: the end row (exclusive, it is not zeroed out) - by default, zero out all the values to the end of the column :return: the zero out col for the given row range >>> xfft = torch.tensor( ... [ # 1 image ... [ # 1 channel ... [[[8, 0], [2, 5], [3, 0]], # 1st row ... [[4, 0], [5, 0], [2, 0]], ... [[-1, 1], [1, 0], [1, 0]]] ... ] ... ]) >>> result = zero_out_col_span(xfft, 1, 0, 3) >>> expect = torch.tensor( ... [ # 1 image ... [ # 1 channel ... [[[8, 0], [0, 0], [3, 0]], # 1st row ... [[4, 0], [0.0, 0.0 ], [2, 0]], ... [[-1, 1], [0, 0], [1, 0]]] ... ] ... ]) >>> # print("result: ", result) >>> np.testing.assert_array_almost_equal(result, expect) >>> result2 = zero_out_col_span(xfft, 2, 0, 1) >>> expect2 = torch.tensor( ... [ # 1 image ... [ # 1 channel ... [[[8, 0], [0, 0], [0, 0]], # 1st row ... [[4, 0], [0.0, 0.0], [2, 0]], ... [[-1, 1], [0, 0], [1, 0]]] ... ] ... ]) >>> np.testing.assert_array_almost_equal(result2, expect2) >>> result3 = zero_out_col_span(xfft, 0, 1, 3) >>> expect3 = torch.tensor( ... [ # 1 image ... [ # 1 channel ... [[[8, 0], [0, 0], [0, 0]], # 1st row ... [[0, 0], [0.0, 0.0], [2, 0]], ... [[0, 0], [0, 0], [1, 0]]] ... ] ... ]) >>> np.testing.assert_array_almost_equal(result3, expect3) """ if end_row is None: # zero out to the end of the column end_row = xfft.shape[2] if end_row > start_row: xfft[:, :, start_row:end_row, col, :] = torch.zeros(xfft.shape[0], xfft.shape[1], end_row - start_row, xfft.shape[4]) return xfft
bigcode/self-oss-instruct-sc2-concepts
def weWantThisPixel(col, row): """ a function that returns True if we want # @IndentOk the pixel at col, row and False otherwise """ if col%10 == 0 and row%10 == 0: return True else: return False
bigcode/self-oss-instruct-sc2-concepts
import calendar def date_to_dow(y, m, d): """ Gets the integer day of week for a date. Sunday is 0. """ # Python uses Monday week start, so wrap around w = calendar.weekday(y, m, d) + 1 if w == 7: w = 0 return w
bigcode/self-oss-instruct-sc2-concepts
def hi_to_wbgt(HI): """ Convert HI to WBGT using emprical relationship from Bernard and Iheanacho 2015 WBGT [◦C] = −0.0034 HI2 + 0.96 HI−34; for HI [◦F] Args: HI = heat index as an array """ WBGT = -0.0034*HI**2 + 0.96*HI - 34 return WBGT
bigcode/self-oss-instruct-sc2-concepts
def shimbel(w): """ Find the Shimbel matrix for first order contiguity matrix. Parameters ---------- w : W spatial weights object Returns ------- info : list list of lists; one list for each observation which stores the shortest order between it and each of the the other observations. Examples -------- >>> from libpysal.weights import lat2W, shimbel >>> w5 = lat2W() >>> w5_shimbel = shimbel(w5) >>> w5_shimbel[0][24] 8 >>> w5_shimbel[0][0:4] [-1, 1, 2, 3] """ info = {} ids = w.id_order for i in ids: s = [0] * w.n s[ids.index(i)] = -1 for j in w.neighbors[i]: s[ids.index(j)] = 1 k = 1 flag = s.count(0) while flag: p = -1 knext = k + 1 for j in range(s.count(k)): neighbor = s.index(k, p + 1) p = neighbor next_neighbors = w.neighbors[ids[p]] for neighbor in next_neighbors: nid = ids.index(neighbor) if s[nid] == 0: s[nid] = knext k = knext flag = s.count(0) info[i] = s return info
bigcode/self-oss-instruct-sc2-concepts
def counts_to_probabilities(counts): """ Convert a dictionary of counts to probalities. Argument: counts - a dictionary mapping from items to integers Returns: A new dictionary where each count has been divided by the sum of all entries in counts. Example: >>> counts_to_probabilities({'a':9, 'b':1}) {'a': 0.9, 'b': 0.1} """ probabilities = {} total = 0 for item in counts: total += counts[item] for item in counts: probabilities[item] = counts[item] / float(total) return probabilities
bigcode/self-oss-instruct-sc2-concepts
def array_set_diag(arr, val, row_labels, col_labels): """ Sets the diagonal of an 2D array to a value. Diagonal in this case is anything where row label == column label. :param arr: Array to modify in place :type arr: np.ndarray :param val: Value to insert into any cells where row label == column label :type val: numeric :param row_labels: Labels which correspond to the rows :type row_labels: list, pd.Index :param col_labels: Labels which correspond to the columns :type col_labels: list, pd.Index :return: Return the number of common row and column labels :rtype: int """ if arr.ndim != 2: raise ValueError("Array must be 2D") # Find all the labels that are shared between rows and columns isect = set(row_labels).intersection(col_labels) # Set the value where row and column names are the same for i in isect: arr[row_labels == i, col_labels == i] = val return len(isect)
bigcode/self-oss-instruct-sc2-concepts
import json def _format_modules(data): """Form module data for JSON.""" modules = [] # Format modules data for json usage for item in data: if item.startswith('module_'): val_json = json.loads(data[item]) modules.append(val_json) return modules
bigcode/self-oss-instruct-sc2-concepts
def get_sparkconfig(session): """ Returns config information used in the SparkSession Parameters ---------- session : SparkSession Returns ------- dict : Dictionary representing spark session configuration """ conf = session.sparkContext.getConf().getAll() return conf
bigcode/self-oss-instruct-sc2-concepts
def stride_chainid_to_pdb_chainid(stride_chainid): """ Convert a STRIDE chainid to a PDB chainid. STRIDE uses '-' for a 'blank' chainid while PDB uses ' ' (space). So all this does is return the stride_chainid unless it is '-', then it returns ' '. Parameters: stride_chainid - the STRIDE chain identifier Return value: PDB chain identifier corresponding to supplied stride_chainid """ if stride_chainid == '-': return ' ' else: return stride_chainid
bigcode/self-oss-instruct-sc2-concepts
def doc_to_labels(document): """ Converts document to a label: list of cluster ids. :param document: Document object :return: list of cluster ids. """ labels = [] word_to_cluster = document.words_to_clusters() cluster_to_id = {cluster:cluster_id for cluster_id, cluster in enumerate(document.get_clusters())} for word in document.get_words(): cluster = word_to_cluster[word] cluster_id = cluster_to_id[cluster] if cluster else -1 labels.append(cluster_id) return labels
bigcode/self-oss-instruct-sc2-concepts
def _GetChangePath(change): """Given a change id, return a path prefix for the change.""" return 'changes/%s' % str(change).replace('/', '%2F')
bigcode/self-oss-instruct-sc2-concepts
import hashlib def list_hash(str_list): """ Return a hash value for a given list of string. :param str_list: a list of strings (e.g. x_test) :type str_list: list (of str) :returns: an MD5 hash value :rtype: str """ m = hashlib.md5() for doc in str_list: try: m.update(doc) except (TypeError, UnicodeEncodeError): m.update(doc.encode('ascii', 'ignore')) return m.hexdigest()
bigcode/self-oss-instruct-sc2-concepts
def computeDelayMatrix(lengthMat, signalV, segmentLength=1): """ Compute the delay matrix from the fiber length matrix and the signal velocity :param lengthMat: A matrix containing the connection length in segment :param signalV: Signal velocity in m/s :param segmentLength: Length of a single segment in mm :returns: A matrix of connexion delay in ms """ normalizedLenMat = lengthMat * segmentLength if signalV > 0: Dmat = normalizedLenMat / signalV # Interareal delays in ms else: Dmat = lengthMat * 0.0 return Dmat
bigcode/self-oss-instruct-sc2-concepts
def present(ds, t0): """ Return clouds that are present at time `t0` """ # time of appearance tmin = ds.tmin # time of disappearance tmax = ds.tmax m = (tmin <= t0) & (t0 <= tmax) return m
bigcode/self-oss-instruct-sc2-concepts
def WI_statewide_eqn(Qm, A, Qr, Q90): """Regression equation of Gebert and others (2007, 2011) for estimating average annual baseflow from a field measurement of streamflow during low-flow conditions. Parameters ---------- Qm : float or 1-D array of floats Measured streamflow. A : float or 1-D array of floats Drainage area in watershed upstream of where Qm was taken. Qr : float or 1-D array of floats Recorded flow at index station when Qm was taken. Q90 : float or 1-D array of floats Q90 flow at index station. Returns ------- Qb : float or 1-D array of floats, of length equal to input arrays Estimated average annual baseflow at point where Qm was taken. Bf : float or 1-D array of floats, of length equal to input arrays Baseflow factor. see Gebert and others (2007, 2011). Notes ----- Gebert, W.A., Radloff, M.J., Considine, E.J., and Kennedy, J.L., 2007, Use of streamflow data to estimate base flow/ground-water recharge for Wisconsin: Journal of the American Water Resources Association, v. 43, no. 1, p. 220-236, http://dx.doi.org/10.1111/j.1752-1688.2007.00018.x Gebert, W.A., Walker, J.F., and Kennedy, J.L., 2011, Estimating 1970-99 average annual groundwater recharge in Wisconsin using streamflow data: U.S. Geological Survey Open-File Report 2009-1210, 14 p., plus appendixes, available at http://pubs.usgs.gov/ofr/2009/1210/. """ Bf = (Qm / A) * (Q90 / Qr) Qb = 0.907 * A**1.02 * Bf**0.52 return Qb.copy(), Bf.copy()
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def time_elapsed_since(start): """Computes elapsed time since start.""" timedelta = datetime.now() - start string = str(timedelta)[:-7] ms = int(timedelta.total_seconds() * 1000) return string, ms
bigcode/self-oss-instruct-sc2-concepts
import ipaddress def is_valid_ip(ip: str): """Return True if IP address is valid.""" try: if ipaddress.ip_address(ip).version == (4 or 6): return True except ValueError: return False
bigcode/self-oss-instruct-sc2-concepts
def get_user_id(user): """Return id attribute of the object if it is relation, otherwise return given value.""" return user.id if type(user).__name__ == "User" else user
bigcode/self-oss-instruct-sc2-concepts
def append_a(string): """Append "_a" to string and return the modified string""" string = '{}{}'.format(string, '_a') return string
bigcode/self-oss-instruct-sc2-concepts
def disable_control_flow_v2(unused_msg): """Decorator for a function in a with_control_flow_v2 enabled test class. Blocks the function from being run with v2 control flow ops. Args: unused_msg: Reason for disabling. Returns: The wrapped function with _disable_control_flow_v2 attr set to True. """ def wrapper(func): func._disable_control_flow_v2 = True return func return wrapper
bigcode/self-oss-instruct-sc2-concepts
def get_list_uniques(_list): """ This function returns the unique/s value/s of a given list. :param _list: List :return: List containing unique values. """ ret = [] for it in _list: if it not in ret: ret.append(it) return ret
bigcode/self-oss-instruct-sc2-concepts
def vi700(b4, b5): """ Vegetation Index 700 (Gitelson et al., 2002). .. math:: VI700 = (b5 - b4)/(b5 + b4) :param b4: Red. :type b4: numpy.ndarray or float :param b5: Red-edge 1. :type b5: numpy.ndarray or float :returns VI700: Index value .. Tip:: Gitelson, A. A., Kaufman, Y. J., Stark, R., Rundquist, D. 2002. \ Novel algorithms for remote estimation of vegetation fraction. \ Remote sensing of Environment 80(1), 76-87. \ doi:10.1016/S0034-4257(01)00289-9. """ VI700 = (b5 - b4)/(b5 + b4) return VI700
bigcode/self-oss-instruct-sc2-concepts
import json def get_json(json_str, encoding='utf-8'): """ Return a list or dictionary converted from an encoded json_str. json_str (str): JSON string to be decoded and converted encoding (str): encoding used by json_str """ return json.loads(json_str.decode(encoding))
bigcode/self-oss-instruct-sc2-concepts
def joueur_continuer() -> bool: """ Cette fonction est utilisée pour demander au joueur s'il veut continuer ou non de piocher. Returns: bool: Retourne True si le joueur veut piocher, False sinon. """ continuer_le_jeux = input("Voulez-vous piocher? y ou n ") if continuer_le_jeux == "y": return True else: return False
bigcode/self-oss-instruct-sc2-concepts
def resend_strawpoll(jenni, input): """.resendstrawpoll - Resends the last strawpoll link created""" if hasattr(jenni.config, "last_strawpoll"): channel = input.sender if channel in jenni.config.last_strawpoll: return jenni.say(jenni.config.last_strawpoll[channel]) jenni.say("No Strawpoll links have been created yet.")
bigcode/self-oss-instruct-sc2-concepts
import re def replaceTags(value, data_record): """ As efficiently as possible, replace tags in input string with corresponding values in data_record dictionary. The idea is to iterate through all of the elements of the data_record, and replace each instance of a bracketed key in the input string with the associated value indicated by the data record. This function will be used a lot, so it's important to make it as efficient as possible. Args: value (str): The string with tags to replace data_record (dict): A dict containing the tags to replace, and what to replace them with Returns: str: `value` with the tags replaced Examples: >>> data_record = {"a": "AAA", "b": "BBB"} >>> input_value = "aye [a] and bee [b]" >>> replaceTags(input_value, data_record) 'aye AAA and bee BBB' """ prog = re.compile(r"\[([a-zA-Z_][a-zA-Z0-9_\(\)]*)\]") matches = prog.finditer(value) for match in matches: if match.group(1) in data_record: value = value.replace(match.group(0), data_record[match.group(1)]) return value
bigcode/self-oss-instruct-sc2-concepts
def LastLineLength(s): """Returns the length of the last line in s. Args: s: A multi-line string, including newlines. Returns: The length of the last line in s, in characters. """ if s.rfind('\n') == -1: return len(s) return len(s) - s.rfind('\n') - len('\n')
bigcode/self-oss-instruct-sc2-concepts
def input_int(prompt: str, min_val: int = 1, max_val: int = 5) -> int: """Get an integer from the user""" while True: try: user_input = int(input(prompt)) if min_val <= user_input <= max_val: return user_input print("Value not within range. Try again!") except ValueError: print("Invalid integer input. Try again!")
bigcode/self-oss-instruct-sc2-concepts
import pathlib def get_test_cases(which_subset): """Return a list of test case files.""" assert which_subset in ("valid", "invalid") cwd = pathlib.Path(__file__).parent.resolve() test_dir = cwd / ".." / "demes-spec" / "test-cases" / which_subset files = [str(file) for file in test_dir.glob("*.yaml")] assert len(files) > 1 return files
bigcode/self-oss-instruct-sc2-concepts
def is_info_hash_valid(data: bytes, info_hash: bytes) -> bool: """ Checks if the info_hash sent by another peer matches ours. """ return data[28:48] == info_hash
bigcode/self-oss-instruct-sc2-concepts
def dict_diff(a, b): """Returns the difference between two dictionaries. Parameters ---------- a : dict The dictionary to prefer different results from. b : dict The dictionary to compare against. Returns ------- dict A dictionary with only the different keys: values. """ diff = {} for key in list(a.keys()): if key in b: if b[key] != a[key]: diff[key] = a[key] else: diff[key] = a[key] return diff
bigcode/self-oss-instruct-sc2-concepts
def read_ccloud_config(config_file): """Read Confluent Cloud configuration for librdkafka clients""" conf = {} with open(config_file) as fh: for line in fh: line = line.strip() if line[0] != "#" and len(line) != 0: parameter, value = line.strip().split('=', 1) conf[parameter] = value.strip() return conf
bigcode/self-oss-instruct-sc2-concepts