seed
stringlengths
1
14k
source
stringclasses
2 values
from datetime import datetime def add_set_time_to_state(state): """Annotate state the time of state creation""" state['setTime'] = datetime.now().timestamp() return state
bigcode/self-oss-instruct-sc2-concepts
import hashlib def generate_hash(content: bytes): """ Create md5 hash from bytes :param content: some data in bytes :type content: bytes :return: hash string :rtype: str """ return hashlib.sha3_512(content).hexdigest()
bigcode/self-oss-instruct-sc2-concepts
def h2r(_hex): """ Convert a hex string to an RGB-tuple. """ if _hex.startswith('#'): l = _hex[1:] else: l = _hex return list(bytes.fromhex(l))
bigcode/self-oss-instruct-sc2-concepts
def namedtuples2dicts(namedtuples): """ Convert a dict of namedtuples to a dict of dicts. :param namedtuples: dict of namedtuples :return: dict of dicts """ return {k: dict(v._asdict()) for k, v in namedtuples.items()}
bigcode/self-oss-instruct-sc2-concepts
import yaml def load_end2end_config(config_file): """ Loads end-to-end test setup file :param config_file: Name of the end-to-end config file. """ with open(config_file) as file: return yaml.full_load(file)
bigcode/self-oss-instruct-sc2-concepts
def get_caption(etype, cell_meta, resources): """return an ipypublish caption or False captions can either be located at cell_meta.ipub.<type>.caption, or at resources.caption[cell_meta.ipub.<type>.label] the resources version is proritised """ try: caption = cell_meta["ipub"][etype]["...
bigcode/self-oss-instruct-sc2-concepts
def hexify(s): """ Used to convert message to hex integers when encrypting. :param s: a string. :return: a string like '0x..', decode each character as a ascii hex number. """ if not s: # if input is null, evcrypt the message: '!' return '0x21' # ascii code for '!' lst = [] fo...
bigcode/self-oss-instruct-sc2-concepts
def IBA_calc(TPR, TNR, alpha=1): """ Calculate IBA (Index of balanced accuracy). :param TNR: specificity or true negative rate :type TNR : float :param TPR: sensitivity, recall, hit rate, or true positive rate :type TPR : float :param alpha : alpha coefficient :type alpha : float :r...
bigcode/self-oss-instruct-sc2-concepts
def get_rect_even_dimensions(rect_item, even_dimensions=True): """ get the the graphics rectangle of the item, moved to position, with sides of even length Args: rect_item (QGraphicsRectItem) even_dimensions (bool): if False even dimensions are not enforced Returns ...
bigcode/self-oss-instruct-sc2-concepts
def dictionary(input_list): """ To generate a dictionary. Index: item in the array. Value: the index of this item. """ return dict(zip(input_list, range(len(input_list))))
bigcode/self-oss-instruct-sc2-concepts
import re from datetime import datetime def buildReportName(appName, reportName): """Constructs report name from app + user supplied report name""" reportName = reportName if reportName else '{}-{}'.format(appName, datetime.now().strftime('%Y-%m-%d-%H:%M:%S')) reportName = re.sub(r'[^\w\-:_\. ]', '_', reportNam...
bigcode/self-oss-instruct-sc2-concepts
def z_score_normalize(tensor, scale_to_range=None): """Performs z-score normalization on a tensor and scales to a range if specified.""" mean = tensor.mean() std = tensor.std() tensor = (tensor - mean) / std if scale_to_range: delta1 = tensor.max() - tensor.min() delta2 = scale_to_...
bigcode/self-oss-instruct-sc2-concepts
def ami_architecture(ami_info): """ Finds source AMI architecture AMI tag. Parameters ---------- ami_info : dict AMI information. Returns ------- string Architecture of source AMI. """ for tag in ami_info['Tags']: if tag['Key'] == 'Architecture': ...
bigcode/self-oss-instruct-sc2-concepts
def unmask_escape(text: str) -> str: """Replaces masking sequences with the original escaped characters. Args: text (str): masked string. Returns: str: unmasked string. """ return text.replace('ҪҪҪҪҪ', '&amp;').replace('ҚҚҚҚ', '&lt;').replace('ҺҺҺҺ', '&gt;')
bigcode/self-oss-instruct-sc2-concepts
def _sq(x): """Square quickly.""" return x * x
bigcode/self-oss-instruct-sc2-concepts
def get_len_of_bedtool(bed_obj, cov_col=3, cutoff=1): """ Get the number of rows (sites) of BedTool object :param bed_obj: :param cutoff: :return: """ # covList = [] # for row in bed_obj: # covList.append(int(row[cov_col])) # covSeries = pd.Series(covList) df = bed_obj.to...
bigcode/self-oss-instruct-sc2-concepts
def rreplace(s, old, new, occurrence): """ Function which replaces a string occurence in a string from the end of the string. """ return new.join(s.rsplit(old, occurrence))
bigcode/self-oss-instruct-sc2-concepts
def generate_description(slug: str) -> str: """ Fungsi yang menerima input berupa string dengan kebab-case dan mengubahnya menjadi string UPPERCASE. Fungsi ini juga akan mengakronim input yang terlalu panjang (lebih dari 30 karakter). Contoh: >>> generate_description("home") 'HOME' ...
bigcode/self-oss-instruct-sc2-concepts
def find_plate_scale(dictionary): """ Find the plate scale determined by Astrometry.net This value is given inside a COMMENT header, hence we have to search for it Will return the plate scale as a float if it exists, None otherwise. """ try: comment_entry = dictionary["COMMENT"] exc...
bigcode/self-oss-instruct-sc2-concepts
def _fix_snpeff_version_line(line, supported_versions): """Change snpEff versions to supported minor releases. ##SnpEffVersion="2.0.3 (build 2011-10-08), by Pablo Cingolani" """ start, rest = line.split('"', 1) version, end = rest.split(" ", 1) version_base = version.rsplit(".", 1)[0] for s...
bigcode/self-oss-instruct-sc2-concepts
def removesuffix(string, suffix): """ Returns <string> without the <suffix> suffix. Copied from https://www.python.org/dev/peps/pep-0616/#specification to support python versions < 3.9 :param str string: string from which to remove suffix :param str suffix: suffix to remove from string :re...
bigcode/self-oss-instruct-sc2-concepts
def get_x(path, width): """Gets the x value from the image filename""" return (float(int(path.split("_")[1])) - width/2) / (width/2)
bigcode/self-oss-instruct-sc2-concepts
def cal_iou(box1, box2): """ :param box1: = [xmin1, ymin1, xmax1, ymax1] :param box2: = [xmin2, ymin2, xmax2, ymax2] :return: """ xmin1, ymin1, xmax1, ymax1 = box1 xmin2, ymin2, xmax2, ymax2 = box2 # 计算每个矩形的面积 s1 = (xmax1 - xmin1) * (ymax1 - ymin1) # C的面积 s2 = (xmax2 - xmin2) * ...
bigcode/self-oss-instruct-sc2-concepts
def _ReadOrder(fo): """Read one example from the order file.""" line = fo.readline() if not line: return None line = line[:-1] order = line.split() order = [int(item) for item in order] return order
bigcode/self-oss-instruct-sc2-concepts
import secrets def bernoulli_neg_exp(gamma, rng=None): """Sample from Bernoulli(exp(-gamma)). Adapted from "The Discrete Gaussian for Differential Privacy", Canonne, Kamath, Steinke, 2020. https://arxiv.org/pdf/2004.00010v2.pdf Parameters ---------- gamma : float Parameter to sample ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional from typing import Tuple def _get_validation_scope( has_valid_abbrev: bool, blacklist_policy: Optional[str], ) -> Tuple[str, str]: """Determine the validationScope for DST and abbreviations. Returns tuple of the C++ ValidationScope and a human-readable comment. """ ...
bigcode/self-oss-instruct-sc2-concepts
def lemmatize(lemma_dict, word): """Lemmatize a word. Lemmatizes a word using a lemmatizer which is represented as a dict that has (word, lemma) as (key, value) pair. An example of a lemma list can be found in https://github.com/michmech/lemmatization-lists. If the word is not found in the diction...
bigcode/self-oss-instruct-sc2-concepts
def get_digits_matching_next(captcha, step_size=1): """Get digits from captcha that are matching next step_size digit.""" matching_digits = [] for index, digit in enumerate(captcha): next_index = (index + step_size) % len(captcha) if digit == captcha[next_index]: matching_digits....
bigcode/self-oss-instruct-sc2-concepts
import torch def accuracy(output, target): """ Compute accuracy comparing the output of the model and the target. Args: output : [batch_size, num_classes, caps_dim] The output from the last caps layer. target : [batch_size] Labels for dataset. Returns: accuracy (float): The...
bigcode/self-oss-instruct-sc2-concepts
def formatField (Field, x, xerr): """ Parameters ---------- Field : The name of the field x : Value of the field xerr : Error in the field Returns ------- Str Field: x +/- xerr """ return str(Field) + " " + str(x) + " +/- " + str(xerr) + "\n"
bigcode/self-oss-instruct-sc2-concepts
def getAttr(argAttrName, argAttrs): """Extract and return the value of a particular attribute from a list of (attributeName, attributeValue) pairs. If the attribute does not exist in the list, return None. """ for attr in argAttrs: if attr[0] == argAttrName: return attr[1] return None
bigcode/self-oss-instruct-sc2-concepts
def get_search_term(request): """Get search term from request. Args: request: Django request object Returns: searchterm: string, search term """ # Get search term searchterm = request.POST.get('search', '') # If no POST data, try GET if not searchterm and request.GET.get('search', ''): s...
bigcode/self-oss-instruct-sc2-concepts
def all_leaf_positions(parented_tree): """Return tree positions of all leaves of a ParentedTree, even if the input is only a subtree of that ParentedTree. """ return parented_tree.root().treepositions('leaves')
bigcode/self-oss-instruct-sc2-concepts
def extract_package(signature): """Extracts the package from a signature. Args: signature (string): JNI signature of a method or field. Returns: The package name of the class containing the field/method. """ full_class_name = signature.split(";->")[0] package_name = full_class_...
bigcode/self-oss-instruct-sc2-concepts
def get_line(s): """get a gui line with given char""" return str(s)*72
bigcode/self-oss-instruct-sc2-concepts
def get_exception_info(exception: BaseException) -> dict: """ Given an Exception object, retrieves some information about it: class and message. :param exception: An exception which inherits from the BaseException class. :return: A dict, containing two values: - class: Th...
bigcode/self-oss-instruct-sc2-concepts
def get_count_proteins(filename): """ Get the number of unique proteins from unique_proteins output. """ with open(filename) as f: line = f.readline() if line.startswith("Found"): count = int(line.split()[1]) else: count = -1 return count
bigcode/self-oss-instruct-sc2-concepts
def fits_header_value(hdu, key): """ Take FITS hdu and a key, return value associated with key (or None if key absent). Adapted from package photrix, class FITS.header_value. :param hdu: astropy fits header+data unit object. :param key: FITS header key [string] or list of keys to try [list of string...
bigcode/self-oss-instruct-sc2-concepts
def camelize(val): """Return the camel case version of a :attr:`str` >>> camelize('this_is_a_thing') 'thisIsAThing' """ s = ''.join([t.title() for t in val.split('_')]) return s[0].lower()+s[1:]
bigcode/self-oss-instruct-sc2-concepts
def format_menu(menu): """ Textually format a menu. Args: menu: A dictionary with as key the type of menu item and as values the menu content and the prices for students and staff. Returns: The nicely format menu including emojis to indicate the menu types. """ me...
bigcode/self-oss-instruct-sc2-concepts
def distance_between(agents_row_a, agents_row_b): """ calculate distance between 2 agents """ length = (((agents_row_a[0] - agents_row_b[0])**2) + ((agents_row_a[1] - agents_row_b[1])**2))**0.5 return(length)
bigcode/self-oss-instruct-sc2-concepts
def crop_border(imgs, crop_border): """Crop borders of images. Args: imgs (list[ndarray] | ndarray): Images with shape (h, w, c). crop_border (int): Crop border for each end of height and weight. Returns: list[ndarray]: Cropped images. """ if crop_border == 0: retur...
bigcode/self-oss-instruct-sc2-concepts
def convert_to_strings(entities): """ Given a tuple of entities, return a list of strings """ return [e.text for e in entities]
bigcode/self-oss-instruct-sc2-concepts
def populate_countries_dict(file_path): """ Function to populate dictionary of countries and url numbers. """ countries_dict = {} with open(file_path, 'r') as f: for line in f.readlines(): key_value = line[:-1].split(':') countries_dict[key_value[0]] = int(k...
bigcode/self-oss-instruct-sc2-concepts
import re def remove_extra_description_terms(description): """ Sometimes the description contains some things we don't want to include like trailing '.', extra spaces, the string (non-protein coding) and a typo in the name of tmRNA's. This corrects those issues. """ description = re.sub( ...
bigcode/self-oss-instruct-sc2-concepts
def dict_diff(first, second): """ Return a dict of keys that differ with another config object. If a value is not found in one fo the configs, it will be represented by KEYNOTFOUND. @param first: Fist dictionary to diff. @param second: Second dicationary to diff. @return diff: ...
bigcode/self-oss-instruct-sc2-concepts
def response_verify(resp): """ Verify if the response's status code is 200 or not. :return: True if response code is 200 :rtype: bool """ if resp.status_code != 200 or resp.text == "": return False else: return True
bigcode/self-oss-instruct-sc2-concepts
def get_transaction_data(consumer_id, transactions): """ For all transactions related to a consumer, return a dictionary with the keys being the offer IDs or the value 'transaction' for non-offer related events. """ txn_dict = {} txn = transactions[transactions["person"] == co...
bigcode/self-oss-instruct-sc2-concepts
import requests def download(url): """ :param url: str Url to get :return: response Response of request """ return requests.get(url)
bigcode/self-oss-instruct-sc2-concepts
def cost(z): """ Cost function. """ return 0.1 + 0.4 * (4 * z[0])**2 + 0.5 * z[1]
bigcode/self-oss-instruct-sc2-concepts
import hashlib def md5_hex(data): """ shortcut of hashlib.md5('xxx').hexdigest() >>> md5_hex('123') '202cb962ac59075b964b07152d234b70' """ return hashlib.md5(data).hexdigest()
bigcode/self-oss-instruct-sc2-concepts
def get_output_jar_paths(version): """ Gets the list of output jars, which includes the primary jep-${version}.jar, the test jar, and the src jars. """ return [ 'build/java/jep-{0}-sources.jar'.format(version), 'build/java/jep-{0}.jar'.format(version), 'build/java/jep-{0}-tes...
bigcode/self-oss-instruct-sc2-concepts
def add_files_to_zip(zip_file, base_dir, file_list): """Pack a list of files into a zip archive, that is already opened for writing. Args: zip_file: An object representing the zip archive. base_dir: Base path of all the files in the real file system. file_list: List of absolute file paths to add. Mus...
bigcode/self-oss-instruct-sc2-concepts
def prior_probability_of_category_k(k, c, nk): """ Function that calculates the prior probability of category k. This is equation 3-4 in [Ande90]_ Parameters ---------- k : int Category index. For example, k can be 0 or 1 or 2 etc c : float Coupling probability. This is the prob...
bigcode/self-oss-instruct-sc2-concepts
import click def format(text): """Format all OK,FAIL,PR,REPO words :param text: word :type text: string :raises Exception: Unknown text :return: formated click style text :rtype: string """ text = text.lower() if text == "ok": return click.style('OK', fg='green', bold...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def HashedKey(*args, version=None): """ BOSS Key creation function Takes a list of different key string elements, joins them with the '&' char, and prepends the MD5 hash of the key to the key. Args (Common usage): parent_iso (None or 'ISO') collection_id experi...
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def parse_date(date_text: str): """ Convert a date string into a datetime instance that can be saved as an SQL DATE. :param date_text: A timestamp string in "YYYY-MM-DD" format :return: A datetime object """ return datetime.strptime(date_text, '%Y-%m-%d')
bigcode/self-oss-instruct-sc2-concepts
def filter_images(data, split_data): """ Keep only images that are in some split and have some captions """ all_split_ids = set() for split_name, ids in split_data.iteritems(): all_split_ids.update(ids) new_data = [] for img in data: keep = img['id'] in all_split_ids and len(img['regions']) > 0 if...
bigcode/self-oss-instruct-sc2-concepts
import torch def adjacency_matrix_to_tensor_representation(W): """ Create a tensor B[:,:,1] = W and B[i,i,0] = deg(i)""" degrees = W.sum(1) B = torch.zeros((len(W), len(W), 2)) B[:, :, 1] = W indices = torch.arange(len(W)) B[indices, indices, 0] = degrees return B
bigcode/self-oss-instruct-sc2-concepts
def inverse_weight(distance, num=1.0, const=0.1): """ 权重函数: 距离的逆. :param distance: 距离 :type distance: float :param num: 分子 :type num: float :param const: 常量 :type const: float :return: 权重值 """ return num / (distance + const)
bigcode/self-oss-instruct-sc2-concepts
import random import math def normal_random(mean = 0.0, variance = 1.0): """ Samples from a normal distribution. :param mean The mean. Default is 0.0. :param variance The variance. Default is 1.0. """ while True: v1 = 2.0 * random.random() - 1.0 ...
bigcode/self-oss-instruct-sc2-concepts
def increment(number): """Increases a given number by 1.""" return number + 1
bigcode/self-oss-instruct-sc2-concepts
import logging def get_logger(logger_name, logger_level, stream=None): """Get a logger for the script. Using stream handler. # Arguments logger_name: `str`<br/> the name of the logger logger_level: `int`<br/> the minimial level that trigger the logger. str...
bigcode/self-oss-instruct-sc2-concepts
def hamming_weight(n): """ Calculates the Hamming weight of a positive integer. The Hamming weight of an integer is defined as the number of 1s in its binary representation. """ c = 0 while n: c += 1 n &= n - 1 return c
bigcode/self-oss-instruct-sc2-concepts
def split_plus(line): """ Split a line according to the + (plus) sign. :param line: :return: """ new_line = line.split("+") return new_line
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from typing import Any def get_keys_containing(obj: Union[dict, Any], key) -> set: """ Returns a set with the keys that contain `key` Example: .. code-block:: python from quantify_core.utilities.general import get_keys_containing dict_obj = {"x0": [1, 2, 3],...
bigcode/self-oss-instruct-sc2-concepts
def commonLeader(data, i, j): """Get the number of common leading elements beginning at data[i] and data[j].""" l = 0 try: while l < 255+9 and data[i+l] == data[j+l]: l += 1 except IndexError: pass # terminates return l
bigcode/self-oss-instruct-sc2-concepts
import re def _validcas(cas): """ Validate a CAS Registry Number See: https://en.wikipedia.org/wiki/CAS_Registry_Number#Format :param cas: a string to be validated as a CAS Registry Number :return: bool """ test = re.search(r'^\d{2,8}-\d{2}-\d$', cas) # if format of string does not mat...
bigcode/self-oss-instruct-sc2-concepts
def join_cols(cols): """Join list of columns into a string for a SQL query""" return ", ".join([i for i in cols]) if isinstance(cols, (list, tuple, set)) else cols
bigcode/self-oss-instruct-sc2-concepts
def _getParameterRange(key): """ Returns fur's default parameter range as 2-tuple (min, max). key: fur attribute (string) """ if "Density" ==key: return (10000.0, 30000.0) ## geometry attributes (1) for single strand if "Length" ==key: return (1.00, 5.00) if "BaseWidth"==key: return ...
bigcode/self-oss-instruct-sc2-concepts
def _read_binary_data(fp, size, name, clip=False): """Read zero-padded binary data from a file. Attempts to read `size+1` bytes from filehandle `fp`. If 0 or more than `size` bytes are read, raises an IOError. Data of any other size is returned to the caller, followed by enough zero padding to yield `size` byt...
bigcode/self-oss-instruct-sc2-concepts
from typing import Counter def create_vocabulary(text, max_vocab_size = 2000): """ Create Vocabulary dictionary Args: text(str): inout text max_vocab_size: maximum number of words in the vocabulary Returns: word2id(dict): word to id mapping id2word(dict): id to word mapping...
bigcode/self-oss-instruct-sc2-concepts
def get_user_version(conn): """Return user_version value.""" result = conn.execute('PRAGMA user_version') return result.fetchone()[0]
bigcode/self-oss-instruct-sc2-concepts
def object_from_args(args): """ Turns argparser's namespace into something manageable by an external library. Args: args: The result from parse.parse_args Returns: A tuple of a dict representing the kwargs and a list of the positional arguments. """ return dict(args._get_kwargs...
bigcode/self-oss-instruct-sc2-concepts
def get_storage_blob(bucket, source_folder_name, source_file_name): """ Fetches and returns the single source file blob from the buck on Google Cloud Storage """ source_path = source_file_name if source_folder_name != '': source_path = f'{source_folder_name}/{source_file_name}' blob ...
bigcode/self-oss-instruct-sc2-concepts
def _to_camel_case(text: str) -> str: """ Convert a text in snake_case format into the CamelCase format :param text: the text to be converted. :return: The text in CamelCase format. """ return "".join(word.title() for word in text.split("_"))
bigcode/self-oss-instruct-sc2-concepts
def largest_prime_factor(number): """ Calculate the largest prime factor of a number :param number: Number of which largest prime should be found :return: Integer: largest prime factor """ count = 2 while count * count <= number: if number % count: count += 1 else...
bigcode/self-oss-instruct-sc2-concepts
import hashlib import json def get_cache_key(args, kwargs): """ Returns a cache key from the given kwargs This is simply a sha256 hexdigest of the keyword arguments Args: kwargs (dict): the arguments to build a cache key from Returns: str: the cache key """ sha = hashlib...
bigcode/self-oss-instruct-sc2-concepts
def text(node): """Extract text from an XML node.""" if node is None: return '' s = ''.join(node.itertext()) return ' '.join(s.split())
bigcode/self-oss-instruct-sc2-concepts
from typing import AnyStr def ensure_bytes(value: AnyStr) -> bytes: """Convert text into bytes, and leaves bytes as-is.""" if isinstance(value, bytes): return value if isinstance(value, str): return value.encode('utf-8') raise TypeError(f"input must be str or bytes, got {type(value).__...
bigcode/self-oss-instruct-sc2-concepts
def add_suffix(suffix, name): """Adds subfix to name.""" return "/".join((name, suffix))
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from typing import List from typing import Tuple from typing import Iterable def flatten(lst: Union[List, Tuple]) -> List: """Recursive function that flatten a list (of potential `Iterable` objects).""" if isinstance(lst, Iterable) and not isinstance(lst, (str, bytes)): return...
bigcode/self-oss-instruct-sc2-concepts
import re def strip_ws(string: str): """ Strip whitespace off a string and replace all instances of >1 space with a single space. """ return re.sub(r'\s+', ' ', string.strip())
bigcode/self-oss-instruct-sc2-concepts
def try_lower(string): # Ask for, forgiveness seems faster, perhaps better :-) """Converts string to lower case Args: string(str): ascii string Returns: converted string """ try: return string.lower() except Exception: return string
bigcode/self-oss-instruct-sc2-concepts
def concatenate_rounds(rounds1, rounds2): """Return a list of rounds that combines `rounds1` and `rounds2`.""" return rounds1 + rounds2
bigcode/self-oss-instruct-sc2-concepts
import torch def coco_category_to_topology(coco_category): """Gets topology tensor from a COCO category """ skeleton = coco_category['skeleton'] K = len(skeleton) topology = torch.zeros((K, 4)).int() for k in range(K): topology[k][0] = 2 * k topology[k][1] = 2 * k + 1 t...
bigcode/self-oss-instruct-sc2-concepts
import collections def tail(n, seq): """ The last n elements of a sequence >>> tail(2, [10, 20, 30, 40, 50]) [40, 50] See Also: drop take """ try: return seq[-n:] except (TypeError, KeyError): return tuple(collections.deque(seq, n))
bigcode/self-oss-instruct-sc2-concepts
import re def delete_whitespace(text: str) -> str: """ Removes whitespaces from text. """ return re.sub(r'\s+', '', text).strip()
bigcode/self-oss-instruct-sc2-concepts
def score_to_quality(qval, offset: int=32, maxval: int=126): """Convert a score to quality value.""" cval = int(qval) + offset if cval > maxval: cval = maxval return chr(cval)
bigcode/self-oss-instruct-sc2-concepts
def record_variant_id(record): """Get variant ID from pyvcf.model._Record""" if record.ID: return record.ID else: return record.CHROM + ':' + str(record.POS)
bigcode/self-oss-instruct-sc2-concepts
from typing import List def chargement_fichier(nom_fichier : str) -> List[str]: """Précondition : nom_fichier est le nom d'un fichier texte existant Retourne le contenu du fichier texte identifié par nom_fichier sous la forme d'une liste de lignes de texte. """ # Lignes contenues dans le fichier ...
bigcode/self-oss-instruct-sc2-concepts
def parse(resp): """ Parse response into status line, headers and body. """ pos = resp.find(b'\r\n\r\n') assert pos != -1, 'response is %s' % repr(resp) head = resp[:pos] body = resp[pos+4:] status,head = head.split(b'\r\n', 1) hdrs = {} for line in head.split(b'\r\n'): k...
bigcode/self-oss-instruct-sc2-concepts
def flatten_board(board): """ Turns the 3x3 board into a 1x9 board """ return [cell for row in board for cell in row]
bigcode/self-oss-instruct-sc2-concepts
import typing def get_path_from_list(to_parse: typing.List[str], path_prefix: str) -> str: """Parse a path from a list of path parts.""" ret = path_prefix for i in to_parse: ret += f"/{i}" return ret.lstrip("/").rstrip("/")
bigcode/self-oss-instruct-sc2-concepts
def _filter_labels(labels, start_datetime, end_datetime, verbose=True): """ Select the labels whose date in the provided datetime range """ mask = (labels.Date >= start_datetime) & (labels.Date <= end_datetime) if verbose: print("Selecting {} out of {} labels".format(mask.sum(), len(labels))) re...
bigcode/self-oss-instruct-sc2-concepts
import random def random_float(min=1.0, max=100.0, decimals=None): """Generate a random float between min and max. `decimals` is the maximum amount of decimal places the generated float should have. """ randomfloat = random.uniform(min, max) if decimals is not None: randomfloat = roun...
bigcode/self-oss-instruct-sc2-concepts
def ip_to_int(ip): """ >>> ip_to_int(None) 0 >>> ip_to_int('0.0.0.0') 0 >>> ip_to_int('1.2.3.4') 16909060 """ if ip is None: return 0 result = 0 for part in ip.split('.'): result = (result << 8) + int(part) return result
bigcode/self-oss-instruct-sc2-concepts
def is_valid(value, mode): """Return True if value is in range of map size. Mode: WIDTH or HEIGHT, depending what value is checked.""" return False if value < 0 or value > mode-1 else True
bigcode/self-oss-instruct-sc2-concepts
def get_docs_changed(diffs: str) -> int: """Processes diffs from a Pull Request to extract number of doc-type files changed in the PR Parameters ---------- diffs : str A string denoting the diffs in the PR Returns ------- int number of files of documentation type that have ...
bigcode/self-oss-instruct-sc2-concepts
def check_fit(plaintext: list, ciphertext: list) -> int: """Check if ciphertext can fit in plaintext's whitespace. Sum number of blanks in **plaintext** and compare to number of characters in **ciphertext** to see if it can fit. Args: plaintext (list): Paragraphs of a fake message in a list of...
bigcode/self-oss-instruct-sc2-concepts