body_hash stringlengths 64 64 | body stringlengths 23 109k | docstring stringlengths 1 57k | path stringlengths 4 198 | name stringlengths 1 115 | repository_name stringlengths 7 111 | repository_stars float64 0 191k | lang stringclasses 1 value | body_without_docstring stringlengths 14 108k | unified stringlengths 45 133k |
|---|---|---|---|---|---|---|---|---|---|
9391a887f4c2f07457350bc659d53c636436c151b2b2904be2aa804f04648334 | @contextlib.contextmanager
def change_working_directory(path):
'Change working directory and revert to previous on exit.'
prev_cwd = Path.cwd()
os.chdir(path)
try:
(yield)
finally:
os.chdir(prev_cwd) | Change working directory and revert to previous on exit. | roughness/helpers.py | change_working_directory | NAU-PIXEL/roughness | 0 | python | @contextlib.contextmanager
def change_working_directory(path):
prev_cwd = Path.cwd()
os.chdir(path)
try:
(yield)
finally:
os.chdir(prev_cwd) | @contextlib.contextmanager
def change_working_directory(path):
prev_cwd = Path.cwd()
os.chdir(path)
try:
(yield)
finally:
os.chdir(prev_cwd)<|docstring|>Change working directory and revert to previous on exit.<|endoftext|> |
322438096a1d7ecca194859e246afa655436e18f4b50dab8835779da88e43eb3 | def compile_lineofsight(los_f90=cfg.FLOS_F90, verbose=False):
'Compile lineofsight module with numpy f2py. Error if no compiler.'
with open(los_f90) as f:
src = f.read()
failed = numpy.f2py.compile(src, 'lineofsight', verbose=verbose, source_fn=los_f90)
if failed:
msg = 'Cannot compile Fortran raytracing code. Please ensure you have a F90 compatible Fortran compiler (e.g. gfortran) installed.'
raise ImportError(msg) | Compile lineofsight module with numpy f2py. Error if no compiler. | roughness/helpers.py | compile_lineofsight | NAU-PIXEL/roughness | 0 | python | def compile_lineofsight(los_f90=cfg.FLOS_F90, verbose=False):
with open(los_f90) as f:
src = f.read()
failed = numpy.f2py.compile(src, 'lineofsight', verbose=verbose, source_fn=los_f90)
if failed:
msg = 'Cannot compile Fortran raytracing code. Please ensure you have a F90 compatible Fortran compiler (e.g. gfortran) installed.'
raise ImportError(msg) | def compile_lineofsight(los_f90=cfg.FLOS_F90, verbose=False):
with open(los_f90) as f:
src = f.read()
failed = numpy.f2py.compile(src, 'lineofsight', verbose=verbose, source_fn=los_f90)
if failed:
msg = 'Cannot compile Fortran raytracing code. Please ensure you have a F90 compatible Fortran compiler (e.g. gfortran) installed.'
raise ImportError(msg)<|docstring|>Compile lineofsight module with numpy f2py. Error if no compiler.<|endoftext|> |
3fb57408d7784b7376b643cca308c0377f9a193b8a2d429aef84813684010765 | def import_lineofsight(fortran_dir=cfg.FORTRAN_DIR):
'Import lineofsight module. Compile first if not found.'
lineofsight = None
with change_working_directory(fortran_dir):
try:
from .fortran import lineofsight
except (ImportError, ModuleNotFoundError):
try:
compile_lineofsight()
from .fortran import lineofsight
except (ImportError, ModuleNotFoundError):
msg = 'Cannot compile lineofsight FORTRAN module. Please ensure you have a F90 compatible Fortran compiler (e.g. gfortran) installed.'
print(msg)
return lineofsight | Import lineofsight module. Compile first if not found. | roughness/helpers.py | import_lineofsight | NAU-PIXEL/roughness | 0 | python | def import_lineofsight(fortran_dir=cfg.FORTRAN_DIR):
lineofsight = None
with change_working_directory(fortran_dir):
try:
from .fortran import lineofsight
except (ImportError, ModuleNotFoundError):
try:
compile_lineofsight()
from .fortran import lineofsight
except (ImportError, ModuleNotFoundError):
msg = 'Cannot compile lineofsight FORTRAN module. Please ensure you have a F90 compatible Fortran compiler (e.g. gfortran) installed.'
print(msg)
return lineofsight | def import_lineofsight(fortran_dir=cfg.FORTRAN_DIR):
lineofsight = None
with change_working_directory(fortran_dir):
try:
from .fortran import lineofsight
except (ImportError, ModuleNotFoundError):
try:
compile_lineofsight()
from .fortran import lineofsight
except (ImportError, ModuleNotFoundError):
msg = 'Cannot compile lineofsight FORTRAN module. Please ensure you have a F90 compatible Fortran compiler (e.g. gfortran) installed.'
print(msg)
return lineofsight<|docstring|>Import lineofsight module. Compile first if not found.<|endoftext|> |
b973e0c78173df8a48c0b3f01a7a467776db7dcd76971d963d32798792205aa4 | def build_jupyter_notebooks(nbpath=cfg.EXAMPLES_DIR):
'Build Jupyter notebooks using Jupytext.'
print('Setting up Jupyter notebooks')
for nb_py in nbpath.rglob('*.py'):
fout = nb_py.with_suffix('.ipynb')
if fout.exists():
print(f'Skipping existing notebook {fout}')
else:
jupytext.write(jupytext.read(nb_py), fout)
print(f'Wrote {fout}') | Build Jupyter notebooks using Jupytext. | roughness/helpers.py | build_jupyter_notebooks | NAU-PIXEL/roughness | 0 | python | def build_jupyter_notebooks(nbpath=cfg.EXAMPLES_DIR):
print('Setting up Jupyter notebooks')
for nb_py in nbpath.rglob('*.py'):
fout = nb_py.with_suffix('.ipynb')
if fout.exists():
print(f'Skipping existing notebook {fout}')
else:
jupytext.write(jupytext.read(nb_py), fout)
print(f'Wrote {fout}') | def build_jupyter_notebooks(nbpath=cfg.EXAMPLES_DIR):
print('Setting up Jupyter notebooks')
for nb_py in nbpath.rglob('*.py'):
fout = nb_py.with_suffix('.ipynb')
if fout.exists():
print(f'Skipping existing notebook {fout}')
else:
jupytext.write(jupytext.read(nb_py), fout)
print(f'Wrote {fout}')<|docstring|>Build Jupyter notebooks using Jupytext.<|endoftext|> |
23a28b7cc29a0b1d16e05961247eb40d5f151b44f9fdfa0e195924b22aac0939 | def get_surf_geometry(ground_zen, ground_az, sun_zen, sun_az, sc_zen, sc_az):
'\n Return local i, e, g, azimuth give input viewing geometry assuming all\n input zeniths and azimuths are in radians.\n '
ground = sph2cart(ground_zen, ground_az)
sun = sph2cart(sun_zen, sun_az)
sc = sph2cart(sc_zen, sc_az)
inc = get_local_inc(ground, sun)
em = get_local_em(ground, sc)
phase = get_local_phase(sun, sc)
az = get_local_az(ground, sun, sc)
return (inc, em, phase, az) | Return local i, e, g, azimuth give input viewing geometry assuming all
input zeniths and azimuths are in radians. | roughness/helpers.py | get_surf_geometry | NAU-PIXEL/roughness | 0 | python | def get_surf_geometry(ground_zen, ground_az, sun_zen, sun_az, sc_zen, sc_az):
'\n Return local i, e, g, azimuth give input viewing geometry assuming all\n input zeniths and azimuths are in radians.\n '
ground = sph2cart(ground_zen, ground_az)
sun = sph2cart(sun_zen, sun_az)
sc = sph2cart(sc_zen, sc_az)
inc = get_local_inc(ground, sun)
em = get_local_em(ground, sc)
phase = get_local_phase(sun, sc)
az = get_local_az(ground, sun, sc)
return (inc, em, phase, az) | def get_surf_geometry(ground_zen, ground_az, sun_zen, sun_az, sc_zen, sc_az):
'\n Return local i, e, g, azimuth give input viewing geometry assuming all\n input zeniths and azimuths are in radians.\n '
ground = sph2cart(ground_zen, ground_az)
sun = sph2cart(sun_zen, sun_az)
sc = sph2cart(sc_zen, sc_az)
inc = get_local_inc(ground, sun)
em = get_local_em(ground, sc)
phase = get_local_phase(sun, sc)
az = get_local_az(ground, sun, sc)
return (inc, em, phase, az)<|docstring|>Return local i, e, g, azimuth give input viewing geometry assuming all
input zeniths and azimuths are in radians.<|endoftext|> |
fcb29a2bbeffe5b9bdbb28ff4036a185ca2ee3ff7f1e6c47a6037a74b9fdd6d0 | def get_ieg(ground_zen, ground_az, sun_zen, sun_az, sc_zen, sc_az):
'\n Return local solar incidence, spacecraft emission and phase angle (i, e, g)\n and azimuth given input viewing geometry.\n\n Input zeniths and azimuths in radians.\n '
ground = sph2cart(ground_zen, ground_az)
sun = sph2cart(sun_zen, sun_az)
sc = sph2cart(sc_zen, sc_az)
inc = get_local_inc(ground, sun)
em = get_local_em(ground, sc)
phase = get_local_phase(sun, sc)
az = get_local_az(ground, sun, sc)
return (inc, em, phase, az) | Return local solar incidence, spacecraft emission and phase angle (i, e, g)
and azimuth given input viewing geometry.
Input zeniths and azimuths in radians. | roughness/helpers.py | get_ieg | NAU-PIXEL/roughness | 0 | python | def get_ieg(ground_zen, ground_az, sun_zen, sun_az, sc_zen, sc_az):
'\n Return local solar incidence, spacecraft emission and phase angle (i, e, g)\n and azimuth given input viewing geometry.\n\n Input zeniths and azimuths in radians.\n '
ground = sph2cart(ground_zen, ground_az)
sun = sph2cart(sun_zen, sun_az)
sc = sph2cart(sc_zen, sc_az)
inc = get_local_inc(ground, sun)
em = get_local_em(ground, sc)
phase = get_local_phase(sun, sc)
az = get_local_az(ground, sun, sc)
return (inc, em, phase, az) | def get_ieg(ground_zen, ground_az, sun_zen, sun_az, sc_zen, sc_az):
'\n Return local solar incidence, spacecraft emission and phase angle (i, e, g)\n and azimuth given input viewing geometry.\n\n Input zeniths and azimuths in radians.\n '
ground = sph2cart(ground_zen, ground_az)
sun = sph2cart(sun_zen, sun_az)
sc = sph2cart(sc_zen, sc_az)
inc = get_local_inc(ground, sun)
em = get_local_em(ground, sc)
phase = get_local_phase(sun, sc)
az = get_local_az(ground, sun, sc)
return (inc, em, phase, az)<|docstring|>Return local solar incidence, spacecraft emission and phase angle (i, e, g)
and azimuth given input viewing geometry.
Input zeniths and azimuths in radians.<|endoftext|> |
49e90034106e03934ebeeb7c0d0e803f64d4bbb2186350aca13e295d4e53d21a | def safe_arccos(arr):
'Return arccos, restricting output to [-1, 1] without raising Exception.'
if ((arr < (- 1)).any() or (arr > 1).any()):
print('Invalid cosine input; restrict to [-1,1]')
arr[(arr < (- 1))] = (- 1)
arr[(arr > 1)] = 1
return np.arccos(arr) | Return arccos, restricting output to [-1, 1] without raising Exception. | roughness/helpers.py | safe_arccos | NAU-PIXEL/roughness | 0 | python | def safe_arccos(arr):
if ((arr < (- 1)).any() or (arr > 1).any()):
print('Invalid cosine input; restrict to [-1,1]')
arr[(arr < (- 1))] = (- 1)
arr[(arr > 1)] = 1
return np.arccos(arr) | def safe_arccos(arr):
if ((arr < (- 1)).any() or (arr > 1).any()):
print('Invalid cosine input; restrict to [-1,1]')
arr[(arr < (- 1))] = (- 1)
arr[(arr > 1)] = 1
return np.arccos(arr)<|docstring|>Return arccos, restricting output to [-1, 1] without raising Exception.<|endoftext|> |
a4ffa1487182121c83b10ed979503896b29e436fdf78121838d739903b550ba7 | def get_azim(ground_sc_ground, ground_sun_ground):
'\n Return the azimuth arccos(dot product of the spacecraft and sun vectors)\n '
dot_azim = np.degrees(np.arccos(np.sum((ground_sc_ground * ground_sun_ground), axis=2)))
oob = dot_azim[((dot_azim < 0) * (dot_azim > 180))]
if oob.any():
w = f'Azimuth {oob} outside (0, 180); Setting to 0'
print(w)
dot_azim[((dot_azim < 0) * (dot_azim > 180))] = 0
return dot_azim | Return the azimuth arccos(dot product of the spacecraft and sun vectors) | roughness/helpers.py | get_azim | NAU-PIXEL/roughness | 0 | python | def get_azim(ground_sc_ground, ground_sun_ground):
'\n \n '
dot_azim = np.degrees(np.arccos(np.sum((ground_sc_ground * ground_sun_ground), axis=2)))
oob = dot_azim[((dot_azim < 0) * (dot_azim > 180))]
if oob.any():
w = f'Azimuth {oob} outside (0, 180); Setting to 0'
print(w)
dot_azim[((dot_azim < 0) * (dot_azim > 180))] = 0
return dot_azim | def get_azim(ground_sc_ground, ground_sun_ground):
'\n \n '
dot_azim = np.degrees(np.arccos(np.sum((ground_sc_ground * ground_sun_ground), axis=2)))
oob = dot_azim[((dot_azim < 0) * (dot_azim > 180))]
if oob.any():
w = f'Azimuth {oob} outside (0, 180); Setting to 0'
print(w)
dot_azim[((dot_azim < 0) * (dot_azim > 180))] = 0
return dot_azim<|docstring|>Return the azimuth arccos(dot product of the spacecraft and sun vectors)<|endoftext|> |
f072602b85de6ca97714d26c89c654ab663f1531c49becc6b75e298474ce9171 | def get_local_inc(ground, sun):
'\n Return solar incidence angle of each pixel given local topography. Assumes\n inputs are same size and shape and are in 3D Cartesian coords (ixjxk).\n '
cos_inc = element_dot(ground, sun)
inc = np.degrees(safe_arccos(cos_inc))
inc[(inc > 89.999)] = 89.999
return inc | Return solar incidence angle of each pixel given local topography. Assumes
inputs are same size and shape and are in 3D Cartesian coords (ixjxk). | roughness/helpers.py | get_local_inc | NAU-PIXEL/roughness | 0 | python | def get_local_inc(ground, sun):
'\n Return solar incidence angle of each pixel given local topography. Assumes\n inputs are same size and shape and are in 3D Cartesian coords (ixjxk).\n '
cos_inc = element_dot(ground, sun)
inc = np.degrees(safe_arccos(cos_inc))
inc[(inc > 89.999)] = 89.999
return inc | def get_local_inc(ground, sun):
'\n Return solar incidence angle of each pixel given local topography. Assumes\n inputs are same size and shape and are in 3D Cartesian coords (ixjxk).\n '
cos_inc = element_dot(ground, sun)
inc = np.degrees(safe_arccos(cos_inc))
inc[(inc > 89.999)] = 89.999
return inc<|docstring|>Return solar incidence angle of each pixel given local topography. Assumes
inputs are same size and shape and are in 3D Cartesian coords (ixjxk).<|endoftext|> |
bdcd0047b2ee79faf78a08c0e974ac71435a0b72b1596c31382ebefd4bd0f292 | def get_local_em(ground, sc):
'\n Return emergence angle of each pixel given local topography. Assumes\n inputs are same size and shape and are in 3D Cartesian coords (ixjxk).\n '
cos_em = element_dot(ground, sc)
em = np.degrees(safe_arccos(cos_em))
return em | Return emergence angle of each pixel given local topography. Assumes
inputs are same size and shape and are in 3D Cartesian coords (ixjxk). | roughness/helpers.py | get_local_em | NAU-PIXEL/roughness | 0 | python | def get_local_em(ground, sc):
'\n Return emergence angle of each pixel given local topography. Assumes\n inputs are same size and shape and are in 3D Cartesian coords (ixjxk).\n '
cos_em = element_dot(ground, sc)
em = np.degrees(safe_arccos(cos_em))
return em | def get_local_em(ground, sc):
'\n Return emergence angle of each pixel given local topography. Assumes\n inputs are same size and shape and are in 3D Cartesian coords (ixjxk).\n '
cos_em = element_dot(ground, sc)
em = np.degrees(safe_arccos(cos_em))
return em<|docstring|>Return emergence angle of each pixel given local topography. Assumes
inputs are same size and shape and are in 3D Cartesian coords (ixjxk).<|endoftext|> |
67306ff87ca3f68cce32244b75e7ebafed2cffb64b91d28de8a0d07c1443c1ed | def get_local_phase(sun, sc):
'\n Return phase angle of each pixel given local topography. Assumes\n inputs are same size and shape and are in 3D Cartesian coords (ixjxk).\n '
cos_phase = element_dot(sc, sun)
phase = np.degrees(safe_arccos(cos_phase))
return phase | Return phase angle of each pixel given local topography. Assumes
inputs are same size and shape and are in 3D Cartesian coords (ixjxk). | roughness/helpers.py | get_local_phase | NAU-PIXEL/roughness | 0 | python | def get_local_phase(sun, sc):
'\n Return phase angle of each pixel given local topography. Assumes\n inputs are same size and shape and are in 3D Cartesian coords (ixjxk).\n '
cos_phase = element_dot(sc, sun)
phase = np.degrees(safe_arccos(cos_phase))
return phase | def get_local_phase(sun, sc):
'\n Return phase angle of each pixel given local topography. Assumes\n inputs are same size and shape and are in 3D Cartesian coords (ixjxk).\n '
cos_phase = element_dot(sc, sun)
phase = np.degrees(safe_arccos(cos_phase))
return phase<|docstring|>Return phase angle of each pixel given local topography. Assumes
inputs are same size and shape and are in 3D Cartesian coords (ixjxk).<|endoftext|> |
65c697797402fe658eaf30ccd75f044544321b0830148402a01cbbfaebcb63e4 | def get_local_az(ground, sun, sc):
'\n Return azimuth angle of the spacecraft with respect to the sun and local\n slope. Assumes inputs are same size and shape and are in 3D\n Cartesian coords (ixjxk).\n '
sc_rel_ground = element_norm(element_triple_cross(ground, sc, ground))
sun_rel_ground = element_norm(element_triple_cross(ground, sun, ground))
cos_az = element_dot(sc_rel_ground, sun_rel_ground)
az = np.degrees(safe_arccos(cos_az))
az[((az < 0) * (az > 180))] = 0
return az | Return azimuth angle of the spacecraft with respect to the sun and local
slope. Assumes inputs are same size and shape and are in 3D
Cartesian coords (ixjxk). | roughness/helpers.py | get_local_az | NAU-PIXEL/roughness | 0 | python | def get_local_az(ground, sun, sc):
'\n Return azimuth angle of the spacecraft with respect to the sun and local\n slope. Assumes inputs are same size and shape and are in 3D\n Cartesian coords (ixjxk).\n '
sc_rel_ground = element_norm(element_triple_cross(ground, sc, ground))
sun_rel_ground = element_norm(element_triple_cross(ground, sun, ground))
cos_az = element_dot(sc_rel_ground, sun_rel_ground)
az = np.degrees(safe_arccos(cos_az))
az[((az < 0) * (az > 180))] = 0
return az | def get_local_az(ground, sun, sc):
'\n Return azimuth angle of the spacecraft with respect to the sun and local\n slope. Assumes inputs are same size and shape and are in 3D\n Cartesian coords (ixjxk).\n '
sc_rel_ground = element_norm(element_triple_cross(ground, sc, ground))
sun_rel_ground = element_norm(element_triple_cross(ground, sun, ground))
cos_az = element_dot(sc_rel_ground, sun_rel_ground)
az = np.degrees(safe_arccos(cos_az))
az[((az < 0) * (az > 180))] = 0
return az<|docstring|>Return azimuth angle of the spacecraft with respect to the sun and local
slope. Assumes inputs are same size and shape and are in 3D
Cartesian coords (ixjxk).<|endoftext|> |
1b34961ef6e467b552202384511aef4a8806d71c7f051b2cc7d31e11acce7e6f | def inc_to_tloc(inc, az):
'\n Convert solar incidence and az to decimal local time (in 6-18h).\n\n Parameters\n ----------\n inc: (float)\n Solar incidence in degrees (0, 90)\n az: (str)\n Solar azimuth in degrees (0, 360)\n '
inc = inc.copy()
if isinstance(az, np.ndarray):
inc[(az < 180)] *= (- 1)
elif (az < 180):
inc *= (- 1)
coinc = (90 + inc)
tloc = (((6 * coinc) / 90) + 6)
return tloc | Convert solar incidence and az to decimal local time (in 6-18h).
Parameters
----------
inc: (float)
Solar incidence in degrees (0, 90)
az: (str)
Solar azimuth in degrees (0, 360) | roughness/helpers.py | inc_to_tloc | NAU-PIXEL/roughness | 0 | python | def inc_to_tloc(inc, az):
'\n Convert solar incidence and az to decimal local time (in 6-18h).\n\n Parameters\n ----------\n inc: (float)\n Solar incidence in degrees (0, 90)\n az: (str)\n Solar azimuth in degrees (0, 360)\n '
inc = inc.copy()
if isinstance(az, np.ndarray):
inc[(az < 180)] *= (- 1)
elif (az < 180):
inc *= (- 1)
coinc = (90 + inc)
tloc = (((6 * coinc) / 90) + 6)
return tloc | def inc_to_tloc(inc, az):
'\n Convert solar incidence and az to decimal local time (in 6-18h).\n\n Parameters\n ----------\n inc: (float)\n Solar incidence in degrees (0, 90)\n az: (str)\n Solar azimuth in degrees (0, 360)\n '
inc = inc.copy()
if isinstance(az, np.ndarray):
inc[(az < 180)] *= (- 1)
elif (az < 180):
inc *= (- 1)
coinc = (90 + inc)
tloc = (((6 * coinc) / 90) + 6)
return tloc<|docstring|>Convert solar incidence and az to decimal local time (in 6-18h).
Parameters
----------
inc: (float)
Solar incidence in degrees (0, 90)
az: (str)
Solar azimuth in degrees (0, 360)<|endoftext|> |
4949f6b84b9baa7b1158a6f61bf4659b6bdbdb7df889ae6e242cd17a4ad8775a | def tloc_to_inc(tloc):
'\n Convert decimal local time to solar incidence (equator only).\n '
coinc = (((tloc - 6) * 90) / 6)
inc = (coinc - 90)
return inc | Convert decimal local time to solar incidence (equator only). | roughness/helpers.py | tloc_to_inc | NAU-PIXEL/roughness | 0 | python | def tloc_to_inc(tloc):
'\n \n '
coinc = (((tloc - 6) * 90) / 6)
inc = (coinc - 90)
return inc | def tloc_to_inc(tloc):
'\n \n '
coinc = (((tloc - 6) * 90) / 6)
inc = (coinc - 90)
return inc<|docstring|>Convert decimal local time to solar incidence (equator only).<|endoftext|> |
5f71939f2aa2506b11c52cde09aeccdd0b3dcede7bfcd95835fa47838bbf8b75 | def element_cross(A, B):
'\n Return element-wise cross product of two 3D arrays in cartesian coords.\n '
out = np.zeros_like(A)
out[(:, :, 0)] = ((A[(:, :, 1)] * B[(:, :, 2)]) - (A[(:, :, 2)] * B[(:, :, 1)]))
out[(:, :, 1)] = ((A[(:, :, 2)] * B[(:, :, 0)]) - (A[(:, :, 0)] * B[(:, :, 2)]))
out[(:, :, 2)] = ((A[(:, :, 0)] * B[(:, :, 1)]) - (A[(:, :, 1)] * B[(:, :, 0)]))
return out | Return element-wise cross product of two 3D arrays in cartesian coords. | roughness/helpers.py | element_cross | NAU-PIXEL/roughness | 0 | python | def element_cross(A, B):
'\n \n '
out = np.zeros_like(A)
out[(:, :, 0)] = ((A[(:, :, 1)] * B[(:, :, 2)]) - (A[(:, :, 2)] * B[(:, :, 1)]))
out[(:, :, 1)] = ((A[(:, :, 2)] * B[(:, :, 0)]) - (A[(:, :, 0)] * B[(:, :, 2)]))
out[(:, :, 2)] = ((A[(:, :, 0)] * B[(:, :, 1)]) - (A[(:, :, 1)] * B[(:, :, 0)]))
return out | def element_cross(A, B):
'\n \n '
out = np.zeros_like(A)
out[(:, :, 0)] = ((A[(:, :, 1)] * B[(:, :, 2)]) - (A[(:, :, 2)] * B[(:, :, 1)]))
out[(:, :, 1)] = ((A[(:, :, 2)] * B[(:, :, 0)]) - (A[(:, :, 0)] * B[(:, :, 2)]))
out[(:, :, 2)] = ((A[(:, :, 0)] * B[(:, :, 1)]) - (A[(:, :, 1)] * B[(:, :, 0)]))
return out<|docstring|>Return element-wise cross product of two 3D arrays in cartesian coords.<|endoftext|> |
31c915c53112df33f1f0bf4182c6f11931256a04277f3e5e8e113a122d19571b | def element_dot(A, B):
'Return element-wise dot product of two 3D arr in Cartesian coords.'
return np.sum((A * B), axis=2) | Return element-wise dot product of two 3D arr in Cartesian coords. | roughness/helpers.py | element_dot | NAU-PIXEL/roughness | 0 | python | def element_dot(A, B):
return np.sum((A * B), axis=2) | def element_dot(A, B):
return np.sum((A * B), axis=2)<|docstring|>Return element-wise dot product of two 3D arr in Cartesian coords.<|endoftext|> |
6edf4a6e88ea5acdb34c87a7ff0ef6bd6be71539bdfc65410783d4dfe0771ab0 | def element_norm(A):
'Return input array of vectors normalized to length 1.'
mag = np.sqrt(np.sum((A ** 2), axis=2))
return (A / mag[(:, :, np.newaxis)]) | Return input array of vectors normalized to length 1. | roughness/helpers.py | element_norm | NAU-PIXEL/roughness | 0 | python | def element_norm(A):
mag = np.sqrt(np.sum((A ** 2), axis=2))
return (A / mag[(:, :, np.newaxis)]) | def element_norm(A):
mag = np.sqrt(np.sum((A ** 2), axis=2))
return (A / mag[(:, :, np.newaxis)])<|docstring|>Return input array of vectors normalized to length 1.<|endoftext|> |
4c9f06b9c8739b2931c7d8572c12523317013f9f52b88829705400a4355e9688 | def element_triple_cross(A, B, C):
'Return element-wise triple cross product of three 3D arr in Cartesian'
return ((B * element_dot(A, C)[(:, :, np.newaxis)]) - (C * element_dot(A, B)[(:, :, np.newaxis)])) | Return element-wise triple cross product of three 3D arr in Cartesian | roughness/helpers.py | element_triple_cross | NAU-PIXEL/roughness | 0 | python | def element_triple_cross(A, B, C):
return ((B * element_dot(A, C)[(:, :, np.newaxis)]) - (C * element_dot(A, B)[(:, :, np.newaxis)])) | def element_triple_cross(A, B, C):
return ((B * element_dot(A, C)[(:, :, np.newaxis)]) - (C * element_dot(A, B)[(:, :, np.newaxis)]))<|docstring|>Return element-wise triple cross product of three 3D arr in Cartesian<|endoftext|> |
23da71730a6e794cefc464ba3a65c2933607f4f59e17271ebbd03ab653eafb75 | def cart2pol(x, y):
'\n Convert ordered coordinate pairs from Cartesian (X,Y) to polar (r,theta).\n\n Parameters\n ----------\n X: X component of ordered Cartesian coordinate pair.\n Y: Y component of ordered Cartesian coordinate pair.\n\n Returns\n -------\n r: Distance from origin.\n theta: Angle, in radians.\n '
r = np.sqrt(((x ** 2) + (y ** 2)))
theta = np.arctan2(y, x)
return (r, theta) | Convert ordered coordinate pairs from Cartesian (X,Y) to polar (r,theta).
Parameters
----------
X: X component of ordered Cartesian coordinate pair.
Y: Y component of ordered Cartesian coordinate pair.
Returns
-------
r: Distance from origin.
theta: Angle, in radians. | roughness/helpers.py | cart2pol | NAU-PIXEL/roughness | 0 | python | def cart2pol(x, y):
'\n Convert ordered coordinate pairs from Cartesian (X,Y) to polar (r,theta).\n\n Parameters\n ----------\n X: X component of ordered Cartesian coordinate pair.\n Y: Y component of ordered Cartesian coordinate pair.\n\n Returns\n -------\n r: Distance from origin.\n theta: Angle, in radians.\n '
r = np.sqrt(((x ** 2) + (y ** 2)))
theta = np.arctan2(y, x)
return (r, theta) | def cart2pol(x, y):
'\n Convert ordered coordinate pairs from Cartesian (X,Y) to polar (r,theta).\n\n Parameters\n ----------\n X: X component of ordered Cartesian coordinate pair.\n Y: Y component of ordered Cartesian coordinate pair.\n\n Returns\n -------\n r: Distance from origin.\n theta: Angle, in radians.\n '
r = np.sqrt(((x ** 2) + (y ** 2)))
theta = np.arctan2(y, x)
return (r, theta)<|docstring|>Convert ordered coordinate pairs from Cartesian (X,Y) to polar (r,theta).
Parameters
----------
X: X component of ordered Cartesian coordinate pair.
Y: Y component of ordered Cartesian coordinate pair.
Returns
-------
r: Distance from origin.
theta: Angle, in radians.<|endoftext|> |
fa93c2ac1d9d2d098fe9254179304860fe39ddcc74383d7952ce40f7c71ec136 | def pol2cart(rho, phi):
'\n Convert ordered coordinate pairs from polar (r,theta) to Cartesian (X,Y).\n\n Parameters\n ----------\n r: Distance from origin.\n theta: Angle, in radians.\n\n Returns\n -------\n X: X component of ordered Cartesian coordinate pair.\n Y: Y component of ordered Cartesian coordinate pair.\n '
x = (rho * np.cos(phi))
y = (rho * np.sin(phi))
return (x, y) | Convert ordered coordinate pairs from polar (r,theta) to Cartesian (X,Y).
Parameters
----------
r: Distance from origin.
theta: Angle, in radians.
Returns
-------
X: X component of ordered Cartesian coordinate pair.
Y: Y component of ordered Cartesian coordinate pair. | roughness/helpers.py | pol2cart | NAU-PIXEL/roughness | 0 | python | def pol2cart(rho, phi):
'\n Convert ordered coordinate pairs from polar (r,theta) to Cartesian (X,Y).\n\n Parameters\n ----------\n r: Distance from origin.\n theta: Angle, in radians.\n\n Returns\n -------\n X: X component of ordered Cartesian coordinate pair.\n Y: Y component of ordered Cartesian coordinate pair.\n '
x = (rho * np.cos(phi))
y = (rho * np.sin(phi))
return (x, y) | def pol2cart(rho, phi):
'\n Convert ordered coordinate pairs from polar (r,theta) to Cartesian (X,Y).\n\n Parameters\n ----------\n r: Distance from origin.\n theta: Angle, in radians.\n\n Returns\n -------\n X: X component of ordered Cartesian coordinate pair.\n Y: Y component of ordered Cartesian coordinate pair.\n '
x = (rho * np.cos(phi))
y = (rho * np.sin(phi))
return (x, y)<|docstring|>Convert ordered coordinate pairs from polar (r,theta) to Cartesian (X,Y).
Parameters
----------
r: Distance from origin.
theta: Angle, in radians.
Returns
-------
X: X component of ordered Cartesian coordinate pair.
Y: Y component of ordered Cartesian coordinate pair.<|endoftext|> |
8e76ed753fd5932af9e97a865e4f5cc3cc17e205ba620f30be3eec627bcd0847 | def sph2cart(theta, phi, radius=1):
'\n Convert from spherical (theta, phi, r) to cartesian (x, y, z) coordinates.\n\n Theta and phi must be specified in radians and returned units correspond to\n units of r, default is unitless (r=1 is unit vector). Returns vectors along\n z-axis (e.g., if theta and phi are int/float return 1x1x3 vector; if theta\n and phi are MxN arrays return 3D array of vectors MxNx3).\n\n Parameters\n ----------\n theta (num or array): Polar angle [rad].\n phi (num or array): Azimuthal angle [rad].\n radius (num or array): Radius (default=1).\n\n Returns\n -------\n cartesian (array): Cartesian vector(s), same shape as theta and phi.\n '
return np.dstack([((radius * np.sin(theta)) * np.cos(phi)), ((radius * np.sin(theta)) * np.sin(phi)), (radius * np.cos(theta))]).squeeze() | Convert from spherical (theta, phi, r) to cartesian (x, y, z) coordinates.
Theta and phi must be specified in radians and returned units correspond to
units of r, default is unitless (r=1 is unit vector). Returns vectors along
z-axis (e.g., if theta and phi are int/float return 1x1x3 vector; if theta
and phi are MxN arrays return 3D array of vectors MxNx3).
Parameters
----------
theta (num or array): Polar angle [rad].
phi (num or array): Azimuthal angle [rad].
radius (num or array): Radius (default=1).
Returns
-------
cartesian (array): Cartesian vector(s), same shape as theta and phi. | roughness/helpers.py | sph2cart | NAU-PIXEL/roughness | 0 | python | def sph2cart(theta, phi, radius=1):
'\n Convert from spherical (theta, phi, r) to cartesian (x, y, z) coordinates.\n\n Theta and phi must be specified in radians and returned units correspond to\n units of r, default is unitless (r=1 is unit vector). Returns vectors along\n z-axis (e.g., if theta and phi are int/float return 1x1x3 vector; if theta\n and phi are MxN arrays return 3D array of vectors MxNx3).\n\n Parameters\n ----------\n theta (num or array): Polar angle [rad].\n phi (num or array): Azimuthal angle [rad].\n radius (num or array): Radius (default=1).\n\n Returns\n -------\n cartesian (array): Cartesian vector(s), same shape as theta and phi.\n '
return np.dstack([((radius * np.sin(theta)) * np.cos(phi)), ((radius * np.sin(theta)) * np.sin(phi)), (radius * np.cos(theta))]).squeeze() | def sph2cart(theta, phi, radius=1):
'\n Convert from spherical (theta, phi, r) to cartesian (x, y, z) coordinates.\n\n Theta and phi must be specified in radians and returned units correspond to\n units of r, default is unitless (r=1 is unit vector). Returns vectors along\n z-axis (e.g., if theta and phi are int/float return 1x1x3 vector; if theta\n and phi are MxN arrays return 3D array of vectors MxNx3).\n\n Parameters\n ----------\n theta (num or array): Polar angle [rad].\n phi (num or array): Azimuthal angle [rad].\n radius (num or array): Radius (default=1).\n\n Returns\n -------\n cartesian (array): Cartesian vector(s), same shape as theta and phi.\n '
return np.dstack([((radius * np.sin(theta)) * np.cos(phi)), ((radius * np.sin(theta)) * np.sin(phi)), (radius * np.cos(theta))]).squeeze()<|docstring|>Convert from spherical (theta, phi, r) to cartesian (x, y, z) coordinates.
Theta and phi must be specified in radians and returned units correspond to
units of r, default is unitless (r=1 is unit vector). Returns vectors along
z-axis (e.g., if theta and phi are int/float return 1x1x3 vector; if theta
and phi are MxN arrays return 3D array of vectors MxNx3).
Parameters
----------
theta (num or array): Polar angle [rad].
phi (num or array): Azimuthal angle [rad].
radius (num or array): Radius (default=1).
Returns
-------
cartesian (array): Cartesian vector(s), same shape as theta and phi.<|endoftext|> |
704526fe3549681ce473a0b0331979d1833476b8de4436c4f779f6b6173ab5bb | def xy2lonlat_coords(x, y, extent):
'Convert x,y coordinates to lat,lon coordinates.'
lon = np.linspace(extent[0], extent[1], len(x))
lat = np.linspace(extent[3], extent[2], len(y))
return (lon, lat) | Convert x,y coordinates to lat,lon coordinates. | roughness/helpers.py | xy2lonlat_coords | NAU-PIXEL/roughness | 0 | python | def xy2lonlat_coords(x, y, extent):
lon = np.linspace(extent[0], extent[1], len(x))
lat = np.linspace(extent[3], extent[2], len(y))
return (lon, lat) | def xy2lonlat_coords(x, y, extent):
lon = np.linspace(extent[0], extent[1], len(x))
lat = np.linspace(extent[3], extent[2], len(y))
return (lon, lat)<|docstring|>Convert x,y coordinates to lat,lon coordinates.<|endoftext|> |
2dd327cc87054f07f1ab8e756e724d36ad002eda6f31cd79895fce7bb5967731 | def tokenize(line: str) -> Token:
'Return the token for the line.'
for token in Token:
if line.startswith(token.value):
return token
return Token.DEFAULT | Return the token for the line. | src/poetry_merge_lock/parser.py | tokenize | davidszotten/poetry-merge-lock | 3 | python | def tokenize(line: str) -> Token:
for token in Token:
if line.startswith(token.value):
return token
return Token.DEFAULT | def tokenize(line: str) -> Token:
for token in Token:
if line.startswith(token.value):
return token
return Token.DEFAULT<|docstring|>Return the token for the line.<|endoftext|> |
f1f1a8367b64f57b617ba99c9921ace9e31c6ca0a44fb654333bd0e281bacf92 | def parse_line(line: str, state: State) -> Tuple[(Token, State)]:
'Parse a single line in a file with merge conflicts.\n\n Args:\n line: The line to be parsed.\n state: The current parser state.\n\n Returns:\n A pair, consisting of the token for the line, and the new parser state.\n\n Raises:\n UnexpectedTokenError: The parser encountered an unexpected token.\n '
token = tokenize(line)
for ((valid_state, the_token), next_state) in state_transitions.items():
if (token is the_token):
if (state is not valid_state):
raise UnexpectedTokenError(token)
return (token, next_state)
return (token, state) | Parse a single line in a file with merge conflicts.
Args:
line: The line to be parsed.
state: The current parser state.
Returns:
A pair, consisting of the token for the line, and the new parser state.
Raises:
UnexpectedTokenError: The parser encountered an unexpected token. | src/poetry_merge_lock/parser.py | parse_line | davidszotten/poetry-merge-lock | 3 | python | def parse_line(line: str, state: State) -> Tuple[(Token, State)]:
'Parse a single line in a file with merge conflicts.\n\n Args:\n line: The line to be parsed.\n state: The current parser state.\n\n Returns:\n A pair, consisting of the token for the line, and the new parser state.\n\n Raises:\n UnexpectedTokenError: The parser encountered an unexpected token.\n '
token = tokenize(line)
for ((valid_state, the_token), next_state) in state_transitions.items():
if (token is the_token):
if (state is not valid_state):
raise UnexpectedTokenError(token)
return (token, next_state)
return (token, state) | def parse_line(line: str, state: State) -> Tuple[(Token, State)]:
'Parse a single line in a file with merge conflicts.\n\n Args:\n line: The line to be parsed.\n state: The current parser state.\n\n Returns:\n A pair, consisting of the token for the line, and the new parser state.\n\n Raises:\n UnexpectedTokenError: The parser encountered an unexpected token.\n '
token = tokenize(line)
for ((valid_state, the_token), next_state) in state_transitions.items():
if (token is the_token):
if (state is not valid_state):
raise UnexpectedTokenError(token)
return (token, next_state)
return (token, state)<|docstring|>Parse a single line in a file with merge conflicts.
Args:
line: The line to be parsed.
state: The current parser state.
Returns:
A pair, consisting of the token for the line, and the new parser state.
Raises:
UnexpectedTokenError: The parser encountered an unexpected token.<|endoftext|> |
6eb12fa85a4ed9eb4710d7118f4e7cf66d982df0c6c456e3a931f5652541b5b1 | def parse_lines(lines: Sequence[str]) -> Iterator[Tuple[(Optional[str], Optional[str])]]:
'Parse a sequence of lines with merge conflicts.\n\n Args:\n lines: The sequence of lines to be parsed.\n\n Yields:\n Pairs, where first item in each pair is a line in *our* version, and\n the second, in *their* version. An item is ``None`` if the line does\n not occur in that version.\n\n Raises:\n ValueError: A conflict marker was not terminated.\n '
state = State.COMMON
for line in lines:
(token, state) = parse_line(line, state)
if (token is not Token.DEFAULT):
continue
if (state is State.OURS):
(yield (line, None))
elif (state is State.THEIRS):
(yield (None, line))
else:
(yield (line, line))
if (state is not State.COMMON):
raise ValueError('unterminated conflict marker') | Parse a sequence of lines with merge conflicts.
Args:
lines: The sequence of lines to be parsed.
Yields:
Pairs, where first item in each pair is a line in *our* version, and
the second, in *their* version. An item is ``None`` if the line does
not occur in that version.
Raises:
ValueError: A conflict marker was not terminated. | src/poetry_merge_lock/parser.py | parse_lines | davidszotten/poetry-merge-lock | 3 | python | def parse_lines(lines: Sequence[str]) -> Iterator[Tuple[(Optional[str], Optional[str])]]:
'Parse a sequence of lines with merge conflicts.\n\n Args:\n lines: The sequence of lines to be parsed.\n\n Yields:\n Pairs, where first item in each pair is a line in *our* version, and\n the second, in *their* version. An item is ``None`` if the line does\n not occur in that version.\n\n Raises:\n ValueError: A conflict marker was not terminated.\n '
state = State.COMMON
for line in lines:
(token, state) = parse_line(line, state)
if (token is not Token.DEFAULT):
continue
if (state is State.OURS):
(yield (line, None))
elif (state is State.THEIRS):
(yield (None, line))
else:
(yield (line, line))
if (state is not State.COMMON):
raise ValueError('unterminated conflict marker') | def parse_lines(lines: Sequence[str]) -> Iterator[Tuple[(Optional[str], Optional[str])]]:
'Parse a sequence of lines with merge conflicts.\n\n Args:\n lines: The sequence of lines to be parsed.\n\n Yields:\n Pairs, where first item in each pair is a line in *our* version, and\n the second, in *their* version. An item is ``None`` if the line does\n not occur in that version.\n\n Raises:\n ValueError: A conflict marker was not terminated.\n '
state = State.COMMON
for line in lines:
(token, state) = parse_line(line, state)
if (token is not Token.DEFAULT):
continue
if (state is State.OURS):
(yield (line, None))
elif (state is State.THEIRS):
(yield (None, line))
else:
(yield (line, line))
if (state is not State.COMMON):
raise ValueError('unterminated conflict marker')<|docstring|>Parse a sequence of lines with merge conflicts.
Args:
lines: The sequence of lines to be parsed.
Yields:
Pairs, where first item in each pair is a line in *our* version, and
the second, in *their* version. An item is ``None`` if the line does
not occur in that version.
Raises:
ValueError: A conflict marker was not terminated.<|endoftext|> |
db1244c545239b9f9af98fba657061b2e81342b9ba3dedc4328fce57ba3be99b | def parse(lines: Sequence[str]) -> Tuple[(Sequence[str], Sequence[str])]:
'Parse a sequence of lines with merge conflicts.\n\n Args:\n lines: The sequence of lines to be parsed.\n\n Returns:\n A pair of sequences of lines. The first sequence corresponds to *our*\n version, and the second, to *their* version.\n '
result = parse_lines(lines)
(ours, theirs) = zip(*result)
return ([line for line in ours if (line is not None)], [line for line in theirs if (line is not None)]) | Parse a sequence of lines with merge conflicts.
Args:
lines: The sequence of lines to be parsed.
Returns:
A pair of sequences of lines. The first sequence corresponds to *our*
version, and the second, to *their* version. | src/poetry_merge_lock/parser.py | parse | davidszotten/poetry-merge-lock | 3 | python | def parse(lines: Sequence[str]) -> Tuple[(Sequence[str], Sequence[str])]:
'Parse a sequence of lines with merge conflicts.\n\n Args:\n lines: The sequence of lines to be parsed.\n\n Returns:\n A pair of sequences of lines. The first sequence corresponds to *our*\n version, and the second, to *their* version.\n '
result = parse_lines(lines)
(ours, theirs) = zip(*result)
return ([line for line in ours if (line is not None)], [line for line in theirs if (line is not None)]) | def parse(lines: Sequence[str]) -> Tuple[(Sequence[str], Sequence[str])]:
'Parse a sequence of lines with merge conflicts.\n\n Args:\n lines: The sequence of lines to be parsed.\n\n Returns:\n A pair of sequences of lines. The first sequence corresponds to *our*\n version, and the second, to *their* version.\n '
result = parse_lines(lines)
(ours, theirs) = zip(*result)
return ([line for line in ours if (line is not None)], [line for line in theirs if (line is not None)])<|docstring|>Parse a sequence of lines with merge conflicts.
Args:
lines: The sequence of lines to be parsed.
Returns:
A pair of sequences of lines. The first sequence corresponds to *our*
version, and the second, to *their* version.<|endoftext|> |
70461a013c5695450a2dc1b925c2c9e3d9dea4432d60bcb5febffe4990b6f15c | def __init__(self, token: Token) -> None:
'Constructor.'
super().__init__('unexpected token {}'.format(token)) | Constructor. | src/poetry_merge_lock/parser.py | __init__ | davidszotten/poetry-merge-lock | 3 | python | def __init__(self, token: Token) -> None:
super().__init__('unexpected token {}'.format(token)) | def __init__(self, token: Token) -> None:
super().__init__('unexpected token {}'.format(token))<|docstring|>Constructor.<|endoftext|> |
092fd016fbc06fc8e2d941cce308681b86bb84b9580ab3c58f5a600524765f01 | def embedded_broker_deprecated(value):
'Warn user that embedded MQTT broker is deprecated.'
_LOGGER.warning('The embedded MQTT broker has been deprecated and will stop workingafter June 5th, 2019. Use an external broker instead. Forinstructions, see https://www.home-assistant.io/docs/mqtt/broker')
return value | Warn user that embedded MQTT broker is deprecated. | homeassistant/components/mqtt/__init__.py | embedded_broker_deprecated | 3guoyangyang7/core | 11 | python | def embedded_broker_deprecated(value):
_LOGGER.warning('The embedded MQTT broker has been deprecated and will stop workingafter June 5th, 2019. Use an external broker instead. Forinstructions, see https://www.home-assistant.io/docs/mqtt/broker')
return value | def embedded_broker_deprecated(value):
_LOGGER.warning('The embedded MQTT broker has been deprecated and will stop workingafter June 5th, 2019. Use an external broker instead. Forinstructions, see https://www.home-assistant.io/docs/mqtt/broker')
return value<|docstring|>Warn user that embedded MQTT broker is deprecated.<|endoftext|> |
3b565469dff1469f87dd10ee8fba174886e87e6f0b59273b5b245ddaec65a34e | def _build_publish_data(topic: Any, qos: int, retain: bool) -> ServiceDataType:
'Build the arguments for the publish service without the payload.'
data = {ATTR_TOPIC: topic}
if (qos is not None):
data[ATTR_QOS] = qos
if (retain is not None):
data[ATTR_RETAIN] = retain
return data | Build the arguments for the publish service without the payload. | homeassistant/components/mqtt/__init__.py | _build_publish_data | 3guoyangyang7/core | 11 | python | def _build_publish_data(topic: Any, qos: int, retain: bool) -> ServiceDataType:
data = {ATTR_TOPIC: topic}
if (qos is not None):
data[ATTR_QOS] = qos
if (retain is not None):
data[ATTR_RETAIN] = retain
return data | def _build_publish_data(topic: Any, qos: int, retain: bool) -> ServiceDataType:
data = {ATTR_TOPIC: topic}
if (qos is not None):
data[ATTR_QOS] = qos
if (retain is not None):
data[ATTR_RETAIN] = retain
return data<|docstring|>Build the arguments for the publish service without the payload.<|endoftext|> |
f0f3ee8e9234328251cfda5f232d0cbb08b8938bd75678e54d60167359a19d31 | @bind_hass
def publish(hass: HomeAssistant, topic, payload, qos=None, retain=None) -> None:
'Publish message to an MQTT topic.'
hass.add_job(async_publish, hass, topic, payload, qos, retain) | Publish message to an MQTT topic. | homeassistant/components/mqtt/__init__.py | publish | 3guoyangyang7/core | 11 | python | @bind_hass
def publish(hass: HomeAssistant, topic, payload, qos=None, retain=None) -> None:
hass.add_job(async_publish, hass, topic, payload, qos, retain) | @bind_hass
def publish(hass: HomeAssistant, topic, payload, qos=None, retain=None) -> None:
hass.add_job(async_publish, hass, topic, payload, qos, retain)<|docstring|>Publish message to an MQTT topic.<|endoftext|> |
817a9a57822a6b1708fc1a04a82c2f2cdf9f467aaf0523e14a9d3de5069a62ff | @callback
@bind_hass
def async_publish(hass: HomeAssistant, topic: Any, payload, qos=None, retain=None) -> None:
'Publish message to an MQTT topic.'
data = _build_publish_data(topic, qos, retain)
data[ATTR_PAYLOAD] = payload
hass.async_create_task(hass.services.async_call(DOMAIN, SERVICE_PUBLISH, data)) | Publish message to an MQTT topic. | homeassistant/components/mqtt/__init__.py | async_publish | 3guoyangyang7/core | 11 | python | @callback
@bind_hass
def async_publish(hass: HomeAssistant, topic: Any, payload, qos=None, retain=None) -> None:
data = _build_publish_data(topic, qos, retain)
data[ATTR_PAYLOAD] = payload
hass.async_create_task(hass.services.async_call(DOMAIN, SERVICE_PUBLISH, data)) | @callback
@bind_hass
def async_publish(hass: HomeAssistant, topic: Any, payload, qos=None, retain=None) -> None:
data = _build_publish_data(topic, qos, retain)
data[ATTR_PAYLOAD] = payload
hass.async_create_task(hass.services.async_call(DOMAIN, SERVICE_PUBLISH, data))<|docstring|>Publish message to an MQTT topic.<|endoftext|> |
89687d91e0dc874c0c08066a9cefd44f92b13bf565a75a8f3533f4097625f7bf | @bind_hass
def publish_template(hass: HomeAssistant, topic, payload_template, qos=None, retain=None) -> None:
'Publish message to an MQTT topic.'
hass.add_job(async_publish_template, hass, topic, payload_template, qos, retain) | Publish message to an MQTT topic. | homeassistant/components/mqtt/__init__.py | publish_template | 3guoyangyang7/core | 11 | python | @bind_hass
def publish_template(hass: HomeAssistant, topic, payload_template, qos=None, retain=None) -> None:
hass.add_job(async_publish_template, hass, topic, payload_template, qos, retain) | @bind_hass
def publish_template(hass: HomeAssistant, topic, payload_template, qos=None, retain=None) -> None:
hass.add_job(async_publish_template, hass, topic, payload_template, qos, retain)<|docstring|>Publish message to an MQTT topic.<|endoftext|> |
64744dea278830a2ed71ce73fa8adb9c3b8eba3a695b0a3e2394a71df86cea89 | @bind_hass
def async_publish_template(hass: HomeAssistant, topic, payload_template, qos=None, retain=None) -> None:
'Publish message to an MQTT topic using a template payload.'
data = _build_publish_data(topic, qos, retain)
data[ATTR_PAYLOAD_TEMPLATE] = payload_template
hass.async_create_task(hass.services.async_call(DOMAIN, SERVICE_PUBLISH, data)) | Publish message to an MQTT topic using a template payload. | homeassistant/components/mqtt/__init__.py | async_publish_template | 3guoyangyang7/core | 11 | python | @bind_hass
def async_publish_template(hass: HomeAssistant, topic, payload_template, qos=None, retain=None) -> None:
data = _build_publish_data(topic, qos, retain)
data[ATTR_PAYLOAD_TEMPLATE] = payload_template
hass.async_create_task(hass.services.async_call(DOMAIN, SERVICE_PUBLISH, data)) | @bind_hass
def async_publish_template(hass: HomeAssistant, topic, payload_template, qos=None, retain=None) -> None:
data = _build_publish_data(topic, qos, retain)
data[ATTR_PAYLOAD_TEMPLATE] = payload_template
hass.async_create_task(hass.services.async_call(DOMAIN, SERVICE_PUBLISH, data))<|docstring|>Publish message to an MQTT topic using a template payload.<|endoftext|> |
534eb5037b64ae118035eaf59ce9fb9f22348501ac0313fd1a4aebfac9fd2865 | def wrap_msg_callback(msg_callback: (AsyncDeprecatedMessageCallbackType | DeprecatedMessageCallbackType)) -> (AsyncMessageCallbackType | MessageCallbackType):
'Wrap an MQTT message callback to support deprecated signature.'
check_func = msg_callback
while isinstance(check_func, partial):
check_func = check_func.func
wrapper_func: (AsyncMessageCallbackType | MessageCallbackType)
if asyncio.iscoroutinefunction(check_func):
@wraps(msg_callback)
async def async_wrapper(msg: ReceiveMessage) -> None:
'Call with deprecated signature.'
(await cast(AsyncDeprecatedMessageCallbackType, msg_callback)(msg.topic, msg.payload, msg.qos))
wrapper_func = async_wrapper
else:
@wraps(msg_callback)
def wrapper(msg: ReceiveMessage) -> None:
'Call with deprecated signature.'
msg_callback(msg.topic, msg.payload, msg.qos)
wrapper_func = wrapper
return wrapper_func | Wrap an MQTT message callback to support deprecated signature. | homeassistant/components/mqtt/__init__.py | wrap_msg_callback | 3guoyangyang7/core | 11 | python | def wrap_msg_callback(msg_callback: (AsyncDeprecatedMessageCallbackType | DeprecatedMessageCallbackType)) -> (AsyncMessageCallbackType | MessageCallbackType):
check_func = msg_callback
while isinstance(check_func, partial):
check_func = check_func.func
wrapper_func: (AsyncMessageCallbackType | MessageCallbackType)
if asyncio.iscoroutinefunction(check_func):
@wraps(msg_callback)
async def async_wrapper(msg: ReceiveMessage) -> None:
'Call with deprecated signature.'
(await cast(AsyncDeprecatedMessageCallbackType, msg_callback)(msg.topic, msg.payload, msg.qos))
wrapper_func = async_wrapper
else:
@wraps(msg_callback)
def wrapper(msg: ReceiveMessage) -> None:
'Call with deprecated signature.'
msg_callback(msg.topic, msg.payload, msg.qos)
wrapper_func = wrapper
return wrapper_func | def wrap_msg_callback(msg_callback: (AsyncDeprecatedMessageCallbackType | DeprecatedMessageCallbackType)) -> (AsyncMessageCallbackType | MessageCallbackType):
check_func = msg_callback
while isinstance(check_func, partial):
check_func = check_func.func
wrapper_func: (AsyncMessageCallbackType | MessageCallbackType)
if asyncio.iscoroutinefunction(check_func):
@wraps(msg_callback)
async def async_wrapper(msg: ReceiveMessage) -> None:
'Call with deprecated signature.'
(await cast(AsyncDeprecatedMessageCallbackType, msg_callback)(msg.topic, msg.payload, msg.qos))
wrapper_func = async_wrapper
else:
@wraps(msg_callback)
def wrapper(msg: ReceiveMessage) -> None:
'Call with deprecated signature.'
msg_callback(msg.topic, msg.payload, msg.qos)
wrapper_func = wrapper
return wrapper_func<|docstring|>Wrap an MQTT message callback to support deprecated signature.<|endoftext|> |
c64f516d97c12e56e816e315f36992395e64936425feb31c759fc2c8389fbdd3 | @bind_hass
async def async_subscribe(hass: HomeAssistant, topic: str, msg_callback: (((AsyncMessageCallbackType | MessageCallbackType) | DeprecatedMessageCallbackType) | AsyncDeprecatedMessageCallbackType), qos: int=DEFAULT_QOS, encoding: (str | None)='utf-8'):
'Subscribe to an MQTT topic.\n\n Call the return value to unsubscribe.\n '
non_default = 0
if msg_callback:
non_default = sum(((p.default == inspect.Parameter.empty) for (_, p) in inspect.signature(msg_callback).parameters.items()))
wrapped_msg_callback = msg_callback
if (non_default == 3):
module = inspect.getmodule(msg_callback)
_LOGGER.warning("Signature of MQTT msg_callback '%s.%s' is deprecated", (module.__name__ if module else '<unknown>'), msg_callback.__name__)
wrapped_msg_callback = wrap_msg_callback(cast(DeprecatedMessageCallbackType, msg_callback))
async_remove = (await hass.data[DATA_MQTT].async_subscribe(topic, catch_log_exception(wrapped_msg_callback, (lambda msg: f"Exception in {msg_callback.__name__} when handling msg on '{msg.topic}': '{msg.payload}'")), qos, encoding))
return async_remove | Subscribe to an MQTT topic.
Call the return value to unsubscribe. | homeassistant/components/mqtt/__init__.py | async_subscribe | 3guoyangyang7/core | 11 | python | @bind_hass
async def async_subscribe(hass: HomeAssistant, topic: str, msg_callback: (((AsyncMessageCallbackType | MessageCallbackType) | DeprecatedMessageCallbackType) | AsyncDeprecatedMessageCallbackType), qos: int=DEFAULT_QOS, encoding: (str | None)='utf-8'):
'Subscribe to an MQTT topic.\n\n Call the return value to unsubscribe.\n '
non_default = 0
if msg_callback:
non_default = sum(((p.default == inspect.Parameter.empty) for (_, p) in inspect.signature(msg_callback).parameters.items()))
wrapped_msg_callback = msg_callback
if (non_default == 3):
module = inspect.getmodule(msg_callback)
_LOGGER.warning("Signature of MQTT msg_callback '%s.%s' is deprecated", (module.__name__ if module else '<unknown>'), msg_callback.__name__)
wrapped_msg_callback = wrap_msg_callback(cast(DeprecatedMessageCallbackType, msg_callback))
async_remove = (await hass.data[DATA_MQTT].async_subscribe(topic, catch_log_exception(wrapped_msg_callback, (lambda msg: f"Exception in {msg_callback.__name__} when handling msg on '{msg.topic}': '{msg.payload}'")), qos, encoding))
return async_remove | @bind_hass
async def async_subscribe(hass: HomeAssistant, topic: str, msg_callback: (((AsyncMessageCallbackType | MessageCallbackType) | DeprecatedMessageCallbackType) | AsyncDeprecatedMessageCallbackType), qos: int=DEFAULT_QOS, encoding: (str | None)='utf-8'):
'Subscribe to an MQTT topic.\n\n Call the return value to unsubscribe.\n '
non_default = 0
if msg_callback:
non_default = sum(((p.default == inspect.Parameter.empty) for (_, p) in inspect.signature(msg_callback).parameters.items()))
wrapped_msg_callback = msg_callback
if (non_default == 3):
module = inspect.getmodule(msg_callback)
_LOGGER.warning("Signature of MQTT msg_callback '%s.%s' is deprecated", (module.__name__ if module else '<unknown>'), msg_callback.__name__)
wrapped_msg_callback = wrap_msg_callback(cast(DeprecatedMessageCallbackType, msg_callback))
async_remove = (await hass.data[DATA_MQTT].async_subscribe(topic, catch_log_exception(wrapped_msg_callback, (lambda msg: f"Exception in {msg_callback.__name__} when handling msg on '{msg.topic}': '{msg.payload}'")), qos, encoding))
return async_remove<|docstring|>Subscribe to an MQTT topic.
Call the return value to unsubscribe.<|endoftext|> |
247cfd23a947ffbcab3ee46125aef06af59cfd12431dce6c4d367d4e7726c149 | @bind_hass
def subscribe(hass: HomeAssistant, topic: str, msg_callback: MessageCallbackType, qos: int=DEFAULT_QOS, encoding: str='utf-8') -> Callable[([], None)]:
'Subscribe to an MQTT topic.'
async_remove = asyncio.run_coroutine_threadsafe(async_subscribe(hass, topic, msg_callback, qos, encoding), hass.loop).result()
def remove():
'Remove listener convert.'
run_callback_threadsafe(hass.loop, async_remove).result()
return remove | Subscribe to an MQTT topic. | homeassistant/components/mqtt/__init__.py | subscribe | 3guoyangyang7/core | 11 | python | @bind_hass
def subscribe(hass: HomeAssistant, topic: str, msg_callback: MessageCallbackType, qos: int=DEFAULT_QOS, encoding: str='utf-8') -> Callable[([], None)]:
async_remove = asyncio.run_coroutine_threadsafe(async_subscribe(hass, topic, msg_callback, qos, encoding), hass.loop).result()
def remove():
'Remove listener convert.'
run_callback_threadsafe(hass.loop, async_remove).result()
return remove | @bind_hass
def subscribe(hass: HomeAssistant, topic: str, msg_callback: MessageCallbackType, qos: int=DEFAULT_QOS, encoding: str='utf-8') -> Callable[([], None)]:
async_remove = asyncio.run_coroutine_threadsafe(async_subscribe(hass, topic, msg_callback, qos, encoding), hass.loop).result()
def remove():
'Remove listener convert.'
run_callback_threadsafe(hass.loop, async_remove).result()
return remove<|docstring|>Subscribe to an MQTT topic.<|endoftext|> |
315f0cb6283fd270e2ae1d1dfb9b10b014643a6a2d07ffe5aefb42ce45101b47 | async def _async_setup_discovery(hass: HomeAssistant, conf: ConfigType, config_entry) -> None:
'Try to start the discovery of MQTT devices.\n\n This method is a coroutine.\n '
(await discovery.async_start(hass, conf[CONF_DISCOVERY_PREFIX], config_entry)) | Try to start the discovery of MQTT devices.
This method is a coroutine. | homeassistant/components/mqtt/__init__.py | _async_setup_discovery | 3guoyangyang7/core | 11 | python | async def _async_setup_discovery(hass: HomeAssistant, conf: ConfigType, config_entry) -> None:
'Try to start the discovery of MQTT devices.\n\n This method is a coroutine.\n '
(await discovery.async_start(hass, conf[CONF_DISCOVERY_PREFIX], config_entry)) | async def _async_setup_discovery(hass: HomeAssistant, conf: ConfigType, config_entry) -> None:
'Try to start the discovery of MQTT devices.\n\n This method is a coroutine.\n '
(await discovery.async_start(hass, conf[CONF_DISCOVERY_PREFIX], config_entry))<|docstring|>Try to start the discovery of MQTT devices.
This method is a coroutine.<|endoftext|> |
2c9e1a8735d4e80e0a4611d697a2c29745cf74c8a73acfac5c6a50ccc4235fa9 | async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
'Start the MQTT protocol service.'
conf: (ConfigType | None) = config.get(DOMAIN)
websocket_api.async_register_command(hass, websocket_subscribe)
websocket_api.async_register_command(hass, websocket_remove_device)
websocket_api.async_register_command(hass, websocket_mqtt_info)
if (conf is None):
return bool(hass.config_entries.async_entries(DOMAIN))
conf = dict(conf)
hass.data[DATA_MQTT_CONFIG] = conf
if (not hass.config_entries.async_entries(DOMAIN)):
hass.async_create_task(hass.config_entries.flow.async_init(DOMAIN, context={'source': config_entries.SOURCE_IMPORT}, data={}))
return True | Start the MQTT protocol service. | homeassistant/components/mqtt/__init__.py | async_setup | 3guoyangyang7/core | 11 | python | async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
conf: (ConfigType | None) = config.get(DOMAIN)
websocket_api.async_register_command(hass, websocket_subscribe)
websocket_api.async_register_command(hass, websocket_remove_device)
websocket_api.async_register_command(hass, websocket_mqtt_info)
if (conf is None):
return bool(hass.config_entries.async_entries(DOMAIN))
conf = dict(conf)
hass.data[DATA_MQTT_CONFIG] = conf
if (not hass.config_entries.async_entries(DOMAIN)):
hass.async_create_task(hass.config_entries.flow.async_init(DOMAIN, context={'source': config_entries.SOURCE_IMPORT}, data={}))
return True | async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
conf: (ConfigType | None) = config.get(DOMAIN)
websocket_api.async_register_command(hass, websocket_subscribe)
websocket_api.async_register_command(hass, websocket_remove_device)
websocket_api.async_register_command(hass, websocket_mqtt_info)
if (conf is None):
return bool(hass.config_entries.async_entries(DOMAIN))
conf = dict(conf)
hass.data[DATA_MQTT_CONFIG] = conf
if (not hass.config_entries.async_entries(DOMAIN)):
hass.async_create_task(hass.config_entries.flow.async_init(DOMAIN, context={'source': config_entries.SOURCE_IMPORT}, data={}))
return True<|docstring|>Start the MQTT protocol service.<|endoftext|> |
c29fbb746cfedc8e550615f5254735ac355375545ecc0e5d70e260db34782a1a | def _merge_config(entry, conf):
'Merge configuration.yaml config with config entry.'
return {**conf, **entry.data} | Merge configuration.yaml config with config entry. | homeassistant/components/mqtt/__init__.py | _merge_config | 3guoyangyang7/core | 11 | python | def _merge_config(entry, conf):
return {**conf, **entry.data} | def _merge_config(entry, conf):
return {**conf, **entry.data}<|docstring|>Merge configuration.yaml config with config entry.<|endoftext|> |
f2d532e284e2fbd9dd2e47a4fbb021068e46d3b90e1acbacbe43febd2158570d | async def async_setup_entry(hass, entry):
'Load a config entry.'
conf = hass.data.get(DATA_MQTT_CONFIG)
if ((conf is None) and (entry.source == config_entries.SOURCE_IMPORT)):
hass.async_create_task(hass.config_entries.async_remove(entry.entry_id))
return False
if (conf is None):
conf = CONFIG_SCHEMA({DOMAIN: dict(entry.data)})[DOMAIN]
elif any(((key in conf) for key in entry.data)):
shared_keys = (conf.keys() & entry.data.keys())
override = {k: entry.data[k] for k in shared_keys}
if (CONF_PASSWORD in override):
override[CONF_PASSWORD] = '********'
_LOGGER.info('Data in your configuration entry is going to override your configuration.yaml: %s', override)
conf = _merge_config(entry, conf)
hass.data[DATA_MQTT] = MQTT(hass, entry, conf)
(await hass.data[DATA_MQTT].async_connect())
async def async_stop_mqtt(_event: Event):
'Stop MQTT component.'
(await hass.data[DATA_MQTT].async_disconnect())
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, async_stop_mqtt)
async def async_publish_service(call: ServiceCall):
'Handle MQTT publish service calls.'
msg_topic: str = call.data[ATTR_TOPIC]
payload = call.data.get(ATTR_PAYLOAD)
payload_template = call.data.get(ATTR_PAYLOAD_TEMPLATE)
qos: int = call.data[ATTR_QOS]
retain: bool = call.data[ATTR_RETAIN]
if (payload_template is not None):
try:
payload = template.Template(payload_template, hass).async_render(parse_result=False)
except template.jinja2.TemplateError as exc:
_LOGGER.error('Unable to publish to %s: rendering payload template of %s failed because %s', msg_topic, payload_template, exc)
return
(await hass.data[DATA_MQTT].async_publish(msg_topic, payload, qos, retain))
hass.services.async_register(DOMAIN, SERVICE_PUBLISH, async_publish_service, schema=MQTT_PUBLISH_SCHEMA)
async def async_dump_service(call: ServiceCall):
'Handle MQTT dump service calls.'
messages = []
@callback
def collect_msg(msg):
messages.append((msg.topic, msg.payload.replace('\n', '')))
unsub = (await async_subscribe(hass, call.data['topic'], collect_msg))
def write_dump():
with open(hass.config.path('mqtt_dump.txt'), 'wt') as fp:
for msg in messages:
fp.write((','.join(msg) + '\n'))
async def finish_dump(_):
'Write dump to file.'
unsub()
(await hass.async_add_executor_job(write_dump))
event.async_call_later(hass, call.data['duration'], finish_dump)
hass.services.async_register(DOMAIN, SERVICE_DUMP, async_dump_service, schema=vol.Schema({vol.Required('topic'): valid_subscribe_topic, vol.Optional('duration', default=5): int}))
if conf.get(CONF_DISCOVERY):
(await _async_setup_discovery(hass, conf, entry))
return True | Load a config entry. | homeassistant/components/mqtt/__init__.py | async_setup_entry | 3guoyangyang7/core | 11 | python | async def async_setup_entry(hass, entry):
conf = hass.data.get(DATA_MQTT_CONFIG)
if ((conf is None) and (entry.source == config_entries.SOURCE_IMPORT)):
hass.async_create_task(hass.config_entries.async_remove(entry.entry_id))
return False
if (conf is None):
conf = CONFIG_SCHEMA({DOMAIN: dict(entry.data)})[DOMAIN]
elif any(((key in conf) for key in entry.data)):
shared_keys = (conf.keys() & entry.data.keys())
override = {k: entry.data[k] for k in shared_keys}
if (CONF_PASSWORD in override):
override[CONF_PASSWORD] = '********'
_LOGGER.info('Data in your configuration entry is going to override your configuration.yaml: %s', override)
conf = _merge_config(entry, conf)
hass.data[DATA_MQTT] = MQTT(hass, entry, conf)
(await hass.data[DATA_MQTT].async_connect())
async def async_stop_mqtt(_event: Event):
'Stop MQTT component.'
(await hass.data[DATA_MQTT].async_disconnect())
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, async_stop_mqtt)
async def async_publish_service(call: ServiceCall):
'Handle MQTT publish service calls.'
msg_topic: str = call.data[ATTR_TOPIC]
payload = call.data.get(ATTR_PAYLOAD)
payload_template = call.data.get(ATTR_PAYLOAD_TEMPLATE)
qos: int = call.data[ATTR_QOS]
retain: bool = call.data[ATTR_RETAIN]
if (payload_template is not None):
try:
payload = template.Template(payload_template, hass).async_render(parse_result=False)
except template.jinja2.TemplateError as exc:
_LOGGER.error('Unable to publish to %s: rendering payload template of %s failed because %s', msg_topic, payload_template, exc)
return
(await hass.data[DATA_MQTT].async_publish(msg_topic, payload, qos, retain))
hass.services.async_register(DOMAIN, SERVICE_PUBLISH, async_publish_service, schema=MQTT_PUBLISH_SCHEMA)
async def async_dump_service(call: ServiceCall):
'Handle MQTT dump service calls.'
messages = []
@callback
def collect_msg(msg):
messages.append((msg.topic, msg.payload.replace('\n', )))
unsub = (await async_subscribe(hass, call.data['topic'], collect_msg))
def write_dump():
with open(hass.config.path('mqtt_dump.txt'), 'wt') as fp:
for msg in messages:
fp.write((','.join(msg) + '\n'))
async def finish_dump(_):
'Write dump to file.'
unsub()
(await hass.async_add_executor_job(write_dump))
event.async_call_later(hass, call.data['duration'], finish_dump)
hass.services.async_register(DOMAIN, SERVICE_DUMP, async_dump_service, schema=vol.Schema({vol.Required('topic'): valid_subscribe_topic, vol.Optional('duration', default=5): int}))
if conf.get(CONF_DISCOVERY):
(await _async_setup_discovery(hass, conf, entry))
return True | async def async_setup_entry(hass, entry):
conf = hass.data.get(DATA_MQTT_CONFIG)
if ((conf is None) and (entry.source == config_entries.SOURCE_IMPORT)):
hass.async_create_task(hass.config_entries.async_remove(entry.entry_id))
return False
if (conf is None):
conf = CONFIG_SCHEMA({DOMAIN: dict(entry.data)})[DOMAIN]
elif any(((key in conf) for key in entry.data)):
shared_keys = (conf.keys() & entry.data.keys())
override = {k: entry.data[k] for k in shared_keys}
if (CONF_PASSWORD in override):
override[CONF_PASSWORD] = '********'
_LOGGER.info('Data in your configuration entry is going to override your configuration.yaml: %s', override)
conf = _merge_config(entry, conf)
hass.data[DATA_MQTT] = MQTT(hass, entry, conf)
(await hass.data[DATA_MQTT].async_connect())
async def async_stop_mqtt(_event: Event):
'Stop MQTT component.'
(await hass.data[DATA_MQTT].async_disconnect())
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, async_stop_mqtt)
async def async_publish_service(call: ServiceCall):
'Handle MQTT publish service calls.'
msg_topic: str = call.data[ATTR_TOPIC]
payload = call.data.get(ATTR_PAYLOAD)
payload_template = call.data.get(ATTR_PAYLOAD_TEMPLATE)
qos: int = call.data[ATTR_QOS]
retain: bool = call.data[ATTR_RETAIN]
if (payload_template is not None):
try:
payload = template.Template(payload_template, hass).async_render(parse_result=False)
except template.jinja2.TemplateError as exc:
_LOGGER.error('Unable to publish to %s: rendering payload template of %s failed because %s', msg_topic, payload_template, exc)
return
(await hass.data[DATA_MQTT].async_publish(msg_topic, payload, qos, retain))
hass.services.async_register(DOMAIN, SERVICE_PUBLISH, async_publish_service, schema=MQTT_PUBLISH_SCHEMA)
async def async_dump_service(call: ServiceCall):
'Handle MQTT dump service calls.'
messages = []
@callback
def collect_msg(msg):
messages.append((msg.topic, msg.payload.replace('\n', )))
unsub = (await async_subscribe(hass, call.data['topic'], collect_msg))
def write_dump():
with open(hass.config.path('mqtt_dump.txt'), 'wt') as fp:
for msg in messages:
fp.write((','.join(msg) + '\n'))
async def finish_dump(_):
'Write dump to file.'
unsub()
(await hass.async_add_executor_job(write_dump))
event.async_call_later(hass, call.data['duration'], finish_dump)
hass.services.async_register(DOMAIN, SERVICE_DUMP, async_dump_service, schema=vol.Schema({vol.Required('topic'): valid_subscribe_topic, vol.Optional('duration', default=5): int}))
if conf.get(CONF_DISCOVERY):
(await _async_setup_discovery(hass, conf, entry))
return True<|docstring|>Load a config entry.<|endoftext|> |
f55abf1ae66e4618e9ad5d746e7c5dba62002b07b697bd10789768db2db1a5b7 | def _raise_on_error(result_code: (int | None)) -> None:
'Raise error if error result.'
import paho.mqtt.client as mqtt
if ((result_code is not None) and (result_code != 0)):
raise HomeAssistantError(f'Error talking to MQTT: {mqtt.error_string(result_code)}') | Raise error if error result. | homeassistant/components/mqtt/__init__.py | _raise_on_error | 3guoyangyang7/core | 11 | python | def _raise_on_error(result_code: (int | None)) -> None:
import paho.mqtt.client as mqtt
if ((result_code is not None) and (result_code != 0)):
raise HomeAssistantError(f'Error talking to MQTT: {mqtt.error_string(result_code)}') | def _raise_on_error(result_code: (int | None)) -> None:
import paho.mqtt.client as mqtt
if ((result_code is not None) and (result_code != 0)):
raise HomeAssistantError(f'Error talking to MQTT: {mqtt.error_string(result_code)}')<|docstring|>Raise error if error result.<|endoftext|> |
ed2ffcf43ac1648226951440245e6f8518b858bba1f485e5a1edd31af734911a | @websocket_api.websocket_command({vol.Required('type'): 'mqtt/device/debug_info', vol.Required('device_id'): str})
@websocket_api.async_response
async def websocket_mqtt_info(hass, connection, msg):
'Get MQTT debug info for device.'
device_id = msg['device_id']
mqtt_info = (await debug_info.info_for_device(hass, device_id))
connection.send_result(msg['id'], mqtt_info) | Get MQTT debug info for device. | homeassistant/components/mqtt/__init__.py | websocket_mqtt_info | 3guoyangyang7/core | 11 | python | @websocket_api.websocket_command({vol.Required('type'): 'mqtt/device/debug_info', vol.Required('device_id'): str})
@websocket_api.async_response
async def websocket_mqtt_info(hass, connection, msg):
device_id = msg['device_id']
mqtt_info = (await debug_info.info_for_device(hass, device_id))
connection.send_result(msg['id'], mqtt_info) | @websocket_api.websocket_command({vol.Required('type'): 'mqtt/device/debug_info', vol.Required('device_id'): str})
@websocket_api.async_response
async def websocket_mqtt_info(hass, connection, msg):
device_id = msg['device_id']
mqtt_info = (await debug_info.info_for_device(hass, device_id))
connection.send_result(msg['id'], mqtt_info)<|docstring|>Get MQTT debug info for device.<|endoftext|> |
856ea9e41d0414e5967fb8e058eade01ca1e53d38671513bbd2ff36691f44575 | @websocket_api.websocket_command({vol.Required('type'): 'mqtt/device/remove', vol.Required('device_id'): str})
@websocket_api.async_response
async def websocket_remove_device(hass, connection, msg):
'Delete device.'
device_id = msg['device_id']
dev_registry = (await hass.helpers.device_registry.async_get_registry())
device = dev_registry.async_get(device_id)
if (not device):
connection.send_error(msg['id'], websocket_api.const.ERR_NOT_FOUND, 'Device not found')
return
for config_entry in device.config_entries:
config_entry = hass.config_entries.async_get_entry(config_entry)
if (config_entry.domain == DOMAIN):
dev_registry.async_remove_device(device_id)
connection.send_message(websocket_api.result_message(msg['id']))
return
connection.send_error(msg['id'], websocket_api.const.ERR_NOT_FOUND, 'Non MQTT device') | Delete device. | homeassistant/components/mqtt/__init__.py | websocket_remove_device | 3guoyangyang7/core | 11 | python | @websocket_api.websocket_command({vol.Required('type'): 'mqtt/device/remove', vol.Required('device_id'): str})
@websocket_api.async_response
async def websocket_remove_device(hass, connection, msg):
device_id = msg['device_id']
dev_registry = (await hass.helpers.device_registry.async_get_registry())
device = dev_registry.async_get(device_id)
if (not device):
connection.send_error(msg['id'], websocket_api.const.ERR_NOT_FOUND, 'Device not found')
return
for config_entry in device.config_entries:
config_entry = hass.config_entries.async_get_entry(config_entry)
if (config_entry.domain == DOMAIN):
dev_registry.async_remove_device(device_id)
connection.send_message(websocket_api.result_message(msg['id']))
return
connection.send_error(msg['id'], websocket_api.const.ERR_NOT_FOUND, 'Non MQTT device') | @websocket_api.websocket_command({vol.Required('type'): 'mqtt/device/remove', vol.Required('device_id'): str})
@websocket_api.async_response
async def websocket_remove_device(hass, connection, msg):
device_id = msg['device_id']
dev_registry = (await hass.helpers.device_registry.async_get_registry())
device = dev_registry.async_get(device_id)
if (not device):
connection.send_error(msg['id'], websocket_api.const.ERR_NOT_FOUND, 'Device not found')
return
for config_entry in device.config_entries:
config_entry = hass.config_entries.async_get_entry(config_entry)
if (config_entry.domain == DOMAIN):
dev_registry.async_remove_device(device_id)
connection.send_message(websocket_api.result_message(msg['id']))
return
connection.send_error(msg['id'], websocket_api.const.ERR_NOT_FOUND, 'Non MQTT device')<|docstring|>Delete device.<|endoftext|> |
c3fad9d1c6bb9c483ee0e621a7680f6ded901719f4cdb4b4031733078b1d55a7 | @websocket_api.websocket_command({vol.Required('type'): 'mqtt/subscribe', vol.Required('topic'): valid_subscribe_topic})
@websocket_api.async_response
async def websocket_subscribe(hass, connection, msg):
'Subscribe to a MQTT topic.'
if (not connection.user.is_admin):
raise Unauthorized
async def forward_messages(mqttmsg: ReceiveMessage):
'Forward events to websocket.'
connection.send_message(websocket_api.event_message(msg['id'], {'topic': mqttmsg.topic, 'payload': mqttmsg.payload, 'qos': mqttmsg.qos, 'retain': mqttmsg.retain}))
connection.subscriptions[msg['id']] = (await async_subscribe(hass, msg['topic'], forward_messages))
connection.send_message(websocket_api.result_message(msg['id'])) | Subscribe to a MQTT topic. | homeassistant/components/mqtt/__init__.py | websocket_subscribe | 3guoyangyang7/core | 11 | python | @websocket_api.websocket_command({vol.Required('type'): 'mqtt/subscribe', vol.Required('topic'): valid_subscribe_topic})
@websocket_api.async_response
async def websocket_subscribe(hass, connection, msg):
if (not connection.user.is_admin):
raise Unauthorized
async def forward_messages(mqttmsg: ReceiveMessage):
'Forward events to websocket.'
connection.send_message(websocket_api.event_message(msg['id'], {'topic': mqttmsg.topic, 'payload': mqttmsg.payload, 'qos': mqttmsg.qos, 'retain': mqttmsg.retain}))
connection.subscriptions[msg['id']] = (await async_subscribe(hass, msg['topic'], forward_messages))
connection.send_message(websocket_api.result_message(msg['id'])) | @websocket_api.websocket_command({vol.Required('type'): 'mqtt/subscribe', vol.Required('topic'): valid_subscribe_topic})
@websocket_api.async_response
async def websocket_subscribe(hass, connection, msg):
if (not connection.user.is_admin):
raise Unauthorized
async def forward_messages(mqttmsg: ReceiveMessage):
'Forward events to websocket.'
connection.send_message(websocket_api.event_message(msg['id'], {'topic': mqttmsg.topic, 'payload': mqttmsg.payload, 'qos': mqttmsg.qos, 'retain': mqttmsg.retain}))
connection.subscriptions[msg['id']] = (await async_subscribe(hass, msg['topic'], forward_messages))
connection.send_message(websocket_api.result_message(msg['id']))<|docstring|>Subscribe to a MQTT topic.<|endoftext|> |
b231a173d25f1ac73af1b9d724cb39ba3700f1afbac80955206237f1d934beeb | @callback
def async_subscribe_connection_status(hass: HomeAssistant, connection_status_callback: ConnectionStatusCallback) -> Callable[([], None)]:
'Subscribe to MQTT connection changes.'
connection_status_callback_job = HassJob(connection_status_callback)
async def connected():
task = hass.async_run_hass_job(connection_status_callback_job, True)
if task:
(await task)
async def disconnected():
task = hass.async_run_hass_job(connection_status_callback_job, False)
if task:
(await task)
subscriptions = {'connect': async_dispatcher_connect(hass, MQTT_CONNECTED, connected), 'disconnect': async_dispatcher_connect(hass, MQTT_DISCONNECTED, disconnected)}
@callback
def unsubscribe():
subscriptions['connect']()
subscriptions['disconnect']()
return unsubscribe | Subscribe to MQTT connection changes. | homeassistant/components/mqtt/__init__.py | async_subscribe_connection_status | 3guoyangyang7/core | 11 | python | @callback
def async_subscribe_connection_status(hass: HomeAssistant, connection_status_callback: ConnectionStatusCallback) -> Callable[([], None)]:
connection_status_callback_job = HassJob(connection_status_callback)
async def connected():
task = hass.async_run_hass_job(connection_status_callback_job, True)
if task:
(await task)
async def disconnected():
task = hass.async_run_hass_job(connection_status_callback_job, False)
if task:
(await task)
subscriptions = {'connect': async_dispatcher_connect(hass, MQTT_CONNECTED, connected), 'disconnect': async_dispatcher_connect(hass, MQTT_DISCONNECTED, disconnected)}
@callback
def unsubscribe():
subscriptions['connect']()
subscriptions['disconnect']()
return unsubscribe | @callback
def async_subscribe_connection_status(hass: HomeAssistant, connection_status_callback: ConnectionStatusCallback) -> Callable[([], None)]:
connection_status_callback_job = HassJob(connection_status_callback)
async def connected():
task = hass.async_run_hass_job(connection_status_callback_job, True)
if task:
(await task)
async def disconnected():
task = hass.async_run_hass_job(connection_status_callback_job, False)
if task:
(await task)
subscriptions = {'connect': async_dispatcher_connect(hass, MQTT_CONNECTED, connected), 'disconnect': async_dispatcher_connect(hass, MQTT_DISCONNECTED, disconnected)}
@callback
def unsubscribe():
subscriptions['connect']()
subscriptions['disconnect']()
return unsubscribe<|docstring|>Subscribe to MQTT connection changes.<|endoftext|> |
b593f277e0069376a69bf64b9a9bcfc5a5e97b8d10af3c2c1d8db29a5d8ee90e | def is_connected(hass: HomeAssistant) -> bool:
'Return if MQTT client is connected.'
return hass.data[DATA_MQTT].connected | Return if MQTT client is connected. | homeassistant/components/mqtt/__init__.py | is_connected | 3guoyangyang7/core | 11 | python | def is_connected(hass: HomeAssistant) -> bool:
return hass.data[DATA_MQTT].connected | def is_connected(hass: HomeAssistant) -> bool:
return hass.data[DATA_MQTT].connected<|docstring|>Return if MQTT client is connected.<|endoftext|> |
4638cf67696929335da895ff6b905fff7bc8e411bf358a58338cb170ea8c7f55 | def remove():
'Remove listener convert.'
run_callback_threadsafe(hass.loop, async_remove).result() | Remove listener convert. | homeassistant/components/mqtt/__init__.py | remove | 3guoyangyang7/core | 11 | python | def remove():
run_callback_threadsafe(hass.loop, async_remove).result() | def remove():
run_callback_threadsafe(hass.loop, async_remove).result()<|docstring|>Remove listener convert.<|endoftext|> |
0fbcb42ab4d69c42e9f02eb4699901e7d2f52f54b3d9c5382efe889343296c26 | async def async_stop_mqtt(_event: Event):
'Stop MQTT component.'
(await hass.data[DATA_MQTT].async_disconnect()) | Stop MQTT component. | homeassistant/components/mqtt/__init__.py | async_stop_mqtt | 3guoyangyang7/core | 11 | python | async def async_stop_mqtt(_event: Event):
(await hass.data[DATA_MQTT].async_disconnect()) | async def async_stop_mqtt(_event: Event):
(await hass.data[DATA_MQTT].async_disconnect())<|docstring|>Stop MQTT component.<|endoftext|> |
9ee436b3be302d2ef9fcd4ee97ef15547ead40cdae114f6c88df0ceda900f669 | async def async_publish_service(call: ServiceCall):
'Handle MQTT publish service calls.'
msg_topic: str = call.data[ATTR_TOPIC]
payload = call.data.get(ATTR_PAYLOAD)
payload_template = call.data.get(ATTR_PAYLOAD_TEMPLATE)
qos: int = call.data[ATTR_QOS]
retain: bool = call.data[ATTR_RETAIN]
if (payload_template is not None):
try:
payload = template.Template(payload_template, hass).async_render(parse_result=False)
except template.jinja2.TemplateError as exc:
_LOGGER.error('Unable to publish to %s: rendering payload template of %s failed because %s', msg_topic, payload_template, exc)
return
(await hass.data[DATA_MQTT].async_publish(msg_topic, payload, qos, retain)) | Handle MQTT publish service calls. | homeassistant/components/mqtt/__init__.py | async_publish_service | 3guoyangyang7/core | 11 | python | async def async_publish_service(call: ServiceCall):
msg_topic: str = call.data[ATTR_TOPIC]
payload = call.data.get(ATTR_PAYLOAD)
payload_template = call.data.get(ATTR_PAYLOAD_TEMPLATE)
qos: int = call.data[ATTR_QOS]
retain: bool = call.data[ATTR_RETAIN]
if (payload_template is not None):
try:
payload = template.Template(payload_template, hass).async_render(parse_result=False)
except template.jinja2.TemplateError as exc:
_LOGGER.error('Unable to publish to %s: rendering payload template of %s failed because %s', msg_topic, payload_template, exc)
return
(await hass.data[DATA_MQTT].async_publish(msg_topic, payload, qos, retain)) | async def async_publish_service(call: ServiceCall):
msg_topic: str = call.data[ATTR_TOPIC]
payload = call.data.get(ATTR_PAYLOAD)
payload_template = call.data.get(ATTR_PAYLOAD_TEMPLATE)
qos: int = call.data[ATTR_QOS]
retain: bool = call.data[ATTR_RETAIN]
if (payload_template is not None):
try:
payload = template.Template(payload_template, hass).async_render(parse_result=False)
except template.jinja2.TemplateError as exc:
_LOGGER.error('Unable to publish to %s: rendering payload template of %s failed because %s', msg_topic, payload_template, exc)
return
(await hass.data[DATA_MQTT].async_publish(msg_topic, payload, qos, retain))<|docstring|>Handle MQTT publish service calls.<|endoftext|> |
1d1303ed95d2375831d4baf9924ac30ed1de1d00040ed75faef61b7c820326fa | async def async_dump_service(call: ServiceCall):
'Handle MQTT dump service calls.'
messages = []
@callback
def collect_msg(msg):
messages.append((msg.topic, msg.payload.replace('\n', '')))
unsub = (await async_subscribe(hass, call.data['topic'], collect_msg))
def write_dump():
with open(hass.config.path('mqtt_dump.txt'), 'wt') as fp:
for msg in messages:
fp.write((','.join(msg) + '\n'))
async def finish_dump(_):
'Write dump to file.'
unsub()
(await hass.async_add_executor_job(write_dump))
event.async_call_later(hass, call.data['duration'], finish_dump) | Handle MQTT dump service calls. | homeassistant/components/mqtt/__init__.py | async_dump_service | 3guoyangyang7/core | 11 | python | async def async_dump_service(call: ServiceCall):
messages = []
@callback
def collect_msg(msg):
messages.append((msg.topic, msg.payload.replace('\n', )))
unsub = (await async_subscribe(hass, call.data['topic'], collect_msg))
def write_dump():
with open(hass.config.path('mqtt_dump.txt'), 'wt') as fp:
for msg in messages:
fp.write((','.join(msg) + '\n'))
async def finish_dump(_):
'Write dump to file.'
unsub()
(await hass.async_add_executor_job(write_dump))
event.async_call_later(hass, call.data['duration'], finish_dump) | async def async_dump_service(call: ServiceCall):
messages = []
@callback
def collect_msg(msg):
messages.append((msg.topic, msg.payload.replace('\n', )))
unsub = (await async_subscribe(hass, call.data['topic'], collect_msg))
def write_dump():
with open(hass.config.path('mqtt_dump.txt'), 'wt') as fp:
for msg in messages:
fp.write((','.join(msg) + '\n'))
async def finish_dump(_):
'Write dump to file.'
unsub()
(await hass.async_add_executor_job(write_dump))
event.async_call_later(hass, call.data['duration'], finish_dump)<|docstring|>Handle MQTT dump service calls.<|endoftext|> |
dc9cda87fcd3130403cc049c77a68cc1dfed420b0ec6cd270b908448b67e9c4e | def __init__(self, hass: HomeAssistant, config_entry, conf) -> None:
'Initialize Home Assistant MQTT client.'
import paho.mqtt.client as mqtt
self.hass = hass
self.config_entry = config_entry
self.conf = conf
self.subscriptions: list[Subscription] = []
self.connected = False
self._ha_started = asyncio.Event()
self._last_subscribe = time.time()
self._mqttc: mqtt.Client = None
self._paho_lock = asyncio.Lock()
self._pending_operations: dict[(str, asyncio.Event)] = {}
if (self.hass.state == CoreState.running):
self._ha_started.set()
else:
@callback
def ha_started(_):
self._ha_started.set()
self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STARTED, ha_started)
self.init_client()
self.config_entry.add_update_listener(self.async_config_entry_updated) | Initialize Home Assistant MQTT client. | homeassistant/components/mqtt/__init__.py | __init__ | 3guoyangyang7/core | 11 | python | def __init__(self, hass: HomeAssistant, config_entry, conf) -> None:
import paho.mqtt.client as mqtt
self.hass = hass
self.config_entry = config_entry
self.conf = conf
self.subscriptions: list[Subscription] = []
self.connected = False
self._ha_started = asyncio.Event()
self._last_subscribe = time.time()
self._mqttc: mqtt.Client = None
self._paho_lock = asyncio.Lock()
self._pending_operations: dict[(str, asyncio.Event)] = {}
if (self.hass.state == CoreState.running):
self._ha_started.set()
else:
@callback
def ha_started(_):
self._ha_started.set()
self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STARTED, ha_started)
self.init_client()
self.config_entry.add_update_listener(self.async_config_entry_updated) | def __init__(self, hass: HomeAssistant, config_entry, conf) -> None:
import paho.mqtt.client as mqtt
self.hass = hass
self.config_entry = config_entry
self.conf = conf
self.subscriptions: list[Subscription] = []
self.connected = False
self._ha_started = asyncio.Event()
self._last_subscribe = time.time()
self._mqttc: mqtt.Client = None
self._paho_lock = asyncio.Lock()
self._pending_operations: dict[(str, asyncio.Event)] = {}
if (self.hass.state == CoreState.running):
self._ha_started.set()
else:
@callback
def ha_started(_):
self._ha_started.set()
self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STARTED, ha_started)
self.init_client()
self.config_entry.add_update_listener(self.async_config_entry_updated)<|docstring|>Initialize Home Assistant MQTT client.<|endoftext|> |
fa6c5bfb151d87528b11d534f25dd961f343adcbddbb08ef7f10d0bdfd4fdb5d | @staticmethod
async def async_config_entry_updated(hass, entry) -> None:
'Handle signals of config entry being updated.\n\n This is a static method because a class method (bound method), can not be used with weak references.\n Causes for this is config entry options changing.\n '
self = hass.data[DATA_MQTT]
conf = hass.data.get(DATA_MQTT_CONFIG)
if (conf is None):
conf = CONFIG_SCHEMA({DOMAIN: dict(entry.data)})[DOMAIN]
self.conf = _merge_config(entry, conf)
(await self.async_disconnect())
self.init_client()
(await self.async_connect())
(await discovery.async_stop(hass))
if self.conf.get(CONF_DISCOVERY):
(await _async_setup_discovery(hass, self.conf, entry)) | Handle signals of config entry being updated.
This is a static method because a class method (bound method), can not be used with weak references.
Causes for this is config entry options changing. | homeassistant/components/mqtt/__init__.py | async_config_entry_updated | 3guoyangyang7/core | 11 | python | @staticmethod
async def async_config_entry_updated(hass, entry) -> None:
'Handle signals of config entry being updated.\n\n This is a static method because a class method (bound method), can not be used with weak references.\n Causes for this is config entry options changing.\n '
self = hass.data[DATA_MQTT]
conf = hass.data.get(DATA_MQTT_CONFIG)
if (conf is None):
conf = CONFIG_SCHEMA({DOMAIN: dict(entry.data)})[DOMAIN]
self.conf = _merge_config(entry, conf)
(await self.async_disconnect())
self.init_client()
(await self.async_connect())
(await discovery.async_stop(hass))
if self.conf.get(CONF_DISCOVERY):
(await _async_setup_discovery(hass, self.conf, entry)) | @staticmethod
async def async_config_entry_updated(hass, entry) -> None:
'Handle signals of config entry being updated.\n\n This is a static method because a class method (bound method), can not be used with weak references.\n Causes for this is config entry options changing.\n '
self = hass.data[DATA_MQTT]
conf = hass.data.get(DATA_MQTT_CONFIG)
if (conf is None):
conf = CONFIG_SCHEMA({DOMAIN: dict(entry.data)})[DOMAIN]
self.conf = _merge_config(entry, conf)
(await self.async_disconnect())
self.init_client()
(await self.async_connect())
(await discovery.async_stop(hass))
if self.conf.get(CONF_DISCOVERY):
(await _async_setup_discovery(hass, self.conf, entry))<|docstring|>Handle signals of config entry being updated.
This is a static method because a class method (bound method), can not be used with weak references.
Causes for this is config entry options changing.<|endoftext|> |
eb6260aa1d43d4cff08a60328b219cfa09ca0919fcb50b03861c453685dcb3d8 | def init_client(self):
'Initialize paho client.'
import paho.mqtt.client as mqtt
if (self.conf[CONF_PROTOCOL] == PROTOCOL_31):
proto: int = mqtt.MQTTv31
else:
proto = mqtt.MQTTv311
client_id = self.conf.get(CONF_CLIENT_ID)
if (client_id is None):
client_id = mqtt.base62(uuid.uuid4().int, padding=22)
self._mqttc = mqtt.Client(client_id, protocol=proto)
self._mqttc.enable_logger()
username = self.conf.get(CONF_USERNAME)
password = self.conf.get(CONF_PASSWORD)
if (username is not None):
self._mqttc.username_pw_set(username, password)
certificate = self.conf.get(CONF_CERTIFICATE)
if (certificate == 'auto'):
certificate = certifi.where()
client_key = self.conf.get(CONF_CLIENT_KEY)
client_cert = self.conf.get(CONF_CLIENT_CERT)
tls_insecure = self.conf.get(CONF_TLS_INSECURE)
if (certificate is not None):
self._mqttc.tls_set(certificate, certfile=client_cert, keyfile=client_key, tls_version=ssl.PROTOCOL_TLS)
if (tls_insecure is not None):
self._mqttc.tls_insecure_set(tls_insecure)
self._mqttc.on_connect = self._mqtt_on_connect
self._mqttc.on_disconnect = self._mqtt_on_disconnect
self._mqttc.on_message = self._mqtt_on_message
self._mqttc.on_publish = self._mqtt_on_callback
self._mqttc.on_subscribe = self._mqtt_on_callback
self._mqttc.on_unsubscribe = self._mqtt_on_callback
if ((CONF_WILL_MESSAGE in self.conf) and (ATTR_TOPIC in self.conf[CONF_WILL_MESSAGE])):
will_message = PublishMessage(**self.conf[CONF_WILL_MESSAGE])
else:
will_message = None
if (will_message is not None):
self._mqttc.will_set(topic=will_message.topic, payload=will_message.payload, qos=will_message.qos, retain=will_message.retain) | Initialize paho client. | homeassistant/components/mqtt/__init__.py | init_client | 3guoyangyang7/core | 11 | python | def init_client(self):
import paho.mqtt.client as mqtt
if (self.conf[CONF_PROTOCOL] == PROTOCOL_31):
proto: int = mqtt.MQTTv31
else:
proto = mqtt.MQTTv311
client_id = self.conf.get(CONF_CLIENT_ID)
if (client_id is None):
client_id = mqtt.base62(uuid.uuid4().int, padding=22)
self._mqttc = mqtt.Client(client_id, protocol=proto)
self._mqttc.enable_logger()
username = self.conf.get(CONF_USERNAME)
password = self.conf.get(CONF_PASSWORD)
if (username is not None):
self._mqttc.username_pw_set(username, password)
certificate = self.conf.get(CONF_CERTIFICATE)
if (certificate == 'auto'):
certificate = certifi.where()
client_key = self.conf.get(CONF_CLIENT_KEY)
client_cert = self.conf.get(CONF_CLIENT_CERT)
tls_insecure = self.conf.get(CONF_TLS_INSECURE)
if (certificate is not None):
self._mqttc.tls_set(certificate, certfile=client_cert, keyfile=client_key, tls_version=ssl.PROTOCOL_TLS)
if (tls_insecure is not None):
self._mqttc.tls_insecure_set(tls_insecure)
self._mqttc.on_connect = self._mqtt_on_connect
self._mqttc.on_disconnect = self._mqtt_on_disconnect
self._mqttc.on_message = self._mqtt_on_message
self._mqttc.on_publish = self._mqtt_on_callback
self._mqttc.on_subscribe = self._mqtt_on_callback
self._mqttc.on_unsubscribe = self._mqtt_on_callback
if ((CONF_WILL_MESSAGE in self.conf) and (ATTR_TOPIC in self.conf[CONF_WILL_MESSAGE])):
will_message = PublishMessage(**self.conf[CONF_WILL_MESSAGE])
else:
will_message = None
if (will_message is not None):
self._mqttc.will_set(topic=will_message.topic, payload=will_message.payload, qos=will_message.qos, retain=will_message.retain) | def init_client(self):
import paho.mqtt.client as mqtt
if (self.conf[CONF_PROTOCOL] == PROTOCOL_31):
proto: int = mqtt.MQTTv31
else:
proto = mqtt.MQTTv311
client_id = self.conf.get(CONF_CLIENT_ID)
if (client_id is None):
client_id = mqtt.base62(uuid.uuid4().int, padding=22)
self._mqttc = mqtt.Client(client_id, protocol=proto)
self._mqttc.enable_logger()
username = self.conf.get(CONF_USERNAME)
password = self.conf.get(CONF_PASSWORD)
if (username is not None):
self._mqttc.username_pw_set(username, password)
certificate = self.conf.get(CONF_CERTIFICATE)
if (certificate == 'auto'):
certificate = certifi.where()
client_key = self.conf.get(CONF_CLIENT_KEY)
client_cert = self.conf.get(CONF_CLIENT_CERT)
tls_insecure = self.conf.get(CONF_TLS_INSECURE)
if (certificate is not None):
self._mqttc.tls_set(certificate, certfile=client_cert, keyfile=client_key, tls_version=ssl.PROTOCOL_TLS)
if (tls_insecure is not None):
self._mqttc.tls_insecure_set(tls_insecure)
self._mqttc.on_connect = self._mqtt_on_connect
self._mqttc.on_disconnect = self._mqtt_on_disconnect
self._mqttc.on_message = self._mqtt_on_message
self._mqttc.on_publish = self._mqtt_on_callback
self._mqttc.on_subscribe = self._mqtt_on_callback
self._mqttc.on_unsubscribe = self._mqtt_on_callback
if ((CONF_WILL_MESSAGE in self.conf) and (ATTR_TOPIC in self.conf[CONF_WILL_MESSAGE])):
will_message = PublishMessage(**self.conf[CONF_WILL_MESSAGE])
else:
will_message = None
if (will_message is not None):
self._mqttc.will_set(topic=will_message.topic, payload=will_message.payload, qos=will_message.qos, retain=will_message.retain)<|docstring|>Initialize paho client.<|endoftext|> |
e9b0e3e3d76160b72a2dd3ba5859cb3f14449c469ce1afa9457fedf40f71bcac | async def async_publish(self, topic: str, payload: PublishPayloadType, qos: int, retain: bool) -> None:
'Publish a MQTT message.'
async with self._paho_lock:
msg_info = (await self.hass.async_add_executor_job(self._mqttc.publish, topic, payload, qos, retain))
_LOGGER.debug("Transmitting message on %s: '%s', mid: %s", topic, payload, msg_info.mid)
_raise_on_error(msg_info.rc)
(await self._wait_for_mid(msg_info.mid)) | Publish a MQTT message. | homeassistant/components/mqtt/__init__.py | async_publish | 3guoyangyang7/core | 11 | python | async def async_publish(self, topic: str, payload: PublishPayloadType, qos: int, retain: bool) -> None:
async with self._paho_lock:
msg_info = (await self.hass.async_add_executor_job(self._mqttc.publish, topic, payload, qos, retain))
_LOGGER.debug("Transmitting message on %s: '%s', mid: %s", topic, payload, msg_info.mid)
_raise_on_error(msg_info.rc)
(await self._wait_for_mid(msg_info.mid)) | async def async_publish(self, topic: str, payload: PublishPayloadType, qos: int, retain: bool) -> None:
async with self._paho_lock:
msg_info = (await self.hass.async_add_executor_job(self._mqttc.publish, topic, payload, qos, retain))
_LOGGER.debug("Transmitting message on %s: '%s', mid: %s", topic, payload, msg_info.mid)
_raise_on_error(msg_info.rc)
(await self._wait_for_mid(msg_info.mid))<|docstring|>Publish a MQTT message.<|endoftext|> |
436b6808f2c98fca4fe9c66a3e00e26a405bbc66de7b0466ba9816ec1ce87332 | async def async_connect(self) -> None:
'Connect to the host. Does not process messages yet.'
import paho.mqtt.client as mqtt
result: (int | None) = None
try:
result = (await self.hass.async_add_executor_job(self._mqttc.connect, self.conf[CONF_BROKER], self.conf[CONF_PORT], self.conf[CONF_KEEPALIVE]))
except OSError as err:
_LOGGER.error('Failed to connect to MQTT server due to exception: %s', err)
if ((result is not None) and (result != 0)):
_LOGGER.error('Failed to connect to MQTT server: %s', mqtt.error_string(result))
self._mqttc.loop_start() | Connect to the host. Does not process messages yet. | homeassistant/components/mqtt/__init__.py | async_connect | 3guoyangyang7/core | 11 | python | async def async_connect(self) -> None:
import paho.mqtt.client as mqtt
result: (int | None) = None
try:
result = (await self.hass.async_add_executor_job(self._mqttc.connect, self.conf[CONF_BROKER], self.conf[CONF_PORT], self.conf[CONF_KEEPALIVE]))
except OSError as err:
_LOGGER.error('Failed to connect to MQTT server due to exception: %s', err)
if ((result is not None) and (result != 0)):
_LOGGER.error('Failed to connect to MQTT server: %s', mqtt.error_string(result))
self._mqttc.loop_start() | async def async_connect(self) -> None:
import paho.mqtt.client as mqtt
result: (int | None) = None
try:
result = (await self.hass.async_add_executor_job(self._mqttc.connect, self.conf[CONF_BROKER], self.conf[CONF_PORT], self.conf[CONF_KEEPALIVE]))
except OSError as err:
_LOGGER.error('Failed to connect to MQTT server due to exception: %s', err)
if ((result is not None) and (result != 0)):
_LOGGER.error('Failed to connect to MQTT server: %s', mqtt.error_string(result))
self._mqttc.loop_start()<|docstring|>Connect to the host. Does not process messages yet.<|endoftext|> |
8bfc47e36dc38574318b10dd8d071da698fbb590406e4ed9fc71f5c96554a4ca | async def async_disconnect(self):
'Stop the MQTT client.'
def stop():
'Stop the MQTT client.'
self._mqttc.loop_stop()
(await self.hass.async_add_executor_job(stop)) | Stop the MQTT client. | homeassistant/components/mqtt/__init__.py | async_disconnect | 3guoyangyang7/core | 11 | python | async def async_disconnect(self):
def stop():
self._mqttc.loop_stop()
(await self.hass.async_add_executor_job(stop)) | async def async_disconnect(self):
def stop():
self._mqttc.loop_stop()
(await self.hass.async_add_executor_job(stop))<|docstring|>Stop the MQTT client.<|endoftext|> |
29ed3ad73263032069aa7aa1dfeb4e798cba5444eac72bcda104d3f31a46f484 | async def async_subscribe(self, topic: str, msg_callback: MessageCallbackType, qos: int, encoding: (str | None)=None) -> Callable[([], None)]:
'Set up a subscription to a topic with the provided qos.\n\n This method is a coroutine.\n '
if (not isinstance(topic, str)):
raise HomeAssistantError('Topic needs to be a string!')
subscription = Subscription(topic, _matcher_for_topic(topic), HassJob(msg_callback), qos, encoding)
self.subscriptions.append(subscription)
self._matching_subscriptions.cache_clear()
if self.connected:
self._last_subscribe = time.time()
(await self._async_perform_subscription(topic, qos))
@callback
def async_remove() -> None:
'Remove subscription.'
if (subscription not in self.subscriptions):
raise HomeAssistantError("Can't remove subscription twice")
self.subscriptions.remove(subscription)
self._matching_subscriptions.cache_clear()
if any(((other.topic == topic) for other in self.subscriptions)):
return
if self.connected:
self.hass.async_create_task(self._async_unsubscribe(topic))
return async_remove | Set up a subscription to a topic with the provided qos.
This method is a coroutine. | homeassistant/components/mqtt/__init__.py | async_subscribe | 3guoyangyang7/core | 11 | python | async def async_subscribe(self, topic: str, msg_callback: MessageCallbackType, qos: int, encoding: (str | None)=None) -> Callable[([], None)]:
'Set up a subscription to a topic with the provided qos.\n\n This method is a coroutine.\n '
if (not isinstance(topic, str)):
raise HomeAssistantError('Topic needs to be a string!')
subscription = Subscription(topic, _matcher_for_topic(topic), HassJob(msg_callback), qos, encoding)
self.subscriptions.append(subscription)
self._matching_subscriptions.cache_clear()
if self.connected:
self._last_subscribe = time.time()
(await self._async_perform_subscription(topic, qos))
@callback
def async_remove() -> None:
'Remove subscription.'
if (subscription not in self.subscriptions):
raise HomeAssistantError("Can't remove subscription twice")
self.subscriptions.remove(subscription)
self._matching_subscriptions.cache_clear()
if any(((other.topic == topic) for other in self.subscriptions)):
return
if self.connected:
self.hass.async_create_task(self._async_unsubscribe(topic))
return async_remove | async def async_subscribe(self, topic: str, msg_callback: MessageCallbackType, qos: int, encoding: (str | None)=None) -> Callable[([], None)]:
'Set up a subscription to a topic with the provided qos.\n\n This method is a coroutine.\n '
if (not isinstance(topic, str)):
raise HomeAssistantError('Topic needs to be a string!')
subscription = Subscription(topic, _matcher_for_topic(topic), HassJob(msg_callback), qos, encoding)
self.subscriptions.append(subscription)
self._matching_subscriptions.cache_clear()
if self.connected:
self._last_subscribe = time.time()
(await self._async_perform_subscription(topic, qos))
@callback
def async_remove() -> None:
'Remove subscription.'
if (subscription not in self.subscriptions):
raise HomeAssistantError("Can't remove subscription twice")
self.subscriptions.remove(subscription)
self._matching_subscriptions.cache_clear()
if any(((other.topic == topic) for other in self.subscriptions)):
return
if self.connected:
self.hass.async_create_task(self._async_unsubscribe(topic))
return async_remove<|docstring|>Set up a subscription to a topic with the provided qos.
This method is a coroutine.<|endoftext|> |
16d522722f073d591dcd795af423177155770605851dec6d6c9cc4eecf2e0263 | async def _async_unsubscribe(self, topic: str) -> None:
'Unsubscribe from a topic.\n\n This method is a coroutine.\n '
async with self._paho_lock:
result: (int | None) = None
(result, mid) = (await self.hass.async_add_executor_job(self._mqttc.unsubscribe, topic))
_LOGGER.debug('Unsubscribing from %s, mid: %s', topic, mid)
_raise_on_error(result)
(await self._wait_for_mid(mid)) | Unsubscribe from a topic.
This method is a coroutine. | homeassistant/components/mqtt/__init__.py | _async_unsubscribe | 3guoyangyang7/core | 11 | python | async def _async_unsubscribe(self, topic: str) -> None:
'Unsubscribe from a topic.\n\n This method is a coroutine.\n '
async with self._paho_lock:
result: (int | None) = None
(result, mid) = (await self.hass.async_add_executor_job(self._mqttc.unsubscribe, topic))
_LOGGER.debug('Unsubscribing from %s, mid: %s', topic, mid)
_raise_on_error(result)
(await self._wait_for_mid(mid)) | async def _async_unsubscribe(self, topic: str) -> None:
'Unsubscribe from a topic.\n\n This method is a coroutine.\n '
async with self._paho_lock:
result: (int | None) = None
(result, mid) = (await self.hass.async_add_executor_job(self._mqttc.unsubscribe, topic))
_LOGGER.debug('Unsubscribing from %s, mid: %s', topic, mid)
_raise_on_error(result)
(await self._wait_for_mid(mid))<|docstring|>Unsubscribe from a topic.
This method is a coroutine.<|endoftext|> |
c78f2fbfc63576c0d86861309b36e1c18488eaadd09eddad80baa8f879d4c291 | async def _async_perform_subscription(self, topic: str, qos: int) -> None:
'Perform a paho-mqtt subscription.'
async with self._paho_lock:
result: (int | None) = None
(result, mid) = (await self.hass.async_add_executor_job(self._mqttc.subscribe, topic, qos))
_LOGGER.debug('Subscribing to %s, mid: %s', topic, mid)
_raise_on_error(result)
(await self._wait_for_mid(mid)) | Perform a paho-mqtt subscription. | homeassistant/components/mqtt/__init__.py | _async_perform_subscription | 3guoyangyang7/core | 11 | python | async def _async_perform_subscription(self, topic: str, qos: int) -> None:
async with self._paho_lock:
result: (int | None) = None
(result, mid) = (await self.hass.async_add_executor_job(self._mqttc.subscribe, topic, qos))
_LOGGER.debug('Subscribing to %s, mid: %s', topic, mid)
_raise_on_error(result)
(await self._wait_for_mid(mid)) | async def _async_perform_subscription(self, topic: str, qos: int) -> None:
async with self._paho_lock:
result: (int | None) = None
(result, mid) = (await self.hass.async_add_executor_job(self._mqttc.subscribe, topic, qos))
_LOGGER.debug('Subscribing to %s, mid: %s', topic, mid)
_raise_on_error(result)
(await self._wait_for_mid(mid))<|docstring|>Perform a paho-mqtt subscription.<|endoftext|> |
689a6bc040b5ef2af1b119202d5c89d7932759ab5fbe40c738419b08a8c5d0f5 | def _mqtt_on_connect(self, _mqttc, _userdata, _flags, result_code: int) -> None:
'On connect callback.\n\n Resubscribe to all topics we were subscribed to and publish birth\n message.\n '
import paho.mqtt.client as mqtt
if (result_code != mqtt.CONNACK_ACCEPTED):
_LOGGER.error('Unable to connect to the MQTT broker: %s', mqtt.connack_string(result_code))
return
self.connected = True
dispatcher_send(self.hass, MQTT_CONNECTED)
_LOGGER.info('Connected to MQTT server %s:%s (%s)', self.conf[CONF_BROKER], self.conf[CONF_PORT], result_code)
keyfunc = attrgetter('topic')
for (topic, subs) in groupby(sorted(self.subscriptions, key=keyfunc), keyfunc):
max_qos = max((subscription.qos for subscription in subs))
self.hass.add_job(self._async_perform_subscription, topic, max_qos)
if ((CONF_BIRTH_MESSAGE in self.conf) and (ATTR_TOPIC in self.conf[CONF_BIRTH_MESSAGE])):
async def publish_birth_message(birth_message):
(await self._ha_started.wait())
(await self._discovery_cooldown())
(await self.async_publish(topic=birth_message.topic, payload=birth_message.payload, qos=birth_message.qos, retain=birth_message.retain))
birth_message = PublishMessage(**self.conf[CONF_BIRTH_MESSAGE])
asyncio.run_coroutine_threadsafe(publish_birth_message(birth_message), self.hass.loop) | On connect callback.
Resubscribe to all topics we were subscribed to and publish birth
message. | homeassistant/components/mqtt/__init__.py | _mqtt_on_connect | 3guoyangyang7/core | 11 | python | def _mqtt_on_connect(self, _mqttc, _userdata, _flags, result_code: int) -> None:
'On connect callback.\n\n Resubscribe to all topics we were subscribed to and publish birth\n message.\n '
import paho.mqtt.client as mqtt
if (result_code != mqtt.CONNACK_ACCEPTED):
_LOGGER.error('Unable to connect to the MQTT broker: %s', mqtt.connack_string(result_code))
return
self.connected = True
dispatcher_send(self.hass, MQTT_CONNECTED)
_LOGGER.info('Connected to MQTT server %s:%s (%s)', self.conf[CONF_BROKER], self.conf[CONF_PORT], result_code)
keyfunc = attrgetter('topic')
for (topic, subs) in groupby(sorted(self.subscriptions, key=keyfunc), keyfunc):
max_qos = max((subscription.qos for subscription in subs))
self.hass.add_job(self._async_perform_subscription, topic, max_qos)
if ((CONF_BIRTH_MESSAGE in self.conf) and (ATTR_TOPIC in self.conf[CONF_BIRTH_MESSAGE])):
async def publish_birth_message(birth_message):
(await self._ha_started.wait())
(await self._discovery_cooldown())
(await self.async_publish(topic=birth_message.topic, payload=birth_message.payload, qos=birth_message.qos, retain=birth_message.retain))
birth_message = PublishMessage(**self.conf[CONF_BIRTH_MESSAGE])
asyncio.run_coroutine_threadsafe(publish_birth_message(birth_message), self.hass.loop) | def _mqtt_on_connect(self, _mqttc, _userdata, _flags, result_code: int) -> None:
'On connect callback.\n\n Resubscribe to all topics we were subscribed to and publish birth\n message.\n '
import paho.mqtt.client as mqtt
if (result_code != mqtt.CONNACK_ACCEPTED):
_LOGGER.error('Unable to connect to the MQTT broker: %s', mqtt.connack_string(result_code))
return
self.connected = True
dispatcher_send(self.hass, MQTT_CONNECTED)
_LOGGER.info('Connected to MQTT server %s:%s (%s)', self.conf[CONF_BROKER], self.conf[CONF_PORT], result_code)
keyfunc = attrgetter('topic')
for (topic, subs) in groupby(sorted(self.subscriptions, key=keyfunc), keyfunc):
max_qos = max((subscription.qos for subscription in subs))
self.hass.add_job(self._async_perform_subscription, topic, max_qos)
if ((CONF_BIRTH_MESSAGE in self.conf) and (ATTR_TOPIC in self.conf[CONF_BIRTH_MESSAGE])):
async def publish_birth_message(birth_message):
(await self._ha_started.wait())
(await self._discovery_cooldown())
(await self.async_publish(topic=birth_message.topic, payload=birth_message.payload, qos=birth_message.qos, retain=birth_message.retain))
birth_message = PublishMessage(**self.conf[CONF_BIRTH_MESSAGE])
asyncio.run_coroutine_threadsafe(publish_birth_message(birth_message), self.hass.loop)<|docstring|>On connect callback.
Resubscribe to all topics we were subscribed to and publish birth
message.<|endoftext|> |
1b6c74d733b986f45cccdb5eeae8a7eaf8d11350e852c8ffad03865fe68e5c97 | def _mqtt_on_message(self, _mqttc, _userdata, msg) -> None:
'Message received callback.'
self.hass.add_job(self._mqtt_handle_message, msg) | Message received callback. | homeassistant/components/mqtt/__init__.py | _mqtt_on_message | 3guoyangyang7/core | 11 | python | def _mqtt_on_message(self, _mqttc, _userdata, msg) -> None:
self.hass.add_job(self._mqtt_handle_message, msg) | def _mqtt_on_message(self, _mqttc, _userdata, msg) -> None:
self.hass.add_job(self._mqtt_handle_message, msg)<|docstring|>Message received callback.<|endoftext|> |
c1abba38610330e3368b6fd89a6d3d291b792987b41fde75e0e2ed9875afa972 | def _mqtt_on_callback(self, _mqttc, _userdata, mid, _granted_qos=None) -> None:
'Publish / Subscribe / Unsubscribe callback.'
self.hass.add_job(self._mqtt_handle_mid, mid) | Publish / Subscribe / Unsubscribe callback. | homeassistant/components/mqtt/__init__.py | _mqtt_on_callback | 3guoyangyang7/core | 11 | python | def _mqtt_on_callback(self, _mqttc, _userdata, mid, _granted_qos=None) -> None:
self.hass.add_job(self._mqtt_handle_mid, mid) | def _mqtt_on_callback(self, _mqttc, _userdata, mid, _granted_qos=None) -> None:
self.hass.add_job(self._mqtt_handle_mid, mid)<|docstring|>Publish / Subscribe / Unsubscribe callback.<|endoftext|> |
d0eb4721f35eeb84f97bed8a4653d7296d82847339bc1c2f285db5db63d5b0bf | def _mqtt_on_disconnect(self, _mqttc, _userdata, result_code: int) -> None:
'Disconnected callback.'
self.connected = False
dispatcher_send(self.hass, MQTT_DISCONNECTED)
_LOGGER.warning('Disconnected from MQTT server %s:%s (%s)', self.conf[CONF_BROKER], self.conf[CONF_PORT], result_code) | Disconnected callback. | homeassistant/components/mqtt/__init__.py | _mqtt_on_disconnect | 3guoyangyang7/core | 11 | python | def _mqtt_on_disconnect(self, _mqttc, _userdata, result_code: int) -> None:
self.connected = False
dispatcher_send(self.hass, MQTT_DISCONNECTED)
_LOGGER.warning('Disconnected from MQTT server %s:%s (%s)', self.conf[CONF_BROKER], self.conf[CONF_PORT], result_code) | def _mqtt_on_disconnect(self, _mqttc, _userdata, result_code: int) -> None:
self.connected = False
dispatcher_send(self.hass, MQTT_DISCONNECTED)
_LOGGER.warning('Disconnected from MQTT server %s:%s (%s)', self.conf[CONF_BROKER], self.conf[CONF_PORT], result_code)<|docstring|>Disconnected callback.<|endoftext|> |
4c05022562b2f4f63ca197afd4b1291518906f16133f7063fba80ac5662c2247 | async def _wait_for_mid(self, mid):
'Wait for ACK from broker.'
if (mid not in self._pending_operations):
self._pending_operations[mid] = asyncio.Event()
try:
(await asyncio.wait_for(self._pending_operations[mid].wait(), TIMEOUT_ACK))
except asyncio.TimeoutError:
_LOGGER.warning('No ACK from MQTT server in %s seconds (mid: %s)', TIMEOUT_ACK, mid)
finally:
del self._pending_operations[mid] | Wait for ACK from broker. | homeassistant/components/mqtt/__init__.py | _wait_for_mid | 3guoyangyang7/core | 11 | python | async def _wait_for_mid(self, mid):
if (mid not in self._pending_operations):
self._pending_operations[mid] = asyncio.Event()
try:
(await asyncio.wait_for(self._pending_operations[mid].wait(), TIMEOUT_ACK))
except asyncio.TimeoutError:
_LOGGER.warning('No ACK from MQTT server in %s seconds (mid: %s)', TIMEOUT_ACK, mid)
finally:
del self._pending_operations[mid] | async def _wait_for_mid(self, mid):
if (mid not in self._pending_operations):
self._pending_operations[mid] = asyncio.Event()
try:
(await asyncio.wait_for(self._pending_operations[mid].wait(), TIMEOUT_ACK))
except asyncio.TimeoutError:
_LOGGER.warning('No ACK from MQTT server in %s seconds (mid: %s)', TIMEOUT_ACK, mid)
finally:
del self._pending_operations[mid]<|docstring|>Wait for ACK from broker.<|endoftext|> |
455441c92e9477a2541a5dd60a82dd4db3be4417467de8727f7eb05c4e16ca0c | async def forward_messages(mqttmsg: ReceiveMessage):
'Forward events to websocket.'
connection.send_message(websocket_api.event_message(msg['id'], {'topic': mqttmsg.topic, 'payload': mqttmsg.payload, 'qos': mqttmsg.qos, 'retain': mqttmsg.retain})) | Forward events to websocket. | homeassistant/components/mqtt/__init__.py | forward_messages | 3guoyangyang7/core | 11 | python | async def forward_messages(mqttmsg: ReceiveMessage):
connection.send_message(websocket_api.event_message(msg['id'], {'topic': mqttmsg.topic, 'payload': mqttmsg.payload, 'qos': mqttmsg.qos, 'retain': mqttmsg.retain})) | async def forward_messages(mqttmsg: ReceiveMessage):
connection.send_message(websocket_api.event_message(msg['id'], {'topic': mqttmsg.topic, 'payload': mqttmsg.payload, 'qos': mqttmsg.qos, 'retain': mqttmsg.retain}))<|docstring|>Forward events to websocket.<|endoftext|> |
aa22ce2372a7059d8b9747ff95177a56e2553b0b7c68271785f7db0a26de3f66 | @wraps(msg_callback)
async def async_wrapper(msg: ReceiveMessage) -> None:
'Call with deprecated signature.'
(await cast(AsyncDeprecatedMessageCallbackType, msg_callback)(msg.topic, msg.payload, msg.qos)) | Call with deprecated signature. | homeassistant/components/mqtt/__init__.py | async_wrapper | 3guoyangyang7/core | 11 | python | @wraps(msg_callback)
async def async_wrapper(msg: ReceiveMessage) -> None:
(await cast(AsyncDeprecatedMessageCallbackType, msg_callback)(msg.topic, msg.payload, msg.qos)) | @wraps(msg_callback)
async def async_wrapper(msg: ReceiveMessage) -> None:
(await cast(AsyncDeprecatedMessageCallbackType, msg_callback)(msg.topic, msg.payload, msg.qos))<|docstring|>Call with deprecated signature.<|endoftext|> |
08bb460125e1d4851b02fef7dbce74a87d2e6c796e2bb579493cf7c4e0601ed7 | @wraps(msg_callback)
def wrapper(msg: ReceiveMessage) -> None:
'Call with deprecated signature.'
msg_callback(msg.topic, msg.payload, msg.qos) | Call with deprecated signature. | homeassistant/components/mqtt/__init__.py | wrapper | 3guoyangyang7/core | 11 | python | @wraps(msg_callback)
def wrapper(msg: ReceiveMessage) -> None:
msg_callback(msg.topic, msg.payload, msg.qos) | @wraps(msg_callback)
def wrapper(msg: ReceiveMessage) -> None:
msg_callback(msg.topic, msg.payload, msg.qos)<|docstring|>Call with deprecated signature.<|endoftext|> |
84c6bd15c44a18ed1bb14de2d7c7886fd408eb6b52ceb957b27e071dcb46a5a2 | async def finish_dump(_):
'Write dump to file.'
unsub()
(await hass.async_add_executor_job(write_dump)) | Write dump to file. | homeassistant/components/mqtt/__init__.py | finish_dump | 3guoyangyang7/core | 11 | python | async def finish_dump(_):
unsub()
(await hass.async_add_executor_job(write_dump)) | async def finish_dump(_):
unsub()
(await hass.async_add_executor_job(write_dump))<|docstring|>Write dump to file.<|endoftext|> |
ae631158f3d7c2efed700fb5a9eefb758aa50e2d60695f620b965bafc7536fb9 | def stop():
'Stop the MQTT client.'
self._mqttc.loop_stop() | Stop the MQTT client. | homeassistant/components/mqtt/__init__.py | stop | 3guoyangyang7/core | 11 | python | def stop():
self._mqttc.loop_stop() | def stop():
self._mqttc.loop_stop()<|docstring|>Stop the MQTT client.<|endoftext|> |
9c71cfef414d8b72484e82275442fd3f9496263d6a6293ed30f67c3a6b4b6456 | @callback
def async_remove() -> None:
'Remove subscription.'
if (subscription not in self.subscriptions):
raise HomeAssistantError("Can't remove subscription twice")
self.subscriptions.remove(subscription)
self._matching_subscriptions.cache_clear()
if any(((other.topic == topic) for other in self.subscriptions)):
return
if self.connected:
self.hass.async_create_task(self._async_unsubscribe(topic)) | Remove subscription. | homeassistant/components/mqtt/__init__.py | async_remove | 3guoyangyang7/core | 11 | python | @callback
def async_remove() -> None:
if (subscription not in self.subscriptions):
raise HomeAssistantError("Can't remove subscription twice")
self.subscriptions.remove(subscription)
self._matching_subscriptions.cache_clear()
if any(((other.topic == topic) for other in self.subscriptions)):
return
if self.connected:
self.hass.async_create_task(self._async_unsubscribe(topic)) | @callback
def async_remove() -> None:
if (subscription not in self.subscriptions):
raise HomeAssistantError("Can't remove subscription twice")
self.subscriptions.remove(subscription)
self._matching_subscriptions.cache_clear()
if any(((other.topic == topic) for other in self.subscriptions)):
return
if self.connected:
self.hass.async_create_task(self._async_unsubscribe(topic))<|docstring|>Remove subscription.<|endoftext|> |
71cd8003495062aeb95889c5264d0f84751ac9c75214f88977b26cbb472ed9ec | @scenario('Sign out')
def test_sign_out() -> None:
'Sign out.' | Sign out. | tests/step_defs/signout/test_signout_success.py | test_sign_out | pbraiders/pomponne-test-bdd | 1 | python | @scenario('Sign out')
def test_sign_out() -> None:
| @scenario('Sign out')
def test_sign_out() -> None:
<|docstring|>Sign out.<|endoftext|> |
fea8ca6d75aaac82167f3b83d6ac13a7fb6b18377d113af0ff2dff92f153a3ab | @given('I am using the app', target_fixture='page_signout')
def page_signout(the_browser, the_config, the_database) -> SignoutPage:
'I am using the app.'
assert (sign_in(driver=the_browser, config=the_config, user='simple') is True)
return SignoutPage(_driver=the_browser, _config=the_config['urls']) | I am using the app. | tests/step_defs/signout/test_signout_success.py | page_signout | pbraiders/pomponne-test-bdd | 1 | python | @given('I am using the app', target_fixture='page_signout')
def page_signout(the_browser, the_config, the_database) -> SignoutPage:
assert (sign_in(driver=the_browser, config=the_config, user='simple') is True)
return SignoutPage(_driver=the_browser, _config=the_config['urls']) | @given('I am using the app', target_fixture='page_signout')
def page_signout(the_browser, the_config, the_database) -> SignoutPage:
assert (sign_in(driver=the_browser, config=the_config, user='simple') is True)
return SignoutPage(_driver=the_browser, _config=the_config['urls'])<|docstring|>I am using the app.<|endoftext|> |
31b0e8a2fe4284941366e58df1cef59d728e24f20f756cb113a9d8f71b1bfd24 | @when('I sign out of the app')
def sign_out(page_signout) -> None:
'I sign out of the app.'
page_signout.visit() | I sign out of the app. | tests/step_defs/signout/test_signout_success.py | sign_out | pbraiders/pomponne-test-bdd | 1 | python | @when('I sign out of the app')
def sign_out(page_signout) -> None:
page_signout.visit() | @when('I sign out of the app')
def sign_out(page_signout) -> None:
page_signout.visit()<|docstring|>I sign out of the app.<|endoftext|> |
cd12a4a64dcb8ea040d495150c05bc97884067ef8066c761eda21f6da7db1f25 | @then('I should be disconnected')
def not_connected(page_signout) -> None:
'I should be disconnected.'
assert (page_signout.on_page() is True) | I should be disconnected. | tests/step_defs/signout/test_signout_success.py | not_connected | pbraiders/pomponne-test-bdd | 1 | python | @then('I should be disconnected')
def not_connected(page_signout) -> None:
assert (page_signout.on_page() is True) | @then('I should be disconnected')
def not_connected(page_signout) -> None:
assert (page_signout.on_page() is True)<|docstring|>I should be disconnected.<|endoftext|> |
9cacf3e2d1cf8be4b38b11cf4382d34c17692739427dca4ec9cff76627320e44 | def mergeTrees(self, t1, t2):
'\n :type t1: TreeNode\n :type t2: TreeNode\n :rtype: TreeNode\n '
if (t1 is None):
return t2
if (t2 is None):
return t1
t1.val += t2.val
t1.left = self.mergeTrees(t1.left, t2.left)
t1.right = self.mergeTrees(t1.right, t2.right)
return t1 | :type t1: TreeNode
:type t2: TreeNode
:rtype: TreeNode | tree/0617_merge_two_binary_trees/0617_merge_two_binary_trees.py | mergeTrees | zdyxry/LeetCode | 6 | python | def mergeTrees(self, t1, t2):
'\n :type t1: TreeNode\n :type t2: TreeNode\n :rtype: TreeNode\n '
if (t1 is None):
return t2
if (t2 is None):
return t1
t1.val += t2.val
t1.left = self.mergeTrees(t1.left, t2.left)
t1.right = self.mergeTrees(t1.right, t2.right)
return t1 | def mergeTrees(self, t1, t2):
'\n :type t1: TreeNode\n :type t2: TreeNode\n :rtype: TreeNode\n '
if (t1 is None):
return t2
if (t2 is None):
return t1
t1.val += t2.val
t1.left = self.mergeTrees(t1.left, t2.left)
t1.right = self.mergeTrees(t1.right, t2.right)
return t1<|docstring|>:type t1: TreeNode
:type t2: TreeNode
:rtype: TreeNode<|endoftext|> |
f8b3cd68d02da991fa23dd52e51a44169346512af60778b6c83f10c355f73dc4 | @property
def statistics(self):
'Test execution :class:`~robot.model.statistics.Statistics`.'
return Statistics(self.suite, **self._stat_config) | Test execution :class:`~robot.model.statistics.Statistics`. | lib/robot/result/executionresult.py | statistics | jussimalinen/robotframework-mabot | 8 | python | @property
def statistics(self):
return Statistics(self.suite, **self._stat_config) | @property
def statistics(self):
return Statistics(self.suite, **self._stat_config)<|docstring|>Test execution :class:`~robot.model.statistics.Statistics`.<|endoftext|> |
8c7d19086199aa94fba4dd409ed93eb0ca1e4c668fe887cf25d8e479bf141398 | @property
def return_code(self):
'Return code (integer) of test execution.'
if self._status_rc:
return min(self.suite.statistics.critical.failed, 250)
return 0 | Return code (integer) of test execution. | lib/robot/result/executionresult.py | return_code | jussimalinen/robotframework-mabot | 8 | python | @property
def return_code(self):
if self._status_rc:
return min(self.suite.statistics.critical.failed, 250)
return 0 | @property
def return_code(self):
if self._status_rc:
return min(self.suite.statistics.critical.failed, 250)
return 0<|docstring|>Return code (integer) of test execution.<|endoftext|> |
5d37e8d53a25bb919758bb56ac645cb1c1b7fef11501caed2063ca5ea45e0785 | def infer(self, conf, faces, target_embs, tta=False):
"\n faces : list of PIL Image\n target_embs : [n, 512] computed embeddings of faces in facebank\n names : recorded names of faces in facebank\n tta : test time augmentation (hfilp, that's all)\n "
embs = []
for img in faces:
if tta:
mirror = trans.functional.hflip(img)
emb = self.model(conf.test_transform(img).to(conf.device).unsqueeze(0))
emb_mirror = self.model(conf.test_transform(mirror).to(conf.device).unsqueeze(0))
embs.append(l2_norm((emb + emb_mirror)))
else:
embs.append(self.model(conf.test_transform(img).to(conf.device).unsqueeze(0)))
source_embs = torch.cat(embs)
diff = (source_embs.unsqueeze((- 1)) - target_embs.transpose(1, 0).unsqueeze(0))
dist = torch.sum(torch.pow(diff, 2), dim=1)
(minimum, min_idx) = torch.min(dist, dim=1)
min_idx[(minimum > self.threshold)] = (- 1)
return (min_idx, minimum) | faces : list of PIL Image
target_embs : [n, 512] computed embeddings of faces in facebank
names : recorded names of faces in facebank
tta : test time augmentation (hfilp, that's all) | Learner.py | infer | lucasforever24/arcface_noonan | 0 | python | def infer(self, conf, faces, target_embs, tta=False):
"\n faces : list of PIL Image\n target_embs : [n, 512] computed embeddings of faces in facebank\n names : recorded names of faces in facebank\n tta : test time augmentation (hfilp, that's all)\n "
embs = []
for img in faces:
if tta:
mirror = trans.functional.hflip(img)
emb = self.model(conf.test_transform(img).to(conf.device).unsqueeze(0))
emb_mirror = self.model(conf.test_transform(mirror).to(conf.device).unsqueeze(0))
embs.append(l2_norm((emb + emb_mirror)))
else:
embs.append(self.model(conf.test_transform(img).to(conf.device).unsqueeze(0)))
source_embs = torch.cat(embs)
diff = (source_embs.unsqueeze((- 1)) - target_embs.transpose(1, 0).unsqueeze(0))
dist = torch.sum(torch.pow(diff, 2), dim=1)
(minimum, min_idx) = torch.min(dist, dim=1)
min_idx[(minimum > self.threshold)] = (- 1)
return (min_idx, minimum) | def infer(self, conf, faces, target_embs, tta=False):
"\n faces : list of PIL Image\n target_embs : [n, 512] computed embeddings of faces in facebank\n names : recorded names of faces in facebank\n tta : test time augmentation (hfilp, that's all)\n "
embs = []
for img in faces:
if tta:
mirror = trans.functional.hflip(img)
emb = self.model(conf.test_transform(img).to(conf.device).unsqueeze(0))
emb_mirror = self.model(conf.test_transform(mirror).to(conf.device).unsqueeze(0))
embs.append(l2_norm((emb + emb_mirror)))
else:
embs.append(self.model(conf.test_transform(img).to(conf.device).unsqueeze(0)))
source_embs = torch.cat(embs)
diff = (source_embs.unsqueeze((- 1)) - target_embs.transpose(1, 0).unsqueeze(0))
dist = torch.sum(torch.pow(diff, 2), dim=1)
(minimum, min_idx) = torch.min(dist, dim=1)
min_idx[(minimum > self.threshold)] = (- 1)
return (min_idx, minimum)<|docstring|>faces : list of PIL Image
target_embs : [n, 512] computed embeddings of faces in facebank
names : recorded names of faces in facebank
tta : test time augmentation (hfilp, that's all)<|endoftext|> |
6367adf54a81aefdc257f6039e53a17061bc22097e770cd147c2e2852d3916f2 | def binfer(self, conf, faces, target_embs, tta=False):
"\n return raw scores for every class \n faces : list of PIL Image\n target_embs : [n, 512] computed embeddings of faces in facebank\n names : recorded names of faces in facebank\n tta : test time augmentation (hfilp, that's all)\n "
self.model.eval()
self.plot_result()
embs = []
for img in faces:
if tta:
mirror = trans.functional.hflip(img)
emb = self.model(conf.test_transform(img).to(conf.device).unsqueeze(0))
emb_mirror = self.model(conf.test_transform(mirror).to(conf.device).unsqueeze(0))
embs.append(l2_norm((emb + emb_mirror)))
else:
embs.append(self.model(conf.test_transform(img).to(conf.device).unsqueeze(0)))
source_embs = torch.cat(embs)
diff = (source_embs.unsqueeze((- 1)) - target_embs.transpose(1, 0).unsqueeze(0))
dist = torch.sum(torch.pow(diff, 2), dim=1)
return dist.detach().cpu().numpy() | return raw scores for every class
faces : list of PIL Image
target_embs : [n, 512] computed embeddings of faces in facebank
names : recorded names of faces in facebank
tta : test time augmentation (hfilp, that's all) | Learner.py | binfer | lucasforever24/arcface_noonan | 0 | python | def binfer(self, conf, faces, target_embs, tta=False):
"\n return raw scores for every class \n faces : list of PIL Image\n target_embs : [n, 512] computed embeddings of faces in facebank\n names : recorded names of faces in facebank\n tta : test time augmentation (hfilp, that's all)\n "
self.model.eval()
self.plot_result()
embs = []
for img in faces:
if tta:
mirror = trans.functional.hflip(img)
emb = self.model(conf.test_transform(img).to(conf.device).unsqueeze(0))
emb_mirror = self.model(conf.test_transform(mirror).to(conf.device).unsqueeze(0))
embs.append(l2_norm((emb + emb_mirror)))
else:
embs.append(self.model(conf.test_transform(img).to(conf.device).unsqueeze(0)))
source_embs = torch.cat(embs)
diff = (source_embs.unsqueeze((- 1)) - target_embs.transpose(1, 0).unsqueeze(0))
dist = torch.sum(torch.pow(diff, 2), dim=1)
return dist.detach().cpu().numpy() | def binfer(self, conf, faces, target_embs, tta=False):
"\n return raw scores for every class \n faces : list of PIL Image\n target_embs : [n, 512] computed embeddings of faces in facebank\n names : recorded names of faces in facebank\n tta : test time augmentation (hfilp, that's all)\n "
self.model.eval()
self.plot_result()
embs = []
for img in faces:
if tta:
mirror = trans.functional.hflip(img)
emb = self.model(conf.test_transform(img).to(conf.device).unsqueeze(0))
emb_mirror = self.model(conf.test_transform(mirror).to(conf.device).unsqueeze(0))
embs.append(l2_norm((emb + emb_mirror)))
else:
embs.append(self.model(conf.test_transform(img).to(conf.device).unsqueeze(0)))
source_embs = torch.cat(embs)
diff = (source_embs.unsqueeze((- 1)) - target_embs.transpose(1, 0).unsqueeze(0))
dist = torch.sum(torch.pow(diff, 2), dim=1)
return dist.detach().cpu().numpy()<|docstring|>return raw scores for every class
faces : list of PIL Image
target_embs : [n, 512] computed embeddings of faces in facebank
names : recorded names of faces in facebank
tta : test time augmentation (hfilp, that's all)<|endoftext|> |
8652075ceecad939d6d859f601a32640cdf51a839e644c4fab045e8b6eb8ba23 | def create_multisequence_model(P1, P2):
'\n\tshould be direction observations\n\n\tpositions ==get==> directions ==infer==> next step ==get==> new position\n\t'
P = np.concatenate([P1, P2])
lengths = [len(P1), len(P2)]
return hmm.GaussianHMM(n_components=3).fit(P, lengths) | should be direction observations
positions ==get==> directions ==infer==> next step ==get==> new position | src/hmm.py | create_multisequence_model | dkkim93/9.66_collision_final_project | 0 | python | def create_multisequence_model(P1, P2):
'\n\tshould be direction observations\n\n\tpositions ==get==> directions ==infer==> next step ==get==> new position\n\t'
P = np.concatenate([P1, P2])
lengths = [len(P1), len(P2)]
return hmm.GaussianHMM(n_components=3).fit(P, lengths) | def create_multisequence_model(P1, P2):
'\n\tshould be direction observations\n\n\tpositions ==get==> directions ==infer==> next step ==get==> new position\n\t'
P = np.concatenate([P1, P2])
lengths = [len(P1), len(P2)]
return hmm.GaussianHMM(n_components=3).fit(P, lengths)<|docstring|>should be direction observations
positions ==get==> directions ==infer==> next step ==get==> new position<|endoftext|> |
f32d7ca2b5f5cc10b2ffb9bb3407312c10e48cd5bb752135c50f900befbbe9d1 | def re_score(pred_relations, gt_relations, mode='strict'):
'Evaluate RE predictions\n\n Args:\n pred_relations (list) : list of list of predicted relations (several relations in each sentence)\n gt_relations (list) : list of list of ground truth relations\n\n rel = { "head": (start_idx (inclusive), end_idx (exclusive)),\n "tail": (start_idx (inclusive), end_idx (exclusive)),\n "head_type": ent_type,\n "tail_type": ent_type,\n "type": rel_type}\n\n vocab (Vocab) : dataset vocabulary\n mode (str) : in \'strict\' or \'boundaries\''
assert (mode in ['strict', 'boundaries'])
relation_types = [v for v in [0, 1] if (not (v == 0))]
scores = {rel: {'tp': 0, 'fp': 0, 'fn': 0} for rel in (relation_types + ['ALL'])}
n_sents = len(gt_relations)
n_rels = sum([len([rel for rel in sent]) for sent in gt_relations])
n_found = sum([len([rel for rel in sent]) for sent in pred_relations])
for (pred_sent, gt_sent) in zip(pred_relations, gt_relations):
for rel_type in relation_types:
if (mode == 'strict'):
pred_rels = {(rel['head'], rel['head_type'], rel['tail'], rel['tail_type']) for rel in pred_sent if (rel['type'] == rel_type)}
gt_rels = {(rel['head'], rel['head_type'], rel['tail'], rel['tail_type']) for rel in gt_sent if (rel['type'] == rel_type)}
elif (mode == 'boundaries'):
pred_rels = {(rel['head'], rel['tail']) for rel in pred_sent if (rel['type'] == rel_type)}
gt_rels = {(rel['head'], rel['tail']) for rel in gt_sent if (rel['type'] == rel_type)}
scores[rel_type]['tp'] += len((pred_rels & gt_rels))
scores[rel_type]['fp'] += len((pred_rels - gt_rels))
scores[rel_type]['fn'] += len((gt_rels - pred_rels))
for rel_type in scores.keys():
if scores[rel_type]['tp']:
scores[rel_type]['p'] = (scores[rel_type]['tp'] / (scores[rel_type]['fp'] + scores[rel_type]['tp']))
scores[rel_type]['r'] = (scores[rel_type]['tp'] / (scores[rel_type]['fn'] + scores[rel_type]['tp']))
else:
(scores[rel_type]['p'], scores[rel_type]['r']) = (0, 0)
if (not ((scores[rel_type]['p'] + scores[rel_type]['r']) == 0)):
scores[rel_type]['f1'] = (((2 * scores[rel_type]['p']) * scores[rel_type]['r']) / (scores[rel_type]['p'] + scores[rel_type]['r']))
else:
scores[rel_type]['f1'] = 0
tp = sum([scores[rel_type]['tp'] for rel_type in relation_types])
fp = sum([scores[rel_type]['fp'] for rel_type in relation_types])
fn = sum([scores[rel_type]['fn'] for rel_type in relation_types])
if tp:
precision = (tp / (tp + fp))
recall = (tp / (tp + fn))
f1 = (((2 * precision) * recall) / (precision + recall))
else:
(precision, recall, f1) = (0, 0, 0)
scores['ALL']['p'] = precision
scores['ALL']['r'] = recall
scores['ALL']['f1'] = f1
scores['ALL']['tp'] = tp
scores['ALL']['fp'] = fp
scores['ALL']['fn'] = fn
scores['ALL']['Macro_f1'] = np.mean([scores[ent_type]['f1'] for ent_type in relation_types])
scores['ALL']['Macro_p'] = np.mean([scores[ent_type]['p'] for ent_type in relation_types])
scores['ALL']['Macro_r'] = np.mean([scores[ent_type]['r'] for ent_type in relation_types])
logger.info(f'RE Evaluation in *** {mode.upper()} *** mode')
logger.info('processed {} sentences with {} relations; found: {} relations; correct: {}.'.format(n_sents, n_rels, n_found, tp))
logger.info('\tALL\t TP: {};\tFP: {};\tFN: {}'.format(scores['ALL']['tp'], scores['ALL']['fp'], scores['ALL']['fn']))
logger.info('\t\t(m avg): precision: {:.2f};\trecall: {:.2f};\tf1: {:.2f} (micro)'.format(precision, recall, f1))
logger.info('\t\t(M avg): precision: {:.2f};\trecall: {:.2f};\tf1: {:.2f} (Macro)\n'.format(scores['ALL']['Macro_p'], scores['ALL']['Macro_r'], scores['ALL']['Macro_f1']))
for rel_type in relation_types:
logger.info('\t{}: \tTP: {};\tFP: {};\tFN: {};\tprecision: {:.2f};\trecall: {:.2f};\tf1: {:.2f};\t{}'.format(rel_type, scores[rel_type]['tp'], scores[rel_type]['fp'], scores[rel_type]['fn'], scores[rel_type]['p'], scores[rel_type]['r'], scores[rel_type]['f1'], (scores[rel_type]['tp'] + scores[rel_type]['fp'])))
return scores | Evaluate RE predictions
Args:
pred_relations (list) : list of list of predicted relations (several relations in each sentence)
gt_relations (list) : list of list of ground truth relations
rel = { "head": (start_idx (inclusive), end_idx (exclusive)),
"tail": (start_idx (inclusive), end_idx (exclusive)),
"head_type": ent_type,
"tail_type": ent_type,
"type": rel_type}
vocab (Vocab) : dataset vocabulary
mode (str) : in 'strict' or 'boundaries' | layoutlmft/layoutlmft/evaluation.py | re_score | sandutsar/unilm | 5,129 | python | def re_score(pred_relations, gt_relations, mode='strict'):
'Evaluate RE predictions\n\n Args:\n pred_relations (list) : list of list of predicted relations (several relations in each sentence)\n gt_relations (list) : list of list of ground truth relations\n\n rel = { "head": (start_idx (inclusive), end_idx (exclusive)),\n "tail": (start_idx (inclusive), end_idx (exclusive)),\n "head_type": ent_type,\n "tail_type": ent_type,\n "type": rel_type}\n\n vocab (Vocab) : dataset vocabulary\n mode (str) : in \'strict\' or \'boundaries\
assert (mode in ['strict', 'boundaries'])
relation_types = [v for v in [0, 1] if (not (v == 0))]
scores = {rel: {'tp': 0, 'fp': 0, 'fn': 0} for rel in (relation_types + ['ALL'])}
n_sents = len(gt_relations)
n_rels = sum([len([rel for rel in sent]) for sent in gt_relations])
n_found = sum([len([rel for rel in sent]) for sent in pred_relations])
for (pred_sent, gt_sent) in zip(pred_relations, gt_relations):
for rel_type in relation_types:
if (mode == 'strict'):
pred_rels = {(rel['head'], rel['head_type'], rel['tail'], rel['tail_type']) for rel in pred_sent if (rel['type'] == rel_type)}
gt_rels = {(rel['head'], rel['head_type'], rel['tail'], rel['tail_type']) for rel in gt_sent if (rel['type'] == rel_type)}
elif (mode == 'boundaries'):
pred_rels = {(rel['head'], rel['tail']) for rel in pred_sent if (rel['type'] == rel_type)}
gt_rels = {(rel['head'], rel['tail']) for rel in gt_sent if (rel['type'] == rel_type)}
scores[rel_type]['tp'] += len((pred_rels & gt_rels))
scores[rel_type]['fp'] += len((pred_rels - gt_rels))
scores[rel_type]['fn'] += len((gt_rels - pred_rels))
for rel_type in scores.keys():
if scores[rel_type]['tp']:
scores[rel_type]['p'] = (scores[rel_type]['tp'] / (scores[rel_type]['fp'] + scores[rel_type]['tp']))
scores[rel_type]['r'] = (scores[rel_type]['tp'] / (scores[rel_type]['fn'] + scores[rel_type]['tp']))
else:
(scores[rel_type]['p'], scores[rel_type]['r']) = (0, 0)
if (not ((scores[rel_type]['p'] + scores[rel_type]['r']) == 0)):
scores[rel_type]['f1'] = (((2 * scores[rel_type]['p']) * scores[rel_type]['r']) / (scores[rel_type]['p'] + scores[rel_type]['r']))
else:
scores[rel_type]['f1'] = 0
tp = sum([scores[rel_type]['tp'] for rel_type in relation_types])
fp = sum([scores[rel_type]['fp'] for rel_type in relation_types])
fn = sum([scores[rel_type]['fn'] for rel_type in relation_types])
if tp:
precision = (tp / (tp + fp))
recall = (tp / (tp + fn))
f1 = (((2 * precision) * recall) / (precision + recall))
else:
(precision, recall, f1) = (0, 0, 0)
scores['ALL']['p'] = precision
scores['ALL']['r'] = recall
scores['ALL']['f1'] = f1
scores['ALL']['tp'] = tp
scores['ALL']['fp'] = fp
scores['ALL']['fn'] = fn
scores['ALL']['Macro_f1'] = np.mean([scores[ent_type]['f1'] for ent_type in relation_types])
scores['ALL']['Macro_p'] = np.mean([scores[ent_type]['p'] for ent_type in relation_types])
scores['ALL']['Macro_r'] = np.mean([scores[ent_type]['r'] for ent_type in relation_types])
logger.info(f'RE Evaluation in *** {mode.upper()} *** mode')
logger.info('processed {} sentences with {} relations; found: {} relations; correct: {}.'.format(n_sents, n_rels, n_found, tp))
logger.info('\tALL\t TP: {};\tFP: {};\tFN: {}'.format(scores['ALL']['tp'], scores['ALL']['fp'], scores['ALL']['fn']))
logger.info('\t\t(m avg): precision: {:.2f};\trecall: {:.2f};\tf1: {:.2f} (micro)'.format(precision, recall, f1))
logger.info('\t\t(M avg): precision: {:.2f};\trecall: {:.2f};\tf1: {:.2f} (Macro)\n'.format(scores['ALL']['Macro_p'], scores['ALL']['Macro_r'], scores['ALL']['Macro_f1']))
for rel_type in relation_types:
logger.info('\t{}: \tTP: {};\tFP: {};\tFN: {};\tprecision: {:.2f};\trecall: {:.2f};\tf1: {:.2f};\t{}'.format(rel_type, scores[rel_type]['tp'], scores[rel_type]['fp'], scores[rel_type]['fn'], scores[rel_type]['p'], scores[rel_type]['r'], scores[rel_type]['f1'], (scores[rel_type]['tp'] + scores[rel_type]['fp'])))
return scores | def re_score(pred_relations, gt_relations, mode='strict'):
'Evaluate RE predictions\n\n Args:\n pred_relations (list) : list of list of predicted relations (several relations in each sentence)\n gt_relations (list) : list of list of ground truth relations\n\n rel = { "head": (start_idx (inclusive), end_idx (exclusive)),\n "tail": (start_idx (inclusive), end_idx (exclusive)),\n "head_type": ent_type,\n "tail_type": ent_type,\n "type": rel_type}\n\n vocab (Vocab) : dataset vocabulary\n mode (str) : in \'strict\' or \'boundaries\
assert (mode in ['strict', 'boundaries'])
relation_types = [v for v in [0, 1] if (not (v == 0))]
scores = {rel: {'tp': 0, 'fp': 0, 'fn': 0} for rel in (relation_types + ['ALL'])}
n_sents = len(gt_relations)
n_rels = sum([len([rel for rel in sent]) for sent in gt_relations])
n_found = sum([len([rel for rel in sent]) for sent in pred_relations])
for (pred_sent, gt_sent) in zip(pred_relations, gt_relations):
for rel_type in relation_types:
if (mode == 'strict'):
pred_rels = {(rel['head'], rel['head_type'], rel['tail'], rel['tail_type']) for rel in pred_sent if (rel['type'] == rel_type)}
gt_rels = {(rel['head'], rel['head_type'], rel['tail'], rel['tail_type']) for rel in gt_sent if (rel['type'] == rel_type)}
elif (mode == 'boundaries'):
pred_rels = {(rel['head'], rel['tail']) for rel in pred_sent if (rel['type'] == rel_type)}
gt_rels = {(rel['head'], rel['tail']) for rel in gt_sent if (rel['type'] == rel_type)}
scores[rel_type]['tp'] += len((pred_rels & gt_rels))
scores[rel_type]['fp'] += len((pred_rels - gt_rels))
scores[rel_type]['fn'] += len((gt_rels - pred_rels))
for rel_type in scores.keys():
if scores[rel_type]['tp']:
scores[rel_type]['p'] = (scores[rel_type]['tp'] / (scores[rel_type]['fp'] + scores[rel_type]['tp']))
scores[rel_type]['r'] = (scores[rel_type]['tp'] / (scores[rel_type]['fn'] + scores[rel_type]['tp']))
else:
(scores[rel_type]['p'], scores[rel_type]['r']) = (0, 0)
if (not ((scores[rel_type]['p'] + scores[rel_type]['r']) == 0)):
scores[rel_type]['f1'] = (((2 * scores[rel_type]['p']) * scores[rel_type]['r']) / (scores[rel_type]['p'] + scores[rel_type]['r']))
else:
scores[rel_type]['f1'] = 0
tp = sum([scores[rel_type]['tp'] for rel_type in relation_types])
fp = sum([scores[rel_type]['fp'] for rel_type in relation_types])
fn = sum([scores[rel_type]['fn'] for rel_type in relation_types])
if tp:
precision = (tp / (tp + fp))
recall = (tp / (tp + fn))
f1 = (((2 * precision) * recall) / (precision + recall))
else:
(precision, recall, f1) = (0, 0, 0)
scores['ALL']['p'] = precision
scores['ALL']['r'] = recall
scores['ALL']['f1'] = f1
scores['ALL']['tp'] = tp
scores['ALL']['fp'] = fp
scores['ALL']['fn'] = fn
scores['ALL']['Macro_f1'] = np.mean([scores[ent_type]['f1'] for ent_type in relation_types])
scores['ALL']['Macro_p'] = np.mean([scores[ent_type]['p'] for ent_type in relation_types])
scores['ALL']['Macro_r'] = np.mean([scores[ent_type]['r'] for ent_type in relation_types])
logger.info(f'RE Evaluation in *** {mode.upper()} *** mode')
logger.info('processed {} sentences with {} relations; found: {} relations; correct: {}.'.format(n_sents, n_rels, n_found, tp))
logger.info('\tALL\t TP: {};\tFP: {};\tFN: {}'.format(scores['ALL']['tp'], scores['ALL']['fp'], scores['ALL']['fn']))
logger.info('\t\t(m avg): precision: {:.2f};\trecall: {:.2f};\tf1: {:.2f} (micro)'.format(precision, recall, f1))
logger.info('\t\t(M avg): precision: {:.2f};\trecall: {:.2f};\tf1: {:.2f} (Macro)\n'.format(scores['ALL']['Macro_p'], scores['ALL']['Macro_r'], scores['ALL']['Macro_f1']))
for rel_type in relation_types:
logger.info('\t{}: \tTP: {};\tFP: {};\tFN: {};\tprecision: {:.2f};\trecall: {:.2f};\tf1: {:.2f};\t{}'.format(rel_type, scores[rel_type]['tp'], scores[rel_type]['fp'], scores[rel_type]['fn'], scores[rel_type]['p'], scores[rel_type]['r'], scores[rel_type]['f1'], (scores[rel_type]['tp'] + scores[rel_type]['fp'])))
return scores<|docstring|>Evaluate RE predictions
Args:
pred_relations (list) : list of list of predicted relations (several relations in each sentence)
gt_relations (list) : list of list of ground truth relations
rel = { "head": (start_idx (inclusive), end_idx (exclusive)),
"tail": (start_idx (inclusive), end_idx (exclusive)),
"head_type": ent_type,
"tail_type": ent_type,
"type": rel_type}
vocab (Vocab) : dataset vocabulary
mode (str) : in 'strict' or 'boundaries'<|endoftext|> |
123dc0a040d40e5a46b6135cad332d8a70d2ba9a0c901b041941acd847c1972d | def init():
'Return True if the plugin has loaded successfully.'
ok = (not g.unitTesting)
if ok:
g.registerHandler('menu2', onMenu)
g.plugin_signon(__name__)
return ok | Return True if the plugin has loaded successfully. | leo/plugins/examples/chinese_menu.py | init | thomasbuttler/leo-editor | 1,550 | python | def init():
ok = (not g.unitTesting)
if ok:
g.registerHandler('menu2', onMenu)
g.plugin_signon(__name__)
return ok | def init():
ok = (not g.unitTesting)
if ok:
g.registerHandler('menu2', onMenu)
g.plugin_signon(__name__)
return ok<|docstring|>Return True if the plugin has loaded successfully.<|endoftext|> |
6c7fb309d3e7e521e1a2c95d5d3ef199ddaa6f9ea79e41cdb259a9837c60bfc0 | def __virtual__():
'\n NAPALM library must be installed for this module to work and run in a (proxy) minion.\n This module in particular requires also napalm-yang.\n '
if (not HAS_NAPALM_YANG):
return (False, 'Unable to load napalm_yang execution module: please install napalm-yang!')
return salt.utils.napalm.virtual(__opts__, __virtualname__, __file__) | NAPALM library must be installed for this module to work and run in a (proxy) minion.
This module in particular requires also napalm-yang. | salt/states/net_napalm_yang.py | __virtual__ | Flowdalic/salt | 9,425 | python | def __virtual__():
'\n NAPALM library must be installed for this module to work and run in a (proxy) minion.\n This module in particular requires also napalm-yang.\n '
if (not HAS_NAPALM_YANG):
return (False, 'Unable to load napalm_yang execution module: please install napalm-yang!')
return salt.utils.napalm.virtual(__opts__, __virtualname__, __file__) | def __virtual__():
'\n NAPALM library must be installed for this module to work and run in a (proxy) minion.\n This module in particular requires also napalm-yang.\n '
if (not HAS_NAPALM_YANG):
return (False, 'Unable to load napalm_yang execution module: please install napalm-yang!')
return salt.utils.napalm.virtual(__opts__, __virtualname__, __file__)<|docstring|>NAPALM library must be installed for this module to work and run in a (proxy) minion.
This module in particular requires also napalm-yang.<|endoftext|> |
76d24773eda49915d1716dd0a65fbd965061bb052b7bc7de8b94df45b5d8a855 | def managed(name, data, **kwargs):
'\n Manage the device configuration given the input data structured\n according to the YANG models.\n\n data\n YANG structured data.\n\n models\n A list of models to be used when generating the config.\n\n profiles: ``None``\n Use certain profiles to generate the config.\n If not specified, will use the platform default profile(s).\n\n compliance_report: ``False``\n Return the compliance report in the comment.\n\n .. versionadded:: 2017.7.3\n\n test: ``False``\n Dry run? If set as ``True``, will apply the config, discard\n and return the changes. Default: ``False`` and will commit\n the changes on the device.\n\n commit: ``True``\n Commit? Default: ``True``.\n\n debug: ``False``\n Debug mode. Will insert a new key under the output dictionary,\n as ``loaded_config`` containing the raw configuration loaded on the device.\n\n replace: ``False``\n Should replace the config with the new generate one?\n\n State SLS example:\n\n .. code-block:: jinja\n\n {%- set expected_config = pillar.get(\'openconfig_interfaces_cfg\') -%}\n interfaces_config:\n napalm_yang.managed:\n - data: {{ expected_config | json }}\n - models:\n - models.openconfig_interfaces\n - debug: true\n\n Pillar example:\n\n .. code-block:: yaml\n\n openconfig_interfaces_cfg:\n _kwargs:\n filter: true\n interfaces:\n interface:\n Et1:\n config:\n mtu: 9000\n Et2:\n config:\n description: "description example"\n '
models = kwargs.get('models', None)
if (isinstance(models, tuple) and isinstance(models[0], list)):
models = models[0]
ret = salt.utils.napalm.default_ret(name)
test = (kwargs.get('test', False) or __opts__.get('test', False))
debug = (kwargs.get('debug', False) or __opts__.get('debug', False))
commit = (kwargs.get('commit', True) or __opts__.get('commit', True))
replace = (kwargs.get('replace', False) or __opts__.get('replace', False))
return_compliance_report = (kwargs.get('compliance_report', False) or __opts__.get('compliance_report', False))
profiles = kwargs.get('profiles', [])
temp_file = __salt__['temp.file']()
log.debug('Creating temp file: %s', temp_file)
if ('to_dict' not in data):
data = {'to_dict': data}
data = [data]
with salt.utils.files.fopen(temp_file, 'w') as file_handle:
salt.utils.yaml.safe_dump(salt.utils.json.loads(salt.utils.json.dumps(data)), file_handle, encoding='utf-8')
device_config = __salt__['napalm_yang.parse'](*models, config=True, profiles=profiles)
log.debug('Parsed the config from the device:')
log.debug(device_config)
compliance_report = __salt__['napalm_yang.compliance_report'](device_config, *models, filepath=temp_file)
log.debug('Compliance report:')
log.debug(compliance_report)
complies = compliance_report.get('complies', False)
if complies:
ret.update({'result': True, 'comment': 'Already configured as required.'})
log.debug('All good here.')
return ret
log.debug('Does not comply, trying to generate and load config')
data = data[0]['to_dict']
if ('_kwargs' in data):
data.pop('_kwargs')
loaded_changes = __salt__['napalm_yang.load_config'](data, *models, profiles=profiles, test=test, debug=debug, commit=commit, replace=replace)
log.debug('Loaded config result:')
log.debug(loaded_changes)
__salt__['file.remove'](temp_file)
loaded_changes['compliance_report'] = compliance_report
return salt.utils.napalm.loaded_ret(ret, loaded_changes, test, debug, opts=__opts__, compliance_report=return_compliance_report) | Manage the device configuration given the input data structured
according to the YANG models.
data
YANG structured data.
models
A list of models to be used when generating the config.
profiles: ``None``
Use certain profiles to generate the config.
If not specified, will use the platform default profile(s).
compliance_report: ``False``
Return the compliance report in the comment.
.. versionadded:: 2017.7.3
test: ``False``
Dry run? If set as ``True``, will apply the config, discard
and return the changes. Default: ``False`` and will commit
the changes on the device.
commit: ``True``
Commit? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key under the output dictionary,
as ``loaded_config`` containing the raw configuration loaded on the device.
replace: ``False``
Should replace the config with the new generate one?
State SLS example:
.. code-block:: jinja
{%- set expected_config = pillar.get('openconfig_interfaces_cfg') -%}
interfaces_config:
napalm_yang.managed:
- data: {{ expected_config | json }}
- models:
- models.openconfig_interfaces
- debug: true
Pillar example:
.. code-block:: yaml
openconfig_interfaces_cfg:
_kwargs:
filter: true
interfaces:
interface:
Et1:
config:
mtu: 9000
Et2:
config:
description: "description example" | salt/states/net_napalm_yang.py | managed | Flowdalic/salt | 9,425 | python | def managed(name, data, **kwargs):
'\n Manage the device configuration given the input data structured\n according to the YANG models.\n\n data\n YANG structured data.\n\n models\n A list of models to be used when generating the config.\n\n profiles: ``None``\n Use certain profiles to generate the config.\n If not specified, will use the platform default profile(s).\n\n compliance_report: ``False``\n Return the compliance report in the comment.\n\n .. versionadded:: 2017.7.3\n\n test: ``False``\n Dry run? If set as ``True``, will apply the config, discard\n and return the changes. Default: ``False`` and will commit\n the changes on the device.\n\n commit: ``True``\n Commit? Default: ``True``.\n\n debug: ``False``\n Debug mode. Will insert a new key under the output dictionary,\n as ``loaded_config`` containing the raw configuration loaded on the device.\n\n replace: ``False``\n Should replace the config with the new generate one?\n\n State SLS example:\n\n .. code-block:: jinja\n\n {%- set expected_config = pillar.get(\'openconfig_interfaces_cfg\') -%}\n interfaces_config:\n napalm_yang.managed:\n - data: {{ expected_config | json }}\n - models:\n - models.openconfig_interfaces\n - debug: true\n\n Pillar example:\n\n .. code-block:: yaml\n\n openconfig_interfaces_cfg:\n _kwargs:\n filter: true\n interfaces:\n interface:\n Et1:\n config:\n mtu: 9000\n Et2:\n config:\n description: "description example"\n '
models = kwargs.get('models', None)
if (isinstance(models, tuple) and isinstance(models[0], list)):
models = models[0]
ret = salt.utils.napalm.default_ret(name)
test = (kwargs.get('test', False) or __opts__.get('test', False))
debug = (kwargs.get('debug', False) or __opts__.get('debug', False))
commit = (kwargs.get('commit', True) or __opts__.get('commit', True))
replace = (kwargs.get('replace', False) or __opts__.get('replace', False))
return_compliance_report = (kwargs.get('compliance_report', False) or __opts__.get('compliance_report', False))
profiles = kwargs.get('profiles', [])
temp_file = __salt__['temp.file']()
log.debug('Creating temp file: %s', temp_file)
if ('to_dict' not in data):
data = {'to_dict': data}
data = [data]
with salt.utils.files.fopen(temp_file, 'w') as file_handle:
salt.utils.yaml.safe_dump(salt.utils.json.loads(salt.utils.json.dumps(data)), file_handle, encoding='utf-8')
device_config = __salt__['napalm_yang.parse'](*models, config=True, profiles=profiles)
log.debug('Parsed the config from the device:')
log.debug(device_config)
compliance_report = __salt__['napalm_yang.compliance_report'](device_config, *models, filepath=temp_file)
log.debug('Compliance report:')
log.debug(compliance_report)
complies = compliance_report.get('complies', False)
if complies:
ret.update({'result': True, 'comment': 'Already configured as required.'})
log.debug('All good here.')
return ret
log.debug('Does not comply, trying to generate and load config')
data = data[0]['to_dict']
if ('_kwargs' in data):
data.pop('_kwargs')
loaded_changes = __salt__['napalm_yang.load_config'](data, *models, profiles=profiles, test=test, debug=debug, commit=commit, replace=replace)
log.debug('Loaded config result:')
log.debug(loaded_changes)
__salt__['file.remove'](temp_file)
loaded_changes['compliance_report'] = compliance_report
return salt.utils.napalm.loaded_ret(ret, loaded_changes, test, debug, opts=__opts__, compliance_report=return_compliance_report) | def managed(name, data, **kwargs):
'\n Manage the device configuration given the input data structured\n according to the YANG models.\n\n data\n YANG structured data.\n\n models\n A list of models to be used when generating the config.\n\n profiles: ``None``\n Use certain profiles to generate the config.\n If not specified, will use the platform default profile(s).\n\n compliance_report: ``False``\n Return the compliance report in the comment.\n\n .. versionadded:: 2017.7.3\n\n test: ``False``\n Dry run? If set as ``True``, will apply the config, discard\n and return the changes. Default: ``False`` and will commit\n the changes on the device.\n\n commit: ``True``\n Commit? Default: ``True``.\n\n debug: ``False``\n Debug mode. Will insert a new key under the output dictionary,\n as ``loaded_config`` containing the raw configuration loaded on the device.\n\n replace: ``False``\n Should replace the config with the new generate one?\n\n State SLS example:\n\n .. code-block:: jinja\n\n {%- set expected_config = pillar.get(\'openconfig_interfaces_cfg\') -%}\n interfaces_config:\n napalm_yang.managed:\n - data: {{ expected_config | json }}\n - models:\n - models.openconfig_interfaces\n - debug: true\n\n Pillar example:\n\n .. code-block:: yaml\n\n openconfig_interfaces_cfg:\n _kwargs:\n filter: true\n interfaces:\n interface:\n Et1:\n config:\n mtu: 9000\n Et2:\n config:\n description: "description example"\n '
models = kwargs.get('models', None)
if (isinstance(models, tuple) and isinstance(models[0], list)):
models = models[0]
ret = salt.utils.napalm.default_ret(name)
test = (kwargs.get('test', False) or __opts__.get('test', False))
debug = (kwargs.get('debug', False) or __opts__.get('debug', False))
commit = (kwargs.get('commit', True) or __opts__.get('commit', True))
replace = (kwargs.get('replace', False) or __opts__.get('replace', False))
return_compliance_report = (kwargs.get('compliance_report', False) or __opts__.get('compliance_report', False))
profiles = kwargs.get('profiles', [])
temp_file = __salt__['temp.file']()
log.debug('Creating temp file: %s', temp_file)
if ('to_dict' not in data):
data = {'to_dict': data}
data = [data]
with salt.utils.files.fopen(temp_file, 'w') as file_handle:
salt.utils.yaml.safe_dump(salt.utils.json.loads(salt.utils.json.dumps(data)), file_handle, encoding='utf-8')
device_config = __salt__['napalm_yang.parse'](*models, config=True, profiles=profiles)
log.debug('Parsed the config from the device:')
log.debug(device_config)
compliance_report = __salt__['napalm_yang.compliance_report'](device_config, *models, filepath=temp_file)
log.debug('Compliance report:')
log.debug(compliance_report)
complies = compliance_report.get('complies', False)
if complies:
ret.update({'result': True, 'comment': 'Already configured as required.'})
log.debug('All good here.')
return ret
log.debug('Does not comply, trying to generate and load config')
data = data[0]['to_dict']
if ('_kwargs' in data):
data.pop('_kwargs')
loaded_changes = __salt__['napalm_yang.load_config'](data, *models, profiles=profiles, test=test, debug=debug, commit=commit, replace=replace)
log.debug('Loaded config result:')
log.debug(loaded_changes)
__salt__['file.remove'](temp_file)
loaded_changes['compliance_report'] = compliance_report
return salt.utils.napalm.loaded_ret(ret, loaded_changes, test, debug, opts=__opts__, compliance_report=return_compliance_report)<|docstring|>Manage the device configuration given the input data structured
according to the YANG models.
data
YANG structured data.
models
A list of models to be used when generating the config.
profiles: ``None``
Use certain profiles to generate the config.
If not specified, will use the platform default profile(s).
compliance_report: ``False``
Return the compliance report in the comment.
.. versionadded:: 2017.7.3
test: ``False``
Dry run? If set as ``True``, will apply the config, discard
and return the changes. Default: ``False`` and will commit
the changes on the device.
commit: ``True``
Commit? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key under the output dictionary,
as ``loaded_config`` containing the raw configuration loaded on the device.
replace: ``False``
Should replace the config with the new generate one?
State SLS example:
.. code-block:: jinja
{%- set expected_config = pillar.get('openconfig_interfaces_cfg') -%}
interfaces_config:
napalm_yang.managed:
- data: {{ expected_config | json }}
- models:
- models.openconfig_interfaces
- debug: true
Pillar example:
.. code-block:: yaml
openconfig_interfaces_cfg:
_kwargs:
filter: true
interfaces:
interface:
Et1:
config:
mtu: 9000
Et2:
config:
description: "description example"<|endoftext|> |
0827720a17564e0668cfb96095ff1b749df591a849a23b4f7419dc7b0ac86d43 | def configured(name, data, **kwargs):
'\n Configure the network device, given the input data strucuted\n according to the YANG models.\n\n .. note::\n The main difference between this function and ``managed``\n is that the later generates and loads the configuration\n only when there are differences between the existing\n configuration on the device and the expected\n configuration. Depending on the platform and hardware\n capabilities, one could be more optimal than the other.\n Additionally, the output of the ``managed`` is different,\n in such a way that the ``pchange`` field in the output\n contains structured data, rather than text.\n\n data\n YANG structured data.\n\n models\n A list of models to be used when generating the config.\n\n profiles: ``None``\n Use certain profiles to generate the config.\n If not specified, will use the platform default profile(s).\n\n test: ``False``\n Dry run? If set as ``True``, will apply the config, discard\n and return the changes. Default: ``False`` and will commit\n the changes on the device.\n\n commit: ``True``\n Commit? Default: ``True``.\n\n debug: ``False``\n Debug mode. Will insert a new key under the output dictionary,\n as ``loaded_config`` containing the raw configuration loaded on the device.\n\n replace: ``False``\n Should replace the config with the new generate one?\n\n State SLS example:\n\n .. code-block:: jinja\n\n {%- set expected_config = pillar.get(\'openconfig_interfaces_cfg\') -%}\n interfaces_config:\n napalm_yang.configured:\n - data: {{ expected_config | json }}\n - models:\n - models.openconfig_interfaces\n - debug: true\n\n Pillar example:\n\n .. code-block:: yaml\n\n openconfig_interfaces_cfg:\n _kwargs:\n filter: true\n interfaces:\n interface:\n Et1:\n config:\n mtu: 9000\n Et2:\n config:\n description: "description example"\n '
models = kwargs.get('models', None)
if (isinstance(models, tuple) and isinstance(models[0], list)):
models = models[0]
ret = salt.utils.napalm.default_ret(name)
test = (kwargs.get('test', False) or __opts__.get('test', False))
debug = (kwargs.get('debug', False) or __opts__.get('debug', False))
commit = (kwargs.get('commit', True) or __opts__.get('commit', True))
replace = (kwargs.get('replace', False) or __opts__.get('replace', False))
profiles = kwargs.get('profiles', [])
if ('_kwargs' in data):
data.pop('_kwargs')
loaded_changes = __salt__['napalm_yang.load_config'](data, *models, profiles=profiles, test=test, debug=debug, commit=commit, replace=replace)
return salt.utils.napalm.loaded_ret(ret, loaded_changes, test, debug) | Configure the network device, given the input data strucuted
according to the YANG models.
.. note::
The main difference between this function and ``managed``
is that the later generates and loads the configuration
only when there are differences between the existing
configuration on the device and the expected
configuration. Depending on the platform and hardware
capabilities, one could be more optimal than the other.
Additionally, the output of the ``managed`` is different,
in such a way that the ``pchange`` field in the output
contains structured data, rather than text.
data
YANG structured data.
models
A list of models to be used when generating the config.
profiles: ``None``
Use certain profiles to generate the config.
If not specified, will use the platform default profile(s).
test: ``False``
Dry run? If set as ``True``, will apply the config, discard
and return the changes. Default: ``False`` and will commit
the changes on the device.
commit: ``True``
Commit? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key under the output dictionary,
as ``loaded_config`` containing the raw configuration loaded on the device.
replace: ``False``
Should replace the config with the new generate one?
State SLS example:
.. code-block:: jinja
{%- set expected_config = pillar.get('openconfig_interfaces_cfg') -%}
interfaces_config:
napalm_yang.configured:
- data: {{ expected_config | json }}
- models:
- models.openconfig_interfaces
- debug: true
Pillar example:
.. code-block:: yaml
openconfig_interfaces_cfg:
_kwargs:
filter: true
interfaces:
interface:
Et1:
config:
mtu: 9000
Et2:
config:
description: "description example" | salt/states/net_napalm_yang.py | configured | Flowdalic/salt | 9,425 | python | def configured(name, data, **kwargs):
'\n Configure the network device, given the input data strucuted\n according to the YANG models.\n\n .. note::\n The main difference between this function and ``managed``\n is that the later generates and loads the configuration\n only when there are differences between the existing\n configuration on the device and the expected\n configuration. Depending on the platform and hardware\n capabilities, one could be more optimal than the other.\n Additionally, the output of the ``managed`` is different,\n in such a way that the ``pchange`` field in the output\n contains structured data, rather than text.\n\n data\n YANG structured data.\n\n models\n A list of models to be used when generating the config.\n\n profiles: ``None``\n Use certain profiles to generate the config.\n If not specified, will use the platform default profile(s).\n\n test: ``False``\n Dry run? If set as ``True``, will apply the config, discard\n and return the changes. Default: ``False`` and will commit\n the changes on the device.\n\n commit: ``True``\n Commit? Default: ``True``.\n\n debug: ``False``\n Debug mode. Will insert a new key under the output dictionary,\n as ``loaded_config`` containing the raw configuration loaded on the device.\n\n replace: ``False``\n Should replace the config with the new generate one?\n\n State SLS example:\n\n .. code-block:: jinja\n\n {%- set expected_config = pillar.get(\'openconfig_interfaces_cfg\') -%}\n interfaces_config:\n napalm_yang.configured:\n - data: {{ expected_config | json }}\n - models:\n - models.openconfig_interfaces\n - debug: true\n\n Pillar example:\n\n .. code-block:: yaml\n\n openconfig_interfaces_cfg:\n _kwargs:\n filter: true\n interfaces:\n interface:\n Et1:\n config:\n mtu: 9000\n Et2:\n config:\n description: "description example"\n '
models = kwargs.get('models', None)
if (isinstance(models, tuple) and isinstance(models[0], list)):
models = models[0]
ret = salt.utils.napalm.default_ret(name)
test = (kwargs.get('test', False) or __opts__.get('test', False))
debug = (kwargs.get('debug', False) or __opts__.get('debug', False))
commit = (kwargs.get('commit', True) or __opts__.get('commit', True))
replace = (kwargs.get('replace', False) or __opts__.get('replace', False))
profiles = kwargs.get('profiles', [])
if ('_kwargs' in data):
data.pop('_kwargs')
loaded_changes = __salt__['napalm_yang.load_config'](data, *models, profiles=profiles, test=test, debug=debug, commit=commit, replace=replace)
return salt.utils.napalm.loaded_ret(ret, loaded_changes, test, debug) | def configured(name, data, **kwargs):
'\n Configure the network device, given the input data strucuted\n according to the YANG models.\n\n .. note::\n The main difference between this function and ``managed``\n is that the later generates and loads the configuration\n only when there are differences between the existing\n configuration on the device and the expected\n configuration. Depending on the platform and hardware\n capabilities, one could be more optimal than the other.\n Additionally, the output of the ``managed`` is different,\n in such a way that the ``pchange`` field in the output\n contains structured data, rather than text.\n\n data\n YANG structured data.\n\n models\n A list of models to be used when generating the config.\n\n profiles: ``None``\n Use certain profiles to generate the config.\n If not specified, will use the platform default profile(s).\n\n test: ``False``\n Dry run? If set as ``True``, will apply the config, discard\n and return the changes. Default: ``False`` and will commit\n the changes on the device.\n\n commit: ``True``\n Commit? Default: ``True``.\n\n debug: ``False``\n Debug mode. Will insert a new key under the output dictionary,\n as ``loaded_config`` containing the raw configuration loaded on the device.\n\n replace: ``False``\n Should replace the config with the new generate one?\n\n State SLS example:\n\n .. code-block:: jinja\n\n {%- set expected_config = pillar.get(\'openconfig_interfaces_cfg\') -%}\n interfaces_config:\n napalm_yang.configured:\n - data: {{ expected_config | json }}\n - models:\n - models.openconfig_interfaces\n - debug: true\n\n Pillar example:\n\n .. code-block:: yaml\n\n openconfig_interfaces_cfg:\n _kwargs:\n filter: true\n interfaces:\n interface:\n Et1:\n config:\n mtu: 9000\n Et2:\n config:\n description: "description example"\n '
models = kwargs.get('models', None)
if (isinstance(models, tuple) and isinstance(models[0], list)):
models = models[0]
ret = salt.utils.napalm.default_ret(name)
test = (kwargs.get('test', False) or __opts__.get('test', False))
debug = (kwargs.get('debug', False) or __opts__.get('debug', False))
commit = (kwargs.get('commit', True) or __opts__.get('commit', True))
replace = (kwargs.get('replace', False) or __opts__.get('replace', False))
profiles = kwargs.get('profiles', [])
if ('_kwargs' in data):
data.pop('_kwargs')
loaded_changes = __salt__['napalm_yang.load_config'](data, *models, profiles=profiles, test=test, debug=debug, commit=commit, replace=replace)
return salt.utils.napalm.loaded_ret(ret, loaded_changes, test, debug)<|docstring|>Configure the network device, given the input data strucuted
according to the YANG models.
.. note::
The main difference between this function and ``managed``
is that the later generates and loads the configuration
only when there are differences between the existing
configuration on the device and the expected
configuration. Depending on the platform and hardware
capabilities, one could be more optimal than the other.
Additionally, the output of the ``managed`` is different,
in such a way that the ``pchange`` field in the output
contains structured data, rather than text.
data
YANG structured data.
models
A list of models to be used when generating the config.
profiles: ``None``
Use certain profiles to generate the config.
If not specified, will use the platform default profile(s).
test: ``False``
Dry run? If set as ``True``, will apply the config, discard
and return the changes. Default: ``False`` and will commit
the changes on the device.
commit: ``True``
Commit? Default: ``True``.
debug: ``False``
Debug mode. Will insert a new key under the output dictionary,
as ``loaded_config`` containing the raw configuration loaded on the device.
replace: ``False``
Should replace the config with the new generate one?
State SLS example:
.. code-block:: jinja
{%- set expected_config = pillar.get('openconfig_interfaces_cfg') -%}
interfaces_config:
napalm_yang.configured:
- data: {{ expected_config | json }}
- models:
- models.openconfig_interfaces
- debug: true
Pillar example:
.. code-block:: yaml
openconfig_interfaces_cfg:
_kwargs:
filter: true
interfaces:
interface:
Et1:
config:
mtu: 9000
Et2:
config:
description: "description example"<|endoftext|> |
3b21a16de2e71d81e9063b160c326967ea398d91fc4b5c28744f06e9d1bc882b | def simple_poly_area(x, y):
"Calculates and returns the area of a 2-D simple polygon.\n\n Input vertices must be in sequence (clockwise or counterclockwise). *x*\n and *y* are arrays that give the x- and y-axis coordinates of the\n polygon's vertices.\n\n Parameters\n ----------\n x : ndarray\n x-coordinates of of polygon vertices.\n y : ndarray\n y-coordinates of of polygon vertices.\n\n Returns\n -------\n out : float\n Area of the polygon\n\n Examples\n --------\n >>> import numpy as np\n >>> from landlab.grid.voronoi import simple_poly_area\n >>> x = np.array([3., 1., 1., 3.])\n >>> y = np.array([1.5, 1.5, 0.5, 0.5])\n >>> simple_poly_area(x, y)\n 2.0\n\n If the input coordinate arrays are 2D, calculate the area of each polygon.\n Note that when used in this mode, all polygons must have the same\n number of vertices, and polygon vertices are listed column-by-column.\n\n >>> x = np.array([[ 3., 1., 1., 3.],\n ... [-2., -2., -1., -1.]]).T\n >>> y = np.array([[1.5, 1.5, 0.5, 0.5],\n ... [ 0., 1., 2., 0.]]).T\n >>> simple_poly_area(x, y)\n array([ 2. , 1.5])\n "
return (0.5 * abs(((sum(((x[:(- 1)] * y[1:]) - (x[1:] * y[:(- 1)]))) + (x[(- 1)] * y[0])) - (x[0] * y[(- 1)])))) | Calculates and returns the area of a 2-D simple polygon.
Input vertices must be in sequence (clockwise or counterclockwise). *x*
and *y* are arrays that give the x- and y-axis coordinates of the
polygon's vertices.
Parameters
----------
x : ndarray
x-coordinates of of polygon vertices.
y : ndarray
y-coordinates of of polygon vertices.
Returns
-------
out : float
Area of the polygon
Examples
--------
>>> import numpy as np
>>> from landlab.grid.voronoi import simple_poly_area
>>> x = np.array([3., 1., 1., 3.])
>>> y = np.array([1.5, 1.5, 0.5, 0.5])
>>> simple_poly_area(x, y)
2.0
If the input coordinate arrays are 2D, calculate the area of each polygon.
Note that when used in this mode, all polygons must have the same
number of vertices, and polygon vertices are listed column-by-column.
>>> x = np.array([[ 3., 1., 1., 3.],
... [-2., -2., -1., -1.]]).T
>>> y = np.array([[1.5, 1.5, 0.5, 0.5],
... [ 0., 1., 2., 0.]]).T
>>> simple_poly_area(x, y)
array([ 2. , 1.5]) | landlab/grid/voronoi.py | simple_poly_area | amandersillinois/landlab | 257 | python | def simple_poly_area(x, y):
"Calculates and returns the area of a 2-D simple polygon.\n\n Input vertices must be in sequence (clockwise or counterclockwise). *x*\n and *y* are arrays that give the x- and y-axis coordinates of the\n polygon's vertices.\n\n Parameters\n ----------\n x : ndarray\n x-coordinates of of polygon vertices.\n y : ndarray\n y-coordinates of of polygon vertices.\n\n Returns\n -------\n out : float\n Area of the polygon\n\n Examples\n --------\n >>> import numpy as np\n >>> from landlab.grid.voronoi import simple_poly_area\n >>> x = np.array([3., 1., 1., 3.])\n >>> y = np.array([1.5, 1.5, 0.5, 0.5])\n >>> simple_poly_area(x, y)\n 2.0\n\n If the input coordinate arrays are 2D, calculate the area of each polygon.\n Note that when used in this mode, all polygons must have the same\n number of vertices, and polygon vertices are listed column-by-column.\n\n >>> x = np.array([[ 3., 1., 1., 3.],\n ... [-2., -2., -1., -1.]]).T\n >>> y = np.array([[1.5, 1.5, 0.5, 0.5],\n ... [ 0., 1., 2., 0.]]).T\n >>> simple_poly_area(x, y)\n array([ 2. , 1.5])\n "
return (0.5 * abs(((sum(((x[:(- 1)] * y[1:]) - (x[1:] * y[:(- 1)]))) + (x[(- 1)] * y[0])) - (x[0] * y[(- 1)])))) | def simple_poly_area(x, y):
"Calculates and returns the area of a 2-D simple polygon.\n\n Input vertices must be in sequence (clockwise or counterclockwise). *x*\n and *y* are arrays that give the x- and y-axis coordinates of the\n polygon's vertices.\n\n Parameters\n ----------\n x : ndarray\n x-coordinates of of polygon vertices.\n y : ndarray\n y-coordinates of of polygon vertices.\n\n Returns\n -------\n out : float\n Area of the polygon\n\n Examples\n --------\n >>> import numpy as np\n >>> from landlab.grid.voronoi import simple_poly_area\n >>> x = np.array([3., 1., 1., 3.])\n >>> y = np.array([1.5, 1.5, 0.5, 0.5])\n >>> simple_poly_area(x, y)\n 2.0\n\n If the input coordinate arrays are 2D, calculate the area of each polygon.\n Note that when used in this mode, all polygons must have the same\n number of vertices, and polygon vertices are listed column-by-column.\n\n >>> x = np.array([[ 3., 1., 1., 3.],\n ... [-2., -2., -1., -1.]]).T\n >>> y = np.array([[1.5, 1.5, 0.5, 0.5],\n ... [ 0., 1., 2., 0.]]).T\n >>> simple_poly_area(x, y)\n array([ 2. , 1.5])\n "
return (0.5 * abs(((sum(((x[:(- 1)] * y[1:]) - (x[1:] * y[:(- 1)]))) + (x[(- 1)] * y[0])) - (x[0] * y[(- 1)]))))<|docstring|>Calculates and returns the area of a 2-D simple polygon.
Input vertices must be in sequence (clockwise or counterclockwise). *x*
and *y* are arrays that give the x- and y-axis coordinates of the
polygon's vertices.
Parameters
----------
x : ndarray
x-coordinates of of polygon vertices.
y : ndarray
y-coordinates of of polygon vertices.
Returns
-------
out : float
Area of the polygon
Examples
--------
>>> import numpy as np
>>> from landlab.grid.voronoi import simple_poly_area
>>> x = np.array([3., 1., 1., 3.])
>>> y = np.array([1.5, 1.5, 0.5, 0.5])
>>> simple_poly_area(x, y)
2.0
If the input coordinate arrays are 2D, calculate the area of each polygon.
Note that when used in this mode, all polygons must have the same
number of vertices, and polygon vertices are listed column-by-column.
>>> x = np.array([[ 3., 1., 1., 3.],
... [-2., -2., -1., -1.]]).T
>>> y = np.array([[1.5, 1.5, 0.5, 0.5],
... [ 0., 1., 2., 0.]]).T
>>> simple_poly_area(x, y)
array([ 2. , 1.5])<|endoftext|> |
1dcb5ad8314d9e8769547b32ae036ae0a74b70519e28e27f37b6da32847c60a5 | def __init__(self, x=None, y=None, reorient_links=True, xy_of_reference=(0.0, 0.0), xy_axis_name=('x', 'y'), xy_axis_units='-'):
'Create a Voronoi Delaunay grid from a set of points.\n\n Create an unstructured grid from points whose coordinates are given\n by the arrays *x*, *y*.\n\n Parameters\n ----------\n x : array_like\n x-coordinate of points\n y : array_like\n y-coordinate of points\n reorient_links (optional) : bool\n whether to point all links to the upper-right quadrant\n xy_of_reference : tuple, optional\n Coordinate value in projected space of (0., 0.)\n Default is (0., 0.)\n\n Returns\n -------\n VoronoiDelaunayGrid\n A newly-created grid.\n\n Examples\n --------\n >>> from numpy.random import rand\n >>> from landlab.grid import VoronoiDelaunayGrid\n >>> x, y = rand(25), rand(25)\n >>> vmg = VoronoiDelaunayGrid(x, y) # node_x_coords, node_y_coords\n >>> vmg.number_of_nodes\n 25\n '
DualVoronoiGraph.__init__(self, (y, x), sort=True)
ModelGrid.__init__(self, xy_axis_name=xy_axis_name, xy_axis_units=xy_axis_units, xy_of_reference=xy_of_reference)
self._node_status = np.full(self.number_of_nodes, self.BC_NODE_IS_CORE, dtype=np.uint8)
self._node_status[self.perimeter_nodes] = self.BC_NODE_IS_FIXED_VALUE | Create a Voronoi Delaunay grid from a set of points.
Create an unstructured grid from points whose coordinates are given
by the arrays *x*, *y*.
Parameters
----------
x : array_like
x-coordinate of points
y : array_like
y-coordinate of points
reorient_links (optional) : bool
whether to point all links to the upper-right quadrant
xy_of_reference : tuple, optional
Coordinate value in projected space of (0., 0.)
Default is (0., 0.)
Returns
-------
VoronoiDelaunayGrid
A newly-created grid.
Examples
--------
>>> from numpy.random import rand
>>> from landlab.grid import VoronoiDelaunayGrid
>>> x, y = rand(25), rand(25)
>>> vmg = VoronoiDelaunayGrid(x, y) # node_x_coords, node_y_coords
>>> vmg.number_of_nodes
25 | landlab/grid/voronoi.py | __init__ | amandersillinois/landlab | 257 | python | def __init__(self, x=None, y=None, reorient_links=True, xy_of_reference=(0.0, 0.0), xy_axis_name=('x', 'y'), xy_axis_units='-'):
'Create a Voronoi Delaunay grid from a set of points.\n\n Create an unstructured grid from points whose coordinates are given\n by the arrays *x*, *y*.\n\n Parameters\n ----------\n x : array_like\n x-coordinate of points\n y : array_like\n y-coordinate of points\n reorient_links (optional) : bool\n whether to point all links to the upper-right quadrant\n xy_of_reference : tuple, optional\n Coordinate value in projected space of (0., 0.)\n Default is (0., 0.)\n\n Returns\n -------\n VoronoiDelaunayGrid\n A newly-created grid.\n\n Examples\n --------\n >>> from numpy.random import rand\n >>> from landlab.grid import VoronoiDelaunayGrid\n >>> x, y = rand(25), rand(25)\n >>> vmg = VoronoiDelaunayGrid(x, y) # node_x_coords, node_y_coords\n >>> vmg.number_of_nodes\n 25\n '
DualVoronoiGraph.__init__(self, (y, x), sort=True)
ModelGrid.__init__(self, xy_axis_name=xy_axis_name, xy_axis_units=xy_axis_units, xy_of_reference=xy_of_reference)
self._node_status = np.full(self.number_of_nodes, self.BC_NODE_IS_CORE, dtype=np.uint8)
self._node_status[self.perimeter_nodes] = self.BC_NODE_IS_FIXED_VALUE | def __init__(self, x=None, y=None, reorient_links=True, xy_of_reference=(0.0, 0.0), xy_axis_name=('x', 'y'), xy_axis_units='-'):
'Create a Voronoi Delaunay grid from a set of points.\n\n Create an unstructured grid from points whose coordinates are given\n by the arrays *x*, *y*.\n\n Parameters\n ----------\n x : array_like\n x-coordinate of points\n y : array_like\n y-coordinate of points\n reorient_links (optional) : bool\n whether to point all links to the upper-right quadrant\n xy_of_reference : tuple, optional\n Coordinate value in projected space of (0., 0.)\n Default is (0., 0.)\n\n Returns\n -------\n VoronoiDelaunayGrid\n A newly-created grid.\n\n Examples\n --------\n >>> from numpy.random import rand\n >>> from landlab.grid import VoronoiDelaunayGrid\n >>> x, y = rand(25), rand(25)\n >>> vmg = VoronoiDelaunayGrid(x, y) # node_x_coords, node_y_coords\n >>> vmg.number_of_nodes\n 25\n '
DualVoronoiGraph.__init__(self, (y, x), sort=True)
ModelGrid.__init__(self, xy_axis_name=xy_axis_name, xy_axis_units=xy_axis_units, xy_of_reference=xy_of_reference)
self._node_status = np.full(self.number_of_nodes, self.BC_NODE_IS_CORE, dtype=np.uint8)
self._node_status[self.perimeter_nodes] = self.BC_NODE_IS_FIXED_VALUE<|docstring|>Create a Voronoi Delaunay grid from a set of points.
Create an unstructured grid from points whose coordinates are given
by the arrays *x*, *y*.
Parameters
----------
x : array_like
x-coordinate of points
y : array_like
y-coordinate of points
reorient_links (optional) : bool
whether to point all links to the upper-right quadrant
xy_of_reference : tuple, optional
Coordinate value in projected space of (0., 0.)
Default is (0., 0.)
Returns
-------
VoronoiDelaunayGrid
A newly-created grid.
Examples
--------
>>> from numpy.random import rand
>>> from landlab.grid import VoronoiDelaunayGrid
>>> x, y = rand(25), rand(25)
>>> vmg = VoronoiDelaunayGrid(x, y) # node_x_coords, node_y_coords
>>> vmg.number_of_nodes
25<|endoftext|> |
ec958f17e4184553941b9affe80be7a25062ebdbbb4e28a36aa6958f3bdc8244 | def save(self, path, clobber=False):
"Save a grid and fields.\n\n This method uses pickle to save a Voronoi grid as a pickle file.\n At the time of coding, this is the only convenient output format\n for Voronoi grids, but support for netCDF is likely coming.\n\n All fields will be saved, along with the grid.\n\n The recommended suffix for the save file is '.grid'. This will\n be added to your save if you don't include it.\n\n This method is equivalent to\n :py:func:`~landlab.io.native_landlab.save_grid`, and\n :py:func:`~landlab.io.native_landlab.load_grid` can be used to\n load these files.\n\n Caution: Pickling can be slow, and can produce very large files.\n Caution 2: Future updates to Landlab could potentially render old\n saves unloadable.\n\n Parameters\n ----------\n path : str\n Path to output file.\n clobber : bool (defaults to false)\n Set to true to allow overwriting\n\n Examples\n --------\n >>> from landlab import VoronoiDelaunayGrid\n >>> import numpy as np\n >>> import os\n >>> x = np.random.rand(20)\n >>> y = np.random.rand(20)\n >>> vmg = VoronoiDelaunayGrid(x,y)\n >>> vmg.save('./mytestsave.grid')\n >>> os.remove('mytestsave.grid') #to remove traces of this test\n\n LLCATS: GINF\n "
import os
import pickle
if (os.path.exists(path) and (not clobber)):
raise ValueError('file exists')
(base, ext) = os.path.splitext(path)
if (ext != '.grid'):
ext = (ext + '.grid')
path = (base + ext)
with open(path, 'wb') as fp:
pickle.dump(self, fp) | Save a grid and fields.
This method uses pickle to save a Voronoi grid as a pickle file.
At the time of coding, this is the only convenient output format
for Voronoi grids, but support for netCDF is likely coming.
All fields will be saved, along with the grid.
The recommended suffix for the save file is '.grid'. This will
be added to your save if you don't include it.
This method is equivalent to
:py:func:`~landlab.io.native_landlab.save_grid`, and
:py:func:`~landlab.io.native_landlab.load_grid` can be used to
load these files.
Caution: Pickling can be slow, and can produce very large files.
Caution 2: Future updates to Landlab could potentially render old
saves unloadable.
Parameters
----------
path : str
Path to output file.
clobber : bool (defaults to false)
Set to true to allow overwriting
Examples
--------
>>> from landlab import VoronoiDelaunayGrid
>>> import numpy as np
>>> import os
>>> x = np.random.rand(20)
>>> y = np.random.rand(20)
>>> vmg = VoronoiDelaunayGrid(x,y)
>>> vmg.save('./mytestsave.grid')
>>> os.remove('mytestsave.grid') #to remove traces of this test
LLCATS: GINF | landlab/grid/voronoi.py | save | amandersillinois/landlab | 257 | python | def save(self, path, clobber=False):
"Save a grid and fields.\n\n This method uses pickle to save a Voronoi grid as a pickle file.\n At the time of coding, this is the only convenient output format\n for Voronoi grids, but support for netCDF is likely coming.\n\n All fields will be saved, along with the grid.\n\n The recommended suffix for the save file is '.grid'. This will\n be added to your save if you don't include it.\n\n This method is equivalent to\n :py:func:`~landlab.io.native_landlab.save_grid`, and\n :py:func:`~landlab.io.native_landlab.load_grid` can be used to\n load these files.\n\n Caution: Pickling can be slow, and can produce very large files.\n Caution 2: Future updates to Landlab could potentially render old\n saves unloadable.\n\n Parameters\n ----------\n path : str\n Path to output file.\n clobber : bool (defaults to false)\n Set to true to allow overwriting\n\n Examples\n --------\n >>> from landlab import VoronoiDelaunayGrid\n >>> import numpy as np\n >>> import os\n >>> x = np.random.rand(20)\n >>> y = np.random.rand(20)\n >>> vmg = VoronoiDelaunayGrid(x,y)\n >>> vmg.save('./mytestsave.grid')\n >>> os.remove('mytestsave.grid') #to remove traces of this test\n\n LLCATS: GINF\n "
import os
import pickle
if (os.path.exists(path) and (not clobber)):
raise ValueError('file exists')
(base, ext) = os.path.splitext(path)
if (ext != '.grid'):
ext = (ext + '.grid')
path = (base + ext)
with open(path, 'wb') as fp:
pickle.dump(self, fp) | def save(self, path, clobber=False):
"Save a grid and fields.\n\n This method uses pickle to save a Voronoi grid as a pickle file.\n At the time of coding, this is the only convenient output format\n for Voronoi grids, but support for netCDF is likely coming.\n\n All fields will be saved, along with the grid.\n\n The recommended suffix for the save file is '.grid'. This will\n be added to your save if you don't include it.\n\n This method is equivalent to\n :py:func:`~landlab.io.native_landlab.save_grid`, and\n :py:func:`~landlab.io.native_landlab.load_grid` can be used to\n load these files.\n\n Caution: Pickling can be slow, and can produce very large files.\n Caution 2: Future updates to Landlab could potentially render old\n saves unloadable.\n\n Parameters\n ----------\n path : str\n Path to output file.\n clobber : bool (defaults to false)\n Set to true to allow overwriting\n\n Examples\n --------\n >>> from landlab import VoronoiDelaunayGrid\n >>> import numpy as np\n >>> import os\n >>> x = np.random.rand(20)\n >>> y = np.random.rand(20)\n >>> vmg = VoronoiDelaunayGrid(x,y)\n >>> vmg.save('./mytestsave.grid')\n >>> os.remove('mytestsave.grid') #to remove traces of this test\n\n LLCATS: GINF\n "
import os
import pickle
if (os.path.exists(path) and (not clobber)):
raise ValueError('file exists')
(base, ext) = os.path.splitext(path)
if (ext != '.grid'):
ext = (ext + '.grid')
path = (base + ext)
with open(path, 'wb') as fp:
pickle.dump(self, fp)<|docstring|>Save a grid and fields.
This method uses pickle to save a Voronoi grid as a pickle file.
At the time of coding, this is the only convenient output format
for Voronoi grids, but support for netCDF is likely coming.
All fields will be saved, along with the grid.
The recommended suffix for the save file is '.grid'. This will
be added to your save if you don't include it.
This method is equivalent to
:py:func:`~landlab.io.native_landlab.save_grid`, and
:py:func:`~landlab.io.native_landlab.load_grid` can be used to
load these files.
Caution: Pickling can be slow, and can produce very large files.
Caution 2: Future updates to Landlab could potentially render old
saves unloadable.
Parameters
----------
path : str
Path to output file.
clobber : bool (defaults to false)
Set to true to allow overwriting
Examples
--------
>>> from landlab import VoronoiDelaunayGrid
>>> import numpy as np
>>> import os
>>> x = np.random.rand(20)
>>> y = np.random.rand(20)
>>> vmg = VoronoiDelaunayGrid(x,y)
>>> vmg.save('./mytestsave.grid')
>>> os.remove('mytestsave.grid') #to remove traces of this test
LLCATS: GINF<|endoftext|> |
02083db93b642b8cd40fb797e2a199e019bdb52aef5317c6cb2c6eaa64770365 | def test_varimax_python():
'Test varimax rotation python implementation'
in_comps = np.eye(TEST_DIM)
rot = rotation.VarimaxRotatorPython()
rot_comps = rot.rotate(in_comps)
assert np.array_equal(in_comps.dot(rot_comps.T), np.eye(TEST_DIM)) | Test varimax rotation python implementation | tests/test_rotation.py | test_varimax_python | bmcmenamin/fa_k | 22 | python | def test_varimax_python():
in_comps = np.eye(TEST_DIM)
rot = rotation.VarimaxRotatorPython()
rot_comps = rot.rotate(in_comps)
assert np.array_equal(in_comps.dot(rot_comps.T), np.eye(TEST_DIM)) | def test_varimax_python():
in_comps = np.eye(TEST_DIM)
rot = rotation.VarimaxRotatorPython()
rot_comps = rot.rotate(in_comps)
assert np.array_equal(in_comps.dot(rot_comps.T), np.eye(TEST_DIM))<|docstring|>Test varimax rotation python implementation<|endoftext|> |
80511d1d8c3e1b5c13753d8e5853ce3254c442c31e297b30d5ded1ca2814e57d | def test_quartimax_python():
'Test quartimax rotation python implementation'
in_comps = np.eye(TEST_DIM)
rot = rotation.QuartimaxRotatorPython()
rot_comps = rot.rotate(in_comps)
assert np.array_equal(in_comps.dot(rot_comps.T), np.eye(TEST_DIM)) | Test quartimax rotation python implementation | tests/test_rotation.py | test_quartimax_python | bmcmenamin/fa_k | 22 | python | def test_quartimax_python():
in_comps = np.eye(TEST_DIM)
rot = rotation.QuartimaxRotatorPython()
rot_comps = rot.rotate(in_comps)
assert np.array_equal(in_comps.dot(rot_comps.T), np.eye(TEST_DIM)) | def test_quartimax_python():
in_comps = np.eye(TEST_DIM)
rot = rotation.QuartimaxRotatorPython()
rot_comps = rot.rotate(in_comps)
assert np.array_equal(in_comps.dot(rot_comps.T), np.eye(TEST_DIM))<|docstring|>Test quartimax rotation python implementation<|endoftext|> |
1b8a5f9016748be489ea4867837ff66dc8ee04e8192430f0129a4a7eefc153dc | def test_varimax_tf():
'Test varimax rotation TF implementation'
in_comps = np.eye(TEST_DIM)
rot = rotation_tf.VarimaxRotatorTf()
rot_comps = rot.rotate(in_comps)
assert np.array_equal(in_comps.dot(rot_comps.T), np.eye(TEST_DIM)) | Test varimax rotation TF implementation | tests/test_rotation.py | test_varimax_tf | bmcmenamin/fa_k | 22 | python | def test_varimax_tf():
in_comps = np.eye(TEST_DIM)
rot = rotation_tf.VarimaxRotatorTf()
rot_comps = rot.rotate(in_comps)
assert np.array_equal(in_comps.dot(rot_comps.T), np.eye(TEST_DIM)) | def test_varimax_tf():
in_comps = np.eye(TEST_DIM)
rot = rotation_tf.VarimaxRotatorTf()
rot_comps = rot.rotate(in_comps)
assert np.array_equal(in_comps.dot(rot_comps.T), np.eye(TEST_DIM))<|docstring|>Test varimax rotation TF implementation<|endoftext|> |
27596084434cdcea657abdd5984b54373d9898223095f07ab2b23a93189ca6bd | def test_quartimax_tf():
'Test quartimax rotation TF implementation'
in_comps = np.eye(TEST_DIM)
rot = rotation_tf.QuartimaxRotatorTf()
rot_comps = rot.rotate(in_comps)
assert np.array_equal(in_comps.dot(rot_comps.T), np.eye(TEST_DIM)) | Test quartimax rotation TF implementation | tests/test_rotation.py | test_quartimax_tf | bmcmenamin/fa_k | 22 | python | def test_quartimax_tf():
in_comps = np.eye(TEST_DIM)
rot = rotation_tf.QuartimaxRotatorTf()
rot_comps = rot.rotate(in_comps)
assert np.array_equal(in_comps.dot(rot_comps.T), np.eye(TEST_DIM)) | def test_quartimax_tf():
in_comps = np.eye(TEST_DIM)
rot = rotation_tf.QuartimaxRotatorTf()
rot_comps = rot.rotate(in_comps)
assert np.array_equal(in_comps.dot(rot_comps.T), np.eye(TEST_DIM))<|docstring|>Test quartimax rotation TF implementation<|endoftext|> |
0dd1c926d8ba494548d54fd1db586d96cd54cd24f899160c6e425cc9f0979e39 | def plot_one_box(x, img, color=None, label=None, line_thickness=None):
'\n description: Plots one bounding box on image img,\n this function comes from YoLov5 project.\n param: \n x: a box likes [x1,y1,x2,y2]\n img: a opencv image object\n color: color to draw rectangle, such as (0,255,0)\n label: str\n line_thickness: int\n return:\n no return\n\n '
tl = (line_thickness or (round(((0.002 * (img.shape[0] + img.shape[1])) / 2)) + 1))
color = (color or [random.randint(0, 255) for _ in range(3)])
(c1, c2) = ((int(x[0]), int(x[1])), (int(x[2]), int(x[3])))
cv2.rectangle(img, c1, c2, color, thickness=tl, lineType=cv2.LINE_AA)
if label:
tf = max((tl - 1), 1)
t_size = cv2.getTextSize(label, 0, fontScale=(tl / 3), thickness=tf)[0]
c2 = ((c1[0] + t_size[0]), ((c1[1] - t_size[1]) - 3))
cv2.rectangle(img, c1, c2, color, (- 1), cv2.LINE_AA)
cv2.putText(img, label, (c1[0], (c1[1] - 2)), 0, (tl / 3), [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA) | description: Plots one bounding box on image img,
this function comes from YoLov5 project.
param:
x: a box likes [x1,y1,x2,y2]
img: a opencv image object
color: color to draw rectangle, such as (0,255,0)
label: str
line_thickness: int
return:
no return | PytorchToTensorRTGIE/yolov5_trt.py | plot_one_box | ZhangwenguangHikvision/YoloV5_JDE_TensorRT_for_Track | 44 | python | def plot_one_box(x, img, color=None, label=None, line_thickness=None):
'\n description: Plots one bounding box on image img,\n this function comes from YoLov5 project.\n param: \n x: a box likes [x1,y1,x2,y2]\n img: a opencv image object\n color: color to draw rectangle, such as (0,255,0)\n label: str\n line_thickness: int\n return:\n no return\n\n '
tl = (line_thickness or (round(((0.002 * (img.shape[0] + img.shape[1])) / 2)) + 1))
color = (color or [random.randint(0, 255) for _ in range(3)])
(c1, c2) = ((int(x[0]), int(x[1])), (int(x[2]), int(x[3])))
cv2.rectangle(img, c1, c2, color, thickness=tl, lineType=cv2.LINE_AA)
if label:
tf = max((tl - 1), 1)
t_size = cv2.getTextSize(label, 0, fontScale=(tl / 3), thickness=tf)[0]
c2 = ((c1[0] + t_size[0]), ((c1[1] - t_size[1]) - 3))
cv2.rectangle(img, c1, c2, color, (- 1), cv2.LINE_AA)
cv2.putText(img, label, (c1[0], (c1[1] - 2)), 0, (tl / 3), [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA) | def plot_one_box(x, img, color=None, label=None, line_thickness=None):
'\n description: Plots one bounding box on image img,\n this function comes from YoLov5 project.\n param: \n x: a box likes [x1,y1,x2,y2]\n img: a opencv image object\n color: color to draw rectangle, such as (0,255,0)\n label: str\n line_thickness: int\n return:\n no return\n\n '
tl = (line_thickness or (round(((0.002 * (img.shape[0] + img.shape[1])) / 2)) + 1))
color = (color or [random.randint(0, 255) for _ in range(3)])
(c1, c2) = ((int(x[0]), int(x[1])), (int(x[2]), int(x[3])))
cv2.rectangle(img, c1, c2, color, thickness=tl, lineType=cv2.LINE_AA)
if label:
tf = max((tl - 1), 1)
t_size = cv2.getTextSize(label, 0, fontScale=(tl / 3), thickness=tf)[0]
c2 = ((c1[0] + t_size[0]), ((c1[1] - t_size[1]) - 3))
cv2.rectangle(img, c1, c2, color, (- 1), cv2.LINE_AA)
cv2.putText(img, label, (c1[0], (c1[1] - 2)), 0, (tl / 3), [225, 255, 255], thickness=tf, lineType=cv2.LINE_AA)<|docstring|>description: Plots one bounding box on image img,
this function comes from YoLov5 project.
param:
x: a box likes [x1,y1,x2,y2]
img: a opencv image object
color: color to draw rectangle, such as (0,255,0)
label: str
line_thickness: int
return:
no return<|endoftext|> |
49bb69113983c7df1273d69c988af989379fc1385bb590a803b5bee87b6e9fdd | def preprocess_image(self, input_image_path):
'\n description: Read an image from image path, convert it to RGB,\n resize and pad it to target size, normalize to [0,1],\n transform to NCHW format.\n param:\n input_image_path: str, image path\n return:\n image: the processed image\n image_raw: the original image\n h: original height\n w: original width\n '
image_raw = cv2.imread(input_image_path)
(h, w, c) = image_raw.shape
image = cv2.cvtColor(image_raw, cv2.COLOR_BGR2RGB)
r_w = (INPUT_W / w)
r_h = (INPUT_H / h)
if (r_h > r_w):
tw = INPUT_W
th = int((r_w * h))
tx1 = tx2 = 0
ty1 = int(((INPUT_H - th) / 2))
ty2 = ((INPUT_H - th) - ty1)
else:
tw = int((r_h * w))
th = INPUT_H
tx1 = int(((INPUT_W - tw) / 2))
tx2 = ((INPUT_W - tw) - tx1)
ty1 = ty2 = 0
image = cv2.resize(image, (tw, th))
image = cv2.copyMakeBorder(image, ty1, ty2, tx1, tx2, cv2.BORDER_CONSTANT, (127.5, 127.5, 127.5))
image = image.astype(np.float32)
image /= 255.0
image = np.transpose(image, [2, 0, 1])
image = np.expand_dims(image, axis=0)
image = np.ascontiguousarray(image)
return (image, image_raw, h, w) | description: Read an image from image path, convert it to RGB,
resize and pad it to target size, normalize to [0,1],
transform to NCHW format.
param:
input_image_path: str, image path
return:
image: the processed image
image_raw: the original image
h: original height
w: original width | PytorchToTensorRTGIE/yolov5_trt.py | preprocess_image | ZhangwenguangHikvision/YoloV5_JDE_TensorRT_for_Track | 44 | python | def preprocess_image(self, input_image_path):
'\n description: Read an image from image path, convert it to RGB,\n resize and pad it to target size, normalize to [0,1],\n transform to NCHW format.\n param:\n input_image_path: str, image path\n return:\n image: the processed image\n image_raw: the original image\n h: original height\n w: original width\n '
image_raw = cv2.imread(input_image_path)
(h, w, c) = image_raw.shape
image = cv2.cvtColor(image_raw, cv2.COLOR_BGR2RGB)
r_w = (INPUT_W / w)
r_h = (INPUT_H / h)
if (r_h > r_w):
tw = INPUT_W
th = int((r_w * h))
tx1 = tx2 = 0
ty1 = int(((INPUT_H - th) / 2))
ty2 = ((INPUT_H - th) - ty1)
else:
tw = int((r_h * w))
th = INPUT_H
tx1 = int(((INPUT_W - tw) / 2))
tx2 = ((INPUT_W - tw) - tx1)
ty1 = ty2 = 0
image = cv2.resize(image, (tw, th))
image = cv2.copyMakeBorder(image, ty1, ty2, tx1, tx2, cv2.BORDER_CONSTANT, (127.5, 127.5, 127.5))
image = image.astype(np.float32)
image /= 255.0
image = np.transpose(image, [2, 0, 1])
image = np.expand_dims(image, axis=0)
image = np.ascontiguousarray(image)
return (image, image_raw, h, w) | def preprocess_image(self, input_image_path):
'\n description: Read an image from image path, convert it to RGB,\n resize and pad it to target size, normalize to [0,1],\n transform to NCHW format.\n param:\n input_image_path: str, image path\n return:\n image: the processed image\n image_raw: the original image\n h: original height\n w: original width\n '
image_raw = cv2.imread(input_image_path)
(h, w, c) = image_raw.shape
image = cv2.cvtColor(image_raw, cv2.COLOR_BGR2RGB)
r_w = (INPUT_W / w)
r_h = (INPUT_H / h)
if (r_h > r_w):
tw = INPUT_W
th = int((r_w * h))
tx1 = tx2 = 0
ty1 = int(((INPUT_H - th) / 2))
ty2 = ((INPUT_H - th) - ty1)
else:
tw = int((r_h * w))
th = INPUT_H
tx1 = int(((INPUT_W - tw) / 2))
tx2 = ((INPUT_W - tw) - tx1)
ty1 = ty2 = 0
image = cv2.resize(image, (tw, th))
image = cv2.copyMakeBorder(image, ty1, ty2, tx1, tx2, cv2.BORDER_CONSTANT, (127.5, 127.5, 127.5))
image = image.astype(np.float32)
image /= 255.0
image = np.transpose(image, [2, 0, 1])
image = np.expand_dims(image, axis=0)
image = np.ascontiguousarray(image)
return (image, image_raw, h, w)<|docstring|>description: Read an image from image path, convert it to RGB,
resize and pad it to target size, normalize to [0,1],
transform to NCHW format.
param:
input_image_path: str, image path
return:
image: the processed image
image_raw: the original image
h: original height
w: original width<|endoftext|> |
c78d7359d00b46e6579d72417d521eac181d444454ba757b6345ece09b0b2000 | def xywh2xyxy(self, origin_h, origin_w, x):
'\n description: Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right\n param:\n origin_h: height of original image\n origin_w: width of original image\n x: A boxes tensor, each row is a box [center_x, center_y, w, h]\n return:\n y: A boxes tensor, each row is a box [x1, y1, x2, y2]\n '
y = (torch.zeros_like(x) if isinstance(x, torch.Tensor) else np.zeros_like(x))
r_w = (INPUT_W / origin_w)
r_h = (INPUT_H / origin_h)
if (r_h > r_w):
y[(:, 0)] = (x[(:, 0)] - (x[(:, 2)] / 2))
y[(:, 2)] = (x[(:, 0)] + (x[(:, 2)] / 2))
y[(:, 1)] = ((x[(:, 1)] - (x[(:, 3)] / 2)) - ((INPUT_H - (r_w * origin_h)) / 2))
y[(:, 3)] = ((x[(:, 1)] + (x[(:, 3)] / 2)) - ((INPUT_H - (r_w * origin_h)) / 2))
y /= r_w
else:
y[(:, 0)] = ((x[(:, 0)] - (x[(:, 2)] / 2)) - ((INPUT_W - (r_h * origin_w)) / 2))
y[(:, 2)] = ((x[(:, 0)] + (x[(:, 2)] / 2)) - ((INPUT_W - (r_h * origin_w)) / 2))
y[(:, 1)] = (x[(:, 1)] - (x[(:, 3)] / 2))
y[(:, 3)] = (x[(:, 1)] + (x[(:, 3)] / 2))
y /= r_h
return y | description: Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right
param:
origin_h: height of original image
origin_w: width of original image
x: A boxes tensor, each row is a box [center_x, center_y, w, h]
return:
y: A boxes tensor, each row is a box [x1, y1, x2, y2] | PytorchToTensorRTGIE/yolov5_trt.py | xywh2xyxy | ZhangwenguangHikvision/YoloV5_JDE_TensorRT_for_Track | 44 | python | def xywh2xyxy(self, origin_h, origin_w, x):
'\n description: Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right\n param:\n origin_h: height of original image\n origin_w: width of original image\n x: A boxes tensor, each row is a box [center_x, center_y, w, h]\n return:\n y: A boxes tensor, each row is a box [x1, y1, x2, y2]\n '
y = (torch.zeros_like(x) if isinstance(x, torch.Tensor) else np.zeros_like(x))
r_w = (INPUT_W / origin_w)
r_h = (INPUT_H / origin_h)
if (r_h > r_w):
y[(:, 0)] = (x[(:, 0)] - (x[(:, 2)] / 2))
y[(:, 2)] = (x[(:, 0)] + (x[(:, 2)] / 2))
y[(:, 1)] = ((x[(:, 1)] - (x[(:, 3)] / 2)) - ((INPUT_H - (r_w * origin_h)) / 2))
y[(:, 3)] = ((x[(:, 1)] + (x[(:, 3)] / 2)) - ((INPUT_H - (r_w * origin_h)) / 2))
y /= r_w
else:
y[(:, 0)] = ((x[(:, 0)] - (x[(:, 2)] / 2)) - ((INPUT_W - (r_h * origin_w)) / 2))
y[(:, 2)] = ((x[(:, 0)] + (x[(:, 2)] / 2)) - ((INPUT_W - (r_h * origin_w)) / 2))
y[(:, 1)] = (x[(:, 1)] - (x[(:, 3)] / 2))
y[(:, 3)] = (x[(:, 1)] + (x[(:, 3)] / 2))
y /= r_h
return y | def xywh2xyxy(self, origin_h, origin_w, x):
'\n description: Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right\n param:\n origin_h: height of original image\n origin_w: width of original image\n x: A boxes tensor, each row is a box [center_x, center_y, w, h]\n return:\n y: A boxes tensor, each row is a box [x1, y1, x2, y2]\n '
y = (torch.zeros_like(x) if isinstance(x, torch.Tensor) else np.zeros_like(x))
r_w = (INPUT_W / origin_w)
r_h = (INPUT_H / origin_h)
if (r_h > r_w):
y[(:, 0)] = (x[(:, 0)] - (x[(:, 2)] / 2))
y[(:, 2)] = (x[(:, 0)] + (x[(:, 2)] / 2))
y[(:, 1)] = ((x[(:, 1)] - (x[(:, 3)] / 2)) - ((INPUT_H - (r_w * origin_h)) / 2))
y[(:, 3)] = ((x[(:, 1)] + (x[(:, 3)] / 2)) - ((INPUT_H - (r_w * origin_h)) / 2))
y /= r_w
else:
y[(:, 0)] = ((x[(:, 0)] - (x[(:, 2)] / 2)) - ((INPUT_W - (r_h * origin_w)) / 2))
y[(:, 2)] = ((x[(:, 0)] + (x[(:, 2)] / 2)) - ((INPUT_W - (r_h * origin_w)) / 2))
y[(:, 1)] = (x[(:, 1)] - (x[(:, 3)] / 2))
y[(:, 3)] = (x[(:, 1)] + (x[(:, 3)] / 2))
y /= r_h
return y<|docstring|>description: Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right
param:
origin_h: height of original image
origin_w: width of original image
x: A boxes tensor, each row is a box [center_x, center_y, w, h]
return:
y: A boxes tensor, each row is a box [x1, y1, x2, y2]<|endoftext|> |
30aebf8b97ab19c5f88f83bee5e0c16332962f65d40ed6771bbd27e088903840 | def post_process(self, output, origin_h, origin_w):
'\n description: postprocess the prediction\n param:\n output: A tensor likes [num_boxes,cx,cy,w,h,conf,cls_id, cx,cy,w,h,conf,cls_id, ...] \n origin_h: height of original image\n origin_w: width of original image\n return:\n result_boxes: finally boxes, a boxes tensor, each row is a box [x1, y1, x2, y2]\n result_scores: finally scores, a tensor, each element is the score correspoing to box\n result_classid: finally classid, a tensor, each element is the classid correspoing to box\n '
num = int(output[0])
pred = np.reshape(output[1:], ((- 1), 6))[(:num, :)]
pred = torch.Tensor(pred).cuda()
boxes = pred[(:, :4)]
scores = pred[(:, 4)]
classid = pred[(:, 5)]
si = (scores > CONF_THRESH)
boxes = boxes[(si, :)]
scores = scores[si]
classid = classid[si]
x_inds = (boxes[(:, 0)] // 8)
y_inds = (boxes[(:, 1)] // 8)
boxes = self.xywh2xyxy(origin_h, origin_w, boxes)
indices = torchvision.ops.nms(boxes, scores, iou_threshold=IOU_THRESHOLD).cpu()
result_boxes = boxes[(indices, :)].cpu()
result_scores = scores[indices].cpu()
result_classid = classid[indices].cpu()
return (result_boxes, result_scores, result_classid, x_inds, y_inds) | description: postprocess the prediction
param:
output: A tensor likes [num_boxes,cx,cy,w,h,conf,cls_id, cx,cy,w,h,conf,cls_id, ...]
origin_h: height of original image
origin_w: width of original image
return:
result_boxes: finally boxes, a boxes tensor, each row is a box [x1, y1, x2, y2]
result_scores: finally scores, a tensor, each element is the score correspoing to box
result_classid: finally classid, a tensor, each element is the classid correspoing to box | PytorchToTensorRTGIE/yolov5_trt.py | post_process | ZhangwenguangHikvision/YoloV5_JDE_TensorRT_for_Track | 44 | python | def post_process(self, output, origin_h, origin_w):
'\n description: postprocess the prediction\n param:\n output: A tensor likes [num_boxes,cx,cy,w,h,conf,cls_id, cx,cy,w,h,conf,cls_id, ...] \n origin_h: height of original image\n origin_w: width of original image\n return:\n result_boxes: finally boxes, a boxes tensor, each row is a box [x1, y1, x2, y2]\n result_scores: finally scores, a tensor, each element is the score correspoing to box\n result_classid: finally classid, a tensor, each element is the classid correspoing to box\n '
num = int(output[0])
pred = np.reshape(output[1:], ((- 1), 6))[(:num, :)]
pred = torch.Tensor(pred).cuda()
boxes = pred[(:, :4)]
scores = pred[(:, 4)]
classid = pred[(:, 5)]
si = (scores > CONF_THRESH)
boxes = boxes[(si, :)]
scores = scores[si]
classid = classid[si]
x_inds = (boxes[(:, 0)] // 8)
y_inds = (boxes[(:, 1)] // 8)
boxes = self.xywh2xyxy(origin_h, origin_w, boxes)
indices = torchvision.ops.nms(boxes, scores, iou_threshold=IOU_THRESHOLD).cpu()
result_boxes = boxes[(indices, :)].cpu()
result_scores = scores[indices].cpu()
result_classid = classid[indices].cpu()
return (result_boxes, result_scores, result_classid, x_inds, y_inds) | def post_process(self, output, origin_h, origin_w):
'\n description: postprocess the prediction\n param:\n output: A tensor likes [num_boxes,cx,cy,w,h,conf,cls_id, cx,cy,w,h,conf,cls_id, ...] \n origin_h: height of original image\n origin_w: width of original image\n return:\n result_boxes: finally boxes, a boxes tensor, each row is a box [x1, y1, x2, y2]\n result_scores: finally scores, a tensor, each element is the score correspoing to box\n result_classid: finally classid, a tensor, each element is the classid correspoing to box\n '
num = int(output[0])
pred = np.reshape(output[1:], ((- 1), 6))[(:num, :)]
pred = torch.Tensor(pred).cuda()
boxes = pred[(:, :4)]
scores = pred[(:, 4)]
classid = pred[(:, 5)]
si = (scores > CONF_THRESH)
boxes = boxes[(si, :)]
scores = scores[si]
classid = classid[si]
x_inds = (boxes[(:, 0)] // 8)
y_inds = (boxes[(:, 1)] // 8)
boxes = self.xywh2xyxy(origin_h, origin_w, boxes)
indices = torchvision.ops.nms(boxes, scores, iou_threshold=IOU_THRESHOLD).cpu()
result_boxes = boxes[(indices, :)].cpu()
result_scores = scores[indices].cpu()
result_classid = classid[indices].cpu()
return (result_boxes, result_scores, result_classid, x_inds, y_inds)<|docstring|>description: postprocess the prediction
param:
output: A tensor likes [num_boxes,cx,cy,w,h,conf,cls_id, cx,cy,w,h,conf,cls_id, ...]
origin_h: height of original image
origin_w: width of original image
return:
result_boxes: finally boxes, a boxes tensor, each row is a box [x1, y1, x2, y2]
result_scores: finally scores, a tensor, each element is the score correspoing to box
result_classid: finally classid, a tensor, each element is the classid correspoing to box<|endoftext|> |
87ef8a60d0940d16807e611065c85f25226f002da1fdfa0d979badd888ddd480 | def save(self, data):
' save a new meetup.'
tags = '{'
for tag in data['tags']:
tags += (('"' + tag) + '",')
tags = (tags[:(- 1)] + '}')
query = "INSERT INTO {} (topic, description, tags, location, happeningOn) VALUES ('{}','{}','{}','{}','{}') RETURNING *".format(self.table, data['topic'], data['description'], tags, data['location'], data['happeningOn'])
self.cur.execute(query)
result = self.cur.fetchone()
self.conn.commit()
return result | save a new meetup. | app/api/v2/models/meetup_models.py | save | MRichardN/Qustioner-api-v2 | 0 | python | def save(self, data):
' '
tags = '{'
for tag in data['tags']:
tags += (('"' + tag) + '",')
tags = (tags[:(- 1)] + '}')
query = "INSERT INTO {} (topic, description, tags, location, happeningOn) VALUES ('{}','{}','{}','{}','{}') RETURNING *".format(self.table, data['topic'], data['description'], tags, data['location'], data['happeningOn'])
self.cur.execute(query)
result = self.cur.fetchone()
self.conn.commit()
return result | def save(self, data):
' '
tags = '{'
for tag in data['tags']:
tags += (('"' + tag) + '",')
tags = (tags[:(- 1)] + '}')
query = "INSERT INTO {} (topic, description, tags, location, happeningOn) VALUES ('{}','{}','{}','{}','{}') RETURNING *".format(self.table, data['topic'], data['description'], tags, data['location'], data['happeningOn'])
self.cur.execute(query)
result = self.cur.fetchone()
self.conn.commit()
return result<|docstring|>save a new meetup.<|endoftext|> |
9e96c5523106bdbfaca2de020e63c792fcf1ba92c4442b83d63829ef511e6f80 | def exists(self, key, value):
' search item by key value pair.'
query = "SELECT * FROM {} WHERE {} = '{}'".format(self.table, key, value)
self.cur.execute(query)
result = self.cur.fetchall()
return (len(result) > 0) | search item by key value pair. | app/api/v2/models/meetup_models.py | exists | MRichardN/Qustioner-api-v2 | 0 | python | def exists(self, key, value):
' '
query = "SELECT * FROM {} WHERE {} = '{}'".format(self.table, key, value)
self.cur.execute(query)
result = self.cur.fetchall()
return (len(result) > 0) | def exists(self, key, value):
' '
query = "SELECT * FROM {} WHERE {} = '{}'".format(self.table, key, value)
self.cur.execute(query)
result = self.cur.fetchall()
return (len(result) > 0)<|docstring|>search item by key value pair.<|endoftext|> |
12eb098336b6fae0c5b1ba7fb388af9c294092fb8468927be05e581e3699260d | def getOne(self, id):
' Get a specific meetup.'
meetup = self.where('id', id)
return meetup | Get a specific meetup. | app/api/v2/models/meetup_models.py | getOne | MRichardN/Qustioner-api-v2 | 0 | python | def getOne(self, id):
' '
meetup = self.where('id', id)
return meetup | def getOne(self, id):
' '
meetup = self.where('id', id)
return meetup<|docstring|>Get a specific meetup.<|endoftext|> |
c54f5f233b54e046a531e06961d8b3fc3d5adc5cd5ec8d1cd0735292c1b3826e | def meetupTags(self, meetup_id, meetup_tags):
' update meetup tags '
meetup = self.where('id', meetup_id)
new_tags = list(set((meetup_tags + meetup['tags'])))
tags = '{'
for tag in new_tags:
tags += (('"' + tag) + '",')
tags = (tags[:(- 1)] + '}')
query = "UPDATE {} SET tags = '{}' WHERE id = '{}' RETURNING *".format(self.table, tags, meetup_id)
self.cur.execute(query)
self.conn.commit()
return self.cur.fetchone() | update meetup tags | app/api/v2/models/meetup_models.py | meetupTags | MRichardN/Qustioner-api-v2 | 0 | python | def meetupTags(self, meetup_id, meetup_tags):
' '
meetup = self.where('id', meetup_id)
new_tags = list(set((meetup_tags + meetup['tags'])))
tags = '{'
for tag in new_tags:
tags += (('"' + tag) + '",')
tags = (tags[:(- 1)] + '}')
query = "UPDATE {} SET tags = '{}' WHERE id = '{}' RETURNING *".format(self.table, tags, meetup_id)
self.cur.execute(query)
self.conn.commit()
return self.cur.fetchone() | def meetupTags(self, meetup_id, meetup_tags):
' '
meetup = self.where('id', meetup_id)
new_tags = list(set((meetup_tags + meetup['tags'])))
tags = '{'
for tag in new_tags:
tags += (('"' + tag) + '",')
tags = (tags[:(- 1)] + '}')
query = "UPDATE {} SET tags = '{}' WHERE id = '{}' RETURNING *".format(self.table, tags, meetup_id)
self.cur.execute(query)
self.conn.commit()
return self.cur.fetchone()<|docstring|>update meetup tags<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.