seed
stringlengths
1
14k
source
stringclasses
2 values
def create_quarterly_schedule_details(api, api_exception, day): """ Creates a ScheduleDetails object for use with a scheduled task for quarterly execution (every 3 months). :param api: The Deep Security API modules. :param api_exception: The Deep Security API exception module. :param day: The day of th...
bigcode/self-oss-instruct-sc2-concepts
def getNumOrRowsForGrid(num_of_cols_for_rgb_grid, rgb_list): """ This is to get a number of rows using a predetermined number of columns. This is to ensure that the images form a grid, so that multiple rgb images can be viewed at once. Args: num_of_cols_for_rgb_grid(integer): The number of co...
bigcode/self-oss-instruct-sc2-concepts
def do_nothing(df, inputs): """ Does absolutely nothing. """ return df
bigcode/self-oss-instruct-sc2-concepts
def bfs_path(ADT,start,end): """Breadth First Search to find the path from start to end""" #create a queue with rule of first-in-first-out queue=[] queue.append(start) #pred keeps track of how we get to the current vertex pred={} while queue: #keep tra...
bigcode/self-oss-instruct-sc2-concepts
import torch def NLLLoss(inputs, targets, device = 'cpu'): """ Custom Negative Log Likelihood loss that returns loss per example, rather than for the entire batch. Args: inputs : (batch_size, num_classes) *Log probabilities of each class* targets: (batch_size) *Tar...
bigcode/self-oss-instruct-sc2-concepts
def digits(n, base, alphabet=None, pad=0, big_endian=True): """ Returns `n` as a sequence of indexes into an alphabet. Parameters ---------- n : int The number to convert into a sequence of indexes. base : int The desired base of the sequence representation. The base must be ...
bigcode/self-oss-instruct-sc2-concepts
def version_param(params): """Return the value of the HTTP version parameter, or `None` if no version parameter is supplied. """ for k, v in params.items(): if k.lower() == "version": return v
bigcode/self-oss-instruct-sc2-concepts
import re def _parse_item(line): """For lines like: - Blah minor returns tuple (True, 3, 'Blah minor') for others - (False, 0, None) """ match = re.search(r'^[ ]*[*-][ ]+', line) if match is not None: ident = len(match.group(0)) return (True, ident, line[ident:]) ret...
bigcode/self-oss-instruct-sc2-concepts
def get_githost(host: str="github.com") -> str: """Returns the git host for GitHub, GitLab, BitBucket. Parameters: host (str): {("gh", "github", "github.com"), ("gl", "gitlab", "gitlab.com"), ("bb", "bitbucket", "bitbucket.org")}. (defa...
bigcode/self-oss-instruct-sc2-concepts
import yaml def parse_ic(fname): """Parse the Nalu yaml input file for the initial conditions""" with open(fname, "r") as stream: try: dat = yaml.full_load(stream) u0 = float( dat["realms"][0]["initial_conditions"][0]["value"]["velocity"][0] ) ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def format_location_name(location: Dict): """Returns a string with a combination of venue name, city and state, depending on what information is available""" if not location: return None if "venue" not in location and "city" not in location and "state" not in location...
bigcode/self-oss-instruct-sc2-concepts
def mean_of_first_n_matches(df, var, n): """Computes for each player the mean of variable var for the first n matches and returns means as a list""" players = df.groupby('account_id', sort=False) means = players.apply(lambda x: x[var].head(n).mean()).tolist() return means
bigcode/self-oss-instruct-sc2-concepts
import itertools def possible_pairs(s, mirrors=True): """Return possible pairs from a set of values. Assume `s = ['a', 'b']`. Then return examples for the following calls are: * `possible_pairs(s)` returns `[('a', 'b'), ('b', 'a')]` * `possible_pairs(s, mirros=False)` returns `[('a', 'b')]` ...
bigcode/self-oss-instruct-sc2-concepts
def read_token_file(filename): """ Read a token file and return the oauth token and oauth token secret. """ with open(filename) as f: return f.readline().strip(), f.readline().strip()
bigcode/self-oss-instruct-sc2-concepts
def string_to_int(value): """Converts a string to an integer Args: value(str): string to convert Return: The integer representation of the nummber. Fractions are truncated. Invalid values return None """ ival = None try: ival = float(value) ival = int(ival) e...
bigcode/self-oss-instruct-sc2-concepts
def find_cell (nb, cell_name): """ find a named cell within a notebook """ for cell in nb.cells: if ("name" in cell.metadata) and (cell.metadata["name"] == cell_name): return nb.cells.index(cell), cell return None, None
bigcode/self-oss-instruct-sc2-concepts
from functools import reduce def convex_hull(points): """ Returns points on convex hull in counterclockwise order according to Graham's scan algorithm. Reference: https://gist.github.com/arthur-e/5cf52962341310f438e96c1f3c3398b8 .. note:: This implementation only works in 2-dimensional space. :para...
bigcode/self-oss-instruct-sc2-concepts
def prod_in_offsets( backend, offsets, content, mask_rows=None, mask_content=None, dtype=None ): """Summary >>> j = awkward.fromiter([[1.0, 2.0],[3.0, 4.0, 5.0], [6.0, 7.0], [8.0]]) >>> mr = numpy.array([True, True, True, False]) # Disable the last event ([8.0]) >>> mc = numpy.array([True, True, Tr...
bigcode/self-oss-instruct-sc2-concepts
from typing import OrderedDict def skip_nan_tracks(tracks): """Filter tracks Args: tracks: dictionary or OrderedDict of arrays with ndim >=2 and same second dimension Returns: OrderedDict of tracks """ if tracks is None: return tracks if isinstance(tracks, OrderedDict): ...
bigcode/self-oss-instruct-sc2-concepts
def delete_file_nokia_sros(ssh_conn, dest_file_system, dest_file): """Delete a remote file for a Nokia SR OS device.""" full_file_name = "{}/{}".format(dest_file_system, dest_file) cmd = "file delete {} force".format(full_file_name) cmd_prefix = "" if "@" in ssh_conn.base_prompt: cmd_prefix ...
bigcode/self-oss-instruct-sc2-concepts
def winCheck(board, marker): """ Check if someone win """ # check lignes return((board[1] == board[2] == board[3] == marker) or (board[4] == board[5] == board[6] == marker) or (board[7] == board[8] == board[9] == marker) or # check cols (board[1] == board[4] == board[7] == marker) o...
bigcode/self-oss-instruct-sc2-concepts
def list_to_dict(l): """Convert list to dict.""" return {k: v for k, v in (x.split("=") for x in l)}
bigcode/self-oss-instruct-sc2-concepts
def sql_compile(dialect, statement, incl_literal_binds=True): """Compile a statement for the given dialect.""" return statement.compile( dialect=dialect, compile_kwargs={'literal_binds': True} if incl_literal_binds else {} )
bigcode/self-oss-instruct-sc2-concepts
def is_string(s): """Check if the argument is a string.""" return isinstance(s, str)
bigcode/self-oss-instruct-sc2-concepts
def find(predicate, iterable, default=None): """Return the first item matching `predicate` in `iterable`, or `default` if no match. If you need all matching items, just use the builtin `filter` or a comprehension; this is a convenience utility to get the first match only. """ return next(filter(pre...
bigcode/self-oss-instruct-sc2-concepts
def check_image_counter(name): """ Note: This method is only ever entered if there actually is a name as well as there will never be a .fits at the end. Pre: Takes in an image name as a string and sees if the standard iterator is on the end of the image name. Post: Returns a boolean of whether t...
bigcode/self-oss-instruct-sc2-concepts
def truncate_string(string, length=80, title=True): """ Returns a truncated string with '..' at the end if it is longer than the length parameter. If the title param is true a span with the original string as title (for mouse over) is added. """ if string is None: return '' # pragma: no cov...
bigcode/self-oss-instruct-sc2-concepts
def gen_data_dict(data, columns): """Fill expected data tuple based on columns list """ return tuple(data.get(attr, '') for attr in columns)
bigcode/self-oss-instruct-sc2-concepts
def validToken(token): """ Return True if token is in hex and is 64 characters long, False otherwise """ if len(token) != 64: return False try: token.decode("hex") except TypeError: return False return True
bigcode/self-oss-instruct-sc2-concepts
def ip_to_num(ip): """ Convert an IP string to a number value. :param ip: IP string to convert :return: A number representation of the IP address """ s = ip[0].split(".") return int(s[0]) << 24 | int(s[1]) << 16 | int(s[2]) << 8 | int(s[3])
bigcode/self-oss-instruct-sc2-concepts
def strip_rule(line): """ Sanitize a rule string provided before writing it to the output hosts file. Some sources put comments around their rules, for accuracy we need to strip them the comments are preserved in the output hosts file. Parameters ---------- line : str The rule prov...
bigcode/self-oss-instruct-sc2-concepts
def get_key(dictionary, field): """Gets an key of an dictionary dynamically from a name""" return dictionary[field]
bigcode/self-oss-instruct-sc2-concepts
import math def calculate_sum(*pairs): """ Computes a derived estimate and its MOE for the aggregation of all the arguments. Args: pairs (list): a list of two-item sequences with a U.S. Census bureau count estimate and its margin of error. Returns: A two-item sequence...
bigcode/self-oss-instruct-sc2-concepts
def val(section, key): """ Return value of section[key] in units specified in configspec Args: section (:class:`qcobj.qconfigobj.QConfigObj`.Section`): instance key (string): valid key for `section` Returns: values in section[key] converted to units defined in c...
bigcode/self-oss-instruct-sc2-concepts
from io import StringIO def print_elastic_ips(ec2, region): """ Print a list of UN-attached Elastic IP addresses :param ec2: The boto3 ec2 client :param region: The region to search in :return: The nicely formatted list of EIPs to print """ addresses_dict = ec2.describe_addresses() fo...
bigcode/self-oss-instruct-sc2-concepts
def remove_invalid_attributes(obj, data): """ remove the attributes of a dictionary that do not belong in an object """ _data = {} for name, value in data.items(): if hasattr(obj, name): _data[name] = value return _data
bigcode/self-oss-instruct-sc2-concepts
import csv def split_csv_size(csv_file, size, folder, keepheader=True): """[Split a large csv file into small csv files with certain rows in each small csv file] Arguments: csv_file {[Path]} -- [the Path object for the large csv file to split] size {[int]} -- [number of observations in ea...
bigcode/self-oss-instruct-sc2-concepts
def get_key_paths(data_dict, keys_to_consider=None, keys_not_to_consider=None, root_path=None): """ Example: get_key_paths({ 'a' : { 'b': 1 }, 'c' : 2 }) returns: ['a.b', 'c'] :param data_dict: (Nest...
bigcode/self-oss-instruct-sc2-concepts
def loadrepr(reprstr): """Returns an instance of the object from the object's repr() string. It involves the dynamic specification of code. >>> obj = loadrepr('datetime/datetime.datetime.now()') >>> obj.__class__.__name__ 'datetime' """ module, evalstr = reprstr.split('/') mylocals = l...
bigcode/self-oss-instruct-sc2-concepts
def _get_axis_num(nrow, row, col): """ computes axis number Parameters ---------- nrow : int number of rows row : int row number col : int column number """ return (nrow * row + col) + 1
bigcode/self-oss-instruct-sc2-concepts
import pytz from datetime import datetime def is_it_june() -> bool: """ determines if it is currently June in Madison, Wisconsin Returns: True if it is June, False otherwise """ tz = pytz.timezone("US/Central") the_now = datetime.now(tz) return datetime.date(the_now).month == 6
bigcode/self-oss-instruct-sc2-concepts
def avp_from_rhmin_rhmax(svp_temperature_min, svp_temperature_max, relative_humidity_min, rh_max): """ Estimate actual vapour pressure (*ea*) from saturation vapour pressure and relative humidity. Based on FAO equation 17 in Allen et al (1998). :param svp_temperature_min: Saturation vapour pressur...
bigcode/self-oss-instruct-sc2-concepts
def cut_and_paste_segment(seq, start, end, new_start): """Move a subsequence by "diff" nucleotides the left or the right.""" sub = seq[start:end] diff = new_start - start if diff > 0: return seq[:start] + seq[end : end + diff] + sub + seq[end + diff :] else: return seq[: start + diff...
bigcode/self-oss-instruct-sc2-concepts
def get_n_document_from_yaml(yaml_generator, index=0): """ Returns n document from yaml generator loaded by load_yaml with multi_document = True. Args: yaml_generator (generator): Generator from yaml.safe_load_all index (int): Index of document to return. (0 - 1st, 1 - 2nd document) ...
bigcode/self-oss-instruct-sc2-concepts
def typedvalue(value): """ Convert value to number whenever possible, return same value otherwise. >>> typedvalue('3') 3 >>> typedvalue('3.0') 3.0 >>> typedvalue('foobar') 'foobar' """ try: return int(value) except ValueError: pass try: retu...
bigcode/self-oss-instruct-sc2-concepts
import random def generate_hex_colour(ex_prop: float = 10.0) -> str: """ Generates a random hex color sampled from a partitioned color space Args: ex_prop (float): Head & tail-end proportions to exclude from sampling. This is to make sure that the generated colours are of a certain ...
bigcode/self-oss-instruct-sc2-concepts
def herfindahl_hirschman_index(distribution): """Herfindahl–Hirschman Index Args: distribution (list): wealth distribution in the market Returns: (float): Herfindahl–Hirschman Index (HHI), market concentration degree 0 <= HHI < 1, HHI = 0, perfectly competitive ...
bigcode/self-oss-instruct-sc2-concepts
def values_to_string(input_values): """Method that takes a list of values and converts them to a '|'-delimted string""" token_list = [] for value in input_values: token_list.append(str(value)) return '|'.join(token_list)
bigcode/self-oss-instruct-sc2-concepts
def get_user_dict(profile_dict): """Collect parameters required for creating users.""" return {k: profile_dict[k] for k in ('email', 'first_name', 'last_name', 'institution')}
bigcode/self-oss-instruct-sc2-concepts
def pretty_list(the_list, conjunction = "and", none_string = "nothing"): """ Returns a grammatically correct string representing the given list. For example... >>> pretty_list(["John", "Bill", "Stacy"]) "John, Bill, and Stacy" >>> pretty_list(["Bill", "Jorgan"], "or") "Bill or Jorgan" >...
bigcode/self-oss-instruct-sc2-concepts
def clear_sentences(data): """ Cleaning sentences, removing special characters and articles """ sentences = list() for record in data: sentence = record['reviewText'] sentence = sentence.lower() for char in "?.!/;:,": sentence = sentence.replace(char, '') ...
bigcode/self-oss-instruct-sc2-concepts
def _engprop(l): # {{{1 """Return the engineering properties as a LaTeX table in the form of a list of lines.""" lines = [ " \\midrule", " \\multicolumn{6}{c}{\\small\\textbf{Engineering properties}}\\\\[0.1em]", " \\multicolumn{3}{c}{\\small\\textbf{In-plane}} & ", ...
bigcode/self-oss-instruct-sc2-concepts
def space_tokenize_with_bow(sentence): """Add <w> markers to ensure word-boundary alignment.""" return ["<w>" + t for t in sentence.split()]
bigcode/self-oss-instruct-sc2-concepts
import collections def _common_observations(physics): """Returns the observations common to all tasks.""" obs = collections.OrderedDict() obs['egocentric_state'] = physics.egocentric_state() obs['torso_velocity'] = physics.torso_velocity() obs['torso_upright'] = physics.torso_upright() obs['imu'] = physic...
bigcode/self-oss-instruct-sc2-concepts
def chunk_generator(l, batch_size): """ Given any list and a batch size, returns a list of lists where each element is a list containing N (BATCH_SIZE) elements. ----------------------------------------------------------- :param l: a 1-D list batch_size: Batch size of a chunk ---...
bigcode/self-oss-instruct-sc2-concepts
def extract_literal_string(memory,address,ztext): """ Extract the literal string from the given memory/address and return the new address + string """ zchar_start_address = address text, next_address = ztext.to_ascii(memory,zchar_start_address,0) return next_address,text
bigcode/self-oss-instruct-sc2-concepts
def wrap_image(img_path, trailing_br=False, **kwargs): """Return a <img> markup, linking to the image in a URL""" _width = kwargs.get('width', '') _style = kwargs.get('style', '') if _style != '': _style = ' style="' + _style + '"' if str(_width) != '' : _width = ' width='+str(_wid...
bigcode/self-oss-instruct-sc2-concepts
def _generate_barcode_ids(info_iter): """Create unique barcode IDs assigned to sequences """ bc_type = "SampleSheet" barcodes = list(set([x[-1] for x in info_iter])) barcodes.sort() barcode_ids = {} for i, bc in enumerate(barcodes): barcode_ids[bc] = (bc_type, i+1) return barcode...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Any from typing import Optional def find_namespace( namespace: str, discovery_map_data: Dict[str, Any], ) -> Optional[Dict[str, Any]]: """Find the service-colors list for the given namespace.""" for namespace_obj in discovery_map_data['namespaces']: ...
bigcode/self-oss-instruct-sc2-concepts
def find_test_index(test, selected_tests, find_last_index=False): """Find the index of the first or last occurrence of a given test/test module in the list of selected tests. This function is used to determine the indices when slicing the list of selected tests when ``options.first``(:attr:`find_last_index...
bigcode/self-oss-instruct-sc2-concepts
def add_mpos_2site(mpo1, mpo2): """Sum of two 2-site MPOs acting on the same pair of sites. """ return (mpo1[0] + mpo2[0], mpo1[1] + mpo2[1])
bigcode/self-oss-instruct-sc2-concepts
def calc_J(df_clust): """Calculate the total angular momentum of the cluster:: N J = Σ r_i × m_i * v_i i=1 :param df_clust: cluster data - position, velocity, and mass :type df_clust: pyspark.sql.DataFrame, with schema schemas.clust :returns: J, broken into components ...
bigcode/self-oss-instruct-sc2-concepts
def levi_civita(tup): """Compute an entry of the Levi-Civita tensor for the indices *tuple*.""" if len(tup) == 2: i, j = tup return j-i if len(tup) == 3: i, j, k = tup return (j-i)*(k-i)*(k-j)/2 else: raise NotImplementedError
bigcode/self-oss-instruct-sc2-concepts
def triangleType(x, y, z): """ Determine if the triangle is valid given the length of each side x,y,z. :param x: First side of triangle :param y: Second side of triangle :param z: Third side of triangle :returns: Whether a triangle is an 'Equilateral Triangle', 'Isosceles Tria...
bigcode/self-oss-instruct-sc2-concepts
def to_bin_centers(x): """ Convert array edges to centers """ return 0.5 * (x[1:] + x[:-1])
bigcode/self-oss-instruct-sc2-concepts
from typing import Any import json def json_pretty_print(parsed: Any) -> str: """ Pretty print a json object. :param parsed: a json object :return: a prettified json object """ if isinstance(parsed, str): parsed = json.loads(parsed) # `ret = pprint.pformat(parsed) ret = json.d...
bigcode/self-oss-instruct-sc2-concepts
def isinteger(number): """ This method decides if a given floating point number is an integer or not -- so only 0s after the decimal point. For example 1.0 is an integer 1.0002 is not.""" return number % 1 == 0
bigcode/self-oss-instruct-sc2-concepts
def _int_to_bin_str(value): """ This function returns the integer value in binary string of length 16. :param value: integer value to be converted to binary string. :return: None if 0 > value > 2^16-1 """ if 0 < value < (2**16): bits = bin(value)[2:] return ('0'*16)[len(bits):] +...
bigcode/self-oss-instruct-sc2-concepts
def _median3(comparables, lo, mid, hi): """Sort the three elements of an array in ascending order in place and return the middle index Arguments: comparables -- an array of which the elements can be compared lo -- index 1 (inclusive) mid -- index 2 (inclusive) hi -- index 3 (inclus...
bigcode/self-oss-instruct-sc2-concepts
import pytz def _make_timezone_naive_utc(datetime_object): """ If a given datetime is timezone-aware, convert to UTC and make timezone=naive """ if (datetime_object.tzinfo is not None) and (datetime_object.tzinfo.utcoffset(datetime_object) is not None): # Convert to UTC utc_time = datetime_ob...
bigcode/self-oss-instruct-sc2-concepts
import logging def aggregate_metrics(raw_metrics, default_strategies, metric_strategies=None): """Aggregate raw TensorBoard metrics according to collection config. Available aggregation strategies: `final`, `min`, `max`. Args: raw_metrics: dict mapping TensorBoard tags to list of MetricPoint. default_...
bigcode/self-oss-instruct-sc2-concepts
def create_n_ride_data(size): """Create n ride request and return as a list""" ride_data = [] for i in range(size): ride_data.append({ "start_location": "Start from here%d" % i, "end_location": "End here%d" % i, }) return ride_data
bigcode/self-oss-instruct-sc2-concepts
def hmsm_to_days(hour=0, min=0, sec=0, micro=0): """ Convert hours, minutes, seconds, and microseconds to fractional days. """ days = sec + (micro / 1.e6) days = min + (days / 60.) days = hour + (days / 60.) return days / 24.
bigcode/self-oss-instruct-sc2-concepts
def get_probe_2(table_name='filtered_links_dated'): """Create SQL query to select repo_id, linked_repo_id, and created_at from table_name.""" inputs = (table_name,) qry = "SELECT repo_id, linked_repo_id, created_at FROM %s" return qry, inputs
bigcode/self-oss-instruct-sc2-concepts
def init_bitstring_groundstate(occ_num: int) -> int: """Occupy the n lowest orbitals of a state in the bitstring representation Args: occ_num (integer): number of orbitals to occupy Returns: (integer): bitstring representation of the ground state """ return (1 << occ_num) - 1
bigcode/self-oss-instruct-sc2-concepts
def is_name_private(name, public=None): """ Answers whether the name is considered private, by checking the leading underscore. A ist of public names can be provided which would override the normal check """ if public and name in public: return False return name.startswith('_')
bigcode/self-oss-instruct-sc2-concepts
def get_str(db,name): """ Get a string from the redis database. """ data_unicode = db.get(name) return str(data_unicode)
bigcode/self-oss-instruct-sc2-concepts
def mask(arr,pixels,val=0): """Mask an array arr based on array pixels of (y,x) pixel coordinates of (Npix,2)""" arr[...,pixels[:,0],pixels[:,1]] = val return arr
bigcode/self-oss-instruct-sc2-concepts
import logging def INFO(target): """A decorator to set the .loglevel attribute to logging.INFO. Can apply to either a TestCase or an individual test method.""" target.loglevel = logging.INFO return target
bigcode/self-oss-instruct-sc2-concepts
def dict_apply_listfun(dict, function): """Applies a function that transforms one list to another with the same number of elements to the values in a dictionary, returning a new dictionary with the same keys as the input dictionary, but the values given by the results of the function acting on the input dictionary...
bigcode/self-oss-instruct-sc2-concepts
def file_names(inp_fname): """Return the linkname and filename for dotfile based on user input. """ link = inp_fname if inp_fname.startswith('.') else ".{}".format(inp_fname) return link, "dot{}.symlink".format(link)
bigcode/self-oss-instruct-sc2-concepts
def create_dict(key_list, val_list): """ The function creates dictionary from given key_list and value_list :param key_list: :param val_list: :return: Dictionary of type (key:val) """ temp_dict = {} for arg in range(len(key_list) - 1): temp_dict[key_list[arg]] = val_list[arg] ...
bigcode/self-oss-instruct-sc2-concepts
import torch def krylov(L, A, b): """ Compute the Krylov matrix (b, Ab, A^2b, ...) using the squaring trick. """ x = b.unsqueeze(-1) # (..., N, 1) A_ = A done = L == 1 while not done: # Save memory on last iteration l = x.shape[-1] if L - l <= l: done = True ...
bigcode/self-oss-instruct-sc2-concepts
def miles2km(miles): """ Converts miles to kilometers. Args: miles: A distance in miles. Returns: The equivalent distance in kilometers. """ return miles*1.60934
bigcode/self-oss-instruct-sc2-concepts
def file2list(filename): """Load text file and dump contents into a list""" listOfFiles = open( filename,'r').readlines() listOfFiles = [i.rstrip('\n') for i in listOfFiles if not i.startswith("#")] return listOfFiles
bigcode/self-oss-instruct-sc2-concepts
import torch def optimizer_to(optimizer, device="cpu"): """ Transfer the given optimizer to device """ for param in optimizer.state.values(): if isinstance(param, torch.Tensor): param.data = param.data.to(device) if param._grad is not None: param._grad.d...
bigcode/self-oss-instruct-sc2-concepts
def append(base, suffix): """Append a suffix to a string""" return f"{base}{suffix}"
bigcode/self-oss-instruct-sc2-concepts
import textwrap def _wrap_text(text): """ Wrap text at given width using textwrap module. Indent should consist of spaces. Its length is deducted from wrap width to ensure exact wrapping. """ wrap_max = 80 indent = ' ' wrap_width = wrap_max - len(indent) return textwrap.fill(text, w...
bigcode/self-oss-instruct-sc2-concepts
def read_txt_file(fname): """ read a txt file, each line is read as a separate element in the returned list""" return open(fname).read().splitlines()
bigcode/self-oss-instruct-sc2-concepts
def RK4(f, y_i, t_i, dt): """Performs Runge-Kutta integration. Parameters ---------- f : callable Derivative function. y_i : ndarray Current state. t_i : float Current time. dt : float Time step. Returns ------- y_j : ndarray State at ...
bigcode/self-oss-instruct-sc2-concepts
import requests from bs4 import BeautifulSoup def scrape_url(url): """ Scrap the content from the input URL using Beautiful Soup. """ # Retrieve the data using a request r = requests.get(url) # Get the content in HTML format html = r.text # Parse the HTML file with BS4 soup = Be...
bigcode/self-oss-instruct-sc2-concepts
import random def random_num_generator(length, repeatable=False): """ Generate a number in specific length. If repeatable is true, the number in different position can be the same one. :type length: int :param length: the length of the number :type repeatable: boolean :param repeatable: ...
bigcode/self-oss-instruct-sc2-concepts
import math def calculate_open_channel_flow(channel, water_level_outside, water_level_inside): """ This functions calculates discharge past a barrier in case it is connected through an open channel :param channel: connecting body of water between outside water level and inside water level :param wate...
bigcode/self-oss-instruct-sc2-concepts
def get_label_mapped_to_positive_belief(query_result): """Return a dictionary mapping each label_id to the probability of the label being True.""" return {label_id: belief[1] for label_id, belief in query_result.items()}
bigcode/self-oss-instruct-sc2-concepts
def load_sentences(file, skip_first=True, single_sentence=False): """ Loads sentences into process-friendly format for a given file path. Inputs ------------------- file - str or pathlib.Path. The file path which needs to be processed skip_first - bool. If True, skips the first line. sin...
bigcode/self-oss-instruct-sc2-concepts
import base64 def base64url_decode(data): """ base64-decodes its input, using the modified URL-safe alphabet given in RFC 4648. """ return base64.b64decode(bytes(data, encoding='ASCII'), altchars='-_')
bigcode/self-oss-instruct-sc2-concepts
import re def ends_with_blank_line(contents): """ Returns true if the given string ends with a line that is either empty or only composed of whitespace. """ return re.search('\n\s*\n\Z', contents) is not None
bigcode/self-oss-instruct-sc2-concepts
def get_native_ranges(my_core, meshset, entity_types): """ Get a dictionary with MOAB ranges for each of the requested entity types inputs ------ my_core : a MOAB Core instance meshset : a MOAB meshset to query for the ranges of entities entity_types : a list of valid pyMOAB types to be...
bigcode/self-oss-instruct-sc2-concepts
def get_list_from_file(file_name): """read the lines from a file into a list""" with open(file_name, mode='r', encoding='utf-8') as f1: lst = f1.readlines() return lst
bigcode/self-oss-instruct-sc2-concepts
def _coerce_field_name(field_name, field_index): """ Coerce a field_name (which may be a callable) to a string. """ if callable(field_name): if field_name.__name__ == '<lambda>': return 'lambda' + str(field_index) else: return field_name.__name__ return field_...
bigcode/self-oss-instruct-sc2-concepts