seed
stringlengths
1
14k
source
stringclasses
2 values
def text_to_word_sequence(text, filters='!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n', lower=True, split=" "): """Converts a text to a sequence of words (or tokens). # Arguments text: Input text (string). filters: Sequence of characters to filter out. lower: Whether to convert the input to lowercase. split: Sentence split marker (string). # Returns A list of words (or tokens). """ if lower: text = text.lower() translate_map = str.maketrans(filters, split * len(filters)) seq = text.translate(translate_map).split(split) return [i for i in seq if i]
bigcode/self-oss-instruct-sc2-concepts
def get_grants(df): """Get list of grant numbers from dataframe. Assumptions: Dataframe has column called 'grantNumber' Returns: set: valid grant numbers, e.g. non-empty strings """ print(f"Querying for grant numbers...", end="") grants = set(df.grantNumber.dropna()) print(f"{len(grants)} found\n") return list(sorted(grants))
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional from pathlib import Path def join_paths(path1: Optional[str] = "", path2: Optional[str] = "") -> str: """ Joins path1 and path2, returning a valid object storage path string. Example: "/p1/p2" + "p3" -> "p1/p2/p3" """ path1 = path1 or "" path2 = path2 or "" # combine paths and ensure the resulting path does not start with "/" char and path = f"{path1.rstrip('/')}/{path2}".lstrip("/") if len(path) > 0: # convert to Posix return Path(path).as_posix() return path
bigcode/self-oss-instruct-sc2-concepts
import struct def seq_to_bytes(s): """Convert a sequence of integers to a *bytes* instance. Good for plastering over Python 2 / Python 3 cracks. """ fmt = "{0}B".format(len(s)) return struct.pack(fmt, *s)
bigcode/self-oss-instruct-sc2-concepts
def parse_int_ge0(value): """Returns value converted to an int. Raises a ValueError if value cannot be converted to an int that is greater than or equal to zero. """ value = int(value) if value < 0: msg = ('Invalid value [{0}]: require a whole number greater than or ' 'equal to zero') raise ValueError(msg.format(value)) else: return value
bigcode/self-oss-instruct-sc2-concepts
import string def remove_punct(value): """Converts string by removing punctuation characters.""" value = value.strip() value = value.translate(str.maketrans('', '', string.punctuation)) return value
bigcode/self-oss-instruct-sc2-concepts
import pickle def default_model_read(modelfile): """Default function to read model files, simply used pickle.load""" return pickle.load(open(modelfile, 'rb'))
bigcode/self-oss-instruct-sc2-concepts
def _variant_genotypes(variants, missing_genotypes_default=(-1, -1)): """Returns the genotypes of variants as a list of tuples. Args: variants: iterable[nucleus.protos.Variant]. The variants whose genotypes we want to get. missing_genotypes_default: tuple. If a variant in variants doesn't have genotypes, this value is returned. The default value is (-1, -1), the standard representation for "missing" diploid genotypes. Returns: list[nucleus.protos.Variant] protos in the same order as variants. """ return [ tuple(v.calls[0].genotype) if v.calls else missing_genotypes_default for v in variants ]
bigcode/self-oss-instruct-sc2-concepts
import struct def byte(number): """ Converts a number between 0 and 255 (both inclusive) to a base-256 (byte) representation. Use it as a replacement for ``chr`` where you are expecting a byte because this will work on all versions of Python. Raises :class:``struct.error`` on overflow. :param number: An unsigned integer between 0 and 255 (both inclusive). :returns: A single byte. """ return struct.pack("B", number)
bigcode/self-oss-instruct-sc2-concepts
import random def generate_events(grid_size, event_type, probability, event_max): """ Generate up to 'number' of events at random times throughout the night. Return events as a list of lists containing the event type and time grid index at which the event occurs. Example ------- >>> events = events(120, 'Target of Opportunity', 0.1, 4) >>> print(events) [['Target of Opportunity', 50], ['Target of Opportunity', 20]] Parameters ---------- grid_size : int number of discrete time vales throughout observing window. event_type : str type of event ('Target of Opportunity' or 'Condition change' for sky conditions changes). probability : float probability of an event occurring. event_max : int number of potential events. """ verbose = False nt = grid_size p = probability n = event_max if verbose: print('\nGenerating random events:') print('grid_size', nt) print('type', event_type) print('probability', p) print('number', n) events = [] if p > 0.: # if event have probability greater than zero for i in range(n): random_num = random.random() # 'roll the dice' for ToO (number in range [0,1)) if verbose: print('random_num', random_num) if random_num <= p: # if roll is >= probability, generate event. event_grid_index = random.randint(0, nt - 1) # random time grid index somewhere in the night. events.append([event_type, event_grid_index]) # save event type and time grid index. if verbose: print('added event:', [event_type, event_grid_index]) return events
bigcode/self-oss-instruct-sc2-concepts
def last(inlist): """ Return the last element from a list or tuple, otherwise return untouched. Examples -------- >>> last([1, 0]) 0 >>> last("/path/somewhere") '/path/somewhere' """ if isinstance(inlist, (list, tuple)): return inlist[-1] return inlist
bigcode/self-oss-instruct-sc2-concepts
from typing import Any import pickle def get_papers_pickle(filename: str) -> dict[str, Any]: """retrive papers (dict format) from file in folder data/papers""" with open(f"data/papers/{filename}", 'rb') as papers_file: return pickle.load(papers_file)
bigcode/self-oss-instruct-sc2-concepts
import requests from bs4 import BeautifulSoup def get_article(url): """ Gets article content from URL Input : URL of article Output : Content in BeautifulSoup format """ r = requests.get(url) html_soup = BeautifulSoup(r.content, 'lxml') return html_soup
bigcode/self-oss-instruct-sc2-concepts
def _convert_from_european_format(string): """ Conver the string given in the European format (commas as decimal points, full stops as the equivalent of commas), e.g. 1,200.5 would be written as 1.200,5 in the European format. :param str string: A representation of the value as a string :returns: The string converted to standard format :rtype: str """ string = string.replace(".", "") string = string.replace(",", ".") return string
bigcode/self-oss-instruct-sc2-concepts
import torch def box_iou(boxes1, boxes2): """Compute IOU between two sets of boxes of shape (N,4) and (M,4).""" # Compute box areas box_area = lambda boxes: ((boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1])) area1 = box_area(boxes1) area2 = box_area(boxes2) lt = torch.max(boxes1[:, None, :2], boxes2[:, :2]) # [N,M,2] rb = torch.min(boxes1[:, None, 2:], boxes2[:, 2:]) # [N,M,2] wh = (rb - lt).clamp(min=0) # [N,M,2] inter = wh[:, :, 0] * wh[:, :, 1] # [N,M] unioun = area1[:, None] + area2 - inter return inter / unioun
bigcode/self-oss-instruct-sc2-concepts
import requests def fetch_json(uri): """Perform an HTTP GET on the given uri, return the results as json. If there is an error fetching the data, raise an exception. Args: uri: the string URI to fetch. Returns: A JSON object with the response. """ data = requests.get(uri) # Raise an exception if the fetch failed. data.raise_for_status() return data.json()
bigcode/self-oss-instruct-sc2-concepts
def my_method2(o): """ This is anoooother doctring of a method living inside package1. Why? Just because I wanted to have more than one. Parameters ---------- o : int Note that this parameter should be a string because it wanted to be different. Returns ------- Five times 'o' """ return 5 * o
bigcode/self-oss-instruct-sc2-concepts
import requests def authenticate_with_refresh_token(client_id, redirect_uri, refresh_token): """Get an access token with the existing refresh token.""" try: url = 'https://api.tdameritrade.com/v1/oauth2/token' headers = { 'Content-Type': 'application/x-www-form-urlencoded' } payload='grant_type=refresh_token&refresh_token='+refresh_token+'&client_id='+client_id+'&redirect_uri='+redirect_uri response = requests.request("POST", url, headers=headers, data = payload) data = response.json() return data['access_token'] except: # Exception occurred, refresh token is invalid print('Invalid refresh token.') return ''
bigcode/self-oss-instruct-sc2-concepts
def root_center(X, root_idx=0): """Subtract the value at root index to make the coordinates center around root. Useful for hip-centering the skeleton. :param X: Position of joints (NxMx2) or (NxMx3) :type X: numpy.ndarray :param root_idx: Root/Hip index, defaults to 0 :type root_idx: int, optional :return: New position of joints (NxMx2) or (NxMx3) :rtype: numpy.ndarray """ assert len(X.shape) == 3 or len(X.shape) == 2 if len(X.shape) == 3: return X - X[:, root_idx:root_idx+1, :] else: return X - X[root_idx:root_idx+1, :]
bigcode/self-oss-instruct-sc2-concepts
def getOperands(inst): """ Get the inputs of the instruction Input: - inst: The instruction list Output: - Returns the inputs of the instruction """ if inst[0] == "00100": return inst[3], inst[4] else: return inst[2], inst[3]
bigcode/self-oss-instruct-sc2-concepts
def checkfile(findstring, fname): """ Checks whether the string can be found in a file """ if findstring in open(fname).read(): #print(findstring, "found in", fname) return True return False
bigcode/self-oss-instruct-sc2-concepts
def crop_region(image, region): """Crops a singular region in an image Args: image (image): A numpy image region (dict): A dictionary containing x1, y1, x2, y2 Returns: image: The cropped image """ return image[ region["y1"]:region["y2"], region["x1"]:region["x2"] ]
bigcode/self-oss-instruct-sc2-concepts
from typing import Sequence import random def sample_coins(coin_biases: Sequence[float]) -> int: """Return integer where bits bias towards 1 as described in coin_biases.""" result = 0 for i, bias in enumerate(coin_biases): result |= int(random.random() < bias) << i return result
bigcode/self-oss-instruct-sc2-concepts
import inspect def get_wrapped_source(f): """ Gets the text of the source code for the given function :param f: Input function :return: Source """ if hasattr(f, "__wrapped__"): # has __wrapped__, going deep return get_wrapped_source(f.__wrapped__) else: # Returning getsource return inspect.getsource(f)
bigcode/self-oss-instruct-sc2-concepts
def pad_sentences(sentences,padding_word="<PAD/>"): """ 填充句子,使所有句子句子长度等于最大句子长度 :param sentences: :param padding_word: :return: padded_sentences """ sequence_length=max(len(x) for x in sentences) padded_sentences=[] for i in range(len(sentences)): sentence=sentences[i] num_padding=sequence_length-len(sentence) new_sentence=sentence+num_padding*[padding_word] padded_sentences.append(new_sentence) return padded_sentences
bigcode/self-oss-instruct-sc2-concepts
def get_util2d_shape_for_layer(model, layer=0): """ Define nrow and ncol for array (Util2d) shape of a given layer in structured and/or unstructured models. Parameters ---------- model : model object model for which Util2d shape is sought. layer : int layer (base 0) for which Util2d shape is sought. Returns --------- (nrow,ncol) : tuple of ints util2d shape for the given layer """ nr, nc, _, _ = model.get_nrow_ncol_nlay_nper() if nr is None: # unstructured nrow = 1 ncol = nc[layer] else: # structured nrow = nr ncol = nc return (nrow, ncol)
bigcode/self-oss-instruct-sc2-concepts
from typing import Any def is_of_type_by_str(value: Any, type_str: str): """ Check if the type of ``value`` is ``type_str``. Parameters ---------- value: any a value type_str: str the expected type of ``value``, given as a str Examples -------- >>> is_of_type_by_str(2, 'int') True >>> is_of_type_by_str("2.5", 'float') False Returns ------- boolean """ return value.__class__.__name__ == type_str
bigcode/self-oss-instruct-sc2-concepts
def default(base, deft): """Return the deft value if base is not set. Otherwise, return base""" if base == 0.0: return base return base or deft
bigcode/self-oss-instruct-sc2-concepts
def points_to_svgd(p, close=True): """ convert list of points (x,y) pairs into a closed SVG path list """ f = p[0] p = p[1:] svgd = 'M%.4f,%.4f' % f for x in p: svgd += 'L%.4f,%.4f' % x if close: svgd += 'z' return svgd
bigcode/self-oss-instruct-sc2-concepts
def __nnc_values_generator_to_list(self, generator): """Converts a NNC values generator to a list.""" vals = [] for chunk in generator: for value in chunk.values: vals.append(value) return vals
bigcode/self-oss-instruct-sc2-concepts
import re def camel_to_snake_case(in_str): """ Convert camel case to snake case :param in_str: camel case formatted string :return snake case formatted string """ return '_'.join(re.split('(?=[A-Z])', in_str)).lower()
bigcode/self-oss-instruct-sc2-concepts
def get_collection_fmt_desc(colltype): """Return the appropriate description for a collection type. E.g. tsv needs to indicate that the items should be tab separated, csv comma separated, etc... """ seps = dict( csv='Multiple items can be separated with a comma', ssv='Multiple items can be separated with a space', tsv='Multiple items can be separated with a tab', pipes='Multiple items can be separated with a pipe (|)', multi='', ) if colltype in seps: return seps[colltype] return ''
bigcode/self-oss-instruct-sc2-concepts
from typing import Callable def interpolator(source_low: float, source_high: float, dest_low: float = 0, dest_high: float = 1, lock_range=False) -> Callable[[float], float]: """ General interpolation function factory :param source_low: Low input value :param source_high: High input value :param dest_low: Desired output value when the input is equal to source_low :param dest_high: Desired output value when the input is equal to source_high :param lock_range: If true (default) the output values will always be strictly constrained to the dest_high, dest_low range, if false then input values outside of source_low, source_high will result in output values beyond this constraint, acting as true linear interpolation. :return: a function of source->dest which applies the specified interpolation """ if source_low > source_high: # Ensure that source_low is always numerically less than source_high return interpolator(source_high, source_low, dest_high, dest_low, lock_range) if source_low == source_high: raise ValueError(f'unable to create interpolator, source_low == source_high == {source_low}') source_range_inverse = 1 / (source_high - source_low) # If we're not locked then just use interpolation def inner_interpolator(value: float) -> float: i = (value - source_low) * source_range_inverse return i * dest_high + (1.0 - i) * dest_low # Otherwise return a version which clamps the interpolation value between 0 and 1 def inner_locked_interpolator(value: float) -> float: i = max(0.0, min(1.0, (value - source_low) * source_range_inverse)) return i * dest_high + (1.0 - i) * dest_low # Return a function from source -> dest return inner_locked_interpolator if lock_range else inner_interpolator
bigcode/self-oss-instruct-sc2-concepts
import struct def of_slicer(remaining_data): """Slice a raw bytes into OpenFlow packets""" data_len = len(remaining_data) pkts = [] while data_len > 3: length_field = struct.unpack('!H', remaining_data[2:4])[0] if data_len >= length_field: pkts.append(remaining_data[:length_field]) remaining_data = remaining_data[length_field:] data_len = len(remaining_data) else: break return pkts, remaining_data
bigcode/self-oss-instruct-sc2-concepts
def ne(value, other): """Not equal""" return value != other
bigcode/self-oss-instruct-sc2-concepts
def type_match(haystack, needle): """Check whether the needle list is fully contained within the haystack list, starting from the front.""" if len(needle) > len(haystack): return False for idx in range(0, len(needle)): if haystack[idx] != needle[idx]: return False return True
bigcode/self-oss-instruct-sc2-concepts
def get_range(xf, yf, low, high): """Gets the values in a range of frequencies. Arguments: xf: A list of frequencies, generated by rfftfreq yf: The amplitudes of frequencies, generated by rfft low: Lower bound of frequency to capture high: Upper bound of frequency to capture returns: Array of values within frquencies. """ x1 = -1 for i in range(len(xf)): if xf[i] >= low: x1 = i break if x1 == -1: raise ValueError x2 = -1 for i in range(len(xf) - x1): if xf[i + x1] >= high: x2 = i + x1 break if x2 == -1: raise ValueError return [abs(x) for x in yf[x1:x2]]
bigcode/self-oss-instruct-sc2-concepts
import pickle def pickle_load(path): """Un-pickles a file provided at the input path Parameters ---------- path : str path of the pickle file to read Returns ------- dict data that was stored in the input pickle file """ with open(path, 'rb') as f: return pickle.load(f)
bigcode/self-oss-instruct-sc2-concepts
from typing import Any import json def is_json_serializable(obj: Any) -> bool: """Check if the object is json serializable Args: obj (Any): object Returns: bool: True for a json serializable object """ try: json.dumps(obj, ensure_ascii=False) return True except: return False
bigcode/self-oss-instruct-sc2-concepts
def shortest_path(g, start, goal): """ Complete BFS via MIT algorith g -> Graph represented via Adjacency list (Dict of sets) start -> start vertex goal -> end vertex Returns shortests path from start to goal """ # level will contains shortest path for each vertex to start level = {start: 0} # parent will contains backtracks for each vertex to its parent parent = {start: None} i = 1 frontier = [start] while frontier: next_f = [] for u in frontier: for v in g[u]: if v not in level: level[v] = i parent[v] = u next_f.append(v) frontier = next_f i += 1 return level[goal] - 1
bigcode/self-oss-instruct-sc2-concepts
import re def fix_links(chunk, tag2file): """Find and fix the the destinations of hyperlinks using HTML or markdown syntax Fix any link in a string text so that they can target a different html document. First use regex on a HTML text to find any HTML or markdown hyperlinks (e.g. <a href="#sec1"> or [sec1](#sec1) ). Then use a dictionary to prepend the filename to the value of a link's href attribute (e.g. <a href="02_jupyterbook.html#sec1">) :param str chunk: text string :param dict tag2file: dictionary mapping a tag to a file basename e.g. tag2file['sec1']='02_jupyterbook' :return: chunk with fixed links :rtype: str """ chunk_out = chunk # html links pattern_tag = r'[\w _\-:]' pattern = r'<' + pattern_tag + '+ href=[\\\]{0,2}["\']#(' + pattern_tag + '+)[\\\]{0,2}["\'][^>]*>' for m in re.finditer(pattern, chunk): match = m.group() tag = m.group(1) fixed_tag = match.replace('#' +tag, tag2file.get(tag, tag) + '.html#' + tag) chunk_out = chunk_out.replace(match, fixed_tag) # markdown links pattern = r'\[' + pattern_tag + '+\]\(#(' + pattern_tag + '+)\)' for m in re.finditer(pattern, chunk): match = m.group() tag = m.group(1) fixed_tag = match.replace('#' + tag, tag2file.get(tag, tag) + '.html#' + tag) chunk_out = chunk_out.replace(match, fixed_tag) return chunk_out
bigcode/self-oss-instruct-sc2-concepts
def is_numeric(value): """Test if a value is numeric.""" return isinstance(value, int) or isinstance(value, float)
bigcode/self-oss-instruct-sc2-concepts
def value_of(column): """value_of({'S': 'Space Invaders'}) -> 'Space Invaders'""" return next(iter(column.values()))
bigcode/self-oss-instruct-sc2-concepts
import six import json import zlib import base64 def send_request(req_url, req_json={}, compress=False, post=True, api_key=None): """ Sends a POST/GET request to req_url with req_json, default to POST. Returns: The payload returned by sending the POST/GET request formatted as a dict. """ # Get the API key headers = { 'x-api-key': api_key, 'Content-Type': 'application/json' } # Send the request and verify the request succeeded if post: req = six.moves.urllib.request.Request(req_url, data=json.dumps(req_json).encode('utf-8'), headers=headers) else: req = six.moves.urllib.request.Request(req_url, headers=headers) try: res = six.moves.urllib.request.urlopen(req) except six.moves.urllib.error.HTTPError as e: raise ValueError( 'Response error: An HTTP {} code was returned by the mixer. Printing ' 'response\n\n{}'.format(e.code, e.read())) # Get the JSON res_json = json.loads(res.read()) if 'payload' not in res_json: raise ValueError('Response error: Payload not found. Printing response\n\n''{}'.format(res.text)) # If the payload is compressed, decompress and decode it payload = res_json['payload'] if compress: payload = zlib.decompress(base64.b64decode(payload), zlib.MAX_WBITS | 32) return json.loads(payload)
bigcode/self-oss-instruct-sc2-concepts
import re def isEndStoryText(string): """ Return True if reach the end of stories. """ match = re.search(r'^\*\*\*', string) if match == None: r = False else: r = True return r
bigcode/self-oss-instruct-sc2-concepts
def depth(obj): """ Calculate the depth of a list object obj. Return 0 if obj is a non-list, or 1 + maximum depth of elements of obj, a possibly nested list of objects. Assume: obj has finite nesting depth @param int|list[int|list[...]] obj: possibly nested list of objects @rtype: int >>> depth(3) 0 >>> depth([]) 1 >>> depth([1, 2, 3]) 1 >>> depth([1, [2, 3], 4]) 2 >>> depth([[], [[]]]) 3 """ if not isinstance(obj, list): # obj is not a list return 0 elif obj == []: return 1 else: # obj is a list return 1 + max([depth(elem) for elem in obj])
bigcode/self-oss-instruct-sc2-concepts
def example(self): """Get and cache an example batch of `inputs, labels` for plotting.""" result = getattr(self, '_example', None) if result is None: # No example batch was found, so get one from the `.train` dataset result = next(iter(self.train)) # And cache it for next time self._example = result return result
bigcode/self-oss-instruct-sc2-concepts
from typing import List def _get_name_matches(name: str, guess_words: List[str]) -> int: """ Return the number of common words in a str and list of words :param name: :param guess_words: :return: number of matches """ matches = sum(word in name for word in guess_words) return matches
bigcode/self-oss-instruct-sc2-concepts
def repo_url_to_full_name(url): """Convert a repository absolute URL to ``full_name`` format used by Github. Parameters ---------- url : str URL of the repository. Returns ------- url : str Full name of the repository accordingly with Github API. """ return "/".join(url.split("/")[3:])
bigcode/self-oss-instruct-sc2-concepts
def calculate_variance(n, p): """ Calculate the sample variance for a binominal distribution """ return p * (1 - p) / n
bigcode/self-oss-instruct-sc2-concepts
def _arguments_str_from_dictionary(options): """ Convert method options passed as a dictionary to a str object having the form of the method arguments """ option_string = "" for k in options: if isinstance(options[k], str): option_string += k+"='"+str(options[k])+"'," else: option_string += k+"="+str(options[k])+"," option_string = option_string.strip(',') return option_string
bigcode/self-oss-instruct-sc2-concepts
def transpose(matrix): """ Takes transpose of the input matrix. Args: matrix: 2D list Return: result: 2D list """ result = [[matrix[col][row] for col in range(len(matrix))] for row in range(len(matrix[0])) ] return result
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional from typing import Dict from typing import Any import jinja2 def merge_template(template_filename: str, config: Optional[Dict[str, Any]]) -> str: """Load a Jinja2 template from file and merge configuration.""" # Step 1: get raw content as a string with open(template_filename) as f: raw_content = f.read() # Step 2: Treat raw_content as a Jinja2 template if providing configuration if config: content = jinja2.Template(raw_content, undefined=jinja2.StrictUndefined).render(**config) else: content = raw_content return content
bigcode/self-oss-instruct-sc2-concepts
def anonymise_max_length_pk(instance, field): """ Handle scenarios where the field has a max_length which makes it smaller than the pk (i.e UUID). """ if hasattr(field, "max_length") and field.max_length and len(str(instance.pk)) > field.max_length: return str(instance.pk)[:field.max_length] else: return str(instance.pk)
bigcode/self-oss-instruct-sc2-concepts
import torch from typing import List def _decode(loc: torch.Tensor, priors: torch.Tensor, variances: List[float]) -> torch.Tensor: """Decode locations from predictions using priors to undo the encoding we did for offset regression at train time. Args: loc:location predictions for loc layers. Shape: [num_priors,4]. priors: Prior boxes in center-offset form. Shape: [num_priors,4]. variances: (list[float]) Variances of priorboxes. Return: Tensor containing decoded bounding box predictions. """ boxes = torch.cat(( priors[:, 0:2] + loc[:, 0:2] * variances[0] * priors[:, 2:4], priors[:, 2:4] * torch.exp(loc[:, 2:4] * variances[1]), priors[:, 0:2] + loc[:, 4:6] * variances[0] * priors[:, 2:4], priors[:, 0:2] + loc[:, 6:8] * variances[0] * priors[:, 2:4], priors[:, 0:2] + loc[:, 8:10] * variances[0] * priors[:, 2:4], priors[:, 0:2] + loc[:, 10:12] * variances[0] * priors[:, 2:4], priors[:, 0:2] + loc[:, 12:14] * variances[0] * priors[:, 2:4]), 1) # prepare final output tmp = boxes[:, 0:2] - boxes[:, 2:4] / 2 return torch.cat((tmp, boxes[:, 2:4] + tmp, boxes[:, 4:]), dim=-1)
bigcode/self-oss-instruct-sc2-concepts
def wrap_argument(text): """ Wrap command argument in quotes and escape when this contains special characters. """ if not any(x in text for x in [' ', '"', "'", '\\']): return text else: return '"%s"' % (text.replace('\\', r'\\').replace('"', r'\"'), )
bigcode/self-oss-instruct-sc2-concepts
def filter_dict(pred, d) : """Return a subset of the dictionary d, consisting only of the keys that satisfy pred(key).""" ret = {} for k in d : if pred(k) : ret[k] = d[k] return ret
bigcode/self-oss-instruct-sc2-concepts
import json def df_to_dict(df, orient='None'): """ Replacement for pandas' to_dict which has trouble with upcasting ints to floats in the case of other floats being there. https://github.com/pandas-dev/pandas/issues/12859#issuecomment-208319535 see also https://stackoverflow.com/questions/37897527/get-python-pandas-to-dict-with-orient-records-but-without-float-cast :param df: a pandas DataFrame :param orient: The format of the intermediate JSON string and resulting dict :return: dict """ return json.loads(df.to_json(orient=orient))
bigcode/self-oss-instruct-sc2-concepts
def create_data_model(distancematrix): """ Create a dictionary/data model Parameters: distancematrix (float[][]): array of distances between addresses Returns: dictionary: data model generated """ # initiate ORTools data = {} data['distance_matrix'] = distancematrix data['num_vehicles'] = 1 data['depot'] = 0 return (data)
bigcode/self-oss-instruct-sc2-concepts
def read_scores_into_list(scores_file): """ Read in scores file, where scores are stored in 2nd column. """ scores_list = [] with open(scores_file) as f: for line in f: cols = line.strip().split("\t") scores_list.append(float(cols[1])) f.closed assert scores_list, "no scores read in (scores_list empty)" return scores_list
bigcode/self-oss-instruct-sc2-concepts
def fields(cursor): """ Given a DB API 2.0 cursor object that has been executed, returns a dictionary that maps each field name to a column index, 0 and up. """ results = {} for column, desc in enumerate(cursor.description): results[desc[0]] = column return results
bigcode/self-oss-instruct-sc2-concepts
def introspection_email(request): """Returns the email to be returned by the introspection endpoint.""" return request.param if hasattr(request, 'param') else None
bigcode/self-oss-instruct-sc2-concepts
def submat(M,i,j): """ return a copy of matrix `M` whitout row `i` and column `j` """ N = M.copy() N.row_del(i) N.col_del(j) return N
bigcode/self-oss-instruct-sc2-concepts
import json def parse_data_file(data_path): """ Parse data file with benchmark run results. """ with open(data_path, "r") as fp: content = fp.read() data = json.loads(content) return data
bigcode/self-oss-instruct-sc2-concepts
import re def splitTypeName(name): """ Split the vendor from the name. splitTypeName('FooTypeEXT') => ('FooType', 'EXT'). """ suffixMatch = re.search(r'[A-Z][A-Z]+$', name) prefix = name suffix = '' if suffixMatch: suffix = suffixMatch.group() prefix = name[:-len(suffix)] return (prefix, suffix)
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def stream_error(e: BaseException, line: str) -> Dict: """ Return an error `_jc_meta` field. """ return { '_jc_meta': { 'success': False, 'error': f'{e.__class__.__name__}: {e}', 'line': line.strip() } }
bigcode/self-oss-instruct-sc2-concepts
def import_object(name): """Function that returns a class in a module given its dot import statement.""" name_module, name_class = name.rsplit('.', 1) module = __import__(name_module, fromlist=[name_class]) return getattr(module, name_class)
bigcode/self-oss-instruct-sc2-concepts
def is_numeric(value): """ check whether a value is numeric (could be float, int, or numpy numeric type) """ return hasattr(value, "__sub__") and hasattr(value, "__mul__")
bigcode/self-oss-instruct-sc2-concepts
def has_extension(filepath, extensions): """Check if file extension is in given extensions.""" return any(filepath.endswith(ext) for ext in extensions)
bigcode/self-oss-instruct-sc2-concepts
def to_basestring(s): """Converts a string argument to a byte string. If the argument is already a byte string, it is returned unchanged. Otherwise it must be a unicode string and is encoded as utf8. """ if isinstance(s, bytes): return s return s.encode('utf-8')
bigcode/self-oss-instruct-sc2-concepts
def cross(str_a, str_b): """Cross product (concatenation) of two strings A and B.""" return [a + b for a in str_a for b in str_b]
bigcode/self-oss-instruct-sc2-concepts
def getKeyNamePath(kms_client, project_id, location, key_ring, key_name): """ Args: kms_client: Client instantiation project_id: str - location: str - key_ring: str - key_name: str - Returns: key_name: str - 'projects/YOUR_GCLOUD_PROJECT/locations/YOUR_LOCATION/keyRings/YOUR_KEY_RING/cryptoKeys /YOUR_CRYPTO_KEY """ key_name_path = kms_client.crypto_key_path_path(project_id=project_id, location=location, key_ring=key_ring, crypto_key_path=key_name) return key_name_path
bigcode/self-oss-instruct-sc2-concepts
def num_pos(y_test): """ Gets number of positive labels in test set. :param y_test: Labels of test set :type nb_points: `np.array` :return: number of positive labels :rtype: `int` """ if y_test == []: return 0 else: return sum(y_test)
bigcode/self-oss-instruct-sc2-concepts
def location(C,s,k): """ Computes the location corresponding to the k-value along a segment of a polyline Parameters ---------- C : [(x,y),...] list of tuples The coordinates of the polyline. s : int The index of a segment on polyline C. Must be within [0,n-2] k : float The proportion from the start pt to the end pt of the segment. Returns ---------- (x,y) : (float,float) The computed location. """ x = C[s][0] + k*(C[s+1][0]-C[s][0]) y = C[s][1] + k*(C[s+1][1]-C[s][1]) return (x,y)
bigcode/self-oss-instruct-sc2-concepts
import re def matchLettersAndNumbersOnly(value): """Match strings of letters and numbers.""" if re.match('^[a-zA-Z0-9]+$', value): return True return False
bigcode/self-oss-instruct-sc2-concepts
import math def haversine_distance(origin, destination): """ Haversine formula to calculate the distance between two lat/long points on a sphere """ radius = 6371.0 # FAA approved globe radius in km dlat = math.radians(destination[0]-origin[0]) dlon = math.radians(destination[1]-origin[1]) a = math.sin(dlat/2.) * math.sin(dlat/2.) + math.cos(math.radians(origin[0])) \ * math.cos(math.radians(destination[0])) * math.sin(dlon/2.) * math.sin(dlon/2.) c = 2.0 * math.atan2(math.sqrt(a), math.sqrt(1-a)) d = radius * c return d
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path from typing import Union import hashlib import re def insert_hash(path: Path, content: Union[str, bytes], *, hash_length=7, hash_algorithm=hashlib.md5): """ Insert a hash based on the content into the path after the first dot. hash_length 7 matches git commit short references """ if isinstance(content, str): content = content.encode() hash_ = hash_algorithm(content).hexdigest()[:hash_length] if '.' in path.name: new_name = re.sub(r'\.', f'.{hash_}.', path.name, count=1) else: new_name = f'{path.name}.{hash_}' return path.with_name(new_name)
bigcode/self-oss-instruct-sc2-concepts
def build_dataservices_by_publisher_query() -> str: """Build query to count dataservices grouped by publisher.""" return """ PREFIX dct: <http://purl.org/dc/terms/> PREFIX dcat: <http://www.w3.org/ns/dcat#> SELECT ?organizationNumber (COUNT(DISTINCT ?service) AS ?count) FROM <https://dataservices.fellesdatakatalog.digdir.no> WHERE {{ ?service a dcat:DataService . ?service dct:publisher ?publisher . ?publisher dct:identifier ?organizationNumber . }} GROUP BY ?organizationNumber"""
bigcode/self-oss-instruct-sc2-concepts
async def get_action(game_state, message: str, possible_actions: list) -> int: """ Helper function used to get action from player for current state of game. :param game_state: GameState object with all game data inside :param message: string with message for player :param possible_actions: list with all possible action for given GameState :return: int value of chosen action """ shelter = game_state.active_player if len(possible_actions) == 1: return possible_actions[0] while True: action = await shelter.input_async(message) if action in possible_actions: break else: shelter.print(f'No such action as {action}!') return action
bigcode/self-oss-instruct-sc2-concepts
def human_file_size(bytes_): """ Formats the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB, 102 bytes, etc.). """ try: bytes_ = float(bytes_) except (TypeError, ValueError, UnicodeDecodeError): return '0 bytes' def filesize_number_format(value): return round(value, 2) KB = 1 << 10 MB = 1 << 20 GB = 1 << 30 TB = 1 << 40 PB = 1 << 50 negative = bytes_ < 0 if negative: bytes_ = -bytes_ # Allow formatting of negative numbers. if bytes_ < KB: value = "{} bytes".format(bytes_) elif bytes_ < MB: value = "{} KB".format(filesize_number_format(bytes_ / KB)) elif bytes_ < GB: value = "{} MB".format(filesize_number_format(bytes_ / MB)) elif bytes_ < TB: value = "{} GB".format(filesize_number_format(bytes_ / GB)) elif bytes_ < PB: value = "{} TB".format(filesize_number_format(bytes_ / TB)) else: value = "{} PB".format( filesize_number_format(bytes_ / PB)) return value
bigcode/self-oss-instruct-sc2-concepts
def square(file_index, rank_index): """Gets a square number by file and rank index.""" return rank_index * 8 + file_index
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def file_name_to_parts(image_file_name) -> Tuple[str, str, int]: """ Given the `file_name` field in an iMerit annotation, return the dataset name, sequence id and frame number. """ parts = image_file_name.split('.') dataset_name = parts[0] seq_id = parts[1].split('seq')[1] frame_num = int(parts[2].split('frame')[1]) return dataset_name, seq_id, frame_num
bigcode/self-oss-instruct-sc2-concepts
import collections def trainval_log_statistic(trainval_log): """ Args: trainval_log (dict): output of function: read_trainval_log_file :return: e.g.: >>> result = { >>> 'total_epoch': 100, >>> 'last_top-1_val_accuracy': 0.87, >>> 'last_top-2_val_accuracy': 0.95, ... >>> 'max_top-1_val_accuracy': 0.88, >>> 'last_top-1_epoch': 65, >>> 'max_top-2_val_accuracy': 0.96, >>> 'last_top-2_epoch': 45, ... >>> } """ result = {'total_epoch': len(trainval_log['epoch'])} # last top-k validation accuracy for k in range(len(trainval_log['val_accuracy'][0])): result[f'last_top-{k + 1}_val_accuracy'] = trainval_log['val_accuracy'][-1][k] # max top-k validation accuracy top_k_acc = collections.OrderedDict() for k in range(len(trainval_log['val_accuracy'][0])): top_k_acc[str(k + 1)] = [] for epoch in trainval_log['epoch']: top_k_acc[str(k + 1)].append(trainval_log['val_accuracy'][epoch-1][k]) for key in top_k_acc.keys(): max_acc = max(top_k_acc[key]) max_acc_epoch = trainval_log['epoch'][top_k_acc[key].index(max_acc)] result[f'max_top-{key}_val_accuracy'] = max_acc result[f'max_top-{key}_epoch'] = max_acc_epoch return result
bigcode/self-oss-instruct-sc2-concepts
import hashlib def sha256_encode(text): """ Returns the digest of SHA-256 of the text """ _hash = hashlib.sha256 if type(text) is str: return _hash(text.encode('utf8')).digest() elif type(text) is bytes: return _hash(text).digest() elif not text: # Generally for calls where the payload is empty. Eg: get calls # Fix for AttributeError: 'NoneType' object has no attribute 'encode' return _hash("".encode('utf8')).digest() else: return _hash(str(text).encode('utf-8')).digest()
bigcode/self-oss-instruct-sc2-concepts
def is_current_or_ancestor(page, current_page): """Returns True if the given page is the current page or is an ancestor of the current page.""" return current_page.is_current_or_ancestor(page)
bigcode/self-oss-instruct-sc2-concepts
def buildVecWithFunction(da, func, extra_args=()): """ Construct a vector using a function applied on each point of the mesh. Parameters ========== da : petsc.DMDA The mesh structure. func: function Function to apply on each point. extra_args: tuple extra parameters of the function. Returns ======= b: petsc.Vec The vector with the function values on each point. """ OUT = da.createGlobalVec() out = da.getVecArray(OUT) coords = da.getVecArray(da.getCoordinates()) if da.getDim() == 2: (xs, xe), (ys, ye) = da.getRanges() func(coords[xs:xe, ys:ye], out[xs:xe, ys:ye], *extra_args) else: (xs, xe), (ys, ye), (zs, ze) = da.getRanges() func(coords[xs:xe, ys:ye, zs:ze], out[xs:xe, ys:ye, zs:ze], *extra_args) return OUT
bigcode/self-oss-instruct-sc2-concepts
def _clean_sambam_id(inputname: str) -> str: """Sometimes there are additional characters in the fast5 names added on by albacore or MinKnow. They have variable length, so this attempts to clean the name to match what is stored by the fast5 files. There are 5 fields. The first has a variable length. [7x or 8x az09]-[4x az09]-[4x az09]-[4x az09]-[12x az09] 0688dd3-160d-4e2c-8af8-71c66c8db127 7e33249c-144c-44e2-af45-ed977f6972d8 67cbf79c-e341-4d5d-97b7-f3d6c91d9a85 """ # just grab the first five things when splitting with dashes splitname = inputname.split("-")[0:5] # The last one might have extra characters, unknown. We're relying # on the 5th field to consistently have 12 characters to extract # the correct id splitname[4] = splitname[4][0:12] return "-".join(splitname)
bigcode/self-oss-instruct-sc2-concepts
import json def validate_invoking_event(event): """Verify the invoking event has all the necessary data fields.""" if 'invokingEvent' in event: invoking_event = json.loads(event['invokingEvent']) else: raise Exception('Error, invokingEvent not found in event, aborting.') if 'resultToken' not in event: raise Exception('Error, resultToken not found in event, aborting.') if 'configurationItem' not in invoking_event: raise Exception("Error, configurationItem not found in event['invokingEvent'], aborting.") if 'resourceType' not in invoking_event['configurationItem']: raise Exception("Error, resourceType not found in event['invokingEvent']['configurationItem'], aborting.") if 'configuration' not in invoking_event['configurationItem']: raise Exception("Error, configuration not found in event['invokingEvent']['configurationItem'], aborting.") if 'userName' not in invoking_event['configurationItem']['configuration']: raise Exception("Error, userName not found in event['invokingEvent']['configurationItem']['configuration'], aborting.") if 'resourceId' not in invoking_event['configurationItem']: raise Exception("Error, resourceId not found in event['invokingEvent']['configurationItem'], aborting.") if 'configurationItemCaptureTime' not in invoking_event['configurationItem']: raise Exception("Error, configurationItemCaptureTime not found in event['invokingEvent']['configurationItem'], aborting.") return invoking_event
bigcode/self-oss-instruct-sc2-concepts
import math def get_oversized(length): """ The oddeven network requires a power-of-2 length. This method computes the next power-of-2 from the *length* if *length* is not a power-of-2 value. """ return 2 ** math.ceil(math.log2(length))
bigcode/self-oss-instruct-sc2-concepts
def is_set(obj) -> bool: """Checks if the given object is either a set or a frozenset.""" return isinstance(obj, (set, frozenset))
bigcode/self-oss-instruct-sc2-concepts
def _csv_dict_row(user, mode, **kwargs): """ Convenience method to create dicts to pass to csv_import """ csv_dict_row = dict(kwargs) csv_dict_row['user'] = user csv_dict_row['mode'] = mode return csv_dict_row
bigcode/self-oss-instruct-sc2-concepts
def divide(a, b): """Divide two numbers and return the quotient""" #Perform the division if the denominator is not zero if b != 0: quotient = round(a/b, 4) print("The quotient of " + str(a) + " and " + str(b) + " is " + str(quotient) + ".") return str(a) + " / " + str(b) + " = " + str(quotient) #Denominator is zero, result in error else: print("You cannot divide by zero.") return "DIV ERROR"
bigcode/self-oss-instruct-sc2-concepts
import math def Euclidean_distance(x,y): """ Given two vectors, calculate the euclidean distance between them. Input: Two vectors Output: Distance """ D = math.sqrt(sum([(a-b)**2 for a,b in zip(x,y)])) return D
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def neighbors(depths: list[list[int]], x: int, y: int) -> list[Tuple[int, int]]: """Generate the list of neighboring points for the given point""" max_x = len(depths[0]) max_y = len(depths) result = [] for _x, _y in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]: if 0 <= _x < max_x and 0 <= _y < max_y: result.append((_x, _y)) return result
bigcode/self-oss-instruct-sc2-concepts
import re def capitalise_chi(value): """CHI at the start of shelfmarks should always be capitalised.""" return re.sub(r'(?i)^chi\.', 'CHI.', value)
bigcode/self-oss-instruct-sc2-concepts
def copy_doc(source): """Copy the docstring from another function (decorator). The docstring of the source function is prepepended to the docstring of the function wrapped by this decorator. This is useful when inheriting from a class and overloading a method. This decorator can be used to copy the docstring of the original method. Parameters ---------- source : function Function to copy the docstring from Returns ------- wrapper : function The decorated function Examples -------- >>> class A: ... def m1(): ... '''Docstring for m1''' ... pass >>> class B (A): ... @copy_doc(A.m1) ... def m1(): ... ''' this gets appended''' ... pass >>> print(B.m1.__doc__) Docstring for m1 this gets appended """ def wrapper(func): if source.__doc__ is None or len(source.__doc__) == 0: raise ValueError('Cannot copy docstring: docstring was empty.') doc = source.__doc__ if func.__doc__ is not None: doc += func.__doc__ func.__doc__ = doc return func return wrapper
bigcode/self-oss-instruct-sc2-concepts
import string def ishex(hexstr): """Checks if string is hexidecimal""" return all(char in string.hexdigits for char in hexstr)
bigcode/self-oss-instruct-sc2-concepts
def build_ig_bio(part_of_day, sky_cond, sky_emoji, temp_feel): """Builds IG bio.""" return f"Back page of the internet.\n\nI look up this {part_of_day} and the Toronto sky looks like {sky_cond}{sky_emoji}.\nKinda feels like {temp_feel}\u00b0C."
bigcode/self-oss-instruct-sc2-concepts
def _get_num_to_fold(stretch: float, ngates: int) -> int: """Returns the number of gates to fold to achieve the desired (approximate) stretch factor. Args: stretch: Floating point value to stretch the circuit by. ngates: Number of gates in the circuit to stretch. """ return int(round(ngates * (stretch - 1.0) / 2.0))
bigcode/self-oss-instruct-sc2-concepts
import re def lreplace(pattern, sub, string): """ Replaces 'pattern' in 'string' with 'sub' if 'pattern' starts 'string'. """ return re.sub('^%s' % pattern, sub, string)
bigcode/self-oss-instruct-sc2-concepts