seed
stringlengths
1
14k
source
stringclasses
2 values
def utf8len(s): """Returns the UTF-8 encoded byte size of a string. `s` is a string parameter.""" return len(s.encode("utf-8"))
bigcode/self-oss-instruct-sc2-concepts
import base64 def convert_bytes_to_base64(data: bytes) -> str: """Convert bytes data to base64 for serialization.""" return base64.b64encode(data).decode("ascii")
bigcode/self-oss-instruct-sc2-concepts
def hasHandlers(logger): """ See if a logger has any handlers. """ rv = False while logger: if logger.handlers: rv = True break elif not logger.propagate: break else: logger = logger.parent return rv
bigcode/self-oss-instruct-sc2-concepts
def values_in_acceptable_entries(sequence, allowed_values) -> bool: """Each value in the sequence must be an allowed values. Otherwise, False.""" if len(sequence) == 0: return True for item in sequence: if item not in allowed_values: return False return True
bigcode/self-oss-instruct-sc2-concepts
def int_or_none(value): """ Try to make `value` an int. If the string is not a number, or empty, return None. """ try: return int(value) except ValueError: return None
bigcode/self-oss-instruct-sc2-concepts
def get_tensor_parents_placeholders(tensor): """ Get all placeholders that is depending the given tensor. """ placeholders_list = [] if tensor.op.type == 'Placeholder': placeholders_list.append(tensor) if tensor.op: for t in tensor.op.inputs: if not 'read:0' in t.name: ...
bigcode/self-oss-instruct-sc2-concepts
def bedtxt2dict(pybed, strand_col=5): """ convert bed object to a dict with keys in bed file From chr123 123 123 + To ('chr123', 123, '+') -> 1 :param pybed: bed object :return: """ ret_dict = {} for t in pybed: ret = str(t).strip().split('\t') key = (ret[...
bigcode/self-oss-instruct-sc2-concepts
def word_count(data): """ 输入一个列表,统计列表中各个元素出现的次数 参数 ---- data : list, 需要统计的列表 返回 ---- re : dict, 结果hash表,key为原列表中的元素,value为对应的出现次数 """ re = {} for item in data: re[item] = re.get(item, 0) + 1 return re
bigcode/self-oss-instruct-sc2-concepts
def getRunFilename(sessionId, runId): """Return run filename given session and run""" filename = "patternsData_run-{0:02d}_id-{1}_py.mat".format(runId, sessionId) return filename
bigcode/self-oss-instruct-sc2-concepts
def lambda_handler(event, context): """Sample pure Lambda function """ return "Hello from a Lambda Image!"
bigcode/self-oss-instruct-sc2-concepts
def _is_datetime_dtype(obj): """Returns True if the obj.dtype is datetime64 or timedelta64 """ dtype = getattr(obj, 'dtype', None) return dtype is not None and dtype.char in 'Mm'
bigcode/self-oss-instruct-sc2-concepts
def get_selected_scenarios_in_cache(request, proj_id): """Given a request and the project id returns the list of selected scenarios""" if isinstance(proj_id, int): proj_id = str(proj_id) selected_scenarios_per_project = request.session.get("selected_scenarios", {}) selected_scenario = selected_s...
bigcode/self-oss-instruct-sc2-concepts
def find_ids(df, id_column: str): """ Reads a dataframe and returns a list of unique data from the id_column. """ return list(set(df[id_column]))
bigcode/self-oss-instruct-sc2-concepts
def text_in_text(entity, attribute, value): """ Return ``True`` if the provided entity has the string provided in ``value`` within its text attribute. """ try: return value.lower() in entity.text.lower() except (UnicodeDecodeError, TypeError): # Binary tiddler return Fals...
bigcode/self-oss-instruct-sc2-concepts
import re def unstring(obj): """ Attempt to parse string to native integer formats. One can't simply call int/float in a try/catch because there is a semantic difference between (for example) 15.0 and 15. """ floatreg = "^\\d+.\\d+$" match = re.findall(floatreg, obj) if match != []: ...
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Optional from typing import cast def _mask_positional_args(name: str) -> List[Optional[str]]: """Create a section name representation that masks names of positional arguments to retain their order in sorts.""" stable_name = cast(List[Optional[str]], name.split("...
bigcode/self-oss-instruct-sc2-concepts
def level_list(root): """Get full level order traversal of binary tree nodes. Example: >>> from leetcode_trees import binarytree >>> tree = binarytree.tree_from_list([5,1,4,None,None,3,6]) >>> binarytree.print_tree(tree) ___5___ 1 _4_ 3 6 >>> print(binarytree.level_representation(tree)) [[...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def get_requirements() -> List[str]: """Read requirements.txt and return the requirements. Returns: List[str]: List of requirements. """ requirements = [] with open("requirements.txt", "r", encoding="utf8") as file: for line in file.readlines(): ...
bigcode/self-oss-instruct-sc2-concepts
def is_nan(x): """ Returns `True` if x is a NaN value. """ if isinstance(x, float): return x != x return False
bigcode/self-oss-instruct-sc2-concepts
def check_edge(e,q,fsm): """ checks whether the current state q has an out-edge e. If so returns the state it goes to and the probability; otherwise returns None Arguments e : we're checking to see if there's an edge with this label q : the current state fsm : the fsm Returns ...
bigcode/self-oss-instruct-sc2-concepts
def total_rows(cursor, table_name, print_out=False): """ Returns the total number of rows in the database """ cursor.execute('SELECT COUNT(*) FROM {}'.format(table_name)) count = cursor.fetchall() if print_out: print('\n[+] Total rows in database: {}'.format(count[0][0])) return count[0][0]
bigcode/self-oss-instruct-sc2-concepts
import time def format_date( unixTime ): """ format epoch time stamp as string """ return time.strftime("%Y/%m/%d %H:%M", time.gmtime(unixTime))
bigcode/self-oss-instruct-sc2-concepts
def sort_fragments_by_elf10wbo(frags): """ Sort fragments by ELF10 WBO. This helps with plotting all distributions so the distributions of the different clusters are together Parameters ---------- frags : dict {'smiles': {'ensamble': , 'individual_confs': []} Returns ------- ...
bigcode/self-oss-instruct-sc2-concepts
import re def get_exclude_patterns_as_regex_list(exclude_patterns=None): """ Takes a list of strings are returns a list of compiled regexes. Strips enclosing quotes if present. :type exclude_patterns: list[str] :return: :rtype: list[re.__Regex] """ exclude_regexes = [] if exclude_...
bigcode/self-oss-instruct-sc2-concepts
def decorated_test_task_with_decorator_args(**kwargs): """ Test task, echos back all arguments that it receives. This one is registered using a decorator """ print(f"The decorated (with args) test task is being run with kwargs {kwargs} and will echo them back") return kwargs
bigcode/self-oss-instruct-sc2-concepts
def separator(simbol, count): """ Функция создает разделитель из любых символов любого количества :param simbol: символ разделителя :param count: количество повторений :return: строка разделитель примеры использования ниже """ s = simbol * count return s
bigcode/self-oss-instruct-sc2-concepts
def eq_by(f, value_1, value_2): """Check if two values are equal when applying f on both of them.""" return f(value_1) == f(value_2)
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def read_markdown(fpath: Path) -> str: """Read Markdown file as a string.""" with open(fpath, "r+") as f: md = f.read() return md
bigcode/self-oss-instruct-sc2-concepts
def parse_contig_assignments(assignment_file_path, contig_name_col=0, unassigned_col=9): """ Finds contig_names that are unassigned twice. Inputs: - assignment_file_path: Path to tab-delimited file - contig_name_col: Index of the col which will have the contig name - unassigned_col: Index of th...
bigcode/self-oss-instruct-sc2-concepts
def create_name(words): """ Concatenate words to create the title name. """ return ' '.join(words).title()
bigcode/self-oss-instruct-sc2-concepts
def covstr(strings): """ convert string to int or float. """ try: result = int(strings) except ValueError: result = float(strings) return result
bigcode/self-oss-instruct-sc2-concepts
def create_dataset_url(base_url, identifier, is_pid): """Creates URL of Dataset. Example: https://data.aussda.at/dataset.xhtml?persistentId=doi:10.11587/CCESLK Parameters ---------- base_url : str Base URL of Dataverse instance identifier : str Identifier of the dataset. Can be...
bigcode/self-oss-instruct-sc2-concepts
import base64 def from_url_safe_stream_id(stream_id: str) -> str: """Convert the URLSafe encoded stream id to the corresponding original stream id :param stream_id: streamId of the stream to be parsed :return: stream id after conversion """ decoded_url_bytes = base64.urlsafe_b64decode(stream_id +...
bigcode/self-oss-instruct-sc2-concepts
def remove(seq1, seq2): """ remove the elements in `seq2` from `seq1` """ return tuple(elem for elem in seq1 if elem not in seq2)
bigcode/self-oss-instruct-sc2-concepts
def empty_prep_nb(context, *args): """Preparation function that forwards received arguments down the stack.""" return args
bigcode/self-oss-instruct-sc2-concepts
def outline(text: str, outline_clr=[10,10,10], text_clr=[250,250,250]) -> str: """ Creates a colored outline around the given text. Requires the "contour" package in the preamble, preferably with the [outline] option. That is: \usepackage[outline]{contour} Currently, this package is not included by de...
bigcode/self-oss-instruct-sc2-concepts
def fetch_licenses(fw_conn): """Fetch Licenses Args: fw_conn (PanDevice): A panos object for device """ try: fw_conn.fetch_licenses_from_license_server() print('Licenses retrieved from Palo Alto Networks') return True except: print('WARNING: Not able to retri...
bigcode/self-oss-instruct-sc2-concepts
def add_two(num): """Add two to num""" return num + 2
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path import pkg_resources def get_path_of_data_dir() -> Path: """ get the path of the package data directory :returns: """ file_path: str = pkg_resources.resource_filename( "{{ cookiecutter.project_slug }}", "data") return Path(file_path)
bigcode/self-oss-instruct-sc2-concepts
def _DictToString(dictionary): """Convert a dictionary to a space separated 'key=value' string. Args: dictionary: the key-value dictionary to be convert Returns: a string representing the dictionary """ dict_str = ' '.join(' {key}={value}'.format(key=key, value=value) for key, ...
bigcode/self-oss-instruct-sc2-concepts
def create_edges(dc): """ Create edges (lines) connecting each pair of stars Arguments --------- dc : dictionary of constellations Returns ------- edges : list of all edges """ edges = [] for k,v in dc.items(): for i in v: edges.append(i) ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from typing import List def get_verbalization_ids(word: str, tokenizer, force_single_token: bool) -> Union[int, List[int]]: """ Get the token ids corresponding to a verbalization :param word: the verbalization :param tokenizer: the tokenizer to use :param force_single_tok...
bigcode/self-oss-instruct-sc2-concepts
import re def normalize_reference(s): """ Normalize reference label: collapse internal whitespace to single space, remove leading/trailing whitespace, case fold. """ return re.sub(r'\s+', ' ', s.strip()).upper()
bigcode/self-oss-instruct-sc2-concepts
import json import re def generate_suppression(filepath: str) -> str: """Generate an example suppression document for the given file.""" return json.dumps( { "include": [], "ignore": [ { "pattern": f"{re.escape(filepath)}$", ...
bigcode/self-oss-instruct-sc2-concepts
def update_bathrooms_slider(area): """ Update bathrooms slider to sensible values. """ return [1, min(int(area / 40) + 1, 5)]
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def extend_path(path: Path, extension: str) -> Path: """Extends a path by adding an extension to the stem. Args: path (Path): Full path. extension (str): Extension to add. This will replace the current extension. Returns: Path: New path with extension. ...
bigcode/self-oss-instruct-sc2-concepts
def get_html(html: str): """Convert HTML so it can be rendered.""" WRAPPER = """<div style="overflow-x: auto; border: 1px solid #e6e9ef; border-radius: 0.25rem; padding: 1rem; margin-bottom: 2.5rem">{}</div>""" # Newlines seem to mess with the rendering html = html.replace("\n", " ") return WRAPPER....
bigcode/self-oss-instruct-sc2-concepts
def _insert_idxs(feature_centre, feature_size, dimensions): """Returns the indices of where to put the signal into the signal volume Parameters ---------- feature_centre : list, int List of coordinates for the centre location of the signal feature_size : list, int How big is the s...
bigcode/self-oss-instruct-sc2-concepts
def get_user_nick(user): """Returns the nickname of the passed user, the name otherwise""" if user.nick is None: return user.name return user.nick
bigcode/self-oss-instruct-sc2-concepts
def xdist_molar(xdist_mass, Massl, Massh): """ Calculates the molar concetration distilliat of liquid. Parameters ---------- xdist_mass : float The mass concetration distilliat of liquid, [kg/kg] Massl : float The molar mass of low-boilling component, [kg/kmol] Massh : float ...
bigcode/self-oss-instruct-sc2-concepts
def calc_pct_reliability(df_pct): """ Calculates percent reliability of interstate and non-interstate network. Args: df_pct, a pandas dataframe. Returns: int_rel_pct, % interstate reliability. non_int_rel_pct, % non interstate reliability. """ # Auto, Bus interstate df_int = d...
bigcode/self-oss-instruct-sc2-concepts
def get_corr(d): """ Calculate correlation between SibSp and Parch :param d: data frame :return: rounded correlation """ return round(d.filter(items=['SibSp', 'Parch']).corr(method='pearson'), 2)
bigcode/self-oss-instruct-sc2-concepts
def _remove_invalid_char(s): """Remove invalid and dangerous characters from a string.""" s = ''.join([i if ord(i) >= 32 and ord(i) < 127 else '' for i in s]) s = s.translate(dict.fromkeys(map(ord, "_%~#\\{}\":$"))) return s
bigcode/self-oss-instruct-sc2-concepts
def _doMatchExcept1(inv, atoms): """ Helper function to check if two atoms in the list are the same, and one not Note: Works only for three atoms Arguments: - inv: atom invariants (used to define equivalence of atoms) - atoms: list of atoms to check Return: atom that i...
bigcode/self-oss-instruct-sc2-concepts
import typing def unpack_key_value_pair(entry) -> typing.Tuple[object, object]: """ensure the given entry can be unpacked into a key/value pair :param entry: an iterable element with exactly two elements :return: a tuple containing the key value pair :raises: ValueError when the entry can't be unpack...
bigcode/self-oss-instruct-sc2-concepts
def value_if_found_else_key(some_dict, key): """Lookup a value in some_dict and use the key itself as fallback""" return some_dict.get(key, key)
bigcode/self-oss-instruct-sc2-concepts
def unitstep(t): """Returns the unit step function: ``u(t) = 1.0 if t>=0 else 0``""" return 1.0 if t >= 0 else 0.0
bigcode/self-oss-instruct-sc2-concepts
def getRowMarker(f, year): """ Get the row marker for given year (where the most recent update left off) and return. Returns 0 if doesn't exist. """ dset = f['data'] marker = 0 if "_row_marker" in dset.attrs: row_marker = dset.attrs["_row_marker"] # returns [year, row] ...
bigcode/self-oss-instruct-sc2-concepts
def strokes_to_lines(strokes): """Convert stroke-3 format to polyline format.""" x = 0 y = 0 lines = [] line = [] for i in range(len(strokes)): if strokes[i, 2] == 1: x += float(strokes[i, 0]) y += float(strokes[i, 1]) line.append([x, y]) l...
bigcode/self-oss-instruct-sc2-concepts
def uncomposekey(prefix, key): """Remove a prefix from a composite key. Example: uncomposekey("attr1.attr2", "attr1.attr2.attr3.attr4") == "attr3.attr4" """ if " " in prefix or " " in key: raise NotImplementedError() prefix, key = prefix.split("."), key.split(".") while prefix: a, b = prefix.pop(0)...
bigcode/self-oss-instruct-sc2-concepts
def fw_action(raw): """Normalize firewall action Gives back a value between allow, deny, reject and other """ lower = raw.lower() if lower in ['allow', 'deny', 'reject']: return lower return 'other'
bigcode/self-oss-instruct-sc2-concepts
import torch def split_tensor_pos(tensor): """ Splits tensor into positive and negative terms """ zeros_like = torch.zeros_like(tensor) pos_tensor = torch.max(tensor, zeros_like) neg_tensor = torch.min(tensor, zeros_like) return pos_tensor, neg_tensor
bigcode/self-oss-instruct-sc2-concepts
import random def randomly_true(probability: float) -> float: """ Return True with a given probability, False otherwise. """ return random.uniform(0,1) < probability
bigcode/self-oss-instruct-sc2-concepts
def numeric_filter(operation, value, column, df): """Filters a data column numerically. Arguments: operation: Operator used to filter data (e.g. ">", "<", "==", ">=", "<=", "!=") value: Operand column: String for column name df: DataFrame Returns: Boolean column that indicates whether each...
bigcode/self-oss-instruct-sc2-concepts
def webpage_attribute_setter(attr): """ Helper function for defining setters for web_page attributes, e.g. ``set_foo_enabled = webpage_attribute_setter("foo")`` sets a value of ``webpage.foo`` attribute. """ def _setter(self, value): setattr(self.web_page, attr, value) return _setter
bigcode/self-oss-instruct-sc2-concepts
def meanOffNadirViewAngle(xmlroot): """Get the mean off nadir view angle from the xml.""" return float(xmlroot.find('IMD/IMAGE/MEANOFFNADIRVIEWANGLE').text)
bigcode/self-oss-instruct-sc2-concepts
def truesi(xs): """ indices for which x[i] is True """ return [i for i, x in enumerate(xs) if x]
bigcode/self-oss-instruct-sc2-concepts
def create_event(event_type, data): """Return a dictionary containing the properties required when defining an event. Keyword arguments: event_type -- the type of event, used to distinguish multiple events apart. data -- a dictionary of key/value pairs containing custom data. """ return { ...
bigcode/self-oss-instruct-sc2-concepts
def resize_bbox(bbox, in_size, out_size): """ Resize bounding boxes according to image resize. :param bbox (numpy.ndarray): An array that has a shape (R, 4), 'R' is the number of the bounding boxes. '4' indicates the position of the box, which represents (y_min, x_min, y_max, x_max) ...
bigcode/self-oss-instruct-sc2-concepts
def strip_spaces_list(list_in, strip_method="all"): """ Remove spaces from all items in a list :param list_in: :param strip_method: Default: 'all' for leading and trailing spaces. Can also be 'leading' or 'trailing' :return: List with items stripped of spaces """ if strip_method == "all...
bigcode/self-oss-instruct-sc2-concepts
def LinearReconstruct( u_stencil ): """Linear reconstruction with linear weights. This reconstructs u_{i+1/2} given cell averages \\bar{u}_i at each neighboring location. See (2.14) in `High Order Weighted Essentially Nonoscillatory Schemes for Convection Dominated Problems'. """ uim2, u...
bigcode/self-oss-instruct-sc2-concepts
def compute_avg_wmd_distance(contexts1, contexts2, gensim_obj): """ Compute an average word metric distance :param contexts1: List of ContextAndEntities objects extracted from Document 1 :param contexts2: List of ContextAndEntities objects extracted from Document 2 :param gensim_obj: a Gensim object...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict import torch def default_fn(x, models, **kwargs) -> Dict[str, torch.Tensor]: """ The default inference function for [BaseAdapter][pytorch_adapt.adapters.BaseAdapter]. """ features = models["G"](x) logits = models["C"](features) return {"features": features, "logits": lo...
bigcode/self-oss-instruct-sc2-concepts
def merge_dico_in_first(d1, d2): """ Merge dictionary d2 in d1. """ for k, v in d2.items(): if k in d1: raise ValueError(f"Key {k} should not be in d1") else: d1[k] = v return d1
bigcode/self-oss-instruct-sc2-concepts
def json_config(json_sample_path): """Return a list containing the key and the sample path for a json config.""" return ["--config", json_sample_path]
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterable from typing import List from typing import Any def flatten(iterable: Iterable, drop_null: bool = False) -> List[Any]: """Flatten out a nested iterable. Flatten a nested iterable, even with multiple nesting levels and different data types. It is also possible to drop null value...
bigcode/self-oss-instruct-sc2-concepts
def get_routes(feed, date=None, time=None): """ Return a subset of ``feed.routes`` Parameters ----------- feed : Feed date : string YYYYMMDD date string restricting routes to only those active on the date time : string HH:MM:SS time string, possibly with HH > 23, res...
bigcode/self-oss-instruct-sc2-concepts
def forecasted_occlusion_position(occlusion_bool_list): """ Given a boolean list of occlusion events, return the index position of the forecasts that indicate that an occlusion event has been predicted. """ positional_list = [] for i in range(len(occlusion_bool_list)): if occlusion...
bigcode/self-oss-instruct-sc2-concepts
import re def _get_name(name): """Internal Method to Change camelcase to underscores. CamelCase -> camel_case """ return re.sub('(?!^)([A-Z]+)', r'_\1', name).lower()
bigcode/self-oss-instruct-sc2-concepts
def vector(feature_key2idsfuncs, example, event_sequence, always_keys=set()): """ Create a feature vector by applying the given feature functions to the given example and event sequence and return it. Runs quickly by applying only those feature functions whose keys match the fact keys or...
bigcode/self-oss-instruct-sc2-concepts
import math def iterate_pagerank(corpus, damping_factor): """ Return PageRank values for each page by iteratively updating PageRank values until convergence. Return a dictionary where keys are page names, and values are their estimated PageRank value (a value between 0 and 1). All PageRank va...
bigcode/self-oss-instruct-sc2-concepts
def copy_column_shift(df, column_source, column_target, shift_amount): """ Copy an existing column (shifted by shift_amount) to a new column in dataframe. :param df: dataframe (sorted in ascending time order) :param column_source: name of source column in dataframe with values to copy :param column...
bigcode/self-oss-instruct-sc2-concepts
import re def _match_time(value): """Return the time (leaveby, arriveat) in value, None if no time in value.""" mat = re.search(r"(\d{1,2}:\d{1,2})", value) if mat is not None and len(mat.groups()) > 0: return mat.groups()[0] return None
bigcode/self-oss-instruct-sc2-concepts
def convert_from_string(x): """ Convert a string that may represent a Python item to its proper data type. It consists in running `eval` on x, and if an error occurs, returning the string itself. """ try: return eval(x, {}, {}) except Exception: return x
bigcode/self-oss-instruct-sc2-concepts
def rescale_tick(tick: int, old_res: int, new_res): """Rescales the given tick from one resolution to another :param tick: tick value to rescale :param old_res: original tick resolution in PPQN :param new_res: new tick resolution in PPQN :return: rescaled tick value as an integer :raises V...
bigcode/self-oss-instruct-sc2-concepts
def parse_address(address): """Parse and address on the format host:port. Returns a tuple (host, port). Raises ValueError if format is invalid or port is not an integer or out of range. """ words = address.split(':') if len(words) != 2: raise ValueError('address must contain exactly one...
bigcode/self-oss-instruct-sc2-concepts
def _calculate_endog_immunity_prob(initial_infections, synthetic_data): """Calculate the immunity probability from initial infections. Args: initial_infections (pandas.DataFrame): DataFrame with same index as synthetic_data and one column for each day between start and end. Dtyp...
bigcode/self-oss-instruct-sc2-concepts
def _find_sentence(translation, language): """Util that returns the sentence in the given language from translation, or None if it is not found Args: translation: `xml.etree.ElementTree.Element`, xml tree element extracted from the translation memory files. language: `str`, language of interest...
bigcode/self-oss-instruct-sc2-concepts
def calc_tf_idf(idf, tf): """Calculate the TF-IDF score based on tf and idf components""" tfidf = {} for key, val in tf.items(): tfidf[key] = val * idf[key] return tfidf
bigcode/self-oss-instruct-sc2-concepts
def thread(read=20, write=20): """Return the kwargs for creating the Thread table.""" return { 'AttributeDefinitions': [ { 'AttributeName': 'ForumName', 'AttributeType': 'S' }, { 'AttributeName': 'Subject', ...
bigcode/self-oss-instruct-sc2-concepts
def BCR(conf_matrix): """ Given a confusion matrix, returns Balanced Classification Rate. BCR is (1 - Balanced Error Rate). BER Definition: http://research.ics.aalto.fi/events/eyechallenge2005/evaluation.shtml """ parts = [] for true_response, guess_dict in list(conf_matrix.items()): error = 0.0 t...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def get_query_string(params: Dict) -> str: """Makes a string corresponding to the query string of `params` Args: params (Dict): Parameters given in the API call Returns: str: URL argument used to call the API """ return '&'.join([f'{k}={v}' for k, v in par...
bigcode/self-oss-instruct-sc2-concepts
def _common_length_of(l1, l2=None, l3=None): """ The arguments are containers or ``None``. The function applies ``len()`` to each element, and returns the common length. If the length differs, ``ValueError`` is raised. Used to check arguments. OUTPUT: A tuple (number of entries, common length ...
bigcode/self-oss-instruct-sc2-concepts
def collect_forces(f, num_atom, hook, force_pos, word=None): """General function to collect forces from lines of a text file. Parameters ---------- f : Text file pointer such as that returned by ``open(filename)``. num_atom : int Number of atoms in cell. Quit parsing when number of ...
bigcode/self-oss-instruct-sc2-concepts
def is_subclass(cls, class_or_tuple): """ Return whether 'cls' is a derived from another class or is the same class. Does not raise `TypeError` if the given `cls` is not a class. """ try: return issubclass(cls, class_or_tuple) except TypeError: return False
bigcode/self-oss-instruct-sc2-concepts
def BuildArtifactSourceTree(files, file_open=open): """Builds a dependency tree using from dependency mapping files. Args: files: A comma separated list of dependency mapping files. file_open: Reference to the builtin open function so it may be overridden for testing. Returns: A dict mapping build...
bigcode/self-oss-instruct-sc2-concepts
import math def haversine(c0, c1): """ :param c0: coordinate 0 in form (lat0, lng0) with degree as unit :param c1: coordinate 1 in form (lat1, lng1) with degree as unit :return: The haversine distance of c0 and c1 in km Compute the haversine distance between https://en.wikipedia.org/wiki/Haver...
bigcode/self-oss-instruct-sc2-concepts
def is_file_available (data, filename): """Return True is the given file is available in the input data file, otherwise return False""" return True if filename in data else False
bigcode/self-oss-instruct-sc2-concepts
def filter_by_energy_structure(record): """ Include only records that have an 'energyratestructure' field defined. True: filter out False: keep :param record: :return: """ if "energyratestructure" not in record.keys(): return True else: return False
bigcode/self-oss-instruct-sc2-concepts
def _get_label_proportion(data_set, target): """Get the proportion of each type. Implemented on spark. Args: data_set (pyspark.sql.dataframe.DataFrame): The data set. target (str): The target column. Returns: label_proportion (dct): A dictionary, (key, values) ~ (attribute, count) ...
bigcode/self-oss-instruct-sc2-concepts