seed
stringlengths
1
14k
source
stringclasses
2 values
def get_source_inputs(tensor, layer=None, node_index=None): """Returns the list of input tensors necessary to compute `tensor`. Output will always be a list of tensors (potentially with 1 element). Arguments: tensor: The tensor to start from. layer: Origin layer of the tensor. Will be de...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def compare_lists(local_list: List[str], remote_list: List[str]) -> List[str]: """ Comapre local and remote list of files and return the list of local files not stored in remote database. :param local_list: list of names of local files :param remote_list: list of names of remot...
bigcode/self-oss-instruct-sc2-concepts
def num_param_Gauss(d): """ count number of parameters for Gaussian d-dimension. input d [int] : dimension of data """ return 0.5 * d * (d + 3.0)
bigcode/self-oss-instruct-sc2-concepts
def obtain_list_db_tickers(conn): """ query our Postgres database table 'symbol' for a list of all tickers in our symbol table args: conn: a Postgres DB connection object returns: list of tuples """ with conn: cur = conn.cursor() cur.execute("SELECT id, ticker FR...
bigcode/self-oss-instruct-sc2-concepts
def update_dict_deep(original, new_values): """ Updates dict *in-place* recursively, adding new keys in depth instead of replacing key-value pairs on top levels like `dict.update()` does. Returns updated dict. """ for key in new_values: if key not in original: original[key] = new_values[key] elif isinstance...
bigcode/self-oss-instruct-sc2-concepts
def get_int_with_default(val, default): """Atempts to comvert input to an int. Returns default if input is None or unable to convert to an int. """ if val is None: return default try: return int(val) except ValueError: pass return default
bigcode/self-oss-instruct-sc2-concepts
def limitaxis(c,maxc,minc=0): """ Limit value in axis. :param c: value :param maxc: max c value. :param minc: min c value. :return: limited c value c E [minc,maxc] """ if c > maxc: c = maxc if c < minc: c = minc return c
bigcode/self-oss-instruct-sc2-concepts
def _get_cache_value(key): """ Returns a value for a cache key, or None """ address = None try: with open(key) as f: address = f.read() except FileNotFoundError: address = None return address
bigcode/self-oss-instruct-sc2-concepts
import random import string def RandomString(length): """Returns a randomly generated string of ascii letters. Args: length: The length for the returned string. Returns: A random ascii letters string. """ return ''.join([random.choice(string.ascii_letters) for unused_i in range(l...
bigcode/self-oss-instruct-sc2-concepts
def generate_fake_oco_status(random_state, size): """ Generate random OCO status, mostly assigned to 200 with some 300 status codes during a random range between 4 and 50 ticks """ values = [200] * size picked_error_values_indexes = random_state.choice( size, round(0.001 * len(values)), ...
bigcode/self-oss-instruct-sc2-concepts
def is_superset(obj1, obj2, path=""): """ Checks whether obj1 is a superset of obj2. Parameter *obj1*: Superset object Parameter *obj2*: Subset object Parameter *path*: Should be "" in initial call Return value: Returns a tuple with 2 arguments. The first argument is a boolean which is true, if o...
bigcode/self-oss-instruct-sc2-concepts
def get_file_and_head(filename, n_head=5): """Get the contents of a file, and the head. Parameters ---------- filename: str The name of the file to read. n_head: int The number of lines to include in the head. """ with open(filename, "r") as fp: content = fp.read() ...
bigcode/self-oss-instruct-sc2-concepts
def make_str(s): """Casts the input to string. If a string instance is Not given, Ikke gitt or None, return empty string.""" if s == 'Not given': return '' if s == 'Ikke gitt': return '' if s is None: return '' return str(s)
bigcode/self-oss-instruct-sc2-concepts
def get_touchdown(df): """ Calculates instance of touchdown (landing). """ df = df.copy() return df.iloc[df['Altitude'].idxmax():][df['Altitude'] <= 2].index[0]
bigcode/self-oss-instruct-sc2-concepts
def format_cmd(cmd): """If some command arguments have spaces, quote them. Then concatenate the results.""" ans = "" for val in cmd: if " " in val or "\t" in cmd: val = '"' + val + '"' ans += val + " " return ans
bigcode/self-oss-instruct-sc2-concepts
import copy def select_keys(d, keys): """Returns a dict containing only those entries in dict whose key is in keys See also select_paths :param d: dict to filter :param keys: a list of keys to select :returns: a copy of subset of d with only the specified keys :rtype: dict """ return...
bigcode/self-oss-instruct-sc2-concepts
def replace_forward_slash(file_name): """ This method takes a string representing a file name and replaces forward slashes with ":" This approach is consistent with how other clients deal with attempts to upload files with forward slashes in the name. """ return file_name.replace("/", ":")
bigcode/self-oss-instruct-sc2-concepts
def jet_id(jets, options): """ Loose jet ID taken from flashgg: https://github.com/cms-analysis/flashgg/blob/dd6661a55448c403b46d1155510c67a313cd44a8/DataFormats/src/Jet.cc#L140-L155 """ nemf_cut = jets.neEmEF < 0.99 nh_cut = jets.neHEF < 0.99 chf_cut = jets.chHEF > 0 chemf_cut = jets.chEmEF...
bigcode/self-oss-instruct-sc2-concepts
def get_tokens(flight_list): """ Create list of booking tokens to retrieve booking info. """ return [i['booking_token'] for i in flight_list]
bigcode/self-oss-instruct-sc2-concepts
def get_element_by_id(_id, group_list): """ Use next generator to find element in a group's list by identifier. """ return next(e for e in group_list if _id == e["id"])
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional from typing import Mapping def _check_scale_factor( spatial_data: Optional[Mapping], img_key: Optional[str], scale_factor: Optional[float], ) -> float: """Resolve scale_factor, defaults to 1.""" if scale_factor is not None: return scale_factor elif spatial_d...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def get_param_docstring(docstring: str) -> str: """ Get docstring of argument part. Parameters ---------- docstring : str Target docstring string. Returns ------- param_docstring : str Argument part docstring. """ param_part_started: bo...
bigcode/self-oss-instruct-sc2-concepts
def get_new_pos(old_pos): """This is a function that converts part-of-speech codes to abbreviated parts-of-speech""" new_pos = "" if old_pos.startswith('J'): new_pos = "a" elif old_pos.startswith('V'): new_pos = "v" elif old_pos.startswith('N'): new_pos = "n" elif old_pos...
bigcode/self-oss-instruct-sc2-concepts
def sanitize_metric_name(metric_name: str) -> str: """ Replace characters in string that are not path-friendly with underscore """ for s in ["?", "/", "\\", ":", "<", ">", "|", "'", '"', "#"]: metric_name = metric_name.replace(s, "_") return metric_name
bigcode/self-oss-instruct-sc2-concepts
def get_alignment_pdb_chain(alignment): """ Returns a string of the chain id, e.g. 'A', 'B', etc. :param alignment: :return: """ pdb_chain_id = alignment.hit_def.encode('ascii').split()[0] chain = pdb_chain_id.split('_')[1].upper() return chain
bigcode/self-oss-instruct-sc2-concepts
from typing import List def calculate_magnitude(reduced_form: List[List[int]]) -> int: """ Generate the magnitude by reducing from inside out. Ex: [[9,1], [1,9]] => [(9, 2), (1, 2), (1, 2), (9, 2)] => [(29, 1), (1, 2), (9, 2)] => [(29, 1), (21, 1)] => [(129, 0)] => ...
bigcode/self-oss-instruct-sc2-concepts
def process_lines(file_reader, corpus_name:str)->list: """Strips and splits the lexicon lines. The case is kept intact for the 'switchboard' corpus, but is lowered for all others Args: file_reader: file reader object of lexicon corpus_name (str) Returns: (list): split lexicon li...
bigcode/self-oss-instruct-sc2-concepts
def documentation_link(chapter): # type: (str)->str """ Creates a link to the documentation. This method is useful for showing a link to the ZSL documentation in case of any misconfiguration, etc. :param chapter: Chapter name in to which the link points. Use underscores instead of spaces. :retu...
bigcode/self-oss-instruct-sc2-concepts
def stcqt(sig, fr, cqbank): """Implement Judith Brown's Constant Q transform. Parameters ---------- sig: array_like Signal to be processed. fr: int Frame rate in Hz, or int(SR/hop_length). cqbank: ConstantQ Filterbank class A pre-defined constant Q filterbank class. ...
bigcode/self-oss-instruct-sc2-concepts
def get_grid_offset(function, axis): """ For a function, return the grid offset for a specified axis. Parameters ---------- function : devito Function The function to get the offset of axis : int The axis for which offset should be recovered """ if function.is_Staggered:...
bigcode/self-oss-instruct-sc2-concepts
def SplitSequence(seq, size): """Split a list. Args: seq: sequence size: int Returns: New list. Recipe From http://code.activestate.com/recipes/425397/ (Modified to not return blank values) """ newseq = [] splitsize = 1.0/size*len(seq) for i in range(size): newseq.append(seq[int(round...
bigcode/self-oss-instruct-sc2-concepts
def remove_formatting(ingredients_series): """Remove text formatting and non alphabetic characters, replace . with ,""" return ( ingredients_series.str.replace("<strong>", "", regex=False) .str.replace("</strong>", "", regex=False) .str.replace(" \(.*?\)", "", regex=True) .st...
bigcode/self-oss-instruct-sc2-concepts
def darken(color, ratio=0.5): """Creates a darker version of a color given by an RGB triplet. This is done by mixing the original color with black using the given ratio. A ratio of 1.0 will yield a completely black color, a ratio of 0.0 will yield the original color. The alpha values are left intact. ...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def find_disappeared(nums: List[int]) -> List[int]: """ Explanation: We have two ways to encode information: the values in the array, and the indices of the array. We iterate through the array, and store info about the values at their corresponding index: value - 1. W...
bigcode/self-oss-instruct-sc2-concepts
def _mock_check_state(_): """Mocked check_state method.""" return True
bigcode/self-oss-instruct-sc2-concepts
import math def conv_float2negexp(val: float) -> int: """Least restrictive negative exponent of base 10 that achieves the floating point convergence criterium `val`.""" return -1 * int(math.floor(math.log(val, 10)))
bigcode/self-oss-instruct-sc2-concepts
def get_keys_by_value(dict_of_elements, value_to_find): """ Parse a dict() to get keys of elements with a specified value :param dict_of_elements: :param value_to_find: :return: """ list_of_keys = list() list_of_items = dict_of_elements.items() for item in list_of_items: if i...
bigcode/self-oss-instruct-sc2-concepts
def compat_is_coresight(dcompat): """ Check if a device tree node claims compatibility with CoreSight. We don't check for "arm" here because an architecture-licensee core might be ETM-compatible but not be an Arm device. We also expect to see "primecell". """ for dc in dcompat: if dc...
bigcode/self-oss-instruct-sc2-concepts
import re def parse_ancestor_offsets(date_arg): """Parse any ancestor offsets in date runtime argument. The date argument passed in doesn't *need* to have any of these offsets. Args: date_arg: A string containing a date argument to be parsed. Returns: A two-tuple con...
bigcode/self-oss-instruct-sc2-concepts
def sum_list(x): """Takes a list, and returns the sum of that list. If x is empty list, return 0. >>> sum_list([1, 2, 3, 4]) 10 >>> sum_list([]) 0 """ return sum(x)
bigcode/self-oss-instruct-sc2-concepts
def locate_tifs(file_list) -> list: """identify the .tif files in a list of files Parameters ---------- file_list : list list of files to parse Returns ------- list list of files where the extension is .tif """ return list([s for s in file_list if '.tif' in s.lower...
bigcode/self-oss-instruct-sc2-concepts
def skip_add(n): """ Takes a number n and returns n + n-2 + n-4 + n-6 + ... + 0. >>> skip_add(5) # 5 + 3 + 1 + 0 9 >>> skip_add(10) # 10 + 8 + 6 + 4 + 2 + 0 30 >>> # Do not use while/for loops! >>> from construct_check import check >>> # ban iteration >>> check(this_file, 'skip_add...
bigcode/self-oss-instruct-sc2-concepts
import resource def li_worker(func, storage, time, memory, *args, **kwargs): """limits the memory consumption and time taken to execute given function Args: func (`function`): function to execute storage (`list`): multiprocessing.Manager().List() to store the peak memory time (`int`):...
bigcode/self-oss-instruct-sc2-concepts
import random def random_system(tree): """Returns random system node. """ systems = tree.xpath('.//system') idx = random.randrange(0,len(systems)) return systems[idx]
bigcode/self-oss-instruct-sc2-concepts
import math def resize(size, hwRatio): """ Return the minimum size of image that is at least "size" but maintains the provided aspect ratio """ if size[0] * hwRatio > size[1]: return (size[0], int(math.ceil(size[0]*hwRatio))) else: return (int(math.ceil(1.0*size[1] / hwRatio)),...
bigcode/self-oss-instruct-sc2-concepts
def _consume_until_marker(it, marker): """ Consume data from the iterator, until marker is found (compared using operator `is`). Returns tuple of number of elements consumed before the marker and bool indicating whether the marker was found (False means the iterator was exhausted. """ i = -1 ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Any def deep_update(src: Dict[Any, Any], dest: Dict[Any, Any]) -> Dict[Any, Any]: """ Similar to ``dict.update``, except that we also ``deep_update`` any dictionaries we find inside of the destination. This is useful for nested default settings, for instance....
bigcode/self-oss-instruct-sc2-concepts
def spark_df_to_records(df): """Dump a Spark DF as a list of tuples representing rows ('records').""" return [tuple(r) for r in df.collect()]
bigcode/self-oss-instruct-sc2-concepts
def findRdkitMolRadicalAtomIds(rdkitMol): """Returns a list of atom ids with radical sites.""" radicalAtomIds = [] for atom in rdkitMol.GetAtoms(): if atom.GetNumRadicalElectrons() > 0: radicalAtomIds.append(atom.GetIdx()) return radicalAtomIds
bigcode/self-oss-instruct-sc2-concepts
def region_slice(dset, x0=None, x1=None , y0=None, y1=None): """ DESCRIPTION: =========== Returns lon / lat rectangle slice of a xarray data set USAGE: ===== sliced_dataset = region(dset, x0, x1, y0, y1) dset: xarray dataset x0: long...
bigcode/self-oss-instruct-sc2-concepts
def find_link(search, soup): """Find and return the first <a> tag's href element in `soup`.""" link = soup.find("a", text=lambda t: search in t) return link.attrs["href"]
bigcode/self-oss-instruct-sc2-concepts
def _ev_remaining_range_supported(data): """Determine if remaining range is supported.""" return ( data["isElectric"] and data["evStatus"]["chargeInfo"]["drivingRangeKm"] is not None )
bigcode/self-oss-instruct-sc2-concepts
def normalize_by_chrom_lengths(counts_dict, chrom_lengths_dict): """ Normalize the number of counts by the length of the chromosome Parameters: counts_dict(dict): count_chrom_alignments chrom_lengths_dict(dict): output from determine_chrom_lengths() Returns: counts_dict (dict):...
bigcode/self-oss-instruct-sc2-concepts
def rule2string(lhs,rhs,isCopy=False): """ Makes a string from a rule. Used in printing and in making a dict of rules and probs. Arguments: lhs : string rhs : string list isCopy : boolean indicating a copy rule. Only used in cky_constituent_copy """ s = "%s->%s"%(lhs,".".join(rhs)...
bigcode/self-oss-instruct-sc2-concepts
import requests def create_oauth_token(grant_type, client_id, client_secret, workspace_id=None, scopes='', username=None, password=None, uri='https://plaidcloud.com/oauth/token', proxy_settings=None): """Attempts to create an Oauth2 auth token using the provided data This is designed primarily for password-t...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def path_for_class(cls) -> List[str]: """ A list describing the import path for a given class. Parameters ---------- cls A class with some module path Returns ------- A list of modules terminating in the name of a class """ return f"{cls.__modu...
bigcode/self-oss-instruct-sc2-concepts
def check_defaults(options, default): """Adds the values in default to options. Args: options (dict): base options. default (dict): default options. Returns: dict: options with the missing values that are in default but not in options. """ if options is None: ...
bigcode/self-oss-instruct-sc2-concepts
def st_align(self,t_start): """ Shifts the current spike train to a different t_start. The duration remains the same, this is just a shift. """ diff = self.t_start - t_start new_st = self[:] - diff new_st.t_start = t_start new_st.t_stop = self.t_stop - diff return new_st
bigcode/self-oss-instruct-sc2-concepts
def uniq(x): """Remove duplicated items and return new list. If there are duplicated items, first appeared item remains and others are removed. >>> uniq([1,2,3,3,2,4,1]) [1, 2, 3, 4] """ y=[] for i in x: if not y.count(i): y.append(i) return y
bigcode/self-oss-instruct-sc2-concepts
def AlternatesInModel(model): """Returns a set of altloc names of all conformers in all chains. :param model: pdb.hierarchy.model to search for alternates. :return: Set of strings. The set is will include only the empty string if no chains in the model have alternates. It has an additional entry for every alt...
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional def decode_bytes_str(input_value=None, charset='utf-8') -> Optional[str]: """ Decode input value to string using the given charset :param charset: charset to use while decoding (defaults to utf-8) :param input_value: :return: """ if input_value is not None and n...
bigcode/self-oss-instruct-sc2-concepts
def instance_with_scenario_name(instance_name, scenario_name): """Format instance name that includes scenario.""" return f"{instance_name}-{scenario_name}"
bigcode/self-oss-instruct-sc2-concepts
def nvmf_create_target(client, name, max_subsystems=0): """Create a new NVMe-oF Target. Args: name: Must be unique within the application max_subsystems: Maximum number of NVMe-oF subsystems (e.g. 1024). default: 0 (Uses SPDK_NVMF_DEFAULT_MAX_SUBSYS...
bigcode/self-oss-instruct-sc2-concepts
def confusion_matrix(classify=lambda document: False, documents=[(None, False)]): """ Returns the performance of a binary classification task (i.e., predicts True or False) as a tuple of (TP, TN, FP, FN): - TP: true positives = correct hits, - TN: true negatives = correct rejections, ...
bigcode/self-oss-instruct-sc2-concepts
def setdeepr(obj, name, value): """Function to set deeper attributes, replaces setattr.""" names = name.split('.') for name in names[:-1]: obj = getattr(obj, name) return setattr(obj, names[-1], value)
bigcode/self-oss-instruct-sc2-concepts
def pos_upper(num, string): """ Returns a string containing its first argument, and its second argument in upper case. :param num: int :param string: str :return: str """ return f'{num}:{string.upper()}'
bigcode/self-oss-instruct-sc2-concepts
def space_name(prefix, index): """Construct name of space from the prefix and its index.""" return "{p}{i}".format(p=prefix, i=index)
bigcode/self-oss-instruct-sc2-concepts
import math def square_distribution(size): """ Determines the "most square" x and y values which will make a grid of the specified size. args: size - the size of the grid (int) returns: size_prime - True if size is prime (bool) x ...
bigcode/self-oss-instruct-sc2-concepts
def is_in_subnet(ip, subnet): """True if given IP instance belongs to Subnet.""" return ip.bits == subnet.bits and (ip.value & subnet.mask) == subnet.base
bigcode/self-oss-instruct-sc2-concepts
import yaml def dump_to_string(data)-> str: """ Dumps 'data' object to yaml string """ result = yaml.safe_dump(data, default_flow_style=False, default_style=None, explicit_start=None) return result
bigcode/self-oss-instruct-sc2-concepts
def xml_combine(root, elements): """Combine two xml elements and their subelements This method will modify the 'root' argument and does not return anything. Args: root (Element): The Element that will contain the merger elements (Element or list): If an Element, merge all subelements o...
bigcode/self-oss-instruct-sc2-concepts
def rescale(values, factor): """ Returns a new dictionary of scaled values The values are scaled by the scale factor given """ return {key: value * float(factor) for (key, value) in values.iteritems()}
bigcode/self-oss-instruct-sc2-concepts
def is_above_or_to_left(ref_control, other_ctrl): """Return true if the other_ctrl is above or to the left of ref_control""" text_r = other_ctrl.rectangle() ctrl_r = ref_control.rectangle() # skip controls where text win is to the right of ctrl if text_r.left >= ctrl_r.right: return False ...
bigcode/self-oss-instruct-sc2-concepts
def relative_humidity(e_a, e_s): """ Calculate the relative humidity of air (Allen et al., 1998). Relative humidity expresses the degree of saturation of the air as a ratio of the actual (e_a) to the saturation (e_s) vapour pressure at the same temperature. Parameters ---------- e_a : ...
bigcode/self-oss-instruct-sc2-concepts
def is_number(x): """Check is a number.""" if isinstance(x, (int, float)): return True else: return False
bigcode/self-oss-instruct-sc2-concepts
def add_data_args(parser): """Train/valid/test data arguments.""" group = parser.add_argument_group('data', 'data configurations') group.add_argument('--model-parallel-size', type=int, default=1, help='size of the model parallel.') group.add_argument('--shuffle', action='store_t...
bigcode/self-oss-instruct-sc2-concepts
def get_paths(rlz): """ :param rlz: a logic tree realization (composite or simple) :returns: a dict {'source_model_tree_path': string, 'gsim_tree_path': string} """ dic = {} if hasattr(rlz, 'sm_lt_path'): # composite realization dic['source_model_tree_path'] = '_'.join(r...
bigcode/self-oss-instruct-sc2-concepts
from textwrap import dedent import traceback def format_exception_trace(exception: BaseException) -> str: """ Formats the traceback part of an exception as it would appear when printed by Python's exception handler. Args: exception: The exception to format Returns: A string, usually ...
bigcode/self-oss-instruct-sc2-concepts
def sub_group_lines(lines): """ Splits lines delimited by empty lines, groups split lines into lists. Args: lines (list): A list of lines seperated by empty lines. Returns: A list of lists of grouped lines. """ groups, sub_group = [], [] for line in lines: if len(line...
bigcode/self-oss-instruct-sc2-concepts
def batch_cmd_create_irf( cwd, mc_gamma, mc_proton, mc_electron, output_irf_file, dl3_config ): """Create batch command to create IRF file with sbatch.""" return [ "sbatch", "--parsable", "--mem=6GB", "--job-name=irf", "-D",...
bigcode/self-oss-instruct-sc2-concepts
def greeting(name: str) -> str: """ Build the greeting message """ return 'Hello, ' + name + '!'
bigcode/self-oss-instruct-sc2-concepts
def get_linear_magnitude_scaling(scale_factor: float): """ Get a linear magnitude scaling function, to correct magnitude. Parameters ---------- scale_factor : float The scale factor, according to the definition given in STDI-0002. Returns ------- callable """ def scale...
bigcode/self-oss-instruct-sc2-concepts
from functools import reduce def deepgetattr(obj, attr, default=None, sep="."): """Recurse through an attribute chain to get the ultimate value.""" return reduce(lambda o, key: o.get(key, default), attr.split(sep), obj)
bigcode/self-oss-instruct-sc2-concepts
def findCmdLineSwitch(argList, switch, ignoreCase=True): """ Argument List에서 command switch를 찾는다. optViewFields = '/view_fields:' optDeletedRecords = '/deleted_records' argv = 'SQLiteParser.py external.db files /view_fields:_data,date_modified,date_added /deleted_records'.split() v1 = findCmdLi...
bigcode/self-oss-instruct-sc2-concepts
def tio_is_attribute(tree_item): """ Returns 'True' if the tree item object is an attribute of the parent opposed to e.g. a list element. """ if tree_item.is_attribute is None: return '' else: return str(tree_item.is_attribute)
bigcode/self-oss-instruct-sc2-concepts
def evaluate(conf_matrix, label_filter=None): """ Evaluate Precision, Recall and F1 based on a confusion matrix as produced by `create_confusion_matrix`. Args: conf_matrix: a confusion matrix in form of a dictionary from `(gold_label,guess_label)` pairs to counts. label_filter: a set of gold...
bigcode/self-oss-instruct-sc2-concepts
def lists_to_dict(list_keys, list_values): """two ordered lists to a dict where list_keys are the keys and list_values are the values Inputs: list_keys - a list of n unique elements, where n = 0, 1 or many list_values - a list of n elements Returns: a dict of ...
bigcode/self-oss-instruct-sc2-concepts
def functionIsCompilable(f): """Is a python function 'f' compilable? Specifically, we try to cordon off the functions we know are not going to compile so that we can just represent them as python objects. """ # we know we can't compile standard numpy and scipy functions if f.__module__ == "nump...
bigcode/self-oss-instruct-sc2-concepts
def list_files(root, extension, parts): """Construct files from root, parts.""" files = [root + part + extension for part in parts] return files
bigcode/self-oss-instruct-sc2-concepts
import asyncio def _get_event_loop() -> asyncio.AbstractEventLoop: """ This simply wraps the asyncio function so we have typing for autocomplet/linting""" return asyncio.get_event_loop()
bigcode/self-oss-instruct-sc2-concepts
def spaceHolder(response): """Return the response without parsing.""" return response
bigcode/self-oss-instruct-sc2-concepts
def get_schedule_v(df): """換気スケジュール Args: df(DateFrame): スケジュール Returns: ndarray: 換気スケジュール """ return df['換気'].values
bigcode/self-oss-instruct-sc2-concepts
from typing import List def bert_preprocess(texts: List[str]) -> List[str]: """ Apply preprocessing appropriate for a BERT (or BERT-based) model to a set of texts. Args: texts: Texts to preprocess. Returns: List of preprocessed texts. """ # BERT truncates input, so don't pass in ...
bigcode/self-oss-instruct-sc2-concepts
def projection_dict(projection): """Get a projection dictionary from a list of attribute names to project. Args: projection: List of string names of attributes to project. Returns: Dictionary like {'attr1': 1, 'attr': 1, ... }. """ if projection: return dict(zip(projection, [1]...
bigcode/self-oss-instruct-sc2-concepts
def datetimefilter(value, format='%d/%m/%Y at %H:%M:%S'): """Convert a datetime to a different format.""" return value.strftime(format)
bigcode/self-oss-instruct-sc2-concepts
def filterNone(l): """Returns the list l after filtering out None (but 0"s are kept).""" return [e for e in l if e is not None]
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path import re def get_compressed_path(path, is_obs=None, compression='gz'): """Get the compressed path corresponding to a RINEX file after compression. Parameters ---------- path : path or str Path to the RINEX file being compressed. is_obs : bool, optional Wh...
bigcode/self-oss-instruct-sc2-concepts
import torch def kron_einsum_batched_1D(A: torch.Tensor, B: torch.Tensor): """ Batched Version of Kronecker Products :param A: has shape (b, c, a) :param B: has shape (b, c, k) :return: (b, c, ak) """ res = torch.einsum('ba,bk->bak', A, B).view(A.size(0), A.size(1)*B.size(1) ) # ...
bigcode/self-oss-instruct-sc2-concepts
import math def generate_equator(step=0.5, type='equ'): """ step is in degrees types: equ = celestial equator ecl = ecliptic gal = galactic equator """ eps = math.radians(23.4392911) se = math.sin(eps) ce = math.cos(eps) d = 0. points = [] while d <= 360...
bigcode/self-oss-instruct-sc2-concepts
import string def removePunctuations(target): """ this function takes in a string, and returns it after removing all leading and trailing punctuations string.punctuation !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ logic: to find a starting index and ending index to slice the string """ # initialise...
bigcode/self-oss-instruct-sc2-concepts