content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def rfcspace(string):
"""
If the string is an RFC designation, and doesn't have
a space between 'RFC' and the rfc-number, a space is
added
"""
string = str(string)
if string[:3].lower() == "rfc" and string[3] != " ":
return string[:3].upper() + " " + string[3:]
else:
retu... | 667f159f5c2a3103db89729ec986735c4849fc02 | 628,707 |
def extract_header(filename: str):
""" Extract the header of a Deltamed .eeg file.
Args:
filename: path to the .eeg file.
Returns:
A list of bytes
"""
header = []
with open(filename, 'rb') as file_:
header = [
char if isinstance(char, bytes) else bytes([char... | 7c9fe634ccf4474054c1b58c467da6a87f28eab8 | 628,713 |
def named(values, names):
"""Creates a dict with `names` as fields, and `values` as values."""
return dict(zip(names.split(), values)) | 67f7eb9c22cd74594137aaed390006ca73d48736 | 628,719 |
def get_majority_vote(a):
"""
Returns the majority vote element of a list
"""
return max(map(lambda val: (a.count(val), val), set(a)))[1] | 95bab122350813aaafc6965a6dcf14c87483701e | 628,721 |
def hasQueryMatch(qList, tweetJSON):
"""Returns true if a tweet containing any keyword in QUERY_KEYWORDS is found"""
return any(keyword in tweetJSON['text'] for keyword in qList) | b0ff979b8c54f09450749ef134c7b9deabe7a231 | 628,722 |
import torch
def get_window(name, window_length, squared=False):
"""
Returns a windowing function.
Arguments:
window (str): name of the window, currently only 'hann' is available
window_length (int): length of the window
squared (bool): if true, square the window
Returns:
... | f5cca82ae8983f0297fac601bc563d6f89d6af6e | 628,724 |
import math
def binom(n, k):
"""
Compute a binomial coefficient (n choose k).
Parameters
----------
n, k : int
Positive integers.
Returns
-------
int
"""
# could be replace by math.comb(n, k) in Python >= 3.8
try:
return math.factorial(n) // ma... | 3a5af73134a2cc1b746d48e5a210af07b66f4a5c | 628,727 |
def get_kinds_section(structure, protocol_settings):
""" Write the &KIND sections given the structure and the settings_dict"""
kinds = []
all_atoms = set(structure.get_ase().get_chemical_symbols())
for atom in all_atoms:
kinds.append({
'_': atom,
'BASIS_SET': protocol_set... | eec6280712b01bdeb09006b5e914acfa11256795 | 628,728 |
def sanitizeContents(contents:str) -> str:
"""
Sanitizes the input `contents` string to be a well-behaved config file.
"""
out = []
for line in contents.splitlines():
tmp=(" ".join(line.split())).strip() #squeezes spaces and trims leading and trailing spaces
tmp=tmp.replace("&", '&') #decodes HTML-encoded ... | 9f407af1f1d46fb9f50a79c84a4040a7a1305646 | 628,729 |
def add_metadata_defaults(md):
"""Central location for defaults for algorithm inputs.
"""
defaults = {"batch": None,
"phenotype": ""}
for k, v in defaults.items():
if k not in md:
md[k] = v
return md | ef612ae8a2d4bccfbb6955a9191aaed1239665f5 | 628,731 |
from typing import List
def parse_reqs(requirements_file: str) -> List[str]:
"""Get requirements as a list of strings from the file."""
with open(requirements_file) as reqs:
return [r for r in reqs if r] | bd9f8decddef9dc6c61ad9d837f18ea7bb45e1e3 | 628,734 |
def _mean_int(*args):
"""Return the mean of the supplied values."""
return int(sum(args) / len(args)) | e3809221fb93d0424f540113adffa4942de63cfe | 628,735 |
def payload_2(kernels, time_2, output_time_format, output_time_custom_format):
"""Payload from WGC API example 2."""
return {
"kernels": [{
"type": "KERNEL_SET",
"id": kernels,
}],
"times": [
time_2,
],
"calculationType": "TIME_CONVERSI... | 94df462a9c31347101eec66f12a4e84e25f10d28 | 628,737 |
def nodeKey(search, node, goal, heuristicFunc):
"""
Give sort key that prioritizes node based on search, where min key is higher priority.
This prioritization is essentially the difference between the various search algorithms.
"""
if search == 'A*':
g = node.cost;
h = heu... | 258b20beabf7ccf2fc89d44e8411187c2957034b | 628,738 |
def _has_surrogates(s):
"""Return True if s contains surrogate-escaped binary data."""
try:
s.encode()
return False
except UnicodeEncodeError:
return True | 19e6ef5bb3e71d37a3f9afa199f8b01aba96e3ef | 628,740 |
def format_indent_line(items, spaces, indent, backslash, is_last):
"""Returns elements separated by commas. The line can be indented. This function is for
internal use and is not available in templates.
:param list items: a list of items.
:param int spaces: indentation spaces
:param bool indent: in... | f8c2ff98286456a51982557471359826c300678c | 628,746 |
def tower_of_hanoi(
n: int = 1,
from_rod: str = 'A',
to_rod: str = 'B',
through_road: str = 'C'
) -> str:
"""
Solving the Hanoi Towers puzzle.
Returns a string with the sequence of disc changes from rod to rod in the format 'disk_number from_rod->to_rod'
If n < 0 it raise... | 7a97c01c775e0200a7d1e44bcd106e66276a5120 | 628,747 |
def parse_exts(extstr):
""" Parse a comma or space-separated list of file extensions. """
if not extstr:
return None
exts = []
for word in extstr.split():
exts.extend((s for s in word.split(',') if s))
return set((
s if s.startswith('.') else '.{}'.format(s)
for s in ... | 530e49ecfc3f7ee5600d3b11c08f4f9957d09087 | 628,757 |
import re
def get_prefixes_from_labels(labels):
"""Extracts a unique list of trigger prefixes from a dict of labels.
"""
regex = r'^SCALING_TRIGGER_[0-9]+_'
trigger_prefixes = set()
for k in labels:
match = re.match(regex, k)
if match is not None:
trigger_prefixes.add(m... | 661441d729d7acf87dfb925f31bf749f096bd70d | 628,758 |
def get_form_details(form):
"""
This function extracts all possible useful information about an HTML `form`
"""
details = {}
# get the form action (target url)
action = form.attrs.get("action").lower()
# get the form method (POST, GET, etc.)
method = form.attrs.get("method", "get").lower... | 3868f9edf07ea731cb2ce8e68be603dd7a9a936c | 628,759 |
def num_of_books_complete_message(tracker):
"""Return the number of books complete in a message string format."""
num_of_books_complete = tracker.shelf.num_complete_books
message = f"You have completed {num_of_books_complete} book"
message += "s" if num_of_books_complete != 1 else "" # Add plural
m... | 2ec18a8a161e73283034cb5dcf14dba0a705dd9f | 628,764 |
def extract_all_wiki_links(entry):
"""
Extract all wikipedia links associated to an entry
:param entry: entry data
:return:
"""
if "sitelinks" in entry:
return entry['sitelinks'] | 58760d1971c68d18880345f7c4999fd844c61fe7 | 628,766 |
def escape_attribute(value, encoding):
"""Escape an attribute value using the given encoding."""
if "&" in value:
value = value.replace("&", "&")
if "<" in value:
value = value.replace("<", "<")
if '"' in value:
value = value.replace('"', """)
return value.encode(... | 2a3ff495a5082e130b8a59af1bff82a4a4ca6430 | 628,768 |
def is_uc_alpha(astring):
"""
(str) -> Boolean
return True if any char in astring is an
uppercase letter.
else return False
>>> is_uc_alpha('CIS122')
True
>>> is_uc_alpha('Ducks')
True
>>> is_uc_alpha('testing')
False
"""
for c in astring:
if c.isupper():
... | 8a409d37cba7110e82b2fef08b8ffa735c868e66 | 628,770 |
def get_window_in_sec(s):
"""Returns number of seconds in a given duration or zero if it fails.
Supported durations are seconds (s), minutes (m), hours (h), and days(d)."""
seconds_per_unit = {"s": 1, "m": 60, "h": 3600, "d": 86400}
try:
return int(float(s[:-1])) * seconds_per_unit[s[-1]]
ex... | 099bdb21dc5745064e5942aae559ea1e2e03d62e | 628,773 |
def echo(event):
"""Echoes back the message it recieves."""
return ' '.join(event.args) | 55621b3f3d7fd362ef7ec11e6101e7abcb417b56 | 628,774 |
import random
def random_int(*, k_min: int = 1, k_max: int = 100000) -> int:
"""Generate a random integer."""
return random.randint(k_min, k_max) | c2542ed55a4a50eee238b09e589d4d9b77df57f2 | 628,783 |
def permutations(lst):
"""Lists all permutations of the given list.
>>> permutations(['angie', 'cat'])
[['angie', 'cat'], ['cat', 'angie']]
>>> permutations([1, 2, 3])
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
"""
if len(lst) <= 1:
return [lst]
total = [... | eb976e799ed1d0dce93572eab6466880d8a92543 | 628,785 |
def set_walls(rooms, walls):
"""
Sets the number of walls between every room
:param rooms: Dictionary of room objects
:param walls: nested list containing number of walls between each room
:return: the updated rooms dictionary
"""
# loop through all walls except the first row, since does not... | 7a09b919c65b5ad061b281cafb26c6289fbdba0b | 628,788 |
def coverage(g, c):
"""Evaluates the coverage of the clustering solution c on a given graph g."""
n = len(g.vs)
A_delta = 0
A = 0
for i in range(n):
for j in g.neighbors(i):
A += 1
if c[i] == c[j]:
A_delta += 1
return A_delta/A | 64a1dc3d4678bdf72c4c360f10316f4de117480f | 628,789 |
def bytesToMac(addr_bytes):
"""Convert byte sequence into MAC address
Byte sequence can comprise of both single character string elements, as
well as byte-encoded string elements, which is extracted as an int. So we
need to convert the character to its ordinal Unicode datapoint.
b'\\xac\\x84\\xc6\... | 14597fdbdd9d0e722907f8437b23826b15534066 | 628,790 |
def mni2tal(xin):
"""
mni2tal for converting from ch2/mni space to tal - very approximate.
This is a standard approach but it's not very accurate.
ANTsR function: `mni2tal`
Arguments
---------
xin : tuple
point in mni152 space.
Returns
-------
tuple
Example
-... | 585db96b55c511e58056ba727c07957ff4ce2e52 | 628,794 |
from typing import Set
def is_sum_of_numbers(number: int, numbers: Set[int]) -> bool:
"""Check if a given number `number` is the sum of any two numbers from `numbers`."""
for i in range(1, number):
if i in numbers and (number - i) in numbers:
return True
return False | 16cf2a7b2e6a5310a43d6e39fb5ecf1e93419f71 | 628,795 |
def safe_int(to_int: str) -> int:
"""Return int from str safely."""
try:
return int(to_int)
except ValueError:
return -1 | b5cf6a4af460b102a0c510542348f856c1329899 | 628,796 |
def parse_events(props):
"""
Pull out the dashEvents from the Component props
Parameters
----------
props: dict
Dictionary with {propName: propMetadata} structure
Returns
-------
list
List of Dash event strings
"""
if 'dashEvents' in props and props['dashEvents'... | f5cfb1b7feaa8833fecff47be2a3e9ba8128df54 | 628,797 |
def make_successive(xs):
"""
Return a list of successive combinations
Parameters
----------
xs : list
List of elements, e.g. [X, Y, Z]
Returns
-------
list
List of combinations where each combination include all the preceding elements
Examples
--------
>>> ... | 2a56ad0b5510a514c777b73ddd2507694e1469da | 628,798 |
def y2label(y_pred, int2tag, mask=0):
"""
Transforms numbers to the corresponding label
:param y_pred: list of lists of tag predictions as integers for each word in a sentence
:param int2tag: (dict) dictionary of integers to their corresponding tag
:param mask: (int) integer corresponding to '-PAD-'... | 4ec74c164c05a0198cd2c9bf15134c8c123dbe38 | 628,800 |
def set_custom_certs_enabled(
self,
enabled: bool,
) -> dict:
"""Enable or disable custom CA certificate trust store
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - customCerts
- POST
- /customCert/enable
... | 942e01fb4dead8166ec328b6e16451ba86e5beed | 628,802 |
def location_modifier(fields):
"""
Modify the parsed location variable.
Subtract 1 from all the start positions in order to be able to use pd.read_fwf()
Parameters:
field (list): The list of tuples created by location_parser()
Returns:
fields: A list of tuples
"""
for i, i... | a121a8d81c96e783c0868df54355d912f1e0ed35 | 628,803 |
def format_output(dets, w, h):
"""
:param dets: detection result input: x1, y1, x2, y2, score, cls_id
:param w: image's original width
:param h: image's original height
:return: list of items: cls_id, conf_score, center_x, center_y, bbox_w, bbox_h, [0, 1]
"""
if dets is None:
return... | 7880cb8e94b79056a3303106d45f094134d9b61e | 628,804 |
def snake_to_camel(name):
"""Converts Python Snake Case to Zscaler's lower camelCase."""
# Edge-cases where camelCase is breaking
edge_cases = {
"routable_ip": "routableIP",
"is_name_l10n_tag": "isNameL10nTag",
"name_l10n_tag": "nameL10nTag",
"surrogate_ip": "surrogateIP",
... | 99f89107e64135353c339f702b16b1113e7e0a1a | 628,805 |
def has_keys(data, keys):
"""
Checks whether a dictionary has all the given keys.
@type data: dict
@param data: Parameter name
@type keys: list
@param keys: list containing the expected keys to be found in the dict.
@rtype: bool
@return: True if all the keys are found in the dict, ... | eeac1caddc30e703cde22ce849707a05d12ef44c | 628,808 |
import string
def simple(s):
"""Break str `s` into a list of str.
1. `s` has all of its peripheral whitespace removed.
1. `s` is downcased with `lower`.
2. `s` is split on whitespace.
3. For each token, any peripheral punctuation on it is stripped
off. Punctuation is here defined by `strin... | 9065163ec57a3d733e900b7608341e98fc318f40 | 628,812 |
def _normalize_depth_vars(depth_k, depth_v, filters):
"""
Accepts depth_k and depth_v as either floats or integers
and normalizes them to integers.
Args:
depth_k: float or int.
depth_v: float or int.
filters: number of output filters.
Returns:
depth_k, depth_v as inte... | 27cc0635b3e5f3f8529ed20883a97efb03ee0c89 | 628,816 |
def add_comma_rs(_index, _value, _row_separator):
"""Adds a comma and row separator if index > 0, used in loops when making lists of references."""
if _index > 0:
return ',' + _row_separator + _value
else:
return _value
# Some database functions | 6a9b684ee95429e1034184654ef6bdcd9269113d | 628,818 |
def group_values_nearest(values, closest=2):
"""Group given values together under multiple buckets.
:param values: values to group
:type values: list
:param closest: closest is the maximun value difference between two values
in order to be considering in the same bucket, defaults to 2
:type clo... | c604ac0e9295da033c10afbc231e06b77a140a61 | 628,820 |
def combinations(seqs):
"""
Recipe 496807 from ActiveState Python CookBook
Non recursive technique for getting all possible combinations of a sequence
of sequences.
"""
r=[[]]
for x in seqs:
r = [ i + [y] for y in x for i in r ]
return r | 0c084b40105c284a29ad9ef189cfda60ce4088a1 | 628,821 |
def collect_content(parent_tag):
"""Collects all text from children p tags of parent_tag"""
content = ''
for tag in parent_tag:
p_tags = tag.find_all('p')
for tag in p_tags:
content += tag.text + '\n'
return content | 8ad73c3c6fc0e4e0fea0fac14485ba881508a881 | 628,822 |
def build_gameboard(term):
"""Build the gameboard layout."""
column, row = 0, 0
board = dict()
spacing = 2
for keycode in sorted(term._keycodes.values()):
if (keycode.startswith('KEY_F')
and keycode[-1].isdigit()
and int(keycode[len('KEY_F'):]) > 24):
... | d844ae414e11bbf895b42f62c4965b05009d108e | 628,825 |
def create_error_text(error_response: dict) -> str:
"""
Creates error text for Telegram Bot error response.
See https://core.telegram.org/bots/api/#making-requests
"""
description = error_response.get("description", "?")
error_code = error_response.get("error_code", "?")
return f"{error_cod... | d9e8b8002e5ce422c29bda85ed9a935ddf1ecf68 | 628,826 |
def extract_file_names(videos_path: str) -> list:
""" Extract filenames from .lst file.
Args:
videos_path (str): Path to .lst file.
Returns:
list: List of filenames.
"""
with open(videos_path, "r") as f:
file_names = [line.strip() for line in f.readlines()]
return file... | e27245dd80ffb668a4e47054805dbc56fee1c498 | 628,827 |
def byte_length(n):
"""Finds the byte length of an `int` object."""
return (n.bit_length() + 7) // 8 | 5d4b258d8c9bcccbdd4f0739458ce91cbd8825fa | 628,829 |
def changePlayer(player):
"""Returns the opposite player given any player"""
if player == "X":
return "O"
else:
return "X" | 118d4c7ad04c16edebb1c8b829462327cccc4235 | 628,830 |
def exp_to_int(s):
"""
Converts numbers like 1.01e+2 or 1.007783151912803607421e+21 to integers.
By default, these are parsed by the float function and lose precision
"""
if 'e' in s: #if it is exponential
exp = int(s.split('+')[1])
(whole, tmp) = s.split('.')
frac = tmp.split('e')[0]
assert(len(frac) <= e... | a7afed4d2a69d5380fee301d52887d4f0785477f | 628,838 |
def reduce_diff(diff):
"""remove the lines added for context and just keep the lines that show the actual differences """
new_diff = ""
for line in diff.splitlines():
if line[:2] in [" ", "? "]:
continue
new_diff += line + "\n"
return new_diff | e297728e9e6948a51c31ecf68f7031b8e2848012 | 628,839 |
def create_time_periods(connector, future_years):
"""
This function writes the time_periods table to an sqlite
database. Only "future" time periods will be written.
Parameters
----------
connector : sqlite3 connection object
An object for connecting to a specific SQLite
database... | a4175f8029427c772c0dc340f85fd52f504d3ee9 | 628,841 |
def merge_list(list1, list2, remove_duplicate=False):
"""
merge two lists
when remove_duplicate is false, duplicate item will be kept.
when remove_dupliate is true, no duplicate item is allowed
"""
merged_list = []
if not list1 and list2:
merged_list.extend(list2)
elif list1 and ... | a24183694c44e75be4d3f3946dab691c9c6ff734 | 628,847 |
def get_date_filter(report_config):
"""
Returns the first date filter, or None.
Assumes the first date filter is the one to use.
.. NOTE: The user might not want to filter by date for DHIS2
integration. They can use a "period" column to return
rows for multiple periods, or se... | c5c105334e96d90b3e6ecd322f69af240c5b7268 | 628,849 |
import pathlib
def join(*pthslist):
""" Returns the join of all paths"""
return str(pathlib.PurePath(*pthslist)) | a783d49670ba908d5331dfbabef008e957905ff2 | 628,853 |
import json
def question_pack(info="", userid="A0001", key="A0001"):
"""Package the question as the JSON format specified by the server.
将问题打包为服务器指定的json格式。
Args:
info: User question. 用户的聊天或提问。
Defaults to "".
userid: User id. 用户唯一标识。
Defaults to "userid".
Ret... | 2bec6ad486da250e91036130b8341397a1eb207c | 628,855 |
def _parsems(value):
"""Parse a I[.F] seconds value into (seconds, microseconds)."""
if "." not in value:
return int(value), 0
else:
i, f = value.split(".")
return int(i), int(f.ljust(6, "0")[:6]) | d444b18bb255a997b7c8a3e84e66a5842a1658b5 | 628,858 |
import ast
def parse_cwes(str1):
"""
Converts string to list.
"""
lst = ast.literal_eval(str1)
lst = [x.strip() for x in lst]
return lst | 01511481c4c86823143e4d24dea068cbe747d4cc | 628,859 |
def reader(fileaddress):
"""Reads the contents of a given file into an array"""
tied = []
with open(fileaddress, 'r') as ft:
for line in ft:
if(line[0]!="#"):
tied.append(line)
ft.close()
return tied | 30e36e49d7af69bff246af1c9cce5d7d7c4e6e95 | 628,864 |
def _expand_path(graph, source, step, visited, degrees):
"""Walk a path on a graph until reaching a tip or junction.
A path is a sequence of degree-2 nodes.
Parameters
----------
graph : NBGraph
A graph encoded identically to a SciPy sparse compressed sparse
row matrix. See the doc... | a79b838319b6314210a86f417554f6d354f22647 | 628,866 |
from typing import Callable
import importlib
def get_callable(function_string: str) -> Callable:
"""get_callable import a function based on its dot notation format as as string
:param function_string: the dot notation location of the function. (i.e. foo_module.bar_function)
:type function_string: str
... | d0e400dfc86d7782b03a94e94d9aedf4cb8447c8 | 628,868 |
from typing import Any
import pickle
def load_pickle(filename: str) -> Any:
"""Load object from pickle filename.
Args:
filename (string): The absolute path to the saved pickle.
Returns:
data (any): The loaded object.
"""
with open(filename, 'rb') as fp:
data = pickle.load... | 1bcbc2a70b51d0074fd4195bb32edc116e07d46d | 628,873 |
import requests
def get_all_weather_data(city="st. john's"):
"""
Helper function. Makes a request to openweathermap server.
:param city:
:return: Returns entire current weather for the city.
"""
base_url = "https://api.openweathermap.org/data/2.5/weather?"
api_key = "e3a3f627f93effe0dc13ea... | 60d64cd3df7b38e4db14380b06a5e86c1c2e3c7c | 628,875 |
def is_json(filename):
"""Predicate for checking if a filename is .json"""
return filename.lower().endswith(".json") | f638e18a0c5cc5ff4c425b1ba89ec0fe84b8db0e | 628,877 |
def new_sequence(num, sequence):
"""
:param num: int, allow users to input a number that is used to offset the original order in the sequence (ALPHABET).
:param sequence: str, the sequence (ALPHABET) that users want to shift the order.
:return: str, the new sequence (ALPHABET) with a new order.
"""
... | 09d63c0984a8b2325efde44debd6afdec352f444 | 628,880 |
from typing import Dict
from typing import Set
import collections
def load_qrels(path: str) -> Dict[str, Set[str]]:
"""Loads qrels into a dict of key: query_id, value: set of relevant doc ids."""
qrels = collections.defaultdict(set)
with open(path) as f:
for i, line in enumerate(f):
li... | 7d57310651e5b7d0f2b79b647d06faee905fb471 | 628,882 |
def get_gap_HS_data(modeling_data, gap_period, gap_station):
"""
Get original HS data in the gap period. Only winter values (Nov-Apr) will
be returned.
"""
y_true = (modeling_data
.loc[modeling_data['stn']==gap_station, 'HS']
.loc[gap_period]
)
y_true =... | 9ffadff48be31253ec3b8ca450b62304c2a1e032 | 628,884 |
import base64
def get_base64_encoded_image(image_path):
""" encode image to string for use in html later"""
with open(image_path, "rb") as img_file:
return base64.b64encode(img_file.read()).decode('utf-8') | 7a28e9ae010cb2412aaff71ce3a8f0eb9f60604e | 628,887 |
def agent_ids(cur, archetype):
"""Gets all agentids from Agententry table for wanted archetype
agententry table has the following format:
SimId / AgentId / Kind / Spec /
Prototype / ParentID / Lifetime / EnterTime
Parameters
----------
cur: cursor
sqlite cursor3... | 2bebea96d8f0ad83363e31443e1295866cbb2775 | 628,890 |
def sol_tracker(w2v_model, solution):
"""Keep a record of those solution words that do not appear in the W2V vocabulary
Args :
w2v_model : standard Word2Vec 'KeyedVectors' data structure
solution : List of tokenised words representing solution
"""
sol_errors = []
for word in solution... | 349b540f9b7a2b788f73e143ed5365c55ec47bef | 628,896 |
from typing import Mapping
def is_updated(dictionary: Mapping, update_dict: Mapping) -> bool:
"""Checks if the dictionary has been updated with the values from update_dict."""
for k, v in update_dict.items():
if isinstance(v, dict):
if not is_updated(dictionary.get(k, {}), v):
... | 8fcdf5a6f8c529e22481c5dcdfd7c72eb3adf8aa | 628,897 |
def colorspace_prefixed_name(colorspace):
"""
Returns given *OCIO* colorspace prefixed name with its family name.
Parameters
----------
colorspace : ColorSpace
ColorSpace to prefix.
Returns
-------
str or unicode
Family prefixed *OCIO* colorspace name.
"""
pref... | 5bda395c9c67476333d3a52eefa90aff861c05d3 | 628,898 |
import re
def extract_pmc(citation):
"""
Extract PMC from a given eutils XML tree.
Parameters
----------
tree: Element
An lxml Element parsed from eutil website
Return
------
pmc: str
PubMed Central ID (PMC) of an article
"""
pmc_text = [c for c in citation.sp... | 4a65a77934d0e1b614058bba3bd05bda1b27ad7d | 628,899 |
def PrefixFromPattern(pattern):
"""Given a path pattern, return the prefix to use in ListKeys.
If a pattern ends with '*', the prefix is the pattern without the '*', otherwise, we format is as a directory.
"""
if pattern.endswith('*'):
return pattern[:-1]
elif pattern.endswith('/'):
return '' if patte... | b503c3eb633cb405c26c64ec24ab7807a423d854 | 628,900 |
def coords_to_lat_lon_lists(coords):
"""Converts a list of coordinates in tuple form (latitude,longitude) to a list of latitudes and a list of longitudes.
Parameters
----------
coords : list(tuple)
a list of coordinates in tuple form (latitude,longitude)
Returns
-------
... | 8da18ee4afb4b3ace26c9e847b9314e9e38a5432 | 628,904 |
def bin_filter(input: float, abs_boundary: float) -> float:
"""
Simple binary filter, will provide abs_ceiling as a binary output,
according to the 'negativity' of the input value
:param input : input value
:param abs_boundary : abs boundary value
:return : output binary value... | 15a53d5602d618f57a538831212fa5814d7640bb | 628,905 |
def lsb(x, n):
"""Return the n least significant bits of x.
>>> lsb(13, 3)
5
"""
return x & ((2 ** n) - 1) | 7e4021556e7136d0e38b70211f4c8e00ba67d2a4 | 628,907 |
import math
def is_square(num : int) -> bool:
"""
Check if a number is perfect square number or not.
Parameters:
num: the number to be checked
Returns:
True if number is square number, otherwise False
"""
if num < 0:
raise ValueError("math domain error")
if m... | e8002cd9d65e53fd62f86fafa41284cb4c5efb6a | 628,908 |
def get_display_data_single(fields, data, missing_field_value=None):
"""Performs slicing of data by set of given fields.
:param fields: Iterable containing names of fields to be retrieved
from data
:param data: Collection of objects representing some external entities
:param missin... | bf73156ad3ced77852470625aa4812402231ffaa | 628,912 |
import re
def IsGitSha(revision):
"""Returns true if the given string is a valid hex-encoded sha"""
return re.match('^[a-fA-F0-9]{6,40}$', revision) is not None | f97271c03109ca618b82180b8c928c8129a06ae3 | 628,913 |
def bits_table_l() -> dict[int, int]:
"""The table of the maximum amount of information (bits) for the version L.
Returns:
dict[int, int]: Dictionary of the form {version: number of bits}
"""
table = {
1: 152, 2: 272, 3: 440, 4: 640, 5: 864, 6: 1088, 7: 1248, 8: 1552,
9: 1856, 1... | cb001b77171c5af1423b542b17a7af9fbd027e20 | 628,914 |
def is_triangle(side_a, side_b, side_c):
"""Returns True if the input satisifes the sides of a triangle"""
return side_a + side_b > side_c and side_a + side_c > side_b and side_b + side_c > side_a | 1eb22261edb13c734430e3ef8207bd256436d1c5 | 628,916 |
def _get_list_feat_names(idx_feat_dict, num_pair):
"""Creates flattened list of (repeated) feature names.
The indexing corresponds with the flattened list of T values and the
flattened list of p-values obtained from _get_list_signif_scores().
Arguments:
idx_feat_dict: {int: string}
... | 7020a722646bdeff4bd520f2b1418fcf2b124fa1 | 628,920 |
def read_file(file: str) -> str:
"""
Reads a file.
Args:
file (str): file to read
Returns:
(str): content
"""
content = ""
with open(file) as fp:
content = fp.read()
return content | 7caf5b1d2cdf35cf1b847c082ad5c1c5f033eeca | 628,921 |
def is_box_inside(in_box, out_box):
"""
check if in_box is inside out_box (both are 4 dim box coordinates in [x1, y1, x2, y2] format)
"""
xmin_o, ymin_o, xmax_o, ymax_o = out_box
xmin_i, ymin_i, xmax_i, ymax_i = in_box
if (xmin_o > xmin_i) or (xmax_o < xmax_i) or (ymin_o > ymin_i) or (ymax_... | 732101c29bb55758ad44836582a96652b6eb4d58 | 628,930 |
def convert_path_to_targetname(include_path):
"""Convert an included header file's path to a quickstep library target in
cmake.
Args:
include_path (str): A header file path taken from a C++ include
statement.
Returns:
str: The target name in CMake that corresponds to the sp... | 9ae408e498825d031851ad8c7dd82fd6bd51e11c | 628,932 |
def parseMalformedBamHeader(headerDict):
"""
Parses the (probably) intended values out of the specified
BAM header dictionary, which is incompletely parsed by pysam.
This is caused by some tools incorrectly using spaces instead
of tabs as a seperator.
"""
headerString = " ".join(
"{}... | 7daa8adb49b9cd4535407e112a4330b13809a45c | 628,934 |
def parse_es_tag_results(response):
"""Parses results of es_tag_query such that a list of dicts is returned"""
to_return = []
for hit in response:
if tags := hit.to_dict().get('tags'):
for key, value in tags.items():
to_return.append({'name': key, 'value': value})
ret... | f052d2741d4506c564cdfa3a240749c67e3e201e | 628,937 |
def _is_required_parameter(param):
"""Indicates whether the parameter is required or not."""
return param.default is param.empty and param.kind is not param.VAR_POSITIONAL | fdd80b0661ea05f62d8c7953b535623c240c3663 | 628,939 |
def set_out_names(count_p2sh, non_std_only):
"""
Set the name of the input / output files from the experiment depending on the given flags.
:param count_p2sh: Whether P2SH should be taken into account.
:type count_p2sh: bool
:param non_std_only: Whether the experiment will be run only considering no... | 61fb310affc0e56e56e3ca29f0c68ad499b31778 | 628,940 |
def normalizeWeights(weights):
"""
Normalize a list of weights so the sum of the list is equal to one.
:return: List of normalized weights
:rtype: list of floats
"""
multiplier = 1/sum(weights)
if multiplier == 1:
return weights
return [w*multiplier for w in weights] | 1fb7721123393ae3e5d64ed01d7fe9fa634c8e76 | 628,943 |
import json
def kernel_for(notebook):
"""Read the notebook and extract the kernel name, if any"""
with open(notebook, "r") as f:
nb = json.load(f)
md = nb.get("metadata")
if md:
ks = md.get("kernelspec")
if ks:
return ks["name"]
return None | d2e774a6095e66c3712325b24d0d9bb45c606202 | 628,946 |
def find_parent(i3, window_id):
"""
Find the parent of a given window id
"""
def finder(con, parent):
if con.id == window_id:
return parent
for node in con.nodes:
res = finder(node, con)
if res:
return res
return None
... | 269575d7604e848652185040ad5466faec0fe655 | 628,948 |
import logging
def setup_logger(options):
"""Configure Python logging module"""
log_fmt = "OpenNESS Setup: [%(levelname)s] %(module)s(%(lineno)d): %(message)s"
ts_fmt = "%Y-%m-%dT%H:%M:%S"
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter(log_fmt, ts_fmt))
root_logger =... | 1a84bdc5887234613c863dd5372107afb95309d3 | 628,953 |
import calendar
from datetime import datetime
def date_n_month(date, n_month):
"""
returns the same date with "n_month" offset
:param date: the date
:param n_month: the number of month, 0 means this month, positive future month, negative previous month
:return: the same date minus the "n_month_bac... | 4f17807de7542e9e9167ff25aac80fcbf37d02a8 | 628,957 |
from typing import List
from typing import Pattern
import re
from typing import Optional
from typing import Match
def _remove_blank_lines(*, expression: str) -> str:
"""
Remove blank (break or spaces only) lines from expression string.
Parameters
----------
expression : str
Target express... | bd6976ea6b38907c93fb53d2b445dd482875ab65 | 628,958 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.