seed
stringlengths
1
14k
source
stringclasses
2 values
from pathlib import Path def parse_lovpy_ignore(path: Path): """Returns all patters contained in given .lovpyignore file.""" if not path.name == ".lovpyignore": raise RuntimeError(f"Invalid .lovpyignore file: {str(path)}") ignore_paths = [] with path.open("r") as f: for line in f: ...
bigcode/self-oss-instruct-sc2-concepts
def is_number(string): """Function to test whether a string is a float number""" try: float(string) return True except ValueError: return False
bigcode/self-oss-instruct-sc2-concepts
def partition_coefficients(IDs, top, bottom): """ Return partition coefficients given streams in equilibrium. Parameters ---------- top : Stream Vapor fluid. bottom : Stream Liquid fluid. IDs : tuple[str] IDs of chemicals in equilibrium. Returns ----...
bigcode/self-oss-instruct-sc2-concepts
def get_vos(da): """ Takes an xarray DataArray containing veg_index values and calculates the vegetation value and time (day of year) at valley of season (vos) for each timeseries per-pixel. The valley of season is the minimum value in the timeseries, per-pixel. Parameters ---------- ...
bigcode/self-oss-instruct-sc2-concepts
def needs_ascii(fh): """ Answer whether to encode as ascii for the given file handle, which is based on whether the handle has an encoding (None under py2 and UTF-8 under py3) and whether the handle is associated with a tty. """ if fh.encoding and fh.encoding != "UTF-8": return True ...
bigcode/self-oss-instruct-sc2-concepts
import torch def preprocess(im, pro): """ This function converts the numpy arrays or lists to tensors and returns it. Can be augmented with different operations in the future if needed (like augmentation). im: BxCxHxW images pro: list of list of integers [delta_elev, delta_azim, e...
bigcode/self-oss-instruct-sc2-concepts
def _get_used_ports(vms): """ Return a set of ports in use by the ``vms``. :param vms: list of virtual machines :type vms: list(:class:`~.vm.VM`) :return: set of ports :rtype: set(int) """ used_ports = set() for vm in vms: ip, port = vm.get_ssh_info() ...
bigcode/self-oss-instruct-sc2-concepts
def dict_to_associative_list(dict_value): """Serializes a dict to an associative list.""" return ",".join(["%s=%s" % (k, dict_value[k]) for k in dict_value])
bigcode/self-oss-instruct-sc2-concepts
import torch def is_on_gpu(model): """ Returns True if all parameters of a model live on the GPU. """ assert isinstance(model, torch.nn.Module) on_gpu = True has_params = False for param in model.parameters(): has_params = True if not param.data.is_cuda: on_gpu ...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def add_metadata_values_to_record(record_message): """Populate metadata _sdc columns from incoming record message The location of the required attributes are fixed in the stream """ extended_record = record_message['record'] extended_record['_sdc_extracted_at'] = reco...
bigcode/self-oss-instruct-sc2-concepts
def optimize_list_worker(x, n0, profiler, **kwargs): """Worker function needed for parallel execution of the likelihood optimization (see the `_optimize_list` method of `Profiler`).""" return profiler._optimize_list(x, n0, **kwargs)
bigcode/self-oss-instruct-sc2-concepts
import requests def web_gbif_validate(tax, rnk, gbif_id=None, gbif_ignore=None): """ Validates a taxon name and rank against the GBIF web API. It uses the API endpoint species/match?name=XXX&rank=YYY&strict=true endpoint to # safe to assume that the next least nested taxonomic level is the pare...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def find_free_filename(file_path: str) -> Path: """Given a file path, check if that file exists, and if so, repeatedly add a numeric infix to that file path until the file does not exist. For example, if output/counts.csv, exists check if counts_1.csv, counts_2.csv, and s...
bigcode/self-oss-instruct-sc2-concepts
def _read_fname(fname): """ Open fname, read the contents, return them. """ with open(fname, 'rb') as fil: return str(fil.read())
bigcode/self-oss-instruct-sc2-concepts
from typing import Union def _get_item(ptr, itempath: str) -> Union[str, dict, list, None]: """Utility function. The ptr param should point at .services then follow the itempath (separated via '.') to the expected object. Returns None if invalid (tries to avoid Error).""" root = ptr for element in ite...
bigcode/self-oss-instruct-sc2-concepts
def get_value_at_index(my_list, index_list): """This method will take a base list and traverse the contained multi-dimensional array. Parameters: my_list -- This is the base list object index_list -- This is a list of nested indexes in a multi-dimensional array for example: [2][...
bigcode/self-oss-instruct-sc2-concepts
def get_lin_func_param(point_1, point_2): """ given two pairs of (X,Y) extracts parameters of a linear function. m: slope b: constant :param point_2: :param point_1: :return: slope, constant """ precision = 5 slope = round((point_1.predicted_profit - point_2.predicted_profit) / ...
bigcode/self-oss-instruct-sc2-concepts
def trading_pair_to_symbol(trading_pair: str) -> str: """ Converts Hummingbot trading pair format to Beaxy exchange API format example: BTC-USDC -> BTCUSDC """ return trading_pair.replace('-', '')
bigcode/self-oss-instruct-sc2-concepts
import ipaddress def is_ip(address): """ Returns True if address is a valid IP address. """ try: # Test to see if already an IPv4/IPv6 address address = ipaddress.ip_address(address) return True except (ValueError): return False
bigcode/self-oss-instruct-sc2-concepts
import re def prep_file_name(path, file): """ append the original path and file name * strips special chars * remove spaces (replace with underscore) * convert to lowercase :param path: the path part of the new file name :param file: the original file name :return: sanitized name ...
bigcode/self-oss-instruct-sc2-concepts
from bs4 import BeautifulSoup def get_job_title_indeed(card: BeautifulSoup) -> str: """ Extracts the jobs title from the portion of HTML containing an individual job card. Args: card (BeautifulSoup object): The individual job posting card being processed. Returns: str: The job title...
bigcode/self-oss-instruct-sc2-concepts
def strip_quotes(S): """ String leading and trailing quotation marks """ if '"' in S[0] or "'" in S[0]: S = S[1:] if '"' in S[-1] or "'" in S[-1]: S = S[:-1] return S
bigcode/self-oss-instruct-sc2-concepts
def tsplit(string, delimiters): """Behaves str.split but supports multiple delimiters.""" delimiters = tuple(delimiters) stack = [string,] for delimiter in delimiters: for i, substring in enumerate(stack): substack = substring.split(delimiter) stack.pop(i) ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union def increment_by_n(n: Union[int, float]): """Generates a function that will increment by n. Args: n (int): integer to increment by. >>> increment_by_n(2)(2) 4 """ def incrementor(base: Union[int, float]): return base + n return incrementor
bigcode/self-oss-instruct-sc2-concepts
def fmt_xpath_spec(tag: str, attributes: dict): """Format a xpath_spec string using the given tag and attributes The xpath_spec returned is 'absolute', and thus can't be used. Prepend "./" to the xpath spec if using it to actually look up an element. :param tag: The tag to format into the xpath spec ...
bigcode/self-oss-instruct-sc2-concepts
def _flatten_array_to_str(array): """ Helper function to reduce an array to a string to make it immutable. Args: array (array): Array to make to string Returns: string: String where each value from the array is appended to each other """ s = "" for i in array: s...
bigcode/self-oss-instruct-sc2-concepts
def checkIfX(coordinate, x): """ This function is a filter which return true if the first value of tuple is equal to x In : tuple : tuple to be tested In : x : float, The test value Out : Bool : Result of test """ if(coordinate[0][0] == x): return True else: return False
bigcode/self-oss-instruct-sc2-concepts
from typing import List def f_range(start: float, end: float, step: float=1.) -> List[float]: """Make list of floats like `numpy.arange`.""" out = [] while start < end: out.append(start) start += step return out
bigcode/self-oss-instruct-sc2-concepts
from typing import List def string_wrap(text: str, wrap_length: int) -> List[str]: """ Split a string into groups of wrap length. :param text: Original text :param wrap_length: Length at which the string has to be wrapped :return: List of wrapped strings """ string_list = [] while tex...
bigcode/self-oss-instruct-sc2-concepts
def calc_confidence(freq_set, H, support_data, rules, min_confidence=0.5, verbose=False): """Evaluates the generated rules. One measurement for quantifying the goodness of association rules is confidence. The confidence for a rule 'P implies H' (P -> H) is defined as the support for P and H divided by ...
bigcode/self-oss-instruct-sc2-concepts
def calc_sales_price(price): """ 计算9折后的价格 :param price: 折前价格 :return: 折后价格 """ if price < 0: raise ValueError("price should not < 0!") sales = 0.9 * price return sales
bigcode/self-oss-instruct-sc2-concepts
import re def remove_html(entry): """ Remove html tags from tweet (use in pd.df.apply) Args: entry (entry of pandas df): an entry of the tweet column of the tweet dataframe Returns: output: tweet with html tags remove """ pattern = r'<.+?>' output = re.sub(pat...
bigcode/self-oss-instruct-sc2-concepts
import yaml def get_model_tracer_lists(spec): """Return the `model_tracer_list` specified in the emergent constraint input file: EC-input.yaml. Parameters ---------- spec : string Specification of the constraint option in EC-input.yaml. Options include: 'ocean_constraint', ...
bigcode/self-oss-instruct-sc2-concepts
def get_number(file): """Returns the number part of the file name """ parts = file.split(sep="_") return parts[1]
bigcode/self-oss-instruct-sc2-concepts
def _quote_arg(arg): """ Quote the argument for safe use in a shell command line. """ # If there is a quote in the string, assume relevants parts of the # string are already quoted (e.g. '-I"C:\\Program Files\\..."') if '"' not in arg and ' ' in arg: return '"%s"' % arg return arg
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict import json def load_dict(filepath: str) -> Dict: """Load a dictionary from a JSON's filepath. Args: filepath (str): JSON's filepath. Returns: A dictionary with the data loaded. """ with open(filepath) as fp: d = json.load(fp) return d
bigcode/self-oss-instruct-sc2-concepts
def max_or_zero(*args, **kwargs): """returns max(*args) or zero if given an empty sequence (in which case max() would throw an error)""" if not args: return 0 if not args[0]: return 0 else: return max(*args, **kwargs)
bigcode/self-oss-instruct-sc2-concepts
def get_all_participants_in_dw_study(dw, study_id): """ return all local participant ids for a study :param dw: data warehouse end point :param study_id: study id in dw :return: list of local participant ids """ participants = dw.get_participants(study_id) local_participant_ids = [] ...
bigcode/self-oss-instruct-sc2-concepts
def task_divide(idx, n): """ Split array into specified number of sub-arrays. Used in context of tasks. Parameters ---------- idx List of tasks. n Number of sub-arrays to split. """ total = len(idx) if n <= 0 or 0 == total: return [idx] if n > total:...
bigcode/self-oss-instruct-sc2-concepts
def simpson(x, f): """ Compute a 1D definite integral using Simpson's rule. Parameters ---------- f : function User defined function. x : numpy array Integration domain. Returns ------- I : float Integration result. """ a = x[0] b = x[1] ya...
bigcode/self-oss-instruct-sc2-concepts
def broadcast_shapes(*shapes): """ Broadcast any number of shapes against each other. Parameters ---------- *shapes : tuples The shapes to broadcast Example ------- >>> broadcast_shapes((1,5), (3, 2, 1)) (3, 2, 5) """ if any(not isinstance(s, tuple) for s in shapes...
bigcode/self-oss-instruct-sc2-concepts
def sort_by_index_with_for_loop(index, array): """ Sort the array with the given index and return a list of (<element>, <original index>, <new index>) tuples. Parameters: index: List of length n that contains interger 0 to n-1. array: List of length n. Returns: A list of len...
bigcode/self-oss-instruct-sc2-concepts
def read_txt(file_list): """Read .txt file list Arg: file_list (str): txt file filename Return: (list): list of read lines """ with open(file_list, "r") as f: filenames = f.readlines() return [filename.replace("\n", "") for filename in filenames]
bigcode/self-oss-instruct-sc2-concepts
import re def sentences(text: str) -> list[str]: """ Splits text into an array of its sentences. Finds two spaces, or newline, or tab, and splits there. Parameters ------------ text: str The text to be split up. Returns ------------ str[] An array of strings (sentenc...
bigcode/self-oss-instruct-sc2-concepts
def division(a, b): """ Divides one operator from another one Parameters: a (int): First value b (int): Second value Returns: int: division result """ if b == 0: raise ValueError('Can not divide by zero') return a / b
bigcode/self-oss-instruct-sc2-concepts
import json def policy_from_file(file_path): """Return dictionary from policy file.""" with open(file_path) as pol_file: policy = pol_file.read() return json.loads(policy)
bigcode/self-oss-instruct-sc2-concepts
import functools import warnings def deprecated(f): """Decorator to mark functions or methods as deprecated.""" @functools.wraps(f) def wrapped(*args, **kwds): message = "Calling deprecated function {}".format(f.__name__) warnings.warn(message, DeprecationWarning, stacklevel=2) re...
bigcode/self-oss-instruct-sc2-concepts
def extract_unmasked_data(radar, field, bad=-32768): """Simplify getting unmasked radar fields from Py-ART""" return radar.fields[field]['data'].filled(fill_value=bad)
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterable def mult_elwise(items: Iterable, value: float): """Multiply all values in an iterable by a constant.""" result = [] for i in items: result.append(i * value) return result
bigcode/self-oss-instruct-sc2-concepts
def rescale_to_max_value(max_value, input_list): """ Rescale each value inside input_list into a target range of 0 to max_value """ scale_factor = max_value / float(max(input_list)) # Multiply each item by the scale_factor input_list_rescaled = [int(x * scale_factor) for x in input_list] return inpu...
bigcode/self-oss-instruct-sc2-concepts
def get_requirements(filename: str): """Build the requirements list from the filename""" requirements_list = [] with open(filename, "r") as reqs: for install in reqs: requirements_list.append(install.strip()) return requirements_list
bigcode/self-oss-instruct-sc2-concepts
def matcher(source): """ Matches user input with datasets, the lists can be extended """ matcher_map = {"power_plant": ["coal", "coals", "natural gas", "gas", "bioenergy", "biomass", "hard coal", "lignite", "Fossil fuels", "fossil", "...
bigcode/self-oss-instruct-sc2-concepts
def __process_line(line, strip_eol, strip): """ process a single line value. """ if strip: line = line.strip() elif strip_eol and line.endswith('\n'): line = line[:-1] return line
bigcode/self-oss-instruct-sc2-concepts
def event(base_url: str) -> str: """ Build the URL for an execution's event. """ return '/'.join([base_url, 'events'])
bigcode/self-oss-instruct-sc2-concepts
def json_int_clean(json_elmnt): """return integer if json element is not none, otherwise return -1""" if json_elmnt: ret = int(json_elmnt) else: ret = -1 return ret
bigcode/self-oss-instruct-sc2-concepts
def get_root(database): """Load root folder from database.""" return list(database.keys())[0]
bigcode/self-oss-instruct-sc2-concepts
def get_movies_by_keyword(hs_movie, enter_val): """ Showing the movies that consists of entered word Parameters: hs_movie (dic): information about movies enter_val (str): Entered keyword returns: list: return list_tuple """ list_tuple = [] for year in hs_movie: for mo...
bigcode/self-oss-instruct-sc2-concepts
def split_sequences(sequences): """The output of the sequencer can be split into four different types of sequences for ease of checking: Sequences of words, sequences of lemmas, sequences of words without stops, and sequences of lemmas without stops. This method performs that split. :param list seq...
bigcode/self-oss-instruct-sc2-concepts
import six def convert_to_text(value): """ Make sure a value is a text type in a Python version generic manner. :param value: a value that is either a text or binary string. :returns value: a text value. """ if isinstance(value, six.binary_type): value = value.decode('utf8') if no...
bigcode/self-oss-instruct-sc2-concepts
import torch def nm_suppression(boxes, scores, overlap=0.45, top_k=200): """ Non-Maximum Suppressionを行う関数。 boxesのうち被り過ぎ(overlap以上)のBBoxを削除する。 Parameters ---------- boxes : [確信度閾値(0.01)を超えたBBox数,4] BBox情報。 scores :[確信度閾値(0.01)を超えたBBox数] confの情報 Returns ------- ...
bigcode/self-oss-instruct-sc2-concepts
def find_occurrence(string, substring, occurrence): """Find position of n'th occurrence of substring in string, else -1.""" # string - a string to be searched # substring - a substring to search for # occurrence - the occurrence to search for, starting from 0 # if not present, return -1 found ...
bigcode/self-oss-instruct-sc2-concepts
def prep_early_warning(hours, minutes, assignment_name): """ Create a early warning message. :param hours: Hours until the deadline. :type hours: int :param minutes: Minutes until the deadline. :type minutes: int :param assignment_name: Name of the assignment that approaches its deadline. ...
bigcode/self-oss-instruct-sc2-concepts
def _agent_is_gene(agent, specific_only): """Returns whether an agent is for a gene. Parameters ---------- agent: Agent The agent to evaluate specific_only : Optional[bool] If True, only elementary genes/proteins evaluate as genes and families will be filtered out. If False,...
bigcode/self-oss-instruct-sc2-concepts
def _MergeSpacedArgs(command_line, argname): """Combine all arguments |argname| with their values, separated by a space.""" i = 0 result = [] while i < len(command_line): arg = command_line[i] if arg == argname: result.append(arg + ' ' + command_line[i + 1]) i += 1 else: result.app...
bigcode/self-oss-instruct-sc2-concepts
import math def nice_num(rge, rnd): """ Get a nice number (1, 2, 5, 10, ...) :param rge: range :param rnd: round or not :return: a nice number """ exponent = math.floor(math.log10(rge)) fraction = rge / math.pow(10, exponent) if rnd: if fraction < 1.5: nice_fra...
bigcode/self-oss-instruct-sc2-concepts
def toDD(n): """Takes an integer and returns a string of length 2 corresponding to it""" if n // 10 > 0: return str(n) else: return "0" + str(n)
bigcode/self-oss-instruct-sc2-concepts
def get_flooded_second_token_from_msg(msg): """Get the first token image from message when flooded Arguments: msg (PIL.Image.Image): Image object Return: token (PIL.Image.Image): Image object """ return msg.crop((202, 0, 229, msg.height))
bigcode/self-oss-instruct-sc2-concepts
def A_pixel(info_dict): """ Compute the projected area of one pixel on the sky Parameter --------- info_dict: dictionnary Returns -------- A_pixel: float projected area of one pixel on the sky (arcsec2/px) """ pix_sky_area = info_dict['pixelScale_X']*info_dict['pi...
bigcode/self-oss-instruct-sc2-concepts
def build_test_info(framework='tensorflow', framework_version=None, framework_describe=None, channel=None, build_type=None, batch_size=None, model=None, accel_cnt=None, ...
bigcode/self-oss-instruct-sc2-concepts
def b36decode(number: str) -> int: """Convert the base36 number to an integer.""" return int(number, 36)
bigcode/self-oss-instruct-sc2-concepts
def get_clim_model_filenames(config, variable): """Extract model filenames from the configuration.""" model_filenames = {} for key, value in config['input_data'].items(): if value['short_name'] == variable: model_filenames[value['dataset']] = key return model_filenames
bigcode/self-oss-instruct-sc2-concepts
def rchop(thestring, ending): """Removes the given ending from the end of the string""" if thestring.endswith(ending): return thestring[:-len(ending)] return thestring
bigcode/self-oss-instruct-sc2-concepts
def get_median_values(data,ds): """extracts median abundance values :param data: PTCF :param ds: data set identifier (ds1 or ds1) :return: median values of given data set """ values = data[[x for x in list(data) if x.startswith(ds) & (x!="ds1_cluster") & (x!="ds2_cluster") & (x!="gene")]] return values.medi...
bigcode/self-oss-instruct-sc2-concepts
import collections def group_posts(parsed): """Take the raw list of posts and group them by categories.""" grouped = collections.defaultdict(list) for post in parsed: grouped[post['category']].append(post) return grouped
bigcode/self-oss-instruct-sc2-concepts
import torch def from_onehot(y): """Converts one-hot encoded probabilities to label indices. Parameters ---------- y: Tensor or Variable Returns ------- Tensor or Variable containing the label indices. """ _, labels_pred = torch.max(y, 1) return labels_pred
bigcode/self-oss-instruct-sc2-concepts
def retrieve_hidden_word(full_word, found_letter): """This function returns a hidden word. The hidden letters are marked with an asterisk *.""" hidden_word = "" for letter in full_word: if letter in found_letter: hidden_word += letter else: hidden_word += "*" ...
bigcode/self-oss-instruct-sc2-concepts
import torch def conv1x1(in_planes, out_planes, stride=1): """1x1 convolution""" return torch.nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)
bigcode/self-oss-instruct-sc2-concepts
import requests import logging import json def get_function_signature_from_4bytes(hex_signature): """ Requests the function signature from 4byte-directory based on the hex_signature to get the text_signature Args: hex_signature: the signature of the function as hex value Returns: signatu...
bigcode/self-oss-instruct-sc2-concepts
def filter_logic_form(lf: list, denylist: list) -> bool: """ Checks whether logic form contains denylisted terms. Parameter: lf (list): logic form denylist (list): denylisted terms Returns: False if logic form contains denylisted term(s). True otherwise """ keep_flags = [] for...
bigcode/self-oss-instruct-sc2-concepts
def calc_stats(total_unique_molecular_bases, total_bases, output_bases, genome_size, coverage): """ >>> calc_stats(0, 0, 0, 0, 0) == \ {'genome_size': 0, 'coverage': 0, 'total_bases': 0, 'total_unique_molecular_bases': 0, \ 'output_bases': 0, 'unique_molecular_avg_cov': 0.0, 'output_avg_cov': 0.0, 'tota...
bigcode/self-oss-instruct-sc2-concepts
import requests def get_live_url(channel): """ Finds a live stream url for channel :param channel: Slug name of channel :return An url """ apiurl = ( "http://ruv.is/sites/all/themes/at_ruv/" "scripts/ruv-stream.php?format=json" ) try: json = requests.get(apiurl ...
bigcode/self-oss-instruct-sc2-concepts
def sparse_min_size(value=1000): """Return minimal sparse problem size for which to warn about converting to dense.""" return value
bigcode/self-oss-instruct-sc2-concepts
def get_folders(values_dict): """Returns a dict of all the folders in the given value_dict.""" return dict( (item, configs) for (item, configs) in values_dict.iteritems() if item.endswith('/') )
bigcode/self-oss-instruct-sc2-concepts
def wrap_lines(lines, line_length=80, word_sep=' ', line_sep='\n', strip_whitespace=True): """Wrap the contents of `lines` to be `line_length` characters long. Parameters ========== lines : string Text to wrap line_length : integer Maximum number of cha...
bigcode/self-oss-instruct-sc2-concepts
def detect_id_type(sid): """Method that tries to infer the type of abstract ID. Parameters ---------- sid : str The ID of an abstract on Scopus. Raises ------ ValueError If the ID type cannot be inferred. Notes ----- ...
bigcode/self-oss-instruct-sc2-concepts
import re def _get_index(passed_id=None): """ From the url w/ index appended, get the index. """ if passed_id: index_matcher = re.search(r'.*?/?(\d+)$', passed_id) if index_matcher: return int(index_matcher.group(1)) # return 0 if no index found return 0
bigcode/self-oss-instruct-sc2-concepts
import random def shuffle_data(x, y, d): """ Randomly shuffle co-indexed lists, pertaining the alignment of the lists""" xyd = list(zip(x, y, d)) random.shuffle(xyd) x, y, d = zip(*xyd) x, y, d = list(x), list(y), list(d) return x, y, d
bigcode/self-oss-instruct-sc2-concepts
def mkdown_h(text, level, link=None): """ Generates the markdown syntax for a header of a certain level. """ if level == 1: return '\n' + ('<a name="{}"></a>'.format(link) if link else '') + text + '\n' \ + '='*len(text) elif level == 2: return '\n' + ('<a name="{}"><...
bigcode/self-oss-instruct-sc2-concepts
import random def simInsertions(numIndices, numInsertions): """Assumes numIndices and numInsertions are positive ints. Returns 1 if there is a collision; 0 otherwise""" choices = range(numIndices) #list of possible indices used = [] for i in range(numInsertions): hashVal = random.choice...
bigcode/self-oss-instruct-sc2-concepts
def unrank_from_list(l): """ Returns an unrank function from a list. EXAMPLES:: sage: import sage.combinat.ranker as ranker sage: l = [1,2,3] sage: u = ranker.unrank_from_list(l) sage: u(2) 3 sage: u(0) 1 """ unrank = lambda j: l[j] retur...
bigcode/self-oss-instruct-sc2-concepts
def hydraulic_losses_suct_feed(dzeta_enter_feed, dzeta_turn90_feed, n_turn90_feed, dzeta_ventil_feed, n_ventil_feed, g, w_liq_real_enter_feed): """ Calculates the hydraulic losses of suction line. Parameters ---------- dzeta_enter_feed : float The local resistance of tube enter, [m] dzet...
bigcode/self-oss-instruct-sc2-concepts
import re def remove_bad_quotes(text): """Returns a string with bad quotes removed""" result = re.sub("[‘’“”…]", " ", text) return result
bigcode/self-oss-instruct-sc2-concepts
def part_encode(part): """Encode a part of a JSON pointer. >>> part_encode("foo") 'foo' >>> part_encode("~foo") '~0foo' >>> part_encode("foo~") 'foo~0' >>> part_encode("/foo") '~1foo' >>> part_encode("foo/") 'foo~1' >>> part_encode("f/o~o") 'f~1o~0o' >>> part_enc...
bigcode/self-oss-instruct-sc2-concepts
def getMonth(month): """Method to return the month in a number format Args: month (string): the month in a string format Returns: string: month in the number format """ if month == 'Jan': return '01' elif month == 'May': return '05' elif month == 'Jun': ...
bigcode/self-oss-instruct-sc2-concepts
def ingest_dns_record(neo4j_session, name, value, type, update_tag, points_to_record): """ Ingest a new DNS record :param neo4j_session: Neo4j session object :param name: record name :param value: record value :param type: record type :param update_tag: Update tag to set the node with and c...
bigcode/self-oss-instruct-sc2-concepts
def get_mir_counts(bamfile, gff_file): """ Takes a AlignmentFile and a gff file and computes for each 'miRNA' region of the gff the number of reads that hit it returns a dict[mir_name] = count """ counts = dict() for line in open(gff_file, 'r'): if line[0] != '#': gff_fie...
bigcode/self-oss-instruct-sc2-concepts
import shlex def shell_variables(data): """ Prepare variables to be consumed by shell Convert dictionary or list/tuple of key=value pairs to list of key=value pairs where value is quoted with shlex.quote(). """ # Convert from list/tuple if isinstance(data, list) or isinstance(data, tuple...
bigcode/self-oss-instruct-sc2-concepts
def startswith_str(text, prefix, start=None, end=None): """ Determines if ``text`` starts with the specified prefix. The prefix can also be a tuple of prefixes to look for. With optional parameter ``start``, the test will begin at that position. With optional parameter ``end``, the test will ...
bigcode/self-oss-instruct-sc2-concepts
import math def intRect(rect): """Round a rectangle to integer values. Guarantees that the resulting rectangle is NOT smaller than the original. Args: rect: Bounding rectangle, expressed as tuples ``(xMin, yMin, xMax, yMax)``. Returns: A rounded bounding rectangle. "...
bigcode/self-oss-instruct-sc2-concepts
def safe_filename(filename): """去掉文件名中的非法字符。 :param str filename: 文件名 :return str: 合法文件名 """ return "".join([c for c in filename if c not in r'\/:*?"<>|']).strip()
bigcode/self-oss-instruct-sc2-concepts