content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _strip_asserts(source):
"""
Remove assert method calls from source code.
Using RedBaron, replace some assert calls with print statements that print the actual
value given in the asserts. Depending on the calls, the actual value can be the first or second
argument.
Parameters
----------... | 5,322,700 |
def _index_clusters(feat_mat, init_mat):
"""Creates a hierarchical binary tree till the top-level clusters supplied."""
cluster_feat = init_mat.T.dot(feat_mat)
cluster_feat = cluster_feat.tocsr()
cluster_feat = skprep.normalize(cluster_feat, "l2", axis=1)
init_cluster = HierarchicalKMeans.gen(
... | 5,322,701 |
def robot_terminal_join(message):
"""
Add a user to the RobotTerminal so they receive the output from the robot.
"""
try:
robot = get_robot_terminal_or_error(message['robot'], message.user)
# add user to the robot_terminal channel so that they get all the messages
robot.websocke... | 5,322,702 |
def gcd(numbers):
"""Return greatest common divisor of integer numbers.
Using Euclid's algorithm.
Examples
--------
>>> gcd([4])
4
>>> gcd([3, 6])
3
>>> gcd([6, 7])
1
"""
def _gcd(a, b):
"""Return greatest common divisor of two integer numbers."""
whil... | 5,322,703 |
def normal_attention(tensor_base, tensor_to_attend,
mask_for_tensor_base,
mask_for_tensor_to_attend,
similarity_method='inner', hn=100,
use_pooling=False, pooling_method='max',
reverse=False, scope=None):
"""
... | 5,322,704 |
def test_users(api):
""" Verify the ``users`` method call """
api._session.request.return_value = [USER1, USER2, USER3]
user_list = list(api.users())
exp_call = mock.call(method=GET, path=AP['get_users'])
assert all(map(lambda u: isinstance(u, dict), user_list))
assert len(user_list) == 3
... | 5,322,705 |
def getPageNum(html):
"""解析第一页网页,返回该用户的书评页数
"""
soup=BeautifulSoup(html,'html.parser')
paginator=soup.find('div','paginator')
pas=paginator.findAll('a')
num=int(pas[-2].text)
return num | 5,322,706 |
def test_basic_status_request_method(flask_app):
"""Tests allowed request methods"""
response = flask_app.post(basic_status_api+'imei=123456789012345&token=12345token&source=web')
assert response.status_code == 405
response = flask_app.put(basic_status_api+'imei=123456789012345&token=12345token&source=... | 5,322,707 |
async def get_user(api_management_name=None,resource_group_name=None,user_id=None,opts=None):
"""
Use this data source to access information about an existing API Management User.
> This content is derived from https://github.com/terraform-providers/terraform-provider-azurerm/blob/master/website/docs/d/api... | 5,322,708 |
def eval_write_answer(status_code, text, dryrun):
"""
Evaluate RIPE answer when writing objects
"""
if dryrun:
try:
exists = json.loads(text)["errormessages"]["errormessage"][0]["text"]
except:
print(f" RIPE answer: {text}")
else:
info = json.... | 5,322,709 |
def makeCC_allpair(spikes, Begin, End, N_thred):
"""
全てのCCをBegin~Endの間で計算する
args:
spikes: list型
Begin, End: int型
N_thred: 並列計算をするときに与えるスレッド数
return:
X: ペアごとに計算したCC. X.shape = (ニューロンのペア数、CCの幅)
index: ペアのニューロンの番号. index.shape = (ニューロンのペア数、2). index[i][0]は結合先ニューロン、in... | 5,322,710 |
def test_experiment(experiment, expected_type, named_configs, config_updates, extra_check):
"""Run Sacred experiment and sanity check run, including type of result."""
named_configs = named_configs + ["test"]
with tempfile.TemporaryDirectory(prefix="eval-rewards-exp") as tmpdir:
config_updates["log_... | 5,322,711 |
def move_position(facility, cur_position, direction):
"""Move position from cur_position in the direction on facility."""
changes = DIRECTIONS[direction]
doors = DIRECTION_TO_DOOR[direction]
for cell in (doors, ROOM):
next_position = []
for coordinate, change in zip(cur_position, changes... | 5,322,712 |
def search_for_improvements(
targets : [Exp],
wf_solver : ModelCachingSolver,
context : Context,
examples : [{str:object}],
cost_model : CostModel,
stop_callback : Callable[[], bool],
hints : [Exp],
ops : [Op],
... | 5,322,713 |
def down_sample(fft_vec, freq_ratio):
"""
Downsamples the provided data vector
Parameters
----------
fft_vec : 1D complex numpy array
Waveform that is already FFT shifted
freq_ratio : float
new sampling rate / old sampling rate (less than 1)
Returns
-------
... | 5,322,714 |
def main(args=None):
"""This is the Main Method.
"""
# loads setting file set parameters
settings = os.path.join(get_package_share_directory('ros2_camera_publish'),
"settings.json")
with open(settings) as fp:
content = json.load(fp)
... | 5,322,715 |
def set_device(cuda: bool) -> int:
"""Set the device for computation.
Args:
cuda (bool): Determine whether to use GPU or not (if available).
Returns:
int: Index of a currently selected device, CPU or GPU.
"""
device = torch.device("cuda" if (torch.cuda.is_available() and cuda) else "... | 5,322,716 |
def disallow_hurting_chair(actor, ctxt, y=None) :
"""These are trybefore to prevent trying to take anything."""
raise AbortAction("You would <i>never</i> even consider such a thing.") | 5,322,717 |
def hsic_regular(x, y, sigma=None, use_cuda=True, to_numpy=False):
"""
"""
Kxc = kernelmat(x, sigma)
Kyc = kernelmat(y, sigma)
KtK = torch.mul(Kxc, Kyc.t())
Pxy = torch.mean(KtK)
return Pxy | 5,322,718 |
def random_correlation(size, n_factors, random_seed=None):
"""
Generates a random correlation matrix with 'size' lines and columns and
'n_factors' factors in the underlying structure of correlation.
:param size: int. Size of the correlation matrix
:param n_factors: int. number of factors in the corr... | 5,322,719 |
def http_get_request(url, params, add_to_headers=None, _async=False):
"""
from 火币demo, get方法
:param url:
:param params:
:param add_to_headers:
:return:
"""
headers = {
'Content-type':
'application/x-www-form-urlencoded',
'User-Agent':
'Mozilla/5.0 (Windows... | 5,322,720 |
async def on_server_role_delete(role):
"""
This event is called when a new role is deleted in a server.
The Server object can be retrieved by ``role.server``.
Args:
role:
The Role object of the deleted role.
"""
print(role, "was deleted in", role.server) | 5,322,721 |
def password_reset_token_created(
sender, instance, reset_password_token, *args, **kwargs
):
"""
Handles password reset tokens
When a token is created, an e-mail needs to be sent to the user
sender: View Class that sent the signal
instance: View Instance that sent the signal
reset_password_t... | 5,322,722 |
def test_get_forwarding_addresses_forward_to_parsing(
forward_to,
expected,
example_vhost,
):
"""Make sure we're a little tolerant in forward_to parsing."""
fake_connection = mock.Mock(
__iter__=lambda _: iter(({
'address': 'test@test.com',
'password': Non... | 5,322,723 |
def run_sql(filename):
""" Executa todos os comandos de um arquivo .sql """
""" Não exibe resultados """
global connection
global cursor
# ler arquivo SQL em um único buffer
file = open(filename, 'r')
sql = file.read()
file.close()
# text = colored('Executando ' + filename, 'green'... | 5,322,724 |
def check_aliens_bottom(ai_settings, stats, screen, ship, aliens, bullets, sb):
"""
Sprawdzenie, czy którykolwiek obcy dotarł do dolnej krawędzi ekranu.
:param sb: Tablica wyników
:param ai_settings: Ustawienia
:param stats: Statystyki
:param screen: Ekran
:param ship: Statek
:param alie... | 5,322,725 |
async def test_custom_availability_payload(hass, mqtt_mock):
"""Test availability by custom payload with defined topic."""
await help_test_custom_availability_payload(
hass, mqtt_mock, select.DOMAIN, DEFAULT_CONFIG
) | 5,322,726 |
def eigendecompose(S):
"""Eigendecompose the input matrix."""
eigvals, V = np.linalg.eig(S)
return eigvals, V | 5,322,727 |
def _CreateSampleDirectoryCoverageData(builder='linux-code-coverage',
modifier_id=0):
"""Returns a sample directory SummaryCoverageData for testing purpose.
Note: only use this method if the exact values don't matter.
"""
return SummaryCoverageData.Create(
server_ho... | 5,322,728 |
def test_label_shift_weight_computation():
"""
Tests that label shift detection can determine the label marginals of validation data.
"""
train_proportion = [.7, .3]
target_proportion = [.3, .7]
data = synthetic_label_shift_simple(N=2000, label_proportions=train_proportion,
... | 5,322,729 |
def sched_time(update_time) -> int:
""" Return interval between the current time and the update time in
seconds
"""
current_time_ss = hhmm_to_seconds(current_time_hhmm())
update = hhmm_to_seconds(update_time)
interval = update-current_time_ss
return interval | 5,322,730 |
def http_jsonrpc_post(hostname, port, uri, method, params):
"""Perform a plain HTTP JSON RPC post (for task farming)"""
url = "http://%s:%s%s" % (hostname, port, uri)
data = simplejson.dumps({ 'method': method, 'params': params,
'jsonrpc': '2.0', 'id': 1 })
req = urllib2.Request(url, data, {'... | 5,322,731 |
def print_proxy_stats():
"""
prints out current progress in checking proxies, called first in code
:return: None
"""
global proxy_stats
print(
f"\nImported: {proxy_stats['suc']} | Dumped: {proxy_stats['fail']} | Dead: {proxy_stats['dead']} | Alive: {proxy_stats['alive']} | Running thread... | 5,322,732 |
def del_files_from_disk(path):
"""Delete files from disk.
"""
shutil.rmtree(path) | 5,322,733 |
def download_hitran(m, i, numin, numax):
"""
Download HITRAN data for a particular molecule. Based on fetch function from
hapi.py.
Parameters
----------
m : int
HITRAN molecule number
i : int
HITRAN isotopologue number
numin : real
lower wavenumber bound
numa... | 5,322,734 |
async def update_note(note,tags=None):
""" Uploads note to serve.
Required item or they will be erased: 'author', 'source_url', 'is_todo'
if 'is_todo' in addition: 'todo_due', 'todo_completed'
All other items are ignored.
:param note: note data as dict
:param tags: list of tag titles to ... | 5,322,735 |
def get_user_event(current_user, event_id):
"""
Query the user to find and return the event specified by the event Id
:param event_id: Event Id
:param current_user: User
:return:
"""
user_event = User.get_by_id(current_user.id).events.filter_by(event_id=event_id).first()
return user_even... | 5,322,736 |
def get_distances(scr_data_dict, distance_keys, data_centroid=None):
"""
@param scr_data_dict:
@param distance_keys:
@param data_centroid: Do not provide if calculating distances for establishing s thresholding
@return:
"""
dataset_keys = scr_data_dict.keys()
# Extracting dataset point o... | 5,322,737 |
def compare_numeric_abundances(values_in_taxa_list_1, values_in_taxa_list_2):
"""Retun a Pandas Series with [abundance-in, abundance-out, p-value]."""
mean1 = mean_ignore_nans(values_in_taxa_list_1)
mean2 = mean_ignore_nans(values_in_taxa_list_2)
keyslist1 = list(values_in_taxa_list_1.keys())
keysli... | 5,322,738 |
def parse_folder(folder, start_time=None, grepcmd=None, tmp_folder=None, force_grep=False):
"""
Args:
grepcmd, tmp_folder, force_grep's default value should be the same with parse_single_log_with_pregrep
Yields:
[[yield], []]: nested yields
"""
def get_first_last_line(filepath):
... | 5,322,739 |
def search(request):
"""
search function which reads get data from a requests and uses it to find stuff in elasticsearch
"""
context = {"table": []}
if "subject" in request.GET or "predicate" in request.GET or "object" in request.GET:
es = elasticsearch.Elasticsearch(settings.ELASTICSEARCH)
... | 5,322,740 |
def test_sbi_list_get_active():
"""Test method to get active SBI"""
DB.flush_db()
sbi_list = SchedulingBlockInstanceList()
pb_list = ProcessingBlockList()
sbi_list.subscribe('test_add_sbi')
sbi_config = generate_sbi_config()
# Register test workflow definitions needed for this SBI.
add_... | 5,322,741 |
def Write_data(data_name,parameters,metrics_name_list,length_input,metrics_mean_list,metrics_std_dev_list):
"""Writes the metrics of a given simulation in a datasheet in .txt format.
Parameters
----------
data_name: string
Desired name of data_sheet archive.
metrics_name_list: ... | 5,322,742 |
def parse_measurement_lines(xml_root: Element) -> Dict[int, LineString]:
"""Parses the measurement line from the given xml root
Args:
xml_root (ET.ElementTree): root of the xml file
Returns:
measurement lines to use in the analysis (id, line)
"""
measurement_lines = {}
if xml_... | 5,322,743 |
def compute_and_apply_approximate_vocabulary(
x: common_types.ConsistentTensorType,
default_value: Any = -1,
top_k: Optional[int] = None,
num_oov_buckets: int = 0,
vocab_filename: Optional[str] = None,
weights: Optional[tf.Tensor] = None,
file_format: common_types.VocabularyFileFormatType = ... | 5,322,744 |
def test_users():
"""Verify that you can list users."""
mock_request = Mock()
users = Users(fixture, mock_request)
assert users['userv']
assert users['userv'].name == 'userv'
assert users['userv'].viewer
assert not users['userv'].operator
assert not users['userv'].admin
assert not u... | 5,322,745 |
def album_cover():
"""Get the current song's album cover."""
cover = app.config["player"].album_cover()
image = io.BytesIO(cover) if cover else "static/no_cover.jpg"
return send_file(image, mimetype="image/jpeg") | 5,322,746 |
def test_serialize_numpy():
"""Regression test for #3709
Check that numpy arrays can be serialized.
"""
data = np.array([1, 2, 3])
serialized = serialize.serialize(data)
deserialized = serialize.deserialize_unsafe(serialized)
assert np.all(data == deserialized) | 5,322,747 |
def verify_bgp_community(
tgen,
addr_type,
router,
network,
input_dict=None,
vrf=None,
bestpath=False,
expected=True,
):
"""
API to veiryf BGP large community is attached in route for any given
DUT by running "show bgp ipv4/6 {route address} json" command.
Parameters
... | 5,322,748 |
def do(in_simulation_dir: str, in_topology_path: str, in_imd_path: str,
out_analysis_dir: str,
vacuum_simulation:bool=False,
gromosPP_bin: str = None,
in_ene_ana_lib: str = ene_ana_libs.ene_ana_lib_path,
verbose: bool = True):
"""
This analysis_worker is analyzing step a_s... | 5,322,749 |
def set_mailbox_message_limit(sender, instance, created, **kwargs):
"""Store mailbox message limit in Redis."""
set_message_limit(instance, instance.full_address) | 5,322,750 |
def create_new_filename(original_filename: str,
user_response: str):
"""
Creates new file name depending on the users response
:param original_filename: str
:param user_response: str
:return: str | new filename
"""
if user_response == "1":
time = str(today.time())[:8].repla... | 5,322,751 |
def get_maestral_command_path() -> str:
"""
Returns the path to the maestral executable. May be an empty string if the
executable cannot be found.
"""
try:
dist_files = files("maestral")
except PackageNotFoundError:
# we may have had installation issues
dist_files = []
... | 5,322,752 |
def genertate_info_tree(traces, trace_events, level="module"):
"""
"""
assert level in ["module", "operator", "mixed"]
tree = OrderedDict()
for trace in traces:
path, module = trace
# unwrap all of the events, in case model is called multiple times
events = [te for tevents i... | 5,322,753 |
def interpolate(x, ratio):
"""Interpolate data in time domain. This is used to compensate the
resolution reduction in downsampling of a CNN.
Args:
x: (batch_size, time_steps, classes_num)
ratio: int, ratio to interpolate
Returns:
upsampled: (batch_size, time_steps * ratio, classes_num... | 5,322,754 |
def _resolve_object(target):
"""Ask MAST to resolve an object string to a set of coordinates."""
from astroquery.mast import MastClass
# Note: `_resolve_object` was renamed `resolve_object` in astroquery 0.3.10 (2019)
return MastClass().resolve_object(target) | 5,322,755 |
def test_block_merge_adjacent():
"""Make sure Block.merge() works when the blocks don't overlap, but are adjacent."""
input_1 = StringIO(dedent("""
Human chr6 50 77 + CGG---GA---TCAACCAAG--AAGAATTGCTATA---
Chimp chr6 7000 7032 - CGGTTGGACCCTCA---AAGttAAGAATT---ATAcct
""").lstrip())
input_2 = S... | 5,322,756 |
def spgr(pd, r1, r2s=None, mt=None, transmit=None, receive=None, gfactor=None,
te=0, tr=25e-3, fa=20, sigma=None, device=None):
"""Simulate data generated by a Spoiled Gradient-Echo (SPGR/FLASH) sequence.
Tissue parameters
-----------------
pd : tensor_like
Proton density
r1 : tens... | 5,322,757 |
def setup_options():
"""
add logging options to cmd-line,
but surpress them, so that they don't clobber up the help-messages
"""
import argparse
my_argparser = argparse.ArgumentParser(add_help=False)
my_argparser.add_argument("--LogLevel_Model", default = "", \
help = argpars... | 5,322,758 |
def create_subject(request):
"""
This is a form
"""
template = loader.get_template('form.html')
form = SubjectForm()
return HttpResponse(template.render({'form':form, 'redirect': '/subject', 'submit':'Create Subject and add to class'}, request)) | 5,322,759 |
def text2number(text):
"""
Convert arabic text into number, for example convert تسعة و عشرون = >29.
Example:
>>> text2number(u"خمسمئة و ثلاث و عشرون")
523
@param text: input text
@return: number extracted from text
@rtype: integer
"""
number_names = WORDS_NUMBERS.copy()
... | 5,322,760 |
def parse_prototype(prototype, additional_definitions={}):
"""Given a single annotated C function prototypes (see module docstring),
for syntax), and an optional dict of non-base type definitions,
return the following information that ctypes needs to load and annotate
a function:
function_name: str
... | 5,322,761 |
def create_resource():
"""QonoS resource factory method."""
return wsgi.Resource(SchedulesController()) | 5,322,762 |
def test_not_found(app: Teal):
"""
When not finding a resource, the db should raise a ``NotFound``
exception instead of the built-in for SQLAlchemy.
"""
with app.app_context():
Device = app.resources['Device'].MODEL
with pytest.raises(NotFound):
Device.query.one() | 5,322,763 |
def compute_heatmap(model, saved_model, image, pred_index, last_conv_layer):
"""
construct our gradient model by supplying (1) the inputs
to our pre-trained model, (2) the output of the (presumably)
final 4D layer in the network, and (3) the output of the
softmax activations from the model
"""
... | 5,322,764 |
def get_all_orders():
"""Returns a list of ALL the orders for rooms and AGs, with reader and approver specified for each."""
# Get a list of all the orders of access groups of all responsible approvers.
ag_relation = ApprovesAgRequest.query \
.join(AccessGroupRequest, AccessGroupRequest.id == ApprovesAgRequest.ag... | 5,322,765 |
def isAnomaly(lowBand, highBand, value):
"""Condition for anomaly on a certain row"""
if value < lowBand or value > highBand:
return True
return False | 5,322,766 |
def main():
"""Send, receive and check IPv6 and IPv6ExtHdrSegmentRouting packets."""
args = TrafficScriptArg(
[
u"tx_src_mac", u"tx_dst_mac", u"rx_src_mac", u"rx_dst_mac",
u"src_ip", u"dst_ip", u"dir0_srcsid", u"dir0_dstsid1",
u"dir0_dstsid2", u"dir1_srcsid", u"dir1_... | 5,322,767 |
def initWeights(positive_count, negative_count, trainingSamples):
"""
Initialise weights.
:param positive_count: Number of positive samples.
:param negative_count: Number of negative samples.
:param trainingSamples: Training samples.
:return: Weights
"""
positiveSampleInitialWeight ... | 5,322,768 |
def get_distance_calculator(name, *args, **kwargs):
"""returns a pairwise distance calculator
name is converted to lower case"""
name = name.lower()
if "moltype" in kwargs and kwargs.get("moltype") is None:
kwargs.pop("moltype")
if name not in _calculators:
raise ValueError('Unknown... | 5,322,769 |
def import_api(Basepath=None, Body=None, FailOnWarnings=None):
"""
Imports an API.
See also: AWS API Documentation
Exceptions
:example: response = client.import_api(
Basepath='string',
Body='string',
FailOnWarnings=True|False
)
:type Basepath: stri... | 5,322,770 |
def git_ls_dirs(root=None):
"""
List all folders tracked by git.
"""
dirs = set()
for fn in git_ls_files(root):
dirs.add(os.path.dirname(fn))
return list(dirs) | 5,322,771 |
def compute_escape_peak(spectrum, ratio, params,
escape_e=1.73998):
"""
Calculate the escape peak for given detector.
Parameters
----------
spectrum : array
original, uncorrected spectrum
ratio : float
ratio of shadow to full spectrum
param : dict
... | 5,322,772 |
def create_transaction(wallet, purchase):
"""
creates a transaction of crypto from the PSP wallet to a user who has paid in fiat
Note: Ideally this will be done for more than 1 tx at a time.. would have a basket of tx ready to go
and then they will all go out in one TX with all the outputs. Then the s... | 5,322,773 |
def _create_globio_lulc_op(
lulc_array, potential_vegetation_array, pasture_array,
ffqi, globio_nodata, pasture_threshold, primary_threshold):
"""Construct GLOBIO lulc given relevant biophysical parameters."""
result = numpy.empty_like(lulc_array, dtype=numpy.int16)
result[:] = globio_nodata... | 5,322,774 |
def load_data():
"""These function will load up the data like as done in phase 4 and 5 """
pass | 5,322,775 |
def load_tlm_npz(tf_tlm: tf.keras.layers.Layer, npz: str, embeddings_key: str = 'x', name: str = "TLM"):
"""Restore a TLM-like model (possibly a `Model` for fine-tuning
We just populate the `TransformerEncoderStack` and the embeddings from weights, all other values remain
uninitialized
:param tf_tlm: ... | 5,322,776 |
def temperature_dist():
"""Random normal variated temperature around RT_MEAN with RT_SIGMA"""
return random.normalvariate(RT_MEAN, RT_SIGMA) | 5,322,777 |
def pair_keys_to_items(items, key):
"""
Convert the list of key:value dicts (nics or disks) into a dict.
The key for the new dict is one value of the current dict identified by the
key parameter. If it does not exist, then the key is the order number in
the list.
"""
new_items = {}
for ... | 5,322,778 |
def load_results(model_no=0):
""" Loads saved results if exists """
losses_path = "./data/test_losses_per_epoch_%d.pkl" % model_no
accuracy_path = "./data/test_accuracy_per_epoch_%d.pkl" % model_no
train_accuracy_path = "./data/train_accuracy_per_epoch_%d.pkl" % model_no
if os.path.isfile(losses_pat... | 5,322,779 |
def rotateStructure(structure):
"""
Rotate a structure randomly
"""
angle_rad = _np.random.rand(1) * 2 * _np.pi
newstructure = _np.array(
[
(structure[0, :]) * _np.cos(angle_rad)
- (structure[1, :]) * _np.sin(angle_rad),
(structure[0, :]) * _np.sin(angle_r... | 5,322,780 |
def fetch_download(file_path, url: str):
"""Circumvent the cache for large file downloads."""
session = requests.Session()
session.headers.update(HEADERS)
log.info("Fetching resource", path=file_path.as_posix(), url=url)
file_path.parent.mkdir(exist_ok=True, parents=True)
with session.get(url, s... | 5,322,781 |
def dedup_model2_norm_by_layer_dedup_by_layer(method):
"""Here, we perform the deduplication to rcv1_2k_xml model, while we normalize the block magnitude
by layer then order them by layer (largest first)
Please use the correct commented out code to evaluate different approaches.
"""
model_path = 'm... | 5,322,782 |
async def iamalive(name, **params):
"""
Accept services promotions
"""
await state.alive_service(name)
return OK | 5,322,783 |
def add_edge(ref_slit, insert_offset, earr, t_dict, final_left, final_right, left=True):
""" Add a new edge using a reference slit
right_slit : Reference slit for the left one
insert_offset : int
Offset fromm the right slit for the new left slit
"""
# New left edge index
if left== 'left':... | 5,322,784 |
def get_finding_statistics(findingCriteria=None, groupBy=None, size=None, sortCriteria=None):
"""
Retrieves (queries) aggregated statistical data about findings.
See also: AWS API Documentation
Exceptions
:example: response = client.get_finding_statistics(
findingCriteria={
... | 5,322,785 |
def diff_payment(loan_p, periods, interest):
"""Function calculates differentiated monthly payment"""
i = interest / 1200
overpayment = 0
for m in range(1, periods + 1):
d_m = math.ceil((loan_p / periods) + i * (loan_p - ((loan_p * (m - 1)) / periods)))
overpayment += d_m
... | 5,322,786 |
def test_read_no_node_id() -> None:
"""Raise TypeError if no node_id is provided for a GET request."""
with pytest.raises(TypeError) as excinfo:
Request("GET", "https://example.org/", AssetType())
assert str(excinfo.value) == "missing required keyword argument: 'node_id'" | 5,322,787 |
def classical_mult(A, x, y):
""" scipy default sparse matrix-vector multiplication
"""
y[:] = A.dot(x) | 5,322,788 |
def add_wind_rotation_info(res: str, ds: xr.Dataset) -> xr.Dataset:
"""
Add wind rotation information to the dataset
Args:
res: grid resolution, format as f'c{number cells in tile}'
"""
rotation = _load_wind_rotation_matrix(res).drop_vars("tile", errors="ignore")
common_coords = {"x": ... | 5,322,789 |
def get_human_size(size):
"""Return a string describing the size in bytes"""
if size < 1024:
return '{} B'.format(size)
if size < 1024 * 1024:
return '{:.2f} KB'.format(float(size) / 1024)
if size < 1024 * 1024 * 1024:
return '{:.2f} MB'.format(float(size) / (1024 * 1024))
if... | 5,322,790 |
def do_authentication(environ, start_response, authn_context, key,
redirect_uri, headers=None):
"""
Display the login form
"""
logger.debug("Do authentication")
auth_info = AUTHN_BROKER.pick(authn_context)
if len(auth_info):
method, reference = auth_info[0]
... | 5,322,791 |
def prepare_m2m_data(model, ctx_dict, fields, parent_ids):
"""
Recebe os argumentos e devolve um dicionário com os dados necessários para montar a lista
"""
#print('in_prepare_m2m_data')
name = ctx_dict.get('name')
record = ctx_dict.get('record')
edit_ok = ctx_dict.get('edit_ok')
popup =... | 5,322,792 |
def empty_when_none(_string=None):
"""If _string if None, return an empty string, otherwise return string.
"""
if _string is None:
return ""
else:
return str(_string) | 5,322,793 |
def visualizeFrame(x, y, z, translation, size = 0.1):
""" Input: x - numpy array (x, y, z) or column vector
y - numpy array (x, y, z) or column vector
z - numpy array (x, y, z) or column vector
translation - numpy array (x, y, z) or column vector
... | 5,322,794 |
def baseline_dwt(
array,
max_iter,
level=None,
wavelet="sym6",
background_regions=None,
mask=None,
mode="constant",
axis=-1,
):
"""
Iterative method of baseline determination, based on the discrete wavelet transform.
Parameters
----------
array : `~numpy.ndarray`
Data with ba... | 5,322,795 |
def get_ego_polygon(ego_state: StateSE2, vehicle: VehicleParameters) -> Polygon:
"""
Return Shapely polygon correspoding to Ego
:param ego_state: x, y (center of rear axle) and heading
:param vehicle: Parameters of the vehicle
:return: Shapely polygon for ego
"""
ego_rectangle = construct_eg... | 5,322,796 |
def file_hashes(f, bufsize=16000000):
"""
computes md5, sha1, sha256 from a file obj. intended for large files.
returns 3-tuple of hexstrings
"""
md5 = hashlib.md5()
sha1 = hashlib.sha1()
sha256 = hashlib.sha256()
while True:
buf = f.read(bufsize)
if len(buf) == 0:
break
md5.update(bu... | 5,322,797 |
def paginate_update(update):
"""
attempts to get next and previous on updates
"""
time = update.pub_time
event = update.event
try:
next = Update.objects.filter(event=event, pub_time__gt=time).order_by('pub_time').only('title')[0]
except:
next = None
try:
previous... | 5,322,798 |
def get_timestep(all_params, stuff_for_time_loop):
"""
Gets the full VFP + logging timestep
:param all_params: (dictionary) contains input parameters for simulation
:param stuff_for_time_loop: (dictionary) contains derived parameters for simulation
:return: a function with the above values initializ... | 5,322,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.