content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def push_changelog_file(conn_api, changelog_file):
"""
Fixture to push to the FIRE archive a mock CHANGELOG to be used with the CurrentTree.run function
Returns
-------
FIRE path of the object that has been pushed
"""
conn_api.push_object(fileO=changelog_file,
fire_... | 6b2a3cd0b414b5166b77076cfae0b16c6088969e | 583,557 |
import hashlib
def get_sha256(local_path):
"""
Computes the sha256 of a local file.
:param local_path: string/path to file
:return: sha256 checksum
"""
file_hash = hashlib.sha256()
with open(local_path, "rb") as in_f:
for chunk in iter(lambda: in_f.read(512 * file_hash.block_size)... | 8f5ae6d2c80c90b4db963bb3cd069e7b253b3372 | 583,560 |
def gross_lev(positions):
"""
Calculates the gross leverage of a strategy.
Parameters
----------
positions : pd.DataFrame
Daily net position values.
- See full explanation in tears.create_full_tear_sheet.
Returns
-------
pd.Series
Gross leverage.
"""
e... | 3451ff9fc4807f45eb33a38498145565d27e5fe3 | 583,561 |
import random
def choice(*args):
"""
Wrapper for random.choice that takes variadic arguments. This allows
iterables and sets to also be used.
Example usage::
x = {1, 2, 3, 4, 5}
y = choice(*x)
"""
return random.choice(args) | b83385657a5946936c6c652357a7b4c052a1648c | 583,563 |
def getSectionNumber(header):
"""
Retrieve the section number of the given node.
@type header: A DOM Node or L{None}
@param header: The section from which to extract a number. The section
number is the value of this node's first child.
@return: C{None} or a C{str} giving the section number.
... | 81b876ce37468f5cfa83db4e9b16c0bc96cf7a77 | 583,567 |
def deduce_loop_size(subject: int, public_key: int) -> int:
"""
Deduce the loop size for ``public_key`` by transforming the ``subject``.
:return: The loop size, or -1 if no success
"""
value = 1
for loop_ct in range(100000000):
if value == public_key:
return loop_ct
... | 2a717562cf6d3e62105e8dbba1d1295a04ecdc8a | 583,568 |
import re
def _dots_to_triple_under(astring):
"""Convert all instances of '.' to '___'."""
return re.sub(r'\.', '___', astring) | 50011114b3012cb6acf55d1d0b2793f9217aa735 | 583,573 |
def macd(df, n_fast=12, n_slow=26, n_signal=9):
"""Calculate MACD, MACD Signal and MACD difference
:param df: pandas.DataFrame
:param n_fast:
:param n_slow:
:return: pandas.DataFrame
"""
EMAfast = df.ewm(span=n_fast, min_periods=n_slow).mean()
EMAslow = df.ewm(span=n_slow, mi... | 890eeecd658c8f868e02d830b83308c8881d4f49 | 583,578 |
def swap(pair):
"""Swap the items in a pair. Return tuple.
>>> swap((1, 2))
(2, 1)
"""
x, y = pair
return y, x | 60b4170b95cf5d664911a60ae1cc2a5c36b80eb9 | 583,586 |
def arbg_int_to_rgba(argb_int):
"""Convert ARGB integer to RGBA array."""
red = (argb_int >> 16) & 255
green = (argb_int >> 8) & 255
blue = argb_int & 255
alpha = (argb_int >> 24) & 255
return [red, green, blue, alpha] | d47c4c3614b720502fb8aacf4c84957f5447c86e | 583,588 |
def replace_country(record: dict, country_name: str, area_name: str):
"""
Replace country name with an `area_covered` name.
Promote a string in `area_covered` to `country_territory_area`.
Applies to records where a WHO recognised country is defined as an
administrative region of a different countr... | e72da80841f4d689aef3571e79745bf3356ae510 | 583,598 |
def response_to_handler_out(response):
"""
Build expected handler return from a Response
"""
return dict(
statusCode=response.status,
body=response.body,
headers={
'Content-Language': 'en',
'Content-Length': len(response.body),
'Content-Type': ... | f1ae1ed87fb8e95ab8e579f97e97d90cbc479223 | 583,604 |
import hashlib
import json
def meta_hasher(**metadata):
"""
Compute the metadata dictionary and hashcode for this run.
We use the hashcodes to distinguish runs.
"""
# compute metadata once for this batch
hashcode_this = hashlib.sha1(json.dumps(metadata,
ensure_ascii=True,sort_keys=True,default=str
).encode(... | bd24891995b16d520220d6ed7374e47687c0b154 | 583,607 |
import json
def load_dict(file_path):
"""Load dictionary from ``file_path``"""
# Check if file exists
try:
file = open(file_path)
except OSError:
print(f"Could not read file from {file_path}\nReturn None")
return None
# Load file
with file as json_file:
return... | 04ea967399a61ceef4030f4b1fd86631121a83d3 | 583,608 |
def _models_save_all_function_name(model):
"""Returns the name of the function to save a list of models as existing records"""
return '{}_save_all_existing'.format(model.get_table_name()) | 14cae95731dcb0e42ebd7b2be31d3a7294d9a120 | 583,609 |
def hexd(digit):
"""
Returns a hex digit '0'..'F' for an integer 0..15
:param digit: integer 0..15
:returns: an ASCII hex character '0'..'F'
"""
if digit < 10:
return chr(ord('0')+digit)
else:
return chr(ord('A')-10+digit) | 0a8c8f3e36561e18ac64f944b6f4702bf71fc88d | 583,610 |
def inline_code(text):
"""Return formatted inline code.
>>> inline_code("This text is code")
'`This text is code`'
"""
return f"`{str(text)}`" | 24827b350d9a11f32cd3c4ac5f6177aa3e15cc3a | 583,613 |
def lookup_page(tiff_page):
"""Obtain relevant information from a TiffPage object"""
xy_dim = (tiff_page.image_width, tiff_page.image_length)
description = tiff_page.image_description.decode('utf-8')
return xy_dim, description | eae33d52899842b21f08ab621a4198802806c15e | 583,615 |
def split_args(args):
"""Split command line args in 3 groups:
- head, containing the initial options
- body, containing everything after head, up to the first option
- tail, containing everything after body
"""
head = []
body = []
tail = []
for arg in args:
if arg.startswith... | 36525eb0dad4b4a1d4f220716dd1b6787192db25 | 583,616 |
def calculate_packet_loss_values(dropped_packets_rate, total_packets_rate):
""" Calculate the packet loss (percentage)
Args:
dropped_packets_rate (float): The rate of dropped packets (packets/sec)
total_packets_rate (float): The rate of total packets (packets/sec)
Returns:
float: T... | e05ee04027d1c928721efe64eda206c94ac115c9 | 583,621 |
def rescale_read_counts(c0, c1, max_allowed_reads=100):
"""Ensures that n_total <= max_allowed_reads, rescaling if necessary."""
Total = c0 + c1
if Total > max_allowed_reads:
c0 = int(max_allowed_reads * float(c0/Total))
c1 = max_allowed_reads - c0
return c0, c1 | 19bdec8db1e87eb73a9f54bf3565a66464e7f633 | 583,622 |
def parseSubscripts(subscr: str):
"""
Parse the subscripts for a primitive category
"""
if subscr:
return subscr[1:-1].split(",")
return [] | b5994ea70709c12380942b094dddab81711e3a1b | 583,623 |
def build_image_args(version):
"""
Returns a list of --build-arg command line arguments that are used by the
docker build command.
Arguments:
- version: Can be a str, in which case it's considered the PRODUCT
or a dict.
"""
result = []
if isinstance(version, dict):
... | 3629f81c752b0eadea27d97430af40d0159e8ef6 | 583,625 |
import math
def entropyOfList(ls):
"""
Given a list of some items, compute entropy of the list
The entropy is sum of -p[i]*log(p[i]) for every unique element i in the list, and p[i] is its frequency
"""
elements = {} # 计数 后面优化
for e in ls:
elements[e] = elements.get(e, 0) + 1
leng... | da8f04afbf66241bc7f5954a627c8f71b276f9ce | 583,628 |
def cut_text_below(text, depth):
"""Simplify text to only show the top parts of a tree
>>> print(cut_text_below("(ROOT (NP (PRP I)) (VP (VBD ran) (NP (NN home))))", 1))
(ROOT)
>>> print(cut_text_below("(ROOT (NP (PRP I)) (VP (VBD ran) (NP (NN home))))", 2))
(ROOT (NP) (VP))
>>> print(cut_text_below("(ROOT (NP (PR... | 52f09dbbe0a8edc0075d922f5c2dcc5a5c609253 | 583,630 |
def is_enum_value(enum_class, potential_value):
"""
A utility function that checks if the enumeration class contains the
provided value.
Args:
enum_class (class): One of the enumeration classes found in this file.
potential_value (int, string): A potential value of the enumeration
... | 9c2f9bd3f46b40eba8cff9edfbbb1bac25a5014e | 583,632 |
import math
def factorial(n):
"""Return the factorial of n, an exact integer >= 0.
>>> [factorial(n) for n in range(6)]
[1, 1, 2, 6, 24, 120]
>>> factorial(30)
265252859812191058636308480000000
>>> factorial(-1)
Traceback (most recent call last):
...
ValueError: n must be >= 0... | b26b599a1c0f5ab2cc5396dae4b003ec4af3e1a7 | 583,634 |
from typing import List
from typing import Any
from typing import Tuple
import random
def consistent_shuffle(*lists: List[List[Any]]) -> Tuple[List[Any], ...]:
"""
Shuffle lists consistently.
Parameters
----------
*lists
Variable length number of lists
Returns
-------
shuffle... | 89b83e53faf308c46d9b3c1cce7076504840f972 | 583,637 |
def get_min_max(ints):
"""
Return a tuple(min, max) out of list of unsorted integers.
Args:
ints(list): list of integers containing one or more integers
"""
min_num = ints[0]
max_num = ints[0]
for i in ints:
if i <min_num:
min_num = i
elif i >max_num:
max_num = i... | 4f392ae011e4570c5bb70ddb93f1768e7f526458 | 583,639 |
def read_test(data_path):
"""Read a wd_*.f1 file in NET-COLING2018 dataset and returns as a list."""
test_examples = []
with open(data_path, 'r', encoding='utf-8') as lines:
for line in lines:
if line:
test_ex = list(line.strip())
test_examples.append(test... | c479ae7953188db5077d6acad360234c7599b74f | 583,642 |
def darken(color,alpha):
"""Darkens a color to specified alpha"""
return (color[0],color[1],color[2],alpha) | 087a944d79a850fc1fe64b43165746c9b4cc39e5 | 583,645 |
def run_test_commands(conda_env_file, test_commands):
"""
Run a list of tests within a conda environment.
Args:
conda_env_file (str): The name of the conda environment file used to create the conda environment.
test_commands (:obj:`list` of :obj:`TestCommand): List of test commands to run.
... | 39b8c80831d1eaf5cb5ea25f6e3f7b412101c637 | 583,649 |
def interp_star_status(status):
"""Interprets \*STATUS command output from MAPDL
Parameters
----------
status : str
Output from MAPDL *STATUS
Returns
-------
parameters : dict
Dictionary of parameters.
"""
parameters = {}
st = status.find("NAME ... | ee42d247c80985ad25d3283ce118b63472cdb43e | 583,651 |
from typing import Type
def _type_to_key(t: Type) -> str:
"""
Common function for transforming a class type to its associated string key
for use in configuration semantics.
:param t: Type to get the key for.
:return: String key for the input type.
"""
return f"{t.__module__}.{t.__name__}" | c88bd2ebb6b537682328d3bcc9350daa2fe54e6c | 583,652 |
def find_first(searched, vec):
"""return the index of the first occurence of item in vec"""
for i, item in enumerate(vec):
if searched == item:
return i
return -1 | 846b697cd680b9332c70390910bfeee00f7f47e9 | 583,655 |
def cnn_output_length(input_length, filter_size, border_mode, stride, dilation=1):
""" Compute the length of the output sequence after 1D convolution along
time. Note that this function is in line with the function used in
Convolution1D class from Keras.
Params:
input_length (int): Lengt... | a6c12285cf5087259b03eade66cb62379d172347 | 583,656 |
def __get_data_at_step(file, mtm_dat, var):
"""
Find the data step that corresponds to an BPM image file and get the
corresponding data (key `var`) from an MTM data file.
Parameters
----------
file: str
The path to a BMP image file. The file name given by the PCS instrument
may... | f5248f925a4e543be1c4bd5faf078e51df0603ff | 583,658 |
def _file_size_bytes(*file_paths):
"""
Total file size for the given paths.
:type file_paths: list[Path]
:rtype: int
"""
return sum([p.stat().st_size for p in file_paths]) | be9a01631724dd2d13c925ae7c5f7ae30fb28cfe | 583,660 |
def find_pop(db, k, spec_range):
"""
:param db: list of designs
:param k: integer indicating the cut off rank
:param spec_range: dictionary indicating the desired specifications
:return:
pop: dictionary: keywords are the desired specs as well as 'cost'.values are db entries
sorted by the key... | 50ea1654fc30ac0d4720942f6259ddbf3fd1276d | 583,662 |
def transformer_class(source):
""" Imports the transformer class for a data source """
class_name = source['transformer']
sub_mods = class_name.split(sep=".")
module = __import__(".".join(sub_mods[:-1]), fromlist=sub_mods[-1])
class_module = getattr(module, sub_mods[-1])
return class_module | 1671aab9b878df01d7ca24174ac5688cb62e2304 | 583,664 |
import math
def vector_of_angle(angle):
""" Unit vector of an angle in degrees. """
return [[0.0, 0.0], [math.sin(math.radians(angle)), math.cos(math.radians(angle))]] | 3ac8b4b4a04dc40cf533588a9bf17cb2b0220588 | 583,672 |
def set_srate(srate=44100.0):
"""Sets the default sampling rate."""
global _srate
_srate = srate
return _srate | 51ac8459855c0fc36aba2310b1bbe5b371098be0 | 583,673 |
from typing import Tuple
def output_shape_conv_and_pool_layer(rows: int,
columns: int,
kernel: int,
stride: int = 1,
padding: int = 0,
... | 2683efe82af24d3fb6d31bdb225779445b607df5 | 583,675 |
from typing import List
import json
def get_checks_from_appinspect_result(path: str) -> List[str]:
"""
Returns manual checks from appinspect json result file
:param path: path to json result file
:return: list of checks in string format
"""
manual_checks = []
with open(path) as f:
... | 4cce76b49e3792c4d40bfe9fc091c5e2681cb970 | 583,676 |
def depth_first_traversal(graph, currentVertex, visited, flag: bool=False) -> list:
"""Depth first traversal to find all paths from 'start' to 'end'
Args:
graph (list): adjacency list
currentVertex (str): string (key into adjacency list)
visited (list): current traversal path
fl... | 7ec54d72ce9ea5cf751662ed23c0489fd5e8c877 | 583,678 |
def speed_for_human(speed):
"""
Returns a string showing human readable speeds given in Mbps.
"""
if not speed:
return ""
elif speed >= 1000000 and speed % 1000000 == 0:
return f"{int(speed / 1000000)} Tbps"
elif speed >= 1000 and speed % 1000 == 0:
return f"{int(speed / ... | 7ce3c74d49be46a1b5efcf8a503f5603445021bd | 583,679 |
import re
def parse_field(line):
"""
Will match:
Number -> (Number, None, None)
+Number -> (+Number, None, None)
Name -> (None, Name, None)
Name (Number) -> (None, Name, Number)
Name (+Number) -> (None, Name, +Number)
"""
p = re.compile(r'^\+?(\d+)$|^(.*?)\s*(?:\(\+?(\d+)\))?$')
m = p.match(line)
if not m:... | 311e0f4d431dfc0dc89b4d4a649ca504631acad6 | 583,680 |
def tensorshape_to_intlist(tensorshape):
"""
TensorFlow has its own wrapper for shapes because some could be None. This function turns them into int-lists. None will become a 1.
Arguments
---------
tensorshape : tf.TensorShape
Return
------
output : list
list of ints co... | 2402b1817697d00dca716876d1668bff7cf90c61 | 583,681 |
def try_get_key(frame, key, default_value=-1):
"""Return `key` in `frame` if it exists; otherwise return `default_value."""
try:
return frame[key]
except KeyError:
return default_value | bb2853a3618f40705d0fc6f56475541acc1213eb | 583,684 |
def create_set_state_payload(context: str, state: int):
"""Create and return "setState" dictionary to send to the Plugin Manager.
Args:
context (str): An opaque value identifying the instance's action you want to modify.
state (int): A 0-based integer value representing the state of an action w... | 3bff49a05b66d7fc4b0615c0e4c8659a8666d364 | 583,685 |
def make_message(msg_format, coll_id="testcoll", type_id="testtype", **kwargs):
"""
Combine supplied message format string with keyword parameters to build
a message text.
"""
msg_vals = dict(kwargs, coll_id=coll_id, type_id=type_id)
msg_text = msg_format%msg_vals
... | 6f909c7d6a5b38a1f2c7b8b3668c9bdcfdc59d19 | 583,695 |
def get_audio_version(version):
"""
Get audio version into a human easy readable format.
Arguments:
:param version: integer
:return: string
"""
return "MPG-%i" %(version) | 91543b2462dc960c31043492f7eea69c1325cd1f | 583,697 |
import math
def weightedMeanStdDev( valueList, weights, scale ):
"""Compute the weighted mean and standard deviation of a *non-empty* list of numbers."""
numElements = sum(weights)
if len(valueList) < 1 or numElements == 0:
return(None, 0.0)
mean = 0
for i in range(len(valueList)):
mean += float(valueList[... | 2d4bb18604e00c40bbd1ae919aed214c2c1ca658 | 583,698 |
import torch
def construct_length_mask(seq_lengths):
"""
construct sequence length mask to rule out padding terms.
:param seq_lengths: a list or 1D Tensor containing the lengths of the sequences in a batch
:return: a 2D Tensor containing the mask
"""
max_sequence_length = max(seq_lengths)
... | 5b3215cd34e95e6e6ef7db564abf679751bcb9b1 | 583,702 |
def does_match_fields(d, field_match):
"""
Returns if the given dictionary matches the {field_match}.
{field_match} may look like: { 'must_be' : 'this', 'and_any_of_' : ['tho', 'se']} """
if not field_match:
return True
for mk, mv in field_match.iteritems(): # each matches must be fulfilled
... | 75cc671f4ba7b8336b0dad92871d538540e63671 | 583,703 |
def is_unlucky_ticket(ticket: str) -> bool:
"""
Проверяет, является ли шестизначный номер билета несчастливым.
Номер билета является несчастливым, если сумма его цифр делится на 13 без остатка.
:param ticket: Шестизначный номер билета.
:return: Результат проверки.
"""
if len(ticket) != 6:
... | 57d994bb8d1f88271f29abf61c0b221f737adaf6 | 583,704 |
def pressure_error(g, num_pressure, true_pressure):
"""Computes discrete L2-error norm for the cell-centered pressures"""
V = g.cell_volumes
error = (V * (true_pressure - num_pressure) ** 2).sum() ** 0.5 / (
V * true_pressure ** 2
).sum() ** 0.5
return error | 00010df5ff88053a713217429c81dad961c215d3 | 583,705 |
import json
def get_all_titles(images_ndjson):
"""Load a list of all titles from images.ndjson."""
titles = []
with open(images_ndjson) as f:
for line in f:
row = json.loads(line)
title = row.get('title')
if title:
titles.append(title)
return... | 5a26b1b39e667459b039c3d1c13147eccb16d06d | 583,706 |
from pydantic import BaseModel # noqa: E0611
import hashlib
def hash_model(obj: BaseModel, **kwargs) -> str:
"""
Creates a deterministic hash of ``obj``, which is some pydantic model. All keyword arguments are forwarded on to
:meth:`pydantic.BaseModel.json`.
"""
digest = hashlib.sha256(obj.json(s... | 0ccb11eca8e4ddf2f63151001381e0fca5e76ca0 | 583,710 |
def hisat2_index_from_prefix(prefix):
"""
Given a prefix, return a list of the corresponding hisat2 index files.
"""
return ['{prefix}.{n}.ht2'.format(prefix=prefix, n=n) for n in range(1, 9)] | 81069fd3faec957e6edbc1aae80f4f3afe1644e9 | 583,711 |
def check_candidates_against_protected(candidates, protected):
"""
use sets to check whether there is any common membership
"""
if bool(set(candidates) & set(protected)):
return True
else:
return False | f5dd4c5f9d6f7fbc00d999aa4187236fb152fb88 | 583,713 |
def ddg ( gxw ):
"""2nd derivative of the psychometric function"""
return gxw*(1-gxw)*(1-2*gxw) | ac32ab8749100a16b76ddaca41d1de0d32ba458f | 583,720 |
def create_new_features(clean_df):
"""
Function to create new features using the cleansed data
clean_df (DataFrame) : DataFrame which is used to create new features
return (DataFrame) : DataFrame with the derived features
"""
# Convert gender feature to numbers
genders = {"male": 0, ... | 42fcee1968b99fd9e10bfde28ce87f20824328e1 | 583,724 |
import requests
def tplink_post(url: str):
""" Issue a POST to the device. The Content-Type header seems to be required by some devices."""
_response = requests.post(url, timeout=5, headers={"Content-Type":"application/x-www-form-urlencoded",})
_response.raise_for_status()
return _response | 91f8e882d411d0bde2b44680789a0e10d79a25e0 | 583,730 |
def calculate_m_metric(flux_a: float, flux_b: float) -> float:
"""Calculate the m variability metric which is the modulation index between two fluxes.
This is proportional to the fractional variability.
See Section 5 of Mooley et al. (2016) for details, DOI: 10.3847/0004-637X/818/2/105.
Args:
f... | 8b2c9b54fb8b3bdce9064d0978e85cf4b93636e7 | 583,732 |
def registery_key_stix_pattern_producer(data):
"""Convert a Registry Key from TC to a STIX pattern."""
key_name, value_name, value_type = data.get('summary').split(':')
parts = []
if key_name.strip():
key_name = key_name.strip().replace('\\', '/')
parts.append(f"windows-registry-key:ke... | e9b159779843f59c4a3e78dafd8d1e7fb1f39bfb | 583,735 |
import itertools
def flatten_dict(**kwargs):
""" Flatten a dict of lists into a list of dicts
For example
flatten_dict(lr=[1, 2], a=[10,3], b=dict(c=[2, 4], d=np.arange(1, 3)))
>>>
[{'lr': 1, 'a': 10, 'b': {'c': 2, 'd': 1}},
{'lr': 2, 'a': 3, 'b': {'c': 4, 'd': 2}}]
"""
ks, vs = [], []... | 4a42dcf4fcceb74382541ec8e9412fa0e87635ff | 583,737 |
from typing import OrderedDict
def get_unfinished_runs(suite_data):
"""
Selects only those items from "suite_data" that
are not finished yet, so we can wait for their
results
"""
suite_data_unfinished = OrderedDict()
for run_id, test_data in suite_data.items():
if not test_data["f... | 49ed8dce5acc01b238d98903f4ed2bfb8f8af76a | 583,741 |
def parse_link_body(link_body):
"""
Given the body of a link, parse it to determine what package and topic ID
the link will navigate to as well as what the visual link text should be.
This always returns a 3-tuple, though the value of the link text will be
None if the parse failed. It's possible fo... | 6e05e54e4b43513e5503f0553fb80702791cfaac | 583,743 |
def smoothbknpo(x, p):
"""
Smooth broken power law function.
Parameters
----------
x: numpy.ndarray
non-zero frequencies
p: iterable
p[0] = normalization frequency
p[1] = power law index for f --> zero
p[2] = power law index for f --> infinity
p[3] = br... | 39d85e6cd6090a7bd5450fe467eb051e860f1c24 | 583,744 |
def convert_time(time):
"""
This function converts time in a form of integers to a hh:mm:ss format
Returns an array | Ex: 01:32:34
"""
time_list = [60*60,60,1]
output_list = []
for i in time_list:
amount, remainder = divmod(time, i)
if len(str(amount)) < 2:
outpu... | bacf23399996d9592c6fe7af0a6aedb4cdb474e9 | 583,753 |
def drop_axes(array, input_axes, output_axes):
"""
Drops the dimensions in input_axes that are not in output_axes.
Takes the first slice (index 0) of the dropped axes.
Arguments:
array (ndarray): array to drop
input_axes (string): dimension order
output_axes (string): dimension ... | c9e68c887c65680abb2917652a0f88797007e464 | 583,757 |
def from_sieve(l: list) -> list:
""" Takes a sieve, a sequence of boolean elements whose index is some type of number -- e.g. a prime number -- if it is set to 'True', and returns that list of numbers. """
p=list()
for i, val in enumerate(l):
if val: p.append(i)
return p | 35a862907d8607d4085062c9de57a0803b4d8fd4 | 583,761 |
def mkdir(resource, bucket_name, dir_name):
"""Create directory inside bucket"""
client = resource.meta.client
if not dir_name.endswith("/"):
dir_name = f"{dir_name}/"
response = client.put_object(Bucket=bucket_name, Body="", Key=dir_name)
return response | 12b8352b81ed5161dd80b14db19b9aeb5bd2f132 | 583,762 |
def index(i,j,N):
"""
Returns the location of {i,j} in the set {{0,1},...,{N-2,N-1}}.
"""
x=[i,j,N]
x.sort()
i, j, N = x[0], x[1], x[2]
return int(i * (N - 2) - (i * (i - 1)) / 2 - 1 + j) | ed98317a8261550b17233f4737f56f091b5cce01 | 583,764 |
def n_o(c_s, n_v):
"""
Number of outer samples given N_I = 3 as recommended by SNS16.
Parameters
----------
c_s : int
Total number of model evaluations.
n_v : int
Number of samples desired for computing total output variance.
Returns
-------
n_o : float
Num... | 26f557860169654bdde33d087616cc30b43aa994 | 583,766 |
from typing import Optional
def float_or_none(val) -> Optional[float]:
"""Convert to float, or leave as None."""
if val is None:
return val
else:
return float(val) | e419fcb5eaf3cf2bb78f6fa331427c30ef02e987 | 583,768 |
def to_youtrack_subsystem(trac_component, yt_bundle):
"""
Converts trac component to YT subsystem.
Args:
trac_component: Trac component to convert.
yt_bundle: YT field bundle to create component in.
Returns:
YT field, that has same name, owner and description, as trac component... | 141259849354a77d006982c993959df561e5dbc1 | 583,770 |
def scale_point(point1, scale):
"""
Scale a point by the given scale
"""
return (int(round(point1[0] * scale)), int(round(point1[1] * scale))) | dbd2681dbbb445a4914dbfc0b42e9fa180c72e85 | 583,771 |
import warnings
def warning_record_to_str(warning_message):
"""Convert a warnings.WarningMessage to a string."""
warn_msg = warning_message.message
msg = warnings.formatwarning(
warn_msg,
warning_message.category,
warning_message.filename,
warning_message.lineno,
wa... | 3d14186125e7b3dd089f4307aabe990f383336a8 | 583,773 |
def const(v):
"""Create a function that always returns a specific value.
* v -- The value the returned function always returns
"""
def f(a):
return v
return f | e24876b3842c94c6431dc2afdbd1ea48246bcd57 | 583,781 |
import torch
def unnormalize(normalized_imgs, mean, std):
"""Unnormalize image for visualization.
Args:
normalized_imgs (torch.tensor): image with shape (b, 3, h, w)
mean (list of floats): list of ImageNet means for 3-channel RGB images
std (list of floats): list of ImageNet stand... | 2a82b0046645341565374abf4823b10c4217333d | 583,782 |
def parse_date_created(dct):
"""Helper function to parse date-created from profile."""
date = dct['date-created']
if date:
return (int(date['@year']), int(date['@month']), int(date['@day']))
else:
return (None, None, None) | 342861d8cdcb1b8fdf24e7993387e51c2a1d0bdb | 583,783 |
def get_invalid_multi_records_sqs_message() -> dict:
"""
Simulates SQS returning a message with
multiple Record entries
"""
data = {
"Records": [
{
"messageId": "2e1424d4-f796-459a-8184-9c92662be6da",
"receiptHandle": "AQEBzWwaftRI0KuVm4tP+/7q1rGgN... | 9bb9caecf6de0449ce0de6c71b380931a938a3e4 | 583,785 |
def action_emoji(status):
"""
Get an emoji based on the workflow status.
"""
if status == 'success':
return ':heavy_check_mark:'
elif status == 'failure':
return ':x:'
else:
return ':large_orange_diamond:' | 986386d915d879f2d22b3a3b0c0ee472b4d05fa6 | 583,788 |
def create_pdf(db_cursor, file_uri) -> int:
"""Assuming PDF does not already exist in database,
create a new PDF instance in database
Parameters:
db_cursor : the cursor pointing to the database
file_uri (str) : the URI assumed to point to the PDF file
Returns:
int: the ID of the created PD... | 9e45fb11b83b6e4b3468fa3154d49d8aa5faec14 | 583,790 |
def locate_constraints_of_type(constraints, constraint_type):
""" Locates all constraints of a given type out of a list
:param constraints: The constraints to filter
:type constraints: iterable of\
:py:class:`pacman.model.constraints.AbstractConstraint.AbstractConstraint`
:param constra... | af64f4edc53690c15e2e539d09a4bcd759be4037 | 583,791 |
from typing import Sequence
from typing import Callable
from typing import Any
from functools import reduce
def compose(functions: Sequence[Callable]) -> Callable:
"""
Compose a sequence of functions
:param functions: sequence of functions
:return: combined functions, e.g. [f(x), g(x)] -> g(f(x))
... | 9b3bcda936c55f53b9891fd1b522742c76a87097 | 583,795 |
def rain_sum(p, prev):
""" Compute amount (sum) of consecutive rainfall
Parameters
----------
p : array
rainfall amount in open over previous 24 hours [mm].
prev : array
Previous sum of consecutive rain.
prev_start = 0.0
Returns
-------
array
sum of consecutive rainfall [mm]
"""
if... | 488647a7b752f52fea3acfd2e12ef9f0ac35219e | 583,796 |
from pathlib import Path
import configparser
def get_config_value(section, key, path_to_config_file=None):
"""Returns the value corresponding to the key-value pair in the configuration file (configparser format)
By defaults, it is assumed that the configuration file is saved on google drive. If not, pass a p... | e248a33160d92b0d891ec8dec698f7ad63f29061 | 583,798 |
import re
def items(s, func=str):
"""Returns items processed by func in a comma or space delimited string."""
return [func(x) for x in re.split(r"\s*,\s*|\s+", s)] | 71a1d046fabb5dfe2c60b7a5e734b13a71343a73 | 583,799 |
def data_loader(e_file, f_file, args):
"""Load the source and target text file into a list with and also
extract lists of unique tokens.
Args:
e_file (str): path to source (eng) file
f_file (str): path to target (foreign) file
Returns:
tuple: comprising of a list of sentence pa... | 2ebb8a9f172cf962876efc034fe3c071bd9acd4a | 583,800 |
def get_underlined_header(header: str, char: str = '-') -> str:
"""Underline the header with given char."""
underline = char * len(header)
return '\n'.join([header, underline]) | 4c4c915a82a9938c14df0d36fd78cd8d03759251 | 583,806 |
def _null_to_None(data):
"""
Converts *Javascript* originated *null* and *undefined* strings
to `None`. Non-matching data will be passed untouched.
Parameters
----------
data : unicode
Data to convert.
Returns
-------
None or unicode
Converted data.
"""
if ... | 79a88409b4165d0c2ae9ad9c2173021edde5a33e | 583,812 |
def _vec(A):
"""
Linear operator _vec() from Wiktorsson2001 p478
Args:
A: a rank 3 array of shape N x m x n, giving a matrix A[j] for each
interval of time j in 0..N-1
Returns:
array of shape N x mn x 1, made by stacking the columns of matrix A[j] on
top of each other, for each j... | 6388d6315e56bb6b55c96d974c84431baa65ee23 | 583,813 |
def get_upgrade_response(connection):
"""
This function reads from the socket until the HTTP/1.1 end-of-headers
sequence (CRLFCRLF) is received. It then checks what the status code of the
response is.
This is not a substitute for proper HTTP/1.1 parsing, but it's good enough
for example purpose... | 32ea4e67a6ae76128083a2c7df1f3fd3a794923b | 583,814 |
def hierarchy_section_header(reversed_heading_tree):
"""
View helper function to extract the Section Numeral and title for the hierarchy context of the heading
and returned as formatted html string
:param reversed_heading_tree:
:return: html
"""
section_index = len(reversed_heading_tree) - 1... | 9827f3afc5c018f58c767e0759c9551c15290e9a | 583,817 |
def get_coursename() -> str:
""" Acquire course name """
course_name = input("Course name: ")
return course_name | fa1534135b7decf3413049a5e6d95d71cc79fc75 | 583,818 |
def validate_graph(graph):
"""
Takes a graph in the form of a dictionary and verifies that for every edge member there exists a source node.
If no source node is found from existing edge members, one is created with an empty edge [].
:param graph:
:return:
"""
vertices = [vertex for edge in ... | 5fdac34a01570c034ec4155f79fb56f850d26257 | 583,822 |
def transform_strings_to_lists(pd_series):
"""
Turns values from pd_series from |-delimited strings to lists
:param pd_series:
:return list of lists:
"""
values_as_strings = pd_series.dropna().values.astype(str)
values_as_lists = [item.split('|') for item in values_as_strings]
return val... | 474c8be71ce6aca1aa91f476edfd1037a8033fed | 583,827 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.