seed
stringlengths
1
14k
source
stringclasses
2 values
def convert_macaddr(addr): """Convert mac address to unique format.""" return addr.replace(':', '').lower()
bigcode/self-oss-instruct-sc2-concepts
def ingest_configs(datacube_env_name): """ Provides dictionary product_name => config file name """ return { 'ls5_nbar_albers': 'ls5_nbar_albers.yaml', 'ls5_pq_albers': 'ls5_pq_albers.yaml', }
bigcode/self-oss-instruct-sc2-concepts
def storeUpdateResult(cache): """ Store results Update T0 Store temperaure results into a dataframe and save it in the cache. """ timeStep = cache['ts'] TProfile = cache['TProfile'] T = cache['T'] cache['T0'] = T.copy() TProfile[:,timeStep] = T.reshape(1,-1) return cach...
bigcode/self-oss-instruct-sc2-concepts
from typing import Any from typing import Optional from typing import Dict def default_target_fcn(actor: Any, instances: tuple, kwargs: Optional[Dict] = None): """ A target function that is executed in parallel given an actor pool. Its arguments must be an actor and a batch of values to be processed by th...
bigcode/self-oss-instruct-sc2-concepts
import typing def parse_tuple_string(argument: typing.Union[str, typing.Tuple, typing.List], type_func=int) -> typing.Optional[typing.Tuple]: """ Return a tuple from parsing 'a,b,c,d' -> (a,b,c,d) """ if argument is None: return None if isinstance(argument, str): ret...
bigcode/self-oss-instruct-sc2-concepts
def select_from_batch(advs, batch): """ Take a rollout-shaped list of lists and select the indices from the mini-batch. """ indices = zip(batch['rollout_idxs'], batch['timestep_idxs']) return [advs[x][y] for x, y in indices]
bigcode/self-oss-instruct-sc2-concepts
def _before_underscore(s): """ :type s: str :rtype: str >>> _before_underscore('LC80880750762013254ASA00_IDF.xml') 'LC80880750762013254ASA00' >>> _before_underscore('LC80880750762013254ASA00_MD5.txt') 'LC80880750762013254ASA00' >>> _before_underscore('383.000.2013137232105971.ASA') ...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime from typing import List def parse_text(now: datetime, key: str, group: List[str]) -> str: """ Handles the Text presentation https://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html#text """ # Era designator if key == "G": # no length impli...
bigcode/self-oss-instruct-sc2-concepts
def is_valid_uni(uni): """ Validate the syntax of a uni string """ # UNIs are (2 or 3 letters) followed by (1 to 4 numbers) # total length 3~7 if not isinstance(uni,str): return False if len(uni) < 3 or len(uni) > 7: return False if uni[:3].isalpha(): # 3 letters return uni[3:].isnumeric() elif uni[:2]....
bigcode/self-oss-instruct-sc2-concepts
def _rear_right_tire_pressure_supported(data): """Determine if rear right tire pressure is supported.""" return data["status"]["tirePressure"]["rearRightTirePressurePsi"] is not None
bigcode/self-oss-instruct-sc2-concepts
def ChangeExtension(file_name, old_str, new_str): """ Change the 'extension' at the end a file or directory to a new type. For example, change 'foo.pp' to 'foo.Data' Do this by substituting the last occurance of 'old_str' in the file name with 'new_str'. This is required because the file name may c...
bigcode/self-oss-instruct-sc2-concepts
def _build_bit_string_set(b_strings, dif_qubits, dif_values): """ Creates a new set of bit strings from b_strings, where the bits in the indexes in dif_qubits match the values in dif_values. Args: b_strings: list of bit strings eg.: ['000', '011', ...,'101'] dif_qubits: list of integer...
bigcode/self-oss-instruct-sc2-concepts
def _filter_subword(sentence, pattern_list): """ If the sentence contains any pattern in the pattern_list as a single word or phrase, return true, else false """ word = False sentence = sentence.replace('-', ' ') sentence = sentence.replace('/', ' ') sentence = sentence.replace('_', ' '...
bigcode/self-oss-instruct-sc2-concepts
def split(iterable, f): """Split an iterable ``I`` into two iterables ``I1`` and ``I2`` of the same type as ``I``. ``I1`` contains all elements ``e`` in ``I`` for which ``f(e)`` returns True; ``I2`` is the complement of ``I1``.""" i1 = type(iterable)(i for i in iterable if f(i)) i2 = type(iterable)(...
bigcode/self-oss-instruct-sc2-concepts
def logEq(a, b): """Returns 1 if the logical value of a equals the logical value of b, 0 otherwise""" return (not a) == (not b)
bigcode/self-oss-instruct-sc2-concepts
import hashlib def md5(string): """ Calculates a MD% sum of the provided string :param string: The string to calculate teh MD% sum :returns: MD% sum of the provided string """ return hashlib.md5(string.encode('utf-8')).hexdigest()
bigcode/self-oss-instruct-sc2-concepts
def cloud_mask_ls8(image): """ Function to mask clouds based on the pixel_qa band of Landsat 8 SR data :param {ee.Image} image input Landsat 8 SR image :return {ee.Image} cloudmasked Landsat 8 image """ # Bits 3 and 5 are cloud shadow and cloud, respectively. cloudShadowBitMask = (1 << 3) ...
bigcode/self-oss-instruct-sc2-concepts
def solve(grades): """ Return grades rounded up to nearest 5 if above 38, otherwise, do not round the score. """ rounded_grades = [] for grade in grades: if grade >= 38: rounded = ((grade + 5) / 5) * 5 if rounded - grade < 3: grade = rounded ...
bigcode/self-oss-instruct-sc2-concepts
def put(a, ind, v, mode='raise'): """ Replaces specified elements of an array with given values. The indexing works on the flattened target array. `put` is roughly equivalent to: :: a.flat[ind] = v Parameters ---------- a : ndarray Target array. ind : array_like ...
bigcode/self-oss-instruct-sc2-concepts
import json def jinja_resilient_substitute(value, json_str): """jinja custom filter to replace values based on a lookup dictionary Args: value ([str]): [original value] json_str ([str]): [string encoded json lookup values] Returns: [str]: [replacement value or original value if n...
bigcode/self-oss-instruct-sc2-concepts
import io def ReadSymbolTable(path, skip_epsilon=False): """Read a bijective symbol table in OpenFst text format.""" symbol2label = {} label2symbol = {} with io.open(path, mode='rt', encoding='utf-8') as reader: for line in reader: line = line.rstrip('\n') fields = line.split() assert le...
bigcode/self-oss-instruct-sc2-concepts
import gzip def build_geneinfo(bed): """ Loads bed file into a dictionary with the key being the name and a string being the value Input: BED -- a bed file to load Return: A dictionary with the key being the name position of the bed file and the values being the ordered bed...
bigcode/self-oss-instruct-sc2-concepts
import sqlite3 def table_drop(cursor, table_name): """ Delete a table Returns: ``True`` if table was removed, ``False`` else """ sql_command = f"DROP TABLE '{table_name}';" try: cursor.execute(sql_command).fetchall() except sqlite3.OperationalError: return False ...
bigcode/self-oss-instruct-sc2-concepts
def std_value(x: float, m_x: float, s_x: float) -> float: """ This function computes standardized values of a sequence value given its mean and standard deviation. """ return (x - m_x) / s_x
bigcode/self-oss-instruct-sc2-concepts
def add(v1, v2): """ Returns the addition of a two 2-D vectors. """ return (v1[0] + v2[0], v1[1] + v2[1])
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def format_selector_movements(info:Dict[str,str])->str: """Callback to parse the accounts/cards into a string format """ return f"{info['name']} - {info.get('currency','')}"
bigcode/self-oss-instruct-sc2-concepts
def is_anagram(s1, s2): """ Figures out if the two strings are anagrams. Complexity: O(n) Args: s1: str s2: str Returns: boolean, True if s1 is an anagram of s2. """ letters = {} for c in s1: if c in letters: letters[c] += 1 else: ...
bigcode/self-oss-instruct-sc2-concepts
def set_and_true(key, _dict): """Is key in dict and value True? Args: key (str): Key to lookup in dictionary. _dict (dict): The dictionary. Returns: bool: Is key in dict and value True? """ return key in _dict and _dict[key] is True
bigcode/self-oss-instruct-sc2-concepts
def tf_trans(T): """ Return translation vector from 4x4 homogeneous transform """ assert T.shape == (4, 4) return T[0:3, 3]
bigcode/self-oss-instruct-sc2-concepts
def develop(envelope): """ Remove the envelope from a message. :param envelope: PokerTHMessage object that envelops a message :return: PokerTH message from the envelope """ msg = [v for _, v in envelope.ListFields() if v != envelope.messageType] assert len(msg) == 1 assert msg[0].IsInit...
bigcode/self-oss-instruct-sc2-concepts
def get_age_schedule_table(schedules): """ Generate a table of initial ages, schedule number, period number, and current age. """ age_schedules = {} for i in range(0, 200, 10): age_schedules[i] = {} for a, schedule in enumerate(schedules): age = i sch...
bigcode/self-oss-instruct-sc2-concepts
def schema_contest() -> str: """Schema for contest document""" return """ _id 5f70c6f3430508338f95ddab winner slateType 1 gameCount 13 siteSlateId 39913 start 2020-09-27T17:00:00.000Z sport 1 prizePool 4275000 maxEntriesPerUser 150 ...
bigcode/self-oss-instruct-sc2-concepts
def format_kit_descriptor(name, version, iteration): """ Returns a properly formatted kit 'descriptor' string in the format <name>-<version>-<iteration> """ return '{0}-{1}-{2}'.format(name, version, iteration)
bigcode/self-oss-instruct-sc2-concepts
def richclub(graph, fraction=0.1, highest=True, scores=None, indices_only=False): # from http://igraph.wikidot.com/python-recipes#toc6 """Extracts the "rich club" of the given graph, i.e. the subgraph spanned between vertices having the top X% of some score. Scores are given by the vertex degrees by de...
bigcode/self-oss-instruct-sc2-concepts
def chain_length(n, chains): """ Return the chain length of a number n. If the chain length of n isn't stored yet, then calculate it according to the collatz sequence rules recursively and store it for future reference. Also store all the chain lengths for numbers that are found duri...
bigcode/self-oss-instruct-sc2-concepts
def calc_ertelPV(n2, bx, rel_vorticity, g=9.8,f=-1e-4): """ As in Thomas et al., 2013; Thompson et al., 2016 The assumption is made that flow is in geostrophic balance PV can be used as a diagnostic to indicate the suscepptibility of a flow to instability e.g., Hoskins, 1974; Thomas et al., 2008 Wh...
bigcode/self-oss-instruct-sc2-concepts
def extractFolders(folders): """ convert a string of folders to a list of tuples (db , schema, node) :param folders: a string containing folders db-schema-node seperated by , :return: a list of tuples (db , schema, node) """ output = [] folderList = folders.split('-') for folder in fol...
bigcode/self-oss-instruct-sc2-concepts
def pdf_norm_from_kernel( kernel_val: float, **kwargs): """ Just use the pdf_max value passed, usually originating from the distance function. """ return kernel_val
bigcode/self-oss-instruct-sc2-concepts
def batch_binary_confusion_matrix(pred, target): """ Compute the binary confusion matrix for batch of prediction, target. ---------- INPUT |---- pred (torch.tensor) the binary prediction with shape (B x *). |---- target (torch.tensor) the binary ground truth with shape (B x *). OUTPU...
bigcode/self-oss-instruct-sc2-concepts
def _to_value_seq(values): """ :param values: Either a single numeric value or a sequence of numeric values :return: A sequence, possibly of length one, of all the values in ``values`` """ try: val = float(values) return [val,] except (ValueError, TypeError): return valu...
bigcode/self-oss-instruct-sc2-concepts
import yaml def load_yaml_config_file(path): """ Returns the parsed structure from a yaml config file. :param path: Path where the yaml file is located. :return: The yaml configuration represented by the yaml file. """ result = None with open(path, 'r') as steam: result = yaml.safe_lo...
bigcode/self-oss-instruct-sc2-concepts
def usage(cmd='', err=''): """ Prints the Usage() statement for the program """ m = '%s\n' %err m += ' Default usage is to scan latest Task Branch (TB) on SalesForce.\n' m += ' ' m += ' walkSF -c walk -s4.1 \n (walk sForce and enforce approval workflow)' m += ' or\n' m +=...
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def split_tab_pair(x: str) -> Tuple[str, str]: """Split a pair of elements by a tab.""" a, b = x.strip().split('\t') return a, b
bigcode/self-oss-instruct-sc2-concepts
def center_data(x, dim=-1): """ Center x along the dimension dim. :param x: torch.Tensor :param dim: int, dim for centering :return: torch.Tensor, centered x """ return x - x.mean(dim=dim, keepdim=True)
bigcode/self-oss-instruct-sc2-concepts
async def get_text(page, b, norm=True): """Get the inner text of an element""" text = await page.evaluate('(element) => element.textContent', b) if norm: text = text.lower().strip() return text
bigcode/self-oss-instruct-sc2-concepts
import random def shuffle_list(arg): """ Return a shuffled copy of a list """ tmp = arg[:] random.shuffle(tmp) return tmp
bigcode/self-oss-instruct-sc2-concepts
import textwrap def cleantext(text: str) -> str: """ Clean a text string. :param text: The input text :type text: str :return: The cleaned text :rtype: str """ return " ".join(textwrap.dedent(text).strip().split("\n"))
bigcode/self-oss-instruct-sc2-concepts
def slurp(filename): """ Return the contents of filename as a string. >>> 'public domain' in slurp('LICENSE.txt') True """ with open(filename) as file: return file.read()
bigcode/self-oss-instruct-sc2-concepts
def format_date(str_date): """ Prepare string to be used by datetime.strptime using format "%Y-%m-%dT%H:%M:%S%z" :param str_date e.g. 2014-04-17T19:14:29+08:00: :return e.g. 2014-04-17T19:14:29+0800: """ str_length = len(str_date) return str_date[:-6] + str_date[str_length-6:str_length-3] + str_...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def recover_info_from_exception(err: Exception) -> Dict: """ Retrives the information added to an exception by :func:`add_info_to_exception`. """ if len(err.args) < 1: return {} info = err.args[-1] if not isinstance(info, dict): return {} return ...
bigcode/self-oss-instruct-sc2-concepts
def string_index(neg_idx, string): """Solution to exercise R-1.8. Python allows negative integers to be used as indices into a sequence, such as a string. If string s has length n, and expression s[k] is used for index −n ≤ k < 0, what is the equivalent index j ≥ 0 such that s[j] references the sam...
bigcode/self-oss-instruct-sc2-concepts
def padding_mask(seq_k, seq_q): """For masking out the padding part of the keys sequence. Args: seq_k: Keys tensor, with shape [B, L_k] seq_q: Query tensor, with shape [B, L_q] Returns: A masking tensor, with shape [B, L_1, L_k] """ len_q = seq_q.size(1) # `PAD` is 0 pad_mask = seq_k.eq(0) ...
bigcode/self-oss-instruct-sc2-concepts
def attempt_actions_for_machine(machine_action_definition, machine, context, actions): """Check the given actions for a machine and determine which action was successfully taken. For the given list of actions, the corresponding function from the given machine_action_definition will be called with the machi...
bigcode/self-oss-instruct-sc2-concepts
def getSimData(opsimDb, sqlconstraint, dbcols, stackers=None, groupBy='default', tableName=None): """Query an opsim database for the needed data columns and run any required stackers. Parameters ---------- opsimDb : `rubin_sim.maf.db.OpsimDatabase` sqlconstraint : `str` SQL constraint to ap...
bigcode/self-oss-instruct-sc2-concepts
def ribbon(dimensions): """Return total ribbon needed for box of size dimensions The total ribbon is equal to twice the lengths of the shortest two dimensions plus the product of all three dimensions. """ s1, s2, s3 = sorted(dimensions) return (2 * s1) + (2 * s2) + (s1 * s2 * s3)
bigcode/self-oss-instruct-sc2-concepts
def DeleteVersion(client, messages, version): """Deletes a version by its name.""" delete_ver_req = messages.ArtifactregistryProjectsLocationsRepositoriesPackagesVersionsDeleteRequest( name=version) return client.projects_locations_repositories_packages_versions.Delete( delete_ver_req)
bigcode/self-oss-instruct-sc2-concepts
def get_gradient_index(val, min_val, max_val, steps): """ Returns the index in gradient given p-value, minimum value, maximum value and number of steps in gradient. >>> get_gradient_index(0.002, 0.001, 0.0029, 10) 5 >>> get_gradient_index(0.0011, 0.001, 0.0029, 10) 0 >>> get_gradien...
bigcode/self-oss-instruct-sc2-concepts
def getPredictedLabels(model, features): """Run inference on trained model to get predicted class labels.""" return model.predict(features)
bigcode/self-oss-instruct-sc2-concepts
def evaluate_guess(guess: str, mystery: str): """Get the partition label for the mystery word given the guess. There are 3^n different partitions, where n is the number of characters in guess or mystery. Args: guess: word being guessed mystery: candidate for mystery word Returns: ...
bigcode/self-oss-instruct-sc2-concepts
def c_is_fun(text): """ Return desired string for /c/<text> route, replace _ with space """ return "C {}".format(text.replace("_", " "))
bigcode/self-oss-instruct-sc2-concepts
def error_on_blank(_value, _error): """Raises an error if blank""" if _value not in [None, '']: return _value else: raise Exception(_error)
bigcode/self-oss-instruct-sc2-concepts
import six def is_listlike(x): """ >>> is_listlike("foo") False >>> is_listlike(5) False >>> is_listlike(b"foo") False >>> is_listlike([b"foo"]) True >>> is_listlike((b"foo",)) True >>> is_listlike({}) True >>> is_listlike(set()) True >>> is_listlike((x ...
bigcode/self-oss-instruct-sc2-concepts
def _integer_surround(number): """Return the 2 closest integers to number, smaller integer first.""" if number > 0: return int(number), int(number) + 1 else: return int(number) - 1, int(number)
bigcode/self-oss-instruct-sc2-concepts
def get_initial_domains_by_genome_assembly(genome_assembly): """Get a list of defaults HiGlass data ranges for a file. Args: genome_assembly(string): Description of the genome assembly. Returns: A dict with these keys: initialXDomain(list): Contains 2 numbers. The HiGlass display wil...
bigcode/self-oss-instruct-sc2-concepts
def _is_ingredient_heading_1(line): """Returns True for the first heading line of ingredients section.""" return line.strip().lower() == 'amount measure ingredient -- preparation method'
bigcode/self-oss-instruct-sc2-concepts
def date_marker(date, today): """Return a one-character date marker.""" if date == today: return '*' if date == today.tomorrow(): return '+' if date == today.tomorrow(-1): return '-' return ' '
bigcode/self-oss-instruct-sc2-concepts
def find_cl_max_length(codelist): """ find and return the length of the longest term in the codelist :param codelist: codelist of terms :return: integer length of the longest codelist item """ max_length = 0 for term in codelist.split(", "): if len(term) > max_length: max...
bigcode/self-oss-instruct-sc2-concepts
import inspect def derive_top_level_package_name(package_level=0, stack_level=1): """Return top level package name. Args: package_level (int): How many package levels down the caller is. 0 indicates this function is being called from the top level package, 1 indicates that it'...
bigcode/self-oss-instruct-sc2-concepts
import torch def size_to_str(torch_size): """Convert a pytorch Size object to a string""" assert isinstance(torch_size, torch.Size) or isinstance(torch_size, tuple) or isinstance(torch_size, list) return '('+(', ').join(['%d' % v for v in torch_size])+')'
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional import dataclasses def field(description: str, *args, metadata: Optional[dict] = None, **kwargs): """ Creates an instance of :py:func:`dataclasses.field`. The first argument, ``description`` is the description of the field, and will be set as the ``"description"`` key in th...
bigcode/self-oss-instruct-sc2-concepts
def rgb(red, green, blue): """ Return the string HTML representation of the color in 'rgb(red, blue, green)' format. :param red: 0 <= int <= 255 :param green: 0 <= int <= 255 :param blue: 0 <= int <= 255 :return: str """ assert isinstance(red, int) assert 0 <= red < 256 ...
bigcode/self-oss-instruct-sc2-concepts
def has_next_page(content: str) -> bool: """Check whether a Flaticon search page has another page Args: content (str): Contents of the current Flaticon search page Returns: bool: Whether a next page exists """ return "<span>Next page</span>" in content
bigcode/self-oss-instruct-sc2-concepts
def FindNextMultiLineCommentEnd(lines, lineix): """We are inside a comment, find the end marker.""" while lineix < len(lines): if lines[lineix].strip().endswith('*/'): return lineix lineix += 1 return len(lines)
bigcode/self-oss-instruct-sc2-concepts
import math def geo_bounds(xmin, ymin, xmax, ymax): """ Project web mercator bounds to geographic. Parameters ---------- xmin: float ymin: float xmax: float ymax: float Returns ------- [xmin, ymin, xmax, ymax] in geographic coordinates """ merc_max = 20037508.342...
bigcode/self-oss-instruct-sc2-concepts
def get_variation(type_variation, list_detections, str_detections): """Gets a specific variation list of detections""" return list_detections[str_detections.index(type_variation)]
bigcode/self-oss-instruct-sc2-concepts
import re def text_normalization(text): """ Normalize text Remove & Replace unnessary characters Parameter argument: text: a string (e.g. '.... *** New York N.Y is a city...') Return: text: a string (New York N.Y is a city.) """ text = re.sub(u'\u201e|\u201c', u'', text) text ...
bigcode/self-oss-instruct-sc2-concepts
def fortfloat(text: str) -> float: """Convert Fortran-style float to python float.""" text = text.strip() if text.endswith("d"): text = text[:-1] text.replace("d", "e") try: return float(text) except ValueError: if len(text) > 1 and "-" in text[1:]: text = f"{...
bigcode/self-oss-instruct-sc2-concepts
from typing import Counter def build_worddict(data, num_words=None): """ Build a dictionary associating words from a set of premises and hypotheses to unique integer indices. Args: data: A dictionary containing the premises and hypotheses for which a worddict must be built. The di...
bigcode/self-oss-instruct-sc2-concepts
def b64pad(data): """ Pad base64 data with '=' so that it's length is a multiple of 4. """ missing = len(data) % 4 if missing: data += b'=' * (4 - missing) return data
bigcode/self-oss-instruct-sc2-concepts
def _tpi_name(scale, smth_factor): """Return name for the array in output of the tpi function""" add = f"_SMTHFACT{smth_factor:.3g}" if smth_factor else "" return f"TPI_{scale}M{add}"
bigcode/self-oss-instruct-sc2-concepts
def GetDiskConfig(dataproc, boot_disk_type, boot_disk_size, num_local_ssds, local_ssd_interface): """Get dataproc cluster disk configuration. Args: dataproc: Dataproc object that contains client, messages, and resources boot_disk_type: Type of the boot disk boot_disk_size: Size of the...
bigcode/self-oss-instruct-sc2-concepts
def _get_port_to_string(iface): """Simple helper which allows to get string representation for interface. Args: iface(list): Which IXIA interface to use for packet sending (list in format [chassis_id, card_id, port_id]) Returns: str: string in format "chassis_id/card_id/port_id" """ ...
bigcode/self-oss-instruct-sc2-concepts
def __ask_int(message): """ Asks User for an Integer Value Args: message = str - Input from Console """ value = '' while not isinstance(value, int): value = input(message) try: value = int(value) return value except: print("The...
bigcode/self-oss-instruct-sc2-concepts
def default_matching(name: str, target_version: int) -> str: """Default matching method """ return name
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def extended_euclidian_gcd(left: int, right: int) -> Tuple[int, int, int]: """Solve left * x + right * y = gcd(left, right) and return r, x, y.""" new_x, new_y, new_r = 0, 1, right old_x, old_y, old_r = 1, 0, left while new_r != 0: quotient = old_r // new_r old...
bigcode/self-oss-instruct-sc2-concepts
def hex_to_rgb(value): """Converts colour from hex triplet into rgb tuple. value (str): colour as hex triplet """ value = value.lstrip('#') lv = len(value) return tuple(int(value[i:i+lv//3], 16) for i in range(0, lv, lv//3))
bigcode/self-oss-instruct-sc2-concepts
def true_stress(tech_stress, tech_strain): """ Calculate the true stress data from technical data Parameters ---------- tech_stress : array-like float stress data from tensile experiments tech_strain : list of float strain data from tensile experiments Returns ------- ...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def hash_string(strdata: str) -> str: """Hash a string :param strdata: string data to hash :return: hexdigest """ return hashlib.sha1(strdata.encode('utf8')).hexdigest()
bigcode/self-oss-instruct-sc2-concepts
def reciprocal_overlap(astart, aend, bstart, bend): """ Calculates reciprocal overlap of two ranges :param `astart`: First range's start position :type `astart`: int :param `aend`: First range's end position :type `aend`: int :param `bstart`: Second range's start position :type `bstart`...
bigcode/self-oss-instruct-sc2-concepts
import itertools def combine_dictionaries(dictionaries): """Combine a list of non-overlapping dictionaries into one. Args: dictionaries (list): List of dictionaries. Returns: dict: The combined dictionary. Examples: >>> combine_dictionaries([{"a": 1}, {"b": 2}]) {'a...
bigcode/self-oss-instruct-sc2-concepts
def tree_similarity_ratio(ted, t1, t2): """ Return the similarity ratio from 0 to 1 between two trees given their edit distance `ratio` idea from [DiffLib](https://fossies.org/dox/Python-3.5.1/difflib_8py_source.html) """ # print(ted) # import networkx as nx # empty_tree = nx.DiGraph() ...
bigcode/self-oss-instruct-sc2-concepts
def is_number(s): """ This function checks if given input is a float and returns True if so, and False if it is not. :param s: input :return: Boolean. """ try: float(s) return True except ValueError: return False
bigcode/self-oss-instruct-sc2-concepts
from bs4 import BeautifulSoup def soupify(html, vars=[]): """ Convert html string to beautiful soup """ return BeautifulSoup(html.format(vars), "html.parser")
bigcode/self-oss-instruct-sc2-concepts
import array def _prepare_for_sound(mls): """ Re-scale the MLS so that is a proper array of bytes. This allows us to use it with an audio device. We assume 16-bit precision. """ new_mls = [] int_max = 2**15 - 2 for sample in mls: if sample == 0: # Min UInt16 ...
bigcode/self-oss-instruct-sc2-concepts
import logging def get_logging_level(level: str) -> int: """Get the logging level as a logging module constant. :param level: `str` The log level to get. :returns: The log level, defaults to `INFO` """ return getattr(logging, level.upper(), logging.INFO)
bigcode/self-oss-instruct-sc2-concepts
def get_model_name(step): """ Return filename of model snapshot by step :param step: global step of model :type step: int :return: model snapshot file name :rtype: str """ return 'network-snapshot-{:06d}.pth'.format(step)
bigcode/self-oss-instruct-sc2-concepts
import hashlib def sha256(s): """Return SHA256 digest of the string `s`.""" return hashlib.sha256(s).digest()
bigcode/self-oss-instruct-sc2-concepts
def build_path(package_name: str) -> str: """Build path from java package name.""" return package_name.replace(".", "/")
bigcode/self-oss-instruct-sc2-concepts
def extList(l, item): """Add 'item' to list 'l', return index of 'item'""" l.append(item) return len(l)-1
bigcode/self-oss-instruct-sc2-concepts
def parse_branch_ref(filename): """Given a filename of a .git/HEAD file return ref path. In particular, if git is in detached head state, this will return None. If git is in attached head, it will return the branch reference. E.g. if on 'master', the HEAD will contain 'ref: refs/heads/master' so 'refs/heads/...
bigcode/self-oss-instruct-sc2-concepts