content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def rewrite_string(
searcher: AbstractSearcher,
source: Text,
path: Text,
max_iterations=1,
) -> Text:
"""Applies any replacements to the input source, and returns the result."""
return formatting.apply_substitutions(
source, find_iter(
searcher,
source,
path,
... | 2de75ca2511ff2496f29674ff762c7a48531c51b | 27,700 |
def build_path_result_tests(name):
"""
Build a test for API commands that respond with ``Err`` and
``Mountpoint`` fields.
:param unicode command_name: The command in the schema to validate.
:return: ``TestCase``.
"""
return build_schema_test(
name=str(name + "Tests"),
schem... | 32491f1eb10d9f175522b7ea55f91a2c1e6aeb27 | 27,701 |
def get_mpls_autobw_template_detail_rpc(self, api_timeout=''):
"""
This is an auto-generated method for the PySwitchLib.
**Supported Versions**:
* SLXOS: 17r.1.01a, 17r.2.00, 17s.1.02
:type api_timeout: long or tuple(long, long)
:param api_timeout: Timeout for connection and response ... | 97e0d7ef9a43ef2335fefc6c62ad34286dbf7efb | 27,702 |
def empty(a):
"""Test whether the slice is empty."""
return a is None or volume(a)==0 | c1de4cfbf3bcc569b4b3cde02d518aabf32ff6fd | 27,703 |
def handle_server_error(exception):
"""
handles server internal core exceptions.
note that normally you should never call this method manually.
in any environment which debug mode is False, the original error
message will be replaced by a generic error message before being
sent to client for se... | 8fd84df5b2bc2a7f5f76e2ae68e70f85fc069153 | 27,704 |
def nnPredict(w1, w2, data):
"""% nnPredict predicts the label of data given the parameter w1, w2 of Neural
% Network.
% Input:
% w1: matrix of weights of connections from input layer to hidden layers.
% w1(i, j) represents the weight of connection from unit i in input
% layer to unit ... | 564e3db0c659713de9dbfda7c279381d50d490e3 | 27,705 |
from typing import List
def count_pairs(array: List[int], difference: int) -> int:
"""
Given an array of integers, count the number of unique pairs of integers that have a given difference.
These pairs are stored in a set in order to remove duplicates.
Time complexity: O(n^2).
:param array: is th... | e027e8885f4c4531da9b7dab7de8e84a7004c913 | 27,706 |
def decompress_deltas_18bit(buffer):
"""Parse packet deltas from 18-byte compression format."""
if bad_data_size(buffer, 18, "18-byte compressed packet"):
raise ValueError("Bad input size for byte conversion.")
deltas = np.zeros((2, 4))
# Sample 1 - Channel 1
minibuf = [(buffer[0] >> 6),
... | 65fc1b7cc12c0d9f0a082c7df57bbae81fb1ec13 | 27,707 |
import re
def password_validate(password):
"""It validates password using regular expression
:param password: contains the users password
:returns: Boolean
:raises: ValidationError
"""
if re.match(
r"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$",
passw... | 57cec9fd1ae1f4f2b4df887d98e65ea9f6191595 | 27,708 |
def get_emr_cluster_status(cluster_id: str, detail: bool = False):
"""
Provides cluster-level details including status, cluster_id, cluster_name and so on.
Args:
cluster_id: string, EMR cluster id
detail: bool, provided additional detail about cluster like ec2 attributes
Returns:
... | 48da66c5aa45f0697b71924a31ea6d942bb5ce19 | 27,709 |
def get_keypair() -> KeyPairInfo:
"""Returns current keypair (ec2.KeyPairInfo)
https://boto3.readthedocs.io/en/latest/reference/services/ec2.html#keypairinfo
"""
return get_keypair_dict()[get_keypair_name()] | 95cba4f8a81858578e831b0bdbae359791399841 | 27,710 |
def char_vectorizer(char,
custom_alphabet=False):
"""
Vectorize given nucleotide character. Convert to uppercase before
vectorizing.
>>> char_vectorizer("C")
[0, 1, 0, 0]
>>> char_vectorizer("g")
[0, 0, 1, 0]
>>> char_vectorizer("M", ['E', 'H', 'I', 'M', 'S'])
[0... | 53c306d814807299b7bac7801f4b7d2a663b6f99 | 27,711 |
def orbit_from_name(name):
"""Return :py:class:`~poliastro.twobody.orbit.Orbit` given a name.
Retrieve info from JPL DASTCOM5 database.
Parameters
----------
name : str
NEO name.
Returns
-------
orbit : list (~poliastro.twobody.orbit.Orbit)
NEO orbits.
"""
rec... | 145c1ef503743e9066ecf8e2f5e06c0526f8ab62 | 27,712 |
def make_snowflake(timestamp_ms, datacenter_id, worker_id, sequence_id, twepoch=twepoch):
"""generate a twitter-snowflake id, based on
https://github.com/twitter/snowflake/blob/master/src/main/scala/com/twitter/service/snowflake/IdWorker.scala
:param: timestamp_ms time since UNIX epoch in milliseconds"""
... | 473d97589dbe90949cb69ecdbeba719cbea5c2ee | 27,713 |
from typing import Sequence
def compute_committee(indices: Sequence[ValidatorIndex],
seed: Bytes32,
index: uint64,
count: uint64) -> Sequence[ValidatorIndex]:
"""
Return the committee corresponding to ``indices``, ``seed``, ``index``, and commi... | 168fc69ef7d4962c089cd6e497cd94ccad062c73 | 27,714 |
def get_default_graph():
""" Setting graphviz graph global options """
graph = Digraph('AWS', engine='dot')
graph.body.append('splines=line')
graph.body.append('rankdir=LR')
graph.body.append('outputorder=edgesfirst')
graph.node_attr.update(shape='rectangle', style='filled', color='black')
r... | 25ae7376b31d280722fb2791dbf9478a6b4cb2d1 | 27,715 |
from json import dumps
def GetJson(data):
"""
将对象转换为JSON
@data 被转换的对象(dict/list/str/int...)
"""
if data == bytes: data = data.decode('utf-8')
return dumps(data) | 372b501f5ada7254efab10447dcbdc91c8799408 | 27,716 |
def binary_tail(n: int) -> int:
""" The last 1 digit and the following 0s of a binary representation, as a number """
return ((n ^ (n - 1)) + 1) >> 1 | 63460cef7b39b7e7ee2ec880810ff71d82be01e9 | 27,717 |
from datetime import datetime
def time_left(expire_date):
"""Return remaining days before feature expiration or 0 if expired."""
today_dt = datetime.today()
expire_dt = datetime.strptime(expire_date, "%d-%b-%Y")
# Calculate remaining days before expiration
days_left_td = expire_dt - today_dt
... | 652acd27b0d4fa9b21321df4ff8ce6ce15b97ed6 | 27,718 |
import yaml
def load_config():
"""
importer_config.yaml must be in the current working directory
"""
with open(_PATH) as fd:
config = yaml.safe_load(fd)
# Remove trailing slashes from URLs
config['kbase_endpoint'] = config['kbase_endpoint'].strip('/')
return config | 0137c59cd2ea7b5b8ba57a82fb2997e6e7330751 | 27,719 |
def get_package_version():
"""Return the Review Board version as a Python package version string.
Returns:
unicode:
The Review Board package version.
"""
version = '%s.%s' % (VERSION[0], VERSION[1])
if VERSION[2] or VERSION[3]:
version = '%s.%s' % (version, VERSION[2])
... | 418eef843dd3647cffdeb879781e3599487cd885 | 27,720 |
def create_state_representation(
name: str, state_space: StateSpace
) -> StateRepresentation:
"""Factory function for state representations
Returns:
Representation:
"""
# TODO: test
if name == 'default':
return DefaultStateRepresentation(state_space)
if name == 'no_overlap... | c9396d5ca28f7718502b7f4e9c17d73144d9acc2 | 27,721 |
def fit(x, y, sigy=None, error=False):
""" Perform a linear fit on a range of x and y values.
This function fits a set of data points x, y with individual standard
deviations sigy for the y values to a straight line y = a + bx by
minimizing chi-square.
If the 'error' parameter is False the functio... | f02db36a6e7395d3f955cafc6f506e3a42984abf | 27,722 |
def eval_metrics_offline(cfg,
pred_folder,
palette,
metrics=['mFscoreCD', 'mFscore']
):
"""Calculate evaluation metrics from offline GT and prediction images, maily use the evaluate of dataset class
Args:
... | 7d5e44a1cda8d7bbb92a56cedf18e940c51663e5 | 27,723 |
def zero_pad_and_crop(img, amount=4):
"""Zero pad by `amount` zero pixels on each side then take a random crop.
Args:
img: numpy image that will be zero padded and cropped.
amount: amount of zeros to pad `img` with horizontally and verically.
Returns:
The cropped zero padded img. The returned numpy ... | 63ac80cb9759fd06032afd97f03e0057aed86784 | 27,724 |
def video_id(video_id_or_url):
"""
Returns video id from given video id or url
Parameters:
-----------
video_id_or_url: str - either a video id or url
Returns:
--------
the video id
"""
if 'watch?v=' in video_id_or_url:
return video_id_or_url.split('watch?v=')[1]
e... | 9f680ac621e1f5c6314a6a3e97093d786fa7ea33 | 27,725 |
def check_permission(resource: Resource, permission_name: str) -> dict:
"""
Check if requester has sufficient permissions to do something on specific resource.
Raises if not.
"""
base_permission_policy = resource.get_guest_authorization()
if (authorization_header := resource.request.headers.get... | b632fbb5f3429c1540da35c3b82e6fa562b81c87 | 27,726 |
from datetime import datetime
import json
def makePalRecordsConsistent(pal_records, low_frequency, high_frequency,
user_id, fcc_channel_id="1",
start_date=None, end_date=None):
"""Make Pal object consistent with the inputs
Args:
pal_records: (list... | 3029ee761afb17428a6a2b0b1e85c0f2f3fdc6d6 | 27,727 |
import yaml
def read_config():
"""Read from rotest.yml config elrados segment."""
config_path = search_config_file()
if config_path is not None:
with open(config_path, "r") as config_file:
configuration_content = config_file.read()
yaml_configuration = yaml.load(configuration_... | 5fb81ef5609074c029203021895ba55654760a60 | 27,728 |
import typing
def cast_to_str(some_value: typing.Any, from_type: typing.Any) -> typing.Any:
"""Just helper for creating suitable test assets."""
if from_type == bytes:
return some_value.decode()
return str(some_value) | 9157873a74d0d02b919d047710c1d4ccee4121a6 | 27,729 |
def downsample_by_group(df,min_distance=1.,message_callback=print):
"""Group and down-sample a DataFrame of xrsd records.
Parameters
----------
df : pandas.DataFrame
dataframe containing xrsd samples
min_distance : float
the minimum allowed nearest-neighbor distance
... | bbcdbab6c1bf5e42554e102bda8d245263a47bfd | 27,730 |
from typing import Union
def get_pure_ratings(
ratings: Union[str, pd.Series, pd.DataFrame]
) -> Union[str, pd.Series, pd.DataFrame]:
"""Removes rating watches/outlooks.
Parameters
----------
ratings : str, pd.Series, or pd.DataFrame
Rating may contain watch, such as `AA- *+`, `BBB+ (CwNe... | a834b3f33f12d8d3b6c109021a4d075c32160544 | 27,731 |
def export_grid(outname,resh,ignore=[255,0]):
"""[Exports given grid to a point cloud]
Args:
outname ([str]): [Output file name]
resh ([np.array]): [3D Volume in grid representation]
ignore (list, optional): [values to ignore]. Defaults to [255,0].
Returns:
Grid as a point c... | 27fd06c37d57f0eb320d0d81908efc1acf6bc8ee | 27,732 |
def sum_errors(dic):
"""Helper function to sum up number of failed jobs per host.
Assumes that dic is in the form
:param dict dic: {"error_code1":count1, "error_code2":count2, etc.}
:return int: Sum of all values in dic
"""
return sum(value for key, value in dic.iteritems()) | 0d2bc9df58e5bf9639a331d64061de4c0a5aa4ed | 27,733 |
def checkFriends(new_user, usernameOfFriend):
""" Check if users are friends or not"""
# Check if users are friends first
viewF = viewFriends(new_user, usernameOfFriend)
# Check if users have any pending requests
viewP = searchPendingRequests(new_user, usernameOfFriend)
# Logic
if viewF:
... | 6268d180a768ad858d5e1c5c69c92837a027f07f | 27,734 |
def update(instance, **data):
"""Update instance with data directly by using ``update()``
skipping calling ``save()`` method.
Usage: ``instance = update(instance, some_field=some_value)``
"""
instance.__class__.objects.filter(pk=instance.pk).update(**data)
return refresh(instance) | 8462d5459ba02d11ef3edd0c1d3c152d4b682634 | 27,735 |
def cast_distance_matrix_to_optimal_integer_type(D_X):
"""
Cast distance matrix to smallest signed integer type, sufficient
to hold all its distances.
Parameters
-----------
D_X: np.array (|X|×|X|)
Distance matrix of a compact metric space X with integer
distances.
Returns
... | 01c8e43259d5edc7282a9c01269277f34495ff9d | 27,736 |
def getObject(name):
"""Get reference to single Rhino object, checking for failure"""
rc, obRef = Rhino.Input.RhinoGet.GetOneObject("Select " + name, True, Rhino.DocObjects.ObjectType.AnyObject)
if rc != Rhino.Commands.Result.Success or not obRef : raise NameError(rc)
return obRef | 20d562dd90dec82a479bdedabef62f17129cecf0 | 27,737 |
def get_falsecolor(input):
"""
picks false color bands from the 12 Sentinel bands (for visual interpretation of vegetation)
:param input: 12-band image tensor
:return: 3-band NIR-RED-GREEN tensor
"""
rgb_band_idxs = [bands.index(b) for b in ["S2B8", "S2B4", "S2B3"]]
return input[rgb_band_idx... | a4e80bb61211456794b34c99ec0ad92f1b1f567d | 27,738 |
import sys
def CUnescape(text):
"""Unescape a text string with C-style escape sequences to UTF-8 bytes."""
def ReplaceHex(m):
# Only replace the match if the number of leading back slashes is odd. i.e.
# the slash itself is not escaped.
if len(m.group(1)) & 1:
return m.group(1) + 'x0' + m.group... | 222e83ee363d2c072356bfc8375fd1bf4bc746bd | 27,739 |
import ast
def apply_bin_op(left, right, op):
"""
Finds binary expression class suitable for combination of left and right
expressions depending on whether their output is scalar or vector and
creates instance of this expression with specified operation.
"""
exr_class = BIN_EXPR_CLASSES.get(
... | fb5e6c0434dfa209ab34c4253e71bba6cb74e901 | 27,740 |
import sys
def create_module(dotted_name=None, filename=None, *, update_parent=True):
"""Create a new blank module at run time, insert it into `sys.modules`, and return it.
This is a utility function that closely emulates what Python's standard
importer does. It fills in some attributes of the module, an... | bf20dd906c757c7d7d16dc7cacd7744a96b77feb | 27,741 |
def pre_filter(image):
"""Apply morphological filter"""
return cv2.morphologyEx(image, cv2.MORPH_OPEN, np.ones((3, 3))) | a1af13d831d8462bc9c23443d2416efe66d3082b | 27,742 |
def build_corpus(docs: DocumentSet, *, remove_words=None, min_word_length=3,
min_docs=5, max_docs_ratio=0.75, max_tokens=5000,
replace_words=None, custom_bigrams=None, ngram_threshold=None
) -> Corpus:
""" Build a `Corpus` object.
This function takes the words... | 746eaa78fa498cd32950b3a006bfa669431037d0 | 27,743 |
def _Data_to_bytes(data: Data) -> bytes:
"""
Cast websockets.typing.Data to bytes.
Parameters
----------
data : str | bytes
Returns
-------
bytes
Either casted string or original bytes.
"""
return data.encode() if isinstance(data, str) else data | 0391dd9b9de0c8a978b16b6c89f9f3515f1a49de | 27,744 |
import torch
import time
def run_pairs(genotype_df, variant_df, phenotype1_df, phenotype2_df, phenotype_pos_df,
covariates1_df=None, covariates2_df=None, p1=1e-4, p2=1e-4, p12=1e-5, mode='beta',
maf_threshold=0, window=1000000, batch_size=10000, logger=None, verbose=True):
"""Compute C... | 3a38f2f38bd7351b93d3ede0f6c6d2e07427263d | 27,745 |
def main(local_argv):
"""
local_argv is the argument list, progrom name is first arugment
this function prints the fibonacci list calcuated by the command line argument n
"""
if len(local_argv) != 2:
print("must add one and only one command argument, , exit ")
return
... | 932c2b7a4f82ed03c62739e6e48350db057957da | 27,746 |
def alternate(*iterables):
"""
[a[0], b[0], ... , a[1], b[1], ..., a[n], b[n] ...]
>>> alternate([1,4], [2,5], [3,6])
[1, 2, 3, 4, 5, 6]
"""
items = []
for tup in zip(*iterables):
items.extend([item for item in tup])
return items | ed3b0c8a32de8d88fc24b8bb08012a0900b37823 | 27,747 |
def softmax(x, axis=-1, t=-100.):
"""
Softmax operation
Args:
x (numpy.array): input X
axis (int): axis for sum
Return:
**softmax** (numpy.array) - softmax(X)
"""
x = x - np.max(x)
if np.min(x) < t:
x = x/np.min(x)*t
e_x = np.exp(x)
return e_x / e_x.sum(axis, keepdims=True) | 7979c7eeaf4be319f06532abc2a2cc3a23af134d | 27,748 |
def format_params_in_str_format(format_string):
"""
Get the "parameter" indices/names of the format_string
Args:
format_string: A format string (i.e. a string with {...} to mark parameter placement and formatting
Returns:
A list of parameter indices used in the format string, in the or... | a8b79cb6ee7a544b60c193dfbc2dbdc22d5d1f92 | 27,749 |
def AMO(df, M1=5, M2=10):
"""
成交金额
:param M1:
:param M2:
:return:
"""
AMOUNT = df['amount']
AMOW = AMOUNT / 10000.0
AMO1 = MA(AMOW, M1)
AMO2 = MA(AMOW, M2)
return pd.DataFrame({
'AMOW': AMOW, 'AMO1': AMO1, 'AMO2': AMO2
}) | ef45e245e1abb5705760e55b99e2e0757c66667c | 27,750 |
def tex_initial_states(data):
"""Initial states are texed."""
initial_state = []
initial_state = [''.join(["\lstick{\ket{", str(data['init'][row]),"}}"]) for row in range(len(data['init']))]
return data, initial_state | cd1758b594ee854cfb7854ec742dc177a43b54b7 | 27,751 |
import csv
def get_upgraded_dependencies_count(repo_path, django_dependency_sheet) -> tuple:
"""
Entry point to read, parse and calculate django dependencies
@param repo_path: path for repo which we are calculating django deps
@param django_dependency_sheet: csv which contains latest status of django ... | 1a793c57b69966c45f680fd39fec31a94d4d5616 | 27,752 |
from pygsti.modelmembers.operations import EmbeddedOp as _EmbeddedOp, StaticArbitraryOp as _StaticArbitraryOp
from pygsti.baseobjs.errorgenbasis import ExplicitElementaryErrorgenBasis as _ExplicitElementaryErrorgenBasis
def first_order_gauge_action_matrix_for_prep(prep_superket_vec, target_sslbls, model_state_space,
... | 9c59db8d9555041a3a3ade2b0d92fb7104ee4a94 | 27,753 |
def FanOut(num):
"""Layer construction function for a fan-out layer."""
init_fun = lambda rng, input_shape: ([input_shape] * num, ())
apply_fun = lambda params, inputs, **kwargs: [inputs] * num
return init_fun, apply_fun | 7e6d07319be600dabf650a4b87f661bf20832455 | 27,754 |
import urllib
import logging
def is_online(url="http://detectportal.firefox.com", expected=b"success\n"):
"""
Checks if the user is able to reach a selected hostname.
:param hostname: The hostname to test against.
Default is packages.linuxmint.com.
:returns: True if able to connect or False otherw... | 00081e05fbb1cfaa81a03a487201af4c07b23fd2 | 27,755 |
def get_Data_temblor():
"""Shows basic usage of the Sheets API.
Creates a Sheets API service object and prints the names and majors of
students in a sample spreadsheet:
https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
"""
credentials = get_credentials()
... | 1dca23ae977dc4400b31e323d1c2aac5e6e685a3 | 27,756 |
def triplet_loss(y_true, y_pred, alpha = 0.2):
"""
Implementation of the triplet loss as defined by formula (3)
Arguments:
y_true -- true labels, required when you define a loss in Keras, you don't need it in this function.
y_pred -- python list containing three objects:
anchor -- t... | 41257b626fdb4773769bf20d2aa11caaa8896259 | 27,757 |
import inspect
def node_from_dict(node_dict):
"""Create a new node from its ``node_dict``.
This is effectively a shorthand for choosing the correct node class and
then calling its ``from_dict`` method.
Args:
node_dict (dict): dict-representation of the node.
Returns:
New schema ... | 299cc2e1f194338ff3bbc13f729284b61b884b1b | 27,758 |
def _get_activation(upsample_activation):
"""get activation"""
nonlinear = getattr(nn, upsample_activation)
return nonlinear | 4423edf977ccd6db6fa6fdb5de426ecbaaed7e55 | 27,759 |
import time
def computeSensitivity(P, W):
"""
The function at hand computes the sensitivity of each point using a reduction from L_\infty to L1.
:return: None
"""
P = np.hstack((P, np.arange(P.shape[0])[:, np.newaxis]))
B, idxs = applyBiCriterea(P[:, :-1], W) # attain set of flats which give... | 089442a4c136ef473582db93b04575562ebecd96 | 27,760 |
def num_bytes_needed_for_data(rom_dict):
"""
Get the number of bytes to store the largest data in the rom.
Args:
rom_dict (dict(int:int)): Dictionary of address and data values
Returns:
(int): Number of bytes needed for largest piece of data
"""
largest_data = max(rom_dict.iterv... | af039a39c86c17d0349d53b2e5020d8cf3560f5d | 27,761 |
def run_simulation(model, **kwargs):
"""Runs the given model using KaSim and returns the parsed results.
Parameters
----------
**kwargs : List of keyword arguments
All keyword arguments specifying conditions for the simulation are
passed to the function :py:func:`run_kasim` (see documen... | 26aba6818a567faf8a08df8d5a47c213bb717183 | 27,762 |
import importlib
def _bot_exists(botname):
"""
Utility method to import a bot.
"""
module = None
try:
module = importlib.import_module('%s.%s' % (botname, botname))
except ImportError as e:
quit('Unable to import bot "%s.%s": %s' % (botname, botname, str(e)))
return module | c091be6d586faa8aacd48b30f4ce2f4fcc665e0b | 27,763 |
import functools
def validator(fn):
"""Decorator that constructs a scenario validator from given function.
Decorated function should return ValidationResult on error.
:param fn: function that performs validation
:returns: rally scenario validator
"""
def wrap_given(*args, **kwargs):
... | 0237711c6910eaf11eaa91df6bfe22283fdea080 | 27,764 |
def bootstrap_alert_message(msg, alert_type):
"""
Wrap Ajax error message for display
:param msg: Message text
:param alert_type: must be alert-danger, alert-success, alert-info, alert-warning
:return: html formatted message
"""
if not msg:
msg = _('An unknown error has occurred')
... | cec9fa851272274a734dfbf6599ee67ed2c7c9f8 | 27,765 |
def get_message_dispatched(correlation_id, steps, primary=True):
"""
Sets a flag in cache to indicate that a message has been dispatched.
:param correlation_id: a str guid for the fsm
:param steps: an integer corresponding to the step in the fsm execution
:return: True if cached and False otherwise... | cd9a373f6b104617dfae2d488fc2348ffae61c5b | 27,766 |
def _format_exponent_notation(input_number, precision, num_exponent_digits):
"""
Format the exponent notation. Python's exponent notation doesn't allow
for a user-defined number of exponent digits.
Based on [Anurag Uniyal's answer][answer] to the StackOverflow
question ['Python - number of digits i... | 59f61897c70ca1d9f95412b2892d5c9592e51561 | 27,767 |
import typing
def unicode_blackboard_activity_stream(
activity_stream: typing.List[blackboard.ActivityItem]=None,
indent: int=0,
show_title: bool=True
):
"""
Pretty print the blackboard stream to console.
Args:
activity_stream: the log of activity, if None, get the entire activity str... | 435c52b630d467aea2835644297e5099d1c69490 | 27,768 |
import argparse
import logging
def parse_args(args):
"""Parse command line parameters
Args:
args ([str]): command line parameters as list of strings
Returns:
:obj:`argparse.Namespace`: command line parameters namespace
"""
parser = argparse.ArgumentParser(
description="Snapcr... | 62d13ddc077d39f3675d6cdaf7944c23ad5735f2 | 27,769 |
def normalize(vector):
"""Normalize a vector to unit length.
Args:
vector (list/tuple/numpy.ndarray): Array to be normalized
Return:
vector (numpy.ndarray): Normalized vector.
"""
length = np.sqrt(np.sum(np.asarray(vector) ** 2))
if length == 0:
return np.asarray(vector... | 5f51933a93fd6b3df0955024585105a8887f3fd2 | 27,770 |
def get_struc_qty(*args):
"""get_struc_qty() -> size_t"""
return _idaapi.get_struc_qty(*args) | f370db3d60fdc0b5870baf8a9b616163d55860c6 | 27,771 |
from typing import Callable
def evaluate0(gametree_: Callable[[Board],
Node], static_eval_: Callable[[Board], int],
prune_: Callable[[Node], Node]) -> Callable[[Board], int]:
"""Return a tree evaluation function"""
def evaluate_(board: Board) -> int:
re... | eda97c4a6be5bac08ca0a73e0653b9c58321b539 | 27,772 |
import http
def fortune(inp):
"""
.fortune -- returns one random card and it's fortune
"""
try:
cards = http.get_json("https://tarot-api.com/draw/1")
except HTTPError:
return "The spirits are displeased."
card = cards[0]
return card["name"] + ": " + ", ".join(card["keywo... | d167238880a63afdd0aee11c2d02354a672d7fb8 | 27,773 |
def declin_0(x, obl):
"""
declination of a point of ecliptic
:param x: longitude of the point in degree
:param obl: obliquity of the ecliptic in degree
return declination in degree
"""
return DEG * m.asin(m.sin(x * RAD) * m.sin(obl * RAD)) | 5853ceb9d0424618a1b1406ee53ea87779f3b535 | 27,774 |
def network_data_structures(stream_names_tuple, agent_descriptor_dict):
"""Builds data structures for the network. These data
structures are helpful for animating the network and
for building networks of processes.
Parameters
----------
Same as for make_network.
Return Values
------... | 158484dd882eb14da1824408c35d7124282d47e1 | 27,775 |
import numpy
from typing import OrderedDict
def to_onnx(model, X=None, name=None, initial_types=None,
target_opset=None, options=None, rewrite_ops=False,
white_op=None, black_op=None, final_types=None):
"""
Converts a model using on :epkg:`sklearn-onnx`.
@param model ... | 27a21d66d78e2432362718b89d8df830471d521c | 27,776 |
def setRx(phi):
"""Rotation matrix around x axis"""
Rx = np.zeros((phi.size,3,3))
Rx[:,0,0] = 1.
Rx[:,1,1] = np.cos(phi)
Rx[:,2,2] = Rx[:,0,0]
Rx[:,1,2] = -np.sin(phi)
Rx[:,2,1] = -Rx[:,0,2]
return Rx | a70699ccc61b30d820fd9172b459680a1287e8e0 | 27,777 |
def discrete_resample(df, freq_code, agg_fun, remove_inter=False, **kwargs):
"""
Function to properly set up a resampling class for discrete data. This assumes a linear interpolation between data points.
Parameters
----------
df: DataFrame or Series
DataFrame or Series with a time index.
... | 502a63b81c8cf027853e45f77e2c9b18c1beddb4 | 27,778 |
def reflect(data, width):
"""Ceflect a data word, means revert the bit order."""
reflected = data & 0x01
for _ in range(width - 1):
data >>= 1
reflected = (reflected << 1) | (data & 0x01)
return reflected | bd5a0b804419c52ebdc6777fa0256c6a2dd4475c | 27,779 |
def snell_angle_2(angle_1, n_1, n_2):
"""Calculate the angle of refraction of a ray travelling between two mediums
according to Snell's law.
Args: angle_1 (array_like[float]): angle of incidence with respect to surface
normal in radians. n_1 (float): index of refraction in first medium.... | 5917dfc412e002bdfe494b3648dfdb7ba63a3cd7 | 27,780 |
def npv(ico, nci, r, n):
""" This capital budgeting function computes the net present
value on a cash flow generating investment.
ico = Initial Capital Outlay
nci = net cash inflows per period
r = discounted rate
n = number of periods
Example: npv(100000, 15000, .03, 10)
"""
pv_nc... | fa3128de0fe8a2f7b8bbe754f0e1b1e1a0eb222d | 27,781 |
import time
import functools
import threading
def instrument_endpoint(time_fn=time.time):
"""Decorator to instrument Cloud Endpoint methods."""
def decorator(fn):
method_name = fn.__name__
assert method_name
@functools.wraps(fn)
def decorated(service, *args, **kwargs):
service_name = service... | cf2fdfff5aa8854cc6c02850d6a9787ca45b7c7e | 27,782 |
def manhattan_distances(X, Y):
"""Compute pairwise Manhattan distance between the rows of two matrices X (shape MxK)
and Y (shape NxK). The output of this function is a matrix of shape MxN containing
the Manhattan distance between two rows.
Arguments:
X {np.ndarray} -- First matrix, contai... | 0cbec7eae4cb33d0ed13947bbc7df7b4b6171807 | 27,783 |
def remove_access_group(request):
"""
Add access groups to the image.
"""
if request.method != "POST":
messages.error(request, "Invalid request method.")
return redirect('images')
if 'id' not in request.POST or not request.POST.get('id').isdigit() or 'access_group' not in request.PO... | 1e61b0a403a06154dce5b7f745a401e7ddf635d6 | 27,784 |
import os
def convert_to_jpg_if_needed(src):
"""
If the src image is not in the supported image format list, convert it to jpg
:param src: the source file
:returns: None, or the new file (django file)
"""
im = Image.open(src)
if im.format in settings.XGDS_IMAGE_ACCEPTED_WEB_FORMATS:
... | 8ee46922c9098b2c15b83f71d5b41d4978e78059 | 27,785 |
def replace_strings_in_file(i):
"""
Input: {
file
(file_out) - if !='', use this file for output, otherwise overwrite original one!
replacement_json_file - replacement file with multiple strings to substitute
}
Output: {
return... | b15d3058e1486d6f6171438bd62da05cb8d5732b | 27,786 |
def fill_polygon(points, im_shape):
"""Fill the polygon defined by convex or contour points
Parameters
----------
points: array
Coordinates of the points that define the convex or contour of the mask
im_shape: array
Array shape of the mask
Returns
-------
im_cnt: array
Fil... | abbe69180582c12233c8632ca2ca60485ce4d717 | 27,787 |
def load(section, option, archive=_ConfigFile):
"""
Load variable
"""
cfg = ConfigParser()
try:
cfg.readfp(file(archive))
except Exception, e:
sys.stderr.write("%s, %s\n" % (archive, e.strerror))
return
try:
return cfg.get(section, option)
except:
sys.stderr.write("Incorrect value... | 3cf8bebb9ffdaf4a25ece950560680fabdf8c459 | 27,788 |
def merge_duplicates(model_name, keep_descriptors=False):
"""
Identifies repeated experimental values and returns mean values for those
data along with their standard deviation. Only aggregates experimental
values that have been acquired at the same temperature and pressure.
Parameters
--------... | a3baa232535f9c3bfd9496259f0cf3fd6142665b | 27,789 |
def autoencoder_cost_and_grad_sparse(theta, visible_size, hidden_size, lambda_, rho_, beta_, data):
"""
Version of cost and grad that incorporates the hidden layer sparsity constraint
rho_ : the target sparsity limit for each hidden node activation
beta_ : controls the weight of the sparsity pen... | 9810517cab7adc5ca71d46d602e347b301a392d4 | 27,790 |
def isnpixok(npix):
"""Return :const:`True` if npix is a valid value for healpix map size, :const:`False` otherwise.
Parameters
----------
npix : int, scalar or array-like
integer value to be tested
Returns
-------
ok : bool, scalar or array-like
:const:`True` if given value is... | 9501ab6e3172761cba0ec2e3693e5442924162af | 27,791 |
from cep_price_console.utils import config
import logging
import os
import yaml
def setup_logging(
default_level=logging.DEBUG,
env_key='LOG_CFG'
):
"""Setup logging configuration
"""
global debug_log
global info_log
global error_log
config.LOGGING_PATH.mkdir(parents=True, exis... | b3c437e7407dbb6a47f58e6a568d6f89c31241ac | 27,792 |
import shutil
import subprocess
def solve_field(fname, timeout=15, solve_opts=None, *args, **kwargs):
""" Plate solves an image.
Note: This is a low-level wrapper around the underlying `solve-field`
program. See `get_solve_field` for more typical usage and examples.
Args:
fname(str, req... | aebbc1770a8eea0faf958bbb4cfc3a00acc83381 | 27,793 |
def get_team_metadata(convert_users_role_to_string=False):
"""Returns team metadata
:param convert_users_role_to_string: convert integer team users' roles to human comprehensible strings
:type convert_users_role_to_string: bool
:return: team metadata
:rtype: dict
"""
response = _api.send_re... | 6b48cc6f30bd2304f54c1ff695be6faaab187a9f | 27,794 |
def get_request_timestamp(req_type=None, timestamp=getCurrentMillis()):
"""
:param req_type: YTD, QTD, MTD, WTD, TODAY or None
if None return first unix timestamp
:return: unix timestamp
"""
@dataclass
class YTD(object):
pass
bench_date = pd.to_datetime(getUTCBeginDay(timestamp... | 2e18c23167bca388b8f2ad4febfe6f3a39df1151 | 27,795 |
def to_nest_placeholder(nested_tensor_specs,
default=None,
name_scope="",
outer_dims=()):
"""Converts a nest of TensorSpecs to a nest of matching placeholders.
Args:
nested_tensor_specs: A nest of tensor specs.
default: Optional consta... | 329bf5e76f5753a07f78394a8a065e3e44334929 | 27,796 |
import asyncio
async def discover():
"""Discover and return devices on local network."""
discovery = TuyaDiscovery()
try:
await discovery.start()
await asyncio.sleep(DEFAULT_TIMEOUT)
finally:
discovery.close()
return discovery.devices | fb3fed149011983520d884f139f9296973686459 | 27,797 |
def update_firewall_policy(module, oneandone_conn):
"""
Updates a firewall policy based on input arguments.
Firewall rules and server ips can be added/removed to/from
firewall policy. Firewall policy name and description can be
updated as well.
module : AnsibleModule object
oneandone_conn: ... | 0d99fbee3a67e2c571bd9d9ad5ce698588ac0df4 | 27,798 |
def dense_to_one_hot(labels_dense, num_classes):
"""Convert class labels from scalars to one-hot vectors."""
num_labels = labels_dense.shape[0]
index_offset = np.arange(num_labels) * num_classes
labels_one_hot = np.zeros((num_labels, num_classes))
labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1
... | 916b040993489754bd3f07b5c7ffc9f3abaf1ed9 | 27,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.