seed
stringlengths
1
14k
source
stringclasses
2 values
def integerize(num, count): """Calculate and return integer value if result is integer""" calc = num * count calc = int(calc) if calc.is_integer() else calc return calc
bigcode/self-oss-instruct-sc2-concepts
import requests def get_redirected_url(url: str) -> str: """ Given a URL, return the URL it redirects to. Args: url (str) """ r = requests.get(url) return r.url
bigcode/self-oss-instruct-sc2-concepts
def _find_var_dictionary(table, dict_name=None, dict_type=None): ############################################################################### """Find and return a var_dictionary named, <dict_name> in <table>. If not found, return None""" var_dicts = table.find("var_dictionaries") target_dict = None if (dict_name is None) and (dict_type is None): raise ValueError(("At least one of <dict_name> or <dict_type> must " "contain a string")) # end if for vdict in var_dicts: if (((dict_name is None) or (vdict.get("name") == dict_name)) and ((dict_type is None) or (vdict.get("type") == dict_type))): target_dict = vdict break # end if # end for return target_dict
bigcode/self-oss-instruct-sc2-concepts
def return_top(scores, metric, x): """ :param scores: Pandas DataFrame with scores :type scores: Pandas DataFrame :param metric: String value for what score is desired ("Growth Score", "Value Score", "Momentum Score", "Score") :type metric: str :param x: Integer number of top stocks to return :type x: int :return: return top x number of stocks by score as Pandas DataFrame :rtype: Pandas DataFrame """ return scores.nlargest(x, [metric])
bigcode/self-oss-instruct-sc2-concepts
def CollateDeps(deps_content): """ Take the output of deps_utils.GetDepsContent and return a hash of: { submod_name : [ [ submod_os, ... ], submod_url, submod_sha1 ], ... } """ spliturl = lambda x: list(x.partition('@')[0::2]) if x else [None, None] submods = {} # Non-OS-specific DEPS always override OS-specific deps. This is an interim # hack until there is a better way to handle OS-specific DEPS. for (deps_os, val) in deps_content[1].iteritems(): for (dep, url) in val.iteritems(): submod_data = submods.setdefault(dep, [[]] + spliturl(url)) submod_data[0].append(deps_os) for (dep, url) in deps_content[0].iteritems(): submods[dep] = [['all']] + spliturl(url) return submods
bigcode/self-oss-instruct-sc2-concepts
def _encode_none(name, dummy0, dummy1, dummy2): """Encode python None.""" return b"\x0A" + name
bigcode/self-oss-instruct-sc2-concepts
def scenegraph_to_json(sg): """ Dump an "SceneGraph" object to a dict that's used for evaluation. The output will be saved as json. Args: sg (SceneGraph): Returns: dict: contains predictions for one image. """ boxes = sg.pred_boxes.tensor.numpy().tolist() # for vg evaluation, all boxes should be in XYXY_ABS scores = sg.scores.numpy().tolist() classes = sg.pred_classes.numpy().tolist() rel_scores = sg.rel_scores.numpy().tolist() rel_inds = sg.rel_inds.numpy().tolist() result = { "category_ids": classes, "bboxes": boxes, "scores": scores, "rel_scores": rel_scores, "rel_inds": rel_inds } return result
bigcode/self-oss-instruct-sc2-concepts
import hashlib def get_md5(file): """Get the md5 checksum of an input file. Arguments --------- file : str Path to file for which compute the checksum. Returns ------- md5 Checksum for the given filepath. Example ------- >>> get_md5('samples/audio_samples/example1.wav') 'c482d0081ca35302d30d12f1136c34e5' """ # Lets read stuff in 64kb chunks! BUF_SIZE = 65536 md5 = hashlib.md5() # Computing md5 with open(file, "rb") as f: while True: data = f.read(BUF_SIZE) if not data: break md5.update(data) return md5.hexdigest()
bigcode/self-oss-instruct-sc2-concepts
def process_mmdet_results(mmdet_results, cat_id=0): """Process mmdet results, and return a list of bboxes. :param mmdet_results: :param cat_id: category id (default: 0 for human) :return: a list of detected bounding boxes """ if isinstance(mmdet_results, tuple): det_results = mmdet_results[0] else: det_results = mmdet_results return det_results[cat_id]
bigcode/self-oss-instruct-sc2-concepts
def assemble_subpeak_record(subpeak, celltype_activations, sequence): """ Assemble the FASTA record of sequence and activation """ # make the header header ='\t'.join([s for s in subpeak]) header = '>' + header # make the activation string activation = ';'.join([ct+' '+str(score) for (ct,score) in celltype_activations]) # append the sequence seq_string = str(sequence) return header, activation, seq_string
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def is_state_nncf(state: Dict) -> bool: """The function to check if sate is the result of NNCF-compressed model.""" return bool(state.get("meta", {}).get("nncf_enable_compression", False))
bigcode/self-oss-instruct-sc2-concepts
def read_split(split_filename): """ Return a list of pdb codes included in the split. """ print('Reading split from file', split_filename) with open(split_filename, 'r') as f: pdbcodes = [t.strip() for t in f.readlines()] return pdbcodes
bigcode/self-oss-instruct-sc2-concepts
def clean_info(package_dict: dict) -> dict: """ Only keep `name` and `home-page` keys. Arguments: package_dict: Package information. Returns: Cleaned-up information. """ return {_: package_dict[_] for _ in ("name", "home-page")}
bigcode/self-oss-instruct-sc2-concepts
def extended_euclidean_algorithm(a, b): # @param ax + by = gcd(a,b) """ Based on the fact that: b % a = b - (b // a) * a\\ gcd(a, b) = gcd(b%a, a) """ if a == 0: return b, 0, 1 gcd, x1, y1 = extended_euclidean_algorithm(b % a, a) x = y1 - (b//a)*x1 y = x1 return (gcd, x, y)
bigcode/self-oss-instruct-sc2-concepts
def cidade_pais(cidade: str, pais: str, populacao: int = 0) -> str: """ -> Aceita o nome de uma cidade, o nome do país e a população dessa cidade, retorna essas informações formatadas. :param cidade: Nome da cidade. :param pais: Nome do país. :param populacao: Número da população da cidade. :return: Retorna uma string com o nome da cidade, do país e a população a cidade no formato 'Cidade, País - população XXX'. """ if populacao: nome_formatado = (f'{cidade.title()}, {pais.title()} ' f'- população {populacao}') else: nome_formatado = f'{cidade}, {pais}'.title() return nome_formatado
bigcode/self-oss-instruct-sc2-concepts
def string_to_bits(str): """ string_to_bits Function Converts a Pythonic string to the string's binary representation. Parameters ---------- str: string The string to be converted. Returns ------- data: string The binary representation of the input string. """ data = (''.join(format(ord(x), 'b') for x in str)) return(data)
bigcode/self-oss-instruct-sc2-concepts
import torch import math def uniform_binning_correction(x, n_bits=8): """Replaces x^i with q^i(x) = U(x, x + 1.0 / 256.0). Args: x: 4-D Tensor of shape (NCHW) n_bits: optional. Returns: x: x ~ U(x, x + 1.0 / 256) objective: Equivalent to -q(x)*log(q(x)). """ b, c, h, w = x.size() n_bins = 2**n_bits chw = c * h * w x += torch.zeros_like(x).uniform_(0, 1.0 / n_bins) objective = -math.log(n_bins) * chw * torch.ones(b, device=x.device) return x, objective
bigcode/self-oss-instruct-sc2-concepts
def remove_underscore(text): """ Call this on variable names and api endpoints, so that BERT tokenizes names like 'find_place' as 'find place'. """ return text.replace("_", " ")
bigcode/self-oss-instruct-sc2-concepts
def filter_contacts(cmap, threshold=0.2): """Remove low score contacts from contact prediction list. :param cmap: Contact prediction map. :type cmap: :class:`~conkit.core.contactmap.ContactMap` :param threshold: Threshold, defaults to 0.2. :type threshold: float, optional """ cmap.sort('raw_score', reverse=True, inplace=True) cnt = 0 for contact in cmap: if contact.raw_score < threshold: break else: cnt = cnt+1 return cmap[:cnt-1]
bigcode/self-oss-instruct-sc2-concepts
def split_seconds(seconds: int) -> dict: """This function converts seconds into a dictionary by splitting seconds without year, month, day, hour, minute and second when possible. :param seconds: seconds that will be converted Example: >>> from phanterpwa.tools import split_seconds >>> split_seconds(123456789) {'year': 3, 'month': 11, 'day': 3, 'hour': 21, 'minute': 33, 'second': 9} >>> split_seconds(121) {'minute': 2, 'second': 1} >>> split_seconds(3659) {'hour': 1, 'second': 59} """ if not isinstance(seconds, int): raise ValueError("The seconds must be an integer. Given: {0}".format(seconds)) def s(seconds, d={}): d = dict(**d) if seconds >= 31536000: if seconds % 31536000: r = seconds % 31536000 d['year'] = seconds // 31536000 return s(r, d) else: d['year'] = seconds // 31536000 return d else: if seconds >= 2592000: if seconds % 2592000: r = seconds % 2592000 d['month'] = seconds // 2592000 return s(r, d) else: d['month'] = seconds // 2592000 return d else: if seconds >= 86400: if seconds % 86400: r = seconds % 86400 d['day'] = seconds // 86400 return s(r, d) else: d['day'] = seconds // 86400 return d else: if seconds >= 3600: if seconds % 3600: r = seconds % 3600 d['hour'] = seconds // 3600 return s(r, d) else: d['hour'] = seconds // 3600 return d else: if seconds >= 60: if seconds % 60: r = seconds % 60 d['minute'] = seconds // 60 return s(r, d) else: d['minute'] = seconds // 60 return d else: d['second'] = seconds return d return s(seconds)
bigcode/self-oss-instruct-sc2-concepts
import base64 import json def encode_data(data): """Return a base64 encoded json dump.""" encoded = base64.b64encode( json.dumps(data).encode('utf-8') ) assert len(encoded) < 250 * 1024 return encoded
bigcode/self-oss-instruct-sc2-concepts
import math def getUnitCost(demand: int) -> float: """ Implementation of decreasing unit cost: Unit cost drops as demand/production increases. """ average_fixed_cost = 2.5 weight = 0.75 average_variable_cost = weight*math.log(demand) return average_fixed_cost + average_variable_cost
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Union def format_sum_formula(sumform: Dict[str, Union[int, float]], break_after: int = 99) -> str: """ Makes html formated sum formula from dictionary. >>> format_sum_formula({'C': 12, 'H': 6, 'O': 3, 'Mn': 7}) '<html><body>C<sub>12 </sub>H<sub>6 </sub>O<sub>3 </sub>Mn<sub>7 </sub></body></html>' """ # atlist = formula_str_to_dict(sumform) if not sumform: return '' l = ['<html><body>'] num = 0 for i in sumform: if i == 'Id' or i == 'StructureId': continue if sumform[i] == 0 or sumform[i] == None: continue try: times = round(sumform[i], 1) except TypeError: times = 1 if num > 3 and num % break_after == 0: l.append("<br>") try: el = i.split('_')[1] # split here, because database returns 'Elem_C' for example except IndexError: el = i l.append("{}<sub>{:g} </sub>".format(el, times)) num += 1 l.append('</body></html>') formula = "".join(l) # print(formula) return formula
bigcode/self-oss-instruct-sc2-concepts
def get_iwp_label_key( iwp_label ): """ Retrieves a key that locates the supplied IWP label within the underlying dataset. The key returned locates the label both temporarly and spatially. Takes 1 argument: iwp_label - IWP label to locate. Returns 1 value: label_key - Tuple identifying iwp_label's location within a dataset. Comprised of (time step index, z index). """ return (iwp_label["time_step_index"], iwp_label["z_index"])
bigcode/self-oss-instruct-sc2-concepts
import yaml def template_params(path): """ Return parameters as dict from a YAML template file. """ with open(path, "r") as file: return yaml.safe_load(file)
bigcode/self-oss-instruct-sc2-concepts
def _mnl_transform_deriv_c(*args, **kwargs): """ Returns None. This is a place holder function since the MNL model has no shape parameters. """ # This is a place holder function since the MNL model has no shape # parameters. return None
bigcode/self-oss-instruct-sc2-concepts
def _pad(slist, n, c=" "): """_pad(slist, n, c=' ') pads each member of string list 'slist' with fill character 'c' to a total length of 'n' characters and returns the concatenated results. strings longer than n are *truncated*. >>> >>> _pad(["this","that","the other"],9," ") 'this that the other' """ if isinstance(slist, str): if n > len(slist): return slist + c*(n-len(slist)) else: return slist[:n] else: result = [] for s in slist: if isinstance(s, str): if n > len(s): t = s + c*(n-len(s)) else: t = s[:n] else: t = _pad(s, n, c) result.append(t) return "".join(result)
bigcode/self-oss-instruct-sc2-concepts
def _ensure_trailing_slash(url: str) -> str: """Return url guaranteed to end in a slash""" return url if url.endswith("/") else f"{url}/"
bigcode/self-oss-instruct-sc2-concepts
def _scoped_name(name_scope, node_name): """Returns scoped name for a node as a string in the form '<scope>/<node name>'. Args: name_scope: a string representing a scope name, similar to that of tf.name_scope. node_name: a string representing the current node name. Returns A string representing a scoped name. """ if name_scope: return '%s/%s' % (name_scope, node_name) return node_name
bigcode/self-oss-instruct-sc2-concepts
def process_claim(claim): """Convert a claim row into a set of points""" claim_number, details = [i.strip() for i in claim.split('@')] # strip the leading # claim_number = int(claim_number[1:]) coordinates, area = [i.strip() for i in details.split(':')] column, row = [int(i) for i in coordinates.split(',')] width, height = [int(i) for i in area.split('x')] claims = set( (x, y) for x in range(row, row + height) for y in range(column, column + width) ) return claim_number, claims
bigcode/self-oss-instruct-sc2-concepts
import math def num_digits(n): """ Return the number of digits (in base 10) for integer n > 0 """ return int(math.log10(n)) + 1
bigcode/self-oss-instruct-sc2-concepts
def get_best_fuzz(predicted_mem): """Retrieve the best prediction""" y_pred = predicted_mem.argmax(axis=1) return y_pred
bigcode/self-oss-instruct-sc2-concepts
def append_heatmap(tokens, scores, latex, gamma, caption, pad_token, formatting="colorbox", truncate_pad=True): """ Produce a heatmap for LaTeX Format options: colorbox, text""" if gamma != 1: raise NotImplementedError latex += "\n\\begin{figure}[!htb]" for token, score in zip(tokens, scores): if token == pad_token and truncate_pad: continue color = "blue" if score >= 0: color = "red" latex += f"\\{formatting}" + "{" + f"{color}!{abs(score) * 100}" + "}" + "{" + token + "}" latex += "\\caption{" + f"{caption}" + "}" latex += "\\end{figure}\n" return latex
bigcode/self-oss-instruct-sc2-concepts
def total_link_cost(net): """ Compute the total of link costs (volume * costfunction(volume)) over all links at current volumes on those links Parameters: net - Net object as returned by parse_net_file() Return value: total link cost """ return sum([link.volume * link.cost for link in net.links])
bigcode/self-oss-instruct-sc2-concepts
def make_grid(x, y, fill: int = 0): """Make a 2x2 list of lists filled with "fill".""" return [[fill for y in range(y)] for _ in range(x)]
bigcode/self-oss-instruct-sc2-concepts
def i8(x): """truncates x to a 8-bit integer""" return x & 0xFF
bigcode/self-oss-instruct-sc2-concepts
def get_las_version(las): """ Get the LAS file format version from an in-memory lasio.LAFile object. There are 3 possible versions (https://www.cwls.org/products/): - LAS 1.2 - LAS 2.0 - LAS 3.0 Args: las (lasio.LASFile): An in-memory lasio.LASFile object Returns: version (float): LAS format version """ version = float(las.version[0].value) return version
bigcode/self-oss-instruct-sc2-concepts
from typing import Sequence from typing import Dict from typing import Any def bind_function_args(argument_names: Sequence[str], *args, **kwargs) -> Dict[str, Any]: """Returns a dict with function arguments.""" outputs = {} for k, val in zip(argument_names, args): outputs[k] = val outputs.update(**kwargs) return outputs
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def make_character_dict() -> Dict[str, str]: """Create dict of {character: label, ->} to label smiles characters """ character_dict = {} atoms = ["C", "O", "N", "S", "B", "P", "F", "I", "c", "n", "o", '*', 'Cl', 'Br', 'p', 'b', 'p', 's'] cyclic = list(range(1,100)) for atom in atoms: character_dict[atom] = "atom" for number in cyclic: character_dict[str(number)] = "cyclic" character_dict["="] = "double_bond" character_dict["("] = "branch_start" character_dict[")"] = "branch_end" character_dict['\\'] = 'chiral_double_bond' character_dict['/'] = 'chiral_double_bond' character_dict['#'] = 'triple_bond' character_dict['$'] = 'quadruple_bond' character_dict['.'] = 'split' character_dict['-'] = 'single_bond' character_dict[':'] = 'aromatic_bond' return character_dict
bigcode/self-oss-instruct-sc2-concepts
def list_contains_only_xs(lst): """Check whether the given list contains only x's""" for elem in lst: if elem != "X": return False return True
bigcode/self-oss-instruct-sc2-concepts
import json def decode_json(json_string: str) -> dict: """ Takes a message as a JSON string and unpacks it to get a dictionary. :param str json_string: A message, as a JSON string. :return dict: An unverified dictionary. Do not trust this data. """ return json.JSONDecoder().decode(json_string)
bigcode/self-oss-instruct-sc2-concepts
def set_length_units(client, units, file_=None, convert=None): """Set the current length units for a model. This will search the model's available Unit Systems for the first one which contains the given length unit. Args: client (obj): creopyson Client. units (str): New length units. `file_` (str|list:str, optional): File name or List of file names; Defaults is currently active model. convert (bool, optional): Whether to convert the model's length values to the new units (True) or leave them the same value (False). Defaults is True. Returns: None """ data = {"units": units} if file_ is not None: if isinstance(file_, (str)): data["file"] = file_ elif isinstance(file_, (list)): data["files"] = file_ else: active_file = client.file_get_active() if active_file: data["file"] = active_file["file"] if convert is not None: data["convert"] = convert return client._creoson_post("file", "set_length_units", data)
bigcode/self-oss-instruct-sc2-concepts
import torch import math def log_sum_exp(a: torch.Tensor, b: torch.Tensor): """ Logsumexp with safety checks for infs. """ if torch.isinf(a): return b if torch.isinf(b): return a if a > b: return math.log1p(math.exp(b - a)) + a else: return math.log1p(math.exp(a - b)) + b
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Any from typing import Union from typing import Tuple def isinstances(__obj: List[Any], __class_or_tuple: Union[Any, Tuple[Any]]) -> bool: """Return whether an every element of the list is an instance of a class or of a subclass thereof. A tuple, as in `isinstance(x, (A, B, ...))`, may be given as the target to check against. This is equivalent to `isinstance(x, A)` or `isinstance(x, B)` or ... etc. """ return all(isinstance(obj, __class_or_tuple) for obj in __obj)
bigcode/self-oss-instruct-sc2-concepts
def polynomial_power_combinations(degree): """ Combinations of powers for a 2D polynomial of a given degree. Produces the (i, j) pairs to evaluate the polynomial with ``x**i*y**j``. Parameters ---------- degree : int The degree of the 2D polynomial. Must be >= 1. Returns ------- combinations : tuple A tuple with ``(i, j)`` pairs. Examples -------- >>> print(polynomial_power_combinations(1)) ((0, 0), (1, 0), (0, 1)) >>> print(polynomial_power_combinations(2)) ((0, 0), (1, 0), (0, 1), (2, 0), (1, 1), (0, 2)) >>> # This is a long polynomial so split it in two lines >>> print(" ".join([str(c) for c in polynomial_power_combinations(3)])) (0, 0) (1, 0) (0, 1) (2, 0) (1, 1) (0, 2) (3, 0) (2, 1) (1, 2) (0, 3) >>> # A degree zero polynomial would be just the mean >>> print(polynomial_power_combinations(0)) ((0, 0),) """ if degree < 0: raise ValueError("Invalid polynomial degree '{}'. Must be >= 0.".format(degree)) combinations = ((i, j) for j in range(degree + 1) for i in range(degree + 1 - j)) return tuple(sorted(combinations, key=sum))
bigcode/self-oss-instruct-sc2-concepts
def from_cpp(str_msg, cls): """Return a ROS message from a serialized string Parameters ---------- - str_msg: str, serialized message - cls: ROS message class, e.g. sensor_msgs.msg.LaserScan. """ msg = cls() result = msg.deserialize(str_msg) return result
bigcode/self-oss-instruct-sc2-concepts
def ipv4_lstrip_zeros(address): """ The function to strip leading zeros in each octet of an IPv4 address. Args: address: An IPv4 address in string format. Returns: String: The modified IPv4 address string. """ # Split the octets. obj = address.strip().split('.') for x, y in enumerate(obj): # Strip leading zeros. Split / here in case CIDR is attached. obj[x] = y.split('/')[0].lstrip('0') if obj[x] in ['', None]: obj[x] = '0' return '.'.join(obj)
bigcode/self-oss-instruct-sc2-concepts
import re def join_lines(src, before, after, sep=" "): """ Remove the newline and indent between a pair of lines where the first ends with ``before`` and the second starts with ``after``, replacing it by the ``sep``. """ before_re = "][".join(before).join("[]") after_re = "][".join(after).join("[]") regex = "\n\\s*".join([before_re, after_re]) return re.sub(regex, sep.join([before, after]), src)
bigcode/self-oss-instruct-sc2-concepts
def flatten_stmts(stmts): """Return the full set of unique stms in a pre-assembled stmt graph. The flattened list of of statements returned by this function can be compared to the original set of unique statements to make sure no statements have been lost during the preassembly process. Parameters ---------- stmts : list of :py:class:`indra.statements.Statement` A list of top-level statements with associated supporting statements resulting from building a statement hierarchy with :py:meth:`combine_related`. Returns ------- stmts : list of :py:class:`indra.statements.Statement` List of all statements contained in the hierarchical statement graph. Examples -------- Calling :py:meth:`combine_related` on two statements results in one top-level statement; calling :py:func:`flatten_stmts` recovers both: >>> from indra.preassembler.hierarchy_manager import hierarchies >>> braf = Agent('BRAF') >>> map2k1 = Agent('MAP2K1') >>> st1 = Phosphorylation(braf, map2k1) >>> st2 = Phosphorylation(braf, map2k1, residue='S') >>> pa = Preassembler(hierarchies, [st1, st2]) >>> pa.combine_related() # doctest:+ELLIPSIS [Phosphorylation(BRAF(), MAP2K1(), S)] >>> flattened = flatten_stmts(pa.related_stmts) >>> flattened.sort(key=lambda x: x.matches_key()) >>> flattened [Phosphorylation(BRAF(), MAP2K1()), Phosphorylation(BRAF(), MAP2K1(), S)] """ total_stmts = set(stmts) for stmt in stmts: if stmt.supported_by: children = flatten_stmts(stmt.supported_by) total_stmts = total_stmts.union(children) return list(total_stmts)
bigcode/self-oss-instruct-sc2-concepts
import math def round_sig(number, precision=4): """ Round number with given number of significant numbers - precision Args: number (number): number to round precision (int): number of significant numbers """ if number == 0.0: return number return round(number, precision - int(math.floor(math.log10(abs(number)))) - 1)
bigcode/self-oss-instruct-sc2-concepts
def pairs(k, arr): """Hackerrank Problem: https://www.hackerrank.com/challenges/pairs/problem You will be given an array of integers and a target value. Determine the number of pairs of array elements that have a difference equal to a target value. Args: k (int): The target difference arr (list): list of integers Returns: int: number of pairs of integers whose difference is k """ vals = {i: 1 for i in arr} count = 0 for i in arr: try: count += vals[i + k] except KeyError: pass return count
bigcode/self-oss-instruct-sc2-concepts
def find(sexp, *names): """Return the first node in `sexp` whose name is in `names`""" for child in sexp: if child[0] in names: return child
bigcode/self-oss-instruct-sc2-concepts
import json def get_workflow_metadata(metadata_json): """Load workflow metadata from a JSON file. Args: metadata_json (str): Path to file containing metadata json for the workflow. Returns: metadata (dict): A dict consisting of Cromwell workflow metadata information. """ with open(metadata_json) as f: metadata = json.load(f) return metadata
bigcode/self-oss-instruct-sc2-concepts
def create_unbroadcast_axis(shape, broadcast_shape): """Creates the reduction axis for unbroadcasting. Args: shape: A list. The shape after the broadcast operation. broadcast_shape: A list. The original shape the array being unbroadcast had. Returns: A list. The axes along which the array needs to be reduced. These axes will be distributed evenly into the original shape. """ return tuple( -(1 + i) for i in range(len(broadcast_shape)) if i >= len(shape) or broadcast_shape[-(1 + i)] > shape[-(1 + i)])
bigcode/self-oss-instruct-sc2-concepts
def check_zeros(counts): """ helper function to check if vector is all zero :param counts: :return: bool """ if sum(counts) == 0: return True else: return False
bigcode/self-oss-instruct-sc2-concepts
def get_nat_orb_occ(lines): """ Find the natural orbital occupations """ nat_occ = [] start = False for line in lines: if start: if line.strip(): nat_occ.append(abs(float(line.split('=')[-1].strip()))) else: break elif line == 'Natural Orbital Occupation Numbers:\n': start = True return nat_occ
bigcode/self-oss-instruct-sc2-concepts
def are_words_in_word_list( words, word_list, case_sensitive=False, get_score=False, all_must_match=True ): """Checks if word(s) are contained in another word list. The search can be performed with or without case sensitivity. The check words can contain wildcards, e.g. "abc*" to allow a wider range of matches against the word list.""" if not isinstance(words, list): check_words = [words] else: check_words = words found = {} for w in check_words: word = w.lower() if not case_sensitive else w if "*" in word: idx = word.find("*") - 1 word = word[:idx] for wl in word_list: wl = wl.lower() if not case_sensitive else wl if wl.startswith(word): found[word] = True if all_must_match and len(found) == len(check_words): if get_score: return True, len(found) return True if not all_must_match and len(found) > 0: if get_score: return True, len(found) return True if get_score: return False, len(found) return False
bigcode/self-oss-instruct-sc2-concepts
def percentiles_from_counts(counts_dt, percentiles_range=None): """Returns [(percentile, value)] with nearest rank percentiles. Percentile 0: <min_value>, 100: <max_value>. counts_dt: { <value>: <count> } percentiles_range: iterable for percentiles to calculate; 0 <= ~ <= 100 Source: https://stackoverflow.com/questions/25070086/percentiles-from-counts-of-values """ if percentiles_range is None: percentiles_range = [0, 1, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 99, 100] # This handle the input if the case under analysis is completely absent in the annotation (count_dt is empty) if not counts_dt: vals = [0 for _ in range(len(percentiles_range))] percentiles = list(zip(percentiles_range, vals)) return percentiles assert all(0 <= p <= 100 for p in percentiles_range) percentiles = [] num = sum(counts_dt.values()) counts = sorted(counts_dt.items()) curr_counts_pos = 0 # current position in counts curr_pos = counts[0][1] # sum of frequencies up to curr_counts_pos for p in sorted(percentiles_range): if p < 100: percentile_pos = p / 100.0 * num while curr_pos <= percentile_pos and curr_counts_pos < len(counts): curr_counts_pos += 1 curr_pos += counts[curr_counts_pos][1] percentiles.append((p, counts[curr_counts_pos][0])) else: percentiles.append((p, counts[-1][0])) return percentiles
bigcode/self-oss-instruct-sc2-concepts
def epsi_vapor_bot(Fr_bot): """ Calculates the vapor content of bubble layer at the bottom of column Parameters ---------- Fr_bot : float The Frudo criterion at the bottom of column, [dimensionless] Returns ------- epsi_vapor_bot : float The vapor content of bubble layer at the bottom of column, [dimensionless] References ---------- Дытнерский, страница 207, формула 5.47 """ return Fr_bot**0.5 / (1 + Fr_bot**0.5)
bigcode/self-oss-instruct-sc2-concepts
def flatten_double_list(double_list): """ flatten a double list into a single list. """ return [obj for single_list in double_list for obj in single_list]
bigcode/self-oss-instruct-sc2-concepts
def slice_list_to_chunks(lst, n): """ Slice a list into chunks of size n. Args: list int Returns: [list] """ chunks = [lst[x:x+n] for x in range(0, len(lst), n)] return chunks
bigcode/self-oss-instruct-sc2-concepts
def get_age_bracket(school_type): """Return the age structure for different school types.""" age_brackets = { 'primary':[6, 7, 8, 9], 'primary_dc':[6, 7, 8, 9], 'lower_secondary':[10, 11, 12, 13], 'lower_secondary_dc':[10, 11, 12, 13], 'upper_secondary':[14, 15, 16, 17], 'secondary':[10, 11, 12, 13, 14, 15, 16, 17], 'secondary_dc':[10, 11, 12, 13, 14, 15, 16, 17] } return age_brackets[school_type]
bigcode/self-oss-instruct-sc2-concepts
def seq_to_arch(seq, num_nodes): """ Translates given sequential representation of an architecture sampled by the controller to an architecture Arguments: seq: sequential representation of architecture num_nodes: number of nodes in cell including the two input nodes Returns: a list of 4-tuples (n0 op0 n1 op1), where n0 and n1 are two previous nodes and op0 and op1 are operations to be applied to n0 and n1, respectively. e.g. [(0, 1, 0, 1), (0, 1, 0, 1), (0, 1, 0, 1), (0, 1, 0, 1), (0, 4, 0, 4)] """ arch = [] for i in range(0, len(seq), 4): arch.append( ( seq[i].item() - 1, seq[i + 1].item() - (num_nodes - 1) - 1, seq[i + 2].item() - 1, seq[i + 3].item() - (num_nodes - 1) - 1, ) ) return arch
bigcode/self-oss-instruct-sc2-concepts
def force_tuple(x): """Make tuple out of `x` if not already a tuple or `x` is None""" if x is not None and not isinstance(x, tuple): return (x,) else: return x
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Dict def _build_record_dict(record_strings: List[str]) -> Dict: """ Parse the pbn line by line. When a block section like "Auction" or "Play" is encountered, collect all the content of the block into a single entry :param record_strings: List of string lines for a single board :return: A dictionary mapping keys from the pbn to strings or other useful values (e.g. list of strings for the bidding record) """ record_dict = {} # Janky while loop to handle non bracketed lines i = 0 while i < len(record_strings): record_string = record_strings[i] if not (record_string.startswith("[") or record_string.startswith("{")): i += 1 continue if record_string.startswith("{"): commentary = "" while i < len(record_strings): record_string = record_strings[i] if record_string.startswith("["): break commentary += record_string + " " i += 1 record_dict["Commentary"] = commentary.strip() continue if record_string.startswith("[") and "]" not in record_string: while "]" not in record_string: i += 1 record_string = record_string + record_strings[i] record_string = record_string.replace("[", "").replace("]", "") key, value = record_string.split(maxsplit=1) value = value.replace('"', "") if key == "Note": number, message = value.split(":", maxsplit=1) key = key + "_" + number value = message record_dict[key] = value if key == "Auction": auction_record = [] i += 1 while i < len(record_strings): auction_str = record_strings[i] if "[" in auction_str: break auction_record.extend(auction_str.split()) i += 1 record_dict["bidding_record"] = auction_record elif key == "Play": play_record = [] i += 1 while i < len(record_strings): play_str = record_strings[i] if "[" in play_str or play_str == "*": break play_record.append(play_str.split()) i += 1 record_dict["play_record"] = play_record else: i += 1 return record_dict
bigcode/self-oss-instruct-sc2-concepts
def ts_to_vtt(timestamp): """ ts_to_vtt converts timestamp into webvtt times """ hours, seconds = divmod(timestamp, 3600) mins, seconds = divmod(seconds, 60) seconds = round(seconds, 3) return f" {int(hours):02}:{int(mins):02}:{seconds:02}"
bigcode/self-oss-instruct-sc2-concepts
def _node_label(node): """Generate a node label in the format of "support:name" if both exist, or "support" or "name" if either exists. Parameters ---------- skbio.TreeNode node containing support value or name Returns ------- str Generated node label """ lblst = [] if node.support is not None: # prevents support of NoneType lblst.append(str(node.support)) if node.name: # prevents name of NoneType lblst.append(node.name) return ':'.join(lblst)
bigcode/self-oss-instruct-sc2-concepts
def fetch_tensor(name, ws): """Return the value of a tensor.""" return ws.get_tensor(name).ToNumpy()
bigcode/self-oss-instruct-sc2-concepts
def torch2numpy(img): """ Converts a torch image to numpy format """ if img.dim() == 4: img = img.permute(0, 2, 3, 1).contiguous() elif img.dim() == 3: img = img.permute(1, 2, 0).contiguous() return img.cpu().numpy()
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict import re def str_replace(s: str, replacements: Dict[str, str]) -> str: """Replaces keys in replacements dict with their values.""" for word, replacement in replacements.items(): if word in s: s = re.sub(re.escape(word), replacement, s, flags=re.IGNORECASE) return s
bigcode/self-oss-instruct-sc2-concepts
def get_bits(num, gen): """ Get "num" bits from gen """ out = 0 for i in range(num): out <<= 1 val = gen.next() if val != []: out += val & 0x01 else: return [] return out
bigcode/self-oss-instruct-sc2-concepts
def GetMangledParam(datatype): """Returns a mangled identifier for the datatype.""" if len(datatype) <= 2: return datatype.replace('[', 'A') ret = '' for i in range(1, len(datatype)): c = datatype[i] if c == '[': ret += 'A' elif c.isupper() or datatype[i - 1] in ['/', 'L']: ret += c.upper() return ret
bigcode/self-oss-instruct-sc2-concepts
def get_feature_class(base_name, workspace): """ Creates a valid ESRI reference to a shapefile or geodatabase feature class base_name: the name of the feature class, without any extension workspace: the name of the folder (for shapefiles) or geodatabase (for gdb feature classes) return: a text string referring to the location of the feature class """ if workspace[-4:] != '.gdb': fc = workspace + '\\' + base_name + '.shp' else: fc = workspace + '\\' + base_name return fc
bigcode/self-oss-instruct-sc2-concepts
import signal def signal_to_human(value): """signal_to_human() -- provide signal name based on subprocess return code Args: value (int) - Popen.returncode Returns: Signal name if it exists, otherwise the original value provided """ signals = {getattr(signal, name) * -1 : name for name in dir(signal) if name.startswith("SIG")} if value < 0 and value in signals: return signals[value] return value
bigcode/self-oss-instruct-sc2-concepts
def interpret_bintime(bintime): """If bin time is negative, interpret as power of two. Examples -------- >>> interpret_bintime(2) 2 >>> interpret_bintime(-2) == 0.25 True >>> interpret_bintime(0) Traceback (most recent call last): ... ValueError: Bin time cannot be = 0 """ if bintime < 0: return 2 ** bintime elif bintime > 0: return bintime raise ValueError("Bin time cannot be = 0")
bigcode/self-oss-instruct-sc2-concepts
def get_kernel(x, kernel): """ Calculates the kernel size given the input. Kernel size is changed only if the input dimentions are smaller than kernel Args: x: The input vector. kernel: The height and width of the convolution kernel filter Returns: The height and width of new convolution kernel filter """ height = kernel[0] width = kernel[1] if x.get_shape().as_list()[1] < height: height = x.get_shape().as_list()[1] elif x.get_shape().as_list()[2] < width: width = x.get_shape().as_list()[2] return (height, width)
bigcode/self-oss-instruct-sc2-concepts
def pot_LJ_dl(r): """Dimensionless Lenard Jones potential, based on distances""" r = r**-6 # Possibly improves speed u = 4*(r**2 - r) return u
bigcode/self-oss-instruct-sc2-concepts
def fit_model(model, callbacks_list, sequence, outseq, n_epoch): """ Make RAENN model Parameters ---------- model : keras.models.Model RAENN model to be trained callbacks_list : list List of keras callbacks sequence : numpy.ndarray Array LC flux times, values and errors outseq : numpy.ndarray An array of LC flux values and limiting magnitudes n_epoch : int Number of epochs to train for Returns ------- model : keras.models.Model Trained keras model """ model.fit([sequence, outseq], sequence, epochs=n_epoch, verbose=1, shuffle=False, callbacks=callbacks_list, validation_split=0.33) return model
bigcode/self-oss-instruct-sc2-concepts
def get_named_object(pathspec): """Return a named from a module. """ parts = pathspec.split('.') module = ".".join(parts[:-1]) mod = __import__(module, fromlist=parts[-1]) named_obj = getattr(mod, parts[-1]) return named_obj
bigcode/self-oss-instruct-sc2-concepts
def get_formatted_emg(emg_row): """ :param emg_row: dict [str] one row that represent data from Electromyograph sensor example: ['2018-07-04T17:39:53.743240', 'emg', '-1', '-6', '-9', '-9', '1', '1', '-1', '-2', '2018-07-04T17:39:53.742082'] :return: formatted emg row example: ['2018-07-04T17:39:53.743240', '-1', '-6', '-9', '-9', '1', '1', '-1', '-2'] """ new_emg_row = emg_row.copy() new_emg_row.pop(1) # remove 'emg' word new_emg_row.pop(9) # remove last timestamp return new_emg_row
bigcode/self-oss-instruct-sc2-concepts
from typing import OrderedDict def get_companies(dbconnection, args): """ Return an ordered dictionary of information from the company table. The key is the db key """ print('Companies') cursor = dbconnection.cursor() cursor.execute('SELECT * FROM Companies') row = cursor.fetchone() company_dict = OrderedDict() row = cursor.fetchone() while row is not None: company_dict[row[0]] = row[1] row = cursor.fetchone() # cursor.close() return company_dict
bigcode/self-oss-instruct-sc2-concepts
def code() -> str: """ Example G-code module, a drawing of a crocodile. Please simulate first, before milling. """ return """ G91 G17 G3 X20 Y0 I10 J0 G0 X40 Y0 G3 X6 Y0 I3 J0 G0 X0 Y3 G3 X-3 Y3 I-3 J0 G0 X-40 Y0 G2 X0 Y6 I0 J3 G0 X40 Y0 G3 X0 Y6 I0 J3 G0 X-40 Y5 G0 X-10 Y10 """
bigcode/self-oss-instruct-sc2-concepts
import re def remove_none_alphanumeric(string): """ remove non-alphanumeric characters """ pattern = re.compile("[\W_]+", re.UNICODE) return pattern.sub("", string)
bigcode/self-oss-instruct-sc2-concepts
def map_values(map_fn, dictionary): """Returns a dictionary whose values have been transformed by map_fn. """ return {k: map_fn(v) for k, v in dictionary.items()}
bigcode/self-oss-instruct-sc2-concepts
def create_poll(poll_options: list) -> dict: """ Creates a poll of a list of options :param poll_options: :return: """ poll_opts_map = {} for opt in poll_options: poll_opts_map.update({opt.lstrip(" ").rstrip(" "): 0}) return poll_opts_map
bigcode/self-oss-instruct-sc2-concepts
import re def loads(hesciiStr, prefix='x'): """ Takes a hescii-encoded string and returns the utf-8 byte string. Args: hesciiStr: a hescii-encoded string prefix: string used to prefix all encoded hex values. Default 'x' Returns: A utf-8 byte string """ def repl(match): s = match.group() return s[len(prefix):].decode('hex') pattern = prefix + r'([0123456789abcdefABCDEF][0123456789abcdefABCDEF])+' return re.sub(pattern, repl, hesciiStr)
bigcode/self-oss-instruct-sc2-concepts
def _make_package(x): """Get the package name and drop the last '.' """ package = '' for p in x: package += p[0] + p[1] if package and package[-1] == '.': package = package[:-1] return package
bigcode/self-oss-instruct-sc2-concepts
def _conv(n): """Convert a node name to a valid dot name, which can't contain the leading space""" if n.startswith(' '): return 't_' + n[1:] else: return 'n_' + n
bigcode/self-oss-instruct-sc2-concepts
def val_or_none_key(getter_fcn): """Wraps getter_fcn, returning a key that is a tuple of (0 or 1, val) where val=getter_fcn(obj), and the int is 0 if val is None.""" def result_key_fcn(obj): val = getter_fcn(obj) n = 0 if val is None else 1 return n, val return result_key_fcn
bigcode/self-oss-instruct-sc2-concepts
def strip_diagnostics(tracks): """Remove diagnostic information from a tracks DataFrame. This returns a copy of the DataFrame. Columns with names that start with "diag_" are excluded.""" base_cols = [cn for cn in tracks.columns if not cn.startswith('diag_')] return tracks.reindex(columns=base_cols)
bigcode/self-oss-instruct-sc2-concepts
def make_token(name, value=''): """Make a token with name and optional value.""" return {'name': name, 'value': value}
bigcode/self-oss-instruct-sc2-concepts
def convert_frac(ratio): """ Converts ratio strings into float, e.g. 1.0/2.0 -> 0.5 """ try: return float(ratio) except ValueError: num, denom = ratio.split('/') return float(num) / float(denom)
bigcode/self-oss-instruct-sc2-concepts
def k8s_url(namespace, kind, name=None): """ Construct URL referring to a set of kubernetes resources Only supports the subset of URLs that we need to generate for use in kubespawner. This currently covers: - All resources of a specific kind in a namespace - A resource with a specific name of a specific kind """ url_parts = [ 'api', 'v1', 'namespaces', namespace, kind ] if name is not None: url_parts.append(name) return '/' + '/'.join(url_parts)
bigcode/self-oss-instruct-sc2-concepts
def _pad_vocabulary(vocab, math): """ Pads vocabulary to a multiple of 'pad' tokens. Args: vocab (list): list with vocabulary math (str): Math precision. either `fp_16`, `manual_fp16` or `fp32` Returns: list: padded vocabulary """ if math == "fp16": pad = 8 elif math == "fp32": pad = 1 else: raise NotImplementedError() vocab_size = len(vocab) padded_vocab_size = (vocab_size + pad - 1) // pad * pad for i in range(0, padded_vocab_size - vocab_size): token = f"madeupword{i:04d}" vocab.append(token) assert len(vocab) % pad == 0 return vocab
bigcode/self-oss-instruct-sc2-concepts
def convert_r_groups_to_tuples(r_groups): """ Converts a list of R-Group model objects to R-Group tuples""" return [r_group.convert_to_tuple() for r_group in r_groups]
bigcode/self-oss-instruct-sc2-concepts
import re def domain(url): """Get domain from url. Domain must start with ``http://``, ``https://`` or ``/``. Parameters ---------- url: str URL to parse to extract the domain. Raises ------ ValueError If the URL pattern is invalid. Examples -------- >>> domain('https://example.com/test/page.html') 'https://example.com/' >>> domain('http://example.com/test/page.html') 'http://example.com/' >>> domain('/example.com/test/page.html') '/example.com/' """ pattern = re.compile(r'^(https?:/)?(/[a-z0-9][a-z0-9-_.]*/)') res = pattern.match(url) if res: return res.group(2) if res.group(1) is None else ''.join(res.groups()) raise ValueError(f'Invalid URL pattern: `{url}`.')
bigcode/self-oss-instruct-sc2-concepts
def scale(x, s): """Scales x by scaling factor s. Parameters ---------- x : float s : float Returns ------- x : float """ x *= s return x
bigcode/self-oss-instruct-sc2-concepts
def pop_sort(pop): """ This function sorts the population based on their fitnesses, using selection sort. pop: The population that are sorted based on their fitnesses. """ for i in range(len(pop)): min_index = i for j in range(i+1, len(pop)): if pop[min_index].fitness > pop[j].fitness: min_index = j pop[i], pop[min_index] = pop[min_index], pop[i] return pop
bigcode/self-oss-instruct-sc2-concepts
def subverParseClient(s): """return the client name given a subversion string""" return s[1:].split(":")[0]
bigcode/self-oss-instruct-sc2-concepts
import requests def get_all_service_groups(asa): """ This function retrieves all service groups from ASA :param asa: ASA device which to retrieve the objects from ASA :return: Returns list of service objects. """ url = asa.url() + "/api/objects/networkservicegroups" headers = { 'Content-Type': 'application/json', 'User-agent': 'REST API Agent', 'X-Auth-Token': asa.token } response = requests.request("GET", url, headers=headers, verify=False).json()['items'] return response
bigcode/self-oss-instruct-sc2-concepts