content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def mark(symbol):
"""Wrap the symbol's result in a tuple where the first element is `symbol`.
Used where the information about "which branch of the grammar was used"
must be propagated upwards for further checks.
"""
def mark_action(x):
return (symbol, x)
return mark_action << symbol | 3180c96d4d2a68df2909f23a544879918016fb37 | 3,636,454 |
def restore_dimensions(array, from_dims, result_like, result_attrs=None):
"""
Restores a numpy array to a DataArray with similar dimensions to a reference
Data Array. This is meant to be the reverse of get_numpy_array.
Parameters
----------
array : ndarray
The numpy array from which to ... | 401015b3e33f17bb7e5be078270391efb0543bfa | 3,636,455 |
import collections
def _combine_qc_samples(samples):
"""Combine split QC analyses into single samples based on BAM files.
"""
by_bam = collections.defaultdict(list)
for data in [utils.to_single_data(x) for x in samples]:
batch = dd.get_batch(data) or dd.get_sample_name(data)
if not isi... | b9fb88f7fae9c6dda8f2435b8c7fcfab5ab15ad2 | 3,636,456 |
import re
def doc(
package_name: str,
plugin_name: str,
long_doc: bool = True,
include_details: bool = False,
) -> str:
"""Document one plug-in
Documentation is taken from the module doc-string. If the plug-in is not part of the
package an UnknownPluginError is raised.
Args:
... | a6c3a1c03936262815299657c6264f70be1e92ba | 3,636,458 |
def microsecond(dt):
""":yaql:property microsecond
Returns microseconds of given datetime.
:signature: datetime.microsecond
:returnType: integer
.. code::
yaql> datetime(2006, 11, 21, 16, 30, 2, 123).microsecond
123
"""
return dt.microsecond | 31d195fa4ceb468bb5666751e56b836fbec8f822 | 3,636,459 |
import math
def decompose_label_vector(label_vector, n_xgrids, n_ygrids, mean_lwh,
xlim=(0.0, 70.0), ylim=(-50.0,50.0), zlim=(-10.0,10.0),
conf_thres=0.5, nms=True, iou_thres=0.1):
""" Build the ground-truth label vector
given a set of poses, classe... | 0cf34bad28a5c8dc335110be95ace5e41d8fa534 | 3,636,460 |
def gen_delay_phs(fqs, ants, dly_rng=(-20, 20)):
"""
Produce a set of mock complex phasors corresponding to cables delays.
Args:
fqs (array-like): shape=(NFREQS,), GHz
the spectral frequencies of the bandpasses
ants (iterable):
the indices/names of the antennas
... | 3e9d2b6bab886c8d6b7b3ef5869d74cf21689e06 | 3,636,461 |
def what_to_add(qtype, origword, newword, terminate):
"""Return a qtype that is needed to finish a partial word.
For example, given an origword of '\"frog' and a newword of '\"frogston',
returns either:
terminate=False: 'ston'
terminate=True: 'ston\"'
This is useful when calculating tab... | c5b06aa1db322e0f6c6d041562ea3585482d789b | 3,636,463 |
def intersect(start1, end1, start2, end2):
"""Return the intersection point of two lines, else return None.
Ideas:
For parallel lines to intercept (equal slope and y-intercept),
they must be overlapping segments of the same infinite line.
Intersection point is given by solving line equation 1 = line... | cd5affbdc57d48783cf50f188b979ad24f117c37 | 3,636,464 |
def start(update, context):
"""Displays welcome message."""
# choose_lang = True
# If we're starting over we don't need do send a new message
if not context.user_data.get(START_OVER):
user = update.message.from_user
try:
context.user_data[LANG] = user.language_code
... | cbb8e0f49f35de1dbd0f47e71b114b2c22ed5ec0 | 3,636,465 |
def model_dir_str(model_dir, hidden_units, logits, processor=lambda: pc.IdentityProcessor(),
activation=tf.nn.relu, uuid=None):
"""Returns a string for the model directory describing the network.
Note that it only stores the information that describes the layout of the network - in partic... | 00ee6a98dfc1f614f335a187f3f998edc908e25d | 3,636,466 |
def validate_search_inputs(row_id, search_column, search_value):
"""Function that determines if row_id, search_column and search_value are defined correctly"""
return_value = {
"valid": True,
"msg": None
}
a_search_var_defined = True if search_column or search_value else False
if r... | ce85ce1b973beab6b0476dfc05edc594fac8c420 | 3,636,467 |
def B1(i,n,t):
"""Restituisce il polinomio di Bernstein (i,n) valutato in t,
usando la definizione binomiale"""
if i < 0 or i > n:
return 0
return binom(n,i)* t**i * (1-t)**(n-i) | ac97d943494e3b194d71de9ae1864633268499ec | 3,636,468 |
def get_text_between(text, before_text, after_text):
"""Return the substring of text between before_text and after_text."""
pos1 = text.find(before_text)
if pos1 != -1:
pos1 += len(before_text)
pos2 = text.find(after_text, pos1)
if pos2 != -1:
return text[pos1:pos2].strip... | 4ec7f1900881422599b05f64b1c8eec8c992452d | 3,636,469 |
def _get_functional_form_section(input_string):
""" grabs the section of text containing all of the job keywords
for functional form of PIPs
"""
pattern = (escape('$functional_form') + LINE_FILL + NEWLINE +
capturing(one_or_more(WILDCARD, greedy=False)) +
escape('$end')... | d4f2061f355c6a09ec564b0d60b0cf6b82d022b8 | 3,636,471 |
def rfftn(a, s=None, axes=None):
"""Multi-dimensional discrete Fourier transform for real input.
Compute the multi-dimensional discrete Fourier transform for real input.
This function is a wrapper for :func:`pyfftw.interfaces.numpy_fft.rfftn`,
with an interface similar to that of :func:`numpy.fft.rfftn... | 9df68b5655d624d6f095b8a33ce31bc706c7ac7a | 3,636,472 |
from pathlib import Path
import pathlib
import requests
import asyncio
async def ChannelLogoAPI(
channel_id:str = Path(..., description='チャンネル ID 。ex:gr011'),
):
"""
チャンネルのロゴを取得する。
"""
# チャンネル情報を取得
channel = await Channels.filter(channel_id=channel_id).get_or_none()
# 指定されたチャンネル ID が存在しな... | ab0e149141cd678b7890927b5b9e50bb9c34a91e | 3,636,473 |
import pathlib
def ImportFromNpb(
db: bytecode_database.Database, cmake_build_root: pathlib.Path
) -> int:
"""Import the cmake files from the given build root."""
bytecodes_to_process = FindBitcodesToImport(cmake_build_root)
i = 0
with sqlutil.BufferedDatabaseWriter(db, max_buffer_length=10) as writer:
... | 3f8635fe64c7bfcd306e847334badcc5a2c5b2e0 | 3,636,474 |
def _partial_ema_scov_init(n_dim=None, r:float=0.025, n_emp=None, target:float=None)->dict:
""" Initialize object to track partial moments
r: Importance of current data point
n_emp: Discouraged. Really only used for tests.
This is the number of samples for which empirical is u... | 5c73db5f3758781a7a47cc72ad85784ada6e57fa | 3,636,475 |
def inner(thing):
""" one level """
if isinstance(thing, DataPackage):
return thing,
else:
return list(thing) | 17eb8b2a272144b4a1732d8f6ce1f40c18f79b8a | 3,636,476 |
def load_dataset(data_name):
"""Load dataset.
Args:
data_name (str): The name of dataset.
Returns:
dataset (pgl.dataset): Return the corresponding dataset, containing graph information, feature, etc.
data_mode (str): Currently we have 's' and 'm' mode, which mean small dataset a... | f99dcc9d64085ef545658d34deb4936f37305f11 | 3,636,477 |
def require_dataset(hdf5_data, path, shape, dtype, maxshape=(None)):
"""
Create or update a dataset, making sure that its shape is resized
if needed
Args:
hdf5_data: object, an already opened hdf5 file
path: string, the path to the dataset
shape: tuple of integers, the shape of t... | dc9b3b4db56854cc2c770875a754474bbc5f56a3 | 3,636,478 |
def findquote(lrrbot, conn, event, respond_to, query):
"""
Command: !findquote QUERY
Section: quotes
Search for a quote in the quote database.
"""
quotes = lrrbot.metadata.tables["quotes"]
with lrrbot.engine.begin() as pg_conn:
fts_column = sqlalchemy.func.to_tsvector('english', quotes.c.quote)
query = sql... | 1d61f7c416d51d6c362b212b0217d1717ef79aa4 | 3,636,479 |
import re
def find_first_in_register_stop(seq):
"""
Find first stop codon on lowercase seq that starts at an index
that is divisible by three
"""
# Compile regexes for stop codons
regex_stop = re.compile('(taa|tag|tga)')
# Stop codon iterator
stop_iterator = regex_stop.finditer(seq)
... | 56741828c42ecf0cb96044d03c8d1b6bc4994e01 | 3,636,480 |
def greet_person(person: Person) -> str:
"""Return a greeting message for the given person.
The message should have the form 'Hello, <given_name> <family_name>!'
>>> david = Person('David', 'Liu', 110, '110 St. George Street')
>>> greet_person(david)
'Hello, David Liu!'
"""
return f'Hello,... | 3050e78295dfeee2d80c4d17fa7acc4bbfcb4d41 | 3,636,482 |
def sw(s1, s2, pen, matrix):
"""
Takes as input two sequences, gap penalty, BLOSUM or PAM dictionary
and returns the scoring matrix(F) and traceback matrix(P)
"""
N = len(s1) + 1
M = len(s2) + 1
F = [] #initialize scoring matrix(F) and traceback matrix(P)
P = []
F = [[... | c466997476259c4f2736ae0dec892f5f8e5f20e7 | 3,636,483 |
def random_multiplex_ER(n,l,p,directed=False):
""" random multilayer ER """
if directed:
G = nx.MultiDiGraph()
else:
G = nx.MultiGraph()
for lx in range(l):
network = nx.fast_gnp_random_graph(n, p, seed=None, directed=directed)
for edge in network.edges(... | 9a70997fb3de5db225b0282a3b217eb4e33f0a8c | 3,636,485 |
def compare_structures(structure_a, structure_b):
"""Compare two StructureData objects A, B and return a delta (A - B) of the relevant properties."""
delta = AttributeDict()
delta.absolute = AttributeDict()
delta.relative = AttributeDict()
volume_a = structure_a.get_cell_volume()
volume_b = str... | 93a7b2a5d28abe844b9daabce840afe275ed851e | 3,636,486 |
from typing import Callable
def parse_response(expected: str) -> Callable:
"""
Decorator for a function that returns a requests.Response object.
This decorator parses that response depending on the value of <expected>.
If the response indicates the request failed (status >= 400) a dictionary
cont... | 2d50fb98553e1803ef86056a0455a864c17bb065 | 3,636,487 |
def find_parents(candidate, branches):
"""Find parents genre of a given genre, ordered from the closest to
the further parent.
"""
for branch in branches:
try:
idx = branch.index(candidate.lower())
return list(reversed(branch[:idx + 1]))
except ValueError:
... | 17934d9ee1d3098cc3d08f38d9e3c387df6b7c19 | 3,636,488 |
import torch
def swig_ptr_from_FloatTensor(x):
""" gets a Faiss SWIG pointer from a pytorch tensor (on CPU or GPU) """
assert x.is_contiguous()
assert x.dtype == torch.float32
return faiss.cast_integer_to_float_ptr(
x.storage().data_ptr() + x.storage_offset() * 4) | d1cdf905fcd45053e9cf42306a68408fa68d1ddf | 3,636,489 |
def generate_reference_user_status(user,references):
"""Generate reference user status instances for a given set of references.
WARNING: the new instances are not saved in the database!
"""
new_ref_status = []
for ref in references:
source_query = ref.sources.filter(userprofile=user.userprofile)\
... | a0d859d06ee4f4a8f47aaad4e6814ae232e6d751 | 3,636,490 |
def binned_bitsets_by_chrom( f, chrom, chrom_col=0, start_col=1, end_col=2):
"""Read a file by chrom name into a bitset"""
bitset = BinnedBitSet( MAX )
for line in f:
if line.startswith("#"): continue
fields = line.split()
if fields[chrom_col] == chrom:
start, end = int( ... | 4e45b58d56f0dcb290995814666db36fa0fca0c7 | 3,636,491 |
def timeperiod_contains(
timeperiod: spec.Timeperiod,
other_timeperiod: spec.Timeperiod,
) -> bool:
"""return bool of whether timeperiod contains other timeperiod"""
start, end = timeperiod_crud.compute_timeperiod_start_end(timeperiod)
other_start, other_end = timeperiod_crud.compute_timeperiod_star... | 62c0f48b30e550a6c223aa46f0e63bf7baac9f4d | 3,636,492 |
import copy
def asdict(obj, dict_factory=dict, filter_field_type=None):
"""
Version of dataclasses.asdict that can use field type infomation.
"""
if _is_dataclass_instance(obj):
result = []
for f in fields(obj):
if filter_field_type is None:
continue
... | 2f5f60bbe7cef89cd13dbde1ffc1c3e11f8e2152 | 3,636,493 |
def process_pdb_file(pdb_file, atom_info_only=False):
"""
Reads pdb_file data and returns in a dictionary format
:param pdb_file: str, the location of the file to be read
:param atom_info_only: boolean, whether to read the atom coordinates only or all atom data
:return: pdb_data, dict organizing pdb... | c3328ec0123d49e2776aee84a1fdce56fb9dc84c | 3,636,494 |
def get_insns(*, cls=None, variant: Variant = RV32I):
"""
Get all Instructions. This is based on all known subclasses of `cls`. If non
is given, all Instructions are returned. Only such instructions are returned
that can be generated, i.e., that have a mnemonic, opcode, etc. So other
classes in the ... | 8f0947ebd5750e19f557959f9ccbe6c9e0ee944e | 3,636,495 |
def _assert_all_equal_and_return(tensors, name=None):
"""Asserts that all tensors are equal and returns the first one."""
with backend.name_scope(name or 'assert_all_equal'):
if len(tensors) == 1:
return tensors[0]
assert_equal_ops = []
for t in tensors[1:]:
assert_equal_ops.append(check_ops... | 2c3043aceebd3bf44a0c2aecb4ed188a4a3d6629 | 3,636,496 |
def _get_igraph(G, edge_weights=None, node_weights=None):
"""
Transforms a NetworkX graph into an iGraph graph.
Parameters
----------
G : NetworkX DiGraph or Graph
The graph to be converted.
edge_weights: list or string
weights stored in edges in the original graph to be kept i... | f444eac372d11c289bf157a24e9fccb5583ce500 | 3,636,497 |
def rename(isamAppliance, instance_id, id, new_name, check_mode=False, force=False):
"""
Deleting a file or directory in the administration pages root
:param isamAppliance:
:param instance_id:
:param id:
:param name:
:param check_mode:
:param force:
:return:
"""
dir_id = Non... | a9d645bdbdc4d5804b57fe93625eba558a9c9c14 | 3,636,498 |
def deepset_update_global_fn(feats: jnp.ndarray) -> jnp.ndarray:
"""Global update function for graph net."""
# we want to sum-pool all our encoded nodes
#feats = feats.sum(axis=-1) # sum-pool
net = hk.Sequential(
[hk.Linear(128), jax.nn.elu,
hk.Linear(30), jax.nn.elu,
hk.Linear(11)]) # numbe... | 34fd3038ed56a494d2a09fa829cfe48d583cea49 | 3,636,499 |
def max_sum_naive(arr: list, length: int, index: int, prev_max: int) -> int:
"""
We can either take or leave the current number depending on previous max number
"""
if index >= length:
return 0
cur_max = 0
if arr[index] > prev_max:
cur_max = arr[index] + max_sum_naive(arr, lengt... | 644b5cb294e78a10add253cad96d3c3e2c3d67d7 | 3,636,500 |
import torch
def accuracy(X, X_ref):
""" Compute classification accuracy.
Parameters
----------
X : torch.Tensor
The classification score tensor of shape [..., num_classes]
X_ref : torch.Tensor
The target integer labels of shape [...]
Returns
-------
The average accua... | a62adda146de6573cdc190b636b0269852604608 | 3,636,501 |
from datetime import datetime
import uuid
def create_cert_builder(subject, issuer_name, public_key, days=365, is_ca=False):
"""
The method to create a builder for all types of certificates.
:param subject: The subject of the certificate.
:param issuer_name: The name of the issuer.
:param public_ke... | 04739a7b81c3e4b6d70bba96e646e64c2d5fdbb7 | 3,636,503 |
def _table_row(line):
"""
Return all elements of a data line.
Return all elements of a data line. Simply splits it.
Parameters
----------
line: string
A stats line.
Returns
-------
list of strings
A list of strings, containing the data on the line, split at white s... | dc5d76db80059b0da257b45f12513d75c2765d55 | 3,636,504 |
def ack_alert_alarm_definition(definition_id):
""" Acknowledge all alert(s) or an alarm(s) associated with the definition identified by definition_id.
"""
try:
# Get definition identified in request
definition = SystemEventDefinition.query.get(definition_id)
if definition is None:
... | 6b15f6019fad506937ed0bcc0c6eeb34ce21faf4 | 3,636,505 |
def range2d(range_x, range_y):
"""Creates a 2D range."""
range_x = list(range_x)
return [ (x, y) for y in range_y for x in range_x ] | ca33799a277f0f72e99836e81a7ffc98b191fc37 | 3,636,506 |
import time
def segment(im, pad=0, caffemodel=None):
"""
Function which segments an input image. uses pyramidal method of scaling, performing
inference, upsampling results, and averaging results.
:param im: image to segment
:param pad: number of pixels of padding to add
:param caffemodel: path... | 0e6f0d8cfd363c7b59007105178eaea3f0238261 | 3,636,509 |
def check_consistency( # pylint: disable=too-many-arguments
num_users=None,
num_items=None,
users_hat=None,
items_hat=None,
users=None,
items=None,
user_item_scores=None,
default_num_users=None,
default_num_items=None,
default_num_attributes=None,
num_attributes=None,
at... | 4139a684751d25bef08d8f4806735be8769bb09e | 3,636,510 |
from datetime import datetime
def verify_forgot_password(request):
"""
Check the forgot-password verification and possibly let the user
change their password because of it.
"""
# get form data variables, and specifically check for presence of token
formdata = _process_for_token(request)
if... | 7ff10e96701c2733702a717fe9bd4fd7103189d1 | 3,636,511 |
def extend_node(node, out_size, axis=-1, value=0):
"""Extend size of `node` array
For now, this function works same with `extend_array` method,
this is just an alias function.
Args:
node (numpy.ndarray): the array whose `axis` to be extended.
first axis is considered as "batch" axi... | 08ef9f3f1cff5dce22ca8b4afacbc496e7d803ad | 3,636,513 |
def forward(X, weights, bias):
"""
Simulate the forward pass on one layer.
:param X: input matrix.
:param weights: weight matrix.
:param bias: bias vector.
:return:
"""
a = np.matmul(weights, np.transpose(X))
b = np.reshape(np.repeat(bias, np.shape(X)[0], axis=0), np.shape(a))
o... | fb330d01a42965c003367997381ca8929200d57e | 3,636,514 |
from typing import Any
def sanitize_for_params(x: Any) -> Any:
"""Sanitizes the input for a more flexible usage with AllenNLP's `.from_params()` machinery.
For now it is mainly used to transform numpy numbers to python types
Parameters
----------
x
The parameter passed on to `allennlp.co... | 538e2268f15960683bfe85e03b96076e7f2241db | 3,636,515 |
import dns.resolver
def host_ip():
"""Test fixture to resolve and return host_ip as a string."""
query = dns.resolver.query("scanme.nmap.org")
assert len(query) > 0, "could not resolve target host name"
return query[0].address | ee801bc2be6311fb1fe0805f5d3efb0a4fe589be | 3,636,518 |
def get_subnet_from_list_by_id(subnet_id, subnets_list):
"""Get Neutron subnet by id from provided subnets list.
:param subnet_id: Neutron subnet ID
:param subnets_list: List of Neutron subnets, where target subnet should
be searched
"""
for subnet in subnets_list:
... | 93e294131a96de321d18ce5a0e5d3b6fb5913b72 | 3,636,520 |
def grafana_logo(dispatcher):
"""Construct an image_element containing the locally hosted Grafana logo."""
return dispatcher.image_element(dispatcher.static_url(GRAFANA_LOGO_PATH), alt_text=GRAFANA_LOGO_ALT) | 2311c77cf2b5054c3a103693a2d9b862a3e503af | 3,636,521 |
import json
def is_json(payload):
"""Check if a payload is valid JSON."""
try:
json.loads(payload)
except (TypeError, ValueError):
return False
else:
return True | a02499ffd0a890fa4697f1002c5deb0fc894cac0 | 3,636,522 |
def gram_schmidt(M):
"""
@param M:
A mxn matrix whose columns to be orthogonalized
@return ret
Matrix whose columns being orthogonalized
"""
columns = M.T
res = []
res.append(columns[0])
for x in range(1, columns.shape[0]):
tmp = np.array([0 for x in range(M.... | e64b2ea4e36c3a5f8394887ba666b4c392d0284c | 3,636,523 |
def horizon_main_nav(context):
""" Generates top-level dashboard navigation entries. """
if 'request' not in context:
return {}
current_dashboard = context['request'].horizon.get('dashboard', None)
dashboards = []
for dash in Horizon.get_dashboards():
if callable(dash.nav) and dash.n... | 40f2e5e5b8661d52d3688a04ac93b7c0d48b99f2 | 3,636,525 |
import warnings
def _filter_out_bad_segments(img1, seg1, img2, seg2):
"""
It's possible for shearing or scaling augmentation to sample
one segment completely out of the image- use this function
to filter out those cases
"""
minval = tf.reduce_min(tf.reduce_sum(seg1, [0,1])*tf.reduce_sum(seg2, ... | fa74ae956c063c15b7fd1e8c21fb6e0788fc19e6 | 3,636,526 |
def _seconds_to_hours(time):
"""Convert time: seconds to hours"""
return time / 3600.0 | d6abd9144882587833601e64d5c2226446f1bbdc | 3,636,527 |
async def process_cmd_entry_erase(guild_id: int, txt_channel: str, bosses: list,
channel = None):
"""Processes boss `entry` `erase` subcommand.
Args:
guild_id (int): the id of the Discord guild of the originating message
txt_channel (str): the id of the channel of the originating message,
... | e385768fc34ebb419f51124e0a0f5a4e1577ad00 | 3,636,529 |
import warnings
import scipy
def mle_iid_gamma(n):
"""Perform maximum likelihood estimates for parameters for i.i.d.
NBinom measurements, parametrized by alpha, b=1/beta"""
with warnings.catch_warnings():
warnings.simplefilter("ignore")
res = scipy.optimize.minimize(
fun=lambd... | 089d181a85a72d42457c7ea1eae3aaabb3d6dd60 | 3,636,530 |
def build_tabnet_results(dataset, image_ids, rois, class_ids, scores, masks):
"""Arrange resutls to match COCO specs in http://cocodataset.org/#format
"""
# If no results, return an empty list
if rois is None:
return []
results = []
for image_id in image_ids:
# Loop through dete... | a564f28751436be9648b60a7badae651be3c4583 | 3,636,531 |
from typing import Callable
from typing import Dict
from typing import Any
def make_raw_serving_input_receiver_fn(
feature_spec: features_specs_type,
transform_input_tensor: Callable[[Dict[str, tf.Tensor]], None],
is_model_canned_estimator: bool = False,
batched_predictions: bool = True
) -> Callable[... | 2780f36ae373b1bd4623b6988ec7b4d130fb21ff | 3,636,532 |
from typing import List
import json
from typing import Set
def load_parentheses_dataset(path: str, depths: List[int]) -> torchtext.data.Dataset:
"""
Load equation verification data as a sequential torchtext Dataset, in infix
notation with parentheses.
The Dataset is additionally populated with `leaf_... | 048c5cc42660c21ab59d8dd2dc205aeeafb22bd3 | 3,636,533 |
from typing import List
def get_angle(v1: List[int], v2: List[int]):
"""
:param v1: 2D vector
:param v2: 2D vector
:return: the angle of v1 and v2 in degree
"""
dot = np.dot(v1, v2)
norm = np.linalg.norm(v1) * np.linalg.norm(v2)
return np.degrees(np.arccos(dot / norm)) | 669a4119c1b6da1bcf0fb84f3d2ce0056acd8170 | 3,636,534 |
import logging
def get_plasma_intersection(lon, lat, alt, plasma_alt=300., tx_lon=-75.552,
tx_lat=45.403, tx_alt=0.07):
"""
This function finds where a ray from a transmitter toward a satellite
intersects the peak plasma in the middle.
*** PARAMS ***
Satellite ephemeri... | 8234bf61ef2b0d501a723ef9553c6b63d3c51998 | 3,636,535 |
def plot_clusters(g, c):
"""
Draws a given graph g with vertex colours corresponding to clusters c and
displays the corresponding sizes of the clusters.
===========================================================================
Parameters
--------------------------------------------------------... | dbeec2b421a23c7b503dc71e29cd7caca3300dc5 | 3,636,536 |
def make_cat_advanced(simple=True, yolo=False):
"""fill the categories manually"""
cat_list = get_cat_list(simple)
if simple:
if yolo:
cat_mapping = {
"benign": 0,
"malign": 1,
}
else:
cat_mapping = [0, 1]
return ca... | 5b4f0bac9126ce3a84ec5ea8d27203f7dfe41e10 | 3,636,537 |
import operator
def process_fuel(context):
"""
Reformats Fuel consumed
"""
fuel = {
0: 'Petrol',
1: 'Desiel'
}
data = []
totals = []
for index, type in enumerate(context['Fuel']):
litresSold = operator.sub(type.closing_meter, type.opening_meter)
total = op... | fea31cb306417cf1dfcef8859ed2585c2903849b | 3,636,538 |
from bs4 import BeautifulSoup
import requests
def prepare_df_financials(
ticker: str, statement: str, quarter: bool = False
) -> pd.DataFrame:
"""Builds a DataFrame with financial statements for a given company
Parameters
----------
ticker : str
Company's stock ticker
statement : str
... | 1fdd3488c81bdf404764bba3b797f931ba77ad93 | 3,636,539 |
def build_si(cp, instruction):
"""
Build the integer representation of the source indices.
:param cp: CoreParameters instance for the target architecture
:param instruction: Instruction instance
:return: integer representation of si
"""
# Check sizing.
if len(instruction.source_indices... | 2d78d75486432c1e41847074ed819194b1f0e643 | 3,636,540 |
def getRegSampledPrfFitsByOffset(prfArray, colOffset, rowOffset):
"""
The 13x13 pixel PRFs on at each grid location are sampled at a 9x9 intra-pixel grid, to
describe how the PRF changes as the star moves by a fraction of a pixel in row or column.
To extract out a single PRF, you need to address the 117... | 551ec8624c9c41bca850cf5110d59f65179d6505 | 3,636,541 |
import click
def generate_list_display(object, attrs):
"""Generate a display string for an object based on some attributes.
Args:
object: An object which has specific attributes.
attrs: An interable of strings containing attributes to get from
the above object.
Returns:
... | 17c876261bede0c38d91b4bd3e7b0048616f8cbf | 3,636,542 |
import tempfile
def create_temporary_config_file():
""" Create a minimal config file with some default values
"""
toml_config = document()
toml_config.add("name", "Test Suite")
tmp_config_file = tempfile.NamedTemporaryFile(delete=False)
with tmp_config_file:
content = dumps(toml_conf... | ff7c226eb035aa6b5d8e79efa2acc8a92a925659 | 3,636,543 |
def shear(image, shear_factor, **kwargs):
"""
Shear image.
For details see:
http://scikit-image.org/docs/dev/api/skimage.transform.html#skimage.transform.AffineTransform
>>> image = np.eye(3, dtype='uint8')
>>> rotated = rotate(image, 45)
:param numpy array image: Numpy array with range [... | 97f6cc57d1aa41569c84601470242350b2805ffc | 3,636,544 |
def segments():
"""Yields all segments in the unnannotated training Qatar-Living dataset."""
return (segment for document in documents() for segment in document.segments) | eea12bb25ca3c143c5b867987444e4d141982e94 | 3,636,545 |
from datetime import datetime
def get_options_between_dates(
start_date,
end_date):
"""get_options_between_dates
:param start_date: start date
:param end_date: end date
"""
valid_options = []
for rec in historical_options():
opt_date = datetime.datetime.strptime(
... | c2528e85f5e1fce9f537639d0ec88ca20477b93d | 3,636,546 |
def format_timestamp(timestamp_str, datetime_formatter):
"""Parse and stringify a timestamp to a specified format.
Args:
timestamp_str (str): A timestamp.
datetime_formatter (str): A format string.
Returns:
str: The formatted, stringified timestamp.
"""
try:
if '"' ... | 528f1a5f7fd2a45de9d4ee77a8eaf29e06dcb310 | 3,636,547 |
import math
def dyn_stdev(val, prev_stdev, prev_mean, n):
"""Dynamic stdev: computes the standard deviation based on a previous stdev plus a new value. Useful when stdev
is built incrementally, it saves the usage of huge arrays.
Keyword arguments:
val -- new val to add to the mean
prev_stdev -- ... | ccf58f769650b209128bc370fc67144f82e68850 | 3,636,548 |
import warnings
def get_detail_backtest_results(input_df,
features,
return_col_name='returns',
equity_identifier='Equity Parent',
date_col_name='date',
n_bins... | 702f80d378d12e3570af6bf69a786ec913eed4e9 | 3,636,549 |
from typing import Counter
def check_train_balance(df,idx_train,keys):
"""
check the balance of the training set.
if only one of the classes has more 2 instances than the other
we will randomly take out those 'extra instances' from the major
class
"""
Counts = dict(Counter(df.iloc[idx_trai... | d99c9e1c4ae0d6124da576b91ce2b2786d53f07b | 3,636,551 |
def eye(w, n):
"""Create diagonal matrix with w on diagonal."""
return np.array([[w if i==j else 0.0*w for i in range(n)] for j in range(n)]) | e12ff719981ff7311c21339ad651d7bd38f204f6 | 3,636,552 |
def Messaging():
"""
Messaging
Creates JMS resources.
Only to use in a resource block.
"""
if state().block and state().block != 'resources':
raise SyntaxError('Messaging can only be used in a resources block')
return subscope('messaging') | 9017c8c0452cf75b05f422d6335b8ba5bcd7bc90 | 3,636,553 |
from datetime import datetime
def timestamp2WP(timestamp):
"""
Converts a Unix Epoch-based timestamp (seconds since Jan. 1st 1970 GMT)
timestamp to one acceptable by Wikipedia.
:Parameters:
timestamp : int
Unix timestamp to be converted
:Return:
string Wikipedia style timestamp
"""
return datet... | c4b9bef9e555c178991569472f3962c7a17d996c | 3,636,554 |
def get_available_node_types(nodenet_uid):
""" Return a dict of available built-in node types and native module types"""
return True, runtime.get_available_node_types(nodenet_uid) | 509730edf1c3ea7958a7356e3c784893c2b4c769 | 3,636,555 |
def dos_element_orbitals(
folder,
element_orbital_dict,
output='dos_element_orbitals.png',
fill=True,
alpha=0.3,
linewidth=1.5,
sigma=0.05,
energyaxis='x',
color_list=None,
legend=True,
total=True,
figsize=(4, 3),
erange=[-6, 6],
spin='up',
soc_axis=None,
... | 957e21298077ece088ef5f6c2c2c7ad5c3e599aa | 3,636,556 |
def get_ceph_nodes():
"""Query named relation 'ceph' to determine current nodes."""
hosts = []
for r_id in relation_ids('ceph'):
for unit in related_units(r_id):
hosts.append(relation_get('private-address', unit=unit, rid=r_id))
return hosts | 35ee1775c9e4d2636e8373cf0936e6e1a8cb0b76 | 3,636,557 |
def metadataAbstractElementIllegalChildElementTest1():
"""
No child elements, child elements not allowed.
>>> doctestMetadataAbstractElementFunction(
... testMetadataAbstractElementIllegalChildElements,
... metadataAbstractElementIllegalChildElementTest1())
[]
"""
metadata = """... | c8405bbe81db5d86941a68c62ba19a6576789e50 | 3,636,558 |
def discover_fields(layout):
"""Discover all fields defined in a layout object
This is used to avoid defining the field list in two places --
the layout object is instead inspected to determine the list
"""
fields = []
try:
comps = list(layout)
except TypeError:
return fiel... | 359a6ed1d23e1c56a699895e8c15a93bce353750 | 3,636,559 |
def replace(project_symbols):
"""
replace old source with non annotated signatures
:param project_symbols: symbols we will use to write out new source code
:return: bool
"""
for module_symbols in project_symbols:
if not write_new_source(module_symbols, access_attr... | b3a00199f336b6711fba2096bec9a0fc0c4976b8 | 3,636,560 |
def element_list_as_string(elements):
"""Flatten a list of elements into a space separated string."""
names = []
for element in elements:
if isinstance(element, AOVGroup):
names.append("@{}".format(element.name))
else:
names.append(element.variable)
return " ".... | baa0c1aaa6bd11932f388756c807c9240abb3958 | 3,636,561 |
def encode_corpus(storage: LetterStorage, corpus: tuple) -> tuple:
"""
Encodes sentences by replacing letters with their ids
:param storage: an instance of the LetterStorage class
:param corpus: a tuple of sentences
:return: a tuple of the encoded sentences
"""
if not isinstance(storage, Let... | 0fa6b4c6b5dd4a33c9e9aee8b1c81fdb119625a7 | 3,636,563 |
from typing import Type
def aggregated_column_unique(chart: Type[BaseChart], data):
"""
description:
main function to calculate histograms
input:
- chart
- data
output:
list_of_unique_values
"""
a_range = cuda.to_device(np.array([chart.min_value, chart.max_valu... | 79f2f896e5a8ad06dba5589896eadfe224e42246 | 3,636,564 |
def collocations_table_exist(con):
"""Return True if the collocations table exist"""
query = con.query(
"select 1 from information_schema.tables "
"where table_name='collocations'")
return bool(list(query.dictresult())) | 9ffa05f698056d9fab6bb9651427b6bc64f414ea | 3,636,566 |
from bs4 import BeautifulSoup
import re
def ftp_profile(publish_settings):
"""Takes PublishSettings, extracts ftp user, password, and host"""
soup = BeautifulSoup(publish_settings, 'html.parser')
profiles = soup.find_all('publishprofile')
ftp_profile = [profile for profile in profiles if profile['publishmeth... | 003218e6d58d01afcbf062a14e68294d0033b8af | 3,636,567 |
from typing import List
def train(name,train_data:List[tuple],test_data=None)->tuple:
"""
Train Naive Bayes Classifier for Multinomial Models
:param list train_data: list train data of tuple (text,tag)
:param object get_features: function of features
:param list test_data: list test data of tuple... | 32fce3f0c69bdb85878549f95c159a1277104f97 | 3,636,568 |
def validate_article(article_json):
"""
Validate the content of a raw article
"""
if article_json is None:
return False
try:
# Filter title
if not vstrlen(article_json['title'], 16):
return False
# Filter contents
if not vstrlen(article_json['con... | 493a539ec933d43980a7724afadc6a478b4a1a6a | 3,636,569 |
def get_model_memory_usage(batch_size, model):
"""
Estimate how much memory the model will take, assuming all parameters is in float32
and float32 takes 4 bytes (32 bits) in memory.
:param batch_size:
:param model:
:return:
"""
# Calculate the total number of outputs from all layers
... | 0452e9943ff2a0c9dbcb8c870237344740502fe4 | 3,636,570 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.