seed
stringlengths
1
14k
source
stringclasses
2 values
def find_key(value, dictionary, default=None): """ Find the given value in the given dictionary and returns its key. If value is not found - return default value (None or given). If many elements can be found - return one of them arbitrarily (the first one found):: >>> find_key('d', {'a': 'b', ...
bigcode/self-oss-instruct-sc2-concepts
def caloria_function(is_male: bool, weight: float, height: float, age: float, sport_a_week: int) -> float: """ Calculates 24hour calory need. Returns -1 in any error case. :param is_male: True/False. Does human have MALE sex? :param weight: float, kilograms :param height: float, santimeters ...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def get_datetime(date, time, *, microseconds=True): """ Combine date and time from dicom to isoformat. Parameters ---------- date : str Date in YYYYMMDD format. time : str Time in either HHMMSS.ffffff format or HHMMSS format. microseconds: boo...
bigcode/self-oss-instruct-sc2-concepts
def remove_dup(df_tweet): """ Remove dupicated tweets (based on the 'tweet' text column) For duplicated tweets, it will keep the first tweeet Args: df_tweet (pandas df): dataframe containing covid tweet Returns: df_tweet (pandas df): dataframe with duplicated tweets removed """ ...
bigcode/self-oss-instruct-sc2-concepts
import ipaddress def ip_subtract(ip, val): """Subtract an integer to an IP address. Args: ip (str): An IP address in string format that is able to be converted by `ipaddress` library. val (int): An integer of which the IP address should be subtracted by. Returns: str: IP address ...
bigcode/self-oss-instruct-sc2-concepts
def within(min=None, max=None): """ Create a validation function to check whether an argument value is within a specified range (inclusive). `min` and `max` cannot both be None. :param min: A lower bound for the value. Optional. :param max: An upper bound for the value. Optional. :return: A...
bigcode/self-oss-instruct-sc2-concepts
import math def _adamic_adar(set_one: list, set_two: list, graph) -> float: """ Calculate Adamic Adar score for input lists :param set_one: A list of graph nodes -> part one :param set_two: A list of graph nodes -> part two :param graph: NetworkX bipartite graph :return: Adamic Adar score ...
bigcode/self-oss-instruct-sc2-concepts
def convert_hex_ascii_to_int(int_val): """ Use to convert from hex-ascii to int when encoding data particle values """ return int(int_val, 16)
bigcode/self-oss-instruct-sc2-concepts
def delta4(a, b, c, d): """Delta function (4 variables) """ if (a == b) & (b == c) & (c == d): return 1 else: return 0
bigcode/self-oss-instruct-sc2-concepts
def _TestTypesMatch(types_to_run, this_tests_types): """types_to_run should be a set of test types to run. this_test_types should be an iterable. Returns true if any type in the latter is also in the former, i.e., if the two are not disjoint.""" return not types_to_run.isdisjoint(this_tests_types)
bigcode/self-oss-instruct-sc2-concepts
import itertools def sorted_groupby(iterator, key, reverse=False): """ Similar to `itertools.groupby`, but sorts the iterator with the same key first. """ return itertools.groupby(sorted(iterator, key=key, reverse=reverse), key)
bigcode/self-oss-instruct-sc2-concepts
def has_decorator(source_lines: list) -> bool: """ Checks if the source code for a function has a decorator or not :param source_lines: Source code lines of a function :return: True if there is a decorator else False """ return '@' in source_lines[0]
bigcode/self-oss-instruct-sc2-concepts
def get_phenotype_curie(phenotype_uri): """Extract Phenotypes CURIE from the URI """ if '/MEDDRA/' in phenotype_uri: phenotype_id = phenotype_uri.split("/MEDDRA/", 1)[1] return 'MEDDRA:' + phenotype_id if '/HP:' in phenotype_uri: phenotype_id = phenotype_uri.split("/HP:", 1)[1] ...
bigcode/self-oss-instruct-sc2-concepts
def quick_stats(x, digits=3): """Quick wrapper to get mean and standard deviation of a tensor. Parameters ---------- x: torch.Tensor digits: int Number of digits to round mean and standard deviation to. Returns ------- tuple[float] """ return round(x.mean().item(), digi...
bigcode/self-oss-instruct-sc2-concepts
def get_output_sdf_path(gold_conf_path): """ This function extracts the output sdf path for docking results from a gold conf-file. Parameters ---------- gold_conf_path : str Full path to gold conf-file. Returns ------- sdf_path : str Full path to sdf-file. """ w...
bigcode/self-oss-instruct-sc2-concepts
def getRequestsFileName(request): """Get the filename from a Requests context""" content_disposition = request.headers.get("Content-Disposition") if content_disposition is not None: attributes = (x.strip() for x in content_disposition.split(";") if x.startswith("filename=")) ...
bigcode/self-oss-instruct-sc2-concepts
def config_contains_tar(pipeline_config: dict, tags=None) -> bool: """ Check if the input file list contains a `.tar` archive. """ if tags is None: tags = ["archive", "inside_archive"] params = pipeline_config.get("params", {}) ffiles = params.get("fetch_files", []) for ff in ffile...
bigcode/self-oss-instruct-sc2-concepts
def stats_variable_names(res): """Return the variable names for a stats object""" def varname(s): pos = s.find(':') return s if pos==-1 else s[0:pos] return set( [ varname(key) for key in res.keys()] )
bigcode/self-oss-instruct-sc2-concepts
import socket def _validate_as_ipv6(text: str) -> bool: """ A helper function for verifying that a string represents an IPv6 address. :param text: the string to verify. :return: `True` if the string looks like an IPv6 address or `False` if not. """ try: socket.inet_pton(socket.AF_INET...
bigcode/self-oss-instruct-sc2-concepts
def fahrenheit(T_in_celsius): """ returns the temperature in degrees Fahrenheit """ print ("FLAG --> my function call is here, accepting temp deg C and returning temp deg Fahrenheit ") return (T_in_celsius * 9 / 5) + 32
bigcode/self-oss-instruct-sc2-concepts
def pc_to_m(pc): """ Converts the input distance (or velocity) of the input from parsec to meters. """ return pc * 3.085677581 * 10**18
bigcode/self-oss-instruct-sc2-concepts
import torch def shiftdim(x, n=None): """Shift the dimensions of x by n. Parameters ---------- x : torch.Tensor Input tensor. n : int, default=None Shift. * When N is positive, `shiftdim` shifts the dimensions to the left and wraps the N l...
bigcode/self-oss-instruct-sc2-concepts
import json def get_json(raw): """ Returns the given text expressed as JSON, or None if any error occurred. """ try: return json.loads(raw) except: return None
bigcode/self-oss-instruct-sc2-concepts
def klass(obj) -> str: """ returns class name of the object. Might be useful when rendering widget class names Args: obj: any python class object Returns: str: name of the class >>> from tests.test_app.models import Author >>> klass(Author) 'ModelBase' """ retur...
bigcode/self-oss-instruct-sc2-concepts
def hasannotation(string_list): """ Judge whether the string type parameter string_list contains annotation """ for c in string_list: if c == "#": return True return False
bigcode/self-oss-instruct-sc2-concepts
def _add_extension_asset( client, customer_id, phone_number, phone_country, conversion_action_id ): """Creates a new asset for the call. Args: client: an initialized GoogleAdsClient instance. customer_id: a client customer ID. phone_number: a phone number for your business, e.g. '(1...
bigcode/self-oss-instruct-sc2-concepts
def find_value(key, headers): """ Search *headers* for *key* and return the common value shared across each element of *headers* and raise an exception if multiple values are encountered. """ values = set([x[key] for x in headers]) if len(values) == 0: raise KeyError('{} not found'.f...
bigcode/self-oss-instruct-sc2-concepts
def remove_even_integers(_array: list) -> list: """ Remove Even Integers from Array """ new_arrays = [number for number in _array if number % 2] return new_arrays
bigcode/self-oss-instruct-sc2-concepts
def exibeTokens(tokens): """ Apresenta sentença toquenizada no formato canônico, como string. """ tokens=[t.encode("utf-8") for t in tokens] return " ".join(tokens)
bigcode/self-oss-instruct-sc2-concepts
def get_rp_health_summary(isamAppliance, check_mode=False, force=False): """ Retrieving a summary of Reverse Proxy health """ return isamAppliance.invoke_get("Retrieving a summary of Reverse Proxy health", "/wga/widgets/health.json")
bigcode/self-oss-instruct-sc2-concepts
def input_validation(input): """ This function is used to test the stock ticker inputs and validate that they pass the two key characteristics tests: being less than 5 characters in length and having no digits. @param: input is a string argument that represents the given input the c...
bigcode/self-oss-instruct-sc2-concepts
def get_currency_for_stripe(currency): """Convert Saleor's currency format to Stripe's currency format. Stripe's currency is using lowercase while Saleor is using uppercase. """ return currency.lower()
bigcode/self-oss-instruct-sc2-concepts
def get_mask_file(img_file): """Takes an image file name and returns the corresponding mask file. The mask represents pixels that belong to the object. Default implentation assumes mask file has same path as image file with different extension only. Write custom code for getting mask file here ...
bigcode/self-oss-instruct-sc2-concepts
def exists_position(layout, row, column): """ Checks whether given row and column indices represent a valid position in the layout. Check whether row is inside the range od rows, check whether the column is at or below the right edge of the keypad and finally check the left edge is not a placeho...
bigcode/self-oss-instruct-sc2-concepts
import string import random def generate_random_string(length=8): """ Generate a random string """ char_set = string.ascii_uppercase + string.digits return ''.join(random.sample(char_set * (length - 1), length))
bigcode/self-oss-instruct-sc2-concepts
import configparser def simulation_configuration(path): """ Reads an ASCII file with relevant parameters for simulation. Parameters ---------- path : string Path to ASCII file. Returns ------- can_params : dict Parameters for cantilever properties. The dictionary contains: amp_invols = float (in m/V)...
bigcode/self-oss-instruct-sc2-concepts
import re def normalize_tainted_string(questionablestring): """ Trim, remove any non alphanumeric character and lower-case a questionable string :param questionablestring: tainted string :return: the normalized string """ return re.sub('\s+', ' ', re.sub('[\W_]+', ' ', questionablestring.lower...
bigcode/self-oss-instruct-sc2-concepts
def mobius_inverse(a,b,c,d): """ Inverse of a Mobius transformation. Parameters ---------- a : complex number b : complex number c : complex number d : complex number Returns ------- function from C -> C """ return lambda z: (d*z - b)/(-c*z + a)
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterable from typing import Tuple from typing import Pattern from typing import Optional def pattern_match(string: str, patterns: Iterable[Tuple[Pattern[str], str]]) -> Optional[str]: """ Returns the replacement string when a pattern matches the string query :param string: string to se...
bigcode/self-oss-instruct-sc2-concepts
def terminal_errors_except(*args): """ Returns a ``can_retry`` function for :py:func:retry` that only retries if errors the ``Exception`` types specified. :return: a function that accepts a :class:`Failure` and returns ``True`` only if the :class:`Failure` wraps an Exception passed in the args....
bigcode/self-oss-instruct-sc2-concepts
def _del_temp(beta, rhat_dot_dgam, dgam0): """Returns the small correction in surface temperature See Eqn (10) from Jackson+ (2012) ApJ. Args: beta (float): gravity-darkening exponent, probably 0.07 or 0.25 rhat_dot_dgam (numpy array): dot product between the unit location vect...
bigcode/self-oss-instruct-sc2-concepts
def capitalize(string): """ helper function to create capitalized copy of string. """ return string[:1].upper() + string[1:]
bigcode/self-oss-instruct-sc2-concepts
def align_up(offset, align): """Align ``offset`` up to ``align`` boundary. Args: offset (int): value to be aligned. align (int): alignment boundary. Returns: int: aligned offset. >>> align_up(3, 2) 4 >>> align_up(3, 1) 3 """ remain = offset % align if ...
bigcode/self-oss-instruct-sc2-concepts
def much_consistency(df): """ Helper function to handle known inconsistencies in raw data files :param df: A pandas dataframe, BLS OEWS data set :return df: A pandas dataframe """ # Force lower case column headers df.columns = map(str.lower, df.columns) print("...Forced column headers to ...
bigcode/self-oss-instruct-sc2-concepts
def sanitize_webscrape_name(name): """ Sanitizes webscrape powerplant names by removing unwanted strings (listed in blacklist), applying lower case, and deleting trailing whitespace. Parameters ---------- name: str webscrape plant name Returns ------- name: str sani...
bigcode/self-oss-instruct-sc2-concepts
import torch def apply_gaussian_noise(img, amplifier=0.1): """ Applies gaussian noise to given image. :param img: input image to add noise. :param amplifier: noise amplifier to control noise. :return: noisy image """ noise = torch.randn_like(img) return (amplifier * noise) + img
bigcode/self-oss-instruct-sc2-concepts
def _check_not_in(obj, string): """ The 'i' substring of the list 'obj' must not be in 'string :param obj: list of substring :param string: element that needs to be checked :return: False if a 'obj' substring is contained in 'string', True otherwise """ for i in obj: if i in string: ...
bigcode/self-oss-instruct-sc2-concepts
import math def calc_eyebrow_coordinates(anchor_point, length, angle, width): """ Calculates points of eyebrow :param anchor_point: a bottom right (bottom left) point :param length: eyebrow length x :param angle: brow angle :param width: eyebrow thickness :return: coordinates """ x...
bigcode/self-oss-instruct-sc2-concepts
def normalise_bytes(buffer_object): """Cast the input into array of bytes.""" return memoryview(buffer_object).cast("B")
bigcode/self-oss-instruct-sc2-concepts
def find_strongest_bot(bots): """Find bot with largest radius.""" return max(bots, key=lambda bot: bot.radius)
bigcode/self-oss-instruct-sc2-concepts
def get_formatted_city_country(city, country, population=''): """Generate a neatly formatted city and country.""" city_country = city.title() + ', ' + country.title() + ': ' + population return city_country
bigcode/self-oss-instruct-sc2-concepts
from itertools import compress def list_contains(list_of_strings, substring, return_true_false_array=False): """ Get strings in list which contains substring. """ key_tf = [keyi.find(substring) != -1 for keyi in list_of_strings] if return_true_false_array: return key_tf keys_to_remove = ...
bigcode/self-oss-instruct-sc2-concepts
import json def agg_all(run_dir, solved, map_fct, agg_fct): """ Calculate aggregates over all runs. Args: run_dir: directory containing benchmark results solved: whether to consider only successful tries map_fct: maps tries to values for aggregation agg_fct: function used ...
bigcode/self-oss-instruct-sc2-concepts
import json def _record_message(record): """Return the message part of the given SNS record.""" source = record["EventSource"] if source == "aws:sns": return json.loads(record["Sns"]["Message"]) raise ValueError(f"Unsuported 'EventSource' {source}. Supported types: 'aws:sns'")
bigcode/self-oss-instruct-sc2-concepts
def compress_secp256k1_public(point): """ Returns a 33-byte compressed key from an secp256k1 public key, which is a point in the form (x,y) where both x and y are 32-byte ints """ if point.y % 2: prefix = b'\x03' else: prefix = b'\x02' return prefix + point.x.to_bytes(32, byt...
bigcode/self-oss-instruct-sc2-concepts
def space_pad(number, length): """ Return a number as a string, padded with spaces to make it the given length :param number: the number to pad with spaces (can be int or float) :param length: the specified length :returns: the number padded with spaces as a string """ number_length = len(...
bigcode/self-oss-instruct-sc2-concepts
import re def ecm_kw_regex_select(ecm_names_list, list_of_match_str): """Identify matching, non-matching ECM names using a list of search terms This function searches a list of ECM names to find all of the ECM names that have the words specified by the user as search terms. This function is used to i...
bigcode/self-oss-instruct-sc2-concepts
def tupleify_state(state): """ Returns the state as a tuple """ temp = [] for row in state: temp.append(tuple(row)) return tuple(temp)
bigcode/self-oss-instruct-sc2-concepts
def lock_params(access_mode): """Returns parameters for Action Lock""" return {'_action': 'LOCK', 'accessMode': access_mode}
bigcode/self-oss-instruct-sc2-concepts
def minus(set1, set2): """Given the two sets, returns set1 - set2.""" return set1 - set2
bigcode/self-oss-instruct-sc2-concepts
def count_perturbations(perturbed_nodes_by_t): """ Count number of perturbations. :param perturbed_nodes_by_t: dict (by time step) of dicts (by node) of node states :return: number of perturbations """ return sum(len(current_perturbed_nodes) for current_perturbed_nodes in perturb...
bigcode/self-oss-instruct-sc2-concepts
def TimeToString(dt): """Convert a DateTime object to an ISO8601-encoded string.""" return dt.isoformat() + 'Z'
bigcode/self-oss-instruct-sc2-concepts
import torch def get_device(model): """ Extract the device to run on from the model. :param model: The model to train. :return: String. The name of the device. """ if next(model.parameters()).is_cuda: return 'cuda:{}'.format(torch.cuda.current_device()) else: return 'cpu'
bigcode/self-oss-instruct-sc2-concepts
def buyholdsell(n): """ Param n is a number. Function will decide if the number is worth buying, holding, or selling. """ if (n) in range(1, 30): return "I'm buying" elif (n) in range(30, 71): return "I'm holding" elif (n) in range(70, 101): return "I'm selling" ...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def opt_filter_string(filter_string: str, id_list: List[int]): """ Generate string for option-based filter. Generates a filter for filtering for specific rows based on the unique element ID that will be added to the main SQL query. Args: filter_string: Start of the fi...
bigcode/self-oss-instruct-sc2-concepts
def load_dico_as_dict(dico_path): """ Load a dico as a dict :param: dico_path: path of the dict :return: a dict """ id = 0 dico = dict() with open(dico_path, 'r') as fd: for word in fd: dico[id] = word.strip() id += 1 return dico
bigcode/self-oss-instruct-sc2-concepts
def build_os_environment_string(env): """ Creates a string of the form export key0=value0;export key1=value1;... for use in running commands with the specified environment :Parameter variables: a dictionay of environmental variables :Returns string: a string that can be prepended to a command to run the comman...
bigcode/self-oss-instruct-sc2-concepts
def remove_prefixes_of_others(values): """ Removes strings that are prefixes of other strings and returns the result. """ to_remove = set() for value in values: for other_value in values: if other_value != value and other_value.startswith(value): to_remove.add(va...
bigcode/self-oss-instruct-sc2-concepts
def diff_mic(pos1, pos2, cell): """Minimum image convention relative vector (orthorhombic cell only)""" diff = pos2 - pos1 for i in range(3): diff[i] -= round(diff[i]/cell[i])*cell[i] return diff
bigcode/self-oss-instruct-sc2-concepts
def int2name(i): """ Convert integer to Excel column name. """ div = i + 1 name = "" while div > 0: mod = (div - 1) % 26 name = chr(65 + mod) + name div = (div - mod) // 26 return name
bigcode/self-oss-instruct-sc2-concepts
def _state_diff(state, previous_state): """A dict to show the new, changed and removed attributes between two states Parameters ---------- state : dict previous_state : dict Returns ------- dict with keys 'new', 'changed' and 'removed' for each of those with content """ ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Optional def compose_custom_response( resp: Dict, success_message: str = "Operation successful.", fail_message: str = "Operation failed.", ) -> Dict: """Enhances a dictionarised Misty2pyResponse with `success_message` in case of success and with `fail_message...
bigcode/self-oss-instruct-sc2-concepts
import math def pixels_per_degree(display_diagonal_mm, height_pix, width_pix, viewing_distance_m): """ computer pixels per degree given display parameters and viewing distance This is a convenience function that can be used to provide angular resolution of input images for the HDR-VDP-2. Note th...
bigcode/self-oss-instruct-sc2-concepts
def extract_request_body(requests_text: str): """ Parse change requests, a text of RPSL objects along with metadata like passwords or deletion requests. Returns a dict suitable as a JSON HTTP POST payload. """ passwords = [] overrides = [] rpsl_texts = [] delete_reason = "" requ...
bigcode/self-oss-instruct-sc2-concepts
def from_ms(time: int) -> str: """ Convert millisconds into a string in format mm:ss.ms """ minute = time // 60_000 second = time // 1000 - minute * 60 millisecond = time - minute * 60_000 - second * 1000 if second < 10: second = "0" + str(second) else: second = str(se...
bigcode/self-oss-instruct-sc2-concepts
def output_file(out): """Convert file path to writeable file object.""" try: return open(out, 'w') except IOError as exc: print('Error opening output file at path: {}.\n\n{}'.format(out, exc)) exit(1)
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional from typing import List def get_class_selector(config_name: str) -> Optional[List[str]]: """Determines the class selector, based on the config name. This enables support for configs, which train a model only on a subset of classes. :param config_name: Name of the config used f...
bigcode/self-oss-instruct-sc2-concepts
def import_m(module): """Will simply import a module into a var Usage : pygame = import_m("pygame")""" return __import__(module)
bigcode/self-oss-instruct-sc2-concepts
def checksum16(payload): """ Calculates checksum of packet. :param payload: Bytearray, data to which the checksum is going to be applied. :return: Int, checksum result given as a number. """ chk_32b = 0 # accumulates short integers to calculate checksum j = 1 # iterates through p...
bigcode/self-oss-instruct-sc2-concepts
def cir_RsC_fit(params, w): """ Fit Function: -Rs-C- """ Rs = params["Rs"] C = params["C"] return Rs + 1 / (C * (w * 1j))
bigcode/self-oss-instruct-sc2-concepts
def read_from_8bit_eeprom(bus, address, count, bs=16): """ Reads from an 8-bit EEPROM. Only supports starting from 0x00, for now. (to add other start addresses, you'll want to improve the address counting mechanism) Default read block size is 16 bytes per read. """ data = [] # We'll add our read...
bigcode/self-oss-instruct-sc2-concepts
import pathlib import lzma import tempfile def extract_lzma(path): """Extract an lzma file and return the temporary file name""" tlfile = pathlib.Path(path) # open lzma file with tlfile.open("rb") as td: data = lzma.decompress(td.read()) # write temporary tar file fd, tmpname = tempfil...
bigcode/self-oss-instruct-sc2-concepts
def is_iterable(x): """Checks if an object x is iterable. It checks only for the presence of __iter__, which must exist for container objects. Note: we do not consider non-containers such as string and unicode as `iterable'; this behavior is intended. """ return hasattr(x, "__iter__")
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Any def slider_handle_label(is_numerical: bool, is_ten_pow: bool = False) -> Dict[str, Any]: """Get the slider handle label dict.""" if is_numerical: label = "BINS" if is_ten_pow: label = "SMART BINS" else: label = "CATEGORIES"...
bigcode/self-oss-instruct-sc2-concepts
def get_integer(prompt): """ Get an integer from Standard Input (stdin). The function will continue looping, and prompting the user, until a valid `int` is entered. :param prompt: The String that the user will see, when they're prompted to enter the value :return: The integer that the...
bigcode/self-oss-instruct-sc2-concepts
def is_tuple(obj): """Helper method to see if the object is a Python tuple. >>> is_tuple((1,)) True """ return type(obj) is tuple
bigcode/self-oss-instruct-sc2-concepts
def escape_register(register): """Escape register names suitable rust module and variable names.""" return register.replace("[", "").replace("]", "")
bigcode/self-oss-instruct-sc2-concepts
import math def pts2bins(pts, prec=0.25): """ :param pts: List of 2d points :param prec: Width of each bin :return: A dictionary of bin centers and points in the bin """ # for pt in pts: # def val2bin_int(val): # return math.ceil(val / prec) if val > 0 else math.floor(pt[1]...
bigcode/self-oss-instruct-sc2-concepts
def serial_listen_ports(migrate_data): """Returns ports serial from a LibvirtLiveMigrateData""" ports = [] if migrate_data.obj_attr_is_set('serial_listen_ports'): ports = migrate_data.serial_listen_ports return ports
bigcode/self-oss-instruct-sc2-concepts
from typing import List def splitStrToList( string: str, separator: str = ',', ignores: str = '\\' ) -> List[str]: """Split the given string into a list, using a separator @type string: str @param string: The string to be splited @type separator: str @param separator: A separator to s...
bigcode/self-oss-instruct-sc2-concepts
import base64 import struct def _decode_linear_biases(linear_string, nodelist): """Inverse of _serialize_linear_biases. Args: linear_string (str): base 64 encoded string of little endian 8 byte floats, one for each of the nodes in nodelist. nodelist (list): list of the form [node1...
bigcode/self-oss-instruct-sc2-concepts
def validate_list_of_numbers_from_csv(data): """ Converts a comma separated string of numeric values to a list of sorted unique integers. The values that do not match are skipped. :param (str, iterable) data: - str | iterable :return: - list(int) """ if isinstance(data, str): ...
bigcode/self-oss-instruct-sc2-concepts
def sizeof_fmt(num, suffix='B'): """Returns human-readable file size Supports: * all currently known binary prefixes * negative and positive numbers * numbers larger than 1000 Yobibytes * arbitrary units (maybe you like to count in Gibibits!) Example: -------- >>> sizeof_fmt(16...
bigcode/self-oss-instruct-sc2-concepts
def compute_reduced_cost(column, duals): """Compute and return the reduced cost of 'column'.""" return (column.objective_coefficient - sum(duals[index] * coef for index, coef in zip(column.row_indices, column.row_coefficients)))
bigcode/self-oss-instruct-sc2-concepts
def extract_array(line): """ Return the array on the RHS of the line >>> extract_array("toto = ['one', 'two']\n") ['one', 'two'] >>> extract_array('toto = ["one", 0.2]\n') ['one', 0.2] """ # Recover RHS of the equal sign, and remove surrounding spaces rhs = line.split('=')[-1].stri...
bigcode/self-oss-instruct-sc2-concepts
def get_bs_dims(bands_array): """ Get the dimensions from the bands array of a BandsData node. :param numpy.array bands_array: an array with bands as stored in an array.bands data node :return: a tuple containing num_bands, num_kp, num_spins. if the array is only 2d, num_spins = 0 :...
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional def comment(c: str, inner: str, units: Optional[str] = None): """Add 'Begin c' and 'End c' comments around an inner block. Optionally add another 'units' comment before the inner block. """ units_str = "" if units is None else f"# {units}\n" return units_str + f"# Beg...
bigcode/self-oss-instruct-sc2-concepts
def parse_position(string): """ >>> parse_position('3,000,000') 3000000 >>> parse_position('3M') 3000000 >>> parse_position('3kk') 3000000 """ units = '' for index, char in enumerate(string): if char.lower() in ['k', 'm']: units = string[index:] st...
bigcode/self-oss-instruct-sc2-concepts
import re def validate_replication_tags(replication_tags): """ Returns validated replication tags or raises an error. - 'replication_tags' should be a list of 'tag's. - a 'tag' should be dictionary with Keys 'Key' and 'Value' - the 'Key' Values should be a string with length between 0 and 127 ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Any def abi_input_signature(input_abi: Dict[str, Any]) -> str: """ Stringifies a function ABI input object according to the ABI specification: https://docs.soliditylang.org/en/v0.5.3/abi-spec.html """ input_type = input_abi["type"] if input_type.start...
bigcode/self-oss-instruct-sc2-concepts