seed
stringlengths
1
14k
source
stringclasses
2 values
import torch def init_control(ctrl_obj, env, live_plot_obj, rec, params_general, random_actions_init, costs_tests, idx_test, num_repeat_actions=1): """ Init the gym env and memory. Define the lists containing the points for visualisations. Control the env with random actions for a number of steps. Args: ct...
bigcode/self-oss-instruct-sc2-concepts
def create_keyword_string(command_string): """Creates the keyword string. The keyword string is everything before the first space character.""" cmd_str = command_string.split(" ")[0] return cmd_str
bigcode/self-oss-instruct-sc2-concepts
def normalize_azimuth(azimuth): """Normalize azimuth to (-180, 180].""" if azimuth <= -180: return azimuth + 360 elif azimuth > 180: return azimuth - 360 else: return azimuth
bigcode/self-oss-instruct-sc2-concepts
def real_calculate_check_digit(gs1_value): """ Calculate the check digit without specifying the identifier key. :param gs1_value: GS1 identifier. :return: Check digit. """ multipliers = [] counter = 0 total = 0 for i in reversed(range(len(gs1_value))): d = gs1_value[i] ...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def make_epoch_seed(epoch_tx_count, ledger_count, sorted_ledger, address_from_ledger): """ epoch_tx_count = number of transactions made in a given epoch ledger_count = the total number of ledger entries in the ledger database. sorted_ledger = iterable that returns the nth ledger item. M...
bigcode/self-oss-instruct-sc2-concepts
def change_list_value(array: list, value_old: str, value_new: str) -> list: """ Returns a given list with a changed value. """ for index, value in enumerate(array): if value == value_old: array[index] = value_new return array
bigcode/self-oss-instruct-sc2-concepts
import json def load_clusters(infile): """ Loads clusters in a sparse format from a JSON file. Parameters ---------- infile : str The JSON file containing sparse cluster information. Returns ------- list of set of tuple of int The sets are clusters, the tuples are the...
bigcode/self-oss-instruct-sc2-concepts
def inclusion_one_default_from_template(one, two='hi'): """Expected inclusion_one_default_from_template __doc__""" return {"result": "inclusion_one_default_from_template - Expected result: %s, %s" % (one, two)}
bigcode/self-oss-instruct-sc2-concepts
def build_metric_link(region, alarm_name): """Generate URL link to the metric Arguments: region {string} -- aws region name alarm_name {string} -- name of the alarm in aws Returns: [type] -- [description] """ url = 'https://{}.console.aws.amazon.com/cloudwatch/home?...
bigcode/self-oss-instruct-sc2-concepts
def vector_multiply(vector_in, scalar): """ Multiplies the vector with a scalar value. This operation is also called *vector scaling*. :param vector_in: vector :type vector_in: list, tuple :param scalar: scalar value :type scalar: int, float :return: updated vector :rtype: tuple ""...
bigcode/self-oss-instruct-sc2-concepts
def load_meta(meta_file): """Load metadata file with rows like `utt_id|unit_sequence`. Args: meta_file: Filepath string for metadata file with utterance IDs and corresponding quantized unit sequences, separated by pipes. Input unit sequences should be separated by spaces. Returns: ...
bigcode/self-oss-instruct-sc2-concepts
def _module_name(*components): """Assemble a fully-qualified module name from its components.""" return '.'.join(components)
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def find_prefix(root, prefix: str) -> Tuple[bool, int]: """ Check and return 1. If the prefix exsists in any of the words we added so far 2. If yes then how may words actually have the prefix """ node = root # If the root node has no children, then return Fals...
bigcode/self-oss-instruct-sc2-concepts
from PIL import ImageFile as PillowImageFile import zlib import struct def get_pillow_attribute(file, pil_attr): """ Returns an attribute from a Pillow image of the given file, file a file. wrappable by Pillow. Must be open pil_attr the attribute to read. return the attrib...
bigcode/self-oss-instruct-sc2-concepts
def find_check_run_by_name(check_runs, name): """ Search through a list of check runs to see if it contains a specific check run based on the name. If the check run is not found this returns 'None'. Parameters ---------- check_runs : list of dict An array of check runs. This can be an ...
bigcode/self-oss-instruct-sc2-concepts
def count_words(item): """Convert the partitioned data for a word to a tuple containing the word and the number of occurances. """ word, occurances = item return word, sum(occurances)
bigcode/self-oss-instruct-sc2-concepts
import torch def randomized_argmax(x: torch.Tensor) -> int: """ Like argmax, but return a random (uniformly) index of the max element This function makes sense only if there are ties for the max element """ if torch.isinf(x).any(): # if some scores are inf, return the index for one of the ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Literal def compatible_operation(*args, language_has_vectors = True): """ Indicates whether an operation requires an index to be correctly understood Parameters ========== args : list of PyccelAstNode The operator arguments language_has_vectors : bo...
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Any def _get_player_pts_stat_type(player_pts: Dict[str, Any]) -> str: """ Helper function to get the stat type within the pulled player points. Will be either 'projectedStats' or 'stats'. """ unique_type = set([list(v.keys())[0] for v in player_pts.values...
bigcode/self-oss-instruct-sc2-concepts
def formatEdgeDestination(node1, node2): """ Gera uma string que representa um arco node1->node2 Recebe dois inteiros (dois vértices do grafo), e o formata com a notação de aresta a->b onde a é o vértice de origem, e b o de destino. Args: node1 (int): número de um dos vértices ligados à ar...
bigcode/self-oss-instruct-sc2-concepts
def make_response(response): """ Make a byte string of the response dictionary """ response_string = response["status"] + "\r\n" keys = [key for key in response if key not in ["status", "content"]] for key in keys: response_string += key + ": " + response[key] + "\r\n" response_strin...
bigcode/self-oss-instruct-sc2-concepts
def repetition_plane(repetitions, n=8): """ :param int repetitions: Number of times a chess position (state) has been reached. :param int n: Chess game dimension (usually 8). :return: An n x n list containing the same value for each entry, the repetitions number. :rtype: list[list[in...
bigcode/self-oss-instruct-sc2-concepts
def line_from_text(content='', some_text=[]): """ returns the first line containing 'content' :param content: :param some_text: list of strings :return: line containing text """ matching_line = '' for line in some_text: if line.find(content) >= 0: matching_line = line...
bigcode/self-oss-instruct-sc2-concepts
import torch def batch_matrix_norm(matrix, norm_order=2): """ normalization of the matrix Args: matrix: torch.Tensor. Expected shape [batch, *] norm_order: int. Order of normalization. Returns: normed matrix: torch.Tensor. """ return torch.norm(matrix, p=norm_order, dim=...
bigcode/self-oss-instruct-sc2-concepts
def _jaccard(a, b): """ Return the Jaccard similarity between two sets a and b. """ return 1. * len(a & b) / len(a | b)
bigcode/self-oss-instruct-sc2-concepts
def compute_grade(questions_coeff, questions_grade): """ Compute a grade from grade for each question (/2) and associated coefficients :param questions_coeff: list of coefficients for each question :param questions_grade: list of grade for each question """ assign_grade = 0 sum_coeff = ...
bigcode/self-oss-instruct-sc2-concepts
def _do_step(x, y, z, tau, kappa, d_x, d_y, d_z, d_tau, d_kappa, alpha): """ An implementation of [1] Equation 8.9 References ---------- .. [1] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point optimizer for linear programming: an implementation of the homog...
bigcode/self-oss-instruct-sc2-concepts
def bgr_to_rgb(color: tuple) -> tuple: """Converts from BGR to RGB Arguments: color {tuple} -- Source color Returns: tuple -- Converted color """ return (color[2], color[1], color[0])
bigcode/self-oss-instruct-sc2-concepts
def get_run_data_from_cmd(line): """Parser input data from a command line that looks like `command: python3 batch_runner.py -t benders -k cache -i s6.xml -v y -r 0` and put it into a dict. """ words = line.split(" ")[3:] word_dict = {} for (i, word) in enumerate(words): if word.sta...
bigcode/self-oss-instruct-sc2-concepts
def slurp(fname: str) -> str: """ Reads a file and all its contents, returns a single string """ with open(fname, 'r') as f: data = f.read() return data
bigcode/self-oss-instruct-sc2-concepts
def create_img(height, width, color): """ Creates an image of the given height/width filled with the given color PARAMS/RETURN height: Height of the image to be created, as an integer width: Width of the image to be created, as an integer color: RGB pixel as a tuple of 3 integers re...
bigcode/self-oss-instruct-sc2-concepts
import zipfile def _NoClassFiles(jar_paths): """Returns True if there are no .class files in the given JARs. Args: jar_paths: list of strings representing JAR file paths. Returns: (bool) True if no .class files are found. """ for jar_path in jar_paths: with zipfile.ZipFile(jar_path) as jar: ...
bigcode/self-oss-instruct-sc2-concepts
import torch def process_sequence_wise(cell, x, h=None): """ Process the entire sequence through an GRUCell. Args: cell (DistillerGRUCell): the cell. x (torch.Tensor): the input h (tuple of torch.Tensor-s): the hidden states of the GRUCell. Returns: y (torch.Tensor)...
bigcode/self-oss-instruct-sc2-concepts
import csv def file_to_position_depths(file_path): """Get the position and depths from one file. Read into memory as a dictionary with (lat, lon) as the key and depth as the value.""" # create the dictionary result = {} # read the position and depth data from the input csv file with open(fil...
bigcode/self-oss-instruct-sc2-concepts
def serialize_email_principal(email): """Serialize email principal to a simple dict.""" return { '_type': 'Email', 'email': email.email, 'id': email.name, 'name': email.name, 'identifier': email.identifier }
bigcode/self-oss-instruct-sc2-concepts
def dates_to_str(dates): """Transforms list of dates into a string representation with the ARRAY keyword heading. Parameters ---------- dates: list Returns ------- dates: str """ heading = 'ARRAY DATE' footing = '/' res = [heading] + [d.strftime('%d %b %Y').upper() for d in...
bigcode/self-oss-instruct-sc2-concepts
def convert_size_in_points_to_size_in_pixels(size): """ 6pt = 8px = 0.5em 7pt = 9px = 0.55em 7.5pt = 10px = 0.625em 8pt = 11px = 0.7em 9pt = 12px = 0.75em 10pt = 13px = 0.8em 10.5pt = 14px = 0.875em 11pt = 15px = 0.95em 12pt = 16px = 1em 13pt = 17px = 1.05em 13.5pt = 18px...
bigcode/self-oss-instruct-sc2-concepts
def scaleto255(value): """Scale the input value from 0-100 to 0-255.""" return max(0, min(255, ((value * 255.0) / 100.0)))
bigcode/self-oss-instruct-sc2-concepts
def receivables_turnover(revenue, average_receivables): """Computes receivables turnover. Parameters ---------- revenue : int or float Revenue average_receivables : int or float Average receivables for the period Returns ------- out : int or float Receivables tu...
bigcode/self-oss-instruct-sc2-concepts
import pathlib def get_files(extensions): """List all files with given extensions in subfolders :param extensions: Array of extensions, e.g. .ttl, .rdf """ all_files = [] for ext in extensions: all_files.extend(pathlib.Path('cloned_repo').rglob(ext)) return all_files
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from typing import List from typing import Tuple def flatten(xs: Union[List, Tuple]) -> List: """ Flatten a nested list or tuple. """ return ( sum(map(flatten, xs), []) if (isinstance(xs, list) or isinstance(xs, tuple)) else [xs] )
bigcode/self-oss-instruct-sc2-concepts
import csv def read_csv(filepath, encoding='utf-8'): """ This function reads in a csv and returns its contents as a list Parameters: filepath (str): A str representing the filepath for the file to be read encoding (str): A str representing the character encoding of the file Returns: ...
bigcode/self-oss-instruct-sc2-concepts
def subtract_year(any_date): """Subtracts one year from any date and returns the result""" date = any_date.split("-") date = str(int(date[0])-1) + "-" + date[1] + "-" + date[2] return date
bigcode/self-oss-instruct-sc2-concepts
import re def remove_whitespace(s, right=False, left=False): """ Remove white-space characters from the given string. If neither right nor left is specified (the default), then all white-space is removed. Parameters ---------- s : str The string to be modified. right : bool ...
bigcode/self-oss-instruct-sc2-concepts
def compact(text, **kw): """ Compact whitespace in a string and format any keyword arguments into the resulting string. Preserves paragraphs. :param text: The text to compact (a string). :param kw: Any keyword arguments to apply using :py:func:`str.format()`. :returns: The compacted, formatted ...
bigcode/self-oss-instruct-sc2-concepts
def parse_ingredients(raw_ingredients): """Parse individual ingredients from ingredients form data.""" ingredients = [] for ingredient in raw_ingredients.split("\r\n"): if ingredient: ingredients.append(ingredient) return ingredients
bigcode/self-oss-instruct-sc2-concepts
def read(metafile): """ Return the contents of the given meta data file assuming UTF-8 encoding. """ with open(str(metafile), encoding="utf-8") as f: return f.read()
bigcode/self-oss-instruct-sc2-concepts
import hashlib def get_ftp_md5(ftp, remote_file): """Compute checksum on remote ftp file.""" m = hashlib.md5() ftp.retrbinary(f'RETR {remote_file}', m.update) return m.hexdigest()
bigcode/self-oss-instruct-sc2-concepts
def usd(value): """ Format value as USD """ return f"${value:,.2f}"
bigcode/self-oss-instruct-sc2-concepts
def get_batch(file_h5, features, batch_number, batch_size=32): """Get a batch of the dataset Args: file_h5(str): path of the dataset features(list(str)): list of names of features present in the dataset that should be returned. batch_number(int): the id of the batch to be re...
bigcode/self-oss-instruct-sc2-concepts
import random def randhex() -> str: """Returns random hex code as string""" return "#" + "".join(random.choices("ABCDEF123456", k=6))
bigcode/self-oss-instruct-sc2-concepts
def split_byte_into_nibbles(value): """Split byte int into 2 nibbles (4 bits).""" first = value >> 4 second = value & 0x0F return first, second
bigcode/self-oss-instruct-sc2-concepts
def _count_spaces_startswith(line): """ Count the number of spaces before the first character """ if line.split("#")[0].strip() == "": return None spaces = 0 for i in line: if i.isspace(): spaces += 1 else: return spaces
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterable def get_proc_name(cmd): """ Get the representative process name from complex command :param str | list[str] cmd: a command to be processed :return str: the basename representative command """ if isinstance(cmd, Iterable) and not isinstance(cmd, str): cmd = ...
bigcode/self-oss-instruct-sc2-concepts
import socket def is_port_open(port_num): """ Detect if a port is open on localhost""" sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) return sock.connect_ex(('127.0.0.1', port_num)) == 0
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from pathlib import Path from typing import Tuple def get_paths(base_path: Union[str, Path]) -> Tuple[Path, Path]: """ Get fsh input and output paths from base path. :param base_path: Base path :return: FSH input path, FSH output path """ return ( Path(base_pa...
bigcode/self-oss-instruct-sc2-concepts
import json def inline_json(obj): """ Format a python object as JSON for inclusion in HTML. Parameters: obj: A python object that can be converted to JSON. Returns: An escaped :term:`native string` of JSON. """ return json.dumps(obj).replace("</script", r"<\/script").replace(...
bigcode/self-oss-instruct-sc2-concepts
def readCols(cols_file): """ Read a .cols file (normally correspondingly to a .dm file) and return two dictionaries: word:index and index:word. In the .cols file, the line number is used as index. :param cols_file: str -- file path to a list of words (words' line numbers are their index) :return: {i...
bigcode/self-oss-instruct-sc2-concepts
def get_invalid_user_credentials(data=None): """ Returns error response for invalid user credentials :param str data: message :return: response :rtype: object """ response = {"status": 401, "message": "Invalid user credentials.", "data": data} return response
bigcode/self-oss-instruct-sc2-concepts
from typing import Mapping def item_iter(obj): """ Return item (key, value) iterator from dict or pair sequence. Empty seqence for None. """ if obj is None: return () if isinstance(obj, Mapping): return obj.items() return obj
bigcode/self-oss-instruct-sc2-concepts
import torch def mean_std_integrand(fx, px): """Compute the expectation value and the standard deviation of a function evaluated on a sample of points taken from a known distribution. Parameters ---------- fx: torch.Tensor batch of function values px: torch.tensor batch of PDF...
bigcode/self-oss-instruct-sc2-concepts
def start_ind(model, dbg=False): """ equation 1 in the paper (called i_0): returns the first index of the w vector used in the random power law graph model """ assert model.gamma > 2 #if gamma=2, this returns 0 num_nodes = model.num_nodes max_deg = model.max_deg avg_deg = model.avg_deg ...
bigcode/self-oss-instruct-sc2-concepts
import base64 import six def serialize(obj): """Serialize the given object :param obj: string representation of the object :return: encoded object (its type is unicode string) """ result = base64.urlsafe_b64encode(obj) # this workaround is needed because in case of python 3 the # urlsafe_b...
bigcode/self-oss-instruct-sc2-concepts
import requests from bs4 import BeautifulSoup def create_soup(url): """ This function takes a url and creates a soup for us to work with""" html = requests.get(url).text soup = BeautifulSoup(html, "html5lib") return soup
bigcode/self-oss-instruct-sc2-concepts
def rad2equiv_evap(energy): """ Converts radiation in MJ m-2 day-1 to the equivalent evaporation in mm day-1 assuming a grass reference crop using FAO equation 20. Energy is converted to equivalent evaporation using a conversion factor equal to the inverse of the latent heat of vapourisation (1 ...
bigcode/self-oss-instruct-sc2-concepts
import json def to_sentiment_json(doc_id, sent, label): """Convert the sentiment info to json. Args: doc_id: Document id sent: Overall Sentiment for the document label: Actual label +1, 0, -1 for the document Returns: String json representation of the input """ j...
bigcode/self-oss-instruct-sc2-concepts
def get_top_matches(matches, top): """Order list of tuples by second value and returns top values. :param list[tuple[str,float]] matches: list of tuples :param int top: top values to return """ sorted_names = sorted(matches, key=lambda x: x[1], reverse=True) return sorted_names[0:top]
bigcode/self-oss-instruct-sc2-concepts
def GetCounterSetting(counter_spec, name): """ Retrieve a particular setting from a counter specification; if that setting is not present, return None. :param counter_spec: A dict of mappings from the name of a setting to its associated value. :param name: The name of the setting of interest. :retur...
bigcode/self-oss-instruct-sc2-concepts
def jaccard_similariy_index(first, second): """ Returns the jaccard similarity between two strings :param first: first string we are comparing :param second: second string we are comparing :return: how similar the two strings are """ # First, split the sentences into words tokenize_firs...
bigcode/self-oss-instruct-sc2-concepts
def scale(score, omax, omin, smax, smin): """ >>> scale(2871, 4871, 0, 1000, 0) 589 """ try: return ((smax - smin) * (score - omin) / (omax - omin)) + smin except ZeroDivisionError: return 0
bigcode/self-oss-instruct-sc2-concepts
def add_prefix_un(word): """ :param word: str of a root word :return: str of root word with un prefix This function takes `word` as a parameter and returns a new word with an 'un' prefix. """ prefix = 'un' return prefix+word
bigcode/self-oss-instruct-sc2-concepts
from typing import List import re def parse_dot_argument(dot_argument: str) -> List[str]: """ Takes a single argument (Dict key) from dot notation and checks if it also contains list indexes. :param dot_argument: Dict key from dot notation possibly containing list indexes :return: Dict key and possibl...
bigcode/self-oss-instruct-sc2-concepts
def apply_building_mapping(mapdict, label): """ Applies a building map YAML to a given label, binning it into the appropriate category. """ for category in mapdict: #print(mapdict, category, label) if label in mapdict[category]['labels']: return category return "house"
bigcode/self-oss-instruct-sc2-concepts
def preprocess_text(raw_text,nlp): """ Preprocesses the raw metaphor by removing sotp words and lemmatizing the words Args: raw_text: (string) the original metaphor text to be processed nlp: (spacy language object) """ tokens=[] for token in nlp(raw_text): if not token.is_...
bigcode/self-oss-instruct-sc2-concepts
def get_major_version(version): """ :param version: the version of edge :return: the major version of edge """ return version.split('.')[0]
bigcode/self-oss-instruct-sc2-concepts
def ordinal(number): """ Get ordinal string representation for input number(s). Parameters ---------- number: Integer or 1D integer ndarray An integer or array of integers. Returns ------- ord: String or List of strings Ordinal representation of input number(s). Return a string if inpu...
bigcode/self-oss-instruct-sc2-concepts
import re def remove_accents(text): """Removes common accent characters.""" text = re.sub(u"[àáâãäå]", 'a', text) text = re.sub(u"[èéêë]", 'e', text) text = re.sub(u"[ìíîï]", 'i', text) text = re.sub(u"[òóôõö]", 'o', text) text = re.sub(u"[ùúûü]", 'u', text) text = re.sub(u"[ýÿ]", 'y', te...
bigcode/self-oss-instruct-sc2-concepts
def cluster_list(list_to_cluster: list, delta: float) -> list: """ Clusters a sorted list :param list_to_cluster: a sorted list :param delta: the value to compare list items to :return: a clustered list of values """ out_list = [[list_to_cluster[0]]] previous_value = list_to_cluster[0] ...
bigcode/self-oss-instruct-sc2-concepts
def external_pressure(rho, g, d): """Return the external pressure [Pa] at water depth. :param float rho: Water density [kg/m^3] :param float g: Acceleration of gravity [m/s/s] :param float d: Water depth [m] """ return rho * g * d
bigcode/self-oss-instruct-sc2-concepts
def sort_words(arguments, words): """ Takes a dict of command line arguments and a list of words to be sorted. Returns a sorted list based on `alphabetical`, `length` and `reverse`. """ if arguments.get('--alphabetical', False): words.sort() elif arguments.get('--length', False): ...
bigcode/self-oss-instruct-sc2-concepts
def source_from_url(link): """ Given a link to a website return the source . """ if 'www' in link: source = link.split('.')[1] else: if '.com' in link: source = link.split('.com')[0] else: source = link.split('.')[0] source = source.replace('https...
bigcode/self-oss-instruct-sc2-concepts
def _check_type(type_, value): """Return true if *value* is an instance of the specified type or if *value* is the specified type. """ return value is type_ or isinstance(value, type_)
bigcode/self-oss-instruct-sc2-concepts
import importlib def get_callback_class(hyperparams): """ Get one or more Callback class specified as a hyper-parameter "callback". e.g. callback: stable_baselines3.common.callbacks.CheckpointCallback for multiple, specify a list: callback: - utils.callbacks.PlotActionWrapper ...
bigcode/self-oss-instruct-sc2-concepts
def area_under_curve(x, y): """Finds the area under unevenly spaced curve y=f(x) using the trapezoid rule. x,y should be arrays of reals with same length. returns: a - float, area under curve""" a = 0.0 for i in range(0, len(x) - 1): # add area of current trapezium to sum ...
bigcode/self-oss-instruct-sc2-concepts
def newman_conway(num): """ Returns a list of the Newman Conway numbers for the given value. Time Complexity: O(n) because the number of calculations performed depends on the size of num. Space Complexity: Space complexity is also O(n) becuase newman_conway_nums array to store sequence valu...
bigcode/self-oss-instruct-sc2-concepts
def _get_position_precedence(position: str) -> int: """Get the precedence of a position abbreviation (e.g. 'GK') useful for ordering.""" PLAYER_POSITION_PRECEDENCE = { "GK": 1, "LB": 2, "LCB": 3, "CB": 4, "RCB": 5, "RB": 6, "LDM": 7, "CDM": 8, ...
bigcode/self-oss-instruct-sc2-concepts
def v1_deep_add(lists): """Return sum of values in given list, iterating deeply.""" total = 0 lists = list(lists) while lists: item = lists.pop() if isinstance(item, list): lists.extend(item) else: total += item return total
bigcode/self-oss-instruct-sc2-concepts
def ngrams(sequence, N): """Return all `N`-grams of the elements in `sequence`""" assert N >= 1 return list(zip(*[sequence[i:] for i in range(N)]))
bigcode/self-oss-instruct-sc2-concepts
def pollutants_per_country(summary): """ Get the available pollutants per country from the summary. :param list[dict] summary: The E1a summary. :return dict[list[dict]]: All available pollutants per country. """ output = dict() for d in summary.copy(): country = d.pop("ct") ...
bigcode/self-oss-instruct-sc2-concepts
import string def read_cstring(view, addr): """Read a C string from address.""" s = "" while True: c = view.read(addr, 1) if c not in string.printable: break if c == "\n": c = "\\n" if c == "\t": c = "\\t" if c == "\v": c = "\\v" if c == "\f": c ...
bigcode/self-oss-instruct-sc2-concepts
def _format_time(time_us): """Defines how to format time in FunctionEvent""" US_IN_SECOND = 1000.0 * 1000.0 US_IN_MS = 1000.0 if time_us >= US_IN_SECOND: return '{:.3f}s'.format(time_us / US_IN_SECOND) if time_us >= US_IN_MS: return '{:.3f}ms'.format(time_us / US_IN_MS) return '{...
bigcode/self-oss-instruct-sc2-concepts
def product_turnover(units_sold_in_period, average_items_stocked_in_period): """Return the product turnover (or sell through rate) for a product based on units sold versus items stocked. Args: units_sold_in_period (int): Number of units of product X sold in the period. average_items_stocked_in_...
bigcode/self-oss-instruct-sc2-concepts
def fib_n_efficient(n): """Efficient way to compute Fibonacci's numbers. Complexity = O(n)""" a = 0 b = 1 for i in range(n - 1): c = a + b a = b b = c print(b) return b
bigcode/self-oss-instruct-sc2-concepts
def _get_single_reg(asm_str): """returns a single register from string and check proper formatting (e.g "r5")""" if len(asm_str.split()) > 1: raise SyntaxError('Unexpected separator in reg reference') if not asm_str.lower().startswith('r'): raise SyntaxError('Missing \'r\' character at start...
bigcode/self-oss-instruct-sc2-concepts
def is_valid_boolean(val): """ Checks if given value is boolean """ values = [True, False] return val in values
bigcode/self-oss-instruct-sc2-concepts
def massage_data(raw_data): """ Preprocess the data for predictions """ raw_data.rename(index=str, columns={"whether he/she donated blood in March 2007": "label"}, inplace=True) # generate features for year for time columns for x, y in zip(['time_years', 'recency_years'], ['Time (months)', 'Recen...
bigcode/self-oss-instruct-sc2-concepts
def remove_multiedges(E): """Returns ``(s, d, w)`` with unique ``(s, d)`` values and `w` minimized. :param E: a set of edges :type E: [(int, int, float)] :return: a subset of edges `E` :rtype: [(int, int, float), ...] """ result = [] exclusion = set() for...
bigcode/self-oss-instruct-sc2-concepts
import six import importlib def load_class(requested_class): """ Check if requested_class is a string, if so attempt to load class from module, otherwise return requested_class as is """ if isinstance(requested_class, six.string_types): module_name, class_name = requested_class.rsplit(".",...
bigcode/self-oss-instruct-sc2-concepts
def calc_tristimulus_array_length(data_array): """ calcurate the array length of tristimulus ndarray. Parameters ---------- data_array : ndarray tristimulus values Returns ------- int length of the tristimulus array. Examples -------- >>> data_1 = np.ones((...
bigcode/self-oss-instruct-sc2-concepts
import json def read_user_ips(file): """Read in the JSON file of the user-IP address mapping.""" with open(file, 'r') as file: return json.loads(file.read())
bigcode/self-oss-instruct-sc2-concepts