content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
from typing import Iterable
from typing import Any
from typing import List
def unique_list(seq: Iterable[Any]) -> List[Any]:
"""
Returns a list of all the unique elements in the input list.
Args:
seq: input list
Returns:
list of unique elements
As per
http://stackoverflow.co... | 40bc33a9e42553fbc924ecf71fb2273a382f502e | 638,521 |
def resource_from_path(path):
"""Get resource name from path (first value before '.')
:param path: dot-separated path
:return: resource name
"""
index = path.find('.')
if index == -1:
return path
return path[:index] | ae5e00cec7be8dd94e4e7083a2db6a8878dabd2f | 638,522 |
def make_numeric_labels(class_set):
"""Generates numeric labels (to feed external tools) for a given set of strings"""
return { cls : idx for idx, cls in enumerate(class_set) } | ad5a002c31bcdd2b305d40430773e918bd89f212 | 638,526 |
def proj(A,B):
"""Returns the projection of A onto the hyper-plane defined by B"""
return A - (A*B).sum()*B/(B**2).sum() | 57036612b3e3307cf079c11969c54a5d8b016a05 | 638,529 |
import csv
def writeCSV(file,data,cols = None):
"""
Write CSV file with data typically supplied as a list or np.arrays.
:param file: file or name of file,
:type file: file or str
:param data: list of numpy.array or two dimensional numpy.array
:type data: list of numpy.array or two dimensiona... | 06ebb93fc019dbfad41e62a69ff772ae2b5bbfd0 | 638,536 |
def parametrized(decorator):
"""
Decorator for easily defining parametrized decorators. Should be used like this:
@parametrized
def my_decorator(func, *args, **kwargs):
@wraps
def _my_decorator(*args_, **kwargs_):
# At this point args and kwargs are decorator parameters whil... | f9cbf0896c1c0948631bb7f7aa94ee0ce95b9f50 | 638,540 |
def make_scenario_name_nice(name):
"""Make a scenario name nice.
Args:
name (str): name of the scenario
Returns:
nice_name (str): nice name of the scenario
"""
replacements = [
("_", " "),
(" with", "\n with"),
("fall", ""),
("spring", ""),
... | 82d9034b5b08db05ae9a7c80797e9cd0574d410b | 638,547 |
def lookup_by_href_or_nickname(href, nickname, find_function):
"""
Helper to retrieve items by href or nickname
:param href (optional): String of the item href
:param nickname (optional): String of the item nickname
:param find_function: The function to use to find by nickname
:return: String o... | 9f7b36bb0c1d4c31e93fd1737fd55fc7210f6dd5 | 638,548 |
def dictify(some_named_tuple):
"""
Convert Named Tuple to dictionary
:param some_named_tuple: collections.namedtuple()
:return:dict,
"""
return dict((s, getattr(some_named_tuple, s)) for s in some_named_tuple._fields) | 2dff7ef035ce9f7b508349cd1afb1bd12e338712 | 638,549 |
import re
def _IsTaskKillError(stderr):
"""Returns whether the stderr output of taskkill indicates it failed.
Args:
stderr: the string error output of the taskkill command
Returns:
True iff the stderr is considered to represent an actual error.
"""
# The taskkill "reason" string indicates why it f... | 9a3e0a8d4ed88b767384cb3802147b18dd37e84b | 638,552 |
def binary_search(numbers, number):
"""Binary search
Locates the number in the list of sorted numbers. Looks at the middle element, and proceeds recursively to the left
or to the right, depending on whether the number was smaller or bigger, respectively
Returns the position of the found number, or the... | b60f3709e0d5e13be4cb268c22bf86dd607141c7 | 638,553 |
def minmax_element(iterable, first=0, last=None, key=None):
"""
Find and return the minimum and maximum element in an iterable range.
Parameters
----------
iterable: an iterable object with __get_item__
first: first element to check
last: one past last element to check. None will check unti... | a5176ac552ff720fdd304c12b64a1ec9a9b9a09b | 638,555 |
def sql_from_dtype(dtype):
"""Returns a sql datatype given a pandas datatype
Args:
dtype (str): The pandas datatype to convert
Returns:
str: the equivalent SQL datatype
Examples:
>>> sql_from_dtype('bool')
'boolean'
>>> sql_from_dtype('float64')
'numeri... | 29873e0530fd5d0bdad027917bd6e121e7de8bb9 | 638,559 |
def escape_ass_tag(text: str) -> str:
"""Escape text so that it doesn't get treated as ASS tags.
:param text: text to escape
:return: escaped text
"""
return text.replace("\\", r"\\").replace("{", r"\[").replace("}", r"\]") | da976a528ff88fea3a36e532b6fc3b73e77ebb34 | 638,561 |
import base64
def encode_base64(input_bytes: bytes, urlsafe: bool = False) -> str:
"""Encode bytes as an unpadded base64 string."""
if urlsafe:
encode = base64.urlsafe_b64encode
else:
encode = base64.b64encode
output_bytes = encode(input_bytes)
output_string = output_bytes.decode... | 65f9c091e4e4c3f0cf2f18f226e3c2a61b384d79 | 638,565 |
def quicksort(lst):
"""quicksort with filter and lambda"""
if not lst:
return lst
else:
pivot, *rest = lst
return (
quicksort(list(filter(lambda x: x < pivot, rest)))
+ [pivot] +
quicksort(list(filter(lambda x: x >= pivot, rest)))
) | 3378e89efeb971cd5e0ea8407afbf208d5ccfc04 | 638,575 |
def _CheckEnum(value, name, values=None):
"""Checks whether value is a member of the set of values given.
Args:
value: The value to check.
name: The name of the value, to use in error messages.
values: The iterable of possible values.
Returns:
The checked value.
Raises:
ValueError: If the... | c18e91bd7a83b0a8e604b51940c18dfb16346ede | 638,584 |
import hashlib
def generate_hashed_slug(slug, limit=63, hash_length=6):
"""
Generate a unique name that's within a certain length limit
Most k8s objects have a 63 char name limit. We wanna be able to compress
larger names down to that if required, while still maintaining some
amount of legibility... | e466a2ba31c81b3961e8ff7215ce51a71c44acd5 | 638,585 |
def get_background_genes_file(filepath):
"""
Get background genes from local file for null-hypothesis formulation.
"""
gene_list = []
with open(filepath) as file_gene:
for line in file_gene:
gene_list.append(line.strip())
return gene_list | 7498bcc40897359bc02b4a6c924aaf8056f05209 | 638,586 |
def uch_leung(us, ut):
"""
Choking velocity based on Equation 6 from Leung [2]_. All parameters must
be in units of ft/s or in units of m/s.
Parameters
----------
us : float
Solids velocity [ft/s or m/s]
ut : float
Terminal velocity of a single particle [ft/s or m/s]
Re... | 1455ba7f3a1ba45a4c722d6b2619de7ef630d3e2 | 638,588 |
def is_windows_path(path):
"""Checks if the path argument is a Windows platform path."""
return '\\' in path or ':' in path or '|' in path | 88d856751744f0400bd4db09013492215b363c2a | 638,591 |
from typing import Union
def count_even(obj: Union[list, int]) -> int:
"""
Return the number of even numbers in obj or sublists of obj
if obj is a list. Otherwise, if obj is a number, return 1
if it is an even number and 0 if it is an odd number.
>>> count_even(3)
0
>>> count_even(16)
... | 8d757d7004c11ac77eb85bbc37fd7b3c9e6c4798 | 638,597 |
from datetime import datetime
def local_to_utc(dtime, zoneinfo=None):
"""Convert local time to UTC time"""
if dtime.tzinfo is not None:
return dtime - dtime.utcoffset()
year, month, day = dtime.year, dtime.month, dtime.day
hour, minute = dtime.hour, dtime.minute
return datetime(year, mont... | deecb91452234a04749fe82f90ae27a9d70148df | 638,601 |
def choices_help_text(choices):
"""Return a clear text for choices.
Args:
choices: list of tuples (value, label)
Returns:
a text in the form:
enum1: label1
enum2: label2
"""
choises_str = ('{enum}: {label}'.format(enum=choice[0], label=choice[1]) for choice... | 67fd67f9e2af7d9ad96de4cea057ac2f992539b7 | 638,602 |
def _shape(tensor):
"""Get the shape of a tensor as an int list."""
return tensor.get_shape().as_list() | 94c17b3def7466a7c24bff542d2455beefd55df3 | 638,603 |
def tipo(inpt, keep_module: bool = True) -> str:
"""
Return the name of an object's type
params:
keep_module
If set to False, the name of the class will be returned without any explicit reference to package nesting
"""
if isinstance(inpt, type):
inpt = str(inpt)
if ke... | 3773e6a51e77b1eb53eb2010f1b5a9407c7bde26 | 638,607 |
def replace_corrupted_instruction(script, instruction_index):
"""
Return the copy of a script with the command (JMP or NOP) of a given instruction replaced.
"jmp" -> "nop"
"nop" -> "jmp"
"""
# Copy the script and get the instruction by index.
new_script = script.copy()
instruction = s... | 583f3cdd3dc7a05d232e2c87825c3e166b253535 | 638,611 |
from datetime import datetime
def commit_datetime_string(dt: datetime):
"""
Return a string representation for a commit's timestamp.
Args:
dt: datetime object with tzinfo
Returns:
string representation (should be localized)
"""
return dt.strftime("%c %z") | 0e5a1ba69bd185029c175413e0cade9af5933bc3 | 638,619 |
import copy
def get_settings(settings_module):
"""
Get a copy of the settings (upper-cased variables) declared in the given settings module.
:param settings_module: A settings module
:type settings_module: module
:return: Dict of settings
:rtype: dict[str, object]
"""
return copy.deep... | e9cc00c69a8a963ec9dfdb99a2f5759c91083f1f | 638,623 |
import random
def generate(number_of_seeds, seed=None):
"""Uses pythons random integer generator to create a set of unique random
seeds.
Parameters
----------
number_of_seeds : int
number of seeds to generate.
seed : int, optional
The random seed to intialize the generator wit... | 3dce8df5d7d2d645a1734e58dcd10cd01ee2af02 | 638,629 |
def normalize_images(images):
"""Normalize image values."""
return images.float().div_(255.0).mul_(2.0).add_(-1) | e5d2b9a08b8667f96da8e4f24efb645ddc74d464 | 638,634 |
import time
def wait_for_task(task, timeout=300):
"""
Wait for a task to complete
"""
timeout_time = time.time() + timeout
timedout = True
while time.time() < timeout_time:
if task.info.state == 'success':
return (True, task.info.result)
if task.info.state == 'error... | 30c1e8e589246c2da0e42850638e59e304e0688c | 638,636 |
from importlib import import_module
def get_code(path):
"""
Given "core.utils:get_code", imports the module "core.utils" and returns
"get_code" from it.
"""
module_name, member_name = path.split(':')
module = import_module(module_name)
return getattr(module, member_name) | 6f9b64e3d8c488f467355663fde0e220864c6256 | 638,637 |
import math
def ceiling(x, y):
"""
Returns number rounded up, away from zero, to the nearest multiple
of significance. For example, if you want to avoid using pennies in
your prices and your product is priced at $4.42, use the formula
ceiling(4.42,0.05) to round prices up to the nearest nickel.
... | 5d79ce3e91c48123c612cc91b55a0737caa96105 | 638,639 |
def map_dtype_name_to_pixel_type(dtype_name):
"""
Performs mapping of ndarray underlying data type to
proper pixel data type
:param: dtype_name: name of data type representation
of underlying np.ndarray
:return: String representing the correct pixel data type
"""
if dtype_name == 'float1... | 763a36ff1fb02abf820cb9e5462809c210309867 | 638,642 |
import re
def is_valid_file_category_id(category_id):
"""
Validates a file lifecycle category ID, also known as the categories "category-ext-name".
A valid category ID should look like: category-00000001 - It should
always start with "category-" and end with 8 hexadecimal characters in lower
case.... | 75b074120fbdd612814a140f056163486a09ade3 | 638,643 |
def normalize_severity_at_baseline(mean_pre_test_treatment, maximum_on_clinical_scale):
"""Normalizes the pre-test scores in order to include them in the SAOB analysis.
Parameters
----------
mean_post_test_treatment: float
Mean score after the treatment.
maximum_on_clinical_sca... | 436076c60bfa26c49cec298c562074f9e5c6fa15 | 638,644 |
import ipaddress
def _calculate_address_pool(addrmask, ipv6=False):
"""
Return a pool of addresses contained in the network.
@param addrmask: Network in IP/mask format.
@return: A list of ip addresses
"""
if ipv6:
netobj = ipaddress.IPv6Network(addrmask, strict=False)
else:
... | 3fb1b60324e47e38c2f74caf9f47d02dcb30cb9f | 638,646 |
def _must_be_updated(today_date, last_modification, allowed_age):
"""
:param today_date: Today's date.
:type today_date: datetime.date
:param last_modification: Date of file's last modification.
:type last_modification: datetime.date
:param allowed_age: Maximum age allowed between today and last... | ba555bf7a80eb5a8ad489fff5154693621a75767 | 638,648 |
import inspect
def extract_module_name(obj, full=False):
"""
Get the name of a module for an object.
"""
properties = inspect.getmembers(obj)
for name, value in properties:
if name == '__module__':
if full:
return value.split('.')[-1]
else:
... | e1742628b19e0e961496016e53ee484e9aff8aae | 638,653 |
def product_first_image_alt(product):
"""
Returns main product image alt for seo
"""
all_images = product.images.all()
alt_text =all_images[0].alt if all_images else ''
return alt_text | d747cc6027b074754934126884fa35ebe123d001 | 638,656 |
def stripFilename(fname):
""" Strip the path and extension from the filename. """
return str(fname).split("\\")[-1].split(".")[0] | a382fc89cca21dfe3bd0d7380f3e90653f508ba6 | 638,657 |
import math
def decantor(z):
"""Inverse Cantor"""
w = math.floor(math.sqrt(8 * z + 1) / 2 - 0.5)
t = ((w + 1) * w) / 2
y = z - t
x = w - y
return int(x), int(y) | 1f26eed41926aea81be6e476064f5ad7ae43b418 | 638,658 |
def clean_headers(hdr_tuples, invalid_hdrs=None):
"""
Given a list of header tuples, filters out tuples with empty header names
or in the specified invalid header names list.
"""
if hdr_tuples is None:
return list()
clean_tuples = list()
for entry in hdr_tuples:
if not entry[... | 509bbbbf1e9dd55ac751a5e436446964678a1e65 | 638,659 |
def flatten_batch(x):
"""
Flattens a batch of arrays to one dimension.
Args:
x (numpy.ndarray): A batch of arrays to be flattened.
Returns:
numpy.ndarray, a flattened one dimension array.
"""
return x.reshape(x.shape[0], -1) | dcd6ac8d50269f695e5df75c9b0eb25da04ddc41 | 638,661 |
def generate_lhs_tokens(distribution, rng):
"""Generate a set of tokens to build production rules for."""
# Iteration order over a set is apparently non-deterministic, so use a list instead...
tokens = []
token_pool = list(distribution.keys())
token_probabilities = list(distribution.values())
wh... | c5d8498260f02c4a19021f8736a466a7b9f94106 | 638,666 |
def Likelihood(evidence, hypo):
"""Computes the likelihood of the evidence assuming the hypothesis is true.
Args:
evidence: a tuple of (number of heads, number of tails)
hypo: float probability of heads
Returns:
probability of tossing the given number of heads and tails with a
... | 6a0f1ae160a3b0b24b522d5dc0a645d2d39ff1cc | 638,668 |
def check_permissions(required_permission, payload):
""" Check if required permission exists in the verified token's payload.
Parameters:
required_permission (string|list):
A string describing the type of permission.
e.g: get:drinks, post:drinks, ['get:drinks', '... | 814405147d1864b8dac1895d56bd0a72fa453def | 638,669 |
def detect_publisher(fstring):
""" Detect the publisher of a html file by searching for unique strings
:param fstring: document HTML or XML text
:type: byte string
:returns: publisher name as a unique string
"""
if b'<meta name="dc.Identifier" scheme="doi" content="10.1021/' in fstring:
... | cc79505a3e514cb7aa631483e7da6d18b1f14ba4 | 638,672 |
def round_to_two_places(num):
"""Return the given number rounded to two decimal places.
>>> round_to_two_places(3.14159)
3.14
"""
# Replace this body with your own code.
# ("pass" is a keyword that does literally nothing. We used it as a placeholder
# because after we begin a code bloc... | 822a768208a871ce0d7e01d9bfdf64c49233f2bc | 638,675 |
def _make_dictnames(tmp_arr, offset=0):
"""
Helper function to create a dictionary mapping a column number
to the name in tmp_arr.
"""
col_map = {}
for i,col_name in enumerate(tmp_arr):
col_map.update({i+offset : col_name})
return col_map | 7bdd5222446a6c47ad547103be4c07dda0c93d4e | 638,676 |
def get_ids(df_cat, prd_col, cli_col):
"""
Obtain Client and Produtct IDs positions
Parameters
----------
df_cat: pandas Data Frames
Representation of df_long, with prd_col and cli_col as categories.
prd_col: str
Name of the column containing the ProductIDs.
cli_col: str
... | 74f2bbda27e0335a18a04fa9fe7250b05ce2c5a7 | 638,678 |
def sphinx_role(record, lang):
"""
Return the Sphinx role used for a record.
This is used for the description directive like ".. c:function::", and
links like ":c:func:`foo`.
"""
kind = record["kind"]
if kind in ["class", "function", "namespace", "struct", "union"]:
return lang + ... | 68db234074179cb51af45ea9a2d5098a9d5311ac | 638,684 |
def card_name(value, suit):
"""
Constructs a name for the card, using the given value,
and suit.
:arg str value:
The value to use.
:arg str suit:
The suit to use.
:returns:
A newly constructed name, using the given value & suit.
"""
if value == "Joker":
... | 6f2db64964e99840aab73f2124c9f9a862cb7a72 | 638,691 |
def extract_string(str, start, end):
""" Returns the string between start and end. """
s = str.find(start)
if s < 0:
return None
slen = len(start)
e = str.find(end, s + slen)
if e < 0:
return None
return str[s + slen:e] | cc1495579383924eca4d96d644c3aacbdaccb459 | 638,692 |
def gf_lshift(f, n, K):
"""
Efficiently multiply ``f`` by ``x**n``.
**Examples**
>>> from sympy.polys.domains import ZZ
>>> from sympy.polys.galoistools import gf_lshift
>>> gf_lshift([3, 2, 4], 4, ZZ)
[3, 2, 4, 0, 0, 0, 0]
"""
if not f:
return f
else:
return ... | cbc00d595534c0f7816d6604756deb712fdb5045 | 638,698 |
import torch
def _signed_area(path: torch.Tensor) -> torch.Tensor:
"""
Calculates the signed area / Lévy area of a 2D path. If the path is closed,
i.e. ends where it starts, this is the integral of the winding number over
the whole plane. If not, consider a closed path made by adding a straight
li... | 47716d51f981613add08d04ed8d01d5794c89fd6 | 638,701 |
def readKeyValueCSV(filename):
"""
Reads a key-value csv file and returns the contents as a python dictionary. @filename is the path to the file.
returns: file contents as <dictionary>
"""
# Resultant dictionary.
result = {}
# Read file and collect key-value pairs into result.
with open(filename, "r") as... | 57ad73af0b85e803cff7722c411ffc617b9c04e3 | 638,706 |
def total_rain(rain_hours: list) -> int:
"""
Sum up the rain mm from list of rain hours
"""
if len(rain_hours) > 0:
return round(sum([list(x.values())[0]['1h'] for x in rain_hours]), 2)
else:
return 0 | 72e26bdb2600eaaa321a532712dd1a815ba01789 | 638,707 |
def match(p1, p2, common):
"""Return whether clauses in common match.
Arguments:
p1 {np.array} -- first possibility
p2 {np.array} -- second possibility
common {(str,int,int)} -- common clauses
Returns:
True/False -- Do clauses in common match?
"""
for c in common:
... | 224d54c21e1613f9813b725e721b8033ee28694b | 638,710 |
def write_int_ranges(int_values, in_hex=True, sep=" "):
"""From a set or list of ints, generate a string representation that can be
parsed by parse_int_ranges to return the original values (not
order_preserving)."""
if not int_values:
return ""
num_list = []
int_values = iter(sorted(i... | 7cd69925887127d3058f3184640f0755b541fe58 | 638,712 |
def build_flow(steps):
"""Builds a flow from a list of steps, by chaining the steps according to their order in the list.
Nested lists are used to represent branches in the flow.
Examples:
build_flow([step1, step2, step3])
is equivalent to
step1.to(step2).to(step3)
build_fl... | 5ed2a0c02f93aca608a8cd161400711bfc00430f | 638,714 |
import time
def toc(tic):
"""Returns the time since 'tic' was called."""
return time.perf_counter() - tic | 976cdeb30a723a8667ae2e0d86a4270ad356d634 | 638,715 |
import inspect
def _schema_get_docstring(starting_class):
""" Given a class, return its docstring.
If no docstring is present for the class, search base classes in MRO for a
docstring.
"""
for cls in inspect.getmro(starting_class):
if inspect.getdoc(cls):
return inspect.getdoc... | 8c2bf48da22ebea9f440d51e903522561b23920e | 638,716 |
def values_to_dict(values):
""" Each row from the spreadsheet is converted to a dict using the first row as the keys.
:param values: a list of lists containing the values of a spreadsheet loaded with the sheets api.
The first row is considered to contain the header information.
:returns: a list of d... | 28cc31d0af662937765d152295f8deea173542ec | 638,718 |
def human_time(s):
"""Convert floating-point seconds into human-readable time"""
if s < 60.0: return "%.3f" % s
m = int(s) / 60
if m < 60: return "%d:%06.3f" % (m, s % 60)
return "%d:%02d:%06.3f" % (m // 60, m % 60, s % 60) | 5ab95271223ab65d44fce3c09e4f77e51e9be342 | 638,729 |
def composition(f, g):
"""Return a composition of two functions
"""
def fg(arg):
return g(f(arg))
return fg | 2e1f99de6250b82bcc63a4f4697cfe3887dc7243 | 638,733 |
import math
def calculate_fuel_requirement(mass):
"""Calculates the fuel requirement
based on the given mass. (Part 1)
Parameters:
mass (int): mass of the module
Returns:
int:Fuel required
"""
return math.floor(mass / 3) - 2 | 4456602dd91a0cb897f3ecdcdc01252795bb2dd7 | 638,734 |
from typing import List
import struct
def unpack_uint64s(data: bytes) -> List[int]:
""" Unpack a series of integers that were packed with pack_uint64."""
if len(data) == 0:
return []
return list(x[0] for x in struct.iter_unpack(">Q", data)) | 1685ed2db9dd903e06578d9a8e98e6071cc013a9 | 638,738 |
def unique_responses(group_responses: list) -> list:
"""
From the list of group responses, pick out the unique responses.
Args:
group_responses [list] : A list of of lists. Each sub-list contains each
groups' person's responses.
Returns:
list [str] : A list of lists, with d... | e3e30198cb5743fd70a68f1cda8d561547d6d7c0 | 638,740 |
from typing import OrderedDict
def read_basis(fname):
"""
return basis names from file (often named as basis.txt). Return a dict. key: basis name. value: basis index, from 0
"""
bdict = OrderedDict()
if fname.endswith('.win'):
with open(fname) as myfile:
inside = False
... | f03f01a610c093e50ad7a0b737491bdc3cb870d8 | 638,741 |
def calc_tot_orbits(n_orbit_dict):
"""Calculate the total number of direct and indirect orbits in
n_orbit_dict.
Parameters
----------
n_orbit_dict : dictionary
A dictionary where each key is an object in the system and each value
is a tuple of 2 values. The first represents the numb... | 07a9dbc11866b9710503ef8fe75297c14aa0b6c9 | 638,743 |
from datetime import datetime
def getyrdoy(date):
"""Return a tuple of year, day of year for a supplied datetime object.
Parameters
----------
date : datetime.datetime
Datetime object
Returns
-------
year : int
Integer year
doy : int
Integer day of year
"... | 506e68bd9dfd47e19771f197dbbf0f93791c30d9 | 638,745 |
def preprocess_df(df):
"""
Select the english captions and extract only the desired columns from the dataframe like 'Name' and 'Description'
df: dataframe which contains the captions
"""
df = df[df['Language'] == 'English'].copy()
df['Name'] = df[['VideoID', 'Start', 'End']].apply(lambda x: x['... | cf73810ba2f152278cffe0acced1b9d454bc75e5 | 638,752 |
from typing import Dict
import re
def update_weight_name(repl_patterns: Dict[str, str], weight_name: str) -> str:
"""Updates weight names according a dictionary of replacement patterns."""
# Create a regular expression from all of the dictionary keys
regex = re.compile('|'.join(map(re.escape, repl_patterns.keys... | bbf382e69501b052a5eb0aa53adf1a53fc735e6f | 638,754 |
def _RemoveRedundantHandlers(handler_list):
"""Removes duplicated or unnecessary handlers from the list.
If a handler's pattern and functionality are fully matched by another handler
with a more general pattern, we do not need the first handler. At the same
time, we remove duplicates.
Args:
handler_lis... | 9fece01e66de352e16590c2dd4aa0942c8452e7c | 638,759 |
import aiohttp
async def request(url, *, headers=None, **kwargs):
"""Base GET request in case you need more control over GET requests.
Params
=======
headers: dict (Optional)
kwarg: kwargs (Optional)
Returns
=======
Response: aiohttp Response object
"""
async with aiohttp.Cli... | 5e1dc33b0667b0a742c7062e5347c43dc4c3d4c0 | 638,760 |
def _date_within( some_date, start_date, end_date ):
"""
check if start_date <= some_date <= end_date ,
considering inequality to be true if either
start_date or end_date is None
"""
result = True # start with a truth assumption
if start_date is not None:
result = resu... | ba9aa20fce1d981cab8401a84b5f1ab45229f424 | 638,762 |
import requests
def aud_to_usd(aud_amount, date):
"""Convert the AUD amount to USD."""
r = requests.get("https://api.fixer.io/{}?base=USD".format(date))
j = r.json()
rate = j["rates"]["AUD"]
return aud_amount / rate | 36f3849382a0c0cc8d1616303c6695b7b32a0782 | 638,764 |
from typing import Tuple
from typing import Any
from typing import List
def unpack_response(response: dict) -> Tuple[Any, List[str]]:
"""Unpack response from dictionary and fetch ranking and keywords."""
assert isinstance(response, dict), "Empty response. Try again."
rankings = [*response[[*response][0]]... | f4d985be4d0d2e7322c85eee1aab8d861c91cb15 | 638,765 |
def _preprocess(sentences, preprocess_pipeline, word_tokenize=None):
"""
Helper function to preprocess a list of paragraphs.
Args:
param (Tuple): params are tuple of (a list of strings,
a list of preprocessing functions, and function to tokenize
setences into words). A parag... | 9f44962a5ba4a66523beb40feb0a25b63d1dc528 | 638,770 |
def extract_task_ids(project_data):
"""
Extract from project data the list of task id
:param project_data: Dictionary of project data of a HOT tasking manager project
:return:
"""
tasks_ids = list()
for feature in project_data['tasks']['features']:
tasks_ids.append(feature['propertie... | bb276370685d977a98a66195b97be051a20a2d87 | 638,778 |
def _FirewallTargetTagsToCell(firewall):
"""Comma-joins the target tags of the given firewall rule."""
return ','.join(firewall.get('targetTags', [])) | c75ccc9caa8893c5371a4be8e9474b089a7eefca | 638,783 |
def WMSBBOX(region):
""" Return the WMS BBOX query string for this region
Returns:
string: BBOX=w,s,e,n
"""
(n,s,e,w) = region.NSEW()
return 'BBOX=%f,%f,%f,%f' % (w,s,e,n) | 83430c38393c68d5865355ecf3e8eeeecfe56014 | 638,790 |
def GateBranches(x, **unused_kwargs):
"""Implements a gating function on a (memory, gate, candidate) tuple.
Final update is memory * gate + (1-gate) * candidate
This gating equation may also be referred to as Highway Network.
Highway Networks: https://arxiv.org/abs/1505.00387
Args:
x: A tuple of (memor... | bb72b6de2af808929e7bb24cb31bfa34d5791c41 | 638,792 |
def text(meta):
"""
Returns the meta message's text as a string.
"""
return meta[3].decode('ascii') | 47dee2ab4606a18f9418dc45b26b9d28269a4abb | 638,793 |
def get_r12_squared(r1, r2):
"""Get the distance between two centers in Cartesian space."""
return (r1[0] - r2[0])**2.0 + (r1[1] - r2[1])**2.0 + (r1[2] - r2[2])**2.0 | 63e792e25e5be209b8a5c783307f067f387c260a | 638,794 |
def hierarchical_label(*names):
"""
Returns the XNAT label for the given hierarchical name, qualified
by a prefix if necessary.
Example:
>>> from qixnat.helpers import hierarchical_label
>>> hierarchical_label('Breast003', 'Session01')
'Breast003_Session01'
>>> hierarchical_lab... | 91124a21ef117c2aa0b3ae45c078cd1e8f4a3314 | 638,797 |
def train_test(df):
"""
split into train and test set
train contains Jan 1, 2018 through July 31, 2018
test contains August 1, 2018 through September 28, 2018
:param df:
:return:
"""
df = df[df['Date'] >= '2018-01-01']
train = df[df['Date'] < '2018-08-01']
test = df[df[... | 665657b8daa804762297063bc4b2fd14c2a5155f | 638,798 |
import re
def is_regex(tentative_regex: str):
""" Returns true if the argument is a valid python regex, and false otherwise. """
if len(tentative_regex) == 0:
return False
try:
re.compile(tentative_regex)
return True
except re.error:
return False | adcf2693bbbdd3e83344dfd4ac393dc8342a1372 | 638,799 |
import codecs
def load_vocab(vocab_path):
""" Loading a vocabulary file
:param vocab_path: Path to vocabulary file
:return: Array contains words
"""
with codecs.open(vocab_path, encoding="utf-8") as fobj:
vocab = fobj.readlines()
return vocab | 2e71a6693c2b174413ccc4447d7387a8cfb43dc1 | 638,801 |
import math
def ceil(number):
"""
Return the ceiling of a number as an int.
This is the smallest integral value >= number.
Example:
>>> ceil(1.5)
2
Arguments:
number (float): A numeric value.
Returns:
int: Smallest integer >= number.
Raises:
TypeError: If argument ... | c0e6e8a4c25d1e9b94b51ee9da6c436c6e9d0cc4 | 638,804 |
def _combine_field_specs(field_specs, exclude_fields):
"""
take a list of FieldSpec objects and return a sorted list where field is unique
and fields in exclude_fields are removed, and where the first mention of a
field in field_specs will win out over any repeats.
"""
combined_field_specs = {... | fa9a8f92dbe31755cecfeecad2c2813b9c6be0a7 | 638,808 |
def halflife_to_phi(rho, dt=1):
"""Convert half-life to the AR(1) propagation parameter phi"""
phi = 0.5 ** (dt / rho)
# st_dev = st_dev * np.sqrt(1 - phi**2)
return phi | 9805166539ce2ca9c3f4f0ede163ab7797573497 | 638,813 |
def remove_unreadable_characters_at_start(string):
"""
Removes non ASCII characters from the string start as eggPlant files often begin with some strange symbols.
The string gets also stripped (blank characters at start and end will be removed)
:param string:
:return: the processed string
"""
... | c8b4ebc8d9c39d57937a460a8bdd38123555d2f2 | 638,823 |
def coin_total_usd(coin: str, amount: float, tickers: dict) -> float:
"""
Get value of coin in USD
:param coin: coin symbol from balance
:param amount: total amount of coin from balance
:param tickers: raw tickers fetched from binance
:return: value of coin in USD as float
"""
price_in_b... | 31ed3c6d4f5d143e294f66f9d2da3e820c0c5e47 | 638,828 |
import torch
def cross_entropy(pred, target):
"""
"Proper" cross entropy between distributions.
:param pred: predicted logits
:type pred: torch.autograd.Variable
:param target: target distributions
:type target: torch.autograd.Variable
:return: loss
:rtype: torch.autograd.Variable
... | eb566bfb94b428bceafa18c9ff5eb50177d23667 | 638,829 |
def find_default_vpc(session, region_name):
"""
Looks for every default VPC in a region
:param session: Boto3 Session
:param region_name: The region name to look in
:return: list of vpc id's
"""
result = []
client = session.client("ec2", region_name)
response = client.describe_vpcs(
... | af77133ab64ec5f3f59335e085c83927c56093c2 | 638,831 |
import math
def to_polar_coordinates(x, y):
"""Convert the 2D pixel coordinates to polar coordinates
:param x: x coordinate of the point
:param y: y coordinate of the point
:returns: tuple -- (r,phi) of the point as polar coordinates
"""
theta = math.atan2(y, x)
if theta < 0:
thet... | 7ca0596c6db352b42566db2d88580478435204b1 | 638,833 |
def run_replace(block: str, replace_dict: dict) -> str:
"""Replace routine for dealing with n-grams.
:param block: Contains the text block replacement is done on
:param replace_dict: {token: replacement_token}
:return: Occurrences of token replaced with replacement_token
"""
for k in replace_d... | cc47686d37df9dbdfcc73b2118a1305700f3c9a2 | 638,834 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.