seed
stringlengths
1
14k
source
stringclasses
2 values
def prepareFixed(query, ftypes, fixed): """Called by :meth:`.FileTreeManager.update`. Prepares a dictionary which contains all possible values for each fixed variable, and for each file type. :arg query: :class:`.FileTreeQuery` object :arg ftypes: List of file types to be displayed :arg fixed: List of fixed variables :returns: A dict of ``{ ftype : { var : [value] } }`` mappings which, for each file type, contains a dictionary of all fixed variables and their possible values. """ allvars = query.variables() # Create a dict for each file type # containing { var : [value] } # mappings for all fixed variables # which are relevant to that file # type. _fixed = {} for ftype in ftypes: ftvars = query.variables(ftype) _fixed[ftype] = {} for var in fixed: if var in ftvars: _fixed[ftype][var] = allvars[var] fixed = _fixed return fixed
bigcode/self-oss-instruct-sc2-concepts
def manhattan(p1, p2): """Return manhattan distance between 2 points.""" return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])
bigcode/self-oss-instruct-sc2-concepts
import re def _load_line(fh) -> str: """Loads a line from the file, skipping blank lines. Validates format, and removes whitespace. """ while True: line = fh.readline() line = line.rstrip() line = re.sub(" ", "", line) if line: # Not blank. assert len(line)==9, f"Invalid {line=}" return line # else blank line, keep reading
bigcode/self-oss-instruct-sc2-concepts
def find_all_lowest(l, f): """Find all elements x in l where f(x) is minimal""" if len(l) == 1: return l minvalue = min([f(x) for x in l]) return [x for x in l if f(x) == minvalue]
bigcode/self-oss-instruct-sc2-concepts
def get_num_attachments(connection): """Get the number of attachments that need to be migrated""" with connection.cursor() as cursor: cursor.execute("SELECT COUNT(*) FROM form_processor_xformattachmentsql") return cursor.fetchone()[0]
bigcode/self-oss-instruct-sc2-concepts
def is_sorted(ls): """Returns true if the list is sorted""" return ls == sorted(ls)
bigcode/self-oss-instruct-sc2-concepts
import math def sin100( x ): """ A sin function that returns values between 0 and 100 and repeats after x == 100. """ return 50 + 50 * math.sin( x * math.pi / 50 )
bigcode/self-oss-instruct-sc2-concepts
def curve_between( coordinates, start_at, end_at, start_of_contour, end_of_contour): """Returns indices of a part of a contour between start and end of a curve. The contour is the cycle between start_of_contour and end_of_contour, and start_at and end_at are on-curve points, and the return value is the part of the curve between them. Args: coordinates: An slicable object containing the data. start_at: The index of on-curve beginning of the range. end_at: The index of on-curve end of the range. start_of_contour: The index of beginning point of the contour. end_of_contour: The index of ending point of the contour. Returns: A list of coordinates, including both start_at and end_at. Will go around the contour if necessary. """ if end_at > start_at: return list(coordinates[start_at:end_at + 1]) elif start_of_contour == end_of_contour: # single-point contour assert start_at == end_at == start_of_contour return [coordinates[start_at]] else: # the curve goes around the range return (list(coordinates[start_at:end_of_contour + 1]) + list(coordinates[start_of_contour:end_at + 1]))
bigcode/self-oss-instruct-sc2-concepts
def X_y_split(data: list): """ Split data in X and y for ML models. """ X = [row[0] for row in data] y = [row[1] for row in data] return X, y
bigcode/self-oss-instruct-sc2-concepts
def attr_str(ctrl_name, attr_name): """ join the two strings together to form the attribute name. :param ctrl_name: :param attr_name: :return: """ return '{}.{}'.format(ctrl_name, attr_name)
bigcode/self-oss-instruct-sc2-concepts
def percent_change(starting_point, current_point): """ Computes the percentage difference between two points :return: The percentage change between starting_point and current_point """ default_change = 0.00001 try: change = ((float(current_point) - starting_point) / abs(starting_point)) * 100.00 if change == 0.0: return default_change else: return change except: return default_change
bigcode/self-oss-instruct-sc2-concepts
def internal_header_to_external(internal_header: str) -> str: """ Within our app we access headers in this form HTTP_LMS_TYPE but they are supplied like LMS-TYPE. This converts the internal form to the external form for error reporting purposes. """ assert internal_header.startswith('HTTP_') assert '-' not in internal_header no_http = internal_header[5:] no_http_dashes = no_http.replace('_', '-') return no_http_dashes
bigcode/self-oss-instruct-sc2-concepts
def get_deps(project_config): """ Get the recipe engine deps of a project from its recipes.cfg file. """ # "[0]" Since parsing makes every field a list return [dep['project_id'][0] for dep in project_config.get('deps', [])]
bigcode/self-oss-instruct-sc2-concepts
from typing import Any import base64 import gzip import json def compress(input: Any) -> str: """ Convenience function for compressing something before sending it to Cloud. Converts to string, encodes, compresses, encodes again using b64, and decodes. Args: - input (Any): the dictionary to be compressed Returns: - str: The string resulting from the compression """ return base64.b64encode(gzip.compress(json.dumps(input).encode())).decode()
bigcode/self-oss-instruct-sc2-concepts
def _parameterval(tsr,sol,coef): """ Creating polynomial surface based on given coefficients and calculating the point at a given TSR and solidity Parameters ---------- tsr : float specified tip-speed ratio sol : float specified solidity coef : array the polynomial surface coefficients for a given EMG parameter Returns ---------- surf : float the polynomial surface value for the EMG parameter based on tip-speed ratio and solidity """ a = coef[0] b = coef[1] c = coef[2] d = coef[3] e = coef[4] f = coef[5] g = coef[6] h = coef[7] i = coef[8] j = coef[9] surf = a + b*tsr + c*sol + d*tsr**2 + e*tsr*sol + f*sol**2 + g*tsr**3 + h*tsr**2*sol + i*tsr*sol**2 + j*sol**3 return surf
bigcode/self-oss-instruct-sc2-concepts
def get_callback(request, spider): """Get ``request.callback`` of a :class:`scrapy.Request`""" if request.callback is None: return getattr(spider, 'parse') return request.callback
bigcode/self-oss-instruct-sc2-concepts
import hashlib import binascii def verify_password(stored_password, provided_password): """Verify a stored password against one provided by user""" pwdhash = hashlib.pbkdf2_hmac( "sha256", provided_password.encode("utf-8"), stored_password["salt"].encode(), 10000, ) return pwdhash == binascii.a2b_base64(stored_password["pwdhash"])
bigcode/self-oss-instruct-sc2-concepts
def get_lat_lon_alt(pandora_filepath): """Returns a dictionary of lat, lon, alt extracted from the pandora file :param pandora_filepath: The pandora file :type pandora_filepath: str :returns: A dict of {"lat":lat, "lon":lon, "alt":alt} :rtype: dict{str:int} """ lat = None lon = None alt = None with open(pandora_filepath, 'r', encoding="Latin-1") as pandora_file: while (lat == None or lon == None or alt == None): current_line = pandora_file.readline() if current_line.startswith("Location latitude [deg]:"): lat = float(current_line.split(":")[1]) elif current_line.startswith("Location longitude [deg]:"): lon = float(current_line.split(":")[1]) elif current_line.startswith("Location altitude [m]:"): alt = float(current_line.split(":")[1]) elif current_line.startswith("--------"): # Future improvements to code: Change for exception if this might happen print("Lat/lon/alt not found in file {}".format(pandora_filepath)) return return {"lat": lat, "lon": lon, "alt": alt}
bigcode/self-oss-instruct-sc2-concepts
def is_user_message(message): """Check if the message is a message from the user""" return (message.get('message') and message['message'].get('text') and not message['message'].get("is_echo"))
bigcode/self-oss-instruct-sc2-concepts
def _ToString(rules): """Formats a sequence of Rule objects into a string.""" return '[\n%s\n]' % '\n'.join('%s' % rule for rule in rules)
bigcode/self-oss-instruct-sc2-concepts
import requests def gateway(self, IPFS_path: str, **kwargs): """ Retrieve an object from the IFPS gateway (useful if you do not want to rely on a public gateway, such as ipfs.blockfrost.dev). https://docs.blockfrost.io/#tag/IPFS-Gateway :param IPFS_path: Path to the IPFS object. :type IPFS_path: str :returns file text. :rtype data :raises ApiError: If API fails :raises Exception: If the API response is somehow malformed. """ response = requests.get( url=f"{self.url}/ipfs/gateway/{IPFS_path}", headers=self.default_headers, ) return response
bigcode/self-oss-instruct-sc2-concepts
import json def ipynb2markdown(ipynb): """ Extract Markdown cells from iPython Notebook Args: ipynb (str): iPython notebook JSON file Returns: str: Markdown """ j = json.loads(ipynb) markdown = "" for cell in j["cells"]: if cell["cell_type"] == "markdown": markdown += "".join(cell["source"]) + "\n" return markdown
bigcode/self-oss-instruct-sc2-concepts
def get_target_shape(shape, size_factor): """ Given an shape tuple and size_factor, return a new shape tuple such that each of its dimensions is a multiple of size_factor :param shape: tuple of integers :param size_factor: integer :return: tuple of integers """ target_shape = [] for dimension in shape: rounded_down_dimension = size_factor * (dimension // size_factor) rounded_up_dimension = rounded_down_dimension + size_factor rounded_down_difference = abs(dimension - rounded_down_dimension) rounded_up_difference = abs(dimension - rounded_up_dimension) target_dimension = \ rounded_down_dimension if rounded_down_difference <= rounded_up_difference else rounded_up_dimension target_shape.append(target_dimension) return tuple(target_shape)
bigcode/self-oss-instruct-sc2-concepts
def format_row(row: list) -> list: """Format a row of scraped data into correct type All elements are scraped as strings and should be converted to the proper format to be used. This converts the following types: - Percentages become floats (Ex: '21.5%' --> 0.215) - Numbers become ints (Ex: '2020' --> 2020) - '-' becomes None - Booleans stay booleans - Strings stay strings :param row: list to be converted :return: list in converted form :rtype: list """ new_row = [] for i in row: if type(i) == bool: new_row.append(i) continue i = i.strip() if i == '-': new_row.append(None) elif i[-1] == '%': i = i[:-1] new_row.append(round(float(i) / 100, len(i))) else: try: new_row.append(int(i)) except ValueError: new_row.append(i) return new_row
bigcode/self-oss-instruct-sc2-concepts
def count_in_progress(state, event): """ Count in-progress actions. Returns current state as each new produced event, so we can see state change over time """ action = event['action'] phase = event['phase'] if phase == 'start': state[action] = state.get(action, 0) + 1 elif phase == 'complete': state[action] = state[action] - 1 elif phase.startswith('fail'): # Using startswith because some events use 'failure' vs 'failed' state[action] = state[action] - 1 state[f'{action}.failed'] = state.get(f'{action}.failed', 0) + 1 state['timestamp'] = event['timestamp'] return state, state
bigcode/self-oss-instruct-sc2-concepts
def is_draft(record, ctx): """Shortcut for links to determine if record is a draft.""" return record.is_draft
bigcode/self-oss-instruct-sc2-concepts
def approx_equal(a_value: float, b_value: float, tolerance: float = 1e-4) -> float: """ Approximate equality. Checks if values are within a given tolerance of each other. @param a_value: a value @param b_value: b value @param tolerance: @return: boolean indicating values are with in given radius """ return abs(a_value - b_value) <= max(abs(a_value), abs(b_value)) * tolerance
bigcode/self-oss-instruct-sc2-concepts
def create_zero_matrix(rows: int, columns: int) -> list: """ Creates a matrix rows * columns where each element is zero :param rows: a number of rows :param columns: a number of columns :return: a matrix with 0s e.g. rows = 2, columns = 2 --> [[0, 0], [0, 0]] """ if not isinstance(rows, int) or not isinstance(columns, int) or \ isinstance(rows, bool) or isinstance(columns, bool): return [] zero_matrix = [] n_columns = [0] * columns if n_columns: zero_matrix = [[0] * columns for _ in range(rows)] return zero_matrix
bigcode/self-oss-instruct-sc2-concepts
def _fix_attribute_names(attrs, change_map): """ Change attribute names as per values in change_map dictionary. Parameters ---------- :param attrs : dict Dict of operator attributes :param change_map : dict Dict of onnx attribute name to mxnet attribute names. Returns ------- :return new_attr : dict Converted dict of operator attributes. """ new_attr = {} for k in attrs.keys(): if k in change_map: new_attr[change_map[k]] = attrs[k] else: new_attr[k] = attrs[k] return new_attr
bigcode/self-oss-instruct-sc2-concepts
def strip_token(token) -> str: """ Strip off suffix substring :param token: token string :return: stripped token if a suffix found, the same token otherwise """ if token.startswith(".") or token.startswith("["): return token pos = token.find("[") # If "." is not found if pos < 0: pos = token.find(".") # If "[" is not found or token starts with "[" return token as is. if pos <= 0: return token return token[:pos:]
bigcode/self-oss-instruct-sc2-concepts
def str_to_tile_index(s, index_of_a = 0xe6, index_of_zero = 0xdb, special_cases = None): """ Convert a string to a series of tile indexes. Params: s: the string to convert index_of_a: begining of alphabetical tiles index_of_zero: begining of numerical tiles special_cases: what to if a character is not alpha-numerical special_case can be: None - non alpha-numerical characters are skipped callable - special cases is called for each non alpha-numerical character dict - a correspondance table between characters and their index """ res = [] for c in s: index = None if ord(c) >= ord('a') and ord(c) <= ord('z'): index = ord(c) - ord('a') + index_of_a elif ord(c) >= ord('A') and ord(c) <= ord('Z'): index = ord(c) - ord('A') + index_of_a elif ord(c) >= ord('0') and ord(c) <= ord('9'): index = ord(c) - ord('0') + index_of_zero elif callable(special_cases): index = special_cases(c) elif special_cases is not None: index = special_cases.get(c) if index is not None: res.append(index) return res
bigcode/self-oss-instruct-sc2-concepts
import csv def load_data(filename): """ Load shopping data from a CSV file `filename` and convert into a list of evidence lists and a list of labels. Return a tuple (evidence, labels). evidence should be a list of lists, where each list contains the following values, in order: - Administrative, an integer - Administrative_Duration, a floating point number - Informational, an integer - Informational_Duration, a floating point number - ProductRelated, an integer - ProductRelated_Duration, a floating point number - BounceRates, a floating point number - ExitRates, a floating point number - PageValues, a floating point number - SpecialDay, a floating point number - Month, an index from 0 (January) to 11 (December) - OperatingSystems, an integer - Browser, an integer - Region, an integer - TrafficType, an integer - VisitorType, an integer 0 (not returning) or 1 (returning) - Weekend, an integer 0 (if false) or 1 (if true) labels should be the corresponding list of labels, where each label is 1 if Revenue is true, and 0 otherwise. """ evidence = [] labels = [] # Read in the data and clean it with open(filename) as csvfile: reader = list(csv.DictReader(csvfile)) int_lst = [ 'Administrative', 'Informational', 'ProductRelated', 'Month', 'OperatingSystems', 'Browser', 'Region', 'TrafficType', 'VisitorType', 'Weekend' ] flt_lst = [ 'Administrative_Duration', 'Informational_Duration', 'ProductRelated_Duration', 'BounceRates', 'ExitRates', 'PageValues', 'SpecialDay' ] month_dict = { 'Jan': 0, 'Feb': 1, 'Mar': 2, 'Apr': 3, 'May': 4, 'June': 5, 'Jul': 6, 'Aug': 7, 'Sep': 8, 'Oct': 9, 'Nov': 10, 'Dec': 11 } for row in reader: # Set month to numerical value from dict row['Month'] = month_dict[row['Month']] row['VisitorType'] = 1 if row['VisitorType'] == 'Returning_Visitor' else 0 row['Weekend'] = 1 if row['Weekend'] == 'TRUE' else 0 row['Revenue'] = 1 if row['Revenue'] == 'TRUE' else 0 # Typecast to int all items in int_lst for item in int_lst: row[item] = int(row[item]) # Typecast to float all items in flt_lst for item in flt_lst: row[item] = float(row[item]) # Append the cleaned data into the new lists evidence.append(list(row.values())[:-1]) labels.append(list(row.values())[-1]) return (evidence, labels)
bigcode/self-oss-instruct-sc2-concepts
def edges_from_matchings(matching): """ Identify all edges within a matching. Parameters ---------- matching : list of all matchings returned by matching api Returns ------- edges : list of all edge tuples """ edges = [] nodes = [] # only address highest confidence matching? m = 0 for match in matching: print(m) m += 1 # only address good matchings if match['confidence'] > 0.95: # look through all legs for leg in match['legs']: # Extract all node sets node = leg['annotation']['nodes'] for i in range(len(node) - 1): if (node[i], node[i+1], 0) not in edges: edges.append((node[i], node[i+1], 0)) return edges
bigcode/self-oss-instruct-sc2-concepts
def find_faces_with_vertex(index, faces): """ For a given vertex, find all faces containing this vertex. Note: faces do not have to be triangles. Parameters ---------- index : integer index to a vertex faces : list of lists of three integers the integers for each face are indices to vertices, starting from zero Returns ------- faces_with_vertex : list of lists of three integers the integers for each face are indices to vertices, starting from zero Examples -------- >>> # Simple example: >>> from mindboggle.guts.mesh import find_faces_with_vertex >>> faces = [[0,1,2],[0,2,3],[0,3,4],[0,1,4],[4,3,1]] >>> index = 3 >>> find_faces_with_vertex(index, faces) [[0, 2, 3], [0, 3, 4], [4, 3, 1]] """ faces_with_vertex = [x for x in faces if index in x] return faces_with_vertex
bigcode/self-oss-instruct-sc2-concepts
def definitions_match(definition_objects, expected_descriptor): """ Return whether Definition objects have expected properties. The order of the definitions, and their sources, may appear in any order. expected_descriptor is a shorthand format, consisting of a list or tuple `(definition_string, sources)` where `sources` may be a single string for a single source, or a list of strings for multiple sources. """ # We want to do set comparisons. But to put things inside sets, we have to # first make them hashable by freezing them. comparable_actual = set( (defn.text, frozenset(c.abbrv for c in defn.citations.all())) for defn in definition_objects ) comparable_expected = set( (e[0], frozenset(e[1] if isinstance(e[1], list) else [e[1]])) for e in expected_descriptor ) return comparable_actual == comparable_expected
bigcode/self-oss-instruct-sc2-concepts
from typing import Pattern import re import fnmatch def _glob_to_re(glob: str) -> Pattern[str]: """Translate and compile glob string into pattern.""" return re.compile(fnmatch.translate(glob))
bigcode/self-oss-instruct-sc2-concepts
def run_dir_name(run_num): """ Returns the formatted directory name for a specific run number """ return "run{:03d}".format(run_num)
bigcode/self-oss-instruct-sc2-concepts
def _and(x,y): """Return: x and y (used for reduce)""" return x and y
bigcode/self-oss-instruct-sc2-concepts
def get_policy(observations, hparams): """Get a policy network. Args: observations: Tensor with observations hparams: parameters Returns: Tensor with policy and value function output """ policy_network_lambda = hparams.policy_network action_space = hparams.environment_spec.action_space return policy_network_lambda(action_space, hparams, observations)
bigcode/self-oss-instruct-sc2-concepts
from typing import Counter def column_checker(chat_df, message_df, attachment_df, handle_df): """ Checks the columns of the major tables for any conflicting column names :param chat_df: the chat table dataframe :param message_df: the message table dataframe :param attachment_df: the attachment table dataframe :param handle_df: the handle table dataframe :return: a list of conflicting column names """ columns = chat_df.columns.tolist() + message_df.columns.tolist() + attachment_df.columns.tolist() + \ handle_df.columns.tolist() conflicts = [item for item, count in Counter(columns).items() if count > 1] return conflicts
bigcode/self-oss-instruct-sc2-concepts
def _IsMacro(command): """Checks whether a command is a macro.""" if len(command) >= 4 and command[0] == "MACRO" and command[2] == "=": return True return False
bigcode/self-oss-instruct-sc2-concepts
import json from collections import defaultdict def read_config_filters(file_config): """ Parse json file to build the filtering configuration Args: file_config (Path): absolute path of the configuration file Returns: combine (str): filter_param (dict): {key:list of keywords} """ # Standard library imports filter_param = defaultdict(list) with open(file_config, "r") as read_file: config_filter = json.load(read_file) combine = config_filter["COMBINE"] exclusion = config_filter["EXCLUSION"] for key, value in config_filter.items(): if isinstance(value, dict): if value['mode']: filter_param[key] = value["list"] return combine,exclusion,filter_param
bigcode/self-oss-instruct-sc2-concepts
def negate_conf(c): """Negate a line of configuration.""" return "no %s" % c
bigcode/self-oss-instruct-sc2-concepts
def input_s(prompt: str = "", interrupt: str = "", eof: str = "logout") -> str: """ Like Python's built-in ``input()``, but it will give a string instead of raising an error when a user cancel(^C) or an end-of-file(^D on Unix-like or Ctrl-Z+Return on Windows) is received. prompt The prompt string, if given, is printed to standard output without a trailing newline before reading input. interrupt The interrupt string will be returned when a KeyboardInterrupt occurs. eof The end-of-file string will be returned when an EOFError occurs. Note: This implement keeps trailing a new line even when KeyboardInterrupt or EOFError is raised. """ try: return input(prompt) except KeyboardInterrupt: print() return interrupt except EOFError: print() return eof
bigcode/self-oss-instruct-sc2-concepts
import re def instruction_decoder_name(instruction): """ Given an instruction with the format specified in ARMv7DecodingSpec.py output a unique name that represents that particular instruction decoder. """ # Replace all the bad chars. name = re.sub('[\s\(\)\-\,\/\#]', '_', instruction["name"]) # Append the encoding. name += "_" + instruction["encoding"] # We may end up with double dashes, remove them. name = name.replace("__", "_") return "decode_" + name.lower()
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional import requests def get_def_tenant_id(sub_id: str) -> Optional[str]: """ Get the tenant ID for a subscription. Parameters ---------- sub_id : str Subscription ID Returns ------- Optional[str] TenantID or None if it could not be found. Notes ----- This function returns the tenant ID that owns the subscription. This may not be the correct ID to use if you are using delegated authorization via Azure Lighthouse. """ get_tenant_url = ( "https://management.azure.com/subscriptions/{subscriptionid}" + "?api-version=2015-01-01" ) resp = requests.get(get_tenant_url.format(subscriptionid=sub_id)) # Tenant ID is returned in the WWW-Authenticate header/Bearer authorization_uri www_header = resp.headers.get("WWW-Authenticate") if not www_header: return None hdr_dict = { item.split("=")[0]: item.split("=")[1].strip('"') for item in www_header.split(", ") } tenant_path = hdr_dict.get("Bearer authorization_uri", "").split("/") return tenant_path[-1] if tenant_path else None
bigcode/self-oss-instruct-sc2-concepts
import asyncio async def subprocess_run_async(*args, shell=False): """Runs a command asynchronously. If ``shell=True`` the command will be executed through the shell. In that case the argument must be a single string with the full command. Otherwise, must receive a list of program arguments. Returns the output of stdout. """ if shell: cmd = await asyncio.create_subprocess_shell( args[0], stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, ) else: cmd = await asyncio.create_subprocess_exec( *args, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, ) await cmd.communicate() return cmd
bigcode/self-oss-instruct-sc2-concepts
from functools import reduce def djb2(L): """ h = 5381 for c in L: h = ((h << 5) + h) + ord(c) # h * 33 + c return h """ return reduce(lambda h, c: ord(c) + ((h << 5) + h), L, 5381)
bigcode/self-oss-instruct-sc2-concepts
def create_user(ssh_fn, name): """Create a user on an instance using the ssh_fn and name. The ssh_fn is a function that takes a command and runs it on the remote system. It must be sudo capable so that a user can be created and the remote directory for the user be determined. The directory for the user is created in /var/lib/{name} :param ssh_fn: a sudo capable ssh_fn that can run commands on the unit. :type ssh_fn: Callable[[str], str] :param name: the name of the user to create. :type name: str :returns: the directory of the new user. :rtype: str """ dir_ = "/var/lib/{name}".format(name=name) cmd = ["sudo", "useradd", "-r", "-s", "/bin/false", "-d", dir_, "-m", name] ssh_fn(cmd) return dir_.strip()
bigcode/self-oss-instruct-sc2-concepts
from random import shuffle def randomize_ietimes(times, ids = []): """ Randomize the times of the point events of all the ids that are given. This randomization keeps the starting time of each individual and reshuffles its own interevent times. Parameters ---------- times : dictionary of lists The dictionary contains for each element their times of events in a list ids : list of ids If not given, the reshuffling is global, if some ids are given, only those will be used for the reshuffling. Returns ------- times_random : dictionary of lists For each element a list of reshuffled event times """ times_random = dict() if len(ids) == 0: ids = times.keys() for idn in ids: Nevents = len(times[idn]) ietlist = [times[idn][i+1]-times[idn][i] for i in range(Nevents-1)] shuffle(ietlist) t0 = times[idn][0] times_random[idn] = [t0] for i in range(Nevents-1): t0 += ietlist[i] times_random[idn].append(t0) return times_random
bigcode/self-oss-instruct-sc2-concepts
def write_csv_string(data): """ Takes a data object (created by one of the read_*_string functions). Returns a string in the CSV format. """ data_return = "" row_num = 0 #Building the string to return #print('data',data) for row in data: data_return += ','.join(str(v) for v in data[row_num].values()) data_return += "\n" row_num += 1 return data_return
bigcode/self-oss-instruct-sc2-concepts
def convert_list_to_string(input_list): """ Converts a list to a string with each value separated with a new paragraph Parameters ---------- input_list : list List of values Returns ------- output : str String output with each value in `input_list` recorded """ output = '' for each in input_list: output += """ {each} """.format(**locals()) return output
bigcode/self-oss-instruct-sc2-concepts
import pathlib import hashlib def get_hash(file_path): """Return sha256 hash of file_path.""" text = b"" if (path := pathlib.Path(file_path)).is_file(): text = path.read_bytes() return hashlib.sha256(text).hexdigest()
bigcode/self-oss-instruct-sc2-concepts
def format_3(value): """Round a number to 3 digits after the dot.""" return "{:.3f}".format(value)
bigcode/self-oss-instruct-sc2-concepts
def get_only_first_stacktrace(lines): """Get the first stacktrace because multiple stacktraces would make stacktrace parsing wrong.""" new_lines = [] for line in lines: line = line.rstrip() if line.startswith('+----') and new_lines: break # We don't add the empty lines in the beginning. if new_lines or line: new_lines.append(line) return new_lines
bigcode/self-oss-instruct-sc2-concepts
def bande_est_noire(nv): """ Determine si une bande est noire ou blanche a partir de son numero """ return nv % 2 == 1
bigcode/self-oss-instruct-sc2-concepts
def fmt(obj): """Value formatter replaces numpy types with base python types.""" if isinstance(obj, (str, int, float, complex, tuple, list, dict, set)): out = obj else: # else, assume numpy try: out = obj.item() # try to get value except: out = obj.tolist() # except, must be np iterable; get list return(out)
bigcode/self-oss-instruct-sc2-concepts
def get_first_aligned_bp_index(alignment_seq): """ Given an alignment string, return the index of the first aligned, i.e. non-gap position (0-indexed!). Args: alignment_seq (string): String of aligned sequence, consisting of gaps ('-') and non-gap characters, such as "HA-LO" or "----ALO". Returns: Integer, >= 0, indicating the first non-gap character within alignment_seq. """ index_of_first_aligned_bp = [i for i,bp in enumerate(alignment_seq) if bp != '-'][0] return index_of_first_aligned_bp
bigcode/self-oss-instruct-sc2-concepts
def risingfactorial(n, m): """ Return the rising factorial; n to the m rising, i.e. n(n+1)..(n+m-1). For example: >>> risingfactorial(7, 3) 504 """ r = 1 for i in range(n, n+m): r *= i return r
bigcode/self-oss-instruct-sc2-concepts
def get_adoc_title(title: str, level: int) -> str: """Returns a string to generate a ascidoc title with the given title, and level""" return " ".join(["="*level, title, '\n'])
bigcode/self-oss-instruct-sc2-concepts
def _normalize_typos(typos, replacement_rules): """ Applies all character replacement rules to the typos and returns a new dictionary of typos of all non-empty elements from normalized 'typos'. """ if len(replacement_rules) > 0: typos_new = dict() for key, values in typos.items(): typos_new[key] = list() for item in values: for orig, replacement in replacement_rules: item = item.replace(orig, replacement) item = item.strip() if item: typos_new[key].append(item) return typos_new else: return typos
bigcode/self-oss-instruct-sc2-concepts
import csv def create_idf_dict() -> dict: """Returns the idf_dict from tstar_idf.txt""" with open("climate_keywords/tstar_idf.txt", "r", encoding='utf-8', errors='ignore') as f: reader = csv.reader(f) idf_dict = {} for term, idf in reader: idf_dict[term] = float(idf) return idf_dict
bigcode/self-oss-instruct-sc2-concepts
import re def sanitize_json_string(string): """ Cleans up extraneous whitespace from the provided string so it may be written to a JSON file. Extraneous whitespace include any before or after the provided string, as well as between words. Parameters ---------- string : str The string to sanitize. Returns ------- string : str The provided string, sanitized of extraneous whitespace. """ # Clean up whitespace (including line breaks) both between words and # at the ends of the string return re.sub(r"\s+", " ", string, flags=re.UNICODE).strip()
bigcode/self-oss-instruct-sc2-concepts
def dict_slice(dict_input, start, end) -> dict: """ take slice for python dict :param dict_input: a dict for slicing :param start: start position for splicing :param end: end position for slicing :return: the sliced dict """ keys = dict_input.keys() dict_slice = {} for k in keys[start:end]: dict_slice[k] = dict_input[k] return dict_slice
bigcode/self-oss-instruct-sc2-concepts
def extract_barcode(read, plen): """ Extract barcode from Seq and Phred quality. :param read: A SeqIO object. :type read: object :param plen: The length of the barcode. :type plen: num :returns: A SeqIO object with barcode removed and a barcode string. """ barcode = str(read.seq[:plen]) read_b = read[plen:] return read_b, barcode
bigcode/self-oss-instruct-sc2-concepts
def getGroupInputDataLength(hg): """ Return the length of a HDF5 group Parameters ---------- hg : `h5py.Group` or `h5py.File` The input data group Returns ------- length : `int` The length of the data Notes ----- For a multi-D array this return the length of the first axis and not the total size of the array. Normally that is what you want to be iterating over. The group is meant to represent a table, hence all child datasets should be the same length """ firstkey = list(hg.keys())[0] nrows = len(hg[firstkey]) firstname = hg[firstkey].name for value in hg.values(): if len(value) != nrows: raise ValueError(f"Group does not represent a table. Length ({len(value)}) of column {value.name} not not match length ({nrows}) of first column {firstname}") return nrows
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict import re def get_current_zones(filename: str) -> Dict[str, str]: """Get dictionary of current zones and patterns""" res = {} try: for line in open(filename).readlines(): if line.startswith("#"): continue if match := re.match(r"^add (\S+) (\w+)$", line.rstrip()): res[match.group(1).lower()] = match.group(2) except FileNotFoundError: pass return res
bigcode/self-oss-instruct-sc2-concepts
def std_ver_minor_uninst_valueerr_iativer(request): """Return a string that looks like it could be a valid IATIver minor version number, but is not.""" return request.param
bigcode/self-oss-instruct-sc2-concepts
def sec_url(period): """ Create url link to SEC Financial Statement Data Set """ url = "".join([ "https://www.sec.gov/files/dera/data/financial-statement-data-sets/", period, ".zip" ]) # handle weird path exception of SEC if period == "2020q1": url = "".join([ "https://www.sec.gov/files/node/add/data_distribution/", period, ".zip" ]) return url
bigcode/self-oss-instruct-sc2-concepts
def compute_sub(guard_str): """ Given a guard, return its sub-guards """ parens = [] sub = [] for i in range(len(guard_str)): if guard_str[i] == '(': parens.append(i) if guard_str[i] == ')': j = parens.pop() g = guard_str[j:i + 1].strip() if g.startswith('(+') or g.startswith('(-') or g.startswith('(*'): continue sub.append(g) return sub
bigcode/self-oss-instruct-sc2-concepts
def clean_string(s): """ Get a string into a canonical form - no whitespace at either end, no newlines, no double-spaces. """ return s.strip().replace("\n", " ").replace(" ", " ")
bigcode/self-oss-instruct-sc2-concepts
import math def precision_digits(f, width): """Return number of digits after decimal point to print f in width chars. Examples -------- >>> precision_digits(-0.12345678, 5) 2 >>> precision_digits(1.23456789, 5) 3 >>> precision_digits(12.3456789, 5) 2 >>> precision_digits(12345.6789, 5) 1 """ precision = math.log(abs(f), 10) if precision < 0: precision = 0 precision = width - int(math.floor(precision)) precision -= 3 if f < 0 else 2 # sign and decimal point if precision < 1: precision = 1 return precision
bigcode/self-oss-instruct-sc2-concepts
def sorted_nodes_by_name(nodes): """Sorts a list of Nodes by their name.""" return sorted(nodes, key=lambda node: node.name)
bigcode/self-oss-instruct-sc2-concepts
def ai(vp,rho): """ Computes de acoustic impedance Parameters ---------- vp : array P-velocity. rho : array Density. Returns ------- ai : array Acoustic impedance. """ ai = vp*rho return (ai)
bigcode/self-oss-instruct-sc2-concepts
def get_bool(bytearray_: bytearray, byte_index: int, bool_index: int) -> bool: """Get the boolean value from location in bytearray Args: bytearray_: buffer data. byte_index: byte index to read from. bool_index: bit index to read from. Returns: True if the bit is 1, else 0. Examples: >>> buffer = bytearray([0b00000001]) # Only one byte length >>> get_bool(buffer, 0, 0) # The bit 0 starts at the right. True """ index_value = 1 << bool_index byte_value = bytearray_[byte_index] current_value = byte_value & index_value return current_value == index_value
bigcode/self-oss-instruct-sc2-concepts
from typing import Callable def evaluate(population: list, evaluation_fn: Callable) -> list: """Evaluates the given population using the given evaluation function. Params: - population (list<str>): The population of chromosomes to evaluate - evaluation_fn (Callable): The evaluation function to use Returns: - evaluated_population (list<tuple<str, Any>>): The evaluated chromosomes with their scores """ evaluated_population = [(chromosome, evaluation_fn(chromosome)) for chromosome in population] return evaluated_population
bigcode/self-oss-instruct-sc2-concepts
import copy def merge_to_panoptic(detection_dicts, sem_seg_dicts): """ Create dataset dicts for panoptic segmentation, by merging two dicts using "file_name" field to match their entries. Args: detection_dicts (list[dict]): lists of dicts for object detection or instance segmentation. sem_seg_dicts (list[dict]): lists of dicts for semantic segmentation. Returns: list[dict] (one per input image): Each dict contains all (key, value) pairs from dicts in both detection_dicts and sem_seg_dicts that correspond to the same image. The function assumes that the same key in different dicts has the same value. """ results = [] sem_seg_file_to_entry = {x["file_name"]: x for x in sem_seg_dicts} assert len(sem_seg_file_to_entry) > 0 for det_dict in detection_dicts: dic = copy.copy(det_dict) dic.update(sem_seg_file_to_entry[dic["file_name"]]) results.append(dic) return results
bigcode/self-oss-instruct-sc2-concepts
def intersection_pt(L1, L2): """Returns intersection point coordinates given two lines. """ D = L1[0] * L2[1] - L1[1] * L2[0] Dx = L1[2] * L2[1] - L1[1] * L2[2] Dy = L1[0] * L2[2] - L1[2] * L2[0] if D != 0: x = Dx / D y = Dy / D return x, y else: return False
bigcode/self-oss-instruct-sc2-concepts
def has_cli_method(script_path): """ Check if a script has a cli() method in order to add it to the main :param script_path: to a python script inside Cider packages :return: Boolean """ file_obj = open(script_path, 'r').read() return "cli()" in file_obj
bigcode/self-oss-instruct-sc2-concepts
def lobid_qs(row, q_field='surname', add_fields=[], base_url="https://lobid.org/gnd/search?q="): """ creates a lobid query string from the passed in fields""" search_url = base_url+row[q_field]+"&filter=type:Person" if add_fields: filters = [] for x in add_fields: if x: filters.append(row[x]) search_url = "{} AND {}".format(search_url, "AND ".join(filters)) return search_url
bigcode/self-oss-instruct-sc2-concepts
def jaccard(ground, found): """Cardinality of set intersection / cardinality of set union.""" ground = set(ground) return len(ground.intersection(found))/float(len(ground.union(found)))
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict import logging def collect_content_packs_to_install(id_set: Dict, integration_ids: set, playbook_names: set, script_names: set) -> set: """Iterates all content entities in the ID set and extract the pack names for the modified ones. Args: id_set (Dict): Structure which holds all content entities to extract pack names from. integration_ids (set): Set of integration IDs to get pack names for. playbook_names (set): Set of playbook names to get pack names for. script_names (set): Set of script names to get pack names for. Returns: set. Pack names to install. """ packs_to_install = set() id_set_integrations = id_set.get('integrations', []) for integration in id_set_integrations: integration_id = list(integration.keys())[0] integration_object = integration[integration_id] if integration_id in integration_ids: integration_pack = integration_object.get('pack') if integration_pack: logging.info( f'Found integration {integration_id} in pack {integration_pack} - adding to packs to install') packs_to_install.add(integration_object.get('pack')) else: logging.warning(f'Found integration {integration_id} without pack - not adding to packs to install') id_set_playbooks = id_set.get('playbooks', []) for playbook in id_set_playbooks: playbook_object = list(playbook.values())[0] playbook_name = playbook_object.get('name') if playbook_name in playbook_names: playbook_pack = playbook_object.get('pack') if playbook_pack: logging.info(f'Found playbook {playbook_name} in pack {playbook_pack} - adding to packs to install') packs_to_install.add(playbook_pack) else: logging.warning(f'Found playbook {playbook_name} without pack - not adding to packs to install') id_set_script = id_set.get('scripts', []) for script in id_set_script: script_id = list(script.keys())[0] script_object = script[script_id] if script_id in script_names: script_pack = script_object.get('pack') if script_pack: logging.info(f'Found script {script_id} in pack {script_pack} - adding to packs to install') packs_to_install.add(script_object.get('pack')) else: logging.warning(f'Found script {script_id} without pack - not adding to packs to install') return packs_to_install
bigcode/self-oss-instruct-sc2-concepts
def maximum_severity(*alarms): """ Get the alarm with maximum severity (or first if items have equal severity) Args: *alarms (Tuple[AlarmSeverity, AlarmStatus]): alarms to choose from Returns: (Optional[Tuple[AlarmSeverity, AlarmStatus]]) alarm with maximum severity; none for no arguments """ maximum_severity_alarm = None for alarm in alarms: if maximum_severity_alarm is None or alarm[0] > maximum_severity_alarm[0]: maximum_severity_alarm = alarm return maximum_severity_alarm
bigcode/self-oss-instruct-sc2-concepts
def extractRoi(frame, pos, dia): """ Extracts a region of interest with size dia x dia in the provided frame, at the specied position Input: frame: Numpy array containing the frame pos: 2D position of center of ROI dia: Integer used as width and height of the ROI Output: patch: Numpy array containing hte extracted ROI """ h,w = frame.shape[:2] xMin = max(int(pos[0]-dia/2)+1, 0) xMax = min(xMin + dia, w) yMin = max(int(pos[1]-dia/2)+1, 0) yMax = min(yMin + dia, h) patch = frame[yMin:yMax, xMin:xMax] return patch
bigcode/self-oss-instruct-sc2-concepts
import secrets import click def generate_secret_key(num_bytes, show=True): """Generate and print a random string of SIZE bytes.""" rnd = secrets.token_urlsafe(num_bytes) if show: click.secho(rnd) return rnd
bigcode/self-oss-instruct-sc2-concepts
def npy_cdouble_from_double_complex(var): """Cast a Cython double complex to a NumPy cdouble.""" res = "_complexstuff.npy_cdouble_from_double_complex({})".format(var) return res
bigcode/self-oss-instruct-sc2-concepts
def find_highest_degree(graph): """ Find the highest degree in a graph """ degrees = graph.degree() max_degree = 0 for node in degrees: if degrees[node] > max_degree: max_degree = degrees[node] return max_degree
bigcode/self-oss-instruct-sc2-concepts
from typing import Callable import functools from typing import Any import warnings def deprecated(func: Callable) -> Callable: """Decorator that can be used to mark functions as deprecated, emitting a warning when the function is used. Arguments: func: The function to be decorated. Returns: The decorated function, which emits a warning when used. """ @functools.wraps(func) def wrapper(*args, **kwargs) -> Any: """Wrapped function to be returned by the decorator. Returns: The original function evaluation. """ warnings.simplefilter("always", DeprecationWarning) # turn off filter warnings.warn( "Deprecated function {} invoked".format(func.__name__), category=DeprecationWarning, stacklevel=2, ) warnings.simplefilter("default", DeprecationWarning) # reset filter return func(*args, **kwargs) return wrapper
bigcode/self-oss-instruct-sc2-concepts
def printtable(table, moe=False): """Pretty print information on a Census table (such as produced by `censustable`). Args: table (OrderedDict): Table information from censustable. moe (bool, optional): Display margins of error. Returns: None. Examples:: censusdata.printtable(censusdata.censustable('acs5', 2015, 'B19013')) """ print(u'{0:12} | {1:30.30} | {2:56} | {3:5}'.format('Variable', 'Table', 'Label', 'Type')) print(u'-'*115) for k in table.keys(): if not moe and k[-1] == 'M': continue # don't clutter output with margins of error label = table[k]['label'] label = '!! '*label.count('!!') + label.replace('!!', ' ') print(u'{0:12} | {1:30.30} | {2:56.56} | {3:5}'.format(k, table[k]['concept'], label, table[k]['predicateType'])) print(u'-'*115) return None
bigcode/self-oss-instruct-sc2-concepts
def _juniper_vrf_default_mapping(vrf_name: str) -> str: """ This function will convert Juniper global/default/master routing instance => master => default :param vrf_name: :return str: "default" if vrf_name = "master" else vrf_name """ if vrf_name == "master": return "default" else: return vrf_name
bigcode/self-oss-instruct-sc2-concepts
def nz(df, y=0): """ Replaces NaN values with zeros (or given value) in a series. Same as the nz() function of Pinescript """ return df.fillna(y)
bigcode/self-oss-instruct-sc2-concepts
def placemark_name(lst): """Formats the placemark name to include its state if incomplete.""" if lst[1] == 'Complete': return lst[0] else: return ': '.join(lst)
bigcode/self-oss-instruct-sc2-concepts
def calc_suffix(_str, n): """ Return an n charaters suffix of the argument string of the form '...suffix'. """ if len(_str) <= n: return _str return '...' + _str[-(n - 3):]
bigcode/self-oss-instruct-sc2-concepts
from typing import List def datum_is_sum(datum: int, preamble: List[int]) -> bool: """Iterate the preamble numbers and determine whether datum is a sum. Args: datum (int): a number that should be a sum of any two numbers in preamble preamble (List[int]): a list of preceeding n numbers where n is preamble_size in check_data_for_invalid() Returns: bool: True if the datum is a sum; False otherwise """ for pre in preamble: diff = datum - pre # The difference must not be the same as the addend that produced it if diff == pre: continue elif diff in preamble: return True return False
bigcode/self-oss-instruct-sc2-concepts
def filter_data(data, var_val_pairs): """ We use this to filter the data more easily than using pandas subsetting Args: data (df) is a dataframe var_val pairs (dict) is a dictionary where the keys are variables and the value are values """ d = data.copy() for k, v in var_val_pairs.items(): d = d.loc[d[k] == v] return d.reset_index(drop=True)
bigcode/self-oss-instruct-sc2-concepts
def getFirstMatching(values, matches): """ Return the first element in :py:obj:`values` that is also in :py:obj:`matches`. Return None if values is None, empty or no element in values is also in matches. :type values: collections.abc.Iterable :param values: list of items to look through, can be None :type matches: collections.abc.Container :param matches: list of items to check against """ assert matches is not None if not values: return None return next((i for i in values if i in matches), None)
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple from typing import List def compute_padding(kernel_size: Tuple[int, int]) -> List[int]: """Computes padding tuple.""" # 4 ints: (padding_left, padding_right,padding_top,padding_bottom) # https://pytorch.org/docs/stable/nn.html#torch.nn.functional.pad assert len(kernel_size) == 2, kernel_size computed = [(k - 1) // 2 for k in kernel_size] return [computed[1], computed[1], computed[0], computed[0]]
bigcode/self-oss-instruct-sc2-concepts
def _calculate_temperature(c, h): """ Compute the temperature give a speed of sound ``c`` and humidity ``h`` """ return (c - 331.4 - 0.0124 * h) / 0.6
bigcode/self-oss-instruct-sc2-concepts
def get_region(df, region): """ Extract a single region from regional dataset. """ return df[df.denominazione_regione == region]
bigcode/self-oss-instruct-sc2-concepts
def get_installed_tool_shed_repository( trans, id ): """Get a tool shed repository record from the Galaxy database defined by the id.""" return trans.sa_session.query( trans.model.ToolShedRepository ).get( trans.security.decode_id( id ) )
bigcode/self-oss-instruct-sc2-concepts