content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import ast
def parse_source_file(filename):
"""Parse source file into AST node
Parameters
----------
filename : str
File path
Returns
-------
node : AST node
content : utf-8 encoded string
"""
# can't use codecs.open(filename, 'r', 'utf-8') here b/c ast doesn't
... | 8064b132c055d0d9c7663333836b006e35f5de82 | 665,445 |
import argparse
def argument_parser():
""" Adds a few command line arguments to improve usability. """
parser = argparse.ArgumentParser(description="Downloads images from 'hot' section of the specified subreddit")
# Valid choices for sort method.
sort_choices = ['hot',
'rising',
... | f2cb55d5c9301b6f1a13f5e8837ea7781135cd2f | 665,446 |
import pickle
import sys
def load_pickle_data(fname):
"""Load pickle data"""
try:
with open(fname, "rb") as pickle_file:
data = pickle.load(pickle_file)
except (FileNotFoundError, IOError) as err:
print("\nError: {}\n".format(err))
sys.exit(1)
return data | 932086c8f1fb96a78f913104e0d0ef4a61e1ffc8 | 665,447 |
def single_spaced(s, convert_tabs_to_spaces=True):
"""Removes redundant whitespace."""
new_s = s.replace('\t', ' ') if convert_tabs_to_spaces else s
new_s = [c for i, c in enumerate(new_s[:-1])
if not c == new_s[i+1] == ' ']
return new_s + new_s[-1] | 02265530ffc61d8cb93a5375597b02fb03fe8097 | 665,448 |
def fibonacci(n):
"""Returns n fibonacci numbers
Args:
n: number of fibonacci numbers to return
Returns:
List that contains n fibonacci numbers
Raises:
ValueError when n is not a positive integer
"""
if n < 1:
raise ValueError("n must be a posit... | ef8e26e63327a3fce20bd36f3d14bc9902cb44b8 | 665,449 |
def to_tuple(d):
"""
Expects dict with single key, returns tuple.
>>> to_tuple({'a': 1})
('a', 1)
"""
return next(iter(d.items())) | a30ee0db94179e125dab96ab8efa38e28456c343 | 665,450 |
def _value_is_array(value):
"""Check if a parameter value is an array.
Parameters
----------
value : str
Parameter value as a string.
Returns
-------
bool
``True`` if the value is an array. Otherwise, ``False``.
"""
return "," in value | 33366d61c3fa6944819b7df37bc7d976b740bf72 | 665,451 |
def slice_list(list_a: list, start: int, end: int):
"""Problem 18: Extract a slice from list.
Parameters
----------
list_a : list
The input list
start : int
The start of the slice
end : int
The end of the slice
Returns
-------
list
A slice of the ini... | 853088bb218666771e6024953e9956524b139443 | 665,452 |
def get_refuse_date(html):
"""
Extract the next refuse collection date from parsed HTML
:param html:
:return:
"""
return html.find("div", {"id": "CTID-19-_-A"}).text | e0d8890906d3edb1c765679f2d6bdc366910ef6d | 665,453 |
def merge(d1, d2):
"""Merges d2 into d1 without overwriting keys."""
left = d1.copy()
right = d2.copy()
for key in right.keys():
if key in left:
left_is_dict = isinstance(left[key], dict)
right_is_dict = isinstance(right[key], dict)
if left_is_dict and right... | 568254522547b47687cdfaab54bfc21e0b535f93 | 665,456 |
def calc_interactions(tissue,mutant_index,n):
"""treats all cells with ancestor 'mutant_index' as cooperators
returns:
n (int): size of clone
I_CC/I_CD (ints): number of cooperator-cooperator/defector interactions in population
W_CC/W_CD (floats): number of cooperator-cooperator/defector... | b6757280c8feeb31b17643a3e02172e054e4bdcf | 665,457 |
def multiply(value, multiplier):
"""
Multiplies two values together.
Usage:
>>> multiply(5, 2)
10
"""
return value * multiplier | bbc055bcc91b3ec82f5e9a7f3e5dcda3d8db0bab | 665,460 |
def get_timestamp(soup):
"""Извлечь дату создания вакансии"""
vac_timestamp = soup.find('p', class_="vacancy-creation-time")
return vac_timestamp.get_text() | 91de4a0916b0ac5d7cfe2efff73f2ef9c75533a6 | 665,461 |
def provider2network(provider):
""" Convert a MADIS network ID to one that I use, here in IEM land"""
if provider in ['KYMN']:
return provider
if provider == 'MesoWest':
return 'VTWAC'
if len(provider) == 5 or provider in ['KYTC-RWIS', 'NEDOR']:
if provider[:2] == 'IA':
... | 71374cda7b66c043d3993f878644602db2e5c5ae | 665,462 |
def __copy_options(user_options, default_options):
"""If user provided option so we use it, if not, default option value should be used"""
for k in default_options.keys():
if k not in user_options.keys():
user_options[k] = default_options[k]
return user_options | 66233ca385baeec7fd032d46f492edd5c6daefea | 665,463 |
def match_code(code:str, raw_line:bytes)->bool:
"""returns True if code is met at the beginning of the line."""
line = raw_line.decode("ascii")
return line.startswith(code + " ") or line.startswith(code + ";") | 88b10075e302d9d9bb1db591fead4f8db2829c40 | 665,464 |
def get_linked_info(issue):
"""
for the given issue, if "[Dd]uplicates: <org>/<repo>#XXX
exists in PR body, returns the parsed org/repo/number
Else return None
"""
body = issue["body"].lower()
if "\nduplicates" in body:
_, url_string = body.split("\nduplicates ")
next_newlin... | b883482b52f226c591c1d623daaa2472f98245c8 | 665,465 |
import functools
def voice_only(fn):
"""A decorator that modifies a cog function command to require a sender to be in a voice channel.
On failure, it'll notify the author with an error message.
Note: discord.py checks would cause it to not show on the help function. So we do this instead.
"""
@fun... | f75cdf2ecc84d45166564945c06d98343b82c25d | 665,466 |
import subprocess
def run(cmd, shell=False):
"""
Wrapper around subprocess to handle exceptions
"""
try:
stdout = subprocess.check_output(
cmd, shell=shell, stderr=subprocess.DEVNULL
).strip()
return stdout
except (subprocess.CalledProcessError, FileNotFoundErro... | 5ef92a2868badc6290ee63079989bba51c641d37 | 665,467 |
def _to_string(val):
"""Convert to text."""
if isinstance(val, bytes):
return val.decode('utf-8')
assert isinstance(val, str)
return val | 16ec1789a0f79f7b6856557caee21b8b61696838 | 665,468 |
def recount_euler(x_points, h, y_0, z_0, func):
"""Euler with recount"""
y_points = [y_0]
z_points = [z_0]
for i in range(len(x_points) - 1):
new_y = y_points[i] + (h/2) * (2 * z_points[i] + h * func(x_points[i], y_points[i], z_points[i]))
new_z = z_points[i] + (h / 2) * (
f... | 1b82b50bc7711977fb57c632aca1999c588245a3 | 665,469 |
def 进制_十到十六(十进制长整数):
"""
十进制到十六进制
"""
return hex(十进制长整数) | 2e0255478ba21eaff5c28831e9edf5574203d131 | 665,471 |
def narrowpeaks_score() -> str:
"""
Return the score column of narrowpeak files
:return:
"""
return 'signalValue' | 8ae382d8871bbe50881e9e3cfe01df0cabdf604e | 665,472 |
def key_all(a):
"""
Return (for each Row) a two column set of Rows that contains each individual
installed addon (the key_addon) as the first column and an array of guids of
all *other* addons that were seen co-installed with the key_addon. Excluding
the key_addon from the second column to avoid inf... | 7aa2628c5c45cf82ddb3988bf3a86c2eecc8f3cd | 665,474 |
def _safe_coord(i, j, img, win_size):
"""Return the coordinates of a window only if
it fits inside the image."""
hwin = (win_size - 1) / 2
m = i - hwin
n = i + hwin + 1
p = j - hwin
q = j + hwin + 1
if (m < 0) or (n >= img.shape[0]) or \
(p < 0) or (q >= img.shape[1]):
ra... | 3338dc350b77bbe4aeb5d4a0d6210580f1b4446e | 665,475 |
def get_model_top_scope_name(model_name, problem_name):
""" Returns the top scope name of all models.
Args:
model_name: The model string.
problem_name: The problem name.
Returns: A str.
"""
if model_name is None:
model_name = "SequenceToSequence"
return problem_name or ... | b9ad22a9090b1588726d57246b3af467c2678647 | 665,477 |
def render_product_dict(the_product):
"""
Return Python dictionary suitable for JSON encoding in requests and
responses to/from cloudfeeds. This dictionary contains a single product
endpoint descriptor.
"""
return {
"title": the_product.title,
"collection": {
"title"... | c54b8ca9b31d433b7ecb5d4adc07818c67b48509 | 665,478 |
def get_wildcard_constraints(image_types):
"""Return a wildcard_constraints dict for snakemake to use, containing
all the wildcards that are in the dynamically grabbed inputs
Parameters
----------
image_types : dict
Returns
-------
Dict containing wildcard constraints for all wildc... | 63f6383f20c3229d34889fc3359ef93112adfadb | 665,479 |
def _get_raw(platform: str, command: str) -> str:
"""Get raw cli output."""
command = str(command.replace(" ", "_"))
with open(
"tests/" + platform + "_" + command + "/" + platform + "_" + command + ".txt",
"r",
) as structured:
raw = structured.read()
return raw | 57eceb39f92daa5cc7e97cd2ec1a67cd7a670cc1 | 665,480 |
import sys
def pypdfBytearray(b):
"""
Abstracts the conversion from a ``bytes`` variable to a ``bytearray`` value
over versions 2.7.x and 3 of Python.
"""
if sys.version_info[0] < 3:
return b
else:
return bytearray(b) | 87cf9fc06288238daa11301f627dcea4cd038b4e | 665,481 |
import torch
def angle_axis_to_quaternion(angle_axis: torch.Tensor) -> torch.Tensor:
"""Convert an angle axis to a quaternion.
Adapted from ceres C++ library: ceres-solver/include/ceres/rotation.h
Args:
angle_axis (torch.Tensor): tensor with angle axis.
Return:
torch.Tensor: tensor ... | e429c2d570e209741e143cb5992bb6a44e8fe80a | 665,482 |
def t_evap(r, phi):
"""Return estimated evaporation time at T=293 K.
- r: radius (m)
- phi: relative humidity
"""
return 3.6e9 * r**2 / (1 - phi) | 11e2ab7186b2402832674c0ba45f87c5b5ed8b07 | 665,483 |
import argparse
def parse_arguments():
"""
Parse the command-line options
:returns: str, str, str -- path to file to backtrack,
output path where to write the files, name of the files
"""
desc = "Adds the connectivity information to a trajectory file that does not have it.\n"... | 2dbeedceb88f8e99c39fdd46945aebf0592d4932 | 665,484 |
def strict_disj(a, b):
"""Strict disjunction
Arguments:
- `a`: a boolean
- `b`: a boolean
"""
return a | b | 89077612cab0e1e9c109caee797cf0dfc8fbb921 | 665,485 |
def expr_to_infix(expr):
"""A string containing a standard infix denotation of the expression
tree EXPR"""
if expr.is_leaf():
return str(expr.label)
else:
return "({} {} {})".format(expr_to_infix(expr[0]),
expr.label,
... | 8e0b9f8314b7a328a60560e669c94a695395db07 | 665,486 |
import struct
import socket
def in_same_network_ipv6(address1, address2, netmask):
"""
Returns True if two IPv6 addresses are in the same network. Faults
if an address is invalid.
"""
address1 = struct.unpack('>2Q', socket.inet_pton(socket.AF_INET6, address1))[0]
address2 = struct.unpack('>2Q'... | 2a93015c11b8f769604074b4e273d11c7e5bd29f | 665,487 |
def is_kanji(character):
""" Return if the character is a kanji character """
return 0x4E00 <= ord(character) <= 0x9FBF or character == '々' | 000a206352c6cf4f6df3d74ac822ec2c851536e3 | 665,488 |
def benchmark_version():
"""
Returns the list of ONNX version to benchmarks.
Following snippet of code shows which version is
current done.
.. runpython::
:showcode:
:warningout: DeprecationWarning
from mlprodict.tools.asv_options_helper import benchmark_version
pri... | 416ed8bad0e33672d733b387654904242d3b8fc5 | 665,489 |
def get_verbose_name(model, field):
"""
Get Django instance's field's verbose_name.
"""
return model._meta.get_field(field).verbose_name.title() | add17b7e4b48235b75b4b70b4ab0e95150f17119 | 665,490 |
def rPeriod_(p_bounds, TeX_on=False):
"""
... return readable style of period from period bounds ...
"""
if p_bounds[0] != p_bounds[-1]:
if TeX_on:
return r'{:d}$-${:d}'.format(p_bounds[0], p_bounds[-1])
else:
return r'{:d}-{:d}'.format(p_bounds[0], p_bounds[-1])
... | c7d2f5c43d0f6bb647fa7f0f44b844a840f60097 | 665,491 |
def _has_method(obj, name):
"""
Check if the object has a method with that name
Args:
obj: the object
name: the name of the method
Returns:
True if the object has a callable method with that name, otherwise False
"""
mth = getattr(obj, name, None)
if mth is None:
... | 2c0a2432e48184cfa7ac0792bee81ba2456cc01c | 665,492 |
def extract_error(b):
"""Extract error from fitargs dictionary."""
return dict((k, v) for k, v in b.items() if k.startswith('error_')) | b884771bb30d11f0f404887006849be8a80042f8 | 665,493 |
import numpy
def compute_pessimistic_predictions(y_signed, predictions, tree_predictions, learning_rate, selected_probability):
"""
Usually, one uses formula in GB:
predictions += learning_rate * tree_predictions,
but in pessimistic probabilistic setting (my term), the formula is
predictions += - ... | d0780e1c17e6284d3f421b95cf09b30a2bbb2662 | 665,494 |
import os
def extract_env_name(file_path):
"""Return environment name for given requirements file path.
>>> extract_env_name("base.in")
'base'
>>> extract_env_name("sub/req.in")
'req'
"""
return os.path.splitext(os.path.basename(file_path))[0] | 525be7bd3e836359a4c2bff10165bb98cdf5d981 | 665,495 |
def replace(template, pattern, subst) :
"""If pattern in the template replaces it with subst.
Returns str object template with replaced patterns.
"""
fields = template.split(pattern, 1)
if len(fields) > 1 :
return '%s%s%s' % (fields[0], subst, fields[1])
else :
return templa... | 46b544ac3edcc3e99b470ba8a780c8cad98b00c9 | 665,498 |
def _edge_mapping(G):
"""Assigns a variable for each edge in G.
(u, v) and (v, u) map to the same variable.
"""
edge_mapping = {edge: idx for idx, edge in enumerate(G.edges)}
edge_mapping.update({(e1, e0): idx for (e0, e1), idx in edge_mapping.items()})
return edge_mapping | 6d3ec0d16f7483671a2a5fba779c015dd0e7edfc | 665,499 |
from typing import List
def findNumberIn2DArray(matrix: List[List[int]], target: int) -> bool:
"""
1.该方法利用题目中所给的矩阵的性质进行求解,因为行和列都是有序排列的,所以,我们可以从第一行的最后一个元素出发,
2.小于就往左走, 大于就往下走
:param matrix:
:param target:
:return:
"""
if len(matrix) != 0 and len(matrix[0]) != 0:
raws = len(matri... | 848c337846ee88cfc3cf423ad002d3f67c15d015 | 665,500 |
import json
def json_format(text: str) -> str:
"""Simple utility to parse json text and format it for printing.
"""
obj = json.loads(text)
return json.dumps(obj, indent=4, sort_keys=True) | bc7e613287d23f1c51ec8c6c825b5422316d71a0 | 665,501 |
def get_all_followings(igapi, target_userid):
"""
Returns a list of {"username": "", "userid": 0, "is_private": false, "full_name": ""}
"""
following_list = []
current_followings_list = igapi.getTotalFollowings(target_userid)
for following in current_followings_list:
user = {
... | c428d2044071a2430b05e793d5ecbf5326479767 | 665,502 |
from typing import Any
def flag(argument: Any) -> bool:
"""
Check for a valid flag option (no argument) and return :py:obj:`True`.
Used in the ``option_spec`` of directives.
.. seealso::
:class:`docutils.parsers.rst.directives.flag`, which returns :py:obj:`None` instead of :py:obj:`True`.
:raises: :exc:`Va... | 7aeb0b0ddf5b98cafebf868adbc95204518513db | 665,503 |
def AdjustBreaks(signal, #const double * signal,
peakLoc, #const int * peakLoc,
):
"""Improve localization of breaks. Suboptimal, but linear-complexity.
We try to move each break 1 sample left/right, choosing the offset which
leads to minimum data error.
Parameters
... | 2ae4cb5ca7daf9148540cb7f93234abc545914a7 | 665,504 |
import math
def _calculate_label_rotation(startx, starty, endx, endy):
"""
Calculates the appropriate rotation angle for a label on an arrow (matches line, is between -90 and 90 degrees)
:param startx: start of arrow (x)
:param starty: start of arrow (y)
:param endx: end of arrow (x)
:param e... | 45a4928102f040847e99c6983ccbff59aa2c841f | 665,505 |
def object_info_as_dict(object_info):
"""Convert a KBase object_info list into a dictionary."""
[
_id,
_name,
_type,
_save,
_version,
_owner,
_ws,
_ws_name,
_md5,
_size,
_meta,
] = object_info
return dict(
ob... | 1d2976b4026efdfa8988ca19695f8815075644eb | 665,506 |
import random
def random_promotion(data_objects, distance_function):
"""
Randomly chooses two objects to be promoted.
"""
data_objects = list(data_objects)
return random.sample(data_objects, 2) | 8a3e78b690e4db44d09adb07bf1c1e0aae7aa06e | 665,507 |
import os
def get_test_root() -> str:
"""Returns the root of the testing directory."""
cwd: str = os.getcwd()
return f"{cwd}/data-manager/jote" | 2d593754bf4fdcad1fdd279d2aee4ebdff63dcd2 | 665,508 |
def css_rgb(color, a=False):
"""Get a CSS `rgb` or `rgba` string from a `QtGui.QColor`."""
return ("rgba({}, {}, {}, {})" if a else "rgb({}, {}, {})").format(*color.getRgb()) | f3f15c2c5fdb7317f679cc080b4f0c6fb343f45a | 665,509 |
def _calc_basic_subreddit_stats(sr_about):
"""
:param dict sr_about: An unmarshalled sub-Reddit about.json 'data' dict.
:rtype: tuple
:returns: Tuple in the form of: sub_count, accounts_active
"""
sub_count = int(sr_about['subscribers'])
accounts_active = int(sr_about['accounts_active'])
... | 02a2e43fd0e8d80ee723a36044257793a0e64c10 | 665,510 |
import numpy as np
def return_float(input_number):
"""
Return input as a float if it's a number (or string of a number).
Parameters
----------
input_number : string or number
Returns
-------
output_number : float
raise exception if not a number or string of a number
"""
... | 1037ede3b6a6569825f7d7d48bc3b08b8cf6391e | 665,511 |
def _code_to_symbol(code, index=False):
"""
生成symbol代码标志
@author: Jimmy Liu
@group : waditu
@contact: jimmysoa@sina.cn
@modified: Wen Gu
"""
# 股票指数与代码的转换表(无需修改)
INDEX_LABELS = ['sh', 'sz', 'hs300', 'sz50', 'cyb', 'zxb', 'zx300', 'zh500']
IN... | 46229c699f16eb9227f4d62e9ad67df0856ee2f1 | 665,512 |
def crop_img(img, msk, crop_dim, n_channels, n_out_channels):
"""
Crop the image and mask
"""
number_of_dimensions = len(crop_dim)
slices = []
for idx in range(number_of_dimensions): # Go through each dimension
cropLen = crop_dim[idx]
imgLen = img.shape[idx]
start =... | 3352afc5f692361b2c3f5f34f069d7d49a07d8bc | 665,513 |
def read_database(db, query, params):
"""
Execute query with params against the database.
:param db: database connection
:param query: str: query to execute
:param params: [object]: list of parameters to use with query
:return [object] rows returned from query
"""
rows = []
cur = db.... | 46fa9032f3762872f1d524d1c5c5e1dad07d7b0f | 665,514 |
def match_shared(self, shared_length: int, shared_features: int) -> int: # pylint: disable=unused-argument
"""Calculate the size of the task variable to match the shared variable."""
return shared_length * shared_features | bac550d8920c5f170176610764837685819061be | 665,515 |
def length(value):
"""
Find the length of a value
:type value: variable
:param value: The value to find the length of
"""
# Try to return the length
return len(value) | a7d842f432743eb8cbab137d19fb4a9937af7021 | 665,516 |
import re
def is_local_variable(variable_name):
"""
@ variable_name: should be single world and remove all '(', ')', '*', '&'
@ return value: -1 if this is not a local variable
variable_num if this is a local variable
"""
pattern = r'_\d+'
m = re.search(pattern, variable_na... | 01b75819600e0eb5d6ebe4e85bfeb6abe87d665c | 665,517 |
def read_template(template_path):
"""Read template file.
Args:
template_path: template file path
Returns:
template file data
"""
with open(template_path, "r") as f:
template_data = f.read()
return template_data | 85e2ae06fbf052fac9f03ca516d5fc5ee28d8319 | 665,518 |
import sys
def equal_float_old(a, b, epsilon=None):
"""Returns True if a and b are equal to the limits of the machine's
accuracy or to the limit of epsilon if given
>>> equal_float_old(.1, .1), equal_float_old(.000000000001, .000000000001)
(True, True)
>>> equal_float_old(.00000000000101, .000000... | 938dacda7ad1cd05c364e4be23557d453e4d93d3 | 665,519 |
import math
def binomial(n, k):
"""Computes the binomial coefficient "n over k".
"""
if k == n:
return 1
if k == 1:
return n
if k > n:
return 0
return math.factorial(n) // (
math.factorial(k) * math.factorial(n - k)
) | 1f7a6e7709cb6adaf178a49fced2f1961f70ef87 | 665,520 |
def _num_32_bit_words_for_bit_fields(bit_fields):
"""
Gets the number of 32 bit unsigned ints needed store a list of bit fields.
"""
num_buckets, cur_bucket = 0, 0
for field in bit_fields:
if field.size + cur_bucket > 32:
num_buckets += 1
cur_bucket = 0
cur_bu... | bb86daa1455a7e1b73b48bfd6f8ff65515e2f3ac | 665,521 |
def export_to_pascal(ibs, *args, **kwargs):
"""Alias for export_to_xml"""
return ibs.export_to_xml(*args, **kwargs) | b7fd4d3c68e09f5665dd658c42fc297341fb0b1e | 665,522 |
def gps_get_point():
""" Get a gps data point """
commands = ['AT+CGNSINF']
return commands | 964ac4367da1720c6a82ac205dc1ee286377b394 | 665,523 |
def daily_visit_count(user, count):
"""Returns True if the number of the user daily visit equals to count."""
return user.get_profile().daily_visit_count >= count | 07fd9bbee88c0645929c22029bb4563e4238710e | 665,524 |
def _remove_whitespaces_beginning_end_text(text: str) -> str:
"""
Removes whitespace from the beginning and end of the given text.
"""
return text.strip() | c8859388e4c60a7413363e1967f876c2714762ea | 665,525 |
def complete_one_tree(span_idxes, doc, range_idxes=None, full_tree=True):
"""Compute the complete subtree for a given span
Args:
span_idxes ([int, int]): the indexes of the given span to be extended
doc (Doc): The spacy doc
range_idxes ([int, int]], optional): the maixmum indexs. Defaul... | da06f10913b7fa00ae460e1f23d00b417b553bc3 | 665,526 |
def nodesOnLine(*args):
"""
Retorna índice dos nós existente em um elemento de linha.
>>> boundary = nodesOnLine(elements, 0, 1, 2, 3)
"""
elements = args[0]
lines = args[1:]
indexes = [ns for line in lines for es in elements
if (es.dim is 1 and line in es.tags)
... | 9b7eae72156452a0b7267da133e8f97fa06f3fa5 | 665,527 |
import re
def _parse_args(args, required_args):
""" Parse args according to required args """
module_args = {}
split_args = []
for index, token in enumerate([x for x in re.split("=|--", args.strip()) if x.strip()]):
if token:
if index % 2 == 0:
split_args.append("--... | 406aae8902520b993fa0028618a53392a9a563af | 665,528 |
import math
def is_relative_prime(num, larger_num):
"""Determine if num is a relative prime to larger_num."""
return math.gcd(num, larger_num) == 1 | a71c00fc66b888723f8a681beda618c5fa899ee3 | 665,529 |
def _user_profile(user_profile):
"""
Returns the user profile object. For now, this just comprises the
profile_image details.
"""
return {
'profile': {
'image': user_profile['profile_image']
}
} | 8952e86db5dfdf84442ff52f89b038a1b45e2351 | 665,530 |
import torch
def map_imgs_to_embs(model, images, device):
"""
With the deep network, project images / batch of images to embedding space
"""
assert len(images.shape) == 4
# turn the model to evaluation mode
model.eval()
images = images.to(device)
with torch.no_grad():
ret = mo... | 70aed02f98d06b140b61ac916d09d5a7d888df71 | 665,531 |
from datetime import datetime
def FindLatestTime(time_list):
"""Find latest time from |time_list|.
The current status is compared to the status of the latest file in
|RESULT_DIR|.
Args:
time_list: a list of time string in the form of 'Year-Month-Day-Hour'
(e.g., 2011-10-23-23). Strings not in th... | 9af56f4d0a3e2c51e0e038b47b450b106852cfe8 | 665,532 |
def prompt_year():
""" get the user's input as to a specific year to analyze """
return int(input('Enter the year of interest: ')) | e2a4f7502803da6f413e08d793e7659fb07b4aec | 665,533 |
def is_proper_component_name(component):
"""Check if the component name is properly formatted."""
return "@" not in component and "/" not in component | 51e26fa4074508b1f60988428806e1990c3d1f2b | 665,534 |
def generate_workflow_metadata( relative_path, exported_workflow_dict, metadata_dict ):
"""Update the received metadata_dict with changes that have been applied to the received exported_workflow_dict."""
if 'workflows' in metadata_dict:
metadata_dict[ 'workflows' ].append( ( relative_path, exported_work... | 02f57b187cc41d1c98f1d2bc69998f807330baaa | 665,535 |
def is_ssh_for_nimbus(env_config):
"""Check if we need to use SSH access to Nimbus or not."""
return env_config.get("use_ssh_for_nimbus", True) | 8c6d31e131f04deeaf09d97c3dd046515795c9eb | 665,536 |
def create_feature_names(prefix, n_features):
"""Generate numbered feature names
Example
-------
from seasalt import create_feature_names
from verto.dim1 import trans, meta
from datasets.demo1 import X_train
trans.set_params(**{'pca__n_components': 3})
X_new = trans... | c82e95232d7d25efb1dee7695634bd8fd4185c07 | 665,537 |
import string
def has_string_formatters(s):
"""
Determine if a string has ``{}`` operators.
Parameters
----------
s : str
The string to analyze.
Returns
-------
bool
``True`` if yes, ``False`` if no.
"""
assert isinstance(s, str), f'`s` of wrong type: {type(s)... | 430d6f627690029e32eac3862c16bfee58b8aec6 | 665,538 |
from functools import reduce
def getTotalCombinationNumFrp(n):
"""
Same result as above but using a FRP style
Although we get the same result but this one it's harder to know the math
"""
return reduce(lambda x, y: x * y, range(1, n + 1), 1) | 49f0a57a3fd0761bc64e3db36894cd35eb14eba8 | 665,539 |
def hexweek_to_weekday_list(hexweek):
"""
Helper to convert speaker's hex representation of weekdays into list of integers represending weekdays.
:param hexweek: Hex string .e.g. 0x3E
:returns: List of weekday integers e.g. [0, 1, 2, 3, 4] for hexweek 0x3E
"""
intweek = int(hexweek, 16)
# ... | b5afead7260fd1ce9b4ec439c1c5f53f9f882b2a | 665,540 |
import math
def aire_triangle(a : float, b : float, c : float) -> float:
"""
PrEcOnDiTiOn : (a>0) and (b>0) and (c>0)
"""
p : float
p = (a + b + c) / 2
return math.sqrt(p * (p - a) * (p - b) * (p - c)) | cd17f7ff54b09c78e2eedd8a76b785cc084d5947 | 665,541 |
def compute_next_hidden_states(srnn, x, h0, weights=None, distilled_params=None,
condition=None):
"""Compute the internal recurrent states subsequent to the current timestep.
This function receives as input an initial hidden state :math:`h_t` and a
set of external inputs :mat... | b59f05fc936d14d4d381c8446270937d56df0be7 | 665,543 |
def run_model(*params, return_preds=False, integrate=False):
"""
Given a model, loss function and daily death data, along with the parameters, run the model on these parameters.
Arguments
--------------
params : A list of parameters. The last three must be the model function, loss function a... | 531854ca22ebb489da34980ba6143ce01751cf6a | 665,544 |
import re
def extract_flavors(html):
"""Takes HTML and returns dictionary flavor info"""
html = html.split('\n')
flavor_info = {}
span_pattern = r'<span class="%s\w*">([^>]+)</span>'
for line in html:
flavor_name_search = re.search(span_pattern % 'flavorhead', line)
... | bfd4babc9c968dbb804c732e41e9338deb6990bf | 665,546 |
import re
def replace_spaces(some_string):
""" Substitute spaces with underscores"""
return re.sub(" ", "_", some_string) | 23f6bb9079ec92afc97f1da1aa0c0eec8af512c8 | 665,548 |
def get_all_constraints(max_domain_val):
"""
Purpose: get all binary constraints of the form xi,xj and put them in
a list. To save space, we just put the row and column indices in the
list.
@param max_domain_val int, The dimensions of each side of the square board
@return constraints list of t... | bfe57d948aca3dbcdc61b8736e1aac9918346502 | 665,549 |
from typing import List
def get_catalog_levels(item: str) -> List[str]:
"""
Return the levels to be updated given a STAC item key
"""
levels = list()
levels.append("/".join(item.split("/")[:-1]))
levels.append("/".join(item.split("/")[:-2]))
levels.append("/".join(item.split("/")[:-3]))
... | 25dbebc62f9b87f46cbc9cadc0085be4444f39e0 | 665,550 |
def cfind(haystack, needle, offset):
"""Return character index of needle found in haystack at offset"""
start = haystack.find(needle)
while start >= 0 and offset > 1:
start = haystack.find(needle, start+len(needle))
offset -= 1
return start | 0655f7e2e2078d4ce16e3506c835fe65662acd2a | 665,551 |
def tier_count(count):
"""
If a tier quota is 9999, treat it as unlimited.
"""
if count == 9999:
return "Unlimited"
else:
return count | dc702e930377d1533fbacf434a2acd0ddfefc457 | 665,552 |
def get_card_split(df, cols, n=11):
"""
Splits categorical columns into 2 lists based on cardinality (i.e # of unique values)
Parameters
----------
df : Pandas DataFrame
DataFrame from which the cardinality of the columns is calculated.
cols : list-like
Categorical columns to lis... | 91cfd36af62cb7b88be44fe9cd3ea292e61c141e | 665,553 |
def degrees_to_cardinal(degrees):
"""Convert degrees >= 0 to one of 16 cardinal directions."""
CARDINALS = ["N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"]
if degrees < 0: return None
i = (degrees + 11.25)/22.5
return CARDINALS[int(i % 16)] | 2c0032be80da7cbf9b7c5ca2236d393cc519a4f5 | 665,554 |
def get_401_error_hint(ctx, opts, exc):
"""Get the hint for a 401/Unauthorised error."""
# pylint: disable=unused-argument
if opts.api_key:
return (
'Since you have an API key set, this probably means '
'you don\'t have the permision to perform this action.')
if ctx.info... | e115e102570447fd685f4e62a0b0551077a5982f | 665,555 |
def model_summary(model):
"""Return a summary of Keras model intance.
Args:
model (Keras model instance): A Keras model instance.
Returns:
str: A summary for the model.
"""
summary = model.summary()
return summary | c01a142d8387cae0fd7e864c194109f1b770cc7d | 665,556 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.