content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def read_data(filename):
"""
对文件数据中标签和内容进行分离
:param filename: 数据文件名
:return:标签和内容列表
"""
try:
label_list = []
data_list = []
with open(filename, 'r', encoding='utf-8') as r:
lines = r.readlines()
for line in lines:
line = line.strip... | 539343f2b2d4691140e230875b9b664f82096cda | 665,003 |
import random
def deal_card():
"""Return a random card from the list of cards
11 = ace
10 = face cards (jacks, queens, kings)
"""
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
card = random.choice(cards)
return card | 4ec00c00b31a5f3a233fc1ca41a7e8c2b9a84dff | 665,004 |
def dict_to_log_string(finding_dict):
"""Export the vulnerabilities to a default log file.
Format is comma seperated like property=value, prob2=val2"""
return ', '.join([f"""'{key}'='{finding_dict[key]}'""" for key in finding_dict.keys()]) | 639cae14ef4aee78f0cc337f7fe939e51187591a | 665,006 |
def max_strand(dataset):
"""Returns the largest strand number in the supplied dataset"""
return max(z.strand for z in dataset.zones()) | fa6d5fb7a8f95a0dc323977377ad7979a66f8166 | 665,007 |
import glob
def file_match(file_dict, target_model, target_variable, target_ensemble):
"""Find matching file in list of files."""
key = '%s_%s_%s' %(target_model, target_ensemble, target_variable)
match = file_dict.get(key, None)
files = glob.glob(match) if match else None
return files | 4520352832d4aeb7f947c3a9f03e175c1ce22350 | 665,008 |
def overlap(a, b):
"""
Checks to see if two casings intersect, or have identical start/end positions.
"""
# If the casing start/end intersects
intersect = (a[0] > b[0] and a[0] < b[1]) or (a[1] > b[0] and a[1] < b[1])
# If the casings start or end in the same place
overlap = (a[0] == b[0]) o... | 28d3382bb8ebd0fc12bb18c6311648d76f593bee | 665,009 |
from typing import Tuple
import math
def rot(
x: float, y: float, deg: float, origin: Tuple[float, float] = (0, 0)
) -> Tuple[float, float]:
"""
Rotate a point by `deg` around the `origin`. This does floating-point math, so
you may encounter precision errors.
"""
theta = deg * math.pi / 180
... | 411c66982dcddf454372058595cc2c142b4d5fe7 | 665,010 |
import json
def load_train_config(filename):
"""Load a configuration file."""
with open(filename, 'r') as f:
config = json.load(f)
return config | c60a6f5893cff1008ec7ed20f0afc3cd53bca388 | 665,011 |
def stock_sectors(degr, stock,interval = 1.1):
""" Split the degree in sectors based upon on the gap.
params: degr=sorted list of unqiue degrees
stock=List which contains the ranges of degree of a sector
interval=step range of degree for look up
return stock=list contain the ranges ... | 5fab52b1ab816c18a6e9a90fd8ab11075fea51c4 | 665,012 |
def my_seriation(Z, N, stack, result):
"""Returns the order implied by a hierarchical tree (dendrogram).
:param Z: A hierarchical tree (dendrogram).
:param N: The number of points given to the clustering process.
:param cur_index: The position in the tree for the recursive traversal.
:... | bfee8f063309e116859e1b91ba063fb0e1b9c755 | 665,013 |
import os
def test_config(empty_config):
"""Return orion's config overwritten with local config file"""
config_file = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "orion_config.yaml"
)
empty_config.load_yaml(config_file)
return empty_config | 981ea6954026e9b871a387c5e09d2953faf6ada6 | 665,014 |
def get_function_signature(func):
""" Get the function signature as a mapping of attributes.
:param func: The function object to interrogate.
:return: A mapping of the components of a function signature.
The signature is constructed as a mapping:
* 'name': The function's defined n... | 6a0b20b9979aae7b1808994d8452b5eb8c8bb00f | 665,015 |
def run_plugin_action(path, block=False):
"""Create an action that can be run with xbmc.executebuiltin in order to run a Kodi plugin specified by path.
If block is True (default=False), the execution of code will block until the called plugin has finished running."""
return f'RunPlugin({path}, {block})' | bac34fe4e68c417271ddc6966abcc045e5636fd8 | 665,017 |
def setup(df, params):
"""Calculate data series required for the backtest.
Takes as input a dataframe with columns `['date', 'price_l',
'price_r']` and returns a dataframe with columns `['date',
'price_l', 'price_r', 'return_l', 'price_change_l', 'std_l',
'std_pcg_l', 'return_r', 'price_change_r',... | e1fdde0eee37ded99ba732c25561c59a639a1da0 | 665,018 |
import os, re
def getPluginModules(packagedir):
"""
Return a list of plugin modules for a given plugin package dir,
omitting any that start with an underscore.
"""
pyre = re.compile(r"^([^_].*)\.py$")
dirlist = os.listdir(packagedir)
matches = [pyre.match(fn) for fn in dirlist]
module... | 748def0b55b32a65630ac02bf176a5e03d46c7ca | 665,020 |
import math
import torch
def construct_scale_pyramid(image, scale_factor=0.75, N=4, method='bicubic'):
"""
Constructs the scale pyramid
:param image: normed image tensor with shape (N, C, H, W)
:param scale_factor: float that indicates scale factor
:param N: int that indicates the number of neede... | 1ba0bb51e3d0384b0a6f8a8bda7d7ec9a06f6238 | 665,022 |
def dki_ad(subses_dict, dwi_affine, dki_params_file, dki_tf):
"""
full path to a nifti file containing
the DKI axial diffusivity
"""
return dki_tf.ad | 548e1f31f2a32bc572406ded749da27e5e0e70ea | 665,023 |
async def help_1(message, name):
"""Provides a description of a specific command."""
name = name.lower()
return message.chat.commands.help(name) | 931f7c6a34416b3401903ed65b24942b837a8de3 | 665,024 |
def read_file(filename):
"""
Read input file and save the crabs into a list.
:param filename: input file
:return: list of crabs
"""
crabs = []
with open(filename, 'r', encoding='UTF-8') as file:
for line in file:
for number in line.split(","):
crabs.append... | 0d06a6bcf98950474e1b2b38cc30697230acf742 | 665,025 |
def lat_fixed_formatter(y):
"""Simple minded latitude formatter.
Only because those available in cartopy do not leave a blank space
after the degree symbol so it looks crammed. If used outside this
module, bear in mind this was thought to be used as part of an
iterator to later be included in a
... | a47ac124bd5bdc5c3ee0feb529f28ba619f340d6 | 665,026 |
def bubble_sort(arr):
""" Sort Array Elements using Bubble Sort Algorithm
:return:
Examples:
>>> bubble_sort([1])
[1]
>>> bubble_sort([10,9,8,7,6,5,4,3,2,1])
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
"""
# Traverse through all array elements
n = len(arr)
for i in range(n):
# ... | 1ef4fe199c742f5b2862d5eb8d1b02b496855a85 | 665,027 |
def calcWaterFractionByVolume(waterVolume, glycerolVolume):
"""
Calculates the volume fraction of water in a water - glycerol mixture
Args:
waterVolume (float): volume of water in l
glycerolVolume (float): volume of glycerol in l
Returns:
:class:`float` Fraction of water by vol... | 266eacb68e10b8943902f8a879ecc25ff4f77b14 | 665,028 |
def sorted_by_attr(vals, attr, reverse=False):
"""Sort sequence <vals> by using attribute/key <attr> for each item in the sequence."""
return sorted(vals, key=lambda x: x[attr], reverse=reverse) | ccf92f78c8cd79fd0cc7034de8ff55a93784e344 | 665,029 |
def test_override_method(namespaceable, namespace):
"""Define a function, then overwrite it.
Non-data descriptors work.
"""
class Test(namespaceable):
"""A throwaway test class, for testing method overrides."""
with namespace() as namespace_:
def footer(self):
... | bcf952624cad5a20ce691517a3b934c39937bb96 | 665,031 |
def linear_search_recursive(array, item, index=0):
"""Return the index of the targeted item"""
if index >= len(array): # index is out of bound
return None # not found
elif array[index] == item:
return index # found
else:
return linear_search_recursive(array, item, index + 1) | 6911cbcf2a09eb9f38c62aaae62ab199d4d15188 | 665,032 |
def f_jet_force (working_mass, reactive_speed):
"""Тяга летательного аппарата."""
max_engine_thrust = working_mass * reactive_speed
return max_engine_thrust | 2c671bcc34167ac36139946a10fb6b879ac6d154 | 665,033 |
from typing import OrderedDict
def orderby(key_f, d: dict, reverse=False):
"""
对字典进行排序
> r = orderby(lambda item: item[1], {'a':3, 'b':1})
> print(r)
> OrderedDict([('b', 1), ('a', 3)])
:param key_f: Tuple[_K, _V] -> Comparable
:param d: dict
:param reverse: bool
:return:
"""... | dc2f7d21f7bfdd0f6e0d9db92e7f0a455fa5da24 | 665,034 |
def children(self):
"""return all children elements"""
return self.find_elements_by_xpath('*') | d65d1f94a333b9c2bc8f0ca46539fdcce5ce1e01 | 665,036 |
import six
import sys
def get_utf8_bytes(message):
"""Get the bytes array encoded by utf-8.
:param message: the string of message
:type message: string
"""
try:
if six.PY2:
message = message.decode(
sys.stdin.encoding if sys.stdin.encoding else 'cp936')
... | f466ef5b117f4b26ea57e477a94a9b740df5b355 | 665,037 |
def level_dataset(lv):
"""Get dataset key part for level.
Parameters
----------
lv : `int`
Level.
Returns
-------
`str`
Dataset key part.
"""
return '_lv%d' % lv | 1ac7d0fc42b2d8d542fac4713d7e414ff8efb4c0 | 665,038 |
def predict(upstream, model):
"""Make a prediction after computing features
"""
return model.predict(upstream['join']) | 1fab90a77e7e6923c7587b9e2e3f2cac7a6bf9b9 | 665,039 |
def user_input() -> int:
"""Displays a menu of the available actions and asks user's input
:return sel: integer representing user's choice"""
print("")
print("=" * 50)
print("1 - Collect images for calibration")
print("2 - Perform calibration")
print("3 - Disparity map tuning on sample imag... | f3d5a7d1f6a398f5c0fd84203c6c0d4d04fca780 | 665,040 |
def time_worked(clocked_in, clocked_out):
"""Return hours and minutes worked.
Args:
clocked_in: str, military time
clocked_out: str, military time
Returns:
(
hours: int, count of hours,
mins: int, count of minutes
): tuple
"""
section_time = la... | f2d9d1096811b1c9c13156a9bd17df6e31fcae47 | 665,041 |
from typing import List
def extract_protocols(client_output: str) -> List[str]:
"""Extract protocol from the output of 'get_protocols' operation."""
return client_output.split() | 4d8edb1a9556cb044e3bb4e68211e938e5668a04 | 665,042 |
def caesar_cipher_encode(n: int, text: str, p: str) -> str:
"""
Returns a string where the characters in text are shifted right n number
of spaces. The characters in text are only encrypted if they exist in p.
If they don't exist in p, they will remain unchanged.
Ex. str = 'abc12'
n = 3
... | ed77ee61eb5f56f55883ff9352241b1b28dab02e | 665,043 |
def get_next_active_day(days, current_day, active_days):
"""Gets the next active day, often this will simply be the next day, i.e. if you set the active days as Mon - Fri
and today is Mon, then the next active day is Tue. However is today is Fri then the next active day will be Mon.
If say our active days ... | 6f98e1a3c489e463b93617c97aab58bc4f7e8f55 | 665,044 |
def end_chat(input_list):
""" End chat
Parameters
----------
input_list : list
List containing 'quit' to end chat.
Returns
-------
True or False : boolean
Boolean assures whether to end chat based on whether the input contains 'quit'.
"""
if 'quit' in in... | bcf96aa2d3dc43c1d8464b9775c7450ebcf7984b | 665,045 |
def sample_from_config(opt):
"""
Applies the distributions specified in the opt.json file
"""
output = {}
for param, dist in opt.items():
if isinstance(dist, dict):
output[param] = sample_from_config(dist)
elif isinstance(dist, list):
output[param] = [sample_... | 83ec08ad173f8a90ca0b626ae43df903a2af89b1 | 665,046 |
import os
def get_ci_envvars():
"""
Get the CI env variables
"""
ci_env_var = {
"installer": os.environ.get('INSTALLER_TYPE'),
"scenario": os.environ.get('DEPLOY_SCENARIO')}
return ci_env_var | de73c1e62c09683c9c19c7f9a392a7dbf079ce96 | 665,047 |
def sort_array(source_array: list) -> list:
"""
Sorting ascending odd numbers but even
numbers must be on their places.
Zero isn't an odd number and you don't
need to move it. If you have an empty array,
ou need to return it.
:param source_array:
:return:
"""
output: list = sou... | 6b120377fea39945677cc81e4c6663ae97a32620 | 665,048 |
import socket
import struct
def parse_socks_addr(dat, allow_remain=False):
"""Extract address and port from SOCKS request header (only 4 parts:
RSV(0x00) | ATYP | DST.ADDR | DST.PORT). The header will be reused in tunnel server."""
if not dat or dat[0] != 0x00:
raise ValueError
try:
at... | 02f426d48327e34c3c7eb16c666d7c6a24577608 | 665,049 |
from typing import Mapping
from typing import Any
from typing import Dict
def logs_as_floats(logs: Mapping[str, Any]) -> Dict[str, float]:
"""Convert Keras metric log values to floats."""
return {name: float(value) for name, value in logs.items()} | e65731f4dd13b9fcf61d331580440d77fd57c940 | 665,051 |
def _keys_to_byte(keys: list, default=b'\x00') -> bytes:
"""Return a byte in which the bits X are 1 for each X in the list keys."""
return bytes([sum(map(lambda b: 1 << b, keys))]) if keys else default | ef6c1cacfc10399189ed40235b5fdbc694acc73e | 665,052 |
import math
def generate_nonpercent_aggregate_col(sorted_tables, site_and_date_info,
date):
"""
Function is used to generate a column that shows the SUM
of the data quality metrics for a particular table across all
sites. This column is for one date of analytics.
... | 2d399b60956abc5bc910a6d4f7a966ef889308c9 | 665,053 |
def byte_pad(data: bytes, block_size: int) -> bytes:
"""
Pad data with 0x00 until its length is a multiple of block_size.
Add a whole block of 0 if data lenght is already a multiple of block_size.
"""
padding = bytes(block_size - (len(data) % block_size))
return data + padding | 1839e36ab309e527d2832fabe190f884645fb5f2 | 665,054 |
def is_key_package(package, codebase):
"""
Return True if the ``package`` Package is a key, top-level package.
"""
# get the datafile_paths of the package
# get the top level files in the codebase
# return True if any datafile_paths is also a top level files? or key file?
datafile_paths = s... | 6ed637d55b3e7685ac9bfb60f74fca2a3ff458fa | 665,055 |
def _has_no_variables(sess):
"""Determines if the graph has any variables.
Args:
sess: TensorFlow Session.
Returns:
Bool.
"""
for op in sess.graph.get_operations():
if op.type.startswith("Variable") or op.type.endswith("VariableOp"):
return False
return True | 5db6d5d2485b49ad7d007f3b07519021b0de2732 | 665,056 |
def d_opt(param,value,extra_q=0):
"""
Create string "-D param=value"
"""
sym_q=""
if extra_q==1:
sym_q="\""
return("-D "+param+"="+sym_q+value+sym_q+" ") | 04daa34d3eca92e60651e763ee08553acd9cf331 | 665,058 |
def merge_vals(current, update):
"""Update the current container with updated values.
Supports dictionary, list and basic types, as well as nesting.
:param current: the container to update
:param update: the container to update with
:return: updated container
"""
if current is None: # val... | 4c4b8c641495b83c68b8abad6640c6ea53e465aa | 665,060 |
from typing import Dict
def get_271_member_not_found(demographics: Dict) -> str:
"""
Returns an Eligibility/271 response where a member is not found.
:param demographics: Demographic fields included within the x12 response.
:return: x12 transaction
"""
x12 = f"""ISA*00* *00* ... | 189ba94782cbf126777a7f8903a0b06ae43260d8 | 665,061 |
def linspace(start, end, num=50):
""" Return equally spaced array from "start" to "end" with "num" vals. """
return [start+i*((end-start)/float(num-1)) for i in range(num)] | 906356e29cdbedc983bc70cb96f714c08e8e8a85 | 665,062 |
def power_digit_sum():
"""Find the sum of the digits of the number 2 ** 1000"""
number = 2 ** 1000
stringify = str(number)
total = 0
for i in stringify:
total += int(i)
return total | 9bb758fd432eeb9895d36b829df9b6b92f726c9a | 665,063 |
def panel_to_multiindex(panel, filter_observations=False):
"""Convert a panel to a MultiIndex DataFrame with the minor_axis of the
panel as the columns and the items and major_axis as the MultiIndex (levels
0 and 1, respectively).
Parameters
----------
panel : a pandas Panel
filter_observa... | 37a90ba6f7e9f1b022dc87c0d3b9524509a6742a | 665,064 |
def get_steps_kwarg_parsers(cls, method_name):
"""
Analyze a method to extract the parameters with command line parsers.
The parser must be a :class:`Param` so it handles parsing of arguments
coming from the command line. It must be specified in the ``options``
class attribute.
:param method_n... | 5cc991c63c8008e92ff2bdc59c08ae1c96caa120 | 665,065 |
from unittest.mock import patch
def mock_cloud():
"""Fixture that mocks Midea cloud API client"""
with patch("midea_beautiful.cloud.MideaCloud") as mc:
return mc | 3225396cdf394b3fe551d396e1f436985c3e2a7d | 665,066 |
def set_buffer(library, session, mask, size):
"""Sets the size for the formatted I/O and/or low-level I/O communication buffer(s).
Corresponds to viSetBuf function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:para... | 01e496fb67f4fd74cfd6105899e5a100f0e77877 | 665,067 |
import random
def _get_hls_enc_option() -> str:
"""
获取 hls 加密选项字符串
:return: hls 加密选项字符串
"""
encrypt_opts = r"-hls_enc 1 -hls_enc_key {enc_key:s} -hls_enc_iv {enc_iv:s}"
enc_key_seed = '0123456789abcdef'
enc_key = ''.join([random.choice(enc_key_seed) for _ in range(32)])
enc_iv = ''.joi... | 4d122108b487cddb83968cdd6cd36c3402447c27 | 665,068 |
def build_loads(bus, demand, timestamp_to_timepoints):
"""Map timestamps to timepoints for demand data frame.
:param pandas.DataFrame bus: bus data from a Grid object.
:param pandas.DataFrame demand: demand by timestamp (index) and zone IDs (columns).
:param pandas.Series timestamp_to_timepoints: timep... | 104bc29184391d9430f0b00566649123754b63cb | 665,069 |
def safe_getattr(obj, attr_name):
"""Get the attribute of an object returning None if the attribute does not
exist.
:param obj: An object
:type obj: mixed
:param attr_name: The name of the attribute
:type attr_name: str or unicode
"""
try:
return getattr(obj, attr_name)
exce... | 9ed3eb8b0da04f65e3ac9316a2afa6c57648fd64 | 665,070 |
def ContactVCard(parent):
"""A factory for generating contact commands"""
synopsis = [(t and t.replace('vcard', 'contact') or t)
for t in parent.SYNOPSIS]
synopsis[2] = synopsis[1]
class ContactVCardCommand(parent):
SYNOPSIS = tuple(synopsis)
KIND = 'individual'
... | 9ca1ac450b554324829d0d2f95a5cb0efe867357 | 665,071 |
import torch
def evaluate_epoch(model,dataLoader,loss_function,
bert, device,with_trans=True):
"""Evaluate one epoch of the model"""
epoch_loss = 0
model.eval()
with torch.no_grad():
for Xsents_input_ids,Xsents_token_type_ids,\
Xsents_attention_mask,Xsents_p... | b9de6616dda71327ee8c1022a51fd9c362619559 | 665,072 |
import numpy as np
def subtract_offset(work):
""" Subtract the initial work of the work trajectory. """
work_offset = []
for cycle in work:
work_offset.append(np.array([value - cycle[0] for value in cycle[1:]]))
work_offset = np.array(work_offset)
return work_offset | e17f1897c989b28523349d3793925b1a4e76d3ba | 665,074 |
def getCcpnExperimentShiftList(ccpnExperiment):
"""Descrn: Fetch the CCPN shift list that corresponds to a CCPN NMR experiment
Inputs: ccp.nmr.Nmr.Experiment
Output: ccp.nmr.Nmr.ShiftList
"""
shiftList = ccpnExperiment.shiftList
if not shiftList:
for spectrum in ccpnExperiment.da... | abd71c118a61fd838ac4da1b9095f3b1ee537c9e | 665,076 |
def GetHotkey(text):
"""Return the position and character of the hotkey"""
# find the last & character that is not followed
# by & or by the end of the string
curEnd = len(text) + 1
text = text.replace("&&", "__")
while True:
pos = text.rfind("&", 0, curEnd)
# One found was at ... | 5fa03a1fe07c7f561143f9f64d5fd3908c86ae7f | 665,077 |
import os
import requests
def create_tg_transition_data(traffic_group, action):
"""Creates the return data used by the tgactive, tgstandby, tgrefresh notifications"""
if traffic_group:
data = {
'instance_id': None,
'device_id': None,
'action': action,
't... | 72ee844e8a138461193300a74a28b1bf18351395 | 665,078 |
def SafeCast(value, desired_type, default=None):
"""Cast between types without any pesky errors."""
try:
return desired_type(value)
except (ValueError, TypeError):
return default | 51646c85412695d11428d50d30451887eebbed76 | 665,079 |
from pathlib import Path
def is_ignored(file: Path, ignore_globs: list[str]) -> bool:
"""
:return: if file should be ignored (matches any glob in .cmpignore)
"""
for glob in ignore_globs:
if file.match(glob):
return True
return False | 74392e33b164e145c9259e1bf3505ada522caf3d | 665,080 |
import os
import sys
import io
def file_2list(input_file):
"""Read in a csv file and return lines a list."""
input_file = os.path.normpath(input_file)
if sys.version_info >= (3, 0, 0):
input_obj = io.open(input_file, "rU")
else:
input_obj = io.open(input_file, encoding=ENCODING)
... | a77eae9723333551af4d56dee1f6cfb70ca73b60 | 665,081 |
import time
def timetrace(message, idstring, tracemessage="TEST_MESSAGE", final=False):
"""
Trace a message with time stamps.
Args:
message (str): The actual message coming through
idstring (str): An identifier string specifying where this trace is happening.
tracemessage (str): T... | 98882610b4a184a6918c0be7302bc9117a6f153a | 665,082 |
def _order_for_score_state_graph(toidf):
"""
Want to arrange teams so top team has most time leading minus trailing.
This method sums over lead/trail, sorts, and arranges so the team with the largest (lead-trail) has the highest Y.
:param toidf: dataframe, unique on team and score state
:return: ... | d9531ea0862d2686f8df9a374d61f9961cef8a9a | 665,083 |
import re
def insert_spaces(text: str) -> str:
"""Insert space in Chinese characters.
>>> insert_spaces("test亨利it四世上")
' test 亨 利 it 四 世 上 '
>>> insert_spaces("test亨利it四世上").strip().__len__()
17
"""
return re.sub(r"(?<=[a-zA-Z\d]) (?=[a-zA-Z\d])", "", text.replace("", " ")) | 27bf13847b717bfaa37fdc79ea21fe7ae3ef9ec4 | 665,084 |
def clean_data(record):
"""Cleans data to get single ',' separated byte messages."""
record = ','.join(record.split())
return record.encode('utf-8') | 2098833553bdccbcc6a6f9f7d7ae49b67f2086e5 | 665,086 |
def build_topic_base_info(topic):
"""
构造 Topic 基本信息
:param topic:
:return:
"""
return {
'id': topic.id,
'title': topic.title,
'user': topic.user.username,
'created_time': topic.created_time.strftime('%Y-%m-%d %H:%M:%S')
} | a2a14e33c511e28b99e8a54fa9baa6178eed1840 | 665,087 |
from typing import Optional
def get_image_provision_timestamp(log_path: str) -> Optional[str]:
"""
Examines the Travis build log file at `log_path` to determine when the image used by the build was provisioned.
:param log_path: The path to the Travis build log. This should be an original build log.
:r... | 182d351302e4e08a377910bfad409dece9d69456 | 665,088 |
def asset_italy(gee_dir):
"""return the italy asset available in our test account"""
return f"{gee_dir}/italy" | f6b11eea022cc7c0ef925e9d626aa1f437a4584c | 665,089 |
def read_file (file):
"""
file is a file object with format:
Read from a list of names and telephone number in format:
1 Name
1 Phone Number
2 Name
2 Telephone number
** Seperated by a new line (\n)
Function: To read from a file and allocate to a variabl... | ccecc2cafb62d5ebdea7d9a163e200cd9dd3398a | 665,090 |
import os
def _get_resized_name(image, width, height, crop, namespace):
"""
Get the name of the resized file when assumed it exists.
"""
path, name = os.path.split(image.name)
name_part = "%s/%ix%i" % (namespace, width, height)
if crop:
name_part += "_cropped"
return os.path.join(... | 360bdf5ec8aa8718fe341439aba87dedf21682f0 | 665,091 |
def _retain_from_list(x, exclude):
"""Returns the features to retain. Used in
conjunction with H2OTransformer classes that
identify features that should be dropped.
Parameters
----------
x : iterable of lists
The list from which to exclude
exclude : array_like
The columns ... | a7e8488dcae2a997dc823ff674101a95ada20f78 | 665,092 |
def network(web3_test_provider):
"""Network name to be used in database when run against in-memory test chain."""
return "testing" | 38f6286558c3aae1ad1de04d02c051f07566443e | 665,093 |
import torch
def normalized_cross_correlation(x, y, return_map, reduction="mean", eps=1e-8):
""" N-dimensional normalized cross correlation (NCC)
Args:
x (~torch.Tensor): Input tensor.
y (~torch.Tensor): Input tensor.
return_map (bool): If True, also return the correlation map.
... | f7989de1bcaf449f2a0380198c37a4de92dcbc27 | 665,094 |
import pytz
def datetime_to_string(dttm):
"""Given a datetime instance, produce the string representation
with microsecond precision"""
# 1. Convert to timezone-aware
# 2. Convert to UTC
# 3. Format in ISO format with microsecond precision
if dttm.tzinfo is None or dttm.tzinfo.utcoffset(dttm)... | d947e06cd75b9e57853fe6cca891911e7d819128 | 665,095 |
def node_size(node):
"""
Get node size
:param node: xpath node
:return: width and height of node
"""
w = h = None
try:
w = float(node.get("box_width"))
h = float(node.get("box_height"))
except TypeError:
pass
return w, h | 5e1ea3094b304759ee8f14ed8dffc37fafe3d77f | 665,096 |
from typing import Iterable
def rgb_hexify(rgb: Iterable[int]) -> str:
"""Convert a list of RGB numbers to a hex format.
"""
return ''.join(
list(map(
lambda x: hex(abs(x))[2:].zfill(2),
rgb
))[::-1]
) | b3acc17d105de8190a4e386d7e2f71c834601ebe | 665,097 |
def _create_fold_path_component(edge_direction, edge_name):
"""Return a tuple representing a fold_path component of a FoldScopeLocation."""
return ((edge_direction, edge_name),) | 6c169272b4d6052b9d6f9883a17e2f5be0d49193 | 665,098 |
import os
def CreateLocalePaksXml(names):
"""Creates the contents for the locale-paks.xml files."""
VALUES_FILE_TEMPLATE = '''<?xml version="1.0" encoding="utf-8"?>
<resources>
<array name="locale_paks">%s
</array>
</resources>
'''
VALUES_ITEM_TEMPLATE = '''
<item>@raw/%s</item>'''
res_names = (os.pa... | 2f4d78ae5fb06e1b8bb188389a6afbc84eb9943b | 665,099 |
def skip_duplicate(keys, child_members, parent_members, combined_dict_temp):
""" Skipping duplicate by deleting from configuration """
for items_c in child_members:
flag = 0
for items_p in parent_members:
if items_c['vip-group'] == items_p['vip-group']:
flag = 0
... | 66140636256df47bf20bc2661aab074a7e8af9e7 | 665,100 |
def default_mq_services() -> set:
"""
Return a specified set of default MQ services
"""
return {"neon-rabbitmq",
"neon-api-proxy",
"neon-email-proxy",
"neon-metrics-service"} | 9ba5e5119647e179e000219d4892fd6b49b7edea | 665,101 |
def read_header_and_channels(filename, chtrig):
"""
Reads a txt file with a header and channels and separates them
Parameters
----------
filename: str
path to the txt Labchart file
chtrig : int
index of trigger channel
Returns
-------
header: list
header lin... | 649d252709cd036264cb9a93abebe5bcf2b1d6b2 | 665,102 |
def quads_to_triangles(mesh):
"""
Convert Quad faces to Triangular ones.
Inputs:
mesh - an OBJ object loaded from load_obj()
Outputs:
Modifies the mesh.f and returns mesh.
"""
newFaces = []
for i, face in enumerate(mesh.f):
if(len(face) != 3):
assert len(f... | e1deeda6d646b0bb0c192181722967b0b41c9b38 | 665,103 |
def stat_lookup(perf_dict, counter_name):
"""
Performance the lookup of the supplied counter name against the dictionary and returns a counter Id
:param perf_dict: The array containing the performance dictionary (with counters and IDs)
:param counter_name: The counter name in the correct format for the... | df968b79ccdf87c968edbe0b2ef6f1584a74f49c | 665,104 |
import re
def get_category_cardinality(files):
""" Deprecated: function used before for identifying the samples based in its name
and calculate the minimum and maximum sample id
:param files: array of root paths.
:return: min_id, max_id: int
"""
file_pattern = r'([0-9]+)\.csv'
id_reg_expre... | 7704fbda7a05d355eb07698ac1975975c18bf4a7 | 665,105 |
from typing import Union
from typing import Optional
def _get_event_url(
cz_event_id : Union[str,int]
,cz_draw_id : Optional[Union[str,int]] = None
)->str:
"""Returns the cz event page url."""
if cz_draw_id is None:
return 'https://curlingzone.com/event.php?view=Scores&eventid=%s#1'%cz_event... | e2492dc76840c4241d5a0202d49eb0eb2be7fe7b | 665,106 |
def to_list(x):
"""Converts input to a list if necessary."""
if isinstance(x, (list, tuple)):
return x
else:
return [x] | 7cfe3e318418318e70a67fa8e871f7993ad59950 | 665,107 |
def add_header(response):
"""Add CORS and Cache-Control headers to the response."""
if not response.cache_control:
response.cache_control.max_age = 30
response.headers['Access-Control-Allow-Origin'] = '*'
response.headers['Access-Control-Allow-Methods'] = 'GET'
return response | 6e08a6d5958dcd0d46904b218b72b3519cfd283c | 665,108 |
import pickle
def load_object(filename, loc):
"""load pickle object by file name"""
with open(loc + '/' + filename, 'rb') as input: # Overwrites any existing file.
obj = pickle.load(input)
return obj | 627186a5f23be350327b77b6bc51b44f5d90e979 | 665,109 |
def parse_head(head_contents):
"""Given contents of HEAD, return file path to branch head file
Example head_contents include:
ref: refs/heads/main
Given the above example, the following would be returned:
.git/refs/heads/main
"""
if head_contents.startswith("ref: "):
return he... | 071cfc2a1171a4bd6d4f9869e09c9bf398858140 | 665,110 |
import numpy
def vecMag(vec):
"""Compute the magnitude of a vector
"""
return numpy.sqrt(numpy.sum(numpy.square(vec))) | 7300954b1f1c1747f62cb206f74a3cfbf6359eac | 665,111 |
def ascent_set(t):
"""
Return the ascent set of a standard tableau ``t``
(encoded as a sorted list).
The *ascent set* of a standard tableau `t` is defined as
the set of all entries `i` of `t` such that the number `i+1`
either appears to the right of `i` or appears in a row above
`i` or does... | 14d1b0872cc461b719827f51532511729597d8f0 | 665,112 |
def empty_string_to_none(string):
"""Given a string, return None if string == "", and the string value
(with type str) otherwise
"""
if string == '':
return None
else:
return str(string) | 3510cc65306e56f5845a9f0fbad737e3660d4f2e | 665,113 |
def get_total_tiles(min_zoom: int, max_zoom: int) -> int:
"""Returns the total number of tiles that will be generated from an image.
Args:
min_zoom (int): The minimum zoom level te image will be tiled at
max_zoom (int): The maximum zoom level te image will be tiled at
Returns:
The t... | 8be77bb05399022385028823b3c1960927b573cc | 665,115 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.