Datasets:

function_name
stringlengths
1
63
docstring
stringlengths
50
5.89k
masked_code
stringlengths
50
882k
implementation
stringlengths
169
12.9k
start_line
int32
1
14.6k
end_line
int32
16
14.6k
file_content
stringlengths
274
882k
tns_close_short_pos
事务平空单仓位 1.来源自止损止盈平仓 2.来源自换仓 逻辑: 如果当前账号昨仓满足平仓数量,直接平仓,如果不满足,则创建锁仓网格. :param 平仓网格 :return:
"""""" import os import uuid import bz2 import pickle import traceback import zlib from abc import ABC from copy import copy,deepcopy from typing import Any, Callable from logging import INFO, ERROR from datetime import datetime from vnpy.trader.constant import Interval, Direction, Offset, Status, OrderType, Color, Ex...
def tns_close_short_pos(self, grid): """ 事务平空单仓位 1.来源自止损止盈平仓 2.来源自换仓 逻辑: 如果当前账号昨仓满足平仓数量,直接平仓,如果不满足,则创建锁仓网格. :param 平仓网格 :return: """ self.write_log(u'执行事务平空仓位:{}'.format(grid.to_json())) # 平仓网格得合约 cover_symbol = grid.snapshot.ge...
2,027
2,125
"""""" import os import uuid import bz2 import pickle import traceback import zlib from abc import ABC from copy import copy,deepcopy from typing import Any, Callable from logging import INFO, ERROR from datetime import datetime from vnpy.trader.constant import Interval, Direction, Offset, Status, OrderType, Color, Ex...
send_message
Sends message in bold mode/Enviar mensagem em negrito. :param chat_id: ID of Telegram account/ID da conta Telgram. :param text: Message/Mensagem. :param parse_mode: Ignore. :param token: ID Telegram bot/ID do bot Telegram.
#!/usr/bin/python import pathlib import requests import smtplib import logging import coloredlogs import verboselogs from etc.api.keys import * path_atual_tl = str(pathlib.Path(__file__).parent.absolute()) path_tl_final = path_atual_tl.replace('/etc/notification','') def logando_notification(tipo, mensagem): ...
def send_message(chat_id, text=None, parse_mode = 'Markdown', token=None): """ Sends message in bold mode/Enviar mensagem em negrito. :param chat_id: ID of Telegram account/ID da conta Telgram. :param text: Message/Mensagem. :param parse_mode: Ignore. :param token: ID Telegram bot/ID do bot Tel...
89
103
#!/usr/bin/python import pathlib import requests import smtplib import logging import coloredlogs import verboselogs from etc.api.keys import * path_atual_tl = str(pathlib.Path(__file__).parent.absolute()) path_tl_final = path_atual_tl.replace('/etc/notification','') def logando_notification(tipo, mensagem): ...
_cnn_net
Create the CNN net topology. :return keras.Sequential(): CNN topology.
#!/usr/bin/python # -*- encoding: utf-8 -*- """ @ide: PyCharm @author: Pedro Silva @contact: pedroh21.silva@gmail.com @created: out-10 of 2019 """ import os import numpy as np import tensorflow as tf import tensorflow.keras.backend as kback from tensorflow import keras class QRSNet(object): # MASKED: _cnn_net fun...
@classmethod def _cnn_net(cls): """ Create the CNN net topology. :return keras.Sequential(): CNN topology. """ qrs_detector = keras.Sequential() # CONV1 qrs_detector.add(keras.layers.Conv1D(96, 49, activation=tf.nn.relu, input_shape=(300, 1), strides=1, n...
21
70
#!/usr/bin/python # -*- encoding: utf-8 -*- """ @ide: PyCharm @author: Pedro Silva @contact: pedroh21.silva@gmail.com @created: out-10 of 2019 """ import os import numpy as np import tensorflow as tf import tensorflow.keras.backend as kback from tensorflow import keras class QRSNet(object): @classmethod d...
build
Build the CNN topology. :param str net_type: the network type, CNN or LSTM. :return keras.Sequential(): CNN topology.
#!/usr/bin/python # -*- encoding: utf-8 -*- """ @ide: PyCharm @author: Pedro Silva @contact: pedroh21.silva@gmail.com @created: out-10 of 2019 """ import os import numpy as np import tensorflow as tf import tensorflow.keras.backend as kback from tensorflow import keras class QRSNet(object): @classmethod d...
@classmethod def build(cls, net_type): """ Build the CNN topology. :param str net_type: the network type, CNN or LSTM. :return keras.Sequential(): CNN topology. """ if net_type == 'cnn': qrs_detector = cls._cnn_net() else: raise Not...
72
84
#!/usr/bin/python # -*- encoding: utf-8 -*- """ @ide: PyCharm @author: Pedro Silva @contact: pedroh21.silva@gmail.com @created: out-10 of 2019 """ import os import numpy as np import tensorflow as tf import tensorflow.keras.backend as kback from tensorflow import keras class QRSNet(object): @classmethod d...
_prepare_data
Prepare the data for the training, turning it into a numpy array. :param list data_x: data that will be used to train. :param tuple input_shape: the input shape that the data must have to be used as training data. :param list data_y: the labels related to the data used to train. :param int number_of_classes: number of ...
#!/usr/bin/python # -*- encoding: utf-8 -*- """ @ide: PyCharm @author: Pedro Silva @contact: pedroh21.silva@gmail.com @created: out-10 of 2019 """ import os import numpy as np import tensorflow as tf import tensorflow.keras.backend as kback from tensorflow import keras class QRSNet(object): @classmethod d...
@classmethod def _prepare_data(cls, data_x, input_shape, data_y, number_of_classes, normalize): """ Prepare the data for the training, turning it into a numpy array. :param list data_x: data that will be used to train. :param tuple input_shape: the input shape that the data must ...
86
107
#!/usr/bin/python # -*- encoding: utf-8 -*- """ @ide: PyCharm @author: Pedro Silva @contact: pedroh21.silva@gmail.com @created: out-10 of 2019 """ import os import numpy as np import tensorflow as tf import tensorflow.keras.backend as kback from tensorflow import keras class QRSNet(object): @classmethod d...
_convert_dataset_to_image_and_bboxes
@param dataset: [image_path, [[x, y, w, h, class_id], ...]] @return image, bboxes image: 0.0 ~ 1.0, Dim(1, height, width, channels)
""" MIT License Copyright (c) 2019 YangYun Copyright (c) 2020 Việt Hùng Copyright (c) 2020-2021 Hyeonki Hong <hhk7734@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restrictio...
def _convert_dataset_to_image_and_bboxes(self, dataset): """ @param dataset: [image_path, [[x, y, w, h, class_id], ...]] @return image, bboxes image: 0.0 ~ 1.0, Dim(1, height, width, channels) """ # pylint: disable=bare-except try: image = cv2...
121
142
""" MIT License Copyright (c) 2019 YangYun Copyright (c) 2020 Việt Hùng Copyright (c) 2020-2021 Hyeonki Hong <hhk7734@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restrictio...
setup_logging
Setup the logging device to log into a uniquely created directory. Args: name: Name of the directory for the log-files. dir: Optional sub-directory within log
# MIT License # Copyright (c) 2020 Simon Schug, João Sacramento # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, ...
def setup_logging(name, dir=""): """ Setup the logging device to log into a uniquely created directory. Args: name: Name of the directory for the log-files. dir: Optional sub-directory within log """ # Setup global log name and directory global log_name log_name = name ...
37
70
# MIT License # Copyright (c) 2020 Simon Schug, João Sacramento # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, ...
__init__
Initializes a observation in light dark domain. Args: position (tuple): position of the robot.
import pomdp_py class Observation(pomdp_py.Observation): """Defines the Observation for the continuous light-dark domain; Observation space: :math:`\Omega\subseteq\mathbb{R}^2` the observation of the robot is an estimate of the robot position :math:`g(x_t)\in\Omega`. """ # the n...
def __init__(self, position, discrete=False): """ Initializes a observation in light dark domain. Args: position (tuple): position of the robot. """ self._discrete = discrete if len(position) != 2: raise ValueError("Observation position must b...
15
29
import pomdp_py class Observation(pomdp_py.Observation): """Defines the Observation for the continuous light-dark domain; Observation space: :math:`\Omega\subseteq\mathbb{R}^2` the observation of the robot is an estimate of the robot position :math:`g(x_t)\in\Omega`. """ # the n...
_find_x12
If x12path is not given, then either x13as[.exe] or x12a[.exe] must be found on the PATH. Otherwise, the environmental variable X12PATH or X13PATH must be defined. If prefer_x13 is True, only X13PATH is searched for. If it is false, only X12PATH is searched for.
""" Run x12/x13-arima specs in a subprocess from Python and curry results back into python. Notes ----- Many of the functions are called x12. However, they are also intended to work for x13. If this is not the case, it's a bug. """ import os import subprocess import tempfile import re from warnings import warn import...
def _find_x12(x12path=None, prefer_x13=True): """ If x12path is not given, then either x13as[.exe] or x12a[.exe] must be found on the PATH. Otherwise, the environmental variable X12PATH or X13PATH must be defined. If prefer_x13 is True, only X13PATH is searched for. If it is false, only X12PATH is s...
46
79
""" Run x12/x13-arima specs in a subprocess from Python and curry results back into python. Notes ----- Many of the functions are called x12. However, they are also intended to work for x13. If this is not the case, it's a bug. """ import os import subprocess import tempfile import re from warnings import warn import...
corpus_reader
Lê as extensões dos arquivos .xml no caminho especificado como path e retorna uma tupla com duas listas.Uma lista contém os paths para os arquivos .xml e a outra contém os arquivos Document gerados para aquele arquilo .xml
# -*- coding: utf-8 -*- """ Criado por Lucas Fonseca Lage em 04/03/2020 """ import re, os, spacy import numpy as np from my_wsd import my_lesk from unicodedata import normalize from document import Document from gensim.models import Phrases # Carregamento do modelo Spacy nlp = spacy.load('pt_core_news_lg') # Carrega...
def corpus_reader(path): '''Lê as extensões dos arquivos .xml no caminho especificado como path e retorna uma tupla com duas listas.Uma lista contém os paths para os arquivos .xml e a outra contém os arquivos Document gerados para aquele arquilo .xml ''' prog = re.compile('(\.xml)$') doc_list = ...
31
49
# -*- coding: utf-8 -*- """ Criado por Lucas Fonseca Lage em 04/03/2020 """ import re, os, spacy import numpy as np from my_wsd import my_lesk from unicodedata import normalize from document import Document from gensim.models import Phrases # Carregamento do modelo Spacy nlp = spacy.load('pt_core_news_lg') # Carrega...
corpus_yeeter
Similar ao corpus_reader. Recebe um caminho para a pasta contendo o corpus e cria um generator. Cada iteração retorna uma tupla contendo um caminho para o arquivo .xml e o objeto Document criado a partir do mesmo
# -*- coding: utf-8 -*- """ Criado por Lucas Fonseca Lage em 04/03/2020 """ import re, os, spacy import numpy as np from my_wsd import my_lesk from unicodedata import normalize from document import Document from gensim.models import Phrases # Carregamento do modelo Spacy nlp = spacy.load('pt_core_news_lg') # Carrega...
def corpus_yeeter(path): '''Similar ao corpus_reader. Recebe um caminho para a pasta contendo o corpus e cria um generator. Cada iteração retorna uma tupla contendo um caminho para o arquivo .xml e o objeto Document criado a partir do mesmo ''' prog = re.compile('(\.xml)$') for dirpath, dirname...
51
61
# -*- coding: utf-8 -*- """ Criado por Lucas Fonseca Lage em 04/03/2020 """ import re, os, spacy import numpy as np from my_wsd import my_lesk from unicodedata import normalize from document import Document from gensim.models import Phrases # Carregamento do modelo Spacy nlp = spacy.load('pt_core_news_lg') # Carrega...
subj_n_elements
Recebe a lista de sentenças da redação. Conta a quantidade de elementos abaixo do sujeito na árvore sintática gerada pelo "dependecy parser" do Spacy. Retorna o número de sujeitos que possuem uma quantidade de elementos maior que 7 e também o número total de elementos que fazem parte de um sujeito em toda a redação.
# -*- coding: utf-8 -*- """ Criado por Lucas Fonseca Lage em 04/03/2020 """ import re, os, spacy import numpy as np from my_wsd import my_lesk from unicodedata import normalize from document import Document from gensim.models import Phrases # Carregamento do modelo Spacy nlp = spacy.load('pt_core_news_lg') # Carrega...
def subj_n_elements(sentence_list): ''' Recebe a lista de sentenças da redação. Conta a quantidade de elementos abaixo do sujeito na árvore sintática gerada pelo "dependecy parser" do Spacy. Retorna o número de sujeitos que possuem uma quantidade de elementos maior que 7 e também o número total de eleme...
157
175
# -*- coding: utf-8 -*- """ Criado por Lucas Fonseca Lage em 04/03/2020 """ import re, os, spacy import numpy as np from my_wsd import my_lesk from unicodedata import normalize from document import Document from gensim.models import Phrases # Carregamento do modelo Spacy nlp = spacy.load('pt_core_news_lg') # Carrega...
__init__
Initialize the DnsEntry object. Closely represent the TransIP dnsEntry object :param content: content (rdata) corresponding to the record type (e.g. ip), defaults to None :type content: str, optional :param expire: Time To Live (TTL) of the record, defaults to None :type expire: int, optional :param n...
# MIT License, Copyright (c) 2020 Bob van den Heuvel # https://github.com/bheuvel/transip/blob/main/LICENSE """Interface with the TransIP API, specifically DNS record management.""" import logging from enum import Enum from pathlib import Path from time import sleep from typing import Dict, Union import requests from...
def __init__( self, content: str = None, expire: int = None, name: str = None, rtype: str = None, ): """Initialize the DnsEntry object. Closely represent the TransIP dnsEntry object :param content: content (rdata) corresponding to the record type...
23
49
# MIT License, Copyright (c) 2020 Bob van den Heuvel # https://github.com/bheuvel/transip/blob/main/LICENSE """Interface with the TransIP API, specifically DNS record management.""" import logging from enum import Enum from pathlib import Path from time import sleep from typing import Dict, Union import requests from...
extract_valid_cpu_usage_data
This method it to extract the valid cpu usage data according to the poll_interval 1. Find the index for the max one for every poll interval, 2. Discard the data if the index is on the edge(0 o the length of program_to_check_cpu_usage -1) 3. If the index is closed in the neighbour interval, only keep the former one 4. R...
import logging import pytest from collections import namedtuple, Counter from tests.platform_tests.counterpoll.cpu_memory_helper import restore_counter_poll # lgtm [py/unused-import] from tests.platform_tests.counterpoll.cpu_memory_helper import counterpoll_type # lgtm [py/unused-import] from tests.platform_test...
def extract_valid_cpu_usage_data(program_to_check_cpu_usage, poll_interval): """ This method it to extract the valid cpu usage data according to the poll_interval 1. Find the index for the max one for every poll interval, 2. Discard the data if the index is on the edge(0 o the length of program_to_check...
156
192
import logging import pytest from collections import namedtuple, Counter from tests.platform_tests.counterpoll.cpu_memory_helper import restore_counter_poll # lgtm [py/unused-import] from tests.platform_tests.counterpoll.cpu_memory_helper import counterpoll_type # lgtm [py/unused-import] from tests.platform_test...
reset_module
reset all local vars Args: None Returns: None
# blender imports import bpy # utility imports import numpy as np import csv import random import importlib from src.TSSBase import TSSBase class TSSMeshHandle(TSSBase): """docstring for TSSMeshHandle""" def __init__(self): super(TSSMeshHandle, self).__init__() # class vars ##################...
def reset_module(self): """ reset all local vars Args: None Returns: None """ # reset all mesh ############################################################################################ for mesh in self._mesh_obj_list: # reset me...
22
41
# blender imports import bpy # utility imports import numpy as np import csv import random import importlib from src.TSSBase import TSSBase class TSSMeshHandle(TSSBase): """docstring for TSSMeshHandle""" def __init__(self): super(TSSMeshHandle, self).__init__() # class vars ##################...
_create_meshes
create function Args: cfg: list of mesh cfgs [list] general_cfg: general cfg [dict] stage_dict: dict of stages [dict] Returns: success code [boolean]
# blender imports import bpy # utility imports import numpy as np import csv import random import importlib from src.TSSBase import TSSBase class TSSMeshHandle(TSSBase): """docstring for TSSMeshHandle""" def __init__(self): super(TSSMeshHandle, self).__init__() # class vars ##################...
def _create_meshes(self,cfg,general_cfg,stage_dict): """ create function Args: cfg: list of mesh cfgs [list] general_cfg: general cfg [dict] stage_dict: dict of stages [dict] Returns: success code [boolean] """ ...
71
122
# blender imports import bpy # utility imports import numpy as np import csv import random import importlib from src.TSSBase import TSSBase class TSSMeshHandle(TSSBase): """docstring for TSSMeshHandle""" def __init__(self): super(TSSMeshHandle, self).__init__() # class vars ##################...
_set_voldb_empty_at_startup_indicator
Determine if the Cinder volume DB is empty. A check of the volume DB is done to determine whether it is empty or not at this point. :param ctxt: our working context
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a ...
def _set_voldb_empty_at_startup_indicator(self, ctxt): """Determine if the Cinder volume DB is empty. A check of the volume DB is done to determine whether it is empty or not at this point. :param ctxt: our working context """ vol_entries = self.db.volume_get_all(ct...
362
377
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a ...
freeze_host
Freeze management plane on this backend. Basically puts the control/management plane into a Read Only state. We should handle this in the scheduler, however this is provided to let the driver know in case it needs/wants to do something specific on the backend. :param context: security context
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a ...
def freeze_host(self, context): """Freeze management plane on this backend. Basically puts the control/management plane into a Read Only state. We should handle this in the scheduler, however this is provided to let the driver know in case it needs/wants to do something spe...
3,325
3,357
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a ...
thaw_host
UnFreeze management plane on this backend. Basically puts the control/management plane back into a normal state. We should handle this in the scheduler, however this is provided to let the driver know in case it needs/wants to do something specific on the backend. :param context: security context
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a ...
def thaw_host(self, context): """UnFreeze management plane on this backend. Basically puts the control/management plane back into a normal state. We should handle this in the scheduler, however this is provided to let the driver know in case it needs/wants to do something s...
3,359
3,390
# Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a ...
__reduce__
Provide pickling support. Normally, this just dispatches to Python's standard handling. However, for models with deferred field loading, we need to do things manually, as they're dynamically created classes and only module-level classes can be pickled by the default path.
# -*- coding: utf-8 -*- from datetime import date import json from operator import itemgetter import os import warnings from django.core.urlresolvers import NoReverseMatch from django.core.exceptions import ValidationError, ObjectDoesNotExist from django.db import models from django.db.models import signals, Model fro...
def __reduce__(self): """ Provide pickling support. Normally, this just dispatches to Python's standard handling. However, for models with deferred field loading, we need to do things manually, as they're dynamically created classes and only module-level classes can be pickle...
94
111
# -*- coding: utf-8 -*- from datetime import date import json from operator import itemgetter import os import warnings from django.core.urlresolvers import NoReverseMatch from django.core.exceptions import ValidationError, ObjectDoesNotExist from django.db import models from django.db.models import signals, Model fro...
generate_mesh
Launch Mesh Generator to generate mesh. @param meshing_dir: the meshing directory @param params: the meshing parameters @return: the mesh generation log content @raise TypeError: if any input parameter is not of required type @raise ValueError: if any input parameter is None/empty, or any field of MeshingParameters is...
# -*- coding: utf-8 -*- """ This Python module provides various service functions. Updated since version 1.1: 1. Added support for postprocess and visualization. 2. Added file path validation for parameters of all related methods. Updated since version 1.2: Merge Code and Update GUI 1. Integrate New Nemoh...
def generate_mesh(meshing_dir, params): ''' Launch Mesh Generator to generate mesh. @param meshing_dir: the meshing directory @param params: the meshing parameters @return: the mesh generation log content @raise TypeError: if any input parameter is not of required type @raise ValueError: if...
81
132
# -*- coding: utf-8 -*- """ This Python module provides various service functions. Updated since version 1.1: 1. Added support for postprocess and visualization. 2. Added file path validation for parameters of all related methods. Updated since version 1.2: Merge Code and Update GUI 1. Integrate ...
simulate
Run simulation. @param simulation_dir: the simulation directory @param params: the simulation parameters @return: the simulation log content @raise TypeError: if any input parameter is not of required type @raise ValueError: if any input parameter is None/empty, or any field of SimulationParameters is not ...
# -*- coding: utf-8 -*- """ This Python module provides various service functions. Updated since version 1.1: 1. Added support for postprocess and visualization. 2. Added file path validation for parameters of all related methods. Updated since version 1.2: Merge Code and Update GUI 1. Integrate New Nemoh...
def simulate(simulation_dir, params): ''' Run simulation. @param simulation_dir: the simulation directory @param params: the simulation parameters @return: the simulation log content @raise TypeError: if any input parameter is not of required type @raise ValueError: if any input parameter i...
134
242
# -*- coding: utf-8 -*- """ This Python module provides various service functions. Updated since version 1.1: 1. Added support for postprocess and visualization. 2. Added file path validation for parameters of all related methods. Updated since version 1.2: Merge Code and Update GUI 1. Integrate ...
postprocess
Run post-processing. @param simulation_dir: the simulation directory @param params: the post-processing parameters @return: the post-processing log content @raise TypeError: if any input parameter is not of required type @raise ValueError: if any input parameter is None/empty, or any field of PostprocessingParameters ...
# -*- coding: utf-8 -*- """ This Python module provides various service functions. Updated since version 1.1: 1. Added support for postprocess and visualization. 2. Added file path validation for parameters of all related methods. Updated since version 1.2: Merge Code and Update GUI 1. Integrate New Nemoh...
def postprocess(simulation_dir, params): ''' Run post-processing. @param simulation_dir: the simulation directory @param params: the post-processing parameters @return: the post-processing log content @raise TypeError: if any input parameter is not of required type @raise ValueError: if any...
244
315
# -*- coding: utf-8 -*- """ This Python module provides various service functions. Updated since version 1.1: 1. Added support for postprocess and visualization. 2. Added file path validation for parameters of all related methods. Updated since version 1.2: Merge Code and Update GUI 1. Integrate ...
run_thread
Run a python function in a thread and wait for it to complete. Redirect its output to fd Args: func: A python function to run args: A tuple containing argument for the function fd: a file descriptor
# -*- coding: utf-8 -*- """ This Python module provides various service functions. Updated since version 1.1: 1. Added support for postprocess and visualization. 2. Added file path validation for parameters of all related methods. Updated since version 1.2: Merge Code and Update GUI 1. Integrate New Nemoh...
def run_thread(func, args, fd): """ Run a python function in a thread and wait for it to complete. Redirect its output to fd Args: func: A python function to run args: A tuple containing argument for the function fd: a file descriptor """ manager = Manager() return_d...
470
487
# -*- coding: utf-8 -*- """ This Python module provides various service functions. Updated since version 1.1: 1. Added support for postprocess and visualization. 2. Added file path validation for parameters of all related methods. Updated since version 1.2: Merge Code and Update GUI 1. Integrate ...
__enter__
Enter the context Args: self: The class itself
# -*- coding: utf-8 -*- """ This Python module provides various service functions. Updated since version 1.1: 1. Added support for postprocess and visualization. 2. Added file path validation for parameters of all related methods. Updated since version 1.2: Merge Code and Update GUI 1. Integrate New Nemoh...
def __enter__(self): """ Enter the context Args: self: The class itself """ import sys self.sys = sys # save previous stdout/stderr self.saved_streams = saved_streams = sys.__stdout__, sys.__stderr__ self.fds = fds = [s.fileno() for...
403
429
# -*- coding: utf-8 -*- """ This Python module provides various service functions. Updated since version 1.1: 1. Added support for postprocess and visualization. 2. Added file path validation for parameters of all related methods. Updated since version 1.2: Merge Code and Update GUI 1. Integrate ...
__exit__
Exit the context Args: self: The class itself args: other arguments
# -*- coding: utf-8 -*- """ This Python module provides various service functions. Updated since version 1.1: 1. Added support for postprocess and visualization. 2. Added file path validation for parameters of all related methods. Updated since version 1.2: Merge Code and Update GUI 1. Integrate New Nemoh...
def __exit__(self, *args): """ Exit the context Args: self: The class itself args: other arguments """ sys = self.sys # flush any pending output for s in self.saved_streams: s.flush() # restore original streams and file descript...
431
447
# -*- coding: utf-8 -*- """ This Python module provides various service functions. Updated since version 1.1: 1. Added support for postprocess and visualization. 2. Added file path validation for parameters of all related methods. Updated since version 1.2: Merge Code and Update GUI 1. Integrate ...
cutouts
Custom version to extract stars cutouts Parameters ---------- Parameters ---------- image: np.ndarray or path stars: np.ndarray stars positions with shape (n,2) size: int size of the cuts around stars (in pixels), by default 15 Returns ------- np.ndarray of shape (size, size)
from scipy.optimize import minimize import warnings import numpy as np from astropy.io import fits from astropy.table import Table from astropy.nddata import NDData from photutils.psf import extract_stars from astropy.stats import gaussian_sigma_to_fwhm from ..core import Block import matplotlib.pyplot as plt from coll...
def cutouts(image, stars, size=15): """Custom version to extract stars cutouts Parameters ---------- Parameters ---------- image: np.ndarray or path stars: np.ndarray stars positions with shape (n,2) size: int size of the cuts around stars (in pixels), by default 15 ...
43
77
from scipy.optimize import minimize import warnings import numpy as np from astropy.io import fits from astropy.table import Table from astropy.nddata import NDData from photutils.psf import extract_stars from astropy.stats import gaussian_sigma_to_fwhm from ..core import Block import matplotlib.pyplot as plt from coll...
_parse_github_path
Parse the absolute github path. Args: path: The full github path. Returns: repo: The repository identifiant. branch: Repository branch. subpath: The inner path. Raises: ValueError: If the path is invalid
# coding=utf-8 # Copyright 2021 The TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
def _parse_github_path(path: str) -> Tuple[str, str, str]: """Parse the absolute github path. Args: path: The full github path. Returns: repo: The repository identifiant. branch: Repository branch. subpath: The inner path. Raises: ValueError: If the path is invalid """ err_msg = (f'In...
328
358
# coding=utf-8 # Copyright 2021 The TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
copy
Copy the current file to the given destination. Args: dst: Target file. It can be any PathLike compatible path (e.g. `gs://...`) overwrite: Whether the file should be overwritten or not Returns: The new created file. Raises: FileExistsError: If `overwrite` is false and destination exists.
# coding=utf-8 # Copyright 2021 The TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
def copy( self, dst: utils.PathLike, overwrite: bool = False, ) -> utils.ReadWritePath: """Copy the current file to the given destination. Args: dst: Target file. It can be any PathLike compatible path (e.g. `gs://...`) overwrite: Whether the file should be overwritten or not ...
303
325
# coding=utf-8 # Copyright 2021 The TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
commandstats
Shows command stats. Use a negative number for bottom instead of top. This is only for the current session.
from discord.ext import commands, tasks from collections import Counter, defaultdict from .utils import checks, db, time, formats from .utils.paginator import CannotPaginate import pkg_resources import logging import discord import textwrap import datetime import traceback import itertools import typing import asyncp...
@commands.command(hidden=True) @commands.is_owner() async def commandstats(self, ctx, limit=20): """Shows command stats. Use a negative number for bottom instead of top. This is only for the current session. """ counter = self.bot.command_stats width = len(ma...
181
200
from discord.ext import commands, tasks from collections import Counter, defaultdict from .utils import checks, db, time, formats from .utils.paginator import CannotPaginate import pkg_resources import logging import discord import textwrap import datetime import traceback import itertools import typing import asyncp...
prepare
Create a 1-node cluster, start it, create a keyspace, and if <table_name>, create a table in that keyspace. If <cdc_enabled_table>, that table is created with CDC enabled. If <column_spec>, use that string to specify the schema of the table -- for example, a valid value is 'a int PRIMARY KEY, b int'. The <configuration...
from __future__ import division import errno import os import re import shutil import time import uuid from collections import namedtuple from itertools import repeat from pprint import pformat import pytest from cassandra import WriteFailure from cassandra.concurrent import (execute_concurrent, ...
def prepare(self, ks_name, table_name=None, cdc_enabled_table=None, gc_grace_seconds=None, column_spec=None, configuration_overrides=None, table_id=None): """ Create a 1-node cluster, start it, create a keyspace, and if ...
244
290
from __future__ import division import errno import os import re import shutil import time import uuid from collections import namedtuple from itertools import repeat from pprint import pformat import pytest from cassandra import WriteFailure from cassandra.concurrent import (execute_concurrent, ...
create_group
Create new group in account. :param api: api fixture :param account: account fixture :yields: create_group function
"""Account, user fixtures.""" import json import logging from time import monotonic, sleep from typing import List, NamedTuple, Optional, Tuple import pytest from box import Box from dynaconf import settings from ambra_sdk.exceptions.service import DuplicateName, NotEmpty from ambra_sdk.models import Group from ambr...
@pytest.fixture def create_group(api, account): """Create new group in account. :param api: api fixture :param account: account fixture :yields: create_group function """ groups = [] group_counter = 0 def _create_group(name: Optional[str] = None): nonlocal group_counter ...
310
348
"""Account, user fixtures.""" import json import logging from time import monotonic, sleep from typing import List, NamedTuple, Optional, Tuple import pytest from box import Box from dynaconf import settings from ambra_sdk.exceptions.service import DuplicateName, NotEmpty from ambra_sdk.models import Group from ambr...
encode
Encodes the CID using a given multibase. If :obj:`None` is given, the CID's own multibase is used by default. Example usage: >>> s = "zb2rhe5P4gXftAwvA4eXQ5HJwsER2owDyS9sKaQRRVQPn93bA" >>> cid = CID.decode(s) >>> cid.encode() # default: cid.base 'zb2rhe5P4gXftAwvA4eXQ5HJwsER2owDyS9sKaQRRVQPn93bA' >>> cid.encode("base...
""" Implementation of the `CID spec <https://github.com/multiformats/cid>`_. This module differs from other modules of :mod:`~multiformats`, in that the functionality is completely encapsulated by a single class :class:`CID`, which is imported from top level instead of the module itself: >>> from ...
def encode(self, base: Union[None, str, Multibase] = None) -> str: """ Encodes the CID using a given multibase. If :obj:`None` is given, the CID's own multibase is used by default. Example usage: >>> s = "zb2rhe5P4gXftAwvA4eXQ5HJwsER2owDyS9sKaQRRVQPn93bA" ...
346
377
""" Implementation of the `CID spec <https://github.com/multiformats/cid>`_. This module differs from other modules of :mod:`~multiformats`, in that the functionality is completely encapsulated by a single class :class:`CID`, which is imported from top level instead of the module itself: >>> from ...
set
Returns a new CID obtained by setting new values for one or more of: ``base``, ``version``, or ``codec``. Example usage: >>> s = "zb2rhe5P4gXftAwvA4eXQ5HJwsER2owDyS9sKaQRRVQPn93bA" >>> cid = CID.decode(s) >>> cid CID('base58btc', 1, 'raw', '12206e6ff7950a36187a801613426e858dce686cd7d7e3c0fc42ee0330072d245c95') >>> ci...
""" Implementation of the `CID spec <https://github.com/multiformats/cid>`_. This module differs from other modules of :mod:`~multiformats`, in that the functionality is completely encapsulated by a single class :class:`CID`, which is imported from top level instead of the module itself: >>> from ...
def set(self, *, base: Union[None, str, Multibase] = None, version: Union[None, int] = None, codec: Union[None, str, int, Multicodec] = None ) -> "CID": """ Returns a new CID obtained by setting new values for one or more of: ``base``, `...
379
449
""" Implementation of the `CID spec <https://github.com/multiformats/cid>`_. This module differs from other modules of :mod:`~multiformats`, in that the functionality is completely encapsulated by a single class :class:`CID`, which is imported from top level instead of the module itself: >>> from ...
onerror
Error handler for ``shutil.rmtree``. If the error is due to an access error (read only file) it attempts to add write permission and then retries. If the error is for another reason it re-raises the error. Usage : ``shutil.rmtree(path, onerror=onerror)``
import os import shutil from thlib.side.Qt import QtWidgets as QtGui from thlib.side.Qt import QtGui as Qt4Gui from thlib.side.Qt import QtCore from thlib.environment import env_inst, env_tactic, cfg_controls, env_read_config, env_write_config, dl import thlib.global_functions as gf import thlib.tactic_classes as tc fr...
def onerror(func, path, exc_info): """ Error handler for ``shutil.rmtree``. If the error is due to an access error (read only file) it attempts to add write permission and then retries. If the error is for another reason it re-raises the error. ...
317
332
import os import shutil from thlib.side.Qt import QtWidgets as QtGui from thlib.side.Qt import QtGui as Qt4Gui from thlib.side.Qt import QtCore from thlib.environment import env_inst, env_tactic, cfg_controls, env_read_config, env_write_config, dl import thlib.global_functions as gf import thlib.tactic_classes as tc fr...
pressure
Calculate pressure at specified loading. For the TemkinApprox model, the pressure will be computed numerically as no analytical inversion is possible. Parameters ---------- loading : float The loading at which to calculate the pressure. Returns ------- float Pressure at specified loading.
"""Temkin Approximation isotherm model.""" import numpy import scipy from ..utilities.exceptions import CalculationError from .base_model import IsothermBaseModel class TemkinApprox(IsothermBaseModel): r""" Asymptotic approximation to the Temkin isotherm. .. math:: n(p) = n_m \frac{K p}{1 + K ...
def pressure(self, loading): """ Calculate pressure at specified loading. For the TemkinApprox model, the pressure will be computed numerically as no analytical inversion is possible. Parameters ---------- loading : float The loading at which to ...
72
99
"""Temkin Approximation isotherm model.""" import numpy import scipy from ..utilities.exceptions import CalculationError from .base_model import IsothermBaseModel class TemkinApprox(IsothermBaseModel): r""" Asymptotic approximation to the Temkin isotherm. .. math:: n(p) = n_m \frac{K p}{1 + K ...
initial_guess
Return initial guess for fitting. Parameters ---------- pressure : ndarray Pressure data. loading : ndarray Loading data. Returns ------- dict Dictionary of initial guesses for the parameters.
"""Temkin Approximation isotherm model.""" import numpy import scipy from ..utilities.exceptions import CalculationError from .base_model import IsothermBaseModel class TemkinApprox(IsothermBaseModel): r""" Asymptotic approximation to the Temkin isotherm. .. math:: n(p) = n_m \frac{K p}{1 + K ...
def initial_guess(self, pressure, loading): """ Return initial guess for fitting. Parameters ---------- pressure : ndarray Pressure data. loading : ndarray Loading data. Returns ------- dict Dictionary of i...
133
159
"""Temkin Approximation isotherm model.""" import numpy import scipy from ..utilities.exceptions import CalculationError from .base_model import IsothermBaseModel class TemkinApprox(IsothermBaseModel): r""" Asymptotic approximation to the Temkin isotherm. .. math:: n(p) = n_m \frac{K p}{1 + K ...
collect_potential_dependencies
Collect all potential dependencies of a job. These might contain ambiguities. The keys of the returned dict represent the files to be considered.
__author__ = "Johannes Köster" __copyright__ = "Copyright 2015-2019, Johannes Köster" __email__ = "koester@jimmy.harvard.edu" __license__ = "MIT" import html import os import shutil import textwrap import time import tarfile from collections import defaultdict, Counter from itertools import chain, filterfalse, groupby...
def collect_potential_dependencies(self, job): """Collect all potential dependencies of a job. These might contain ambiguities. The keys of the returned dict represent the files to be considered.""" dependencies = defaultdict(list) # use a set to circumvent multiple jobs for the same...
1,423
1,458
__author__ = "Johannes Köster" __copyright__ = "Copyright 2015-2019, Johannes Köster" __email__ = "koester@jimmy.harvard.edu" __license__ = "MIT" import html import os import shutil import textwrap import time import tarfile from collections import defaultdict, Counter from itertools import chain, filterfalse, groupby...
archive
Archives workflow such that it can be re-run on a different system. Archiving includes git versioned files (i.e. Snakefiles, config files, ...), ancestral input files and conda environments.
__author__ = "Johannes Köster" __copyright__ = "Copyright 2015-2019, Johannes Köster" __email__ = "koester@jimmy.harvard.edu" __license__ = "MIT" import html import os import shutil import textwrap import time import tarfile from collections import defaultdict, Counter from itertools import chain, filterfalse, groupby...
def archive(self, path): """Archives workflow such that it can be re-run on a different system. Archiving includes git versioned files (i.e. Snakefiles, config files, ...), ancestral input files and conda environments. """ if path.endswith(".tar"): mode = "x" ...
1,856
1,926
__author__ = "Johannes Köster" __copyright__ = "Copyright 2015-2019, Johannes Köster" __email__ = "koester@jimmy.harvard.edu" __license__ = "MIT" import html import os import shutil import textwrap import time import tarfile from collections import defaultdict, Counter from itertools import chain, filterfalse, groupby...
_min_norm_2d
Find the minimum norm solution as combination of two points This is correct only in 2D ie. min_c |\sum c_i x_i|_2^2 st. \sum c_i = 1 , 1 >= c_1 >= 0 for all i, c_i + c_j = 1.0 for some i, j
# Credits to Ozan Sener # https://github.com/intel-isl/MultiObjectiveOptimization import numpy as np import torch class MGDASolver: MAX_ITER = 250 STOP_CRIT = 1e-5 @staticmethod def _min_norm_element_from2(v1v1, v1v2, v2v2): """ Analytical solution for min_{c} |cx_1 + (1-c)x_2|_2^2 ...
@staticmethod def _min_norm_2d(vecs: list, dps): """ Find the minimum norm solution as combination of two points This is correct only in 2D ie. min_c |\sum c_i x_i|_2^2 st. \sum c_i = 1 , 1 >= c_1 >= 0 for all i, c_i + c_j = 1.0 for some i, j """ dmin = 1e...
36
70
# Credits to Ozan Sener # https://github.com/intel-isl/MultiObjectiveOptimization import numpy as np import torch class MGDASolver: MAX_ITER = 250 STOP_CRIT = 1e-5 @staticmethod def _min_norm_element_from2(v1v1, v1v2, v2v2): """ Analytical solution for min_{c} |cx_1 + (1-c)x_2|_2^2 ...
refresh
Refresh materialized views. First, this method finds the namespaces being replicated, by referring to the config for schemas and tables. Then it finds any materialized views in the namespaces. Then it refreshes the materialized views.
"""This module contains logic for refreshing materialized views. Materialized views don't get refreshed automatically after a bucardo initial sync. This module detects them and refreshes them. Classes exported: MatViews: Identify materialized views and refresh them on the secondary database. """ import psycopg2 from...
def refresh(self): """Refresh materialized views. First, this method finds the namespaces being replicated, by referring to the config for schemas and tables. Then it finds any materialized views in the namespaces. Then it refreshes the materialized views. """ ...
41
73
"""This module contains logic for refreshing materialized views. Materialized views don't get refreshed automatically after a bucardo initial sync. This module detects them and refreshes them. Classes exported: MatViews: Identify materialized views and refresh them on the secondary database. """ import psycopg2 from...
get_scattering_phase_function
Return the scattering phase function in function of wavelength for the corresponding dust type (SMC or MW). The scattering phase function gives the angle at which the photon scatters. Parameters ---------- x: float expects either x in units of wavelengths or frequency or assumes wavelengths in [micron] inter...
# -*- coding: utf-8 -*- import numpy as np import astropy.units as u import pkg_resources from astropy.io import ascii from astropy.modeling.tabular import tabular_model from .baseclasses import BaseAtttauVModel from .helpers import _test_valid_x_range __all__ = ["WG00"] x_range_WG00 = [0.1, 3.0001] class WG00(...
def get_scattering_phase_function(self, x): """ Return the scattering phase function in function of wavelength for the corresponding dust type (SMC or MW). The scattering phase function gives the angle at which the photon scatters. Parameters ---------- x: fl...
619
735
# -*- coding: utf-8 -*- import numpy as np import astropy.units as u import pkg_resources from astropy.io import ascii from astropy.modeling.tabular import tabular_model from .baseclasses import BaseAtttauVModel from .helpers import _test_valid_x_range __all__ = ["WG00"] x_range_WG00 = [0.1, 3.0001] class WG00(...
load_raster_tile_lookup
Load in the preprocessed raster tile lookup. Parameters ---------- iso3 : string Country iso3 code. Returns ------- lookup : dict A lookup table containing raster tile boundary coordinates as the keys, and the file paths as the values.
""" Extract CLOS / NLOS lookup. Written by Ed Oughton. March 2021 """ import os import configparser import json import math import glob import random import numpy as np import pandas as pd import geopandas as gpd import pyproj from shapely.geometry import Point, Polygon, box, LineString from shapely.ops import trans...
def load_raster_tile_lookup(iso3): """ Load in the preprocessed raster tile lookup. Parameters ---------- iso3 : string Country iso3 code. Returns ------- lookup : dict A lookup table containing raster tile boundary coordinates as the keys, and the file paths as...
44
72
""" Extract CLOS / NLOS lookup. Written by Ed Oughton. March 2021 """ import os import configparser import json import math import glob import random import numpy as np import pandas as pd import geopandas as gpd import pyproj from shapely.geometry import Point, Polygon, box, LineString from shapely.ops import trans...
find_tile
Parameters ---------- polygon : tuple The bounds of the modeling region. tile_lookup : dict A lookup table containing raster tile boundary coordinates as the keys, and the file paths as the values. Return ------ output : list Contains the file path to the correct raster tile. Note: only the first e...
""" Extract CLOS / NLOS lookup. Written by Ed Oughton. March 2021 """ import os import configparser import json import math import glob import random import numpy as np import pandas as pd import geopandas as gpd import pyproj from shapely.geometry import Point, Polygon, box, LineString from shapely.ops import trans...
def find_tile(polygon, tile_lookup): """ Parameters ---------- polygon : tuple The bounds of the modeling region. tile_lookup : dict A lookup table containing raster tile boundary coordinates as the keys, and the file paths as the values. Return ------ output : ...
132
168
""" Extract CLOS / NLOS lookup. Written by Ed Oughton. March 2021 """ import os import configparser import json import math import glob import random import numpy as np import pandas as pd import geopandas as gpd import pyproj from shapely.geometry import Point, Polygon, box, LineString from shapely.ops import trans...
test_jlock_init_and_delete
Tests initialization and deleting a ``JLock``. Args: self (TestJLock): the ``TestJLock`` instance Returns: ``None``
# Copyright 2017 Square, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,...
@mock.patch('tempfile.tempdir', new='tmp') def test_jlock_init_and_delete(self): """Tests initialization and deleting a ``JLock``. Args: self (TestJLock): the ``TestJLock`` instance Returns: ``None`` """ serial_no = 0xdeadbeef lock = jlock.J...
54
69
# Copyright 2017 Square, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,...
test_jlock_acquire_exists
Tests trying to acquire when the lock exists for an active process. Args: self (TestJLock): the ``TestJLock`` instance mock_open (Mock): mocked built-in open method mock_util (Mock): mocked ``psutil`` module mock_rm (Mock): mocked os remove method mock_wr (Mock): mocked os write method mock_op (Mock): mock...
# Copyright 2017 Square, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,...
@mock.patch('tempfile.tempdir', new='tmp') @mock.patch('os.close') @mock.patch('os.path.exists') @mock.patch('os.open') @mock.patch('os.write') @mock.patch('os.remove') @mock.patch('pylink.jlock.psutil') @mock.patch('pylink.jlock.open') def test_jlock_acquire_exists(self, mock_open, ...
71
117
# Copyright 2017 Square, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,...
test_jlock_acquire_os_error
Tests trying to acquire the lock but generating an os-level error. Args: self (TestJLock): the ``TestJLock`` instance mock_open (Mock): mocked built-in open method mock_util (Mock): mocked ``psutil`` module mock_rm (Mock): mocked os remove method mock_wr (Mock): mocked os write method mock_op (Mock): mocke...
# Copyright 2017 Square, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,...
@mock.patch('tempfile.tempdir', new='tmp') @mock.patch('os.close') @mock.patch('os.path.exists') @mock.patch('os.open') @mock.patch('os.write') @mock.patch('os.remove') @mock.patch('pylink.jlock.psutil') @mock.patch('pylink.jlock.open') def test_jlock_acquire_os_error(self, mock_open...
119
162
# Copyright 2017 Square, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,...
test_jlock_acquire_bad_file
Tests acquiring the lockfile when the current lockfile is invallid. Args: self (TestJLock): the ``TestJLock`` instance mock_open (Mock): mocked built-in open method mock_util (Mock): mocked ``psutil`` module mock_rm (Mock): mocked os remove method mock_wr (Mock): mocked os write method mock_op (Mock): mock...
# Copyright 2017 Square, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,...
@mock.patch('tempfile.tempdir', new='tmp') @mock.patch('os.close') @mock.patch('os.path.exists') @mock.patch('os.open') @mock.patch('os.write') @mock.patch('os.remove') @mock.patch('pylink.jlock.psutil') @mock.patch('pylink.jlock.open') def test_jlock_acquire_bad_file(self, mock_open...
164
211
# Copyright 2017 Square, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,...
test_jlock_acquire_invalid_pid
Tests acquiring the lockfile when the pid in the lockfile is invalid. Args: self (TestJLock): the ``TestJLock`` instance mock_open (Mock): mocked built-in open method mock_util (Mock): mocked ``psutil`` module mock_rm (Mock): mocked os remove method mock_wr (Mock): mocked os write method mock_op (Mock): mo...
# Copyright 2017 Square, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,...
@mock.patch('tempfile.tempdir', new='tmp') @mock.patch('os.close') @mock.patch('os.path.exists') @mock.patch('os.open') @mock.patch('os.write') @mock.patch('os.remove') @mock.patch('pylink.jlock.psutil') @mock.patch('pylink.jlock.open') def test_jlock_acquire_invalid_pid(self, mock_o...
213
258
# Copyright 2017 Square, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,...
test_jlock_acquire_old_pid
Tests acquiring when the PID in the lockfile does not exist. Args: self (TestJLock): the ``TestJLock`` instance mock_open (Mock): mocked built-in open method mock_util (Mock): mocked ``psutil`` module mock_rm (Mock): mocked os remove method mock_wr (Mock): mocked os write method mock_op (Mock): mocked os o...
# Copyright 2017 Square, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,...
@mock.patch('tempfile.tempdir', new='tmp') @mock.patch('os.close') @mock.patch('os.path.exists') @mock.patch('os.open') @mock.patch('os.write') @mock.patch('os.remove') @mock.patch('pylink.jlock.psutil') @mock.patch('pylink.jlock.open') def test_jlock_acquire_old_pid(self, mock_open,...
260
306
# Copyright 2017 Square, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,...
test_jlock_release_acquired
Tests releasing a held lock. Args: self (TestJLock): the ``TestJLock`` instance mock_remove (Mock): mock file removal method mock_close (Mock): mocked close method mock_exists (Mock): mocked path exist method Returns: ``None``
# Copyright 2017 Square, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,...
@mock.patch('tempfile.tempdir', new='tmp') @mock.patch('os.path.exists') @mock.patch('os.close') @mock.patch('os.remove') def test_jlock_release_acquired(self, mock_remove, mock_close, mock_exists): """Tests releasing a held lock. Args: self (TestJLock): the ``TestJLock`` ...
308
336
# Copyright 2017 Square, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,...
distance_p2p
Computes minimal distances of each point in points_src to points_tgt. Args: points_src (numpy array): source points normals_src (numpy array): source normals points_tgt (numpy array): target points normals_tgt (numpy array): target normals
import logging import numpy as np import trimesh from src.common import compute_iou # from scipy.spatial import cKDTree from src.utils.libkdtree import KDTree from src.utils.libmesh import check_mesh_contains # Maximum values for bounding box [-0.5, 0.5]^3 EMPTY_PCL_DICT = { 'completeness': np.sqrt(3), 'accu...
def distance_p2p(points_src, normals_src, points_tgt, normals_tgt): """ Computes minimal distances of each point in points_src to points_tgt. Args: points_src (numpy array): source points normals_src (numpy array): source normals points_tgt (numpy array): target points normals_t...
173
194
import logging import numpy as np import trimesh from src.common import compute_iou # from scipy.spatial import cKDTree from src.utils.libkdtree import KDTree from src.utils.libmesh import check_mesh_contains # Maximum values for bounding box [-0.5, 0.5]^3 EMPTY_PCL_DICT = { 'completeness': np.sqrt(3), 'accu...
add_descriptor
Add a descriptor to this index. Adding the same descriptor multiple times should not add multiple copies of the descriptor in the index. :param descriptor: Descriptor to index. :type descriptor: smqtk.representation.DescriptorElement :param no_cache: Do not cache the internal table if a file cache was provided. ...
import six from smqtk.representation import DescriptorIndex, get_data_element_impls from smqtk.utils import merge_dict, plugin, SimpleTimer try: from six.moves import cPickle as pickle except ImportError: import pickle class MemoryDescriptorIndex (DescriptorIndex): """ In-memory descriptor index wit...
def add_descriptor(self, descriptor, no_cache=False): """ Add a descriptor to this index. Adding the same descriptor multiple times should not add multiple copies of the descriptor in the index. :param descriptor: Descriptor to index. :type descriptor: smqtk.represe...
161
179
import six from smqtk.representation import DescriptorIndex, get_data_element_impls from smqtk.utils import merge_dict, plugin, SimpleTimer try: from six.moves import cPickle as pickle except ImportError: import pickle class MemoryDescriptorIndex (DescriptorIndex): """ In-memory descriptor index wit...
add_many_descriptors
Add multiple descriptors at one time. :param descriptors: Iterable of descriptor instances to add to this index. :type descriptors: collections.Iterable[smqtk.representation.DescriptorElement]
import six from smqtk.representation import DescriptorIndex, get_data_element_impls from smqtk.utils import merge_dict, plugin, SimpleTimer try: from six.moves import cPickle as pickle except ImportError: import pickle class MemoryDescriptorIndex (DescriptorIndex): """ In-memory descriptor index wit...
def add_many_descriptors(self, descriptors): """ Add multiple descriptors at one time. :param descriptors: Iterable of descriptor instances to add to this index. :type descriptors: collections.Iterable[smqtk.representation.DescriptorElement] """ ...
181
197
import six from smqtk.representation import DescriptorIndex, get_data_element_impls from smqtk.utils import merge_dict, plugin, SimpleTimer try: from six.moves import cPickle as pickle except ImportError: import pickle class MemoryDescriptorIndex (DescriptorIndex): """ In-memory descriptor index wit...
__init__
Set up jailer fields. This plays the role of a default constructor as it populates the jailer's fields with some default values. Each field can be further adjusted by each test even with None values.
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """Define a class for creating the jailed context.""" import os import shutil from subprocess import run, PIPE from retry.api import retry_call from framework.defs import API_USOCKET_NAME, FC_BINARY_NAME,...
def __init__( self, jailer_id, exec_file, numa_node=0, uid=1234, gid=1234, chroot_base=JAILER_DEFAULT_CHROOT, netns=None, daemonize=True, seccomp_level=2 ): """Set up jailer fields. ...
33
59
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """Define a class for creating the jailed context.""" import os import shutil from subprocess import run, PIPE from retry.api import retry_call from framework.defs import API_USOCKET_NAME, FC_BINARY_NAME,...
_kill_crgoup_tasks
Simulate wait on pid. Read the tasks file and stay there until /proc/{pid} disappears. The retry function that calls this code makes sure we do not timeout.
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """Define a class for creating the jailed context.""" import os import shutil from subprocess import run, PIPE from retry.api import retry_call from framework.defs import API_USOCKET_NAME, FC_BINARY_NAME,...
def _kill_crgoup_tasks(self, controller): """Simulate wait on pid. Read the tasks file and stay there until /proc/{pid} disappears. The retry function that calls this code makes sure we do not timeout. """ tasks_file = '/sys/fs/cgroup/{}/{}/{}/tasks'.format( ...
208
233
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """Define a class for creating the jailed context.""" import os import shutil from subprocess import run, PIPE from retry.api import retry_call from framework.defs import API_USOCKET_NAME, FC_BINARY_NAME,...
__init__
Constructor for :class:`.RepTaxonomy` Parameters ---------- taxonomy Data containing feature taxonomy taxonomy_columns Column(s) containing taxonomy data kwargs Passed to :func:`~pandas.read_csv` or :mod:`biome` loader.
import warnings warnings.simplefilter("ignore", category=FutureWarning) from pmaf.biome.essentials._metakit import EssentialFeatureMetabase from pmaf.biome.essentials._base import EssentialBackboneBase from pmaf.internal._constants import ( AVAIL_TAXONOMY_NOTATIONS, jRegexGG, jRegexQIIME, BIOM_TAXONOMY...
def __init__( self, taxonomy: Union[pd.DataFrame, pd.Series, str], taxonomy_columns: Union[str, int, Sequence[Union[int, str]]] = None, **kwargs: Any ) -> None: """Constructor for :class:`.RepTaxonomy` Parameters ---------- taxonomy Da...
33
107
import warnings warnings.simplefilter("ignore", category=FutureWarning) from pmaf.biome.essentials._metakit import EssentialFeatureMetabase from pmaf.biome.essentials._base import EssentialBackboneBase from pmaf.internal._constants import ( AVAIL_TAXONOMY_NOTATIONS, jRegexGG, jRegexQIIME, BIOM_TAXONOMY...
__load_biom
Actual private method to process :mod:`biom` file. Parameters ---------- filepath :mod:`biom` file path. kwargs Compatibility
import warnings warnings.simplefilter("ignore", category=FutureWarning) from pmaf.biome.essentials._metakit import EssentialFeatureMetabase from pmaf.biome.essentials._base import EssentialBackboneBase from pmaf.internal._constants import ( AVAIL_TAXONOMY_NOTATIONS, jRegexGG, jRegexQIIME, BIOM_TAXONOMY...
@classmethod def __load_biom(cls, filepath: str, **kwargs: Any) -> Tuple[pd.DataFrame, dict]: """Actual private method to process :mod:`biom` file. Parameters ---------- filepath :mod:`biom` file path. kwargs Compatibility """ biom...
166
200
import warnings warnings.simplefilter("ignore", category=FutureWarning) from pmaf.biome.essentials._metakit import EssentialFeatureMetabase from pmaf.biome.essentials._base import EssentialBackboneBase from pmaf.internal._constants import ( AVAIL_TAXONOMY_NOTATIONS, jRegexGG, jRegexQIIME, BIOM_TAXONOMY...
_merge_features_by_map
Merge features and ratify action. Parameters ---------- map_dict Map to use for merging done Whether merging was completed or not. Compatibility. kwargs Compatibility
import warnings warnings.simplefilter("ignore", category=FutureWarning) from pmaf.biome.essentials._metakit import EssentialFeatureMetabase from pmaf.biome.essentials._base import EssentialBackboneBase from pmaf.internal._constants import ( AVAIL_TAXONOMY_NOTATIONS, jRegexGG, jRegexQIIME, BIOM_TAXONOMY...
def _merge_features_by_map( self, map_dict: Mapper, done: bool = False, **kwargs: Any ) -> Optional[Mapper]: """Merge features and ratify action. Parameters ---------- map_dict Map to use for merging done Whether merging was completed or n...
219
241
import warnings warnings.simplefilter("ignore", category=FutureWarning) from pmaf.biome.essentials._metakit import EssentialFeatureMetabase from pmaf.biome.essentials._base import EssentialBackboneBase from pmaf.internal._constants import ( AVAIL_TAXONOMY_NOTATIONS, jRegexGG, jRegexQIIME, BIOM_TAXONOMY...
get_taxonomy_by_id
Get taxonomy :class:`~pandas.DataFrame` by feature `ids`. Parameters ---------- ids Either feature indices or None for all. Returns ------- class:`pandas.DataFrame` with taxonomy data
import warnings warnings.simplefilter("ignore", category=FutureWarning) from pmaf.biome.essentials._metakit import EssentialFeatureMetabase from pmaf.biome.essentials._base import EssentialBackboneBase from pmaf.internal._constants import ( AVAIL_TAXONOMY_NOTATIONS, jRegexGG, jRegexQIIME, BIOM_TAXONOMY...
def get_taxonomy_by_id( self, ids: Optional[AnyGenericIdentifier] = None ) -> pd.DataFrame: """Get taxonomy :class:`~pandas.DataFrame` by feature `ids`. Parameters ---------- ids Either feature indices or None for all. Returns ------- ...
261
282
import warnings warnings.simplefilter("ignore", category=FutureWarning) from pmaf.biome.essentials._metakit import EssentialFeatureMetabase from pmaf.biome.essentials._base import EssentialBackboneBase from pmaf.internal._constants import ( AVAIL_TAXONOMY_NOTATIONS, jRegexGG, jRegexQIIME, BIOM_TAXONOMY...
drop_features_without_ranks
Remove features that do not contain `ranks` Parameters ---------- ranks Ranks to look for any If True removes feature with single occurrence of missing rank. If False all `ranks` must be missing. kwargs Compatibility
import warnings warnings.simplefilter("ignore", category=FutureWarning) from pmaf.biome.essentials._metakit import EssentialFeatureMetabase from pmaf.biome.essentials._base import EssentialBackboneBase from pmaf.internal._constants import ( AVAIL_TAXONOMY_NOTATIONS, jRegexGG, jRegexQIIME, BIOM_TAXONOMY...
def drop_features_without_ranks( self, ranks: Sequence[str], any: bool = False, **kwargs: Any ) -> Optional[AnyGenericIdentifier]: # Done """Remove features that do not contain `ranks` Parameters ---------- ranks Ranks to look for any If ...
374
400
import warnings warnings.simplefilter("ignore", category=FutureWarning) from pmaf.biome.essentials._metakit import EssentialFeatureMetabase from pmaf.biome.essentials._base import EssentialBackboneBase from pmaf.internal._constants import ( AVAIL_TAXONOMY_NOTATIONS, jRegexGG, jRegexQIIME, BIOM_TAXONOMY...
merge_features_by_rank
Merge features by taxonomic rank/level. Parameters ---------- level Taxonomic rank/level to use for merging. kwargs Compatibility
import warnings warnings.simplefilter("ignore", category=FutureWarning) from pmaf.biome.essentials._metakit import EssentialFeatureMetabase from pmaf.biome.essentials._base import EssentialBackboneBase from pmaf.internal._constants import ( AVAIL_TAXONOMY_NOTATIONS, jRegexGG, jRegexQIIME, BIOM_TAXONOMY...
def merge_features_by_rank(self, level: str, **kwargs: Any) -> Optional[Mapper]: """Merge features by taxonomic rank/level. Parameters ---------- level Taxonomic rank/level to use for merging. kwargs Compatibility """ ret = {} ...
425
458
import warnings warnings.simplefilter("ignore", category=FutureWarning) from pmaf.biome.essentials._metakit import EssentialFeatureMetabase from pmaf.biome.essentials._base import EssentialBackboneBase from pmaf.internal._constants import ( AVAIL_TAXONOMY_NOTATIONS, jRegexGG, jRegexQIIME, BIOM_TAXONOMY...
get_subset
Get subset of the :class:`.RepTaxonomy`. Parameters ---------- rids Feature identifiers. args Compatibility kwargs Compatibility Returns ------- class:`.RepTaxonomy`
import warnings warnings.simplefilter("ignore", category=FutureWarning) from pmaf.biome.essentials._metakit import EssentialFeatureMetabase from pmaf.biome.essentials._base import EssentialBackboneBase from pmaf.internal._constants import ( AVAIL_TAXONOMY_NOTATIONS, jRegexGG, jRegexQIIME, BIOM_TAXONOMY...
def get_subset( self, rids: Optional[AnyGenericIdentifier] = None, *args, **kwargs: Any ) -> "RepTaxonomy": """Get subset of the :class:`.RepTaxonomy`. Parameters ---------- rids Feature identifiers. args Compatibility kwargs ...
474
502
import warnings warnings.simplefilter("ignore", category=FutureWarning) from pmaf.biome.essentials._metakit import EssentialFeatureMetabase from pmaf.biome.essentials._base import EssentialBackboneBase from pmaf.internal._constants import ( AVAIL_TAXONOMY_NOTATIONS, jRegexGG, jRegexQIIME, BIOM_TAXONOMY...
export
Exports the taxonomy into the specified file. Parameters ---------- output_fp Export filepath args Compatibility _add_ext Add file extension or not. sep Delimiter kwargs Compatibility
import warnings warnings.simplefilter("ignore", category=FutureWarning) from pmaf.biome.essentials._metakit import EssentialFeatureMetabase from pmaf.biome.essentials._base import EssentialBackboneBase from pmaf.internal._constants import ( AVAIL_TAXONOMY_NOTATIONS, jRegexGG, jRegexQIIME, BIOM_TAXONOMY...
def export( self, output_fp: str, *args, _add_ext: bool = False, sep: str = ",", **kwargs: Any ) -> None: """Exports the taxonomy into the specified file. Parameters ---------- output_fp Export filepath args ...
526
553
import warnings warnings.simplefilter("ignore", category=FutureWarning) from pmaf.biome.essentials._metakit import EssentialFeatureMetabase from pmaf.biome.essentials._base import EssentialBackboneBase from pmaf.internal._constants import ( AVAIL_TAXONOMY_NOTATIONS, jRegexGG, jRegexQIIME, BIOM_TAXONOMY...
__init_internal_taxonomy
Main method to initialize taxonomy. Parameters ---------- taxonomy_data Incoming parsed taxonomy data taxonomy_notation Taxonomy lineage notation style. Can be one of :const:`pmaf.internals._constants.AVAIL_TAXONOMY_NOTATIONS` order_ranks List with the target rank order. Default is set to None. ...
import warnings warnings.simplefilter("ignore", category=FutureWarning) from pmaf.biome.essentials._metakit import EssentialFeatureMetabase from pmaf.biome.essentials._base import EssentialBackboneBase from pmaf.internal._constants import ( AVAIL_TAXONOMY_NOTATIONS, jRegexGG, jRegexQIIME, BIOM_TAXONOMY...
def __init_internal_taxonomy( self, taxonomy_data: Union[pd.Series, pd.DataFrame], taxonomy_notation: Optional[str] = "greengenes", order_ranks: Optional[Sequence[str]] = None, **kwargs: Any ) -> None: """Main method to initialize taxonomy. Parameters ...
590
645
import warnings warnings.simplefilter("ignore", category=FutureWarning) from pmaf.biome.essentials._metakit import EssentialFeatureMetabase from pmaf.biome.essentials._base import EssentialBackboneBase from pmaf.internal._constants import ( AVAIL_TAXONOMY_NOTATIONS, jRegexGG, jRegexQIIME, BIOM_TAXONOMY...
get_share
Represents a share on the Data Box Edge/Gateway device. :param str device_name: The device name. :param str name: The share name. :param str resource_group_name: The resource group name.
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities fro...
def get_share(device_name: Optional[str] = None, name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetShareResult: """ Represents a share on the Data Box Edge/Gateway device. :param str...
202
238
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities fro...
get
Get an existing DataCollectionRule resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: ...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables from...
@staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None) -> 'DataCollectionRule': """ Get an existing DataCollectionRule resource's state with the given name, id, and optional extra properties used to qualify ...
90
116
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from ... import _utilities, _tables from...
get_zones
Method to fetch zones for given region or all the regions if none specified. Args: region (str): Name of region to get zones of. Returns: zones (obj): Map of zone -> subnet
#!/usr/bin/env python # # Copyright 2019 YugaByte, Inc. and Contributors # # Licensed under the Polyform Free Trial License 1.0.0 (the "License"); you # may not use this file except in compliance with the License. You # may obtain a copy of the License at # # https://github.com/YugaByte/yugabyte-db/blob/master/licenses...
def get_zones(region, dest_vpc_id=None): """Method to fetch zones for given region or all the regions if none specified. Args: region (str): Name of region to get zones of. Returns: zones (obj): Map of zone -> subnet """ result = {} filters = get_filters("state", "available") ...
363
389
#!/usr/bin/env python # # Copyright 2019 YugaByte, Inc. and Contributors # # Licensed under the Polyform Free Trial License 1.0.0 (the "License"); you # may not use this file except in compliance with the License. You # may obtain a copy of the License at # # https://github.com/YugaByte/yugabyte-db/blob/master/licenses...
create_subnet
Method to create subnet based on cidr and tag name. Args: client (boto client): Region specific boto client vpc (VPC object): VPC object to create subnet. zone (str): Availability zone name cidr (str): CIDR string tag_name (str): Tag name for subnet. Returns: subnet: Newly created subnet object.
#!/usr/bin/env python # # Copyright 2019 YugaByte, Inc. and Contributors # # Licensed under the Polyform Free Trial License 1.0.0 (the "License"); you # may not use this file except in compliance with the License. You # may obtain a copy of the License at # # https://github.com/YugaByte/yugabyte-db/blob/master/licenses...
def create_subnet(client, vpc, zone, cidr, tag_name): """Method to create subnet based on cidr and tag name. Args: client (boto client): Region specific boto client vpc (VPC object): VPC object to create subnet. zone (str): Availability zone name cidr (str): CIDR string t...
416
433
#!/usr/bin/env python # # Copyright 2019 YugaByte, Inc. and Contributors # # Licensed under the Polyform Free Trial License 1.0.0 (the "License"); you # may not use this file except in compliance with the License. You # may obtain a copy of the License at # # https://github.com/YugaByte/yugabyte-db/blob/master/licenses...
create_igw
Method to create Internet Gateway based on tag_name in given VPC. If the gateway already exists, it would return that object. If the object doesn't have a tag, we would tag it accordingly. Args: client (boto client): Region specific boto client tag_name (str): Tag name for internet gateway. vpc (VPC object)...
#!/usr/bin/env python # # Copyright 2019 YugaByte, Inc. and Contributors # # Licensed under the Polyform Free Trial License 1.0.0 (the "License"); you # may not use this file except in compliance with the License. You # may obtain a copy of the License at # # https://github.com/YugaByte/yugabyte-db/blob/master/licenses...
@get_or_create(get_igw) def create_igw(client, tag_name, vpc): """Method to create Internet Gateway based on tag_name in given VPC. If the gateway already exists, it would return that object. If the object doesn't have a tag, we would tag it accordingly. Args: client (boto client): Region specif...
486
509
#!/usr/bin/env python # # Copyright 2019 YugaByte, Inc. and Contributors # # Licensed under the Polyform Free Trial License 1.0.0 (the "License"); you # may not use this file except in compliance with the License. You # may obtain a copy of the License at # # https://github.com/YugaByte/yugabyte-db/blob/master/licenses...
create_route_table
Method to create route table based on tag_name in given VPC. It will first query for the tag name to see if the route table already exists or if one is already attached to the VPC, if so it will return that route table. Args: client (boto client): Region specific boto client tag_name (str): Route table tag name...
#!/usr/bin/env python # # Copyright 2019 YugaByte, Inc. and Contributors # # Licensed under the Polyform Free Trial License 1.0.0 (the "License"); you # may not use this file except in compliance with the License. You # may obtain a copy of the License at # # https://github.com/YugaByte/yugabyte-db/blob/master/licenses...
@get_or_create(get_route_table) def create_route_table(client, tag_name, vpc): """Method to create route table based on tag_name in given VPC. It will first query for the tag name to see if the route table already exists or if one is already attached to the VPC, if so it will return that route table. Ar...
524
545
#!/usr/bin/env python # # Copyright 2019 YugaByte, Inc. and Contributors # # Licensed under the Polyform Free Trial License 1.0.0 (the "License"); you # may not use this file except in compliance with the License. You # may obtain a copy of the License at # # https://github.com/YugaByte/yugabyte-db/blob/master/licenses...
cleanup_igw
Method to cleanup Internet Gateway matching the tag name. And also remove any vpc that is attached to the Internet Gateway. Args: igw: Instance of Internet Gateway matching tag_name.
#!/usr/bin/env python # # Copyright 2019 YugaByte, Inc. and Contributors # # Licensed under the Polyform Free Trial License 1.0.0 (the "License"); you # may not use this file except in compliance with the License. You # may obtain a copy of the License at # # https://github.com/YugaByte/yugabyte-db/blob/master/licenses...
@get_and_cleanup(get_igw) def cleanup_igw(igw, **kwargs): """Method to cleanup Internet Gateway matching the tag name. And also remove any vpc that is attached to the Internet Gateway. Args: igw: Instance of Internet Gateway matching tag_name. """ for vpc in igw.attachments: igw.deta...
557
566
#!/usr/bin/env python # # Copyright 2019 YugaByte, Inc. and Contributors # # Licensed under the Polyform Free Trial License 1.0.0 (the "License"); you # may not use this file except in compliance with the License. You # may obtain a copy of the License at # # https://github.com/YugaByte/yugabyte-db/blob/master/licenses...
create_vpc
Method to create vpc based on the cidr and tag with tag_name. Args: client (boto client): Region specific boto client tag_name (str): VPC tag name cidr (str): CIDR string. Returns: VPC(Object): Newly created VPC object.
#!/usr/bin/env python # # Copyright 2019 YugaByte, Inc. and Contributors # # Licensed under the Polyform Free Trial License 1.0.0 (the "License"); you # may not use this file except in compliance with the License. You # may obtain a copy of the License at # # https://github.com/YugaByte/yugabyte-db/blob/master/licenses...
@get_or_create(get_vpc) def create_vpc(client, tag_name, cidr): """Method to create vpc based on the cidr and tag with tag_name. Args: client (boto client): Region specific boto client tag_name (str): VPC tag name cidr (str): CIDR string. Returns: VPC(Object): Newly created V...
589
602
#!/usr/bin/env python # # Copyright 2019 YugaByte, Inc. and Contributors # # Licensed under the Polyform Free Trial License 1.0.0 (the "License"); you # may not use this file except in compliance with the License. You # may obtain a copy of the License at # # https://github.com/YugaByte/yugabyte-db/blob/master/licenses...
set_yb_sg_and_fetch_vpc
Method to bootstrap vpc and security group, and enable vpc peering with the host_instance vpc. Args: metadata (obj): Cloud metadata object with cidr prefix and other metadata. region (str): Region name to create the vpc in. dest_vpc_id (str): Id of the VPC that yugabyte machines will reside in. Returns: ...
#!/usr/bin/env python # # Copyright 2019 YugaByte, Inc. and Contributors # # Licensed under the Polyform Free Trial License 1.0.0 (the "License"); you # may not use this file except in compliance with the License. You # may obtain a copy of the License at # # https://github.com/YugaByte/yugabyte-db/blob/master/licenses...
def set_yb_sg_and_fetch_vpc(metadata, region, dest_vpc_id): """Method to bootstrap vpc and security group, and enable vpc peering with the host_instance vpc. Args: metadata (obj): Cloud metadata object with cidr prefix and other metadata. region (str): Region name to create the vpc in. ...
605
626
#!/usr/bin/env python # # Copyright 2019 YugaByte, Inc. and Contributors # # Licensed under the Polyform Free Trial License 1.0.0 (the "License"); you # may not use this file except in compliance with the License. You # may obtain a copy of the License at # # https://github.com/YugaByte/yugabyte-db/blob/master/licenses...
vpc_components_as_json
Method takes VPC, Security Group and Subnets and returns a json data format with ids. Args: vpc (VPC Object): Region specific VPC object sgs (List of Security Group Object): Region specific Security Group object subnets (subnet object map): Map of Subnet objects keyed of zone. Retuns: json (str): A Json...
#!/usr/bin/env python # # Copyright 2019 YugaByte, Inc. and Contributors # # Licensed under the Polyform Free Trial License 1.0.0 (the "License"); you # may not use this file except in compliance with the License. You # may obtain a copy of the License at # # https://github.com/YugaByte/yugabyte-db/blob/master/licenses...
def vpc_components_as_json(vpc, sgs, subnets): """Method takes VPC, Security Group and Subnets and returns a json data format with ids. Args: vpc (VPC Object): Region specific VPC object sgs (List of Security Group Object): Region specific Security Group object subnets (subnet object map...
688
703
#!/usr/bin/env python # # Copyright 2019 YugaByte, Inc. and Contributors # # Licensed under the Polyform Free Trial License 1.0.0 (the "License"); you # may not use this file except in compliance with the License. You # may obtain a copy of the License at # # https://github.com/YugaByte/yugabyte-db/blob/master/licenses...
get_vpc_peerings
Method to fetch all the VPC peerings against given VPC. If host_vpc is provided it will check if there is a peering against that vpc. Args: vpc(VPC object): VPC Object to search for peerings host_vpc (Host VPC object): Can be Null as well, to check if specific host_vpc peering is...
#!/usr/bin/env python # # Copyright 2019 YugaByte, Inc. and Contributors # # Licensed under the Polyform Free Trial License 1.0.0 (the "License"); you # may not use this file except in compliance with the License. You # may obtain a copy of the License at # # https://github.com/YugaByte/yugabyte-db/blob/master/licenses...
def get_vpc_peerings(vpc, host_vpc, **kwargs): """Method to fetch all the VPC peerings against given VPC. If host_vpc is provided it will check if there is a peering against that vpc. Args: vpc(VPC object): VPC Object to search for peerings host_vpc (Host VPC object): Can be Null as well, to...
774
795
#!/usr/bin/env python # # Copyright 2019 YugaByte, Inc. and Contributors # # Licensed under the Polyform Free Trial License 1.0.0 (the "License"); you # may not use this file except in compliance with the License. You # may obtain a copy of the License at # # https://github.com/YugaByte/yugabyte-db/blob/master/licenses...
__init__
Keyword args: transmitted_bytes_per_sec (float): Total bytes transmitted per second. received_bytes_per_sec (float): Total bytes received per second.
# coding: utf-8 """ FlashBlade REST API A lightweight client for FlashBlade REST API 2.3, developed by Pure Storage, Inc. (http://www.purestorage.com/). OpenAPI spec version: 2.3 Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re import six import typ...
def __init__( self, transmitted_bytes_per_sec=None, # type: float received_bytes_per_sec=None, # type: float ): """ Keyword args: transmitted_bytes_per_sec (float): Total bytes transmitted per second. received_bytes_per_sec (float): Total bytes r...
45
58
# coding: utf-8 """ FlashBlade REST API A lightweight client for FlashBlade REST API 2.3, developed by Pure Storage, Inc. (http://www.purestorage.com/). OpenAPI spec version: 2.3 Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re import six import typ...
debug_identity
Debug Identity Op. Provides an identity mapping of the non-Ref type input tensor for debugging. Args: input: A `Tensor`. Input tensor, non-Reference type. device_name: An optional `string`. Defaults to `""`. tensor_name: An optional `string`. Defaults to `""`. Name of the input tensor. debug_urls: An opti...
"""Python wrappers around TensorFlow ops. This file is MACHINE GENERATED! Do not edit. """ import collections as _collections import six as _six from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow from tensorflow.python.eager import context as _context from tensorflow.python.eager import core as _c...
@tf_export('debug_identity') def debug_identity(input, device_name="", tensor_name="", debug_urls=[], gated_grpc=False, name=None): r"""Debug Identity Op. Provides an identity mapping of the non-Ref type input tensor for debugging. Args: input: A `Tensor`. Input tensor, non-Reference type. device_name: ...
224
302
"""Python wrappers around TensorFlow ops. This file is MACHINE GENERATED! Do not edit. """ import collections as _collections import six as _six from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow from tensorflow.python.eager import context as _context from tensorflow.python.eager import ...
debug_nan_count
Debug NaN Value Counter Op Counts number of NaNs in the input tensor, for debugging. Args: input: A `Tensor`. Input tensor, non-Reference type. device_name: An optional `string`. Defaults to `""`. tensor_name: An optional `string`. Defaults to `""`. Name of the input tensor. debug_urls: An optional list o...
"""Python wrappers around TensorFlow ops. This file is MACHINE GENERATED! Do not edit. """ import collections as _collections import six as _six from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow from tensorflow.python.eager import context as _context from tensorflow.python.eager import core as _c...
@tf_export('debug_nan_count') def debug_nan_count(input, device_name="", tensor_name="", debug_urls=[], gated_grpc=False, name=None): r"""Debug NaN Value Counter Op Counts number of NaNs in the input tensor, for debugging. Args: input: A `Tensor`. Input tensor, non-Reference type. device_name: An option...
338
416
"""Python wrappers around TensorFlow ops. This file is MACHINE GENERATED! Do not edit. """ import collections as _collections import six as _six from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow from tensorflow.python.eager import context as _context from tensorflow.python.eager import ...
test_module
Tests a given module's stub against introspecting it at runtime. Requires the stub to have been built already, accomplished by a call to ``build_stubs``. :param module_name: The module to test
"""Tests for stubs. Verify that various things in stubs are consistent with how things behave at runtime. """ import argparse import copy import enum import importlib import inspect import re import sys import types import warnings from functools import singledispatch from pathlib import Path from typing import Any,...
def test_module(module_name: str) -> Iterator[Error]: """Tests a given module's stub against introspecting it at runtime. Requires the stub to have been built already, accomplished by a call to ``build_stubs``. :param module_name: The module to test """ stub = get_stub(module_name) if stub is...
157
180
"""Tests for stubs. Verify that various things in stubs are consistent with how things behave at runtime. """ import argparse import copy import enum import importlib import inspect import re import sys import types import warnings from functools import singledispatch from pathlib import Path from typing import Any,...
_resolve_funcitem_from_decorator
Returns a FuncItem that corresponds to the output of the decorator. Returns None if we can't figure out what that would be. For convenience, this function also accepts FuncItems.
"""Tests for stubs. Verify that various things in stubs are consistent with how things behave at runtime. """ import argparse import copy import enum import importlib import inspect import re import sys import types import warnings from functools import singledispatch from pathlib import Path from typing import Any,...
def _resolve_funcitem_from_decorator(dec: nodes.OverloadPart) -> Optional[nodes.FuncItem]: """Returns a FuncItem that corresponds to the output of the decorator. Returns None if we can't figure out what that would be. For convenience, this function also accepts FuncItems. """ if isinstance(dec, no...
806
848
"""Tests for stubs. Verify that various things in stubs are consistent with how things behave at runtime. """ import argparse import copy import enum import importlib import inspect import re import sys import types import warnings from functools import singledispatch from pathlib import Path from typing import Any,...
build_stubs
Uses mypy to construct stub objects for the given modules. This sets global state that ``get_stub`` can access. Returns all modules we might want to check. If ``find_submodules`` is False, this is equal to ``modules``. :param modules: List of modules to build stubs for. :param options: Mypy options for finding and b...
"""Tests for stubs. Verify that various things in stubs are consistent with how things behave at runtime. """ import argparse import copy import enum import importlib import inspect import re import sys import types import warnings from functools import singledispatch from pathlib import Path from typing import Any,...
def build_stubs(modules: List[str], options: Options, find_submodules: bool = False) -> List[str]: """Uses mypy to construct stub objects for the given modules. This sets global state that ``get_stub`` can access. Returns all modules we might want to check. If ``find_submodules`` is False, this is equal ...
1,005
1,060
"""Tests for stubs. Verify that various things in stubs are consistent with how things behave at runtime. """ import argparse import copy import enum import importlib import inspect import re import sys import types import warnings from functools import singledispatch from pathlib import Path from typing import Any,...
_maybe_convert_timedelta
Convert timedelta-like input to an integer multiple of self.freq Parameters ---------- other : timedelta, np.timedelta64, DateOffset, int, np.ndarray Returns ------- converted : int, np.ndarray[int64] Raises ------ IncompatibleFrequency : if the input cannot be written as a multiple of self.freq. Note Incompati...
from __future__ import annotations from datetime import ( datetime, timedelta, ) from typing import Hashable import warnings import numpy as np from pandas._libs import ( index as libindex, lib, ) from pandas._libs.tslibs import ( BaseOffset, NaT, Period, Resolution, Tick, ) from ...
def _maybe_convert_timedelta(self, other): """ Convert timedelta-like input to an integer multiple of self.freq Parameters ---------- other : timedelta, np.timedelta64, DateOffset, int, np.ndarray Returns ------- converted : int, np.ndarray[int64] ...
275
309
from __future__ import annotations from datetime import ( datetime, timedelta, ) from typing import Hashable import warnings import numpy as np from pandas._libs import ( index as libindex, lib, ) from pandas._libs.tslibs import ( BaseOffset, NaT, Period, Resolution, Tick, ) from ...
get_loc
Get integer location for requested label. Parameters ---------- key : Period, NaT, str, or datetime String or datetime key must be parsable as Period. Returns ------- loc : int or ndarray[int64] Raises ------ KeyError Key is not present in the index. TypeError If key is listlike or otherwise not hashable...
from __future__ import annotations from datetime import ( datetime, timedelta, ) from typing import Hashable import warnings import numpy as np from pandas._libs import ( index as libindex, lib, ) from pandas._libs.tslibs import ( BaseOffset, NaT, Period, Resolution, Tick, ) from ...
def get_loc(self, key, method=None, tolerance=None): """ Get integer location for requested label. Parameters ---------- key : Period, NaT, str, or datetime String or datetime key must be parsable as Period. Returns ------- loc : int or n...
393
485
from __future__ import annotations from datetime import ( datetime, timedelta, ) from typing import Hashable import warnings import numpy as np from pandas._libs import ( index as libindex, lib, ) from pandas._libs.tslibs import ( BaseOffset, NaT, Period, Resolution, Tick, ) from ...
_maybe_cast_slice_bound
If label is a string or a datetime, cast it to Period.ordinal according to resolution. Parameters ---------- label : object side : {'left', 'right'} kind : {'loc', 'getitem'}, or None Returns ------- bound : Period or object Notes ----- Value of `side` parameter should be validated in caller.
from __future__ import annotations from datetime import ( datetime, timedelta, ) from typing import Hashable import warnings import numpy as np from pandas._libs import ( index as libindex, lib, ) from pandas._libs.tslibs import ( BaseOffset, NaT, Period, Resolution, Tick, ) from ...
def _maybe_cast_slice_bound(self, label, side: str, kind=lib.no_default): """ If label is a string or a datetime, cast it to Period.ordinal according to resolution. Parameters ---------- label : object side : {'left', 'right'} kind : {'loc', 'getitem'...
487
525
from __future__ import annotations from datetime import ( datetime, timedelta, ) from typing import Hashable import warnings import numpy as np from pandas._libs import ( index as libindex, lib, ) from pandas._libs.tslibs import ( BaseOffset, NaT, Period, Resolution, Tick, ) from ...
inference_graph
Constructs a TF graph for evaluating a random forest. Args: input_data: A tensor or SparseTensor or placeholder for input data. data_spec: A list of tf.dtype values specifying the original types of each column. Returns: The last op in the random forest inference graph.
# pylint: disable=g-bad-file-header # Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENS...
def inference_graph(self, input_data, data_spec=None): """Constructs a TF graph for evaluating a random forest. Args: input_data: A tensor or SparseTensor or placeholder for input data. data_spec: A list of tf.dtype values specifying the original types of each column. Returns: ...
389
412
# pylint: disable=g-bad-file-header # Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENS...
average_size
Constructs a TF graph for evaluating the average size of a forest. Returns: The average number of nodes over the trees.
# pylint: disable=g-bad-file-header # Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENS...
def average_size(self): """Constructs a TF graph for evaluating the average size of a forest. Returns: The average number of nodes over the trees. """ sizes = [] for i in range(self.params.num_trees): with ops.device(self.device_assigner.get_device(i)): sizes.append(self.trees...
414
424
# pylint: disable=g-bad-file-header # Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENS...
average_impurity
Constructs a TF graph for evaluating the leaf impurity of a forest. Returns: The last op in the graph.
# pylint: disable=g-bad-file-header # Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENS...
def average_impurity(self): """Constructs a TF graph for evaluating the leaf impurity of a forest. Returns: The last op in the graph. """ impurities = [] for i in range(self.params.num_trees): with ops.device(self.device_assigner.get_device(i)): impurities.append(self.trees[i]...
433
443
# pylint: disable=g-bad-file-header # Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENS...
inference_graph
Constructs a TF graph for evaluating a random tree. Args: input_data: A tensor or SparseTensor or placeholder for input data. data_spec: A list of tf.dtype values specifying the original types of each column. Returns: The last op in the random tree inference graph.
# pylint: disable=g-bad-file-header # Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENS...
def inference_graph(self, input_data, data_spec): """Constructs a TF graph for evaluating a random tree. Args: input_data: A tensor or SparseTensor or placeholder for input data. data_spec: A list of tf.dtype values specifying the original types of each column. Returns: The las...
777
801
# pylint: disable=g-bad-file-header # Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENS...
average_impurity
Constructs a TF graph for evaluating the average leaf impurity of a tree. If in regression mode, this is the leaf variance. If in classification mode, this is the gini impurity. Returns: The last op in the graph.
# pylint: disable=g-bad-file-header # Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENS...
def average_impurity(self): """Constructs a TF graph for evaluating the average leaf impurity of a tree. If in regression mode, this is the leaf variance. If in classification mode, this is the gini impurity. Returns: The last op in the graph. """ children = array_ops.squeeze(array_ops...
803
827
# pylint: disable=g-bad-file-header # Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENS...
ncc_loss
Computes the normalized cross-correlation (NCC) loss. Currently, only 4-D inputs are supported. Parameters ---------- static : tf.Tensor, shape (N, H, W, C) The static image to which the moving image is aligned. moving : tf.Tensor, shape (N, H, W, C) The moving image, the same shape as the static image. Retu...
# -*- coding: utf-8 -*- """poc.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1fTzz1aT2sb8oAXRO1-dr6O_IR6dof36e A simple example for deep-learning-based non-rigid image registration with the MNIST dataset. **README:** If the below error occurs,...
@tf.function def ncc_loss(static, moving): """Computes the normalized cross-correlation (NCC) loss. Currently, only 4-D inputs are supported. Parameters ---------- static : tf.Tensor, shape (N, H, W, C) The static image to which the moving image is aligned. moving : tf.Tensor, shape (N...
53
94
# -*- coding: utf-8 -*- """poc.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1fTzz1aT2sb8oAXRO1-dr6O_IR6dof36e A simple example for deep-learning-based non-rigid image registration with the MNIST dataset. **README:** If the below error occurs,...
simple_cnn
Creates a 2-D convolutional encoder-decoder network. Parameters ---------- input_shape : sequence of ints, optional Input data shape of the form (H, W, C). Default is (32, 32, 2). Returns ------- model An instance of Keras' Model class. Notes ----- Given a concatenated pair of static and moving images as inp...
# -*- coding: utf-8 -*- """poc.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1fTzz1aT2sb8oAXRO1-dr6O_IR6dof36e A simple example for deep-learning-based non-rigid image registration with the MNIST dataset. **README:** If the below error occurs,...
def simple_cnn(input_shape=(32, 32, 2)): """Creates a 2-D convolutional encoder-decoder network. Parameters ---------- input_shape : sequence of ints, optional Input data shape of the form (H, W, C). Default is (32, 32, 2). Returns ------- model An instance of Keras' Model ...
98
178
# -*- coding: utf-8 -*- """poc.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1fTzz1aT2sb8oAXRO1-dr6O_IR6dof36e A simple example for deep-learning-based non-rigid image registration with the MNIST dataset. **README:** If the below error occurs,...
regular_grid
Returns a batch of 2-D regular grids. Currently, only 2-D regular grids are supported. Parameters ---------- shape : sequence of ints, shape (3, ) The desired regular grid shape of the form (N, H, W). Returns ------- grid : tf.Tensor, shape (N, H, W, 2) A batch of 2-D regular grids, values normalized to [-1....
# -*- coding: utf-8 -*- """poc.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1fTzz1aT2sb8oAXRO1-dr6O_IR6dof36e A simple example for deep-learning-based non-rigid image registration with the MNIST dataset. **README:** If the below error occurs,...
@tf.function def regular_grid(shape): """Returns a batch of 2-D regular grids. Currently, only 2-D regular grids are supported. Parameters ---------- shape : sequence of ints, shape (3, ) The desired regular grid shape of the form (N, H, W). Returns ------- grid : tf.Tensor, s...
286
328
# -*- coding: utf-8 -*- """poc.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1fTzz1aT2sb8oAXRO1-dr6O_IR6dof36e A simple example for deep-learning-based non-rigid image registration with the MNIST dataset. **README:** If the below error occurs,...
test_step
A generic testing procedure. Parameters ---------- model A convolutional encoder-decoder network. moving : tf.Tensor, shape (N, H, W, C) A batch of moving images. static : tf.Tensor, shape (1, H, W, C) The static image. criterion The loss function. Returns ------- loss : tf.Tensor, shape () The av...
# -*- coding: utf-8 -*- """poc.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1fTzz1aT2sb8oAXRO1-dr6O_IR6dof36e A simple example for deep-learning-based non-rigid image registration with the MNIST dataset. **README:** If the below error occurs,...
@tf.function def test_step(model, moving, static, criterion): """A generic testing procedure. Parameters ---------- model A convolutional encoder-decoder network. moving : tf.Tensor, shape (N, H, W, C) A batch of moving images. static : tf.Tensor, shape (1, H, W, C) The ...
383
423
# -*- coding: utf-8 -*- """poc.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1fTzz1aT2sb8oAXRO1-dr6O_IR6dof36e A simple example for deep-learning-based non-rigid image registration with the MNIST dataset. **README:** If the below error occurs,...
create_process_chain_entry
Create a Actinia process description that uses t.rast.series to create the minimum value of the time series. :param input_time_series: The input time series name :param output_map: The name of the output map :return: A Actinia process chain description
# -*- coding: utf-8 -*- from random import randint import json from .base import analyse_process_graph, PROCESS_DICT, PROCESS_DESCRIPTION_DICT from openeo_grass_gis_driver.process_schemas import Parameter, ProcessDescription, ReturnValue from .actinia_interface import ActiniaInterface __license__ = "Apache License, Ve...
def create_process_chain_entry(input_name): """Create a Actinia process description that uses t.rast.series to create the minimum value of the time series. :param input_time_series: The input time series name :param output_map: The name of the output map :return: A Actinia process chain description...
73
109
# -*- coding: utf-8 -*- from random import randint import json from .base import analyse_process_graph, PROCESS_DICT, PROCESS_DESCRIPTION_DICT from openeo_grass_gis_driver.process_schemas import Parameter, ProcessDescription, ReturnValue from .actinia_interface import ActiniaInterface __license__ = "Apache License, Ve...
__init__
Create a FeatureImportanceSummarySaver Hook. This hook creates scalar summaries representing feature importance for each feature column during training. Args: model_dir: model base output directory. every_n_steps: frequency, in number of steps, for logging summaries. Raises: ValueError: If one of the arguments...
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
def __init__(self, model_dir, every_n_steps=1): """Create a FeatureImportanceSummarySaver Hook. This hook creates scalar summaries representing feature importance for each feature column during training. Args: model_dir: model base output directory. every_n_steps: frequency, in number of...
35
52
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
with_parent
Add filtering criterion that relates the given instance to a child object or collection, using its attribute state as well as an established :func:`.relationship()` configuration. The method uses the :func:`.with_parent` function to generate the clause, the result of which is passed to :meth:`.Query.filter`. Paramete...
# orm/query.py # Copyright (C) 2005-2014 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """The Query class and support. Defines the :class:`.Query` class, the central constru...
def with_parent(self, instance, property=None): """Add filtering criterion that relates the given instance to a child object or collection, using its attribute state as well as an established :func:`.relationship()` configuration. The method uses the :func:`.with_parent` fun...
924
956
# orm/query.py # Copyright (C) 2005-2014 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """The Query class and support. Defines the :class:`.Query` class, the central constru...
params
add values for bind parameters which may have been specified in filter(). parameters may be specified using \**kwargs, or optionally a single dictionary as the first positional argument. The reason for both is that \**kwargs is convenient, however some parameter dictionaries contain unicode keys in which case \**kwarg...
# orm/query.py # Copyright (C) 2005-2014 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """The Query class and support. Defines the :class:`.Query` class, the central constru...
@_generative() def params(self, *args, **kwargs): """add values for bind parameters which may have been specified in filter(). parameters may be specified using \**kwargs, or optionally a single dictionary as the first positional argument. The reason for both is that \**...
1,260
1,278
# orm/query.py # Copyright (C) 2005-2014 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """The Query class and support. Defines the :class:`.Query` class, the central constru...
__init__
Construct a new :class:`.Bundle`. e.g.:: bn = Bundle("mybundle", MyClass.x, MyClass.y) for row in session.query(bn).filter( bn.c.x == 5).filter(bn.c.y == 4): print(row.mybundle.x, row.mybundle.y) :param name: name of the bundle. :param \*exprs: columns or SQL expressions comprising the b...
# orm/query.py # Copyright (C) 2005-2014 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """The Query class and support. Defines the :class:`.Query` class, the central constru...
def __init__(self, name, *exprs, **kw): """Construct a new :class:`.Bundle`. e.g.:: bn = Bundle("mybundle", MyClass.x, MyClass.y) for row in session.query(bn).filter( bn.c.x == 5).filter(bn.c.y == 4): print(row.mybundle.x, row.mybundle.y...
3,299
3,322
# orm/query.py # Copyright (C) 2005-2014 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """The Query class and support. Defines the :class:`.Query` class, the central constru...
create_row_processor
Produce the "row processing" function for this :class:`.Bundle`. May be overridden by subclasses. .. seealso:: :ref:`bundles` - includes an example of subclassing.
# orm/query.py # Copyright (C) 2005-2014 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """The Query class and support. Defines the :class:`.Query` class, the central constru...
def create_row_processor(self, query, procs, labels): """Produce the "row processing" function for this :class:`.Bundle`. May be overridden by subclasses. .. seealso:: :ref:`bundles` - includes an example of subclassing. """ keyed_tuple = util.lightweight_name...
3,371
3,385
# orm/query.py # Copyright (C) 2005-2014 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """The Query class and support. Defines the :class:`.Query` class, the central constru...