seed
stringlengths
1
14k
source
stringclasses
2 values
def comma_join(items, stringify=False): """ Joins an iterable of strings with commas. """ if stringify: return ', '.join(str(item) for item in items) else: return ', '.join(items)
bigcode/self-oss-instruct-sc2-concepts
import math def polar_to_cartesian(r, theta, r_ref=0.0, theta_ref=0.0): """ Helper function to convert polar coordinates to Cartesian coordinates (relative to a defined reference point). :Parameters: r: float Radial distance of point from origin. theta: float Angular bearing of point, clockwise from Y axis (in radians) r_ref: float (optional) Radial distance of reference point from origin (if reference point is not the origin). theta_ref: float (optional) Angular bearing of reference point, clockwise from Y axis (in radians)(if reference point is not the origin). :Returns: (x, y): tuple of 2 floats Cartesian coordinates of point """ if float(r_ref) > 0.0: x = r * math.sin(theta) - r_ref * math.sin(theta_ref) y = r * math.cos(theta) - r_ref * math.cos(theta_ref) # Old anticlockwise from the X axis code # x = r * math.cos(theta) - r_ref * math.cos(theta_ref) # y = r * math.sin(theta) - r_ref * math.sin(theta_ref) else: x = r * math.sin(theta) y = r * math.cos(theta) # Old anticlockwise from the X axis code # x = r * math.cos(theta) # y = r * math.sin(theta) return (x, y)
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def make_paths_absolute(value: str, workdir: Path = Path.cwd()) -> str: """ Detect if value is a relative path and make it absolut if so. :param value: Parameter value from arguments :param workdir: Path to workdir. Default: CWD :return: """ if "../" in value and (workdir / value).exists(): if (workdir / value).is_symlink(): return str((workdir / value).absolute()) return str((workdir / value).resolve(True)) return value
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict import math def position_distance(a: Dict[str, float], b: Dict[str, float]) -> float: """Compute the distance between two positions.""" return math.sqrt((a['x'] - b['x'])**2 + (a['y'] - b['y'])**2 + (a['z'] - b['z'])**2)
bigcode/self-oss-instruct-sc2-concepts
def fix_strength(val, default): """ Assigns given strength to a default value if needed. """ return val and int(val) or default
bigcode/self-oss-instruct-sc2-concepts
def get_refs_from_soup(soup): """get_refs_from_soup. Returns a list of `<cite>` tags from the passed BeautifulSoup object. :param soup: BeautifulSoup object (parsed HTML) """ return soup.find_all('cite', recursive=True)
bigcode/self-oss-instruct-sc2-concepts
def get_target_value(data_frame, target_type): """ Get the value of a specific target from the engineered features pandas data frame. :param data_frame: The engineered features pandas data frame. :param target_type: The name of the prediction target. :return: The prediction target value. """ metadata = data_frame._metadata target_value = metadata[target_type] return target_value
bigcode/self-oss-instruct-sc2-concepts
import string def filename_from_string(text): """Produces a valid (space-free) filename from some text""" text = text.lower() valid_chars = "-_." + string.ascii_letters + string.digits return ''.join(c for c in text if c in valid_chars)
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path from typing import List def read_tabular_data(filename: Path) -> List[List[float]]: """Reads a tabular data file, skipping comment lines. Args: filename (Path): The full path of the file to be read Returns: List[List[float]]: The file contents, with comment lines removed. """ lines = [] for line in open(filename, 'r').readlines(): if line.startswith('#'): # Skip comment lines continue lines.append([float(x) for x in line.strip().split()]) return lines
bigcode/self-oss-instruct-sc2-concepts
def _tile_url(tile_format, x, y, zoom): """Build S3 URL prefix The S3 bucket is organized {tile_format}/{z}/{x}/{y}.tif Parameters ---------- tile_format : str One of 'terrarium', 'normal', 'geotiff' zoom : int zoom level x : int x tilespace coordinate y : int x tilespace coordinate Returns ------- str Bucket prefix Raises ------ TypeError """ tile_url = "{tile_format}/{zoom}/{x}/{y}.{ext}" ext = {"geotiff": "tif", "normal": "png", "terrarium": "png"} return tile_url.format(tile_format=tile_format, zoom=zoom, x=x, y=y, ext=ext[tile_format])
bigcode/self-oss-instruct-sc2-concepts
def parse_opcode(token): """Extract the opcode and the mode of all params""" opcode = token % 100 modes = [0, 0, 0, 0] if token > 100: for (i, mode) in enumerate(str(token)[-3::-1]): modes[i] = int(mode) return opcode, modes
bigcode/self-oss-instruct-sc2-concepts
def _desc_has_possible_number_data(desc): """Returns true if there is any possible number data set for a particular PhoneNumberDesc.""" # If this is empty, it means numbers of this type inherit from the "general desc" -> the value # "-1" means that no numbers exist for this type. if desc is None: return False return len(desc.possible_length) != 1 or desc.possible_length[0] != -1
bigcode/self-oss-instruct-sc2-concepts
import pickle def load_pickle(path): """ Load object from path :param path: path to pickle file :type path: str :return: object """ with open(path, 'rb') as f: obj = pickle.load(f) return obj
bigcode/self-oss-instruct-sc2-concepts
def has_dtypes(df, items): """ Assert that a DataFrame has ``dtypes`` Parameters ========== df: DataFrame items: dict mapping of columns to dtype. Returns ======= df : DataFrame """ dtypes = df.dtypes for k, v in items.items(): if not dtypes[k] == v: raise AssertionError("{} has the wrong dtype. Should be ({}), is ({})".format(k, v,dtypes[k])) return df
bigcode/self-oss-instruct-sc2-concepts
def parse_filename(filename): # time_tag=TIME_INFOLDER_TAG, # time_fmt=TIME_INFILE_FMT, # ): """Parse Hive and RPi number from filename. Filename e.g.: raw_hive1_rpi1_190801-000002-utc.jpg """ prefix, hive_str, rpi_str, t_str = filename.split("_") hive = int(hive_str[-1]) rpi = int(rpi_str[-1]) return hive, rpi
bigcode/self-oss-instruct-sc2-concepts
def do_steps_help(cls_list): """Print out the help for the given steps classes.""" for cls in cls_list: print(cls.help()) return 0
bigcode/self-oss-instruct-sc2-concepts
def bbox_to_pptx(left, bottom, width, height): """ Convert matplotlib bounding box format to pptx format Parameters ---------- bottom : float left : float width : float height : float Returns ------- left, top, width, height """ return left, bottom-height, width, height
bigcode/self-oss-instruct-sc2-concepts
def get_ids(cls, inherit=None): """Function that returns all the IDs to use as primary key For a given class, this function will check for the _ids parameter and call itself recursively on the given class' base classes to append all other required IDs, thus generating the list of parameters to use as primary key for the database. This allows not to repeat the same IDs for each inheritance level and to compute it automatically. """ if not inherit or issubclass(cls, inherit): ids = list(getattr(cls, '_ids', [])) else: ids = [] for c in cls.__bases__: for i in get_ids(c, inherit): if i not in ids: ids.append(i) return ids
bigcode/self-oss-instruct-sc2-concepts
import itertools def createListWord(n): """Creates the list of word with size n on the alphabet {1,2,3,4}.""" temp = [''.join(x) for x in itertools.product('1234', repeat=n)] L = [int(y) for y in temp] return L
bigcode/self-oss-instruct-sc2-concepts
def build_group_id(ad, desc_list, prettify=(), force_list=(), additional=None): """ Builds a Group ID from information found in the descriptors. It takes a number of descriptor names, invokes and then concatenates their result (converted to string) to from a group ID. Additional parameters can be passed to modify the result. Parameters ---------- ad: AstroData An instance of `AstroData` derivative that the descriptors will be desc_list: list of str A list of descriptor names (order matters) which will be used to build the Group ID prettify: sequence/set of str Names of descriptors that need to be invoked with `pretty=True` force_list: sequence/set of str The descriptors named in this list will have their results coerced into a list, if they returned something else. additional: str Additional information that will be added verbatim at the end of the Group ID Returns ------- A string with the group id """ desc_object_string_list = [] for descriptor in desc_list: desc_method = getattr(ad, descriptor) if descriptor in prettify or 'section' in descriptor: desc_object = desc_method(pretty=True) else: desc_object = desc_method() # Ensure we get a list, even if only looking at one extension if (descriptor in force_list and not isinstance(desc_object, list)): desc_object = [desc_object] # Convert descriptor to a string and store desc_object_string_list.append(str(desc_object)) # Add in any none descriptor related information if additional is not None: desc_object_string_list.append(additional) # Create and return the final group_id string return '_'.join(desc_object_string_list)
bigcode/self-oss-instruct-sc2-concepts
import random def tirage_uniforme(min, max): """ Renvoie un nombre décimal (float) choisi de manière (pseudo)aléatoire et uniforme de l'intervalle \[``min`` ; ``max``\[. Arguments: min (float): Un nombre réel. max (float): Un nombre réel. """ return random.uniform(min, max)
bigcode/self-oss-instruct-sc2-concepts
def greet(greeting, name): """Returns a greeting Args: greeting (string): A greet word name (string): A persons name Returns: string -- A greeting with a name """ return f'{greeting} {name}'
bigcode/self-oss-instruct-sc2-concepts
def _is_parameter_for(name, container, docmap): """ @rtype: C{boolean} @return: True if C{name} is the name of a parameter for the routine C{container}, given the DocMap C{docmap}. """ if docmap is None or not docmap.has_key(container): return 0 container_doc = docmap.get(container) if container.is_routine(): for param in container_doc.parameter_list(): if param.name() == name: return 1 return 0
bigcode/self-oss-instruct-sc2-concepts
def is_lvm(name): """ Check if device is marked as an lvm """ if "lvm" in name: return True return False
bigcode/self-oss-instruct-sc2-concepts
def place_figures(figures): """Generate LaTeX code for figure placement. Parameters ---------- figures : list List holding LaTeX code of individual figures to be placed in document. Returns ------- latex : str LaTeX code for figure alignment. """ latex = '' num_per_row = 2 num_rows = len(figures) // num_per_row + 1 for row in range(num_rows): for figure in figures[num_per_row * row:num_per_row * (row + 1)]: latex += ( r'\begin{minipage}{' + str(1 / num_per_row) + r'\textwidth}' + '\n') latex += figure latex += r'\end{minipage}' + '\n' latex += '\n' return latex
bigcode/self-oss-instruct-sc2-concepts
import random def scramble_word(word: str) -> str: """Return a scrambled version of the word.""" return ''.join(random.sample(word, k=len(word)))
bigcode/self-oss-instruct-sc2-concepts
def _get_node_name_prefix(node_name): """ Returns the node name prefix, without phase character or trailing whitespaces. """ wows_name = node_name.strip() return wows_name[:-1]
bigcode/self-oss-instruct-sc2-concepts
def file_requires_unicode(x): """ Return whether the given writable file-like object requires Unicode to be written to it. """ try: x.write(b'') except TypeError: return True else: return False
bigcode/self-oss-instruct-sc2-concepts
def get_type_name(value_type): """Returns the name of the given type.""" return value_type.__name__
bigcode/self-oss-instruct-sc2-concepts
def runge_kutta_fourth_xy(rhs, h, x, y): """ Solves one step using a fourth-order Runge-Kutta method. RHS expects both x and y variables. Moin, P. 2010. Fundamentals of Engineering Numerical Analysis. 2nd ed. Cambridge University Press. New York, New York. :param rhs: "Right-hand Side" of the equation(s). Everything but the derivative. (e.g dy/dx = f(x, y)) :param h: step size :param x: step dimension :param y: output dimension :return: """ k_1 = rhs(x, y) k_2 = rhs(x + h / 2.0, y + k_1 / 2.0) k_3 = rhs(x + h / 2.0, y + k_2 / 2.0) k_4 = rhs(x + h, y + k_3) return y + (k_1 + 2 * (k_2 + k_3) + k_4) / 6.0 * h
bigcode/self-oss-instruct-sc2-concepts
def ptbunescape(token): """Unescape brackets in a single token, including PTB notation.""" if token in ('', '#FRONTIER#', None): return None elif token == '-LCB-': return '{' elif token == '-RCB-': return '}' elif token == '-LSB-': return '[' elif token == '-RSB-': return ']' return token.replace('-LRB-', '(').replace('-RRB-', ')').replace( '#LRB#', '(').replace('#RRB#', ')')
bigcode/self-oss-instruct-sc2-concepts
def mean(list): """ Calcula a média de um vetor de números. Args: list (list): vetor de números Returns: (float) média dos números """ return sum(list) / len(list)
bigcode/self-oss-instruct-sc2-concepts
def parse_config(configfile): """Parse the config file 'configfile' and return the parsed key-value pairs as dict""" return {k:v for k,v in map(lambda x: x.strip().split('='), filter(lambda x: not x.strip().startswith('#'), (line for line in open(configfile))))}
bigcode/self-oss-instruct-sc2-concepts
def parse_id(string): """Returns the UUID part of a string only.""" return string.split('/')[-1]
bigcode/self-oss-instruct-sc2-concepts
def formalize_bbox(_im_summary): """ Extract bboxes from all classes and return a list of bbox. Each element of the list is in the form: [x1, y1, x2, y2, class_id, score]. The returned list is sorted descendingly according to score. """ boxes = [] # each element: x, y, w, h, class_id, score probs = [] # prob distribution for each bounding box feats = [] # pooled features for class_id, items in enumerate(_im_summary.pred.boxes): for bbox in items: x1, y1, x2, y2, score = bbox boxes.append([x1, y1, x2, y2, class_id, score]) for class_id, items in enumerate(_im_summary.pred.cls_prob): for cls_prob in items: probs.append(cls_prob) assert len(boxes) == len(probs) for class_id, items in enumerate(_im_summary.pred.pooled_feat): for f in items: feats.append(f) assert len(boxes) == len(feats) bundles = list(zip(boxes, probs, feats)) bundles = sorted(bundles, key=lambda x: x[0][-1], reverse = True) # sort by confidence descendingly boxes, probs, feats = zip(*bundles) return (list(boxes), list(probs), list(feats))
bigcode/self-oss-instruct-sc2-concepts
def row_full(row, puzzle): """ Takes a row number, and a sudoku puzzle as parameter Returns True if there is no empty space on the row ReturnsFalse if otherwise """ for col in range(0, 9): if puzzle[row][col] == -1: return False return True
bigcode/self-oss-instruct-sc2-concepts
def collect_families_from_instances(instances, only_active=False): """Collect all families for passed publish instances. Args: instances(list<pyblish.api.Instance>): List of publish instances from which are families collected. only_active(bool): Return families only for active instances. """ all_families = set() for instance in instances: if only_active: if instance.data.get("publish") is False: continue family = instance.data.get("family") if family: all_families.add(family) families = instance.data.get("families") or tuple() for family in families: all_families.add(family) return list(all_families)
bigcode/self-oss-instruct-sc2-concepts
def isvlan(value): """Checks if the argument is a valid VLAN A valid VLAN is an integer value in the range of 1 to 4094. This function will test if the argument falls into the specified range and is considered a valid VLAN Args: value: The value to check if is a valid VLAN Returns: True if the supplied value is a valid VLAN otherwise False """ try: value = int(value) return value in range(1, 4095) except ValueError: return False
bigcode/self-oss-instruct-sc2-concepts
def parse(utxo, offset=0): """ Parses a given serialized UTXO to extract a base-128 varint. :param utxo: Serialized UTXO from which the varint will be parsed. :type utxo: hex str :param offset: Offset where the beginning of the varint if located in the UTXO. :type offset: int :return: The extracted varint, and the offset of the byte located right after it. :rtype: hex str, int """ i = 0 ret = 0 go = True while go: next_byte = ord(utxo[i]) go = bool(next_byte & 0x80) ret = (ret << 7 | next_byte & 0x7f) + go i += 1 return ret,i
bigcode/self-oss-instruct-sc2-concepts
def _list_readline(x): """Given a list, returns a readline() function that returns the next element with each call. """ x = iter(x) def readline(): return next(x) return readline
bigcode/self-oss-instruct-sc2-concepts
import random import string def random_string(nlen): """Create random string which length is `nlen`.""" return "".join([random.choice(string.ascii_lowercase) for _ in range(nlen)])
bigcode/self-oss-instruct-sc2-concepts
def match_word(encoded_word, words_list): """ Find first probably correct word based on list of words and given encoded word. """ results = [] for word in words_list: #skip all items with different first and last char if word[0] != encoded_word[0] or word[-1] != encoded_word[-1]: continue #skip all items with different chars elif sorted(list(word)) != sorted(list(encoded_word)): continue results.append(word) return results[0]
bigcode/self-oss-instruct-sc2-concepts
def extract_meta_from_keys(keys, prefix): """Extract metadata contained in a key's name. Parameters ---------- keys : list of strings prefix : string Returns ------- meta : string """ return next(k[len(prefix):] for k in keys if k.startswith(prefix))
bigcode/self-oss-instruct-sc2-concepts
def ChannelFirst(arr): """Convert a HWC array to CHW.""" ndim = arr.ndim return arr.swapaxes(ndim - 1, ndim - 2).swapaxes(ndim - 2, ndim - 3)
bigcode/self-oss-instruct-sc2-concepts
import torch def exp(x): """ The exponential link function given by $$ y = e^{x} $$ """ return torch.exp(x)
bigcode/self-oss-instruct-sc2-concepts
def get_linef(fp, line_no): """'fp' should be (readable) file object. Return the line content at line_no or an empty line if there is less lines than line_no. """ fp.seek(0) for line in fp: line_no -= 1 if line_no == 0: return line return ''
bigcode/self-oss-instruct-sc2-concepts
def make_1024_list() : """ Generates a list of 1024 strings of numbers in the format "XXXX", filled with zeros before the number. It is here to translate integers into the format used in the dataset (+1 because the list starts at "0001"). :return: returns a list of 1024 strings """ list = [] for x in range(1,10) : list.append('000'+str(x)) for x in range(10,100) : list.append('00'+str(x)) for x in range(100,1000) : list.append('0'+str(x)) for x in range(1000,1025) : list.append(str(x)) return list
bigcode/self-oss-instruct-sc2-concepts
import collections def longest_path(current_state): """Find longest possible path from the current state to the final state Args: current_state: StateForGraphs The state at the beginning of the search; the root of the tree. Returns: The maximum number of steps that can be used to get from current_state to a final state, using state.possible_next_states to find states reachable in one step from the current state See Also: StateForGraphs to understand the required methods for the states used in the graph. The states must implement __hash__, __eq__, possible_next_states, and is_final """ queue = collections.deque() discovered = {current_state: 0} queue.append(current_state) lengths = set() while queue: state = queue.popleft() num_steps = discovered[state] new_states = state.possible_next_states() for new_state in new_states: if new_state.is_final(): lengths.add(num_steps + 1) elif new_state not in discovered: queue.append(new_state) discovered[new_state] = num_steps + 1 return max(lengths)
bigcode/self-oss-instruct-sc2-concepts
def get_topic_key(project_name, topic): """ Get the topic key for a project name and a topic :param project_name: project name :param topic: topic :return: topic key """ return f"{project_name}/{topic}"
bigcode/self-oss-instruct-sc2-concepts
def nvl(*args): """ SQL like coelesce / redshift NVL, returns first non Falsey arg """ for arg in args: try: if arg: return arg except ValueError: if arg is not None: return arg return args[-1]
bigcode/self-oss-instruct-sc2-concepts
def parseFields(fields, output): """ Take a string of fields encoded as key1=value1,key2=value2,... and add the keys and values to the output dict""" for field in fields.split('|'): key, value = field.split('=') try: value = int(value) except: pass output[key] = value return output
bigcode/self-oss-instruct-sc2-concepts
def to_camel_case(snake_str): """ Transforms a snake_case string into camelCase. Parameters ---------- snake_str : str Returns ------- str """ parts = snake_str.split("_") # We capitalize the first letter of each component except the first one # with the 'title' method and join them together. return parts[0] + "".join(x.title() for x in parts[1:])
bigcode/self-oss-instruct-sc2-concepts
def to_bytes(s, encoding="utf-8"): """Convert a text string (unicode) to bytestring, i.e. str on Py2 and bytes on Py3.""" if type(s) is not bytes: s = bytes(s, encoding) return s
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Counter def top_k_frequent_bucket_sort(nums: List[int], k: int) -> List[int]: """Given a list of numbers, return the the top k most frequent numbers. Solved using buckets sort approach. Example: nums: [1, 1, 1, 2, 2, 3], k=2 output: [1, 2] 1. Create a list of buckets to store frequencies. Note: no item can appear more than the length of the array 2. Append each item to the frequency bucket. Ex. [[], [3], [2], [1], [], [], []] 3. Flatten the list and return last k elements: [3, 2, 1] Time: O(n): Where n is len(nums) Space: O(n): Where n is len(nums) -- worst case, where every number unique. """ # All items unique. if k == len(nums): return nums # Declare buckets for each frequency frequency_buckets = [[] for _ in range(len(nums) + 1)] # Gets count of item frequency counts = Counter(nums) # Add the numbers to the frequency buckets for num, frequency in counts.items(): frequency_buckets[frequency].append(num) # Flatten the list flat_list = [item for sublist in frequency_buckets for item in sublist] # Return last k items in the list return flat_list[-k:]
bigcode/self-oss-instruct-sc2-concepts
import re def increment(s): """ look for the last sequence of number(s) in a string and increment """ lastNum = re.compile(r'(?:[^\d]*(\d+)[^\d]*)+') m = lastNum.search(s) if m: next = str(int(m.group(1))+1) start, end = m.span(1) s = s[:max(end-len(next), start)] + next + s[end:] return s
bigcode/self-oss-instruct-sc2-concepts
def _check_delimiter(output_filename, delim=None): """Detect delimiter by filename extension if not set""" if output_filename and (delim is None): delimiters = {"tsv": "\t", "csv": ","} delim = delimiters[output_filename.rsplit(".", 1)[-1].lower()] assert delim, "File output delimiter not known. Cannot proceed." return delim
bigcode/self-oss-instruct-sc2-concepts
from typing import Counter def precision_recall_f1(prediction, ground_truth): """ This function calculates and returns the precision, recall and f1-score Args: prediction: prediction string or list to be matched ground_truth: golden string or list reference Returns: floats of (p, r, f1) Raises: None """ if not isinstance(prediction, list): prediction_tokens = prediction.split() else: prediction_tokens = prediction if not isinstance(ground_truth, list): ground_truth_tokens = ground_truth.split() else: ground_truth_tokens = ground_truth common = Counter(prediction_tokens) & Counter(ground_truth_tokens) num_same = sum(common.values()) if num_same == 0: return 0, 0, 0 p = 1.0 * num_same / len(prediction_tokens) r = 1.0 * num_same / len(ground_truth_tokens) f1 = (2 * p * r) / (p + r) return p, r, f1
bigcode/self-oss-instruct-sc2-concepts
from bs4 import BeautifulSoup import requests def fetch_page(url, method, **kwargs) -> BeautifulSoup: """Execute request for page and return as soup""" ret = requests.request(method, url, **kwargs) if ret.status_code != 200: raise Exception(f"Page {url} returned {ret.status_code}") return BeautifulSoup(ret.text, features='lxml')
bigcode/self-oss-instruct-sc2-concepts
def on_off(image, w, h, threshold=128): """ Black and white (no greyscale) with a simple threshold. If the color is dark enough, the laser is on! """ result = [] for row in image: result_row = [] for pixel in row: # We draw black, so 255 is for dark pixels result_row.append(255 if pixel < threshold else 0) result.append(result_row) return result
bigcode/self-oss-instruct-sc2-concepts
def get_init(order): """Return initial guess for fit parameters.""" lambda_guess = [1.0] coeff_guess = [0.0] * (2 * order) return lambda_guess + coeff_guess
bigcode/self-oss-instruct-sc2-concepts
def get_caller_name(caller): """Find the name of a calling (i.e. observed) object. Args: caller: The observed object which is calling an observer. Returns: The name of the caller. If the caller is a function we return that function's .__name__. If the caller is a bound method we return the name of bound object. """ if hasattr(caller, "__self__"): # caller is a Foo instance name = caller.__self__.name else: # caller is a function. name = caller.__name__ return name
bigcode/self-oss-instruct-sc2-concepts
def wc(q,mc2,B): """ Calculate the electron gyrofrequency q is the charge in multiples of the fundamental mc2 is the particle rest mass in MeV B is the magnetic field magnitude in nT """ cof = 89.8755311 res = cof*q*B/mc2 return res
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from typing import List from typing import Tuple def deduplicate(x: Union[List, Tuple]): """Remove duplicates in a list or tuple; preserves original order.""" return type(x)(dict.fromkeys(x))
bigcode/self-oss-instruct-sc2-concepts
def sizeof(bsObj): """ Size of BotSense object in bytes. Size is contextual by object type. """ return bsObj.__sizeof__()
bigcode/self-oss-instruct-sc2-concepts
def extract_variable_index_and_name(string): """Takes a string of the form variable_name[index] and returns the variable_name, and index. The method will return a `ValueError` if the string does not contain a valid set of access brackets, or if the string contains multiple bracket accessors. Parameters ---------- string: str The string to inspect Returns ------- str The name of the variable in the string. str The index that was inside of the accessor brackets. """ if string.count('[') > 1 or string.count(']') > 1: raise ValueError('Nested array indices (e.g. values[0][0]) are not ' 'supported: {}'.format(string)) start_bracket_index = string.find('[') end_bracket_index = string.find(']') if start_bracket_index >= 0 > end_bracket_index: raise ValueError('Property name containts a [ without a matching ]: ' '{}'.format('.'.join(string))) if end_bracket_index >= 0 > start_bracket_index: raise ValueError('Property name containts a ] without a matching [: ' '{}'.format(string)) if start_bracket_index > end_bracket_index: raise ValueError('Property name containts a ] before a [: ' '{}'.format(string)) if end_bracket_index == start_bracket_index + 1: raise ValueError('There is no index between the array brackets: ' '{}'.format(string)) if end_bracket_index != len(string) - 1: raise ValueError('The ] array bracket must be at the end of the property name: ' '{}'.format(string)) array_index = string[start_bracket_index + 1: end_bracket_index] property_name = string[0: start_bracket_index] return property_name, array_index
bigcode/self-oss-instruct-sc2-concepts
async def start_entry() -> dict: """Create a mock start_entry object.""" return { "id": "start_entry_1", "race_id": "race_1", "startlist_id": "startlist_1", "bib": 1, "name": "name names", "club": "the club", "scheduled_start_time": ("2021-08-31T12:00:00"), "starting_position": 1, "status": "", "changelog": [], }
bigcode/self-oss-instruct-sc2-concepts
def myfunc(_a, _b): """Add two numbers.""" return _a + _b
bigcode/self-oss-instruct-sc2-concepts
def is_one_to_one(table): """A staticmethod that takes a codon table as a dictionary and returns True if it represents a One-To-One genetic code and False otherwise. A one-to-one code is defined as a code in which every amino acid is represented with exactly one codon. This defines an unambiguous mapping of protein sequence to corresponding DNA sequence. Parameters ---------- dict table: a python dict representing the codon table Returns ------- bool one2one: boolean; True if One-To-One, and False otherwise """ # declare storage dict to count amino acid number aa_set = set(aa for aa in table.values()) aa_counts = {aa: 0 for aa in aa_set} # count number of amino acids for aa in table.values(): aa_counts[aa] += 1 # iterate through dictionary and check counts one2one = True for aa, count in aa_counts.items(): # skip stop and null signals: if aa in {'*', '0'}: continue elif count > 1: one2one = False break return one2one
bigcode/self-oss-instruct-sc2-concepts
def mex(L): """Return the minimum excluded value of a list""" L = set(L) n = 0 while n in L: n += 1 return n
bigcode/self-oss-instruct-sc2-concepts
def _get_magnitude(string): """ Get the magnitude of the smallest significant value in the string :param str string: A representation of the value as a string :returns: The magnitude of the value in the string. e.g. for 102, the magnitude is 0, and for 102.03 it is -2 :rtype: int """ split_by_period = string.split(".") if len(split_by_period) == 2: return -1 * len(split_by_period[-1]) elif len(split_by_period) == 1: return len(string) - len(string.rstrip('0')) else: raise ValueError(string + " does not contain a value")
bigcode/self-oss-instruct-sc2-concepts
def __get_pivots(diameter, x, y): """ Get the x-intercepts and y-intercepts of the circle and return a list of pivots which the coin lies on. """ pivots = [] radius = diameter / 2 sqval = radius**2 - y**2 if sqval > 0: # no imaginary numbers! sqrt = sqval**(0.5) pivots.append((x + sqrt, 0)) pivots.append((x - sqrt, 0)) elif sqval == 0: # tangent pivots.append((x, 0)) sqval = radius**2 - x**2 if sqval > 0: sqrt = sqval**(0.5) pivots.append((0, y + sqrt)) pivots.append((0, y - sqrt)) elif sqval == 0: pivots.append((0, y)) return pivots
bigcode/self-oss-instruct-sc2-concepts
def create_filename(lecture_num, title): """ Create a filename from a title string. Converts spaces to dashes and makes everything lowercase Returns: lecture filename """ return "lecture-{:02d}{}.md".format(int(lecture_num), "" if not title else '-' + title.lower().replace(" ", "-"))
bigcode/self-oss-instruct-sc2-concepts
def get_line(s3_autoimport): """Build a list of relevant data to be printed. Args: s3_autoimport (S3ProjectImport): instance of S3 autoimport Returns: list(str): list of relevant data to be printed """ return "\t".join( [ str(s3_autoimport.id), str(s3_autoimport.project_id), str(s3_autoimport.s3_uri), ] )
bigcode/self-oss-instruct-sc2-concepts
def FindPhaseByID(phase_id, phases): """Find the specified phase, or return None""" for phase in phases: if phase.phase_id == phase_id: return phase return None
bigcode/self-oss-instruct-sc2-concepts
def dataToString(var, data): """Given a tuple of data, and a name to save it as returns var <- c(data) """ #convert data to strings d = [str(d) for d in data] return "%s <- c(%s)" % (var, ",".join(d))
bigcode/self-oss-instruct-sc2-concepts
def alt_ternary_handle(tokens): """Handle if ... then ... else ternary operator.""" cond, if_true, if_false = tokens return "{if_true} if {cond} else {if_false}".format(cond=cond, if_true=if_true, if_false=if_false)
bigcode/self-oss-instruct-sc2-concepts
def extract_volume_number(value): """Extract the volume number from a string, returns None if not matched.""" return value.replace("v.", "").replace("v .", "").strip()
bigcode/self-oss-instruct-sc2-concepts
def get_full_exception_name(exception: Exception) -> str: """Get the full exception name i.e. get sqlalchemy.exc.IntegrityError instead of just IntegrityError """ module = exception.__class__.__module__ if module is None or module == str.__class__.__module__: return exception.__class__.__name__ return module + "." + exception.__class__.__name__
bigcode/self-oss-instruct-sc2-concepts
def prettyTimeDelta (seconds): """ Pretty-print seconds to human readable string 1d 1h 1m 1s """ seconds = int(seconds) days, seconds = divmod(seconds, 86400) hours, seconds = divmod(seconds, 3600) minutes, seconds = divmod(seconds, 60) s = [(days, 'd'), (hours, 'h'), (minutes, 'm'), (seconds, 's')] s = filter (lambda x: x[0] != 0, s) return ' '.join (map (lambda x: '{}{}'.format (*x), s))
bigcode/self-oss-instruct-sc2-concepts
def _convert_snake_to_pascal(snake_case_string: str) -> str: """ Convert a string provided in snake_case to PascalCase """ return ''.join(word.capitalize() for word in snake_case_string.split('_'))
bigcode/self-oss-instruct-sc2-concepts
def read_file_str(file_path: str) -> str: """ Read the target file string. Parameters ---------- file_path : str Path of target file. Returns ------- file_str : str The target string read. """ with open(file_path, mode='r', encoding='utf-8') as f: file_str: str = f.read() return file_str
bigcode/self-oss-instruct-sc2-concepts
def getHlAtt(app, n, highlights, isSlot): """Get the highlight attribute and style for a node for both pretty and plain modes. Parameters ---------- app: obj The high-level API object n: int The node to be highlighted highlights: set|dict The nodes to be highlighted. Keys/elements are the nodes to be highlighted. This function is only interested in whether `n` is in it, and if so, what the value is (in case of a dict). If given as set: use the default highlight color. If given as dict: use the value as color. isSlot: boolean Whether the node has the slotType Returns ------- hlCls: dict Highlight attribute, keyed by boolean 'is pretty' hlStyle: dict Highlight color as css style, keyed by boolean 'is pretty' """ noResult = ({True: "", False: ""}, {True: "", False: ""}) if highlights is None: return noResult color = ( highlights.get(n, None) if type(highlights) is dict else "" if n in highlights else None ) if color is None: return noResult hlCls = {True: "hl", False: "hl" if isSlot else "hlbx"} hlObject = {True: "background", False: "background" if isSlot else "border"} hlCls = {b: hlCls[b] for b in (True, False)} hlStyle = { b: f' style="{hlObject[b]}-color: {color};" ' if color != "" else "" for b in (True, False) } return (hlCls, hlStyle)
bigcode/self-oss-instruct-sc2-concepts
def dir_tree_find(tree, kind): """Find nodes of the given kind from a directory tree structure Parameters ---------- tree : dict Directory tree. kind : int Kind to find. Returns ------- nodes : list List of matching nodes. """ nodes = [] if isinstance(tree, list): for t in tree: nodes += dir_tree_find(t, kind) else: # Am I desirable myself? if tree['block'] == kind: nodes.append(tree) # Search the subtrees for child in tree['children']: nodes += dir_tree_find(child, kind) return nodes
bigcode/self-oss-instruct-sc2-concepts
def intToDBaseTuple(x, dim, D): """ Transfer a integer to a base-D fixed-length tuple of digits. Parameters ---------- x : int A positive integer to be transformed into base-D. dim : int The length of digit tuple as the output. D : int The base of the digit tuple. Returns ------- tuple of ints [0, D - 1) of the digit tuple, of size (dim, ) """ res = [] for _ in range(dim): res.append(x % D) x = x // D return tuple(res)
bigcode/self-oss-instruct-sc2-concepts
def list_product(num_list): """Multiplies all of the numbers in a list """ product = 1 for x in num_list: product *= x return product
bigcode/self-oss-instruct-sc2-concepts
def lin_interp(x, x0, x1, y0, y1): """ Simple helper function for linear interpolation. Estimates the value of y at x by linearly interpolating between points (x0, y0) and (x1, y1), where x0 <= x < x1. Args: x: Float. x-value for which to esrimate y x0: Float. x-value of point 0 x1: Float. x-value of point 1 y0: Float. y-value of point 0 y1: Float. y-value of point 1 Returns: Float. Estimated value of y at x. """ y = y0 + (y1-y0)*(x-x0)/(x1-x0) return y
bigcode/self-oss-instruct-sc2-concepts
def output_size(W, F, P, S): """ https://adventuresinmachinelearning.com/convolutional-neural-networks-tutorial-in-pytorch/ :param W: width in :param F: filter diameter :param P: padding :param S: stride :return:width out """ return (W-F+2*P)/S + 1
bigcode/self-oss-instruct-sc2-concepts
import torch def out_degree(adjacency: torch.Tensor) -> torch.Tensor: """Compute out-degrees of nodes in a graph. Parameters ---------- adjacency Adjacency matrix. Shape: :math:`(N_{nodes},N_{nodes})` Returns ------- torch.Tensor Nodewise out-degree tensor. Shape: :math:`(N_{nodes},)` """ return adjacency.sum(dim=1)
bigcode/self-oss-instruct-sc2-concepts
def is_fasta_file_extension(file_name): """ Check if file has fasta extension Parameters ---------- file_name : str file name Returns ------- bool True if file has fasta extension, False otherwise """ if file_name[-4:] == ".fna": return True elif file_name[-4:] == ".faa": return True elif file_name[-6:] == ".fasta": return True elif file_name[-6:] == ".fastq": return True elif file_name[-3:] == ".fa": return True else: return False
bigcode/self-oss-instruct-sc2-concepts
from typing import Union def _get_remainder(code: Union[list, int]) -> int: """Calculate remainder of validation calculations. :param Union[list, int] code: input code :return: remainder of calculations :rtype: int :raises TypeError: if code is not a list or an integer """ # raise an exception if code is not a list or an integer if not isinstance(code, (list, int)): raise TypeError('code should be a list or an integer') # convert integer code to a list of integers if isinstance(code, int): code = list(map(int, str(code))) # a 10 to 2 list, it will be used for next calculation reversed_range = range(10, 1, -1) # calculate the remainder of CodeMelli formula division return sum([i * j for i, j in zip(code, reversed_range)]) % 11
bigcode/self-oss-instruct-sc2-concepts
def _is_group(token): """ sqlparse 0.2.2 changed it from a callable to a bool property """ is_group = token.is_group if isinstance(is_group, bool): return is_group else: return is_group()
bigcode/self-oss-instruct-sc2-concepts
import warnings def force_connect(client): """ Convenience to wait for a newly-constructed client to connect. Taken from pymongo test.utils.connected. """ with warnings.catch_warnings(): # Ignore warning that "ismaster" is always routed to primary even # if client's read preference isn't PRIMARY. warnings.simplefilter("ignore", UserWarning) client.admin.command("ismaster") # Force connection. return client
bigcode/self-oss-instruct-sc2-concepts
def unescape(st): """ Unescape special chars and return the given string *st*. **Examples**: >>> unescape('\\\\t and \\\\n and \\\\r and \\\\" and \\\\\\\\') '\\t and \\n and \\r and " and \\\\' """ st = st.replace(r'\"', '"') st = st.replace(r'\n', '\n') st = st.replace(r'\r', '\r') st = st.replace(r'\t', '\t') st = st.replace(r'\\', '\\') return st
bigcode/self-oss-instruct-sc2-concepts
import torch def batch_project(xyz_tensor, K): """ Project a point cloud into pixels (u,v) given intrinsic K [u';v';w] = [K][x;y;z] u = u' / w; v = v' / w :param the xyz points :param calibration is a torch array composed of [fx, fy, cx, cy] ------- :return u, v grid tensor in image coordinate (tested through inverse project) """ B, _, H, W = xyz_tensor.size() batch_K = K.expand(H, W, B, 4).permute(2,3,0,1) x, y, z = torch.split(xyz_tensor, 1, dim=1) fx, fy, cx, cy = torch.split(batch_K, 1, dim=1) u = fx*x / z + cx v = fy*y / z + cy return torch.cat((u,v), dim=1)
bigcode/self-oss-instruct-sc2-concepts
def format_sig(name, args, retv): """ Format method signature with Javap's method definition style. Arguments are: name of method, list of argument types, and type of return value. >>> format_sig('getSomeValue', ['int', 'java.lang.String'], 'org.mydomain.myapp.SomeData[]') u'org.mydomain.myapp.SomeData[] getSomeValue(int, java.lang.String)' """ return u'%s %s(%s)' % (retv, name, ', '.join(args))
bigcode/self-oss-instruct-sc2-concepts
import collections def GetTurnStats(game_results): """Returns a histogram of game lengths (in rounds played).""" hist = collections.Counter() for game_result in game_results: hist[game_result.num_rounds_played] += 1 return hist
bigcode/self-oss-instruct-sc2-concepts
def _ParseIssueReferences(issue_ref_list): """Parses a list of issue references into a tuple of IDs added/removed. For example: [ "alpha:7", "beta:8", "-gamma:9" ] => ([ "7", "8" ], [ "9" ]) NOTE: We don't support cross-project issue references. Rather we just assume the issue reference is within the same project. """ added = [] removed = [] for proj in issue_ref_list: parts = proj.split(":") proj_id = parts[1] if len(parts) >= 2 else proj[1:] if proj[0] != "-": added.append(proj_id) else: removed.append(proj_id) return added, removed
bigcode/self-oss-instruct-sc2-concepts
import base64 def write_to_data_uri(s): """ Writes to a uri. Use this function to embed javascript into the dash app. Adapted from the suggestion by user 'mccalluc' found here: https://community.plotly.com/t/problem-of-linking-local-javascript-file/6955/2 """ uri = ( ('data:;base64,').encode('utf8') + base64.urlsafe_b64encode(s.encode('utf8')) ).decode("utf-8", "strict") return uri
bigcode/self-oss-instruct-sc2-concepts
def cart2(list1: list, list2: list) -> list: """Cartesian product of two lists. :param list list1: input list 1 :param list list2: input list 2 :return: a new list contains all Cartesian products of the two lists. :rtype: list >>> cart2(['a','b'], [1,2]) [['a',1],['a',2],['b',1], ['b',2]] """ def aux(list1: list, list2: list, accum: list) -> list: if len(list1) == 0 or len(list2) == 0: # base case return accum elif len(list1) == 1: # start to traverse list2 return aux(list1, list2[1:], accum + [[list1[0], list2[0]]]) else: return aux(list1[1:], list2, aux([list1[0]], list2, accum)) return aux(list1, list2, [])
bigcode/self-oss-instruct-sc2-concepts
def get_sentences(docs, min_words): """ Given a set of documents we extract all sentences that pass a minimum word threshold ARGS: docs(list of Documents), min_words(int) Returns: sentences(list of Sentences) """ sentences = [] [sentences.extend(doc.get_filtered_sentences(min_words)) for doc in docs] return sentences
bigcode/self-oss-instruct-sc2-concepts