seed
stringlengths
1
14k
source
stringclasses
2 values
from typing import Optional from typing import Dict def prepare_ids_str(ids: Optional[Dict]) -> Optional[str]: """Prepare string with EntitySet IDs.""" if isinstance(ids, dict): # Generate ID string (id1='value',id2='value') ids_str = ','.join("{}='{}'".format(k, v) for k, v in ids.items()) ...
bigcode/self-oss-instruct-sc2-concepts
def _to_xml(number): """ convert Python number to XML String representation Keyword Parameters: number -- Python numeric variable >>> _to_xml(0) '0' >>> _to_xml(0.09834894752) '0.09834894752' >>> _to_xml(None) '' """ if number is None: return '' return str(...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union def check_outliers(lower_bound: float, upper_bound: float, current_value: Union[int, float]) -> bool: """ Check if a value is an outliers by comparing it with interquartile range :param lower_bound: lower bound of interquartile range :param upper_bound: upper bound of interqu...
bigcode/self-oss-instruct-sc2-concepts
def convert_cost_units(items): """To convert cost_unit choice type to it's value. For example, for each item's cost_unit tuple (type="per-packet", value="Per Packet") will be converted to a `str` "Per Packet". """ for item in items: item.cost_unit = item.cost_unit.value return items
bigcode/self-oss-instruct-sc2-concepts
def ap(docs, n=10): """Average Precision""" precision_values = [ len([ doc for doc in docs[:idx] if doc["relevant"] == "true" ]) / idx for idx in range(1, n + 1) ] return sum(precision_values) / len(precision_values)
bigcode/self-oss-instruct-sc2-concepts
def shinglelize(text, shingle_size=3): """ Transform an input string to a list of shingles (or n-grams) with a given size. Parameters ---------- text : string Text to shinglelize shingle_size: int, optional, default 3 Size of a shingle Returns ------- shingles : li...
bigcode/self-oss-instruct-sc2-concepts
def format_fold_run(rep=None, fold=None, run=None, mode="concise"): """Construct a string to display the repetition, fold, and run currently being executed Parameters ---------- rep: Int, or None, default=None The repetition number currently being executed fold: Int, or None, default=None ...
bigcode/self-oss-instruct-sc2-concepts
def read_tles(tle_path): """ Convert TLE text files in a given directory to a list of TLEs. Parameters ---------- tle_dir : str Path to the directory containing TLE .txt files. Returns ------- sats : List of lists. Each internal list has the 3 lines of a TLE as its elem...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def file_md5(file_path, buffer_size=1024 * 16): """ Calculate the md5 checksum for the provided file path :param str file_path: path of the file to read :param int buffer_size: read buffer size, default 16k :return str: Hexadecimal md5 string """ md5 = hashlib.md5() wit...
bigcode/self-oss-instruct-sc2-concepts
def unify_equivalent_indels(df): """Unify equivalent indels with highest somatic probability Args: df (pandas.DataFrame): df after left-alignment -> all equivalent indels have same 'chr', 'pos', 'ref', 'alt' Returns: df (pand...
bigcode/self-oss-instruct-sc2-concepts
import socket def getFQDN(default=None): """Return the FQDN.""" fqdn = socket.gethostname() if not '.' in fqdn: return default return fqdn
bigcode/self-oss-instruct-sc2-concepts
def check_for_reqd_cols(data, reqd_cols): """ Check data (PmagPy list of dicts) for required columns """ missing = [] for col in reqd_cols: if col not in data[0]: missing.append(col) return missing
bigcode/self-oss-instruct-sc2-concepts
def sanitize_html(text): """Prevent parsing errors by converting <, >, & to their HTML codes.""" return text\ .replace('<', '&lt;')\ .replace('>', '&gt;')\ .replace('&', '&amp;')
bigcode/self-oss-instruct-sc2-concepts
def get_overridable_template_name(name, plugin, core_prefix='', plugin_prefix=''): """Return template names for templates that may be overridden in a plugin. :param name: the name of the template :param plugin: the :class:`IndicoPlugin` that may override it (can be none) :param core_prefix: the path pr...
bigcode/self-oss-instruct-sc2-concepts
def ndre(nm790, nm720): """function returning a NDRE map. NDRE is calculated as: NDRE = (790nm - 720nm) / (790nm + 720nm) which corresponds to: NDRE = (NIR - RE) / (NIR + RE) Parameters ---------- nm790 : numpy.ndarray 2d-numpy array of the target response at 790nm (NIR) n...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def prettify_wildfire_rule(rule: Dict) -> Dict: """ Args: rule: The profile security rule to prettify. Returns: The rule dict compatible with our standard. """ pretty_rule = { 'Name': rule['@name'], } if isinstance(rule.get('application'), dict) an...
bigcode/self-oss-instruct-sc2-concepts
def convert_v4_address_string_to_bits(ip_address): """ return v4 address string to bits for example: '255.255.0.0' -> '11111111111111110000000000000000' """ return ''.join([bin(int(octet))[2:].zfill(8) for octet in ip_address.split('.')])
bigcode/self-oss-instruct-sc2-concepts
def is_closed(instance, *args, **kwargs): """ Helper function to test if some instance is closed (to be used with ``raise_if`` decorator) :param instance: some instance with ``is_closed`` property accessible :returns: value of ``instance.is_closed`` or False """ return getattr(insta...
bigcode/self-oss-instruct-sc2-concepts
def find_sublist_containing(el, lst, index=False): """ Parameters ---------- el : The element to search for in the sublists of `lst`. lst : collections.Sequence A sequence of sequences or sets. index : bool, default: False If False (default), the subsequence or subset co...
bigcode/self-oss-instruct-sc2-concepts
def round_coordinates(cell_poly): """ Rounds the coords of the polygon Only implemented to pass tests. :param cell_poly: polygon feature :returns: polygon feature """ coords = cell_poly["geometry"]["coordinates"] coords = [ [[round(coord, 6) for coord in point] for point in l...
bigcode/self-oss-instruct-sc2-concepts
def user_is_mentor(user): """Check if a user belongs to Mentor group.""" return user.groups.filter(name='Mentor').exists()
bigcode/self-oss-instruct-sc2-concepts
def dynamic_import(name): """ Dynamically import a class from an absolute path string """ components = name.split(".") mod = __import__(components[0]) for comp in components[1:]: mod = getattr(mod, comp) return mod
bigcode/self-oss-instruct-sc2-concepts
def _get_node_value(nod): """XML parsing helper for extracting text value from an ElementTree Element. No error checking performed. Parameters ---------- nod : ElementTree.Element the xml dom element Returns ------- str the string value of the node. """ if nod.text...
bigcode/self-oss-instruct-sc2-concepts
def n_eff(dlnsdlnm): """ Return the power spectral slope at the scale of the halo radius, Parameters ---------- dlnsdlnm : array The derivative of log sigma with log M Returns ------- n_eff : float Notes ----- Uses eq. 42 in Lukic et. al 2007. """ ...
bigcode/self-oss-instruct-sc2-concepts
def apply_weight_decay_data_parameters(args, loss, class_parameter_minibatch, inst_parameter_minibatch): """Applies weight decay on class and instance level data parameters. We apply weight decay on only those data parameters which participate in a mini-batch. To apply weight-decay on a subset of data para...
bigcode/self-oss-instruct-sc2-concepts
def compute_hash(*args): """Compute a hash vlaue from all given arguments.""" return hash(args)
bigcode/self-oss-instruct-sc2-concepts
def get_ospf(engine): """ Get OSPF settings for the engine :return: dict of entries only if OSPF is enabled """ ospf = engine.dynamic_routing.ospf data = dict( enabled=ospf.status, router_id=ospf.router_id) if ospf.status: data.update(ospf_profile=ospf.profile.na...
bigcode/self-oss-instruct-sc2-concepts
def clean_name(name): """Replace dashes and spaces with underscores""" return '_'.join(name.split()).replace('-', '_')
bigcode/self-oss-instruct-sc2-concepts
def flatten_dictionary(dictionary): """Get a list of tuples with the key value pairs of the dictionary. """ result = [] for k, s in dictionary.items(): for v in s: result.append((k, v)) return result
bigcode/self-oss-instruct-sc2-concepts
def flake8(ctx, noerror=False): """check the project files for correctness with flake8""" return ctx.run(f'python -m flake8 w3modmanager{" --exit-zero" if noerror else ""}').exited
bigcode/self-oss-instruct-sc2-concepts
import shutil def create_make_command(keyboard, keymap, target=None): """Create a make compile command Args: keyboard The path of the keyboard, for example 'plank' keymap The name of the keymap, for example 'algernon' target Usually a bootloader....
bigcode/self-oss-instruct-sc2-concepts
import binascii def gotenna_to_intelhex(firmware_data): """ Convert raw bytes in goTenna firmware to the hex encoded INTELHEX """ firmware_bytes = bytearray(firmware_data) output_bytes = bytearray() while firmware_bytes: header_byte = firmware_bytes.pop(0) assert header_byte =...
bigcode/self-oss-instruct-sc2-concepts
def arg_list(items, prefix=''): """Process a list or string of arguments into a string containing them Used so users can pass arguments as a string or list in the configuration file. :param items: :param prefix: :return: """ if not items: return '' list_of_items = items.split(...
bigcode/self-oss-instruct-sc2-concepts
def is_number(s): """ Args: s: A string Returns: True iff the string represents a number """ try: float(s) return True except (ValueError, TypeError): return False
bigcode/self-oss-instruct-sc2-concepts
def remove_non_name_matches(entries, query_obj): """Filter out Person entries if there is no overlap between names_prefixes and query_obj.query_words.""" filtered_entries = [] for entry in entries: for word in query_obj.query_words: if word in entry.names_prefixes: fi...
bigcode/self-oss-instruct-sc2-concepts
def rotate_matrix(matrix): """ Rotate the n x n matrix 90 degrees clockwise. Given the original matrix. initial_matrix = [ [1, 2], [3, 4] ] The rotated matrix should look like this. rotated_matrix = [ [3, 1], [4, 2] ] ...
bigcode/self-oss-instruct-sc2-concepts
def commonprefix(m): """Return the longest prefix of all list elements.""" if not m: return '' prefix = m[0] for item in m: for i in range(len(prefix)): if prefix[:i+1] != item[:i+1]: prefix = prefix[:i] if i == 0: return '' break ...
bigcode/self-oss-instruct-sc2-concepts
def isnamemacro(function): """Return whether the macro function `function` has been declared as an identifier macro.""" return hasattr(function, "_isnamemacro")
bigcode/self-oss-instruct-sc2-concepts
def get_class_properties(class_name: str, vocab: dict) -> list: """ Return all the properties of the given class. """ properties = list() defines = vocab['@graph'] for obj in defines: if obj.get('propertyOf'): propertyof = obj['propertyOf'].split('#')[1] if proper...
bigcode/self-oss-instruct-sc2-concepts
def updated_with(orig_dict, *new_values): """Return a copy of orig_dict updated with new_values. New keys are added, and the values of existing keys will take the values in new_values. You can specify more than one update dictionary. They are applied in order, so the values of any keys in later di...
bigcode/self-oss-instruct-sc2-concepts
def add_three(one, two, three): """Adds three values together and returns it.""" return one + two + three
bigcode/self-oss-instruct-sc2-concepts
from typing import List def find_all_matchstrings_in_string(string: str, matchstrings: List[str]): """ check if string has all matchstrings in it """ return all([matchstring in string for matchstring in matchstrings])
bigcode/self-oss-instruct-sc2-concepts
import torch def has_tensor(obj) -> bool: """ Given a possibly complex data structure, check if it has any torch.Tensors in it. """ if isinstance(obj, torch.Tensor): return True elif isinstance(obj, dict): return any(has_tensor(value) for value in obj.values()) elif isinsta...
bigcode/self-oss-instruct-sc2-concepts
def first_not_none(itr): """ returns the first non-none result from an iterable, similar to any() but return value not true/false """ for x in itr: if x: return x return None
bigcode/self-oss-instruct-sc2-concepts
def max_with_none(first, second): """Returns the maximum of the two inputs, ignoring Nones.""" if first is None: return second elif second is None: return first else: return max(first, second)
bigcode/self-oss-instruct-sc2-concepts
def _quote_filter_value(s): """Put a string in double quotes, escaping double quote characters""" return '"%s"' % s.replace('"', r'\"')
bigcode/self-oss-instruct-sc2-concepts
import random def encode_string(value): """ Encode a string into it's equivalent html entity. The tag will randomly choose to represent the character as a hex digit or decimal digit. """ e_string = "" for a in value: e_type = random.randint(0, 1) if e_type: en...
bigcode/self-oss-instruct-sc2-concepts
def _default_kwargs_split_fn(kwargs): """Default `kwargs` `dict` getter.""" return (kwargs.get('distribution_kwargs', {}), kwargs.get('bijector_kwargs', {}))
bigcode/self-oss-instruct-sc2-concepts
def worker_process_control(_destination, _destination_process_id, _command, _reason, _message_id, _source, _source_process_id, _user_id): """ Creates a worker process control message. Tells a worker process to stop, kill, etcetera. """ return { "destination": _destinat...
bigcode/self-oss-instruct-sc2-concepts
def features(indel_class): """Manage feature names Args: indel_class (str): "s" for single-nucleotide indels (1-nt indels) "m" for multi-nucleotide indels (>1-nt indels) Returns: features (list): a list of feature names """ assert indel_class == "s" or in...
bigcode/self-oss-instruct-sc2-concepts
def get_var_names(variable): """ get the long variable names from 'flow' or 'temp' :param variable: [str] either 'flow' or 'temp' :return: [str] long variable names """ if variable == "flow": obs_var = "discharge_cms" seg_var = "seg_outflow" elif variable == "temp": o...
bigcode/self-oss-instruct-sc2-concepts
def replace_module_suffix(state_dict, suffix, replace_with=""): """ Replace suffixes in a state_dict Needed when loading DDP or classy vision models """ state_dict = { (key.replace(suffix, replace_with, 1) if key.startswith(suffix) else key): val for (key, val) in state_dict.items() ...
bigcode/self-oss-instruct-sc2-concepts
def check_response(response): """Check the status of responses from polyswarmd Args: response: Response dict parsed from JSON from polyswarmd Returns: (bool): True if successful else False """ status = response.get('status') return status and status == 'OK'
bigcode/self-oss-instruct-sc2-concepts
def stations_level_over_threshold(stations,tol): """This function returns a list of tuples, where each tuple holds a station at which the latest relative water level is over tol and the relative water level at the station""" stations_over_threshold = [] for station in stations: relative_level = stat...
bigcode/self-oss-instruct-sc2-concepts
def Collect(iterable, container=list): """ iterable >> Collect(container) Collects all elements of the iterable input in the given container. >>> range(5) >> Collect() [0, 1, 2, 3, 4] >>> [1, 2, 3, 2] >> Collect(set) # doctest: +SKIP {1, 2, 3} >>> [('one', 1), ('two', 2)] >> Collect...
bigcode/self-oss-instruct-sc2-concepts
def unread(thread, user): """ Check whether there are any unread messages for a particular thread for a user. """ return thread.user_threads.filter(user=user, is_read=False).exists()
bigcode/self-oss-instruct-sc2-concepts
def add(a, b): """ Return the addition of the arguments: a + b >>> add(1, 2) 3 >>> add(-1, 10) 9 >>> add('a', 'b') 'ab' >>> add(1, '2') Traceback (most recent call last): File "test.py", line 17, in <module> add(1, '2') File "test.py", line 14, in add ...
bigcode/self-oss-instruct-sc2-concepts
def _get_vector_identifier(line): """Return the identifier from the vector string. """ return line.split()[0]
bigcode/self-oss-instruct-sc2-concepts
def clip(data, start_idx): """Return data[start_idx:]""" return data[start_idx:]
bigcode/self-oss-instruct-sc2-concepts
def normalizeAudio(audio, width): """ Returns audio file that with range +/-1 :param audio: numpy array of audio samples :param width: sample width in bytes (1 = 8 bit, 2 = 16 bit...) :returns: noramlized audio file """ max_val = 2**(8*width-1) return audio/max_val
bigcode/self-oss-instruct-sc2-concepts
def compare_versions(version1, version2, split_char="."): """ Compares two version strings. Each string is to be split into segments by the given string. Each segment is only compared by numerical character value (e.g. a, b, rc are ignored) Ordinality is determined by the first non equal numeric seg...
bigcode/self-oss-instruct-sc2-concepts
def IsWithinTMRegion(pos, posTM):#{{{ """Check whether a residue position is within TM region """ isWithin = False for (b,e) in posTM: if pos >= b and pos < e: return True return False
bigcode/self-oss-instruct-sc2-concepts
def filter_private_methods(method): """Simple filter method. Ignores private functions""" return not method.startswith('_')
bigcode/self-oss-instruct-sc2-concepts
def trunc_time_minute(date): """ Truncate an object of type DateTime with time to 00:00:00 :param date: Date for truncate :return: Date truncated """ return date.replace(second=0, microsecond=0)
bigcode/self-oss-instruct-sc2-concepts
def fifo_path(dest, channel, epoch): """Construct full FIFO path. :param dest: Path to directory of FIFO :param channel: FIFO name :param epoch: Integer appended to FIFO name indicating the training epoch :return: full FIFO path """ return dest + '/' + channel + '_' + str(epoch)
bigcode/self-oss-instruct-sc2-concepts
def _area(bbox): """Computes area of a 2D bounding box. Args: bbox: A dict with keys 'x1', 'x2', 'y1', 'y2' encoding spatial co-ordinates. Returns: The area of the bounding box. """ return (bbox['x2'] - bbox['x1']) * (bbox['y2'] - bbox['y1'])
bigcode/self-oss-instruct-sc2-concepts
import requests def get_alert(service, resource): """ Get an entry from alerta :param service: alerta service :param resource: unique resource id of required entry :return: dict """ resp = requests.get(service.data['url'] + "/alerts", params={'environment': service....
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def gen_geojson(conn, model_num): """ Queries postgres and returns a geoJSON file with boundary data and properties that give us demographics and transit access data. Parameters ---------- model_num: int The number of the model in question Returns ...
bigcode/self-oss-instruct-sc2-concepts
def get_member_hp(checks, member_uuid, pool_uuid): """Helper function to find a members health in a given pool :param checks list: https://sldn.softlayer.com/reference/datatypes/SoftLayer_Network_LBaaS_Pool/#healthMonitor :param member_uuid: server UUID we are looking for :param pool_uuid: Connection p...
bigcode/self-oss-instruct-sc2-concepts
def clip_candidates(a, b, numCandidates): """ Clip retrieved candidates to numCandidates or, in case one method retrieived a smaller list than numCandidates, clip retrieved candidates to the same number as the smaller list. """ a = a[:numCandidates] b = b[:numCandidates] if len(b) <=...
bigcode/self-oss-instruct-sc2-concepts
def config_lower_get(tgt_dict, query, default=None): """ Case Insensitve dict get. :param tgt_dict: Dictionary :param query: String to look for key from :param default: Default value to return if not found. :return: Value in dict if found, otherwise default """ value = {k.lower(): v for ...
bigcode/self-oss-instruct-sc2-concepts
def flatten_nested(iterable): """ Recursively flatten nested structure of tuples, list and dicts. """ result = [] if isinstance(iterable, (tuple, list)): for item in iterable: result.extend(flatten_nested(item)) elif isinstance(iterable, dict): for key, value in sorted(iterab...
bigcode/self-oss-instruct-sc2-concepts
import base64 def _b64decode(s: str) -> bytes: """ Base 64 decodes a string to bytes. """ return base64.b64decode(s.encode("utf-8"))
bigcode/self-oss-instruct-sc2-concepts
def alias(aliases): """Decorator for slashcommand aliases that will add the same command but with different names. Parameters ---------- aliases: List[:class:`str`] | :class:`str` The alias(es) for the command with wich the command can be invoked with Usage: .. code-block:: ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Any def response_state_from_mediation_record(record: Dict[str, Any]): """Maps from acapy mediation role and state to AATH state""" state = record["state"] mediator_states = { "request": "request-received", "granted": "grant-sent", "denied...
bigcode/self-oss-instruct-sc2-concepts
def splitname(obj): """ Given an object that has a __module__ and __qualname__, return a list of name components from both. If __module__ is None, 'builtins' is used. """ modname = obj.__module__ or 'builtins' return modname.split('.') + obj.__qualname__.split('.')
bigcode/self-oss-instruct-sc2-concepts
def double_quote(text): """double-quotes a text""" return '"{}"'.format(text)
bigcode/self-oss-instruct-sc2-concepts
def get_n_regions(grid_enc): """ Get the number of regions encoded by compress_background_smartgrid(). Parameters ---------- grid_enc: dict Output from compress_background_smartgrid() Returns ------- int Number of regions encoded """ regions = 0 for row in g...
bigcode/self-oss-instruct-sc2-concepts
def remove_chars(line, chars=' \t', quotes='\'\"', comments=None): """ Removes all specified characters but leaves quotes intact. Removes comments if comment character is specified. """ new_line = '' quote_stack = '' remove_comments = (type(comments) is list) or (type(comments) is str) for ...
bigcode/self-oss-instruct-sc2-concepts
def notify_owner(func): """ A decorator for mutating methods of property container classes that notifies owners of the property container about mutating changes. Args: func (callable) : the container method to wrap in a notification Returns: wrapped method Examples: A ``_...
bigcode/self-oss-instruct-sc2-concepts
import socket import time def check_connection( ipv4_addr: str, port: int, timeout_secs: float = 3.0, retries: int = 1, retry_delay: float = 1.0, raise_error: bool = False) -> bool: """ Check if remote TCP connection is possible :param ipv4_addr: remote ipv4 add...
bigcode/self-oss-instruct-sc2-concepts
def close_time(km,brevet_distance): """ input: km brevet_distance is one of the standered distances 200,300,400,600,1000 km output: Closing time in minutes """ ## brevet_dict[brevet_distance]=[max_time,min_speed] brevet_max = { 200:810, 300:1200,400:1620,600:...
bigcode/self-oss-instruct-sc2-concepts
def mapped_columns(*column_maps): """ Given any number of column_maps return a list of unique column names """ result = set() for column_map in column_maps: result |= set(column_map.values()) return list(result)
bigcode/self-oss-instruct-sc2-concepts
def transform_map(kfun=lambda x: x, vfun=lambda x: x): """ Function that takes two functions as arguments and returns a function that applies those functions over all of the keys and values in a map and returns the transformed version of the map. kfun: function applied to all keys (default iden...
bigcode/self-oss-instruct-sc2-concepts
def _compute_offset(page: int, items_per_page: int) -> int: """Compute the offset value for pagination. Args: page (int): The current page to compute the offset from. items_per_page (int): Number of items per page. Returns: int: The offset value. """ return int(int(int(page)...
bigcode/self-oss-instruct-sc2-concepts
def _positions(field): """Given an index into the puzzle (i.e. a single field, calculate and return a 3-tuple (row, column, box) of the units the field belongs to. """ row = field // 9 column = field % 9 box = (field // 3) % 3 + 3 * ((field // 9) // 3) return row, column, box
bigcode/self-oss-instruct-sc2-concepts
def get_object_instances(predictions, target, confidence): """ Return the number of instances of a target class. """ targets_identified = [ pred for pred in predictions if pred['label'] == target and float(pred['confidence']) >= confidence] return len(targets_identified)
bigcode/self-oss-instruct-sc2-concepts
def get_gid_ignore_list(inputfile): """Input a file with a list of geneids to ignore when normalizing across taxa Each line should have 1 geneid on it. Use '#' at the start of the line for comments Output a list of geneids to ignore. """ # Don't convert GIDs to ints, # GIDs are not ints for ...
bigcode/self-oss-instruct-sc2-concepts
def listify(x): """ Coerce iterable object into a list or turn a scalar into single element list >>> listify(1.2) [1.2] >>> listify(range(3)) [0, 1, 2] """ try: return list(x) except: if x is None: return [] return [x]
bigcode/self-oss-instruct-sc2-concepts
from bs4 import BeautifulSoup import re def parse_course_detail(html): """ Use beautifulsoup to get detailed information of one course, then put them in a dictionary. """ soup = BeautifulSoup(html, 'lxml') table = soup.find_all('span', attrs = {'id': re.compile("^u2(45|54|63|72|81|90)_line\d.?...
bigcode/self-oss-instruct-sc2-concepts
def get_admission_rules(data, scope): """Get admission control rules.""" args = {} if scope == 'fed' or scope == 'local': args["scope"] = scope rules = data.client.show("admission/rules", "rules", None, **args) # show(self, path, obj, obj_id, **kwargs) return rules
bigcode/self-oss-instruct-sc2-concepts
def acquire(filename): """Return a grid of integers by parsing a file.""" grid = [] with open(filename) as f: for line in f: grid.append([int(x) for x in line.split()]) return grid
bigcode/self-oss-instruct-sc2-concepts
def determine_well_width_tolerance(mean_width): """ Determine the tolerance by which well widths are determined to be nearly equal. Fitted to a polynomial trend line for the following data of (mean, tolerance) pairs:: (100, 0.11), (60, 0.13), (50, 0.15), (25, 0.25), (5, 0.50), (1, 0.59) Args:...
bigcode/self-oss-instruct-sc2-concepts
def to_unsigned_byte(num): """ Convert given signed byte number to byte number. :param num: Signed number in range from -128 to 127. :return: Unsigned byte number in range from 0 to 255. """ assert -128 <= num <= 127, 'Value out of range (-128 - 127)!' ret = num if num >= 0 else (256 + num...
bigcode/self-oss-instruct-sc2-concepts
import string import random def generate_random_string( string_length=88, chars=string.ascii_lowercase + string.ascii_uppercase + string.digits, remove_confusing_digits=False): """ Generate a random string. :param string_length: :param chars: :param remove_confusing_digits:...
bigcode/self-oss-instruct-sc2-concepts
def get_engagement_rate_min(selectpicker_id: str) -> int: """ Min-Delegate-target of get_engagement_rates_min_max (dac-pattern) :param selectpicker_id: :return: int -> min-value of engagement-rate """ min_values = { "1": 0, "2": 1, "3": 2, "4": 3, "5": 4,...
bigcode/self-oss-instruct-sc2-concepts
def total_job_cost(labor, paint_cost): """ Function that will return the total cost of a job """ return labor + paint_cost
bigcode/self-oss-instruct-sc2-concepts
def encode(batch, tokenizer, max_len): """ This function takes in a batch and a tokenizer and outputs encoded batch """ return tokenizer.encode_plus( batch, None, add_special_tokens=True, max_length=max_len, pad_to_max_length=True )
bigcode/self-oss-instruct-sc2-concepts
def retrieve_fields(arg: str) -> str: """Strip and filter out the empty elements from the string. :type arg: ``str`` :param arg: The string from which we want to filter out the empty elements. :return: Filtered out result. :rtype: ``str`` """ return ",".join([x.strip() for x in arg.split...
bigcode/self-oss-instruct-sc2-concepts
def get_cz(mag): """ Returns the amount of magnetization along z. Parameters ---------- mag : ndarray Magnetization vector. Returns ------- magz_a, magz_b : float Amount of magnetization in state a and b along z. """ magz_a = mag[2, 0] magz_b = mag[5, 0] ...
bigcode/self-oss-instruct-sc2-concepts