seed
stringlengths
1
14k
source
stringclasses
2 values
import random import socket def find_unbound_port(start=None, increment=False, port_range=(10000, 50000), verbose=False, logger=None): """ Find a unbound port. Parameters ---------- start : int The por...
bigcode/self-oss-instruct-sc2-concepts
import csv def read_csv_file(file_path, delimiter, remove_header=False): """ Reads a csv file with records separated by delimiter""" rows = [] with open(file_path) as csv_file: csv_reader = csv.reader(csv_file, delimiter=delimiter) for row in csv_reader: rows.append(row) if...
bigcode/self-oss-instruct-sc2-concepts
def _mask_for_bits(i): """Helper function for read_bitpacked to generage a mask to grab i bits.""" return (1 << i) - 1
bigcode/self-oss-instruct-sc2-concepts
def to_float(val, sub_val): """Try to convert 'val' to a float. If it fails, return 'sub_val' instead. Remove any commas before trying to convert. """ try: if isinstance(val, str): # remove any commas before converting. val = val.replace(',', '') return float(val...
bigcode/self-oss-instruct-sc2-concepts
def get_make_targets(benchmarks, fuzzer): """Return pull and build targets for |fuzzer| and each benchmark in |benchmarks| to pass to make.""" return [('pull-%s-%s' % (fuzzer, benchmark), 'build-%s-%s' % (fuzzer, benchmark)) for benchmark in benchmarks]
bigcode/self-oss-instruct-sc2-concepts
def get_optimal(opt_file, optimisation): """Returns the optimal value given the specified optimisation. Args: opt_file: The file with optimal results. optimisation: The optimisation value to return. Returns: Optimal value. """ f = open(opt_file, "r") profile = '' for lin...
bigcode/self-oss-instruct-sc2-concepts
import json def to_json(obj: object, *args, **kwargs): """Serialize a nested object to json. Tries to call `to_json` attribute on object first.""" def serialize(obj: object): return getattr(obj, 'to_json', getattr(obj, '__dict__') if hasattr(obj, '__dict__') else str(obj)) return json.dumps(obj, ...
bigcode/self-oss-instruct-sc2-concepts
def get_context(seq, pos, n=1, s=1): """ Gets context from a sequence at a given position. :param seq: the sequence :param pos: target position :param n: context size (each side) :param s: size of the target region, displaces the position of right context :return: a string matching [ACTG]*[....
bigcode/self-oss-instruct-sc2-concepts
def get_host_batchid_map(workspec_list): """ Get a dictionary of submissionHost: list of batchIDs from workspec_list return {submissionHost_1: {batchID_1_1, ...}, submissionHost_2: {...}, ...} """ host_batchid_map = {} for workspec in workspec_list: host = workspec.submissionHost ...
bigcode/self-oss-instruct-sc2-concepts
def decExponential(agent,state): """ Implements a decreasing-epsilon method which starts with a high exploration rate and then decreases exponentially with time """ return (0.5 ** (agent.episodesSoFar + state.trial))
bigcode/self-oss-instruct-sc2-concepts
def consistent_typical_range_stations(stations): """ returns the stations that have consistent typical range data Inputs ------ stations: list of MonitoringStation objects Returns ------ a list of stations that have consistent typical range data """ consistent_station_list = [...
bigcode/self-oss-instruct-sc2-concepts
import math def get_direction(x, y): """Gets a direction from two differences in coordinates""" return math.atan2(y, x)
bigcode/self-oss-instruct-sc2-concepts
def weighted_sum(df, var, wt="s006"): """ Return the weighted sum of specified variable Parameters ---------- df: Pandas DataFrame data overwhich to compute weighted sum var: str variable name from df for which to computer weighted sum wt: str name of weight variable...
bigcode/self-oss-instruct-sc2-concepts
def _axes_all_finite_sized(fig): """Return whether all axes in the figure have a finite width and height.""" for ax in fig.axes: if ax._layoutbox is not None: newpos = ax._poslayoutbox.get_rect() if newpos[2] <= 0 or newpos[3] <= 0: return False return True
bigcode/self-oss-instruct-sc2-concepts
from typing import Counter def compute_state_distribution(interactions): """ Returns the count of each state for a set of interactions. Parameters ---------- interactions : list of tuples A list containing the interactions of the match as shown at the top of this file. Return...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def calculahash(cadena): """Devuelve el hash SHA256 de una cadena dada como entrada :param cadena: texto de entrada para calcular su hash :return: el hash calculado con SHA256 """ return hashlib.sha256(cadena.encode()).hexdigest()
bigcode/self-oss-instruct-sc2-concepts
def modify_df(df, sentence_length): """ Convert the columns STB_Text from a string of list to a list. Gather length of STB_Text/Ref_Text list and filter based on sentence length argument. Explode STB_Text and Ref_Text as separate dataframes. Filter repetitive sentences within a topic. Create a c...
bigcode/self-oss-instruct-sc2-concepts
import requests from bs4 import BeautifulSoup def get_definition(search): """ Get the first definition of the word using merriam-webster dictionary online. :param search: Word to find the definition of. :return: Definition of search. """ # Read HTML website req = requests.get("https://merr...
bigcode/self-oss-instruct-sc2-concepts
def absolutelyNonDecreasing(buffer,item,attempts): """ Stops after the buffer has seen an absolute value larger than the one being searched for. The example halting condition given in the documentation. """ if abs(buffer._cache[-1])>abs(item): return True return False
bigcode/self-oss-instruct-sc2-concepts
import re def parse_quicklook_key(key): """ Parse quicklook key and return dictionary with relevant fields. Input: key(string): quicklook key Output: dict with the following keys: satellite(string): e.g. CBERS4 camera(string): e.g. MUX path(string): 0 padded path, 3 dig...
bigcode/self-oss-instruct-sc2-concepts
def qobj_to_dict_current_version(qobj): """ Return a dictionary representation of the QobjItem, recursively converting its public attributes. Args: qobj (Qobj): input Qobj. Returns: dict: dictionary representing the qobj. """ return qobj.as_dict()
bigcode/self-oss-instruct-sc2-concepts
def get_batch_appliance_tunnels_config( self, ne_pk: str, tunnel_id_list: list, ) -> bool: """Get appliance tunnel configuration for specified tunnels .. note:: This API Call is not in current Swagger as of Orch 9.0.3 .. list-table:: :header-rows: 1 * - Swagger Section ...
bigcode/self-oss-instruct-sc2-concepts
def escape_jsonpointer_part(part: str) -> str: """convert path-part according to the json-pointer standard""" return str(part).replace("~", "~0").replace("/", "~1")
bigcode/self-oss-instruct-sc2-concepts
def soil_heat_conductivity(w, T, ro, soil_type): """ Heat conductivity of a soil, W/(m2*K) :param w: humidity, % :param T: temperature, K :param ro: density of a soil, kg/m3 :param soil_type: (str) type of a soil :return: heat conductivity of a soil, W/(m2*K) """ ro = ro / 1000 r...
bigcode/self-oss-instruct-sc2-concepts
import math def split_equally(lst, nparts): """Splits equally list into nparts. If length of the list cannot be devided without residue the functions splits list in the way when some parts have n items and some n-1, so lengths of them are almost equal. """ data_size = len(lst) ratio...
bigcode/self-oss-instruct-sc2-concepts
import re def version_parts(version): """ Split a version string into numeric X.Y.Z part and the rest (milestone). """ m = re.match(r'(\d+(?:\.\d+)*)([.%]|$)(.*)', version) if m: numver = m.group(1) rest = m.group(2) + m.group(3) return numver, rest else: return...
bigcode/self-oss-instruct-sc2-concepts
def is_cmp(op): """ Tests whether an operation requires comparing two types. """ return op in ['<', '<=', '==', '!=', '>', '>=']
bigcode/self-oss-instruct-sc2-concepts
def datetime_to_text(datetime_object): """ covert python3 datetime object to text string to store in sqlite3 database :param datetime_object: python3 datetime object :return: string containing datetime in format MM-DD-YYYY HH:MM:SS """ return str(datetime_object)
bigcode/self-oss-instruct-sc2-concepts
def subst_variables_in_str(line: str, values: dict, start_char: str = "%") -> object: """ Replace variables inside the specified string :param line: String to replace the variables in. :param values: Dictionary, holding variables and their values. :param start_char: Character used to i...
bigcode/self-oss-instruct-sc2-concepts
def alt2ambiguousnucleotide(alts): """Translate list of alt nucleotides to single IUPAC abmiguity symbol Uses http://www.dnabaser.com/articles/IUPAC%20ambiguity%20codes.html Args: alts: List of alternate nucleotides of a SNP Raises: KeyError: when multi alt is not in translation map ...
bigcode/self-oss-instruct-sc2-concepts
def lt_log_determinant(L): """ Log-determinant of a triangular matrix Args: L (Variable): Lower-triangular matrix to take log-determinant of. """ return L.diag().log().sum()
bigcode/self-oss-instruct-sc2-concepts
def get_update_author_profile(d_included, base_url): """Parse a dict and returns, if present, the URL corresponding the profile :param d_included: a dict, as returned by res.json().get("included", {}) :type d_raw: dict :param base_url: site URL :type d_raw: str :return: URL with either company...
bigcode/self-oss-instruct-sc2-concepts
def isLucky(n): """ isLucky takes in an integer and return True if the sum of its right half == sum of the right half :param n: :return: """ # l = list(map(int, str(n))) # return sum(l[0:len(l) // 2]) == sum(l[len(l) // 2:]) s = str(n) return sum(map(int, s[: len(s) // 2])) == ...
bigcode/self-oss-instruct-sc2-concepts
def get_area(pos): """ Args pos: [B, N, 4] (x1, x2, y1, y2) Return area : [B, N] """ # [B, N] height = pos[:, :, 3] - pos[:, :, 2] width = pos[:, :, 1] - pos[:, :, 0] area = height * width return area
bigcode/self-oss-instruct-sc2-concepts
import re def cache_key(query): """Make filesystem-friendly cache key""" key = query key = key.lower() key = re.sub(r"[^a-z0-9-_;.]", "-", key) key = re.sub(r"-+", "-", key) return key
bigcode/self-oss-instruct-sc2-concepts
async def _get_post_id(db, author, permlink): """Get post_id from hive db.""" sql = "SELECT id FROM hive_posts WHERE author = :a AND permlink = :p" return await db.query_one(sql, a=author, p=permlink)
bigcode/self-oss-instruct-sc2-concepts
def sum(a: int, b: int) -> int: """ Let's sum two integers! >>> sum(1,2) 3 :param a: An integer :param b: Another integer :return: the sum of both parameters """ return a + b
bigcode/self-oss-instruct-sc2-concepts
def find_header(path: str) -> int: """find_header this function counts the lines of the header (i.e. how many lines there are until the first line with doesn't start with a '#' is encountered) Parameters ---------- path : str file path Returns ------- int number of ...
bigcode/self-oss-instruct-sc2-concepts
def split_addresses(email_string_list): """ Converts a string containing comma separated email addresses into a list of email addresses. """ return filter(None, [s.strip() for s in email_string_list.split(",")])
bigcode/self-oss-instruct-sc2-concepts
def order(replay1, replay2): """ An ordered tuple of the given replays. The first element is the earlier replay, and the second element is the later replay. Parameters ---------- replay1: Replay The first replay to order. replay2: Replay The second replay to order. Retu...
bigcode/self-oss-instruct-sc2-concepts
def teardown(teardown_method): """Decorator for declaring teardown methods for test cases.""" teardown_method._is_teardown_method = True return teardown_method
bigcode/self-oss-instruct-sc2-concepts
import re def removeMultEspaços(string: str) -> str: """ Remove espaços ectras entre as palavras Parameters ---------- string : str string com multiplos espaços Returns ------- string : str string com apenas um espaço entre palavras """ string_arru...
bigcode/self-oss-instruct-sc2-concepts
def parse_log(logfile, body, param): """" Parse log file for one of a body's initial conditions and return it. This is useful for when a parameter is not outputted but one needs it later on for bigplanet analysis. Parameters ---------- logfile : str path to the logfile body : s...
bigcode/self-oss-instruct-sc2-concepts
def generate_spec(key_condictions): """get mongo query filter by recursion key_condictions is a list of (key, value, direction) >>> generate_spec([ ... ('a', '10', 1), ... ('b', '20', 0), ... ]) {'$or': [{'$and': [{'a': '10'}, {'b': {'$lt': '20'}}]}, {'a': {'$gt': '10'}}]} """ ...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def convert_time_searchable(ts): """converts timestamps from time.time() into reasonably searchable string format""" return datetime.fromtimestamp(ts).strftime("%Y%m%d%H%M%S")
bigcode/self-oss-instruct-sc2-concepts
def bioconductor_tarball_url(package, pkg_version, bioc_version): """ Constructs a url for a package tarball Parameters ---------- package : str Case-sensitive Bioconductor package name pkg_version : str Bioconductor package version bioc_version : str Bioconductor ...
bigcode/self-oss-instruct-sc2-concepts
def evaluate_using_acc(model, X_test, y_test, batch_size): """ Evaluation function using accuracy. # Arguments: model: Model to be evaluated. X_test: Inputs of the testing set. y_test: Outputs of the testing set. batch_size: Batch size. # Returns: Accuracy of the gi...
bigcode/self-oss-instruct-sc2-concepts
def _calculate_mid_points(bounds): """ Calculate middle points based on the geometry bounds Parameters ---------- bounds : array_like array containing xmin, ymin, xmax, ymax Returns --------- x_mids : mid points of x values y_mids : mid points of y values """ # Cal...
bigcode/self-oss-instruct-sc2-concepts
def get_mapping_data(name, field, integral, region=None, integration='volume'): """ General helper function for accessing reference mapping data. Get data attribute `name` from reference mapping corresponding to `field` in `region` in quadrature points of the given `integral` and `integration` type...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime import calendar def formatted_timestamp_utc_time(timestamp_str, format_str): """ Converts a formatted timestamp timestamp string to UTC time NOTE: will not handle seconds >59 correctly due to limitation in datetime module. :param timestamp_str: a formatted timestamp s...
bigcode/self-oss-instruct-sc2-concepts
import itertools def _get_permutations_draw(draw): """Helper to get all permutations of a draw (list of letters), hint: use itertools.permutations (order of letters matters)""" return list(it for i in range(1, 8) for it in itertools.permutations(draw, i))
bigcode/self-oss-instruct-sc2-concepts
def generate_early_stop_file_path(experiment_path_prefix, net_number): """ Given an 'experiment_path_prefix', return an early-stop-file path with 'net_number'. """ return f"{experiment_path_prefix}-early-stop{net_number}.pth"
bigcode/self-oss-instruct-sc2-concepts
def ver_str_to_tuple(ver_str): """Convert a version string into a version tuple.""" out = [] for x in ver_str.split("."): try: x = int(x) except ValueError: pass out.append(x) return tuple(out)
bigcode/self-oss-instruct-sc2-concepts
def distance(color_one: tuple, color_two: tuple) -> float: """Finds the distance between two rgb colors. Colors must be given as a 3D tuple representing a point in the cartesian rgb color space. Consequently the distance is calculated by a simple cartesian distance formula. Returns a float representing...
bigcode/self-oss-instruct-sc2-concepts
def get_artist_ids(db_session): """Returns a list of all artist ID's.""" c = db_session.cursor() c.execute("""SELECT artist_id FROM artists""") l = [] for row in c: l.append(row[0]) #db_session.commit() c.close() return l
bigcode/self-oss-instruct-sc2-concepts
def nearest(items, pivot): """ :param items: list of type datetime :param pivot: the one pivot we are referring to :return: return the nearest item in items to the pivot """ return min(items, key=lambda x: abs(x - pivot))
bigcode/self-oss-instruct-sc2-concepts
def p2f(x): """Convert percent string to float. """ return float(x.strip('%')) / 100.
bigcode/self-oss-instruct-sc2-concepts
def isKColRequired(config, num): """A quick helper function that checks whether we need to bother reading the k column. The logic here is the same as for `isGColRequired`, but we check for output files that require the k column rather than g1,g2. Parameters: config (dict): The configuration f...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def generate_equally_spaced_scopes(num_envs: int, num_agents: int) -> List[int]: """Generate a list of equally spaced scopes for the agents :param num_envs: Number of environments :type num_envs: int :param num_agents: Number of agents :type num_agents: int :raises Va...
bigcode/self-oss-instruct-sc2-concepts
def GetFieldNumber(field_tuple): """Get the field number from the tuple returned by `Message.ListFields`.""" return field_tuple[0].number
bigcode/self-oss-instruct-sc2-concepts
import torch def reshape(tensor, shape): """ Reshapes a tensor. Parameters ---------- tensor : tensor A Tensor. shape : tensor Defines the shape of the output tensor. Returns ------- A Tensor. Has the same type as tensor """ return torch.reshape(tenso...
bigcode/self-oss-instruct-sc2-concepts
def get_package_url(data): """Get the url from the extension data""" # homepage, repository are optional if "homepage" in data: url = data["homepage"] elif "repository" in data and isinstance(data["repository"], dict): url = data["repository"].get("url", "") else: url = "" ...
bigcode/self-oss-instruct-sc2-concepts
import re def stream_name_match(stream_reg: str, stream_name: str) -> bool: """Decide whether a stream regex matches a stream_name (fullmatch). Currently, Zulip considers stream names to be case insensitive. """ return re.fullmatch(stream_reg, stream_name, flags = re.I) is not None
bigcode/self-oss-instruct-sc2-concepts
def image_destroy(client, image_id): """Destroy the image or raise if it does not exist.""" return client.image_destroy(image_id=image_id)
bigcode/self-oss-instruct-sc2-concepts
def bids_for_doc(doc_top_list, td, reviewers): """ Generate bids for the document for all provided reviewers """ bids = [] for rev in reviewers: rev_top_dict = dict(td.rev_top[rev.name()]) score = 0 for t_id, t_prob in doc_top_list: score += rev_top_dict.get(t_id,...
bigcode/self-oss-instruct-sc2-concepts
def diff(b: list, d: list) -> list: """ Sorting 2 list numbers without same numbers >>> diff([1, 2, 3, 6, 4, 7], [1, 2, 36, 96, 78, 99]) [3, 4, 6, 7, 36, 78, 96, 99] """ # Making set of list x = set(b) y = set(d) # Find numbers which are not same in lists p = y.difference(x) ...
bigcode/self-oss-instruct-sc2-concepts
def _is_extended_slice(s): """Return whether a slice is an extended slice.""" return s.step is not None and s.step != 1
bigcode/self-oss-instruct-sc2-concepts
def padded_batch(dset, batch_size, sequence_length, label_shape=()): """Pads examples to a fixed length, and collects them into batches.""" # We assume the dataset contains inputs, labels, and an index. padded_shapes = { 'inputs': (sequence_length,), 'labels': label_shape, 'index': (), } #...
bigcode/self-oss-instruct-sc2-concepts
def security_header_tween_factory(handler, registry): """Add security-related headers to every response.""" def security_header_tween(request): resp = handler(request) # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy # # Browsers should respect the last...
bigcode/self-oss-instruct-sc2-concepts
def pattern_molecular_weight(mzs: list, intensities: list, charge: int = 1): """ Calculates the molecular weight given by an isotope pattern. :param mzs: m/z (x) values for pattern :param intensities: intensity (y) values for the pattern :param charge: charge for the molecule :return: molecular...
bigcode/self-oss-instruct-sc2-concepts
import operator def filtered_join (sep, strings, pred = None) : """Return a string which is the concatenation of the items in the iterable `strings` for which `pred` is true, separated by `sep`. >>> filtered_join ("-", ["", "abc", "ced"]) 'abc-ced' >>> filtered_join ("-", [" ", "abc",...
bigcode/self-oss-instruct-sc2-concepts
def from_bits(bin_str: str): """ This function will convert a binary string (with or without prefix) into a integer; :param bin_str: A binary string to convert into integer :return: A integer representing the given binary string """ return int(bin_str, 2)
bigcode/self-oss-instruct-sc2-concepts
def swap_order(value): """ Common crawl optimizes search by working back to front ("org.example.www") This is a utility function for swapping the order back to the expected value ("www.example.org") """ parts = value.split(".") new_value = "" for part in parts: new_value = part + "....
bigcode/self-oss-instruct-sc2-concepts
def dtype_to_json_type(dtype) -> str: """Convert Pandas Dataframe types to Airbyte Types. :param dtype: Pandas Dataframe type :return: Corresponding Airbyte Type """ if dtype == object: return "string" elif dtype in ("int64", "float64"): return "number" elif dtype == "bool": ...
bigcode/self-oss-instruct-sc2-concepts
def get_string_trace_attribute_rep(trace, trace_attribute): """ Get a representation of the feature name associated to a string trace attribute value Parameters ------------ trace Trace of the log trace_attribute Attribute of the trace to consider Returns ------------ ...
bigcode/self-oss-instruct-sc2-concepts
def _get_qualifiers(graph, source_node: int, target_node: int): """ Retrieve the qualifiers list (empty list if nonexistent) """ if "qualifiers" in graph.es[0].attributes(): qualifiers_list = graph.es.select(_source=source_node, _target=target_node)["qualifiers"] qualifiers_list = [x if x is not...
bigcode/self-oss-instruct-sc2-concepts
def question_is_nonarray(questions, question_id): """ Return whether the question exists and has no subquestions. """ if question_id not in questions: return False question = questions[question_id] if question[1] is not None or question[2] is not None: return False return Tru...
bigcode/self-oss-instruct-sc2-concepts
import random def extract_text(para): """Returns a sufficiently-large random text from a tokenized paragraph, if such text exists. Otherwise, returns None.""" for _ in range(10): text = random.choice(para) if text and 60 < len(text) < 210: return text return None
bigcode/self-oss-instruct-sc2-concepts
def get_missing_frameworks(descriptor, environment, yml_file): """ Returns a list of missing frameworks from a given environment based on the list of dependencies returned by a bundle descriptor. :param descriptor: The bundle for which missing dependencies will be searched. :param environment: The ...
bigcode/self-oss-instruct-sc2-concepts
def inject_none_for_missing_fields(cls, values): """Given a BaseModel class and a dictionary to populate its fields, inject None for missing fields.""" for field_name, field_info in cls.__fields__.items(): if field_name not in values and field_info.alias not in values: values[field_name] = N...
bigcode/self-oss-instruct-sc2-concepts
def find_constant_features(data): """ Get a list of the constant features in a dataframe. """ const_features = [] for column in list(data.columns): if data[column].unique().size < 2: const_features.append(column) return const_features
bigcode/self-oss-instruct-sc2-concepts
def remove_unspecified_items(attrs): """Remove the items that don't have any values.""" for key, value in list(attrs.items()): if value is None: del attrs[key] return attrs
bigcode/self-oss-instruct-sc2-concepts
import tempfile def tmpfile(prefix, direc): """Returns the path to a newly created temporary file.""" return tempfile.mktemp(prefix=prefix, suffix='.pdb', dir=direc)
bigcode/self-oss-instruct-sc2-concepts
def group_degree_centrality(G, S): """Compute the group degree centrality for a group of nodes. Group degree centrality of a group of nodes $S$ is the fraction of non-group members connected to group members. Parameters ---------- G : graph A NetworkX graph. S : list or set ...
bigcode/self-oss-instruct-sc2-concepts
import bisect def clip_around_detections(detections, time_interval): """Return the narrowest sublist of detections (a list of Detections) containing time_interval. """ times = [d.timestamp for d in detections] lo = bisect.bisect(times, time_interval[0]) - 1 hi = bisect.bisect_left(times, time...
bigcode/self-oss-instruct-sc2-concepts
import requests def pr_info(branch: str): """Get PR title and link from github api""" _, _, pr_nr = branch.partition("-") try: response = requests.get( f"https://api.github.com/repos/glotaran/pyglotaran/pulls/{pr_nr}", ).json() return response["title"], response["html_u...
bigcode/self-oss-instruct-sc2-concepts
def token_depth(token): """ determines the "depth" of a regex prefix tree. Used for guaranteeing unique node labels. """ if token[0] == 'singleton': return 1 else: depth = 0 for operand in token[1][1:]: if token_depth(operand) > depth: dep...
bigcode/self-oss-instruct-sc2-concepts
def is_string_arg(parameter): """Whether the parameter's type is string or bytes.""" return parameter["grpc_type"] in ["string", "bytes"]
bigcode/self-oss-instruct-sc2-concepts
def _is_leap(y): """True if y is a leap year.""" return (y % 400 == 0 or (y % 4 == 0 and y % 100 != 0))
bigcode/self-oss-instruct-sc2-concepts
import random def random_case(message: str) -> str: """Convert the string to RanDoM CasE. Parameters ---------- message : str The string to be converted Returns ------- str The string in RandOm caSe """ characters = [] for character in message: conver...
bigcode/self-oss-instruct-sc2-concepts
def center_of_effect(cloud, duration): """ The center of effect condenses musical information in the spiral array by a single point. Parameters ---------- cloud : 3D array Array containing the coordinates in the spiral array of the notes in the cloud. duration : array ...
bigcode/self-oss-instruct-sc2-concepts
def limpiar_1(texto:str): """ Se hace una primera limpieza de los datos. Eliminando saltos de línea, y espacios innecesarios. """ texto = texto.replace('\n', '') return texto
bigcode/self-oss-instruct-sc2-concepts
def hex_to_rgb(hexstring): """ Converts a hexadecimal string to RGB tuple Parameters ---------- hexstring : str Hexadecimal string such as '#FFFFFF' Returns ------- tuple RGB tuple such as (256,256,256) """ #From http://stackoverflow.com/a/214657 hexstri...
bigcode/self-oss-instruct-sc2-concepts
def is_valid_minimizer(object): """ Checks if the minimzer object has the following attributes/methods: * minimize """ has_minimize = hasattr(object, "minimize") return has_minimize
bigcode/self-oss-instruct-sc2-concepts
def C2F(C): """Convert Celcius to Fahrenheit""" return 1.8 * C + 32
bigcode/self-oss-instruct-sc2-concepts
def _GetDataFilesForTestSuite(test_suite_basename): """Returns a list of data files/dirs needed by the test suite. Args: test_suite_basename: The test suite basename for which to return file paths. Returns: A list of test file and directory paths. """ test_files = [] if test_suite_basename in ['Ch...
bigcode/self-oss-instruct-sc2-concepts
def estimarPGC(h, a, n, sexo): """Estimación del PGC utilizando la fórmula del item M. Args: h (float): Altura en centímetros a (float): Circunferencia abdominal en centímetros n (float): Circunferencia del cuello en centímetros sexo (string): 'M': Masculino ; 'F': Femenino ...
bigcode/self-oss-instruct-sc2-concepts
def loop(self, n=None, duracion=None): """ Returns a clip that plays the current clip in an infinite loop. Ideal for clips coming from gifs. Parameters ------------ n Number of times the clip should be played. If `None` the the clip will loop indefinitely (i.e. with no set durac...
bigcode/self-oss-instruct-sc2-concepts
def normalized_in_degree(in_degree_dict): """ dict -> dict Takes a dictionary of nodes with their indegree value, and returns a normalized dictionary whose values sum up to 1. """ normalized = {} for key in in_degree_dict: normalized[key] = float(in_degree_dict[key]) / len(in_degree_dic...
bigcode/self-oss-instruct-sc2-concepts
def countMotHitCmp(motDistr1, motDistr2): """Helper function for comparing two motif distributions. Compares based on number of central hits.""" return motDistr2.getNcentralHits() - motDistr1.getNcentralHits()
bigcode/self-oss-instruct-sc2-concepts