content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import List
def set_firewall_rule_ids_to_computer_command(client: Client, computer_id: int, rule_ids: List[int],
overrides: bool) -> CommandResults:
"""
Assign rule IDs to a certain computer.
Args:
client (Client): The Trend Micro API clie... | 58ac799738c8ce510cc30f1f6d5de26ad5e124d2 | 72,000 |
from datetime import datetime
import torch
def train(model, epochs, data, optimizer, criterion, device, logger):
""" Train NN """
epochs = epochs
steps = 0
running_loss = 0
print_every = 40
for e in range(epochs):
start_ts = datetime.now()
model.train()
for images, labe... | 92f5e8b9a7388de26a3369338c5ceed37ffea4ee | 72,001 |
def single_column_kernel(i, scale_sqrt=True):
"""Returns a kernel function with weights that correspond to a single column of the veps numpy.ndarray.
:param int i: column of which weights should be selected
:return: kernel function that linearly weights the genotypes with a single column of veps (e.g. corr... | 9fb5bbbf8bc5f86709a78924869030ac5398c749 | 72,002 |
def validate_data(data, root, shape_file_path, started=False, http_kwargs={}):
"""Validate a jsonld document against a shape.
Since PyLD requires an http url, a local server is started to serve the
document.
Parameters
----------
data : dict
Python dictionary containing JSONLD object
... | eae05b9078887bae5e2e7b568b90d6775710b76d | 72,003 |
def is_exists(t):
"""Whether t is of the form ?x. P x."""
return t.is_comb() and t.fun.is_const() and \
t.fun.name == "exists" and t.arg.is_abs() | 7f7c5f32685df636ec2181efd5a1b7dbc8313d4c | 72,004 |
from typing import Dict
from typing import Any
def get_amendments_for_year(year: int, bill_number: int) -> Dict[str, Any]:
"""See: http://wslwebservices.leg.wa.gov/legislationservice.asmx?op=GetAmendmentsForYear"""
argdict: Dict[str, Any] = dict(year=year, billNumber=bill_number)
keydict: Dict[str, Any] =... | 8866bd8bf00fee8431bb4eed9beb2716d7dc1d99 | 72,005 |
def generate_help():
"""Generates help text with alphabetically sorted recipes."""
help_text = '\nAvailable recipes:\n\n'
recipes = config.Config.get_registered_recipes()
for contents, _, _ in sorted(recipes, key=lambda k: k[0]['name']):
help_text += ' {0:<35s}{1:s}\n'.format(
contents['name'], cont... | 92451c52feb7610b8ceb4bbb562d04cec3415b4c | 72,006 |
def welch_statistic(sample_a, sample_b):
"""Calculates Welch's t statistic.
Takes a 2D data matrix, a column to classify data by, and the labels
corresponding to the data of interest. Assumes that the largest (-1)
column in the data matrix is the dependent variable.
Parameters
----------
d... | a6f937aebaa52709a9763e0dbb3d5b6946e69dfe | 72,007 |
def lookup(type, language, key):
"""
Get an object of a certain *type*, specified by the code for what
*language* it is in and its *key*. The types currently supported are:
`assertion`
Use the `id` as the key.
`concept`
Use the concept's raw name as the key.
... | 0bb71860882cb7f653a274ea083f56bdaa8b7438 | 72,008 |
import requests
import json
def login(request):
"""
Do OAUTH dance with GitHub (for sign in) and PyPI (for releasing
packages)
"""
# # Redir https
# if request.headers.get('X-Forwarded-Proto') is not None:
# if request.headers['X-Forwarded-Proto'] != 'https':
# return H... | bf12dc64dcf286fc3ff4bcef252d12c9eab05140 | 72,009 |
import numpy
def xy_field_grid_points_to_edges(field_matrix=None, x_min_metres=None,
y_min_metres=None, x_spacing_metres=None,
y_spacing_metres=None):
"""Re-references x-y field from grid points to edges.
M = number of rows (unique grid-poin... | 075977ced527458a84823e64d64ebbe05a8f2e14 | 72,010 |
def predict(samplerid):
"""
provides a prediction of the forward model at a set of given query
parameters
It expects a list of lists with n elements in the main list
corresponding to the number of queries and each element has d elements
corresponding to the number of parameters in the forward m... | cc65e566e3bb5bca754d1b5b47c7739cd371ec4a | 72,011 |
from typing import Optional
def all_history_date(
tickers: tuple[str, ...],
*,
start: Optional[pd.Timestamp] = None,
end: Optional[pd.Timestamp] = None,
bus: bootstrap.TableBus = bootstrap.BUS,
) -> pd.Index:
"""Перечень дат для которых есть котировки после проверки на наличие новых данных.
... | 21a84b7451a50db691a885d94e6b09efa8a28461 | 72,012 |
import zfused_api
import maya.cmds as cmds
def software_id():
"""
return zfused software id
"""
_softwares = zfused_api.zFused.get("software", filter = {"Name":"Autodesk Maya", "Code":"maya", "Version": int(cmds.about(version = True))})
if _softwares:
return _softwares[0]["Id"]
return... | 7ead0b78c54d122c6212dfb2ff9d519294ad4efe | 72,013 |
def is_in_poly(p, poly):
"""
:param p: [x, y]
:param poly: [[], [], [], [], ...]
:return: is_in: boolean. True = p in poly
"""
px, py = p
is_in = False
for i, corner in enumerate(poly):
next_i = i + 1 if i + 1 < len(poly) else 0
x1, y1 = corner
x2, y2 = poly[next_... | 00d46af2dc04c6d3c1d86db887d904abe17e3bdb | 72,014 |
from typing import Tuple
def InterpolateValue(x: float, xy0: Tuple[float, float], xy1: Tuple[float, float]) -> float:
"""Get the position of x on the line between xy0 and xy1.
:type x: float
:type xy0: Tuple[float, float]
:type xy1: Tuple[float, float]
:return: y
:rtype: float
"""
if ... | 9de4372b593fae65f772c19a8ac369315a8489d0 | 72,015 |
def max_bounded(max_func, bounds, *args, **options):
"""Finds the input value that maximizes `max_func`.
min_func: computes the function to be maximized
bounds: sequence of two values, lower and upper bounds of the
range to be searched
args: any additional positional arguments are passe... | 5056bd9b19acb2ea145cfa2ce6107ca9176eacae | 72,016 |
from typing import Tuple
from typing import Any
def v3_pos_to_position(v3_rep: Tuple[Any], hex_width: float, hex_depth: float) -> Position:
""" Maps from the Unity-given tuple representing the position to a Position.
Inputs:
v3_rep (Tuple[str]): The Unity representation of the position (x, y, z).
... | 6045afbb17e6e93fd06bb46f728194bceff6339f | 72,017 |
from typing import Dict
def bwt_transform(s: str) -> Dict:
"""
:param s: The string that will be used at bwt algorithm
:return: the string composed of the last char of each row of the ordered
rotations and the index of the original string at ordered rotations list
:raises TypeError: If the s param... | a206074307f0857cbe0e6e75d2101fc9b50d21e9 | 72,018 |
def facebook_share(context, label=None, css_class=None, icon_class=None,
**kwargs):
"""
Renders a 'Share' button to share content on Facebook.
Parameters:
- label: the text to show as button label.
- css_class: the class to apply to the button.
Keyword arguments:
... | 23be9f936c0f5a993b228bf1f0847cbb22791d3c | 72,019 |
def get_sliding_band(sym, lam_int, lam_ext):
"""Returns a list of surface in the airgap including the sliding band surface
Parameters
----------
sym: int
Symmetry factor (1= full machine, 2= half of the machine...)
Rgap_mec_int: float
Internal lamination mechanic radius
Rgap_me... | 65b67d8a22492d94cdd6d49fcc2a120a225be4d1 | 72,020 |
def get_subset_with_sum(a, n):
"""Returns a subset of a with sum equal to n (if exists)."""
dp = [[]] * (n + 1)
for i in range(len(a)):
for j in range(n, a[i] - 1, -1):
if j == a[i]:
dp[j] = [a[i]]
elif dp[j]:
continue
elif dp[j - a... | c9e2ba7b6ea3b33d839cdad3586ccd8717089ebf | 72,021 |
def blackbody_lambda(in_x, temperature):
"""Like :func:`blackbody_nu` but for :math:`B_{\\lambda}(T)`.
Parameters
----------
in_x : number, array-like, or `~astropy.units.Quantity`
Frequency, wavelength, or wave number.
If not a Quantity, it is assumed to be in Angstrom.
temperatur... | 8db191c843836a7bef4e8a82d1218120ba075f9c | 72,022 |
def op_wait(pc,lc,seconds,dummy,dummy2,rtime):
"""
waits for a number of seconds or on a previously set condition
seconds : wait time, or timeout if waiting for condition
"""
global condition,wtime
res = pc
if (condition == None):
# unconditional wait based on time
if wtime == 0:
wtime = rtime
if... | f72705ea0a6a229c8a247d6323f3712407f6ec62 | 72,023 |
def _safe_latex(to_fix):
"""Escape characters that make LaTeX unhappy.
"""
chars = ["%", "_", "&", "#"]
for char in chars:
to_fix = to_fix.replace(char, "\\%s" % char)
return to_fix | 166de7858b319d9e07f7e0ad67e293ca96da63ab | 72,024 |
import six
import json
def create_doc_obj(body):
"""Turn a message str into a |DocumentObj|.
Parses a message body, adds an ``_id`` field based on the document's
``@uuid`` field, and creates a |DocumentObj| from the result.
Parameters
----------
body : str
Returns
-------
|Docum... | 37ee7ac927909e51fd1fdd3de175364cfaaacd69 | 72,025 |
def _abs(u):
"""np.abs for AD array."""
if isinstance(u, ADI):
return u.abs()
else:
return np.abs(u) | f8820046cde6a999b64e2ac8c7817269ba88f35a | 72,026 |
def boolean(prompt=None, yes='y', no='n', default=None, sensitive=False,
partial=True):
"""Prompt for a yes/no response.
Parameters
----------
prompt : str, optional
Use an alternative prompt.
yes : str, optional
Response corresponding to 'yes'.
no : str, optional
... | 159c8be6004e4e9f2c5a271e36facd3610561b61 | 72,027 |
def get_tags_from_names(session,taglist):
"""Returns all tag objects with Tag.name in taglist.
"""
return session.query(Tag).filter(Tag.name.in_(taglist)).all() | 52a1db2eef1bb7ebf769d606698f107fbdfbf4e4 | 72,028 |
def top_token_set_ratio(values):
"""Return the best token set ratio match from fuzzywuzzy module."""
scores = []
for combo in combinations(values, 2):
score = fuzz.token_set_ratio(combo[0], combo[1])
tokens_0 = len(combo[0].split())
tokens_1 = len(combo[1].split())
if tokens_... | 084b86af527ca2832530c066883a49d7a69bf7ad | 72,029 |
def get_non_refinement_chain():
""" Create 3-level chain without class_decompose node """
node_scaling = PrimaryNode('scaling')
node_rf = SecondaryNode('rf', nodes_from=[node_scaling])
node_logit = SecondaryNode('logit', nodes_from=[node_scaling])
node_xgboost = SecondaryNode('xgboost', nodes_from=[... | 0504218d27d7c49146022cca57c5e5c9602c624d | 72,030 |
def get_auc(m, auc_limits):
"""Gustavo's method for generating uniformly distributed auc values.
Args:
m: (int) > 2, representing the number of base classifiers
auc_limits: (len(2) list, tuple, or ndarray, i.e. Sequence)
representing the (minimum AUC, maximum AUC) among the
... | b658fc028f69cc0c4f934e7176a6cfbd7738c661 | 72,031 |
def create_model(architecture, num_features):
"""
create uncompiled model with given architecture
NOTE: currently only the DeepSpeech model is supported. Other models can be added here
:param architecture: name of the architecture (see descriptions in argparse)
:param num_features: number of feature... | f33959efa568f898df3927e314fb3a8eac8a5ccb | 72,032 |
from pathlib import Path
def get_image_path(card_number):
"""
Return the full path of the image file on the server. This may be
used by printable templates.
"""
if card_number:
parts = get_image_parts(card_number)
# return os.path.join(settings.MEDIA_ROOT, *parts)
return Pa... | 7bc97c2272447aaea2dd0b36e78aa8a1e4d8241c | 72,033 |
def export_result_image(song: Song, chords_vocabulary: ChordVocabulary, midi: bool = True, tab: bool = True,
audio: str = 'CHF_2017', df: bool = True):
"""
Export visualisation to a png file.
:param song: Song for which we want to export the visualisation
:param chords_vocabular... | d0e404779eeaae4a963d37f24b6615796bdf1375 | 72,034 |
def arg_num_in_range(args, low, up):
""" check if low <= len(args) <= up """
return check_in_range(len(args), low, up) | b478d0b3aee1373e6a45b2f6339af005bf8a093c | 72,035 |
import time
def retry(exceptions=Exception, tries=4, delay=3, backoff=2, logger=None, silence: bool = False):
"""
Retry calling the decorated function using an exponential backoff.
Args:
exceptions: The exception to check. may be a tuple of
exceptions to check.
tries: Number o... | 24b61bd7634a75ad38ec35a878f1faf39bbbbd1a | 72,036 |
import json
def dumps(obj, **kwargs):
""" calls json.dumps using DateTimeEncoder """
return json.dumps(obj, cls=DateTimeEncoder, **kwargs) | 397b2efd2145a894582532fd20f9e0631caa34d5 | 72,037 |
def parse_image_meta(meta):
"""Parses an image info Numpy array to its components.
See compose_image_meta() for more details.
"""
image_id = meta[:, 0]
image_shape = meta[:, 1:4]
window = meta[:, 4:8] # (y1, x1, y2, x2) window of image in in pixels
active_class_ids = meta[:, 8:]
return... | 9c5099351b6a63be3a2e7b62464b846db8fe3836 | 72,038 |
import unicodedata
import re
def slugify(value):
"""
URL to filename
Normalizes string, converts to lowercase, removes non-alpha characters,
and converts spaces to hyphens.
"""
val = unicodedata.normalize('NFKD', value).encode('utf-8', 'ignore')
val = val.decode()
val = re.sub(r'[^\w\s... | 028d6800c87932c61c18fc2ec09d5d97ad3fd399 | 72,039 |
def make_html(email_dict: dict) -> MIMEText:
"""
Function that makes html text portion of message, including placeholders for inline images
@param email_dict: output of make_email_dict, a dict with the email body text as a key, the images to attach as values
@returns: HTML encoded email text
""... | 4ea2885d0381419ebec5d05c144445ce2de1cb2e | 72,040 |
def kernel(t):
""" 畳み込みカーネル """
return np.exp(-t / 20) - np.exp(-t / 10) | b5b4085681b6e84f25072863e04f09e6cdf72ed0 | 72,041 |
def scoring_function(context_features, example_features, mode):
"""A feed-forward network to score query-document pairs."""
with tf.compat.v1.name_scope("input_layer"):
context_input = [
tf.compat.v1.layers.flatten(context_features[name])
for name in sorted(context_feature_columns())
]
e... | edae314eb09e896028d9c8334fdaa1fb92733c0f | 72,042 |
def _not_(x: symbol) -> symbol:
"""
>>> isinstance(not_(symbol(True)), symbol)
True
>>> not_.instance(True)
False
"""
return not x | 6961757837cfbfeb134e7b932dd48d7fcc9d070a | 72,043 |
import torch
def compute_local_cost(pi, a, dx, b, dy, eps, rho, rho2, complete_cost=True):
"""Compute the local cost by averaging the distortion with the current
transport plan.
Parameters
----------
pi: torch.Tensor of size [Batch, size_X, size_Y]
transport plan used to compute local cost
... | 3d29e8ae5ef14ab30cd676eebeb6507e9cbfafca | 72,044 |
def discretenorm(K,mu,sig):
"""
Discrete approximation of normal density with N bins, mean mu and
standard deviation sigma.
"""
pts = np.linspace(mu-3*sig, mu+3*sig, K)
space = pts[1]-pts[0]
probs = st.norm.cdf(pts+space/2, loc=mu, scale=sig) - st.norm.cdf(pts-space/2, loc=mu, scale=sig)
... | f3bd2178ed8c7e171c54426726e100c8869b07f0 | 72,045 |
from typing import Sequence
def domain_concatenated_no_4gc(seq: str, seqs: Sequence[str]) -> bool:
"""prevent {G,C}^4 under concatenation"""
for altseq in seqs:
catseq = altseq + seq + altseq
strength = catseq.translate(_binaryGCTable)
if '1111' in strength:
return False
... | 9a11a67fbdddefc7b1b5b44eed8ec701f7d92a76 | 72,046 |
def delete_item(id:int, db: Session = Depends(get_db)):
"""This functions takes the id delete the required item """
existing_item = db.query(models.Item).filter(models.Item.id == id).delete()
if not existing_item :
return("Item Does Not Exist ")
db.commit()
return("Item del... | b63c0078794f28fef9b07c9024fed21287dfeb34 | 72,047 |
def convert_file(source_file, to, format=None, extra_args=(), encoding='utf-8',
outputfile=None, filters=None, verify_format=True):
"""Converts given `source` from `format` to `to`.
:param str source_file: file path (see encoding)
:param str to: format into which the input should be conve... | 2ed89f9c7cdedcffc45b7e028c9377e192eaaf12 | 72,048 |
def make_polynomial_mmd_evaluation(degree=3, theta=None):
"""Make a Polynomial MMD evaluation function
See coresets.kernels.PolynomialKernel for a description the polynomial
kernel parameters.
Parameters
----------
degree : int, optional
theta : float, optional
Returns
-------
... | 20452374dc9dbe681a9d5b256683ae4010bdf2d1 | 72,049 |
def geocode(query, limit=None):
"""Convenience function to query Address objects for a text string and return a subset of the
queryset object values.
"""
qs = Address.objects.filter(address_text__search=query)
resp = []
if limit:
qs = qs[0:limit]
for address in qs:
resp.appen... | 8e8fd4f771867a35808b741a2ec6378237ddbc3d | 72,050 |
from typing import Callable
from typing import List
async def create_and_add_event_emitters(
hass: HomeAssistant, entry: ConfigEntry, is_emitter: Callable[[Device], bool],
) -> List[HubitatEventEmitter]:
"""Create event emitters."""
hub = get_hub(hass, entry.entry_id)
devices = hub.devices
emitter... | 9f54bf2d0884851ffaf6f9206cc7a5dbfa142d37 | 72,051 |
def polar(fmla,pos,pol):
""" Return the polarity of the `pos` argument of `fmla` assuming the
polarity of `fmla` is `pol`. The polarity indicates the
number of negations under which the formula occurs. It is 0 for an
even number, one for an odd number and None if the formula occurs
under both an eve... | 944db348e22739b598fff686803b23cfe935086f | 72,052 |
import numpy
def Mat3Vec3Mult(mat3, vec3):
"""Performs elementwise Mat3-Vec3 multiplication."""
return numpy.einsum('lij,lj->li', mat3['d'], Vec3ToArray(vec3)) | e10d3f2eca1e1623b29f34a9269186dd0942d08c | 72,053 |
def multipolygon_to_polygon(geometry): # TODO: Deprecated?
"""
If object is a Polygon, returns the object unmodified.
If object is a Multipolygon, returns its biggest(in area) polygon.
This means this function gives only 1 polygon for each country.
This will have to be fixed later.
"""
if i... | 3e139c5f21a588d64fbd9f635ddb808824a240ad | 72,054 |
def minutes_to_seconds(minutes:str)->int:
""" Converts minutes to seconds """
return int(minutes)*60 | a4aa5851749cf8081a8f49b1a1b7eb136e2bb372 | 72,055 |
def open_default_resource_manager(library):
"""This function returns a session to the Default Resource Manager resource.
Corresponds to viOpenDefaultRM function of the VISA library.
Returns
-------
VISARMSession
Unique logical identifier to a Default Resource Manager session
constants.... | ab6cb802e09d9e60fcf32ee3ab4ccb53960e2c6e | 72,056 |
import torch
def warp_from_NormMap2D(x, NormMap2D):
"""
warp an image/tensor (im2) back to im1, according to the optical flow
x: [B, C, H, W] (im2)
flo: [B, 2, H, W] flow
"""
B, C, H, W = x.size()
# mesh grid
vgrid = NormMap2D.permute(0, 2, 3, 1).contiguous()
output = nn.functi... | d4d429b72fe1949f8d5de9bde85b841845479057 | 72,057 |
def jd_corr(jd,
ra,
dec,
obslon=None,
obslat=None,
obsalt=None,
jd_type='bjd'):
"""Return BJD_TDB or HJD_TDB for input JD_UTC
BJD_TDB = JD_UTC + JD_to_TDB_corr + romer_delay
where:
JD_to_TDB_corr is the difference between UTC... | cc4912e8f221caa595e8e08588b3ab7ee0ee8050 | 72,058 |
import time
def timeit(method=None, *, wargs=False):
"""takes method and wraps it in a timer"""
if method is None:
return partial(timeit, wargs=wargs)
log = LogMixin()
@wraps(method)
def timed(*args, **kw):
ts = time.time()
result = method(*args, **kw)
te = time.t... | 6a9de69bf51d5aba452ff577585760793322f0a0 | 72,059 |
def api_machine_num(val: int) -> None:
"""Set available number of machine/node for running job .
Args:
val (int): available number of machines
"""
return enable_if.unique([machine_num, do_nothing])(val) | b0749b41b5afd7d418d91739927fd1cf1df1b528 | 72,060 |
def common_modulus_attack(c1: int, c2: int, e1: int, e2: int, n: int) -> int:
"""
This functionw will carry out the common modulus attack.
:param c1: Ciphertext integer 1.
:param c2: Ciphertext integer 2.
:param e1: encryption exponent 1.
:param e2: encryption exponent 2.
:param n: The modulus n.
:return: The ... | cc3f94a99638c8519ea2a39446451269c82b15ac | 72,061 |
def fragmentation_heuristic(board):
"""Estimates how fragmented the board is.
This works because we'd get the same total cost if
we would remove each zone individually.
"""
zones = get_zones(board)
num_zones = len(zones)
if num_zones == 0:
return 0
color_counts = defaultdict(i... | 02ac9e770423d9f6179201479c71a3de40500812 | 72,062 |
import math
def normal_approximation_to_binomial(n, p):
"""finds mu and sigma corresponding to a Binomial(n, p)"""
mu = p * n
sigma = math.sqrt(p * (1 - p) * n)
return mu, sigma | 6c25d1009df6f15fa413ab561af2e58ba831cfab | 72,063 |
def read_data(filename, sep=",", aFilter=int):
"""
Data format(ith line): label_i,x_i1,x_i2,...x_id
"""
def split_line(line):
return line.split(sep)
def process_line(line):
return map(aFilter, split_line(line))
with open(filename) as f:
lines = map(process_l... | 40a4c1fda3bce6e70acef0b72971b99dd4507b9a | 72,064 |
def get_vision_sensor_image():
"""
Purpose:
---
This function should first get the handle of the Vision Sensor object from the scene.
After that it should get the Vision Sensor's image array from the CoppeliaSim scene.
Input Arguments:
---
None
Returns:
---
`vision_sensor_image` : [ list ]
the imag... | ac6470c0f7d4f4f8226060f99e110fbf8b16a0bf | 72,065 |
def get_presets(global_presets, groups):
"""Returns a dictionary of presets merged with the referenced preset
Presets define a direct acyclic graph by including the `preset` property, so
this function validates that there are no cycles and that all referenced presets
are defined.
In the output, pres... | 068c639f16c8711da7ef7ccd1bd7e34fdb018153 | 72,066 |
import io
async def import_books_csv(file: UploadFile = File(...)):
"""import `Book`s from csv file"""
session = Session()
df: pd.DataFrame = pd.read_csv(
io.StringIO(UnicodeDammit(file.file.read()).unicode_markup)
).replace({np.nan: None})
logger.info(f"shape: {df.shape}")
df = df[
... | b4de9cda2b14e77477e2d94d26dde511aa781e81 | 72,067 |
def string_array(array):
"""
Make a numpy array a space separated string
"""
return " ".join(map(str, array)) | beaa9b8e8911454409be2c4e255b919f9e379635 | 72,068 |
def get_docs(log, yaml_editor, yaml_file):
"""Get all documents from a YAML/JSON/Compatible file."""
docs_loaded = True
docs = []
if yaml_file != "-" and not isfile(yaml_file):
log.error("File not found: {}".format(yaml_file))
return ([], False)
for (yaml_data, doc_loaded) in Parse... | 3b82236e850660803da4e66742ff726a07e14ca1 | 72,069 |
def generateSplitEnvs(
train_df,
valid_df,
test_df,
window_size,
steps_per_episode,
feature_columns,
reward_type=REVENUE_REWARD,
max_final_reward=1,
max_step_reward=0,
num_parallel_environments=1,
position_as_observation=True,
constant_step=False,
is_training=True,
... | 3f5a71addd569999ebb2827392b33d6e610674b4 | 72,070 |
from typing import List
from typing import OrderedDict
def _analyze_class(ctx: 'mypy.plugin.ClassDefContext',
auto_attribs: bool,
kw_only: bool) -> List[Attribute]:
"""Analyze the class body of an attr maker, its parents, and return the Attributes found.
auto_attribs=Tru... | ae5085cf883e3ecbbb6a9e32e596b23602364724 | 72,071 |
def get_player_colour(player):
"""
Decide the colour of a plot element based on the freeze-frame player's
team and position.
"""
if player['teammate']:
return 'pink'
if not player['teammate'] and not is_gk(player):
return 'skyblue'
if is_gk(player):
return 'green' | b7ba5d9fce7c8acd8a5cb352381fd68b5889134f | 72,072 |
def _dict2df(to_plot_dict:dict, meta_key:str) -> pd.DataFrame:
"""Transform a dictionary into a DataFrame for catplotting"""
to_plot_df = []
for range, values in to_plot_dict.items():
range_grouped = []
for ds in values:
values_ds = values[ds].to_frame(name="values")
... | 562f9bbe1c8c021b484b6b553dacbdb2d7218611 | 72,073 |
def orthonormalize_axes(xaxis, yaxis):
"""Corrects xaxis and yaxis to be unit vectors and orthonormal.
Parameters
----------
xaxis: [float, float, float] | :class:`~compas.geometry.Vector`
The first axis.
yaxis: [float, float, float] | :class:`~compas.geometry.Vector`
The second axi... | 717c4feb940d59874c9880f735c09d929407a074 | 72,074 |
def _binary_expression(
value, to_camel_case, serial_field_relations, level_limits, bidirectional
):
""" _binary_expression
it is probably a relationship
NOTE: Not used here,
but prop.entity.all_orm_descriptors
is access to related column
"""
if hasattr(value, "prop"):
... | 04718f295e4796914c0550e17abf8f8926978bb8 | 72,075 |
def electron_binding_energy(charge_number):
"""Return the electron binding energy for a given number of protons (unit
is MeV). Expression is taken from [Lunney D., Pearson J. M., Thibault C.,
2003, Rev. Mod. Phys.,75, 1021]."""
return 1.44381e-5 * charge_number ** 2.39\
+ 1.55468e-12 * char... | 6d5a845b1b11720b44b62500f979f0a621faca0a | 72,076 |
from datetime import datetime
def new_task_to_run(request, task_slice_index):
"""Returns a fresh new TaskToRun for the task ready to be scheduled.
Returns:
Unsaved TaskToRun entity.
"""
assert 0 <= task_slice_index < 64, task_slice_index
created = request.created_ts
if task_slice_index:
created =... | 0e849dd215351760bc110d937c20b43e6827c61a | 72,077 |
def policy_gradient(*, policies, actions, action_values):
"""
https://github.com/deepmind/trfl/blob/master/docs/trfl.md#policy_gradientpolicies-actions-action_values-policy_varsnone-namepolicy_gradient
"""
actions = jax.lax.stop_gradient(actions)
action_values = jax.lax.stop_gradient(action_values)
... | 6903e8be60f89e722ead6fdb4e6fe139b2054eb3 | 72,078 |
from .base import Kit
def Celery(module_name, path=None):
"""Returns the Celery application registered for the module.
:param module_name: the module name for which to get the application.
Typically, this should always be set to ``__name__``.
:type module_name: str
:param path: the path to the overall ki... | c47dd9c86f59b48ce3f5c2e68c926149c4cfbca2 | 72,079 |
def year_filter_from_year(year):
"""Generate a filter for year based on a year."""
filter_field = "original_release_date"
filter_string = f"{filter_field}:{year}-1-1 00:00:00|{year}-12-31 23:59:59"
LOG.debug(f"Year filter is {filter_string}.")
return filter_string | 9207933897a6850e8d5006b49a4d8746e2607446 | 72,080 |
def grid1d(dist: float, L: int, parms: list[float] = None) -> np.ndarray:
"""
generate 1D grid
Parameters
----------
dist: float
one-way distance from origin (meters)
L: int
number of cells
Returns
-------
x: np.ndarray
1D vector grid
"""
xmin = -... | 75c3f9cf12f8cab30a7a06363f7273f0bd6746d1 | 72,081 |
import pylab
from matplotlib import gridspec
import arrview
import os
def view(dicoms, groupby=tuple(), roi_filename=None, roi_tag=None, viewer=None, viewer_kws=None):
"""Display a dicomset with arrview
Parameters
==========
dicoms : iterable of dicoms
An iterable of dicoms
groupby
... | d1c3c7c3c8e53a444ec8a294fac6798fea10c75c | 72,082 |
def autodoc_skip_member(app, what, name, obj, skip, options):
"""Which members the autodoc should ignore."""
if _no_autodoc:
return True
if name.startswith("_") and name != "__init__":
return True
return False | c8bb804d55f97dc6fa2dca16b1cddc3c17ab24bd | 72,083 |
import math
import numpy
def rquaternionu(u, theta):
"""Returns a quaternion representing the right handed rotation of theta
radians about vector u. Quaternions are typed as Numeric Python
numpy.arrays of length 4.
"""
u = normalize(u)
half_sin_theta = math.sin(theta / 2.0)
x = u[0] * ha... | b8e852378d98b51e156d4a4889bec68bb858c410 | 72,084 |
def ctsim_drsa_cal(Model_RDMs, RDMs, method='spearman'):
"""
Calculate the Cross-Temporal Similarities between temporal model RDMs and temporal neural RDMs (dynamic-RSA)
Parameters
----------
Model_RDMs : array
The Coding Model RDMs.
The shape should be [n_ts, n_cons, n_cons]. n_ts... | 136a72910d9ed7a737e6fe9f92496319977f50d9 | 72,085 |
def madmom_1(filename, reference_beats_filename):
"""
Estimates beats using reference beats and the `DBNBarTrackingProcessor` provided
with madmom:
S. Bock, F. Korzeniowski, J. Schlüter, F. Krebs, and G. Widmer, “Madmom: A new Python Audio and Music
Signal Processing Library,” in P... | 41fc14d19fed3f7416a30219e4c26d6f1437471a | 72,086 |
import requests
import html
def login(username: str, password: str) -> TransperthSession:
"""
:returns: a session object with login cookies attached
"""
logger.info('Authenticating...')
s = requests.Session()
r = _login(s, username, password)
doc = html.document_fromstring(r.text)
m... | 0e7a419eec4dca86465bbc3618cd731ea0b4a4e6 | 72,087 |
import re
def urlencode_paths(path):
"""Urlencode some paths before forwarding requests."""
for rule_regex in SPECIAL_ROUTE_REGEXES:
m = re.search(rule_regex, path)
if m:
return '{leading}{before}{match}{after}{trailing}'.format(
leading=m.group(1),
... | c6aa0dbffe4ea69fd017fcadfe61f3b07e1be2fa | 72,088 |
def add_to_mechfile(location=None, box=None, name=None, box_version=None, add_me=None,
use_me=None, provider=None, windows=None):
"""Add entry to the Mechfile."""
LOGGER.debug("name:%s box:%s box_version:%s location:%s add_me:%s use_me:%s "
"provider:%s windows:%s", name, bo... | db719bc6bf2ac7073ccdf3d1e02fe61ed7ba3400 | 72,089 |
def executedf():
"""
Executes df command
Returns:
lOutput = [
{
sName :'partition1',
iBlocksTotal :1234,
iBlocksUsed :1000
iBlocksAvailable:234
iPercent :90
sMountpoint... | 13fef095a7104c1d3ab94c2a1cb6c005e1b9f897 | 72,090 |
def recall(y_true,y_pred):
"""Recall metric.
Only computes a batch-wise average of recall.
Computes the recall, a metric for multi-label classification of
how many relevant items are selected.
"""
true_positives = K.sum(K.round(K.clip(y_true * y_pred,0,1)))
possible_positives = K.sum(K.round(K.clip(y_true,0,1)... | 84fe5f3a68cc1df0bdc956813442068245e6879c | 72,091 |
def pad_image(img, size, smooth=None):
"""
Pads image to new_length x new_length and pads with black.
Only works with grayscale right now.
Arguments:
- smooth (float/None) : sigma value for Gaussian smoothing
"""
if np.max(img.shape) > size:
resize_factor = float(size) / np.max(im... | 7cf850e7ed76e17637ffa92c7e32b18297596d12 | 72,092 |
def L(x, gamma):
"""Return Lorentzian line shape at x with HWHM gamma"""
return gamma / np.pi / (x**2 + gamma**2) | cbae0d5f37ae24e3ab22900f6433806e3faa7110 | 72,093 |
from matplotlib.patches import Circle
from matplotlib.collections import PatchCollection
import numpy as np
import matplotlib.pyplot as plt
def circles(x, y, s,ax, c='b',vmin=None, vmax=None, **kwargs):
"""
Make a scatter of circles plot of x vs y, where x and y are sequence
like objects of the same leng... | 69481fa7c0a6e0e78d795598130a633d1b9dabdf | 72,094 |
import warnings
import torch
def load_from_openmmlab(filename, map_location=None):
"""load checkpoint through the file path prefixed with open-mmlab or
openmmlab.
Args:
filename (str): checkpoint file path with open-mmlab or
openmmlab prefix
map_location (str, optional): Same as :... | 02b079ebf2c4cb0f18f700ae098d3c9e80cc7d3a | 72,095 |
def __dict_to_pod_spec(spec):
"""
Converts a dictionary into kubernetes V1PodSpec instance.
"""
spec_obj = kubernetes.client.V1PodSpec()
for key, value in iteritems(spec):
if hasattr(spec_obj, key):
setattr(spec_obj, key, value)
return spec_obj | 0e84fb28217c35f9897fc33ccdbdadee1800e100 | 72,096 |
def pca(X,Y,k):
"""Count accuracy of PCA method
Parameters
----------
X : array
A 2-d array with the entropy and godel numbering
Y : array
The value of the class
k: int
K-mer value
Returns
-------
The accuracy of the pca method in RandomForestClassifier.
"""
# te... | 547fe123e579badad8e63d798b7f0c4bfdf1b191 | 72,097 |
def gumbel_softmax_sample(logits, tau=1, eps=1e-10):
"""
NOTE: Stolen from https://github.com/pytorch/pytorch/pull/3341/commits/327fcfed4c44c62b208f750058d14d4dc1b9a9d3
Draw a sample from the Gumbel-Softmax distribution
based on
https://github.com/ericjang/gumbel-softmax/blob/3c8584924603869e90ca7... | 2d17c4e14153d98074266cb1007ec5889fff5a29 | 72,098 |
def cross3(left, right):
"""Numpy is inefficient for this
Args:
left (3x0 array): left term of the cross product
right (3x0 array): right term of the cross product
"""
return np.array([[left[1] * right[2] - left[2] * right[1]],
[left[2] * right[0] - left[0] * right[... | a77e1d719c07722537f10a5232c9bf8282ac0c6b | 72,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.