seed
stringlengths
1
14k
source
stringclasses
2 values
def current_ratio(current_assets, current_liabilities, inventory = 0): """Computes current ratio. Parameters ---------- current_assets : int or float Current assets current_liabilities : int or float Current liabilities inventory: int or float Inventory Returns ------- out : int or float Current ratio """ return (current_assets-inventory) / current_liabilities
bigcode/self-oss-instruct-sc2-concepts
def ci(_tuple): """ Combine indices """ return "-".join([str(i) for i in _tuple])
bigcode/self-oss-instruct-sc2-concepts
def base_point_finder(line1, line2, y=720): """ This function calculates the base point of the suggested path by averaging the x coordinates of both detected lines at the highest y value. :param line1: Coefficients of equation of first line in standard form as a tuple. :param line2: Coefficients of equation of second line in standard form as a tuple. :param y: Height value from which base point should be calculated. :return: Tuple representation of the point from which the suggested path will originate. """ x1 = (line1[2] - line1[1] * y) / (line1[0]) x2 = (line2[2] - line2[1] * y) / (line2[0]) x = (x1 + x2) / 2 return int(x), int(y)
bigcode/self-oss-instruct-sc2-concepts
def expand_var(v, env): """ If v is a variable reference (for example: '$myvar'), replace it using the supplied env dictionary. Args: v: the variable to replace if needed. env: user supplied dictionary. Raises: Exception if v is a variable reference but it is not found in env. """ if len(v) == 0: return v # Using len() and v[0] instead of startswith makes this Unicode-safe. if v[0] == '$': v = v[1:] if len(v) and v[0] != '$': if v in env: v = env[v] else: raise Exception('Cannot expand variable $%s' % v) return v
bigcode/self-oss-instruct-sc2-concepts
from typing import List def is_primary_stressed(syllable: List[str]) -> bool: """ Checks if a syllables is primary stressed or not. :param syllable: represented as a list of phonemes :return: True or False """ return True if any(phoneme.endswith('1') for phoneme in syllable) else False
bigcode/self-oss-instruct-sc2-concepts
def count_bad_pixels_per_block(x, y, bad_bins_x, bad_bins_y): """ Calculate number of "bad" pixels per rectangular block of a contact map "Bad" pixels are inferred from the balancing weight column `weight_name` or provided directly in the form of an array `bad_bins`. Setting `weight_name` and `bad_bins` to `None` yields 0 bad pixels in a block. Parameters ---------- x : int block width in pixels y : int block height in pixels bad_bins_x : int number of bad bins on x-side bad_bins_y : int number of bad bins on y-side Returns ------- number_of_pixes : int number of "bad" pixels in a block """ # Calculate the resulting bad pixels in a rectangular block: return (x * bad_bins_y) + (y * bad_bins_x) - (bad_bins_x * bad_bins_y)
bigcode/self-oss-instruct-sc2-concepts
import io def csv_parseln( p_line, delim=',', quote='\"', esc='\\'): """ Given a sample CSV line, this function will parse the line into a list of cells representing that CSV row. If the given `p_line` contains newline characters, only the content present before the first newline character is parsed. :param p_line The string representing the CSV line to parse. This is usually a line in a CSV file obtained via `f.readline()` or of the likes. :param delim The cell delimiter. By default this is the standard comma. :param quote The quote character used to encase complex cell information that may otherwise break the entire CSV structure, for example, by containing an illegal delimiter character. :param esc The escape character used to escape sensitive characters. :return list The list of cells in the given row line. If `p_line` is None, this function does nothing and returns None. If `delim` is None or `quote` is None or `esc` is None, this function throws a ValueError. If len(`delim`) != 1 or len(`quote`) != 1 or len(`esc`) != 1, this function also throws a ValueError. """ if p_line is None: return None if delim is None or quote is None or esc is None: raise ValueError("delim, quote, and/or esc cannot be None") if len(delim) != 1 and len(quote) != 1 and len(esc) != 1: raise ValueError("len of delim, quote, and esc must be 1") cells = [] buf = io.StringIO() in_quote = False esc_next = False for c in p_line: if c == '\n': break if esc_next: buf.write(c) esc_next = False continue if c == esc: esc_next = True continue if c == quote: in_quote = not in_quote continue if c == delim and not in_quote: cells.append(buf.getvalue()) buf = io.StringIO() continue buf.write(c) leftover = buf.getvalue() if len(leftover) > 0: cells.append(leftover) return cells
bigcode/self-oss-instruct-sc2-concepts
def rechunk_da(da, sample_chunks): """ Args: da: xarray DataArray sample_chunks: Chunk size in sample dimensions Returns: da: xarray DataArray rechunked """ lev_str = [s for s in list(da.coords) if 'lev' in s][0] return da.chunk({'sample': sample_chunks, lev_str: da.coords[lev_str].size})
bigcode/self-oss-instruct-sc2-concepts
from typing import List def denormalize_identity(texts: List[str], verbose=False) -> List[str]: """ Identity function. Returns input unchanged Args: texts: input strings Returns input strings """ return texts
bigcode/self-oss-instruct-sc2-concepts
import math def calculate_fuel_requirement_plus(fuel): """Calculates the fuel requirement based on the given fuel mass. (Part 2) Parameters: fuel (int): mass of the fuel Returns: int:Additional fuel required """ add = math.floor(fuel / 3) - 2 if add > 0: return add + calculate_fuel_requirement_plus(add) else: return 0
bigcode/self-oss-instruct-sc2-concepts
def assumed_metric(y_true, y_pred, metric, assume_unlabeled=0, **kwargs): """ This will wrap a metric so that you can pass it in and it will compute it on labeled and unlabeled instances converting unlabeled to assume_unlabeled Assumption: label -1 == unlabled, 0 == negative, 1 == positive """ unlabeled_mask = y_true == -1 y_true_assume = y_true.copy() y_true_assume[unlabeled_mask] = assume_unlabeled # check if a probability, then take the last column and use it (probability of the positive class) if (len(y_pred.shape) > 1): y_pred = y_pred[:,-1] return metric(y_true_assume, y_pred, **kwargs)
bigcode/self-oss-instruct-sc2-concepts
def _HELP_convert_RMSD_nm2angstrom(RMSD_nm): """ Helpfunction for plot_HEATMAP_REX_RMSD(): convert RMSD values: RMSD_nm -> RMSD_anstrom Args: RMSD_nm (list): rmsd values in nm Returns: RMSD (list) rmsd values in angstrom """ RMSD = [x*10 for x in RMSD_nm] return RMSD
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path import json def read_features(corpus_folder): """Read the dictionary of each poem in "corpus_folder" and return the list of python dictionaries :param corpus_folder: Local folder where the corpus is located :return: List of python dictionaries with the poems features """ features_path = Path.cwd() / Path(corpus_folder) / "averell" / "parser" features = [] for json_file in features_path.rglob("*.json"): features.append(json.loads(json_file.read_text())) features = sorted(features, key=lambda i: i['poem_title']) return features
bigcode/self-oss-instruct-sc2-concepts
def static_vars(**kwargs): """ Attach static variables to a function. Usage: @static_vars(k1=v1, k2=k2, ...) def myfunc(...): myfunc.k1... Parameters: **kwargs Keyword=value pairs converted to static variables in decorated function. Returns: decorate """ def decorate(func): for k, v in kwargs.items(): setattr(func, k, v) return func return decorate
bigcode/self-oss-instruct-sc2-concepts
def flatten(iter_of_iters): """ Flatten an iterator of iterators into a single, long iterator, exhausting each subiterator in turn. >>> flatten([[1, 2], [3, 4]]) [1, 2, 3, 4] """ retval = [] for val in iter_of_iters: retval.extend(val) return retval
bigcode/self-oss-instruct-sc2-concepts
def is_number(s): """ Checks if the variable is a number. :param s: the variable :return: True if it is, otherwise False """ try: # Don't need to check for int, if it can pass as a float then it's a number float(s) return True except ValueError: return False
bigcode/self-oss-instruct-sc2-concepts
import math def cond_loglik_bpd(model, x, context): """Compute the log-likelihood in bits per dim.""" return - model.log_prob(x, context).sum() / (math.log(2) * x.shape.numel())
bigcode/self-oss-instruct-sc2-concepts
import threading def create_thread(func, args): """Creates a thread with specified function and arguments""" thread = threading.Thread(target=func, args=args) thread.start() return thread
bigcode/self-oss-instruct-sc2-concepts
def calculate_stretch_factor(array_length_samples, overlap_ms, sr): """Determine stretch factor to add `overlap_ms` to length of signal.""" length_ms = array_length_samples / sr * 1000 return (length_ms + overlap_ms) / length_ms
bigcode/self-oss-instruct-sc2-concepts
def nothing(text: str, expression: str) -> bool: # pylint: disable=unused-argument """Always returns False""" return False
bigcode/self-oss-instruct-sc2-concepts
import requests def read_build_cause(job_url, build_id): """Read cause why the e2e job has been started.""" api_query = job_url + "/" + str(build_id) + "/api/json" response = requests.get(api_query) actions = response.json()["actions"] cause = None for action in actions: if "_class" in action and action["_class"] == "hudson.model.CauseAction": cause = action["causes"][0] # None or real build cause return cause
bigcode/self-oss-instruct-sc2-concepts
import re def to_valid_filename(filename: str) -> str: """Given any string, return a valid filename. For this purpose, filenames are expected to be all lower-cased, and we err on the side of being more restrictive with allowed characters, including not allowing space. Args: filename (str): The input filename. Returns: str: A valid filename. """ return re.sub(r'[^a-z0-9.%_-]+', '-', filename.lower())
bigcode/self-oss-instruct-sc2-concepts
def shapes(tensors): """Get the static shapes of tensors in a list. Arguments: tensors: an iterable of `tf.Tensor`. Returns: a `list` of `tf.TensorShape`, one for each tensor in `tensors`, representing their static shape (via `tf.Tensor.get_shape()`). """ return [t.get_shape() for t in tensors]
bigcode/self-oss-instruct-sc2-concepts
def get_4d_idx(day): """ A small utility function for indexing into a 4D dataset represented as a 3D dataset. [month, level, y, x], where level contains 37 levels, and day contains 28, 29, 30 or 31 days. """ start = 1 + 37 * (day - 1) stop = start + 37 return list(range(start, stop, 1))
bigcode/self-oss-instruct-sc2-concepts
def cookielaw(request): """Add cookielaw context variable to the context.""" cookie = request.COOKIES.get('cookielaw_accepted') return { 'cookielaw': { 'notset': cookie is None, 'accepted': cookie == '1', 'rejected': cookie == '0', } }
bigcode/self-oss-instruct-sc2-concepts
def calculate_offset(address, base, shadow_base=0): """ Calculates an offset between two addresses, taking optional shadow base into consideration. Args: address (int): first address base (int): second address shadow_base (int): mask of shadow address that is applied to `base` Returns: The minimal non-negative offset between `address` and `base` calculated with and without applying the `shadow_base`. """ return min(a - base for a in (address, (address | shadow_base), (address & ~shadow_base)) if a >= base)
bigcode/self-oss-instruct-sc2-concepts
import yaml def get_yaml_dict(yaml_file): """Return a yaml_dict from reading yaml_file. If yaml_file is empty or doesn't exist, return an empty dict instead.""" try: with open(yaml_file, "r") as file_: yaml_dict = yaml.safe_load(file_.read()) or {} return yaml_dict except FileNotFoundError: return {}
bigcode/self-oss-instruct-sc2-concepts
import math def tand(v): """Return the tangent of x (measured in in degrees).""" return math.tan(math.radians(v))
bigcode/self-oss-instruct-sc2-concepts
def cartesian(coords): """ Convert 2D homogeneus/projective coordinates to cartesian. """ return coords[:, :2]
bigcode/self-oss-instruct-sc2-concepts
def getObjectKey(rpcObject): """Given a rpc object, get a unique key that in the form 'class.id' @type rpcObject: grpc.Message @param rpcObject: Rpc object to get a key for @rtype: str @return: String key in the form <class>.<id> """ objectClass = rpcObject.__class__.__name__ objectId = rpcObject.id() return "{}.{}".format(objectClass, objectId)
bigcode/self-oss-instruct-sc2-concepts
import calendar def sort_months(months): """Sort a sequence of months by their calendar order""" month_ref = list(calendar.month_name)[1:] return sorted(months, key=lambda month: month_ref.index(month))
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path import tempfile import venv def create_new_venv() -> Path: """Create a new venv. Returns: path to created venv """ # Create venv venv_dir = Path(tempfile.mkdtemp()) venv.main([str(venv_dir)]) return venv_dir
bigcode/self-oss-instruct-sc2-concepts
def total_seconds(td): """ Return total seconds in timedelta object :param td: timedelta :type td: datetime.timedelta :return: seconds :rtype: float """ return (td.microseconds + (td.seconds + td.days * 86400) * 1000000) / 1000000.0
bigcode/self-oss-instruct-sc2-concepts
import getpass def get_mysql_pwd(config): """Get the MySQL password from the config file or an interactive prompt.""" # Two ways to get the password are supported. # # 1. Read clear-text password from config file. (least secure) # 2. Read password as entered manually from a console prompt. (most secure) # First try the config file. This is the least secure method. Protect the file. #mysql_pwd = config.get('mysql', 'mysql_pwd', 0) mysql_pwd = config['mysql'].get('mysql_pwd') # Try other method if config file password is blank or missing. if mysql_pwd == '': # Prompt for the password. More secure, but won't work unattended. mysql_pwd = getpass.getpass() return(mysql_pwd)
bigcode/self-oss-instruct-sc2-concepts
def resolve_attribute(name, bases, default=None): """Find the first definition of an attribute according to MRO order.""" for base in bases: if hasattr(base, name): return getattr(base, name) return default
bigcode/self-oss-instruct-sc2-concepts
def _get_date_and_time_strings(date): """Return string of YYYYMMDD and time in HHMM format for file access.""" y, m, d, h = [str(i) for i in [date.year, date.month, date.day, date.hour]] # add zeros if needed if len(m) == 1: m = '0' + m if len(d) == 1: d = '0' + d if len(h) == 1: h = '0' + h if len(h) == 2: h += '00' return y+m+d, h
bigcode/self-oss-instruct-sc2-concepts
import typing def format_scopes(scopes: typing.List[str]) -> str: """Format a list of scopes.""" return " ".join(scopes)
bigcode/self-oss-instruct-sc2-concepts
import re def get_size_from_tags(tags): """Searches a tags string for a size tag and returns the size tag. Size tags: spacesuit, extrasmall, small, medium, large, extralarge. """ match = re.search( r'\b(spacesuit|extrasmall|small|medium|large|extralarge)\b', tags ) if match: return match[0] return ''
bigcode/self-oss-instruct-sc2-concepts
def distance_from_camera(bbox, image_shape, real_life_size): """ Calculates the distance of the object from the camera. PARMS bbox: Bounding box [px] image_shape: Size of the image (width, height) [px] real_life_size: Height of the object in real world [cms] """ ## REFERENCE FOR GOPRO # Focal Length and Image Size # https://clicklikethis.com/gopro-sensor-size/ # https://gethypoxic.com/blogs/technical/gopro-hero9-teardown # https://www.sony-semicon.co.jp/products/common/pdf/IMX677-AAPH5_AAPJ_Flyer.pdf # http://photoseek.com/2013/compare-digital-camera-sensor-sizes-full-frame-35mm-aps-c-micro-four-thirds-1-inch-type/ # https://www.gophotonics.com/products/cmos-image-sensors/sony-corporation/21-209-imx677 # Camera Sensor: Sony IMX677 # Camera Sensor array pixel size: 1.12[um] X 1.12[um] # Camera Resolution: 5663(H) X 4223(V) # Camera Sensor dimensions: 6.343[mm/H] X 4.730[mm/V] # Camera Focal Length: 2.92 mm # 5633(px) # 4 ------------------- # 2 - - # 2 - - # 3 - - # (p - - # x) - - # ------------------- # REFERNCE FOR CALCULATION # https://www.scantips.com/lights/subjectdistance.html # GoPro Intrensic Camera Settings # ################################### focal_length_mm = 5.21 unit_pixel_length = 1.12 sen_res = (5663, 4223) sensor_height_mm = (unit_pixel_length*sen_res[1])/1000 sensor_width_mm = (unit_pixel_length*sen_res[0])/1000 ################################### # Calculation image_height_px = image_shape[0] image_width_px = image_shape[1] (startX, startY, endX, endY) = bbox height_of_object_px = endY - startY width_of_object_px = endX - startX obj_height_on_sensor_mm = (sensor_height_mm * height_of_object_px) / image_height_px return (real_life_size * focal_length_mm)/obj_height_on_sensor_mm
bigcode/self-oss-instruct-sc2-concepts
def get_occurences(node, root): """ Count occurences of root in node. """ count = 0 for c in node: if c == root: count += 1 return count
bigcode/self-oss-instruct-sc2-concepts
def snd(tpl): """ >>> snd((0, 1)) 1 """ return tpl[1]
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path from typing import List def get_regions_data(path: Path) -> List[dict]: """Gets base data for a region in a page. :param path: Path to the region directory. :return: List of dictionaries holding base region data. """ regions = list() for region in sorted(path.glob("./*.offset")): region_dict = dict() with region.open("r") as file: (x, y) = file.read().split(",") region_dict["name"] = str(region.stem) region_dict["offset"] = (int(x), int(y)) regions.append(region_dict) return regions
bigcode/self-oss-instruct-sc2-concepts
def get_members_name(member): """Check if member has a nickname on server. Args: member (Union[discord.member.Member, list]): Info about member of guild Returns: str: User's name, if user doesn't have a nickname and otherwise list: List of names of user's nicknames """ if isinstance(member, list): members_data = [] for m in member: members_data.append(m.name if not m.nick else m.nick) return members_data return member.name if not member.nick else member.nick
bigcode/self-oss-instruct-sc2-concepts
def find_layer_idx(model, layer_name): """Looks up the layer index corresponding to `layer_name` from `model`. Args: model: The `keras.models.Model` instance. layer_name: The name of the layer to lookup. Returns: The layer index if found. Raises an exception otherwise. """ layer_idx = None for idx, layer in enumerate(model.layers): if layer.name == layer_name: layer_idx = idx break if layer_idx is None: raise ValueError("No layer with name '{}' within the model".format(layer_name)) return layer_idx
bigcode/self-oss-instruct-sc2-concepts
def _start_time_from_groupdict(groupdict): """Convert the argument hour/minute/seconds minute into a millisecond value. """ if groupdict['hours'] is None: groupdict['hours'] = 0 return (int(groupdict['hours']) * 3600 + int(groupdict['minutes']) * 60 + int(groupdict['seconds'])) * 1000
bigcode/self-oss-instruct-sc2-concepts
def frame_to_pattern(frame_path): """Convert frame count to frame pattern in an image file path. Args: frame_path (str): Path of an image file with frame count. Returns: str: Path of an image sequence with frame pattern. """ name_list = frame_path.split('.') name_list[-2] = '%04d' return '.'.join(name_list).replace('\\', '/')
bigcode/self-oss-instruct-sc2-concepts
import math def visibility(nov, nol, a): """Compute visibility using height-correlated GGX. Heitz 2014, "Understanding the Masking-Shadowing Function in Microfacet-Based BRDFs" Args: nov: Normal dot view direction. nol: Normal dot light direction. a: Linear roughness. Returns: The geometric visibility (V) term. """ a2 = a * a ggxl = nov * math.sqrt((nol - nol * a2) * nol + a2) ggxv = nol * math.sqrt((nov - nov * a2) * nov + a2) return 0.5 / (ggxv + ggxl)
bigcode/self-oss-instruct-sc2-concepts
def flip(res): """flips 'x', 'o' or 'draw'.""" if res == 'x': return 'o' elif res == 'o': return 'x' elif res == 'draw': return 'draw' else: raise RuntimeError("Invalid res: %s" % str(res))
bigcode/self-oss-instruct-sc2-concepts
import math def calculate_tail_correction(box_legth, n_particles, cutoff): """ Calculates the tail correction Parameters ---------- box_legth : float The distance between the particles in reduced units. n_particles : int The number of particles. cutoff : float The cutoff value. """ pi_term = (8 * math.pi * math.pow(n_particles, 2)) / (3 * math.pow(box_legth, 3)) r9_term = (1/3) * (math.pow(1/cutoff, 9)) r3_term = math.pow(1/cutoff, 3) tail_correction = pi_term * (r9_term - r3_term) return tail_correction
bigcode/self-oss-instruct-sc2-concepts
def getPdbCifLink(pdb_code): """Returns the html path to the cif file on the pdb server """ file_name = pdb_code + '.cif' pdb_loc = 'https://files.rcsb.org/download/' + file_name return file_name, pdb_loc
bigcode/self-oss-instruct-sc2-concepts
def prep_sub_id(sub_id_input): """Processes subscription ID Args: sub_id_input: raw subscription id Returns: Processed subscription id """ if not isinstance(sub_id_input, str): return "" if len(sub_id_input) == 0: return "" return "{" + sub_id_input.strip().upper() + "}"
bigcode/self-oss-instruct-sc2-concepts
def nth_eol(src, lineno): """ Compute the ending index of the n-th line (before the newline, where n is 1-indexed) >>> nth_eol("aaa\\nbb\\nc", 2) 6 """ assert lineno >= 1 pos = -1 for _ in range(lineno): pos = src.find('\n', pos + 1) if pos == -1: return len(src) return pos
bigcode/self-oss-instruct-sc2-concepts
import requests def get_online_person(params=None, **kwargs) -> bytes: """Get a picture of a fictional person from the ThisPersonDoesNotExist webpage. :param params: params dictionary used by requests.get :param kwargs: kwargs used by requests.get :return: the image as bytes """ r = requests.get("https://thispersondoesnotexist.com/image", headers={'User-Agent': 'My User Agent 1.0'}).content return r
bigcode/self-oss-instruct-sc2-concepts
def cols_to_count(df, group, columns): """Count the number of column values when grouping by another column and return new columns in original dataframe. Args: df: Pandas DataFrame. group: Column name to groupby columns: Columns to count. Returns: Original DataFrame with new columns containing prefixed count values. """ for col in columns: df['count_' + col + '_by_' + group] = df.groupby(group)[col].transform('count') return df
bigcode/self-oss-instruct-sc2-concepts
import math def calcVector(p1,p2): """ calculate a line vector in polar form from two points. The return is the length of the line and the slope in degrees """ dx = p2[0]-p1[0] dy = p2[1]-p1[1] mag = math.sqrt(dx * dx + dy * dy) theta = math.atan2(dy,dx) * 180.0 / math.pi + 90.0 return mag,theta
bigcode/self-oss-instruct-sc2-concepts
def striplines(text): """ Remove all leading/trailing whitespaces from lines and blank lines. """ return "\n".join( line.strip() for line in text.splitlines() if len(line.strip()) )
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def ms_since_epoch(dt): """ Get the milliseconds since epoch until specific a date and time. Args: dt (datetime): date and time limit. Returns: int: number of milliseconds. """ return (dt - datetime(1970, 1, 1)).total_seconds() * 1000
bigcode/self-oss-instruct-sc2-concepts
import re def slugify(s): """ Simplifies ugly strings into something URL-friendly. >>> print slugify("[Some] _ Article's Title--") some-articles-title """ # "[Some] _ Article's Title--" # "[some] _ article's title--" s = s.lower() # "[some] _ article's_title--" # "[some]___article's_title__" for c in [' ', '-', '.', '/']: s = s.replace(c, '_') # "[some]___article's_title__" # "some___articles_title__" s = re.sub('\W', '', s) # "some___articles_title__" # "some articles title " s = s.replace('_', ' ') # "some articles title " # "some articles title " s = re.sub('\s+', ' ', s) # "some articles title " # "some articles title" s = s.strip() # "some articles title" # "some-articles-title" s = s.replace(' ', '-') return s
bigcode/self-oss-instruct-sc2-concepts
import linecache def get_title(notes_path, file_stem): """ Get the title by reading the second line of the .md file """ title = linecache.getline(notes_path + file_stem + '.md', 2) title = title.replace('\n', '') title = title.replace('title: ', '') return title
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Dict from typing import Any def sew_messages_and_reactions( messages: List[Dict[str, Any]], reactions: List[Dict[str, Any]] ) -> List[Dict[str, Any]]: """Given a iterable of messages and reactions stitch reactions into messages. """ # Add all messages with empty reaction item for message in messages: message["reactions"] = [] # Convert list of messages into dictionary to make reaction stitching easy converted_messages = {message["id"]: message for message in messages} for reaction in reactions: converted_messages[reaction["message_id"]]["reactions"].append(reaction) return list(converted_messages.values())
bigcode/self-oss-instruct-sc2-concepts
def get_timing(line: str) -> str: """ Returns the stimulus timing from a line of text grabbed from a .vmrk file. """ return line.split(",")[2]
bigcode/self-oss-instruct-sc2-concepts
def empty_string_check(string, raise_exception=True): """ Simple check to see if the string provided by parameter string is empty. False indicates the string is NOT empty. Parameter raise_exception determines if a ValueError exception should be raised if the string is empty. If raise_exception is False and the string is empty, True is returned. """ if string != '': return False if raise_exception: raise ValueError("Empty string detected!") return True
bigcode/self-oss-instruct-sc2-concepts
def get_public_key_from_x509cert_obj(x509cert) -> bytes: """ returns a RSA public key object from a x509 certificate object """ return x509cert.public_key()
bigcode/self-oss-instruct-sc2-concepts
import re def cap_case_str(s): """ Translate a string like "foo_Bar-baz whee" and return "FooBarBazWhee". """ return re.sub(r'(?:[^a-z0-9]+|^)(.)', lambda m: m.group(1).upper(), s, flags=re.IGNORECASE)
bigcode/self-oss-instruct-sc2-concepts
def transfer_mac(mac): """Transfer MAC address format from xxxx.xxxx.xxxx to xx:xx:xx:xx:xx:xx""" mac = ''.join(mac.split('.')) rslt = ':'.join([mac[e:e + 2] for e in range(0, 11, 2)]) return rslt
bigcode/self-oss-instruct-sc2-concepts
def make_name(key): """Return a string suitable for use as a python identifer from an environment key.""" return key.replace('PLATFORM_', '').lower()
bigcode/self-oss-instruct-sc2-concepts
def get_crowd_selection_counts(input_id, task_runs_json_object): """ Figure out how many times the crowd selected each option :param input_id: the id for a given task :type input_id: int :param task_runs_json_object: all of the input task_runs from json.load(open('task_run.json')) :type task_runs_json_object: list :return: number of responses for each selection :rtype: dict """ counts = {'n_nop_res': 0, 'n_unk_res': 0, 'n_pad_res': 0, 'ERROR': 0} for task_run in task_runs_json_object: if input_id == task_run['task_id']: try: selection = task_run['info']['selection'] except KeyError: selection = 'ERROR' if selection == 'nopad': counts['n_nop_res'] += 1 elif selection == 'unknown': counts['n_unk_res'] += 1 elif selection == 'pad': counts['n_pad_res'] += 1 else: counts['ERROR'] += 1 return counts
bigcode/self-oss-instruct-sc2-concepts
def _GetSupportedApiVersions(versions, runtime): """Returns the runtime-specific or general list of supported runtimes. The provided 'versions' dict contains a field called 'api_versions' which is the list of default versions supported. This dict may also contain a 'supported_api_versions' dict which lists api_versions by runtime. This function will prefer to return the runtime-specific api_versions list, but will default to the general list. Args: versions: dict of versions from app.yaml or /api/updatecheck server. runtime: string of current runtime (e.g. 'go'). Returns: List of supported api_versions (e.g. ['go1']). """ if 'supported_api_versions' in versions: return versions['supported_api_versions'].get( runtime, versions)['api_versions'] return versions['api_versions']
bigcode/self-oss-instruct-sc2-concepts
def build_hugo_links(links: list) -> list: """ Extens the passed wiki links list by adding a dict key for the hugo link. """ for link in links: link['hugo_link'] = f'[{link["text"]}]({{{{< ref "{link["link"]}" >}}}})' return links
bigcode/self-oss-instruct-sc2-concepts
def _is_digit_power_sum(number: int, power: int) -> bool: """ Returns whether a number is equal to the sum of its digits to the given power """ return number == sum(d ** power for d in map(int, str(number)))
bigcode/self-oss-instruct-sc2-concepts
def get_achievement(dist): """Получить поздравления за пройденную дистанцию.""" # В уроке «Строки» вы описали логику # вывода сообщений о достижении в зависимости # от пройденной дистанции. # Перенесите этот код сюда и замените print() на return. if dist >= 6.5: return 'Отличный результат! Цель достигнута.' elif dist >= 3.9: return 'Неплохо! День был продуктивным.' elif dist >= 2: return 'Маловато, но завтра наверстаем!' else: return 'Лежать тоже полезно. Главное — участие, а не победа!'
bigcode/self-oss-instruct-sc2-concepts
def support(node): """Get support value of a node. Parameters ---------- node : skbio.TreeNode node to get support value of Returns ------- float or None support value of the node, or None if not available Notes ----- A "support value" is defined as the numeric form of a whole node label without ":", or the part preceding the first ":" in the node label. - For examples: "(a,b)1.0", "(a,b)1.0:2.5", and "(a,b)'1.0:species_A'". In these cases the support values are all 1.0. - For examples: "(a,b):1.0" and "(a,b)species_A". In these cases there are no support values. Examples -------- >>> from skbio import TreeNode >>> tree = TreeNode.read(['((a,b)99,(c,d):1.0);']) >>> support(tree.lca(['a', 'b'])) 99.0 >>> support(tree.lca(['c', 'd'])) is None True """ try: return float(node.name.split(':')[0]) except (ValueError, AttributeError): return None
bigcode/self-oss-instruct-sc2-concepts
def merge_sort(sorted_l1, sorted_l2): """ Merge sorting two sorted array """ result = [] i = 0 j = 0 while i < len(sorted_l1) and j < len(sorted_l2): if sorted_l1[i] < sorted_l2[j]: result.append(sorted_l1[i]) i += 1 else: result.append(sorted_l2[j]) j += 1 while i < len(sorted_l1): result.append(sorted_l1[i]) i += 1 while j < len(sorted_l2): result.append(sorted_l2[j]) j += 1 return result
bigcode/self-oss-instruct-sc2-concepts
def construct_html(search_term, results): """ Given a list of results, construct the HTML page. """ link_format = '<a href="{0.img_url}"><img src="{0.thumb_url}" alt="{0.name}" title="{0.name}"></a>' html_links = '\n'.join([link_format.format(result) for result in results]) html_output = ( '<html>' '<head><title>{search_term} pictures</title></head>' '<body>' '<h1>&ldquo;{search_term}&rdquo; pictures</h1>' '{html_links}' '</body>' '</html>' ).format(search_term=search_term, html_links=html_links) return html_output
bigcode/self-oss-instruct-sc2-concepts
def split_by_comma(s): """ Split a string by comma, trim each resultant string element, and remove falsy-values. :param s: str to split by comma :return: list of provided string split by comma """ return [i.strip() for i in s.split(",") if i]
bigcode/self-oss-instruct-sc2-concepts
def compute_resource_attributes(decos, compute_deco, resource_defaults): """ Compute resource values taking into account defaults, the values specified in the compute decorator (like @batch or @kubernetes) directly, and resources specified via @resources decorator. Returns a dictionary of resource attr -> value (str). """ assert compute_deco is not None # Use the value from resource_defaults by default result = {k: v for k, v in resource_defaults.items()} for deco in decos: # If resource decorator is used if deco.name == "resources": for k, v in deco.attributes.items(): # ..we use the larger of @resources and @batch attributes my_val = compute_deco.attributes.get(k) if not (my_val is None and v is None): result[k] = str(max(int(my_val or 0), int(v or 0))) return result # If there is no resources decorator, values from compute_deco override # the defaults. for k, v in resource_defaults.items(): if compute_deco.attributes.get(k): result[k] = str(compute_deco.attributes[k]) return result
bigcode/self-oss-instruct-sc2-concepts
import glob def get_file_list(file_type): """ Returns a list of all files to be processed :param file_type: string - The type to be used: crash, charges, person, primaryperson, unit :return: array """ return glob.glob("/data/extract_*_%s_*.csv" % file_type)
bigcode/self-oss-instruct-sc2-concepts
def _ns(obj, search): """Makes searching via namespace slightly easier.""" return obj.xpath(search, namespaces={'aws':'http://www.aws.com/aws'})
bigcode/self-oss-instruct-sc2-concepts
def clustering(cloud, tol, min_size, max_size): """ Input parameters: cloud: Input cloud tol: tolerance min_size: minimal number of points to form a cluster max_size: maximal number of points that a cluster allows Output: cluster_indices: a list of list. Each element list contains the indices of the points that belongs to the same cluster """ tree = cloud.make_kdtree() ec = cloud.make_EuclideanClusterExtraction() ec.set_ClusterTolerance(tol) ec.set_MinClusterSize(min_size) ec.set_MaxClusterSize(max_size) ec.set_SearchMethod(tree) cluster_indices = ec.Extract() return cluster_indices
bigcode/self-oss-instruct-sc2-concepts
def findInEdges(nodeNum, edges, att=None): """ Find the specified node index in either node_i or node_j columns of input edges df. Parameters ---------- nodeNum : int This is the node index not protein index. edges : pandas dataframe Dataframe in which to search for node. Returns ------- pandas dataframe """ edges = edges.copy() if att is not None: return edges[(edges.attribute == att) & ((edges.node_i == nodeNum) | (edges.node_j == nodeNum))] else: return edges[(edges.node_i == nodeNum) | (edges.node_j == nodeNum)]
bigcode/self-oss-instruct-sc2-concepts
from functools import reduce def deepGetAttr(obj, path): """ Resolves a dot-delimited path on an object. If path is not found an `AttributeError` will be raised. """ return reduce(getattr, path.split('.'), obj)
bigcode/self-oss-instruct-sc2-concepts
def tokenize(sent, bert_tok): """Return tokenized sentence""" return ' '.join(bert_tok.tokenize(sent))
bigcode/self-oss-instruct-sc2-concepts
def get_mask_from_lengths(memory, memory_lengths): """Get mask tensor from list of length Args: memory: (batch, max_time, dim) memory_lengths: array like """ mask = memory.data.new(memory.size(0), memory.size(1)).byte().zero_() for idx, l in enumerate(memory_lengths): mask[idx][:l] = 1 return ~mask
bigcode/self-oss-instruct-sc2-concepts
import math def _get_burst_docids(dtd_matrix, burst_loc, burst_scale): """ Given a burst and width of an event burst, retrieve all documents published within that burst, regardless of whether they actually concern any event. :param dtd_matrix: document-to-day matrix :param burst_loc: location of the burst :param burst_scale: scale of the burst :return: start day of the burst, end day of the burst, indices of documents within the burst """ n_days = dtd_matrix.shape[1] # If an event burst starts right at day 0, this would get negative. burst_start = max(math.floor(burst_loc - burst_scale), 0) # If an event burst ends at stream length, this would exceed the boundary. burst_end = min(math.ceil(burst_loc + burst_scale), n_days - 1) # All documents published on burst days. There is exactly one '1' in every row. burst_docs, _ = dtd_matrix[:, burst_start:burst_end + 1].nonzero() return burst_start, burst_end, burst_docs
bigcode/self-oss-instruct-sc2-concepts
def split_by_commas(string): """Split a string by unenclosed commas. Splits a string by commas that are not inside of: - quotes - brackets Arguments: string {String} -- String to be split. Usuall a function parameter string Examples: >>> split_by_commas('foo, bar(baz, quux), fwip = "hey, hi"') ['foo', 'bar(baz, quux)', 'fwip = "hey, hi"'] Returns: {list} List of elements in the string that were delimited by commas """ out = [] if not string: return out # the current token current = '' # characters which open a section inside which commas are not separators between different # arguments open_quotes = '"\'<({' # characters which close the section. The position of the character here should match the # opening indicator in `open_quotes` close_quotes = '"\'>)}' matching_quote = '' inside_quotes = False is_next_literal = False for char in string: if is_next_literal: # previous char was a \ current += char is_next_literal = False elif inside_quotes: if char == '\\': is_next_literal = True else: current += char if char == matching_quote: inside_quotes = False else: if char == ',': out.append(current.strip()) current = '' else: current += char quote_index = open_quotes.find(char) if quote_index > -1: matching_quote = close_quotes[quote_index] inside_quotes = True out.append(current.strip()) return out
bigcode/self-oss-instruct-sc2-concepts
def drop_null_values(df): """ Drop records with NaN values. """ df = df.dropna() return df
bigcode/self-oss-instruct-sc2-concepts
def run_checks(checks): """ Run a number of checks. :param tuple checks: a tuple of tuples, with check name and parameters dict. :returns: whether all checks succeeded, and the results of each check :rtype: tuple of (bool, dict) """ results = {} all_succeeded = True for check, kwargs in checks: succeeded = check(**kwargs).succeeded if isinstance(succeeded, bool): if not succeeded: all_succeeded = False results[check.__name__] = succeeded elif isinstance(succeeded, tuple): if not succeeded[0]: all_succeeded = False results[check.__name__] = succeeded return (all_succeeded, results)
bigcode/self-oss-instruct-sc2-concepts
import pickle def read_raw_results(results_file): """ Read the raw results from the pickle file. Parameters: - results_file: the path to the pickle file. Return: - results: a dictionary of objects. """ results = None with open(results_file, 'rb') as f: results = pickle.load(f) return results
bigcode/self-oss-instruct-sc2-concepts
import calendar def totimestamp(value): """ convert a datetime into a float since epoch """ return int(calendar.timegm(value.timetuple()) * 1000 + value.microsecond / 1000)
bigcode/self-oss-instruct-sc2-concepts
def error_format(search): """ :param search: inputted word :return: bool. Checking every element in the inputted word is in alphabet. """ for letter in search: if letter.isalpha() is False: return True
bigcode/self-oss-instruct-sc2-concepts
import re def from_dms(dms_string): """ Converts a string from sexagesimal format to a numeric value, in the same units as the major unit of the sexagesimal number (typically hours or degrees). The value can have one, two, or three fields representing hours/degrees, minutes, and seconds respectively. Fields can be separated by any consecutive number of the following characters: :, _, d, h, m, s, or space This allows the following types of inputs (as examples): "3.5" "3 30.2" "3:40:55.6" "3h 22m 45s" "-20 30 40.5" """ dms_string = str(dms_string) # So we can technically accept floats and ints as well SEPARATORS = ": _dhms" dms_string = dms_string.strip() sign = 1 if dms_string.startswith("-"): sign = -1 dms_string = dms_string[1:] separator_regex = '[' + SEPARATORS + ']+' # One or more of any of the separator characters fields = re.split(separator_regex, dms_string) # In case of input like "3h30m" or "6d 10m 04.5s", split() will produce an empty # field following the final separator character. If one exists, strip it out. if fields[-1] == '': fields = fields[:-1] value = float(fields[0]) if len(fields) > 1: value += float(fields[1]) / 60.0 if len(fields) > 2: value += float(fields[2]) / 3600.0 if len(fields) > 3: raise ValueError("Too many fields in sexagesimal number") return sign*value
bigcode/self-oss-instruct-sc2-concepts
def qualify_name(name_or_qname, to_kind): """ Formats a name or qualified name (kind/name) into a qualified name of the specified target kind. :param name_or_qname: The name to transform :param to_kind: The kind to apply :return: A qualified name like: kind/name """ if '/' in name_or_qname: name_or_qname = name_or_qname.split('/')[-1] return '{}/{}'.format(to_kind, name_or_qname)
bigcode/self-oss-instruct-sc2-concepts
import typing def linear_search(arr: typing.List[int], target: int) -> int: """ Performs a linear search through arr. This is O(N) as worst case the last element in arr will need to be checked :param arr: The sequence of integers :param target: The target number to retrieve the index of. :return: the index of target; or -1 if target is not `in` arr. """ for idx, n in enumerate(arr): if n == target: return idx return -1
bigcode/self-oss-instruct-sc2-concepts
import math def distance(x0, y0, x1, y1): """Return the coordinate distance between 2 points""" dist = math.hypot((x1-x0),(y1-y0)) return dist
bigcode/self-oss-instruct-sc2-concepts
def r_squared(measured, predicted): """Assumes measured a one-dimensional array of measured values predicted a one-dimensional array of predicted values Returns coefficient of determination""" estimated_error = ((predicted - measured)**2).sum() mean_of_measured = measured.sum()/len(measured) variability = ((measured - mean_of_measured)**2).sum() return 1 - estimated_error/variability
bigcode/self-oss-instruct-sc2-concepts
def compute_gcvf(sdam: float, scdm: float) -> float: """ Compute the goodness of class variance fit (GCVF). :param sdam: Sum of squared deviations for array mean (SDAM) :param scdm: Sum of squared class devations from mean (SCDM) :return: GCVF Sources: https://arxiv.org/abs/2005.01653 https://medium.com/analytics-vidhya/jenks-natural-breaks-best-range-finder-algorithm-8d1907192051 """ return (sdam - scdm) / sdam
bigcode/self-oss-instruct-sc2-concepts
def bind(func, *args): """ Returns a nullary function that calls func with the given arguments. """ def noarg_func(): return func(*args) return noarg_func
bigcode/self-oss-instruct-sc2-concepts
def read_fasta(fasta): """ Read the protein sequences in a fasta file Parameters ----------- fasta : str Filename of fasta file containing protein sequences Returns ---------- (list_of_headers, list_of_sequences) : tuple A tuple of corresponding lists of protein descriptions and protein sequences in the fasta file """ with open(fasta, 'r') as fastaobject: headers, sequences = [], [] for line in fastaobject: if line.startswith('>'): head = line.replace('>','').strip() headers.append(head) sequences.append('') else : seq = line.strip() if len(seq) > 0: sequences[-1] += seq return (headers, sequences)
bigcode/self-oss-instruct-sc2-concepts
def get_service_at_index(asset, index): """Gets asset's service at index.""" matching_services = [s for s in asset.services if s.index == int(index)] if not matching_services: return None return matching_services[0]
bigcode/self-oss-instruct-sc2-concepts
def count(pets): """Return count from queryset.""" return pets.count()
bigcode/self-oss-instruct-sc2-concepts