content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import struct
def discard_blanks(data):
"""Remove blank spaces from the data file"""
pos = 0
for i_char in data:
char = struct.unpack('s', data[pos:pos + 1])[0].decode()
if char not in ["*", " "]:
break
else:
pos += 1
return data[pos:] | aff090ab188bffd6bca86eb3b861d25a0440dbcc | 72,868 |
def matches(text):
"""
Return the list of keyword matches in text
"""
matches = []
for rgx in compiledRegexes:
found = rgx.findall(text)
matches.append((rgx.pattern, len(found)))
return matches | 334f5739f946f3c9f545a2bc4ffb9c05940f0ea6 | 72,869 |
def set_amplifier_mode(
con_handle: ConnectionHandler,
slot_id: str,
channel_index: int,
amplifier_mode: str | int,
) -> str:
"""Set the amplifier mode for an analog channel.
The system needs to be idle before calling this function.
If the specified amplifier mode is not supported by the... | c234814b3c96664e90414bf023fe4f450cab630f | 72,870 |
def get_saliency_maps_for_class_activation(
model_object, target_class, list_of_input_matrices):
"""For each input example, creates saliency map for prob of target class.
:param model_object: Instance of `keras.models.Model`.
:param target_class: Saliency maps will be created for this class. Must ... | cd2a329a3f42e8760e5e0cf0134fa6d3a7798f05 | 72,871 |
def select_one():
"""
Select 1 from database
"""
sql = "SELECT 1"
results = query_db(sql, db = get_db(), pretty_print=True)
return results | 4fd4cc6e4a707f581dba3f284cf288299b209211 | 72,872 |
from typing import Dict
def approve_root(
chain: str, start: int, end: int, current_rewards: Dict, tree_manager: TreeManager
):
"""Approve latest root on a chain
:param chain: chain to approve root
:param start: start block for rewards
:param end: end block for rewards
:param current_rewards:... | 7813171adde29775e724edb3a39b5262122b954c | 72,873 |
def _is_required_serializer_field(field):
# type: (ast.Field) -> bool
"""
Get whether we require this field to have a value set before serialization.
Fields that must be set before serialization are fields without default values, that are not
optional, and are not chained.
"""
return not fi... | dc2a07ec4bccca01844e97daa1b8f3632c7c8e81 | 72,874 |
from typing import Callable
def muzero_expand_node(
n: DeterministicNode,
info: Info,
inference: Callable[[State, Action], MuzeroInferenceOutput],
) -> float:
"""Muzero's way of expanding and evaluating a node
``n`` is assumed to contain "action", and its parent "latent_state".
Will create a... | b010a88853bacf1b1d1964fb31df03ab0542435d | 72,875 |
def quote(s):
"""Quote a string, with either single or double quotes depending on the content"""
sq = single_quote(s)
dq = double_quote(s)
return sq if len(sq) <= len(dq) else dq | 92c0ac7547a976c0f9b2745b87d8150e3cdb3de8 | 72,876 |
def PreToolBar(*args, **kwargs):
"""PreToolBar() -> ToolBar"""
val = _controls_.new_PreToolBar(*args, **kwargs)
return val | 804e74dba6758f12330663ec2af7f42c2a214b8a | 72,877 |
def convert_date(date_column):
"""Converts date from object to datetime format
Args:
date_column (pd.Series): Raw object data
Returns:
pd.Series: Default <pd.datetime> format
"""
return pd.to_datetime(date_column, format='%Y-%m-%dT%H:%M:%S') | 0da414e2ca32aa18efc76297184ba7ea40285df9 | 72,878 |
def blank_lines(logical_line, blank_lines, indent_level, line_number,
previous_logical):
"""
Separate top-level function and class definitions with two blank lines.
Method definitions inside a class are separated by a single blank line.
Extra blank lines may be used (sparingly) to sepa... | 0f2d89ae662ffd39170e83f8788cf2946f7cd045 | 72,879 |
import math
def gen_circarrow(axis=np.array([1, 0, 0]),
starting_vector=None,
portion=0.3,
center=np.array([0, 0, 0]),
radius=0.005,
thickness=0.0015,
sections=8,
discretization=24):
"""
... | 1523994cfa6923ce3219a59bfbfcb7f16144441c | 72,883 |
def confirmation_option(*param_decls, **attrs):
"""Shortcut for confirmation prompts that can be ignored by passing
``--yes`` as parameter.
This is equivalent to decorating a function with :func:`option` with
the following parameters::
def callback(ctx, param, value):
if not value:... | a587cacf29e76c2da95187c1906f311ed0c45338 | 72,884 |
def dual_quaternions_from_transforms(A2Bs):
"""Get dual quaternions from transformations.
Parameters
----------
A2Bs : array-like, shape (..., 4, 4)
Poses represented by homogeneous matrices
Returns
-------
dqs : array, shape (..., 8)
Dual quaternions to represent transform... | e310547021a1a5939a2ce26d5d81903fedabda28 | 72,886 |
from typing import Union
from typing import List
from typing import Tuple
from typing import OrderedDict
def split_features(
features: Union[List[DenseFeature], List[SparseFeature], List[SparseSeqFeature]]
) -> Tuple[
OrderedDict[str, DenseFeature],
OrderedDict[str, SparseFeature],
OrderedDict[str, Sp... | 0a999cb99c4042dbe55028d8ea948c6f0af7e309 | 72,887 |
def expand_packed(n,packed):
"""
Unpacks the entries of a lower triangular matrix from one dimension
to two dimensions.Identical to PyMC3 expand_packed except it operates on
numpy arrays rather than theano tensors.
Parameters
----------
n : int
The dimension of the matrix to be unpa... | 706bd34160b62d71df4196197986526d0a9f84f5 | 72,888 |
def states_to_piece_positions(next_states):
"""Given a list of next states, produce a list of two coordinates for each
possible next state. The first coordinate will be the location of the
piece that was moved, and the second coordinate will be the location that
the piece moved to.
"""
moves... | b65d4d0d7d9e6e7bd874a51f73c632017de36b99 | 72,889 |
import json
def TriggerSwarmingTask(host, request, http_client):
"""Triggers a new Swarming task for the given request.
Args:
request (SwarmingTaskRequest): A Swarming task request.
http_client (FinditHttpClient): An http client with automatic retry.
"""
response_data, error = http_client_util.SendR... | c90b965a3931240f7151ab0d050254d6f180d68d | 72,891 |
def gem_cov(frags, weight_flag):
"""
GEM coverage.
Args:
frags (list of list): [chrom,start,end] for each fragment in a GEM
weight_flag (binary): True if weighted by fragment number; False otherwise
Returns:
gem_all (list of bed entries): bed entries in format [chrom,start,end]
... | cd515d0f358992e07d9bf441c486ce088ce7c7a3 | 72,892 |
import re
def fix_outputs_doc(lines):
"""
Convert a list of lines from the Matlab OUTPUTS section
into a list suitable for the numpydoc Returns section,
handling multiple output variables if present.
Exception: we don't support the 'in_ocean' return, so
it is filtered out here.
"""
pa... | 659a9ac494094c2beae6bc052ac842aae6dd9259 | 72,893 |
def load_task_specific_data_in_proportion(datasets, task_labels, classes_appearing_in_tasks, class_seen_already):
"""
Loads task specific data from the datasets proportionate to classes appearing in different tasks
"""
global_class_indices = np.column_stack(np.nonzero(datasets['labels']))
count = 0
... | 1f8e9693908d82e9679175f277f0cfc6a9610452 | 72,894 |
import re
def tokenize(text):
"""
This function tokenizes text by deleting punctuation, converting
to lowercase, deleting stopwords, lemmatizing and stemming
Input:
text - text to be tokenized
Output:
stemmed - the resulting tokens
"""
url_regex = 'http[s]?://(?:[a-zA-Z]|... | c8c82d8eb2fb0dfa966ed7f974358709eb5db573 | 72,895 |
def svn_stream_copy(*args):
"""svn_stream_copy(svn_stream_t _from, svn_stream_t to, apr_pool_t pool) -> svn_error_t"""
return _core.svn_stream_copy(*args) | bcf56d71a44d2b229f8677998484e033de46c92b | 72,896 |
def get_short_name(obj):
"""
Returns short name of given Maya object
:param obj: str
:return: str
"""
try:
obj = obj.meta_node
except Exception:
pass
node_names = maya.cmds.ls(obj, shortNames=True)
if node_names:
if len(node_names) == 1:
return n... | 671c5eab19ee0308a248ac4cf71aff89213eadd2 | 72,897 |
def BPRLoss(vocab_size: int, dim: int):
"""BPR Loss with biases."""
return dpr.layers.Sequential(
dpr.layers.Select(inputs=("userEmbeddings", "targetPositives", "targetNegatives", "targetMask")),
dpr.layers.Embedding(
inputs="targetPositives",
outputs="targetPositiveEmbed... | 7ca500c9f16483f8a0457c41b1029239b7c47ee1 | 72,898 |
from typing import List
import random
def generate_good_endowments(nb_goods: int, nb_agents: int, base_amount: int, uniform_lower_bound_factor: int, uniform_upper_bound_factor: int) -> List[List[int]]:
"""
Compute good endowments per agent. That is, a matrix of shape (nb_agents, nb_goods).
:param nb_good... | 954feb953a760a473ac684c0b2f21eb5fa9fd046 | 72,899 |
def unnormalise_density(c, rho):
"""Reverses any desnity normalisation
As a general rule this should be done using the units read in from the file,
with unit conversion done afterwards"""
return c * rho | 1ffa7b4f5e08a071d5f8e94489d363a085f31930 | 72,900 |
def test_parser():
"""A parser for testing convenience"""
return parser("Testing", "Use this from a test", "") | ec20c957efee80ee7781eb3cf30efa442454fdcf | 72,901 |
def fit_function_latticeparameters(varying_parameters_values_array,
varying_parameters_keys,
Miller_indices,
allparameters,
absolutespotsindices,
... | 12fb928c0cb6d816d8381bfa5c6df5e5073fae5f | 72,902 |
def _set_quality(in_bam):
"""
change all quality to 255
"""
bam = pysam.AlignmentFile(in_bam, "rb")
out_file = utils.append_stem(in_bam, "_normqual")
if file_exists(out_file):
return out_file
with file_transaction(out_file) as tx_out:
with pysam.AlignmentFile(tx_out, "wb", te... | e5cbf239b34e330c65006dba0bf9b352e14da516 | 72,903 |
def gaussian(sigma):
"""
The Fourier transform of a Gaussian
G(w) = 1/(sqrt(2pi) sigma) * exp(- 1/2 (w/sigma)^2 )
is again a Gaussian
g(t) = 1/(2pi) exp(-1/2 sigma^2 * t^2)
Parameters
----------
sigma : float
standard deviation of Gaussian in energy domain
Returns
... | 1f4afeeaa816227a230f619699ba21ff4fd552c2 | 72,904 |
def watch():
"""Watch an example movie, streamed directly to you from hug"""
return 'movie.mp4' | fc72e5cf6570a667f86a9a9e2e764d07090b482c | 72,905 |
def get_transcription_id_base(page_id: int) -> int:
""" Get the current transcription id that should be based off of """
return (
db.session.query(Transcription)
.filter(Transcription.page_id == page_id)
.filter(Transcription.partial == False)
.order_by(Transcription.start_time.d... | 5bbbb1696e1eee599040a0958d8cfe5e236a4457 | 72,906 |
def remove_gps_photo(photo, new_photo=None):
"""Remove GPS from EXIF of a given photo. Returns flag indicating if
original file had GPS EXIF data.
photo: Location of original photo.
new_photo: Location for modified photo. Optional. Default is to overwrite
the original photo.
gps: Flag indic... | 1a82b059db0ec3ae547f2b0fba74bbc8d0239a3d | 72,907 |
def relocate_deps(target_src, target_dst, config):
"""
Make the target relocatable and copy all of its dependencies into the
artifact directory.
"""
if IS_LINUX:
return relocate_deps_linux(target_src, target_dst, config)
if IS_MACOS:
return relocate_deps_macos(target_src, target_dst, config)
raise... | e46ec86a02276b98e080ae9e2dc04e65b17f11f8 | 72,908 |
def read_scene_bbox(cziobject, metadata,
sceneindex=0,
channel=0,
timepoint=0,
zplane=0,
scalefactor=1.0):
"""Read a specific scene from a CZI image file.
: param cziobject: The CziFile reader object from aicspy... | 0b5ae2ca6dfc0a2e66df44f7ce0bb107876a310b | 72,909 |
def ikeep(hcenter, frame, dom):
""" hcenter is a histogram in time
return indices of hcenter that fall outside of the saturation window and calibration errata
"""
iskips = [np.array([False]*len(hcenter))]
if frame.Has('CalibrationErrata') and dom in frame['CalibrationErrata']:
for cerrata i... | d998937fa4118dcb9b6f2e40aeb264198117f579 | 72,910 |
import math
def acosh(x):
"""
Return the hyperbolic arc cosine of x.
There is one branch cut, extending left from 1 along the real axis to -∞, continuous from above.
"""
ret = _SPECIAL_VALUE(x, _acosh_special_values)
if ret is not None:
return ret
if math.fab... | 4ad8ed09e90f369f57bf93303130f97661676c66 | 72,912 |
def get_vlans(netmiko_session, vdc=None) -> list:
"""Get vlans"""
vlan_table = []
iter_vlan = "1"
ports = ['']
if vdc is not None:
vdc_command = f"switchto vdc {vdc}"
get_vdcs = send_command(netmiko_session, vdc_command)
get_vlans = 'show vlan brief'
vlan_ports = None
... | d595a7a6931627e0af964886b7fa5805246920ac | 72,913 |
def get_ip(base_url, session_key):
"""Get the IP address set on the router"""
return get_info(base_url, session_key)['wan_ipaddr'] | e55796ea6c7eeab009a9f9e5bfa4bb216969e9fe | 72,914 |
def seekret(seekret_session, request) -> Context:
"""
Seekret context and functions.
"""
context = Context(session=seekret_session, scope=request.scope)
default_user: Mark = request.node.get_closest_marker('default_user')
if default_user is not None:
context.default_user = default_user... | 651405ce2bcae47296f219d8bfa6248ec145cf2c | 72,915 |
def xy2hadec(x,y,tel_ha,tel_dec) :
"""
Convert tangent plane x,y to HA,Dec given a telescope pointing tel_ha, tel_dec
Args:
x: float or 1D np.array with tangent plane coord.
y: float or 1D np.array with tangent plane coord.
tel_ha: float; telescope pointing Hour Angle in degree... | f8b47c4347537d99ec47c78965529664e9fb9e40 | 72,916 |
def _mean(fiberTree, scalarType, idxes=None):
""" *INTERNAL FUNCTION*
Finds the average of all fibers in bundle at specific sample points
INPUT:
fiberTree - tree containing spatial and quantitative information of
fibers
scalarType - type of quantitative data to find aver... | eb633f8fb5bfa555e305b1bd2f292615967e04a1 | 72,917 |
def make_fun ( fun , args , name ) :
"""Helper function to create the function
"""
assert fun and isinstance ( fun , ROOT.RooAbsReal ), 'make_fun: Invalid type %s' % type ( fun )
num = len ( args )
if 1 == num : return Fun1D ( fun , name = name , *args )
elif 2 == num : return Fun2D... | 21c9fd67687b550c09b1a45cf6fe04a92c8003e4 | 72,918 |
def parse_to_int_or_float(value):
"""
Tries to parse `value` as float or int, if not possible will raise a ValueError
"""
try:
return parse_int_with_commas(value)
except ValueError:
return float(value) | 302975f3f81cee78f10220cd3b7b63758d2a6723 | 72,919 |
import random
def mutate_color(color):
"""
Mutates one coordinate of a color in a HSV cube.
"""
color[random.randrange(0, 3)] = random.random() % 1
return color | 5fdfef8b7c29be367dee85f195458924bb8421aa | 72,922 |
def create_stub_multiplexed_library() -> MultiplexedLibrary:
"""
Creates a `MultiplexedLibrary` stub.
:return: stub a `MultiplexedLibrary` model
"""
multiplexed_library = MultiplexedLibrary()
multiplexed_library.internal_id = INTERNAL_ID
multiplexed_library.name = NAME
return multiplexed... | 264759d125438c1e9075819de84aac786e06aaf3 | 72,923 |
def _bring_problem_in_right_form(cls: CLS):
"""
Brings the CLS problem in the right format so that qpsolvers.solve_ls can solve it.
:param cls: CLS
:return: r, s, g, h, a, b, lb
"""
r = cls.h
s = cls.y
if cls.inequality_constrained:
g = - cls.c
h = - cls.d
else:
... | af09fda59fceffe64bde7ea36ccee0dfb1a30938 | 72,924 |
def singlesummarise(question, docstext, n=2):
"""Return the output of the default single-document summariser
>>> question = "my sentence"
>>> text = ["This is one sentence.",\
"This is another sentence.",\
"This is yet another sentence.",\
"And this is the fin... | 87b732229e38cfe8c203403ca8789f19c1e14c5f | 72,925 |
import pickle
def model_encode(data):
"""Pickle data utilising the patched_model context manager."""
with patched_model():
return pickle.dumps(data) | 4b8b7db1abc9c658c1d3cc0c0808775fa5d6d49a | 72,926 |
import itertools
def tensors_from_data(data_dict, batch_size, axes=None, shuffle=False):
"""Turns a dict of numpy.ndarrays into a dict of minibatch tensors.
Arrays are split into minibatches of `batch_size` along `axes`. If `axes` is None,
then all arrays are split along axis==0. Tensors can iterate sequ... | 2a2ec944268906fda7ed61e7738c11b8d94aa1e6 | 72,927 |
def find_monster(grid, mon):
"""
Given a grid and a list of
indices of monster,
find the number of "#" that
are not part of any monster.
:param grid: An (8 * 12) x (8 * 12)
list of chars.
:param mon: A list of indices of
the monster.
:return: The count of "#" that
are not p... | 90ff7da5800addd0ba2ae469e9c00be822a3cfde | 72,928 |
def _ensure_spacing(coord, spacing, p_norm):
"""Returns a subset of coord where a minimum spacing is guaranteed.
Parameters
----------
coord : ndarray
The coordinates of the considered points.
spacing : float
the maximum allowed spacing between the points.
p_norm : float
... | d13a134a9ad8578650c6740a1e7826cbb9f19102 | 72,929 |
def test_post_getattr():
"""Test the post_getattr behaviors.
"""
class ModuloInt(Int):
def __init__(self):
super(ModuloInt, self).__init__()
mode = PostGetAttr.MemberMethod_ObjectValue
self.set_post_getattr_mode(mode, 'post_getattr')
def post_getattr(se... | 0c9239a8738393042b48576e7ca83a68cf35870e | 72,931 |
def create_merge_consecutive_day_input_filenames(datestring):
""" Create the list of filenames for merge_consecutive_day_trajectories.py. """
prev_datestring = iso8601_previous_day(datestring)
return [create_matching_ids_filename(PREV_DAY, datestring)] + \
create_match_consecutive_day_input_filename... | 2e708330c9a587b3d6774778d5c914d0a7841c9b | 72,932 |
def raw_commands(layout_in):
"""Return raw command set. (<command(str)>, <index(int)>).
Args:
layout_in(str): Simple layout string.
"""
panes = _generate_panes(layout_in)
return panes.commands | d19056f0a0577e9a69451348cd9d4ab0fc24577b | 72,933 |
def EnsureHeapMetadataHomogeneity(Metadata):
"""Ensures that all of the metadata provded are homoenous on the
size, offset-from-base, and backtrace for all heap interactions.
Returns:
Tuple containing (size,offset,backtrace) for the common
allocation type.
"""
HeapMeta = tuple(M for... | 9236730f2e1ebd2c0f8fafd6f8ca490db22d138a | 72,934 |
def _create_fake_dataset(output_path, seq_length, num_labels, num_examples):
"""Creates a fake dataset."""
writer = tf.io.TFRecordWriter(output_path)
def create_int_feature(values):
f = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values)))
return f
for i in range(num_examples):
featu... | 5d1db578b3959c32a70946a2fefd95a2ee2cf305 | 72,935 |
def do_embed(parser, token):
"""{% embed %} template tag. Allows to include a template and optionally override its slots, in a similar fashion
to block tags in extended templates.
Example::
{% embed 'section.html' %}
{% slot title %}<h1>Title</h1>{% endslot %}
{% slot conte... | 557d2aa7fe4d808fae8c7abd6cf7f7ce51df45aa | 72,936 |
def dispatch_samples(sample, scheme, n_agents, fields=None):
""" transform samples from buffer to feed in maddpg learner
specify how to decode sample to per-agent experience
Arguments:
sample: SampleBatch/EpisodeBatch, each is (B,D)
scheme: multi-agent sample scheme
Returns:
... | 4ed79713a3ef4768c9921b17d71ab4510b4aab59 | 72,937 |
def container_with_most_water(heights):
"""
Parameters
----------
heights : list
A list of integers representing heights of containers
Returns
-------
int
area of container with most water
>>> container_with_most_water([1, 8, 6, 2, 5, 4, 8, 3, 7])
49
>>> conta... | d25c602bac1aab4484ca60680bcaa21abbb78dc7 | 72,938 |
def log_loss(actual, predicted):
"""
Computes the log loss.
This function computes the log loss between two lists
of numbers.
Parameters
----------
actual : list of numbers, numpy array
The ground truth value
predicted : same type as actual
The predicted va... | 24a067d0fcb98489acb59b59e5af0f66fb975c8d | 72,939 |
from . import components
def incidence_matrix(network, branch_components=None, busorder=None):
"""
Construct a sparse incidence matrix (directed)
Parameters
----------
branch_components : iterable sublist of `branch_components`
Buses connected by any of the selected branches are adjacent
... | ae5c477e84f7ff1a9d995b5350d21c50723ae8d5 | 72,940 |
def preprocess_data(data):
"""preprocessing the text data, conversion to numerical array format."""
def deal_line(line):
pos, rating = line.split(',')
row, col = pos.split("_")
row = row.replace("r", "")
col = col.replace("c", "")
return int(row), int(col), float(rating)
... | 1a9c8e01e8ca80a2b6ebe162510a902b69170a83 | 72,941 |
from .._tier1 import set
def generate_distance_matrix(coordindate_list1 :Image, coordinate_list2 :Image, distance_matrix_destination :Image = None):
"""Computes the distance between all point coordinates given in two point lists.
Takes two images containing pointlists (dimensionality n * d, n: number of ... | 794f338af8c118f2f92a1da939008d6c6c67b721 | 72,942 |
def getClampState(data_handle):
"""
Return the full clamp state
"""
if not isClampFile(data_handle):
raise Exception('%s not a clamp file.' % data_handle.shortName())
data = data_handle.read(readAllData=False)
info = data._info[-1]
if 'ClampState' in info.keys():
return info[... | 03a3b5818ad1005057d972fd60b2f993ad594130 | 72,943 |
import random
import functools
def compute_background_loss(model, state, params, key, points, noise_std,
alpha=-2, scale=0.001):
"""Compute the background regularization loss."""
metadata = random.choice(key, model.warp_embeds, shape=(points.shape[0], 1)) # for each of the point, choos... | 44746f8eb45f4ed7f0f207b81423d1719a48a6f0 | 72,944 |
import hashlib
def calculate_file_hash(file_path):
"""
Quickly compute a hash (md5) of a file
:param file_path:
:return:
"""
with open(file_path) as file_to_hash:
file_content = file_to_hash.read()
digest = hashlib.md5()
digest.update(file_content)
hash_result = digest.hexd... | 907c458ee4a93b1e2d18c34fa7b74e28134443b5 | 72,947 |
def sec_dev_max(f, a, b):
"""
Calculates the max second derivative within the range [a,b]
"""
n = 999999
i = (b - a) / float(n)
max = abs(sec_dev(f, a))
for counter in range(n):
temp = abs(sec_dev(f, a + (counter + 1) * i))
if temp > max:
max = temp
return max | 23fc1d32452b925b60270cc9f26b8b1f37cece65 | 72,948 |
def is_ok_title(title: str) -> bool:
"""
タイトルにNGワードを含んでいないかを確認する
:param str title: イベントのタイトル
:return: True: 含んでいない(OK)、False: 含んでいる(NG)
"""
for word in NG_WORDS:
if word in title:
return False
return True | 1ae4e5bd4a205052d797ac7c242cbfe05b69bfcb | 72,949 |
import re
def trim_arn_to_name(arn: str) -> str:
"""
Extract just the name of function from full ARN. Supports versions, aliases or raw name (without ARN).
More information about ARN Format:
https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#genref-arns
"""
# Special ... | f0f02b0e965d245ef61942c7bfd5d7e91bcc5fff | 72,950 |
def param(nnet, Mb=True):
"""
Return number parameters(not bytes) in nnet
"""
neles = sum([param.nelement() for param in nnet.parameters()])
return neles / 10**6 if Mb else neles | 1121b19ffe63176d1f7f08345bc8295aa56a9a4c | 72,951 |
def paga(
adata,
solid_edges='confidence',
dashed_edges=None,
layout=None,
root=0,
groups=None,
color=None,
threshold=None,
threshold_solid=None,
threshold_dashed=None,
fontsize=None,
node_size_scale=1,
node_size_pow... | 4d4bb8ff24ab9a1e43605b54a4d94a193f009ec7 | 72,952 |
import mimetypes
import cgi
def _get_content_type(conn) -> str:
"""Pull out mime type from a connection.
Prefer explicit header if available, otherwise guess from url.
"""
content_type = mimetypes.guess_type(conn.url)[0] or ""
if hasattr(conn, "getheaders"):
content_type = dict(conn.gethea... | 22a093210fcebd5b080106b7484d6ff3b8dfee3a | 72,953 |
from typing import Any
from typing import Optional
def max_elevation_selector(_: Any, pass_: PredictedPass, left_range: Optional[DateTimeRange], right_range: Optional[DateTimeRange]) -> Optional[DateTimeRange]:
"""
This selection strategy selects the passes that have highest elevation during TCA.
"""
... | c33437faf4554093f5264a6815f22e1dfd44699b | 72,954 |
def basic_req(url: str, types: int, proxies=None, data=None, header=None, need_cookie: bool = False):
"""
requests
@types XY: X=0.->get; =1.->post;
Y=0.->html; =1.->json; =2.->basic; =3.->text;
"""
req_set(url)
result = None
if not types:
result = get_html(url, prox... | d1a8b6b8cae77042c9465c6db63451483cfc42d2 | 72,955 |
def get_disk(compute, project, zone, name):
"""Get info of disk in GCE
:param compute: GCE compute resource object using googleapiclient.discovery
:param project: string, GCE Project Id
:param zone: string, GCE Name of zone
:param name: string, GCE disk name
:return: GCE disk information
:r... | b139f0cbec91b4903c791fff557250e6762442aa | 72,956 |
import datetime as dt
import calendar
def _parse_date(row):
"""parse the date of a single row into datetime object."""
day_ix = 4; mon_ix = 5; year_ix = 6;
date = dt.date(int(row[year_ix]),
list(calendar.month_abbr).index(row[mon_ix]),
int(row[day_ix]))
del row[... | 51b3c86d98f2c7686b34fbae3dd1306e0f00f817 | 72,957 |
def iris_classifier(verbose=False):
"""Basic Decision Tree Classifier for Iris problem.
Based on: http://scikit-learn.org/stable/modules/tree.html
"""
# Load dataset:
iris = load_iris()
# Build and train classifier:
clf = tree.DecisionTreeClassifier()
clf = clf.fit(iris.data, iris.tar... | d6b015f0e0512863043ee79ed15623db1b7fe5cd | 72,958 |
def parse_dft_forces(outfile: str):
"""
Get forces from a pwscf file in eV/A
:param outfile: str, Path to pwscf output file
:return: list[nparray] , List of forces acting on atoms
"""
forces = []
total_energy = np.nan
with open(outfile, "r") as outf:
for line in outf:
... | c66d391b2b51fea59f862e8de9b309e7f7e13607 | 72,959 |
from mws.mws import MWSError
def clean_params_dict(params):
"""Clean multiple param values in a dict, returning a new dict
containing the original keys and cleaned values.
"""
cleaned_params = dict()
for key, val in params.items():
try:
cleaned_params[key] = clean_value(val)
... | e9759efa3ddf7d0d4e5ab3d9fed9846689e356db | 72,960 |
def pd_dt_concat(frames, axis=0):
"""
Concatenate sequence of datatable Frames or pandas DataFrames `frames` along `axis` (0 means rows, 1 means columns).
"""
if USE_DT:
if axis == 0:
return dt.rbind(*frames)
elif axis == 1:
return dt.cbind(*frames)
else:... | 54ea2b6bf442285c84068d9d79a859a4ed4b923f | 72,961 |
def _DetailedHelp(version):
"""Construct help text based on the command release track."""
detailed_help = {
'brief': 'SSH into a virtual machine instance',
'DESCRIPTION': """\
*{command}* is a thin wrapper around the *ssh(1)* command that
takes care of authentication and the translation of the
instance ... | 08b0046cf279e6577f27cb45869a9067adecbfc3 | 72,962 |
def shiny_gold_in(bag: str, rules: dict) -> bool:
"""Recursively check for shiny gold bags."""
if "shiny gold" in rules[bag].keys():
return True
elif not rules[bag]: # bag holds no others
return False
else:
for inner in rules[bag]:
if shiny_gold_in(inner, rules):
... | 1859f499b72a938a58a78af5ca1a78e9f7221731 | 72,963 |
def gen_featweight_worker(tup):
"""
Function to be parallelized by multiprocessing / joblib / whatever.
Must take in one argument to be used by multiprocessing.map_async
Args:
tup (aid, tuple(kpts(ndarray), probchip_fpath )): keypoints and
probability chip file path aid, kpts, probc... | 3722032f2ef21f259d5b73679567e467691726c2 | 72,964 |
def get_position_type(salary_plan):
"""
Given a salary plan code, map to one of the VIVO position types
"""
position_dict = {
'CPFI': 'postdoc',
'CTSY': 'courtesy-faculty',
'FA09': 'faculty',
'FA9M': 'clinical-faculty',
'FA10': 'faculty',
'FA12': 'faculty'... | eaaa64bfe35d27476eb9218d6401e0565126392d | 72,965 |
def asim_jac_edges(graph_premise, graph_hypothesis):
"""
Asymmetric Jaccard similarity between the edges of the definition graphs
:param graph_premise: the definition graph of the premise
:param graph_hypothesis: the definition graph of the hypothesis
:return: the ratio of overlapping edges per the ... | 41102b8cf7fa7f6b06595ded242997d6cef0627f | 72,966 |
import ast
import logging
def _generate_trees(filename, with_filenames=False, with_file_content=False):
"""
Generated trees.
:param filename: filename
:param with_filenames: boolean
:param with_file_content: boolean
:return: list of ast object
"""
trees = []
with open(filename, 'r... | 258ccfabebb4de21d971939dfa3369a4658bace4 | 72,967 |
def find_datasets(detector=None, type=None, host=api.DEFAULT_URL):
"""Find datasets available on the given GW open science host
Parameters
----------
detector : `str`, optional
prefix of GW detector
type : `str`, optional
type of datasets to restrict, one of ``'run'`` or ``'event'`... | a828797108bcf92d9bf1993bd57ab8a46a03da59 | 72,968 |
from typing import Iterable
from datetime import datetime
from typing import List
def _calculate_displayable_predictions(
fitted_formulas: Iterable[FittedFormula],
max_peak_distance: datetime.timedelta,
max_peak_variability: datetime.timedelta,
now: datetime.datetime,
) -> List[FittedFormula]:
"""... | f42cd4385c33ec68a83e8d0a5994acff821c15a6 | 72,970 |
import re
def cleanup(string):
"""
Cleans up pathway long-names for presentation.
:param string:
:return:
"""
string = re.sub("|", "", string) # vertical bar
string = re.sub("<[^<]+?>", '', string) # HTML tags
string = re.sub("\'", "", string) # remove quotes
return string | 02a66153cf92815f53acfb61edf58df9dd9a8752 | 72,971 |
import builtins
def is_builtin(name: str) -> bool:
"""return true if <name> could be considered as a builtin defined by python
"""
return name in builtins or name in SPECIAL_BUILTINS | 7dd7d770f728e8a57ac310ef257a3469307a341d | 72,972 |
def perkalian(matrix_a: list[list], matrix_b: list[list]) -> list[list]:
"""
>>> perkalian([[1,2],[3,4]],[[5,5],[7,5]])
[[19, 15], [43, 35]]
>>> perkalian([[1,2.5],[3,4.5]],[[5,5],[7,5]])
[[22.5, 17.5], [46.5, 37.5]]
>>> perkalian([[1, 2, 3]], [[2], [3], [4]])
[[20]]
"""
if _check_no... | 4b37e9c2a92e3c9f5a35c74169449f74627d95c8 | 72,973 |
def parser_config(p):
"""Graphical user interface runner."""
loader.parser_config(p)
p.add_argument('--iterations',
default=1,
type=int,
help='The number of iterations. 0=infinite')
return on_cmd | 8ea0c4e94320ac115d82ff0c32c1d04d381d57f9 | 72,974 |
def loads_state(string):
"""Loads the state from a string object. This does not import any
modules."""
return StateUnpickler(BytesIO(string)).load() | 24c330b9baecd3377a07648d8653a6d2da3a0b03 | 72,975 |
def construct_affine_vanishing_polynomial_Moore(field: Field, aff: AffineSpace) -> Poly:
"""Constructs a polynomial which vanishes over a given affine space."""
# pick a basis a_1, ..., a_d for the space
b = aff.basis
#construct Moore matrix with d+1 colums, The Moore matrix has successive powers of the Frobeni... | bdc8e9041432ed71cbfdc92fc4350b6089a591d6 | 72,976 |
def compose_postprocessing(prng, queries, epsilon, alg, **kwargs):
"""
The composed algorithm with postprocessing actually tested by StatP.
"""
algorithm = alg.algorithm
postprocessing = alg.postprocessing
new_kwargs = kwargs.copy()
del new_kwargs['_d1']
b = algorithm(prng, queries, epsi... | 1b132231c561463edfb37913ca0fe97ad7e13ee7 | 72,977 |
from typing import OrderedDict
def group_by(self, key, key_name=None, key_type=None):
"""
Create a :class:`.TableSet` with a table for each unique key.
Note that group names will always be coerced to a string, regardless of the
format of the input column.
:param key:
Either the name of a... | 104668b798dab4e989d377224d9fdbd4d9c6447e | 72,978 |
import math
def i4_sobol(dim_num, seed):
"""Generates a new quasirandom Sobol vector with each call."""
# Parameters:
#
# Input, integer DIM_NUM, the number of spatial dimensions.
# DIM_NUM must satisfy 1 <= DIM_NUM <= 40.
#
# Input/output, integer SEED, the "seed" for the sequence.... | c3c792b0537c28e95efbaeaadec6689d50765e46 | 72,979 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.