seed
stringlengths
1
14k
source
stringclasses
2 values
def is_valid_id(id): """Check if id is valid. """ parts = id.split(':') if len(parts) == 3: group, artifact, version = parts if group and artifact and version: return True return False
bigcode/self-oss-instruct-sc2-concepts
def STD_DEV_SAMP(*expression): """ Calculates the sample standard deviation of the input values. Use if the values encompass a sample of a population of data from which to generalize about the population. See https://docs.mongodb.com/manual/reference/operator/aggregation/stdDevSamp/ for more details :param expression: expression/expressions :return: Aggregation operator """ return {'$stdDevSamp': list(expression)} if len(expression) > 1 else {'$stdDevSamp': expression[0]} if expression else {}
bigcode/self-oss-instruct-sc2-concepts
def misclassification_percentage(y_true, y_pred): """ Returns misclassification percentage ( misclassified_examples / total_examples * 100.0) """ misclassified_examples = list(y_true == y_pred).count(False) * 1. total_examples = y_true.shape[0] return (misclassified_examples / total_examples) * 100.0
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterable def _unique(*args: Iterable) -> list: """Return a list of all unique values, in order of first appearance. Args: args: Iterables of values. Examples: >>> _unique([0, 2], (2, 1)) [0, 2, 1] >>> _unique([{'x': 0, 'y': 1}, {'y': 1, 'x': 0}], [{'z': 2}]) [{'x': 0, 'y': 1}, {'z': 2}] """ values = [] for parent in args: for child in parent: if child not in values: values.append(child) return values
bigcode/self-oss-instruct-sc2-concepts
def linear_function(m, x, b): """ A linear function of one variable x with slope m and and intercept b. """ return m * x + b
bigcode/self-oss-instruct-sc2-concepts
import functools def dgetattr(obj, name, is_dict=False): """ get deep attribute operates the same as getattr(obj, name) but can use '.' for nested attributes e.g. dgetattr(my_object, 'a.b') would return value of my_object.a.b """ atr = dict.__getitem__ if is_dict else getattr names = name.split('.') names = [obj] + names return functools.reduce(atr, names)
bigcode/self-oss-instruct-sc2-concepts
import json from pathlib import Path def get_total_epochs(save_path, run, last_gen): """ Compute the total number of performed epochs. Parameters ---------- save_path: str path where the ojects needed to resume evolution are stored. run : int current evolutionary run last_gen : int count the number of performed epochs until the last_gen generation Returns ------- total_epochs : int sum of the number of epochs performed by all trainings """ total_epochs = 0 for gen in range(0, last_gen+1): j = json.load(open(Path('%s/run_%d/gen_%d.csv' % (save_path, run, gen)))) num_epochs = [elm['num_epochs'] for elm in j] total_epochs += sum(num_epochs) return total_epochs
bigcode/self-oss-instruct-sc2-concepts
def filter_same_tokens(tokens): """ Function for filtering repetitions in tokens. :param tokens: list with str List of tokens for filtering. :return: Filtered list of tokens without repetitions. """ if not isinstance(tokens, list): raise TypeError for token in tokens: if not isinstance(token, str): raise TypeError tmp_set = set(tokens) return [token for token in tmp_set]
bigcode/self-oss-instruct-sc2-concepts
import json def loads(json_str): """Load an object from a JSON string""" return json.loads(json_str)
bigcode/self-oss-instruct-sc2-concepts
def tag_case(tag, uppercased, articles): """ Changes a tag to the correct title case while also removing any periods: 'U.S. bureau Of Geoinformation' -> 'US Bureau of Geoinformation'. Should properly upper-case any words or single tags that are acronyms: 'ugrc' -> 'UGRC', 'Plss Fabric' -> 'PLSS Fabric'. Any words separated by a hyphen will also be title-cased: 'water-related' -> 'Water-Related'. Note: No check is done for articles at the begining of a tag; all articles will be lowercased. tag: The single or multi-word tag to check uppercased: Lower-cased list of words that should be uppercased (must be lower-cased to facilitate checking) articles: Lower-cased list of words that should always be lower-cased: 'in', 'of', etc """ new_words = [] for word in tag.split(): cleaned_word = word.replace('.', '') #: Upper case specified words: if cleaned_word.lower() in uppercased: new_words.append(cleaned_word.upper()) #: Lower case articles/conjunctions elif cleaned_word.lower() in articles: new_words.append(cleaned_word.lower()) #: Title case everything else else: new_words.append(cleaned_word.title()) return ' '.join(new_words)
bigcode/self-oss-instruct-sc2-concepts
def link_album(album_id): """Generates a link to an album Args: album_id: ID of the album Returns: The link to that album on Spotify """ return "https://open.spotify.com/album/" + album_id
bigcode/self-oss-instruct-sc2-concepts
def fetch_seq_pygr(chr, start, end, strand, genome): """Fetch a genmoic sequence upon calling `pygr` `genome` is initialized and stored outside the function Parameters ---------- chr : str chromosome start : int start locus end : int end locuse strand : str either '+' or '-' Returns -------- seq : str genomic sequence in upper cases """ try: seq = genome[chr][start:end] if strand == "-": seq = -seq except Exception as e: raise Exception('pygr cannot fetch sequences; %s' % e) return str(seq).upper()
bigcode/self-oss-instruct-sc2-concepts
def compute_metrics(y_true, y_pred, metrics): """ Computation of a given metric Parameters ---------- y_true: True values for y y_pred: Predicted values for y. metrics: metric Chosen performance metric to measure the model capabilities. Returns ------- dict Performance metric and its value""" return {metric_name: func(y_true, y_pred) for metric_name, func in metrics.items()}
bigcode/self-oss-instruct-sc2-concepts
def centerOfGravity( array ): """ Vypočítá ze zadaých bodů jejich těžiště. Parametry: ---------- array: list Pole s body. Vrací: ----- list Pole s X- a Y-ovou souřadnicí těžiště. """ sum_X = 0 sum_Y = 0 # Sečte X-ové a Y-ové souřadnice všech bodů for element in array: sum_X += element[0] sum_Y += element[1] # Vratí průměr. return sum_X/len(array), sum_Y/len(array)
bigcode/self-oss-instruct-sc2-concepts
def rk4(y, x, dx, f): """computes 4th order Runge-Kutta for dy/dx. y is the initial value for y x is the initial value for x dx is the difference in x (e.g. the time step) f is a callable function (y, x) that you supply to compute dy/dx for the specified values. """ k1 = dx * f(y, x) k2 = dx * f(y + 0.5*k1, x + 0.5*dx) k3 = dx * f(y + 0.5*k2, x + 0.5*dx) k4 = dx * f(y + k3, x + dx) return y + (k1 + 2*k2 + 2*k3 + k4) / 6.
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Any def add_parser_options(options: Dict[str, Dict[str, Any]], parser_id: str, parser_options: Dict[str, Dict[str, Any]], overwrite: bool = False): """ Utility method to add options for a given parser, to the provided options structure :param options: :param parser_id: :param parser_options: :param overwrite: True to silently overwrite. Otherwise an error will be thrown :return: """ if parser_id in options.keys() and not overwrite: raise ValueError('There are already options in this dictionary for parser id ' + parser_id) options[parser_id] = parser_options return options
bigcode/self-oss-instruct-sc2-concepts
from typing import List def distributed_axial(w:float, L:float, l1:float, l2:float) -> List[float]: """ Case 6 from Matrix Analysis of Framed Structures [Aslam Kassimali] """ Fa = w/(2*L) * (L-l1-l2) * (L-l1+l2) Fb = w/(2*L) * (L-l1-l2) * (L+l1-l2) return [Fa, Fb]
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def parse_time(time_string): """Parse a time string from the config into a :class:`datetime.time` object.""" formats = ['%I:%M %p', '%H:%M', '%H:%M:%S'] for f in formats: try: return datetime.strptime(time_string, f).time() except ValueError: continue raise ValueError('invalid time `%s`' % time_string)
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def format_link_object(url: str, text: str) -> Dict[str, str]: """ Formats link dictionary object. """ return {"href": url, "text": text}
bigcode/self-oss-instruct-sc2-concepts
def mul(args): """ Multiply the all the numbers in the list Args(list): A list of number Return(int or float): The computing result """ result = 1 for num in args: result *= num return result
bigcode/self-oss-instruct-sc2-concepts
import base64 def ddb_to_json(ddb_item): """Convert a DDB item to a JSON-compatible format. For now, this means encoding any binary fields as base64. """ json_item = ddb_item.copy() for attribute in json_item: for value in json_item[attribute]: if value == "B": json_item[attribute][value] = base64.b64encode(json_item[attribute][value]).decode("utf-8") return json_item
bigcode/self-oss-instruct-sc2-concepts
import pwd def valid_user(username): """ Returns True if the username given is a valid username on the system """ try: if username and pwd.getpwnam(username): return True except KeyError: # getpwnam returns a key error if entry isn't present return False return False
bigcode/self-oss-instruct-sc2-concepts
import time def datetime_to_timestamp(a_date): """Transform a datetime.datetime to a timestamp microseconds are lost ! :type a_date: datetime.datetime :rtype: float """ return time.mktime(a_date.timetuple())
bigcode/self-oss-instruct-sc2-concepts
import asyncio async def check_address(host: str, port: int = 80, timeout: int = 2) -> bool: """ Async version of test if an address (IP) is reachable. Parameters: host: str host IP address or hostname port : int HTTP port number Returns ------- awaitable bool """ try: reader, writer = await asyncio.wait_for( asyncio.open_connection(host, port), timeout=timeout ) writer.close() await writer.wait_closed() return True except: return False
bigcode/self-oss-instruct-sc2-concepts
def convert_distance(val, old_scale="meter", new_scale="centimeter"): """ Convert from a length scale to another one among meter, centimeter, inch, feet, and mile. Parameters ---------- val: float or int Value of the length to be converted expressed in the original scale. old_scale: str Original scale from which the length value will be converted. Supported scales are Meter ['Meter', 'meter', 'm'], Centimeter ['Centimeter', 'centimeter', 'vm'], Inch ['Inch', 'inch', 'in'], Feet ['Feet', 'feet', 'ft'] or Mile ['Mile', 'mile', 'mil']. new_scale: str New scale from which the length value will be converted. Supported scales are Meter ['Meter', 'meter', 'm'], Centimeter ['Centimeter', 'centimeter', 'cm'], Inch ['Inch', 'inch', 'in'], Feet ['Feet', 'feet', 'ft'] or Mile ['Mile', 'mile', 'mil']. Raises ------- NotImplementedError if either of the scales are not one of the requested ones. Returns ------- res: float Value of the converted length expressed in the new scale. """ # Convert from 'old_scale' to Meter if old_scale.lower() in ['centimeter', 'cm']: temp = val / 100.0 elif old_scale.lower() in ['meter', 'm']: temp = val elif old_scale.lower() in ['inch', 'in']: temp = val / 39.37008 elif old_scale.lower() in ['feet', 'ft']: temp = val / 3.28084 elif old_scale.lower() in ['mile', 'mil']: temp = 1609.344 * val else: raise AttributeError( f'{old_scale} is unsupported. m, cm, ft, in and mile are supported') # and from Meter to 'new_scale' if new_scale.lower() in ['centimeter', 'cm']: result = 100*temp elif new_scale.lower() in ['meter', 'm']: result = temp elif new_scale.lower() in ['inch', 'in']: result= 39.37008*temp elif new_scale.lower() in ['feet', 'ft']: result=3.28084*temp elif new_scale.lower() in ['mile', 'mil']: result=temp/1609.344 else: raise AttributeError( f'{new_scale} is unsupported. m, cm, ft, in and mile are supported') return result
bigcode/self-oss-instruct-sc2-concepts
def get_cell_connection(cell, pin): """ Returns the name of the net connected to the given cell pin. Returns None if unconnected """ # Only for subckt assert cell["type"] == "subckt" # Find the connection and return it for i in range(1, len(cell["args"])): p, net = cell["args"][i].split("=") if p == pin: return net # Not found return None
bigcode/self-oss-instruct-sc2-concepts
import re def nest(text, nest): """ Indent documentation block for nesting. Args: text (str): Documentation body. nest (int): Nesting level. For each level, the final block is indented one level. Useful for (e.g.) declaring structure members. Returns: str: Indented reST documentation string. """ return re.sub('(?m)^(?!$)', ' ' * nest, text)
bigcode/self-oss-instruct-sc2-concepts
from typing import Union import time def time_format(seconds: float, format_='%H:%M:%S') -> Union[str, float]: """ Default format is '%H:%M:%S' >>> time_format(3600) '01:00:00' """ # this because NaN if seconds >= 0 or seconds < 0: time_ = time.strftime(format_, time.gmtime(abs(seconds))) if seconds < 0: return f"-{time_}" return time_ return seconds
bigcode/self-oss-instruct-sc2-concepts
def validate_identifier(key: str): """Check if key starts with alphabetic or underscore character.""" key = key.strip() return key[0].isalpha() or key.startswith("_")
bigcode/self-oss-instruct-sc2-concepts
import struct def _single_byte_from_hex_string(h): """Return a byte equal to the input hex string.""" try: i = int(h, 16) if i < 0: raise ValueError except ValueError: raise ValueError("Can't convert hex string to a single byte") if len(h) > 2: raise ValueError("Hex string can't be more than one byte in size") if len(h) == 2: return struct.pack("B", i) elif len(h) == 1: return struct.pack("B", i << 4)
bigcode/self-oss-instruct-sc2-concepts
def mean(num_list): """ Computes the mean of a list of numbers Parameters ---------- num_list : list List of number to calculate mean of Returns ------- mean : float Mean value of the num_list """ # Check that input is of type list if not isinstance(num_list, list): raise TypeError('Invalid input %s - must be type list' % (num_list)) list_sum = 0.0 list_len = len(num_list) # Check that the list is not empty if list_len == 0: raise ValueError("Num list is empty") for el in num_list: list_sum += el return list_sum / list_len
bigcode/self-oss-instruct-sc2-concepts
import csv def get_rows(input_tsv): """Parse input CSV into list of rows Keyword arguments: input_tsv -- input TSV containing study metadata Returns _csv.reader -- content of input file """ tsv_rows = csv.reader(open(input_tsv, 'r'), delimiter='\t') return tsv_rows # see tsv2xml.py
bigcode/self-oss-instruct-sc2-concepts
def get_queue(conn, queue_name): """ Create a queue with the given name, or get an existing queue with that name from the AWS connection. """ return conn.get_queue(queue_name)
bigcode/self-oss-instruct-sc2-concepts
def check_reversibility(reaction): """ Return: - *forward* if reaction is irreversible in forward direction - *backward* if reaction is irreversible in the rbackward (reverse) direction - *reversible* if the reaction is reversible - *blocked* if the reactions is blocked """ if (reaction.lower_bound < 0) and (reaction.upper_bound == 0): return "backward" elif (reaction.lower_bound == 0) and (reaction.upper_bound > 0): return "forward" elif (reaction.lower_bound == 0) and (reaction.upper_bound == 0): return "blocked" else: return "reversible"
bigcode/self-oss-instruct-sc2-concepts
def summ_nsqr(i1, i2): """Return the summation from i1 to i2 of n^2""" return ((i2 * (i2+1) * (2*i2 + 1)) / 6) - (((i1-1) * i1 * (2*(i1-1) + 1)) / 6)
bigcode/self-oss-instruct-sc2-concepts
def _cost_to_qubo(cost) -> dict: """Get the the Q matrix corresponding to the given cost. :param cost: cost :return: QUBO matrix """ model = cost.compile() Q = model.to_qubo()[0] return Q
bigcode/self-oss-instruct-sc2-concepts
def base_count(DNA): """Counts number of Nucleotides""" return DNA.count('A'), DNA.count('T'), DNA.count('G'), DNA.count('C')
bigcode/self-oss-instruct-sc2-concepts
def alphabetical_value(name): """ Returns the alphabetical value of a name as described in the problem statement. """ return sum([ord(c) - 64 for c in list(str(name))])
bigcode/self-oss-instruct-sc2-concepts
def GetFilters(user_agent_string, js_user_agent_string=None, js_user_agent_family=None, js_user_agent_v1=None, js_user_agent_v2=None, js_user_agent_v3=None): """Return the optional arguments that should be saved and used to query. js_user_agent_string is always returned if it is present. We really only need it for Chrome Frame. However, I added it in the generally case to find other cases when it is different. When the recording of js_user_agent_string was added, we created new records for all new user agents. Since we only added js_document_mode for the IE 9 preview case, it did not cause new user agent records the way js_user_agent_string did. js_document_mode has since been removed in favor of individual property overrides. Args: user_agent_string: The full user-agent string. js_user_agent_string: JavaScript ua string from client-side js_user_agent_family: This is an override for the family name to deal with the fact that IE platform preview (for instance) cannot be distinguished by user_agent_string, but only in javascript. js_user_agent_v1: v1 override - see above. js_user_agent_v2: v1 override - see above. js_user_agent_v3: v1 override - see above. Returns: {js_user_agent_string: '[...]', js_family_name: '[...]', etc...} """ filters = {} filterdict = { 'js_user_agent_string': js_user_agent_string, 'js_user_agent_family': js_user_agent_family, 'js_user_agent_v1': js_user_agent_v1, 'js_user_agent_v2': js_user_agent_v2, 'js_user_agent_v3': js_user_agent_v3 } for key, value in filterdict.items(): if value is not None and value != '': filters[key] = value return filters
bigcode/self-oss-instruct-sc2-concepts
def filter_api_changed(record): """Filter out LogRecords for requests that poll for changes.""" return not record.msg.endswith('api/changed/ HTTP/1.1" 200 -')
bigcode/self-oss-instruct-sc2-concepts
def apply_decorators(decorators): """Apply multiple decorators to the same function. Useful for reusing common decorators among many functions.""" def wrapper(func): for decorator in reversed(decorators): func = decorator(func) return func return wrapper
bigcode/self-oss-instruct-sc2-concepts
import string def LazyFormat(s, *args, **kwargs): """Format a string, allowing unresolved parameters to remain unresolved. Args: s: str, The string to format. *args: [str], A list of strings for numerical parameters. **kwargs: {str:str}, A dict of strings for named parameters. Returns: str, The lazily-formatted string. """ class SafeDict(dict): def __missing__(self, key): return '{' + key + '}' return string.Formatter().vformat(s, args, SafeDict(kwargs))
bigcode/self-oss-instruct-sc2-concepts
def find_gcd(number1: int, number2: int) -> int: """Returns the greatest common divisor of number1 and number2.""" remainder: int = number1 % number2 return number2 if remainder == 0 else find_gcd(number2, remainder)
bigcode/self-oss-instruct-sc2-concepts
def rect_area(r): """Return the area of a rectangle. Args: r: an object with attributes left, top, width, height Returns: float """ return float(r.width) * float(r.height)
bigcode/self-oss-instruct-sc2-concepts
def ascii2int(str, base=10, int=int): """ Convert a string to an integer. Works like int() except that in case of an error no exception raised but 0 is returned; this makes it useful in conjunction with map(). """ try: return int(str, base) except: return 0
bigcode/self-oss-instruct-sc2-concepts
def create_chord_progression(a_train=False): """Creates a midi chord progression Args: a_train (bool, optional): Defaults at False. If True, returns chord progression for Take the A Train by Duke Ellington. Otherwise, returns standard 12-bar blues in C major. Returns: (int, int)[]: Returns chord progression, which is list of (chord_root, dur) """ chord_progression = [] if not a_train: for _ in range(4): chord_progression.append((1, 32)) for _ in range(2): chord_progression.append((4, 32)) for _ in range(2): chord_progression.append((1, 32)) for _ in range(1): chord_progression.append((5, 32)) for _ in range(1): chord_progression.append((4, 32)) for _ in range(2): chord_progression.append((1, 32)) else: for _ in range(2): # 16 measures for _ in range(2): chord_progression.append((1, 32)) for _ in range(2): chord_progression.append((2, 32)) for _ in range(1): chord_progression.append((3, 32)) for _ in range(1): chord_progression.append((4, 32)) for _ in range(2): chord_progression.append((1, 32)) for _ in range(4): # 8 measures chord_progression.append((5, 32)) for _ in range(2): chord_progression.append((4, 32)) for _ in range(1): chord_progression.append((3, 32)) for _ in range(1): chord_progression.append((6, 32)) for _ in range(2): # 8 measures chord_progression.append((1, 32)) for _ in range(2): chord_progression.append((2, 32)) for _ in range(1): chord_progression.append((3, 32)) for _ in range(1): chord_progression.append((6, 32)) for _ in range(2): chord_progression.append((1, 32)) return chord_progression
bigcode/self-oss-instruct-sc2-concepts
import itertools def subsets(parent_set, include_empty=False, include_self=False): """ Given a set of variable names, return all subsets :param parent_set: a set, or tuple, of variables :return: a set of tuples, each one denoting a subset """ s = set() n = len(parent_set) for i in range(n - 1): for combo in itertools.combinations(list(parent_set), i + 1): s.add(tuple(sorted(combo))) if include_empty: s.add(tuple()) if include_self: s.add(tuple(sorted(parent_set))) return s
bigcode/self-oss-instruct-sc2-concepts
from typing import Any from typing import Optional def _guess_crs_str(crs_spec: Any)->Optional[str]: """ Returns a string representation of the crs spec. Returns `None` if it does not understand the spec. """ if isinstance(crs_spec, str): return crs_spec if hasattr(crs_spec, 'to_epsg'): epsg = crs_spec.to_epsg() if epsg is not None: return 'EPSG:{}'.format(crs_spec.to_epsg()) if hasattr(crs_spec, 'to_wkt'): return crs_spec.to_wkt() return None
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterable from typing import List def unique_by(pairs: Iterable[tuple]) -> List: """Return a list of items with distinct keys. pairs yields (item, key).""" # return a list rather than a set, because items might not be hashable return list({key: item for item, key in pairs}.values())
bigcode/self-oss-instruct-sc2-concepts
def area_of_polygon(x, y): """Calculates the area of an arbitrary polygon given its verticies""" area = 0.0 for i in range(-1, len(x)-1): area += x[i] * (y[i+1] - y[i-1]) return abs(area) / 2.0
bigcode/self-oss-instruct-sc2-concepts
def _set_default_max_rated_temperature(subcategory_id: int) -> float: """Set the default maximum rated temperature. :param subcategory_id: the subcategory ID of the inductive device with missing defaults. :return: _rated_temperature_max :rtype: float """ return 130.0 if subcategory_id == 1 else 125.0
bigcode/self-oss-instruct-sc2-concepts
def SimpleMaxMLECheck(BasinDF): """ This function checks through the basin dataframe and returns a dict with the basin key and the best fit m/n Args: BasinDF: pandas dataframe from the basin csv file. Returns: m_over_n_dict: dictionary with the best fit m/n for each basin, the key is the basin key and the value is the best fit m/n Author: FJC """ # read in the basin csv basin_keys = list(BasinDF['basin_key']) #print BasinDF # remove the first 2 columns from DF del BasinDF['basin_key'] del BasinDF['outlet_jn'] # now find the index and value of the max MLE in each row MOverNs = list(BasinDF.idxmax(axis=1)) MOverNs = [float(x.split()[-1]) for x in MOverNs] print ("MAX MOVERNS") print (MOverNs) # zip into a dictionary MOverNDict = dict(zip(basin_keys, MOverNs)) return MOverNDict
bigcode/self-oss-instruct-sc2-concepts
import re def get_pkgver(pkginfo): """Extracts the APK version from pkginfo; returns string.""" try: pkgver = re.findall("versionName=\'(.*?)\'", pkginfo)[0] pkgver = "".join(pkgver.split()).replace("/", "") except: pkgver = "None" return pkgver
bigcode/self-oss-instruct-sc2-concepts
def getBBox(df, cam_key, frame, fid): """ Returns the bounding box of a given fish in a given frame/cam view. Input: df: Dataset Pandas dataframe cam_key: String designating the camera view (cam1 or cam2) frame: int indicating the frame which should be looked up fid: int indicating the fish ID Output: Tuple containing the top left x/y coordiante and the bottom right x/y coordinates """ df_f = df[(df["id"] == fid) & (df["{}_frame".format(cam_key)] == frame)] return (df_f["{}_tl_x".format(cam_key)].values, df_f["{}_tl_y".format(cam_key)].values, df_f["{}_br_x".format(cam_key)].values, df_f["{}_br_y".format(cam_key)].values)
bigcode/self-oss-instruct-sc2-concepts
def constituent_copyin_subname(host_model): ############################################################################### """Return the name of the subroutine to copy constituent fields to the host model. Because this is a user interface API function, the name is fixed.""" return "{}_ccpp_gather_constituents".format(host_model.name)
bigcode/self-oss-instruct-sc2-concepts
import codecs def check_encoding(stream, encoding): """Test, whether the encoding of `stream` matches `encoding`. Returns :None: if `encoding` or `stream.encoding` are not a valid encoding argument (e.g. ``None``) or `stream.encoding is missing. :True: if the encoding argument resolves to the same value as `encoding`, :False: if the encodings differ. """ if stream.encoding == None: return None try: return codecs.lookup(stream.encoding) == codecs.lookup(encoding) except (LookupError, AttributeError, TypeError): return None
bigcode/self-oss-instruct-sc2-concepts
def _list_distance(list1, list2, metric): """ Calculate distance between two lists of the same length according to a given metric. Assumes that lists are of the same length. Args: list1 (list): first input list. list2 (list): second input list. metric (str): 'identity' counts identical positions, 'euclid' calculates the Euclidean distance (L2 norm), 'taxi' calculates the taxicab (Manhattan) distance (L1 norm), 'sup' returns maximum distance between positions, 'inf' returns minimum distance between positions. Returns distance between the two lists. Raises: ValueError if unsupported distance metric used. """ # Equal length of both lists is assumed distance = 0 if metric == 'taxi': distance = sum([abs(list1[pos] - list2[pos]) for pos in range(len(list1))]) return distance elif metric == 'euclid': distance = sum([(list1[pos] - list2[pos]) ** 2 for pos in range(len(list1))]) return distance ** 0.5 elif metric == 'identity': distance = sum([list1[pos] != list2[pos] for pos in range(len(list1))]) return distance elif metric == 'sup': distance = max([abs(list1[pos] - list2[pos]) for pos in range(len(list1))]) return distance elif metric == 'inf': distance = min([abs(list1[pos] - list2[pos]) for pos in range(len(list1))]) return distance else: raise ValueError("Proper distance calculation metrics are \'taxi\',\ \'euclid\', \'identity\', \'sup\', or \'inf\'.")
bigcode/self-oss-instruct-sc2-concepts
import torch from typing import Type def count_module_instances(model: torch.nn.Module, module_class: Type[torch.nn.Module]) -> int: """ Counts the number of instances of module_class in the model. Example: >>> model = nn.Sequential([nn.Linear(16, 32), nn.Linear(32, 64), nn.ReLU]) >>> count_module_instances(model, nn.Linear) 2 >>> count_module_instances(model, (nn.Linear, nn.ReLU)) 3 Args: model (torch.nn.Module): Source model module_class (Type[torch.nn.Module]): module_class to count. Can also be a tuple of classes. Returns: int: The number of instances of `module_class` in `model` """ count = 0 for _, child in model.named_children(): if isinstance(child, module_class): count += 1 count += count_module_instances(child, module_class) return count
bigcode/self-oss-instruct-sc2-concepts
def get_all_layers(model): """ Get all layers of model, including ones inside a nested model """ layers = [] for l in model.layers: if hasattr(l, 'layers'): layers += get_all_layers(l) else: layers.append(l) return layers
bigcode/self-oss-instruct-sc2-concepts
def escape_markdown(raw_string: str) -> str: """Returns a new string which escapes all markdown metacharacters. Args ---- raw_string : str A string, possibly with markdown metacharacters, e.g. "1 * 2" Returns ------- A string with all metacharacters escaped. Examples -------- :: escape_markdown("1 * 2") -> "1 \\* 2" """ metacharacters = ["\\", "*", "-", "=", "`", "!", "#", "|"] result = raw_string for character in metacharacters: result = result.replace(character, "\\" + character) return result
bigcode/self-oss-instruct-sc2-concepts
import csv def detect_csv_sep(filename: str) -> str: """Detect the separator used in a raw source CSV file. :param filename: The name of the raw CSV in the raw/ directory :type filename: str :return: The separator string :rtype: str """ sep = '' with open(f'raw/{filename}',"r") as csv_file: res = csv.Sniffer().sniff(csv_file.read(1024)) csv_file.seek(0) sep = res.delimiter return sep
bigcode/self-oss-instruct-sc2-concepts
def get_restraints(contact_f): """Parse a contact file and retrieve the restraints.""" restraint_dic = {} with open(contact_f) as fh: for line in fh.readlines(): if not line: # could be empty continue data = line.split() res_i = int(data[0]) chain_i = data[1] res_j = int(data[3]) chain_j = data[4] if chain_i not in restraint_dic: restraint_dic[chain_i] = [] if chain_j not in restraint_dic: restraint_dic[chain_j] = [] if res_i not in restraint_dic[chain_i]: restraint_dic[chain_i].append(res_i) if res_j not in restraint_dic[chain_j]: restraint_dic[chain_j].append(res_j) return restraint_dic
bigcode/self-oss-instruct-sc2-concepts
def easy_name(s): """Remove special characters in column names""" return s.replace(':', '_')
bigcode/self-oss-instruct-sc2-concepts
def skymapweights_keys(self): """ Return the list of string names of valid weight attributes. For unpolarized weights, this list includes only TT. Otherwise, the list includes all six unique weight attributes in row major order: TT, TQ, TU, QQ, QU, UU. """ if self.polarized: return ['TT', 'TQ', 'TU', 'QQ', 'QU', 'UU'] return ['TT']
bigcode/self-oss-instruct-sc2-concepts
def one_lvl_colnames(df,cols,tickers): """This function changes a multi-level column indexation into a one level column indexation Inputs: ------- df (pandas Dataframe): dataframe with the columns whose indexation will be flattened. tickers (list|string): list/string with the tickers (s) in the data frame df. cols (list|string): list/string with the name of the columns (e.g. 'Adj Close', 'High', 'Close', etc.) that are in the dataframe df. Ouputs: ------- df (pandas Dataframe): dataframe with the same information as df, but with one level of indexation. """ # Define important variables: if isinstance(tickers, str): tickers = [tickers] if isinstance(cols, str): cols = [cols] # For multi-level column indexing: if isinstance(df.columns.values[0], tuple): # Define important varibles columns = df.columns.values new_cols = [] # Itarate through the multi-level column names and flatten them: for col in columns: temp = [] for name in col: if name != '': temp.append(name) new_temp = '_'.join(temp) new_cols.append(new_temp) # Change the column names: df.columns = new_cols # For uni-level colum indexing: elif isinstance(df.columns.values[0], str): # Define new names: col_names = [column+'_'+ticker for column in cols\ for ticker in tickers] df.columns = col_names return df
bigcode/self-oss-instruct-sc2-concepts
def has_imm(opcode): """Returns True if the opcode has an immediate operand.""" return bool(opcode & 0b1000)
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterator def second(itr: Iterator[float]) -> float: """Returns the second item in an iterator.""" next(itr) return next(itr)
bigcode/self-oss-instruct-sc2-concepts
def _run_subsuite(args): """ Run a suite of tests with a RemoteTestRunner and return a RemoteTestResult. This helper lives at module-level and its arguments are wrapped in a tuple because of the multiprocessing module's requirements. """ runner_class, subsuite_index, subsuite, failfast = args runner = runner_class(failfast=failfast) result = runner.run(subsuite) return subsuite_index, result.events
bigcode/self-oss-instruct-sc2-concepts
from typing import List import re def parse_seasons(seasons: List[str]): """Parses a string of seasons into a list of seasons. Used by main and by collect_course_length main""" parsed_seasons = [] for season in seasons: if re.match("[0-9]{4}\-[0-9]{4}", season): int_range = list(map(int, season.split("-"))) # increase end so our range is inclusive int_range[1] += 1 parsed_seasons += list(map(str, range(*int_range))) elif re.match("[0-9]{4}", season): parsed_seasons.append(season) else: raise ValueError("The season must be a valid 4-digit year") return parsed_seasons
bigcode/self-oss-instruct-sc2-concepts
def _copy_dict(dct, description): """Return a copy of `dct` after overwriting the `description`""" _dct = dct.copy() _dct['description'] = description return _dct
bigcode/self-oss-instruct-sc2-concepts
def poly_from_box(W, E, N, S): """ Helper function to create a counter-clockwise polygon from the given box. N, E, S, W are the extents of the box. """ return [[W, N], [W, S], [E, S], [E, N]]
bigcode/self-oss-instruct-sc2-concepts
def valfilterfalse(predicate, d, factory=dict): """ Filter items in dictionary by values which are false. >>> iseven = lambda x: x % 2 == 0 >>> d = {1: 2, 2: 3, 3: 4, 4: 5} >>> valfilterfalse(iseven, d) {2: 3, 4: 5} See Also: valfilter """ rv = factory() for k, v in d.items(): if not predicate(v): rv[k] = v return rv
bigcode/self-oss-instruct-sc2-concepts
def yxbounds(shape1, shape2): """Bounds on the relative position of two arrays such that they overlap. Given the shapes of two arrays (second array smaller) return the range of allowed center offsets such that the second array is wholly contained in the first. Parameters ---------- shape1 : tuple Shape of larger array. shape2 : tuple Shape of smaller array. Returns ------- ybounds : tuple Length 2 tuple giving ymin, ymax. xbounds : tuple Length 2 tuple giving xmin, xmax. Examples -------- >>> yxbounds((32, 32), (15, 15)) (-8.5, 8.5), (-8.5, 8.5) """ yd = (shape1[0] - shape2[0]) / 2. xd = (shape1[1] - shape2[1]) / 2. return (-yd, yd), (-xd, xd)
bigcode/self-oss-instruct-sc2-concepts
def parse_spec(spec, default_module): """Parse a spec of the form module.class:kw1=val,kw2=val. Returns a triple of module, classname, arguments list and keyword dict. """ name, args = (spec.split(':', 1) + [''])[:2] if '.' not in name: if default_module: module, klass = default_module, name else: module, klass = name, None else: module, klass = name.rsplit('.', 1) al = [a for a in args.split(',') if a and '=' not in a] kw = dict(a.split('=', 1) for a in args.split(',') if '=' in a) return module, klass, al, kw
bigcode/self-oss-instruct-sc2-concepts
def handle_returning_date_to_string(date_obj): """Gets date object to string""" # if the returning date is a string leave it as is. if isinstance(date_obj, str): return date_obj # if event time is datetime object - convert it to string. else: return date_obj.isoformat()
bigcode/self-oss-instruct-sc2-concepts
def getAtomNames(values): """ Assign to each value an atomname, O for negatives, H for 0 and N for positives. This function is created for assign atomnames for custom pdbs :param values: Collection of numbers to assing an atom name for :type values: iterable :returns: list -- List of atom names """ names = ["O", "H", "N"] values += 1 return [names[int(value)] for value in values]
bigcode/self-oss-instruct-sc2-concepts
def event_loop_settings(auto_launch=True): """Settings for pyMOR's MPI event loop. Parameters ---------- auto_launch If `True`, automatically execute :func:`event_loop` on all MPI ranks (except 0) when pyMOR is imported. """ return {'auto_launch': auto_launch}
bigcode/self-oss-instruct-sc2-concepts
def mate_in_region(aln, regtup): """ Check if mate is found within region Return True if mate is found within region or region is None Args: aln (:obj:`pysam.AlignedSegment`): An aligned segment regtup (:tuple: (chrom, start, end)): Region Returns: bool: True if mate is within region """ if regtup is None: return True return aln.next_reference_id == regtup[0] and \ regtup[1] < aln.next_reference_start < regtup[2]
bigcode/self-oss-instruct-sc2-concepts
def format_query(query, params=None): """ Replaces "{foo}" in query with values from params. Works just like Python str.format :type query str :type params dict :rtype: str """ if params is None: return query for key, value in params.items(): query = query.replace('{%s}' % key, str(value)) return query
bigcode/self-oss-instruct-sc2-concepts
def rename_dupe_cols(cols): """ Renames duplicate columns in order of occurrence. columns [0, 0, 0, 0] turn into [0, 1, 2, 3] columns [name10, name10, name10, name10] turn into [name10, name11, name12, name13] :param cols: iterable of columns :return: unique columns with digits incremented. """ cols = [str(c) for c in cols] new_cols = [] for i in range(len(cols)): c = cols.pop(0) while c in new_cols: try: num = int(''.join(x for x in c if x.isdigit())) c = c.replace(str(num), str(num + 1)) except: c = c + str(2) new_cols.append(c) return new_cols
bigcode/self-oss-instruct-sc2-concepts
def find_all(soup, first, second, third): """ A simpler (sorta...) method to BeautifulSoup.find_all :param soup: A BeautifulSoup object :param first: The first item to search for. Example: div :param second: the second aspect to search for. The key in the key:value pair. Example: class :param third: The third aspect, which is the value in the key: value pair. Example: <class-name> Example: BeautifulSoup(<url>,<parser>).find_all("div", {"class": <"classname">}) is simplifed with this method by using: results = common.find_all(soup_obj, "div", "class", "<classname>") :return: a list of items found by the search. """ # returns a soup object with find_all try: items = soup.find_all(first, {second:third}) except Exception as error: print("There was an error trying to find all", error) return None if not items: print("Didn't find anything!") return items
bigcode/self-oss-instruct-sc2-concepts
def add_suffix_to_parameter_set(parameters, suffix, divider='__'): """ Adds a suffix ('__suffix') to the keys of a dictionary of MyTardis parameters. Returns a copy of the dict with suffixes on keys. (eg to prevent name clashes with identical parameters at the Run Experiment level) """ suffixed_parameters = {} for p in parameters: suffixed_parameters[u'%s%s%s' % (p['name'], divider, suffix)] = p['value'] return suffixed_parameters
bigcode/self-oss-instruct-sc2-concepts
def value_to_string(ast): """Remove the quotes from around the string value""" if ast.value[:3] in ('"""', "'''"): ast.value = ast.value[3:-3] else: ast.value = ast.value[1:-1] return ast
bigcode/self-oss-instruct-sc2-concepts
def module_of (object) : """Returns the name of the module defining `object`, if possible. `module_of` works for classes, functions, and class proxies. """ try : object = object.__dict__ ["Essence"] except (AttributeError, KeyError, TypeError) : pass result = getattr (object, "__module__", None) if not result : globals = getattr (object, "func_globals", None) if globals : result = globals.get ("__name__") return result
bigcode/self-oss-instruct-sc2-concepts
import itertools def nQubit_Meas(n): """ Generate a list of measurement operators correponding to the [X,Y,Z]^n Pauli group Input: n (int): Number of qubits to perform tomography over Returns: (list) list of measurement operators corresponding to all combinations of the n qubit Pauli group for QST or QPT """ #Pulse in [X,Y,Z] order seq_single = ['X', 'Y', 'Z'] return list(itertools.product(seq_single, repeat=n))
bigcode/self-oss-instruct-sc2-concepts
import copy def make_all_strokes_dashed(svg, unfilled=False): """ Makes all strokes in the SVG dashed :param svg: The SVG, in xml.etree.ElementTree format :param unfilled: Whether this is an unfilled symbol :return: The resulting SVG """ stroke_elements = [ele for ele in svg.findall('.//*[@stroke]') if ele.attrib['stroke'] != 'none'] if not unfilled: stroke_elements_with_dash = [copy.deepcopy(ele) for ele in stroke_elements] for ele in stroke_elements: ele.attrib['stroke'] = '#ffffff' for ele in stroke_elements_with_dash: ele.attrib['stroke-dasharray'] = '2 2' svg.extend(stroke_elements_with_dash) else: for ele in stroke_elements: ele.attrib['stroke-dasharray'] = '2 2' return svg
bigcode/self-oss-instruct-sc2-concepts
def iter_copy(structure): """ Returns a copy of an iterable object (also copying all embedded iterables). """ l = [] for i in structure: if hasattr(i, "__iter__"): l.append(iter_copy(i)) else: l.append(i) return l
bigcode/self-oss-instruct-sc2-concepts
def tag_predicate(p): """ Given a full URI predicate, return a tagged predicate. So, for example, given http://www.w3.org/1999/02/22-rdf-syntax-ns#type return rdf:type """ ns = { "http://www.w3.org/1999/02/22-rdf-syntax-ns#":"rdf:", "http://www.w3.org/2000/01/rdf-schema#":"rdfs:", "http://www.w3.org/2001/XMLSchema#":"xsd:", "http://www.w3.org/2002/07/owl#":"owl:", "http://www.w3.org/2003/11/swrl#":"swrl:", "http://www.w3.org/2003/11/swrlb#":"swrlb:", "http://vitro.mannlib.cornell.edu/ns/vitro/0.7#":"vitro:", "http://purl.org/ontology/bibo/":"bibo:", "http://purl.org/spar/c4o/":"c4o:", "http://purl.org/spar/cito/":"cito:", "http://purl.org/dc/terms/":"dcterms:", "http://purl.org/NET/c4dm/event.owl#":"event:", "http://purl.org/spar/fabio/":"fabio:", "http://xmlns.com/foaf/0.1/":"foaf:", "http://aims.fao.org/aos/geopolitical.owl#":"geo:", "http://purl.obolibrary.org/obo/":"obo:", "http://purl.org/net/OCRe/research.owl#":"ocrer:", "http://purl.org/net/OCRe/study_design.owl#":"ocresd:", "http://www.w3.org/2004/02/skos/core#":"skos:", "http://vivo.ufl.edu/ontology/vivo-ufl/":"ufVivo:", "http://www.w3.org/2006/vcard/ns#":"vcard:", "http://vitro.mannlib.cornell.edu/ns/vitro/public#":"vitro-public:", "http://vivoweb.org/ontology/core#":"vivo:", "http://vivoweb.org/ontology/scientific-research#":"scires:" } for uri, tag in ns.items(): if p.find(uri) > -1: newp = p.replace(uri, tag) return newp return None
bigcode/self-oss-instruct-sc2-concepts
def chunk(arr:list, size:int=1) -> list: """ This function takes a list and divides it into sublists of size equal to size. Args: arr ( list ) : list to split size ( int, optional ) : chunk size. Defaults to 1 Return: list : A new list containing the chunks of the original Examples: >>> chunk([1, 2, 3, 4]) [[1], [2], [3], [4]] >>> chunk([1, 2, 3, 4], 2) [[1, 2], [3, 4]] >>> chunk([1, 2, 3, 4, 5, 6], 3) [[1, 2, 3], [4, 5, 6]] """ _arr = [] for i in range(0, len(arr), size): _arr.append(arr[i : i + size]) return _arr
bigcode/self-oss-instruct-sc2-concepts
def listify(x): """Convert item to a `list` of items if it isn't already a `list`.""" if not isinstance(x, list): return [x] return x
bigcode/self-oss-instruct-sc2-concepts
def find_missing_number(array): """ :param array: given integer array from 1 to len(array), missing one of value :return: The missing value Method: Using sum of list plus missing number subtract the list of the given array Complexity: O(n) """ n = len(array) expected_sum = (n + 1) * (n + 2) // 2 return expected_sum - sum(array)
bigcode/self-oss-instruct-sc2-concepts
def prune_nones_list(data): """Remove trailing None values from list.""" return [x for i, x in enumerate(data) if any(xx is not None for xx in data[i:])]
bigcode/self-oss-instruct-sc2-concepts
def get_clean_path_option(a_string): """ Typically install flags are shown as 'flag:PATH=value', so this function splits the two, and removes the :PATH portion. This function returns a tuple consisting of the install flag and the default value that is set for it. """ option, default = a_string.split('=') option = option[:-5] return option, default
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple from typing import List import re def parse_command(input: str) -> Tuple[str, List[str]]: """ Parse the command. :param input: The input to parse. :returns: Tuple of command, and a list of parameters to the command. """ input = input.strip() # Strip whitespace at start and end. input = re.sub(r"\s\s+", " ", input) # Remove double spaces. tokens = input.split(" ") command = tokens.pop(0) return command, tokens
bigcode/self-oss-instruct-sc2-concepts
def id_2_addr(hue_id): """ Convert a Phillips Hue ID to ISY Address """ return hue_id.replace(':', '').replace('-', '')[-14:]
bigcode/self-oss-instruct-sc2-concepts
def merge(novel_adj_dict, full_adj_dict): """ Merges adjective occurrence results from a single novel with results for each novel. :param novel_adj_dict: dictionary of adjectives/#occurrences for one novel :param full_adj_dict: dictionary of adjectives/#occurrences for multiple novels :return: full_results dictionary with novel_results merged in >>> novel_adj_dict = {'hello': 5, 'hi': 7, 'hola': 9, 'bonjour': 2} >>> full_adj_dict = {'hello': 15, 'bienvenue': 3, 'hi': 23} >>> merge(novel_adj_dict, full_adj_dict) {'hello': 20, 'bienvenue': 3, 'hi': 30, 'hola': 9, 'bonjour': 2} """ for adj in list(novel_adj_dict.keys()): adj_count = novel_adj_dict[adj] if adj in list(full_adj_dict.keys()): full_adj_dict[adj] += adj_count else: full_adj_dict[adj] = adj_count return full_adj_dict
bigcode/self-oss-instruct-sc2-concepts
def jinja2_lower(env, s): """Converts string `s` to lowercase letters. """ return s.lower()
bigcode/self-oss-instruct-sc2-concepts
def compute_cycle_length_with_denom(denom): """ Compute the decimal cycle length for unit fraction 1/denom (where denom>1) e.g. 1/6 has decimal representation 0.1(6) so cycle length is 1, etc """ digit_pos = 0 # Remaining fraction after subtracting away portions of earlier decimal digits frac_numer = 1 frac_numer_history = dict() while True: digit_pos += 1 # For this digit position, compute the common denominator and numerator # for the remaining fraction. E.g. if we started with denom = 7, then: # digit_pos=1: frac = 1/7 => 10/70 - 1*7/70 = 3/70 [0.1] # digit_pos=2: frac = 3/70 => 30/700 - 4*7/700 = 2/700 [0.14] # digit_pos=3: frac = 2/700 => 20/7000 - 2*7/7000 = 6/7000 [0.142] # It's clear that we can ignore the denominator (it's known from digit_pos): # digit_pos=4: frac = 6/d => 60/10d - 8*7/10d = 4/10d [0.1428] # digit_pos=5: frac = 4/d => 40/10d - 5*7/10d = 5/10d [0.14285] # digit_pos=6: frac = 5/d => 50/10d - 7*7/10d = 1/10d [0.142857] # digit_pos=7: frac = 1/d => we're back to digit_pos=1! Seq length is 7-1 = 6. # Another example for 1/6: # digit_pos=1: frac = 1/d => 10/10d - 1*6/10d = 4/10d [0.1] # digit_pos=2: frac = 4/d => 40/10d - 6*6/10d = 4/10d [0.16] # digit_pos=3: frac = 4/d => we're back to digit_pos=2! Seq length is 3-2 = 1. minuend = 10 * frac_numer subtrahend = denom digit = minuend // subtrahend difference = minuend - digit * subtrahend # Has it terminated? if difference == 0: return 0 # Have we found a repeating sequence? if frac_numer in frac_numer_history: return digit_pos - frac_numer_history[frac_numer] # Add this digit to the "seen before" dict frac_numer_history[frac_numer] = digit_pos # Update remaining fraction numerator frac_numer = difference
bigcode/self-oss-instruct-sc2-concepts
def binary_to_ascii(binary_item): """ Convert a binary number to an ASCII char. """ str_number = str(binary_item) if str_number == '': return -1 decimal_number = int(str_number, 2) decoded = chr(decimal_number) return decoded
bigcode/self-oss-instruct-sc2-concepts
import shutil def read_binary(shared_dir, output_file): """ Read back binary file output from container into one string, not an iterable. Then remove the temporary parent directory the container mounted. :param shared_dir: temporary directory container mounted :param output_file: path to output file :return: str of file contents """ with open(output_file, 'rb') as file_handle: output = file_handle.read() shutil.rmtree(shared_dir) return output
bigcode/self-oss-instruct-sc2-concepts