content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def pe(cmd, shell=True):
"""
Print and execute command on system
"""
ret = []
for line in execute(cmd, shell=shell):
ret.append(line)
print(line, end="")
return ret | 0a238be68a7c383153834d45fbf3193f9b8c9a72 | 13,957 |
def crop(image):
"""
Method to crop out the uncessary white parts of the image.
Inputs:
image (numpy array): Numpy array of the image label.
Outputs:
image (numpy array): Numpy array of the image label, cropped.
"""
image = ImageOps.invert(image)
imageBox = image.getbbox()
imag... | 37a12733bcda66a9da16d72ff3fae749784481a0 | 13,959 |
def all_pairs_normalized_distances(X):
"""
We can't really compute distances over incomplete data since
rows are missing different numbers of entries.
The next best thing is the mean squared difference between two vectors
(a normalized distance), which gets computed only over the columns that
tw... | c744c6ac87cbd3760d6512178747ac60794d616a | 13,960 |
import torch
def forward_pass(model, target_angle, mixed_data, conditioning_label, args):
"""
Runs the network on the mixed_data
with the candidate region given by voice
"""
target_pos = np.array([
FAR_FIELD_RADIUS * np.cos(target_angle),
FAR_FIELD_RADIUS * np.sin(target_angle)
... | e9644b01ea04b08ae92d50d3c7944e0d72213b2b | 13,961 |
import select
from typing import Optional
from datetime import datetime
import pytz
async def get_event_by_code(code: str, db: AsyncSession) -> Event:
"""
Get an event by its code
"""
statement = select(Event).where(Event.code == code)
result = await db.execute(statement)
event: Optional[Event... | 592cd6b5aad7b12a98889bf82ea7e32a55b8832e | 13,962 |
def get(name):
"""Returns an OpDef for a given `name` or None if the lookup fails."""
with _sync_lock:
return _registered_ops.get(name) | 75e3ba3601f1ad8f67e77046a9b286bee8e60be6 | 13,963 |
def angle_detect_dnn(img, adjust=True):
"""
文字方向检测
"""
h, w = img.shape[:2]
ROTATE = [0, 90, 180, 270]
if adjust:
thesh = 0.05
xmin, ymin, xmax, ymax = int(thesh * w), int(thesh * h), w - int(thesh * w), h - int(thesh * h)
img = img[ymin:ymax, xmin:xmax] ##剪切图片边缘
in... | a3fc8513afce26e96a315a606acfd9be9feaa376 | 13,964 |
def get_correct_line(df_decisions):
"""
The passed df has repeated lines for the same file (same chemin_source).
We take the most recent one.
:param df_decisions: Dataframe of decisions
:return: Dataframe without repeated lines (according to the chemin_source column)
"""
return df_decisions.... | 989f1aba1c5e0c61f8b7ca1c883baf4dd181ebbc | 13,965 |
def fix_1(lst1, lst2):
"""
Divide all of the elements in `lst1` by each element in `lst2`
and return the values in a list.
>>> fix_1([1, 2, 3], [0, 1])
[1.0, 2.0, 3.0]
>>> fix_1([], [])
[]
>>> fix_1([10, 20, 30], [0, 10, 10, 0])
[1.0, 2.0, 3.0, 1.0, 2.0, 3.0]
"""
out = []
... | 7929cfc19952a829c66c18af967668d1015f8477 | 13,966 |
def user_wants_upload():
"""
Determines whether or not the user wants to upload the extension
:return: boolean
"""
choice = input("Do you want to upload your extension right now? :")
if "y" in choice or "Y" in choice:
return True
else:
return False | 67643d1ccf8d1ffe23ddc503cd8e9f4dc4e98707 | 13,967 |
def has_genus_flag(df, genus_col="mhm_Genus", bit_col="mhm_HasGenus", inplace=False):
"""
Creates a bit flag: `mhm_HasGenus` where 1 denotes a recorded Genus and 0 denotes the contrary.
Parameters
----------
df : pd.DataFrame
A mosquito habitat mapper DataFrame
genus_col : str, default=... | 7e178f7570f8de436521047e012518e6f5ee6a72 | 13,968 |
from typing import Tuple
def compass(
size: Tuple[float, float] = (4.0, 2.0),
layer: Layer = gf.LAYER.WG,
port_type: str = "electrical",
) -> Component:
"""Rectangular contact pad with centered ports on rectangle edges
(north, south, east, and west)
Args:
size: rectangle size
... | fefa0842958fb91b870eb78e2170a81d7c8daaa9 | 13,969 |
def get_service(vm, port):
"""Return the service for a given port."""
for service in vm.get('suppliedServices', []):
if service['portRange'] == port:
return service | d617771c25c69ee874b0bc64adcc735aa876f929 | 13,970 |
async def async_setup_entry(hass, config_entry):
"""Set up AirVisual as config entry."""
entry_updates = {}
if not config_entry.unique_id:
# If the config entry doesn't already have a unique ID, set one:
entry_updates["unique_id"] = config_entry.data[CONF_API_KEY]
if not config_entry.opt... | e09b0c8e499a055123a88503cac4d1d1492a3d53 | 13,971 |
def rotation_point_cloud(pc):
"""
Randomly rotate the point clouds to augment the dataset
rotation is per shape based along up direction
:param pc: B X N X 3 array, original batch of point clouds
:return: BxNx3 array, rotated batch of point clouds
"""
# rotated_data = np.zeros(pc.shape, dtyp... | f1f84b9dad06bea6c377559d8b4a64be88031847 | 13,972 |
import time
def alliance_system_oneday(mongohandle, alliance_id, system):
"""find by corp and system - one day"""
allkills = mongohandle.allkills
system = int(system)
timeframe = 24 * 60 * 60
gmtminus = time.mktime(time.gmtime()) - timeframe
cursor = allkills.find({"alliance_id": alliance_id,
... | b951f11f606352dc6614e1ff1c587c3a64ed1ea8 | 13,973 |
def slit_select(ra, dec, length, width, center_ra=0, center_dec=0, angle=0):
"""
:param ra: angular coordinate of photon/ray
:param dec: angular coordinate of photon/ray
:param length: length of slit
:param width: width of slit
:param center_ra: center of slit
:param center_dec: center of s... | a3047a59bbc8566d261f1d52f92b437ad2b26d52 | 13,974 |
def login():
""" Logs in user """
req = flask.request.get_json(force=True)
username = req.get('username', None)
password = req.get('password', None)
user = guard.authenticate(username, password)
ret = {'access_token': guard.encode_jwt_token(user)}
return ret, 200 | b577c7982bf65d3a24cfd3f116f5cb128079cd1f | 13,975 |
def statuses_filter(auth, **params):
"""
Collect tweets from the twitter statuses_filter api.
"""
endpoint = "https://stream.twitter.com/1.1/statuses/filter.json"
if "follow" in params and isinstance(params["follow"], (list, tuple)):
params["follow"] = list_to_csv(params["follow"])
if ... | e81f85d5c747a4bcca8fc9b3b82d362905404452 | 13,976 |
def adjust_hue(image, hue_factor):
"""Adjusts hue of an image.
The image hue is adjusted by converting the image to HSV and
cyclically shifting the intensities in the hue channel (H).
The image is then converted back to original image mode.
`hue_factor` is the amount of shift in H channel and must... | 52390b83a60cc8f23632f198a558b518d687f94e | 13,977 |
import json
import requests
import time
def lambda_handler(event, context):
"""Sample pure Lambda function
Parameters
----------
event: dict, required
API Gateway Lambda Proxy Input Format
Event doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-int... | 05b5da6e2c2aff16c43a3822978f0cd800370bed | 13,978 |
def compareDict(a, b):
"""
Compare two definitions removing the unique Ids from the entities
"""
ignore = ['Id']
_a = [hashDict(dict(x), ignore) for x in a]
_b = [hashDict(dict(y), ignore) for y in b]
_a.sort()
_b.sort()
return _a == _b | 19f0340064c95584a4e80ecb4a090c25944f6923 | 13,979 |
import traceback
import time
def create_twitter_auth(cf_t):
"""Function to create a twitter object
Args: cf_t is configuration dictionary.
Returns: Twitter object.
"""
# When using twitter stream you must authorize.
# these tokens are necessary for user authe... | 0eff78ce2dba182d739cc2bb082d5053a6a8847a | 13,980 |
def _project(doc, projection):
"""Return new doc with items filtered according to projection."""
def _include_key(key, projection):
for k, v in projection.items():
if key == k:
if v == 0:
return False
elif v == 1:
return... | 0f2cd190e73b39ceeec0f850054baab1dd357587 | 13,981 |
import random
def random_swap(words, n):
"""
Randomly swap two words in the sentence n times
Args:
words ([type]): [description]
n ([type]): [description]
Returns:
[type]: [description]
"""
def swap_word(new_words):
random_idx_1 = random.randint(0, l... | d6916404c363176f13010d006cd61354dcd4e16e | 13,982 |
def get_dist_for_angles(dict_of_arrays, clusters, roll, pitch, yaw, metric='3d', kind='max'):
"""
Calculate a single distance metric for a combination of angles
"""
if (dict_of_arrays['yaw_corr'] == 0).all():
rot_by_boresight = apply_boresight_same(dict_of_arrays, roll, pitch, yaw)
else:... | 4db8a68cebc845de942817eb9eb28e57d2db5cc4 | 13,983 |
import asyncio
async def stream():
"""Main streaming loop for PHD"""
while True:
if phd_client.is_connected and manager.active_connections:
response = await phd_client.get_responses()
if response is not None:
# Add to the websocket queue
# If it ... | 19e1934e8cb48fa66f8ab3f61ca013fd19b040fc | 13,984 |
def filter_camera_angle(places, angle=1.):
"""Filter pointclound by camera angle"""
bool_in = np.logical_and((places[:, 1] * angle < places[:, 0]),
(-places[:, 1] * angle < places[:, 0]))
return places[bool_in] | 9956c5b001989c5f64d935087a1e13ffbc6469b7 | 13,985 |
def load_nifti(path: str) \
-> tuple[np.ndarray, np.ndarray, nib.nifti1.Nifti1Header]:
"""
This function loads a nifti image using
the nibabel library.
"""
# Extract image
img = nib.load(path)
img_aff = img.affine
img_hdr = img.header
# Extract the actual data in a numpy arra... | 9e76e3f6e6d200b3cd3be34b3780f8fe84cad53e | 13,986 |
def f5_list_policy_hostnames_command(client: Client, policy_md5: str) -> CommandResults:
"""
Get a list of all policy hostnames.
Args:
client (Client): f5 client.
policy_md5 (str): MD5 hash of the policy.
"""
result = client.list_policy_hostnames(policy_md5)
table_name = 'f5 da... | 38263c85480ba5d7de8a21509820052444b4cdab | 13,987 |
def predict(m, count, s, A):
"""predict the chain after s
calculate the probability of a m-length chain,
then return chains.
CAUTION the number of chains maybe less then count
args:
m: the length of predict chain
count: the number of predict chain
s: the last element of the... | f45acc67c97204efdabb48f29d73277fb4b75967 | 13,988 |
def f_multidim(anchors, basis, distance_measurements, coeffs):
"""
:param anchors: anchors dim x N
:param basis: basis vectors K x M
:param distance_measurements: matrix of squared distances M x N
:param coeffs: coefficient matrix dim x K
:return: vector of differences between estimate distanc... | cd9f7fa67e6cbf3cfb5fe14e53b019713c56aa26 | 13,990 |
def getHomography(indict, outdict, outsize=None):
"""Returns a transformation to go from input pts to output pts using a homography.
'indict' and 'outdict' should contain identical keys mapping to 2-tuples.
We create A:
x1 y1 1 0 0 0 -x1*x1' -y1*x1'
0 0 0 x1 y1 1 -x1*y1' -y1*y1'
... | 709fad7ffba7047e8d2c15e79611c3ac897733b7 | 13,991 |
def variables_to_restore(scope=None, strip_scope=False):
"""Returns a list of variables to restore for the specified list of methods.
It is supposed that variable name starts with the method's scope (a prefix
returned by _method_scope function).
Args:
methods_names: a list of names of configurable methods... | bc1f433b6a67898d8c010a56c6c51821f50df81a | 13,992 |
def from_strings(data, gaps="-", length=None, dtype=np.int8):
"""Convert a series of strings to an array of integer encoded alleles.
Parameters
----------
data : array_like, str
Sequence of strings of alleles.
gaps : str, optional
String of symbols to be interpreted as gaps in the s... | 7405e208613aa75b132f686fcf5fe7451a4160cc | 13,993 |
def get_relationship_targets(item_ids, relationships, id2rec):
"""Get item ID set of item IDs in a relationship target set"""
# Requirements to use this function:
# 1) item Terms must have been loaded with 'relationships'
# 2) item IDs in 'item_ids' arguement must be present in id2rec
# ... | 55542448af0eb2b46442bff0e0464361b669241a | 13,994 |
def cli(ctx, newick, analysis_id, name="", xref_db="null", xref_accession="", match_on_name=False, prefix=""):
"""Load a phylogenetic tree (Newick format) into Chado db
Output:
Number of inserted trees
"""
return ctx.gi.phylogeny.load_tree(newick, analysis_id, name=name, xref_db=xref_db, xref_accessio... | 9b68dec5584a692f2fe04746d9bb179c9e002682 | 13,995 |
def roll_neighbors(sites, site, dims=None, radius=1):
""" N-dimensional pixel neighborhood
for periodic images on regular grids """
index = np.unravel_index(site, dims=dims)
neighs = sites.take(nbr_range+index, axis=0, mode='wrap')
return neighs.flatten() | e653604c07f4824ef766c3a7f41a6c6c8a35bad0 | 13,996 |
import requests
import json
def folder0_content(folder0_id, host, token):
"""
Modules
-------
request, json
----------
Parameters
----------
folder0_id : Onedata folder level 0 id containing the data to publish.
host : OneData provider (e.g., ceta-ciemat-02.datahub.egi.eu).
tok... | 8ce6ae617666f936643b9599ae115e140b30bd2b | 13,999 |
import urllib
import json
def fetch_object(object_id: int, url: str):
"""
Fetch a single object from a feature layer. We have to fetch objects one by one, because they
can get pretty big. Big enough, that if you ask for more than one at a time, you're likely to
encounter 500 errors.
object_id: ob... | d193d9368eec79028beeb545a3fe411fa0c131bc | 14,000 |
def density_forecast_param(Yp, sigma, _, rankmatrix, errordist_normed, dof):
"""creates a density forecast for Yp with Schaake Schuffle
Parameters
----------
Yp: numpy.array
24-dimensional array with point-predictions of day ahead prices
sigma: nump... | 809458a7d3de0ae2997f392e52f91a9b4c02e181 | 14,001 |
def gaussian_blur(img: np.ndarray, kernel_size: int) -> np.ndarray:
"""Applies a Gaussian Noise kernel"""
if not is_valid_kernel_size(kernel_size):
raise ValueError(
"kernel_size must either be 0 or a positive, odd integer")
return cv2.GaussianBlur(img, (kernel_size, kernel_size), 0) | 6bedc6b15848c18ed52c8348f3bec1b4181f74d7 | 14,002 |
def get_controls_snapshots_count(selenium, src_obj):
"""Return dictionary with controls snapshots actual count and count taken
from tab title."""
controls_ui_service = webui_service.ControlsService(selenium)
return {
"controls_tab_count": controls_ui_service.get_count_objs_from_tab(
src_obj=src_... | 5e6a11a2a94093850f810e0ec6c93037a9f40bca | 14,003 |
import random
import math
def fast_gnp_random_graph(n, p, seed=None, directed=False):
"""Returns a `G_{n,p}` random graph, also known as an Erdős-Rényi graph or
a binomial graph.
Parameters
----------
n : int
The number of nodes.
p : float
Probability for edge creation.
se... | f84c577a4f575186913980c8d9a5dcc16d771291 | 14,004 |
import math
def round_to(f: float, p: int = 0) -> float:
"""Round to the specified precision using "half up" rounding."""
# Do no rounding, just return a float with full precision
if p == -1:
return float(f)
# Integer rounding
elif p == 0:
return round_half_up(f)
# Round to ... | ad464bced2e2b1b87208f61e7ca73b42d5e31fa5 | 14,005 |
def get_interface_type(interface):
"""Gets the type of interface
"""
if interface.upper().startswith('GI'):
return 'GigabitEthernet'
elif interface.upper().startswith('TE'):
return 'TenGigabitEthernet'
elif interface.upper().startswith('FA'):
return 'FastEthernet'
elif i... | 8a898f75e0e05715e0ced7258b8e8d4bf9905377 | 14,006 |
def __get_global_options(cmd_line_options, conf_file_options=None):
""" Get all global options
:type cmd_line_options: dict
:param cmd_line_options: Dictionary with all command line options
:type conf_file_options: dict
:param conf_file_options: Dictionary with all config file options
:returns: ... | 3c9880616ae274f4254cdd29558f1022fdfc6ff4 | 14,007 |
def download_file(service, drive_file):
"""Download a file's content.
Args:
service: Drive API service instance.
drive_file: Drive File instance.
Returns:
File's content if successful, None otherwise.
"""
download_url = drive_file.get('downloadUrl')
if download_url:
resp, content = service... | fa8ad859e47dbaec0cb9a4eea0be5497239e359e | 14,008 |
def get_include_file_end_before(block: Block) -> str:
"""
>>> # test end-before set to 'end-marker'
>>> block = lib_test.get_test_block_ok()
>>> get_include_file_end_before(block)
'# end-marker'
>>> assert block.include_file_end_before == '# end-marker'
>>> # test end-before not set
>>>... | c8ae330fb24a2a7e5304d8a5e5c5438bf9346c63 | 14,009 |
import torch
import random
def add_random_circles(tensor: torch.Tensor, n_circles: int, equalize_overlaps: bool = True):
"""Adds n_circles random circles onto the image."""
height, width = tensor.shape
circle_img = torch.zeros_like(tensor)
for _ in range(n_circles):
circle_img = add_circle(cir... | 17e0cf8d53cf0f8b3c542f0fd0f49151c6842ba9 | 14,010 |
def sample_quadric_surface(quadric, center, samples):
"""Samples the algebraic distance to the input quadric at sparse locations.
Args:
quadric: Tensor with shape [..., 4, 4]. Contains the matrix of the quadric
surface.
center: Tensor with shape [..., 3]. Contains the [x,y,z] coordinates of the
... | e4448be0058f4a8010a72eaf9506e95695b1b35e | 14,011 |
def mol2df(mols: Mols[pd.DataFrame], multiindex=False) -> pd.DataFrame:
"""
flattens a mol into a dataframe with the columns containing the start, stop and price
:param mols: mols to transform
:return:
"""
if multiindex:
flat = {
((start, stop), price): series
for... | 63b16fa99a9c76a29cbef8755cf29928f05637f6 | 14,012 |
from typing import Tuple
def load_sequence_classifier_configs(args) -> Tuple[WrapperConfig, pet.TrainConfig, pet.EvalConfig]:
"""
Load the model, training and evaluation configs for a regular sequence classifier from the given command line
arguments. This classifier can either be used as a standalone mode... | 8729851faae06ed7c0331960db4f933283e7278e | 14,013 |
def gender(word):
""" Returns the gender for the given word, either:
MALE, FEMALE, (MALE, FEMALE), (MALE, PLURAL) or (FEMALE, PLURAL).
"""
w = word.lower()
# Adjectives ending in -e: cruciale, difficile, ...
if w.endswith(("ale", "ile", "ese", "nte")):
return (MALE, FEMALE)
# Mos... | 7a8384d778b9aec9fcc5eb32f26c282805cdfa0b | 14,014 |
from typing import Counter
def fcmp(d,r):
"""
Compares two files, d and r, cell by cell. Float comparisons
are made to 4 decimal places. Extending this function could
be a project in and of itself.
"""
# we need to compare the files
dh=open(d,'rb')
rh=open(r,'rb')
dlines = dh... | 9f6f24314316fbef26ce0fb404a88d34c3049b2b | 14,015 |
def is_vector_equal(vec1, vec2, tolerance=1e-10):
"""Compare if two vectors are equal (L1-norm) according to a tolerance"""
return np.all(np.abs(vec1 - vec2) <= tolerance) | 9bb42fa3bc2cbb25edd6eabeddb2aa2d8d93e5c8 | 14,016 |
def partition_pair(bif_point):
"""Calculate the partition pairs at a bifurcation point.
The number of nodes in each child tree is counted. The partition
pairs is the number of bifurcations in the two child subtrees
at each branch point.
"""
n = float(sum(1 for _ in bif_point.children[0].ipreord... | 7889eb95a0ac3b2a7d1138061a4651b1e79427c0 | 14,017 |
def readPyCorrFit(file):
"""
Read header and data of .csv PyCorrFit output file
========== ===============================================================
Input Meaning
---------- ---------------------------------------------------------------
file String with path to .csv file
... | 0dcaa26c0ef2f8270748241cbd03bc6aaa750672 | 14,018 |
def end_of_time(t):
""" Return the next hour of the passed time. e.g, 18:25:36 --> 19:00:00 """
return t + timedelta(minutes=60) - timedelta(minutes=t.minute) - timedelta(seconds=t.second) | dce1f0cde67c834580edb349e0dfbcdee0b4d171 | 14,019 |
def modf(x):
"""modf(x)
Return the fractional and integer parts of x. Both results carry the sign
of x.
"""
signx = sign(x)
absx = Abs(x)
return (signx * Mod(absx, 1), signx * floor(absx)) | 18f4e9aca22591f2960bb6ddf28fcf677bedee65 | 14,020 |
from typing import Tuple
def get_user_from_request(request, available_query_params: list()) -> Tuple[User, GeneralApiResponse]:
"""
Entra com o request da view e uma lista de query params do user que podem ser consultados
Retorna um user caso seja si mesmo, ou tenha permissão de acesso a outros usuários
... | b9d0274ac5ea8e0cbc210b1f4f5e8d46398e8e6d | 14,021 |
def longest_CD(values):
"""
Return the sequence range for the longest continuous
disorder (CDl) subsequence.
"""
# Filter residues with score equal or greater than 0.5
# and store its position index
dis_res = [index for index, res in enumerate(values)
if float(res) >= 0.5]
... | f07b74b9553c156d2d4b62e17ea02b466a16fe74 | 14,022 |
def get_read_length(filename):
""" Return the first read length of fastq file.
:param str filename: fastq file.
"""
with FastqReader(filename) as filin:
read_len = len(next(iter(filin)))
return read_len | 961af7ff12c422c68349dabee064acd465a1a090 | 14,023 |
def no_outliers_estimator(base_estimator, x, alpha=0.01):
""" Calculate base_estimator function after removal of extreme quantiles
from the sample
"""
x = np.array(x)
if len(x.shape) < 3:
x = np.expand_dims(x, -1)
low_value = np.quantile(x, alpha, axis=(0, 1))
high_value = np.quantil... | 3c23f9cacc1108d6ecb24b690ff731e3a3554b44 | 14,024 |
from server.forms import FormNotCompleteError, FormValidationError
from typing import cast
from typing import Tuple
def error_state_to_dict(err: ErrorState) -> ErrorDict:
"""Return an ErrorDict based on the exception, string or tuple in the ErrorState.
Args:
err: ErrorState from a api error state
... | 79cf9a971886241c8760bf0091af0c91a4d80ade | 14,025 |
from typing import Set
def english_words() -> Set[str]:
"""Return a set of english words from the nltk corpus "words".
Returns:
Set of english words.
"""
nltk_resource("corpora/words")
return set(nltk.corpus.words.words()) | 2cda38fb0026805c7792bcf45727492b09b38a89 | 14,026 |
def bipartite_matching_wrapper(a, b, score_func, symmetric=False):
"""A wrapper to `bipartite_matching()` that returns `(matches, unmatched_in_a, unmatched_in_b)`
The list of `matches` contains tuples of `(score, a_element, b_element)`. The two unmatched
lists are elements from each of the respective input... | 702c290b6874b595fb0249c865c5723c84d485ba | 14,027 |
def get_interface_type(interface):
"""Gets the type of interface
Args:
interface (str): full name of interface, i.e. Ethernet1/1, loopback10,
port-channel20, vlan20
Returns:
type of interface: ethernet, svi, loopback, management, portchannel,
or unknown
"""
if in... | 8196bfa37ef25f0fa1c08577d215329ecc977c4a | 14,029 |
def create_int_feature_list(name, key, prefix="", module_dict=None):
"""Creates accessor functions for bytes feature lists.
The provided functions are has_${NAME}, get_${NAME}_size, get_${NAME}_at,
clear_${NAME}, and add_${NAME}.
example = tensorflow.train.SequenceExample()
add_image_timestamp(1000000, exam... | 58b08f518050a67db72f0572a78f7dab5a68d468 | 14,030 |
def ROC(y_pred, y_true, positive_column = 0,draw = True):
"""
ROC
"""
y_pred = y_pred[:,0]
y_true = y_true[:,0]
# sort by y_pred
sort_index = np.argsort(-y_pred)
y_pred = y_pred[sort_index]
y_true = y_true[sort_index]
tprs = []
fprs = []
positive_num = (y_tru... | efeefbd570988c83f912345794cbd19e15ec67a2 | 14,031 |
def ignore_check(self, channel: discord.TextChannel, ignore_dm: bool = False, from_main: bool = False):
"""
A function that checks whether or not that channel allows command.
Args:
self: instance of the class this command calls or this can be commands.Bot
channel (discord.TextChannel): the ... | 284ba6432d792a3382383cf9b53a5932897b5e53 | 14,032 |
def network_count_allocated_ips(context, network_id):
"""Return the number of allocated non-reserved ips in the network."""
return IMPL.network_count_allocated_ips(context, network_id) | 33f7ce340d222c3843962e6e64a06440e5dfd526 | 14,033 |
def _parse_transform_spec( transform_spec ):
"""
Parses a transform specification into its name and parameters dictionary.
Raises ValueError if the specification is invalid, it represents an unknown
transform, or if the encoded parameters do not match the transform's expected
types.
Takes 1 ar... | b914d96d9ad1e8da3deb10f1c6500c2ee58b4928 | 14,034 |
from typing import Union
from typing import List
def parse_text_multiline(data: Union[str, List[str]]) -> str:
"""Parse the text in multiline mode."""
if isinstance(data, str):
return data
elif isinstance(data, list) and all(map(is_str, data)):
return '\n'.join(data)
else:
ra... | ba8e50422a89de14a464d4917138c5faa051124d | 14,035 |
def _set_user_permissions_for_volumes(users, volumes):
"""
Returns the section of the user data script to create a Linux
user group and grant the group permission to access the mounted
volumes on the EC2 instance.
"""
group_name = 'volumes'
user_data_script_section = f"""
groupadd {group_n... | 2d262a52cfa2f3e142da3dd7767dcc6cff14c929 | 14,037 |
def cached_examples():
"""This view should be cached for 60 sec"""
examples = ExampleModel.query()
return render_template('list_examples_cached.html', examples=examples) | f598589967f82daaf3c7e9cb88f7679786e5bf18 | 14,038 |
from typing import Callable
import datasets
def librispeech_adversarial(
split_type: str = "adversarial",
epochs: int = 1,
batch_size: int = 1,
dataset_dir: str = None,
preprocessing_fn: Callable = None,
cache_dataset: bool = True,
framework: str = "numpy",
clean_key: str = "clean",
... | 2ab2da4f56194dada3cd361371ef32b1f2fd6194 | 14,040 |
def search4letters(phrase, letters='aeiou'):
"""
->return a set of the 'letters' found in 'phrase'.
:param phrase: phrase where the search will be made
:param letters:set of letters that will be searched for in the sentence
:return returns a set ()
"""
return set(letters).intersection(set(ph... | e58d0863aa090ac3644cd7bf26e783efe2956d35 | 14,041 |
import gc
def merge_flights(prev_flights_filename, next_flights_filename, ids_df, log):
"""
Gets the next days flights that are the continuation of the previous days
flights and merges them with the previous days flights.
It writes the new next days and previous days flights to files prepended
wi... | 6d0cec2c8cc66d04facdde01e24ce0b3aa57dc55 | 14,043 |
def findClusters( peaks, thresh ):
"""Since the peaks are in sequence, this method follows a very simplistic
approach. For each peak it checks its distance from the previous peak. If
it is less than threshold, it clusters that peak with the previous one.
Note that in each of the clusters, input ord... | f74e504557e7c7e796d29290dccabe043ac70dc0 | 14,044 |
def acq_max_single_seed(ac, gp, y_max, bounds):
"""
A function to find the maximum of the acquisition function using
the 'L-BFGS-B' method.
Input Parameters
----------
ac: The acquisition function object that return its point-wise value.
gp: A gaussian process fitted to the relevant data.
... | 5a705e15e41be8063f476a40b1cfae9385b98af7 | 14,047 |
def futures_pig_rank(symbol: str = "外三元") -> pd.DataFrame:
"""
价格排行榜
https://zhujia.zhuwang.cc/lists.shtml
:param symbol: choice of {"外三元", "内三元", "土杂猪", "玉米", "豆粕"}
:type symbol: str
:return: 价格排行榜
:rtype: pandas.DataFrame
"""
if symbol == "外三元":
temp_df = pd.read_html("http... | 9afc155021afc2b8ffbef4a0e778f1ab6360219f | 14,048 |
import math
def psubl_T(T):
"""
EQ 6 / Sublimation Pressure
"""
T_star = 273.16
p_star = 611.657E-6
a = (-0.212144006E2, 0.273203819E2, -0.610598130E1)
b = ( 0.333333333E-2, 0.120666667E1, 0.170333333E1)
theta = T / T_star
sum = 0
for i in range(0, 3):
sum += a[i] * t... | 0e3f875fc2d249c78a5db6268dcc0df31213a7ff | 14,049 |
def map_key_values(f, dct):
"""
Like map_with_obj but expects a key value pair returned from f and uses it to form a new dict
:param f: Called with a key and value
:param dct:
:return:
"""
return from_pairs(values(map_with_obj(f, dct))) | 0918ff4ff9ab994b10fe2543dce305f99b7278fb | 14,050 |
def plot_ppc(
ax,
length_plotters,
rows,
cols,
figsize,
animated,
obs_plotters,
pp_plotters,
posterior_predictive,
pp_sample_ix,
kind,
alpha,
linewidth,
mean,
xt_labelsize,
ax_labelsize,
jitter,
total_pp_samples,
legend,
markersize,
ani... | 83d01e6b9f9f170b9e8dc2ff3cf95916106196c5 | 14,051 |
import importlib
def load_module(name):
"""Load the named module without registering it in ``sys.modules``.
Parameters
----------
name : string
Module name
Returns
-------
mod : module
Loaded module
"""
spec = importlib.util.find_spec(name)
mod = importlib.util.mod... | 762c99efcc17f9f1d1659cdae52989c9cfa9423a | 14,052 |
def make_no_graph_input_fn(graph_data, args, treatments, outcomes, filter_test=False):
"""
A dataset w/ all the label processing, but no graph structure.
Used at evaluation and prediction time
"""
def input_fn():
vertex_dataset = tf.data.Dataset.from_tensor_slices(
({'vertex_in... | 8526a64b55608f986ef4b000b2cb75a99160e1a0 | 14,053 |
import torch
def compute_gradient_penalty(D, real_samples, fake_samples):
"""Calculates the gradient penalty loss for WGAN GP"""
# Random weight term for interpolation between real and fake samples
alpha = torch.tensor(np.random.random((real_samples.size(0), 1, 1, 1,1)), dtype = real_samples.dtype, device... | 110e4854284be694c0813fd5fc71d2ff51d3b6d8 | 14,054 |
def tab(num):
"""
Get tab indentation.
Parameters
----------
num : int
indentation depth
"""
return num * 4 * " " | 39311a9f28aa70f105271432916745dddeb0b46a | 14,056 |
def merge_sort(lst):
"""Sorts the input list into ascending order."""
if len(lst) < 2:
return lst
half = len(lst) // 2
# This variant of merge sort uses O(N * log N) memory, since list slicing in Python 3 creates a copy.
return merge(merge_sort(lst[:half]), merge_sort(lst[half:])) | e8cada6428fde5aa430497c3c562dc4361c11c1e | 14,057 |
from typing import Optional
def get_top_experts_per_item_dispatcher(gates: Array, name: str,
num_selected_experts: int,
batch_priority: bool,
capacity: Optional[int] = None,
... | 94e090bc3de59fd03903151fa2e34b2daca50198 | 14,058 |
def find_files_list(*args, **kwargs):
""" Returns a list of find_files generator"""
return list(find_files(*args, **kwargs)) | b51595dbc75308c583b75c3151c41ea84aafaeaf | 14,060 |
def bool_from_string(subject, strict=False, default=False):
"""Interpret a subject as a boolean.
A subject can be a boolean, a string or an integer. Boolean type value
will be returned directly, otherwise the subject will be converted to
a string. A case-insensitive match is performed such that strings... | b3f7728eb5fdd4c660144279200daabd25034bf3 | 14,061 |
import logging
def get_msg_timeout(options):
"""Reads the configured sbd message timeout from each device.
Key arguments:
options -- options dictionary
Return Value:
msg_timeout (integer, seconds)
"""
# get the defined msg_timeout
msg_timeout = -1 # default sbd msg timeout
cmd ... | 4b2df955ac796da38b5b9fa176477fec3c0470a2 | 14,063 |
import requests
import logging
def odata_getone(url, headers):
"""
Get a single object from Odata
"""
r = requests.get(url, headers=headers)
if not r.ok:
logging.warning(f"Fetch url {url} hit {r.status_code}")
return None
rjson = r.json()
if 'error' in rjson:
loggin... | 5d6c668845132d821f175a2e8c1a924492a9eb2f | 14,064 |
import json
def _tokenizer_from_json(json_string):
"""Parses a JSON tokenizer configuration file and returns a
tokenizer instance.
# Arguments
json_string: JSON string encoding a tokenizer configuration.
# Returns
A Keras Tokenizer instance
"""
tokenizer_config = json.loads(jso... | 665485d9faad1352927879e81c381dd81b77b5c5 | 14,065 |
from typing import List
from pathlib import Path
def get_all_pip_requirements_files() -> List[Path]:
"""
If the root level hi-ml directory is available (e.g. it has been installed as a submodule or
downloaded directly into a parent repo) then we must add it's pip requirements to any environment
defini... | 7ce5a327af6961ad23555ba5334246b75d8bd782 | 14,066 |
def load_data(dataset_name: str, split: str) -> object:
"""
Load the data from datasets library and convert to dataframe
Parameters
----------
dataset_name : str
name of the dataset to be downloaded.
split : str
type of split (train or test).
Returns
-------
object
... | f6dc374d8c12fa74b9f390a1766af369791bc3b2 | 14,067 |
def horizontal_south_link_neighbor(shape, horizontal_ids, bad_index_value=-1):
"""ID of south horizontal link neighbor.
Parameters
----------
shape : tuple of int
Shape of grid of nodes.
horizontal_ids : array of int
Array of all horizontal link ids *must be of len(horizontal_links)... | 413fdd5a4af8a0e77b0c3ab191bac60f2ba2cc26 | 14,068 |
def _get_output(algorithm, iport=0, iconnection=0, oport=0, active_scalar=None,
active_scalar_field='point'):
"""A helper to get the algorithm's output and copy input's vtki meta info"""
ido = algorithm.GetInputDataObject(iport, iconnection)
data = wrap(algorithm.GetOutputDataObject(oport))
... | dd70cbb1ee6c2d6ed085fc589c24e88fc62a17ab | 14,069 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.