seed
stringlengths
1
14k
source
stringclasses
2 values
def groupIntersections(intersections: list, key: int) -> dict: """ Function to group horizontal or vertical intersections Groups horizontal or vertical intersections as a list into a dict by the given key Parameters: intersections (list): List of tuples representing intersection points key (int): Tu...
bigcode/self-oss-instruct-sc2-concepts
from unittest.mock import Mock def get_output_string(patch_obj: Mock) -> str: """Helper function to get text pathed to output.""" return patch_obj["output_path"].write.call_args[0][0].strip()
bigcode/self-oss-instruct-sc2-concepts
def remove_padding(im, pad=0): """ Function for removing padding from an image :param im: image or prob map to remove padding from :param pad: number of pixels of padding to remove :return: """ if pad == 0: return im else: return im[pad:-pad, pad:-pad]
bigcode/self-oss-instruct-sc2-concepts
import hashlib def get_md5_tmp(path): """ return the md5 sum of the path. if the path is a temporary directory, the md5 is prefixed with "tmp_" """ m = hashlib.md5() m.update(path) if path.__contains__("temp") or path.__contains__("tmp"): return "tmp_%r" % m.hexdigest() ...
bigcode/self-oss-instruct-sc2-concepts
def main(argv): """Main entry point of the program""" print("This is a boilerplate") ## NOTE: indented using two tabs or 4 species return 0
bigcode/self-oss-instruct-sc2-concepts
def parse_tags(tagset): """Convert the tagset as returned by AWS into a normal dict of {"tagkey": "tagvalue"}""" output = {} for tag in tagset: # aws is inconsistent with tags sometimes they use caps and sometimes not if 'Key' in tag: output[tag['Key']] = tag['Value'] if ...
bigcode/self-oss-instruct-sc2-concepts
def convert(vertical_lists): """rotate a given list of lists converts a list as if it was a matrix interchanges 'row' and 'columns' Args: vertical_lists: list of lists to be rotated Returns: list: list of lists contains the same elements as original except t...
bigcode/self-oss-instruct-sc2-concepts
def pad_hexdigest(s, n): """Pad a hex string with leading zeroes Arguments: s (str): input hex string n (int): number of expected characters in hex string Returns: (str): hex string padded with leading zeroes, such that its length is n """ return "0" * (n - len(s)) + ...
bigcode/self-oss-instruct-sc2-concepts
import json def catch_json_error(blob, filepath, **kwargs): """Wrapper to provide better error message for JSON reads""" try: parsed = json.loads(blob, **kwargs) except ValueError as e: raise ValueError("JSON error reading {}: {}!".format(filepath, ...
bigcode/self-oss-instruct-sc2-concepts
def is_oauth_configured(ta_tabs): """ Check if oauth is configured in globalConfig.json. Args: ta_tabs (list): List of tabs mentioned in globalConfig.json. Returns: bool: True if oauth is configured, False otherwise. """ for tab in ta_tabs: if tab["name"] == "account":...
bigcode/self-oss-instruct-sc2-concepts
def translate(curve): """ P.translate(numpy.ndarray) -> numpy.ndarray Take a three dimensional curve defined by a numpy ndarray and translate that curve so that the mean of each of spatial componenets lies at the origin. """ try: return curve - sum(curve)/curve.shape[0] exce...
bigcode/self-oss-instruct-sc2-concepts
def get_last_insert_id(dict_cursor): """ return the last inserted id by this client/connection. see also https://dev.mysql.com/doc/refman/5.7/en/mysql-insert-id.html """ dict_cursor.execute('select last_insert_id() as id') return dict_cursor.fetchone()['id']
bigcode/self-oss-instruct-sc2-concepts
def full_invoiceitem(faker): """Returns a dict for an `InvoiceItem`.""" full_item_dict = { "service": "Some Material", "qty": 5.0, "unit_price": 12.3, "vat": 19.0, "description": faker.sentence(nb_words=5), } return full_item_dict
bigcode/self-oss-instruct-sc2-concepts
from typing import List import inspect def _get_failing_lines(code, lineno: int) -> List[str]: """Get list of strings (lines of code) from lineno to lineno+3. Ideally we'd return the exact line where the error took place, but there are reasons why this is not possible without a lot of work, including ...
bigcode/self-oss-instruct-sc2-concepts
import json def _load_predictions_dicts(filepath): """Returns list of predictions dicts.""" predictions_dicts = json.load(open(filepath)) return predictions_dicts
bigcode/self-oss-instruct-sc2-concepts
def train_test_split(df_ml): """ Split log data into train and test by well ID """ test_wells = set(['B03', 'B05', 'B06']) train_wells = set(df_ml.HACKANAME.unique()) - test_wells print('Train well: ', train_wells) print('Test wells: ', test_wells) mask_train = df_ml.HACKANAME.isin(train_wells...
bigcode/self-oss-instruct-sc2-concepts
def _extract_first_argument(args: tuple, kwargs: dict): """ Returns the tuple (X, _args, _kwargs) where X is the first argument ( found in either args or kwargs), and _args, _kwargs are the same (with X removed) >>> _extract_first_argument((1,2,3), {'d': 4}) (1, [2, 3], {'d': 4}) >>> _extra...
bigcode/self-oss-instruct-sc2-concepts
def simple_hello(name="you"): """Returns string with greeting.""" return "Hello {}!".format(name)
bigcode/self-oss-instruct-sc2-concepts
def parse_summary_file(summary_file): """ Parse a summary file generated by this pipeline and return the metrics as a dictionary {"metric":val} summary_file : str; the path to the summary file """ metrics = {} with open(summary_file,"r") as IN: for line in IN: contents = lin...
bigcode/self-oss-instruct-sc2-concepts
def find_shortest(array: list[int]) -> int: """ Find the shortest element in an array. find_shortest ============= The `find_shortest` function takes an array and finds the shortest element in it. Parameters ---------- array: list[int] An array/list of integers Returns ------- ...
bigcode/self-oss-instruct-sc2-concepts
def _user_keyed_dict(reader): """ create a dict of the rows of the csv, keyed by the "user" value """ return {row['user']: row for row in reader}
bigcode/self-oss-instruct-sc2-concepts
def sign(x): """Sign function. :return -1 if x < 0, else return 1 """ if x < 0: return -1 else: return 1
bigcode/self-oss-instruct-sc2-concepts
def get_results_from_dict_of_sets(list_of_elements, dict_of_sets): """ We have a list of elements that are in a dict of elements, and every element have a set with results. We want to extract the results corresponding to our elements. """ results = set() for element in list_of_elements: ...
bigcode/self-oss-instruct-sc2-concepts
def largest_factor(n): """Return the largest factor of n*n-1 that is smaller than n. >>> largest_factor(4) # n*n-1 is 15; factors are 1, 3, 5, 15 3 >>> largest_factor(9) # n*n-1 is 80; factors are 1, 2, 4, 5, 8, 10, ... 8 """ factor = n - 1 while factor > 0: if (n*n-1) % factor ...
bigcode/self-oss-instruct-sc2-concepts
def boolNot(num): """ return True if num is not 0 """ return num != 0
bigcode/self-oss-instruct-sc2-concepts
def get_mbean_name(location, existing_names, alias_helper): """ Return the mbean name for the specified location. For unpredictable single folders: 1. if an existing folder name is present, use that name as the mbean name. 2. set the location's token to the mbean name. :param location: the l...
bigcode/self-oss-instruct-sc2-concepts
def _stanza_handler(element_name, stanza_type, payload_class, payload_key, usage_restriction): """Method decorator generator for decorating <message/> or <presence/> stanza handler methods in `XMPPFeatureHandler` subclasses. :Parameters: -...
bigcode/self-oss-instruct-sc2-concepts
def get_item_from_gcp_response(key_field, key_name, items): """ Get item from GCP REST response JSON list by name. items = [{ 'key_field': 'key_name', 'key_field_value': 'value'}] :param key_field: item dictionary key :param key_value: item dictionary value :param items: list of items(dictionari...
bigcode/self-oss-instruct-sc2-concepts
import re def _FormatNameAsConstant(name): """Formats a name to be a C++ constant of the form kConstantName""" name = '%s%s' % (name[0].upper(), name[1:]) return 'k%s' % re.sub('_[a-z]', lambda m: m.group(0)[1].upper(), name.replace('.', '_'))
bigcode/self-oss-instruct-sc2-concepts
def is_boxcar(die1, die2): """Return true if face values of die total 12.""" BOXCARS = 12 return True if (die1 + die2 == BOXCARS) else False
bigcode/self-oss-instruct-sc2-concepts
def is_a_conv_layer_label(layer_label): """ Returns true if a convolutional layer. """ return 'conv' in layer_label or 'res' in layer_label
bigcode/self-oss-instruct-sc2-concepts
import math import random def randint_sample(min, max, size): """ Generate sample of random integers number inclusively """ width = max - min + 1 return [math.floor(random.random() * width + min) for _ in range(size)]
bigcode/self-oss-instruct-sc2-concepts
import typing import pathlib def is_path_obj(obj: typing.Any) -> bool: """Is given object ``obj`` a pathlib.Path object? """ return isinstance(obj, pathlib.Path)
bigcode/self-oss-instruct-sc2-concepts
def table_to_csv(table_name): """ DESCRIPTION: Turn table name into filename, i.e., add .csv INPUT: table name (filename without extension) OUTPUT: filename (with extension) """ csv_filename = str(table_name) + '.csv' return csv_filename
bigcode/self-oss-instruct-sc2-concepts
def __isInBounds(x: int, y: int, nRows: int, nCols: int) -> bool: """ Check if x and y is within bounds """ return (x >= 1 and x <= nCols and y >= 1 and y <= nRows)
bigcode/self-oss-instruct-sc2-concepts
import unicodedata def is_wide(char): """is_wide(unicode_char) -> boolean Return True if unicode_char is Fullwidth or Wide, False otherwise. Fullwidth and Wide CJK chars are double-width. """ return unicodedata.east_asian_width(char) in ("F", "W")
bigcode/self-oss-instruct-sc2-concepts
def vrh(kclay, kqtz, vclay): """ Voigt-Reuss-Hill average to find Kmatrix from clay and qtz components. From Smith et al, Geophysics 68(2), 2003. Works for any two components. Args: kclay (float): K_clay. kqtz (float): K_quartz. vclay (float): V_clay. Returns: ...
bigcode/self-oss-instruct-sc2-concepts
def efd_name(csc, topic): """Get a fully qualified EFD topic name. Parameters ---------- csc : str The name of the CSC. topic : str The name of the topic. """ return f"lsst.sal.{csc}.{topic}"
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def month_start(src_time): """Return the beginning of the month of the specified datetime""" return datetime(src_time.year, src_time.month, 1)
bigcode/self-oss-instruct-sc2-concepts
import string def base62_encode(num: int) -> str: """ Encode a positive number using 62 characters 0-1a-zA-Z """ charset = string.digits + string.ascii_letters size = len(charset) result = '' while True: num, rem = num // size, num % size result += charset[rem] if n...
bigcode/self-oss-instruct-sc2-concepts
import re def extract_path(path_string): """Convert a path string to a list of names""" return re.findall(r"[^/\\]+", path_string)
bigcode/self-oss-instruct-sc2-concepts
def defaultTransformation(mol): """ defaultTransformation() returns the mol it receives as parameter. For testing, corrsponds to a .sdf copy action without any molecule transformation """ return mol
bigcode/self-oss-instruct-sc2-concepts
from typing import List import re def parse_csv(text: str) -> List[str]: """Parse comma separated **double quoted** strings in behave steps Args: text: double quoted comma separated string Returns: List of string tokens """ return re.findall(r"\"(.+?)\"\s*,?", text)
bigcode/self-oss-instruct-sc2-concepts
import torch from typing import cast import warnings def predict_segmentation( logits: torch.Tensor, mutually_exclusive: bool = False, threshold: float = 0.0 ) -> torch.Tensor: """ Given the logits from a network, computing the segmentation by thresholding all values above 0 if multi-labels task, comp...
bigcode/self-oss-instruct-sc2-concepts
def _GetMetaDict(items, key, value): """Gets the dict in items that contains key==value. A metadict object is a list of dicts of the form: [ {key: value-1, ...}, {key: value-2, ...}, ... ] Args: items: A list of dicts. key: The dict key name. value: The dict key value. R...
bigcode/self-oss-instruct-sc2-concepts
import math def round_down_to_multiplicity(multiplicity: int, num: int): """ Function to round a number to the nearest multiplicity given the multiplicity :param multiplicity: multiplicity for rounding :param num: input number to be rounded :return: number rounded down to nearest multiplicity ...
bigcode/self-oss-instruct-sc2-concepts
import six def sort_db_results(results): """Deterministically sort DB results. Args: results: List[Dict], results from a DB. Returns: List[Dict], sorted DB results. """ sort_order = [] if len(results) > 0: sort_order = sorted(six.iterkeys(results[0])) def sort_ke...
bigcode/self-oss-instruct-sc2-concepts
def Add(xs, **unused_kwargs): """Adds two tensors.""" return xs[0] + xs[1]
bigcode/self-oss-instruct-sc2-concepts
def create_row(size): """Returns a single, empty row with the given size. Each empty spot is represented by the string '-'. >>> create_row(5) ['-', '-', '-', '-', '-'] """ return ['-' for i in range(size)]
bigcode/self-oss-instruct-sc2-concepts
def has_valid_token(client): """Does the session have a valid token?""" return client.authorized
bigcode/self-oss-instruct-sc2-concepts
import re def get_version(string): """ Retrieve the ``__version__`` attribute for Layabout. """ flags = re.S pattern = r".*__version__ = '(.*?)'" match = re.match(pattern=pattern, string=string, flags=flags) if match: return match.group(1) raise RuntimeError('No version string could ...
bigcode/self-oss-instruct-sc2-concepts
def unpack_string_from(data, offset=0): """Unpacks a zero terminated string from the given offset in the data""" result = "" while data[offset] != 0: result += chr(data[offset]) offset += 1 return result
bigcode/self-oss-instruct-sc2-concepts
def code() -> str: """ Example G-code module, an arrow. Please simulate first, before milling. """ return (""" G91 G0 X0 Y2 G0 X0 Y-4 G0 X0 Y2 G0 X-20 Y0 G0 X40 Y0 G0 X-5 Y-5 G0 X5 Y5 G0 X-5 Y5 G0 X5 Y-5 """)
bigcode/self-oss-instruct-sc2-concepts
def to_capital(word: str): """ Make the 'word' parameter capitalized :param word: string to be capitalized :return: capitalized string """ return word.capitalize()
bigcode/self-oss-instruct-sc2-concepts
def get_count_and_move(s: str, pos: list) -> int: """ Extract a repeat {count} from s[pos[0]:] Args: s (str): the string to extract from. pos (list): pos[0] points to the next char in s to start extracting. Returns: int: the repeat count that was extracted. pos[0]: sinc...
bigcode/self-oss-instruct-sc2-concepts
def listwise_delete(data, inplace=False, verbose=False): """Delete all rows from a DataFrame where any missing values exist. Deletion is one way to handle missing values. This method removes any records that have a missing value in any of the features. This package focuses on imputation, not deletion. ...
bigcode/self-oss-instruct-sc2-concepts
import torch def to_device(m, x): """Function to send tensor into corresponding device :param torch.nn.Module m: torch module :param torch.Tensor x: torch tensor :return: torch tensor located in the same place as torch module :rtype: torch.Tensor """ assert isinstance(m, torch.nn.Module) ...
bigcode/self-oss-instruct-sc2-concepts
def naorthreshold(lmbda, mu, costofbalking): """ Function to return Naor's threshold for optimal behaviour in an M/M/1 queue. This is taken from Naor's 1969 paper: 'The regulation of queue size by Levying Tolls' Arguments: lmbda - arrival rate (float) mu - service rate (float) costo...
bigcode/self-oss-instruct-sc2-concepts
import torch def _tblr_pred_to_delta_xywh_pred(bbox_pred: torch.Tensor, normalizer: torch.Tensor) -> torch.Tensor: """Transform tblr format bbox prediction to delta_xywh format for ncnn. An internal function for transforming tblr format bbox prediction to delta_xywh form...
bigcode/self-oss-instruct-sc2-concepts
def get_conn_str(db_name): """Returns the connection string for the passed in database.""" return f'postgresql://postgres:postgres123@localhost:5432/{db_name}'
bigcode/self-oss-instruct-sc2-concepts
def convert_km_to_length(length): """Convert length like '1' to 1000 or '30M' to 30""" try: if length[-1:] == "M": t_length = int(length[:-1]) # Trim off the 'M' else: t_length = int(float(length) * 1000) # Convert to meters length_str = str(t_length) exc...
bigcode/self-oss-instruct-sc2-concepts
def calc_SST(X_act): """ This function returns the Sum of Square of actual values. """ return (X_act ** 2).sum()
bigcode/self-oss-instruct-sc2-concepts
def transform(addon_df, threshold, num_addons): """ Converts the locale-specific addon data in to a dictionary. :param addon_df: the locale-specific addon dataframe; :param threshold: the minimum number of addon-installs per locale; :param num_addons: requested number of recommendations. :return: a...
bigcode/self-oss-instruct-sc2-concepts
def _debian_dist_name(env): """ Determine Debian dist name (e.g. squeeze). """ return env.safe_run_output("lsb_release -a | grep Codename | cut -f 2")
bigcode/self-oss-instruct-sc2-concepts
import six def _get_exec_table_data(headers): """Extract a stats table from execution HTTP response headers. Stats include things like node name, execution time, number of reads/writes, bytes read/written, etc. :param dict headers: `dict` of response headers from a job execution request. It ...
bigcode/self-oss-instruct-sc2-concepts
import requests import logging def recently_traded(symbol): """Check if a ticker was recently traded on thetagang.com.""" url = "https://api.thetagang.com/trades" params = {"ticker": symbol} trades = requests.get(url, params=params).json()['data']['trades'] # Skip this message if nobody has trade...
bigcode/self-oss-instruct-sc2-concepts
import math def f_1(scores): """Compute the corpus-wide F1 score represented by the scores. Each score should contain four entries. Consider: - first/second entry numerator/denominator for recall, - third/fourth entry numerator and denominator for precision. Then define r = sum(first ent...
bigcode/self-oss-instruct-sc2-concepts
def sorted_values(x): """Returns the sorted values of a dictionary as a list.""" return [x[k] for k in sorted(x)]
bigcode/self-oss-instruct-sc2-concepts
def reverse_url(context, name, **parts): """ jinja2 filter for generating urls, see http://aiohttp.readthedocs.io/en/stable/web.html#reverse-url-constructing-using-named-resources Usage: {{ 'the-view-name'|url }} might become "/path/to/view" or with parts and a query {{ 'item-details...
bigcode/self-oss-instruct-sc2-concepts
import platform def getSystemBitness() -> int: """ Solution adapted from https://stackoverflow.com/questions/2208828/detect-64bit-os-windows-in-python """ machine = platform.machine() if machine.endswith('64'): return 64 else: return 32
bigcode/self-oss-instruct-sc2-concepts
def seatsInTheater(nCols, nRows, col, row): """ Given the total number of rows and columns in the theater (nRows and nCols, respectively), and the row and column you're sitting in, return the number of people who sit strictly behind you and in your column or to the left, assuming all se...
bigcode/self-oss-instruct-sc2-concepts
def prepend_license(license_text, src_text, file_extension): """Prepend a license notice to the file commented out based on the extension. Args: src_text (str): The text which will have the license prepended. file_extension (str): The relevant file extension. Returns: str: The full...
bigcode/self-oss-instruct-sc2-concepts
from typing import Any from datetime import datetime def json_encoder(obj: Any) -> Any: """json encoder function supporting datetime serialization. Args: obj: object to encode to JSON Returns: json encoded data """ if isinstance(obj, datetime): return obj.isoformat() ...
bigcode/self-oss-instruct-sc2-concepts
def declr_has_sym(declr, sym): """Check if the given declr has sym""" for existing in declr: if existing["kind"] == sym["kind"] and existing["name"] == sym["name"]: return True return False
bigcode/self-oss-instruct-sc2-concepts
def create_p_yaw_model_tf(d, gp): """ Create transfer function for fly yaw dynamics model with proportional controlller. Arguments: d = damping gp = proportional gain Returns: tf = transfer function. """ def tf(s): return gp/(s + d + gp) return tf
bigcode/self-oss-instruct-sc2-concepts
def _calculate_insertion_point(existing_knob_list, knob_point=None, insert_before=False): """Encapsulates logic on working out where to insert in a the knob list Returns an integer index which tells us where to insert. For example in list [A,B,C]: - before A is 0 - ...
bigcode/self-oss-instruct-sc2-concepts
def create_and_list(list): """ Given a list of 1 items, return item Given a list of 2 items, return item[0] and item[1] Given a list of n items, return item[0], item[1], ..., and item[-1] """ if len(list) == 1: return list[0] elif len(list) == 2: return list[0] + " and " + l...
bigcode/self-oss-instruct-sc2-concepts
def db_list_fields(con, tabel): """Return all column names for a specified table""" cursor = con.cursor() cursor.execute(f"select * from {tabel} limit 1;") return [name[0] for name in cursor.description]
bigcode/self-oss-instruct-sc2-concepts
import six def has_digit(string_or_list, sep="_"): """ Given a string or a list will return true if the last word or element is a digit. sep is used when a string is given to know what separates one word from another. """ if isinstance(string_or_list, (tuple, list)): list_length = len...
bigcode/self-oss-instruct-sc2-concepts
import re def parse_basename(bname): """return tuple (tsh, axis, ddd, hh, this_file, total_files) given basename""" # input like BXM00018.15R m = re.match('(?P<tsh>.)(?P<axis>.)(.)(?P<day>\d{3})(?P<hour>\d{2})\.(?P<this_file>\d)(?P<num_files>\d).', bname) if m: return m.group('tsh'), m.group('...
bigcode/self-oss-instruct-sc2-concepts
def check_subtraction_file_type(file_name: str) -> str: """ Get the subtraction file type based on the extension of given `file_name` :param file_name: subtraction file name :return: file type """ if file_name.endswith(".fa.gz"): return "fasta" else: return "bowtie2"
bigcode/self-oss-instruct-sc2-concepts
def get_configuration_tag(api): """ Return tag value for the configuration. :param ConfigurationAPIUserV1 api: API instance. :return: Tag as ``bytes``. """ return api.persistence_service.configuration_hash()
bigcode/self-oss-instruct-sc2-concepts
import random def yes(specifier=0): """ Decide if we should perform this action, this is just a simple way to do something I do in tests every now and again :Example: # EXAMPLE -- simple yes or no question if testdata.yes(): # do this else: # don't do i...
bigcode/self-oss-instruct-sc2-concepts
def _extended_euclidean(a, b): """Helper function that runs the extended Euclidean algorithm, which finds x and y st a * x + b * y = gcd(a, b). Used for gcd and modular division. Returns x, y, gcd(a, b)""" flip = b > a if flip: a, b = b, a if b == 0: return 1, 0, a x, y, gcd = _extended_eucl...
bigcode/self-oss-instruct-sc2-concepts
def group_aggregation(df, group_var, agg_var): """ We need to group the Auto MPG Dataset on the basis of a column. Then we have to calculate the mean of the grouped data according to another column parameters df: A dataframe containing the dataset in the form of a matri...
bigcode/self-oss-instruct-sc2-concepts
import torch def disagreement(logits_1, logits_2): """Disagreement between the predictions of two classifiers.""" preds_1 = torch.argmax(logits_1, dim=-1).type(torch.int32) preds_2 = torch.argmax(logits_2, dim=-1).type(torch.int32) return torch.mean((preds_1 != preds_2).type(torch.float32))
bigcode/self-oss-instruct-sc2-concepts
def get_formatted_place (city, country, population): """Generate the name of a place and it's population.""" place = f"{city} {country}-Population: {population}" return place.title()
bigcode/self-oss-instruct-sc2-concepts
def parse_password_file(file_name): """ parse the apache password file into usernames and passwords """ passwords = {} for line in open(file_name, 'r'): username, password = line.split(':') passwords[username] = password.strip() return passwords
bigcode/self-oss-instruct-sc2-concepts
def generate_pairs(n_rex): """Generate list of pairs that will attempt to swap configurations during replica exchange Monte Carlo. """ pairs = list(zip(range(n_rex), range(1,n_rex))) return pairs[::2], pairs[1::2]
bigcode/self-oss-instruct-sc2-concepts
from functools import reduce import operator def get_in(keys, coll, default=None, no_default=False): """ Returns coll[i0][i1]...[iX] where [i0, i1, ..., iX]==keys. If coll[i0][i1]...[iX] cannot be found, returns ``default``, unless ``no_default`` is specified, then it raises KeyError or IndexError. ...
bigcode/self-oss-instruct-sc2-concepts
def _make_equal_size(a: str, b: str): """ Make the strings a and b equal size, by right-padding with spaces the shortest string """ max_length = max(len(a), len(b)) a = a.ljust(max_length).upper() b = b.ljust(max_length).upper() return a, b
bigcode/self-oss-instruct-sc2-concepts
import socket def create_socket(port, host=None, connect=True): """Creates and returns a socket Args: port (int): port number to use connect (bool, optional): whether socket should be connected (default=True) host (str, optional): hostname to connect to (default="localhost") Retu...
bigcode/self-oss-instruct-sc2-concepts
from functools import wraps import warnings def suppress_warnings(function): """ Decorate the given function to suppress any warnings. Parameters ---------- function : function Function to be decorated. Returns ------- decorated function Decorated function. """ ...
bigcode/self-oss-instruct-sc2-concepts
def get_LDA_potential(vxct, kxct, s): """Evaluating the potential of LDA functional in a batch of spherical projection directions. Parameters ---------- vxct: tuple of (vrho, vs), where vrho and vs are np.ndarray with shape (Ngrid) The exchange-corelation energy of original LDA function. ...
bigcode/self-oss-instruct-sc2-concepts
def TypeCodeToType(typeCode): """ Convert a type code to the class it represents """ if typeCode in ["b", "d", "f", "s"]: return float elif typeCode in ["i", "l"]: return int elif typeCode in ["c"]: return str else: raise Exception("Unrecognised type code: " + typeCode) return
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path import click def validate_existing_dir(ctx, param, value: Path) -> Path: """ Callback for click commands that checks that a given path is a directory """ if not value.is_dir(): raise click.BadParameter(f"{value} is not a directory") return value
bigcode/self-oss-instruct-sc2-concepts
def abbreviation_in(abbreviations): """Constrain the course to given abbreviations.""" def _satisfies(course): return course.abbreviation in abbreviations return _satisfies
bigcode/self-oss-instruct-sc2-concepts
import shutil def center_text(message:str) -> str: """Takes a string and returns the centered result as a string. Parameters ---------- message: (str) The message to center Examples -------- Printing someones name centered in terminal. ``` from sdu.cli import center_text...
bigcode/self-oss-instruct-sc2-concepts
import base64 def serialize_bytes(b: bytes) -> str: """ Takes a bytes object and serialize it. Must be reversible with `deserialize_string()`. """ return base64.b64encode(b).decode("utf-8")
bigcode/self-oss-instruct-sc2-concepts
def _get_interval_result(result): """Parse the raw output of the REST API output and return the timestep Args: result (dict): the raw JSON output of the ESnet REST API Returns: int or None """ value = result.get('agg') if value: return int(value) value = result.get...
bigcode/self-oss-instruct-sc2-concepts