content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import torch
def neginf(dtype: torch.dtype) -> float:
"""
Return a representable finite number near -inf for a dtype.
"""
return -1e20 | d9b613e815f84e18045b4367fc39404127c04ace | 627,477 |
def page_number(request, page_total):
"""Gets the current page number of a media list.
'request' is expected to have one query parameter, 'page',
containing a page number (with the first page being page 1); if it
does not exist, it is taken to be 1. This page number may be
outside the bounds dicta... | 6deab9a107cfc36d6afb1b771734579af581b602 | 627,478 |
def non_empty(d):
"""
Check whether the `collection` is none or empty.
"""
return d is not None and len(d) > 0 | 1104ce6610cf336501f47ee7f22d5e769658b05c | 627,481 |
def vecs_add(v1, v2):
"""Add two vectors 'v1' and 'v2'."""
return v1 + v2 | 6183fdc9f92f9ba3592643292b2635a5bccd570e | 627,485 |
def _add_extension_feed_item(client, customer_id, callout_text, language_code):
"""Creates a new extension feed item for the callout extension.
Args:
client: an initialized GoogleAdsClient instance.
customer_id: a client customer ID.
callout_text: a str of text for a hotel callout feed ... | e181c5d0ac6a993568732cca23500a4e82919c5c | 627,486 |
import re
def _EscapePerfResult(s):
"""Escapes |s| for use in a perf result."""
return re.sub(r'[\:|=/#&,]', '_', s) | c966bf4ffd482c27467731ca84395effe9e4fc7e | 627,499 |
def area_triangle(b, h):
"""
Returns the area of a triangle given its base
and its height
"""
area = b * h / 2
return area | a9bdd783f1a43fe73bcd7338120ffaef4863fac6 | 627,500 |
from typing import Any
import pathlib
def to_path(source: Any) -> pathlib.Path:
"""Converts 'source' to a pathlib.Path.
Args:
source (Any): source to convert to a pathlib.Path.
Raises:
TypeError: if 'source' is a type that is not registered.
Returns:
pathlib.Path: derive... | 1e0cf017d7a523641e812b10181ae78ecef477f0 | 627,502 |
def _ArgbToRgbaTuple(argb):
"""Convert from a single ARGB value to a tuple containing RGBA.
Args:
argb: Signed 32 bit integer containing an ARGB value.
Returns:
RGBA tuple.
"""
unsigned_argb = argb % 0x100000000
return ((unsigned_argb >> 16) & 0xFF,
(unsigned_argb >> 8) & 0xFF,
... | fae533892b25a193c7d664f59161a8deef1931a1 | 627,505 |
from datetime import datetime
def editor_reg_date(identity: dict, global_userinfo: dict):
"""
Normalize registration date from either oauth or global_userinfo as datetime.date object.
Parameters
----------
identity : dict
global_userinfo : dict
Returns
-------
datetime.date
""... | 871d0267c3f27945f5fbe1193cb7c66d93d942dd | 627,509 |
def FindOrderNums(orders, wavelengths):
"""
Given a list of xypoint orders and
another list of wavelengths, this
finds the order numbers with the
requested wavelengths
"""
nums = []
for wave in wavelengths:
for i, order in enumerate(orders):
if order.x[0] < wa... | 40f974709e37a6df3cb9bb8f1dd040904669eb76 | 627,510 |
def merge_clusters(articles):
"""Merges articles of every cluster into one article object."""
clusters = []
cluster_ids = set([article['cluster_id'] for article in articles])
for id in cluster_ids:
body = []
for article in articles:
if article['cluster_id'] == id:
... | bd5965b331519423322d146d3ce065885d44a760 | 627,512 |
def provider2network(p):
""" Convert a MADIS network ID to one that I use, here in IEM land"""
if p in ['KYMN']:
return p
if len(p) == 5 or p in ['KYTC-RWIS', 'NEDOR']:
if p[:2] == 'IA':
return None
return '%s_RWIS' % (p[:2],)
print("Unsure how to convert %s into a ne... | 75328bf129f3619b63d24b4cbe6f70037aefc3ad | 627,514 |
def figshare_stem(stem: str = '', production: bool = True) -> str:
"""
Construct Grouper figshare stems
:param stem: string corresponding to the sub-stem.
Options are: 'quota', 'portal'. Default: root stem
:param production: Bool to use production stem.
Otherwise a stage/test is u... | 929acec5e0a467ddd24d54751bf3f0747f66faa3 | 627,518 |
def build_client_user_topic(user_id: str):
"""
Builds the topic name where user push notification are received
:param user_id:
:return:
"""
return f"/app/{user_id}/subscribe" | b9bf7dec85cfec7d818b9091f1e0a5b784e5dbb9 | 627,520 |
def convert(hours: int, minutes: int) -> int:
"""Convert hours and minutes to total seconds."""
total_seconds = (minutes * 60) + (hours * 3600)
return total_seconds | b9aa43a2009dd9561829a934d2bac424bbc88460 | 627,521 |
def findall_lod(lst, key, val):
"""get list of dicts of all matches of key-value pair in list of dicts"""
return [x for x in lst if x[key] == val] | 17c101399367443a1ac40030a14110325f09920f | 627,523 |
import hashlib
def hash_from_url(url: str):
"""Hash url to create a unique ID."""
return hashlib.sha256(url.encode("utf-8")).hexdigest() | bda9aceca362d9b57780d0d333320eaccc556a91 | 627,524 |
def back2dim(x, xdim=-1):
"""
Transpose ndarray so that the back dimension is moved to a given position.
Parameters
----------
x : ndarray
Input array.
xdim : int, optional
Dimension at which to put the back "x" input array dimension.
(default=-1)
Returns
------... | 6db1b8ca2398e7fe7e90010598944823bf770148 | 627,526 |
def maximum_element_size_for_length(length):
"""
Returns the maximum element size representable in a given number of bytes.
:arg length: the limit on the length of the encoded representation in bytes
:type length: int
:returns: the maximum element size representable
:rtype: int
"""
return (2**(7*length)... | 69e2577d1b7b489ed159339dcc32d4a441dace36 | 627,527 |
def first(iterable):
"""Returns the first item of 'iterable'
"""
try:
return next(iter(iterable))
except StopIteration:
return None | ef3a589f21c89a59a73e117463ecdb4c341bb7b0 | 627,530 |
def _translate_slice(exp, length):
""" Given a slice object, return a 3-tuple
(start, count, step)
for use with the hyperslab selection routines
"""
start, stop, step = exp.indices(length)
# Now if step > 0, then start and stop are in [0, length];
# if step < 0, they are in ... | ba91234e21c1f32dcf44440580dbc7f590e320e7 | 627,531 |
def get_measurement_variable(gt_id, shift=None):
"""Returns measurement variable name for the given ground truth id
Args:
gt_id: ground truth data string accepted by get_ground_truth
shift: (optional) Number of days by which ground truth measurements
should be shifted forward
"""
... | 6d4aa672d04b896f8963b4ebe36d7b056b7a4c6c | 627,532 |
def readDictionary(input):
"""
Read file to a dictionary data structure:
Input file is a lexicon consisting lines of the word and the most frequent associated tag
"""
dictionary = {}
lines = open(input, "r").readlines()
for line in lines:
wordtag = line.strip().split()
... | 543261fe7cbff53b4dc3082d56687aa3d2cef336 | 627,535 |
import random
def randomize_list_of_words(input_words):
"""
Returns the same list of words in a random order.
Input:
-input_words list of strings
Output:
-output_words list of strings
"""
output_words = []
random_order = random.sample(range(len(input_words)), len(input_word... | cbe19aa8cddddedcb439245cfc9ad67e20d7e382 | 627,536 |
def only_hostname(s):
"""
Given an SSH target, returns only the hostname.
e.g. only_hostname('user@mydomain:port') == 'mydomain'
"""
return s.split('@')[-1].split(':')[0].strip() | 256d21128c14072ce915d70492f79d6c21e1d24b | 627,539 |
import collections
def log_string_to_dict_list(log_string):
"""
Take a single string representing the contents of a jewel::Log file,
and return a list of OrderedDicts representing the logging events in the
log file.
"""
record_separator = "{R}"
field_separator = "{F}"
raw_records = log... | 44f144c05a4584aece82abc6d31607fa60199911 | 627,540 |
def limitValue(value, min, max):
"""Limits value to a min or max value
Arguments:
value {int, float} -- value
min {int, float} -- minValue
max {int, float} -- maxValue
Returns:
int, float -- limited value
"""
if value > max:
out = max
elif value < min:
... | 6280ee2e4b414a1020f225ff8a588394bd3c0a53 | 627,543 |
def int_depth(h_int: list, thickness: float):
"""
Computes depth to the interface for a three layer model.
:param h_int: depth to to first interface
:param thickness: thickness
:return:
d_interface: interface depths
"""
d_interface = h_int
d_interface.append(d_interface[0] + thi... | 816bc15b51668fb2f8376826c065197802e88c98 | 627,546 |
def remove_subdomain(name: str) -> str:
"""Removes the subdomain from a given URL.
Example:
>>> remove_subdomain("www.example.com")
'.example.com'
Arguments:
name: the domain
Returns:
the string with the subdomain removed. The string starts with the dot.
"""
tr... | e507a4dedc6eb9a9ca8e2f6e1db2cb9dc399283d | 627,548 |
def euclid(a:int, b:int, Verbose=False):
"""Return the Greatest Common Divisor (GCD) of number a and b."""
# The GCD of two relative integers is equal to the GCD of their absolute values.
a, b=abs(a), abs(b)
# The largest of the two numbers is replaced by the remainder of the Euclidean div... | 3172e024b2782f1077673f05d732607ecf3e59f7 | 627,550 |
def get_crop(params, shape):
"""
Parses crop from params object.
Parameters
----------
params : object
object holding configuration parameters
shape : tuple
shape of image array, i.e. the array to be cropped
Returns
-------
crop : list
crop in each... | 0bdeeed81c3578301654df72d97e27dce9326dba | 627,551 |
def btc_to_satoshi(btc):
"""
Converts a value in BTC to satoshi
outputs => <int>
btc: <Decimal> or <Float>
"""
value = btc * 100000000
return int(value) | c75fe3bec4389b8fc332188edfeda575766aeae2 | 627,552 |
from functools import reduce
def ichain(obj, *items):
"""
Gets through a chain of items
handling exceptions with None value.
Useful for data restored from a JSON string:
>>> ichain(data, 'result', 'users', 0, 'address', 'street')
"""
def get_item(obj, item):
if obj is None:
... | b4f4bf3da2a57ec95af6779f3fbd67c351414045 | 627,553 |
import torch
def transform_coords(Ms, coords, wrap_around=False):
"""
Ms - affine transform matrices, (B,2,3), assumes x-y coordinate system in math
coords - (B,dimx,dimy,2)
"""
B, dimx, dimy = coords.size()[0], coords.size()[1], coords.size()[2]
augmented_coords = torch.cat((coords, torch.one... | b3093ce3a58a83125744265ab70394643888df71 | 627,557 |
def clamp(val, low, high):
"""Return val, within [low,high]"""
if val < low:
return low
elif val > high:
return high
return val | 58c0c8afbfa8527617a15c20989fe4b0c1fd2db9 | 627,560 |
def _bin_to_hex(bitstring):
"""Convert bitstring readouts (memory) to hexadecimal readouts."""
return hex(int(bitstring, 2)) | ebd5197ee5956d388ee1ea1b365a0b3fbba7c804 | 627,561 |
def list_apim_nv(client, resource_group_name, service_name):
"""List all Named Values of an API Management instance. """
return client.named_value.list_by_service(resource_group_name, service_name) | d14f5d8e4fba0fe08d158cfbf099228fda5599e0 | 627,564 |
import time
def is_bst(st: time.struct_time) -> bool:
"""
Calculates whether the given day falls within British Summer Time.
.. note::
This function does not consider the time of day,
and therefore does not handle the fact that the time changes at 1 AM GMT.
:param st: The :class:`time.struct_time` represen... | 7428810629c417cb8a55994b3086a7e9515194b7 | 627,570 |
def convert_masking(sentences):
"""Converts hash masking to internal [MASK] tokens"""
converted_sentences = []
for sent in sentences:
sent = list(sent)
for i, c in enumerate(sent):
if c == "#":
sent[i] = "[MASK]"
converted_sentences.append("".join(sent))
... | 2ae095b06694d8f592159f5f5eee6491fe479d23 | 627,572 |
def calGasVisEq2(eqExpr, T):
"""
gas viscosity equation - Pa.s
args:
eqExpr: equation expression
T: temperature [K]
"""
# try/except
try:
return eval(eqExpr)
except Exception as e:
raise | b56d1a267777bbc6803f65937f2a5d96c00f284d | 627,573 |
def get_security_group_rules(body_response_sec_group_list, sec_group_name):
"""
Retrieve security group rules list
:param body_response_sec_group_list: Parsed response (python dic). List of sec. groups
:param sec_group_name: Name of Sec. Group to look for
:return: Return the first sec. group with se... | 0ec23f16fcc3bd166ed8fa4412bd768e6e9c72da | 627,574 |
def calcRCutIsolate(rh):
""" For isolated star clusters, set rcut to 20 * half-mass radius
Return
----------
rcut: float
escaper distance criterion
"""
return 20*rh | c4a37a1145270fee17a67f944dec9ecfbce93ea4 | 627,579 |
def _pre_commit_has_hallmark(pre_commit_file):
"""
Looks at a pre-commit file and determine if it was created by Jig.
:returns: True if Jig created it
"""
with open(pre_commit_file) as fh:
script = fh.read()
if u'from jig' in script or u'jig init' in script:
return True
... | d55b5ea21c69558d8937296b518d058db9334e6a | 627,583 |
def extract(d, keys, exclude=False):
"""
Helper function to extract keys and values from dictionary
Parameters
----------
d : dict
Dictionary from which to extract keys
keys : list of keys
List of keys to exclude or include
exclude : boolean
If true, excludes the... | ef9e526b2db018e8adc53f14c67d5c316495858e | 627,584 |
def merge_ranges(ranges, max_gap):
"""
Merge ranges which are closer than max_gap
"""
merged_ranges = []
for range in ranges:
if merged_ranges:
curr_start, curr_end = range
# compare against last interval in merged_ranges
pre_start, pre_end = merged_ra... | 981ae0dedb9ef5df5852994a7f7712953f2a5d3e | 627,587 |
def freq(T):
"""
Convert array of periods in days to frequencies in Hz.
"""
return 1./T/86400. | d4b1e31ec6468141803405d82535330803a03869 | 627,589 |
def _parse_fingerprint_awsconsole(line, host=None):
"""Parse SSH host fingerprint from AWS console output"""
fingerprint = None
if line.startswith('ec2:'):
host = host
fingerprint = line.split(': ', 2)[1]
return host, fingerprint | f114c138fb7c1fe10e9a2db5d105f6587520742d | 627,594 |
import logging
import socket
def check_port_in_use(host, port):
"""Check if port is already in use.
Arguments
---------
host: str
The current host.
port: int
The host port to be checked.
Returns
-------
bool:
True if port is in use, false otherwise.
"""
... | 7351f26ae44d19d6640999ffee3e9c61cffb7770 | 627,598 |
def make_sic_div_lookup(sic):
"""Creates lookup between SIC class and division."""
return (
sic.assign(
Division=lambda x: x.Class.str[0:2],
Class=lambda x: x.Class.str.replace(".", ""),
)
.set_index("Class")["Division"]
.to_dict()
) | 1c0ceae74334c06e0f69e6d33d7120f4ec0105c0 | 627,601 |
def get_main_domain_name(url_str) -> str:
"""get url domain texts
Args:
url_str (str): url string
Returns:
str: domain name of url
"""
domain_name = url_str.split("/")[2]
main_domain_name = domain_name.split(".")[-2]
return main_domain_name | ddc3fc8aa2b0b61eafd84ac9754c271f011ac8d2 | 627,602 |
def force_console_input(
query: str,
allowable,
onfail: str = "Input not recognised, please try again.\n",
case_sensitive=False,
):
"""Get an input from the user matching some string in allowable.
Args:
query (str): The query to issue the user with.
allowable (str or container):... | d43e98f77a14f0045117738900128bf779cba173 | 627,605 |
def did(tag_class, is_constructed, tag_id):
"""
Calculate decoder_id as <tag id > | tag_class | constructed
:param tag_class:
:param is_constructed:
:param tag_id:
:return:
"""
did = tag_class >> 5
if is_constructed:
did |= 1
return did | (tag_id << 3) | 1fa8a0b11b7260a4f607eb79770fd76a87bfbdb1 | 627,607 |
def compute_wave_height(crest_height, trough_depth):
"""Computes wave height from given crest height and trough depth."""
assert crest_height > trough_depth
return crest_height - trough_depth | b259e28afa3c6ef4514a087490b62a70f6a0b1f6 | 627,609 |
import configparser
import logging
def read_config(filename):
"""Reads a config file.
Args:
filename (str): Filename of config file to be read.
Returns:
configparser.ConfigParser: Read config file.
"""
parser = configparser.ConfigParser()
parser.read(filename)
logging.inf... | 2336979a44246a93fbb4a563e54ebb9f5a356d23 | 627,611 |
def UsersInvolvedInComponents(component_defs):
"""Return a set of user IDs referenced in the given components."""
result = set()
for cd in component_defs:
result.update(cd.admin_ids)
result.update(cd.cc_ids)
if cd.creator_id:
result.add(cd.creator_id)
if cd.modifier_id:
result.add(cd.m... | 431d63647d8cf6f8588700015ef94b46d96ce651 | 627,612 |
def parse_none_or_string(value):
""" This function is primarily used to parse command-line arguments. Whenever
the string 'None' is passed, it will return it as None, otherwise it will return
whatever it was passed as a string.
"""
if value == 'None':
return None
return value | 5ebbce7afe13e9fa5de3233c41d54ae036c88dfe | 627,614 |
import pathlib
def about_package(init_posixpath: pathlib.Path) -> dict:
"""
Return package information defined with dunders in __init__.py as a dictionary, when
provided with a PosixPath to the __init__.py file.
"""
about_text: str = init_posixpath.read_text()
return {
entry.split(" = ... | 4e43c305ecf784e8355d2ab9ac735c18b7346881 | 627,624 |
def divide_to_keys(dict_all_embeddings):
"""
Distinguish between types of embedding methods - ours and state-of-the-art
:param dict_all_embeddings: dict of all embeddings
:return: Names of our methods, names of state-of-the-art methods
"""
keys_ours = []
keys_state_of_the_art = []
keys =... | fe88a8a7a515a8d09b8aa541e56c3fa22b91554d | 627,625 |
import requests
from bs4 import BeautifulSoup
def get_valid_urls(url, break_url):
"""
Get valid urls from sitemap.xml. Note: only links after group-49 are valid for download.
- url: the link to stemap.xml
- break_url: the url link to the group-49
>>> url = "https://apkpure.com/sitemap.xml... | f12afcce54d873239bfe621eaa2ee640a8879329 | 627,628 |
def get_correlation_values(cors, r, c):
"""
Gets correlation between properties r and c for all files
Parameters
----------
cors : list
propertiess correlations per file
r : int
first property index
c : int
second property index
Returns
... | da02af082d947a371c66fce87ef9a961cf00283e | 627,629 |
import requests
import json
def get_vendor_from_mac(mac):
"""Get the vendor from the MAC using an API"""
url = "https://mac2vendor.com/api/v4/mac/"
mac_str = "".join(mac.split(":")[:3])
try:
r = requests.get(url + mac_str)
response = json.loads(r.text)
if not response["success"... | 271c855d7d8f9ec8ae124e20899273b305b4b807 | 627,631 |
def next_name(container, key):
"""
Given a container object and some key prefix, yield the next key with the
given prefix that is not contained into container.
"""
if key not in container:
return key
for i in range(1, 1000):
test = f"{key}_{i}"
if test not in container:
... | d7b7e660a97b7586e162c7517ade46151b65e534 | 627,633 |
def measurement_exists(cur, project_key, id):
"""
Check whether the measurement exists in the database in the given project.
"""
measurement = cur.execute(
"SELECT * FROM measurements WHERE id=? AND projects_key=?", (id, project_key)
).fetchone()
if not measurement:
return False... | d5b8392813960a50364640692aeb12d7b694a44b | 627,634 |
import warnings
def divide2(a, b):
"""Return a/b.
If b = 0, raise a warning and return the NaN ("Not a Number") value."""
if b == 0:
warnings.warn("Division by zero !")
return float("nan")
else:
return a/b | 7c940b49a142f77417381702ea853e69115f18f5 | 627,637 |
import torch
def clip_linear(values, a, b):
"""Clip values to [-1, 1]
Input:
- values(torch tensor): values to be clipped
- a (float): coefficient
- b (float): intersection
Output: (torch tensor) clipped values
"""
return torch.clamp(values * a + b, -1, 1) | 3e2e909814b2c3e46635e2b68c06ab66f063f56f | 627,640 |
def to_camel_case(snake_str):
"""
Converts snake_string to camelCase
:param str snake_str:
:returns: str
"""
components = snake_str.split('_')
return components[0] + "".join(x.title() for x in components[1:]) | 4245decbef1fd052c57f7ebe74e6b55d7238db1d | 627,644 |
import typing
import textwrap
def WrapText(text: str, length: int) -> typing.List[str]:
"""
A function that wraps text.
Parameters
----------
text : str
The text to wrap.
length : int
The length to wrap the text at.
Returns
-------
typing.List[str]
A list ... | 9fa22bbcc075bfd068f124822c761d4509b16147 | 627,645 |
def data_split(dataset, n_test_set=30):
"""
split data into train and test sets
Arguments:
----------
dataset: pd.DataFrame
- time series dataset
n_test_set: int
- the last n data points
Returns:
--------
X_train : pd.DataFrame
- training set
X_test : pd... | 9ddf63e3355ee8c6e77356c4ab75e40600a99de6 | 627,648 |
import re
def match_first(string, prefix_infos, key):
"""Match string against each regex. Return first match, or None"""
for prefix_info in prefix_infos:
regex = prefix_info.get(key)
if regex:
match = re.match(regex, string)
if match:
prefix_info["match... | b8722d0393aff5f378893025957cfd31e27caead | 627,650 |
def sign(x):
"""
Returns the sign of x.
:param x:
:return:
"""
if x > 0:
return +1
elif x < 0:
return -1
elif x == 0:
return 0 | bcbbcda206c0c2c45983554449850eabbd19d842 | 627,652 |
import re
def grep(regex, output):
"""Similar to linux's `grep`, this returns the line in an output stream
that matches a given regex pattern.
It does not rely on the `grep` binary and is not sensitive to line endings,
so it can be used cross-platform.
Args:
regex: string, a regex that matches the exp... | 7b09acac1a268caf89a3268f8272696f4a1dee2f | 627,653 |
import uuid
def generate_enrollment_record_data() -> dict:
"""Helper method for generating data for an EnrollmentRecord"""
return {
"csp_user_uuid": uuid.uuid4(),
"first_name": "Bob",
"last_name": "Testington",
} | d4cbe12723a04734029c66f51643a59c1f329b26 | 627,654 |
import torch
def to_onehot(indices: torch.Tensor, num_classes: int) -> torch.Tensor:
"""Convert a tensor of indices of any shape `(N, ...)` to a
tensor of one-hot indicators of shape `(N, num_classes, ...) and of type uint8. Output's device is equal to the
input's device`.
"""
onehot = torch.zeros... | d677812dc217d5408e784e94c5e9e88526e7a674 | 627,657 |
import random
def block_permutation(preserve_symmetry = True):
"""Choose order to rearrange rows or columns of blocks."""
if preserve_symmetry:
return random.choice([[0,1,2],[2,1,0]])
result = [0,1,2]
random.shuffle(result)
return result | 087199eca4b462eb9745054bb898227c86e2f99b | 627,662 |
def first_char_is_number(text):
"""Check if string starts with a number."""
return text[0].isdigit() | 1caa7978b6dd9e7cca1200a905026d6f9de92a65 | 627,663 |
def extract_authors(pubs):
"""Get list of author IDs from a list of namedtuples representing
publications.
"""
l = [x.author_ids.split(";") for x in pubs if isinstance(x.author_ids, str)]
return [au for sl in l for au in sl] | dd128f8e5ccba16ed7c83f5d15fe3ca269bf6616 | 627,664 |
def no_perf_degrad(optimzed_time: float, non_optimized_time: float, rtol: float = 5e-2) -> bool:
"""Assert no performance degradation.
Args:
optimzed_time (float): [description]
non_optimized_time (float): [description]
rtol (float, optional): Max tolerant runtime degradation. Defaults ... | 8b02fdfa87e33d3cc27a13c7338d2be22f85588a | 627,666 |
def flatten_model_colnames(model_colnames):
"""
From a dict that maps model name to a list of field names, generate a list with string elements `<module>.<field>`.
"""
flat_colnames = []
for modelname, colnames in model_colnames.items():
flat_colnames.extend([modelname + '.' + c for c in col... | c75ce44c76e984696f90dcbf35dc223df380045f | 627,667 |
def line_plot(ax, x, ys, labels=None, styles=None, param_dict=None):
"""
A helper function to make a line graph
Parameters
----------
ax : Axes
The axes to draw to
x : array
The x data
ys : array
The y data
labels : list
The ys labels
param_dict : di... | 837867df9029f9a1c78cf448079e19e3ba9a17b3 | 627,669 |
def _intersect(a, b):
"""Returns the Intersection of two sets.
Returns common elements of two iterables
._intersect("apples", "oranges") returns "aes"
Args:
a, b: iterables that can be compared
Returns:
list of common elements between the two input iterables
"""
retu... | ab8cd7c1f4f27c0db4d0bf4c45cc047bbcf31bde | 627,671 |
def jenkins_api_query_build_statuses(jenkins_url):
"""Construct API query to Jenkins (CI)."""
return "{url}/api/json?tree=builds[result]".format(url=jenkins_url) | eb8625ba17dfb6f630701f4356cbcce6a6d39265 | 627,674 |
import torch
import copy
def clone(module: torch.nn.Module, num_copies: int) -> torch.nn.ModuleList:
"""Produce N identical layers."""
return torch.nn.ModuleList(copy.deepcopy(module) for _ in range(num_copies)) | 044e2f6742760c0e46b2ad9c961e646f1d04c6df | 627,676 |
def integer_if_integral(x):
"""Convert a float to int if it can be represented as an int"""
return int(x) if x == int(x) else x | 88f61d2792612f8108728a76d1eb8eb9b4c0abe6 | 627,680 |
def proportion_of_energy_delivered(sim):
""" Calculate the percentage of total energy delivered over total energy requested.
Args:
sim (Simulator): A Simulator object which has been run.
Returns:
float: Proportion of total energy requested which was delivered during the simulation.
"""... | 48a6dc2f4f81317c838b0e040937adb488760d48 | 627,683 |
def d(d):
"""Decode the given bytes instance using UTF-8."""
return d.decode('UTF-8') | 07efd6024ddf39b2e2e592457d9d52d2256cfc22 | 627,685 |
def profile_key(prof):
"""Get the sort key for profiles."""
if prof == 'core':
return (0, prof)
return (1, prof) | 88d7a0c6955852ef1ccb4fbce340e48ed7b295df | 627,687 |
def identify(rod, x, y):
"""Adds chip ids (chip_x, chip_y) to the key for a rod
Args:
rod: dict of (x, y): [values]
x: x coordinate that identifies the source chip
y: y coordinate that identifies the source chip
Returns:
dict: {(chip_x, chip_y, x, y): [values]}
... | 1fd1b94c87d2bcd4f685d3d8738deab026ad002c | 627,689 |
def datagenerator_affine(gen,test = False):
"""
Datagenerator for the affine network (both stages)
Args:
gen: an image generator, loading the image, indicator, loss placeholders and landmarks
test: True in case we test the function
Returns:
generator to train the affine networ... | 9018412abb087d48f61a9756d304f0b658b30fe6 | 627,690 |
from typing import Dict
from typing import Any
def get_value_len(dct: Dict[Any, Any]) -> Dict[Any, int]:
"""Get length of each dictionary value.
Args:
dct: Python `dict()` object.
Returns:
`dict()` object.
Example:
>>> status_codes = {
200: ['google.com', 'so... | 9f8cd9e6d08bd624c1666eba691dea7fc40e6767 | 627,691 |
def plant_pm_heat_rates(annual_gen_fuel_923):
"""
Calculate the heat rate by plant, prime mover, and fuel type. Values are saved
as a dictionary.
Parameters
----------
annual_gen_fuel_923 : dataframe
Data from the 923 generation and fuel use table. Heat rate for each row should
... | 028fbe063d301a27bbc8dc6ee8fbc0b1d03f5463 | 627,693 |
import hashlib
def hash_nested_tuple(tup):
""" Hash a nested tuple to hexadecimal """
return hashlib.md5(repr(sorted(tup)).encode('utf8')).hexdigest() | 2662cea34043e3b13c1570d740ca109a209a306e | 627,697 |
def get_icon_detail(icon_details):
"""
Iterate over icon details from response.
This method is used in "risksense-get-apps" command.
:param icon_details: Icon details from response.
:return: List of required icon detail dictionary.
"""
return [{
'Type': icon_detail.get('type', ''),
... | c21181a6135ff9982a1ce549c21fc497f03f3788 | 627,699 |
def _maybe_parse_as_library_copts(srcs):
"""Returns a list of compiler flags depending on `main.swift`'s presence.
Builds on Apple platforms typically don't use `swift_binary`; they use
different linking logic (https://github.com/bazelbuild/rules_apple) to
produce fat binaries and bundles. This means t... | 0661f70e4ffca4f04d76c4ab0f442683355e0c61 | 627,700 |
from typing import OrderedDict
def get_parameters_from_path(store, paths, **kwargs):
"""
Gets parameters from the specified paths and combines them
into one dictionary. Values that are the same WILL be overwritten.
Arguments:
store {EC2ParameterStore} -- The AWS Parameter Store you wish t... | 8d06c1c9f79c19e029b2c64931a199ae88d24728 | 627,702 |
import torch
def construct_diag(x):
"""
Constructs a diagonal matrix based on batched data. Solution found here:
https://stackoverflow.com/questions/47372508/how-to-construct-a-3d-tensor-where-every-2d-sub-tensor-is-a-diagonal-matrix-in-p
Do note that it only considers the last axis.
:param x: The... | d622fc0681498ba878990090d80855760d545ab9 | 627,703 |
def dim(self):
"""Return the dimensionality of the ambient space."""
return self.shape[-1] | 6e41cc940ec8626c646564bf6887664caac52df2 | 627,704 |
import random
import string
def random_id(length: int = 8) -> str:
"""Sample a random string to use for job id."""
return "".join(random.sample(string.ascii_letters + string.digits, length)) | bf1cde20f62b5429b02a1f85e42d8e4de8630231 | 627,706 |
def param_uses_64bits(param):
"""Returns True iff a syscall parameter description corresponds
to a 64-bit type."""
param = param.strip()
# First, check that the param type begins with one of the known
# 64-bit types.
if not ( \
param.startswith("int64_t") or param.startswith("uint64_t"... | 24098bf43fd7e999a86574120f5de1415f7eb47e | 627,708 |
def contingency(set1,set2,all_genes):
"""Creates contingency table for gene enrichment
set1: Set of genes (e.g. regulon)
set2: Set of genes (e.g. i-modulon)
all_genes: Set of all genes
"""
tp = len(set1 & set2)
fp = len(set2 - set1)
tn = len(all_genes - set1 - set2)
... | d52a7f6f291d66095b6a62073eef8025f4a097da | 627,709 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.