seed
stringlengths
1
14k
source
stringclasses
2 values
def rows(matrix): """ Returns the no. of rows of a matrix """ if type(matrix) != list: return 1 return len(matrix)
bigcode/self-oss-instruct-sc2-concepts
def assignment_explicit_no_context(arg): """Expected assignment_explicit_no_context __doc__""" return "assignment_explicit_no_context - Expected result: %s" % arg
bigcode/self-oss-instruct-sc2-concepts
def server_supports_alter_user(cursor): """Check if the server supports ALTER USER statement or doesn't. Args: cursor (cursor): DB driver cursor object. Returns: True if supports, False otherwise. """ cursor.execute("SELECT VERSION()") version_str = cursor.fetchone()[0] version = v...
bigcode/self-oss-instruct-sc2-concepts
def get_insight(df): """ Get insight from a youtube_history dataframe transformed by transform() Parameters ---------- df : DataFrame A youtube_history dataframe transformed by transform() Returns ------- df_info : dictionary Contains informations about a specific youtu...
bigcode/self-oss-instruct-sc2-concepts
def ensure_absent(spec): """ test if an 'Ensure' key is set to absent in dictionary 'spec' """ if 'Ensure' in spec and spec['Ensure'] == 'absent': return True return False
bigcode/self-oss-instruct-sc2-concepts
def expand_hex(x): """Expands shorthand hexadecimal code, ex: c30 -> cc3300""" if len(x) == 3: t = list(x) return "".join([t[0], t[0], t[1], t[1], t[2], t[2]]) else: return x
bigcode/self-oss-instruct-sc2-concepts
def percentagify(numerator, denominator): """Given a numerator and a denominator, return them expressed as a percentage. Return 'N/A' in the case of division by 0. """ if denominator: return '{:04.2f}%'.format((numerator / denominator) * 100) else: return 'N/A'
bigcode/self-oss-instruct-sc2-concepts
import torch def load_model( model_path: str = "saved_models/traced_pspnet_model.pt", ) -> torch.ScriptModule: """Loads and returns the torchscript model from path. Parameters ---------- model_path : str, optional The path to the torchscript model, by default "models/face_blur.pt" Re...
bigcode/self-oss-instruct-sc2-concepts
import typing def _versify ( py_version_info: typing.Tuple ) -> str: """ Semiprivate helper function to convert Python version to a point release (a string). py_version_info: Python version info as a named tuple from the operating system, e.g., from [`sys.version_info[:2]`](https://docs.python.org/3/...
bigcode/self-oss-instruct-sc2-concepts
def secondOrderTrans(high_phase, low_phase, Tstr='Tnuc'): """ Assemble a dictionary describing a second-order phase transition. """ rdict = {} rdict[Tstr] = 0.5*(high_phase.T[0] + low_phase.T[-1]) rdict['low_vev'] = rdict['high_vev'] = high_phase.X[0] rdict['low_phase'] = low_phase.key r...
bigcode/self-oss-instruct-sc2-concepts
def colorize(text, color): """ Display text with some ANSI color in the terminal. """ code = f"\033[{color}m" restore = "\033[0m" return "".join([code, text, restore])
bigcode/self-oss-instruct-sc2-concepts
def strip(pre, s): """Strip prefix 'pre' if present. """ if s.startswith(pre): return s[len(pre):] else: return s
bigcode/self-oss-instruct-sc2-concepts
def id_list_from_editor_output(bs, **kwargs): """bs is a string of console output the lines are: # delete me if you .... (must be deleted) id col1 col2 010101 c11 c22222 ... If first line begins with # then return an empty list Ignore the second line Return a list composed of...
bigcode/self-oss-instruct-sc2-concepts
import copy def pop_from_list(lst, items): """Pop all `items` from `lst` and return a shorter copy of `lst`. Parameters ---------- lst: list items : sequence Returns ------- lst2 : list Copy of `lst` with `items` removed. """ lst2 = copy.deepcopy(lst) for item...
bigcode/self-oss-instruct-sc2-concepts
import hashlib def hash_md5(filename, chunk_size=2 ** 16): """ Computes the *Message Digest 5 (MD5)* hash of given file. Parameters ---------- filename : unicode File to compute the *MD5* hash of. chunk_size : int, optional Chunk size to read from the file. Returns --...
bigcode/self-oss-instruct-sc2-concepts
from typing import Callable import click def variant_option(command: Callable[..., None]) -> Callable[..., None]: """ Option to choose the DC/OS variant for installation. """ function = click.option( '--variant', type=click.Choice(['oss', 'enterprise']), required=True, ...
bigcode/self-oss-instruct-sc2-concepts
def unit_length(ua): """ Computes the unit length in the given units """ return ua.solar_mass * ua.grav_constant / ua.light_speed**2
bigcode/self-oss-instruct-sc2-concepts
import base64 def csv_download_link(df, filename): """Returns a link to download the dataframe as the given filename.""" csv = df.to_csv(index=False) b64 = base64.b64encode(csv.encode()).decode() href = f'data:file/csv;base64,{b64}' return f'<a href="{href}" download="{filename}">`{filename}`</a>'
bigcode/self-oss-instruct-sc2-concepts
def datetime_from_msdos_time(data, timezone): """ Convert from MSDOS timestamp to date/time string """ data_high = (data & 0xffff0000) >> 16 data_low = data & 0xffff year = 1980 + ((data_low & 0xfe00) >> 9) month = ((data_low & 0x1e0) >> 5) day = data_low & 0x1f hour = (data_high & ...
bigcode/self-oss-instruct-sc2-concepts
def distLInf (a, b): """ Utility method to compute the L-infinity distance between the given two coordinates. """ return max (abs (a[0] - b[0]), abs (a[1] - b[1]))
bigcode/self-oss-instruct-sc2-concepts
def has_right_component_fragment(root, comp_index): """ Return True if component at comp_index has a component to its right with same comp_num INPUT: - ``root`` -- The forest to which component belongs - ``comp_index`` -- Index at which component is present in root OUTPUT: ``True`` ...
bigcode/self-oss-instruct-sc2-concepts
def negative_log_likelihood(y_true, predicted_distributions): """Calculates the negative log likelihood of the predicted distribution ``predicted_distribution`` and the true label value ``y_true`` # Arguments y_true: Numpy array of shape [num_samples, 1]. predicted_distribution: TensorFlow p...
bigcode/self-oss-instruct-sc2-concepts
def cull_candidates(candidates, text, sep=' '): """Cull candidates that do not start with ``text``. Returned candidates also have a space appended. Arguments: :candidates: Sequence of match candidates. :text: Text to match. :sep: Separator to append to match. >>> cull_candidat...
bigcode/self-oss-instruct-sc2-concepts
import re def original_url_from_httrack_comment(html): """ Extracts the original url from HTTrack comment """ url = "unknown_url" for m in re.finditer( "<!-- Mirrored from ([^>]+) by HTTrack Website Copier", html): url = m.groups()[0] if not url.startswith('http://'): ...
bigcode/self-oss-instruct-sc2-concepts
def tag_ordinal(tag): """ Given a beautiful soup tag, look at the tags of the same name that come before it to get the tag ordinal. For example, if it is tag name fig and two fig tags are before it, then it is the third fig (3) """ return len(tag.find_all_previous(tag.name)) + 1
bigcode/self-oss-instruct-sc2-concepts
from functools import reduce def deep_get(dictionary, keys): """ Get the data out of the dictionary at the given nested key path. :param dictionary: Dictionary to retrieve the data from at the given keys path :param keys: ['a', 'b', 'c'] :return: Value """ return reduce(lambda d, key: d.g...
bigcode/self-oss-instruct-sc2-concepts
import string import secrets def get_random_string(length=12, allowed_chars=string.ascii_letters + string.digits): """Return a securely generated random string. """ return ''.join(secrets.choice(allowed_chars) for _ in range(length))
bigcode/self-oss-instruct-sc2-concepts
def iterationstopixel(i, iterations): """ Assigns a color based on iteration count. You can implement your own color function here. """ d = int(i / iterations * 255) return d, d, d
bigcode/self-oss-instruct-sc2-concepts
def cols(matrix): """ Returns the no. of columns of a matrix """ if type(matrix[0]) != list: return 1 return len(matrix[0])
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def _setup_filetree_for_priority_test(tmp_path: Path) -> Path: """ root └─ dir_1 └─ dir_1_1 └─ file_1.py Returns: path for file_1.py """ root_dir = tmp_path / 'root' root_dir.mkdir() dir_1 = root_dir / 'dir_1' dir_1.mkdir() dir_1_1 =...
bigcode/self-oss-instruct-sc2-concepts
def simple_incorrect_scan_and_codes(simple_scan): """ Return a scan and error codes, representing a small mesh which produces a couple of known requirement and advisory statements, and the relevant statement codes. Errors as follows: mesh missing cf_role (but identified from datavar) --> R1...
bigcode/self-oss-instruct-sc2-concepts
def key(request) -> int: """Get instance key.""" return request.param
bigcode/self-oss-instruct-sc2-concepts
def derive_table_from(source): """Ease the typical use case /somewhere/TAB.txt -> TAB.json.""" table = source.stem.upper() return table, f'{table}.json'
bigcode/self-oss-instruct-sc2-concepts
def remove_alignments(group, min_length: int=1000, min_coverage: float=0.2): """ Since MUMmer aligns sections of a sequence, it can produce multiple regions of alignment for a given sequence. We filter out low alignments using this function. Args: group: A pandas group_by group. ...
bigcode/self-oss-instruct-sc2-concepts
import functools def require_owner(message=None): """Decorate a function to require the triggering user to be the bot owner. If they are not, `message` will be said if given.""" def actual_decorator(function): @functools.wraps(function) def guarded(bot, trigger, *args, **kwargs): ...
bigcode/self-oss-instruct-sc2-concepts
import socket def ip_sort_key(ip_address): """Get a sort key for an IPv4 or IPv6 address""" if ':' in ip_address: # IPv6 return b'6' + socket.inet_pton(socket.AF_INET6, ip_address) # IPv4 return b'4' + socket.inet_aton(ip_address)
bigcode/self-oss-instruct-sc2-concepts
def lha2scale(lha): """Extract the high scale from a dictionary eturned by pylha from a DSixTools options file.""" return dict(lha['BLOCK']['SCALES']['values'])[1]
bigcode/self-oss-instruct-sc2-concepts
def generate_dot(dc): """ Generates a dot format graph of docker-compose depends_on between services :param dict dc: Docker comppose configuration loaded as a python dict :rtype: string """ lines = [] lines.append("digraph docker {") for service_name, service in dc["services"].items(): ...
bigcode/self-oss-instruct-sc2-concepts
def find_mirror_next(seq, max_window_size, mirror_centre): """Find the next token that will lead to a mirror pattern. Searches in the range of `window_size` tokens to the left from the `mirror_centre` if it's found. E.g., in [a, b, AND, a] the next token should be 'b' to create a mirror pattern. ...
bigcode/self-oss-instruct-sc2-concepts
import requests def exchange_code_for_token(code, token_url, client_id, client_secret, redirect_uri): """exchange a OAuth2 authorization code for an access token https://docs.github.com/en/free-pro-team@latest/developers/apps/authorizing-oauth-apps#2-users-are-redirected-back-to-your-site-by-github Para...
bigcode/self-oss-instruct-sc2-concepts
def query(query_string, data): """ Return a query string for use in HTML links. For example, if query_string is "?page=foo" and data is "date=200807" this function will return "?page=foo&date=200807" while if query_string were "" it would return "?date=200807". """ if query_s...
bigcode/self-oss-instruct-sc2-concepts
def return_item(item, key, silently=False): """Depending of the type of item, return the value corresponding to `key` or the attribute `key` of the object item. Args: item (dict or object): Python object to explore key (str): key to search in the object silently (bool, optional): wh...
bigcode/self-oss-instruct-sc2-concepts
import json def typeforms_embed(url, selector, options={}, mode='widget'): """Embed a typeforms form. Parameters ---------- url : str Typeform share typeform_url. selector : str CSS selector to place typeform_id into. options : dict, str Accepts a dictionary or JSON as...
bigcode/self-oss-instruct-sc2-concepts
def de_dup_and_sort(input): """ Given an input list of strings, return a list in which the duplicates are removed and the items are sorted. """ input = set(input) input = list(input) input.sort() return input
bigcode/self-oss-instruct-sc2-concepts
def get_volume(shade_client, name_or_id, filters=None): """Get a volume by name or ID. :param name_or_id: Name or ID of the volume. :param filters: A dictionary of meta data to use for further filtering. :returns: A volume ``munch.Munch`` or None if no matching volume is found. """ return shad...
bigcode/self-oss-instruct-sc2-concepts
def generate_group_by_range_and_index_str(group_by, data_str, value_str, index_str): """ Generate the range and index string for GROUP BY expression. Args: group_by (str): the column name to be grouped. data_str (str): a string that represents the t...
bigcode/self-oss-instruct-sc2-concepts
def compute_xi_t(return_t, risk_free_rate, sigma_t): """ Compute innovation xi at time t as a function of return t, rf rate, and sigma t """ return return_t - risk_free_rate + 1/2 * sigma_t
bigcode/self-oss-instruct-sc2-concepts
def _cholesky_solve(M, rhs, dotprodsimp=None): """Solves ``Ax = B`` using Cholesky decomposition, for a general square non-singular matrix. For a non-square matrix with rows > cols, the least squares solution is returned. Parameters ========== dotprodsimp : bool, optional Specifies...
bigcode/self-oss-instruct-sc2-concepts
def rstrip(val: str) -> str: """Remove trailing whitespace.""" return val.rstrip()
bigcode/self-oss-instruct-sc2-concepts
def intprod(xs): """ Product of a sequence of integers """ out = 1 for x in xs: out *= x return out
bigcode/self-oss-instruct-sc2-concepts
def safe_float(val): """ Convert the given value to a float or 0f. """ result = float(0) try: result = float(val) except (ValueError, TypeError): pass return result
bigcode/self-oss-instruct-sc2-concepts
import requests def get_html(url, session_obj=None, headers=None): """ Request to the server and receiving a response, in the form of an html code of a web page. """ try: request = session_obj if session_obj else requests response = request.get(url, timeout = 5, headers=headers) ...
bigcode/self-oss-instruct-sc2-concepts
def _MetadataMessageToDict(metadata_message): """Converts a Metadata message to a dict.""" res = {} if metadata_message: for item in metadata_message.items: res[item.key] = item.value return res
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def get_abs_path_from_here(relative_path: str, calling_file_name: str) -> Path: """ return absolute path to file, based on path from the calling location :param calling_file_name: optional name of the calling script that will serce as reference :param relative_path: relative p...
bigcode/self-oss-instruct-sc2-concepts
def lerpv3(a,b,t): """linear interplation (1-t)*a + (t)*b""" return ( (1-t)*a[0] + (t)*b[0], (1-t)*a[1] + (t)*b[1], (1-t)*a[2] + (t)*b[2] )
bigcode/self-oss-instruct-sc2-concepts
def get_venv_name(dockenv_name): """ Helper function to split the user-defined virtual env name out of the full name that includes the dockenv tag :param dockenv_name: The full name to pull the virtual env name out of """ # Format of tage name if dockenv-**NAME**:latest...
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path from typing import Optional from typing import List import uuid def make_metakernel(kernel_dir: Path, kernels: Optional[List[str]] = None) -> Path: """Create a uniquely-named SPICE metakernel in ``kernel_dir`` and return its path. If ``kernels`` is `None`, this function searches ``ker...
bigcode/self-oss-instruct-sc2-concepts
def _Aij(A, i, j): """Sum of upper-left and lower right blocks of contingency table.""" # See `somersd` References [2] bottom of page 309 return A[:i, :j].sum() + A[i+1:, j+1:].sum()
bigcode/self-oss-instruct-sc2-concepts
from typing import Callable from typing import Any def get_func_name( func: Callable[..., Any], prepend_module: bool = False, repr_fallback: bool = False, ) -> str: """Extract and return the name of **func**. A total of three attempts are performed at retrieving the passed functions name: 1....
bigcode/self-oss-instruct-sc2-concepts
def mimic_case(old_word, new_word): """ >>> print(mimic_case('EtAt', 'état')) ÉtAt """ if len(old_word) != len(new_word): raise ValueError("lengths don't match") return ''.join([ new_word[i].upper() if old_word[i].isupper() else new_word[i].lower() for i in range(len(old_...
bigcode/self-oss-instruct-sc2-concepts
def text_to_word_sequence(text, filters='!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n', lower=True, split=" ") -> list: """ Convert text to word list :param text: test list :param filters: filter rules, filter all punctuation marks, tabs, newlines, etc. by default :param lower: whether to convert text to lowerc...
bigcode/self-oss-instruct-sc2-concepts
def phase(x): """Returns 1 if the input is even and -1 if it is odd. Mathematically equivalent to (-1)^x""" if x % 2 == 0: return 1 else: return -1
bigcode/self-oss-instruct-sc2-concepts
def calculate_chunk_slices(items_per_chunk, num_items): """Calculate slices for indexing an adapter. Parameters ---------- items_per_chunk: (int) Approximate number of items per chunk. num_items: (int) Total number of items. Returns ------- list of slices """ a...
bigcode/self-oss-instruct-sc2-concepts
import math def rotate_point(x,y,theta): """Rotate a point around the origin by an angle theta. Args: x (float): x coordinate of point. y (float): y coordinate of point. theta (float): rotation angle (rad). Returns: list: [x,y] coordinates of rotated point. """ "...
bigcode/self-oss-instruct-sc2-concepts
def iterable(obj): """Utility to check if object is iterable""" try: iter(obj) except: return False else: return True
bigcode/self-oss-instruct-sc2-concepts
import pathlib def zcoord(path:pathlib.Path) -> float: """ Return the putative Z coordinate for a image file path name """ return int(path.name.split(".")[0]) / 10
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def can_override(path: Path, override: bool) -> Path: """Check if it's allowed to override a `path`. Args: path: path, where we are going to write override: permission to override flag Returns: The input `path`to facilitate chaining in mapping in code. ...
bigcode/self-oss-instruct-sc2-concepts
def isLarger(ser1, ser2, fractionTrue=1.0, startIdx=0): """ Checks that arr1[startIdx:] > arr2[startIdx:] Parameters ---------- ser1: pd.Series ser2: pd.Series fractionTrue: float in [0, 1] startIdx: int Returns ------- bool """ numTrue = sum(ser1.loc[startIdx:] > s...
bigcode/self-oss-instruct-sc2-concepts
import glob from itertools import chain from typing import Iterable def poly_iglob(filenames_or_patterns: Iterable, *, recursive=True, ignore_case=True): """ Read sequence of file names with or without wildcard characters. Any wildcards are replaced by matching file names using glob.iglob(). :param f...
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterable from typing import Sequence def report_invalid_whitelist_values( whitelist: Iterable[str], items: Sequence[str], item_type: str ) -> str: """Warns the user if there are entries in ``whitelist`` which don't correspond to any item in ``items``. Helps highlight typos. """ ...
bigcode/self-oss-instruct-sc2-concepts
def _count_of_curr_and_next(rule): """Count tokens to be matched and those to follow them in rule.""" return len(rule.tokens) + len(rule.next_tokens or []) + len(rule.next_classes or [])
bigcode/self-oss-instruct-sc2-concepts
def get_charge(lines): """ Searches through file and finds the charge of the molecule. """ for line in lines: if 'ICHRGE' in line: return line.split()[2] return None
bigcode/self-oss-instruct-sc2-concepts
def tvi(b3, b4, b6): """ Transformed Vegetation Index (Broge and Leblanc, 2001). .. math:: TVI = 0.5 * (120 * (b6 - b3) - 200 * (b4 - b3)) :param b3: Green. :type b3: numpy.ndarray or float :param b4: Red. :type b4: numpy.ndarray or float :param b6: Red-edge 2. :type b6: numpy.ndar...
bigcode/self-oss-instruct-sc2-concepts
from typing import Callable def _derive_template_name(view_function: Callable) -> str: """Derive the template name from the view function's module and name.""" # Select segments between `byceps.blueprints.` and `.views`. module_package_name_segments = view_function.__module__.split('.') blueprint_path...
bigcode/self-oss-instruct-sc2-concepts
def count_incident_type(incidents, type): """ Gets total number of incidents of a certain type :param incidents: dictionary -- set of incidents to parse :param type: string -- key to parse within incidents :return: int -- total incidents """ total = 0 for _, incident in incidents.item...
bigcode/self-oss-instruct-sc2-concepts
def load_data(path): """ Load input data from a given path. Data is stored as word,label\nword,label\n ... :param path: path to file :return: (list of words, list of labels) """ words = [] labels = [] with open(path, encoding='utf-8') as f: lines = f.read().splitlines() for ...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def get_clabe_control_digit(clabe: str) -> int: """Generate the checksum digit for a CLABE. :param clabe: CLABE. :return: The CLABE checksum digit. """ factors = [3, 7, 1] products: List[int] = [] for i, digit in enumerate(clabe[:17]): products.append((int...
bigcode/self-oss-instruct-sc2-concepts
def _getcalday(instcal, date): """ Get index of row for current night in instrument calendar table. """ for i in range(len(instcal['date'])): if instcal['date'][i] in date: return i print('\n Date '+date+' not found in instrument configuration calendar.') raise ValueError('Da...
bigcode/self-oss-instruct-sc2-concepts
def comp(DNA: str, pat_len: int) -> list: """Sort all substrings of pat_len length :param DNA: the string to pull substrings from :type DNA: str :param pat_len: the length of substrings to pull :type pat_len: int :returns: all substrings, sorted :rtype: list (of strs) """ if not DN...
bigcode/self-oss-instruct-sc2-concepts
def get_single_value(group, name): """Return single value from attribute or dataset with given name in group. If `name` is an attribute of the HDF5 group `group`, it is returned, otherwise it is interpreted as an HDF5 dataset of `group` and the last value of `name` is returned. This is meant to retriev...
bigcode/self-oss-instruct-sc2-concepts
import typing def lane_offset_width_meters(shape: typing.Sequence[int], poly_evals: typing.Tuple[typing.List[float], typing.List[float]], xm_per_pix: float) -> typing.Tuple[float, float]: """Calculate center-offset of the lane, given polynomial curves for ...
bigcode/self-oss-instruct-sc2-concepts
def z_inverse(x, mean, std): """The inverse of function z_score""" return x * std + mean
bigcode/self-oss-instruct-sc2-concepts
def get_product_images(product): """Return list of product images that will be placed in product gallery.""" return list(product.images.all())
bigcode/self-oss-instruct-sc2-concepts
import random def choose_between_by_p(l1, l2, p, count): """ Choose `count` elements from `l1` (w/ prob `p`) and `l2` (w/ prob `p`-1). """ assert 0 <= p assert p <= 1 return [random.choice(l1) if random.random() <= p else random.choice(l2) for _ in range(count)]
bigcode/self-oss-instruct-sc2-concepts
def mol_file_basename(tag): """Covert a tag into a molecular data file name""" return 'c%06d.' % tag
bigcode/self-oss-instruct-sc2-concepts
def python_trailing(n): """Count the number of trailing zero bits in abs(n).""" if not n: return 0 t = 0 while not n & 1: n >>= 1 t += 1 return t
bigcode/self-oss-instruct-sc2-concepts
import torch def flip_segment(X_spikes, segment): """ Flips the values of a segment in X_spikes format :param X_spikes: spiking input data from spike generator :param segment: segment in X_spikes to be flipped :return: spiking data with flipped segment """ _, (d, t_start, t_end) = segment ...
bigcode/self-oss-instruct-sc2-concepts
def valueFactory(zeroValue, elemValue): """ Return elemValue converted to a value of the same type as zeroValue. If zeroValue is a sequence, return a sequence of the same type and length, with each element set to elemValue. """ val = zeroValue typ = type(val) try: # If the type i...
bigcode/self-oss-instruct-sc2-concepts
def tts_version(version): """Convert a version string to something the TTS will pronounce correctly. Args: version (str): The version string, e.g. '1.1.2' Returns: str: A pronounceable version string, e.g. '1 point 1 point 2' """ return version.replace('.', ' point ')
bigcode/self-oss-instruct-sc2-concepts
def to_sec(d=0, h=0, m=0, s=0): """Convert Day, Hour, minute, seconds to number of seconds.""" secs = d*86400 secs += h*3600 secs += m*60 secs += s return secs ##################
bigcode/self-oss-instruct-sc2-concepts
def alpha_for_N(comps,Influx=10,Outflux=1000): """calculates alpha based on required outflux for given influx""" c=(Outflux/Influx)**(1/float(comps)) alpha_sol= (c-2)/(c-1) return alpha_sol
bigcode/self-oss-instruct-sc2-concepts
def _created_on_to_timestamp_ms(created_on): """ Converts the Message CreatedOn column to a millisecond timestamp value. CreatedOn is number of 100 nanosecond increments since midnight 0000-01-01. Output is number of millisecond increments since midnight 1970-01-01. """ return created_on / 1000...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def left(lst: List[int], idx: int) -> int: """Return left heap child.""" left_idx = idx * 2 + 1 if left_idx < len(lst): return left_idx else: return -1
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def outputSPDX(doc, spdxPath): """ Write SPDX doc, package and files content to disk. Arguments: - doc: BuilderDocument - spdxPath: path to write SPDX content Returns: True on success, False on error. """ try: with open(spdxPath, 'w') as f...
bigcode/self-oss-instruct-sc2-concepts
def write_nonequilibrium_trajectory(nonequilibrium_trajectory, trajectory_filename): """ Write the results of a nonequilibrium switching trajectory to a file. The trajectory is written to an mdtraj hdf5 file. Parameters ---------- nonequilibrium_trajectory : md.Trajectory The trajectory...
bigcode/self-oss-instruct-sc2-concepts
import random def random_IP() -> str: """ Get random IP """ ip = [] for _ in range(0, 4): ip.append(str(random.randint(1, 255))) return ".".join(ip)
bigcode/self-oss-instruct-sc2-concepts
import hashlib def compute_checksum(path, algorithm: str) -> str: """ Generates a hex digest using specified algorithm for a file. """ buffer_size = 65536 hash_builder = hashlib.new(algorithm) with open(path, 'rb') as f: while True: data = f.read(buffer_size) if not d...
bigcode/self-oss-instruct-sc2-concepts
def rev_bit_str(n: int, bitlen: int) -> int: """ Reverses the bitstring of length bitlen of a number n and returns the bitreverses integer. I.e. rev_bits(3, 4) => "0011" => "1100" => 12 """ bits = bin(n)[2:] # Truncate first 2 characters to avoid '0b' start_pow = bitlen - len(bits) return s...
bigcode/self-oss-instruct-sc2-concepts
def pattern_count(pattern, text): """ The number of times that a pattern appears as a substring of text. Args: pattern (str): the substring pattern to find in the given text. text (str): the string space for looking. Returns: String, number of substring pattern that appears in ...
bigcode/self-oss-instruct-sc2-concepts
def sort_seconds(timestamps): """ Sorts a list of 2-tuples by their first element """ return sorted(timestamps, key=lambda tup: tup[0])
bigcode/self-oss-instruct-sc2-concepts