content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def lambda_handler(event, context):
"""
Generate a pre-signed URL that allows a save file to be uploaded to S3 in the player's specified save slot. If the
slot is new, will verify that MAX_SAVE_SLOTS_PER_PLAYER has not been reached.
Parameters:
Request Context:
custom:gk_user_id: str
... | 5,336,400 |
def getLanguageLevel() -> dict:
"""
Takes the user input and returns the found documents as dictionary.
:text: String
:language: String
:return: Dictionary
"""
text: str = request.params.get('text')
language: str = request.params.get('language')
# check API Key
if str(request.pa... | 5,336,401 |
def list_networks(**kwargs):
"""Lists all networks of the given compartment
Args:
**kwargs: Additional options
Keyword Args:
public_subnet (bool): Whether only public or private subnets should be
considered
compartment_id (str): OCID of the parent compartment.... | 5,336,402 |
def ed_affine_to_extended(pt):
"""Map (x, y) to (x : y : x*y : 1)."""
new_curve = EllipticCurve(pt.curve, ED_EXT_HOM_PROJ, Edwards_ExtProj_Arithm)
return new_curve((pt.x, pt.y, pt.x * pt.y, new_curve.field(1))) | 5,336,403 |
def _download(path, url, archive_name, hash_, hash_type='md5'):
"""Download and extract an archive, completing the filename."""
full_name = op.join(path, archive_name)
remove_archive = True
fetch_archive = True
if op.exists(full_name):
logger.info('Archive exists (%s), checking hash %s.'
... | 5,336,404 |
def do_setup(experiment_folder, path_to_additional_args):
""" Setup Shell Scripts for Experiment """
additional_args = joblib.load(path_to_additional_args)
# Setup Data
logger.info("Setting Up Data")
data_args = setup_train_test_data(experiment_folder, **additional_args)
# Setup
logger.inf... | 5,336,405 |
def getorgadmins(apikey, orgid, suppressprint=False):
"""
Args:
apikey: User's Meraki API Key
orgid: OrganizationId for operation to be performed against
suppressprint:
Returns:
"""
__hasorgaccess(apikey, orgid)
calltype = 'Organization'
geturl = '{0}/organizations/{... | 5,336,406 |
def calc_recall(TP, FN):
"""
Calculate recall from TP and FN
"""
if TP + FN != 0:
recall = TP / (TP + FN)
else:
recall = 0
return recall | 5,336,407 |
def lookup_last_report_execution(job_type, work_ids=None):
"""Lookup in the database when the report/job chunk last executed
This is the expected table schema from the database (id and timestamp columns
are omitted),
---------------------------------------------------
| work_id | history ... | 5,336,408 |
def get_course_goal_options():
"""
Returns the valid options for goal keys, mapped to their translated
strings, as defined by theCourseGoal model.
"""
return {goal_key: goal_text for goal_key, goal_text in GOAL_KEY_CHOICES} | 5,336,409 |
def to_dataframe(y):
"""
If the input is not a dataframe, convert it to a dataframe
:param y: The target variable
:return: A dataframe
"""
if not isinstance(y, pd.DataFrame):
return pd.DataFrame(y)
return y | 5,336,410 |
def url_equal(first, second, ignore_scheme=False, ignore_netloc=False, ignore_path=False, ignore_params=False,
ignore_query=False, ignore_fragment=False):
"""
Compare two URLs and return True if they are equal, some parts of the URLs can be ignored
:param first: URL
:param second: URL
... | 5,336,411 |
def yggdrasil_model_to_keras_model(
src_path: str,
dst_path: str,
input_model_signature_fn: Optional[tf_core.InputModelSignatureFn] = tf_core
.build_default_input_model_signature):
"""Converts an Yggdrasil model into a Keras model.
Args:
src_path: Path to input Yggdrasil Decision Forests model.... | 5,336,412 |
def test_struct(n: cython.int, x: cython.double) -> MyStruct2:
"""
>>> test_struct(389, 1.64493)
(389, 1.64493)
>>> d = test_struct.__annotations__
>>> sorted(d)
['n', 'return', 'x']
"""
assert cython.typeof(n) == 'int', cython.typeof(n)
if is_compiled:
assert cython.typeof(x... | 5,336,413 |
def build_document(json_schema: dict) -> list:
"""
Returns a list of lines to generate a basic adoc file, with the format:
Title
A table for the data properties
A table for the data attributes and nested attributes if any
"""
lines = []
"""
Title and description of schema
""... | 5,336,414 |
def test_streaming_histogram_1d(dtype, error):
"""Test the computation of streaming histogram for a 1D array."""
values = np.random.random_sample((10000, )).astype(dtype)
hist = StreamingHistogram(values, dtype=dtype, bin_count=values.size)
check_stats(hist, values, dtype, error)
assert np.all(hist... | 5,336,415 |
def remove_potential_nonlipids_bad_esi_mode():
"""
remove_potential_nonlipids_bad_esi_mode
description:
ESI mode of the dataset is not 'pos' or 'neg'
returns:
(bool) -- test pass (True) or fail (False)
"""
dset = Dataset(os.path.join(os.path.dirname(__file__), 'real_data_1.csv'))
try... | 5,336,416 |
def test_no_args_workspace_configured_with_some_groups(tmp_path: Path) -> None:
"""Scenario:
* Nothing passed on the command line
* A group named 'group1' in the manifest containing foo
* A group named 'group2' in the manifest containing bar
* Workspace configured with repo_groups=[group1]
Shou... | 5,336,417 |
def is_oasis_db():
""" Is this likely an OASIS database? Look at the table names to see
if we have the more specific ones.
Return "yes", "no", or "empty"
"""
expect = ['qtvariations', 'users', 'examqtemplates', 'marklog', 'qtattach',
'questions', 'guesses', 'exams', 'qtemplate... | 5,336,418 |
def selection_screen(screen: pygame.Surface) -> None:
"""
Selection screen between SEARCHING, SORTING, TITLE
"""
clear_screen(screen)
border(screen)
# Labels
draw_header(screen, "Table of Content")
b1 = PButton(screen, (180, 230, 300, 50))
b1.add_text("Sorting")
b2 = ... | 5,336,419 |
def make_segment(segment, discontinuity=False):
"""Create a playlist response for a segment."""
response = []
if discontinuity:
response.append("#EXT-X-DISCONTINUITY")
response.extend(["#EXTINF:10.0000,", f"./segment/{segment}.m4s"]),
return "\n".join(response) | 5,336,420 |
def seq_aggregate_with_reducer(x, y):
"""
Sequencing function that works with the dataframe created by get_normal_frame
:param x:
:param y:
:return:
"""
res = []
for i in range(0, len(x)):
res.append((x[i][0], x[i][1], get_aggregation_func_by_name(x[i][0])(x[i][2], y[i][2])))
... | 5,336,421 |
def console(bot: Optional[Union[T_Base, T_Group]]=None, **kwargs) -> None:
"""
Function for direct interaction via terminal.
Useful for testing, not advised for production code
Params:
-bot = Instance of the bot/botgroup you wish to control via console.
-kwargs = dict of global variables define... | 5,336,422 |
def from_dicts(key: str, *dicts, default: Any = None):
"""
Returns value of key in first matchning dict.
If not matching dict, default value is returned.
Return:
Any
"""
for d in dicts:
if key in d:
return d[key]
return default | 5,336,423 |
def comp_play_hand(hand, word_list):
"""
Allows the computer to play the given hand, as follows:
* The hand is displayed.
* The computer chooses a word using comp_choose_words(hand, word_dict).
* After every valid word: the score for that word is displayed,
the remaining letters in th... | 5,336,424 |
def test_clear_objects():
"""
Checks the clear_objects method
"""
obj_storage = (
object_storage.ObjectStorage()
) # obj_storage is a wrapper object to a collection of objects
x = torch.tensor(1)
obj_storage.set_obj(x)
objs = obj_storage.current_objects() # Returns a copy of... | 5,336,425 |
def test_update_patient(mock_app, test_client, gpx4_patients, test_node, database):
"""Test updating a patient by sending a POST request to the add endpoint with valid data"""
patient_data = gpx4_patients[1]
# Given a node with authorized token
ok_token = test_client["auth_token"]
add_node(mongo_... | 5,336,426 |
def setIndexingRules(fixed_allocations, indexer_id,blacklist_parameter = True, parallel_allocations = 0 , network = "mainnet"):
"""
setIndexingRule via indexer agent management endpoint (default :18000).
Endpoint works with graphQL mutation. So the mutations are sent via a request.post
method.
retu... | 5,336,427 |
def make_obj(f, mesh):
"""Crude export to Wavefront mesh format"""
for v in mesh.verts:
f.write("v {} {} {}\n".format(v.x, v.y, v.z))
for face in mesh.faces:
if isinstance(face, Quad):
f.write("f {} {} {} {}\n".format(face.v1, face.v2, face.v3, face.v4))
if isinstance(fac... | 5,336,428 |
def temporary_dir(chdir=True):
"""Context manager that creates a temporary directory and chdirs to it.
When the context manager exits it returns to the previous cwd
and deletes the temporary directory.
"""
d = tempfile.mkdtemp()
try:
with contextlib.ExitStack() as stack:
if ... | 5,336,429 |
def time_in_words(h, m):
"""Hackerrank Problem: https://www.hackerrank.com/challenges/the-time-in-words/problem
Given the time in numerals we may convert it into words, as shown below:
----------------------------------------------
| 5:00 | -> | five o' clock |
| 5:01 | -> | one m... | 5,336,430 |
def swap_values_at(first_position, second_position, list):
"""
Swaps two values in-place in a list of lists.
:param first_position: A two-tuple of integers - the index of the
first value.
:param second_position: A two-tuple of integers - the index of the
second value.
:param list: A list of... | 5,336,431 |
def majorityElement(nums):
"""超过三分之一的数,最多不超过两个数"""
num1, num2 = -1, -1
count1, count2 = 0, 0
for i in range(len(nums)):
curNum = nums[i]
if curNum == num1:
count1 += 1
elif curNum == num2:
count2 += 1
elif count1 == 0:
num1 = curNum
... | 5,336,432 |
def calcDensHeight(T,p,z):
"""
Calculate the density scale height H_rho
Parameters
----------
T: vector (float)
temperature (K)
p: vector (float) of len(T)
pressure (pa)
z: vector (float) of len(T
height (m)
Returns
-------
Hb... | 5,336,433 |
def test_app_initialisation():
"""
.. test:: Additional test 1
:id: TC_LE_GROUNDWORK_0_1_12_0404
This test case checks
- if a groundwork app can be instantiated
- if the app path is set to the current working directory (APP_PATH is unset because no configuration is given)
""... | 5,336,434 |
def resetDb(db_name):
""" Create or cleanup a user DB"""
if db_name in bw.databases:
_eprint("Db %s was here. Reseting it" % db_name)
del bw.databases[db_name]
db = bw.Database(db_name)
db.write(dict()) | 5,336,435 |
def Signal_figure(name,I,mask):
"""Plots a figure designed to show the influences of the image parameters and creates a .png image of it.
Parameters
----------
name: string
Desired name of the image.
I: array
MRI image.
mask: array
Region of interest binary m... | 5,336,436 |
async def test_zeroconf_parse_error(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test we abort zeroconf flow on IPP parse error."""
mock_connection(aioclient_mock, parse_error=True)
discovery_info = MOCK_ZEROCONF_IPP_SERVICE_INFO.copy()
result = await hass.config_entries.... | 5,336,437 |
def load_many_data(filenames, clean=True, first_seconds_remove=2, bandpass_range=(5, 50)):
"""
Loads several files and cleans data if clean is True. Returns a concatenated set of data (MNE object).
"""
# TODO: check for matching channels and other errors
raw_data = []
if filenames is None:
... | 5,336,438 |
def extract_push_target(push_target: str):
"""
Extract push target from the url configured
Workspace is optional
"""
if not push_target:
raise ValueError("Cannot extract push-target if push-target is not set.")
match_pattern = re.compile(
r"(?P<http_scheme>https|http):\/\/(?P<ask... | 5,336,439 |
def main(global_config, **settings):
"""This function returns a Pyramid WSGI application."""
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
Base.metadata.bind = engine
authn_policy = AuthTktAuthenticationPolicy('sosecret', callback=groupfinder,
... | 5,336,440 |
def dish_gain(radius, freq):
"""
Dish radar gain.
Inputs:
- radius [float]: Dish radius (m)
- freq [float]: Transmit frequency (Hz)
Outputs:
- g: Gain
"""
return 4*pi**2*radius**2/wavelen(freq)**2 | 5,336,441 |
def test_advection_1d_constructor():
"""
Test constructor
"""
x_start = 0
x_end = 1
nx = 11
c = 1
advection_1d = Advection1D(c=c, x_start=x_start, x_end=x_end, nx=nx, t_start=0, t_stop=1, nt=11)
np.testing.assert_equal(advection_1d.x_start, x_start)
np.testing.assert_equal(advec... | 5,336,442 |
def _collect_files(gold_dir, system_dir, limit):
"""Return the list of files to run the comparison on."""
gold_files = os.listdir(gold_dir)
system_files = os.listdir(system_dir)
# don't assume the directory content is the same, take the intersection
fnames = sorted(list(set(gold_files).intersection(... | 5,336,443 |
def center_img(img, size=None, fill_value=255):
"""
center img in a square background
"""
h, w = img.shape[:2]
if size is None:
size = max(h, w)
shape = (size, size) + img.shape[2:]
background = np.full(shape, fill_value, np.uint8)
center_x = (size - w) // 2
center_y = (size ... | 5,336,444 |
def concat_files(*files):
"""
Concat some files together. Returns out and err to keep parity with shell commands.
Args:
*files: src1, src2, ..., srcN, dst.
Returns:
out: string
err: string
"""
out = ''
err = ''
dst_name = files[-1]
sources = [files[f] for f ... | 5,336,445 |
def distribution_quality( df, refdata, values, ascending, names, fig):
"""Locate the quantile position of each putative :class:`.DesingSerie`
in a list of score distributions.
:param df: Data container.
:type df: :class:`~pandas.DataFrame`
:param grid: Shape of the grid to plot the values in the f... | 5,336,446 |
def join_paths(path, *paths):
"""
"""
return os.path.join(path, *paths) | 5,336,447 |
def determine_configure_options(module):
"""
Determine configure arguments for this system.
Automatically determine configure options for this system and build
options when the explicit configure options are not specified.
"""
options = module.params['configure_options']
build_userspace = m... | 5,336,448 |
def __test_maxwellian_solution__(collision_operator, solver):
"""
tests if df/dt = 0 if f = maxwellian
:return:
"""
f, f_out, v, dv = __run_collision_operator_test_loop__(
vshift=0.0, t_end=T_END, collision_operator=collision_operator, solver=solver
)
np.testing.assert_almost_equa... | 5,336,449 |
def test_transform_coverage_to_coordinates(coverage, snapshot):
"""
Test that two sample coverage data sets are correctly converted to coordinates.
"""
assert transform_coverage_to_coordinates(coverage) == snapshot | 5,336,450 |
def getElementTypeToolTip(t):
"""Wrapper to prevent loading qtgui when this module is imported"""
if t == PoolControllerView.ControllerModule:
return "Controller module"
elif t == PoolControllerView.ControllerClass:
return "Controller class" | 5,336,451 |
def parse_dates(array):
"""Parse the valid dates in an array of strings.
"""
parsed_dates = []
for elem in array:
elem = parse_date(elem)
if elem is not None:
parsed_dates.append(elem)
return parsed_dates | 5,336,452 |
def export_secret_to_environment(name):
"""
Add secret to envvar.
:param name: The secret key.
:return:
"""
logger.info('Adding envvar: {0}.'.format(name))
try:
value = base64.b64decode(os.environ[name])
except KeyError:
raise EcosystemTestException(
'Secret e... | 5,336,453 |
def app_factory(global_config, **local_config):
"""
定义一个 app 的 factory 方法,以便在运行时绑定具体的 app,而不是在配置文件中就绑定。
:param global_config:
:param local_config:
:return:
"""
return MyApp() | 5,336,454 |
def str_to_datetime(dt_str):
""" Converts a string to a UTC datetime object.
@rtype: datetime
"""
try:
return dt.datetime.strptime(
dt_str, DATE_STR_FORMAT).replace(tzinfo=pytz.utc)
except ValueError: # If dt_str did not match our format
return None | 5,336,455 |
def quantize(img):
"""Quantize the output of model.
:param img: the input image
:type img: ndarray
:return: the image after quantize
:rtype: ndarray
"""
pixel_range = 255
return img.mul(pixel_range).clamp(0, 255).round().div(pixel_range) | 5,336,456 |
def detect_os(ctx, loc="local", verbose=0):
"""
detect what type of os we are using
Usage: inv db.detect-os
"""
env = get_compose_env(ctx, loc=loc)
# Override run commands' env variables one key at a time
for k, v in env.items():
ctx.config["run"]["env"][k] = v
res_os = ctx.run... | 5,336,457 |
def test_confusion_matrix_per_subgroup_indexed():
"""
Tests calculating confusion matrix per index-based sub-population.
Tests
:func:`fatf.utils.metrics.tools.confusion_matrix_per_subgroup_indexed`
function.
"""
incorrect_shape_error_gt = ('The ground_truth parameter should be a '
... | 5,336,458 |
def is_normalized(M, x, eps):
"""Return True if (a Fuchsian) matrix M is normalized, that
is all the eigenvalues of it's residues in x lie in [-1/2, 1/2)
range (in limit eps->0). Return False otherwise.
Examples:
>>> x, e = var("x epsilon")
>>> is_normalized(matrix([[(1+e)/3/x, 0], [0, e/x]]), ... | 5,336,459 |
def _get_dashboard_link(course_key):
""" Construct a URL to the external analytics dashboard """
analytics_dashboard_url = f'{settings.ANALYTICS_DASHBOARD_URL}/courses/{str(course_key)}'
link = HTML("<a href=\"{0}\" rel=\"noopener\" target=\"_blank\">{1}</a>").format(
analytics_dashboard_url, settin... | 5,336,460 |
def show_datas(x_train, y_train, x_test, y_test):
"""Show shapes, values, and images."""
# Show shapes.
print('x_train', x_train.shape)
print('y_train', y_train.shape)
print('x_test', x_test.shape)
print('y_test', y_test.shape)
# Show a data value.
#print(x_train[0])
#print(y_train... | 5,336,461 |
def figure1_control(data1, cols):
""" Creates a data set to plot figure 1, Panel B, D, F.
Args:
- data1 (pd.DataFrame): the original data set
- cols (list): a list of column names ["agus", "bct", "bcg"]
Returns:
- df_fig1_contr (pd.DataFrame): a data set for plotting panels with co... | 5,336,462 |
async def async_setup_entry(
hass: HomeAssistant,
entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up the IPX800 lights."""
controller = hass.data[DOMAIN][entry.entry_id][CONTROLLER]
coordinator = hass.data[DOMAIN][entry.entry_id][COORDINATOR]
devices = hass.dat... | 5,336,463 |
def GetEffectiveRightsFromAclW(acl, sid):
"""
Takes a SID instead of a trustee!
"""
_GetEffectiveRightsFromAclW = windll.advapi32.GetEffectiveRightsFromAclW
_GetEffectiveRightsFromAclW.argtypes = [PVOID, PTRUSTEE_W, PDWORD] #[HANDLE, SE_OBJECT_TYPE, DWORD, PSID, PSID, PACL, PACL, PSECURITY_DESCRIPTOR]
_GetEffecti... | 5,336,464 |
def store(mnemonic, opcode):
""" Create a store instruction """
ra = Operand("ra", Or1kRegister, read=True)
rb = Operand("rb", Or1kRegister, read=True)
imm = Operand("imm", int)
syntax = Syntax(["l", ".", mnemonic, " ", imm, "(", ra, ")", ",", " ", rb])
patterns = {"opcode": opcode, "ra": ra, "r... | 5,336,465 |
def hlmlDeviceGetPowerUsage(device: hlml_t.HLML_DEVICE.TYPE) -> int:
""" Retrieves power usage for the device in mW
Parameters:
device (HLML_DEVICE.TYPE) - The handle for a habana device.
Returns:
power (int) - The given device's power usage in mW.
"""
global _hlmlOBJ... | 5,336,466 |
def usgs_coef_parse(**kwargs):
"""
Combine, parse, and format the provided dataframes
:param kwargs: potential arguments include:
dataframe_list: list of dataframes to concat and format
args: dictionary, used to run flowbyactivity.py ('year' and 'source')
:return: d... | 5,336,467 |
def repeat_move_randomly(n, circle, window):
"""
Runs move_randomly n times using the given circle and window,
each time making 1000 random moves with 0 seconds pause after each.
Waits for a mouse click after each of the n trials.
Preconditions:
:type n: int
:type circle: rg.Circle
... | 5,336,468 |
def success_poly_overlap(gt_poly, res_poly, n_frame):
"""
:param gt_poly: [Nx8]
:param result_bb:
:param n_frame:
:return:
"""
thresholds_overlap = np.arange(0, 1.05, 0.05)
success = np.zeros(len(thresholds_overlap))
iou_list = []
for i in range(gt_poly.shape[0]):
iou ... | 5,336,469 |
def my_get_size_png(gg, height, width, dpi, limitsize):
"""
Get actual size of ggplot image saved (with bbox_inches="tight")
"""
buf = io.BytesIO()
gg.save(buf, format= "png", height = height, width = width,
dpi=dpi, units = "in", limitsize = limitsize,verbose=False,
bbox_inc... | 5,336,470 |
def main() -> None:
"""Main function for model inference."""
args = parse_args()
assert args.format_only or args.show or args.show_dir, (
"Please specify at least one operation (save/eval/format/show the "
"results / save the results) with the argument '--format-only', "
"'--show' o... | 5,336,471 |
def dispatch(bot, update: Update):
"""
Takes a Telegram Update delegates to the correct
function to handle that update.
Keyword Arguments:
bot -- The overall BuzzardBot instance
update -- The raw Telegram Update
"""
print(update)
message = Message(bot, update)
text = message.te... | 5,336,472 |
def main():
"""main"""
args = sys.argv
if len(args) == 1:
arg1 = os.path.basename(args[0])
print('Usage: {} FILE'.format(arg1))
sys.exit(1)
infile = sys.argv[1]
if not os.path.isfile(infile):
print('{} is not a file'.format(infile))
sys.exit(1)
for i,l... | 5,336,473 |
def getRnnGenerator(vocab_size,hidden_dim,input_dim=512):
"""
"Apply" the RNN to the input x
For initializing the network, the vocab size needs to be known
Default of the hidden layer is set tot 512 like Karpathy
"""
generator = SequenceGenerator(
Readout(readout_dim = vocab_size,
... | 5,336,474 |
def first_true(iterable, default=False, pred=None):
"""Returns the first true value in the iterable.
If no true value is found, returns *default*
If *pred* is not None, returns the first item
for which pred(item) is true.
"""
# first_true([a,b,c], x) --> a or b or c or x
# first_true([a,b... | 5,336,475 |
def display_results(final=True):
"""
Display the results using a colored barplot and event location plot
"""
if final:
st.pyplot(
barplot_colored(st.session_state.thresh_fvs, st.session_state.results)
)
st.pyplot(mk_event_location_plot(st.session_state.results))
... | 5,336,476 |
def parseFileRefs(htmlfile, usedFiles, skipFiles, indent, trace=print):
"""
find files referenced in root, recur for html files
"""
trace('%sParsing:' % ('.' * indent), htmlfile)
parser = MyParser(usedFiles, skipFiles, indent)
text = open(htmlfile).read()
try:
parser.feed(text)
... | 5,336,477 |
def get_length(filename):
"""
Get the length of a specific file with ffrobe from the ffmpeg library
:param filename: this param is used for the file
:type filename: str
:return: length of the given video file
:rtype: float
"""
# use ffprobe because it is faster then other (for example mo... | 5,336,478 |
def get_loan_by_id(link):
"""performs a GET request to the /api/loans/:{insert loanId here} endpoint """
get = requests.get(link)
print(get.text) | 5,336,479 |
def is_File(path):
"""Takes the path of the folder as argument
Returns is the path is a of a Folder or not in bool"""
if os.path.isfile(path):
return True
else:
return False | 5,336,480 |
def get_device_serial_no(instanceId, gwMgmtIp, fwApiKey):
"""
Retrieve the serial number from the FW.
@param gwMgmtIP: The IP address of the FW
@type: ```str```
@param fwApiKey: Api key of the FW
@type: ```str```
@return The serial number of the FW
@rtype: ```str```
"""
serial... | 5,336,481 |
def dump_dict(dct, outpath='./dict.txt'):
""" Dump dict into file. """
with open(Path(outpath), 'w') as file:
for k in sorted(dct.keys()):
file.write('{}: {}\n'.format(k, dct[k])) | 5,336,482 |
def multilabel_cross_entropy(
x: Tensor,
target: Tensor,
weight: Optional[Tensor] = None,
ignore_index: int = -100,
reduction: str = 'mean'
) -> Tensor:
"""Implements the cross entropy loss for multi-label targets
Args:
x (torch.Tensor[N, K, ...]): input tensor
target (torch... | 5,336,483 |
def dataset_string(dataset):
"""Generate string from dataset"""
data = dataset_data(dataset)
try:
# single value
return fn.VALUE_FORMAT % data
except TypeError:
# array
if dataset.size > 1:
return fn.data_string(data)
# probably a string
return fn.shor... | 5,336,484 |
def create_constant_value_validator(
constant_cls: Type, is_required: bool
) -> Callable[[str], bool]:
"""
Create a validator func that validates a value is one of the valid values.
Parameters
----------
constant_cls: Type
The constant class that contains the valid values.
is_requir... | 5,336,485 |
def process_arguments(arguments):
"""
Process command line arguments to execute VM actions.
Called from cm4.command.command
:param arguments:
"""
result = None
if arguments.get("--debug"):
pp = pprint.PrettyPrinter(indent=4)
print("vm processing arguments")
pp.pprint... | 5,336,486 |
def forward_resolve(state):
"""Mark the target of a forward branch"""
target_label = state.data_stack.pop()
label(target_label) | 5,336,487 |
def deliver_hybrid():
"""
Endpoint for submissions intended for dap and legacy systems. POST request requires the submission JSON to be
uploaded as "submission", the zipped transformed artifact as "transformed", and the filename passed in the
query parameters.
"""
logger.info('Processing Hybrid ... | 5,336,488 |
def clear_screen():
"""Clear the screen"""
os.system("cls" if os.name == "nt" else "clear") | 5,336,489 |
def change_path(path, dir="", file="", pre="", post="", ext=""):
"""
Change the path ingredients with the provided directory, filename
prefix, postfix, and extension
:param path:
:param dir: new directory
:param file: filename to replace the filename full_path
:param pre: pref... | 5,336,490 |
def test_entities_false():
"""Test entity ID policy."""
policy = False
with pytest.raises(vol.Invalid):
ENTITY_POLICY_SCHEMA(policy) | 5,336,491 |
def midi_to_chroma(pitch):
"""Given a midi pitch (e.g. 60 == C), returns its corresponding
chroma class value. A == 0, A# == 1, ..., G# == 11 """
return ((pitch % 12) + 3) % 12 | 5,336,492 |
def _snippet_items(snippet):
"""Return all markdown items in the snippet text.
For this we expect it the snippet to contain *nothing* but a markdown list.
We do not support "indented" list style, only one item per linebreak.
Raises SyntaxError if snippet not in proper format (e.g. contains
any... | 5,336,493 |
def get_collection(*args, **kwargs):
""" Returns event collection schema
:param event_collection: string, the event collection from which schema is to be returned,
if left blank will return schema for all collections
"""
_initialize_client_from_environment()
return _client.get_collection(*args,... | 5,336,494 |
def get_tf_generator(data_source: extr.PymiaDatasource):
"""Returns a generator that wraps :class:`.PymiaDatasource` for the tensorflow data handling.
The returned generator can be used with `tf.data.Dataset.from_generator
<https://www.tensorflow.org/api_docs/python/tf/data/Dataset#from_generator>`_ in or... | 5,336,495 |
def is_mechanical_ventilation_heat_recovery_active(bpr, tsd, t):
"""
Control of activity of heat exchanger of mechanical ventilation system
Author: Gabriel Happle
Date: APR 2017
:param bpr: Building Properties
:type bpr: BuildingPropertiesRow
:param tsd: Time series data of buildin... | 5,336,496 |
def test_get_triup_dim():
"""Check that the function returns the correct number of nodes couples."""
cm = BiCM(np.array([[1, 0, 1], [1, 1, 1]]))
assert cm.get_triup_dim(False) == 3
assert cm.get_triup_dim(True) == 1
td = np.random.randint(low=0, high=2, size=50).reshape(5, 10)
cm = BiCM(td)
... | 5,336,497 |
def init_app(app, **kwargs):
""" Performs app-initialization operations related to the current module. """
from . import errors # noqa: F401
from . import views
app.register_blueprint(views.main_blueprint) | 5,336,498 |
async def fetch_user(user_id):
"""
Asynchronous function which performs an API call to retrieve a user from their ID
"""
session = aiohttp.ClientSession()
res = await session.get(url=str(f'{MAIN_URL}/api/user/{user_id}'),
headers=headers)
await session.close()
# ... | 5,336,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.