seed
stringlengths
1
14k
source
stringclasses
2 values
def deploy_command(deb_package, hostname, username = "pasha"): """Command for start deployment on `target_hosts` of package. Args: deb_package (File): Debian package to install hostname (str): host for installation username (str): SSH user for installation process Returns: Prepared string containing full bash command to start a deployment """ echo = 'echo "Deploying to {hostname}"\n' remove_old = "ssh {username}@{hostname} 'sudo rm -f {package_name}'\n" copy = "scp {package_path} {username}@{hostname}:~\n" remote_install = "sudo -H apt install --reinstall ./{package_name}".format(package_name = deb_package.basename) notify = "ssh {username}@{hostname} '{remote_notify}'\n" install = "ssh {username}@{hostname} '{remote_install}'\n" return (echo + remove_old + copy + install + remove_old).format( package_name = deb_package.basename, package_path = deb_package.short_path, hostname = hostname, username = username, remote_install = remote_install, )
bigcode/self-oss-instruct-sc2-concepts
def parameter_values(params, **kwargs): """Return a copy of the parameter list, substituting values from kwargs. Usage example:: params = parameter_values(params, stock='GOOG', days_back=300 ) Any parameters not supplied will keep their original value. """ res = [] for p in params: if p.name in kwargs: res.append(p.with_value(kwargs[p.name])) else: res.append(p) return res
bigcode/self-oss-instruct-sc2-concepts
def gf_TC(f, K): """ Return trailing coefficient of ``f``. **Examples** >>> from sympy.polys.domains import ZZ >>> from sympy.polys.galoistools import gf_TC >>> gf_TC([3, 0, 1], ZZ) 1 """ if not f: return K.zero else: return f[-1]
bigcode/self-oss-instruct-sc2-concepts
import re def utc_offset_string_to_seconds(utc_offset: str) -> int: """match a UTC offset in format ±[hh]:[mm], ±[h]:[mm], or ±[hh][mm] and return number of seconds offset""" patterns = ["^([+-]?)(\d{1,2}):(\d{2})$", "^([+-]?)(\d{2})(\d{2})$"] for pattern in patterns: match = re.match(pattern, utc_offset) if not match: continue sign = match.group(1) hours = int(match.group(2)) minutes = int(match.group(3)) if sign == "-": hours = -hours minutes = -minutes return (hours * 60 + minutes) * 60 else: raise ValueError(f"Invalid UTC offset format: {utc_offset}.")
bigcode/self-oss-instruct-sc2-concepts
def output_to_IOB2_string(output): """ Convert Stanford NER tags to IOB2 tags. """ iob2_tags = [] names = [] previous_tag = 'O' for _, tup in enumerate(output): name, tag = tup if tag != 'O': tag = 'E' if tag == 'O': iob2_tags.append(tag) previous_tag = tag names.append(name) else: if previous_tag == 'O': iob2_tags.append('B-' + tag) else: iob2_tags.append('I-' + tag) previous_tag = tag names.append(name) return names, iob2_tags
bigcode/self-oss-instruct-sc2-concepts
import ipaddress def get_networks(cidrs): """Convert a comma-separated list of CIDRs to a list of networks.""" if not cidrs: return [] return [ipaddress.ip_interface(cidr).network for cidr in cidrs.split(",")]
bigcode/self-oss-instruct-sc2-concepts
def release_for_relnote(relnote): """ Turn a release note dict into the data needed by GitHub for a release. """ tag = relnote['version'] return { "tag_name": tag, "name": tag, "body": relnote["text"], "draft": False, "prerelease": relnote["prerelease"], }
bigcode/self-oss-instruct-sc2-concepts
import pytz def localized_datetime(naive_dt, timezone_name='America/Los_Angeles'): """Attaches a timezone to a `naive_dt` """ tz = pytz.timezone(timezone_name) dt = tz.localize(naive_dt) return dt
bigcode/self-oss-instruct-sc2-concepts
import re def parse_time_window(window): """ Parse the specified time window and return as (float) minutes, or None if invalid """ regexps = { '^(\d+):?$': lambda match: float(match.group(1)) * 60, '^(\d+):(\d+)$': lambda match: float(match.group(1)) * 60 + float(match.group(2)), '^:(\d+)$': lambda match: float(match.group(1)) } for r in regexps: m = re.match(r, window) if m: return regexps[r](m) return None
bigcode/self-oss-instruct-sc2-concepts
def sequence(*decorators): """ Helper method which creates a decorator that applies the given sub-decorators. Decorators are applied in reverse order given. @decorator_sequence(dec_1, dec_2, ...) def function(...): ... is equivalent to: @dec_1 @dec_2 ... def function(...): ... :param decorators: The sub-decorators. :return: A function which applies the given decorators. """ def apply(obj): for dec in reversed(decorators): obj = dec(obj) return obj return apply
bigcode/self-oss-instruct-sc2-concepts
def then_by_descending(collection, selector, context): """:yaql:thenByDescending To be used with orderBy or orderByDescending. Uses selector to extract secondary sort key (descending) from the elements of the collection and adds it to the iterator. :signature: collection.thenByDescending(selector) :receiverArg collection: collection to be ordered :argType collection: iterable :arg selector: specifies a function of one argument that is used to extract a comparison key from each element :argType selector: lambda :returnType: iterable .. code:: yaql> [[3,'c'], [2,'b'], [1,'c']].orderBy($[1]).thenByDescending($[0]) [[2, 'b'], [3, 'c'], [1, 'c']] """ collection.append_field(selector, False) collection.context = context return collection
bigcode/self-oss-instruct-sc2-concepts
def int_or_string(val: str): """ Loads a value from MO into either an int or string value. String is returned if we can't turn it into an int. """ new_s = val.replace(",", "") try: return float(new_s) except ValueError: return val
bigcode/self-oss-instruct-sc2-concepts
from typing import List def add_jupyter_args(run_args: List[str]) -> List[str]: """ Adds `--ip 0.0.0.0` and `--no-browser` options to run args if those are not there yet. Args: run_args: Existing list of run arguments. Returns: Modified list of run arguments. """ run_args = run_args.copy() if not any(arg.split("=", 1)[0] == "--ip" for arg in run_args): run_args += ["--ip", "0.0.0.0"] # nosec if "--no-browser" not in run_args: run_args += ["--no-browser"] return run_args
bigcode/self-oss-instruct-sc2-concepts
def drop_table_sql(name = "small_peptide"): """Generate an SQL statement for droping a table.""" return f"DROP TABLE IF EXISTS {name};"
bigcode/self-oss-instruct-sc2-concepts
def regularise_periapse_time(raw, period): """ Change the periapse time so it would be between 0 and the period """ res = raw if res < 0: res += period if res > period: res -= period return res
bigcode/self-oss-instruct-sc2-concepts
def get_redundant_feature_pairs(feature_distance_series, threshold): """ Expects results from a `feature_distances` func. Returns redundant feature pairs, as determined by passed `threshold` for inter-feature measurement. """ return feature_distance_series[ feature_distance_series < threshold ].reset_index( ).iloc[:, :2 ].drop_duplicates()
bigcode/self-oss-instruct-sc2-concepts
def _get_join_indices(left_table, right_table, join_conditions): """Given the join conditions, return the indices of the columns used in the join.""" left_indices = [] right_indices = [] for cond in join_conditions: for join_col_name in (cond.left_operand, cond.right_operand): left_col = left_table.get_column_for_name(join_col_name) right_col = right_table.get_column_for_name(join_col_name) assert not (left_col and right_col) if left_col: left_indices.append(left_table.column_idxs[left_col][0]) elif right_col: right_indices.append(right_table.column_idxs[right_col][0]) else: raise ValueError('Column name {0} not found on tables {1} or {2}'.format( join_col_name, left_table, right_table )) return zip(left_indices, right_indices)
bigcode/self-oss-instruct-sc2-concepts
def trim(s): """Removes whitespace, carriage returns, and new line characters.""" s = s.strip().replace("\n", "").replace("\r", "") return s
bigcode/self-oss-instruct-sc2-concepts
def filter_values(function, dictionary): """Filter ``dictionary`` by its values using ``function``.""" return {k: v for k, v in dictionary.items() if function(v)}
bigcode/self-oss-instruct-sc2-concepts
def intersection(l1, l2): """Return intersection of two lists as a new list:: >>> intersection([1, 2, 3], [2, 3, 4]) [2, 3] >>> intersection([1, 2, 3], [1, 2, 3, 4]) [1, 2, 3] >>> intersection([1, 2, 3], [3, 4]) [3] >>> intersection([1, 2, 3], [4, 5, 6]) [] """ #return set(l1) & set(l2) #Close, but no cigar #set(l1).intersection(l2) #Unsure why this didn't work, but returned nothing? return [x for x in l1 if x in l2]
bigcode/self-oss-instruct-sc2-concepts
import re def remove_html_a_element_for_dingtalk(s): """ Replace <a ..>xx</a> to xx and wrap content with <div></div>. """ patt = '<a.*?>(.+?)</a>' def repl(matchobj): return matchobj.group(1) return re.sub(patt, repl, s)
bigcode/self-oss-instruct-sc2-concepts
import re def dist_info_name(distribution, version): """Get the correct name of the .dist-info folder""" escaped_name = re.sub(r"[^\w\d.]+", "_", distribution, flags=re.UNICODE) escaped_version = re.sub(r"[^\w\d.]+", "_", version, flags=re.UNICODE) return '{}-{}.dist-info'.format(escaped_name, escaped_version)
bigcode/self-oss-instruct-sc2-concepts
def repr2(x): """Analogous to repr(), but will suppress 'u' prefix when repr-ing a unicode string.""" s = repr(x) if len(s) >= 2 and s[0] == "u" and (s[1] == "'" or s[1] == '"'): s = s[1:] return s
bigcode/self-oss-instruct-sc2-concepts
def get_fix_string(input_string: str, length: int): """ Transforms input_string to the string of the size length. Parameters ---------- input_string : str input_string length : int length of output_string, if -1 then output_string is the same as input_string Returns ------- str beautiful string of the size length """ input_string = str(input_string) if length < 0: output_string = input_string elif len(input_string) > length: sep = (length - 3) // 2 if length % 2 == 0: output_string = input_string[:sep + 1] + "..." + input_string[-sep:] else: output_string = input_string[:sep] + "..." + input_string[-sep:] else: output_string = input_string + " " * (length - len(input_string)) return output_string
bigcode/self-oss-instruct-sc2-concepts
def get_elements_of_type(xform, field_type): """ This function returns a list of column names of a specified type """ return [f.get('name') for f in xform.get_survey_elements_of_type(field_type)]
bigcode/self-oss-instruct-sc2-concepts
from typing import Sequence from typing import Tuple from typing import Optional import re def find_token( string: bytes, pos: int, tokens: Sequence[bytes] ) -> Tuple[Optional[bytes], int]: """Find the first occurrence of any of multiple tokens.""" pattern = re.compile(b"|".join(re.escape(token) for token in tokens)) match = pattern.search(string, pos) if match is None: return None, -1 return match.group(), match.start()
bigcode/self-oss-instruct-sc2-concepts
def get_heatmap_y_sample_sizes(parsed_mutations, sample_sizes): """Get sample size y axis values of heatmap cells. :param parsed_mutations: A dictionary containing multiple merged ``get_parsed_gvf_dir`` return "mutations" values. :type parsed_mutations: dict :param sample_sizes: A dictionary containing multiple merged ``get_parsed_gvf_dir`` return "sample_size" values. :type sample_sizes: dict :return: List of sample size y axis values :rtype: list[str] """ ret = [] for strain in parsed_mutations: ret.append(sample_sizes[strain]) return ret
bigcode/self-oss-instruct-sc2-concepts
def cloudfront_public_lookup(session, hostname): """ Lookup cloudfront public domain name which has hostname as the origin. Args: session(Session|None) : Boto3 session used to lookup information in AWS If session is None no lookup is performed hostname: name of api domain or auth domain. Ex: api.integration.theboss.io Returns: (string|None) : Public DNS name of cloud front or None if it could not be located """ if session is None: return None client = session.client('cloudfront') response = client.list_distributions( MaxItems='100' ) items = response["DistributionList"]["Items"] for item in items: cloud_front_domain_name = item["DomainName"] if item["Aliases"]["Quantity"] > 0: if hostname in item["Aliases"]["Items"]: return cloud_front_domain_name return None
bigcode/self-oss-instruct-sc2-concepts
def check_queue(queue, config): """ Check length and policy of a single queue :param queue: Queue form rabbit :param config: Desired queue state :return: length of a queue and lists of warnings and errors """ warnings = [] errors = [] length = queue['messages_ready'] if length > config['critical']: errors.append(length) elif length > config['warning']: warnings.append(length) policy = config.get('policy') queue_policy = queue.get('effective_policy_definition') if policy and policy != queue_policy: errors.append('Wrong queue policy') return length, warnings, errors
bigcode/self-oss-instruct-sc2-concepts
def news_dict(cleaned_articles): """ For the cleaned_articles data, extract only the headline and summary. :param cleaned_articles: List of dictionaries, extract only the target information. :return: dictionary of Headlines to Summary. """ temp_dict = {} for i in cleaned_articles: temp_dict[i['title']] = i['content'] return temp_dict
bigcode/self-oss-instruct-sc2-concepts
import logging def _create_list_of_class_names(view, label_field): """Create list of class names from the label field. Args: view (voxel51 view object) - the voxel51 dataset label_field (str) - label field set in config Returns: class_names (list) """ logging.info("Extracting class names from label field.") class_names = [] for sample in view.select_fields(label_field): if sample[label_field] is not None: for detection in sample[label_field].detections: label = detection["label"] if label not in class_names: class_names.append(label) logging.info("Finished extracting class names from label field.") return class_names
bigcode/self-oss-instruct-sc2-concepts
def _ResolvePortName(args): """Determine port name if one was not specified.""" if args.port_name: return args.port_name if args.protocol == 'HTTPS': return 'https' if args.protocol == 'SSL': return 'ssl' if args.protocol == 'TCP': return 'tcp' return 'http'
bigcode/self-oss-instruct-sc2-concepts
def check_row(board, num_rows, num_cols): """check if any 4 are connected horizontally(in 1 row) returns bool""" won = False for row in range(num_rows): for col in range(num_cols - 3): start = board[row][col] if start == " ": continue won = True for i in range(1, 4): if start != board[row][col + i]: won = False break if won: return won return won
bigcode/self-oss-instruct-sc2-concepts
def chomp_lines(istream): """ Returns a lazy generator of lines without trailing newline characters from the specified input stream. """ return (line.rstrip('\n\r') for line in istream)
bigcode/self-oss-instruct-sc2-concepts
import math import collections def get_number_of_letter_permutations(permute_word): """ Finds the number of permutations of letters in a given word :param permute_word: a word to find permutations of :return: number of permutations of letters in the word """ # find all letter combinations to get the numerator of the permutation expression letter_combinations = math.factorial(len(permute_word)) # create letter frequency map to find total number of permutations letter_frequencies = collections.Counter(permute_word) # multiply all the frequency values of letters to get the denominator for permutations letter_freq_product = 1 for letter_frequency in letter_frequencies.values(): letter_freq_product *= math.factorial(letter_frequency) # combine the expressions above to calculate permutations letter_permutations = letter_combinations / letter_freq_product return letter_permutations
bigcode/self-oss-instruct-sc2-concepts
import json def load_hash(filepath): """ Load hashes from json file. Parameters ---------- filepath : str path to json file to be loaded Returns ------- dict { str : dict } """ with open(filepath, "r") as f: return json.load(f)
bigcode/self-oss-instruct-sc2-concepts
def _snake_to_dromedary_case(string): """Convert snake_case to dromedaryCase. >>> _snake_to_dromedary_case('snake_case') 'snakeCase' >>> _snake_to_dromedary_case('longer_snake_case_name') 'longerSnakeCaseName' """ words = string.split("_") if len(words) > 1: words[1:] = [w.title() for w in words[1:]] return "".join(words)
bigcode/self-oss-instruct-sc2-concepts
import math def rat_from_rtc(rtc_s): """ Turn a real-time clock value into a radio time value Args: rtc_s: real-time-clock in seconds Returns: rat_s: radio time in seconds rat_t: radio time in ticks """ # Updated assumed RAT tick based on RTC value (magic magic) # Doing the same assumptions as done inside the RF (0x100000000LL/32768) # RTC in ticks like on our devices rtc_sec = int((math.floor(rtc_s) * 32768)) rtc_subsec = int((rtc_s - rtc_sec) * 2 ** 32) new_rat = (rtc_sec << 32) + rtc_subsec # Conservatively assume that we are just about to increment # the RTC Scale with the 4 MHz that the RAT is running # Add the RAT offset for RTC == 0 * / new_rat += 4294967296 / 32768 new_rat *= 4000000 # Scale to 4 MHz ticks new_rat = new_rat / 4294967296 # Store as ticks rat_t = new_rat # Store as time rat_s = new_rat / 4000000 return rat_s, rat_t
bigcode/self-oss-instruct-sc2-concepts
def _translate_keyname(inp): """map key names in settings file to key names in HotKeys """ convert = {'Escape': 'Esc', 'Delete': 'Del', 'Return': 'Enter', 'Page_up': 'PgUp', 'Page_down': 'PgDn', 'NUMPAD_ENTER': 'NumEnter'} if inp in convert: out = convert[inp] else: out = inp return out
bigcode/self-oss-instruct-sc2-concepts
from itertools import zip_longest def grouper(n, iterable, fillvalue=None): """ Split an iterable in groups of max N elements. grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx """ args = [iter(iterable)] * n if fillvalue: return zip_longest(fillvalue=fillvalue, *args) for chunk in zip_longest(*args): yield filter(None, chunk)
bigcode/self-oss-instruct-sc2-concepts
def andGate(a, b): """ Input: a, b Two 1 bit values as 1/0 Returns: 1 if both incoming bits are 1 otherwise 0 """ if a == 1 and b == 1: return 1 else: return 0
bigcode/self-oss-instruct-sc2-concepts
import torch def select_device() -> str: """Selects the device to use, either CPU (default) or CUDA/GPU; assuming just one GPU.""" return "cuda" if torch.cuda.is_available() else "cpu"
bigcode/self-oss-instruct-sc2-concepts
def _normalize_integer_rgb(value: int) -> int: """ Internal normalization function for clipping integer values into the permitted range (0-255, inclusive). """ return 0 if value < 0 else 255 if value > 255 else value
bigcode/self-oss-instruct-sc2-concepts
def count_descendents(graph, root): """ Inputs: A weighted directed acyclic `graph` with positive edge weights and a starting `root` node Let the weight of a path in the graph be the product of the weights of its constituent edges and 0 if the path is trivial with no edges Returns: The sum of the weights of all paths in the graph starting at the `root` node """ if len(graph[root]) == 0: # `root` has no children, so no (paths to) descendents contributing to the sum/count return 0 # Iterate over each child, multiplying by the weight of edge from root to child before recursing # This counts the child node itself as well as all of the higher degree descendents return sum(count * (1 + count_descendents(graph, node)) for node, count in graph[root].items())
bigcode/self-oss-instruct-sc2-concepts
import re def applyRegexps(text, listRegExp): """ Applies successively many regexps to a text""" # apply all the rules in the ruleset for element in listRegExp: left = element['left'] right = element['right'] r = re.compile(left) text = r.sub(right, text) return text
bigcode/self-oss-instruct-sc2-concepts
def is_multiple(n, divide): """ >>> is_multiple(0, 1) False >>> is_multiple(10, 1) True >>> is_multiple(10, 2) True >>> is_multiple(10, 3) False """ return (0 != n) and (0 == (n % divide))
bigcode/self-oss-instruct-sc2-concepts
import csv def detect(stream): """Returns True if given stream is valid CSV.""" try: csv.Sniffer().sniff(stream, delimiters=',') return True except (csv.Error, TypeError): return False
bigcode/self-oss-instruct-sc2-concepts
from typing import List def rotate90(buttonsIdx: List[int]) -> List[int]: """ Rotate puzzle by 90 degrees counterclockwise. :param buttonsIdx: list with position index for each button and empty cell :returns: list with positions after rotation """ newButtonsIdx = [] for i in buttonsIdx: row, col = i//4, i%4 newCol = row newRow = 3 - col newButtonsIdx.append(newRow*4 + newCol) return newButtonsIdx
bigcode/self-oss-instruct-sc2-concepts
def get_equivalence_ratio( p_fuel, p_oxidizer, f_a_st ): """ Simple equivalence ratio function Parameters ---------- p_fuel : float or un.ufloat Partial pressure of fuel p_oxidizer : float or un.ufloat Partial pressure of oxidizer f_a_st : float or un.ufloat Stoichiometric fuel/air ratio Returns ------- float or un.ufloat Mixture equivalence ratio """ return p_fuel / p_oxidizer / f_a_st
bigcode/self-oss-instruct-sc2-concepts
def sv_length(pos, end, chrom, end_chrom, svlen=None): """Return the length of a structural variant Args: pos(int) end(int) chrom(str) end_chrom(str) svlen(int) Returns: length(int) """ if chrom != end_chrom: return int(10e10) if svlen: return abs(int(svlen)) # Some software does not give a length but they give END if not end: return -1 if end == pos: return -1 return end - pos
bigcode/self-oss-instruct-sc2-concepts
def sampling(generate_data, nb_samples): """ Generates nb_samples from generate_data :param generate_data: Function that takes takes an integer n and samples from a synthetic distribution. Returns an array of n samples. :param nb_samples: Number of samples to generate :return: Samples. Shape=(nb_samples, nb_genes) """ return generate_data(nb_samples)
bigcode/self-oss-instruct-sc2-concepts
def identity(x, name=None): """Returns a tensor with the same content as the input tensor. # Arguments x: The input tensor. name: String, name for the variable to create. # Returns A tensor of the same shape, type and content. """ return x.copy(name=name)
bigcode/self-oss-instruct-sc2-concepts
import math def same_padding(in_dim, kernel_dim, stride_dim): """ Calculates the output dimension and also the padding required for that dimension. :param in_dim: Width/Height of Input :param kernel_dim: Width/Height of Kernel :param stride_dim: Vertical/Horizontal Stride """ output_dim = math.ceil(float(in_dim) / float(stride_dim)) pad = ((output_dim - 1) * stride_dim + kernel_dim - in_dim) / 2 return output_dim, pad
bigcode/self-oss-instruct-sc2-concepts
def parameters_equal(a, b): """Compares two parameter instances Checks full name, data, and ranges. Does not consider the comment. :return: True or False :raises: ValueError if both inputs are no parameter instances """ if (not b.v_is_parameter and not a.v_is_parameter): raise ValueError('Both inputs are not parameters') if (not b.v_is_parameter or not a.v_is_parameter): return False if a.v_full_name != b.v_full_name: return False if a.f_is_empty() and b.f_is_empty(): return True if a.f_is_empty() != b.f_is_empty(): return False if not a._values_of_same_type(a.f_get(), b.f_get()): return False if not a._equal_values(a.f_get(), b.f_get()): return False if a.f_has_range() != b.f_has_range(): return False if a.f_has_range(): if a.f_get_range_length() != b.f_get_range_length(): return False for myitem, bitem in zip(a.f_get_range(copy=False), b.f_get_range(copy=False)): if not a._values_of_same_type(myitem, bitem): return False if not a._equal_values(myitem, bitem): return False return True
bigcode/self-oss-instruct-sc2-concepts
def binary_string(number: int) -> str: """Number to binary string :param number: some number (an integer) to turn into a binary string :return: Some string which is the binary string :rtype: str .. doctest:: python >>> binary_string(200) '11001000' >>> binary_string(10) '1010' """ return bin(number)[2:]
bigcode/self-oss-instruct-sc2-concepts
def get_ytid2labels(segment_csv): """ compute the mapping (dict object) from youtube id to audioset labels. """ with open(segment_csv) as F: lines = F.read().split('\n') lines = [l for l in lines if len(l) > 0 and l[0] != '#'] ytid2labels = {l.split(',')[0]: l.split('"')[-2] for l in lines} return ytid2labels
bigcode/self-oss-instruct-sc2-concepts
def get_bind_addr(conf, default_port=None): """Return the host and port to bind to.""" return (conf.bind_host, conf.bind_port or default_port)
bigcode/self-oss-instruct-sc2-concepts
def _part(f): """ Return a character representing a partly-filled cell with proportion `f` (rounded down to width of nearest available character). """ return [" ", "▏", "▎", "▍", "▌", "▋", "▊", "▉", "█"][int(9*f)]
bigcode/self-oss-instruct-sc2-concepts
def join_infile_path(*paths): """ Join path components using '/' as separator. This method is defined as an alternative to os.path.join, which uses '\\' as separator in Windows environments and is therefore not valid to navigate within data files. Parameters: ----------- *paths: all strings with path components to join Returns: -------- A string with the complete path using '/' as separator. """ # Join path components path = '/'.join(paths) # Correct double slashes, if any is present path = path.replace('//', '/') return path
bigcode/self-oss-instruct-sc2-concepts
def get_latlon_from_cube(cube): """Return domain covered by cube, taking into account cell boundaries :param cube: target cube :return: tuple(lat_max, lat_min, lon_max, lon_min, nlat, nlon) """ for latlon in ['latitude', 'longitude']: if not cube.coord(latlon).has_bounds(): cube.coord(latlon).guess_bounds() longitude = cube.coord('longitude') latitude = cube.coord('latitude') nlon = len(longitude.points) nlat = len(latitude.points) lon_min, lon_max = longitude.bounds[0, 0], longitude.bounds[-1, 1] lat_min, lat_max = latitude.bounds[0, 0], latitude.bounds[-1, 1] return lat_max, lat_min, lon_max, lon_min, nlat, nlon
bigcode/self-oss-instruct-sc2-concepts
def trapezoid(poly, lower, upper): """Calculate trapezoid slice from two polynomial evaluations and step size""" lower_value = poly.evaluate(lower) upper_value = poly.evaluate(upper) return (upper - lower) * ((lower_value + upper_value)/2.0)
bigcode/self-oss-instruct-sc2-concepts
def set_dict_indices(my_array): """Creates a dictionary based on values in my_array, and links each of them to an index. Parameters ---------- my_array: An array (e.g. [a,b,c]) Returns ------- my_dict: A dictionary (e.g. {a:0, b:1, c:2}) """ my_dict = {} i = 0 for value in my_array: my_dict[value] = i i += 1 return my_dict
bigcode/self-oss-instruct-sc2-concepts
def get_day_of_the_week_number_from_datetime(datetime_obj) -> int: """Does what the function title states.""" return datetime_obj.weekday()
bigcode/self-oss-instruct-sc2-concepts
import logging def setup_logging(args): """Setup logging for the application""" log = logging.getLogger(__package__) log.setLevel(args.loglevel) # disable root logger handlers root_logger = logging.getLogger() root_logger.handlers = [] # set log output destination if args.logfile: handler = logging.FileHandler('mosyco.log', mode='w') else: handler = logging.StreamHandler() handler.setFormatter(logging.Formatter('{name}: {message}', style='{')) root_logger.addHandler(handler) # set prophet loglevel logging.getLogger('fbprophet').setLevel(logging.WARNING) return log
bigcode/self-oss-instruct-sc2-concepts
def count(val, iterable): """ Counts how many times a value (val) occurs in an iterable, excluding `None` :param val: The value to be counted :param iterable: values to be counted over :type iterable: iterable :return: the count of values :rtype: int """ return sum(1 for x in (y for y in iterable if y is not None) if val == x)
bigcode/self-oss-instruct-sc2-concepts
def format_metrics(metrics, split): """Formats metrics for logging. Args: metrics: Dictionary with metrics. split: String indicating the KG dataset split. Returns: String with formatted metrics. """ result = '\t {} MR: {:.2f} | '.format(split, metrics['MR']) result += 'MRR: {:.3f} | '.format(metrics['MRR']) result += 'H@1: {:.3f} | '.format(metrics['hits@[1,3,10]'][0]) result += 'H@3: {:.3f} | '.format(metrics['hits@[1,3,10]'][1]) result += 'H@10: {:.3f}'.format(metrics['hits@[1,3,10]'][2]) return result
bigcode/self-oss-instruct-sc2-concepts
def word_count(review_str)->int: """ count number of words in a string of reviews """ return len(review_str.split())
bigcode/self-oss-instruct-sc2-concepts
def _kl_normal_loss(mean, logvar, storer=None): """ Calculates the KL divergence between a normal distribution with diagonal covariance and a unit normal distribution. Parameters ---------- mean : torch.Tensor Mean of the normal distribution. Shape (batch_size, latent_dim) where D is dimension of distribution. logvar : torch.Tensor Diagonal log variance of the normal distribution. Shape (batch_size, latent_dim) storer : dict Dictionary in which to store important variables for vizualisation. """ latent_dim = mean.size(1) # batch mean of kl for each latent dimension latent_kl = 0.5 * (-1 - logvar + mean.pow(2) + logvar.exp()).mean(dim=0) total_kl = latent_kl.sum() if storer is not None: storer['kl_loss'].append(total_kl.item()) for i in range(latent_dim): storer['kl_loss_' + str(i)].append(latent_kl[i].item()) return total_kl
bigcode/self-oss-instruct-sc2-concepts
import torch def index2points(points, idx): """Construct edge feature for each point Parameters ---------- points: (batch_size, num_dims, num_points) idx: (batch_size, num_points) or (batch_size, num_points, k) Returns ------- edge_features: (batch_size, num_dims, num_points) or (batch_size, num_dims, num_points, k) """ B, C, N = points.shape idx_shape = idx.shape idx_base = torch.arange(0, B, device=points.device).view(-1, *[1]*(len(idx_shape)-1)) * N # if len(idx_shape) = 3, .view(-1, 1, 1) idx = idx + idx_base idx = idx.view(-1) # (batch_size, num_dims, num_points) -> (batch_size, num_points, num_dims) points = points.transpose(2, 1).contiguous() feature = points.view(B*N, -1) feature = feature[idx, :] edge_feature = feature.view(*idx_shape, C) # (batch_size, num_points, num_dims) -> (batch_size, num_dims, num_points, ...) edge_feature = edge_feature.permute(0, -1, *range(1, len(idx_shape))) edge_feature = edge_feature.contiguous() return edge_feature
bigcode/self-oss-instruct-sc2-concepts
from typing import IO def read_line(in_fd: IO[str]) -> str: """ Reads a single line from a file in bytes mode :param in_fd: Input file descriptor :return: The line (from in_fd current position), without EOL """ result = [] while True: # Ignore the first line read_char = in_fd.read(1) if not read_char or read_char == "\n": # Don't include EOL or EOF break result.append(read_char) return "".join(result)
bigcode/self-oss-instruct-sc2-concepts
def compute_Cp(T,Cv,V,B0,beta): """ This function computes the isobaric heat capacity from the equation: :math:`Cp - Cv = T V beta^2 B0` where *Cp,Cv* are the isobaric and isocoric heat capacities respectively, *T* is the temperature, *V* the unit cell volume, *beta* the volumetric thermal expansion and *B0* the isothermal bulk modulus. """ Cp = Cv + T * V * beta * beta * B0 return Cp
bigcode/self-oss-instruct-sc2-concepts
def _architecture(target): """Returns architecture for current active target, e.g. i386, x86_64, armv7""" return target.GetTriple().split('-', 1)[0]
bigcode/self-oss-instruct-sc2-concepts
import torch def _tokenize_str(string, char_tensor=None): """ Parses a utf-8 encoded string and assigns to ByteTensor char_tensor. If no char_tensor is provide one is created. Typically used internally by `tokenize_str_batch`. """ if char_tensor is None: char_tensor = torch.ByteTensor(len(string.encode())) for i, char in enumerate(string): char_tensor[i] = char return char_tensor
bigcode/self-oss-instruct-sc2-concepts
import logging def is_encoded_image_spec(tensor_spec): """Determines whether the passed tensor_spec speficies an encoded image.""" if hasattr(tensor_spec, 'data_format'): # If tensor_spec is an ExtendedTensorSpec, use the data_format to check. return (tensor_spec.data_format is not None) and ( tensor_spec.data_format.upper() in ['JPEG', 'PNG']) else: # Otherwise default to the old "name contains 'image'" logic. logging.warn('Using a deprecated tensor specification. ' 'Use ExtendedTensorSpec.') return 'image' in tensor_spec.name
bigcode/self-oss-instruct-sc2-concepts
def colour_linear_interpolation(col_a, col_b, t): """ Linearly interpolates between two colours. """ col = tuple([a + (b - a) * t for a, b in zip(col_a, col_b)]) return col
bigcode/self-oss-instruct-sc2-concepts
def is_valid_instant(x): """ Returns true iff x is a well-shaped concrete time instant (i.e. has a numeric position). """ try: return hasattr(x, "inTimePosition") and len(x.inTimePosition) > 0 and \ len(x.inTimePosition[0].numericPosition) > 0 except TypeError: return False
bigcode/self-oss-instruct-sc2-concepts
def truncate_val(val, lower_bound, upper_bound): """Truncate val to be in the range [lower_bound, upper_bound].""" val = max(val, lower_bound) val = min(val, upper_bound) return val
bigcode/self-oss-instruct-sc2-concepts
def _access(*args, **kargs): """Assume access to the path is allowed.""" return True
bigcode/self-oss-instruct-sc2-concepts
def write(file, lines): """ Write file from an array """ with open(file, 'w') as f: bytes_ = f.write('\n'.join(lines[0:]) + '\n') return bytes_
bigcode/self-oss-instruct-sc2-concepts
def getQuestionLabels(task_question_answer_labels, task_uuid): """ Gets a list of question labels under the same task uuid """ series = task_question_answer_labels[task_question_answer_labels["quiz_task_uuid"] == task_uuid] return series["question_label"].unique().tolist()
bigcode/self-oss-instruct-sc2-concepts
def cli_cosmosdb_gremlin_database_throughput_migrate(client, resource_group_name, account_name, database_name, throughput_type): """Migrate an Azure Cosmos DB Gremlin database throughput""" if throughput_type == "autoscale": return client.migrate_gremlin_database_to_autoscale(resource_group_name, account_name, database_name) return client.migrate_gremlin_database_to_manual_throughput(resource_group_name, account_name, database_name)
bigcode/self-oss-instruct-sc2-concepts
def contrib_xref(contrib_tag, ref_type): """ Given a contrib tag, look for an xref tag of type ref_type directly inside the contrib tag """ aff_tags = [] for child_tag in contrib_tag: if ( child_tag and child_tag.name and child_tag.name == "xref" and child_tag.get("ref-type") and child_tag.get("ref-type") == ref_type ): aff_tags.append(child_tag) return aff_tags
bigcode/self-oss-instruct-sc2-concepts
from typing import List import random import itertools def get_model_nncf_cat() -> List: """Test helper for getting cartesian product of models and categories. Returns: List: Returns a combination of models with their nncf support for each category. """ model_support = [ ("padim", False), ("dfkde", False), ("dfm", False), ("stfpm", False), # ("stfpm", True), ("patchcore", False), ("cflow", False), ("ganomaly", False), ] categories = random.sample( [ "bottle", "cable", "capsule", "carpet", "grid", "hazelnut", "leather", "metal_nut", "pill", "screw", "tile", "toothbrush", "transistor", "wood", "zipper", ], k=3, ) return [ (model, nncf, category) for ((model, nncf), category) in list(itertools.product(*[model_support, categories])) ]
bigcode/self-oss-instruct-sc2-concepts
def get_hyperhdr_device_id(server_id: str, instance: int) -> str: """Get an id for a HyperHDR device/instance.""" return f"{server_id}_{instance}"
bigcode/self-oss-instruct-sc2-concepts
def strict_forall(l, f): """Takes an iterable of elements, and returns (True, None) if f applied to each element returns True. Otherwise it returns (False, e) where e is the first element for which f returns False. Arguments: - `l`: an iterable of elements - `f`: a function that applies to these elements """ for e in l: if f(e) == False: return (False, e) elif f(e) == True: pass else: raise TypeError("Expected a Boolean") return (True, None)
bigcode/self-oss-instruct-sc2-concepts
import pyclbr def is_handler_subclass(cls, classnames=("ViewHandler", "APIHandler")): """Determines if ``cls`` is indeed a subclass of ``classnames`` This function should only be used with ``cls`` from ``pyclbr.readmodule`` """ if isinstance(cls, pyclbr.Class): return is_handler_subclass(cls.super) elif isinstance(cls, list): return any(is_handler_subclass(s) for s in cls) elif isinstance(cls, str): return cls in classnames else: raise TypeError( "Unexpected pyclbr.Class.super type `{}` for class `{}`".format( type(cls), cls ) )
bigcode/self-oss-instruct-sc2-concepts
def create_label_column(row) -> str: """ Helper function to generate a new column which will be used to label the choropleth maps. Function used to label missing data (otherwise they will show up on the map as "-1 SEK"). Parameters ---------- row : Returns ------- str Column label to show when user hovers mouse over a choropleth map. """ if row["Median Rent (SEK)"] > 0: return "Median Cost: " + str(int(row["Median Rent (SEK)"])) + " SEK" else: return "Missing Data"
bigcode/self-oss-instruct-sc2-concepts
import pathlib def derive_filepath(filepath, append_string='', suffix=None, path=None): """Generate a file path based on the name and potentially path of the input file path. Parameters ---------- filepath: str of pathlib.Path Path to file. append_string: str String to append to file name stem. Default: ''. suffix: str or None File extension to use. If None, the same as video file. path: str or pathlib.Path or None Path to use. If None use same path as video file. Returns ------- pathlib.Path Path derived from video file path. """ stem = filepath.stem if suffix is None: suffix = filepath.suffix filename = f'{stem}_{append_string}{suffix}' if path is None: dpath = filepath.parent / filename else: dpath = pathlib.Path(path) / filename return dpath
bigcode/self-oss-instruct-sc2-concepts
def gather_pages(pdfs: list) -> list: """ Creates a list of pages from a list of PDFs. Args: pdfs (list): List of PDFs to collate. Returns: list: List of pages from all passed PDFs. """ output = [] for pdf in pdfs: for page in pdf.pages: output.append(page) return output
bigcode/self-oss-instruct-sc2-concepts
import torch def create_alternating_binary_mask(features, even=True): """ Creates a binary mask of a given dimension which alternates its masking. :param features: Dimension of mask. :param even: If True, even values are assigned 1s, odd 0s. If False, vice versa. :return: Alternating binary mask of type torch.Tensor. """ mask = torch.zeros(features).byte() start = 0 if even else 1 mask[start::2] += 1 return mask
bigcode/self-oss-instruct-sc2-concepts
def parse_none(*args): """Return tuple of arguments excluding the ones being None.""" return tuple(arg if arg is not None else "" for arg in args)
bigcode/self-oss-instruct-sc2-concepts
def remove_dupes(items): """ make sure no item appears twice in list i.e. filter for any duplicates """ clean = [] for i in items: if not i in clean: clean.append(i) return clean
bigcode/self-oss-instruct-sc2-concepts
def wordList(fname = 'dictionaryWords.txt'): """Generate list of possible words from the passed file.""" wordlist = [] with open(fname, 'r') as fin: for word in fin: word = word.rstrip() ; wordlist.append(word) return wordlist
bigcode/self-oss-instruct-sc2-concepts
def calc_electrons_from_photons(photons, quantum_efficiency): """ Calculate the number of electrons generated by incident photons. Returns ------- int : no units, a number of electrons """ return int(photons * quantum_efficiency)
bigcode/self-oss-instruct-sc2-concepts
def _gutenberg_simple_parse(raw_content): """Clean a project Gunteberg file content.""" content = raw_content # *** START OF THIS PROJECT GUTENBERG EBOOK THE RED BADGE OF COURAGE *** starts = [ '*** START OF THIS PROJECT GUTENBERG EBOOK', '***START OF THE PROJECT GUTENBERG EBOOK', '*** START OF THE PROJECT GUTENBERG EBOOK', '*END*THE SMALL PRINT! FOR PUBLIC DOMAIN', '*END THE SMALL PRINT! FOR PUBLIC DOMAIN', 'This etext was prepared by', 'This Etext was prepared by', 'This etext was provided by', 'This Etext prepared by ', '***START OF THIS PROJECT GUTENBERG EBOOK', ] # *** END OF THIS PROJECT GUTENBERG EBOOK THE RED BADGE OF COURAGE *** ends = [ '*** END OF THIS PROJECT GUTENBERG EBOOK', '***END OF THE PROJECT GUTENBERG EBOOK', '*** END OF THE PROJECT GUTENBERG EBOOK', 'End of Project Gutenberg Etext', 'End of this Project Gutenberg Etext', 'End of the Project Gutenberg Etext', 'End of The Project Gutenberg Etext', 'End of the Project Gutenberg etext', 'End of Project Gutenberg\'s Etext of ', 'END OF PROJECT GUTENBERG ETEXT OF ', '***END OF THIS PROJECT GUTENBERG EBOOK', ] has_start = any([s in content for s in starts]) has_end = any([e in content for e in ends]) if not has_start or not has_end: return None start_index = max([content.rfind(s) for s in starts]) end_index = min([content.find(e) % len(content) for e in ends]) # Strip the prefix: '*** START OF THIS PROJECT GUTENBERG EBOOK ***' _, content = content[start_index:end_index].split('\n', 1) return content
bigcode/self-oss-instruct-sc2-concepts
def counter_mean(counter): """Takes the mean of a collections.Counter object (or dictionary).""" mean = 0. total = 0. for k, v in counter.items(): if k <= 0: k = 200 mean += k * v total += v return mean / total
bigcode/self-oss-instruct-sc2-concepts
import torch def quat_conj(Q): """ Returns the conjugate of the given quaternion Parameters ---------- Q : Tensor the (4,) or (N,4,) quaternion tensor Returns ------- Tensor the (4,) or (N,4,) conjugate quaternion tensor """ return Q * torch.tensor([-1, -1, -1, 1])
bigcode/self-oss-instruct-sc2-concepts
def xauth(auth): """Expand authentication token >>> xauth(None) >>> xauth(('user', 'pass')) ('user', 'pass') >>> xauth('user:pass') ('user', 'pass') >>> xauth('apikey') ('apikey', '') """ if auth is None or isinstance(auth, tuple): return auth else: u, _, p = auth.partition(':') return u, p
bigcode/self-oss-instruct-sc2-concepts
import json def _get_codes(error_response_json): """Get the list of error codes from an error response json""" if isinstance(error_response_json, str): error_response_json = json.loads(error_response_json) error_response_json = error_response_json.get("error") if error_response_json is None: return [] code = error_response_json.get('code') if code is None: raise ValueError("Error response does not contain an error code.") codes = [code] inner_error = error_response_json.get( 'inner_error', error_response_json.get('innerError', None)) while inner_error is not None: code = inner_error.get('code') if code is None: break codes.append(code) inner_error = inner_error.get( 'inner_error', inner_error.get('innerError', None)) return codes[::-1]
bigcode/self-oss-instruct-sc2-concepts
def get_channel_id(data: dict) -> str: """Return channel id from payload""" channel = data['channel'] return channel
bigcode/self-oss-instruct-sc2-concepts