seed
stringlengths
1
14k
source
stringclasses
2 values
import re def get_read_group(list_of_names): """Extracts the correct group name for the group containing the read_id""" for name in list_of_names: if re.search(r'Read_\d+$', name): return name
bigcode/self-oss-instruct-sc2-concepts
def reloc_exit_patch(patch_data, relocs, start_address): """Relocate a piece of 6502 code to a given starting address.""" patch_data = bytearray(patch_data) for i in relocs: address = patch_data[i] + (patch_data[i + 1] << 8) + start_address patch_data[i] = address & 0xFF patch_data[i + 1] = address >> 8 return patch_data
bigcode/self-oss-instruct-sc2-concepts
def fingerprints_as_string(fingerprints): """ Method to formatting fingerprints list to human readable string value :param fingerprints: fingerprints set as list :type fingerprints: list :return: fingerprints set as string :rtype: str """ all_fingerprints_string = [] # loop all fingerprints values in list for fingerprint in fingerprints: fingerprint_string = '{}'.format(fingerprint['Type']) if 'Radius' in fingerprint.keys(): fingerprint_string += ' {} radius'.format(fingerprint['Radius']) if 'Size' in fingerprint.keys(): fingerprint_string += ' {} size'.format(fingerprint['Size']) all_fingerprints_string.append(fingerprint_string) return ', '.join(all_fingerprints_string)
bigcode/self-oss-instruct-sc2-concepts
import math def haversine(lat1,lon1,lat2,lon2,radius=6371000.0): """ Haversine function, used to calculate the distance between two points on the surface of a sphere. Good approximation for distances between two points on the surface of the Earth if the correct local curvature is used and the points are relatively close to one another. Parameters ---------- lat1 : array_like Latitude of first point in radians lon1 : array_like Longitude of first point in radians lat2: array_like Latitude of second point in radians lon2 : array_like Longitude of second point in radians radius : float Local radius of curvature in meters Returns ------- distance : float Distance between the two locations """ distance = 2*radius*math.asin(math.sqrt(math.sin((lat2-lat1)/2)**2+math.cos(lat1)*math.cos(lat2)*math.sin((lon2-lon1)/2)**2)) return distance
bigcode/self-oss-instruct-sc2-concepts
def no_blending(rgba, norm_intensities): """Just returns the intensities. Use in hill_shade to just view the calculated intensities""" assert norm_intensities.ndim == 2, "norm_intensities must be 2 dimensional" return norm_intensities
bigcode/self-oss-instruct-sc2-concepts
def feature_fixture(request): """Return an entity wrapper from given fixture name.""" return request.getfixturevalue(request.param)
bigcode/self-oss-instruct-sc2-concepts
def _filter_cols(dataset, seed): """Mapping function. Filter columns for batch. Args: dataset: tf.data.Dataset with several columns. seed: int Returns: dataset: tf.data.Dataset with two columns (X, Y). """ col_y = f'image/sim_{seed}_y/value' return dataset['image/encoded'], dataset[col_y]
bigcode/self-oss-instruct-sc2-concepts
def find_sum(inputs, target): """ given a list of input integers, find the (first) two numbers which sum to the given target, and return them as a 2-tuple. Return None if the sum could not be made. """ for i in inputs: if i < target // 2 + 1: if target - i in inputs: return (i, target - i)
bigcode/self-oss-instruct-sc2-concepts
import inspect def is_static_method(klass, name: str) -> bool: """ Check if the attribute of the passed `klass` is a `@staticmethod`. Arguments: klass: Class object or instance to check for the attribute on. name: Name of the attribute to check for. Returns: `True` if the method is a staticmethod, else `False`. """ if not inspect.isclass(klass): klass = klass.__class__ meth = getattr(klass, name) if inspect.isfunction(meth): if getattr(meth, "__self__", None): return False for cls in klass.__mro__: descriptor = vars(cls).get(name) if descriptor is not None: return isinstance(descriptor, staticmethod) return False
bigcode/self-oss-instruct-sc2-concepts
from typing import Union def astuple(i, argname: Union[str, None]) -> tuple: """ Converts iterables (except strings) into a tuple. :param argname: If string, it's used in the exception raised when `i` not an iterable. If `None`, wraps non-iterables in a single-item tuple, and no exception is ever raised. """ if not i: return () if isinstance(i, str): i = (i,) else: try: i = tuple(i) except Exception as ex: if argname is None: return (i,) raise ValueError( f"Cannot tuple-ize {argname}({i!r}) due to: {ex}" ) from None return i
bigcode/self-oss-instruct-sc2-concepts
def ms_to_hours(ms): """Convert milliseconds to hours""" return round(ms / 60.0 / 60.0 / 1000.0, 2)
bigcode/self-oss-instruct-sc2-concepts
def org_add_payload(org_default_payload): """Provide an organization payload for adding a member.""" add_payload = org_default_payload add_payload["action"] = "member_added" return add_payload
bigcode/self-oss-instruct-sc2-concepts
def cchunkify(lines, lang='', limit=2000): """ Creates code block chunks from the given lines. Parameters ---------- lines : `list` of `str` Lines of text to be chunkified. lang : `str`, Optional Language prefix of the code-block. limit : `int`, Optional The maximal length of a generated chunk. Returns ------- result : `list` of `str` Raises ------ ValueError` If limit is less than `500`. """ if limit < 500: raise ValueError(f'Minimal limit should be at least 500, got {limit!r}.') starter = f'```{lang}' limit = limit-len(starter)-5 result = [] chunk_length = 0 chunk = [starter] for line in lines: while True: ln = len(line)+1 if chunk_length+ln > limit: position = limit-chunk_length if position < 250: chunk.append('```') result.append('\n'.join(chunk)) chunk.clear() chunk.append(starter) chunk.append(line) chunk_length = ln break position = line.rfind(' ', position-250, position-3) if position == -1: position = limit-chunk_length-3 post_part = line[position:] else: post_part = line[position+1:] pre_part = line[:position]+'...' chunk.append(pre_part) chunk.append('```') result.append('\n'.join(chunk)) chunk.clear() chunk.append(starter) if len(post_part) > limit: line = post_part chunk_length = 0 continue chunk.append(post_part) chunk_length = len(post_part)+1 break chunk.append(line) chunk_length += ln break if len(chunk)>1: chunk.append('```') result.append('\n'.join(chunk)) return result
bigcode/self-oss-instruct-sc2-concepts
def exist_unchecked_leafs(G): """Helper function for hierachical hill climbing. The function determines whether any of the leaf nodes of the graph have the attribute checked set to False. It returns number of leafs for which this is the case. Args: G (nx.DirectedGraph): The directed graph to be checked. Returns: int: Number of unchecked leafs. """ # set counter and determine leaves count_unchecked = 0 leafs = [node for node in G.nodes if G.in_degree(node) == 0] # check all leaves and count the unchecked ones for leaf in leafs: if G.nodes[leaf]["checked"] == False: count_unchecked += 1 # return number of unchecked leafs return count_unchecked
bigcode/self-oss-instruct-sc2-concepts
def num_edges(graph): """Returns the number of edges in a ProgramGraph.""" return len(graph.edges)
bigcode/self-oss-instruct-sc2-concepts
import tempfile def simple_net_file(num_output): """Make a simple net prototxt, based on test_net.cpp, returning the name of the (temporary) file.""" f = tempfile.NamedTemporaryFile(mode='w+', delete=False) f.write("""name: 'testnet' force_backward: true layer { type: 'DummyData' name: 'data' top: 'data' top: 'label' dummy_data_param { num: 5 channels: 2 height: 3 width: 4 num: 5 channels: 1 height: 1 width: 1 data_filler { type: 'gaussian' std: 1 } data_filler { type: 'constant' } } } layer { type: 'Convolution' name: 'conv' bottom: 'data' top: 'conv' convolution_param { num_output: 11 kernel_size: 2 pad: 3 weight_filler { type: 'gaussian' std: 1 } bias_filler { type: 'constant' value: 2 } } param { decay_mult: 1 } param { decay_mult: 0 } } layer { type: 'InnerProduct' name: 'ip' bottom: 'conv' top: 'ip' inner_product_param { num_output: """ + str(num_output) + """ weight_filler { type: 'gaussian' std: 2.5 } bias_filler { type: 'constant' value: -3 } } } layer { type: 'SoftmaxWithLoss' name: 'loss' bottom: 'ip' bottom: 'label' top: 'loss' }""") f.close() return f.name
bigcode/self-oss-instruct-sc2-concepts
import re def get_fortfloat(key, txt, be_case_sensitive=True): """ Matches a fortran compatible specification of a float behind a defined key in a string. :param key: The key to look for :param txt: The string where to search for the key :param be_case_sensitive: An optional boolean whether to search case-sensitive, defaults to ``True`` If abc is a key, and f is a float, number, than this regex will match t and return f in the following cases: * charsbefore, abc = f, charsafter * charsbefore abc = f charsafter * charsbefore, abc = f charsafter and vice-versa. If no float is matched, returns None Exampes of matchable floats are: * 0.1d2 * 0.D-3 * .2e1 * -0.23 * 23. * 232 """ pattern = """ [\n,] # key - value pair can be prepended by comma or start [ \t]* # in a new line and some optional white space {} # the key goes here [ \t]* # Optional white space between key and equal sign = # Equals, you can put [=:,] if you want more specifiers [ \t]* # optional white space between specifier and float (?P<float> # Universal float pattern ( \d*[\.]\d+ | \d+[\.]?\d* ) ([ E | D | e | d ] [+|-]? \d+)? ) [ \t]*[,\n,#] # Can be followed by comma, end of line, or a comment """.format(key) REKEYS = re.X | re.M if be_case_sensitive else re.X | re.M | re.I match = re.search( pattern, txt, REKEYS) if not match: return None else: return float(match.group('float').replace('d', 'e').replace('D', 'e'))
bigcode/self-oss-instruct-sc2-concepts
def option_namespace(name): """ArgumentParser options namespace (prefix of all options).""" return name + "-"
bigcode/self-oss-instruct-sc2-concepts
def is_verb(tok): """ Is this token a verb """ return tok.tag_.startswith('V')
bigcode/self-oss-instruct-sc2-concepts
def get_fuel_required(module_mass: float) -> float: """Get the fuel required for a module. Args: module_mass: module mass Returns: fueld required to take off """ return int(module_mass / 3.0) - 2.0
bigcode/self-oss-instruct-sc2-concepts
def uniq(xs): """Remove duplicates in given list with its order kept. >>> uniq([]) [] >>> uniq([1, 4, 5, 1, 2, 3, 5, 10]) [1, 4, 5, 2, 3, 10] """ acc = xs[:1] for x in xs[1:]: if x not in acc: acc += [x] return acc
bigcode/self-oss-instruct-sc2-concepts
def lang(name, comment_symbol, multistart=None, multiend=None): """ Generate a language entry dictionary, given a name and comment symbol and optional start/end strings for multiline comments. """ result = { "name": name, "comment_symbol": comment_symbol } if multistart is not None and multiend is not None: result.update(multistart=multistart, multiend=multiend) return result
bigcode/self-oss-instruct-sc2-concepts
def listify(item) -> list: """ If given a non-list, encapsulate in a single-element list. """ return item if isinstance(item, list) else [item]
bigcode/self-oss-instruct-sc2-concepts
import copy def copy_original_exchange_id(data): """Copy each exchange id to the field ``original id`` for use in writing ecospold2 files later.""" for ds in data: for exc in ds['exchanges']: exc['original id'] = copy.copy(exc['id']) return data
bigcode/self-oss-instruct-sc2-concepts
def _strip_wmic_response(wmic_resp): """Strip and remove header row (if attribute) or call log (if method).""" return [line.strip() for line in wmic_resp.split('\n') if line.strip() != ''][1:]
bigcode/self-oss-instruct-sc2-concepts
import sympy def render(expr, lhs=""): """ Puts $ at the beginning and end of a latex expression. lhs : if we want to render something like: $x = 3 + 5$, set the left hand side here """ left = "$$" if lhs: left = "$$%s =" % lhs return ''.join([left, sympy.latex(expr), "$$"])
bigcode/self-oss-instruct-sc2-concepts
def compress_name(champion_name): """To ensure champion names can be searched for and compared, the names need to be reduced. The process is to remove any characters not in the alphabet (apostrophe, space, etc) and then convert everything to lowercase. Note that reversing this is non-trivial, there are inconsistencies in the naming scheme used. Examples: Jhin -> jhin GALIO -> galio Aurelion Sol -> aurelionsol Dr. Mundo -> drmundo kha'zix -> khazix """ compressed_name = "".join(c for c in champion_name if c.isalpha()) return compressed_name.lower()
bigcode/self-oss-instruct-sc2-concepts
def createDatas(*models): """Call createData() on each Model or GeometryModel in input and return the results in a tuple. If one of the models is None, the corresponding data object in the result is also None. """ return tuple([None if model is None else model.createData() for model in models])
bigcode/self-oss-instruct-sc2-concepts
def _create_source_file(source, tmp_path): """Create a file with the source code.""" directory = tmp_path / "models" directory.mkdir() source_file = directory / "models.py" source_file.write_text(source) return source_file
bigcode/self-oss-instruct-sc2-concepts
def __top_frond_left(dfs_data): """Returns the frond at the top of the LF stack.""" return dfs_data['LF'][-1]
bigcode/self-oss-instruct-sc2-concepts
def link_cmd(path, link): """Returns link creation command.""" return ['ln', '-sfn', path, link]
bigcode/self-oss-instruct-sc2-concepts
import ntpath import posixpath def as_posixpath(location): """ Return a posix-like path using posix path separators (slash or "/") for a `location` path. This converts Windows paths to look like posix paths that Python accepts gracefully on Windows for path handling. """ return location.replace(ntpath.sep, posixpath.sep)
bigcode/self-oss-instruct-sc2-concepts
def flag_greens_on_set(func): """Decorator to signal Green's functions are now out of date.""" def setter_wrapper(obj, value): retval = func(obj, value) obj._uptodate = False return retval return setter_wrapper
bigcode/self-oss-instruct-sc2-concepts
def _auth_header(module): """Generate an authentication header from a token.""" token = module.params.get('auth')['access_token'] auth_header = { 'Authorization': 'Bearer {}'.format(token) } return auth_header
bigcode/self-oss-instruct-sc2-concepts
import uuid def _replace_substrings(code, first_char, last_char): """Replace the substrings between first_char and last_char with a unique id. Return the replaced string and a list of replacement tuples: (unique_id, original_substring) """ substrings = [] level = 0 start = -1 for i in range(len(code)): if code[i] == first_char: level += 1 if level == 1: start = i if code[i] == last_char: level -= 1 if level == 0: substrings.append((start, i + 1)) code_ = code replacements = [] for substr_index in substrings: unique_id = '{}"{}"{}'.format(first_char, str(uuid.uuid4()), last_char) substring = code[substr_index[0]:substr_index[1]] code_ = code_.replace(substring, unique_id) replacements.append((unique_id, substring)) return code_, replacements
bigcode/self-oss-instruct-sc2-concepts
import re def get_set(srr_rar_block): """ An SRR file can contain re-creation data of different RAR sets. This function tries to pick the basename of such a set. """ n = srr_rar_block.file_name[:-4] match = re.match("(.*)\.part\d*$", n, re.I) if match: return match.group(1) else: return n
bigcode/self-oss-instruct-sc2-concepts
def intersect2D(segment, point): """ Calculates if a ray of x->inf from "point" intersects with the segment segment = [(x1, y1), (x2, y2)] """ x, y = point #print(segment) x1, y1 = segment[0] x2, y2 = segment[1] if (y1<=y and y<y2) or (y2<=y and y<y1): x3 = x2*(y1-y)/(y1-y2) + x1*(y-y2)/(y1-y2) if x3 >= x: return True else: return False else: return False
bigcode/self-oss-instruct-sc2-concepts
def _get_reserved_field(field_id, reserved_fields): """Returns the desired reserved field. Args: field_id: str. The id of the field to retrieve. reserved_fields: list(fields). The reserved fields to search. Returns: The reserved field with the given `field_id`. Raises: ValueError: `field_id` is not a known reserved field. """ matching_fields = [field for field in reserved_fields if field.id == field_id] if not matching_fields: raise ValueError('No reserved field with id `{}`'.format(field_id)) return matching_fields[0]
bigcode/self-oss-instruct-sc2-concepts
import math def sigmoid(x): """Sigmoid function f(x)=1/(1+e^(-x)) Args: x: float, input of sigmoid function Returns: y: float, function value """ # for x which is to large, the sigmoid returns 1 if x > 100: return 1.0 # for x which is very small, the sigmoid returns 0 if x < -100: return 1e-6 return 1.0 / (1.0 + math.exp(-x))
bigcode/self-oss-instruct-sc2-concepts
def connect_the_dots(pts): """given a list of tag pts, convert the point observations to poly-lines. If there is only one pt, return None, otherwise connect the dots by copying the points and offseting by 1, producing N-1 line segments. Arguments: - `pts`: a list of point observations of the form [[lat1,lon1],[lat2, lon2], ... ] """ if len(pts) > 1: # pts = [(x[1], x[0]) for x in pts] pts = [x[1] for x in pts] A = pts[:-1] B = pts[1:] coords = list(zip(A, B)) return coords else: return None
bigcode/self-oss-instruct-sc2-concepts
import base64 def encode_photo(filepath): """ encode photo to text :param filepath: file encoded :return: encoded text """ with open(filepath, mode="rb") as f: return base64.encodebytes(f.read()).decode("utf-8")
bigcode/self-oss-instruct-sc2-concepts
def rotate_list(l): """ Rotate a list of lists :param l: list of lists to rotate :return: """ return list(map(list, zip(*l)))
bigcode/self-oss-instruct-sc2-concepts
def segwit_scriptpubkey(witver, witprog): """Create a segwit locking script for a given witness program (P2WPKH and P2WSH).""" return bytes([witver + 0x50 if witver else 0, len(witprog)] + witprog)
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from typing import List def parse_setup(options: Union[List, str]) -> str: """Convert potentially a list of commands into a single string. This creates a single string with newlines between each element of the list so that they will all run after each other in a bash script. """ if isinstance(options, str): return options return "\n".join(options)
bigcode/self-oss-instruct-sc2-concepts
import unicodedata def is_printable(char: str) -> bool: """ Determines if a chode point is printable/visible when printed. Args: char (str): Input code point. Returns: True if printable, False otherwise. """ letters = ('LC', 'Ll', 'Lm', 'Lo', 'Lt', 'Lu') numbers = ('Nd', 'Nl', 'No') punctuation = ('Pc', 'Pd', 'Pe', 'Pf', 'Pi', 'Po', 'Ps') symbol = ('Sc', 'Sk', 'Sm', 'So') printable = letters + numbers + punctuation + symbol return unicodedata.category(char) in printable
bigcode/self-oss-instruct-sc2-concepts
def convert_secret_hex_to_bytes(secret): """ Convert a string secret to bytes. """ return int(secret, 16).to_bytes(32, byteorder="big")
bigcode/self-oss-instruct-sc2-concepts
from typing import Counter def count_items(column_list): """ Function count the users. Args: column_list: The data list that is doing to be iterable. Returns: A list with the item types and another list with the count values. """ item_types = [] count_items = [] new_count_list = [] counting_list = Counter(column_list) for i in counting_list: new_count_list.append([i, counting_list[i]]) item_types, count_items = zip(*new_count_list) return item_types, count_items
bigcode/self-oss-instruct-sc2-concepts
def get_brief_description(description): """Get brief description from paragraphs of command description.""" if description: return description[0] else: return 'No description available.'
bigcode/self-oss-instruct-sc2-concepts
def needs_reversal(chain): """ Determine if the chain needs to be reversed. This is to set the chains such that they are in a canonical ordering Parameters ---------- chain : tuple A tuple of elements to treat as a chain Returns ------- needs_flip : bool Whether or not the chain needs to be reversed """ x = len(chain) if x == 1: first = 0 second = 0 else: q, r = divmod(x, 2) first = q - 1 second = q + r while first >= 0 and second < len(chain): if chain[first] > chain[second]: # Case where order reversal is needed return True elif chain[first] == chain[second]: # Indeterminate case first -= 1 second += 1 else: # Case already in the correct order return False return False
bigcode/self-oss-instruct-sc2-concepts
def bulleted_list(items, max_count=None, indent=2): """Format a bulleted list of values.""" if max_count is not None and len(items) > max_count: item_list = list(items) items = item_list[: max_count - 1] items.append("...") items.append(item_list[-1]) line_template = (" " * indent) + "- {}" return "\n".join(map(line_template.format, items))
bigcode/self-oss-instruct-sc2-concepts
def _maybe_list_replace(lst, sublist, replacement): """Replace first occurrence of sublist in lst with replacement.""" new_list = [] idx = 0 replaced = False while idx < len(lst): if not replaced and lst[idx:idx + len(sublist)] == sublist: new_list.append(replacement) replaced = True idx += len(sublist) else: new_list.append(lst[idx]) idx += 1 if not replaced: return None return new_list
bigcode/self-oss-instruct-sc2-concepts
def PrintHtml(log): """Prints a log as HTML. Args: log: a Log namedtuple. """ def Tag(tag, cls, value): return '<%s class="%s">%s</%s>' % (tag, cls, value, tag) classes = ['filename', 'date', 'log'] line = ' '.join([Tag('span', cls, value) for cls, value in zip(classes, log)]) print(Tag('div', 'line', line))
bigcode/self-oss-instruct-sc2-concepts
def get_max_offset_supported(atten): """Get maximum supported offset for given attenuation""" if atten >= 0.1: return (-8, +8) else: return (-2, +2)
bigcode/self-oss-instruct-sc2-concepts
def log_likelihood_from(*, chi_squared: float, noise_normalization: float) -> float: """ Returns the log likelihood of each model data point's fit to the dataset, where: Log Likelihood = -0.5*[Chi_Squared_Term + Noise_Term] (see functions above for these definitions) Parameters ---------- chi_squared The chi-squared term for the model-simulator fit to the dataset. noise_normalization The normalization noise_map-term for the dataset's noise-map. """ return float(-0.5 * (chi_squared + noise_normalization))
bigcode/self-oss-instruct-sc2-concepts
def rename_fields(columns, data): """Replace any column names using a dict of 'old column name': 'new column name' """ return data.rename(columns=columns)
bigcode/self-oss-instruct-sc2-concepts
def _user_is_admin_for(user, org): """ Whether this user is an administrator for the given org """ return org.administrators.filter(pk=user.pk).exists()
bigcode/self-oss-instruct-sc2-concepts
def drive_list(service, parent_id): """ List resources in parent_id """ query = "trashed=false and '%s' in parents" % parent_id response = service.files().list(q=query).execute() if response and 'items' in response and response['items']: return response['items'] return []
bigcode/self-oss-instruct-sc2-concepts
def _new_or_old_field_property(prop, new_field, old_field, old_priority): """ Get the given property on the old field or the new field, with priority given to a field of the user's choosing. Arguments: prop -- a string of the requested property name old_field -- the old field as a Field instance new_field -- the new field as a Field instance old_priority -- a boolean that, if True, gives priority to the old field, and, if False, gives priority to the new field Returns: the requested property on the new field or old field """ new_prop = getattr(new_field, prop) old_prop = getattr(old_field, prop) if old_priority: return old_prop or new_prop else: return new_prop or old_prop
bigcode/self-oss-instruct-sc2-concepts
import re def sanitize( word: str, chars=['.', ",", "-", "/", "#"], check_mongoengine=True) -> str: """Sanitize a word by removing unwanted characters and lowercase it. Args: word (str): the word to sanitize chars (list): a list of characters to remove check_mongoengine (bool): true to add '_' after a mongoengine reserved word Returns: str: the sanitized word """ # remove unwanted characters from word by putting spaces pattern = "".join(chars) tmp = re.sub(r'[%s]' % (pattern), ' ', word) # remove spaces from column name and lowercase all sanitized = re.sub(r"\s+", "_", tmp).lower() if check_mongoengine: if sanitized in ['size', 'type']: sanitized += "_" # remove starting sanitized char (can't be used with namedtuple) if sanitized.startswith("_"): sanitized = sanitized[1:] return sanitized
bigcode/self-oss-instruct-sc2-concepts
def add_space_to_parentheses(string: str): """ :param string: Must be a string :return: string with space before '(' and after ')' """ return string.replace('(', ' (').replace(')', ') ')
bigcode/self-oss-instruct-sc2-concepts
def cast_type(cls, val, default): """Convert val to cls or return default.""" try: val = cls(val) except Exception: val = default return val
bigcode/self-oss-instruct-sc2-concepts
def is_insertion(row): """Encodes if the indel is an insertion or deletion. Args: row (pandas.Series): reference seq (str) at index 'ref' Returns: is_insertion (int): 0 if insertion, 1 if deletion """ is_insertion = 0 if row["ref"] == "-": is_insertion = 1 return is_insertion
bigcode/self-oss-instruct-sc2-concepts
import textwrap def unindent(text: str) -> str: """Remove indentation from text""" return textwrap.dedent(text).strip()
bigcode/self-oss-instruct-sc2-concepts
def get_error_res(eval_id): """Creates a default error response based on the policy_evaluation_result structure Parameters: eval_id (String): Unique identifier for evaluation policy Returns: PolicyEvalResultStructure object: with the error state with the given id """ return { "id": eval_id, "result": { "message": f"No evaluation with the id {eval_id} ongoing", "status": "ERROR", "confidenceLevel": "0", }, }
bigcode/self-oss-instruct-sc2-concepts
import string import random def gen_random_string(n=24): """Returns a random n-length string, suitable for a password or random secret""" # RFC 3986 section 2.3. unreserved characters (no special escapes required) char_set = string.ascii_letters + string.digits + "-._~" return "".join(random.choices(char_set, k=n))
bigcode/self-oss-instruct-sc2-concepts
def query_adapter(interface, request, context=None, view=None, name=''): """Registry adapter lookup helper If view is provided, this function is trying to find a multi-adapter to given interface for request, context and view; if not found, the lookup is done for request and context, and finally only for context. :param interface: adapter provided interface :param request: current request :param context: current context; if context is None, request context is used :param view: current view :param name: adapter name """ registry = request.registry if context is None: context = request.context adapter = registry.queryMultiAdapter((context, request, view), interface, name=name) \ if view is not None else None if adapter is None: adapter = registry.queryMultiAdapter((context, request), interface, name=name) if adapter is None: adapter = registry.queryAdapter(context, interface, name=name) return adapter
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional def _rename_list( list1: list[str], method: str, list2: Optional[list[str]] = None ) -> list[str]: """Renames multiple list items following different methods. Method can be "consecutive" to rename identical consecutive items with increasing number or "fuse" to fuse with the second list (list2) Args: list1: List of strings to be renamed method: Type of renaming method. Can be "consecutive" to rename consecutive identical items as progressive values ("tree", "tree" will become "tree_0", "tree_1"); "fuse" to fuse with the values from list2. list2 must be of the same length as list1 while fusing. Returns: list of renamed values """ last = None new_list = [] count = 0 if method == "consecutive": for item in list1: if item == last: count += 1 new_list.append(item + "_" + str(count)) last = item else: new_list.append(item + "_0") count = 0 last = item elif method == "fuse" and list2 is not None: if len(list1) != len(list2): raise ValueError( ("Length of lists not equal:" f" {len(list1)} vs {len(list2)}") ) new_list = [str(i1) + "_" + str(i2) for i1, i2 in zip(list1, list2)] else: raise ValueError("Unrecognized method or list2 unspecified") return new_list
bigcode/self-oss-instruct-sc2-concepts
def ping(request): """ Simple resource to check that server is up. """ return 'pong'
bigcode/self-oss-instruct-sc2-concepts
def null_count(df): """This functions returns the number of null values in a Dataframe""" NullSum = df.isnull().sum().sum() return NullSum
bigcode/self-oss-instruct-sc2-concepts
def type_factor(NT, NP, SC=30.0): """ NT - Number of planet types in area NP - Number of planets in area SC - a number used to scale how bad it is to differ from the optimal number of planet types. Lower number means less bad Returns a number between 0.0 and 1.0 indicating how good the ratio of different planet types is compared to the optimal ratio The optimal is to have as many different planet types as possible """ max_types = 9.0 if NP < max_types: max_types = NP ratio = 0.0 if max_types > 0.0: ratio = NT / max_types diff_from_opt = 1.0 - ratio exponent = -SC * diff_from_opt * diff_from_opt return pow(2.718281828, exponent)
bigcode/self-oss-instruct-sc2-concepts
def compute_long_chain(number): """Compute a long chain Arguments: number {int} -- Requested number for which to compute the cube Returns: int -- Value of the cube/long chain for the given number """ return number * number * number
bigcode/self-oss-instruct-sc2-concepts
def get_markers_to_contigs(marker_sets, contigs): """Get marker to contig mapping :param marker_sets: Marker sets from CheckM :type marker_sets: set :param contigs: Contig to marker mapping :type contigs: dict :return: Marker to contigs list mapping :rtype: dict """ marker2contigs = {} for marker_set in marker_sets: for gene in marker_set: marker2contigs[gene] = [] for contig in contigs: if gene in contigs[contig]: marker2contigs[gene].append(contig) return marker2contigs
bigcode/self-oss-instruct-sc2-concepts
def _IsAnomalyInRef(change_point, ref_change_points): """Checks if anomalies are detected in both ref and non ref build. Args: change_point: A find_change_points.ChangePoint object to check. ref_change_points: List of find_change_points.ChangePoint objects found for a ref build series. Returns: True if there is a match found among the ref build series change points. """ for ref_change_point in ref_change_points: if change_point.x_value == ref_change_point.x_value: return True return False
bigcode/self-oss-instruct-sc2-concepts
def _sum(op1, op2): """Sum of two operators, allowing for one of them to be None.""" if op1 is None: return op2 elif op2 is None: return op1 else: return op1 + op2
bigcode/self-oss-instruct-sc2-concepts
def eyr_valid(passport): """ Check that eyr is valid eyr (Expiration Year) - four digits; at least 2020 and at most 2030. :param passport: passport :return: boolean """ return len(passport['eyr']) == 4 and 2020 <= int(passport['eyr']) <= 2030
bigcode/self-oss-instruct-sc2-concepts
def ParseWorkflow(args): """Get and validate workflow from the args.""" return args.CONCEPTS.workflow.Parse()
bigcode/self-oss-instruct-sc2-concepts
def file_to_ints(input_file): """ Input: A file containing one number per line Output: An int iterable Blank lines and lines starting with '#' are ignored """ ints = [] with open(input_file) as f: for line in f.readlines(): line = line.strip() if line and not line.startswith('#'): ints.append(int(line)) return ints
bigcode/self-oss-instruct-sc2-concepts
def feature_to_tpm_dict(feature_to_read_count, feature_to_feature_length): """Calculate TPM values for feature feature_to_read_count: dictionary linking features to read counts (float) feature_to_feature_length: dictionary linking features to feature lengths (float) Return value: dictionary linking feature ID to TPM value """ total_rpk = 0.0 feature_to_rpk = {} feature_to_tpm = {} # Get read per kilobase counts for each feature for feature in feature_to_read_count: try: rpk = feature_to_read_count[feature] / feature_to_feature_length[feature] except KeyError: continue feature_to_rpk[feature] = rpk total_rpk += rpk # Calculate scaling factor scaling = total_rpk / 1000000.0 # Calculate TPM values for feature in feature_to_rpk: tpm = feature_to_rpk[feature] / scaling feature_to_tpm[feature] = tpm return feature_to_tpm
bigcode/self-oss-instruct-sc2-concepts
def remove_stopwords(texts, stop_words): """ Parameters: - `texts` a list of documents - `stop_words` a list of words to be removed from each document in `texts` Returns: a list of documents that does not contain any element of `stop_words` """ return [[word for word in doc if word not in stop_words] for doc in texts]
bigcode/self-oss-instruct-sc2-concepts
def get_mapping_pfts(mapping): """Get all PFT names from the mapping.""" pft_names = set() for value in mapping.values(): pft_names.update(value["pfts"]) return sorted(pft_names)
bigcode/self-oss-instruct-sc2-concepts
def encode(token): """Escape special characters in a token for path representation. :param str token: The token to encode :return: The encoded string :rtype: str """ return token.replace('\\', '\\\\').replace('/', '\\/')
bigcode/self-oss-instruct-sc2-concepts
def build_window_title(paused: bool, current_file) -> str: """ Returns a neatly formatted window title. :param bool paused: whether the VM is currently paused :param current_file: the name of the file to display :return str: a neatly formatted window title """ return f"EightDAD {'(PAUSED)' if paused else '-'} {current_file}"
bigcode/self-oss-instruct-sc2-concepts
def mph_to_kph(mph): """Convert mph to kph.""" return mph * 1.609
bigcode/self-oss-instruct-sc2-concepts
def sort_hand(hand, deck): """Returns a hand of cards sorted in the index order of the given deck""" sorted_hand = [] for i in deck: for card in hand: if i == card: sorted_hand.append(card) return sorted_hand
bigcode/self-oss-instruct-sc2-concepts
def get_read_count_type(line): """ Return the count number and read type from the log line """ data = line.rstrip().split(":") count = data[-1].strip() type = data[-3].lstrip().rstrip() return count, type
bigcode/self-oss-instruct-sc2-concepts
def read_text_file(path_to_file): """ Read a text file and import each line as an item in a list. * path_to_file: the path to a text file. """ with open(path_to_file) as f: lines = [line.rstrip() for line in f] return lines
bigcode/self-oss-instruct-sc2-concepts
import requests def load_text_lines_from_url(url): """Load lines of text from `url`.""" try: response = requests.get(url) response.raise_for_status() content = response.text.split("\n") return [x.strip() for x in content if len(x.strip()) > 0] except requests.RequestException: pass return None
bigcode/self-oss-instruct-sc2-concepts
def x10(S: str, n: int): """change float to int by *10**n Args: S (str): float n (int, optional): n of float(S)*10**n (number of shift). Returns: int: S*10**n """ if "." not in S: return int(S) * 10**n return int("".join([S.replace(".", ""), "0" * (n - S[::-1].find("."))]))
bigcode/self-oss-instruct-sc2-concepts
def inverter_elementos(iteravel): """ Inverte os elementos dentro de um tuplo. :param iteravel: tuplo :return: tuplo Exemplo: >>> tpl = ("a1", "b3") >>> inverter_elementos(tpl) ("1a", "3b") """ res = () for e in iteravel: res += (e[::-1],) return res
bigcode/self-oss-instruct-sc2-concepts
def scrapeints(string): """Extract a series of integers from a string. Slow but robust. readints('[124, 56|abcdsfad4589.2]') will return: [124, 56, 4589, 2] """ # 2012-08-28 16:19 IJMC: Created numbers = [] nchar = len(string) thisnumber = '' for n, char in enumerate(string): try: val = int(char) anumber = True except: anumber = False if anumber: thisnumber = thisnumber + char else: #if (not anumber) or n==(nchar-1): if len(thisnumber)>0: numbers.append(int(thisnumber)) thisnumber = '' return numbers
bigcode/self-oss-instruct-sc2-concepts
def vm_ready_based_on_state(state): """Return True if the state is one where we can communicate with it (scp/ssh, etc.) """ if state in ["started", "powered on", "running", "unpaused"]: return True return False
bigcode/self-oss-instruct-sc2-concepts
def get_utm_zone(lat,lon): """A function to grab the UTM zone number for any lat/lon location """ zone_str = str(int((lon + 180)/6) + 1) if ((lat>=56.) & (lat<64.) & (lon >=3.) & (lon <12.)): zone_str = '32' elif ((lat >= 72.) & (lat <84.)): if ((lon >=0.) & (lon<9.)): zone_str = '31' elif ((lon >=9.) & (lon<21.)): zone_str = '33' elif ((lon >=21.) & (lon<33.)): zone_str = '35' elif ((lon >=33.) & (lon<42.)): zone_str = '37' return zone_str
bigcode/self-oss-instruct-sc2-concepts
def counters(stats): """ Count all_sentences all_questions all_questions_with_ans & all_corrects :param stats: list(quintet) :rtype int, int, int, int :return: all_sentences, all_questions, all_questions_with_ans, all_corrects """ # Initialization of counters. all_sentences = 0 all_questions = 0 all_questions_with_ans = 0 all_corrects = 0 # Parse stats and implement the addings. for sentences_num, questions_num, questions_with_ans, corrects, acc in stats: all_sentences += sentences_num all_questions += questions_num all_questions_with_ans += questions_with_ans all_corrects += corrects return all_sentences, all_questions, all_questions_with_ans, all_corrects
bigcode/self-oss-instruct-sc2-concepts
import torch def define_device(device_name): """ Define the device to use during training and inference. If auto it will detect automatically whether to use cuda or cpu Parameters ---------- device_name : str Either "auto", "cpu" or "cuda" Returns ------- str Either "cpu" or "cuda" """ if device_name == "auto": if torch.cuda.is_available(): return "cuda" else: return "cpu" elif device_name == "cuda" and not torch.cuda.is_available(): return "cpu" else: return device_name
bigcode/self-oss-instruct-sc2-concepts
from collections import Counter def most_common(words, n=10): """ Returnes the most common words in a document Args: words (list): list of words in a document n (int, optional): Top n common words. Defaults to 10. Returns: list: list of Top n common terms """ bow = Counter(words) ncommon = bow.most_common(n) return(ncommon)
bigcode/self-oss-instruct-sc2-concepts
def num_items() -> int: """The number of candidate items to rank""" return 10000
bigcode/self-oss-instruct-sc2-concepts
import json def json_dumps(json_obj, indent=2, sort_keys=True): """Unified (default indent and sort_keys) invocation of json.dumps """ return json.dumps(json_obj, indent=indent, sort_keys=sort_keys)
bigcode/self-oss-instruct-sc2-concepts
def nonSynonCount(t): """ count the number of nonsynon labels in the transcript annotations. """ count = 0 for a in t.annotations: for l in a.labels: if l == 'nonsynon': count += 1 return count
bigcode/self-oss-instruct-sc2-concepts
def _make_socket_path(host: str, display: int, screen: int) -> str: """ Attempt to create a path to a bspwm socket. No attempts are made to ensure its actual existence. The parameters are intentionally identical to the layout of an XDisplay, so you can just unpack one. Parameters: host -- hostname display -- display number screen -- screen number Example: >>> _make_socket_path(*_parse_display(':0')) '/tmp/bspwm_0_0-socket' """ return f'/tmp/bspwm{host}_{display}_{screen}-socket'
bigcode/self-oss-instruct-sc2-concepts
def strip_unsupported_schema(base_data, schema): """ Strip keys/columns if not in SCHEMA """ return [ {key: value for key, value in place.items() if key in schema} for place in base_data ]
bigcode/self-oss-instruct-sc2-concepts