text
stringlengths 3
1.05M
|
|---|
#ifndef SEAFILE_CLIENT_UTILS_SINGLETON_H
#define SEAFILE_CLIENT_UTILS_SINGLETON_H
/**
* This macro helps conveniently define singleton classes. Usage:
*
* // foo.h
* #include "utils/singleton.h"
* class Foo {
* SINGLETON_DEFINE(Foo)
* private:
* Foo()
* ...
* }
* // foo.cpp
* #include "foo.h"
* SINGLETON_IMPL(Foo)
*/
#define SINGLETON_DEFINE(CLASS) \
public: \
static CLASS *instance(); \
private: \
static CLASS *singleton_; \
#define SINGLETON_IMPL(CLASS) \
CLASS* CLASS::singleton_; \
CLASS* CLASS::instance() { \
if (singleton_ == NULL) { \
static CLASS instance; \
singleton_ = &instance; \
} \
return singleton_; \
}
#endif // SEAFILE_CLIENT_UTILS_SINGLETON_H
|
{
var object = {
a: 0,
b: 1,
c: 2
};
for (var key in object) {
if (key == 'a') {
delete object.b;
object.d = 3;
}
yield key;
yield object[key];
}
}
|
import tensorflow.keras
from PIL import Image, ImageOps
import numpy as np
import requests
def get(img):
np.set_printoptions(suppress=True)
model = tensorflow.keras.models.load_model('keras_model.h5')
data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)
image = Image.open(requests.get(img, stream=True).raw)
size = (224, 224)
image = ImageOps.fit(image, size, Image.ANTIALIAS)
image_array = np.asarray(image)
#image.show()
normalized_image_array = (image_array.astype(np.float32) / 127.0) - 1
data[0] = normalized_image_array
prediction = model.predict(data)
print(prediction)
result = np.argmax(prediction)
labels = ['Flooding','Flood Warning', 'Not Flooding']
return labels[result]
|
# -*- coding: utf-8 -*-
"""
Raw ctypes wrappers of the cuBLAS library v7.0+ (libcublas.so.7.0)
For documentation see:
http://docs.nvidia.com/cuda/cublas
/usr/include/ cublas_api.h and cublas_v2.h
"""
import platform
import ctypes
import ctypes.util
import enum
from ctypes import *
### cuBLAS Library ###
libname = ctypes.util.find_library('cublas')
#TODO import name for windows/mac?
if platform.system()=='Windows':
libcublas = ctypes.windll.LoadLibrary(libname)
elif platform.system()=='Linux':
libcublas = ctypes.CDLL(libname, ctypes.RTLD_GLOBAL)
else:
libcublas = ctypes.cdll.LoadLibrary(libname)
## cuBLAS Datatypes ##
#cublasStatus_t
class cublasStatus_t(enum.IntEnum):
CUBLAS_STATUS_SUCCESS =0
CUBLAS_STATUS_NOT_INITIALIZED =1
CUBLAS_STATUS_ALLOC_FAILED =3
CUBLAS_STATUS_INVALID_VALUE =7
CUBLAS_STATUS_ARCH_MISMATCH =8
CUBLAS_STATUS_MAPPING_ERROR =11
CUBLAS_STATUS_EXECUTION_FAILED=13
CUBLAS_STATUS_INTERNAL_ERROR =14
CUBLAS_STATUS_NOT_SUPPORTED =15
#cublasFillMode_t
class cublasFillMode_t(enum.IntEnum):
CUBLAS_FILL_MODE_LOWER=0
CUBLAS_FILL_MODE_UPPER=1
c_cublasFillMode_t = c_int
#cublasDiagType_t
class cublasDiagType_t(enum.IntEnum):
CUBLAS_DIAG_NON_UNIT=0
CUBLAS_DIAG_UNIT=1
c_cublasDiagType_t = c_int
#cublasSideMode_t
class cublasSideMode_t(enum.IntEnum):
CUBLAS_SIDE_LEFT =0
CUBLAS_SIDE_RIGHT=1
c_cublasSideMode_t = c_int
#cublasOperation_t
class cublasOperation_t(enum.IntEnum):
CUBLAS_OP_N=0
CUBLAS_OP_T=1
CUBLAS_OP_C=2
c_cublasOperation_t = c_int
#cublasPointerMode_t
class cublasPointerMode_t(enum.IntEnum):
CUBLAS_POINTER_MODE_HOST = 0
CUBLAS_POINTER_MODE_DEVICE = 1
c_cublasPointerMode_t = c_int
#cublasAtomicsMode_t
class cublasAtomicsMode_t(enum.IntEnum):
CUBLAS_ATOMICS_NOT_ALLOWED = 0
CUBLAS_ATOMICS_ALLOWED = 1
c_cublasAtomicsMode_t = c_int
#/* Opaque structure holding CUBLAS library context */
# struct cublasContext;
# typedef struct cublasContext *cublasHandle_t;
class _opaque(ctypes.Structure):
pass
cublasHandle_t = POINTER(_opaque)
cublasHandle_t.__name__ = 'cublasHandle_t'
memory_pointer = ctypes.c_void_p
array_pointer = ctypes.c_void_p
result_pointer = ctypes.c_void_p
scalar_pointer = ctypes.c_void_p
param_pointer = ctypes.c_void_p
## cuBLAS Helper Functions ##
# cublasStatus_t cublasCreate(cublasHandle_t *handle)
cublasCreate = libcublas.cublasCreate_v2
cublasCreate.restype = cublasStatus_t
cublasCreate.argtypes = [POINTER(cublasHandle_t)]
# cublasStatus_t cublasDestroy(cublasHandle_t handle)
cublasDestroy = libcublas.cublasDestroy_v2
cublasDestroy.restype = cublasStatus_t
cublasDestroy.argtypes = [cublasHandle_t]
# cublasStatus_t cublasGetVersion(cublasHandle_t handle, int *version)
cublasGetVersion = libcublas.cublasGetVersion_v2
cublasGetVersion.restype = cublasStatus_t
cublasGetVersion.argtypes = [cublasHandle_t, POINTER(c_int)]
# cublasStatus_t = cublasSetStream(cublasHandle_t handle, cudaStream_t streamId)
# cublasStatus_t = cublasGetStream(cublasHandle_t handle, cudaStream_t *streamId)
# cublasStatus_t cublasGetPointerMode(cublasHandle_t handle, cublasPointerMode_t *mode)
cublasGetPointerMode = libcublas.cublasGetPointerMode_v2
cublasGetPointerMode.restype = cublasStatus_t
cublasGetPointerMode.argtypes = [cublasHandle_t, POINTER(c_cublasPointerMode_t)]
# cublasStatus_t cublasSetPointerMode(cublasHandle_t handle, cublasPointerMode_t mode)
cublasSetPointerMode = libcublas.cublasSetPointerMode_v2
cublasSetPointerMode.restype = cublasStatus_t
cublasSetPointerMode.argtypes = [cublasHandle_t, c_cublasPointerMode_t]
# cublasStatus_t cublasSetVector(int n, int elemSize,
# const void *x, int incx, void *y, int incy)
# cublasStatus_t cublasGetVector(int n, int elemSize,
# const void *x, int incx, void *y, int incy)
cublasSetVector = libcublas.cublasSetVector
cublasGetVector = libcublas.cublasGetVector
for funct in [cublasSetVector, cublasGetVector]:
funct.restype = cublasStatus_t
funct.argtypes = [c_int, c_int, #n, elemSize
memory_pointer, c_int, #*x, incx
memory_pointer, c_int #*y, incy
]
# cublasStatus_t cublasSetMatrix(int rows, int cols, int elemSize,
# const void *A, int lda, void *B, int ldb)
# cublasStatus_t cublasGetMatrix(int rows, int cols, int elemSize,
# const void *A, int lda, void *B, int ldb)
cublasSetMatrix = libcublas.cublasSetMatrix
cublasGetMatrix = libcublas.cublasGetMatrix
for funct in [cublasSetMatrix, cublasGetMatrix]:
funct.restype = cublasStatus_t
funct.argtypes = [c_int, c_int, c_int, #rows, cols, elemSize
memory_pointer, c_int, #*A, incx
memory_pointer, c_int #*B, incy
]
# cublasStatus_t cublasSetVectorAsync(int n, int elemSize, const void *hostPtr, int incx,
# void *devicePtr, int incy, cudaStream_t stream)
# cublasStatus_t cublasGetVectorAsync(int n, int elemSize, const void *devicePtr, int incx,
# void *hostPtr, int incy, cudaStream_t stream)
# cublasStatus_t cublasSetMatrixAsync(int rows, int cols, int elemSize, const void *A,
# int lda, void *B, int ldb, cudaStream_t stream)
# cublasStatus_t cublasGetMatrixAsync(int rows, int cols, int elemSize, const void *A,
# int lda, void *B, int ldb, cudaStream_t stream)
# cublasStatus_t cublasSetAtomicsMode(cublasHandlet handle, cublasAtomicsMode_t mode)
cublasGetAtomicsMode = libcublas.cublasGetAtomicsMode
cublasGetAtomicsMode.restype = cublasStatus_t
cublasGetAtomicsMode.argtypes = [cublasHandle_t, POINTER(c_cublasAtomicsMode_t)]
# cublasStatus_t cublasSetAtomicsMode(cublasHandlet handle, cublasAtomicsMode_t mode)
cublasSetAtomicsMode = libcublas.cublasSetAtomicsMode
cublasSetAtomicsMode.restype = cublasStatus_t
cublasSetAtomicsMode.argtypes = [cublasHandle_t, c_cublasAtomicsMode_t]
## cuBLAS Level-1 Functions ##
# cublasStatus_t cublasIsamax(cublasHandle_t handle, int n,
# const float *x, int incx, int *result)
# cublasStatus_t cublasIdamax(cublasHandle_t handle, int n,
# const double *x, int incx, int *result)
# cublasStatus_t cublasIcamax(cublasHandle_t handle, int n,
# const cuComplex *x, int incx, int *result)
# cublasStatus_t cublasIzamax(cublasHandle_t handle, int n,
# const cuDoubleComplex *x, int incx, int *result)
cublasIsamax = libcublas.cublasIsamax_v2
cublasIdamax = libcublas.cublasIdamax_v2
cublasIcamax = libcublas.cublasIcamax_v2
cublasIzamax = libcublas.cublasIzamax_v2
for funct in [cublasIsamax, cublasIdamax, cublasIcamax, cublasIzamax]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_int, #n
memory_pointer, c_int, #*x, incx
POINTER(c_int) #*result
]
# cublasStatus_t cublasIsamin(cublasHandle_t handle, int n,
# const float *x, int incx, int *result)
# cublasStatus_t cublasIdamin(cublasHandle_t handle, int n,
# const double *x, int incx, int *result)
# cublasStatus_t cublasIcamin(cublasHandle_t handle, int n,
# const cuComplex *x, int incx, int *result)
# cublasStatus_t cublasIzamin(cublasHandle_t handle, int n,
# const cuDoubleComplex *x, int incx, int *result)
cublasIsamin = libcublas.cublasIsamin_v2
cublasIdamin = libcublas.cublasIdamin_v2
cublasIcamin = libcublas.cublasIcamin_v2
cublasIzamin = libcublas.cublasIzamin_v2
for funct in [cublasIsamin, cublasIdamin, cublasIcamin, cublasIzamin]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_int, #n
memory_pointer, c_int, #*x, incx
POINTER(c_int) #*result
]
# cublasStatus_t cublasSasum(cublasHandle_t handle, int n,
# const float *x, int incx, float *result)
# cublasStatus_t cublasDasum(cublasHandle_t handle, int n,
# const double *x, int incx, double *result)
# cublasStatus_t cublasScasum(cublasHandle_t handle, int n,
# const cuComplex *x, int incx, float *result)
# cublasStatus_t cublasDzasum(cublasHandle_t handle, int n,
# const cuDoubleComplex *x, int incx, double *result)
cublasSasum = libcublas.cublasSasum_v2
cublasDasum = libcublas.cublasDasum_v2
cublasScasum = libcublas.cublasScasum_v2
cublasDzasum = libcublas.cublasDzasum_v2
for (funct, result_type) in [(cublasSasum, c_float), (cublasDasum, c_double),
(cublasScasum, c_float), (cublasDzasum, c_double)]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_int, #n
memory_pointer, c_int, #*x, incx
POINTER(result_type) #*result
]
# cublasStatus_t cublasSaxpy(cublasHandle_t handle, int n,
# const float *alpha,
# const float *x, int incx,
# float *y, int incy)
# cublasStatus_t cublasDaxpy(cublasHandle_t handle, int n,
# const double *alpha,
# const double *x, int incx,
# double *y, int incy)
# cublasStatus_t cublasCaxpy(cublasHandle_t handle, int n,
# const cuComplex *alpha,
# const cuComplex *x, int incx,
# cuComplex *y, int incy)
# cublasStatus_t cublasZaxpy(cublasHandle_t handle, int n,
# const cuDoubleComplex *alpha,
# const cuDoubleComplex *x, int incx,
# cuDoubleComplex *y, int incy)
cublasSaxpy = libcublas.cublasSaxpy_v2
cublasDaxpy = libcublas.cublasDaxpy_v2
cublasCaxpy = libcublas.cublasCaxpy_v2
cublasZaxpy = libcublas.cublasZaxpy_v2
for funct in [cublasSaxpy, cublasDaxpy, cublasCaxpy, cublasZaxpy]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_int, #n
scalar_pointer, #*alpha
memory_pointer, c_int, #*x, incx
memory_pointer, c_int #*y, incy
]
# cublasStatus_t cublasScopy(cublasHandle_t handle, int n,
# const float *x, int incx,
# float *y, int incy)
# cublasStatus_t cublasDcopy(cublasHandle_t handle, int n,
# const double *x, int incx,
# double *y, int incy)
# cublasStatus_t cublasCcopy(cublasHandle_t handle, int n,
# const cuComplex *x, int incx,
# cuComplex *y, int incy)
# cublasStatus_t cublasZcopy(cublasHandle_t handle, int n,
# const cuDoubleComplex *x, int incx,
# cuDoubleComplex *y, int incy)
cublasScopy = libcublas.cublasScopy_v2
cublasDcopy = libcublas.cublasDcopy_v2
cublasCcopy = libcublas.cublasCcopy_v2
cublasZcopy = libcublas.cublasZcopy_v2
for funct in [cublasScopy, cublasDcopy, cublasCcopy, cublasZcopy]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_int, #n
memory_pointer, c_int, #*x, incx
memory_pointer, c_int #*y, incy
]
# cublasStatus_t cublasSdot (cublasHandle_t handle, int n,
# const float *x, int incx,
# const float *y, int incy,
# float *result)
# cublasStatus_t cublasDdot (cublasHandle_t handle, int n,
# const double *x, int incx,
# const double *y, int incy,
# double *result)
# cublasStatus_t cublasCdotu(cublasHandle_t handle, int n,
# const cuComplex *x, int incx,
# const cuComplex *y, int incy,
# cuComplex *result)
# cublasStatus_t cublasCdotc(cublasHandle_t handle, int n,
# const cuComplex *x, int incx,
# const cuComplex *y, int incy,
# cuComplex *result)
# cublasStatus_t cublasZdotu(cublasHandle_t handle, int n,
# const cuDoubleComplex *x, int incx,
# const cuDoubleComplex *y, int incy,
# cuDoubleComplex *result)
# cublasStatus_t cublasZdotc(cublasHandle_t handle, int n,
# const cuDoubleComplex *x, int incx,
# const cuDoubleComplex *y, int incy,
# cuDoubleComplex *result)
cublasSdot = libcublas.cublasSdot_v2
cublasDdot = libcublas.cublasDdot_v2
cublasCdotu = libcublas.cublasCdotu_v2
cublasCdotc = libcublas.cublasCdotc_v2
cublasZdotu = libcublas.cublasZdotu_v2
cublasZdotc = libcublas.cublasZdotc_v2
for funct in [cublasSdot, cublasDdot,
cublasCdotu, cublasCdotc,
cublasZdotu, cublasZdotc]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_int, #n
memory_pointer, c_int, #*x, incx
memory_pointer, c_int, #*y, incy
result_pointer #*result
]
# cublasStatus_t cublasSnrm2(cublasHandle_t handle, int n,
# const float *x, int incx, float *result)
# cublasStatus_t cublasDnrm2(cublasHandle_t handle, int n,
# const double *x, int incx, double *result)
# cublasStatus_t cublasScnrm2(cublasHandle_t handle, int n,
# const cuComplex *x, int incx, float *result)
# cublasStatus_t cublasDznrm2(cublasHandle_t handle, int n,
# const cuDoubleComplex *x, int incx, double *result)
cublasSnrm2 = libcublas.cublasSnrm2_v2
cublasDnrm2 = libcublas.cublasDnrm2_v2
cublasScnrm2 = libcublas.cublasScnrm2_v2
cublasDznrm2 = libcublas.cublasDznrm2_v2
for (funct, result_type) in [(cublasSnrm2, c_float), (cublasDnrm2, c_double),
(cublasScnrm2, c_float), (cublasDznrm2, c_double)]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_int, #n
memory_pointer, c_int, #*x, incx
POINTER(result_type) #*result
]
# cublasStatus_t cublasSrot(cublasHandle_t handle, int n,
# float *x, int incx,
# float *y, int incy,
# const float *c, const float *s)
# cublasStatus_t cublasDrot(cublasHandle_t handle, int n,
# double *x, int incx,
# double *y, int incy,
# const double *c, const double *s)
# cublasStatus_t cublasCrot(cublasHandle_t handle, int n,
# cuComplex *x, int incx,
# cuComplex *y, int incy,
# const float *c, const cuComplex *s)
# cublasStatus_t cublasCsrot(cublasHandle_t handle, int n,
# cuComplex *x, int incx,
# cuComplex *y, int incy,
# const float *c, const float *s)
# cublasStatus_t cublasZrot(cublasHandle_t handle, int n,
# cuDoubleComplex *x, int incx,
# cuDoubleComplex *y, int incy,
# const double *c, const cuDoubleComplex *s)
# cublasStatus_t cublasZdrot(cublasHandle_t handle, int n,
# cuDoubleComplex *x, int incx,
# cuDoubleComplex *y, int incy,
# const double *c, const double *s)
cublasSrot = libcublas.cublasSrot_v2
cublasDrot = libcublas.cublasDrot_v2
cublasCrot = libcublas.cublasCrot_v2
cublasCsrot = libcublas.cublasCsrot_v2
cublasZrot = libcublas.cublasZrot_v2
cublasZdrot = libcublas.cublasZdrot_v2
for funct in [cublasSrot, cublasDrot,
cublasCrot, cublasCsrot,
cublasZrot, cublasZdrot]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_int, #*n
memory_pointer, c_int, #*x, incx
memory_pointer, c_int, #*y, incy
scalar_pointer, #*c
scalar_pointer #*s
]
# cublasStatus_t cublasSrotg(cublasHandle_t handle,
# float *a, float *b,
# float *c, float *s)
# cublasStatus_t cublasDrotg(cublasHandle_t handle,
# double *a, double *b,
# double *c, double *s)
# cublasStatus_t cublasCrotg(cublasHandle_t handle,
# cuComplex *a, cuComplex *b,
# float *c, cuComplex *s)
# cublasStatus_t cublasZrotg(cublasHandle_t handle,
# cuDoubleComplex *a, cuDoubleComplex *b,
# double *c, cuDoubleComplex *s)
cublasSrotg = libcublas.cublasSrotg_v2
cublasDrotg = libcublas.cublasDrotg_v2
cublasCrotg = libcublas.cublasCrotg_v2
cublasZrotg = libcublas.cublasZrotg_v2
for funct in [cublasSrotg, cublasDrotg, cublasCrotg, cublasZrotg]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
scalar_pointer, #*a
scalar_pointer, #*b
result_pointer, #*c
result_pointer #*s
]
# cublasStatus_t cublasSrotm(cublasHandle_t handle, int n, float *x, int incx,
# float *y, int incy, const float* param)
# cublasStatus_t cublasDrotm(cublasHandle_t handle, int n, double *x, int incx,
# double *y, int incy, const double* param)
cublasSrotm = libcublas.cublasSrotm_v2
cublasDrotm = libcublas.cublasDrotm_v2
for funct in [cublasSrotm, cublasDrotm]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_int, #n
memory_pointer, c_int, #*x, incx
memory_pointer, c_int, #*y, incy
param_pointer #*param
]
# cublasStatus_t cublasSrotmg(cublasHandle_t handle, float *d1, float *d2,
# float *x1, const float *y1, float *param)
# cublasStatus_t cublasDrotmg(cublasHandle_t handle, double *d1, double *d2,
# double *x1, const double *y1, double *param)
cublasSrotmg = libcublas.cublasSrotmg_v2
cublasDrotmg = libcublas.cublasDrotmg_v2
for funct in [cublasSrotmg, cublasDrotmg]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
scalar_pointer, #*d1
scalar_pointer, #*d2
scalar_pointer, #*x1
scalar_pointer, #*y1
param_pointer #*param
]
# cublasStatus_t cublasSscal(cublasHandle_t handle, int n,
# const float *alpha,
# float *x, int incx)
# cublasStatus_t cublasDscal(cublasHandle_t handle, int n,
# const double *alpha,
# double *x, int incx)
# cublasStatus_t cublasCscal(cublasHandle_t handle, int n,
# const cuComplex *alpha,
# cuComplex *x, int incx)
# cublasStatus_t cublasCsscal(cublasHandle_t handle, int n,
# const float *alpha,
# cuComplex *x, int incx)
# cublasStatus_t cublasZscal(cublasHandle_t handle, int n,
# const cuDoubleComplex *alpha,
# cuDoubleComplex *x, int incx)
# cublasStatus_t cublasZdscal(cublasHandle_t handle, int n,
# const double *alpha,
# cuDoubleComplex *x, int incx)
cublasSscal = libcublas.cublasSscal_v2
cublasDscal = libcublas.cublasDscal_v2
cublasCscal = libcublas.cublasCscal_v2
cublasCsscal = libcublas.cublasCsscal_v2
cublasZscal = libcublas.cublasZscal_v2
cublasZdscal = libcublas.cublasZdscal_v2
for funct in [cublasSscal, cublasDscal,
cublasCscal, cublasCsscal,
cublasZscal, cublasZdscal]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_int, #n
scalar_pointer, #*alpha
memory_pointer, c_int #*x, incx
]
# cublasStatus_t cublasSswap(cublasHandle_t handle, int n, float *x,
# int incx, float *y, int incy)
# cublasStatus_t cublasDswap(cublasHandle_t handle, int n, double *x,
# int incx, double *y, int incy)
# cublasStatus_t cublasCswap(cublasHandle_t handle, int n, cuComplex *x,
# int incx, cuComplex *y, int incy)
# cublasStatus_t cublasZswap(cublasHandle_t handle, int n, cuDoubleComplex *x,
# int incx, cuDoubleComplex *y, int incy)
cublasSswap = libcublas.cublasSswap_v2
cublasDswap = libcublas.cublasDswap_v2
cublasCswap = libcublas.cublasCswap_v2
cublasZswap = libcublas.cublasZswap_v2
for funct in [cublasSswap, cublasDswap, cublasCswap, cublasZswap]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_int, #n
memory_pointer, c_int, #*x, incx
memory_pointer, c_int #*y, incy
]
## cuBLAS Level-2 Functions ##
# cublasStatus_t cublasSgbmv(cublasHandle_t handle, cublasOperation_t trans,
# int m, int n, int kl, int ku,
# const float *alpha,
# const float *A, int lda,
# const float *x, int incx,
# const float *beta,
# float *y, int incy)
# cublasStatus_t cublasDgbmv(cublasHandle_t handle, cublasOperation_t trans,
# int m, int n, int kl, int ku,
# const double *alpha,
# const double *A, int lda,
# const double *x, int incx,
# const double *beta,
# double *y, int incy)
# cublasStatus_t cublasCgbmv(cublasHandle_t handle, cublasOperation_t trans,
# int m, int n, int kl, int ku,
# const cuComplex *alpha,
# const cuComplex *A, int lda,
# const cuComplex *x, int incx,
# const cuComplex *beta,
# cuComplex *y, int incy)
# cublasStatus_t cublasZgbmv(cublasHandle_t handle, cublasOperation_t trans,
# int m, int n, int kl, int ku,
# const cuDoubleComplex *alpha,
# const cuDoubleComplex *A, int lda,
# const cuDoubleComplex *x, int incx,
# const cuDoubleComplex *beta,
# cuDoubleComplex *y, int incy)
cublasSgbmv = libcublas.cublasSgbmv_v2
cublasDgbmv = libcublas.cublasDgbmv_v2
cublasCgbmv = libcublas.cublasCgbmv_v2
cublasZgbmv = libcublas.cublasZgbmv_v2
for funct in [cublasSgbmv, cublasDgbmv, cublasCgbmv, cublasZgbmv]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_cublasOperation_t, #trans
c_int, c_int, #m, n
c_int, c_int, #kl, ku
scalar_pointer, #*alpha
memory_pointer, c_int, #*A, lda
memory_pointer, c_int, #*x, incx
scalar_pointer, #*beta
memory_pointer, c_int, #*y, incy
]
# cublasStatus_t cublasSgemv(cublasHandle_t handle, cublasOperation_t trans,
# int m, int n,
# const float *alpha,
# const float *A, int lda,
# const float *x, int incx,
# const float *beta,
# float *y, int incy)
# cublasStatus_t cublasDgemv(cublasHandle_t handle, cublasOperation_t trans,
# int m, int n,
# const double *alpha,
# const double *A, int lda,
# const double *x, int incx,
# const double *beta,
# double *y, int incy)
# cublasStatus_t cublasCgemv(cublasHandle_t handle, cublasOperation_t trans,
# int m, int n,
# const cuComplex *alpha,
# const cuComplex *A, int lda,
# const cuComplex *x, int incx,
# const cuComplex *beta,
# cuComplex *y, int incy)
# cublasStatus_t cublasZgemv(cublasHandle_t handle, cublasOperation_t trans,
# int m, int n,
# const cuDoubleComplex *alpha,
# const cuDoubleComplex *A, int lda,
# const cuDoubleComplex *x, int incx,
# const cuDoubleComplex *beta,
# cuDoubleComplex *y, int incy)
cublasSgemv = libcublas.cublasSgemv_v2
cublasDgemv = libcublas.cublasDgemv_v2
cublasCgemv = libcublas.cublasCgemv_v2
cublasZgemv = libcublas.cublasZgemv_v2
for funct in [cublasSgemv, cublasDgemv, cublasCgemv, cublasZgemv]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_cublasOperation_t, #trans
c_int, c_int, #m, n
scalar_pointer, #*alpha
memory_pointer, c_int, #*A, lda
memory_pointer, c_int, #*x, incx
scalar_pointer, #*beta
memory_pointer, c_int, #*y, incy
]
# cublasStatus_t cublasSger(cublasHandle_t handle, int m, int n,
# const float *alpha,
# const float *x, int incx,
# const float *y, int incy,
# float *A, int lda)
# cublasStatus_t cublasDger(cublasHandle_t handle, int m, int n,
# const double *alpha,
# const double *x, int incx,
# const double *y, int incy,
# double *A, int lda)
# cublasStatus_t cublasCgeru(cublasHandle_t handle, int m, int n,
# const cuComplex *alpha,
# const cuComplex *x, int incx,
# const cuComplex *y, int incy,
# cuComplex *A, int lda)
# cublasStatus_t cublasCgerc(cublasHandle_t handle, int m, int n,
# const cuComplex *alpha,
# const cuComplex *x, int incx,
# const cuComplex *y, int incy,
# cuComplex *A, int lda)
# cublasStatus_t cublasZgeru(cublasHandle_t handle, int m, int n,
# const cuDoubleComplex *alpha,
# const cuDoubleComplex *x, int incx,
# const cuDoubleComplex *y, int incy,
# cuDoubleComplex *A, int lda)
# cublasStatus_t cublasZgerc(cublasHandle_t handle, int m, int n,
# const cuDoubleComplex *alpha,
# const cuDoubleComplex *x, int incx,
# const cuDoubleComplex *y, int incy,
# cuDoubleComplex *A, int lda)
cublasSger = libcublas.cublasSger_v2
cublasDger = libcublas.cublasDger_v2
cublasCgeru = libcublas.cublasCgeru_v2
cublasCgerc = libcublas.cublasCgerc_v2
cublasZgeru = libcublas.cublasZgeru_v2
cublasZgerc = libcublas.cublasZgerc_v2
for funct in [cublasSger, cublasDger,
cublasCgeru, cublasCgerc,
cublasZgeru, cublasZgerc]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_int, c_int, #m, n
scalar_pointer, #*alpha
memory_pointer, c_int, #*x, incx
memory_pointer, c_int, #*y, incy
memory_pointer, c_int #*A, lda
]
# cublasStatus_t cublasSsbmv(cublasHandle_t handle, cublasFillMode_t uplo,
# int n, int k, const float *alpha,
# const float *A, int lda,
# const float *x, int incx,
# const float *beta, float *y, int incy)
# cublasStatus_t cublasDsbmv(cublasHandle_t handle, cublasFillMode_t uplo,
# int n, int k, const double *alpha,
# const double *A, int lda,
# const double *x, int incx,
# const double *beta, double *y, int incy)
cublasSsbmv = libcublas.cublasSsbmv_v2
cublasDsbmv = libcublas.cublasDsbmv_v2
for funct in [cublasSsbmv, cublasDsbmv]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_cublasFillMode_t, #uplo
c_int, c_int, #n, k
scalar_pointer, #*alpha
memory_pointer, c_int, #*A, lda
memory_pointer, c_int, #*x, incx
scalar_pointer, #*beta
memory_pointer, c_int #*y, incy
]
# cublasStatus_t cublasSspmv(cublasHandle_t handle, cublasFillMode_t uplo,
# int n, const float *alpha, const float *AP,
# const float *x, int incx, const float *beta,
# float *y, int incy)
# cublasStatus_t cublasDspmv(cublasHandle_t handle, cublasFillMode_t uplo,
# int n, const double *alpha, const double *AP,
# const double *x, int incx, const double *beta,
# double *y, int incy)
cublasSspmv = libcublas.cublasSspmv_v2
cublasDspmv = libcublas.cublasDspmv_v2
for funct in [cublasSspmv, cublasDspmv]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_cublasFillMode_t, #uplo
c_int, #n
scalar_pointer, #*alpha
memory_pointer, #*AP
memory_pointer, c_int, #*x, incx
scalar_pointer, #*beta
memory_pointer, c_int #*y, incy
]
# cublasStatus_t cublasSspr(cublasHandle_t handle, cublasFillMode_t uplo,
# int n, const float *alpha,
# const float *x, int incx, float *AP)
# cublasStatus_t cublasDspr(cublasHandle_t handle, cublasFillMode_t uplo,
# int n, const double *alpha,
# const double *x, int incx, double *AP)
cublasSspr = libcublas.cublasSspr_v2
cublasDspr = libcublas.cublasDspr_v2
for funct in [cublasSspr, cublasDspr]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_cublasFillMode_t, #uplo
c_int, #n
scalar_pointer, #*alpha
memory_pointer, c_int, #*x, incx
memory_pointer #*AP
]
# cublasStatus_t cublasSspr2(cublasHandle_t handle, cublasFillMode_t uplo,
# int n, const float *alpha,
# const float *x, int incx,
# const float *y, int incy, float *AP)
# cublasStatus_t cublasDspr2(cublasHandle_t handle, cublasFillMode_t uplo,
# int n, const double *alpha,
# const double *x, int incx,
# const double *y, int incy, double *AP)
cublasSspr2 = libcublas.cublasSspr2_v2
cublasDspr2 = libcublas.cublasDspr2_v2
for funct in [cublasSspr2, cublasDspr2]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_cublasFillMode_t, #uplo
c_int, #n
scalar_pointer, #*alpha
memory_pointer, c_int, #*x, incx
memory_pointer, c_int, #*y, incy
memory_pointer #*AP
]
# cublasStatus_t cublasSsymv(cublasHandle_t handle, cublasFillMode_t uplo,
# int n, const float *alpha,
# const float *A, int lda,
# const float *x, int incx, const float *beta,
# float *y, int incy)
# cublasStatus_t cublasDsymv(cublasHandle_t handle, cublasFillMode_t uplo,
# int n, const double *alpha,
# const double *A, int lda,
# const double *x, int incx, const double *beta,
# double *y, int incy)
# cublasStatus_t cublasCsymv(cublasHandle_t handle, cublasFillMode_t uplo,
# int n, const cuComplex *alpha, /* host or device pointer */
# const cuComplex *A, int lda,
# const cuComplex *x, int incx, const cuComplex *beta,
# cuComplex *y, int incy)
# cublasStatus_t cublasZsymv(cublasHandle_t handle, cublasFillMode_t uplo,
# int n, const cuDoubleComplex *alpha,
# const cuDoubleComplex *A, int lda,
# const cuDoubleComplex *x, int incx, const cuDoubleComplex *beta,
# cuDoubleComplex *y, int incy)
cublasSsymv = libcublas.cublasSsymv_v2
cublasDsymv = libcublas.cublasDsymv_v2
cublasCsymv = libcublas.cublasCsymv_v2
cublasZsymv = libcublas.cublasZsymv_v2
for funct in [cublasSsymv, cublasDsymv, cublasCsymv, cublasZsymv]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_cublasFillMode_t, #uplo
c_int, #n
scalar_pointer, #*alpha
memory_pointer, c_int, #*A, lda
memory_pointer, c_int, #*x, incx
scalar_pointer, #*beta
memory_pointer, c_int #*y, incy
]
# cublasStatus_t cublasSsyr(cublasHandle_t handle, cublasFillMode_t uplo,
# int n, const float *alpha,
# const float *x, int incx, float *A, int lda)
# cublasStatus_t cublasDsyr(cublasHandle_t handle, cublasFillMode_t uplo,
# int n, const double *alpha,
# const double *x, int incx, double *A, int lda)
# cublasStatus_t cublasCsyr(cublasHandle_t handle, cublasFillMode_t uplo,
# int n, const cuComplex *alpha,
# const cuComplex *x, int incx, cuComplex *A, int lda)
# cublasStatus_t cublasZsyr(cublasHandle_t handle, cublasFillMode_t uplo,
# int n, const cuDoubleComplex *alpha,
# const cuDoubleComplex *x, int incx, cuDoubleComplex *A, int lda)
cublasSsyr = libcublas.cublasSsyr_v2
cublasDsyr = libcublas.cublasDsyr_v2
cublasCsyr = libcublas.cublasCsyr_v2
cublasZsyr = libcublas.cublasZsyr_v2
for funct in [cublasSsyr, cublasDsyr, cublasCsyr, cublasZsyr]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_cublasFillMode_t, #uplo
c_int, #n
scalar_pointer, #*alpha
memory_pointer, c_int, #*x, incx
memory_pointer, c_int #*A, lda
]
# cublasStatus_t cublasSsyr2(cublasHandle_t handle, cublasFillMode_t uplo, int n,
# const float *alpha, const float *x, int incx,
# const float *y, int incy, float *A, int lda
# cublasStatus_t cublasDsyr2(cublasHandle_t handle, cublasFillMode_t uplo, int n,
# const double *alpha, const double *x, int incx,
# const double *y, int incy, double *A, int lda
# cublasStatus_t cublasCsyr2(cublasHandle_t handle, cublasFillMode_t uplo, int n,
# const cuComplex *alpha, const cuComplex *x, int incx,
# const cuComplex *y, int incy, cuComplex *A, int lda
# cublasStatus_t cublasZsyr2(cublasHandle_t handle, cublasFillMode_t uplo, int n,
# const cuDoubleComplex *alpha, const cuDoubleComplex *x, int incx,
# const cuDoubleComplex *y, int incy, cuDoubleComplex *A, int lda
cublasSsyr2 = libcublas.cublasSsyr2_v2
cublasDsyr2 = libcublas.cublasDsyr2_v2
cublasCsyr2 = libcublas.cublasCsyr2_v2
cublasZsyr2 = libcublas.cublasZsyr2_v2
for funct in [cublasSsyr2, cublasDsyr2, cublasCsyr2, cublasZsyr2]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_cublasFillMode_t, #uplo
c_int, #n
scalar_pointer, #*alpha
memory_pointer, c_int, #*x, incx
memory_pointer, c_int, #*y, incy
memory_pointer, c_int #*A, lda
]
# cublasStatus_t cublasStbmv(cublasHandle_t handle, cublasFillMode_t uplo,
# cublasOperation_t trans, cublasDiagType_t diag,
# int n, int k, const float *A, int lda,
# float *x, int incx)
# cublasStatus_t cublasDtbmv(cublasHandle_t handle, cublasFillMode_t uplo,
# cublasOperation_t trans, cublasDiagType_t diag,
# int n, int k, const double *A, int lda,
# double *x, int incx)
# cublasStatus_t cublasCtbmv(cublasHandle_t handle, cublasFillMode_t uplo,
# cublasOperation_t trans, cublasDiagType_t diag,
# int n, int k, const cuComplex *A, int lda,
# cuComplex *x, int incx)
# cublasStatus_t cublasZtbmv(cublasHandle_t handle, cublasFillMode_t uplo,
# cublasOperation_t trans, cublasDiagType_t diag,
# int n, int k, const cuDoubleComplex *A, int lda,
# cuDoubleComplex *x, int incx)
cublasStbmv = libcublas.cublasStbmv_v2
cublasDtbmv = libcublas.cublasDtbmv_v2
cublasCtbmv = libcublas.cublasCtbmv_v2
cublasZtbmv = libcublas.cublasZtbmv_v2
for funct in [cublasStbmv, cublasDtbmv, cublasCtbmv, cublasZtbmv]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_cublasFillMode_t, #uplo
c_cublasOperation_t, #trans
c_cublasDiagType_t, #diag
c_int, c_int, #n, k
memory_pointer, c_int, #*A, lda
memory_pointer, c_int #*x, incx
]
# cublasStatus_t cublasStbsv(cublasHandle_t handle, cublasFillMode_t uplo,
# cublasOperation_t trans, cublasDiagType_t diag,
# int n, int k, const float *A, int lda,
# float *x, int incx)
# cublasStatus_t cublasDtbsv(cublasHandle_t handle, cublasFillMode_t uplo,
# cublasOperation_t trans, cublasDiagType_t diag,
# int n, int k, const double *A, int lda,
# double *x, int incx)
# cublasStatus_t cublasCtbsv(cublasHandle_t handle, cublasFillMode_t uplo,
# cublasOperation_t trans, cublasDiagType_t diag,
# int n, int k, const cuComplex *A, int lda,
# cuComplex *x, int incx)
# cublasStatus_t cublasZtbsv(cublasHandle_t handle, cublasFillMode_t uplo,
# cublasOperation_t trans, cublasDiagType_t diag,
# int n, int k, const cuDoubleComplex *A, int lda,
# cuDoubleComplex *x, int incx)
cublasStbsv = libcublas.cublasStbsv_v2
cublasDtbsv = libcublas.cublasDtbsv_v2
cublasCtbsv = libcublas.cublasCtbsv_v2
cublasZtbsv = libcublas.cublasZtbsv_v2
for funct in [cublasStbsv, cublasDtbsv, cublasCtbsv, cublasZtbsv]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_cublasFillMode_t, #uplo
c_cublasOperation_t, #trans
c_cublasDiagType_t, #diag
c_int, c_int, #n, k
memory_pointer, c_int, #*A, lda
memory_pointer, c_int #*x, incx
]
# cublasStatus_t cublasStpmv(cublasHandle_t handle, cublasFillMode_t uplo,
# cublasOperation_t trans, cublasDiagType_t diag,
# int n, const float *AP,
# float *x, int incx)
# cublasStatus_t cublasDtpmv(cublasHandle_t handle, cublasFillMode_t uplo,
# cublasOperation_t trans, cublasDiagType_t diag,
# int n, const double *AP,
# double *x, int incx)
# cublasStatus_t cublasCtpmv(cublasHandle_t handle, cublasFillMode_t uplo,
# cublasOperation_t trans, cublasDiagType_t diag,
# int n, const cuComplex *AP,
# cuComplex *x, int incx)
# cublasStatus_t cublasZtpmv(cublasHandle_t handle, cublasFillMode_t uplo,
# cublasOperation_t trans, cublasDiagType_t diag,
# int n, const cuDoubleComplex *AP,
# cuDoubleComplex *x, int incx)
cublasStpmv = libcublas.cublasStpmv_v2
cublasDtpmv = libcublas.cublasDtpmv_v2
cublasCtpmv = libcublas.cublasCtpmv_v2
cublasZtpmv = libcublas.cublasZtpmv_v2
for funct in [cublasStpmv, cublasDtpmv, cublasCtpmv, cublasZtpmv]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_cublasFillMode_t, #uplo
c_cublasOperation_t, #trans
c_cublasDiagType_t, #diag
c_int, #n
memory_pointer, #*AP
memory_pointer, c_int #*x, incx
]
# cublasStatus_t cublasStpsv(cublasHandle_t handle, cublasFillMode_t uplo,
# cublasOperation_t trans, cublasDiagType_t diag,
# int n, const float *AP,
# #float *x, int incx)
# cublasStatus_t cublasDtpsv(cublasHandle_t handle, cublasFillMode_t uplo,
# cublasOperation_t trans, cublasDiagType_t diag,
# int n, const double *AP,
# double *x, int incx)
# cublasStatus_t cublasCtpsv(cublasHandle_t handle, cublasFillMode_t uplo,
# cublasOperation_t trans, cublasDiagType_t diag,
# int n, const cuComplex *AP,
# cuComplex *x, int incx)
# cublasStatus_t cublasZtpsv(cublasHandle_t handle, cublasFillMode_t uplo,
# cublasOperation_t trans, cublasDiagType_t diag,
# int n, const cuDoubleComplex *AP,
# cuDoubleComplex *x, int incx)
cublasStpsv = libcublas.cublasStpsv_v2
cublasDtpsv = libcublas.cublasDtpsv_v2
cublasCtpsv = libcublas.cublasCtpsv_v2
cublasZtpsv = libcublas.cublasZtpsv_v2
for funct in [cublasStpsv, cublasDtpsv, cublasCtpsv, cublasZtpsv]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_cublasFillMode_t, #uplo
c_cublasOperation_t, #trans
c_cublasDiagType_t, #diag
c_int, #n
memory_pointer, #*AP
memory_pointer, c_int #*x, incx
]
# cublasStatus_t cublasStrmv(cublasHandle_t handle, cublasFillMode_t uplo,
# cublasOperation_t trans, cublasDiagType_t diag,
# int n, const float *A, int lda,
# float *x, int incx)
# cublasStatus_t cublasDtrmv(cublasHandle_t handle, cublasFillMode_t uplo,
# cublasOperation_t trans, cublasDiagType_t diag,
# int n, const double *A, int lda,
# double *x, int incx)
# cublasStatus_t cublasCtrmv(cublasHandle_t handle, cublasFillMode_t uplo,
# cublasOperation_t trans, cublasDiagType_t diag,
# int n, const cuComplex *A, int lda,
# cuComplex *x, int incx)
# cublasStatus_t cublasZtrmv(cublasHandle_t handle, cublasFillMode_t uplo,
# cublasOperation_t trans, cublasDiagType_t diag,
# int n, const cuDoubleComplex *A, int lda,
# cuDoubleComplex *x, int incx)
cublasStrmv = libcublas.cublasStrmv_v2
cublasDtrmv = libcublas.cublasDtrmv_v2
cublasCtrmv = libcublas.cublasCtrmv_v2
cublasZtrmv = libcublas.cublasZtrmv_v2
for funct in [cublasStrmv, cublasDtrmv, cublasCtrmv, cublasZtrmv]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_cublasFillMode_t, #uplo
c_cublasOperation_t, #trans
c_cublasDiagType_t, #diag
c_int, #n
memory_pointer, c_int, #*A, lda
memory_pointer, c_int #*x, incx
]
# cublasStatus_t cublasStrsv(cublasHandle_t handle, cublasFillMode_t uplo,
# cublasOperation_t trans, cublasDiagType_t diag,
# int n, const float *A, int lda,
# float *x, int incx)
# cublasStatus_t cublasDtrsv(cublasHandle_t handle, cublasFillMode_t uplo,
# cublasOperation_t trans, cublasDiagType_t diag,
# int n, const double *A, int lda,
# double *x, int incx)
# cublasStatus_t cublasCtrsv(cublasHandle_t handle, cublasFillMode_t uplo,
# cublasOperation_t trans, cublasDiagType_t diag,
# int n, const cuComplex *A, int lda,
# cuComplex *x, int incx)
# cublasStatus_t cublasZtrsv(cublasHandle_t handle, cublasFillMode_t uplo,
# cublasOperation_t trans, cublasDiagType_t diag,
# int n, const cuDoubleComplex *A, int lda,
# cuDoubleComplex *x, int incx)
cublasStrsv = libcublas.cublasStrsv_v2
cublasDtrsv = libcublas.cublasDtrsv_v2
cublasCtrsv = libcublas.cublasCtrsv_v2
cublasZtrsv = libcublas.cublasZtrsv_v2
for funct in [cublasStrsv, cublasDtrsv, cublasCtrsv, cublasZtrsv]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_cublasFillMode_t, #uplo
c_cublasOperation_t, #trans
c_cublasDiagType_t, #diag
c_int, #n
memory_pointer, c_int, #*A, lda
memory_pointer, c_int #*x, incx
]
# cublasStatus_t cublasChemv(cublasHandle_t handle, cublasFillMode_t uplo,
# int n, const cuComplex *alpha,
# const cuComplex *A, int lda,
# const cuComplex *x, int incx,
# const cuComplex *beta,
# cuComplex *y, int incy)
# cublasStatus_t cublasZhemv(cublasHandle_t handle, cublasFillMode_t uplo,
# int n, const cuDoubleComplex *alpha,
# const cuDoubleComplex *A, int lda,
# const cuDoubleComplex *x, int incx,
# const cuDoubleComplex *beta,
# cuDoubleComplex *y, int incy)
cublasChemv = libcublas.cublasChemv_v2
cublasZhemv = libcublas.cublasZhemv_v2
for funct in [cublasChemv, cublasZhemv]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_cublasFillMode_t, #uplo
c_int, #n
scalar_pointer, #*alpha
memory_pointer, c_int, #*A, lda
memory_pointer, c_int, #*x, incx
scalar_pointer, #*beta
memory_pointer, c_int #*y, incy
]
# cublasStatus_t cublasChbmv(cublasHandle_t handle, cublasFillMode_t uplo,
# int n, int k, const cuComplex *alpha,
# const cuComplex *A, int lda,
# const cuComplex *x, int incx,
# const cuComplex *beta,
# cuComplex *y, int incy)
# cublasStatus_t cublasZhbmv(cublasHandle_t handle, cublasFillMode_t uplo,
# int n, int k, const cuDoubleComplex *alpha,
# const cuDoubleComplex *A, int lda,
# const cuDoubleComplex *x, int incx,
# const cuDoubleComplex *beta,
# cuDoubleComplex *y, int incy)
cublasChbmv = libcublas.cublasChbmv_v2
cublasZhbmv = libcublas.cublasZhbmv_v2
for funct in [cublasChbmv, cublasZhbmv]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_cublasFillMode_t, #uplo
c_int, c_int, #n, k
scalar_pointer, #*alpha
memory_pointer, c_int, #*A, lda
memory_pointer, c_int, #*x, incx
scalar_pointer, #*beta
memory_pointer, c_int #*y, incy
]
# cublasStatus_t cublasChpmv(cublasHandle_t handle, cublasFillMode_t uplo,
# int n, const cuComplex *alpha,
# const cuComplex *AP,
# const cuComplex *x, int incx,
# const cuComplex *beta,
# cuComplex *y, int incy)
# cublasStatus_t cublasZhpmv(cublasHandle_t handle, cublasFillMode_t uplo,
# int n, const cuDoubleComplex *alpha,
# const cuDoubleComplex *AP,
# const cuDoubleComplex *x, int incx,
# const cuDoubleComplex *beta,
# cuDoubleComplex *y, int incy)
cublasChpmv = libcublas.cublasChpmv_v2
cublasZhpmv = libcublas.cublasZhpmv_v2
for funct in [cublasChpmv, cublasZhpmv]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_cublasFillMode_t, #uplo
c_int, #n
scalar_pointer, #*alpha
memory_pointer, #*AP
memory_pointer, c_int, #*x, incx
scalar_pointer, #*beta
memory_pointer, c_int #*y, incy
]
# cublasStatus_t cublasCher(cublasHandle_t handle, cublasFillMode_t uplo,
# int n, const float *alpha,
# const cuComplex *x, int incx,
# cuComplex *A, int lda)
# cublasStatus_t cublasZher(cublasHandle_t handle, cublasFillMode_t uplo,
# int n, const double *alpha,
# const cuDoubleComplex *x, int incx,
# cuDoubleComplex *A, int lda)
cublasCher = libcublas.cublasCher_v2
cublasZher = libcublas.cublasZher_v2
for funct in [cublasCher, cublasZher]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_cublasFillMode_t, #uplo
c_int, #n
scalar_pointer, #*alpha
memory_pointer, c_int, #*x, incx
memory_pointer, c_int #*A, lda
]
# cublasStatus_t cublasCher2(cublasHandle_t handle, cublasFillMode_t uplo,
# int n, const cuComplex *alpha,
# const cuComplex *x, int incx,
# const cuComplex *y, int incy,
# cuComplex *A, int lda)
# cublasStatus_t cublasZher2(cublasHandle_t handle, cublasFillMode_t uplo,
# int n, const cuDoubleComplex *alpha,
# const cuDoubleComplex *x, int incx,
# const cuDoubleComplex *y, int incy,
# cuDoubleComplex *A, int lda)
cublasCher2 = libcublas.cublasCher2_v2
cublasZher2 = libcublas.cublasZher2_v2
for funct in [cublasCher2, cublasZher2]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_cublasFillMode_t, #uplo
c_int, #n
scalar_pointer, #*alpha
memory_pointer, c_int, #*x, incx
memory_pointer, c_int, #*y, incy
memory_pointer, c_int #*A, lda
]
# cublasStatus_t cublasChpr(cublasHandle_t handle, cublasFillMode_t uplo,
# int n, const float *alpha,
# const cuComplex *x, int incx,
# cuComplex *AP)
# cublasStatus_t cublasZhpr(cublasHandle_t handle, cublasFillMode_t uplo,
# int n, const double *alpha,
# const cuDoubleComplex *x, int incx,
# cuDoubleComplex *AP)
cublasChpr = libcublas.cublasChpr_v2
cublasZhpr = libcublas.cublasZhpr_v2
for funct in [cublasChpr, cublasZhpr]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_cublasFillMode_t, #uplo
c_int, #n
scalar_pointer, #alpha
memory_pointer, c_int, #*x, incx
memory_pointer #*AP
]
# cublasStatus_t cublasChpr2(cublasHandle_t handle, cublasFillMode_t uplo,
# int n, const cuComplex *alpha,
# const cuComplex *x, int incx,
# const cuComplex *y, int incy,
# cuComplex *AP)
# cublasStatus_t cublasZhpr2(cublasHandle_t handle, cublasFillMode_t uplo,
# int n, const cuDoubleComplex *alpha,
# const cuDoubleComplex *x, int incx,
# const cuDoubleComplex *y, int incy,
# cuDoubleComplex *AP)
cublasChpr2 = libcublas.cublasChpr2_v2
cublasZhpr2 = libcublas.cublasZhpr2_v2
for funct in [cublasChpr2, cublasZhpr2]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_cublasFillMode_t, #uplo
c_int, #n
scalar_pointer, #*alpha
memory_pointer, c_int, #*x, incx
memory_pointer, c_int, #*y, incy
memory_pointer #*AP
]
## cuBLAS Level-3 Functions ##
# cublasStatus_t cublasSgemm(cublasHandle_t handle,
# cublasOperation_t transa, cublasOperation_t transb,
# int m, int n, int k,
# const float *alpha,
# const float *A, int lda,
# const float *B, int ldb,
# const float *beta,
# float *C, int ldc)
# cublasStatus_t cublasDgemm(cublasHandle_t handle,
# cublasOperation_t transa, cublasOperation_t transb,
# int m, int n, int k,
# const double *alpha,
# const double *A, int lda,
# const double *B, int ldb,
# const double *beta,
# double *C, int ldc)
# cublasStatus_t cublasCgemm(cublasHandle_t handle,
# cublasOperation_t transa, cublasOperation_t transb,
# int m, int n, int k,
# const cuComplex *alpha,
# const cuComplex *A, int lda,
# const cuComplex *B, int ldb,
# const cuComplex *beta,
# cuComplex *C, int ldc)
# cublasStatus_t cublasZgemm(cublasHandle_t handle,
# cublasOperation_t transa, cublasOperation_t transb,
# int m, int n, int k,
# const cuDoubleComplex *alpha,
# const cuDoubleComplex *A, int lda,
# const cuDoubleComplex *B, int ldb,
# const cuDoubleComplex *beta,
# cuDoubleComplex *C, int ldc)
cublasSgemm = libcublas.cublasSgemm_v2
cublasDgemm = libcublas.cublasDgemm_v2
cublasCgemm = libcublas.cublasCgemm_v2
cublasZgemm = libcublas.cublasZgemm_v2
for funct in [cublasSgemm, cublasDgemm, cublasCgemm, cublasZgemm]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_cublasOperation_t, #transa
c_cublasOperation_t, #transb
c_int, c_int, c_int, #m, n, k
scalar_pointer, #*alpha
memory_pointer, c_int, #*A, lda
memory_pointer, c_int, #*B, ldb
scalar_pointer, #*beta
memory_pointer, c_int #*C, ldc
]
# cublasStatus_t cublasSgemmBatched(cublasHandle_t handle,
# cublasOperation_t transa, cublasOperation_t transb,
# int m, int n, int k,
# const float *alpha,
# const float *Aarray[], int lda,
# const float *Barray[], int ldb,
# const float *beta,
# float *Carray[], int ldc, int batchCount)
# cublasStatus_t cublasDgemmBatched(cublasHandle_t handle,
# cublasOperation_t transa, cublasOperation_t transb,
# int m, int n, int k,
# const double *alpha,
# const double *Aarray[], int lda,
# const double *Barray[], int ldb,
# const double *beta,
# double *Carray[], int ldc, int batchCount)
# cublasStatus_t cublasCgemmBatched(cublasHandle_t handle,
# cublasOperation_t transa, cublasOperation_t transb,
# int m, int n, int k,
# const cuComplex *alpha,
# const cuComplex *Aarray[], int lda,
# const cuComplex *Barray[], int ldb,
# const cuComplex *beta,
# cuComplex *Carray[], int ldc, int batchCount)
# cublasStatus_t cublasZgemmBatched(cublasHandle_t handle,
# cublasOperation_t transa, cublasOperation_t transb,
# int m, int n, int k,
# const cuDoubleComplex *alpha,
# const cuDoubleComplex *Aarray[], int lda,
# const cuDoubleComplex *Barray[], int ldb,
# const cuDoubleComplex *beta,
# cuDoubleComplex *Carray[], int ldc, int batchCount)
cublasSgemmBatched = libcublas.cublasSgemmBatched
cublasDgemmBatched = libcublas.cublasDgemmBatched
cublasCgemmBatched = libcublas.cublasCgemmBatched
cublasZgemmBatched = libcublas.cublasZgemmBatched
for funct in [cublasSgemmBatched, cublasDgemmBatched,
cublasCgemmBatched, cublasZgemmBatched]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_cublasOperation_t, #transa
c_cublasOperation_t, #transb
c_int, c_int, c_int, #m, n, k
scalar_pointer, #*alpha
array_pointer, c_int, #*A[], lda
array_pointer, c_int, #*B[], ldb
scalar_pointer, #*beta
array_pointer, c_int, #*C[], ldc
c_int #batchCount
]
# cublasStatus_t cublasSsymm(cublasHandle_t handle,
# cublasSideMode_t side, cublasFillMode_t uplo,
# int m, int n,
# const float *alpha,
# const float *A, int lda,
# const float *B, int ldb,
# const float *beta,
# float *C, int ldc)
# cublasStatus_t cublasDsymm(cublasHandle_t handle,
# cublasSideMode_t side, cublasFillMode_t uplo,
# int m, int n,
# const double *alpha,
# const double *A, int lda,
# const double *B, int ldb,
# const double *beta,
# double *C, int ldc)
# cublasStatus_t cublasCsymm(cublasHandle_t handle,
# cublasSideMode_t side, cublasFillMode_t uplo,
# int m, int n,
# const cuComplex *alpha,
# const cuComplex *A, int lda,
# const cuComplex *B, int ldb,
# const cuComplex *beta,
# cuComplex *C, int ldc)
# cublasStatus_t cublasZsymm(cublasHandle_t handle,
# cublasSideMode_t side, cublasFillMode_t uplo,
# int m, int n,
# const cuDoubleComplex *alpha,
# const cuDoubleComplex *A, int lda,
# const cuDoubleComplex *B, int ldb,
# const cuDoubleComplex *beta,
# cuDoubleComplex *C, int ldc)
cublasSsymm = libcublas.cublasSsymm_v2
cublasDsymm = libcublas.cublasDsymm_v2
cublasCsymm = libcublas.cublasCsymm_v2
cublasZsymm = libcublas.cublasZsymm_v2
for funct in [cublasSsymm, cublasDsymm, cublasCsymm, cublasZsymm]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_cublasSideMode_t, #side
c_cublasFillMode_t, #uplo
c_int, c_int, #m, n
scalar_pointer, #*alpha
memory_pointer, c_int, #*A, lda
memory_pointer, c_int, #*B, ldb
scalar_pointer, #*beta
memory_pointer, c_int #*C, ldc
]
# cublasStatus_t cublasSsyrk(cublasHandle_t handle,
# cublasFillMode_t uplo, cublasOperation_t trans,
# int n, int k,
# const float *alpha,
# const float *A, int lda,
# const float *beta,
# float *C, int ldc)
# cublasStatus_t cublasDsyrk(cublasHandle_t handle,
# cublasFillMode_t uplo, cublasOperation_t trans,
# int n, int k,
# const double *alpha,
# const double *A, int lda,
# const double *beta,
# double *C, int ldc)
# cublasStatus_t cublasCsyrk(cublasHandle_t handle,
# cublasFillMode_t uplo, cublasOperation_t trans,
# int n, int k,
# const cuComplex *alpha,
# const cuComplex *A, int lda,
# const cuComplex *beta,
# cuComplex *C, int ldc)
# cublasStatus_t cublasZsyrk(cublasHandle_t handle,
# cublasFillMode_t uplo, cublasOperation_t trans,
# int n, int k,
# const cuDoubleComplex *alpha,
# const cuDoubleComplex *A, int lda,
# const cuDoubleComplex *beta,
# cuDoubleComplex *C, int ldc)
cublasSsyrk = libcublas.cublasSsyrk_v2
cublasDsyrk = libcublas.cublasDsyrk_v2
cublasCsyrk = libcublas.cublasCsyrk_v2
cublasZsyrk = libcublas.cublasZsyrk_v2
for funct in [cublasSsyrk, cublasDsyrk, cublasCsyrk, cublasZsyrk]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_cublasFillMode_t, #uplo
c_cublasOperation_t, #trans
c_int, c_int, #n, k
scalar_pointer, #*alpha
memory_pointer, c_int, #*A, lda
scalar_pointer, #*beta
memory_pointer, c_int #*C, ldc
]
# cublasStatus_t cublasSsyr2k(cublasHandle_t handle,
# cublasFillMode_t uplo, cublasOperation_t trans,
# int n, int k,
# const float *alpha,
# const float *A, int lda,
# const float *B, int ldb,
# const float *beta,
# float *C, int ldc)
# cublasStatus_t cublasDsyr2k(cublasHandle_t handle,
# cublasFillMode_t uplo, cublasOperation_t trans,
# int n, int k,
# const double *alpha,
# const double *A, int lda,
# const double *B, int ldb,
# const double *beta,
# double *C, int ldc)
# cublasStatus_t cublasCsyr2k(cublasHandle_t handle,
# cublasFillMode_t uplo, cublasOperation_t trans,
# int n, int k,
# const cuComplex *alpha,
# const cuComplex *A, int lda,
# const cuComplex *B, int ldb,
# const cuComplex *beta,
# cuComplex *C, int ldc)
# cublasStatus_t cublasZsyr2k(cublasHandle_t handle,
# cublasFillMode_t uplo, cublasOperation_t trans,
# int n, int k,
# const cuDoubleComplex *alpha,
# const cuDoubleComplex *A, int lda,
# const cuDoubleComplex *B, int ldb,
# const cuDoubleComplex *beta,
# cuDoubleComplex *C, int ldc)
cublasSsyr2k = libcublas.cublasSsyr2k_v2
cublasDsyr2k = libcublas.cublasDsyr2k_v2
cublasCsyr2k = libcublas.cublasCsyr2k_v2
cublasZsyr2k = libcublas.cublasZsyr2k_v2
for funct in [cublasSsyr2k, cublasDsyr2k, cublasCsyr2k, cublasZsyr2k]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_cublasFillMode_t, #uplo
c_cublasOperation_t, #trans
c_int, c_int, #n, k
scalar_pointer, #*alpha
memory_pointer, c_int, #*A, lda
memory_pointer, c_int, #*B, ldb
scalar_pointer, #*beta
memory_pointer, c_int #*C, ldc
]
# cublasStatus_t cublasSsyrkx(cublasHandle_t handle,
# cublasFillMode_t uplo, cublasOperation_t trans,
# int n, int k,
# const float *alpha,
# const float *A, int lda,
# const float *B, int ldb,
# const float *beta,
# float *C, int ldc)
# cublasStatus_t cublasDsyrkx(cublasHandle_t handle,
# cublasFillMode_t uplo, cublasOperation_t trans,
# int n, int k,
# const double *alpha,
# const double *A, int lda,
# const double *B, int ldb,
# const double *beta,
# double *C, int ldc)
# cublasStatus_t cublasCsyrkx(cublasHandle_t handle,
# cublasFillMode_t uplo, cublasOperation_t trans,
# int n, int k,
# const cuComplex *alpha,
# const cuComplex *A, int lda,
# const cuComplex *B, int ldb,
# const cuComplex *beta,
# cuComplex *C, int ldc)
# cublasStatus_t cublasZsyrkx(cublasHandle_t handle,
# cublasFillMode_t uplo, cublasOperation_t trans,
# int n, int k,
# const cuDoubleComplex *alpha,
# const cuDoubleComplex *A, int lda,
# const cuDoubleComplex *B, int ldb,
# const cuDoubleComplex *beta,
# cuDoubleComplex *C, int ldc)
cublasSsyrkx = libcublas.cublasSsyrkx
cublasDsyrkx = libcublas.cublasDsyrkx
cublasCsyrkx = libcublas.cublasCsyrkx
cublasZsyrkx = libcublas.cublasZsyrkx
for funct in [cublasSsyrkx, cublasDsyrkx, cublasCsyrkx, cublasZsyrkx]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_cublasFillMode_t, #uplo
c_cublasOperation_t, #trans
c_int, c_int, #n, k
scalar_pointer, #*alpha
memory_pointer, c_int, #*A, lda
memory_pointer, c_int, #*B, ldb
scalar_pointer, #*beta
memory_pointer, c_int #*C, ldc
]
# cublasStatus_t cublasStrmm(cublasHandle_t handle,
# cublasSideMode_t side, cublasFillMode_t uplo,
# cublasOperation_t trans, cublasDiagType_t diag,
# int m, int n,
# const float *alpha,
# const float *A, int lda,
# const float *B, int ldb,
# float *C, int ldc)
# cublasStatus_t cublasDtrmm(cublasHandle_t handle,
# cublasSideMode_t side, cublasFillMode_t uplo,
# cublasOperation_t trans, cublasDiagType_t diag,
# int m, int n,
# const double *alpha,
# const double *A, int lda,
# const double *B, int ldb,
# double *C, int ldc)
# cublasStatus_t cublasCtrmm(cublasHandle_t handle,
# cublasSideMode_t side, cublasFillMode_t uplo,
# cublasOperation_t trans, cublasDiagType_t diag,
# int m, int n,
# const cuComplex *alpha,
# const cuComplex *A, int lda,
# const cuComplex *B, int ldb,
# cuComplex *C, int ldc)
# cublasStatus_t cublasZtrmm(cublasHandle_t handle,
# cublasSideMode_t side, cublasFillMode_t uplo,
# cublasOperation_t trans, cublasDiagType_t diag,
# int m, int n,
# const cuDoubleComplex *alpha,
# const cuDoubleComplex *A, int lda,
# const cuDoubleComplex *B, int ldb,
# cuDoubleComplex *C, int ldc)
cublasStrmm = libcublas.cublasStrmm_v2
cublasDtrmm = libcublas.cublasDtrmm_v2
cublasCtrmm = libcublas.cublasCtrmm_v2
cublasZtrmm = libcublas.cublasZtrmm_v2
for funct in [cublasStrmm, cublasDtrmm, cublasCtrmm, cublasZtrmm]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_cublasSideMode_t, #side
c_cublasFillMode_t, #uplo
c_cublasOperation_t, #trans
c_cublasDiagType_t, #diag
c_int, c_int, #m, n
scalar_pointer, #*alpha
memory_pointer, c_int, #*A, lda
memory_pointer, c_int, #*B, ldb
memory_pointer, c_int #*C, ldc
]
# cublasStatus_t cublasStrsm(cublasHandle_t handle,
# cublasSideMode_t side, cublasFillMode_t uplo,
# cublasOperation_t trans, cublasDiagType_t diag,
# int m, int n,
# const float *alpha,
# const float *A, int lda,
# float *B, int ldb)
# cublasStatus_t cublasDtrsm(cublasHandle_t handle,
# cublasSideMode_t side, cublasFillMode_t uplo,
# cublasOperation_t trans, cublasDiagType_t diag,
# int m, int n,
# const double *alpha,
# const double *A, int lda,
# double *B, int ldb)
# cublasStatus_t cublasCtrsm(cublasHandle_t handle,
# cublasSideMode_t side, cublasFillMode_t uplo,
# cublasOperation_t trans, cublasDiagType_t diag,
# int m, int n,
# const cuComplex *alpha,
# const cuComplex *A, int lda,
# cuComplex *B, int ldb)
# cublasStatus_t cublasZtrsm(cublasHandle_t handle,
# cublasSideMode_t side, cublasFillMode_t uplo,
# cublasOperation_t trans, cublasDiagType_t diag,
# int m, int n,
# const cuDoubleComplex *alpha,
# const cuDoubleComplex *A, int lda,
# cuDoubleComplex *B, int ldb)
cublasStrsm = libcublas.cublasStrsm_v2
cublasDtrsm = libcublas.cublasDtrsm_v2
cublasCtrsm = libcublas.cublasCtrsm_v2
cublasZtrsm = libcublas.cublasZtrsm_v2
for funct in [cublasStrsm, cublasDtrsm, cublasCtrsm, cublasZtrsm]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_cublasSideMode_t, #side
c_cublasFillMode_t, #uplo
c_cublasOperation_t, #trans
c_cublasDiagType_t, #diag
c_int, c_int, #m, n
scalar_pointer, #*alpha
memory_pointer, c_int, #*A, lda
memory_pointer, c_int #*B, ldb
]
# cublasStatus_t cublasStrsmBatched( cublasHandle_t handle,
# cublasSideMode_t side,
# cublasFillMode_t uplo,
# cublasOperation_t trans,
# cublasDiagType_t diag,
# int m,
# int n,
# const float *alpha,
# float *A[],
# int lda,
# float *B[],
# int ldb,
# int batchCount);
# cublasStatus_t cublasDtrsmBatched( cublasHandle_t handle,
# cublasSideMode_t side,
# cublasFillMode_t uplo,
# cublasOperation_t trans,
# cublasDiagType_t diag,
# int m,
# int n,
# const double *alpha,
# double *A[],
# int lda,
# double *B[],
# int ldb,
# int batchCount);
# cublasStatus_t cublasCtrsmBatched( cublasHandle_t handle,
# cublasSideMode_t side,
# cublasFillMode_t uplo,
# cublasOperation_t trans,
# cublasDiagType_t diag,
# int m,
# int n,
# const cuComplex *alpha,
# cuComplex *A[],
# int lda,
# cuComplex *B[],
# int ldb,
# int batchCount);
# cublasStatus_t cublasZtrsmBatched( cublasHandle_t handle,
# cublasSideMode_t side,
# cublasFillMode_t uplo,
# cublasOperation_t trans,
# cublasDiagType_t diag,
# int m,
# int n,
# const cuDoubleComplex *alpha,
# cuDoubleComplex *A[],
# int lda,
# cuDoubleComplex *B[],
# int ldb,
# int batchCount);
cublasStrsmBatched = libcublas.cublasStrsmBatched
cublasDtrsmBatched = libcublas.cublasDtrsmBatched
cublasCtrsmBatched = libcublas.cublasCtrsmBatched
cublasZtrsmBatched = libcublas.cublasZtrsmBatched
for funct in [cublasStrsmBatched, cublasDtrsmBatched,
cublasCtrsmBatched, cublasZtrsmBatched]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_cublasSideMode_t, #side
c_cublasFillMode_t, #uplo
c_cublasOperation_t, #trans
c_cublasDiagType_t, #diag
c_int, c_int, #m, n
scalar_pointer, #*alpha
array_pointer, c_int, #*A[], lda
array_pointer, c_int, #*B[], ldb
c_int #batchCount
]
# cublasStatus_t cublasChemm(cublasHandle_t handle,
# cublasSideMode_t side, cublasFillMode_t uplo,
# int m, int n,
# const cuComplex *alpha,
# const cuComplex *A, int lda,
# const cuComplex *B, int ldb,
# const cuComplex *beta,
# cuComplex *C, int ldc)
# cublasStatus_t cublasZhemm(cublasHandle_t handle,
# cublasSideMode_t side, cublasFillMode_t uplo,
# int m, int n,
# const cuDoubleComplex *alpha,
# const cuDoubleComplex *A, int lda,
# const cuDoubleComplex *B, int ldb,
# const cuDoubleComplex *beta,
# cuDoubleComplex *C, int ldc)
cublasChemm = libcublas.cublasChemm_v2
cublasZhemm = libcublas.cublasZhemm_v2
for funct in [cublasChemm, cublasZhemm]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_cublasSideMode_t, #side
c_cublasFillMode_t, #uplo
c_int, c_int, #m, n
scalar_pointer, #*alpha
memory_pointer, c_int, #*A, lda
memory_pointer, c_int, #*B, ldb
scalar_pointer, #*beta
memory_pointer, c_int #*C, ldc
]
# cublasStatus_t cublasCherk(cublasHandle_t handle,
# cublasFillMode_t uplo, cublasOperation_t trans,
# int n, int k,
# const float *alpha,
# const cuComplex *A, int lda,
# const float *beta,
# cuComplex *C, int ldc)
# cublasStatus_t cublasZherk(cublasHandle_t handle,
# cublasFillMode_t uplo, cublasOperation_t trans,
# int n, int k,
# const double *alpha,
# const cuDoubleComplex *A, int lda,
# const double *beta,
# cuDoubleComplex *C, int ldc)
cublasCherk = libcublas.cublasCherk_v2
cublasZherk = libcublas.cublasZherk_v2
for funct in [cublasCherk, cublasZherk]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_cublasFillMode_t, #uplo
c_cublasOperation_t, #trans
c_int, c_int, #n, k
scalar_pointer, #*alpha
memory_pointer, c_int, #*A, lda
scalar_pointer, #*beta
memory_pointer, c_int #*C, ldc
]
# cublasStatus_t cublasCher2k(cublasHandle_t handle,
# cublasFillMode_t uplo, cublasOperation_t trans,
# int n, int k,
# const cuComplex *alpha,
# const cuComplex *A, int lda,
# const cuComplex *B, int ldb,
# const float *beta,
# cuComplex *C, int ldc)
# cublasStatus_t cublasZher2k(cublasHandle_t handle,
# cublasFillMode_t uplo, cublasOperation_t trans,
# int n, int k,
# const cuDoubleComplex *alpha,
# const cuDoubleComplex *A, int lda,
# const cuDoubleComplex *B, int ldb,
# const double *beta,
# cuDoubleComplex *C, int ldc)
cublasCher2k = libcublas.cublasCher2k_v2
cublasZher2k = libcublas.cublasZher2k_v2
for funct in [cublasCher2k, cublasZher2k]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_cublasFillMode_t, #uplo
c_cublasOperation_t, #trans
c_int, c_int, #n, k
scalar_pointer, #*alpha
memory_pointer, c_int, #*A, lda
memory_pointer, c_int, #*B, ldb
scalar_pointer, #*beta
memory_pointer, c_int #*C, ldc
]
# cublasStatus_t cublasCherkx(cublasHandle_t handle,
# cublasFillMode_t uplo, cublasOperation_t trans,
# int n, int k,
# const cuComplex *alpha,
# const cuComplex *A, int lda,
# const cuComplex *B, int ldb,
# const float *beta,
# cuComplex *C, int ldc)
# cublasStatus_t cublasZherkx(cublasHandle_t handle,
# cublasFillMode_t uplo, cublasOperation_t trans,
# int n, int k,
# const cuDoubleComplex *alpha,
# const cuDoubleComplex *A, int lda,
# const cuDoubleComplex *B, int ldb,
# const double *beta,
# cuDoubleComplex *C, int ldc)
cublasCherkx = libcublas.cublasCherkx
cublasZherkx = libcublas.cublasZherkx
for funct in [cublasCherkx, cublasZherkx]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_cublasFillMode_t, #uplo
c_cublasOperation_t, #trans
c_int, c_int, #n, k
scalar_pointer, #*alpha
memory_pointer, c_int, #*A, lda
memory_pointer, c_int, #*B, ldb
scalar_pointer, #*beta
memory_pointer, c_int #*C, ldc
]
## cuBLAS BLAS-like Extension Functions ##
#cublasStatus_t cublasSgeam(cublasHandle_t handle,
# cublasOperation_t transa, cublasOperation_t transb,
# int m, int n,
# const float *alpha,
# const float *A, int lda,
# const float *beta,
# const float *B, int ldb,
# float *C, int ldc)
#cublasStatus_t cublasDgeam(cublasHandle_t handle,
# cublasOperation_t transa, cublasOperation_t transb,
# int m, int n,
# const double *alpha,
# const double *A, int lda,
# const double *beta,
# const double *B, int ldb,
# double *C, int ldc)
#cublasStatus_t cublasCgeam(cublasHandle_t handle,
# cublasOperation_t transa, cublasOperation_t transb,
# int m, int n,
# const cuComplex *alpha,
# const cuComplex *A, int lda,
# const cuComplex *beta ,
# const cuComplex *B, int ldb,
# cuComplex *C, int ldc)
#cublasStatus_t cublasZgeam(cublasHandle_t handle,
# cublasOperation_t transa, cublasOperation_t transb,
# int m, int n,
# const cuDoubleComplex *alpha,
# const cuDoubleComplex *A, int lda,
# const cuDoubleComplex *beta,
# const cuDoubleComplex *B, int ldb,
# cuDoubleComplex *C, int ldc)
cublasSgeam = libcublas.cublasSgeam
cublasDgeam = libcublas.cublasDgeam
cublasCgeam = libcublas.cublasCgeam
cublasZgeam = libcublas.cublasZgeam
for funct in [cublasSgeam, cublasDgeam, cublasCgeam, cublasZgeam]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_cublasOperation_t, #trans
c_cublasOperation_t, #transb
c_int, c_int, #m, n
scalar_pointer, #*alpha
memory_pointer, c_int, #*A, lda
scalar_pointer, #*beta
memory_pointer, c_int, #*B, ldb
memory_pointer, c_int #*C, ldc
]
#cublasStatus_t cublasSdgmm(cublasHandle_t handle, cublasSideMode_t mode,
# int m, int n,
# const float *A, int lda,
# const float *x, int incx,
# float *C, int ldc)
#cublasStatus_t cublasDdgmm(cublasHandle_t handle, cublasSideMode_t mode,
# int m, int n,
# const double *A, int lda,
# const double *x, int incx,
# double *C, int ldc)
#cublasStatus_t cublasCdgmm(cublasHandle_t handle, cublasSideMode_t mode,
# int m, int n,
# const cuComplex *A, int lda,
# const cuComplex *x, int incx,
# cuComplex *C, int ldc)
#cublasStatus_t cublasZdgmm(cublasHandle_t handle, cublasSideMode_t mode,
# int m, int n,
# const cuDoubleComplex *A, int lda,
# const cuDoubleComplex *x, int incx,
# cuDoubleComplex *C, int ldc)
cublasSdgmm = libcublas.cublasSdgmm
cublasDdgmm = libcublas.cublasDdgmm
cublasCdgmm = libcublas.cublasCdgmm
cublasZdgmm = libcublas.cublasZdgmm
for funct in [cublasSdgmm, cublasDdgmm, cublasCdgmm, cublasZdgmm]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_cublasSideMode_t, #mode
c_int, c_int, #m, n
memory_pointer, c_int, #*A, lda
memory_pointer, c_int, #*x, incx
memory_pointer, c_int #*C, ldc
]
#cublasStatus_t cublasSgetrfBatched(cublasHandle_t handle,
# int n,
# float *Aarray[],
# int lda,
# int *PivotArray,
# int *infoArray,
# int batchSize);
#cublasStatus_t cublasDgetrfBatched(cublasHandle_t handle,
# int n,
# double *Aarray[],
# int lda,
# int *PivotArray,
# int *infoArray,
# int batchSize);
#cublasStatus_t cublasCgetrfBatched(cublasHandle_t handle,
# int n,
# cuComplex *Aarray[],
# int lda,
# int *PivotArray,
# int *infoArray,
# int batchSize);
#cublasStatus_t cublasZgetrfBatched(cublasHandle_t handle,
# int n,
# cuDoubleComplex *Aarray[],
# int lda,
# int *PivotArray,
# int *infoArray,
# int batchSize);
cublasSgetrfBatched = libcublas.cublasSgetrfBatched
cublasDgetrfBatched = libcublas.cublasDgetrfBatched
cublasCgetrfBatched = libcublas.cublasCgetrfBatched
cublasZgetrfBatched = libcublas.cublasZgetrfBatched
for funct in [cublasSgetrfBatched, cublasDgetrfBatched, cublasCgetrfBatched, cublasZgetrfBatched]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_int, #n
array_pointer, #*Aarray[]
c_int, #lda
scalar_pointer, #*PivotArray
scalar_pointer, #*infoArray
c_int #batchSize
]
#cublasStatus_t cublasSgetrsBatched(cublasHandle_t handle,
# cublasOperation_t trans,
# int n,
# int nrhs,
# const float *Aarray[],
# int lda,
# const int *devIpiv,
# float *Barray[],
# int ldb,
# int *info,
# int batchSize);
#cublasStatus_t cublasDgetrsBatched(cublasHandle_t handle,
# cublasOperation_t trans,
# int n,
# int nrhs,
# const double *Aarray[],
# int lda,
# const int *devIpiv,
# double *Barray[],
# int ldb,
# int *info,
# int batchSize);
#cublasStatus_t cublasCgetrsBatched(cublasHandle_t handle,
# cublasOperation_t trans,
# int n,
# int nrhs,
# const cuComplex *Aarray[],
# int lda,
# const int *devIpiv,
# cuComplex *Barray[],
# int ldb,
# int *info,
# int batchSize);
#cublasStatus_t cublasZgetrsBatched(cublasHandle_t handle,
# cublasOperation_t trans,
# int n,
# int nrhs,
# const cuDoubleComplex *Aarray[],
# int lda,
# const int *devIpiv,
# cuDoubleComplex *Barray[],
# int ldb,
# int *info,
# int batchSize);
cublasSgetrsBatched = libcublas.cublasSgetrsBatched
cublasDgetrsBatched = libcublas.cublasDgetrsBatched
cublasCgetrsBatched = libcublas.cublasCgetrsBatched
cublasZgetrsBatched = libcublas.cublasZgetrsBatched
for funct in [cublasSgetrsBatched, cublasDgetrsBatched, cublasCgetrsBatched, cublasZgetrsBatched]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_cublasOperation_t, #trans
c_int, #n
c_int, #nrhs
array_pointer, #*Aarray[]
c_int, #lda
scalar_pointer, #*devIpiv
array_pointer, #*Barray[]
c_int, #ldb
scalar_pointer, #*info
c_int #batchSize
]
#cublasStatus_t cublasSgetriBatched(cublasHandle_t handle,
# int n,
# float *Aarray[],
# int lda,
# int *PivotArray,
# float *Carray[],
# int ldc,
# int *infoArray,
# int batchSize);
#cublasStatus_t cublasDgetriBatched(cublasHandle_t handle,
# int n,
# double *Aarray[],
# int lda,
# int *PivotArray,
# double *Carray[],
# int ldc,
# int *infoArray,
# int batchSize);
#cublasStatus_t cublasCgetriBatched(cublasHandle_t handle,
# int n,
# cuComplex *Aarray[],
# int lda,
# int *PivotArray,
# cuComplex *Carray[],
# int ldc,
# int *infoArray,
# int batchSize);
#cublasStatus_t cublasZgetriBatched(cublasHandle_t handle,
# int n,
# cuDoubleComplex *Aarray[],
# int lda,
# int *PivotArray,
# cuDoubleComplex *Carray[],
# int ldc,
# int *infoArray,
# int batchSize);
cublasSgetriBatched = libcublas.cublasSgetriBatched
cublasDgetriBatched = libcublas.cublasDgetriBatched
cublasCgetriBatched = libcublas.cublasCgetriBatched
cublasZgetriBatched = libcublas.cublasZgetriBatched
for funct in [cublasSgetriBatched, cublasDgetriBatched, cublasCgetriBatched, cublasZgetriBatched]:
funct.restype = cublasStatus_t
funct.argtypes = [cublasHandle_t,
c_int, #n
array_pointer, #*Aarray[]
c_int, #lda
scalar_pointer, #*PivotArray,
array_pointer, #*Carray[]
c_int, #ldc
scalar_pointer, #*infoArray
c_int #batchSize
]
#Published symbols in libcublas.so.7.0 not implemented yet:
# cublasXerbla ** Not documented??
# cublasSetBackdoor ** Not documented??
# cublasGetStream_v2
# cublasSetStream_v2
# cublasGetVectorAsync
# cublasSetVectorAsync
# cublasGetMatrixAsync
# cublasSetMatrixAsync
# cublasAlloc ** Deprecated, use cudaMalloc
# cublasFree ** Deprecated, use cudaFree
# cublasInit ** Deprecated, use cublasCreate
# cublasShutdown ** Deprecated, use cublasDestroy
# cublasGetError ** Deprecated, use functions return value
# cublasSetKernelStream ** Deprecated, use cublasSetStream_v2
# cublasCgetri ** Not documented??
# cublasDgetri ** Not documented??
# cublasSgetri ** Not documented??
# cublasZgetri ** Not documented??
# cublasCbdmm ** Not documented??
# cublasDbdmm ** Not documented??
# cublasSbdmm ** Not documented??
# cublasZbdmm ** Not documented??
# cublasCmatinvBatched
# cublasDmatinvBatched
# cublasSmatinvBatched
# cublasZmatinvBatched
# cublasCgeqrfBatched
# cublasDgeqrfBatched
# cublasSgeqrfBatched
# cublasZgeqrfBatched
# cublasCgelsBatched
# cublasDgelsBatched
# cublasSgelsBatched
# cublasZgelsBatched
# cublasCtrttp
# cublasDtrttp
# cublasStrttp
# cublasZtrttp
# cublasCtpttr
# cublasDtpttr
# cublasStpttr
# cublasZtpttr
|
/*jslint browser: true */
/*jslint node: true */
/*global global, ActiveXObject, define, escape, module, pnotify, Proxy, jQuery, require, self, setImmediate, window */
/*!
* modified jQuery JavaScript Library v3.1.1
* @see {@link https://jquery.com/}
*
* Includes Sizzle.js
* @see {@link https://sizzlejs.com/}
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license
* @see {@link https://jquery.org/license}
*
* Date: 2016-09-22T22:30Z
* source: cdn.jsdelivr.net/jquery/3.1.1/jquery.js
* pass jshint with suppressing comments
*/
/*jshint ignore:start */
(function(global,factory){"use strict";if(typeof module==="object"&&typeof module.exports==="object"){module.exports=global.document?factory(global,true):function(w){if(!w.document){throw new Error("jQuery requires a window with a document");}return factory(w);};}else{factory(global);}})("undefined"!==typeof window?window:this,function(window,noGlobal){"use strict";var arr=[];var document=window.document;var getProto=Object.getPrototypeOf;var slice=arr.slice;var concat=arr.concat;var push=arr.push;var indexOf=arr.indexOf;var class2type={};var toString=class2type.toString;var hasOwn=class2type.hasOwnProperty;var fnToString=hasOwn.toString;var ObjectFunctionString=fnToString.call(Object);var support={};function DOMEval(code,doc){doc=doc||document;var script=doc.createElement("script");script.text=code;doc.head.appendChild(script).parentNode.removeChild(script);}var version="3.1.1",jQuery=function(selector,context){return new jQuery.fn.init(selector,context);},rtrim=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,rmsPrefix=/^-ms-/,rdashAlpha=/-([a-z])/g,fcamelCase=function(all,letter){return letter.toUpperCase();};jQuery.fn=jQuery.prototype={jquery:version,constructor:jQuery,length:0,toArray:function(){return slice.call(this);},get:function(num){if(num==null){return slice.call(this);}return num<0?this[num+this.length]:this[num];},pushStack:function(elems){var ret=jQuery.merge(this.constructor(),elems);ret.prevObject=this;return ret;},each:function(callback){return jQuery.each(this,callback);},map:function(callback){return this.pushStack(jQuery.map(this,function(elem,i){return callback.call(elem,i,elem);}));},slice:function(){return this.pushStack(slice.apply(this,arguments));},first:function(){return this.eq(0);},last:function(){return this.eq(-1);},eq:function(i){var len=this.length,j=+i+(i<0?len:0);return this.pushStack(j>=0&&j<len?[this[j]]:[]);},end:function(){return this.prevObject||this.constructor();},push:push,sort:arr.sort,splice:arr.splice};jQuery.extend=jQuery.fn.extend=function(){var options,name,src,copy,copyIsArray,clone,target=arguments[0]||{},i=1,length=arguments.length,deep=false;if(typeof target==="boolean"){deep=target;target=arguments[i]||{};i++;}if(typeof target!=="object"&&!jQuery.isFunction(target)){target={};}if(i===length){target=this;i--;}for(;i<length;i++){if((options=arguments[i])!=null){for(name in options){src=target[name];copy=options[name];if(target===copy){continue;}if(deep&©&&(jQuery.isPlainObject(copy)||(copyIsArray=jQuery.isArray(copy)))){if(copyIsArray){copyIsArray=false;clone=src&&jQuery.isArray(src)?src:[];}else{clone=src&&jQuery.isPlainObject(src)?src:{};}target[name]=jQuery.extend(deep,clone,copy);}else if(copy!==undefined){target[name]=copy;}}}}return target;};jQuery.extend({expando:"jQuery"+(version+Math.random()).replace(/\D/g,""),isReady:true,error:function(msg){throw new Error(msg);},noop:function(){},isFunction:function(obj){return jQuery.type(obj)==="function";},isArray:Array.isArray,isWindow:function(obj){return obj!=null&&obj===obj.window;},isNumeric:function(obj){var type=jQuery.type(obj);return(type==="number"||type==="string")&&!isNaN(obj-parseFloat(obj));},isPlainObject:function(obj){var proto,Ctor;if(!obj||toString.call(obj)!=="[object Object]"){return false;}proto=getProto(obj);if(!proto){return true;}Ctor=hasOwn.call(proto,"constructor")&&proto.constructor;return typeof Ctor==="function"&&fnToString.call(Ctor)===ObjectFunctionString;},isEmptyObject:function(obj){var name;for(name in obj){return false;}return true;},type:function(obj){if(obj==null){return obj+"";}return typeof obj==="object"||typeof obj==="function"?class2type[toString.call(obj)]||"object":typeof obj;},globalEval:function(code){DOMEval(code);},camelCase:function(string){return string.replace(rmsPrefix,"ms-").replace(rdashAlpha,fcamelCase);},nodeName:function(elem,name){return elem.nodeName&&elem.nodeName.toLowerCase()===name.toLowerCase();},each:function(obj,callback){var length,i=0;if(isArrayLike(obj)){length=obj.length;for(;i<length;i++){if(callback.call(obj[i],i,obj[i])===false){break;}}}else{for(i in obj){if(callback.call(obj[i],i,obj[i])===false){break;}}}return obj;},trim:function(text){return text==null?"":(text+"").replace(rtrim,"");},makeArray:function(arr,results){var ret=results||[];if(arr!=null){if(isArrayLike(Object(arr))){jQuery.merge(ret,typeof arr==="string"?[arr]:arr);}else{push.call(ret,arr);}}return ret;},inArray:function(elem,arr,i){return arr==null?-1:indexOf.call(arr,elem,i);},merge:function(first,second){var len=+second.length,j=0,i=first.length;for(;j<len;j++){first[i++]=second[j];}first.length=i;return first;},grep:function(elems,callback,invert){var callbackInverse,matches=[],i=0,length=elems.length,callbackExpect=!invert;for(;i<length;i++){callbackInverse=!callback(elems[i],i);if(callbackInverse!==callbackExpect){matches.push(elems[i]);}}return matches;},map:function(elems,callback,arg){var length,value,i=0,ret=[];if(isArrayLike(elems)){length=elems.length;for(;i<length;i++){value=callback(elems[i],i,arg);if(value!=null){ret.push(value);}}}else{for(i in elems){value=callback(elems[i],i,arg);if(value!=null){ret.push(value);}}}return concat.apply([],ret);},guid:1,proxy:function(fn,context){var tmp,args,proxy;if(typeof context==="string"){tmp=fn[context];context=fn;fn=tmp;}if(!jQuery.isFunction(fn)){return undefined;}args=slice.call(arguments,2);proxy=function(){return fn.apply(context||this,args.concat(slice.call(arguments)));};proxy.guid=fn.guid=fn.guid||jQuery.guid++;return proxy;},now:Date.now,support:support});if(typeof Symbol==="function"){jQuery.fn[Symbol.iterator]=arr[Symbol.iterator];}jQuery.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(i,name){class2type["[object "+name+"]"]=name.toLowerCase();});function isArrayLike(obj){var length=!!obj&&"length"in obj&&obj.length,type=jQuery.type(obj);if(type==="function"||jQuery.isWindow(obj)){return false;}return type==="array"||length===0||typeof length==="number"&&length>0&&(length-1)in obj;}var Sizzle=(function(window){var i,support,Expr,getText,isXML,tokenize,compile,select,outermostContext,sortInput,hasDuplicate,setDocument,document,docElem,documentIsHTML,rbuggyQSA,rbuggyMatches,matches,contains,expando="sizzle"+1*new Date(),preferredDoc=window.document,dirruns=0,done=0,classCache=createCache(),tokenCache=createCache(),compilerCache=createCache(),sortOrder=function(a,b){if(a===b){hasDuplicate=true;}return 0;},hasOwn=({}).hasOwnProperty,arr=[],pop=arr.pop,push_native=arr.push,push=arr.push,slice=arr.slice,indexOf=function(list,elem){var i=0,len=list.length;for(;i<len;i++){if(list[i]===elem){return i;}}return-1;},booleans="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",whitespace="[\\x20\\t\\r\\n\\f]",identifier="(?:\\\\.|[\\w-]|[^\0-\\xa0])+",attributes="\\["+whitespace+"*("+identifier+")(?:"+whitespace+"*([*^$|!~]?=)"+whitespace+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+identifier+"))|)"+whitespace+"*\\]",pseudos=":("+identifier+")(?:\\(("+"('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|"+"((?:\\\\.|[^\\\\()[\\]]|"+attributes+")*)|"+".*"+")\\)|)",rwhitespace=new RegExp(whitespace+"+","g"),rtrim=new RegExp("^"+whitespace+"+|((?:^|[^\\\\])(?:\\\\.)*)"+whitespace+"+$","g"),rcomma=new RegExp("^"+whitespace+"*,"+whitespace+"*"),rcombinators=new RegExp("^"+whitespace+"*([>+~]|"+whitespace+")"+whitespace+"*"),rattributeQuotes=new RegExp("="+whitespace+"*([^\\]'\"]*?)"+whitespace+"*\\]","g"),rpseudo=new RegExp(pseudos),ridentifier=new RegExp("^"+identifier+"$"),matchExpr={"ID":new RegExp("^#("+identifier+")"),"CLASS":new RegExp("^\\.("+identifier+")"),"TAG":new RegExp("^("+identifier+"|[*])"),"ATTR":new RegExp("^"+attributes),"PSEUDO":new RegExp("^"+pseudos),"CHILD":new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+whitespace+"*(even|odd|(([+-]|)(\\d*)n|)"+whitespace+"*(?:([+-]|)"+whitespace+"*(\\d+)|))"+whitespace+"*\\)|)","i"),"bool":new RegExp("^(?:"+booleans+")$","i"),"needsContext":new RegExp("^"+whitespace+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+whitespace+"*((?:-\\d)?\\d*)"+whitespace+"*\\)|)(?=[^-]|$)","i")},rinputs=/^(?:input|select|textarea|button)$/i,rheader=/^h\d$/i,rnative=/^[^{]+\{\s*\[native \w/,rquickExpr=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,rsibling=/[+~]/,runescape=new RegExp("\\\\([\\da-f]{1,6}"+whitespace+"?|("+whitespace+")|.)","ig"),funescape=function(_,escaped,escapedWhitespace){var high="0x"+escaped-0x10000;return high!==high||escapedWhitespace?escaped:high<0?String.fromCharCode(high+0x10000):String.fromCharCode(high>>10|0xD800,high&0x3FF|0xDC00);},rcssescape=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,fcssescape=function(ch,asCodePoint){if(asCodePoint){if(ch==="\0"){return"\uFFFD";}return ch.slice(0,-1)+"\\"+ch.charCodeAt(ch.length-1).toString(16)+" ";}return"\\"+ch;},unloadHandler=function(){setDocument();},disabledAncestor=addCombinator(function(elem){return elem.disabled===true&&("form"in elem||"label"in elem);},{dir:"parentNode",next:"legend"});try{push.apply((arr=slice.call(preferredDoc.childNodes)),preferredDoc.childNodes);arr[preferredDoc.childNodes.length].nodeType;}catch(e){push={apply:arr.length?function(target,els){push_native.apply(target,slice.call(els));}:function(target,els){var j=target.length,i=0;while((target[j++]=els[i++])){}target.length=j-1;}};}function Sizzle(selector,context,results,seed){var m,i,elem,nid,match,groups,newSelector,newContext=context&&context.ownerDocument,nodeType=context?context.nodeType:9;results=results||[];if(typeof selector!=="string"||!selector||nodeType!==1&&nodeType!==9&&nodeType!==11){return results;}if(!seed){if((context?context.ownerDocument||context:preferredDoc)!==document){setDocument(context);}context=context||document;if(documentIsHTML){if(nodeType!==11&&(match=rquickExpr.exec(selector))){if((m=match[1])){if(nodeType===9){if((elem=context.getElementById(m))){if(elem.id===m){results.push(elem);return results;}}else{return results;}}else{if(newContext&&(elem=newContext.getElementById(m))&&contains(context,elem)&&elem.id===m){results.push(elem);return results;}}}else if(match[2]){push.apply(results,context.getElementsByTagName(selector));return results;}else if((m=match[3])&&support.getElementsByClassName&&context.getElementsByClassName){push.apply(results,context.getElementsByClassName(m));return results;}}if(support.qsa&&!compilerCache[selector+" "]&&(!rbuggyQSA||!rbuggyQSA.test(selector))){if(nodeType!==1){newContext=context;newSelector=selector;}else if(context.nodeName.toLowerCase()!=="object"){if((nid=context.getAttribute("id"))){nid=nid.replace(rcssescape,fcssescape);}else{context.setAttribute("id",(nid=expando));}groups=tokenize(selector);i=groups.length;while(i--){groups[i]="#"+nid+" "+toSelector(groups[i]);}newSelector=groups.join(",");newContext=rsibling.test(selector)&&testContext(context.parentNode)||context;}if(newSelector){try{push.apply(results,newContext.querySelectorAll(newSelector));return results;}catch(qsaError){}finally{if(nid===expando){context.removeAttribute("id");}}}}}}return select(selector.replace(rtrim,"$1"),context,results,seed);}function createCache(){var keys=[];function cache(key,value){if(keys.push(key+" ")>Expr.cacheLength){delete cache[keys.shift()];}return(cache[key+" "]=value);}return cache;}function markFunction(fn){fn[expando]=true;return fn;}function assert(fn){var el=document.createElement("fieldset");try{return!!fn(el);}catch(e){return false;}finally{if(el.parentNode){el.parentNode.removeChild(el);}el=null;}}function addHandle(attrs,handler){var arr=attrs.split("|"),i=arr.length;while(i--){Expr.attrHandle[arr[i]]=handler;}}function siblingCheck(a,b){var cur=b&&a,diff=cur&&a.nodeType===1&&b.nodeType===1&&a.sourceIndex-b.sourceIndex;if(diff){return diff;}if(cur){while((cur=cur.nextSibling)){if(cur===b){return-1;}}}return a?1:-1;}function createInputPseudo(type){return function(elem){var name=elem.nodeName.toLowerCase();return name==="input"&&elem.type===type;};}function createButtonPseudo(type){return function(elem){var name=elem.nodeName.toLowerCase();return(name==="input"||name==="button")&&elem.type===type;};}function createDisabledPseudo(disabled){return function(elem){if("form"in elem){if(elem.parentNode&&elem.disabled===false){if("label"in elem){if("label"in elem.parentNode){return elem.parentNode.disabled===disabled;}else{return elem.disabled===disabled;}}return elem.isDisabled===disabled||elem.isDisabled!==!disabled&&disabledAncestor(elem)===disabled;}return elem.disabled===disabled;}else if("label"in elem){return elem.disabled===disabled;}return false;};}function createPositionalPseudo(fn){return markFunction(function(argument){argument=+argument;return markFunction(function(seed,matches){var j,matchIndexes=fn([],seed.length,argument),i=matchIndexes.length;while(i--){if(seed[(j=matchIndexes[i])]){seed[j]=!(matches[j]=seed[j]);}}});});}function testContext(context){return context&&typeof context.getElementsByTagName!=="undefined"&&context;}support=Sizzle.support={};isXML=Sizzle.isXML=function(elem){var documentElement=elem&&(elem.ownerDocument||elem).documentElement;return documentElement?documentElement.nodeName!=="HTML":false;};setDocument=Sizzle.setDocument=function(node){var hasCompare,subWindow,doc=node?node.ownerDocument||node:preferredDoc;if(doc===document||doc.nodeType!==9||!doc.documentElement){return document;}document=doc;docElem=document.documentElement;documentIsHTML=!isXML(document);if(preferredDoc!==document&&(subWindow=document.defaultView)&&subWindow.top!==subWindow){if(subWindow.addEventListener){subWindow.addEventListener("unload",unloadHandler,false);}else if(subWindow.attachEvent){subWindow.attachEvent("onunload",unloadHandler);}}support.attributes=assert(function(el){el.className="i";return!el.getAttribute("className");});support.getElementsByTagName=assert(function(el){el.appendChild(document.createComment(""));return!el.getElementsByTagName("*").length;});support.getElementsByClassName=rnative.test(document.getElementsByClassName);support.getById=assert(function(el){docElem.appendChild(el).id=expando;return!document.getElementsByName||!document.getElementsByName(expando).length;});if(support.getById){Expr.filter["ID"]=function(id){var attrId=id.replace(runescape,funescape);return function(elem){return elem.getAttribute("id")===attrId;};};Expr.find["ID"]=function(id,context){if(typeof context.getElementById!=="undefined"&&documentIsHTML){var elem=context.getElementById(id);return elem?[elem]:[];}};}else{Expr.filter["ID"]=function(id){var attrId=id.replace(runescape,funescape);return function(elem){var node=typeof elem.getAttributeNode!=="undefined"&&elem.getAttributeNode("id");return node&&node.value===attrId;};};Expr.find["ID"]=function(id,context){if(typeof context.getElementById!=="undefined"&&documentIsHTML){var node,i,elems,elem=context.getElementById(id);if(elem){node=elem.getAttributeNode("id");if(node&&node.value===id){return[elem];}elems=context.getElementsByName(id);i=0;while((elem=elems[i++])){node=elem.getAttributeNode("id");if(node&&node.value===id){return[elem];}}}return[];}};}Expr.find["TAG"]=support.getElementsByTagName?function(tag,context){if(typeof context.getElementsByTagName!=="undefined"){return context.getElementsByTagName(tag);}else if(support.qsa){return context.querySelectorAll(tag);}}:function(tag,context){var elem,tmp=[],i=0,results=context.getElementsByTagName(tag);if(tag==="*"){while((elem=results[i++])){if(elem.nodeType===1){tmp.push(elem);}}return tmp;}return results;};Expr.find["CLASS"]=support.getElementsByClassName&&function(className,context){if(typeof context.getElementsByClassName!=="undefined"&&documentIsHTML){return context.getElementsByClassName(className);}};rbuggyMatches=[];rbuggyQSA=[];if((support.qsa=rnative.test(document.querySelectorAll))){assert(function(el){docElem.appendChild(el).innerHTML="<a id='"+expando+"'></a>"+"<select id='"+expando+"-\r\\' msallowcapture=''>"+"<option selected=''></option></select>";if(el.querySelectorAll("[msallowcapture^='']").length){rbuggyQSA.push("[*^$]="+whitespace+"*(?:''|\"\")");}if(!el.querySelectorAll("[selected]").length){rbuggyQSA.push("\\["+whitespace+"*(?:value|"+booleans+")");}if(!el.querySelectorAll("[id~="+expando+"-]").length){rbuggyQSA.push("~=");}if(!el.querySelectorAll(":checked").length){rbuggyQSA.push(":checked");}if(!el.querySelectorAll("a#"+expando+"+*").length){rbuggyQSA.push(".#.+[+~]");}});assert(function(el){el.innerHTML="<a href='' disabled='disabled'></a>"+"<select disabled='disabled'><option/></select>";var input=document.createElement("input");input.setAttribute("type","hidden");el.appendChild(input).setAttribute("name","D");if(el.querySelectorAll("[name=d]").length){rbuggyQSA.push("name"+whitespace+"*[*^$|!~]?=");}if(el.querySelectorAll(":enabled").length!==2){rbuggyQSA.push(":enabled",":disabled");}docElem.appendChild(el).disabled=true;if(el.querySelectorAll(":disabled").length!==2){rbuggyQSA.push(":enabled",":disabled");}el.querySelectorAll("*,:x");rbuggyQSA.push(",.*:");});}if((support.matchesSelector=rnative.test((matches=docElem.matches||docElem.webkitMatchesSelector||docElem.mozMatchesSelector||docElem.oMatchesSelector||docElem.msMatchesSelector)))){assert(function(el){support.disconnectedMatch=matches.call(el,"*");matches.call(el,"[s!='']:x");rbuggyMatches.push("!=",pseudos);});}rbuggyQSA=rbuggyQSA.length&&new RegExp(rbuggyQSA.join("|"));rbuggyMatches=rbuggyMatches.length&&new RegExp(rbuggyMatches.join("|"));hasCompare=rnative.test(docElem.compareDocumentPosition);contains=hasCompare||rnative.test(docElem.contains)?function(a,b){var adown=a.nodeType===9?a.documentElement:a,bup=b&&b.parentNode;return a===bup||!!(bup&&bup.nodeType===1&&(adown.contains?adown.contains(bup):a.compareDocumentPosition&&a.compareDocumentPosition(bup)&16));}:function(a,b){if(b){while((b=b.parentNode)){if(b===a){return true;}}}return false;};sortOrder=hasCompare?function(a,b){if(a===b){hasDuplicate=true;return 0;}var compare=!a.compareDocumentPosition-!b.compareDocumentPosition;if(compare){return compare;}compare=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1;if(compare&1||(!support.sortDetached&&b.compareDocumentPosition(a)===compare)){if(a===document||a.ownerDocument===preferredDoc&&contains(preferredDoc,a)){return-1;}if(b===document||b.ownerDocument===preferredDoc&&contains(preferredDoc,b)){return 1;}return sortInput?(indexOf(sortInput,a)-indexOf(sortInput,b)):0;}return compare&4?-1:1;}:function(a,b){if(a===b){hasDuplicate=true;return 0;}var cur,i=0,aup=a.parentNode,bup=b.parentNode,ap=[a],bp=[b];if(!aup||!bup){return a===document?-1:b===document?1:aup?-1:bup?1:sortInput?(indexOf(sortInput,a)-indexOf(sortInput,b)):0;}else if(aup===bup){return siblingCheck(a,b);}cur=a;while((cur=cur.parentNode)){ap.unshift(cur);}cur=b;while((cur=cur.parentNode)){bp.unshift(cur);}while(ap[i]===bp[i]){i++;}return i?siblingCheck(ap[i],bp[i]):ap[i]===preferredDoc?-1:bp[i]===preferredDoc?1:0;};return document;};Sizzle.matches=function(expr,elements){return Sizzle(expr,null,null,elements);};Sizzle.matchesSelector=function(elem,expr){if((elem.ownerDocument||elem)!==document){setDocument(elem);}expr=expr.replace(rattributeQuotes,"='$1']");if(support.matchesSelector&&documentIsHTML&&!compilerCache[expr+" "]&&(!rbuggyMatches||!rbuggyMatches.test(expr))&&(!rbuggyQSA||!rbuggyQSA.test(expr))){try{var ret=matches.call(elem,expr);if(ret||support.disconnectedMatch||elem.document&&elem.document.nodeType!==11){return ret;}}catch(e){}}return Sizzle(expr,document,null,[elem]).length>0;};Sizzle.contains=function(context,elem){if((context.ownerDocument||context)!==document){setDocument(context);}return contains(context,elem);};Sizzle.attr=function(elem,name){if((elem.ownerDocument||elem)!==document){setDocument(elem);}var fn=Expr.attrHandle[name.toLowerCase()],val=fn&&hasOwn.call(Expr.attrHandle,name.toLowerCase())?fn(elem,name,!documentIsHTML):undefined;return val!==undefined?val:support.attributes||!documentIsHTML?elem.getAttribute(name):(val=elem.getAttributeNode(name))&&val.specified?val.value:null;};Sizzle.escape=function(sel){return(sel+"").replace(rcssescape,fcssescape);};Sizzle.error=function(msg){throw new Error("Syntax error, unrecognized expression: "+msg);};Sizzle.uniqueSort=function(results){var elem,duplicates=[],j=0,i=0;hasDuplicate=!support.detectDuplicates;sortInput=!support.sortStable&&results.slice(0);results.sort(sortOrder);if(hasDuplicate){while((elem=results[i++])){if(elem===results[i]){j=duplicates.push(i);}}while(j--){results.splice(duplicates[j],1);}}sortInput=null;return results;};getText=Sizzle.getText=function(elem){var node,ret="",i=0,nodeType=elem.nodeType;if(!nodeType){while((node=elem[i++])){ret+=getText(node);}}else if(nodeType===1||nodeType===9||nodeType===11){if(typeof elem.textContent==="string"){return elem.textContent;}else{for(elem=elem.firstChild;elem;elem=elem.nextSibling){ret+=getText(elem);}}}else if(nodeType===3||nodeType===4){return elem.nodeValue;}return ret;};Expr=Sizzle.selectors={cacheLength:50,createPseudo:markFunction,match:matchExpr,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:true}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:true},"~":{dir:"previousSibling"}},preFilter:{"ATTR":function(match){match[1]=match[1].replace(runescape,funescape);match[3]=(match[3]||match[4]||match[5]||"").replace(runescape,funescape);if(match[2]==="~="){match[3]=" "+match[3]+" ";}return match.slice(0,4);},"CHILD":function(match){match[1]=match[1].toLowerCase();if(match[1].slice(0,3)==="nth"){if(!match[3]){Sizzle.error(match[0]);}match[4]=+(match[4]?match[5]+(match[6]||1):2*(match[3]==="even"||match[3]==="odd"));match[5]=+((match[7]+match[8])||match[3]==="odd");}else if(match[3]){Sizzle.error(match[0]);}return match;},"PSEUDO":function(match){var excess,unquoted=!match[6]&&match[2];if(matchExpr["CHILD"].test(match[0])){return null;}if(match[3]){match[2]=match[4]||match[5]||"";}else if(unquoted&&rpseudo.test(unquoted)&&(excess=tokenize(unquoted,true))&&(excess=unquoted.indexOf(")",unquoted.length-excess)-unquoted.length)){match[0]=match[0].slice(0,excess);match[2]=unquoted.slice(0,excess);}return match.slice(0,3);}},filter:{"TAG":function(nodeNameSelector){var nodeName=nodeNameSelector.replace(runescape,funescape).toLowerCase();return nodeNameSelector==="*"?function(){return true;}:function(elem){return elem.nodeName&&elem.nodeName.toLowerCase()===nodeName;};},"CLASS":function(className){var pattern=classCache[className+" "];return pattern||(pattern=new RegExp("(^|"+whitespace+")"+className+"("+whitespace+"|$)"))&&classCache(className,function(elem){return pattern.test(typeof elem.className==="string"&&elem.className||typeof elem.getAttribute!=="undefined"&&elem.getAttribute("class")||"");});},"ATTR":function(name,operator,check){return function(elem){var result=Sizzle.attr(elem,name);if(result==null){return operator==="!=";}if(!operator){return true;}result+="";return operator==="="?result===check:operator==="!="?result!==check:operator==="^="?check&&result.indexOf(check)===0:operator==="*="?check&&result.indexOf(check)>-1:operator==="$="?check&&result.slice(-check.length)===check:operator==="~="?(" "+result.replace(rwhitespace," ")+" ").indexOf(check)>-1:operator==="|="?result===check||result.slice(0,check.length+1)===check+"-":false;};},"CHILD":function(type,what,argument,first,last){var simple=type.slice(0,3)!=="nth",forward=type.slice(-4)!=="last",ofType=what==="of-type";return first===1&&last===0?function(elem){return!!elem.parentNode;}:function(elem,context,xml){var cache,uniqueCache,outerCache,node,nodeIndex,start,dir=simple!==forward?"nextSibling":"previousSibling",parent=elem.parentNode,name=ofType&&elem.nodeName.toLowerCase(),useCache=!xml&&!ofType,diff=false;if(parent){if(simple){while(dir){node=elem;while((node=node[dir])){if(ofType?node.nodeName.toLowerCase()===name:node.nodeType===1){return false;}}start=dir=type==="only"&&!start&&"nextSibling";}return true;}start=[forward?parent.firstChild:parent.lastChild];if(forward&&useCache){node=parent;outerCache=node[expando]||(node[expando]={});uniqueCache=outerCache[node.uniqueID]||(outerCache[node.uniqueID]={});cache=uniqueCache[type]||[];nodeIndex=cache[0]===dirruns&&cache[1];diff=nodeIndex&&cache[2];node=nodeIndex&&parent.childNodes[nodeIndex];while((node=++nodeIndex&&node&&node[dir]||(diff=nodeIndex=0)||start.pop())){if(node.nodeType===1&&++diff&&node===elem){uniqueCache[type]=[dirruns,nodeIndex,diff];break;}}}else{if(useCache){node=elem;outerCache=node[expando]||(node[expando]={});uniqueCache=outerCache[node.uniqueID]||(outerCache[node.uniqueID]={});cache=uniqueCache[type]||[];nodeIndex=cache[0]===dirruns&&cache[1];diff=nodeIndex;}if(diff===false){while((node=++nodeIndex&&node&&node[dir]||(diff=nodeIndex=0)||start.pop())){if((ofType?node.nodeName.toLowerCase()===name:node.nodeType===1)&&++diff){if(useCache){outerCache=node[expando]||(node[expando]={});uniqueCache=outerCache[node.uniqueID]||(outerCache[node.uniqueID]={});uniqueCache[type]=[dirruns,diff];}if(node===elem){break;}}}}}diff-=last;return diff===first||(diff%first===0&&diff/first>=0);}};},"PSEUDO":function(pseudo,argument){var args,fn=Expr.pseudos[pseudo]||Expr.setFilters[pseudo.toLowerCase()]||Sizzle.error("unsupported pseudo: "+pseudo);if(fn[expando]){return fn(argument);}if(fn.length>1){args=[pseudo,pseudo,"",argument];return Expr.setFilters.hasOwnProperty(pseudo.toLowerCase())?markFunction(function(seed,matches){var idx,matched=fn(seed,argument),i=matched.length;while(i--){idx=indexOf(seed,matched[i]);seed[idx]=!(matches[idx]=matched[i]);}}):function(elem){return fn(elem,0,args);};}return fn;}},pseudos:{"not":markFunction(function(selector){var input=[],results=[],matcher=compile(selector.replace(rtrim,"$1"));return matcher[expando]?markFunction(function(seed,matches,context,xml){var elem,unmatched=matcher(seed,null,xml,[]),i=seed.length;while(i--){if((elem=unmatched[i])){seed[i]=!(matches[i]=elem);}}}):function(elem,context,xml){input[0]=elem;matcher(input,null,xml,results);input[0]=null;return!results.pop();};}),"has":markFunction(function(selector){return function(elem){return Sizzle(selector,elem).length>0;};}),"contains":markFunction(function(text){text=text.replace(runescape,funescape);return function(elem){return(elem.textContent||elem.innerText||getText(elem)).indexOf(text)>-1;};}),"lang":markFunction(function(lang){if(!ridentifier.test(lang||"")){Sizzle.error("unsupported lang: "+lang);}lang=lang.replace(runescape,funescape).toLowerCase();return function(elem){var elemLang;do{if((elemLang=documentIsHTML?elem.lang:elem.getAttribute("xml:lang")||elem.getAttribute("lang"))){elemLang=elemLang.toLowerCase();return elemLang===lang||elemLang.indexOf(lang+"-")===0;}}while((elem=elem.parentNode)&&elem.nodeType===1);return false;};}),"target":function(elem){var hash=window.location&&window.location.hash;return hash&&hash.slice(1)===elem.id;},"root":function(elem){return elem===docElem;},"focus":function(elem){return elem===document.activeElement&&(!document.hasFocus||document.hasFocus())&&!!(elem.type||elem.href||~elem.tabIndex);},"enabled":createDisabledPseudo(false),"disabled":createDisabledPseudo(true),"checked":function(elem){var nodeName=elem.nodeName.toLowerCase();return(nodeName==="input"&&!!elem.checked)||(nodeName==="option"&&!!elem.selected);},"selected":function(elem){if(elem.parentNode){elem.parentNode.selectedIndex;}return elem.selected===true;},"empty":function(elem){for(elem=elem.firstChild;elem;elem=elem.nextSibling){if(elem.nodeType<6){return false;}}return true;},"parent":function(elem){return!Expr.pseudos["empty"](elem);},"header":function(elem){return rheader.test(elem.nodeName);},"input":function(elem){return rinputs.test(elem.nodeName);},"button":function(elem){var name=elem.nodeName.toLowerCase();return name==="input"&&elem.type==="button"||name==="button";},"text":function(elem){var attr;return elem.nodeName.toLowerCase()==="input"&&elem.type==="text"&&((attr=elem.getAttribute("type"))==null||attr.toLowerCase()==="text");},"first":createPositionalPseudo(function(){return[0];}),"last":createPositionalPseudo(function(matchIndexes,length){return[length-1];}),"eq":createPositionalPseudo(function(matchIndexes,length,argument){return[argument<0?argument+length:argument];}),"even":createPositionalPseudo(function(matchIndexes,length){var i=0;for(;i<length;i+=2){matchIndexes.push(i);}return matchIndexes;}),"odd":createPositionalPseudo(function(matchIndexes,length){var i=1;for(;i<length;i+=2){matchIndexes.push(i);}return matchIndexes;}),"lt":createPositionalPseudo(function(matchIndexes,length,argument){var i=argument<0?argument+length:argument;for(;--i>=0;){matchIndexes.push(i);}return matchIndexes;}),"gt":createPositionalPseudo(function(matchIndexes,length,argument){var i=argument<0?argument+length:argument;for(;++i<length;){matchIndexes.push(i);}return matchIndexes;})}};Expr.pseudos["nth"]=Expr.pseudos["eq"];for(i in{radio:true,checkbox:true,file:true,password:true,image:true}){Expr.pseudos[i]=createInputPseudo(i);}for(i in{submit:true,reset:true}){Expr.pseudos[i]=createButtonPseudo(i);}function setFilters(){}setFilters.prototype=Expr.filters=Expr.pseudos;Expr.setFilters=new setFilters();tokenize=Sizzle.tokenize=function(selector,parseOnly){var matched,match,tokens,type,soFar,groups,preFilters,cached=tokenCache[selector+" "];if(cached){return parseOnly?0:cached.slice(0);}soFar=selector;groups=[];preFilters=Expr.preFilter;while(soFar){if(!matched||(match=rcomma.exec(soFar))){if(match){soFar=soFar.slice(match[0].length)||soFar;}groups.push((tokens=[]));}matched=false;if((match=rcombinators.exec(soFar))){matched=match.shift();tokens.push({value:matched,type:match[0].replace(rtrim," ")});soFar=soFar.slice(matched.length);}for(type in Expr.filter){if((match=matchExpr[type].exec(soFar))&&(!preFilters[type]||(match=preFilters[type](match)))){matched=match.shift();tokens.push({value:matched,type:type,matches:match});soFar=soFar.slice(matched.length);}}if(!matched){break;}}return parseOnly?soFar.length:soFar?Sizzle.error(selector):tokenCache(selector,groups).slice(0);};function toSelector(tokens){var i=0,len=tokens.length,selector="";for(;i<len;i++){selector+=tokens[i].value;}return selector;}function addCombinator(matcher,combinator,base){var dir=combinator.dir,skip=combinator.next,key=skip||dir,checkNonElements=base&&key==="parentNode",doneName=done++;return combinator.first?function(elem,context,xml){while((elem=elem[dir])){if(elem.nodeType===1||checkNonElements){return matcher(elem,context,xml);}}return false;}:function(elem,context,xml){var oldCache,uniqueCache,outerCache,newCache=[dirruns,doneName];if(xml){while((elem=elem[dir])){if(elem.nodeType===1||checkNonElements){if(matcher(elem,context,xml)){return true;}}}}else{while((elem=elem[dir])){if(elem.nodeType===1||checkNonElements){outerCache=elem[expando]||(elem[expando]={});uniqueCache=outerCache[elem.uniqueID]||(outerCache[elem.uniqueID]={});if(skip&&skip===elem.nodeName.toLowerCase()){elem=elem[dir]||elem;}else if((oldCache=uniqueCache[key])&&oldCache[0]===dirruns&&oldCache[1]===doneName){return(newCache[2]=oldCache[2]);}else{uniqueCache[key]=newCache;if((newCache[2]=matcher(elem,context,xml))){return true;}}}}}return false;};}function elementMatcher(matchers){return matchers.length>1?function(elem,context,xml){var i=matchers.length;while(i--){if(!matchers[i](elem,context,xml)){return false;}}return true;}:matchers[0];}function multipleContexts(selector,contexts,results){var i=0,len=contexts.length;for(;i<len;i++){Sizzle(selector,contexts[i],results);}return results;}function condense(unmatched,map,filter,context,xml){var elem,newUnmatched=[],i=0,len=unmatched.length,mapped=map!=null;for(;i<len;i++){if((elem=unmatched[i])){if(!filter||filter(elem,context,xml)){newUnmatched.push(elem);if(mapped){map.push(i);}}}}return newUnmatched;}function setMatcher(preFilter,selector,matcher,postFilter,postFinder,postSelector){if(postFilter&&!postFilter[expando]){postFilter=setMatcher(postFilter);}if(postFinder&&!postFinder[expando]){postFinder=setMatcher(postFinder,postSelector);}return markFunction(function(seed,results,context,xml){var temp,i,elem,preMap=[],postMap=[],preexisting=results.length,elems=seed||multipleContexts(selector||"*",context.nodeType?[context]:context,[]),matcherIn=preFilter&&(seed||!selector)?condense(elems,preMap,preFilter,context,xml):elems,matcherOut=matcher?postFinder||(seed?preFilter:preexisting||postFilter)?[]:results:matcherIn;if(matcher){matcher(matcherIn,matcherOut,context,xml);}if(postFilter){temp=condense(matcherOut,postMap);postFilter(temp,[],context,xml);i=temp.length;while(i--){if((elem=temp[i])){matcherOut[postMap[i]]=!(matcherIn[postMap[i]]=elem);}}}if(seed){if(postFinder||preFilter){if(postFinder){temp=[];i=matcherOut.length;while(i--){if((elem=matcherOut[i])){temp.push((matcherIn[i]=elem));}}postFinder(null,(matcherOut=[]),temp,xml);}i=matcherOut.length;while(i--){if((elem=matcherOut[i])&&(temp=postFinder?indexOf(seed,elem):preMap[i])>-1){seed[temp]=!(results[temp]=elem);}}}}else{matcherOut=condense(matcherOut===results?matcherOut.splice(preexisting,matcherOut.length):matcherOut);if(postFinder){postFinder(null,results,matcherOut,xml);}else{push.apply(results,matcherOut);}}});}function matcherFromTokens(tokens){var checkContext,matcher,j,len=tokens.length,leadingRelative=Expr.relative[tokens[0].type],implicitRelative=leadingRelative||Expr.relative[" "],i=leadingRelative?1:0,matchContext=addCombinator(function(elem){return elem===checkContext;},implicitRelative,true),matchAnyContext=addCombinator(function(elem){return indexOf(checkContext,elem)>-1;},implicitRelative,true),matchers=[function(elem,context,xml){var ret=(!leadingRelative&&(xml||context!==outermostContext))||((checkContext=context).nodeType?matchContext(elem,context,xml):matchAnyContext(elem,context,xml));checkContext=null;return ret;}];for(;i<len;i++){if((matcher=Expr.relative[tokens[i].type])){matchers=[addCombinator(elementMatcher(matchers),matcher)];}else{matcher=Expr.filter[tokens[i].type].apply(null,tokens[i].matches);if(matcher[expando]){j=++i;for(;j<len;j++){if(Expr.relative[tokens[j].type]){break;}}return setMatcher(i>1&&elementMatcher(matchers),i>1&&toSelector(tokens.slice(0,i-1).concat({value:tokens[i-2].type===" "?"*":""})).replace(rtrim,"$1"),matcher,i<j&&matcherFromTokens(tokens.slice(i,j)),j<len&&matcherFromTokens((tokens=tokens.slice(j))),j<len&&toSelector(tokens));}matchers.push(matcher);}}return elementMatcher(matchers);}function matcherFromGroupMatchers(elementMatchers,setMatchers){var bySet=setMatchers.length>0,byElement=elementMatchers.length>0,superMatcher=function(seed,context,xml,results,outermost){var elem,j,matcher,matchedCount=0,i="0",unmatched=seed&&[],setMatched=[],contextBackup=outermostContext,elems=seed||byElement&&Expr.find["TAG"]("*",outermost),dirrunsUnique=(dirruns+=contextBackup==null?1:Math.random()||0.1),len=elems.length;if(outermost){outermostContext=context===document||context||outermost;}for(;i!==len&&(elem=elems[i])!=null;i++){if(byElement&&elem){j=0;if(!context&&elem.ownerDocument!==document){setDocument(elem);xml=!documentIsHTML;}while((matcher=elementMatchers[j++])){if(matcher(elem,context||document,xml)){results.push(elem);break;}}if(outermost){dirruns=dirrunsUnique;}}if(bySet){if((elem=!matcher&&elem)){matchedCount--;}if(seed){unmatched.push(elem);}}}matchedCount+=i;if(bySet&&i!==matchedCount){j=0;while((matcher=setMatchers[j++])){matcher(unmatched,setMatched,context,xml);}if(seed){if(matchedCount>0){while(i--){if(!(unmatched[i]||setMatched[i])){setMatched[i]=pop.call(results);}}}setMatched=condense(setMatched);}push.apply(results,setMatched);if(outermost&&!seed&&setMatched.length>0&&(matchedCount+setMatchers.length)>1){Sizzle.uniqueSort(results);}}if(outermost){dirruns=dirrunsUnique;outermostContext=contextBackup;}return unmatched;};return bySet?markFunction(superMatcher):superMatcher;}compile=Sizzle.compile=function(selector,match){var i,setMatchers=[],elementMatchers=[],cached=compilerCache[selector+" "];if(!cached){if(!match){match=tokenize(selector);}i=match.length;while(i--){cached=matcherFromTokens(match[i]);if(cached[expando]){setMatchers.push(cached);}else{elementMatchers.push(cached);}}cached=compilerCache(selector,matcherFromGroupMatchers(elementMatchers,setMatchers));cached.selector=selector;}return cached;};select=Sizzle.select=function(selector,context,results,seed){var i,tokens,token,type,find,compiled=typeof selector==="function"&&selector,match=!seed&&tokenize((selector=compiled.selector||selector));results=results||[];if(match.length===1){tokens=match[0]=match[0].slice(0);if(tokens.length>2&&(token=tokens[0]).type==="ID"&&context.nodeType===9&&documentIsHTML&&Expr.relative[tokens[1].type]){context=(Expr.find["ID"](token.matches[0].replace(runescape,funescape),context)||[])[0];if(!context){return results;}else if(compiled){context=context.parentNode;}selector=selector.slice(tokens.shift().value.length);}i=matchExpr["needsContext"].test(selector)?0:tokens.length;while(i--){token=tokens[i];if(Expr.relative[(type=token.type)]){break;}if((find=Expr.find[type])){if((seed=find(token.matches[0].replace(runescape,funescape),rsibling.test(tokens[0].type)&&testContext(context.parentNode)||context))){tokens.splice(i,1);selector=seed.length&&toSelector(tokens);if(!selector){push.apply(results,seed);return results;}break;}}}}(compiled||compile(selector,match))(seed,context,!documentIsHTML,results,!context||rsibling.test(selector)&&testContext(context.parentNode)||context);return results;};support.sortStable=expando.split("").sort(sortOrder).join("")===expando;support.detectDuplicates=!!hasDuplicate;setDocument();support.sortDetached=assert(function(el){return el.compareDocumentPosition(document.createElement("fieldset"))&1;});if(!assert(function(el){el.innerHTML="<a href='#'></a>";return el.firstChild.getAttribute("href")==="#";})){addHandle("type|href|height|width",function(elem,name,isXML){if(!isXML){return elem.getAttribute(name,name.toLowerCase()==="type"?1:2);}});}if(!support.attributes||!assert(function(el){el.innerHTML="<input/>";el.firstChild.setAttribute("value","");return el.firstChild.getAttribute("value")==="";})){addHandle("value",function(elem,name,isXML){if(!isXML&&elem.nodeName.toLowerCase()==="input"){return elem.defaultValue;}});}if(!assert(function(el){return el.getAttribute("disabled")==null;})){addHandle(booleans,function(elem,name,isXML){var val;if(!isXML){return elem[name]===true?name.toLowerCase():(val=elem.getAttributeNode(name))&&val.specified?val.value:null;}});}return Sizzle;})(window);jQuery.find=Sizzle;jQuery.expr=Sizzle.selectors;jQuery.expr[":"]=jQuery.expr.pseudos;jQuery.uniqueSort=jQuery.unique=Sizzle.uniqueSort;jQuery.text=Sizzle.getText;jQuery.isXMLDoc=Sizzle.isXML;jQuery.contains=Sizzle.contains;jQuery.escapeSelector=Sizzle.escape;var dir=function(elem,dir,until){var matched=[],truncate=until!==undefined;while((elem=elem[dir])&&elem.nodeType!==9){if(elem.nodeType===1){if(truncate&&jQuery(elem).is(until)){break;}matched.push(elem);}}return matched;};var siblings=function(n,elem){var matched=[];for(;n;n=n.nextSibling){if(n.nodeType===1&&n!==elem){matched.push(n);}}return matched;};var rneedsContext=jQuery.expr.match.needsContext;var rsingleTag=(/^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i);var risSimple=/^.[^:#\[\.,]*$/;function winnow(elements,qualifier,not){if(jQuery.isFunction(qualifier)){return jQuery.grep(elements,function(elem,i){return!!qualifier.call(elem,i,elem)!==not;});}if(qualifier.nodeType){return jQuery.grep(elements,function(elem){return(elem===qualifier)!==not;});}if(typeof qualifier!=="string"){return jQuery.grep(elements,function(elem){return(indexOf.call(qualifier,elem)>-1)!==not;});}if(risSimple.test(qualifier)){return jQuery.filter(qualifier,elements,not);}qualifier=jQuery.filter(qualifier,elements);return jQuery.grep(elements,function(elem){return(indexOf.call(qualifier,elem)>-1)!==not&&elem.nodeType===1;});}jQuery.filter=function(expr,elems,not){var elem=elems[0];if(not){expr=":not("+expr+")";}if(elems.length===1&&elem.nodeType===1){return jQuery.find.matchesSelector(elem,expr)?[elem]:[];}return jQuery.find.matches(expr,jQuery.grep(elems,function(elem){return elem.nodeType===1;}));};jQuery.fn.extend({find:function(selector){var i,ret,len=this.length,self=this;if(typeof selector!=="string"){return this.pushStack(jQuery(selector).filter(function(){for(i=0;i<len;i++){if(jQuery.contains(self[i],this)){return true;}}}));}ret=this.pushStack([]);for(i=0;i<len;i++){jQuery.find(selector,self[i],ret);}return len>1?jQuery.uniqueSort(ret):ret;},filter:function(selector){return this.pushStack(winnow(this,selector||[],false));},not:function(selector){return this.pushStack(winnow(this,selector||[],true));},is:function(selector){return!!winnow(this,typeof selector==="string"&&rneedsContext.test(selector)?jQuery(selector):selector||[],false).length;}});var rootjQuery,rquickExpr=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/,init=jQuery.fn.init=function(selector,context,root){var match,elem;if(!selector){return this;}root=root||rootjQuery;if(typeof selector==="string"){if(selector[0]==="<"&&selector[selector.length-1]===">"&&selector.length>=3){match=[null,selector,null];}else{match=rquickExpr.exec(selector);}if(match&&(match[1]||!context)){if(match[1]){context=context instanceof jQuery?context[0]:context;jQuery.merge(this,jQuery.parseHTML(match[1],context&&context.nodeType?context.ownerDocument||context:document,true));if(rsingleTag.test(match[1])&&jQuery.isPlainObject(context)){for(match in context){if(jQuery.isFunction(this[match])){this[match](context[match]);}else{this.attr(match,context[match]);}}}return this;}else{elem=document.getElementById(match[2]);if(elem){this[0]=elem;this.length=1;}return this;}}else if(!context||context.jquery){return(context||root).find(selector);}else{return this.constructor(context).find(selector);}}else if(selector.nodeType){this[0]=selector;this.length=1;return this;}else if(jQuery.isFunction(selector)){return root.ready!==undefined?root.ready(selector):selector(jQuery);}return jQuery.makeArray(selector,this);};init.prototype=jQuery.fn;rootjQuery=jQuery(document);var rparentsprev=/^(?:parents|prev(?:Until|All))/,guaranteedUnique={children:true,contents:true,next:true,prev:true};jQuery.fn.extend({has:function(target){var targets=jQuery(target,this),l=targets.length;return this.filter(function(){var i=0;for(;i<l;i++){if(jQuery.contains(this,targets[i])){return true;}}});},closest:function(selectors,context){var cur,i=0,l=this.length,matched=[],targets=typeof selectors!=="string"&&jQuery(selectors);if(!rneedsContext.test(selectors)){for(;i<l;i++){for(cur=this[i];cur&&cur!==context;cur=cur.parentNode){if(cur.nodeType<11&&(targets?targets.index(cur)>-1:cur.nodeType===1&&jQuery.find.matchesSelector(cur,selectors))){matched.push(cur);break;}}}}return this.pushStack(matched.length>1?jQuery.uniqueSort(matched):matched);},index:function(elem){if(!elem){return(this[0]&&this[0].parentNode)?this.first().prevAll().length:-1;}if(typeof elem==="string"){return indexOf.call(jQuery(elem),this[0]);}return indexOf.call(this,elem.jquery?elem[0]:elem);},add:function(selector,context){return this.pushStack(jQuery.uniqueSort(jQuery.merge(this.get(),jQuery(selector,context))));},addBack:function(selector){return this.add(selector==null?this.prevObject:this.prevObject.filter(selector));}});function sibling(cur,dir){while((cur=cur[dir])&&cur.nodeType!==1){}return cur;}jQuery.each({parent:function(elem){var parent=elem.parentNode;return parent&&parent.nodeType!==11?parent:null;},parents:function(elem){return dir(elem,"parentNode");},parentsUntil:function(elem,i,until){return dir(elem,"parentNode",until);},next:function(elem){return sibling(elem,"nextSibling");},prev:function(elem){return sibling(elem,"previousSibling");},nextAll:function(elem){return dir(elem,"nextSibling");},prevAll:function(elem){return dir(elem,"previousSibling");},nextUntil:function(elem,i,until){return dir(elem,"nextSibling",until);},prevUntil:function(elem,i,until){return dir(elem,"previousSibling",until);},siblings:function(elem){return siblings((elem.parentNode||{}).firstChild,elem);},children:function(elem){return siblings(elem.firstChild);},contents:function(elem){return elem.contentDocument||jQuery.merge([],elem.childNodes);}},function(name,fn){jQuery.fn[name]=function(until,selector){var matched=jQuery.map(this,fn,until);if(name.slice(-5)!=="Until"){selector=until;}if(selector&&typeof selector==="string"){matched=jQuery.filter(selector,matched);}if(this.length>1){if(!guaranteedUnique[name]){jQuery.uniqueSort(matched);}if(rparentsprev.test(name)){matched.reverse();}}return this.pushStack(matched);};});var rnothtmlwhite=(/[^\x20\t\r\n\f]+/g);function createOptions(options){var object={};jQuery.each(options.match(rnothtmlwhite)||[],function(_,flag){object[flag]=true;});return object;}jQuery.Callbacks=function(options){options=typeof options==="string"?createOptions(options):jQuery.extend({},options);var firing,memory,fired,locked,list=[],queue=[],firingIndex=-1,fire=function(){locked=options.once;fired=firing=true;for(;queue.length;firingIndex=-1){memory=queue.shift();while(++firingIndex<list.length){if(list[firingIndex].apply(memory[0],memory[1])===false&&options.stopOnFalse){firingIndex=list.length;memory=false;}}}if(!options.memory){memory=false;}firing=false;if(locked){if(memory){list=[];}else{list="";}}},self={add:function(){if(list){if(memory&&!firing){firingIndex=list.length-1;queue.push(memory);}(function add(args){jQuery.each(args,function(_,arg){if(jQuery.isFunction(arg)){if(!options.unique||!self.has(arg)){list.push(arg);}}else if(arg&&arg.length&&jQuery.type(arg)!=="string"){add(arg);}});})(arguments);if(memory&&!firing){fire();}}return this;},remove:function(){jQuery.each(arguments,function(_,arg){var index;while((index=jQuery.inArray(arg,list,index))>-1){list.splice(index,1);if(index<=firingIndex){firingIndex--;}}});return this;},has:function(fn){return fn?jQuery.inArray(fn,list)>-1:list.length>0;},empty:function(){if(list){list=[];}return this;},disable:function(){locked=queue=[];list=memory="";return this;},disabled:function(){return!list;},lock:function(){locked=queue=[];if(!memory&&!firing){list=memory="";}return this;},locked:function(){return!!locked;},fireWith:function(context,args){if(!locked){args=args||[];args=[context,args.slice?args.slice():args];queue.push(args);if(!firing){fire();}}return this;},fire:function(){self.fireWith(this,arguments);return this;},fired:function(){return!!fired;}};return self;};function Identity(v){return v;}function Thrower(ex){throw ex;}function adoptValue(value,resolve,reject){var method;try{if(value&&jQuery.isFunction((method=value.promise))){method.call(value).done(resolve).fail(reject);}else if(value&&jQuery.isFunction((method=value.then))){method.call(value,resolve,reject);}else{resolve.call(undefined,value);}}catch(value){reject.call(undefined,value);}}jQuery.extend({Deferred:function(func){var tuples=[["notify","progress",jQuery.Callbacks("memory"),jQuery.Callbacks("memory"),2],["resolve","done",jQuery.Callbacks("once memory"),jQuery.Callbacks("once memory"),0,"resolved"],["reject","fail",jQuery.Callbacks("once memory"),jQuery.Callbacks("once memory"),1,"rejected"]],state="pending",promise={state:function(){return state;},always:function(){deferred.done(arguments).fail(arguments);return this;},"catch":function(fn){return promise.then(null,fn);},pipe:function(){var fns=arguments;return jQuery.Deferred(function(newDefer){jQuery.each(tuples,function(i,tuple){var fn=jQuery.isFunction(fns[tuple[4]])&&fns[tuple[4]];deferred[tuple[1]](function(){var returned=fn&&fn.apply(this,arguments);if(returned&&jQuery.isFunction(returned.promise)){returned.promise().progress(newDefer.notify).done(newDefer.resolve).fail(newDefer.reject);}else{newDefer[tuple[0]+"With"](this,fn?[returned]:arguments);}});});fns=null;}).promise();},then:function(onFulfilled,onRejected,onProgress){var maxDepth=0;function resolve(depth,deferred,handler,special){return function(){var that=this,args=arguments,mightThrow=function(){var returned,then;if(depth<maxDepth){return;}returned=handler.apply(that,args);if(returned===deferred.promise()){throw new TypeError("Thenable self-resolution");}then=returned&&(typeof returned==="object"||typeof returned==="function")&&returned.then;if(jQuery.isFunction(then)){if(special){then.call(returned,resolve(maxDepth,deferred,Identity,special),resolve(maxDepth,deferred,Thrower,special));}else{maxDepth++;then.call(returned,resolve(maxDepth,deferred,Identity,special),resolve(maxDepth,deferred,Thrower,special),resolve(maxDepth,deferred,Identity,deferred.notifyWith));}}else{if(handler!==Identity){that=undefined;args=[returned];}(special||deferred.resolveWith)(that,args);}},process=special?mightThrow:function(){try{mightThrow();}catch(e){if(jQuery.Deferred.exceptionHook){jQuery.Deferred.exceptionHook(e,process.stackTrace);}if(depth+1>=maxDepth){if(handler!==Thrower){that=undefined;args=[e];}deferred.rejectWith(that,args);}}};if(depth){process();}else{if(jQuery.Deferred.getStackHook){process.stackTrace=jQuery.Deferred.getStackHook();}window.setTimeout(process);}};}return jQuery.Deferred(function(newDefer){tuples[0][3].add(resolve(0,newDefer,jQuery.isFunction(onProgress)?onProgress:Identity,newDefer.notifyWith));tuples[1][3].add(resolve(0,newDefer,jQuery.isFunction(onFulfilled)?onFulfilled:Identity));tuples[2][3].add(resolve(0,newDefer,jQuery.isFunction(onRejected)?onRejected:Thrower));}).promise();},promise:function(obj){return obj!=null?jQuery.extend(obj,promise):promise;}},deferred={};jQuery.each(tuples,function(i,tuple){var list=tuple[2],stateString=tuple[5];promise[tuple[1]]=list.add;if(stateString){list.add(function(){state=stateString;},tuples[3-i][2].disable,tuples[0][2].lock);}list.add(tuple[3].fire);deferred[tuple[0]]=function(){deferred[tuple[0]+"With"](this===deferred?undefined:this,arguments);return this;};deferred[tuple[0]+"With"]=list.fireWith;});promise.promise(deferred);if(func){func.call(deferred,deferred);}return deferred;},when:function(singleValue){var remaining=arguments.length,i=remaining,resolveContexts=Array(i),resolveValues=slice.call(arguments),master=jQuery.Deferred(),updateFunc=function(i){return function(value){resolveContexts[i]=this;resolveValues[i]=arguments.length>1?slice.call(arguments):value;if(!(--remaining)){master.resolveWith(resolveContexts,resolveValues);}};};if(remaining<=1){adoptValue(singleValue,master.done(updateFunc(i)).resolve,master.reject);if(master.state()==="pending"||jQuery.isFunction(resolveValues[i]&&resolveValues[i].then)){return master.then();}}while(i--){adoptValue(resolveValues[i],updateFunc(i),master.reject);}return master.promise();}});var rerrorNames=/^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;jQuery.Deferred.exceptionHook=function(error,stack){if(window.console&&window.console.warn&&error&&rerrorNames.test(error.name)){window.console.warn("jQuery.Deferred exception: "+error.message,error.stack,stack);}};jQuery.readyException=function(error){window.setTimeout(function(){throw error;});};var readyList=jQuery.Deferred();jQuery.fn.ready=function(fn){readyList.then(fn).catch(function(error){jQuery.readyException(error);});return this;};jQuery.extend({isReady:false,readyWait:1,holdReady:function(hold){if(hold){jQuery.readyWait++;}else{jQuery.ready(true);}},ready:function(wait){if(wait===true?--jQuery.readyWait:jQuery.isReady){return;}jQuery.isReady=true;if(wait!==true&&--jQuery.readyWait>0){return;}readyList.resolveWith(document,[jQuery]);}});jQuery.ready.then=readyList.then;function completed(){document.removeEventListener("DOMContentLoaded",completed);window.removeEventListener("load",completed);jQuery.ready();}if(document.readyState==="complete"||(document.readyState!=="loading"&&!document.documentElement.doScroll)){window.setTimeout(jQuery.ready);}else{document.addEventListener("DOMContentLoaded",completed);window.addEventListener("load",completed);}var access=function(elems,fn,key,value,chainable,emptyGet,raw){var i=0,len=elems.length,bulk=key==null;if(jQuery.type(key)==="object"){chainable=true;for(i in key){access(elems,fn,i,key[i],true,emptyGet,raw);}}else if(value!==undefined){chainable=true;if(!jQuery.isFunction(value)){raw=true;}if(bulk){if(raw){fn.call(elems,value);fn=null;}else{bulk=fn;fn=function(elem,key,value){return bulk.call(jQuery(elem),value);};}}if(fn){for(;i<len;i++){fn(elems[i],key,raw?value:value.call(elems[i],i,fn(elems[i],key)));}}}if(chainable){return elems;}if(bulk){return fn.call(elems);}return len?fn(elems[0],key):emptyGet;};var acceptData=function(owner){return owner.nodeType===1||owner.nodeType===9||!(+owner.nodeType);};function Data(){this.expando=jQuery.expando+Data.uid++;}Data.uid=1;Data.prototype={cache:function(owner){var value=owner[this.expando];if(!value){value={};if(acceptData(owner)){if(owner.nodeType){owner[this.expando]=value;}else{Object.defineProperty(owner,this.expando,{value:value,configurable:true});}}}return value;},set:function(owner,data,value){var prop,cache=this.cache(owner);if(typeof data==="string"){cache[jQuery.camelCase(data)]=value;}else{for(prop in data){cache[jQuery.camelCase(prop)]=data[prop];}}return cache;},get:function(owner,key){return key===undefined?this.cache(owner):owner[this.expando]&&owner[this.expando][jQuery.camelCase(key)];},access:function(owner,key,value){if(key===undefined||((key&&typeof key==="string")&&value===undefined)){return this.get(owner,key);}this.set(owner,key,value);return value!==undefined?value:key;},remove:function(owner,key){var i,cache=owner[this.expando];if(cache===undefined){return;}if(key!==undefined){if(jQuery.isArray(key)){key=key.map(jQuery.camelCase);}else{key=jQuery.camelCase(key);key=key in cache?[key]:(key.match(rnothtmlwhite)||[]);}i=key.length;while(i--){delete cache[key[i]];}}if(key===undefined||jQuery.isEmptyObject(cache)){if(owner.nodeType){owner[this.expando]=undefined;}else{delete owner[this.expando];}}},hasData:function(owner){var cache=owner[this.expando];return cache!==undefined&&!jQuery.isEmptyObject(cache);}};var dataPriv=new Data();var dataUser=new Data();var rbrace=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,rmultiDash=/[A-Z]/g;function getData(data){if(data==="true"){return true;}if(data==="false"){return false;}if(data==="null"){return null;}if(data===+data+""){return+data;}if(rbrace.test(data)){return JSON.parse(data);}return data;}function dataAttr(elem,key,data){var name;if(data===undefined&&elem.nodeType===1){name="data-"+key.replace(rmultiDash,"-$&").toLowerCase();data=elem.getAttribute(name);if(typeof data==="string"){try{data=getData(data);}catch(e){}dataUser.set(elem,key,data);}else{data=undefined;}}return data;}jQuery.extend({hasData:function(elem){return dataUser.hasData(elem)||dataPriv.hasData(elem);},data:function(elem,name,data){return dataUser.access(elem,name,data);},removeData:function(elem,name){dataUser.remove(elem,name);},_data:function(elem,name,data){return dataPriv.access(elem,name,data);},_removeData:function(elem,name){dataPriv.remove(elem,name);}});jQuery.fn.extend({data:function(key,value){var i,name,data,elem=this[0],attrs=elem&&elem.attributes;if(key===undefined){if(this.length){data=dataUser.get(elem);if(elem.nodeType===1&&!dataPriv.get(elem,"hasDataAttrs")){i=attrs.length;while(i--){if(attrs[i]){name=attrs[i].name;if(name.indexOf("data-")===0){name=jQuery.camelCase(name.slice(5));dataAttr(elem,name,data[name]);}}}dataPriv.set(elem,"hasDataAttrs",true);}}return data;}if(typeof key==="object"){return this.each(function(){dataUser.set(this,key);});}return access(this,function(value){var data;if(elem&&value===undefined){data=dataUser.get(elem,key);if(data!==undefined){return data;}data=dataAttr(elem,key);if(data!==undefined){return data;}return;}this.each(function(){dataUser.set(this,key,value);});},null,value,arguments.length>1,null,true);},removeData:function(key){return this.each(function(){dataUser.remove(this,key);});}});jQuery.extend({queue:function(elem,type,data){var queue;if(elem){type=(type||"fx")+"queue";queue=dataPriv.get(elem,type);if(data){if(!queue||jQuery.isArray(data)){queue=dataPriv.access(elem,type,jQuery.makeArray(data));}else{queue.push(data);}}return queue||[];}},dequeue:function(elem,type){type=type||"fx";var queue=jQuery.queue(elem,type),startLength=queue.length,fn=queue.shift(),hooks=jQuery._queueHooks(elem,type),next=function(){jQuery.dequeue(elem,type);};if(fn==="inprogress"){fn=queue.shift();startLength--;}if(fn){if(type==="fx"){queue.unshift("inprogress");}delete hooks.stop;fn.call(elem,next,hooks);}if(!startLength&&hooks){hooks.empty.fire();}},_queueHooks:function(elem,type){var key=type+"queueHooks";return dataPriv.get(elem,key)||dataPriv.access(elem,key,{empty:jQuery.Callbacks("once memory").add(function(){dataPriv.remove(elem,[type+"queue",key]);})});}});jQuery.fn.extend({queue:function(type,data){var setter=2;if(typeof type!=="string"){data=type;type="fx";setter--;}if(arguments.length<setter){return jQuery.queue(this[0],type);}return data===undefined?this:this.each(function(){var queue=jQuery.queue(this,type,data);jQuery._queueHooks(this,type);if(type==="fx"&&queue[0]!=="inprogress"){jQuery.dequeue(this,type);}});},dequeue:function(type){return this.each(function(){jQuery.dequeue(this,type);});},clearQueue:function(type){return this.queue(type||"fx",[]);},promise:function(type,obj){var tmp,count=1,defer=jQuery.Deferred(),elements=this,i=this.length,resolve=function(){if(!(--count)){defer.resolveWith(elements,[elements]);}};if(typeof type!=="string"){obj=type;type=undefined;}type=type||"fx";while(i--){tmp=dataPriv.get(elements[i],type+"queueHooks");if(tmp&&tmp.empty){count++;tmp.empty.add(resolve);}}resolve();return defer.promise(obj);}});var pnum=(/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source;var rcssNum=new RegExp("^(?:([+-])=|)("+pnum+")([a-z%]*)$","i");var cssExpand=["Top","Right","Bottom","Left"];var isHiddenWithinTree=function(elem,el){elem=el||elem;return elem.style.display==="none"||elem.style.display===""&&jQuery.contains(elem.ownerDocument,elem)&&jQuery.css(elem,"display")==="none";};var swap=function(elem,options,callback,args){var ret,name,old={};for(name in options){old[name]=elem.style[name];elem.style[name]=options[name];}ret=callback.apply(elem,args||[]);for(name in options){elem.style[name]=old[name];}return ret;};function adjustCSS(elem,prop,valueParts,tween){var adjusted,scale=1,maxIterations=20,currentValue=tween?function(){return tween.cur();}:function(){return jQuery.css(elem,prop,"");},initial=currentValue(),unit=valueParts&&valueParts[3]||(jQuery.cssNumber[prop]?"":"px"),initialInUnit=(jQuery.cssNumber[prop]||unit!=="px"&&+initial)&&rcssNum.exec(jQuery.css(elem,prop));if(initialInUnit&&initialInUnit[3]!==unit){unit=unit||initialInUnit[3];valueParts=valueParts||[];initialInUnit=+initial||1;do{scale=scale||".5";initialInUnit=initialInUnit/scale;jQuery.style(elem,prop,initialInUnit+unit);}while(scale!==(scale=currentValue()/initial)&&scale!==1&&--maxIterations);}if(valueParts){initialInUnit=+initialInUnit||+initial||0;adjusted=valueParts[1]?initialInUnit+(valueParts[1]+1)*valueParts[2]:+valueParts[2];if(tween){tween.unit=unit;tween.start=initialInUnit;tween.end=adjusted;}}return adjusted;}var defaultDisplayMap={};function getDefaultDisplay(elem){var temp,doc=elem.ownerDocument,nodeName=elem.nodeName,display=defaultDisplayMap[nodeName];if(display){return display;}temp=doc.body.appendChild(doc.createElement(nodeName));display=jQuery.css(temp,"display");temp.parentNode.removeChild(temp);if(display==="none"){display="block";}defaultDisplayMap[nodeName]=display;return display;}function showHide(elements,show){var display,elem,values=[],index=0,length=elements.length;for(;index<length;index++){elem=elements[index];if(!elem.style){continue;}display=elem.style.display;if(show){if(display==="none"){values[index]=dataPriv.get(elem,"display")||null;if(!values[index]){elem.style.display="";}}if(elem.style.display===""&&isHiddenWithinTree(elem)){values[index]=getDefaultDisplay(elem);}}else{if(display!=="none"){values[index]="none";dataPriv.set(elem,"display",display);}}}for(index=0;index<length;index++){if(values[index]!=null){elements[index].style.display=values[index];}}return elements;}jQuery.fn.extend({show:function(){return showHide(this,true);},hide:function(){return showHide(this);},toggle:function(state){if(typeof state==="boolean"){return state?this.show():this.hide();}return this.each(function(){if(isHiddenWithinTree(this)){jQuery(this).show();}else{jQuery(this).hide();}});}});var rcheckableType=(/^(?:checkbox|radio)$/i);var rtagName=(/<([a-z][^\/\0>\x20\t\r\n\f]+)/i);var rscriptType=(/^$|\/(?:java|ecma)script/i);var wrapMap={option:[1,"<select multiple='multiple'>","</select>"],thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};wrapMap.optgroup=wrapMap.option;wrapMap.tbody=wrapMap.tfoot=wrapMap.colgroup=wrapMap.caption=wrapMap.thead;wrapMap.th=wrapMap.td;function getAll(context,tag){var ret;if(typeof context.getElementsByTagName!=="undefined"){ret=context.getElementsByTagName(tag||"*");}else if(typeof context.querySelectorAll!=="undefined"){ret=context.querySelectorAll(tag||"*");}else{ret=[];}if(tag===undefined||tag&&jQuery.nodeName(context,tag)){return jQuery.merge([context],ret);}return ret;}function setGlobalEval(elems,refElements){var i=0,l=elems.length;for(;i<l;i++){dataPriv.set(elems[i],"globalEval",!refElements||dataPriv.get(refElements[i],"globalEval"));}}var rhtml=/<|&#?\w+;/;function buildFragment(elems,context,scripts,selection,ignored){var elem,tmp,tag,wrap,contains,j,fragment=context.createDocumentFragment(),nodes=[],i=0,l=elems.length;for(;i<l;i++){elem=elems[i];if(elem||elem===0){if(jQuery.type(elem)==="object"){jQuery.merge(nodes,elem.nodeType?[elem]:elem);}else if(!rhtml.test(elem)){nodes.push(context.createTextNode(elem));}else{tmp=tmp||fragment.appendChild(context.createElement("div"));tag=(rtagName.exec(elem)||["",""])[1].toLowerCase();wrap=wrapMap[tag]||wrapMap._default;tmp.innerHTML=wrap[1]+jQuery.htmlPrefilter(elem)+wrap[2];j=wrap[0];while(j--){tmp=tmp.lastChild;}jQuery.merge(nodes,tmp.childNodes);tmp=fragment.firstChild;tmp.textContent="";}}}fragment.textContent="";i=0;while((elem=nodes[i++])){if(selection&&jQuery.inArray(elem,selection)>-1){if(ignored){ignored.push(elem);}continue;}contains=jQuery.contains(elem.ownerDocument,elem);tmp=getAll(fragment.appendChild(elem),"script");if(contains){setGlobalEval(tmp);}if(scripts){j=0;while((elem=tmp[j++])){if(rscriptType.test(elem.type||"")){scripts.push(elem);}}}}return fragment;}(function(){var fragment=document.createDocumentFragment(),div=fragment.appendChild(document.createElement("div")),input=document.createElement("input");input.setAttribute("type","radio");input.setAttribute("checked","checked");input.setAttribute("name","t");div.appendChild(input);support.checkClone=div.cloneNode(true).cloneNode(true).lastChild.checked;div.innerHTML="<textarea>x</textarea>";support.noCloneChecked=!!div.cloneNode(true).lastChild.defaultValue;}());var documentElement=document.documentElement;var rkeyEvent=/^key/,rmouseEvent=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,rtypenamespace=/^([^.]*)(?:\.(.+)|)/;function returnTrue(){return true;}function returnFalse(){return false;}function safeActiveElement(){try{return document.activeElement;}catch(err){}}function on(elem,types,selector,data,fn,one){var origFn,type;if(typeof types==="object"){if(typeof selector!=="string"){data=data||selector;selector=undefined;}for(type in types){on(elem,type,selector,data,types[type],one);}return elem;}if(data==null&&fn==null){fn=selector;data=selector=undefined;}else if(fn==null){if(typeof selector==="string"){fn=data;data=undefined;}else{fn=data;data=selector;selector=undefined;}}if(fn===false){fn=returnFalse;}else if(!fn){return elem;}if(one===1){origFn=fn;fn=function(event){jQuery().off(event);return origFn.apply(this,arguments);};fn.guid=origFn.guid||(origFn.guid=jQuery.guid++);}return elem.each(function(){jQuery.event.add(this,types,fn,data,selector);});}jQuery.event={global:{},add:function(elem,types,handler,data,selector){var handleObjIn,eventHandle,tmp,events,t,handleObj,special,handlers,type,namespaces,origType,elemData=dataPriv.get(elem);if(!elemData){return;}if(handler.handler){handleObjIn=handler;handler=handleObjIn.handler;selector=handleObjIn.selector;}if(selector){jQuery.find.matchesSelector(documentElement,selector);}if(!handler.guid){handler.guid=jQuery.guid++;}if(!(events=elemData.events)){events=elemData.events={};}if(!(eventHandle=elemData.handle)){eventHandle=elemData.handle=function(e){return typeof jQuery!=="undefined"&&jQuery.event.triggered!==e.type?jQuery.event.dispatch.apply(elem,arguments):undefined;};}types=(types||"").match(rnothtmlwhite)||[""];t=types.length;while(t--){tmp=rtypenamespace.exec(types[t])||[];type=origType=tmp[1];namespaces=(tmp[2]||"").split(".").sort();if(!type){continue;}special=jQuery.event.special[type]||{};type=(selector?special.delegateType:special.bindType)||type;special=jQuery.event.special[type]||{};handleObj=jQuery.extend({type:type,origType:origType,data:data,handler:handler,guid:handler.guid,selector:selector,needsContext:selector&&jQuery.expr.match.needsContext.test(selector),namespace:namespaces.join(".")},handleObjIn);if(!(handlers=events[type])){handlers=events[type]=[];handlers.delegateCount=0;if(!special.setup||special.setup.call(elem,data,namespaces,eventHandle)===false){if(elem.addEventListener){elem.addEventListener(type,eventHandle);}}}if(special.add){special.add.call(elem,handleObj);if(!handleObj.handler.guid){handleObj.handler.guid=handler.guid;}}if(selector){handlers.splice(handlers.delegateCount++,0,handleObj);}else{handlers.push(handleObj);}jQuery.event.global[type]=true;}},remove:function(elem,types,handler,selector,mappedTypes){var j,origCount,tmp,events,t,handleObj,special,handlers,type,namespaces,origType,elemData=dataPriv.hasData(elem)&&dataPriv.get(elem);if(!elemData||!(events=elemData.events)){return;}types=(types||"").match(rnothtmlwhite)||[""];t=types.length;while(t--){tmp=rtypenamespace.exec(types[t])||[];type=origType=tmp[1];namespaces=(tmp[2]||"").split(".").sort();if(!type){for(type in events){jQuery.event.remove(elem,type+types[t],handler,selector,true);}continue;}special=jQuery.event.special[type]||{};type=(selector?special.delegateType:special.bindType)||type;handlers=events[type]||[];tmp=tmp[2]&&new RegExp("(^|\\.)"+namespaces.join("\\.(?:.*\\.|)")+"(\\.|$)");origCount=j=handlers.length;while(j--){handleObj=handlers[j];if((mappedTypes||origType===handleObj.origType)&&(!handler||handler.guid===handleObj.guid)&&(!tmp||tmp.test(handleObj.namespace))&&(!selector||selector===handleObj.selector||selector==="**"&&handleObj.selector)){handlers.splice(j,1);if(handleObj.selector){handlers.delegateCount--;}if(special.remove){special.remove.call(elem,handleObj);}}}if(origCount&&!handlers.length){if(!special.teardown||special.teardown.call(elem,namespaces,elemData.handle)===false){jQuery.removeEvent(elem,type,elemData.handle);}delete events[type];}}if(jQuery.isEmptyObject(events)){dataPriv.remove(elem,"handle events");}},dispatch:function(nativeEvent){var event=jQuery.event.fix(nativeEvent);var i,j,ret,matched,handleObj,handlerQueue,args=new Array(arguments.length),handlers=(dataPriv.get(this,"events")||{})[event.type]||[],special=jQuery.event.special[event.type]||{};args[0]=event;for(i=1;i<arguments.length;i++){args[i]=arguments[i];}event.delegateTarget=this;if(special.preDispatch&&special.preDispatch.call(this,event)===false){return;}handlerQueue=jQuery.event.handlers.call(this,event,handlers);i=0;while((matched=handlerQueue[i++])&&!event.isPropagationStopped()){event.currentTarget=matched.elem;j=0;while((handleObj=matched.handlers[j++])&&!event.isImmediatePropagationStopped()){if(!event.rnamespace||event.rnamespace.test(handleObj.namespace)){event.handleObj=handleObj;event.data=handleObj.data;ret=((jQuery.event.special[handleObj.origType]||{}).handle||handleObj.handler).apply(matched.elem,args);if(ret!==undefined){if((event.result=ret)===false){event.preventDefault();event.stopPropagation();}}}}}if(special.postDispatch){special.postDispatch.call(this,event);}return event.result;},handlers:function(event,handlers){var i,handleObj,sel,matchedHandlers,matchedSelectors,handlerQueue=[],delegateCount=handlers.delegateCount,cur=event.target;if(delegateCount&&cur.nodeType&&!(event.type==="click"&&event.button>=1)){for(;cur!==this;cur=cur.parentNode||this){if(cur.nodeType===1&&!(event.type==="click"&&cur.disabled===true)){matchedHandlers=[];matchedSelectors={};for(i=0;i<delegateCount;i++){handleObj=handlers[i];sel=handleObj.selector+" ";if(matchedSelectors[sel]===undefined){matchedSelectors[sel]=handleObj.needsContext?jQuery(sel,this).index(cur)>-1:jQuery.find(sel,this,null,[cur]).length;}if(matchedSelectors[sel]){matchedHandlers.push(handleObj);}}if(matchedHandlers.length){handlerQueue.push({elem:cur,handlers:matchedHandlers});}}}}cur=this;if(delegateCount<handlers.length){handlerQueue.push({elem:cur,handlers:handlers.slice(delegateCount)});}return handlerQueue;},addProp:function(name,hook){Object.defineProperty(jQuery.Event.prototype,name,{enumerable:true,configurable:true,get:jQuery.isFunction(hook)?function(){if(this.originalEvent){return hook(this.originalEvent);}}:function(){if(this.originalEvent){return this.originalEvent[name];}},set:function(value){Object.defineProperty(this,name,{enumerable:true,configurable:true,writable:true,value:value});}});},fix:function(originalEvent){return originalEvent[jQuery.expando]?originalEvent:new jQuery.Event(originalEvent);},special:{load:{noBubble:true},focus:{trigger:function(){if(this!==safeActiveElement()&&this.focus){this.focus();return false;}},delegateType:"focusin"},blur:{trigger:function(){if(this===safeActiveElement()&&this.blur){this.blur();return false;}},delegateType:"focusout"},click:{trigger:function(){if(this.type==="checkbox"&&this.click&&jQuery.nodeName(this,"input")){this.click();return false;}},_default:function(event){return jQuery.nodeName(event.target,"a");}},beforeunload:{postDispatch:function(event){if(event.result!==undefined&&event.originalEvent){event.originalEvent.returnValue=event.result;}}}}};jQuery.removeEvent=function(elem,type,handle){if(elem.removeEventListener){elem.removeEventListener(type,handle);}};jQuery.Event=function(src,props){if(!(this instanceof jQuery.Event)){return new jQuery.Event(src,props);}if(src&&src.type){this.originalEvent=src;this.type=src.type;this.isDefaultPrevented=src.defaultPrevented||src.defaultPrevented===undefined&&src.returnValue===false?returnTrue:returnFalse;this.target=(src.target&&src.target.nodeType===3)?src.target.parentNode:src.target;this.currentTarget=src.currentTarget;this.relatedTarget=src.relatedTarget;}else{this.type=src;}if(props){jQuery.extend(this,props);}this.timeStamp=src&&src.timeStamp||jQuery.now();this[jQuery.expando]=true;};jQuery.Event.prototype={constructor:jQuery.Event,isDefaultPrevented:returnFalse,isPropagationStopped:returnFalse,isImmediatePropagationStopped:returnFalse,isSimulated:false,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=returnTrue;if(e&&!this.isSimulated){e.preventDefault();}},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=returnTrue;if(e&&!this.isSimulated){e.stopPropagation();}},stopImmediatePropagation:function(){var e=this.originalEvent;this.isImmediatePropagationStopped=returnTrue;if(e&&!this.isSimulated){e.stopImmediatePropagation();}this.stopPropagation();}};jQuery.each({altKey:true,bubbles:true,cancelable:true,changedTouches:true,ctrlKey:true,detail:true,eventPhase:true,metaKey:true,pageX:true,pageY:true,shiftKey:true,view:true,"char":true,charCode:true,key:true,keyCode:true,button:true,buttons:true,clientX:true,clientY:true,offsetX:true,offsetY:true,pointerId:true,pointerType:true,screenX:true,screenY:true,targetTouches:true,toElement:true,touches:true,which:function(event){var button=event.button;if(event.which==null&&rkeyEvent.test(event.type)){return event.charCode!=null?event.charCode:event.keyCode;}if(!event.which&&button!==undefined&&rmouseEvent.test(event.type)){if(button&1){return 1;}if(button&2){return 3;}if(button&4){return 2;}return 0;}return event.which;}},jQuery.event.addProp);jQuery.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(orig,fix){jQuery.event.special[orig]={delegateType:fix,bindType:fix,handle:function(event){var ret,target=this,related=event.relatedTarget,handleObj=event.handleObj;if(!related||(related!==target&&!jQuery.contains(target,related))){event.type=handleObj.origType;ret=handleObj.handler.apply(this,arguments);event.type=fix;}return ret;}};});jQuery.fn.extend({on:function(types,selector,data,fn){return on(this,types,selector,data,fn);},one:function(types,selector,data,fn){return on(this,types,selector,data,fn,1);},off:function(types,selector,fn){var handleObj,type;if(types&&types.preventDefault&&types.handleObj){handleObj=types.handleObj;jQuery(types.delegateTarget).off(handleObj.namespace?handleObj.origType+"."+handleObj.namespace:handleObj.origType,handleObj.selector,handleObj.handler);return this;}if(typeof types==="object"){for(type in types){this.off(type,selector,types[type]);}return this;}if(selector===false||typeof selector==="function"){fn=selector;selector=undefined;}if(fn===false){fn=returnFalse;}return this.each(function(){jQuery.event.remove(this,types,fn,selector);});}});var rxhtmlTag=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi,rnoInnerhtml=/<script|<style|<link/i,rchecked=/checked\s*(?:[^=]|=\s*.checked.)/i,rscriptTypeMasked=/^true\/(.*)/,rcleanScript=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;function manipulationTarget(elem,content){if(jQuery.nodeName(elem,"table")&&jQuery.nodeName(content.nodeType!==11?content:content.firstChild,"tr")){return elem.getElementsByTagName("tbody")[0]||elem;}return elem;}function disableScript(elem){elem.type=(elem.getAttribute("type")!==null)+"/"+elem.type;return elem;}function restoreScript(elem){var match=rscriptTypeMasked.exec(elem.type);if(match){elem.type=match[1];}else{elem.removeAttribute("type");}return elem;}function cloneCopyEvent(src,dest){var i,l,type,pdataOld,pdataCur,udataOld,udataCur,events;if(dest.nodeType!==1){return;}if(dataPriv.hasData(src)){pdataOld=dataPriv.access(src);pdataCur=dataPriv.set(dest,pdataOld);events=pdataOld.events;if(events){delete pdataCur.handle;pdataCur.events={};for(type in events){for(i=0,l=events[type].length;i<l;i++){jQuery.event.add(dest,type,events[type][i]);}}}}if(dataUser.hasData(src)){udataOld=dataUser.access(src);udataCur=jQuery.extend({},udataOld);dataUser.set(dest,udataCur);}}function fixInput(src,dest){var nodeName=dest.nodeName.toLowerCase();if(nodeName==="input"&&rcheckableType.test(src.type)){dest.checked=src.checked;}else if(nodeName==="input"||nodeName==="textarea"){dest.defaultValue=src.defaultValue;}}function domManip(collection,args,callback,ignored){args=concat.apply([],args);var fragment,first,scripts,hasScripts,node,doc,i=0,l=collection.length,iNoClone=l-1,value=args[0],isFunction=jQuery.isFunction(value);if(isFunction||(l>1&&typeof value==="string"&&!support.checkClone&&rchecked.test(value))){return collection.each(function(index){var self=collection.eq(index);if(isFunction){args[0]=value.call(this,index,self.html());}domManip(self,args,callback,ignored);});}if(l){fragment=buildFragment(args,collection[0].ownerDocument,false,collection,ignored);first=fragment.firstChild;if(fragment.childNodes.length===1){fragment=first;}if(first||ignored){scripts=jQuery.map(getAll(fragment,"script"),disableScript);hasScripts=scripts.length;for(;i<l;i++){node=fragment;if(i!==iNoClone){node=jQuery.clone(node,true,true);if(hasScripts){jQuery.merge(scripts,getAll(node,"script"));}}callback.call(collection[i],node,i);}if(hasScripts){doc=scripts[scripts.length-1].ownerDocument;jQuery.map(scripts,restoreScript);for(i=0;i<hasScripts;i++){node=scripts[i];if(rscriptType.test(node.type||"")&&!dataPriv.access(node,"globalEval")&&jQuery.contains(doc,node)){if(node.src){if(jQuery._evalUrl){jQuery._evalUrl(node.src);}}else{DOMEval(node.textContent.replace(rcleanScript,""),doc);}}}}}}return collection;}function remove(elem,selector,keepData){var node,nodes=selector?jQuery.filter(selector,elem):elem,i=0;for(;(node=nodes[i])!=null;i++){if(!keepData&&node.nodeType===1){jQuery.cleanData(getAll(node));}if(node.parentNode){if(keepData&&jQuery.contains(node.ownerDocument,node)){setGlobalEval(getAll(node,"script"));}node.parentNode.removeChild(node);}}return elem;}jQuery.extend({htmlPrefilter:function(html){return html.replace(rxhtmlTag,"<$1></$2>");},clone:function(elem,dataAndEvents,deepDataAndEvents){var i,l,srcElements,destElements,clone=elem.cloneNode(true),inPage=jQuery.contains(elem.ownerDocument,elem);if(!support.noCloneChecked&&(elem.nodeType===1||elem.nodeType===11)&&!jQuery.isXMLDoc(elem)){destElements=getAll(clone);srcElements=getAll(elem);for(i=0,l=srcElements.length;i<l;i++){fixInput(srcElements[i],destElements[i]);}}if(dataAndEvents){if(deepDataAndEvents){srcElements=srcElements||getAll(elem);destElements=destElements||getAll(clone);for(i=0,l=srcElements.length;i<l;i++){cloneCopyEvent(srcElements[i],destElements[i]);}}else{cloneCopyEvent(elem,clone);}}destElements=getAll(clone,"script");if(destElements.length>0){setGlobalEval(destElements,!inPage&&getAll(elem,"script"));}return clone;},cleanData:function(elems){var data,elem,type,special=jQuery.event.special,i=0;for(;(elem=elems[i])!==undefined;i++){if(acceptData(elem)){if((data=elem[dataPriv.expando])){if(data.events){for(type in data.events){if(special[type]){jQuery.event.remove(elem,type);}else{jQuery.removeEvent(elem,type,data.handle);}}}elem[dataPriv.expando]=undefined;}if(elem[dataUser.expando]){elem[dataUser.expando]=undefined;}}}}});jQuery.fn.extend({detach:function(selector){return remove(this,selector,true);},remove:function(selector){return remove(this,selector);},text:function(value){return access(this,function(value){return value===undefined?jQuery.text(this):this.empty().each(function(){if(this.nodeType===1||this.nodeType===11||this.nodeType===9){this.textContent=value;}});},null,value,arguments.length);},append:function(){return domManip(this,arguments,function(elem){if(this.nodeType===1||this.nodeType===11||this.nodeType===9){var target=manipulationTarget(this,elem);target.appendChild(elem);}});},prepend:function(){return domManip(this,arguments,function(elem){if(this.nodeType===1||this.nodeType===11||this.nodeType===9){var target=manipulationTarget(this,elem);target.insertBefore(elem,target.firstChild);}});},before:function(){return domManip(this,arguments,function(elem){if(this.parentNode){this.parentNode.insertBefore(elem,this);}});},after:function(){return domManip(this,arguments,function(elem){if(this.parentNode){this.parentNode.insertBefore(elem,this.nextSibling);}});},empty:function(){var elem,i=0;for(;(elem=this[i])!=null;i++){if(elem.nodeType===1){jQuery.cleanData(getAll(elem,false));elem.textContent="";}}return this;},clone:function(dataAndEvents,deepDataAndEvents){dataAndEvents=dataAndEvents==null?false:dataAndEvents;deepDataAndEvents=deepDataAndEvents==null?dataAndEvents:deepDataAndEvents;return this.map(function(){return jQuery.clone(this,dataAndEvents,deepDataAndEvents);});},html:function(value){return access(this,function(value){var elem=this[0]||{},i=0,l=this.length;if(value===undefined&&elem.nodeType===1){return elem.innerHTML;}if(typeof value==="string"&&!rnoInnerhtml.test(value)&&!wrapMap[(rtagName.exec(value)||["",""])[1].toLowerCase()]){value=jQuery.htmlPrefilter(value);try{for(;i<l;i++){elem=this[i]||{};if(elem.nodeType===1){jQuery.cleanData(getAll(elem,false));elem.innerHTML=value;}}elem=0;}catch(e){}}if(elem){this.empty().append(value);}},null,value,arguments.length);},replaceWith:function(){var ignored=[];return domManip(this,arguments,function(elem){var parent=this.parentNode;if(jQuery.inArray(this,ignored)<0){jQuery.cleanData(getAll(this));if(parent){parent.replaceChild(elem,this);}}},ignored);}});jQuery.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(name,original){jQuery.fn[name]=function(selector){var elems,ret=[],insert=jQuery(selector),last=insert.length-1,i=0;for(;i<=last;i++){elems=i===last?this:this.clone(true);jQuery(insert[i])[original](elems);push.apply(ret,elems.get());}return this.pushStack(ret);};});var rmargin=(/^margin/);var rnumnonpx=new RegExp("^("+pnum+")(?!px)[a-z%]+$","i");var getStyles=function(elem){var view=elem.ownerDocument.defaultView;if(!view||!view.opener){view=window;}return view.getComputedStyle(elem);};(function(){function computeStyleTests(){if(!div){return;}div.style.cssText="box-sizing:border-box;"+"position:relative;display:block;"+"margin:auto;border:1px;padding:1px;"+"top:1%;width:50%";div.innerHTML="";documentElement.appendChild(container);var divStyle=window.getComputedStyle(div);pixelPositionVal=divStyle.top!=="1%";reliableMarginLeftVal=divStyle.marginLeft==="2px";boxSizingReliableVal=divStyle.width==="4px";div.style.marginRight="50%";pixelMarginRightVal=divStyle.marginRight==="4px";documentElement.removeChild(container);div=null;}var pixelPositionVal,boxSizingReliableVal,pixelMarginRightVal,reliableMarginLeftVal,container=document.createElement("div"),div=document.createElement("div");if(!div.style){return;}div.style.backgroundClip="content-box";div.cloneNode(true).style.backgroundClip="";support.clearCloneStyle=div.style.backgroundClip==="content-box";container.style.cssText="border:0;width:8px;height:0;top:0;left:-9999px;"+"padding:0;margin-top:1px;position:absolute";container.appendChild(div);jQuery.extend(support,{pixelPosition:function(){computeStyleTests();return pixelPositionVal;},boxSizingReliable:function(){computeStyleTests();return boxSizingReliableVal;},pixelMarginRight:function(){computeStyleTests();return pixelMarginRightVal;},reliableMarginLeft:function(){computeStyleTests();return reliableMarginLeftVal;}});}());function curCSS(elem,name,computed){var width,minWidth,maxWidth,ret,style=elem.style;computed=computed||getStyles(elem);if(computed){ret=computed.getPropertyValue(name)||computed[name];if(ret===""&&!jQuery.contains(elem.ownerDocument,elem)){ret=jQuery.style(elem,name);}if(!support.pixelMarginRight()&&rnumnonpx.test(ret)&&rmargin.test(name)){width=style.width;minWidth=style.minWidth;maxWidth=style.maxWidth;style.minWidth=style.maxWidth=style.width=ret;ret=computed.width;style.width=width;style.minWidth=minWidth;style.maxWidth=maxWidth;}}return ret!==undefined?ret+"":ret;}function addGetHookIf(conditionFn,hookFn){return{get:function(){if(conditionFn()){delete this.get;return;}return(this.get=hookFn).apply(this,arguments);}};}var rdisplayswap=/^(none|table(?!-c[ea]).+)/,cssShow={position:"absolute",visibility:"hidden",display:"block"},cssNormalTransform={letterSpacing:"0",fontWeight:"400"},cssPrefixes=["Webkit","Moz","ms"],emptyStyle=document.createElement("div").style;function vendorPropName(name){if(name in emptyStyle){return name;}var capName=name[0].toUpperCase()+name.slice(1),i=cssPrefixes.length;while(i--){name=cssPrefixes[i]+capName;if(name in emptyStyle){return name;}}}function setPositiveNumber(elem,value,subtract){var matches=rcssNum.exec(value);return matches?Math.max(0,matches[2]-(subtract||0))+(matches[3]||"px"):value;}function augmentWidthOrHeight(elem,name,extra,isBorderBox,styles){var i,val=0;if(extra===(isBorderBox?"border":"content")){i=4;}else{i=name==="width"?1:0;}for(;i<4;i+=2){if(extra==="margin"){val+=jQuery.css(elem,extra+cssExpand[i],true,styles);}if(isBorderBox){if(extra==="content"){val-=jQuery.css(elem,"padding"+cssExpand[i],true,styles);}if(extra!=="margin"){val-=jQuery.css(elem,"border"+cssExpand[i]+"Width",true,styles);}}else{val+=jQuery.css(elem,"padding"+cssExpand[i],true,styles);if(extra!=="padding"){val+=jQuery.css(elem,"border"+cssExpand[i]+"Width",true,styles);}}}return val;}function getWidthOrHeight(elem,name,extra){var val,valueIsBorderBox=true,styles=getStyles(elem),isBorderBox=jQuery.css(elem,"boxSizing",false,styles)==="border-box";if(elem.getClientRects().length){val=elem.getBoundingClientRect()[name];}if(val<=0||val==null){val=curCSS(elem,name,styles);if(val<0||val==null){val=elem.style[name];}if(rnumnonpx.test(val)){return val;}valueIsBorderBox=isBorderBox&&(support.boxSizingReliable()||val===elem.style[name]);val=parseFloat(val)||0;}return(val+augmentWidthOrHeight(elem,name,extra||(isBorderBox?"border":"content"),valueIsBorderBox,styles))+"px";}jQuery.extend({cssHooks:{opacity:{get:function(elem,computed){if(computed){var ret=curCSS(elem,"opacity");return ret===""?"1":ret;}}}},cssNumber:{"animationIterationCount":true,"columnCount":true,"fillOpacity":true,"flexGrow":true,"flexShrink":true,"fontWeight":true,"lineHeight":true,"opacity":true,"order":true,"orphans":true,"widows":true,"zIndex":true,"zoom":true},cssProps:{"float":"cssFloat"},style:function(elem,name,value,extra){if(!elem||elem.nodeType===3||elem.nodeType===8||!elem.style){return;}var ret,type,hooks,origName=jQuery.camelCase(name),style=elem.style;name=jQuery.cssProps[origName]||(jQuery.cssProps[origName]=vendorPropName(origName)||origName);hooks=jQuery.cssHooks[name]||jQuery.cssHooks[origName];if(value!==undefined){type=typeof value;if(type==="string"&&(ret=rcssNum.exec(value))&&ret[1]){value=adjustCSS(elem,name,ret);type="number";}if(value==null||value!==value){return;}if(type==="number"){value+=ret&&ret[3]||(jQuery.cssNumber[origName]?"":"px");}if(!support.clearCloneStyle&&value===""&&name.indexOf("background")===0){style[name]="inherit";}if(!hooks||!("set"in hooks)||(value=hooks.set(elem,value,extra))!==undefined){style[name]=value;}}else{if(hooks&&"get"in hooks&&(ret=hooks.get(elem,false,extra))!==undefined){return ret;}return style[name];}},css:function(elem,name,extra,styles){var val,num,hooks,origName=jQuery.camelCase(name);name=jQuery.cssProps[origName]||(jQuery.cssProps[origName]=vendorPropName(origName)||origName);hooks=jQuery.cssHooks[name]||jQuery.cssHooks[origName];if(hooks&&"get"in hooks){val=hooks.get(elem,true,extra);}if(val===undefined){val=curCSS(elem,name,styles);}if(val==="normal"&&name in cssNormalTransform){val=cssNormalTransform[name];}if(extra===""||extra){num=parseFloat(val);return extra===true||isFinite(num)?num||0:val;}return val;}});jQuery.each(["height","width"],function(i,name){jQuery.cssHooks[name]={get:function(elem,computed,extra){if(computed){return rdisplayswap.test(jQuery.css(elem,"display"))&&(!elem.getClientRects().length||!elem.getBoundingClientRect().width)?swap(elem,cssShow,function(){return getWidthOrHeight(elem,name,extra);}):getWidthOrHeight(elem,name,extra);}},set:function(elem,value,extra){var matches,styles=extra&&getStyles(elem),subtract=extra&&augmentWidthOrHeight(elem,name,extra,jQuery.css(elem,"boxSizing",false,styles)==="border-box",styles);if(subtract&&(matches=rcssNum.exec(value))&&(matches[3]||"px")!=="px"){elem.style[name]=value;value=jQuery.css(elem,name);}return setPositiveNumber(elem,value,subtract);}};});jQuery.cssHooks.marginLeft=addGetHookIf(support.reliableMarginLeft,function(elem,computed){if(computed){return(parseFloat(curCSS(elem,"marginLeft"))||elem.getBoundingClientRect().left-swap(elem,{marginLeft:0},function(){return elem.getBoundingClientRect().left;}))+"px";}});jQuery.each({margin:"",padding:"",border:"Width"},function(prefix,suffix){jQuery.cssHooks[prefix+suffix]={expand:function(value){var i=0,expanded={},parts=typeof value==="string"?value.split(" "):[value];for(;i<4;i++){expanded[prefix+cssExpand[i]+suffix]=parts[i]||parts[i-2]||parts[0];}return expanded;}};if(!rmargin.test(prefix)){jQuery.cssHooks[prefix+suffix].set=setPositiveNumber;}});jQuery.fn.extend({css:function(name,value){return access(this,function(elem,name,value){var styles,len,map={},i=0;if(jQuery.isArray(name)){styles=getStyles(elem);len=name.length;for(;i<len;i++){map[name[i]]=jQuery.css(elem,name[i],false,styles);}return map;}return value!==undefined?jQuery.style(elem,name,value):jQuery.css(elem,name);},name,value,arguments.length>1);}});function Tween(elem,options,prop,end,easing){return new Tween.prototype.init(elem,options,prop,end,easing);}jQuery.Tween=Tween;Tween.prototype={constructor:Tween,init:function(elem,options,prop,end,easing,unit){this.elem=elem;this.prop=prop;this.easing=easing||jQuery.easing._default;this.options=options;this.start=this.now=this.cur();this.end=end;this.unit=unit||(jQuery.cssNumber[prop]?"":"px");},cur:function(){var hooks=Tween.propHooks[this.prop];return hooks&&hooks.get?hooks.get(this):Tween.propHooks._default.get(this);},run:function(percent){var eased,hooks=Tween.propHooks[this.prop];if(this.options.duration){this.pos=eased=jQuery.easing[this.easing](percent,this.options.duration*percent,0,1,this.options.duration);}else{this.pos=eased=percent;}this.now=(this.end-this.start)*eased+this.start;if(this.options.step){this.options.step.call(this.elem,this.now,this);}if(hooks&&hooks.set){hooks.set(this);}else{Tween.propHooks._default.set(this);}return this;}};Tween.prototype.init.prototype=Tween.prototype;Tween.propHooks={_default:{get:function(tween){var result;if(tween.elem.nodeType!==1||tween.elem[tween.prop]!=null&&tween.elem.style[tween.prop]==null){return tween.elem[tween.prop];}result=jQuery.css(tween.elem,tween.prop,"");return!result||result==="auto"?0:result;},set:function(tween){if(jQuery.fx.step[tween.prop]){jQuery.fx.step[tween.prop](tween);}else if(tween.elem.nodeType===1&&(tween.elem.style[jQuery.cssProps[tween.prop]]!=null||jQuery.cssHooks[tween.prop])){jQuery.style(tween.elem,tween.prop,tween.now+tween.unit);}else{tween.elem[tween.prop]=tween.now;}}}};Tween.propHooks.scrollTop=Tween.propHooks.scrollLeft={set:function(tween){if(tween.elem.nodeType&&tween.elem.parentNode){tween.elem[tween.prop]=tween.now;}}};jQuery.easing={linear:function(p){return p;},swing:function(p){return 0.5-Math.cos(p*Math.PI)/2;},_default:"swing"};jQuery.fx=Tween.prototype.init;jQuery.fx.step={};var fxNow,timerId,rfxtypes=/^(?:toggle|show|hide)$/,rrun=/queueHooks$/;function raf(){if(timerId){window.requestAnimationFrame(raf);jQuery.fx.tick();}}function createFxNow(){window.setTimeout(function(){fxNow=undefined;});return(fxNow=jQuery.now());}function genFx(type,includeWidth){var which,i=0,attrs={height:type};includeWidth=includeWidth?1:0;for(;i<4;i+=2-includeWidth){which=cssExpand[i];attrs["margin"+which]=attrs["padding"+which]=type;}if(includeWidth){attrs.opacity=attrs.width=type;}return attrs;}function createTween(value,prop,animation){var tween,collection=(Animation.tweeners[prop]||[]).concat(Animation.tweeners["*"]),index=0,length=collection.length;for(;index<length;index++){if((tween=collection[index].call(animation,prop,value))){return tween;}}}function defaultPrefilter(elem,props,opts){var prop,value,toggle,hooks,oldfire,propTween,restoreDisplay,display,isBox="width"in props||"height"in props,anim=this,orig={},style=elem.style,hidden=elem.nodeType&&isHiddenWithinTree(elem),dataShow=dataPriv.get(elem,"fxshow");if(!opts.queue){hooks=jQuery._queueHooks(elem,"fx");if(hooks.unqueued==null){hooks.unqueued=0;oldfire=hooks.empty.fire;hooks.empty.fire=function(){if(!hooks.unqueued){oldfire();}};}hooks.unqueued++;anim.always(function(){anim.always(function(){hooks.unqueued--;if(!jQuery.queue(elem,"fx").length){hooks.empty.fire();}});});}for(prop in props){value=props[prop];if(rfxtypes.test(value)){delete props[prop];toggle=toggle||value==="toggle";if(value===(hidden?"hide":"show")){if(value==="show"&&dataShow&&dataShow[prop]!==undefined){hidden=true;}else{continue;}}orig[prop]=dataShow&&dataShow[prop]||jQuery.style(elem,prop);}}propTween=!jQuery.isEmptyObject(props);if(!propTween&&jQuery.isEmptyObject(orig)){return;}if(isBox&&elem.nodeType===1){opts.overflow=[style.overflow,style.overflowX,style.overflowY];restoreDisplay=dataShow&&dataShow.display;if(restoreDisplay==null){restoreDisplay=dataPriv.get(elem,"display");}display=jQuery.css(elem,"display");if(display==="none"){if(restoreDisplay){display=restoreDisplay;}else{showHide([elem],true);restoreDisplay=elem.style.display||restoreDisplay;display=jQuery.css(elem,"display");showHide([elem]);}}if(display==="inline"||display==="inline-block"&&restoreDisplay!=null){if(jQuery.css(elem,"float")==="none"){if(!propTween){anim.done(function(){style.display=restoreDisplay;});if(restoreDisplay==null){display=style.display;restoreDisplay=display==="none"?"":display;}}style.display="inline-block";}}}if(opts.overflow){style.overflow="hidden";anim.always(function(){style.overflow=opts.overflow[0];style.overflowX=opts.overflow[1];style.overflowY=opts.overflow[2];});}propTween=false;for(prop in orig){if(!propTween){if(dataShow){if("hidden"in dataShow){hidden=dataShow.hidden;}}else{dataShow=dataPriv.access(elem,"fxshow",{display:restoreDisplay});}if(toggle){dataShow.hidden=!hidden;}if(hidden){showHide([elem],true);}anim.done(function(){if(!hidden){showHide([elem]);}dataPriv.remove(elem,"fxshow");for(prop in orig){jQuery.style(elem,prop,orig[prop]);}});}propTween=createTween(hidden?dataShow[prop]:0,prop,anim);if(!(prop in dataShow)){dataShow[prop]=propTween.start;if(hidden){propTween.end=propTween.start;propTween.start=0;}}}}function propFilter(props,specialEasing){var index,name,easing,value,hooks;for(index in props){name=jQuery.camelCase(index);easing=specialEasing[name];value=props[index];if(jQuery.isArray(value)){easing=value[1];value=props[index]=value[0];}if(index!==name){props[name]=value;delete props[index];}hooks=jQuery.cssHooks[name];if(hooks&&"expand"in hooks){value=hooks.expand(value);delete props[name];for(index in value){if(!(index in props)){props[index]=value[index];specialEasing[index]=easing;}}}else{specialEasing[name]=easing;}}}function Animation(elem,properties,options){var result,stopped,index=0,length=Animation.prefilters.length,deferred=jQuery.Deferred().always(function(){delete tick.elem;}),tick=function(){if(stopped){return false;}var currentTime=fxNow||createFxNow(),remaining=Math.max(0,animation.startTime+animation.duration-currentTime),temp=remaining/animation.duration||0,percent=1-temp,index=0,length=animation.tweens.length;for(;index<length;index++){animation.tweens[index].run(percent);}deferred.notifyWith(elem,[animation,percent,remaining]);if(percent<1&&length){return remaining;}else{deferred.resolveWith(elem,[animation]);return false;}},animation=deferred.promise({elem:elem,props:jQuery.extend({},properties),opts:jQuery.extend(true,{specialEasing:{},easing:jQuery.easing._default},options),originalProperties:properties,originalOptions:options,startTime:fxNow||createFxNow(),duration:options.duration,tweens:[],createTween:function(prop,end){var tween=jQuery.Tween(elem,animation.opts,prop,end,animation.opts.specialEasing[prop]||animation.opts.easing);animation.tweens.push(tween);return tween;},stop:function(gotoEnd){var index=0,length=gotoEnd?animation.tweens.length:0;if(stopped){return this;}stopped=true;for(;index<length;index++){animation.tweens[index].run(1);}if(gotoEnd){deferred.notifyWith(elem,[animation,1,0]);deferred.resolveWith(elem,[animation,gotoEnd]);}else{deferred.rejectWith(elem,[animation,gotoEnd]);}return this;}}),props=animation.props;propFilter(props,animation.opts.specialEasing);for(;index<length;index++){result=Animation.prefilters[index].call(animation,elem,props,animation.opts);if(result){if(jQuery.isFunction(result.stop)){jQuery._queueHooks(animation.elem,animation.opts.queue).stop=jQuery.proxy(result.stop,result);}return result;}}jQuery.map(props,createTween,animation);if(jQuery.isFunction(animation.opts.start)){animation.opts.start.call(elem,animation);}jQuery.fx.timer(jQuery.extend(tick,{elem:elem,anim:animation,queue:animation.opts.queue}));return animation.progress(animation.opts.progress).done(animation.opts.done,animation.opts.complete).fail(animation.opts.fail).always(animation.opts.always);}jQuery.Animation=jQuery.extend(Animation,{tweeners:{"*":[function(prop,value){var tween=this.createTween(prop,value);adjustCSS(tween.elem,prop,rcssNum.exec(value),tween);return tween;}]},tweener:function(props,callback){if(jQuery.isFunction(props)){callback=props;props=["*"];}else{props=props.match(rnothtmlwhite);}var prop,index=0,length=props.length;for(;index<length;index++){prop=props[index];Animation.tweeners[prop]=Animation.tweeners[prop]||[];Animation.tweeners[prop].unshift(callback);}},prefilters:[defaultPrefilter],prefilter:function(callback,prepend){if(prepend){Animation.prefilters.unshift(callback);}else{Animation.prefilters.push(callback);}}});jQuery.speed=function(speed,easing,fn){var opt=speed&&typeof speed==="object"?jQuery.extend({},speed):{complete:fn||!fn&&easing||jQuery.isFunction(speed)&&speed,duration:speed,easing:fn&&easing||easing&&!jQuery.isFunction(easing)&&easing};if(jQuery.fx.off||document.hidden){opt.duration=0;}else{if(typeof opt.duration!=="number"){if(opt.duration in jQuery.fx.speeds){opt.duration=jQuery.fx.speeds[opt.duration];}else{opt.duration=jQuery.fx.speeds._default;}}}if(opt.queue==null||opt.queue===true){opt.queue="fx";}opt.old=opt.complete;opt.complete=function(){if(jQuery.isFunction(opt.old)){opt.old.call(this);}if(opt.queue){jQuery.dequeue(this,opt.queue);}};return opt;};jQuery.fn.extend({fadeTo:function(speed,to,easing,callback){return this.filter(isHiddenWithinTree).css("opacity",0).show().end().animate({opacity:to},speed,easing,callback);},animate:function(prop,speed,easing,callback){var empty=jQuery.isEmptyObject(prop),optall=jQuery.speed(speed,easing,callback),doAnimation=function(){var anim=Animation(this,jQuery.extend({},prop),optall);if(empty||dataPriv.get(this,"finish")){anim.stop(true);}};doAnimation.finish=doAnimation;return empty||optall.queue===false?this.each(doAnimation):this.queue(optall.queue,doAnimation);},stop:function(type,clearQueue,gotoEnd){var stopQueue=function(hooks){var stop=hooks.stop;delete hooks.stop;stop(gotoEnd);};if(typeof type!=="string"){gotoEnd=clearQueue;clearQueue=type;type=undefined;}if(clearQueue&&type!==false){this.queue(type||"fx",[]);}return this.each(function(){var dequeue=true,index=type!=null&&type+"queueHooks",timers=jQuery.timers,data=dataPriv.get(this);if(index){if(data[index]&&data[index].stop){stopQueue(data[index]);}}else{for(index in data){if(data[index]&&data[index].stop&&rrun.test(index)){stopQueue(data[index]);}}}for(index=timers.length;index--;){if(timers[index].elem===this&&(type==null||timers[index].queue===type)){timers[index].anim.stop(gotoEnd);dequeue=false;timers.splice(index,1);}}if(dequeue||!gotoEnd){jQuery.dequeue(this,type);}});},finish:function(type){if(type!==false){type=type||"fx";}return this.each(function(){var index,data=dataPriv.get(this),queue=data[type+"queue"],hooks=data[type+"queueHooks"],timers=jQuery.timers,length=queue?queue.length:0;data.finish=true;jQuery.queue(this,type,[]);if(hooks&&hooks.stop){hooks.stop.call(this,true);}for(index=timers.length;index--;){if(timers[index].elem===this&&timers[index].queue===type){timers[index].anim.stop(true);timers.splice(index,1);}}for(index=0;index<length;index++){if(queue[index]&&queue[index].finish){queue[index].finish.call(this);}}delete data.finish;});}});jQuery.each(["toggle","show","hide"],function(i,name){var cssFn=jQuery.fn[name];jQuery.fn[name]=function(speed,easing,callback){return speed==null||typeof speed==="boolean"?cssFn.apply(this,arguments):this.animate(genFx(name,true),speed,easing,callback);};});jQuery.each({slideDown:genFx("show"),slideUp:genFx("hide"),slideToggle:genFx("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(name,props){jQuery.fn[name]=function(speed,easing,callback){return this.animate(props,speed,easing,callback);};});jQuery.timers=[];jQuery.fx.tick=function(){var timer,i=0,timers=jQuery.timers;fxNow=jQuery.now();for(;i<timers.length;i++){timer=timers[i];if(!timer()&&timers[i]===timer){timers.splice(i--,1);}}if(!timers.length){jQuery.fx.stop();}fxNow=undefined;};jQuery.fx.timer=function(timer){jQuery.timers.push(timer);if(timer()){jQuery.fx.start();}else{jQuery.timers.pop();}};jQuery.fx.interval=13;jQuery.fx.start=function(){if(!timerId){timerId=window.requestAnimationFrame?window.requestAnimationFrame(raf):window.setInterval(jQuery.fx.tick,jQuery.fx.interval);}};jQuery.fx.stop=function(){if(window.cancelAnimationFrame){window.cancelAnimationFrame(timerId);}else{window.clearInterval(timerId);}timerId=null;};jQuery.fx.speeds={slow:600,fast:200,_default:400};jQuery.fn.delay=function(time,type){time=jQuery.fx?jQuery.fx.speeds[time]||time:time;type=type||"fx";return this.queue(type,function(next,hooks){var timeout=window.setTimeout(next,time);hooks.stop=function(){window.clearTimeout(timeout);};});};(function(){var input=document.createElement("input"),select=document.createElement("select"),opt=select.appendChild(document.createElement("option"));input.type="checkbox";support.checkOn=input.value!=="";support.optSelected=opt.selected;input=document.createElement("input");input.value="t";input.type="radio";support.radioValue=input.value==="t";}());var boolHook,attrHandle=jQuery.expr.attrHandle;jQuery.fn.extend({attr:function(name,value){return access(this,jQuery.attr,name,value,arguments.length>1);},removeAttr:function(name){return this.each(function(){jQuery.removeAttr(this,name);});}});jQuery.extend({attr:function(elem,name,value){var ret,hooks,nType=elem.nodeType;if(nType===3||nType===8||nType===2){return;}if(typeof elem.getAttribute==="undefined"){return jQuery.prop(elem,name,value);}if(nType!==1||!jQuery.isXMLDoc(elem)){hooks=jQuery.attrHooks[name.toLowerCase()]||(jQuery.expr.match.bool.test(name)?boolHook:undefined);}if(value!==undefined){if(value===null){jQuery.removeAttr(elem,name);return;}if(hooks&&"set"in hooks&&(ret=hooks.set(elem,value,name))!==undefined){return ret;}elem.setAttribute(name,value+"");return value;}if(hooks&&"get"in hooks&&(ret=hooks.get(elem,name))!==null){return ret;}ret=jQuery.find.attr(elem,name);return ret==null?undefined:ret;},attrHooks:{type:{set:function(elem,value){if(!support.radioValue&&value==="radio"&&jQuery.nodeName(elem,"input")){var val=elem.value;elem.setAttribute("type",value);if(val){elem.value=val;}return value;}}}},removeAttr:function(elem,value){var name,i=0,attrNames=value&&value.match(rnothtmlwhite);if(attrNames&&elem.nodeType===1){while((name=attrNames[i++])){elem.removeAttribute(name);}}}});boolHook={set:function(elem,value,name){if(value===false){jQuery.removeAttr(elem,name);}else{elem.setAttribute(name,name);}return name;}};jQuery.each(jQuery.expr.match.bool.source.match(/\w+/g),function(i,name){var getter=attrHandle[name]||jQuery.find.attr;attrHandle[name]=function(elem,name,isXML){var ret,handle,lowercaseName=name.toLowerCase();if(!isXML){handle=attrHandle[lowercaseName];attrHandle[lowercaseName]=ret;ret=getter(elem,name,isXML)!=null?lowercaseName:null;attrHandle[lowercaseName]=handle;}return ret;};});var rfocusable=/^(?:input|select|textarea|button)$/i,rclickable=/^(?:a|area)$/i;jQuery.fn.extend({prop:function(name,value){return access(this,jQuery.prop,name,value,arguments.length>1);},removeProp:function(name){return this.each(function(){delete this[jQuery.propFix[name]||name];});}});jQuery.extend({prop:function(elem,name,value){var ret,hooks,nType=elem.nodeType;if(nType===3||nType===8||nType===2){return;}if(nType!==1||!jQuery.isXMLDoc(elem)){name=jQuery.propFix[name]||name;hooks=jQuery.propHooks[name];}if(value!==undefined){if(hooks&&"set"in hooks&&(ret=hooks.set(elem,value,name))!==undefined){return ret;}return(elem[name]=value);}if(hooks&&"get"in hooks&&(ret=hooks.get(elem,name))!==null){return ret;}return elem[name];},propHooks:{tabIndex:{get:function(elem){var tabindex=jQuery.find.attr(elem,"tabindex");if(tabindex){return parseInt(tabindex,10);}if(rfocusable.test(elem.nodeName)||rclickable.test(elem.nodeName)&&elem.href){return 0;}return-1;}}},propFix:{"for":"htmlFor","class":"className"}});if(!support.optSelected){jQuery.propHooks.selected={get:function(elem){var parent=elem.parentNode;if(parent&&parent.parentNode){parent.parentNode.selectedIndex;}return null;},set:function(elem){var parent=elem.parentNode;if(parent){parent.selectedIndex;if(parent.parentNode){parent.parentNode.selectedIndex;}}}};}jQuery.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){jQuery.propFix[this.toLowerCase()]=this;});function stripAndCollapse(value){var tokens=value.match(rnothtmlwhite)||[];return tokens.join(" ");}function getClass(elem){return elem.getAttribute&&elem.getAttribute("class")||"";}jQuery.fn.extend({addClass:function(value){var classes,elem,cur,curValue,clazz,j,finalValue,i=0;if(jQuery.isFunction(value)){return this.each(function(j){jQuery(this).addClass(value.call(this,j,getClass(this)));});}if(typeof value==="string"&&value){classes=value.match(rnothtmlwhite)||[];while((elem=this[i++])){curValue=getClass(elem);cur=elem.nodeType===1&&(" "+stripAndCollapse(curValue)+" ");if(cur){j=0;while((clazz=classes[j++])){if(cur.indexOf(" "+clazz+" ")<0){cur+=clazz+" ";}}finalValue=stripAndCollapse(cur);if(curValue!==finalValue){elem.setAttribute("class",finalValue);}}}}return this;},removeClass:function(value){var classes,elem,cur,curValue,clazz,j,finalValue,i=0;if(jQuery.isFunction(value)){return this.each(function(j){jQuery(this).removeClass(value.call(this,j,getClass(this)));});}if(!arguments.length){return this.attr("class","");}if(typeof value==="string"&&value){classes=value.match(rnothtmlwhite)||[];while((elem=this[i++])){curValue=getClass(elem);cur=elem.nodeType===1&&(" "+stripAndCollapse(curValue)+" ");if(cur){j=0;while((clazz=classes[j++])){while(cur.indexOf(" "+clazz+" ")>-1){cur=cur.replace(" "+clazz+" "," ");}}finalValue=stripAndCollapse(cur);if(curValue!==finalValue){elem.setAttribute("class",finalValue);}}}}return this;},toggleClass:function(value,stateVal){var type=typeof value;if(typeof stateVal==="boolean"&&type==="string"){return stateVal?this.addClass(value):this.removeClass(value);}if(jQuery.isFunction(value)){return this.each(function(i){jQuery(this).toggleClass(value.call(this,i,getClass(this),stateVal),stateVal);});}return this.each(function(){var className,i,self,classNames;if(type==="string"){i=0;self=jQuery(this);classNames=value.match(rnothtmlwhite)||[];while((className=classNames[i++])){if(self.hasClass(className)){self.removeClass(className);}else{self.addClass(className);}}}else if(value===undefined||type==="boolean"){className=getClass(this);if(className){dataPriv.set(this,"__className__",className);}if(this.setAttribute){this.setAttribute("class",className||value===false?"":dataPriv.get(this,"__className__")||"");}}});},hasClass:function(selector){var className,elem,i=0;className=" "+selector+" ";while((elem=this[i++])){if(elem.nodeType===1&&(" "+stripAndCollapse(getClass(elem))+" ").indexOf(className)>-1){return true;}}return false;}});var rreturn=/\r/g;jQuery.fn.extend({val:function(value){var hooks,ret,isFunction,elem=this[0];if(!arguments.length){if(elem){hooks=jQuery.valHooks[elem.type]||jQuery.valHooks[elem.nodeName.toLowerCase()];if(hooks&&"get"in hooks&&(ret=hooks.get(elem,"value"))!==undefined){return ret;}ret=elem.value;if(typeof ret==="string"){return ret.replace(rreturn,"");}return ret==null?"":ret;}return;}isFunction=jQuery.isFunction(value);return this.each(function(i){var val;if(this.nodeType!==1){return;}if(isFunction){val=value.call(this,i,jQuery(this).val());}else{val=value;}if(val==null){val="";}else if(typeof val==="number"){val+="";}else if(jQuery.isArray(val)){val=jQuery.map(val,function(value){return value==null?"":value+"";});}hooks=jQuery.valHooks[this.type]||jQuery.valHooks[this.nodeName.toLowerCase()];if(!hooks||!("set"in hooks)||hooks.set(this,val,"value")===undefined){this.value=val;}});}});jQuery.extend({valHooks:{option:{get:function(elem){var val=jQuery.find.attr(elem,"value");return val!=null?val:stripAndCollapse(jQuery.text(elem));}},select:{get:function(elem){var value,option,i,options=elem.options,index=elem.selectedIndex,one=elem.type==="select-one",values=one?null:[],max=one?index+1:options.length;if(index<0){i=max;}else{i=one?index:0;}for(;i<max;i++){option=options[i];if((option.selected||i===index)&&!option.disabled&&(!option.parentNode.disabled||!jQuery.nodeName(option.parentNode,"optgroup"))){value=jQuery(option).val();if(one){return value;}values.push(value);}}return values;},set:function(elem,value){var optionSet,option,options=elem.options,values=jQuery.makeArray(value),i=options.length;while(i--){option=options[i];if(option.selected=jQuery.inArray(jQuery.valHooks.option.get(option),values)>-1){optionSet=true;}}if(!optionSet){elem.selectedIndex=-1;}return values;}}}});jQuery.each(["radio","checkbox"],function(){jQuery.valHooks[this]={set:function(elem,value){if(jQuery.isArray(value)){return(elem.checked=jQuery.inArray(jQuery(elem).val(),value)>-1);}}};if(!support.checkOn){jQuery.valHooks[this].get=function(elem){return elem.getAttribute("value")===null?"on":elem.value;};}});var rfocusMorph=/^(?:focusinfocus|focusoutblur)$/;jQuery.extend(jQuery.event,{trigger:function(event,data,elem,onlyHandlers){var i,cur,tmp,bubbleType,ontype,handle,special,eventPath=[elem||document],type=hasOwn.call(event,"type")?event.type:event,namespaces=hasOwn.call(event,"namespace")?event.namespace.split("."):[];cur=tmp=elem=elem||document;if(elem.nodeType===3||elem.nodeType===8){return;}if(rfocusMorph.test(type+jQuery.event.triggered)){return;}if(type.indexOf(".")>-1){namespaces=type.split(".");type=namespaces.shift();namespaces.sort();}ontype=type.indexOf(":")<0&&"on"+type;event=event[jQuery.expando]?event:new jQuery.Event(type,typeof event==="object"&&event);event.isTrigger=onlyHandlers?2:3;event.namespace=namespaces.join(".");event.rnamespace=event.namespace?new RegExp("(^|\\.)"+namespaces.join("\\.(?:.*\\.|)")+"(\\.|$)"):null;event.result=undefined;if(!event.target){event.target=elem;}data=data==null?[event]:jQuery.makeArray(data,[event]);special=jQuery.event.special[type]||{};if(!onlyHandlers&&special.trigger&&special.trigger.apply(elem,data)===false){return;}if(!onlyHandlers&&!special.noBubble&&!jQuery.isWindow(elem)){bubbleType=special.delegateType||type;if(!rfocusMorph.test(bubbleType+type)){cur=cur.parentNode;}for(;cur;cur=cur.parentNode){eventPath.push(cur);tmp=cur;}if(tmp===(elem.ownerDocument||document)){eventPath.push(tmp.defaultView||tmp.parentWindow||window);}}i=0;while((cur=eventPath[i++])&&!event.isPropagationStopped()){event.type=i>1?bubbleType:special.bindType||type;handle=(dataPriv.get(cur,"events")||{})[event.type]&&dataPriv.get(cur,"handle");if(handle){handle.apply(cur,data);}handle=ontype&&cur[ontype];if(handle&&handle.apply&&acceptData(cur)){event.result=handle.apply(cur,data);if(event.result===false){event.preventDefault();}}}event.type=type;if(!onlyHandlers&&!event.isDefaultPrevented()){if((!special._default||special._default.apply(eventPath.pop(),data)===false)&&acceptData(elem)){if(ontype&&jQuery.isFunction(elem[type])&&!jQuery.isWindow(elem)){tmp=elem[ontype];if(tmp){elem[ontype]=null;}jQuery.event.triggered=type;elem[type]();jQuery.event.triggered=undefined;if(tmp){elem[ontype]=tmp;}}}}return event.result;},simulate:function(type,elem,event){var e=jQuery.extend(new jQuery.Event(),event,{type:type,isSimulated:true});jQuery.event.trigger(e,null,elem);}});jQuery.fn.extend({trigger:function(type,data){return this.each(function(){jQuery.event.trigger(type,data,this);});},triggerHandler:function(type,data){var elem=this[0];if(elem){return jQuery.event.trigger(type,data,elem,true);}}});jQuery.each(("blur focus focusin focusout resize scroll click dblclick "+"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave "+"change select submit keydown keypress keyup contextmenu").split(" "),function(i,name){jQuery.fn[name]=function(data,fn){return arguments.length>0?this.on(name,null,data,fn):this.trigger(name);};});jQuery.fn.extend({hover:function(fnOver,fnOut){return this.mouseenter(fnOver).mouseleave(fnOut||fnOver);}});support.focusin="onfocusin"in window;if(!support.focusin){jQuery.each({focus:"focusin",blur:"focusout"},function(orig,fix){var handler=function(event){jQuery.event.simulate(fix,event.target,jQuery.event.fix(event));};jQuery.event.special[fix]={setup:function(){var doc=this.ownerDocument||this,attaches=dataPriv.access(doc,fix);if(!attaches){doc.addEventListener(orig,handler,true);}dataPriv.access(doc,fix,(attaches||0)+1);},teardown:function(){var doc=this.ownerDocument||this,attaches=dataPriv.access(doc,fix)-1;if(!attaches){doc.removeEventListener(orig,handler,true);dataPriv.remove(doc,fix);}else{dataPriv.access(doc,fix,attaches);}}};});}var location=window.location;var nonce=jQuery.now();var rquery=(/\?/);jQuery.parseXML=function(data){var xml;if(!data||typeof data!=="string"){return null;}try{xml=(new window.DOMParser()).parseFromString(data,"text/xml");}catch(e){xml=undefined;}if(!xml||xml.getElementsByTagName("parsererror").length){jQuery.error("Invalid XML: "+data);}return xml;};var rbracket=/\[\]$/,rCRLF=/\r?\n/g,rsubmitterTypes=/^(?:submit|button|image|reset|file)$/i,rsubmittable=/^(?:input|select|textarea|keygen)/i;function buildParams(prefix,obj,traditional,add){var name;if(jQuery.isArray(obj)){jQuery.each(obj,function(i,v){if(traditional||rbracket.test(prefix)){add(prefix,v);}else{buildParams(prefix+"["+(typeof v==="object"&&v!=null?i:"")+"]",v,traditional,add);}});}else if(!traditional&&jQuery.type(obj)==="object"){for(name in obj){buildParams(prefix+"["+name+"]",obj[name],traditional,add);}}else{add(prefix,obj);}}jQuery.param=function(a,traditional){var prefix,s=[],add=function(key,valueOrFunction){var value=jQuery.isFunction(valueOrFunction)?valueOrFunction():valueOrFunction;s[s.length]=encodeURIComponent(key)+"="+encodeURIComponent(value==null?"":value);};if(jQuery.isArray(a)||(a.jquery&&!jQuery.isPlainObject(a))){jQuery.each(a,function(){add(this.name,this.value);});}else{for(prefix in a){buildParams(prefix,a[prefix],traditional,add);}}return s.join("&");};jQuery.fn.extend({serialize:function(){return jQuery.param(this.serializeArray());},serializeArray:function(){return this.map(function(){var elements=jQuery.prop(this,"elements");return elements?jQuery.makeArray(elements):this;}).filter(function(){var type=this.type;return this.name&&!jQuery(this).is(":disabled")&&rsubmittable.test(this.nodeName)&&!rsubmitterTypes.test(type)&&(this.checked||!rcheckableType.test(type));}).map(function(i,elem){var val=jQuery(this).val();if(val==null){return null;}if(jQuery.isArray(val)){return jQuery.map(val,function(val){return{name:elem.name,value:val.replace(rCRLF,"\r\n")};});}return{name:elem.name,value:val.replace(rCRLF,"\r\n")};}).get();}});var r20=/%20/g,rhash=/#.*$/,rantiCache=/([?&])_=[^&]*/,rheaders=/^(.*?):[ \t]*([^\r\n]*)$/mg,rlocalProtocol=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,rnoContent=/^(?:GET|HEAD)$/,rprotocol=/^\/\//,prefilters={},transports={},allTypes="*/".concat("*"),originAnchor=document.createElement("a");originAnchor.href=location.href;function addToPrefiltersOrTransports(structure){return function(dataTypeExpression,func){if(typeof dataTypeExpression!=="string"){func=dataTypeExpression;dataTypeExpression="*";}var dataType,i=0,dataTypes=dataTypeExpression.toLowerCase().match(rnothtmlwhite)||[];if(jQuery.isFunction(func)){while((dataType=dataTypes[i++])){if(dataType[0]==="+"){dataType=dataType.slice(1)||"*";(structure[dataType]=structure[dataType]||[]).unshift(func);}else{(structure[dataType]=structure[dataType]||[]).push(func);}}}};}function inspectPrefiltersOrTransports(structure,options,originalOptions,jqXHR){var inspected={},seekingTransport=(structure===transports);function inspect(dataType){var selected;inspected[dataType]=true;jQuery.each(structure[dataType]||[],function(_,prefilterOrFactory){var dataTypeOrTransport=prefilterOrFactory(options,originalOptions,jqXHR);if(typeof dataTypeOrTransport==="string"&&!seekingTransport&&!inspected[dataTypeOrTransport]){options.dataTypes.unshift(dataTypeOrTransport);inspect(dataTypeOrTransport);return false;}else if(seekingTransport){return!(selected=dataTypeOrTransport);}});return selected;}return inspect(options.dataTypes[0])||!inspected["*"]&&inspect("*");}function ajaxExtend(target,src){var key,deep,flatOptions=jQuery.ajaxSettings.flatOptions||{};for(key in src){if(src[key]!==undefined){(flatOptions[key]?target:(deep||(deep={})))[key]=src[key];}}if(deep){jQuery.extend(true,target,deep);}return target;}function ajaxHandleResponses(s,jqXHR,responses){var ct,type,finalDataType,firstDataType,contents=s.contents,dataTypes=s.dataTypes;while(dataTypes[0]==="*"){dataTypes.shift();if(ct===undefined){ct=s.mimeType||jqXHR.getResponseHeader("Content-Type");}}if(ct){for(type in contents){if(contents[type]&&contents[type].test(ct)){dataTypes.unshift(type);break;}}}if(dataTypes[0]in responses){finalDataType=dataTypes[0];}else{for(type in responses){if(!dataTypes[0]||s.converters[type+" "+dataTypes[0]]){finalDataType=type;break;}if(!firstDataType){firstDataType=type;}}finalDataType=finalDataType||firstDataType;}if(finalDataType){if(finalDataType!==dataTypes[0]){dataTypes.unshift(finalDataType);}return responses[finalDataType];}}function ajaxConvert(s,response,jqXHR,isSuccess){var conv2,current,conv,tmp,prev,converters={},dataTypes=s.dataTypes.slice();if(dataTypes[1]){for(conv in s.converters){converters[conv.toLowerCase()]=s.converters[conv];}}current=dataTypes.shift();while(current){if(s.responseFields[current]){jqXHR[s.responseFields[current]]=response;}if(!prev&&isSuccess&&s.dataFilter){response=s.dataFilter(response,s.dataType);}prev=current;current=dataTypes.shift();if(current){if(current==="*"){current=prev;}else if(prev!=="*"&&prev!==current){conv=converters[prev+" "+current]||converters["* "+current];if(!conv){for(conv2 in converters){tmp=conv2.split(" ");if(tmp[1]===current){conv=converters[prev+" "+tmp[0]]||converters["* "+tmp[0]];if(conv){if(conv===true){conv=converters[conv2];}else if(converters[conv2]!==true){current=tmp[0];dataTypes.unshift(tmp[1]);}break;}}}}if(conv!==true){if(conv&&s.throws){response=conv(response);}else{try{response=conv(response);}catch(e){return{state:"parsererror",error:conv?e:"No conversion from "+prev+" to "+current};}}}}}}return{state:"success",data:response};}jQuery.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:location.href,type:"GET",isLocal:rlocalProtocol.test(location.protocol),global:true,processData:true,async:true,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":allTypes,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":true,"text json":JSON.parse,"text xml":jQuery.parseXML},flatOptions:{url:true,context:true}},ajaxSetup:function(target,settings){return settings?ajaxExtend(ajaxExtend(target,jQuery.ajaxSettings),settings):ajaxExtend(jQuery.ajaxSettings,target);},ajaxPrefilter:addToPrefiltersOrTransports(prefilters),ajaxTransport:addToPrefiltersOrTransports(transports),ajax:function(url,options){if(typeof url==="object"){options=url;url=undefined;}options=options||{};var transport,cacheURL,responseHeadersString,responseHeaders,timeoutTimer,urlAnchor,completed,fireGlobals,i,uncached,s=jQuery.ajaxSetup({},options),callbackContext=s.context||s,globalEventContext=s.context&&(callbackContext.nodeType||callbackContext.jquery)?jQuery(callbackContext):jQuery.event,deferred=jQuery.Deferred(),completeDeferred=jQuery.Callbacks("once memory"),statusCode=s.statusCode||{},requestHeaders={},requestHeadersNames={},strAbort="canceled",jqXHR={readyState:0,getResponseHeader:function(key){var match;if(completed){if(!responseHeaders){responseHeaders={};while((match=rheaders.exec(responseHeadersString))){responseHeaders[match[1].toLowerCase()]=match[2];}}match=responseHeaders[key.toLowerCase()];}return match==null?null:match;},getAllResponseHeaders:function(){return completed?responseHeadersString:null;},setRequestHeader:function(name,value){if(completed==null){name=requestHeadersNames[name.toLowerCase()]=requestHeadersNames[name.toLowerCase()]||name;requestHeaders[name]=value;}return this;},overrideMimeType:function(type){if(completed==null){s.mimeType=type;}return this;},statusCode:function(map){var code;if(map){if(completed){jqXHR.always(map[jqXHR.status]);}else{for(code in map){statusCode[code]=[statusCode[code],map[code]];}}}return this;},abort:function(statusText){var finalText=statusText||strAbort;if(transport){transport.abort(finalText);}done(0,finalText);return this;}};deferred.promise(jqXHR);s.url=((url||s.url||location.href)+"").replace(rprotocol,location.protocol+"//");s.type=options.method||options.type||s.method||s.type;s.dataTypes=(s.dataType||"*").toLowerCase().match(rnothtmlwhite)||[""];if(s.crossDomain==null){urlAnchor=document.createElement("a");try{urlAnchor.href=s.url;urlAnchor.href=urlAnchor.href;s.crossDomain=originAnchor.protocol+"//"+originAnchor.host!==urlAnchor.protocol+"//"+urlAnchor.host;}catch(e){s.crossDomain=true;}}if(s.data&&s.processData&&typeof s.data!=="string"){s.data=jQuery.param(s.data,s.traditional);}inspectPrefiltersOrTransports(prefilters,s,options,jqXHR);if(completed){return jqXHR;}fireGlobals=jQuery.event&&s.global;if(fireGlobals&&jQuery.active++===0){jQuery.event.trigger("ajaxStart");}s.type=s.type.toUpperCase();s.hasContent=!rnoContent.test(s.type);cacheURL=s.url.replace(rhash,"");if(!s.hasContent){uncached=s.url.slice(cacheURL.length);if(s.data){cacheURL+=(rquery.test(cacheURL)?"&":"?")+s.data;delete s.data;}if(s.cache===false){cacheURL=cacheURL.replace(rantiCache,"$1");uncached=(rquery.test(cacheURL)?"&":"?")+"_="+(nonce++)+uncached;}s.url=cacheURL+uncached;}else if(s.data&&s.processData&&(s.contentType||"").indexOf("application/x-www-form-urlencoded")===0){s.data=s.data.replace(r20,"+");}if(s.ifModified){if(jQuery.lastModified[cacheURL]){jqXHR.setRequestHeader("If-Modified-Since",jQuery.lastModified[cacheURL]);}if(jQuery.etag[cacheURL]){jqXHR.setRequestHeader("If-None-Match",jQuery.etag[cacheURL]);}}if(s.data&&s.hasContent&&s.contentType!==false||options.contentType){jqXHR.setRequestHeader("Content-Type",s.contentType);}jqXHR.setRequestHeader("Accept",s.dataTypes[0]&&s.accepts[s.dataTypes[0]]?s.accepts[s.dataTypes[0]]+(s.dataTypes[0]!=="*"?", "+allTypes+"; q=0.01":""):s.accepts["*"]);for(i in s.headers){jqXHR.setRequestHeader(i,s.headers[i]);}if(s.beforeSend&&(s.beforeSend.call(callbackContext,jqXHR,s)===false||completed)){return jqXHR.abort();}strAbort="abort";completeDeferred.add(s.complete);jqXHR.done(s.success);jqXHR.fail(s.error);transport=inspectPrefiltersOrTransports(transports,s,options,jqXHR);if(!transport){done(-1,"No Transport");}else{jqXHR.readyState=1;if(fireGlobals){globalEventContext.trigger("ajaxSend",[jqXHR,s]);}if(completed){return jqXHR;}if(s.async&&s.timeout>0){timeoutTimer=window.setTimeout(function(){jqXHR.abort("timeout");},s.timeout);}try{completed=false;transport.send(requestHeaders,done);}catch(e){if(completed){throw e;}done(-1,e);}}function done(status,nativeStatusText,responses,headers){var isSuccess,success,error,response,modified,statusText=nativeStatusText;if(completed){return;}completed=true;if(timeoutTimer){window.clearTimeout(timeoutTimer);}transport=undefined;responseHeadersString=headers||"";jqXHR.readyState=status>0?4:0;isSuccess=status>=200&&status<300||status===304;if(responses){response=ajaxHandleResponses(s,jqXHR,responses);}response=ajaxConvert(s,response,jqXHR,isSuccess);if(isSuccess){if(s.ifModified){modified=jqXHR.getResponseHeader("Last-Modified");if(modified){jQuery.lastModified[cacheURL]=modified;}modified=jqXHR.getResponseHeader("etag");if(modified){jQuery.etag[cacheURL]=modified;}}if(status===204||s.type==="HEAD"){statusText="nocontent";}else if(status===304){statusText="notmodified";}else{statusText=response.state;success=response.data;error=response.error;isSuccess=!error;}}else{error=statusText;if(status||!statusText){statusText="error";if(status<0){status=0;}}}jqXHR.status=status;jqXHR.statusText=(nativeStatusText||statusText)+"";if(isSuccess){deferred.resolveWith(callbackContext,[success,statusText,jqXHR]);}else{deferred.rejectWith(callbackContext,[jqXHR,statusText,error]);}jqXHR.statusCode(statusCode);statusCode=undefined;if(fireGlobals){globalEventContext.trigger(isSuccess?"ajaxSuccess":"ajaxError",[jqXHR,s,isSuccess?success:error]);}completeDeferred.fireWith(callbackContext,[jqXHR,statusText]);if(fireGlobals){globalEventContext.trigger("ajaxComplete",[jqXHR,s]);if(!(--jQuery.active)){jQuery.event.trigger("ajaxStop");}}}return jqXHR;},getJSON:function(url,data,callback){return jQuery.get(url,data,callback,"json");},getScript:function(url,callback){return jQuery.get(url,undefined,callback,"script");}});jQuery.each(["get","post"],function(i,method){jQuery[method]=function(url,data,callback,type){if(jQuery.isFunction(data)){type=type||callback;callback=data;data=undefined;}return jQuery.ajax(jQuery.extend({url:url,type:method,dataType:type,data:data,success:callback},jQuery.isPlainObject(url)&&url));};});jQuery._evalUrl=function(url){return jQuery.ajax({url:url,type:"GET",dataType:"script",cache:true,async:false,global:false,"throws":true});};jQuery.fn.extend({wrapAll:function(html){var wrap;if(this[0]){if(jQuery.isFunction(html)){html=html.call(this[0]);}wrap=jQuery(html,this[0].ownerDocument).eq(0).clone(true);if(this[0].parentNode){wrap.insertBefore(this[0]);}wrap.map(function(){var elem=this;while(elem.firstElementChild){elem=elem.firstElementChild;}return elem;}).append(this);}return this;},wrapInner:function(html){if(jQuery.isFunction(html)){return this.each(function(i){jQuery(this).wrapInner(html.call(this,i));});}return this.each(function(){var self=jQuery(this),contents=self.contents();if(contents.length){contents.wrapAll(html);}else{self.append(html);}});},wrap:function(html){var isFunction=jQuery.isFunction(html);return this.each(function(i){jQuery(this).wrapAll(isFunction?html.call(this,i):html);});},unwrap:function(selector){this.parent(selector).not("body").each(function(){jQuery(this).replaceWith(this.childNodes);});return this;}});jQuery.expr.pseudos.hidden=function(elem){return!jQuery.expr.pseudos.visible(elem);};jQuery.expr.pseudos.visible=function(elem){return!!(elem.offsetWidth||elem.offsetHeight||elem.getClientRects().length);};jQuery.ajaxSettings.xhr=function(){try{return new window.XMLHttpRequest();}catch(e){}};var xhrSuccessStatus={0:200,1223:204},xhrSupported=jQuery.ajaxSettings.xhr();support.cors=!!xhrSupported&&("withCredentials"in xhrSupported);support.ajax=xhrSupported=!!xhrSupported;jQuery.ajaxTransport(function(options){var callback,errorCallback;if(support.cors||xhrSupported&&!options.crossDomain){return{send:function(headers,complete){var i,xhr=options.xhr();xhr.open(options.type,options.url,options.async,options.username,options.password);if(options.xhrFields){for(i in options.xhrFields){xhr[i]=options.xhrFields[i];}}if(options.mimeType&&xhr.overrideMimeType){xhr.overrideMimeType(options.mimeType);}if(!options.crossDomain&&!headers["X-Requested-With"]){headers["X-Requested-With"]="XMLHttpRequest";}for(i in headers){xhr.setRequestHeader(i,headers[i]);}callback=function(type){return function(){if(callback){callback=errorCallback=xhr.onload=xhr.onerror=xhr.onabort=xhr.onreadystatechange=null;if(type==="abort"){xhr.abort();}else if(type==="error"){if(typeof xhr.status!=="number"){complete(0,"error");}else{complete(xhr.status,xhr.statusText);}}else{complete(xhrSuccessStatus[xhr.status]||xhr.status,xhr.statusText,(xhr.responseType||"text")!=="text"||typeof xhr.responseText!=="string"?{binary:xhr.response}:{text:xhr.responseText},xhr.getAllResponseHeaders());}}};};xhr.onload=callback();errorCallback=xhr.onerror=callback("error");if(xhr.onabort!==undefined){xhr.onabort=errorCallback;}else{xhr.onreadystatechange=function(){if(xhr.readyState===4){window.setTimeout(function(){if(callback){errorCallback();}});}};}callback=callback("abort");try{xhr.send(options.hasContent&&options.data||null);}catch(e){if(callback){throw e;}}},abort:function(){if(callback){callback();}}};}});jQuery.ajaxPrefilter(function(s){if(s.crossDomain){s.contents.script=false;}});jQuery.ajaxSetup({accepts:{script:"text/javascript, application/javascript, "+"application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(text){jQuery.globalEval(text);return text;}}});jQuery.ajaxPrefilter("script",function(s){if(s.cache===undefined){s.cache=false;}if(s.crossDomain){s.type="GET";}});jQuery.ajaxTransport("script",function(s){if(s.crossDomain){var script,callback;return{send:function(_,complete){script=jQuery("<script>").prop({charset:s.scriptCharset,src:s.url}).on("load error",callback=function(evt){script.remove();callback=null;if(evt){complete(evt.type==="error"?404:200,evt.type);}});document.head.appendChild(script[0]);},abort:function(){if(callback){callback();}}};}});var oldCallbacks=[],rjsonp=/(=)\?(?=&|$)|\?\?/;jQuery.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var callback=oldCallbacks.pop()||(jQuery.expando+"_"+(nonce++));this[callback]=true;return callback;}});jQuery.ajaxPrefilter("json jsonp",function(s,originalSettings,jqXHR){var callbackName,overwritten,responseContainer,jsonProp=s.jsonp!==false&&(rjsonp.test(s.url)?"url":typeof s.data==="string"&&(s.contentType||"").indexOf("application/x-www-form-urlencoded")===0&&rjsonp.test(s.data)&&"data");if(jsonProp||s.dataTypes[0]==="jsonp"){callbackName=s.jsonpCallback=jQuery.isFunction(s.jsonpCallback)?s.jsonpCallback():s.jsonpCallback;if(jsonProp){s[jsonProp]=s[jsonProp].replace(rjsonp,"$1"+callbackName);}else if(s.jsonp!==false){s.url+=(rquery.test(s.url)?"&":"?")+s.jsonp+"="+callbackName;}s.converters["script json"]=function(){if(!responseContainer){jQuery.error(callbackName+" was not called");}return responseContainer[0];};s.dataTypes[0]="json";overwritten=window[callbackName];window[callbackName]=function(){responseContainer=arguments;};jqXHR.always(function(){if(overwritten===undefined){jQuery(window).removeProp(callbackName);}else{window[callbackName]=overwritten;}if(s[callbackName]){s.jsonpCallback=originalSettings.jsonpCallback;oldCallbacks.push(callbackName);}if(responseContainer&&jQuery.isFunction(overwritten)){overwritten(responseContainer[0]);}responseContainer=overwritten=undefined;});return"script";}});support.createHTMLDocument=(function(){var body=document.implementation.createHTMLDocument("").body;body.innerHTML="<form></form><form></form>";return body.childNodes.length===2;}());jQuery.parseHTML=function(data,context,keepScripts){if(typeof data!=="string"){return[];}if(typeof context==="boolean"){keepScripts=context;context=false;}var base,parsed,scripts;if(!context){if(support.createHTMLDocument){context=document.implementation.createHTMLDocument("");base=context.createElement("base");base.href=document.location.href;context.head.appendChild(base);}else{context=document;}}parsed=rsingleTag.exec(data);scripts=!keepScripts&&[];if(parsed){return[context.createElement(parsed[1])];}parsed=buildFragment([data],context,scripts);if(scripts&&scripts.length){jQuery(scripts).remove();}return jQuery.merge([],parsed.childNodes);};jQuery.fn.load=function(url,params,callback){var selector,type,response,self=this,off=url.indexOf(" ");if(off>-1){selector=stripAndCollapse(url.slice(off));url=url.slice(0,off);}if(jQuery.isFunction(params)){callback=params;params=undefined;}else if(params&&typeof params==="object"){type="POST";}if(self.length>0){jQuery.ajax({url:url,type:type||"GET",dataType:"html",data:params}).done(function(responseText){response=arguments;self.html(selector?jQuery("<div>").append(jQuery.parseHTML(responseText)).find(selector):responseText);}).always(callback&&function(jqXHR,status){self.each(function(){callback.apply(this,response||[jqXHR.responseText,status,jqXHR]);});});}return this;};jQuery.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(i,type){jQuery.fn[type]=function(fn){return this.on(type,fn);};});jQuery.expr.pseudos.animated=function(elem){return jQuery.grep(jQuery.timers,function(fn){return elem===fn.elem;}).length;};function getWindow(elem){return jQuery.isWindow(elem)?elem:elem.nodeType===9&&elem.defaultView;}jQuery.offset={setOffset:function(elem,options,i){var curPosition,curLeft,curCSSTop,curTop,curOffset,curCSSLeft,calculatePosition,position=jQuery.css(elem,"position"),curElem=jQuery(elem),props={};if(position==="static"){elem.style.position="relative";}curOffset=curElem.offset();curCSSTop=jQuery.css(elem,"top");curCSSLeft=jQuery.css(elem,"left");calculatePosition=(position==="absolute"||position==="fixed")&&(curCSSTop+curCSSLeft).indexOf("auto")>-1;if(calculatePosition){curPosition=curElem.position();curTop=curPosition.top;curLeft=curPosition.left;}else{curTop=parseFloat(curCSSTop)||0;curLeft=parseFloat(curCSSLeft)||0;}if(jQuery.isFunction(options)){options=options.call(elem,i,jQuery.extend({},curOffset));}if(options.top!=null){props.top=(options.top-curOffset.top)+curTop;}if(options.left!=null){props.left=(options.left-curOffset.left)+curLeft;}if("using"in options){options.using.call(elem,props);}else{curElem.css(props);}}};jQuery.fn.extend({offset:function(options){if(arguments.length){return options===undefined?this:this.each(function(i){jQuery.offset.setOffset(this,options,i);});}var docElem,win,rect,doc,elem=this[0];if(!elem){return;}if(!elem.getClientRects().length){return{top:0,left:0};}rect=elem.getBoundingClientRect();if(rect.width||rect.height){doc=elem.ownerDocument;win=getWindow(doc);docElem=doc.documentElement;return{top:rect.top+win.pageYOffset-docElem.clientTop,left:rect.left+win.pageXOffset-docElem.clientLeft};}return rect;},position:function(){if(!this[0]){return;}var offsetParent,offset,elem=this[0],parentOffset={top:0,left:0};if(jQuery.css(elem,"position")==="fixed"){offset=elem.getBoundingClientRect();}else{offsetParent=this.offsetParent();offset=this.offset();if(!jQuery.nodeName(offsetParent[0],"html")){parentOffset=offsetParent.offset();}parentOffset={top:parentOffset.top+jQuery.css(offsetParent[0],"borderTopWidth",true),left:parentOffset.left+jQuery.css(offsetParent[0],"borderLeftWidth",true)};}return{top:offset.top-parentOffset.top-jQuery.css(elem,"marginTop",true),left:offset.left-parentOffset.left-jQuery.css(elem,"marginLeft",true)};},offsetParent:function(){return this.map(function(){var offsetParent=this.offsetParent;while(offsetParent&&jQuery.css(offsetParent,"position")==="static"){offsetParent=offsetParent.offsetParent;}return offsetParent||documentElement;});}});jQuery.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(method,prop){var top="pageYOffset"===prop;jQuery.fn[method]=function(val){return access(this,function(elem,method,val){var win=getWindow(elem);if(val===undefined){return win?win[prop]:elem[method];}if(win){win.scrollTo(!top?val:win.pageXOffset,top?val:win.pageYOffset);}else{elem[method]=val;}},method,val,arguments.length);};});jQuery.each(["top","left"],function(i,prop){jQuery.cssHooks[prop]=addGetHookIf(support.pixelPosition,function(elem,computed){if(computed){computed=curCSS(elem,prop);return rnumnonpx.test(computed)?jQuery(elem).position()[prop]+"px":computed;}});});jQuery.each({Height:"height",Width:"width"},function(name,type){jQuery.each({padding:"inner"+name,content:type,"":"outer"+name},function(defaultExtra,funcName){jQuery.fn[funcName]=function(margin,value){var chainable=arguments.length&&(defaultExtra||typeof margin!=="boolean"),extra=defaultExtra||(margin===true||value===true?"margin":"border");return access(this,function(elem,type,value){var doc;if(jQuery.isWindow(elem)){return funcName.indexOf("outer")===0?elem["inner"+name]:elem.document.documentElement["client"+name];}if(elem.nodeType===9){doc=elem.documentElement;return Math.max(elem.body["scroll"+name],doc["scroll"+name],elem.body["offset"+name],doc["offset"+name],doc["client"+name]);}return value===undefined?jQuery.css(elem,type,extra):jQuery.style(elem,type,value,extra);},type,chainable?margin:undefined,chainable);};});});jQuery.fn.extend({bind:function(types,data,fn){return this.on(types,null,data,fn);},unbind:function(types,fn){return this.off(types,null,fn);},delegate:function(selector,types,data,fn){return this.on(types,selector,data,fn);},undelegate:function(selector,types,fn){return arguments.length===1?this.off(selector,"**"):this.off(types,selector||"**",fn);}});jQuery.parseJSON=JSON.parse;if(typeof define==="function"&&define.amd){define("jquery",[],function(){return jQuery;});}var _jQuery=window.jQuery,_$=window.$;jQuery.noConflict=function(deep){if(window.$===jQuery){window.$=_$;}if(deep&&window.jQuery===jQuery){window.jQuery=_jQuery;}return jQuery;};if(!noGlobal){window.jQuery=window.$=jQuery;}return jQuery;});
/*jshint ignore:end */
|
"""
Support for IntesisHome Smart AC Controllers
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/intesishome/
"""
import logging
# from datetime import timedelta
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.const import (CONF_PASSWORD, CONF_USERNAME, CONF_STRUCTURE)
# from homeassistant.util import Throttle
from homeassistant.helpers.discovery import async_load_platform
from homeassistant.components import persistent_notification
_LOGGER = logging.getLogger(__name__)
DOMAIN = 'intesishome'
REQUIREMENTS = ['pyintesishome==0.4']
controller = None
hass = None
# MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=180)
CONFIG_SCHEMA = vol.Schema({
DOMAIN: vol.Schema({
vol.Required(CONF_USERNAME): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
vol.Optional(CONF_STRUCTURE): vol.All(cv.ensure_list, cv.string)
})
}, extra=vol.ALLOW_EXTRA)
def setup(hass, config):
"""Setup IntesisHome platform."""
global controller
from pyintesishome import IntesisHome
conf = config[DOMAIN]
_user = conf.get(CONF_USERNAME)
_pass = conf.get(CONF_PASSWORD)
if controller is None:
controller = IntesisHome(_user,_pass, hass.loop)
controller.connect()
hass.async_add_job(async_load_platform(hass, 'climate', DOMAIN))
if controller.error_message:
persistent_notification.create(hass, controller.error_message, "IntesisHome Error", 'intesishome')
return True
def stop_intesishome():
controller.stop()
def get_devices():
return controller.get_devices()
|
from machine import I2C
import LSM6DSO
i2c = I2C(1)
lsm = LSM6DSO.LSM6DSO(i2c)
lsm.ax()
lsm.get_a()
lsm.get()
|
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require bootstrap/tooltip
//= require bootstrap/popover
//= require_tree .
|
import PIL
import scipy.misc
from io import BytesIO
import tensorboardX as tb
from tensorboardX.summary import Summary
class TensorBoard(object):
def __init__(self, model_dir):
self.summary_writer = tb.FileWriter(model_dir)
def image_summary(self, tag, value, step):
for idx, img in enumerate(value):
summary = Summary()
bio = BytesIO()
if type(img) == str:
img = PIL.Image.open(img)
elif type(img) == PIL.Image.Image:
pass
else:
img = scipy.misc.toimage(img)
img.save(bio, format="png")
image_summary = Summary.Image(encoded_image_string=bio.getvalue())
summary.value.add(tag="{0}/{1}".format(tag,idx), image=image_summary)
self.summary_writer.add_summary(summary, global_step=step)
def scalar_summary(self, tag, value, step):
summary= Summary(value=[Summary.Value(tag=tag, simple_value=value)])
self.summary_writer.add_summary(summary, global_step=step)
|
var a00532 =
[
[ "value_type", "a00532.html#aa3c63f3f5da681da27e2aa133f8bffd2", null ],
[ "opencl_async_msg", "a00532.html#a2ad7b779cdac9478994000840cd2ef8f", null ],
[ "opencl_async_msg", "a00532.html#aadd4b2e6518cf36405fd47ac87db7f19", null ],
[ "opencl_async_msg", "a00532.html#a4371b06eb85a3abaf7ba0ca3d66bc5cc", null ],
[ "opencl_async_msg", "a00532.html#a46fe2dd1ef8547701e58e14a483e0de3", null ],
[ "opencl_async_msg", "a00532.html#aa70010c232651e11ff07e88991717745", null ],
[ "~opencl_async_msg", "a00532.html#adecb2ade5cb158956855fba6a8c0a82b", null ],
[ "clear_event", "a00532.html#a93064e1bfa9bb387c650faa75401981a", null ],
[ "data", "a00532.html#ac8a163f1a440bcddf34dc8b06eb61b21", null ],
[ "data", "a00532.html#ae47837a584dc42f4c7bd44dad7708e9d", null ],
[ "finalize", "a00532.html#a15d3b949f1ce48860a05fb3e0a537907", null ],
[ "get_event", "a00532.html#ae07788102cdb52b24ffa3c60bf35b561", null ],
[ "operator const T &", "a00532.html#ae6c7c0102d601788ff6c54f34b066293", null ],
[ "operator T &", "a00532.html#ac1c1cf1accbc0f7b9b2e9104dcfdc0c9", null ],
[ "operator=", "a00532.html#a384293c9b08c51e87164e1e4fffbeddf", null ],
[ "register_callback", "a00532.html#af267060e5a040c3db3c26ae16e088914", null ],
[ "register_callback_func", "a00532.html#a9a6c57f3e3f6829a3a35e1ad3e321c2e", null ],
[ "set_event", "a00532.html#a030a92451783a9c07287983339b927d4", null ],
[ "my_callback_flag_ptr", "a00532.html#a36afd28b4241fd335f9ddb8934429c80", null ],
[ "my_data", "a00532.html#aabf5afb014f67aacc58e17a7a90391fd", null ],
[ "my_event", "a00532.html#a657138f7e8217613a43b9506ea3260f2", null ],
[ "my_is_event", "a00532.html#a29d4cc394c206b43b8652699284be236", null ]
];
|
/*
* This header is generated by classdump-dyld 1.5
* on Wednesday, October 27, 2021 at 3:23:08 PM Mountain Standard Time
* Operating System: Version 13.5.1 (Build 17F80)
* Image Source: /System/Library/PrivateFrameworks/iCloudQuotaUI.framework/iCloudQuotaUI
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley.
*/
#import <libobjc.A.dylib/AAUIServerHook.h>
@protocol AAUIServerHookDelegate, ICQServerHookDelegate;
@class FACircleStateController, NSString, AAUIServerHookResponse;
@interface ICQFamilySharingHook : NSObject <AAUIServerHook> {
id<AAUIServerHookDelegate> _delegate;
id<ICQServerHookDelegate> _flowDelegate;
FACircleStateController* _familyCircleStateController;
}
@property (__weak) id<ICQServerHookDelegate> flowDelegate; //@synthesize flowDelegate=_flowDelegate - In the implementation block
@property (retain) FACircleStateController * familyCircleStateController; //@synthesize familyCircleStateController=_familyCircleStateController - In the implementation block
@property (readonly) unsigned long long hash;
@property (readonly) Class superclass;
@property (copy,readonly) NSString * description;
@property (copy,readonly) NSString * debugDescription;
@property (nonatomic,retain) AAUIServerHookResponse * serverHookResponse;
@property (assign,nonatomic,__weak) id<AAUIServerHookDelegate> delegate; //@synthesize delegate=_delegate - In the implementation block
-(id<AAUIServerHookDelegate>)delegate;
-(void)setDelegate:(id<AAUIServerHookDelegate>)arg1 ;
-(BOOL)shouldMatchElement:(id)arg1 ;
-(BOOL)shouldMatchModel:(id)arg1 ;
-(void)processElement:(id)arg1 attributes:(id)arg2 objectModel:(id)arg3 completion:(/*^block*/id)arg4 ;
-(void)processObjectModel:(id)arg1 completion:(/*^block*/id)arg2 ;
-(id)initWithFlowDelegate:(id)arg1 ;
-(void)_beginFamilySharingFlowWithCompletion:(/*^block*/id)arg1 ;
-(id<ICQServerHookDelegate>)flowDelegate;
-(void)setFlowDelegate:(id<ICQServerHookDelegate>)arg1 ;
-(FACircleStateController *)familyCircleStateController;
-(void)setFamilyCircleStateController:(FACircleStateController *)arg1 ;
@end
|
import base64
def make(backend):
class ExtendedDoubleRatchet(backend.DoubleRatchet):
def __init__(self, other_ik, *args, **kwargs):
super().__init__(*args, **kwargs)
self.__other_ik = other_ik
def serialize(self):
return {
"super" : super().serialize(),
"other_ik" : base64.b64encode(self.__other_ik).decode("US-ASCII")
}
@classmethod
def fromSerialized(cls, serialized, *args, **kwargs):
self = super().fromSerialized(
serialized["super"],
*args,
ad = None, # TODO: This is ugly
root_key = None,
**kwargs
)
self.__other_ik = base64.b64decode(serialized["other_ik"].encode("US-ASCII"))
return self
@property
def ik(self):
return self.__other_ik
@property
def receiving_chain_length(self):
return self._DoubleRatchet__skr.receiving_chain_length
return ExtendedDoubleRatchet
|
"strict mode"
const NETWORK = process.env.OT_NETWORK;
if (NETWORK !== 'Polyjuice' && NETWORK !== 'Rinkeby') {
throw "NETWORK environment variable must be either Polyjuice or Rinkeby";
}
console.log(`Using ${NETWORK} network with ${process.env.OT_RPC_URL ? process.env.OT_RPC_URL : "default"} RPC URL`);
if (!process.env.OT_ACCOUNT_PRIVATE_KEY) {
throw "OT_ACCOUNT_PRIVATE_KEY environment variable not set"
}
const { web3, DEFAULT_SEND_OPTIONS, account, ACCOUNT_POLY_ADDRESS } = require('./' + NETWORK);
async function checkBalance(address, amount) {
console.log(`Calling web3.eth.getBalance...`);
const balance = BigInt(await web3.eth.getBalance(address));
console.log(`Balance of ${address} = ${balance}`);
if (balance < amount) {
throw `Insufficient balance. Can't issue a smart contract call. Please deposit funds to your address: ${address}`;
}
return balance;
}
async function deploy(contractArtifact, arguments) {
console.log(`Calling deploy of a contract...`);
const tx = new web3.eth.Contract(contractArtifact.abi).deploy({
data: contractArtifact.bytecode || contractArtifact.data.bytecode.object,
arguments: arguments,
}).send(
{
...DEFAULT_SEND_OPTIONS,
from: account.address,
}
);
tx.on('transactionHash', hash => console.log(`Txn Hash: ${hash}`));
return tx;
}
async function checkERC20Balance(contract, address, amount, equality=true) {
// console.log(`Calling balanceOf of an ERC20...`);
const balance = BigInt(await contract.methods.balanceOf(address).call({
from: account.address
}));
// console.log(`ERC20 Balance of ${address} = ${balance}`);
if (equality == true) {
if (balance != amount) {
throw `Mismatch in ERC20 balance: ${balance} != ${amount}`;
}
} else {
if (balance < amount) {
throw `Insufficient ERC20 balance. Please deposit ERC20 funds to your Ethereum address: ${account.address}`;
}
}
return balance;
}
async function getOpthys(contract) {
console.log(`Calling getOpthys...`);
return contract.methods.getOpthys().call({
from: account.address
});
}
async function approve(contract, address, amount) {
console.log(`Calling approve on ERC20...`);
const tx = contract.methods.approve(address, amount).send(
{
...DEFAULT_SEND_OPTIONS,
from: account.address,
}
);
tx.on('transactionHash', hash => console.log(`Txn Hash: ${hash}`));
return tx;
}
async function newOpthy(OpthysContract, ISell, duration, token0, token1, r0, r1, amount0) {
console.log(`Calling newOpthy...`);
const tx = OpthysContract.methods.newOpthy(ISell, duration, token0, token1, r0, r1, amount0).send(
{
...DEFAULT_SEND_OPTIONS,
from: account.address,
}
);
tx.on('transactionHash', hash => console.log(`Txn Hash: ${hash}`));
return tx;
}
async function update(contract, duration, amount0, r0, r1) {
console.log(`Calling update...`);
const tx = contract.methods.update(duration, amount0, r0, r1).send(
{
...DEFAULT_SEND_OPTIONS,
from: account.address,
}
);
tx.on('transactionHash', hash => console.log(`Txn Hash: ${hash}`));
return tx;
}
async function agree(contract, amount0, phase) {
console.log(`Calling agree...`);
const tx = contract.methods.agree(amount0, phase).send(
{
...DEFAULT_SEND_OPTIONS,
from: account.address,
}
);
tx.on('transactionHash', hash => console.log(`Txn Hash: ${hash}`));
return tx;
}
async function swap(contract, amount0In, amount1In, amount0Out, amount1Out) {
console.log(`Calling swap...`);
const tx = contract.methods.swap(amount0In, amount1In, amount0Out, amount1Out).send(
{
...DEFAULT_SEND_OPTIONS,
from: account.address,
}
);
tx.on('transactionHash', hash => console.log(`Txn Hash: ${hash}`));
return tx;
}
async function reclaim(contract) {
console.log(`Calling reclaim...`);
const tx = contract.methods.reclaim().send(
{
...DEFAULT_SEND_OPTIONS,
from: account.address,
}
);
tx.on('transactionHash', hash => console.log(`Txn Hash: ${hash}`));
return tx;
}
async function sleep(ms) {
console.log(`Sleeping for ${ms/1000} seconds`);
return new Promise(resolve => setTimeout(resolve, ms));
}
(async () => {
try {
const OPTHYS_ARTIFACT = require("opthy-v0-core/artifacts/Opthys");
const OPTHY_ARTIFACT = require("opthy-v0-core/artifacts/Opthy");
const TESTERC20_ARTIFACT = require("./artifacts/testERC20");
await checkBalance(account.address, 1);
const OPTHYS_ADDRESS = process.env.OT_OPTHYS_ADDRESS || (await deploy(OPTHYS_ARTIFACT, []))._address;
console.log(`Opthys on address: ${OPTHYS_ADDRESS}`);
const OpthysContract = new web3.eth.Contract(OPTHYS_ARTIFACT.abi, OPTHYS_ADDRESS);
const ERC20_0_ADDRESS = process.env.OT_ERC20_0_ADDRESS || (await deploy(TESTERC20_ARTIFACT, []))._address;
console.log(`ERC20 Token 0 on address: ${ERC20_0_ADDRESS}`);
const ERC20_0_contract = new web3.eth.Contract(TESTERC20_ARTIFACT.abi, ERC20_0_ADDRESS);
oldBalance0 = await checkERC20Balance(ERC20_0_contract, ACCOUNT_POLY_ADDRESS, 100, equality = false);
await approve(ERC20_0_contract, OPTHYS_ADDRESS, 2);
const ERC20_1_ADDRESS = process.env.OT_ERC20_1_ADDRESS || (await deploy(TESTERC20_ARTIFACT, []))._address;
console.log(`ERC20 Token 1 on address: ${ERC20_1_ADDRESS}`);
const ERC20_1_contract = new web3.eth.Contract(TESTERC20_ARTIFACT.abi, ERC20_1_ADDRESS);
oldBalance1 = await checkERC20Balance(ERC20_1_contract, ACCOUNT_POLY_ADDRESS, 100, equality = false);
//////newOpthy(OpthysContract, ISell, duration, token0, token1, r0, r1, amount0)
await newOpthy(OpthysContract, true, 10, ERC20_0_ADDRESS, ERC20_1_ADDRESS, 3, 3, 2);
tx = await getOpthys(OpthysContract);
const OPTHY_ADDRESS = tx[0].opthy;
console.log(`Opthy deployed on address: ${OPTHY_ADDRESS}`);
const OContract = new web3.eth.Contract(OPTHY_ARTIFACT.abi, OPTHY_ADDRESS);
await checkERC20Balance(ERC20_0_contract, OPTHY_ADDRESS, 2);
await checkERC20Balance(ERC20_1_contract, OPTHY_ADDRESS, 0);
await approve(ERC20_0_contract, OPTHY_ADDRESS, 100);
await approve(ERC20_1_contract, OPTHY_ADDRESS, 100);
//////update(contract, duration, amount0, r0, r1)
await update(OContract, 60, 7, 10, 10);
await checkERC20Balance(ERC20_0_contract, OPTHY_ADDRESS, 9);
await checkERC20Balance(ERC20_1_contract, OPTHY_ADDRESS, 0);
//////agree(contract, amount0, phase)
await agree(OContract, 1, 2);
await checkERC20Balance(ERC20_0_contract, OPTHY_ADDRESS, 10);
await checkERC20Balance(ERC20_1_contract, OPTHY_ADDRESS, 0);
//////swap(contract, amount0In, amount1In, amount0Out, amount1Out)
await swap(OContract, 0, 10, 10, 0);
await checkERC20Balance(ERC20_0_contract, OPTHY_ADDRESS, 0);
await checkERC20Balance(ERC20_1_contract, OPTHY_ADDRESS, 10);
//////swap(contract, amount0In, amount1In, amount0Out, amount1Out)
await swap(OContract, 3, 0, 0, 3);
await checkERC20Balance(ERC20_0_contract, OPTHY_ADDRESS, 3);
await checkERC20Balance(ERC20_1_contract, OPTHY_ADDRESS, 7);
await sleep(300000)
await reclaim(OContract);
await checkERC20Balance(ERC20_0_contract, OPTHY_ADDRESS, 0);
await checkERC20Balance(ERC20_1_contract, OPTHY_ADDRESS, 0);
await checkERC20Balance(ERC20_0_contract, ACCOUNT_POLY_ADDRESS, oldBalance0);
await checkERC20Balance(ERC20_1_contract, ACCOUNT_POLY_ADDRESS, oldBalance1);
} catch (error) {
console.log(error);
}
})();
|
// LAF FreeType Wrapper
// Copyright (c) 2017 David Capello
//
// This file is released under the terms of the MIT license.
// Read LICENSE.txt for more information.
#ifndef FT_HB_FACE_H_INCLUDED
#define FT_HB_FACE_H_INCLUDED
#pragma once
#include "base/string.h"
#include "ft/face.h"
#include <hb.h>
#include <hb-ft.h>
namespace ft {
template<typename FaceFT>
class HBFace : public FaceFT {
public:
HBFace(FT_Face face) : FaceFT(face) {
m_font = (face ? hb_ft_font_create((FT_Face)face, nullptr): nullptr);
m_buffer = (face ? hb_buffer_create(): nullptr);
}
~HBFace() {
if (m_buffer) hb_buffer_destroy(m_buffer);
if (m_font) hb_font_destroy(m_font);
}
hb_font_t* font() const { return m_font; }
hb_buffer_t* buffer() const { return m_buffer; }
private:
hb_buffer_t* m_buffer;
hb_font_t* m_font;
};
typedef HBFace<FaceFT<SimpleCache> > Face;
} // namespace ft
#endif
|
import Login from './Login'
export default Login;
|
# CS 510 Cloud and Cluster Data Management
# Fall 2018
# Team Spartans:
# Punam Pal
# Haomin He
# Pallavi Gusain
# Yokesh Thirumoorthi
import logging
log = logging.getLogger()
log.setLevel('DEBUG')
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter("%(asctime)s [%(levelname)s] %(name)s: %(message)s"))
log.addHandler(handler)
from cassandra import ConsistencyLevel
from cassandra.cluster import Cluster
from cassandra.query import SimpleStatement
import pandas as pd
from cassandra.cluster import Cluster
pd.set_option('expand_frame_repr', True)
KEYSPACE = "dblp"
CREATE_KEYSPACE = """
CREATE KEYSPACE IF NOT EXISTS %s
WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '2' }
""" % KEYSPACE
DROP_KEYSPACE = "DROP KEYSPACE " + KEYSPACE
def printTables(session):
auth = session.execute('select pub_id,auth_id,pub_type,title from publication_details')
mostcoauthors =[]
mostauthors = 0
for each in auth:
if(len(each.auth_id ) >= mostauthors):
mostcoauthors = []
mostcoauthors.append(each.pub_id)
mostcoauthors.append(len(each.auth_id))
mostcoauthors.append(each.pub_type)
mostcoauthors.append(each.title)
mostauthors = len(each.auth_id)
print(mostcoauthors)
def main():
cluster = Cluster(['127.0.0.1'])
session = cluster.connect()
log.info("creating keyspace...")
session.execute(CREATE_KEYSPACE)
log.info("setting keyspace...")
session.set_keyspace(KEYSPACE)
# log.info("creating table...")
# session.execute(CREATE_PUBLICATIONS_IF_NOT_EXISTS)
# populateTables(session)
printTables(session)
log.info("dropping keyspace...")
#session.execute(DROP_KEYSPACE)
if __name__ == "__main__":
main()
|
"""Database Module. Currently wrapping up all Redshift, PostgreSQL and MySQL functionalities."""
import json
import logging
import uuid
from typing import Any, Dict, Iterator, List, Optional, Tuple, Union
from urllib.parse import quote_plus as _quote_plus
import boto3
import pandas as pd
import pyarrow as pa
import sqlalchemy
from sqlalchemy.sql.visitors import VisitableType
from awswrangler import _data_types, _utils, exceptions, s3
from awswrangler.s3._list import _path2list # noqa
_logger: logging.Logger = logging.getLogger(__name__)
_RS_DISTSTYLES = ["AUTO", "EVEN", "ALL", "KEY"]
_RS_SORTSTYLES = ["COMPOUND", "INTERLEAVED"]
def _rs_drop_table(con: Any, schema: str, table: str) -> None:
sql = f"DROP TABLE IF EXISTS {schema}.{table}"
_logger.debug("Drop table query:\n%s", sql)
con.execute(sql)
def _rs_get_primary_keys(con: Any, schema: str, table: str) -> List[str]:
cursor: Any = con.execute(
f"SELECT indexdef FROM pg_indexes WHERE schemaname = '{schema}' AND tablename = '{table}'"
)
result: str = cursor.fetchall()[0][0]
rfields: List[str] = result.split("(")[1].strip(")").split(",")
fields: List[str] = [field.strip().strip('"') for field in rfields]
return fields
def _rs_does_table_exist(con: Any, schema: str, table: str) -> bool:
cursor = con.execute(
f"SELECT true WHERE EXISTS ("
f"SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE "
f"TABLE_SCHEMA = '{schema}' AND TABLE_NAME = '{table}'"
f");"
)
if len(cursor.fetchall()) > 0:
return True
return False
def _rs_upsert(con: Any, table: str, temp_table: str, schema: str, primary_keys: Optional[List[str]] = None) -> None:
if not primary_keys:
primary_keys = _rs_get_primary_keys(con=con, schema=schema, table=table)
_logger.debug("primary_keys: %s", primary_keys)
if not primary_keys:
raise exceptions.InvalidRedshiftPrimaryKeys()
equals_clause: str = f"{table}.%s = {temp_table}.%s"
join_clause: str = " AND ".join([equals_clause % (pk, pk) for pk in primary_keys])
sql: str = f"DELETE FROM {schema}.{table} USING {temp_table} WHERE {join_clause}"
_logger.debug(sql)
con.execute(sql)
sql = f"INSERT INTO {schema}.{table} SELECT * FROM {temp_table}"
_logger.debug(sql)
con.execute(sql)
_rs_drop_table(con=con, schema=schema, table=temp_table)
def _rs_create_table(
con: Any,
table: str,
schema: str,
mode: str,
redshift_types: Dict[str, str],
diststyle: str,
sortstyle: str,
distkey: Optional[str] = None,
sortkey: Optional[List[str]] = None,
primary_keys: Optional[List[str]] = None,
) -> Tuple[str, Optional[str]]:
if mode == "overwrite":
_rs_drop_table(con=con, schema=schema, table=table)
else:
if _rs_does_table_exist(con=con, schema=schema, table=table) is True:
if mode == "upsert":
guid: str = uuid.uuid4().hex
temp_table: str = f"temp_redshift_{guid}"
sql: str = f"CREATE TEMPORARY TABLE {temp_table} (LIKE {schema}.{table})"
_logger.debug(sql)
con.execute(sql)
return temp_table, None
return table, schema
diststyle = diststyle.upper() if diststyle else "AUTO"
sortstyle = sortstyle.upper() if sortstyle else "COMPOUND"
_rs_validate_parameters(
redshift_types=redshift_types,
diststyle=diststyle,
distkey=distkey,
sortstyle=sortstyle,
sortkey=sortkey,
)
cols_str: str = "".join([f"{k} {v},\n" for k, v in redshift_types.items()])[:-2]
primary_keys_str: str = f",\nPRIMARY KEY ({', '.join(primary_keys)})" if primary_keys else ""
distkey_str: str = f"\nDISTKEY({distkey})" if distkey and diststyle == "KEY" else ""
sortkey_str: str = f"\n{sortstyle} SORTKEY({','.join(sortkey)})" if sortkey else ""
sql = (
f"CREATE TABLE IF NOT EXISTS {schema}.{table} (\n"
f"{cols_str}"
f"{primary_keys_str}"
f")\nDISTSTYLE {diststyle}"
f"{distkey_str}"
f"{sortkey_str}"
)
_logger.debug("Create table query:\n%s", sql)
con.execute(sql)
return table, schema
def _rs_validate_parameters(
redshift_types: Dict[str, str],
diststyle: str,
distkey: Optional[str],
sortstyle: str,
sortkey: Optional[List[str]],
) -> None:
if diststyle not in _RS_DISTSTYLES:
raise exceptions.InvalidRedshiftDiststyle(f"diststyle must be in {_RS_DISTSTYLES}")
cols = list(redshift_types.keys())
_logger.debug("Redshift columns: %s", cols)
if (diststyle == "KEY") and (not distkey):
raise exceptions.InvalidRedshiftDistkey("You must pass a distkey if you intend to use KEY diststyle")
if distkey and distkey not in cols:
raise exceptions.InvalidRedshiftDistkey(f"distkey ({distkey}) must be in the columns list: {cols})")
if sortstyle and sortstyle not in _RS_SORTSTYLES:
raise exceptions.InvalidRedshiftSortstyle(f"sortstyle must be in {_RS_SORTSTYLES}")
if sortkey:
if not isinstance(sortkey, list):
raise exceptions.InvalidRedshiftSortkey(
f"sortkey must be a List of items in the columns list: {cols}. " f"Currently value: {sortkey}"
)
for key in sortkey:
if key not in cols:
raise exceptions.InvalidRedshiftSortkey(
f"sortkey must be a List of items in the columns list: {cols}. " f"Currently value: {key}"
)
def _rs_copy(
con: Any,
table: str,
manifest_path: str,
iam_role: str,
num_files: int,
schema: Optional[str] = None,
) -> int:
if schema is None:
table_name: str = table
else:
table_name = f"{schema}.{table}"
sql: str = f"COPY {table_name} FROM '{manifest_path}'\nIAM_ROLE '{iam_role}'\nFORMAT AS PARQUET\nMANIFEST"
_logger.debug("copy query:\n%s", sql)
con.execute(sql)
sql = "SELECT pg_last_copy_id() AS query_id"
query_id: int = con.execute(sql).fetchall()[0][0]
sql = f"SELECT COUNT(DISTINCT filename) as num_files_loaded FROM STL_LOAD_COMMITS WHERE query = {query_id}"
num_files_loaded: int = con.execute(sql).fetchall()[0][0]
_logger.debug("%s files counted. %s expected.", num_files_loaded, num_files)
if num_files_loaded != num_files:
raise exceptions.RedshiftLoadError(
f"Redshift load rollbacked. {num_files_loaded} files counted. {num_files} expected."
)
return num_files_loaded
def _validate_engine(con: sqlalchemy.engine.Engine) -> None:
if not isinstance(con, sqlalchemy.engine.Engine):
raise exceptions.InvalidConnection(
"Invalid 'con' argument, please pass a "
"SQLAlchemy Engine. Use wr.db.get_engine(), "
"wr.db.get_redshift_temp_engine() or wr.catalog.get_engine()"
)
def _records2df(
records: List[Tuple[Any]],
cols_names: List[str],
index: Optional[Union[str, List[str]]],
safe: bool,
dtype: Optional[Dict[str, pa.DataType]],
) -> pd.DataFrame:
arrays: List[pa.Array] = []
for col_values, col_name in zip(tuple(zip(*records)), cols_names): # Transposing
if (dtype is None) or (col_name not in dtype):
try:
array: pa.Array = pa.array(obj=col_values, safe=safe) # Creating Arrow array
except pa.ArrowInvalid as ex:
array = _data_types.process_not_inferred_array(ex, values=col_values) # Creating Arrow array
else:
try:
array = pa.array(obj=col_values, type=dtype[col_name], safe=safe) # Creating Arrow array with dtype
except pa.ArrowInvalid:
array = pa.array(obj=col_values, safe=safe) # Creating Arrow array
array = array.cast(target_type=dtype[col_name], safe=safe) # Casting
arrays.append(array)
table = pa.Table.from_arrays(arrays=arrays, names=cols_names) # Creating arrow Table
df: pd.DataFrame = table.to_pandas( # Creating Pandas DataFrame
use_threads=True,
split_blocks=True,
self_destruct=True,
integer_object_nulls=False,
date_as_object=True,
types_mapper=_data_types.pyarrow2pandas_extension,
safe=safe,
)
if index is not None:
df.set_index(index, inplace=True)
return df
def _iterate_cursor(
cursor: Any,
chunksize: int,
cols_names: List[str],
index: Optional[Union[str, List[str]]],
safe: bool,
dtype: Optional[Dict[str, pa.DataType]],
) -> Iterator[pd.DataFrame]:
while True:
records = cursor.fetchmany(chunksize)
if not records:
break
yield _records2df(records=records, cols_names=cols_names, index=index, safe=safe, dtype=dtype)
def _convert_params(sql: str, params: Optional[Union[List[Any], Tuple[Any, ...], Dict[Any, Any]]]) -> List[Any]:
args: List[Any] = [sql]
if params is not None:
if hasattr(params, "keys"):
return args + [params]
return args + [list(params)]
return args
def _read_parquet_iterator(
paths: List[str],
keep_files: bool,
use_threads: bool,
categories: Optional[List[str]],
chunked: Union[bool, int],
boto3_session: Optional[boto3.Session],
s3_additional_kwargs: Optional[Dict[str, str]],
) -> Iterator[pd.DataFrame]:
dfs: Iterator[pd.DataFrame] = s3.read_parquet(
path=paths,
categories=categories,
chunked=chunked,
dataset=False,
use_threads=use_threads,
boto3_session=boto3_session,
s3_additional_kwargs=s3_additional_kwargs,
)
yield from dfs
if keep_files is False:
s3.delete_objects(path=paths, use_threads=use_threads, boto3_session=boto3_session)
def to_sql(df: pd.DataFrame, con: sqlalchemy.engine.Engine, **pandas_kwargs: Any) -> None:
"""Write records stored in a DataFrame to a SQL database.
Support for **Redshift**, **PostgreSQL** and **MySQL**.
Support for all pandas to_sql() arguments:
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_sql.html
Note
----
Redshift: For large DataFrames (1MM+ rows) consider the function **wr.db.copy_to_redshift()**.
Note
----
Redshift: `index=False` will be forced.
Parameters
----------
df : pandas.DataFrame
Pandas DataFrame https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html
con : sqlalchemy.engine.Engine
SQLAlchemy Engine. Please use,
wr.db.get_engine(), wr.db.get_redshift_temp_engine() or wr.catalog.get_engine()
pandas_kwargs
KEYWORD arguments forwarded to pandas.DataFrame.to_sql(). You can NOT pass `pandas_kwargs` explicit, just add
valid Pandas arguments in the function call and Wrangler will accept it.
e.g. wr.db.to_sql(df, con=con, name="table_name", schema="schema_name", if_exists="replace", index=False)
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_sql.html
Returns
-------
None
None.
Examples
--------
Writing to Redshift with temporary credentials
>>> import awswrangler as wr
>>> import pandas as pd
>>> wr.db.to_sql(
... df=pd.DataFrame({'col': [1, 2, 3]}),
... con=wr.db.get_redshift_temp_engine(cluster_identifier="...", user="..."),
... name="table_name",
... schema="schema_name"
... )
Writing to Redshift with temporary credentials and using pandas_kwargs
>>> import awswrangler as wr
>>> import pandas as pd
>>> wr.db.to_sql(
... df=pd.DataFrame({'col': [1, 2, 3]}),
... con=wr.db.get_redshift_temp_engine(cluster_identifier="...", user="..."),
... name="table_name",
... schema="schema_name",
... if_exists="replace",
... index=False,
... )
Writing to Redshift from Glue Catalog Connections
>>> import awswrangler as wr
>>> import pandas as pd
>>> wr.db.to_sql(
... df=pd.DataFrame({'col': [1, 2, 3]}),
... con=wr.catalog.get_engine(connection="..."),
... name="table_name",
... schema="schema_name"
... )
"""
if "pandas_kwargs" in pandas_kwargs:
raise exceptions.InvalidArgument(
"You can NOT pass `pandas_kwargs` explicit, just add valid "
"Pandas arguments in the function call and Wrangler will accept it."
"e.g. wr.db.to_sql(df, con, name='...', schema='...', if_exists='replace')"
)
if df.empty is True:
raise exceptions.EmptyDataFrame()
if not isinstance(con, sqlalchemy.engine.Engine):
raise exceptions.InvalidConnection(
"Invalid 'con' argument, please pass a "
"SQLAlchemy Engine. Use wr.db.get_engine(), "
"wr.db.get_redshift_temp_engine() or wr.catalog.get_engine()"
)
if "dtype" in pandas_kwargs:
cast_columns: Dict[str, VisitableType] = pandas_kwargs["dtype"]
else:
cast_columns = {}
dtypes: Dict[str, VisitableType] = _data_types.sqlalchemy_types_from_pandas(
df=df, db_type=con.name, dtype=cast_columns
)
pandas_kwargs["dtype"] = dtypes
pandas_kwargs["con"] = con
if pandas_kwargs["con"].name.lower() == "redshift": # Redshift does not accept index
pandas_kwargs["index"] = False
_utils.try_it(f=df.to_sql, ex=sqlalchemy.exc.InternalError, **pandas_kwargs)
def read_sql_query(
sql: str,
con: sqlalchemy.engine.Engine,
index_col: Optional[Union[str, List[str]]] = None,
params: Optional[Union[List[Any], Tuple[Any, ...], Dict[Any, Any]]] = None,
chunksize: Optional[int] = None,
dtype: Optional[Dict[str, pa.DataType]] = None,
safe: bool = True,
) -> Union[pd.DataFrame, Iterator[pd.DataFrame]]:
"""Return a DataFrame corresponding to the result set of the query string.
Support for **Redshift**, **PostgreSQL** and **MySQL**.
Note
----
Redshift: For large extractions (1MM+ rows) consider the function **wr.db.unload_redshift()**.
Parameters
----------
sql : str
Pandas DataFrame https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html
con : sqlalchemy.engine.Engine
SQLAlchemy Engine. Please use,
wr.db.get_engine(), wr.db.get_redshift_temp_engine() or wr.catalog.get_engine()
index_col : Union[str, List[str]], optional
Column(s) to set as index(MultiIndex).
params : Union[List, Tuple, Dict], optional
List of parameters to pass to execute method.
The syntax used to pass parameters is database driver dependent.
Check your database driver documentation for which of the five syntax styles,
described in PEP 249’s paramstyle, is supported.
Eg. for psycopg2, uses %(name)s so use params={‘name’ : ‘value’}.
chunksize : int, optional
If specified, return an iterator where chunksize is the number of rows to include in each chunk.
dtype : Dict[str, pyarrow.DataType], optional
Specifying the datatype for columns.
The keys should be the column names and the values should be the PyArrow types.
safe : bool
Check for overflows or other unsafe data type conversions.
Returns
-------
Union[pandas.DataFrame, Iterator[pandas.DataFrame]]
Result as Pandas DataFrame(s).
Examples
--------
Reading from Redshift with temporary credentials
>>> import awswrangler as wr
>>> df = wr.db.read_sql_query(
... sql="SELECT * FROM public.my_table",
... con=wr.db.get_redshift_temp_engine(cluster_identifier="...", user="...")
... )
Reading from Redshift from Glue Catalog Connections
>>> import awswrangler as wr
>>> df = wr.db.read_sql_query(
... sql="SELECT * FROM public.my_table",
... con=wr.catalog.get_engine(connection="...")
... )
"""
_validate_engine(con=con)
with con.connect() as _con:
args = _convert_params(sql, params)
cursor = _con.execute(*args)
if chunksize is None:
return _records2df(
records=cursor.fetchall(), cols_names=cursor.keys(), index=index_col, dtype=dtype, safe=safe
)
return _iterate_cursor(
cursor=cursor, chunksize=chunksize, cols_names=cursor.keys(), index=index_col, dtype=dtype, safe=safe
)
def read_sql_table(
table: str,
con: sqlalchemy.engine.Engine,
schema: Optional[str] = None,
index_col: Optional[Union[str, List[str]]] = None,
params: Optional[Union[List[Any], Tuple[Any, ...], Dict[Any, Any]]] = None,
chunksize: Optional[int] = None,
dtype: Optional[Dict[str, pa.DataType]] = None,
safe: bool = True,
) -> Union[pd.DataFrame, Iterator[pd.DataFrame]]:
"""Return a DataFrame corresponding to the result set of the query string.
Support for **Redshift**, **PostgreSQL** and **MySQL**.
Note
----
Redshift: For large extractions (1MM+ rows) consider the function `wr.db.unload_redshift()`.
Parameters
----------
table : str
Nable name.
con : sqlalchemy.engine.Engine
SQLAlchemy Engine. Please use,
wr.db.get_engine(), wr.db.get_redshift_temp_engine() or wr.catalog.get_engine()
schema : str, optional
Name of SQL schema in database to query (if database flavor supports this).
Uses default schema if None (default).
index_col : Union[str, List[str]], optional
Column(s) to set as index(MultiIndex).
params : Union[List, Tuple, Dict], optional
List of parameters to pass to execute method.
The syntax used to pass parameters is database driver dependent.
Check your database driver documentation for which of the five syntax styles,
described in PEP 249’s paramstyle, is supported.
Eg. for psycopg2, uses %(name)s so use params={‘name’ : ‘value’}.
chunksize : int, optional
If specified, return an iterator where chunksize is the number of rows to include in each chunk.
dtype : Dict[str, pyarrow.DataType], optional
Specifying the datatype for columns.
The keys should be the column names and the values should be the PyArrow types.
safe : bool
Check for overflows or other unsafe data type conversions.
Returns
-------
Union[pandas.DataFrame, Iterator[pandas.DataFrame]]
Result as Pandas DataFrame(s).
Examples
--------
Reading from Redshift with temporary credentials
>>> import awswrangler as wr
>>> df = wr.db.read_sql_table(
... table="my_table",
... schema="public",
... con=wr.db.get_redshift_temp_engine(cluster_identifier="...", user="...")
... )
Reading from Redshift from Glue Catalog Connections
>>> import awswrangler as wr
>>> df = wr.db.read_sql_table(
... table="my_table",
... schema="public",
... con=wr.catalog.get_engine(connection="...")
... )
"""
if schema is None:
sql: str = f"SELECT * FROM {table}"
else:
sql = f"SELECT * FROM {schema}.{table}"
return read_sql_query(
sql=sql, con=con, index_col=index_col, params=params, chunksize=chunksize, dtype=dtype, safe=safe
)
def get_redshift_temp_engine(
cluster_identifier: str,
user: str,
database: Optional[str] = None,
duration: int = 900,
auto_create: bool = True,
db_groups: Optional[List[str]] = None,
boto3_session: Optional[boto3.Session] = None,
**sqlalchemy_kwargs: Any,
) -> sqlalchemy.engine.Engine:
"""Get Glue connection details.
Parameters
----------
cluster_identifier : str
The unique identifier of a cluster.
This parameter is case sensitive.
user : str, optional
The name of a database user.
database : str, optional
Database name. If None, the default Database is used.
duration : int, optional
The number of seconds until the returned temporary password expires.
Constraint: minimum 900, maximum 3600.
Default: 900
auto_create : bool
Create a database user with the name specified for the user named in user if one does not exist.
db_groups: List[str], optinal
A list of the names of existing database groups that the user named in DbUser will join for the current session,
in addition to any group memberships for an existing user.
If not specified, a new user is added only to PUBLIC.
boto3_session : boto3.Session(), optional
Boto3 Session. The default boto3 session will be used if boto3_session receive None.
sqlalchemy_kwargs
keyword arguments forwarded to sqlalchemy.create_engine().
https://docs.sqlalchemy.org/en/13/core/engines.html
Returns
-------
sqlalchemy.engine.Engine
SQLAlchemy Engine.
Examples
--------
>>> import awswrangler as wr
>>> engine = wr.db.get_redshift_temp_engine('my_cluster', 'my_user')
"""
client_redshift: boto3.client = _utils.client(service_name="redshift", session=boto3_session)
args: Dict[str, Any] = {
"DbUser": user,
"ClusterIdentifier": cluster_identifier,
"DurationSeconds": duration,
"AutoCreate": auto_create,
}
if db_groups is not None:
args["DbGroups"] = db_groups
res: Dict[str, Any] = client_redshift.get_cluster_credentials(**args)
_user: str = _quote_plus(res["DbUser"])
password: str = _quote_plus(res["DbPassword"])
cluster: Dict[str, Any] = client_redshift.describe_clusters(ClusterIdentifier=cluster_identifier)["Clusters"][0]
host: str = cluster["Endpoint"]["Address"]
port: str = cluster["Endpoint"]["Port"]
if database is None:
database = cluster["DBName"]
conn_str: str = f"redshift+psycopg2://{_user}:{password}@{host}:{port}/{database}"
sqlalchemy_kwargs["executemany_mode"] = "values"
sqlalchemy_kwargs["executemany_values_page_size"] = 100_000
return sqlalchemy.create_engine(conn_str, **sqlalchemy_kwargs)
def get_engine(
db_type: str, host: str, port: int, database: str, user: str, password: str, **sqlalchemy_kwargs: Any
) -> sqlalchemy.engine.Engine:
"""Return a SQLAlchemy Engine from the given arguments.
Only Redshift, PostgreSQL and MySQL are supported.
Parameters
----------
db_type : str
Database type: "redshift", "mysql" or "postgresql".
host : str
Host address.
port : str
Port number.
database : str
Database name.
user : str
Username.
password : str
Password.
sqlalchemy_kwargs
keyword arguments forwarded to sqlalchemy.create_engine().
https://docs.sqlalchemy.org/en/13/core/engines.html
Returns
-------
sqlalchemy.engine.Engine
SQLAlchemy Engine.
Examples
--------
>>> import awswrangler as wr
>>> engine = wr.db.get_engine(
... db_type="postgresql",
... host="...",
... port=1234,
... database="...",
... user="...",
... password="..."
... )
"""
if db_type == "postgresql":
_utils.ensure_postgresql_casts()
if db_type in ("redshift", "postgresql"):
conn_str: str = f"{db_type}+psycopg2://{user}:{password}@{host}:{port}/{database}"
sqlalchemy_kwargs["executemany_mode"] = "values"
sqlalchemy_kwargs["executemany_values_page_size"] = 100_000
return sqlalchemy.create_engine(conn_str, **sqlalchemy_kwargs)
if db_type == "mysql":
conn_str = f"mysql+pymysql://{user}:{password}@{host}:{port}/{database}"
return sqlalchemy.create_engine(conn_str, **sqlalchemy_kwargs)
raise exceptions.InvalidDatabaseType(
f"{db_type} is not a valid Database type." f" Only Redshift, PostgreSQL and MySQL are supported."
)
def copy_to_redshift( # pylint: disable=too-many-arguments
df: pd.DataFrame,
path: str,
con: sqlalchemy.engine.Engine,
table: str,
schema: str,
iam_role: str,
index: bool = False,
dtype: Optional[Dict[str, str]] = None,
mode: str = "append",
diststyle: str = "AUTO",
distkey: Optional[str] = None,
sortstyle: str = "COMPOUND",
sortkey: Optional[List[str]] = None,
primary_keys: Optional[List[str]] = None,
varchar_lengths_default: int = 256,
varchar_lengths: Optional[Dict[str, int]] = None,
keep_files: bool = False,
use_threads: bool = True,
boto3_session: Optional[boto3.Session] = None,
s3_additional_kwargs: Optional[Dict[str, str]] = None,
max_rows_by_file: Optional[int] = 10_000_000,
) -> None:
"""Load Pandas DataFrame as a Table on Amazon Redshift using parquet files on S3 as stage.
This is a **HIGH** latency and **HIGH** throughput alternative to `wr.db.to_sql()` to load large
DataFrames into Amazon Redshift through the ** SQL COPY command**.
This strategy has more overhead and requires more IAM privileges
than the regular `wr.db.to_sql()` function, so it is only recommended
to inserting +1MM rows at once.
https://docs.aws.amazon.com/redshift/latest/dg/r_COPY.html
Note
----
If the table does not exist yet,
it will be automatically created for you
using the Parquet metadata to
infer the columns data types.
Note
----
In case of `use_threads=True` the number of threads
that will be spawned will be gotten from os.cpu_count().
Parameters
----------
df: pandas.DataFrame
Pandas DataFrame.
path : Union[str, List[str]]
S3 path to write stage files (e.g. s3://bucket_name/any_name/)
con : sqlalchemy.engine.Engine
SQLAlchemy Engine. Please use,
wr.db.get_engine(), wr.db.get_redshift_temp_engine() or wr.catalog.get_engine()
table : str
Table name
schema : str
Schema name
iam_role : str
AWS IAM role with the related permissions.
index : bool
True to store the DataFrame index in file, otherwise False to ignore it.
dtype: Dict[str, str], optional
Dictionary of columns names and Athena/Glue types to be casted.
Useful when you have columns with undetermined or mixed data types.
Only takes effect if dataset=True.
(e.g. {'col name': 'bigint', 'col2 name': 'int'})
mode : str
Append, overwrite or upsert.
diststyle : str
Redshift distribution styles. Must be in ["AUTO", "EVEN", "ALL", "KEY"].
https://docs.aws.amazon.com/redshift/latest/dg/t_Distributing_data.html
distkey : str, optional
Specifies a column name or positional number for the distribution key.
sortstyle : str
Sorting can be "COMPOUND" or "INTERLEAVED".
https://docs.aws.amazon.com/redshift/latest/dg/t_Sorting_data.html
sortkey : List[str], optional
List of columns to be sorted.
primary_keys : List[str], optional
Primary keys.
varchar_lengths_default : int
The size that will be set for all VARCHAR columns not specified with varchar_lengths.
varchar_lengths : Dict[str, int], optional
Dict of VARCHAR length by columns. (e.g. {"col1": 10, "col5": 200}).
keep_files : bool
Should keep the stage files?
use_threads : bool
True to enable concurrent requests, False to disable multiple threads.
If enabled os.cpu_count() will be used as the max number of threads.
boto3_session : boto3.Session(), optional
Boto3 Session. The default boto3 session will be used if boto3_session receive None.
s3_additional_kwargs:
Forward to botocore requests. Valid parameters: "ACL", "Metadata", "ServerSideEncryption", "StorageClass",
"SSECustomerAlgorithm", "SSECustomerKey", "SSEKMSKeyId", "SSEKMSEncryptionContext", "Tagging".
e.g. s3_additional_kwargs={'ServerSideEncryption': 'aws:kms', 'SSEKMSKeyId': 'YOUR_KMY_KEY_ARN'}
max_rows_by_file : int
Max number of rows in each file.
Default is None i.e. dont split the files.
(e.g. 33554432, 268435456)
Returns
-------
None
None.
Examples
--------
>>> import awswrangler as wr
>>> import pandas as pd
>>> wr.db.copy_to_redshift(
... df=pd.DataFrame({'col': [1, 2, 3]}),
... path="s3://bucket/my_parquet_files/",
... con=wr.catalog.get_engine(connection="my_glue_conn_name"),
... table="my_table",
... schema="public"
... iam_role="arn:aws:iam::XXX:role/XXX"
... )
"""
path = path if path.endswith("/") else f"{path}/"
session: boto3.Session = _utils.ensure_session(session=boto3_session)
paths: List[str] = s3.to_parquet(
df=df,
path=path,
index=index,
dataset=True,
mode="append",
dtype=dtype,
use_threads=use_threads,
boto3_session=session,
s3_additional_kwargs=s3_additional_kwargs,
max_rows_by_file=max_rows_by_file,
)["paths"]
s3.wait_objects_exist(paths=paths, use_threads=False, boto3_session=session)
copy_files_to_redshift(
path=paths,
manifest_directory=_utils.get_directory(path=path),
con=con,
table=table,
schema=schema,
iam_role=iam_role,
mode=mode,
diststyle=diststyle,
distkey=distkey,
sortstyle=sortstyle,
sortkey=sortkey,
primary_keys=primary_keys,
varchar_lengths_default=varchar_lengths_default,
varchar_lengths=varchar_lengths,
use_threads=use_threads,
boto3_session=session,
s3_additional_kwargs=s3_additional_kwargs,
)
if keep_files is False:
s3.delete_objects(path=paths, use_threads=use_threads, boto3_session=session)
def copy_files_to_redshift( # pylint: disable=too-many-locals,too-many-arguments
path: Union[str, List[str]],
manifest_directory: str,
con: sqlalchemy.engine.Engine,
table: str,
schema: str,
iam_role: str,
parquet_infer_sampling: float = 1.0,
mode: str = "append",
diststyle: str = "AUTO",
distkey: Optional[str] = None,
sortstyle: str = "COMPOUND",
sortkey: Optional[List[str]] = None,
primary_keys: Optional[List[str]] = None,
varchar_lengths_default: int = 256,
varchar_lengths: Optional[Dict[str, int]] = None,
use_threads: bool = True,
boto3_session: Optional[boto3.Session] = None,
s3_additional_kwargs: Optional[Dict[str, str]] = None,
) -> None:
"""Load Parquet files from S3 to a Table on Amazon Redshift (Through COPY command).
https://docs.aws.amazon.com/redshift/latest/dg/r_COPY.html
This function accepts Unix shell-style wildcards in the path argument.
* (matches everything), ? (matches any single character),
[seq] (matches any character in seq), [!seq] (matches any character not in seq).
Note
----
If the table does not exist yet,
it will be automatically created for you
using the Parquet metadata to
infer the columns data types.
Note
----
In case of `use_threads=True` the number of threads
that will be spawned will be gotten from os.cpu_count().
Parameters
----------
path : Union[str, List[str]]
S3 prefix (accepts Unix shell-style wildcards)
(e.g. s3://bucket/prefix) or list of S3 objects paths (e.g. [s3://bucket/key0, s3://bucket/key1]).
manifest_directory : str
S3 prefix (e.g. s3://bucket/prefix)
con : sqlalchemy.engine.Engine
SQLAlchemy Engine. Please use,
wr.db.get_engine(), wr.db.get_redshift_temp_engine() or wr.catalog.get_engine()
table : str
Table name
schema : str
Schema name
iam_role : str
AWS IAM role with the related permissions.
parquet_infer_sampling : float
Random sample ratio of files that will have the metadata inspected.
Must be `0.0 < sampling <= 1.0`.
The higher, the more accurate.
The lower, the faster.
mode : str
Append, overwrite or upsert.
diststyle : str
Redshift distribution styles. Must be in ["AUTO", "EVEN", "ALL", "KEY"].
https://docs.aws.amazon.com/redshift/latest/dg/t_Distributing_data.html
distkey : str, optional
Specifies a column name or positional number for the distribution key.
sortstyle : str
Sorting can be "COMPOUND" or "INTERLEAVED".
https://docs.aws.amazon.com/redshift/latest/dg/t_Sorting_data.html
sortkey : List[str], optional
List of columns to be sorted.
primary_keys : List[str], optional
Primary keys.
varchar_lengths_default : int
The size that will be set for all VARCHAR columns not specified with varchar_lengths.
varchar_lengths : Dict[str, int], optional
Dict of VARCHAR length by columns. (e.g. {"col1": 10, "col5": 200}).
use_threads : bool
True to enable concurrent requests, False to disable multiple threads.
If enabled os.cpu_count() will be used as the max number of threads.
boto3_session : boto3.Session(), optional
Boto3 Session. The default boto3 session will be used if boto3_session receive None.
s3_additional_kwargs:
Forward to botocore requests. Valid parameters: "ACL", "Metadata", "ServerSideEncryption", "StorageClass",
"SSECustomerAlgorithm", "SSECustomerKey", "SSEKMSKeyId", "SSEKMSEncryptionContext", "Tagging".
e.g. s3_additional_kwargs={'ServerSideEncryption': 'aws:kms', 'SSEKMSKeyId': 'YOUR_KMY_KEY_ARN'}
Returns
-------
None
None.
Examples
--------
>>> import awswrangler as wr
>>> wr.db.copy_files_to_redshift(
... path="s3://bucket/my_parquet_files/",
... con=wr.catalog.get_engine(connection="my_glue_conn_name"),
... table="my_table",
... schema="public"
... iam_role="arn:aws:iam::XXX:role/XXX"
... )
"""
_varchar_lengths: Dict[str, int] = {} if varchar_lengths is None else varchar_lengths
session: boto3.Session = _utils.ensure_session(session=boto3_session)
paths: List[str] = _path2list(path=path, boto3_session=session) # pylint: disable=protected-access
manifest_directory = manifest_directory if manifest_directory.endswith("/") else f"{manifest_directory}/"
manifest_path: str = f"{manifest_directory}manifest.json"
write_redshift_copy_manifest(
manifest_path=manifest_path,
paths=paths,
use_threads=use_threads,
boto3_session=session,
s3_additional_kwargs=s3_additional_kwargs,
)
s3.wait_objects_exist(paths=paths + [manifest_path], use_threads=False, boto3_session=session)
athena_types, _ = s3.read_parquet_metadata(
path=paths, sampling=parquet_infer_sampling, dataset=False, use_threads=use_threads, boto3_session=session
)
_logger.debug("athena_types: %s", athena_types)
redshift_types: Dict[str, str] = {}
for col_name, col_type in athena_types.items():
length: int = _varchar_lengths[col_name] if col_name in _varchar_lengths else varchar_lengths_default
redshift_types[col_name] = _data_types.athena2redshift(dtype=col_type, varchar_length=length)
with con.begin() as _con:
created_table, created_schema = _rs_create_table(
con=_con,
table=table,
schema=schema,
redshift_types=redshift_types,
mode=mode,
diststyle=diststyle,
sortstyle=sortstyle,
distkey=distkey,
sortkey=sortkey,
primary_keys=primary_keys,
)
_rs_copy(
con=_con,
table=created_table,
schema=created_schema,
manifest_path=manifest_path,
iam_role=iam_role,
num_files=len(paths),
)
if table != created_table: # upsert
_rs_upsert(con=_con, schema=schema, table=table, temp_table=created_table, primary_keys=primary_keys)
s3.delete_objects(path=[manifest_path], use_threads=use_threads, boto3_session=session)
def write_redshift_copy_manifest(
manifest_path: str,
paths: List[str],
use_threads: bool = True,
boto3_session: Optional[boto3.Session] = None,
s3_additional_kwargs: Optional[Dict[str, str]] = None,
) -> Dict[str, List[Dict[str, Union[str, bool, Dict[str, int]]]]]:
"""Write Redshift copy manifest and return its structure.
Only Parquet files are supported.
Note
----
In case of `use_threads=True` the number of threads
that will be spawned will be gotten from os.cpu_count().
Parameters
----------
manifest_path : str
Amazon S3 manifest path (e.g. s3://...)
paths: List[str]
List of S3 paths (Parquet Files) to be copied.
use_threads : bool
True to enable concurrent requests, False to disable multiple threads.
If enabled os.cpu_count() will be used as the max number of threads.
boto3_session : boto3.Session(), optional
Boto3 Session. The default boto3 session will be used if boto3_session receive None.
s3_additional_kwargs:
Forward to botocore requests. Valid parameters: "ACL", "Metadata", "ServerSideEncryption", "StorageClass",
"SSECustomerAlgorithm", "SSECustomerKey", "SSEKMSKeyId", "SSEKMSEncryptionContext", "Tagging".
e.g. s3_additional_kwargs={'ServerSideEncryption': 'aws:kms', 'SSEKMSKeyId': 'YOUR_KMY_KEY_ARN'}
Returns
-------
Dict[str, List[Dict[str, Union[str, bool, Dict[str, int]]]]]
Manifest content.
Examples
--------
Copying two files to Redshift cluster.
>>> import awswrangler as wr
>>> wr.db.write_redshift_copy_manifest(
... path="s3://bucket/my.manifest",
... paths=["s3://...parquet", "s3://...parquet"]
... )
"""
session: boto3.Session = _utils.ensure_session(session=boto3_session)
objects_sizes: Dict[str, Optional[int]] = s3.size_objects(
path=paths, use_threads=use_threads, boto3_session=session
)
manifest: Dict[str, List[Dict[str, Union[str, bool, Dict[str, int]]]]] = {"entries": []}
path: str
size: Optional[int]
for path, size in objects_sizes.items():
if size is not None:
entry: Dict[str, Union[str, bool, Dict[str, int]]] = {
"url": path,
"mandatory": True,
"meta": {"content_length": size},
}
manifest["entries"].append(entry)
payload: str = json.dumps(manifest)
bucket: str
bucket, key = _utils.parse_path(manifest_path)
additional_kwargs: Dict[str, str] = {} if s3_additional_kwargs is None else s3_additional_kwargs
_logger.debug("payload: %s", payload)
client_s3: boto3.client = _utils.client(service_name="s3", session=session)
_logger.debug("bucket: %s", bucket)
_logger.debug("key: %s", key)
client_s3.put_object(Body=payload, Bucket=bucket, Key=key, **additional_kwargs)
return manifest
def unload_redshift(
sql: str,
path: str,
con: sqlalchemy.engine.Engine,
iam_role: str,
region: Optional[str] = None,
max_file_size: Optional[float] = None,
kms_key_id: Optional[str] = None,
categories: Optional[List[str]] = None,
chunked: Union[bool, int] = False,
keep_files: bool = False,
use_threads: bool = True,
boto3_session: Optional[boto3.Session] = None,
s3_additional_kwargs: Optional[Dict[str, str]] = None,
) -> Union[pd.DataFrame, Iterator[pd.DataFrame]]:
"""Load Pandas DataFrame from a Amazon Redshift query result using Parquet files on s3 as stage.
This is a **HIGH** latency and **HIGH** throughput alternative to
`wr.db.read_sql_query()`/`wr.db.read_sql_table()` to extract large
Amazon Redshift data into a Pandas DataFrames through the **UNLOAD command**.
This strategy has more overhead and requires more IAM privileges
than the regular `wr.db.read_sql_query()`/`wr.db.read_sql_table()` function,
so it is only recommended to fetch +1MM rows at once.
https://docs.aws.amazon.com/redshift/latest/dg/r_UNLOAD.html
Note
----
``Batching`` (`chunked` argument) (Memory Friendly):
Will anable the function to return a Iterable of DataFrames instead of a regular DataFrame.
There are two batching strategies on Wrangler:
- If **chunked=True**, a new DataFrame will be returned for each file in your path/dataset.
- If **chunked=INTEGER**, Wrangler will iterate on the data by number of rows igual the received INTEGER.
`P.S.` `chunked=True` if faster and uses less memory while `chunked=INTEGER` is more precise
in number of rows for each Dataframe.
Note
----
In case of `use_threads=True` the number of threads
that will be spawned will be gotten from os.cpu_count().
Parameters
----------
sql: str
SQL query.
path : Union[str, List[str]]
S3 path to write stage files (e.g. s3://bucket_name/any_name/)
con : sqlalchemy.engine.Engine
SQLAlchemy Engine. Please use,
wr.db.get_engine(), wr.db.get_redshift_temp_engine() or wr.catalog.get_engine()
iam_role : str
AWS IAM role with the related permissions.
region : str, optional
Specifies the AWS Region where the target Amazon S3 bucket is located.
REGION is required for UNLOAD to an Amazon S3 bucket that isn't in the
same AWS Region as the Amazon Redshift cluster. By default, UNLOAD
assumes that the target Amazon S3 bucket is located in the same AWS
Region as the Amazon Redshift cluster.
max_file_size : float, optional
Specifies the maximum size (MB) of files that UNLOAD creates in Amazon S3.
Specify a decimal value between 5.0 MB and 6200.0 MB. If None, the default
maximum file size is 6200.0 MB.
kms_key_id : str, optional
Specifies the key ID for an AWS Key Management Service (AWS KMS) key to be
used to encrypt data files on Amazon S3.
categories: List[str], optional
List of columns names that should be returned as pandas.Categorical.
Recommended for memory restricted environments.
keep_files : bool
Should keep the stage files?
chunked : Union[int, bool]
If passed will split the data in a Iterable of DataFrames (Memory friendly).
If `True` wrangler will iterate on the data by files in the most efficient way without guarantee of chunksize.
If an `INTEGER` is passed Wrangler will iterate on the data by number of rows igual the received INTEGER.
use_threads : bool
True to enable concurrent requests, False to disable multiple threads.
If enabled os.cpu_count() will be used as the max number of threads.
boto3_session : boto3.Session(), optional
Boto3 Session. The default boto3 session will be used if boto3_session receive None.
s3_additional_kwargs:
Forward to botocore requests, only "SSECustomerAlgorithm" and "SSECustomerKey" arguments will be considered.
Returns
-------
Union[pandas.DataFrame, Iterator[pandas.DataFrame]]
Result as Pandas DataFrame(s).
Examples
--------
>>> import awswrangler as wr
>>> import pandas as pd
>>> df = wr.db.unload_redshift(
... sql="SELECT * FROM public.mytable",
... path="s3://bucket/extracted_parquet_files/",
... con=wr.catalog.get_engine(connection="my_glue_connection"),
... iam_role="arn:aws:iam::XXX:role/XXX"
... )
"""
session: boto3.Session = _utils.ensure_session(session=boto3_session)
paths: List[str] = unload_redshift_to_files(
sql=sql,
path=path,
con=con,
iam_role=iam_role,
region=region,
max_file_size=max_file_size,
kms_key_id=kms_key_id,
use_threads=use_threads,
boto3_session=session,
)
s3.wait_objects_exist(paths=paths, use_threads=False, boto3_session=session)
if chunked is False:
if not paths:
return pd.DataFrame()
df: pd.DataFrame = s3.read_parquet(
path=paths,
categories=categories,
chunked=chunked,
dataset=False,
use_threads=use_threads,
boto3_session=session,
s3_additional_kwargs=s3_additional_kwargs,
)
if keep_files is False:
s3.delete_objects(path=paths, use_threads=use_threads, boto3_session=session)
return df
if not paths:
return _utils.empty_generator()
return _read_parquet_iterator(
paths=paths,
categories=categories,
chunked=chunked,
use_threads=use_threads,
boto3_session=session,
s3_additional_kwargs=s3_additional_kwargs,
keep_files=keep_files,
)
def unload_redshift_to_files(
sql: str,
path: str,
con: sqlalchemy.engine.Engine,
iam_role: str,
region: Optional[str] = None,
max_file_size: Optional[float] = None,
kms_key_id: Optional[str] = None,
use_threads: bool = True,
manifest: bool = False,
partition_cols: Optional[List[str]] = None,
boto3_session: Optional[boto3.Session] = None,
) -> List[str]:
"""Unload Parquet files from a Amazon Redshift query result to parquet files on s3 (Through UNLOAD command).
https://docs.aws.amazon.com/redshift/latest/dg/r_UNLOAD.html
Note
----
In case of `use_threads=True` the number of threads
that will be spawned will be gotten from os.cpu_count().
Parameters
----------
sql: str
SQL query.
path : Union[str, List[str]]
S3 path to write stage files (e.g. s3://bucket_name/any_name/)
con : sqlalchemy.engine.Engine
SQLAlchemy Engine. Please use,
wr.db.get_engine(), wr.db.get_redshift_temp_engine() or wr.catalog.get_engine()
iam_role : str
AWS IAM role with the related permissions.
region : str, optional
Specifies the AWS Region where the target Amazon S3 bucket is located.
REGION is required for UNLOAD to an Amazon S3 bucket that isn't in the
same AWS Region as the Amazon Redshift cluster. By default, UNLOAD
assumes that the target Amazon S3 bucket is located in the same AWS
Region as the Amazon Redshift cluster.
max_file_size : float, optional
Specifies the maximum size (MB) of files that UNLOAD creates in Amazon S3.
Specify a decimal value between 5.0 MB and 6200.0 MB. If None, the default
maximum file size is 6200.0 MB.
kms_key_id : str, optional
Specifies the key ID for an AWS Key Management Service (AWS KMS) key to be
used to encrypt data files on Amazon S3.
use_threads : bool
True to enable concurrent requests, False to disable multiple threads.
If enabled os.cpu_count() will be used as the max number of threads.
manifest : bool
Unload a manifest file on S3.
partition_cols: List[str], optional
Specifies the partition keys for the unload operation.
boto3_session : boto3.Session(), optional
Boto3 Session. The default boto3 session will be used if boto3_session receive None.
Returns
-------
List[str]
Paths list with all unloaded files.
Examples
--------
>>> import awswrangler as wr
>>> paths = wr.db.unload_redshift_to_files(
... sql="SELECT * FROM public.mytable",
... path="s3://bucket/extracted_parquet_files/",
... con=wr.catalog.get_engine(connection="my_glue_connection"),
... iam_role="arn:aws:iam::XXX:role/XXX"
... )
"""
path = path if path.endswith("/") else f"{path}/"
session: boto3.Session = _utils.ensure_session(session=boto3_session)
s3.delete_objects(path=path, use_threads=use_threads, boto3_session=session)
with con.connect() as _con:
partition_str: str = f"\nPARTITION BY ({','.join(partition_cols)})" if partition_cols else ""
manifest_str: str = "\nmanifest" if manifest is True else ""
region_str: str = f"\nREGION AS '{region}'" if region is not None else ""
max_file_size_str: str = f"\nMAXFILESIZE AS {max_file_size} MB" if max_file_size is not None else ""
kms_key_id_str: str = f"\nKMS_KEY_ID '{kms_key_id}'" if kms_key_id is not None else ""
sql = (
f"UNLOAD ('{sql}')\n"
f"TO '{path}'\n"
f"IAM_ROLE '{iam_role}'\n"
"ALLOWOVERWRITE\n"
"PARALLEL ON\n"
"FORMAT PARQUET\n"
"ENCRYPTED"
f"{kms_key_id_str}"
f"{partition_str}"
f"{region_str}"
f"{max_file_size_str}"
f"{manifest_str};"
)
_logger.debug("sql: \n%s", sql)
_con.execute(sql)
sql = "SELECT pg_last_query_id() AS query_id"
query_id: int = _con.execute(sql).fetchall()[0][0]
sql = f"SELECT path FROM STL_UNLOAD_LOG WHERE query={query_id};"
paths = [x[0].replace(" ", "") for x in _con.execute(sql).fetchall()]
_logger.debug("paths: %s", paths)
return paths
|
function init() {
em.setProperty("state", "0");
em.setProperty("leader", "true");
}
function setup(eim, leaderid) {
em.setProperty("state", "1");
em.setProperty("leader", "true");
var eim = em.newInstance("ZakumBattle" + leaderid);
eim.setProperty("zakSummoned", "0");
eim.setInstanceMap(280030000).resetFully();
eim.startEventTimer(60000 * 600);
return eim;
}
function playerEntry(eim, player) {
var map = eim.getMapInstance(0);
player.changeMap(map, map.getPortal(0));
}
function playerRevive(eim, player) {
return false;
}
function changedMap(eim, player, mapid) {
if (mapid != 280030000) {
eim.unregisterPlayer(player);
if (eim.disposeIfPlayerBelow(0, 0)) {
em.setProperty("leader", "true");
em.setProperty("state", "0");
}
}
}
function playerDisconnected(eim, player) {
return 0;
}
function scheduledTimeout(eim) {
end(eim);
}
function monsterValue(eim, mobId) {
return 1;
}
function playerExit(eim, player) {
eim.unregisterPlayer(player);
if (eim.disposeIfPlayerBelow(0, 0)) {
em.setProperty("leader", "true");
em.setProperty("state", "0");
}
}
function end(eim) {
eim.disposeIfPlayerBelow(100, 211042300);
em.setProperty("state", "0");
em.setProperty("leader", "true");
em.setProperty("zakSummoned", "0");
}
function clearPQ(eim) {
end(eim);
}
function allMonstersDead(eim) {
if (em.getProperty("state").equals("1")) {
em.setProperty("state", "2");
} else if (em.getProperty("state").equals("2")) {
em.setProperty("state", "3");
}
}
function leftParty (eim, player) {}
function disbandParty (eim) {}
function playerDead(eim, player) {}
function cancelSchedule() {}
|
from django.db import models
# Create your models here.
class URL(models.Model):
url = models.URLField(max_length=1000)
short_url = models.CharField(max_length=1000, blank=True)
number_of_view = models.IntegerField(default=0)
owner = models.ForeignKey('auth.User', on_delete=models.CASCADE)
def __str__(self):
return self.url
|
import ssl
import pytest
from celery_exporter.utils import get_transport_scheme, generate_broker_use_ssl
@pytest.mark.parametrize("brokers", [("redis://foo", "redis"), ("amqp://bar", "amqp")])
def test_get_transport_scheme(brokers):
assert get_transport_scheme(brokers[0]) == brokers[1]
def test_generate_broker_use_ssl_no_ssl():
assert (
generate_broker_use_ssl(
False, "redis", "CERT_NONE", "path/ca.pem", "path/cert.pem", "path/key.pem"
)
== None
)
def test_generate_broker_use_ssl_exception():
with pytest.raises(ValueError):
generate_broker_use_ssl(
True, "wrong", "CERT_NONE", "path/ca.pem", "path/cert.pem", "path/key.pem"
)
with pytest.raises(ValueError):
generate_broker_use_ssl(
True,
"redis",
"WRONG_VERIFY",
"path/ca.pem",
"path/cert.pem",
"path/key.pem",
)
def test_generate_broker_use_ssl():
assert generate_broker_use_ssl(
True, "redis", "CERT_NONE", "path/ca.pem", "path/cert.pem", "path/key.pem"
) == {
"ssl_keyfile": "path/key.pem",
"ssl_certfile": "path/cert.pem",
"ssl_ca_certs": "path/ca.pem",
"ssl_cert_reqs": ssl.CERT_NONE,
}
assert generate_broker_use_ssl(
True, "amqp", "CERT_OPTIONAL", "path/ca.pem", "path/cert.pem", "path/key.pem"
) == {
"keyfile": "path/key.pem",
"certfile": "path/cert.pem",
"ca_certs": "path/ca.pem",
"cert_reqs": ssl.CERT_OPTIONAL,
}
assert generate_broker_use_ssl(
True, "amqp", "CERT_REQUIRED", "path/ca.pem", "path/cert.pem", "path/key.pem"
) == {
"keyfile": "path/key.pem",
"certfile": "path/cert.pem",
"ca_certs": "path/ca.pem",
"cert_reqs": ssl.CERT_REQUIRED,
}
|
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("cases", "0001_initial"), ("events", "0001_initial")]
operations = [
migrations.AddField(
model_name="alarm",
name="case",
field=models.ForeignKey(
on_delete=models.CASCADE, default=1, to="cases.Case"
),
preserve_default=False,
),
migrations.AddField(
model_name="event",
name="case",
field=models.ForeignKey(
on_delete=models.CASCADE, default=1, to="cases.Case"
),
preserve_default=False,
),
]
|
// Copyright 2021, University of Colorado Boulder
// Auto-generated by modulifyFontAwesomeIcons.js, please do not modify directly.
import Shape from '../../../../kite/js/Shape.js';
import korvueString from './korvueString.js';
export default new Shape( korvueString );
|
REPETITIONS = 10 ** 4
|
import Prompt from './Prompt'
export default Prompt
|
# Licensed to Modin Development Team under one or more contributor license agreements.
# See the NOTICE file distributed with this work for additional information regarding
# copyright ownership. The Modin Development Team licenses this file to you under the
# Apache License, Version 2.0 (the "License"); you may not use this file except in
# compliance with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under
# the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific language
# governing permissions and limitations under the License.
import abc
from pandas.core.dtypes.common import (
is_list_like,
get_dtype,
is_float_dtype,
is_integer_dtype,
is_numeric_dtype,
is_string_like_dtype,
is_categorical_dtype,
is_datetime64_any_dtype,
is_bool_dtype,
)
import numpy as np
def _get_common_dtype(lhs_dtype, rhs_dtype):
if lhs_dtype == rhs_dtype:
return lhs_dtype
if is_float_dtype(lhs_dtype) or is_float_dtype(rhs_dtype):
return get_dtype(float)
assert is_integer_dtype(lhs_dtype) and is_integer_dtype(rhs_dtype)
return get_dtype(int)
_aggs_preserving_numeric_type = {"sum", "min", "max"}
_aggs_with_int_result = {"count", "size"}
_aggs_with_float_result = {"mean", "std", "skew"}
def _agg_dtype(agg, dtype):
if agg in _aggs_preserving_numeric_type:
return dtype
elif agg in _aggs_with_int_result:
return get_dtype(int)
elif agg in _aggs_with_float_result:
return get_dtype(float)
else:
raise NotImplementedError(f"unsupported aggreagte {agg}")
_cmp_ops = {"eq", "ge", "gt", "le", "lt", "ne"}
def is_cmp_op(op):
return op in _cmp_ops
class BaseExpr(abc.ABC):
binary_operations = {
"add": "+",
"sub": "-",
"mul": "*",
"mod": "MOD",
"floordiv": "/",
"truediv": "/",
"pow": "POWER",
"eq": "=",
"ge": ">=",
"gt": ">",
"le": "<=",
"lt": "<",
"ne": "<>",
}
preserve_dtype_math_ops = {"add", "sub", "mul", "mod", "floordiv", "pow"}
promote_to_float_math_ops = {"truediv"}
def eq(self, other):
if not isinstance(other, BaseExpr):
other = LiteralExpr(other)
new_expr = OpExpr("=", [self, other], get_dtype(bool))
return new_expr
def le(self, other):
if not isinstance(other, BaseExpr):
other = LiteralExpr(other)
new_expr = OpExpr("<=", [self, other], get_dtype(bool))
return new_expr
def cast(self, res_type):
new_expr = OpExpr("CAST", [self], res_type)
return new_expr
def is_null(self):
new_expr = OpExpr("IS NULL", [self], get_dtype(bool))
return new_expr
def is_not_null(self):
new_expr = OpExpr("IS NOT NULL", [self], get_dtype(bool))
return new_expr
def bin_op(self, other, op_name):
if op_name not in self.binary_operations:
raise NotImplementedError(f"unsupported binary operation {op_name}")
if is_cmp_op(op_name):
return self._cmp_op(other, op_name)
# True division may require prior cast to float to avoid integer division
if op_name == "truediv":
if is_integer_dtype(self._dtype) and is_integer_dtype(other._dtype):
other = other.cast(get_dtype(float))
res_type = self._get_bin_op_res_type(op_name, self._dtype, other._dtype)
new_expr = OpExpr(self.binary_operations[op_name], [self, other], res_type)
# Floor division may require additional FLOOR expr.
if op_name == "floordiv" and not is_integer_dtype(res_type):
return new_expr.floor()
return new_expr
def add(self, other):
return self.bin_op(other, "add")
def sub(self, other):
return self.bin_op(other, "sub")
def mul(self, other):
return self.bin_op(other, "mul")
def mod(self, other):
return self.bin_op(other, "mod")
def truediv(self, other):
return self.bin_op(other, "truediv")
def floordiv(self, other):
return self.bin_op(other, "floordiv")
def pow(self, other):
return self.bin_op(other, "pow")
def floor(self):
return OpExpr("FLOOR", [self], get_dtype(int))
def _cmp_op(self, other, op_name):
lhs_dtype_class = self._get_dtype_cmp_class(self._dtype)
rhs_dtype_class = self._get_dtype_cmp_class(other._dtype)
res_dtype = get_dtype(bool)
# In OmniSci comparison with NULL always results in NULL,
# but in Pandas it is True for 'ne' comparison and False
# for others.
# Also Pandas allow 'eq' and 'ne' comparison for values
# of incompatible types which doesn't work in OmniSci.
if lhs_dtype_class != rhs_dtype_class:
if op_name == "eq" or op_name == "ne":
return LiteralExpr(op_name == "ne")
else:
raise TypeError(
f"Invalid comparison between {self._dtype} and {other._dtype}"
)
else:
cmp = OpExpr(self.binary_operations[op_name], [self, other], res_dtype)
return build_if_then_else(
self.is_null(), LiteralExpr(op_name == "ne"), cmp, res_dtype
)
@staticmethod
def _get_dtype_cmp_class(dtype):
if is_numeric_dtype(dtype) or is_bool_dtype(dtype):
return "numeric"
if is_string_like_dtype(dtype) or is_categorical_dtype(dtype):
return "string"
if is_datetime64_any_dtype(dtype):
return "datetime"
return "other"
def _get_bin_op_res_type(self, op_name, lhs_dtype, rhs_dtype):
if op_name in self.preserve_dtype_math_ops:
return _get_common_dtype(lhs_dtype, rhs_dtype)
elif op_name in self.promote_to_float_math_ops:
return get_dtype(float)
elif is_cmp_op(op_name):
return get_dtype(bool)
else:
raise NotImplementedError(f"unsupported binary operation {op_name}")
@abc.abstractmethod
def copy(self):
pass
def collect_frames(self, frames):
"""Return the first modin frame referenced in expression."""
for op in getattr(self, "operands", []):
op.collect_frames(frames)
# currently we translate only exprs with a single input frame
def translate_input(self, mapper):
if hasattr(self, "operands"):
res = self.copy()
for i in range(0, len(self.operands)):
res.operands[i] = res.operands[i].translate_input(mapper)
return res
return self._translate_input(mapper)
def _translate_input(self, mapper):
return self
class InputRefExpr(BaseExpr):
def __init__(self, frame, col, dtype):
self.modin_frame = frame
self.column = col
self._dtype = dtype
def copy(self):
return InputRefExpr(self.modin_frame, self.column, self._dtype)
def collect_frames(self, frames):
frames.add(self.modin_frame)
def _translate_input(self, mapper):
return mapper.translate(self)
def __repr__(self):
return f"{self.modin_frame.id_str()}.{self.column}[{self._dtype}]"
class LiteralExpr(BaseExpr):
def __init__(self, val):
assert val is None or isinstance(
val, (int, float, bool, str, np.int8, np.int16, np.int32, np.int64)
), f"unsupported literal value {val} of type {type(val)}"
self.val = val
if val is None:
self._dtype = get_dtype(float)
else:
self._dtype = get_dtype(type(val))
def copy(self):
return LiteralExpr(self.val)
def __repr__(self):
return f"{self.val}[{self._dtype}]"
class OpExpr(BaseExpr):
def __init__(self, op, operands, dtype):
self.op = op
self.operands = operands
self._dtype = dtype
def copy(self):
return OpExpr(self.op, self.operands.copy(), self._dtype)
def __repr__(self):
if len(self.operands) == 1:
return f"({self.op} {self.operands[0]} [{self._dtype}])"
return f"({self.op} {self.operands} [{self._dtype}])"
class AggregateExpr(BaseExpr):
def __init__(self, agg, op, distinct=False, dtype=None):
self.agg = agg
self.operands = [op]
self._dtype = dtype if dtype else _agg_dtype(agg, op._dtype if op else None)
assert self._dtype is not None
self.distinct = distinct
def copy(self):
return AggregateExpr(self.agg, self.operands[0], self.distinct, self._dtype)
def __repr__(self):
if len(self.operands) == 1:
return f"{self.agg}({self.operands[0]})[{self._dtype}]"
return f"{self.agg}({self.operands})[{self._dtype}]"
def build_row_idx_filter_expr(row_idx, row_col):
"""Build calcite expression to filter rows by rowid.
Parameters
----------
row_idx
The row numeric indices to select
row_col
InputRefExpr referencing proper rowid column to filter by
Returns
-------
CalciteBaseExpr
A BaseExpr implementing filter condition
"""
if not is_list_like(row_idx):
return row_col.eq(row_idx)
exprs = []
for idx in row_idx:
exprs.append(row_col.eq(idx))
res = OpExpr("OR", exprs, get_dtype(bool))
return res
def build_if_then_else(cond, then_val, else_val, res_type):
return OpExpr("CASE", [cond, then_val, else_val], res_type)
def build_dt_expr(dt_operation, col_expr):
operation = LiteralExpr(dt_operation)
res = OpExpr("PG_EXTRACT", [operation, col_expr], get_dtype(int))
return res
|
/* global describe,it */
var getSlug = require('../lib/speakingurl');
describe('getSlug languages', function () {
'use strict';
it('should replace language specific symbols', function (done) {
var symbolMap = {
'ar': {
'∆': 'delta',
'∞': 'la-nihaya',
'♥': 'hob',
'&': 'wa',
'|': 'aw',
'<': 'aqal-men',
'>': 'akbar-men',
'∑': 'majmou',
'¤': 'omla'
},
'cz': {
'∆': 'delta',
'∞': 'nekonecno',
'♥': 'laska',
'&': 'a',
'|': 'nebo',
'<': 'mene jako',
'>': 'vice jako',
'∑': 'soucet',
'¤': 'mena'
},
'de': {
'∆': 'delta',
'∞': 'unendlich',
'♥': 'Liebe',
'&': 'und',
'|': 'oder',
'<': 'kleiner als',
'>': 'groesser als',
'∑': 'Summe von',
'¤': 'Waehrung'
},
'en': {
'∆': 'delta',
'∞': 'infinity',
'♥': 'love',
'&': 'and',
'|': 'or',
'<': 'less than',
'>': 'greater than',
'∑': 'sum',
'¤': 'currency'
},
'es': {
'∆': 'delta',
'∞': 'infinito',
'♥': 'amor',
'&': 'y',
'|': 'u',
'<': 'menos que',
'>': 'mas que',
'∑': 'suma de los',
'¤': 'moneda'
},
'fr': {
'∆': 'delta',
'∞': 'infiniment',
'♥': 'Amour',
'&': 'et',
'|': 'ou',
'<': 'moins que',
'>': 'superieure a',
'∑': 'somme des',
'¤': 'monnaie'
},
'hu': {
'∆': 'delta',
'∞': 'vegtelen',
'♥': 'szerelem',
'&': 'es',
'|': 'vagy',
'<': 'kisebb mint',
'>': 'nagyobb mint',
'∑': 'szumma',
'¤': 'penznem'
},
'my': {
'∆': 'kwahkhyaet',
'∞': 'asaonasme',
'♥': 'akhyait',
'&': 'nhin',
'|': 'tho',
'<': 'ngethaw',
'>': 'kyithaw',
'∑': 'paungld',
'¤': 'ngwekye'
},
'nl': {
'∆': 'delta',
'∞': 'oneindig',
'♥': 'liefde',
'&': 'en',
'|': 'of',
'<': 'kleiner dan',
'>': 'groter dan',
'∑': 'som',
'¤': 'valuta'
},
'it': {
'∆': 'delta',
'∞': 'infinito',
'♥': 'amore',
'&': 'e',
'|': 'o',
'<': 'minore di',
'>': 'maggiore di',
'∑': 'somma',
'¤': 'moneta'
},
'pl': {
'∆': 'delta',
'∞': 'nieskonczonosc',
'♥': 'milosc',
'&': 'i',
'|': 'lub',
'<': 'mniejsze niz',
'>': 'wieksze niz',
'∑': 'suma',
'¤': 'waluta'
},
'pt': {
'∆': 'delta',
'∞': 'infinito',
'♥': 'amor',
'&': 'e',
'|': 'ou',
'<': 'menor que',
'>': 'maior que',
'∑': 'soma',
'¤': 'moeda'
},
'ru': {
'∆': 'delta',
'∞': 'beskonechno',
'♥': 'lubov',
'&': 'i',
'|': 'ili',
'<': 'menshe',
'>': 'bolshe',
'∑': 'summa',
'¤': 'valjuta'
},
'sk': {
'∆': 'delta',
'∞': 'nekonecno',
'♥': 'laska',
'&': 'a',
'|': 'alebo',
'<': 'menej ako',
'>': 'viac ako',
'∑': 'sucet',
'¤': 'mena'
},
'tr': {
'∆': 'delta',
'∞': 'sonsuzluk',
'♥': 'ask',
'&': 've',
'|': 'veya',
'<': 'kucuktur',
'>': 'buyuktur',
'∑': 'toplam',
'¤': 'para birimi'
},
'vn': {
'∆': 'delta',
'∞': 'vo cuc',
'♥': 'yeu',
'&': 'va',
'|': 'hoac',
'<': 'nho hon',
'>': 'lon hon',
'∑': 'tong',
'¤': 'tien te'
}
};
Object.keys(symbolMap)
.forEach(function (l) {
// console.log('\ncheck language: ' + l);
Object.keys(symbolMap[l])
.forEach(function (s) {
var k = symbolMap[l][s];
// console.log('check symbol: ' + s);
getSlug('Foo ' + s + ' Bar', {
lang: l,
maintainCase: true
})
.should.eql('Foo-' + getSlug(k, {
maintainCase: true
}) + '-Bar');
getSlug('Foo ' + s + ' Bar', {
lang: l
})
.should.eql('foo-' + getSlug(k) + '-bar');
});
});
getSlug('EN Foo & Bar ')
.should.eql('en-foo-and-bar');
getSlug('EN Foo & Bar ', {
lang: "en"
})
.should.eql('en-foo-and-bar');
getSlug('de Foo & Bar ', {
lang: "de"
})
.should.eql('de-foo-und-bar');
getSlug('True Foo & Bar ', {
lang: true
})
.should.eql('true-foo-and-bar');
getSlug('False Foo & Bar ', {
lang: false
})
.should.eql('false-foo-bar');
getSlug('False Foo & Bar ', {
lang: false,
symbols: true
})
.should.eql('false-foo-bar');
getSlug('xx Foo & Bar ', {
lang: "xx"
})
.should.eql('xx-foo-and-bar');
getSlug('obj Foo & Bar ', {
lang: {}
})
.should.eql('obj-foo-and-bar');
getSlug('array Foo & Bar ', {
lang: []
})
.should.eql('array-foo-and-bar');
getSlug('array Foo & Bar ', {
lang: [],
symbols: false
})
.should.eql('array-foo-bar');
getSlug('null Foo & Bar ', {
lang: null
})
.should.eql('null-foo-and-bar');
getSlug('null Foo & Bar ', {
lang: null,
symbols: false
})
.should.eql('null-foo-bar');
getSlug('null Foo & Bar ', {
lang: null,
symbols: true
})
.should.eql('null-foo-and-bar');
done();
});
});
|
"use strict";
var Promise = require('bluebird'),
Property = require('./property'),
RID = require('../../recordid'),
utils = require('../../utils'),
errors = require('../../errors');
/**
* The class constructor.
* @param {Object} config The configuration for the class
*/
function Class(config) {
config = config || {};
if (!(this instanceof Class)) {
return new Class(config);
}
this.augment('property', Property);
this.augment('custom', require('./custom'));
this.configure(config);
}
Class.prototype.augment = utils.augment;
module.exports = exports = Class;
/**
* Configure the class instance.
* @param {Object} config The configuration object.
*/
Class.prototype.configure = function (config) {
this.db = config.db;
this.name = config.name || '';
this.shortName = config.shortName || null;
this.defaultClusterId = config.defaultClusterId || null;
this.clusterIds = config.clusterIds || [];
this.properties = (config.properties || []).map(function (item) {
item.class = this;
return new Property(item);
}, this);
this.superClass = config.superClass || null;
this.superClasses= config.superClasses || null;
this.originalName = this.name;
if (config.custom && config.custom.fields) {
this.custom.fields = config.custom.fields;
}
else if (config.customFields) {
this.custom.fields = config.customFields;
}
};
/**
* Return a list of records in the class.
*
* @param {Integer|Object} limit The maximum number of records to return, or a configuration object.
* @param {Integer} offset The offset to start returning records from.
* @promise {Object[]} An array of records in the class.
*/
Class.prototype.list = function (limit, offset) {
var query = 'SELECT * FROM ' + this.name,
config = {};
if (limit && typeof limit === 'object') {
config = limit;
limit = config.limit;
offset = config.offset;
}
limit = +limit || 20;
offset = +offset || 0;
if (limit !== Infinity) {
query += ' LIMIT ' + limit + ' OFFSET ' + offset;
}
else {
query += ' OFFSET ' + offset;
}
return this.db.query(query, config);
};
/**
* Find a list of records in the class.
*
* @param {Object} attributes The attributes to search with.
* @param {Integer} limit The maximum number of records to return
* @param {Integer} offset The offset to start returning records from.
* @promise {Object[]} An array of records in the class.
*/
Class.prototype.find = function (attributes, limit, offset) {
var query = 'SELECT * FROM ' + this.name,
keys = Object.keys(attributes),
total = keys.length,
conditions = [],
params = {},
key, sanitizedKey, value, i;
for (i = 0; i < total; i++) {
key = keys[i];
value = attributes[key];
sanitizedKey = key.replace(/\./g, '_');
params[sanitizedKey] = value;
conditions.push(key + ' = :' + sanitizedKey);
}
if (conditions.length) {
query += ' WHERE ' + conditions.join(' AND ');
}
limit = +limit || 20;
offset = +offset || 0;
if (limit !== Infinity) {
query += ' LIMIT ' + limit + ' OFFSET ' + offset;
}
else {
query += ' OFFSET ' + offset;
}
return this.db.query(query, {
params: params
});
};
/**
* Create a record for this class.
*
* @param {Object} record The record to create.
* @promise {Object} The created record.
*/
Class.prototype.create = function (record) {
if (Array.isArray(record)) {
return Promise.map(record, this.create.bind(this));
}
record['@class'] = this.name;
return this.db.record.create(record)
.then(function (record) {
// delete record['@class'];
return record;
});
};
/**
* Reload the class instance.
*
* @promise {Class} The class instance.
*/
Class.prototype.reload = function () {
return this.db.class.get(this.originalName, true)
.bind(this)
.then(function (item) {
this.configure(item);
return this;
});
};
/**
* Static methods.
* These methods are invoked with the database instance as `this`, not `Class`!
*/
/**
* The cached class items.
* @type {Object|false}
*/
exports.cached = false;
/**
* Retreive a list of classes from the database.
*
* @param {Boolean} refresh Whether to refresh the list or not.
* @promise {Object[]} An array of class objects.
*/
exports.list = function (refresh) {
if (!refresh && this.class.cached) {
return Promise.resolve(this.class.cached.items);
}
return this.send('record-load', {
cluster: 0,
position: 1
})
.bind(this)
.then(function (response) {
var record = response.records[0];
if (!record || !record.classes) {
return [];
}
else {
return record.classes;
}
})
.then(this.class.cacheData)
.then(function () {
return this.class.cached.items;
});
};
/**
* Create a new class.
*
* @param {String} name The name of the class to create.
* @param {String} parentName The name of the parent to extend, if any.
* @param {String|Integer} cluster The cluster name or id.
* @param {Boolean} isAbstract The flag for the abstract class
* @promise {Object} The created class object
*/
exports.create = function (name, parentName, cluster, isAbstract , ifnotexist) {
var query = 'CREATE CLASS ' + name;
if (ifnotexist) {
query += (ifnotexist===true ? " IF NOT EXISTS " : "");
}
if (parentName) {
query += ' EXTENDS ' + parentName;
}
if (cluster) {
query += ' CLUSTERS ' + cluster;
}
if (isAbstract) {
query += ' ABSTRACT';
}
return this.query(query)
.bind(this)
.then(function () {
return this.reload();
})
.then(function () {
return this.class.list(true);
})
.then(function (classes) {
return this.class.get(name);
});
};
/**
* Update the given class.
*
* @param {Object} class The class settings.
* @param {Boolean} reload Whether to reload the class, default to true.
* @promise {Object} The updated class.
*/
exports.update = function (cls, reload) {
var promises = [],
prefix = 'ALTER CLASS ' + cls.name + ' ';
if (reload == null) {
reload = true;
}
if (cls.superClass !== undefined) {
promises.push(this.exec(prefix + 'SUPERCLASS ' + cls.superClass));
}
return Promise.all(promises)
.bind(this)
.then(function () {
return this.class.get(cls.name, reload);
});
};
/**
* Delete a class.
*
* @param {String} name The name of the class to delete.
* @param {Object} config The config.
* @promise {Db} The database instance.
*/
exports.drop = function (name,config) {
config = config || {};
config.ifexist = config.ifexist ? config.ifexist : false;
config.unsafe = config.unsafe ? config.unsafe : false;
var query = 'DROP CLASS ' + name;
// modified for support IF NOT EXISTS and UNSAFE
query += (config.ifexist===true ? " IF EXISTS " : "") + ' ' + (config.unsafe===true ? " UNSAFE " : "");
return this.exec(query)
.bind(this)
.then(function () {
return this.class.list(true);
})
.then(function (classes) {
return this;
});
};
/**
* Get a class by name.
*
* @param {Integer|String} name The name of the class.
* @param {Boolean} refresh Whether to refresh the data, defaults to false.
* @promise {Object} The class object if it exists.
*/
exports.get = function (name, refresh) {
var className = name.toLocaleUpperCase();
if (!refresh && this.class.cached && this.class.cached.names[className]) {
return Promise.resolve(this.class.cached.names[className]);
}
else if (!this.class.cached || refresh) {
return this.class.list(refresh)
.bind(this)
.then(function () {
return this.class.cached.names[className] || Promise.reject(new errors.Request('No such class: ' + name));
});
}
else {
return Promise.reject(new errors.Request('No such class: ' + name));
}
};
/**
* Cache the given class data for fast lookup later.
*
* @param {Object[]} classes The class objects to cache.
* @return {Db} The db instance.
*/
exports.cacheData = function (classes) {
var total = classes.length,
item, i;
classes = classes.map(function (item) {
item.db = this;
return new Class(item);
}, this);
this.class.cached = {
names: {},
items: classes
};
for (i = 0; i < total; i++) {
item = classes[i];
this.class.cached.names[item.name.toLocaleUpperCase()] = item;
}
return this;
};
|
import LeafData from './LeafData'
import Property from "./Property";
class StateProvider
{
// Action
static deleteAction(id)
{
return { type: 'delete',id }
}
static addRootAction()
{
return { type: 'addRoot' }
}
static addSiblingAction(id)
{
return { type: 'addSibling', id }
}
static addChildAction(id)
{
return { type: 'addChild', id }
}
static editAction(leaf)
{
return { type: 'edit', leaf }
}
static moveAction(from, to)
{
return { type: 'move', from, to }
}
static walkAction(whereTo)
{
return { type: 'walk', whereTo }
}
static jumpAction(id)
{
return { type: 'jump', id }
}
static changeModeAction(mode)
{
return { type: 'changeMode', mode }
}
static changePreviewModeAction(mode)
{
return { type: 'changePreviewMode', mode }
}
// Reducer
static leafReducer(state = { root: new LeafData(), property: new Property() }, action) {
try{
let result;
if(state.property.isReadOnly===Property.readOnlyLevel().canEdit || action.type==="changeMode" || action.type==="changePreviewMode")
{
switch (action.type) {
case 'delete':
result= StateProvider.delete(state, action.id,state.property.focusId);
break;
case 'addRoot':
result= StateProvider.addRoot(state ,state.property.focusId,state.property.focusId);
break;
case 'addSibling':
let youngerbrothers=state.root.getYoungerBrother(state.property.focusId);
if(youngerbrothers===null)
{result= StateProvider.addSibling(state ,action.id)}
else
{result = StateProvider.walk(state, state.property.focusId, StateProvider.whereToMove().DOWN)};
break;
case 'addChild':
let children = state.root.getChildren(state.property.focusId);
if(children.length===0)
{result = StateProvider.addChild(state ,action.id)}
else
{result = StateProvider.walk(state, state.property.focusId, StateProvider.whereToMove().LEVELDOWN)};
break;
case 'edit':
result= StateProvider.edit(state ,action.leaf,state.property.focusId);
break;
case 'move':
result= StateProvider.move(state, action.from, action.to ,state.property.focusId);
break;
case 'walk':
result = StateProvider.walk(state, state.property.focusId, action.whereTo);
break;
case 'jump':
result = StateProvider.jump(state, action.id);
break;
case 'changeMode':
result = StateProvider.changeMode(state, action.mode);
break;
case 'changePreviewMode':
result = StateProvider.changePreviewMode(state, action.mode);
break;
default:
result= state;
break;
}
return result;
}
else
{
return state;
}
}catch(e)
{
console.error("Failed to update state: "+ e.message)
return state;
}
}
//Reducer implementation
static addRoot(state,id,focusId)
{
if (state.root!=null)
{
return {root:state.root, property: state.property}
}
else
{
let leaf = new LeafData(0, "", []);
let property = Property.getNewObject(state.property);
property.focusId=leaf.id;
return { root: leaf, property: property}
}
}
static addChild(state, id)
{
let current=state.root.getLeaf(id);
let leaf=new LeafData(state.root.getNewId(), "", []);
current.children=current.children.concat(leaf);
let property = Property.getNewObject(state.property);
property.focusId=leaf.id;
return { root: LeafData.getNewObject(state.root), property: property }
}
static addSibling(state, id)
{
let parent=state.root.getParent(id);
if(parent===null)
{
return { root: state.root, property: state.property }
}
else
{
let leaf=new LeafData(state.root.getNewId());
parent.children=parent.children.concat(leaf);
let property = Property.getNewObject(state.property);
property.focusId=leaf.id;
return { root: LeafData.getNewObject(state.root), property:property }
}
}
static edit(state, newleaf, focusId)
{
let leaf = state.root.getLeaf(newleaf.id);
leaf.description=newleaf.description;
leaf.imgs=newleaf.imgs;
leaf.color=newleaf.color;
return { root: state.root , property:state.property}
}
static move(state, from, to, focusId)
{
let current=state.root.getLeaf(from);
let currentParent = state.root.getParent(from);
let destination = state.root.getLeaf(to);
if(destination!=null && current!=null && currentParent!=null)
{
if(currentParent.id!=destination.id)
{
let newleaf = LeafData.getNewObject(current);
destination.children=destination.children.concat(newleaf);
currentParent.children=currentParent.children.filter(child=>child.id!=from);
}
}
return { root: LeafData.getNewObject(state.root) , property:state.property}
}
static delete(state, id, focusId)
{
if(state.root!=null && state.root.id!=id)
{
let parent=state.root.getParent(id);
parent.children=parent.children.filter(child=>child.id!=id);
let property = Property.getNewObject(state.property);
property.focusId=parent.id;
return {root: LeafData.getNewObject(state.root), property: property}
}
else
{
return {root: state.root , property:state.property}
}
}
static whereToMove()
{
return {
LEVELDOWN: "LEVELDOWN",
LEVELUP: "LEVELUP",
DOWN: "DOWN",
UP: "UP"
}
}
static walk(state, focusId, whereToMove)
{
let destination = StateProvider.whereToMove();
let moveTo="";
switch (whereToMove) {
case destination.UP:
let elderBrother=state.root.getElderBrother(focusId);
if(elderBrother!=null){moveTo=elderBrother.id}
else{moveTo=focusId};
break;
case destination.DOWN:
let youngerBrother=state.root.getYoungerBrother(focusId);
if(youngerBrother!=null){moveTo=youngerBrother.id}
else{moveTo=focusId};
break;
case destination.LEVELUP:
let parent=state.root.getParent(focusId);
if(parent!=null){moveTo=parent.id}
else {moveTo=focusId};
break;
case destination.LEVELDOWN:
let children = state.root.getChildren(focusId);
if(children.length>0){moveTo=children[0].id}
else{moveTo=focusId}
break;
default:
moveTo=focusId;
break;
}
let property=Property.getNewObject(state.property)
property.focusId=moveTo;
return { root: state.root , property:property}
}
static jump(state, focusId)
{
let property=Property.getNewObject(state.property)
property.focusId=focusId;
return { root: state.root , property: property}
}
static changeMode(state, mode)
{
let property=Property.getNewObject(state.property)
property.isReadOnly=mode;
return { root: state.root , property: property}
}
static changePreviewMode(state, mode)
{
let property=Property.getNewObject(state.property)
property.previewMode=mode;
if(mode!=Property.previewMode().none)
{
property.isReadOnly=Property.readOnlyLevel().softReadOnly;
}
else
{
property.isReadOnly=Property.readOnlyLevel().canEdit;
}
return { root: state.root , property: property}
}
// Map Redux state to component props
static mapStateToProps(state) {
return {
root: state.root,
property: state.property
}
}
// Map Redux actions to component props
static mapDispatchToProps(dispatch) {
return {
delete: (id) => dispatch(StateProvider.deleteAction(id)),
addRoot: () => dispatch(StateProvider.addRootAction()),
addSibling: (id) => dispatch(StateProvider.addSiblingAction(id)),
addChild: (id) => dispatch(StateProvider.addChildAction(id)),
edit: (leaf) => dispatch(StateProvider.editAction(leaf)),
move: (from, to) => dispatch(StateProvider.moveAction(from, to)),
walk: (whereTo) => dispatch(StateProvider.walkAction(whereTo)),
jump: (id) => dispatch(StateProvider.jumpAction(id)),
changeMode: (mode) => dispatch(StateProvider.changeModeAction(mode)),
changePreviewMode: (mode) => dispatch(StateProvider.changePreviewModeAction(mode))
}
}
}
export default StateProvider;
|
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
from .. import _utilities
import typing
# Export this package's modules as members:
from ._enums import *
from .app_service_environment import *
from .app_service_environment_private_endpoint_connection import *
from .app_service_plan import *
from .app_service_plan_route_for_vnet import *
from .certificate import *
from .connection import *
from .connection_gateway import *
from .custom_api import *
from .get_app_service_environment import *
from .get_app_service_environment_private_endpoint_connection import *
from .get_app_service_plan import *
from .get_certificate import *
from .get_connection import *
from .get_connection_gateway import *
from .get_custom_api import *
from .get_static_site import *
from .get_static_site_custom_domain import *
from .get_static_site_private_endpoint_connection import *
from .get_static_site_user_provided_function_app_for_static_site import *
from .get_static_site_user_provided_function_app_for_static_site_build import *
from .get_web_app import *
from .get_web_app_deployment import *
from .get_web_app_deployment_slot import *
from .get_web_app_diagnostic_logs_configuration import *
from .get_web_app_domain_ownership_identifier import *
from .get_web_app_domain_ownership_identifier_slot import *
from .get_web_app_function import *
from .get_web_app_host_name_binding import *
from .get_web_app_host_name_binding_slot import *
from .get_web_app_hybrid_connection import *
from .get_web_app_hybrid_connection_slot import *
from .get_web_app_instance_function_slot import *
from .get_web_app_premier_add_on import *
from .get_web_app_premier_add_on_slot import *
from .get_web_app_private_endpoint_connection import *
from .get_web_app_private_endpoint_connection_slot import *
from .get_web_app_public_certificate import *
from .get_web_app_public_certificate_slot import *
from .get_web_app_relay_service_connection import *
from .get_web_app_relay_service_connection_slot import *
from .get_web_app_site_extension import *
from .get_web_app_site_extension_slot import *
from .get_web_app_slot import *
from .get_web_app_slot_configuration_names import *
from .get_web_app_source_control import *
from .get_web_app_source_control_slot import *
from .get_web_app_swift_virtual_network_connection import *
from .get_web_app_swift_virtual_network_connection_slot import *
from .get_web_app_vnet_connection import *
from .get_web_app_vnet_connection_slot import *
from .list_app_service_plan_hybrid_connection_keys import *
from .list_connection_consent_links import *
from .list_connection_keys import *
from .list_custom_api_wsdl_interfaces import *
from .list_site_identifiers_assigned_to_host_name import *
from .list_static_site_app_settings import *
from .list_static_site_build_app_settings import *
from .list_static_site_build_function_app_settings import *
from .list_static_site_configured_roles import *
from .list_static_site_function_app_settings import *
from .list_static_site_secrets import *
from .list_static_site_users import *
from .list_web_app_application_settings import *
from .list_web_app_application_settings_slot import *
from .list_web_app_auth_settings import *
from .list_web_app_auth_settings_slot import *
from .list_web_app_azure_storage_accounts import *
from .list_web_app_azure_storage_accounts_slot import *
from .list_web_app_backup_configuration import *
from .list_web_app_backup_configuration_slot import *
from .list_web_app_backup_status_secrets import *
from .list_web_app_backup_status_secrets_slot import *
from .list_web_app_connection_strings import *
from .list_web_app_connection_strings_slot import *
from .list_web_app_function_keys import *
from .list_web_app_function_keys_slot import *
from .list_web_app_function_secrets import *
from .list_web_app_function_secrets_slot import *
from .list_web_app_host_keys import *
from .list_web_app_host_keys_slot import *
from .list_web_app_hybrid_connection_keys import *
from .list_web_app_hybrid_connection_keys_slot import *
from .list_web_app_metadata import *
from .list_web_app_metadata_slot import *
from .list_web_app_publishing_credentials import *
from .list_web_app_publishing_credentials_slot import *
from .list_web_app_site_backups import *
from .list_web_app_site_backups_slot import *
from .list_web_app_site_push_settings import *
from .list_web_app_site_push_settings_slot import *
from .list_web_app_sync_function_triggers import *
from .list_web_app_sync_function_triggers_slot import *
from .static_site import *
from .static_site_custom_domain import *
from .static_site_private_endpoint_connection import *
from .static_site_user_provided_function_app_for_static_site import *
from .static_site_user_provided_function_app_for_static_site_build import *
from .web_app import *
from .web_app_application_settings import *
from .web_app_application_settings_slot import *
from .web_app_auth_settings import *
from .web_app_auth_settings_slot import *
from .web_app_auth_settings_v2 import *
from .web_app_auth_settings_v2_slot import *
from .web_app_azure_storage_accounts import *
from .web_app_azure_storage_accounts_slot import *
from .web_app_backup_configuration import *
from .web_app_backup_configuration_slot import *
from .web_app_connection_strings import *
from .web_app_connection_strings_slot import *
from .web_app_deployment import *
from .web_app_deployment_slot import *
from .web_app_diagnostic_logs_configuration import *
from .web_app_domain_ownership_identifier import *
from .web_app_domain_ownership_identifier_slot import *
from .web_app_function import *
from .web_app_host_name_binding import *
from .web_app_host_name_binding_slot import *
from .web_app_hybrid_connection import *
from .web_app_hybrid_connection_slot import *
from .web_app_instance_function_slot import *
from .web_app_metadata import *
from .web_app_metadata_slot import *
from .web_app_premier_add_on import *
from .web_app_premier_add_on_slot import *
from .web_app_private_endpoint_connection import *
from .web_app_private_endpoint_connection_slot import *
from .web_app_public_certificate import *
from .web_app_public_certificate_slot import *
from .web_app_relay_service_connection import *
from .web_app_relay_service_connection_slot import *
from .web_app_site_extension import *
from .web_app_site_extension_slot import *
from .web_app_site_push_settings import *
from .web_app_site_push_settings_slot import *
from .web_app_slot import *
from .web_app_slot_configuration_names import *
from .web_app_source_control import *
from .web_app_source_control_slot import *
from .web_app_swift_virtual_network_connection import *
from .web_app_swift_virtual_network_connection_slot import *
from .web_app_vnet_connection import *
from .web_app_vnet_connection_slot import *
from ._inputs import *
from . import outputs
# Make subpackages available:
if typing.TYPE_CHECKING:
import pulumi_azure_native.web.v20150801 as v20150801
import pulumi_azure_native.web.v20150801preview as v20150801preview
import pulumi_azure_native.web.v20160301 as v20160301
import pulumi_azure_native.web.v20160601 as v20160601
import pulumi_azure_native.web.v20160801 as v20160801
import pulumi_azure_native.web.v20160901 as v20160901
import pulumi_azure_native.web.v20180201 as v20180201
import pulumi_azure_native.web.v20181101 as v20181101
import pulumi_azure_native.web.v20190801 as v20190801
import pulumi_azure_native.web.v20200601 as v20200601
import pulumi_azure_native.web.v20200901 as v20200901
import pulumi_azure_native.web.v20201001 as v20201001
import pulumi_azure_native.web.v20201201 as v20201201
else:
v20150801 = _utilities.lazy_import('pulumi_azure_native.web.v20150801')
v20150801preview = _utilities.lazy_import('pulumi_azure_native.web.v20150801preview')
v20160301 = _utilities.lazy_import('pulumi_azure_native.web.v20160301')
v20160601 = _utilities.lazy_import('pulumi_azure_native.web.v20160601')
v20160801 = _utilities.lazy_import('pulumi_azure_native.web.v20160801')
v20160901 = _utilities.lazy_import('pulumi_azure_native.web.v20160901')
v20180201 = _utilities.lazy_import('pulumi_azure_native.web.v20180201')
v20181101 = _utilities.lazy_import('pulumi_azure_native.web.v20181101')
v20190801 = _utilities.lazy_import('pulumi_azure_native.web.v20190801')
v20200601 = _utilities.lazy_import('pulumi_azure_native.web.v20200601')
v20200901 = _utilities.lazy_import('pulumi_azure_native.web.v20200901')
v20201001 = _utilities.lazy_import('pulumi_azure_native.web.v20201001')
v20201201 = _utilities.lazy_import('pulumi_azure_native.web.v20201201')
|
import {
saveCurrentLocation,
getAuthData,
getPreviousLocation,
} from './navigation/navigation-helpers';
import { communication } from './communication';
import { settings } from './settings';
import { createAuth } from './auth.js';
import { saveInitParamsIfPresent } from './init-params';
import { config } from './config';
import { getInitParams } from './init-params';
import {
navigation,
getNavigationData,
resolveNavigationNodes,
} from './navigation/navigation-data-init';
import { onQuotaExceed } from './luigi-event-handlers';
export const NODE_PARAM_PREFIX = `~`;
(async () => {
await saveInitParamsIfPresent(location);
const params = getInitParams();
if (!params) {
window.location = '/login.html';
}
const luigiConfig = {
auth: !params.rawAuth && (await createAuth(params.auth)),
communication,
navigation,
routing: {
nodeParamPrefix: NODE_PARAM_PREFIX,
skipRoutingForUrlPatterns: [/access_token=/, /id_token=/],
},
settings,
lifecycleHooks: {
luigiAfterInit: () => {
if (params.rawAuth) {
Luigi.auth().store.setAuthData(params.rawAuth);
}
const showSystemNamespaces = localStorage.getItem(
'busola.showSystemNamespaces'
);
if (showSystemNamespaces === 'true') {
Luigi.featureToggles().setFeatureToggle('showSystemNamespaces');
} else {
Luigi.featureToggles().unsetFeatureToggle('showSystemNamespaces');
}
const auth = getAuthData();
if (auth) {
getNavigationData(auth).then((response) => {
resolveNavigationNodes(response);
Luigi.ux().hideAppLoadingIndicator();
const prevLocation = getPreviousLocation();
if (prevLocation) {
Luigi.navigation().navigate(prevLocation);
}
});
} else {
saveCurrentLocation();
}
},
},
};
Luigi.setConfig(luigiConfig);
})();
window.addEventListener('message', (e) => {
if (e.data.msg === 'busola.quotaexceeded') {
onQuotaExceed(e.data);
}
});
|
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pytest
import os
import get_model_evaluation_slice_sample
PROJECT_ID = os.getenv("BUILD_SPECIFIC_GCLOUD_PROJECT")
MODEL_ID = "5162251072873431040" # permanent_safe_driver_model
EVALUATION_ID = "5615675837586029221" # permanent_safe_driver_model Evaluation
SLICE_ID = "4322488217836113260" # permanent_safe_driver_model Eval Slice
def test_ucaip_generated_get_model_evaluation_slice_sample(capsys):
get_model_evaluation_slice_sample.get_model_evaluation_slice_sample(
project=PROJECT_ID,
model_id=MODEL_ID,
evaluation_id=EVALUATION_ID,
slice_id=SLICE_ID,
)
out, _ = capsys.readouterr()
assert "metrics_schema_uri" in out
|
#!/usr/bin/env python3
# Copyright (c) 2014-2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Helpful routines for regression testing."""
from base64 import b64encode
from binascii import hexlify, unhexlify
from decimal import Decimal, ROUND_DOWN
import hashlib
import inspect
import json
import logging
import os
import random
import re
from subprocess import CalledProcessError
import time
from . import coverage
from .authproxy import AuthServiceProxy, JSONRPCException
logger = logging.getLogger("TestFramework.utils")
# Assert functions
##################
def assert_fee_amount(fee, tx_size, fee_per_kB):
"""Assert the fee was in range"""
target_fee = round(tx_size * fee_per_kB / 1000, 8)
if fee < target_fee:
raise AssertionError("Fee of %s PRP too low! (Should be %s PRP)" % (str(fee), str(target_fee)))
# allow the wallet's estimation to be at most 2 bytes off
if fee > (tx_size + 2) * fee_per_kB / 1000:
raise AssertionError("Fee of %s PRP too high! (Should be %s PRP)" % (str(fee), str(target_fee)))
def assert_equal(thing1, thing2, *args):
if thing1 != thing2 or any(thing1 != arg for arg in args):
raise AssertionError("not(%s)" % " == ".join(str(arg) for arg in (thing1, thing2) + args))
def assert_greater_than(thing1, thing2):
if thing1 <= thing2:
raise AssertionError("%s <= %s" % (str(thing1), str(thing2)))
def assert_greater_than_or_equal(thing1, thing2):
if thing1 < thing2:
raise AssertionError("%s < %s" % (str(thing1), str(thing2)))
def assert_raises(exc, fun, *args, **kwds):
assert_raises_message(exc, None, fun, *args, **kwds)
def assert_raises_message(exc, message, fun, *args, **kwds):
try:
fun(*args, **kwds)
except JSONRPCException:
raise AssertionError("Use assert_raises_rpc_error() to test RPC failures")
except exc as e:
if message is not None and message not in e.error['message']:
raise AssertionError("Expected substring not found:" + e.error['message'])
except Exception as e:
raise AssertionError("Unexpected exception raised: " + type(e).__name__)
else:
raise AssertionError("No exception raised")
def assert_raises_process_error(returncode, output, fun, *args, **kwds):
"""Execute a process and asserts the process return code and output.
Calls function `fun` with arguments `args` and `kwds`. Catches a CalledProcessError
and verifies that the return code and output are as expected. Throws AssertionError if
no CalledProcessError was raised or if the return code and output are not as expected.
Args:
returncode (int): the process return code.
output (string): [a substring of] the process output.
fun (function): the function to call. This should execute a process.
args*: positional arguments for the function.
kwds**: named arguments for the function.
"""
try:
fun(*args, **kwds)
except CalledProcessError as e:
if returncode != e.returncode:
raise AssertionError("Unexpected returncode %i" % e.returncode)
if output not in e.output:
raise AssertionError("Expected substring not found:" + e.output)
else:
raise AssertionError("No exception raised")
def assert_raises_rpc_error(code, message, fun, *args, **kwds):
"""Run an RPC and verify that a specific JSONRPC exception code and message is raised.
Calls function `fun` with arguments `args` and `kwds`. Catches a JSONRPCException
and verifies that the error code and message are as expected. Throws AssertionError if
no JSONRPCException was raised or if the error code/message are not as expected.
Args:
code (int), optional: the error code returned by the RPC call (defined
in src/rpc/protocol.h). Set to None if checking the error code is not required.
message (string), optional: [a substring of] the error string returned by the
RPC call. Set to None if checking the error string is not required.
fun (function): the function to call. This should be the name of an RPC.
args*: positional arguments for the function.
kwds**: named arguments for the function.
"""
assert try_rpc(code, message, fun, *args, **kwds), "No exception raised"
def try_rpc(code, message, fun, *args, **kwds):
"""Tries to run an rpc command.
Test against error code and message if the rpc fails.
Returns whether a JSONRPCException was raised."""
try:
fun(*args, **kwds)
except JSONRPCException as e:
# JSONRPCException was thrown as expected. Check the code and message values are correct.
if (code is not None) and (code != e.error["code"]):
raise AssertionError("Unexpected JSONRPC error code %i" % e.error["code"])
if (message is not None) and (message not in e.error['message']):
raise AssertionError("Expected substring not found:" + e.error['message'])
return True
except Exception as e:
raise AssertionError("Unexpected exception raised: " + type(e).__name__)
else:
return False
def assert_is_hex_string(string):
try:
int(string, 16)
except Exception as e:
raise AssertionError(
"Couldn't interpret %r as hexadecimal; raised: %s" % (string, e))
def assert_is_hash_string(string, length=64):
if not isinstance(string, str):
raise AssertionError("Expected a string, got type %r" % type(string))
elif length and len(string) != length:
raise AssertionError(
"String of length %d expected; got %d" % (length, len(string)))
elif not re.match('[abcdef0-9]+$', string):
raise AssertionError(
"String %r contains invalid characters for a hash." % string)
def assert_array_result(object_array, to_match, expected, should_not_find=False):
"""
Pass in array of JSON objects, a dictionary with key/value pairs
to match against, and another dictionary with expected key/value
pairs.
If the should_not_find flag is true, to_match should not be found
in object_array
"""
if should_not_find:
assert_equal(expected, {})
num_matched = 0
for item in object_array:
all_match = True
for key, value in to_match.items():
if item[key] != value:
all_match = False
if not all_match:
continue
elif should_not_find:
num_matched = num_matched + 1
for key, value in expected.items():
if item[key] != value:
raise AssertionError("%s : expected %s=%s" % (str(item), str(key), str(value)))
num_matched = num_matched + 1
if num_matched == 0 and not should_not_find:
raise AssertionError("No objects matched %s" % (str(to_match)))
if num_matched > 0 and should_not_find:
raise AssertionError("Objects were found %s" % (str(to_match)))
# Utility functions
###################
def check_json_precision():
"""Make sure json library being used does not lose precision converting BTC values"""
n = Decimal("20000000.00000003")
satoshis = int(json.loads(json.dumps(float(n))) * 1.0e8)
if satoshis != 2000000000000003:
raise RuntimeError("JSON encode/decode loses precision")
def count_bytes(hex_string):
return len(bytearray.fromhex(hex_string))
def bytes_to_hex_str(byte_str):
return hexlify(byte_str).decode('ascii')
def hash256(byte_str):
sha256 = hashlib.sha256()
sha256.update(byte_str)
sha256d = hashlib.sha256()
sha256d.update(sha256.digest())
return sha256d.digest()[::-1]
def hex_str_to_bytes(hex_str):
return unhexlify(hex_str.encode('ascii'))
def str_to_b64str(string):
return b64encode(string.encode('utf-8')).decode('ascii')
def satoshi_round(amount):
return Decimal(amount).quantize(Decimal('0.00000001'), rounding=ROUND_DOWN)
def wait_until(predicate, *, attempts=float('inf'), timeout=float('inf'), lock=None):
if attempts == float('inf') and timeout == float('inf'):
timeout = 60
attempt = 0
time_end = time.time() + timeout
while attempt < attempts and time.time() < time_end:
if lock:
with lock:
if predicate():
return
else:
if predicate():
return
attempt += 1
time.sleep(0.05)
# Print the cause of the timeout
predicate_source = "''''\n" + inspect.getsource(predicate) + "'''"
logger.error("wait_until() failed. Predicate: {}".format(predicate_source))
if attempt >= attempts:
raise AssertionError("Predicate {} not true after {} attempts".format(predicate_source, attempts))
elif time.time() >= time_end:
raise AssertionError("Predicate {} not true after {} seconds".format(predicate_source, timeout))
raise RuntimeError('Unreachable')
# RPC/P2P connection constants and functions
############################################
# The maximum number of nodes a single test can spawn
MAX_NODES = 8
# Don't assign rpc or p2p ports lower than this
PORT_MIN = 11000
# The number of ports to "reserve" for p2p and rpc, each
PORT_RANGE = 5000
class PortSeed:
# Must be initialized with a unique integer for each process
n = None
def get_rpc_proxy(url, node_number, timeout=None, coveragedir=None):
"""
Args:
url (str): URL of the RPC server to call
node_number (int): the node number (or id) that this calls to
Kwargs:
timeout (int): HTTP timeout in seconds
Returns:
AuthServiceProxy. convenience object for making RPC calls.
"""
proxy_kwargs = {}
if timeout is not None:
proxy_kwargs['timeout'] = timeout
proxy = AuthServiceProxy(url, **proxy_kwargs)
proxy.url = url # store URL on proxy for info
coverage_logfile = coverage.get_filename(
coveragedir, node_number) if coveragedir else None
return coverage.AuthServiceProxyWrapper(proxy, coverage_logfile)
def p2p_port(n):
assert(n <= MAX_NODES)
return PORT_MIN + n + (MAX_NODES * PortSeed.n) % (PORT_RANGE - 1 - MAX_NODES)
def rpc_port(n):
return PORT_MIN + PORT_RANGE + n + (MAX_NODES * PortSeed.n) % (PORT_RANGE - 1 - MAX_NODES)
def rpc_url(datadir, i, rpchost=None):
rpc_u, rpc_p = get_auth_cookie(datadir)
host = '127.0.0.1'
port = rpc_port(i)
if rpchost:
parts = rpchost.split(':')
if len(parts) == 2:
host, port = parts
else:
host = rpchost
return "http://%s:%s@%s:%d" % (rpc_u, rpc_p, host, int(port))
# Node functions
################
def initialize_datadir(dirname, n):
datadir = get_datadir_path(dirname, n)
if not os.path.isdir(datadir):
os.makedirs(datadir)
with open(os.path.join(datadir, "prpalcoin.conf"), 'w', encoding='utf8') as f:
f.write("regtest=1\n")
f.write("[regtest]\n")
f.write("port=" + str(p2p_port(n)) + "\n")
f.write("rpcport=" + str(rpc_port(n)) + "\n")
f.write("server=1\n")
f.write("keypool=1\n")
f.write("discover=0\n")
f.write("listenonion=0\n")
f.write("printtoconsole=0\n")
f.write("upnp=0\n")
os.makedirs(os.path.join(datadir, 'stderr'), exist_ok=True)
os.makedirs(os.path.join(datadir, 'stdout'), exist_ok=True)
return datadir
def get_datadir_path(dirname, n):
return os.path.join(dirname, "node" + str(n))
def append_config(datadir, options):
with open(os.path.join(datadir, "prpalcoin.conf"), 'a', encoding='utf8') as f:
for option in options:
f.write(option + "\n")
def get_auth_cookie(datadir):
user = None
password = None
if os.path.isfile(os.path.join(datadir, "prpalcoin.conf")):
with open(os.path.join(datadir, "prpalcoin.conf"), 'r', encoding='utf8') as f:
for line in f:
if line.startswith("rpcuser="):
assert user is None # Ensure that there is only one rpcuser line
user = line.split("=")[1].strip("\n")
if line.startswith("rpcpassword="):
assert password is None # Ensure that there is only one rpcpassword line
password = line.split("=")[1].strip("\n")
if os.path.isfile(os.path.join(datadir, "regtest", ".cookie")) and os.access(os.path.join(datadir, "regtest", ".cookie"), os.R_OK):
with open(os.path.join(datadir, "regtest", ".cookie"), 'r', encoding="ascii") as f:
userpass = f.read()
split_userpass = userpass.split(':')
user = split_userpass[0]
password = split_userpass[1]
if user is None or password is None:
raise ValueError("No RPC credentials")
return user, password
# If a cookie file exists in the given datadir, delete it.
def delete_cookie_file(datadir):
if os.path.isfile(os.path.join(datadir, "regtest", ".cookie")):
logger.debug("Deleting leftover cookie file")
os.remove(os.path.join(datadir, "regtest", ".cookie"))
def get_bip9_status(node, key):
info = node.getblockchaininfo()
return info['bip9_softforks'][key]
def set_node_times(nodes, t):
for node in nodes:
node.setmocktime(t)
def disconnect_nodes(from_connection, node_num):
for peer_id in [peer['id'] for peer in from_connection.getpeerinfo() if "testnode%d" % node_num in peer['subver']]:
try:
from_connection.disconnectnode(nodeid=peer_id)
except JSONRPCException as e:
# If this node is disconnected between calculating the peer id
# and issuing the disconnect, don't worry about it.
# This avoids a race condition if we're mass-disconnecting peers.
if e.error['code'] != -29: # RPC_CLIENT_NODE_NOT_CONNECTED
raise
# wait to disconnect
wait_until(lambda: [peer['id'] for peer in from_connection.getpeerinfo() if "testnode%d" % node_num in peer['subver']] == [], timeout=5)
def connect_nodes(from_connection, node_num):
ip_port = "127.0.0.1:" + str(p2p_port(node_num))
from_connection.addnode(ip_port, "onetry")
# poll until version handshake complete to avoid race conditions
# with transaction relaying
wait_until(lambda: all(peer['version'] != 0 for peer in from_connection.getpeerinfo()))
def connect_nodes_bi(nodes, a, b):
connect_nodes(nodes[a], b)
connect_nodes(nodes[b], a)
def sync_blocks(rpc_connections, *, wait=1, timeout=60):
"""
Wait until everybody has the same tip.
sync_blocks needs to be called with an rpc_connections set that has least
one node already synced to the latest, stable tip, otherwise there's a
chance it might return before all nodes are stably synced.
"""
stop_time = time.time() + timeout
while time.time() <= stop_time:
best_hash = [x.getbestblockhash() for x in rpc_connections]
if best_hash.count(best_hash[0]) == len(rpc_connections):
return
time.sleep(wait)
raise AssertionError("Block sync timed out:{}".format("".join("\n {!r}".format(b) for b in best_hash)))
def sync_mempools(rpc_connections, *, wait=1, timeout=60, flush_scheduler=True):
"""
Wait until everybody has the same transactions in their memory
pools
"""
stop_time = time.time() + timeout
while time.time() <= stop_time:
pool = [set(r.getrawmempool()) for r in rpc_connections]
if pool.count(pool[0]) == len(rpc_connections):
if flush_scheduler:
for r in rpc_connections:
r.syncwithvalidationinterfacequeue()
return
time.sleep(wait)
raise AssertionError("Mempool sync timed out:{}".format("".join("\n {!r}".format(m) for m in pool)))
# Transaction/Block functions
#############################
def find_output(node, txid, amount, *, blockhash=None):
"""
Return index to output of txid with value amount
Raises exception if there is none.
"""
txdata = node.getrawtransaction(txid, 1, blockhash)
for i in range(len(txdata["vout"])):
if txdata["vout"][i]["value"] == amount:
return i
raise RuntimeError("find_output txid %s : %s not found" % (txid, str(amount)))
def gather_inputs(from_node, amount_needed, confirmations_required=1):
"""
Return a random set of unspent txouts that are enough to pay amount_needed
"""
assert(confirmations_required >= 0)
utxo = from_node.listunspent(confirmations_required)
random.shuffle(utxo)
inputs = []
total_in = Decimal("0.00000000")
while total_in < amount_needed and len(utxo) > 0:
t = utxo.pop()
total_in += t["amount"]
inputs.append({"txid": t["txid"], "vout": t["vout"], "address": t["address"]})
if total_in < amount_needed:
raise RuntimeError("Insufficient funds: need %d, have %d" % (amount_needed, total_in))
return (total_in, inputs)
def make_change(from_node, amount_in, amount_out, fee):
"""
Create change output(s), return them
"""
outputs = {}
amount = amount_out + fee
change = amount_in - amount
if change > amount * 2:
# Create an extra change output to break up big inputs
change_address = from_node.getnewaddress()
# Split change in two, being careful of rounding:
outputs[change_address] = Decimal(change / 2).quantize(Decimal('0.00000001'), rounding=ROUND_DOWN)
change = amount_in - amount - outputs[change_address]
if change > 0:
outputs[from_node.getnewaddress()] = change
return outputs
def random_transaction(nodes, amount, min_fee, fee_increment, fee_variants):
"""
Create a random transaction.
Returns (txid, hex-encoded-transaction-data, fee)
"""
from_node = random.choice(nodes)
to_node = random.choice(nodes)
fee = min_fee + fee_increment * random.randint(0, fee_variants)
(total_in, inputs) = gather_inputs(from_node, amount + fee)
outputs = make_change(from_node, total_in, amount, fee)
outputs[to_node.getnewaddress()] = float(amount)
rawtx = from_node.createrawtransaction(inputs, outputs)
signresult = from_node.signrawtransactionwithwallet(rawtx)
txid = from_node.sendrawtransaction(signresult["hex"], True)
return (txid, signresult["hex"], fee)
# Helper to create at least "count" utxos
# Pass in a fee that is sufficient for relay and mining new transactions.
def create_confirmed_utxos(fee, node, count):
to_generate = int(0.5 * count) + 101
while to_generate > 0:
node.generate(min(25, to_generate))
to_generate -= 25
utxos = node.listunspent()
iterations = count - len(utxos)
addr1 = node.getnewaddress()
addr2 = node.getnewaddress()
if iterations <= 0:
return utxos
for i in range(iterations):
t = utxos.pop()
inputs = []
inputs.append({"txid": t["txid"], "vout": t["vout"]})
outputs = {}
send_value = t['amount'] - fee
outputs[addr1] = satoshi_round(send_value / 2)
outputs[addr2] = satoshi_round(send_value / 2)
raw_tx = node.createrawtransaction(inputs, outputs)
signed_tx = node.signrawtransactionwithwallet(raw_tx)["hex"]
node.sendrawtransaction(signed_tx)
while (node.getmempoolinfo()['size'] > 0):
node.generate(1)
utxos = node.listunspent()
assert(len(utxos) >= count)
return utxos
# Create large OP_RETURN txouts that can be appended to a transaction
# to make it large (helper for constructing large transactions).
def gen_return_txouts():
# Some pre-processing to create a bunch of OP_RETURN txouts to insert into transactions we create
# So we have big transactions (and therefore can't fit very many into each block)
# create one script_pubkey
script_pubkey = "6a4d0200" # OP_RETURN OP_PUSH2 512 bytes
for i in range(512):
script_pubkey = script_pubkey + "01"
# concatenate 128 txouts of above script_pubkey which we'll insert before the txout for change
txouts = "81"
for k in range(128):
# add txout value
txouts = txouts + "0000000000000000"
# add length of script_pubkey
txouts = txouts + "fd0402"
# add script_pubkey
txouts = txouts + script_pubkey
return txouts
# Create a spend of each passed-in utxo, splicing in "txouts" to each raw
# transaction to make it large. See gen_return_txouts() above.
def create_lots_of_big_transactions(node, txouts, utxos, num, fee):
addr = node.getnewaddress()
txids = []
for _ in range(num):
t = utxos.pop()
inputs = [{"txid": t["txid"], "vout": t["vout"]}]
outputs = {}
change = t['amount'] - fee
outputs[addr] = satoshi_round(change)
rawtx = node.createrawtransaction(inputs, outputs)
newtx = rawtx[0:92]
newtx = newtx + txouts
newtx = newtx + rawtx[94:]
signresult = node.signrawtransactionwithwallet(newtx, None, "NONE")
txid = node.sendrawtransaction(signresult["hex"], True)
txids.append(txid)
return txids
def mine_large_block(node, utxos=None):
# generate a 66k transaction,
# and 14 of them is close to the 1MB block limit
num = 14
txouts = gen_return_txouts()
utxos = utxos if utxos is not None else []
if len(utxos) < num:
utxos.clear()
utxos.extend(node.listunspent())
fee = 100 * node.getnetworkinfo()["relayfee"]
create_lots_of_big_transactions(node, txouts, utxos, num, fee=fee)
node.generate(1)
def find_vout_for_address(node, txid, addr):
"""
Locate the vout index of the given transaction sending to the
given address. Raises runtime error exception if not found.
"""
tx = node.getrawtransaction(txid, True)
for i in range(len(tx["vout"])):
if any([addr == a for a in tx["vout"][i]["scriptPubKey"]["addresses"]]):
return i
raise RuntimeError("Vout not found for address: txid=%s, addr=%s" % (txid, addr))
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from .migrate_postgre_sql_azure_db_for_postgre_sql_sync_task_output import MigratePostgreSqlAzureDbForPostgreSqlSyncTaskOutput
class MigratePostgreSqlAzureDbForPostgreSqlSyncTaskOutputError(MigratePostgreSqlAzureDbForPostgreSqlSyncTaskOutput):
"""MigratePostgreSqlAzureDbForPostgreSqlSyncTaskOutputError.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar id: Result identifier
:vartype id: str
:param result_type: Constant filled by server.
:type result_type: str
:ivar error: Migration error
:vartype error: ~azure.mgmt.datamigration.models.ReportableException
"""
_validation = {
'id': {'readonly': True},
'result_type': {'required': True},
'error': {'readonly': True},
}
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'result_type': {'key': 'resultType', 'type': 'str'},
'error': {'key': 'error', 'type': 'ReportableException'},
}
def __init__(self):
super(MigratePostgreSqlAzureDbForPostgreSqlSyncTaskOutputError, self).__init__()
self.error = None
self.result_type = 'ErrorOutput'
|
import React from 'react';
import { Helmet } from 'react-helmet';
import Feed from './Feed';
import Chats from './Chats';
import Bar from './components/bar';
import './components/fontawesome';
import '../../assets/css/style.css';
const App = () => {
return (
<div className="container">
<Helmet>
<title>Graphbook - Feed</title>
<meta name="description" content="Newsfeed of all your friends on Graphbook" />
</Helmet>
<Bar />
<Feed />
<Chats />
</div>
)
}
export default App
|
#! /usr/bin/env node
'use strict';
process.env.NODE_ENV = 'development';
const fs = require('fs-extra');
const mri = require('mri');
const webpack = require('webpack');
const createConfig = require('../config/createConfigAsync');
const loadRazzleConfig = require('../config/loadRazzleConfig');
const devServer = require('../config/razzleDevServer');
const printErrors = require('razzle-dev-utils/printErrors');
const clearConsole = require('react-dev-utils/clearConsole');
const logger = require('razzle-dev-utils/logger');
const setPorts = require('razzle-dev-utils/setPorts');
const chalk = require('chalk');
const terminate = require('terminate');
process.once('SIGINT', () => {
console.error(chalk.bgRedBright(' SIGINT '), chalk.redBright('exiting...'));
terminate(process.pid, 'SIGINT', { timeout: 1000 }, () => {
console.error(chalk.bgGreen(' Goodbye '));
terminate(process.pid);
});
});
process.noDeprecation = true; // turns off that loadQuery clutter.
const argv = process.argv.slice(2);
const cliArgs = mri(argv);
// Capture any --inspect or --inspect-brk flags (with optional values) so that we
// can pass them when we invoke nodejs
process.env.INSPECT_BRK = formatInspectFlag(cliArgs, 'inspect-brk');
process.env.INSPECT = formatInspectFlag(cliArgs, 'inspect');
function main() {
return new Promise(async (resolve, reject) => {
loadRazzleConfig(webpack).then(
async ({ razzle, razzleOptions, webpackObject, plugins, paths }) => {
const verbose = razzleOptions.verbose;
const clientOnly = /spa|single-page-application/.test(razzleOptions.buildType);
const serverOnly = /serveronly|server-only/.test(razzleOptions.buildType);
process.env.BUILD_TYPE = razzleOptions.buildType;
setPorts(clientOnly)
.then(async () => {
// Optimistically, we make the console look exactly like the output of our
// FriendlyErrorsPlugin during compilation, so the user has immediate feedback.
// clearConsole();
logger.start('Compiling...');
let clientConfig;
// Create dev configs using our config factory, passing in razzle file as
// options.
clientConfig = await createConfig(
'web',
'dev',
razzle,
webpackObject,
clientOnly,
paths,
plugins,
razzleOptions
);
if (clientOnly) {
// Check for public/index.html file
if (!fs.existsSync(paths.appHtml)) {
clearConsole();
logger.error(`index.html dose not exists public folder.`);
process.exit(1);
}
}
// Delete assets.json to always have a manifest up to date
fs.removeSync(paths.appAssetsManifest);
const clientCompiler = compile(clientConfig, verbose);
let serverCompiler;
let serverConfig;
if (!clientOnly) {
serverConfig = await createConfig(
'node',
'dev',
razzle,
webpackObject,
clientOnly,
paths,
plugins,
razzleOptions
);
serverCompiler = compile(serverConfig, verbose);
}
const port = razzle.port || clientConfig.devServer.port;
// Compile our assets with webpack
// Instatiate a variable to track server watching
let watching;
// in SPA mode we want to give the user
// feedback about the port that app is running on
// this variable helps us to don't show
// the message multiple times ...
let logged = false;
// Start our server webpack instance in watch mode after assets compile
clientCompiler.hooks.done.tap('razzle', () => {
// If we've already started the server watcher, bail early.
if (watching) {
return;
}
if (!clientOnly && serverCompiler) {
// Otherwise, create a new watcher for our server code.
watching = serverCompiler.watch(
{
quiet: !verbose,
stats: 'none',
},
/* eslint-disable no-unused-vars */
stats => {}
);
}
// in SPA mode we want to give the user
// feedback about the port that app is running on
if (clientOnly && !logged) {
logged = true;
console.log(chalk.green(`> SPA Started on port ${port}`));
}
});
// Create a new instance of Webpack-dev-server for our client assets.
// This will actually run on a different port than the users app.
const clientDevServer = new devServer(
clientCompiler,
Object.assign(clientConfig.devServer, { verbose: verbose })
);
// Start Webpack-dev-server
clientDevServer.listen(port, err => {
if (err) {
logger.error(err);
}
});
['SIGINT', 'SIGTERM'].forEach(sig => {
process.on(sig, () => {
clientDevServer.close();
if (watching) {
watching.close();
}
});
});
resolve();
}
);
})
.catch(console.error);
});
}
// Webpack compile in a try-catch
function compile(config, verbose) {
let compiler;
try {
compiler = webpack(config);
} catch (e) {
printErrors('Failed to compile.', [e], verbose);
process.exit(1);
}
return compiler;
}
function formatInspectFlag(cliArgs, flag) {
const value = cliArgs[flag];
if (typeof value === 'undefined' || value === '') {
return '';
}
// When passed as `--inspect`.
if (value === true) {
return '--' + flag;
}
// When passed as `--inspect=[port]` or `--inspect=[host:port]`
return '--' + flag + '=' + value.toString();
}
main();
|
import numpy as np
import properties
import scipy.sparse as sp
from scipy.constants import pi
from discretize.utils import (
kron3,
ndgrid,
av,
speye,
ddx,
sdiag,
spzeros,
interpolation_matrix,
cyl2cart,
)
from discretize.base import BaseTensorMesh, BaseRectangularMesh
from discretize.operators import DiffOperators, InnerProducts
from discretize.utils.code_utils import (
deprecate_class,
deprecate_property,
deprecate_method,
)
import warnings
class CylindricalMesh(
BaseTensorMesh, BaseRectangularMesh, InnerProducts, DiffOperators
):
"""
CylindricalMesh is a mesh class for cylindrical problems. It supports both
cylindrically symmetric and 3D cylindrical meshes that include an azimuthal
discretization.
For a cylindrically symmetric mesh use :code:`h = [hx, 1, hz]`. For example:
.. plot::
:include-source:
import discretize
from discretize import utils
cs, nc, npad = 20., 30, 8
hx = utils.unpack_widths([(cs, npad+10, -0.7), (cs, nc), (cs, npad, 1.3)])
hz = utils.unpack_widths([(cs, npad ,-1.3), (cs, nc), (cs, npad, 1.3)])
mesh = discretize.CylindricalMesh([hx, 1, hz], origin=[0, 0, -hz.sum()/2])
mesh.plot_grid()
To create a 3D cylindrical mesh, we also include an azimuthal discretization
.. plot::
:include-source:
import discretize
from discretize import utils
cs, nc, npad = 20., 30, 8
nc_theta = 8
hx = utils.unpack_widths([(cs, npad+10, -0.7), (cs, nc), (cs, npad, 1.3)])
hy = 2 * np.pi/nc_theta * np.ones(nc_theta)
hz = utils.unpack_widths([(cs,npad, -1.3), (cs,nc), (cs, npad, 1.3)])
mesh = discretize.CylindricalMesh([hx, hy, hz], origin=[0, 0, -hz.sum()/2])
mesh.plot_grid()
"""
_meshType = "CYL"
_unitDimensions = [1, 2 * np.pi, 1]
_aliases = {
**DiffOperators._aliases,
**BaseRectangularMesh._aliases,
**BaseTensorMesh._aliases,
}
cartesian_origin = properties.Array(
"Cartesian origin of the mesh", dtype=float, shape=("*",)
)
def __init__(self, h=None, origin=None, **kwargs):
super().__init__(h=h, origin=origin, **kwargs)
self.reference_system = "cylindrical"
if not np.abs(self.h[1].sum() - 2 * np.pi) < 1e-10:
raise AssertionError("The 2nd dimension must sum to 2*pi")
if self.dim == 2:
print("Warning, a disk mesh has not been tested thoroughly.")
if "cartesian_origin" in kwargs.keys():
self.cartesian_origin = kwargs.pop("cartesian_origin")
elif "cartesianOrigin" in kwargs.keys():
self.cartesian_origin = kwargs.pop("cartesianOrigin")
else:
self.cartesian_origin = np.zeros(self.dim)
@properties.validator("cartesian_origin")
def check_cartesian_origin_shape(self, change):
change["value"] = np.array(change["value"], dtype=float).ravel()
if len(change["value"]) != self.dim:
raise Exception(
"Dimension mismatch. The mesh dimension is {}, and the "
"cartesian_origin provided has length {}".format(
self.dim, len(change["value"])
)
)
@property
def is_symmetric(self):
"""
Is the mesh cylindrically symmetric?
Returns
-------
bool
True if the mesh is cylindrically symmetric, False otherwise
"""
return self.shape_cells[1] == 1
@property
def shape_nodes(self):
vnC = self.shape_cells
if self.is_symmetric:
return (vnC[0], 0, vnC[2] + 1)
else:
return (vnC[0] + 1, vnC[1], vnC[2] + 1)
@property
def _shape_total_nodes(self):
vnC = self.shape_cells
if self.is_symmetric:
return (vnC[0], 1, vnC[2] + 1)
else:
return tuple(x + 1 for x in vnC)
@property
def n_nodes(self):
"""
Returns
-------
int
Total number of nodes
"""
if self.is_symmetric:
return 0
nx, ny, nz = self.shape_nodes
return (nx - 1) * ny * nz + nz
@property
def _shape_total_faces_x(self):
"""
vector number of total Fx (prior to deflating)
"""
return self._shape_total_nodes[:1] + self.shape_cells[1:]
@property
def _n_total_faces_x(self):
"""
number of total Fx (prior to defplating)
"""
return int(np.prod(self._shape_total_faces_x))
@property
def _n_hanging_faces_x(self):
"""
Number of hanging Fx
"""
return int(np.prod(self.shape_cells[1:]))
@property
def shape_faces_x(self):
"""
Returns
-------
numpy.ndarray
Number of x-faces in each direction, (dim, )
"""
return self.shape_cells
@property
def _shape_total_faces_y(self):
"""
vector number of total Fy (prior to deflating)
"""
vnC = self.shape_cells
return (vnC[0], self._shape_total_nodes[1]) + vnC[2:]
@property
def _n_total_faces_y(self):
"""
number of total Fy (prior to deflating)
"""
return int(np.prod(self._shape_total_faces_y))
@property
def _n_hanging_faces_y(self):
"""
number of hanging y-faces
"""
return int(np.prod(self.shape_cells[::2]))
@property
def _shape_total_faces_z(self):
"""
vector number of total Fz (prior to deflating)
"""
return self.shape_cells[:-1] + self._shape_total_nodes[-1:]
@property
def _n_total_faces_z(self):
"""
number of total Fz (prior to deflating)
"""
return int(np.prod(self._shape_total_faces_z))
@property
def _n_hanging_faces_z(self):
"""
number of hanging Fz
"""
return int(np.prod(self.shape_cells[::2]))
@property
def _shape_total_edges_x(self):
"""
vector number of total Ex (prior to deflating)
"""
return self.shape_cells[:1] + self._shape_total_nodes[1:]
@property
def _n_total_edges_x(self):
"""
number of total Ex (prior to deflating)
"""
return int(np.prod(self._shape_total_edges_x))
@property
def _shape_total_edges_y(self):
"""
vector number of total Ey (prior to deflating)
"""
_shape_total_nodes = self._shape_total_nodes
return (_shape_total_nodes[0], self.shape_cells[1], _shape_total_nodes[2])
@property
def _n_total_edges_y(self):
"""
number of total Ey (prior to deflating)
"""
return int(np.prod(self._shape_total_edges_y))
@property
def shape_edges_y(self):
"""
Number of y-edges in each direction
Returns
-------
tuple of ints
vnEy or None if dim < 2, (dim, )
"""
return tuple(x + y for x, y in zip(self.shape_cells, [0, 0, 1]))
@property
def _shape_total_edges_z(self):
"""
vector number of total Ez (prior to deflating)
"""
return self._shape_total_nodes[:-1] + self.shape_cells[-1:]
@property
def _n_total_edges_z(self):
"""
number of total Ez (prior to deflating)
"""
return int(np.prod(self._shape_total_edges_z))
@property
def shape_edges_z(self):
"""
Returns
-------
tuple of ints
Number of z-edges in each direction or None if nCy > 1, (dim, )
"""
return self.shape_nodes[:-1] + self.shape_cells[-1:]
@property
def n_edges_z(self):
"""
Returns
-------
int
Number of z-edges
"""
z_shape = self.shape_edges_z
cell_shape = self.shape_cells
if self.is_symmetric:
return int(np.prod(z_shape))
return int(np.prod([z_shape[0] - 1, z_shape[1], cell_shape[2]])) + cell_shape[2]
@property
def cell_centers_x(self):
"""Cell-centered grid vector (1D) in the x direction."""
return np.r_[0, self.h[0][:-1].cumsum()] + self.h[0] * 0.5
@property
def cell_centers_y(self):
"""Cell-centered grid vector (1D) in the y direction."""
if self.is_symmetric:
return np.r_[0, self.h[1][:-1]]
return np.r_[0, self.h[1][:-1].cumsum()] + self.h[1] * 0.5
@property
def nodes_x(self):
"""Nodal grid vector (1D) in the x direction."""
if self.is_symmetric:
return self.h[0].cumsum()
return np.r_[0, self.h[0]].cumsum()
@property
def _nodes_y_full(self):
"""
full nodal y vector (prior to deflating)
"""
if self.is_symmetric:
return np.r_[0]
return np.r_[0, self.h[1].cumsum()]
@property
def nodes_y(self):
"""Nodal grid vector (1D) in the y direction."""
# if self.is_symmetric:
# # There aren't really any nodes, but all the grids need
# # somewhere to live, why not zero?!
# return np.r_[0]
return np.r_[0, self.h[1][:-1].cumsum()]
@property
def _edge_x_lengths_full(self):
"""
full x-edge lengths (prior to deflating)
"""
nx, ny, nz = self._shape_total_nodes
return np.kron(np.ones(nz), np.kron(np.ones(ny), self.h[0]))
@property
def edge_x_lengths(self):
"""
x-edge lengths - these are the radial edges. Radial edges only exist
for a 3D cyl mesh.
Returns
-------
numpy.ndarray
vector of radial edge lengths
"""
if getattr(self, "_edge_lengths_x", None) is None:
self._edge_lengths_x = self._edge_x_lengths_full[~self._ishanging_edges_x]
return self._edge_lengths_x
@property
def _edge_y_lengths_full(self):
"""
full vector of y-edge lengths (prior to deflating)
"""
if self.is_symmetric:
return 2 * pi * self.nodes[:, 0]
return np.kron(np.ones(self._shape_total_nodes[2]), np.kron(self.h[1], self.nodes_x))
@property
def edge_y_lengths(self):
"""
y-edge lengths - these are the azimuthal edges. Azimuthal edges exist
for all cylindrical meshes. These are arc-lengths (:math:`\\theta r`)
Returns
-------
numpy.ndarray
vector of the azimuthal edges
"""
if getattr(self, "_edge_lengths_y", None) is None:
if self.is_symmetric:
self._edge_lengths_y = self._edge_y_lengths_full
else:
self._edge_lengths_y = self._edge_y_lengths_full[~self._ishanging_edges_y]
return self._edge_lengths_y
@property
def _edge_z_lengths_full(self):
"""
full z-edge lengths (prior to deflation)
"""
nx, ny, nz = self._shape_total_nodes
return np.kron(self.h[2], np.kron(np.ones(ny), np.ones(nx)))
@property
def edge_z_lengths(self):
"""
z-edge lengths - these are the vertical edges. Vertical edges only
exist for a 3D cyl mesh.
Returns
-------
numpy.ndarray
vector of the vertical edges
"""
if getattr(self, "_edge_lengths_z", None) is None:
self._edge_lengths_z = self._edge_z_lengths_full[~self._ishanging_edges_z]
return self._edge_lengths_z
@property
def _edge_lengths_full(self):
"""
full edge lengths [r-edges, theta-edgesm z-edges] (prior to
deflation)
"""
if self.is_symmetric:
raise NotImplementedError
else:
return np.r_[self._edge_x_lengths_full, self._edge_y_lengths_full, self._edge_z_lengths_full]
@property
def edge_lengths(self):
"""
Edge lengths
Returns
-------
numpy.ndarray
vector of edge lengths :math:`(r, \\theta, z)`
"""
if self.is_symmetric:
return self.edge_y_lengths
else:
return np.r_[self.edge_x_lengths, self.edge_y_lengths, self.edge_z_lengths]
@property
def _face_x_areas_full(self):
"""
area of x-faces prior to deflation
"""
if self.is_symmetric:
return np.kron(self.h[2], 2 * pi * self.nodes_x)
return np.kron(self.h[2], np.kron(self.h[1], self.nodes_x))
@property
def face_x_areas(self):
"""
Area of the x-faces (radial faces). Radial faces exist on all
cylindrical meshes
.. math::
A_x = r \\theta h_z
Returns
-------
numpy.ndarray
area of x-faces
"""
if getattr(self, "_face_x_areas", None) is None:
if self.is_symmetric:
self._face_x_areas = self._face_x_areas_full
else:
self._face_x_areas = self._face_x_areas_full[~self._ishanging_faces_x]
return self._face_x_areas
@property
def _face_y_areas_full(self):
"""
Area of y-faces (Azimuthal faces), prior to deflation.
"""
return np.kron(self.h[2], np.kron(np.ones(self._shape_total_nodes[1]), self.h[0]))
@property
def face_y_areas(self):
"""
Area of y-faces (Azimuthal faces). Azimuthal faces exist only on 3D
cylindrical meshes.
.. math::
A_y = h_x h_z
Returns
-------
numpy.ndarray
area of y-faces
"""
if getattr(self, "_face_y_areas", None) is None:
if self.is_symmetric:
raise Exception("There are no y-faces on the Cyl Symmetric mesh")
self._face_y_areas = self._face_y_areas_full[~self._ishanging_faces_y]
return self._face_y_areas
@property
def _face_z_areas_full(self):
"""
area of z-faces prior to deflation
"""
if self.is_symmetric:
return np.kron(
np.ones_like(self.nodes_z),
pi * (self.nodes_x ** 2 - np.r_[0, self.nodes_x[:-1]] ** 2),
)
return np.kron(
np.ones(self._shape_total_nodes[2]),
np.kron(
self.h[1],
0.5 * (self.nodes_x[1:] ** 2 - self.nodes_x[:-1] ** 2),
),
)
@property
def face_z_areas(self):
"""
Area of z-faces.
.. math::
A_z = \\frac{\\theta}{2} (r_2^2 - r_1^2)z
Returns
-------
numpy.ndarray
area of the z-faces
"""
if getattr(self, "_face_z_areas", None) is None:
if self.is_symmetric:
self._face_z_areas = self._face_z_areas_full
else:
self._face_z_areas = self._face_z_areas_full[~self._ishanging_faces_z]
return self._face_z_areas
@property
def _face_areas_full(self):
"""
Area of all faces (prior to delflation)
"""
return np.r_[self._face_x_areas_full, self._face_y_areas_full, self._face_z_areas_full]
@property
def face_areas(self):
"""
Face areas
For a 3D cyl mesh: [radial, azimuthal, vertical], while a cylindrically
symmetric mesh doesn't have y-Faces, so it returns [radial, vertical]
Returns
-------
numpy.ndarray
face areas
"""
# if getattr(self, '_area', None) is None:
if self.is_symmetric:
return np.r_[self.face_x_areas, self.face_z_areas]
else:
return np.r_[self.face_x_areas, self.face_y_areas, self.face_z_areas]
@property
def cell_volumes(self):
"""
Volume of each cell
Returns
-------
numpy.ndarray
cell volumes
"""
if getattr(self, "_cell_volumes", None) is None:
if self.is_symmetric:
az = pi * (
self.nodes_x ** 2 - np.r_[0, self.nodes_x[:-1]] ** 2
)
self._cell_volumes = np.kron(self.h[2], az)
else:
self._cell_volumes = np.kron(
self.h[2],
np.kron(
self.h[1],
0.5
* (self.nodes_x[1:] ** 2 - self.nodes_x[:-1] ** 2),
),
)
return self._cell_volumes
###########################################################################
# Active and Hanging Edges and Faces
#
# To find the active edges, faces, we use krons of bools (sorry). It is
# more efficient than working with 3D matrices. For example...
#
# The computation of `ishangingFx` (is the Fx face hanging? a vector of
# True and False corresponding to each face) can be computed using krons
# of bools:
#
# hang_x = np.zeros(self._ntNx, dtype=bool)
# hang_x[0] = True
# ishangingFx_bool = np.kron(
# np.ones(self.shape_cells[2], dtype=bool), # 1 * 0 == 0
# np.kron(np.ones(self.shape_cells[1], dtype=bool), hang_x)
# )
# return self._ishanging_faces_x_bool
#
#
# This is equivalent to forming the 3D matrix and indexing the
# corresponding rows and columns (here, the hanging faces are all of
# the first x-faces along the axis of symmetry):
#
# hang_x = np.zeros(self._shape_total_faces_x, dtype=bool)
# hang_x[0, :, :] = True
# isHangingFx_bool = mkvc(hang_x)
#
#
# but krons of bools is more efficient.
#
###########################################################################
@property
def _ishanging_faces_x(self):
"""
bool vector indicating if an x-face is hanging or not
"""
if getattr(self, "_ishanging_faces_x_bool", None) is None:
# the following is equivalent to
# hang_x = np.zeros(self._shape_total_faces_x, dtype=bool)
# hang_x[0, :, :] = True
# isHangingFx_bool = mkvc(hang_x)
#
# but krons of bools is more efficient
hang_x = np.zeros(self._shape_total_nodes[0], dtype=bool)
hang_x[0] = True
self._ishanging_faces_x_bool = np.kron(
np.ones(self.shape_cells[2], dtype=bool), # 1 * 0 == 0
np.kron(np.ones(self.shape_cells[1], dtype=bool), hang_x),
)
return self._ishanging_faces_x_bool
@property
def _hanging_faces_x(self):
"""
dictionary of the indices of the hanging x-faces (keys) and a list
of indices that the eliminated faces map to (if applicable)
"""
if getattr(self, "_hanging_faces_x_dict", None) is None:
self._hanging_faces_x_dict = dict(
zip(np.nonzero(self._ishanging_faces_x)[0].tolist(), [None] * self._n_hanging_faces_x)
)
return self._hanging_faces_x_dict
@property
def _ishanging_faces_y(self):
"""
bool vector indicating if a y-face is hanging or not
"""
if getattr(self, "_ishanging_faces_y_bool", None) is None:
hang_y = np.zeros(self._shape_total_nodes[1], dtype=bool)
hang_y[-1] = True
self._ishanging_faces_y_bool = np.kron(
np.ones(self.shape_cells[2], dtype=bool),
np.kron(hang_y, np.ones(self.shape_cells[0], dtype=bool)),
)
return self._ishanging_faces_y_bool
@property
def _hanging_faces_y(self):
"""
dictionary of the indices of the hanging y-faces (keys) and a list
of indices that the eliminated faces map to (if applicable)
"""
if getattr(self, "_hanging_faces_y_dict", None) is None:
deflate_y = np.zeros(self._shape_total_nodes[1], dtype=bool)
deflate_y[0] = True
deflateFy = np.nonzero(
np.kron(
np.ones(self.shape_cells[2], dtype=bool),
np.kron(deflate_y, np.ones(self.shape_cells[0], dtype=bool)),
)
)[0].tolist()
self._hanging_faces_y_dict = dict(
zip(np.nonzero(self._ishanging_faces_y)[0].tolist(), deflateFy)
)
return self._hanging_faces_y_dict
@property
def _ishanging_faces_z(self):
"""
bool vector indicating if a z-face is hanging or not
"""
if getattr(self, "_ishanging_faces_z_bool", None) is None:
self._ishanging_faces_z_bool = np.zeros(self._n_total_faces_z, dtype=bool)
return self._ishanging_faces_z_bool
@property
def _hanging_faces_z(self):
"""
dictionary of the indices of the hanging z-faces (keys) and a list
of indices that the eliminated faces map to (if applicable)
"""
return {}
@property
def _ishanging_edges_x(self):
"""
bool vector indicating if a x-edge is hanging or not
"""
if getattr(self, "_ishanging_edges_x_bool", None) is None:
nx, ny, nz = self._shape_total_nodes
hang_y = np.zeros(ny, dtype=bool)
hang_y[-1] = True
self._ishanging_edges_x_bool = np.kron(
np.ones(nz, dtype=bool),
np.kron(hang_y, np.ones(self.shape_cells[0], dtype=bool)),
)
return self._ishanging_edges_x_bool
@property
def _hanging_edges_x(self):
"""
dictionary of the indices of the hanging x-edges (keys) and a list
of indices that the eliminated faces map to (if applicable)
"""
if getattr(self, "_hanging_edges_x_dict", None) is None:
nx, ny, nz = self._shape_total_nodes
deflate_y = np.zeros(ny, dtype=bool)
deflate_y[0] = True
deflateEx = np.nonzero(
np.kron(
np.ones(nz, dtype=bool),
np.kron(deflate_y, np.ones(self.shape_cells[0], dtype=bool)),
)
)[0].tolist()
self._hanging_edges_x_dict = dict(
zip(np.nonzero(self._ishanging_edges_x)[0].tolist(), deflateEx)
)
return self._hanging_edges_x_dict
@property
def _ishanging_edges_y(self):
"""
bool vector indicating if a y-edge is hanging or not
"""
if getattr(self, "_ishanging_edges_y_bool", None) is None:
nx, ny, nz = self._shape_total_nodes
hang_x = np.zeros(nx, dtype=bool)
hang_x[0] = True
self._ishanging_edges_y_bool = np.kron(
np.ones(nz, dtype=bool),
np.kron(np.ones(self.shape_cells[1], dtype=bool), hang_x),
)
return self._ishanging_edges_y_bool
@property
def _hanging_edges_y(self):
"""
dictionary of the indices of the hanging y-edges (keys) and a list
of indices that the eliminated faces map to (if applicable)
"""
if getattr(self, "_hanging_edges_y_dict", None) is None:
self._hanging_edges_y_dict = dict(
zip(
np.nonzero(self._ishanging_edges_y)[0].tolist(),
[None] * len(self._ishanging_edges_y_bool),
)
)
return self._hanging_edges_y_dict
@property
def _axis_of_symmetry_edges_z(self):
"""
bool vector indicating if a z-edge is along the axis of symmetry or not
"""
if getattr(self, "_axis_of_symmetry_edges_z_bool", None) is None:
nx, ny, nz = self._shape_total_nodes
axis_x = np.zeros(nx, dtype=bool)
axis_x[0] = True
axis_y = np.zeros(ny, dtype=bool)
axis_y[0] = True
self._axis_of_symmetry_edges_z_bool = np.kron(
np.ones(self.shape_cells[2], dtype=bool), np.kron(axis_y, axis_x)
)
return self._axis_of_symmetry_edges_z_bool
@property
def _ishanging_edges_z(self):
"""
bool vector indicating if a z-edge is hanging or not
"""
if getattr(self, "_ishanging_edges_z_bool", None) is None:
if self.is_symmetric:
self._ishanging_edges_z_bool = np.ones(self._n_total_edges_z, dtype=bool)
else:
nx, ny, nz = self._shape_total_nodes
hang_x = np.zeros(nx, dtype=bool)
hang_x[0] = True
hang_y = np.zeros(ny, dtype=bool)
hang_y[-1] = True
hangingEz = np.kron(
np.ones(self.shape_cells[2], dtype=bool),
(
# True * False = False
np.kron(np.ones(ny, dtype=bool), hang_x)
| np.kron(hang_y, np.ones(nx, dtype=bool))
),
)
self._ishanging_edges_z_bool = hangingEz & ~self._axis_of_symmetry_edges_z
return self._ishanging_edges_z_bool
@property
def _hanging_edges_z(self):
"""
dictionary of the indices of the hanging z-edges (keys) and a list
of indices that the eliminated faces map to (if applicable)
"""
if getattr(self, "_hanging_edges_z_dict", None) is None:
nx, ny, nz = self._shape_total_nodes
# deflate
deflateEz = np.hstack(
[
np.hstack(
[np.zeros(ny - 1, dtype=int), np.arange(1, nx, dtype=int)]
)
+ i * int(nx * ny)
for i in range(self.shape_cells[2])
]
)
deflate = zip(np.nonzero(self._ishanging_edges_z)[0].tolist(), deflateEz)
self._hanging_edges_z_dict = dict(deflate)
return self._hanging_edges_z_dict
@property
def _axis_of_symmetry_nodes(self):
"""
bool vector indicating if a node is along the axis of symmetry or not
"""
if getattr(self, "_axis_of_symmetry_nodes_bool", None) is None:
nx, ny, nz = self._shape_total_nodes
axis_x = np.zeros(nx, dtype=bool)
axis_x[0] = True
axis_y = np.zeros(ny, dtype=bool)
axis_y[0] = True
self._axis_of_symmetry_nodes_bool = np.kron(
np.ones(nz, dtype=bool), np.kron(axis_y, axis_x)
)
return self._axis_of_symmetry_nodes_bool
@property
def _ishanging_nodes(self):
"""
bool vector indicating if a node is hanging or not
"""
if getattr(self, "_ishanging_nodes_bool", None) is None:
nx, ny, nz = self._shape_total_nodes
hang_x = np.zeros(nx, dtype=bool)
hang_x[0] = True
hang_y = np.zeros(ny, dtype=bool)
hang_y[-1] = True
hangingN = np.kron(
np.ones(nz, dtype=bool),
(
np.kron(np.ones(ny, dtype=bool), hang_x)
| np.kron(hang_y, np.ones(nx, dtype=bool))
),
)
self._ishanging_nodes_bool = hangingN & ~self._axis_of_symmetry_nodes
return self._ishanging_nodes_bool
@property
def _hanging_nodes(self):
"""
dictionary of the indices of the hanging nodes (keys) and a list
of indices that the eliminated faces map to (if applicable)
"""
if getattr(self, "_hanging_nodes_dict", None) is None:
nx, ny, nz = self._shape_total_nodes
# go by layer
deflateN = np.hstack(
[
np.hstack(
[np.zeros(ny - 1, dtype=int), np.arange(1, nx, dtype=int)]
)
+ i * int(nx * ny)
for i in range(nz)
]
).tolist()
self._hanging_nodes_dict = dict(
zip(np.nonzero(self._ishanging_nodes)[0].tolist(), deflateN)
)
return self._hanging_nodes_dict
####################################################
# Grids
####################################################
@property
def _nodes_full(self):
"""
Full Nodal grid (including hanging nodes)
"""
return ndgrid([self.nodes_x, self._nodes_y_full, self.nodes_z])
@property
def nodes(self):
"""
Nodal grid in cylindrical coordinates :math:`(r, \\theta, z)`.
Nodes do not exist in a cylindrically symmetric mesh.
Returns
-------
numpy.ndarray
grid locations of nodes
"""
if self.is_symmetric:
self._nodes = self._nodes_full
if getattr(self, "_nodes", None) is None:
self._nodes = self._nodes_full[~self._ishanging_nodes, :]
return self._nodes
@property
def _faces_x_full(self):
"""
Full Fx grid (including hanging faces)
"""
return ndgrid(
[self.nodes_x, self.cell_centers_y, self.cell_centers_z]
)
@property
def faces_x(self):
"""
Grid of x-faces (radial-faces) in cylindrical coordinates
:math:`(r, \\theta, z)`.
Returns
-------
numpy.ndarray
grid locations of radial faces
"""
if getattr(self, "_faces_x", None) is None:
if self.is_symmetric:
return super().faces_x
else:
self._faces_x = self._faces_x_full[~self._ishanging_faces_x, :]
return self._faces_x
@property
def _edges_y_full(self):
"""
Full grid of y-edges (including eliminated edges)
"""
return super().edges_y
@property
def edges_y(self):
"""
Grid of y-edges (azimuthal-faces) in cylindrical coordinates
:math:`(r, \\theta, z)`.
Returns
-------
numpy.ndarray
grid locations of azimuthal faces
"""
if getattr(self, "_edges_y", None) is None:
if self.is_symmetric:
return self._edges_y_full
else:
self._edges_y = self._edges_y_full[~self._ishanging_edges_y, :]
return self._edges_y
@property
def _edges_z_full(self):
"""
Full z-edge grid (including hanging edges)
"""
return ndgrid([self.nodes_x, self._nodes_y_full, self.cell_centers_z])
@property
def edges_z(self):
"""
Grid of z-faces (vertical-faces) in cylindrical coordinates
:math:`(r, \\theta, z)`.
Returns
-------
numpy.ndarray
grid locations of radial faces
"""
if getattr(self, "_edges_z", None) is None:
if self.is_symmetric:
self._edges_z = None
else:
self._edges_z = self._edges_z_full[~self._ishanging_edges_z, :]
return self._edges_z
####################################################
# Operators
####################################################
@property
def face_divergence(self):
"""
Construct divergence operator (faces to cell-centres).
"""
if getattr(self, "_face_divergence", None) is None:
# Compute faceDivergence operator on faces
D1 = self.face_x_divergence
D3 = self.face_z_divergence
if self.is_symmetric:
D = sp.hstack((D1, D3), format="csr")
elif self.shape_cells[1] > 1:
D2 = self.face_y_divergence
D = sp.hstack((D1, D2, D3), format="csr")
self._face_divergence = D
return self._face_divergence
@property
def face_x_divergence(self):
"""
Construct divergence operator in the x component
(faces to cell-centres).
"""
if getattr(self, "_face_x_divergence", None) is None:
if self.is_symmetric:
ncx, ncy, ncz = self.shape_cells
D1 = kron3(speye(ncz), speye(ncy), ddx(ncx)[:, 1:])
else:
D1 = super()._face_x_divergence_stencil
S = self._face_x_areas_full
V = self.cell_volumes
self._face_x_divergence = sdiag(1 / V) * D1 * sdiag(S)
if not self.is_symmetric:
self._face_x_divergence = (
self._face_x_divergence * self._deflation_matrix("Fx", as_ones=True).T
)
return self._face_x_divergence
@property
def face_y_divergence(self):
"""
Construct divergence operator in the y component
(faces to cell-centres).
"""
if getattr(self, "_face_y_divergence", None) is None:
D2 = super()._face_y_divergence_stencil
S = self._face_y_areas_full # self.reshape(self.face_areas, 'F', 'Fy', 'V')
V = self.cell_volumes
self._face_y_divergence = (
sdiag(1 / V)
* D2
* sdiag(S)
* self._deflation_matrix("Fy", as_ones=True).T
)
return self._face_y_divergence
@property
def face_z_divergence(self):
"""
Construct divergence operator in the z component
(faces to cell-centres).
"""
if getattr(self, "_face_z_divergence", None) is None:
D3 = super()._face_z_divergence_stencil
S = self._face_z_areas_full
V = self.cell_volumes
self._face_z_divergence = sdiag(1 / V) * D3 * sdiag(S)
return self._face_z_divergence
# @property
# def stencil_cell_gradient_x(self):
# n = self.vnC
# if self.is_symmetric:
# G1 = sp.kron(speye(n[2]), ddxCellGrad(n[0], BC))
# else:
# G1 = self._deflation_matrix('Fx').T * kron3(
# speye(n[2]), speye(n[1]), ddxCellGrad(n[0], BC)
# )
# return G1
@property
def cell_gradient_x(self):
raise NotImplementedError("Cell Grad is not yet implemented.")
# if getattr(self, '_cellGradx', None) is None:
# G1 = super(CylindricalMesh, self).stencil_cell_gradient_x
# V = self._deflation_matrix('F', withHanging='True', as_ones='True')*self.aveCC2F*self.cell_volumes
# A = self.face_areas
# L = (A/V)[:self._n_total_faces_x]
# # L = self.reshape(L, 'F', 'Fx', 'V')
# # L = A[:self.nFx] / V
# self._cellGradx = self._deflation_matrix('Fx')*sdiag(L)*G1
# return self._cellGradx
@property
def stencil_cell_gradient_y(self):
raise NotImplementedError("Cell Grad is not yet implemented.")
@property
def stencil_cell_gradient_z(self):
raise NotImplementedError("Cell Grad is not yet implemented.")
@property
def stencil_cell_gradient(self):
raise NotImplementedError("Cell Grad is not yet implemented.")
@property
def cell_gradient(self):
raise NotImplementedError("Cell Grad is not yet implemented.")
# @property
# def _nodal_gradient_x_stencil(self):
# if self.is_symmetric:
# return None
# return kron3(speye(self.shape_nodes[2]), speye(self.shape_nodes[1]), ddx(self.shape_cells[0]))
# @property
# def _nodal_gradient_y_stencil(self):
# if self.is_symmetric:
# None
# # return kron3(speye(self.shape_nodes[2]), ddx(self.shape_cells[1]), speye(self.shape_nodes[0])) * self._deflation_matrix('Ey')
# return kron3(speye(self.shape_nodes[2]), ddx(self.shape_cells[1]), speye(self.shape_nodes[0]))
# @property
# def _nodal_gradient_z_stencil(self):
# if self.is_symmetric:
# return None
# return kron3(ddx(self.shape_cells[2]), speye(self.shape_nodes[1]), speye(self.shape_nodes[0]))
# @property
# def _nodal_gradient_stencil(self):
# if self.is_symmetric:
# return None
# else:
# G = self._deflation_matrix('E').T * sp.vstack((
# self._nodal_gradient_x_stencil,
# self._nodal_gradient_y_stencil,
# self._nodal_gradient_z_stencil
# ), format="csr") * self._deflation_matrix('N')
# return G
@property
def nodal_gradient(self):
"""Construct gradient operator (nodes to edges)."""
if self.is_symmetric:
return None
raise NotImplementedError("nodalGrad not yet implemented")
@property
def nodal_laplacian(self):
"""Construct laplacian operator (nodes to edges)."""
raise NotImplementedError("nodalLaplacian not yet implemented")
@property
def edge_curl(self):
"""
The edgeCurl (edges to faces)
Returns
-------
scipy.sparse.csr_matrix
edge curl operator
"""
if getattr(self, "_edge_curl", None) is None:
A = self.face_areas
E = self.edge_lengths
if self.is_symmetric:
nCx, nCy, nCz = self.shape_cells
# 1D Difference matricies
dr = sp.spdiags(
(np.ones((nCx + 1, 1)) * [-1, 1]).T, [-1, 0], nCx, nCx, format="csr"
)
dz = sp.spdiags(
(np.ones((nCz + 1, 1)) * [-1, 1]).T,
[0, 1],
nCz,
nCz + 1,
format="csr",
)
# 2D Difference matricies
Dr = sp.kron(sp.identity(nCz + 1), dr)
Dz = -sp.kron(dz, sp.identity(nCx))
# Edge curl operator
self._edge_curl = sdiag(1 / A) * sp.vstack((Dz, Dr)) * sdiag(E)
else:
self._edge_curl = (
sdiag(1 / self.face_areas)
* self._deflation_matrix("F", as_ones=False)
* self._edge_curl_stencil
* sdiag(self._edge_lengths_full)
* self._deflation_matrix("E", as_ones=True).T
)
return self._edge_curl
@property
def average_edge_x_to_cell(self):
"""
averaging operator of x-edges (radial) to cell centers
Returns
-------
scipy.sparse.csr_matrix
matrix that averages from x-edges to cell centers
"""
if self.is_symmetric:
raise Exception("There are no x-edges on a cyl symmetric mesh")
return (
kron3(
av(self.shape_cells[2]),
av(self.shape_cells[1]),
speye(self.shape_cells[0]),
)
* self._deflation_matrix("Ex", as_ones=True).T
)
@property
def average_edge_y_to_cell(self):
"""
averaging operator of y-edges (azimuthal) to cell centers
Returns
-------
scipy.sparse.csr_matrix
matrix that averages from y-edges to cell centers
"""
if self.is_symmetric:
avR = av(self.shape_cells[0])[:, 1:]
return sp.kron(av(self.shape_cells[2]), avR, format="csr")
else:
return (
kron3(
av(self.shape_cells[2]),
speye(self.shape_cells[1]),
av(self.shape_cells[0]),
)
* self._deflation_matrix("Ey", as_ones=True).T
)
@property
def average_edge_z_to_cell(self):
"""
averaging operator of z-edges to cell centers
Returns
-------
scipy.sparse.csr_matrix
matrix that averages from z-edges to cell centers
"""
if self.is_symmetric:
raise Exception("There are no z-edges on a cyl symmetric mesh")
return (
kron3(
speye(self.shape_cells[2]),
av(self.shape_cells[1]),
av(self.shape_cells[0]),
)
* self._deflation_matrix("Ez", as_ones=True).T
)
@property
def average_edge_to_cell(self):
"""
averaging operator of edges to cell centers
Returns
-------
scipy.sparse.csr_matrix
matrix that averages from edges to cell centers
"""
if getattr(self, "_average_edge_to_cell", None) is None:
# The number of cell centers in each direction
# n = self.vnC
if self.is_symmetric:
self._average_edge_to_cell = self.aveEy2CC
else:
self._average_edge_to_cell = (
1.0
/ self.dim
* sp.hstack(
(self.aveEx2CC, self.aveEy2CC, self.aveEz2CC), format="csr"
)
)
return self._average_edge_to_cell
@property
def average_edge_to_cell_vector(self):
"""
averaging operator of edges to a cell centered vector
Returns
-------
scipy.sparse.csr_matrix
matrix that averages from edges to cell centered vectors
"""
if self.is_symmetric:
return self.average_edge_to_cell
else:
if getattr(self, "_average_edge_to_cell_vector", None) is None:
self._average_edge_to_cell_vector = sp.block_diag(
(self.aveEx2CC, self.aveEy2CC, self.aveEz2CC), format="csr"
)
return self._average_edge_to_cell_vector
@property
def average_face_x_to_cell(self):
"""
averaging operator of x-faces (radial) to cell centers
Returns
-------
scipy.sparse.csr_matrix
matrix that averages from x-faces to cell centers
"""
avR = av(self.vnC[0])[
:, 1:
] # TODO: this should be handled by a deflation matrix
return kron3(speye(self.vnC[2]), speye(self.vnC[1]), avR)
@property
def average_face_y_to_cell(self):
"""
averaging operator of y-faces (azimuthal) to cell centers
Returns
-------
scipy.sparse.csr_matrix
matrix that averages from y-faces to cell centers
"""
return (
kron3(speye(self.vnC[2]), av(self.vnC[1]), speye(self.vnC[0]))
* self._deflation_matrix("Fy", as_ones=True).T
)
@property
def average_face_z_to_cell(self):
"""
averaging operator of z-faces (vertical) to cell centers
Returns
-------
scipy.sparse.csr_matrix
matrix that averages from z-faces to cell centers
"""
return kron3(av(self.vnC[2]), speye(self.vnC[1]), speye(self.vnC[0]))
@property
def average_face_to_cell(self):
"""
averaging operator of faces to cell centers
Returns
-------
scipy.sparse.csr_matrix
matrix that averages from faces to cell centers
"""
if getattr(self, "_average_face_to_cell", None) is None:
if self.is_symmetric:
self._average_face_to_cell = 0.5 * (
sp.hstack((self.aveFx2CC, self.aveFz2CC), format="csr")
)
else:
self._average_face_to_cell = (
1.0
/ self.dim
* (
sp.hstack(
(self.aveFx2CC, self.aveFy2CC, self.aveFz2CC), format="csr"
)
)
)
return self._average_face_to_cell
@property
def average_face_to_cell_vector(self):
"""
averaging operator of x-faces (radial) to cell centered vectors
Returns
-------
scipy.sparse.csr_matrix
matrix that averages from faces to cell centered vectors
"""
if getattr(self, "_average_face_to_cell_vector", None) is None:
# n = self.vnC
if self.is_symmetric:
self._average_face_to_cell_vector = sp.block_diag(
(self.aveFx2CC, self.aveFz2CC), format="csr"
)
else:
self._average_face_to_cell_vector = sp.block_diag(
(self.aveFx2CC, self.aveFy2CC, self.aveFz2CC), format="csr"
)
return self._average_face_to_cell_vector
####################################################
# Deflation Matrices
####################################################
def _deflation_matrix(self, location, as_ones=False):
"""
construct the deflation matrix to remove hanging edges / faces / nodes
from the operators
"""
location = self._parse_location_type(location)
if location not in ["nodes", "faces", "faces_x", "faces_y", "faces_z", "edges", "edges_x", "edges_y", "edges_z", "cell_centers"]:
raise AssertionError(
"Location must be a grid location, not {}".format(location)
)
if location == "cell_centers":
return speye(self.nC)
elif location in ["edges", "faces"]:
if self.is_symmetric:
if location == "edges":
return self._deflation_matrix("edges_y", as_ones=as_ones)
elif location == "faces":
return sp.block_diag(
[
self._deflation_matrix(location + coord, as_ones=as_ones)
for coord in ["_x", "_z"]
]
)
return sp.block_diag(
[
self._deflation_matrix(location + coord, as_ones=as_ones)
for coord in ["_x", "_y", "_z"]
]
)
R = speye(getattr(self, "_n_total_{}".format(location)))
hanging_dict = getattr(self, "_hanging_{}".format(location))
nothanging = ~getattr(self, "_ishanging_{}".format(location))
# remove eliminated edges / faces (eg. Fx just doesn't exist)
hang = {k: v for k, v in hanging_dict.items() if v is not None}
values = list(hang.values())
entries = np.ones(len(values))
if not as_ones and len(hang) > 0:
repeats = set(values)
repeat_locs = [(np.r_[values] == repeat).nonzero()[0] for repeat in repeats]
for loc in repeat_locs:
entries[loc] = 1.0 / len(loc)
Hang = sp.csr_matrix(
(entries, (values, list(hang.keys()))),
shape=(
getattr(self, "_n_total_{}".format(location)),
getattr(self, "_n_total_{}".format(location)),
),
)
R = R + Hang
R = R[nothanging, :]
if not as_ones:
R = sdiag(1.0 / R.sum(1)) * R
return R
####################################################
# Interpolation
####################################################
def get_interpolation_matrix(
self, loc, location_type="cell_centers", zeros_outside=False, **kwargs
):
"""Produces interpolation matrix
Parameters
----------
loc : numpy.ndarray
Location of points to interpolate to
location_type : str
What to interpolate location_type can be::
'Ex', 'edges_x' -> x-component of field defined on x edges
'Ey', 'edges_y' -> y-component of field defined on y edges
'Ez', 'edges_z' -> z-component of field defined on z edges
'Fx', 'faces_x' -> x-component of field defined on x faces
'Fy', 'faces_y' -> y-component of field defined on y faces
'Fz', 'faces_z' -> z-component of field defined on z faces
'N', 'nodes' -> scalar field defined on nodes
'CC', 'cell_centers' -> scalar field defined on cell centers
'CCVx', 'cell_centers_x' -> x-component of vector field defined on cell centers
'CCVy', 'cell_centers_y' -> y-component of vector field defined on cell centers
'CCVz', 'cell_centers_z' -> z-component of vector field defined on cell centers
Returns
-------
scipy.sparse.csr_matrix
M, the interpolation matrix
"""
if "locType" in kwargs:
warnings.warn(
"The locType keyword argument has been deprecated, please use location_type. "
"This will be removed in discretize 1.0.0",
DeprecationWarning,
)
location_type = kwargs["locType"]
if "zerosOutside" in kwargs:
warnings.warn(
"The zerosOutside keyword argument has been deprecated, please use zeros_outside. "
"This will be removed in discretize 1.0.0",
DeprecationWarning,
)
zeros_outside = kwargs["zerosOutside"]
location_type = self._parse_location_type(location_type)
if self.is_symmetric and location_type in ["edges_x", "edges_z", "faces_y"]:
raise Exception(
"Symmetric CylindricalMesh does not support {0!s} interpolation, "
"as this variable does not exist.".format(location_type)
)
if location_type in ["cell_centers_x", "cell_centers_y", "cell_centers_z"]:
Q = interpolation_matrix(loc, *self.get_tensor("cell_centers"))
Z = spzeros(loc.shape[0], self.nC)
if location_type[-1] == "x":
Q = sp.hstack([Q, Z])
elif location_type[-1] == "y":
Q = sp.hstack([Q])
elif location_type[-1] == "z":
Q = sp.hstack([Z, Q])
if zeros_outside:
indZeros = np.logical_not(self.is_inside(loc))
loc[indZeros, :] = np.array([v.mean() for v in self.get_tensor("CC")])
Q[indZeros, :] = 0
return Q.tocsr()
return self._getInterpolationMat(loc, location_type, zeros_outside)
def cartesian_grid(self, location_type="cell_centers", theta_shift=None, **kwargs):
"""
Takes a grid location ('CC', 'N', 'Ex', 'Ey', 'Ez', 'Fx', 'Fy', 'Fz')
and returns that grid in cartesian coordinates
Parameters
----------
location_type : {'CC', 'N', 'Ex', 'Ey', 'Ez', 'Fx', 'Fy', 'Fz'}
grid location
theta_shift : float, optional
shift for theta
Returns
-------
numpy.ndarray
cartesian coordinates for the cylindrical grid
"""
if "locType" in kwargs:
warnings.warn(
"The locType keyword argument has been deprecated, please use location_type. "
"This will be removed in discretize 1.0.0",
DeprecationWarning,
)
location_type = kwargs["locType"]
try:
grid = getattr(self, location_type).copy()
except AttributeError:
grid = getattr(self, f"grid{location_type}").copy()
if theta_shift is not None:
grid[:, 1] = grid[:, 1] - theta_shift
return cyl2cart(grid) # TODO: account for cartesian origin
def get_interpolation_matrix_cartesian_mesh(
self, Mrect, location_type="cell_centers", location_type_to=None, **kwargs
):
"""
Takes a cartesian mesh and returns a projection to translate onto
the cartesian grid.
Parameters
----------
Mrect : discretize.base.BaseMesh
the mesh to interpolate on to
location_type : {'CC', 'N', 'Ex', 'Ey', 'Ez', 'Fx', 'Fy', 'Fz'}
grid location
location_type_to : {'CC', 'N', 'Ex', 'Ey', 'Ez', 'Fx', 'Fy', 'Fz'}, or None, optional
grid location to interpolate to. If None, the same grid type as `location_type` will be assumed
Returns
-------
scipy.sparse.csr_matrix
M, the interpolation matrix
"""
if "locType" in kwargs:
warnings.warn(
"The locType keyword argument has been deprecated, please use location_type. "
"This will be removed in discretize 1.0.0",
DeprecationWarning,
)
location_type = kwargs["locType"]
if "locTypeTo" in kwargs:
warnings.warn(
"The locTypeTo keyword argument has been deprecated, please use location_type_to. "
"This will be removed in discretize 1.0.0",
DeprecationWarning,
)
location_type_to = kwargs["locTypeTo"]
location_type = self._parse_location_type(location_type)
if not self.is_symmetric:
raise AssertionError(
"Currently we have not taken into account other projections "
"for more complicated CylindricalMeshes"
)
if location_type_to is None:
location_type_to = location_type
location_type_to = self._parse_location_type(location_type_to)
print(location_type, location_type_to)
if location_type == "faces":
# do this three times for each component
X = self.get_interpolation_matrix_cartesian_mesh(
Mrect, location_type="faces_x", location_type_to=location_type_to + "_x"
)
Y = self.get_interpolation_matrix_cartesian_mesh(
Mrect, location_type="faces_y", location_type_to=location_type_to + "_y"
)
Z = self.get_interpolation_matrix_cartesian_mesh(
Mrect, location_type="faces_z", location_type_to=location_type_to + "_z"
)
return sp.vstack((X, Y, Z))
if location_type == "edges":
X = self.get_interpolation_matrix_cartesian_mesh(
Mrect, location_type="edges_x", location_type_to=location_type_to + "_x"
)
Y = self.get_interpolation_matrix_cartesian_mesh(
Mrect, location_type="edges_y", location_type_to=location_type_to + "_y"
)
Z = spzeros(getattr(Mrect, "n_" + location_type_to + "_z"), self.n_edges)
return sp.vstack((X, Y, Z))
grid = getattr(Mrect, location_type_to)
# This is unit circle stuff, 0 to 2*pi, starting at x-axis, rotating
# counter clockwise in an x-y slice
theta = (
-np.arctan2(
grid[:, 0] - self.cartesian_origin[0],
grid[:, 1] - self.cartesian_origin[1],
)
+ np.pi / 2
)
theta[theta < 0] += np.pi * 2.0
r = (
(grid[:, 0] - self.cartesian_origin[0]) ** 2
+ (grid[:, 1] - self.cartesian_origin[1]) ** 2
) ** 0.5
if location_type in ["cell_centers", "nodes", "faces_z", "edges_z"]:
G, proj = np.c_[r, theta, grid[:, 2]], np.ones(r.size)
else:
dotMe = {
"faces_x": Mrect.face_normals[:Mrect.nFx, :],
"faces_y": Mrect.face_normals[Mrect.nFx:(Mrect.nFx + Mrect.nFy), :],
"faces_z": Mrect.face_normals[-Mrect.nFz:, :],
"edges_x": Mrect.edge_tangents[: Mrect.nEx, :],
"edges_y": Mrect.edge_tangents[Mrect.nEx: (Mrect.nEx + Mrect.nEy), :],
"edges_z": Mrect.edge_tangents[-Mrect.nEz:, :],
}[location_type_to]
if "faces" in location_type:
normals = np.c_[np.cos(theta), np.sin(theta), np.zeros(theta.size)]
proj = (normals * dotMe).sum(axis=1)
elif "edges" in location_type:
tangents = np.c_[-np.sin(theta), np.cos(theta), np.zeros(theta.size)]
proj = (tangents * dotMe).sum(axis=1)
G = np.c_[r, theta, grid[:, 2]]
interp_type = location_type
if interp_type == "faces_y":
interp_type = "faces_x"
elif interp_type == "edges_x":
interp_type = "edges_y"
Pc2r = self.get_interpolation_matrix(G, interp_type)
Proj = sdiag(proj)
return Proj * Pc2r
# DEPRECATIONS
vol = deprecate_property("cell_volumes", "vol", removal_version="1.0.0")
area = deprecate_property("face_areas", "area", removal_version="1.0.0")
areaFx = deprecate_property("face_x_areas", "areaFx", removal_version="1.0.0")
areaFy = deprecate_property("face_y_areas", "areaFy", removal_version="1.0.0")
areaFz = deprecate_property("face_z_areas", "areaFz", removal_version="1.0.0")
edgeEx = deprecate_property("edge_x_lengths", "edgeEx", removal_version="1.0.0")
edgeEy = deprecate_property("edge_y_lengths", "edgeEy", removal_version="1.0.0")
edgeEz = deprecate_property("edge_z_lengths", "edgeEz", removal_version="1.0.0")
edge = deprecate_property("edge_lengths", "edge", removal_version="1.0.0")
isSymmetric = deprecate_property(
"is_symmetric", "isSymmetric", removal_version="1.0.0"
)
cartesianOrigin = deprecate_property(
"cartesian_origin", "cartesianOrigin", removal_version="1.0.0"
)
getInterpolationMatCartMesh = deprecate_method(
"get_interpolation_matrix_cartesian_mesh",
"getInterpolationMatCartMesh",
removal_version="1.0.0",
)
cartesianGrid = deprecate_method(
"cartesian_grid", "cartesianGrid", removal_version="1.0.0"
)
@deprecate_class(removal_version="1.0.0")
class CylMesh(CylindricalMesh):
pass
|
// COPYRIGHT © 2020 Esri
//
// All rights reserved under the copyright laws of the United States
// and applicable international laws, treaties, and conventions.
//
// This material is licensed for use under the Esri Master License
// Agreement (MLA), and is bound by the terms of that agreement.
// You may redistribute and use this code without modification,
// provided you adhere to the terms of the MLA and include this
// copyright notice.
//
// See use restrictions at http://www.esri.com/legal/pdfs/mla_e204_e300/english
//
// For additional information, contact:
// Environmental Systems Research Institute, Inc.
// Attn: Contracts and Legal Services Department
// 380 New York Street
// Redlands, California, USA 92373
// USA
//
// email: contracts@esri.com
//
// See http://js.arcgis.com/3.33/esri/copyright.txt for details.
define({distToNearest:"Khoảng cách đến Đối tượng Gần nhất",attrOfInterest:"Thuộc tính của Đối tượng Gần nhất",summaryNearby:"Tóm tắt về thông tin Lân cận",summaryIntersecting:"Tóm tắt về thông tin Giao cắt",distToNearestLabel:"Khoảng cách từ tâm bin đến đối tượng gần nhất trong lớp đầu vào",attrOfInterestLabel:"Giá trị của một trường cụ thể từ đối tượng gần nhất từ lớp đầu vào",summaryNearbyLabel:"Một phép thống kê được tính toán trên tất cả đối tượng tìm thấy với khoảng cách cụ thể của tâm bin",summaryIntersectingLabel:"Một phép thống kê đã tính toán thống kê trên tất cả đối tượng giao cắt bin",maxDistancefromCtr:"Khoảng cách tối đa tính từ tâm bin",fieldToIncude:"Trường cần bao gồm",statstoCalculate:"Phép thống kê cần tính",summFeatuesWithin:"Tóm tắt các đối tượng trong",smallMaxDistErrorMsg:"Khoảng cách tối đa tính từ tâm bin phải lớn hơn kích thước bin.",smallSumFeaturesErrorMsg:"Khoảng cách tối đa tính từ tâm bin phải lớn hơn kích thước bin."});
|
'use strict';
/**
* Returns true if word occurrs in the specified word snaking puzzle.
* Each words can be constructed using "snake" path inside a grid with top, left, right and bottom directions.
* Each char can be used only once ("snake" should not cross itself).
*
* @param {array} puzzle
* @param {array} searchStr
* @return {bool}
*
* @example
* var puzzle = [
* 'ANGULAR',
* 'REDNCAE',
* 'RFIDTCL',
* 'AGNEGSA',
* 'YTIRTSP',
* ];
* 'ANGULAR' => true (first row)
* 'REACT' => true (starting from the top-right R adn follow the ↓ ← ← ↓ )
* 'UNDEFINED' => true
* 'RED' => true
* 'STRING' => true
* 'CLASS' => true
* 'ARRAY' => true (first column)
* 'FUNCTION' => false
* 'NULL' => false
*/
function findStringInSnakingPuzzle(puzzle, searchStr) {
puzzle = puzzle.map(a => a.split(''));
let neighbours = (x, y, stack) => {
return [[y + 1, x], [y, x + 1], [y - 1, x], [y, x - 1]].filter(a => {
return a[0] >= 0 && a[0] < puzzle.length && a[1] >= 0 && a[1] < puzzle[0].length
&& !stack.some(b => a[0] == b[0] && a[1] == b[1]);
}).map(a => ({ v: puzzle[a[0]][a[1]], x: a[1], y: a[0] }));
};
let next = (n, stack) => {
return neighbours(n.x, n.y, stack).filter(a => a.v === searchStr[stack.length + 1]);
};
return searchStr.length === 0 || (function test(positions, stack) {
return stack.map(a =>
puzzle[a[0]][a[1]]).join('') === searchStr ||
positions.some(a => {
return test(next(a, stack), stack.concat([[a.y, a.x]]));
});
})(puzzle.map((a, b) =>
a.map((c, d) => ({ v: c, x: d, y: b })))
.reduce((a, b) =>
a.concat(b), [])
.filter(a => a.v === searchStr[0]), []);
}
/**
* Returns all permutations of the specified string.
* Assume all chars in the specified string are different.
* The order of permutations does not matter.
*
* @param {string} chars
* @return {Iterable.<string>} all posible strings constructed with the chars from the specfied string
*
* @example
* 'ab' => 'ab','ba'
* 'abc' => 'abc','acb','bac','bca','cab','cba'
*/
function* getPermutations(chars) {
function *HeapsAlgorithm(n, A) {
if (n == 1) {
yield A.join('');
} else {
let temp;
for (let i = 0; i < n; i++) {
yield *HeapsAlgorithm(n - 1, A);
if (n % 2 == 0) {
temp = A[i];
A[i] = A[n - 1];
A[n - 1] = temp;
} else {
temp = A[0];
A[0] = A[n - 1];
A[n - 1] = temp;
}
}
}
}
yield *HeapsAlgorithm(chars.length, chars.split(''));
}
/**
* Returns the most profit from stock quotes.
* Stock quotes are stores in an array in order of date.
* The stock profit is the difference in prices in buying and selling stock.
* Each day, you can either buy one unit of stock, sell any number of stock units you have already bought, or do nothing.
* Therefore, the most profit is the maximum difference of all pairs in a sequence of stock prices.
*
* @param {array} quotes
* @return {number} max profit
*
* @example
* [ 1, 2, 3, 4, 5, 6] => 15 (buy at 1,2,3,4,5 and then sell all at 6)
* [ 6, 5, 4, 3, 2, 1] => 0 (nothing to buy)
* [ 1, 6, 5, 10, 8, 7 ] => 18 (buy at 1,6,5 and sell all at 10)
*/
function getMostProfitFromStockQuotes(quotes) {
let profit = 0, count = quotes.length;
while(--count > 0) {
while(count >= 0 && quotes[count] < quotes[count - 1]) {
count--;
}
let end = count--;
while(count >= 0 && quotes[count] < quotes[end]) {
count--;
}
count++;
if (count >= 0) {
profit += quotes[end] * (end - count) - quotes.slice(count, end).reduce((a, b) => a + b, 0);
}
}
return profit;
}
/**
* Class representing the url shorting helper.
* Feel free to implement any algorithm, but do not store link in the key\value stores.
* The short link can be at least 1.5 times shorter than the original url.
*
* @class
*
* @example
*
* var urlShortener = new UrlShortener();
* var shortLink = urlShortener.encode('https://en.wikipedia.org/wiki/URL_shortening');
* var original = urlShortener.decode(shortLink); // => 'https://en.wikipedia.org/wiki/URL_shortening'
*
*/
let store = new Map(), id = 0, generator = url => {
store.set(++id, url);
return id;
};
function UrlShortener() {
this.urlAllowedChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"+
"abcdefghijklmnopqrstuvwxyz"+
"0123456789-_.~!*'();:@&=+$,/?#[]";
}
UrlShortener.prototype = {
encode: function(url) {
let str = '', num = generator(url);
while (num > 0) {
str = this.urlAllowedChars.charAt(num % this.urlAllowedChars.length) + str;
num = Math.floor(num / this.urlAllowedChars.length);
}
return 'https://test.go/' + str;
},
decode: function(code) {
code = code.split('https://test.go/')[1];
let num = 0;
for (var i = 0; i < code.length; i++) {
num = num * this.urlAllowedChars.length + this.urlAllowedChars.indexOf(code.charAt(i));
}
return store.get(num);
},
constructor: UrlShortener
}
module.exports = {
findStringInSnakingPuzzle: findStringInSnakingPuzzle,
getPermutations: getPermutations,
getMostProfitFromStockQuotes: getMostProfitFromStockQuotes,
UrlShortener: UrlShortener
};
|
/*
* turnstile_multihop: Tests turnstile and multi hop priority propagation.
*/
#ifdef T_NAMESPACE
#undef T_NAMESPACE
#endif
#include <darwintest.h>
#include <darwintest_multiprocess.h>
#include <dispatch/dispatch.h>
#include <pthread.h>
#include <launch.h>
#include <mach/mach.h>
#include <mach/message.h>
#include <mach/mach_voucher.h>
#include <pthread/workqueue_private.h>
#include <voucher/ipc_pthread_priority_types.h>
#include <servers/bootstrap.h>
#include <stdlib.h>
#include <sys/event.h>
#include <unistd.h>
#include <crt_externs.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/sysctl.h>
#include <libkern/OSAtomic.h>
#include <sys/wait.h>
#include "turnstile_multihop_helper.h"
T_GLOBAL_META(T_META_NAMESPACE("xnu.turnstile_multihop"));
#define HELPER_TIMEOUT_SECS (3000)
struct test_msg {
mach_msg_header_t header;
mach_msg_body_t body;
mach_msg_port_descriptor_t port_descriptor;
};
static boolean_t spin_for_ever = false;
static void
thread_create_at_qos(qos_class_t qos, void * (*function)(void *));
static uint64_t
nanoseconds_to_absolutetime(uint64_t nanoseconds);
static int
sched_create_load_at_qos(qos_class_t qos, void **load_token);
static int
sched_terminate_load(void *load_token) __unused;
static void do_work(int num);
static void
dispatch_sync_cancel(mach_port_t owner_thread, qos_class_t promote_qos);
static void *sched_load_thread(void *);
struct load_token_context {
volatile int threads_should_exit;
int thread_count;
qos_class_t qos;
pthread_t *threads;
};
static struct mach_timebase_info sched_mti;
static pthread_once_t sched_mti_once_control = PTHREAD_ONCE_INIT;
static void
sched_mti_init(void)
{
mach_timebase_info(&sched_mti);
}
uint64_t
nanoseconds_to_absolutetime(uint64_t nanoseconds)
{
pthread_once(&sched_mti_once_control, sched_mti_init);
return (uint64_t)(nanoseconds * (((double)sched_mti.denom) / ((double)sched_mti.numer)));
}
static int
sched_create_load_at_qos(qos_class_t qos, void **load_token)
{
struct load_token_context *context = NULL;
int ret;
int ncpu;
size_t ncpu_size = sizeof(ncpu);
int nthreads;
int i;
pthread_attr_t attr;
ret = sysctlbyname("hw.ncpu", &ncpu, &ncpu_size, NULL, 0);
if (ret == -1) {
T_LOG("sysctlbyname(hw.ncpu)");
return errno;
}
T_QUIET; T_LOG("%s: Detected %d CPUs\n", __FUNCTION__, ncpu);
nthreads = ncpu;
T_QUIET; T_LOG("%s: Will create %d threads\n", __FUNCTION__, nthreads);
ret = pthread_attr_init(&attr);
T_QUIET; T_ASSERT_MACH_SUCCESS(ret, "pthread_attr_init");
if (&pthread_attr_set_qos_class_np) {
ret = pthread_attr_set_qos_class_np(&attr, qos, 0);
T_QUIET; T_ASSERT_MACH_SUCCESS(ret, "pthread_attr_set_qos_class_np");
}
context = calloc(1, sizeof(*context));
if (context == NULL) {
T_QUIET; T_LOG("calloc returned error"); return ENOMEM;
}
context->threads_should_exit = 0;
context->thread_count = nthreads;
context->qos = qos;
context->threads = calloc((unsigned int)nthreads, sizeof(pthread_t));
OSMemoryBarrier();
for (i = 0; i < nthreads; i++) {
ret = pthread_create(&context->threads[i], &attr, sched_load_thread, context);
T_QUIET; T_ASSERT_MACH_SUCCESS(ret, "pthread_create");
T_QUIET; T_LOG("%s: Created thread %d (%p)\n", __FUNCTION__, i, (void *)context->threads[i]);
}
ret = pthread_attr_destroy(&attr);
T_QUIET; T_ASSERT_MACH_SUCCESS(ret, "pthread_attr_destroy");
*load_token = context;
return 0;
}
static void *
sched_load_thread(void *arg)
{
struct load_token_context *context = (struct load_token_context *)arg;
T_QUIET; T_LOG("%s: Thread started %p\n", __FUNCTION__, (void *)pthread_self());
while (!context->threads_should_exit) {
uint64_t start = mach_absolute_time();
uint64_t end = start + nanoseconds_to_absolutetime(900ULL * NSEC_PER_MSEC);
while ((mach_absolute_time() < end) && !context->threads_should_exit) {
;
}
}
T_QUIET; T_LOG("%s: Thread terminating %p\n", __FUNCTION__, (void *)pthread_self());
return NULL;
}
static int
sched_terminate_load(void *load_token)
{
int ret;
int i;
struct load_token_context *context = (struct load_token_context *)load_token;
context->threads_should_exit = 1;
OSMemoryBarrier();
for (i = 0; i < context->thread_count; i++) {
T_QUIET; T_LOG("%s: Joining thread %d (%p)\n", __FUNCTION__, i, (void *)context->threads[i]);
ret = pthread_join(context->threads[i], NULL);
T_QUIET; T_ASSERT_MACH_SUCCESS(ret, "pthread_join");
}
free(context->threads);
free(context);
return 0;
}
// Find the first num primes, simply as a means of doing work
static void
do_work(int num)
{
volatile int i = 3, count, c;
for (count = 2; count <= num;) {
for (c = 2; c <= i; c++) {
if (i % c == 0) {
break;
}
}
if (c == i) {
count++;
}
i++;
}
}
#pragma mark pthread callbacks
static void
worker_cb(pthread_priority_t __unused priority)
{
T_FAIL("a worker thread was created");
}
static void
event_cb(void ** __unused events, int * __unused nevents)
{
T_FAIL("a kevent routine was called instead of workloop");
}
static uint32_t
get_user_promotion_basepri(void)
{
mach_msg_type_number_t count = THREAD_POLICY_STATE_COUNT;
struct thread_policy_state thread_policy;
boolean_t get_default = FALSE;
mach_port_t thread_port = pthread_mach_thread_np(pthread_self());
kern_return_t kr = thread_policy_get(thread_port, THREAD_POLICY_STATE,
(thread_policy_t)&thread_policy, &count, &get_default);
T_QUIET; T_ASSERT_MACH_SUCCESS(kr, "thread_policy_get");
return thread_policy.thps_user_promotion_basepri;
}
#define LISTENER_WLID 0x100
#define CONN_WLID 0x200
static uint32_t
register_port_options(void)
{
return MACH_RCV_MSG | MACH_RCV_LARGE | MACH_RCV_LARGE_IDENTITY |
MACH_RCV_TRAILER_ELEMENTS(MACH_RCV_TRAILER_CTX) |
MACH_RCV_TRAILER_TYPE(MACH_MSG_TRAILER_FORMAT_0) |
MACH_RCV_VOUCHER;
}
static void
register_port(uint64_t wlid, mach_port_t port)
{
int r;
struct kevent_qos_s kev = {
.ident = port,
.filter = EVFILT_MACHPORT,
.flags = EV_ADD | EV_UDATA_SPECIFIC | EV_DISPATCH | EV_VANISHED,
.fflags = register_port_options(),
.data = 1,
.qos = (int32_t)_pthread_qos_class_encode(QOS_CLASS_MAINTENANCE, 0, 0)
};
struct kevent_qos_s kev_err = { 0 };
/* Setup workloop for mach msg rcv */
r = kevent_id(wlid, &kev, 1, &kev_err, 1, NULL,
NULL, KEVENT_FLAG_WORKLOOP | KEVENT_FLAG_ERROR_EVENTS);
T_QUIET; T_ASSERT_POSIX_SUCCESS(r, "kevent_id");
T_QUIET; T_ASSERT_EQ(r, 0, "no errors returned from kevent_id");
}
/*
* Basic WL handler callback, it checks the
* effective Qos of the servicer thread.
*/
static void
workloop_cb_test_intransit(uint64_t *workloop_id, void **eventslist, int *events)
{
static bool got_peer;
struct kevent_qos_s *kev = eventslist[0];
mach_msg_header_t *hdr;
struct test_msg *tmsg;
T_LOG("Workloop handler %s called. Received message on 0x%llx",
__func__, *workloop_id);
/* Skip the test if we can't check Qos */
if (geteuid() != 0) {
T_SKIP("kevent_qos test requires root privileges to run.");
}
T_QUIET; T_ASSERT_EQ(*events, 1, "should have one event");
hdr = (mach_msg_header_t *)kev->ext[0];
T_ASSERT_NOTNULL(hdr, "has a message");
T_ASSERT_EQ(hdr->msgh_size, (uint32_t)sizeof(struct test_msg), "of the right size");
tmsg = (struct test_msg *)hdr;
switch (*workloop_id) {
case LISTENER_WLID:
T_LOG("Registering peer connection");
T_QUIET; T_ASSERT_FALSE(got_peer, "Should not have seen peer yet");
got_peer = true;
break;
case CONN_WLID:
T_LOG("Received message on peer");
break;
default:
T_FAIL("???");
}
sleep(5);
T_LOG("Do some CPU work.");
do_work(5000);
/* Check if the override now is IN + 60 boost */
T_EXPECT_EFFECTIVE_QOS_EQ(QOS_CLASS_USER_INITIATED,
"dispatch_source event handler QoS should be QOS_CLASS_USER_INITIATED");
T_EXPECT_EQ(get_user_promotion_basepri(), 60u,
"dispatch_source event handler should be overridden at 60");
if (*workloop_id == LISTENER_WLID) {
register_port(CONN_WLID, tmsg->port_descriptor.name);
kev->flags = EV_ADD | EV_ENABLE | EV_UDATA_SPECIFIC | EV_DISPATCH | EV_VANISHED;
kev->fflags = register_port_options();
kev->ext[0] = kev->ext[1] = kev->ext[2] = kev->ext[3] = 0;
*events = 1;
} else {
/* this will unblock the waiter */
mach_msg_destroy(hdr);
*events = 0;
}
}
static void
run_client_server(const char *server_name, const char *client_name)
{
dt_helper_t helpers[] = {
dt_launchd_helper_domain("com.apple.xnu.test.turnstile_multihop.plist",
server_name, NULL, LAUNCH_SYSTEM_DOMAIN),
dt_fork_helper(client_name)
};
dt_run_helpers(helpers, 2, HELPER_TIMEOUT_SECS);
}
#pragma mark Mach receive
#define TURNSTILE_MULTIHOP_SERVICE_NAME "com.apple.xnu.test.turnstile_multihop"
static mach_port_t
get_server_port(void)
{
mach_port_t port;
kern_return_t kr = bootstrap_check_in(bootstrap_port,
TURNSTILE_MULTIHOP_SERVICE_NAME, &port);
T_QUIET; T_ASSERT_MACH_SUCCESS(kr, "server bootstrap_check_in");
return port;
}
static mach_voucher_t
create_pthpriority_voucher(mach_msg_priority_t qos)
{
char voucher_buf[sizeof(mach_voucher_attr_recipe_data_t) + sizeof(ipc_pthread_priority_value_t)];
mach_voucher_t voucher = MACH_PORT_NULL;
kern_return_t ret;
ipc_pthread_priority_value_t ipc_pthread_priority_value =
(ipc_pthread_priority_value_t)qos;
mach_voucher_attr_raw_recipe_array_t recipes;
mach_voucher_attr_raw_recipe_size_t recipe_size = 0;
mach_voucher_attr_recipe_t recipe =
(mach_voucher_attr_recipe_t)&voucher_buf[recipe_size];
recipe->key = MACH_VOUCHER_ATTR_KEY_PTHPRIORITY;
recipe->command = MACH_VOUCHER_ATTR_PTHPRIORITY_CREATE;
recipe->previous_voucher = MACH_VOUCHER_NULL;
memcpy((char *)&recipe->content[0], &ipc_pthread_priority_value, sizeof(ipc_pthread_priority_value));
recipe->content_size = sizeof(ipc_pthread_priority_value_t);
recipe_size += sizeof(mach_voucher_attr_recipe_data_t) + recipe->content_size;
recipes = (mach_voucher_attr_raw_recipe_array_t)&voucher_buf[0];
ret = host_create_mach_voucher(mach_host_self(),
recipes,
recipe_size,
&voucher);
T_QUIET; T_ASSERT_MACH_SUCCESS(ret, "client host_create_mach_voucher");
return voucher;
}
static void
send(
mach_port_t send_port,
mach_port_t reply_port,
mach_port_t msg_port,
mach_msg_priority_t qos,
mach_msg_option_t options)
{
kern_return_t ret = 0;
struct test_msg send_msg = {
.header = {
.msgh_remote_port = send_port,
.msgh_local_port = reply_port,
.msgh_bits = MACH_MSGH_BITS_SET(MACH_MSG_TYPE_COPY_SEND,
reply_port ? MACH_MSG_TYPE_MAKE_SEND_ONCE : 0,
MACH_MSG_TYPE_MOVE_SEND,
MACH_MSGH_BITS_COMPLEX),
.msgh_id = 0x100,
.msgh_size = sizeof(send_msg),
},
.body = {
.msgh_descriptor_count = 1,
},
.port_descriptor = {
.name = msg_port,
.disposition = MACH_MSG_TYPE_MOVE_RECEIVE,
.type = MACH_MSG_PORT_DESCRIPTOR,
},
};
if (options & MACH_SEND_SYNC_USE_THRPRI) {
send_msg.header.msgh_voucher_port = create_pthpriority_voucher(qos);
}
if (msg_port == MACH_PORT_NULL) {
send_msg.body.msgh_descriptor_count = 0;
}
ret = mach_msg(&(send_msg.header),
MACH_SEND_MSG |
MACH_SEND_TIMEOUT |
MACH_SEND_OVERRIDE |
((reply_port ? MACH_SEND_SYNC_OVERRIDE : 0) | options),
send_msg.header.msgh_size,
0,
MACH_PORT_NULL,
10000,
0);
T_QUIET; T_ASSERT_MACH_SUCCESS(ret, "client mach_msg");
}
static void
receive(
mach_port_t rcv_port,
mach_port_t notify_port)
{
kern_return_t ret = 0;
struct {
mach_msg_header_t header;
mach_msg_body_t body;
mach_msg_port_descriptor_t port_descriptor;
} rcv_msg = {
.header =
{
.msgh_remote_port = MACH_PORT_NULL,
.msgh_local_port = rcv_port,
.msgh_size = sizeof(rcv_msg),
},
};
T_LOG("Client: Starting sync receive\n");
ret = mach_msg(&(rcv_msg.header),
MACH_RCV_MSG |
MACH_RCV_SYNC_WAIT,
0,
rcv_msg.header.msgh_size,
rcv_port,
0,
notify_port);
}
static lock_t lock_DEF;
static lock_t lock_IN;
static lock_t lock_UI;
static mach_port_t main_thread_port;
static mach_port_t def_thread_port;
static mach_port_t in_thread_port;
static mach_port_t ui_thread_port;
static mach_port_t sixty_thread_port;
static uint64_t dispatch_sync_owner;
static int
get_pri(thread_t thread_port)
{
kern_return_t kr;
thread_extended_info_data_t extended_info;
mach_msg_type_number_t count = THREAD_EXTENDED_INFO_COUNT;
kr = thread_info(thread_port, THREAD_EXTENDED_INFO,
(thread_info_t)&extended_info, &count);
T_QUIET; T_ASSERT_MACH_SUCCESS(kr, "thread_info");
return extended_info.pth_curpri;
}
static void
set_thread_name(const char *fn_name)
{
char name[50] = "";
thread_t thread_port = pthread_mach_thread_np(pthread_self());
int pri = get_pri(thread_port);
snprintf(name, sizeof(name), "%s at pri %2d", fn_name, pri);
pthread_setname_np(name);
}
static void
thread_wait_to_block(mach_port_t thread_port)
{
thread_extended_info_data_t extended_info;
kern_return_t kr;
while (1) {
mach_msg_type_number_t count = THREAD_EXTENDED_INFO_COUNT;
kr = thread_info(thread_port, THREAD_EXTENDED_INFO,
(thread_info_t)&extended_info, &count);
T_QUIET; T_ASSERT_MACH_SUCCESS(kr, "thread_info");
if (extended_info.pth_run_state == TH_STATE_WAITING) {
T_LOG("Target thread blocked\n");
break;
}
thread_switch(thread_port, SWITCH_OPTION_DEPRESS, 0);
}
}
static void
thread_wait_to_boost(mach_port_t thread_port, mach_port_t yield_thread, int priority)
{
thread_extended_info_data_t extended_info;
kern_return_t kr;
while (1) {
mach_msg_type_number_t count = THREAD_EXTENDED_INFO_COUNT;
kr = thread_info(thread_port, THREAD_EXTENDED_INFO,
(thread_info_t)&extended_info, &count);
T_QUIET; T_ASSERT_MACH_SUCCESS(kr, "thread_info");
if (extended_info.pth_priority >= priority) {
T_LOG("Target thread boosted\n");
break;
}
thread_switch(yield_thread, SWITCH_OPTION_DEPRESS, 0);
}
}
static void
dispatch_sync_wait(mach_port_t owner_thread, qos_class_t promote_qos)
{
struct kevent_qos_s kev_err[] = {{ 0 }};
uint32_t fflags = 0;
uint64_t mask = 0;
uint16_t action = 0;
int r;
action = EV_ADD | EV_DISABLE;
fflags = NOTE_WL_SYNC_WAIT | NOTE_WL_DISCOVER_OWNER;
dispatch_sync_owner = owner_thread;
struct kevent_qos_s kev[] = {{
.ident = mach_thread_self(),
.filter = EVFILT_WORKLOOP,
.flags = action,
.fflags = fflags,
.udata = (uintptr_t) &def_thread_port,
.qos = (int32_t)_pthread_qos_class_encode(promote_qos, 0, 0),
.ext[EV_EXTIDX_WL_MASK] = mask,
.ext[EV_EXTIDX_WL_VALUE] = dispatch_sync_owner,
.ext[EV_EXTIDX_WL_ADDR] = (uint64_t)&dispatch_sync_owner,
}};
/* Setup workloop to fake dispatch sync wait on a workloop */
r = kevent_id(30, kev, 1, kev_err, 1, NULL,
NULL, KEVENT_FLAG_WORKLOOP | KEVENT_FLAG_ERROR_EVENTS);
T_QUIET; T_LOG("dispatch_sync_wait returned\n");
}
static void
dispatch_sync_cancel(mach_port_t owner_thread, qos_class_t promote_qos)
{
struct kevent_qos_s kev_err[] = {{ 0 }};
uint32_t fflags = 0;
uint64_t mask = 0;
uint16_t action = 0;
int r;
action = EV_DELETE | EV_ENABLE;
fflags = NOTE_WL_SYNC_WAKE | NOTE_WL_END_OWNERSHIP;
dispatch_sync_owner = owner_thread;
struct kevent_qos_s kev[] = {{
.ident = def_thread_port,
.filter = EVFILT_WORKLOOP,
.flags = action,
.fflags = fflags,
.udata = (uintptr_t) &def_thread_port,
.qos = (int32_t)_pthread_qos_class_encode(promote_qos, 0, 0),
.ext[EV_EXTIDX_WL_MASK] = mask,
.ext[EV_EXTIDX_WL_VALUE] = dispatch_sync_owner,
.ext[EV_EXTIDX_WL_ADDR] = (uint64_t)&dispatch_sync_owner,
}};
/* Setup workloop to fake dispatch sync wake on a workloop */
r = kevent_id(30, kev, 1, kev_err, 1, NULL,
NULL, KEVENT_FLAG_WORKLOOP | KEVENT_FLAG_ERROR_EVENTS);
T_QUIET; T_LOG("dispatch_sync_cancel returned\n");
}
static void *
thread_at_sixty(void *arg __unused)
{
int policy;
struct sched_param param;
int ret;
void *load_token;
uint64_t before_lock_time, after_lock_time;
sixty_thread_port = mach_thread_self();
set_thread_name(__FUNCTION__);
/* Change our priority to 60 */
ret = pthread_getschedparam(pthread_self(), &policy, ¶m);
T_QUIET; T_ASSERT_MACH_SUCCESS(ret, "pthread_getschedparam");
param.sched_priority = 60;
ret = pthread_setschedparam(pthread_self(), policy, ¶m);
T_QUIET; T_ASSERT_MACH_SUCCESS(ret, "pthread_setschedparam");
ret = pthread_getschedparam(pthread_self(), &policy, ¶m);
T_QUIET; T_ASSERT_MACH_SUCCESS(ret, "pthread_getschedparam");
T_LOG("My priority is %d", param.sched_priority);
thread_wait_to_boost(in_thread_port, ui_thread_port, 46);
if (spin_for_ever) {
/* Schedule load at Default */
sched_create_load_at_qos(QOS_CLASS_DEFAULT, &load_token);
}
T_LOG("Thread at priority 60 trying to acquire UI lock");
before_lock_time = mach_absolute_time();
ull_lock(&lock_UI, 3, UL_UNFAIR_LOCK, 0);
after_lock_time = mach_absolute_time();
T_QUIET; T_LOG("The time for priority 60 thread to acquire lock was %llu \n",
(after_lock_time - before_lock_time));
T_END;
}
static void *
thread_at_ui(void *arg __unused)
{
ui_thread_port = mach_thread_self();
set_thread_name(__FUNCTION__);
/* Grab the first ulock */
ull_lock(&lock_UI, 2, UL_UNFAIR_LOCK, 0);
thread_wait_to_boost(def_thread_port, in_thread_port, 37);
thread_create_at_qos(QOS_CLASS_USER_INTERACTIVE, thread_at_sixty);
T_LOG("Thread at UI priority trying to acquire IN lock");
ull_lock(&lock_IN, 2, UL_UNFAIR_LOCK, 0);
ull_unlock(&lock_UI, 2, UL_UNFAIR_LOCK, 0);
return NULL;
}
static void *
thread_at_in(void *arg __unused)
{
in_thread_port = mach_thread_self();
set_thread_name(__FUNCTION__);
/* Grab the first ulock */
ull_lock(&lock_IN, 2, UL_UNFAIR_LOCK, 0);
T_LOG("Thread at IN priority got first lock ");
thread_wait_to_boost(main_thread_port, def_thread_port, 31);
/* Create a new thread at QOS_CLASS_USER_INTERACTIVE qos */
thread_create_at_qos(QOS_CLASS_USER_INTERACTIVE, thread_at_ui);
T_LOG("Thread at IN priority trying to acquire default lock");
ull_lock(&lock_DEF, 1, UL_UNFAIR_LOCK, 0);
ull_unlock(&lock_IN, 2, UL_UNFAIR_LOCK, 0);
return NULL;
}
static void *
thread_at_default(void *arg __unused)
{
def_thread_port = mach_thread_self();
set_thread_name(__FUNCTION__);
/* Grab the first ulock */
ull_lock(&lock_DEF, 1, UL_UNFAIR_LOCK, 0);
T_LOG("Thread at DEFAULT priority got first lock ");
thread_wait_to_block(main_thread_port);
/* Create a new thread at QOS_CLASS_USER_INITIATED qos */
thread_create_at_qos(QOS_CLASS_USER_INITIATED, thread_at_in);
T_LOG("Thread at Default priority trying to wait on dispatch sync for maintenance thread");
dispatch_sync_wait(main_thread_port, QOS_CLASS_DEFAULT);
ull_unlock(&lock_DEF, 1, UL_UNFAIR_LOCK, 0);
return NULL;
}
static void *
thread_at_maintenance(void *arg __unused)
{
mach_port_t service_port;
mach_port_t conn_port;
mach_port_t special_reply_port;
mach_port_options_t opts = {
.flags = MPO_INSERT_SEND_RIGHT,
};
main_thread_port = mach_thread_self();
set_thread_name(__FUNCTION__);
kern_return_t kr = bootstrap_look_up(bootstrap_port,
TURNSTILE_MULTIHOP_SERVICE_NAME, &service_port);
T_QUIET; T_ASSERT_MACH_SUCCESS(kr, "client bootstrap_look_up");
kr = mach_port_construct(mach_task_self(), &opts, 0ull, &conn_port);
T_QUIET; T_ASSERT_MACH_SUCCESS(kr, "mach_port_construct");
special_reply_port = thread_get_special_reply_port();
T_QUIET; T_ASSERT_TRUE(MACH_PORT_VALID(special_reply_port), "get_thread_special_reply_port");
/* Become the dispatch sync owner, dispatch_sync_owner will be set in dispatch_sync_wait function */
/* Send a sync message */
send(conn_port, special_reply_port, MACH_PORT_NULL,
(uint32_t)_pthread_qos_class_encode(QOS_CLASS_MAINTENANCE, 0, 0), 0);
/* Send an async checkin message */
send(service_port, MACH_PORT_NULL, conn_port,
(uint32_t)_pthread_qos_class_encode(QOS_CLASS_MAINTENANCE, 0, 0), 0);
/* Create a new thread at QOS_CLASS_DEFAULT qos */
thread_create_at_qos(QOS_CLASS_DEFAULT, thread_at_default);
/* Block on Sync IPC */
receive(special_reply_port, service_port);
T_LOG("received reply");
dispatch_sync_cancel(def_thread_port, QOS_CLASS_DEFAULT);
return NULL;
}
T_HELPER_DECL(three_ulock_sync_ipc_hop,
"Create chain of 4 threads with 3 ulocks and 1 sync IPC at different qos")
{
thread_create_at_qos(QOS_CLASS_MAINTENANCE, thread_at_maintenance);
sigsuspend(0);
}
static void
thread_create_at_qos(qos_class_t qos, void * (*function)(void *))
{
qos_class_t qos_thread;
pthread_t thread;
pthread_attr_t attr;
int ret;
ret = setpriority(PRIO_DARWIN_ROLE, 0, PRIO_DARWIN_ROLE_UI_FOCAL);
if (ret != 0) {
T_LOG("set priority failed\n");
}
pthread_attr_init(&attr);
pthread_attr_set_qos_class_np(&attr, qos, 0);
pthread_create(&thread, &attr, function, NULL);
T_LOG("pthread created\n");
pthread_get_qos_class_np(thread, &qos_thread, NULL);
}
#pragma mark Mach receive - kevent_qos
T_HELPER_DECL(server_kevent_id,
"Reply with the QoS that a dispatch source event handler ran with")
{
T_QUIET; T_ASSERT_POSIX_ZERO(_pthread_workqueue_init_with_workloop(
worker_cb, event_cb,
(pthread_workqueue_function_workloop_t)workloop_cb_test_intransit, 0, 0), NULL);
register_port(LISTENER_WLID, get_server_port());
sigsuspend(0);
T_ASSERT_FAIL("should receive a message");
}
#define TEST_MULTIHOP(server_name, client_name, name) \
T_DECL(server_kevent_id_##name, \
"Event delivery using a kevent_id", \
T_META_ASROOT(YES)) \
{ \
run_client_server(server_name, client_name); \
}
#define TEST_MULTIHOP_SPIN(server_name, client_name, name) \
T_DECL(server_kevent_id_##name, \
"Event delivery using a kevent_id", \
T_META_ASROOT(YES), T_META_ENABLED(FALSE)) \
{ \
spin_for_ever = true; \
run_client_server(server_name, client_name); \
spin_for_ever = false; \
}
/*
* Test 1: Test multihop priority boosting with ulocks, dispatch sync and sync IPC.
*
* Create thread's at different Qos and acquire a ulock and block on next ulock/dispatch sync
* creating a sync chain. The last hop the chain is blocked on Sync IPC.
*/
TEST_MULTIHOP("server_kevent_id", "three_ulock_sync_ipc_hop", three_ulock_sync_ipc_hop)
/*
* Test 2: Test multihop priority boosting with ulocks, dispatch sync and sync IPC.
*
* Create thread's at different Qos and acquire a ulock and block on next ulock/dispatch sync
* creating a sync chain. The last hop the chain is blocked on Sync IPC.
* Before the last priority 60 thread blocks on ulock, it also starts spinforeverd at priority 31.
*/
TEST_MULTIHOP_SPIN("server_kevent_id", "three_ulock_sync_ipc_hop", three_ulock_sync_ipc_hop_spin)
|
#!/usr/bin/env python
# Save parameters every a few SGD iterations as fail-safe
SAVE_PARAMS_EVERY = 5000
import pickle
import glob
import random
import numpy as np
import os.path as op
def load_saved_params(label):
"""
A helper function that loads previously saved parameters and resets
iteration start.
"""
st = 0
for f in glob.glob("models/word2vec/saved_params*.npy"):
if label in f:
iter = int(op.splitext(op.basename(f))[0].split("_")[2])
if (iter > st):
st = iter
if st > 0:
params_file = "models/word2vec/saved_params{}_{}.npy".format(label, st)
state_file = "models/word2vec/saved_state{}_{}.pickle".format(label, st)
params = np.load(params_file)
with open(state_file, "rb") as f:
state = pickle.load(f)
return st, params, state
else:
return st, None, None
def save_params(iter, params,label):
params_file = "models/word2vec/saved_params{}_{}.npy".format(label, iter)
state_file = "models/word2vec/saved_state{}_{}.pickle".format(label, iter)
np.save(params_file, params)
with open(state_file, "wb") as f:
pickle.dump(random.getstate(), f)
def sgd(f, x0, step, iterations, postprocessing=None, useSaved=False,
PRINT_EVERY=10,label=None):
""" Stochastic Gradient Descent
Implement the stochastic gradient descent method in this function.
Arguments:
f -- the function to optimize, it should take a single
argument and yield two outputs, a loss and the gradient
with respect to the arguments
x0 -- the initial point to start SGD from
step -- the step size for SGD
iterations -- total iterations to run SGD for
postprocessing -- postprocessing function for the parameters
if necessary. In the case of word2vec we will need to
normalize the word vectors to have unit length.
PRINT_EVERY -- specifies how many iterations to output loss
Return:
x -- the parameter value after SGD finishes
"""
# Anneal learning rate every several iterations
ANNEAL_EVERY = 20000
if useSaved:
start_iter, oldx, state = load_saved_params(label)
if start_iter > 0:
x0 = oldx
step *= 0.5 ** (start_iter / ANNEAL_EVERY)
if state:
random.setstate(state)
else:
start_iter = 0
x = x0
if not postprocessing:
postprocessing = lambda x: x
exploss = None
for iter in range(start_iter + 1, iterations + 1):
# You might want to print the progress every few iterations.
loss = None
### YOUR CODE HERE (~2 lines)
loss, grad = f(x)
x -= step * grad
### END YOUR CODE
x = postprocessing(x)
if iter % PRINT_EVERY == 0:
if not exploss:
exploss = loss
else:
exploss = .95 * exploss + .05 * loss
print("iter %d: %f" % (iter, exploss))
if iter % SAVE_PARAMS_EVERY == 0 and useSaved:
save_params(iter, x, label)
if iter % ANNEAL_EVERY == 0:
step *= 0.5
return x
|
module.exports = {
root: true,
env: {
node: true,
},
extends: [
'plugin:vue/vue3-essential',
'eslint:recommended',
'@vue/typescript/recommended',
'@vue/prettier',
'@vue/prettier/@typescript-eslint',
],
parserOptions: {
ecmaVersion: 2020,
},
rules: {
'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
},
overrides: [
{
files: [
'**/__tests__/*.{j,t}s?(x)',
'**/tests/unit/**/*.spec.{j,t}s?(x)',
],
env: {
mocha: true,
},
},
],
};
|
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('cms', '0012_auto_20150607_2207'),
('pages', '0014_socialplugin'),
]
operations = [
migrations.CreateModel(
name='FAQItemPlugin',
fields=[
('cmsplugin_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='cms.CMSPlugin', on_delete=models.CASCADE)),
('question', models.TextField(blank=True)),
('answer', models.TextField(blank=True)),
],
options={
'abstract': False,
},
bases=('cms.cmsplugin',),
),
migrations.CreateModel(
name='FAQPlugin',
fields=[
('cmsplugin_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='cms.CMSPlugin', on_delete=models.CASCADE)),
('title', models.CharField(max_length=70, blank=True)),
],
options={
'abstract': False,
},
bases=('cms.cmsplugin',),
),
]
|
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.11.3
# kernelspec:
# display_name: Python 3
# name: python3
# ---
# + [markdown] id="view-in-github" colab_type="text"
# <a href="https://colab.research.google.com/github/Nirzu97/pyprobml/blob/logreg_jax/notebooks/logreg_jax.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# + [markdown] id="eB0c7K3GpBrg"
# # Logistic regression <a class="anchor" id="logreg"></a>
#
# In this notebook, we illustrate how to perform logistic regression on some small datasets. We will compare binary logistic regression as implemented by sklearn with our own implementation, for which we use a batch optimizer from scipy. We code the gradients by hand. We also show how to use the JAX autodiff package (see [JAX AD colab](https://github.com/probml/pyprobml/tree/master/book1/supplements/autodiff_jax.ipynb)).
#
# + id="Ml8l4WVLpWCI"
# Standard Python libraries
from __future__ import absolute_import, division, print_function, unicode_literals
import os
import time
import numpy as np
import glob
import matplotlib.pyplot as plt
import PIL
import imageio
from IPython import display
import sklearn
import seaborn as sns;
sns.set(style="ticks", color_codes=True)
# + colab={"base_uri": "https://localhost:8080/"} id="cH-3xvdv7dXD" outputId="66dc6c29-9c1b-4419-cfb9-da7b1c0bef1d"
# https://github.com/google/jax
import jax
import jax.numpy as jnp
from jax.scipy.special import logsumexp
from jax import grad, hessian, jacfwd, jacrev, jit, vmap
from jax.experimental import optimizers
print("jax version {}".format(jax.__version__))
# + id="1UrGDEYb58qF"
# First we create a dataset.
import sklearn.datasets
from sklearn.model_selection import train_test_split
iris = sklearn.datasets.load_iris()
X = iris["data"]
y = (iris["target"] == 2).astype(np.int) # 1 if Iris-Virginica, else 0'
N, D = X.shape # 150, 4
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.33, random_state=42)
# + colab={"base_uri": "https://localhost:8080/"} id="S8GCOQm16OB3" outputId="69703c4d-84dd-48ff-dc12-1b9b0680ade1"
# Now let's find the MLE using sklearn. We will use this as the "gold standard"
from sklearn.linear_model import LogisticRegression
# We set C to a large number to turn off regularization.
# We don't fit the bias term to simplify the comparison below.
log_reg = LogisticRegression(solver="lbfgs", C=1e5, fit_intercept=False)
log_reg.fit(X_train, y_train)
w_mle_sklearn = jnp.ravel(log_reg.coef_)
print(w_mle_sklearn)
# + colab={"base_uri": "https://localhost:8080/"} id="-FtE7SSE6V0k" outputId="80b5de9f-f2a4-46bb-d6f4-777563472401"
# First we define the model, and check it gives the same output as sklearn.
def sigmoid(x): return 0.5 * (jnp.tanh(x / 2.) + 1)
def predict_logit(weights, inputs):
return jnp.dot(inputs, weights) # Already vectorized
def predict_prob(weights, inputs):
return sigmoid(predict_logit(weights, inputs))
ptest_sklearn = log_reg.predict_proba(X_test)[:,1]
print(jnp.round(ptest_sklearn, 3))
ptest_us = predict_prob(w_mle_sklearn, X_test)
print(jnp.round(ptest_us, 3))
assert jnp.allclose(ptest_sklearn, ptest_us, atol=1e-2)
# + colab={"base_uri": "https://localhost:8080/"} id="X27Iy_4D62Dl" outputId="759225be-b4c5-429a-847a-24d067e51d6a"
# Next we define the objective and check it gives the same output as sklearn.
from sklearn.metrics import log_loss
from jax.scipy.special import logsumexp
#from scipy.misc import logsumexp
def NLL_unstable(weights, batch):
inputs, targets = batch
p1 = predict_prob(weights, inputs)
logprobs = jnp.log(p1) * targets + jnp.log(1 - p1) * (1 - targets)
N = inputs.shape[0]
return -jnp.sum(logprobs)/N
def NLL(weights, batch):
# Use log-sum-exp trick
inputs, targets = batch
# p1 = 1/(1+exp(-logit)), p0 = 1/(1+exp(+logit))
logits = predict_logit(weights, inputs).reshape((-1,1))
N = logits.shape[0]
logits_plus = jnp.hstack([jnp.zeros((N,1)), logits]) # e^0=1
logits_minus = jnp.hstack([jnp.zeros((N,1)), -logits])
logp1 = -logsumexp(logits_minus, axis=1)
logp0 = -logsumexp(logits_plus, axis=1)
logprobs = logp1 * targets + logp0 * (1-targets)
return -jnp.sum(logprobs)/N
# We can use a small amount of L2 regularization, for numerical stability
def PNLL(weights, batch, l2_penalty=1e-5):
nll = NLL(weights, batch)
l2_norm = jnp.sum(jnp.power(weights, 2)) # squared L2 norm
return nll + l2_penalty*l2_norm
# We evaluate the training loss at the MLE, where the parameter values are "extreme".
nll_train = log_loss(y_train, predict_prob(w_mle_sklearn, X_train))
nll_train2 = NLL(w_mle_sklearn, (X_train, y_train))
nll_train3 = NLL_unstable(w_mle_sklearn, (X_train, y_train))
print(nll_train)
print(nll_train2)
print(nll_train3)
# + id="O8PxEPaC7pMK"
# Next we check the gradients compared to the manual formulas.
# For simplicity, we initially just do this for a single random example.
np.random.seed(42)
D = 5
w = np.random.randn(D)
x = np.random.randn(D)
y = 0
#d/da sigmoid(a) = s(a) * (1-s(a))
deriv_sigmoid = lambda a: sigmoid(a) * (1-sigmoid(a))
deriv_sigmoid_jax = grad(sigmoid)
a = 1.5 # a random logit
assert jnp.isclose(deriv_sigmoid(a), deriv_sigmoid_jax(a))
# mu(w)=sigmoid(w'x), d/dw mu(w) = mu * (1-mu) .* x
def mu(w): return sigmoid(jnp.dot(w,x))
def deriv_mu(w): return mu(w) * (1-mu(w)) * x
deriv_mu_jax = grad(mu)
assert jnp.allclose(deriv_mu(w), deriv_mu_jax(w))
# NLL(w) = -[y*log(mu) + (1-y)*log(1-mu)]
# d/dw NLL(w) = (mu-y)*x
def nll(w): return -(y*jnp.log(mu(w)) + (1-y)*jnp.log(1-mu(w)))
def deriv_nll(w): return (mu(w)-y)*x
deriv_nll_jax = grad(nll)
assert jnp.allclose(deriv_nll(w), deriv_nll_jax(w))
# + colab={"base_uri": "https://localhost:8080/"} id="TVT2tlmA7z72" outputId="e9fa28ab-ca6c-423f-ebb3-0c49a2a12a5d"
# Now let's check the gradients on the batch version of our data.
N = X_train.shape[0]
mu = predict_prob(w_mle_sklearn, X_train)
g1 = grad(NLL)(w_mle_sklearn, (X_train, y_train))
g2 = jnp.sum(jnp.dot(jnp.diag(mu - y_train), X_train), axis=0)/N
print(g1)
print(g2)
assert jnp.allclose(g1, g2, atol=1e-2)
H1 = hessian(NLL)(w_mle_sklearn, (X_train, y_train))
S = jnp.diag(mu * (1-mu))
H2 = jnp.dot(jnp.dot(X_train.T, S), X_train)/N
print(H1)
print(H2)
assert jnp.allclose(H1, H2, atol=1e-2)
# + colab={"base_uri": "https://localhost:8080/"} id="-_LREVYj79IW" outputId="3125bf39-8feb-48a8-e7a9-5ed9c8c626d5"
# Finally, use BFGS batch optimizer to compute MLE, and compare to sklearn
import scipy.optimize
def training_loss(w):
return NLL(w, (X_train, y_train))
def training_grad(w):
return grad(training_loss)(w)
np.random.seed(43)
N, D = X_train.shape
w_init = np.random.randn(D)
w_mle_scipy = scipy.optimize.minimize(training_loss, w_init, jac=training_grad, method='BFGS').x
print("parameters from sklearn {}".format(w_mle_sklearn))
print("parameters from scipy-bfgs {}".format(w_mle_scipy))
assert jnp.allclose(w_mle_sklearn, w_mle_scipy, atol=1e-1)
prob_scipy = predict_prob(w_mle_scipy, X_test)
prob_sklearn = predict_prob(w_mle_sklearn, X_test)
print(jnp.round(prob_scipy, 3))
print(jnp.round(prob_sklearn, 3))
assert jnp.allclose(prob_scipy, prob_sklearn, atol=1e-2)
# + id="jGXLRuHI0Xrw"
|
import os
import sys
from PyQt5 import QtWidgets, QtMultimedia, uic, QtCore
class Form(QtWidgets.QDialog):
def __init__(self, parent=None):
QtWidgets.QDialog.__init__(self, parent)
self.ui = uic.loadUi(os.path.join(os.path.dirname(__file__), "form.ui"),self)
self.player = QtMultimedia.QMediaPlayer(None, QtMultimedia.QMediaPlayer.VideoSurface)
file = os.path.join(os.path.dirname(__file__), "small.mp4")
self.player.setMedia(QtMultimedia.QMediaContent(QtCore.QUrl.fromLocalFile(file)))
self.player.setVideoOutput(self.ui.widget)
self.player.play()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
w = Form()
w.show()
sys.exit(app.exec())
|
import Class from '../mixin/class';
import {default as Togglable, toggleHeight} from '../mixin/togglable';
import {$, $$, attr, filter, getIndex, hasClass, includes, index, isInView, scrollIntoView, toggleClass, unwrap, wrapAll} from 'uikit-util';
export default {
mixins: [Class, Togglable],
props: {
targets: String,
active: null,
collapsible: Boolean,
multiple: Boolean,
toggle: String,
content: String,
transition: String,
offset: Number
},
data: {
targets: '> *',
active: false,
animation: [true],
collapsible: true,
multiple: false,
clsOpen: 'uk-open',
toggle: '> .uk-accordion-title',
content: '> .uk-accordion-content',
transition: 'ease',
offset: 0
},
computed: {
items: {
get({targets}, $el) {
return $$(targets, $el);
},
watch(items, prev) {
items.forEach(el => hide($(this.content, el), !hasClass(el, this.clsOpen)));
if (prev || hasClass(items, this.clsOpen)) {
return;
}
const active = this.active !== false && items[Number(this.active)]
|| !this.collapsible && items[0];
if (active) {
this.toggle(active, false);
}
},
immediate: true
},
toggles({toggle}) {
return this.items.map(item => $(toggle, item));
}
},
events: [
{
name: 'click',
delegate() {
return `${this.targets} ${this.$props.toggle}`;
},
handler(e) {
e.preventDefault();
this.toggle(index(this.toggles, e.current));
}
}
],
methods: {
toggle(item, animate) {
let items = [this.items[getIndex(item, this.items)]];
const activeItems = filter(this.items, `.${this.clsOpen}`);
if (!this.multiple && !includes(activeItems, items[0])) {
items = items.concat(activeItems);
}
if (!this.collapsible && activeItems.length < 2 && !filter(items, `:not(.${this.clsOpen})`).length) {
return;
}
items.forEach(el => this.toggleElement(el, !hasClass(el, this.clsOpen), (el, show) => {
toggleClass(el, this.clsOpen, show);
attr($(this.$props.toggle, el), 'aria-expanded', show);
const content = $(`${el._wrapper ? '> * ' : ''}${this.content}`, el);
if (animate === false || !this.hasTransition) {
hide(content, !show);
return;
}
if (!el._wrapper) {
el._wrapper = wrapAll(content, `<div${show ? ' hidden' : ''}>`);
}
hide(content, false);
return toggleHeight(this)(el._wrapper, show).then(() => {
hide(content, !show);
delete el._wrapper;
unwrap(content);
if (show) {
const toggle = $(this.$props.toggle, el);
if (!isInView(toggle)) {
scrollIntoView(toggle, {offset: this.offset});
}
}
});
}));
}
}
};
function hide(el, hide) {
el && (el.hidden = hide);
}
|
from olo.field import ConstField, UnionField
from olo.errors import ValidationError, DbFieldVersionError
from .base import TestCase, Dummy, Foo
from .utils import patched_db_get, patched_db_get_multi
class TestField(TestCase):
def test_default(self):
d = Dummy.create()
self.assertEqual(d.age, 12)
def test_automic(self):
f = Foo.create()
self.assertEqual(f.age, 1)
f.update(age=Foo.age + 1)
self.assertEqual(f.age, 2)
f.age = Foo.age + 1
f.save()
self.assertEqual(f.age, 3)
def test_output(self):
foo = Foo.create(age_str=1)
self.assertEqual(foo.age_str, '1')
def test_deparse(self):
v = Foo.age.deparse(1)
self.assertEqual(v, '1')
class V:
def __str__(self):
raise ValueError
_v = V()
v = Foo.age.deparse(_v)
self.assertEqual(v, _v)
def test_validate(self):
choices = Foo.age.choices
Foo.age.choices = None
Foo.age.validate(234)
Foo.age.choices = [1]
try:
with self.assertRaises(ValidationError):
Foo.age.validate(2)
finally:
Foo.age.choices = choices
def test_sub(self):
exp = Foo.age - 1
sql, _ = exp.get_sql_and_params()
self.assertEqual(sql, '`age` - %s')
def test_mul(self):
exp = Foo.age * 1
sql, _ = exp.get_sql_and_params()
self.assertEqual(sql, '`age` * %s')
def test_div(self):
x = Foo.age / 2
sql, _ = x.get_sql_and_params()
self.assertEqual(sql, '`age` / %s')
def test_mod(self):
x = Foo.age % 1
sql, _ = x.get_sql_and_params()
self.assertEqual(sql, '`age` % %s')
def test_eq(self):
v = Foo.age == 1
sql, _ = v.get_sql_and_params()
self.assertEqual(sql, '`age` = %s')
v = Foo.age == None # noqa
sql, _ = v.get_sql_and_params()
self.assertEqual(sql, '`age` IS %s')
def test_ne(self):
v = Foo.age != 1
sql, _ = v.get_sql_and_params()
self.assertEqual(sql, '`age` != %s')
v = Foo.age != None # noqa
sql, _ = v.get_sql_and_params()
self.assertEqual(sql, '`age` IS NOT %s')
def test_gt(self):
v = Foo.age > 1
sql, _ = v.get_sql_and_params()
self.assertEqual(sql, '`age` > %s')
def test_ge(self):
v = Foo.age >= 1
sql, _ = v.get_sql_and_params()
self.assertEqual(sql, '`age` >= %s')
def test_lt(self):
v = Foo.age < 1
sql, _ = v.get_sql_and_params()
self.assertEqual(sql, '`age` < %s')
def test_le(self):
v = Foo.age <= 1
sql, _ = v.get_sql_and_params()
self.assertEqual(sql, '`age` <= %s')
def test_not_in_(self):
v = Foo.age.not_in_([1])
sql, _ = v.get_sql_and_params()
self.assertEqual(sql, '`age` NOT IN %s')
f = UnionField(Foo.age, Foo.id)
v = f.not_in_([1])
sql, _ = v.get_sql_and_params()
self.assertEqual(sql, '(`age`, `id`) NOT IN %s')
def test_like_(self):
v = Foo.age.like_(1)
sql, _ = v.get_sql_and_params()
self.assertEqual(sql, '`age` LIKE %s')
def test_ilike_(self):
v = Foo.age.ilike_(1)
sql, _ = v.get_sql_and_params()
self.assertEqual(sql, '`age` ILIKE %s')
def test_regexp_(self):
v = Foo.age.regexp_(1)
sql, _ = v.get_sql_and_params()
self.assertEqual(sql, '`age` REGEXP %s')
def test_between_(self):
v = Foo.age.between_(1)
sql, _ = v.get_sql_and_params()
self.assertEqual(sql, '`age` BETWEEN %s')
def test_concat_(self):
v = Foo.age.concat_(1)
sql, _ = v.get_sql_and_params()
self.assertEqual(sql, '`age` || %s')
def test_is_(self):
v = Foo.age.is_(1)
sql, _ = v.get_sql_and_params()
self.assertEqual(sql, '`age` IS %s')
def test_is_not_(self):
v = Foo.age.is_not_(1)
sql, _ = v.get_sql_and_params()
self.assertEqual(sql, '`age` IS NOT %s')
def test_get_model(self):
model_ref = Foo.age._model_ref
try:
model = Foo.age.get_model()
self.assertEqual(model, Foo)
Foo.age._model_ref = None
model = Foo.age.get_model()
self.assertEqual(model, None)
finally:
Foo.age._model_ref = model_ref
def test_table_name(self):
model_ref = Foo.age._model_ref
try:
table_name = Foo.age.table_name
self.assertEqual(table_name, 'foo')
Foo.age._model_ref = None
table_name = Foo.age.table_name
self.assertEqual(table_name, None)
finally:
Foo.age._model_ref = model_ref
class TestConstField(TestCase):
def test_sqlize(self):
v = 1
f = ConstField(v)
self.assertEqual(
f.get_sql_and_params(),
('%s', [v]),
)
v = 'a'
f = ConstField(v)
self.assertEqual(
f.get_sql_and_params(),
('%s', [v]),
)
class TestDbField(TestCase):
def test_get_v0(self):
ver = Foo.prop1.version
f = Foo.create(prop1=[1])
f._data.pop('prop1')
db = f._get_db()
uuid = f.get_finally_uuid()
db.db_set(uuid, '{"prop1": [2]}')
try:
Foo.prop1.version = 0
self.assertEqual(f.prop1, [2])
finally:
Foo.prop1.version = ver
def test_set_v0(self):
ver = Foo.prop1.version
f = Foo.create(prop1=[1])
f._data.pop('prop1')
db = f._get_db()
uuid = f.get_finally_uuid()
db.db_set(uuid, '{"prop1": [2]}')
try:
Foo.prop1.version = 0
f.prop1 = [1]
f.save()
self.assertEqual(f.prop1, [1])
finally:
Foo.prop1.version = ver
def test_set_v1(self):
f = Foo.create(prop1=[1])
self.assertEqual(f.prop1, [1])
f.update(prop1=None)
self.assertIsNone(f.prop1)
def test__get__(self):
ver = Foo.prop1.version
f = Foo.create(prop1=[1])
self.assertEqual(f.prop1, [1])
f = Foo.get(f.id)
try:
Foo.prop1.version = 999
with self.assertRaises(DbFieldVersionError):
f.prop1
finally:
Foo.prop1.version = ver
def test__set__(self):
f = Foo.create(prop1=[1])
f.prop1 = [2]
f.save()
self.assertEqual(f.prop1, [2])
f = Foo.get(f.id)
self.assertEqual(f.prop1, [2])
bu = f.before_update
try:
f.before_update = lambda **kwargs: False
f.prop1 = [3]
f.save()
self.assertEqual(f.prop1, [2])
finally:
f.before_update = bu
ver = Foo.prop1.version
try:
Foo.prop1.version = 999
with self.assertRaises(DbFieldVersionError):
Foo.prop1.db_set(f, [3])
finally:
Foo.prop1.version = ver
def test__delete__(self):
f = Foo.create(prop1=[1])
bu = f.before_update
try:
f.before_update = lambda **kwargs: False
del f.prop1
self.assertEqual(f.prop1, [1])
finally:
f.before_update = bu
def test_prefetch(self):
for i in xrange(1, 8):
Dummy.create(count=i, prop1=[i])
ds = Dummy.gets_by()
with patched_db_get as db_get:
with patched_db_get_multi as db_get_multi:
for d in ds:
self.assertEqual(d.count, d.id)
self.assertEqual(d.prop1, [str(d.id)])
self.assertEqual(db_get.call_count, 0)
self.assertEqual(db_get_multi.call_count, 3)
|
const fs = require("fs");
const filepath = "./state.txt";
const getState = () => parseInt(fs.readFileSync(filepath), 10);
const setState = n => fs.writeFileSync(filepath, n);
const increment = () => fs.writeFileSync(filepath, getState() + 1);
const decrement = () => fs.writeFileSync(filepath, getState() - 1);
module.exports = { getState, setState, increment, decrement };
|
/****************************************************************************
*
* Copyright 2016 Samsung Electronics All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*
****************************************************************************/
/**
* @file
* Address Resolution Protocol module for IP over Ethernet
*
* Functionally, ARP is divided into two parts. The first maps an IP address
* to a physical address when sending a packet, and the second part answers
* requests from other machines for our physical address.
*
* This implementation complies with RFC 826 (Ethernet ARP). It supports
* Gratuitious ARP from RFC3220 (IP Mobility Support for IPv4) section 4.6
* if an interface calls etharp_gratuitous(our_netif) upon address change.
*/
/*
* Copyright (c) 2001-2003 Swedish Institute of Computer Science.
* Copyright (c) 2003-2004 Leon Woestenberg <leon.woestenberg@axon.tv>
* Copyright (c) 2003-2004 Axon Digital Design B.V., The Netherlands.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
*/
#include <tinyara/config.h>
#include <net/lwip/opt.h>
#if LWIP_ARP || LWIP_ETHERNET
#include <net/lwip/inet_chksum.h>
#include <net/lwip/stats.h>
#include <net/lwip/snmp.h>
#include <net/lwip/dhcp.h>
#include <net/lwip/autoip.h>
#include <net/lwip/netif/etharp.h>
#include <net/ethernet.h>
#include <string.h>
#ifdef LWIP_HOOK_FILENAME
#include LWIP_HOOK_FILENAME
#endif
/** The 24-bit IANA multicast OUI is 01-00-5e: */
#define LL_MULTICAST_ADDR_0 0x01
#define LL_MULTICAST_ADDR_1 0x00
#define LL_MULTICAST_ADDR_2 0x5e
#if LWIP_IPV4 && LWIP_ARP /* don't build if not configured for use in lwipopts.h */
/**
* Re-request a used ARP entry 1 minute before it would expire to prevent
* breaking a steadily used connection because the ARP entry timed out.
*/
#define ARP_AGE_REREQUEST_USED_UNICAST (ARP_MAXAGE - 30)
#define ARP_AGE_REREQUEST_USED_BROADCAST (ARP_MAXAGE - 15)
/** the time an ARP entry stays pending after first request,
* for ARP_TMR_INTERVAL = 1000, this is
* 10 seconds.
*
* @internal Keep this number at least 2, otherwise it might
* run out instantly if the timeout occurs directly after a request.
*/
#define ARP_MAXPENDING 5
/** ARP states */
enum etharp_state {
ETHARP_STATE_EMPTY = 0,
ETHARP_STATE_PENDING,
ETHARP_STATE_STABLE,
ETHARP_STATE_STABLE_REREQUESTING_1,
ETHARP_STATE_STABLE_REREQUESTING_2
#if ETHARP_SUPPORT_STATIC_ENTRIES
, ETHARP_STATE_STATIC
#endif /* ETHARP_SUPPORT_STATIC_ENTRIES */
};
struct etharp_entry {
#if ARP_QUEUEING
/** Pointer to queue of pending outgoing packets on this ARP entry. */
struct etharp_q_entry *q;
#else /* ARP_QUEUEING */
/** Pointer to a single pending outgoing packet on this ARP entry. */
struct pbuf *q;
#endif /* ARP_QUEUEING */
ip4_addr_t ipaddr;
struct netif *netif;
struct eth_addr ethaddr;
u16_t ctime;
u8_t state;
};
static struct etharp_entry arp_table[ARP_TABLE_SIZE];
#if !LWIP_NETIF_HWADDRHINT
static u8_t etharp_cached_entry;
#endif /* !LWIP_NETIF_HWADDRHINT */
/**
* Try hard to create a new entry - we want the IP address to appear in
* the cache (even if this means removing an active entry or so).
*/
#define ETHARP_FLAG_TRY_HARD 1
#define ETHARP_FLAG_FIND_ONLY 2
#if ETHARP_SUPPORT_STATIC_ENTRIES
#define ETHARP_FLAG_STATIC_ENTRY 4
#endif /* ETHARP_SUPPORT_STATIC_ENTRIES */
#if LWIP_NETIF_HWADDRHINT
static void ETHARP_SET_HINT(struct netif *netif, s8_t hint)
{
if (((netif) != NULL) && ((netif)->addr_hint != NULL)) {
*((netif)->addr_hint) = (hint);
}
}
#else /* LWIP_NETIF_HWADDRHINT */
#define ETHARP_SET_HINT(netif, hint) (etharp_cached_entry = (hint))
#endif /* LWIP_NETIF_HWADDRHINT */
/* Some checks, instead of etharp_init(): */
#if (LWIP_ARP && (ARP_TABLE_SIZE > 0x7f))
#error "ARP_TABLE_SIZE must fit in an s8_t, you have to reduce it in your lwipopts.h"
#endif /* (LWIP_ARP && (ARP_TABLE_SIZE > 0x7f)) */
static err_t etharp_request_dst(struct netif *netif, const ip4_addr_t *ipaddr, const struct eth_addr *hw_dst_addr);
static err_t etharp_raw(struct netif *netif, const struct eth_addr *ethsrc_addr, const struct eth_addr *ethdst_addr, const struct eth_addr *hwsrc_addr, const ip4_addr_t *ipsrc_addr, const struct eth_addr *hwdst_addr, const ip4_addr_t *ipdst_addr, const u16_t opcode);
#if ARP_QUEUEING
/**
* Free a complete queue of etharp entries
*
* @param q a qeueue of etharp_q_entry's to free
*/
static void free_etharp_q(struct etharp_q_entry *q)
{
struct etharp_q_entry *r;
LWIP_ASSERT("q != NULL", q != NULL);
LWIP_ASSERT("q->p != NULL", q->p != NULL);
while (q) {
r = q;
q = q->next;
LWIP_ASSERT("r->p != NULL", (r->p != NULL));
pbuf_free(r->p);
memp_free(MEMP_ARP_QUEUE, r);
}
}
#else /* ARP_QUEUEING */
/** Compatibility define: free the queued pbuf */
#define free_etharp_q(q) pbuf_free(q)
#endif /* ARP_QUEUEING */
/** Clean up ARP table entries */
static void etharp_free_entry(int i)
{
/* remove from SNMP ARP index tree */
mib2_remove_arp_entry(arp_table[i].netif, &arp_table[i].ipaddr);
/* and empty packet queue */
if (arp_table[i].q != NULL) {
/* remove all queued packets */
LWIP_DEBUGF(ETHARP_DEBUG, ("etharp_free_entry: freeing entry %" U16_F ", packet queue %p.\n", (u16_t) i, (void *)(arp_table[i].q)));
free_etharp_q(arp_table[i].q);
arp_table[i].q = NULL;
}
/* recycle entry for re-use */
arp_table[i].state = ETHARP_STATE_EMPTY;
#ifdef LWIP_DEBUG
/* for debugging, clean out the complete entry */
arp_table[i].ctime = 0;
arp_table[i].netif = NULL;
ip4_addr_set_zero(&arp_table[i].ipaddr);
arp_table[i].ethaddr = ethzero;
#endif /* LWIP_DEBUG */
}
/**
* Clears expired entries in the ARP table.
*
* This function should be called every ARP_TMR_INTERVAL milliseconds (1 second),
* in order to expire entries in the ARP table.
*/
void etharp_tmr(void)
{
u8_t i;
LWIP_DEBUGF(ETHARP_DEBUG, ("etharp_timer\n"));
/* remove expired entries from the ARP table */
for (i = 0; i < ARP_TABLE_SIZE; ++i) {
u8_t state = arp_table[i].state;
if (state != ETHARP_STATE_EMPTY
#if ETHARP_SUPPORT_STATIC_ENTRIES
&& (state != ETHARP_STATE_STATIC)
#endif /* ETHARP_SUPPORT_STATIC_ENTRIES */
) {
arp_table[i].ctime++;
if ((arp_table[i].ctime >= ARP_MAXAGE) || ((arp_table[i].state == ETHARP_STATE_PENDING) && (arp_table[i].ctime >= ARP_MAXPENDING))) {
/* pending or stable entry has become old! */
LWIP_DEBUGF(ETHARP_DEBUG, ("etharp_timer: expired %s entry %" U16_F ".\n", arp_table[i].state >= ETHARP_STATE_STABLE ? "stable" : "pending", (u16_t) i));
/* clean up entries that have just been expired */
etharp_free_entry(i);
} else if (arp_table[i].state == ETHARP_STATE_STABLE_REREQUESTING_1) {
/* Don't send more than one request every 2 seconds. */
arp_table[i].state = ETHARP_STATE_STABLE_REREQUESTING_2;
} else if (arp_table[i].state == ETHARP_STATE_STABLE_REREQUESTING_2) {
/**
* Reset state to stable, so that the next transmitted packet will
* re-send an ARP request.
*/
arp_table[i].state = ETHARP_STATE_STABLE;
} else if (arp_table[i].state == ETHARP_STATE_PENDING) {
/* still pending, resend an ARP query */
etharp_request(arp_table[i].netif, &arp_table[i].ipaddr);
}
}
}
}
/**
* Search the ARP table for a matching or new entry.
*
* If an IP address is given, return a pending or stable ARP entry that matches
* the address. If no match is found, create a new entry with this address set,
* but in state ETHARP_EMPTY. The caller must check and possibly change the
* state of the returned entry.
*
* If ipaddr is NULL, return a initialized new entry in state ETHARP_EMPTY.
*
* In all cases, attempt to create new entries from an empty entry. If no
* empty entries are available and ETHARP_FLAG_TRY_HARD flag is set, recycle
* old entries. Heuristic choose the least important entry for recycling.
*
* @param ipaddr IP address to find in ARP cache, or to add if not found.
* @param flags See @ref etharp_state
* @param netif netif related to this address (used for NETIF_HWADDRHINT)
*
* @return The ARP entry index that matched or is created, ERR_MEM if no
* entry is found or could be recycled.
*/
static s8_t etharp_find_entry(const ip4_addr_t *ipaddr, u8_t flags, struct netif *netif)
{
s8_t old_pending = ARP_TABLE_SIZE, old_stable = ARP_TABLE_SIZE;
s8_t empty = ARP_TABLE_SIZE;
u8_t i = 0;
/* oldest entry with packets on queue */
s8_t old_queue = ARP_TABLE_SIZE;
/* its age */
u16_t age_queue = 0, age_pending = 0, age_stable = 0;
LWIP_UNUSED_ARG(netif);
/**
* a) do a search through the cache, remember candidates
* b) select candidate entry
* c) create new entry
*/
/* a) in a single search sweep, do all of this
* 1) remember the first empty entry (if any)
* 2) remember the oldest stable entry (if any)
* 3) remember the oldest pending entry without queued packets (if any)
* 4) remember the oldest pending entry with queued packets (if any)
* 5) search for a matching IP entry, either pending or stable
* until 5 matches, or all entries are searched for.
*/
for (i = 0; i < ARP_TABLE_SIZE; ++i) {
u8_t state = arp_table[i].state;
/* no empty entry found yet and now we do find one? */
if ((empty == ARP_TABLE_SIZE) && (state == ETHARP_STATE_EMPTY)) {
LWIP_DEBUGF(ETHARP_DEBUG, ("etharp_find_entry: found empty entry %" U16_F "\n", (u16_t) i));
/* remember first empty entry */
empty = i;
} else if (state != ETHARP_STATE_EMPTY) {
LWIP_ASSERT("state == ETHARP_STATE_PENDING || state >= ETHARP_STATE_STABLE", state == ETHARP_STATE_PENDING || state >= ETHARP_STATE_STABLE);
/* if given, does IP address match IP address in ARP entry? */
if (ipaddr && ip4_addr_cmp(ipaddr, &arp_table[i].ipaddr)
#if ETHARP_TABLE_MATCH_NETIF
&& ((netif == NULL) || (netif == arp_table[i].netif))
#endif /* ETHARP_TABLE_MATCH_NETIF */
) {
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_find_entry: found matching entry %" U16_F "\n", (u16_t) i));
/* found exact IP address match, simply bail out */
return i;
}
/* pending entry? */
if (state == ETHARP_STATE_PENDING) {
/* pending with queued packets? */
if (arp_table[i].q != NULL) {
if (arp_table[i].ctime >= age_queue) {
old_queue = i;
age_queue = arp_table[i].ctime;
}
} else
/* pending without queued packets? */
{
if (arp_table[i].ctime >= age_pending) {
old_pending = i;
age_pending = arp_table[i].ctime;
}
}
/* stable entry? */
} else if (state >= ETHARP_STATE_STABLE) {
#if ETHARP_SUPPORT_STATIC_ENTRIES
/* don't record old_stable for static entries since they never expire */
if (state < ETHARP_STATE_STATIC)
#endif /* ETHARP_SUPPORT_STATIC_ENTRIES */
{
/* remember entry with oldest stable entry in oldest, its age in maxtime */
if (arp_table[i].ctime >= age_stable) {
old_stable = i;
age_stable = arp_table[i].ctime;
}
}
}
}
}
/* { we have no match } => try to create a new entry */
/* don't create new entry, only search? */
if (((flags & ETHARP_FLAG_FIND_ONLY) != 0) ||
/* or no empty entry found and not allowed to recycle? */
((empty == ARP_TABLE_SIZE) && ((flags & ETHARP_FLAG_TRY_HARD) == 0))) {
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_find_entry: no empty entry found and not allowed to recycle\n"));
return (s8_t) ERR_MEM;
}
/* b) choose the least destructive entry to recycle:
* 1) empty entry
* 2) oldest stable entry
* 3) oldest pending entry without queued packets
* 4) oldest pending entry with queued packets
*
* { ETHARP_FLAG_TRY_HARD is set at this point }
*/
/* 1) empty entry available? */
if (empty < ARP_TABLE_SIZE) {
i = empty;
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_find_entry: selecting empty entry %" U16_F "\n", (u16_t) i));
} else {
/* 2) found recyclable stable entry? */
if (old_stable < ARP_TABLE_SIZE) {
/* recycle oldest stable */
i = old_stable;
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_find_entry: selecting oldest stable entry %" U16_F "\n", (u16_t) i));
/* no queued packets should exist on stable entries */
LWIP_ASSERT("arp_table[i].q == NULL", arp_table[i].q == NULL);
/* 3) found recyclable pending entry without queued packets? */
} else if (old_pending < ARP_TABLE_SIZE) {
/* recycle oldest pending */
i = old_pending;
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_find_entry: selecting oldest pending entry %" U16_F " (without queue)\n", (u16_t) i));
/* 4) found recyclable pending entry with queued packets? */
} else if (old_queue < ARP_TABLE_SIZE) {
/* recycle oldest pending (queued packets are free in etharp_free_entry) */
i = old_queue;
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_find_entry: selecting oldest pending entry %" U16_F ", freeing packet queue %p\n", (u16_t) i, (void *)(arp_table[i].q)));
/* no empty or recyclable entries found */
} else {
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_find_entry: no empty or recyclable entries found\n"));
return (s8_t) ERR_MEM;
}
/* { empty or recyclable entry found } */
LWIP_ASSERT("i < ARP_TABLE_SIZE", i < ARP_TABLE_SIZE);
etharp_free_entry(i);
}
LWIP_ASSERT("i < ARP_TABLE_SIZE", i < ARP_TABLE_SIZE);
LWIP_ASSERT("arp_table[i].state == ETHARP_STATE_EMPTY", arp_table[i].state == ETHARP_STATE_EMPTY);
/* IP address given? */
if (ipaddr != NULL) {
/* set IP address */
ip4_addr_copy(arp_table[i].ipaddr, *ipaddr);
}
arp_table[i].ctime = 0;
#if ETHARP_TABLE_MATCH_NETIF
arp_table[i].netif = netif;
#endif /* ETHARP_TABLE_MATCH_NETIF */
return (err_t) i;
}
/**
* Update (or insert) a IP/MAC address pair in the ARP cache.
*
* If a pending entry is resolved, any queued packets will be sent
* at this point.
*
* @param netif netif related to this entry (used for NETIF_ADDRHINT)
* @param ipaddr IP address of the inserted ARP entry.
* @param ethaddr Ethernet address of the inserted ARP entry.
* @param flags See @ref etharp_state
*
* @return
* - ERR_OK Successfully updated ARP cache.
* - ERR_MEM If we could not add a new ARP entry when ETHARP_FLAG_TRY_HARD was set.
* - ERR_ARG Non-unicast address given, those will not appear in ARP cache.
*
* @see pbuf_free()
*/
static err_t etharp_update_arp_entry(struct netif *netif, const ip4_addr_t *ipaddr, struct eth_addr *ethaddr, u8_t flags)
{
s8_t i;
LWIP_ASSERT("netif->hwaddr_len == ETH_HWADDR_LEN", netif->hwaddr_len == ETH_HWADDR_LEN);
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_update_arp_entry: %" U16_F ".%" U16_F ".%" U16_F ".%" U16_F " - %02" X16_F ":%02" X16_F ":%02" X16_F ":%02" X16_F ":%02" X16_F ":%02" X16_F "\n", ip4_addr1_16(ipaddr), ip4_addr2_16(ipaddr), ip4_addr3_16(ipaddr), ip4_addr4_16(ipaddr), (u16_t) ethaddr->addr[0], (u16_t) ethaddr->addr[1], (u16_t) ethaddr->addr[2], (u16_t) ethaddr->addr[3], (u16_t) ethaddr->addr[4], (u16_t) ethaddr->addr[5]));
/* non-unicast address? */
if (ip4_addr_isany(ipaddr) || ip4_addr_isbroadcast(ipaddr, netif) || ip4_addr_ismulticast(ipaddr)) {
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_update_arp_entry: will not add non-unicast IP address to ARP cache\n"));
return ERR_ARG;
}
/* find or create ARP entry */
i = etharp_find_entry(ipaddr, flags, netif);
/* bail out if no entry could be found */
if (i < 0) {
return (err_t) i;
}
#if ETHARP_SUPPORT_STATIC_ENTRIES
if (flags & ETHARP_FLAG_STATIC_ENTRY) {
/* record static type */
arp_table[i].state = ETHARP_STATE_STATIC;
} else if (arp_table[i].state == ETHARP_STATE_STATIC) {
/* found entry is a static type, don't overwrite it */
return ERR_VAL;
} else
#endif /* ETHARP_SUPPORT_STATIC_ENTRIES */
{
/* mark it stable */
arp_table[i].state = ETHARP_STATE_STABLE;
}
/* record network interface */
arp_table[i].netif = netif;
/* insert in SNMP ARP index tree */
mib2_add_arp_entry(netif, &arp_table[i].ipaddr);
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_update_arp_entry: updating stable entry %" S16_F "\n", (s16_t) i));
/* update address */
ETHADDR32_COPY(&arp_table[i].ethaddr, ethaddr);
/* reset time stamp */
arp_table[i].ctime = 0;
/* this is where we will send out queued packets! */
#if ARP_QUEUEING
while (arp_table[i].q != NULL) {
struct pbuf *p;
/* remember remainder of queue */
struct etharp_q_entry *q = arp_table[i].q;
/* pop first item off the queue */
arp_table[i].q = q->next;
/* get the packet pointer */
p = q->p;
/* now queue entry can be freed */
memp_free(MEMP_ARP_QUEUE, q);
#else /* ARP_QUEUEING */
if (arp_table[i].q != NULL) {
struct pbuf *p = arp_table[i].q;
arp_table[i].q = NULL;
#endif /* ARP_QUEUEING */
/* send the queued IP packet */
ethernet_output(netif, p, (struct eth_addr *)(netif->hwaddr), ethaddr, ETHTYPE_IP);
/* free the queued IP packet */
pbuf_free(p);
}
return ERR_OK;
}
#if ETHARP_SUPPORT_STATIC_ENTRIES
/** Add a new static entry to the ARP table. If an entry exists for the
* specified IP address, this entry is overwritten.
* If packets are queued for the specified IP address, they are sent out.
*
* @param ipaddr IP address for the new static entry
* @param ethaddr ethernet address for the new static entry
* @return See return values of etharp_add_static_entry
*/
err_t etharp_add_static_entry(const ip4_addr_t *ipaddr, struct eth_addr *ethaddr)
{
struct netif *netif;
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_add_static_entry: %" U16_F ".%" U16_F ".%" U16_F ".%" U16_F " - %02" X16_F ":%02" X16_F ":%02" X16_F ":%02" X16_F ":%02" X16_F ":%02" X16_F "\n", ip4_addr1_16(ipaddr), ip4_addr2_16(ipaddr), ip4_addr3_16(ipaddr), ip4_addr4_16(ipaddr), (u16_t) ethaddr->addr[0], (u16_t) ethaddr->addr[1], (u16_t) ethaddr->addr[2], (u16_t) ethaddr->addr[3], (u16_t) ethaddr->addr[4], (u16_t) ethaddr->addr[5]));
netif = ip4_route(ipaddr);
if (netif == NULL) {
return ERR_RTE;
}
return etharp_update_arp_entry(netif, ipaddr, ethaddr, ETHARP_FLAG_TRY_HARD | ETHARP_FLAG_STATIC_ENTRY);
}
/** Remove a static entry from the ARP table previously added with a call to
* etharp_add_static_entry.
*
* @param ipaddr IP address of the static entry to remove
* @return ERR_OK: entry removed
* ERR_MEM: entry wasn't found
* ERR_ARG: entry wasn't a static entry but a dynamic one
*/
err_t etharp_remove_static_entry(const ip4_addr_t *ipaddr)
{
s8_t i;
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_remove_static_entry: %" U16_F ".%" U16_F ".%" U16_F ".%" U16_F "\n", ip4_addr1_16(ipaddr), ip4_addr2_16(ipaddr), ip4_addr3_16(ipaddr), ip4_addr4_16(ipaddr)));
/* find or create ARP entry */
i = etharp_find_entry(ipaddr, ETHARP_FLAG_FIND_ONLY, NULL);
/* bail out if no entry could be found */
if (i < 0) {
return (err_t) i;
}
if (arp_table[i].state != ETHARP_STATE_STATIC) {
/* entry wasn't a static entry, cannot remove it */
return ERR_ARG;
}
/* entry found, free it */
etharp_free_entry(i);
return ERR_OK;
}
#endif /* ETHARP_SUPPORT_STATIC_ENTRIES */
/**
* Remove all ARP table entries of the specified netif.
*
* @param netif points to a network interface
*/
void etharp_cleanup_netif(struct netif *netif)
{
u8_t i;
for (i = 0; i < ARP_TABLE_SIZE; ++i) {
u8_t state = arp_table[i].state;
if ((state != ETHARP_STATE_EMPTY) && (arp_table[i].netif == netif)) {
etharp_free_entry(i);
}
}
}
/**
* Finds (stable) ethernet/IP address pair from ARP table
* using interface and IP address index.
* @note the addresses in the ARP table are in network order!
*
* @param netif points to interface index
* @param ipaddr points to the (network order) IP address index
* @param eth_ret points to return pointer
* @param ip_ret points to return pointer
* @return table index if found, -1 otherwise
*/
s8_t etharp_find_addr(struct netif *netif, const ip4_addr_t *ipaddr, struct eth_addr **eth_ret, const ip4_addr_t **ip_ret)
{
s8_t i;
LWIP_ASSERT("eth_ret != NULL && ip_ret != NULL", eth_ret != NULL && ip_ret != NULL);
LWIP_UNUSED_ARG(netif);
i = etharp_find_entry(ipaddr, ETHARP_FLAG_FIND_ONLY, netif);
if ((i >= 0) && (arp_table[i].state >= ETHARP_STATE_STABLE)) {
*eth_ret = &arp_table[i].ethaddr;
*ip_ret = &arp_table[i].ipaddr;
return i;
}
return -1;
}
/**
* Possibility to iterate over stable ARP table entries
*
* @param i entry number, 0 to ARP_TABLE_SIZE
* @param ipaddr return value: IP address
* @param netif return value: points to interface
* @param eth_ret return value: ETH address
* @return 1 on valid index, 0 otherwise
*/
u8_t etharp_get_entry(u8_t i, ip4_addr_t **ipaddr, struct netif **netif, struct eth_addr **eth_ret)
{
LWIP_ASSERT("ipaddr != NULL", ipaddr != NULL);
LWIP_ASSERT("netif != NULL", netif != NULL);
LWIP_ASSERT("eth_ret != NULL", eth_ret != NULL);
if ((i < ARP_TABLE_SIZE) && (arp_table[i].state >= ETHARP_STATE_STABLE)) {
*ipaddr = &arp_table[i].ipaddr;
*netif = arp_table[i].netif;
*eth_ret = &arp_table[i].ethaddr;
return 1;
} else {
return 0;
}
}
/**
* Responds to ARP requests to us. Upon ARP replies to us, add entry to cache
* send out queued IP packets. Updates cache with snooped address pairs.
*
* Should be called for incoming ARP packets. The pbuf in the argument
* is freed by this function.
*
* @param p The ARP packet that arrived on netif. Is freed by this function.
* @param netif The lwIP network interface on which the ARP packet pbuf arrived.
*
* @see pbuf_free()
*/
void etharp_input(struct pbuf *p, struct netif *netif)
{
struct etharp_hdr *hdr;
/* these are aligned properly, whereas the ARP header fields might not be */
ip4_addr_t sipaddr, dipaddr;
u8_t for_us;
LWIP_ERROR("netif != NULL", (netif != NULL), return;);
hdr = (struct etharp_hdr *)p->payload;
/* RFC 826 "Packet Reception": */
if ((hdr->hwtype != PP_HTONS(HWTYPE_ETHERNET)) || (hdr->hwlen != ETH_HWADDR_LEN) || (hdr->protolen != sizeof(ip4_addr_t)) || (hdr->proto != PP_HTONS(ETHTYPE_IP))) {
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_WARNING, ("etharp_input: packet dropped, wrong hw type, hwlen, proto, protolen or ethernet type (%" U16_F "/%" U16_F "/%" U16_F "/%" U16_F ")\n", hdr->hwtype, (u16_t) hdr->hwlen, hdr->proto, (u16_t) hdr->protolen));
ETHARP_STATS_INC(etharp.proterr);
ETHARP_STATS_INC(etharp.drop);
pbuf_free(p);
return;
}
ETHARP_STATS_INC(etharp.recv);
#if LWIP_AUTOIP
/**
* We have to check if a host already has configured our random
* created link local address and continuously check if there is
* a host with this IP-address so we can detect collisions
*/
autoip_arp_reply(netif, hdr);
#endif /* LWIP_AUTOIP */
/**
* Copy struct ip4_addr2 to aligned ip4_addr, to support compilers without
* structure packing (not using structure copy which breaks strict-aliasing rules).
*/
IPADDR2_COPY(&sipaddr, &hdr->sipaddr);
IPADDR2_COPY(&dipaddr, &hdr->dipaddr);
/* this interface is not configured? */
if (ip4_addr_isany_val(*netif_ip4_addr(netif))) {
for_us = 0;
} else {
/* ARP packet directed to us? */
for_us = (u8_t) ip4_addr_cmp(&dipaddr, netif_ip4_addr(netif));
}
/**
* ARP message directed to us?
* -> add IP address in ARP cache; assume requester wants to talk to us,
* can result in directly sending the queued packets for this host.
* ARP message not directed to us?
* -> update the source IP address in the cache, if present
*/
etharp_update_arp_entry(netif, &sipaddr, &(hdr->shwaddr), for_us ? ETHARP_FLAG_TRY_HARD : ETHARP_FLAG_FIND_ONLY);
/* now act on the message itself */
switch (hdr->opcode) {
/* ARP request? */
case PP_HTONS(ARP_REQUEST):
/**
* ARP request. If it asked for our address, we send out a
* reply. In any case, we time-stamp any existing ARP entry,
* and possibly send out an IP packet that was queued on it.
*/
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_input: incoming ARP request\n"));
/* ARP request for our address? */
if (for_us) {
/* send ARP response */
etharp_raw(netif, (struct eth_addr *)netif->hwaddr, &hdr->shwaddr, (struct eth_addr *)netif->hwaddr, netif_ip4_addr(netif), &hdr->shwaddr, &sipaddr, ARP_REPLY);
/* we are not configured? */
} else if (ip4_addr_isany_val(*netif_ip4_addr(netif))) {
/* { for_us == 0 and netif->ip_addr.addr == 0 } */
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_input: we are unconfigured, ARP request ignored.\n"));
/* request was not directed to us */
} else {
/* { for_us == 0 and netif->ip_addr.addr != 0 } */
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_input: ARP request was not for us.\n"));
}
break;
case PP_HTONS(ARP_REPLY):
/* ARP reply. We already updated the ARP cache earlier. */
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_input: incoming ARP reply\n"));
#if (LWIP_DHCP && DHCP_DOES_ARP_CHECK)
/**
* DHCP wants to know about ARP replies from any host with an
* IP address also offered to us by the DHCP server. We do not
* want to take a duplicate IP address on a single network.
* @todo How should we handle redundant (fail-over) interfaces?
*/
dhcp_arp_reply(netif, &sipaddr);
#endif /* (LWIP_DHCP && DHCP_DOES_ARP_CHECK) */
break;
default:
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_input: ARP unknown opcode type %" S16_F "\n", lwip_htons(hdr->opcode)));
ETHARP_STATS_INC(etharp.err);
break;
}
/* free ARP packet */
pbuf_free(p);
}
/** Just a small helper function that sends a pbuf to an ethernet address
* in the arp_table specified by the index 'arp_idx'.
*/
static err_t etharp_output_to_arp_index(struct netif *netif, struct pbuf *q, u8_t arp_idx)
{
LWIP_ASSERT("arp_table[arp_idx].state >= ETHARP_STATE_STABLE", arp_table[arp_idx].state >= ETHARP_STATE_STABLE);
/**
* if arp table entry is about to expire: re-request it,
* but only if its state is ETHARP_STATE_STABLE to prevent flooding the
* network with ARP requests if this address is used frequently.
*/
if (arp_table[arp_idx].state == ETHARP_STATE_STABLE) {
if (arp_table[arp_idx].ctime >= ARP_AGE_REREQUEST_USED_BROADCAST) {
/* issue a standard request using broadcast */
if (etharp_request(netif, &arp_table[arp_idx].ipaddr) == ERR_OK) {
arp_table[arp_idx].state = ETHARP_STATE_STABLE_REREQUESTING_1;
}
} else if (arp_table[arp_idx].ctime >= ARP_AGE_REREQUEST_USED_UNICAST) {
/* issue a unicast request (for 15 seconds) to prevent unnecessary broadcast */
if (etharp_request_dst(netif, &arp_table[arp_idx].ipaddr, &arp_table[arp_idx].ethaddr) == ERR_OK) {
arp_table[arp_idx].state = ETHARP_STATE_STABLE_REREQUESTING_1;
}
}
}
return ethernet_output(netif, q, (struct eth_addr *)(netif->hwaddr), &arp_table[arp_idx].ethaddr, ETHTYPE_IP);
}
/**
* Resolve and fill-in Ethernet address header for outgoing IP packet.
*
* For IP multicast and broadcast, corresponding Ethernet addresses
* are selected and the packet is transmitted on the link.
*
* For unicast addresses, the packet is submitted to etharp_query(). In
* case the IP address is outside the local network, the IP address of
* the gateway is used.
*
* @param netif The lwIP network interface which the IP packet will be sent on.
* @param q The pbuf(s) containing the IP packet to be sent.
* @param ipaddr The IP address of the packet destination.
*
* @return
* - ERR_RTE No route to destination (no gateway to external networks),
* or the return type of either etharp_query() or ethernet_input().
*/
err_t etharp_output(struct netif *netif, struct pbuf *q, const ip4_addr_t *ipaddr)
{
const struct eth_addr *dest;
struct eth_addr mcastaddr;
const ip4_addr_t *dst_addr = ipaddr;
LWIP_ASSERT("netif != NULL", netif != NULL);
LWIP_ASSERT("q != NULL", q != NULL);
LWIP_ASSERT("ipaddr != NULL", ipaddr != NULL);
/**
* Determine on destination hardware address. Broadcasts and multicasts
* are special, other IP addresses are looked up in the ARP table.
*/
/* broadcast destination IP address? */
if (ip4_addr_isbroadcast(ipaddr, netif)) {
/* broadcast on Ethernet also */
dest = (const struct eth_addr *)ðbroadcast;
/* multicast destination IP address? */
} else if (ip4_addr_ismulticast(ipaddr)) {
/* Hash IP multicast address to MAC address. */
mcastaddr.addr[0] = LL_IP4_MULTICAST_ADDR_0;
mcastaddr.addr[1] = LL_IP4_MULTICAST_ADDR_1;
mcastaddr.addr[2] = LL_IP4_MULTICAST_ADDR_2;
mcastaddr.addr[3] = ip4_addr2(ipaddr) & 0x7f;
mcastaddr.addr[4] = ip4_addr3(ipaddr);
mcastaddr.addr[5] = ip4_addr4(ipaddr);
/* destination Ethernet address is multicast */
dest = &mcastaddr;
/* unicast destination IP address? */
} else {
s8_t i;
/**
* outside local network? if so, this can neither be a global broadcast nor
* a subnet broadcast.
*/
if (!ip4_addr_netcmp(ipaddr, netif_ip4_addr(netif), netif_ip4_netmask(netif)) && !ip4_addr_islinklocal(ipaddr)) {
#if LWIP_AUTOIP
struct ip_hdr *iphdr = LWIP_ALIGNMENT_CAST(struct ip_hdr *, q->payload);
/**
* According to RFC 3297, chapter 2.6.2 (Forwarding Rules), a packet with
* a link-local source address must always be "directly to its destination
* on the same physical link. The host MUST NOT send the packet to any
* router for forwarding".
*/
if (!ip4_addr_islinklocal(&iphdr->src))
#endif /* LWIP_AUTOIP */
{
#ifdef LWIP_HOOK_ETHARP_GET_GW
/**
* For advanced routing, a single default gateway might not be enough, so get
* the IP address of the gateway to handle the current destination address.
*/
dst_addr = LWIP_HOOK_ETHARP_GET_GW(netif, ipaddr);
if (dst_addr == NULL)
#endif /* LWIP_HOOK_ETHARP_GET_GW */
{
/* interface has default gateway? */
if (!ip4_addr_isany_val(*netif_ip4_gw(netif))) {
/* send to hardware address of default gateway IP address */
dst_addr = netif_ip4_gw(netif);
/* no default gateway available */
} else {
/* no route to destination error (default gateway missing) */
return ERR_RTE;
}
}
}
}
#if LWIP_NETIF_HWADDRHINT
if (netif->addr_hint != NULL) {
/* per-pcb cached entry was given */
u8_t etharp_cached_entry = *(netif->addr_hint);
if (etharp_cached_entry < ARP_TABLE_SIZE) {
#endif /* LWIP_NETIF_HWADDRHINT */
if ((arp_table[etharp_cached_entry].state >= ETHARP_STATE_STABLE) &&
#if ETHARP_TABLE_MATCH_NETIF
(arp_table[etharp_cached_entry].netif == netif) &&
#endif /* ETHARP_TABLE_MATCH_NETIF */
(ip4_addr_cmp(dst_addr, &arp_table[etharp_cached_entry].ipaddr))) {
/* the per-pcb-cached entry is stable and the right one! */
ETHARP_STATS_INC(etharp.cachehit);
return etharp_output_to_arp_index(netif, q, etharp_cached_entry);
}
#if LWIP_NETIF_HWADDRHINT
}
}
#endif /* LWIP_NETIF_HWADDRHINT */
/**
* find stable entry: do this here since this is a critical path for
* throughput and etharp_find_entry() is kind of slow
*/
for (i = 0; i < ARP_TABLE_SIZE; i++) {
if ((arp_table[i].state >= ETHARP_STATE_STABLE) &&
#if ETHARP_TABLE_MATCH_NETIF
(arp_table[i].netif == netif) &&
#endif /* ETHARP_TABLE_MATCH_NETIF */
(ip4_addr_cmp(dst_addr, &arp_table[i].ipaddr))) {
/* found an existing, stable entry */
ETHARP_SET_HINT(netif, i);
return etharp_output_to_arp_index(netif, q, i);
}
}
/**
* no stable entry found, use the (slower) query function:
* queue on destination Ethernet address belonging to ipaddr
*/
return etharp_query(netif, dst_addr, q);
}
/* continuation for multicast/broadcast destinations */
/* obtain source Ethernet address of the given interface */
/* send packet directly on the link */
return ethernet_output(netif, q, (struct eth_addr *)(netif->hwaddr), dest, ETHTYPE_IP);
}
/**
* Send an ARP request for the given IP address and/or queue a packet.
*
* If the IP address was not yet in the cache, a pending ARP cache entry
* is added and an ARP request is sent for the given address. The packet
* is queued on this entry.
*
* If the IP address was already pending in the cache, a new ARP request
* is sent for the given address. The packet is queued on this entry.
*
* If the IP address was already stable in the cache, and a packet is
* given, it is directly sent and no ARP request is sent out.
*
* If the IP address was already stable in the cache, and no packet is
* given, an ARP request is sent out.
*
* @param netif The lwIP network interface on which ipaddr
* must be queried for.
* @param ipaddr The IP address to be resolved.
* @param q If non-NULL, a pbuf that must be delivered to the IP address.
* q is not freed by this function.
*
* @note q must only be ONE packet, not a packet queue!
*
* @return
* - ERR_BUF Could not make room for Ethernet header.
* - ERR_MEM Hardware address unknown, and no more ARP entries available
* to query for address or queue the packet.
* - ERR_MEM Could not queue packet due to memory shortage.
* - ERR_RTE No route to destination (no gateway to external networks).
* - ERR_ARG Non-unicast address given, those will not appear in ARP cache.
*
*/
err_t etharp_query(struct netif *netif, const ip4_addr_t *ipaddr, struct pbuf *q)
{
struct eth_addr *srcaddr = (struct eth_addr *)netif->hwaddr;
err_t result = ERR_MEM;
int is_new_entry = 0;
s8_t i; /* ARP entry index */
/* non-unicast address? */
if (ip4_addr_isbroadcast(ipaddr, netif) || ip4_addr_ismulticast(ipaddr) || ip4_addr_isany(ipaddr)) {
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_query: will not add non-unicast IP address to ARP cache\n"));
return ERR_ARG;
}
/* find entry in ARP cache, ask to create entry if queueing packet */
i = etharp_find_entry(ipaddr, ETHARP_FLAG_TRY_HARD, netif);
/* could not find or create entry? */
if (i < 0) {
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_query: could not create ARP entry\n"));
if (q) {
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_query: packet dropped\n"));
ETHARP_STATS_INC(etharp.memerr);
}
return (err_t) i;
}
/* mark a fresh entry as pending (we just sent a request) */
if (arp_table[i].state == ETHARP_STATE_EMPTY) {
is_new_entry = 1;
arp_table[i].state = ETHARP_STATE_PENDING;
/* record network interface for re-sending arp request in etharp_tmr */
arp_table[i].netif = netif;
}
/* { i is either a STABLE or (new or existing) PENDING entry } */
LWIP_ASSERT("arp_table[i].state == PENDING or STABLE", ((arp_table[i].state == ETHARP_STATE_PENDING) || (arp_table[i].state >= ETHARP_STATE_STABLE)));
/* do we have a new entry? or an implicit query request? */
if (is_new_entry || (q == NULL)) {
/* try to resolve it; send out ARP request */
result = etharp_request(netif, ipaddr);
if (result != ERR_OK) {
/* ARP request couldn't be sent */
/**
* We don't re-send arp request in etharp_tmr, but we still queue packets,
* since this failure could be temporary, and the next packet calling
* etharp_query again could lead to sending the queued packets.
*/
}
if (q == NULL) {
return result;
}
}
/* packet given? */
LWIP_ASSERT("q != NULL", q != NULL);
/* stable entry? */
if (arp_table[i].state >= ETHARP_STATE_STABLE) {
/* we have a valid IP->Ethernet address mapping */
ETHARP_SET_HINT(netif, i);
/* send the packet */
result = ethernet_output(netif, q, srcaddr, &(arp_table[i].ethaddr), ETHTYPE_IP);
/* pending entry? (either just created or already pending */
} else if (arp_table[i].state == ETHARP_STATE_PENDING) {
/* entry is still pending, queue the given packet 'q' */
struct pbuf *p;
int copy_needed = 0;
/**
* IF q includes a PBUF_REF, PBUF_POOL or PBUF_RAM, we have no choice but
* to copy the whole queue into a new PBUF_RAM (see bug #11400)
* PBUF_ROMs can be left as they are, since ROM must not get changed.
*/
p = q;
while (p) {
LWIP_ASSERT("no packet queues allowed!", (p->len != p->tot_len) || (p->next == 0));
if (p->type != PBUF_ROM) {
copy_needed = 1;
break;
}
p = p->next;
}
if (copy_needed) {
/* copy the whole packet into new pbufs */
p = pbuf_alloc(PBUF_LINK, p->tot_len, PBUF_RAM);
if (p != NULL) {
if (pbuf_copy(p, q) != ERR_OK) {
pbuf_free(p);
p = NULL;
}
}
} else {
/* referencing the old pbuf is enough */
p = q;
pbuf_ref(p);
}
/* packet could be taken over? */
if (p != NULL) {
/* queue packet ... */
#if ARP_QUEUEING
struct etharp_q_entry *new_entry;
/* allocate a new arp queue entry */
new_entry = (struct etharp_q_entry *)memp_malloc(MEMP_ARP_QUEUE);
if (new_entry != NULL) {
unsigned int qlen = 0;
new_entry->next = 0;
new_entry->p = p;
if (arp_table[i].q != NULL) {
/* queue was already existent, append the new entry to the end */
struct etharp_q_entry *r;
r = arp_table[i].q;
qlen++;
while (r->next != NULL) {
r = r->next;
qlen++;
}
r->next = new_entry;
} else {
/* queue did not exist, first item in queue */
arp_table[i].q = new_entry;
}
#if ARP_QUEUE_LEN
if (qlen >= ARP_QUEUE_LEN) {
struct etharp_q_entry *old;
old = arp_table[i].q;
arp_table[i].q = arp_table[i].q->next;
pbuf_free(old->p);
memp_free(MEMP_ARP_QUEUE, old);
}
#endif /* ARP_QUEUE_LEN */
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_query: queued packet %p on ARP entry %" S16_F "\n", (void *)q, (s16_t) i));
result = ERR_OK;
} else {
/* the pool MEMP_ARP_QUEUE is empty */
pbuf_free(p);
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_query: could not queue a copy of PBUF_REF packet %p (out of memory)\n", (void *)q));
result = ERR_MEM;
}
#else /* ARP_QUEUEING */
/* always queue one packet per ARP request only, freeing a previously queued packet */
if (arp_table[i].q != NULL) {
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_query: dropped previously queued packet %p for ARP entry %" S16_F "\n", (void *)q, (s16_t) i));
pbuf_free(arp_table[i].q);
}
arp_table[i].q = p;
result = ERR_OK;
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_query: queued packet %p on ARP entry %" S16_F "\n", (void *)q, (s16_t) i));
#endif /* ARP_QUEUEING */
} else {
ETHARP_STATS_INC(etharp.memerr);
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_query: could not queue a copy of PBUF_REF packet %p (out of memory)\n", (void *)q));
result = ERR_MEM;
}
}
return result;
}
/**
* Send a raw ARP packet (opcode and all addresses can be modified)
*
* @param netif the lwip network interface on which to send the ARP packet
* @param ethsrc_addr the source MAC address for the ethernet header
* @param ethdst_addr the destination MAC address for the ethernet header
* @param hwsrc_addr the source MAC address for the ARP protocol header
* @param ipsrc_addr the source IP address for the ARP protocol header
* @param hwdst_addr the destination MAC address for the ARP protocol header
* @param ipdst_addr the destination IP address for the ARP protocol header
* @param opcode the type of the ARP packet
* @return ERR_OK if the ARP packet has been sent
* ERR_MEM if the ARP packet couldn't be allocated
* any other err_t on failure
*/
static err_t etharp_raw(struct netif *netif, const struct eth_addr *ethsrc_addr, const struct eth_addr *ethdst_addr, const struct eth_addr *hwsrc_addr, const ip4_addr_t *ipsrc_addr, const struct eth_addr *hwdst_addr, const ip4_addr_t *ipdst_addr, const u16_t opcode)
{
struct pbuf *p;
err_t result = ERR_OK;
struct etharp_hdr *hdr;
LWIP_ASSERT("netif != NULL", netif != NULL);
/* allocate a pbuf for the outgoing ARP request packet */
p = pbuf_alloc(PBUF_LINK, SIZEOF_ETHARP_HDR, PBUF_RAM);
/* could allocate a pbuf for an ARP request? */
if (p == NULL) {
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE | LWIP_DBG_LEVEL_SERIOUS, ("etharp_raw: could not allocate pbuf for ARP request.\n"));
ETHARP_STATS_INC(etharp.memerr);
return ERR_MEM;
}
LWIP_ASSERT("check that first pbuf can hold struct etharp_hdr", (p->len >= SIZEOF_ETHARP_HDR));
hdr = (struct etharp_hdr *)p->payload;
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_raw: sending raw ARP packet.\n"));
hdr->opcode = lwip_htons(opcode);
LWIP_ASSERT("netif->hwaddr_len must be the same as ETH_HWADDR_LEN for etharp!", (netif->hwaddr_len == ETH_HWADDR_LEN));
/* Write the ARP MAC-Addresses */
ETHADDR16_COPY(&hdr->shwaddr, hwsrc_addr);
ETHADDR16_COPY(&hdr->dhwaddr, hwdst_addr);
/**
* Copy struct ip4_addr2 to aligned ip4_addr, to support compilers without
* structure packing.
*/
IPADDR2_COPY(&hdr->sipaddr, ipsrc_addr);
IPADDR2_COPY(&hdr->dipaddr, ipdst_addr);
hdr->hwtype = PP_HTONS(HWTYPE_ETHERNET);
hdr->proto = PP_HTONS(ETHTYPE_IP);
/* set hwlen and protolen */
hdr->hwlen = ETH_HWADDR_LEN;
hdr->protolen = sizeof(ip4_addr_t);
/* send ARP query */
#if LWIP_AUTOIP
/**
* If we are using Link-Local, all ARP packets that contain a Link-Local
* 'sender IP address' MUST be sent using link-layer broadcast instead of
* link-layer unicast. (See RFC3927 Section 2.5, last paragraph)
*/
if (ip4_addr_islinklocal(ipsrc_addr)) {
ethernet_output(netif, p, ethsrc_addr, ðbroadcast, ETHTYPE_ARP);
} else
#endif /* LWIP_AUTOIP */
{
ethernet_output(netif, p, ethsrc_addr, ethdst_addr, ETHTYPE_ARP);
}
ETHARP_STATS_INC(etharp.xmit);
/* free ARP query packet */
pbuf_free(p);
p = NULL;
/* could not allocate pbuf for ARP request */
return result;
}
/**
* Send an ARP request packet asking for ipaddr to a specific eth address.
* Used to send unicast request to refresh the ARP table just before an entry
* times out
*
* @param netif the lwip network interface on which to send the request
* @param ipaddr the IP address for which to ask
* @param hw_dst_addr the ethernet address to send this packet to
* @return ERR_OK if the request has been sent
* ERR_MEM if the ARP packet couldn't be allocated
* any other err_t on failure
*/
static err_t etharp_request_dst(struct netif *netif, const ip4_addr_t *ipaddr, const struct eth_addr *hw_dst_addr)
{
return etharp_raw(netif, (struct eth_addr *)netif->hwaddr, hw_dst_addr, (struct eth_addr *)netif->hwaddr, netif_ip4_addr(netif), ðzero, ipaddr, ARP_REQUEST);
}
/**
* Send an ARP request packet asking for ipaddr.
*
* @param netif the lwip network interface on which to send the request
* @param ipaddr the IP address for which to ask
* @return ERR_OK if the request has been sent
* ERR_MEM if the ARP packet couldn't be allocated
* any other err_t on failure
*/
err_t etharp_request(struct netif *netif, const ip4_addr_t *ipaddr)
{
LWIP_DEBUGF(ETHARP_DEBUG | LWIP_DBG_TRACE, ("etharp_request: sending ARP request.\n"));
return etharp_request_dst(netif, ipaddr, ðbroadcast);
}
#endif /* LWIP_IPV4 && LWIP_ARP */
#endif /* LWIP_ARP || LWIP_ETHERNET */
|
const Sequelize = require('sequelize');
require('dotenv').config();
let sequelize;
if(process.env.JAWSDB_URL){
sequelize = new Sequelize(process.env.JAWSDB_URL)
}
else {
sequelize = new Sequelize(
process.env.DB_NAME,
process.env.DB_USER,
process.env.DB_PASSWORD,
{
host: 'localhost',
dialect: 'mysql',
port: 3306
}
);
}
module.exports = sequelize;
|
(function($){
$(function(){
$('.sidenav').sidenav();
}); // end of document ready
})(jQuery); // end of jQuery name space
|
import React from 'react';
const HighlightContext = React.createContext({
highlightedPlayer: null,
setHighlightedPlayer: () => { },
});
export default HighlightContext;
|
/*---------------------------------------------------------------*/
/*--- begin guest_x86_defs.h ---*/
/*---------------------------------------------------------------*/
/*
This file is part of Valgrind, a dynamic binary instrumentation
framework.
Copyright (C) 2004-2015 OpenWorks LLP
info@open-works.net
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
The GNU General Public License is contained in the file COPYING.
Neither the names of the U.S. Department of Energy nor the
University of California nor the names of its contributors may be
used to endorse or promote products derived from this software
without prior written permission.
*/
/* Only to be used within the guest-x86 directory. */
#ifndef __VEX_GUEST_X86_DEFS_H
#define __VEX_GUEST_X86_DEFS_H
#include "libvex_basictypes.h"
#include "libvex_guest_x86.h" // VexGuestX86State
#include "libvex_emnote.h" // VexEmNote
#include "guest_generic_bb_to_IR.h" // DisResult
/*---------------------------------------------------------*/
/*--- x86 to IR conversion ---*/
/*---------------------------------------------------------*/
/* Convert one x86 insn to IR. See the type DisOneInstrFn in
bb_to_IR.h. */
extern
DisResult disInstr_X86 ( IRSB* irbb,
Bool (*resteerOkFn) ( void*, Addr ),
Bool resteerCisOk,
void* callback_opaque,
const UChar* guest_code,
Long delta,
Addr guest_IP,
VexArch guest_arch,
const VexArchInfo* archinfo,
const VexAbiInfo* abiinfo,
VexEndness host_endness,
Bool sigill_diag );
/* Used by the optimiser to specialise calls to helpers. */
extern
IRExpr* guest_x86_spechelper ( const HChar* function_name,
IRExpr** args,
IRStmt** precedingStmts,
Int n_precedingStmts );
/* Describes to the optimiser which part of the guest state require
precise memory exceptions. This is logically part of the guest
state description. */
extern
Bool guest_x86_state_requires_precise_mem_exns ( Int, Int,
VexRegisterUpdates );
extern
VexGuestLayout x86guest_layout;
/*---------------------------------------------------------*/
/*--- x86 guest helpers ---*/
/*---------------------------------------------------------*/
/* --- CLEAN HELPERS --- */
extern UInt x86g_calculate_eflags_all (
UInt cc_op, UInt cc_dep1, UInt cc_dep2, UInt cc_ndep
);
VEX_REGPARM(3)
extern UInt x86g_calculate_eflags_c (
UInt cc_op, UInt cc_dep1, UInt cc_dep2, UInt cc_ndep
);
extern UInt x86g_calculate_condition (
UInt/*X86Condcode*/ cond,
UInt cc_op,
UInt cc_dep1, UInt cc_dep2, UInt cc_ndep
);
extern UInt x86g_calculate_FXAM ( UInt tag, ULong dbl );
extern ULong x86g_calculate_RCR (
UInt arg, UInt rot_amt, UInt eflags_in, UInt sz
);
extern ULong x86g_calculate_RCL (
UInt arg, UInt rot_amt, UInt eflags_in, UInt sz
);
extern UInt x86g_calculate_daa_das_aaa_aas ( UInt AX_and_flags, UInt opcode );
extern UInt x86g_calculate_aad_aam ( UInt AX_and_flags, UInt opcode );
extern ULong x86g_check_fldcw ( UInt fpucw );
extern UInt x86g_create_fpucw ( UInt fpround );
extern ULong x86g_check_ldmxcsr ( UInt mxcsr );
extern UInt x86g_create_mxcsr ( UInt sseround );
/* Translate a guest virtual_addr into a guest linear address by
consulting the supplied LDT/GDT structures. Their representation
must be as specified in pub/libvex_guest_x86.h. To indicate a
translation failure, 1<<32 is returned. On success, the lower 32
bits of the returned result indicate the linear address.
*/
extern
ULong x86g_use_seg_selector ( HWord ldt, HWord gdt,
UInt seg_selector, UInt virtual_addr );
extern ULong x86g_calculate_mmx_pmaddwd ( ULong, ULong );
extern ULong x86g_calculate_mmx_psadbw ( ULong, ULong );
/* --- DIRTY HELPERS --- */
extern ULong x86g_dirtyhelper_loadF80le ( Addr );
extern void x86g_dirtyhelper_storeF80le ( Addr, ULong );
extern void x86g_dirtyhelper_CPUID_sse0 ( VexGuestX86State* );
extern void x86g_dirtyhelper_CPUID_mmxext ( VexGuestX86State* );
extern void x86g_dirtyhelper_CPUID_sse1 ( VexGuestX86State* );
extern void x86g_dirtyhelper_CPUID_sse2 ( VexGuestX86State* );
extern void x86g_dirtyhelper_CPUID_sse3 ( VexGuestX86State* );
extern void x86g_dirtyhelper_FINIT ( VexGuestX86State* );
extern void x86g_dirtyhelper_FXSAVE ( VexGuestX86State*, HWord );
extern void x86g_dirtyhelper_FSAVE ( VexGuestX86State*, HWord );
extern void x86g_dirtyhelper_FSTENV ( VexGuestX86State*, HWord );
extern ULong x86g_dirtyhelper_RDTSC ( void );
extern UInt x86g_dirtyhelper_IN ( UInt portno, UInt sz/*1,2 or 4*/ );
extern void x86g_dirtyhelper_OUT ( UInt portno, UInt data,
UInt sz/*1,2 or 4*/ );
extern void x86g_dirtyhelper_SxDT ( void* address,
UInt op /* 0 or 1 */ );
extern VexEmNote
x86g_dirtyhelper_FXRSTOR ( VexGuestX86State*, HWord );
extern VexEmNote
x86g_dirtyhelper_FRSTOR ( VexGuestX86State*, HWord );
extern VexEmNote
x86g_dirtyhelper_FLDENV ( VexGuestX86State*, HWord );
/*---------------------------------------------------------*/
/*--- Condition code stuff ---*/
/*---------------------------------------------------------*/
/* eflags masks */
#define X86G_CC_SHIFT_O 11
#define X86G_CC_SHIFT_S 7
#define X86G_CC_SHIFT_Z 6
#define X86G_CC_SHIFT_A 4
#define X86G_CC_SHIFT_C 0
#define X86G_CC_SHIFT_P 2
#define X86G_CC_MASK_O (1 << X86G_CC_SHIFT_O)
#define X86G_CC_MASK_S (1 << X86G_CC_SHIFT_S)
#define X86G_CC_MASK_Z (1 << X86G_CC_SHIFT_Z)
#define X86G_CC_MASK_A (1 << X86G_CC_SHIFT_A)
#define X86G_CC_MASK_C (1 << X86G_CC_SHIFT_C)
#define X86G_CC_MASK_P (1 << X86G_CC_SHIFT_P)
/* additional eflags masks */
#define X86G_CC_SHIFT_ID 21
#define X86G_CC_SHIFT_AC 18
#define X86G_CC_SHIFT_D 10
#define X86G_CC_MASK_ID (1 << X86G_CC_SHIFT_ID)
#define X86G_CC_MASK_AC (1 << X86G_CC_SHIFT_AC)
#define X86G_CC_MASK_D (1 << X86G_CC_SHIFT_D)
/* FPU flag masks */
#define X86G_FC_SHIFT_C3 14
#define X86G_FC_SHIFT_C2 10
#define X86G_FC_SHIFT_C1 9
#define X86G_FC_SHIFT_C0 8
#define X86G_FC_MASK_C3 (1 << X86G_FC_SHIFT_C3)
#define X86G_FC_MASK_C2 (1 << X86G_FC_SHIFT_C2)
#define X86G_FC_MASK_C1 (1 << X86G_FC_SHIFT_C1)
#define X86G_FC_MASK_C0 (1 << X86G_FC_SHIFT_C0)
/* %EFLAGS thunk descriptors. A four-word thunk is used to record
details of the most recent flag-setting operation, so the flags can
be computed later if needed. It is possible to do this a little
more efficiently using a 3-word thunk, but that makes it impossible
to describe the flag data dependencies sufficiently accurately for
Memcheck. Hence 4 words are used, with minimal loss of efficiency.
The four words are:
CC_OP, which describes the operation.
CC_DEP1 and CC_DEP2. These are arguments to the operation.
We want Memcheck to believe that the resulting flags are
data-dependent on both CC_DEP1 and CC_DEP2, hence the
name DEP.
CC_NDEP. This is a 3rd argument to the operation which is
sometimes needed. We arrange things so that Memcheck does
not believe the resulting flags are data-dependent on CC_NDEP
("not dependent").
To make Memcheck believe that (the definedness of) the encoded
flags depends only on (the definedness of) CC_DEP1 and CC_DEP2
requires two things:
(1) In the guest state layout info (x86guest_layout), CC_OP and
CC_NDEP are marked as always defined.
(2) When passing the thunk components to an evaluation function
(calculate_condition, calculate_eflags, calculate_eflags_c) the
IRCallee's mcx_mask must be set so as to exclude from
consideration all passed args except CC_DEP1 and CC_DEP2.
Strictly speaking only (2) is necessary for correctness. However,
(1) helps efficiency in that since (2) means we never ask about the
definedness of CC_OP or CC_NDEP, we may as well not even bother to
track their definedness.
When building the thunk, it is always necessary to write words into
CC_DEP1 and CC_DEP2, even if those args are not used given the
CC_OP field (eg, CC_DEP2 is not used if CC_OP is CC_LOGIC1/2/4).
This is important because otherwise Memcheck could give false
positives as it does not understand the relationship between the
CC_OP field and CC_DEP1 and CC_DEP2, and so believes that the
definedness of the stored flags always depends on both CC_DEP1 and
CC_DEP2.
However, it is only necessary to set CC_NDEP when the CC_OP value
requires it, because Memcheck ignores CC_NDEP, and the evaluation
functions do understand the CC_OP fields and will only examine
CC_NDEP for suitable values of CC_OP.
A summary of the field usages is:
Operation DEP1 DEP2 NDEP
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
add/sub/mul first arg second arg unused
adc/sbb first arg (second arg)
XOR old_carry old_carry
and/or/xor result zero unused
inc/dec result zero old_carry
shl/shr/sar result subshifted- unused
result
rol/ror result zero old_flags
copy old_flags zero unused.
Therefore Memcheck will believe the following:
* add/sub/mul -- definedness of result flags depends on definedness
of both args.
* adc/sbb -- definedness of result flags depends on definedness of
both args and definedness of the old C flag. Because only two
DEP fields are available, the old C flag is XOR'd into the second
arg so that Memcheck sees the data dependency on it. That means
the NDEP field must contain a second copy of the old C flag
so that the evaluation functions can correctly recover the second
arg.
* and/or/xor are straightforward -- definedness of result flags
depends on definedness of result value.
* inc/dec -- definedness of result flags depends only on
definedness of result. This isn't really true -- it also depends
on the old C flag. However, we don't want Memcheck to see that,
and so the old C flag must be passed in NDEP and not in DEP2.
It's inconceivable that a compiler would generate code that puts
the C flag in an undefined state, then does an inc/dec, which
leaves C unchanged, and then makes a conditional jump/move based
on C. So our fiction seems a good approximation.
* shl/shr/sar -- straightforward, again, definedness of result
flags depends on definedness of result value. The subshifted
value (value shifted one less) is also needed, but its
definedness is the same as the definedness of the shifted value.
* rol/ror -- these only set O and C, and leave A Z C P alone.
However it seems prudent (as per inc/dec) to say the definedness
of all resulting flags depends on the definedness of the result,
hence the old flags must go in as NDEP and not DEP2.
* rcl/rcr are too difficult to do in-line, and so are done by a
helper function. They are not part of this scheme. The helper
function takes the value to be rotated, the rotate amount and the
old flags, and returns the new flags and the rotated value.
Since the helper's mcx_mask does not have any set bits, Memcheck
will lazily propagate undefinedness from any of the 3 args into
both results (flags and actual value).
*/
enum {
X86G_CC_OP_COPY=0, /* DEP1 = current flags, DEP2 = 0, NDEP = unused */
/* just copy DEP1 to output */
X86G_CC_OP_ADDB, /* 1 */
X86G_CC_OP_ADDW, /* 2 DEP1 = argL, DEP2 = argR, NDEP = unused */
X86G_CC_OP_ADDL, /* 3 */
X86G_CC_OP_SUBB, /* 4 */
X86G_CC_OP_SUBW, /* 5 DEP1 = argL, DEP2 = argR, NDEP = unused */
X86G_CC_OP_SUBL, /* 6 */
X86G_CC_OP_ADCB, /* 7 */
X86G_CC_OP_ADCW, /* 8 DEP1 = argL, DEP2 = argR ^ oldCarry, NDEP = oldCarry */
X86G_CC_OP_ADCL, /* 9 */
X86G_CC_OP_SBBB, /* 10 */
X86G_CC_OP_SBBW, /* 11 DEP1 = argL, DEP2 = argR ^ oldCarry, NDEP = oldCarry */
X86G_CC_OP_SBBL, /* 12 */
X86G_CC_OP_LOGICB, /* 13 */
X86G_CC_OP_LOGICW, /* 14 DEP1 = result, DEP2 = 0, NDEP = unused */
X86G_CC_OP_LOGICL, /* 15 */
X86G_CC_OP_INCB, /* 16 */
X86G_CC_OP_INCW, /* 17 DEP1 = result, DEP2 = 0, NDEP = oldCarry (0 or 1) */
X86G_CC_OP_INCL, /* 18 */
X86G_CC_OP_DECB, /* 19 */
X86G_CC_OP_DECW, /* 20 DEP1 = result, DEP2 = 0, NDEP = oldCarry (0 or 1) */
X86G_CC_OP_DECL, /* 21 */
X86G_CC_OP_SHLB, /* 22 DEP1 = res, DEP2 = res', NDEP = unused */
X86G_CC_OP_SHLW, /* 23 where res' is like res but shifted one bit less */
X86G_CC_OP_SHLL, /* 24 */
X86G_CC_OP_SHRB, /* 25 DEP1 = res, DEP2 = res', NDEP = unused */
X86G_CC_OP_SHRW, /* 26 where res' is like res but shifted one bit less */
X86G_CC_OP_SHRL, /* 27 */
X86G_CC_OP_ROLB, /* 28 */
X86G_CC_OP_ROLW, /* 29 DEP1 = res, DEP2 = 0, NDEP = old flags */
X86G_CC_OP_ROLL, /* 30 */
X86G_CC_OP_RORB, /* 31 */
X86G_CC_OP_RORW, /* 32 DEP1 = res, DEP2 = 0, NDEP = old flags */
X86G_CC_OP_RORL, /* 33 */
X86G_CC_OP_UMULB, /* 34 */
X86G_CC_OP_UMULW, /* 35 DEP1 = argL, DEP2 = argR, NDEP = unused */
X86G_CC_OP_UMULL, /* 36 */
X86G_CC_OP_SMULB, /* 37 */
X86G_CC_OP_SMULW, /* 38 DEP1 = argL, DEP2 = argR, NDEP = unused */
X86G_CC_OP_SMULL, /* 39 */
X86G_CC_OP_NUMBER
};
typedef
enum {
X86CondO = 0, /* overflow */
X86CondNO = 1, /* no overflow */
X86CondB = 2, /* below */
X86CondNB = 3, /* not below */
X86CondZ = 4, /* zero */
X86CondNZ = 5, /* not zero */
X86CondBE = 6, /* below or equal */
X86CondNBE = 7, /* not below or equal */
X86CondS = 8, /* negative */
X86CondNS = 9, /* not negative */
X86CondP = 10, /* parity even */
X86CondNP = 11, /* not parity even */
X86CondL = 12, /* jump less */
X86CondNL = 13, /* not less */
X86CondLE = 14, /* less or equal */
X86CondNLE = 15, /* not less or equal */
X86CondAlways = 16 /* HACK */
}
X86Condcode;
#endif /* ndef __VEX_GUEST_X86_DEFS_H */
/*---------------------------------------------------------------*/
/*--- end guest_x86_defs.h ---*/
/*---------------------------------------------------------------*/
|
// Copyright (c) 2020, suganya and contributors
// For license information, please see license.txt
frappe.ui.form.on('Case', {
// refresh: function(frm) {
// }
});
|
import os
import ave.config
def load(home):
path = os.path.join(home, '.ave', 'config', 'gerrit.json')
return ave.config.load(path)
def validate(config):
for key in ['host', 'port', 'user']:
if key not in config:
raise Exception('missing gerrit configuration key: %s' % key)
if type(config['host']) not in [str, unicode]:
raise Exception('host must be a string')
if type(config['port']) != int:
raise Exception('port must be an integer')
if type(config['user']) not in [str, unicode]:
raise Exception('user must a string')
if config['user'].startswith('REPLACE THIS'):
raise Exception(
'user must be the name part of the email address that has been '
'registered as a gerrit user. i.e. the "jane.doe" part from the '
'jane.doe@sonymobile.com email address. PLEASE EDIT your gerrit '
'configuration file (normally $HOME/.ave/config/gerrit.json)'
)
return config
|
// (C) Copyright 2015 Martin Dougiamas
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// We use this code for handling unexpected errors.
// Using JS confirm function we are sure that the user get notified in a Mobile device.
// This script should be added at the begining of the index.html and it should only use native javascript functions.
var appVersion = '1.0 (2018)',
reportInBackgroundName = 'mmCoreReportInBackground',
errors = [],
ignoredFiles = ['www/index.html#/site/mod_page', 'www/index.html#/site/mod_resource', 'www/index.html#/site/mm_course-section'],
reportedOnDBReady = false;
/**
* Check if error should be reported in background. If setting is not set, a confirm modal will be shown.
*
* @return {Boolean} True if should be reported in background, false otherwise.
*/
function shouldReportInBackground() {
if (localStorage && localStorage.getItem && localStorage.setItem) {
return localStorage.getItem(reportInBackgroundName) === '1';
}
return false;
}
/**
* Add the storage type to the error report and send it.
*
* @param {String} reportUrl URL to report the error.
* @param {Object} db DB.
*/
function getStorageAndReport(reportUrl, db) {
if (!reportedOnDBReady) {
reportedOnDBReady = true;
reportUrl = reportUrl + '&storage=' + encodeURIComponent(db.getType());
sendError(reportUrl);
}
}
/**
* Gather the needed data to report an error and reports it.
*/
function sendErrorReport(msg, url, lineNumber) {
url = url || "";
lineNumber = lineNumber || 0;
var reportUrl = 'http://prototype.moodle.net/mobile/feedback/mmfeedback.php?message=' + encodeURIComponent(msg) +
'&file=' + encodeURIComponent(url) + '&line=' + encodeURIComponent(lineNumber) + '&appv=' +
encodeURIComponent(appVersion) + '&bg=1';
if (window.device) {
reportUrl = reportUrl + '&platform=' + encodeURIComponent(window.device.platform) +
'&model=' + encodeURIComponent(window.device.model) +
'&osversion=' + encodeURIComponent(window.device.version) +
'&cordova=' + encodeURIComponent(window.device.cordova);
}
if (window.location) {
reportUrl = reportUrl + '&localurl=' + encodeURIComponent(window.location.href);
}
if (navigator.userAgent) {
reportUrl = reportUrl + '&useragent=' + encodeURIComponent(navigator.userAgent);
}
if (typeof ydn != 'undefined' && ydn.db && ydn.db.Storage) {
// Detect Storage type by default.
var db = new ydn.db.Storage('test', {}, {});
if (db && db.getType && db.onReady) {
db.onReady(function() {
getStorageAndReport(reportUrl, db);
});
setTimeout(function() {
getStorageAndReport(reportUrl, db);
}, 1000);
return;
}
}
sendError(reportUrl);
}
/**
* Send error to the server.
*
* @param {String} reportUrl URL to report the error.
*/
function sendError(reportUrl) {
var xhr = new XMLHttpRequest();
xhr.open('GET', reportUrl, true);
xhr.send();
}
/**
* Check if an error should be ignored.
*
* @return {Boolean} True if error should be ignored, false otherwise.
*/
function shouldBeIgnored() {
if (!url) {
return false;
}
for (var i = 0; i < ignoredFiles.length; i++) {
if (url.indexOf(ignoredFiles[i]) > -1) {
return true;
}
}
return false;
}
window.onerror = function(msg, url, lineNumber) {
try {
var errorReported;
function reportError() {
if (!errorReported) {
errorReported = true;
sendErrorReport(msg, url, lineNumber);
}
}
if (typeof msg == "string" && errors.indexOf(msg) == -1 && !shouldBeIgnored()) {
// Error hasn't happened yet.
errors.push(msg);
// Only report errors in background. See MOBILE-1889.
if (shouldReportInBackground()) {
// Wait for device ready so we can retrieve device data. In most cases device will already be ready.
document.addEventListener('deviceready', reportError);
// Report error if device ready isn't fired after 5 seconds.
setTimeout(reportError, 5000);
}
}
// This may help debugging if we use logging apps in iOs or Android.
if (typeof console != "undefined" && typeof console.log == "function") {
console.log(msg);
}
} catch(ex) {
// Something bad happened.
}
// Let default error handler run.
return false;
};
|
#include "../../lv_examples.h"
#if LV_USE_GRID && LV_BUILD_EXAMPLES
/**
* Demonstrate track placement
*/
void lv_example_grid_4(void)
{
static lv_coord_t col_dsc[] = {60, 60, 60, LV_GRID_TEMPLATE_LAST};
static lv_coord_t row_dsc[] = {40, 40, 40, LV_GRID_TEMPLATE_LAST};
/*Add space between the columns and move the rows to the bottom (end)*/
/*Create a container with grid*/
lv_obj_t * cont = lv_obj_create(lv_scr_act());
lv_obj_set_grid_align(cont, LV_GRID_ALIGN_SPACE_BETWEEN, LV_GRID_ALIGN_END);
lv_obj_set_grid_dsc_array(cont, col_dsc, row_dsc);
lv_obj_set_size(cont, 300, 220);
lv_obj_center(cont);
lv_obj_t * label;
lv_obj_t * obj;
uint32_t i;
for(i = 0; i < 9; i++) {
uint8_t col = i % 3;
uint8_t row = i / 3;
obj = lv_obj_create(cont);
/*Stretch the cell horizontally and vertically too
*Set span to 1 to make the cell 1 column/row sized*/
lv_obj_set_grid_cell(obj, LV_GRID_ALIGN_STRETCH, col, 1,
LV_GRID_ALIGN_STRETCH, row, 1);
label = lv_label_create(obj);
lv_label_set_text_fmt(label, "%d,%d", col, row);
lv_obj_center(label);
}
}
#endif
|
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import json
import os
from xml.dom import minidom
from pants.backend.project_info.tasks.idea_plugin_gen import IDEA_PLUGIN_VERSION, IdeaPluginGen
from pants.base.build_environment import get_buildroot
from pants.base.cmd_line_spec_parser import CmdLineSpecParser
from pants.util.contextutil import temporary_file
from pants_test.pants_run_integration_test import PantsRunIntegrationTest
class IdeaPluginIntegrationTest(PantsRunIntegrationTest):
def _do_check(self, project_dir_path, expected_project_path, expected_targets,
incremental_import=None):
"""Check to see that the project contains the expected source folders."""
iws_file = os.path.join(
project_dir_path, f'{IdeaPluginGen.get_project_name(expected_targets)}.iws'
)
self.assertTrue(os.path.exists(iws_file))
dom = minidom.parse(iws_file)
self.assertEqual(1, len(dom.getElementsByTagName("project")))
project = dom.getElementsByTagName("project")[0]
self.assertEqual(1, len(project.getElementsByTagName('component')))
component = project.getElementsByTagName('component')[0]
actual_properties = component.getElementsByTagName('property')
valid_property_names = {
'targets',
'project_path',
'pants_idea_plugin_version',
'incremental_import'
}
self.assertTrue({p.getAttribute('name')
for p in actual_properties}.issubset(valid_property_names))
self.assertTrue(len(actual_properties) >= 3)
self.assertEqual('targets', actual_properties[0].getAttribute('name'))
actual_targets = json.loads(actual_properties[0].getAttribute('value'))
abs_expected_target_specs = [os.path.join(get_buildroot(), relative_spec) for relative_spec in expected_targets]
self.assertEqual(abs_expected_target_specs, actual_targets)
self.assertEqual('project_path', actual_properties[1].getAttribute('name'))
actual_project_path = actual_properties[1].getAttribute('value')
self.assertEqual(os.path.join(get_buildroot(), expected_project_path), actual_project_path)
self.assertEqual('pants_idea_plugin_version', actual_properties[2].getAttribute('name'))
self.assertEqual(IDEA_PLUGIN_VERSION, actual_properties[2].getAttribute('value'))
incremental_import_props = [p
for p in actual_properties
if p.getAttribute('name') == 'incremental_import']
if incremental_import is None:
self.assertEqual(incremental_import_props, [])
else:
self.assertEqual([str(incremental_import)], [p.getAttribute('value')
for p in incremental_import_props])
def _get_project_dir(self, output_file):
with open(output_file, 'r') as result:
return result.readlines()[0].strip()
def _run_and_check(self, target_specs, incremental_import=None):
"""
Invoke idea-plugin goal and check for target specs and project in the
generated project and workspace file.
:param target_specs: list of target specs
:return: n/a
"""
self.assertTrue(target_specs, "targets are empty")
spec_parser = CmdLineSpecParser(get_buildroot())
# project_path is always the directory of the first target,
# which is where intellij is going to zoom in under project view.
project_path = spec_parser.parse_spec(target_specs[0]).directory
with self.temporary_workdir() as workdir:
with temporary_file(root_dir=workdir, cleanup=True) as output_file:
args = [
'idea-plugin',
f'--output-file={output_file.name}',
'--no-open',
]
if incremental_import is not None:
args.append(f'--incremental-import={incremental_import}')
pants_run = self.run_pants_with_workdir(args + target_specs, workdir)
self.assert_success(pants_run)
project_dir = self._get_project_dir(output_file.name)
self.assertTrue(os.path.exists(project_dir), f"{project_dir} does not exist")
self._do_check(project_dir, project_path, target_specs, incremental_import=incremental_import)
def test_idea_plugin_single_target(self):
target = 'examples/src/scala/org/pantsbuild/example/hello:hello'
self._run_and_check([target])
def test_idea_plugin_single_directory(self):
target = 'testprojects/src/python/antlr::'
self._run_and_check([target])
def test_idea_plugin_incremental_import(self):
target = 'testprojects/src/python/antlr::'
self._run_and_check([target], incremental_import=1337)
def test_idea_plugin_multiple_targets(self):
target_a = 'examples/src/scala/org/pantsbuild/example/hello:'
target_b = 'testprojects/src/python/antlr::'
self._run_and_check([target_a, target_b])
|
/**
******************************************************************************
* @file stm32f3xx_hal_rtc.c
* @author MCD Application Team
* @version V1.4.0
* @date 16-December-2016
* @brief RTC HAL module driver.
* This file provides firmware functions to manage the following
* functionalities of the Real-Time Clock (RTC) peripheral:
* + Initialization
* + Calendar (Time and Date) configuration
* + Alarms (Alarm A and Alarm B) configuration
* + WakeUp Timer configuration
* + TimeStamp configuration
* + Tampers configuration
* + Backup Data Registers configuration
* + RTC Tamper and TimeStamp Pins Selection
* + Interrupts and flags management
*
@verbatim
===============================================================================
##### RTC Operating Condition #####
===============================================================================
[..] The real-time clock (RTC) and the RTC backup registers can be powered
from the VBAT voltage when the main VDD supply is powered off.
To retain the content of the RTC backup registers and supply the RTC
when VDD is turned off, VBAT pin can be connected to an optional
standby voltage supplied by a battery or by another source.
[..] To allow the RTC to operate even when the main digital supply (VDD)
is turned off, the VBAT pin powers the following blocks:
(#) The RTC
(#) The LSE oscillator
(#) PC13 to PC15 I/Os (when available)
[..] When the backup domain is supplied by VDD (analog switch connected
to VDD), the following functions are available:
(#) PC14 and PC15 can be used as either GPIO or LSE pins
(#) PC13 can be used as a GPIO or as the RTC_OUT pin
[..] When the backup domain is supplied by VBAT (analog switch connected
to VBAT because VDD is not present), the following functions are available:
(#) PC14 and PC15 can be used as LSE pins only
(#) PC13 can be used as the RTC_OUT pin
##### Backup Domain Reset #####
===============================================================================
[..] The backup domain reset sets all RTC registers and the RCC_BDCR
register to their reset values.
A backup domain reset is generated when one of the following events
occurs:
(#) Software reset, triggered by setting the BDRST bit in the
RCC Backup domain control register (RCC_BDCR).
(#) VDD or VBAT power on, if both supplies have previously been
powered off.
##### Backup Domain Access #####
===================================================================
[..] After reset, the backup domain (RTC registers, RTC backup data
registers and backup SRAM) is protected against possible unwanted write
accesses.
[..] To enable access to the RTC Domain and RTC registers, proceed as follows:
(#) Enable the Power Controller (PWR) APB1 interface clock using the
__HAL_RCC_PWR_CLK_ENABLE() function.
(#) Enable access to RTC domain using the HAL_PWR_EnableBkUpAccess() function.
(#) Select the RTC clock source using the __HAL_RCC_RTC_CONFIG() function.
(#) Enable RTC Clock using the __HAL_RCC_RTC_ENABLE() function.
##### How to use RTC Driver #####
===================================================================
[..]
(+) Enable the RTC domain access (see description in the section above).
(+) Configure the RTC Prescaler (Asynchronous and Synchronous) and RTC hour
format using the HAL_RTC_Init() function.
*** Time and Date configuration ***
===================================
[..]
(+) To configure the RTC Calendar (Time and Date) use the HAL_RTC_SetTime()
and HAL_RTC_SetDate() functions.
(+) To read the RTC Calendar, use the HAL_RTC_GetTime() and HAL_RTC_GetDate() functions.
*** Alarm configuration ***
===========================
[..]
(+) To configure the RTC Alarm use the HAL_RTC_SetAlarm() function.
You can also configure the RTC Alarm with interrupt mode using the
HAL_RTC_SetAlarm_IT() function.
(+) To read the RTC Alarm, use the HAL_RTC_GetAlarm() function.
*** RTC Wakeup configuration ***
================================
[..]
(+) To configure the RTC Wakeup Clock source and Counter use the HAL_RTC_SetWakeUpTimer()
function. You can also configure the RTC Wakeup timer with interrupt mode
using the HAL_RTC_SetWakeUpTimer_IT() function.
(+) To read the RTC WakeUp Counter register, use the HAL_RTC_GetWakeUpTimer()
function.
*** TimeStamp configuration ***
===============================
[..]
(+) Configure the RTC_AF trigger and enables the RTC TimeStamp using the
HAL_RTC_SetTimeStamp() function. You can also configure the RTC TimeStamp with
interrupt mode using the HAL_RTC_SetTimeStamp_IT() function.
(+) To read the RTC TimeStamp Time and Date register, use the HAL_RTC_GetTimeStamp()
function.
*** Tamper configuration ***
============================
[..]
(+) Enable the RTC Tamper and Configure the Tamper filter count, trigger Edge
or Level according to the Tamper filter (if equal to 0 Edge else Level)
value, sampling frequency, precharge or discharge and Pull-UP using the
HAL_RTC_SetTamper() function. You can configure RTC Tamper with interrupt
mode using HAL_RTC_SetTamper_IT() function.
*** Backup Data Registers configuration ***
===========================================
[..]
(+) To write to the RTC Backup Data registers, use the HAL_RTC_BKUPWrite()
function.
(+) To read the RTC Backup Data registers, use the HAL_RTC_BKUPRead()
function.
##### RTC and low power modes #####
===================================================================
[..] The MCU can be woken up from a low power mode by an RTC alternate
function.
[..] The RTC alternate functions are the RTC alarms (Alarm A and Alarm B),
RTC wakeup, RTC tamper event detection and RTC time stamp event detection.
These RTC alternate functions can wake up the system from the Stop and
Standby low power modes.
[..] The system can also wake up from low power modes without depending
on an external interrupt (Auto-wakeup mode), by using the RTC alarm
or the RTC wakeup events.
[..] The RTC provides a programmable time base for waking up from the
Stop or Standby mode at regular intervals.
Wakeup from STOP and Standby modes is possible only when the RTC clock source
is LSE or LSI.
@endverbatim
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2016 STMicroelectronics</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32f3xx_hal.h"
/** @addtogroup STM32F3xx_HAL_Driver
* @{
*/
/** @addtogroup RTC
* @brief RTC HAL module driver
* @{
*/
#ifdef HAL_RTC_MODULE_ENABLED
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions ---------------------------------------------------------*/
/** @addtogroup RTC_Exported_Functions
* @{
*/
/** @addtogroup RTC_Exported_Functions_Group1
* @brief Initialization and Configuration functions
*
@verbatim
===============================================================================
##### Initialization and de-initialization functions #####
===============================================================================
[..] This section provides functions allowing to initialize and configure the
RTC Prescaler (Synchronous and Asynchronous), RTC Hour format, disable
RTC registers Write protection, enter and exit the RTC initialization mode,
RTC registers synchronization check and reference clock detection enable.
(#) The RTC Prescaler is programmed to generate the RTC 1Hz time base.
It is split into 2 programmable prescalers to minimize power consumption.
(++) A 7-bit asynchronous prescaler and a 15-bit synchronous prescaler.
(++) When both prescalers are used, it is recommended to configure the
asynchronous prescaler to a high value to minimize power consumption.
(#) All RTC registers are Write protected. Writing to the RTC registers
is enabled by writing a key into the Write Protection register, RTC_WPR.
(#) To configure the RTC Calendar, user application should enter
initialization mode. In this mode, the calendar counter is stopped
and its value can be updated. When the initialization sequence is
complete, the calendar restarts counting after 4 RTCCLK cycles.
(#) To read the calendar through the shadow registers after Calendar
initialization, calendar update or after wakeup from low power modes
the software must first clear the RSF flag. The software must then
wait until it is set again before reading the calendar, which means
that the calendar registers have been correctly copied into the
RTC_TR and RTC_DR shadow registers.The HAL_RTC_WaitForSynchro() function
implements the above software sequence (RSF clear and RSF check).
@endverbatim
* @{
*/
/**
* @brief Initialize the RTC according to the specified parameters
* in the RTC_InitTypeDef structure and initialize the associated handle.
* @param hrtc: RTC handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTC_Init(RTC_HandleTypeDef *hrtc)
{
/* Check the RTC peripheral state */
if(hrtc == NULL)
{
return HAL_ERROR;
}
/* Check the parameters */
assert_param(IS_RTC_ALL_INSTANCE(hrtc->Instance));
assert_param(IS_RTC_HOUR_FORMAT(hrtc->Init.HourFormat));
assert_param(IS_RTC_ASYNCH_PREDIV(hrtc->Init.AsynchPrediv));
assert_param(IS_RTC_SYNCH_PREDIV(hrtc->Init.SynchPrediv));
assert_param(IS_RTC_OUTPUT(hrtc->Init.OutPut));
assert_param(IS_RTC_OUTPUT_POL(hrtc->Init.OutPutPolarity));
assert_param(IS_RTC_OUTPUT_TYPE(hrtc->Init.OutPutType));
if(hrtc->State == HAL_RTC_STATE_RESET)
{
/* Allocate lock resource and initialize it */
hrtc->Lock = HAL_UNLOCKED;
/* Initialize RTC MSP */
HAL_RTC_MspInit(hrtc);
}
/* Set RTC state */
hrtc->State = HAL_RTC_STATE_BUSY;
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
/* Set Initialization mode */
if(RTC_EnterInitMode(hrtc) != HAL_OK)
{
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
/* Set RTC state */
hrtc->State = HAL_RTC_STATE_ERROR;
return HAL_ERROR;
}
else
{
/* Clear RTC_CR FMT, OSEL and POL Bits */
hrtc->Instance->CR &= ((uint32_t)~(RTC_CR_FMT | RTC_CR_OSEL | RTC_CR_POL));
/* Set RTC_CR register */
hrtc->Instance->CR |= (uint32_t)(hrtc->Init.HourFormat | hrtc->Init.OutPut | hrtc->Init.OutPutPolarity);
/* Configure the RTC PRER */
hrtc->Instance->PRER = (uint32_t)(hrtc->Init.SynchPrediv);
hrtc->Instance->PRER |= (uint32_t)(hrtc->Init.AsynchPrediv << 16U);
/* Exit Initialization mode */
hrtc->Instance->ISR &= (uint32_t)~RTC_ISR_INIT;
hrtc->Instance->TAFCR &= (uint32_t)~RTC_TAFCR_ALARMOUTTYPE;
hrtc->Instance->TAFCR |= (uint32_t)(hrtc->Init.OutPutType);
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
/* Set RTC state */
hrtc->State = HAL_RTC_STATE_READY;
return HAL_OK;
}
}
/**
* @brief DeInitialize the RTC peripheral.
* @param hrtc: RTC handle
* @note This function doesn't reset the RTC Backup Data registers.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTC_DeInit(RTC_HandleTypeDef *hrtc)
{
uint32_t tickstart = 0U;
/* Check the parameters */
assert_param(IS_RTC_ALL_INSTANCE(hrtc->Instance));
/* Set RTC state */
hrtc->State = HAL_RTC_STATE_BUSY;
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
/* Set Initialization mode */
if(RTC_EnterInitMode(hrtc) != HAL_OK)
{
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
/* Set RTC state */
hrtc->State = HAL_RTC_STATE_ERROR;
return HAL_ERROR;
}
else
{
/* Reset TR, DR and CR registers */
hrtc->Instance->TR = 0x00000000U;
hrtc->Instance->DR = (RTC_DR_WDU_0 | RTC_DR_MU_0 | RTC_DR_DU_0);
/* Reset All CR bits except CR[2:0] */
hrtc->Instance->CR &= RTC_CR_WUCKSEL;
tickstart = HAL_GetTick();
/* Wait till WUTWF flag is set and if Time out is reached exit */
while(((hrtc->Instance->ISR) & RTC_ISR_WUTWF) == (uint32_t)RESET)
{
if((HAL_GetTick()-tickstart) > RTC_TIMEOUT_VALUE)
{
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
/* Set RTC state */
hrtc->State = HAL_RTC_STATE_TIMEOUT;
return HAL_TIMEOUT;
}
}
/* Reset all RTC CR register bits */
hrtc->Instance->CR &= 0x00000000U;
hrtc->Instance->WUTR = RTC_WUTR_WUT;
hrtc->Instance->PRER = ((uint32_t)(RTC_PRER_PREDIV_A | 0x000000FFU));
hrtc->Instance->ALRMAR = 0x00000000U;
hrtc->Instance->ALRMBR = 0x00000000U;
hrtc->Instance->SHIFTR = 0x00000000U;
hrtc->Instance->CALR = 0x00000000U;
hrtc->Instance->ALRMASSR = 0x00000000U;
hrtc->Instance->ALRMBSSR = 0x00000000U;
/* Reset ISR register and exit initialization mode */
hrtc->Instance->ISR = 0x00000000U;
/* Reset Tamper and alternate functions configuration register */
hrtc->Instance->TAFCR = 0x00000000U;
/* If RTC_CR_BYPSHAD bit = 0U, wait for synchro else this check is not needed */
if((hrtc->Instance->CR & RTC_CR_BYPSHAD) == RESET)
{
if(HAL_RTC_WaitForSynchro(hrtc) != HAL_OK)
{
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
hrtc->State = HAL_RTC_STATE_ERROR;
return HAL_ERROR;
}
}
}
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
/* De-Initialize RTC MSP */
HAL_RTC_MspDeInit(hrtc);
hrtc->State = HAL_RTC_STATE_RESET;
/* Release Lock */
__HAL_UNLOCK(hrtc);
return HAL_OK;
}
/**
* @brief Initialize the RTC MSP.
* @param hrtc: RTC handle
* @retval None
*/
__weak void HAL_RTC_MspInit(RTC_HandleTypeDef* hrtc)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hrtc);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_RTC_MspInit could be implemented in the user file
*/
}
/**
* @brief DeInitialize the RTC MSP.
* @param hrtc: RTC handle
* @retval None
*/
__weak void HAL_RTC_MspDeInit(RTC_HandleTypeDef* hrtc)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hrtc);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_RTC_MspDeInit could be implemented in the user file
*/
}
/**
* @}
*/
/** @addtogroup RTC_Exported_Functions_Group2
* @brief RTC Time and Date functions
*
@verbatim
===============================================================================
##### RTC Time and Date functions #####
===============================================================================
[..] This section provides functions allowing to configure Time and Date features
@endverbatim
* @{
*/
/**
* @brief Set RTC current time.
* @param hrtc: RTC handle
* @param sTime: Pointer to Time structure
* @param Format: Specifies the format of the entered parameters.
* This parameter can be one of the following values:
* @arg RTC_FORMAT_BIN: Binary data format
* @arg RTC_FORMAT_BCD: BCD data format
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTC_SetTime(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTime, uint32_t Format)
{
uint32_t tmpreg = 0U;
/* Check the parameters */
assert_param(IS_RTC_FORMAT(Format));
assert_param(IS_RTC_DAYLIGHT_SAVING(sTime->DayLightSaving));
assert_param(IS_RTC_STORE_OPERATION(sTime->StoreOperation));
/* Process Locked */
__HAL_LOCK(hrtc);
hrtc->State = HAL_RTC_STATE_BUSY;
if(Format == RTC_FORMAT_BIN)
{
if((hrtc->Instance->CR & RTC_CR_FMT) != (uint32_t)RESET)
{
assert_param(IS_RTC_HOUR12(sTime->Hours));
assert_param(IS_RTC_HOURFORMAT12(sTime->TimeFormat));
}
else
{
sTime->TimeFormat = 0x00U;
assert_param(IS_RTC_HOUR24(sTime->Hours));
}
assert_param(IS_RTC_MINUTES(sTime->Minutes));
assert_param(IS_RTC_SECONDS(sTime->Seconds));
tmpreg = (uint32_t)(((uint32_t)RTC_ByteToBcd2(sTime->Hours) << 16U) | \
((uint32_t)RTC_ByteToBcd2(sTime->Minutes) << 8U) | \
((uint32_t)RTC_ByteToBcd2(sTime->Seconds)) | \
(((uint32_t)sTime->TimeFormat) << 16U));
}
else
{
if((hrtc->Instance->CR & RTC_CR_FMT) != (uint32_t)RESET)
{
tmpreg = RTC_Bcd2ToByte(sTime->Hours);
assert_param(IS_RTC_HOUR12(tmpreg));
assert_param(IS_RTC_HOURFORMAT12(sTime->TimeFormat));
}
else
{
sTime->TimeFormat = 0x00U;
assert_param(IS_RTC_HOUR24(RTC_Bcd2ToByte(sTime->Hours)));
}
assert_param(IS_RTC_MINUTES(RTC_Bcd2ToByte(sTime->Minutes)));
assert_param(IS_RTC_SECONDS(RTC_Bcd2ToByte(sTime->Seconds)));
tmpreg = (((uint32_t)(sTime->Hours) << 16U) | \
((uint32_t)(sTime->Minutes) << 8U) | \
((uint32_t)sTime->Seconds) | \
((uint32_t)(sTime->TimeFormat) << 16U));
}
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
/* Set Initialization mode */
if(RTC_EnterInitMode(hrtc) != HAL_OK)
{
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
/* Set RTC state */
hrtc->State = HAL_RTC_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_ERROR;
}
else
{
/* Set the RTC_TR register */
hrtc->Instance->TR = (uint32_t)(tmpreg & RTC_TR_RESERVED_MASK);
/* Clear the bits to be configured */
hrtc->Instance->CR &= ((uint32_t)~RTC_CR_BCK);
/* Configure the RTC_CR register */
hrtc->Instance->CR |= (uint32_t)(sTime->DayLightSaving | sTime->StoreOperation);
/* Exit Initialization mode */
hrtc->Instance->ISR &= ((uint32_t)~RTC_ISR_INIT);
/* If CR_BYPSHAD bit = 0U, wait for synchro else this check is not needed */
if((hrtc->Instance->CR & RTC_CR_BYPSHAD) == RESET)
{
if(HAL_RTC_WaitForSynchro(hrtc) != HAL_OK)
{
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
hrtc->State = HAL_RTC_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_ERROR;
}
}
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
hrtc->State = HAL_RTC_STATE_READY;
__HAL_UNLOCK(hrtc);
return HAL_OK;
}
}
/**
* @brief Get RTC current time.
* @param hrtc: RTC handle
* @param sTime: Pointer to Time structure
* @param Format: Specifies the format of the entered parameters.
* This parameter can be one of the following values:
* @arg RTC_FORMAT_BIN: Binary data format
* @arg RTC_FORMAT_BCD: BCD data format
* @note You can use SubSeconds and SecondFraction (sTime structure fields returned) to convert SubSeconds
* value in second fraction ratio with time unit following generic formula:
* Second fraction ratio * time_unit= [(SecondFraction-SubSeconds)/(SecondFraction+1)] * time_unit
* This conversion can be performed only if no shift operation is pending (ie. SHFP=0) when PREDIV_S >= SS
* @note Call HAL_RTC_GetDate() after HAL_RTC_GetTime() to unlock the values
* in the higher-order calendar shadow registers.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTC_GetTime(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTime, uint32_t Format)
{
uint32_t tmpreg = 0U;
/* Check the parameters */
assert_param(IS_RTC_FORMAT(Format));
/* Get subseconds structure field from the corresponding register*/
sTime->SubSeconds = (uint32_t)(hrtc->Instance->SSR);
/* Get SecondFraction structure field from the corresponding register field*/
sTime->SecondFraction = (uint32_t)(hrtc->Instance->PRER & RTC_PRER_PREDIV_S);
/* Get the TR register */
tmpreg = (uint32_t)(hrtc->Instance->TR & RTC_TR_RESERVED_MASK);
/* Fill the structure fields with the read parameters */
sTime->Hours = (uint8_t)((tmpreg & (RTC_TR_HT | RTC_TR_HU)) >> 16U);
sTime->Minutes = (uint8_t)((tmpreg & (RTC_TR_MNT | RTC_TR_MNU)) >>8U);
sTime->Seconds = (uint8_t)(tmpreg & (RTC_TR_ST | RTC_TR_SU));
sTime->TimeFormat = (uint8_t)((tmpreg & (RTC_TR_PM)) >> 16U);
/* Check the input parameters format */
if(Format == RTC_FORMAT_BIN)
{
/* Convert the time structure parameters to Binary format */
sTime->Hours = (uint8_t)RTC_Bcd2ToByte(sTime->Hours);
sTime->Minutes = (uint8_t)RTC_Bcd2ToByte(sTime->Minutes);
sTime->Seconds = (uint8_t)RTC_Bcd2ToByte(sTime->Seconds);
}
return HAL_OK;
}
/**
* @brief Set RTC current date.
* @param hrtc: RTC handle
* @param sDate: Pointer to date structure
* @param Format: specifies the format of the entered parameters.
* This parameter can be one of the following values:
* @arg RTC_FORMAT_BIN: Binary data format
* @arg RTC_FORMAT_BCD: BCD data format
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTC_SetDate(RTC_HandleTypeDef *hrtc, RTC_DateTypeDef *sDate, uint32_t Format)
{
uint32_t datetmpreg = 0U;
/* Check the parameters */
assert_param(IS_RTC_FORMAT(Format));
/* Process Locked */
__HAL_LOCK(hrtc);
hrtc->State = HAL_RTC_STATE_BUSY;
if((Format == RTC_FORMAT_BIN) && ((sDate->Month & 0x10U) == 0x10U))
{
sDate->Month = (uint8_t)((sDate->Month & (uint8_t)~(0x10U)) + (uint8_t)0x0AU);
}
assert_param(IS_RTC_WEEKDAY(sDate->WeekDay));
if(Format == RTC_FORMAT_BIN)
{
assert_param(IS_RTC_YEAR(sDate->Year));
assert_param(IS_RTC_MONTH(sDate->Month));
assert_param(IS_RTC_DATE(sDate->Date));
datetmpreg = (((uint32_t)RTC_ByteToBcd2(sDate->Year) << 16U) | \
((uint32_t)RTC_ByteToBcd2(sDate->Month) << 8U) | \
((uint32_t)RTC_ByteToBcd2(sDate->Date)) | \
((uint32_t)sDate->WeekDay << 13U));
}
else
{
assert_param(IS_RTC_YEAR(RTC_Bcd2ToByte(sDate->Year)));
datetmpreg = RTC_Bcd2ToByte(sDate->Month);
assert_param(IS_RTC_MONTH(datetmpreg));
datetmpreg = RTC_Bcd2ToByte(sDate->Date);
assert_param(IS_RTC_DATE(datetmpreg));
datetmpreg = ((((uint32_t)sDate->Year) << 16U) | \
(((uint32_t)sDate->Month) << 8U) | \
((uint32_t)sDate->Date) | \
(((uint32_t)sDate->WeekDay) << 13U));
}
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
/* Set Initialization mode */
if(RTC_EnterInitMode(hrtc) != HAL_OK)
{
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
/* Set RTC state*/
hrtc->State = HAL_RTC_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_ERROR;
}
else
{
/* Set the RTC_DR register */
hrtc->Instance->DR = (uint32_t)(datetmpreg & RTC_DR_RESERVED_MASK);
/* Exit Initialization mode */
hrtc->Instance->ISR &= ((uint32_t)~RTC_ISR_INIT);
/* If CR_BYPSHAD bit = 0U, wait for synchro else this check is not needed */
if((hrtc->Instance->CR & RTC_CR_BYPSHAD) == RESET)
{
if(HAL_RTC_WaitForSynchro(hrtc) != HAL_OK)
{
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
hrtc->State = HAL_RTC_STATE_ERROR;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_ERROR;
}
}
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
hrtc->State = HAL_RTC_STATE_READY ;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_OK;
}
}
/**
* @brief Get RTC current date.
* @param hrtc: RTC handle
* @param sDate: Pointer to Date structure
* @param Format: Specifies the format of the entered parameters.
* This parameter can be one of the following values:
* @arg RTC_FORMAT_BIN : Binary data format
* @arg RTC_FORMAT_BCD : BCD data format
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTC_GetDate(RTC_HandleTypeDef *hrtc, RTC_DateTypeDef *sDate, uint32_t Format)
{
uint32_t datetmpreg = 0U;
/* Check the parameters */
assert_param(IS_RTC_FORMAT(Format));
/* Get the DR register */
datetmpreg = (uint32_t)(hrtc->Instance->DR & RTC_DR_RESERVED_MASK);
/* Fill the structure fields with the read parameters */
sDate->Year = (uint8_t)((datetmpreg & (RTC_DR_YT | RTC_DR_YU)) >> 16U);
sDate->Month = (uint8_t)((datetmpreg & (RTC_DR_MT | RTC_DR_MU)) >> 8U);
sDate->Date = (uint8_t)(datetmpreg & (RTC_DR_DT | RTC_DR_DU));
sDate->WeekDay = (uint8_t)((datetmpreg & (RTC_DR_WDU)) >> 13U);
/* Check the input parameters format */
if(Format == RTC_FORMAT_BIN)
{
/* Convert the date structure parameters to Binary format */
sDate->Year = (uint8_t)RTC_Bcd2ToByte(sDate->Year);
sDate->Month = (uint8_t)RTC_Bcd2ToByte(sDate->Month);
sDate->Date = (uint8_t)RTC_Bcd2ToByte(sDate->Date);
}
return HAL_OK;
}
/**
* @}
*/
/** @addtogroup RTC_Exported_Functions_Group3
* @brief RTC Alarm functions
*
@verbatim
===============================================================================
##### RTC Alarm functions #####
===============================================================================
[..] This section provides functions allowing to configure Alarm feature
@endverbatim
* @{
*/
/**
* @brief Set the specified RTC Alarm.
* @param hrtc: RTC handle
* @param sAlarm: Pointer to Alarm structure
* @param Format: Specifies the format of the entered parameters.
* This parameter can be one of the following values:
* @arg RTC_FORMAT_BIN: Binary data format
* @arg RTC_FORMAT_BCD: BCD data format
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTC_SetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Format)
{
uint32_t tickstart = 0U;
uint32_t tmpreg = 0U, subsecondtmpreg = 0U;
/* Check the parameters */
assert_param(IS_RTC_FORMAT(Format));
assert_param(IS_RTC_ALARM(sAlarm->Alarm));
assert_param(IS_RTC_ALARM_MASK(sAlarm->AlarmMask));
assert_param(IS_RTC_ALARM_DATE_WEEKDAY_SEL(sAlarm->AlarmDateWeekDaySel));
assert_param(IS_RTC_ALARM_SUB_SECOND_VALUE(sAlarm->AlarmTime.SubSeconds));
assert_param(IS_RTC_ALARM_SUB_SECOND_MASK(sAlarm->AlarmSubSecondMask));
/* Process Locked */
__HAL_LOCK(hrtc);
hrtc->State = HAL_RTC_STATE_BUSY;
if(Format == RTC_FORMAT_BIN)
{
if((hrtc->Instance->CR & RTC_CR_FMT) != (uint32_t)RESET)
{
assert_param(IS_RTC_HOUR12(sAlarm->AlarmTime.Hours));
assert_param(IS_RTC_HOURFORMAT12(sAlarm->AlarmTime.TimeFormat));
}
else
{
sAlarm->AlarmTime.TimeFormat = 0x00U;
assert_param(IS_RTC_HOUR24(sAlarm->AlarmTime.Hours));
}
assert_param(IS_RTC_MINUTES(sAlarm->AlarmTime.Minutes));
assert_param(IS_RTC_SECONDS(sAlarm->AlarmTime.Seconds));
if(sAlarm->AlarmDateWeekDaySel == RTC_ALARMDATEWEEKDAYSEL_DATE)
{
assert_param(IS_RTC_ALARM_DATE_WEEKDAY_DATE(sAlarm->AlarmDateWeekDay));
}
else
{
assert_param(IS_RTC_ALARM_DATE_WEEKDAY_WEEKDAY(sAlarm->AlarmDateWeekDay));
}
tmpreg = (((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmTime.Hours) << 16U) | \
((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmTime.Minutes) << 8U) | \
((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmTime.Seconds)) | \
((uint32_t)(sAlarm->AlarmTime.TimeFormat) << 16U) | \
((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmDateWeekDay) << 24U) | \
((uint32_t)sAlarm->AlarmDateWeekDaySel) | \
((uint32_t)sAlarm->AlarmMask));
}
else
{
if((hrtc->Instance->CR & RTC_CR_FMT) != (uint32_t)RESET)
{
tmpreg = RTC_Bcd2ToByte(sAlarm->AlarmTime.Hours);
assert_param(IS_RTC_HOUR12(tmpreg));
assert_param(IS_RTC_HOURFORMAT12(sAlarm->AlarmTime.TimeFormat));
}
else
{
sAlarm->AlarmTime.TimeFormat = 0x00U;
assert_param(IS_RTC_HOUR24(RTC_Bcd2ToByte(sAlarm->AlarmTime.Hours)));
}
assert_param(IS_RTC_MINUTES(RTC_Bcd2ToByte(sAlarm->AlarmTime.Minutes)));
assert_param(IS_RTC_SECONDS(RTC_Bcd2ToByte(sAlarm->AlarmTime.Seconds)));
if(sAlarm->AlarmDateWeekDaySel == RTC_ALARMDATEWEEKDAYSEL_DATE)
{
tmpreg = RTC_Bcd2ToByte(sAlarm->AlarmDateWeekDay);
assert_param(IS_RTC_ALARM_DATE_WEEKDAY_DATE(tmpreg));
}
else
{
tmpreg = RTC_Bcd2ToByte(sAlarm->AlarmDateWeekDay);
assert_param(IS_RTC_ALARM_DATE_WEEKDAY_WEEKDAY(tmpreg));
}
tmpreg = (((uint32_t)(sAlarm->AlarmTime.Hours) << 16U) | \
((uint32_t)(sAlarm->AlarmTime.Minutes) << 8U) | \
((uint32_t) sAlarm->AlarmTime.Seconds) | \
((uint32_t)(sAlarm->AlarmTime.TimeFormat) << 16U) | \
((uint32_t)(sAlarm->AlarmDateWeekDay) << 24U) | \
((uint32_t)sAlarm->AlarmDateWeekDaySel) | \
((uint32_t)sAlarm->AlarmMask));
}
/* Configure the Alarm A or Alarm B Sub Second registers */
subsecondtmpreg = (uint32_t)((uint32_t)(sAlarm->AlarmTime.SubSeconds) | (uint32_t)(sAlarm->AlarmSubSecondMask));
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
/* Configure the Alarm register */
if(sAlarm->Alarm == RTC_ALARM_A)
{
/* Disable the Alarm A interrupt */
__HAL_RTC_ALARMA_DISABLE(hrtc);
/* In case of interrupt mode is used, the interrupt source must disabled */
__HAL_RTC_ALARM_DISABLE_IT(hrtc, RTC_IT_ALRA);
tickstart = HAL_GetTick();
/* Wait till RTC ALRAWF flag is set and if Time out is reached exit */
while(__HAL_RTC_ALARM_GET_FLAG(hrtc, RTC_FLAG_ALRAWF) == RESET)
{
if((HAL_GetTick()-tickstart) > RTC_TIMEOUT_VALUE)
{
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
hrtc->State = HAL_RTC_STATE_TIMEOUT;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_TIMEOUT;
}
}
hrtc->Instance->ALRMAR = (uint32_t)tmpreg;
/* Configure the Alarm A Sub Second register */
hrtc->Instance->ALRMASSR = subsecondtmpreg;
/* Configure the Alarm state: Enable Alarm */
__HAL_RTC_ALARMA_ENABLE(hrtc);
}
else
{
/* Disable the Alarm B interrupt */
__HAL_RTC_ALARMB_DISABLE(hrtc);
/* In case of interrupt mode is used, the interrupt source must disabled */
__HAL_RTC_ALARM_DISABLE_IT(hrtc, RTC_IT_ALRB);
tickstart = HAL_GetTick();
/* Wait till RTC ALRBWF flag is set and if Time out is reached exit */
while(__HAL_RTC_ALARM_GET_FLAG(hrtc, RTC_FLAG_ALRBWF) == RESET)
{
if((HAL_GetTick()-tickstart) > RTC_TIMEOUT_VALUE)
{
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
hrtc->State = HAL_RTC_STATE_TIMEOUT;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_TIMEOUT;
}
}
hrtc->Instance->ALRMBR = (uint32_t)tmpreg;
/* Configure the Alarm B Sub Second register */
hrtc->Instance->ALRMBSSR = subsecondtmpreg;
/* Configure the Alarm state: Enable Alarm */
__HAL_RTC_ALARMB_ENABLE(hrtc);
}
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
/* Change RTC state */
hrtc->State = HAL_RTC_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_OK;
}
/**
* @brief Set the specified RTC Alarm with Interrupt.
* @param hrtc: RTC handle
* @param sAlarm: Pointer to Alarm structure
* @param Format: Specifies the format of the entered parameters.
* This parameter can be one of the following values:
* @arg RTC_FORMAT_BIN: Binary data format
* @arg RTC_FORMAT_BCD: BCD data format
* @note The Alarm register can only be written when the corresponding Alarm
* is disabled (Use the HAL_RTC_DeactivateAlarm()).
* @note The HAL_RTC_SetTime() must be called before enabling the Alarm feature.
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTC_SetAlarm_IT(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Format)
{
uint32_t tickstart = 0U;
uint32_t tmpreg = 0U, subsecondtmpreg = 0U;
/* Check the parameters */
assert_param(IS_RTC_FORMAT(Format));
assert_param(IS_RTC_ALARM(sAlarm->Alarm));
assert_param(IS_RTC_ALARM_MASK(sAlarm->AlarmMask));
assert_param(IS_RTC_ALARM_DATE_WEEKDAY_SEL(sAlarm->AlarmDateWeekDaySel));
assert_param(IS_RTC_ALARM_SUB_SECOND_VALUE(sAlarm->AlarmTime.SubSeconds));
assert_param(IS_RTC_ALARM_SUB_SECOND_MASK(sAlarm->AlarmSubSecondMask));
/* Process Locked */
__HAL_LOCK(hrtc);
hrtc->State = HAL_RTC_STATE_BUSY;
if(Format == RTC_FORMAT_BIN)
{
if((hrtc->Instance->CR & RTC_CR_FMT) != (uint32_t)RESET)
{
assert_param(IS_RTC_HOUR12(sAlarm->AlarmTime.Hours));
assert_param(IS_RTC_HOURFORMAT12(sAlarm->AlarmTime.TimeFormat));
}
else
{
sAlarm->AlarmTime.TimeFormat = 0x00U;
assert_param(IS_RTC_HOUR24(sAlarm->AlarmTime.Hours));
}
assert_param(IS_RTC_MINUTES(sAlarm->AlarmTime.Minutes));
assert_param(IS_RTC_SECONDS(sAlarm->AlarmTime.Seconds));
if(sAlarm->AlarmDateWeekDaySel == RTC_ALARMDATEWEEKDAYSEL_DATE)
{
assert_param(IS_RTC_ALARM_DATE_WEEKDAY_DATE(sAlarm->AlarmDateWeekDay));
}
else
{
assert_param(IS_RTC_ALARM_DATE_WEEKDAY_WEEKDAY(sAlarm->AlarmDateWeekDay));
}
tmpreg = (((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmTime.Hours) << 16U) | \
((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmTime.Minutes) << 8U) | \
((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmTime.Seconds)) | \
((uint32_t)(sAlarm->AlarmTime.TimeFormat) << 16U) | \
((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmDateWeekDay) << 24U) | \
((uint32_t)sAlarm->AlarmDateWeekDaySel) | \
((uint32_t)sAlarm->AlarmMask));
}
else
{
if((hrtc->Instance->CR & RTC_CR_FMT) != (uint32_t)RESET)
{
tmpreg = RTC_Bcd2ToByte(sAlarm->AlarmTime.Hours);
assert_param(IS_RTC_HOUR12(tmpreg));
assert_param(IS_RTC_HOURFORMAT12(sAlarm->AlarmTime.TimeFormat));
}
else
{
sAlarm->AlarmTime.TimeFormat = 0x00U;
assert_param(IS_RTC_HOUR24(RTC_Bcd2ToByte(sAlarm->AlarmTime.Hours)));
}
assert_param(IS_RTC_MINUTES(RTC_Bcd2ToByte(sAlarm->AlarmTime.Minutes)));
assert_param(IS_RTC_SECONDS(RTC_Bcd2ToByte(sAlarm->AlarmTime.Seconds)));
if(sAlarm->AlarmDateWeekDaySel == RTC_ALARMDATEWEEKDAYSEL_DATE)
{
tmpreg = RTC_Bcd2ToByte(sAlarm->AlarmDateWeekDay);
assert_param(IS_RTC_ALARM_DATE_WEEKDAY_DATE(tmpreg));
}
else
{
tmpreg = RTC_Bcd2ToByte(sAlarm->AlarmDateWeekDay);
assert_param(IS_RTC_ALARM_DATE_WEEKDAY_WEEKDAY(tmpreg));
}
tmpreg = (((uint32_t)(sAlarm->AlarmTime.Hours) << 16U) | \
((uint32_t)(sAlarm->AlarmTime.Minutes) << 8U) | \
((uint32_t) sAlarm->AlarmTime.Seconds) | \
((uint32_t)(sAlarm->AlarmTime.TimeFormat) << 16U) | \
((uint32_t)(sAlarm->AlarmDateWeekDay) << 24U) | \
((uint32_t)sAlarm->AlarmDateWeekDaySel) | \
((uint32_t)sAlarm->AlarmMask));
}
/* Configure the Alarm A or Alarm B Sub Second registers */
subsecondtmpreg = (uint32_t)((uint32_t)(sAlarm->AlarmTime.SubSeconds) | (uint32_t)(sAlarm->AlarmSubSecondMask));
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
/* Configure the Alarm register */
if(sAlarm->Alarm == RTC_ALARM_A)
{
/* Disable the Alarm A interrupt */
__HAL_RTC_ALARMA_DISABLE(hrtc);
/* Clear flag alarm A */
__HAL_RTC_ALARM_CLEAR_FLAG(hrtc, RTC_FLAG_ALRAF);
tickstart = HAL_GetTick();
/* Wait till RTC ALRAWF flag is set and if Time out is reached exit */
while(__HAL_RTC_ALARM_GET_FLAG(hrtc, RTC_FLAG_ALRAWF) == RESET)
{
if((HAL_GetTick()-tickstart) > RTC_TIMEOUT_VALUE)
{
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
hrtc->State = HAL_RTC_STATE_TIMEOUT;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_TIMEOUT;
}
}
hrtc->Instance->ALRMAR = (uint32_t)tmpreg;
/* Configure the Alarm A Sub Second register */
hrtc->Instance->ALRMASSR = subsecondtmpreg;
/* Configure the Alarm state: Enable Alarm */
__HAL_RTC_ALARMA_ENABLE(hrtc);
/* Configure the Alarm interrupt */
__HAL_RTC_ALARM_ENABLE_IT(hrtc,RTC_IT_ALRA);
}
else
{
/* Disable the Alarm B interrupt */
__HAL_RTC_ALARMB_DISABLE(hrtc);
/* Clear flag alarm B */
__HAL_RTC_ALARM_CLEAR_FLAG(hrtc, RTC_FLAG_ALRBF);
tickstart = HAL_GetTick();
/* Wait till RTC ALRBWF flag is set and if Time out is reached exit */
while(__HAL_RTC_ALARM_GET_FLAG(hrtc, RTC_FLAG_ALRBWF) == RESET)
{
if((HAL_GetTick()-tickstart) > RTC_TIMEOUT_VALUE)
{
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
hrtc->State = HAL_RTC_STATE_TIMEOUT;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_TIMEOUT;
}
}
hrtc->Instance->ALRMBR = (uint32_t)tmpreg;
/* Configure the Alarm B Sub Second register */
hrtc->Instance->ALRMBSSR = subsecondtmpreg;
/* Configure the Alarm state: Enable Alarm */
__HAL_RTC_ALARMB_ENABLE(hrtc);
/* Configure the Alarm interrupt */
__HAL_RTC_ALARM_ENABLE_IT(hrtc, RTC_IT_ALRB);
}
/* RTC Alarm Interrupt Configuration: EXTI configuration */
__HAL_RTC_ALARM_EXTI_ENABLE_IT();
__HAL_RTC_ALARM_EXTI_ENABLE_RISING_EDGE();
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
hrtc->State = HAL_RTC_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_OK;
}
/**
* @brief Deactivate the specified RTC Alarm.
* @param hrtc: RTC handle
* @param Alarm: Specifies the Alarm.
* This parameter can be one of the following values:
* @arg RTC_ALARM_A : AlarmA
* @arg RTC_ALARM_B : AlarmB
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTC_DeactivateAlarm(RTC_HandleTypeDef *hrtc, uint32_t Alarm)
{
uint32_t tickstart = 0U;
/* Check the parameters */
assert_param(IS_RTC_ALARM(Alarm));
/* Process Locked */
__HAL_LOCK(hrtc);
hrtc->State = HAL_RTC_STATE_BUSY;
/* Disable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_DISABLE(hrtc);
if(Alarm == RTC_ALARM_A)
{
/* AlarmA */
__HAL_RTC_ALARMA_DISABLE(hrtc);
/* In case of interrupt mode is used, the interrupt source must disabled */
__HAL_RTC_ALARM_DISABLE_IT(hrtc, RTC_IT_ALRA);
tickstart = HAL_GetTick();
/* Wait till RTC ALRxWF flag is set and if Time out is reached exit */
while(__HAL_RTC_ALARM_GET_FLAG(hrtc, RTC_FLAG_ALRAWF) == RESET)
{
if((HAL_GetTick()-tickstart) > RTC_TIMEOUT_VALUE)
{
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
hrtc->State = HAL_RTC_STATE_TIMEOUT;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_TIMEOUT;
}
}
}
else
{
/* AlarmB */
__HAL_RTC_ALARMB_DISABLE(hrtc);
/* In case of interrupt mode is used, the interrupt source must disabled */
__HAL_RTC_ALARM_DISABLE_IT(hrtc,RTC_IT_ALRB);
tickstart = HAL_GetTick();
/* Wait till RTC ALRxWF flag is set and if Time out is reached exit */
while(__HAL_RTC_ALARM_GET_FLAG(hrtc, RTC_FLAG_ALRBWF) == RESET)
{
if((HAL_GetTick()-tickstart) > RTC_TIMEOUT_VALUE)
{
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
hrtc->State = HAL_RTC_STATE_TIMEOUT;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_TIMEOUT;
}
}
}
/* Enable the write protection for RTC registers */
__HAL_RTC_WRITEPROTECTION_ENABLE(hrtc);
hrtc->State = HAL_RTC_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hrtc);
return HAL_OK;
}
/**
* @brief Get the RTC Alarm value and masks.
* @param hrtc: RTC handle
* @param sAlarm: Pointer to Date structure
* @param Alarm: Specifies the Alarm.
* This parameter can be one of the following values:
* @arg RTC_ALARM_A: AlarmA
* @arg RTC_ALARM_B: AlarmB
* @param Format: Specifies the format of the entered parameters.
* This parameter can be one of the following values:
* @arg RTC_FORMAT_BIN: Binary data format
* @arg RTC_FORMAT_BCD: BCD data format
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTC_GetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Alarm, uint32_t Format)
{
uint32_t tmpreg = 0U, subsecondtmpreg = 0U;
/* Check the parameters */
assert_param(IS_RTC_FORMAT(Format));
assert_param(IS_RTC_ALARM(Alarm));
if(Alarm == RTC_ALARM_A)
{
/* AlarmA */
sAlarm->Alarm = RTC_ALARM_A;
tmpreg = (uint32_t)(hrtc->Instance->ALRMAR);
subsecondtmpreg = (uint32_t)((hrtc->Instance->ALRMASSR ) & RTC_ALRMASSR_SS);
}
else
{
sAlarm->Alarm = RTC_ALARM_B;
tmpreg = (uint32_t)(hrtc->Instance->ALRMBR);
subsecondtmpreg = (uint32_t)((hrtc->Instance->ALRMBSSR) & RTC_ALRMBSSR_SS);
}
/* Fill the structure with the read parameters */
sAlarm->AlarmTime.Hours = (uint32_t)((tmpreg & (RTC_ALRMAR_HT | RTC_ALRMAR_HU)) >> 16U);
sAlarm->AlarmTime.Minutes = (uint32_t)((tmpreg & (RTC_ALRMAR_MNT | RTC_ALRMAR_MNU)) >> 8U);
sAlarm->AlarmTime.Seconds = (uint32_t)(tmpreg & (RTC_ALRMAR_ST | RTC_ALRMAR_SU));
sAlarm->AlarmTime.TimeFormat = (uint32_t)((tmpreg & RTC_ALRMAR_PM) >> 16U);
sAlarm->AlarmTime.SubSeconds = (uint32_t) subsecondtmpreg;
sAlarm->AlarmDateWeekDay = (uint32_t)((tmpreg & (RTC_ALRMAR_DT | RTC_ALRMAR_DU)) >> 24U);
sAlarm->AlarmDateWeekDaySel = (uint32_t)(tmpreg & RTC_ALRMAR_WDSEL);
sAlarm->AlarmMask = (uint32_t)(tmpreg & RTC_ALARMMASK_ALL);
if(Format == RTC_FORMAT_BIN)
{
sAlarm->AlarmTime.Hours = RTC_Bcd2ToByte(sAlarm->AlarmTime.Hours);
sAlarm->AlarmTime.Minutes = RTC_Bcd2ToByte(sAlarm->AlarmTime.Minutes);
sAlarm->AlarmTime.Seconds = RTC_Bcd2ToByte(sAlarm->AlarmTime.Seconds);
sAlarm->AlarmDateWeekDay = RTC_Bcd2ToByte(sAlarm->AlarmDateWeekDay);
}
return HAL_OK;
}
/**
* @brief Handle Alarm interrupt request.
* @param hrtc: RTC handle
* @retval None
*/
void HAL_RTC_AlarmIRQHandler(RTC_HandleTypeDef* hrtc)
{
/* Get the AlarmA interrupt source enable status */
if(__HAL_RTC_ALARM_GET_IT_SOURCE(hrtc, RTC_IT_ALRA) != RESET)
{
/* Get the pending status of the AlarmA Interrupt */
if(__HAL_RTC_ALARM_GET_FLAG(hrtc, RTC_FLAG_ALRAF) != RESET)
{
/* AlarmA callback */
HAL_RTC_AlarmAEventCallback(hrtc);
/* Clear the AlarmA interrupt pending bit */
__HAL_RTC_ALARM_CLEAR_FLAG(hrtc,RTC_FLAG_ALRAF);
}
}
/* Get the AlarmB interrupt source enable status */
if(__HAL_RTC_ALARM_GET_IT_SOURCE(hrtc, RTC_IT_ALRB) != RESET)
{
/* Get the pending status of the AlarmB Interrupt */
if(__HAL_RTC_ALARM_GET_FLAG(hrtc, RTC_FLAG_ALRBF) != RESET)
{
/* AlarmB callback */
HAL_RTCEx_AlarmBEventCallback(hrtc);
/* Clear the AlarmB interrupt pending bit */
__HAL_RTC_ALARM_CLEAR_FLAG(hrtc,RTC_FLAG_ALRBF);
}
}
/* Clear the EXTI's line Flag for RTC Alarm */
__HAL_RTC_ALARM_EXTI_CLEAR_FLAG();
/* Change RTC state */
hrtc->State = HAL_RTC_STATE_READY;
}
/**
* @brief Alarm A callback.
* @param hrtc: RTC handle
* @retval None
*/
__weak void HAL_RTC_AlarmAEventCallback(RTC_HandleTypeDef *hrtc)
{
/* Prevent unused argument(s) compilation warning */
UNUSED(hrtc);
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_RTC_AlarmAEventCallback could be implemented in the user file
*/
}
/**
* @brief Handle AlarmA Polling request.
* @param hrtc: RTC handle
* @param Timeout: Timeout duration
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTC_PollForAlarmAEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout)
{
uint32_t tickstart = HAL_GetTick();
while(__HAL_RTC_ALARM_GET_FLAG(hrtc, RTC_FLAG_ALRAF) == RESET)
{
if(Timeout != HAL_MAX_DELAY)
{
if((Timeout == 0U) || ((HAL_GetTick()-tickstart) > Timeout))
{
hrtc->State = HAL_RTC_STATE_TIMEOUT;
return HAL_TIMEOUT;
}
}
}
/* Clear the Alarm interrupt pending bit */
__HAL_RTC_ALARM_CLEAR_FLAG(hrtc, RTC_FLAG_ALRAF);
/* Change RTC state */
hrtc->State = HAL_RTC_STATE_READY;
return HAL_OK;
}
/**
* @}
*/
/** @@addtogroup RTC_Exported_Functions_Group4 Peripheral Control functions
* @brief Peripheral Control functions
*
@verbatim
===============================================================================
##### Peripheral Control functions #####
===============================================================================
[..]
This subsection provides functions allowing to
(+) Wait for RTC Time and Date Synchronization
@endverbatim
* @{
*/
/**
* @brief Wait until the RTC Time and Date registers (RTC_TR and RTC_DR) are
* synchronized with RTC APB clock.
* @note The RTC Resynchronization mode is write protected, use the
* __HAL_RTC_WRITEPROTECTION_DISABLE() before calling this function.
* @note To read the calendar through the shadow registers after Calendar
* initialization, calendar update or after wakeup from low power modes
* the software must first clear the RSF flag.
* The software must then wait until it is set again before reading
* the calendar, which means that the calendar registers have been
* correctly copied into the RTC_TR and RTC_DR shadow registers.
* @param hrtc: RTC handle
* @retval HAL status
*/
HAL_StatusTypeDef HAL_RTC_WaitForSynchro(RTC_HandleTypeDef* hrtc)
{
uint32_t tickstart = 0U;
/* Clear RSF flag */
hrtc->Instance->ISR &= (uint32_t)RTC_RSF_MASK;
tickstart = HAL_GetTick();
/* Wait the registers to be synchronised */
while((hrtc->Instance->ISR & RTC_ISR_RSF) == (uint32_t)RESET)
{
if((HAL_GetTick()-tickstart) > RTC_TIMEOUT_VALUE)
{
return HAL_TIMEOUT;
}
}
return HAL_OK;
}
/**
* @}
*/
/** @@addtogroup RTC_Exported_Functions_Group5 Peripheral State functions
* @brief Peripheral State functions
*
@verbatim
===============================================================================
##### Peripheral State functions #####
===============================================================================
[..]
This subsection provides functions allowing to
(+) Get RTC state
@endverbatim
* @{
*/
/**
* @brief Return the RTC handle state.
* @param hrtc: RTC handle
* @retval HAL state
*/
HAL_RTCStateTypeDef HAL_RTC_GetState(RTC_HandleTypeDef* hrtc)
{
/* Return RTC handle state */
return hrtc->State;
}
/**
* @}
*/
/**
* @}
*/
/** @@addtogroup RTC_Private_Functions RTC Private Functions
* @{
*/
/**
* @brief Enter the RTC Initialization mode.
* @note The RTC Initialization mode is write protected, use the
* __HAL_RTC_WRITEPROTECTION_DISABLE() before calling this function.
* @param hrtc: RTC handle
* @retval An ErrorStatus enumeration value:
* - HAL_OK : RTC is in Init mode
* - HAL_TIMEOUT : RTC is not in Init mode and in Timeout
*/
HAL_StatusTypeDef RTC_EnterInitMode(RTC_HandleTypeDef* hrtc)
{
uint32_t tickstart = 0U;
/* Check if the Initialization mode is set */
if((hrtc->Instance->ISR & RTC_ISR_INITF) == (uint32_t)RESET)
{
/* Set the Initialization mode */
hrtc->Instance->ISR = (uint32_t)RTC_INIT_MASK;
tickstart = HAL_GetTick();
/* Wait till RTC is in INIT state and if Time out is reached exit */
while((hrtc->Instance->ISR & RTC_ISR_INITF) == (uint32_t)RESET)
{
if((HAL_GetTick()-tickstart) > RTC_TIMEOUT_VALUE)
{
return HAL_TIMEOUT;
}
}
}
return HAL_OK;
}
/**
* @brief Convert a 2 digit decimal to BCD format.
* @param Value: Byte to be converted
* @retval Converted byte
*/
uint8_t RTC_ByteToBcd2(uint8_t Value)
{
uint32_t bcdhigh = 0U;
while(Value >= 10U)
{
bcdhigh++;
Value -= 10U;
}
return ((uint8_t)(bcdhigh << 4U) | Value);
}
/**
* @brief Convert from 2 digit BCD to Binary.
* @param Value: BCD value to be converted
* @retval Converted word
*/
uint8_t RTC_Bcd2ToByte(uint8_t Value)
{
uint32_t tmp = 0U;
tmp = ((uint8_t)(Value & (uint8_t)0xF0U) >> (uint8_t)0x4U) * 10U;
return (tmp + (Value & (uint8_t)0x0FU));
}
/**
* @}
*/
#endif /* HAL_RTC_MODULE_ENABLED */
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|
/*
Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang('sourcedialog', 'bn', {
toolbar: 'উৎস',
title: 'সোর্স'
});
|
'use strict';
// ---------------------------------------------------------------------------
const Exchange = require ('./base/Exchange');
const { AccountSuspended, BadRequest, BadResponse, NetworkError, DDoSProtection, AuthenticationError, PermissionDenied, ExchangeError, InsufficientFunds, InvalidOrder, InvalidNonce, OrderNotFound, InvalidAddress, RateLimitExceeded, BadSymbol } = require ('./base/errors');
// ---------------------------------------------------------------------------
module.exports = class digifinex extends Exchange {
describe () {
return this.deepExtend (super.describe (), {
'id': 'digifinex',
'name': 'DigiFinex',
'countries': [ 'SG' ],
'version': 'v3',
'rateLimit': 900, // 300 for posts
'has': {
'cancelOrder': true,
'cancelOrders': true,
'createOrder': true,
'fetchBalance': true,
'fetchCurrencies': true,
'fetchDepositAddress': true,
'fetchDeposits': true,
'fetchLedger': true,
'fetchMarkets': true,
'fetchMyTrades': true,
'fetchOHLCV': true,
'fetchOpenOrders': true,
'fetchOrder': true,
'fetchOrderBook': true,
'fetchOrders': true,
'fetchStatus': true,
'fetchTicker': true,
'fetchTickers': true,
'fetchTime': true,
'fetchTrades': true,
'fetchWithdrawals': true,
'withdraw': true,
},
'timeframes': {
'1m': '1',
'5m': '5',
'15m': '15',
'30m': '30',
'1h': '60',
'4h': '240',
'12h': '720',
'1d': '1D',
'1w': '1W',
},
'urls': {
'logo': 'https://user-images.githubusercontent.com/51840849/87443315-01283a00-c5fe-11ea-8628-c2a0feaf07ac.jpg',
'api': 'https://openapi.digifinex.com',
'www': 'https://www.digifinex.com',
'doc': [
'https://docs.digifinex.com',
],
'fees': 'https://digifinex.zendesk.com/hc/en-us/articles/360000328422-Fee-Structure-on-DigiFinex',
'referral': 'https://www.digifinex.com/en-ww/from/DhOzBg?channelCode=ljaUPp',
},
'api': {
'public': {
'get': [
'{market}/symbols',
'kline',
'margin/currencies',
'margin/symbols',
'markets',
'order_book',
'ping',
'spot/symbols',
'time',
'trades',
'trades/symbols',
'ticker',
'currencies', // todo add fetchCurrencies
],
},
'private': {
'get': [
'{market}/financelog',
'{market}/mytrades',
'{market}/order',
'{market}/order/detail', // todo add fetchOrder
'{market}/order/current',
'{market}/order/history',
'margin/assets',
'margin/financelog',
'margin/mytrades',
'margin/order',
'margin/order/current',
'margin/order/history',
'margin/positions',
'otc/financelog',
'spot/assets',
'spot/financelog',
'spot/mytrades',
'spot/order',
'spot/order/current',
'spot/order/history',
'deposit/address', // todo add fetchDepositAddress
'deposit/history', // todo add fetchDeposits
'withdraw/history', // todo add fetchWithdrawals
],
'post': [
'{market}/order/cancel',
'{market}/order/new',
'{market}/order/batch_new',
'margin/order/cancel',
'margin/order/new',
'margin/position/close',
'spot/order/cancel',
'spot/order/new',
'transfer',
'withdraw/new', // todo add withdraw()
'withdraw/cancel',
],
},
},
'fees': {
'trading': {
'tierBased': false,
'percentage': true,
'maker': this.parseNumber ('0.002'),
'taker': this.parseNumber ('0.002'),
},
},
'exceptions': {
'exact': {
'10001': [ BadRequest, "Wrong request method, please check it's a GET ot POST request" ],
'10002': [ AuthenticationError, 'Invalid ApiKey' ],
'10003': [ AuthenticationError, "Sign doesn't match" ],
'10004': [ BadRequest, 'Illegal request parameters' ],
'10005': [ DDoSProtection, 'Request frequency exceeds the limit' ],
'10006': [ PermissionDenied, 'Unauthorized to execute this request' ],
'10007': [ PermissionDenied, 'IP address Unauthorized' ],
'10008': [ InvalidNonce, 'Timestamp for this request is invalid, timestamp must within 1 minute' ],
'10009': [ NetworkError, 'Unexist endpoint, please check endpoint URL' ],
'10011': [ AccountSuspended, 'ApiKey expired. Please go to client side to re-create an ApiKey' ],
'20001': [ PermissionDenied, 'Trade is not open for this trading pair' ],
'20002': [ PermissionDenied, 'Trade of this trading pair is suspended' ],
'20003': [ InvalidOrder, 'Invalid price or amount' ],
'20007': [ InvalidOrder, 'Price precision error' ],
'20008': [ InvalidOrder, 'Amount precision error' ],
'20009': [ InvalidOrder, 'Amount is less than the minimum requirement' ],
'20010': [ InvalidOrder, 'Cash Amount is less than the minimum requirement' ],
'20011': [ InsufficientFunds, 'Insufficient balance' ],
'20012': [ BadRequest, 'Invalid trade type, valid value: buy/sell)' ],
'20013': [ InvalidOrder, 'No order info found' ],
'20014': [ BadRequest, 'Invalid date, Valid format: 2018-07-25)' ],
'20015': [ BadRequest, 'Date exceeds the limit' ],
'20018': [ PermissionDenied, 'Your trading rights have been banned by the system' ],
'20019': [ BadSymbol, 'Wrong trading pair symbol. Correct format:"usdt_btc". Quote asset is in the front' ],
'20020': [ DDoSProtection, "You have violated the API operation trading rules and temporarily forbid trading. At present, we have certain restrictions on the user's transaction rate and withdrawal rate." ],
'50000': [ ExchangeError, 'Exception error' ],
'20021': [ BadRequest, 'Invalid currency' ],
'20022': [ BadRequest, 'The ending timestamp must be larger than the starting timestamp' ],
'20023': [ BadRequest, 'Invalid transfer type' ],
'20024': [ BadRequest, 'Invalid amount' ],
'20025': [ BadRequest, 'This currency is not transferable at the moment' ],
'20026': [ InsufficientFunds, 'Transfer amount exceed your balance' ],
'20027': [ PermissionDenied, 'Abnormal account status' ],
'20028': [ PermissionDenied, 'Blacklist for transfer' ],
'20029': [ PermissionDenied, 'Transfer amount exceed your daily limit' ],
'20030': [ BadRequest, 'You have no position on this trading pair' ],
'20032': [ PermissionDenied, 'Withdrawal limited' ],
'20033': [ BadRequest, 'Wrong Withdrawal ID' ],
'20034': [ PermissionDenied, 'Withdrawal service of this crypto has been closed' ],
'20035': [ PermissionDenied, 'Withdrawal limit' ],
'20036': [ ExchangeError, 'Withdrawal cancellation failed' ],
'20037': [ InvalidAddress, 'The withdrawal address, Tag or chain type is not included in the withdrawal management list' ],
'20038': [ InvalidAddress, 'The withdrawal address is not on the white list' ],
'20039': [ ExchangeError, "Can't be canceled in current status" ],
'20040': [ RateLimitExceeded, 'Withdraw too frequently; limitation: 3 times a minute, 100 times a day' ],
'20041': [ PermissionDenied, 'Beyond the daily withdrawal limit' ],
'20042': [ BadSymbol, 'Current trading pair does not support API trading' ],
},
'broad': {
},
},
'options': {
'defaultType': 'spot',
'types': [ 'spot', 'margin', 'otc' ],
},
'commonCurrencies': {
'BHT': 'Black House Test',
'EPS': 'Epanus',
'MBN': 'Mobilian Coin',
'TEL': 'TEL666',
},
});
}
async fetchCurrencies (params = {}) {
const response = await this.publicGetCurrencies (params);
//
// {
// "data":[
// {
// "deposit_status":1,
// "min_deposit_amount":10,
// "withdraw_fee_rate":0,
// "min_withdraw_amount":10,
// "min_withdraw_fee":5,
// "currency":"USDT",
// "withdraw_status":0,
// "chain":"OMNI"
// },
// {
// "deposit_status":1,
// "min_deposit_amount":10,
// "withdraw_fee_rate":0,
// "min_withdraw_amount":10,
// "min_withdraw_fee":3,
// "currency":"USDT",
// "withdraw_status":1,
// "chain":"ERC20"
// },
// {
// "deposit_status":0,
// "min_deposit_amount":0,
// "withdraw_fee_rate":0,
// "min_withdraw_amount":0,
// "min_withdraw_fee":0,
// "currency":"DGF13",
// "withdraw_status":0,
// "chain":""
// },
// ],
// "code":200
// }
//
const data = this.safeValue (response, 'data', []);
const result = {};
for (let i = 0; i < data.length; i++) {
const currency = data[i];
const id = this.safeString (currency, 'currency');
const code = this.safeCurrencyCode (id);
const depositStatus = this.safeValue (currency, 'deposit_status', 1);
const withdrawStatus = this.safeValue (currency, 'withdraw_status', 1);
const active = depositStatus && withdrawStatus;
const fee = this.safeNumber (currency, 'withdraw_fee_rate');
if (code in result) {
if (Array.isArray (result[code]['info'])) {
result[code]['info'].push (currency);
} else {
result[code]['info'] = [ result[code]['info'], currency ];
}
} else {
result[code] = {
'id': id,
'code': code,
'info': currency,
'type': undefined,
'name': undefined,
'active': active,
'fee': fee,
'precision': 8, // todo fix hardcoded value
'limits': {
'amount': {
'min': undefined,
'max': undefined,
},
'withdraw': {
'min': this.safeNumber (currency, 'min_withdraw_amount'),
'max': undefined,
},
},
};
}
}
return result;
}
async fetchMarkets (params = {}) {
const options = this.safeValue (this.options, 'fetchMarkets', {});
const method = this.safeString (options, 'method', 'fetch_markets_v2');
return await this[method] (params);
}
async fetchMarketsV2 (params = {}) {
const response = await this.publicGetTradesSymbols (params);
//
// {
// "symbol_list":[
// {
// "order_types":["LIMIT","MARKET"],
// "quote_asset":"USDT",
// "minimum_value":2,
// "amount_precision":4,
// "status":"TRADING",
// "minimum_amount":0.0001,
// "symbol":"BTC_USDT",
// "is_allow":1,
// "zone":"MAIN",
// "base_asset":"BTC",
// "price_precision":2
// }
// ],
// "code":0
// }
//
const markets = this.safeValue (response, 'symbol_list', []);
const result = [];
for (let i = 0; i < markets.length; i++) {
const market = markets[i];
const id = this.safeString (market, 'symbol');
const baseId = this.safeString (market, 'base_asset');
const quoteId = this.safeString (market, 'quote_asset');
const base = this.safeCurrencyCode (baseId);
const quote = this.safeCurrencyCode (quoteId);
const symbol = base + '/' + quote;
const precision = {
'amount': this.safeInteger (market, 'amount_precision'),
'price': this.safeInteger (market, 'price_precision'),
};
const limits = {
'amount': {
'min': this.safeNumber (market, 'minimum_amount'),
'max': undefined,
},
'price': {
'min': undefined,
'max': undefined,
},
'cost': {
'min': this.safeNumber (market, 'minimum_value'),
'max': undefined,
},
};
//
// The status is documented in the exchange API docs as follows:
// TRADING, HALT (delisted), BREAK (trading paused)
// https://docs.digifinex.vip/en-ww/v3/#/public/spot/symbols
// However, all spot markets actually have status === 'HALT'
// despite that they appear to be active on the exchange website.
// Apparently, we can't trust this status.
// const status = this.safeString (market, 'status');
// const active = (status === 'TRADING');
//
const isAllowed = this.safeInteger (market, 'is_allow', 1);
const active = isAllowed ? true : false;
const type = 'spot';
const spot = (type === 'spot');
const margin = (type === 'margin');
result.push ({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'baseId': baseId,
'quoteId': quoteId,
'active': active,
'type': type,
'spot': spot,
'margin': margin,
'precision': precision,
'limits': limits,
'info': market,
});
}
return result;
}
async fetchMarketsV1 (params = {}) {
const response = await this.publicGetMarkets (params);
//
// {
// "data": [
// {
// "volume_precision":4,
// "price_precision":2,
// "market":"btc_usdt",
// "min_amount":2,
// "min_volume":0.0001
// },
// ],
// "date":1564507456,
// "code":0
// }
//
const markets = this.safeValue (response, 'data', []);
const result = [];
for (let i = 0; i < markets.length; i++) {
const market = markets[i];
const id = this.safeString (market, 'market');
const [ baseId, quoteId ] = id.split ('_');
const base = this.safeCurrencyCode (baseId);
const quote = this.safeCurrencyCode (quoteId);
const symbol = base + '/' + quote;
const precision = {
'amount': this.safeInteger (market, 'volume_precision'),
'price': this.safeInteger (market, 'price_precision'),
};
const limits = {
'amount': {
'min': this.safeNumber (market, 'min_volume'),
'max': undefined,
},
'price': {
'min': undefined,
'max': undefined,
},
'cost': {
'min': this.safeNumber (market, 'min_amount'),
'max': undefined,
},
};
const active = undefined;
result.push ({
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'baseId': baseId,
'quoteId': quoteId,
'active': active,
'precision': precision,
'limits': limits,
'info': market,
});
}
return result;
}
async fetchBalance (params = {}) {
const defaultType = this.safeString (this.options, 'defaultType', 'spot');
const type = this.safeString (params, 'type', defaultType);
params = this.omit (params, 'type');
const method = 'privateGet' + this.capitalize (type) + 'Assets';
const response = await this[method] (params);
//
// {
// "code": 0,
// "list": [
// {
// "currency": "BTC",
// "free": 4723846.89208129,
// "total": 0
// }
// ]
// }
const balances = this.safeValue (response, 'list', []);
const result = { 'info': response };
for (let i = 0; i < balances.length; i++) {
const balance = balances[i];
const currencyId = this.safeString (balance, 'currency');
const code = this.safeCurrencyCode (currencyId);
const account = this.account ();
account['used'] = this.safeString (balance, 'frozen');
account['free'] = this.safeString (balance, 'free');
account['total'] = this.safeString (balance, 'total');
result[code] = account;
}
return this.safeBalance (result);
}
async fetchOrderBook (symbol, limit = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'symbol': market['id'],
};
if (limit !== undefined) {
request['limit'] = limit; // default 10, max 150
}
const response = await this.publicGetOrderBook (this.extend (request, params));
//
// {
// "bids": [
// [9605.77,0.0016],
// [9605.46,0.0003],
// [9602.04,0.0127],
// ],
// "asks": [
// [9627.22,0.025803],
// [9627.12,0.168543],
// [9626.52,0.0011529],
// ],
// "date":1564509499,
// "code":0
// }
//
const timestamp = this.safeTimestamp (response, 'date');
return this.parseOrderBook (response, symbol, timestamp);
}
async fetchTickers (symbols = undefined, params = {}) {
await this.loadMarkets ();
const response = await this.publicGetTicker (params);
//
// {
// "ticker": [{
// "vol": 40717.4461,
// "change": -1.91,
// "base_vol": 392447999.65374,
// "sell": 9592.23,
// "last": 9592.22,
// "symbol": "btc_usdt",
// "low": 9476.24,
// "buy": 9592.03,
// "high": 9793.87
// }],
// "date": 1589874294,
// "code": 0
// }
//
const result = {};
const tickers = this.safeValue (response, 'ticker', []);
const date = this.safeInteger (response, 'date');
for (let i = 0; i < tickers.length; i++) {
const rawTicker = this.extend ({
'date': date,
}, tickers[i]);
const ticker = this.parseTicker (rawTicker);
const symbol = ticker['symbol'];
result[symbol] = ticker;
}
return this.filterByArray (result, 'symbol', symbols);
}
async fetchTicker (symbol, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'symbol': market['id'],
};
const response = await this.publicGetTicker (this.extend (request, params));
//
// {
// "ticker": [{
// "vol": 40717.4461,
// "change": -1.91,
// "base_vol": 392447999.65374,
// "sell": 9592.23,
// "last": 9592.22,
// "symbol": "btc_usdt",
// "low": 9476.24,
// "buy": 9592.03,
// "high": 9793.87
// }],
// "date": 1589874294,
// "code": 0
// }
//
const date = this.safeInteger (response, 'date');
const tickers = this.safeValue (response, 'ticker', []);
const firstTicker = this.safeValue (tickers, 0, {});
const result = this.extend ({ 'date': date }, firstTicker);
return this.parseTicker (result, market);
}
parseTicker (ticker, market = undefined) {
//
// fetchTicker, fetchTickers
//
// {
// "last":0.021957,
// "symbol": "btc_usdt",
// "base_vol":2249.3521732227,
// "change":-0.6,
// "vol":102443.5111,
// "sell":0.021978,
// "low":0.021791,
// "buy":0.021946,
// "high":0.022266,
// "date"1564518452, // injected from fetchTicker/fetchTickers
// }
//
const marketId = this.safeStringUpper (ticker, 'symbol');
const symbol = this.safeSymbol (marketId, market, '_');
const timestamp = this.safeTimestamp (ticker, 'date');
const last = this.safeNumber (ticker, 'last');
const percentage = this.safeNumber (ticker, 'change');
return {
'symbol': symbol,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'high': this.safeNumber (ticker, 'high'),
'low': this.safeNumber (ticker, 'low'),
'bid': this.safeNumber (ticker, 'buy'),
'bidVolume': undefined,
'ask': this.safeNumber (ticker, 'sell'),
'askVolume': undefined,
'vwap': undefined,
'open': undefined,
'close': last,
'last': last,
'previousClose': undefined,
'change': undefined,
'percentage': percentage,
'average': undefined,
'baseVolume': this.safeNumber (ticker, 'vol'),
'quoteVolume': this.safeNumber (ticker, 'base_vol'),
'info': ticker,
};
}
parseTrade (trade, market = undefined) {
//
// fetchTrades (public)
//
// {
// "date":1564520003,
// "id":1596149203,
// "amount":0.7073,
// "type":"buy",
// "price":0.02193,
// }
//
// fetchMyTrades (private)
//
// {
// "symbol": "BTC_USDT",
// "order_id": "6707cbdcda0edfaa7f4ab509e4cbf966",
// "id": 28457,
// "price": 0.1,
// "amount": 0,
// "fee": 0.096,
// "fee_currency": "USDT",
// "timestamp": 1499865549,
// "side": "buy",
// "is_maker": true
// }
//
const id = this.safeString (trade, 'id');
const orderId = this.safeString (trade, 'order_id');
const timestamp = this.safeTimestamp2 (trade, 'date', 'timestamp');
const side = this.safeString2 (trade, 'type', 'side');
const priceString = this.safeString (trade, 'price');
const amountString = this.safeString (trade, 'amount');
const marketId = this.safeString (trade, 'symbol');
const symbol = this.safeSymbol (marketId, market, '_');
const takerOrMaker = this.safeValue (trade, 'is_maker');
const feeCostString = this.safeString (trade, 'fee');
let fee = undefined;
if (feeCostString !== undefined) {
const feeCurrencyId = this.safeString (trade, 'fee_currency');
const feeCurrencyCode = this.safeCurrencyCode (feeCurrencyId);
fee = {
'cost': feeCostString,
'currency': feeCurrencyCode,
};
}
return this.safeTrade ({
'id': id,
'info': trade,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'symbol': symbol,
'type': undefined,
'order': orderId,
'side': side,
'price': priceString,
'amount': amountString,
'cost': undefined,
'takerOrMaker': takerOrMaker,
'fee': fee,
}, market);
}
async fetchTime (params = {}) {
const response = await this.publicGetTime (params);
//
// {
// "server_time": 1589873762,
// "code": 0
// }
//
return this.safeTimestamp (response, 'server_time');
}
async fetchStatus (params = {}) {
await this.publicGetPing (params);
//
// {
// "msg": "pong",
// "code": 0
// }
//
this.status = this.extend (this.status, {
'status': 'ok',
'updated': this.milliseconds (),
});
return this.status;
}
async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'symbol': market['id'],
};
if (limit !== undefined) {
request['limit'] = limit; // default 100, max 500
}
const response = await this.publicGetTrades (this.extend (request, params));
//
// {
// "data":[
// {
// "date":1564520003,
// "id":1596149203,
// "amount":0.7073,
// "type":"buy",
// "price":0.02193,
// },
// {
// "date":1564520002,
// "id":1596149165,
// "amount":0.3232,
// "type":"sell",
// "price":0.021927,
// },
// ],
// "code": 0,
// "date": 1564520003,
// }
//
const data = this.safeValue (response, 'data', []);
return this.parseTrades (data, market, since, limit);
}
parseOHLCV (ohlcv, market = undefined) {
//
// [
// 1556712900,
// 2205.899,
// 0.029967,
// 0.02997,
// 0.029871,
// 0.029927
// ]
//
return [
this.safeTimestamp (ohlcv, 0),
this.safeNumber (ohlcv, 5), // open
this.safeNumber (ohlcv, 3), // high
this.safeNumber (ohlcv, 4), // low
this.safeNumber (ohlcv, 2), // close
this.safeNumber (ohlcv, 1), // volume
];
}
async fetchOHLCV (symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const request = {
'symbol': market['id'],
'period': this.timeframes[timeframe],
// 'start_time': 1564520003, // starting timestamp, 200 candles before end_time by default
// 'end_time': 1564520003, // ending timestamp, current timestamp by default
};
if (since !== undefined) {
const startTime = parseInt (since / 1000);
request['start_time'] = startTime;
if (limit !== undefined) {
const duration = this.parseTimeframe (timeframe);
request['end_time'] = this.sum (startTime, limit * duration);
}
} else if (limit !== undefined) {
const endTime = this.seconds ();
const duration = this.parseTimeframe (timeframe);
request['startTime'] = this.sum (endTime, -limit * duration);
}
const response = await this.publicGetKline (this.extend (request, params));
//
// {
// "code":0,
// "data":[
// [1556712900,2205.899,0.029967,0.02997,0.029871,0.029927],
// [1556713800,1912.9174,0.029992,0.030014,0.029955,0.02996],
// [1556714700,1556.4795,0.029974,0.030019,0.029969,0.02999],
// ]
// }
//
const data = this.safeValue (response, 'data', []);
return this.parseOHLCVs (data, market, timeframe, since, limit);
}
async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const defaultType = this.safeString (this.options, 'defaultType', 'spot');
const orderType = this.safeString (params, 'type', defaultType);
params = this.omit (params, 'type');
const request = {
'market': orderType,
'symbol': market['id'],
'amount': this.amountToPrecision (symbol, amount),
// 'post_only': 0, // 0 by default, if set to 1 the order will be canceled if it can be executed immediately, making sure there will be no market taking
};
let suffix = '';
if (type === 'market') {
suffix = '_market';
} else {
request['price'] = this.priceToPrecision (symbol, price);
}
request['type'] = side + suffix;
const response = await this.privatePostMarketOrderNew (this.extend (request, params));
//
// {
// "code": 0,
// "order_id": "198361cecdc65f9c8c9bb2fa68faec40"
// }
//
const result = this.parseOrder (response, market);
return this.extend (result, {
'symbol': symbol,
'side': side,
'type': type,
'amount': amount,
'price': price,
});
}
async cancelOrder (id, symbol = undefined, params = {}) {
await this.loadMarkets ();
const defaultType = this.safeString (this.options, 'defaultType', 'spot');
const orderType = this.safeString (params, 'type', defaultType);
params = this.omit (params, 'type');
const request = {
'market': orderType,
'order_id': id,
};
const response = await this.privatePostMarketOrderCancel (this.extend (request, params));
//
// {
// "code": 0,
// "success": [
// "198361cecdc65f9c8c9bb2fa68faec40",
// "3fb0d98e51c18954f10d439a9cf57de0"
// ],
// "error": [
// "78a7104e3c65cc0c5a212a53e76d0205"
// ]
// }
//
const canceledOrders = this.safeValue (response, 'success', []);
const numCanceledOrders = canceledOrders.length;
if (numCanceledOrders !== 1) {
throw new OrderNotFound (this.id + ' cancelOrder ' + id + ' not found');
}
return response;
}
async cancelOrders (ids, symbol = undefined, params = {}) {
await this.loadMarkets ();
const defaultType = this.safeString (this.options, 'defaultType', 'spot');
const orderType = this.safeString (params, 'type', defaultType);
params = this.omit (params, 'type');
const request = {
'market': orderType,
'order_id': ids.join (','),
};
const response = await this.privatePostCancelOrder (this.extend (request, params));
//
// {
// "code": 0,
// "success": [
// "198361cecdc65f9c8c9bb2fa68faec40",
// "3fb0d98e51c18954f10d439a9cf57de0"
// ],
// "error": [
// "78a7104e3c65cc0c5a212a53e76d0205"
// ]
// }
//
const canceledOrders = this.safeValue (response, 'success', []);
const numCanceledOrders = canceledOrders.length;
if (numCanceledOrders < 1) {
throw new OrderNotFound (this.id + ' cancelOrders error');
}
return response;
}
parseOrderStatus (status) {
const statuses = {
'0': 'open',
'1': 'open', // partially filled
'2': 'closed',
'3': 'canceled',
'4': 'canceled', // partially filled and canceled
};
return this.safeString (statuses, status, status);
}
parseOrder (order, market = undefined) {
//
// createOrder
//
// {
// "code": 0,
// "order_id": "198361cecdc65f9c8c9bb2fa68faec40"
// }
//
// fetchOrder, fetchOpenOrders, fetchOrders
//
// {
// "symbol": "BTC_USDT",
// "order_id": "dd3164b333a4afa9d5730bb87f6db8b3",
// "created_date": 1562303547,
// "finished_date": 0,
// "price": 0.1,
// "amount": 1,
// "cash_amount": 1,
// "executed_amount": 0,
// "avg_price": 0,
// "status": 1,
// "type": "buy",
// "kind": "margin"
// }
//
const id = this.safeString (order, 'order_id');
const timestamp = this.safeTimestamp (order, 'created_date');
const lastTradeTimestamp = this.safeTimestamp (order, 'finished_date');
let side = this.safeString (order, 'type');
let type = undefined;
if (side !== undefined) {
const parts = side.split ('_');
const numParts = parts.length;
if (numParts > 1) {
side = parts[0];
type = parts[1];
} else {
type = 'limit';
}
}
const status = this.parseOrderStatus (this.safeString (order, 'status'));
const marketId = this.safeString (order, 'symbol');
const symbol = this.safeSymbol (marketId, market, '_');
const amountString = this.safeString (order, 'amount');
const filledString = this.safeString (order, 'executed_amount');
const priceString = this.safeString (order, 'price');
const averageString = this.safeString (order, 'avg_price');
return this.safeOrder ({
'info': order,
'id': id,
'clientOrderId': undefined,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'lastTradeTimestamp': lastTradeTimestamp,
'symbol': symbol,
'type': type,
'timeInForce': undefined,
'postOnly': undefined,
'side': side,
'price': priceString,
'stopPrice': undefined,
'amount': amountString,
'filled': filledString,
'remaining': undefined,
'cost': undefined,
'average': averageString,
'status': status,
'fee': undefined,
'trades': undefined,
}, market);
}
async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
const defaultType = this.safeString (this.options, 'defaultType', 'spot');
const orderType = this.safeString (params, 'type', defaultType);
params = this.omit (params, 'type');
await this.loadMarkets ();
let market = undefined;
const request = {
'market': orderType,
};
if (symbol !== undefined) {
market = this.market (symbol);
request['symbol'] = market['id'];
}
const response = await this.privateGetMarketOrderCurrent (this.extend (request, params));
//
// {
// "code": 0,
// "data": [
// {
// "symbol": "BTC_USDT",
// "order_id": "dd3164b333a4afa9d5730bb87f6db8b3",
// "created_date": 1562303547,
// "finished_date": 0,
// "price": 0.1,
// "amount": 1,
// "cash_amount": 1,
// "executed_amount": 0,
// "avg_price": 0,
// "status": 1,
// "type": "buy",
// "kind": "margin"
// }
// ]
// }
//
const data = this.safeValue (response, 'data', []);
return this.parseOrders (data, market, since, limit);
}
async fetchOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
const defaultType = this.safeString (this.options, 'defaultType', 'spot');
const orderType = this.safeString (params, 'type', defaultType);
params = this.omit (params, 'type');
await this.loadMarkets ();
let market = undefined;
const request = {
'market': orderType,
};
if (symbol !== undefined) {
market = this.market (symbol);
request['symbol'] = market['id'];
}
if (since !== undefined) {
request['start_time'] = parseInt (since / 1000); // default 3 days from now, max 30 days
}
if (limit !== undefined) {
request['limit'] = limit; // default 10, max 100
}
const response = await this.privateGetMarketOrderHistory (this.extend (request, params));
//
// {
// "code": 0,
// "data": [
// {
// "symbol": "BTC_USDT",
// "order_id": "dd3164b333a4afa9d5730bb87f6db8b3",
// "created_date": 1562303547,
// "finished_date": 0,
// "price": 0.1,
// "amount": 1,
// "cash_amount": 1,
// "executed_amount": 0,
// "avg_price": 0,
// "status": 1,
// "type": "buy",
// "kind": "margin"
// }
// ]
// }
//
const data = this.safeValue (response, 'data', []);
return this.parseOrders (data, market, since, limit);
}
async fetchOrder (id, symbol = undefined, params = {}) {
const defaultType = this.safeString (this.options, 'defaultType', 'spot');
const orderType = this.safeString (params, 'type', defaultType);
params = this.omit (params, 'type');
await this.loadMarkets ();
let market = undefined;
if (symbol !== undefined) {
market = this.market (symbol);
}
const request = {
'market': orderType,
'order_id': id,
};
const response = await this.privateGetMarketOrder (this.extend (request, params));
//
// {
// "code": 0,
// "data": [
// {
// "symbol": "BTC_USDT",
// "order_id": "dd3164b333a4afa9d5730bb87f6db8b3",
// "created_date": 1562303547,
// "finished_date": 0,
// "price": 0.1,
// "amount": 1,
// "cash_amount": 1,
// "executed_amount": 0,
// "avg_price": 0,
// "status": 1,
// "type": "buy",
// "kind": "margin"
// }
// ]
// }
//
const data = this.safeValue (response, 'data', []);
const order = this.safeValue (data, 0);
if (order === undefined) {
throw new OrderNotFound (this.id + ' fetchOrder() order ' + id + ' not found');
}
return this.parseOrder (order, market);
}
async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) {
const defaultType = this.safeString (this.options, 'defaultType', 'spot');
const orderType = this.safeString (params, 'type', defaultType);
params = this.omit (params, 'type');
await this.loadMarkets ();
let market = undefined;
const request = {
'market': orderType,
};
if (symbol !== undefined) {
market = this.market (symbol);
request['symbol'] = market['id'];
}
if (since !== undefined) {
request['start_time'] = parseInt (since / 1000); // default 3 days from now, max 30 days
}
if (limit !== undefined) {
request['limit'] = limit; // default 10, max 100
}
const response = await this.privateGetMarketMytrades (this.extend (request, params));
//
// {
// "list":[
// {
// "timestamp":1639506068,
// "is_maker":false,
// "id":"8975951332",
// "amount":31.83,
// "side":"sell_market",
// "symbol":"DOGE_USDT",
// "fee_currency":"USDT",
// "fee":0.01163774826
// ,"order_id":"32b169792f4a7a19e5907dc29fc123d4",
// "price":0.182811
// }
// ],
// "code": 0
// }
//
const data = this.safeValue (response, 'list', []);
return this.parseTrades (data, market, since, limit);
}
parseLedgerEntryType (type) {
const types = {};
return this.safeString (types, type, type);
}
parseLedgerEntry (item, currency = undefined) {
//
// {
// "currency_mark": "BTC",
// "type": 100234,
// "num": 28457,
// "balance": 0.1,
// "time": 1546272000
// }
//
const id = this.safeString (item, 'num');
const account = undefined;
const type = this.parseLedgerEntryType (this.safeString (item, 'type'));
const code = this.safeCurrencyCode (this.safeString (item, 'currency_mark'), currency);
const timestamp = this.safeTimestamp (item, 'time');
const before = undefined;
const after = this.safeNumber (item, 'balance');
const status = 'ok';
return {
'info': item,
'id': id,
'direction': undefined,
'account': account,
'referenceId': undefined,
'referenceAccount': undefined,
'type': type,
'currency': code,
'amount': undefined,
'before': before,
'after': after,
'status': status,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'fee': undefined,
};
}
async fetchLedger (code = undefined, since = undefined, limit = undefined, params = {}) {
const defaultType = this.safeString (this.options, 'defaultType', 'spot');
const orderType = this.safeString (params, 'type', defaultType);
params = this.omit (params, 'type');
await this.loadMarkets ();
const request = {
'market': orderType,
};
let currency = undefined;
if (code !== undefined) {
currency = this.currency (code);
request['currency_mark'] = currency['id'];
}
if (since !== undefined) {
request['start_time'] = parseInt (since / 1000);
}
if (limit !== undefined) {
request['limit'] = limit; // default 100, max 1000
}
const response = await this.privateGetMarketFinancelog (this.extend (request, params));
//
// {
// "code": 0,
// "data": {
// "total": 521,
// "finance": [
// {
// "currency_mark": "BTC",
// "type": 100234,
// "num": 28457,
// "balance": 0.1,
// "time": 1546272000
// }
// ]
// }
// }
//
const data = this.safeValue (response, 'data', {});
const items = this.safeValue (data, 'finance', []);
return this.parseLedger (items, currency, since, limit);
}
parseDepositAddress (depositAddress, currency = undefined) {
//
// {
// "addressTag":"",
// "address":"0xf1104d9f8624f89775a3e9d480fc0e75a8ef4373",
// "currency":"USDT",
// "chain":"ERC20"
// }
//
const address = this.safeString (depositAddress, 'address');
const tag = this.safeString (depositAddress, 'addressTag');
const currencyId = this.safeStringUpper (depositAddress, 'currency');
const code = this.safeCurrencyCode (currencyId);
return {
'info': depositAddress,
'currency': code,
'address': address,
'tag': tag,
'network': undefined,
};
}
async fetchDepositAddress (code, params = {}) {
await this.loadMarkets ();
const currency = this.currency (code);
const request = {
'currency': currency['id'],
};
const response = await this.privateGetDepositAddress (this.extend (request, params));
//
// {
// "data":[
// {
// "addressTag":"",
// "address":"0xf1104d9f8624f89775a3e9d480fc0e75a8ef4373",
// "currency":"USDT",
// "chain":"ERC20"
// }
// ],
// "code":200
// }
//
const data = this.safeValue (response, 'data', []);
const addresses = this.parseDepositAddresses (data);
const address = this.safeValue (addresses, code);
if (address === undefined) {
throw new InvalidAddress (this.id + ' fetchDepositAddress did not return an address for ' + code + ' - create the deposit address in the user settings on the exchange website first.');
}
return address;
}
async fetchTransactionsByType (type, code = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
let currency = undefined;
const request = {
// 'currency': currency['id'],
// 'from': 'fromId', // When direct is' prev ', from is 1, returning from old to new ascending, when direct is' next ', from is the ID of the most recent record, returned from the old descending order
// 'size': 100, // default 100, max 500
// 'direct': 'prev', // "prev" ascending, "next" descending
};
if (code !== undefined) {
currency = this.currency (code);
request['currency'] = currency['id'];
}
if (limit !== undefined) {
request['size'] = Math.min (500, limit);
}
const method = (type === 'deposit') ? 'privateGetDepositHistory' : 'privateGetWithdrawHistory';
const response = await this[method] (this.extend (request, params));
//
// {
// "code": 200,
// "data": [
// {
// "id": 1171,
// "currency": "xrp",
// "hash": "ed03094b84eafbe4bc16e7ef766ee959885ee5bcb265872baaa9c64e1cf86c2b",
// "chain": "",
// "amount": 7.457467,
// "address": "rae93V8d2mdoUQHwBDBdM4NHCMehRJAsbm",
// "memo": "100040",
// "fee": 0,
// "state": "safe",
// "created_date": "2020-04-20 11:23:00",
// "finished_date": "2020-04-20 13:23:00"
// },
// ]
// }
//
const data = this.safeValue (response, 'data', []);
return this.parseTransactions (data, currency, since, limit, { 'type': type });
}
async fetchDeposits (code = undefined, since = undefined, limit = undefined, params = {}) {
return await this.fetchTransactionsByType ('deposit', code, since, limit, params);
}
async fetchWithdrawals (code = undefined, since = undefined, limit = undefined, params = {}) {
return await this.fetchTransactionsByType ('withdrawal', code, since, limit, params);
}
parseTransactionStatus (status) {
const statuses = {
'0': 'pending', // Email Sent
'1': 'canceled', // Cancelled (different from 1 = ok in deposits)
'2': 'pending', // Awaiting Approval
'3': 'failed', // Rejected
'4': 'pending', // Processing
'5': 'failed', // Failure
'6': 'ok', // Completed
};
return this.safeString (statuses, status, status);
}
parseTransaction (transaction, currency = undefined) {
//
// withdraw
//
// {
// "code": 200,
// "withdraw_id": 700
// }
//
// fetchDeposits, fetchWithdrawals
//
// {
// "id": 1171,
// "currency": "xrp",
// "hash": "ed03094b84eafbe4bc16e7ef766ee959885ee5bcb265872baaa9c64e1cf86c2b",
// "chain": "",
// "amount": 7.457467,
// "address": "rae93V8d2mdoUQHwBDBdM4NHCMehRJAsbm",
// "memo": "100040",
// "fee": 0,
// "state": "safe",
// "created_date": "2020-04-20 11:23:00",
// "finished_date": "2020-04-20 13:23:00"
// }
//
const id = this.safeString2 (transaction, 'id', 'withdraw_id');
const address = this.safeString (transaction, 'address');
let tag = this.safeString (transaction, 'memo'); // set but unused
if (tag !== undefined) {
if (tag.length < 1) {
tag = undefined;
}
}
const txid = this.safeString (transaction, 'hash');
const currencyId = this.safeStringUpper (transaction, 'currency');
const code = this.safeCurrencyCode (currencyId, currency);
const timestamp = this.parse8601 (this.safeString (transaction, 'created_date'));
const updated = this.parse8601 (this.safeString (transaction, 'finished_date'));
const status = this.parseTransactionStatus (this.safeString (transaction, 'state'));
const amount = this.safeNumber (transaction, 'amount');
const feeCost = this.safeNumber (transaction, 'fee');
let fee = undefined;
if (feeCost !== undefined) {
fee = { 'currency': code, 'cost': feeCost };
}
return {
'info': transaction,
'id': id,
'txid': txid,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'address': address,
'addressTo': address,
'addressFrom': undefined,
'tag': tag,
'tagTo': tag,
'tagFrom': undefined,
'type': undefined,
'amount': amount,
'currency': code,
'status': status,
'updated': updated,
'fee': fee,
};
}
async withdraw (code, amount, address, tag = undefined, params = {}) {
[ tag, params ] = this.handleWithdrawTagAndParams (tag, params);
this.checkAddress (address);
await this.loadMarkets ();
const currency = this.currency (code);
const request = {
// 'chain': 'ERC20', 'OMNI', 'TRC20', // required for USDT
'address': address,
'amount': parseFloat (amount),
'currency': currency['id'],
};
if (tag !== undefined) {
request['memo'] = tag;
}
const response = await this.privatePostWithdrawNew (this.extend (request, params));
//
// {
// "code": 200,
// "withdraw_id": 700
// }
//
return this.parseTransaction (response, currency);
}
sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
const version = this.version;
let url = this.urls['api'] + '/' + version + '/' + this.implodeParams (path, params);
const query = this.omit (params, this.extractParams (path));
const urlencoded = this.urlencode (this.keysort (query));
if (api === 'private') {
const nonce = this.nonce ().toString ();
const auth = urlencoded;
// the signature is not time-limited :\
const signature = this.hmac (this.encode (auth), this.encode (this.secret));
if (method === 'GET') {
if (urlencoded) {
url += '?' + urlencoded;
}
} else if (method === 'POST') {
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
};
if (urlencoded) {
body = urlencoded;
}
}
headers = {
'ACCESS-KEY': this.apiKey,
'ACCESS-SIGN': signature,
'ACCESS-TIMESTAMP': nonce,
};
} else {
if (urlencoded) {
url += '?' + urlencoded;
}
}
return { 'url': url, 'method': method, 'body': body, 'headers': headers };
}
handleErrors (statusCode, statusText, url, method, responseHeaders, responseBody, response, requestHeaders, requestBody) {
if (!response) {
return; // fall back to default error handler
}
const code = this.safeString (response, 'code');
if ((code === '0') || (code === '200')) {
return; // no error
}
const feedback = this.id + ' ' + responseBody;
if (code === undefined) {
throw new BadResponse (feedback);
}
const unknownError = [ ExchangeError, feedback ];
const [ ExceptionClass, message ] = this.safeValue (this.exceptions['exact'], code, unknownError);
throw new ExceptionClass (message);
}
};
|
import torch
import torch.distributed as dist
import torch.nn as nn
from mmcv.cnn import ConvModule, Scale, bias_init_with_prob, normal_init
from mmcv.runner import force_fp32
from mmdet.core import (anchor_inside_flags, build_assigner, build_sampler,
images_to_levels, multi_apply, multiclass_nms, unmap)
from ..builder import HEADS, build_loss
from .anchor_head import AnchorHead
EPS = 1e-12
def reduce_mean(tensor):
if not (dist.is_available() and dist.is_initialized()):
return tensor
tensor = tensor.clone()
dist.all_reduce(tensor.div_(dist.get_world_size()), op=dist.ReduceOp.SUM)
return tensor
@HEADS.register_module()
class ATSSHead(AnchorHead):
"""Bridging the Gap Between Anchor-based and Anchor-free Detection via
Adaptive Training Sample Selection.
ATSS head structure is similar with FCOS, however ATSS use anchor boxes
and assign label by Adaptive Training Sample Selection instead max-iou.
https://arxiv.org/abs/1912.02424
"""
def __init__(self,
num_classes,
in_channels,
stacked_convs=4,
conv_cfg=None,
norm_cfg=dict(type='GN', num_groups=32, requires_grad=True),
loss_centerness=dict(
type='CrossEntropyLoss',
use_sigmoid=True,
loss_weight=1.0),
**kwargs):
self.stacked_convs = stacked_convs
self.conv_cfg = conv_cfg
self.norm_cfg = norm_cfg
super(ATSSHead, self).__init__(num_classes, in_channels, **kwargs)
self.sampling = False
if self.train_cfg:
self.assigner = build_assigner(self.train_cfg.assigner)
# SSD sampling=False so use PseudoSampler
sampler_cfg = dict(type='PseudoSampler')
self.sampler = build_sampler(sampler_cfg, context=self)
self.loss_centerness = build_loss(loss_centerness)
def _init_layers(self):
"""Initialize layers of the head."""
self.relu = nn.ReLU(inplace=True)
self.cls_convs = nn.ModuleList()
self.reg_convs = nn.ModuleList()
for i in range(self.stacked_convs):
chn = self.in_channels if i == 0 else self.feat_channels
self.cls_convs.append(
ConvModule(
chn,
self.feat_channels,
3,
stride=1,
padding=1,
conv_cfg=self.conv_cfg,
norm_cfg=self.norm_cfg))
self.reg_convs.append(
ConvModule(
chn,
self.feat_channels,
3,
stride=1,
padding=1,
conv_cfg=self.conv_cfg,
norm_cfg=self.norm_cfg))
self.atss_cls = nn.Conv2d(
self.feat_channels,
self.num_anchors * self.cls_out_channels,
3,
padding=1)
self.atss_reg = nn.Conv2d(
self.feat_channels, self.num_anchors * 4, 3, padding=1)
self.atss_centerness = nn.Conv2d(
self.feat_channels, self.num_anchors * 1, 3, padding=1)
self.scales = nn.ModuleList(
[Scale(1.0) for _ in self.anchor_generator.strides])
def init_weights(self):
"""Initialize weights of the head."""
for m in self.cls_convs:
normal_init(m.conv, std=0.01)
for m in self.reg_convs:
normal_init(m.conv, std=0.01)
bias_cls = bias_init_with_prob(0.01)
normal_init(self.atss_cls, std=0.01, bias=bias_cls)
normal_init(self.atss_reg, std=0.01)
normal_init(self.atss_centerness, std=0.01)
def forward(self, feats):
"""Forward features from the upstream network.
Args:
feats (tuple[Tensor]): Features from the upstream network, each is
a 4D-tensor.
Returns:
tuple: Usually a tuple of classification scores and bbox prediction
cls_scores (list[Tensor]): Classification scores for all scale
levels, each is a 4D-tensor, the channels number is
num_anchors * num_classes.
bbox_preds (list[Tensor]): Box energies / deltas for all scale
levels, each is a 4D-tensor, the channels number is
num_anchors * 4.
"""
return multi_apply(self.forward_single, feats, self.scales)
def forward_single(self, x, scale):
"""Forward feature of a single scale level.
Args:
x (Tensor): Features of a single scale level.
scale (:obj: `mmcv.cnn.Scale`): Learnable scale module to resize
the bbox prediction.
Returns:
tuple:
cls_score (Tensor): Cls scores for a single scale level
the channels number is num_anchors * num_classes.
bbox_pred (Tensor): Box energies / deltas for a single scale
level, the channels number is num_anchors * 4.
centerness (Tensor): Centerness for a single scale level, the
channel number is (N, num_anchors * 1, H, W).
"""
cls_feat = x
reg_feat = x
# print("x")
# print(x.shape)
for cls_conv in self.cls_convs:
cls_feat = cls_conv(cls_feat)
for reg_conv in self.reg_convs:
reg_feat = reg_conv(reg_feat)
# print("cls_feat")
# print(cls_feat.shape)
cls_score = self.atss_cls(cls_feat)
# print("cls_score")
# print(cls_score.shape)
# we just follow atss, not apply exp-kaggle in bbox_pred
bbox_pred = scale(self.atss_reg(reg_feat)).float()
centerness = self.atss_centerness(reg_feat)
return cls_score, bbox_pred, centerness
def loss_single(self, anchors, cls_score, bbox_pred, centerness, labels,
label_weights, bbox_targets, num_total_samples):
"""Compute loss of a single scale level.
Args:
cls_score (Tensor): Box scores for each scale level
Has shape (N, num_anchors * num_classes, H, W).
bbox_pred (Tensor): Box energies / deltas for each scale
level with shape (N, num_anchors * 4, H, W).
anchors (Tensor): Box reference for each scale level with shape
(N, num_total_anchors, 4).
labels (Tensor): Labels of each anchors with shape
(N, num_total_anchors).
label_weights (Tensor): Label weights of each anchor with shape
(N, num_total_anchors)
bbox_targets (Tensor): BBox regression targets of each anchor wight
shape (N, num_total_anchors, 4).
num_total_samples (int): Number os positive samples that is
reduced over all GPUs.
Returns:
dict[str, Tensor]: A dictionary of loss components.
"""
anchors = anchors.reshape(-1, 4)
cls_score = cls_score.permute(0, 2, 3, 1).reshape(
-1, self.cls_out_channels).contiguous()
bbox_pred = bbox_pred.permute(0, 2, 3, 1).reshape(-1, 4)
centerness = centerness.permute(0, 2, 3, 1).reshape(-1)
bbox_targets = bbox_targets.reshape(-1, 4)
labels = labels.reshape(-1)
label_weights = label_weights.reshape(-1)
# classification loss
loss_cls = self.loss_cls(
cls_score, labels, label_weights, avg_factor=num_total_samples)
# FG cat_id: [0, num_classes -1], BG cat_id: num_classes
bg_class_ind = self.num_classes
pos_inds = ((labels >= 0)
& (labels < bg_class_ind)).nonzero().squeeze(1)
if len(pos_inds) > 0:
pos_bbox_targets = bbox_targets[pos_inds]
pos_bbox_pred = bbox_pred[pos_inds]
pos_anchors = anchors[pos_inds]
pos_centerness = centerness[pos_inds]
centerness_targets = self.centerness_target(
pos_anchors, pos_bbox_targets)
pos_decode_bbox_pred = self.bbox_coder.decode(
pos_anchors, pos_bbox_pred)
pos_decode_bbox_targets = self.bbox_coder.decode(
pos_anchors, pos_bbox_targets)
# regression loss
loss_bbox = self.loss_bbox(
pos_decode_bbox_pred,
pos_decode_bbox_targets,
weight=centerness_targets,
avg_factor=1.0)
# centerness loss
loss_centerness = self.loss_centerness(
pos_centerness,
centerness_targets,
avg_factor=num_total_samples)
else:
loss_bbox = bbox_pred.sum() * 0
loss_centerness = centerness.sum() * 0
centerness_targets = bbox_targets.new_tensor(0.)
return loss_cls, loss_bbox, loss_centerness, centerness_targets.sum()
@force_fp32(apply_to=('cls_scores', 'bbox_preds', 'centernesses'))
def loss(self,
cls_scores,
bbox_preds,
centernesses,
gt_bboxes,
gt_labels,
img_metas,
gt_bboxes_ignore=None):
"""Compute losses of the head.
Args:
cls_scores (list[Tensor]): Box scores for each scale level
Has shape (N, num_anchors * num_classes, H, W)
bbox_preds (list[Tensor]): Box energies / deltas for each scale
level with shape (N, num_anchors * 4, H, W)
centernesses (list[Tensor]): Centerness for each scale
level with shape (N, num_anchors * 1, H, W)
gt_bboxes (list[Tensor]): Ground truth bboxes for each image with
shape (num_gts, 4) in [tl_x, tl_y, br_x, br_y] format.
gt_labels (list[Tensor]): class indices corresponding to each box
img_metas (list[dict]): Meta information of each image, e.g.,
image size, scaling factor, etc.
gt_bboxes_ignore (list[Tensor] | None): specify which bounding
boxes can be ignored when computing the loss.
Returns:
dict[str, Tensor]: A dictionary of loss components.
"""
featmap_sizes = [featmap.size()[-2:] for featmap in cls_scores]
assert len(featmap_sizes) == self.anchor_generator.num_levels
device = cls_scores[0].device
anchor_list, valid_flag_list = self.get_anchors(
featmap_sizes, img_metas, device=device)
label_channels = self.cls_out_channels if self.use_sigmoid_cls else 1
cls_reg_targets = self.get_targets(
anchor_list,
valid_flag_list,
gt_bboxes,
img_metas,
gt_bboxes_ignore_list=gt_bboxes_ignore,
gt_labels_list=gt_labels,
label_channels=label_channels)
if cls_reg_targets is None:
return None
(anchor_list, labels_list, label_weights_list, bbox_targets_list,
bbox_weights_list, num_total_pos, num_total_neg) = cls_reg_targets
num_total_samples = reduce_mean(
torch.tensor(num_total_pos).cuda()).item()
num_total_samples = max(num_total_samples, 1.0)
losses_cls, losses_bbox, loss_centerness,\
bbox_avg_factor = multi_apply(
self.loss_single,
anchor_list,
cls_scores,
bbox_preds,
centernesses,
labels_list,
label_weights_list,
bbox_targets_list,
num_total_samples=num_total_samples)
bbox_avg_factor = sum(bbox_avg_factor)
bbox_avg_factor = reduce_mean(bbox_avg_factor).item()
if bbox_avg_factor < EPS:
bbox_avg_factor = 1
losses_bbox = list(map(lambda x: x / bbox_avg_factor, losses_bbox))
return dict(
loss_cls=losses_cls,
loss_bbox=losses_bbox,
loss_centerness=loss_centerness)
def centerness_target(self, anchors, bbox_targets):
# only calculate pos centerness targets, otherwise there may be nan
gts = self.bbox_coder.decode(anchors, bbox_targets)
anchors_cx = (anchors[:, 2] + anchors[:, 0]) / 2
anchors_cy = (anchors[:, 3] + anchors[:, 1]) / 2
l_ = anchors_cx - gts[:, 0]
t_ = anchors_cy - gts[:, 1]
r_ = gts[:, 2] - anchors_cx
b_ = gts[:, 3] - anchors_cy
left_right = torch.stack([l_, r_], dim=1)
top_bottom = torch.stack([t_, b_], dim=1)
centerness = torch.sqrt(
(left_right.min(dim=-1)[0] / left_right.max(dim=-1)[0]) *
(top_bottom.min(dim=-1)[0] / top_bottom.max(dim=-1)[0]))
assert not torch.isnan(centerness).any()
return centerness
@force_fp32(apply_to=('cls_scores', 'bbox_preds', 'centernesses'))
def get_bboxes(self,
cls_scores,
bbox_preds,
centernesses,
img_metas,
cfg=None,
rescale=False,
with_nms=True):
"""Transform network output for a batch into bbox predictions.
Args:
cls_scores (list[Tensor]): Box scores for each scale level
with shape (N, num_anchors * num_classes, H, W).
bbox_preds (list[Tensor]): Box energies / deltas for each scale
level with shape (N, num_anchors * 4, H, W).
centernesses (list[Tensor]): Centerness for each scale level with
shape (N, num_anchors * 1, H, W).
img_metas (list[dict]): Meta information of each image, e.g.,
image size, scaling factor, etc.
cfg (mmcv.Config | None): Test / postprocessing configuration,
if None, test_cfg would be used. Default: None.
rescale (bool): If True, return boxes in original image space.
Default: False.
with_nms (bool): If True, do nms before return boxes.
Default: True.
Returns:
list[tuple[Tensor, Tensor]]: Each item in result_list is 2-tuple.
The first item is an (n, 5) tensor, where the first 4 columns
are bounding box positions (tl_x, tl_y, br_x, br_y) and the
5-th column is a score between 0 and 1. The second item is a
(n,) tensor where each item is the predicted class label of the
corresponding box.
"""
cfg = self.test_cfg if cfg is None else cfg
assert len(cls_scores) == len(bbox_preds)
num_levels = len(cls_scores)
device = cls_scores[0].device
featmap_sizes = [cls_scores[i].shape[-2:] for i in range(num_levels)]
mlvl_anchors = self.anchor_generator.grid_anchors(
featmap_sizes, device=device)
result_list = []
for img_id in range(len(img_metas)):
cls_score_list = [
cls_scores[i][img_id].detach() for i in range(num_levels)
]
bbox_pred_list = [
bbox_preds[i][img_id].detach() for i in range(num_levels)
]
centerness_pred_list = [
centernesses[i][img_id].detach() for i in range(num_levels)
]
img_shape = img_metas[img_id]['img_shape']
scale_factor = img_metas[img_id]['scale_factor']
proposals = self._get_bboxes_single(cls_score_list, bbox_pred_list,
centerness_pred_list,
mlvl_anchors, img_shape,
scale_factor, cfg, rescale,
with_nms)
result_list.append(proposals)
return result_list
def _get_bboxes_single(self,
cls_scores,
bbox_preds,
centernesses,
mlvl_anchors,
img_shape,
scale_factor,
cfg,
rescale=False,
with_nms=True):
"""Transform outputs for a single batch item into labeled boxes.
Args:
cls_scores (list[Tensor]): Box scores for a single scale level
with shape (num_anchors * num_classes, H, W).
bbox_preds (list[Tensor]): Box energies / deltas for a single
scale level with shape (num_anchors * 4, H, W).
centernesses (list[Tensor]): Centerness for a single scale level
with shape (num_anchors * 1, H, W).
mlvl_anchors (list[Tensor]): Box reference for a single scale level
with shape (num_total_anchors, 4).
img_shape (tuple[int]): Shape of the input image,
(height, width, 3).
scale_factor (ndarray): Scale factor of the image arrange as
(w_scale, h_scale, w_scale, h_scale).
cfg (mmcv.Config | None): Test / postprocessing configuration,
if None, test_cfg would be used.
rescale (bool): If True, return boxes in original image space.
Default: False.
with_nms (bool): If True, do nms before return boxes.
Default: True.
Returns:
tuple(Tensor):
det_bboxes (Tensor): BBox predictions in shape (n, 5), where
the first 4 columns are bounding box positions
(tl_x, tl_y, br_x, br_y) and the 5-th column is a score
between 0 and 1.
det_labels (Tensor): A (n,) tensor where each item is the
predicted class label of the corresponding box.
"""
assert len(cls_scores) == len(bbox_preds) == len(mlvl_anchors)
mlvl_bboxes = []
mlvl_scores = []
mlvl_centerness = []
for cls_score, bbox_pred, centerness, anchors in zip(
cls_scores, bbox_preds, centernesses, mlvl_anchors):
assert cls_score.size()[-2:] == bbox_pred.size()[-2:]
scores = cls_score.permute(1, 2, 0).reshape(
-1, self.cls_out_channels).sigmoid()
bbox_pred = bbox_pred.permute(1, 2, 0).reshape(-1, 4)
centerness = centerness.permute(1, 2, 0).reshape(-1).sigmoid()
nms_pre = cfg.get('nms_pre', -1)
if nms_pre > 0 and scores.shape[0] > nms_pre:
max_scores, _ = (scores * centerness[:, None]).max(dim=1)
_, topk_inds = max_scores.topk(nms_pre)
anchors = anchors[topk_inds, :]
bbox_pred = bbox_pred[topk_inds, :]
scores = scores[topk_inds, :]
centerness = centerness[topk_inds]
bboxes = self.bbox_coder.decode(
anchors, bbox_pred, max_shape=img_shape)
mlvl_bboxes.append(bboxes)
mlvl_scores.append(scores)
mlvl_centerness.append(centerness)
mlvl_bboxes = torch.cat(mlvl_bboxes)
if rescale:
mlvl_bboxes /= mlvl_bboxes.new_tensor(scale_factor)
mlvl_scores = torch.cat(mlvl_scores)
# Add a dummy background class to the backend when using sigmoid
# remind that we set FG labels to [0, num_class-1] since mmdet v2.0
# BG cat_id: num_class
padding = mlvl_scores.new_zeros(mlvl_scores.shape[0], 1)
mlvl_scores = torch.cat([mlvl_scores, padding], dim=1)
mlvl_centerness = torch.cat(mlvl_centerness)
if with_nms:
det_bboxes, det_labels = multiclass_nms(
mlvl_bboxes,
mlvl_scores,
cfg.score_thr,
cfg.nms,
cfg.max_per_img,
score_factors=mlvl_centerness)
return det_bboxes, det_labels
else:
return mlvl_bboxes, mlvl_scores, mlvl_centerness
def get_targets(self,
anchor_list,
valid_flag_list,
gt_bboxes_list,
img_metas,
gt_bboxes_ignore_list=None,
gt_labels_list=None,
label_channels=1,
unmap_outputs=True):
"""Get targets for ATSS head.
This method is almost the same as `AnchorHead.get_targets()`. Besides
returning the targets as the parent method does, it also returns the
anchors as the first element of the returned tuple.
"""
num_imgs = len(img_metas)
assert len(anchor_list) == len(valid_flag_list) == num_imgs
# anchor number of multi levels
num_level_anchors = [anchors.size(0) for anchors in anchor_list[0]]
num_level_anchors_list = [num_level_anchors] * num_imgs
# concat all level anchors and flags to a single tensor
for i in range(num_imgs):
assert len(anchor_list[i]) == len(valid_flag_list[i])
anchor_list[i] = torch.cat(anchor_list[i])
valid_flag_list[i] = torch.cat(valid_flag_list[i])
# compute targets for each image
if gt_bboxes_ignore_list is None:
gt_bboxes_ignore_list = [None for _ in range(num_imgs)]
if gt_labels_list is None:
gt_labels_list = [None for _ in range(num_imgs)]
(all_anchors, all_labels, all_label_weights, all_bbox_targets,
all_bbox_weights, pos_inds_list, neg_inds_list) = multi_apply(
self._get_target_single,
anchor_list,
valid_flag_list,
num_level_anchors_list,
gt_bboxes_list,
gt_bboxes_ignore_list,
gt_labels_list,
img_metas,
label_channels=label_channels,
unmap_outputs=unmap_outputs)
# no valid anchors
if any([labels is None for labels in all_labels]):
return None
# sampled anchors of all images
num_total_pos = sum([max(inds.numel(), 1) for inds in pos_inds_list])
num_total_neg = sum([max(inds.numel(), 1) for inds in neg_inds_list])
# split targets to a list w.r.t. multiple levels
anchors_list = images_to_levels(all_anchors, num_level_anchors)
labels_list = images_to_levels(all_labels, num_level_anchors)
label_weights_list = images_to_levels(all_label_weights,
num_level_anchors)
bbox_targets_list = images_to_levels(all_bbox_targets,
num_level_anchors)
bbox_weights_list = images_to_levels(all_bbox_weights,
num_level_anchors)
return (anchors_list, labels_list, label_weights_list,
bbox_targets_list, bbox_weights_list, num_total_pos,
num_total_neg)
def _get_target_single(self,
flat_anchors,
valid_flags,
num_level_anchors,
gt_bboxes,
gt_bboxes_ignore,
gt_labels,
img_meta,
label_channels=1,
unmap_outputs=True):
"""Compute regression, classification targets for anchors in a single
image.
Args:
flat_anchors (Tensor): Multi-level anchors of the image, which are
concatenated into a single tensor of shape (num_anchors ,4)
valid_flags (Tensor): Multi level valid flags of the image,
which are concatenated into a single tensor of
shape (num_anchors,).
num_level_anchors Tensor): Number of anchors of each scale level.
gt_bboxes (Tensor): Ground truth bboxes of the image,
shape (num_gts, 4).
gt_bboxes_ignore (Tensor): Ground truth bboxes to be
ignored, shape (num_ignored_gts, 4).
gt_labels (Tensor): Ground truth labels of each box,
shape (num_gts,).
img_meta (dict): Meta info of the image.
label_channels (int): Channel of label.
unmap_outputs (bool): Whether to map outputs back to the original
set of anchors.
Returns:
tuple: N is the number of total anchors in the image.
labels (Tensor): Labels of all anchors in the image with shape
(N,).
label_weights (Tensor): Label weights of all anchor in the
image with shape (N,).
bbox_targets (Tensor): BBox targets of all anchors in the
image with shape (N, 4).
bbox_weights (Tensor): BBox weights of all anchors in the
image with shape (N, 4)
pos_inds (Tensor): Indices of postive anchor with shape
(num_pos,).
neg_inds (Tensor): Indices of negative anchor with shape
(num_neg,).
"""
inside_flags = anchor_inside_flags(flat_anchors, valid_flags,
img_meta['img_shape'][:2],
self.train_cfg.allowed_border)
if not inside_flags.any():
return (None, ) * 7
# assign gt and sample anchors
anchors = flat_anchors[inside_flags, :]
num_level_anchors_inside = self.get_num_level_anchors_inside(
num_level_anchors, inside_flags)
assign_result = self.assigner.assign(anchors, num_level_anchors_inside,
gt_bboxes, gt_bboxes_ignore,
gt_labels)
sampling_result = self.sampler.sample(assign_result, anchors,
gt_bboxes)
num_valid_anchors = anchors.shape[0]
bbox_targets = torch.zeros_like(anchors)
bbox_weights = torch.zeros_like(anchors)
labels = anchors.new_full((num_valid_anchors, ),
self.num_classes,
dtype=torch.long)
# print("labels")
# print(labels.shape)
label_weights = anchors.new_zeros(num_valid_anchors, dtype=torch.float)
pos_inds = sampling_result.pos_inds
neg_inds = sampling_result.neg_inds
if len(pos_inds) > 0:
pos_bbox_targets = self.bbox_coder.encode(
sampling_result.pos_bboxes, sampling_result.pos_gt_bboxes)
bbox_targets[pos_inds, :] = pos_bbox_targets
bbox_weights[pos_inds, :] = 1.0
if gt_labels is None:
# Only rpn gives gt_labels as None
# Foreground is the first class since v2.5.0
labels[pos_inds] = 0
else:
labels[pos_inds] = gt_labels[
sampling_result.pos_assigned_gt_inds]
if self.train_cfg.pos_weight <= 0:
label_weights[pos_inds] = 1.0
else:
label_weights[pos_inds] = self.train_cfg.pos_weight
if len(neg_inds) > 0:
label_weights[neg_inds] = 1.0
# map up to original set of anchors
if unmap_outputs:
num_total_anchors = flat_anchors.size(0)
anchors = unmap(anchors, num_total_anchors, inside_flags)
labels = unmap(
labels, num_total_anchors, inside_flags, fill=self.num_classes)
label_weights = unmap(label_weights, num_total_anchors,
inside_flags)
bbox_targets = unmap(bbox_targets, num_total_anchors, inside_flags)
bbox_weights = unmap(bbox_weights, num_total_anchors, inside_flags)
return (anchors, labels, label_weights, bbox_targets, bbox_weights,
pos_inds, neg_inds)
def get_num_level_anchors_inside(self, num_level_anchors, inside_flags):
split_inside_flags = torch.split(inside_flags, num_level_anchors)
num_level_anchors_inside = [
int(flags.sum()) for flags in split_inside_flags
]
return num_level_anchors_inside
|
const room = require("../room/room");
const template = require("./template");
const SocketHandler = template.SocketHandler;
const Worker = require("./../worker/worker").Worker; //worker
let tables = {};
let exitSocketList = []; //退房的socket
/**
* 开个定时器跑,清除已经离开房间的数据
*/
function cleanExitSocketData(){
async function removeRoomSokect(){
if(exitSocketList == null || !(exitSocketList instanceof Array)){
return;
}
if(exitSocketList.length <= 0){
return;
}
for(let i = 0; i < exitSocketList.length; i++){
await exitRoom({sid : exitSocketList.shift()})
}
}
let cusWorker = new Worker(24 * 60 * 60 * 1000,removeRoomSokect);
cusWorker.run();
}
/**
* 执行器
* @param {*} tabs
* @param {*} config
*/
function excute(tabs = {}, config = {}) {
init(config);
tables = tabs;
}
/**
* 参数初始化
* @param {*} config
*/
function init(config) {
let io = config.ws.io;
if (io === undefined || io === null) {
console.error("init socket error ");
return;
}
//前置执行函数
if (config.ws.beforeInit) {
config.ws.beforeInit();
}
listen(io);
cleanExitSocketData();
//后置执行函数
if (config.ws.afterInit) {
config.ws.afterInit();
}
}
/**
* 监听函数
* @param {*} io
*/
function listen(io) {
io.sockets.on('connection', function (socket) {
var handler = new SocketHandler(io.sockets,socket);
socket.on('disconnect',async function (reason) {
handler._disconnect({});
// exitSocketList.push(socket.id);
// if(exitSocketList.length > 1000){
// new Worker(24 * 60 * 60 * 1000,removeRoomSokect);
// cusWorker.run();
// }
});
socket.on('createAndJoin', async function (message) {
let room = message.room;
let recoderId = 1;
handler._createAndJoin(message,{
created : {recoderId:recoderId},
joined : {recoderId:recoderId}
})
});
socket.on('offer', function (message) {
handler._offer(message,{})
});
socket.on('answer', function (message) {
handler._answer(message,{})
});
socket.on('candidate', function (message) {
handler._candidate(message,{})
});
socket.on('exit', async function (message) {
let recoderId = message.recoderId;
handler._exit(message,{})
if(recoderId != undefined){
exitSocketList.push(socket.id);
}
});
socket.on('exist', async function (message) {
let room = message.room;
let data = {};
data.success = true;
data.msg = "ok";
data.room = room;
socket.emit('exist', data);
})
socket.on('catchError', function (err) {
console.log('err : ', err)
})
socket.on('message', function (message) {
handler._message(message,{})
})
});
}
/**
* 房间是否存在
* @param {*} data
*/
async function isRoomExist(data) {
let req = {
ctx: {
tables: tables
},
params: {
rname: data.roomName,
}
};
let rooms = await room.getRoomByName(req, null);
return rooms.length > 0;
}
/**
* 首次创房数据入库
* @param {*} data
*/
async function createRoom(data) {
let req = {
ctx: {
tables: tables
},
params: {
uid: data.uid,
uname: data.uname,
rname: data.roomName,
sid: data.socketId,
ip: data.ip,
device: data.device,
url: data.url,
content: JSON.stringify(data.content)
}
};
let res = await room.addOwnerRoom(req, null);
return res.dataValues.id;
}
/**
* 加入房间
* @param {*} data
*/
async function joinRoom(data) {
let req = {
ctx: {
tables: tables
},
params: {
uid: data.uid,
uname: data.uname,
rname: data.roomName,
sid: data.socketId,
ip: data.ip,
device: data.device,
url: data.url,
content: JSON.stringify(data.content)
}
};
let res = await room.addJoinRoom(req, null);
return res.dataValues.id;
}
/**
* 退出房间
* @param {*} data
*/
async function exitRoom(data) {
let req = {
ctx: {
tables: tables
},
params: {
sid: data.sid
}
};
let res = await room.updateRoomBySid(req, null);
return 0;
}
function addWorker(){
}
module.exports = {
excute : excute
}
|
import mod1392 from './mod1392';
var value=mod1392+1;
export default value;
|
/** @type {import("../../../../").Configuration} */
module.exports = {
name: "compiler-name",
module: {
rules: [
{
test: /a\.js$/,
compiler: "compiler",
use: "./loader"
},
{
test: /b\.js$/,
compiler: "other-compiler",
use: "./loader"
}
]
}
};
|
const { Logger } = require("../config/logger");
const logger = Logger.getInstance();
const {
getUserFromUserEvents,
allEventsArray,
getAllEventsUserRegisteredFor,
filterEventData,
} = require("../services/UserEventsActivitiesService");
const { BadRequestError, NotFoundError } = require("../utils/errors");
//@endpoint GET /userActivities
//@desc get all events that the user joined
//@access PRIVATE - will need to validate token? YES
const handleUserActivities = async (req, res, next) => {
try {
let userId = req.params.userId;
if (!userId) {
throw new BadRequestError(
"Missing user credentials in handleUserActivities."
);
}
let userData = await getUserFromUserEvents(userId);
//if you have never signed up for any events yet.
if (!userData.events) {
throw new NotFoundError(
"Seems like you are new, you may head to the home page to find activities or talk to our chatbot!"
);
}
//if you registered for events.
let allEvents = allEventsArray(userData);
let eventData = await getAllEventsUserRegisteredFor(allEvents, userId);
if (!eventData) {
throw new NotFoundError("Currently not registered for any events.");
}
//get all the events the user is signed up for but NOT HOSTING.
let filteredEventData = filterEventData(eventData);
if (!filteredEventData) {
throw new NotFoundError(
"Seems like you have no registered to any events! Head to the home page to find activities!"
);
}
return res.status(200).json({
status: 200,
message: "Success getting all events you have registered for!",
events: filteredEventData,
});
//find all the events that you have registered for.
} catch (err) {
next(err);
}
};
//@endpoint GET /userRegisteredEvents/:_id
//@desc get registered events associated with current user logged in.
//@access PRIVATE - will need to validate token? YES
const handleUserRegisteredEvents = async (req, res, next) => {
try {
const userId = req.params._id;
if (!userId) {
throw new BadRequestError(
"Missing user credentials in handleUserRegisteredEvents."
);
}
let userData = await getUserFromUserEvents(userId);
if (!userData.events) {
throw new NotFoundError(
"There are no registered events under this user."
);
}
//now we have array of event Ids... we can get back all ids.
let allEvents = allEventsArray(userData);
let eventData = await getAllEventsUserRegisteredFor(allEvents, userId);
if (!eventData) {
throw new NotFoundError(
"Currently not registered for any events in handleUserRegisteredEvents."
);
}
res.status(200).json({
status: 200,
message:
"Success getting all registered events associated with the user!",
userRegisteredEvents: allEvents.events,
eventInfo: eventData,
});
} catch (err) {
next(err);
}
};
module.exports = { handleUserRegisteredEvents, handleUserActivities };
|
import React from 'react';
import { Image, StyleSheet, Button, Text, View} from 'react-native';
import { ImagePicker } from 'expo';
import * as firebase from 'firebase';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
pct:0,
foto:null
}
let config = {
apiKey: "AIzaSyCStywi2WBlq4U6PbfDQ01zkSDWWCZGLwg",
authDomain: "projeto-teste-4354f.firebaseapp.com",
databaseURL: "https://projeto-teste-4354f.firebaseio.com",
projectId: "projeto-teste-4354f",
storageBucket: "projeto-teste-4354f.appspot.com",
messagingSenderId: "949847838320"
};
firebase.initializeApp(config);
this.pegarFoto = this.pegarFoto.bind(this);
this.carregarAvatar = this.carregarAvatar.bind(this);
this.carregarAvatar('images/imagem.jpg');
}
carregarAvatar(img) {
firebase.storage().ref().child(img).getDownloadURL().then((url)=>{
let state = this.state;
state.foto = {uri:url};
this.setState(state);
});
}
pegarFoto = async () => {
let result = await ImagePicker.launchImageLibraryAsync();
if(!result.cancelled) {
this.uploadImage(result.uri, "imagem2.jpg")
.then(() => {
alert("success");
})
.catch((error) =>{
alert(error.code);
});
}
}
uploadImage = async (uri, imageName) => {
const response = await fetch(uri);
const blob = await response.blob();
let ref = firebase.storage().ref().child("images/" + imageName);
let mine = 'image/jpeg';
return ref.put(blob, {contentType:mine})
.on('state_changed', (snapshot)=>{
let pct = ( snapshot.bytesTransferred / snapshot.totalBytes ) * 100;
let state = this.state;
state.pct = pct;
this.setState(state);
},
(error)=>{
alert(error.code);
},
()=>{
ref.getDownloadURL().then((url)=>{
let state = this.state;
state.foto = {uri:url};
this.setState(state);
});
alert("Imagem carregada com sucesso");
})
}
render() {
return(
<View style={styles.container}>
<Button title="Choose Image..." onPress={this.pegarFoto} />
<Text>{this.state.pct}</Text>
<View style={{width: this.state.pct+'%', height: 40, backgroundColor: '#FF0000'}}></View>
<Image source={this.state.foto} style={styles.foto} />
</View>
);
}
}
const styles = StyleSheet.create({
container:{
flex:1,
paddingTop: 40
},
foto:{
width: 300,
height: 300
}
});
|
const {Block, Attribute, Fragment, Slice} = require("../model")
const {Step, StepResult, PosMap, ReplaceStep} = require("../transform")
const {copyObj} = require("../util/obj")
const {Selection} = require("../edit")
// ;; A table node type. Has one attribute, **`columns`**, which holds
// a number indicating the amount of columns in the table.
class Table extends Block {
get attrs() { return {columns: new Attribute({default: 1})} }
toDOM() { return ["table", ["tbody", 0]] }
get matchDOMTag() {
return {"table": dom => {
let row = dom.querySelector("tr")
if (!row || !row.children.length) return false
// FIXME using the child count as column width is problematic
// when parsing document fragments
return {columns: row.children.length}
}}
}
}
exports.Table = Table
// ;; A table row node type. Has one attribute, **`columns`**, which
// holds a number indicating the amount of columns in the table.
class TableRow extends Block {
get attrs() { return {columns: new Attribute({default: 1})} }
toDOM() { return ["tr", 0] }
get matchDOMTag() {
return {"tr": dom => dom.children.length ? {columns: dom.children.length} : false}
}
}
exports.TableRow = TableRow
// ;; A table cell node type.
class TableCell extends Block {
toDOM() { return ["td", 0] }
get matchDOMTag() { return {"td": null} }
}
exports.TableCell = TableCell
// :: (OrderedMap, string, ?string) → OrderedMap
// Convenience function for adding table-related node types to a map
// describing the nodes in a schema. Adds `Table` as `"table"`,
// `TableRow` as `"table_row"`, and `TableCell` as `"table_cell"`.
// `cellContent` should be a content expression describing what may
// occur inside cells.
function addTableNodes(nodes, cellContent, tableGroup) {
return nodes.append({
table: {type: Table, content: "table_row[columns=.columns]+", group: tableGroup},
table_row: {type: TableRow, content: "table_cell{.columns}"},
table_cell: {type: TableCell, content: cellContent}
})
}
exports.addTableNodes = addTableNodes
// :: (NodeType, number, number, ?Object) → Node
// Create a table node with the given number of rows and columns.
function createTable(nodeType, rows, columns, attrs) {
attrs = attrs ? copyObj(attrs) : Object.create(null)
attrs.columns = columns
let rowType = nodeType.contentExpr.elements[0].nodeTypes[0]
let cellType = rowType.contentExpr.elements[0].nodeTypes[0]
let cell = cellType.createAndFill(), cells = []
for (let i = 0; i < columns; i++) cells.push(cell)
let row = rowType.create({columns}, Fragment.from(cells)), rowNodes = []
for (let i = 0; i < rows; i++) rowNodes.push(row)
return nodeType.create(attrs, Fragment.from(rowNodes))
}
exports.createTable = createTable
// Steps to add and remove a column
function adjustColumns(attrs, diff) {
let copy = copyObj(attrs)
copy.columns = attrs.columns + diff
return copy
}
// ;; A `Step` subclass for adding a column to a table in a single
// atomic step.
class AddColumnStep extends Step {
constructor(positions, cells) {
super()
this.positions = positions
this.cells = cells
}
// :: (Node, number, number, NodeType, ?Object) → AddColumnStep
// Create a step that inserts a column into the table after
// `tablePos`, at the index given by `columnIndex`, using cells with
// the given type and attributes.
static create(doc, tablePos, columnIndex, cellType, cellAttrs) {
let cell = cellType.createAndFill(cellAttrs)
let positions = [], cells = []
let table = doc.nodeAt(tablePos)
table.forEach((row, rowOff) => {
let cellPos = tablePos + 2 + rowOff
for (let i = 0; i < columnIndex; i++) cellPos += row.child(i).nodeSize
positions.push(cellPos)
cells.push(cell)
})
return new AddColumnStep(positions, cells)
}
apply(doc) {
let index = null, table = null, tablePos = null
for (let i = 0; i < this.positions.length; i++) {
let $pos = doc.resolve(this.positions[i])
if ($pos.depth < 2 || $pos.index(-1) != i)
return StepResult.fail("Invalid cell insert position")
if (table == null) {
table = $pos.node(-1)
if (table.childCount != this.positions.length)
return StepResult.fail("Mismatch in number of rows")
tablePos = $pos.before(-1)
index = $pos.index()
} else if ($pos.before(-1) != tablePos || $pos.index() != index) {
return StepResult.fail("Column insert positions not consistent")
}
}
let updatedRows = []
for (let i = 0; i < table.childCount; i++) {
let row = table.child(i), rowCells = index ? [] : [this.cells[i]]
for (let j = 0; j < row.childCount; j++) {
rowCells.push(row.child(j))
if (j + 1 == index) rowCells.push(this.cells[i])
}
updatedRows.push(row.type.create(adjustColumns(row.attrs, 1), Fragment.from(rowCells)))
}
let updatedTable = table.type.create(adjustColumns(table.attrs, 1), Fragment.from(updatedRows))
return StepResult.fromReplace(doc, tablePos, tablePos + table.nodeSize,
new Slice(Fragment.from(updatedTable), 0, 0))
}
posMap() {
let ranges = []
for (let i = 0; i < this.positions.length; i++)
ranges.push(this.positions[i], 0, this.cells[i].nodeSize)
return new PosMap(ranges)
}
invert(doc) {
let $first = doc.resolve(this.positions[0])
let table = $first.node(-1)
let from = [], to = [], dPos = 0
for (let i = 0; i < table.childCount; i++) {
let pos = this.positions[i] + dPos, size = this.cells[i].nodeSize
from.push(pos)
to.push(pos + size)
dPos += size
}
return new RemoveColumnStep(from, to)
}
map(mapping) {
return new AddColumnStep(this.positions.map(p => mapping.map(p)), this.cells)
}
toJSON() {
return {stepType: this.jsonID,
positions: this.positions,
cells: this.cells.map(c => c.toJSON())}
}
static fromJSON(schema, json) {
return new AddColumnStep(json.positions, json.cells.map(schema.nodeFromJSON))
}
}
exports.AddColumnStep = AddColumnStep
Step.jsonID("addTableColumn", AddColumnStep)
// ;; A subclass of `Step` that removes a column from a table.
class RemoveColumnStep extends Step {
constructor(from, to) {
super()
this.from = from
this.to = to
}
// :: (Node, number, number) → RemoveColumnStep
// Create a step that deletes the column at `columnIndex` in the
// table after `tablePos`.
static create(doc, tablePos, columnIndex) {
let from = [], to = []
let table = doc.nodeAt(tablePos)
table.forEach((row, rowOff) => {
let cellPos = tablePos + 2 + rowOff
for (let i = 0; i < columnIndex; i++) cellPos += row.child(i).nodeSize
from.push(cellPos)
to.push(cellPos + row.child(columnIndex).nodeSize)
})
return new RemoveColumnStep(from, to)
}
apply(doc) {
let index = null, table = null, tablePos = null
for (let i = 0; i < this.from.length; i++) {
let $from = doc.resolve(this.from[i]), after = $from.nodeAfter
if ($from.depth < 2 || $from.index(-1) != i || !after || this.from[i] + after.nodeSize != this.to[i])
return StepResult.fail("Invalid cell delete positions")
if (table == null) {
table = $from.node(-1)
if (table.childCount != this.from.length)
return StepResult.fail("Mismatch in number of rows")
tablePos = $from.before(-1)
index = $from.index()
} else if ($from.before(-1) != tablePos || $from.index() != index) {
return StepResult.fail("Column delete positions not consistent")
}
}
let updatedRows = []
for (let i = 0; i < table.childCount; i++) {
let row = table.child(i), rowCells = []
for (let j = 0; j < row.childCount; j++)
if (j != index) rowCells.push(row.child(j))
updatedRows.push(row.type.create(adjustColumns(row.attrs, -1), Fragment.from(rowCells)))
}
let updatedTable = table.type.create(adjustColumns(table.attrs, -1), Fragment.from(updatedRows))
return StepResult.fromReplace(doc, tablePos, tablePos + table.nodeSize,
new Slice(Fragment.from(updatedTable), 0, 0))
}
posMap() {
let ranges = []
for (let i = 0; i < this.from.length; i++)
ranges.push(this.from[i], this.to[i] - this.from[i], 0)
return new PosMap(ranges)
}
invert(doc) {
let $first = doc.resolve(this.from[0])
let table = $first.node(-1), index = $first.index()
let positions = [], cells = [], dPos = 0
for (let i = 0; i < table.childCount; i++) {
positions.push(this.from[i] - dPos)
let cell = table.child(i).child(index)
dPos += cell.nodeSize
cells.push(cell)
}
return new AddColumnStep(positions, cells)
}
map(mapping) {
let from = [], to = []
for (let i = 0; i < this.from.length; i++) {
let start = mapping.map(this.from[i], 1), end = mapping.map(this.to[i], -1)
if (end <= start) return null
from.push(start)
to.push(end)
}
return new RemoveColumnStep(from, to)
}
static fromJSON(_schema, json) {
return new RemoveColumnStep(json.from, json.to)
}
}
exports.RemoveColumnStep = RemoveColumnStep
Step.jsonID("removeTableColumn", RemoveColumnStep)
// Table-related command functions
function findRow($pos, pred) {
for (let d = $pos.depth; d > 0; d--)
if ($pos.node(d).type instanceof TableRow && (!pred || pred(d))) return d
return -1
}
// :: (ProseMirror, ?bool) → bool
// Command function that adds a column before the column with the
// selection.
function addColumnBefore(pm, apply) {
let $from = pm.selection.$from, cellFrom
let rowDepth = findRow($from, d => cellFrom = d == $from.depth ? $from.nodeBefore : $from.node(d + 1))
if (rowDepth == -1) return false
if (apply !== false)
pm.tr.step(AddColumnStep.create(pm.doc, $from.before(rowDepth - 1), $from.index(rowDepth),
cellFrom.type, cellFrom.attrs)).apply()
return true
}
exports.addColumnBefore = addColumnBefore
// :: (ProseMirror, ?bool) → bool
// Command function that adds a column after the column with the
// selection.
function addColumnAfter(pm, apply) {
let $from = pm.selection.$from, cellFrom
let rowDepth = findRow($from, d => cellFrom = d == $from.depth ? $from.nodeAfter : $from.node(d + 1))
if (rowDepth == -1) return false
if (apply !== false)
pm.tr.step(AddColumnStep.create(pm.doc, $from.before(rowDepth - 1),
$from.indexAfter(rowDepth) + (rowDepth == $from.depth ? 1 : 0),
cellFrom.type, cellFrom.attrs)).apply()
return true
}
exports.addColumnAfter = addColumnAfter
// :: (ProseMirror, ?bool) → bool
// Command function that removes the column with the selection.
function removeColumn(pm, apply) {
let $from = pm.selection.$from
let rowDepth = findRow($from, d => $from.node(d).childCount > 1)
if (rowDepth == -1) return false
if (apply !== false)
pm.tr.step(RemoveColumnStep.create(pm.doc, $from.before(rowDepth - 1), $from.index(rowDepth))).apply()
return true
}
exports.removeColumn = removeColumn
function addRow(pm, apply, side) {
let $from = pm.selection.$from
let rowDepth = findRow($from)
if (rowDepth == -1) return false
if (apply !== false) {
let exampleRow = $from.node(rowDepth)
let cells = [], pos = side < 0 ? $from.before(rowDepth) : $from.after(rowDepth)
exampleRow.forEach(cell => cells.push(cell.type.createAndFill(cell.attrs)))
let row = exampleRow.copy(Fragment.from(cells))
pm.tr.step(new ReplaceStep(pos, pos, new Slice(Fragment.from(row), 0, 0))).apply()
}
return true
}
// :: (ProseMirror, ?bool) → bool
// Command function that adds a row after the row with the
// selection.
function addRowBefore(pm, apply) {
return addRow(pm, apply, -1)
}
exports.addRowBefore = addRowBefore
// :: (ProseMirror, ?bool) → bool
// Command function that adds a row before the row with the
// selection.
function addRowAfter(pm, apply) {
return addRow(pm, apply, 1)
}
exports.addRowAfter = addRowAfter
// :: (ProseMirror, ?bool) → bool
// Command function that removes the row with the selection.
function removeRow(pm, apply) {
let $from = pm.selection.$from
let rowDepth = findRow($from, d => $from.node(d - 1).childCount > 1)
if (rowDepth == -1) return false
if (apply !== false)
pm.tr.step(new ReplaceStep($from.before(rowDepth), $from.after(rowDepth), Slice.empty)).apply()
return true
}
exports.removeRow = removeRow
function moveCell(pm, dir, apply) {
let {$from} = pm.selection
let rowDepth = findRow($from)
if (rowDepth == -1) return false
let row = $from.node(rowDepth), newIndex = $from.index(rowDepth) + dir
if (newIndex >= 0 && newIndex < row.childCount) {
let $cellStart = pm.doc.resolve(row.content.offsetAt(newIndex) + $from.start(rowDepth))
let sel = Selection.findFrom($cellStart, 1)
if (!sel || sel.from >= $cellStart.end()) return false
if (apply !== false) pm.setSelection(sel)
return true
} else {
let rowIndex = $from.index(rowDepth - 1) + dir, table = $from.node(rowDepth - 1)
if (rowIndex < 0 || rowIndex >= table.childCount) return false
let cellStart = dir > 0 ? $from.after(rowDepth) + 2 : $from.before(rowDepth) - 2 - table.child(rowIndex).lastChild.content.size
let $cellStart = pm.doc.resolve(cellStart), sel = Selection.findFrom($cellStart, 1)
if (!sel || sel.from >= $cellStart.end()) return false
if (apply !== false) pm.setSelection(sel)
return true
}
}
// :: (ProseMirror, ?bool) → bool
// Move to the next cell in the current table, if there is one.
function selectNextCell(pm, apply) { return moveCell(pm, 1, apply) }
exports.selectNextCell = selectNextCell
// :: (ProseMirror, ?bool) → bool
// Move to the previous cell in the current table, if there is one.
function selectPreviousCell(pm, apply) { return moveCell(pm, -1, apply) }
exports.selectPreviousCell = selectPreviousCell
|
/*! Copyright 2009-2017 Evernote Corporation. All rights reserved. */
function ReminderSetter(a,b,c,d,e,f,g,h,i,j){"use strict";function k(a){var b=document.querySelector("#date span.focused");if(b){clearTimeout(w);var c=parseInt(s.innerText||s.textContent),d=parseInt(q.innerText||q.textContent)-1,e=parseInt(r.innerText||r.textContent);if(38==a.keyCode)b===s?A.selectDate(new Date(c+1,d,e),"year"):b===q?A.selectDate(new Date(c,d+1,e),"month"):b===r?A.selectDate(new Date(c,d,e+1),"date"):b===t?(hour=(hour+1)%24,A.selectDate(new Date(c,d,e),"hour")):b===u?(minute=(minute+1)%60,A.selectDate(new Date(c,d,e),"minute")):b===v&&(hour=(hour+12)%24,A.selectDate(new Date(c,d,e),"meridian"));else if(39==a.keyCode)b.nextElementSibling&&b.nextElementSibling.click();else if(40==a.keyCode)b===s?A.selectDate(new Date(c-1,d,e),"year"):b===q?A.selectDate(new Date(c,d-1,e),"month"):b===r?A.selectDate(new Date(c,d,e-1),"date"):b===t?(hour=(hour-1+24)%24,A.selectDate(new Date(c,d,e),"hour")):b===u?(minute=(minute-1+60)%60,A.selectDate(new Date(c,d,e),"minute")):b===v&&(hour=(hour-12+24)%24,A.selectDate(new Date(c,d,e),"meridian"));else if(37==a.keyCode)b.previousElementSibling&&b.previousElementSibling.click();else if(a.keyCode>=48&&a.keyCode<=57||a.keyCode>=96&&a.keyCode<=105){var f=a.keyCode%48;if(a.keyCode>57&&(f=a.keyCode%96),b===s)s.innerText.length<3?(s.innerText+=f,w=setTimeout(function(){A.selectDate(new Date(parseInt(s.innerText||s.textContent),d,e))},500)):3==s.innerText.length?(s.innerText+=f,A.selectDate(new Date(parseInt(s.innerText||s.textContent),d,e))):(s.innerText=f,w=setTimeout(function(){A.selectDate(new Date(parseInt(s.innerText||s.textContent),d,e))},500));else if(b===q)q.innerText.length<2?-1==d?(q.innerText=f,A.selectDate(new Date(c,f-1,e))):f<3?(q.innerText+=f,A.selectDate(new Date(c,parseInt(q.innerText||q.textContent)-1,e))):w=setTimeout(function(){A.selectDate(new Date(c,d,e))},500):(q.innerText=f,f>1?A.selectDate(new Date(c,f-1,e)):w=setTimeout(function(){var a=parseInt(q.innerText||q.textContent)-1;a=a<0?d:a,A.selectDate(new Date(c,a,e))},500));else if(b===r)r.innerText.length<2?e<2?(r.innerText+=f,A.selectDate(new Date(c,d,parseInt(r.innerText||r.textContent)))):new Date(c,d,10*e+f).getDate()==10*e+f?(r.innerText+=f,A.selectDate(new Date(c,d,parseInt(r.innerText||r.textContent)))):w=setTimeout(function(){A.selectDate(new Date(c,d,e))},500):(r.innerText=f,f>3?A.selectDate(new Date(c,d,parseInt(r.innerText||r.textContent))):w=setTimeout(function(){A.selectDate(new Date(c,d,parseInt(r.innerText||r.textContent)))},500));else if(b===t)if(t.innerText.length<2){var g=parseInt(t.innerText);0==g?(hour=f,A.selectDate(new Date(c,d,e))):1==g&&(f<3?(hour=10+f,A.selectDate(new Date(c,d,e))):w=setTimeout(function(){hour=1,A.selectDate(new Date(c,d,e))},500))}else f<2?(t.innerText=f,w=setTimeout(function(){0!=f&&(hour=f),A.selectDate(new Date(c,d,e))},500)):(hour=f,A.selectDate(new Date(c,d,e)));else if(b===u)if(u.innerText.length<2){var g=parseInt(u.innerText);minute=10*g+f,A.selectDate(new Date(c,d,e))}else f<6?(u.innerText=f,w=setTimeout(function(){0!=f&&(minute=f),A.selectDate(new Date(c,d,e))},500)):(minute=f,A.selectDate(new Date(c,d,e)))}else 65!=a.keyCode&&80!=a.keyCode||b===v&&(("AM"==v.innerText&&80==a.keyCode||"PM"==v.innerText&&65==a.keyCode)&&(hour=(hour+12)%24),A.selectDate(new Date(c,d,e)))}}function l(){var a=o.querySelector("#date span.focused");a&&a.classList.remove("focused"),this.classList.add("focused")}function m(a,b){var c=new Date(a.year,a.month,a.date,hour,minute,0,0);if(y.innerHTML=A.format(c),q=document.getElementById("selectedMonth"),r=document.getElementById("selectedDate"),s=document.getElementById("selectedYear"),t=document.getElementById("selectedHour"),u=document.getElementById("selectedMinute"),v=document.getElementById("selectedMeridian"),q.addEventListener("click",l),r.addEventListener("click",l),s.addEventListener("click",l),t.addEventListener("click",l),u.addEventListener("click",l),v.addEventListener("click",l),b)switch(b){case"year":s.click();break;case"month":q.click();break;case"date":r.click();break;case"hour":t.click();break;case"minute":u.click();break;case"meridian":v.click()}return c}function n(){if(h(),a.classList.contains("added")?(A.selectedDate()||(o.classList.remove("hasDate"),document.onkeydown=null),A.showTodayOrSelected()):(document.onkeydown=function(a){8==a.keyCode&&a.preventDefault()},a.classList.add("added"),x=Date.now(),Browser.sendToExtension({name:"setReminder",shardId:c,token:b,noteGuid:e,noteStoreUrl:d,title:f,sourceURL:g,reminderOrder:x}),j(ReminderSetter.REMINDER_TYPES.NO_DATE)),o.classList.toggle("visible"))a.classList.add("changingDate");else{a.classList.remove("changingDate");var i=o.querySelector("#date span.focused");i&&i.classList.remove("focused")}}var o=document.createElement("div");o.id="remindersSetter",o.innerHTML='<div id="noDate"><div class="reminderHeader">'+Browser.i18n.getMessage("reminderAdded")+'</div><div id="addDate" class="reminderButton">'+Browser.i18n.getMessage("addDate")+'</div></div><div id="hasDate"><div class="reminderHeader">'+Browser.i18n.getMessage("notifyMe")+'</div><div id="tomorrow" class="reminderButton">'+Browser.i18n.getMessage("tomorrow")+'</div><div id="nextWeek" class="reminderButton">'+Browser.i18n.getMessage("nextWeek")+'</div><div id="date"></div><div id="datePicker"></div></div>',a.parentNode.insertBefore(o,a.nextElementSibling);var p=Math.min(255,456-a.offsetLeft-38);p+130<456-a.offsetLeft+5?(o.style.left=Math.max(5,a.offsetLeft-38)+"px",o.style.transformOrigin=a.offsetLeft+9+"px 0"):(o.style.right=p+"px",o.style.transformOrigin="calc(100% - "+(456-p-a.offsetLeft+9)+"px) 0");var q,r,s,t,u,v,w,x=null,y=document.getElementById("date"),z=!1,A=new DatePicker(document.getElementById("datePicker"),function(a,h){Browser.sendToExtension({name:"setReminder",token:b,shardId:c,noteStoreUrl:d,noteGuid:e,title:f,sourceURL:g,reminderOrder:x,reminderTime:m(a,h)-0}),z||(z=!0,j(ReminderSetter.REMINDER_TYPES.CUSTOM_DATE))}),B=new Date;m({year:B.getFullYear(),month:B.getMonth(),date:B.getDate()});var C=document.getElementById("addDate"),D=document.querySelector("#noDate .reminderHeader");if(C.scrollWidth>C.clientWidth||D.scrollWidth>D.clientWidth||o.scrollHeight>o.clientHeight){var E=document.createElement("style");if(C.scrollWidth>C.clientWidth||D.scrollWidth>D.clientWidth){var F=Math.max(C.scrollWidth-C.clientWidth,D.scrollWidth-D.clientWidth);E.innerText="#remindersSetter { width: "+(112+F)+"px; }"}else o.scrollHeight>o.clientHeight&&(E.innerText="#remindersSetter { height: "+(165+o.scrollHeight-o.clientHeight)+"px; }");document.head.appendChild(E)}a.addEventListener("click",n),C.addEventListener("click",function(){h(),o.classList.add("hasDate")}),document.getElementById("tomorrow").addEventListener("click",function(){z||(z=!0,j(ReminderSetter.REMINDER_TYPES.TOMORROW));var a=new Date;a.setDate(a.getDate()+1),A.selectDate(a)}),document.getElementById("nextWeek").addEventListener("click",function(){z||(z=!0,j(ReminderSetter.REMINDER_TYPES.NEXT_WEEK));var a=new Date;a.setDate(a.getDate()+7),A.selectDate(a)}),o.addEventListener("click",function(a){if(!y.contains(a.target)){var b=o.querySelector("#date span.focused");b&&b.classList.remove("focused")}}),o.addEventListener(Browser.whichTransitionEnd(),function(a){if("width"===a.propertyName&&!o.classList.contains("hasDate")&&o.scrollHeight>o.clientHeight){var b=document.createElement("style");b.innerText="#remindersSetter { height: "+(53+o.scrollHeight-o.clientHeight)+"px; }",document.head.appendChild(b)}else"height"!==a.propertyName&&"opacity"!==a.propertyName||i()}),window.addEventListener("keydown",k),window.addEventListener("click",function(b){!o.classList.contains("visible")||o.contains(b.target)||a.contains(b.target)||n.call(a)}),this.__defineGetter__("height",function(){return o.classList.contains("visible")?o.offsetHeight+5:0}),this.__defineGetter__("top",function(){return o.offsetTop}),Object.preventExtensions(this)}ReminderSetter.REMINDER_TYPES={NO_DATE:1,TOMORROW:2,NEXT_WEEK:3,CUSTOM_DATE:4},Object.preventExtensions(ReminderSetter);
|
#import <Foundation/Foundation.h>
#import <CoreGraphics/CoreGraphics.h>
#import "MGLFoundation.h"
#import "MGLTypes.h"
NS_ASSUME_NONNULL_BEGIN
typedef NSString *MGLStyleFunctionOption NS_STRING_ENUM NS_UNAVAILABLE;
extern MGL_EXPORT const MGLStyleFunctionOption MGLStyleFunctionOptionInterpolationBase __attribute__((unavailable("Use NSExpression instead, applying the mgl_interpolate:withCurveType:parameters:stops: function with a curve type of “exponential” and a non-nil parameter.")));
extern MGL_EXPORT const MGLStyleFunctionOption MGLStyleFunctionOptionDefaultValue __attribute__((unavailable("Use +[NSExpression expressionForConditional:trueExpression:falseExpression:] instead.")));
typedef NS_ENUM(NSUInteger, MGLInterpolationMode) {
MGLInterpolationModeExponential __attribute__((unavailable("Use NSExpression instead, applying the mgl_interpolate:withCurveType:parameters:stops: function with a curve type of “exponential”."))) = 0,
MGLInterpolationModeInterval __attribute__((unavailable("Use NSExpression instead, calling the mgl_step:from:stops: function."))),
MGLInterpolationModeCategorical __attribute__((unavailable("Use NSExpression instead."))),
MGLInterpolationModeIdentity __attribute__((unavailable("Use +[NSExpression expressionForKeyPath:] instead.")))
} __attribute__((unavailable("Use NSExpression instead.")));
MGL_EXPORT __attribute__((unavailable("Use NSExpression instead.")))
@interface MGLStyleValue<T> : NSObject
@end
MGL_EXPORT __attribute__((unavailable("Use +[NSExpression expressionForConstantValue:] instead.")))
@interface MGLConstantStyleValue<T> : MGLStyleValue<T>
@end
@compatibility_alias MGLStyleConstantValue MGLConstantStyleValue;
MGL_EXPORT __attribute__((unavailable("Use NSExpression instead, calling the mgl_step:from:stops: or mgl_interpolate:withCurveType:parameters:stops: function.")))
@interface MGLStyleFunction<T> : MGLStyleValue<T>
@end
MGL_EXPORT __attribute__((unavailable("Use NSExpression instead, applying the mgl_step:from:stops: or mgl_interpolate:withCurveType:parameters:stops: function to the $zoomLevel variable.")))
@interface MGLCameraStyleFunction<T> : MGLStyleFunction<T>
@end
MGL_EXPORT __attribute__((unavailable("Use NSExpression instead, applying the mgl_step:from:stops: or mgl_interpolate:withCurveType:parameters:stops: function to a key path expression.")))
@interface MGLSourceStyleFunction<T> : MGLStyleFunction<T>
@end
MGL_EXPORT __attribute__((unavailable("Use a NSExpression instead with nested mgl_step:from:stops: or mgl_interpolate:withCurveType:parameters:stops: function calls.")))
@interface MGLCompositeStyleFunction<T> : MGLStyleFunction<T>
@end
NS_ASSUME_NONNULL_END
|
import React from 'react';
import People from '../../assets/People-asking.svg';
import { Icon } from 'antd';
const Historial = () =>{
return(
<div className="container-body-empty">
<h2>Historial</h2>
</div>
)
}
export default Historial
|
// @flow
/*
Author: Ievgeniia Ozirna
Licensed under the CC BY-NC-ND 3.0: http://creativecommons.org/licenses/by-nc-nd/3.0/
*/
import { combineReducers } from 'redux';
import { createAction, handleActions } from 'redux-actions';
import { formReducer, modelReducer } from 'react-redux-form';
export type RequestState = {
isPending: boolean
}
export type CountryStoreForm = {
country: string,
store: string
}
export const modelPath: string = 'findStore.data';
export const requestState: RequestState = { isPending: false };
export const formState: CountryStoreForm = {
country: '',
store: '',
};
export const findStore = createAction('FIND_STORE');
export const findStorePending = createAction('FIND_STORE_PENDING');
export const findStoreFulfilled = createAction('FIND_STORE_FULFILLED');
export const findStoreRejected = createAction('FIND_STORE_REJECTED');
export default combineReducers({
request: handleActions({
[findStorePending]: () => ({ isPending: true }),
[findStoreFulfilled]: () => ({ isPending: false }),
[findStoreRejected]: () => ({ isPending: false }),
}, requestState),
form: formReducer(modelPath, formState),
data: modelReducer(modelPath, formState),
});
|
from rdflib import URIRef, Namespace
from rdflib.namespace import RDF
from pyproms.proms_report import PromsReport
from pyproms.prov_activity import ProvActivity
from pyproms.proms_error import *
class PromsInternalReport(PromsReport):
"""
Creates a PROMS-O Internal Report instance
This has the set of all Activities and an ending activity in addition to a Report class object
"""
def __init__(self,
label,
wasReportedBy,
nativeId,
startingActivity,
endingActivity,
all_activities,
generatedAtTime,
comment=None):
PromsReport.__init__(self,
label,
wasReportedBy,
nativeId,
startingActivity,
generatedAtTime,
comment)
self.__set_endingActivity(startingActivity, endingActivity)
self.__set_all_activities(all_activities)
def __set_endingActivity(self, startingActivity, endingActivity):
if type(endingActivity) is ProvActivity:
if startingActivity is not None:
if endingActivity == startingActivity:
raise PromsOntologyError(
'For an Internal Report, the ending activity and starting activity must not be the same')
self.endingActivity = endingActivity
else:
raise TypeError('endingActivity must be an Agent, not a %s' % type(endingActivity))
def __set_all_activities(self, all_activities):
if all(isinstance(n, ProvActivity) for n in all_activities):
self.all_activities = all_activities
else:
raise TypeError('all_activities must be a list of Activity objects')
def make_graph(self):
"""
Specialises PromsReport.make_graph()
:return: an rdflib Graph object
"""
PromsReport.make_graph(self)
PROMS = Namespace('http://promsns.org/def/proms#')
self.g.bind('proms', PROMS)
self.g.remove((
URIRef(self.uri),
RDF.type,
PROMS.Report))
self.g.add((
URIRef(self.uri),
RDF.type,
PROMS.InternalReport))
for activity in self.all_activities:
# add the Activity to the graph
self.g = self.g + activity.get_graph()
# remove the triple that points the endingActivity to the startingActivity in the Report class
self.g.remove((None, PROMS.endingActivity, None))
# re-add the endingActivity triple pointing to the new Activity
self.g.add((URIRef(self.uri),
PROMS.endingActivity,
URIRef(self.endingActivity.uri)))
|
import unittest
from subprocess import Popen, PIPE, STDOUT
import string
import random
import os
def string_generator(size=6, chars=string.ascii_uppercase + string.digits + " " + string.punctuation):
return ''.join(random.choice(chars) for _ in range(size))
def TestBase():
stdIn = string_generator()
p = Popen(['python', 'solution.py'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
stdout = p.communicate(input=bytes(stdIn, encoding='utf-8'))[0]
expectedStdout = "Hello, World." + os.linesep + stdIn + os.linesep
return (stdout.decode(), expectedStdout)
class test(unittest.TestCase):
def testCase1(self):
result = TestBase()
self.assertEqual( result[0], result[1])
def testCase2(self):
result = TestBase()
self.assertEqual( result[0], result[1])
def testCase3(self):
result = TestBase()
self.assertEqual( result[0], result[1])
def testCase4(self):
result = TestBase()
self.assertEqual( result[0], result[1])
def testCase5(self):
result = TestBase()
self.assertEqual( result[0], result[1])
def testCase6(self):
result = TestBase()
self.assertEqual( result[0], result[1])
def testCase7(self):
result = TestBase()
self.assertEqual( result[0], result[1])
def testCase8(self):
result = TestBase()
self.assertEqual( result[0], result[1])
def testCase9(self):
result = TestBase()
self.assertEqual( result[0], result[1])
def testCase10(self):
result = TestBase()
self.assertEqual( result[0], result[1])
if __name__ == '__main__':
unittest.main()
|
"""
Cerberus schema building utilities
"""
from cerberus import Validator
PRIMITIVES = [int, float, bool, str, dict, list]
def build_validator(**schema):
"""
Returns a function that validates an input dictionary,
based on the supplied validation schema.
"""
cerberus_schema = _build_schema(schema)
def validate(data: dict):
"""
Ensure data adhers to schema.
"""
validator = Validator(cerberus_schema, allow_unknown=False, require_all=True)
if not validator.validate(data):
errors = validator.errors
raise ValidationException(errors)
return validate
def build_schema(**schema):
return _build_schema(schema)
def _build_schema(schema):
if schema in PRIMITIVES:
return _build_primitive(schema)
s_type = type(schema)
if s_type in [Dict, List, DictGeneric]:
return schema.build_schema()
assert type(schema) is dict, "Schema must be a dict"
cerberus_schema = {}
for k, v in schema.items():
if v in PRIMITIVES:
cerberus_schema[k] = _build_primitive(v)
else:
v_type = type(v)
if v_type not in [Dict, List, DictGeneric]:
raise ValueError(f"Could not build schema from type {k}: {v_type}")
cerberus_schema[k] = v.build_schema()
return cerberus_schema
def _build_primitive(v_type):
if v_type is int:
return {"type": "integer"}
elif v_type is float:
return {"type": "float"}
elif v_type is bool:
return {"type": "boolean"}
elif v_type is str:
return {"type": "string"}
elif v_type is dict:
return {"type": "dict"}
elif v_type is list:
return {"type": "list"}
else:
raise ValueError(f"Could not find type {v_type}")
class List:
def __init__(self, arg_schema):
self.arg_schema = arg_schema
def build_schema(self):
return {"type": "list", "schema": _build_schema(self.arg_schema)}
class Dict:
def __init__(self, **kwargs):
self.schema = kwargs
def build_schema(self):
return {"type": "dict", "schema": _build_schema(self.schema)}
class DictGeneric:
def __init__(self, key_schema, value_schema):
self.key_schema = key_schema
self.value_schema = value_schema
def build_schema(self):
return {
"type": "dict",
"valuesrules": _build_schema(self.value_schema),
"keysrules": _build_schema(self.key_schema),
}
class ValidationException(Exception):
"""An exception thrown when data is invalid"""
|
const request = require('supertest')
const { expressApp } = require('../app/express-app')
const { appConfig } = require('../app/app-config')
const SERVER_URL = appConfig.testServerUrl
const TAREGT_URL = appConfig.testTargetUrl
const LAUNCH_HC_PAGES_NUM = appConfig.launchHcPagesNum
const HTML_TEST_STRINGS = '<html>ok</html>'
console.log('SERVER_URL:', SERVER_URL)
console.log('TAREGT_URL:', TAREGT_URL)
console.log('HTML_TEST_STRINGS:', HTML_TEST_STRINGS)
const sleep = (waitSeconds, someFunction) => {
return new Promise(resolve => {
setTimeout(() => {
resolve(someFunction())
}, waitSeconds)
})
}
describe('requests routes', function () {
this.timeout(2000 * LAUNCH_HC_PAGES_NUM)
let app
before(beforeDone => {
(async() => {
const { getBrowserInstance } = require('../app/browser-instance')
const browserInstance = getBrowserInstance()
app = await expressApp(browserInstance)
beforeDone()
})()
})
after(afterDone => {
/*
しばらくコネクションが残るため
expressのプロセスが終わらないので
テスト終了後、少し待って明示的に終了
*/
(async ()=> {
await app.close()
sleep(5000, () => {
console.log('testing express-app complete! process.exit()')
process.exit()
})
afterDone()
})()
})
const req = request(SERVER_URL)
it('Health Check GET /hc', async () => {
await req.get('/hc')
.expect(200, 'ok')
})
it('GET / with no url', async () => {
await req.get('/')
.expect(400, 'get parameter "url" is not set')
})
it('GET / with url ' + TAREGT_URL, async () => {
await req.get('/?url=' + TAREGT_URL)
.expect('Content-Type', 'application/pdf')
.expect((res) => {
const contentLength = Number(res.headers['content-length'])
if (contentLength < 1024) {
throw new Error('content-length is less than 1KB ' + contentLength)
}
})
.expect(200)
})
it('POST / html=' + HTML_TEST_STRINGS, async () => {
await req.post('/')
.send('html=' + encodeURI(HTML_TEST_STRINGS))
.expect('Content-Type', 'application/pdf')
.expect((res) => {
const contentLength = Number(res.headers['content-length'])
if (contentLength < 1024) {
throw new Error('content-length is less than 1KB ' + contentLength)
}
})
.expect(200)
})
it('LAUNCH_HC_PAGES_NUM of concurrent access to POST / html=' + HTML_TEST_STRINGS, async () => {
function task() {
return new Promise(async function(resolve) {
await req.post('/')
.send('html=' + encodeURI(HTML_TEST_STRINGS))
.expect('Content-Type', 'application/pdf')
.expect(200)
resolve()
})
}
const tasks = []
for (let i=0; i<LAUNCH_HC_PAGES_NUM; i++) {
tasks.push(task())
}
await Promise.all(tasks)
})
it('GET /screenshot with url ' + TAREGT_URL, async () => {
await req.get('/screenshot?url=' + TAREGT_URL)
.expect('Content-Type', 'image/png')
.expect(200)
})
it('POST /screenshot html=' + HTML_TEST_STRINGS, async () => {
await req.post('/screenshot')
.send('html=' + encodeURI(HTML_TEST_STRINGS))
.expect('Content-Type', 'image/png')
.expect(200)
})
})
|
"""
Functional test
Deletion Epic
Storyboard is defined within the comments of the program itself
"""
import unittest
from flask import url_for
from biblib.tests.stubdata.stub_data import UserShop, LibraryShop
from biblib.tests.base import TestCaseDatabase, MockEmailService
class TestDeletionEpic(TestCaseDatabase):
"""
Base class used to test the Deletion Epic
"""
def test_deletion_epic(self):
"""
Carries out the epic 'Deletion', where a user wants to delete their
libraries that they have created
:return: no return
"""
# The librarian makes
# 1. two different libraries on her account
# 2. decides she wants to delete one
# 3. decides she wants to delete the next one too
# She then checks that they were deleted
# Load stub data 1
stub_user = UserShop()
stub_library_1 = LibraryShop()
stub_library_2 = LibraryShop()
# Makes the two libraries
url = url_for('userview')
response = self.client.post(
url,
data=stub_library_1.user_view_post_data_json,
headers=stub_user.headers
)
library_name_1 = response.json['name']
self.assertEqual(response.status_code, 200, response)
self.assertTrue('name' in response.json)
self.assertTrue(library_name_1 == stub_library_1.name)
# Second stub data
url = url_for('userview')
response = self.client.post(
url,
data=stub_library_2.user_view_post_data_json,
headers=stub_user.headers
)
library_name_2 = response.json['name']
self.assertEqual(response.status_code, 200, response)
self.assertTrue('name' in response.json)
self.assertTrue(library_name_2 == stub_library_2.name)
# Check the two libraries are not the same
self.assertNotEqual(library_name_1,
library_name_2,
'Name should be unique: {0} == {1}'
.format(library_name_1, library_name_2))
# Deletes the first library
url = url_for('userview')
with MockEmailService(stub_user, end_type='uid'):
response = self.client.get(
url,
headers=stub_user.headers
)
self.assertTrue(len(response.json['libraries']) == 2)
library_id_1 = response.json['libraries'][0]['id']
library_id_2 = response.json['libraries'][1]['id']
# Deletes the second library
url = url_for('documentview', library=library_id_2)
response = self.client.delete(
url,
headers=stub_user.headers
)
self.assertEqual(response.status_code, 200)
# Looks to check there are is only one library
url = url_for('userview')
with MockEmailService(stub_user, end_type='uid'):
response = self.client.get(
url,
headers=stub_user.headers
)
self.assertTrue(len(response.json['libraries']) == 1)
# Deletes the first library
url = url_for('documentview', library=library_id_1)
response = self.client.delete(
url,
headers=stub_user.headers
)
self.assertEqual(response.status_code, 200)
# Looks to check there are is only one libraries
url = url_for('userview')
with MockEmailService(stub_user, end_type='uid'):
response = self.client.get(
url,
headers=stub_user.headers
)
self.assertTrue(len(response.json['libraries']) == 0)
if __name__ == '__main__':
unittest.main(verbosity=2)
|
''' Test for inheritence '''
from __future__ import print_function
__revision__ = 1
# pylint: disable=too-few-public-methods
class AAAA(object):
''' class AAAA '''
def __init__(self):
pass
def method1(self):
''' method 1 '''
print(self)
def method2(self):
''' method 2 '''
print(self)
class BBBB(AAAA):
''' class BBBB '''
def __init__(self):
AAAA.__init__(self)
# should ignore docstring calling from class AAAA
def method1(self):
AAAA.method1(self)
class CCCC(BBBB):
''' class CCCC '''
def __init__(self):
BBBB.__init__(self)
# should ignore docstring since CCCC is inherited from BBBB which is
# inherited from AAAA containing method2
if __revision__:
def method2(self):
AAAA.method2(self)
else:
def method2(self):
AAAA.method1(self)
|
const express = require('express');
const app = express();
const cors = require('cors');
// const mongoose = require('./mongoose');
const bodyParser = require('body-parser');
const sessionHandler = require('./middlewares/sessionHandler');
const urlHandler = require('./middlewares/urlHandler');
const dbHandler = require('./middlewares/dbHandler');
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.use(cors())
// Routes
app.get('/session', sessionHandler.sessionGEThandler)
app.post('/session', sessionHandler.sessionPOSThandler)
app.get('/url', dbHandler.dbGEThandler)
app.post('/url', dbHandler.dbPOSThandler)
app.get('/db', urlHandler.urlGEThandler)
app.post('/db', urlHandler.urlPOSThandler)
const port = process.env.PORT || 5000
app.listen(port, console.log('Serving on port: ', port));
|
# Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""BERT model input pipelines."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
def decode_record(record, name_to_features):
"""Decodes a record to a TensorFlow example."""
example = tf.io.parse_single_example(record, name_to_features)
# tf.Example only supports tf.int64, but the TPU only supports tf.int32.
# So cast all int64 to int32.
for name in list(example.keys()):
t = example[name]
if t.dtype == tf.int64:
t = tf.cast(t, tf.int32)
example[name] = t
return example
def single_file_dataset(input_file, name_to_features):
"""Creates a single-file dataset to be passed for BERT custom training."""
# For training, we want a lot of parallel reading and shuffling.
# For eval, we want no shuffling and parallel reading doesn't matter.
d = tf.data.TFRecordDataset(input_file)
d = d.map(lambda record: decode_record(record, name_to_features))
# When `input_file` is a path to a single file or a list
# containing a single path, disable auto sharding so that
# same input file is sent to all workers.
if isinstance(input_file, str) or len(input_file) == 1:
options = tf.data.Options()
options.experimental_distribute.auto_shard_policy = (
tf.data.experimental.AutoShardPolicy.OFF)
d = d.with_options(options)
return d
def create_pretrain_dataset(input_patterns,
seq_length,
max_predictions_per_seq,
batch_size,
is_training=True,
input_pipeline_context=None,
use_next_sentence_label=True):
"""Creates input dataset from (tf)records files for pretraining."""
name_to_features = {
'input_ids':
tf.io.FixedLenFeature([seq_length], tf.int64),
'input_mask':
tf.io.FixedLenFeature([seq_length], tf.int64),
'segment_ids':
tf.io.FixedLenFeature([seq_length], tf.int64),
'masked_lm_positions':
tf.io.FixedLenFeature([max_predictions_per_seq], tf.int64),
'masked_lm_ids':
tf.io.FixedLenFeature([max_predictions_per_seq], tf.int64),
'masked_lm_weights':
tf.io.FixedLenFeature([max_predictions_per_seq], tf.float32),
}
if use_next_sentence_label:
name_to_features['next_sentence_labels'] = tf.io.FixedLenFeature([1],
tf.int64)
for input_pattern in input_patterns:
if not tf.io.gfile.glob(input_pattern):
raise ValueError('%s does not match any files.' % input_pattern)
dataset = tf.data.Dataset.list_files(input_patterns, shuffle=is_training)
if input_pipeline_context and input_pipeline_context.num_input_pipelines > 1:
dataset = dataset.shard(input_pipeline_context.num_input_pipelines,
input_pipeline_context.input_pipeline_id)
if is_training:
dataset = dataset.repeat()
# We set shuffle buffer to exactly match total number of
# training files to ensure that training data is well shuffled.
input_files = []
for input_pattern in input_patterns:
input_files.extend(tf.io.gfile.glob(input_pattern))
dataset = dataset.shuffle(len(input_files))
# In parallel, create tf record dataset for each train files.
# cycle_length = 8 means that up to 8 files will be read and deserialized in
# parallel. You may want to increase this number if you have a large number of
# CPU cores.
dataset = dataset.interleave(
tf.data.TFRecordDataset, cycle_length=8,
num_parallel_calls=tf.data.experimental.AUTOTUNE)
decode_fn = lambda record: decode_record(record, name_to_features)
dataset = dataset.map(
decode_fn, num_parallel_calls=tf.data.experimental.AUTOTUNE)
def _select_data_from_record(record):
"""Filter out features to use for pretraining."""
x = {
'input_word_ids': record['input_ids'],
'input_mask': record['input_mask'],
'input_type_ids': record['segment_ids'],
'masked_lm_positions': record['masked_lm_positions'],
'masked_lm_ids': record['masked_lm_ids'],
'masked_lm_weights': record['masked_lm_weights'],
}
if use_next_sentence_label:
x['next_sentence_labels'] = record['next_sentence_labels']
y = record['masked_lm_weights']
return (x, y)
dataset = dataset.map(
_select_data_from_record,
num_parallel_calls=tf.data.experimental.AUTOTUNE)
if is_training:
dataset = dataset.shuffle(100)
dataset = dataset.batch(batch_size, drop_remainder=is_training)
dataset = dataset.prefetch(1024)
return dataset
def create_classifier_dataset(file_path,
seq_length,
batch_size,
is_training=True,
input_pipeline_context=None):
"""Creates input dataset from (tf)records files for train/eval."""
name_to_features = {
'input_ids': tf.io.FixedLenFeature([seq_length], tf.int64),
'input_mask': tf.io.FixedLenFeature([seq_length], tf.int64),
'segment_ids': tf.io.FixedLenFeature([seq_length], tf.int64),
'label_ids': tf.io.FixedLenFeature([], tf.int64),
'is_real_example': tf.io.FixedLenFeature([], tf.int64),
}
dataset = single_file_dataset(file_path, name_to_features)
# The dataset is always sharded by number of hosts.
# num_input_pipelines is the number of hosts rather than number of cores.
if input_pipeline_context and input_pipeline_context.num_input_pipelines > 1:
dataset = dataset.shard(input_pipeline_context.num_input_pipelines,
input_pipeline_context.input_pipeline_id)
def _select_data_from_record(record):
x = {
'input_word_ids': record['input_ids'],
'input_mask': record['input_mask'],
'input_type_ids': record['segment_ids']
}
y = record['label_ids']
return (x, y)
dataset = dataset.map(_select_data_from_record)
if is_training:
dataset = dataset.shuffle(100)
dataset = dataset.repeat()
dataset = dataset.batch(batch_size, drop_remainder=is_training)
dataset = dataset.prefetch(1024)
return dataset
def create_squad_dataset(file_path,
seq_length,
batch_size,
is_training=True,
input_pipeline_context=None):
"""Creates input dataset from (tf)records files for train/eval."""
name_to_features = {
'input_ids': tf.io.FixedLenFeature([seq_length], tf.int64),
'input_mask': tf.io.FixedLenFeature([seq_length], tf.int64),
'segment_ids': tf.io.FixedLenFeature([seq_length], tf.int64),
}
if is_training:
name_to_features['start_positions'] = tf.io.FixedLenFeature([], tf.int64)
name_to_features['end_positions'] = tf.io.FixedLenFeature([], tf.int64)
else:
name_to_features['unique_ids'] = tf.io.FixedLenFeature([], tf.int64)
dataset = single_file_dataset(file_path, name_to_features)
# The dataset is always sharded by number of hosts.
# num_input_pipelines is the number of hosts rather than number of cores.
if input_pipeline_context and input_pipeline_context.num_input_pipelines > 1:
dataset = dataset.shard(input_pipeline_context.num_input_pipelines,
input_pipeline_context.input_pipeline_id)
def _select_data_from_record(record):
"""Dispatches record to features and labels."""
x, y = {}, {}
for name, tensor in record.items():
if name in ('start_positions', 'end_positions'):
y[name] = tensor
elif name == 'input_ids':
x['input_word_ids'] = tensor
elif name == 'segment_ids':
x['input_type_ids'] = tensor
else:
x[name] = tensor
return (x, y)
dataset = dataset.map(_select_data_from_record)
if is_training:
dataset = dataset.shuffle(100)
dataset = dataset.repeat()
dataset = dataset.batch(batch_size, drop_remainder=True)
dataset = dataset.prefetch(1024)
return dataset
|
import React, { Component } from 'react';
import fs from 'fs';
import moment from 'moment'; // day-time
import { exec } from 'child_process';
// import { Link } from 'react-router'; // not currently needed
import styles from './Home.css';
// removed flow for now, will add later w/ type annotations etc.
export default class Home extends Component {
constructor(props) {
super(props);
this.state = {
title: '',
tags: '',
question: '',
solution: ''
};
this.handleChangeTitle = this.handleChangeTitle.bind(this);
this.handleChangeTags = this.handleChangeTags.bind(this);
this.handleChangeQuestion = this.handleChangeQuestion.bind(this);
this.handleChangeSolution = this.handleChangeSolution.bind(this);
this.emptyDialogs = this.emptyDialogs.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
// this.enableTab = this.enableTab.bind(this);
}
handleChangeTitle(event) {
this.setState({ title: event.target.value });
}
handleChangeTags(event) {
this.setState({ tags: event.target.value });
}
handleChangeQuestion(event) {
this.setState({ question: event.target.value });
}
handleChangeSolution(event) {
this.setState({ solution: event.target.value });
}
emptyDialogs() {
this.setState({ title: '' });
this.setState({ tags: '' });
}
/*
enableTab(e) {
add onKeyDown={this.enableTab} to solution's textarea
need to figure this out:
possible help:
https://css-tricks.com/snippets/javascript/support-tabs-in-textareas/
or just go full steam ahead and embed a code editor (not likely!)
}
*/
handleSubmit(event) {
// generating file name and path
const currDate = moment().format('YYYY-MM-DD');
const currTime = moment().format('hh:mm:ss');
const dirToWrite = '/Users/AhsanAzim/Developer/Algos/_posts';
const titleDashed = this.state.title.replace(/ /g, '-');
const fName = `${currDate}-${titleDashed}.md`;
const fNameAndPath = `${dirToWrite}/${fName}`;
// generating text to insert
const header = `---\nlayout: post\ntitle: ${this.state.title}\ndate: ${currDate} ${currTime}\ncategories: ${this.state.tags}\n---\n`;
const body = `**Question:**\n${this.state.question}\n\n\n**Solution:** \n{% highlight python %}\n${this.state.solution}\n{% endhighlight %}`;
const content = `${header}${body}`;
// insert text into a markdown file in _posts dir
fs.writeFile(fNameAndPath, content, (err) => {
if (err) {
alert(`An error ocurred creating the file ${err.message}`);
}
// open file in atom editor
// note full path necessary (ref: https://discuss.atom.io/t/how-to-execute-node-js-child-process-from-package/4880/12)
exec(`/usr/local/bin/atom ${fNameAndPath}`, (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
alert(`exec error: ${error}`);
return;
}
this.emptyDialogs();
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
});
alert('The file has been succesfully saved');
});
event.preventDefault();
}
render() {
return (
<div className={styles.container}>
<div className={styles.formContainer}>
{/* change back to this when Question/Solution added:
<div className={`${styles.formItem} ${styles.oneLiners}`}>
both tags and title will be in one formItem bunched together
*/}
<div className={styles.formItem}>
<input type="text" value={this.state.title} onChange={this.handleChangeTitle} id={styles.title} placeholder={'title'} />
</div>
<div className={styles.formItem}>
<input type="text" value={this.state.tags} onChange={this.handleChangeTags} id={styles.tags} placeholder={'tags'} />
</div>
{/* <div className={`${styles.formItem} ${styles.questionContainer}`}>
<textarea type="text" value={this.state.question} onChange={this.handleChangeQuestion}
id={styles.question} placeholder={'question'} />
</div>
<div className={`${styles.formItem} ${styles.biggerContainer}`}>
<textarea type="text" value={this.state.solution} onChange={this.handleChangeSolution}
id={styles.solution} placeholder={'solution'} />
</div>*/}
<div className={styles.formItem}>
<button onClick={this.handleSubmit}>create template</button>
</div>
</div>
</div>
);
}
}
|
//
// AppDelegate.h
// Demo02_GitServer
//
// Created by jutao on 15/10/8.
// Copyright (c) 2015年 tarena. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
|
# Generated by Django 3.0.4 on 2020-04-18 17:10
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('comps', '0007_auto_20200418_1705'),
]
operations = [
migrations.RemoveField(
model_name='heatresult',
name='heat',
),
]
|
import React from 'react'
import SuccessIcon from "../../img/success.png";
const OrderConfirmation = () => {
return (
<>
<center>
<img alt="" className="img-circle" src={SuccessIcon} width="50px" height="50px" />
<br /><br />
<h4>Your order has been successfully placed!</h4>
<br /><br />
</center>
</>
)
}
export default OrderConfirmation
|
/** PURE_IMPORTS_START .._.._Observable,.._.._operator_withLatestFrom PURE_IMPORTS_END */
import { Observable } from '../../Observable'
import { withLatestFrom } from '../../operator/withLatestFrom'
Observable.prototype.withLatestFrom = withLatestFrom
// # sourceMappingURL=withLatestFrom.js.map
|
import mask from 'json-mask';
import { Module } from '../../lib/di';
import DataFetcher from '../../lib/DataFetcher';
import createSimpleReducer from '../../lib/createSimpleReducer';
import callControlError from '../ActiveCallControl/callControlError';
import actionTypes from './actionTypes';
import proxify from '../../lib/proxy/proxify';
import {
updateJoinBeforeHost,
getConferenceInfo,
formatDialInNumbers,
} from './conferenceHelper';
const DEFAULT_MASK =
'phoneNumber,hostCode,participantCode,phoneNumbers(country(callingCode,id,isoCode,name),phoneNumber,location),allowJoinBeforeHost';
/**
* @class
* @description Conference managing module
*/
@Module({
deps: [
'Alert',
'Client',
'Storage',
'RegionSettings',
'RolesAndPermissions',
'ExtensionInfo',
'Locale',
{ dep: 'AvailabilityMonitor', optional: true },
{ dep: 'ConferenceOptions', optional: true },
],
})
export default class Conference extends DataFetcher {
/**
* @constructor
* @param {Object} params - params object
* @param {RegionSettings} params.regionSettings - regionSettings module instance
* @param {Client} params.client - client module instance
*/
constructor({
alert,
client,
regionSettings,
storage,
rolesAndPermissions,
availabilityMonitor,
showSaveAsDefault = false,
extensionInfo,
locale,
...options
}) {
super({
client,
fetchFunction: async () =>
mask(await getConferenceInfo(client), DEFAULT_MASK),
storage,
...options,
});
this._alert = alert;
this._dialInNumberStorageKey = 'conferenceDialInNumber';
this._additionalNumbersStorageKey = 'conferenceAdditionalNumbers';
this._savedStorageKey = 'conferenceSaveCurrentSettings';
this._regionSettings = regionSettings;
this._rolesAndPermissions = rolesAndPermissions;
this._availabilityMonitor = availabilityMonitor;
this._lastCountryCode = null;
this._showSaveAsDefault = showSaveAsDefault;
this._extensionInfo = extensionInfo;
this._locale = locale;
this._storage.registerReducer({
key: this._dialInNumberStorageKey,
reducer: createSimpleReducer(
this.actionTypes.updateDialInNumber,
'dialInNumber',
),
});
this._storage.registerReducer({
key: this._additionalNumbersStorageKey,
reducer: createSimpleReducer(
this.actionTypes.updateAdditionalNumbers,
'additionalNumbers',
),
});
this._storage.registerReducer({
key: this._savedStorageKey,
reducer: createSimpleReducer(
this.actionTypes.updateSaveCurrentSettings,
'_saved',
),
});
}
get _name() {
return 'conference';
}
get _actionTypes() {
return actionTypes;
}
async _onStateChange() {
super._onStateChange();
if (
!this.data ||
!this._regionSettings.ready ||
this._lastCountryCode === this._regionSettings.countryCode
) {
return;
}
this._lastCountryCode = this._regionSettings.countryCode;
const matchedPhoneNumber = this.data.phoneNumbers.find(
(e) => e.country.isoCode === this._lastCountryCode,
);
if (
matchedPhoneNumber &&
matchedPhoneNumber.phoneNumber !== this.dialInNumber
) {
this.updateDialInNumber(matchedPhoneNumber.phoneNumber);
}
}
_shouldInit() {
return (
super._shouldInit() &&
this._rolesAndPermissions.ready &&
this._alert.ready &&
(!this._availabilityMonitor || this._availabilityMonitor.ready) &&
this._extensionInfo.ready &&
this._locale.ready &&
this._regionSettings.ready
);
}
@proxify
async updateEnableJoinBeforeHost(allowJoinBeforeHost) {
try {
const data = await updateJoinBeforeHost(
this._client,
allowJoinBeforeHost,
);
this._store.dispatch({ type: this.actionTypes.fetchSuccess, data });
return data;
} catch (error) {
if (
!this._availabilityMonitor ||
!(await this._availabilityMonitor.checkIfHAError(error))
) {
this._alert.warning({ message: callControlError.generalError });
}
return null;
}
}
@proxify
updateDialInNumber(dialInNumber) {
this._store.dispatch({
type: this.actionTypes.updateDialInNumber,
dialInNumber,
});
}
@proxify
updateAdditionalNumbers(additionalNumbers) {
this._store.dispatch({
type: this.actionTypes.updateAdditionalNumbers,
additionalNumbers,
});
}
@proxify
updateSaveCurrentSettings(_saved) {
this._store.dispatch({
type: this.actionTypes.updateSaveCurrentSettings,
_saved,
});
}
// for track invite with text
@proxify
onInviteWithText() {
this.store.dispatch({
type: this.actionTypes.inviteWithText,
});
}
// for track join as host
@proxify
onJoinAsHost() {
this.store.dispatch({
type: this.actionTypes.joinAsHost,
});
}
@proxify
getDefaultSettings(countryNames) {
if (!countryNames || typeof countryNames !== 'object') {
console.log('please privide the countryNames I18n object');
return;
}
const dialInNumbers = formatDialInNumbers({
currentLocale: this._locale.currentLocale,
areaCode: this._regionSettings.areaCode,
countryCode: this._regionSettings.countryCode,
phoneNumbers: this.data.phoneNumbers,
countryNames,
});
return {
dialInNumbers,
phoneNumber: this.data.phoneNumber,
dialInNumber: this.dialInNumber || '',
_saved: this._saved || false,
additionalNumbers: this.additionalNumbers,
allowJoinBeforeHost: this.data.allowJoinBeforeHost,
currentLocale: this._locale.currentLocale,
participantCode: this.data.participantCode,
extensionName: this._extensionInfo.info.name || '',
};
}
get additionalNumbers() {
return this._storage.getItem(this._additionalNumbersStorageKey) || [];
}
get _saved() {
return this._storage.getItem(this._savedStorageKey) || false;
}
get dialInNumber() {
return (
this._storage.getItem(this._dialInNumberStorageKey) ||
(this.data && this.data.phoneNumber)
);
}
get _hasPermission() {
return !!this._rolesAndPermissions.permissions.OrganizeConference;
}
get showSaveAsDefault() {
return this._showSaveAsDefault;
}
}
|
// Copyright (c) 2003-2020 Xsens Technologies B.V. or subsidiaries worldwide.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions, and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions, and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the names of the copyright holders nor the names of their contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
// OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY OR
// TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.THE LAWS OF THE NETHERLANDS
// SHALL BE EXCLUSIVELY APPLICABLE AND ANY DISPUTES SHALL BE FINALLY SETTLED UNDER THE RULES
// OF ARBITRATION OF THE INTERNATIONAL CHAMBER OF COMMERCE IN THE HAGUE BY ONE OR MORE
// ARBITRATORS APPOINTED IN ACCORDANCE WITH SAID RULES.
//
// Copyright (c) 2003-2020 Xsens Technologies B.V. or subsidiaries worldwide.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions, and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions, and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the names of the copyright holders nor the names of their contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
// OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY OR
// TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.THE LAWS OF THE NETHERLANDS
// SHALL BE EXCLUSIVELY APPLICABLE AND ANY DISPUTES SHALL BE FINALLY SETTLED UNDER THE RULES
// OF ARBITRATION OF THE INTERNATIONAL CHAMBER OF COMMERCE IN THE HAGUE BY ONE OR MORE
// ARBITRATORS APPOINTED IN ACCORDANCE WITH SAID RULES.
//
#ifndef USBINTERFACE_H
#define USBINTERFACE_H
#include <xstypes/xstime.h>
#include <stdlib.h>
#include <stdio.h>
#ifdef _WIN32
# include <windows.h>
//# include <sys/types.h>
#else
# include <termios.h>
// these are not required by level 1, but to keep the higher levels platform-independent they are put here
# include <string.h>
# include <stddef.h>
#endif
#include "streaminterface.h"
#include <stdio.h>
struct XsPortInfo;
class UsbInterfacePrivate;
class UsbInterface : public StreamInterface {
UsbInterfacePrivate *d;
public:
UsbInterface();
~UsbInterface();
XsResultValue open(const XsPortInfo &portInfo, XsFilePos readBufSize = 0, XsFilePos writeBufSize = 0, PortOptions = PO_XsensDefaults) override;
XsResultValue close(void);
XsResultValue closeUsb(void);
XsResultValue flushData (void);
bool isOpen (void) const;
uint8_t usbBus() const;
uint8_t usbAddress() const;
XsResultValue getLastResult(void) const;
XsResultValue setTimeout (uint32_t ms);
uint32_t getTimeout (void) const;
void setRawIo(bool enable);
bool getRawIo(void);
XsResultValue writeData(const XsByteArray& data, XsFilePos* written = NULL) override;
XsResultValue readData(XsFilePos maxLength, XsByteArray& data) override;
using IoInterface::waitForData;
XsResultValue writeData(XsFilePos length, const void *data, XsFilePos* written = NULL);
XsResultValue readData(XsFilePos maxLength, void *data, XsFilePos* length = NULL);
XsResultValue waitForData(XsFilePos maxLength, void *data, XsFilePos* length = NULL);
void getPortName(XsString& portname) const;
XSENS_DISABLE_COPY(UsbInterface);
};
#endif
|
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Cycle=f()}})(function(){var define,module,exports;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){var process=module.exports={};var queue=[];var draining=false;var currentQueue;var queueIndex=-1;function cleanUpNextTick(){draining=false;if(currentQueue.length){queue=currentQueue.concat(queue)}else{queueIndex=-1}if(queue.length){drainQueue()}}function drainQueue(){if(draining){return}var timeout=setTimeout(cleanUpNextTick);draining=true;var len=queue.length;while(len){currentQueue=queue;queue=[];while(++queueIndex<len){currentQueue[queueIndex].run()}queueIndex=-1;len=queue.length}currentQueue=null;draining=false;clearTimeout(timeout)}process.nextTick=function(fun){var args=new Array(arguments.length-1);if(arguments.length>1){for(var i=1;i<arguments.length;i++){args[i-1]=arguments[i]}}queue.push(new Item(fun,args));if(queue.length===1&&!draining){setTimeout(drainQueue,0)}};function Item(fun,array){this.fun=fun;this.array=array}Item.prototype.run=function(){this.fun.apply(null,this.array)};process.title="browser";process.browser=true;process.env={};process.argv=[];process.version="";process.versions={};function noop(){}process.on=noop;process.addListener=noop;process.once=noop;process.off=noop;process.removeListener=noop;process.removeAllListeners=noop;process.emit=noop;process.binding=function(name){throw new Error("process.binding is not supported")};process.cwd=function(){return"/"};process.chdir=function(dir){throw new Error("process.chdir is not supported")};process.umask=function(){return 0}},{}],2:[function(require,module,exports){(function(process,global){(function(undefined){var objectTypes={"function":true,object:true};var freeExports=objectTypes[typeof exports]&&exports&&!exports.nodeType&&exports,freeSelf=objectTypes[typeof self]&&self.Object&&self,freeWindow=objectTypes[typeof window]&&window&&window.Object&&window,freeModule=objectTypes[typeof module]&&module&&!module.nodeType&&module,moduleExports=freeModule&&freeModule.exports===freeExports&&freeExports,freeGlobal=freeExports&&freeModule&&typeof global=="object"&&global&&global.Object&&global;var root=root=freeGlobal||freeWindow!==(this&&this.window)&&freeWindow||freeSelf||this;var Rx={internals:{},config:{Promise:root.Promise},helpers:{}};var noop=Rx.helpers.noop=function(){},identity=Rx.helpers.identity=function(x){return x},defaultNow=Rx.helpers.defaultNow=Date.now,defaultComparer=Rx.helpers.defaultComparer=function(x,y){return isEqual(x,y)},defaultSubComparer=Rx.helpers.defaultSubComparer=function(x,y){return x>y?1:x<y?-1:0},defaultKeySerializer=Rx.helpers.defaultKeySerializer=function(x){return x.toString()},defaultError=Rx.helpers.defaultError=function(err){throw err},isPromise=Rx.helpers.isPromise=function(p){return!!p&&typeof p.subscribe!=="function"&&typeof p.then==="function"},isFunction=Rx.helpers.isFunction=function(){var isFn=function(value){return typeof value=="function"||false};if(isFn(/x/)){isFn=function(value){return typeof value=="function"&&toString.call(value)=="[object Function]"}}return isFn}();function cloneArray(arr){for(var a=[],i=0,len=arr.length;i<len;i++){a.push(arr[i])}return a}var errorObj={e:{}};var tryCatchTarget;function tryCatcher(){try{return tryCatchTarget.apply(this,arguments)}catch(e){errorObj.e=e;return errorObj}}function tryCatch(fn){if(!isFunction(fn)){throw new TypeError("fn must be a function")}tryCatchTarget=fn;return tryCatcher}function thrower(e){throw e}Rx.config.longStackSupport=false;var hasStacks=false,stacks=tryCatch(function(){throw new Error})();hasStacks=!!stacks.e&&!!stacks.e.stack;var rStartingLine=captureLine(),rFileName;var STACK_JUMP_SEPARATOR="From previous event:";function makeStackTraceLong(error,observable){if(hasStacks&&observable.stack&&typeof error==="object"&&error!==null&&error.stack&&error.stack.indexOf(STACK_JUMP_SEPARATOR)===-1){var stacks=[];for(var o=observable;!!o;o=o.source){if(o.stack){stacks.unshift(o.stack)}}stacks.unshift(error.stack);var concatedStacks=stacks.join("\n"+STACK_JUMP_SEPARATOR+"\n");error.stack=filterStackString(concatedStacks)}}function filterStackString(stackString){var lines=stackString.split("\n"),desiredLines=[];for(var i=0,len=lines.length;i<len;i++){var line=lines[i];if(!isInternalFrame(line)&&!isNodeFrame(line)&&line){desiredLines.push(line)}}return desiredLines.join("\n")}function isInternalFrame(stackLine){var fileNameAndLineNumber=getFileNameAndLineNumber(stackLine);if(!fileNameAndLineNumber){return false}var fileName=fileNameAndLineNumber[0],lineNumber=fileNameAndLineNumber[1];return fileName===rFileName&&lineNumber>=rStartingLine&&lineNumber<=rEndingLine}function isNodeFrame(stackLine){return stackLine.indexOf("(module.js:")!==-1||stackLine.indexOf("(node.js:")!==-1}function captureLine(){if(!hasStacks){return}try{throw new Error}catch(e){var lines=e.stack.split("\n");var firstLine=lines[0].indexOf("@")>0?lines[1]:lines[2];var fileNameAndLineNumber=getFileNameAndLineNumber(firstLine);if(!fileNameAndLineNumber){return}rFileName=fileNameAndLineNumber[0];return fileNameAndLineNumber[1]}}function getFileNameAndLineNumber(stackLine){var attempt1=/at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine);if(attempt1){return[attempt1[1],Number(attempt1[2])]}var attempt2=/at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine);if(attempt2){return[attempt2[1],Number(attempt2[2])]}var attempt3=/.*@(.+):(\d+)$/.exec(stackLine);if(attempt3){return[attempt3[1],Number(attempt3[2])]}}var EmptyError=Rx.EmptyError=function(){this.message="Sequence contains no elements.";this.name="EmptyError";Error.call(this)};EmptyError.prototype=Error.prototype;var ObjectDisposedError=Rx.ObjectDisposedError=function(){this.message="Object has been disposed";this.name="ObjectDisposedError";Error.call(this)};ObjectDisposedError.prototype=Error.prototype;var ArgumentOutOfRangeError=Rx.ArgumentOutOfRangeError=function(){this.message="Argument out of range";this.name="ArgumentOutOfRangeError";Error.call(this)};ArgumentOutOfRangeError.prototype=Error.prototype;var NotSupportedError=Rx.NotSupportedError=function(message){this.message=message||"This operation is not supported";this.name="NotSupportedError";Error.call(this)};NotSupportedError.prototype=Error.prototype;var NotImplementedError=Rx.NotImplementedError=function(message){this.message=message||"This operation is not implemented";this.name="NotImplementedError";Error.call(this)};NotImplementedError.prototype=Error.prototype;var notImplemented=Rx.helpers.notImplemented=function(){throw new NotImplementedError};var notSupported=Rx.helpers.notSupported=function(){throw new NotSupportedError};var $iterator$=typeof Symbol==="function"&&Symbol.iterator||"_es6shim_iterator_";if(root.Set&&typeof(new root.Set)["@@iterator"]==="function"){$iterator$="@@iterator"}var doneEnumerator=Rx.doneEnumerator={done:true,value:undefined};var isIterable=Rx.helpers.isIterable=function(o){return o[$iterator$]!==undefined};var isArrayLike=Rx.helpers.isArrayLike=function(o){return o&&o.length!==undefined};Rx.helpers.iterator=$iterator$;var bindCallback=Rx.internals.bindCallback=function(func,thisArg,argCount){if(typeof thisArg==="undefined"){return func}switch(argCount){case 0:return function(){return func.call(thisArg)};case 1:return function(arg){return func.call(thisArg,arg)};case 2:return function(value,index){return func.call(thisArg,value,index)};case 3:return function(value,index,collection){return func.call(thisArg,value,index,collection)}}return function(){return func.apply(thisArg,arguments)}};var dontEnums=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],dontEnumsLength=dontEnums.length;var argsClass="[object Arguments]",arrayClass="[object Array]",boolClass="[object Boolean]",dateClass="[object Date]",errorClass="[object Error]",funcClass="[object Function]",numberClass="[object Number]",objectClass="[object Object]",regexpClass="[object RegExp]",stringClass="[object String]";var toString=Object.prototype.toString,hasOwnProperty=Object.prototype.hasOwnProperty,supportsArgsClass=toString.call(arguments)==argsClass,supportNodeClass,errorProto=Error.prototype,objectProto=Object.prototype,stringProto=String.prototype,propertyIsEnumerable=objectProto.propertyIsEnumerable;try{supportNodeClass=!(toString.call(document)==objectClass&&!({toString:0}+""))}catch(e){supportNodeClass=true}var nonEnumProps={};nonEnumProps[arrayClass]=nonEnumProps[dateClass]=nonEnumProps[numberClass]={constructor:true,toLocaleString:true,toString:true,valueOf:true};nonEnumProps[boolClass]=nonEnumProps[stringClass]={constructor:true,toString:true,valueOf:true};nonEnumProps[errorClass]=nonEnumProps[funcClass]=nonEnumProps[regexpClass]={constructor:true,toString:true};nonEnumProps[objectClass]={constructor:true};var support={};(function(){var ctor=function(){this.x=1},props=[];ctor.prototype={valueOf:1,y:1};for(var key in new ctor){props.push(key)}for(key in arguments){}support.enumErrorProps=propertyIsEnumerable.call(errorProto,"message")||propertyIsEnumerable.call(errorProto,"name");support.enumPrototypes=propertyIsEnumerable.call(ctor,"prototype");support.nonEnumArgs=key!=0;support.nonEnumShadows=!/valueOf/.test(props)})(1);var isObject=Rx.internals.isObject=function(value){var type=typeof value;return value&&(type=="function"||type=="object")||false};function keysIn(object){var result=[];if(!isObject(object)){return result}if(support.nonEnumArgs&&object.length&&isArguments(object)){object=slice.call(object)}var skipProto=support.enumPrototypes&&typeof object=="function",skipErrorProps=support.enumErrorProps&&(object===errorProto||object instanceof Error);for(var key in object){if(!(skipProto&&key=="prototype")&&!(skipErrorProps&&(key=="message"||key=="name"))){result.push(key)}}if(support.nonEnumShadows&&object!==objectProto){var ctor=object.constructor,index=-1,length=dontEnumsLength;if(object===(ctor&&ctor.prototype)){var className=object===stringProto?stringClass:object===errorProto?errorClass:toString.call(object),nonEnum=nonEnumProps[className]}while(++index<length){key=dontEnums[index];if(!(nonEnum&&nonEnum[key])&&hasOwnProperty.call(object,key)){result.push(key)}}}return result}function internalFor(object,callback,keysFunc){var index=-1,props=keysFunc(object),length=props.length;while(++index<length){var key=props[index];if(callback(object[key],key,object)===false){break}}return object}function internalForIn(object,callback){return internalFor(object,callback,keysIn)}function isNode(value){return typeof value.toString!="function"&&typeof(value+"")=="string"}var isArguments=function(value){return value&&typeof value=="object"?toString.call(value)==argsClass:false};if(!supportsArgsClass){isArguments=function(value){return value&&typeof value=="object"?hasOwnProperty.call(value,"callee"):false}}var isEqual=Rx.internals.isEqual=function(x,y){return deepEquals(x,y,[],[])};function deepEquals(a,b,stackA,stackB){if(a===b){return a!==0||1/a==1/b}var type=typeof a,otherType=typeof b;if(a===a&&(a==null||b==null||type!="function"&&type!="object"&&otherType!="function"&&otherType!="object")){return false}var className=toString.call(a),otherClass=toString.call(b);if(className==argsClass){className=objectClass}if(otherClass==argsClass){otherClass=objectClass}if(className!=otherClass){return false}switch(className){case boolClass:case dateClass:return+a==+b;case numberClass:return a!=+a?b!=+b:a==0?1/a==1/b:a==+b;case regexpClass:case stringClass:return a==String(b)}var isArr=className==arrayClass;if(!isArr){if(className!=objectClass||!support.nodeClass&&(isNode(a)||isNode(b))){return false}var ctorA=!support.argsObject&&isArguments(a)?Object:a.constructor,ctorB=!support.argsObject&&isArguments(b)?Object:b.constructor;if(ctorA!=ctorB&&!(hasOwnProperty.call(a,"constructor")&&hasOwnProperty.call(b,"constructor"))&&!(isFunction(ctorA)&&ctorA instanceof ctorA&&isFunction(ctorB)&&ctorB instanceof ctorB)&&("constructor"in a&&"constructor"in b)){return false}}var initedStack=!stackA;stackA||(stackA=[]);stackB||(stackB=[]);var length=stackA.length;while(length--){if(stackA[length]==a){return stackB[length]==b}}var size=0;var result=true;stackA.push(a);stackB.push(b);if(isArr){length=a.length;size=b.length;result=size==length;if(result){while(size--){var index=length,value=b[size];if(!(result=deepEquals(a[size],value,stackA,stackB))){break}}}}else{internalForIn(b,function(value,key,b){if(hasOwnProperty.call(b,key)){size++;return result=hasOwnProperty.call(a,key)&&deepEquals(a[key],value,stackA,stackB)}});if(result){internalForIn(a,function(value,key,a){if(hasOwnProperty.call(a,key)){return result=--size>-1}})}}stackA.pop();stackB.pop();return result}var hasProp={}.hasOwnProperty,slice=Array.prototype.slice;var inherits=Rx.internals.inherits=function(child,parent){function __(){this.constructor=child}__.prototype=parent.prototype;child.prototype=new __};var addProperties=Rx.internals.addProperties=function(obj){for(var sources=[],i=1,len=arguments.length;i<len;i++){sources.push(arguments[i])}for(var idx=0,ln=sources.length;idx<ln;idx++){var source=sources[idx];for(var prop in source){obj[prop]=source[prop]}}};var addRef=Rx.internals.addRef=function(xs,r){return new AnonymousObservable(function(observer){return new CompositeDisposable(r.getDisposable(),xs.subscribe(observer))})};function arrayInitialize(count,factory){var a=new Array(count);for(var i=0;i<count;i++){a[i]=factory()}return a}function IndexedItem(id,value){this.id=id;this.value=value}IndexedItem.prototype.compareTo=function(other){var c=this.value.compareTo(other.value);c===0&&(c=this.id-other.id);return c};var PriorityQueue=Rx.internals.PriorityQueue=function(capacity){this.items=new Array(capacity);this.length=0};var priorityProto=PriorityQueue.prototype;priorityProto.isHigherPriority=function(left,right){return this.items[left].compareTo(this.items[right])<0};priorityProto.percolate=function(index){if(index>=this.length||index<0){return}var parent=index-1>>1;if(parent<0||parent===index){return}if(this.isHigherPriority(index,parent)){var temp=this.items[index];this.items[index]=this.items[parent];this.items[parent]=temp;this.percolate(parent)}};priorityProto.heapify=function(index){+index||(index=0);if(index>=this.length||index<0){return}var left=2*index+1,right=2*index+2,first=index;if(left<this.length&&this.isHigherPriority(left,first)){first=left}if(right<this.length&&this.isHigherPriority(right,first)){first=right}if(first!==index){var temp=this.items[index];this.items[index]=this.items[first];this.items[first]=temp;this.heapify(first)}};priorityProto.peek=function(){return this.items[0].value};priorityProto.removeAt=function(index){this.items[index]=this.items[--this.length];this.items[this.length]=undefined;this.heapify()};priorityProto.dequeue=function(){var result=this.peek();this.removeAt(0);return result};priorityProto.enqueue=function(item){var index=this.length++;this.items[index]=new IndexedItem(PriorityQueue.count++,item);this.percolate(index)};priorityProto.remove=function(item){for(var i=0;i<this.length;i++){if(this.items[i].value===item){this.removeAt(i);return true}}return false};PriorityQueue.count=0;var CompositeDisposable=Rx.CompositeDisposable=function(){var args=[],i,len;if(Array.isArray(arguments[0])){args=arguments[0];len=args.length}else{len=arguments.length;args=new Array(len);for(i=0;i<len;i++){args[i]=arguments[i]}}for(i=0;i<len;i++){if(!isDisposable(args[i])){throw new TypeError("Not a disposable")}}this.disposables=args;this.isDisposed=false;this.length=args.length};var CompositeDisposablePrototype=CompositeDisposable.prototype;CompositeDisposablePrototype.add=function(item){if(this.isDisposed){item.dispose()}else{this.disposables.push(item);this.length++}};CompositeDisposablePrototype.remove=function(item){var shouldDispose=false;if(!this.isDisposed){var idx=this.disposables.indexOf(item);if(idx!==-1){shouldDispose=true;this.disposables.splice(idx,1);this.length--;item.dispose()}}return shouldDispose};CompositeDisposablePrototype.dispose=function(){if(!this.isDisposed){this.isDisposed=true;var len=this.disposables.length,currentDisposables=new Array(len);for(var i=0;i<len;i++){currentDisposables[i]=this.disposables[i]}this.disposables=[];this.length=0;for(i=0;i<len;i++){currentDisposables[i].dispose()}}};var Disposable=Rx.Disposable=function(action){this.isDisposed=false;this.action=action||noop};Disposable.prototype.dispose=function(){if(!this.isDisposed){this.action();this.isDisposed=true}};var disposableCreate=Disposable.create=function(action){return new Disposable(action)};var disposableEmpty=Disposable.empty={dispose:noop};var isDisposable=Disposable.isDisposable=function(d){return d&&isFunction(d.dispose)};var checkDisposed=Disposable.checkDisposed=function(disposable){if(disposable.isDisposed){throw new ObjectDisposedError}};var SingleAssignmentDisposable=Rx.SingleAssignmentDisposable=function(){this.isDisposed=false;this.current=null};SingleAssignmentDisposable.prototype.getDisposable=function(){return this.current};SingleAssignmentDisposable.prototype.setDisposable=function(value){if(this.current){throw new Error("Disposable has already been assigned")}var shouldDispose=this.isDisposed;!shouldDispose&&(this.current=value);shouldDispose&&value&&value.dispose()};SingleAssignmentDisposable.prototype.dispose=function(){if(!this.isDisposed){this.isDisposed=true;var old=this.current;this.current=null}old&&old.dispose()};var SerialDisposable=Rx.SerialDisposable=function(){this.isDisposed=false;this.current=null};SerialDisposable.prototype.getDisposable=function(){return this.current};SerialDisposable.prototype.setDisposable=function(value){var shouldDispose=this.isDisposed;if(!shouldDispose){var old=this.current;this.current=value}old&&old.dispose();shouldDispose&&value&&value.dispose()};SerialDisposable.prototype.dispose=function(){if(!this.isDisposed){this.isDisposed=true;var old=this.current;this.current=null}old&&old.dispose()};var RefCountDisposable=Rx.RefCountDisposable=function(){function InnerDisposable(disposable){this.disposable=disposable;this.disposable.count++;this.isInnerDisposed=false}InnerDisposable.prototype.dispose=function(){if(!this.disposable.isDisposed&&!this.isInnerDisposed){this.isInnerDisposed=true;this.disposable.count--;if(this.disposable.count===0&&this.disposable.isPrimaryDisposed){this.disposable.isDisposed=true;this.disposable.underlyingDisposable.dispose()}}};function RefCountDisposable(disposable){this.underlyingDisposable=disposable;this.isDisposed=false;this.isPrimaryDisposed=false;this.count=0}RefCountDisposable.prototype.dispose=function(){if(!this.isDisposed&&!this.isPrimaryDisposed){this.isPrimaryDisposed=true;if(this.count===0){this.isDisposed=true;this.underlyingDisposable.dispose()}}};RefCountDisposable.prototype.getDisposable=function(){return this.isDisposed?disposableEmpty:new InnerDisposable(this)};return RefCountDisposable}();function ScheduledDisposable(scheduler,disposable){this.scheduler=scheduler;this.disposable=disposable;this.isDisposed=false}function scheduleItem(s,self){if(!self.isDisposed){self.isDisposed=true;self.disposable.dispose()}}ScheduledDisposable.prototype.dispose=function(){this.scheduler.scheduleWithState(this,scheduleItem)};var ScheduledItem=Rx.internals.ScheduledItem=function(scheduler,state,action,dueTime,comparer){this.scheduler=scheduler;this.state=state;this.action=action;this.dueTime=dueTime;this.comparer=comparer||defaultSubComparer;this.disposable=new SingleAssignmentDisposable};ScheduledItem.prototype.invoke=function(){this.disposable.setDisposable(this.invokeCore())};ScheduledItem.prototype.compareTo=function(other){return this.comparer(this.dueTime,other.dueTime)};ScheduledItem.prototype.isCancelled=function(){return this.disposable.isDisposed};ScheduledItem.prototype.invokeCore=function(){return this.action(this.scheduler,this.state)};var Scheduler=Rx.Scheduler=function(){function Scheduler(now,schedule,scheduleRelative,scheduleAbsolute){this.now=now;this._schedule=schedule;this._scheduleRelative=scheduleRelative;this._scheduleAbsolute=scheduleAbsolute}Scheduler.isScheduler=function(s){return s instanceof Scheduler};function invokeAction(scheduler,action){action();return disposableEmpty}var schedulerProto=Scheduler.prototype;schedulerProto.schedule=function(action){return this._schedule(action,invokeAction)};schedulerProto.scheduleWithState=function(state,action){return this._schedule(state,action)};schedulerProto.scheduleWithRelative=function(dueTime,action){return this._scheduleRelative(action,dueTime,invokeAction)};schedulerProto.scheduleWithRelativeAndState=function(state,dueTime,action){return this._scheduleRelative(state,dueTime,action)};schedulerProto.scheduleWithAbsolute=function(dueTime,action){return this._scheduleAbsolute(action,dueTime,invokeAction)};schedulerProto.scheduleWithAbsoluteAndState=function(state,dueTime,action){return this._scheduleAbsolute(state,dueTime,action)};Scheduler.now=defaultNow;Scheduler.normalize=function(timeSpan){timeSpan<0&&(timeSpan=0);return timeSpan};return Scheduler}();var normalizeTime=Scheduler.normalize,isScheduler=Scheduler.isScheduler;(function(schedulerProto){function invokeRecImmediate(scheduler,pair){var state=pair[0],action=pair[1],group=new CompositeDisposable;action(state,innerAction);return group;function innerAction(state2){var isAdded=false,isDone=false;var d=scheduler.scheduleWithState(state2,scheduleWork);if(!isDone){group.add(d);isAdded=true}function scheduleWork(_,state3){if(isAdded){group.remove(d)}else{isDone=true}action(state3,innerAction);return disposableEmpty}}}function invokeRecDate(scheduler,pair,method){var state=pair[0],action=pair[1],group=new CompositeDisposable;action(state,innerAction);return group;function innerAction(state2,dueTime1){var isAdded=false,isDone=false;var d=scheduler[method](state2,dueTime1,scheduleWork);if(!isDone){group.add(d);isAdded=true}function scheduleWork(_,state3){if(isAdded){group.remove(d)}else{isDone=true}action(state3,innerAction);return disposableEmpty}}}function invokeRecDateRelative(s,p){return invokeRecDate(s,p,"scheduleWithRelativeAndState")}function invokeRecDateAbsolute(s,p){return invokeRecDate(s,p,"scheduleWithAbsoluteAndState")}function scheduleInnerRecursive(action,self){action(function(dt){self(action,dt)})}schedulerProto.scheduleRecursive=function(action){return this.scheduleRecursiveWithState(action,scheduleInnerRecursive)};schedulerProto.scheduleRecursiveWithState=function(state,action){return this.scheduleWithState([state,action],invokeRecImmediate)};schedulerProto.scheduleRecursiveWithRelative=function(dueTime,action){return this.scheduleRecursiveWithRelativeAndState(action,dueTime,scheduleInnerRecursive)};schedulerProto.scheduleRecursiveWithRelativeAndState=function(state,dueTime,action){return this._scheduleRelative([state,action],dueTime,invokeRecDateRelative)};schedulerProto.scheduleRecursiveWithAbsolute=function(dueTime,action){return this.scheduleRecursiveWithAbsoluteAndState(action,dueTime,scheduleInnerRecursive)};schedulerProto.scheduleRecursiveWithAbsoluteAndState=function(state,dueTime,action){return this._scheduleAbsolute([state,action],dueTime,invokeRecDateAbsolute)}})(Scheduler.prototype);(function(schedulerProto){Scheduler.prototype.schedulePeriodic=function(period,action){return this.schedulePeriodicWithState(null,period,action)};Scheduler.prototype.schedulePeriodicWithState=function(state,period,action){if(typeof root.setInterval==="undefined"){throw new NotSupportedError}period=normalizeTime(period);var s=state,id=root.setInterval(function(){s=action(s)},period);return disposableCreate(function(){root.clearInterval(id)})}})(Scheduler.prototype);(function(schedulerProto){schedulerProto.catchError=schedulerProto["catch"]=function(handler){return new CatchScheduler(this,handler)}})(Scheduler.prototype);var SchedulePeriodicRecursive=Rx.internals.SchedulePeriodicRecursive=function(){function tick(command,recurse){recurse(0,this._period);try{this._state=this._action(this._state)}catch(e){this._cancel.dispose();throw e}}function SchedulePeriodicRecursive(scheduler,state,period,action){this._scheduler=scheduler;this._state=state;this._period=period;this._action=action}SchedulePeriodicRecursive.prototype.start=function(){var d=new SingleAssignmentDisposable;this._cancel=d;d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0,this._period,tick.bind(this)));return d};return SchedulePeriodicRecursive}();var immediateScheduler=Scheduler.immediate=function(){function scheduleNow(state,action){return action(this,state)}return new Scheduler(defaultNow,scheduleNow,notSupported,notSupported)}();var currentThreadScheduler=Scheduler.currentThread=function(){var queue;function runTrampoline(){while(queue.length>0){var item=queue.shift();!item.isCancelled()&&item.invoke()}}function scheduleNow(state,action){var si=new ScheduledItem(this,state,action,this.now());if(!queue){queue=[si];var result=tryCatch(runTrampoline)();queue=null;if(result===errorObj){return thrower(result.e)}}else{queue.push(si)}return si.disposable}var currentScheduler=new Scheduler(defaultNow,scheduleNow,notSupported,notSupported);currentScheduler.scheduleRequired=function(){return!queue};return currentScheduler}();var scheduleMethod,clearMethod;var localTimer=function(){var localSetTimeout,localClearTimeout=noop;if(!!root.setTimeout){localSetTimeout=root.setTimeout;localClearTimeout=root.clearTimeout}else if(!!root.WScript){localSetTimeout=function(fn,time){root.WScript.Sleep(time);fn()}}else{throw new NotSupportedError}return{setTimeout:localSetTimeout,clearTimeout:localClearTimeout}}();var localSetTimeout=localTimer.setTimeout,localClearTimeout=localTimer.clearTimeout;(function(){var nextHandle=1,tasksByHandle={},currentlyRunning=false;clearMethod=function(handle){delete tasksByHandle[handle]};function runTask(handle){if(currentlyRunning){localSetTimeout(function(){runTask(handle)},0)}else{var task=tasksByHandle[handle];if(task){currentlyRunning=true;var result=tryCatch(task)();clearMethod(handle);currentlyRunning=false;if(result===errorObj){return thrower(result.e)}}}}var reNative=RegExp("^"+String(toString).replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/toString| for [^\]]+/g,".*?")+"$");var setImmediate=typeof(setImmediate=freeGlobal&&moduleExports&&freeGlobal.setImmediate)=="function"&&!reNative.test(setImmediate)&&setImmediate;function postMessageSupported(){if(!root.postMessage||root.importScripts){return false}var isAsync=false,oldHandler=root.onmessage;root.onmessage=function(){isAsync=true};root.postMessage("","*");root.onmessage=oldHandler;return isAsync}if(isFunction(setImmediate)){scheduleMethod=function(action){var id=nextHandle++;tasksByHandle[id]=action;setImmediate(function(){runTask(id)});return id}}else if(typeof process!=="undefined"&&{}.toString.call(process)==="[object process]"){scheduleMethod=function(action){var id=nextHandle++;tasksByHandle[id]=action;process.nextTick(function(){runTask(id)});return id}}else if(postMessageSupported()){var MSG_PREFIX="ms.rx.schedule"+Math.random();function onGlobalPostMessage(event){if(typeof event.data==="string"&&event.data.substring(0,MSG_PREFIX.length)===MSG_PREFIX){runTask(event.data.substring(MSG_PREFIX.length))}}if(root.addEventListener){root.addEventListener("message",onGlobalPostMessage,false)}else if(root.attachEvent){root.attachEvent("onmessage",onGlobalPostMessage)}else{root.onmessage=onGlobalPostMessage}scheduleMethod=function(action){var id=nextHandle++;tasksByHandle[id]=action;root.postMessage(MSG_PREFIX+currentId,"*");return id}}else if(!!root.MessageChannel){var channel=new root.MessageChannel;channel.port1.onmessage=function(e){runTask(e.data)};scheduleMethod=function(action){var id=nextHandle++;tasksByHandle[id]=action;channel.port2.postMessage(id);return id}}else if("document"in root&&"onreadystatechange"in root.document.createElement("script")){scheduleMethod=function(action){var scriptElement=root.document.createElement("script");var id=nextHandle++;tasksByHandle[id]=action;scriptElement.onreadystatechange=function(){runTask(id);scriptElement.onreadystatechange=null;scriptElement.parentNode.removeChild(scriptElement);scriptElement=null};root.document.documentElement.appendChild(scriptElement);return id}}else{scheduleMethod=function(action){var id=nextHandle++;tasksByHandle[id]=action;localSetTimeout(function(){runTask(id)},0);return id}}})();var timeoutScheduler=Scheduler.timeout=Scheduler["default"]=function(){function scheduleNow(state,action){var scheduler=this,disposable=new SingleAssignmentDisposable;var id=scheduleMethod(function(){!disposable.isDisposed&&disposable.setDisposable(action(scheduler,state))});return new CompositeDisposable(disposable,disposableCreate(function(){clearMethod(id)}))}function scheduleRelative(state,dueTime,action){var scheduler=this,dt=Scheduler.normalize(dueTime),disposable=new SingleAssignmentDisposable;if(dt===0){return scheduler.scheduleWithState(state,action)}var id=localSetTimeout(function(){!disposable.isDisposed&&disposable.setDisposable(action(scheduler,state))},dt);return new CompositeDisposable(disposable,disposableCreate(function(){localClearTimeout(id)}))}function scheduleAbsolute(state,dueTime,action){return this.scheduleWithRelativeAndState(state,dueTime-this.now(),action)}return new Scheduler(defaultNow,scheduleNow,scheduleRelative,scheduleAbsolute)}();var CatchScheduler=function(__super__){function scheduleNow(state,action){return this._scheduler.scheduleWithState(state,this._wrap(action))}function scheduleRelative(state,dueTime,action){return this._scheduler.scheduleWithRelativeAndState(state,dueTime,this._wrap(action))}function scheduleAbsolute(state,dueTime,action){return this._scheduler.scheduleWithAbsoluteAndState(state,dueTime,this._wrap(action))}inherits(CatchScheduler,__super__);function CatchScheduler(scheduler,handler){this._scheduler=scheduler;this._handler=handler;this._recursiveOriginal=null;this._recursiveWrapper=null;__super__.call(this,this._scheduler.now.bind(this._scheduler),scheduleNow,scheduleRelative,scheduleAbsolute)}CatchScheduler.prototype._clone=function(scheduler){return new CatchScheduler(scheduler,this._handler)};CatchScheduler.prototype._wrap=function(action){var parent=this;return function(self,state){try{return action(parent._getRecursiveWrapper(self),state)}catch(e){if(!parent._handler(e)){throw e}return disposableEmpty}}};CatchScheduler.prototype._getRecursiveWrapper=function(scheduler){if(this._recursiveOriginal!==scheduler){this._recursiveOriginal=scheduler;var wrapper=this._clone(scheduler);wrapper._recursiveOriginal=scheduler;wrapper._recursiveWrapper=wrapper;this._recursiveWrapper=wrapper}return this._recursiveWrapper};CatchScheduler.prototype.schedulePeriodicWithState=function(state,period,action){var self=this,failed=false,d=new SingleAssignmentDisposable;d.setDisposable(this._scheduler.schedulePeriodicWithState(state,period,function(state1){if(failed){return null}try{return action(state1)}catch(e){failed=true;if(!self._handler(e)){throw e}d.dispose();return null}}));return d};return CatchScheduler}(Scheduler);var Notification=Rx.Notification=function(){function Notification(kind,value,exception,accept,acceptObservable,toString){this.kind=kind;this.value=value;
this.exception=exception;this._accept=accept;this._acceptObservable=acceptObservable;this.toString=toString}Notification.prototype.accept=function(observerOrOnNext,onError,onCompleted){return observerOrOnNext&&typeof observerOrOnNext==="object"?this._acceptObservable(observerOrOnNext):this._accept(observerOrOnNext,onError,onCompleted)};Notification.prototype.toObservable=function(scheduler){var self=this;isScheduler(scheduler)||(scheduler=immediateScheduler);return new AnonymousObservable(function(observer){return scheduler.scheduleWithState(self,function(_,notification){notification._acceptObservable(observer);notification.kind==="N"&&observer.onCompleted()})})};return Notification}();var notificationCreateOnNext=Notification.createOnNext=function(){function _accept(onNext){return onNext(this.value)}function _acceptObservable(observer){return observer.onNext(this.value)}function toString(){return"OnNext("+this.value+")"}return function(value){return new Notification("N",value,null,_accept,_acceptObservable,toString)}}();var notificationCreateOnError=Notification.createOnError=function(){function _accept(onNext,onError){return onError(this.exception)}function _acceptObservable(observer){return observer.onError(this.exception)}function toString(){return"OnError("+this.exception+")"}return function(e){return new Notification("E",null,e,_accept,_acceptObservable,toString)}}();var notificationCreateOnCompleted=Notification.createOnCompleted=function(){function _accept(onNext,onError,onCompleted){return onCompleted()}function _acceptObservable(observer){return observer.onCompleted()}function toString(){return"OnCompleted()"}return function(){return new Notification("C",null,null,_accept,_acceptObservable,toString)}}();var Observer=Rx.Observer=function(){};Observer.prototype.toNotifier=function(){var observer=this;return function(n){return n.accept(observer)}};Observer.prototype.asObserver=function(){var self=this;return new AnonymousObserver(function(x){self.onNext(x)},function(err){self.onError(err)},function(){self.onCompleted()})};Observer.prototype.checked=function(){return new CheckedObserver(this)};var observerCreate=Observer.create=function(onNext,onError,onCompleted){onNext||(onNext=noop);onError||(onError=defaultError);onCompleted||(onCompleted=noop);return new AnonymousObserver(onNext,onError,onCompleted)};Observer.fromNotifier=function(handler,thisArg){var cb=bindCallback(handler,thisArg,1);return new AnonymousObserver(function(x){return cb(notificationCreateOnNext(x))},function(e){return cb(notificationCreateOnError(e))},function(){return cb(notificationCreateOnCompleted())})};Observer.prototype.notifyOn=function(scheduler){return new ObserveOnObserver(scheduler,this)};Observer.prototype.makeSafe=function(disposable){return new AnonymousSafeObserver(this._onNext,this._onError,this._onCompleted,disposable)};var AbstractObserver=Rx.internals.AbstractObserver=function(__super__){inherits(AbstractObserver,__super__);function AbstractObserver(){this.isStopped=false}AbstractObserver.prototype.next=notImplemented;AbstractObserver.prototype.error=notImplemented;AbstractObserver.prototype.completed=notImplemented;AbstractObserver.prototype.onNext=function(value){!this.isStopped&&this.next(value)};AbstractObserver.prototype.onError=function(error){if(!this.isStopped){this.isStopped=true;this.error(error)}};AbstractObserver.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=true;this.completed()}};AbstractObserver.prototype.dispose=function(){this.isStopped=true};AbstractObserver.prototype.fail=function(e){if(!this.isStopped){this.isStopped=true;this.error(e);return true}return false};return AbstractObserver}(Observer);var AnonymousObserver=Rx.AnonymousObserver=function(__super__){inherits(AnonymousObserver,__super__);function AnonymousObserver(onNext,onError,onCompleted){__super__.call(this);this._onNext=onNext;this._onError=onError;this._onCompleted=onCompleted}AnonymousObserver.prototype.next=function(value){this._onNext(value)};AnonymousObserver.prototype.error=function(error){this._onError(error)};AnonymousObserver.prototype.completed=function(){this._onCompleted()};return AnonymousObserver}(AbstractObserver);var CheckedObserver=function(__super__){inherits(CheckedObserver,__super__);function CheckedObserver(observer){__super__.call(this);this._observer=observer;this._state=0}var CheckedObserverPrototype=CheckedObserver.prototype;CheckedObserverPrototype.onNext=function(value){this.checkAccess();var res=tryCatch(this._observer.onNext).call(this._observer,value);this._state=0;res===errorObj&&thrower(res.e)};CheckedObserverPrototype.onError=function(err){this.checkAccess();var res=tryCatch(this._observer.onError).call(this._observer,err);this._state=2;res===errorObj&&thrower(res.e)};CheckedObserverPrototype.onCompleted=function(){this.checkAccess();var res=tryCatch(this._observer.onCompleted).call(this._observer);this._state=2;res===errorObj&&thrower(res.e)};CheckedObserverPrototype.checkAccess=function(){if(this._state===1){throw new Error("Re-entrancy detected")}if(this._state===2){throw new Error("Observer completed")}if(this._state===0){this._state=1}};return CheckedObserver}(Observer);var ScheduledObserver=Rx.internals.ScheduledObserver=function(__super__){inherits(ScheduledObserver,__super__);function ScheduledObserver(scheduler,observer){__super__.call(this);this.scheduler=scheduler;this.observer=observer;this.isAcquired=false;this.hasFaulted=false;this.queue=[];this.disposable=new SerialDisposable}ScheduledObserver.prototype.next=function(value){var self=this;this.queue.push(function(){self.observer.onNext(value)})};ScheduledObserver.prototype.error=function(e){var self=this;this.queue.push(function(){self.observer.onError(e)})};ScheduledObserver.prototype.completed=function(){var self=this;this.queue.push(function(){self.observer.onCompleted()})};ScheduledObserver.prototype.ensureActive=function(){var isOwner=false;if(!this.hasFaulted&&this.queue.length>0){isOwner=!this.isAcquired;this.isAcquired=true}if(isOwner){this.disposable.setDisposable(this.scheduler.scheduleRecursiveWithState(this,function(parent,self){var work;if(parent.queue.length>0){work=parent.queue.shift()}else{parent.isAcquired=false;return}var res=tryCatch(work)();if(res===errorObj){parent.queue=[];parent.hasFaulted=true;return thrower(res.e)}self(parent)}))}};ScheduledObserver.prototype.dispose=function(){__super__.prototype.dispose.call(this);this.disposable.dispose()};return ScheduledObserver}(AbstractObserver);var ObserveOnObserver=function(__super__){inherits(ObserveOnObserver,__super__);function ObserveOnObserver(scheduler,observer,cancel){__super__.call(this,scheduler,observer);this._cancel=cancel}ObserveOnObserver.prototype.next=function(value){__super__.prototype.next.call(this,value);this.ensureActive()};ObserveOnObserver.prototype.error=function(e){__super__.prototype.error.call(this,e);this.ensureActive()};ObserveOnObserver.prototype.completed=function(){__super__.prototype.completed.call(this);this.ensureActive()};ObserveOnObserver.prototype.dispose=function(){__super__.prototype.dispose.call(this);this._cancel&&this._cancel.dispose();this._cancel=null};return ObserveOnObserver}(ScheduledObserver);var observableProto;var Observable=Rx.Observable=function(){function makeSubscribe(self,subscribe){return function(o){var oldOnError=o.onError;o.onError=function(e){makeStackTraceLong(e,self);oldOnError.call(o,e)};return subscribe.call(self,o)}}function Observable(subscribe){if(Rx.config.longStackSupport&&hasStacks){var e=tryCatch(thrower)(new Error).e;this.stack=e.stack.substring(e.stack.indexOf("\n")+1);this._subscribe=makeSubscribe(this,subscribe)}else{this._subscribe=subscribe}}observableProto=Observable.prototype;Observable.isObservable=function(o){return o&&isFunction(o.subscribe)};observableProto.subscribe=observableProto.forEach=function(oOrOnNext,onError,onCompleted){return this._subscribe(typeof oOrOnNext==="object"?oOrOnNext:observerCreate(oOrOnNext,onError,onCompleted))};observableProto.subscribeOnNext=function(onNext,thisArg){return this._subscribe(observerCreate(typeof thisArg!=="undefined"?function(x){onNext.call(thisArg,x)}:onNext))};observableProto.subscribeOnError=function(onError,thisArg){return this._subscribe(observerCreate(null,typeof thisArg!=="undefined"?function(e){onError.call(thisArg,e)}:onError))};observableProto.subscribeOnCompleted=function(onCompleted,thisArg){return this._subscribe(observerCreate(null,null,typeof thisArg!=="undefined"?function(){onCompleted.call(thisArg)}:onCompleted))};return Observable}();var ObservableBase=Rx.ObservableBase=function(__super__){inherits(ObservableBase,__super__);function fixSubscriber(subscriber){return subscriber&&isFunction(subscriber.dispose)?subscriber:isFunction(subscriber)?disposableCreate(subscriber):disposableEmpty}function setDisposable(s,state){var ado=state[0],self=state[1];var sub=tryCatch(self.subscribeCore).call(self,ado);if(sub===errorObj){if(!ado.fail(errorObj.e)){return thrower(errorObj.e)}}ado.setDisposable(fixSubscriber(sub))}function subscribe(observer){var ado=new AutoDetachObserver(observer),state=[ado,this];if(currentThreadScheduler.scheduleRequired()){currentThreadScheduler.scheduleWithState(state,setDisposable)}else{setDisposable(null,state)}return ado}function ObservableBase(){__super__.call(this,subscribe)}ObservableBase.prototype.subscribeCore=notImplemented;return ObservableBase}(Observable);var FlatMapObservable=function(__super__){inherits(FlatMapObservable,__super__);function FlatMapObservable(source,selector,resultSelector,thisArg){this.resultSelector=Rx.helpers.isFunction(resultSelector)?resultSelector:null;this.selector=Rx.internals.bindCallback(Rx.helpers.isFunction(selector)?selector:function(){return selector},thisArg,3);this.source=source;__super__.call(this)}FlatMapObservable.prototype.subscribeCore=function(o){return this.source.subscribe(new InnerObserver(o,this.selector,this.resultSelector,this))};function InnerObserver(observer,selector,resultSelector,source){this.i=0;this.selector=selector;this.resultSelector=resultSelector;this.source=source;this.isStopped=false;this.o=observer}InnerObserver.prototype._wrapResult=function(result,x,i){return this.resultSelector?result.map(function(y,i2){return this.resultSelector(x,y,i,i2)},this):result};InnerObserver.prototype.onNext=function(x){if(this.isStopped)return;var i=this.i++;var result=tryCatch(this.selector)(x,i,this.source);if(result===errorObj){return this.o.onError(result.e)}Rx.helpers.isPromise(result)&&(result=Rx.Observable.fromPromise(result));(Rx.helpers.isArrayLike(result)||Rx.helpers.isIterable(result))&&(result=Rx.Observable.from(result));this.o.onNext(this._wrapResult(result,x,i))};InnerObserver.prototype.onError=function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e)}};InnerObserver.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=true;this.o.onCompleted()}};return FlatMapObservable}(ObservableBase);var Enumerable=Rx.internals.Enumerable=function(){};var ConcatEnumerableObservable=function(__super__){inherits(ConcatEnumerableObservable,__super__);function ConcatEnumerableObservable(sources){this.sources=sources;__super__.call(this)}ConcatEnumerableObservable.prototype.subscribeCore=function(o){var isDisposed,subscription=new SerialDisposable;var cancelable=immediateScheduler.scheduleRecursiveWithState(this.sources[$iterator$](),function(e,self){if(isDisposed){return}var currentItem=tryCatch(e.next).call(e);if(currentItem===errorObj){return o.onError(currentItem.e)}if(currentItem.done){return o.onCompleted()}var currentValue=currentItem.value;isPromise(currentValue)&&(currentValue=observableFromPromise(currentValue));var d=new SingleAssignmentDisposable;subscription.setDisposable(d);d.setDisposable(currentValue.subscribe(new InnerObserver(o,self,e)))});return new CompositeDisposable(subscription,cancelable,disposableCreate(function(){isDisposed=true}))};function InnerObserver(o,s,e){this.o=o;this.s=s;this.e=e;this.isStopped=false}InnerObserver.prototype.onNext=function(x){if(!this.isStopped){this.o.onNext(x)}};InnerObserver.prototype.onError=function(err){if(!this.isStopped){this.isStopped=true;this.o.onError(err)}};InnerObserver.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=true;this.s(this.e)}};InnerObserver.prototype.dispose=function(){this.isStopped=true};InnerObserver.prototype.fail=function(err){if(!this.isStopped){this.isStopped=true;this.o.onError(err);return true}return false};return ConcatEnumerableObservable}(ObservableBase);Enumerable.prototype.concat=function(){return new ConcatEnumerableObservable(this)};var CatchErrorObservable=function(__super__){inherits(CatchErrorObservable,__super__);function CatchErrorObservable(sources){this.sources=sources;__super__.call(this)}CatchErrorObservable.prototype.subscribeCore=function(o){var e=this.sources[$iterator$]();var isDisposed,subscription=new SerialDisposable;var cancelable=immediateScheduler.scheduleRecursiveWithState(null,function(lastException,self){if(isDisposed){return}var currentItem=tryCatch(e.next).call(e);if(currentItem===errorObj){return o.onError(currentItem.e)}if(currentItem.done){return lastException!==null?o.onError(lastException):o.onCompleted()}var currentValue=currentItem.value;isPromise(currentValue)&&(currentValue=observableFromPromise(currentValue));var d=new SingleAssignmentDisposable;subscription.setDisposable(d);d.setDisposable(currentValue.subscribe(function(x){o.onNext(x)},self,function(){o.onCompleted()}))});return new CompositeDisposable(subscription,cancelable,disposableCreate(function(){isDisposed=true}))};return CatchErrorObservable}(ObservableBase);Enumerable.prototype.catchError=function(){return new CatchErrorObservable(this)};Enumerable.prototype.catchErrorWhen=function(notificationHandler){var sources=this;return new AnonymousObservable(function(o){var exceptions=new Subject,notifier=new Subject,handled=notificationHandler(exceptions),notificationDisposable=handled.subscribe(notifier);var e=sources[$iterator$]();var isDisposed,lastException,subscription=new SerialDisposable;var cancelable=immediateScheduler.scheduleRecursive(function(self){if(isDisposed){return}var currentItem=tryCatch(e.next).call(e);if(currentItem===errorObj){return o.onError(currentItem.e)}if(currentItem.done){if(lastException){o.onError(lastException)}else{o.onCompleted()}return}var currentValue=currentItem.value;isPromise(currentValue)&&(currentValue=observableFromPromise(currentValue));var outer=new SingleAssignmentDisposable;var inner=new SingleAssignmentDisposable;subscription.setDisposable(new CompositeDisposable(inner,outer));outer.setDisposable(currentValue.subscribe(function(x){o.onNext(x)},function(exn){inner.setDisposable(notifier.subscribe(self,function(ex){o.onError(ex)},function(){o.onCompleted()}));exceptions.onNext(exn)},function(){o.onCompleted()}))});return new CompositeDisposable(notificationDisposable,subscription,cancelable,disposableCreate(function(){isDisposed=true}))})};var RepeatEnumerable=function(__super__){inherits(RepeatEnumerable,__super__);function RepeatEnumerable(v,c){this.v=v;this.c=c==null?-1:c}RepeatEnumerable.prototype[$iterator$]=function(){return new RepeatEnumerator(this)};function RepeatEnumerator(p){this.v=p.v;this.l=p.c}RepeatEnumerator.prototype.next=function(){if(this.l===0){return doneEnumerator}if(this.l>0){this.l--}return{done:false,value:this.v}};return RepeatEnumerable}(Enumerable);var enumerableRepeat=Enumerable.repeat=function(value,repeatCount){return new RepeatEnumerable(value,repeatCount)};var OfEnumerable=function(__super__){inherits(OfEnumerable,__super__);function OfEnumerable(s,fn,thisArg){this.s=s;this.fn=fn?bindCallback(fn,thisArg,3):null}OfEnumerable.prototype[$iterator$]=function(){return new OfEnumerator(this)};function OfEnumerator(p){this.i=-1;this.s=p.s;this.l=this.s.length;this.fn=p.fn}OfEnumerator.prototype.next=function(){return++this.i<this.l?{done:false,value:!this.fn?this.s[this.i]:this.fn(this.s[this.i],this.i,this.s)}:doneEnumerator};return OfEnumerable}(Enumerable);var enumerableOf=Enumerable.of=function(source,selector,thisArg){return new OfEnumerable(source,selector,thisArg)};observableProto.observeOn=function(scheduler){var source=this;return new AnonymousObservable(function(observer){return source.subscribe(new ObserveOnObserver(scheduler,observer))},source)};observableProto.subscribeOn=function(scheduler){var source=this;return new AnonymousObservable(function(observer){var m=new SingleAssignmentDisposable,d=new SerialDisposable;d.setDisposable(m);m.setDisposable(scheduler.schedule(function(){d.setDisposable(new ScheduledDisposable(scheduler,source.subscribe(observer)))}));return d},source)};var FromPromiseObservable=function(__super__){inherits(FromPromiseObservable,__super__);function FromPromiseObservable(p){this.p=p;__super__.call(this)}FromPromiseObservable.prototype.subscribeCore=function(o){this.p.then(function(data){o.onNext(data);o.onCompleted()},function(err){o.onError(err)});return disposableEmpty};return FromPromiseObservable}(ObservableBase);var observableFromPromise=Observable.fromPromise=function(promise){return new FromPromiseObservable(promise)};observableProto.toPromise=function(promiseCtor){promiseCtor||(promiseCtor=Rx.config.Promise);if(!promiseCtor){throw new NotSupportedError("Promise type not provided nor in Rx.config.Promise")}var source=this;return new promiseCtor(function(resolve,reject){var value,hasValue=false;source.subscribe(function(v){value=v;hasValue=true},reject,function(){hasValue&&resolve(value)})})};var ToArrayObservable=function(__super__){inherits(ToArrayObservable,__super__);function ToArrayObservable(source){this.source=source;__super__.call(this)}ToArrayObservable.prototype.subscribeCore=function(o){return this.source.subscribe(new InnerObserver(o))};function InnerObserver(o){this.o=o;this.a=[];this.isStopped=false}InnerObserver.prototype.onNext=function(x){if(!this.isStopped){this.a.push(x)}};InnerObserver.prototype.onError=function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e)}};InnerObserver.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=true;this.o.onNext(this.a);this.o.onCompleted()}};InnerObserver.prototype.dispose=function(){this.isStopped=true};InnerObserver.prototype.fail=function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e);return true}return false};return ToArrayObservable}(ObservableBase);observableProto.toArray=function(){return new ToArrayObservable(this)};Observable.create=function(subscribe,parent){return new AnonymousObservable(subscribe,parent)};var observableDefer=Observable.defer=function(observableFactory){return new AnonymousObservable(function(observer){var result;try{result=observableFactory()}catch(e){return observableThrow(e).subscribe(observer)}isPromise(result)&&(result=observableFromPromise(result));return result.subscribe(observer)})};var EmptyObservable=function(__super__){inherits(EmptyObservable,__super__);function EmptyObservable(scheduler){this.scheduler=scheduler;__super__.call(this)}EmptyObservable.prototype.subscribeCore=function(observer){var sink=new EmptySink(observer,this.scheduler);return sink.run()};function EmptySink(observer,scheduler){this.observer=observer;this.scheduler=scheduler}function scheduleItem(s,state){state.onCompleted();return disposableEmpty}EmptySink.prototype.run=function(){return this.scheduler.scheduleWithState(this.observer,scheduleItem)};return EmptyObservable}(ObservableBase);var EMPTY_OBSERVABLE=new EmptyObservable(immediateScheduler);var observableEmpty=Observable.empty=function(scheduler){isScheduler(scheduler)||(scheduler=immediateScheduler);return scheduler===immediateScheduler?EMPTY_OBSERVABLE:new EmptyObservable(scheduler)};var FromObservable=function(__super__){inherits(FromObservable,__super__);function FromObservable(iterable,mapper,scheduler){this.iterable=iterable;this.mapper=mapper;this.scheduler=scheduler;__super__.call(this)}FromObservable.prototype.subscribeCore=function(o){var sink=new FromSink(o,this);return sink.run()};return FromObservable}(ObservableBase);var FromSink=function(){function FromSink(o,parent){this.o=o;this.parent=parent}FromSink.prototype.run=function(){var list=Object(this.parent.iterable),it=getIterable(list),o=this.o,mapper=this.parent.mapper;function loopRecursive(i,recurse){var next=tryCatch(it.next).call(it);if(next===errorObj){return o.onError(next.e)}if(next.done){return o.onCompleted()}var result=next.value;if(isFunction(mapper)){result=tryCatch(mapper)(result,i);if(result===errorObj){return o.onError(result.e)}}o.onNext(result);recurse(i+1)}return this.parent.scheduler.scheduleRecursiveWithState(0,loopRecursive)};return FromSink}();var maxSafeInteger=Math.pow(2,53)-1;function StringIterable(s){this._s=s}StringIterable.prototype[$iterator$]=function(){return new StringIterator(this._s)};function StringIterator(s){this._s=s;this._l=s.length;this._i=0}StringIterator.prototype[$iterator$]=function(){return this};StringIterator.prototype.next=function(){return this._i<this._l?{done:false,value:this._s.charAt(this._i++)}:doneEnumerator};function ArrayIterable(a){this._a=a}ArrayIterable.prototype[$iterator$]=function(){return new ArrayIterator(this._a)};function ArrayIterator(a){this._a=a;this._l=toLength(a);this._i=0}ArrayIterator.prototype[$iterator$]=function(){return this};ArrayIterator.prototype.next=function(){return this._i<this._l?{done:false,value:this._a[this._i++]}:doneEnumerator};function numberIsFinite(value){return typeof value==="number"&&root.isFinite(value)}function isNan(n){return n!==n}function getIterable(o){var i=o[$iterator$],it;if(!i&&typeof o==="string"){it=new StringIterable(o);return it[$iterator$]()}if(!i&&o.length!==undefined){it=new ArrayIterable(o);return it[$iterator$]()}if(!i){throw new TypeError("Object is not iterable")}return o[$iterator$]()}function sign(value){var number=+value;if(number===0){return number}if(isNaN(number)){return number}return number<0?-1:1}function toLength(o){var len=+o.length;if(isNaN(len)){return 0}if(len===0||!numberIsFinite(len)){return len}len=sign(len)*Math.floor(Math.abs(len));if(len<=0){return 0}if(len>maxSafeInteger){return maxSafeInteger}return len}var observableFrom=Observable.from=function(iterable,mapFn,thisArg,scheduler){if(iterable==null){throw new Error("iterable cannot be null.")}if(mapFn&&!isFunction(mapFn)){throw new Error("mapFn when provided must be a function")}if(mapFn){var mapper=bindCallback(mapFn,thisArg,2)}isScheduler(scheduler)||(scheduler=currentThreadScheduler);return new FromObservable(iterable,mapper,scheduler)};var FromArrayObservable=function(__super__){inherits(FromArrayObservable,__super__);function FromArrayObservable(args,scheduler){this.args=args;this.scheduler=scheduler;__super__.call(this)}FromArrayObservable.prototype.subscribeCore=function(observer){var sink=new FromArraySink(observer,this);return sink.run()};return FromArrayObservable}(ObservableBase);function FromArraySink(observer,parent){this.observer=observer;this.parent=parent}FromArraySink.prototype.run=function(){var observer=this.observer,args=this.parent.args,len=args.length;function loopRecursive(i,recurse){if(i<len){observer.onNext(args[i]);recurse(i+1)}else{observer.onCompleted()}}return this.parent.scheduler.scheduleRecursiveWithState(0,loopRecursive)};var observableFromArray=Observable.fromArray=function(array,scheduler){isScheduler(scheduler)||(scheduler=currentThreadScheduler);return new FromArrayObservable(array,scheduler)};Observable.generate=function(initialState,condition,iterate,resultSelector,scheduler){isScheduler(scheduler)||(scheduler=currentThreadScheduler);return new AnonymousObservable(function(o){var first=true;return scheduler.scheduleRecursiveWithState(initialState,function(state,self){var hasResult,result;try{if(first){first=false}else{state=iterate(state)}hasResult=condition(state);hasResult&&(result=resultSelector(state))}catch(e){return o.onError(e)}if(hasResult){o.onNext(result);self(state)}else{o.onCompleted()}})})};function observableOf(scheduler,array){isScheduler(scheduler)||(scheduler=currentThreadScheduler);return new FromArrayObservable(array,scheduler)}Observable.of=function(){var len=arguments.length,args=new Array(len);for(var i=0;i<len;i++){args[i]=arguments[i]}return new FromArrayObservable(args,currentThreadScheduler)};Observable.ofWithScheduler=function(scheduler){var len=arguments.length,args=new Array(len-1);for(var i=1;i<len;i++){args[i-1]=arguments[i]}return new FromArrayObservable(args,scheduler)};Observable.ofArrayChanges=function(array){if(!Array.isArray(array)){throw new TypeError("Array.observe only accepts arrays.")}if(typeof Array.observe!=="function"&&typeof Array.unobserve!=="function"){throw new TypeError("Array.observe is not supported on your platform")}return new AnonymousObservable(function(observer){function observerFn(changes){for(var i=0,len=changes.length;i<len;i++){observer.onNext(changes[i])}}Array.observe(array,observerFn);return function(){Array.unobserve(array,observerFn)}})};Observable.ofObjectChanges=function(obj){if(obj==null){throw new TypeError("object must not be null or undefined.")}if(typeof Object.observe!=="function"&&typeof Object.unobserve!=="function"){throw new TypeError("Object.observe is not supported on your platform")}return new AnonymousObservable(function(observer){function observerFn(changes){for(var i=0,len=changes.length;i<len;i++){observer.onNext(changes[i])}}Object.observe(obj,observerFn);return function(){Object.unobserve(obj,observerFn)}})};var NeverObservable=function(__super__){inherits(NeverObservable,__super__);function NeverObservable(){__super__.call(this)}NeverObservable.prototype.subscribeCore=function(observer){return disposableEmpty};return NeverObservable}(ObservableBase);var NEVER_OBSERVABLE=new NeverObservable;var observableNever=Observable.never=function(){return NEVER_OBSERVABLE};var PairsObservable=function(__super__){inherits(PairsObservable,__super__);function PairsObservable(obj,scheduler){this.obj=obj;this.keys=Object.keys(obj);this.scheduler=scheduler;__super__.call(this)}PairsObservable.prototype.subscribeCore=function(observer){var sink=new PairsSink(observer,this);return sink.run()};return PairsObservable}(ObservableBase);function PairsSink(observer,parent){this.observer=observer;this.parent=parent}PairsSink.prototype.run=function(){var observer=this.observer,obj=this.parent.obj,keys=this.parent.keys,len=keys.length;function loopRecursive(i,recurse){if(i<len){var key=keys[i];observer.onNext([key,obj[key]]);recurse(i+1)}else{observer.onCompleted()}}return this.parent.scheduler.scheduleRecursiveWithState(0,loopRecursive)};Observable.pairs=function(obj,scheduler){scheduler||(scheduler=currentThreadScheduler);return new PairsObservable(obj,scheduler)};var RangeObservable=function(__super__){inherits(RangeObservable,__super__);function RangeObservable(start,count,scheduler){this.start=start;this.rangeCount=count;this.scheduler=scheduler;__super__.call(this)}RangeObservable.prototype.subscribeCore=function(observer){var sink=new RangeSink(observer,this);return sink.run()};return RangeObservable}(ObservableBase);var RangeSink=function(){function RangeSink(observer,parent){this.observer=observer;this.parent=parent}RangeSink.prototype.run=function(){var start=this.parent.start,count=this.parent.rangeCount,observer=this.observer;function loopRecursive(i,recurse){if(i<count){observer.onNext(start+i);recurse(i+1)}else{observer.onCompleted()}}return this.parent.scheduler.scheduleRecursiveWithState(0,loopRecursive)};return RangeSink}();Observable.range=function(start,count,scheduler){isScheduler(scheduler)||(scheduler=currentThreadScheduler);return new RangeObservable(start,count,scheduler)};var RepeatObservable=function(__super__){inherits(RepeatObservable,__super__);function RepeatObservable(value,repeatCount,scheduler){this.value=value;this.repeatCount=repeatCount==null?-1:repeatCount;this.scheduler=scheduler;__super__.call(this)}RepeatObservable.prototype.subscribeCore=function(observer){var sink=new RepeatSink(observer,this);return sink.run()};return RepeatObservable}(ObservableBase);function RepeatSink(observer,parent){this.observer=observer;this.parent=parent}RepeatSink.prototype.run=function(){var observer=this.observer,value=this.parent.value;function loopRecursive(i,recurse){if(i===-1||i>0){observer.onNext(value);i>0&&i--}if(i===0){return observer.onCompleted()}recurse(i)}return this.parent.scheduler.scheduleRecursiveWithState(this.parent.repeatCount,loopRecursive)};Observable.repeat=function(value,repeatCount,scheduler){isScheduler(scheduler)||(scheduler=currentThreadScheduler);return new RepeatObservable(value,repeatCount,scheduler)};var JustObservable=function(__super__){inherits(JustObservable,__super__);function JustObservable(value,scheduler){this.value=value;this.scheduler=scheduler;__super__.call(this)}JustObservable.prototype.subscribeCore=function(observer){var sink=new JustSink(observer,this.value,this.scheduler);return sink.run()};function JustSink(observer,value,scheduler){this.observer=observer;this.value=value;this.scheduler=scheduler}function scheduleItem(s,state){var value=state[0],observer=state[1];observer.onNext(value);observer.onCompleted();return disposableEmpty}JustSink.prototype.run=function(){var state=[this.value,this.observer];return this.scheduler===immediateScheduler?scheduleItem(null,state):this.scheduler.scheduleWithState(state,scheduleItem)};return JustObservable}(ObservableBase);var observableReturn=Observable["return"]=Observable.just=function(value,scheduler){isScheduler(scheduler)||(scheduler=immediateScheduler);return new JustObservable(value,scheduler)};var ThrowObservable=function(__super__){inherits(ThrowObservable,__super__);function ThrowObservable(error,scheduler){this.error=error;this.scheduler=scheduler;__super__.call(this)}ThrowObservable.prototype.subscribeCore=function(o){var sink=new ThrowSink(o,this);return sink.run()};function ThrowSink(o,p){this.o=o;this.p=p}function scheduleItem(s,state){var e=state[0],o=state[1];o.onError(e)}ThrowSink.prototype.run=function(){return this.p.scheduler.scheduleWithState([this.p.error,this.o],scheduleItem)};return ThrowObservable}(ObservableBase);var observableThrow=Observable["throw"]=function(error,scheduler){isScheduler(scheduler)||(scheduler=immediateScheduler);return new ThrowObservable(error,scheduler)};Observable.using=function(resourceFactory,observableFactory){return new AnonymousObservable(function(o){var disposable=disposableEmpty;var resource=tryCatch(resourceFactory)();if(resource===errorObj){return new CompositeDisposable(observableThrow(resource.e).subscribe(o),disposable)}resource&&(disposable=resource);var source=tryCatch(observableFactory)(resource);if(source===errorObj){return new CompositeDisposable(observableThrow(source.e).subscribe(o),disposable)}return new CompositeDisposable(source.subscribe(o),disposable)})};observableProto.amb=function(rightSource){var leftSource=this;return new AnonymousObservable(function(observer){var choice,leftChoice="L",rightChoice="R",leftSubscription=new SingleAssignmentDisposable,rightSubscription=new SingleAssignmentDisposable;isPromise(rightSource)&&(rightSource=observableFromPromise(rightSource));function choiceL(){if(!choice){choice=leftChoice;rightSubscription.dispose()}}function choiceR(){if(!choice){choice=rightChoice;leftSubscription.dispose()}}var leftSubscribe=observerCreate(function(left){choiceL();choice===leftChoice&&observer.onNext(left)},function(e){choiceL();choice===leftChoice&&observer.onError(e)},function(){choiceL();choice===leftChoice&&observer.onCompleted()});var rightSubscribe=observerCreate(function(right){choiceR();choice===rightChoice&&observer.onNext(right)},function(e){choiceR();choice===rightChoice&&observer.onError(e)},function(){choiceR();choice===rightChoice&&observer.onCompleted()});leftSubscription.setDisposable(leftSource.subscribe(leftSubscribe));
rightSubscription.setDisposable(rightSource.subscribe(rightSubscribe));return new CompositeDisposable(leftSubscription,rightSubscription)})};function amb(p,c){return p.amb(c)}Observable.amb=function(){var acc=observableNever(),items;if(Array.isArray(arguments[0])){items=arguments[0]}else{var len=arguments.length;items=new Array(items);for(var i=0;i<len;i++){items[i]=arguments[i]}}for(var i=0,len=items.length;i<len;i++){acc=amb(acc,items[i])}return acc};var CatchObserver=function(__super__){inherits(CatchObserver,__super__);function CatchObserver(o,s,fn){this._o=o;this._s=s;this._fn=fn;__super__.call(this)}CatchObserver.prototype.next=function(x){this._o.onNext(x)};CatchObserver.prototype.completed=function(){return this._o.onCompleted()};CatchObserver.prototype.error=function(e){var result=tryCatch(this._fn)(e);if(result===errorObj){return this._o.onError(result.e)}isPromise(result)&&(result=observableFromPromise(result));var d=new SingleAssignmentDisposable;this._s.setDisposable(d);d.setDisposable(result.subscribe(this._o))};return CatchObserver}(AbstractObserver);function observableCatchHandler(source,handler){return new AnonymousObservable(function(o){var d1=new SingleAssignmentDisposable,subscription=new SerialDisposable;subscription.setDisposable(d1);d1.setDisposable(source.subscribe(new CatchObserver(o,subscription,handler)));return subscription},source)}observableProto["catch"]=function(handlerOrSecond){return isFunction(handlerOrSecond)?observableCatchHandler(this,handlerOrSecond):observableCatch([this,handlerOrSecond])};var observableCatch=Observable["catch"]=function(){var items;if(Array.isArray(arguments[0])){items=arguments[0]}else{var len=arguments.length;items=new Array(len);for(var i=0;i<len;i++){items[i]=arguments[i]}}return enumerableOf(items).catchError()};observableProto.combineLatest=function(){var len=arguments.length,args=new Array(len);for(var i=0;i<len;i++){args[i]=arguments[i]}if(Array.isArray(args[0])){args[0].unshift(this)}else{args.unshift(this)}return combineLatest.apply(this,args)};var combineLatest=Observable.combineLatest=function(){var len=arguments.length,args=new Array(len);for(var i=0;i<len;i++){args[i]=arguments[i]}var resultSelector=args.pop();Array.isArray(args[0])&&(args=args[0]);return new AnonymousObservable(function(o){var n=args.length,falseFactory=function(){return false},hasValue=arrayInitialize(n,falseFactory),hasValueAll=false,isDone=arrayInitialize(n,falseFactory),values=new Array(n);function next(i){hasValue[i]=true;if(hasValueAll||(hasValueAll=hasValue.every(identity))){try{var res=resultSelector.apply(null,values)}catch(e){return o.onError(e)}o.onNext(res)}else if(isDone.filter(function(x,j){return j!==i}).every(identity)){o.onCompleted()}}function done(i){isDone[i]=true;isDone.every(identity)&&o.onCompleted()}var subscriptions=new Array(n);for(var idx=0;idx<n;idx++){(function(i){var source=args[i],sad=new SingleAssignmentDisposable;isPromise(source)&&(source=observableFromPromise(source));sad.setDisposable(source.subscribe(function(x){values[i]=x;next(i)},function(e){o.onError(e)},function(){done(i)}));subscriptions[i]=sad})(idx)}return new CompositeDisposable(subscriptions)},this)};observableProto.concat=function(){for(var args=[],i=0,len=arguments.length;i<len;i++){args.push(arguments[i])}args.unshift(this);return observableConcat.apply(null,args)};var ConcatObservable=function(__super__){inherits(ConcatObservable,__super__);function ConcatObservable(sources){this.sources=sources;__super__.call(this)}ConcatObservable.prototype.subscribeCore=function(o){var sink=new ConcatSink(this.sources,o);return sink.run()};function ConcatSink(sources,o){this.sources=sources;this.o=o}ConcatSink.prototype.run=function(){var isDisposed,subscription=new SerialDisposable,sources=this.sources,length=sources.length,o=this.o;var cancelable=immediateScheduler.scheduleRecursiveWithState(0,function(i,self){if(isDisposed){return}if(i===length){return o.onCompleted()}var currentValue=sources[i];isPromise(currentValue)&&(currentValue=observableFromPromise(currentValue));var d=new SingleAssignmentDisposable;subscription.setDisposable(d);d.setDisposable(currentValue.subscribe(function(x){o.onNext(x)},function(e){o.onError(e)},function(){self(i+1)}))});return new CompositeDisposable(subscription,cancelable,disposableCreate(function(){isDisposed=true}))};return ConcatObservable}(ObservableBase);var observableConcat=Observable.concat=function(){var args;if(Array.isArray(arguments[0])){args=arguments[0]}else{args=new Array(arguments.length);for(var i=0,len=arguments.length;i<len;i++){args[i]=arguments[i]}}return new ConcatObservable(args)};observableProto.concatAll=function(){return this.merge(1)};var MergeObservable=function(__super__){inherits(MergeObservable,__super__);function MergeObservable(source,maxConcurrent){this.source=source;this.maxConcurrent=maxConcurrent;__super__.call(this)}MergeObservable.prototype.subscribeCore=function(observer){var g=new CompositeDisposable;g.add(this.source.subscribe(new MergeObserver(observer,this.maxConcurrent,g)));return g};return MergeObservable}(ObservableBase);var MergeObserver=function(){function MergeObserver(o,max,g){this.o=o;this.max=max;this.g=g;this.done=false;this.q=[];this.activeCount=0;this.isStopped=false}MergeObserver.prototype.handleSubscribe=function(xs){var sad=new SingleAssignmentDisposable;this.g.add(sad);isPromise(xs)&&(xs=observableFromPromise(xs));sad.setDisposable(xs.subscribe(new InnerObserver(this,sad)))};MergeObserver.prototype.onNext=function(innerSource){if(this.isStopped){return}if(this.activeCount<this.max){this.activeCount++;this.handleSubscribe(innerSource)}else{this.q.push(innerSource)}};MergeObserver.prototype.onError=function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e)}};MergeObserver.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=true;this.done=true;this.activeCount===0&&this.o.onCompleted()}};MergeObserver.prototype.dispose=function(){this.isStopped=true};MergeObserver.prototype.fail=function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e);return true}return false};function InnerObserver(parent,sad){this.parent=parent;this.sad=sad;this.isStopped=false}InnerObserver.prototype.onNext=function(x){if(!this.isStopped){this.parent.o.onNext(x)}};InnerObserver.prototype.onError=function(e){if(!this.isStopped){this.isStopped=true;this.parent.o.onError(e)}};InnerObserver.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=true;var parent=this.parent;parent.g.remove(this.sad);if(parent.q.length>0){parent.handleSubscribe(parent.q.shift())}else{parent.activeCount--;parent.done&&parent.activeCount===0&&parent.o.onCompleted()}}};InnerObserver.prototype.dispose=function(){this.isStopped=true};InnerObserver.prototype.fail=function(e){if(!this.isStopped){this.isStopped=true;this.parent.o.onError(e);return true}return false};return MergeObserver}();observableProto.merge=function(maxConcurrentOrOther){return typeof maxConcurrentOrOther!=="number"?observableMerge(this,maxConcurrentOrOther):new MergeObservable(this,maxConcurrentOrOther)};var observableMerge=Observable.merge=function(){var scheduler,sources=[],i,len=arguments.length;if(!arguments[0]){scheduler=immediateScheduler;for(i=1;i<len;i++){sources.push(arguments[i])}}else if(isScheduler(arguments[0])){scheduler=arguments[0];for(i=1;i<len;i++){sources.push(arguments[i])}}else{scheduler=immediateScheduler;for(i=0;i<len;i++){sources.push(arguments[i])}}if(Array.isArray(sources[0])){sources=sources[0]}return observableOf(scheduler,sources).mergeAll()};var MergeAllObservable=function(__super__){inherits(MergeAllObservable,__super__);function MergeAllObservable(source){this.source=source;__super__.call(this)}MergeAllObservable.prototype.subscribeCore=function(observer){var g=new CompositeDisposable,m=new SingleAssignmentDisposable;g.add(m);m.setDisposable(this.source.subscribe(new MergeAllObserver(observer,g)));return g};function MergeAllObserver(o,g){this.o=o;this.g=g;this.isStopped=false;this.done=false}MergeAllObserver.prototype.onNext=function(innerSource){if(this.isStopped){return}var sad=new SingleAssignmentDisposable;this.g.add(sad);isPromise(innerSource)&&(innerSource=observableFromPromise(innerSource));sad.setDisposable(innerSource.subscribe(new InnerObserver(this,sad)))};MergeAllObserver.prototype.onError=function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e)}};MergeAllObserver.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=true;this.done=true;this.g.length===1&&this.o.onCompleted()}};MergeAllObserver.prototype.dispose=function(){this.isStopped=true};MergeAllObserver.prototype.fail=function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e);return true}return false};function InnerObserver(parent,sad){this.parent=parent;this.sad=sad;this.isStopped=false}InnerObserver.prototype.onNext=function(x){if(!this.isStopped){this.parent.o.onNext(x)}};InnerObserver.prototype.onError=function(e){if(!this.isStopped){this.isStopped=true;this.parent.o.onError(e)}};InnerObserver.prototype.onCompleted=function(){if(!this.isStopped){var parent=this.parent;this.isStopped=true;parent.g.remove(this.sad);parent.done&&parent.g.length===1&&parent.o.onCompleted()}};InnerObserver.prototype.dispose=function(){this.isStopped=true};InnerObserver.prototype.fail=function(e){if(!this.isStopped){this.isStopped=true;this.parent.o.onError(e);return true}return false};return MergeAllObservable}(ObservableBase);observableProto.mergeAll=function(){return new MergeAllObservable(this)};var CompositeError=Rx.CompositeError=function(errors){this.name="NotImplementedError";this.innerErrors=errors;this.message="This contains multiple errors. Check the innerErrors";Error.call(this)};CompositeError.prototype=Error.prototype;Observable.mergeDelayError=function(){var args;if(Array.isArray(arguments[0])){args=arguments[0]}else{var len=arguments.length;args=new Array(len);for(var i=0;i<len;i++){args[i]=arguments[i]}}var source=observableOf(null,args);return new AnonymousObservable(function(o){var group=new CompositeDisposable,m=new SingleAssignmentDisposable,isStopped=false,errors=[];function setCompletion(){if(errors.length===0){o.onCompleted()}else if(errors.length===1){o.onError(errors[0])}else{o.onError(new CompositeError(errors))}}group.add(m);m.setDisposable(source.subscribe(function(innerSource){var innerSubscription=new SingleAssignmentDisposable;group.add(innerSubscription);isPromise(innerSource)&&(innerSource=observableFromPromise(innerSource));innerSubscription.setDisposable(innerSource.subscribe(function(x){o.onNext(x)},function(e){errors.push(e);group.remove(innerSubscription);isStopped&&group.length===1&&setCompletion()},function(){group.remove(innerSubscription);isStopped&&group.length===1&&setCompletion()}))},function(e){errors.push(e);isStopped=true;group.length===1&&setCompletion()},function(){isStopped=true;group.length===1&&setCompletion()}));return group})};observableProto.onErrorResumeNext=function(second){if(!second){throw new Error("Second observable is required")}return onErrorResumeNext([this,second])};var onErrorResumeNext=Observable.onErrorResumeNext=function(){var sources=[];if(Array.isArray(arguments[0])){sources=arguments[0]}else{for(var i=0,len=arguments.length;i<len;i++){sources.push(arguments[i])}}return new AnonymousObservable(function(observer){var pos=0,subscription=new SerialDisposable,cancelable=immediateScheduler.scheduleRecursive(function(self){var current,d;if(pos<sources.length){current=sources[pos++];isPromise(current)&&(current=observableFromPromise(current));d=new SingleAssignmentDisposable;subscription.setDisposable(d);d.setDisposable(current.subscribe(observer.onNext.bind(observer),self,self))}else{observer.onCompleted()}});return new CompositeDisposable(subscription,cancelable)})};observableProto.skipUntil=function(other){var source=this;return new AnonymousObservable(function(o){var isOpen=false;var disposables=new CompositeDisposable(source.subscribe(function(left){isOpen&&o.onNext(left)},function(e){o.onError(e)},function(){isOpen&&o.onCompleted()}));isPromise(other)&&(other=observableFromPromise(other));var rightSubscription=new SingleAssignmentDisposable;disposables.add(rightSubscription);rightSubscription.setDisposable(other.subscribe(function(){isOpen=true;rightSubscription.dispose()},function(e){o.onError(e)},function(){rightSubscription.dispose()}));return disposables},source)};var SwitchObservable=function(__super__){inherits(SwitchObservable,__super__);function SwitchObservable(source){this.source=source;__super__.call(this)}SwitchObservable.prototype.subscribeCore=function(o){var inner=new SerialDisposable,s=this.source.subscribe(new SwitchObserver(o,inner));return new CompositeDisposable(s,inner)};function SwitchObserver(o,inner){this.o=o;this.inner=inner;this.stopped=false;this.latest=0;this.hasLatest=false;this.isStopped=false}SwitchObserver.prototype.onNext=function(innerSource){if(this.isStopped){return}var d=new SingleAssignmentDisposable,id=++this.latest;this.hasLatest=true;this.inner.setDisposable(d);isPromise(innerSource)&&(innerSource=observableFromPromise(innerSource));d.setDisposable(innerSource.subscribe(new InnerObserver(this,id)))};SwitchObserver.prototype.onError=function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e)}};SwitchObserver.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=true;this.stopped=true;!this.hasLatest&&this.o.onCompleted()}};SwitchObserver.prototype.dispose=function(){this.isStopped=true};SwitchObserver.prototype.fail=function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e);return true}return false};function InnerObserver(parent,id){this.parent=parent;this.id=id;this.isStopped=false}InnerObserver.prototype.onNext=function(x){if(this.isStopped){return}this.parent.latest===this.id&&this.parent.o.onNext(x)};InnerObserver.prototype.onError=function(e){if(!this.isStopped){this.isStopped=true;this.parent.latest===this.id&&this.parent.o.onError(e)}};InnerObserver.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=true;if(this.parent.latest===this.id){this.parent.hasLatest=false;this.parent.isStopped&&this.parent.o.onCompleted()}}};InnerObserver.prototype.dispose=function(){this.isStopped=true};InnerObserver.prototype.fail=function(e){if(!this.isStopped){this.isStopped=true;this.parent.o.onError(e);return true}return false};return SwitchObservable}(ObservableBase);observableProto["switch"]=observableProto.switchLatest=function(){return new SwitchObservable(this)};var TakeUntilObservable=function(__super__){inherits(TakeUntilObservable,__super__);function TakeUntilObservable(source,other){this.source=source;this.other=isPromise(other)?observableFromPromise(other):other;__super__.call(this)}TakeUntilObservable.prototype.subscribeCore=function(o){return new CompositeDisposable(this.source.subscribe(o),this.other.subscribe(new InnerObserver(o)))};function InnerObserver(o){this.o=o;this.isStopped=false}InnerObserver.prototype.onNext=function(x){if(this.isStopped){return}this.o.onCompleted()};InnerObserver.prototype.onError=function(err){if(!this.isStopped){this.isStopped=true;this.o.onError(err)}};InnerObserver.prototype.onCompleted=function(){!this.isStopped&&(this.isStopped=true)};InnerObserver.prototype.dispose=function(){this.isStopped=true};InnerObserver.prototype.fail=function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e);return true}return false};return TakeUntilObservable}(ObservableBase);observableProto.takeUntil=function(other){return new TakeUntilObservable(this,other)};function falseFactory(){return false}observableProto.withLatestFrom=function(){var len=arguments.length,args=new Array(len);for(var i=0;i<len;i++){args[i]=arguments[i]}var resultSelector=args.pop(),source=this;Array.isArray(args[0])&&(args=args[0]);return new AnonymousObservable(function(observer){var n=args.length,hasValue=arrayInitialize(n,falseFactory),hasValueAll=false,values=new Array(n);var subscriptions=new Array(n+1);for(var idx=0;idx<n;idx++){(function(i){var other=args[i],sad=new SingleAssignmentDisposable;isPromise(other)&&(other=observableFromPromise(other));sad.setDisposable(other.subscribe(function(x){values[i]=x;hasValue[i]=true;hasValueAll=hasValue.every(identity)},function(e){observer.onError(e)},noop));subscriptions[i]=sad})(idx)}var sad=new SingleAssignmentDisposable;sad.setDisposable(source.subscribe(function(x){var allValues=[x].concat(values);if(!hasValueAll){return}var res=tryCatch(resultSelector).apply(null,allValues);if(res===errorObj){return observer.onError(res.e)}observer.onNext(res)},function(e){observer.onError(e)},function(){observer.onCompleted()}));subscriptions[n]=sad;return new CompositeDisposable(subscriptions)},this)};function zipArray(second,resultSelector){var first=this;return new AnonymousObservable(function(o){var index=0,len=second.length;return first.subscribe(function(left){if(index<len){var right=second[index++],res=tryCatch(resultSelector)(left,right);if(res===errorObj){return o.onError(res.e)}o.onNext(res)}else{o.onCompleted()}},function(e){o.onError(e)},function(){o.onCompleted()})},first)}function falseFactory(){return false}function emptyArrayFactory(){return[]}observableProto.zip=function(){if(Array.isArray(arguments[0])){return zipArray.apply(this,arguments)}var len=arguments.length,args=new Array(len);for(var i=0;i<len;i++){args[i]=arguments[i]}var parent=this,resultSelector=args.pop();args.unshift(parent);return new AnonymousObservable(function(o){var n=args.length,queues=arrayInitialize(n,emptyArrayFactory),isDone=arrayInitialize(n,falseFactory);var subscriptions=new Array(n);for(var idx=0;idx<n;idx++){(function(i){var source=args[i],sad=new SingleAssignmentDisposable;isPromise(source)&&(source=observableFromPromise(source));sad.setDisposable(source.subscribe(function(x){queues[i].push(x);if(queues.every(function(x){return x.length>0})){var queuedValues=queues.map(function(x){return x.shift()}),res=tryCatch(resultSelector).apply(parent,queuedValues);if(res===errorObj){return o.onError(res.e)}o.onNext(res)}else if(isDone.filter(function(x,j){return j!==i}).every(identity)){o.onCompleted()}},function(e){o.onError(e)},function(){isDone[i]=true;isDone.every(identity)&&o.onCompleted()}));subscriptions[i]=sad})(idx)}return new CompositeDisposable(subscriptions)},parent)};Observable.zip=function(){var len=arguments.length,args=new Array(len);for(var i=0;i<len;i++){args[i]=arguments[i]}var first=args.shift();return first.zip.apply(first,args)};function falseFactory(){return false}function arrayFactory(){return[]}Observable.zipArray=function(){var sources;if(Array.isArray(arguments[0])){sources=arguments[0]}else{var len=arguments.length;sources=new Array(len);for(var i=0;i<len;i++){sources[i]=arguments[i]}}return new AnonymousObservable(function(o){var n=sources.length,queues=arrayInitialize(n,arrayFactory),isDone=arrayInitialize(n,falseFactory);var subscriptions=new Array(n);for(var idx=0;idx<n;idx++){(function(i){subscriptions[i]=new SingleAssignmentDisposable;subscriptions[i].setDisposable(sources[i].subscribe(function(x){queues[i].push(x);if(queues.every(function(x){return x.length>0})){var res=queues.map(function(x){return x.shift()});o.onNext(res)}else if(isDone.filter(function(x,j){return j!==i}).every(identity)){return o.onCompleted()}},function(e){o.onError(e)},function(){isDone[i]=true;isDone.every(identity)&&o.onCompleted()}))})(idx)}return new CompositeDisposable(subscriptions)})};function asObservable(source){return function subscribe(o){return source.subscribe(o)}}observableProto.asObservable=function(){return new AnonymousObservable(asObservable(this),this)};function toArray(x){return x.toArray()}function notEmpty(x){return x.length>0}observableProto.bufferWithCount=function(count,skip){typeof skip!=="number"&&(skip=count);return this.windowWithCount(count,skip).flatMap(toArray).filter(notEmpty)};observableProto.dematerialize=function(){var source=this;return new AnonymousObservable(function(o){return source.subscribe(function(x){return x.accept(o)},function(e){o.onError(e)},function(){o.onCompleted()})},this)};var DistinctUntilChangedObservable=function(__super__){inherits(DistinctUntilChangedObservable,__super__);function DistinctUntilChangedObservable(source,keyFn,comparer){this.source=source;this.keyFn=keyFn;this.comparer=comparer;__super__.call(this)}DistinctUntilChangedObservable.prototype.subscribeCore=function(o){return this.source.subscribe(new DistinctUntilChangedObserver(o,this.keyFn,this.comparer))};return DistinctUntilChangedObservable}(ObservableBase);function DistinctUntilChangedObserver(o,keyFn,comparer){this.o=o;this.keyFn=keyFn;this.comparer=comparer;this.hasCurrentKey=false;this.currentKey=null;this.isStopped=false}DistinctUntilChangedObserver.prototype.onNext=function(x){if(this.isStopped){return}var key=x;if(isFunction(this.keyFn)){key=tryCatch(this.keyFn)(x);if(key===errorObj){return this.o.onError(key.e)}}if(this.hasCurrentKey){comparerEquals=tryCatch(this.comparer)(this.currentKey,key);if(comparerEquals===errorObj){return this.o.onError(comparerEquals.e)}}if(!this.hasCurrentKey||!comparerEquals){this.hasCurrentKey=true;this.currentKey=key;this.o.onNext(x)}};DistinctUntilChangedObserver.prototype.onError=function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e)}};DistinctUntilChangedObserver.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=true;this.o.onCompleted()}};DistinctUntilChangedObserver.prototype.dispose=function(){this.isStopped=true};DistinctUntilChangedObserver.prototype.fail=function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e);return true}return false};observableProto.distinctUntilChanged=function(keyFn,comparer){comparer||(comparer=defaultComparer);return new DistinctUntilChangedObservable(this,keyFn,comparer)};var TapObservable=function(__super__){inherits(TapObservable,__super__);function TapObservable(source,observerOrOnNext,onError,onCompleted){this.source=source;this._oN=observerOrOnNext;this._oE=onError;this._oC=onCompleted;__super__.call(this)}TapObservable.prototype.subscribeCore=function(o){return this.source.subscribe(new InnerObserver(o,this))};function InnerObserver(o,p){this.o=o;this.t=!p._oN||isFunction(p._oN)?observerCreate(p._oN||noop,p._oE||noop,p._oC||noop):p._oN;this.isStopped=false}InnerObserver.prototype.onNext=function(x){if(this.isStopped){return}var res=tryCatch(this.t.onNext).call(this.t,x);if(res===errorObj){this.o.onError(res.e)}this.o.onNext(x)};InnerObserver.prototype.onError=function(err){if(!this.isStopped){this.isStopped=true;var res=tryCatch(this.t.onError).call(this.t,err);if(res===errorObj){return this.o.onError(res.e)}this.o.onError(err)}};InnerObserver.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=true;var res=tryCatch(this.t.onCompleted).call(this.t);if(res===errorObj){return this.o.onError(res.e)}this.o.onCompleted()}};InnerObserver.prototype.dispose=function(){this.isStopped=true};InnerObserver.prototype.fail=function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e);return true}return false};return TapObservable}(ObservableBase);observableProto["do"]=observableProto.tap=observableProto.doAction=function(observerOrOnNext,onError,onCompleted){return new TapObservable(this,observerOrOnNext,onError,onCompleted)};observableProto.doOnNext=observableProto.tapOnNext=function(onNext,thisArg){return this.tap(typeof thisArg!=="undefined"?function(x){onNext.call(thisArg,x)}:onNext)};observableProto.doOnError=observableProto.tapOnError=function(onError,thisArg){return this.tap(noop,typeof thisArg!=="undefined"?function(e){onError.call(thisArg,e)}:onError)};observableProto.doOnCompleted=observableProto.tapOnCompleted=function(onCompleted,thisArg){return this.tap(noop,null,typeof thisArg!=="undefined"?function(){onCompleted.call(thisArg)}:onCompleted)};observableProto["finally"]=function(action){var source=this;return new AnonymousObservable(function(observer){var subscription=tryCatch(source.subscribe).call(source,observer);if(subscription===errorObj){action();return thrower(subscription.e)}return disposableCreate(function(){var r=tryCatch(subscription.dispose).call(subscription);action();r===errorObj&&thrower(r.e)})},this)};var IgnoreElementsObservable=function(__super__){inherits(IgnoreElementsObservable,__super__);function IgnoreElementsObservable(source){this.source=source;__super__.call(this)}IgnoreElementsObservable.prototype.subscribeCore=function(o){return this.source.subscribe(new InnerObserver(o))};function InnerObserver(o){this.o=o;this.isStopped=false}InnerObserver.prototype.onNext=noop;InnerObserver.prototype.onError=function(err){if(!this.isStopped){this.isStopped=true;this.o.onError(err)}};InnerObserver.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=true;this.o.onCompleted()}};InnerObserver.prototype.dispose=function(){this.isStopped=true};InnerObserver.prototype.fail=function(e){if(!this.isStopped){this.isStopped=true;this.observer.onError(e);return true}return false};return IgnoreElementsObservable}(ObservableBase);observableProto.ignoreElements=function(){return new IgnoreElementsObservable(this)};observableProto.materialize=function(){var source=this;return new AnonymousObservable(function(observer){return source.subscribe(function(value){observer.onNext(notificationCreateOnNext(value))},function(e){observer.onNext(notificationCreateOnError(e));observer.onCompleted()},function(){observer.onNext(notificationCreateOnCompleted());observer.onCompleted()})},source)};observableProto.repeat=function(repeatCount){return enumerableRepeat(this,repeatCount).concat()};observableProto.retry=function(retryCount){return enumerableRepeat(this,retryCount).catchError()};observableProto.retryWhen=function(notifier){return enumerableRepeat(this).catchErrorWhen(notifier)};var ScanObservable=function(__super__){inherits(ScanObservable,__super__);function ScanObservable(source,accumulator,hasSeed,seed){this.source=source;this.accumulator=accumulator;this.hasSeed=hasSeed;this.seed=seed;__super__.call(this)}ScanObservable.prototype.subscribeCore=function(o){return this.source.subscribe(new InnerObserver(o,this))};return ScanObservable}(ObservableBase);function InnerObserver(o,parent){this.o=o;this.accumulator=parent.accumulator;this.hasSeed=parent.hasSeed;this.seed=parent.seed;this.hasAccumulation=false;this.accumulation=null;this.hasValue=false;this.isStopped=false}InnerObserver.prototype={onNext:function(x){if(this.isStopped){return}!this.hasValue&&(this.hasValue=true);if(this.hasAccumulation){this.accumulation=tryCatch(this.accumulator)(this.accumulation,x)}else{this.accumulation=this.hasSeed?tryCatch(this.accumulator)(this.seed,x):x;this.hasAccumulation=true}if(this.accumulation===errorObj){return this.o.onError(this.accumulation.e)}this.o.onNext(this.accumulation)},onError:function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e)}},onCompleted:function(){if(!this.isStopped){this.isStopped=true;!this.hasValue&&this.hasSeed&&this.o.onNext(this.seed);this.o.onCompleted()}},dispose:function(){this.isStopped=true},fail:function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e);return true}return false}};observableProto.scan=function(){var hasSeed=false,seed,accumulator=arguments[0];if(arguments.length===2){hasSeed=true;seed=arguments[1]}return new ScanObservable(this,accumulator,hasSeed,seed)};observableProto.skipLast=function(count){if(count<0){throw new ArgumentOutOfRangeError}var source=this;return new AnonymousObservable(function(o){var q=[];return source.subscribe(function(x){q.push(x);q.length>count&&o.onNext(q.shift())},function(e){o.onError(e)},function(){o.onCompleted()})},source)};observableProto.startWith=function(){var values,scheduler,start=0;if(!!arguments.length&&isScheduler(arguments[0])){scheduler=arguments[0];start=1}else{scheduler=immediateScheduler}for(var args=[],i=start,len=arguments.length;i<len;i++){args.push(arguments[i])}return enumerableOf([observableFromArray(args,scheduler),this]).concat()};observableProto.takeLast=function(count){if(count<0){throw new ArgumentOutOfRangeError}var source=this;return new AnonymousObservable(function(o){var q=[];return source.subscribe(function(x){q.push(x);q.length>count&&q.shift()},function(e){o.onError(e)},function(){while(q.length>0){o.onNext(q.shift())}o.onCompleted()})},source)};observableProto.takeLastBuffer=function(count){var source=this;return new AnonymousObservable(function(o){var q=[];return source.subscribe(function(x){q.push(x);q.length>count&&q.shift()},function(e){o.onError(e)},function(){o.onNext(q);o.onCompleted()})},source)};observableProto.windowWithCount=function(count,skip){var source=this;+count||(count=0);Math.abs(count)===Infinity&&(count=0);if(count<=0){throw new ArgumentOutOfRangeError}skip==null&&(skip=count);+skip||(skip=0);Math.abs(skip)===Infinity&&(skip=0);if(skip<=0){throw new ArgumentOutOfRangeError}return new AnonymousObservable(function(observer){var m=new SingleAssignmentDisposable,refCountDisposable=new RefCountDisposable(m),n=0,q=[];function createWindow(){var s=new Subject;q.push(s);observer.onNext(addRef(s,refCountDisposable))}createWindow();m.setDisposable(source.subscribe(function(x){for(var i=0,len=q.length;i<len;i++){q[i].onNext(x)}var c=n-count+1;c>=0&&c%skip===0&&q.shift().onCompleted();++n%skip===0&&createWindow()},function(e){while(q.length>0){q.shift().onError(e)}observer.onError(e)},function(){while(q.length>0){q.shift().onCompleted()}observer.onCompleted()}));return refCountDisposable},source)};function concatMap(source,selector,thisArg){var selectorFunc=bindCallback(selector,thisArg,3);return source.map(function(x,i){var result=selectorFunc(x,i,source);isPromise(result)&&(result=observableFromPromise(result));(isArrayLike(result)||isIterable(result))&&(result=observableFrom(result));return result}).concatAll()}observableProto.selectConcat=observableProto.concatMap=function(selector,resultSelector,thisArg){if(isFunction(selector)&&isFunction(resultSelector)){return this.concatMap(function(x,i){var selectorResult=selector(x,i);isPromise(selectorResult)&&(selectorResult=observableFromPromise(selectorResult));(isArrayLike(selectorResult)||isIterable(selectorResult))&&(selectorResult=observableFrom(selectorResult));return selectorResult.map(function(y,i2){return resultSelector(x,y,i,i2)})})}return isFunction(selector)?concatMap(this,selector,thisArg):concatMap(this,function(){return selector})};observableProto.concatMapObserver=observableProto.selectConcatObserver=function(onNext,onError,onCompleted,thisArg){var source=this,onNextFunc=bindCallback(onNext,thisArg,2),onErrorFunc=bindCallback(onError,thisArg,1),onCompletedFunc=bindCallback(onCompleted,thisArg,0);return new AnonymousObservable(function(observer){var index=0;return source.subscribe(function(x){var result;try{result=onNextFunc(x,index++)}catch(e){observer.onError(e);return}isPromise(result)&&(result=observableFromPromise(result));observer.onNext(result)},function(err){var result;try{result=onErrorFunc(err)}catch(e){observer.onError(e);return}isPromise(result)&&(result=observableFromPromise(result));observer.onNext(result);observer.onCompleted()},function(){var result;try{result=onCompletedFunc()}catch(e){observer.onError(e);return}isPromise(result)&&(result=observableFromPromise(result));observer.onNext(result);observer.onCompleted()})},this).concatAll()};observableProto.defaultIfEmpty=function(defaultValue){var source=this;defaultValue===undefined&&(defaultValue=null);return new AnonymousObservable(function(observer){var found=false;return source.subscribe(function(x){found=true;observer.onNext(x)},function(e){observer.onError(e)},function(){!found&&observer.onNext(defaultValue);observer.onCompleted()})},source)};function arrayIndexOfComparer(array,item,comparer){for(var i=0,len=array.length;i<len;i++){if(comparer(array[i],item)){return i;
}}return-1}function HashSet(comparer){this.comparer=comparer;this.set=[]}HashSet.prototype.push=function(value){var retValue=arrayIndexOfComparer(this.set,value,this.comparer)===-1;retValue&&this.set.push(value);return retValue};observableProto.distinct=function(keySelector,comparer){var source=this;comparer||(comparer=defaultComparer);return new AnonymousObservable(function(o){var hashSet=new HashSet(comparer);return source.subscribe(function(x){var key=x;if(keySelector){try{key=keySelector(x)}catch(e){o.onError(e);return}}hashSet.push(key)&&o.onNext(x)},function(e){o.onError(e)},function(){o.onCompleted()})},this)};observableProto.groupBy=function(keySelector,elementSelector){return this.groupByUntil(keySelector,elementSelector,observableNever)};observableProto.groupByUntil=function(keySelector,elementSelector,durationSelector){var source=this;return new AnonymousObservable(function(o){var map=new Map,groupDisposable=new CompositeDisposable,refCountDisposable=new RefCountDisposable(groupDisposable),handleError=function(e){return function(item){item.onError(e)}};groupDisposable.add(source.subscribe(function(x){var key=tryCatch(keySelector)(x);if(key===errorObj){map.forEach(handleError(key.e));return o.onError(key.e)}var fireNewMapEntry=false,writer=map.get(key);if(writer===undefined){writer=new Subject;map.set(key,writer);fireNewMapEntry=true}if(fireNewMapEntry){var group=new GroupedObservable(key,writer,refCountDisposable),durationGroup=new GroupedObservable(key,writer);var duration=tryCatch(durationSelector)(durationGroup);if(duration===errorObj){map.forEach(handleError(duration.e));return o.onError(duration.e)}o.onNext(group);var md=new SingleAssignmentDisposable;groupDisposable.add(md);md.setDisposable(duration.take(1).subscribe(noop,function(e){map.forEach(handleError(e));o.onError(e)},function(){if(map["delete"](key)){writer.onCompleted()}groupDisposable.remove(md)}))}var element=x;if(isFunction(elementSelector)){element=tryCatch(elementSelector)(x);if(element===errorObj){map.forEach(handleError(element.e));return o.onError(element.e)}}writer.onNext(element)},function(e){map.forEach(handleError(e));o.onError(e)},function(){map.forEach(function(item){item.onCompleted()});o.onCompleted()}));return refCountDisposable},source)};var MapObservable=function(__super__){inherits(MapObservable,__super__);function MapObservable(source,selector,thisArg){this.source=source;this.selector=bindCallback(selector,thisArg,3);__super__.call(this)}function innerMap(selector,self){return function(x,i,o){return selector.call(this,self.selector(x,i,o),i,o)}}MapObservable.prototype.internalMap=function(selector,thisArg){return new MapObservable(this.source,innerMap(selector,this),thisArg)};MapObservable.prototype.subscribeCore=function(o){return this.source.subscribe(new InnerObserver(o,this.selector,this))};function InnerObserver(o,selector,source){this.o=o;this.selector=selector;this.source=source;this.i=0;this.isStopped=false}InnerObserver.prototype.onNext=function(x){if(this.isStopped){return}var result=tryCatch(this.selector)(x,this.i++,this.source);if(result===errorObj){return this.o.onError(result.e)}this.o.onNext(result)};InnerObserver.prototype.onError=function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e)}};InnerObserver.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=true;this.o.onCompleted()}};InnerObserver.prototype.dispose=function(){this.isStopped=true};InnerObserver.prototype.fail=function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e);return true}return false};return MapObservable}(ObservableBase);observableProto.map=observableProto.select=function(selector,thisArg){var selectorFn=typeof selector==="function"?selector:function(){return selector};return this instanceof MapObservable?this.internalMap(selectorFn,thisArg):new MapObservable(this,selectorFn,thisArg)};function plucker(args,len){return function mapper(x){var currentProp=x;for(var i=0;i<len;i++){var p=currentProp[args[i]];if(typeof p!=="undefined"){currentProp=p}else{return undefined}}return currentProp}}observableProto.pluck=function(){var len=arguments.length,args=new Array(len);if(len===0){throw new Error("List of properties cannot be empty.")}for(var i=0;i<len;i++){args[i]=arguments[i]}return this.map(plucker(args,len))};observableProto.flatMap=observableProto.selectMany=function(selector,resultSelector,thisArg){return new FlatMapObservable(this,selector,resultSelector,thisArg).mergeAll()};observableProto.flatMapObserver=observableProto.selectManyObserver=function(onNext,onError,onCompleted,thisArg){var source=this;return new AnonymousObservable(function(observer){var index=0;return source.subscribe(function(x){var result;try{result=onNext.call(thisArg,x,index++)}catch(e){observer.onError(e);return}isPromise(result)&&(result=observableFromPromise(result));observer.onNext(result)},function(err){var result;try{result=onError.call(thisArg,err)}catch(e){observer.onError(e);return}isPromise(result)&&(result=observableFromPromise(result));observer.onNext(result);observer.onCompleted()},function(){var result;try{result=onCompleted.call(thisArg)}catch(e){observer.onError(e);return}isPromise(result)&&(result=observableFromPromise(result));observer.onNext(result);observer.onCompleted()})},source).mergeAll()};Rx.Observable.prototype.flatMapLatest=function(selector,resultSelector,thisArg){return new FlatMapObservable(this,selector,resultSelector,thisArg).switchLatest()};var SkipObservable=function(__super__){inherits(SkipObservable,__super__);function SkipObservable(source,count){this.source=source;this.skipCount=count;__super__.call(this)}SkipObservable.prototype.subscribeCore=function(o){return this.source.subscribe(new InnerObserver(o,this.skipCount))};function InnerObserver(o,c){this.c=c;this.r=c;this.o=o;this.isStopped=false}InnerObserver.prototype.onNext=function(x){if(this.isStopped){return}if(this.r<=0){this.o.onNext(x)}else{this.r--}};InnerObserver.prototype.onError=function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e)}};InnerObserver.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=true;this.o.onCompleted()}};InnerObserver.prototype.dispose=function(){this.isStopped=true};InnerObserver.prototype.fail=function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e);return true}return false};return SkipObservable}(ObservableBase);observableProto.skip=function(count){if(count<0){throw new ArgumentOutOfRangeError}return new SkipObservable(this,count)};observableProto.skipWhile=function(predicate,thisArg){var source=this,callback=bindCallback(predicate,thisArg,3);return new AnonymousObservable(function(o){var i=0,running=false;return source.subscribe(function(x){if(!running){try{running=!callback(x,i++,source)}catch(e){o.onError(e);return}}running&&o.onNext(x)},function(e){o.onError(e)},function(){o.onCompleted()})},source)};observableProto.take=function(count,scheduler){if(count<0){throw new ArgumentOutOfRangeError}if(count===0){return observableEmpty(scheduler)}var source=this;return new AnonymousObservable(function(o){var remaining=count;return source.subscribe(function(x){if(remaining-->0){o.onNext(x);remaining<=0&&o.onCompleted()}},function(e){o.onError(e)},function(){o.onCompleted()})},source)};observableProto.takeWhile=function(predicate,thisArg){var source=this,callback=bindCallback(predicate,thisArg,3);return new AnonymousObservable(function(o){var i=0,running=true;return source.subscribe(function(x){if(running){try{running=callback(x,i++,source)}catch(e){o.onError(e);return}if(running){o.onNext(x)}else{o.onCompleted()}}},function(e){o.onError(e)},function(){o.onCompleted()})},source)};var FilterObservable=function(__super__){inherits(FilterObservable,__super__);function FilterObservable(source,predicate,thisArg){this.source=source;this.predicate=bindCallback(predicate,thisArg,3);__super__.call(this)}FilterObservable.prototype.subscribeCore=function(o){return this.source.subscribe(new InnerObserver(o,this.predicate,this))};function innerPredicate(predicate,self){return function(x,i,o){return self.predicate(x,i,o)&&predicate.call(this,x,i,o)}}FilterObservable.prototype.internalFilter=function(predicate,thisArg){return new FilterObservable(this.source,innerPredicate(predicate,this),thisArg)};function InnerObserver(o,predicate,source){this.o=o;this.predicate=predicate;this.source=source;this.i=0;this.isStopped=false}InnerObserver.prototype.onNext=function(x){if(this.isStopped){return}var shouldYield=tryCatch(this.predicate)(x,this.i++,this.source);if(shouldYield===errorObj){return this.o.onError(shouldYield.e)}shouldYield&&this.o.onNext(x)};InnerObserver.prototype.onError=function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e)}};InnerObserver.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=true;this.o.onCompleted()}};InnerObserver.prototype.dispose=function(){this.isStopped=true};InnerObserver.prototype.fail=function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e);return true}return false};return FilterObservable}(ObservableBase);observableProto.filter=observableProto.where=function(predicate,thisArg){return this instanceof FilterObservable?this.internalFilter(predicate,thisArg):new FilterObservable(this,predicate,thisArg)};function extremaBy(source,keySelector,comparer){return new AnonymousObservable(function(o){var hasValue=false,lastKey=null,list=[];return source.subscribe(function(x){var comparison,key;try{key=keySelector(x)}catch(ex){o.onError(ex);return}comparison=0;if(!hasValue){hasValue=true;lastKey=key}else{try{comparison=comparer(key,lastKey)}catch(ex1){o.onError(ex1);return}}if(comparison>0){lastKey=key;list=[]}if(comparison>=0){list.push(x)}},function(e){o.onError(e)},function(){o.onNext(list);o.onCompleted()})},source)}function firstOnly(x){if(x.length===0){throw new EmptyError}return x[0]}var ReduceObservable=function(__super__){inherits(ReduceObservable,__super__);function ReduceObservable(source,acc,hasSeed,seed){this.source=source;this.acc=acc;this.hasSeed=hasSeed;this.seed=seed;__super__.call(this)}ReduceObservable.prototype.subscribeCore=function(observer){return this.source.subscribe(new InnerObserver(observer,this))};function InnerObserver(o,parent){this.o=o;this.acc=parent.acc;this.hasSeed=parent.hasSeed;this.seed=parent.seed;this.hasAccumulation=false;this.result=null;this.hasValue=false;this.isStopped=false}InnerObserver.prototype.onNext=function(x){if(this.isStopped){return}!this.hasValue&&(this.hasValue=true);if(this.hasAccumulation){this.result=tryCatch(this.acc)(this.result,x)}else{this.result=this.hasSeed?tryCatch(this.acc)(this.seed,x):x;this.hasAccumulation=true}if(this.result===errorObj){this.o.onError(this.result.e)}};InnerObserver.prototype.onError=function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e)}};InnerObserver.prototype.onCompleted=function(){if(!this.isStopped){this.isStopped=true;this.hasValue&&this.o.onNext(this.result);!this.hasValue&&this.hasSeed&&this.o.onNext(this.seed);!this.hasValue&&!this.hasSeed&&this.o.onError(new EmptyError);this.o.onCompleted()}};InnerObserver.prototype.dispose=function(){this.isStopped=true};InnerObserver.prototype.fail=function(e){if(!this.isStopped){this.isStopped=true;this.o.onError(e);return true}return false};return ReduceObservable}(ObservableBase);observableProto.reduce=function(accumulator){var hasSeed=false;if(arguments.length===2){hasSeed=true;var seed=arguments[1]}return new ReduceObservable(this,accumulator,hasSeed,seed)};var SomeObserver=function(__super__){inherits(SomeObserver,__super__);function SomeObserver(o,fn,s){this._o=o;this._fn=fn;this._s=s;this._i=0;__super__.call(this)}SomeObserver.prototype.next=function(x){var result=tryCatch(this._fn)(x,this._i++,this._s);if(result===errorObj){return this._o.onError(result.e)}if(Boolean(result)){this._o.onNext(true);this._o.onCompleted()}};SomeObserver.prototype.error=function(e){this._o.onError(e)};SomeObserver.prototype.completed=function(){this._o.onNext(false);this._o.onCompleted()};return SomeObserver}(AbstractObserver);observableProto.some=function(predicate,thisArg){var source=this,fn=bindCallback(predicate,thisArg,3);return new AnonymousObservable(function(o){return source.subscribe(new SomeObserver(o,fn,source))})};var IsEmptyObserver=function(__super__){inherits(IsEmptyObserver,__super__);function IsEmptyObserver(o){this._o=o;__super__.call(this)}IsEmptyObserver.prototype.next=function(){this._o.onNext(false);this._o.onCompleted()};IsEmptyObserver.prototype.error=function(e){this._o.onError(e)};IsEmptyObserver.prototype.completed=function(){this._o.onNext(true);this._o.onCompleted()};return IsEmptyObserver}(AbstractObserver);observableProto.isEmpty=function(){var source=this;return new AnonymousObservable(function(o){return source.subscribe(new IsEmptyObserver(o))},source)};var EveryObserver=function(__super__){inherits(EveryObserver,__super__);function EveryObserver(o,fn,s){this._o=o;this._fn=fn;this._s=s;this._i=0;__super__.call(this)}EveryObserver.prototype.next=function(x){var result=tryCatch(this._fn)(x,this._i++,this._s);if(result===errorObj){return this._o.onError(result.e)}if(!Boolean(result)){this._o.onNext(false);this._o.onCompleted()}};EveryObserver.prototype.error=function(e){this._o.onError(e)};EveryObserver.prototype.completed=function(){this._o.onNext(true);this._o.onCompleted()};return EveryObserver}(AbstractObserver);observableProto.every=function(predicate,thisArg){var source=this,fn=bindCallback(predicate,thisArg,3);return new AnonymousObservable(function(o){return source.subscribe(new EveryObserver(o,fn,source))},this)};observableProto.includes=function(searchElement,fromIndex){var source=this;function comparer(a,b){return a===0&&b===0||(a===b||isNaN(a)&&isNaN(b))}return new AnonymousObservable(function(o){var i=0,n=+fromIndex||0;Math.abs(n)===Infinity&&(n=0);if(n<0){o.onNext(false);o.onCompleted();return disposableEmpty}return source.subscribe(function(x){if(i++>=n&&comparer(x,searchElement)){o.onNext(true);o.onCompleted()}},function(e){o.onError(e)},function(){o.onNext(false);o.onCompleted()})},this)};observableProto.contains=function(searchElement,fromIndex){observableProto.includes(searchElement,fromIndex)};observableProto.count=function(predicate,thisArg){return predicate?this.filter(predicate,thisArg).count():this.reduce(function(count){return count+1},0)};observableProto.indexOf=function(searchElement,fromIndex){var source=this;return new AnonymousObservable(function(o){var i=0,n=+fromIndex||0;Math.abs(n)===Infinity&&(n=0);if(n<0){o.onNext(-1);o.onCompleted();return disposableEmpty}return source.subscribe(function(x){if(i>=n&&x===searchElement){o.onNext(i);o.onCompleted()}i++},function(e){o.onError(e)},function(){o.onNext(-1);o.onCompleted()})},source)};observableProto.sum=function(keySelector,thisArg){return keySelector&&isFunction(keySelector)?this.map(keySelector,thisArg).sum():this.reduce(function(prev,curr){return prev+curr},0)};observableProto.minBy=function(keySelector,comparer){comparer||(comparer=defaultSubComparer);return extremaBy(this,keySelector,function(x,y){return comparer(x,y)*-1})};observableProto.min=function(comparer){return this.minBy(identity,comparer).map(function(x){return firstOnly(x)})};observableProto.maxBy=function(keySelector,comparer){comparer||(comparer=defaultSubComparer);return extremaBy(this,keySelector,comparer)};observableProto.max=function(comparer){return this.maxBy(identity,comparer).map(function(x){return firstOnly(x)})};var AverageObserver=function(__super__){inherits(AverageObserver,__super__);function AverageObserver(o,fn,s){this._o=o;this._fn=fn;this._s=s;this._c=0;this._t=0;__super__.call(this)}AverageObserver.prototype.next=function(x){if(this._fn){var r=tryCatch(this._fn)(x,this._c++,this._s);if(r===errorObj){return this._o.onError(r.e)}this._t+=r}else{this._c++;this._t+=x}};AverageObserver.prototype.error=function(e){this._o.onError(e)};AverageObserver.prototype.completed=function(){if(this._c===0){return this._o.onError(new EmptyError)}this._o.onNext(this._t/this._c);this._o.onCompleted()};return AverageObserver}(AbstractObserver);observableProto.average=function(keySelector,thisArg){var source=this,fn;if(isFunction(keySelector)){fn=bindCallback(keySelector,thisArg,3)}return new AnonymousObservable(function(o){return source.subscribe(new AverageObserver(o,fn,source))},source)};observableProto.sequenceEqual=function(second,comparer){var first=this;comparer||(comparer=defaultComparer);return new AnonymousObservable(function(o){var donel=false,doner=false,ql=[],qr=[];var subscription1=first.subscribe(function(x){var equal,v;if(qr.length>0){v=qr.shift();try{equal=comparer(v,x)}catch(e){o.onError(e);return}if(!equal){o.onNext(false);o.onCompleted()}}else if(doner){o.onNext(false);o.onCompleted()}else{ql.push(x)}},function(e){o.onError(e)},function(){donel=true;if(ql.length===0){if(qr.length>0){o.onNext(false);o.onCompleted()}else if(doner){o.onNext(true);o.onCompleted()}}});(isArrayLike(second)||isIterable(second))&&(second=observableFrom(second));isPromise(second)&&(second=observableFromPromise(second));var subscription2=second.subscribe(function(x){var equal;if(ql.length>0){var v=ql.shift();try{equal=comparer(v,x)}catch(exception){o.onError(exception);return}if(!equal){o.onNext(false);o.onCompleted()}}else if(donel){o.onNext(false);o.onCompleted()}else{qr.push(x)}},function(e){o.onError(e)},function(){doner=true;if(qr.length===0){if(ql.length>0){o.onNext(false);o.onCompleted()}else if(donel){o.onNext(true);o.onCompleted()}}});return new CompositeDisposable(subscription1,subscription2)},first)};observableProto.elementAt=function(index,defaultValue){if(index<0){throw new ArgumentOutOfRangeError}var source=this;return new AnonymousObservable(function(o){var i=index;return source.subscribe(function(x){if(i--===0){o.onNext(x);o.onCompleted()}},function(e){o.onError(e)},function(){if(defaultValue===undefined){o.onError(new ArgumentOutOfRangeError)}else{o.onNext(defaultValue);o.onCompleted()}})},source)};observableProto.single=function(predicate,thisArg){if(isFunction(predicate)){return this.filter(predicate,thisArg).single()}var source=this;return new AnonymousObservable(function(o){var value,seenValue=false;return source.subscribe(function(x){if(seenValue){o.onError(new Error("Sequence contains more than one element"))}else{value=x;seenValue=true}},function(e){o.onError(e)},function(){o.onNext(value);o.onCompleted()})},source)};var FirstObserver=function(__super__){inherits(FirstObserver,__super__);function FirstObserver(o,obj,s){this._o=o;this._obj=obj;this._s=s;this._i=0;__super__.call(this)}FirstObserver.prototype.next=function(x){if(this._obj.predicate){var res=tryCatch(this._obj.predicate)(x,this._i++,this._s);if(res===errorObj){return this._o.onError(res.e)}if(Boolean(res)){this._o.onNext(x);this._o.onCompleted()}}else if(!this._obj.predicate){this._o.onNext(x);this._o.onCompleted()}};FirstObserver.prototype.error=function(e){this._o.onError(e)};FirstObserver.prototype.completed=function(){if(this._obj.defaultValue===undefined){this._o.onError(new EmptyError)}else{this._o.onNext(this._obj.defaultValue);this._o.onCompleted()}};return FirstObserver}(AbstractObserver);observableProto.first=function(){var obj={},source=this;if(typeof arguments[0]==="object"){obj=arguments[0]}else{obj={predicate:arguments[0],thisArg:arguments[1],defaultValue:arguments[2]}}if(isFunction(obj.predicate)){var fn=obj.predicate;obj.predicate=bindCallback(fn,obj.thisArg,3)}return new AnonymousObservable(function(o){return source.subscribe(new FirstObserver(o,obj,source))},source)};observableProto.last=function(){var obj={},source=this;if(typeof arguments[0]==="object"){obj=arguments[0]}else{obj={predicate:arguments[0],thisArg:arguments[1],defaultValue:arguments[2]}}if(isFunction(obj.predicate)){var fn=obj.predicate;obj.predicate=bindCallback(fn,obj.thisArg,3)}return new AnonymousObservable(function(o){var value,seenValue=false,i=0;return source.subscribe(function(x){if(obj.predicate){var res=tryCatch(obj.predicate)(x,i++,source);if(res===errorObj){return o.onError(res.e)}if(res){seenValue=true;value=x}}else if(!obj.predicate){seenValue=true;value=x}},function(e){o.onError(e)},function(){if(seenValue){o.onNext(value);o.onCompleted()}else if(obj.defaultValue===undefined){o.onError(new EmptyError)}else{o.onNext(obj.defaultValue);o.onCompleted()}})},source)};function findValue(source,predicate,thisArg,yieldIndex){var callback=bindCallback(predicate,thisArg,3);return new AnonymousObservable(function(o){var i=0;return source.subscribe(function(x){var shouldRun;try{shouldRun=callback(x,i,source)}catch(e){o.onError(e);return}if(shouldRun){o.onNext(yieldIndex?i:x);o.onCompleted()}else{i++}},function(e){o.onError(e)},function(){o.onNext(yieldIndex?-1:undefined);o.onCompleted()})},source)}observableProto.find=function(predicate,thisArg){return findValue(this,predicate,thisArg,false)};observableProto.findIndex=function(predicate,thisArg){return findValue(this,predicate,thisArg,true)};observableProto.toSet=function(){if(typeof root.Set==="undefined"){throw new TypeError}var source=this;return new AnonymousObservable(function(o){var s=new root.Set;return source.subscribe(function(x){s.add(x)},function(e){o.onError(e)},function(){o.onNext(s);o.onCompleted()})},source)};observableProto.toMap=function(keySelector,elementSelector){if(typeof root.Map==="undefined"){throw new TypeError}var source=this;return new AnonymousObservable(function(o){var m=new root.Map;return source.subscribe(function(x){var key;try{key=keySelector(x)}catch(e){o.onError(e);return}var element=x;if(elementSelector){try{element=elementSelector(x)}catch(e){o.onError(e);return}}m.set(key,element)},function(e){o.onError(e)},function(){o.onNext(m);o.onCompleted()})},source)};var wrap=Observable.wrap=function(fn){createObservable.__generatorFunction__=fn;return createObservable;function createObservable(){return Observable.spawn.call(this,fn.apply(this,arguments))}};var spawn=Observable.spawn=function(){var gen=arguments[0],self=this,args=[];for(var i=1,len=arguments.length;i<len;i++){args.push(arguments[i])}return new AnonymousObservable(function(o){var g=new CompositeDisposable;if(isFunction(gen)){gen=gen.apply(self,args)}if(!gen||!isFunction(gen.next)){o.onNext(gen);return o.onCompleted()}processGenerator();function processGenerator(res){var ret=tryCatch(gen.next).call(gen,res);if(ret===errorObj){return o.onError(ret.e)}next(ret)}function onError(err){var ret=tryCatch(gen.next).call(gen,err);if(ret===errorObj){return o.onError(ret.e)}next(ret)}function next(ret){if(ret.done){o.onNext(ret.value);o.onCompleted();return}var value=toObservable.call(self,ret.value);if(Observable.isObservable(value)){g.add(value.subscribe(processGenerator,onError))}else{onError(new TypeError("type not supported"))}}return g})};function toObservable(obj){if(!obj){return obj}if(Observable.isObservable(obj)){return obj}if(isPromise(obj)){return Observable.fromPromise(obj)}if(isGeneratorFunction(obj)||isGenerator(obj)){return spawn.call(this,obj)}if(isFunction(obj)){return thunkToObservable.call(this,obj)}if(isArrayLike(obj)||isIterable(obj)){return arrayToObservable.call(this,obj)}if(isObject(obj)){return objectToObservable.call(this,obj)}return obj}function arrayToObservable(obj){return Observable.from(obj).flatMap(toObservable).toArray()}function objectToObservable(obj){var results=new obj.constructor,keys=Object.keys(obj),observables=[];for(var i=0,len=keys.length;i<len;i++){var key=keys[i];var observable=toObservable.call(this,obj[key]);if(observable&&Observable.isObservable(observable)){defer(observable,key)}else{results[key]=obj[key]}}return Observable.forkJoin.apply(Observable,observables).map(function(){return results});function defer(observable,key){results[key]=undefined;observables.push(observable.map(function(next){results[key]=next}))}}function thunkToObservable(fn){var self=this;return new AnonymousObservable(function(o){fn.call(self,function(){var err=arguments[0],res=arguments[1];if(err){return o.onError(err)}if(arguments.length>2){var args=[];for(var i=1,len=arguments.length;i<len;i++){args.push(arguments[i])}res=args}o.onNext(res);o.onCompleted()})})}function isGenerator(obj){return isFunction(obj.next)&&isFunction(obj.throw)}function isGeneratorFunction(obj){var ctor=obj.constructor;if(!ctor){return false}if(ctor.name==="GeneratorFunction"||ctor.displayName==="GeneratorFunction"){return true}return isGenerator(ctor.prototype)}Observable.start=function(func,context,scheduler){return observableToAsync(func,context,scheduler)()};var observableToAsync=Observable.toAsync=function(func,context,scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);return function(){var args=arguments,subject=new AsyncSubject;scheduler.schedule(function(){var result;try{result=func.apply(context,args)}catch(e){subject.onError(e);return}subject.onNext(result);subject.onCompleted()});return subject.asObservable()}};function createCbObservable(fn,ctx,selector,args){var o=new AsyncSubject;args.push(createCbHandler(o,ctx,selector));fn.apply(ctx,args);return o.asObservable()}function createCbHandler(o,ctx,selector){return function handler(){var len=arguments.length,results=new Array(len);for(var i=0;i<len;i++){results[i]=arguments[i]}if(isFunction(selector)){results=tryCatch(selector).apply(ctx,results);if(results===errorObj){return o.onError(results.e)}o.onNext(results)}else{if(results.length<=1){o.onNext(results[0])}else{o.onNext(results)}}o.onCompleted()}}Observable.fromCallback=function(fn,ctx,selector){return function(){typeof ctx==="undefined"&&(ctx=this);var len=arguments.length,args=new Array(len);for(var i=0;i<len;i++){args[i]=arguments[i]}return createCbObservable(fn,ctx,selector,args)}};function createNodeObservable(fn,ctx,selector,args){var o=new AsyncSubject;args.push(createNodeHandler(o,ctx,selector));fn.apply(ctx,args);return o.asObservable()}function createNodeHandler(o,ctx,selector){return function handler(){var err=arguments[0];if(err){return o.onError(err)}var len=arguments.length,results=[];for(var i=1;i<len;i++){results[i-1]=arguments[i]}if(isFunction(selector)){var results=tryCatch(selector).apply(ctx,results);if(results===errorObj){return o.onError(results.e)}o.onNext(results)}else{if(results.length<=1){o.onNext(results[0])}else{o.onNext(results)}}o.onCompleted()}}Observable.fromNodeCallback=function(fn,ctx,selector){return function(){typeof ctx==="undefined"&&(ctx=this);var len=arguments.length,args=new Array(len);for(var i=0;i<len;i++){args[i]=arguments[i]}return createNodeObservable(fn,ctx,selector,args)}};function ListenDisposable(e,n,fn){this._e=e;this._n=n;this._fn=fn;this._e.addEventListener(this._n,this._fn,false);this.isDisposed=false}ListenDisposable.prototype.dispose=function(){if(!this.isDisposed){this._e.removeEventListener(this._n,this._fn,false);this.isDisposed=true}};function createEventListener(el,eventName,handler){var disposables=new CompositeDisposable;var elemToString=Object.prototype.toString.call(el);if(elemToString==="[object NodeList]"||elemToString==="[object HTMLCollection]"){for(var i=0,len=el.length;i<len;i++){disposables.add(createEventListener(el.item(i),eventName,handler))}}else if(el){disposables.add(new ListenDisposable(el,eventName,handler))}return disposables}Rx.config.useNativeEvents=false;function eventHandler(o,selector){return function handler(){var results=arguments[0];if(isFunction(selector)){results=tryCatch(selector).apply(null,arguments);if(results===errorObj){return o.onError(results.e)}}o.onNext(results)}}Observable.fromEvent=function(element,eventName,selector){if(element.addListener){return fromEventPattern(function(h){element.addListener(eventName,h)},function(h){element.removeListener(eventName,h)},selector)}if(!Rx.config.useNativeEvents){if(typeof element.on==="function"&&typeof element.off==="function"){return fromEventPattern(function(h){element.on(eventName,h)},function(h){element.off(eventName,h)},selector)}}return new AnonymousObservable(function(o){return createEventListener(element,eventName,eventHandler(o,selector))}).publish().refCount()};var fromEventPattern=Observable.fromEventPattern=function(addHandler,removeHandler,selector,scheduler){isScheduler(scheduler)||(scheduler=immediateScheduler);return new AnonymousObservable(function(o){function innerHandler(){var result=arguments[0];if(isFunction(selector)){result=tryCatch(selector).apply(null,arguments);if(result===errorObj){return o.onError(result.e)}}o.onNext(result)}var returnValue=addHandler(innerHandler);return disposableCreate(function(){isFunction(removeHandler)&&removeHandler(innerHandler,returnValue)})}).publish().refCount()};Observable.startAsync=function(functionAsync){var promise;try{promise=functionAsync()}catch(e){return observableThrow(e)}return observableFromPromise(promise)};var PausableObservable=function(__super__){inherits(PausableObservable,__super__);function subscribe(observer){var conn=this.source.publish(),subscription=conn.subscribe(observer),connection=disposableEmpty;var pausable=this.pauser.distinctUntilChanged().subscribe(function(b){if(b){connection=conn.connect()}else{connection.dispose();connection=disposableEmpty}});return new CompositeDisposable(subscription,connection,pausable)}function PausableObservable(source,pauser){this.source=source;this.controller=new Subject;if(pauser&&pauser.subscribe){this.pauser=this.controller.merge(pauser)}else{this.pauser=this.controller}__super__.call(this,subscribe,source)}PausableObservable.prototype.pause=function(){this.controller.onNext(false)};PausableObservable.prototype.resume=function(){this.controller.onNext(true)};return PausableObservable}(Observable);observableProto.pausable=function(pauser){return new PausableObservable(this,pauser)};function combineLatestSource(source,subject,resultSelector){return new AnonymousObservable(function(o){var hasValue=[false,false],hasValueAll=false,isDone=false,values=new Array(2),err;function next(x,i){values[i]=x;hasValue[i]=true;if(hasValueAll||(hasValueAll=hasValue.every(identity))){if(err){return o.onError(err)}var res=tryCatch(resultSelector).apply(null,values);if(res===errorObj){return o.onError(res.e)}o.onNext(res)}isDone&&values[1]&&o.onCompleted()}return new CompositeDisposable(source.subscribe(function(x){next(x,0)},function(e){if(values[1]){o.onError(e)}else{err=e}},function(){isDone=true;values[1]&&o.onCompleted()}),subject.subscribe(function(x){next(x,1)},function(e){o.onError(e)},function(){isDone=true;next(true,1)}))},source)}var PausableBufferedObservable=function(__super__){inherits(PausableBufferedObservable,__super__);function subscribe(o){var q=[],previousShouldFire;function drainQueue(){while(q.length>0){o.onNext(q.shift())}}var subscription=combineLatestSource(this.source,this.pauser.startWith(false).distinctUntilChanged(),function(data,shouldFire){return{data:data,shouldFire:shouldFire}}).subscribe(function(results){if(previousShouldFire!==undefined&&results.shouldFire!=previousShouldFire){previousShouldFire=results.shouldFire;if(results.shouldFire){drainQueue()}}else{previousShouldFire=results.shouldFire;if(results.shouldFire){o.onNext(results.data)}else{q.push(results.data)}}},function(err){drainQueue();o.onError(err)},function(){drainQueue();o.onCompleted()});return subscription}function PausableBufferedObservable(source,pauser){this.source=source;this.controller=new Subject;if(pauser&&pauser.subscribe){this.pauser=this.controller.merge(pauser)}else{this.pauser=this.controller}__super__.call(this,subscribe,source)}PausableBufferedObservable.prototype.pause=function(){this.controller.onNext(false)};PausableBufferedObservable.prototype.resume=function(){this.controller.onNext(true)};return PausableBufferedObservable}(Observable);observableProto.pausableBuffered=function(subject){return new PausableBufferedObservable(this,subject)};var ControlledObservable=function(__super__){inherits(ControlledObservable,__super__);
function subscribe(observer){return this.source.subscribe(observer)}function ControlledObservable(source,enableQueue,scheduler){__super__.call(this,subscribe,source);this.subject=new ControlledSubject(enableQueue,scheduler);this.source=source.multicast(this.subject).refCount()}ControlledObservable.prototype.request=function(numberOfItems){return this.subject.request(numberOfItems==null?-1:numberOfItems)};return ControlledObservable}(Observable);var ControlledSubject=function(__super__){function subscribe(observer){return this.subject.subscribe(observer)}inherits(ControlledSubject,__super__);function ControlledSubject(enableQueue,scheduler){enableQueue==null&&(enableQueue=true);__super__.call(this,subscribe);this.subject=new Subject;this.enableQueue=enableQueue;this.queue=enableQueue?[]:null;this.requestedCount=0;this.requestedDisposable=null;this.error=null;this.hasFailed=false;this.hasCompleted=false;this.scheduler=scheduler||currentThreadScheduler}addProperties(ControlledSubject.prototype,Observer,{onCompleted:function(){this.hasCompleted=true;if(!this.enableQueue||this.queue.length===0){this.subject.onCompleted();this.disposeCurrentRequest()}else{this.queue.push(Notification.createOnCompleted())}},onError:function(error){this.hasFailed=true;this.error=error;if(!this.enableQueue||this.queue.length===0){this.subject.onError(error);this.disposeCurrentRequest()}else{this.queue.push(Notification.createOnError(error))}},onNext:function(value){if(this.requestedCount<=0){this.enableQueue&&this.queue.push(Notification.createOnNext(value))}else{this.requestedCount--===0&&this.disposeCurrentRequest();this.subject.onNext(value)}},_processRequest:function(numberOfItems){if(this.enableQueue){while(this.queue.length>0&&(numberOfItems>0||this.queue[0].kind!=="N")){var first=this.queue.shift();first.accept(this.subject);if(first.kind==="N"){numberOfItems--}else{this.disposeCurrentRequest();this.queue=[]}}}return numberOfItems},request:function(number){this.disposeCurrentRequest();var self=this;this.requestedDisposable=this.scheduler.scheduleWithState(number,function(s,i){var remaining=self._processRequest(i);var stopped=self.hasCompleted||self.hasFailed;if(!stopped&&remaining>0){self.requestedCount=remaining;return disposableCreate(function(){self.requestedCount=0})}});return this.requestedDisposable},disposeCurrentRequest:function(){if(this.requestedDisposable){this.requestedDisposable.dispose();this.requestedDisposable=null}}});return ControlledSubject}(Observable);observableProto.controlled=function(enableQueue,scheduler){if(enableQueue&&isScheduler(enableQueue)){scheduler=enableQueue;enableQueue=true}if(enableQueue==null){enableQueue=true}return new ControlledObservable(this,enableQueue,scheduler)};var StopAndWaitObservable=function(__super__){function subscribe(observer){this.subscription=this.source.subscribe(new StopAndWaitObserver(observer,this,this.subscription));var self=this;timeoutScheduler.schedule(function(){self.source.request(1)});return this.subscription}inherits(StopAndWaitObservable,__super__);function StopAndWaitObservable(source){__super__.call(this,subscribe,source);this.source=source}var StopAndWaitObserver=function(__sub__){inherits(StopAndWaitObserver,__sub__);function StopAndWaitObserver(observer,observable,cancel){__sub__.call(this);this.observer=observer;this.observable=observable;this.cancel=cancel}var stopAndWaitObserverProto=StopAndWaitObserver.prototype;stopAndWaitObserverProto.completed=function(){this.observer.onCompleted();this.dispose()};stopAndWaitObserverProto.error=function(error){this.observer.onError(error);this.dispose()};stopAndWaitObserverProto.next=function(value){this.observer.onNext(value);var self=this;timeoutScheduler.schedule(function(){self.observable.source.request(1)})};stopAndWaitObserverProto.dispose=function(){this.observer=null;if(this.cancel){this.cancel.dispose();this.cancel=null}__sub__.prototype.dispose.call(this)};return StopAndWaitObserver}(AbstractObserver);return StopAndWaitObservable}(Observable);ControlledObservable.prototype.stopAndWait=function(){return new StopAndWaitObservable(this)};var WindowedObservable=function(__super__){function subscribe(observer){this.subscription=this.source.subscribe(new WindowedObserver(observer,this,this.subscription));var self=this;timeoutScheduler.schedule(function(){self.source.request(self.windowSize)});return this.subscription}inherits(WindowedObservable,__super__);function WindowedObservable(source,windowSize){__super__.call(this,subscribe,source);this.source=source;this.windowSize=windowSize}var WindowedObserver=function(__sub__){inherits(WindowedObserver,__sub__);function WindowedObserver(observer,observable,cancel){this.observer=observer;this.observable=observable;this.cancel=cancel;this.received=0}var windowedObserverPrototype=WindowedObserver.prototype;windowedObserverPrototype.completed=function(){this.observer.onCompleted();this.dispose()};windowedObserverPrototype.error=function(error){this.observer.onError(error);this.dispose()};windowedObserverPrototype.next=function(value){this.observer.onNext(value);this.received=++this.received%this.observable.windowSize;if(this.received===0){var self=this;timeoutScheduler.schedule(function(){self.observable.source.request(self.observable.windowSize)})}};windowedObserverPrototype.dispose=function(){this.observer=null;if(this.cancel){this.cancel.dispose();this.cancel=null}__sub__.prototype.dispose.call(this)};return WindowedObserver}(AbstractObserver);return WindowedObservable}(Observable);ControlledObservable.prototype.windowed=function(windowSize){return new WindowedObservable(this,windowSize)};observableProto.pipe=function(dest){var source=this.pausableBuffered();function onDrain(){source.resume()}dest.addListener("drain",onDrain);source.subscribe(function(x){!dest.write(String(x))&&source.pause()},function(err){dest.emit("error",err)},function(){!dest._isStdio&&dest.end();dest.removeListener("drain",onDrain)});source.resume();return dest};observableProto.multicast=function(subjectOrSubjectSelector,selector){var source=this;return typeof subjectOrSubjectSelector==="function"?new AnonymousObservable(function(observer){var connectable=source.multicast(subjectOrSubjectSelector());return new CompositeDisposable(selector(connectable).subscribe(observer),connectable.connect())},source):new ConnectableObservable(source,subjectOrSubjectSelector)};observableProto.publish=function(selector){return selector&&isFunction(selector)?this.multicast(function(){return new Subject},selector):this.multicast(new Subject)};observableProto.share=function(){return this.publish().refCount()};observableProto.publishLast=function(selector){return selector&&isFunction(selector)?this.multicast(function(){return new AsyncSubject},selector):this.multicast(new AsyncSubject)};observableProto.publishValue=function(initialValueOrSelector,initialValue){return arguments.length===2?this.multicast(function(){return new BehaviorSubject(initialValue)},initialValueOrSelector):this.multicast(new BehaviorSubject(initialValueOrSelector))};observableProto.shareValue=function(initialValue){return this.publishValue(initialValue).refCount()};observableProto.replay=function(selector,bufferSize,windowSize,scheduler){return selector&&isFunction(selector)?this.multicast(function(){return new ReplaySubject(bufferSize,windowSize,scheduler)},selector):this.multicast(new ReplaySubject(bufferSize,windowSize,scheduler))};observableProto.shareReplay=function(bufferSize,windowSize,scheduler){return this.replay(null,bufferSize,windowSize,scheduler).refCount()};var InnerSubscription=function(subject,observer){this.subject=subject;this.observer=observer};InnerSubscription.prototype.dispose=function(){if(!this.subject.isDisposed&&this.observer!==null){var idx=this.subject.observers.indexOf(this.observer);this.subject.observers.splice(idx,1);this.observer=null}};var BehaviorSubject=Rx.BehaviorSubject=function(__super__){function subscribe(observer){checkDisposed(this);if(!this.isStopped){this.observers.push(observer);observer.onNext(this.value);return new InnerSubscription(this,observer)}if(this.hasError){observer.onError(this.error)}else{observer.onCompleted()}return disposableEmpty}inherits(BehaviorSubject,__super__);function BehaviorSubject(value){__super__.call(this,subscribe);this.value=value,this.observers=[],this.isDisposed=false,this.isStopped=false,this.hasError=false}addProperties(BehaviorSubject.prototype,Observer,{getValue:function(){checkDisposed(this);if(this.hasError){throw this.error}return this.value},hasObservers:function(){return this.observers.length>0},onCompleted:function(){checkDisposed(this);if(this.isStopped){return}this.isStopped=true;for(var i=0,os=cloneArray(this.observers),len=os.length;i<len;i++){os[i].onCompleted()}this.observers.length=0},onError:function(error){checkDisposed(this);if(this.isStopped){return}this.isStopped=true;this.hasError=true;this.error=error;for(var i=0,os=cloneArray(this.observers),len=os.length;i<len;i++){os[i].onError(error)}this.observers.length=0},onNext:function(value){checkDisposed(this);if(this.isStopped){return}this.value=value;for(var i=0,os=cloneArray(this.observers),len=os.length;i<len;i++){os[i].onNext(value)}},dispose:function(){this.isDisposed=true;this.observers=null;this.value=null;this.exception=null}});return BehaviorSubject}(Observable);var ReplaySubject=Rx.ReplaySubject=function(__super__){var maxSafeInteger=Math.pow(2,53)-1;function createRemovableDisposable(subject,observer){return disposableCreate(function(){observer.dispose();!subject.isDisposed&&subject.observers.splice(subject.observers.indexOf(observer),1)})}function subscribe(observer){var so=new ScheduledObserver(this.scheduler,observer),subscription=createRemovableDisposable(this,so);checkDisposed(this);this._trim(this.scheduler.now());this.observers.push(so);for(var i=0,len=this.q.length;i<len;i++){so.onNext(this.q[i].value)}if(this.hasError){so.onError(this.error)}else if(this.isStopped){so.onCompleted()}so.ensureActive();return subscription}inherits(ReplaySubject,__super__);function ReplaySubject(bufferSize,windowSize,scheduler){this.bufferSize=bufferSize==null?maxSafeInteger:bufferSize;this.windowSize=windowSize==null?maxSafeInteger:windowSize;this.scheduler=scheduler||currentThreadScheduler;this.q=[];this.observers=[];this.isStopped=false;this.isDisposed=false;this.hasError=false;this.error=null;__super__.call(this,subscribe)}addProperties(ReplaySubject.prototype,Observer.prototype,{hasObservers:function(){return this.observers.length>0},_trim:function(now){while(this.q.length>this.bufferSize){this.q.shift()}while(this.q.length>0&&now-this.q[0].interval>this.windowSize){this.q.shift()}},onNext:function(value){checkDisposed(this);if(this.isStopped){return}var now=this.scheduler.now();this.q.push({interval:now,value:value});this._trim(now);for(var i=0,os=cloneArray(this.observers),len=os.length;i<len;i++){var observer=os[i];observer.onNext(value);observer.ensureActive()}},onError:function(error){checkDisposed(this);if(this.isStopped){return}this.isStopped=true;this.error=error;this.hasError=true;var now=this.scheduler.now();this._trim(now);for(var i=0,os=cloneArray(this.observers),len=os.length;i<len;i++){var observer=os[i];observer.onError(error);observer.ensureActive()}this.observers.length=0},onCompleted:function(){checkDisposed(this);if(this.isStopped){return}this.isStopped=true;var now=this.scheduler.now();this._trim(now);for(var i=0,os=cloneArray(this.observers),len=os.length;i<len;i++){var observer=os[i];observer.onCompleted();observer.ensureActive()}this.observers.length=0},dispose:function(){this.isDisposed=true;this.observers=null}});return ReplaySubject}(Observable);var ConnectableObservable=Rx.ConnectableObservable=function(__super__){inherits(ConnectableObservable,__super__);function ConnectableObservable(source,subject){var hasSubscription=false,subscription,sourceObservable=source.asObservable();this.connect=function(){if(!hasSubscription){hasSubscription=true;subscription=new CompositeDisposable(sourceObservable.subscribe(subject),disposableCreate(function(){hasSubscription=false}))}return subscription};__super__.call(this,function(o){return subject.subscribe(o)})}ConnectableObservable.prototype.refCount=function(){var connectableSubscription,count=0,source=this;return new AnonymousObservable(function(observer){var shouldConnect=++count===1,subscription=source.subscribe(observer);shouldConnect&&(connectableSubscription=source.connect());return function(){subscription.dispose();--count===0&&connectableSubscription.dispose()}})};return ConnectableObservable}(Observable);observableProto.singleInstance=function(){var source=this,hasObservable=false,observable;function getObservable(){if(!hasObservable){hasObservable=true;observable=source.finally(function(){hasObservable=false}).publish().refCount()}return observable}return new AnonymousObservable(function(o){return getObservable().subscribe(o)})};observableProto.join=function(right,leftDurationSelector,rightDurationSelector,resultSelector){var left=this;return new AnonymousObservable(function(o){var group=new CompositeDisposable;var leftDone=false,rightDone=false;var leftId=0,rightId=0;var leftMap=new Map,rightMap=new Map;var handleError=function(e){o.onError(e)};group.add(left.subscribe(function(value){var id=leftId++,md=new SingleAssignmentDisposable;leftMap.set(id,value);group.add(md);var duration=tryCatch(leftDurationSelector)(value);if(duration===errorObj){return o.onError(duration.e)}md.setDisposable(duration.take(1).subscribe(noop,handleError,function(){leftMap["delete"](id)&&leftMap.size===0&&leftDone&&o.onCompleted();group.remove(md)}));rightMap.forEach(function(v){var result=tryCatch(resultSelector)(value,v);if(result===errorObj){return o.onError(result.e)}o.onNext(result)})},handleError,function(){leftDone=true;(rightDone||leftMap.size===0)&&o.onCompleted()}));group.add(right.subscribe(function(value){var id=rightId++,md=new SingleAssignmentDisposable;rightMap.set(id,value);group.add(md);var duration=tryCatch(rightDurationSelector)(value);if(duration===errorObj){return o.onError(duration.e)}md.setDisposable(duration.take(1).subscribe(noop,handleError,function(){rightMap["delete"](id)&&rightMap.size===0&&rightDone&&o.onCompleted();group.remove(md)}));leftMap.forEach(function(v){var result=tryCatch(resultSelector)(v,value);if(result===errorObj){return o.onError(result.e)}o.onNext(result)})},handleError,function(){rightDone=true;(leftDone||rightMap.size===0)&&o.onCompleted()}));return group},left)};observableProto.groupJoin=function(right,leftDurationSelector,rightDurationSelector,resultSelector){var left=this;return new AnonymousObservable(function(o){var group=new CompositeDisposable;var r=new RefCountDisposable(group);var leftMap=new Map,rightMap=new Map;var leftId=0,rightId=0;var handleError=function(e){return function(v){v.onError(e)}};function handleError(e){}group.add(left.subscribe(function(value){var s=new Subject;var id=leftId++;leftMap.set(id,s);var result=tryCatch(resultSelector)(value,addRef(s,r));if(result===errorObj){leftMap.forEach(handleError(result.e));return o.onError(result.e)}o.onNext(result);rightMap.forEach(function(v){s.onNext(v)});var md=new SingleAssignmentDisposable;group.add(md);var duration=tryCatch(leftDurationSelector)(value);if(duration===errorObj){leftMap.forEach(handleError(duration.e));return o.onError(duration.e)}md.setDisposable(duration.take(1).subscribe(noop,function(e){leftMap.forEach(handleError(e));o.onError(e)},function(){leftMap["delete"](id)&&s.onCompleted();group.remove(md)}))},function(e){leftMap.forEach(handleError(e));o.onError(e)},function(){o.onCompleted()}));group.add(right.subscribe(function(value){var id=rightId++;rightMap.set(id,value);var md=new SingleAssignmentDisposable;group.add(md);var duration=tryCatch(rightDurationSelector)(value);if(duration===errorObj){leftMap.forEach(handleError(duration.e));return o.onError(duration.e)}md.setDisposable(duration.take(1).subscribe(noop,function(e){leftMap.forEach(handleError(e));o.onError(e)},function(){rightMap["delete"](id);group.remove(md)}));leftMap.forEach(function(v){v.onNext(value)})},function(e){leftMap.forEach(handleError(e));o.onError(e)}));return r},left)};function toArray(x){return x.toArray()}observableProto.buffer=function(){return this.window.apply(this,arguments).flatMap(toArray)};observableProto.window=function(windowOpeningsOrClosingSelector,windowClosingSelector){if(arguments.length===1&&typeof arguments[0]!=="function"){return observableWindowWithBoundaries.call(this,windowOpeningsOrClosingSelector)}return typeof windowOpeningsOrClosingSelector==="function"?observableWindowWithClosingSelector.call(this,windowOpeningsOrClosingSelector):observableWindowWithOpenings.call(this,windowOpeningsOrClosingSelector,windowClosingSelector)};function observableWindowWithOpenings(windowOpenings,windowClosingSelector){return windowOpenings.groupJoin(this,windowClosingSelector,observableEmpty,function(_,win){return win})}function observableWindowWithBoundaries(windowBoundaries){var source=this;return new AnonymousObservable(function(observer){var win=new Subject,d=new CompositeDisposable,r=new RefCountDisposable(d);observer.onNext(addRef(win,r));d.add(source.subscribe(function(x){win.onNext(x)},function(err){win.onError(err);observer.onError(err)},function(){win.onCompleted();observer.onCompleted()}));isPromise(windowBoundaries)&&(windowBoundaries=observableFromPromise(windowBoundaries));d.add(windowBoundaries.subscribe(function(w){win.onCompleted();win=new Subject;observer.onNext(addRef(win,r))},function(err){win.onError(err);observer.onError(err)},function(){win.onCompleted();observer.onCompleted()}));return r},source)}function observableWindowWithClosingSelector(windowClosingSelector){var source=this;return new AnonymousObservable(function(observer){var m=new SerialDisposable,d=new CompositeDisposable(m),r=new RefCountDisposable(d),win=new Subject;observer.onNext(addRef(win,r));d.add(source.subscribe(function(x){win.onNext(x)},function(err){win.onError(err);observer.onError(err)},function(){win.onCompleted();observer.onCompleted()}));function createWindowClose(){var windowClose;try{windowClose=windowClosingSelector()}catch(e){observer.onError(e);return}isPromise(windowClose)&&(windowClose=observableFromPromise(windowClose));var m1=new SingleAssignmentDisposable;m.setDisposable(m1);m1.setDisposable(windowClose.take(1).subscribe(noop,function(err){win.onError(err);observer.onError(err)},function(){win.onCompleted();win=new Subject;observer.onNext(addRef(win,r));createWindowClose()}))}createWindowClose();return r},source)}observableProto.pairwise=function(){var source=this;return new AnonymousObservable(function(observer){var previous,hasPrevious=false;return source.subscribe(function(x){if(hasPrevious){observer.onNext([previous,x])}else{hasPrevious=true}previous=x},observer.onError.bind(observer),observer.onCompleted.bind(observer))},source)};observableProto.partition=function(predicate,thisArg){return[this.filter(predicate,thisArg),this.filter(function(x,i,o){return!predicate.call(thisArg,x,i,o)})]};var WhileEnumerable=function(__super__){inherits(WhileEnumerable,__super__);function WhileEnumerable(c,s){this.c=c;this.s=s}WhileEnumerable.prototype[$iterator$]=function(){var self=this;return{next:function(){return self.c()?{done:false,value:self.s}:{done:true,value:void 0}}}};return WhileEnumerable}(Enumerable);function enumerableWhile(condition,source){return new WhileEnumerable(condition,source)}observableProto.letBind=observableProto["let"]=function(func){return func(this)};Observable["if"]=function(condition,thenSource,elseSourceOrScheduler){return observableDefer(function(){elseSourceOrScheduler||(elseSourceOrScheduler=observableEmpty());isPromise(thenSource)&&(thenSource=observableFromPromise(thenSource));isPromise(elseSourceOrScheduler)&&(elseSourceOrScheduler=observableFromPromise(elseSourceOrScheduler));typeof elseSourceOrScheduler.now==="function"&&(elseSourceOrScheduler=observableEmpty(elseSourceOrScheduler));return condition()?thenSource:elseSourceOrScheduler})};Observable["for"]=Observable.forIn=function(sources,resultSelector,thisArg){return enumerableOf(sources,resultSelector,thisArg).concat()};var observableWhileDo=Observable["while"]=Observable.whileDo=function(condition,source){isPromise(source)&&(source=observableFromPromise(source));return enumerableWhile(condition,source).concat()};observableProto.doWhile=function(condition){return observableConcat([this,observableWhileDo(condition,this)])};Observable["case"]=function(selector,sources,defaultSourceOrScheduler){return observableDefer(function(){isPromise(defaultSourceOrScheduler)&&(defaultSourceOrScheduler=observableFromPromise(defaultSourceOrScheduler));defaultSourceOrScheduler||(defaultSourceOrScheduler=observableEmpty());isScheduler(defaultSourceOrScheduler)&&(defaultSourceOrScheduler=observableEmpty(defaultSourceOrScheduler));var result=sources[selector()];isPromise(result)&&(result=observableFromPromise(result));return result||defaultSourceOrScheduler})};observableProto.expand=function(selector,scheduler){isScheduler(scheduler)||(scheduler=immediateScheduler);var source=this;return new AnonymousObservable(function(observer){var q=[],m=new SerialDisposable,d=new CompositeDisposable(m),activeCount=0,isAcquired=false;var ensureActive=function(){var isOwner=false;if(q.length>0){isOwner=!isAcquired;isAcquired=true}if(isOwner){m.setDisposable(scheduler.scheduleRecursive(function(self){var work;if(q.length>0){work=q.shift()}else{isAcquired=false;return}var m1=new SingleAssignmentDisposable;d.add(m1);m1.setDisposable(work.subscribe(function(x){observer.onNext(x);var result=null;try{result=selector(x)}catch(e){observer.onError(e)}q.push(result);activeCount++;ensureActive()},observer.onError.bind(observer),function(){d.remove(m1);activeCount--;if(activeCount===0){observer.onCompleted()}}));self()}))}};q.push(source);activeCount++;ensureActive();return d},this)};Observable.forkJoin=function(){var allSources=[];if(Array.isArray(arguments[0])){allSources=arguments[0]}else{for(var i=0,len=arguments.length;i<len;i++){allSources.push(arguments[i])}}return new AnonymousObservable(function(subscriber){var count=allSources.length;if(count===0){subscriber.onCompleted();return disposableEmpty}var group=new CompositeDisposable,finished=false,hasResults=new Array(count),hasCompleted=new Array(count),results=new Array(count);for(var idx=0;idx<count;idx++){(function(i){var source=allSources[i];isPromise(source)&&(source=observableFromPromise(source));group.add(source.subscribe(function(value){if(!finished){hasResults[i]=true;results[i]=value}},function(e){finished=true;subscriber.onError(e);group.dispose()},function(){if(!finished){if(!hasResults[i]){subscriber.onCompleted();return}hasCompleted[i]=true;for(var ix=0;ix<count;ix++){if(!hasCompleted[ix]){return}}finished=true;subscriber.onNext(results);subscriber.onCompleted()}}))})(idx)}return group})};observableProto.forkJoin=function(second,resultSelector){var first=this;return new AnonymousObservable(function(observer){var leftStopped=false,rightStopped=false,hasLeft=false,hasRight=false,lastLeft,lastRight,leftSubscription=new SingleAssignmentDisposable,rightSubscription=new SingleAssignmentDisposable;isPromise(second)&&(second=observableFromPromise(second));leftSubscription.setDisposable(first.subscribe(function(left){hasLeft=true;lastLeft=left},function(err){rightSubscription.dispose();observer.onError(err)},function(){leftStopped=true;if(rightStopped){if(!hasLeft){observer.onCompleted()}else if(!hasRight){observer.onCompleted()}else{var result;try{result=resultSelector(lastLeft,lastRight)}catch(e){observer.onError(e);return}observer.onNext(result);observer.onCompleted()}}}));rightSubscription.setDisposable(second.subscribe(function(right){hasRight=true;lastRight=right},function(err){leftSubscription.dispose();observer.onError(err)},function(){rightStopped=true;if(leftStopped){if(!hasLeft){observer.onCompleted()}else if(!hasRight){observer.onCompleted()}else{var result;try{result=resultSelector(lastLeft,lastRight)}catch(e){observer.onError(e);return}observer.onNext(result);observer.onCompleted()}}}));return new CompositeDisposable(leftSubscription,rightSubscription)},first)};observableProto.manySelect=observableProto.extend=function(selector,scheduler){isScheduler(scheduler)||(scheduler=immediateScheduler);var source=this;return observableDefer(function(){var chain;return source.map(function(x){var curr=new ChainObservable(x);chain&&chain.onNext(x);chain=curr;return curr}).tap(noop,function(e){chain&&chain.onError(e)},function(){chain&&chain.onCompleted()}).observeOn(scheduler).map(selector)},source)};var ChainObservable=function(__super__){function subscribe(observer){var self=this,g=new CompositeDisposable;g.add(currentThreadScheduler.schedule(function(){observer.onNext(self.head);g.add(self.tail.mergeAll().subscribe(observer))}));return g}inherits(ChainObservable,__super__);function ChainObservable(head){__super__.call(this,subscribe);this.head=head;this.tail=new AsyncSubject}addProperties(ChainObservable.prototype,Observer,{onCompleted:function(){this.onNext(Observable.empty())},onError:function(e){this.onNext(Observable["throw"](e))},onNext:function(v){this.tail.onNext(v);this.tail.onCompleted()}});return ChainObservable}(Observable);var Map=root.Map||function(){function Map(){this.size=0;this._values=[];this._keys=[]}Map.prototype["delete"]=function(key){var i=this._keys.indexOf(key);if(i===-1){return false}this._values.splice(i,1);this._keys.splice(i,1);this.size--;return true};Map.prototype.get=function(key){var i=this._keys.indexOf(key);return i===-1?undefined:this._values[i]};Map.prototype.set=function(key,value){var i=this._keys.indexOf(key);if(i===-1){this._keys.push(key);this._values.push(value);this.size++}else{this._values[i]=value}return this};Map.prototype.forEach=function(cb,thisArg){for(var i=0;i<this.size;i++){cb.call(thisArg,this._values[i],this._keys[i])}};return Map}();function Pattern(patterns){this.patterns=patterns}Pattern.prototype.and=function(other){return new Pattern(this.patterns.concat(other))};Pattern.prototype.thenDo=function(selector){return new Plan(this,selector)};function Plan(expression,selector){this.expression=expression;this.selector=selector}Plan.prototype.activate=function(externalSubscriptions,observer,deactivate){var self=this;var joinObservers=[];for(var i=0,len=this.expression.patterns.length;i<len;i++){joinObservers.push(planCreateObserver(externalSubscriptions,this.expression.patterns[i],observer.onError.bind(observer)))}var activePlan=new ActivePlan(joinObservers,function(){var result;try{result=self.selector.apply(self,arguments)}catch(e){observer.onError(e);return}observer.onNext(result)},function(){for(var j=0,jlen=joinObservers.length;j<jlen;j++){joinObservers[j].removeActivePlan(activePlan)}deactivate(activePlan)});for(i=0,len=joinObservers.length;i<len;i++){joinObservers[i].addActivePlan(activePlan)}return activePlan};function planCreateObserver(externalSubscriptions,observable,onError){var entry=externalSubscriptions.get(observable);if(!entry){var observer=new JoinObserver(observable,onError);externalSubscriptions.set(observable,observer);return observer}return entry}function ActivePlan(joinObserverArray,onNext,onCompleted){this.joinObserverArray=joinObserverArray;this.onNext=onNext;this.onCompleted=onCompleted;this.joinObservers=new Map;for(var i=0,len=this.joinObserverArray.length;i<len;i++){var joinObserver=this.joinObserverArray[i];this.joinObservers.set(joinObserver,joinObserver)}}ActivePlan.prototype.dequeue=function(){this.joinObservers.forEach(function(v){v.queue.shift()})};ActivePlan.prototype.match=function(){var i,len,hasValues=true;for(i=0,len=this.joinObserverArray.length;i<len;i++){if(this.joinObserverArray[i].queue.length===0){hasValues=false;break}}if(hasValues){var firstValues=[],isCompleted=false;for(i=0,len=this.joinObserverArray.length;i<len;i++){firstValues.push(this.joinObserverArray[i].queue[0]);this.joinObserverArray[i].queue[0].kind==="C"&&(isCompleted=true)}if(isCompleted){this.onCompleted()}else{this.dequeue();var values=[];for(i=0,len=firstValues.length;i<firstValues.length;i++){values.push(firstValues[i].value)}this.onNext.apply(this,values)}}};var JoinObserver=function(__super__){inherits(JoinObserver,__super__);function JoinObserver(source,onError){__super__.call(this);this.source=source;this.onError=onError;this.queue=[];this.activePlans=[];this.subscription=new SingleAssignmentDisposable;this.isDisposed=false}var JoinObserverPrototype=JoinObserver.prototype;JoinObserverPrototype.next=function(notification){if(!this.isDisposed){if(notification.kind==="E"){return this.onError(notification.exception)}this.queue.push(notification);var activePlans=this.activePlans.slice(0);for(var i=0,len=activePlans.length;i<len;i++){activePlans[i].match()}}};JoinObserverPrototype.error=noop;JoinObserverPrototype.completed=noop;JoinObserverPrototype.addActivePlan=function(activePlan){this.activePlans.push(activePlan)};JoinObserverPrototype.subscribe=function(){this.subscription.setDisposable(this.source.materialize().subscribe(this))};JoinObserverPrototype.removeActivePlan=function(activePlan){this.activePlans.splice(this.activePlans.indexOf(activePlan),1);this.activePlans.length===0&&this.dispose()};JoinObserverPrototype.dispose=function(){__super__.prototype.dispose.call(this);if(!this.isDisposed){this.isDisposed=true;this.subscription.dispose()}};return JoinObserver}(AbstractObserver);observableProto.and=function(right){return new Pattern([this,right])};observableProto.thenDo=function(selector){return new Pattern([this]).thenDo(selector)};Observable.when=function(){var len=arguments.length,plans;if(Array.isArray(arguments[0])){plans=arguments[0]}else{plans=new Array(len);for(var i=0;i<len;i++){plans[i]=arguments[i]}}return new AnonymousObservable(function(o){var activePlans=[],externalSubscriptions=new Map;var outObserver=observerCreate(function(x){o.onNext(x)},function(err){externalSubscriptions.forEach(function(v){v.onError(err)});o.onError(err)},function(x){o.onCompleted()});try{for(var i=0,len=plans.length;i<len;i++){activePlans.push(plans[i].activate(externalSubscriptions,outObserver,function(activePlan){var idx=activePlans.indexOf(activePlan);activePlans.splice(idx,1);activePlans.length===0&&o.onCompleted()}))}}catch(e){observableThrow(e).subscribe(o)}var group=new CompositeDisposable;externalSubscriptions.forEach(function(joinObserver){joinObserver.subscribe();group.add(joinObserver)});return group})};function observableTimerDate(dueTime,scheduler){return new AnonymousObservable(function(observer){return scheduler.scheduleWithAbsolute(dueTime,function(){observer.onNext(0);observer.onCompleted()})})}function observableTimerDateAndPeriod(dueTime,period,scheduler){return new AnonymousObservable(function(observer){var d=dueTime,p=normalizeTime(period);return scheduler.scheduleRecursiveWithAbsoluteAndState(0,d,function(count,self){if(p>0){var now=scheduler.now();d=d+p;d<=now&&(d=now+p)}observer.onNext(count);self(count+1,d)})})}function observableTimerTimeSpan(dueTime,scheduler){return new AnonymousObservable(function(observer){return scheduler.scheduleWithRelative(normalizeTime(dueTime),function(){observer.onNext(0);observer.onCompleted()})})}function observableTimerTimeSpanAndPeriod(dueTime,period,scheduler){return dueTime===period?new AnonymousObservable(function(observer){return scheduler.schedulePeriodicWithState(0,period,function(count){observer.onNext(count);return count+1})}):observableDefer(function(){return observableTimerDateAndPeriod(scheduler.now()+dueTime,period,scheduler)})}var observableinterval=Observable.interval=function(period,scheduler){return observableTimerTimeSpanAndPeriod(period,period,isScheduler(scheduler)?scheduler:timeoutScheduler)};var observableTimer=Observable.timer=function(dueTime,periodOrScheduler,scheduler){
var period;isScheduler(scheduler)||(scheduler=timeoutScheduler);if(periodOrScheduler!=null&&typeof periodOrScheduler==="number"){period=periodOrScheduler}else if(isScheduler(periodOrScheduler)){scheduler=periodOrScheduler}if(dueTime instanceof Date&&period===undefined){return observableTimerDate(dueTime.getTime(),scheduler)}if(dueTime instanceof Date&&period!==undefined){return observableTimerDateAndPeriod(dueTime.getTime(),periodOrScheduler,scheduler)}return period===undefined?observableTimerTimeSpan(dueTime,scheduler):observableTimerTimeSpanAndPeriod(dueTime,period,scheduler)};function observableDelayTimeSpan(source,dueTime,scheduler){return new AnonymousObservable(function(observer){var active=false,cancelable=new SerialDisposable,exception=null,q=[],running=false,subscription;subscription=source.materialize().timestamp(scheduler).subscribe(function(notification){var d,shouldRun;if(notification.value.kind==="E"){q=[];q.push(notification);exception=notification.value.exception;shouldRun=!running}else{q.push({value:notification.value,timestamp:notification.timestamp+dueTime});shouldRun=!active;active=true}if(shouldRun){if(exception!==null){observer.onError(exception)}else{d=new SingleAssignmentDisposable;cancelable.setDisposable(d);d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime,function(self){var e,recurseDueTime,result,shouldRecurse;if(exception!==null){return}running=true;do{result=null;if(q.length>0&&q[0].timestamp-scheduler.now()<=0){result=q.shift().value}if(result!==null){result.accept(observer)}}while(result!==null);shouldRecurse=false;recurseDueTime=0;if(q.length>0){shouldRecurse=true;recurseDueTime=Math.max(0,q[0].timestamp-scheduler.now())}else{active=false}e=exception;running=false;if(e!==null){observer.onError(e)}else if(shouldRecurse){self(recurseDueTime)}}))}}});return new CompositeDisposable(subscription,cancelable)},source)}function observableDelayDate(source,dueTime,scheduler){return observableDefer(function(){return observableDelayTimeSpan(source,dueTime-scheduler.now(),scheduler)})}observableProto.delay=function(dueTime,scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);return dueTime instanceof Date?observableDelayDate(this,dueTime.getTime(),scheduler):observableDelayTimeSpan(this,dueTime,scheduler)};observableProto.debounce=function(dueTime,scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);var source=this;return new AnonymousObservable(function(observer){var cancelable=new SerialDisposable,hasvalue=false,value,id=0;var subscription=source.subscribe(function(x){hasvalue=true;value=x;id++;var currentId=id,d=new SingleAssignmentDisposable;cancelable.setDisposable(d);d.setDisposable(scheduler.scheduleWithRelative(dueTime,function(){hasvalue&&id===currentId&&observer.onNext(value);hasvalue=false}))},function(e){cancelable.dispose();observer.onError(e);hasvalue=false;id++},function(){cancelable.dispose();hasvalue&&observer.onNext(value);observer.onCompleted();hasvalue=false;id++});return new CompositeDisposable(subscription,cancelable)},this)};observableProto.throttle=function(dueTime,scheduler){return this.debounce(dueTime,scheduler)};observableProto.windowWithTime=function(timeSpan,timeShiftOrScheduler,scheduler){var source=this,timeShift;timeShiftOrScheduler==null&&(timeShift=timeSpan);isScheduler(scheduler)||(scheduler=timeoutScheduler);if(typeof timeShiftOrScheduler==="number"){timeShift=timeShiftOrScheduler}else if(isScheduler(timeShiftOrScheduler)){timeShift=timeSpan;scheduler=timeShiftOrScheduler}return new AnonymousObservable(function(observer){var groupDisposable,nextShift=timeShift,nextSpan=timeSpan,q=[],refCountDisposable,timerD=new SerialDisposable,totalTime=0;groupDisposable=new CompositeDisposable(timerD),refCountDisposable=new RefCountDisposable(groupDisposable);function createTimer(){var m=new SingleAssignmentDisposable,isSpan=false,isShift=false;timerD.setDisposable(m);if(nextSpan===nextShift){isSpan=true;isShift=true}else if(nextSpan<nextShift){isSpan=true}else{isShift=true}var newTotalTime=isSpan?nextSpan:nextShift,ts=newTotalTime-totalTime;totalTime=newTotalTime;if(isSpan){nextSpan+=timeShift}if(isShift){nextShift+=timeShift}m.setDisposable(scheduler.scheduleWithRelative(ts,function(){if(isShift){var s=new Subject;q.push(s);observer.onNext(addRef(s,refCountDisposable))}isSpan&&q.shift().onCompleted();createTimer()}))}q.push(new Subject);observer.onNext(addRef(q[0],refCountDisposable));createTimer();groupDisposable.add(source.subscribe(function(x){for(var i=0,len=q.length;i<len;i++){q[i].onNext(x)}},function(e){for(var i=0,len=q.length;i<len;i++){q[i].onError(e)}observer.onError(e)},function(){for(var i=0,len=q.length;i<len;i++){q[i].onCompleted()}observer.onCompleted()}));return refCountDisposable},source)};observableProto.windowWithTimeOrCount=function(timeSpan,count,scheduler){var source=this;isScheduler(scheduler)||(scheduler=timeoutScheduler);return new AnonymousObservable(function(observer){var timerD=new SerialDisposable,groupDisposable=new CompositeDisposable(timerD),refCountDisposable=new RefCountDisposable(groupDisposable),n=0,windowId=0,s=new Subject;function createTimer(id){var m=new SingleAssignmentDisposable;timerD.setDisposable(m);m.setDisposable(scheduler.scheduleWithRelative(timeSpan,function(){if(id!==windowId){return}n=0;var newId=++windowId;s.onCompleted();s=new Subject;observer.onNext(addRef(s,refCountDisposable));createTimer(newId)}))}observer.onNext(addRef(s,refCountDisposable));createTimer(0);groupDisposable.add(source.subscribe(function(x){var newId=0,newWindow=false;s.onNext(x);if(++n===count){newWindow=true;n=0;newId=++windowId;s.onCompleted();s=new Subject;observer.onNext(addRef(s,refCountDisposable))}newWindow&&createTimer(newId)},function(e){s.onError(e);observer.onError(e)},function(){s.onCompleted();observer.onCompleted()}));return refCountDisposable},source)};function toArray(x){return x.toArray()}observableProto.bufferWithTime=function(timeSpan,timeShiftOrScheduler,scheduler){return this.windowWithTime(timeSpan,timeShiftOrScheduler,scheduler).flatMap(toArray)};function toArray(x){return x.toArray()}observableProto.bufferWithTimeOrCount=function(timeSpan,count,scheduler){return this.windowWithTimeOrCount(timeSpan,count,scheduler).flatMap(toArray)};observableProto.timeInterval=function(scheduler){var source=this;isScheduler(scheduler)||(scheduler=timeoutScheduler);return observableDefer(function(){var last=scheduler.now();return source.map(function(x){var now=scheduler.now(),span=now-last;last=now;return{value:x,interval:span}})})};observableProto.timestamp=function(scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);return this.map(function(x){return{value:x,timestamp:scheduler.now()}})};function sampleObservable(source,sampler){return new AnonymousObservable(function(o){var atEnd=false,value,hasValue=false;function sampleSubscribe(){if(hasValue){hasValue=false;o.onNext(value)}atEnd&&o.onCompleted()}var sourceSubscription=new SingleAssignmentDisposable;sourceSubscription.setDisposable(source.subscribe(function(newValue){hasValue=true;value=newValue},function(e){o.onError(e)},function(){atEnd=true;sourceSubscription.dispose()}));return new CompositeDisposable(sourceSubscription,sampler.subscribe(sampleSubscribe,function(e){o.onError(e)},sampleSubscribe))},source)}observableProto.sample=observableProto.throttleLatest=function(intervalOrSampler,scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);return typeof intervalOrSampler==="number"?sampleObservable(this,observableinterval(intervalOrSampler,scheduler)):sampleObservable(this,intervalOrSampler)};observableProto.timeout=function(dueTime,other,scheduler){(other==null||typeof other==="string")&&(other=observableThrow(new Error(other||"Timeout")));isScheduler(scheduler)||(scheduler=timeoutScheduler);var source=this,schedulerMethod=dueTime instanceof Date?"scheduleWithAbsolute":"scheduleWithRelative";return new AnonymousObservable(function(observer){var id=0,original=new SingleAssignmentDisposable,subscription=new SerialDisposable,switched=false,timer=new SerialDisposable;subscription.setDisposable(original);function createTimer(){var myId=id;timer.setDisposable(scheduler[schedulerMethod](dueTime,function(){if(id===myId){isPromise(other)&&(other=observableFromPromise(other));subscription.setDisposable(other.subscribe(observer))}}))}createTimer();original.setDisposable(source.subscribe(function(x){if(!switched){id++;observer.onNext(x);createTimer()}},function(e){if(!switched){id++;observer.onError(e)}},function(){if(!switched){id++;observer.onCompleted()}}));return new CompositeDisposable(subscription,timer)},source)};Observable.generateWithAbsoluteTime=function(initialState,condition,iterate,resultSelector,timeSelector,scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);return new AnonymousObservable(function(observer){var first=true,hasResult=false;return scheduler.scheduleRecursiveWithAbsoluteAndState(initialState,scheduler.now(),function(state,self){hasResult&&observer.onNext(state);try{if(first){first=false}else{state=iterate(state)}hasResult=condition(state);if(hasResult){var result=resultSelector(state);var time=timeSelector(state)}}catch(e){observer.onError(e);return}if(hasResult){self(result,time)}else{observer.onCompleted()}})})};Observable.generateWithRelativeTime=function(initialState,condition,iterate,resultSelector,timeSelector,scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);return new AnonymousObservable(function(observer){var first=true,hasResult=false;return scheduler.scheduleRecursiveWithRelativeAndState(initialState,0,function(state,self){hasResult&&observer.onNext(state);try{if(first){first=false}else{state=iterate(state)}hasResult=condition(state);if(hasResult){var result=resultSelector(state);var time=timeSelector(state)}}catch(e){observer.onError(e);return}if(hasResult){self(result,time)}else{observer.onCompleted()}})})};observableProto.delaySubscription=function(dueTime,scheduler){var scheduleMethod=dueTime instanceof Date?"scheduleWithAbsolute":"scheduleWithRelative";var source=this;isScheduler(scheduler)||(scheduler=timeoutScheduler);return new AnonymousObservable(function(o){var d=new SerialDisposable;d.setDisposable(scheduler[scheduleMethod](dueTime,function(){d.setDisposable(source.subscribe(o))}));return d},this)};observableProto.delayWithSelector=function(subscriptionDelay,delayDurationSelector){var source=this,subDelay,selector;if(isFunction(subscriptionDelay)){selector=subscriptionDelay}else{subDelay=subscriptionDelay;selector=delayDurationSelector}return new AnonymousObservable(function(observer){var delays=new CompositeDisposable,atEnd=false,subscription=new SerialDisposable;function start(){subscription.setDisposable(source.subscribe(function(x){var delay=tryCatch(selector)(x);if(delay===errorObj){return observer.onError(delay.e)}var d=new SingleAssignmentDisposable;delays.add(d);d.setDisposable(delay.subscribe(function(){observer.onNext(x);delays.remove(d);done()},function(e){observer.onError(e)},function(){observer.onNext(x);delays.remove(d);done()}))},function(e){observer.onError(e)},function(){atEnd=true;subscription.dispose();done()}))}function done(){atEnd&&delays.length===0&&observer.onCompleted()}if(!subDelay){start()}else{subscription.setDisposable(subDelay.subscribe(start,function(e){observer.onError(e)},start))}return new CompositeDisposable(subscription,delays)},this)};observableProto.timeoutWithSelector=function(firstTimeout,timeoutdurationSelector,other){if(arguments.length===1){timeoutdurationSelector=firstTimeout;firstTimeout=observableNever()}other||(other=observableThrow(new Error("Timeout")));var source=this;return new AnonymousObservable(function(observer){var subscription=new SerialDisposable,timer=new SerialDisposable,original=new SingleAssignmentDisposable;subscription.setDisposable(original);var id=0,switched=false;function setTimer(timeout){var myId=id;function timerWins(){return id===myId}var d=new SingleAssignmentDisposable;timer.setDisposable(d);d.setDisposable(timeout.subscribe(function(){timerWins()&&subscription.setDisposable(other.subscribe(observer));d.dispose()},function(e){timerWins()&&observer.onError(e)},function(){timerWins()&&subscription.setDisposable(other.subscribe(observer))}))}setTimer(firstTimeout);function observerWins(){var res=!switched;if(res){id++}return res}original.setDisposable(source.subscribe(function(x){if(observerWins()){observer.onNext(x);var timeout;try{timeout=timeoutdurationSelector(x)}catch(e){observer.onError(e);return}setTimer(isPromise(timeout)?observableFromPromise(timeout):timeout)}},function(e){observerWins()&&observer.onError(e)},function(){observerWins()&&observer.onCompleted()}));return new CompositeDisposable(subscription,timer)},source)};observableProto.debounceWithSelector=function(durationSelector){var source=this;return new AnonymousObservable(function(o){var value,hasValue=false,cancelable=new SerialDisposable,id=0;var subscription=source.subscribe(function(x){var throttle=tryCatch(durationSelector)(x);if(throttle===errorObj){return o.onError(throttle.e)}isPromise(throttle)&&(throttle=observableFromPromise(throttle));hasValue=true;value=x;id++;var currentid=id,d=new SingleAssignmentDisposable;cancelable.setDisposable(d);d.setDisposable(throttle.subscribe(function(){hasValue&&id===currentid&&o.onNext(value);hasValue=false;d.dispose()},function(e){o.onError(e)},function(){hasValue&&id===currentid&&o.onNext(value);hasValue=false;d.dispose()}))},function(e){cancelable.dispose();o.onError(e);hasValue=false;id++},function(){cancelable.dispose();hasValue&&o.onNext(value);o.onCompleted();hasValue=false;id++});return new CompositeDisposable(subscription,cancelable)},source)};observableProto.skipLastWithTime=function(duration,scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);var source=this;return new AnonymousObservable(function(o){var q=[];return source.subscribe(function(x){var now=scheduler.now();q.push({interval:now,value:x});while(q.length>0&&now-q[0].interval>=duration){o.onNext(q.shift().value)}},function(e){o.onError(e)},function(){var now=scheduler.now();while(q.length>0&&now-q[0].interval>=duration){o.onNext(q.shift().value)}o.onCompleted()})},source)};observableProto.takeLastWithTime=function(duration,scheduler){var source=this;isScheduler(scheduler)||(scheduler=timeoutScheduler);return new AnonymousObservable(function(o){var q=[];return source.subscribe(function(x){var now=scheduler.now();q.push({interval:now,value:x});while(q.length>0&&now-q[0].interval>=duration){q.shift()}},function(e){o.onError(e)},function(){var now=scheduler.now();while(q.length>0){var next=q.shift();if(now-next.interval<=duration){o.onNext(next.value)}}o.onCompleted()})},source)};observableProto.takeLastBufferWithTime=function(duration,scheduler){var source=this;isScheduler(scheduler)||(scheduler=timeoutScheduler);return new AnonymousObservable(function(o){var q=[];return source.subscribe(function(x){var now=scheduler.now();q.push({interval:now,value:x});while(q.length>0&&now-q[0].interval>=duration){q.shift()}},function(e){o.onError(e)},function(){var now=scheduler.now(),res=[];while(q.length>0){var next=q.shift();now-next.interval<=duration&&res.push(next.value)}o.onNext(res);o.onCompleted()})},source)};observableProto.takeWithTime=function(duration,scheduler){var source=this;isScheduler(scheduler)||(scheduler=timeoutScheduler);return new AnonymousObservable(function(o){return new CompositeDisposable(scheduler.scheduleWithRelative(duration,function(){o.onCompleted()}),source.subscribe(o))},source)};observableProto.skipWithTime=function(duration,scheduler){var source=this;isScheduler(scheduler)||(scheduler=timeoutScheduler);return new AnonymousObservable(function(observer){var open=false;return new CompositeDisposable(scheduler.scheduleWithRelative(duration,function(){open=true}),source.subscribe(function(x){open&&observer.onNext(x)},observer.onError.bind(observer),observer.onCompleted.bind(observer)))},source)};observableProto.skipUntilWithTime=function(startTime,scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);var source=this,schedulerMethod=startTime instanceof Date?"scheduleWithAbsolute":"scheduleWithRelative";return new AnonymousObservable(function(o){var open=false;return new CompositeDisposable(scheduler[schedulerMethod](startTime,function(){open=true}),source.subscribe(function(x){open&&o.onNext(x)},function(e){o.onError(e)},function(){o.onCompleted()}))},source)};observableProto.takeUntilWithTime=function(endTime,scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);var source=this,schedulerMethod=endTime instanceof Date?"scheduleWithAbsolute":"scheduleWithRelative";return new AnonymousObservable(function(o){return new CompositeDisposable(scheduler[schedulerMethod](endTime,function(){o.onCompleted()}),source.subscribe(o))},source)};observableProto.throttleFirst=function(windowDuration,scheduler){isScheduler(scheduler)||(scheduler=timeoutScheduler);var duration=+windowDuration||0;if(duration<=0){throw new RangeError("windowDuration cannot be less or equal zero.")}var source=this;return new AnonymousObservable(function(o){var lastOnNext=0;return source.subscribe(function(x){var now=scheduler.now();if(lastOnNext===0||now-lastOnNext>=duration){lastOnNext=now;o.onNext(x)}},function(e){o.onError(e)},function(){o.onCompleted()})},source)};observableProto.transduce=function(transducer){var source=this;function transformForObserver(o){return{"@@transducer/init":function(){return o},"@@transducer/step":function(obs,input){return obs.onNext(input)},"@@transducer/result":function(obs){return obs.onCompleted()}}}return new AnonymousObservable(function(o){var xform=transducer(transformForObserver(o));return source.subscribe(function(v){var res=tryCatch(xform["@@transducer/step"]).call(xform,o,v);if(res===errorObj){o.onError(res.e)}},function(e){o.onError(e)},function(){xform["@@transducer/result"](o)})},source)};observableProto.switchFirst=function(){var sources=this;return new AnonymousObservable(function(o){var hasCurrent=false,isStopped=false,m=new SingleAssignmentDisposable,g=new CompositeDisposable;g.add(m);m.setDisposable(sources.subscribe(function(innerSource){if(!hasCurrent){hasCurrent=true;isPromise(innerSource)&&(innerSource=observableFromPromise(innerSource));var innerSubscription=new SingleAssignmentDisposable;g.add(innerSubscription);innerSubscription.setDisposable(innerSource.subscribe(function(x){o.onNext(x)},function(e){o.onError(e)},function(){g.remove(innerSubscription);hasCurrent=false;isStopped&&g.length===1&&o.onCompleted()}))}},function(e){o.onError(e)},function(){isStopped=true;!hasCurrent&&g.length===1&&o.onCompleted()}));return g},this)};observableProto.flatMapFirst=observableProto.selectManyFirst=function(selector,resultSelector,thisArg){return new FlatMapObservable(this,selector,resultSelector,thisArg).switchFirst()};Rx.Observable.prototype.flatMapWithMaxConcurrent=function(limit,selector,resultSelector,thisArg){return new FlatMapObservable(this,selector,resultSelector,thisArg).merge(limit)};var VirtualTimeScheduler=Rx.VirtualTimeScheduler=function(__super__){function localNow(){return this.toDateTimeOffset(this.clock)}function scheduleNow(state,action){return this.scheduleAbsoluteWithState(state,this.clock,action)}function scheduleRelative(state,dueTime,action){return this.scheduleRelativeWithState(state,this.toRelative(dueTime),action)}function scheduleAbsolute(state,dueTime,action){return this.scheduleRelativeWithState(state,this.toRelative(dueTime-this.now()),action)}function invokeAction(scheduler,action){action();return disposableEmpty}inherits(VirtualTimeScheduler,__super__);function VirtualTimeScheduler(initialClock,comparer){this.clock=initialClock;this.comparer=comparer;this.isEnabled=false;this.queue=new PriorityQueue(1024);__super__.call(this,localNow,scheduleNow,scheduleRelative,scheduleAbsolute)}var VirtualTimeSchedulerPrototype=VirtualTimeScheduler.prototype;VirtualTimeSchedulerPrototype.add=notImplemented;VirtualTimeSchedulerPrototype.toDateTimeOffset=notImplemented;VirtualTimeSchedulerPrototype.toRelative=notImplemented;VirtualTimeSchedulerPrototype.schedulePeriodicWithState=function(state,period,action){var s=new SchedulePeriodicRecursive(this,state,period,action);return s.start()};VirtualTimeSchedulerPrototype.scheduleRelativeWithState=function(state,dueTime,action){var runAt=this.add(this.clock,dueTime);return this.scheduleAbsoluteWithState(state,runAt,action)};VirtualTimeSchedulerPrototype.scheduleRelative=function(dueTime,action){return this.scheduleRelativeWithState(action,dueTime,invokeAction)};VirtualTimeSchedulerPrototype.start=function(){if(!this.isEnabled){this.isEnabled=true;do{var next=this.getNext();if(next!==null){this.comparer(next.dueTime,this.clock)>0&&(this.clock=next.dueTime);next.invoke()}else{this.isEnabled=false}}while(this.isEnabled)}};VirtualTimeSchedulerPrototype.stop=function(){this.isEnabled=false};VirtualTimeSchedulerPrototype.advanceTo=function(time){var dueToClock=this.comparer(this.clock,time);if(this.comparer(this.clock,time)>0){throw new ArgumentOutOfRangeError}if(dueToClock===0){return}if(!this.isEnabled){this.isEnabled=true;do{var next=this.getNext();if(next!==null&&this.comparer(next.dueTime,time)<=0){this.comparer(next.dueTime,this.clock)>0&&(this.clock=next.dueTime);next.invoke()}else{this.isEnabled=false}}while(this.isEnabled);this.clock=time}};VirtualTimeSchedulerPrototype.advanceBy=function(time){var dt=this.add(this.clock,time),dueToClock=this.comparer(this.clock,dt);if(dueToClock>0){throw new ArgumentOutOfRangeError}if(dueToClock===0){return}this.advanceTo(dt)};VirtualTimeSchedulerPrototype.sleep=function(time){var dt=this.add(this.clock,time);if(this.comparer(this.clock,dt)>=0){throw new ArgumentOutOfRangeError}this.clock=dt};VirtualTimeSchedulerPrototype.getNext=function(){while(this.queue.length>0){var next=this.queue.peek();if(next.isCancelled()){this.queue.dequeue()}else{return next}}return null};VirtualTimeSchedulerPrototype.scheduleAbsolute=function(dueTime,action){return this.scheduleAbsoluteWithState(action,dueTime,invokeAction)};VirtualTimeSchedulerPrototype.scheduleAbsoluteWithState=function(state,dueTime,action){var self=this;function run(scheduler,state1){self.queue.remove(si);return action(scheduler,state1)}var si=new ScheduledItem(this,state,run,dueTime,this.comparer);this.queue.enqueue(si);return si.disposable};return VirtualTimeScheduler}(Scheduler);Rx.HistoricalScheduler=function(__super__){inherits(HistoricalScheduler,__super__);function HistoricalScheduler(initialClock,comparer){var clock=initialClock==null?0:initialClock;var cmp=comparer||defaultSubComparer;__super__.call(this,clock,cmp)}var HistoricalSchedulerProto=HistoricalScheduler.prototype;HistoricalSchedulerProto.add=function(absolute,relative){return absolute+relative};HistoricalSchedulerProto.toDateTimeOffset=function(absolute){return new Date(absolute).getTime()};HistoricalSchedulerProto.toRelative=function(timeSpan){return timeSpan};return HistoricalScheduler}(Rx.VirtualTimeScheduler);var AnonymousObservable=Rx.AnonymousObservable=function(__super__){inherits(AnonymousObservable,__super__);function fixSubscriber(subscriber){return subscriber&&isFunction(subscriber.dispose)?subscriber:isFunction(subscriber)?disposableCreate(subscriber):disposableEmpty}function setDisposable(s,state){var ado=state[0],self=state[1];var sub=tryCatch(self.__subscribe).call(self,ado);if(sub===errorObj){if(!ado.fail(errorObj.e)){return thrower(errorObj.e)}}ado.setDisposable(fixSubscriber(sub))}function innerSubscribe(observer){var ado=new AutoDetachObserver(observer),state=[ado,this];if(currentThreadScheduler.scheduleRequired()){currentThreadScheduler.scheduleWithState(state,setDisposable)}else{setDisposable(null,state)}return ado}function AnonymousObservable(subscribe,parent){this.source=parent;this.__subscribe=subscribe;__super__.call(this,innerSubscribe)}return AnonymousObservable}(Observable);var AutoDetachObserver=function(__super__){inherits(AutoDetachObserver,__super__);function AutoDetachObserver(observer){__super__.call(this);this.observer=observer;this.m=new SingleAssignmentDisposable}var AutoDetachObserverPrototype=AutoDetachObserver.prototype;AutoDetachObserverPrototype.next=function(value){var result=tryCatch(this.observer.onNext).call(this.observer,value);if(result===errorObj){this.dispose();thrower(result.e)}};AutoDetachObserverPrototype.error=function(err){var result=tryCatch(this.observer.onError).call(this.observer,err);this.dispose();result===errorObj&&thrower(result.e)};AutoDetachObserverPrototype.completed=function(){var result=tryCatch(this.observer.onCompleted).call(this.observer);this.dispose();result===errorObj&&thrower(result.e)};AutoDetachObserverPrototype.setDisposable=function(value){this.m.setDisposable(value)};AutoDetachObserverPrototype.getDisposable=function(){return this.m.getDisposable()};AutoDetachObserverPrototype.dispose=function(){__super__.prototype.dispose.call(this);this.m.dispose()};return AutoDetachObserver}(AbstractObserver);var GroupedObservable=function(__super__){inherits(GroupedObservable,__super__);function subscribe(observer){return this.underlyingObservable.subscribe(observer)}function GroupedObservable(key,underlyingObservable,mergedDisposable){__super__.call(this,subscribe);this.key=key;this.underlyingObservable=!mergedDisposable?underlyingObservable:new AnonymousObservable(function(observer){return new CompositeDisposable(mergedDisposable.getDisposable(),underlyingObservable.subscribe(observer))})}return GroupedObservable}(Observable);var Subject=Rx.Subject=function(__super__){function subscribe(observer){checkDisposed(this);if(!this.isStopped){this.observers.push(observer);return new InnerSubscription(this,observer)}if(this.hasError){observer.onError(this.error);return disposableEmpty}observer.onCompleted();return disposableEmpty}inherits(Subject,__super__);function Subject(){__super__.call(this,subscribe);this.isDisposed=false,this.isStopped=false,this.observers=[];this.hasError=false}addProperties(Subject.prototype,Observer.prototype,{hasObservers:function(){return this.observers.length>0},onCompleted:function(){checkDisposed(this);if(!this.isStopped){this.isStopped=true;for(var i=0,os=cloneArray(this.observers),len=os.length;i<len;i++){os[i].onCompleted()}this.observers.length=0}},onError:function(error){checkDisposed(this);if(!this.isStopped){this.isStopped=true;this.error=error;this.hasError=true;for(var i=0,os=cloneArray(this.observers),len=os.length;i<len;i++){os[i].onError(error)}this.observers.length=0}},onNext:function(value){checkDisposed(this);if(!this.isStopped){for(var i=0,os=cloneArray(this.observers),len=os.length;i<len;i++){os[i].onNext(value)}}},dispose:function(){this.isDisposed=true;this.observers=null}});Subject.create=function(observer,observable){return new AnonymousSubject(observer,observable)};return Subject}(Observable);var AsyncSubject=Rx.AsyncSubject=function(__super__){function subscribe(observer){checkDisposed(this);if(!this.isStopped){this.observers.push(observer);return new InnerSubscription(this,observer)}if(this.hasError){observer.onError(this.error)}else if(this.hasValue){observer.onNext(this.value);observer.onCompleted()}else{observer.onCompleted()}return disposableEmpty}inherits(AsyncSubject,__super__);function AsyncSubject(){__super__.call(this,subscribe);this.isDisposed=false;this.isStopped=false;this.hasValue=false;this.observers=[];this.hasError=false}addProperties(AsyncSubject.prototype,Observer,{hasObservers:function(){checkDisposed(this);return this.observers.length>0},onCompleted:function(){var i,len;checkDisposed(this);if(!this.isStopped){this.isStopped=true;var os=cloneArray(this.observers),len=os.length;if(this.hasValue){for(i=0;i<len;i++){var o=os[i];o.onNext(this.value);o.onCompleted()}}else{for(i=0;i<len;i++){os[i].onCompleted()}}this.observers.length=0}},onError:function(error){checkDisposed(this);if(!this.isStopped){this.isStopped=true;this.hasError=true;this.error=error;for(var i=0,os=cloneArray(this.observers),len=os.length;i<len;i++){os[i].onError(error)}this.observers.length=0}},onNext:function(value){checkDisposed(this);if(this.isStopped){return}this.value=value;this.hasValue=true},dispose:function(){this.isDisposed=true;this.observers=null;this.exception=null;this.value=null}});return AsyncSubject}(Observable);var AnonymousSubject=Rx.AnonymousSubject=function(__super__){inherits(AnonymousSubject,__super__);function subscribe(observer){return this.observable.subscribe(observer)}function AnonymousSubject(observer,observable){this.observer=observer;this.observable=observable;__super__.call(this,subscribe)}addProperties(AnonymousSubject.prototype,Observer.prototype,{onCompleted:function(){this.observer.onCompleted()},onError:function(error){this.observer.onError(error)},onNext:function(value){this.observer.onNext(value)}});return AnonymousSubject}(Observable);Rx.Pauser=function(__super__){inherits(Pauser,__super__);function Pauser(){__super__.call(this)}Pauser.prototype.pause=function(){this.onNext(false)};Pauser.prototype.resume=function(){this.onNext(true)};return Pauser}(Subject);if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){root.Rx=Rx;define(function(){return Rx})}else if(freeExports&&freeModule){if(moduleExports){(freeModule.exports=Rx).Rx=Rx}else{freeExports.Rx=Rx}}else{root.Rx=Rx}var rEndingLine=captureLine()}).call(this)}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{_process:1}],3:[function(require,module,exports){"use strict";var Rx=require("rx");function makeRequestProxies(drivers){var requestProxies={};for(var _name in drivers){if(drivers.hasOwnProperty(_name)){requestProxies[_name]=new Rx.ReplaySubject(1)}}return requestProxies}function callDrivers(drivers,requestProxies){var responses={};for(var _name2 in drivers){if(drivers.hasOwnProperty(_name2)){responses[_name2]=drivers[_name2](requestProxies[_name2],_name2)}}return responses}function attachDisposeToRequests(requests,replicationSubscription){Object.defineProperty(requests,"dispose",{enumerable:false,value:function value(){replicationSubscription.dispose()}});return requests}function makeDisposeResponses(responses){return function dispose(){for(var _name3 in responses){if(responses.hasOwnProperty(_name3)&&typeof responses[_name3].dispose==="function"){responses[_name3].dispose()}}}}function attachDisposeToResponses(responses){Object.defineProperty(responses,"dispose",{enumerable:false,value:makeDisposeResponses(responses)});return responses}function logToConsoleError(err){var target=err.stack||err;if(console&&console.error){console.error(target)}}function replicateMany(observables,subjects){return Rx.Observable.create(function(observer){var subscription=new Rx.CompositeDisposable;setTimeout(function(){for(var _name4 in observables){if(observables.hasOwnProperty(_name4)&&subjects.hasOwnProperty(_name4)&&!subjects[_name4].isDisposed){subscription.add(observables[_name4].doOnError(logToConsoleError).subscribe(subjects[_name4].asObserver()))}}observer.onNext(subscription)},1);return function dispose(){subscription.dispose();for(var x in subjects){if(subjects.hasOwnProperty(x)){subjects[x].dispose()}}}})}function isObjectEmpty(obj){for(var key in obj){if(obj.hasOwnProperty(key)){return false}}return true}function run(main,drivers){if(typeof main!=="function"){throw new Error("First argument given to Cycle.run() must be the 'main' "+"function.")}if(typeof drivers!=="object"||drivers===null){throw new Error("Second argument given to Cycle.run() must be an object "+"with driver functions as properties.")}if(isObjectEmpty(drivers)){throw new Error("Second argument given to Cycle.run() must be an object "+"with at least one driver function declared as a property.")}var requestProxies=makeRequestProxies(drivers);var responses=callDrivers(drivers,requestProxies);
var requests=main(responses);var subscription=replicateMany(requests,requestProxies).subscribe();var requestsWithDispose=attachDisposeToRequests(requests,subscription);var responsesWithDispose=attachDisposeToResponses(responses);return[requestsWithDispose,responsesWithDispose]}var Cycle={run:run,Rx:Rx};module.exports=Cycle},{rx:2}]},{},[3])(3)});
|
"""
BFS time complexity : O(|E|)
BFS space complexity : O(|V|)
do BFS from (0,0) of the grid and get the minimum number of steps needed to get to the lower right column
only step on the columns whose value is 1
if there is no path, it returns -1
Ex 1)
If grid is
[[1,0,1,1,1,1],
[1,0,1,0,1,0],
[1,0,1,0,1,1],
[1,1,1,0,1,1]],
the answer is: 14
Ex 2)
If grid is
[[1,0,0],
[0,1,1],
[0,1,1]],
the answer is: -1
"""
def maze_search(grid):
dx = [0, 0, -1, 1]
dy = [-1, 1, 0, 0]
n = len(grid)
m = len(grid[0])
q = [(0, 0, 0)]
visit = [[0]*m for _ in range(n)]
if grid[0][0] == 0:
return -1
visit[0][0] = 1
while q:
i, j, step = q.pop(0)
if i == n-1 and j == m-1:
return step
for k in range(4):
x = i + dx[k]
y = j + dy[k]
if (0 <= x < n and y >= 0 and y) < m:
if grid[x][y] == 1 and visit[x][y] == 0:
visit[x][y] = 1
q.append((x, y, step+1))
return -1
|
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2009 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
#ifndef _SYS_SCSI_SCSI_RESOURCE_H
#define _SYS_SCSI_SCSI_RESOURCE_H
#ifdef __lock_lint
#include <note.h>
#endif
#include <sys/scsi/scsi_types.h>
#ifdef __cplusplus
extern "C" {
#endif
/*
* SCSI Resource Function Declarations
*/
/*
* Defines for stating preferences in resource allocation
*/
#define NULL_FUNC ((int (*)())0)
#define SLEEP_FUNC ((int (*)())1)
#ifdef _KERNEL
/*
* Defines for the flags to scsi_init_pkt()
*/
#define PKT_CONSISTENT 0x0001 /* this is an 'iopb' packet */
#define PKT_DMA_PARTIAL 0x040000 /* partial xfer ok */
#define PKT_XARQ 0x080000 /* request for extra sense */
/*
* Old PKT_CONSISTENT value for binary compatibility with x86 2.1
*/
#define PKT_CONSISTENT_OLD 0x001000
/*
* Kernel function declarations
*/
struct buf *scsi_alloc_consistent_buf(struct scsi_address *,
struct buf *, size_t, uint_t, int (*)(caddr_t), caddr_t);
struct scsi_pkt *scsi_init_pkt(struct scsi_address *,
struct scsi_pkt *, struct buf *, int, int, int, int,
int (*)(caddr_t), caddr_t);
void scsi_destroy_pkt(struct scsi_pkt *);
void scsi_free_consistent_buf(struct buf *);
int scsi_pkt_allocated_correctly(struct scsi_pkt *);
struct scsi_pkt *scsi_dmaget(struct scsi_pkt *, opaque_t, int (*)(void));
void scsi_dmafree(struct scsi_pkt *);
void scsi_sync_pkt(struct scsi_pkt *);
/*
* Private wrapper for scsi_pkt's allocated via scsi_init_cache_pkt()
*/
struct scsi_pkt_cache_wrapper {
struct scsi_pkt pcw_pkt;
int pcw_magic;
uint_t pcw_total_xfer;
uint_t pcw_curwin;
uint_t pcw_totalwin;
uint_t pcw_granular;
struct buf *pcw_bp;
ddi_dma_cookie_t pcw_cookie;
uint_t pcw_flags;
};
#ifdef __lock_lint
_NOTE(SCHEME_PROTECTS_DATA("unique per packet",
scsi_pkt_cache_wrapper::pcw_bp
scsi_pkt_cache_wrapper::pcw_curwin
scsi_pkt_cache_wrapper::pcw_flags
scsi_pkt_cache_wrapper::pcw_granular
scsi_pkt_cache_wrapper::pcw_total_xfer
scsi_pkt_cache_wrapper::pcw_totalwin))
#endif
struct buf *scsi_pkt2bp(struct scsi_pkt *);
#define PCW_NEED_EXT_CDB 0x0001
#define PCW_NEED_EXT_TGT 0x0002
#define PCW_NEED_EXT_SCB 0x0004
#define PCW_BOUND 0x0020
/*
* Private defines i.e. not part of the DDI.
*/
#define DEFAULT_CDBLEN 16
#define DEFAULT_PRIVLEN 0
#define DEFAULT_SCBLEN (sizeof (struct scsi_arq_status))
/* Private functions */
size_t scsi_pkt_size();
void scsi_size_clean(dev_info_t *);
/* Obsolete kernel functions: */
struct scsi_pkt *scsi_pktalloc(struct scsi_address *, int, int, int (*)(void));
struct scsi_pkt *scsi_resalloc(struct scsi_address *, int,
int, opaque_t, int (*)(void));
void scsi_resfree(struct scsi_pkt *);
#define scsi_pktfree scsi_resfree
#endif /* _KERNEL */
#ifdef __cplusplus
}
#endif
#endif /* _SYS_SCSI_SCSI_RESOURCE_H */
|
if __name__ == '__main__':
import sys
import os
pkg_dir = os.path.split(os.path.abspath(__file__))[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = (pkg_name == 'tests' and
os.path.split(parent_dir)[1] == 'pygame')
if not is_pygame_pkg:
sys.path.insert(0, parent_dir)
else:
is_pygame_pkg = __name__.startswith('pygame.tests.')
import unittest
import pygame
import sys
import platform
IS_PYPY = 'PyPy' == platform.python_implementation()
if not IS_PYPY: #TODO: pypy skip known failure.
class SurfaceLockTest (unittest.TestCase):
def test_lock (self):
sf = pygame.Surface ((5, 5))
sf.lock ()
self.assertEquals (sf.get_locked (), True)
self.assertEquals (sf.get_locks (), (sf,))
sf.lock ()
self.assertEquals (sf.get_locked (), True)
self.assertEquals (sf.get_locks (), (sf, sf))
sf.unlock ()
self.assertEquals (sf.get_locked (), True)
self.assertEquals (sf.get_locks (), (sf,))
sf.unlock ()
self.assertEquals (sf.get_locked (), False)
self.assertEquals (sf.get_locks (), ())
def test_subsurface_lock (self):
sf = pygame.Surface ((5, 5))
subsf = sf.subsurface ((1, 1, 2, 2))
sf2 = pygame.Surface ((5, 5))
# Simple blits, nothing should happen here.
sf2.blit (subsf, (0, 0))
sf2.blit (sf, (0, 0))
# Test blitting on self:
self.assertRaises (pygame.error, sf.blit, subsf, (0, 0))
#self.assertRaises (pygame.error, subsf.blit, sf, (0, 0))
# ^ Fails although it should not in my opinion. If I cannot
# blit the subsurface to the surface, it should not be allowed
# the other way around as well.
# Test additional locks.
sf.lock ()
sf2.blit (subsf, (0, 0))
self.assertRaises (pygame.error, sf2.blit, sf, (0, 0))
subsf.lock ()
self.assertRaises (pygame.error, sf2.blit, subsf, (0, 0))
self.assertRaises (pygame.error, sf2.blit, sf, (0, 0))
# sf and subsf are now explicitly locked. Unlock sf, so we can
# (assume) to blit it.
# It will fail though as the subsurface still has a lock around,
# which is okay and correct behaviour.
sf.unlock ()
self.assertRaises (pygame.error, sf2.blit, subsf, (0, 0))
self.assertRaises (pygame.error, sf2.blit, sf, (0, 0))
# Run a second unlock on the surface. This should ideally have
# no effect as the subsurface is the locking reason!
sf.unlock ()
self.assertRaises (pygame.error, sf2.blit, sf, (0, 0))
self.assertRaises (pygame.error, sf2.blit, subsf, (0, 0))
subsf.unlock ()
sf.lock ()
self.assertEquals (sf.get_locked (), True)
self.assertEquals (sf.get_locks (), (sf,))
self.assertEquals (subsf.get_locked (), False)
self.assertEquals (subsf.get_locks (), ())
subsf.lock ()
self.assertEquals (sf.get_locked (), True)
self.assertEquals (sf.get_locks (), (sf, subsf))
self.assertEquals (subsf.get_locked (), True)
self.assertEquals (subsf.get_locks (), (subsf,))
sf.unlock ()
self.assertEquals (sf.get_locked (), True)
self.assertEquals (sf.get_locks (), (subsf,))
self.assertEquals (subsf.get_locked (), True)
self.assertEquals (subsf.get_locks (), (subsf,))
subsf.unlock ()
self.assertEquals (sf.get_locked (), False)
self.assertEquals (sf.get_locks (), ())
self.assertEquals (subsf.get_locked (), False)
self.assertEquals (subsf.get_locks (), ())
subsf.lock ()
self.assertEquals (sf.get_locked (), True)
self.assertEquals (sf.get_locks (), (subsf,))
self.assertEquals (subsf.get_locked (), True)
self.assertEquals (subsf.get_locks (), (subsf,))
subsf.lock ()
self.assertEquals (sf.get_locked (), True)
self.assertEquals (sf.get_locks (), (subsf, subsf))
self.assertEquals (subsf.get_locked (), True)
self.assertEquals (subsf.get_locks (), (subsf, subsf))
def test_pxarray_ref (self):
sf = pygame.Surface ((5, 5))
ar = pygame.PixelArray (sf)
ar2 = pygame.PixelArray (sf)
self.assertEquals (sf.get_locked (), True)
self.assertEquals (sf.get_locks (), (ar, ar2))
del ar
self.assertEquals (sf.get_locked (), True)
self.assertEquals (sf.get_locks (), (ar2,))
ar = ar2[:]
self.assertEquals (sf.get_locked (), True)
self.assertEquals (sf.get_locks (), (ar2,))
del ar
self.assertEquals (sf.get_locked (), True)
self.assertEquals (len (sf.get_locks ()), 1)
def test_buffer (self):
sf = pygame.Surface ((5, 5))
buf = sf.get_buffer ()
self.assertEquals (sf.get_locked (), True)
self.assertEquals (sf.get_locks (), (buf,))
sf.unlock ()
self.assertEquals (sf.get_locked (), True)
self.assertEquals (sf.get_locks (), (buf,))
del buf
self.assertEquals (sf.get_locked (), False)
self.assertEquals (sf.get_locks (), ())
if __name__ == '__main__':
unittest.main()
|
# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
# with the License. A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "LICENSE.txt" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
# OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions and
# limitations under the License.
import datetime
from flask import Flask, Response, request, send_from_directory
from flask.json import JSONEncoder
from flask_cors import CORS # comment this on deployment
from flask_restful import Api
import api.utils as utils
from api.PclusterApiHandler import (
PclusterApiHandler,
authenticate,
authenticated,
get_cluster_config,
get_custom_image_config,
get_dcv_session,
get_aws_config,
get_identity,
list_users,
login,
logout,
set_user_role,
)
class PClusterJSONEncoder(JSONEncoder):
"""Make the model objects JSON serializable."""
include_nulls = False
def default(self, obj):
if isinstance(obj, datetime.date):
return utils.to_iso_timestr(obj)
return JSONEncoder.default(self, obj)
def run():
app = Flask(__name__, static_url_path="", static_folder="frontend/public")
app.json_encoder = PClusterJSONEncoder
CORS(app) # comment this on deployment
api = Api(app)
@app.before_request
def authenticate_static():
# Ensure we redirect to login on loading of index.html
return authenticate("guest") if "index.html" in request.path else None
@app.errorhandler(401)
def custom_401(_error):
return Response(
"You are not authorized to perform this action.", 401, {"WWW-Authenticate": 'Basic realm="Login Required"'}
)
@app.route("/", defaults={"path": ""})
@authenticated()
def serve(path):
return send_from_directory(app.static_folder, "index.html")
@app.route("/manager/get_cluster_configuration")
@authenticated()
def get_cluster_config_():
return get_cluster_config()
@app.route("/manager/get_custom_image_configuration")
@authenticated()
def get_custom_image_config_():
return get_custom_image_config()
@app.route("/manager/get_aws_configuration")
@authenticated()
def get_aws_config_():
return get_aws_config()
@app.route("/manager/get_dcv_session")
@authenticated()
def get_dcv_session_():
return get_dcv_session()
@app.route("/manager/get_identity")
@authenticated("guest")
def get_identity_():
return get_identity()
@app.route("/manager/list_users")
@authenticated("admin")
def list_users_():
return list_users()
@app.route("/manager/set_user_role", methods=["PUT"])
@authenticated("admin")
def set_user_role_():
return set_user_role()
@app.route("/login")
def login_():
return login()
@app.route("/logout")
def logout_():
return logout()
api.add_resource(PclusterApiHandler, "/api")
return app
if __name__ == "__main__":
run()
|
/*! Lazy Load XT v0.8.11 2014-01-10
* http://ressio.github.io/lazy-load-xt
* (C) 2014 RESS.io
* Licensed under MIT */
(function ($, window, document) {
var options = $.lazyLoadXT,
matchMedia = window.matchMedia;
options.selector += ',picture';
$(document)
// remove default behaviour for inner <img> tag
.on('lazyinit', 'img', function (e, $el) {
if ($el.parent('picture').length) {
$el.lazyLoadXT.srcAttr = '';
}
})
// prepare <picture> polyfill
.on('lazyinit', 'picture', function (e, $el) {
if (!$el[0].firstChild) {
return;
}
var $img = $el.children('img');
if (!$img.length) {
$img = $('<img>').appendTo($el);
}
$img
.attr('width', $el.attr('width'))
.attr('height', $el.attr('height'));
})
// show picture
.on('lazyshow', 'picture', function (e, $el) {
if (!$el[0].firstChild) {
return;
}
var srcAttr = $el.lazyLoadXT.srcAttr,
isFuncSrcAttr = $.isFunction(srcAttr),
$img = $el.children('img'),
src = isFuncSrcAttr ? srcAttr($img) : $img.attr(srcAttr);
if (src) {
$img.attr('src', src);
}
if (matchMedia) {
$el
.children('br')
.each(function () {
var $child = $(this),
src = isFuncSrcAttr ? srcAttr($child) : $child.attr(srcAttr),
media = $child.attr('media');
if (src && (!media || matchMedia(media).matches)) {
$img.attr('src', src);
}
});
}
});
})(window.jQuery || window.Zepto, window, document);
|
import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import LikesContent from "./LikesContent";
import * as actions from "store/actions";
class PostLikes extends Component {
static propTypes = {
children: PropTypes.node,
className: PropTypes.string,
postId: PropTypes.string.isRequired,
likePost: PropTypes.func.isRequired,
deletePostLike: PropTypes.func.isRequired,
likes: PropTypes.array,
loading: PropTypes.bool,
currentUserId: PropTypes.string,
likeId: PropTypes.string,
likesCount: PropTypes.number,
dislikesCount: PropTypes.number,
userReaction: PropTypes.string
};
handleLikeClick = reaction => {
if (this.props.userReaction === reaction) {
this.props.deletePostLike(this.props.postId);
} else {
this.props.likePost(this.props.postId, reaction);
}
};
render() {
return (
<LikesContent
handleLikeClick={this.handleLikeClick}
likesCount={this.props.likesCount}
dislikesCount={this.props.dislikesCount}
userReaction={this.props.userReaction}
/>
);
}
}
const mapStateToProps = (state, ownProps) => {
const post = state.getIn(["posts", "posts", "byId", ownProps.postId]);
return {
likesCount: post.getIn(["reactionsCount", "Like"]),
dislikesCount: post.getIn(["reactionsCount", "Dislike"]),
userReaction: post.get("userReaction")
};
};
const mapDispatchToProps = dispatch => {
return {
likePost: (postId, reaction) =>
dispatch(actions.postsLike(postId, reaction)),
deletePostLike: postId => dispatch(actions.postsLikeDelete(postId))
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(PostLikes);
|
#-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2022, Anaconda, Inc. All rights reserved.
#
# Powered by the Bokeh Development Team.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Boilerplate
#-----------------------------------------------------------------------------
from __future__ import annotations # isort:skip
import pytest ; pytest
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
# Standard library imports
from subprocess import run
from sys import executable as python
# Bokeh imports
from bokeh._testing.util.project import ls_modules, verify_clean_imports
#-----------------------------------------------------------------------------
# Tests
#-----------------------------------------------------------------------------
TORNADO_ALLOWED = (
"bokeh._testing",
"bokeh.client",
"bokeh.command",
"bokeh.io.notebook",
"bokeh.server",
"bokeh.util.tornado",
)
MODULES = ls_modules(skip_prefixes=TORNADO_ALLOWED)
# This test takes a long time to run, but if the combined test fails then
# uncommenting it will locate exactly what module(s) are the problem
# @pytest.mark.parametrize('module', MODULES)
# def test_no_tornado_common_individual(module) -> None:
# proc = run([python, "-c", verify_clean_imports('tornado', [module])])
# assert proc.returncode == 0, f"Tornado imported in common module {module}"
def test_no_tornado_common_combined() -> None:
''' Basic usage of Bokeh should not result in any Tornado code being
imported. This test ensures that importing basic modules does not bring in
Tornado.
'''
proc = run([python, "-c", verify_clean_imports('tornado', MODULES)])
assert proc.returncode == 0, "Tornado imported in collective common modules"
|
from webclient.models import Image, ImageLabel, CategoryType
from django.conf import settings
from webclient.image_ops import convert_images
from PIL import Image as PILImage
from StringIO import StringIO
import numpy as np
import matplotlib.pyplot as plt
import requests
import urllib2
from webclient.image_ops import convert_images
def reflect(labelList = [ImageLabel.objects.all().last()]):
allLabels = labelPatch(map(lambda label:[parentImg(label), labels(label)],labelList))
for idx,patch in enumerate(allLabels):
if idx%25==0:
plt.subplots(5, 5)
plt.subplot(5,5,(idx%25)+1)
plt.imshow(patch)
return allLabels
def labels(label):
npArray = []
separatedPaths = convert_images.separatePaths(label.labelShapes)
if len(separatedPaths) > 0:
imgLabel = plt.imread(StringIO(separatedPaths[0]))
npArray = np.array(svgStringToXML(label))
return npArray
def parentImg(label):
image = label.parentImage
hostpath = 'http://airborne.ddns.net:8000'
imageURL = hostpath + image.path + image.name
return plt.imread(urllib2.urlopen(imageURL), format='jpeg')
def labelPatch(labelInfoList):
allLabelPatches = []
for labelInfo in labelInfoList:
vecAll = labelInfo[1]
imgParent = labelInfo[0]
if len(vecAll)>0:
xc=vecAll[:,0].astype(np.float)+vecAll[:,3].astype(np.float)
yc=vecAll[:,1].astype(np.float)+vecAll[:,4].astype(np.float)
delta = 1.3*vecAll[:,2].astype(np.float)
xr=(xc+delta).astype(np.int16)
yr=(yc+delta).astype(np.int16)
xl = (xc-delta).astype(np.int16)
yl = (yc-delta).astype(np.int16)
for i in range(0,len(vecAll)):
allLabelPatches.append(imgParent[yl[i]:yr[i],xl[i]:xr[i],:])
return allLabelPatches
def plotImageWithLabels(vecAll, imgParent):
dpi = 80.0
xpixels, ypixels = 1280, 1920
fig = plt.figure(figsize=(ypixels/dpi, xpixels/dpi), dpi=dpi)
plt.imshow(imgParent)
plt.hold('on')
plt.scatter(vecAll[:,0].astype(np.float)+vecAll[:,3].astype(np.float), vecAll[:,1].astype(np.float)+vecAll[:,4].astype(np.float), s=vecAll[:,2].astype(np.float)*vecAll[:,2].astype(np.float), facecolors='none', edgecolors='y', marker='o')
def svgStringToXML(labelDBObj):
import xml.etree.ElementTree as ET
svgXML = ET.fromstring(labelDBObj.labelShapes.encode())
vecAll = []
for circle in svgXML.findall('{http://www.w3.org/2000/svg}circle'):
keys = {'cx','cy', 'r'}
vec = []
for key in keys:
vec.append(circle.get(key))
trans = circle.get('transform')
exec('xt, yt = ' + trans)
vec.append(xt)
vec.append(yt)
vecAll.append(vec)
return vecAll
def translate(xt,yt):
return [xt, yt]
def plotAllPatchesForLabel(label):
dpi = 4.0
xpixels, ypixels = 400, 400
for idx,img in enumerate(labelSurvey.labelPatch(labelSurvey.reportLabelStats(label))):
fig = plt.figure(figsize=(ypixels/dpi, xpixels/dpi), dpi=dpi)
plt.subplot(25,1,idx+1)
plt.imshow(val)
def trainingsPatchForLabel(label):
imageParent = parentImg(label)
imageWindow = label.imageWindow
x = imageWindow.x
y = imageWindow.y
width = imageWindow.width
height = imageWindow.height
croppedImage = imageParent[y-20:(y+height+20),x-20:(x+width+20),:]
labelImage = convert_images.countableLabel(label.labelShapes)
croppedLabelImage = labelImage[y-20:(y+height+20),x-20:(x+width+20)]
return croppedImage,croppedLabelImage
|
import requests,json
import re
def chouqian(msg,user_id):
res = requests.get(f'https://api.iyk0.com/gdlq/?msg={msg}&n={user_id}')
try:
res = json.loads(res.text)
if res['code'] == 200:
data = res['title']
data += '\n'+res['desc']
# for i in res['data']:
# data += '\n'+i['sign'] + '\n'+i['sign_desc'] + '\n'
if len(res["data"][3]) < 3:
data += f'\n解签:\n{res["data"][0]["sign_desc"]}'
else:
data += f'\n解签:\n{res["data"][3]["sign_desc"]}'
else:
data = res['msg']
return data
except:
return res.text
def yiyan():
res = requests.get('http://api.guaqb.cn/v1/onesaid/').text
return f'兔宝·你抽出的纸条是:🍒{res}'
def icp(url):
res = requests.get('https://www.hlapi.cn/api/icp?url='+url).text
return res
def duanzi():
res = requests.get('https://www.hlapi.cn/api/gxdz').text
return res
def wuduanzi():
res = requests.get('https://res.abeim.cn/api-text_wu?export=json').text
res = json.loads(res)
return res['content']
def ping(url):
res = requests.get('https://res.abeim.cn/api-ping?domain='+url).text
res = json.loads(res)
return res
|
"""
The MIT License (MIT)
Copyright © 2019 Jean-Christophe Bos & HC² (www.hc2.fr)
"""
import _thread
class MicroWorkersException(Exception) :
pass
class MicroWorkers :
# ============================================================================
# ===( Thread )===============================================================
# ============================================================================
def _workerThreadFunc(self, arg) :
threadID = _thread.get_ident()
print('MicroWorkers: Thread #%s created' % threadID)
while True :
self._workersLock.acquire()
try :
jobName, jobFunc, jobArg, jobCBFunc = self._jobs.pop(0)
except :
jobFunc = None
print('MicroWorkers: Thread #%s waiting for a job...' % threadID)
self._workersLock.acquire()
self._workersLock.release()
if jobFunc :
with self._jobsLock :
self._jobsPrcCount += 1
print('MicroWorkers: Job %s starts in thread #%s' % (jobName, threadID))
try :
jobResult = jobFunc(jobName, jobArg)
print('MicroWorkers: Job %s finished successfully in thread #%s' % (jobName, threadID))
except Exception as ex :
jobResult = None
print('MicroWorkers: Job %s raises an exception in thread #%s : %s' % (jobName, threadID, ex))
if jobCBFunc :
try :
jobCBFunc(jobName, jobArg, jobResult)
except Exception as ex :
print('MicroWorkers: Finished callback of job %s raises an exception in thread #%s : %s' % (jobName, threadID, ex))
with self._jobsLock :
self._jobsPrcCount -= 1
# ============================================================================
# ===( Constructor )==========================================================
# ============================================================================
def __init__(self, workersCount, workersStackSize=None) :
self._workersCount = workersCount
self._workersLock = _thread.allocate_lock()
self._jobsLock = _thread.allocate_lock()
self._jobsPrcCount = 0
self._jobs = [ ]
originalStackSize = None
if not isinstance(workersCount, int) or workersCount <= 0 :
raise MicroWorkersException('"workersCount" must be an integer greater than zero.')
if workersStackSize is not None :
if not isinstance(workersStackSize, int) or workersStackSize <= 0 :
raise MicroWorkersException('"workersStackSize" must be an integer greater than zero or None.')
try :
originalStackSize = _thread.stack_size(workersStackSize)
except :
raise MicroWorkersException('"workersStackSize" of %s cannot be used.' % workersStackSize)
try :
for x in range(workersCount) :
_thread.start_new_thread(self._workerThreadFunc, (None, ))
except Exception as ex :
raise MicroWorkersException('Error to create workers : %s' % ex)
if originalStackSize is not None :
_thread.stack_size(originalStackSize)
# ============================================================================
# ===( Functions )============================================================
# ============================================================================
def AddJob(self, name, function, arg=None, onFinished=None) :
if function :
self._jobs.append( (name, function, arg, onFinished) )
print('MicroWorkers: Job %s added' % name)
try :
self._workersLock.release()
except :
pass
# ============================================================================
# ===( Properties )===========================================================
# ============================================================================
@property
def Count(self) :
return self._workersCount
# ----------------------------------------------------------------------------
@property
def JobsInQueue(self) :
return len(self._jobs)
# ----------------------------------------------------------------------------
@property
def JobsInProcess(self) :
return self._jobsPrcCount
# ----------------------------------------------------------------------------
@property
def IsWorking(self) :
return (len(self._jobs) > 0 or self._jobsPrcCount > 0)
# ============================================================================
# ============================================================================
# ============================================================================
|
const route = (path, element) => ({path, element});
export default route;
|
exports.foo = 'foo';
exports = {};
exports.bar = 'bar';
global.hasWrappedExportsRun = true;
|
"use strict";
exports.__esModule = true;
exports.useReduxContext = useReduxContext;
var _react = require("react");
var _Context = require("../components/Context");
/**
* A hook to access the value of the `ReactReduxContext`. This is a low-level
* hook that you should usually not need to call directly.
*
* @returns {any} the value of the `ReactReduxContext`
*
* @example
*
* import React from 'react'
* import { useReduxContext } from 'react-redux'
*
* export const CounterComponent = () => {
* const { store } = useReduxContext()
* return <div>{store.getState()}</div>
* }
*/
function useReduxContext() {
const contextValue = (0, _react.useContext)(_Context.ReactReduxContext);
if (process.env.NODE_ENV !== 'production' && !contextValue) {
throw new Error('could not find react-redux context value; please ensure the component is wrapped in a <Provider>');
}
return contextValue;
}
|