content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import json
from datetime import datetime
def get_github_info(packages=packages):
"""
Get information about subpackage releases that have been tagged on github
"""
no_release = []
release = {}
for package in packages:
url = f"https://api.github.com/repos/pysal/{package}/releases/lates... | 1c13522ad816f4f4898a193bd5b7bb04febbf67a | 29,300 |
from typing import Dict
def matrix_str_to_dict(matrix_str: str) -> Dict[str, Dict[str, int]]:
"""Transform dictionary string to 2-d array of ints."""
scoring_matrix = {}
table = [line.split() for line in matrix_str.split("\n") if line[0] != "#"]
aa_tos = table[0]
for row in table[1:]:
aa_f... | de1d4fd581a40cb6e61bd2b13c3a89718a67736f | 29,301 |
def restriction(model, sfield, residual, sc_dir):
"""Downsampling of grid, model, and fields to a coarser grid.
The restriction of the residual is used as source term for the coarse grid.
Corresponds to Equations 8 and 9 and surrounding text in [Muld06]_. In the
case of the restriction of the residual... | b3f97cef119ae219f5bca2d56d1c6ec55bb3d5db | 29,302 |
def check_good_not_bad(decider, good, bad):
"""Check if bad prof becomes GOOD by adding funcs it lacks from good prof"""
bad_copy = bad.copy()
for func in good:
if func not in bad:
bad_copy[func] = good[func]
return decider.run(bad_copy) == StatusEnum.GOOD_STATUS | 0464721aae2c20310eefb3e78f1b3e4c36a558ed | 29,303 |
from typing import List
def filter_by_length(data: List[list], lower_bound: int, upper_bound: int) -> List[list]:
"""
:param data: [[word1, word2, word3], ..., [word1, word2]]
:param lower_bound: 3
:param upper_bound: 5
:return: [[word1, word2, word3, ... ], ..., None]
"""
for index in ra... | 4b7d83a82c29622d4d26fc718b6bb5fbe959c8dd | 29,304 |
def run_games_and_record_payoffs(game_queries, evaluate_game, ckpt_to_policy):
"""Simulate games according to game queries and return results.
Args:
game_queries: set of tuples containing indices specifying each players strat
evaluate_game: callable function that takes a list of policies as argument
ck... | 7d03b48e076efab99353b582baf04b96503695c5 | 29,305 |
def gnocchiclient(request):
""" Initialization of Gnocchi client.
"""
auth_endpoint = getattr(settings, 'OPENSTACK_KEYSTONE_URL', None)
loader = loading.get_plugin_loader('token')
auth = loader.load_from_options(auth_url=auth_endpoint,
token=request.user.token.id... | cd933c348d0a10333473bb6b7bcfbac007a6b3d5 | 29,306 |
from typing import Type
from typing import Tuple
from typing import Any
def create_namespace_handler(
file_type: Type[NamespaceFile],
namespace_scope: Tuple[str, ...],
namespace_extension: str,
) -> Type[NamespaceFile]:
"""Create handler that turns yaml namespace files into json."""
class AutoYam... | a9013dfbbe48a4b6cc5b48ca3e5cb07c833e870c | 29,307 |
from typing import Union
import os
def trsh_job_on_server(server: str,
job_name: str,
job_id: Union[int, str],
job_server_status: str,
remote_path: str,
server_nodes: list = None):
"""
Troublesho... | 837c399553c3d58a91444cda9973f92fb317751f | 29,308 |
def get_native_backend_config_dict():
""" Get backend_config_dict for PyTorch Native backend (fbgemm/qnnpack). """
binary_op_dtype_configs = [
weighted_op_int8_dtype_config,
default_op_fp16_dtype_config,
]
share_qparams_op_dtype_configs = [
default_op_quint8_dtype_config,
... | 3b0332feb223b9e08724f45d6397b418a5690e0e | 29,309 |
def dummy_content_widget(title='Dummy Content Widget', content="Dummy Content",
slug="dummy_content_widget", is_published=True):
"""Will directly write to the database a dummy content widget for our
tests.
Parameters
----------
title : str
Widget title.
content... | e0164f5512c02abc79ddd6149c1c855fbf6b4241 | 29,310 |
import os
def get_ckpt_epoch(ckpt_dir):
"""Get checkpoint epoch"""
ckpt_epoch = {}
files = os.listdir(ckpt_dir)
if not files:
print("No ckpt files")
return None, None
for file_name in files:
file_path = os.path.join(ckpt_dir, file_name)
if os.path.splitext(file_pa... | fe972b5fc9c7701ebb90323a17d47d6f2842c498 | 29,311 |
def ask_note():
"""Function to ask user for task notes"""
task_note = input("Enter any additional task notes here >")
return task_note | 952010409c0430b697b899edf7c29b5fa2f9bedb | 29,312 |
import os
def mkdir_for_girl(f_path):
"""
创建以标题命令的目录
:param f_path: 文件根路径
:return: 返回创建的目录路径
"""
if not os.path.exists(f_path):
os.mkdir(f_path)
return f_path | d37e4d4d34fce29fcb5e7928dfbc02b8153d654b | 29,313 |
def main(prmtop_file, mdcrd_traj_file, inpcrd_file, get_B = False, target_length=15, cluster_size = 10, simplify_only = False, rod=None, radius = 5e-9, rod_out=None, unroll_rod=True, get_inhomogenous_beta=False, get_inhomogenous_kappa=False):
"""
For an atomistic trajectory, this will create an equivalent rod t... | b6f243f7e5c2a9f30f3af928b452c3ec00e912aa | 29,314 |
def Yt_1d_full():
"""
1d Yt fully observed
"""
y = np.array([[[2]], [[1.3]], [[2.5]], [[3.1]]])
return y | e44e98ab25336e16802c670361ad18359fab0957 | 29,315 |
def threshold_isodata(image, nbins=256, shift=None, max_limit=None, min_limit=None):
"""Return threshold value based on ISODATA method.
Histogram-based threshold, known as Ridler-Calvard method or intermeans.
Parameters
----------
image : array
Input image.
nbins : int, optional
... | 7c660baac593cbd965f1b6a48a0dfc861c69b878 | 29,316 |
def populate_task_view(request):
"""
populate project_task view
"""
project_id = request.GET.get('project_id')
project_name = request.GET.get('project_name')
template = loader.get_template('project_management/add_project_tasks.html')
project = Project.objects.get(id=int(project_id))
sta... | 33f7ab5b60ef4cbc8fd0e39bf74f5a851f13659a | 29,317 |
def cleanup_queryset(queryset):
"""
Remove multiple joins on the same table, if any
WARNING: can alter the origin queryset order
"""
return queryset.model.objects.filter(pk__in=[instance.pk for instance in queryset.all()]) | ecdab862fd67359fab1a5706092fe0d023d31321 | 29,318 |
def svn_diff_output_fns_invoke_output_conflict(*args):
"""
svn_diff_output_fns_invoke_output_conflict(svn_diff_output_fns_t _obj, void output_baton, apr_off_t original_start,
apr_off_t original_length,
apr_off_t modified_start, apr_off_t modified_length,
apr_off_t latest_start, apr_off_... | a434298342e50c2803c3ccaf69fecbe0de36b816 | 29,319 |
def capacity_factors():
"""
This function generates a hard-coded dictionary
containing the capacity factors for different fuels
and movers. The values are defaulted to 1.0 if no
capacity factor information can be found. The
numbers are specific to the 2018 year and may lead
to innacurate res... | b75e4a86224af565ffab919e63a1a352696e73bc | 29,320 |
def _is_greater(list1: list, list2: list):
"""
return True if `list1[i] > list2[i]` for each `i`
"""
return all([list1[i] > list2[i] for i in range(len(list1))]) | 925fb214f741d6503b41b49d57a268506f05a048 | 29,321 |
def isenabled(handle):
"""Return True if the window is enabled"""
return bool(win32functions.IsWindowEnabled(handle)) | edb99831f561fd84ab0bb17bf568e200699a7aa1 | 29,322 |
def monte_carlo(d):
"""
Calculate Monte Carlo value for π.
Arguments:
d: list of unsigned byte values.
Returns:
Approximation of π as Decimal
"""
MONTEN = 6
incirc = Decimal((256.0 ** (MONTEN // 2) - 1) ** 2)
d = (Decimal(j) for j in d[: len(d) // MONTEN * MONTEN])
... | fe6fdc07c18ae35abcc3ab428f13188a0ff306c2 | 29,323 |
def verifyIfRepo(dirName):
"""
"""
dbPath = getDbPath(dirName)
print dbPath
try:
if verifyShelveVersionCompatibility(dbPath):
return True
else:
return False
except:
return False | ecedb0569a0a1d41ad23dcef1f9155145756cb8c | 29,324 |
def machine_setter(_latfile=None, _machine=None, _handle_name=None):
""" set flame machine, prefer *_latfile*
:return: FLAME machine object
"""
if _latfile is not None:
try:
with open(_latfile, 'rb') as f:
m = Machine(f)
except:
if _machine is Non... | 8fa5802d7307269d57667c84e3d832b1985dba8f | 29,325 |
def vgg_preprocess_images(image_tensor):
"""
:param image_tensor: float 32 array of Batch x Height x Width x Channel immages (range 0 - 1)
:return: pre-processed images (ready to input to VGG)
"""
vgg_mean = tf.convert_to_tensor(np.array([103.939, 116.779, 123.68], dtype=np.float32))
red, green,... | 8354e3023af981b4d7f9d2c98f60a7e05943e218 | 29,326 |
def computeIntCorrections(npix,factor):
"""Compute `newnpix` and `newfactor` such that `npix_new` is the
nearest odd-valued integer to ``npix*factor``.
Parameters
----------
npix : int
Odd-valued integer.
factor : float
Multiplicative factor.
Returns
-------
newn... | 9b662acecd54795c50eb8ca5e4ac7af45a006c5c | 29,327 |
def LU_factor(A,LOUD=True):
"""Factor in place A in L*U=A. The lower triangular parts of A
are the L matrix. The L has implied ones on the diagonal.
Args:
A: N by N array
Returns:
a vector holding the order of the rows, relative to the original order
Side Effects:
A is fact... | aa74e20888892ba5edafd9deaf10976633319544 | 29,328 |
def get_zvals_from_grid(line,xyzgrid):
""" Input: line (LineString or ARRAY with first two columns the xy coords)
get z values at every point in line from xyzgrid
xyzgrid: DataFrame with x,y,z columns or 3 column ARRAY
returns: array of z values for each point on line """
#create dataframe if np.arra... | 5eee6c46559bcf30e9d3dca30bb18ca7e3b30489 | 29,329 |
def HBIh(time, gsd = None, gh = None):
"""
paras
gsd: optional
Conductance of slow depolarizing
gh : optional
Return
Var_t : action potential
"""
def HyB(Var,t,tempF):
[rrho,pphi] = tempF
[v,ar,asd,ca,ah]=Var
ad = 1/(... | 2abbf9611097e65b6a6e03e0dfdfbecd61a5bb35 | 29,330 |
import requests
import json
def discovery(uri="", data_format="json"):
"""
Method description:
Deletes/Unregisters an application entity(AE) from the OneM2M framework/tree
under the specified CSE
Parameters:
uri_cse : [str] URI of parent CSE
ae_name : [str] name of the AE
fmt_ex : [st... | 5b09ce0f7ce533c02386cba9f4cf2ffebc85edcf | 29,331 |
async def test_map_two_iterables_expected_result(
arange: ty.Type[ty.AsyncIterator[int]], stop: int
):
"""Look for expected results which should returned by
:class:`none.collection.a.map` with two iterables given.
"""
async def _add(a: int, b: int) -> int:
return a + b
async for i, x ... | 10749b3315e911e4f5c07d1adeef43e258e18092 | 29,332 |
def dijkstra_search(problem):
"""
Best first search that uses g(n) to evaluate cost
:param problem:
:return: final node
"""
return best_first_graph_search(problem, lambda n: n.path_cost) | e3c9dbdea4f4fc8ce99dcf4be41d4d42cfac1555 | 29,333 |
def _get_pair_nodes(root_node):
"""
Internal method to get "pair" nodes under root_node
"""
method_elem = root_node
in_configs_elem_list = method_elem.getElementsByTagName("inConfigs")
in_configs_elem = in_configs_elem_list[0]
pair_elems_list = in_configs_elem.getElementsByTagName("pair")
... | c2b74f7a507394d2117cd6292116e62d34f3e556 | 29,334 |
import sys
def get_string(message="Enter your response", title="Title",
default_response=""):
"""Simple text input box. Used to query the user and get a string back.
:param message: Message displayed to the user, inviting a response
:param title: Window title
:param default_r... | ce8f3fbd566531f1cf7da56ece7502050268ca2d | 29,335 |
def has_ao_2e_int_eri_lr(trexio_file) -> bool:
"""Check that ao_2e_int_eri_lr variable exists in the TREXIO file.
Parameter is a ~TREXIO File~ object that has been created by a call to ~open~ function.
Returns:
True if the variable exists, False otherwise
Raises:
- Exception from tr... | 3f903aa4e03ed78313b59ff0b03ddcc65c6de0ca | 29,336 |
def corelucy(image, h):
"""
Make core for the LR estimation. Calculates f to produce the next
iteration array that maximizes the likelihood that the entire suite
satisfies the Poisson statistics.
This is a simplified version of MATLAB corelucy function without
damping, weights and externally def... | b376be72f3572ac06f0a401f5d768abf76d3ba00 | 29,337 |
def convert_to_bipartite(S):
"""
convert a standard stoichiometric matrix (in a Pandas DataFrame)
to a bipartite graph with an edge between every reactant and all its
reactions
"""
# convert the stoichiometric matrix to a sparse representation
S_sparse = pd.melt(S.reset_index(),
... | cd931f92b4ef32624202ab1145236d54801ab048 | 29,338 |
def proj_l1_neg_tan_cone(u, v):
"""
Project u onto the negative tangent cone of l1 ball with diameter ||v||_1
at v. It's actually the tangent cone of l1 ball with bound ||v||_1 at -v.
@param u: the vector to calculate projection from.
@param v: the vector at whom the tangent cone forms.
... | a5a1dbf74ba3f58dc31bda50ffbc9483ab258301 | 29,339 |
def generate(prompt: str, context: str) -> str:
"""Generates a response for the given prompt and context.
:param prompt: The prompt to generate a response for.
:type prompt: str
:param context: The context to generate a response for.
:type context: str
:return: The generated response.
:rtyp... | e752c3fa10d1de40d944bfa41b88f34c2d3e4894 | 29,340 |
def fista(input_size, eval_fun, regulariser,
regulariser_function=None, thresholding_function=None, initial_x=0,
L0=1., eta=2., update_L=True,
verbose=1, verbose_output=0):
"""
FISTA (Fast Iterative Shrinkage Thresholding Algorithm) is an algorithm to solve the convex minimization ... | 17710174114e6b8772d3e53e49a379bc476f3c81 | 29,341 |
def __ldns_pkt_set_question(*args):
"""LDNS buffer."""
return _ldns.__ldns_pkt_set_question(*args) | 2dfb8d0bea1aee4348d5ddc5850e36963c0f092e | 29,342 |
import random
def get_nick(infraction_id: int, member_id: int) -> str:
"""Randomly select a nickname from the Superstarify nickname list."""
rng = random.Random(str(infraction_id) + str(member_id))
return rng.choice(STAR_NAMES) | 120ba3abcf5f68bff46672b18cbce3e18c5088d0 | 29,343 |
def find_best_path(starting):
"""Find the best moves using A*"""
@dataclass(order=True)
class PrioritizedState:
"""Dataclass to insert the RoomStates into the priority queue"""
cost: int
config: RoomState=field(compare=False)
open_set = PriorityQueue()
open_set.put(Priorit... | 2328af1e8fbf01808c321e18b27e7c6e0e9b8f9c | 29,344 |
def Shard(ilist, shard_index, num_shards):
"""Shard a given list and return the group at index |shard_index|.
Args:
ilist: input list
shard_index: 0-based sharding index
num_shards: shard count
"""
chunk_size = len(ilist) / num_shards
chunk_start = shard_index * chunk_size
if shard_index == num... | 7f79ade521c1264d0ddc8c5a228679d7053d9651 | 29,345 |
from typing import Any
from typing import Tuple
def get_oof_pred(
model: Any,
X_train: pd.DataFrame,
y_train: pd.Series,
X_test: pd.DataFrame,
n_fold: int,
) -> Tuple[np.ndarray, np.ndarray]:
"""
Get Out of Fold prediction for both training and testing dataset
Args:
model (Any)... | 19871121a674ad6730db17d97930c7bd6c09f7e2 | 29,346 |
async def get_aes_key(password: str, settings: EncryptionSettings) -> bytes:
"""Returns the 32 byte system encryption key."""
assert isinstance(password, str)
assert isinstance(settings, EncryptionSettings)
return await decrypt_chunk(get_decryption_key(password, settings), settings.encrypted_key) | 8f5c67d1d64c25d02c33363c572fc04c6e364e55 | 29,347 |
def nextpow2(value):
"""
Extracted from
caiman.source_extraction.cnmf.deconvolution import axcov
Find exponent such that 2^exponent is >= abs(value).
Parameters:
----------
value : int
Returns:
-------
exponent : int
"""
exponent = 0
avalue = np.abs(value)
while a... | 4e485d9ebb8e2103dff45d777783f1f2bcdc5509 | 29,348 |
def workshopinquiry_accept_event(request, inquiry_id):
"""Accept workshop inquiry by creating a new event."""
wr = get_object_or_404(WorkshopInquiryRequest, state='p', pk=inquiry_id)
if request.method == 'POST':
form = EventCreateForm(request.POST)
if form.is_valid():
event = f... | fde98bd8924ac1bc4f5c39365c90c1e53bbc7546 | 29,349 |
def load_level_data():
"""Read the `level.dat` file and return the `Data` compound."""
try:
level_data = nbt.load(LEVEL_DATA_PATH, gzipped=True).root['Data']
except FileNotFoundError:
display_error(f'Couldn\'t find any "{LEVEL_DATA_PATH}" file. Are you '
'sure that the ... | 82039e0ba2156e0231d1403081e9cb83a140e5ce | 29,350 |
def separation_scorer(catalogue,name_TGSS,name_NVSS):
"""given two names, gives separation
by set-up, only gives non-zero for those in catalogue"""
if (name_TGSS,name_NVSS) in catalogue.index:
sep = catalogue.loc[name_TGSS,name_NVSS].separation
sep *= 3600
return max(0,(40-sep)/40)
... | f70a6cf58ec12caba784ff7f51cbdbbf74f536b6 | 29,351 |
def mms_hpca_calc_anodes(fov=[0, 360], probe='1', suffix=''):
"""
This function will sum (or average, for flux) the HPCA data over the requested field-of-view (fov)
Parameters
----------
fov : list of int
field of view, in angles, from 0-360
probe : str
prob... | 3c6ca26f06eb65c4e2c5e3f71724d890aba5a6a9 | 29,352 |
def get_host_call_fn(model_dir):
"""`host_call` function for creating training summaries when using TPU."""
def host_call_fn(**kwargs):
"""Host_call_fn.
Args:
**kwargs: dict of summary name to tf.Tensor mapping. The value we see here
is the tensor across all cores, concatenated along axis 0.... | 4dafbbed695205f97501ab44f4eeae480d562f7e | 29,353 |
from datetime import datetime
def determine_horizons_id(lines, now=None):
"""Attempts to determine the HORIZONS id of a target body that has multiple
possibilities. The passed [lines] (from the .args attribute of the exception)
are searched for the HORIZONS id (column 1) whose 'epoch year' (column 2)
... | 1cbf143bfd8a7b5a3178a443b3dfc4298e02bbfd | 29,354 |
def export_read_file(channel, start_index, end_index, bulkfile, output_dir, remove_pore=False):
"""Generate a read FAST5 file from channel and coordinates in a bulk FAST5 file
Parameters
----------
channel : int
channel number from bulk FAST5 file
start_index : int
start index for r... | 8fc7b93492eb709d6e08d66c4089f48908d91919 | 29,355 |
def escape_html(s: str)-> str:
"""
Escape html
:param str s: string
:return: replaced html-string
"""
s = s.replace('&','&')
s = s.replace('<','<')
s = s.replace( '>','>')
s = s.replace('"','"')
s = s.replace("'", ''')
return s | d66f1af0990a108b7c6fa9ce1e5a0e51bf44f416 | 29,356 |
def CSCH(*args) -> Function:
"""
The CSCH function returns the hyperbolic cosecant of any real number.
Learn more:
https//support.google.comhttps://support.google.com/docs/answer/9116336.
"""
return Function("CSCH", args) | 506c16e1d53a91e18e73d416f252a47f5c35fc95 | 29,357 |
def _get_valid_name(proposed_name):
"""Return a unique slug name for a service"""
slug_name = slugify(proposed_name)
name = slug_name
if len(slug_name) > 40:
name = slug_name[:40]
return name | cce3a986fc671233c7c25029cd306c8438465618 | 29,358 |
def create_pif(headers, row):
"""
Creates PIFs from lists of table row
:param headers: header data from the table
:param row: the row of data
:return: ChemicalSystem containing the data from that row
"""
sys_dict = {}
keywords, names, units, systs = get_header_info(headers)
sys_di... | 25c69e69787d6abb173318d112e1fdcc7a400174 | 29,359 |
def update_user(old_email, new_email=None, password=None):
"""Update the email and password of the user.
Old_email is required, new_email and password are optional, if both parameters are
empty update_user() will do nothing. Not asking for the current password is
intentional, creating and updating are ... | cb8f23ccd2d9e0d0b390358ef440af28d67e549d | 29,360 |
from typing import Optional
def get_text(text_node: Optional[ET.Element]) -> Optional[str]:
"""Return stripped text from node. None otherwise."""
if text_node is None:
return None
if not text_node.text:
return None
return text_node.text.strip() | 2bb7c8ae6500d9a8ca5ef6be09dbf3abfc04a013 | 29,361 |
def function_d(d, d1, d2=1):
"""doc string"""
return d + d1 + d2 | 92d3bb788191612c6a67f67a05bd703a02f43a04 | 29,362 |
from unittest.mock import patch
def qgs_access_control_filter():
"""
Mock some QgsAccessControlFilter methods:
- __init__ which does not accept a mocked QgsServerInterface;
- serverInterface to return the right server_iface.
"""
class DummyQgsAccessControlFilter:
def __init__(self, s... | df84f1ff78c52376777c9238a3ee857c8c31f3d2 | 29,363 |
def ppmv2pa(x, p):
"""Convert ppmv to Pa
Parameters
----------
x Gas pressure [ppmv]
p total air pressure [Pa]
Returns
-------
pressure [Pa]
"""
return x * p / (1e6 + x) | 974d79d022a7fb655040c7c2900988cd4a10f064 | 29,364 |
def make_elastic_uri(schema: str, user: str, secret: str, hostname: str, port: int) -> str:
"""Make an Elasticsearch URI.
:param schema: the schema, e.g. http or https.
:param user: Elasticsearch username.
:param secret: Elasticsearch secret.
:param hostname: Elasticsearch hostname.
:param port... | be959e98330913e75485006d1f4380a57e990a05 | 29,365 |
def _truncate(s: str, max_length: int) -> str:
"""Returns the input string s truncated to be at most max_length characters
long.
"""
return s if len(s) <= max_length else s[0:max_length] | 52c49c027057024eaa27a705a0d2c013bff7a2ce | 29,366 |
def verify_days_of_week_struct(week, binary=False):
"""Given a dictionary, verify its keys are the correct days
of the week and values are lists of 24 integers greater than zero.
"""
if set(DAYS_OF_WEEK) != set(week.keys()):
return False
# Each day must be a list of ints
for _, v in we... | 57b4b23d0b492f2fc25a0bdb9d218c6fd9deefc0 | 29,367 |
def create_attention_mask_from_input_mask(from_tensor, to_mask):
"""Create 3D attention mask from a 2D tensor mask.
Args:
from_tensor: 2D or 3D Tensor of shape [batch_size, from_seq_length, ...].
to_mask: int32 Tensor of shape [batch_size, to_seq_length].
Returns:
float Tensor of shape [batch_size, from_seq_... | d0a5c11108717c1e389d0940c9740d7a0c2671f0 | 29,368 |
def execute_inspection_visits_data_source(operator_context, return_value, non_data_function_args) -> BackendResult:
"""Execute inspections when the current operator is a data source and does not have parents in the DAG"""
# pylint: disable=unused-argument
inspection_count = len(singleton.inspections)
it... | f42ce3cb7b0900a5e7458bf0ad478843860db0f9 | 29,369 |
def parse(template, delimiters=None, name='<string>'):
"""
Parse a template string and return a ParsedTemplate instance.
Arguments:
template: a template string.
delimiters: a 2-tuple of delimiters. Defaults to the package default.
Examples:
>>> parsed = parse(u"Hey {{#who}}{{name}}... | 51a9da21831afb0b124cc9481f49b546a51a587a | 29,370 |
def get_phases(t, P, t0):
"""
Given input times, a period (or posterior dist of periods)
and time of transit center (or posterior), returns the
phase at each time t. From juliet =]
"""
if type(t) is not float:
phase = ((t - np.median(t0)) / np.median(P)) % 1
ii = np.where(phase >... | 8d5e821112c7fffd0766dbb0158fd2f4034ef313 | 29,371 |
async def my_profile(current_user: User = Depends(get_current_active_user)):
"""GET Current user's information."""
return current_user | fd03fe06b9737565e338b3b3ccd5999b0da32cc1 | 29,372 |
def are_2d_vecs_collinear(u1, u2):
"""Check that two 2D vectors are collinear"""
n1 = np.array([-u1[1], u1[0]])
dot_prod = n1.dot(u2)
return np.abs(dot_prod) < TOL_COLLINEAR | 2861b6316a5125799a91a471129bfc1ce2e91992 | 29,373 |
from datetime import datetime
import time
def TimeFromTicks(ticks: int) -> datetime.time: # pylint: disable=invalid-name
"""
Constructs an object holding a time value from the given ticks value.
Ticks should be in number of seconds since the epoch.
"""
return Time(*time.gmtime(ticks)[3:6]) | a53564b2890080a7fbe0f406ae76c7237c92c34a | 29,374 |
import importlib
def load_model(opt, dataloader):
""" Load model based on the model name.
Arguments:
opt {[argparse.Namespace]} -- options
dataloader {[dict]} -- dataloader class
Returns:
[model] -- Returned model
"""
model_name = opt.model
model_path = f"lib.models.{... | 8ad05c4a0f51c40851a9daecf81ed8bf9862979c | 29,375 |
def process(cntrl):
""" We have all are variables and parameters set in the object, attempt to
login and post the data to the APIC
"""
if cntrl.aaaLogin() != 200:
return (1, "Unable to login to controller")
rc = cntrl.genericGET()
if rc == 200:
return (0, format_content(cn... | 8e20f4b81314436e53713a418447072820e5c55b | 29,376 |
from typing import Callable
from typing import Iterator
def create_token_swap_augmenter(
level: float, respect_ents: bool = True, respect_eos: bool = True
) -> Callable[[Language, Example], Iterator[Example]]:
"""Creates an augmenter that randomly swaps two neighbouring tokens.
Args:
level (float... | 1fc41e75d96ea7d4153802f4e86f8ab25d7227c3 | 29,377 |
def getUnigram(str1):
"""
Input: a list of words, e.g., ['I', 'am', 'Denny']
Output: a list of unigram
"""
words = str1.split()
assert type(words) == list
return words | d540ee199ab62c383461893e91034399d22fe6d6 | 29,378 |
def expval_and_stddev(items, exp_ops=''):
"""Compute expectation values from distributions.
.. versionadded:: 0.16.0
Parameters:
items (list or dict or Counts or ProbDistribution or QuasiDistribution): Input
distributions.
exp_ops (str or dict or list): String or... | c024797f00d87ece0b0e871530c747a93d151f3c | 29,379 |
def newton_polish(polys,root,niter=100,tol=1e-8):
"""
Perform Newton's method on a system of N polynomials in M variables.
Parameters
----------
polys : list
A list of polynomial objects of the same type (MultiPower or MultiCheb).
root : ndarray
An initial guess for Newton's met... | cdf2b993bb34142cf82de9f7a2a003f7eb9a0a24 | 29,380 |
def COUNT(logic, n=2):
"""
统计满足条件的周期数
:param logic:
:param n:
:return:
"""
return pd.Series(np.where(logic, 1, 0), index=logic.index).rolling(n).sum() | e175629e301152978e5d9a46caa4921e080048a8 | 29,381 |
import yaml
def get_model(name):
"""
Get the warpped model given the name. Current support name:
"COCO-Detection/retinanet_R_50_FPN";
"COCO-Detection/retinanet_R_101_FPN";
"COCO-Detection/faster_rcnn_R_50_FPN";
"COCO-Detection/faster_rcnn_R_101_FPN";
"COCO-InstanceSegmentation/mask_rcnn_... | fe1842950c93d790623d6ba072c5cab48eb03eb9 | 29,382 |
import os
import requests
import tqdm
import math
import torch
def load_model_params(model, model_name, model_uri, ignore_cache=False, device=None):
"""Load model parameters from disk or from the web.
Parameters
----------
model : torch.nn.modules.container.Sequential
The model instance to lo... | 64fc4282065f44e4e179ce3d5d23381705fc1cf6 | 29,383 |
def energy_sensor(
gateway_nodes: dict[int, Sensor], energy_sensor_state: dict
) -> Sensor:
"""Load the energy sensor."""
nodes = update_gateway_nodes(gateway_nodes, energy_sensor_state)
node = nodes[1]
return node | 8e2560aa8b442c94fb39d602b100a7aa8757de84 | 29,384 |
def compute_one_decoding_video_metrics(iterator, feed_dict, num_videos):
"""Computes the average of all the metric for one decoding.
Args:
iterator: dataset iterator.
feed_dict: feed dict to initialize iterator.
num_videos: number of videos.
Returns:
all_psnr: 2-D Numpy array, shape=(num_samples... | 8acd5cd1b564d22b26ebfd0ddd40fb76e90aa9a4 | 29,385 |
import uuid
import os
def supplier_rif_file_path(instance, filename):
"""Generate file path for new suppliers rif image"""
ext = filename.split('.')[-1]
filename = f'{uuid.uuid4()}.{ext}'
return os.path.join('uploads/supplier/rif/', filename) | 1c15484dd173712c94db70e81752d832c4b83144 | 29,386 |
import os
import hashlib
def get_hash(name):
""" This hash function receives the name of the file
and returns the hash code
"""
readsize = 64 * 1024
with open(name, 'rb') as f:
size = os.path.getsize(name)
data = f.read(readsize)
f.seek(-readsize, os.SEEK_END)
data ... | b0962aeacd6747b5a0ee4cef1d30a78e9d7c7686 | 29,387 |
def geocode_locations(df: gpd.GeoDataFrame, loc_col: str):
"""
Geocode location names into polygon coordinates
Parameters
----------
df: Geopandas DataFrame
loc_col:str
name of column in df which contains locations
Returns
-------
"""
locations = geocode(df.loc[:, loc_col])
... | c1ba4edfa31ca4d7d6a2e01a5c3342025936b085 | 29,388 |
import json
def get_data():
"""Get dummy data returned from the server."""
jwt_data = get_jwt()
data = {'Heroes': ['Hero1', 'Hero2', 'Hero3']}
json_response = json.dumps(data)
return Response(json_response,
status=Status.HTTP_OK_BASIC,
mimetype='applic... | c3df0a63dbb06822bbea1278c539ab1386e59d99 | 29,389 |
import pandas
def coerce_integer(df):
"""
Loop through the columns of a df, if it is numeric,
convert it to integer and fill nans with zeros.
This is somewhat heavy-handed in an attempt to force
Esri to recognize sparse columns as integers.
"""
# Numeric columns to not coerce to integer
... | d4b5963378a10a4bde6f7e1e2111908b83d90b7d | 29,390 |
def read_cfg(floc, cfg_proc=process_cfg):
"""
Reads the given configuration file, returning a dict with the converted values supplemented by default values.
:param floc: The location of the file to read.
:param cfg_proc: The processor to use for the raw configuration values. Uses default values when t... | 1ec276ad434ce36e32fab73b1cc65c05a14e032a | 29,391 |
import os
def get_jsmol_input(request, pk):
"""Return a statement to be executed by JSmol.
Go through the atomic structure data subsets of the representative
data set of the given system. Pick the first one that comes with a
geometry file and construct the "load data ..." statement for
JSmol. If ... | 836a5920f7510e82259cbcc7abea8d5a863406b2 | 29,392 |
from datetime import datetime
def convert_date(raw_date: str, dataserver=True):
"""
Convert raw date field into a value interpretable by the dataserver.
The date is listed in mddyy format,
"""
date = datetime.strptime(raw_date, "%Y%m%d")
if not dataserver:
return date.strftime("%m/%d/%... | 6fc9ec6bf5a336998e4bd9752abb8804251d8c33 | 29,393 |
from re import VERBOSE
def getComputerMove(board):
"""
Given a board and the computer's letter, determine where to move and return that move. \n
Here is our algorithm for our Tic Tac Toe AI:
"""
copy = getBoardCopy(board)
for i in range(1, NUMBER_SPACES):
if isSpaceFree(copy, i):
... | 83328215ca64170ec88c577ae41fcbd0e2076c47 | 29,394 |
from .. import Plane
def triangular_prism(p1, p2, p3, height, ret_unique_vertices_and_faces=False):
"""
Tesselate a triangular prism whose base is the triangle `p1`, `p2`, `p3`.
If the vertices are oriented in a counterclockwise direction, the prism
extends from behind them.
Args:
p1 (np.... | 99ecdc6054dba1f2b955b08bf082636cac546fb8 | 29,395 |
def chain_species_base(base, basesite, subunit, site1, site2, size, comp=1):
"""
Return a MonomerPattern representing a chained species, chained to a base complex.
Parameters
----------
base : Monomer or MonomerPattern
The base complex to which the growing chain will be attached.
basesi... | b7b619a810b7d84ee64a92bcda4b4578d797be63 | 29,396 |
def find_one_item(itemname):
"""
GET the one item in the shop whose title matches itemname.
:param itemname: The title to look for in the shop.
:type itemname: str
:return: dict(str, Decimal, int). A dict representing the requested item.
:raise: werkzeug.exceptions.NotFound
"""
try:
... | cec13fec0489489660da375e7b7fc2168324909f | 29,397 |
import string
def PromGraph(data_source, title, expressions, **kwargs):
"""Create a graph that renders Prometheus data.
:param str data_source: The name of the data source that provides
Prometheus data.
:param title: The title of the graph.
:param expressions: List of tuples of (legend, expr)... | 7a2a8d0902bc9ef2fcc03e16678c4a40976bdb0e | 29,398 |
import os
def create_output_subdirectory(subdirectory: str) -> str:
""" Creates a subdirectory in the output directory. """
path = os.path.join(GLOBAL_CONFIG['output_directory_path'], subdirectory)
path = os.path.abspath(path)
os.makedirs(path, exist_ok=True)
return path | bd63573a6dc0500662535a541879a47b156b6e42 | 29,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.