content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_ssa(net, blob_versions=None):
"""
Given a net, return a structure containing the version of each input and
output blob used by each operator.
Args:
net: either a Net or a NetDef
blob_versions: (optional) map with current version number for given
... | 64,200 |
def band_dos_element_spd_spin_polarized(
band_folder,
dos_folder,
element_spd_dict,
output='band_dos_element_spd_sp.png',
scale_factor=5,
color_list=None,
legend=True,
linewidth=0.75,
band_color='black',
unprojected_band_color='gray',
unprojected_linewidth=0.6,
figsize=(8... | 64,201 |
def test_PathTuplesToChunk_directory_not_found(tempdir: pathlib.Path,
photodir: pathlib.Path):
"""A ValueError is raised if any of the source directories do not exist."""
with pytest.raises(ValueError) as e_ctx:
shutterbug.PathTuplesToChunk([photodir, tempdir / 'fo... | 64,202 |
def get_redirect_target():
""" Returns the redirect target. """
for target in request.args.get('next'), request.referrer:
if not target:
continue
elif is_safe_url(target):
return target | 64,203 |
def construct_schedule(
name: str,
**kwargs,
) -> Callable[[chex.Numeric], chex.Array]:
"""Constructs the actual schedule from its name and extra kwargs."""
if name == "fixed":
return functools.partial(fixed_schedule, **kwargs)
elif name == "imagenet_sgd":
return functools.partial(imagenet_sgd_sch... | 64,204 |
def set_month_year(io: IO, user_selected_moth_year: str) -> tuple[int, int]:
"""
Produce Month/Year combination to filter calendar by
:param io: instance of IO object
:param user_selected_moth_year: string containing user-selected combination of Month/Year
:return: tuple[int, int] Month, Year
""... | 64,205 |
def dump_to_writer(writer, resources, resource_type=None, fields=None):
"""
Dump resources to a CSV writer interface.
The interface should expose the :py:class:`csv.writer` interface.
:type writer: :py:class:`csv.writer`
:param writer: Writer object
:param fields: List of fields to write
:... | 64,206 |
def find_author(name, authors):
""" Find the author with the provided name, in the list of authors"""
for author in authors:
if author.name == name: return author
raise ValueError('Author', name, 'not found.') | 64,207 |
def IAM_calc(ang_target,IAM_type,file_loc):
"""
This IAM is calculated with a table of many known IAM for specific angles
and computes a linear interpolation between two known angles for unknown angles.
"""
ang_target=abs(ang_target)
IAM_raw = np.loadtxt(file_loc, delimiter=",")
... | 64,208 |
def _format_resolution_output(path, project, folderpath, entity_name, result):
"""
:param path: Path to the object that required resolution; propagated from
command-line
:type path: string
:param project: The potential project the entity belongs to
:type project: string
:param f... | 64,209 |
def find_corr_vars(correlation_dataframe,corr_limit = 0.70):
"""
This returns a dictionary of counts of each variable and how many vars it is correlated to in the dataframe
"""
flatten = lambda l: [item for sublist in l for item in sublist]
flatten_items = lambda dic: [x for x in dic.items()]
... | 64,210 |
def removeblanklines(astr):
"""remove the blank lines in astr"""
lines = astr.splitlines()
lines = [line for line in lines if line.strip() != ""]
return "\n".join(lines) | 64,211 |
def create_sha256sum_file(
directory: str, sumfile: str = "SHA256SUMS.TXT", depth: int = 1
) -> None:
"""
Create a checksum file for a given directory
This function creates the file on the fly bacause we yield results
:param directory: (str) path to the directory to create the sumfile for
:para... | 64,212 |
def image_filtering(img_array):
"""Put each object in the image into seperate image, returns list of images """
objects_array = []
object_ids = set(np.unique(img_array))
object_ids -= {0}
for object_id in object_ids:
obj_array = np.where(img_array == object_id, img_array, 0)
objects_... | 64,213 |
def get_system_settings(clear_metadata=True, exclude_locals=None):
"""System settings with applied studio overrides."""
default_values = get_default_settings()[SYSTEM_SETTINGS_KEY]
studio_values = get_studio_system_settings_overrides()
result = apply_overrides(default_values, studio_values)
# Clear... | 64,214 |
def resolve_average_callable(
averaging_method: [str, Callable[[np.ndarray], np.ndarray]]
) -> Callable[[np.ndarray], np.ndarray]:
"""Resolve a string or callable to a averaging callable.
Parameters
----------
averaging_method: str or Callable, defaults = 'mean'
Averaging method to compute ... | 64,215 |
def test_execute_for_all_repos(
mock_config_manager: MockerFixture,
mock_github_service: MockerFixture,
domain_branch: str,
) -> None:
"""It returns success."""
config_manager = mock_config_manager.return_value
github_service = mock_github_service.return_value
response = ghdb.GhDeleteBranchU... | 64,216 |
def cli(
) -> None:
"""A Bitbucket restapi client."""
pass | 64,217 |
def printChapterE(self, section):
"""
"""
output = []
#if self.FAxial == 'COMPRESSION':
#
output.append(" "+"\n")
output.append("_______________________________________________________________________________________"+"\n")
output.append(" "+"\n")
output.append(" F... | 64,218 |
def CheckEmailFormat(email: str) -> bool:
"""
Emailアドレスのフォーマットをチェックする。
ask him
"""
regex = r'^(\w|\.|\_|\-)+[@](\w|\_|\-|\.)+[.]\w{2,3}$'
if(re.search(regex, email)):
# print("Valid Email")
return True
else:
# print("Invalid Email")
return False | 64,219 |
def start(stocks):
"""Starts the MarketWatcher."""
echo("Starting MarketWatcher...")
try:
context.running = True
echo("MarketWatcher started.")
echo(f"Reading target stocks from file: {stocks}")
target_stocks = get_terget_stocks(stocks)
notifiers = []
if c... | 64,220 |
def run_pipeline_location_list(configuration_file,
location_list=None,
input_data_dir=None,
persistent_data_dir=None,
output_dir=None):
"""Run `run.py` for a list of locations."""
for... | 64,221 |
def datadriven(**testcases):
"""
You should decorate tests with datadriven if you want to pass data to them
(and have them called multiple times).
For example, declaring a test method like this:
@datadriven(
dataA=Args(paramA="foo"),
dataB=Args("hello", paramB="world")
... | 64,222 |
def version():
"""Returns the version number of the plugin manager.
Returns:
str
"""
return VERSION | 64,223 |
def main():
"""Entry point to the script."""
sample_id = None
sample_id_re = re.compile(SAMPLE_ID_PATTERN)
# Basic parsing of command line arguments to allow a filename
# to be passed when running this code in the debugger.
path = None
file_handle = sys.stdin
if 2 <= len(sys.argv):
path = sys.argv... | 64,224 |
def AccountMoveVolumes(account_name,
account_id,
volume_names,
volume_ids,
volume_prefix,
volume_regex,
volume_count,
source_account,
so... | 64,225 |
def parse_notes(filename):
"""Build a Node list from the note text file"""
with codecs.open(filename, "r", "utf8") as file:
lines = file.readlines()
valid_line_regex = re.compile(r"^ *(il. ?)?~?\d+")
move_regex = re.compile(
r"((?:[KQBNR][a-h]?[1-8]?|[a-h])?x?[a-h][1-8]\+?\#?|O-O-O|O-O|\... | 64,226 |
def get_history_file_n(folderlist, param, nyears):
"""
Exhibits a graphic with the production of the group of researchers.
The 'production' is defined according to the parameters inserted.
Args:
folderlist: the list of folders where the Lattes CV file are
found.
param: a... | 64,227 |
def get_spark_memory_config(memory=SparkDefault.MEMORY):
"""
Assemble memory configuration for a Spark session
:param memory: string with memory configuration for spark
:return: memory configuration
"""
if not memory:
return ()
memory = memory.split(",")
if len(memory) != 3:
... | 64,228 |
def to_type(cls):
"""
Cast the data to a specific type
Parameters
----------
cls : class object
The class to cast the object to
"""
return lambda _, value: cls(value) | 64,229 |
def post_save(sender, instance, raw, created, using, update_fields, **kwargs):
"""https://docs.djangoproject.com/es/1.10/ref/signals/#post-save"""
try:
if not should_audit(instance):
return False
# new created obj
if created:
event_type = CRUDEvent.CREATE
... | 64,230 |
def tuneModel(grid, x_train, y_train, n_iter=3, cv=3, random_state=42, n_jobs = -1):
"""
Implements randomized parameter search for Random Forest models.
Parameters
----------
grid: dict
dictionary with list of possible values for each parameter
that should be tuned
x_train: li... | 64,231 |
def md5_key(chrom, start, end, ref, alt, assembly):
"""Generate a md5 key representing uniquely the variant
Accepts:
chrom(str): chromosome
start(int): variant start
end(int): variant end
ref(str): references bases
alt(str): alternative bases
assembly(str) genome... | 64,232 |
def test_get_correct_gene(genes):
"""Test that the get_correct_gene returns the right gene"""
# GIVEN a list of genes
gene_list = list(genes.values())
assert len(gene_list) > 0
# And a random gene from the list
random_gene = gene_list[2]
# THEN the get_correct_gene function should return ... | 64,233 |
def temp_filename(filename):
"""Context that returns a temporary filename and deletes the file on exit if
it still exists (so that this is not forgotten).
"""
_, temp_fname = tempfile.mkstemp(filename)
yield temp_fname
if os.path.exists(temp_fname):
os.remove(temp_fname) | 64,234 |
def convert_xml_to_json(xml_filename, output_filename):
"""Create a JSON file based on XML assessment data.
Parameters
----------
xml_filename : str
The name of the source XML assessment data file.
output_filename : str
The name of the target JSON assessment data file.
Returns... | 64,235 |
def load_object_with_pickle(file_name: str) -> object:
"""Loads a object easily be using pickle module.
Args:
file_name (str): file_name.pkl
Returns:
object (object): Any PyAbsorp object.
"""
__endswith_pkl_check(file_name)
try:
with open(file_name, "wb") as load_file:
... | 64,236 |
def create_table():
"""Creates table 'survivors' if table doesn't exist."""
conn = connect_db()
cur = conn.cursor() #cursor (TBD: see init_db 'c' for cursor: determine if a general cursor object for the entire app should get made)
cur.execute('CREATE TABLE IF NOT EXISTS survivors(familyName... | 64,237 |
def test_aspen_qubit_positions_and_distance():
"""test AspenQubit 2D position and distance calculations"""
qubit10 = AspenQubit(1, 0)
assert qubit10.octagon == 1
assert qubit10.octagon_position == 0
assert qubit10.dimension == 2
assert np.isclose(qubit10.x, 3 + 3 / sqrt(2))
assert np.isclos... | 64,238 |
def main():
"""
This code, which must run on a LAPTOP:
1. Constructs a GUI for my part of the Capstone Project.
2. Communicates via MQTT with the code that runs on the EV3 robot.
"""
# -------------------------------------------------------------------------
# Construct and connect the M... | 64,239 |
def _roll_cube_data(cube, shift, axis):
"""Roll a cube data on specified axis."""
cube.data = np.roll(cube.data, shift, axis=axis)
return cube | 64,240 |
def activate(username):
"""Activate a user.
Example:
\b
```bash
$ polyaxon user activate david
```
"""
try:
PolyaxonClient().user.activate_user(username)
except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:
Printer.print_error('Could no... | 64,241 |
def test_index(client):
"""Does the portfolio's main page render properly?"""
response = client.get("/")
assert b"Development" in response.data | 64,242 |
def _NW(dataset):
""" Nerve Weakness
"""
pass | 64,243 |
def _dataset_version(path, name):
"""Get the version of the dataset."""
ver_fname = op.join(path, 'version.txt')
if op.exists(ver_fname):
with open(ver_fname, 'r') as fid:
version = fid.readline().strip() # version is on first line
else:
# Sample dataset versioning was intro... | 64,244 |
def main():
"""Generates markdown file"""
client = carla.Client('127.0.0.1', 2000)
client.set_timeout(2.0)
world = client.get_world()
bp_dict = {}
blueprints = [bp for bp in world.get_blueprint_library().filter('*')] # Returns list of all blueprints
blueprint_ids = [bp.id for bp in world.g... | 64,245 |
def acf(x, max_lag):
"""
Autocorrelation function transform, currently calculated using standard
stats method. We could use inverse of power spectrum, especially given we
already have found it, worth testing for speed and correctness. HOWEVER,
for long series, it may not give much benefit, as we do ... | 64,246 |
def _missing_ids(vba, pcode_ids, verbose=False):
"""
See if there are any function names or variables that appear in
the p-code that do not appear in the decompressed VBA source code.
vba - (str) The decompressed VBA source code.
pcode_ids - (set) The IDs defined in the p-code.
return - (floa... | 64,247 |
def remove_url_from_file(src_file, dst_file):
"""
Remove URLs from the file, keep everything else as it was
"""
with open(src_file, 'r') as f:
with open (dst_file, 'wa') as outfile:
for line in f:
out_string = remove_url(line)
outfile.write(out_string) | 64,248 |
def get_staking_transaction_by_hash(tx_hash, endpoint=_default_endpoint, timeout=_default_timeout) -> dict:
"""
Get staking transaction by hash
Parameters
----------
tx_hash: str
Hash of staking transaction to fetch
endpoint: :obj:`str`, optional
Endpoint to send request to
... | 64,249 |
def make_wrap_words(length, sep=','):
"""Returng wrap words function."""
return lambda words: wrap_words(words, length, sep) | 64,250 |
def parse_assignments_expressions(code):
"""Parse a code block composed of variable assignments.
Args:
code: Multiline string representing Python code
Returns: Dict <variable_name>: <(variable_type, variable_value)>
"""
variables = dict()
tree = ast.parse(code)
for block in tree.bo... | 64,251 |
def hearing_test():
"""
Determines if the user is eligible to take the hearing test (i.e. has not exceeded `MAX_HEARING_TEST_ATTEMPTS`, and
then renders the hearing test, which consists of the assessor counting the tones in two audio files.
If caqe.settings.HEARING_TEST_REJECTION_ENABLED is set to Fals... | 64,252 |
def load_cdk_app(cdk_app_path, cdk_app_name):
"""
Load a CDK app from a folder path (dynamically)
:param cdk_app_path: The full path of the CDK app to load
:param cdk_app_name: The module path (starting from cdk_app_path) to find the function returning synth()
:return:
"""
try:
(cdk... | 64,253 |
def sizeof_fmt(num: float, suffix: str = 'B') -> str:
"""
Formats a number of bytes in a human-readable binary format (e.g. ``2048``
becomes ``'2 KiB'``); from http://stackoverflow.com/questions/1094841.
"""
for unit in ('', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi'):
if abs(num) < 1024.0:
... | 64,254 |
def get_pod_memory_usage_range(cluster_id, namespace, pod_name_list, start, end, bk_biz_id=None):
"""获取CPU总使用率
start, end单位为毫秒,和数据平台保持一致
"""
step = (end - start) // 60
pod_name_list = "|".join(pod_name_list)
porm_query = f"""
sum by (pod_name) (container_memory_working_set_bytes{{cluste... | 64,255 |
def is_isotropic(self, p):
"""
Checks if Q is isotropic over the p-adic numbers `Q_p`.
INPUT:
`p` -- a prime number > 0
OUTPUT:
boolean
EXAMPLES::
sage: Q = DiagonalQuadraticForm(ZZ, [1,1])
sage: Q.is_isotropic(2)
False
sage: Q.is_isotropic(3)
... | 64,256 |
def floquet_markov_mesolve(
R, rho0, tlist, e_ops, options=None, floquet_basis=True,
f_modes_0=None, f_modes_table_t=None, f_energies=None, T=None,
):
"""
Solve the dynamics for the system using the Floquet-Markov master equation.
.. note::
It is important to understand in which frame and ... | 64,257 |
def build_query(filters, page):
"""
Construye el query de búsqueda a partir de los filtros.
"""
return filters.buildQuery().order_by('nombre') | 64,258 |
def _get_storage_api(retry_params, account_id=None):
"""Returns storage_api instance for API methods.
Args:
retry_params: An instance of api_utils.RetryParams.
account_id: Internal-use only.
Returns:
A storage_api instance to handle urlfetch work to GCS.
On dev appserver, this instance by defaul... | 64,259 |
def store_dial_data(app_name, data):
"""Store the DIAL data key/value pairs in to a file"""
# NOTE: the reference code store the file in the application folder, we save the file in our data folder
# perhaps other changes will be needed to allow USE_ADDITIONAL_DATA feature to work
file_path = 'dial_dat... | 64,260 |
def ensure_ipynb_compatibility(group: "TestGroup", items: list) -> None:
"""
Ensures that group doesn't contain partial IPy notebook cells.
``pytest-split`` might, in principle, break up the cells of an
IPython notebook into different test groups, in which case the tests
most likely fail (for start... | 64,261 |
def io_wrapper(io_str: str, mode: str) -> Tuple[bool, Any]:
"""
Wrapper for IO stream
Args:
io_str: "-" or file name
mode: IO mode
"""
if io_str != "-":
std = False
stream = codecs.open(io_str, mode, encoding="utf-8")
else:
std = True
if mode not i... | 64,262 |
def create_replication_instance(ReplicationInstanceIdentifier=None, AllocatedStorage=None, ReplicationInstanceClass=None, VpcSecurityGroupIds=None, AvailabilityZone=None, ReplicationSubnetGroupIdentifier=None, PreferredMaintenanceWindow=None, MultiAZ=None, EngineVersion=None, AutoMinorVersionUpgrade=None, Tags=None, Km... | 64,263 |
def bas(carte,personnage,etat) :
""" fonction qui fait une action lorsque l'on appuis sur la fleche du haut ou s(azerty) """
print("s ou fleche bas") | 64,264 |
def main():
"""模拟tornado框架,处理两个请求"""
req_a()
req_b() | 64,265 |
def get_algo_invalidate_solved_values(board: Board):
"""
simple invalidator: iterate through rows, cols, packages and invalidate already-solved candidates
"""
def invalidate_solved_values():
for unit in board.get_all_houses():
unit.invalidate_solved_values()
board.validate_co... | 64,266 |
def query_parse(field_key_map: FieldKeyMap, **kwargs):
"""
将查询条件转化为 filterByFormula
records.filter(title="hello", subtitle="world") => '{title}="hello" AND {subtitle}="world"'
1. 通过 filter 和 get 参数查询到的只能转化为 and 条件。
"""
query_str = ""
for k, v in kwargs.items():
if query_str:
... | 64,267 |
def thrown_showers_per_ebin(sim_list, log_energy_bins=None):
"""Calculate the number of thrown showers in each energy bin
Parameters
----------
sim_list : array_like
Sequence of simulation dataset numbers.
log_energy_bins : array_like or None, optional
Log energy bins to use (defaul... | 64,268 |
def test_associate_attribute_to_product_instance_from_different_attribute(
product, color_attribute, size_attribute
):
"""Ensure an assertion error is raised when one tries to associate attribute values
to an object that don't belong to the supplied attribute.
"""
instance = product
attribute = ... | 64,269 |
def validate_job_tags(job_tags: Optional[List[str]], exception: Type[Exception]) -> None:
"""Validates input job tags.
Args:
job_tags: Job tags to be validated.
exception: Exception to raise if the tags are invalid.
Raises:
Exception: If the job tags are invalid.
"""
if job... | 64,270 |
def save_resources(filename, resources):
"""
Save the identified resources to a file.
"""
with open(filename, 'w') as f:
for resource in resources:
f.write('{0}\n'.format(resource)) | 64,271 |
def test_newClient_import_fix(monkeypatch):
"""newClient should set an 'ImportDoctor' derived from the wsdl"""
call_args = newClient_call_args(
monkeypatch, wsdl='https://rando-domain.gov/some/where?wsdl')
doctor = call_args['doctor']
assert 'xmlsoap' in doctor.imports[0].ns
assert doctor.im... | 64,272 |
def _request_youtube(method, url, env, params=None, headers=None, json=None):
"""Perform a YouTube Reporting API request.
This function refreshes the access token if necessary.
"""
request_fn = {"DELETE": requests.delete, "GET": requests.get, "POST": requests.post}
assert method in request_fn
... | 64,273 |
def test_python(host):
""" Test the installed Python.
"""
python = "~/.pyenv/shims/python" # path must be explicit
assert host.check_output(f"{python:s} --version") == "Python 3.6.4"
return | 64,274 |
def test_profile_sys_object_unknown(aggregator, caplog):
"""If the fetched sysObjectID is not referenced by any profiles, check fails."""
caplog.set_level(logging.WARNING)
unknown_sysobjectid = '1.2.3.4.5'
init_config = {
'profiles': {
'profile1': {'definition': {'metrics': common.S... | 64,275 |
def train(net, dataloader, loss_fn, params, metrics, optimizer):
"""
Train the net for one epoch i.e 1..len(dataloader)
net: The model to test
params: The hyperparams
loss_fn: The loss function
metrics: The metrics dictionary containing evaluation metrics.
"""
net.train()
summarie... | 64,276 |
def async_register_services(hass: HomeAssistant) -> None:
"""Register services for Hue integration."""
async def hue_activate_scene(call: ServiceCall, skip_reload=True):
"""Handle activation of Hue scene."""
# Get parameters
group_name = call.data[ATTR_GROUP_NAME]
scene_name = c... | 64,277 |
def faceBlobSalientBasedOnAverageValue(value, salientLabelValue):
"""Deprecated"""
# the face is considered salient if 50% of pixels or more are marked salient
if value > (0.5 * salientLabelValue):
return True # bright green
# if the face is not salient:
else:
return False | 64,278 |
def download(url, force_download=False):
""" Downloads given URL and saves a local file"""
cur_dir = Path(__file__).absolute().parent
DATA_DIR = os.path.join(cur_dir, 'data')
if not os.path.exists(DATA_DIR):
print('[i] create following folder: {0}'.format(DATA_DIR))
os.makedirs(DATA_DIR... | 64,279 |
def test_mutate_binomial_dist():
"""When we apply binomial mutation repeatedly, the resulting distribution
of offspring should follow the expected theoretical distribution."""
N = 5000 # Number of mutantes to generate
binom_n = 10000 # "coin flips" parameter for the binomial
std = 2.5 # Standard... | 64,280 |
def find_field(child, field_name: str, tag_root: str) -> str:
""" Fetch specific fields of the child nodes of current the XML node.
Args:
child (object): child of node that may have field = field_name.
field_name (str): name of field of XML node.
tag_root (str): start of tag of each XML... | 64,281 |
def prepare_data(gt_2d_bdb=False, patch_h=224, patch_w=224, shift=True, iou_threshold=0.1):
"""
Generating the ground truth for end-to-end training
Parameters
----------
gt_2d_bdb : bool
indicates whether to use the ground truth of 2D bounding boxes
patch_h: int
... | 64,282 |
def rmse(predictions, targets):
""" RMSE function
Args:
predictions (1-d array of float): Predicted values.
targets (1-d array of float): Observed values.
"""
return np.sqrt(((predictions - targets) ** 2).mean()) | 64,283 |
def main():
"""minimal funcs testing"""
assert rot13('Some text here') == 'Fbzr grkg urer'
assert rot13('Some text here', 0) == 'Some text here'
assert rot13(rot13('Some text here', 5), -5) == 'Some text here'
assert rot13('Некий текст тут') == 'Ътчхц ятчюя яая'
assert rot13('Некий текст тут', 0... | 64,284 |
def base64_encode_nifti(image):
"""Returns base64 encoded string of the specified image.
Parameters
----------
image : nibabel.Nifti2Image
image to be encoded.
Returns
-------
str
base64 encoded string of the image.
"""
encoded_image = base64.encodebytes(image.to_by... | 64,285 |
def test_input():
"""test for input"""
for val in ['Universe', 'Multiverse']:
for option in ['-n', '--name']:
rv, out = getstatusoutput(f'{prg} {option} {val}')
assert rv == 0
assert out.strip() == f'Hello, {val}!' | 64,286 |
def get_token(auth_url, username, password):
"""
Authenticate user and return generated token
auth_url: Url to be used for BDSE
Username: Username for BDSE
Password: Password for the user
"""
buf = cStringIO.StringIO()
curl = pycurl.Curl()
curl.setopt(curl.UR... | 64,287 |
def compare_configs(fn1, fn2):
"""compare two ini files
"""
result = []
gen1 = sort_inifile(fn1)
gen2 = sort_inifile(fn2)
def gen_next(gen):
"generator to get next item from file"
eof = False
try:
sect, opt, val = next(gen)
except StopIter... | 64,288 |
def tf_build_varying_top_k_mask_4d_op(input_tensor, k_max, batch_size, h, w, input_area, ranking_mask):
"""Build varying top K mask."""
batch_h_w_size = batch_size * h * w
logging.debug('encoding shape = (%s, %s, %s, %s)',
batch_size, h, w, input_area)
# Find the "winners". The top k elements ... | 64,289 |
def pacman_mirrors():
"""Switch mirrors (for yaourt and pacman-based systems)"""
if shutil.which("pacman-mirrors"):
os.system("sudo pacman-mirrors -c Germany") | 64,290 |
def resolve_parameter_name(
parameter_name: str,
obs_date: datetime,
) -> Tuple[str, str, str]:
"""
Resolves a ``parameter_name`` into a dictionary that contains
information about which archive the parameter can be obtained
from, using which parameter_key.
Args:
parameter_name: Name... | 64,291 |
def draw_window_2(alex):
"""
This function draws patterns inside the square.
:param alex: a turtle object
:return: None
"""
alex.pensize(1)
alex.pu()
alex.setpos(-130,-40)
alex.lt(90)
alex.fillcolor("#B03060")
alex.begin_fill()
alex.fd(25)
alex.rt(90)
alex.fd(25)... | 64,292 |
def publish_dataset(prod_dir, dataset_file, job, ctx):
"""Publish a dataset. Track metrics."""
# get job info
job_dir = job["job_info"]["job_dir"]
time_start_iso = job["job_info"]["time_start"]
context_file = job["job_info"]["context_file"]
datasets_cfg_file = job["job_info"]["datasets_cfg_file... | 64,293 |
def calc_array_manifold_f(fbinX, fftlen, samplerate, delays, half_band_shift):
"""
Calculate one (conjugate) array manifold vector for each frequancy bin or subband.
"""
chan_num = len(delays)
Delta_f = samplerate / float(fftlen)
J = (0+1j)
fftlen2 = fftlen / 2
if half_band_shift:
... | 64,294 |
def get_network_interface(interface='default'):
"""
Returns the network interface which contains addr, broadcasts, and netmask elements
:param interface: The interface name to check, default grabs
"""
# Get the default gateway
gws = netifaces.gateways()
LOGGER.debug("gws: {}".format(gws))
... | 64,295 |
def build_g_suite_service(service, version, credentials):
"""
Builds a Google API Resource Client.
:param service: The service to get a client for.
:type service: str
:param version: The version of the service to get a client for.
:type version: str
:param credentials: The credentials used t... | 64,296 |
def _get_number_partitions_up_to_sum(ranked_numbers, sum_):
"""
Iterator over all possible partitions (with repetitions) of numbers that sum up to a target sum (larger numbers appear first).
Used by get_ranked_set_partitions.
(note that in the contect of planet matching, 1 is always in ranked_numbers - ... | 64,297 |
def resnet_v1_beta(inputs,
blocks,
num_classes=None,
is_training=None,
global_pool=True,
output_stride=None,
root_block_fn=None,
reuse=None,
scope=None):
"""Generator... | 64,298 |
def harvest_and_convert(genes):
""" get data from mm, convert it to ga4gh and return via yield """
for evidence in harvest(genes):
# print "harvester_yield {}".format(evidence.keys())
# print evidence
for feature_association in convert(evidence):
# print "mm convert_yield {}"... | 64,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.