content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import socket
def is_valid_ipv6_address(address: str) -> bool:
"""
>>> is_valid_ipv6_address('::1')
True
>>> is_valid_ipv6_address('127.0.0.1')
False
>>> is_valid_ipv6_address('unknown')
False
"""
try:
socket.inet_pton(socket.AF_INET6, address)
except socket.error: # ... | a6214a75c926ce79c7542ceeb0dbddf078374d5c | 600,747 |
def _manufacturer_from_status(status):
"""Find the best manufacturer value from the status."""
return (
status.get("device.mfr")
or status.get("ups.mfr")
or status.get("ups.vendorid")
or status.get("driver.version.data")
) | fe04bc8bffd0265e0ec0a1921c6cef30156419af | 600,749 |
import re
def isDecimalPrecision2(num):
"""assumes num is a float or a string representing a float
returns a boolean, True if num is a decial with a precision of 2,
else False"""
num = str(num)
pattern = "\d+\.(\d+)"
result = re.match(pattern, num)
if result:
decimal_len = len(resu... | a3bd3a1ecd81ab15b87132a769cb54b542fcbe0a | 600,751 |
from typing import Tuple
def get_route_color_type(id: str, desc: str) -> Tuple[str, str, str]:
"""Get route_type, route_color, route_text_color based on route's id and description."""
desc = desc.casefold()
if "kolei" in desc:
return "2", "009955", "FFFFFF"
elif "tram" in desc:
return ... | caefe45508f7d09e424cb9a317c3371ff2157648 | 600,753 |
def _group_check(*args):
"""Return True when arguments are all None or all not None
"""
l = [val is None for val in args]
return len(set(l)) <= 1 | fa7c943f6c7803af6ced0d631d25f00f62fa003a | 600,754 |
def isNumber(x):
"""Returns true if x is an int or a float"""
return isinstance(x, (int, float)) | a2881608b40896bb341fd6fb84d924fdc7027e43 | 600,761 |
from typing import Callable
from typing import Tuple
def parse_line(line: str, distance_metric: Callable) -> Tuple[str, str, float]:
"""Parse a line of BLAST+6 output.
Parameters
----------
line : str
A blast line in format `-outfmt "6 qacc sacc length qlen slen ident"`
distance_metric : ... | 362a9ab44a32197c90e3d7064c11db7e7e0af2b6 | 600,766 |
import re
def is_cplusplus_compiler(name):
""" Returns true when the compiler name refer to a C++ compiler. """
match = re.match(r'^([^/]*/)*(\w*-)*(\w+\+\+)(-(\d+(\.\d+){0,3}))?$', name)
return False if match is None else True | 1709070286c8836902b54b8d750e258eee20aa38 | 600,767 |
def fetchall(cursor):
"""
Convenience function for fetching rows from a psycopg2 cursor as
Python dictionaries.
"""
columns = [col[0] for col in cursor.description]
return [dict(zip(columns, row)) for row in cursor.fetchall()] | 79ceb786e3c22a3e10fa7a78fc92058b422112d0 | 600,768 |
def rename_bitransformer_inputs(json_config):
"""
In "BiTransformer" model, rename input "characters" -> "bytes" and update subfields.
"""
[task] = json_config["task"].values()
model = task.get("model")
if model and len(model) == 1 and "BiTransformer" in model:
model_val = list(model.va... | ca1d93bfdfca7635e981c152d60394922b16a4f7 | 600,770 |
import math
def correct_lever_arm(linear_speeds, angular_speeds, dvl_pos_on_vehicle):
"""Correct DVL speeds when offset from AUV centre
Source: https://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=8729737
Args:
linear_speeds (tuple(float, float, float)):
Raw DVL linear speeds
... | 7fef60b445369f8fcdcc5ef12d3bbf5b2fa7906d | 600,772 |
def is_criador(usuario, sugestao):
"""
Verificar se o Usuário é o criador da Sugestão de Turma.
:param usuario: Usuário autenticado.
:param sugestao: Sugestão de Turma.
:return: True se o usuário for o criador da Sugestão de Turma.
"""
return usuario == sugestao.criador | 226dc8db705ae20fa5dda389ee2e747ad61f2c8d | 600,775 |
def attack_succcess_probability(atk, df):
"""Dictionary with pre-calculated probabilities for each combination of dice
Parameters
----------
atk : int
Number of dice the attacker has
df : int
Number of dice the defender has
Returns
-------
float
"""
return {
... | 610ebe8c1f721de7fc18e3c80f2d27567d2a1fe1 | 600,781 |
def text(item):
"""
Get the text from the tweet
"""
if 'text' in item:
return item['text']
return None | 1451d0933c65b5c09eb8a39eb882162af335cb57 | 600,784 |
def rotate(x, y, co, si):
"""Rotate x, y position given cos/sin of angle."""
xx = co * x + si * y
yy = -si * x + co * y
return [xx, yy] | 232e8a839f3624deb38d2bca3d531f1c18a1c179 | 600,786 |
def pract_text(trial):
"""
input: current practice trial # (int)
output: practice instruction text (string) for given practice trial
"""
intro = '\n\n Thank you for participating in this experiment! ' \
'\n\n In the experiment, you will pay attention to specific items on the sc... | f55c27af03b4b921b1c5ab3923aac8e6f7af1fca | 600,787 |
import string
def get_gis_field(csv_field, gis_field_lookup):
"""return a (max) 10 character representation of csv_field that is unique to the list of analysis fields"""
if csv_field in gis_field_lookup:
return gis_field_lookup[csv_field]
gis_field_set = set(gis_field_lookup.values())
gis_fiel... | 8adfc88babc4514c715f63ec8c258268862226b2 | 600,794 |
def count_unequal_bits(a, b):
"""Counts number of bits that are different between them a and b.
Args:
a, b: Non-negative integers.
Returns:
Number of bits different between a and b.
Raises:
ValueError: If either of the arguments is negative.
"""
if a < 0 or b < 0:
... | 064323f04d675afba0e9eff264e08cc48e3808f3 | 600,795 |
def display_duration(value):
"""
Maps a session requested duration from select index to
label."""
map = {'0':'None',
'1800':'30 Minutes',
'3000':'50 Minutes',
'3600':'1 Hour',
'5400':'1.5 Hours',
'6000':'100 Minutes',
'7200':'2 Hours',
... | 686576178b0cd695ad0c2de1cdd12890277e06da | 600,799 |
def tensorrt_bind(symbol, ctx, all_params, type_dict=None, stype_dict=None, group2ctx=None,
**kwargs):
"""Bind current symbol to get an optimized trt executor.
Parameters
----------
symbol : Symbol
The symbol you wish to bind, and optimize with TensorRT.
ctx : Context
... | dfc30ec16ba52f645a7ec10bc5b656daea4961a3 | 600,800 |
import re
def split_str_to_field(input_str):
"""Split the input_str into 2 parts, the field name and field body.
The split is based on this regex format: :field_name: field_body.
"""
regex_pattern = "((^:{1}.*:{1})(.*))"
field_name = None
field_body = None
if input_str is None:
... | 7fbd3b4aa4f15421f656543227779384d619043c | 600,801 |
def bf_inputs(cbf, bf):
"""Input labels associated with specified beamformer."""
reply = cbf.req.dbe_label_input()
return [] if not reply.succeeded else \
[m.arguments[0] for m in reply.messages[1:] if m.arguments[3] == bf] | e0d9fedfbc1977d63cbddb741749ca6e7b664394 | 600,810 |
def write_relevant_features_to_file(fname, clusters, cluster_dict, feature_dict, feature_count=5):
"""
Writes the features with the highest weight in each cluster to a file
Parameters
----------
fname: str
clusters: int
Number of clusters
cluster_dict: dict
dict of dicts. fo... | 532679917822de1caeefa5b4d78dc1e30bd18c02 | 600,813 |
def _color_to_list(color):
"""Converts a Blender Color to a list of 4 color values to use with shaders and drawing"""
return list(color) + [1.0] | 27196931c9773ff6dd94fdbb21be29f91c2834fb | 600,821 |
def structure(status="", msg=""):
"""
basic JSON message structure
Args:
status: status (ok, failed)
msg: the message content
Returns:
a JSON message
"""
return {
"status": status,
"msg": msg
} | 910bc23d2ee09fa854b9e21ff7ec14a923a43fc5 | 600,822 |
from typing import List
def get_remaining_ports(ports: List[int], last_used_port: int) -> List[int]:
"""Get a new list with the remaining ports after cutting out all ports until and incl. the last used port.
Args:
ports (List[int]): The port list to be updated.
last_used_port (int): The last ... | f68d325d56e9ba3f111e6b9eb4eef4489ed5c50f | 600,824 |
import inspect
async def await_if_coro(x):
"""Async/sync compatible wrapper."""
if inspect.iscoroutine(x):
return await x
return x | e75dc032caa4c2e5098a3ccb14636195c4803111 | 600,825 |
def group(list_, size):
"""Separate list into sublists of size size"""
return [list_[i:i + size] for i in range(0, len(list_), size)] | d4a6b80a6b674f21fb18cfe49bd38a1fe0cc4db2 | 600,826 |
import inspect
def get_line_no(obj, rel_pos):
"""
Extracts absolute line number based on object and relative position.
"""
_, start = inspect.getsourcelines(obj)
return start + rel_pos | 5302b09d607b596641efae241fa4b9ff00bb9c94 | 600,829 |
import statistics
def found_convergence(validation_accuracy):
"""Given validation accuracy, return bool defining if convergence has been reached: <=5% change in last 10 points"""
last_ten = validation_accuracy[-10:]
diffs = []
for x in range(9):
d = last_ten[x+1] - last_ten[x]
diffs.ap... | 1209a9d5fb4c11a6692dcb650981af57efa1b448 | 600,830 |
def vflip(anns, size):
"""
Vertically flip the bounding boxes of the given PIL Image.
Parameters
----------
anns : ``List[Dict]``
Sequences of annotation of objects, containing `bbox` of [l, t, w, h].
size : ``Sequence[int]``
Size of the original image.
"""
w, h = size
... | e5ac28342dca85010c8af014065dd668bf1a6327 | 600,831 |
import hashlib
def persistent_hash(s: str):
"""Compute a hash that persists across multiple Python sessions for a
string."""
return int(hashlib.sha224(s.encode()).hexdigest(), 16) | 62bc73d28118e73aa0ce8a731be0247998938482 | 600,833 |
def is_index_out(index, arr):
"""
:param index: looping index
:param arr: array / list
:return: bool -> if index out of range
"""
return index < len(arr)-1 | 3a8c8a5c248c25cea551398a9946c9d7c70e0024 | 600,834 |
import hashlib
def file_hash(content):
"""
file_hash will hash the content of a file.
>>> from io import BytesIO
>>> long_text = "Harrie en Henk (Hent)" * 879
>>> file_hash(BytesIO(long_text.encode()))
'cf3c7be4778cded29fab4b66622c5e8af91d01a9'
"""
hasher = hashlib.sha1()
buf = co... | 576ab24470e9787901c1e4aa0a862e5e995d3723 | 600,835 |
def kelvin_to_c(k):
"""Convert temperature from Kelvin to Celsius."""
return k - 273.15 | 2926ac2ffc5965e8ddb1b08c2343e67184f1fcbd | 600,838 |
def is_cuda(model):
""" predicate for 'model' begin on a Cuda device """
return next(model.parameters()).is_cuda | 99626af0d181f534395dd4d1426a5bc174e53765 | 600,841 |
def all_note_tasks_approved(sg, note, args):
"""
Determine if all Notes on the relevent Task have been approved.
:param sg: A Shotgun API handle object.
:param note: A Shotgun Note dictionary.
:param args: A dict of plugin args.
:returns: True if all Notes on the relevant Task have been approve... | 1992949e0f1d102848c3b219d1c48c746c23ba4f | 600,850 |
def display_list(l):
"""Returns a comma-punctuated string for the input list
with a trailing ('Oxford') comma."""
length = len(l)
if length <= 2:
return " and ".join(l)
else:
# oxford comma
return ", ".join(l[:-1]) + ", and " + l[-1] | f5f957b70fd996085f5e7b64c1f2ab26f7c7396e | 600,855 |
import torch
def padding_mask(lengths, max_len=None):
"""
Used to mask padded positions: creates a (batch_size, max_len) boolean mask from a tensor of sequence lengths,
where 1 means keep element at this position (time step)
"""
batch_size = lengths.numel()
max_len = max_len or lengths.max_val... | 1be3227d5efe55e0a5874d09a118172fdcde1a03 | 600,864 |
def CollapsePath(path_tokens):
"""
CollapsePath() takes a list of Strings argument representing a
directory-like path string
(for example '/SUB1A/Sub2A/../Sub2B/sub3b/../sub3c/entry'),
and replaces it with a version which should contain no '..' patterns.
(In the example above, it returns /SUB1A/... | afd4766b5bf688fdb1e9d0d18266f27914c9ee4f | 600,865 |
def enrich_ioc_dict_with_ids(ioc_dict):
"""
Enriches the provided ioc_dict with IOC ID
:param ioc_dict: IOC dict transformed using the SEARCH_IOC_KEY_MAP
:return: ioc_dict with its ID key:value updated
"""
for ioc in ioc_dict:
ioc['ID'] = '{type}:{val}'.format(type=ioc.get('T... | 34c471337a4e4c520dd8598e85c4cbd25ce56b93 | 600,868 |
def remove_extension(file_path):
"""
Removes extension of the given file path
For example, C:/test/rig.py will return rig
:param file_path: str
:return: str
"""
split_path = file_path.split('.')
new_name = file_path
if len(split_path) > 1:
new_name = '.'.join(split_path[:-1]... | 8c82e3bde6e2dc64781feafabb639e25e3f329a0 | 600,870 |
def hex2text(hex):
"""
Convert hex to text
:param hex: hex to convert
:return: text string
"""
return ''.join(chr(int(hex[i:i+2], 16)) for i in range(0, len(hex), 2)) | 25fc44b8f72b73873572f2781fa801cdbf8ea51d | 600,873 |
def isAudio(pinName):
"""\
Predicate to check whether the input corresponds to an audio- or light sensor-input
:param pinName: indicates a pin to add to the set of pins to be read during capture.
one of "LIGHT_0", "AUDIO_0", "LIGHT_1", "AUDIO_1"
:returns boolean: True if pin is associated wit... | df8fde650fdf5224f32a2e59cacaf3551695d294 | 600,874 |
import string
import random
def __create_random_string(length: int = 32, contain_digits: bool = False) -> str:
"""
:param length: The length of the random string
:param contain_digits: If set to True, the random string will contain digits
:return: The random string
"""
chars = string.ascii_le... | e14574866ddf6c3f389dfd0ecfa404886699170c | 600,875 |
def copy_grid (grid):
"""return a copy of the given grid"""
another_grid = []
for i in grid:
another_grid.append(i)
return another_grid | dcb453ebc91bd9f32b7986c932cb98f7c594af6f | 600,876 |
import hashlib
def generate_hashsum(file_name):
"""Generate a SHA-256 hashsum of the given file."""
hash_sha256 = hashlib.sha256()
with open(file_name, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_sha256.update(chunk)
return hash_sha256.hexdigest() | 45e52e7777a30c46ab0d81a923f39a4bdd94d32b | 600,882 |
from pathlib import Path
def tests_dir() -> Path:
"""Directory where tests + data is located."""
return Path(__file__).parent | 2ac2f2756cf21e27a245a3494f0ae3f73ecc2ff8 | 600,884 |
def limit(requestContext, seriesList, n):
"""
Takes one metric or a wildcard seriesList followed by an integer N.
Only draw the first N metrics. Useful when testing a wildcard in a metric.
Example:
.. code-block:: none
&target=limit(server*.instance*.memory.free,5)
Draws only the first 5 instance'... | 65cdb981734eac60b24f7878ac169e90145405b9 | 600,885 |
def abstract(cls):
"""
Declares that this class cannot be instantiated. Only subclasses that are
not declared abstract could be instantiated.
This is equivalent to setting the class property ``_abstract=True``.
:param cls: The class that should be abstract
:return: The same class
"""
c... | 8c23bf878e56bfe39892366293d644c62c5f5b53 | 600,887 |
import torch
def get_box_class_count(box_class, class_count):
"""
Return a tensor with the number of bounding boxes with class c for each bounding box b, where `c = cls(b)`.
:param box_class: A [*, d1] tensor
:param class_count: A [*, d2] tensor
:return: A [*, d1] tensor
"""
return torch.... | 89127c8ef66f78e2bce26a375afcd00989109d11 | 600,890 |
def textops_grep(match, lines, exclude=False, case_sensitive=True):
"""
<Purpose>
Return a subset of lines matching (or not matching) a given string.
<Arguments>
match:
The string to match.
lines:
The lines to filter.
exclude (optional, defaults to false):
... | 9e75034e15c3c3a8af6e81c9570190f6d0cc6ba0 | 600,892 |
def str2bool(s):
"""
Converts an on/off, yes/no, true/false string to True/False.
Booleans will be returned as they are, as will non-boolean False-y values.
Anything else must be a string.
"""
if type(s) == bool:
return s
if s and s.upper() in [ 'ON', 'YES', 'Y', 'TRUE', '1' ]:
return True
else:
return ... | 4109d4b90af8914fb5956c9821cfd70a0e71f6f3 | 600,895 |
def map_a_number_into_minus_half_to_half(number):
"""map a number into [-0.5, 0.5]"""
while number > 0.5:
number -= 1
while number < -0.5:
number += 1
return number | 48909aa6dad43fce630bdba0eff22de83e9ef0b3 | 600,897 |
def find(x, parent):
"""
This function gets a node x and the parent-part of a union find data structure.
It returns the root of the tree that contains x. A tree compression technique called path halving is used.
It is optimized with numba, using njit.
"""
while x != parent[x]:
#path com... | 2c311b82c6729f38fad617a8feabe179f22ad35b | 600,899 |
def get_movie_names_dict(df):
"""creates dictionary out of movie id and title in df, returns dict"""
MOVIE_NAMES = dict(zip(df['movieid'], df['title']))
return MOVIE_NAMES | 3f3c8c411bbd86145cf3d9ab94bcf490cf2e628a | 600,900 |
def get_trailing(xs, x_end):
"""
if x_end is larger than xs
return x_start (the end of xs facing x_end) and trailing (bool) indicating whether x_end > xs
complains if x_end is within xs
"""
if x_end > max(xs):
x_start = max(xs)
trailing = True
elif x_end < min(xs):
x_start = min(xs)
trailing = False
e... | f5999c5563c4d35ccfe5c930ec3161669681acc5 | 600,904 |
def apply_to_window(sequence, window_size, function, step=None):
""" apply_to_window(sequence, window_size, function) -> [(int, float),(int, float),...]
o sequence Bio.Seq.Seq object
o window_size Int describing the length of sequence to consider
o step Int describing the ... | c12e21434a1707d40c1bacfa63b0cbc86f23a8b6 | 600,906 |
def create_mask(inputs, pad_token):
"""
Create a binary mask to indicate whether a token is pad or not
:param inputs: (seq_len, batch_size)
:param pad_token: token for padding
:return: mask: (seq_len, batch_size)
"""
return inputs != pad_token | aef8baf5101027b7591b1cb0ae49d6f9fdf9b2f4 | 600,907 |
import json
def get_pretty_json(json_obj):
"""JSON encode argument in pretty format."""
return json.dumps(json_obj, sort_keys=True,
indent=4, separators=(',', ': ')) | 839d19b396fe02ea2d74c55dc500d22132996a65 | 600,908 |
import json
def dumps_dict(dic: dict) -> str:
"""
Dumps a dictionary in a pretty-ish format to the logger.
Args:
dic (dict): The dictionary to print
Returns:
str: The pretty-ish string representation of the dict argument
"""
return json.dumps(dic, indent=4) | 181643968d971dbe4d34e7eeec3735679149a0aa | 600,909 |
import random
def make_random_tree(size):
"""Make a random binary tree with size nodes."""
if size <= 1:
return 0
r = random.randint(1, size-1)
return (make_random_tree(r), make_random_tree(size-r)) | f950e58a22f6b615c0ae9c940c93f0174244178d | 600,916 |
def phy_grid_dims(conn):
""" Returns physical grid dimensions. """
cur = conn.cursor()
cur.execute("SELECT grid_x FROM phy_tile ORDER BY grid_x DESC LIMIT 1;")
x_max = cur.fetchone()[0]
cur.execute("SELECT grid_y FROM phy_tile ORDER BY grid_y DESC LIMIT 1;")
y_max = cur.fetchone()[0]
return... | 8c2690b988dbc0d6a7fd2caf10891f15db1b435e | 600,917 |
def read_matrix(matrix, m_file):
"""Read 1+n lines from given file, n is read from the first line.
Write n rows of n floats to the matrix."""
n = 0
with open(m_file, "r") as f:
first_line = f.readline()
n = int(first_line);
for i in range(n):
line = f.readline()
... | 9f61d464df87d1d12a28d183c8825ace72c596ee | 600,918 |
import yaml
def open_yaml_file(filename):
"""
Open a yaml file to extract configuration details.
Paramters
---------
filename : STRING
path to the file to be opened.
Returns
-------
config : STRING
configuration details located in the file.
"""
try:
wi... | 7474e813edd5e69db2971850422d3701332d7258 | 600,919 |
def normalizeImages(lst_images):
"""
Preprocessing images by normalizing
"""
return [((x - x.mean())/x.std()) for x in lst_images] | 7da28d00d6ad44edea74a33b3eb20db2d33efc8c | 600,920 |
import logging
def batch_delete(service, message_ids, user_id, **kwargs):
"""Deletes multiple messages given the message_ids"""
try:
service.users().messages().batchDelete(userId = user_id, body = message_ids).execute()
return True
except Exception as ex:
logging.exception('BatchFi... | a41deb5e36acecb136a283e77b1a8d820908f2da | 600,923 |
def isSafe(row,
column,
oblique,
oblique_inv,
ctrl_line,
ctrl_oblique,
ctrl_obliqueinv):
"""Check if it is safe to put a queen at that position
Args:
row (int): row number
column (int): column number
oblique (array): for the di... | 65a6c35c5040b04e8577582073de2b4f1fc1105a | 600,924 |
import pathlib
def get_file(file: pathlib.Path) -> str:
"""Extract all lines from a file."""
with open(file, "r") as f:
return f.read() | 86f7a57b5b5394e82082a11f69a37514f39e0e71 | 600,925 |
def absolute_error(interval):
"""Calculate the absolute error of a interval"""
return abs(interval[-1] - interval[0]) | 986ccca95ed9fc51aee3b92a1cfc3e5ec3482240 | 600,927 |
def get_executors(tech):
"""From a loaded technique, get all executors."""
return tech['atomic_tests'] | b5a8d6ed974c22f1c73b6671961b009828d1e87c | 600,930 |
import math
def rgb_bin(rgba, binsize):
"""
Compute the RGB index for the hash table. We do not need a bin for every
RGB value, and do not have enough training images to support that anyway.
So, lump together the adjacent R, G, and B values in bins of size binsize.
"""
rgb = rgba[0:3]
if ... | 8adcf8eef689987297058a5633caef43e7d4a7be | 600,932 |
def expand_list(_list):
"""
Convert list of '.' separated values to a nested dict.
Taken from SO article which I now can't find, this will take a list
and return a dictionary which contains an empty dict as each leaf
node.
>>> expand_list(['a', 'b.c'])
{
'a': {},
... | b7040d9274e47be1335220f6cf0b387100125287 | 600,934 |
def _create_embedded_row(value, out_row, out_col_ndx, config, group_values):
"""
Copies the given output row and assigns the given pattern match
group values to the corresponding output row columns defined by
the configuration.
:return: the new output row
"""
# Make a new output row.
ro... | 53b7b271282be06d559cc17c4bf44363ff065407 | 600,935 |
def split_into_X_and_Y(df_xy_name, label_selection = 'queue_count_binned'):
"""Separate the features (X) and the labels (Y). The default label selection (Y) is queue_count_binned.
However, you could use queue_count_max (not binned) or queue_indicator for the classifier instead."""
# preparing X and y
... | 9ad59c4abffd8a50579580694336ce91e8db98a5 | 600,937 |
def fix_actress_name(name):
"""Returns the updated name for any actress based on our replacement scheme"""
""" if you want to ad any additional ways to fix names, simply add another elif line below
elif name == 'name returned from javlibrary'
return 'different name'
"""
if name == 'Kitagaw... | 396b6a168e5c74c6d13c6c96a908d160b7124b7a | 600,941 |
def iterate(source, *keys):
"""Iterate a nested dict based on list of keys.
:param source: nested dict
:param keys: list of keys
:returns: value
"""
d = source
for k in keys:
if type(d) is list:
d = d[int(k)]
elif k not in d:
d[k] = {}
else:
... | 8ff40d970f6a41b21415c53158f323dc8df73006 | 600,943 |
import re
def remove_punctuation(text: str) -> str:
"""
Remove non-alphanumeric characters from a text, replacing them with spaces.
Parameters
----------
text:
Text to process.
Returns
-------
text
"""
# replace non-alphanumeric symbols with spaces
pattern = r"[^a... | 1f6f3d497f1bf26f7fba9561b4597c2a37654085 | 600,944 |
import torch
def torch_amplitude_to_db(feats, amin=1e-10, top_db=80.0, to_prob=False):
"""
Take the log of a time-frequency representation with differentiable
PyTorch functions, scaling values to be between 0 and 1. Adapted from
the Librosa amplitude_to_db function.
Parameters
----------
... | 2f2927cccb112fad9df2135ab9fb92f21b1b22f9 | 600,945 |
def find_target_system(data, target_system):
"""
Finds target system ``aeroelastic``, ``aerodynamic`` or ``structural``.
Args:
data (sharpy.PreSharpy): Object containing problem data
target_system (str): Desired target system.
Returns:
sharpy.linear.src.libss.ss: State-space ob... | 5ac360acf1135eaf48e901137add6ee1ff83284c | 600,956 |
def extract_disease(risk_assessment):
"""Extracts disease from a RiskAssessment resource.
Example resource:
{
...
"basis": [
{
"reference": "Patient/610c6252-34de-4493-a3b4-f7ecc43e5681"
},
{
"reference": "QuestionnaireResponse/9c318953-f6b3-492c-aa76-a9564a3cbeba"
... | 1f030c32580d968a482230126f1ae25a6c6dfa9c | 600,957 |
def separa_palavras(frase):
"""
A funcao recebe uma frase e devolve uma lista das palavras dentro
da frase.
"""
return frase.split() | 45572c5dc1d218d02359f0e2dd607c0a944d6d91 | 600,960 |
def non_zero_func(x):
"""Function which returns non-zero indices of an array
Args:
x (1d numpy array): input array
Returns:
1d numpy array: output non-zero indicies
"""
inds = x.nonzero()[0]
return inds | cee61902ae0c0e1370e108d1ac827f26f05ebc31 | 600,963 |
def get_longest_contig_list(readers):
"""
Get the largest list of contig names from a list of readers
:param readers: list of vcf readers
:return: list of contig names
"""
sorted_readers = sorted(readers, key=lambda x: len(x.contigs))
return sorted_readers[-1].contigs.keys() | 0f7164cccfd05be77691ad224918f2b9ee93b8bd | 600,966 |
import collections
def minWindow(self, s: str, t: str) -> str:
"""
>>>Use two pointer
Maintain a sliding window to to track the
characters and a variable cond to track the
number of conditions that we need to make it
containing all the chars in t. The key is we
... | 524b3fed5c7d8c3dac49a73008eb2c292dddf4d9 | 600,967 |
def trim_shared_prefix(ref, alt):
"""
Sometimes mutations are given with a shared prefix between the reference
and alternate strings. Examples: C>CT (nucleotides) or GYFP>G (amino acids).
This function trims the common prefix and returns the disjoint ref
and alt strings, along with the shared prefi... | 96a390b92588ebd61207aff13505b27be91f4241 | 600,969 |
def itemfilter(predicate, d, factory=dict):
""" Filter items in dictionary by item
>>> def isvalid(item):
... k, v = item
... return k % 2 == 0 and v < 4
>>> d = {1: 2, 2: 3, 3: 4, 4: 5}
>>> itemfilter(isvalid, d)
{2: 3}
See Also:
keyfilter
valfilter
it... | 72a62f8b00fa3b709b1b269a5ac866e00a7b2958 | 600,970 |
from datetime import datetime
def filetime_to_timestamp(filetime_64):
"""
The FILETIME timestamp is a 64-bit integer that contains the number
of 100th nano seconds since 1601-01-01 00:00:00.
The number is usually saved in the registry using two DWORD["values"]
:return: string of UTC time
"""
... | a4eda024637a817fc6323eb558d4209d6ac3baf2 | 600,972 |
def check_constraints(Px,pk1,pk2,mu1,mu2,mu3):
"""
Check that the parameters are within the bounds and constraints of the
asymmetric BB84 protocol with weak coherent pulses with 2 'decoy' states.
Stops the script if any bounds or constraints are violated.
Parameters
----------
Px : float
... | db57d4122f714c7e6f942645a889b25c744cf79d | 600,976 |
from re import VERBOSE
def trp(pointer, main_stack, aux_stack):
"""
Trp
Take the top element of the main stack to the power of the top element of
the auxiliary stack.
If either stack is empty, treat it as zero.
"""
if VERBOSE:
print("Trp", main_stack, aux_stack)
if main_stack:
... | 65a64c4589a167a72bcd3a936fa4fc07a3753188 | 600,979 |
def cast_or_none(value, cast_function):
"""
Cast a value to a desired type, or return None if the cast is not possible
:param value: value
:param cast_function: cast function like float, int or str
:return: casted value or None
"""
try:
return cast_function(value)
except (TypeErr... | 57537e218285d1de9d9db3647426b56c9e7b6af8 | 600,983 |
def build_trainset_surprise(dataset):
"""
Build a training set from a Surprise Dataset so that
it can be used for model training.
"""
trainset = dataset.build_full_trainset()
return trainset | 0c43284c11654e4bfce7f52caf21e01652be80bd | 600,984 |
def strip_stopwords(tokens, stopwords):
"""
Input:
tokens (list)
stopwords (list)
Returns:
A list of tokens without stopwords
"""
return list(set(tokens) - set(stopwords)) | 3496c5fdbd31b4e42e42dea6254618d22ae514f6 | 600,987 |
def _align_indices(data, order, axis=1):
"""Align the indices/ columns in a collection of pandas objects to order"""
for i in range(len(data)):
if data[i] is not None:
data[i] = data[i].reindex(order, axis=axis)
return data | 14a2519952294c44410450dbf48e34ef3df106f3 | 600,989 |
import time
def check_cli_output_with_mocker(dut, mocker_object, command, max_wait_time, key_index=0):
"""
Check the command line output matches the mocked data.
:param dut: DUT object representing a SONiC switch under test.
:param mocker_object: A mocker instance.
:param command: The command to b... | f16c1d691dcd614d27bcc79a5e57a8eeeab82eaf | 600,990 |
def convexHullIndex(convex_hull, listPts):
"""Returns the indices of of the given points of the convex_hull from the listPts
"""
output = []
for point in convex_hull:
output.append(listPts.index(point))
return output | 3e9dd48272f541ffd8fa0d1e6dd54f1b484444a5 | 600,995 |
def csv_to_json(csv_filename):
"""
converts string referencing csv file to a json file
:param csv_filename: (string) name of data, as a csv file
:return: string of json filename matching csv file
"""
csv_trimmed = csv_filename[:-3]
json_added = csv_trimmed + 'json'
return json_added | 7be0247a61048112d3eeedc1bd877a98915c421a | 600,996 |
def min_rw_index(prices, start, end):
"""
Searches min price index inside window [start,end]
:param prices: in list format
:param start: window start index
:param end: window end index
:return:
"""
matching_index = start
for i in range(start, end + 1):
if prices[matching... | dbed333535c1cb9b22d2af5a355ceec90e657804 | 600,999 |
def _get_magnification(r1, r2):
"""
Calculate magnification factor of the object.
Parameters
----------
r1 : float
Source to object distance.
r2 : float
Object to detector distance.
Returns
-------
float
Magnification factor.
"""
return (r1 + r2) / ... | 3c186b64a33c858d2976cea2f259adf6e0ba3515 | 601,000 |
def boolean_cast(value):
"""Converter for boolean attributes."""
return str(value).lower() in ('true', '1', 'yes') | a73286b0312b1b9dbefaaf261f4f3a990b4563b1 | 601,005 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.