seed stringlengths 1 14k | source stringclasses 2
values |
|---|---|
def mmedian(lst):
"""
get the median value
"""
sortedLst = sorted(lst)
lstLen = len(lst)
if lstLen==0:
return 0.0
index = (lstLen - 1) // 2
if (lstLen % 2):
return sortedLst[index]
else:
return (sortedLst[index] + sortedLst[index + 1])/2.0 | bigcode/self-oss-instruct-sc2-concepts |
def _format_spreadsheet_headers(token):
"""
Return formatted authorization headers for further
interactions with spreadsheet api.
"""
return {
"Authorization": f"Bearer {token}"
} | bigcode/self-oss-instruct-sc2-concepts |
import re
def getFilename(name):
"""Get a filename from given name without dangerous or incompatible
characters."""
# first replace all illegal chars
name = re.sub(r"[^0-9a-zA-Z_\-\.]", "_", name)
# then remove double dots and underscores
while ".." in name:
name = name.replace('..', '... | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def _get_old_file(new_file: Path) -> Path:
"""Return the same file without the .new suffix"""
assert new_file.name.endswith('.new') # noqa
return new_file.with_name(new_file.stem) | bigcode/self-oss-instruct-sc2-concepts |
def xor_fixed_buffers(buf1, buf2):
"""
Creates XOR buffered string from two hex string buffers
:param buf1: hex encoded string
:param buf2: hex encoded string
:return: xor hex encoded string
"""
# Convert hex to bytearray
decoded_hex_buf1 = bytearray.fromhex(buf1)
decoded_hex_buf2 =... | bigcode/self-oss-instruct-sc2-concepts |
def previous(some_list, current_index):
"""
Returns the previous element of the list using the current
index if it exists. Otherwise returns an empty string.
"""
try:
return some_list[int(current_index) - 1] # access the previous element
except:
return '' | bigcode/self-oss-instruct-sc2-concepts |
def get_truck(client, truck_id):
"""
returns the truck specified.
:param client: The test client to make the request with
:param truck_id: The id of the truck to find
:return: truck with id=id
"""
return client.get(f'/api/trucks/{truck_id}') | bigcode/self-oss-instruct-sc2-concepts |
def ros_service_response_cmd(service, result, _id=None, values=None):
"""
create a rosbridge service_response command object
a response to a ROS service call
:param service: name of the service that was called
:param result: boolean return value of service callback. True means success, False failu... | bigcode/self-oss-instruct-sc2-concepts |
def escapeAttrJavaScriptStringDQ(sText):
""" Escapes a javascript string that is to be emitted between double quotes. """
if '"' not in sText:
chMin = min(sText);
if ord(chMin) >= 0x20:
return sText;
sRet = '';
for ch in sText:
if ch == '"':
sRet += '\\"'... | bigcode/self-oss-instruct-sc2-concepts |
def center_scale_to_corners(yx, hw):
"""Convert bounding boxes from "center+scale" form to "corners" form"""
hw_half = 0.5 * hw
p0 = yx - hw_half
p1 = yx + hw_half
return p0, p1 | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
def get_error_message(traceback: str) -> Union[str, None]:
"""Extracts the error message from the traceback.
If no error message is found, will return None.
Here's an example:
input:
Traceback (most recent call last):
File "example_code.py", line 2, in <module>
... | bigcode/self-oss-instruct-sc2-concepts |
def read(filepath, readfunc, treant):
"""Read data from a treant
Args:
filepath: the filepath to read from
readfunc: the read callback
treant: the treant to read from
Returns:
the data
"""
return readfunc(treant[filepath].abspath) | bigcode/self-oss-instruct-sc2-concepts |
import re
def is_project_issue(text):
"""
Issues/pull requests from Apache projects in Jira.
See: https://issues.apache.org/jira/secure/BrowseProjects.jspa#all
>>> is_project_issue('thrift-3615')
True
>>> is_project_issue('sling-5511')
True
>>> is_project_issue('sling')
False
... | bigcode/self-oss-instruct-sc2-concepts |
def read_input(fpath):
"""
Read the global input file.
Args:
fpath (str): Path to the input file to read.
Returns:
list
"""
with open(fpath, 'r') as f:
return [line.strip() for line in f.readlines()] | bigcode/self-oss-instruct-sc2-concepts |
def _cell_fracs_sort_vol_frac_reverse(cell_fracs):
"""
Sort cell_fracs according to the order of increasing idx and decreasing
with vol_frac.
Parameters
----------
cell_fracs : structured array
The output from dagmc.discretize_geom(). A sorted, one dimensional
array, eac... | bigcode/self-oss-instruct-sc2-concepts |
import math
def fromSpherical(r, theta, phi):
""" convert spherical coordinates to 3-d cartesian coordinates """
return r*math.sin(theta)*math.cos(phi), r*math.sin(theta)*math.sin(phi), r*math.cos(theta) | bigcode/self-oss-instruct-sc2-concepts |
import torch
def cross_product_matrix(v):
"""skew symmetric form of cross-product matrix
Args:
v: tensor of shape `[...,3]`
Returns:
The skew symmetric form `[...,3,3]`
"""
v0 = v[..., 0]
v1 = v[..., 1]
v2 = v[..., 2]
zero = torch.zeros_like(v0)
mat = torch.stack([... | bigcode/self-oss-instruct-sc2-concepts |
def is_generator(iterable):
"""
Check if an iterable is a generator.
Args:
iterable: Iterable.
Returns:
boolean
"""
return hasattr(iterable, '__iter__') and not hasattr(iterable, '__len__') | bigcode/self-oss-instruct-sc2-concepts |
import inspect
def caller(n=1):
"""Return the name of the calling function n levels up in the frame stack.
>>> caller(0)
'caller'
>>> def f():
... return caller()
>>> f()
'f'
"""
return inspect.getouterframes(inspect.currentframe())[n][3] | bigcode/self-oss-instruct-sc2-concepts |
import collections
def parse_result_ranks(stream):
"""Reads a results stream: one line per item, expected format:
``qid, iter, docno, rank, sim, run_id``.
The output data structure is a dict indexed by (tid, docno)
and the values are ranks.
"""
ranks = collections.defaultdict(int)
for i, ... | bigcode/self-oss-instruct-sc2-concepts |
def getFormURL(form_id):
""" Return a form URL based on form_id
"""
return 'https://docs.google.com/forms/d/%s/viewform' % (form_id, ) | bigcode/self-oss-instruct-sc2-concepts |
import unicodedata
def to_ascii(s):
"""
Translates the string or bytes input into an ascii string with the
accents stripped off.
"""
if isinstance(s, bytes):
s = s.decode('utf-8')
return ''.join((c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn')) | bigcode/self-oss-instruct-sc2-concepts |
import torch
def rejoin_props(datasets):
"""
Rejoin properties from datasets into one dictionary of
properties.
Args:
datasets (list): list of smaller datasets
Returns:
new_props (dict): combined properties
"""
new_props = {}
for dataset in datasets:
for key, va... | bigcode/self-oss-instruct-sc2-concepts |
def _l_str_ ( self ) :
"""Self-printout of line: (point, direction)
>>> line = ...
>>> print line
"""
return "Line3D(%s,%s)" % ( self.beginPoint() , self.direction() ) | bigcode/self-oss-instruct-sc2-concepts |
def get_mesh_texture(bsp, mesh_index: int) -> str:
"""Returns the name of the .vmt applied to bsp.MESHES[mesh_index]"""
mesh = bsp.MESHES[mesh_index]
material_sort = bsp.MATERIAL_SORT[mesh.material_sort]
texture_data = bsp.TEXTURE_DATA[material_sort.texture_data]
return bsp.TEXTURE_DATA_STRING_DATA[... | bigcode/self-oss-instruct-sc2-concepts |
def verify_askingto_by_verify_y(actor, x, y, ctxt) :
"""Updates the actor for y to x and then verifies that action."""
y.update_actor(x)
return ctxt.actionsystem.verify_action(y, ctxt) | bigcode/self-oss-instruct-sc2-concepts |
def create_document(bookmark):
"""Creates a Document (a dict) for the search engine"""
return {
"id": str(bookmark.id),
"title": bookmark.title or "",
"notes": bookmark.notes or "",
"tags": ", ".join([tag.name for tag in bookmark.tags]),
} | bigcode/self-oss-instruct-sc2-concepts |
def bytes_find_single(x: bytes, sub: int, start: int, end: int) -> int:
"""Where is the first location of a specified byte within a given slice of a bytes object?
Compiling bytes.find compiles this function, when sub is an integer 0 to 255.
This function is only intended to be executed in this compiled for... | bigcode/self-oss-instruct-sc2-concepts |
import csv
def get_data_X_y(data_dir, X=[], y=[]):
"""Read the log file and turn it into X/y pairs."""
with open(data_dir + 'driving_log.csv') as fin:
next(fin)
log = list(csv.reader(fin))
for row in log:
if float(row[6]) < 20: continue # throw away low-speed samples
X +=... | bigcode/self-oss-instruct-sc2-concepts |
def sigfig(number, places):
"""
Round `number` to `places` significant digits.
Parameters:
number (int or float): A number to round.
places (int): The number of places to round to.
Returns:
A number
"""
# Passing a negative int to round() gives us a sigfig determinatio... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def read_time_stamp (out):
"""Reads timestamp from a file provided. Format: time.time()"""
st_hd = open(out, 'r')
st = st_hd.read()
st_hd.close()
stamp = datetime.fromtimestamp(float(st)).strftime('%Y-%m-%d %H:%M:%S')
return(stamp) | bigcode/self-oss-instruct-sc2-concepts |
import json
def load_characters(path_to_backup):
"""
Characters are saved in a json file.
Read and return the saved content
as a Python dict.
"""
with open(path_to_backup, 'r') as content:
try:
return json.loads(content.read())
except json.JSONDecodeError:
... | bigcode/self-oss-instruct-sc2-concepts |
import hashlib
def file_hash(filename):
"""
Hash the contents of the specified file using SHA-256 and return the hash
as a string.
@param filename The filename to hash the contents of
@return String representing the SHA-256 hash of the file contents
"""
hasher = hashlib.sha256()
with... | bigcode/self-oss-instruct-sc2-concepts |
def unionRect(rect1, rect2):
"""Return the smallest rectangle in which both input rectangles are fully
enclosed. In other words, return the total bounding rectangle of both input
rectangles.
"""
(xMin1, yMin1, xMax1, yMax1) = rect1
(xMin2, yMin2, xMax2, yMax2) = rect2
xMin, yMin, xMax, yMax ... | bigcode/self-oss-instruct-sc2-concepts |
def build_synthethic_iid_datasets(client_data, client_dataset_size):
"""Constructs an iterable of IID clients from a `tf.data.Dataset`.
The returned iterator yields a stream of `tf.data.Datsets` that approximates
the true statistical IID setting with the entirety of `client_data`
representing the global distri... | bigcode/self-oss-instruct-sc2-concepts |
def is_int(s: str) -> bool:
"""Test if string is int
Args:
s (str): Input String
Returns:
bool: result of test
"""
try:
int(s)
return True
except ValueError:
return False | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def _new_file(file: Path) -> Path:
"""Return the same file path with a .new additional extension."""
return file.with_suffix(f"{file.suffix}.new") | bigcode/self-oss-instruct-sc2-concepts |
def get_users_preferred_timezone(user, service):
"""
Determines the users preferred timezone by checking what timezone they use for their primary google calendar
:param user: Django User object for the user whose calendar is being accessed
:return: A string representation of the timezone:
- "E... | bigcode/self-oss-instruct-sc2-concepts |
def split_string(command:str, character:str):
"""
Split incoming command on a character
args:
command: string that's the command.
character: the character on which the command should be split.
Returns:
Array with at least length 2 containing the split command.
"""
... | bigcode/self-oss-instruct-sc2-concepts |
def offset_stopword(rank, nb_lemmas_in_stopwords):
"""Offset word frequency rankings by a small amount to take into account the missing ranks from ignored stopwords"""
return max(1, rank - nb_lemmas_in_stopwords) | bigcode/self-oss-instruct-sc2-concepts |
def compute_loss(criterion, outputs, labels, batch_size):
"""
Helper function to compute the loss. Since this is a pixel-wise
prediction task we need to reshape the output and ground truth
tensors into a 2D tensor before passing it in to the loss criterion.
Args:
criterion: pytorch loss criter... | bigcode/self-oss-instruct-sc2-concepts |
def poly_smooth(x: float, n: float = 3) -> float:
"""Polynomial easing of a variable in range [0, 1].
Args:
x (float): variable to be smoothed
n (float, optional): polynomial degree. Defaults to 3.
Returns:
float: _description_
"""
if x > 1:
return 1
if x < 0:
... | bigcode/self-oss-instruct-sc2-concepts |
import re
def del_tokens_len_one(text: str) -> str:
"""Delete tokens with length = 1.
This is kind of a basic stopword filtering.
"""
text = re.sub('(\s)\w(\s)',' ',text)
return text | bigcode/self-oss-instruct-sc2-concepts |
from typing import Callable
from typing import Iterable
from typing import Tuple
from typing import List
def split(predicate: Callable, iterable: Iterable) -> Tuple[List, List]:
"""
Splits the iterable into two list depending on the result of predicate.
Parameters
----------
predicate: Callable
... | bigcode/self-oss-instruct-sc2-concepts |
from typing import List
def _entity_report(entity_name: str, messages: List[str]) -> List[str]:
""" Serializes the messages of a given entity to the Report
It generates a list that translates as:
+ entity
+ message one
+ message two"""
return [f' + {entity_name}'] + [f' + {message}'... | bigcode/self-oss-instruct-sc2-concepts |
def make_preterminal(label, word):
"""returns a preterminal node with label for word"""
return [label, word] | bigcode/self-oss-instruct-sc2-concepts |
def isVariable(name, dataset):
"""
Determines if given string is an existing variable name for a variable in dataset.
This helper function returns True if the given name is a valid name of a variable
in the Tecplot file, False otherwise.
Arguments:
name -- the string that we are testin... | bigcode/self-oss-instruct-sc2-concepts |
def fgrep(text, term, window=25, with_idx=False, reverse=False):
"""Search a string for a given term. If found, print it with some context.
Similar to `grep -C 1 term text`. `fgrep` is short for faux grep.
Parameters
----------
text: str
Text to search.
term: str
Term to look fo... | bigcode/self-oss-instruct-sc2-concepts |
import re
def fix_gitlab_links(base_url, text):
"""
Fixes gitlab upload links that are relative and makes them absolute
"""
matches = re.findall('(\[[^]]*\]\s*\((/[^)]+)\))', text)
for (replace_string, link) in matches:
new_string = replace_string.replace(link, base_url + link)
t... | bigcode/self-oss-instruct-sc2-concepts |
def get_objlist(*, galaxy_catalog, survey, star_catalog=None, noise=None):
"""
get the objlist and shifts, possibly combining the galaxy catalog
with a star catalog
Parameters
----------
galaxy_catalog: catalog
e.g. WLDeblendGalaxyCatalog
survey: descwl Survey
For the approp... | bigcode/self-oss-instruct-sc2-concepts |
import re
def clean_newline(text: str) -> str:
"""Filter newlines.
Arguments:
text:
The text to be filtered.
Returns:
The filtered text.
"""
return re.sub("\n", "", text) | bigcode/self-oss-instruct-sc2-concepts |
import copy
def thrift_to_dict(thrift_inst, update_func=None):
"""convert thrift instance into a dict in strings
:param thrift_inst: a thrift instance
:param update_func: transformation function to update dict value of
thrift object. It is optional.
:return dict: dict with at... | bigcode/self-oss-instruct-sc2-concepts |
def sum_reduce(iter, params):
"""
Sums the values for each key.
This is a convenience function for performing a basic sum in the reduce.
"""
buf = {}
for key, value in iter:
buf[key] = buf.get(key, 0) + value
return buf.items() | bigcode/self-oss-instruct-sc2-concepts |
def _totalUniqueWords(dataset, index):
"""
Given a dataset, compute the total number of unique words at the given index.
GIVEN:
dataset (list) list of lists, where each sublist is a document
index (int) index in dataset to count unique words
RETURN:
unique_words (int... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import List
def get_parents(class_name: str, parent_mapping: Dict[str, List[str]]) -> List[str]:
"""
Recursively resolve all parents (ancestry) of class_name
:param class_name: class to resolve
:param parent_mapping: mapping of class_name -> parents
:return: Lis... | bigcode/self-oss-instruct-sc2-concepts |
import re
def matching(value, pattern, casesensitive=True):
"""
Filter that performs a regex match
:param value: Input source
:type value: str
:param pattern: Regex Pattern to be matched
:return: True if matches. False otherwise
:rtype: bool
"""
flags = re.I if not casesensitive e... | bigcode/self-oss-instruct-sc2-concepts |
def collate_fn(batch):
"""Pack batch"""
return tuple(batch) | bigcode/self-oss-instruct-sc2-concepts |
import six
def get_members(group):
"""Get a list of member resources managed by the specified group.
Sort the list of instances first by created_time then by name.
"""
resources = []
if group.nested():
resources = [r for r in six.itervalues(group.nested())
if r.status... | bigcode/self-oss-instruct-sc2-concepts |
def get_albums(tracks):
"""
Returns a dict where:
key: album_id
value: list of track ids
"""
albums = {}
for _,row in tracks.iterrows():
album = row['album'][1:-1]
if album != '' and album != 'None':
if album in albums:
albums[a... | bigcode/self-oss-instruct-sc2-concepts |
import re
def has_spdx_text_in_analysed_file(scanned_file_content):
"""Returns true if the file analysed by ScanCode contains SPDX identifier."""
return bool(re.findall("SPDX-License-Identifier:?", scanned_file_content)) | bigcode/self-oss-instruct-sc2-concepts |
def clamp_tensor(tensor, minimum, maximum):
"""
Supports sparse and dense tensors.
Returns a tensor with values clamped between the provided minimum and maximum,
without modifying the original tensor.
"""
if tensor.is_sparse:
coalesced_tensor = tensor.coalesce()
coalesced_tensor... | bigcode/self-oss-instruct-sc2-concepts |
def extract_picard_stats(path):
"""
Extract relevant information from picard wgs or size stats file.
This is assumed to be for a single sample and that there will only be
two lines in the "METRICS CLASS" section, which is the only section we'll
extract.
No effort is made to convert strings to nu... | bigcode/self-oss-instruct-sc2-concepts |
def canAcceptVassal(masterTeam, vassalTeam, bAtWar):
"""
Returns True if <vassalTeam> can become a vassal of <masterTeam>.
Pass True for <bAtWar> to test for capitulation and False to test for peaceful vassalage.
"""
if masterTeam.getID() == vassalTeam.getID():
return False
if masterTeam.isAVassal() or vassal... | bigcode/self-oss-instruct-sc2-concepts |
def unpack_bytes(word):
"""Unpacks a 32 bit word into 4 signed byte length values."""
def as_8bit_signed(val):
val = val & 0xff
return val if val < 128 else val - 256
return (as_8bit_signed(word),
as_8bit_signed(word >> 8),
as_8bit_signed(word >> 16),
as_8... | bigcode/self-oss-instruct-sc2-concepts |
def lowerBound(sortedCollection, item, key=lambda x: x):
"""
Given a sorted collection, perform binary search to find element x for which
the following holds: item > key(x) and the value key(x) is the largest.
Returns index of such an element.
"""
lo = 0
hi = len(sortedCollection)
while ... | bigcode/self-oss-instruct-sc2-concepts |
def gt_pseudophase(g):
"""
Return pseudophased genotype call.
Parameters
----------
g : str
Genotype call.
Returns
-------
str
Pseudophased genotype call.
Examples
--------
>>> from fuc import pyvcf
>>> pyvcf.pseudophase('0/1')
'0|1'
>>> pyvcf.... | bigcode/self-oss-instruct-sc2-concepts |
def get_users(user_file_path):
"""read usernames from file."""
user_file = open(user_file_path)
users = user_file.readlines()
user_file.close()
return users | bigcode/self-oss-instruct-sc2-concepts |
def transform( event, settings ):
"""
Takes a pipeline event and transforms it to pipeline event containing
an array of payloads
"""
adapters = settings.adapters()
payloads = []
for index in range( 0, len( adapters ) ):
outputter = settings.outputters[ index ]
if not output... | bigcode/self-oss-instruct-sc2-concepts |
def _strip_predicate(s):
"""Remove quotes and _rel suffix from predicate *s*"""
if s.startswith('"') and s.endswith('"'):
s = s[1:-1]
elif s.startswith("'"):
s = s[1:]
if s[-4:].lower() == '_rel':
s = s[:-4]
return s | bigcode/self-oss-instruct-sc2-concepts |
import math
def cosine_annealing_lr(
iteration: int,
num_iterations: int,
initial_lr: float,
final_lr: float,
):
"""
Cosine annealing NO restarts
Args:
iteration: current iteration
num_iterations: total number of iterations of coine lr
initial_lr: learning rate to ... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Union
def expand_fine_modality_questions(
answer: str, matched_word: str, modality: Union[None, str]
):
"""Create new questions for fine modality task with given information.
Args:
answer: Original answer to the question
matched_word: The keyword which labeled the origi... | bigcode/self-oss-instruct-sc2-concepts |
def _parse_volumes_param(volumes):
"""Parse volumes details for Docker containers from blueprint
Takes in a list of dicts that contains Docker volume info and
transforms them into docker-py compliant (unflattened) data structures.
Look for the `volumes` parameters under the `run` method on
[this pa... | bigcode/self-oss-instruct-sc2-concepts |
from typing import Dict
from typing import Optional
def role_has_tag(role: Dict, key: str, value: Optional[str] = None) -> bool:
"""
Checks a role dictionary and determine of the role has the specified tag. If `value` is passed,
This function will only return true if the tag's value matches the `value` va... | bigcode/self-oss-instruct-sc2-concepts |
def get_datasets(datasets=''):
"""Gets the list of dataset names.
Args:
datasets: A string of comma separated dataset names.
Returns:
A list of dataset names.
"""
return [d.strip() for d in datasets.split(',')] | bigcode/self-oss-instruct-sc2-concepts |
import functools
def synchronized(obj):
"""
This function has two purposes:
1. Decorate a function that automatically synchronizes access to the object
passed as the first argument (usually `self`, for member methods)
2. Synchronize access to the object, used in a `with`-statement.
Note that you can ... | bigcode/self-oss-instruct-sc2-concepts |
import logging
def _set_root_logger(loglevel=logging.INFO):
""" Setup the root logger.
Parameters
----------
loglevel: int, optional
The log level to set the root logger to. Default :attr:`logging.INFO`
Returns
-------
:class:`logging.Logger`
The root logger for Faceswap
... | bigcode/self-oss-instruct-sc2-concepts |
def _recurse_binary_exponentiation(num, power):
"""
Recursively calculate num**power quickly (via binary exponentiation).
Helper function. We did parameter checks before so that we don't have to
do them inside every recursive call.
"""
if power == 1:
return num
num_squared = n... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def today(tz=None) -> datetime:
"""get datetime of today (no time info)"""
now = datetime.now(tz)
return datetime(year=now.year, month=now.month, day=now.day) | bigcode/self-oss-instruct-sc2-concepts |
def _GetGetRequest(client, health_check_ref):
"""Returns a request for fetching the existing health check."""
return (client.apitools_client.healthChecks, 'Get',
client.messages.ComputeHealthChecksGetRequest(
healthCheck=health_check_ref.Name(),
project=health_check_ref.project... | bigcode/self-oss-instruct-sc2-concepts |
import six
def exact_filter(query, model, filters):
"""Applies exact match filtering to a query.
Returns the updated query. Modifies filters argument to remove
filters consumed.
:param query: query to apply filters to
:param model: model object the query applies to, for IN-style
... | bigcode/self-oss-instruct-sc2-concepts |
def filter_dose_by_individual_species(doses, species):
"""Filter out relevent doses by the species name
If it does find doses with the specific species name, it returns a list of these.
If it doesn't find any doses with the specific species name, it returns None.
:param doses: A list of dose objects
... | bigcode/self-oss-instruct-sc2-concepts |
def check_bit(val, n):
""" Returns the value of the n-th (0 index) bit in given number """
try:
if val & 2**n:
return 1
else:
return 0
except TypeError:
return -1 | bigcode/self-oss-instruct-sc2-concepts |
def getAccurateFocalLengths(imageSize, focalLength, sensorSize):
"""
Parameters: image size x,y (pixels), focalLength (mili meters), sensorSize x,y (meters)
Focal length listed on the image exif is unitless...
We need focal length in pixels / meters.
Therefore, we scale the exif focal length b... | bigcode/self-oss-instruct-sc2-concepts |
import base64
def base_64_encode(key, secret):
"""encodes key and secret in base 64 for the auth credential"""
conversion_string = "{}:{}".format(key, secret).encode('ascii')
auth_credential = base64.b64encode(conversion_string)
auth_credential = auth_credential.decode()
return auth_credential | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def get_or_create_path(path_string, parents=True):
""" Get path object from string, create if non-existing"""
p = Path(path_string)
if not p.exists():
p.mkdir(parents=parents)
return p | bigcode/self-oss-instruct-sc2-concepts |
def no_duplicates(seq):
""" Remove all duplicates from a sequence and preserve its order """
# source: https://www.peterbe.com/plog/uniqifiers-benchmark
# Author: Dave Kirby
# Order preserving
seen = set()
return [x for x in seq if x not in seen and not seen.add(x)] | bigcode/self-oss-instruct-sc2-concepts |
import secrets
def draft_conv_key() -> str:
"""
Create reference for a draft conversation.
"""
return secrets.token_hex(10) | bigcode/self-oss-instruct-sc2-concepts |
def _errmsg(argname, ltd, errmsgExtra=''):
"""Construct an error message.
argname, string, the argument name.
ltd, string, description of the legal types.
errmsgExtra, string, text to append to error mssage.
Returns: string, the error message.
"""
if errmsgExtra:
errmsgExtra = '\n' ... | bigcode/self-oss-instruct-sc2-concepts |
def replace_chars(string, chars=r':\/|<>?*"', replacement=''):
"""
Return `string` with any char in the `chars` replaced by `replacement`.
Defaults to replace problematic/invalid chars for filenames/paths.
"""
for c in string:
if c in chars:
string = string.replace(c, replacemen... | bigcode/self-oss-instruct-sc2-concepts |
import string
import secrets
def code_verifier(length: int = 128):
"""
Return a cryptographically random string as specified in RFC7636 section 4.1
See https://datatracker.ietf.org/doc/html/rfc7636#section-4.1
:param length:
length of the generated string, minimum 43, maximum 128. Defaults t... | bigcode/self-oss-instruct-sc2-concepts |
def crop(image, rectangle):
"""
Crop out input image's fragment specified by the rectangle.
:param image: input image
:param rectangle: rectangle, which indicates cropped area
:return: cropped original image fragment
"""
x, y, w, h = rectangle
return image[y:y + h, x:x + w] | bigcode/self-oss-instruct-sc2-concepts |
def lookup_newsletter_recipients(resource):
"""
Callback function to look up the recipients corresponding to a
distribution list entry (in this instance: send all newsletters
to orgs)
Args:
the (filtered) resource
Returns:
a list of pe_ids of the rec... | bigcode/self-oss-instruct-sc2-concepts |
def lex_tokenize(tokenized_sentence):
"""Returns a list of lexes from a given tokenizer.TokenizedSentence instance. Each lex is represented as a 3-tuples of (start, end, token)."""
return [(lex.begin, lex.end, lex.text) for (token, lex) in tokenized_sentence.as_pairs()] | bigcode/self-oss-instruct-sc2-concepts |
def ensure_list(config):
"""
ensure_list
Ensure that config is a list of one-valued dictionaries. This is called
when the order of elements is important when loading the config file. (The
yaml elements MUST have hyphens '-' in front of them).
Returns config if no exception was raised. This... | bigcode/self-oss-instruct-sc2-concepts |
from datetime import datetime
def json_serial(obj):
"""JSON serializer for objects not serializable by default json code"""
# yyyy-MM-dd'T'HH:mm:ss.SSS strict_date_hour_minute_second_millis
if isinstance(obj, datetime):
tz_string = "Z"
serial = "%s.%03d" % (
obj.strftime("%Y... | bigcode/self-oss-instruct-sc2-concepts |
def generate_source(email):
"""Generate a source code to be used in links inside an email"""
return u"ev_{date}_{uuid}".format(
date=email.created_at.strftime('%Y%m%d'),
uuid=email.uuid) | bigcode/self-oss-instruct-sc2-concepts |
from pathlib import Path
def make_save_path(save_path, net_name, net_number, epochs):
"""make a unique save path for model and checkpoints,
using network architecture, training replicate number, and number of epochs"""
save_path = Path(save_path).joinpath(
f'trained_{epochs}_epochs',
f'ne... | bigcode/self-oss-instruct-sc2-concepts |
def alter_board(board, player, cell):
"""Alter board string for player input"""
board = list(board)
# enter player letter in supplied cell
board[cell - 1] = player
return ''.join(board) | bigcode/self-oss-instruct-sc2-concepts |
import torch
def cov(m, rowvar=False):
"""Estimate a covariance matrix given data.
Covariance indicates the level to which two variables vary together.
If we examine N-dimensional samples, `X = [x_1, x_2, ... x_N]^T`,
then the covariance matrix element `C_{ij}` is the covariance of
`x_i` and `x_j... | bigcode/self-oss-instruct-sc2-concepts |
def process_notebook_name(notebook_name: str) -> str:
"""Processes notebook name
:param notebook_name: Notebook name by default keeps convention:
[3 digit]-name-with-dashes-with-output.rst,
example: 001-hello-world-with-output.rst
:type notebook_name: str
:returns: Processed notebook na... | bigcode/self-oss-instruct-sc2-concepts |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.