content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def scale(input_value, input_min, input_max, out_min, out_max):
""" scale a value from one range to another
"""
# Figure out how 'wide' each range is
input_span = input_max - input_min
output_span = out_max - out_min
# Convert the left range into a 0-1 range (float)
valuescaled = float(input... | d062380aeaf4aa802c03f7a94fba93efdd9f3990 | 574,008 |
def IsPakFileName(file_name):
"""Returns whether the given file name ends with .pak or .lpak."""
return file_name.endswith('.pak') or file_name.endswith('.lpak') | 0ed3c4da1e1fdcfd994b317b2eadef95e25719d8 | 574,009 |
from typing import Mapping
def stream_matches_language(stream: Mapping, language: str) -> bool:
"""Check if a stream matches given language."""
language = language.lower()
try:
tags = stream["tags"]
return bool(
tags["language"].lower() == language
or tags["title"].... | b340ad48d31e35ce149e411ac677bbf9e275741e | 574,010 |
def _add_line(screen, y, x, string, *args):
"""
Helper function for curses to add a line, clear the line to the end of
the screen, and update the line number counter.
"""
screen.addstr(y, x, string, *args)
screen.clrtoeol()
return y + 1 | 78f2a9fbfa2f02f9e2e9f645aec1103b703c6412 | 574,015 |
import logging
def create_bgp_speaker(neutron_client, local_as=12345, ip_version=4,
name='bgp-speaker'):
"""Create BGP speaker.
:param neutron_client: Authenticated neutronclient
:type neutron_client: neutronclient.Client object
:param local_as: Autonomous system number of the ... | bf43ea1dec2c5189c59ef283382088496d3f4121 | 574,019 |
def parse_file(filename):
"""
Parses a file and counts the occurrences of the word "pride"
Args:
filename: The file to be parsed
Returns:
The number of occurrences
"""
count = 0
# this is a super cool way to open a file, so it
# will automatically be closed / cleaned up ... | 5bc4336e06ac4cf0d90be8e97462f11de2bebacd | 574,023 |
import random
def randomFlips(n, p):
"""
Return an array of length n of random bits {0, 1} where Probability(0) = p and Probability(1) = 1 - p
this is used for randomly selecting some of the tokens for vertical placement.
"""
ans = n*[0]
for i in range(n):
x = random.random()
... | 8e692a77e2ec61c9651b86b052f9eb620f7c40ca | 574,024 |
def bivar_central_moment(x, y, pow=1, ddof=1):
"""Computes the bivariate central moment.
Default parameters compute sample covariance. Two-pass algorithm for stability.
Parameters
----------
x, y : 1D array-likes
x and y values to be compared
pow : int, optional
Power to raise ... | 93a1e4ee436e82eb6a586ebe2da837dc02dae17a | 574,026 |
from typing import Dict
from typing import Any
def query_metadata(
metadata: Dict[int, Dict[str, Any]], key: str, full_dict=False
) -> Any:
"""
Reverse iterates through the metadata until the key is found.
When successful, returns the matching dictionary value.
If full_dict is True, then the whole... | 93dd3b3948b193276795a05b02c786201ef42c58 | 574,028 |
from typing import List
def dashed(positions: List[int], chain: str) -> str:
"""
Take a set of positions (i.e., 1 2 3 7 8 9) and a chain ("A"), and produce a
repr like "A:1-3 A:7-9"
"""
#print(positions)
positions = sorted(positions)
acc_start = None
acc_end = None
numbering = ""... | 9dc005cbd14314aad2a42a1a2a8dc15f75b96662 | 574,030 |
import csv
def load_categories_from_csv_file(args):
"""Loads categories from a csv file.
The CSV file should have one comma delimited numeric category id and string
category name pair per line. For example:
0,"cat"
1,"dog"
2,"bird"
...
Args:
csv_path: Path to the csv file to be parsed into categor... | d2352159d86ccaceaba605c844a8a6951159760e | 574,034 |
def format_table_style(table_styles):
"""
Convert table style into a format ReportLab will accept.
:param table_styles: List of RowStyle objects defining the style of the
ReportLab table.
:type table_styles: ``list`` of ``testplan.common.exporters.pdf.RowStyle``
:return: Li... | 291a90b95b1ee3313a28a51932d026f8f5fee106 | 574,035 |
import socket
def is_valid_ipv6(ip_str):
"""
Check the validity of an IPv6 address
"""
try:
socket.inet_pton(socket.AF_INET6, ip_str)
except socket.error:
return False
return True | d48ed450ec3cf8c50ae3b07005eb99a8f3ac2c21 | 574,036 |
def extract_ingredient_counts(ingredients_dict, ingredient_labels):
"""
Extract ingredient counts from dict for plotting in chart.
:param ingredients_dict: dict mapping ingredient names to counts
:param ingredient_labels: list of strings containing ingredient names
:return: list of counts of ingredi... | 852b299d31e8896ec047db9bbf296cdbc7a0a2b0 | 574,037 |
def combine(lf):
"""Combine a list of faces into a single string."""
s = ""
for x in lf:
s += x
return s | ad3ba13e5fead7d7e8d81e9e32333ecd52b2ca71 | 574,038 |
def linux_get_string_mac_address(iface_name):
"""
It returns the MAC from an interface in Linux platforms as a string.
"""
address_path = '/sys/class/net/%s/address' % iface_name
fd = open(address_path, 'r')
mac_address = fd.read()
fd.close()
return mac_address.strip() | ee310831a0441014eca3ac3101f0962b1ea646f8 | 574,041 |
import torch
from typing import Optional
def _expand_mask(
mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None
):
"""
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
"""
bsz, src_len = mask.size()
tgt_len = tgt_len if tgt_len is not None ... | 4323c1909c78df863856d6b5fb63e0fd897d66db | 574,042 |
import math
import random
def exp(lambd):
"""
返回指数分布的值
"""
# 方法1:
# return random.expovariate(lambd)
# 方法 2:
return -math.log(1 - random.random()) / lambd | a45c0efe2436ddc713951a34719f66c04af3f0fa | 574,043 |
import logging
def IsBinaryNode(node):
"""Returns True if the node type is BINARY."""
if not isinstance(node, dict):
logging.warning('Reached non-dict node. Skipping: %s', node)
return False
return node.get('type') == 'BINARY' | e5742fca550f8d8cb01d8d550bd402847989b719 | 574,045 |
import json
def parse(filename):
"""
Creates a json object from a file
Args:
filename: the path to the file
Returns:
a json object
"""
with open(filename, 'r') as f:
data = json.load(f)
return data | 908de0fe9349e077a9f112646d7997bbee5da66c | 574,047 |
def sanitize_filename(filename):
"""
Return a sanitized file path with certain characters replaced.
"""
return filename.replace(":", "_").replace("/", "_") | 6c7f9ef6f21adefe037db107e6f9c1c3badca986 | 574,050 |
def _grad(A, Y):
"""
Returns gradient of the objective function.
"""
return -A.dot(Y) | 889e95fc1249dffb84aee12f1bed6c7132e37437 | 574,052 |
def _fixup(d):
"""
Convenience method to let the protocol implementation use the key '_class'
instead of 'class', which is a reserved word, as an argument to the dict
constructor
>>> _fixup(dict(a=1, _b=2)) == {'a': 1, 'b': 2}
True
"""
return (
{(k[1:] if k.startswith("_") else ... | dcdb64f45e8e831f89a1b5755c5888db01714d9d | 574,053 |
import re
def encode_string(string):
"""Encode a string by escaping quotation marks and backslashes."""
return '"{}"'.format(re.sub(r'["\\]', r'\\\0', string)) | 2d36e7876b000a397b5420bbb71f1e27a4208ed8 | 574,054 |
import io
def print_str(*args, **kwargs):
"""
Same as print() signature but returns a string
"""
sstream = io.StringIO()
kwargs.pop('file', None)
print(*args, **kwargs, file=sstream)
return sstream.getvalue() | 7d283f6fe5c3d7bce450c88a73cb2a0b427876ec | 574,055 |
def __jaccard(int_a, int_b): # pragma: no cover
"""Jaccard similarity between two intervals
Parameters
----------
int_a, int_b : np.ndarrays, shape=(2,)
Returns
-------
Jaccard similarity between intervals
"""
ends = [int_a[1], int_b[1]]
if ends[1] < ends[0]:
ends.reve... | b4651f52931aec2ce3f1e620a421fc5173db310e | 574,057 |
def byte_to_readable(size_bytes):
"""Function to convert bytes to human readable format (MB,GB ...)
Parameters
----------
size_bytes: float
size in bytes
:return: Return size in human readable format
:rtype: str
"""
for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
... | a0bed1c3d736e8b0fe4d0a3b5868084ebf589e96 | 574,058 |
def xcode(text, encoding="utf8", mode="ignore"):
"""
Converts unicode encoding to str
>>> xcode(b'hello')
b'hello'
>>> xcode('hello')
b'hello'
"""
return text.encode(encoding, mode) if isinstance(text, str) else text | ab53fbca6a150d17e60a5313bf2cc9d1eceec102 | 574,060 |
def infer_lengths_from_mask(mask):
"""
Get array of lengths from binary mask
:param mask: BatchSize x SequenceLen
:return: BatchSize
"""
return mask.long().sum(1) | 57598d96e6821e112843b2f8883f4435844e532a | 574,066 |
def evap_volume_OILTRANS(k, area, p_oil, molar_v, T, molar_fraction = 1,
R = 8.314):
"""
Return the evaporated fraction by unit of time [/s]
source : (Berry et al., 2012)
Parameters
----------
k : mass transsfert coefficent [m/s]
area : Area [m²]
p_oil : Vapor p... | 6ee524f0fd6face8cc8037a80607b720663557fc | 574,070 |
import logging
def parseCacheLogEntry(entry):
"""
This takes an FTL log entry and parses out relevant caching information
It returns a map with the information parsed from the entry
Example entry (truncated for line length):
INFO [CACHE][MISS] v1:PYTHON:click:==6.7->f1ea...
Return va... | 0d8b90596f49acb5dd76a0bd1bb502deb9b2a1d1 | 574,073 |
def EvalCdf(sample, x):
"""Computes CDF(x) in a sample.
sample: sequence
x: value
returns: cumulative probability
"""
count = 0.0
for value in sample:
if value <= x:
count += 1.0
prob = count / len(sample)
return prob | 7e6126daa20577d1b20993923968206f526e0e97 | 574,074 |
import itertools
def _col_name(index):
"""
Converts a column index to a column name.
>>> _col_name(0)
'A'
>>> _col_name(26)
'AA'
"""
for exp in itertools.count(1):
limit = 26 ** exp
if index < limit:
return ''.join(chr(ord('A') + index // (26 ** i) % 26) f... | aeed8be08f0830f0586a3fafdee91822fa3e5c45 | 574,075 |
def cmyk2rgb(c, m, y, k):
"""
Convert cmyk color to rbg color.
"""
r = 1.0 - min(1.0, c + k)
g = 1.0 - min(1.0, m + k)
b = 1.0 - min(1.0, y + k)
return r, g, b | ec4c03860f881a7877f1a2c2d3d1886205421aba | 574,082 |
from typing import Set
from typing import Callable
from typing import List
import collections
def add_subrepositories_depending_on(
changed: Set[str], all_subrepos: Set[str], requirement_getter: Callable[[str], List[str]]
) -> Set[str]:
"""
Augments "changed" with other members of "all_subrepos" that dire... | eb50a7ea06da5d4688dc28dea17805a8b5fb9125 | 574,086 |
def demarco2011(history, al=1, lb=1):
"""
CE formalism from
`De Marco et al. 2011, MNRAS, 411, 2277 <https://ui.adsabs.harvard.edu/abs/2011MNRAS.411.2277D/abstract>`_
Required history parameters:
- star_1_mass
- star_2_mass
- he_core_mass
- binary_separation
- rl... | 2e71951ed38c4570ab798402a3f76af57d1e237d | 574,088 |
import time
def wait(timeout, precision=0.05, break_cond=None):
"""
wait until timeout.
input:
timeout -> unit: seconds
precision -> between how many seconds, the break_cond will be checked.
break_cond -> break condition function
func... | 4fd2edf7d73e17818f582391b5a9d2a6d0b77d15 | 574,089 |
def wrong_value(value_name, decorator_name):
"""
Retrieves the "wrong value at decorator" error message.
:param value_name: Wrong value's name
:param decorator_name: Decorator name which requires the message.
:return: String - Wrong value at decorator message.
"""
return "ERROR: Wrong " + v... | 145821ea05385f0f2538d6fc5e3fe4d401e6df02 | 574,092 |
def traverse_fields(entry, ignore_fields=None):
"""
Returns a list of sets of nested fields (one set per level of nesting)
of a JSON data entry produced by a benchmark analysis script.
Ignores the dashboard-appended 'timestamp' and 'tvm_hash' fields at the top level by default.
Also ignores the 'det... | 71600093799271b5fc81f03459d819ef230e2cc3 | 574,094 |
import binascii
def reverseHex (data):
"""
Flip byte order in the given data (hex string).
"""
b = bytearray (binascii.unhexlify (data))
b.reverse ()
return binascii.hexlify (b) | 01c500b48e6b8554de1d641a23fce9361e515fef | 574,102 |
import unicodedata
def remove_accent(text: str) -> str:
"""Remove accent from string"""
return unicodedata.normalize('NFKD', text).encode('ASCII', 'ignore').decode('utf-8') | 877c37d75f22bb74c7631d1b1cf827305d042702 | 574,114 |
import base64
def base64_to_bytes(seq):
"""Converts seq from ASCII base 64 encoding to byte array"""
return bytes(base64.b64decode(seq)) | e9b507a0b3ace7a14a9688b290d5bb580ad2f592 | 574,121 |
def y_position(coldstart_status):
"""Returns a hardcoded y-position for text
depending on coldstart status."""
if coldstart_status == 'warm':
return 0.8
elif coldstart_status == 'partial':
return 0.6
elif coldstart_status == 'cold':
return 0.4
else:
return 0.1 | 860ec47eb05b96cd68d2af71bae9692dc1612693 | 574,128 |
from typing import List
from typing import Dict
def build_slack_message_blocks(
title: str, markdown_message: str, pipeline_name: str, run_id: str, mode: str, run_page_url: str
) -> List[Dict]:
"""
A helper method to build visually rich Slack message block, primarily used for Slack alerts.
See details... | 951b35e0bb045cc5d61cf2acba7c750d17b2488c | 574,133 |
from datetime import datetime
def get_week_number(dt=datetime.now()):
"""
Returns the week number for the given date.
"""
return dt.date().isocalendar()[1] | 2c1dc14dc6d13ee980e43212ab14b60cd4940142 | 574,138 |
def compose_msg(email_file, format_args):
"""
Compose an email message from the input HTML template, using
the input args as format arguments
:param email_file: Filename of the HTML template.
:param format_args: Formatting arguments for the email.
"""
with open('server/emails/' + email_fil... | 0b71ad923b33d35c8cde3697f6eb93cda7cfaa16 | 574,140 |
def parse_seed(seed_str):
"""converts 3-4 char seed string to integer value"""
return int(seed_str[1:3]) | 81afb0124653b1b41757a8747625306b271be346 | 574,141 |
def drop_rows(rows):
"""Drop rows in a DataFrame and reset the index."""
def dropper(data):
return data.drop(rows).reset_index(drop=True)
return dropper | 9edb8eab028c15355f9883fcab31e47018e4da57 | 574,142 |
def complex_permittivity_to_tan_delta(real_permittivity: float,
imag_permittivity: float) -> float:
"""Computes loss tangent from complex relative permittivity
This is a simple and straightforward calculation of a material's loss
tangent from the real and imaginary par... | 1d0465c5e344c50bb440ab042408bedc104302ba | 574,144 |
def has_overlap(x, y):
"""
Determines whether the text of two entities overlap. This function is symmetric.
Returns
-------
bool
True iff text overlaps.
"""
end_x = x.start + len(x.text)
end_y = y.start + len(y.text)
return x.start < end_y and y.start < end_x | aa988dfdf88f422841ba8e242e294fd33b57bfdc | 574,145 |
def get_junction_tuple(ivc):
"""Convert a |SegmentChain| representing a splice junction to a tuple
Parameters
----------
ivc : |SegmentChain|
A two-exon fragment representing a splice junction
Returns
-------
tuple
`(chromosome name, half-open end of fiveprime ... | e0aa8921e6e7bd19893888b57b8cbfcd475201c6 | 574,146 |
def extractKps(kps1, kps2, ratioMatches):
"""
Take in two sets of keypoints and the matches that survived ratio test
Extract all the keypoints in the set of ratio matches
Return extracted keypoints
"""
newKps1 = list()
newKps2 = list()
for match in ratioMatches:
newKps1.append(kp... | 2ea1600698cc78f1d9bf1b43c0cc0f6788844efa | 574,149 |
from typing import List
import re
import yaml
def parse_multidicts(config: str) -> List[dict]:
"""Parse multiple YAML dictionaries from string, return list of them"""
data = ""
for line in config.split("\n"):
if line.startswith("#") or re.fullmatch(r"^\s+$", line):
print("IGNORE", line... | fbb5b8cee0346eb6257578665ebbbcb88539f645 | 574,150 |
from datetime import datetime
def _convert(value, tzto, defaulttz):
"""Convert datetime.datetime object between timezones"""
if not isinstance(value, datetime):
raise ValueError('value must be a datetime.datetime object')
if value.tzinfo is None:
value = value.replace(tzinfo=defaulttz)
... | 7fd84821c7341647bb8494436cd2b48cc631e015 | 574,156 |
def bitCount(int_type):
"""
Counting bits set, Brian Kernighan's way.
Source: http://wiki.python.org/moin/BitManipulation
"""
count = 0
while int_type:
int_type &= int_type - 1
count += 1
return count | 0c827248372e78043ab27d767ab61db13711b861 | 574,160 |
def _pil_image_to_bytes(p_img):
"""
Get the component bytes from the given PIL Image.
In recent version of PIL, the tobytes function is the correct thing to
call, but some older versions of PIL do not have this function.
:param p_img: PIL Image to get the bytes from.
:type p_img: PIL.Image.Image... | c8dd0a53fdc205429b4ae0074c0fc0b127da60de | 574,162 |
def toupper(s):
"""
string to uppercase
only lowercase letters are modified
"""
_s = ''
for c in s:
if ord(c) >= 97 and ord(c) <= 122:
_s += chr(ord(c) - 32)
else:
_s += c
return _s | 897baceaa3e6883f2ca959dce008179f648274c6 | 574,164 |
def y(v0, t):
"""
Compute vertical position at time t, given the initial vertical
velocity v0. Assume negligible air resistance.
"""
g = 9.81
return v0*t - 0.5*g*t**2 | 1ad7044daee647e4e444c52c09bdb41c014c8aa2 | 574,166 |
import zipfile
def unzip(zfile, outdir):
"""Unpack a zip file into the given output directory outdir
Return True if it worked, False otherwise"""
try:
zf2 = zipfile.ZipFile(zfile)
zf2.extractall(outdir)
return True
except zipfile.BadZipfile:
return False
except Not... | 6ffe697f9810bbc7701855b25628e359f2f58a51 | 574,168 |
from typing import Counter
def dict_to_str (d, tab="\t", ntab=0):
""" Transform a multilevel dict to a tabulated str """
m = ""
if isinstance(d, Counter):
for i, j in d.most_common():
m += "{}{}: {:,}\n".format(tab*ntab, i, j)
else:
for i, j in d.items():
if i... | 389a19b013138e7acaa1ccdc84e6430c30f7b319 | 574,171 |
def func_getattr(val, attr):
"""
Return attribute if it exists; otherwise treat attribute as a dict key.
:param Any val: an object that either has attribute ``attr`` or is a dict
and has a key named ``attr``
:param str attr: name of the attribute/dict key.
"""
try:
r... | 40adc5cff52f937f18ea2fdcc4392a751b6a313c | 574,172 |
def _get_fitness_diff(payoffs, num_players, player_changing, new_strat, base_strat):
"""
Simple function for returning the difference between the payoffs of 2 strategies.
There is a difference in the calculation for 1 or more populations.
Arguments:
payoffs {list of numpy arrays} -- The pa... | b4472b2a920eb91a3988fba9898f55b078aaf5ab | 574,174 |
import pickle
def load_regression_result(filename):
"""
Load a regression result from the specified file.
Parameters
----------
filename : str
the file to load the result from
Returns
-------
result : dict
the dictionary holding the relevant result information
"""... | 2280ac440aef498d951ae55a91d0d313e2e3f909 | 574,176 |
import re
def remove_html_tags(html_str: str):
"""
remove all html tags from the html_str
"""
# remove all tags
page = re.compile(r'<.*?>', re.IGNORECASE)
html_str = page.sub('', html_str)
return html_str | 9078f9eacb214634d7c12a0612927a8911a2a354 | 574,177 |
def amap(x, in_min, in_max, out_min, out_max):
"""
This is an analog of Arduino's `map()` function. It maps the `x` located in range `[in_min, in_max]` to a new value located in range `[out_min, out_max]` accordingly to the position of `x` in `in`-range
This function does not check if `x` is really located... | 4e3effe7aaf3ae96cc62cd309937398f637307ec | 574,178 |
def _P23_T(T):
"""Define the boundary between Region 2 and 3, P=f(T)
Parameters
----------
T : float
Temperature [K]
Returns
-------
P : float
Pressure [MPa]
References
----------
IAPWS, Revised Release on the IAPWS Industrial Formulation 1997 for the
Therm... | 04a46d7a7b16cfd1b5dd0cc3d80a54c080fa50ff | 574,179 |
import math
def gauss(x, mu=0.0, sigma=1.0):
"""
Return the value of the Gaussian probability function with mean mu
and standard deviation sigma at the given x value.
"""
# aus https://introcs.cs.princeton.edu/python/22module/gaussian.py.html
x = float(x - mu) / sigma
return math.exp(-x*x/... | a753f5983c0c2bebab7f34b79e1894f07bb41eeb | 574,180 |
def tact_to_strat_proj_truck_cut_in_6d(x_r, x_h, x_t):
"""Project the given robot, human, and truck tactical states to the 5D strategic
state corresponding to the truck cut-in scenario.
Arguments:
- x_r: robot state
- x_h: human state
- x_t: truck state
The state is
x = [xR, yR_rel... | d3a779dbfa08a236c3b641a2ead17982c871d8fc | 574,182 |
import base64
import uuid
def base64_to_uuid(b64_uuid):
"""Convert a base64-encoded UUID back into a canonical UUID string.
:param b64_uuid: string, Base64-encoded UUID string
:returns: string, Canonical UUID string
"""
## See https://stackoverflow.com/a/23515770/201674
bin_uuid = base64.b6... | a855ec9849379f90ecdfe7da2041c554e7f5da39 | 574,184 |
def _compute_fans(shape):
"""Computes the number of input and output units for a weight shape.
Args:
shape: Integer shape tuple or TF tensor shape.
Returns:
A tuple of integer scalars (fan_in, fan_out).
"""
assert len(shape) == 3 # only used for ensemble dense layer
fan_in = shape... | 7b4a6495b383037577f63808ca8a2acb388733a9 | 574,185 |
def clk_chksum(icmp_packet):
"""Calculate ICMP packet checksum"""
packet_len = len(icmp_packet)
summ = 0
for i in range(0, packet_len, 2):
if i + 1 < packet_len:
# Fold 2 neighbour bytes into a number and add it to the summ
summ += icmp_packet[i] + (icmp_packet[i + 1] <<... | c9fe08f6f09de41867b9320e630362b9afc832b5 | 574,187 |
def getSegments(image,bounds):
"""
Gets separated images acording to bounds provided
Parameters
----------
image(numpy.ndarray) : Image to obtain segmented image from
bounds(list) : List of bounds for segment images as lists [top, down, left, right]
Returns
-------
list : The list ... | 260bff088e396d30c82c37334137a2b470f54a59 | 574,194 |
def scale_loss(loss, loss_scale):
"""Scales the loss by the loss scale."""
if callable(loss):
return lambda: loss() * loss_scale
else:
return loss * loss_scale | 474cb0964a2f04e152c14b97747821b18d2fa223 | 574,196 |
def set_title_str(season, day_of_week):
"""
Generate title string for plot
"""
dow_str = 'Per Month' if day_of_week == 'All' else "Per Month For {}s".format(day_of_week.title())
return "Season {} | Average Daily Trailhead Users {}".format(season, dow_str) | 6184a2908aeed192dba0580dab53edc6c2a2ed81 | 574,199 |
from typing import Dict
import shutil
def dt_calc_table_width(min_widths: Dict[str, int], pad: bool, border: bool,
table_width: int) -> int:
"""Calculate the width of the table based on all of the table parameters
and column min widths.
:param min_widths: Minimum column width by c... | 389ff242b22773afdec2f7cefe61ad06d079ca17 | 574,204 |
import requests
import json
def get_champ_from_id(champ_id):
"""Obtains a champion name given its ID assigned by Riot
Args:
id (int): Champion's ID
Returns:
str: Champion's name
"""
response = requests.get('https://ddragon.leagueoflegends.com/api/versions.json')
version_data... | 43275cc282a2d6ddde9128c71ee6c3ef84be056d | 574,206 |
import socket
def check_free_port(host, port):
"""Check if a given port is available."""
sock = socket.socket()
try:
sock.bind((host, port))
sock.close()
print("host {} on port {} is AVAILABLE".format(host, port))
return(True)
except Exception as e:
print(e)
... | 9351e0d8b46c22e5da119b56b36caf00af8ec5c6 | 574,209 |
import re
def request_url_to_fixture(url: str):
"""Convert a URL path to a fixtures filename ('/account/events' -> 'account_events')"""
params = url.split('?')
return '_'.join([param for param in re.split('/|-', params[0]) if param != '']) | 0b20c02cf804c55de6697f58e61ab5390dad9125 | 574,211 |
def structure_cartesian_coordinates_mapping( structure, symmop ):
"""
Maps the coordinates of pymatgen ``Structure`` according to a ``SymmOp`` symmetry operation.
Args:
structure (``Structure``): The pymatgen ``Structure``.
symmop (``SymmOp``): The pymatgen symmetry operation object.
... | 2d9f8e96d5e7415926d23f7eb3bbfe0ec0f95de3 | 574,213 |
def gm_get(state, b1, b2):
"""
If goal is ('pos',b1,b2='hand') and b is clear and we're holding nothing
Generate either a pickup or an unstack subtask for b1.
"""
if b2 == 'hand' and state.clear[b1] and state.holding['hand'] == False:
if state.pos[b1] == 'table':
return [('a_pick... | 1ed0d8d55f31f7771a71d58f5a0b130e09944817 | 574,214 |
def _fmt_float(x: float) -> str:
"""Format floats appropriately, with 6 decimal points but no trailing zeros."""
res = format(x, '.6f').rstrip('0')
if res.endswith('.'):
return res[:-1]
return res | eb3422402a13a2834e8dde2aa6480983e06c43f9 | 574,216 |
import socket
def is_port_open(port, host="127.0.0.1"):
"""
Check if a port is open
:param port:
:param host:
:return bool:
"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((host, int(port)))
s.shutdown(2)
return True
except Exception... | 111cd436cfe5a5e1b6a8980fc062d49931a498ab | 574,217 |
def union_probability(p_a, p_b, p_intersection):
"""Compute the probability of P(A or B) given P(A), P(B) and P(A and B)"""
return p_a + p_b - p_intersection | a280e62008a2bf3dfeb4b7df5d31f5eb531f9341 | 574,219 |
def rets_date(py_date):
"""
Converts a Python datetime into a RETS (ISO 8601 format) date
:param py_date: a Python datetime
:type pydate: date
:rtype: str
:return: py_date as a string in ISO 8601 format (no microseconds)
"""
return py_date.replace(microsecond=0).isoformat() | e70d8741d3e34e7cca3fb7eee3c07e3f9b0fc7e9 | 574,222 |
def serialize_group(group):
"""Serialize group to JSON-like object."""
return {
'id': group.id if group.is_local else group.name,
'name': group.name,
'provider': group.provider,
'provider_title': group.provider_title if not group.is_local else None,
'identifier': group.id... | ee9d1991595e6595bd03db9c35e43f8c71f80062 | 574,226 |
def _fullSide_(side):
"""
Internal function to return the side based on the string short name
@param side(string) The short name
@return: The full form based on the input
"""
side = side.upper()
sideDict = {"L": "Left",
"R": "Right",
"C": "Centre"
... | 3b671e6829ad04407f60d4ab98682bee3d5e0bda | 574,229 |
import re
def _ExprOverwrite(expr, true_variables):
"""Overwrite variables in |expr| based on |true_variables|.
Overwrite variables in |expr| with 'True' if they occur in |true_variables|,
'False' otherwise.
Args:
expr: The orginal boolean expression, like 'A and B'.
true_variables: Collection of va... | 6e7fa1ecc694a0e9ff279674e6f0a681440cc24d | 574,231 |
def is_prime(n):
"""Returns True if n is prime and False otherwise"""
if n == 1:
return False
# check for all numbers up to sqrt(n) whether they divide n
for divider in range(2, int(n ** 0.5) + 1):
if n % divider == 0:
# if a divider is found, immediately return False
... | 9fd0cc41a275cefdba2d4276057e6ea78427faa0 | 574,237 |
import torch
from typing import Optional
from typing import Sequence
def correct(outputs: torch.Tensor, labels: torch.Tensor,
weights: Optional[torch.Tensor] = None,
top: Sequence[int] = (1,)) -> dict[int, float]:
"""
Args:
outputs: torch.Tensor, shape [N, num_classes],
... | da8302a06e2162ebadb53dcf2d4a123b31a2a41e | 574,239 |
def config_unpack(config):
"""
Unpacks relevant options from the configuration object.
:type config: configobj.ConfigObj
:param config: A configuration object
:rtype tuple
:return Relevant options
"""
return config['main']['host'], config['main']['user'], config['main']['password'] | 6a014822cfa2082d6a089191f970c98e7f8d9f11 | 574,243 |
def pad_to(unpadded, target_len):
"""
Pad a string to the target length in characters, or return the original
string if it's longer than the target length.
"""
under = target_len - len(unpadded)
if under <= 0:
return unpadded
return unpadded + (' ' * under) | 1daf79393b7cf8d8c75e4e32eba4155ec2ee65b6 | 574,244 |
def values(service, id, ranges):
"""Fetch and return spreadsheet cell values with Google sheets API."""
params = {'majorDimension': 'ROWS',
'valueRenderOption': 'UNFORMATTED_VALUE',
'dateTimeRenderOption': 'FORMATTED_STRING',
'spreadsheetId': id,
'ranges':... | 70d1097833086f76006a908f331aa46aef107bd9 | 574,245 |
def scale_image(image, new_width=100):
"""Resizes an image preserving the aspect ratio.
"""
(original_width, original_height) = image.size
aspect_ratio = original_height/float(original_width)
new_height = int(aspect_ratio * new_width)
new_image = image.resize((new_width, new_height))
return... | 22e6f2f2e36f44ec41323bbea6d6b794c6d4d5d7 | 574,248 |
def exp(self, ir="", ia="", name="", facta="", factb="", **kwargs):
"""Forms the exponential of a variable.
APDL Command: EXP
Parameters
----------
ir
Arbitrary reference number assigned to the resulting
variable (2 to NV [NUMVAR]). If this number is the same as
for a previ... | bf54b57b4ad542e14b49fb3c2b41a8e1b9e05272 | 574,250 |
def fix_dir_path(path):
"""Add a / at the end if necessary"""
return path if path.endswith("/") else path + "/" | a2ae0af40191951e813ef579261f83e5262ba99a | 574,253 |
import requests
def get_opensea_collection(collection: str) -> list:
"""Retrieve all assets of collection on OpenSea and return a list of all assets found."""
def get_page(offset: int):
"""Retrieve one page of 50 assets at offset."""
opensea_url = "https://api.opensea.io/api/v1/assets"
... | 77072329e45adf8f750a5736a010a6c36d362834 | 574,254 |
def guess_module_name(fct):
"""
Guesses the module name based on a function.
@param fct function
@return module name
"""
mod = fct.__module__
spl = mod.split('.')
name = spl[0]
if name == 'src':
return spl[1]
return spl[0] | e7153ad73178840108c60167fc155abf32edca61 | 574,256 |
def forkprint(iterator, *filenames, bufferlength=100, sep='\n'):
"""Given an iterator returning (index, line) and N filenames, prints
the line to the index'th filename memory-efficiently.
Returns a tuple of the number of printing operations.
"""
operations = [0]*len(filenames)
buf... | 20df234cb108316c3bc3360b6e45b3bdfbc8d20c | 574,258 |
import csv
def parse_mash_dist_result(path_to_mash_dist_result):
"""
Args:
path_to_mash_screen (str): Path to the mash screen report file.
Returns:
list(dict): Parsed mash screen report
For example:
[
{
"reference_id": "GCF_001519515.1_ASM151951v1_gen... | cae91cc2fdb7aab5e2b2888dbc0eb6b987f3625e | 574,263 |
def write_entities_to_dict(
compartments,
species,
parameters,
reactions,
assignments=None,
parameter_rules=None,
rate_rules=None,
splines=None,
events=None,
):
"""
Transforms inputs to dictionaries with the entities as keys and the
objects as containing all the informati... | 7e5ced47f81f1962a1236e221e181bafa7f61dec | 574,271 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.