seed
stringlengths
1
14k
source
stringclasses
2 values
import itertools def split_mosaic(image, tile_size): """ Returns image after splitting image to multiple tiles of of tile_size. Args: image: str an image array to split tile_size: tuple size each image in the split is resized to Returns: Returns list of images """ # Set number of tiles shape = image.shape x_tiles = shape[0] // tile_size[0] y_tiles = shape[1] // tile_size[1] tile_size_x = tile_size[0] tile_size_y = tile_size[1] images = [] # Set each of the tiles with an image in images_in_path indices = list(itertools.product(range(x_tiles), range(y_tiles))) for index in range(len(indices)): x, y = indices[index] images.append( image[ x * tile_size_x : tile_size_x * (x + 1), y * tile_size_y : tile_size_y * (y + 1), ] ) return images
bigcode/self-oss-instruct-sc2-concepts
def skolemize_one(bnode: str, url: str) -> str: """Skolemize a blank node. If the input value is not a Blank node, then do nothing. Args: * value: RDF Blank node to skolemize. * url: Prefix URL used for skolemization. Returns: The skolemized blank node, or the value itself if it was not a blank node. """ return f"{url}/bnode#{bnode[2:]}" if bnode.startswith("_:") else bnode
bigcode/self-oss-instruct-sc2-concepts
def search_datastore_spec(client_factory, file_name): """Builds the datastore search spec.""" search_spec = client_factory.create('ns0:HostDatastoreBrowserSearchSpec') search_spec.matchPattern = [file_name] return search_spec
bigcode/self-oss-instruct-sc2-concepts
def artist_src_schema_to_dw_schema(df): """ Rename the event src columns to dimensional and fact tables format. dim_artist columns: artist_id, name, location, latitude, longitude """ df = df.withColumnRenamed("artist_name", "name") df = df.withColumnRenamed("artist_location", "location") df = df.withColumnRenamed("artist_latitude", "latitude") df = df.withColumnRenamed("artist_longitude", "longitude") return df
bigcode/self-oss-instruct-sc2-concepts
def get_file_lines(filename): """ Inputs: filename - name of file to read Output: Returns a list of lines from the file named filename. Each line will be a single line string with no newline ('\n') or return ('\r') characters. If the file does not exist or is not readable, then the behavior of this function is undefined. """ with open(filename, 'rt') as infile: lines = infile.read() return lines.splitlines()
bigcode/self-oss-instruct-sc2-concepts
def get_lines(text_string, sub_string): """Get individual lines in a text file Arguments: text_string {string} -- The text string to test sub_string {string} -- The conditional string to perform splitting on Returns: {list} -- A list of split strings """ lines = [line for line in text_string.split("\n") if sub_string in line] return lines
bigcode/self-oss-instruct-sc2-concepts
def tag(accessing_obj, accessed_obj, *args, **kwargs): """ Usage: tag(tagkey) tag(tagkey, category) Only true if accessing_obj has the specified tag and optional category. If accessing_obj has the ".obj" property (such as is the case for a command), then accessing_obj.obj is used instead. """ if hasattr(accessing_obj, "obj"): accessing_obj = accessing_obj.obj tagkey = args[0] if args else None category = args[1] if len(args) > 1 else None return bool(accessing_obj.tags.get(tagkey, category=category))
bigcode/self-oss-instruct-sc2-concepts
import re def get_filename_components(filename): """Decomposes a standard note filename A standard filename has the form of 2_03_04a_5_Some_Topic_fb134b00b Where 2_03_04a_5 define the order within the hierachy of notes (in this case 4 levels), Some_Topic is the base of the filename and fb134b00b is a unique identifier. The return value is ['2_03_04a_5','Some_Topic','fb134b00b'] Args: filename (str): The filename of a note Returns: list: List of strings with the components of the filename """ components = [] id_filename = '' if re.match(r'.*_[0-9a-f]{9}\.md$', filename): id_filename = filename[-12:-3] filename = filename[:-13] else: id_filename = '' filename = filename[:-3] # Split by first underscore followed by a character = Non-Digit if re.match(r'^\d', filename): ordering_filename = re.split(r'_\D', filename, maxsplit=1)[0] base_filename = filename[(len(ordering_filename)+1):] else: ordering_filename = '' base_filename = filename components = [ordering_filename, base_filename, id_filename] return components
bigcode/self-oss-instruct-sc2-concepts
def get_label_from_directory(directory): """ Function to set the label for each image. In our case, we'll use the file path of a label indicator. Based on your initial data Args: directory: string Returns: int - label Raises: NotImplementedError if unknown image class is detected """ lowered_directory = directory.lower() if "buildings" in lowered_directory: label = 0 elif "forest" in lowered_directory: label = 1 elif "glacier" in lowered_directory: label = 2 elif "mountain" in lowered_directory: label = 3 elif "sea" in lowered_directory: label = 4 elif "street" in lowered_directory: label = 5 else: raise NotImplementedError("Found unknown image") return label
bigcode/self-oss-instruct-sc2-concepts
import math def euclidean_distance(x0, y0, x1, y1): """ Regular Euclidean distance algorithm. :param x0: x value of the first coordinate :param y0: y value of the first coordinate :param x1: x value of the second coordinate :param y1: y value of the second coordinate :return: euclidean distance """ return math.sqrt(((x1 - x0) ** 2) + ((y1 - y0) ** 2))
bigcode/self-oss-instruct-sc2-concepts
def GetExtent(ds): """ Return list of corner coordinates from a gdal Dataset """ xmin, xpixel, _, ymax, _, ypixel = ds.GetGeoTransform() width, height = ds.RasterXSize, ds.RasterYSize xmax = xmin + width * xpixel ymin = ymax + height * ypixel return (xmin, ymax), (xmax, ymax), (xmax, ymin), (xmin, ymin)
bigcode/self-oss-instruct-sc2-concepts
def filter_request_parameters(field_name, msg, look_in_response=False): """ From an event, extract the field name from the message. Different API calls put this information in different places, so check a few places. """ val = msg['detail'].get(field_name, None) try: if not val: val = msg['detail'].get('requestParameters', {}).get(field_name, None) # If we STILL didn't find it -- check if it's in the response element (default off) if not val and look_in_response: if msg['detail'].get('responseElements'): val = msg['detail']['responseElements'].get(field_name, None) # Just in case... We didn't find the value, so just make it None: except AttributeError: val = None return val
bigcode/self-oss-instruct-sc2-concepts
from typing import List import random def randboolList(len: int) -> List[bool]: """Returns a list of booleans generated randomly with length `len`""" finalList: List[bool] = [] for _ in range(len): finalList.append(random.choice([True, False])) return finalList
bigcode/self-oss-instruct-sc2-concepts
import mpmath def mean(p, b, loc=0, scale=1): """ Mean of the generalized inverse Gaussian distribution. The mean is: K_{p + 1}(b) loc + scale -------------- K_p(b) where K_n(x) is the modified Bessel function of the second kind (implemented in mpmath as besselk(n, x)). """ p = mpmath.mpf(p) b = mpmath.mpf(b) loc = mpmath.mpf(loc) scale = mpmath.mpf(scale) return loc + scale*mpmath.besselk(p + 1, b)/mpmath.besselk(p, b)
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def with_type(d: Dict, kind) -> Dict: """ Add or overwrite the key "type", associating it with kind, while not mutating original dict. :param d: dictionary to add "type": kind to :param kind: the kind of object dict represents :return: d | {"type": kind} >>> with_type({}, "foo") == {"type": "foo"} True >>> with_type({"a": "b"}, "bar") == {"a": "b", "type": "bar"} True >>> with_type({"a": "c", "type": "foo"}, "bar") == {"a": "c", "type": "bar"} True >>> d = {"a": "e"} >>> with_type(d, "baz") == {"a": "e", "type": "baz"} True >>> d == {"a": "e"} True """ return {**d, "type": kind}
bigcode/self-oss-instruct-sc2-concepts
def Dir(v): """Like dir(v), but only non __ names""" return [n for n in dir(v) if not n.startswith('__')]
bigcode/self-oss-instruct-sc2-concepts
import re def splitFastaHeader(name): """ Split a FASTA/FASTQ header into its id and metadata components """ nameParts = re.split('\s', name, maxsplit=1) id_ = nameParts[0] if len(nameParts) > 1: metadata = nameParts[1].strip() else: metadata = None return (id_, metadata)
bigcode/self-oss-instruct-sc2-concepts
def selectGenes(df, selection): """ Remove all rows (gene_ids) from a data frame which can not be found in selection. Parameters --------- df : DataFrame The data frame to work with. selection : set All ids to keep. Return ------ df : DataFrame The cleand data frame. """ selection = set(selection) for id in df.index: if id not in selection: df = df.drop(id) return df
bigcode/self-oss-instruct-sc2-concepts
def move_to_same_host_as(source, destin): """ Returns source or a copy of `source` such that `source.is_cuda == `destin.is_cuda`. """ return source.cuda(destin.get_device()) if destin.is_cuda else source.cpu()
bigcode/self-oss-instruct-sc2-concepts
def subdict(d, keep=None, drop=None): """Compute the "subdictionary" of a dict, *d*. A subdict is to a dict what a subset is a to set. If *A* is a subdict of *B*, that means that all keys of *A* are present in *B*. Returns a new dict with any keys in *drop* removed, and any keys in *keep* still present, provided they were in the original dict. *keep* defaults to all keys, *drop* defaults to empty, so without one of these arguments, calling this function is equivalent to calling ``dict()``. >>> from pprint import pprint as pp >>> pp(subdict({'a': 1, 'b': 2})) {'a': 1, 'b': 2} >>> subdict({'a': 1, 'b': 2, 'c': 3}, drop=['b', 'c']) {'a': 1} >>> pp(subdict({'a': 1, 'b': 2, 'c': 3}, keep=['a', 'c'])) {'a': 1, 'c': 3} """ if keep is None: keep = d.keys() if drop is None: drop = [] keys = set(keep) - set(drop) return type(d)([(k, v) for k, v in d.items() if k in keys])
bigcode/self-oss-instruct-sc2-concepts
def any_heterozygous(genotypes): """Determine if any of the genotypes are heterozygous Parameters ---------- genoytypes : container Genotype for each sample of the variant being considered Returns ------- bool True if at least one sample is heterozygous at the variant being considered, otherwise False """ return bool( {'0|1', '1|0', '0/1'} & {genotype.split(':')[0] for genotype in genotypes} )
bigcode/self-oss-instruct-sc2-concepts
import operator def get_operator_function(op_sign): """ Get operator function from sign Args: op_sign (str): operator sign Returns: operator function """ return { '>': operator.gt, '<': operator.lt, '>=': operator.ge, '<=': operator.le, '==': operator.eq, '!=': operator.ne, }[op_sign]
bigcode/self-oss-instruct-sc2-concepts
import unittest import operator def create_datecalctestcase(start, duration, expectation): """ Create a TestCase class for a specific test. This allows having a separate TestCase for each test tuple from the DATE_CALC_TEST_CASES list, so that a failed test won't stop other tests. """ class TestDateCalc(unittest.TestCase): ''' A test case template test addition operators for Duration objects. ''' def test_calc(self): ''' Test operator +. ''' if expectation is None: self.assertRaises(ValueError, operator.add, start, duration) else: self.assertEqual(start + duration, expectation) return unittest.TestLoader().loadTestsFromTestCase(TestDateCalc)
bigcode/self-oss-instruct-sc2-concepts
def true_positives(truth, pred, axis=None): """ Computes number of true positive """ return ((pred==1) & (truth==1)).sum(axis=axis)
bigcode/self-oss-instruct-sc2-concepts
def merge_dicts(create_dict, iterable): """ Merges multiple dictionaries, which are created by the output of a function and an iterable. The function is applied to the values of the iterable, that creates dictionaries :param create_dict: function, that given a parameter, outputs a dictionary. :param iterable: iterable, on which the function will be applied. :return: dict, the created dictionary. """ merged_dict = {} for dictionary in map(create_dict, iterable): merged_dict = {**merged_dict, **dictionary} return merged_dict
bigcode/self-oss-instruct-sc2-concepts
def hs2_text_constraint(v): """Constraint function, used to only run HS2 against uncompressed text, because file format and the client protocol are orthogonal.""" return (v.get_value('protocol') == 'beeswax' or v.get_value('table_format').file_format == 'text' and v.get_value('table_format').compression_codec == 'none')
bigcode/self-oss-instruct-sc2-concepts
import random def recursive_back_tracker_maze(bm_edges, full_mesh=False): """trace a perfect maze through bm_edges input: bm_edges: list of BMEdges - needs to be pre-sorted on index full_mesh: does bm_edges include the whole mesh output: maze_path: list of BMEdges maze_verts: list of BMVerts """ stack = [] maze_path = [] maze_verts = [] # start at a random vert in maze start_vert = random.choice(bm_edges).verts[0] stack.append(start_vert) maze_verts.append(start_vert) while len(stack) > 0: current_vert = stack[-1] if full_mesh: # faster if we don't check edge is in bm_edges free_link_edges = [ e for e in current_vert.link_edges if (e.other_vert(current_vert) not in maze_verts) ] else: # check edge in bm_edge free_link_edges = [ e for e in current_vert.link_edges if (e in bm_edges) and (e.other_vert(current_vert) not in maze_verts) ] if len(free_link_edges) == 0: stack.pop() else: link_edge = random.choice(free_link_edges) maze_path.append(link_edge) new_vert = link_edge.other_vert(current_vert) stack.append(new_vert) maze_verts.append(new_vert) return maze_path, maze_verts
bigcode/self-oss-instruct-sc2-concepts
def get_trunk(py): """helper function that returns name of df column name for particular percentile (py) of latency""" p_col_name = { "P50_latency(ms)": "P50ms", 'P90_latency(ms)': "P90ms", 'P95_latency(ms)': "P95ms", 'P99_latency(ms)': "P99ms" } return p_col_name[py]
bigcode/self-oss-instruct-sc2-concepts
def isBuildConfFake(conf): """ Return True if loaded buildconf is a fake module. """ return conf.__name__.endswith('fakeconf')
bigcode/self-oss-instruct-sc2-concepts
def is_palindrome(n): """Checks if n is a palindrome""" n = str(n) return n == n[::-1]
bigcode/self-oss-instruct-sc2-concepts
import torch def load_model(filename, model): """Load the model parameters in {filename}.""" model_params = torch.load(str(filename)) model.load_state_dict(model_params) return model
bigcode/self-oss-instruct-sc2-concepts
def table(lst): """ Takes a list of iterables and returns them as a nicely formatted table. All values must be convertible to a str, or else a ValueError will be raised. N.B. I thought Python's standard library had a module that did this (or maybe it was Go's standard library), but I'm on an airplane and pydoc sucks. """ pad = 2 maxcols = [] output = [] first_row = True for row in lst: if row is None: output.append([]) continue output_row = [] for i, cell in enumerate(row): cell = str(cell) if first_row: maxcols.append(len(cell) + pad) else: maxcols[i] = max([maxcols[i], len(cell) + pad]) output_row.append(cell) output.append(output_row) first_row = False rowsep = '-' * sum(maxcols) nice = [] for i, row in enumerate(output): nice_row = [] for j, cell in enumerate(row): nice_row.append(cell.rjust(maxcols[j])) nice.append(''.join(nice_row)) if i < len(output) - 1: nice.append(rowsep) return '\n'.join(nice)
bigcode/self-oss-instruct-sc2-concepts
def push_variable_on_stack(assembler, stack_offset, value, value_array): """Push a value on a specified location on stack Args: assembler (Assembler): the assembler to use stack_offset (int): the offset relative to the current stack pointer value (bytearray): the byte array to append the machine code to value_array (bytearray): the bytearray to push to stack Returns: bytearray: the array with the added machine code int: the stackoffset """ number_of_words = int((len(value_array) - 1) / 4) + 1 for i in range(number_of_words): part_of_array = value_array[i * 4:(i + 1) * 4] stack_offset -= 4 value += assembler.push_value_to_stack(part_of_array, stack_offset) # if multiple words are used, move the offset a word further if number_of_words > 1: stack_offset -= 4 return value, stack_offset
bigcode/self-oss-instruct-sc2-concepts
from typing import Mapping def signature(signages): """ Creates Signature HTTP header item from signages list RFC8941 Structured Field Values for HTTP Returns: header (dict): {'Signature': 'value'} where value is RFC8941 compliant (Structured Field Values for HTTP) formatted str of of Signage group. Each signage group is separated by a comma. Each group is parameter list of label=value items separated by ; The signer and indexed are special parameters in each group. This format is compatible with HTTP servers that merge multiple signature headers into one header by iteratively appending the comma separated value from each Signature header. Parameters: signages (list): items are Signage namedtuples, (markers, indexed, signer, ordinal, kind) where: markers (Union[list, dict]): When dict each item (key, val) has key as str identifier of marker and has val as instance of either coring.Siger or coring.Cigar. When list each item is instance of either coring.Siger or coring.Cigar. All markers must be of same class indexed (bool): True means marker values are indexed signatures using coring.Siger. False means marker values are unindexed signatures using coring.Cigar. None means auto detect from first marker value class. All markers must be of same class. signer (str): optional identifier of signage. May be a multi-sig group identifier. Default is None. When None or empty signer is not included in header value ordinal (str): optional ordinal hex str of int that is an ordinal such as sequence number to further identify the keys used for the signatures. Usually when indexed with signer and digest digest (str): optional CESR Base64 serialization of a digest to further identify the keys used for the signatures. Usually when indexed with signer and ordinal kind (str): serialization kind of the markers and other primitives """ values = [] # list of parameter items value str for each signage for signage in signages: markers = signage.markers indexed = signage.indexed signer = signage.signer ordinal = signage.ordinal digest = signage.digest kind = signage.kind if isinstance(markers, Mapping): tags = list(markers.keys()) markers = list(markers.values()) else: tags = [] if indexed is None: indexed = hasattr(markers[0], "index") items = [] tag = 'indexed' val = '?1' if indexed else '?0' # RFC8941 HTTP structured field values items.append(f'{tag}="{val}"') if signer: tag = "signer" val = signer items.append(f'{tag}="{val}"') if ordinal: tag = "ordinal" val = ordinal items.append(f'{tag}="{val}"') if digest: tag = "digest" val = digest items.append(f'{tag}="{val}"') if kind: tag = "kind" val = kind items.append(f'{tag}="{val}"') for i, marker in enumerate(markers): if tags: tag = tags[i] else: # assign defaults names since not provided if hasattr(marker, "index"): # Siger has index if not indexed: raise ValueError(f"Indexed signature marker {marker} when " f"indexed False.") tag = str(marker.index) elif hasattr(marker, "verfer"): # Cigar has verfer but not index if indexed: raise ValueError(f"Unindexed signature marker {marker}" f" when indexed True.") tag = marker.verfer.qb64 else: raise ValueError(f"Invalid signature marker instance = " f"{marker}.") val = marker.qb64 items.append(f'{tag}="{val}"') values.append(";".join(items)) return dict(Signature=",".join(values))
bigcode/self-oss-instruct-sc2-concepts
def get_file_content(fpath: str, **kwargs) -> str: """Get content from a file given a path Parameters ---------- fpath : str file path Returns ------- str file content """ with open(fpath, **kwargs) as f: txt = f.read() return txt
bigcode/self-oss-instruct-sc2-concepts
def multiples(s1, s2, s3): """Show multiples of two numbers within a given range.""" result = [] for i in range(s3): if i % s1 == 0 and i % s2 == 0 and i: result.append(i) return result
bigcode/self-oss-instruct-sc2-concepts
def avg(array): """ Makes the average of an array without Nones. Args: array (list): a list of floats and Nones Returns: float: the average of the list without the Nones. """ array_wo_nones = list(filter(None, array)) return (sum(array_wo_nones, 0.0) / len(array_wo_nones)) if len(array_wo_nones) > 0 else 0.0
bigcode/self-oss-instruct-sc2-concepts
def pms_to_addrportsq(poolmembers): """ Converts PoolMembers into a list of address, port dictionaries """ return [{'address': p._node.name, 'port': p._port} for p in poolmembers]
bigcode/self-oss-instruct-sc2-concepts
def qualify(ns, name): """Makes a namespace-qualified name.""" return '{%s}%s' % (ns, name)
bigcode/self-oss-instruct-sc2-concepts
import difflib def simple_merge(txt1, txt2): """Merges two texts""" differ = difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK) diff = differ.compare(txt1.splitlines(1), txt2.splitlines(1)) content = "".join([l[2:] for l in diff]) return content
bigcode/self-oss-instruct-sc2-concepts
def encoding_fmt(request): """ Fixture for all possible string formats of a UTF encoding. """ return request.param
bigcode/self-oss-instruct-sc2-concepts
import math def sph2cart(theta, phi, r=1): """Converts spherical coords to cartesian""" x = r * math.sin(theta) * math.cos(phi) y = r * math.sin(theta) * math.sin(phi) z = r * math.cos(theta) vect = [x, y, z] return vect
bigcode/self-oss-instruct-sc2-concepts
import base64 def convert_img_to_b64_string(img_path): """ Converts medical image to b64 string This function takes the image filepath as an input and outputs it as a b64 string. This string can be sent to the server and then the database. Args: img_path (str): the name of the file path containing an image to be loaded Returns: b64_img_string (str): the image file as a b64 string """ with open(img_path, "rb") as image_file: b64_bytes = base64.b64encode(image_file.read()) b64_img_string = str(b64_bytes, encoding='utf-8') return b64_img_string
bigcode/self-oss-instruct-sc2-concepts
import random import math def randomLogGamma(beta,seed=None): """ Generate Log-Gamma variates p(x|beta) = exp(beta*x - x)/gamma(beta) RNG derived from G. Marsaglia and W. Tsang. A simple method for generating gamma variables. ACM Transactions on Mathematical Software, 26(3):363-372, 2000. See http://www.hongliangjie.com/2012/12/19/how-to-generate-gamma-random-variables/ for reference. """ if seed!=None: random.seed(seed) assert beta > 0, "beta=%s must be greater than 0" % beta beta0 = beta if beta0 < 1: beta = beta+1 d = beta-1.0/3.0 cinv = 3.0*(d**0.5) while True: Z = random.normalvariate(0,1) if Z > -cinv: logU = math.log(random.uniform(0,1)) val = 1+Z/cinv V = val**3.0 logV = 3*math.log(val) if logU < 0.5*(Z**2.0)+d-d*V+d*logV: # 1.5*math.log(9) = 3.2958368660043 logX = -0.5*math.log(d) + 3.0*math.log(cinv+Z)-3.2958368660043 break if beta0 < 1: logU = math.log(random.uniform(0,1)) logX = logX + logU/beta0 return logX
bigcode/self-oss-instruct-sc2-concepts
def _fmt_cmd_for_err(cmd): """ Join a git cmd, quoting individual segments first so that it's relatively easy to see if there were whitespace issues or not. """ return ' '.join(['"%s"' % seg for seg in cmd])
bigcode/self-oss-instruct-sc2-concepts
def get_slices_by_indices(str, indices): """Given a string and a list of indices, this function returns a list of the substrings defined by those indices. For example, given the arguments:: str='antidisestablishmentarianism', indices=[4, 7, 16, 20, 25] this function returns the list:: ['anti', 'dis', 'establish', 'ment', arian', 'ism'] @param str: text @type str: string @param indices: indices @type indices: list of integers """ slices = [] for i in range(0, len(indices)): slice = None start = indices[i] if i == len(indices)-1: slice = str[start: ] else: finish = indices[i+1] slice = str[start: finish] slices.append(slice) return slices
bigcode/self-oss-instruct-sc2-concepts
def _read_pid_file(filename): """ Reads a pid file and returns the contents. PID files have 1 or 2 lines; - first line is always the pid - optional second line is the port the server is listening on. :param filename: Path of PID to read :return: (pid, port): with the PID in the file and the port number if it exists. If the port number doesn't exist, then port is None. """ pid_file_lines = open(filename, "r").readlines() if len(pid_file_lines) == 2: pid, port = pid_file_lines pid, port = int(pid), int(port) elif len(pid_file_lines) == 1: # The file only had one line pid, port = int(pid_file_lines[0]), None else: raise ValueError("PID file must have 1 or two lines") return pid, port
bigcode/self-oss-instruct-sc2-concepts
def col_variables(datatype): """This function provides a key for column names of the two most widely used battery data collection instruments, Arbin and MACCOR""" assert datatype == 'ARBIN' or datatype == 'MACCOR' if datatype == 'ARBIN': cycle_ind_col = 'Cycle_Index' data_point_col = 'Data_Point' volt_col = 'Voltage(V)' curr_col = 'Current(A)' dis_cap_col = 'Discharge_Capacity(Ah)' char_cap_col = 'Charge_Capacity(Ah)' charge_or_discharge = 'Step_Index' elif datatype == 'MACCOR': cycle_ind_col = 'Cycle_Index' data_point_col = 'Rec' volt_col = 'Voltage(V)' curr_col = 'Current(A)' dis_cap_col = 'Cap(Ah)' char_cap_col = 'Cap(Ah)' charge_or_discharge = 'Md' else: return None return(cycle_ind_col, data_point_col, volt_col, curr_col, dis_cap_col, char_cap_col, charge_or_discharge)
bigcode/self-oss-instruct-sc2-concepts
def uri_to_id(uri): """ Utility function to convert entity URIs into numeric identifiers. """ _, _, identity = uri.rpartition("/") return int(identity)
bigcode/self-oss-instruct-sc2-concepts
def centimeter2feet(dist): """ Function that converts cm to ft. """ return dist / 30.48
bigcode/self-oss-instruct-sc2-concepts
import struct def char(c): """ Input: requires a size 1 string Output: 1 byte of the ascii encoded char """ return struct.pack('=c', c.encode('ascii'))
bigcode/self-oss-instruct-sc2-concepts
import torch def covariance_z_mean(z_mean): """Computes the covariance of z_mean. Borrowed from https://github.com/google-research/disentanglement_lib/ Uses cov(z_mean) = E[z_mean*z_mean^T] - E[z_mean]E[z_mean]^T. Args: z_mean: Encoder mean, tensor of size [batch_size, num_latent]. Returns: cov_z_mean: Covariance of encoder mean, tensor of size [num_latent, num_latent]. """ expectation_z_mean_z_mean_t = torch.mean(z_mean.unsqueeze(2) * z_mean.unsqueeze(1), dim=0) expectation_z_mean = torch.mean(z_mean, dim=0) cov_z_mean = expectation_z_mean_z_mean_t - \ (expectation_z_mean.unsqueeze(1) * expectation_z_mean.unsqueeze(0)) return cov_z_mean
bigcode/self-oss-instruct-sc2-concepts
import socket def inet_to_str(inet): """Convert inet object to a string :param inet: inet network address :type inet: inet struct :return: str of printable/readable IP address """ try: return socket.inet_ntop(socket.AF_INET, inet) except ValueError: return socket.inet_ntop(socket.AF_INET6, inet)
bigcode/self-oss-instruct-sc2-concepts
import torch def get_idxs(results, test_targets, device): """ Args: results (tensor): predictions test_targets (tensor): Ground truth labels Returns: miss_index: index of misclassifier images hit_index: index of correctly classifier images """ miss_index = torch.where((results.argmax(dim=1) == torch.tensor(test_targets).to(device)) == False)[0] hit_index = torch.where((results.argmax(dim=1) == torch.tensor(test_targets).to(device)) == True)[0] return((miss_index, hit_index))
bigcode/self-oss-instruct-sc2-concepts
def trailing_zeros(value: int) -> int: """Returns the number of trailing zeros in the binary representation of the given integer. """ num_zeros = 0 while value & 1 == 0: num_zeros += 1 value >>= 1 return num_zeros
bigcode/self-oss-instruct-sc2-concepts
def getAverageVectorForWords( word_list, model, np ): """Calculates average vector for the set of word. Parameters ---------- word_list : array Array of words in format [word1, word2, ...]. model : object Word2Vec model. np : object numpy library. Returns ------- array multidimensional vector, float. """ arr_vectors = [] for w in word_list: # print u'word {0} {1}'.format(w, model[ w ]) arr_vectors.append( model[ w ] ) average_vector = np.average( arr_vectors, axis=0) # print u'average_vector {0} '.format(average_vector) return average_vector
bigcode/self-oss-instruct-sc2-concepts
def is_ethiopia_dataset(name): """Names with 'TR' at start or Ethiopia""" return name.upper().startswith('TR') or \ name.lower().find('ethiopia') > -1
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def exhaustive_directory_search(root, filename): """Executes an exhaustive, recursive directory search of all downstream directories, finding directories which contain a file matching the provided file name query string. Parameters ---------- root : os.PathLike The path (absolute or relative) to the directory from which to conduct the exhaustive search. filename : str The exact name of the file which identifies a directory as one of interest. Returns ------- list of os.PathLike A list of directories containing the filename provided. """ return [xx.parent for xx in Path(root).rglob(filename)]
bigcode/self-oss-instruct-sc2-concepts
def dot(v1,v2): """Dot product of two vectors""" n = len(v1) prod = 0 if n == len(v2): for i in range(n): prod += v1[i]*v2[i] return prod
bigcode/self-oss-instruct-sc2-concepts
def has_time_layer(layers): """Returns `True` if there is a time/torque layer in `layers. Returns `False` otherwise""" return any(layer.time for layer in layers if not layer.is_basemap)
bigcode/self-oss-instruct-sc2-concepts
def is_storage(file, storage=None): """ Check if file is a local file or a storage file. Args: file (str or int): file path, URL or file descriptor. storage (str): Storage name. Returns: bool: return True if file is not local. """ if storage: return True elif isinstance(file, int): return False split_url = file.split("://", 1) if len(split_url) == 2 and split_url[0].lower() != "file": return True return False
bigcode/self-oss-instruct-sc2-concepts
def flatten(x): """flatten(sequence) -> list Return a single, flat list which contains all elements retrieved from the sequence and all recursively contained sub-sequences (iterables). Examples:: >>> [1, 2, [3,4], (5,6)] [1, 2, [3, 4], (5, 6)] >>> flatten([[[1,2,3], (42,None)], [4,5], [6], 7, (8,9,10)]) [1, 2, 3, 42, None, 4, 5, 6, 7, 8, 9, 10] """ result = [] for el in x: if isinstance(el, (list, tuple)): result.extend(flatten(el)) else: result.append(el) return result
bigcode/self-oss-instruct-sc2-concepts
def minimum_distance(mp, ip, dp, i): """ Compares each element from the distance profile with the corresponding element from the matrix profile. Parameters ---------- mp: numpy.array Matrix profile. ip: numpy.array Index profile. dp: numpy.array Distance profile. i: int Index of the element to be compared from the matrix profile. Output ------ mp: numpy.array Array with the distance between every subsequence from ts1 to the nearest subsequence with same length from ts2. ip: numpy.array Array with the index of the ts1's nearest neighbor in ts2. """ for k in range(0, dp.size): if dp[k] < mp[i]: mp[i] = dp[k] ip[i] = k return mp, ip
bigcode/self-oss-instruct-sc2-concepts
def convert_duration(milliseconds): """ Convert milliseconds to a timestamp Format: HH:MM:SS """ # it's easier to wrap your head around seconds seconds = milliseconds / 1000 hrs = seconds // 3600 mins = (seconds % 3600) // 60 s = (seconds % 3600) % 60 return "{:02}:{:02}:{:02}".format(int(hrs), int(mins), int(s))
bigcode/self-oss-instruct-sc2-concepts
def rivers_with_station(stations): """Returns a set containing all rivers which have a monitoring station. Params: Stations - List of all stations. \n. Returns: {River 1, River 2, ... } """ rivers = set() # set for station in stations: # iterate and add rivers to set rivers.add(station.river) return rivers
bigcode/self-oss-instruct-sc2-concepts
def place_mld_breakpoints(incompt_pos :list): """ Adds an MLD breakpoint in the middle of an incompatible interval. Parameters: incompt_pos (list): chop_list() output Output: list: indexes of MLD breakpoints in the sequence """ return [int(inter[0] + (inter[1] - inter[0])/2) for inter in incompt_pos]
bigcode/self-oss-instruct-sc2-concepts
def list_drawings_from_document(client, did, wid): """List the drawings in a given workspace""" # Restrict to the application type for drawings res = client.list_elements(did, wid, element_type='APPLICATION') res_data = res.json() drawings = [] for element in res_data: if element['dataType'] == "onshape-app/drawing": drawings.append(element) return drawings
bigcode/self-oss-instruct-sc2-concepts
def read_order(order_file): """ Read the order of the API functions from a file. Comments can be put on lines starting with # """ fo = open(order_file, 'r') order = {} i = 0 for line in fo: line = line.strip() if not line.startswith('#'): order[line] = i i += 1 fo.close() return order
bigcode/self-oss-instruct-sc2-concepts
def add_spaces_to_fill(text, places): """Adds blank spaces to a string so that the length of the final string is given by 'places'. """ return text + (places-len(text))*" "
bigcode/self-oss-instruct-sc2-concepts
import time def _invoke_timed_callback( reference_time, callback_lambda, callback_period): """Invoke callback if a certain amount of time has passed. This is a convenience function to standardize update callbacks from the module. Args: reference_time (float): time to base `callback_period` length from. callback_lambda (lambda): function to invoke if difference between current time and `reference_time` has exceeded `callback_period`. callback_period (float): time in seconds to pass until `callback_lambda` is invoked. Returns: `reference_time` if `callback_lambda` not invoked, otherwise the time when `callback_lambda` was invoked. """ current_time = time.time() if current_time - reference_time > callback_period: callback_lambda() return current_time return reference_time
bigcode/self-oss-instruct-sc2-concepts
def remove_entity_from_list(unique_list, i): """ Removes all instances of a particular entity from a list >>> remove_entity_from_list(['test', 'test', 'three'], 1) ['three'] """ return [x for x in unique_list if x != unique_list[i]]
bigcode/self-oss-instruct-sc2-concepts
def _tbl_str_width(num, widths): """Returns the width-argument for an html table cell using the width from the list of widths. Returns width="[some number]" or the empty-string if no width is specified for this num""" if num >= len(widths): return "" return ' width="%s"' % widths[num]
bigcode/self-oss-instruct-sc2-concepts
import shutil def center_text(msg: str, *, pad: str = ' ') -> str: """Centers text horizontally for display within the current terminal, optionally padding both sides. :param msg: message to display in the center :param pad: if provided, the first character will be used to pad both sides of the message :return: centered message, optionally padded on both sides with pad_char """ term_width = shutil.get_terminal_size().columns surrounded_msg = ' {} '.format(msg) if not pad: pad = ' ' fill_char = pad[:1] return surrounded_msg.center(term_width, fill_char)
bigcode/self-oss-instruct-sc2-concepts
import typing def _parse_config_file(content: str) -> typing.Mapping[str, str]: """Parses an ini-style config file into a map. Each line is expected to be a key/value pair, using `=` as a delimiter. Lines without `=` are silently dropped. """ kv = {} for line in content.splitlines(): if not line or line.startswith('#') or '=' not in line: continue k, v = line.split('=', 1) kv[k] = v.strip().strip('"\'') return kv
bigcode/self-oss-instruct-sc2-concepts
def get_same_padding_for_kernel_size(kernel_size): """ Returns the required padding for "same" style convolutions """ if kernel_size % 2 == 0: raise ValueError(f"Only odd sized kernels are supported, got {kernel_size}") return (kernel_size - 1) // 2
bigcode/self-oss-instruct-sc2-concepts
def _remove_output_cell(cell): """Remove the output of an ipymd cell.""" cell = cell.copy() if cell['cell_type'] == 'code': cell['output'] = None return cell
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple from typing import Optional def _parse_hp_template(template_name) -> Tuple[str, Optional[int]]: """Parses a template name as specified by the user. Template can versionned: "my_template@v5" -> Returns (my_template, 5) or non versionned: "my_template" -> Returns (my_template, None) Args: template_name: User specified template. Returns: Base template name and version. """ malformed_msg = (f"The template \"{template_name}\" is malformed. Expecting " "\"{template}@v{version}\" or \"{template}") if "@" in template_name: # Template with version. parts = template_name.split("@v") if len(parts) != 2: raise ValueError(malformed_msg) base_name = parts[0] try: version = int(parts[1]) except: raise ValueError(malformed_msg) return base_name, version else: # Template without version? return template_name, None
bigcode/self-oss-instruct-sc2-concepts
def PyUnixTimeConv(some_DT_obj): """ func to convert DateTime Obj to Unix Epoch time, in SECONDS, hence rounding""" output_unix_time = some_DT_obj.timestamp() return round(output_unix_time)
bigcode/self-oss-instruct-sc2-concepts
import json def to_json(raw_data): """ Pretty-prints JSON data :param str raw_data: raw JSON data """ return json.dumps(raw_data, sort_keys=True, indent=4, separators=(',', ': '))
bigcode/self-oss-instruct-sc2-concepts
import re def get_sleep_awake_folder(s): """Get the if animal is sleeping from folder""" temp = re.split("_|\.|\ |\/", s.lower()) if "sleep" in temp or "sleeping" in temp: return 1 return 0
bigcode/self-oss-instruct-sc2-concepts
def make_tuple(str_in): """ makes a tuple out of a string of the form "(a,b,c)" """ str_in = str_in.strip("()") l = str_in.split(",") return tuple(l)
bigcode/self-oss-instruct-sc2-concepts
def rotate_ccw(str_array: list[str]) -> list[str]: """ Rotate a list of strings quarter-turn counter-clock-wise :param str_array: array as a list of strings :return: array rotated counter clock-wise """ zip_array = list(''.join(c) for c in zip(*str_array)) ccw_rot_array = zip_array[::-1] return ccw_rot_array
bigcode/self-oss-instruct-sc2-concepts
def get_object_name_from_schema(obj: object) -> str: """ Returns the name of an object based on type. This is used to return a userfriendly exception to the client on bulk update operations. """ obj_name = type(obj).__name__ to_remove = ["Base", "Create", "Update"] for item in to_remove: if item in obj_name: obj_name = obj_name.replace(item, "") return obj_name
bigcode/self-oss-instruct-sc2-concepts
def normalize_description(description): """ Normalizes a docstrings. Parameters ---------- description : `str` or `Any` The docstring to clear. Returns ------- cleared : `str` or `Any` The cleared docstring. If `docstring` was given as `None` or is detected as empty, will return `None`. """ if (description is None) or (not isinstance(description, str)): return description lines = description.splitlines() for index in reversed(range(len(lines))): line = lines[index] line = line.strip() if line: lines[index] = line else: del lines[index] if not lines: return None return ' '.join(lines)
bigcode/self-oss-instruct-sc2-concepts
def max_counts(ng1, ng2): """ Return a dicitonary of ngram counts such that each count is the greater of the two individual counts for each ngram in the input ngram count dictionaries /ng1/ and /ng2/. """ ret = ng1.copy() for k, v in ng2.items(): ret[k] = max(ret.get(k, 0), v) return ret
bigcode/self-oss-instruct-sc2-concepts
def turn(n): """Formula from WIkipedia. n could be numpy array of integers """ return (((n & -n) << 1) & n) != 0
bigcode/self-oss-instruct-sc2-concepts
def ratio(x,y): """The ratio of 'x' to 'y'.""" return x/y
bigcode/self-oss-instruct-sc2-concepts
import operator def sequence_eq(sequence1, sequence2): """ Compares two sequences. Parameters ---------- sequence1 : sequence The first sequence. sequence2 : sequence The second sequence. Returns ------- bool `True` iff `sequence1` equals `sequence2`, otherwise `False`. """ return len(sequence1) == len(sequence2) and all(map(operator.eq, sequence1, sequence2))
bigcode/self-oss-instruct-sc2-concepts
import re def fix_tx_name(tx): """Remove the .[0-9] at the end of RefSeq IDs.""" if tx.startswith('NM'): return re.sub('\.[0-9]$', '', tx) else: return tx
bigcode/self-oss-instruct-sc2-concepts
def simple_call_string(function_name, argument_list, return_value=None): """Return function_name(arg[0], arg[1], ...) as a string""" call = function_name + "(" + \ ", ".join([var + "=" + repr(value) for (var, value) in argument_list]) + ")" if return_value is not None: call += " = " + repr(return_value) return call
bigcode/self-oss-instruct-sc2-concepts
def get_ticket_url_from_id(ticket_id): """ Get the associate ticket id :param ticket_id: `str` ticket_id :return: `str` ticket url """ return "https://jira.com/id={0}".format(ticket_id)
bigcode/self-oss-instruct-sc2-concepts
def _q_start(query_seq, q_seq): """ returns the starting pytyon string index of query alignment (q_seq) in the query_sequence (query_seq) :param query_seq: string full query sequence :param q_seq: string alignment sequence (may contain gaps as "-") :return: :example: >>_q_start(query_seq = "ATGATG", q_seq = "ATG") 0 >>_q_start(query_seq = "ATGATG", q_seq = "GATG") 2 >>_q_start(query_seq="ATGATG", q_seq="GA-TG") 2 """ q_seq = q_seq.replace("-", "") # remove gaps to get index for original sequence q_start = query_seq.find(q_seq) return(q_start)
bigcode/self-oss-instruct-sc2-concepts
from typing import List def set_ignored_keys(**kwargs) -> List[str]: """ Lets users pass a list of string that will not be checked by case-check. For example, validate_response(..., ignore_case=["List", "OF", "improperly cased", "kEYS"]). """ if 'ignore_case' in kwargs: return kwargs['ignore_case'] return []
bigcode/self-oss-instruct-sc2-concepts
def ft2m(ft): """feet -> meters""" return 0.3048*ft
bigcode/self-oss-instruct-sc2-concepts
def format_labels(labels): """ Convert a dictionary of labels into a comma separated string """ if labels: return ",".join(["{}={}".format(k, v) for k, v in labels.items()]) else: return ""
bigcode/self-oss-instruct-sc2-concepts
def _refresh_candles(candle: dict, candlelist: list[dict], max_len: int = 10000) -> tuple[list[dict], bool]: """Recieve candlestick data and append to candlestick list if it is new candlestick.""" changed = False if candle['k']['x']: if candlelist: if candle['k']['t'] != candlelist[-1]['t']: candlelist.append(candle['k']) changed = True if len(candlelist) > max_len: candlelist.pop(0) else: candlelist.append(candle['k']) changed = True return candlelist, changed
bigcode/self-oss-instruct-sc2-concepts
def get_string_for_language(language_name): """ Maps language names to the corresponding string for qgrep. """ language_name = language_name.lower().lstrip() if language_name == "c": return "tc-getCC" if language_name == "c++" or language_name == "cxx": return "tc-getCXX" if language_name == "": return ""
bigcode/self-oss-instruct-sc2-concepts
def _trc_filename(isd, version): """ Return the TRC file path for a given ISD. """ return 'ISD%s-V%s.trc' % (isd.isd_id, version)
bigcode/self-oss-instruct-sc2-concepts
def get_recs(user_recs, k=None): """ Extracts recommended item indices, leaving out their scores. params: user_recs: list of lists of tuples of recommendations where each tuple has (item index, relevance score) with the list of tuples sorted in order of decreasing relevance k: maximumum number of recommendations to include for each user, if None, include all recommendations returns: list of lists of recommendations where each list has the column indices of recommended items sorted in order they appeared in user_recs """ recs = [[item for item, score in recs][0:k] for recs in user_recs] return recs
bigcode/self-oss-instruct-sc2-concepts
import torch def polar_to_rect(mag, ang): """Converts the polar complex representation to rectangular""" real = mag * torch.cos(ang) imag = mag * torch.sin(ang) return real, imag
bigcode/self-oss-instruct-sc2-concepts