seed
stringlengths
1
14k
source
stringclasses
2 values
def _which_asm_has_finer_mesh(asm, neighbor=None): """Determine which assembly has finer meshing Parameters ---------- asm1 : DASSH Assembly object Active assembly around which we are creating mesh asm2 (optional) : DASSH Assembly object Neighboring assembly across active hex side ...
bigcode/self-oss-instruct-sc2-concepts
def crop(vol, mins, maxs): """ Crops the input volume. Parameters ---------- vol : ndarray Volume to crop. mins : array Array containg minimum index of each dimension. maxs : array Array containg maximum index of each dimension. Returns ------- vol : ndarray...
bigcode/self-oss-instruct-sc2-concepts
def get_gc(seq_str): """ Return GC content from a sequence string. """ return float(seq_str.count('G') + seq_str.count('C')) / len(seq_str)
bigcode/self-oss-instruct-sc2-concepts
def transpose_imat(nrows, ncols, nnz, imat): """Transpose an index matrix iterator""" def data(): for i, j, v in imat: yield j, i, v return ncols, nrows, nnz, data()
bigcode/self-oss-instruct-sc2-concepts
def get_objs(content, vimtype): """ Get all the vsphere objects associated with a given type """ obj = {} container = content.viewManager.CreateContainerView( content.rootFolder, vimtype, True) for c in container.view: obj.update({c.name: c}) return obj
bigcode/self-oss-instruct-sc2-concepts
def get_value_by_name(en, name): """ Returns value by name from enums """ for n in en: if n.name == name: return n.value
bigcode/self-oss-instruct-sc2-concepts
import random def noiseFilter(move, noise): """Turns 'move' into its opposite with the probability noise.""" if random.random() < noise: if move == 1: return 0 else: return 1 else: return move
bigcode/self-oss-instruct-sc2-concepts
def detach_var(var): """Detaches a var from torch Args: var (torch var): Torch variable that requires grad Returns: TYPE: numpy array """ return var.cpu().detach().numpy()
bigcode/self-oss-instruct-sc2-concepts
from typing import Callable from typing import Tuple from typing import Any import time def retry_call(callabl: Callable, args=None, kwargs=None, exceptions: Tuple[Any, ...] = (), retries: int = 10, wait: float = 0.1) -> Any: """ Make ...
bigcode/self-oss-instruct-sc2-concepts
def identity(frame): """ Identity function to return an input frame. """ return frame
bigcode/self-oss-instruct-sc2-concepts
def takeBlock(aList, row_l,row_r,col_l,col_r): """ Take sublist given from row row_l to row_r and column col_l to col_r from a double list. The convention for the index of the rows and columns are the same as in slicing. """ result = [] for aRow in aList[row_l:row_r]: result.append(aRow[col_l:col_r]) re...
bigcode/self-oss-instruct-sc2-concepts
import re def parse_event_fields(lines, idx, event_dict): """ Parses lines from a proto file that contain an event definition and stores it in event_dict """ fields = [] end_of_event = False # record all fields in event definition. # note: we don't check if there's a leading brace. ...
bigcode/self-oss-instruct-sc2-concepts
def _predict_fn(input_data, model): """Apply model to the incoming request. :param input_data: The request data in a Pandas Dataframe format. :param model: The loaded model for prediction. :return: Predicted results. """ return model.predict(input_data).values[:]
bigcode/self-oss-instruct-sc2-concepts
def fv(rate_ : float, nper : int, pmt : float, pv_ : float = 0, type_ : int = 0) -> float: """ Calculates the future value of a loan based on a constant interest rate. Parameters ---------- rate_ : float The interest rate per period. nper : int The total number of payment period...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def temporary_frameworks( tmp_path, test_input_request_template: str, test_input_aqa: str, ) -> Path: """Create a temporary frameworks folder with sub-folders, and files.""" # Create a temporary folder dir_example = tmp_path.joinpath("example") # Create a tempora...
bigcode/self-oss-instruct-sc2-concepts
import array def get_hex(code_seq): """Return a hex representation of a string. This function does not remove the delimiter code. Parameters ---------- code_seq : bytearray A sequence of character codes. Returns ------- dump : str E.g. "26 24 12 24 DC 0E AC". """...
bigcode/self-oss-instruct-sc2-concepts
def parse_value_bitmask(bitstring): """Parse a ternary string specifying a bitmask. The bitmask is given as a string of 36 bits, written with the most significant bit on the left and the least significant bit on the right. A 0 or 1 overwrites the corresponding bit in the value, while an X leaves the bi...
bigcode/self-oss-instruct-sc2-concepts
def _maybe_append_seq(n, prefix): """Append a sequence value to a prefix if non-zero""" if not n: return prefix return f"{prefix} {n}"
bigcode/self-oss-instruct-sc2-concepts
def create_data_model(distance_matrix, pickup_delivery_pair, num_drivers: int, depot: int): """Stores the data for the problem.""" data = {} data['distance_matrix'] = distance_matrix data['pickups_deliveries'] = pickup_delivery_pair data['num_vehicles'] = num_drivers data['depot'] = depot re...
bigcode/self-oss-instruct-sc2-concepts
def get_h5_attributes(stack): """Get attributes from a stack.""" element_size_um = axislabels = None if 'element_size_um' in stack.attrs.keys(): element_size_um = stack.attrs['element_size_um'] if 'DIMENSION_LABELS' in stack.attrs.keys(): axislabels = stack.attrs['DIMENSION_LABELS'] ...
bigcode/self-oss-instruct-sc2-concepts
def capacity_cost_rule(mod, prj, prd): """ The capacity cost of projects of the *fuel_spec* capacity type is a pre-specified number with the following costs: * fuel production capacity x fuel production fixed cost; * fuel release capacity x fuel release fixed cost; * fuel storage capacity x fuel...
bigcode/self-oss-instruct-sc2-concepts
def reaction_needs_internal_standard(message): """Whether any analysis uses an internal standard.""" for outcome in message.outcomes: for analysis in outcome.analyses.values(): if analysis.uses_internal_standard: return True return False
bigcode/self-oss-instruct-sc2-concepts
import re def valid_sql_in_clause_str(input_str): """Validates if input is comma separated, single quoted strings. Returns: True: valid False: Invalid For example: True: "'1', '2345'" "'1'" False: "1, 2345" "'abc', 'xy...
bigcode/self-oss-instruct-sc2-concepts
def media_ponderada(valores, pesos): """ Encontra a média ponderada de 'valores'. Parâmetros: listas de floats. Retorna: a média ponderada de 'valores'. """ soma_media = 0 soma_peso = 0 for i in range(len(valores)): soma_media += valores[i]*pesos[i] soma_peso += pesos[...
bigcode/self-oss-instruct-sc2-concepts
def chessboard_3DPoints(board_size, square_size): """ - board_size: a tuple (rows,columns) representing the number of rows and columns of the board. - square_size: the size of a square (cell) on the board in mm """ corners = [] for col in range(0, board_size[1]): for row in range(0,...
bigcode/self-oss-instruct-sc2-concepts
def get_is_tors_list(mode_dict): """ A list contains the boolean values of each mode to determine if the normal mode is internal rotation or not. """ is_tors_list = [] for mode in sorted(mode_dict.keys()): is_tors = True if mode_dict[mode]['mode'] == 'tors' else False is_tors_li...
bigcode/self-oss-instruct-sc2-concepts
def parse_gpkgb_header_size(gpkg_wkb): """ Parse header of geopackage wkb and return its size """ # some constants no_envelope_header_size = 8 flag_byte_pos = 3 envelope_size_mask = 14 try: flag_byte = gpkg_wkb[flag_byte_pos] except IndexError: return -1 # probably some inv...
bigcode/self-oss-instruct-sc2-concepts
def get_midpoint(bounding_box): """ Get middle points of given frame Arguments: ---------- bounding_box : (width,height) or (x, y, w, h) """ if(len(bounding_box) == 2): width, height = bounding_box y = float(height) / float(2) x = float(width) / float(2) return (i...
bigcode/self-oss-instruct-sc2-concepts
def safe_short_path(file_): """Like `File.short_path` but safe for use with files from external repositories. """ # Note: "F" is "File", "FO": is "File.owner". (Lifted from genpkg.bzl.) # | File type | Repo | `F.path` | `F.root.path` | ...
bigcode/self-oss-instruct-sc2-concepts
def _transform_hostname_to_http_endpoint(hostnames): """Convert hostnames to status page endpoint. Args: hostnames: List of server names Returns a list of urls in the format "http://<hostname>/status" """ return ["http://{}/status".format(server) for server in hostnames]
bigcode/self-oss-instruct-sc2-concepts
def akm(m: int, n: int) -> int: """ Ackmann 函数 Args: m (int):m >= 0 n (int):n >= 0 Returns: int """ assert m >= 0 and n >= 0, 'm, n must greater than 0' if m == 0: return n + 1 elif n == 0: return akm(m - 1, 1) else: # n > 0 return akm(...
bigcode/self-oss-instruct-sc2-concepts
def dollarsToEuros(dollar): """ Convert dollar to euros (valid in 21/06/2021) The input format is '$1,200.35' """ return round(0.84*float(dollar[1::].replace(',','')))
bigcode/self-oss-instruct-sc2-concepts
def convert_bool_to_char(value=False): """Convert boolean to SIP2 char representation.""" return 'Y' if value else 'N'
bigcode/self-oss-instruct-sc2-concepts
import time def to_mmss(time_input): """ Converts a time based integer (in seconds) to MM:SS format. """ return time.strftime("%M:%S", time.gmtime(time_input))
bigcode/self-oss-instruct-sc2-concepts
def get_len(in_string, max_len): """Calculate string length, return as a string with trailing 0s. Keyword argument(s): in_string -- input string max_len -- length of returned string """ tmp_str = str(len(in_string)) len_to_return = tmp_str for _ in range(max_len - len(tmp_str)): ...
bigcode/self-oss-instruct-sc2-concepts
def _extra_urls(entry): """Returns a dict of URL types to URLs, e.g. { 'nytimes': 'http://nytimes.com/story/about/research.html', ... } """ urls = {} for k, v in entry.fields.items(): k = k.lower() if not k.endswith('_url'): continue k = k[:-4] ...
bigcode/self-oss-instruct-sc2-concepts
def age_ceiling(age: float, max_age=85) -> float: """ Given an *age*, returns the same *age* unless it exceeds the *max_age*, in which case the *max_age* is returned. """ return min(age, max_age)
bigcode/self-oss-instruct-sc2-concepts
import torch def inference_single_frame(model, data, return_heatmap=False, beautify_results=True): """ Does inference for model of a given a single data object. Arguments: model MMDataParallel/nn.Module in eval mode data dict( img torch.Tensor ...
bigcode/self-oss-instruct-sc2-concepts
def find_histogram_range(histogram): """ Find the min and max index where histogram value is larger than zero. :param histogram: A histogram, e.g. an output of cv.calcHist(). :returns: The min and max index with larger-than-zero value """ size = len(histogram) min_i = 0 while min_i < si...
bigcode/self-oss-instruct-sc2-concepts
def is_sublist(l1, l2, pos=False): """ Check if l1 is a sublist of l2 (it contains all elements from l1 in the same order). if pos is True, return position where sublist starts, not a boolean value """ if l1 == []: return 0 if pos else True elif l1 == l2: return 0 if pos else Tr...
bigcode/self-oss-instruct-sc2-concepts
def _get_token_ids(token_word_ids, span_word_id, offset=1): """Retrieve token ids based on word ids. Args: token_word_ids: the list of word ids for token. span_word_id: int. the word id in the original string. offset: int. if the tokenized sequence is prepended with special token, this o...
bigcode/self-oss-instruct-sc2-concepts
def ndk(name): """ Return the NDK version of given name, which replace the leading "android" to "acamera" Args: name: name string of an entry Returns: A NDK version name string of the input name """ name_list = name.split(".") if name_list[0] == "android": name_list[0] = "acamera" return...
bigcode/self-oss-instruct-sc2-concepts
import socket def ip_str_to_bytes(ip): """Convert an IP string to a four-byte bytes. :param ip: IP address string, e.g. '127.0.0.1' :return 4-byte representation of ip, e.g. b'\x7F\x00\x00\x01' :rtype bytes :raises ValueError if ip is not a legal IP address. """ try: return sock...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def date_subdir(name): """ define function to construct date sub-directories from FTS product-name """ return Path(name[9:13], name[13:15], name[15:17], name)
bigcode/self-oss-instruct-sc2-concepts
def exif_resolution_unit(value): """ ResolutionUnit可读化 :param value: int :return: description """ dict_desc = {'1': 'cm', '2': 'Inch', '3': 'km'} return dict_desc.get(str(value) if isinstance(value, int) else value, '')
bigcode/self-oss-instruct-sc2-concepts
def weight_to_duro(weight, boardside=True): """ Takes a weight in KG and returns an appropriate duro bushing. """ bushings = [78, 81, 85, 87, 90, 93, 95, 97] if not boardside: weight -= 5 weight -= 40 if weight < 0: weight = 0 approx_duro = ((weight) ** 0.66 ) + 79 duro = min(bushings, k...
bigcode/self-oss-instruct-sc2-concepts
def lorentz_berthelot_rule(sig_A, sig_B, eps_A, eps_B): """ Lorentz-Berthelot rules for combining LJ paramters. Parameters ----------- sig_A: float sig_B: float input sigma values eps_A: float eps_B: float input epsilon values Returns -------- float ...
bigcode/self-oss-instruct-sc2-concepts
def new_ccf(rw, purity): """ Compute CCF with estimate of purity :param rw: row (variant) :param purity: purity :return: CCF of each variant """ vaf = rw['t_alt_reads']/(rw['t_ref_reads']+rw['t_alt_reads']) # definition of CCF rw['ccf'] = vaf*(purity*rw['cnv_facets'] + (1-purity)*2...
bigcode/self-oss-instruct-sc2-concepts
def find_array_start_position(big_array, small_array): """ Find the starting index of a sub_array inside of a larger array Returns -1 if the small_array is not contrained within the larger array Arguments: big_array (arr) : the larger array to search through small...
bigcode/self-oss-instruct-sc2-concepts
def isWinner(board, player): """Return True if player is a winner on this TTTBoard.""" b, p = board, player # Shorter names as "syntactic sugar". # Check for 3 marks across the 3 rows, 3 columns, and 2 diagonals. return ((b['1'] == b['2'] == b['3'] == p) or # Across the top (b['4'] == b['5']...
bigcode/self-oss-instruct-sc2-concepts
def first_or_default(items, default=None): """ Helper method to fetch first element of list (if exists) """ for item in items: return item return default
bigcode/self-oss-instruct-sc2-concepts
def has_same_digits(num1: int, num2: int) -> bool: """ Return True if num1 and num2 have the same frequency of every digit, False otherwise. digits[] is a frequency table where the index represents the digit from 0-9, and the element stores the number of appearances. Increment the respective in...
bigcode/self-oss-instruct-sc2-concepts
def strip_node_name(node_name): """Strips off ports and other decorations to get the underlying node name.""" if node_name.startswith("^"): node_name = node_name[1:] return node_name.split(':')[0]
bigcode/self-oss-instruct-sc2-concepts
def _ComputeDeltas(old_items, new_items): """Finds the added and removed items in a new set compared to an old one. Args: old_items: A collection of existing items. Could be a list or set. new_items: Another collection of items. Returns: A pair of sets (added, removed). """ old, new = set(old_it...
bigcode/self-oss-instruct-sc2-concepts
def _string_left(self, nchars): """ Return left-most up to N characters from each string. Convenience use of substr. Returns ------- substrings : type of caller """ return self.substr(0, length=nchars)
bigcode/self-oss-instruct-sc2-concepts
def rescale(range1, range2): """Return a function that resizes values from range1 to values in range2 This is useful for interpolating values from one range to another """ min1, max1, min2, max2 = min(range1), max(range1), min(range2), max(range2) def resize(value): return (((value - mi...
bigcode/self-oss-instruct-sc2-concepts
def _autoconvert(value): """Convert to int or float if possible, otherwise return string""" try: return int(value) except ValueError: pass try: return float(value) except ValueError: return value
bigcode/self-oss-instruct-sc2-concepts
def all_transitions(transition_lists): """ Given a list of transition lists, combine them all into a list of unique transitions. """ transitions = set() for trans_list in transition_lists: for trans in trans_list: transitions.add(trans) return sorted(transitions)
bigcode/self-oss-instruct-sc2-concepts
def check_site_id(args, json_payload): """Return True if site_id matches one of configured site_ids""" if args.site_id: site_id = json_payload.get("site_id", "default") return site_id in args.site_id return True
bigcode/self-oss-instruct-sc2-concepts
def _check_for_unknown_fields(cls, data): """ Checks for keys in a dictionary that don't exist as fields on a model. :param cls: The ``Model`` class to validate ``data`` against. :param data: A dict with keys to validate. :returns: Errors of the fields that were not presen...
bigcode/self-oss-instruct-sc2-concepts
def cin(prompt=">> ", default="q", raw=False): """ A general prompt for operator input. Kind of simulates a terminal. Will display whatever prompt is (with no newlines, unless they are explicitly in prompt) and accept input from the operator. If the user enteres nothing or whitespaces only, then the prompt wi...
bigcode/self-oss-instruct-sc2-concepts
def filter_match_kwargs(kwargs, children=False): """ Filters out kwargs for Match construction :param kwargs: :type kwargs: dict :param children: :type children: Flag to filter children matches :return: A filtered dict :rtype: dict """ kwargs = kwargs.copy() for key in ('pat...
bigcode/self-oss-instruct-sc2-concepts
def Gain_22(RS, TS, URU, tdiffuse): """ Two sphere gain in T sphere for light starting in T sphere. Similarly, when the light starts in the second sphere, the gain for light on the detector in the second sphere $G_{22}$ is found by switching all primed variables to unprimed. Thus $G_{21}(r_s,t_s)$...
bigcode/self-oss-instruct-sc2-concepts
import operator def transcript_exons_to_bed12(exons_list, transcript_id): """ Convert a list of exon Genomic Intervals from a transcripts (from HTseq) to bed12 line """ blockSizes = [] blockStarts = [] sorted_exons = sorted(exons_list, key=operator.attrgetter("iv.start")) chrom = sorted_e...
bigcode/self-oss-instruct-sc2-concepts
def merge(dict1, dict2): """ Recursive merge dictionaries. :param dict1: Base dictionary to merge. :param dict2: Dictionary to merge on top of base dictionary. :return: Merged dictionary """ for key, val in dict1.items(): if isinstance(val, dict): dict2_node = dict2.setd...
bigcode/self-oss-instruct-sc2-concepts
import re def title_sortkey(s): """Transform a document title into a key useful for sorting and partitioning documents. >>> title_sortkey("The 'viewstate' property") == 'viewstateproperty' True """ s = s.lower() if s.startswith("the "): s = s[4:] # filter away all non-word charac...
bigcode/self-oss-instruct-sc2-concepts
def is_publication(record): """Check if a given record is a published record. Returns: bool: True if the record is a published record, else False. """ return record.json['$schema'].endswith('#/json_schema')
bigcode/self-oss-instruct-sc2-concepts
def _maybe_expand_batchnorm_weights(model_dict, state_dict, num_splits): """Expands the weights of the BatchNorm2d to the size of SplitBatchNorm. """ running_mean = 'running_mean' running_var = 'running_var' for key, item in model_dict.items(): # not batchnorm -> continue if not ru...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path import pickle def read_pickle_dict(filename, folder='C:/Users/Avram/Dropbox (MIT)/MIT' '/Research/Thesis/Sections/mod_studies/'): """Read ptrac data dictionary from pickle file.""" if folder == '': folder = Path.cwd() # set folder ='' to use current dir...
bigcode/self-oss-instruct-sc2-concepts
def ge(a, b): """Is a >= b?""" if a[0] > b[0]: return True if a[0] < b[0]: return False return a[1] >= b[1]
bigcode/self-oss-instruct-sc2-concepts
def active_queues(state): """List the task queues a worker is currently consuming from.""" if state.consumer.task_consumer: return [dict(queue.as_dict(recurse=True)) for queue in state.consumer.task_consumer.queues] return []
bigcode/self-oss-instruct-sc2-concepts
def clean(df): """ Clean the input datframe with a specific strategy. Input df :[pandas.DataFrame] with the raw data Output df :[pandas.DataFrame] with the rows containing na removed """ return df.dropna(axis=0)
bigcode/self-oss-instruct-sc2-concepts
def get_stat( dance, player, stat ): """ Accepts a bin representing the player and a string representing the stat and returns the stat's value. """ return dance[ str(player) ][ str(stat) ]
bigcode/self-oss-instruct-sc2-concepts
import pickle def load_keypoints_boxes(vid_path, i): """ Given a video path, with .pkl file included, load the keypoints & boxes """ keypoints = pickle.load(open(vid_path + "keypoints_vid"+str(i)+".pkl", "rb")) keypoints[:, 0, :] = keypoints[:, 0, :]*1.40625 + 280 keypoints[:, 1, :] = keypoints[:, 1, :]*1...
bigcode/self-oss-instruct-sc2-concepts
def xyxy2xywh(bbox): """ change bbox to coco format :param bbox: [x1, y1, x2, y2] :return: [x, y, w, h] """ return [ bbox[0], bbox[1], bbox[2] - bbox[0], bbox[3] - bbox[1], ]
bigcode/self-oss-instruct-sc2-concepts
def differentiate(coefficients): """ Calculates the derivative of a polynomial and returns the corresponding coefficients. """ new_cos = [] for deg, prev_co in enumerate(coefficients[1:]): new_cos.append((deg+1) * prev_co) return new_cos
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterator def limit( dictset: Iterator[dict], limit: int): """ Returns up to 'limit' number of records """ counter = limit for record in dictset: if counter == 0: return None counter -= 1 yield record
bigcode/self-oss-instruct-sc2-concepts
import re def is_valid_relation(line: str) -> bool: """Check if the line is a valid binary relation annotation.""" regex = r'^R\d+\t\w+ \w+:T\d+ \w+:T\d+$' return re.fullmatch(regex, line) is not None
bigcode/self-oss-instruct-sc2-concepts
def format_walk_time(walk_time): """ takes argument: float walkTime in seconds returns argument: string time "xx minutes xx seconds" """ if walk_time > 0.0: return str(int(walk_time / 60.0)) + " minutes " + str(int(round(walk_time % 60))) + " seconds" else: return "Walk time is ...
bigcode/self-oss-instruct-sc2-concepts
def bitwise_and_2lists(list1, list2): """ Takes two bit patterns of equal length and performs the logical inclusive AND operation on each pair of corresponding bits """ list_len = len(list2) return_list = [None] * list_len for i in range(list_len): return_list[i] = list1[i] & list2[i...
bigcode/self-oss-instruct-sc2-concepts
import json def json_output(response: dict) -> str: """ Output API response in prettified JSON format Parameters ---------- response : dict Returns ------- str """ return json.dumps(response, indent=2, sort_keys=True)
bigcode/self-oss-instruct-sc2-concepts
def read_file(file): """ Reads a file. Parameters: file: Path to the file. Returns: The content of the file. """ with open(file, 'r') as f: return f.read()
bigcode/self-oss-instruct-sc2-concepts
def mode_dict(lst): # It returns a dict that contains frequencies of the input. """ >>> mode_dict([3,3,4,4,5,5,6]) {3: 2, 4: 2, 5: 2, 6: 1} >>> mode_dict(["x","y","x"]) {'x': 2, 'y': 1} """ unique_values = {i: 0 for i in list(set(lst))} for i in lst: if i in unique_values.keys():...
bigcode/self-oss-instruct-sc2-concepts
import re def path_contain_regex(path, path_reg=None): """ test if a path string contains regular expression """ if path_reg is None: return True return bool(re.search(path_reg, path))
bigcode/self-oss-instruct-sc2-concepts
def get_all_subclasses(klass): """Return all subclasses of a class Use Python introspection to list all subclasses of the given class. This function do not stop to the direct children, but walk the whole inheritance tree. :param klass: the root class to use for introspection :type klass: T ...
bigcode/self-oss-instruct-sc2-concepts
def asint(val, minimum=None, maximum=None): """Converts a value into an integer :param val: value to convert :param minimum: if specified, this determines the lower boundary for the returned value, defaults to None :param maximum: if specified, this determines the upper boundary for the...
bigcode/self-oss-instruct-sc2-concepts
import six def check_iterable(value): """Check if a value is iterable (list), but not a string. The checking process is done by trying the `iter` method of Python and matching if the value is a string or not. Parametes --------- value: any Value to be checked if it is iterable. ...
bigcode/self-oss-instruct-sc2-concepts
def amtszeit_ende_isnull(value): """ Template-Filter, der prüft, ob der übergebene Wert None ist. :param value: Der Wert, der überprüft werden soll :type value: any :return: True, wenn der Wert None ist, sonst False. :rtype: bool """ if value is None: return True re...
bigcode/self-oss-instruct-sc2-concepts
import posixpath import ntpath def as_winpath(location): """ Return a Windows-like path using Windows path separators (backslash or "\") for a `location` path. """ return location.replace(posixpath.sep, ntpath.sep)
bigcode/self-oss-instruct-sc2-concepts
def _GenerateDeviceHVInfoStr(hvinfo): """Construct the -device option string for hvinfo dict PV disk: virtio-blk-pci,id=disk-1234,bus=pci.0,addr=0x9 PV NIC: virtio-net-pci,id=nic-1234,bus=pci.0,addr=0x9 SG disk: scsi-generic,id=disk-1234,bus=scsi.0,channel=0,scsi-id=1,lun=0 @type hvinfo: dict @param hvin...
bigcode/self-oss-instruct-sc2-concepts
import re def date_to_version(tag): """Convert a tag from YYYYMMDD to y.M.D where y is years after 2020.""" if re.match(r"\d\d\d\d\d\d\d\d", tag): year = int(tag[2:4]) - 20 month = int(tag[4:6]) day = int(tag[6:8]) return f"{year}.{month}.{day}" return tag
bigcode/self-oss-instruct-sc2-concepts
def neighbours_alive_count(grid, row, col): """ Takes a grid and a position and returns the number of living neighbour cells.""" rows = range(max(0, row - 1), min(len(grid) - 1, row + 1) + 1) cols = range(max(0, col - 1), min(len(grid[0]) - 1, col + 1) + 1) return len([1 for x in cols for y in rows ...
bigcode/self-oss-instruct-sc2-concepts
def _partial_match(buffer, string, safe_size): """ Helper to handle the possible edge case of a string partially occurring at the end of buffer currently under analysis. @param buffer buffer to inspect @param string string to find @param safe_size size of buffer suffix where the partial match i...
bigcode/self-oss-instruct-sc2-concepts
import math def z_dir_imp_factor(z, num_waves, total_wave_length, **kwargs): """ Returns the imperfection factor based on the z-direction. :param float z: Coordinate in length direction. :param int num_waves: Number of half-wave lengths, either 1 or 2. :param float total_wave_length: Range of the loca...
bigcode/self-oss-instruct-sc2-concepts
def date_format(date: str) -> dict: """Formating the date for dict structure Example: >>> date = date_format("Mai 15, 2015") >>> print(date) Output: { "month": "Mai", "day": "15", "year": "2015", "full_date":...
bigcode/self-oss-instruct-sc2-concepts
def pagify(text: str, delim="\n", *, shorten_by=0, page_length=2000): """ Chunk text into manageable chunks. This does not respect code blocks or special formatting. """ list_of_chunks = [] chunk_length = page_length - shorten_by deliminator_test = text.rfind(delim) if deliminator_test...
bigcode/self-oss-instruct-sc2-concepts
def l2_norm(x): """ Calculates the l2 norm of the input tensor. Args: x: tensor, any shape tensor to take the l2 norm of. Returns: float, l2 norm of the input """ return x.view(-1).dot(x.view(-1))
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def convert_day(x): """ Converts TIME field to an integer representing the day of the week eg - 2019-02-10 -> 0 (Sunday) """ current_date = datetime.strptime(x, "%Y-%m-%dT%H:%M") return current_date.strftime('%w')
bigcode/self-oss-instruct-sc2-concepts
def isPrime(num): """ Tell whether the given number is a prime number """ if num < 1: return False if num == 1: return True for i in range(2, int(num / 2) + 1): if num % i == 0: return False return True
bigcode/self-oss-instruct-sc2-concepts
def plusMinus(arr): """Function that calculates the ratio of positive, negative and 0 values in a given array""" l = len(arr) p = 0 n = 0 z = 0 for val in arr: if val > 0: p += 1 elif val < 0: n += 1 else: z += 1 p_ratio = roun...
bigcode/self-oss-instruct-sc2-concepts