seed
stringlengths
1
14k
source
stringclasses
2 values
def _package_exists(module_name: str): """Check if a package exists""" mod = __import__(module_name) return mod is not None
bigcode/self-oss-instruct-sc2-concepts
import re def _parse_address(addr='XFD1048576') -> str: """ Parses the address given using a regexp and returns a cleaned string that can be split Accepts any valid excel cell address definition, incl. absoulte adresses with $. :param addr: :return: """ patt = re.match(r'^(\$?[A-Z]{1,3}\$?...
bigcode/self-oss-instruct-sc2-concepts
import itertools def generate_swapped_match(match, klass): """ Generate a new OpenFlow match with source and destination fields swapped :param match: OpenFlow match :param klass: Match class :return: Swapped match """ def get_args(m): args = {} for key, arg in m.items(): ...
bigcode/self-oss-instruct-sc2-concepts
def get_relative5_positions(brc5): """Get relative positions of barcode nucleotides from 5'end.""" return list(range(0, len(brc5)))
bigcode/self-oss-instruct-sc2-concepts
def averageListEntry(datalist): """ Return the average value of a Python List :param datalist: :return: average of list """ return sum(datalist)/len(datalist)
bigcode/self-oss-instruct-sc2-concepts
def add_vecs(vec1, vec2): """ Return the vector sum of vec1 and vec2 """ return [vec1[0] + vec2[0], vec1[1] + vec2[1]]
bigcode/self-oss-instruct-sc2-concepts
def ConvertAsci(L): """Converti les éléments d'une liste de lettres en entiers. Cette fonction converti une liste de caractères en une liste d'entier correspondant à leur code ascii. Parameters ---------- L : list `L` est une liste de caractères. Returns ------- La : list ...
bigcode/self-oss-instruct-sc2-concepts
def ipstr(barray): """Print a string of ip digits""" return ".".join('{}'.format(x) for x in barray)
bigcode/self-oss-instruct-sc2-concepts
def parse_zone_id(full_zone_id): """Parses the returned hosted zone id and returns only the ID itself.""" return full_zone_id.split("/")[2]
bigcode/self-oss-instruct-sc2-concepts
def guess_num() -> str: """ 049 Create a variable called comp_num and set the value to 50. Ask the user to enter a number. While their guess is not the same as the comp_num value, tell them if their guess is too low or too high and ask them to have another guess. If they enter the same value as comp...
bigcode/self-oss-instruct-sc2-concepts
def get_rank_function(rank_method): """ Gets the function to calculate the rank of a entity based on the `rank_method`. The function receives two inputs: (1) the number of entities whose rank is greater than the rank of the target entity; (2) the number of entities whose rank is equal to the rank of...
bigcode/self-oss-instruct-sc2-concepts
def diff_between_angles(angle_a: float, angle_b: float) -> float: """Calculates the difference between two angles angle_a and angle_b Args: angle_a (float): angle in degree angle_b (float): angle in degree Returns: float: difference between the two angles in degree. """ de...
bigcode/self-oss-instruct-sc2-concepts
def c(units): """Speed of light Parameters ---------- units : str Units for c. Supported units ===== ===================== =========== Unit Description Value ===== ===================== =========== m/s Meter per second...
bigcode/self-oss-instruct-sc2-concepts
def parse_line(line): """ Parse $VNYMR message: Yaw float deg Calculated attitude heading angle in degrees. Pitch float deg Calculated attitude pitch angle in degrees. Roll float deg Calculated attitude roll angle in degrees. MagX float Gauss Compensated magnetometer ...
bigcode/self-oss-instruct-sc2-concepts
import random def get_gif() -> str: """Returns a random GIF""" gifs = [ 'https://media.giphy.com/media/lZqlpPlT9llVm/giphy.gif', 'https://media.giphy.com/media/26FPzWoJlFvXyiZ6E/giphy.gif', 'https://media.giphy.com/media/9hqsyNVlf0DOU/giphy.gif', 'https://media.giphy.com/media/...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def _fetch_dirs(bucket, prefix=None): """Return set of all directory paths within a GCS bucket blob names Parameters ---------- bucket : google.cloud.storage.bucket.Bucket Returns ------- all_dirs : set """ all_dirs = set([]) for blob in bucket.list_bl...
bigcode/self-oss-instruct-sc2-concepts
def find_key(dict_obj, key): """ Return a value for a key in a dictionary. Function to loop over a dictionary and search for an specific key It supports nested dictionary Arguments: dict_obj (obj): A list or a dictionary key (str): dictionary key Return: (li...
bigcode/self-oss-instruct-sc2-concepts
def control_key_name(code): """Prefix the name of a control key with '^'""" name = chr(code - 1 + ord("A")) return f"^{name}"
bigcode/self-oss-instruct-sc2-concepts
import copy from functools import reduce def Gal_NLFSR(R, FF, ZF, N0): """Run Galois NLFSR Parameters ---------- R : int the number of output bits FF : list feedback functions of the Galois NLFSR ZF : list output function of the Galois NLFSR N0 : list initia...
bigcode/self-oss-instruct-sc2-concepts
import time def ago(past_timestamp): """ Returns a string, the number of days, hours, minutes, or seconds ago a timestamp is. Example output: 5h30m ago 3d5h ago 2m30s ago """ time_diff = int(time.time() - past_timestamp) time_diff_units = [] ...
bigcode/self-oss-instruct-sc2-concepts
def hg_repo(repo): """ Tests if a repo URL is a hg repo, then returns the repo url. """ if repo.startswith('https://bitbucket.org/') and not repo.endswith('.git'): return repo if repo.startswith('http://hg.'): return repo # not hg return None
bigcode/self-oss-instruct-sc2-concepts
import re def parse_component(comp): """Parse "10 ORE" -> (10, 'ORE').""" m = re.match(r'(\d+) ([A-Z]+)$', comp) assert m, comp amt, what = m.groups() return int(amt), what
bigcode/self-oss-instruct-sc2-concepts
def enact_interventions(background_inmate_turnover, background_release_number, time, infected_list, release_number, social_distance, social_distance_tau, stop_inflow_at_intervention, tau): """Enacts specified interventions.""" # Print intervention info print(f'Release intervention co...
bigcode/self-oss-instruct-sc2-concepts
def calc_RMM_phase(RMM1, RMM2, amp_thresh=0): """ Given RMM1 and RMM2 indices, calculate MJO phase. Provided by Zane K. Martin (CSU). Args: RMM1: EOF for MJO phase space diagram. RMM2: EOF for MJO phase space diagram. amp_thresh (int): MJO amplitude threshold. Defaults to 0....
bigcode/self-oss-instruct-sc2-concepts
def parse_bbox(bbox): """Given PDFMiner bbox info as a comma-delimited string, return it as a list of floats.""" return list(map(float, bbox.split(',')))
bigcode/self-oss-instruct-sc2-concepts
def d_perspective_camera_d_shape_parameters(shape_pc_uv, warped_uv, camera): """ Calculates the derivative of the perspective projection with respect to the shape parameters. Parameters ---------- shape_pc_uv : ``(n_points, 3, n_parameters)`` `ndarray` The (sampled) basis of the shape m...
bigcode/self-oss-instruct-sc2-concepts
import random def v(N=50,min=-10,max=10): """Generates a random vector (in an array) of dimension N; the values are integers in the range [min,max].""" out = [] for k in range(N): out.append(random.randint(min,max)) return out
bigcode/self-oss-instruct-sc2-concepts
def remove_non_printable_characters(string): """ Eliminates from the input string all the characters that are not printable. """ return ''.join(char for char in string if char.isprintable())
bigcode/self-oss-instruct-sc2-concepts
import itertools def has_fset_with_last(f, b, g): """Return True if g contains f-set of order b containing vertex n-1. Arguments: f -- predicate Given a graph and a subset of its vertex set, returns bool. g -- graph b -- nonnegative int We search for an order-b f-set. See isograp...
bigcode/self-oss-instruct-sc2-concepts
def gen_targets(polynomial_fn, data): """Generate targets (ground truth) from polynomial""" return [polynomial_fn(instance) for instance in data]
bigcode/self-oss-instruct-sc2-concepts
def celsius_to_fahrenheit(celsius): """ Celsius to Fahrenheit :param celsius: Degrees Celsius :return: Fahrenheit """ return float(celsius) * 9.0/5.0 + 32
bigcode/self-oss-instruct-sc2-concepts
def is_valid_mask(mask): """ Validates a UNIX style permissions mask. Mask must be octal. :type mask: str :param mask: The octal mask to be validated. For example: '0755'. :rtype: bool :return: True or False depending on whether mask passes validation. """ if mask is None: re...
bigcode/self-oss-instruct-sc2-concepts
def get_os_data_from_box_title(box_title: str) -> tuple: """ Gets OS name and version from a properly formatted box title. Returns: (str, str): OS name, OS version """ # Split box title into [os name, os version] box_title_elements = box_title.split(" v") return box_title_elements[...
bigcode/self-oss-instruct-sc2-concepts
import json def read_json(file): """ Loads JSON data from file Arguments: file: the path to the JSON file Return: the dictionary with parsed JSON """ with open(file) as f: data = json.load(f) return data
bigcode/self-oss-instruct-sc2-concepts
def flatten(data): """ Flatten list of tuples or tuple of tuples Args: data (list or tuple): list/tuple of data to flatten Returns: list: flattened list """ result = [] for var in data: if isinstance(var, tuple): result = flatten(var) else: ...
bigcode/self-oss-instruct-sc2-concepts
def CFE_mu(theta, l_tilde, n): """ Marginal disutility of labor supply from the constant Frisch elasticity utility function Args: theta (scalar): inverse of the Frisch elasticity of labor supply l_tilde (scalar): maximum amount of labor supply n (array_like): labor supply amoun...
bigcode/self-oss-instruct-sc2-concepts
import re def render(template, **params): """Replace placeholders in template with values from params.""" return re.sub(r'{{\s*([^}\s]+)\s*}}', lambda match: str(params.get(match.group(1), match.group(0))), template)
bigcode/self-oss-instruct-sc2-concepts
import hashlib def blake2b_hash(b: bytes) -> bytes: """ blake2b_hash hashes the given bytes with BLAKE2b (optimized for 64-bit platforms) Args: b (bytes): bytes to hash Returns: bytes: The hash result """ return hashlib.blake2b(b, digest_size=32).digest()
bigcode/self-oss-instruct-sc2-concepts
import math def format_bytes(input_bytes, precision=2): """ Format an integer number of input_bytes to a human readable string. If input_bytes is negative, this method raises ArithmeticError """ if input_bytes < 0: raise ArithmeticError("Only Positive Integers Allowed") if input...
bigcode/self-oss-instruct-sc2-concepts
import logging def setupLogging(logfileName, logFormat, logLevel, logToConsole=True): """ Setup simultaneous logging to file and console. """ # logFormat = "%(asctime)s %(levelname)s %(funcName)s:%(lineno)d # %(message)s" logging.basicConfig(filename=logfileName, level=logging.NOTSET, ...
bigcode/self-oss-instruct-sc2-concepts
def col_filter_dict_with_vals(df, col, field, values): """Filter dictionaries with specific values from a column with lists of dictionaries Args: df(pd.Dataframe): dataframe col(str): column name field(str): field of the dictionary to extract values(list)...
bigcode/self-oss-instruct-sc2-concepts
def deserialize_grid(serialized): """Deserialize a serialized grid. Arguments: serialized (str): Serialized representation of a grid of integers. Returns: list of lists of ints """ return [list(map(int, row.split())) for row in serialized.split('\n') if row]
bigcode/self-oss-instruct-sc2-concepts
def discard_console_entries() -> dict: """Discards collected exceptions and console API calls.""" return {"method": "Runtime.discardConsoleEntries", "params": {}}
bigcode/self-oss-instruct-sc2-concepts
def user(request): """Return db user.""" return request.config.getoption("--user")
bigcode/self-oss-instruct-sc2-concepts
def digitsToStr(digitNum, base=10): """ Convert list of digits (in specified base) to a string suitable for printing """ if base <= 10: return ''.join(chr(d + 48) for d in digitNum) elif base <= 36: def _char(d): if d < 10: return chr(d + 48) else: return chr(d + 55) re...
bigcode/self-oss-instruct-sc2-concepts
def byte(val, fmt="{:.2f}"): """Returns a byte representation of the input value :param val: value to format, must be convertible into a float :param fmt: optional output format string, defaults to {:.2f} :return: byte representation (e.g. <X> KiB, GiB, etc.) of the input value :rtype: string ...
bigcode/self-oss-instruct-sc2-concepts
def set_bit(number, offset): """Set the `offset` bit in the binary representation of `number` to 1""" return number | (1 << offset)
bigcode/self-oss-instruct-sc2-concepts
def map_palette(station): """ Function that returns the colour of a given station to use on the map, depending on the relationship between latest level and typical range. Args: station (MonitoringStation): The station. Returns: str: One of * 'gray' - typical range not cons...
bigcode/self-oss-instruct-sc2-concepts
def momentum_averager(momentum=0.9): """First order running averager with momentum. y_n = momentum*y_{n-1} + (1-momentum)*x_n""" def avg(): y = yield while True: x = yield y y = momentum*y + (1-momentum)*x return avg
bigcode/self-oss-instruct-sc2-concepts
def unpack_bitmap(num): """ Unpact bitmap to indicate which cores are set. For instance 11d = 1011b = [3,1,0] """ bit_length = num.bit_length() return set(idx for idx in range(bit_length) if 2**idx & num)
bigcode/self-oss-instruct-sc2-concepts
def get_next_set_offset(context, matching_sets): """Get the set search offset for the next query.""" # Set the next offset. If we found all matching sets, set the offset to 'done' if len(matching_sets) == 8: return f"{context.inline_query_id}:{context.offset + 8}" # We reached the end of the st...
bigcode/self-oss-instruct-sc2-concepts
def _check_git_access(req, dataset): """Validate HTTP token has access to the requested dataset.""" user = 'user' in req.context and req.context['user'] or None # Check that this request includes the correct token if user != None and 'dataset:git' in user['scopes'] and user['dataset'] == dataset: ...
bigcode/self-oss-instruct-sc2-concepts
def first_line(s): """Return first full line from string s (not including the '\n') """ i = s.find('\n') if i > 0: return s[:i] else: raise RuntimeError("can't find '\\n' in first_line")
bigcode/self-oss-instruct-sc2-concepts
def scrapeFloorplanSoups(soup): """Returns a list of soups, one per floorplan""" obj = soup.find('table', class_='availabilityTable') if obj is not None: floorplans = obj.find_all('tr', class_='rentalGridRow') if floorplans is not None: return floorplans return []
bigcode/self-oss-instruct-sc2-concepts
def get_filter(main_data, filtername='Month'): """Get filter params.""" filters = main_data[filtername].unique() return filters
bigcode/self-oss-instruct-sc2-concepts
def dict_contain(dict_a, dict_b): """Test if all the key:value pairs of dict_b are in dict_a. Arguments: dict_a -- The dictionary dict_b -- The sub-dictionary Return: True if all the key:value pairs of dict_b are in dict_a, False otherwise """ if len(dict_b) > len(dict_a): return...
bigcode/self-oss-instruct-sc2-concepts
def get_mol_coordinate(conformer): """ Get the coordination vectors of the molecule. :param conformer: Rdkit.Conformer. :return: np.array, The numpy array of the coordinates for the conformer. """ return conformer.GetPositions()
bigcode/self-oss-instruct-sc2-concepts
def _get_demographics_adjusted_to_contact_matrix_agebins(P_AGE, POPULATION_SIZE): """ Given that we are aggregating data from various sources, it is required that we adjust for the underlying assumptions. One of these structural assumption is of age groups. Contact matrices available consider only 16 classe...
bigcode/self-oss-instruct-sc2-concepts
def _aggregate_player_attributes(player_df, columns): """Compute the mean for all the players for the given columns Parameters ---------- player_df: pd.DataFrame The DataFrame containing the statistics of all the players columns: list The columns on which to calculate the mean ...
bigcode/self-oss-instruct-sc2-concepts
def calculate_accuracy(fx, y): """ Calculate top-1 accuracy fx = [batch size, output dim] y = [batch size] """ pred_idxs = fx.max(1, keepdim=True)[1] correct = pred_idxs.eq(y.view_as(pred_idxs)).sum() acc = correct.float()/pred_idxs.shape[0] return acc
bigcode/self-oss-instruct-sc2-concepts
def recall_interval(recall): """Return the interval of recall classified to 11 equal intervals of 10 (the field range is 0-100)""" return ((recall*10)//1)*10
bigcode/self-oss-instruct-sc2-concepts
import random def identify_random_elements(max, num_random_elements): """ Picks a specified number of random elements from 0 - max. Used to select poisoned workers Unmodified from Tolpegin et al. :param max: Max number to pick from :type max: int :param num_random_elements: Number of rand...
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple from typing import Dict from typing import Union from typing import List def parse_stan_vars( names: Tuple[str, ...] ) -> Tuple[Dict[str, Tuple[int, ...]], Dict[str, Tuple[int, ...]]]: """ Parses out Stan variable names (i.e., names not ending in `__`) from list of CSV file co...
bigcode/self-oss-instruct-sc2-concepts
import fileinput def read_description(path): """Reads a text description from a file. """ return ''.join(fileinput.input([path]))
bigcode/self-oss-instruct-sc2-concepts
def load_sentence_data(row): """Loads sentence-delimited data. Returns task_name, program, [array of sentences] """ if row['phrase_kind'] != 'output': return None, None, None else: task_name = row[""] program = row["program"] sentences = row['natural_language'].split(...
bigcode/self-oss-instruct-sc2-concepts
def powell(ind): """Powell function defined as: $$ f(x) = \sum_{i=1}^{n/4} ( (x_{4i-3}+10x_{4i-2})^2. + 5(x_{4i-1}-x_{4i})^2 + (x_{4i-2}-2x_{4i-1})^4 + 10(x_{4i-3}-x{4i})^4 )$$ with a search domain of $-4 < x_i < 5, 1 \leq i \leq n$. The global minimum is at $f(x_1, ..., x_n) = f(0, ..., 0) = 0. """...
bigcode/self-oss-instruct-sc2-concepts
def gardner(vp, alpha=310, beta=0.25): """ Compute bulk density (in kg/m^3) from vp (in m/s). """ return alpha * vp ** beta
bigcode/self-oss-instruct-sc2-concepts
def normalize_image(img): """ Scale image Parameters ---------- img : numpy array image img to be scaled Returns ------- numpy array image scaled """ return img / 255
bigcode/self-oss-instruct-sc2-concepts
import json def read_proxy_config(file_name): """convert proxy file from json file to python data structure Parameters -------------- file_name : str location of proxies json list file Returns ------------- object datastructure representation of json file """ with...
bigcode/self-oss-instruct-sc2-concepts
import re def mark_code_blocks(txt, keyword='>>>', split='\n', tag="```", lang='python'): """ Enclose code blocks in formatting tags. Default settings are consistent with markdown-styled code blocks for Python code. Args: txt: String to search for code blocks. keyword(optional, strin...
bigcode/self-oss-instruct-sc2-concepts
def fasta_processor(filename): """ Given a fasta generates a unique string with it to be processed by the next functions """ lines = [line.rstrip('\n') for line in open(filename)] # remove > line del lines[0] # Join sequence sequence = "".join(lines) return sequence
bigcode/self-oss-instruct-sc2-concepts
def seq_adjacent_terms_sum(sequence: list, sum_level: int): """ A function to extract the sums of adjacent terms sequence: A list of integers that contains the sequence sum_level: The level indicates the number of times the operation will be applied on the sequence return: A list of list of integers...
bigcode/self-oss-instruct-sc2-concepts
def string_tag(name, value): """Create a DMAP tag with string data.""" return name.encode('utf-8') + \ len(value).to_bytes(4, byteorder='big') + \ value.encode('utf-8')
bigcode/self-oss-instruct-sc2-concepts
def get_in(d, *keys, default=None): """Get a nested value from a dict.""" for k in keys: if not isinstance(d, dict) or k not in d: return default d = d[k] return d
bigcode/self-oss-instruct-sc2-concepts
def count_flowables_by_class(flowlist): """ Counts flowables by class :param flowlist: A FlowList in standard format :return: pandas df with 'Class' and counts of unique flowables """ flowables_by_class = flowlist[['Class', 'Flowable']] flowables_by_class = flowables_by_class.drop_duplicates...
bigcode/self-oss-instruct-sc2-concepts
def or_default(value, default): """ Helps to avoid using a temporary variable in cases similiar to the following:: if slow_function() is not None: return slow_function() else: return default """ return value if value is not None else default
bigcode/self-oss-instruct-sc2-concepts
import random import math def gamma(alpha=1): """ Returns value greater than 0 from the gamma distribution (https://en.wikipedia.org/wiki/Gamma_distribution). Parameter alpha controls the distribution's shape and should be a positive integer (if a non-integer is provided, the value is rounded.) W...
bigcode/self-oss-instruct-sc2-concepts
import re def get_project_names(r): """ Extracts a list of project names from a wiki page HTML. """ # projects short names are in h2 elements without any attributes # there is one more h2 element, but it has `class` attribute # re_proj_names = re.compile(r'<h2><a[^>]>(.+)</a></h2>') re_pro...
bigcode/self-oss-instruct-sc2-concepts
def chromosome(record): """ Get the chromosome this record is from. If it is part of a scaffold then it will be returned. """ basic = record.id if basic.startswith("chromosome:") or basic.startswith("scaffold:"): parts = basic.split(":") return parts[2] return basic.split("....
bigcode/self-oss-instruct-sc2-concepts
def file_type_by_extension( extension): """ Tries to guess the file type by looking up the filename extension from a table of known file types. Will return the type as string ("audio", "video" or "torrent") or None if the file type cannot be determined. """ types={ 'audio': [ ...
bigcode/self-oss-instruct-sc2-concepts
def CStructName(t): """Obtain the name of the CType struct from Python.""" # Clang2py translates C structs to python classes with # prefixes like 'struct_c__SA_Foo' and then assign # types like 'Foo = struct_c__SA_Foo'. This function # gets the real C struct name by removing those prefixes. struct_name = t....
bigcode/self-oss-instruct-sc2-concepts
def __get_num_parent_instantiations__(parents, num_values): """ Gets the number of parent instantiations. :param parents: List of parent indices. :param num_values: List of the number of values per node. :return: Number of parent instantiations. """ num_pa_instantiations = 1 for pa in p...
bigcode/self-oss-instruct-sc2-concepts
import csv def read_source_file(filename, tsv=False): """ Read a source file into a list of video dictionaries :param filename: A file opened for reading :param tsv: The type of file: false for UTF-8 CSV, true for UTF-16 TSV :return: A list of video dictionaries """ with open(filename, 'r', newline='', ...
bigcode/self-oss-instruct-sc2-concepts
def replace_files(d,file_list): """ Replace files for mzmine task Inputs: d: an xml derived dictionary of batch commands file_list: a list of full paths to mzML files Outputs: d: an xml derived dict with new files in it """ for i,step in enumerate(d['batch']['batchstep']): ...
bigcode/self-oss-instruct-sc2-concepts
def _validate_dataset(dataset): """ Confirm a valid ICESat-2 dataset was specified """ if isinstance(dataset, str): dataset = str.upper(dataset) assert dataset in [ "ATL01", "ATL02", "ATL03", "ATL04", "ATL06", "ATL07...
bigcode/self-oss-instruct-sc2-concepts
def vgr_callback(prepend_msg='', logger=None, msg_update_callback=None): """Create a callback function to use for vsphere-guest-run functions. :param str prepend_msg: string to prepend to all messages received from vsphere-guest-run function. :param logging.Logger logger: logger to use in case of e...
bigcode/self-oss-instruct-sc2-concepts
def get_padded_string(string: str, in_string: str, from_char_index: int) -> str: """ Return a string that is appropriately padded/indented, given a starting position. For example, if a starting index of 4 is given for a string " content\ngoes here", th...
bigcode/self-oss-instruct-sc2-concepts
def ret_group_delay(taps): """ Helper function computes group delay of FIR filter. """ grp_delay = (len(taps)-1)//2 return grp_delay
bigcode/self-oss-instruct-sc2-concepts
def _role_valid(roles, role_list): """ Return ``True`` if there is an intersection between the users roles and any roles in the constraint. """ if [role for role in roles if role in role_list]: return True return False
bigcode/self-oss-instruct-sc2-concepts
import collections import itertools import logging def categorize(metapath): """ Returns the classification of a given metapath as one of a set of metapath types which we approach differently. Parameters ---------- metapath : hetio.hetnet.MetaPath Returns ------- classification :...
bigcode/self-oss-instruct-sc2-concepts
def is_quote(code, idx=0): """Position in string is an unescaped quotation mark.""" return (0 <= idx < len(code) and code[idx] == '"' and (idx == 0 or code[idx-1] != '\\'))
bigcode/self-oss-instruct-sc2-concepts
def deep_merge(left, right): """Deep merge dictionaries, replacing values from right""" if isinstance(left, dict) and isinstance(right, dict): result = left.copy() for key in right: if key in left: result[key] = deep_merge(left[key], right[key]) else: ...
bigcode/self-oss-instruct-sc2-concepts
import csv def write_proc_periods(start_times, end_times, fname): """ writes an output file containing start and stop times of periods to process Parameters ---------- start_times, end_times : datetime object The starting and ending times of the periods fname : str The nam...
bigcode/self-oss-instruct-sc2-concepts
def rename_col_index(df, label): """rename level 0 of column indes to "label" Parameters ---------- df : dataframe labour force and population timeseries data label : string name of level 0 of multiindex Returns ------- df dataframe with column multiinde...
bigcode/self-oss-instruct-sc2-concepts
def calc_checksum(content: bytes) -> bytes: """ Calculate checksum using 8-bit Fletcher's algorithm. :param bytes content: message content, excluding header and checksum bytes :return: checksum :rtype: bytes """ check_a = 0 check_b = 0 for char in content: check_a += char...
bigcode/self-oss-instruct-sc2-concepts
def fix_object(value): """Fixes python objects so that they can be properly inserted into SQL queries""" if isinstance(value, str): return value.encode('utf-8') else: return value
bigcode/self-oss-instruct-sc2-concepts
def ranking_list(input_list): """ Returns the rank of each element of the list :param input_list: a list of elements :return: output_list: the corresponding ranks """ indices = list(range(len(input_list))) indices.sort(key=lambda x: input_list[x]) output_list = [0] * len(indices) fo...
bigcode/self-oss-instruct-sc2-concepts
from typing import Any from typing import List from typing import Tuple import csv def get_phone_times(phn_file: Any) -> List[Tuple[int, int, str]]: """Gets endpoint times for each phone in a recording. Reads phone endpoint times from .phn file. The .phn file has a simple text format as used in TIMIT. Each row...
bigcode/self-oss-instruct-sc2-concepts
import asyncio def _run(awaitable): """A shim for :func:`asyncio.run` from 3.7+.""" loop = asyncio.get_event_loop() return loop.run_until_complete(awaitable)
bigcode/self-oss-instruct-sc2-concepts
import math def clog(x,b=2): """returns the ceil of log base b x, and never returns negative.""" if x < b: return 1 else: return math.ceil(math.log(x,b))
bigcode/self-oss-instruct-sc2-concepts