content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import shutil
from shutil import copyfile
def copytree(src, dst, ignore=None):
"""Similar to shutil.copytree but makes sure that copyfile is used for copying"""
try:
shutil.copytree(src, dst,
ignore=ignore,
symlinks=False,
ignore_... | ea6800cb32e098df9bd7f02b28fc22af8fca43fe | 596,609 |
def flood_fill(arr, j, i, target, replacement):
"""
Adaption of the 8-neighbours flood fill (See https://en.wikipedia.org/wiki/Flood_fill)
Args:
arr(numpy.ndarray): Array to segment
j(int): rows index
i(int): cols index
target(int): value to replace
... | cf2453590fb42b9a0add4cbc5ec730f58f3980af | 596,610 |
def is_coloring(G, coloring):
"""Determine if the coloring is a valid coloring for the graph G."""
# Verify that the coloring is valid.
for (s, d) in G.edges:
if coloring[s] == coloring[d]:
return False
return True | b10a934f1c9f229c85dcf7ba4c5e5304c9c1afed | 596,612 |
def waveinfo(es, i, channel):
"""Returns 4 values: peak-to-trough amplitude difference, peak-to-trough time difference, min amplitude, and max amplitude for all events on the specified channel."""
w = es.get_spike_waveform(i, channel)
min = 0
max = 0
tmin = 0
tmax = 0
for j in range(0,len(w... | e517a167aaf923dba65c200f5dba369ba6952ded | 596,619 |
def is_str(obj):
"""
Check if object is a string or bytes. On python 3, checking for string
would be sufficient, but on python 2, it may not be.
"""
return isinstance(obj, (bytes, str)) | 44b337a981543a142b1e38f03b26f7ea0175bdf6 | 596,621 |
def pressure(ps, ak, bk):
"""computes pressure at model levels.
Uses surface pressure and vertical hybrid coordinates.
Parameters
----------
ps : xarray.DataArray
Surface pressure field.
ak : xarray.DataArray
Hybrid sigma A coefficient at full levels or
level interfaces... | 67ac7f810cbfad98f52335a3d8135e5132a89bde | 596,623 |
def code_recursive(string: str) -> int:
"""Transforms string into number with symbols' UTF codes
:param str string: string to transform
:rtype: int
"""
if not string:
return 0
num = ord(string[-1])
num_len = 0
while num > 0:
num_len += 1
num = num // 10
r... | b1cafd85a030a3673992aa3671b8980cc3a2045a | 596,626 |
def get_cat_features(X, feature_threshold=2):
"""Determine categorical features
Parameters:
X : array-like, shape (n_samples, n_features)
Training vector, where n_samples is the number of samples and n_features is the number of features.
feature_threshold: int, defaults to 2.
... | cc9f1e64882e57210dd8910e2d21e4e2c8e16438 | 596,627 |
def parse_ui__quit(user_input):
"""Parse quit."""
flag_run = False
return flag_run | f62204dec45ff32b8b5808c7e6267763fe3d74a4 | 596,629 |
def get_index(docs, id):
"""Finds the index of the first doc with a matching id
defaults to -1"""
return next((i for i, d in enumerate(docs) if d[1] == id), -1) | 266477650e9884a35c0d79f2db81380553f01345 | 596,635 |
def get_object_or_none(klass, *args, **kwargs):
"""
Use get() to return an object, or return None
does not exist.
klass may be a Model, Manager, or QuerySet object. All other passed
arguments and keyword arguments are used in the get() query.
Like with QuerySet.get(), MultipleObjectsReturned is ... | a4d96d6461f2bafcac5a1db0947ecd425a158e13 | 596,636 |
import json
def process_event(event):
"""Checks if the event is valid (comes from OneTrigger) and returns the
file path"""
try:
event = json.loads(event)
except Exception as e:
raise Exception(f'Invalid event format: {e}')
if ('Records' in event and
event['Records'] and... | 0722ff5384e8148810841e94df92c87907a57006 | 596,638 |
def should_fetch_alert(alert, existing_ids, alert_status_to_fetch, alert_severities_to_fetch):
""" Check the alert to see if it's data stands by the conditions.
Args:
alert (dict): The alert data
existing_ids (list): The existing alert's ids list
alert_status_to_fetch(str): Status to fi... | a50a370f62ac7f4266ad4827cc1ba61fda0269fd | 596,640 |
import math
def gcd(*args):
"""
Generalize math.gcd to take more than two inputs.
"""
items = list(args)
while len(items) > 1:
items.append(math.gcd(items.pop(), items.pop()))
return items[0] | c9d139b9a05d68e09ff7b0756167d92a0b1c2211 | 596,641 |
import click
def update(obj, service, token):
"""Update a specific service token in the configuration file."""
obj.update(service, token)
obj.save()
click.echo(f"Updated token for {service}.")
return 0 | 7ccb64972ffbc1a7c954bd8a18725a748026f417 | 596,645 |
def const(x):
"""(curried) constant function"""
def f(y):
return x
return f | a533788b770fc663ffb9c8a3182cc2819ace5561 | 596,646 |
def construct_author2doc(doc2author):
"""Make a mapping from author IDs to document IDs.
Parameters
----------
doc2author: dict of (int, list of str)
Mapping of document id to authors.
Returns
-------
dict of (str, list of int)
Mapping of authors to document ids.
"""
... | 75ad52b3c008ad0ac1a6725b6902b911c27731dc | 596,649 |
def sort(items, key=None, start_with_none=False, reverse=False):
"""
Sorts a list (or any other iterable). It differs from built-in
function ``sorted`` by treating ``None`` keys in a special way:
they are all gathered either in the end of the result (default),
or in the beginning. It also constructs... | b4f1c357178846c9567649b765cc46b186faede2 | 596,652 |
import torch
def no_masker(batch_size, mask_shape):
"""Return a mask of all 1."""
mask = torch.ones(1).bool()
# share memory
return mask.expand(batch_size, *mask_shape, 1) | 65001aea30e525b26a6329c60f4b857e09c55f14 | 596,656 |
def dehomogeneize(points):
"""Converts homogeneous coordinates back to cartesian coordinates by
element-wise division by the last row.
Args:
points (np.ndarray): An MxN matrix of N points with M dimension.
The M'th row is assumed to be the additional dimension.
Returns:
np.n... | 0ec2469822898cb2a0a92a9a0384073d7f75c3b3 | 596,657 |
def convert_sets_to_lists(obj):
"""Recursively converts dictionaries that contain sets to lists"""
if isinstance(obj, set):
# This brings short names to the top of the list
try:
obj = sorted(list(obj), key=len)
except TypeError:
obj = list(obj)
elif isinstance... | 973cc071c136f34317f07ee15e08ffb7c6f79dc1 | 596,660 |
def wrap_text(text: str, max_length: int = 16) -> str:
"""Return a new label with wrapped text.
Parameters
----------
text : str
The current label text
max_length : int
The max length for the label (defaults to 16 characters)
Returns
-------
str
The new label te... | 416582db88e4770a5069f2821bb8ee148ed0dc2e | 596,661 |
from typing import List
import yaml
def extract_all_packages_names_and_versions(file_content: str) -> List:
"""Returns the list of packages names and version from a conda environment
file.
Parameters
----------
file_content: str
Content of the environment file
Returns
-------
... | c4baaf4120708c210ff043263ea89170c7eb9416 | 596,662 |
import re
def sanitize_filename(filename):
""" Sanitizes a filename by removing .. / and \\. """
return re.sub(r"(~|(\.\.)|/|\+)", "", filename) | 65027d2c3956e9e423fd78dd464566c662e14dec | 596,664 |
import torch
def masked_mean(input: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
"""
input: (batch, seq_len, hidden_dim)
mask: (batch, seq_len)
output: (batch, hidden_dim)
"""
return (input * mask.unsqueeze(-1)).sum(dim=1) / mask.sum(dim=1, keepdim=True) | 526bcf386e7f05ad69d6a73f488cd3d83af80b95 | 596,665 |
def parse_coeff_line(coeff_str):
"""
split str coef to float list
:param coeff_str : line coef
:type coeff_str : str
:return coeff list
:rtype list()
"""
return [float(el) for el in coeff_str.split()] | f4a616c1b2c4a3396fcb919fa367d49f016353ed | 596,666 |
def create_droplist(keywords, cols):
"""
This function creates a list with all feauters in which the given keywords occur.
Args:
keywords (list): list with keywords to drop
cols (list): list with feauters
"""
drops = []
for key in keywords:
for col in cols:
i... | 8c46dc2c9bb0200c2c7a5e09348911be236d4dbc | 596,668 |
def sg_period_to_hour(period_str):
"""Singapore electricity markets are split into 48 periods.
Period 1 starts at 00:00 Singapore time. Period 9 starts at 04:00.
This function returns hours since midnight, possibly with 0.5 to indicate 30 minutes."""
return (float(period_str) - 1) / 2.0 | 85531d2565839a77d636150e3b70e700cd4c578d | 596,670 |
def list_head_to_string(items, max_items=10):
"""
returns the string representation of a list,
but only showing the first max_items elements
"""
res = "["
for i, item in enumerate(items):
if i >= max_items:
break
if i > 0:
res += ", "
res += str(it... | 384a585464ea8fb76da692f814614cd5080f4721 | 596,675 |
import random
def shuffle_mutation(agent_genome):
"""
Applies a single shuffle mutation to the given road trip.
A shuffle mutation takes a random sub-section of the road trip
and moves it to another location in the road trip.
"""
agent_genome = list(agent_genome)
start_index... | 64747889733b4ccf867b1bae0ee87459dd2b59f2 | 596,678 |
import torch
def crop_border(img: torch.Tensor, border_crop_size: int, order: str = 'NCHW') -> torch.Tensor:
"""Crop borders of image.
Args:
img (torch.Tensor): Input image.
border_crop_size (int): Crop border for each end of height and weight.
order (str, optional): The order of inpu... | 21e4be56fea9fa3f15e2cc1ba78a0adb37417f48 | 596,685 |
def el(site):
"""
Return the element symbol of a pymatgen
site object
"""
return site.specie.symbol | 364938c842754e4072306260ca83fd5cf155c21d | 596,686 |
def File_to_String(file_name):
"""Opens a file and returns the contents as a string"""
in_file=open(file_name,'r')
out_string=in_file.read()
in_file.close()
return out_string | 1b271cfe48328030ae01b367587df90c2ec81897 | 596,687 |
def nbsdot(nv, nb0, nbs, C, e_effective, F, g, alpha, pv, r, eta):
"""
Calculates the rate of change in minutes for the number of bacteria with spacers.
Inputs:
nv : total phage population size at time t
nb0 : number of bacteria without spacers at time t
nbs : number of bacteria with spacer... | 520fbf10bb3950c5e9eb57bc72a7d74416586f38 | 596,701 |
import torch
def lincomb_norm_cov(cov: torch.Tensor, weights: torch.Tensor) -> torch.Tensor:
"""Returns the covariance matrix for w linear combinations of n normal
distributions
Args:
cov (torch.Tensor): n-by-n covariance matrix where the (i, j) entry
corresponds to the covariance of th... | 6fb1aba04a5ad4d3d85485d1c8e836e3d1c55fe1 | 596,708 |
def child_identifier(lang, parent_name, child_name):
"""
Return the identifier for an enum value or struct member.
Sphinx, for some reason, uses a different syntax for this in C and C++.
"""
separator = "::" if lang == "cpp" else "."
return "%s%s%s" % (parent_name, separator, child_name) | 6a2b9df6b1b623f7b8edfbce6b7b590d92558abc | 596,709 |
def parse_number(f):
"""Parse numbers like 123.456 or 1,234M."""
if f[-1] == 'M':
return int(float(f[:-1].replace(',', '.')) * 1e6)
return int(f.replace('.', '')) | 9c6152a12b58a898187f28009fa785bf0b16841c | 596,717 |
def infer_type_from_types(types):
"""
Infer types of a field from its original type list.
"""
type_kinds = len(types)
if type_kinds == 0:
field_type = "empty"
implied_type = "empty"
elif type_kinds == 1:
field_type = types[0]
implied_type = types[0]
elif typ... | f800cd6838085d1921763fd42a4326ff7e1793ce | 596,719 |
def bsearch(target: int, l: list) -> int:
""" 二分查找
:param target:
:param l:
:return:
"""
if not l:
return -1
low = 0
hi = len(l) - 1
while low <= hi:
mid = low + (hi - low) // 2
if l[mid] == target:
return mid
elif l[mid] > target:
... | 3dbd0be0fadde89d3311491664a81f9db0ec4c3f | 596,722 |
import math
def min_spread_record(records, max_field, min_field):
"""Return record with smallest difference between max_field and min_field or None if sequence is empty"""
min_spread = math.inf
rv = None
for rec in records:
if rec[max_field] is None or rec[min_field] is None:
conti... | 79f13fab1909601b9b863125f4700b141c4b8b0a | 596,723 |
def is_simulation_complete(state: tuple) -> bool:
"""Check if simulation has reached end state.
Args:
state (tuple): The current simulation state.
Returns:
bool: True if simulation is complete, False otherwise
"""
hallway, rooms = state
for target_crab, room... | b4317af0a07167123401a181d714ba181e7485c3 | 596,725 |
import torch
def scale_batch_per_example(tensor):
"""Scale batch of tensors to range (0, 1)
Scaling is done by taking the minimum and maximum per channel and example
Parameters
----------
tensor : torch.Tensor or torch.autograd.Variable
Tensor of shape BxCxHxW
"""
b, c, h, w = tensor.shape
out =... | bf274bca3021930ff1bd1afdfe5103a749c46dee | 596,730 |
def integral_1(Nstrips):
"""
The first integral: integrate x**2 between 0 and 1.
"""
width = 1/Nstrips
integral = 0
for point in range(Nstrips):
height = (point / Nstrips)**2
integral = integral + width * height
return integral | 6c0fb99501a5ef647e096c1ba1e960109d97403e | 596,732 |
import re
def requirements(filename):
"""Parse requirements file."""
with open(filename) as f:
lines = f.read().splitlines()
c = re.compile(r'\s*#.*')
return list(filter(bool, map(lambda y: c.sub('', y).strip(), lines))) | 7b5dfab0374c33efb00c83af12ba18702b5ea30f | 596,734 |
def invalid_request_body_with_invalid_priority(
valid_client_model, valid_staff_model
):
"""
A fixture for creating a request body with invalid priority.
Args:
valid_client_model (Model): a valid client model created by a fixture.
valid_staff_model (Model): a valid staff model created b... | c9e50b68d7a28634ece08a41a8f831399e41d6b7 | 596,736 |
def _load_polygons(geojson):
"""
Loads polygons from a geojson file; should work for both MultiPolygon and
FeatureCollection of Polygons
"""
polygons = []
if geojson['type'] == 'MultiPolygon':
for polygon in geojson['coordinates']:
polygons.append(polygon)
elif geojson['t... | b9da48508136ef1f27fff74401b2a041e59c3626 | 596,738 |
def backtrack(node):
"""Iterate back through each path node to return a list of move positions"""
steps = []
while node is not None:
steps.append(node.position)
node = node.parent
return steps[::-1] | af7c3ae291a35f2fbb6a93af502ab5d6649cb980 | 596,744 |
def cipher(text, shift, encrypt=True):
"""
Encrypts or decrypts the alphabetical portion of strings based on a given
integer value of shift.
Parameters
----------
text : str
A string that you want to encrypt/decrypt.
shift : int
An integer by which you want to shift the valu... | c26ce179a0fdc03d4f5d5949937bcc6613f7e8f4 | 596,745 |
def get_switch_port_name (port):
"""
Get the name for the specified switch port.
Parameters:
port -- The port number to use when generating the same.
Return:
The internal name for the switch port.
"""
return "gi" + str (port) | 24eb7f7623575dcdc50869a435707b37f547df89 | 596,750 |
def append_before_ext(path, addition):
""" Add a string between the file descriptor and the extension """
dot_index = path.rfind('.')
if dot_index == -1: # . Not found
return path + addition
return path[:dot_index] + addition + path[dot_index:] | e30a68236f030d70294e90cce41f98a0cfb5fa20 | 596,752 |
def index_to_coord(width, i):
"""Return the 2D position (x, y) which corresponds to 1D index.
Examples:
If we have a 2D grid like this:
0 1 2
3 4 5
6 7 8
We can assert that element 8 is of the coordinate (2, 2):
>>> (2, 2) == index_to_coord(3, 8)
True
"""
i... | 9180b57fae8b6ee1c7342e0c76929195b6995c4a | 596,753 |
def get_cpu_value(repository_ctx):
"""Compute the cpu_value based on the OS name. Doesn't %-escape the result!
Args:
repository_ctx: The repository context.
Returns:
One of (darwin, freebsd, x64_windows, ppc, s390x, arm, aarch64, k8, piii)
"""
os_name = repository_ctx.os.name.lower()
... | 5d29e8b2561bbfa34e96d24576fadfd19b3ddaaf | 596,754 |
def indexToGridCell(flat_map_index, map_width):
"""
Converts a linear index of a flat map to grid cell coordinate values
flat_map_index: a linear index value, specifying a cell/pixel in an 1-D array
map_width: the map's width
returns: list with [x,y] grid cell coordinates
"""
grid_cell_map_x = flat_map_i... | 771b824d6796a7d3c2f8c3be881596a36faaa686 | 596,756 |
def format_tune_scores(results):
"""
Creates a tune_results dict from the output of get_tune_output_dol applied to the results output by fit_and_score.
This creates the proper score names e.g. train_score, test_score, etc. It also formats the tune parameter list.
Parameters
----------
results:... | f212dd8cb43f5c42a390d00f8f4d91d70c3762f6 | 596,759 |
def get_latest_report_date(soup):
"""return the current date and time of the latest report"""
try:
todays_date_in_div = soup.find_all("dd", class_="mrgn-bttm-0")[1]
except IndexError:
print("Invalid City Code. Get code at weather.gc.ca")
exit(0)
return todays_date_in_div.get_text... | 4933789633bf91257b94101f3b1c4ef42531fdc7 | 596,764 |
def getValues(l, index):
"""from list l get the values at indices specified by index"""
return [l[i] for i in index] | 7834228d373f3a6067e78a9dd7a46db9bff3cf84 | 596,765 |
def _parse_brackets(brackets):
"""
Return a `dict` of brackets from the given string.
"""
return dict(zip(brackets[::2], brackets[1::2])) | 6a5e79ba4644856d70dedc64bdacd95a869045f7 | 596,767 |
def format_timer(seconds):
""" formates an integer seconds to a string in minutes : seconds """
minutes = seconds // 60
timer_string = "Time: {:02d}:{:02d}".format(int(minutes), int(seconds) % 60)
return timer_string | 2ffe559635eaae09e4b177331914bb71179ea453 | 596,771 |
def format_seconds(seconds):
"""
Format a floating point representing seconds into
a nice readable string.
Arguments:
seconds The seconds to format.
Returns:
A formatted string as either seconds, minutes, or hours.
"""
output_time = seconds
o... | 277279fb3c37ebbe9db1f6c4fb804391c3ab81e9 | 596,772 |
from typing import Dict
import torch
from typing import Optional
from typing import Union
from typing import List
from typing import Tuple
from typing import KeysView
def detach_dict(data: Dict[str, torch.Tensor], keys: Optional[Union[List, Tuple, KeysView]] = None) -> Dict:
"""Return a detached copy of a diction... | 3a952899509bccd9f7fa23fccf848b024e8c6f93 | 596,774 |
def extract_source_region(region):
"""
DESCRIPTION:
============
Give the lon/lat of the rectangle defining each source
ARGUMENTS:
==========
region, currently defined regions are: taklamakan, north_west, mongolia, jungger_basin
and quaidam_basin
RETURN:
===... | 54f51d5f946304621cee9e553dd9c2c83db90c1c | 596,775 |
from typing import Dict
import collections
def parse_packer_log(packer_log: str) -> Dict[str, str]:
"""Parse the output of packer's -machine-readable format, strange though it may be."""
out = {}
lines = packer_log.strip().split("\n")
fields = [line.split(",") for line in lines]
# We only care ab... | c12edaa555be6701ee4c2087d4db177c1a657b9c | 596,776 |
import re
def prase_data(content, fields_count):
"""
解析数据
:param content:文件内容
:param fields_count:diff字段数
:return: [(,),(,),...]
"""
try:
# 如果匹配的内容中包含\r\n类东西,要用[\s\S]+?
pat = re.compile(r'[~]' + '[\n]{0,}([\s\S]+?)[~][\n]{0,}' * fields_count )
outs = re.findall(pat,... | a9b9a7116923e06827665dbcbb161c27c626f13d | 596,777 |
def wrap_bits_left(binary, amount):
"""Move the characters of the binary string to the left. Bits will
be wrapped. E.g. shift_bits('1011', 1) -> '0111'.
"""
return ''.join([binary[(place + amount) % len(binary)]
for place in range(len(binary))]) | 88fe45f02910cba5b4f2fc594902ee364a80b42d | 596,779 |
def creation_initialization_output_lists(fm):
""" Format function initialization of global measure of descriptors for
list of lists result.
Parameters
----------
fm: pst.FeatureManager
the featuresmanager object.
Returns
-------
initialization_output: function
function ... | 207789830591d0e0c0367c965cc07a7a2890ac09 | 596,781 |
from collections import OrderedDict
def order_by_keys(dict):
"""
Sort a dictionary by keys, case insensitive ie [ Ada, eC, Fortran ]
Default ordering, or using json.dump with sort_keys=True, produces
[ Ada, Fortran, eC ]
"""
return OrderedDict(sorted(dict.items(), key=lambda s: s[0].lower())) | b1f6a7f1ff40154338f43315a2431037860e7b7b | 596,782 |
def getVenueList(timetable):
""" Return a list of all unique venues from the timetable
Args:
timetable: A list of TimetableEntry to scrape venues from
"""
venueList = []
# Add all unique venues from the timetable to the venue list
for entry in timetable:
if not entry.venue in venueList:
venueList.append... | 0cde80a0f31ce45adda351e57d55f3cb74dea598 | 596,783 |
def parametrize_over(cls, test, data):
"""Iterates over dataset and adds test for each combination of params
Args:
cls: TestCase class where tests will be attached.
test: method of TestCase to parametrize.
data: List of ParamSet objects, one for each test run.
Returns:
None... | e444583fcce78882b9c8743a2ecefcebdb2ef5cf | 596,784 |
import ipaddress
def prefixlen(addr):
"""Return the prefix length of an address
"""
return str(ipaddress.ip_interface(addr).network.prefixlen) | 35e660e57b3b02ef3fb5de1bbf2c05d876a458cb | 596,788 |
def pad_batch(batch):
""" pad sequences in batch with 0s to obtain sequences of identical length """
seq_len = list(map(len, batch))
max_len = max(seq_len)
padded_batch = [seq + [0]*(max_len-len(seq)) for seq in batch]
return padded_batch, seq_len | 251a62bc4c89df9c14e51d7ca53d1130901542ed | 596,789 |
import re
def get_latest_app_install(install_path):
"""Locate the most up to date Battle.net install.
Blizzard keeps multiple installs of Battle.net in the install folder
in the form of Battle.net.0000. Use regex to match that plus an optional
digit to still work when the version number hits 5 digits... | 2e0c043f023b0d7b1908b6930aee6f902a2a1dcf | 596,791 |
def get_site_name(html, url):
"""Scrape site name."""
if html.find("meta", property="og:site_name"):
sitename = html.find("meta", property="og:site_name").get('content')
elif html.find("meta", property='twitter:title'):
sitename = html.find("meta", property="twitter:title").get('content')
... | 51878113cafdabdbb893a1ea016fdad4af7ad316 | 596,794 |
def _optionally_make_call(method_name, param):
# type: (str, str) -> str
"""Return a call to method_name if it is not None, otherwise return an empty string."""
if not method_name:
return ''
return "%s(%s);" % (method_name, param) | d71e5c5bb1ba88545156272fa957c59885a80531 | 596,797 |
def logged_superuser_required_alt(x):
"""Alternative method, to test coverage for decorator with and without parenthesis"""
return x | a2dc6aa81432bd67931602ef35cdf0ff6ec4b4a1 | 596,798 |
def encode_test_case(test_case):
"""
Encode test case name to escape commas. Avoids that test case names including commas
are interpreted as several test cases in the comma separated list of enabled test cases
included in the runner_cfg string.
"""
if test_case is not None:
return test_c... | ebb67739c12eaad518a42d9e4906ca7086a5eba5 | 596,801 |
def get_free_symbols(func, symbs_to_ignore=None):
"""
Returns all free elements of a function, by ignoring symbs_to_ignore
:param func: function to check
:param symbs_to_ignore: values to ignore in result
:return: list of all free symbols
"""
if isinstance(func, int) or isinstance(func, floa... | 9887a9795c399d1695219307afa4d92e5d7fe55f | 596,802 |
import math
def get_radian_angle_btwn_vecs(vec1_x, vec1_y, vec2_x, vec2_y):
"""Compute the angle between two vectors (vec1, vec2) in radians.
:param vec1_x: the x-coordinate of vec1
:param vec1_y: the y-coordinate of vec1
:param vec2_x: the x-coordinate of vec2
:param vec2_y: the y-coordinate of ... | f8365b19a4a38eefd3e750556322a1c6522a9e2a | 596,803 |
import torch
def xyxy_to_xywh(boxes: torch.Tensor):
"""Converts a set of boxes in [top_left_x, top_left_y, bottom_right_x, bottom_right_y] format to
[top_left_x, top_left_y, width, height] format"""
assert boxes.shape[-1] == 4
converted = boxes.clone()
converted[..., 2:] -= converted[..., :2]
... | 4854509eca2a75d8ea622dc7cf1fe748ad02bb99 | 596,804 |
def constantly(x):
""" Returns a function that takes any args and returns x """
def func(*args, **kwargs):
return x
return func | 29bc9c107659f8cc3929d3d69ddf6c7c7e7835fd | 596,813 |
def to_char(integer):
""" Convert integer into charactere
>>> ord(to_char(1))
1
>>> ord(to_char(0x80))
128
"""
if integer >= 0x80:
return eval(u"'\\x%02X'"%integer)
else:
return chr(integer) | 2aeccedc66e9c900470872606cf76fd7fd2ada1e | 596,816 |
def assign_node(node):
"""Get the name used by an assignment in the class method."""
return node.body[2].body[0].body[0].value | a9660ccca7e7b18cd099f7799aa265026df622a7 | 596,818 |
import torch
def l2_penalty(var):
"""
L2/Ridge regularization penalty.
Parameters
----------
var : torch.Variable
Torch variable representing the weight matrix over which the penalty
should be computed
Returns
-------
penalty : torch.Variable
Torch variable co... | 2952721742a3acfcd7d8645f95da7955ef5f4f06 | 596,819 |
def get_intrusion_prevention_recommendations(api, configuration, api_version, api_exception, computer_id):
"""Obtains the list of recommended intrusion prevention rules to apply to a computer, according to the results of the last recommendation scan.
:param api: The Deep Security API modules.
:param config... | 72f0688ebeeff55b807f0503a4b1532c08ee2ff5 | 596,820 |
def heat_equation(Cu, Cth, Ck, density=2700, c1=9.52, c2=2.56, c3=3.48):
"""
Heat production equation from Beamish and Busby (2016)
density is the density of the
density: rock density in kg/m3
Cu: weight of uranium in ppm
Cth: weight of thorium in ppm
Ck: weight of potassium in %
... | 0767c0e5b735e6efdb3b36c8468a9fa8a4b77ca3 | 596,825 |
import random
def add_random_choices(choices, stats):
"""
Given randomly choose 4 options from choices. It also records data about
the choices in stats so we can ensure the generated stats are accurate.
:param choices: A list of (key, value) pairs to choose from.
:param stats: A dict in the forma... | d0b3840302680cfad9598e4a3e2a10c3aaaf1b67 | 596,828 |
def lines_intersect(line1, line2):
"""Check if two lines intersect.
Algorithm defined here:
https://bryceboe.com/2006/10/23/line-segment-intersection-algorithm/
Parameters
----------
line1 : tuple of (tuple, tuple)
each element is the x, y position defining an endpoint of line1
lin... | b8b8c130adb08db77c92e9ef3cfb5c77185a985a | 596,829 |
def is_job_flow_done(job_flow):
"""Return True if the given job flow is done running."""
return hasattr(job_flow, 'enddatetime') | 10a44d5c61f5a23d8cef0ae4d686bc799fdba6f5 | 596,831 |
def mean_over_dims(x, dims):
"""Take a mean over a list of dimensions keeping the as singletons"""
for dim in dims:
x = x.mean(dim=dim, keepdim=True)
return x | 6e4dcba935b67c6c5e8e028c9e9a0930f1d84201 | 596,832 |
def build_scoring_matrix(alphabet, diag_score, off_diag_score, dash_score):
"""
Takes as input a set of characters alphabet and three scores diag_score,
off_diag_score, and dash_score. The function returns a dictionary of
dictionaries whose entries are indexed by pairs of characters in alphabet
plus... | e1c9acbcb41c5d30772d8201532146d84140f914 | 596,835 |
def dataverse_tree_walker(
data: list,
dv_keys: list = ["dataverse_id", "dataverse_alias"],
ds_keys: list = ["dataset_id", "pid"],
df_keys: list = ["datafile_id", "filename", "pid", "label"],
) -> tuple:
"""Walk through a Dataverse tree by get_children().
Recursively walk through the tree struc... | a3ce15354e5a9b6c38510eafaec0dfa531b595ef | 596,836 |
import pathlib
import typing
def list_subdirs(path: pathlib.Path) -> typing.List[pathlib.Path]:
"""Returns a list of subdirectories"""
subdirs = [f for f in path.iterdir() if f.is_dir() and not f.name[0] in (".", "_")]
return subdirs | b2813b8004e5fb79f3a27f33f8bf4ad06221ba1f | 596,837 |
def normalize(x):
"""
Normalize input features
:param x: original features
:return: normalized features
"""
x_norm = x.astype('float32') / 255.0
return x_norm | 460cb15f31bef6502add291e461ed7ea5b87d1a0 | 596,843 |
def sequence_kmers(sequence, kmer_canonical, k):
"""Returns a set of canonical kmers of length k from
the sequence
Args:
sequence (str): Sequencing read
kmer_canonical (dict): Hashmap of kmer as key
and its canonical kmer as the value
k (int): Length of kmer
Returns... | c38255467289cef6e58662bdc87075b355d6e6f3 | 596,844 |
def correlate(groups_, users):
"""
Correlate the role with the users via the groups.
Example:
>>> # Define the groups and their roles.
>>> groups = {
>>> "admin": ["role/owner", "role/manager"],
>>> "dev": ["role/viewer"],
>>> "ops": ["role/editor"],
... | 406128f6914ded01aaded8dd88fb62f5d8aeb4bb | 596,847 |
def addGMSHCircle( number, startPoint, centerPoint, endPoint ):
""" Add a circle to GMSH """
string = "Circle(" + str(number) + ") = {" + str(startPoint) + ", " + str(centerPoint) + ", " + str(endPoint) + "};"
return string | 1650b516a0fa2f8f85860fdb25ef74cbed1b5eff | 596,850 |
def merge_dict(target, *to_merge):
"""Merges dictionaries into a target. If keys already exist,
only merges target if they are not falsey.
Args:
target: dict -- Will be modified
*to_merge: dicts -- Will be merged into target
Returns:
dict -- modified target
"""
for d in ... | fef411beeabcb6da294995560dd1a5c7996f22c5 | 596,852 |
from typing import Set
from typing import List
from pathlib import Path
def get_local_scenario_cache(cache_path: str, feature_names: Set[str]) -> List[Path]:
"""
Get a list of cached scenario paths from a local cache.
:param cache_path: Root path of the local cache dir.
:param feature_names: Set of re... | 29d7b71b1fcface257d68e3ed1c7444edd105304 | 596,853 |
def tex_braces(obj):
"""Return obj with curly braces if there are more than one character."""
result = str(obj)
return f"{{{result}}}" if len(result) > 1 else result | 53d2efe6faaefd825fd449e61a97126e7f6afd51 | 596,855 |
def channelFirst(tensor):
"""
Permute the dimension to match pytorch convention
for images (BCHW: Batch x Channel x Height x Width).
:param tensor: (th.Tensor)
:return: (th.Tensor)
"""
return tensor.permute(0, 3, 1, 2) | 177c9493c7ba7285d0eb096d3ae05f5fe47b0808 | 596,858 |
def dataframe_summary (df):
"""
Computes summary statisitcs of a data frame
:param df: Dataframe to comoute statistics for
:return: Dataframe with summary statisitcs for input data frame
"""
df_summary = df.describe(include='all')
df_summary.loc['Missing #'] = df.isnull().sum(axis=0)
df... | 7948a28380894ac6b5ba4f5e31ca3499215c633a | 596,860 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.