seed
stringlengths
1
14k
source
stringclasses
2 values
def add_trailing_slash(s): """Add trailing slash. """ if not s.endswith('/'): s = s + '/' return(s)
bigcode/self-oss-instruct-sc2-concepts
import torch def get_interior_points(N=10000, d=2): """ randomly sample N points from interior of [0,1]^d """ return torch.rand(N, d)
bigcode/self-oss-instruct-sc2-concepts
def calc_brightness(value: float, actual_brightness_value: int, max_brightness_value: int, function: str) -> int: """Calculate brightness value based on actual and maximal brightness. The function calculates a brightness value using the `function` string and the `value` as a percentage. If `function` is em...
bigcode/self-oss-instruct-sc2-concepts
import requests def get_html(url): """ Get HTML document from GET request from URL :param url: str URL of request :return: str HTML document """ r = requests.get(url, headers={'User-Agent': 'Custom'}) r.encoding = r.apparent_encoding print(r) return r.text
bigcode/self-oss-instruct-sc2-concepts
def lower_column(col): """ Return column from lower level tables if possible >>> metadata = sa.MetaData() >>> s = sa.Table('accounts', metadata, ... sa.Column('name', sa.String), ... sa.Column('amount', sa.Integer), ... sa.Column('id', sa.Integer, primary...
bigcode/self-oss-instruct-sc2-concepts
def tuple_replace(tup, *pairs): """Return a copy of a tuple with some elements replaced. :param tup: The tuple to be copied. :param pairs: Any number of (index, value) tuples where index is the index of the item to replace and value is the new value of the item. """ tuple_list = list(tup) ...
bigcode/self-oss-instruct-sc2-concepts
import re def separate_words(name): """Convenience function for inserting spaces into CamelCase names.""" return re.sub(r"(.)([A-Z])", r"\1 \2", name)
bigcode/self-oss-instruct-sc2-concepts
def first_is_not(l, v): """ Return first item in list which is not the specified value. If all items are the specified value, return it. Parameters ---------- l : sequence The list of elements to be inspected. v : object The value not to be matched. Example: -------...
bigcode/self-oss-instruct-sc2-concepts
def default_str(str_, default_str): """Returns :attr:`str_` if it is not `None` or empty, otherwise returns :attr:`default_str`. Args: str_: A string. default_str: A string. Returns: Either :attr:`str_` or :attr:`default_str`. """ if str_ is not None and str_ != "": ...
bigcode/self-oss-instruct-sc2-concepts
def _get_morphometry_data_suffix_for_surface(surf): """ Determine FreeSurfer surface representation string. Determine the substring representing the given surface in a FreeSurfer output curv file. For FreeSurfer's default surface 'white', the surface is not represented in the output file name pattern. For ...
bigcode/self-oss-instruct-sc2-concepts
import math def format_duration(seconds: float) -> str: """Formats duration in seconds into hours/minutes/seconds.""" if seconds < 60: return f'{seconds:.0f}s' elif seconds < 3600: minutes = math.floor(seconds / 60) seconds -= minutes * 60 return f'{minutes}m{seconds:.0f}s' else: hours = m...
bigcode/self-oss-instruct-sc2-concepts
def save_as(user): """ Returns a callback which saves the model as the user that you pass in """ def user_save(instance): instance.save(user) return user_save
bigcode/self-oss-instruct-sc2-concepts
def get_test_count(test_data): """ Args: test_data: json of test data Returns: int: total test count """ return int(test_data.get("testsuites").get("testsuite").get("@tests"))
bigcode/self-oss-instruct-sc2-concepts
def map_diameter(c: int) -> float: """ Compute the diameter """ return 1 / 3 * (c + 1) * (c - 1)
bigcode/self-oss-instruct-sc2-concepts
def label_set_match(object_labels, returned_labels): """Return True if at least one of the object labels is contained in at least one of the returned labels""" for o in object_labels: for r in returned_labels: if o.lower() in r.lower(): return True return False
bigcode/self-oss-instruct-sc2-concepts
def chain_value(row, attribute_ids): """ Join all the values of attributes to get a identifier :param row: a row of the table, e.g. a list of attribute values :param attribute_ids: a set of attribute :return: a string consists of joint value """ result = [] for attribute_id in sorted(att...
bigcode/self-oss-instruct-sc2-concepts
def shared_data_volume_container_path(sdv, sdvkey): # type: (dict, str) -> str """Get shared data volume container path :param dict sdv: shared_data_volume configuration object :param str sdvkey: key to sdv :rtype: str :return: container path """ return sdv[sdvkey]['container_path']
bigcode/self-oss-instruct-sc2-concepts
def isYes(string): """Returns True if the string represents a yes, False, if it represents no, and another string if it represents something else""" value = string.strip().lower() if value in ['yes', 'always', 'on', 'true']: return True if value in ['no', 'never', 'off', 'false', 'null']: ...
bigcode/self-oss-instruct-sc2-concepts
def _add_new_line_if_none(s: str): """Since graphviz 0.18, need to have a newline in body lines. This util is there to address that, adding newlines to body lines when missing.""" if s and s[-1] != "\n": return s + "\n" return s
bigcode/self-oss-instruct-sc2-concepts
def build_from_cfg(name, cfg, registry, default_args=None): """Build a module from config dict. Args: name (str): Name of the object cfg (addict): Config dict of the object registry (:obj:`Registry`): The registry to search the type from. default_args (dict, optional): Default i...
bigcode/self-oss-instruct-sc2-concepts
import torch def truncated_normal(size, std): """ Pytorch does not have a truncated normal function to we manually make one in order to cut the dependancy on tensorflow Modified Version of: https://discuss.pytorch.org/t/implementing-truncated-normal-initializer/4778/20 """ mean = 0 tensor ...
bigcode/self-oss-instruct-sc2-concepts
def compare_equal(compare_data): # pylint: disable=redefined-outer-name """ Returns a function which checks that a given data is equal to the stored reference. """ return lambda data, tag=None: compare_data(lambda x, y: x == y, data, tag)
bigcode/self-oss-instruct-sc2-concepts
def type_validator(property_type): """Create validator that requires specific type. Args: property_type: The type of the validator. Returns: Validator that only accepts values of a specific type. """ def type_validator_impl(value): if not isinstance(value, property_type): raise TypeError('...
bigcode/self-oss-instruct-sc2-concepts
def prod(lst): """Product of list elements.""" if len(lst) == 0: return 0 x = lst[0] for v in lst[1:]: x *= v return x
bigcode/self-oss-instruct-sc2-concepts
def get_agent_location_from_maze_string(mazeString=str): """[Get the location of the agent from the maze] Args: mazeString ([str], optional): [string of the maze location]. Defaults to str. Returns: [tuple]: [location of the maze] """ mazeString = [list(x.strip()) for x in mazeStri...
bigcode/self-oss-instruct-sc2-concepts
def decompose_path(path): """ Break a path down into individual parts Parameters ---------- path : string Path to variable on the Returns ------- structure : tuple of strings Tuple of split apart path """ return tuple((path_entry for path_entry in path.split('/')...
bigcode/self-oss-instruct-sc2-concepts
from typing import OrderedDict def groupby(items, by): """ Group items using a function to derive a key. :param items: The items to group :param by: A lambda function to create a key based on the item :return: an Ordered dict """ result = OrderedDict() for it...
bigcode/self-oss-instruct-sc2-concepts
def check_textbound_overlap(anns): """ Checks for overlap between the given TextBoundAnnotations. Returns a list of pairs of overlapping annotations. """ overlapping = [] for a1 in anns: for a2 in anns: if a1 is a2: continue if a2.start < a1.end a...
bigcode/self-oss-instruct-sc2-concepts
def det3x3(matrix): """ Calculate a determinant of a 3x3 matrix. Should be usually substituted by `numpy.linalg.det`, but is indispensable for matrices with uncertainties. :param matrix: 3x3 array/matrix which allows for 2d indexing :type matrix: numpy.ndarray or uncertainties.unumpy.matrix :re...
bigcode/self-oss-instruct-sc2-concepts
def get_counts(filename): """ reads the .counts_edit file and extracts the counts :param filename: counts file (original or simulated) :return: list of counts """ with open(filename, "r") as counts_file: counts = [] for line in counts_file: line = line.strip() ...
bigcode/self-oss-instruct-sc2-concepts
def _get_human_bytes(num_bytes): """Return the given bytes as a human friendly KB, MB, GB, or TB string thanks https://stackoverflow.com/questions/12523586/python-format-size-application-converting-b-to-kb-mb-gb-tb """ num_bytes = float(num_bytes) one_kb = float(1024) one_mb = float(one_kb ** 2)...
bigcode/self-oss-instruct-sc2-concepts
import re def get_brute(brute_file, mini=1, maxi=63, banned='[^a-z0-9_-]'): """ Generates a list of brute-force words based on length and allowed chars """ # Read the brute force file into memory with open(brute_file, encoding="utf8", errors="ignore") as infile: names = infile.read().split...
bigcode/self-oss-instruct-sc2-concepts
def get_post_from_row(post_row): """ extracts the post body from a post row """ return post_row.find("td").find("div", class_="content")
bigcode/self-oss-instruct-sc2-concepts
def get_status(query_type, command, execution_status, status_dict): """ Get the status code of a command according to a query Args: query_type (str): Type of status query, chunk in this case command (str): Command name execution_status: State of the last given command execution ...
bigcode/self-oss-instruct-sc2-concepts
def get_all_individuals_to_be_vaccinated_by_area( vaccinated_compartments, non_vaccination_state, virus_states, area ): """Get sum of all names of species that have to be vaccinated. Parameters ---------- vaccinated_compartments : list of strings List of compartments from which individuals ...
bigcode/self-oss-instruct-sc2-concepts
def get_lt(hdr): """Obtain the LTV and LTM keyword values. Note that this returns the values just as read from the header, which means in particular that the LTV values are for one-indexed pixel coordinates. LTM keywords are the diagonal elements of MWCS linear transformation matrix, while LTV...
bigcode/self-oss-instruct-sc2-concepts
import pathlib def data_file(module, *comps): """Return Path object of file in the data directory of an app.""" return pathlib.Path(module.__file__).parent.joinpath('..', 'data', *comps)
bigcode/self-oss-instruct-sc2-concepts
def depend_on_proj_props(target, source, env): """ Emitter which adds a dependency for the project properties file """ #sys.stderr.write("depend_on_proj_props called\n") #sys.stderr.flush() return (target, source + [env['XISE_PY_PROPFILE']])
bigcode/self-oss-instruct-sc2-concepts
from bs4 import BeautifulSoup from typing import List from typing import Dict import re def parse_row(row: BeautifulSoup, columns: List[str], table_id: str) -> Dict[str, str]: """Takes a BeautifulSoup tag corresponding to a single row in an HTML table as input, along with an ordered list of normalized column ...
bigcode/self-oss-instruct-sc2-concepts
def ses(count, plural='s', singular=''): """ ses is pronounced "esses". Return a string suffix that indicates a singular sense if the count is 1, and a plural sense otherwise. So, for example: log.info("%d item%s found", items, utils.ses(items)) would log: ...
bigcode/self-oss-instruct-sc2-concepts
import math def fpart(x): """Returns the fractional part of x.""" return x - math.floor(x)
bigcode/self-oss-instruct-sc2-concepts
def host_dict(host): """Convert a host model object to a result dict""" if host: return host.state else: return {}
bigcode/self-oss-instruct-sc2-concepts
def get_total_results(results): """Return the totalResults object from a Google Analytics API request. :param results: Google Analytics API results set :return: Number of results """ if results['totalResults']: return results['totalResults']
bigcode/self-oss-instruct-sc2-concepts
from typing import List def _format_results(results: list) -> List[dict]: """ Args: results: a list of results with the following format: ['"<hash>","<anchor_hash>",<score>'] Returns: a list of dictionaries containing the hash and score """ formatted_res = [] # Remove last e...
bigcode/self-oss-instruct-sc2-concepts
def textarea( rows="", span=2, placeholder="", htmlId=False, inlineHelpText=False, blockHelpText=False, focusedInputText=False, required=False, disabled=False, prepopulate=False): """ *Generate a textarea - TBS style* **Key Arg...
bigcode/self-oss-instruct-sc2-concepts
def _construct_target_subscription(_target_id, _target_type='board'): """This function constructs a dictionary for an individual subscription target to be used in a payload. .. versionadded:: 3.5.0 :param _target_id: The unique identifier for the target (e.g. Node ID) :type _target_id: str :param ...
bigcode/self-oss-instruct-sc2-concepts
def monkey_patch(cls): """ Return a method decorator to monkey-patch the given class. """ def decorate(func): name = func.__name__ func.super = getattr(cls, name, None) setattr(cls, name, func) return func return decorate
bigcode/self-oss-instruct-sc2-concepts
def pil_to_flatten_data(img): """ Convert data from [(R1, G1, B1, A1), (R2, G2, B2, A2)] to [R1, G1, B1, A1, R2, G2, B2, A2] """ return [x for p in img.convert('RGBA').getdata() for x in p]
bigcode/self-oss-instruct-sc2-concepts
def count_numeric(df): """ Returns the number of numeric variables in the dataset. Parameters: df (pandas DataFrame): Dataset to perform calculation on Returns: counter_numeric (int): Number of numeric variables in df """ counter_numeric = 0 for i in range(len...
bigcode/self-oss-instruct-sc2-concepts
def bahai_major(date): """Return 'major' element of a Bahai date, date.""" return date[0]
bigcode/self-oss-instruct-sc2-concepts
def check_alpha_signs(svm): """Returns the set of training points that violate either condition: * all non-support-vector training points have alpha = 0 * all support vectors have alpha > 0 Assumes that the SVM has support vectors assigned, and that all training points have alpha values assi...
bigcode/self-oss-instruct-sc2-concepts
import random def luck(n=2): """ gives 1 chance out of n (default: 2) to return True """ assert n > 1 return bool(random.randint(0, n-1))
bigcode/self-oss-instruct-sc2-concepts
def convert_dict(my_dict): """Convert dictionaries from Netmiko format to NAPALM format.""" new_dict = {} for k, v in my_dict.items(): new_dict[k] = v hostname = new_dict.pop('host') new_dict['hostname'] = hostname device_type = new_dict.pop('device_type') new_device_type = device_...
bigcode/self-oss-instruct-sc2-concepts
def bspline(p, j, x): """ Return the value at x in [0,1[ of the B-spline with integer nodes of degree p with support starting at j. Implemented recursively using the [De Boor's Algorithm](https://en.wikipedia.org/wiki/De_Boor%27s_algorithm) .. math:: B_{i,0}(x) := \left\{ \begin{matrix...
bigcode/self-oss-instruct-sc2-concepts
def dict_partial_from_keys(keys): """Return a function that constructs a dict with predetermined keys.""" def dict_partial(values): return dict(zip(keys, values)) return dict_partial
bigcode/self-oss-instruct-sc2-concepts
def create_accounttax_sample(account_id, **overwrites): """Creates a sample accounttax resource object for the accounttax samples. Args: account_id: int, Merchant Center ID these tax settings are for. **overwrites: dictionary, a set of accounttax attributes to overwrite Returns: A new accountt...
bigcode/self-oss-instruct-sc2-concepts
import shlex def split_args(line): """Version of shlex.split that silently accept incomplete strings. Parameters ---------- line : str The string to split Returns ------- [str] The line split in separated arguments """ lex = shlex.shlex(line, posix=True) lex.w...
bigcode/self-oss-instruct-sc2-concepts
def delete_cluster(dataproc, project, region, cluster): """Delete the cluster.""" print('Tearing down cluster.') result = dataproc.delete_cluster( project_id=project, region=region, cluster_name=cluster) return result
bigcode/self-oss-instruct-sc2-concepts
def ReshapeShortFat(original): """ ReshapeShortFat(original) Reshapes the image numpy array from original shape to the ShortFat single row shape and captures shape info in the output: channel_0, channel_1, channel_2 functionally performs original.reshape(1, x*y*z) to create single...
bigcode/self-oss-instruct-sc2-concepts
def get_class_prob(predictions_dict): """Get true and predicted targets from predictions_dict. Parameters ---------- predictions_dict : dict Dict of model predictions. Must contain "target_true" and "target_pred" keys with corresponding dict values of the form class_label : probability....
bigcode/self-oss-instruct-sc2-concepts
def generate_video_url(video_id:str)->str: """Takes video Id and generates the video url example https://www.youtube.com/watch?v=e3LqeN0e0as """ return f'https://www.youtube.com/watch?v={video_id}'
bigcode/self-oss-instruct-sc2-concepts
import base64 def base64url_encode(msg): """ Encode a message to base64 based on JWT spec, Appendix B. "Notes on implementing base64url encoding without padding" """ normalb64 = base64.urlsafe_b64encode(msg) return normalb64.rstrip(b'=')
bigcode/self-oss-instruct-sc2-concepts
def num_parameters(model): """ Returns the number of parameters in the given model Parameters ---------- model : torch.nn.Module the model to count the parameters of Returns ------- int the number of parameters in the given model """ n = 0 for p in model.pa...
bigcode/self-oss-instruct-sc2-concepts
def simplex_dimension(simplex): """ Get the dimension of a simplex. :param simplex: Simplex defined by a list of vertex indices. :type simplex: List[int] :return: Dimension of the simplex. """ return len(simplex) - 1
bigcode/self-oss-instruct-sc2-concepts
def ssXXsuffix( i ): """Turns an integer into an ssXX ending between .ss01 and .ss20, e.g. 5 -> '.ss05'.""" i = i%21 # max 20 if not i: # if 0 i = 1 return ".calt.ss%.2d" % ( i )
bigcode/self-oss-instruct-sc2-concepts
def decode_rgb565(val): """Decode a RGB565 uint16 into a RGB888 tuple.""" r5 = (val & 0xf800) >> 11 g6 = (val & 0x7e0) >> 5 b5 = val & 0x1f return ( int((r5 * 255 + 15) / 31), int((g6 * 255 + 31) / 63), int((b5 * 255 + 15) / 31) )
bigcode/self-oss-instruct-sc2-concepts
from typing import OrderedDict def quant_params_vec2dict(keys, vals, search_clipping=False): """ Convert the vector(s) created by quant_params_dict2vec to a dictionary of quantization parameters that the post-training quantizer API can digest """ res = OrderedDict() for idx, k in enumerate(key...
bigcode/self-oss-instruct-sc2-concepts
from bs4 import BeautifulSoup def clean_data(data): """ Strip HTML and clean spaces """ data = BeautifulSoup(data, "lxml").text.strip() data = ' '.join(data.split()).encode("utf-8") return data
bigcode/self-oss-instruct-sc2-concepts
import pkg_resources def get_template(name): """ Look for 'name' in the vr.runners.templates folder. Return its contents. >>> import six >>> tmpl = get_template('base_image.lxc') >>> isinstance(tmpl, six.string_types) True """ path = 'templates/' + name b_stream = pkg_resources.r...
bigcode/self-oss-instruct-sc2-concepts
def service_exists(keystone, service_name): """ Return True if service already exists""" return service_name in [x.name for x in keystone.services.list()]
bigcode/self-oss-instruct-sc2-concepts
def material_type(rec): """Determine material type for record (arg1). Returns: A string, one of BK (books), CF (computer files), MP (maps), MU (music), CR (continuing resource), VM (visual materials), MX (mixed materials) """ l = rec[0] # Book: Leader/06 (Type of record) co...
bigcode/self-oss-instruct-sc2-concepts
def classname(cls): """Return the name of a class""" return cls.__name__
bigcode/self-oss-instruct-sc2-concepts
def normalize_lang(lang): """Normalize input languages string >>> from pyams_utils.i18n import normalize_lang >>> lang = 'fr,en_US ; q=0.9, en-GB ; q=0.8, en ; q=0.7' >>> normalize_lang(lang) 'fr,en-us;q=0.9,en-gb;q=0.8,en;q=0.7' """ return lang.strip() \ .lower() \ ...
bigcode/self-oss-instruct-sc2-concepts
def doi_to_directory(doi): """Converts a doi string to a more directory-friendly name Parameters ---------- doi : string doi Returns ------- doi : string doi with "/" and ":" replaced by "-" and "-" respectively """ return doi.replace("/", "-").replace(":", "-")
bigcode/self-oss-instruct-sc2-concepts
def get_soil_texture_superclass_id(superclass: str): """Get soil texture superclass ID. Parameters ---------- superclass : str Superclass from {L, S, T, U}. Returns ------- int ID of superclass """ superclass_dict = {"L": 0, "S": 1, "T": 2, "U": 3} return super...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def write_fn(period: datetime = datetime.now(), prefix: str = 'xbrlrss', ext: str = '.xml') -> str: """Write the filename with pattern prefix-YYYY-MM-.xml Args: period (datetime, optional): Date from which year and month come. Defaults to datetime.now(). prefix (...
bigcode/self-oss-instruct-sc2-concepts
def fullName(first: str, middle: str, last: str) -> str: """ Compose parts of a name into a full name. """ if middle: return f"{first} {middle}. {last}" else: return f"{first} {last}"
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Tuple def write_inertia(inertia: List[Tuple[int, int]]): """ Given an inertia decomposition as returned by `compute_inertia`, create the string version that is latex displayable. Example: >>> write_inertia([(2, 1), (2, 3), (1, 2), (1, 1)]) '(...
bigcode/self-oss-instruct-sc2-concepts
def xyz_to_zyx(data, x=0, y=0, z=0): """ Reverses dimensions of matrix. Assumes data is not flattened. If it is flattened, pass in y, x, z parameters :param data: :param y: :param x: :param z: """ x = data.shape[0] if x == 0 else x y = data.shape[1] if y == 0 else y z...
bigcode/self-oss-instruct-sc2-concepts
def lowercase(raw_text: str) -> str: """ >>> lowercase("This is NeW YoRk wIth upPer letters") 'this is new york with upper letters' """ return raw_text.lower()
bigcode/self-oss-instruct-sc2-concepts
def create_obj(d): """Create an object from a dict""" return type('D', (object,), d)()
bigcode/self-oss-instruct-sc2-concepts
def get_option(name,project,default=None): """ Get an option flag from the project structure, returning None if the flag is not defined. """ if 'options' not in project: return default if name not in project['options']: return default return project['options'][name]
bigcode/self-oss-instruct-sc2-concepts
import re def read_segmentation(word_boundary_path): """ Args: word_boundary_paths (list): list of paths to word boundary files Returns: segmentation_dict (dict): key (string): utt_index value (list): list of [start_frame, end_frame, word] """ segmentation_d...
bigcode/self-oss-instruct-sc2-concepts
import re def fixSlashes(url): """ Removes double slashes in URLs, and ensures the protocol is doubleslahed """ # insert missing protocol slashes p = re.compile( '(:/)([^/])' ) url = p.subn( r'\1/\2', url)[0] # strip any double slashes excluding :// p = re.compile( '([^:])//' ) ...
bigcode/self-oss-instruct-sc2-concepts
import secrets import binascii def generate_consul_key(unique=False): """ Generate a consul key. https://www.consul.io/docs/security/encryption Key generated per the following description: https://github.com/hashicorp/consul/blob/b3292d13fb8bbc8b14b2a1e2bbae29c6e105b8f4/command/keygen/keygen.go ...
bigcode/self-oss-instruct-sc2-concepts
def find_index(token, low, high, features): # binary search to find element index in list """ # Binary search helper method # helps finding token index # with O(log n) time whereas # np.where() will need O(n) """ if high >= low: mid = int((high + low) / 2) if features[mid] ...
bigcode/self-oss-instruct-sc2-concepts
def _calc_target_shape(target_range): """Returns the shape of the target image.""" return tuple((target_range[:, 1] - target_range[:, 0]).astype(int))
bigcode/self-oss-instruct-sc2-concepts
def _convert(x): """Generically convert strings to numbers. :param x: string that maybe represents a number :returns: value :rtype: string, float, or int """ try: return int(x) except ValueError: try: return float(x) except ValueError: return...
bigcode/self-oss-instruct-sc2-concepts
def is_imported_from_same_module(the_class: str, imported_name: str) -> bool: """ Is the class imported from another module? :param the_class: the class object itself :param imported_name: name of the imported class :return: true if the class was imported from another module """ return "."....
bigcode/self-oss-instruct-sc2-concepts
def checkPrefix(s, prefix): """ Return a pair (hasPrefix, rest). If prefix is a prefix of s: hasPrefix is True rest is everything after the prefix Else: hasPrefix is False rest is s """ if s.startswith(prefix): return (True, s[len(prefix):]) else: ...
bigcode/self-oss-instruct-sc2-concepts
import io import wave def buffer_to_wav(buffer: bytes) -> bytes: """Wraps a buffer of raw audio data (16-bit, 16Khz mono) in a WAV""" with io.BytesIO() as wav_buffer: wav_file: wave.Wave_write = wave.open(wav_buffer, mode="wb") with wav_file: wav_file.setframerate(16000) ...
bigcode/self-oss-instruct-sc2-concepts
import torch def discriminator_loss(logits_r,logits_m,logits_f,logits_f_prime): """ Computes the discriminator loss described in the homework pdf using the bce_loss function. Inputs: - logits_r: PyTorch Variable of shape (N,) giving scores for the real data. - logits_f: PyTorch Variable o...
bigcode/self-oss-instruct-sc2-concepts
import toml def parse_toml_file(file_object): """Parses toml data using a file-like object to a dictionary. Args: file_object: (file-like object) file like object instantiated from a toml formatted file Returns: A dictionary with parsed toml data fields. """ return toml.load(file...
bigcode/self-oss-instruct-sc2-concepts
def escape_delimit(s): """ escapes bytes 0x7e, 0x7d, 0x11 (XON), 0x13 (XOFF) 0x7e and 0x7d will be escaped to 0x7d 0x5e and 0x7d 0x5d 0x11 and 0x13 will be escaped to 0x7d 0x31 and 0x7d 0x33 0x7e - packet start/end 0x7d - escape character. escapes the following byte by inverting bit 5. exa...
bigcode/self-oss-instruct-sc2-concepts
def csv_file(tmp_path): """Generate a csv file for test purposes Args: tmp_path: temporary area to use to write files Returns: path to the csv file """ tmp_path.mkdir(exist_ok=True) csv_file_path = tmp_path / "file.csv" csv_file_path.write_text("x,y\n0,0\n1,1\n") return csv...
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def calculate_center_coords( cell_index: Tuple[int, int], cell_size: Tuple[int, int] ) -> Tuple[int, int]: """Calculate cell center coordinates. :param cell_index: selected cell index :param cell_size: given cell size (height, width) :return: given cell center coordinates...
bigcode/self-oss-instruct-sc2-concepts
def cleanup_comment(comment): """Given a dictionary of a comment record, return a new dictionary for output as JSON.""" comm_data = comment comm_data["id"] = str(comm_data["_id"]) comm_data["user"] = str(comm_data["user"]) comm_data["post"] = str(comm_data["post"]) comm_data["created"] = s...
bigcode/self-oss-instruct-sc2-concepts
def tag2String(tag): """Takes a tag placement, and turns it into a verbose string""" return ("Tag with ID #%d, was placed @ (%f,%f), facing %f deg" % (tag['id'], tag['x'], tag['y'], tag['th_deg']))
bigcode/self-oss-instruct-sc2-concepts
def get_level_size(slide, level): """Returns the dimensions of a level """ return slide.level_dimensions[level]
bigcode/self-oss-instruct-sc2-concepts
import torch def regularization_loss(params, weight): """Compute regularization loss. Args: params: iterable of all parameters weight: weight for the regularization term Returns: the regularization loss """ l2_reg = 0 for param in params: l2_reg += torch.norm(param) return weight * l2_...
bigcode/self-oss-instruct-sc2-concepts