content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_cropped_array(png_array):
"""Crop the array neatly to the center 100x100 points
Notes:
- this has only been tested on 1000x1000 size lattice images
"""
xlen, ylen, _ = png_array.shape
cropped_png_array = png_array[0.4165*xlen:0.5143*xlen, 0.4627*ylen:0.5623*ylen, :]
return croppe... | c137b8055ada63bc5422380bfc3694d12fa40c5b | 616,381 |
def move_to_ctx(arr, ctx):
"""Move a nested structure of array to the given context
Parameters
----------
arr
The input array
ctx
The MXNet context
Returns
-------
new_arr
The array that has been moved to context
"""
if isinstance(arr, tuple):
re... | 111f525c900c931661c5f969ac79e74ad9100a83 | 616,384 |
import hashlib
def calc_package_index_hash(deb_names):
"""
Calculates a hash of all the given deb file names. This is deterministic so
we can use it for short-circuiting.
"""
md5 = hashlib.md5()
md5.update("\n".join(sorted(deb_names)).encode('utf-8'))
return md5.hexdigest() | 67c897959bc1e979c598da9d875bec298f9c1bec | 616,387 |
def _is_via_hub(node):
"""Check if a node is a Via Labs hub.
The topology of this device is a 4-port hub,
with another 4-port hub connected on port 4.
"""
if '2109:2812' not in node.desc and '2109:0812' not in node.desc:
return False
if not node.HasPort(4):
return False
return ('2109:2812' in node... | 90aedec81efd9e5dcbf90a8d725c9e642fa008b5 | 616,389 |
def CheckAttr(f):
"""Automatically set mock_attr based on class default.
This function decorator automatically sets the mock_attr keyword argument
based on the class default. The mock_attr specifies which mocked attribute
a given function is referring to.
Raises an AssertionError if mock_attr is left unspec... | 4d6fd797e854339e53f5f9d40c17f5420c6940c9 | 616,390 |
import math
def lsf_format_bytes_ceil(n, lsf_units="mb"):
""" Format bytes as text
Convert bytes to megabytes which LSF requires.
Parameters
----------
n: int
Bytes
lsf_units: str
Units for the memory in 2 character shorthand, kb through eb
Examples
--------
>>> ... | 7440e1994d8e8d89382758916087b1cc805b1fa3 | 616,400 |
def rmin(a, b):
"""
Min function for real numbers
Parameters
----------
a: scalar
b: scalar
Returns
-------
scalar
"""
# seems to be much faster than the built-in
return a if a < b else b | c41bcc67de8283658cdb7a329abdbcf914e13906 | 616,401 |
def get_user_printable_name(user, errstring="???"):
"""
Gets name of user in printable form.
:param user: user object
:param errstring: string to return if name could not be resolved
:return: user.nick if exists, user.name otherwise (if exists), errstring if nick and name are missing
"""
i... | 6e56c04c2bb199e330fabb0fa349418d4fb48cbd | 616,402 |
def define_interval(weight, eps, method):
"""
:param weight: element weight
:param eps: measurement error
:param method: method for interval construction (0 - error is absolute, 1 - error is relative)
:return: interval value
"""
if method == 0:
return weight - eps, weight + eps
e... | 0ed0b352e70fea493f9cabb4353f4e7b520f6ddb | 616,405 |
def _infer_n_folds(cv_results):
"""
Gets the number of CV folds from a cv_results object
Parameters
----------
cv_results: dict
The cv results.
Output
------
cv: int
The number of cv folds
"""
split_keys = [k for k in cv_results.keys()
if k.spl... | d8e1010f0ac45711a44ae74a59aea5168cb6011c | 616,406 |
import random
import hashlib
def md5(*args):
"""Generates MD5 based on the provided string or a random int"""
value = ""
if len(args) > 0:
value = args[0]
if value == "":
value = str(random.getrandbits(128))
return hashlib.md5(value.encode('utf-8')).hexdigest() | 0d0becac0fad0aca2dcc79923f580ee7e6f06d16 | 616,407 |
def cigarops2string(cigarOps):
"""
Takes in a list of cigar tuples (c.op in the set MID, c.size is an int)
and returns a cigar string (all concatenated together)
"""
# common case
if len(cigarOps)== 1:
return str(cigarOps[0].size) + cigarOps[0].op
# general
return "".join( [str(c.size) + c.op for c ... | 5415ccd562ab3fe02e4ddf3709abd43e58fb3131 | 616,409 |
def checkFilter(filters, record):
"""Check record against filters."""
for i in filters:
if i.http:
if not record.http:
return False
value = record.http
else:
value = record.header
string = value.get(i.k, None)
if not string or ... | bb3461d617282f70893e1757daa836d0ac5adc04 | 616,414 |
def contains_3_consecutive(list_of_nums):
"""Return True if the list contains 3 consecutive numbers each increasing by 1."""
for i in range(len(list_of_nums) - 2):
if (list_of_nums[i+1] == list_of_nums[i] + 1 and
list_of_nums[i+2] == list_of_nums[i] + 2):
return True
return ... | 7f0de2108d69f9bbdd56a45461e521125d964603 | 616,415 |
def i_to_the_power(k):
"""
Return the sign (-1 or 1) and minimal integer power (0 or 1) of i to an
integer power.
"""
sign = {0: 1, 1: 1, 2: -1, 3: -1}[k % 4]
imaginary = k % 2
return sign, imaginary | 31f3aa62b3a71b36dda4ecb0828c683d2d4ac9e0 | 616,417 |
from typing import List
from bs4 import BeautifulSoup
def extract_flags(ci_attrs: str) -> List[str]:
"""
Get the course flags from the ci_attrs field.
Parameters
----------
ci_attrs:
the field from the Yale API response.
Returns
-------
flag_texts:
Flags (keywords) fo... | c72145e6a80e004b0439a735070df46bdb1d954b | 616,419 |
def version_number_str(major, minor=0, patch=0, prerelease=None, build=None):
"""
Takes the parts of a semantic version number, and returns a nicely
formatted string.
"""
version = str(major) + "." + str(minor) + "." + str(patch)
if prerelease:
if prerelease.startswith("-"):
... | 8004ef5bc67e609e61faafff87ca63bd63c1b492 | 616,420 |
def health() -> bool:
"""Shows that the worker is still receiving messages.
"""
return True | b4019e96a73156c527f50ee39313ec64bcb78456 | 616,421 |
from typing import List
import functools
import operator
def flatten(lst: list) -> List:
"""flatten the list of lists.
:param lst: list of lists
:return: flattened list
"""
return functools.reduce(operator.iconcat, lst, []) | 009affc4a28288402bbcbdf70509a2d7fbc4725b | 616,425 |
def surrounding_tiles(tile_x, tile_y, remove_outside_tiles=False):
"""Return the 8 tiles surrounding the given tile.
Parameters:
tile_x: X coord of tile
tile_y: Y coord of tile
Returns:
List of two tuples (x, y) of surrounding tiles.
The list will exclude the given tile it... | ec71180b92e63fa2cd55aea1a308f5f9fdf9b97a | 616,426 |
def add_xml_data(**property_paths_types):
"""Add properties to a class that access data using :meth:`get_data`.
This provides an alternative usage to directly calling
:meth:`ActivityElement._add_data_properties` below a class definition.
Args:
**property_paths_types: kwargs mapping property_name : tuple(... | a5359482890d79f7c4d55b9370499ad314cefb0f | 616,427 |
from pathlib import Path
from warnings import warn
def git_rev(repo):
"""
Get the git revision for the repo in the path *repo*.
Returns the commit id of the current head.
Note: this function parses the files in the git repository directory
without using the git application. It may break if the ... | 877fa58bfeaadefc42920c2695af03117fe80fd3 | 616,431 |
def selection_sort(arrayParam):
"""
Sort a list using selection sort algorithm. Run time: O(n**2)
"""
position = 0
array = arrayParam[:]
for k in array:
smallest = None
subPosition = position
smallestIndex = None
# Getting smallest value and index
for i in... | 7891c733fe3029f474855afcb03dafc5636a8cb3 | 616,432 |
import re
def parse_range_header(range):
"""
Parse a range header as used by the dojo Json Rest store.
:param str range: The content of the range header to be parsed.
eg. `items=0-9`
:returns: A dict with keys start, finish and number or `False` if the
range is invalid.
"""
m... | 3223ceda13a2e6d2ad7112f154613daba787591a | 616,434 |
def has_children(element):
"""
Find out whether a xml element contains any children.
The lxml native approach with len is a bit confusing literaly.
Args:
element: lxml.etree.Element
Returns: boolean
"""
return bool(len(element)) | bec9ae397b4c73806aa54ff479f6d959ad6df516 | 616,435 |
def sir_dydt(t, y, beta, gamma, N):
"""
Defines the differential equations for the SIR model system.
Arguments:
t : time
y : vector of state variables:
y = [S, I, R]
beta, gamma, N : model parameters
"""
S, I, R = y
# Output array of form f = (S',... | 731f99ebaa4ac5f58178effb6456b24fd3ad78bd | 616,436 |
def find_by_attribute(element, name, value):
"""Find children of 'element' where attribute 'name' is equal to 'value'.
"""
return [child for child in element if child.get(name) == value] | da0720c44304fc1c5f7981357a69c35ff33c2020 | 616,438 |
def domains(client):
"""
Get list of domains owned by current reseller.
"""
return client.domain.all() | 82253a098178252faebf68156e45d28a24b92938 | 616,440 |
import math
def percentile(arr, P, is_sorted=False):
"""
NOTE: Returns the first element that is GREATER than the percentile
Inputs:
-------
arr: Array to be sorted
P: Percentile desired [0,1]
Options:
-------
is_sorted: [False] Whether or not the list is already sorte... | 6700b7b7ad174d28d84420e20d06e9fb5dc2bc47 | 616,443 |
def cpu_name(proc):
"""Return CPU name"""
items_count = len(proc)
if items_count == 1:
return proc[0]
if items_count >= 3:
return proc[2]
return "Unknown" | 62db71940bae78982a3035f7df77d6291fd47120 | 616,445 |
from datetime import datetime
import pytz
def get_local_time_from_utc(user_datetime: datetime, user_tz='UTC'):
"""
Converts a datetime from UTC into the user's timezone
:param user_datetime: the datetime in the user's TZ
:type user_datetime: datetime
:param user_tz: the user's Timezone
:type u... | c0b85b6be247632e959477bcb71f1ca8114d4c23 | 616,447 |
def generate_absolute_path(home_directory: str, bucket_name: str) -> str:
"""
Generate absolute S3 path in the format that SFTP Transfer accepts.
:param bucket_name: bucket;
:param home_directory: directory in the bucket.
:return: path.
"""
return f'/{bucket_name}/{home_directory}' | dc50f7b6e1e0922607b24be49ed96d7ec2bea3be | 616,449 |
def check_options(cart_option, baseprice_option):
"""
Checks if the options of a product in the cart matches with the options of the given
product in the base-price file.
:param cart_option: The dict containing options provided with the product in the cart
:type cart_option: dict
:param basepric... | 6c42e5b32addb13bf62bc91b52277e9c29d8569b | 616,454 |
def create_scheduler_resources(scheduler, base, goal):
"""Return a dictionary with scheduler resources.
This function will take a dictionary 'base', which contains scheduler resource settings that can be set for the
'resources' key in the 'options' input of a CalcJob, and update it with target scheduler re... | 1a587240f7fce149770f33aece2ddc4eec4c7d59 | 616,456 |
def set_mail_from(message):
"""
Returns a string to be used to fill the 'from' field of and email
If no from address is provided in the html form, return 'from_default'
"""
# If a from address is included in html form, return it
if 'mail_from' in message and message['mail_from']:
return ... | 21472f32805e6a970267b88bd3dcb74f138bdb23 | 616,458 |
def _get_name(type_, value):
"""Return the name for the given value of the given type_.
The value `None` returns empty string.
"""
return type_._VALUES_TO_NAMES[value] if value is not None else "None" | 6bfba4372adf10fec5c61873e6b3bf27b46490e0 | 616,462 |
def calc_euclidean_gcd(left: int, right: int) -> int:
"""Find greatest common divisor using Euclidean Algorithm."""
if right == 0:
return left
return calc_euclidean_gcd(left=right, right=left % right) | e23ef880804777c6965921d5917ce0d1b1a0d6e6 | 616,467 |
import torch
def batch_square_vector(vector, M):
"""
Compute x^T M x
"""
vector = vector.unsqueeze(2)
return torch.bmm(torch.bmm(vector.transpose(2, 1), M), vector).squeeze(2) | e23589efea1a61932fc7620334e0236e2a4e2158 | 616,468 |
def to_camel_case(snake_case):
"""
Convert snake_case string to camelCase
:param snake_case: snake_case string to convert
:type snake_case: str
:return: camelCase string
:rtype: str
"""
words = snake_case.split('_')
return words[0] + ''.join(x.capitalize() for x in words[1:]) | f1faed05d478b16ce9cb09de5455fcc16db2d8bb | 616,477 |
def is_han(c):
"""Return true if the input is a han character, false otherwise"""
return 0x4E00 <= ord(c) <= 0x9FFF | c244a1abd1a6603a3ff5fdb9e8baa17fcf6b7ca4 | 616,479 |
def Unzip(iterable):
"""Unzips specified iterable of pairs to pair of two iterables.
This function is an inversion of the standard `zip` function and the following
hold:
* ∀ l, r. l, r == unzip(zip(l, r))
* ∀ p. p == zip(unzip(p))
Examples:
>>> Unzip([("foo", 1), ("bar", 2), ("baz", 3)])
(["f... | d5f59344b028c02ca80f2772eaa12d015e1c3291 | 616,482 |
def dot(origin, p1_end, p2_end):
"""Return dot product of (origin, p1_end) and (origin, p2_end)."""
ux, uy = (p1_end[0] - origin[0], p1_end[1] - origin[1])
vx, vy = (p2_end[0] - origin[0], p2_end[1] - origin[1])
return ux * vx + uy * vy | 7e7d9a6ef5b29e885acaea969af87ba8ad9d15c1 | 616,483 |
def tfidf2freqdoc(words_tfidf, doc_length=1000):
"""
語のtfidfに応じて頻度が大きくなるような文書を返す.文書は,日本語の語をスペース区切りにしたもの.
Args:
words_tfidf (dict):key:語, value:語のtfidf となる辞書 {word(str):tfidf(float)}
doc_length (int, optional): 文書の長さ. Defaults to 1000.
"""
# tfidfの和が1になるように正規化し,語数に換算する.
tfidf_sum... | 55823149631a8b287cbf70e67e1ce02a066c0492 | 616,484 |
def fill_with_label(sessions, label, start=None, stop=None, min_gap=.1):
"""fill gaps with a certain label, e.g., absence.
Args:
sessions: list of tuples
label: label str to be added in the gaps
start: starting time
stop: stopping time
min_gap: minimum gap length that ha... | 3bc24dcb0cdff92f3dab00a5aecc747219d8b58f | 616,485 |
def multiple_letter_count(phrase):
"""Return dict of {ltr: frequency} from phrase.
>>> multiple_letter_count('yay')
{'y': 2, 'a': 1}
>>> multiple_letter_count('Yay')
{'Y': 1, 'a': 1, 'y': 1}
"""
return_dict = {}
for letter in phrase:
if return_dict.get(letter):
... | 1bcdfcde609f163e6d23dbc78da3e8eb943144da | 616,486 |
import json
def render_json(tree, indent):
"""Converts the tree into a flat json representation.
The json repr will be a list of hashes, each hash having 2 fields:
- package
- dependencies: list of dependencies
:param dict tree: dependency tree
:param int indent: no. of spaces to indent ... | eefb9ac7e0f0d674200101f063629142182c8442 | 616,493 |
def PickHistoryName(args):
"""Returns the results history name to use to look up a history ID.
The history ID corresponds to a history name. If the user provides their
own history name, we use that to look up the history ID; If not, but the user
provides an app-package name, we use the app-package name with ' ... | 2cc6487d804b2bdb586c699a50421f60869a1e18 | 616,495 |
def escape_html(str):
"""Return an HTML-escaped version of STR."""
return str.replace('&', '&').replace('<', '<').replace('>', '>') | c4cf609163ece2f2a79d0ecbb943a45ca927ed74 | 616,498 |
def _create_rects(rect_list):
"""
Create a vertex buffer for a set of rectangles.
"""
v2f = []
for shape in rect_list:
v2f.extend([-shape.width / 2, -shape.height / 2,
shape.width / 2, -shape.height / 2,
shape.width / 2, shape.height / 2,
... | 8cd7cfbb52dd62be989f312c5bb5bccd690bc9b4 | 616,499 |
def _get_subclasses(classname):
"""Recursively obtains all subclasses of the given class."""
subclasses = []
for p in classname.__subclasses__():
subclasses.append(p)
subclasses.extend(_get_subclasses(p))
return subclasses | a5edde240c97d8c21109a055593ca488552affa3 | 616,501 |
import yaml
def generate_item_with_upstream_options(yaml_manifest, options) -> dict:
"""
Generate a VS/VSR item with an upstream option.
Update all the upstreams in VS/VSR
:param yaml_manifest: an absolute path to a file
:param options: dict
:return: dict
"""
with open(yaml_manifest) ... | 6c0e2d77dc64103bcc3f746c39748d2f01bc88f4 | 616,503 |
def twice(z):
"""
task 0.5.27
implement one line procedures def twice(z): return 2*z
"""
return 2*z | 3371e2cc3bca1c43e4daf46fec9b8dc0dc4d15c8 | 616,505 |
def remove_des(name):
"""
remove 'Class A Common Stock' and 'Common Stock' from listing names
"""
if name.endswith("Class A Common Stock"):
name = name[:-21]
if name.endswith("Common Stock"):
name = name[:-13]
return name | 3f4fb80d42c029e85b5354f226206df511911cc1 | 616,507 |
def _is_displayed(row, current_quarter, current_offset):
"""
Return true if message is for current quarter and current date
falls within the display range for a given message.
Message will display for 7 days.
"""
display_quarter = row[2]
display_offset = int(row[3])
return current_quart... | 9b5f7a067e06f4104a44d89e03c9afe3169fc99e | 616,508 |
def snakemake_job_script(tmp_path_factory, tumor_normal_config):
"""
Creates a dummy snakemake jobscript
"""
script_dir = tmp_path_factory.mktemp("snakemake_script")
snakemake_script_file = script_dir / "example_script.sh"
snakemake_script = """#!/bin/sh
# properties = {"type": "single", "rule"... | 3c9a5560dd94ed1e690efa0463890d9f2405db53 | 616,514 |
from pathlib import Path
def getProcFNFromOrigFN(fp):
"""Returns the processed filename (as Path object, which can be treated as string) from origina filename (as string or Path object)"""
return Path(Path(fp).stem + '_processed.h5') | 3fba14bb76e1e49d7c3d7dee74613cb938f72701 | 616,516 |
def fmtcdb(key, val):
"""Formats a key and value into cdb format."""
key = str(key)
val = str(val)
s = '+%d,%d:%s->%s' % (len(key), len(val), key, val)
return s | a3f62257f591a76d94139b2033ee546bfca4ee0f | 616,517 |
import pathlib
import io
def read_file(path: pathlib.Path) -> bytes:
"""
Function to read in an image file and return the bytes
:param path: File path
"""
with io.open(path, "rb") as file:
content = file.read()
return content | 48f30c846325869d98b463f09d5a27cf0a079e5a | 616,519 |
def remove_protected_attrs(item: dict) -> dict:
"""
Remove protected (AWS-only) attributes from a DynamoDB item.
"""
attrs = [attr for attr in item.keys() if attr.startswith('aws:')]
for attr in attrs:
del item[attr]
return item | 55ed4fe710fb78423ef002a2b8d655bdb33897a6 | 616,520 |
def _get_bib_element(bibitem, element):
"""Return element from bibitem or None."""
lst = [i.strip() for i in bibitem.split("\n")]
for i in lst:
if i.startswith(element):
value = i.split("=", 1)[-1]
value = value.strip()
while value.endswith(','):
v... | 19bf76c0f50ca7ef6469386aa6246c24f8eb26b2 | 616,525 |
import zipfile
def unzip_with_python(zip_file, output):
"""Unzips an archive using 'zipfile' python module.
Works everywhere where python works (Windows and Posix).
Args:
zip_file: absolute path to an archive to unzip.
output: existing directory to unzip to.
Returns:
Exit code (0 on success).
... | 2ae3f359a2969c81f32a2c025482be19a2379fa8 | 616,529 |
def find_containers(bag, bag_rules):
"""Find the bags that can contain a specified bag."""
allowed = []
for n, item in bag_rules.items():
if bag in item.keys():
allowed.append(n)
return allowed | 8c0d2dd33f2ea8ce8aa60c4ba6e0af005022754f | 616,531 |
def popravi_st_glasov(seznam_slovarjev):
"""
Popravi vnos ST_GLASOV, da vrne število brez decimalne vejice.
"""
for pivo in seznam_slovarjev:
glasovi = pivo['ST_GLASOV']
glasovi = int(glasovi.replace(',', ''))
pivo['ST_GLASOV'] = glasovi
return seznam_slovarjev | 96aa06d03530c8721bb4cf8681eafec5438081b2 | 616,539 |
def value_to_float(x: str):
"""
Converts strings with abbreviated numbers to floats
>>> value_to_float('1.2k')
1200.0
"""
if type(x) == float or type(x) == int:
return x
x = x.upper()
x = x.replace(',', '')
if 'K' in x:
if len(x) > 1:
return float(x.repla... | 394ae5dcabe8c181c0cc47cd2e64a2a4fa77eb38 | 616,540 |
def decorate_c_array_data (hexdata: str,
var_name: str,
var_type: str,
newline_value: str):
"""
Place @hexdata into a valid C array named @var_name of C type @var_type.
"""
ret = var_type + " " + var_name + "[] = {" + newli... | c2bb35ad5178f590197a46b7fa3cc64919da495d | 616,541 |
from typing import Callable
from typing import List
def get_shingles(
doc: str,
normalization_func: Callable,
split_method: str,
ngram_size: int,
ngram_stride: int,
) -> List[str]:
"""Extracts the shingles from a document.
Args:
doc (str):
The document to extract the s... | 98189a9562a1b45b8cbe98e52167c7b60ff1771c | 616,545 |
from typing import List
def max_array_sum(arr: List[int]) -> int:
"""
Return the maximum sum of an array subset of non-adjacent items.
:time: O(n)
:space: O(n)
"""
max_sum = [0] * (len(arr) + 2)
for i, num in enumerate(arr, start=2):
max_sum[i] = max(max_sum[i - 2] + num, max_sum[... | 004aeed629bdd35d86e6677e07013a35d44cdf54 | 616,549 |
import math
def wind_speed_2m(ws, z):
"""
Convert wind speed measured at different heights above the soil
surface to wind speed at 2 m above the surface, assuming a short grass
surface.
Based on FAO equation 47 in Allen et al (1998).
:param ws: Measured wind speed [m s-1]
:param z: Heigh... | f5c84fac3e5a7404e7baa8f2a6dd44388fe64ff1 | 616,554 |
def transform_boolean(value):
"""Transfroms boolean to `1` or `0`.
:param value: Boolean value.
:type value: boolean
:return: number representation of boolean `1` or `0`.
:rtype: str
"""
if value:
return '1'
else:
return '0' | c2cf69cfe06aacfe23f28b782ab2e93448b76afd | 616,556 |
import math
def sigmoid(x: float) -> float:
"""
Numerically stable scaled logistic function.
Maps all values ``x`` to [0, 1]. Values between -1000 and 1000 are
mapped reasonably far from 0 and 1, after which the function
converges to bounds.
Parameters
----------
x:
Input.
... | c2f6cfc570aaad688247a7b278523686b95c2231 | 616,557 |
import six
def get_string_mapping(kvp):
"""Returns a dictionary mapping strings to strings.
This can take either a string of the form "name=value:name2=value2"
or a dictionary containing all string keys and values.
:param kvp: dictionary or string
:returns: dictionary
"""
if kvp is None... | c08eeea361725ff0ec6023fffaae9388d48dc534 | 616,562 |
from functools import reduce
import operator
def get_by_path(root: dict, items: list[str | int]) -> dict:
"""Access a nested object in root by item sequence."""
return reduce(operator.getitem, items, root) | 15234c22acd27fe8cd912a457f06777fa0e78dc6 | 616,563 |
def is_number(text):
"""
Checking if the text is a number
:param text: text we want to examine
:type text: str
:return: whether this is a number or not
:rtype: bool
"""
try:
float(text.strip())
except ValueError:
return False
return True | f8c53c0a9319aa49146edf1a86ab81e15ead27c5 | 616,567 |
import torch
def _get_device(device_string):
"""Returns a `torch.device`
Args:
device_string: 'cpu' or 'cuda'
Returns:
`torch.device`
"""
if device_string.lower() == 'cpu':
return torch.device('cpu')
if device_string.lower() == 'cuda':
if torch.cuda.device_count() == ... | b501b9dbc0a65ee9ac7cf23012531331c650fa4c | 616,568 |
import math
def euclidean_distance(a, b=None):
"""
Euclidean distance between two n-dimensional points.
"""
if b is None: return euclidean_distance(a, (0,) * len(a))
return math.sqrt(sum((a - b) ** 2 for a, b in zip(a, b)))
#np.linalg.norm(a - b)
#np.sqrt(np.sum((a-b)**2))) | 4eac16a69b7bb756023c71a09af658aa0cfab551 | 616,569 |
import random
def random_condition(*conditions) -> str:
"""
Returns a random condition based on the supplied arguments with
equal probability of all conditions.
Args:
*conditions: A variable number of condition identifiers
Returns:
str: One of the input arguments, chosen at rando... | 1fb24934df8c2db7ee594f6930d19877efa91111 | 616,571 |
import math
def norm(vec):
"""Return the norm of a 2-dimensional vector."""
return math.sqrt(vec[0] ** 2 + vec[1] ** 2) | 118a4b73a6c71680517e13df0430b3ff20e167cf | 616,573 |
def between(full, start, end):
"""Returns the substring of the given string that occurs between the start
and end strings."""
try:
if not start:
parse = full
else:
parse = full.split(start, 1)[1]
if end:
result = parse.split(end, 1)[0]
else... | 34697a5625d07724b2f6b22cad6b6b98badcd7c1 | 616,575 |
def get_mask_paths(metadata):
"""
localization.txt (for masks) has the structure
<path>,<link_to_mask_file>,<link_to_ignore_mask_file>
path/to/image1.jpg,path/to/mask1a.png,path/to/ignore1.png
path/to/image1.jpg,path/to/mask1b.png,
path/to/image2.jpg,path/to/mask2a.png,path/to/ignore2.png
p... | fb4f27cb7cc2ea81f03fd80698a5a52f467dbad0 | 616,576 |
import pkg_resources
def get_schema_path(version='1.0.1'):
"""
Location of CPHD schema file.
Returns
-------
str
The path to the CPHD schema.
"""
if version == '1.0.1':
return pkg_resources.resource_filename('sarpy.io.phase_history.cphd_schema', 'CPHD_schema_V1.0.1_2018_0... | eb2dcb2a0c2c5f550e221ebc585db000b2129ede | 616,578 |
def _parse_dummy(logfile):
"""Dummy parser for testing"""
return {} | c9dacf3bb1b67e7d86905690e69b29924a86f2b9 | 616,579 |
import torch
from typing import List
from typing import Dict
from typing import Any
def add_weight_decay(
model: torch.nn.Module, weight_decay: float
) -> List[Dict[str, Any]]:
"""Add weight decay to only the convolutional kernels. Do not add weight decay
to biases and BN. TensorFlow does this automatical... | 12a2c637b5f667155a38344015c31050c1134119 | 616,583 |
def get_offer_photos_links(html_parser):
"""
This method returns a list of links to photos of the apartment.
:param html_parser: a BeautifulSoup object
:rtype: list(string)
:return: A list of links to photos of the apartment
"""
gallery = html_parser.findAll(class_="gallery-box-thumb-item")... | e0f97f7e4aa8dd7038721de4d2c4282bd5ba2c0d | 616,584 |
def unescape_double_quote(content: str) -> str:
"""
Replace escaped double quote in content by removing the backslash.
>>> unescape_double_quote(r'UTF\"-8')
'UTF"-8'
>>> unescape_double_quote(r'UTF"-8')
'UTF"-8'
"""
return content.replace(r"\"", '"') | ae93bccd6491ca53b4b2a1dfec1f54a4ff066fea | 616,585 |
def check_url(url):
""" Check if exist a well-formed url"""
if url[:8] == "https://" or url[:7] == "http://":
return True
else:
return False | 32de5e56ffbdeaad8aee81964fef6af7ac8d1987 | 616,586 |
def help(title, url=None) -> str:
"""Creat help badge
Args:
title: help text
url: url to open in new tab (optional)
Returns:
HTML formatted help badge
"""
if url is not None:
return f'<a title="{title}" href="{url}" target="_blank"><span class="badge pull-right" sty... | 7e2be99d931d2c0d473dbcc0020e20c498c3ef1e | 616,587 |
def average(values):
"""(list of number) -> number
Return the average of the numbers in values. Some items in values are None,
and they are not counted toward the average.
>>> average([20, 30])
25.0
>>> average([None, 20, 30])
25.0
"""
count = 0 # The number of values seen so far... | 18d2dc034dc22de92e0bdb2b2d2a2d637f998a82 | 616,588 |
def get_mask_names_dict(mask_names, tracer_names):
"""
Return a dictionary with the mask names assotiated to the fields to be
correlated
Parameters:
-----------
mask_names (dict): Dictionary of the masks names assotiated to the
fields to be correlated. It has to be given as {1: nam... | d6d393fa7cd78233c6a3899ae1740d822381e6c1 | 616,589 |
def clean_text(text):
"""Removing spaces and converting the text into lowercase"""
return text.strip().lower() | f10398b49da946180f9635c08e12cf172f9a585a | 616,591 |
def filter_gtf_file(gtf_file, source=None, feature=None, copy=True):
"""
filter gtf file based on tthe source of the annotations (HAVANA or ENSEMBL),
and/or the type of feature (transcript, exon, gene)
if source/feature is not None.
It returns a new filtered pandas.DataFrame.
Parameter... | 718dc2e08ccdfd2f0549b71ae88fc85cd021e3ab | 616,592 |
def compile_str_from_parsed(parsed):
"""The (quasi-)inverse of string.Formatter.parse.
Args:
parsed: iterator of (literal_text, field_name, format_spec, conversion) tuples,
as yield by string.Formatter.parse
Returns:
A format string that would produce such a parsed input.
>>> ... | 6acec4e3e846341a99dd757f7267f2d68f8327c0 | 616,594 |
def getYearsAsList(macroDemand, startYear, endYear):
""" Return a sorted list containing only the years (or "time steps"). """
years = macroDemand.keys()
years.sort()
for i in range(len(years)):
years[i] = int(years[i])
startIndex = years.index(startYear)
endIndex = years.index(endYear)... | 4a9501ae2c06c769e12752b620272928d9c381a2 | 616,598 |
def open_json(spark, json_path):
"""Opens a json file as a pandas DataFrame.
Parameters
----------
spark
Spark session.
json_path
a HDFS file path and file name ending in .json
Returns
-------
Pandas DataFrame
"""
sdf = spark.read.json(
json_path,
en... | fe53397d944b862fa9b0f48a1fe2b9b12c37a65e | 616,599 |
def roll_uint8(value):
"""Roll given one-byte value, i.e. increment it such that
the range is preserved.
>>> roll_uint8(-10)
ValueError: Acceptable range: 0 - 255
>>> roll_uint8(-1)
ValueError: Acceptable range: 0 - 255
>>> roll_uint8(0)
1
>>> roll_uint8(10)
11
>>> roll_uint8... | 82684b3a7d3e64106ed5f21fab34815f0755426c | 616,602 |
def remove_end_from_pathname(filen, end='.image'):
"""
Retrieve the file name excluding an ending extension or terminating string.
Parameters
----------
filen : str
end : str
End to file name to remove. If an extension, include the period, e.g.
".image".
"""
if not filen... | 212b3ddab23d1edf03e8900cae0b445ab0032564 | 616,604 |
def filter_pdna(lognorm_df, pdna_cols, z_low=-3, z_high=None):
"""
Filter the lognorm dataframe based on the z_scored lognorms of pDNA
lognorm_df: dataframe |
pdna_cols: list |
z_low: int or None, lower range of z-scores to filter |
z_high: int or None, upper range of z-scores to filter |
r... | f503b8e4624252e7eec172a1411ea61ae38ba2ce | 616,607 |
def safestr(text):
"""
Safely convert unicode to a string
"""
if text is None:
return
try:
return str(text)
except UnicodeEncodeError:
return str(text.encode('utf-8')) | 838cf13c6e49e18e608537fcc29f6a4597ed3832 | 616,611 |
def cmdstr(cmd):
"""Return a string for the |cmd| list w/reasonable quoting."""
quoted = []
for arg in cmd:
if ' ' in arg:
arg = '"%s"' % (arg,)
quoted.append(arg)
return ' '.join(quoted) | 4650f7ea82028a8eaf57ac3b4bef539f4bdd7e34 | 616,617 |
def _unified_indent(kwargs):
"""
Private helper. If kwargs has an `indent` parameter, that is
made into the the value of both the `initial_indent` and the
`subsequent_indent` parameters in the returned dictionary.
"""
indent = kwargs.get('indent')
if indent is None:
return kwargs
... | 50f295d0909162755f5058e24e17e91834294b7d | 616,618 |
def dataframe_has_columns_of_these_types(df, types_list):
"""Returns true if the dataset has the given types.
Args:
df: The dataframe to inspect.
types_list: list of types to check for.
Returns:
True if the types are present in the data frame.
"""
return not df.select_dtype... | 3f25be8623463d9d96134182b57421d3666e1699 | 616,620 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.