seed
stringlengths
1
14k
source
stringclasses
2 values
def reformatExampleBlock(lines, name): """Turn an example block into a verbatim text. """ out = [u'::', u''] out += lines # safety line out.append(u'') return out
bigcode/self-oss-instruct-sc2-concepts
def chr_less(chr_left, chr_right, sorted_lex): """ Returns true if the left chromosome comes before the right or is the same. Args: chr_left = (string) the left chromsome being compared chr_right = (string) the right chromosome being compared sorted_lex = true if file sorted lexicog...
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional import re def get_package_version( package_xml_path: str, ) -> Optional[str]: """ Get a package's version from its package.xml file. :param package_xml_path: the path to the package's package.xml file :return: the version, or None if it failed """ version = Non...
bigcode/self-oss-instruct-sc2-concepts
def find_subnet_nat_instance(subnet_id, ec2_conn, vpc_conn): """ Find the NAT instance for the given subnet :param subnet_id: The desired subnet :param ec2_conn: A boto.ec2.connect_to_region() object :param vpc_conn: A boto.vpc.connect_to_region() object :return: The NAT instance public IP "...
bigcode/self-oss-instruct-sc2-concepts
import json def eval_functions_dumps(obj): """ This is a replacement for json.dumps that does not quote strings that start with 'function', so that these functions are evaluated in the HTML code. """ if isinstance(obj, str): if obj.lstrip().startswith("function"): return ob...
bigcode/self-oss-instruct-sc2-concepts
def edge(geom): """ return a polygon representing the edge of `geom` """ h = 1e-8 try: geomext = geom.exterior except: try: geomext = geom.buffer(h).exterior except: geomext = geom return geomext
bigcode/self-oss-instruct-sc2-concepts
def prime_sieve(num: int) -> list[int]: """ Returns a list with all prime numbers up to n. >>> prime_sieve(50) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] >>> prime_sieve(25) [2, 3, 5, 7, 11, 13, 17, 19, 23] >>> prime_sieve(10) [2, 3, 5, 7] >>> prime_sieve(9) [2, 3,...
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple from pathlib import Path def get_relative_and_absolute_paths(path: str) -> Tuple[str, str]: """Get relative (if possible) and absolute versions of path.""" absolute_path = Path(path).resolve() try: relative_path = absolute_path.relative_to(Path.cwd()) except ValueError...
bigcode/self-oss-instruct-sc2-concepts
def getRequestRedirectForRole(entity, role_name): """Returns the redirect to create a request for a specific role. """ result ='/%s/request/%s' % ( role_name, entity.key().id_or_name()) return result
bigcode/self-oss-instruct-sc2-concepts
def run_log_retention_in_days() -> int: """How many days to keep node run times, output logs and system statistics""" return 30
bigcode/self-oss-instruct-sc2-concepts
import hashlib def get_hashed_string(s): """Given a string s return a sha1 hashed version""" return hashlib.sha1(s.encode('utf-8')).hexdigest()
bigcode/self-oss-instruct-sc2-concepts
def hosts_contain_id(hosts_data, host_id): """ True if host_id is id of a host. :param hosts_data: list of hosts :param host_id: id of a host :return: True or False """ for host in hosts_data: if host_id == host['id']: return True return False
bigcode/self-oss-instruct-sc2-concepts
import re def validate_gene_sets(genesets, var_names, context=None): """ Check validity of gene sets, return if correct, else raise error. May also modify the gene set for conditions that should be resolved, but which do not warrant a hard error. Argument gene sets may be either the REST OTA form...
bigcode/self-oss-instruct-sc2-concepts
from typing import Set def all_subclasses(cls) -> Set: """Return all (transitive) subclasses of cls.""" res = set(cls.__subclasses__()) for sub in res.copy(): res |= all_subclasses(sub) return res
bigcode/self-oss-instruct-sc2-concepts
import hashlib def string_to_md5(content): """Calculate the md5 hash of a string. This 'string' can be the binary content of a file too.""" content = content.encode("utf8") return hashlib.md5(content).hexdigest()
bigcode/self-oss-instruct-sc2-concepts
def with_request(method): """ Decorator to enable the request to be passed as the first argument. """ method.with_request = True return method
bigcode/self-oss-instruct-sc2-concepts
def _GetHoles(i, n, cont, assigned): """Find holes for path i: i.e., unassigned paths directly inside it. Directly inside means there is not some other unassigned path k such that path such that path i contains k and path k contains j. (If such a k is already assigned, then its islands have been assign...
bigcode/self-oss-instruct-sc2-concepts
def get_unique_office_name(element=None): """Provide an autogenerated unique <office:name> for the document. """ if element is not None: body = element.document_body else: body = None if body: used = body.get_office_names() else: used = [] # unplugged current ...
bigcode/self-oss-instruct-sc2-concepts
def key(row, key_attributes): """Return a key for identifying equivalent rows. Return a key consisting of a tuple of the key attributes for the row, which should be a dict-like object. Parameters ---------- row : dict-like The row for which to create a key. key_attributes : List[st...
bigcode/self-oss-instruct-sc2-concepts
def get_cluster_status(els): """Function: get_cluster_status Description: Return status of the Elasticsearch cluster. Arguments: (input) els -> ElasticSearch instance. (output) Status of the Elasticsearch cluster. """ return els.cluster.health()["status"]
bigcode/self-oss-instruct-sc2-concepts
def convert_words_to_id(corpus, word2id): """Convert list of words to list of corresponding id. Args: corpus: a list of str words. word2id: a dictionary that maps word to id. Returns: converted corpus, i.e., list of word ids. """ new_corpus = [-1] * len(corpus) for i, wo...
bigcode/self-oss-instruct-sc2-concepts
def endfInterpolationLine( interpolation ) : """Makes one ENDF interpolation line.""" s = '' for d in interpolation : s += "%11d" % d for i1 in range( len( interpolation ), 6 ) : s += "%11d" % 0 return( s )
bigcode/self-oss-instruct-sc2-concepts
def glob_to_regex(pattern): """Given a glob pattern, return an equivalent regex expression. :param string glob: The glob pattern. "**" matches 0 or more dirs recursively. "*" only matches patterns in a single dir. :returns: A regex string that matches same paths as the input glob does. """...
bigcode/self-oss-instruct-sc2-concepts
def endf_float_str(value): """ Return the ENDF format string of a floating point number Parameters ---------- value : float A single floating point value Returns ------- valstring : str An ENDF format string of input par `value` """ if(abs(value) < 1e-9 or abs(v...
bigcode/self-oss-instruct-sc2-concepts
def next_permutation(seq): """Emulation of C++ std::next_permutation: Treats all permutations of seq as a set of "dictionary" sorted sequences. Permutes the current sequence into the next one of this set. Returns true if there are more sequences to generate. If the sequence is the largest of the set, the smal...
bigcode/self-oss-instruct-sc2-concepts
def condense_into_single_line(text): """ Remove all the newlines from a block of text, compressing multiple lines of HTML onto a single line. Used as a Jinja2 filter. """ lines = [line.lstrip() for line in text.split('\n')] return ''.join(lines)
bigcode/self-oss-instruct-sc2-concepts
def get_table_count(connection, table): """ Return the number of table entries. :param connection: A database connection instance :param str table: Name of the database table :return: The number of table entries :rtype: int """ sql = 'SELECT COUNT(*) FROM {table};'.format(table=table) ...
bigcode/self-oss-instruct-sc2-concepts
def _clear_entity_type_registry(entity, **kwargs): """Clear the given database/collection object's type registry.""" codecopts = entity.codec_options.with_options(type_registry=None) return entity.with_options(codec_options=codecopts, **kwargs)
bigcode/self-oss-instruct-sc2-concepts
def fibonacci2(number: int) -> int: """ Generate the fibonacci number for n Utilizes caching to mimic literal memoization, has lower recursive limit... 0, 1, 1, 2, 3, 5, 8, 13, .... 0 = 0 , 1 = 1, 3 = 2, etc :param number: iteration of the Fibonacci sequence :return: Fibonacci number """ ...
bigcode/self-oss-instruct-sc2-concepts
def get_tasks_args(parser): """Provide extra arguments required for tasks.""" group = parser.add_argument_group(title='tasks') # parameters for the knowledgeable dialogue generation group.add_argument('--task', type=str, required=True, help='Task name.') group.add_argument("-...
bigcode/self-oss-instruct-sc2-concepts
def clean_process_parameters(params): """ Removes any null valued parameters before passing them to the extension scripts :param dict params: :return: cleaned parameters :rtype: dict """ for key, value in params.items(): if value is None: del params[key] return param...
bigcode/self-oss-instruct-sc2-concepts
def extract_fragment_features_librosa(time_series, start_time, end_time, description, PID, EXP): """ Extracts / aggregates features in a certain time period within the time series data Parameters ---------- time_series: pandas.core.frame.DataFrame A pandas data.frame for which there is a co...
bigcode/self-oss-instruct-sc2-concepts
def b64d(n): """Return decoded values from a base64 string.""" b64 = n.decode("base64") return b64
bigcode/self-oss-instruct-sc2-concepts
def get_writetoinput_filenames(writetofile): """ Extract the writeToFile file name(s). writeToFile='tmpin_mc16_13TeV.blah:AOD.15760866._000002.pool.root.1' -> return 'tmpin_mc16_13TeV.blah' :param writetofile: string containing file name information. :return: list of file names """ fil...
bigcode/self-oss-instruct-sc2-concepts
def pdb(coords, types, a, b, c, alpha, beta, gamma, model=1): """ Return string in the protein databank atomic structure format. Arguments: coords[i, j] (float): j-th Cartesian coordinate of the i-th atom types[i] (str): chemical symbol of atom i a, b, c (float): lenghts of the three latt...
bigcode/self-oss-instruct-sc2-concepts
def divisors(num): """ Takes a number and returns all divisors of the number, ordered least to greatest :param num: int :return: list (int) """ divlist = [] counter = 0 for item in range(1, num + 1): if num % item == 0: divlist.append(item) counter = count...
bigcode/self-oss-instruct-sc2-concepts
def firstNotNone(*args): """ Returns first not-None value from a given list of arguments >>> firstNotNone(None, None, 1, 2, 3) 1 """ retVal = None for _ in args: if _ is not None: retVal = _ break return retVal
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional from typing import Union from typing import Sequence from typing import Tuple def _get_target_principal_and_delegates( impersonation_chain: Optional[Union[str, Sequence[str]]] = None ) -> Tuple[Optional[str], Optional[Sequence[str]]]: """ Analyze contents of impersonation_chain...
bigcode/self-oss-instruct-sc2-concepts
def mean(array): """ Returns the mean (average) of a numpy array :param array: A one dimensional numpy array """ return float(sum(array) / max(len(array), 1))
bigcode/self-oss-instruct-sc2-concepts
def should_quit(string_given) -> bool: """ This function determines if the string_given should exit :param string_given: :return: Returns if the string is 'q' or 'quit' """ return string_given in ['q', 'quit']
bigcode/self-oss-instruct-sc2-concepts
def linked_embeddings_name(channel_id): """Returns the name of the linked embedding matrix for some channel ID.""" return 'linked_embedding_matrix_%d' % channel_id
bigcode/self-oss-instruct-sc2-concepts
def hamming_weight(number): """Returns the number of bits set in number""" return bin(number).count("1")
bigcode/self-oss-instruct-sc2-concepts
def search_for_vertex_at_pos(chromosome, position, location_dict): """ Given a chromosome and a position (1-based), this function queries the location dict to determine whether a vertex fitting those criteria exists. Returns the row if yes, and __ if no. """ try: return location_di...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def sha256sum(file: str) -> str: """ Returns the sha256 sum of a file :param file: (str) path to file :return: (str) checksum """ sha256 = hashlib.sha256() try: with open(file, "rb") as file_handle: while True: data = file_handle.read(65...
bigcode/self-oss-instruct-sc2-concepts
def scatter_geo(ds, prop="pressure", stat="count"): """ Takes in xarray Dataset and creates a tidy and clean pandas DataFrame for plotting with plotly Parameters ---------- ds : xarray Dataset A dataset of aggregated data with a specified format prop : str, default 'pressure' ...
bigcode/self-oss-instruct-sc2-concepts
def compare_rows(row_check, dataframe_check, drop_column="idx"): """Find all the matched rows in dataframe_check given a row to check (row_check)""" # all(1) means that all items of row_check should match with # rows in dataframe_check except for drop_column dataframe_matched = dataframe_check[(datafram...
bigcode/self-oss-instruct-sc2-concepts
def search_cord_start(xy_cord): """ Find at the index of the coordinate corresponding to the coordinate -11.810 cm in order to exclude the doses at positions at which there are no detectors """ for idx in range(len(xy_cord)): if abs(xy_cord[idx] + 11.810) < 0.01: return idx
bigcode/self-oss-instruct-sc2-concepts
def get_trid_isrc_full_con(tr_id, tr_exc, exid2next_dic, nexts_cisrc_dic): """ Get intron-spanning read count for transcript with ID tr_id. Also return if transcript exons are fully connected by intron-spanning reads (True, False). tr_id: Transcript ID tr_exc: Transcript exon c...
bigcode/self-oss-instruct-sc2-concepts
def aic_scorer(estimator, X, y_true = None) -> float: """AIC score for Gaussian Mixture Model Metric can be used in GridSearch for hyperparameter tuning :param estimator: must have ``aic`` method which returns aic score :param X: :param y_true: :return: the protocol requires greater the better,...
bigcode/self-oss-instruct-sc2-concepts
async def read_body(receive): """ Read and return the entire body from an incoming ASGI message. """ body = b'' more_body = True while more_body: message = await receive() body += message.get('body', b'') more_body = message.get('more_body', False) return body
bigcode/self-oss-instruct-sc2-concepts
def inInfo(item,info,alt='None'): """ Checks if item is in given list. return item if true, else return alt Args: item: the item to be compared info: the list to be checked alt: alternative output """ if item in info: return info[item] ...
bigcode/self-oss-instruct-sc2-concepts
import re def extract_features_for_clustering(text): """ Extracts the presence of specific word phrase features that are used to determine the overall structure of the document. :param text: original report in str form :return: feature vector """ key_phrases = [ 'Electronically sig...
bigcode/self-oss-instruct-sc2-concepts
import json def map_category_names(cat_to_name:str, classes:list) -> list: """Map category labels to category names Args: cat_to_name: Path to JSON file with category to name mapping classes: list of predicted classes Returns: List of category names """ with open(cat_to_n...
bigcode/self-oss-instruct-sc2-concepts
def multiply(string, times): """ Repeats a string a given number of times. :param str string: given string :param number times: number of repeats :return str: repeated string """ return string * times
bigcode/self-oss-instruct-sc2-concepts
import re def extract_dependencies(content): """Extract dependencies by parsing import statements""" deps = set() for line in content.split('\n'): line = line.strip() # we don't care about indentation if not (line.startswith("from") or line.startswith("import")): ...
bigcode/self-oss-instruct-sc2-concepts
def dict_from_str(s): """Convert 'key:value, ...' string to dict.""" d = {} for item in s.split(','): key, value = item.split(':') d[key.strip()] = value.strip() return d
bigcode/self-oss-instruct-sc2-concepts
from typing import List def word_block(text: str, blocked_words: List[str], replace: str = '****') -> str: """Replace blocked words in text.""" tmp_string: str = text for word in blocked_words: if word in tmp_string: tmp_string = tmp_string.replace(word, replace) return tmp_string
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple from typing import Counter def generate_checksum_components(box: str) -> Tuple[int, int]: """ Generates the checksum components from the string and returns a tuple indicating whether a character appeared twice or thrice in string. For example a (1, 1) would indicate that at le...
bigcode/self-oss-instruct-sc2-concepts
def identity(label): """Identity function that returns the input label. Args: label: A `Tensor` or anything that can be converted to a tensor using `tf.convert_to_tensor`. Returns: The input label. """ return label
bigcode/self-oss-instruct-sc2-concepts
import torch def smooth_l1_loss(input, target, beta=1. / 9, size_average=False): """Smmoth L1 loss, as defined in the Fast R-CNN paper. Girshick, R. (2015). Fast R-CNN. """ diff = torch.abs(input - target) mask = (diff < beta) loss = torch.where(mask, 0.5 * diff ** 2 / beta, diff - 0.5 * b...
bigcode/self-oss-instruct-sc2-concepts
import torch def predict_rating(review, classifier, vectorizer, decision_threshold=0.5): """ Predict the rating of a given review :param review (str): the text to review :param classifier (ReviewClassifier): the trained model :param vectorizer (ReviewVectorizer): The correspo...
bigcode/self-oss-instruct-sc2-concepts
from typing import OrderedDict def secondary_settings(structure,form,primary_settings): """Return secondary settings, along with sensible default values. Secondary settings depend on the structure, form, and possibly primary setting values. Primary settings are defined by xrsdkit.definitions.structur...
bigcode/self-oss-instruct-sc2-concepts
import json def jsonify(obj): """Return Python objects as JSON (in bytes).""" jsonified = "{}".format(json.dumps(obj)).encode() return jsonified
bigcode/self-oss-instruct-sc2-concepts
def expected_utility(a, s, U, mdp): """The expected utility of doing a in state s, according to the MDP and U.""" return sum(p * U[s1] for (p, s1) in mdp.T(s, a))
bigcode/self-oss-instruct-sc2-concepts
import uuid def load_table(service, source_schema, source_csv, projectId, datasetId, tableId, num_retries=5): """ Starts a job to load a bigquery table from CSV Args: service: an initialized and authorized bigquery google-api-client object source_schema: a valid big...
bigcode/self-oss-instruct-sc2-concepts
def nodes_iter(topology): """Get an iterator for all nodes in the topology""" return topology.nodes_iter()
bigcode/self-oss-instruct-sc2-concepts
def indent(text, prefix=" "): """ Return `text` indented using `prefix`. """ return "\n".join(prefix + repr(line) for line in text.splitlines())
bigcode/self-oss-instruct-sc2-concepts
def format_number(num): """Format a number in a string. >>> format_number(1234567) -> '1 234 567' >>> format_number(1234.56789) -> '1 234.56' # round with 2 decimals >>> format_number(None) -> '???' >>> format_number('not a number') -> 'not a number'""" if isinstance(num, int): return f"...
bigcode/self-oss-instruct-sc2-concepts
from typing import OrderedDict def remove_repeated_elements(tokens): """ removes repeated tokens args: tokens: a list of tokens returns: filtered_tokens: a list of tokens without repeated tokens """ filtered_tokens = list(OrderedDict((token, None) for token in tokens)) return f...
bigcode/self-oss-instruct-sc2-concepts
import torch def gradient_retriever(model): """fn to retrieve gradients from model :param model: torch model :returns: gradient norm, gradient tensor :rtype: (float, tensor) """ grads = [] grad_norm = 0 for p in model.parameters(): grads.append(p.grad.clone()) grad_no...
bigcode/self-oss-instruct-sc2-concepts
def alpha (v, dt, dx): """ Calculate Courant number, alpha = v*dt/dx. For 2D, this function can be used if dx=xz """ return (v*dt/dx)
bigcode/self-oss-instruct-sc2-concepts
def funct_worker(input_list,pre_text): """ Worker Function: define function that each process should do e.g. create string from content in input_list while begin with pre_text => "[pre_text] [input_list] """ output_string = f"{pre_text}" output_string = output_string + " ".join(input_list) ...
bigcode/self-oss-instruct-sc2-concepts
def _models_count_all_function_name(model): """Returns the name of the function get the number of models in the database""" return '{}_count_all'.format(model.get_table_name())
bigcode/self-oss-instruct-sc2-concepts
def cut_file(source_file, aim_path, chunk_size): """ this function will take a source file, cut it into pieces with chunk size store them to the aim path return a list of cut names """ ori_bin = open(source_file, 'rb') chunk_list = [] while True: cur_bin = ori_bin.read(chunk_size...
bigcode/self-oss-instruct-sc2-concepts
def is_datetime(input): """ Template tag to check if input is Datetime :param input: Input field :return: True if is datetime, False if not """ return input.field.widget.__class__.__name__ == "DateTimeInput"
bigcode/self-oss-instruct-sc2-concepts
import math def get_biorhythms(days_elapsed: int): """바이오리듬을 반환합니다. Args: days_elapsed: 출생일로부터의 경과일 Returns: 바이오리듬(신체, 감성, 지성)의 튜플 """ def biovalue(circle, elaspeddays): """바이오리듬 값(%)""" return math.sin(2 * math.pi * elaspeddays / circle) * 100 physical = bi...
bigcode/self-oss-instruct-sc2-concepts
def convert_tokens_to_ids_and_pad(word_pieces, max_length, token_converter): """Converts the input tokens to padded ids and mask. Args: word_pieces: list of word-piece tokens. max_length: length sequences should be padded/truncated to. token_converter: the tokenizer used. Returns: word_piece_id...
bigcode/self-oss-instruct-sc2-concepts
def fsextract(string,method): """ Extracts the indices or filenames from a comma-separated string Input Parameters ---------------- string : str a comma separated string of either file names or file index numbers. method : {'index','filename'} 'index' if the values passed are ...
bigcode/self-oss-instruct-sc2-concepts
def GC_skew(seq, window=100): """Calculates GC skew (G-C)/(G+C) for multiple windows along the sequence. Returns a list of ratios (floats), controlled by the length of the sequence and the size of the window. Does NOT look at any ambiguous nucleotides. """ # 8/19/03: Iddo: added lowercase ...
bigcode/self-oss-instruct-sc2-concepts
def oxy_umolkg_to_ml(oxy_umol_kg, sigma0): """Convert dissolved oxygen from units of micromol/kg to mL/L. Parameters ---------- oxy_umol_kg : array-like Dissolved oxygen in units of [umol/kg] sigma0 : array-like Potential density anomaly (i.e. sigma - 1000) referenced to 0 dbar [kg/...
bigcode/self-oss-instruct-sc2-concepts
def get_exit_event(state, events): """Check if a given state has been exited at some point during an execution""" return next( ( e for e in events if e["type"].endswith("StateExited") and e["stateExitedEventDetails"]["name"] == state ), Non...
bigcode/self-oss-instruct-sc2-concepts
def validate_comparison_operator(comparison_operator): """ Validate Comparison Operator for WebACL SizeConstraintStatement Property: SizeConstraintStatement.ComparisonOperator """ VALID_COMPARISON_OPERATORS = ( "EQ", "GE", "GT", "LE", "LT", "NE", ...
bigcode/self-oss-instruct-sc2-concepts
def get_device_name_prefix(device_name): """Return device name without device number. /dev/sda1 -> /dev/sd /dev/vda -> /dev/vd """ dev_num_pos = 0 while '0' <= device_name[dev_num_pos - 1] <= '9': dev_num_pos -= 1 return device_name[:dev_num_pos - 1]
bigcode/self-oss-instruct-sc2-concepts
import struct def calc_padding(fmt, align): """Calculate how many padding bytes needed for ``fmt`` to be aligned to ``align``. Args: fmt (str): :mod:`struct` format. align (int): alignment (2, 4, 8, etc.) Returns: str: padding format (e.g., various number of 'x'). >>> ca...
bigcode/self-oss-instruct-sc2-concepts
import re def dep_base(dep): """ Strip a dependency of version requirements, for example: dep_base('foo >= 1.2.3') == 'foo' :param dep: dependency to strip version from :return: dep stripped of version requirement (str) """ dep = str(dep) m = re.match(r'([^<>!=\s]+)\s*[<>!=]', de...
bigcode/self-oss-instruct-sc2-concepts
def is_simple_requires(requires): """ Return True if ``requires`` is a sequence of strings. """ return ( requires and isinstance(requires, list) and all(isinstance(i, str) for i in requires) )
bigcode/self-oss-instruct-sc2-concepts
import math def simplify_U(theta, phi, lam): """Return the gate u1, u2, or u3 implementing U with the fewest pulses. U(theta, phi, lam) is the input gate. The returned gate implements U exactly, not up to a global phase. Return (gate_string, params, "OpenQASM string") where gate_string is one of ...
bigcode/self-oss-instruct-sc2-concepts
import urllib3 def get_wikidata_item(wikidata_id: str) -> bytes: """Get Wikidata item structure.""" return urllib3.PoolManager().request( "GET", f"https://www.wikidata.org/wiki/Special:EntityData/Q{wikidata_id}.json", ).data
bigcode/self-oss-instruct-sc2-concepts
import torch def get_targeted_classes(model, images, clip, a, b, k=5, case='avg'): """ Input: - model (pytorch model): bagnet model without avgerage pooling - images (pytorch tensor): a batch of preprocessed images, same context as model's images - k (int): get targeted classes based on top-K pr...
bigcode/self-oss-instruct-sc2-concepts
import re def safe_name(string: str) -> str: """Returns 'string' with all non-alpha-numeric characters replaced by '_'.""" return re.sub("[^A-Za-z0-9]", "_", string)
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path import csv def get_fieldnames_from_csv_file(f_name, encoding='utf-8', newline='', delimiter=','): """ Возвращает список заголовков колонок CSV-файла. :param f_name: CSV-файл :param encoding: кодировка CSV-файла :param newline: newline: new...
bigcode/self-oss-instruct-sc2-concepts
def to_int(toks): """ Parser action for converting strings of digits to int. """ return int(toks[0])
bigcode/self-oss-instruct-sc2-concepts
def get_default_token(word2vec_model): """ Returns the token from a Word2Vec model to use as a default for end-of-sequence marking. """ return "." if "." in word2vec_model.vocab.keys() else word2vec_model.index2word[0]
bigcode/self-oss-instruct-sc2-concepts
def plain_text(node): """ Return the plain text of a node with all tags ignored. This is needed where Doxygen may include refs but Sphinx needs plain text because it parses things itself to generate links. """ if node.tag == "sp": markup = " " elif node.text is not None: ma...
bigcode/self-oss-instruct-sc2-concepts
from typing import Callable def position_features(sentence: str, tokenizer: Callable, vocab: set) -> list: """Encodes the relative position of the tokens in :param sentence: as follows: - 0 for tokens at the beginning of the sentence; - 1 for tokens in the middle of the sentence; - 2 for tokens at t...
bigcode/self-oss-instruct-sc2-concepts
from typing import Callable def runge_kutta_method_o4(f: Callable[[float, float], float], y0: float, x: list[float], h: float, precission: int = 5) -> float: """Finds the value of y(x) for some ODE using Runge Kutta method (order 4). Params ------ f: Callable[[float, float], float] function r...
bigcode/self-oss-instruct-sc2-concepts
import re def clean_for_filename(string): """ Cleans up string for use in filename """ string = re.sub(r"\[.*?]", "", string) # noqa: W605 string = re.sub('\s+', ' ', string) # noqa: W605 string = string.replace(' : ', ' - ') string = string.replace(':', '-') string = string.replace('&', 'an...
bigcode/self-oss-instruct-sc2-concepts
def prod(seq): """ return the product of all numbers in seq """ p = 1 for a in seq: p *= a return p
bigcode/self-oss-instruct-sc2-concepts
def build_extensions(available_extensions): """ Builds websocket extensions header from the given extension values. Parameters ---------- available_extensions : `list` of `Any` Each websocket extension should have the following `4` attributes / methods: - `name`, type `str`. The...
bigcode/self-oss-instruct-sc2-concepts
def _byte_pad(data, bound=4): """ GLTF wants chunks aligned with 4 byte boundaries. This function will add padding to the end of a chunk of bytes so that it aligns with the passed boundary size. Parameters -------------- data : bytes Data to be padded bound : int Length ...
bigcode/self-oss-instruct-sc2-concepts