seed
stringlengths
1
14k
source
stringclasses
2 values
def serialize_drive(drive) -> str: """ Serialize the drive residues and calibration state to xml. """ drivexml = drive.state_to_xml() return drivexml
bigcode/self-oss-instruct-sc2-concepts
def return_list_smart(func): """ Decorator. If a function is trying to return a list of length 1 it returns the list element instead """ def inner(*args, **kwargs): out = func(*args, **kwargs) if not out: return None if len(out) == 1: return...
bigcode/self-oss-instruct-sc2-concepts
def vec_bin(v, nbins, f, init=0): """ Accumulate elements of a vector into bins Parameters ---------- v: list[] A vector of scalar values nbins: int The number of bins (accumulators) that will be returned as a list. f: callable A function f(v)->[bo,...,bn] that maps ...
bigcode/self-oss-instruct-sc2-concepts
import requests from bs4 import BeautifulSoup def get_soup(url): """ input url, output a soup object of that url """ page=requests.get(url) soup = BeautifulSoup(page.text.encode("utf-8"), 'html.parser') return soup
bigcode/self-oss-instruct-sc2-concepts
import functools def if_inactive(f): """decorator for callback methods so that they are only called when inactive""" @functools.wraps(f) def inner(self, loop, *args, **kwargs): if not self.active: return f(self, loop, *args, **kwargs) return inner
bigcode/self-oss-instruct-sc2-concepts
import asyncio import functools def async_test(loop=None): """Wrap an async test in a run_until_complete for the event loop.""" loop = loop or asyncio.get_event_loop() def _outer_async_wrapper(func): """Closure for capturing the configurable loop.""" @functools.wraps(func) def _in...
bigcode/self-oss-instruct-sc2-concepts
def get_strains(output_file): """ Returns a dictionary that maps cell id to strain. Takes Biocellion output as the input file. """ strain_map = {} with open(output_file, 'r') as f: for line in f: if line.startswith("Cell:"): tokens = line.split(',') cell = int(tokens[0].split('...
bigcode/self-oss-instruct-sc2-concepts
def is_iterable(x): """Returns True for all iterables except str, bytes, bytearray, else False.""" return hasattr(x, "__iter__") and not isinstance(x, (str, bytes, bytearray))
bigcode/self-oss-instruct-sc2-concepts
def bprop_scalar_log(x, out, dout): """Backpropagator for primitive `scalar_log`.""" return (dout / x,)
bigcode/self-oss-instruct-sc2-concepts
def _get_drive_distance(maps_response): """ from the gmaps response object, extract the driving distance """ try: return maps_response[0].get('legs')[0].get('distance').get('text') except Exception as e: print(e) return 'unknown distance'
bigcode/self-oss-instruct-sc2-concepts
def calc_tcp(gamma, td_tcd, eud): """Tumor Control Probability / Normal Tissue Complication Probability 1.0 / (1.0 + (``td_tcd`` / ``eud``) ^ (4.0 * ``gamma``)) Parameters ---------- gamma : float Gamma_50 td_tcd : float Either TD_50 or TCD_50 eud : float equivalen...
bigcode/self-oss-instruct-sc2-concepts
def get_enrollment(classroom, enrolled_only=False): """Gets the list of students that have enrolled. Args: classroom: The classroom whose enrollment to get. enrolled_only: If True, only return the set that are enrolled. Default is False. Returns: Set of Enrollment entries for the classroom. ...
bigcode/self-oss-instruct-sc2-concepts
def get_price_for_market_state_crypto(result): """Returns the price for the current state of the market for Cryptocurrency symbols""" ## Crypto always on REGULAR market state, as it never sleeps ZZzzZZzzz... return { "current": result['regularMarketPrice']['fmt'], "previous": result['regular...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def get_latest_archive_url(data: dict) -> str: """ Use the given metadata to find the archive URL of the latest image. """ metadata = data[-1] img = metadata["image"] date = datetime.strptime(metadata["date"], "%Y-%m-%d %H:%M:%S") archive_path = f"{date.year:0...
bigcode/self-oss-instruct-sc2-concepts
import shlex def generate_input_download_command(url, path): """Outputs command to download 'url' to 'path'""" return f"python /home/ft/cloud-transfer.py -v -d {shlex.quote(url)} {shlex.quote(path)}"
bigcode/self-oss-instruct-sc2-concepts
def _calculate_shrinking_factor(initial_shrinking_factor: float, step_number: int, n_dim: int) -> float: """The length of each in interval bounding the parameter space needs to be multiplied by this number. Args: initial_shrinking_factor: in each step the total volume is shrunk by this amount s...
bigcode/self-oss-instruct-sc2-concepts
def calc_grv(thickness, height, area, top='slab', g=False): """Calculate GRV for given prospect Args: thickness [float]: average thickness of reservoir height [float]: height of hydrocarbon column area [float]: area of hydrocarbon prospect top: structure shape, one of `{'slab', '...
bigcode/self-oss-instruct-sc2-concepts
import struct def decode_override_information(data_set): """decode result from override info :param tuple result_set: bytes returned by the system parameter query command R_RI for override info :returns: dictionary with override info values :rtype: dict """ overri...
bigcode/self-oss-instruct-sc2-concepts
def is_link_displayed(link: str, source: str): """Check if the link is explicitly displayed in the source. Args: link: a string containing the link to find in the webpage source code. source: the source code of the webpage. Returns: True is the link is visible in the webpage, False...
bigcode/self-oss-instruct-sc2-concepts
import codecs def decode_utf_8_text(text): """Decode the text from utf-8 format Parameters ---------- text : str String to be decoded Returns ------- str Decoded string """ try: return codecs.decode(text, 'utf-8') except: return text
bigcode/self-oss-instruct-sc2-concepts
def create_user2(django_user_model): """ create another user """ user = django_user_model.objects.create_user( username='user_2', email='another@gmail.com', password='pass123' ) return user
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def _time_stamp_filename(fname, fmt='%Y-%m-%d_{fname}'): """ Utility function to add a timestamp to names of uploaded files. Arguments: fname (str) fmt (str) Returns: str """ return datetime.now().strftime(fmt).format(fname=fname)
bigcode/self-oss-instruct-sc2-concepts
def _format_size(x: int, sig_figs: int = 3, hide_zero: bool = False) -> str: """ Formats an integer for printing in a table or model representation. Expresses the number in terms of 'kilo', 'mega', etc., using 'K', 'M', etc. as a suffix. Args: x (int) : The integer to format. sig_fi...
bigcode/self-oss-instruct-sc2-concepts
def normalize(df, col_name, replace=True): """Normalize number column in DataFrame The normalization is done with max-min equation: z = (x - min(x)) / (max(x) - min(x)) replace -- set to False if it's desired to return new DataFrame instead of editing it. """ col = df[col_name] ...
bigcode/self-oss-instruct-sc2-concepts
import torch def csv_collator(samples): """Merge a list of samples to form a batch. The batch is a 2-element tuple, being the first element the BxHxW tensor and the second element a list of dictionaries. :param samples: List of samples returned by CSVDataset as (img, dict) tuples. """ imgs ...
bigcode/self-oss-instruct-sc2-concepts
def in_box(coords, box): """ Find if a coordinate tuple is inside a bounding box. :param coords: Tuple containing latitude and longitude. :param box: Two tuples, where first is the bottom left, and the second is the top right of the box. :return: Boolean indicating if the coordinates are in the box....
bigcode/self-oss-instruct-sc2-concepts
def batch_delete(query, session): """ Delete the result rows from the given query in batches. This minimizes the amount of time that the table(s) that the query selects from will be locked for at once. """ n = 0 query = query.limit(25) while True: if query.count() == 0: ...
bigcode/self-oss-instruct-sc2-concepts
def to_triplets(colors): """ Coerce a list into a list of triplets. If `colors` is a list of lists or strings, return it as is. Otherwise, divide it into tuplets of length three, silently discarding any extra elements beyond a multiple of three. """ try: colors[0][0] return...
bigcode/self-oss-instruct-sc2-concepts
import random import string def random_text(n) : """Generate random text 'n' characters""" return ''.join([random.choice(string.digits + string.ascii_letters) for x in range(n)])
bigcode/self-oss-instruct-sc2-concepts
import six import re def to_bytes(value): """Convert numbers with a byte suffix to bytes. """ if isinstance(value, six.string_types): pattern = re.compile('^(\d+)([K,M,G]{1})$') match = pattern.match(value) if match: value = match.group(1) suffix = match.gro...
bigcode/self-oss-instruct-sc2-concepts
def is_perfect_slow(n): """ decides if a given integer n is a perfect number or not this is the straightforward implementation """ if n <= 0: return(False) sum = 0 for i in range(1,n): if n % i == 0: sum += i return(sum == n)
bigcode/self-oss-instruct-sc2-concepts
def licence_name_to_file_name(licence_name: str) -> str: """ Converts a licence name to the name of the file containing its definition. :param licence_name: The licence name. :return: The file name. """ return licence_name.lower().replace(" ", "-") + ".txt"
bigcode/self-oss-instruct-sc2-concepts
def format_position(variant): """Gets a string representation of the variants position. Args: variant: third_party.nucleus.protos.Variant. Returns: A string chr:start + 1 (as start is zero-based). """ return '{}:{}'.format(variant.reference_name, variant.start + 1)
bigcode/self-oss-instruct-sc2-concepts
def score(goal, test_string): """compare two input strings and return decimal value of quotient likeness""" #goal = 'methinks it is like a weasel' num_equal = 0 for i in range(len(goal)): if goal[i] == test_string[i]: num_equal += 1 return num_equal / len(goal)
bigcode/self-oss-instruct-sc2-concepts
import copy def pad_1d_list(data, element, thickness=1): """ Adds padding at the start and end of a list This will make a shallow copy of the original eg: pad_1d_list([1,2], 0) -> returns [0,1,2,0] Args: data: the list to pad element: gets added as padding (if its an object, ...
bigcode/self-oss-instruct-sc2-concepts
def process_single(word): """ Process a single word, whether it's identifier, number or symbols. :param word: str, the word to process :return: str, the input """ if word[0].isnumeric(): try: int(word) except ValueError: raise ValueError("Expression {} no...
bigcode/self-oss-instruct-sc2-concepts
def remove_non_seriasable(d): """ Converts AnnotationType and EntityType classes to strings. This is needed when saving to a file. """ return { k: str(val.name).lower() if k in ('annotation_type', 'entity_type') else val for k, val in d.items() ...
bigcode/self-oss-instruct-sc2-concepts
def merge_dictionaries(dict1, dict2): """Merge dictionaries together, for the case of aggregating bindings.""" new_dict = dict1.copy() new_dict.update(dict2) return new_dict
bigcode/self-oss-instruct-sc2-concepts
def transpose(matrix): """ Compute the matrix transpose :param matrix: the matrix to be transposed, the transposing will not modify the input matrix :return: the transposed of matrix """ _transposed = [] for row in range(len(matrix)): _transposed.append( [matrix[i...
bigcode/self-oss-instruct-sc2-concepts
def rivers_with_station(stations): """Given a list of stations, return a alphabetically sorted set of rivers with at least one monitoring station""" river_set = set() for station in stations: river_set.add(station.river) river_set = sorted(river_set) return river_set
bigcode/self-oss-instruct-sc2-concepts
def permute(lst, perm): """Permute the given list by the permutation. Args: lst: The given list. perm: The permutation. The integer values are the source indices, and the index of the integer is the destination index. Returns: A permutation copy of lst. """ return tuple([...
bigcode/self-oss-instruct-sc2-concepts
import socket def gethostbyaddr(ip): """ Resolve a single host name with gethostbyaddr. Returns a string on success. If resolution fails, returns None. """ host = None try: host = socket.gethostbyaddr(ip)[0] except OSError: pass return host
bigcode/self-oss-instruct-sc2-concepts
import torch import math def gain_change(dstrfs, batch_size=8): """ Measure standard deviation of dSTRF gains. Arguments: dstrfs: tensor of dSTRFs with shape [time * channel * lag * frequency] Returns: gain_change: shape change parameter, tensor of shape [channel] """ ...
bigcode/self-oss-instruct-sc2-concepts
def multiply(*fields, n): """ Multiply ``n`` to the given fields in the document. """ def transform(doc): for field in fields: doc = doc[field] doc *= n return transform
bigcode/self-oss-instruct-sc2-concepts
def to_matrix_vector(transform): """Split an homogeneous transform into its matrix and vector components. The transformation must be represented in homogeneous coordinates. It is split into its linear transformation matrix and translation vector components. This function does not normalize the matri...
bigcode/self-oss-instruct-sc2-concepts
def prompt_int(prompt): """ Prompt until the user provides an integer. """ while True: try: return int(input(prompt)) except ValueError as e: print('Provide an integer')
bigcode/self-oss-instruct-sc2-concepts
def check_overlap(stem1, stem2): """ Checks if 2 stems use any of the same nucleotides. Args: stem1 (tuple): 4-tuple containing stem information. stem2 (tuple): 4-tuple containing stem information. Returns: bool: Boolean indicating if the two stems overlap....
bigcode/self-oss-instruct-sc2-concepts
import ast def str_to_list(string: str) -> list: """ convert list-like str to list :param string: "[(0, 100), (105, 10) ...]" :return: list of tuples """ return ast.literal_eval(string)
bigcode/self-oss-instruct-sc2-concepts
import json def json_load(path, verbose=False): """Load python dictionary stored in JSON file at ``path``. Args: path (str): Path to the file verbose (bool): Verbosity flag Returns: (dict): Loaded JSON contents """ with open(path, 'r') as f: if verbose: ...
bigcode/self-oss-instruct-sc2-concepts
def center_crop(img_mat, size = (224, 224)): """ Center Crops an image with certain size, image must be bigger than crop size (add check for that) params: img_mat: (3D-matrix) image matrix of shape (width, height, channels) size: (tuple) the size of crops (width, height) returns: ...
bigcode/self-oss-instruct-sc2-concepts
def plot_line(m, line, colour='b', lw=1, alpha=1): """ Plots a line given a line with lon,lat coordinates. Note: This means you probably have to call shapely `transform` on your line before passing it to this function. There is a helper partial function in utils called `utm2lola` w...
bigcode/self-oss-instruct-sc2-concepts
def _get_orientation(exif): """Get Orientation from EXIF. Args: exif (dict): Returns: int or None: Orientation """ if not exif: return None orientation = exif.get(0x0112) # EXIF: Orientation return orientation
bigcode/self-oss-instruct-sc2-concepts
import random def generate_layers(layer_limit: int, size_limit: int, matching: bool): """ Helper function for generating a random layer set NOTE: Randomized! :param layer_limit: The maximum amount of layers to generate :param size_limit: The maximum size of each layer :param matching: Specif...
bigcode/self-oss-instruct-sc2-concepts
def expand_resources(resources): """ Construct the submit_job arguments from the resource dict. In general, a k,v from the dict turns into an argument '--k v'. If the value is a boolean, then the argument turns into a flag. If the value is a list/tuple, then multiple '--k v' are presented, ...
bigcode/self-oss-instruct-sc2-concepts
def gen_workspace_tfvars_files(environment, region): """Generate possible Terraform workspace tfvars filenames.""" return [ # Give preference to explicit environment-region files "%s-%s.tfvars" % (environment, region), # Fallback to environment name only "%s.tfvars" % environment...
bigcode/self-oss-instruct-sc2-concepts
def comma_sep(values, limit=20, stringify=repr): """ Print up to ``limit`` values, comma separated. Args: values (list): the values to print limit (optional, int): the maximum number of values to print (None for no limit) stringify (callable): a function to use to convert values to ...
bigcode/self-oss-instruct-sc2-concepts
def myround (val, r=2): """ Converts a string of float to rounded string @param {String} val, "42.551" @param {int} r, the decimal to round @return {string} "42.55" if r is 2 """ return "{:.{}f}".format(float(val), r)
bigcode/self-oss-instruct-sc2-concepts
def normaliseports(ports): """Normalise port list Parameters ---------- ports : str Comma separated list of ports Returns ------- str | List If None - set to all Otherwise make sorted list """ if ports is None: return 'all' if ports in ('all', ...
bigcode/self-oss-instruct-sc2-concepts
def review_pks(database): """ Check that all tables have a PK. It's not necessarily wrong, but gives a warning that they don't exist. :param database: The database to review. Only the name is needed. :type database: Database :return: A list of recommendations. :rtype: list of str """ p...
bigcode/self-oss-instruct-sc2-concepts
import re def read_sta_file(sta_file): """ Read information from the station file with free format: net,sta,lon,lat,ele,label. The label is designed with the purpose to distinguish stations into types. """ cont = [] with open(sta_file,'r') as f: for line in f: line = line.r...
bigcode/self-oss-instruct-sc2-concepts
def read_file(file_name): """Returns the content of file file_name.""" with open(file_name) as f: return f.read()
bigcode/self-oss-instruct-sc2-concepts
def t_add(t, v): """ Add value v to each element of the tuple t. """ return tuple(i + v for i in t)
bigcode/self-oss-instruct-sc2-concepts
def fix_nonload_cmds(nl_cmds): """ Convert non-load commands commands dict format from Chandra.cmd_states to the values/structure needed here. A typical value is shown below: {'cmd': u'SIMTRANS', # Needs to be 'type' 'date': u'2017:066:00:24:22.025', 'id': 371228, ...
bigcode/self-oss-instruct-sc2-concepts
import copy def _update_inner_xml_ele(ele, list_): """Copies an XML element, populates sub-elements from `list_` Returns a copy of the element with the subelements given via list_ :param ele: XML element to be copied, modified :type ele: :class:`xml.ElementTree.Element` :param list list_: List of...
bigcode/self-oss-instruct-sc2-concepts
def construct_fixture_middleware(fixtures): """ Constructs a middleware which returns a static response for any method which is found in the provided fixtures. """ def fixture_middleware(make_request, web3): def middleware(method, params): if method in fixtures: r...
bigcode/self-oss-instruct-sc2-concepts
def can_leftarc(stack, graph): """ Checks that the top of the has no head :param stack: :param graph: :return: """ if not stack: return False if stack[0]['id'] in graph['heads']: return False else: return True
bigcode/self-oss-instruct-sc2-concepts
def concatenate_dictionaries(d1: dict, d2: dict, *d): """ Concatenate two or multiple dictionaries. Can be used with multiple `find_package_data` return values. """ base = d1 base.update(d2) for x in d: base.update(x) return base
bigcode/self-oss-instruct-sc2-concepts
def nulls(x): """ Convert values of -1 into None. Parameters ---------- x : float or int Value to convert Returns ------- val : [x, None] """ if x == -1: return None else: return x
bigcode/self-oss-instruct-sc2-concepts
from typing import List def compute_skew(sequence: str) -> List[float]: """Find the skew of the given sequence Arguments: sequence {str} -- DNA string Returns: List[float] -- skew list """ running_skew = [] skew = 0 for base in sequence.upper(): if base =...
bigcode/self-oss-instruct-sc2-concepts
import base64 import hashlib def generate_hash(url): """ Generates the hash value to be stored as key in the redis database """ hashval = base64.urlsafe_b64encode(hashlib.md5(url).digest()) hashval=hashval[0:6] return hashval
bigcode/self-oss-instruct-sc2-concepts
def Fplan(A, Phi, Fstar, Rp, d, AU=False): """ Planetary flux function Parameters ---------- A : float or array-like Planetary geometric albedo Phi : float Planetary phase function Fstar : float or array-like Stellar flux [W/m**2/um] Rp : float Planetary ...
bigcode/self-oss-instruct-sc2-concepts
def create_inventory(items): """ Create an inventory dictionary from a list of items. The string value of the item becomes the dictionary key. The number of times the string appears in items becomes the value, an integer representation of how many times. :param items: list - list of items to c...
bigcode/self-oss-instruct-sc2-concepts
import six def get_paramfile(path, cases): """Load parameter based on a resource URI. It is possible to pass parameters to operations by referring to files or URI's. If such a reference is detected, this function attempts to retrieve the data from the file or URI and returns it. If there are an...
bigcode/self-oss-instruct-sc2-concepts
def adds_comment_sign(data: str, comment_sign: str) -> str: """Adds comment signs to the string.""" return "\n".join(list(f"{comment_sign} {line}".strip() for line in data.split("\n")[:-1]))
bigcode/self-oss-instruct-sc2-concepts
def positive_coin_types_to_string(coin_dict): """ Converts only the coin elements that are greater than 0 into a string. Arguments: coin_dict (dict): A dictionary consisting of all 4 coin types. Returns: (string): The resulting string. """ plat = "" gold = "" silver = "...
bigcode/self-oss-instruct-sc2-concepts
def finalize_model(input_model): """ Extracts string from the model data. This function is always the last stage in the model post-processing pipeline. :param input_model: Model to be processed :return: list of strings, ready to be written to a module file """ finalized_output = [] for m...
bigcode/self-oss-instruct-sc2-concepts
from typing import OrderedDict def load_object(worksheet): """ Converts worksheet to dictionary Args: object: worksheet Returns: object: dictionary """ #d = {} #d = OrderedDict() d = OrderedDict() for curr_col in range(0, worksheet.ncols): liste_elts = work...
bigcode/self-oss-instruct-sc2-concepts
def getConstructors(jclass): """Returns an array containing Constructor objects reflecting all the public constructors of the class represented by this Class object.""" return jclass.class_.getConstructors()[:]
bigcode/self-oss-instruct-sc2-concepts
def ask_move(player: int) -> int: """Ask the player which pawn to move. Returns an integer between 0 and 3.""" while True: try: pawn_number = int(input(f"Player {player}: Choose a piece to move (0-3): ")) except ValueError: continue else: if 0 <= paw...
bigcode/self-oss-instruct-sc2-concepts
def find(arr, icd_code=False): """Search in the first column of `arr` for a 'Yes' and return the respective entry in the second column.""" search = [str(item) for item in arr[:,0]] find = [str(item) for item in arr[:,1]] try: idx = [i for i,item in enumerate(search) if "Yes" in item] ...
bigcode/self-oss-instruct-sc2-concepts
from typing import IO def open_file_or_stream(fos, attr, **kwargs) -> IO: """Open a file or use the existing stream. Avoids adding this logic to every function that wants to provide multiple ways of specifying a file. Args: fos: File or stream attr: Attribute to check on the ``fos`` ob...
bigcode/self-oss-instruct-sc2-concepts
def find_max_sub(l): """ Find subset with higest sum Example: [-2, 3, -4, 5, 1, -5] -> (3,4), 6 @param l list @returns subset bounds and highest sum """ # max sum max = l[0] # current sum m = 0 # max sum subset bounds bounds = (0, 0) # current subset start s = 0 ...
bigcode/self-oss-instruct-sc2-concepts
def f_W(m_act, n, Wint): """ Calculate shaft power """ return m_act * n - Wint
bigcode/self-oss-instruct-sc2-concepts
def _formatDict(d): """ Returns dict as string with HTML new-line tags <br> between key-value pairs. """ s = '' for key in d: new_s = str(key) + ": " + str(d[key]) + "<br>" s += new_s return s[:-4]
bigcode/self-oss-instruct-sc2-concepts
from typing import List def clusters_list(num_clusters: int) -> List[list]: """Create a list of empty lists for number of desired clusters. Args: num_clusters: number of clusters to find, we will be storing points in these empty indexed lists. Returns: clusters: empty list of lists. ...
bigcode/self-oss-instruct-sc2-concepts
def number_format(num, places=0): """Format a number with grouped thousands and given decimal places""" places = max(0,places) tmp = "%.*f" % (places, num) point = tmp.find(".") integer = (point == -1) and tmp or tmp[:point] decimal = (point != -1) and tmp[point:] or "" count = 0 formatted = ...
bigcode/self-oss-instruct-sc2-concepts
def get_cdm_cluster_location(self, cluster_id): """Retrieves the location address for a CDM Cluster Args: cluster_id (str): The ID of a CDM cluster Returns: str: The Cluster location address str: Cluster location has not be configured. str: A cluster with an ID of {cluster_id...
bigcode/self-oss-instruct-sc2-concepts
def is_session_dir(path): """Return whether a path is a session directory. Example of a session dir: `/path/to/root/mainenlab/Subjects/ZM_1150/2019-05-07/001/` """ return path.is_dir() and path.parent.parent.parent.name == 'Subjects'
bigcode/self-oss-instruct-sc2-concepts
def coalesce(*xs): """ Coalescing monoid operation: return the first non-null argument or None. Examples: >>> coalesce(None, None, "not null") 'not null' """ if len(xs) == 1: xs = xs[0] for x in xs: if x is not None: return x return None
bigcode/self-oss-instruct-sc2-concepts
import re def __is_rut_perfectly_formatted(rut: str) -> bool: """ Validates if Chilean RUT Number is perfectly formatted Args: rut (str): A Chilean RUT Number. For example 5.126.663-3 Returns: bool: True when Chilean RUT number (rut:str) is perfectly formatted ** Only valida...
bigcode/self-oss-instruct-sc2-concepts
def create_single_object_response(status, object, object_naming_singular): """ Create a response for one returned object @param status: success, error or fail @param object: dictionary object @param object_naming_singular: name of the object, f.ex. book @return: dictionary. """ return {"...
bigcode/self-oss-instruct-sc2-concepts
def _query_item(item, query_id, query_namespace): """ Check if the given cobra collection item matches the query arguments. Parameters ---------- item: cobra.Reaction or cobra.Metabolite query_id: str The identifier to compare. The comparison is made case insensitively. query_namesp...
bigcode/self-oss-instruct-sc2-concepts
import re def strip_html_tags(text): """Strip HTML tags in a string. :param text: String containing HTML code :type text: str :return: String without HTML tags :rtype: str :Example: >>> strip_html_tags('<div><p>This is a paragraph</div>') 'This is a paragraph' >>> strip_html_ta...
bigcode/self-oss-instruct-sc2-concepts
def get_next_open_row(board, col): """ Finds the topmost vacant cell in column `col`, in `board`'s grid. Returns that cell's corresponding row index. """ n_rows = board.n_rows # check row by row, from bottom row to top row ([0][0] is topleft of grid) for row in range(n_rows - 1, -1, -1): ...
bigcode/self-oss-instruct-sc2-concepts
import csv def proc_attendees(att_file, config): """Opens the attendee list file, reads the contents and collects the desired information (currently first name, last name and email addresses) of the actual attendees into a dictionary keyed by the lowercase email address. This collection is returned. ...
bigcode/self-oss-instruct-sc2-concepts
import re def _parse_arn(arn): """ ec2) arn:aws:ec2:<REGION>:<ACCOUNT_ID>:instance/<instance-id> arn:partition:service:region:account-id:resource-id arn:partition:service:region:account-id:resource-type/resource-id arn:partition:service:region:account-id:resource-type:resource-id Returns: r...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def is_subpath(parent_path: str, child_path: str): """Return True if `child_path is a sub-path of `parent_path` :param parent_path: :param child_path: :return: """ return Path(parent_path) in Path(child_path).parents
bigcode/self-oss-instruct-sc2-concepts
def getIPaddr(prefix): """ Get the IP address of the client, by grocking the .html report. """ addr="Unknown" f=open(prefix+".html", "r") for l in f: w=l.split(" ") if w[0] == "Target:": addr=w[2].lstrip("(").rstrip(")") break f.close() return(addr...
bigcode/self-oss-instruct-sc2-concepts
import re def clean_text(text, max_words=None, stopwords=None): """ Remove stopwords, punctuation, and numbers from text. Args: text: article text max_words: number of words to keep after processing if None, include all words stopwords: a list of words to skip d...
bigcode/self-oss-instruct-sc2-concepts
def array_value(postiion, arr): """Returns the value at an array from the tuple""" row, col = postiion[0], postiion[1] value = arr[row, col] return value
bigcode/self-oss-instruct-sc2-concepts