uid
stringlengths
24
24
category
stringclasses
2 values
granularity
stringclasses
1 value
prefix
stringlengths
125
1.24k
suffix
stringlengths
39
35.8k
content
stringlengths
61
35.9k
repo
stringlengths
10
70
path
stringlengths
11
86
3122b1cd3ac999fb01386c9a
function
simple
# from __future__ import absolute_import, print_function import os import sys sys.path.append('./') import numpy as np from util.data_process import load_3d_volume_as_array, binary_dice3d def get_ground_truth_names(g_folder, patient_names_file, year = 15):
assert(year==15 or year == 17) with open(patient_names_file) as f: content = f.readlines() patient_names = [x.strip() for x in content] full_gt_names = [] for patient_name in patient_names: patient_dir = os.path.join(g_folder, patient_name) img_names = os.listdi...
def get_ground_truth_names(g_folder, patient_names_file, year = 15): assert(year==15 or year == 17) with open(patient_names_file) as f: content = f.readlines() patient_names = [x.strip() for x in content] full_gt_names = [] for patient_name in patient_names: patient_dir =...
MohamedHeshamMustafa/Brain-Tumor-Automatic-Detection-and-Segmentation-
util/evaluation.py
0b43fc9a9ff93f5e76021d3c
function
simple
val=1, dtype=tf.float32) return (example_input, (example_target_phons, example_target_mask)) def generate_fake_batch( batch_size: int, channels=83, bins=1024, ) -> List[Tuple[tf.Tensor, Tuple[tf.Tensor, tf.Tensor]]]:
example_batch = [] for _ in range(batch_size): input_example, ( target_phons_example, target_mask_example) = generate_fake_example( channels=channels, bins=bins) input_example = tf.expand_dims(input_example, axis=0) target_phons_example = tf.expand_dims(target_phons_example, axis=0) ...
def generate_fake_batch( batch_size: int, channels=83, bins=1024, ) -> List[Tuple[tf.Tensor, Tuple[tf.Tensor, tf.Tensor]]]: example_batch = [] for _ in range(batch_size): input_example, ( target_phons_example, target_mask_example) = generate_fake_example( channels=channels, bins=bins) ...
Xtuden-com/korvapuusti
listening_test_summer_2020/modelling/end_to_end_model/neural_model/test_helpers.py
903e859d625006b8f8af186d
function
simple
type(s)) if PY2 and isinstance(s, text_type): s = s.encode(encoding, errors) elif PY3 and isinstance(s, binary_type): s = s.decode(encoding, errors) return s def ensure_text(s, encoding="utf-8", errors="strict"):
"""Coerce *s* to six.text_type. For Python 2: - `unicode` -> `unicode` - `str` -> `unicode` For Python 3: - `str` -> `str` - `bytes` -> decoded to `str` """ if isinstance(s, binary_type): return s.decode(encoding, errors) elif isinstance(s, text_type): r...
def ensure_text(s, encoding="utf-8", errors="strict"): """Coerce *s* to six.text_type. For Python 2: - `unicode` -> `unicode` - `str` -> `unicode` For Python 3: - `str` -> `str` - `bytes` -> decoded to `str` """ if isinstance(s, binary_type): return s.decode(encodin...
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
7b35902f68453b027bb2ea35
function
simple
""" if isinstance(s, text_type): return s.encode(encoding, errors) elif isinstance(s, binary_type): return s else: raise TypeError("not expecting type '%s'" % type(s)) def ensure_str(s, encoding="utf-8", errors="strict"):
"""Coerce *s* to `str`. For Python 2: - `unicode` -> encoded to `str` - `str` -> `str` For Python 3: - `str` -> `str` - `bytes` -> decoded to `str` """ if not isinstance(s, (text_type, binary_type)): raise TypeError("not expecting type '%s'" % type(s)) if PY2 an...
def ensure_str(s, encoding="utf-8", errors="strict"): """Coerce *s* to `str`. For Python 2: - `unicode` -> encoded to `str` - `str` -> `str` For Python 3: - `str` -> `str` - `bytes` -> decoded to `str` """ if not isinstance(s, (text_type, binary_type)): raise TypeEr...
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
bd5b8a9613c5205c1e066287
function
simple
.urllib_robotparser") def __dir__(self): return ["parse", "error", "request", "response", "robotparser"] _importer._add_module( Module_six_moves_urllib(__name__ + ".moves.urllib"), "moves.urllib" ) def add_move(move):
"""Add an item to six.moves.""" setattr(_MovedItems, move.name, move)
def add_move(move): """Add an item to six.moves.""" setattr(_MovedItems, move.name, move)
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
838a27d5ee9e6313b6270deb
function
simple
Equal(self, *args, **kwargs): return getattr(self, _assertCountEqual)(*args, **kwargs) def assertRaisesRegex(self, *args, **kwargs): return getattr(self, _assertRaisesRegex)(*args, **kwargs) def assertRegex(self, *args, **kwargs):
return getattr(self, _assertRegex)(*args, **kwargs)
def assertRegex(self, *args, **kwargs): return getattr(self, _assertRegex)(*args, **kwargs)
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
eb7305e335169287e7a80182
function
simple
= "assertRegexpMatches" _add_doc(b, """Byte literal""") _add_doc(u, """Text literal""") def assertCountEqual(self, *args, **kwargs): return getattr(self, _assertCountEqual)(*args, **kwargs) def assertRaisesRegex(self, *args, **kwargs):
return getattr(self, _assertRaisesRegex)(*args, **kwargs)
def assertRaisesRegex(self, *args, **kwargs): return getattr(self, _assertRaisesRegex)(*args, **kwargs)
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
52c59c2ee045081efc58fa09
function
simple
weakref__", None) if hasattr(cls, "__qualname__"): orig_vars["__qualname__"] = cls.__qualname__ return metaclass(cls.__name__, cls.__bases__, orig_vars) return wrapper def ensure_binary(s, encoding="utf-8", errors="strict"):
"""Coerce **s** to six.binary_type. For Python 2: - `unicode` -> encoded to `str` - `str` -> `str` For Python 3: - `str` -> encoded to `bytes` - `bytes` -> `bytes` """ if isinstance(s, text_type): return s.encode(encoding, errors) elif isinstance(s, binary_type)...
def ensure_binary(s, encoding="utf-8", errors="strict"): """Coerce **s** to six.binary_type. For Python 2: - `unicode` -> encoded to `str` - `str` -> `str` For Python 3: - `str` -> encoded to `bytes` - `bytes` -> `bytes` """ if isinstance(s, text_type): return s.enc...
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
39427e09dfd55fc72c7c204e
function
simple
decoded to `str` """ if isinstance(s, binary_type): return s.decode(encoding, errors) elif isinstance(s, text_type): return s else: raise TypeError("not expecting type '%s'" % type(s)) def python_2_unicode_compatible(klass):
""" A decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. To support Python 2 and 3 with a single code base, define a __str__ method returning text and apply this decorator to the class. """ if PY2: if "__str__" not in klass.__dict_...
def python_2_unicode_compatible(klass): """ A decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. To support Python 2 and 3 with a single code base, define a __str__ method returning text and apply this decorator to the class. """ if PY2: ...
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
c8d052b4f89bf310a7568f5b
function
simple
(X()) except OverflowError: # 32-bit MAXSIZE = int((1 << 31) - 1) else: # 64-bit MAXSIZE = int((1 << 63) - 1) del X def _add_doc(func, doc):
"""Add documentation to a function.""" func.__doc__ = doc
def _add_doc(func, doc): """Add documentation to a function.""" func.__doc__ = doc
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
5632f7ac38ad3183a9fe7d6d
function
simple
", "robotparser"] _importer._add_module( Module_six_moves_urllib(__name__ + ".moves.urllib"), "moves.urllib" ) def add_move(move): """Add an item to six.moves.""" setattr(_MovedItems, move.name, move) def remove_move(name):
"""Remove item from six.moves.""" try: delattr(_MovedItems, name) except AttributeError: try: del moves.__dict__[name] except KeyError: raise AttributeError("no such move, %r" % (name,))
def remove_move(name): """Remove item from six.moves.""" try: delattr(_MovedItems, name) except AttributeError: try: del moves.__dict__[name] except KeyError: raise AttributeError("no such move, %r" % (name,))
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
ec09a13a489444b23f45beb3
function
simple
IO _assertCountEqual = "assertItemsEqual" _assertRaisesRegex = "assertRaisesRegexp" _assertRegex = "assertRegexpMatches" _add_doc(b, """Byte literal""") _add_doc(u, """Text literal""") def assertCountEqual(self, *args, **kwargs):
return getattr(self, _assertCountEqual)(*args, **kwargs)
def assertCountEqual(self, *args, **kwargs): return getattr(self, _assertCountEqual)(*args, **kwargs)
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
77a9c9ca696bbd3d37597ba3
function
simple
31) - 1) else: # 64-bit MAXSIZE = int((1 << 63) - 1) del X def _add_doc(func, doc): """Add documentation to a function.""" func.__doc__ = doc def _import_module(name):
"""Import module, returning the module after the last dot.""" __import__(name) return sys.modules[name]
def _import_module(name): """Import module, returning the module after the last dot.""" __import__(name) return sys.modules[name]
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
224d6fdf56f3ac9c2a9c0544
function
simple
ases, d): return meta(name, bases, d) @classmethod def __prepare__(cls, name, this_bases): return meta.__prepare__(name, bases) return type.__new__(metaclass, "temporary_class", (), {}) def add_metaclass(metaclass):
"""Class decorator for creating a class with a metaclass.""" def wrapper(cls): orig_vars = cls.__dict__.copy() slots = orig_vars.get("__slots__") if slots is not None: if isinstance(slots, str): slots = [slots] for slots_var in slots: ...
def add_metaclass(metaclass): """Class decorator for creating a class with a metaclass.""" def wrapper(cls): orig_vars = cls.__dict__.copy() slots = orig_vars.get("__slots__") if slots is not None: if isinstance(slots, str): slots = [slots] for sl...
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
07433ba7a17c945822e6b55c
function
simple
functools.WRAPPER_UPDATES, ): def wrapper(f): f = functools.wraps(wrapped, assigned, updated)(f) f.__wrapped__ = wrapped return f return wrapper else: wraps = functools.wraps def with_metaclass(meta, *bases):
"""Create a base class with a metaclass.""" # This requires a bit of explanation: the basic idea is to make a dummy # metaclass for one level of class instantiation that replaces itself with # the actual metaclass. class metaclass(type): def __new__(cls, name, this_bases, d): ret...
def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" # This requires a bit of explanation: the basic idea is to make a dummy # metaclass for one level of class instantiation that replaces itself with # the actual metaclass. class metaclass(type): def __new__(cls, nam...
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
3be4f4c4427650ca566bc656
function
simple
) # seconds # context.driver.set_window_size(1200, 600) context.base_url = BASE_URL # -- SET LOG LEVEL: behave --logging-level=ERROR ... # on behave command-line or in "behave.ini" context.config.setup_logging() def after_all(context):
""" Executed after all tests """ context.driver.quit()
def after_all(context): """ Executed after all tests """ context.driver.quit()
nyu-devops-shopcarts/shopcarts
features/environment.py
ef1a041852a2be10773d5596
function
simple
status = '200 OK' headers = [('Content-type', 'text/plain')] start_response(status, headers) ret = ["%s: %s\n" % (key, value) for key, value in environ.iteritems()] return ret def sitemap_app(environ, start_response):
status = '200 OK' headers = [('Content-type', 'text/plain')] start_response(status, headers) requested_url = environ['PATH_INFO'] if requested_url == '/sleep': time.sleep(2) response = 'Done' else: response = sitemap_app.sitemap.get(requested_url) log.debug('Request...
def sitemap_app(environ, start_response): status = '200 OK' headers = [('Content-type', 'text/plain')] start_response(status, headers) requested_url = environ['PATH_INFO'] if requested_url == '/sleep': time.sleep(2) response = 'Done' else: response = sitemap_app.sitemap...
ahlinc/pomp
tests/mockserver.py
28be5cf22156129bb1fced13
function
simple
response) try: ret = [json.dumps(response).encode('utf-8')] except Exception: log.exception("bla-bla") log.debug('Requested url: %s, ret: %s', requested_url, ret) return ret def make_reponse_body(items, links):
return { 'items': items, 'links': links, }
def make_reponse_body(items, links): return { 'items': items, 'links': links, }
ahlinc/pomp
tests/mockserver.py
e45817a3dc82bb44d830a98f
function
simple
%s, ret: %s', requested_url, ret) return ret def make_reponse_body(items, links): return { 'items': items, 'links': links, } def make_sitemap(level=3, links_on_page=3, sitemap=None, entry='/root'):
sitemap = sitemap if sitemap else {} if level == 0: return sitemap def make_entry(url, sitemap, links_on_page): sitemap.update({ url: make_reponse_body( ['a', 'b'], ['%s/%s' % (url, i) for i in range(0, links_on_page)], ) }) ...
def make_sitemap(level=3, links_on_page=3, sitemap=None, entry='/root'): sitemap = sitemap if sitemap else {} if level == 0: return sitemap def make_entry(url, sitemap, links_on_page): sitemap.update({ url: make_reponse_body( ['a', 'b'], ['%s/%s' ...
ahlinc/pomp
tests/mockserver.py
f50eed5646f8e7a1c33c237a
function
simple
sys.stderr = self._stdout, self._stderr def __exit__(self, exc_type, exc_value, traceback): self._stdout.flush() self._stderr.flush() sys.stdout = self.old_stdout sys.stderr = self.old_stderr def simple_app(environ, start_response):
setup_testing_defaults(environ) status = '200 OK' headers = [('Content-type', 'text/plain')] start_response(status, headers) ret = ["%s: %s\n" % (key, value) for key, value in environ.iteritems()] return ret
def simple_app(environ, start_response): setup_testing_defaults(environ) status = '200 OK' headers = [('Content-type', 'text/plain')] start_response(status, headers) ret = ["%s: %s\n" % (key, value) for key, value in environ.iteritems()] return ret
ahlinc/pomp
tests/mockserver.py
afd4d5e24037dd985da7919e
function
simple
def HATT(max_byte_size=33554432, memory_estimate_period=1000000, grace_period=200, min_samples_reevaluate=20, split_criterion='info_gain', split_confidence=0.0000001, tie_threshold=0.05, binary_split=False, stop_mem_management=False, leaf_prediction='nba', nb_threshold=0, nominal_attributes=None): # ...
warnings.warn("'HATT' has been renamed to 'ExtremelyFastDecisionTreeClassifier' in v0.5.0.\n" "The old name will be removed in v0.7.0", category=FutureWarning) return ExtremelyFastDecisionTreeClassifier(max_byte_size=max_byte_size, memory_estimate...
def HATT(max_byte_size=33554432, memory_estimate_period=1000000, grace_period=200, min_samples_reevaluate=20, split_criterion='info_gain', split_confidence=0.0000001, tie_threshold=0.05, binary_split=False, stop_mem_management=False, leaf_prediction='nba', nb_threshold=0, nominal_attributes=None): # ...
imran-salim/scikit-multiflow
src/skmultiflow/trees/extremely_fast_decision_tree.py
3eaf5aeea26b5aaffa3e044e
function
simple
1]) return zp def get_LM_Pos_from_state(x, ind): lm = x[STATE_SIZE + LM_SIZE * ind: STATE_SIZE + LM_SIZE * (ind + 1), :] return lm def search_correspond_LM_ID(xAug, PAug, zi):
""" Landmark association with Mahalanobis distance """ nLM = calc_n_LM(xAug) mdist = [] for i in range(nLM): lm = get_LM_Pos_from_state(xAug, i) y, S, H = calc_innovation(lm, xAug, PAug, zi, i) mdist.append(y.T @ np.linalg.inv(S) @ y) mdist.append(M_DIST_TH) # ne...
def search_correspond_LM_ID(xAug, PAug, zi): """ Landmark association with Mahalanobis distance """ nLM = calc_n_LM(xAug) mdist = [] for i in range(nLM): lm = get_LM_Pos_from_state(xAug, i) y, S, H = calc_innovation(lm, xAug, PAug, zi, i) mdist.append(y.T @ np.linalg.i...
takayuki5168/PythonRobotics
SLAM/EKFSLAM/ekf_slam.py
c5039d2d0d236eeb23cc1c63
function
simple
u[0] * math.cos(x[2, 0])], [0.0, 0.0, 0.0]]) G = np.eye(STATE_SIZE) + Fx.T * jF * Fx return G, Fx, def calc_LM_Pos(x, z):
zp = np.zeros((2, 1)) zp[0, 0] = x[0, 0] + z[0] * math.cos(x[2, 0] + z[1]) zp[1, 0] = x[1, 0] + z[0] * math.sin(x[2, 0] + z[1]) #zp[0, 0] = x[0, 0] + z[0, 0] * math.cos(x[2, 0] + z[0, 1]) #zp[1, 0] = x[1, 0] + z[0, 0] * math.sin(x[2, 0] + z[0, 1]) return zp
def calc_LM_Pos(x, z): zp = np.zeros((2, 1)) zp[0, 0] = x[0, 0] + z[0] * math.cos(x[2, 0] + z[1]) zp[1, 0] = x[1, 0] + z[0] * math.sin(x[2, 0] + z[1]) #zp[0, 0] = x[0, 0] + z[0, 0] * math.cos(x[2, 0] + z[0, 1]) #zp[1, 0] = x[1, 0] + z[0, 0] * math.sin(x[2, 0] + z[0, 1]) return zp
takayuki5168/PythonRobotics
SLAM/EKFSLAM/ekf_slam.py
2d437a4ff3273382edc59920
function
simple
i) mdist.append(y.T @ np.linalg.inv(S) @ y) mdist.append(M_DIST_TH) # new landmark minid = mdist.index(min(mdist)) return minid def calc_innovation(lm, xEst, PEst, z, LMid):
delta = lm - xEst[0:2] q = (delta.T @ delta)[0, 0] zangle = math.atan2(delta[1, 0], delta[0, 0]) - xEst[2, 0] zp = np.array([[math.sqrt(q), pi_2_pi(zangle)]]) y = (z - zp).T y[1] = pi_2_pi(y[1]) H = jacobH(q, delta, xEst, LMid + 1) S = H @ PEst @ H.T + Cx[0:2, 0:2] return y, S, H
def calc_innovation(lm, xEst, PEst, z, LMid): delta = lm - xEst[0:2] q = (delta.T @ delta)[0, 0] zangle = math.atan2(delta[1, 0], delta[0, 0]) - xEst[2, 0] zp = np.array([[math.sqrt(q), pi_2_pi(zangle)]]) y = (z - zp).T y[1] = pi_2_pi(y[1]) H = jacobH(q, delta, xEst, LMid + 1) S = H @ PE...
takayuki5168/PythonRobotics
SLAM/EKFSLAM/ekf_slam.py
9aee475d0df6824c8b038ce7
function
simple
.inv(S) xEst = xEst + (K @ y) PEst = (np.eye(len(xEst)) - (K @ H)) @ PEst xEst[2] = pi_2_pi(xEst[2]) return xEst, PEst def calc_input():
v = 1.0 # [m/s] yawrate = 0.1 # [rad/s] u = np.array([[v, yawrate]]).T return u
def calc_input(): v = 1.0 # [m/s] yawrate = 0.1 # [rad/s] u = np.array([[v, yawrate]]).T return u
takayuki5168/PythonRobotics
SLAM/EKFSLAM/ekf_slam.py
aa13b7b2a8a12c04c9cfee7e
function
simple
(y[1]) H = jacobH(q, delta, xEst, LMid + 1) S = H @ PEst @ H.T + Cx[0:2, 0:2] return y, S, H def jacobH(q, delta, x, i):
sq = math.sqrt(q) G = np.array([[-sq * delta[0, 0], - sq * delta[1, 0], 0, sq * delta[0, 0], sq * delta[1, 0]], [delta[1, 0], - delta[0, 0], - 1.0, - delta[1, 0], delta[0, 0]]]) G = G / q nLM = calc_n_LM(x) F1 = np.hstack((np.eye(3), np.zeros((3, 2 * nLM)))) F2 = np.hstack((np...
def jacobH(q, delta, x, i): sq = math.sqrt(q) G = np.array([[-sq * delta[0, 0], - sq * delta[1, 0], 0, sq * delta[0, 0], sq * delta[1, 0]], [delta[1, 0], - delta[0, 0], - 1.0, - delta[1, 0], delta[0, 0]]]) G = G / q nLM = calc_n_LM(x) F1 = np.hstack((np.eye(3), np.zeros((3, 2 * nL...
takayuki5168/PythonRobotics
SLAM/EKFSLAM/ekf_slam.py
ff37468fef6b746d2bcced7a
function
simple
2 DT = 0.1 # time tick [s] SIM_TIME = 50.0 # simulation time [s] MAX_RANGE = 20.0 # maximum observation range M_DIST_TH = 2.0 # Threshold of Mahalanobis distance for data association. STATE_SIZE = 3 # State size [x,y,yaw] LM_SIZE = 2 # LM state size [x,y] show_animation = True def ekf_slam(xEst, PEst, u, z): ...
S = STATE_SIZE xEst[0:S] = motion_model(xEst[0:S], u) G, Fx = jacob_motion(xEst[0:S], u) PEst[0:S, 0:S] = G.T * PEst[0:S, 0:S] * G + Fx.T * Cx * Fx initP = np.eye(2) # Update for iz in range(len(z[:, 0])): # for each observation minid = search_correspond_LM_ID(xEst, PEst, z[iz, 0:2...
def ekf_slam(xEst, PEst, u, z): # Predict S = STATE_SIZE xEst[0:S] = motion_model(xEst[0:S], u) G, Fx = jacob_motion(xEst[0:S], u) PEst[0:S, 0:S] = G.T * PEst[0:S, 0:S] * G + Fx.T * Cx * Fx initP = np.eye(2) # Update for iz in range(len(z[:, 0])): # for each observation minid ...
takayuki5168/PythonRobotics
SLAM/EKFSLAM/ekf_slam.py
a9c1943c9e8e57781f87d45c
function
simple
G / q nLM = calc_n_LM(x) F1 = np.hstack((np.eye(3), np.zeros((3, 2 * nLM)))) F2 = np.hstack((np.zeros((2, 3)), np.zeros((2, 2 * (i - 1))), np.eye(2), np.zeros((2, 2 * nLM - 2 * i)))) F = np.vstack((F1, F2)) H = G @ F return H def pi_2_pi(angle): return (angle + math...
print(__file__ + " start!!") time = 0.0 # RFID positions [x, y] RFID = np.array([[10.0, -2.0], [15.0, 10.0], [3.0, 15.0], [-5.0, 20.0]]) # State Vector [x y yaw v]' xEst = np.zeros((STATE_SIZE, 1)) xTrue = np.zeros((STATE_SIZE...
def main(): print(__file__ + " start!!") time = 0.0 # RFID positions [x, y] RFID = np.array([[10.0, -2.0], [15.0, 10.0], [3.0, 15.0], [-5.0, 20.0]]) # State Vector [x y yaw v]' xEst = np.zeros((STATE_SIZE, 1)) xTrue = np.zeros...
takayuki5168/PythonRobotics
SLAM/EKFSLAM/ekf_slam.py
2f5cc4114b6246fe6779cded
function
simple
([[DT * math.cos(x[2, 0]), 0], [DT * math.sin(x[2, 0]), 0], [0.0, DT]]) x = (F @ x) + (B @ u) return x def calc_n_LM(x):
n = int((len(x) - STATE_SIZE) / LM_SIZE) return n
def calc_n_LM(x): n = int((len(x) - STATE_SIZE) / LM_SIZE) return n
takayuki5168/PythonRobotics
SLAM/EKFSLAM/ekf_slam.py
7e507578587551412140e8fa
function
simple
.randn() * Rsim[0, 0], u[1, 0] + np.random.randn() * Rsim[1, 1]]]).T xd = motion_model(xd, ud) return xTrue, z, xd, ud def motion_model(x, u):
F = np.array([[1.0, 0, 0], [0, 1.0, 0], [0, 0, 1.0]]) B = np.array([[DT * math.cos(x[2, 0]), 0], [DT * math.sin(x[2, 0]), 0], [0.0, DT]]) x = (F @ x) + (B @ u) return x
def motion_model(x, u): F = np.array([[1.0, 0, 0], [0, 1.0, 0], [0, 0, 1.0]]) B = np.array([[DT * math.cos(x[2, 0]), 0], [DT * math.sin(x[2, 0]), 0], [0.0, DT]]) x = (F @ x) + (B @ u) return x
takayuki5168/PythonRobotics
SLAM/EKFSLAM/ekf_slam.py
07c0d37e6455da054ad71740
function
simple
((2, 2 * (i - 1))), np.eye(2), np.zeros((2, 2 * nLM - 2 * i)))) F = np.vstack((F1, F2)) H = G @ F return H def pi_2_pi(angle):
return (angle + math.pi) % (2 * math.pi) - math.pi
def pi_2_pi(angle): return (angle + math.pi) % (2 * math.pi) - math.pi
takayuki5168/PythonRobotics
SLAM/EKFSLAM/ekf_slam.py
3ed00a84573e319ea00ba306
function
simple
Est xEst[2] = pi_2_pi(xEst[2]) return xEst, PEst def calc_input(): v = 1.0 # [m/s] yawrate = 0.1 # [rad/s] u = np.array([[v, yawrate]]).T return u def observation(xTrue, xd, u, RFID):
xTrue = motion_model(xTrue, u) # add noise to gps x-y z = np.zeros((0, 3)) for i in range(len(RFID[:, 0])): dx = RFID[i, 0] - xTrue[0, 0] dy = RFID[i, 1] - xTrue[1, 0] d = math.sqrt(dx**2 + dy**2) angle = pi_2_pi(math.atan2(dy, dx) - xTrue[2, 0]) if d <= MAX_RA...
def observation(xTrue, xd, u, RFID): xTrue = motion_model(xTrue, u) # add noise to gps x-y z = np.zeros((0, 3)) for i in range(len(RFID[:, 0])): dx = RFID[i, 0] - xTrue[0, 0] dy = RFID[i, 1] - xTrue[1, 0] d = math.sqrt(dx**2 + dy**2) angle = pi_2_pi(math.atan2(dy, dx)...
takayuki5168/PythonRobotics
SLAM/EKFSLAM/ekf_slam.py
02e13c6b8f37c9f3953aaed1
function
simple
0], [0.0, DT]]) x = (F @ x) + (B @ u) return x def calc_n_LM(x): n = int((len(x) - STATE_SIZE) / LM_SIZE) return n def jacob_motion(x, u):
Fx = np.hstack((np.eye(STATE_SIZE), np.zeros( (STATE_SIZE, LM_SIZE * calc_n_LM(x))))) jF = np.array([[0.0, 0.0, -DT * u[0] * math.sin(x[2, 0])], [0.0, 0.0, DT * u[0] * math.cos(x[2, 0])], [0.0, 0.0, 0.0]]) G = np.eye(STATE_SIZE) + Fx.T * jF * Fx return G,...
def jacob_motion(x, u): Fx = np.hstack((np.eye(STATE_SIZE), np.zeros( (STATE_SIZE, LM_SIZE * calc_n_LM(x))))) jF = np.array([[0.0, 0.0, -DT * u[0] * math.sin(x[2, 0])], [0.0, 0.0, DT * u[0] * math.cos(x[2, 0])], [0.0, 0.0, 0.0]]) G = np.eye(STATE_SIZE) + Fx.T...
takayuki5168/PythonRobotics
SLAM/EKFSLAM/ekf_slam.py
3803e5c82743f67fb1d64573
function
simple
[0, 1]) #zp[1, 0] = x[1, 0] + z[0, 0] * math.sin(x[2, 0] + z[0, 1]) return zp def get_LM_Pos_from_state(x, ind):
lm = x[STATE_SIZE + LM_SIZE * ind: STATE_SIZE + LM_SIZE * (ind + 1), :] return lm
def get_LM_Pos_from_state(x, ind): lm = x[STATE_SIZE + LM_SIZE * ind: STATE_SIZE + LM_SIZE * (ind + 1), :] return lm
takayuki5168/PythonRobotics
SLAM/EKFSLAM/ekf_slam.py
eb8a65f7efebbc0d3caa966f
function
simple
ester=icsr_semester, **kwargs, ) @staticmethod def create_user(**kwargs): default_kwargs = { "username": "default username", } kwargs = {**default_kwargs, **kwargs} return User.objects.create(**kwargs) def login_user(test_cls):
user = ModelFactory.create_user() password = "custom password" user.set_password(password) user.save() group = Group(name="officer") group.save() group.user_set.add(user) group.save() test_cls.client.login(username=user.username, password=password)
def login_user(test_cls): user = ModelFactory.create_user() password = "custom password" user.set_password(password) user.save() group = Group(name="officer") group.save() group.user_set.add(user) group.save() test_cls.client.login(username=user.username, password=password)
jyxzhang/hknweb
hknweb/academics/tests/utils.py
3d158063f17070436ef011fe
function
simple
of training losses at the end of each training epoch." np_losses = [to_np(l).item() for l in learn.recorder.losses] batch_size = len(learn.data.train_dl) return [batch[-1] for batch in partition(np_losses, batch_size)] def itemize(metrics):
return [m.item() for m in metrics]
def itemize(metrics): return [m.item() for m in metrics]
jeffrwells/fastai
tests/test_callbacks_csv_logger.py
a2d4e7f2b1894cd7f98f15a9
function
simple
_less_precise=True (or better =3), until then using =2 as it works, but this check is less good. pd.testing.assert_frame_equal(csv_df, recorder_df, check_exact=False, check_less_precise=2) @pytest.fixture(scope="module", autouse=True) def cleanup(request):
"""Cleanup the autogenerated file once we are finished.""" def remove_history_csv(): file = "history.csv" if os.path.exists(file): os.remove(file) request.addfinalizer(remove_history_csv)
@pytest.fixture(scope="module", autouse=True) def cleanup(request): """Cleanup the autogenerated file once we are finished.""" def remove_history_csv(): file = "history.csv" if os.path.exists(file): os.remove(file) request.addfinalizer(remove_history_csv)
jeffrwells/fastai
tests/test_callbacks_csv_logger.py
fe4738dc6959880838e4df1d
function
simple
line.split()[:-1]] for line in lines] records = [dict(zip(header, metrics_list)) for metrics_list in floats] df = pd.DataFrame(records, columns=header) df['epoch'] = df['epoch'].astype(int) return df def get_train_losses(learn):
"Returns list of training losses at the end of each training epoch." np_losses = [to_np(l).item() for l in learn.recorder.losses] batch_size = len(learn.data.train_dl) return [batch[-1] for batch in partition(np_losses, batch_size)]
def get_train_losses(learn): "Returns list of training losses at the end of each training epoch." np_losses = [to_np(l).item() for l in learn.recorder.losses] batch_size = len(learn.data.train_dl) return [batch[-1] for batch in partition(np_losses, batch_size)]
jeffrwells/fastai
tests/test_callbacks_csv_logger.py
9c9846400060f2dac2cc1340
function
simple
)] for i, (loss, val_loss, epoch_metrics) in enumerate(zip( get_train_losses(learn), learn.recorder.val_losses, learn.recorder.metrics), 1)] return pd.DataFrame(records, columns=learn.recorder.names[:-1]) def convert_into_dataframe(buffer):
"Converts data captured from `fastprogress.ConsoleProgressBar` into dataframe." lines = buffer.split('\n') header, *lines = [l.strip() for l in lines if l and not l.startswith('Total')] header = header.split()[:-1] floats = [[float(x) for x in line.split()[:-1]] for line in lines] records = [dic...
def convert_into_dataframe(buffer): "Converts data captured from `fastprogress.ConsoleProgressBar` into dataframe." lines = buffer.split('\n') header, *lines = [l.strip() for l in lines if l and not l.startswith('Total')] header = header.split()[:-1] floats = [[float(x) for x in line.split()[:-1]] f...
jeffrwells/fastai
tests/test_callbacks_csv_logger.py
73eb738aa83d0a6b83c8d65d
function
simple
np_losses = [to_np(l).item() for l in learn.recorder.losses] batch_size = len(learn.data.train_dl) return [batch[-1] for batch in partition(np_losses, batch_size)] def itemize(metrics): return [m.item() for m in metrics] def test_logger():
learn = fake_learner() learn.metrics = [accuracy, error_rate] learn.callback_fns.append(callbacks.CSVLogger) with CaptureStdout() as cs: learn.fit_one_cycle(3) csv_df = learn.csv_logger.read_logged_file() stdout_df = convert_into_dataframe(cs.out) csv_df.drop(columns=['time'], axis=1, inplac...
def test_logger(): learn = fake_learner() learn.metrics = [accuracy, error_rate] learn.callback_fns.append(callbacks.CSVLogger) with CaptureStdout() as cs: learn.fit_one_cycle(3) csv_df = learn.csv_logger.read_logged_file() stdout_df = convert_into_dataframe(cs.out) csv_df.drop(columns=['tim...
jeffrwells/fastai
tests/test_callbacks_csv_logger.py
5a1c9ed79fc82f32da3867af
function
simple
(fake_cmd_from_conftest['_ver_nice']['COMMAND_OUTPUT'], str) assert isinstance(fake_cmd_from_conftest['_ver_nice']['COMMAND_KWARGS'], dict) assert isinstance(fake_cmd_from_conftest['_ver_nice']['COMMAND_RESULT'], dict) def test_validate_documentation_existence():
from moler.util.cmds_events_doc import _validate_documentation_existence fake_cmd = import_module('conftest') test_data = {'_ver_execute': {'COMMAND_OUTPUT': '', 'COMMAND_KWARGS': {}, 'COMMAND_RESULT': {}}, '_ver_test': {'COMMAND_OUTPUT': '', 'COMMAND_KWARGS': {}, 'COMMAND_RESULT': {}}} ...
def test_validate_documentation_existence(): from moler.util.cmds_events_doc import _validate_documentation_existence fake_cmd = import_module('conftest') test_data = {'_ver_execute': {'COMMAND_OUTPUT': '', 'COMMAND_KWARGS': {}, 'COMMAND_RESULT': {}}, '_ver_test': {'COMMAND_OUTPUT': '', 'C...
carr-elagheb/moler
test/test_cmds_events_doc.py
f0e782e890944e0cc51c8f01
function
simple
_variant(test_data, '_ver_test2', "COMMAND") assert result1 == ('out1', {1: 1}, {1: 1}) assert result2 == ('out2', {}, {2: 2}) def test_create_command_raise_exception_when_object_takes_no_params(fake_cmd):
from moler.util.cmds_events_doc import _create_command, _buffer_connection with raises(Exception) as exc: _create_command(fake_cmd, _buffer_connection().moler_connection, {}) assert "via FakeCommand() : object() takes no parameters" or "via FakeCommand() : this constructor takes no arguments" in s...
def test_create_command_raise_exception_when_object_takes_no_params(fake_cmd): from moler.util.cmds_events_doc import _create_command, _buffer_connection with raises(Exception) as exc: _create_command(fake_cmd, _buffer_connection().moler_connection, {}) assert "via FakeCommand() : object() takes n...
carr-elagheb/moler
test/test_cmds_events_doc.py
74eaaa4b845518ee463d0f4d
function
simple
_list = [f for root, dirs, files in walk(abs_test_path) for f in files if isfile(join(root, f)) and '__init__' not in f and '.pyc' not in f and f.endswith('.py')] return file_list def _load_obj(func_name):
""" Load instance from module. :param func_name: function name as string :return: object instance :rtype: type """ return getattr(import_module('moler.util.cmds_events_doc'), func_name)
def _load_obj(func_name): """ Load instance from module. :param func_name: function name as string :return: object instance :rtype: type """ return getattr(import_module('moler.util.cmds_events_doc'), func_name)
carr-elagheb/moler
test/test_cmds_events_doc.py
891919fd8933081d1fad9cbb
function
simple
""" Load instance from module. :param func_name: function name as string :return: object instance :rtype: type """ return getattr(import_module('moler.util.cmds_events_doc'), func_name) # --------------- helper functions --------------- def test_documentation_exists():
from moler.util.cmds_events_doc import check_if_documentation_exists dir_path = path.dirname(path.realpath(__file__)) moler_dir_path = path.dirname(dir_path) cmd_path = path.join(moler_dir_path, "moler", "cmd") events_path = path.join(moler_dir_path, "moler", "events") assert check_if_document...
def test_documentation_exists(): from moler.util.cmds_events_doc import check_if_documentation_exists dir_path = path.dirname(path.realpath(__file__)) moler_dir_path = path.dirname(dir_path) cmd_path = path.join(moler_dir_path, "moler", "cmd") events_path = path.join(moler_dir_path, "moler", "event...
carr-elagheb/moler
test/test_cmds_events_doc.py
80f670d789556f43ce3926e6
function
simple
@mark.parametrize('func2test,method_param,base_class, expected', [ ('_walk_moler_python_files', cmd_dir_under_test, "COMMAND", True), ('_walk_moler_commands', cmd_dir_under_test, Command, True), ('_walk_moler_nonabstract_commands', cmd_dir_under_test, Command, True)]) def test_functions_are_generators(func2...
from inspect import isgenerator, isgeneratorfunction func_obj = _load_obj(func_name=func2test) generator_obj = func_obj(method_param, base_class) assert isgeneratorfunction(func_obj) is expected assert isgenerator(generator_obj) is expected
@mark.parametrize('func2test,method_param,base_class, expected', [ ('_walk_moler_python_files', cmd_dir_under_test, "COMMAND", True), ('_walk_moler_commands', cmd_dir_under_test, Command, True), ('_walk_moler_nonabstract_commands', cmd_dir_under_test, Command, True)]) def test_functions_are_generators(func2...
carr-elagheb/moler
test/test_cmds_events_doc.py
51afb10c37ded1a13c91c137
function
simple
, "moler", "cmd") events_path = path.join(moler_dir_path, "moler", "events") assert check_if_documentation_exists(cmd_path) is True assert check_if_documentation_exists(events_path) is True def test_buffer_connection_returns_threadconnection_with_moler_conn():
from moler.io.raw.memory import ThreadedFifoBuffer from moler.observable_connection import ObservableConnection from moler.util.cmds_events_doc import _buffer_connection buff_conn = _buffer_connection() assert isinstance(buff_conn, ThreadedFifoBuffer) is True assert isinstance(buff_conn.moler_c...
def test_buffer_connection_returns_threadconnection_with_moler_conn(): from moler.io.raw.memory import ThreadedFifoBuffer from moler.observable_connection import ObservableConnection from moler.util.cmds_events_doc import _buffer_connection buff_conn = _buffer_connection() assert isinstance(buff_co...
carr-elagheb/moler
test/test_cmds_events_doc.py
9824e10de59142c4ef4433b5
function
simple
_ver_test2' in result2[1] assert '> has COMMAND_OUTPUT_ver_test3 but no COMMAND_RESULT_ver_test3' in result3[0] assert '> has COMMAND_KWARGS_ver_test3 but no COMMAND_RESULT_ver_test3' in result3[1] def test_get_doc_variant():
from moler.util.cmds_events_doc import _get_doc_variant test_data = {'_ver_test1': {'COMMAND_OUTPUT': 'out1', 'COMMAND_KWARGS': {1: 1}, 'COMMAND_RESULT': {1: 1}}, '_ver_test2': {'COMMAND_OUTPUT': 'out2', 'COMMAND_RESULT': {2: 2}}} result1 = _get_doc_variant(test_data, '_ver_test1', "COMMAN...
def test_get_doc_variant(): from moler.util.cmds_events_doc import _get_doc_variant test_data = {'_ver_test1': {'COMMAND_OUTPUT': 'out1', 'COMMAND_KWARGS': {1: 1}, 'COMMAND_RESULT': {1: 1}}, '_ver_test2': {'COMMAND_OUTPUT': 'out2', 'COMMAND_RESULT': {2: 2}}} result1 = _get_doc_variant(test...
carr-elagheb/moler
test/test_cmds_events_doc.py
b6e6b88e035a4829c17c1b6c
function
simple
) generator_obj = func_obj(method_param, base_class) file_list = _list_in_path(listing_type='allfiles') with raises(StopIteration): for _ in range(len(file_list)): next(generator_obj) def test_walk_moler_nonabstract_commands_raise_exception_when_called(fake_cmd):
from moler.util.cmds_events_doc import _walk_moler_nonabstract_commands with mock.patch('moler.util.cmds_events_doc._walk_moler_commands', return_value=(None, fake_cmd)): with raises(Exception): next(_walk_moler_nonabstract_commands(cmd_dir_under_test, Command))
def test_walk_moler_nonabstract_commands_raise_exception_when_called(fake_cmd): from moler.util.cmds_events_doc import _walk_moler_nonabstract_commands with mock.patch('moler.util.cmds_events_doc._walk_moler_commands', return_value=(None, fake_cmd)): with raises(Exception): next(_walk_moler...
carr-elagheb/moler
test/test_cmds_events_doc.py
5b676c9ddf4dd4d87c532ca7
function
simple
@mark.parametrize('func2test,method_param,base_class', [ ('_walk_moler_python_files', cmd_dir_under_test, Command), ('_walk_moler_commands', cmd_dir_under_test, Command), ('_walk_moler_nonabstract_commands', cmd_dir_under_test, Command)]) def test_genertors_return_files_without_dunder_init(func2test, method...
func_obj = _load_obj(func_name=func2test) generator_obj = func_obj(method_param, base_class) file_list = _list_in_path(listing_type='allfiles') with raises(StopIteration): for _ in range(len(file_list)): next(generator_obj)
@mark.parametrize('func2test,method_param,base_class', [ ('_walk_moler_python_files', cmd_dir_under_test, Command), ('_walk_moler_commands', cmd_dir_under_test, Command), ('_walk_moler_nonabstract_commands', cmd_dir_under_test, Command)]) def test_genertors_return_files_without_dunder_init(func2test, method...
carr-elagheb/moler
test/test_cmds_events_doc.py
e74b900a7428608c519bec43
function
simple
walk_moler_nonabstract_commands with mock.patch('moler.util.cmds_events_doc._walk_moler_commands', return_value=(None, fake_cmd)): with raises(Exception): next(_walk_moler_nonabstract_commands(cmd_dir_under_test, Command)) def test_retrieve_command_documentation_as_dict():
from moler.util.cmds_events_doc import _retrieve_command_documentation fake_cmd_from_conftest = _retrieve_command_documentation(import_module('conftest'), "COMMAND") assert isinstance(fake_cmd_from_conftest, dict) assert isinstance(fake_cmd_from_conftest['_ver_nice'], dict) assert isinstance(fake_c...
def test_retrieve_command_documentation_as_dict(): from moler.util.cmds_events_doc import _retrieve_command_documentation fake_cmd_from_conftest = _retrieve_command_documentation(import_module('conftest'), "COMMAND") assert isinstance(fake_cmd_from_conftest, dict) assert isinstance(fake_cmd_from_confte...
carr-elagheb/moler
test/test_cmds_events_doc.py
50d134e4f2f18ef85288214d
class
simple
prefix else "", own_keys ) ) def _recursive_check_keys(new_config, old_config, prefix=""): _check_keys(new_config, old_config, prefix) for k, v in new_config.items(): new_prefix = prefix + "/" + k if prefix else k # if isinstance(v, dict): # _recursive_check_ke...
""" This class aims to check whether user config exists if default config system, Mostly, Config is sampled from parameter space in PGDrive Besides, the value type will also be checked, but sometimes the value type is not unique (maybe Union[str, int]). For these <key, value> items, use Config["you...
class Config: """ This class aims to check whether user config exists if default config system, Mostly, Config is sampled from parameter space in PGDrive Besides, the value type will also be checked, but sometimes the value type is not unique (maybe Union[str, int]). For these <key, value> items, u...
decisionforce/pgdrive
pgdrive/utils/config.py
a5fea548b6b15fbb74a43290
class
simple
#!/usr/bin/python3 from __future__ import unicode_literals from adapt.intent import IntentBuilder from mycroft import MycroftSkill, intent_handler import youtube_dl from subprocess import Popen, DEVNULL, STDOUT, CalledProcessError from os import remove class YoutubedlSkill(MycroftSkill):
def __init__(self): super().__init__() self.proc = None self.vid = None self.queue = [] def initialize(self): my_setting = self.settings.get("my_setting") def play_vid(self): if self.proc is not None: self.stop() try: self.pro...
class YoutubedlSkill(MycroftSkill): def __init__(self): super().__init__() self.proc = None self.vid = None self.queue = [] def initialize(self): my_setting = self.settings.get("my_setting") def play_vid(self): if self.proc is not None: self.stop...
bosangeros/mycroft-youtubedl-skill
__init__.py
638ee517e1e6c81d8743daf6
class
simple
_size, self.exp_disk_size) if self.snapshot_count is not None: self.assertEqual(len(image_info.snapshots), self.snapshot_count) def test_qemu_img_info(self): img_info = self._initialize_img_info() if self.garbage_before_snapshot is True: img_info = img_info + ('blah ...
_file_format = [ ('qcow2', dict(file_format='qcow2')), ] _qcow2_cluster_size = [ ('65536', dict(cluster_size='65536', exp_cluster_size=65536)), ] _qcow2_encrypted = [ ('no_encryption', dict(encrypted=None)), ('encrypted', dict(encrypted='yes')), ] _qcow2_ba...
class ImageUtilsQemuTestCase(ImageUtilsRawTestCase): _file_format = [ ('qcow2', dict(file_format='qcow2')), ] _qcow2_cluster_size = [ ('65536', dict(cluster_size='65536', exp_cluster_size=65536)), ] _qcow2_encrypted = [ ('no_encryption', dict(encrypted=None)), ('en...
songhao8080/nova-client
venv/lib/python2.7/site-packages/oslo_utils/tests/test_imageutils.py
c5da39700ea65cf44a921a7d
class
simple
None: self.assertEqual(image_info.backing_file, self.exp_backing_file) if self.encrypted is not None: self.assertEqual(image_info.encrypted, self.encrypted) ImageUtilsQemuTestCase.generate_scenarios() class ImageUtilsBlankTestCase(test_base.BaseTestCase):...
def test_qemu_img_info_blank(self): example_output = '\n'.join(['image: None', 'file_format: None', 'virtual_size: None', 'disk_size: None', 'cluster_size: None', 'backing_file: None']) image_...
class ImageUtilsBlankTestCase(test_base.BaseTestCase): def test_qemu_img_info_blank(self): example_output = '\n'.join(['image: None', 'file_format: None', 'virtual_size: None', 'disk_size: None', 'cluster_size: None', ...
songhao8080/nova-client
venv/lib/python2.7/site-packages/oslo_utils/tests/test_imageutils.py
6e4e9977dd1cfc4b1f0b6f27
class
simple
'virtual_size: None', 'disk_size: None', 'cluster_size: None', 'backing_file: None']) image_info = imageutils.QemuImgInfo() self.assertEqual(str(image_info), example_output) self.assertEqual(len(image_info.snapshots), 0) ...
def test_qemu_img_info_json_format(self): img_output = '''{ "virtual-size": 41126400, "filename": "fake_img", "cluster-size": 65536, "format": "qcow2", "actual-size": 13168640 ...
class ImageUtilsJSONTestCase(test_base.BaseTestCase): def test_qemu_img_info_json_format(self): img_output = '''{ "virtual-size": 41126400, "filename": "fake_img", "cluster-size": 65536, "format": "qcow2", ...
songhao8080/nova-client
venv/lib/python2.7/site-packages/oslo_utils/tests/test_imageutils.py
230cbe79c3ad659dd8dd19b3
class
simple
# Copyright (C) 2012 Yahoo! Inc. # 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 ...
_image_name = [ ('disk_config', dict(image_name='disk.config')), ] _file_format = [ ('raw', dict(file_format='raw')), ] _virtual_size = [ ('64M', dict(virtual_size='64M', exp_virtual_size=67108864)), ('64M_with_byte_hint', dict(virtual_size='64M...
class ImageUtilsRawTestCase(test_base.BaseTestCase): _image_name = [ ('disk_config', dict(image_name='disk.config')), ] _file_format = [ ('raw', dict(file_format='raw')), ] _virtual_size = [ ('64M', dict(virtual_size='64M', exp_virtual_size=67108864)),...
songhao8080/nova-client
venv/lib/python2.7/site-packages/oslo_utils/tests/test_imageutils.py
7bb0a3913746d20edba9060a
class
simple
except ImportError: HAVE_SSDEEP = False try: import magic except ImportError: pass class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cl...
def __init__(self, event): self.event_id = event['Event']['id'] self.event = event def get_all_ips(self): return [a['value'] for a in self.event['Event']['Attribute'] if a['type'] == 'ip-dst' or a['type'] == 'ip-src'] def get_all_domains(self): return [a['va...
class MispEvent(object): def __init__(self, event): self.event_id = event['Event']['id'] self.event = event def get_all_ips(self): return [a['value'] for a in self.event['Event']['Attribute'] if a['type'] == 'ip-dst' or a['type'] == 'ip-src'] def get_all_domains(se...
vasporig/viper
viper/common/objects.py
e9a0b425aa32da9788154690
class
simple
ms = magic.open(magic.MIME) ms.load() mime_type = ms.file(self.path) except: try: mime = magic.Magic(mime=True) mime_type = mime.from_file(self.path) except: return '' return mime_type class Di...
"""Viper custom dict.""" def __getattr__(self, key): return self.get(key, None) __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__
class Dictionary(dict): """Viper custom dict.""" def __getattr__(self, key): return self.get(key, None) __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__
vasporig/viper
viper/common/objects.py
588076bd2cf31ec44fb8bbad
class
simple
See the file 'LICENSE' for copying permission. import os import hashlib import binascii try: import pydeep HAVE_SSDEEP = True except ImportError: HAVE_SSDEEP = False try: import magic except ImportError: pass class Singleton(type):
_instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls]
class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls]
vasporig/viper
viper/common/objects.py
787dc265334e21fed757b7ce
class
simple
'hostname'] def get_all_urls(self): return [a['value'] for a in self.event['Event']['Attribute'] if a['type'] == 'url'] def get_all_hashes(self): event_hashes = [] sample_hashes = [] for a in self.event['Event']['Attribute']: h = None if a['type'] in ('...
def __init__(self, path): self.id = None self.path = path self.name = '' self.size = 0 self.type = '' self.mime = '' self.md5 = '' self.sha1 = '' self.sha256 = '' self.sha512 = '' self.crc32 = '' self.ssdeep = '' ...
class File(object): def __init__(self, path): self.id = None self.path = path self.name = '' self.size = 0 self.type = '' self.mime = '' self.md5 = '' self.sha1 = '' self.sha256 = '' self.sha512 = '' self.crc32 = '' sel...
vasporig/viper
viper/common/objects.py
e907e0ffcba147001684451b
class
simple
and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, dis- # tribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, sub...
""" This is the AWS Data Pipeline API Reference . This guide provides descriptions and samples of the AWS Data Pipeline API. AWS Data Pipeline is a web service that configures and manages a data-driven workflow called a pipeline. AWS Data Pipeline handles the details of scheduling and ens...
class DataPipelineConnection(AWSQueryConnection): """ This is the AWS Data Pipeline API Reference . This guide provides descriptions and samples of the AWS Data Pipeline API. AWS Data Pipeline is a web service that configures and manages a data-driven workflow called a pipeline. AWS Data Pipe...
Rome84/AWS
datapipeline/layer1.py
ff1e2924876f96e62c622f55
class
simple
complex for some models) Attribute: u (Parameter): torch container packaging disentangler tensor u u.leg_type (tuple): a pair of int number indicating the number of in and out bonds of u ((2, 2) for u) """ def __init__(self, chi_in, chi_out, dtype): assert chi_in > 0 and chi_out > 0...
r"""single layer for ternary MERA. Args: chi_in (int): dimension of in (bottom) bond chi_out (int): dimension of out (upper) bond leg_type (tuple): a pair of int number indicating the number of in and out bonds of w (default: (3, 1)) dtype (tensor.dtype): data type (may be comple...
class SimpleTernary(SimpleLayer): r"""single layer for ternary MERA. Args: chi_in (int): dimension of in (bottom) bond chi_out (int): dimension of out (upper) bond leg_type (tuple): a pair of int number indicating the number of in and out bonds of w (default: (3, 1)) dtype (tenso...
xwkgch/IsoTensor
layer/MERAlayer.py
4b963885a9c62346bfb07176
class
simple
return 0 @focus_position.setter def focus_position(self, value): self.listbox.focus_position = value self.listbox._invalidate() @property def row_count(self): return len(self.listbox.body) @property def selection(self): if self.body: # len(self.body) != 0 ...
align = 'left' wrap = 'space' padding = None def __init__(self, name, label=None, width=('weight', 1), format_fn=None, sort_key=None, sort_fn=None, sort_reverse=False): self.name = name self.label = label if label else name self.format_fn = for...
class TableColumn(object): align = 'left' wrap = 'space' padding = None def __init__(self, name, label=None, width=('weight', 1), format_fn=None, sort_key=None, sort_fn=None, sort_reverse=False): self.name = name self.label = label if label else name ...
akosthekiss/fuzzinator
fuzzinator/ui/tui/table.py
8f6095ad25c10bfcf9bca903
class
simple
[-1].highlight() def unhighlight(self): for x in self.contents: x[-1].unhighlight() class TableBodyRow(TableRow): column_class = BodyColumns attr_map = {None: 'default'} focus_map = {None: 'selected'} class TableHeaderRow(TableRow):
signals = ['column_click'] column_class = HeaderColumns decorate = False def __init__(self, table, *args, **kwargs): self.row = None self.attr_map = {None: 'table_head'} self.focus_map = {None: 'table_head'} self.table = table self.contents = [str(x.label) for...
class TableHeaderRow(TableRow): signals = ['column_click'] column_class = HeaderColumns decorate = False def __init__(self, table, *args, **kwargs): self.row = None self.attr_map = {None: 'table_head'} self.focus_map = {None: 'table_head'} self.table = table s...
akosthekiss/fuzzinator
fuzzinator/ui/tui/table.py
f0c7596b6c193ad61b947354
class
simple
ata Hodovan, Akos Kiss. # # Licensed under the BSD 3-Clause License # <LICENSE.rst or https://opensource.org/licenses/BSD-3-Clause>. # This file may not be copied, modified, or distributed except # according to those terms. from functools import cmp_to_key from urwid import * from .decor_widgets import PatternBox fr...
def __init__(self, table, sort=None): self.table = table self.sort = sort self.focus = 0 self.rows = [] super().__init__() def __getitem__(self, position): if position < 0 or position >= len(self.rows): raise IndexError return self.rows[posit...
class TableRowsListWalker(ListWalker): def __init__(self, table, sort=None): self.table = table self.sort = sort self.focus = 0 self.rows = [] super().__init__() def __getitem__(self, position): if position < 0 or position >= len(self.rows): raise Ind...
akosthekiss/fuzzinator
fuzzinator/ui/tui/table.py
f3dc274557e1a79bfcfa3133
class
simple
(v, float): v = '%.03f' % v # If v doesn't match any of the previous options than it might be a Widget. if not isinstance(v, Widget): return Text(v, align=self.align, wrap=self.wrap) return v class HeaderColumns(Columns):
def __init__(self, contents): self.selected_column = None super().__init__(contents) def __setitem__(self, i, v): self.contents[i * 2] = (v, self.contents[i * 2][1])
class HeaderColumns(Columns): def __init__(self, contents): self.selected_column = None super().__init__(contents) def __setitem__(self, i, v): self.contents[i * 2] = (v, self.contents[i * 2][1])
akosthekiss/fuzzinator
fuzzinator/ui/tui/table.py
de2f7ab08d4799585c66c7a2
class
simple
BodyColumns attr_map = {None: 'default'} focus_map = {None: 'selected'} class TableHeaderRow(TableRow): signals = ['column_click'] column_class = HeaderColumns decorate = False def __init__(self, table, *args, **kwargs): self.row = None self.attr_map = {None: 'table_head'}...
signals = ['select', 'refresh', 'focus', 'delete'] attr_map = {} focus_map = {} row_dict = {} title = '' columns = [] query_data = [] key_columns = None sort_field = None _selectable = True def __init__(self, initial_sort=None, limit=None): self.border = (1, ' ', '...
class Table(WidgetWrap): signals = ['select', 'refresh', 'focus', 'delete'] attr_map = {} focus_map = {} row_dict = {} title = '' columns = [] query_data = [] key_columns = None sort_field = None _selectable = True def __init__(self, initial_sort=None, limit=None): ...
akosthekiss/fuzzinator
fuzzinator/ui/tui/table.py
eb7c95b0c86281f9d04db5da
class
simple
self.contents[i * 2][1]) class BodyColumns(Columns): def __init__(self, contents, header=None): self.header = header super().__init__(contents) @property def selected_column(self): return self.header.selected_column @selected_column.setter def selected_column(self, value...
signals = ['click', 'select'] def __init__(self, table, column, row, value): self.table = table self.column = column self.row = row self.value = value self.contents = self.column._format(self.value) padding = self.column.padding or self.table.padding sel...
class TableCell(WidgetWrap): signals = ['click', 'select'] def __init__(self, table, column, row, value): self.table = table self.column = column self.row = row self.value = value self.contents = self.column._format(self.value) padding = self.column.padding or s...
akosthekiss/fuzzinator
fuzzinator/ui/tui/table.py
a183384acda0dcb4a1373d73
class
simple
Columns): def __init__(self, contents): self.selected_column = None super().__init__(contents) def __setitem__(self, i, v): self.contents[i * 2] = (v, self.contents[i * 2][1]) class BodyColumns(Columns):
def __init__(self, contents, header=None): self.header = header super().__init__(contents) @property def selected_column(self): return self.header.selected_column @selected_column.setter def selected_column(self, value): self.header.selected_column = value
class BodyColumns(Columns): def __init__(self, contents, header=None): self.header = header super().__init__(contents) @property def selected_column(self): return self.header.selected_column @selected_column.setter def selected_column(self, value): self.header.selec...
akosthekiss/fuzzinator
fuzzinator/ui/tui/table.py
42b99c2447ef4471c1af94d2
class
simple
= self.column.padding or self.table.padding self.padding = Padding(self.contents, left=padding, right=padding) self.attr = AttrMap(self.padding, attr_map=row.attr_map, focus_map=row.focus_map) super().__init__(self.attr) def selectable(self): return isinstance(self.row, TableBodyRo...
attr_map = {} focus_map = {} border_char = ' ' column_class = Columns # To be redefined by subclasses. decorate = True _selectable = True def __init__(self, table, data, header=None, cell_click=None, cell_select=None, attr_map=None, focus...
class TableRow(WidgetWrap): attr_map = {} focus_map = {} border_char = ' ' column_class = Columns # To be redefined by subclasses. decorate = True _selectable = True def __init__(self, table, data, header=None, cell_click=None, cell_select=None, ...
akosthekiss/fuzzinator
fuzzinator/ui/tui/table.py
b6f2ffc3c198d74128a67417
class
simple
, value): self.rows.remove(value) def next_position(self, position): index = position + 1 if position >= len(self.rows): raise IndexError return index def prev_position(self, position): index = position - 1 if position < 0: raise IndexErr...
signals = ['select', 'load_more'] def __init__(self, body, infinite=False): self.infinite = infinite self.requery = False self.height = 0 self.listbox = ListBox(body) self.body = self.listbox.body self.ends_visible = self.listbox.ends_visible super()._...
class ScrollingListBox(WidgetWrap): signals = ['select', 'load_more'] def __init__(self, body, infinite=False): self.infinite = infinite self.requery = False self.height = 0 self.listbox = ListBox(body) self.body = self.listbox.body self.ends_visible = self.lis...
akosthekiss/fuzzinator
fuzzinator/ui/tui/table.py
a097e543c2b11a16122e6b2e
class
simple
###################################################################################### # Descirption: C14_RS485 Protocol python class # author: Gabriel Zima (z1mEk) # e-mail: gabriel.zima@wp.pl # github: https://github.com/z1mEk/c14_protocol.git # create date: 2018-08-09 # update date: 2019-05-10 ######################...
def __init__(self, SerialPort): self.SerialPort = SerialPort self.BaudRate = 9600 print('Started') # Read frame from serial port # @param self, bytearray(30) bFrame # @return bytearray(30) def SerialRequest(self, bFrame): try: print('Serial initial...') ...
class C14_RS485: def __init__(self, SerialPort): self.SerialPort = SerialPort self.BaudRate = 9600 print('Started') # Read frame from serial port # @param self, bytearray(30) bFrame # @return bytearray(30) def SerialRequest(self, bFrame): try: print('Ser...
z1mEk/c14_protocol
c14_class.py
8a0e626a56f16c2fd7f27d6e
class
simple
one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtai...
def __init__(self, alert_meta, alert_source_meta, config, recovery_manager): super(RecoveryAlert, self).__init__(alert_meta, alert_source_meta, config) self.recovery_manager = recovery_manager self.warning_count = DEFAULT_WARNING_RECOVERIES_COUNT self.critical_count = DEFAULT_CRITICAL_RECOVERIES_COUN...
class RecoveryAlert(BaseAlert): def __init__(self, alert_meta, alert_source_meta, config, recovery_manager): super(RecoveryAlert, self).__init__(alert_meta, alert_source_meta, config) self.recovery_manager = recovery_manager self.warning_count = DEFAULT_WARNING_RECOVERIES_COUNT self.critical_count =...
likenamehaojie/Apache-Ambari-ZH
ambari-agent/src/main/python/ambari_agent/alerts/recovery_alert.py
28a67309784dcdbf4c2c7608
class
simple
# -*- coding: utf-8 -*- ''' :codeauthor: :email:`Erik Johnson <erik@saltstack.com>` ''' # Import Python libs from __future__ import absolute_import import os import platform # Import Salt Testing Libs from salttesting import TestCase, skipIf from salttesting.helpers import ensure_in_syspath from salttesting.mock ...
''' Test cases for core grains ''' @skipIf(not salt.utils.is_linux(), 'System is not Linux') def test_gnu_slash_linux_in_os_name(self): ''' Test to return a list of all enabled services ''' _path_exists_map = { '/proc/1/cmdline': False } _p...
@skipIf(NO_MOCK, NO_MOCK_REASON) class CoreGrainsTestCase(TestCase): ''' Test cases for core grains ''' @skipIf(not salt.utils.is_linux(), 'System is not Linux') def test_gnu_slash_linux_in_os_name(self): ''' Test to return a list of all enabled services ''' _path_exi...
fictivekin/salt
tests/unit/grains/core_test.py
e3e0a328c0297476625af4c9
class
simple
"""This module contains the general information for VnicVnicBehPolicy ManagedObject.""" from ...ucscentralmo import ManagedObject from ...ucscentralcoremeta import UcsCentralVersion, MoPropertyMeta, MoMeta from ...ucscentralmeta import VersionMeta class VnicVnicBehPolicyConsts(): ACTION_HW_INHERIT = "hw-inherit"...
"""This is VnicVnicBehPolicy class.""" consts = VnicVnicBehPolicyConsts() naming_props = set([]) mo_meta = MoMeta("VnicVnicBehPolicy", "vnicVnicBehPolicy", "beh-vnic", VersionMeta.Version111a, "InputOutput", 0x7f, [], ["read-only"], [u'orgOrg'], [], ["Get", "Set"]) prop_meta = { "action":...
class VnicVnicBehPolicy(ManagedObject): """This is VnicVnicBehPolicy class.""" consts = VnicVnicBehPolicyConsts() naming_props = set([]) mo_meta = MoMeta("VnicVnicBehPolicy", "vnicVnicBehPolicy", "beh-vnic", VersionMeta.Version111a, "InputOutput", 0x7f, [], ["read-only"], [u'orgOrg'], [], ["Get", "Set...
ragupta-git/ucscentralsdk
ucscentralsdk/mometa/vnic/VnicVnicBehPolicy.py
7d82db435cd89c4c726e6cd7
class
simple
# 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...
""" The properties of a storage account’s Table service. """ def __init__(__self__, cors=None, id=None, name=None, type=None): if cors and not isinstance(cors, dict): raise TypeError("Expected argument 'cors' to be a dict") pulumi.set(__self__, "cors", cors) if id and...
@pulumi.output_type class GetTableServicePropertiesResult: """ The properties of a storage account’s Table service. """ def __init__(__self__, cors=None, id=None, name=None, type=None): if cors and not isinstance(cors, dict): raise TypeError("Expected argument 'cors' to be a dict") ...
sebtelko/pulumi-azure-native
sdk/python/pulumi_azure_native/storage/v20210101/get_table_service_properties.py
160f18c7faf1ba4e9bdb40f8
class
simple
: """ The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" """ return pulumi.get(self, "type") class AwaitableGetTableServicePropertiesResult(GetTableServicePropertiesResult): # pylint: disable=using-constant-test
def __await__(self): if False: yield self return GetTableServicePropertiesResult( cors=self.cors, id=self.id, name=self.name, type=self.type)
class AwaitableGetTableServicePropertiesResult(GetTableServicePropertiesResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return GetTableServicePropertiesResult( cors=self.cors, id=self.id, name=self.name, ...
sebtelko/pulumi-azure-native
sdk/python/pulumi_azure_native/storage/v20210101/get_table_service_properties.py
e81819677ca8224428bf0d27
class
simple
labels = list(labels) labels = torch.LongTensor(labels) x1 = torch.LongTensor(len(questions), max(question_lens)).zero_() for i, (question, q_len) in enumerate(zip(questions, question_lens)): x1[i, :q_len].copy_(torch.LongTensor(question)) return { 'text': x1, 'len': torch.FloatTensor(question_lens), 'lab...
def __init__(self, n_classes, vocab_size, embedding_dimension=EMBEDDING_LENGTH, embedder=None, n_hidden=50, dropout_rate=.5): super(Model, self).__init__() self.n_classes = n_classes self.vocab_size = vocab_size self.n_hidden = n_hidden self.embedding_dimension = emb...
class Model(nn.Module): def __init__(self, n_classes, vocab_size, embedding_dimension=EMBEDDING_LENGTH, embedder=None, n_hidden=50, dropout_rate=.5): super(Model, self).__init__() self.n_classes = n_classes self.vocab_size = vocab_size self.n_hidden = n_hidden self.e...
ExSidius/qanta-codalab
src/qanta/guesser_model.py
94042771d3f32682f3839155
class
simple
] >= cutoff]) new_train = [] new_dev = [] for example in training_examples: if example.label in ans_keep: new_train.append(example) for example in dev_examples: if example.label in ans_keep: new_dev.append(example) return new_train, new_dev, len(ans_keep)/len(ans_count) class QuestionDataset(Dataset):
def __init__(self, examples: List[Example], word2index: Dict[str, int], num_classes: int, class2index: Optional[Dict[str, int]] = None): self.tokenized_questions = [] self.labels = [] tokenized_questions, labels = zip(*examples) self.tokenized_questions = list(tokenized_questions) self.l...
class QuestionDataset(Dataset): def __init__(self, examples: List[Example], word2index: Dict[str, int], num_classes: int, class2index: Optional[Dict[str, int]] = None): self.tokenized_questions = [] self.labels = [] tokenized_questions, labels = zip(*examples) self.tokenized_questions = li...
ExSidius/qanta-codalab
src/qanta/guesser_model.py
b4145d12e73aa8ae2f2daac6
class
simple
_view(ModelView(ImageModel, category='DB')) # app_admin.add_view(ModelView(MatchTagRelationship, category='DB')) # routing app.add_url_rule('/thumb/<path:basename>', view_func=thumb) return app class CustomFlaskGroup(flask_cli.FlaskGroup):
"""Custom Flask Group.""" def __init__(self, **kwargs): """Class init.""" super().__init__(**kwargs) self.params[0].help = 'Show the program version' self.params[0].callback = get_custom_version
class CustomFlaskGroup(flask_cli.FlaskGroup): """Custom Flask Group.""" def __init__(self, **kwargs): """Class init.""" super().__init__(**kwargs) self.params[0].help = 'Show the program version' self.params[0].callback = get_custom_version
a1270/iqdb_tagger
iqdb_tagger/__main__.py
d0b55ebba710e1da694580ee
class
simple
Reader/Writer/Recevier for the call.""" if method.type() is ProtoServiceMethod.Type.UNARY: call_class = 'UnaryReceiver' elif method.type() is ProtoServiceMethod.Type.SERVER_STREAMING: call_class = 'ClientReader' elif method.type() is ProtoServiceMethod.Type.CLIENT_STREAMING: call_cla...
"""Generates RPC code for services and clients.""" def __init__(self, output_filename: str) -> None: self.output = OutputFile(output_filename) def indent(self, amount: int = OutputFile.INDENT_WIDTH) -> Any: """Indents the output. Use in a with block.""" return self.output.indent(amo...
class CodeGenerator(abc.ABC): """Generates RPC code for services and clients.""" def __init__(self, output_filename: str) -> None: self.output = OutputFile(output_filename) def indent(self, amount: int = OutputFile.INDENT_WIDTH) -> Any: """Indents the output. Use in a with block.""" ...
curtin-space/pigweed
pw_rpc/py/pw_rpc/codegen.py
95e455d184301b1cc509b1e2
class
simple
# Generate the method lookup table _method_lookup_table(gen, service) gen.line('};') def _method_lookup_table(gen: CodeGenerator, service: ProtoService) -> None: """Generates array of method IDs for looking up methods at compile time.""" gen.line('static constexpr std::array<uint32_t, ' ...
"""Generates stub method implementations that can be copied-and-pasted.""" @abc.abstractmethod def unary_signature(self, method: ProtoServiceMethod, prefix: str) -> str: """Returns the signature of this unary method.""" @abc.abstractmethod def unary_stub(self, method: ProtoServiceMethod, ...
class StubGenerator(abc.ABC): """Generates stub method implementations that can be copied-and-pasted.""" @abc.abstractmethod def unary_signature(self, method: ProtoServiceMethod, prefix: str) -> str: """Returns the signature of this unary method.""" @abc.abstractmethod def unary_stub(self, ...
curtin-space/pigweed
pw_rpc/py/pw_rpc/codegen.py
7944761eb0595c7820acc122
class
simple
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
"""NetworkSecurityGroup resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :param location: Resource ...
class NetworkSecurityGroup(Resource): """NetworkSecurityGroup resource. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype ty...
JonathanGailliez/azure-sdk-for-python
azure-mgmt-network/azure/mgmt/network/v2018_07_01/models/network_security_group_py3.py
c84e455b7e2cf9ec10dce389
class
simple
library is versioned library_file = find_library("libmit-0") assert(library_file) libmit = CDLL(library_file) assert(libmit) # Errors class Error(Exception): ''' An error from the Python bindings for Mit. ''' pass class VMError(Error):
''' An error from Mit. Public fields: - error_code - int - message - str ''' def __init__(self, error_code, message): super().__init__(error_code, message)
class VMError(Error): ''' An error from Mit. Public fields: - error_code - int - message - str ''' def __init__(self, error_code, message): super().__init__(error_code, message)
rrthomas/m
python/mit/binding.py
7f121a9693fc0c962832fa06
class
simple
# coding: utf-8 # Python libs from __future__ import absolute_import # Salt testing libs from tests.support.unit import skipIf, TestCase from tests.support.mock import NO_MOCK, NO_MOCK_REASON, MagicMock from tests.support.mixins import LoaderModuleMockMixin # Salt libs import salt.beacons.sensehat as sensehat @ski...
''' Test case for salt.beacons.[s] ''' def setup_loader_modules(self): self.HUMIDITY_MOCK = MagicMock(return_value=80) self.TEMPERATURE_MOCK = MagicMock(return_value=30) self.PRESSURE_MOCK = MagicMock(return_value=1500) self.addCleanup(delattr, self, 'HUMIDITY_MOCK') ...
@skipIf(NO_MOCK, NO_MOCK_REASON) class SensehatBeaconTestCase(TestCase, LoaderModuleMockMixin): ''' Test case for salt.beacons.[s] ''' def setup_loader_modules(self): self.HUMIDITY_MOCK = MagicMock(return_value=80) self.TEMPERATURE_MOCK = MagicMock(return_value=30) self.PRESSUR...
byteskeptical/salt
tests/unit/beacons/test_sensehat.py
7e859a1390ebf98c06339fbe
class
simple
import os import sys if __name__ == '__main__': sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir))) if sys.version_info[:2] < (2, 7): import unittest2 as unittest else: import unittest import metrics from metrics.bod import BuildOrderDeviatio...
def test_time_deviation_calculated_correctly_when_late_on_time(self): golden_bo = [] compare_bo = [] golden_bo.append(BuildOrderElement(1, 'Probe', 12, 0, 0)) golden_bo.append(BuildOrderElement(2, 'Assimilator', 15, 50, 200)) compare_bo.append(BuildOrderElement(1, 'Pro...
class TestBuildOrderDeviation(unittest.TestCase): #region time_deviation def test_time_deviation_calculated_correctly_when_late_on_time(self): golden_bo = [] compare_bo = [] golden_bo.append(BuildOrderElement(1, 'Probe', 12, 0, 0)) golden_bo.append(BuildOrderElement(2, 'A...
matthewj8489/Starcraft2Metrics
tests/unit/test_bod.py
f1e92d2d8938c94c5e0e4d33
class
simple
"""Monte Carlo Tree Search, as described in Silver et al 2015. This is a "pure" implementation of the AlphaGo MCTS algorithm in that it is not specific to the game of Go; everything in this file is implemented generically with respect to some state, actions, policy function, and value function. """ import numpy as np ...
"""A node in the MCTS tree. Each node keeps track of its own value Q, prior probability P, and its visit-count-adjusted prior score u. """ def __init__(self, parent, prior_p): self._parent = parent self._children = {} # a map from action to TreeNode self._n_visits = 0 s...
class TreeNode(object): """A node in the MCTS tree. Each node keeps track of its own value Q, prior probability P, and its visit-count-adjusted prior score u. """ def __init__(self, parent, prior_p): self._parent = parent self._children = {} # a map from action to TreeNode self...
sjkim04/AlphaGOZero-python-tensorflow
support/RocAlphaGo-develop/AlphaGo/mcts.py
b0e14fb3c9a950192ff73602
class
simple
u is not normalized to be a distribution. if not self.is_root(): self._u = c_puct * self._P * np.sqrt(self._parent._n_visits) / (1 + self._n_visits) def update_recursive(self, leaf_value, c_puct): """Like a call to update(), but applied recursively for all ancestors. Note: it ...
"""A simple (and slow) single-threaded implementation of Monte Carlo Tree Search. Search works by exploring moves randomly according to the given policy up to a certain depth, which is relatively small given the search space. "Leaves" at this depth are assigned a value comprising a weighted combination...
class MCTS(object): """A simple (and slow) single-threaded implementation of Monte Carlo Tree Search. Search works by exploring moves randomly according to the given policy up to a certain depth, which is relatively small given the search space. "Leaves" at this depth are assigned a value comprising a ...
sjkim04/AlphaGOZero-python-tensorflow
support/RocAlphaGo-develop/AlphaGo/mcts.py
3823e035c387dd6374ba40c9
class
simple
: 2022 - Symas Corporation ''' from ..util import RbacError from ..util.global_ids import USER_PW_INVLD,USER_PW_CHK_FAILED class NotFound(RbacError): pass class NotUnique(RbacError): pass class AuthFail(RbacError):
def __init__(self,msg="Authentication fail",id=USER_PW_INVLD, **kw): super().__init__(msg=msg,id=id,**kw)
class AuthFail(RbacError): def __init__(self,msg="Authentication fail",id=USER_PW_INVLD, **kw): super().__init__(msg=msg,id=id,**kw)
shawnmckinney/py-fortress
rbac/file/fileex.py
0eed375b0072983c2aaa1f55
class
simple
): pass class NotUnique(RbacError): pass class AuthFail(RbacError): def __init__(self,msg="Authentication fail",id=USER_PW_INVLD, **kw): super().__init__(msg=msg,id=id,**kw) class AuthError(RbacError):
def __init__(self,msg="Authentication error",id=USER_PW_CHK_FAILED, **kw): super().__init__(msg=msg,id=id,**kw)
class AuthError(RbacError): def __init__(self,msg="Authentication error",id=USER_PW_CHK_FAILED, **kw): super().__init__(msg=msg,id=id,**kw)
shawnmckinney/py-fortress
rbac/file/fileex.py
2008fb946183fe2b3d95b4a7
class
simple
nn import time def conv3x3(in_planes, out_planes, stride=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False) class BasicBlock(nn.Module):
expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None): super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes, planes, stride) self.bn1 = nn.BatchNorm2d(planes) self.relu = nn.ReLU(inplace=True) self.conv2 = conv3x3(planes, planes...
class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None): super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes, planes, stride) self.bn1 = nn.BatchNorm2d(planes) self.relu = nn.ReLU(inplace=True) self....
luk-ai-420/ExcelFIT_project
cor_src/cor_LSTM_network.py
daa59e9655278bbfad87a0cd
class
simple
nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False) class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None): super(BasicBlock, self).__init__() self.conv1 = conv3x3(inplanes, plan...
def __init__(self, block, layers, num_classes,frame_num, grayscale): self.num_classes = num_classes self.inplanes = 64 self.LSTMlayer_num = 2 self.LSTMframe_num = frame_num self.LSTMinputsize = 2048 self.LSTMhiddensize = 2048 self.average_LSTM_t = 0 ...
class LSTM_ResNet(nn.Module): def __init__(self, block, layers, num_classes,frame_num, grayscale): self.num_classes = num_classes self.inplanes = 64 self.LSTMlayer_num = 2 self.LSTMframe_num = frame_num self.LSTMinputsize = 2048 self.LSTMhiddensize = 2048 ...
luk-ai-420/ExcelFIT_project
cor_src/cor_LSTM_network.py
50828e9dcfc62fa9c85b3a97
class
simple
ID_REF", "LV-C&si-Control-1", "Detection Pval", "LV-C&si-Control-2", "Detection Pval", "LV-C&si-Control-3", "Detection Pval", "LV-C&si-EZH2-1", "Detection Pval", "LV-C&si-EZH2-2", "Detection Pval", "LV-C&si-EZH2-3", "Detection Pval", "LV-EZH2&si-EZH2-1", "Detectio...
def test_illumina_to_pcl(self): """Most basic Illumina to PCL test""" organism = Organism(name="HOMO_SAPIENS", taxonomy_id=9606, is_scientific_name=True) organism.save() job = prepare_illumina_job({**GSE22427, "organism": organism}) # Remove the title of one of the samples...
class IlluminaToPCLTestCase(TestCase, testing_utils.ProcessorJobTestCaseMixin): @tag("illumina") def test_illumina_to_pcl(self): """Most basic Illumina to PCL test""" organism = Organism(name="HOMO_SAPIENS", taxonomy_id=9606, is_scientific_name=True) organism.save() job = prepa...
AlexsLemonade/refinebio
workers/data_refinery_workers/processors/test_illumina.py
ae3e7fd8151b7ec7a058f267
class
simple
self, user, object_id, object_state_id), kwargs={"automatic": automatic}) thr.start() return thr else: return _execute_transition(transition=self, user=user, object_id=object_id, object_state_id=object_state_id, automatic=automatic) def cl...
CONDITION_TYPES = [ ("function", "Function Call"), ("and", "Boolean AND"), ("or", "Boolean OR"), ("not", "Boolean NOT"), ] workflow = models.ForeignKey(Workflow, on_delete=PROTECT, verbose_name=ugettext_lazy("Workflow"), editable=False) condition_type = models.Cha...
class Condition(models.Model): CONDITION_TYPES = [ ("function", "Function Call"), ("and", "Boolean AND"), ("or", "Boolean OR"), ("not", "Boolean NOT"), ] workflow = models.ForeignKey(Workflow, on_delete=PROTECT, verbose_name=ugettext_lazy("Workflow"), editable=False) ...
dani0805/auprico-workflow
auprico_workflow/models.py
821f4048bfa2cd0c1aa77b5b
class
simple
_name=ugettext_lazy("Object State")) state_variable_def = models.ForeignKey(StateVariableDef, on_delete=PROTECT, verbose_name=ugettext_lazy("Variable Definition")) value = models.CharField(max_length=4000, verbose_name=ugettext_lazy("Value")) class SingleWorkflowModel(models.Model):
current_state = models.ForeignKey(CurrentObjectState, on_delete=PROTECT, verbose_name=ugettext_lazy("Object State"), related_name="%(app_label)s_%(class)s") class Meta: abstract = True @property def state(self): return self.current_state.state @property def transition_...
class SingleWorkflowModel(models.Model): current_state = models.ForeignKey(CurrentObjectState, on_delete=PROTECT, verbose_name=ugettext_lazy("Object State"), related_name="%(app_label)s_%(class)s") class Meta: abstract = True @property def state(self): return self.current_state...
dani0805/auprico-workflow
auprico_workflow/models.py
b885533e7c3e30b26f25f958
class
simple
_state, old_state = clone(self, workflow=workflow, **defaults) for variableDef in old_state.variable_definitions.all(): new_var, _ = clone(variableDef, state=new_state, workflow=workflow, **defaults) return new_state, old_state class StateVariableDefManager(models.Manager):
def get_by_natural_key(self, name, workflow): return self.get(name=name, workflow__name=workflow)
class StateVariableDefManager(models.Manager): def get_by_natural_key(self, name, workflow): return self.get(name=name, workflow__name=workflow)
dani0805/auprico-workflow
auprico_workflow/models.py
ff2b5afecfb745db65850ba2
class
simple
ogether = (('name', 'workflow', 'state'),) def __unicode__(self): return "{}: {} - {}".format(self.workflow.name, self.state.name, self.name) def natural_key(self): return self.name, self.state.name, self.workflow.name class TransitionManager(models.Manager):
def get_by_natural_key(self, name, workflow, initial_state, final_state): return self.get( name=name, workflow__name=workflow, initial_state__name=initial_state, final_state__name=final_state )
class TransitionManager(models.Manager): def get_by_natural_key(self, name, workflow, initial_state, final_state): return self.get( name=name, workflow__name=workflow, initial_state__name=initial_state, final_state__name=final_state )
dani0805/auprico-workflow
auprico_workflow/models.py
3211a4b3da36a2482d4361a7
class
simple
__name=workflow) class StateVariableDef(models.Model): objects = StateVariableDefManager() workflow = models.ForeignKey(Workflow, on_delete=PROTECT, verbose_name=ugettext_lazy("Workflow")) state = models.ForeignKey(State, on_delete=PROTECT, verbose_name=ugettext_lazy("State"), related_name="variab...
objects = TransitionManager() workflow = models.ForeignKey(Workflow, on_delete=PROTECT, verbose_name=ugettext_lazy("Workflow"), editable=False) name = models.CharField(max_length=50, verbose_name=ugettext_lazy("Name")) label = models.CharField(max_length=50, verbose_name=ugettext_lazy("Label"),...
class Transition(models.Model): objects = TransitionManager() workflow = models.ForeignKey(Workflow, on_delete=PROTECT, verbose_name=ugettext_lazy("Workflow"), editable=False) name = models.CharField(max_length=50, verbose_name=ugettext_lazy("Name")) label = models.CharField(max_length=50, verb...
dani0805/auprico-workflow
auprico_workflow/models.py
bdefcad8bb2fac91827a73d9
class
simple
clone(variableDef, state=new_state, workflow=workflow, **defaults) return new_state, old_state class StateVariableDefManager(models.Manager): def get_by_natural_key(self, name, workflow): return self.get(name=name, workflow__name=workflow) class StateVariableDef(models.Model):
objects = StateVariableDefManager() workflow = models.ForeignKey(Workflow, on_delete=PROTECT, verbose_name=ugettext_lazy("Workflow")) state = models.ForeignKey(State, on_delete=PROTECT, verbose_name=ugettext_lazy("State"), related_name="variable_definitions") name = models.CharField(max_length=1...
class StateVariableDef(models.Model): objects = StateVariableDefManager() workflow = models.ForeignKey(Workflow, on_delete=PROTECT, verbose_name=ugettext_lazy("Workflow")) state = models.ForeignKey(State, on_delete=PROTECT, verbose_name=ugettext_lazy("State"), related_name="variable_definitions") ...
dani0805/auprico-workflow
auprico_workflow/models.py
baa2b5f87d2a7060234227ad
class
simple
_transition(self, transition: Transition, user: User, asynchonous=False, automatic=False): return transition.execute( user, self.current_state.object_id, object_state_id=self.current_state, asynchonous=asynchonous, automatic=automatic ) class...
current_states = models.ManyToManyField(CurrentObjectState, verbose_name=ugettext_lazy("Object States"), related_name="%(app_label)s_%(class)s") class Meta: abstract = True def state(self, workflow: Workflow): return self.current_states.get(workflow=workflow).state def transit...
class MultiWorkflowModel(models.Model): current_states = models.ManyToManyField(CurrentObjectState, verbose_name=ugettext_lazy("Object States"), related_name="%(app_label)s_%(class)s") class Meta: abstract = True def state(self, workflow: Workflow): return self.current_states.get(w...
dani0805/auprico-workflow
auprico_workflow/models.py