seed
stringlengths
1
14k
source
stringclasses
2 values
import random def duplicate(row, n=5): """ Duplicates (augments) the row by modifying the sale price :param row: pandas series :param n: how many duplicates to return :return: duplicates in list """ price = row['sales.price'] lower, higher = price * 0.9, price * 1.1 dupe_list = [] ...
bigcode/self-oss-instruct-sc2-concepts
def get_gtf_chromosomes(gtf_fn): """Return a set of chromosomes in gtf""" chrs = set() with open(gtf_fn, 'r') as reader: for line in reader: if line.startswith('#') or len(line.strip()) == 0: continue else: chrs.add(line.split('\t')[0]) ret...
bigcode/self-oss-instruct-sc2-concepts
def _adjmatType(adjMat): """(helper function) retruns <class 'int'> if the adjacency matrix is a (0,1)-matrix, and returns <class 'list'> if the adjacency matrix contains edge weights, and returns None if neither of the cases occurs. Args: adjMat (2D - nested - list): the adjacency matrix. ...
bigcode/self-oss-instruct-sc2-concepts
def get_user_article_choice() -> int: """ Get user's choice on which article they want to view. :precondition: User's input must be an integer :postcondition: Successfully return user's input as an integer :return: User's choice of article number as an integer """ # Loop until there is val...
bigcode/self-oss-instruct-sc2-concepts
from typing import List from typing import Optional import bisect def get_bucket(seq_len: int, buckets: List[int]) -> Optional[int]: """ Given sequence length and a list of buckets, return corresponding bucket. :param seq_len: Sequence length. :param buckets: List of buckets. :return: Chosen buck...
bigcode/self-oss-instruct-sc2-concepts
def Quantity(number, singular, plural=None): """A quantity, with the correctly-pluralized form of a word. E.g., '3 hours', or '1 minute'. Args: number: The number used to decide whether to pluralize. (Basically: we will, unless it's 1.) singular: The singular form of the term....
bigcode/self-oss-instruct-sc2-concepts
from typing import List def smart_join(elements: List[str], sep: str) -> str: """ Uses regular join after filtering null elements from the initial list Parameters ---------- elements : List[str] list of /possibly null/ strings to join sep : str joining delimiter Returns ...
bigcode/self-oss-instruct-sc2-concepts
def obscure_string(input_string): """ Obscures the input string by replacing all but the last 4 characters in the string with the character '*'. Useful for obscuring, security credentials, credit card numbers etc. Args: input_string A string of characters Returns: A new string where all but the l...
bigcode/self-oss-instruct-sc2-concepts
def WignerHsize(mp_max, ell_max=-2): """Total size of array of wedges of width mp_max up to ell_max Parameters ---------- ell_max : int mp_max : int, optional If None, it is assumed to be at least ell See Also -------- WignerHrange : Array of (ℓ, m', m) indices corresponding to...
bigcode/self-oss-instruct-sc2-concepts
def convert_spreadsheet_to_unix(val): """ This function converts a date from an Excel spreadsheet (which is an integer) into the number of seconds since the Unix epoch (which is also an integer). """ # Return answer .. return 86400 * (val - 25569)
bigcode/self-oss-instruct-sc2-concepts
def compute_distribution_bounds(history, parameter, alpha, run): """Returns distribution bounds from pyabc posterior distribution. Parameters ---------- history : pyabc.smc An object created by :func:`pyabc.abc.run()` or :func:`respyabc.respyabc()`. parameter : str Paramete...
bigcode/self-oss-instruct-sc2-concepts
def balanced_eq(x, z, y): """Gradient of the max operator with tie breaking. Args: x: The left value z: The maximum of x and y y: The right value Returns: The gradient of the left value i.e. 1 if it is the maximum, 0.5 if they are equal and 0 if it was not the maximum. """ return (x == z...
bigcode/self-oss-instruct-sc2-concepts
def unwrap(url): """Transform a string like '<URL:scheme://host/path>' into 'scheme://host/path'. The string is returned unchanged if it's not a wrapped URL. """ url = str(url).strip() if url[:1] == '<' and url[-1:] == '>': url = url[1:-1].strip() if url[:4] == 'URL:': url = url...
bigcode/self-oss-instruct-sc2-concepts
def repr_dict(dict_obj): """Human readable repr for a dictonary object. Turns a dict into a newline delimited string. Intended use is for loading up sample specifications into the starting buffer of an editor :param dict_obj: type dict dictionary to format""" res = '' for k, v in dict_obj.iteritems...
bigcode/self-oss-instruct-sc2-concepts
from bs4 import BeautifulSoup import requests def fetch(session, url): """ Fetch a URL and parse it with Beautiful Soup for scraping. """ return BeautifulSoup(requests.get(url, stream=False).text, "html.parser")
bigcode/self-oss-instruct-sc2-concepts
import torch def get_simple_trajopt_cost(x_dim, u_dim, alpha_dim, dtype): """ Returns a set of tensors that represent the a simple cost for a trajectory optimization problem. This is useful to write tests for example @return Q, R, Z, q, r, z, Qt, Rt, Zt, qt, rt, zt where min ∑(.5 xᵀ[n] Q ...
bigcode/self-oss-instruct-sc2-concepts
def _range_representer(representer, node: range): """Represents a Python range object using the ``!range`` YAML tag. Args: representer (ruamel.yaml.representer): The representer module node (range): The node, i.e. a range instance Returns: a yaml sequence that is able to recreate a...
bigcode/self-oss-instruct-sc2-concepts
import pathlib import tempfile import zipfile def extract_archvie(archive_path: pathlib.Path) -> pathlib.Path: """ Extract a user data archive to a temporary directory. If the user supplied a path to an already unzipped archive, this is a no-op and will return the same path. Otherwise, the archive is...
bigcode/self-oss-instruct-sc2-concepts
def return_characters(data: bytes) -> bytes: """ Characters that are used for telegram control are replaced with others so that it is easier to parse the message over the wire. Final character is never replaced. This function returns them to their original form. '\x1b\x0e' -> '\x0d' '\x1b\x...
bigcode/self-oss-instruct-sc2-concepts
def calculate_separate_operator_conditionals(expression: str) -> int: """Return the evaluation of the given infix arithmetic expression Note: integer division should truncate toward zero. Args: expression: A valid infix arithmetic expression containing only digits and operators in '+', '-'...
bigcode/self-oss-instruct-sc2-concepts
def get_final_ranks(rank_probs): """Orders final rank probabilities into a list and trims decimal places. """ ranks = [] for team, prob_dict in sorted(rank_probs.items(), key=lambda x: -sum([i*p for i,p in enumerate(x[1].values())])): ranks.append({"team": team, "prob...
bigcode/self-oss-instruct-sc2-concepts
def _sort_by_fitness(parameters, fitness): """Given a parameters and fitness array, returns the same arrays but sorted in ascending order of the fitness. Args: fitness (numpy array): As a numpy array, the values for the fitness. parameters (numpy array): As a numpy array, the values for the...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path import yaml def load_game_reource(game_tag: str, filename: str) -> dict: """Return specific game resource from `{filename}.yml` file.""" path = Path(f"incarn/resources/games/{game_tag}/{filename}.yml").read_text("utf8") return yaml.load(path, Loader=yaml.FullLoader)
bigcode/self-oss-instruct-sc2-concepts
def _index_story(stories, title): """Returns index of title in story list returns -1 if not found Arguments: stories [Story] -- List of stories (Story) title str -- Story title to look for in list """ for i, story in enumerate(stories): if story == title: ret...
bigcode/self-oss-instruct-sc2-concepts
import math def principal_value(angle_in_radians: float) -> float: """ Ensures the angle is within [-pi, pi). :param angle_in_radians: Angle in radians. :return: Scaled angle in radians. """ interval_min = -math.pi two_pi = 2 * math.pi scaled_angle = (angle_in_radians - interval_min) ...
bigcode/self-oss-instruct-sc2-concepts
def desc_sort_list(list, key): """desc sort list of dicts for a given key.""" return sorted(list, key=lambda kev: kev[key], reverse=True)
bigcode/self-oss-instruct-sc2-concepts
import torch def to_onehot(target: torch.Tensor, num_classes: int) -> torch.Tensor: """ Convert given target tensor to onehot format :param target: `LongTensor` of `BxCx(optional dimensions)` :param num_classes: number of classes :return: """ size = list(target.size()) size.insert(1, num...
bigcode/self-oss-instruct-sc2-concepts
import torch def dihedral( x0: torch.Tensor, x1: torch.Tensor, x2: torch.Tensor, x3: torch.Tensor ) -> torch.Tensor: """Dihedral between four points. Reference --------- Closely follows implementation in Yutong Zhao's timemachine: https://github.com/proteneer/timemachine/blob/1a0ab45e605d...
bigcode/self-oss-instruct-sc2-concepts
def conv2d(obj, filt): """ 2-D spatial convolution of an `Image` or `ImageCollection`. Parameters ---------- obj: `Image` or `ImageCollection` Object to convolve over filt: `Kernel` object Kernel object to convolve Example ------- >>> from descarteslabs.workflows im...
bigcode/self-oss-instruct-sc2-concepts
from typing import Callable from typing import Any def to_string_gen(gen) -> Callable[[Any], str]: """ Accepts a string or a function that returns a string and returns a function that returns a string :param gen: either the string to be returned or a generator that accepts an element and returns a string...
bigcode/self-oss-instruct-sc2-concepts
def switchAndTranslate(gm1, gm2, v1, v2, wrapModulo): """ Transforms [v1,v2] and returns it such that it is in the same order and has the same middle interval as [gm1, gm2] """ assert(v1 < v2) # keep the same middle of the interval if (wrapModulo): gmMiddle = float(gm1 + gm2) / 2...
bigcode/self-oss-instruct-sc2-concepts
def form_intro(pol_areas, description=None): """ Form the introduction line Parameters ---------- pol_areas: list of all the policy areas included in the reform used to create a description of the reform description: user provided description of the reform """ # these are all of...
bigcode/self-oss-instruct-sc2-concepts
import struct def get_vbmeta_size(vbmeta_bytes): """Returns the total size of a AvbVBMeta image.""" # Keep in sync with |AvbVBMetaImageHeader|. AVB_MAGIC = b'AVB0' # pylint: disable=C0103 AVB_VBMETA_IMAGE_HEADER_SIZE = 256 # pylint: disable=C0103 FORMAT_STRING = ( ...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def get_current_month_name(month=None): """ get the current month name. if month is given then get the name of that month otherwise get this month name """ current_date = datetime.now() if month is not None: current_date = datetime(current_date.ye...
bigcode/self-oss-instruct-sc2-concepts
def _compute_delta_t( data: dict, nodeid: str, event1: str, event1_pos: int, event2: str, event2_pos: int) -> float: """Compute time delta between two events :param dict data: data :param str nodeid: node id :param str event1: event1 :param int event1_pos: event1 position in stream ...
bigcode/self-oss-instruct-sc2-concepts
def interpolate(a0, a1, w): """ Interpolate between the two points, with weight 0<w<1 """ # return (a1 - a0) * w + a0 # Can make this smoother later return (a1 - a0) * ((w * (w * 6.0 - 15.0) + 10.0) * w * w * w) + a0
bigcode/self-oss-instruct-sc2-concepts
def time2str(time): """ returns utc time as hh:mm string """ minute = '0'+str(time.minute) if time.minute < 10 else str(time.minute) return str(time.hour)+':'+minute
bigcode/self-oss-instruct-sc2-concepts
import torch def argmin(x): """Deterministic argmin. Different from torch.argmin, which may have undetermined result if the are multiple elements equal to the min, this argmin is guaranteed to return the index of the first element equal to the min in each row. Args: x (Tensor): only supp...
bigcode/self-oss-instruct-sc2-concepts
import json def buildJson(self, fields, values): """ Builds json :param fields: fields for json :param values: values for fields in json :return: json """ i = 0 data = {} for field in fields: data[field] = values[i] i += 1 json_data = json.dumps(data) retur...
bigcode/self-oss-instruct-sc2-concepts
def restore_field_information_state(func): """ A decorator that takes a function with the API of (self, grid, field) and ensures that after the function is called, the field_parameters will be returned to normal. """ def save_state(self, grid, field=None, *args, **kwargs): old_params = g...
bigcode/self-oss-instruct-sc2-concepts
def get_list_subsets(object_list, subset_size): """ Breaks a larger list apart into a list of smaller subsets. :param object_list: The initial list to be broken up :param subset_size: The maximum size of the smaller subsets :return: A list of subsets whose size are equal to subset_size. The last sub...
bigcode/self-oss-instruct-sc2-concepts
import math def keypoint_rot90(keypoint, factor, rows, cols, **params): """Rotates a keypoint by 90 degrees CCW (see np.rot90) Args: keypoint (tuple): A keypoint `(x, y, angle, scale)`. factor (int): Number of CCW rotations. Must be in range [0;3] See np.rot90. rows (int): Image heigh...
bigcode/self-oss-instruct-sc2-concepts
def class_to_fqn(cls): """Returns the fully qualified name for cls""" return '%s.%s' % (cls.__module__, cls.__name__)
bigcode/self-oss-instruct-sc2-concepts
def seqcomp(s1, s2): """ Compares 2 sequences and returns a value with how many differents elements they have. """ p = len(s1) for x,y in zip(s1, s2): # Walk through 2 sequences. if x==y: p -= 1 return p
bigcode/self-oss-instruct-sc2-concepts
import torch def abs2(x: torch.Tensor): """Return the squared absolute value of a tensor in complex form.""" return x[..., -1] ** 2 + x[..., -2] ** 2
bigcode/self-oss-instruct-sc2-concepts
def get_features(words, word_features): """ Given a string with a word_features as universe, it will return their respective features : param words: String to generate the features to : param word_features: Universe of words : return: Dictionary with the features for document string """ ...
bigcode/self-oss-instruct-sc2-concepts
def clip_box(box, shape): """ Clip box for given image shape. Args: box (array_like[int]): Box for clipping in the next format: [y_min, x_min, y_max, x_max]. shape (tuple[int]): Shape of image. Returns: array_like[int]: Clipped box. """ ymin, xmin, ymax, xm...
bigcode/self-oss-instruct-sc2-concepts
def get_embedding_dict(filename): """ Read given embedding text file (e.g. Glove...), then output an embedding dictionary. Input: - filename: full path of text file in string format Return: - embedding_dict: dictionary contains embedding vectors (values) for all words (keys) """ ...
bigcode/self-oss-instruct-sc2-concepts
def week_cal(cal: str, current_day: int) -> str: """Function used to transform a HTML month calendar into a week calendar. Args: `cal`(str): the html calendar to transform. `current_day`(int): the current day to select the current week. Returns: `str`: the calendar transformed. ...
bigcode/self-oss-instruct-sc2-concepts
def check_unique_scores(score_list): """Method that checks if the scores presented are unique. Returns true if only unique, false if there are duplicates""" return len(score_list) == len(set(score_list))
bigcode/self-oss-instruct-sc2-concepts
def ReadFile(filename): """Returns the contents of a file.""" file = open(filename, 'r') result = file.read() file.close() return result
bigcode/self-oss-instruct-sc2-concepts
def _subsample(name, indices, doc=""): """Create an alias property for slices of mesh data.""" def get(self): return self.vectors[indices] def set(self, value): self.vectors[indices] = value get.__name__ = name return property(get, set, None, doc)
bigcode/self-oss-instruct-sc2-concepts
import requests import json def CoinNames(n=None): """Gets ID's of all coins on cmc""" names = [] response = requests.get("https://api.coinmarketcap.com/v1/ticker/?limit=0") respJSON = json.loads(response.text) for i in respJSON[:n]: names.append(i['id']) return names
bigcode/self-oss-instruct-sc2-concepts
def dot(a, b): """The dot product between vectors a and b.""" c = sum(a[i] * b[i] for i in range(len(a))) return c
bigcode/self-oss-instruct-sc2-concepts
import pickle def read_Docs(path): """ This function will return a list which includes documents as string format. Parameters: path: path for the pickle file we will provide. """ with open(path,'rb') as P: Docs = pickle.load(P) return Docs
bigcode/self-oss-instruct-sc2-concepts
def molar_concentration_water_vapour(relative_humidity, saturation_pressure, pressure): """ Molar concentration of water vapour :math:`h`. :param relative_humidity: Relative humidity :math:`h_r` :param saturation_pressure: Saturation pressure :math:`p_{sat}` :param pressure: Ambient pressure :m...
bigcode/self-oss-instruct-sc2-concepts
def mean(values): """ Compute the mean of a sequence of numbers. """ return sum(values)/len(values)
bigcode/self-oss-instruct-sc2-concepts
def build_dir_list(project_dir, year_list, product_list): """Create a list of full directory paths for downloaded MODIS files.""" dir_list = [] for product in product_list: for year in year_list: dir_list.append("{}\{}\{}".format(project_dir, product, year)) return dir_list
bigcode/self-oss-instruct-sc2-concepts
def str_to_bool(s): """ Convert multiple string sequence possibilities to a simple bool There are many strings that represent True or False connotation. For example: Yes, yes, y, Y all imply a True statement. This function compares the input string against a set of known strings to see if it ...
bigcode/self-oss-instruct-sc2-concepts
import six def optionalArgumentDecorator(baseDecorator): """ This decorator can be applied to other decorators, allowing the target decorator to be used either with or without arguments. The target decorator is expected to take at least 1 argument: the function to be wrapped. If additional argume...
bigcode/self-oss-instruct-sc2-concepts
def unit_can_reach(unit, location): """ Return whether a unit can reach a location. Arguments: unit: the unit location: the location Returns: whether the unit can reach the location """ x, y = location return unit.partition[y][x]
bigcode/self-oss-instruct-sc2-concepts
def smallest_square(n: int): """ returns the smallest int square that correspond to a integer example: smallest_square(65) returs 8 (8*8 = 64) """ n = abs(n) i = 0 while i**2 <= n: i += 1 if n - (i-1)**2 < i**2 - n: return i - 1 else: return i
bigcode/self-oss-instruct-sc2-concepts
from typing import List def split_lines(*streams: bytes) -> List[str]: """Returns a single list of string lines from the byte streams in args.""" return [ s for stream in streams for s in stream.decode('utf8').splitlines() ]
bigcode/self-oss-instruct-sc2-concepts
def get_pred_text(eval_dict, example_ids, pred_starts, pred_ends, probs, use_official_ids=False): """Get text of predicted answers for a number of predicted starts, ends, and the corresponding example_ids. If use_official_ids is True, the returned dictionary maps from official UUIDs to predicted (answer text, p...
bigcode/self-oss-instruct-sc2-concepts
import math def time_since(s): """compute time Args: s (float): the amount of time in seconds. Returns: (str) : formatting time. """ m = math.floor(s / 60) s -= m * 60 h = math.floor(m / 60) m -= h * 60 return '%dh %dm %ds' % (h, m, s)
bigcode/self-oss-instruct-sc2-concepts
def _get_euclidean_dist(e1, e2): """Calculate the euclidean distance between e1 and e2.""" e1 = e1.flatten() e2 = e2.flatten() return sum([(el1 - el2) ** 2 for el1, el2 in zip(e1, e2)]) ** 0.5
bigcode/self-oss-instruct-sc2-concepts
def is_block_structure_complete_for_assignments(block_data, block_key): """ Considers a block complete only if all scored & graded leaf blocks are complete. This is different from the normal `complete` flag because children of the block that are informative (like readings or videos) do not count. We on...
bigcode/self-oss-instruct-sc2-concepts
import torch def log_density(x: torch.Tensor) -> torch.Tensor: """Computes the density of points for a set of points Args: x (torch.Tensor): set of points (N x D) Returns: torch.Tensor: density in # points per unit of volume in the set """ hypercube_min, _ = torch.min(x, dim=0) ...
bigcode/self-oss-instruct-sc2-concepts
def unit_step(t): """ Takes time as argument and returns a unit-step function """ return 1*(t>=0)
bigcode/self-oss-instruct-sc2-concepts
def substitute(arg, value, replacement=None, else_=None): """ Substitute (replace) one or more values in a value expression Parameters ---------- value : expr-like or dict replacement : expr-like, optional If an expression is passed to value, this must be passed else_ : expr, optional...
bigcode/self-oss-instruct-sc2-concepts
def delete_elem(s, elem): """delete a item in set""" r = set(s) r.remove(elem) return r
bigcode/self-oss-instruct-sc2-concepts
def readMDL(filename): """ Read the MDL file in ASCII and return the data. """ filehandle = open(filename,'r') data = filehandle.read() filehandle.close() return data
bigcode/self-oss-instruct-sc2-concepts
def check_previewUrls(search_results): """ Checks if a result provides a previewUrl for thumbnails. Otherwise a placeholder will be set. This function is needed to avoid too much logic in template rendering. Args: search_results: Contains all search results Returns: search_results ...
bigcode/self-oss-instruct-sc2-concepts
import re def starts_with_auth(s): """Checks is string s starts with standard name type Args: s (str): WhatsApp message string Returns: bool: True if matches regex for name, False if not """ patterns = [ r'([\w]+):', # 1st Name r'([\w]+[\s]+...
bigcode/self-oss-instruct-sc2-concepts
import socket def is_port_open(host, port): """ determine whether `host` has the `port` open """ # creates a new socket s = socket.socket() try: # tries to connect to host using that port s.connect((host, port)) # make timeout if you want it a little faster ( less accur...
bigcode/self-oss-instruct-sc2-concepts
def format_num_3(num): """ Format the number to 3 decimal places. :param num: The number to format. :return: The number formatted to 3 decimal places. """ return float("{:.3f}".format(num))
bigcode/self-oss-instruct-sc2-concepts
import secrets import string def generate_secret_key() -> str: """Securely generate random 50 ASCII letters and digits.""" return "".join(secrets.choice(string.ascii_letters + string.digits) for _ in range(50))
bigcode/self-oss-instruct-sc2-concepts
import re def camelcase(value): """ Convert a module name or string with underscores and periods to camel case. :param value: the string to convert :type value: str :returns: the value converted to camel case. """ return ''.join(x.capitalize() if x else '_' for x in re....
bigcode/self-oss-instruct-sc2-concepts
import math def _compute_effect_size(slice_metric: float, slice_std_dev: float, base_metric: float, base_std_dev: float): """Computes effect size.""" metric_diff = abs(slice_metric - base_metric) slice_var = slice_std_dev * slice_std_dev base_var = base_std_dev * base_std_dev return...
bigcode/self-oss-instruct-sc2-concepts
def hex2dec(s): """return the integer value of a hexadecimal string s""" return int(s, 16)
bigcode/self-oss-instruct-sc2-concepts
def isNumber(string): """ check if a string can be converted to a number """ try: number = float(string) return True except: return False
bigcode/self-oss-instruct-sc2-concepts
def uniqueValues(aDict): """ Write a Python function that returns a list of keys in aDict that map to integer values that are unique (i.e. values appear exactly once in aDict). The list of keys you return should be sorted in increasing order. (If aDict does not contain any unique values, you should ...
bigcode/self-oss-instruct-sc2-concepts
import string import random def generate_random_string(size=6, chars=string.printable): """ generates a random printable string of the given size using the given characters :param size: length of the string to be generated :param chars: set of characters to be used :return: a random string """...
bigcode/self-oss-instruct-sc2-concepts
def subset_df(df, nrows=None, ncols=None, row_seed=0, col_seed=0): """Randomly subset a dataframe, preserving row and column order.""" if nrows is None: nrows = len(df) if ncols is None: ncols = len(df.columns) return (df .sample(n=nrows, random_state=row_seed, axis='rows') ...
bigcode/self-oss-instruct-sc2-concepts
def get_bucket(timestamp, resolution): """ Normalize the timestamp to the given resolution. """ return resolution * (int(timestamp) // resolution)
bigcode/self-oss-instruct-sc2-concepts
def get_data(features, labels_aud, labels_foc, files, indices): """Return features, labels and files at given indices """ features = [features[idx] for idx in indices] labels_aud = [labels_aud[idx] for idx in indices] labels_foc = [labels_foc[idx] for idx in indices] files = [files[idx] for idx in i...
bigcode/self-oss-instruct-sc2-concepts
def model_app_name(value): """ Return the app verbose name of an object """ return value._meta.app_config.verbose_name
bigcode/self-oss-instruct-sc2-concepts
import yaml def pretty(d): """Pretty object as YAML.""" return yaml.safe_dump(d, default_flow_style=False)
bigcode/self-oss-instruct-sc2-concepts
def locale_dict_fetch_with_fallbacks(data_dict, locale): """ Take a dictionary with various locales as keys and translations as values and a locale, and try to find a value that matches with good fallbacks. """ # try returning the locale as-is if data_dict.has_key(locale): return dat...
bigcode/self-oss-instruct-sc2-concepts
import math def _ceil_partial(value, grid_spacing): """Ceil to next point on a grid with a given grid_spacing.""" return math.ceil(value / grid_spacing) * grid_spacing
bigcode/self-oss-instruct-sc2-concepts
import copy def swap_variables(self, r, s, in_place = False): """ Switch the variables `x_r` and `x_s` in the quadratic form (replacing the original form if the in_place flag is True). INPUT: `r`, `s` -- integers >= 0 OUTPUT: a QuadraticForm (by default, otherwise none) EX...
bigcode/self-oss-instruct-sc2-concepts
def totuples(data): """ Convert python container tree to key/value tuples. """ def crawl(obj, path): try: for key, value in sorted(obj.items()): yield from crawl(value, path + (key,)) except AttributeError: if not isinstance(obj, str) and hasattr(obj, '__...
bigcode/self-oss-instruct-sc2-concepts
def create_navigator_apt_entry(nav_info, appointment_timestamp): """ This function takes a dictionary popluated with navigator information and an appointment timestamp and creates an dictionary containing appointment information corresponding to the information given. :param nav_info: :param appoin...
bigcode/self-oss-instruct-sc2-concepts
import re def clean(sentence): """ Clean up a sentence. Remove non alpha number letters. Lower cased. >>> clean('all done.') 'all done' >>> clean('ALL DONE.') 'all done' >>> clean('here we go:') 'here we go' :param sentence: :return: """ return re.sub('[^A-Za-z0-9]', ...
bigcode/self-oss-instruct-sc2-concepts
import struct def bytes_to_integer(bytes_): """Convert bytes to integer""" integer, = struct.unpack("!I", bytes_) return integer
bigcode/self-oss-instruct-sc2-concepts
def to_rpc_byte_order(internal_byte_order): """ Returns a given internal byte order hash (bytes) to the format expected by the RPC client. """ return internal_byte_order[::-1]
bigcode/self-oss-instruct-sc2-concepts
import secrets def token_url() -> str: """Return random and URL safe token.""" return secrets.token_urlsafe()
bigcode/self-oss-instruct-sc2-concepts
import sympy def antal_l_coefficient(index, game_matrix): """ Returns the L_index coefficient, according to Antal et al. (2009), as given by equation 1. L_k = \frac{1}{n} \sum_{i=1}^{n} (a_{kk}+a_{ki}-a_{ik}-a_{ii}) Parameters ---------- index: int game_matrix: sympy.Matrix Return...
bigcode/self-oss-instruct-sc2-concepts
import requests def copy_job(job_id, key): """Helper function to create a Figure 8 job based on existing job. Args: job_id: ID number of job to copy instructions and settings from when creating new job key: API key to access Figure 8 account Returns: int: ID number of job created...
bigcode/self-oss-instruct-sc2-concepts
def most_common_bit_for_position(numbers: list[str], position: int) -> int: """calculates the most common bit for a given position (if equal, returns 1)""" sum_for_position = 0 for number in numbers: sum_for_position += int(number[position]) return int(sum_for_position >= len(numbers) / 2)
bigcode/self-oss-instruct-sc2-concepts