content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def solution(A): # O(NlogN)
"""
Sort numbers in list A using quick sort.
>>> solution([5, 2, 2, 4, 1, 3, 7, 9])
[1, 2, 2, 3, 4, 5, 7, 9]
>>> solution([2, 4, 6, 2, 0, 8])
[0, 2, 2, 4, 6, 8]
>>> solution([1, 3, 5, 7, 3, 9, 1, 5])
[1, 1, 3... | a61534397ceac27acb9714a299ef9900f5ab5144 | 3,621,600 |
import tokenize
def build_model():
"""
Builds pipeline and use grid search to perform multioutputclassification
Returns:
cv: GridSearchCV pipeline with best parameters for the model
"""
pipeline = Pipeline([
('vect', CountVectorizer(tokenizer=tokenize)),
('tfidf', TfidfT... | 9955f753335d71c8e36aa2a7c6ddf372afae6659 | 3,621,601 |
def func_split_token(str_token):
"""
Splits a VCF info token while guarenteeing 2 tokens
* str_token : String token to split at '='
: String
* return : List of 2 strings
"""
if str_token:
lstr_pieces = str_token.split("=")
i_pieces = len(lstr_pieces)
if i_... | 581b7729ab8dba6f3032b6f1f3bf9bc7dd17c67e | 3,621,602 |
import os
def _discover_test_files():
"""Discover a list of files to run smoke tests on.
This is generally every file that came with the cmake distribution
"""
# List of files we will be testing against
test_files = []
# These files are templates and invalid cmake code
exclude_files = ["... | 59d13a6a805d9c0597c6a7682a00dff539db4c1c | 3,621,603 |
from typing import Union
def _add_descriptor_labels(
rdm: rsatoolbox.rdm.RDMs,
pattern_descriptor: str,
icon_method: str,
axis: Union[matplotlib.axis.XAxis, matplotlib.axis.YAxis],
num_pattern_groups: int = None,
icon_spacing: float = 1.0,
linewidth: float = 0.5,
horizontalalignment: s... | 1779b1e3a2aa79b7b0ef5560322d58fb78085e9a | 3,621,604 |
def _parse_example_proto(example_serialized):
"""Parses an Example proto containing a training example of an image.
The output of the build_image_data.py image preprocessing script is a dataset
containing serialized Example protocol buffers. Each Example proto contains
the following fields (values are ... | f2e41dc9c5a59ee3bde0f580c512ae639c304425 | 3,621,605 |
from pathlib import Path
import os
import logging
def fried(dataset_dir: Path) -> bool:
"""
fried x train dataset (32614, 10)
fried y train dataset (32614, 1)
fried x test dataset (8154, 10)
fried y train dataset (8154, 1)
"""
dataset_name = 'fried'
os.makedirs(dataset_dir, exist_ok... | 69a5da1c25d4469cd5669755490819d685a83444 | 3,621,606 |
def params_to_state(
class_name,
name,
handler=None,
graph_shape=None,
function=None,
full_event=None,
class_args=None,
):
"""return state object from provided params or classes/objects"""
if class_name and hasattr(class_name, "to_dict"):
struct = class_name.to_dict()
... | 8f1f23cdac2d462b70625fe5f321873d1179153e | 3,621,607 |
def parse_wps_server_info(root, namespaces, provider, passed_url):
"""
Parses the xml file provided by the wps server.
Searches for the information about the WPS server.
Returns a new object of the class WPS
@param root: root Element of the Element tree
@type root: ElementTree.Element
@para... | 425007d5de517c70a93e3c3a93e1ffc967d1f063 | 3,621,608 |
def resnet101(pretrained=True, **kwargs):
"""Constructs a ResNet-101 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['resnet101'... | 1073c8104c7f3064bbf4a180f03153e82ccaf314 | 3,621,609 |
def fraction_input(x,y):
""" Takes two inputs and returns it as a fraction
Parameters
___________
:param x: int/float: a number
:param y: int/float: a number
Returns
___________
:return: Returns the fraction
"""
# Try creating a Fraction using the two numbers inputted
... | 9b8be454352a253085291bef34ab7858ef176136 | 3,621,610 |
def format_datetime(obj, constant_hour=False, hour=("00", "00")):
"""Will format a datetime object into a string."""
if not constant_hour:
return "{}{}{}{}{}".format(
obj.year,
"{:02d}".format(obj.month),
"{:02d}".format(obj.day),
"{:02d}".format(obj.hour)... | 0d8d3d35e9ad3168a0e264f6b4e77248406bf7c6 | 3,621,611 |
def select_modalities(combs, modalities_flag):
"""
:param combs: example [[1, 1, 1], [1, 1, 0], [0, 1, 1], [1, 0, 1], [1, 0, 0], [0, 1, 0], [0, 0, 1]]
:param modalities_flag: e.g [1,1,0]
:return: e.g [ [1, 1, 0], [1, 0, 0], [0, 1, 0]]
"""
combs = [[a * b for a, b in zip(c, modalities_flag)] fo... | 3942423468fc8f29a4d135d0503a59472e1a0943 | 3,621,612 |
def test_component_inherited_factory_value():
"""https://github.com/larq/zookeeper/issues/123."""
@factory
class IntFactory:
def build(self) -> int:
return 5
@component
class Child:
x: int = ComponentField()
@component
class Parent:
child: Child = Compo... | 40cbb10c967095c87f8a85e55b4c80c10287ba37 | 3,621,613 |
def GuessVCS(options, path, file_list):
"""Helper to guess the version control system.
NOTE: Very similar to upload.GuessVCS. Doesn't look for hg since we don't
support it yet.
This examines the path directory, guesses which SCM we're using, and
returns an instance of the appropriate class. Exit with an er... | aff738ad9a55cd68efd12db58a613a0832dd94e7 | 3,621,614 |
def tactic_application_to_string(t_app: deephol_pb2.TacticApplication) -> Text:
"""Generate tactic strings.
Args:
t_app: TacticApplication proto
Returns:
tactic string; to be parsed by third_party/hol_light/parse_tactic.ml
Raises:
ProofFailedError: When invariants of the tactic application are no... | 14c39b09adf90a5da6cfe5f0f53a6506ec7ed884 | 3,621,615 |
import collections
def accumulatable_wer_stats(refs, hyps, stats=collections.Counter()):
"""Computes word error rate and the related counts for a batch.
Can also be used to accumulate the counts over many batches, by passing
the output back to the function in the call for the next batch.
Arguments
... | 6d2b698ae162abcda8c120ae5bd3408a074d1874 | 3,621,616 |
def waterfall(stack, profile, yaxis="rel_time", cmap="inferno", ax=None, **kwargs):
"""_summary_
Parameters
----------
stack : _type_
_description_
profile : _type_
_description_
yaxis : str, optional
_description_, by default "rel_time"
cmap : str, optional
... | f0dc359a53d67e36d2dcd132fc786fd2cc0e7c41 | 3,621,617 |
import urllib
import json
def parse_sport_parionssport(sport):
"""
Get ParionsSport odds from sport
"""
sports_alias = {
"football" : "FOOT",
"basketball" : "BASK",
"tennis" : "TENN",
"handball" : "HAND",
"rugby" :... | 725e63405d6259d150e7b8581018dd521e19822e | 3,621,618 |
def conf_to_ccs(conformers, infodf):
"""Converts list of conformer indexes (from a 50x50 matrix) to Boltzmann weighted CCS average and Lowest Energy CCS.
Args:
conformers (np.array): Array of conformer indexes selected from a 50x50 rmsd matrix as returned in the
SDS() datafra... | a403b167b22153805665b99fb5f29cd198177b35 | 3,621,619 |
from typing import List
def list_datasets() -> List[str]:
"""Returns list of available datasets names
Returns:
List[str]: list of dataset names as string
>>> import src
>>> src.list_datasets()
['emodb']
"""
return sorted(__dataset_mapper__.keys()) | 502dbeb3b61ee6887ad9d8bb4180cad7aff310f0 | 3,621,620 |
from typing import Optional
def get_nat_address(instance_id: Optional[str] = None,
nat_address_id: Optional[str] = None,
organization_id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetNatAddressResult:
"""
Gets the... | 1a8665a6a977ea7d4a65c6fb60459685d40506e6 | 3,621,621 |
import os
import csv
def grab_q_values(fname):
"""Parses data from three q_val csv files.
Parameters
----------
fname : str
Name of q_value file.
"""
# Create list
all_q_values = []
# Open .csv files and parses them
with open(os.path.join(os.path.dirname(__file__), fname... | ea1a7b55b0dd47fdb3a117e09df3c9aa8b30bf12 | 3,621,622 |
def make_replaced_box(element, box, image):
"""Wrap an image in a replaced box.
That box is either block-level or inline-level, depending on what the
element should be.
"""
if box.style['display'] in ('block', 'list-item', 'table'):
type_ = boxes.BlockReplacedBox
else:
# TODO: ... | f8545b98070dac67cd8c8ef53336190886294fa1 | 3,621,623 |
def roc(values, period):
"""
ROC ใ่จ็ฎใใใฎใงใใ
* values: ่ชฟๆดๅพ็ตๅคใๆๅฎใใใฎใงใใ
* period: ๆ้ใชใฎใงใใ
* return: ็ตๅคใใผในใฎ ROC ใ่ฟใใฎใงใใ
"""
_values = DataFrame(values)
pasts = _values.shift(period)
return (_values - pasts) / _values | 6332a65f147626675e2c75ab09081f05873cf40b | 3,621,624 |
def compute_density(start, end, length, time_unit='us'):
"""
Computes a grid density given the edges and number of samples.
Handles datetime grids correctly by computing timedeltas and
computing a density for the given time_unit.
"""
if isinstance(start, int): start = float(start)
if isinsta... | 821c984b2787d91f6af475da1e974e5262eab129 | 3,621,625 |
def intersection_pt(triangle_left, triangle_right):
""" get intersection point of two output triangles"""
a, b, c = triangle_left[0], triangle_left[1], triangle_left[2]
d, e, f = triangle_right[0], triangle_right[1], triangle_right[2]
x = (c * (b - c) - d * (e - d)) / (b - c - e + d)
y = (e - d) * (... | 051137af7eaa57edae25ff814593deb1a134ea14 | 3,621,626 |
def pitch(freq):
"""finds the closest pitch to the frequency freq"""
return _ftop[closest(_fs, freq)] | cbcc64605ce4c74a0f39a8db37bbdf9f946a431c | 3,621,627 |
import math
def algorithm(feature):
"""
Content-Based Algorithm+
๊ธฐ์กด์ Content-Based์์ Youflix ์์คํ
์ ์ํด ํ๋์ด ๋ ์๊ณ ๋ฆฌ์ฆ ์
๋๋ค.
์ฌ์ฉ์๊ฐ ํ๊ฐํ ๊ฒฐ๊ณผ๋ฅผ ํ ๋๋ก ๋ ๋์ ์ ์๋ฅผ ๋ฐ์ ์ํ๋ ๊ฐ์ค์น๋ฅผ ๋๊ฒ์ค์
๋น์ทํ ์ํ๊ฐ ๋ง์ด ์ถ์ฒ ๋๋๋ก ํ๊ณ , ๋ฐ๋๋ก ๋ฎ์ ์ ์์ ์ํ์ ์ ์ฌํ ์ํ๋
์ถ์ฒ๋์ง ์๋๋ก ํ์ฌ ์ฌ์ฉ์์๊ฒ ์๋ฏธ์๋ ๊ฒฐ๊ณผ๋ฅผ ๋ด๋๋ก ํ์์ต๋๋ค.
์ถ๊ฐ์ ์ผ๋ก ์ํ๊ฐ๋
์ด๋ ์ํ๋ฐฐ์ฐ๋ค์ ๊ธฐ... | d62bcc2c9a60525b9ddfe8a0615503e8be31c9af | 3,621,628 |
def get_volume_page_score_for_input_fields(result_record, hypothesis):
"""
:param result_record:
:param hypothesis:
:return:
"""
input_fields = hypothesis.get_detail('input_fields')
evidences = Evidences()
exist = bool('volume' in input_fields) + bool('page' in input_fields)
ads_... | 4f18544a46754ff4abeb39c556672f3998ec9cb1 | 3,621,629 |
def array_to_dist_graph(point_set, point_weight=1, metric='sqeuclidean'):
"""take a set of points P and create the complete graph with vertex set P and weights equal to the distance between pairs"""
link_idx = triu_indices(len(point_set), k=1)
g = nx.Graph(data=list(zip(link_idx[0],
... | 9802cba1ae75e239e75cdfde306e03b1b7646a3f | 3,621,630 |
import torch
def adaptive_scaling_loss(logits: Tensor, targets: Tensor, positive_idx: Tensor,
mask: Tensor = None, beta: float = 1.0, reduction='none',
weight_trainable: bool = False):
"""
:param logits: (batch, num_label)
:param targets: (batch, )
... | 214362eba1b32c996b079ff66a830f4de8386d90 | 3,621,631 |
def get_ir_exon_transcript(tx_data, introns):
"""
List exons and transcriptts that contain Intron Retention events where an intron is encompassed
by an exon. Also return intron coords for flagging IR EFs.
"""
ir_exon_list = []
ir_transcript_list = []
for e_tx in tx_data:
e_ints = [(i... | d0811390be08ec75f1a5f4221b6873e70fc564c0 | 3,621,632 |
def mp_wms_130_nometadata(monkeypatch):
"""Monkeypatch the call to the remote GetCapabilities request of WMS
version 1.3.0, not containing MetadataURLs.
Parameters
----------
monkeypatch : pytest.fixture
PyTest monkeypatch fixture.
"""
def read(*args, **kwargs):
with open('... | 6556af96fbb4c14ed1a1db44c8940470f0378b34 | 3,621,633 |
from Acquire.Service import start_profile, end_profile
def _handle(ctx=None, function=None, additional_function=None, args=None):
"""This function routes calls to sub-functions, thereby allowing
a single identity function to stay hot for longer. If you want
to add additional functions then add them ... | d2cce59835273eddb4ab9ef4af7ad948e53c8b91 | 3,621,634 |
import torch
def _learn(x, logw, loss, optim_kwargs, schedule_kwargs, n_steps, init_x, optim_class_name='Adam',
scheduler_class_name='StepLR'):
"""
Combine solve_for_state and transport_from_potentials in a "reweighting scheme"
:param x: torch.Tensor[N, D]
The input
:param w: torch.... | 68e2922c6a3ec595a0c9a682cb819567a975f272 | 3,621,635 |
from typing import Sequence
from typing import cast
async def create_tcp_message_payload_connection(
queue: "Queue[bytes]",
loop: AbstractEventLoop | None,
readers: Sequence[MeterReaderBase] | None,
*args,
**kwargs,
) -> MeterTransportProtocol:
"""
Create TCP connection using SmartMeterMes... | f0e5a3dc857cb7278f062e6bb5150c9e0c073cc8 | 3,621,636 |
import numpy
def _numpy_repr(array, prefix="", suffix=""):
"""Wrapper for showing Numpy array in custom class"""
max_line_width = numpy.get_printoptions()["linewidth"]
array_str = numpy.array2string(
array,
separator=", ",
prefix=prefix,
suffix="," if suffix else None,
... | e0edcf8eadceadccbf9f615c3e685ea40126764f | 3,621,637 |
def parse_collect_msg(orig_msg):
"""
Parse "collect" message received from backend
"""
# collect response and message have the same message format
return parse_message_msg(orig_msg) | b998102967e907d12b0aab14ede92ca71fa7e9e6 | 3,621,638 |
from typing import Iterator
from pathlib import Path
import tqdm
def read_chessboards(images: Iterator[Path]):
"""
Charuco base pose estimation.
"""
logger.info("Pose Estimation Starts:")
allCorners = []
allIds = []
decimator = 0
# SUB PIXEL CORNER DETECTION CRITERION
criteria = (c... | 7c5316e24f4a6c52d60cd424856a0787b1e95a83 | 3,621,639 |
def populate_sd_dict(herbivore_list):
"""Create and populate the stocking density dictionary, giving the stocking
density of each herbivore type."""
stocking_density_dict = {}
for herb_class in herbivore_list:
stocking_density_dict[herb_class.label] = herb_class.stocking_density
return stoc... | 87a0b9375a5a419557443506522ab2cf8d34c308 | 3,621,640 |
def timeInForce() -> str:
"""TODO: Add description."""
return 'GTC' | 3e9cb4d5da2a86c9fef57804ed807211e8f30c82 | 3,621,641 |
from rfpipe import source
def read_segment(st, segment, cfile, vys_timeout):
""" Wrapper for source.read_segment that secedes from worker
thread pool
"""
logger.info("Reading datasetId {0}, segment {1} locally."
.format(st.metadata.scanId, segment))
with distributed.worker_clien... | 2be4453f349ba180fe53339b3d382cfd27161277 | 3,621,642 |
def require_self(f):
"""Require the logged-in user to be the user that is currently being edited"""
@wraps(f)
def fn(*args, **kwargs):
try:
username = kwargs["username"]
except KeyError:
abort(
500,
"The require_self decorator only wor... | e1b48c6b4f80d2ba6293dda6dc7aa5f334fdb28e | 3,621,643 |
def _estimate_score_file_format(filename, ncolumns=None):
"""Estimates the score file format from the given score file.
If ``ncolumns`` is in ``(4,5)``, then ``ncolumns`` is returned instead.
"""
if ncolumns in (4, 5):
return ncolumns
f = open_file(filename, "rb")
try:
line = f.... | fae8d90e3e1ba8cc1009d80c3b289bb8d3f56983 | 3,621,644 |
def spec_chain_zero_truncated(chain, ln_proba=None, ar=None):
"""
Return the Markov chain with the dimension: walkers x steps* x parameters,
where steps* is the last step before having 0 (not yet constructed chain).
Parameters
----------
chain: numpy.array
The MCMC chain.
ln_pro... | 348a0e42845b8a9ab384708fdc464f856f3a4c85 | 3,621,645 |
def precision_recall_f1(y, y_pred, average='macro'):
"""
average: str {'macro', 'micro'}
"""
cm = confusion_matrix(y, y_pred)
if y.ndim == 1: # binary classification
pr = (cm.diagonal()/cm.sum(axis=0))[1]
rc = (cm.diagonal()/cm.sum(axis=1))[1]
f1 = 2*pr*rc / (pr+rc)
... | a342c5e0e1d1e14c598c64a54da968ded4c00c4d | 3,621,646 |
from typing import List
import pathlib
def get_files(
catalog: str, recursive: bool, suffix_markup: str, extension: str
) -> List[str]:
"""
ะัััะตััะฒะปัะตั ะฟะพะธัะบ ะฒ ะบะฐัะฐะปะพะณะต ะธ ะฒัะดะฐะตั ัะฟะธัะพะบ ะฟััะตะน ะฝะฐะนะดะตะฝะฝัั
ัะฐะนะปะพะฒ.
ะะพ-ัะผะพะปัะฐะฝะธั, recursive = False, ะธัะตั ัะฐะนะปั ัะพะปัะบะพ ะฒ ะบะฐัะฐะปะพะณะต.
extension ะธ suffix_marku... | 99f6d591b0548aafb654d05b94271a6d9ae243b6 | 3,621,647 |
def CppTypedefString(scope, type_defn):
"""Gets the representation of a type when used in a C++ typedef.
Args:
scope: a Definition for the scope in which the expression will be written.
type_defn: a Definition for the type.
Returns:
a (string, boolean) pair, the first element being the representatio... | 693d4fa235d970769a1bf1eb3ae1a2d1dc3cc11d | 3,621,648 |
import collections
def get_acl(device, acl_name, seq_number):
"""Retrieves ACL configuration
Args:
device (Device): This is the device object of an NX-API enabled device
using the Device class from pycsco
acl_name (str): Case-sensitive name of the ACL
seq_number (str): Num... | 2f53d6340ae76c2b6a4899be770fc84055d7d19c | 3,621,649 |
def output_tensor(interpreter):
"""Returns dequantized output tensor."""
output_details = interpreter.get_output_details()[0]
output_data = np.squeeze(interpreter.tensor(output_details['index'])())
scale, zero_point = output_details['quantization']
return scale * (output_data - zero_point) | c2ac664328307f2722842a1ff0a49fa604e29ac3 | 3,621,650 |
import argparse
import logging
import os
def arg_parse_params(params):
"""
SEE: https://docs.python.org/3/library/argparse.html
:return dict:
"""
parser = argparse.ArgumentParser()
parser.add_argument(
'-imgs',
'--path_images',
type=str,
required=False,
... | 58775f599174a1428b52ed256a922afac30b6b29 | 3,621,651 |
from pathlib import Path
def normalize_features(feature: np.ndarray, variable: str) -> np.ndarray:
"""Normalize features using global pre-computed statistics.
Parameters
----------
feature : np.ndarray
Data to normalize
variable : str
One of ['inputs', 'output'], where `inputs` me... | 61efd55545e321dfc755059b70fc8bae064132ca | 3,621,652 |
def lonlat2xyz(lon,lat,r=1):
""" """
x = r*np.cos(lon*c)*np.cos(lat*c)
y = r*np.sin(lon*c)*np.cos(lat*c)
z = r*np.sin(lat*c)
return x,y,z | 3ca8b879256a35593bb0b4ff2c23961183c62aad | 3,621,653 |
def train_switcher(**params):
"""
function to call the correct train function depending on the dataset. s.t.
parallel training easily works altough different fuctions need to be called
:param params: all params needed by the train function, as passed by
parallel_training
:return: functio... | 1caa78fbb9bea335225b6c34fc9efaa8b980515a | 3,621,654 |
import dateutil
def debugobsolete(ui, repo, precursor=None, *successors, **opts):
"""create arbitrary obsolete marker
With no arguments, displays the list of obsolescence markers."""
opts = pycompat.byteskwargs(opts)
def parsenodeid(s):
try:
# We do not use revsingle/revrange fu... | be5535026ea10c977022c7ae2dbe7cd0f146267a | 3,621,655 |
def get_stock_price(symbol, start, end):
"""get stock price of a company over a time range
Args:
symbol (str): ticker symbol of a stock
start (datetime.datetime): start time
end (datetime.datetime): end time
Returns:
pd.DataFrame: stock price of a company over a time range
... | 69f7150cb1c266360ab4e6a5175b5453f35a0618 | 3,621,656 |
import socket
def ip6_from_bytes(data: bytes) -> str:
"""Converts ip4 address from bytes to string representation.
Keyword arguments:
data -- address bytes to convert
"""
return socket.inet_ntop(socket.AF_INET6, data) | 694384d872b6fe27baa3fd97cba9dbfa7c35f8a9 | 3,621,657 |
import typing
def unletterbox(image) -> typing.Optional[
typing.Tuple[typing.Tuple[int, int], typing.Tuple[int, int]]]:
"""Return bounds of non-trivial region of image or None.
Unletterboxing is cropping an image such that trivial edge regions
are removed. Trivial in this context means that the m... | cb0813dd52e0edd9a94ad72f831c8b6fc976335d | 3,621,658 |
def hash_side_effect(value):
"""Side effect value."""
if "mail_none.gif" in value:
return "633d7356947eec543c50b76a1852f92427f4dca9"
else:
return "133d7356947fec542c50b76b1856f92427f5dca9" | cc791ad289b4a198a0e66916467aae6c015f5676 | 3,621,659 |
def cbow_context(source, window, empty, name=None):
"""Generates `Continuous bag-of-words` contexts for inference from batched list of tokens.
Args:
source: `2-D` string `Tensor` or `RaggedTensor`, batched lists of tokens [sentences, tokens].
window: `int`, size of context before and after targ... | 017bcf470956011dc0d002c58f8f0548f00ecb0a | 3,621,660 |
def CombineParallelDense(min_num_branches=3):
"""Combine multiple dense operators into one. For example:
data
/ \
dense (2,2) dense (2,2)
| |
elemwise/bcast (2,2) elemwise/bcast (2,2)
Would become:
data
... | a77c2f25a99839269ef6e5cd52cb19bb24e3398f | 3,621,661 |
def layer_norm__ncnn(ctx, *args):
"""Register default symbolic function for `layer_norm`.
Add support to layer_norm to ONNX.
"""
return layer_norm(*args) | 23cdae45587c43d6ee57f3148fc36012bd0fe48e | 3,621,662 |
def new_locale(language: str = None, country: str = None, variant: str = None,
use_locale_module: bool = False) -> Locale:
"""
Instantiates a new Locale
:param language: The language code
:type language: str
:param country: The country code
:type country: str
:param variant: T... | cd85965284404084ac73e445467504853b6e881b | 3,621,663 |
def plot_variance_explained(model, bar_kwargs=None, ax=None):
"""
Parameters
----------
model : ``sklearn.decomposition.PCA``
The fitted model.
bar_kwargs : dict-like, optional
Additional keyword arguments passed through to ``ax.bar()``.
ax : axes, optional
The axes on ... | 99082357bc288fa591123c6244bd450b287dee03 | 3,621,664 |
from typing import Optional
import json
import urllib
def get_latest_news_metadata(local: Optional[bool] = False):
"""
Get latest news metadata file from S3 bucket
"""
if local:
with open(LOCAL_NEWS, 'rb') as f:
news = json.loads(f.read().decode('utf-8'))
# {"datetime":... | 2fd562c90b40b00c593b5feb46a2cb249cf47f21 | 3,621,665 |
from typing import Tuple
def get_direction(ch: str) -> Tuple[int, int]:
"""Coordinates point for direction
Args:
ch: str - direction as a single letter UDLR or NEWS
Returns:
tuple (x, y) - direction coordinates.
E.g.:
N -> (0, 1) # north
S -> (0, -1) # s... | 763b973f62f0fc4606fb9b504f93a3afc604e608 | 3,621,666 |
import tqdm
def run_batched_rollout(num_episodes, batched_env, agent):
"""
This function will generate a series of rollouts in a batched manner.
"""
num_envs = batched_env.num_envs
# This part can be left as is
observations = batched_env.batch_reset()
rewards = [0.0 for _ in range(num_en... | 7356a27dcd75e555727384afeba1c4425cf15fea | 3,621,667 |
import torch
def model_params_stats(model, param_dims=None):
"""Returns the model sparsity, weights count, and the count of weights in the sparse model.
Returns:
model_sparsity - the model weights sparsity (in percent)
params_cnt - the number of weights in the entire model (incl. zeros)
... | 567454901c506f67dd6171bfce344db694a9467b | 3,621,668 |
from typing import Dict
from typing import Any
import json
def get_connect_dict() -> Dict[str, Any]:
"""Read in database connection settings and return values as a
dictionary.
"""
with open("config.json", "r") as config_file:
config_dict = json.load(config_file)
if "database" in config... | 4d292d02e959aa091e2124f9c10b0876417ffba9 | 3,621,669 |
def peak_transform_sd(data, tm):
"""
Using multiplier of standard-deviation.
data: N x L matrix, N profiles of length L
l = codon density signal profile sequence
tm = threshold multipler.
Returns individual profiles peak values (st) (Series object)
"""
N, L = data.shape
peak_mat... | d447d0affd268ec5cf6437347f1acd38661aee5a | 3,621,670 |
def unless(predicate, function, value):
"""Tests the final argument by passing it to the given predicate function. If
the predicate is not satisfied, the function will return the result of
calling the whenFalseFn function with the same argument. If the predicate
is satisfied, the argument is returned as... | 9a883fb57b99f5dbc4e8b357dfeb9b88682ef621 | 3,621,671 |
import logging
def getLogger():
"""Helper for retrieve the logger object
"""
return logging.getLogger(__name__) | 470424ea4b3f6b18225db6994b6b43439f2fd425 | 3,621,672 |
def pnchunk(darray, maxsize_4d=1000**2, sample_var="u", round_func=round, **kwargs):
""" Chunk `darray` in time while keeping each chunk's size roughly
around `maxsize_4d`. The default `maxsize_4d=1000**2` comes from
xarray's rule of thumb for chunking:
http://xarray.pydata.org/en/stable/dask.html#chun... | 770bc7465168d89bf85800e01d1fcbb8fa0af663 | 3,621,673 |
import logging
def _create_fn(name, local_params: list[str] = [], lines: list[str] = ['pass'], globals: dict = {}):
"""
This function receives a name for the function, and returns a
function with the given locals and globals
"""
lines_as_str = '\n ' + '\n '.join(lines)
fn_text = f'def {... | c774d89ed43478ff1a4b71dab5127a58b8a7b88e | 3,621,674 |
def _RecursiveAssembleBD(disk, owner, as_primary):
"""Activate a block device for an instance.
This is run on the primary and secondary nodes for an instance.
@note: this function is called recursively.
@type disk: L{objects.Disk}
@param disk: the disk we try to assemble
@type owner: str
@param owner: ... | ad393f5572a8565d01c4f0672297525ff9491d33 | 3,621,675 |
def reformat_raw_matrices(raw_matrix_files):
""" Convert txt format to sparse matrix format. Use csr format (compressed sparse row; triplet format).
:param raw_matrix_files: [txt] raw Hi-C matrices
"""
chr_raw_matrix_col_0 = np.array(raw_matrix_files[:, 0])
chr_raw_matrix_col_1 = np.array(raw_m... | 818f3cdb4596beb0bf7ab579efaa9a3820fe6708 | 3,621,676 |
def get_all_folder_ids(service, parent_id=None, drive_id=False):
"""
Returns the id of the destination folder name in Google Drive
"""
parent_ids = []
# build query string
if parent_id:
query = 'mimeType = \'application/vnd.google-apps.folder\'' \
f' and \'{parent_id}\' in pa... | 56f1ae373533efcf991572aab9816540620fd949 | 3,621,677 |
import math
def estimate_wrapped_gaussian_stddev(values, clip_lower, clip_upper):
"""Estimate the stddev of values assuming a wrapped normal distribution.
This function takes an input tensor `values` and estimates the sample standard
deviation of its values with the following assumptions:
1. The values are... | 58e3f1a476482f39168acca7ad4c83f8c184e257 | 3,621,678 |
import errno
def _convert_errno_parm(code_should_be):
""" Convert the code_should_be value to an integer
If code_should_be isn't an integer, then try to use
the code_should_be value as a errno "name" and extract
the errno value from the errno module.
"""
try:
code = int(code_should_be)... | 949c9f17539d885a0fc4a51f3358fc3695c42e22 | 3,621,679 |
import random
import math
def find_new_host(RAM, vCPU):
"""
Select a random host from list of 3 hosts with available RAM and CPU
Availability is checked with 200 percent over-commitment.
"""
hosts = current.db(current.db.host.status == 1).select()
hosts = hosts.as_list(True,False)
count =... | a125e09c88bef8659760e1dca3fd9ae392854f60 | 3,621,680 |
def unknownwordftb(word, loc, _lexicon):
"""Model 2 for French of the Stanford parser."""
sig = UNK
if ADVSUFFIX.search(word):
sig += "-ADV"
elif VERBSUFFIX.search(word):
sig += "-VB"
elif NOUNSUFFIX.search(word):
sig += "-NN"
if ADJSUFFIX.search(word):
sig += "-ADV"
if HASDIGIT.search(word):
sig += ... | 56a371ec67f16121a4ee286823c778b41c3e6e8b | 3,621,681 |
def patch_src_utils_logger_create_logger(mocker) -> MagicMock:
"""Patch the `src.utils.logger.create_logger` function."""
return mocker.patch("src.utils.logger.create_logger") | a855ce570f9a122c56304e7420368f3aa396ba15 | 3,621,682 |
import torch
def rectangleMesh(x_range=(0,1), y_range=(0,1), h=0.25):
"""
Input:
- x's range, (x_min, x_max)
- y's range, (y_min, y_max)
- h, mesh size, can be a tuple
Return the element matrix (NT, 3)
of the mesh a torch.meshgrid
"""
try:
hx, hy = h[0], h[1]
except:... | 3af1e2a514ff878b058830b63a2e53a96b2a9363 | 3,621,683 |
from typing import List
def group_notes_to_chords(notes: List[MidiNote], kernel=None) -> List[List[MidiNote]]:
"""
Groups the list of `MidiNote`s by time.
The return value maps time to a list of `MidiNote`s for that time.
"""
if kernel is None:
kernel = kernel_default
# Degenerate ca... | 6379402d1ea4e3b19f3a1c93b97423aa19ac6230 | 3,621,684 |
import getopt
import sys
import os
def parse_options():
"""Parses the command line options."""
try:
long_options = ["inputDataset=", "outputFile="]
opts, _ = getopt.getopt(sys.argv[1:], "d:o:", long_options)
except getopt.GetoptError as err:
print(str(err))
sys.exit(2)
... | 40cc252f9d0af90d7887aa5484d35371142ef541 | 3,621,685 |
def readVGIline(line,l1dic,l2dic,l3dic):
"""reads and interpretes one line of a VGI file."""
if line.startswith("{"):
#new level 1 heading
if level1 != "":
l2dic[level2] = l3dic
l1dic[level1] = l2dic
level1 = line.lstrip("{").rstrip("}\n")
level2 = ""
... | 597b87944785588d20ee77f369862f9c950036ff | 3,621,686 |
def garch_fit_and_predict(series, ticker, horizon=1, p=1, q=1, o=1, print_series_name=False):
#p=1,q=1, o=1
#series=returns_df['spy']
#horizon=1
"""
This function takes a series of returns, and get back the GJR-GARCH time series fit for the conditional volatility,
using one shock, and a t-stud... | 4ec226eec64c804be93e589919db4c92c89f7109 | 3,621,687 |
import re
def find_all_starts_regex(seq):
""" Find the starting index of all start codons in a lowercase seq """
regex_start = re.compile('atg')
# Find the indices of all start codons
starts = []
for match in regex_start.finditer(seq):
starts.append(match.start())
return tuple(starts... | 5dd16b36352bbf41005fdf008606e503a050a175 | 3,621,688 |
def get(isamAppliance, error_page, check_mode=False, force=False):
"""
Retrieving an error page
"""
return isamAppliance.invoke_get("Retrieving an error page", "{0}{1}".format(module_uri, error_page),
requires_modules=requires_modules, requires_version=requires_versio... | be2176a344273c0fceab446cbfcac651b6d02845 | 3,621,689 |
import unittest
import os
import sys
import time
def run_test(test_list, xml_report, timeout=60, verbosity=0):
"""
Runs a specific test suite or test case given with the fully qualified
test name and prints stdout.
Args:
test_list: This is the list of tests to run,filtered based on the
rege... | 8043f79fe432d351265741c992e26271c92322c4 | 3,621,690 |
def edit_category(category_id):
"""
Edit category for database.
Inject all existing data from the category document into the form.
"""
the_category = mongo.db.categories.find_one({"_id": ObjectId(category_id)})
return render_template('editcategory.html',
cate... | 691c78bea14fdf8e489a5f7cbb2cc3e7c653600b | 3,621,691 |
import sys
def import_transformer(module_name, trans_name):
"""This function needed, import a transformer for a given module and
appends it to the appropriate lists.
The code inside a module where a transformer is defined should be
standard Python code, which does not need any transformation... | 2ead7827cafdbc2c682ab529c4651384718cb27f | 3,621,692 |
def update_blurs(blur_o, blur_d, routing):
"""Signal when all the input fields are full (or at least visited?) and a routing option has been picked."""
if routing == 'slope':
c = 0
elif routing == 'balance':
c = 1
else:
c = 2
if (not blur_o) or (not blur_d):
return 0
... | 092ad87e42d682a1369dca41ddc1dab491bd7525 | 3,621,693 |
def index():
"""Basic home page."""
return render_template('hi.html') | f7d256c658f29d500388bfbb500c022511c8bb4f | 3,621,694 |
def create_tag_query(session, collection=None, document_ids=None, tag_buffer=TAG_BUFFER_SIZE):
"""
returns a query for tags with specified parameters
:param session: session to execute query on
:param collection: filter by collection
:param document_ids: filter by ids
:param tag_buffer: yield pe... | 8a85d058d357225d9ab430d563cd885b9167b962 | 3,621,695 |
def collect_go_info(target, ctx, semantics, ide_info, ide_info_file, output_groups):
"""Updates Go-specific output groups, returns false if not a recognized Go target."""
sources = []
generated = []
# currently there's no Go Skylark API, with the only exception being proto_library targets
if ctx.ru... | be019cb029e0b78584545f1a8ddf92e46d6783c3 | 3,621,696 |
def _add(x):
"""
Add all elements of a list.
:param x: List to sum
:return: Sum of all elements in the input list
"""
return sum(x) | 19d42b51dbd07a992f3256b8b0d69c1f4043fa89 | 3,621,697 |
import torch
def make_data_loader(dataset, batch_size=cfg.batch_size,
shuffle=True, sampler=None):
"""Make dataloader from dataset."""
data_loader = torch.utils.data.DataLoader(
dataset=dataset,
batch_size=batch_size,
shuffle=shuffle if sampler is None else False,
... | 8297d89c6e89b867dad34807e8584067cab3085e | 3,621,698 |
import math
def to_yaw_angle_quat(qxyzw):
"""
:param qxyzw: a list or numpy array
:return: a float angle [-pi, pi)
"""
qxyzw = qxyzw / np.linalg.norm(qxyzw)
if qxyzw[2] < 0:
theta = math.acos(-qxyzw[3])*2
else:
theta = math.acos(qxyzw[3])*2
if theta > math.pi:
theta -= 2*math.pi
return ... | 8f8a19edbb6bd2b8b95fddd52adfba31c265ce43 | 3,621,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.