seed
stringlengths
1
14k
source
stringclasses
2 values
def _read_nlines(filename, nlines): """ Read at most nlines lines from file filename. If nlines is < 0, the entire file is read. """ if nlines < 0: with open(filename) as fh: return fh.readlines() lines = [] with open(filename) as fh: for lineno, line in enumerat...
bigcode/self-oss-instruct-sc2-concepts
def human_time(seconds): """Returns a human-friendly representation of the number of seconds.""" assert seconds >= 0 hours = seconds / (60 * 60) minutes = (seconds / 60) % 60 seconds = seconds % 60 return '%02d:%02d:%02d' % (hours, minutes, seconds)
bigcode/self-oss-instruct-sc2-concepts
def max_strand(dataset): """Returns the largest strand number in the supplied dataset""" return max(z.strand for z in dataset.zones())
bigcode/self-oss-instruct-sc2-concepts
def overlap(a, b): """ Checks to see if two casings intersect, or have identical start/end positions. """ # If the casing start/end intersects intersect = (a[0] > b[0] and a[0] < b[1]) or (a[1] > b[0] and a[1] < b[1]) # If the casings start or end in the same place overlap = (a[0] == b[0]) o...
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple import math def rot( x: float, y: float, deg: float, origin: Tuple[float, float] = (0, 0) ) -> Tuple[float, float]: """ Rotate a point by `deg` around the `origin`. This does floating-point math, so you may encounter precision errors. """ theta = deg * math.pi / 180 ...
bigcode/self-oss-instruct-sc2-concepts
import json def load_train_config(filename): """Load a configuration file.""" with open(filename, 'r') as f: config = json.load(f) return config
bigcode/self-oss-instruct-sc2-concepts
def get_function_signature(func): """ Get the function signature as a mapping of attributes. :param func: The function object to interrogate. :return: A mapping of the components of a function signature. The signature is constructed as a mapping: * 'name': The function's defined n...
bigcode/self-oss-instruct-sc2-concepts
def run_plugin_action(path, block=False): """Create an action that can be run with xbmc.executebuiltin in order to run a Kodi plugin specified by path. If block is True (default=False), the execution of code will block until the called plugin has finished running.""" return f'RunPlugin({path}, {block})'
bigcode/self-oss-instruct-sc2-concepts
def setup(df, params): """Calculate data series required for the backtest. Takes as input a dataframe with columns `['date', 'price_l', 'price_r']` and returns a dataframe with columns `['date', 'price_l', 'price_r', 'return_l', 'price_change_l', 'std_l', 'std_pcg_l', 'return_r', 'price_change_r',...
bigcode/self-oss-instruct-sc2-concepts
import math import torch def construct_scale_pyramid(image, scale_factor=0.75, N=4, method='bicubic'): """ Constructs the scale pyramid :param image: normed image tensor with shape (N, C, H, W) :param scale_factor: float that indicates scale factor :param N: int that indicates the number of neede...
bigcode/self-oss-instruct-sc2-concepts
async def help_1(message, name): """Provides a description of a specific command.""" name = name.lower() return message.chat.commands.help(name)
bigcode/self-oss-instruct-sc2-concepts
def read_file(filename): """ Read input file and save the crabs into a list. :param filename: input file :return: list of crabs """ crabs = [] with open(filename, 'r', encoding='UTF-8') as file: for line in file: for number in line.split(","): crabs.append...
bigcode/self-oss-instruct-sc2-concepts
def lat_fixed_formatter(y): """Simple minded latitude formatter. Only because those available in cartopy do not leave a blank space after the degree symbol so it looks crammed. If used outside this module, bear in mind this was thought to be used as part of an iterator to later be included in a ...
bigcode/self-oss-instruct-sc2-concepts
def calcWaterFractionByVolume(waterVolume, glycerolVolume): """ Calculates the volume fraction of water in a water - glycerol mixture Args: waterVolume (float): volume of water in l glycerolVolume (float): volume of glycerol in l Returns: :class:`float` Fraction of water by vol...
bigcode/self-oss-instruct-sc2-concepts
def sorted_by_attr(vals, attr, reverse=False): """Sort sequence <vals> by using attribute/key <attr> for each item in the sequence.""" return sorted(vals, key=lambda x: x[attr], reverse=reverse)
bigcode/self-oss-instruct-sc2-concepts
def level_dataset(lv): """Get dataset key part for level. Parameters ---------- lv : `int` Level. Returns ------- `str` Dataset key part. """ return '_lv%d' % lv
bigcode/self-oss-instruct-sc2-concepts
def predict(upstream, model): """Make a prediction after computing features """ return model.predict(upstream['join'])
bigcode/self-oss-instruct-sc2-concepts
def user_input() -> int: """Displays a menu of the available actions and asks user's input :return sel: integer representing user's choice""" print("") print("=" * 50) print("1 - Collect images for calibration") print("2 - Perform calibration") print("3 - Disparity map tuning on sample imag...
bigcode/self-oss-instruct-sc2-concepts
def time_worked(clocked_in, clocked_out): """Return hours and minutes worked. Args: clocked_in: str, military time clocked_out: str, military time Returns: ( hours: int, count of hours, mins: int, count of minutes ): tuple """ section_time = la...
bigcode/self-oss-instruct-sc2-concepts
def get_next_active_day(days, current_day, active_days): """Gets the next active day, often this will simply be the next day, i.e. if you set the active days as Mon - Fri and today is Mon, then the next active day is Tue. However is today is Fri then the next active day will be Mon. If say our active days ...
bigcode/self-oss-instruct-sc2-concepts
def end_chat(input_list): """ End chat Parameters ---------- input_list : list List containing 'quit' to end chat. Returns ------- True or False : boolean Boolean assures whether to end chat based on whether the input contains 'quit'. """ if 'quit' in in...
bigcode/self-oss-instruct-sc2-concepts
from typing import Mapping from typing import Any from typing import Dict def logs_as_floats(logs: Mapping[str, Any]) -> Dict[str, float]: """Convert Keras metric log values to floats.""" return {name: float(value) for name, value in logs.items()}
bigcode/self-oss-instruct-sc2-concepts
def _keys_to_byte(keys: list, default=b'\x00') -> bytes: """Return a byte in which the bits X are 1 for each X in the list keys.""" return bytes([sum(map(lambda b: 1 << b, keys))]) if keys else default
bigcode/self-oss-instruct-sc2-concepts
def byte_pad(data: bytes, block_size: int) -> bytes: """ Pad data with 0x00 until its length is a multiple of block_size. Add a whole block of 0 if data lenght is already a multiple of block_size. """ padding = bytes(block_size - (len(data) % block_size)) return data + padding
bigcode/self-oss-instruct-sc2-concepts
def _has_no_variables(sess): """Determines if the graph has any variables. Args: sess: TensorFlow Session. Returns: Bool. """ for op in sess.graph.get_operations(): if op.type.startswith("Variable") or op.type.endswith("VariableOp"): return False return True
bigcode/self-oss-instruct-sc2-concepts
def d_opt(param,value,extra_q=0): """ Create string "-D param=value" """ sym_q="" if extra_q==1: sym_q="\"" return("-D "+param+"="+sym_q+value+sym_q+" ")
bigcode/self-oss-instruct-sc2-concepts
def merge_vals(current, update): """Update the current container with updated values. Supports dictionary, list and basic types, as well as nesting. :param current: the container to update :param update: the container to update with :return: updated container """ if current is None: # val...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def get_271_member_not_found(demographics: Dict) -> str: """ Returns an Eligibility/271 response where a member is not found. :param demographics: Demographic fields included within the x12 response. :return: x12 transaction """ x12 = f"""ISA*00* *00* ...
bigcode/self-oss-instruct-sc2-concepts
def linspace(start, end, num=50): """ Return equally spaced array from "start" to "end" with "num" vals. """ return [start+i*((end-start)/float(num-1)) for i in range(num)]
bigcode/self-oss-instruct-sc2-concepts
def panel_to_multiindex(panel, filter_observations=False): """Convert a panel to a MultiIndex DataFrame with the minor_axis of the panel as the columns and the items and major_axis as the MultiIndex (levels 0 and 1, respectively). Parameters ---------- panel : a pandas Panel filter_observa...
bigcode/self-oss-instruct-sc2-concepts
def get_steps_kwarg_parsers(cls, method_name): """ Analyze a method to extract the parameters with command line parsers. The parser must be a :class:`Param` so it handles parsing of arguments coming from the command line. It must be specified in the ``options`` class attribute. :param method_n...
bigcode/self-oss-instruct-sc2-concepts
def set_buffer(library, session, mask, size): """Sets the size for the formatted I/O and/or low-level I/O communication buffer(s). Corresponds to viSetBuf function of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier to a session. :para...
bigcode/self-oss-instruct-sc2-concepts
def safe_getattr(obj, attr_name): """Get the attribute of an object returning None if the attribute does not exist. :param obj: An object :type obj: mixed :param attr_name: The name of the attribute :type attr_name: str or unicode """ try: return getattr(obj, attr_name) exce...
bigcode/self-oss-instruct-sc2-concepts
def GetHotkey(text): """Return the position and character of the hotkey""" # find the last & character that is not followed # by & or by the end of the string curEnd = len(text) + 1 text = text.replace("&&", "__") while True: pos = text.rfind("&", 0, curEnd) # One found was at ...
bigcode/self-oss-instruct-sc2-concepts
import time def timetrace(message, idstring, tracemessage="TEST_MESSAGE", final=False): """ Trace a message with time stamps. Args: message (str): The actual message coming through idstring (str): An identifier string specifying where this trace is happening. tracemessage (str): T...
bigcode/self-oss-instruct-sc2-concepts
import re def insert_spaces(text: str) -> str: """Insert space in Chinese characters. >>> insert_spaces("test亨利it四世上") ' test 亨 利 it 四 世 上 ' >>> insert_spaces("test亨利it四世上").strip().__len__() 17 """ return re.sub(r"(?<=[a-zA-Z\d]) (?=[a-zA-Z\d])", "", text.replace("", " "))
bigcode/self-oss-instruct-sc2-concepts
def clean_data(record): """Cleans data to get single ',' separated byte messages.""" record = ','.join(record.split()) return record.encode('utf-8')
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional def get_image_provision_timestamp(log_path: str) -> Optional[str]: """ Examines the Travis build log file at `log_path` to determine when the image used by the build was provisioned. :param log_path: The path to the Travis build log. This should be an original build log. :r...
bigcode/self-oss-instruct-sc2-concepts
def _retain_from_list(x, exclude): """Returns the features to retain. Used in conjunction with H2OTransformer classes that identify features that should be dropped. Parameters ---------- x : iterable of lists The list from which to exclude exclude : array_like The columns ...
bigcode/self-oss-instruct-sc2-concepts
import torch def normalized_cross_correlation(x, y, return_map, reduction="mean", eps=1e-8): """ N-dimensional normalized cross correlation (NCC) Args: x (~torch.Tensor): Input tensor. y (~torch.Tensor): Input tensor. return_map (bool): If True, also return the correlation map. ...
bigcode/self-oss-instruct-sc2-concepts
import pytz def datetime_to_string(dttm): """Given a datetime instance, produce the string representation with microsecond precision""" # 1. Convert to timezone-aware # 2. Convert to UTC # 3. Format in ISO format with microsecond precision if dttm.tzinfo is None or dttm.tzinfo.utcoffset(dttm)...
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterable def rgb_hexify(rgb: Iterable[int]) -> str: """Convert a list of RGB numbers to a hex format. """ return ''.join( list(map( lambda x: hex(abs(x))[2:].zfill(2), rgb ))[::-1] )
bigcode/self-oss-instruct-sc2-concepts
def _create_fold_path_component(edge_direction, edge_name): """Return a tuple representing a fold_path component of a FoldScopeLocation.""" return ((edge_direction, edge_name),)
bigcode/self-oss-instruct-sc2-concepts
def read_header_and_channels(filename, chtrig): """ Reads a txt file with a header and channels and separates them Parameters ---------- filename: str path to the txt Labchart file chtrig : int index of trigger channel Returns ------- header: list header lin...
bigcode/self-oss-instruct-sc2-concepts
def quads_to_triangles(mesh): """ Convert Quad faces to Triangular ones. Inputs: mesh - an OBJ object loaded from load_obj() Outputs: Modifies the mesh.f and returns mesh. """ newFaces = [] for i, face in enumerate(mesh.f): if(len(face) != 3): assert len(f...
bigcode/self-oss-instruct-sc2-concepts
def stat_lookup(perf_dict, counter_name): """ Performance the lookup of the supplied counter name against the dictionary and returns a counter Id :param perf_dict: The array containing the performance dictionary (with counters and IDs) :param counter_name: The counter name in the correct format for the...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from typing import Optional def _get_event_url( cz_event_id : Union[str,int] ,cz_draw_id : Optional[Union[str,int]] = None )->str: """Returns the cz event page url.""" if cz_draw_id is None: return 'https://curlingzone.com/event.php?view=Scores&eventid=%s#1'%cz_event...
bigcode/self-oss-instruct-sc2-concepts
def to_list(x): """Converts input to a list if necessary.""" if isinstance(x, (list, tuple)): return x else: return [x]
bigcode/self-oss-instruct-sc2-concepts
def add_header(response): """Add CORS and Cache-Control headers to the response.""" if not response.cache_control: response.cache_control.max_age = 30 response.headers['Access-Control-Allow-Origin'] = '*' response.headers['Access-Control-Allow-Methods'] = 'GET' return response
bigcode/self-oss-instruct-sc2-concepts
def ascent_set(t): """ Return the ascent set of a standard tableau ``t`` (encoded as a sorted list). The *ascent set* of a standard tableau `t` is defined as the set of all entries `i` of `t` such that the number `i+1` either appears to the right of `i` or appears in a row above `i` or does...
bigcode/self-oss-instruct-sc2-concepts
def empty_string_to_none(string): """Given a string, return None if string == "", and the string value (with type str) otherwise """ if string == '': return None else: return str(string)
bigcode/self-oss-instruct-sc2-concepts
def get_total_tiles(min_zoom: int, max_zoom: int) -> int: """Returns the total number of tiles that will be generated from an image. Args: min_zoom (int): The minimum zoom level te image will be tiled at max_zoom (int): The maximum zoom level te image will be tiled at Returns: The t...
bigcode/self-oss-instruct-sc2-concepts
def _strip_outliers(w, max_value=1e4, n_devs=5): """Removes work values that are more than 5 (n_devs) standard deviations from the mean or larger than 1E4 (max_value). Parameters ---------- w : list(float) List of works max_value : int, default=1E4 Work values larger than this will ...
bigcode/self-oss-instruct-sc2-concepts
def add_train_args(parser): """Add training-related arguments. Args: * parser: argument parser Returns: * parser: argument parser with training-related arguments inserted """ train_arg = parser.add_argument_group('Train') train_arg.add_argument('--n_batch', ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from typing import List import json def parse_issues_json_string(issues_json: Union[str, bytes]) -> List[str]: """ Parses a JSON string containing GitHub issues into a list of issue titles. Note: The issue data must contain the `title` field. :param issue_json: Issue data en...
bigcode/self-oss-instruct-sc2-concepts
def female_filter(variable): """ Simple function to know the gender by name ending. If name ends with 'a' - it is female's name. """ return variable[-1].lower() == 'a'
bigcode/self-oss-instruct-sc2-concepts
import json def read_config_file(config_filename): """Reads configuration parameters from the specified JSON file.""" # Strip comments while keeping line numbers. config_str = "" with open(config_filename, "r") as f_in: for line in f_in: line = line.rstrip() comment_pos = line.find("//") ...
bigcode/self-oss-instruct-sc2-concepts
def cleanString(s): """ takes in a string s and return a string with no punctuation and no upper-case letters""" s = s.lower() for p in "?.!,'": # looping over punctuation s = s.replace(p,'') # replacing punctuation with space return s
bigcode/self-oss-instruct-sc2-concepts
def title_case(sentence): """ Converts enetered string into the title_case Parameters ----------- sentence : string string to be converted into sentence case Returns ------- title_case_sentence : string string in TITLE CASE Example ------- >>>title_case('Th...
bigcode/self-oss-instruct-sc2-concepts
def makeCd_from_vec(vecCd,nDims,n_neurons): """ convert between vector and matrix forms of C and d""" C = vecCd[:nDims*n_neurons].reshape(nDims,n_neurons).T d = vecCd[nDims*n_neurons:] return C,d
bigcode/self-oss-instruct-sc2-concepts
import hashlib def _validate_file(fpath, md5_hash): """ Validate a file against a MD5 hash. Parameters ---------- fpath: string Path to the file being validated md5_hash: string The MD5 hash being validated against Returns --------- bool True, if the file ...
bigcode/self-oss-instruct-sc2-concepts
def _clamp_window_size(index, data_size, window_size=200): """Return the window of data which should be used to calculate a moving window percentile or average. Clamped to the 0th and (len-1)th indices of the sequence. E.g. _clamp_window_size(50, 1000, 200) == (0, 150) _clamp_window_size(300...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def utc_timestamp_to_datetime(timestamp): """ Converts timestamp (seconds) to UTC datetime :type timestamp: float | int :rtype: datetime """ return datetime.utcfromtimestamp(round(timestamp))
bigcode/self-oss-instruct-sc2-concepts
def usafe_filter(entity): """Returns the URL safe key string given an entity.""" return entity.urlsafe
bigcode/self-oss-instruct-sc2-concepts
import torch from typing import Union def normalise_coords(coords: torch.Tensor, shape: Union[tuple, list]) -> torch.Tensor: """Normalise actual coordinates to [-1, 1] Coordinate locations start "mid-pixel" and end "mid-pixel" (pixel box model): Pixels | 0 | 1 | 2 | | | | ...
bigcode/self-oss-instruct-sc2-concepts
import torch from pathlib import Path from typing import Dict from typing import Any def load_checkpoint(path_to_checkpoint: Path, use_gpu: bool = True) -> Dict[str, Any]: """ Loads a Torch checkpoint from the given file. If use_gpu==False, map all parameters to the GPU, otherwise left the device of all p...
bigcode/self-oss-instruct-sc2-concepts
import warnings import time def warn_and_continue(exn): """Call in an exception handler to ignore any exception, isssue a warning, and continue.""" warnings.warn(repr(exn)) time.sleep(0.5) return True
bigcode/self-oss-instruct-sc2-concepts
def is_leading_low(x, j): """Return True if bit ``j`` is the lowest bit set in ``x``.""" return x & ((1 << (j+1)) - 1) == 1 << j
bigcode/self-oss-instruct-sc2-concepts
import re def colFromRegex(referenceList, regex): """ Return a list created by mapping a regular expression to another list. The regular expression must contain at least one capture group. Parameters ---------- referenceList : list-like A list to derive new values from. regex : str ...
bigcode/self-oss-instruct-sc2-concepts
def returns_minus_base(returns, b, masks): """ Subtract optimal baseline from returns :param returns: returns from each step on or for whole trajectory. Size: batch_size x 1 :param b: Optimal baseline per time step for every trajectory. Size: length_time_horizon :param masks: indicate the final step...
bigcode/self-oss-instruct-sc2-concepts
def delta(a, b): """ Kronecker delta function """ return 1 if a == b else 0
bigcode/self-oss-instruct-sc2-concepts
def policy_rollout(env, agent): """Run one episode.""" observation, reward, done = env.reset(), 0, False obs, acts, rews = [], [], [] while not done: env.render() obs.append(observation) action = agent.act(observation) observation, reward, done, _ = env.step(action) ...
bigcode/self-oss-instruct-sc2-concepts
import ntpath def StripPathToFile( path ): """ Strip a file path down to the last folder/file name. """ head, tail = ntpath.split(path) return tail or ntpath.basename(head)
bigcode/self-oss-instruct-sc2-concepts
from typing import Any def truebool(val: Any | None) -> bool: """Return `True` if the value passed in matches a "True" value, otherwise `False`. "True" values are: 'true', 't', 'yes', 'y', 'on' or '1'. """ return val is not None and str(val).lower() in ("true", "t", "yes", "y", "on", "1")
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Optional def smp_converge(men_engage: Dict[str, Optional[str]], women_engage: Dict[str, Optional[str]]) -> bool: """Return True if there exists a couple that are unengaged.""" return None in men_engage.values() or None in women_engage.values()
bigcode/self-oss-instruct-sc2-concepts
def calculate_clipping(cfg, scale): """ Helper function for calculating lo and hi. Args: -- cfg: configuration file for model -- scale: scale for lo, hi. If lo, hi in [0,255], scale is 1. If lo, hi in [0,1], scale is 1/255 Returns: -- LO, HI: list, lower bound and upper bound of each chann...
bigcode/self-oss-instruct-sc2-concepts
def get_attr(f, name): """ Try to access the path `name` in the file `f` Return the corresponding attribute if it is present """ if name in list(f.attrs.keys()): return(True, f.attrs[name]) else: return(False, None)
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def format_timestamp(time_string): """Return the timestamp as a formatted string.""" return datetime.strptime(time_string, '%Y%m%d%H%M%S').isoformat().replace('T', ' ')
bigcode/self-oss-instruct-sc2-concepts
def get_bbox(img, bbox): """ API expects bbox as [ymin, xmin, ymax, xmax], in relative values, convert to tuple (xmin, ymin, xmax, ymax), in pixel values """ width, height = img.size bbox_px = (0, 0, width, height) if bbox: bbox_px = ( int(bbox[1] * width), int(bb...
bigcode/self-oss-instruct-sc2-concepts
import base64 def base64_from_image(image_path): """ Encodes an image in base64 (> str) """ image = open(image_path, 'rb') image_content = image.read() image.close() return(base64.b64encode(image_content).decode('ascii'))
bigcode/self-oss-instruct-sc2-concepts
def preprocess_proxy(proxy): """fix proxy list to IPAddress,Port format from dictionary to ipaddress,port Parameters ---------------- proxy : dict proxy details form the proxy json file Returns --------------- dict constaining keys ipaddress and port for the proxy """ ...
bigcode/self-oss-instruct-sc2-concepts
import pickle import dill def maybe_dill_loads(o): """Unpickle using cPickle or the Dill pickler as a fallback.""" try: return pickle.loads(o) except Exception: # pylint: disable=broad-except return dill.loads(o)
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def format_bybit_candle_timestamp(timestamp: datetime) -> float: """Format Bybit candles timestamp.""" return int(timestamp.timestamp())
bigcode/self-oss-instruct-sc2-concepts
from typing import Union import math def truncate_to_block(length: Union[int, float], block_size: int) -> int: """ Rounds the given length to the nearest (smaller) multiple of the block size. """ return int(math.floor(length / block_size)) * block_size
bigcode/self-oss-instruct-sc2-concepts
def not_caught_by_spamhaus(log_data): """ Returns a dict like log_data but with IPs that were found in zen.spamhaus.org removed. """ return {ip: lists for ip, lists in log_data.items() if "zen.spamhaus.org" not in lists and len(lists) >= 1}
bigcode/self-oss-instruct-sc2-concepts
def construct_path(u,v,discovered): """Use the discovered dictionary from depth-first search to reconstruct a path from node u to node v. """ path = [] # Deal with empty case if v not in discovered: return path # build list of edges # that connect v to u, # then r...
bigcode/self-oss-instruct-sc2-concepts
import torch def vstack_params(params,new_params): """ Stacks vertically for each key in params, new_params """ assert params.keys() == new_params.keys() res = {k: torch.vstack([params[k], new_params[k]]) for k in params.keys()} return res
bigcode/self-oss-instruct-sc2-concepts
import torch def _cross_squared_distance_matrix(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: """ Pairwise squared distance between two (batch) matrices' rows (2nd dim). Computes the pairwise distances between rows of x and rows of y :param x : 3-D float Tensor :shape: (batc...
bigcode/self-oss-instruct-sc2-concepts
def find_parent_fnames(var): """ Find full names of parents, recursively. These names will be forbidden in the subsequent resolution to make sure there's no back branch in the constructed DAG. """ names = [var.fname] # No self-referential if var.parent: names.append(var.parent.fnam...
bigcode/self-oss-instruct-sc2-concepts
import math def sector(angle, radius, rad=False): """Finds the area of a sector of a circle""" if rad: angle = math.degrees(angle) return (angle / 360) * (math.pi * (radius ** 2))
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterable from functools import reduce def _digits_to_number(digits: Iterable[int]) -> int: """ Gives the number given by its digits, e.g. [1, 2, 3] -> 123 """ return reduce(lambda x, y: x * 10 + y, digits)
bigcode/self-oss-instruct-sc2-concepts
def form_assignment_string_from_dict(adict): """ Generate a parameter-equals-value string from the given dictionary. The generated string has a leading blank. """ result = "" for aparameter in adict.keys(): result += " {}={}".format(aparameter, adict[aparameter]) return resul...
bigcode/self-oss-instruct-sc2-concepts
def tobytes(value): """implicitly try to convert values to byte strings mainly for python 2 and 3 compatibility""" if not isinstance(value, bytes): value = value.encode('utf8') return value
bigcode/self-oss-instruct-sc2-concepts
def iff( a, b, c ): """ Ternary shortcut """ if a: return b else: return c
bigcode/self-oss-instruct-sc2-concepts
def searchkit_aggs(aggs): """Format the aggs configuration to be used in React-SearchKit JS. :param aggs: A dictionary with Invenio facets configuration :returns: A list of dicts for React-SearchKit JS. """ return [ {"title": k.capitalize(), "aggName": k, "field": v["terms"]["field"]} ...
bigcode/self-oss-instruct-sc2-concepts
def pre_process_data(full_file_lines): """ I group all the possible configurations in a dictionary the key is MACHINE + BENCHMARK + LOG HEADER :param full_file_lines: :return: dictionary that contains the grouped benchmarks """ grouped_benchmarks = {} for i in full_file_lines: ...
bigcode/self-oss-instruct-sc2-concepts
def parse_argparser(parser): """Parse the argparser. Parameters ---------- parser : argparse.ArgumentParser Returns ------- dict """ args = parser.parse_args() config = vars(args) return config
bigcode/self-oss-instruct-sc2-concepts
def enthalpyVaporization(T, eVP): """ enthalpyVaporization(T, eVP) enthalpyVaporization (kJ/mol) = A*(1-T/critT)^n Parameters T, temperature in Kelvin eVP, A=eVP[0], critT=eVP[1], n=eVP[2] A and n are regression coefficients, critT: critical temperature Returns ent...
bigcode/self-oss-instruct-sc2-concepts
def metricresample(metric, samples): """ Resample a metric vector using random resamples computed using indexresample. Parameters: - - - - - metric: array of scalar values describing mesh samples: indices to sample from """ resamples = metric[samples] return resamples
bigcode/self-oss-instruct-sc2-concepts
def get_reader_pairs(reader): """Return the set of alphabetically-sorted word (str) tuples in `reader` """ return {tuple(sorted([w1, w2])): score for w1, w2, score in reader()}
bigcode/self-oss-instruct-sc2-concepts