content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def bytes_to_msg(seq, standard="utf-8"):
"""Decode bytes to text."""
return seq.decode(standard) | 5664d97b3fec5d119daa2171bcb431ca5a4b5f33 | 3,640,400 |
from tqdm.auto import tqdm
from typing import Union
import random
import time
import statistics
def cross_validate(
estimator,
input_relation: Union[str, vDataFrame],
X: list,
y: str,
metric: Union[str, list] = "all",
cv: int = 3,
pos_label: Union[int, float, str] = None,
cutoff: float... | fc59bb42c9e776e91b455f5d79e762721246754d | 3,640,401 |
def bonferroni_correction(pvals):
"""
Bonferroni correction.
Reference: http://en.wikipedia.org/wiki/Bonferroni_correction
"""
n = len(pvals)
return [min(x * n , 1.0) for x in pvals] | f57ffd6b77a0a74a61904334604d1cb0eb08f8ff | 3,640,402 |
from typing import Any
from typing import List
from typing import Optional
from typing import Dict
def to_r4(fhir_json: JsonObj, opts: Namespace, ifn: str) -> JsonObj:
"""
Convert the FHIR Resource in "o" into the R4 value notation
:param fhir_json: FHIR resource
:param opts: command line parser argu... | c1e249387fa5045be65bc4ca742ebf086745a8a8 | 3,640,403 |
from itertools import accumulate, chain, repeat
def make_fib():
"""Returns a function that returns the next Fibonacci number
every time it is called.
>>> fib = make_fib()
>>> fib()
0
>>> fib()
1
>>> fib()
1
>>> fib()
2
>>> fib()
3
>>> fib2 = make_fib()
>>> ... | e546ce79c4b441418f5325b0ac5d7c3faf6ac35e | 3,640,404 |
import codecs
import os
def find_issue(case):
"""
Find the issue sentence for a given case.
"""
if ".txt" not in case:
case += ".txt"
f = codecs.open(os.path.join(BASE_DIR, case), encoding="utf-8", errors="replace")
issue, switch = "", False
for line in f.readlines():
if ... | d7e063cb131b1658a40bd04155c4d839889825b5 | 3,640,405 |
def render_injected(http_resp, extra_html):
"""
render_injected(http_resp, extra_html) -> HttpResponse
Inject the extra html into the content of the http_resp.
``extra_html`` can be a string or an object with an ``html`` method/field.
"""
assert isinstance(http_resp, HttpResponse)
if 'text/html' not in h... | a3f49419359a68ecc72f78f00ae3e4a18f4957d6 | 3,640,406 |
import os
def _extract_username(filename):
"""Return username (if found) from the credentials"""
if not os.path.exists(filename):
logger.warning("Cifs credentials file %s does not exist", filename)
return
for line in open(filename):
if ("username" in line) and ("=" in line):
... | 51c72e7febfb435f61eee32aaaa628a4af6f1f85 | 3,640,407 |
from unittest.mock import Mock
from unittest.mock import patch
def mock_gitlab_api_projects(save=None, mergerequests_list=None):
"""A pseudo mock"""
def get(*args, **kwargs):
project = Mock('gitlab.v4.objects.Project')
project.save = save
project.mergerequests = \
Mock('git... | 52b48a0f9083a22fdafcfa3b797d6580967b1f02 | 3,640,408 |
def text_in_bytes(text, binary_data, encoding="utf-8"):
"""Return True of the text can be found in the decoded binary data"""
return text in binary_data.decode(encoding) | e416057989c452718fa27b5f84286e347b986117 | 3,640,409 |
import json
def make_auth(sub, tenant=None):
"""
Prepare an almost-valid JWT token header, suitable for consumption by our identity middleware (needs sub and optionally mender.tenant claims).
The token contains valid base64-encoded payload, but the header/signature are bogus.
This is enou... | c8f8896814d1571bb4bb54a5507eda19e5ffd46c | 3,640,410 |
import re
def available_mem(cores, mem, fmtstring=True):
"""Calculate available memory for a process
Params:
cores (int): number of cores
mem (str): set memory as string with conversion (M, G, g)
fmtstring (bool): return memory as formatted string
"""
prefix = "G"
m = re.match("[0... | 241ad5133917d84b78bc0670fc974184b88e3978 | 3,640,411 |
def normalize_v(v):
""" Normalize velocity to [-1, 1].
Ref: https://github.com/microsoft/AirSim-Drone-Racing-VAE-Imitation/blob/e651be52ff8274c9f595e88b13fe42d51302403d/racing_utils/dataset_utils.py#L20 """
# normalization of velocities from whatever to [-1, 1] range
v_x_range = [-1, 7]
v_y_ran... | cd47c8d3498e677a1f566b64199224f23a4b5896 | 3,640,412 |
def allele_counts_dataframe(read_evidence_generator):
"""
Creates a DataFrame containing number of reads supporting the
ref vs. alt alleles for each variant.
"""
return dataframe_from_generator(
element_class=ReadEvidence,
variant_and_elements_generator=read_evidence_generator,
... | dd76b3b168977eb185ba1205a75ba4642becc913 | 3,640,413 |
def validate_rule_paths(sched: schedule.Schedule) -> schedule.Schedule:
"""A validator to be run after schedule creation to ensure
each path contains at least one rule with an expression or value.
A ValueError is raised when this check fails."""
for path in sched.unfold():
if path.is_final and ... | 2ddfd6f9607687f6a3e3c955ed3470913fdf14bd | 3,640,414 |
def spiralcontrolpointsvert(
x: int, y: int,
step: int,
growthfactor: float,
turns: int):
"""Returns a list[(int, int)]
of 2D vertices along a path
defined by a square spiral
Args:
x, y: int centerpoint
coordinates
step: int step... | de9f577ed826b227d44b69e638dd33e08ea9c430 | 3,640,415 |
def determine_current_taxid(given_taxid):
"""Determine NCBI's current taxonomic ID given an (old) taxonomic ID
Args:
given_taxid: previously used NCBI taxonomic ID
Returns:
most current NCBI taxonomic ID
"""
taxid = given_taxid
aka_taxid_in_xml = None
redirects = 0
# S... | f924309e8e19b5ffd9a46bf8c80054577bb7a28b | 3,640,416 |
def validate_dependencies():
"""Validate external dependencies.
This function does NOT have to exist. If it does exist the runtime will call and execute it during api
initialization. The purpose of this function is to verify that external dependencies required to auto-generate
a problem are properly in... | 0bea4c7bbf6198bf18514233c902f5bfa62dc8f8 | 3,640,417 |
def find_closest_vertex(desired_hop, available_vertices):
""" Find the closest downstream (greater than or equal) vertex
in availbale vertices. If nothing exists, then return -1.
Keyword arguments:
desired_hop -- float representing the desired hop location
available_location -- np array of avai... | c0aa85238faf58ff30cc937bf73b53ce2cc0ee48 | 3,640,418 |
def second_smallest(numbers):
"""Find second smallest element of numbers."""
m1, m2 = float('inf'), float('inf')
for x in numbers:
if x <= m1:
m1, m2 = x, m1
elif x < m2:
m2 = x
return m2 | 0ca7b297da68651e4a8b56377e08f09d4d82cfb7 | 3,640,419 |
import numpy
def calc_sft_ccs_by_dictionary(dict_crystal, dict_in_out, flag_use_precalculated_data: bool = False):
"""Calculate structure factor tensor in CCS (X||a*, Z||c) based on the information given in dictionary.
Output information is written in the same dictionary.
"""
dict_crystal_keys = dict... | 6905b0c1b4d4b3b65099600822ca0f6077fe1393 | 3,640,420 |
def normalize_mesh(mesh, in_place=True):
"""Rescales vertex positions to lie inside unit cube."""
scale = 1.0 / np.max(mesh.bounds[1, :] - mesh.bounds[0, :])
centroid = mesh.centroid
scaled_vertices = (mesh.vertices - centroid) * scale
if in_place:
scaled_mesh = mesh
scaled_mesh.vertices = scaled_vert... | e70ff4dea9173a541267c2a5bd040f12de4499c8 | 3,640,421 |
from datetime import datetime
import socket
def get_run_name():
""" A unique name for each run """
return datetime.now().strftime(
'%b%d-%H-%M-%S') + '_' + socket.gethostname() | 26f57e72912e896fe192de61b6477ef65051fccd | 3,640,422 |
import traceback
def process_request(identifier, browser, document_type='Annual Return', num_doc=1, status_df=None):
"""
Search ICRIS for the passed identifier, analyze the returned documents,
and cart the documents depending on whether we purchased
the document before.
Parameters
---------... | 7a6071488aba447959264d80d5bb201deb9a2339 | 3,640,423 |
def create_blackboard():
"""
Create a blackboard with a few variables.
Fill with as many different types as we need to get full coverage on
pretty printing blackboard tests.
"""
Blackboard.clear()
blackboard = Client(name="Tester")
for key in {"foo", "some_tuple", "nested", "nothing"}:
... | 776129ba57a545ef3bcfca75c99816fd198bfc3d | 3,640,424 |
def adminRoomDelete(*args, **kwargs):
""" 删除房间 """
params = kwargs['params']
filters = {
Room.room_uuid == params['room_uuid']
}
Room().delete(filters)
filters = {
UserRoomRelation.room_uuid == params['room_uuid']
}
UserRoomRelation().delete(filters)
return BaseContro... | d8f9a29b46aac908eda9e5fedbc113ce93bc2bf4 | 3,640,425 |
def who_is_it(image_path, database, model):
"""
Arguments:
image_path -- path to an image
database -- database containing image encodings along with the name of the person on the image
model -- your Inception model instance in Keras
Returns:
min_dist -- the minimum distance between image_pa... | e2301b2504cc7bbb4c362b98541cad325b4b8587 | 3,640,426 |
def compute_win_state_str_row(n_rows, n_cols, n_connects):
"""Each win state will be a string of 0s and 1s which can
then converted into an integer in base 2.
I assume that at the maximum n_rows = n_cols = 5, which means
that a 31 bit integer (since in Python it's always signed)
should be more th... | b0f0f2846de7506b4b69f90bb8a0b1641a421659 | 3,640,427 |
import hmac
import hashlib
def hmac_sha512(key: bytes, data: bytes) -> bytes:
"""
Return the SHA512 HMAC for the byte sequence ``data`` generated with the
secret key ``key``.
Corresponds directly to the "HMAC-SHA512(Key = ..., Data = ...)" function
in BIP32
(https://github.com/bitcoin/bips/bl... | 64850ea2d5e921138d8e0ebc2d021f8eaf5a7357 | 3,640,428 |
def __scheduler_trigger(cron_time_now, now_sec_tuple, crontask, deltasec=2):
"""
SchedulerCore logic
actual time: cron_time_now format: (WD, H, M, S)
actual time in sec: now_sec_tuple: (H sec, M sec, S)
crontask: ("WD:H:M:S", "LM FUNC")
deltasec: sample time window: +/- sec: -sec... | 8c3cc2f23bf94bfe7f817db542f50345be8f1a20 | 3,640,429 |
from typing import Dict
import os
import yaml
import getpass
def gen_canvas_config() -> Dict:
"""Generates yaml config from user input for canvas interface
Returns
-------
Dict
canvas config dict
"""
# check for existing canvas config
if (
os.path.exists(CANVAS_CONF_PA... | 2141e0793444b1687dbb2c5d786327cdb3d935cc | 3,640,430 |
def get13FAmendmentType(accNo, formType=None) :
"""
Gets the amendment type for a 13F-HR/A filing - may be RESTATEMENT or NEW HOLDINGS.
This turned out to be unreliable (often missing or wrong), so I don't use it to get
the combined holdings for an investor. Instead I just look at the number of holdings... | a8ff184b4d3eb43ea8da75a64e83cb136908364e | 3,640,431 |
def tabs_to_cover_string(string):
"""
Get the number of tabs required to be at least the same length as a given string.
:param string: The string
:return: The number of tabs to cover it
:rtype: int
"""
num_tabs = int(np.floor(len(string) / 8) + 1)
return num_tabs | 242496271bafc78a2180c8e8798b9ed4892afb29 | 3,640,432 |
def kl(p, q):
"""
Kullback-Leibler divergence for discrete distributions
Parameters
----------
p: ndarray
probability mass function
q: ndarray
probability mass function
Returns
--------
float : D(P || Q) = sum(p(i) * log(p(i)/q(i))
Discrete probability distribut... | 905903324958414972329e32becf9c8848f54029 | 3,640,433 |
def map_uris(uris):
"""Map URIs from external URI to HDFS
:return:
"""
pkgs_path = __pillar__['hdfs']['pkgs_path']
ns = nameservice_names()
return map(lambda x: 'hdfs://{0}{1}/{2}'.format(ns[0], pkgs_path, __salt__['system.basename'](x)), uris) | 8dd682e932c2ac4dd495cfd11e88abdf58e78800 | 3,640,434 |
from typing import Any
def delete_task(id: str, db: Session = Depends(get_db)) -> Any:
"""Delete a task"""
try:
todo_interactor = ToDoInteractor(db=db)
todo_interactor.remove(id=id)
return {"success": f"removed task: {id}"}
except HTTPException as e:
logger.exception(e)
... | 93841bd4975bcd3851ee4cc6e38f62c735b85183 | 3,640,435 |
def get_body(name):
"""Retrieve the Body structure of a JPL .bsp file object
Args:
name (str)
Return:
:py:class:`~beyond.constants.Body`
"""
return Pck()[name] | d9949d9638c27b77f0bff203d2015aeb7af8c389 | 3,640,436 |
def is_available():
"""
Convenience function to check if the current platform is supported by this
module.
"""
return ProcessMemoryInfo().update() | d7d1d842009b39f79c650d54f776db664b30ea14 | 3,640,437 |
def render_path_spiral(c2w, up, rads, focal, zrate, rots, N):
"""
enumerate list of poses around a spiral
used for test set visualization
"""
render_poses = []
rads = np.array(list(rads) + [1.])
for theta in np.linspace(0., 2. * np.pi * rots, N+1)[:-1]:
c = np.dot(c2w[:3,:4], np.arra... | 0eb608be5f29425cca62b15ce48db02e2297be17 | 3,640,438 |
from typing import Dict
from typing import List
from typing import Any
def placeAnchorSourceToLagunaTX(
common_anchor_connections: Dict[str, List[Dict[str, Any]]]
) -> List[str]:
"""
The anchors are placed on the Laguna RX registers
We move the source cell of the anchor onto the corresponding TX registers
"... | d30cef6a42b846a3d82467eabebce1275a3d81ed | 3,640,439 |
def post_example_form():
"""Example of a post form."""
return render_template("post-form.html") | e5e934dfe0d2b81081cda5deeca483f46fae89fe | 3,640,440 |
def validate(data):
"""Validates incoming data
Args:
data(dict): the incoming data
Returns:
True if the data is valid
Raises:
ValueError: the data is not valid
"""
if not isinstance(data, dict):
raise ValueError("data should be dict")
if "text" not in data ... | ae8b7e74bd7607a7c8f5079014a0f5e3af5bc011 | 3,640,441 |
def stripExtra(name):
"""This function removes paranthesis from a string
*Can later be implemented for other uses like removing other characters from string
Args:
name (string): character's name
Returns:
string: character's name without paranthesis
"""
startIndexPer=name.find('(')
start... | fd9b8c2d6f513f06d8b1df067520c7f05cff023d | 3,640,442 |
def google_maps(maiden: str) -> str:
"""
generate Google Maps URL from Maidenhead grid
Parameters
----------
maiden : str
Maidenhead grid
Results
-------
url : str
Google Maps URL
"""
latlon = toLoc(maiden)
url = "https://www.google.com/maps/@?api=1&map_... | 04c2a6d730831746dc63ce6c733b16322d0696da | 3,640,443 |
def format_signed(feature, # type: Dict[str, Any]
formatter=None, # type: Callable[..., str]
**kwargs
):
# type: (...) -> str
"""
Format unhashed feature with sign.
>>> format_signed({'name': 'foo', 'sign': 1})
'foo'
>>> format_signed({'na... | 4adeecb92b0d102ae512c2c8acf89d38454b4e4e | 3,640,444 |
def load_ligand(sdf):
"""Loads a ligand from an sdf file and fragments it.
Args:
sdf: Path to sdf file containing a ligand.
"""
lig = next(Chem.SDMolSupplier(sdf, sanitize=False))
frags = generate_fragments(lig)
return lig, frags | 984ba4bf61af6f8197f96a80f0f493b7dae84f08 | 3,640,445 |
def CMDpending(parser, args):
"""Lists pending jobs."""
parser.add_option('-b',
'--builder',
dest='builders',
action='append',
default=[],
help='Builders to filter on')
options, args, buildbot = parser.parse_args(a... | a9d56333fa84f2c92a969135c0dcc02bf94b972f | 3,640,446 |
def numpy_translation(xyz):
"""Returns the dual quaternion for a pure translation.
"""
res = np.zeros(8)
res[3] = 1.0
res[4] = xyz[0]/2.0
res[5] = xyz[1]/2.0
res[6] = xyz[2]/2.0
return res | 8180449ec6128237f63b4519117553e85a2d1369 | 3,640,447 |
def sort_car_models(car_db):
"""return a copy of the cars dict with the car models (values)
sorted alphabetically"""
sorted_db = {}
for model in car_db:
sorted_db[model] = sorted(car_db[model])
return sorted_db | a478f16ece83058ba411480b91584e4c61026141 | 3,640,448 |
import requests
def test_module(params) -> str:
"""Tests API connectivity and authentication'"
Returning 'ok' indicates that the integration works like it is supposed to.
Connection to the service is successful.
Raises exceptions if something goes wrong.
:return: 'ok' if test passed, anything else... | 64d45742c82854a9eb3d4e04aadbe05d458f9aca | 3,640,449 |
from typing import Tuple
from typing import Container
import asyncio
def create(auto_remove: bool = False) -> Tuple[str, str]:
"""
Creates a database inside a docker container
:return: container name, database name
:rtype: Tuple[str, str]
"""
piccolo_docker_repository = PiccoloDockerRepository... | c875b034b564d85e104655086b7faa1ed7a2df2c | 3,640,450 |
def get_by_id(db: Session, work_item_id):
"""Get a specified WorkItem and return it."""
workitem = db.get(WorkItem, work_item_id)
if workitem:
return workitem
if not workitem:
logger.debug("Item not found")
raise HTTPException(status_code=404, detail="Item not found") | c9e8899ec9d159115e03f91ab9e9656984f20cf9 | 3,640,451 |
import os
import tqdm
import torch
def evaluate(args, model, eval_dataset, tokenizer, step, prefix=""):
"""
Evaluation of model
:param args: input arguments from parser
:param model: pytorch model to be evaluated
:param eval_dataset: dataset used for evaluation
:param tokenizer: tokenizer used... | 720898cff8566b7f48f5c11abde8de0875797f87 | 3,640,452 |
import os
import subprocess
import time
import itertools
def test(path, shell, indent=2):
"""Run test at path and return input, output, and diff.
This returns a 3-tuple containing the following:
(list of lines in test, same list with actual output, diff)
diff is a generator that yields the diff... | a973190b180ca2bf2c46ed93ee91c55275235d1c | 3,640,453 |
import re
def load_expected_results(file, pattern):
"""Reads the file, named file, which contains test results separated
by the regular expression pattern.
The test results are returned as a dictionary.
"""
expected = {}
compiled_pattern = re.compile(pattern)
with open(file) as f:
... | 05e20e2e6932c2a4db634f48046ea3e3f6e5dedc | 3,640,454 |
def following(request):
"""View all posts from followed users"""
if request.method == "GET":
user = User.objects.get(pk=request.user.id)
following = user.follow_list.following.all()
# Post pagination: https://docs.djangoproject.com/en/3.1/topics/pagination/
posts = Post.objects.... | 1b350c835d6bbf6d51c1a99d56d405a989f681a2 | 3,640,455 |
def create_random_polygon(min_x, min_y, max_x, max_y, vertex_num):
"""Create a random polygon with the passed x and y bounds and the passed number of vertices; code adapted from: https://stackoverflow.com/a/45841790"""
# generate the point coordinates within the bounds
x = np.random.uniform(min_x, max_x, ... | ad04591daf524bd0c97890a36722233cd08c4e5e | 3,640,456 |
def document_hidden(session):
"""Polls for the document to become hidden."""
def hidden(session):
return session.execute_script("return document.hidden")
return Poll(session, timeout=3, raises=None).until(hidden) | 21376291398aea859ed0f4d080a7bf617d93521f | 3,640,457 |
def create_blueprint():
"""Creates a Blueprint"""
blueprint = Blueprint('Tasks Blueprint', __name__, url_prefix='/tasks')
blueprint.route('/', methods=['POST'])(tasks.create)
blueprint.route('/', methods=['PATCH'])(tasks.patch)
blueprint.route('/', methods=['GET'])(tasks.list)
return blueprint | c0e0412e599e4f4378efa2e2749f957a8b58043b | 3,640,458 |
import gzip
def estimate_null_variance_gs(gs_lists, statslist, Wsq, single_gs_hpo=False,
n_or_bins=1):
"""
Estimates null variance from the average of a list of known causal windows
"""
statspaths = {h : p for h, p in [x.rstrip().split('\t')[:2] \
for... | 755f35c108b9045d237a6cbfa442e7b6b0c24829 | 3,640,459 |
import torch
def create_model(config):
"""Create the score model."""
model_name = config.model.name
score_model = get_model(model_name)(config)
score_model = score_model.to(config.device)
score_model = torch.nn.DataParallel(score_model)
return score_model | ca0b9fa1c68d83c1697d82273fc740ba35826c87 | 3,640,460 |
import gc
def at(addr):
"""Look up an object by its id."""
for o in gc.get_objects():
if id(o) == addr:
return o
return None | f408b9a63afad1638f156163c6249e0e8095bff4 | 3,640,461 |
import warnings
def money_flow_index(close_data, high_data, low_data, volume, period):
"""
Money Flow Index.
Formula:
MFI = 100 - (100 / (1 + PMF / NMF))
"""
catch_errors.check_for_input_len_diff(
close_data, high_data, low_data, volume
)
catch_errors.check_for_period_erro... | 7c122ae10ef406fabf56f63ac80a35557999c2ee | 3,640,462 |
def Get_Weights(dict_rank):
"""Converts rankings into weights."""
Weights = adapt.create_Weightings(dict_rank)
return Weights | d50b9dcad7803a34c969f357cd4659ffe49ab740 | 3,640,463 |
import os
import torch
def load_client_model(models_path, config):
"""
Returns Pytorch client model loaded given the client model's path
"""
device = load_device()
client_hparams = config.get("client_hparams")
for needed_param in client_hparams.get("needed", []):
client_hparams[needed_... | c9af03430daf779c4d5f84cf873e2bf02131ddef | 3,640,464 |
def psisloo(log_likelihood):
"""
Summarize the model fit using Pareto-smoothed importance sampling (PSIS)
and approximate Leave-One-Out cross-validation (LOO).
Takes as input an ndarray of posterior log likelihood terms [ p( y_i | theta^s ) ]
per observation unit.
e.x. if using py... | 5500ebd85eb9ac796b0410756e4b51f674890ca6 | 3,640,465 |
from typing import Tuple
from typing import Optional
from typing import Pattern
def rxdelim(content: str) -> Tuple[Optional[Pattern], Optional[Pattern]]:
"""
Return suitable begin and end delimiters for the content `content`.
If no matching delimiters are found, return `None, None`.
"""
tp = magic... | 884efcd13846da9938b6f120cb3d8963addd0b42 | 3,640,466 |
def GenKeyOrderAttrs(soappy_service, ns, type_name):
"""Generates the order and attributes of keys in a complex type.
Args:
soappy_service: SOAPpy.WSDL.Proxy The SOAPpy service object encapsulating
the information stored in the WSDL.
ns: string The namespace the given WSDL-defined type ... | 794f74502b5db305f51bd560b388c64d305cd4e2 | 3,640,467 |
def read_binary_stl(filename):
"""Reads a 3D triangular mesh from an STL file (binary format).
:param filename: path of the stl file
:type filename: str
:return: The vertices, normals and index array of the mesh
:rtype: Mesh
:raises: ValueError
"""
with open(filename, 'rb') as stl_file:... | 53ae2a1806413280719286813e091392d965ce76 | 3,640,468 |
def monotonise_tree(tree, n_feats, incr_feats, decr_feats):
"""Helper to turn a tree into as set of rules
"""
PLUS = 0
MINUS = 1
mt_feats = np.asarray(list(incr_feats) + list(decr_feats))
def traverse_nodes(node_id=0,
operator=None,
threshold=None,
... | 78405b1d2bf5c2617b248210058caca0b062b668 | 3,640,469 |
import pickle
def pythonify_and_pickle(file, out_filename):
"""Convert all the data in the XML file and save as pickled files for
nodes, ways, relations and tags separately.
:param file: Filename (the file will be opened 4 times, so passing a file
object will not work). Can be anything which :... | 4140c9e66b9a43b6880b152c50facf89ba723339 | 3,640,470 |
def compute_inverse_volatility_weights(df: pd.DataFrame) -> pd.Series:
"""
Calculate inverse volatility relative weights.
:param df: cols contain log returns
:return: series of weights
"""
dbg.dassert_isinstance(df, pd.DataFrame)
dbg.dassert(not df.columns.has_duplicates)
# Compute inve... | 347343729dc271dd161f419a394151b99f1ce876 | 3,640,471 |
def resattnet164(**kwargs):
"""
ResAttNet-164 model from 'Residual Attention Network for Image Classification,' https://arxiv.org/abs/1704.06904.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/model... | 35023591d70a577526280489c19f47fffb0800a2 | 3,640,472 |
def stype(obj):
"""
Return string shape representation of structured objects.
>>> import numpy as np
>>> a = np.zeros((3,4), dtype='uint8')
>>> b = np.zeros((1,2), dtype='float32')
>>> stype(a)
'<ndarray> 3x4:uint8'
>>> stype(b)
'<ndarray> 1x2:float32'
>>> stype([a, (b, b)])
... | 76b805684361a13f03955692dacd02c045c43bd9 | 3,640,473 |
def board2key(Z):
""" Turn a "Game of Life" board into a key.
"""
return(bin2hex(array2string(Z[1:-1, 1:-1].reshape((1, 512 * 512 * 4))[0]))) | 101b4ecdf03e9a9a832434d59e2eaa9a6bed2ef5 | 3,640,474 |
def CipherArray(Array = [[" "]," "], Random = 1):
"""
Array - array to coding
Key - Key number to coding
It's а function that encodes elements
Returns an array consisting of coded elements
"""
if (type(Array) != list):
raise TypeError("Неправильний формат масиву")
if (type(Random... | a2d472cd49a803a4a08f0fba5362b54cce24c37a | 3,640,475 |
def voltage(raw_value, v_min=0, v_max=10, res=32760, gain=1):
"""Converts a raw value to a voltage measurement.
``V = raw_value / res * (v_max - v_min) * gain``
"""
return (float(raw_value) / res * (v_max - v_min) * gain, "V") | b4ea7d2521e1fa856a21b98ace2a9490f8a3b043 | 3,640,476 |
def extract_characteristics_from_string(species_string):
"""
Species are named for the SBML as species_name_dot_characteristic1_dot_characteristic2
So this transforms them into a set
Parameters:
species_string (str) = species string in MobsPy for SBML format (with _dot_ instead ... | abfcc0d3e425e8f43d776a02254a04b0e85dc6d1 | 3,640,477 |
def _get_bzr_version():
"""Looks up bzr version by calling bzr --version.
:raises: VcsError if bzr is not installed"""
try:
value, output, _ = run_shell_command('bzr --version',
shell=True,
us_env=True)
... | fb0171fe286e6251b25536dd40323c4af73a1255 | 3,640,478 |
def C(source):
"""Compile at runtime and run code in-line"""
return _embed_or_inline_c(source, True) | d1bd11370a1df3c93209b8d60046c077ac872d3e | 3,640,479 |
def normalize(x):
"""Standardize the original data set."""
max_x = np.max(x, axis=0)
min_x = np.min(x, axis=0)
x = (x-min_x) / (max_x-min_x)
return x | eba8ff32dca072b134c689d727e0246d7563a95d | 3,640,480 |
def _diff_bearings(bearings, bearing_thresh=40):
"""
Identify kinked nodes (nodes that change direction of an edge) by diffing
Args:
bearings (list(tuple)): containing (start_node, end_node, bearing)
bearing_thresh (int): threshold for identifying kinked nodes (range 0, 360)
Returns:
... | a29c3cdd009065d7a73dd993ae66f81853d5e2bc | 3,640,481 |
from typing import Any
import json
import aiohttp
import re
async def request(method: str,
url: str,
params: dict = None,
data: Any = None,
credential: Credential = None,
no_csrf: bool = False,
json_body: bool ... | 68b68df293f474ecfff5fdd7ae93f0431d700d50 | 3,640,482 |
def InflRate():
"""Inflation rate"""
return asmp.InflRate() | 33fcaa24cc00875e059850574469a95bcab3b469 | 3,640,483 |
def author_single_view(request, slug):
"""
Render Single User
:param request:
:param slug:
:return:
"""
author = get_object_or_404(Profile, slug=slug)
author_forum_list = Forum.objects.filter(forum_author=author.id).order_by("-is_created")[:10]
author_comments = Comment.objects.filte... | 506ec5f980d5ee59809358ac2add7cfcd0327a60 | 3,640,484 |
def get_predefined(schedule):
"""
Predefined learn rate changes at specified epochs
:param schedule: dictionary that maps epochs to to learn rate values.
"""
def update(lr, epoch):
if epoch in schedule:
return floatX(schedule[epoch])
else:
return floatX(lr)
... | 5cb9fab3bb3b4b4d868504953d78e3f93f5a7198 | 3,640,485 |
def launch_ec2_instances(config, nb=1):
"""
Launch new ec2 instance(s)
"""
conf = config[AWS_CONFIG_SECTION]
ami_image_id = conf.get(AMI_IMAGE_ID_FIELD)
ami_name = conf.get(AMI_IMAGE_NAME_FIELD)
if ami_image_id and ami_name:
raise ValueError('The fields ami_image_id and ami_image_nam... | 27b3aa745021f3a1516b09746db1c8111b8905d2 | 3,640,486 |
def residual_error(X_train,X_test,y_train,y_test, reg="linear"):
"""
Plot the residual error of the Regresssion model for the input data,
and return the fitted Regression model.
-------------------------------------------------------------------
# Parameters
# X_train,X_test,y_train,y_test (np.arrays): G... | 38513473122ff1430f6f6cf44eb984086bcdda72 | 3,640,487 |
def centerSquare(pil_img: Image.Image):
"""Adds padding on both sides to make an image square. (Centered)"""
pil_img = pil_img.convert('RGBA') # ensure transparency
background_color = (0, 0, 0, 0)
width, height = pil_img.size
if width == height:
return pil_img
elif width > height:
... | a991fa4a7a877334bba9e93126e4c8561c27e6f7 | 3,640,488 |
def _convert_steplist_to_string(step_data):
"""Converts list of step data into a single string.
Parameters
----------
step_data : list
List of step data
Returns
-------
str
A space delimited string where every 6th value is followed by a newline.
"""
text = ''
for i, datum in enumerate(step_data):
... | 112495edbafc3db39946d7abeefff6466e2dff94 | 3,640,489 |
from typing import Optional
def get_global_public_delegated_prefix(project: Optional[str] = None,
public_delegated_prefix: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetGlobalPublicDelegatedPrefixResult:
... | 7c48f4ccce1fb1640d3e3851d9e5481a9dd6a281 | 3,640,490 |
def has_conformer(molecule, check_two_dimension=False):
"""
Check if conformer exists for molecule. Return True or False
Parameters
----------
molecule
check_two_dimension: bool, optional. Default False
If True, will also check if conformation is a 2D conformation (all z coordinates are ... | fd0501a70f3ad002612be7d0625678ccc9f24dc9 | 3,640,491 |
def pad_sequence(yseqs, batch_first=False, padding_value=0):
"""Numpy implementation of torch.pad_sequence
Args:
yseqs (np.ndarray): List of array. (B, *)
batch_first (bool):
padding_value (int, optional): Padding value. Defaults to 0.
Returns:
np.ndarray
Examples:
... | 42fe65a15b39227a31b6022f8dae84cabd1888fb | 3,640,492 |
async def fetch_sequence_id(session: _session.Session) -> int:
"""Fetch sequence ID."""
params = {
"limit": 0,
"tags": ["INBOX"],
"before": None,
"includeDeliveryReceipts": False,
"includeSeqID": True,
}
log.debug("Fetching MQTT sequence ID")
# Same doc id as ... | f7fee50e13002ffa02110358c21a1d8794008f30 | 3,640,493 |
import sys
def main(args=None):
"""
Processes command line parameters into options and files, then checks
or update FITS DATASUM and CHECKSUM keywords for the specified files.
"""
errors = 0
fits_files = handle_options(args or sys.argv[1:])
setup_logging()
for filename in fits_files:... | 563d7c7366e25932d42e6e01468b1db244faf64b | 3,640,494 |
import re
def parse_transceiver_dom_sensor(output_lines):
"""
@summary: Parse the list of transceiver from DB table TRANSCEIVER_DOM_SENSOR content
@param output_lines: DB table TRANSCEIVER_DOM_SENSOR content output by 'redis' command
@return: Return parsed transceivers in a list
"""
result = [... | 367d6a744add04e7649c971ef8fec3788ed8db88 | 3,640,495 |
import math
def superimposition_matrix(
v0: np.ndarray,
v1: np.ndarray,
scaling: bool = False,
usesvd: bool = True
) -> np.ndarray:
"""
Return matrix to transform given vector set into second vector set.
Args:
----
v0: shape (3, *) or (4, *) arrays of at least 3 vectors.
... | a83fb9532a59cffdd986c364825c32fa682a45dc | 3,640,496 |
def get_graph_metadata(graph_id: int):
"""Returns the metadata for a single graph. This is automatically generated
by the datasource classes.
Parameters
----------
graph_id : int
Graph ID.
Returns 404 if the graph ID is not found
Returns
-------
Dict
A dictionary r... | a3eb61fcaf901d8caa47da345a8279e4e7058a84 | 3,640,497 |
def username_exists(username, original=""):
"""Returns true if the given username exists."""
return username != original and User.objects.filter(username=username).count() > 0 | 16f9a53922d0141459327e79aba5678af9446536 | 3,640,498 |
def set_n_jobs(n_jobs: int, x_df: pd.DataFrame) -> int:
"""
Sets the number of n_jobs, processes to run in parallel. If n_jobs is not specified, the max number of CPUs is
used. If n_jobs is set to a higher amount than the number of observations in x_df, n_jobs is rebalanced to match
the length of x_df.
... | e081f0f2ee6ceeac7587cb362c62ffef0a114a56 | 3,640,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.