content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def mask_finished_scores(score, flag):
"""
If a sequence is finished, we only allow one alive branch. This function aims to give one branch a zero score
and the rest -inf score.
Args:
score: A real value array with shape [batch_size * beam_size, beam_size].
flag: A bool array with shape ... | 5,302,500 |
def get_user(url: str, access_key: str) -> Dict[str, Any]: # pylint: disable=unused-argument
"""Execute the OpenAPI `GET /v1/users`.
Arguments:
url: The URL of the graviti website.
access_key: User's access key.
Returns:
The response of OpenAPI.
Examples:
Get informat... | 5,302,501 |
def streamers_alter_workers(streamers):
"""
Alter the number of workers currently in a cluster
RouteParams:
"""
streamers = int(streamers)
account = request.form['account']
user = request.form['user']
spot = request.form.get('spot') is not None
if streamers != 1 and streamers != ... | 5,302,502 |
def get_default_scaler(model_type):
"""
Get default values for scaler in and output for each model.
Args:
model_type (str): Model identifier.
Returns:
Dict: Scaling dictionary.
"""
if model_type == 'mlp_e':
return EnergyStandardScaler()
elif model_type == 'mlp_eg':... | 5,302,503 |
def key_gen():
"""
Generate (but not store) a generic (passwordless) SSH keypair,
e.g. to use in CI/CD.
"""
# Generate the keypair
print("\nGenerating keypair ... ", end="")
private_key = PrivateKey.generate()
public_key = private_key.get_public_key()
print("Done.")
# Copy priv... | 5,302,504 |
def read(file_name: str) -> str:
"""Helper to read README."""
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, file_name), encoding="utf-8") as f:
return f.read() | 5,302,505 |
def test_list_batch_change_summaries_with_pending_status(shared_zone_test_context):
"""
Test listing a limited number of user's batch change summaries with approvalStatus filter
"""
client = shared_zone_test_context.shared_zone_vinyldns_client
group = shared_zone_test_context.shared_record_group
... | 5,302,506 |
def test_unicode_method_name(executed_docstring_source):
"""
>>> class TestCase:
... def test_unicode_method_例子(self):
... pass
"""
assert_that(executed_docstring_source.allure_report,
has_test_case("test_unicode_method_例子")
) | 5,302,507 |
def get_correlation(arg1,arg2=None):
"""Return correlation
The input arguments may be a pair of uncertain numbers,
or a single uncertain complex number.
When a pair of uncertain real numbers is provided,
the correlation between the arguments is returned as
a real number.
W... | 5,302,508 |
def _extractDicomMetadata_old(dcmdata, water_suppressed=True):
""" Extract information from the nibabel DICOM object to insert into the json header ext.
Args:
dcmdata: nibabel.nicom image object
Returns:
obj (hdr_ext): NIfTI MRS hdr ext object.
"""
# Extract required metadata and c... | 5,302,509 |
def rotmat2d(theta: float) -> np.ndarray:
"""Convert angle `theta` (in radians) to a 2x2 rotation matrix."""
s = np.sin(theta)
c = np.cos(theta)
R = np.array([[c, -s], [s, c]])
return R | 5,302,510 |
def test_encode_timestamp(value: int, suffix: bytes, should_pass: bool):
""" Unit test for encode_timestamp. """
if should_pass:
print('value', value)
assert timestamp.encode_timestamp(value) == suffix
else:
with pytest.raises(ValueError):
timestamp.encode_timestamp(value... | 5,302,511 |
def start_game(player_data: ActorData):
"""
Create a new game and show the gamemap
"""
# create clean snecs.world
empty_world = snecs.World()
world.move_world(empty_world)
# init and save map
game_map = GameMap("cave", 10)
store.current_game_map = game_map
# populate the map
... | 5,302,512 |
def Vector(size, dtype='float32', name=None): # pylint: disable=invalid-name
"""A block that converts its input to a vector."""
return Tensor(shape=[size], dtype=dtype, name=name).set_constructor_name(
'td.Vector') | 5,302,513 |
def render_correlation_single_heatmaps(
itmdt: Intermediate, plot_width: int, plot_height: int, palette: Sequence[str]
) -> Tabs:
"""
Render correlation heatmaps, but with single column
"""
tabs: List[Panel] = []
tooltips = [("y", "@y"), ("correlation", "@correlation{1.11}")]
for method, df... | 5,302,514 |
def test_macrons(sro, syllabics):
"""
Test that macrons can be converted
"""
assert sro2syllabics(sro) == syllabics
assert syllabics2sro(syllabics, produce_macrons=True) == sro | 5,302,515 |
def get_blocks(text):
"""
Get a traversed README doctree
Args:
text: Text of the example's README
Returns: Returns an iterable containing the README document structure
See `traverse` implementation in docutils/nodes.py for more details.
"""
doctree = publish_doctree(text)
... | 5,302,516 |
def get_feature_geojson(features):
"""convert input clip_features to list of clip_features in the
geojson format.
Parameters
----------
features : str (shapefile path) or list of clip_features
If clip_features is a list, the clip_features can be in shapely polygon
or wkt format (e.g... | 5,302,517 |
def bridge_bigquery(context):
"""
Define the structures and metadata to perform bridge load
"""
context.vault_structure_type = "bridge"
context.hashed_columns = {
"STG_CUSTOMER_ORDER": {
"CUSTOMER_PK": "CUSTOMER_ID",
"CUSTOMER_FK": "CUSTOMER_ID",
"ORDER_... | 5,302,518 |
def app():
""" The main UI and application """
header()
logging.info('Header created!')
body()
logging.info('Body created!')
footer()
logging.info('Footer created!') | 5,302,519 |
def args_combinations(*args, **kwargs):
"""
Given a bunch of arguments that are all a set of types, generate all
possible possible combinations of argument type
args is list of type or set of types
kwargs is a dict whose values are types or set of types
"""
def asset(v):
if isinstanc... | 5,302,520 |
def coordinate_tensor(dim):
"""
:param dim: list of lengths for each dimension
:return: a list of every possible coordinate within the dimension system
"""
# recurrent function
def recurrent_dim_filler(dim_current, dim_higher, coordinate_higher, coordinates):
# processing the lowest di... | 5,302,521 |
def help(context, cmd=None):
"""Documentation"""
if cmd == None:
print __doc__
for c in sorted(cmdset.keys()):
print ' %s \t%s' % (c,cmdset[c].__doc__)
print "\nSee 'jink help COMMAND' for more information on a specific command."
elif cmd in cmdset:
c = cmdset[cmd]
print 'jink-%s\t%s'... | 5,302,522 |
def save_full_array(arr, name, image=False):
"""
saves FULL array (mean curvature array)
Parameters
----------
arr : array of Z, Y, X curvatures??
name : filepath, str
image : boolean, Default = False
Returns
-------
none, just saves pickle file in correct indicated location
... | 5,302,523 |
def get_relation_injectivity_df(
*,
dataset: Dataset,
parts: Optional[Collection[str]] = None,
add_labels: bool = True,
) -> pd.DataFrame:
"""
Calculate "soft" injectivity scores for each relation.
:param dataset:
The dataset to investigate.
:param parts:
Only use certai... | 5,302,524 |
def vimeval(cmd, to_int=0):
"""
:to_int:
0 for original
1 for int
2 for float
"""
r = vim.eval(cmd)
if to_int == 0:
return r
if to_int == 1:
return int(r)
return float(r) | 5,302,525 |
def RGBStringToList(rgb_string):
"""Convert string "rgb(red,green,blue)" into a list of ints.
The purple air JSON returns a background color based on the air
quality as a string. We want the actual values of the components.
Args:
rgb_string: A string of the form "rgb(0-255, 0-255, 0-255)".
Returns:
... | 5,302,526 |
def test_layer_1_aggregated():
"""test_layer_1_aggregated
1層目の集計テーブルのカラムとデータが抽出出来ているかのテスト
"""
data_list = [
"only_solver",
"normal_data",
"normal_data_order",
"only_other",
"cg_iter"
]
for file_name in data_list:
data_path = f"/../test_dat... | 5,302,527 |
def preprocessing(df, deduplicate=False):
"""
Split the `sen_tok` column into sentence ID (combined with note ID) and token ID.
If the `deduplicate` parameter is True, duplicate notes are removed.
"""
if deduplicate:
df = deduplicate_notes(df)
return df.assign(
sen_id = lambda df... | 5,302,528 |
def change_alias(conn, hosted_zone_id, name, type, new_alias_hosted_zone_id, new_alias_dns_name, identifier=None, weight=None, comment=""):
"""Delete and then add an alias to a zone. identifier and weight are optional."""
from boto.route53.record import ResourceRecordSets
changes = ResourceRecordSets(conn,... | 5,302,529 |
def get_files_involved_in_pr(repo, pr_number):
"""
Return a list of file names modified/added in the PR
"""
headers = {"Accept": "application/vnd.github.VERSION.diff"}
query = f"/repos/{repo}/pulls/{pr_number}"
r = utils.query_request(query, headers=headers)
patch = unidiff.PatchSet(r.cont... | 5,302,530 |
def csv(file_path):
"""Read CSV file, return DataFrame"""
return pd.read_csv(file_path) | 5,302,531 |
def _metric_value(value_str, metric_type):
"""
Return a Python-typed metric value from a metric value string.
"""
if metric_type in (int, float):
try:
return metric_type(value_str)
except ValueError:
raise ValueError("Invalid {} metric value: {!r}".
... | 5,302,532 |
def point_sample_raster(gdf, rds, win_radius=0, stat_func=np.mean, col_names=None):
"""
Sample all bands of a raster data set `rds`, and attribute each point of
a geopandas GeoDataFrame `gdf`. A radius value can be supplied to sample
the mean of a square window rather than individual pixels.
Parame... | 5,302,533 |
def vol_spherical_cap(height: float, radius: float) -> float:
"""
Calculate the Volume of the spherical cap.
:return 1/3 pi * height ^ 2 * (3 * radius - height)
>>> vol_spherical_cap(1, 2)
5.235987755982988
"""
return 1 / 3 * pi * pow(height, 2) * (3 * radius - height) | 5,302,534 |
def im2col(input_data, filter_h, filter_w, stride=1, pad=0):
"""
Parameters
----------
input_data : (データ数, チャンネル, 高さ, 幅)の4次元配列からなる入力データ
filter_h : フィルターの高さ
filter_w : フィルターの幅
stride : ストライド
pad : パディング
Returns
-------
col : 2次元配列
"""
N, C, H, W = inpu... | 5,302,535 |
def get_deliverability_dashboard_options():
"""
Retrieve information about the status of the Deliverability dashboard for your Amazon Pinpoint account. When the Deliverability dashboard is enabled, you gain access to reputation, deliverability, and other metrics for the domains that you use to send email using ... | 5,302,536 |
def generate_g(b, d, p, q):
"""Compute a generator of a subgroup of Z^*_n that has order
b**d mod p and order b**d mod q"""
rs = PRNG()
b_to_the_d = b ** d
while True:
x = rs.random_Zsp(p)
if gmpy2.powmod(x, mpz((p-1)/b), p) != 1:
gp = gmpy2.powmod(x, mpz((p-1)/b_to_the_d... | 5,302,537 |
def load_runner(
tag: t.Union[str, Tag],
name: t.Optional[str] = None,
resource_quota: t.Optional[t.Dict[str, t.Any]] = None,
batch_options: t.Optional[t.Dict[str, t.Any]] = None,
model_store: "ModelStore" = Provide[BentoMLContainer.model_store],
) -> "_PyFuncRunner":
"""
Runner represents a... | 5,302,538 |
def get_html(url):
"""抓取传入url页面并返回html"""
try:
with sync_playwright() as p:
disable_warnings() # 禁用安全请求警告
browser = p.webkit.launch() # 启用webkit浏览器访问
page = browser.new_page()
page.goto(url)
page.wait_for_timeout(3000) # 等待网页加载
h... | 5,302,539 |
def in_main_thread():
"""
True when the current thread is the main thread.
"""
return threading.current_thread().__class__.__name__ == '_MainThread' | 5,302,540 |
def itmlogic_p2p(main_user_defined_parameters, surface_profile_m):
"""
Run itmlogic in point to point (p2p) prediction mode.
Parameters
----------
main_user_defined_parameters : dict
User defined parameters.
surface_profile_m : list
Contains surface profile measurements in meter... | 5,302,541 |
def merge_files_in_folder(path='./wiki', filename='aida_train.txt',filetype='.txt',filler_start='',filler_end='',add_id=False,replace_spaces=False, wiki_id_name_dict=None,num_of_files = None):
"""Merges all files inside a folder in one file
Parameters:
path - root folder with subfolders
filename (str) ... | 5,302,542 |
def get_commit_messages(starting_version: str, ending_version: str = "HEAD"):
"""Get the commit messages from the current git branch.
Depends on `git`.
Args:
starting_version (str): Starting version number, not included in the results
ending_version (str): Ending version number, defaults t... | 5,302,543 |
def compute_results(ann_inter, est_inter, ann_labels, est_labels, bins,
est_file, weight=0.58):
"""Compute the results using all the available evaluations.
Parameters
----------
ann_inter : np.array
Annotated intervals in seconds.
est_inter : np.array
Estimated i... | 5,302,544 |
def gsl_blas_ssyrk(*args, **kwargs):
"""
gsl_blas_ssyrk(CBLAS_UPLO_t Uplo, CBLAS_TRANSPOSE_t Trans, float alpha,
gsl_matrix_float A, float beta, gsl_matrix_float C) -> int
"""
return _gslwrap.gsl_blas_ssyrk(*args, **kwargs) | 5,302,545 |
def add_pies(data, x, verbose=False):
"""
Add the pie charts
:param data: our same/difference/total/lat/lon data
:param x: the plot axes/fram
:param verbose: more output
:return:
"""
for d in data:
o = data[d]['lon']
a = data[d]['lat']
t = data[d]['total']
... | 5,302,546 |
def get_ages(location, country, level, num_agebrackets=85):
"""
Get the age count for the synthetic population of the location.
Args:
location (str) : name of the location
country (str) : name of the country
level (str) : name of level (country or subnationa... | 5,302,547 |
def address_to_string(b):
"""Converts an IP address to its string representation.
Takes a 4-byte string representing an IP address, and returns a
dot-separated decimal representation on the form '123.123.123.123'.
"""
assert len(b) == 4
b = map(lambda x: str(_decode_byte(x)), b)
return '.'... | 5,302,548 |
def TestPauseWatcher():
"""Tests and pauses the watcher.
"""
master = qa_config.GetMasterNode()
AssertCommand(["gnt-cluster", "watcher", "pause", "4h"])
cmd = ["gnt-cluster", "watcher", "info"]
output = GetCommandOutput(master.primary,
utils.ShellQuoteArgs(cmd))
AssertMatch(... | 5,302,549 |
def small_testing_registry():
"""Return a small registry with a few widgets for testing.
"""
from ..description import WidgetDescription, CategoryDescription
from .. import WidgetRegistry
registry = WidgetRegistry()
data_desc = CategoryDescription.from_package("Orange.widgets.data")
file_... | 5,302,550 |
def test_listen0a():
"""Process `listen0a.txt`."""
_test(TESTDATAPATH / "find0.txt", TESTDATAPATH / "listen0a", 777) | 5,302,551 |
def fixUnits(object, **kwargs):
"""Convert output pint units into a proper latex string."""
string = str(object)
type = kwargs.get('type', None)
unitColor = 'darkBlue'
replacements = kwargs.get('replacements', None)
if replacements:
for old, new in replacements.items():
str... | 5,302,552 |
def get_schema_for_macro_definition(schema):
"""Return a schema with macro definition directives added in.
Preconditions:
1. All compiler-supported and GraphQL-default directives have their default behavior.
This returned schema can be used to validate macro definitions, and support GraphQL
macro ... | 5,302,553 |
def rect(r, w, deg=False):
"""
Convert from polar (r,w) to rectangular (x,y)
x = r cos(w)
y = r sin(w)
"""
# radian if deg=0; degree if deg=1
if deg:
w = np.pi * w / 180.0
return r * np.cos(w), r * np.sin(w) | 5,302,554 |
def get_account_ssh_key(name: Optional[str] = None,
ssh_key_id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetAccountSshKeyResult:
"""
Use this data source to get SSH key information based on its ID or name.
## Example Usag... | 5,302,555 |
def map_l2dist_sinhnormalmech_tCDP(sensitivity, scale, A):
"""map via the sinhnormal mechanism an L2 distance `sensitivity`
with parameters `scale` and `A` to (rho, omega)-tCDP
"""
rho = (sensitivity / scale) ** 2 / 2
assert 1 < 1 / np.sqrt(rho) <= A / sensitivity
return 16 * rho, A / (8 * sen... | 5,302,556 |
def simplify_sequential(sequentials: List[nn.Module]) -> Iterator[nn.Module]:
"""
Flatten the sequential blocks so that the hierarchy looks better.
Eliminate identity modules automatically.
"""
for module in sequentials:
if isinstance(module, nn.Sequential):
for submodule in modu... | 5,302,557 |
def getMDistance(plug):
"""
Gets the MDistance value from the supplied plug.
:type plug: om.MPlug
:rtype: om.MDistance
"""
return plug.asMDistance() | 5,302,558 |
def untag_resource(ResourceArn=None, TagKeys=None):
"""
Remove one or more tags (keys and values) from a specified resource.
See also: AWS API Documentation
Exceptions
:example: response = client.untag_resource(
ResourceArn='string',
TagKeys=[
'string',
... | 5,302,559 |
def create_activation_stats_collectors(model, *phases):
"""Create objects that collect activation statistics.
This is a utility function that creates two collectors:
1. Fine-grade sparsity levels of the activations
2. L1-magnitude of each of the activation channels
Args:
model - the model ... | 5,302,560 |
def test_missing_optional_field(event, field_name, glsc):
"""This test verifies that the form is still valid if the optional
fields are not provided. It is parameterized to take a list of
requried field names, then submit the form with each field
missing. The form should always be valid.
"""
... | 5,302,561 |
def main():
"""Run directly"""
# Get commandline arguments
parser = _get_args()
args = parser.parse_args()
if isinstance(args.infile, str):
infile_string = True
else:
infile_string = False
if isinstance(args.outfile, str):
outfile_string = True
else:
out... | 5,302,562 |
def get_fach_choices(item_container):
""" liefert die Liste der moeglichen Faecher """
ret = []
ret.append((-1, '---'))
faecher = get_fach_list(item_container)
for fach in faecher:
ret.append((fach.fach_id, fach.fach_name))
return ret | 5,302,563 |
def isPositive(phrase):
"""
Returns True if the input phrase has a positive sentiment.
Arguments:
phrase -- the input phrase to-be evaluated
"""
return bool(re.search(r'\b(sure|yes|yeah|go)\b', phrase, re.IGNORECASE)) | 5,302,564 |
def tree_of_size(size, root, *stops, with_data = True, loc_prefix = 'a', data_prefix = 'd'):
"""Return expression for a tree segment of size `size` rooted in `root`.
If `stops` is non-empty, the given stop nodes are used as the
first (but not necessarily left-most) leaves.
Warning: Stop nodes are in f... | 5,302,565 |
def test_job_list_route_inrow_delete(live_server, sl_operator, job): # pylint: disable=unused-argument
"""delete job inrow button"""
job_id = job.id
db.session.expunge(job)
sl_operator.get(url_for('scheduler.job_list_route', _external=True))
dt_inrow_delete(sl_operator, 'job_list_table')
asse... | 5,302,566 |
def init():
"""セッション情報初期化処理"""
app.secret_key = os.urandom(32)
session.pop('filename', None) | 5,302,567 |
def test_correct_format_time_convert():
"""
Validates the time conversion function
correctly formats time.
"""
key_object = ApiKey(
key_id='52b426b4-f56a-4901-855e-235345234',
display_name='API key 1',
created_by='None',
create_time='2021-03-14T18:15:28.914878Z',
... | 5,302,568 |
def inspect_prop_pts(dom: AbsDom, sample_size=1000):
""" Sample points for each property, and watch for any safe≠0 points.
Pt Safe Ratio
Property 2 0.99
Property 8 0.999
All the rest are with 1.0 safe ratio, these are are perhaps due to numerical error?
"""
def debug_unsafe_poi... | 5,302,569 |
def to_netcdf(
grid, path, include="*", exclude=None, time=None, format="NETCDF4", mode="w"
):
"""Write landlab a grid to a netcdf file.
Write the data and grid information for *grid* to *path* as NetCDF.
If the *append* keyword argument in True, append the data to an existing
file, if it exists. O... | 5,302,570 |
def less_than(value: Any) -> Matcher[Any]:
"""Matches if object is less than a given value.
:param value: The value to compare against.
"""
return OrderingComparison(value, operator.lt, "less than") | 5,302,571 |
def get_time_size(rates):
"""
Get number of time intervals
Parameters
----------
Returns
-------
out : int
Number of time intervals
See Also
--------
DataStruct
"""
wgname_keys = list(rates.keys())
mnemo_keys = list(rates[wgname_keys[0]].keys())
return... | 5,302,572 |
def arg_parser():
"""
"""
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--input", type=str, dest='input_file',
help="Input file with tweets summary information")
parser.add_argument("-e", "--input-entities", type=str, dest='input_ent',
... | 5,302,573 |
def to_pandas(summary, metrics=None, date_key="summary_date"):
"""
Creates a dataframe from a summary object
:param summary: A summary object returned from API
:type summary: dictionary of dictionaries. See https://cloud.ouraring.com/docs/readiness for an example
:param metrics: The metrics to inc... | 5,302,574 |
def custom_loss(y_true, y_pred, alpha1=1, alpha2=0.5, alpha3=1):
"""
The designed loss function consists of precision, recall and mean squared error as follows:
loss = a1 * precision_loss + a2 * recall_loss + a3 * mae_loss
where α 1 , α 2 and α3 are the balance parameters.
"""
prec, recall =... | 5,302,575 |
def fusion_new_search_cluster(cluster, name):
"""
Creates a new search cluster in Fusion with the specified name using the zkHost of the provided cluster.
"""
hosts = _lookup_hosts(cluster)
zkHost = _read_cloud_env(cluster)['ZK_HOST'] # get the zkHost from the env on the server
createClusterJson... | 5,302,576 |
def test_electromagnetic_potential_contravariant(test_input):
"""
Tests, if the calculated EM 4-Potential, in contravariant form, is the same as that \
calculated manually
"""
bl, M, a = test_input
Q = 15.5 * u.C
x_vec = bl.position()
r, theta = x_vec[1], x_vec[2]
mkn = KerrNewman(... | 5,302,577 |
def networkx_to_data_dict(graph_nx,
node_shape_hint=None,
edge_shape_hint=None,
data_type_hint=np.float32):
"""Returns a data dict of Numpy data from a networkx graph.
The networkx graph should be set up such that, for fixed shapes `node... | 5,302,578 |
def compute_attributes_record(service):
""" compute the number of attributes needed by this service. """
attribute_records = 1
for characteristic in service.get_characteristics():
# add two attributes, one for the characteristic declaration
# and the other for the characteristic value.
... | 5,302,579 |
def twoQ_clifford_error(ngates, gate_qubit, gate_err):
"""
The two qubit Clifford gate error given measured errors in the primitive
gates used to construct the Clifford (see arxiv:1712.06550). Assumes the
error in the underlying gates is depolarizing.
Args:
ngates: list of the number of gat... | 5,302,580 |
def main():
"""
The main entry point for adb_push_built_products.
Parse arguments and kick off the script. Return zero to indicate success.
Raises an exception otherwise.
"""
parser = argument_parser()
args = parser.parse_args()
for path in args.paths:
if os.path.isdir(path):
... | 5,302,581 |
def posix_timing(trace_graph):
"""Generate timing stats"""
for posix_call in trace_graph.timing_info:
yield posix_call, trace_graph.timing_info[posix_call] | 5,302,582 |
def gather_texture(
blender_shader_sockets: typing.Tuple[bpy.types.NodeSocket],
export_settings):
"""
Gather texture sampling information and image channels from a blender shader texture attached to a shader socket.
:param blender_shader_sockets: The sockets of the material which should con... | 5,302,583 |
def print_dashes():
"""print dashes"""
print('-' * 100, flush=True) | 5,302,584 |
def _make_gaussian_kernel_uri(sigma, kernel_uri):
"""Create a 2D Gaussian kernel.
Parameters:
sigma (float): the sigma as in the classic Gaussian function
kernel_uri (string): path to raster on disk to write the gaussian
kernel.
Returns:
None.
"""
# going 3.0 ti... | 5,302,585 |
def define_vectorized_funcs():
"""
Defines vectorized versions of functions from uncertainties.umath.
Some functions have their name translated, so as to follow NumPy's
convention (example: math.acos -> numpy.arccos).
"""
this_module = sys.modules[__name__]
# NumPy does not always use the ... | 5,302,586 |
def splitFragP(uriref, punct=0):
"""split a URI reference before the fragment
Punctuation is kept.
e.g.
>>> splitFragP("abc#def")
('abc', '#def')
>>> splitFragP("abcdef")
('abcdef', '')
"""
i = uriref.rfind("#")
if i >= 0:
return uriref[:i], uriref[i:]
else:
... | 5,302,587 |
def insert(data):
""" Connect to the PostgreSQL database server """
conn = None
cards = data["cards"]
try:
# read connection parameters
params = config()
# connect to the PostgreSQL server
logger.info('Connecting to the PostgreSQL database...')
conn = psycopg2.c... | 5,302,588 |
def get_scopes_from_groups(
config: Config, groups: Optional[List[TokenGroup]]
) -> Optional[List[str]]:
"""Get scopes from a list of groups.
Used to determine the scope claim of a token issued based on an OpenID
Connect authentication.
Parameters
----------
config : `gafaelfawr.config.Con... | 5,302,589 |
def test_ok_none_discharge_rate(schema: Type[BaseModel], data: Dict[str, Any]):
"""
Test that a discharge rate is optional for a schema
"""
schema(discharge_rate=None, **data) | 5,302,590 |
def get_notifications(refresh: bool = True) -> List[Dict[str, str]]:
"""
Get a list of notifications.
:params refresh: Whether to get new news. If false, the existing notifications will be returned
:returns: The list of notifications
"""
if refresh:
covid_notification_id, covid_notific... | 5,302,591 |
def plot_invkin(t, r, ang, unit, legenda, ax):
"""Plot inverse kinematics data."""
try:
import matplotlib.pyplot as plt
except ImportError:
print('matplotlib is not available.')
return
if ax is None:
_, ax = plt.subplots(2, 2, figsize=(8, 5))
if unit[1] in ... | 5,302,592 |
def _convert_double_vector_out( dlist ):
"""
Convert python list to datum as PyCapsule.
Possibly check type of input and handle arrays amd nparrays too.
Convert to standard form for C translation to datum.
"""
_VCL = _find_converter_lib()
func = _VCL.double_vector_to_datum
func.argtype... | 5,302,593 |
def fix_and_display_w(*args):
"""This is designed to accept objects as args, add them to the global namespace, with
made-up names, then call display_w with the made-up names. The idea is that
display_w() can be relegated to utilitites.
This works - sort of - in that the objects a... | 5,302,594 |
def sanitize_name(name):
""" Clean-up the given username."""
name = name.strip()
# clean up group
name = name.replace('- IE', ' -IE')
name = name.replace('- MA', ' -MA')
for l in [1,2,3,4,5,6,7,8,9]:
for g in "AB":
name = name.replace(f'IE{l}-{g}', f'IE-{l}{g}')
... | 5,302,595 |
def to_md(mmyaml, projdir, mddir, use_synopsis=False):
"""
Generates markdown files from Scrivener RTF sources.
If `use_synopsis` is `True` the Scrivener synopsis text files for each
chapter must contain valid yaml `key: value` pairs. These will be prepended
to the chapter markdown as metadata.
... | 5,302,596 |
def init_DB(version,config_path = None):
"""Amaril CLI offers the following commands: (for help type: amaril_cli COMMAND --help)"""
# CONFIG:
# construct default config path:
if (not config_path):
current_path = pathlib.Path().absolute()
config_path = current_path
config_dir = ... | 5,302,597 |
def test_semisuper_succeeds():
"""Regression test. Ensure that this can write"""
with helpers.tempdir() as temp:
env = gym.make('SemisuperPendulumDecay-v0')
env = Monitor(env, temp)
env.reset()
env.step(env.action_space.sample())
env.close() | 5,302,598 |
def _givens_rotation_matrix_entries(a, b):
"""
Compute matrix entries for Givens rotation.
"""
r = hypot(a, b)
c = a/r
s = -b/r
return c, s | 5,302,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.