content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def is_complete(p):
"""
Determine if the logged optimization was completed
"""
l = find_line(p, "Optimization Done")
return l is not None | 7575793e95d9225b99580f512c0490f5ca42bc2b | 3,603,725 |
def in_top_k(predictions, targets, k):
"""Returns whether the ``targets`` are in the top ``k`` ``predictions``.
# Arguments
predictions: A tensor of shape batch_size x classes and type float32.
targets: A tensor of shape batch_size and type int32 or int64.
k: An int, number of top eleme... | 2b0af6ec66e135bf9a93174af0cbf7d43ab07ee7 | 3,603,727 |
def hoop_thickness(P_i, P_o_min, D_o, sig_y_d):
"""Return the minimum (note not nominal) wall thickness for internal pressure
containment.
Considers:
- Allowable hoop stress
- Worst case maximum pressure difference
- Appropriate wall thickness theory, i.e. thick or thin
:param float P_i: I... | 20317e1fceafe10c24ad877c7d5160cf179960a0 | 3,603,728 |
from typing import List
from typing import Tuple
def mix_encoding_pairs(encodings: List[np.ndarray],
encodings_name: List[str]) \
-> Tuple[np.ndarray, List[str]]:
"""
Mixes each elements of the encodings two by two, by adding the encodings
together and returning them, with their resul... | 4d47af1c6523ecf469edc183026dbad22039fa10 | 3,603,729 |
def remove_stopwords(words, stoplist):
""" Remove stop words
Parameter arguments:
words = list of words e.g. ['.', 'The', 'boy', 'is', 'playing', '.']
return:
list of tokens
['boy', 'is', 'playing']
"""
return [token for token in words if not (token.startswith(PUNCT) or token in stoplis... | 9ab9ee2b44ce5e73c5545991deb45118903dd6ba | 3,603,730 |
def norm_matrix(R):
"""Normalize rotation matrix.
Parameters
----------
R : array-like, shape (3, 3)
Rotation matrix with small numerical errors
Returns
-------
R : array, shape (3, 3)
Normalized rotation matrix
"""
R = np.asarray(R)
c2 = R[:, 1]
c3 = norm_v... | c4b4ebef51fa315d655dd7d599b583ae18d512b3 | 3,603,731 |
def DMux8Way(i: Bit, s: Bus3) -> Bus8:
"""
8-way demultiplexor
{a, b, c, d, e, f, g, h} = {in, 0, 0, 0, 0, 0, 0, 0} if sel == 000
, {0, in, 0, 0, 0, 0, 0, 0} if sel == 001
, ...
, {0, 0, 0, 0, 0, 0, 0, in} if sel == 111
```
+------------------+--+ i
| | ... | 63f2d91a54cc220e79289fe045ebd2db763a1548 | 3,603,732 |
def get_args() -> Namespace:
"""Method to create and configure a argument parser"""
parser: ArgumentParser = ArgumentParser(prog='python osc_tools.py',
formatter_class=RawTextHelpFormatter)
subparsers = parser.add_subparsers(title='These are the available OSC com... | 0dc76cec968adc1b0a119a4edd2ff47a67c247c5 | 3,603,733 |
def padding_attention_mask(from_tensor, to_mask, *, dtype):
"""Create 3D attention mask from a 2D tensor mask.
Args:
from_tensor: A Tensor of shape [batch_size, heads, from_seq_length, to_seq_length].
to_mask: int32 Tensor of shape [batch_size, to_seq_length].
Returns:
float Te... | b929376254529644e71fd9ddc371240dc1eaab08 | 3,603,736 |
def get_model_parallel_group():
"""Get the model parallel group the caller rank belongs to."""
assert _MODEL_PARALLEL_GROUP is not None, \
'model parallel group is not initialized'
return _MODEL_PARALLEL_GROUP | 5372c3662c4a3907326b52237594e941d8dc0935 | 3,603,737 |
import numpy
def blackBodySpectrum(TemplateSpectrum=None, **kwargs):
""" Returns a blackbody function over the given wavelength """
"""
inputs:
wl : wavelength array
Assumed to be in units of cm, unless specified by wlUnits kwarg
nu : frequency array
... | e99dc61e250744f2b39184999f42690206637f15 | 3,603,738 |
def calculate_fracture_starting_position(shape, seed):
"""Choose a random starting position along the x or y axis (random choice).
Parameters
----------
shape : tuple of int
Number of rows and columns in the grid
seed : int
Seeds the random number generator, so that a particular ran... | 8d69180624cf4afc9c51258e12fd1e34b0d1d10c | 3,603,739 |
def two_way_merge(array1, array2):
"""
Given two sorted arrays, merge them into a single sorted array.
This is a very simple operation but is a precursor to k-way merge.
We compare each element at the beginning of each array and remove smaller one and add it to the merged array.
If one of the array... | 6d1a4779634809b7ff63159928af668596f5c00e | 3,603,740 |
import torch
def fake_image_tensor(H, W, C) -> torch.Tensor:
""" Fake image tensor """
torch.manual_seed(0)
return torch.rand(C, H, W) | 3cf09924a856ff46240804c6f4ceea65ce70410c | 3,603,741 |
def wavelength_to_energy(wavelength: float):
"""Conversion from photon wavelength (angstroms) to photon energy (eV)"""
return 1.2398 / wavelength * 1e4 | fc067b9fd9cae68103742e8998b6aa0117d906d0 | 3,603,743 |
def openTypeOS2TypoDescenderFallback(info):
"""
Fallback to *descender*.
"""
return getAttrWithFallback(info, "descender") | 740f32214fc5396c7272810225d4408300afb167 | 3,603,744 |
def parser_add_optgroup_from_def(parser, defn, exclusive=False, prefix=None):
"""Add an entire option group from a definition in a custom format
Parameters
----------
parser : argparser instance
defn : tuple
Option group spec. Complicated beast. Grep source code for syntax examples.
exclu... | 08cf69d9374389508f0b104e972d17942aec6c27 | 3,603,745 |
import pathlib
def featurizer(tmpdir):
"""Generate a featurizer for tests."""
node_storage = LocalModelStorage(pathlib.Path(tmpdir))
node_resource = Resource("sparse_feat")
context = ExecutionContext(node_storage, node_resource)
return CountVectorsFeaturizer(
config=CountVectorsFeaturizer.... | b7461a8ab23523ff418b332eab5ad96dc404ac6f | 3,603,746 |
def compute_content_cost(a_C, a_G):
"""
Computes the content cost
Arguments:
a_C -- tensor of dimension (1, n_H, n_W, n_C), hidden layer activations representing content of the image C
a_G -- tensor of dimension (1, n_H, n_W, n_C), hidden layer activations representing content of the image G
R... | 139f71dc038d143d1de4738d4d0646322256ba71 | 3,603,747 |
import random
def generate_graph(rule_dict, rule_list):
"""
Create a new graph from the VRG at random
:param rule_dict: List of unique VRG rules
:return: newly generated graph
"""
node_counter = 1
# non_terminals = set()
non_terminals = {} # now a dictionary, key: non-terminal id, va... | 68cd97b56958266d7b9ba65571a9146b021de89f | 3,603,748 |
from typing import List
def get(sp: str, *args, **kwargs) -> List[List[int]]:
"""Wrapper function for sparsity patterns
Args:
sp (str): type of sparsity pattern, e.g.,
- 'diag' -- Diagonal matrix
- 'dense' -- Dense matrix
- 'nodiag' -- Dense without main diagonal e... | 3636f2f7d3c83724eb1bafb832f464e8b4d1e3cf | 3,603,749 |
from typing import Iterable
def iterate(iterable, progress_bar=None, text='', echo=1, echo_items=False):
"""
:type iterable: Iterable
:type progress_bar: ProgressBar
:type text: str
:type echo: bool or int or ProgressBar
:type echo_items: bool or list[str]
:rtype: Iterable
"""
return Iterable(inner=list(iter... | 261edb6bb841b89a3248c7ab3530a55d385fcce0 | 3,603,750 |
def chebgrid3d(x, y, z, c):
"""
Evaluate a 3-D Chebyshev series on the Cartesian product of x, y, and z.
This function returns the values:
.. math:: p(a,b,c) = \\sum_{i,j,k} c_{i,j,k} * T_i(a) * T_j(b) * T_k(c)
where the points `(a, b, c)` consist of all triples formed by taking
`a` from `x`,... | 01a07cddcacd9fbe7564ff3edc83d1bab8f13f2a | 3,603,751 |
def gen_wind_speed(interval):
"""
Generate the wind speed graph.
:params interval: update the graph based on an interval
"""
total_time = get_current_time()
df = get_wind_data(total_time - 200, total_time)
trace = go.Scatter(
y=df["Speed"],
line={"color": "#42C4F7"},
... | 375c4fccbf6e942a6f2a6b24fbc92343fe3921eb | 3,603,753 |
import string
import random
import logging
def random_pass():
"""Function to create random RDS database password"""
try:
letters = string.ascii_letters
numbers = string.digits
special_chars = string.punctuation
dummy_phrase = (''.join(random.choice(letters + numbers + special_... | b6aaf00069a269e09b2d8d96251741c54709bffa | 3,603,754 |
from typing import Callable
from typing import Any
def is_empty_() -> Callable[[Observable[Any]], Observable[bool]]:
"""Determines whether an observable sequence is empty.
Returns:
An observable sequence containing a single element
determining whether the source sequence is empty.
"""
... | 9dc1f2e0de088d2026293943b53a81f3ce3680ef | 3,603,755 |
def api_burst_call(request):
"""API burst call"""
if request.method == 'POST':
if request.user.is_authenticated():
now = timezone.now()
lastcall = request.user.profile.lastcall
if now - timezone.timedelta(days=5) > lastcall:
if now.weekday() == 4 or no... | 6d253c43f3fd67b9845d7f563b80938063694023 | 3,603,757 |
def query_header_jwt_required(fn):
"""
A decorator to protect a query resolver.
If you decorate an resolver with this, it will ensure that the requester
has a valid access token before allowing the resolver to be called. This
does not check the freshness of the access token.
"""
@wraps(fn)... | a483617ffd73a20978bcce3b13c36f0f05d32845 | 3,603,758 |
import threading
def concurrent_map(func, data):
"""
Similar to the bultin function map(). But spawn a thread for each argument
and apply `func` concurrently.
Note: unlike map(), we cannot take an iterable argument. `data` should be an
indexable sequence.
"""
N = len(data)
result = [... | 5fb482055699087ca7f7b3b95b7d8c425894882f | 3,603,759 |
from typing import Dict
from typing import Any
def _node_type_from_group_spec(
group_spec: Dict[str, Any], is_head: bool
) -> Dict[str, Any]:
"""Converts CR group spec to autoscaler node type."""
if is_head:
# The head node type has no workers because the head is not a worker.
min_workers ... | 950d74fec20bf61c42e1497df5d168a55d7eb71b | 3,603,760 |
def pack_quotes(quotes, **kwargs):
"""
:param quotes: a list of BeautifulSoup tags containing quotes, and quote details
:return: a dictionary of packaged quotes
"""
packed_quotes = {}
for group in quotes:
raw = group.select_one(kwargs.get('quotetag'))
raw_quote = raw.string
... | 011382f79572fedd0c40f10952d71c77ba25ae37 | 3,603,761 |
def handleRespReadMultHR(payload):
""" Handles a MODBUS response of multiple holding registers reading (fn code 3). """
values = payload[1:]
tmp = []
while True:
try:
req = READ_QUEUE["HoldingRegister"].pop(0)
value = int.from_bytes(values[:2], byteorder="big")
... | eb4ee35b9fbb0b4f9b076b07848cafe95acddea5 | 3,603,763 |
def van_vleck_weisskopf(νeval, ν, γ, δ):
"""Complex Van Vleck-Weisskopf line shape function.
νeval GHz frequency at which line shape is evaluated
ν GHz center frequency of line
γ GHz width parameter of line
δ - overlap parameter of line
Returned value is u... | f2f221196fbe911d4582cfc74bf260bb87ce7db0 | 3,603,764 |
def exists_management_key_with_priority_zero(
active_management_keys, new_management_keys, management_keys_to_revoke
):
"""
Checks if a management key of priority zero would be present if the management keys will be updated according
to the given parameters.
Parameters
----------
active_man... | e4bff322bf4cb9d4b6ccc002f277a5af63e993e4 | 3,603,765 |
from typing import Tuple
from typing import Dict
from typing import Any
def multiview() -> Tuple["MultiViewMount", ComponentConstructor]:
"""Dynamically add components to a layout on the fly
Since you can't change the component functions used to create a layout
in an imperative manner, you can use ``mult... | 3ce29da959f1e692a0e0754d3d585130551b1bd3 | 3,603,766 |
import glob
def create_df():
"""Return a Pandas Dataframe containing the path to every Garmin
.TCX file and its date in the local time zone---instead of the UTC
time standard."""
lst_files = glob.glob(path_to_garmin_files + '*.tcx')
lst_dates = [get_date_from_filename(f) for f in lst_files]
df... | 085be3b525c85653a4e61bef262bb5999962974e | 3,603,767 |
def get_str_volume_list():
"""Return a list of string representations of all volumes."""
return [volume.string_representation for volume in get_volume_list()] | 1fc5fa33ea180ef3967732e61420e0a8ba24d362 | 3,603,768 |
import numpy
def create_empty_trace(trace, channel):
"""
Utility to create an empty trace, similar to another trace.
Parameters
----------
trace: obspy.core.Trace
Trace that is source of most metadata, including array length.
channel: String
Channel name for created Trace.
... | 46f90f7ac79683a1e34cbd0340c5787941951fcc | 3,603,769 |
import re
def is_valid_username(field):
"""
Checks if it's an alphanumeric + underscore, lowercase string, at least
two characters long, and starts with a letter, ends with alphanumeric
"""
return re.match(r"[a-z][0-9a-z_]*[a-z0-9]$", field) is not None | b4c870951715e103d58d1187703276dbb21e84cf | 3,603,772 |
def distance_from_earth(R, z, theta, Rsun=8.2*u.kpc):
"""Convert radii, height and angle to a distance to the Earth using trig.
Parameters
----------
R : `float/array`
Galactocentric radius
z : `float/array`
Height above Galactic plane
theta : `float/array`
Azimuthal ang... | e134caf8b9121b51f74cb1179b22c1696f6bb40d | 3,603,774 |
from typing import List
from typing import Tuple
def calculate_mark(data: List[Tuple[str, float]], weight: float) -> float:
""" Returns the average of all the marks in data with weights
:param: data: the List of entries of data. Each entry is in the form
(description, mark)
:weight: the weight of... | 49f911894f73515ff0073b29b83ee2cb95c02e10 | 3,603,776 |
from typing import OrderedDict
def transform_container_group(result):
"""Transform a container group to table output. """
return OrderedDict([('Name', result['name']),
('ResourceGroup', result['resourceGroup']),
('Status', _format_status(result)),
... | 2ccd013e8f645563481624b3076251a9cacdb4a0 | 3,603,777 |
def optional_interfaces(args, *interfaces):
"""Return a tuple with possible optional interfaces
:param args: a list of reactive interfaces
:param *interfaces: list of strings representing possible reactive
interfaces.
:returns: [list of reactive interfaces]
"""
return args + tuple(ri fo... | 33fc406fc93559d955793c18e9ee146c789ca587 | 3,603,778 |
import math
def weight(name, shape, init='he', range=None):
""" Initializes weight.
:param name: Variable name
:param shape: Tensor shape
:param init: Init mode. xavier / normal / uniform / he (default is 'he')
:param range:
:return: Variable
"""
initializer = tf.constant_initializer()... | 9762ecf2e38acf0960e0c22b65bc0676c684e856 | 3,603,779 |
def list_available_drivers(device_address=None):
"""
Returns a list of known drivers/packages for qwiic devices.
:param device_address: A list with an I2C address or addresses. If no value
was given, the I2C bus will be scanned and the address(es) of the
connected qwiic devi... | 1df8633d0db9b5b5f997ee810bce1cbe7c78da4d | 3,603,780 |
from donkeycar.parts.controller import get_js_controller as get_controller
def get_js_controller(cfg):
"""
myconfig.py上にて指定されたCONTROLLER_TYPE値にあわせて
ジョイスティックコントローラパーツを生成し、
オブジェクトを返却するファクトリ関数。
引数:
cfg config.py/myconfig.py にて指定された定義をインスタンス変数として
参照できるオブジェクト
戻り値
ctr ジョイ... | 5d63b67a2bceb23332599dd7402ca191891fe0c3 | 3,603,781 |
def rowSum_A(X, norm = False):
"""
[Added 22/10/2018]
Computes rowSum**2 for dense array efficiently, instead of using einsum
"""
n = len(X)
s = 0
for i in range(n):
s += X[i]**2
if norm:
s **= 0.5
return s | cd6b147fb171094d3a4a2e77c1d5e63b07a6e560 | 3,603,782 |
def get_shorthands(flat_search_config):
""" Convert flattened keys to shorthand notations for serialization str.
"""
shorthands = {}
for k in flat_search_config:
if not any(k.endswith(s) for s in RESERVED_SUFFIXES):
route = k.split(ROUTE_STR)
shorthand = ''
fo... | 74ec79dba294621c64e37427996d8382abba8212 | 3,603,783 |
import re
def get_name(view):
"""
Return a name for the view.
If view has a name attribute, use that, otherwise use the view's class name, with 'CamelCaseNames' converted to 'Camel Case Names'.
"""
# If we're looking up the name of a view callable, as found by reverse,
# grok the class insta... | 8cd2848d0166da45da4ee01e62c81bedd3a2067a | 3,603,784 |
import hashlib
def md5hash(fname):
"""Get md5 hash of a file using hashlib"""
hash_md5 = hashlib.md5()
with open(fname, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest() | fb0c1a7c79a5d9d6101aca9cd13f56fd914c457e | 3,603,785 |
def Rx(t):
"""
Generates the unitary rotation matrix about the X axis on the Bloch sphere.
"""
Sx = np.array([[0, 1], [1, 0]])
return expm(-1j * t * Sx / 2.0) | 5c3db7c663b3f97e08ea9f2be85e373cf8bd70f8 | 3,603,786 |
def _jit_rouse_homologs(N, N_tot, tether_list, loop_list, L, b, D, Aex, rx, ry,
rz, t, t_save, x0=None):
"""
"Inner loop" of rouse_homologs.
Some typing stuff: needs N, N_tot as int, needs tether_list/loop_list as
dtype == int64, and uses loop_list.shape[0] to get num_loops. Thi... | 53e6e54edd59bf385f98977f3e847103e3388eba | 3,603,787 |
def simplest_clique():
"""
Answer to "what is the simplest clique".
"""
return render_html("The simplest clique is an edge.") | d49217d7d627d6ff15c16bf0d2cbb6dd93d23acc | 3,603,788 |
def all_bits_list(vals, width=16):
"""Convert list of values into a list of bits in those values"""
return flatten_list([to_bit_list(val, width) for val in vals]) | 76a780ac78e423b9d2d6a691a87bec4e5fdb892c | 3,603,789 |
import math
def find_divisors(n):
"""
Find divisors of n
"""
#div = []
count = 0
sqrt_n = int(math.sqrt(n))
if sqrt_n**2==n:
count += 1
#div.append(sqrt_n)
for d in range(1, sqrt_n):
if n%d==0:
#div.append(d)
#div.append(n//d)
... | 8d6d0406024dae195c0f13db60e0a65bee93dd6c | 3,603,790 |
from ooiservices.app.uframe.status_tools import get_uid_digests
def build_uid_cache():
""" Force update of asset information.
"""
try:
uid_digests = get_uid_digests(refresh=True)
print '\n Completed compiling uid digests information.'
print '\n Number of digests: ', len(uid_digests... | 7f1e073b9018b8e89185ed11bb17cdb7fd9800e2 | 3,603,791 |
import numpy
def _diff_rasters(
a_raster_path, b_raster_path, target_diff_raster_path):
"""Calculate a-b.
Args:
a_raster_path (str): raster A, same nodata and size as B
b_raster_path (str): raster B
target_diff_raster_path (str): result of A-B accounting for nodata.
Retur... | 7f926861d80478b1773fc16188957f68935eb9ad | 3,603,792 |
def df_dx_func(x_id, s_x, corn_x, A):
"""
Computes derivatives to make the bicubic interpolation
When a query point is in the left or rightmost bin of the x axis, it
automatically ignores the knots that would have gone outside array
boundaries in the computation (this is done by a mask and tf.where,... | d3ed05359444960f59b0e3bbda4f8c3c68501aaa | 3,603,793 |
import random
def power_method(A, niter, y0=None, random_state=None):
"""Power iteration method. Definition 5.12."""
y0 = random.get_start_vector(d=A.shape[0], y0=y0, random_state=random_state)
x0 = nolina.normalise(y0)
for _ in range(niter):
y0 = A @ x0
sigma = -1 if np.dot(y0, x0) < ... | be3953630ec977d13dbd9724e5d17cae7b91be3b | 3,603,794 |
def _has_all(series, values, exclusive=False):
""" Returns the index of rows from series containing all of the given
values.
Parameters
----------
series : pandas.Series
The data to be queried
values : list-like
The values to be tested
Returns
-------
index : panda... | 805df8708d7e00ecbaf76ebdd99ce599e0ea004c | 3,603,797 |
import importlib
def load_plugin(name):
"""
:param name:
"""
return importlib.import_module(f"plugins.{name}", ".").run | 5631f51672dd8a4597a49b4336584e769577ff09 | 3,603,798 |
def sfn_execute(session, name, input_={}):
"""Start executing a StepFunction
Args:
session (Session): Boto3 session
name (str): Name of the StepFunction to execute
input_ (Json): Json input data for the first state to process
Returns:
(str): ARN of the state machine executi... | 65d469ee281fc952ff51f9341f2b8b5da3be8764 | 3,603,799 |
def exchange_ecYeast(s1, subystem):
"""
this function is used to define the exchange reaction
s1=['a --> b','a <=> c', 'H+ [extracellular] + L-citrulline [extracellular] <=> H+ [cytoplasm] L-citrulline [cytoplasm]', ' a--> ']
subsystem = ['a','a','b','']
"""
for i, x in enumerate(s1):
p... | 0f8eb84b3270c910acd673491238d52b2744f68c | 3,603,800 |
import traceback
def search(user: User, start_time, end_time, date, room_id):
"""
返回座位列表
:param user:
:param start_time:
:param end_time:
:param date:
:param room_id:
:return:
"""
try:
search_json = user.search_seat(start_time, end_time, date, room_id)
if search... | 643c4cd79a47a03c7427f5b1d78e09f2642634cf | 3,603,801 |
import functools
def _check_length(func):
"""Wrapper which checks the length of inputs to set_X
Eg:
@_check_length
def set_X(self, group, values):
Will check the length of *values* compared to *group* before proceeding with
anything in the *set_X* method.
Pseudo code for the check:
... | 8d6f6e0a082472f4eb58c3246717266508a95e3c | 3,603,802 |
from typing import Optional
def get_in_reply_to(event: nio.Event) -> Optional[str]:
"""
Pulls an in reply to event ID from an event, if any.
"""
return event.source.get("content", {}).get("m.relates_to", {}).get("m.in_reply_to", {}).get("event_id") | 2331b2b8eff59c1f9c36af2ad5f3ce3def571e10 | 3,603,803 |
def readResults(file_name, _start_time, _end_time):
"""Read micro-data from file_name, structured on a separate line per year. In particular, read from start_year until
end_year, both inclusive"""
# Read list of float values, one per household
data_float = []
with open(file_name, "r") as _f:
... | 4ca6bb102b0605d3472430725a8349fa891dd247 | 3,603,804 |
def move_and_check_if_over(game: GameBoard, current_player: Player,
move: Move) -> Player:
"""
This method is invoked from the main Game Runner utility to perform
a move selected by the Current player and check if this move opted by
the user gave him a winning board.
In o... | 84fc7bd05caab51d456dff61e4d61ebf57dd57fc | 3,603,805 |
async def get_research_by_player(keys, context):
"""Get researches."""
where, values = compound_where(keys, ('match_id', 'player_number'))
query = """
select name, started::interval(0), finished::interval(0), player_number, match_id,
extract(epoch from started)::integer as started_secs, extr... | 0468786e1d08e46bcbcbf59e471e5117454049cd | 3,603,806 |
import requests
def create_client(hostname, port, reauth=False, logins=[]):
"""Create Docker client
Args:
-----
reauth: (boolean) Forces reauthentication e.g. Docker login
"""
base_url = "tcp://{0}:{1}".format(hostname, port)
try:
client = docker.APIClient(base_url=base_url)
... | a17e4672f0bc58d2512cc5c8d82d2be5cdf2b9c3 | 3,603,808 |
def pendulum_duration_from_isodate_duration(dur: IsodateDuration) -> Duration:
"""
Converts a :class:`isodate.isoduration.Duration` into a
:class:`pendulum.Duration`.
Both :class:`isodate.isoduration.Duration` and :class:`pendulum.Duration`
incorporate an internal representation of a :class:`dateti... | 9ed2ab0ce6dcddafdd3b7bb1933209eed85bd8f1 | 3,603,809 |
import time
def compute_perplexity(model, sess, name, eval_handle):
"""Compute perplexity of the output of the model based on loss function."""
def aggregate_all_summaries(original, updates):
for key in updates:
if key not in original:
original[key] = 0.0
original[key] += updates[key]
... | 126b6e87b9c700289438eccec3301f9416d3ae1d | 3,603,810 |
def array_pack(img):
"""
img: numpy array. I primarily use this for OpenCV images
"""
d = img.tobytes()
s = img.shape
t = img.dtype
return (s, t, d) | e01398caf1018000d0dabd776945a223e39b130b | 3,603,811 |
def new_gauge(name):
"""
Build a new "gauge" metric
"""
return new_metric(name, simple_metrics.Gauge) | 7452fe823a7b72beb8cf877012c1849558b03ca7 | 3,603,812 |
def create_cons_seq(seq: str, df_vcf: pd.DataFrame) -> str:
"""Create consensus sequence given a reference sequence and a table of a Snippy vcf_to_tab
Args:
seq: Reference sequence
df_vcf: VCF file DataFrame
Returns:
Consensus sequence
"""
segments = []
prev_position = ... | 7db0116574ea7965f064d030a6d00ce580da66a6 | 3,603,813 |
from typing import Dict
from typing import List
def get_notice_tokens() -> Dict[str, List[str]]:
"""Tokenised Covid notices."""
run_id = sg_covid_impact.config["flows"]["notice_tokens"]["run_id"]
return flow_getter("NoticeTokeniseFlow", run_id=run_id).docs | 645e460488d9fdc03048fabaa2d0baf1ea0d94fc | 3,603,814 |
import torch
def run_test_adversarial(net, loader, epsilon):
"""
This function is responsible to evaluate the model robustness against an FGSM attack on the given data loader.
Args:
net: a CNN model.
loader: a pytorch data loader that load either validation or test set samples
epsi... | 0ba78d792a5a0322095b76dae476f91243fb2fb9 | 3,603,815 |
def _build_rotation_dataset(imfiles, imshape=(256,256), batch_size=256,
num_parallel_calls=None, norm=255,
num_channels=3, augment=False,
single_channel=False):
"""
"""
ds = _image_file_dataset(imfiles, shuffle=True, augment=augment,
... | 87a748829578b7c44979554f4b329765906640b8 | 3,603,816 |
def get_taxes(tu):
""" Calculates taxes by running taxcalc on a tax unit DataFrame.
Args:
tu: Tax unit DataFrame.
Returns:
Series with tax liability for each tax unit.
"""
return mdf.calc_df(records=tc.Records(tu, weights=None, gfactors=None),
# year doesn't ... | 6ece3d327c18b00f8470c8e4b8e09444327ae80e | 3,603,817 |
def getref():
"""Current default values for graph and component tables, primary area,
and wavelength set.
.. note::
Also see :func:`setref`.
Returns
-------
ans : dict
Mapping of parameter names to their current values.
"""
ans=dict(graphtable=GRAPHTABLE,
... | 91671bde04c8e60f1d2af2da1a28cc35adb96a49 | 3,603,818 |
def _normalize_type(the_type):
"""
A single entry point for parsing the type.
This assumes that enums and optional properties have been
taken care of.
Parameters
----------
the_type : str
The type string extracted from the docs
Returns
-------
norm_type : str
T... | 3a6ac79bb655fc3aa2751f1c1a179d8a95082229 | 3,603,819 |
import yaml
def kv_string2dict(s):
"""Convert a key-value string: k=v,k2=v2,... into a dictionary
"""
return yaml.load(s.replace(",", "\n").replace("=", ": ")) | 78380d6735dc139afe5879aee7d25e5adf7d7e0d | 3,603,820 |
def auto_histogram(x, **histogram_opts):
"""Auto version of :func:`~xyzpy.histogram` that accepts array arguments
by converting them to a ``Dataset`` first.
"""
return AutoHistogram(x, **histogram_opts)() | 8a1e4e52669bed58f0603fca7f00e729bd1d25f1 | 3,603,821 |
def test_idempotent_persistence_exception_getting(
persistence_store,
lambda_apigw_event,
timestamp_future,
lambda_response,
hashed_idempotency_key,
expected_params_put_item,
):
"""
Test idempotent decorator when lambda is executed with an event with a previously unknown event key, but
... | 0d82bd10d2560096b907e54316863ca3dc6384f7 | 3,603,822 |
def select_number(list_of_numbers):
"""The player select *one* number of a list of numbers"""
answer = ""
while ((not answer.isdecimal()) or int(answer) not in list_of_numbers):
answer = input("Please type selected number and press ENTER: ")
return int(answer) | af91b18508ff361b0524a551949aac7d93f9afc6 | 3,603,823 |
def compose_context_fst(ifst1, ifst2, connect=True, compose_filter="auto"):
"""Composes context FST with an FST over the tropical semiring.
Args:
ifst1 (StdContextFst): The input context FST over the tropical semiring.
ifst2 (StdFst): The input FST over the tropical semiring.
connect (b... | 8dfc0f1ba01d42ca10ab1965dd5e2f491182396d | 3,603,824 |
def welcome():
"""最简单的接口
"""
return 'Hello World' | 5ae25fb699343bb48cdf113dc783a37290b3c38a | 3,603,825 |
def create_mel_filterbank(sample_rate, frame_len, num_bands, min_freq,
max_freq, crop=False):
"""
Creates a mel filterbank of `num_bands` triangular filters, with the first
filter starting at `min_freq` and the last one stopping at `max_freq`.
Returns the filterbank as a matrix... | c7c1b46e2d092128db42dce1a58e80b1be735e9d | 3,603,826 |
import numpy
def _time_zone_string_to_utc_offset(time_zone_string):
"""Converts time zone from string to UTC offset.
:param time_zone_string: String describing time zone (examples: "PST",
"MST", etc.).
:return: utc_offset_hours: Local time minus UTC.
"""
time_zone_string = time_zone_stri... | 063622222372c8eeb7f69e1240058088ef65fa2f | 3,603,827 |
import logging
def uc_exp(params, inputFilesFormatString):
"""Universal circuit creation.
params should be a tuple containing (inputLength, numberOfGates)
"""
inputLength, numberOfGates = params
logging.warning('Starting UC generation for %d inputs and %d gates' % params)
ioGen = IndistinguishabilityObfuscat... | b728bb6464e33b025ec54004edc0ec2658a32041 | 3,603,828 |
def cast(s):
""" Function which clarifies the implicit type of
strings, a priori coming from csv-like files.
Example
-------
>>> cast('1')
1
>>> cast('1.')
1.0
>>> cast('1E+0')
1.0
>>> cast('1E+1')
10.0
>>> cast('one')
'one'
>>> cast('One')
'one'
"""
... | 5e2c9b3b913a733608cab614ae0f08421e489196 | 3,603,829 |
def is_macosx_sdk_path(path):
"""
Returns True if 'path' can be located in an OSX SDK
"""
return (path.startswith('/usr/') and not path.startswith('/usr/local')) or path.startswith('/System/') | 59b60fa00bf6dd10cf207e6421ea3e4828de5b9c | 3,603,830 |
import math
def _mean_standard(dist):
"""Find the mean and standard deviation."""
# In the dist dictionary, the key is the value of the metric and
# the value is the number of times it appears. So, the sample
# value is the key and the number of samples for the value is the
# value in dist for th... | 3d90807a619b6fe090571a3f07db807e60c3849c | 3,603,832 |
def load_data():
"""Load data from the CSV files referundum/regions/departments."""
referendum = pd.read_csv("data/referendum.csv", sep=';')
regions = pd.read_csv("data/regions.csv", sep=',')
departments = pd.read_csv("data/departments.csv", sep=',')
return referendum, regions, departments | a16073711331e70fe969fd060e7ff0cacaf6e0b6 | 3,603,833 |
def VolumeDensity(imge, R, z):
"""
Calculates the volume density of an MGE at given position (R,z).
INPUTS
imge : intrinsic MGE, must be given as an astropy Table or QTable
R : intrinsic R, should have the same units as MGE widths
z : intrinsic z, should have the same units... | f81a32d13e390bc95aaa2ee3d2854c316e912922 | 3,603,834 |
def compatible_features(current):
"""Fuzz compatible features header field."""
constraints = [
[(0, UINT64_M)]
]
return selector(current, constraints, bit_validator) | 97d2e17fb3cba1a0fef2133d8f2159a5ede65994 | 3,603,835 |
def is_port_provisioned(context, port_id, host_id=None):
"""Checks if a port is already known to EOS
:returns: True, if yes; False otherwise.
:param port_id: globally unique port ID that connects VM to network
:param host_id: host to which the port is bound to
"""
filters = {
'port_id'... | 1d4dba306471ed462d9791502043fe3fa4b66ad5 | 3,603,836 |
def shift2d(x,w,a,b):
"""Shift a 2d quadrature rule to the box defined by the tuples a and b"""
xs=[[a[0]],[a[1]]]+x*[[b[0]-a[0]],[b[1]-a[1]]]
ws=w*(b[0]-a[0])*(b[1]-a[1])
return xs,ws | 84c2090cc0e1689a79aa2c7fa40fb399bc03f535 | 3,603,837 |
def _get_initial_policy_state(policy, time_steps):
"""Gets the initial state of a policy."""
batch_size = (tf.compat.dimension_at_index(time_steps.discount.shape, 0) or
tf.shape(time_steps.discount)[0])
return policy.get_initial_state(batch_size=batch_size) | 122a0a5e2f846a44a63a789e13050b7171d8d936 | 3,603,838 |
def create_cube(base_query, dimensions, measures):
""" Return cube from give base query, dimensions and measures. """
return aa.Cube(
base_query=base_query,
resolve_table_name="Flight Route",
storage="Full",
dimensions=dimensions,
measures=measures,
) | ed77295cd00b827a0f1ff356e474b47b9e5df1be | 3,603,839 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.