body_hash stringlengths 64 64 | body stringlengths 23 109k | docstring stringlengths 1 57k | path stringlengths 4 198 | name stringlengths 1 115 | repository_name stringlengths 7 111 | repository_stars float64 0 191k | lang stringclasses 1 value | body_without_docstring stringlengths 14 108k | unified stringlengths 45 133k |
|---|---|---|---|---|---|---|---|---|---|
deb4d7013b6a277c04e84c46979b4f528864eace97d04b6aa7ea4aa19f7cc18c | def unitVector(v):
' input: - v, array or list [x, y, z]\n output: - v_norm, array or list [x, y, z]\n normalizes a given vector using tf2_ros '
v = np.array(v, dtype=np.float64, copy=True)
if (v.ndim == 1):
v /= math.sqrt(np.dot(v, v))
return v | input: - v, array or list [x, y, z]
output: - v_norm, array or list [x, y, z]
normalizes a given vector using tf2_ros | rob9/scripts/rob9Utils/transformations.py | unitVector | daniellehot/ROB10 | 0 | python | def unitVector(v):
' input: - v, array or list [x, y, z]\n output: - v_norm, array or list [x, y, z]\n normalizes a given vector using tf2_ros '
v = np.array(v, dtype=np.float64, copy=True)
if (v.ndim == 1):
v /= math.sqrt(np.dot(v, v))
return v | def unitVector(v):
' input: - v, array or list [x, y, z]\n output: - v_norm, array or list [x, y, z]\n normalizes a given vector using tf2_ros '
v = np.array(v, dtype=np.float64, copy=True)
if (v.ndim == 1):
v /= math.sqrt(np.dot(v, v))
return v<|docstring|>input: - v, array or list [x, y, z]
output: - v_norm, array or list [x, y, z]
normalizes a given vector using tf2_ros<|endoftext|> |
c29c739ce21c2e497c18385c20df2cbe1875846108bd87afd05066d77a2afa12 | def quaternionFromRotation(R):
' Input: R - 3 x 3 numpy matrix or 2D list, rotation matrix\n Output: q - 1 x 4 numpy array, quaternion (x, y, z, w)\n https://github.com/cgohlke/transformations/blob/master/transformations/transformations.py\n '
K = np.array([[((R[(0, 0)] - R[(1, 1)]) - R[(2, 2)]), 0.0, 0.0, 0.0], [(R[(0, 1)] + R[(1, 0)]), ((R[(1, 1)] - R[(0, 0)]) - R[(2, 2)]), 0.0, 0.0], [(R[(0, 2)] + R[(2, 0)]), (R[(1, 2)] + R[(2, 1)]), ((R[(2, 2)] - R[(0, 0)]) - R[(1, 1)]), 0.0], [(R[(2, 1)] - R[(1, 2)]), (R[(0, 2)] - R[(2, 0)]), (R[(1, 0)] - R[(0, 1)]), ((R[(0, 0)] + R[(1, 1)]) + R[(2, 2)])]])
K /= 3.0
(w, V) = np.linalg.eigh(K)
q = V[([3, 0, 1, 2], np.argmax(w))]
if (q[0] < 0.0):
np.negative(q, q)
(w, x, y, z) = q
q[0] = x
q[1] = y
q[2] = z
q[3] = w
return q | Input: R - 3 x 3 numpy matrix or 2D list, rotation matrix
Output: q - 1 x 4 numpy array, quaternion (x, y, z, w)
https://github.com/cgohlke/transformations/blob/master/transformations/transformations.py | rob9/scripts/rob9Utils/transformations.py | quaternionFromRotation | daniellehot/ROB10 | 0 | python | def quaternionFromRotation(R):
' Input: R - 3 x 3 numpy matrix or 2D list, rotation matrix\n Output: q - 1 x 4 numpy array, quaternion (x, y, z, w)\n https://github.com/cgohlke/transformations/blob/master/transformations/transformations.py\n '
K = np.array([[((R[(0, 0)] - R[(1, 1)]) - R[(2, 2)]), 0.0, 0.0, 0.0], [(R[(0, 1)] + R[(1, 0)]), ((R[(1, 1)] - R[(0, 0)]) - R[(2, 2)]), 0.0, 0.0], [(R[(0, 2)] + R[(2, 0)]), (R[(1, 2)] + R[(2, 1)]), ((R[(2, 2)] - R[(0, 0)]) - R[(1, 1)]), 0.0], [(R[(2, 1)] - R[(1, 2)]), (R[(0, 2)] - R[(2, 0)]), (R[(1, 0)] - R[(0, 1)]), ((R[(0, 0)] + R[(1, 1)]) + R[(2, 2)])]])
K /= 3.0
(w, V) = np.linalg.eigh(K)
q = V[([3, 0, 1, 2], np.argmax(w))]
if (q[0] < 0.0):
np.negative(q, q)
(w, x, y, z) = q
q[0] = x
q[1] = y
q[2] = z
q[3] = w
return q | def quaternionFromRotation(R):
' Input: R - 3 x 3 numpy matrix or 2D list, rotation matrix\n Output: q - 1 x 4 numpy array, quaternion (x, y, z, w)\n https://github.com/cgohlke/transformations/blob/master/transformations/transformations.py\n '
K = np.array([[((R[(0, 0)] - R[(1, 1)]) - R[(2, 2)]), 0.0, 0.0, 0.0], [(R[(0, 1)] + R[(1, 0)]), ((R[(1, 1)] - R[(0, 0)]) - R[(2, 2)]), 0.0, 0.0], [(R[(0, 2)] + R[(2, 0)]), (R[(1, 2)] + R[(2, 1)]), ((R[(2, 2)] - R[(0, 0)]) - R[(1, 1)]), 0.0], [(R[(2, 1)] - R[(1, 2)]), (R[(0, 2)] - R[(2, 0)]), (R[(1, 0)] - R[(0, 1)]), ((R[(0, 0)] + R[(1, 1)]) + R[(2, 2)])]])
K /= 3.0
(w, V) = np.linalg.eigh(K)
q = V[([3, 0, 1, 2], np.argmax(w))]
if (q[0] < 0.0):
np.negative(q, q)
(w, x, y, z) = q
q[0] = x
q[1] = y
q[2] = z
q[3] = w
return q<|docstring|>Input: R - 3 x 3 numpy matrix or 2D list, rotation matrix
Output: q - 1 x 4 numpy array, quaternion (x, y, z, w)
https://github.com/cgohlke/transformations/blob/master/transformations/transformations.py<|endoftext|> |
550f924046582d344bf612ddf2fb037ae267a2406874123a03779e17a9494339 | def poseToMatrix(pose):
' Input:\n pose - array [x, y, z, qx, qy, qz, qw]\n\n Output:\n T - np.array, shape (4,4) homogeneous transformation matrix\n '
position = np.zeros(3)
position[0] = pose[0]
position[1] = pose[1]
position[2] = pose[2]
quaternion = np.zeros(4)
quaternion[0] = pose[3]
quaternion[1] = pose[4]
quaternion[2] = pose[5]
quaternion[3] = pose[6]
rotMat = quatToRot(quaternion)
T = np.identity(4)
T[(:3, :3)] = rotMat
T[(:3, 3)] = position
return T | Input:
pose - array [x, y, z, qx, qy, qz, qw]
Output:
T - np.array, shape (4,4) homogeneous transformation matrix | rob9/scripts/rob9Utils/transformations.py | poseToMatrix | daniellehot/ROB10 | 0 | python | def poseToMatrix(pose):
' Input:\n pose - array [x, y, z, qx, qy, qz, qw]\n\n Output:\n T - np.array, shape (4,4) homogeneous transformation matrix\n '
position = np.zeros(3)
position[0] = pose[0]
position[1] = pose[1]
position[2] = pose[2]
quaternion = np.zeros(4)
quaternion[0] = pose[3]
quaternion[1] = pose[4]
quaternion[2] = pose[5]
quaternion[3] = pose[6]
rotMat = quatToRot(quaternion)
T = np.identity(4)
T[(:3, :3)] = rotMat
T[(:3, 3)] = position
return T | def poseToMatrix(pose):
' Input:\n pose - array [x, y, z, qx, qy, qz, qw]\n\n Output:\n T - np.array, shape (4,4) homogeneous transformation matrix\n '
position = np.zeros(3)
position[0] = pose[0]
position[1] = pose[1]
position[2] = pose[2]
quaternion = np.zeros(4)
quaternion[0] = pose[3]
quaternion[1] = pose[4]
quaternion[2] = pose[5]
quaternion[3] = pose[6]
rotMat = quatToRot(quaternion)
T = np.identity(4)
T[(:3, :3)] = rotMat
T[(:3, 3)] = position
return T<|docstring|>Input:
pose - array [x, y, z, qx, qy, qz, qw]
Output:
T - np.array, shape (4,4) homogeneous transformation matrix<|endoftext|> |
ccea059c1c695963f007e0e460c9d2447755953c863e2175a5998ffd073e170c | def poseStampedToMatrix(msg):
' Input:\n msg - geometry_msgs/PoseStamped\n\n Output:\n T - np.array, shape (4,4) homogeneous transformation matrix\n '
position = np.zeros(3)
position[0] = msg.pose.position.x
position[1] = msg.pose.position.y
position[2] = msg.pose.position.z
quaternion = np.zeros(4)
quaternion[0] = msg.pose.orientation.x
quaternion[1] = msg.pose.orientation.y
quaternion[2] = msg.pose.orientation.z
quaternion[3] = msg.pose.orientation.w
rotMat = quatToRot(quaternion)
T = np.identity(4)
T[(:3, :3)] = rotMat
T[(:3, 3)] = position
return T | Input:
msg - geometry_msgs/PoseStamped
Output:
T - np.array, shape (4,4) homogeneous transformation matrix | rob9/scripts/rob9Utils/transformations.py | poseStampedToMatrix | daniellehot/ROB10 | 0 | python | def poseStampedToMatrix(msg):
' Input:\n msg - geometry_msgs/PoseStamped\n\n Output:\n T - np.array, shape (4,4) homogeneous transformation matrix\n '
position = np.zeros(3)
position[0] = msg.pose.position.x
position[1] = msg.pose.position.y
position[2] = msg.pose.position.z
quaternion = np.zeros(4)
quaternion[0] = msg.pose.orientation.x
quaternion[1] = msg.pose.orientation.y
quaternion[2] = msg.pose.orientation.z
quaternion[3] = msg.pose.orientation.w
rotMat = quatToRot(quaternion)
T = np.identity(4)
T[(:3, :3)] = rotMat
T[(:3, 3)] = position
return T | def poseStampedToMatrix(msg):
' Input:\n msg - geometry_msgs/PoseStamped\n\n Output:\n T - np.array, shape (4,4) homogeneous transformation matrix\n '
position = np.zeros(3)
position[0] = msg.pose.position.x
position[1] = msg.pose.position.y
position[2] = msg.pose.position.z
quaternion = np.zeros(4)
quaternion[0] = msg.pose.orientation.x
quaternion[1] = msg.pose.orientation.y
quaternion[2] = msg.pose.orientation.z
quaternion[3] = msg.pose.orientation.w
rotMat = quatToRot(quaternion)
T = np.identity(4)
T[(:3, :3)] = rotMat
T[(:3, 3)] = position
return T<|docstring|>Input:
msg - geometry_msgs/PoseStamped
Output:
T - np.array, shape (4,4) homogeneous transformation matrix<|endoftext|> |
6ee55324336d45dd50a1de2755ece8baed900297da1090379e0c1b3f932bfd66 | def start(self):
'\n Start output plugin\n '
self.apiKey = CowrieConfig.get('output_cowrie', 'api_key', fallback=None)
self.debug = CowrieConfig.getboolean('output_cowrie', 'debug', fallback=False) | Start output plugin | src/cowrie/output/crashreporter.py | start | maarlo/cowrie | 2,316 | python | def start(self):
'\n \n '
self.apiKey = CowrieConfig.get('output_cowrie', 'api_key', fallback=None)
self.debug = CowrieConfig.getboolean('output_cowrie', 'debug', fallback=False) | def start(self):
'\n \n '
self.apiKey = CowrieConfig.get('output_cowrie', 'api_key', fallback=None)
self.debug = CowrieConfig.getboolean('output_cowrie', 'debug', fallback=False)<|docstring|>Start output plugin<|endoftext|> |
695ae9a3a2db01c5fe7bce3c6d16cdfaadc457d95067729d10c4dc7b8894e394 | def emit(self, event):
'\n Note we override emit() here, unlike other plugins.\n '
if (event.get('log_level') == LogLevel.critical):
self.crashreport(event) | Note we override emit() here, unlike other plugins. | src/cowrie/output/crashreporter.py | emit | maarlo/cowrie | 2,316 | python | def emit(self, event):
'\n \n '
if (event.get('log_level') == LogLevel.critical):
self.crashreport(event) | def emit(self, event):
'\n \n '
if (event.get('log_level') == LogLevel.critical):
self.crashreport(event)<|docstring|>Note we override emit() here, unlike other plugins.<|endoftext|> |
91b1be3163082a16ac01b8c4c2b2ac8cf783a366c8a14e11f2a78f20eb80daa8 | def stop(self):
'\n Stop output plugin\n '
pass | Stop output plugin | src/cowrie/output/crashreporter.py | stop | maarlo/cowrie | 2,316 | python | def stop(self):
'\n \n '
pass | def stop(self):
'\n \n '
pass<|docstring|>Stop output plugin<|endoftext|> |
6cb9ca22ff07c8d0d0edaa78307857f9dd7afdfbb3216ce2d7df822b6537003a | def write(self, entry):
'\n events are done in emit() not in write()\n '
pass | events are done in emit() not in write() | src/cowrie/output/crashreporter.py | write | maarlo/cowrie | 2,316 | python | def write(self, entry):
'\n \n '
pass | def write(self, entry):
'\n \n '
pass<|docstring|>events are done in emit() not in write()<|endoftext|> |
75bf940593959f85af9ba1fd29c51c54d39b63252a9b098c152452a1c45b544e | @defer.inlineCallbacks
def crashreport(self, entry):
'\n Crash report\n '
try:
r = (yield treq.post(COWRIE_URL, json.dumps({'log_text': entry.get('log_text'), 'system': entry.get('system')}).encode('ascii'), headers={b'Content-Type': [b'application/json'], b'User-Agent': [COWRIE_USER_AGENT]}))
content = (yield r.text())
if self.debug:
print(('crashreport: ' + content))
except Exception as e:
print(('crashreporter failed' + repr(e))) | Crash report | src/cowrie/output/crashreporter.py | crashreport | maarlo/cowrie | 2,316 | python | @defer.inlineCallbacks
def crashreport(self, entry):
'\n \n '
try:
r = (yield treq.post(COWRIE_URL, json.dumps({'log_text': entry.get('log_text'), 'system': entry.get('system')}).encode('ascii'), headers={b'Content-Type': [b'application/json'], b'User-Agent': [COWRIE_USER_AGENT]}))
content = (yield r.text())
if self.debug:
print(('crashreport: ' + content))
except Exception as e:
print(('crashreporter failed' + repr(e))) | @defer.inlineCallbacks
def crashreport(self, entry):
'\n \n '
try:
r = (yield treq.post(COWRIE_URL, json.dumps({'log_text': entry.get('log_text'), 'system': entry.get('system')}).encode('ascii'), headers={b'Content-Type': [b'application/json'], b'User-Agent': [COWRIE_USER_AGENT]}))
content = (yield r.text())
if self.debug:
print(('crashreport: ' + content))
except Exception as e:
print(('crashreporter failed' + repr(e)))<|docstring|>Crash report<|endoftext|> |
749e7a2042694c7b54ab633dac696573354447b4101fe96831664d20be35d766 | def test_horseshoe_nbinom(srng):
'\n This test example is modified from section 3.2 of Makalic & Schmidt (2016)\n '
h = 2
p = 10
N = 50
true_beta = np.array(([5, 3, 3, 1, 1] + ([0] * (p - 5))))
S = toeplitz((0.5 ** np.arange(p)))
X = srng.multivariate_normal(np.zeros(p), cov=S, size=N)
y = srng.nbinom(h, at.sigmoid((- X.dot(true_beta))))
tau_rv = srng.halfcauchy(0, 1, size=1)
lambda_rv = srng.halfcauchy(0, 1, size=p)
beta_rv = srng.normal(0, (tau_rv * lambda_rv), size=p)
eta_tt = (X @ beta_rv)
p_tt = at.sigmoid((- eta_tt))
Y_rv = srng.nbinom(h, p_tt)
num_samples = at.scalar('num_samples', dtype='int32')
(outputs, updates) = nbinom_horseshoe_gibbs(srng, Y_rv, y, num_samples)
sample_fn = aesara.function((num_samples,), outputs, updates=updates)
(beta, lmbda, tau) = sample_fn(2000)
assert (beta.shape == (2000, p))
assert (lmbda.shape == (2000, p))
assert (tau.shape == (2000, 1))
assert np.all((tau > 0))
assert np.all((lmbda > 0)) | This test example is modified from section 3.2 of Makalic & Schmidt (2016) | tests/test_gibbs.py | test_horseshoe_nbinom | aesara-devs/aemcmc | 13 | python | def test_horseshoe_nbinom(srng):
'\n \n '
h = 2
p = 10
N = 50
true_beta = np.array(([5, 3, 3, 1, 1] + ([0] * (p - 5))))
S = toeplitz((0.5 ** np.arange(p)))
X = srng.multivariate_normal(np.zeros(p), cov=S, size=N)
y = srng.nbinom(h, at.sigmoid((- X.dot(true_beta))))
tau_rv = srng.halfcauchy(0, 1, size=1)
lambda_rv = srng.halfcauchy(0, 1, size=p)
beta_rv = srng.normal(0, (tau_rv * lambda_rv), size=p)
eta_tt = (X @ beta_rv)
p_tt = at.sigmoid((- eta_tt))
Y_rv = srng.nbinom(h, p_tt)
num_samples = at.scalar('num_samples', dtype='int32')
(outputs, updates) = nbinom_horseshoe_gibbs(srng, Y_rv, y, num_samples)
sample_fn = aesara.function((num_samples,), outputs, updates=updates)
(beta, lmbda, tau) = sample_fn(2000)
assert (beta.shape == (2000, p))
assert (lmbda.shape == (2000, p))
assert (tau.shape == (2000, 1))
assert np.all((tau > 0))
assert np.all((lmbda > 0)) | def test_horseshoe_nbinom(srng):
'\n \n '
h = 2
p = 10
N = 50
true_beta = np.array(([5, 3, 3, 1, 1] + ([0] * (p - 5))))
S = toeplitz((0.5 ** np.arange(p)))
X = srng.multivariate_normal(np.zeros(p), cov=S, size=N)
y = srng.nbinom(h, at.sigmoid((- X.dot(true_beta))))
tau_rv = srng.halfcauchy(0, 1, size=1)
lambda_rv = srng.halfcauchy(0, 1, size=p)
beta_rv = srng.normal(0, (tau_rv * lambda_rv), size=p)
eta_tt = (X @ beta_rv)
p_tt = at.sigmoid((- eta_tt))
Y_rv = srng.nbinom(h, p_tt)
num_samples = at.scalar('num_samples', dtype='int32')
(outputs, updates) = nbinom_horseshoe_gibbs(srng, Y_rv, y, num_samples)
sample_fn = aesara.function((num_samples,), outputs, updates=updates)
(beta, lmbda, tau) = sample_fn(2000)
assert (beta.shape == (2000, p))
assert (lmbda.shape == (2000, p))
assert (tau.shape == (2000, 1))
assert np.all((tau > 0))
assert np.all((lmbda > 0))<|docstring|>This test example is modified from section 3.2 of Makalic & Schmidt (2016)<|endoftext|> |
48a9fa79e8891b21fa2b532d97823aeda6dcdfce57b3a34919e861ebdfad1c02 | def test_horseshoe_nbinom_w_dispersion(srng):
'\n This test example is modified from section 3.2 of Makalic & Schmidt (2016)\n '
true_h = 10
M = 10
N = 50
true_beta = np.array(([2, 0.02, 0.2, 0.1, 1] + ([0.1] * (M - 5))))
S = toeplitz((0.5 ** np.arange(M)))
X_at = srng.multivariate_normal(np.zeros(M), cov=S, size=N)
(X, y) = aesara.function([], [X_at, srng.nbinom(true_h, at.sigmoid((- X_at.dot(true_beta))))])()
X = at.as_tensor(X)
y = at.as_tensor(y)
tau_rv = srng.halfcauchy(0, 1, name='tau')
lambda_rv = srng.halfcauchy(0, 1, size=M, name='lambda')
beta_rv = srng.normal(0, (tau_rv * lambda_rv), size=M, name='beta')
eta_tt = (X @ beta_rv)
p_tt = at.sigmoid((- eta_tt))
p_tt.name = 'p'
h_rv = srng.gamma(100, 1, name='h')
Y_rv = srng.nbinom(h_rv, p_tt, name='Y')
num_samples = at.lscalar('num_samples')
(outputs, updates) = nbinom_horseshoe_gibbs_with_dispersion(srng, Y_rv, y, num_samples)
sample_fn = aesara.function((num_samples,), outputs, updates=updates)
sample_num = 2000
(beta, lmbda, tau, h) = sample_fn(sample_num)
assert (beta.shape == (sample_num, M))
assert (lmbda.shape == (sample_num, M))
assert (tau.shape == (sample_num, 1))
assert (h.shape == (sample_num,))
assert np.all((tau > 0))
assert np.all((lmbda > 0))
assert np.all((h > 0))
assert np.allclose(h.mean(), true_h, rtol=0.1) | This test example is modified from section 3.2 of Makalic & Schmidt (2016) | tests/test_gibbs.py | test_horseshoe_nbinom_w_dispersion | aesara-devs/aemcmc | 13 | python | def test_horseshoe_nbinom_w_dispersion(srng):
'\n \n '
true_h = 10
M = 10
N = 50
true_beta = np.array(([2, 0.02, 0.2, 0.1, 1] + ([0.1] * (M - 5))))
S = toeplitz((0.5 ** np.arange(M)))
X_at = srng.multivariate_normal(np.zeros(M), cov=S, size=N)
(X, y) = aesara.function([], [X_at, srng.nbinom(true_h, at.sigmoid((- X_at.dot(true_beta))))])()
X = at.as_tensor(X)
y = at.as_tensor(y)
tau_rv = srng.halfcauchy(0, 1, name='tau')
lambda_rv = srng.halfcauchy(0, 1, size=M, name='lambda')
beta_rv = srng.normal(0, (tau_rv * lambda_rv), size=M, name='beta')
eta_tt = (X @ beta_rv)
p_tt = at.sigmoid((- eta_tt))
p_tt.name = 'p'
h_rv = srng.gamma(100, 1, name='h')
Y_rv = srng.nbinom(h_rv, p_tt, name='Y')
num_samples = at.lscalar('num_samples')
(outputs, updates) = nbinom_horseshoe_gibbs_with_dispersion(srng, Y_rv, y, num_samples)
sample_fn = aesara.function((num_samples,), outputs, updates=updates)
sample_num = 2000
(beta, lmbda, tau, h) = sample_fn(sample_num)
assert (beta.shape == (sample_num, M))
assert (lmbda.shape == (sample_num, M))
assert (tau.shape == (sample_num, 1))
assert (h.shape == (sample_num,))
assert np.all((tau > 0))
assert np.all((lmbda > 0))
assert np.all((h > 0))
assert np.allclose(h.mean(), true_h, rtol=0.1) | def test_horseshoe_nbinom_w_dispersion(srng):
'\n \n '
true_h = 10
M = 10
N = 50
true_beta = np.array(([2, 0.02, 0.2, 0.1, 1] + ([0.1] * (M - 5))))
S = toeplitz((0.5 ** np.arange(M)))
X_at = srng.multivariate_normal(np.zeros(M), cov=S, size=N)
(X, y) = aesara.function([], [X_at, srng.nbinom(true_h, at.sigmoid((- X_at.dot(true_beta))))])()
X = at.as_tensor(X)
y = at.as_tensor(y)
tau_rv = srng.halfcauchy(0, 1, name='tau')
lambda_rv = srng.halfcauchy(0, 1, size=M, name='lambda')
beta_rv = srng.normal(0, (tau_rv * lambda_rv), size=M, name='beta')
eta_tt = (X @ beta_rv)
p_tt = at.sigmoid((- eta_tt))
p_tt.name = 'p'
h_rv = srng.gamma(100, 1, name='h')
Y_rv = srng.nbinom(h_rv, p_tt, name='Y')
num_samples = at.lscalar('num_samples')
(outputs, updates) = nbinom_horseshoe_gibbs_with_dispersion(srng, Y_rv, y, num_samples)
sample_fn = aesara.function((num_samples,), outputs, updates=updates)
sample_num = 2000
(beta, lmbda, tau, h) = sample_fn(sample_num)
assert (beta.shape == (sample_num, M))
assert (lmbda.shape == (sample_num, M))
assert (tau.shape == (sample_num, 1))
assert (h.shape == (sample_num,))
assert np.all((tau > 0))
assert np.all((lmbda > 0))
assert np.all((h > 0))
assert np.allclose(h.mean(), true_h, rtol=0.1)<|docstring|>This test example is modified from section 3.2 of Makalic & Schmidt (2016)<|endoftext|> |
46f4f32abd25ef757152b1c83d20c303d32f8edddc45136ca3f27e3af4b389fc | def change_lock_status(title, new_lock_status, default=False, forced=False):
'\n This is called when a user starts or stops editing a\n page\n '
title = title.replace(' ', '_')
if default:
return
if forced:
update_lock_query(title, new_lock_status)
return
uid = auth_utils.get_user_id(flask.session['username'])
query = 'SELECT last_edit_uid FROM webpage_files WHERE title = %s'
with flask.g.pymysql_db.cursor() as cursor:
cursor.execute(query, title)
res = cursor.fetchone()
if ((not is_locked(title)) or (res['last_edit_uid'] == uid)):
update_lock_query(title, new_lock_status) | This is called when a user starts or stops editing a
page | donut/modules/editor/helpers.py | change_lock_status | dqu123/donut | 0 | python | def change_lock_status(title, new_lock_status, default=False, forced=False):
'\n This is called when a user starts or stops editing a\n page\n '
title = title.replace(' ', '_')
if default:
return
if forced:
update_lock_query(title, new_lock_status)
return
uid = auth_utils.get_user_id(flask.session['username'])
query = 'SELECT last_edit_uid FROM webpage_files WHERE title = %s'
with flask.g.pymysql_db.cursor() as cursor:
cursor.execute(query, title)
res = cursor.fetchone()
if ((not is_locked(title)) or (res['last_edit_uid'] == uid)):
update_lock_query(title, new_lock_status) | def change_lock_status(title, new_lock_status, default=False, forced=False):
'\n This is called when a user starts or stops editing a\n page\n '
title = title.replace(' ', '_')
if default:
return
if forced:
update_lock_query(title, new_lock_status)
return
uid = auth_utils.get_user_id(flask.session['username'])
query = 'SELECT last_edit_uid FROM webpage_files WHERE title = %s'
with flask.g.pymysql_db.cursor() as cursor:
cursor.execute(query, title)
res = cursor.fetchone()
if ((not is_locked(title)) or (res['last_edit_uid'] == uid)):
update_lock_query(title, new_lock_status)<|docstring|>This is called when a user starts or stops editing a
page<|endoftext|> |
3701b0bedf813311959131db586a32b90ba84347602b4729afaa8d4aa77b4561 | def update_lock_query(title, new_lock_status):
'\n Query for updating lock status\n '
title = title.replace(' ', '_')
query = '\n UPDATE webpage_files \n SET locked = %s, last_edit_time = NOW(), last_edit_uid = %s \n WHERE title = %s\n '
with flask.g.pymysql_db.cursor() as cursor:
cursor.execute(query, (new_lock_status, auth_utils.get_user_id(flask.session['username']), title)) | Query for updating lock status | donut/modules/editor/helpers.py | update_lock_query | dqu123/donut | 0 | python | def update_lock_query(title, new_lock_status):
'\n \n '
title = title.replace(' ', '_')
query = '\n UPDATE webpage_files \n SET locked = %s, last_edit_time = NOW(), last_edit_uid = %s \n WHERE title = %s\n '
with flask.g.pymysql_db.cursor() as cursor:
cursor.execute(query, (new_lock_status, auth_utils.get_user_id(flask.session['username']), title)) | def update_lock_query(title, new_lock_status):
'\n \n '
title = title.replace(' ', '_')
query = '\n UPDATE webpage_files \n SET locked = %s, last_edit_time = NOW(), last_edit_uid = %s \n WHERE title = %s\n '
with flask.g.pymysql_db.cursor() as cursor:
cursor.execute(query, (new_lock_status, auth_utils.get_user_id(flask.session['username']), title))<|docstring|>Query for updating lock status<|endoftext|> |
4b85227bdcf3df4867876ab2089c06fd7d6369327a1fd36fd49e7e0dbec50513 | def is_locked(title, default=False):
'\n Gets the edit lock status of the current request page. \n If we are landing in the default page, automatically return True\n '
if default:
return False
title = title.replace(' ', '_')
query = '\n SELECT locked, TIMESTAMPDIFF(SECOND, last_edit_time, NOW()) as expired \n FROM webpage_files WHERE title = %s\n '
with flask.g.pymysql_db.cursor() as cursor:
cursor.execute(query, title)
res = cursor.fetchone()
if (res == None):
return False
if (res['expired'] >= TIMEOUT):
change_lock_status(title, False, forced=True)
return False
return res['locked'] | Gets the edit lock status of the current request page.
If we are landing in the default page, automatically return True | donut/modules/editor/helpers.py | is_locked | dqu123/donut | 0 | python | def is_locked(title, default=False):
'\n Gets the edit lock status of the current request page. \n If we are landing in the default page, automatically return True\n '
if default:
return False
title = title.replace(' ', '_')
query = '\n SELECT locked, TIMESTAMPDIFF(SECOND, last_edit_time, NOW()) as expired \n FROM webpage_files WHERE title = %s\n '
with flask.g.pymysql_db.cursor() as cursor:
cursor.execute(query, title)
res = cursor.fetchone()
if (res == None):
return False
if (res['expired'] >= TIMEOUT):
change_lock_status(title, False, forced=True)
return False
return res['locked'] | def is_locked(title, default=False):
'\n Gets the edit lock status of the current request page. \n If we are landing in the default page, automatically return True\n '
if default:
return False
title = title.replace(' ', '_')
query = '\n SELECT locked, TIMESTAMPDIFF(SECOND, last_edit_time, NOW()) as expired \n FROM webpage_files WHERE title = %s\n '
with flask.g.pymysql_db.cursor() as cursor:
cursor.execute(query, title)
res = cursor.fetchone()
if (res == None):
return False
if (res['expired'] >= TIMEOUT):
change_lock_status(title, False, forced=True)
return False
return res['locked']<|docstring|>Gets the edit lock status of the current request page.
If we are landing in the default page, automatically return True<|endoftext|> |
b3518e00b64bca3ec006eef3d1328b4442f0031f8857a6467c4923e880fb2c64 | def create_page_in_database(title, content):
'\n There are some pages that exist but do not have entries in the \n database. \n '
title = title.replace(' ', '_')
query = '\n INSERT INTO webpage_files (title, content) VALUES (%s, %s) ON DUPLICATE KEY UPDATE locked = locked, content = %s\n '
with flask.g.pymysql_db.cursor() as cursor:
cursor.execute(query, [title, content, content]) | There are some pages that exist but do not have entries in the
database. | donut/modules/editor/helpers.py | create_page_in_database | dqu123/donut | 0 | python | def create_page_in_database(title, content):
'\n There are some pages that exist but do not have entries in the \n database. \n '
title = title.replace(' ', '_')
query = '\n INSERT INTO webpage_files (title, content) VALUES (%s, %s) ON DUPLICATE KEY UPDATE locked = locked, content = %s\n '
with flask.g.pymysql_db.cursor() as cursor:
cursor.execute(query, [title, content, content]) | def create_page_in_database(title, content):
'\n There are some pages that exist but do not have entries in the \n database. \n '
title = title.replace(' ', '_')
query = '\n INSERT INTO webpage_files (title, content) VALUES (%s, %s) ON DUPLICATE KEY UPDATE locked = locked, content = %s\n '
with flask.g.pymysql_db.cursor() as cursor:
cursor.execute(query, [title, content, content])<|docstring|>There are some pages that exist but do not have entries in the
database.<|endoftext|> |
8da4b1aea2dafb52bc20d8e8765c8a3758f78a93652bebdc1d0b635673cbb197 | def rename_title(old_filename, new_filename):
'\n Changes the file name of an html file\n '
old_filename = old_filename.replace(' ', '_')
new_filename = new_filename.replace(' ', '_')
query = '\n UPDATE webpage_files SET title = %s WHERE title = %s\n '
with flask.g.pymysql_db.cursor() as cursor:
cursor.execute(query, [new_filename, old_filename]) | Changes the file name of an html file | donut/modules/editor/helpers.py | rename_title | dqu123/donut | 0 | python | def rename_title(old_filename, new_filename):
'\n \n '
old_filename = old_filename.replace(' ', '_')
new_filename = new_filename.replace(' ', '_')
query = '\n UPDATE webpage_files SET title = %s WHERE title = %s\n '
with flask.g.pymysql_db.cursor() as cursor:
cursor.execute(query, [new_filename, old_filename]) | def rename_title(old_filename, new_filename):
'\n \n '
old_filename = old_filename.replace(' ', '_')
new_filename = new_filename.replace(' ', '_')
query = '\n UPDATE webpage_files SET title = %s WHERE title = %s\n '
with flask.g.pymysql_db.cursor() as cursor:
cursor.execute(query, [new_filename, old_filename])<|docstring|>Changes the file name of an html file<|endoftext|> |
cc74ae32f33a182bd11cbb871ec06e4058ab2fd57906336378df40e0bf3dbec6 | def read_file(path):
'\n Reads in a file\n '
if (not os.path.isfile(path)):
return ''
with open(path) as f:
return f.read() | Reads in a file | donut/modules/editor/helpers.py | read_file | dqu123/donut | 0 | python | def read_file(path):
'\n \n '
if (not os.path.isfile(path)):
return
with open(path) as f:
return f.read() | def read_file(path):
'\n \n '
if (not os.path.isfile(path)):
return
with open(path) as f:
return f.read()<|docstring|>Reads in a file<|endoftext|> |
9b7f513927862fd51a9fac7b6ba76c5491c4082c4b81fbba600de745675f3579 | def clean_file_names(path, links):
'\n Stripes a few things from the glob links\n '
return [link.replace((path + '/'), '').replace('.md', '').replace('_', ' ') for link in links] | Stripes a few things from the glob links | donut/modules/editor/helpers.py | clean_file_names | dqu123/donut | 0 | python | def clean_file_names(path, links):
'\n \n '
return [link.replace((path + '/'), ).replace('.md', ).replace('_', ' ') for link in links] | def clean_file_names(path, links):
'\n \n '
return [link.replace((path + '/'), ).replace('.md', ).replace('_', ' ') for link in links]<|docstring|>Stripes a few things from the glob links<|endoftext|> |
8edde19c5e5548713cd50e867acd7872ced51a9f107a621aefeaffdff28f249d | def remove_file_from_db(filename):
'\n Removes the information for a file from the db\n '
filename = filename.replace(' ', '_')
query = 'DELETE FROM webpage_files WHERE title = %s'
with flask.g.pymysql_db.cursor() as cursor:
cursor.execute(query, filename) | Removes the information for a file from the db | donut/modules/editor/helpers.py | remove_file_from_db | dqu123/donut | 0 | python | def remove_file_from_db(filename):
'\n \n '
filename = filename.replace(' ', '_')
query = 'DELETE FROM webpage_files WHERE title = %s'
with flask.g.pymysql_db.cursor() as cursor:
cursor.execute(query, filename) | def remove_file_from_db(filename):
'\n \n '
filename = filename.replace(' ', '_')
query = 'DELETE FROM webpage_files WHERE title = %s'
with flask.g.pymysql_db.cursor() as cursor:
cursor.execute(query, filename)<|docstring|>Removes the information for a file from the db<|endoftext|> |
09510538d286b50058265ebda931d77adf03b68513d5576cfb0b2a6d17d4dd9a | def check_duplicate(filename):
'\n Check to see if there are duplicate file names\n '
filename = filename.replace(' ', '_')
query = 'SELECT title FROM webpage_files WHERE title = %s'
with flask.g.pymysql_db.cursor() as cursor:
cursor.execute(query, [filename])
res = cursor.fetchone()
return (False if (res is None) else True) | Check to see if there are duplicate file names | donut/modules/editor/helpers.py | check_duplicate | dqu123/donut | 0 | python | def check_duplicate(filename):
'\n \n '
filename = filename.replace(' ', '_')
query = 'SELECT title FROM webpage_files WHERE title = %s'
with flask.g.pymysql_db.cursor() as cursor:
cursor.execute(query, [filename])
res = cursor.fetchone()
return (False if (res is None) else True) | def check_duplicate(filename):
'\n \n '
filename = filename.replace(' ', '_')
query = 'SELECT title FROM webpage_files WHERE title = %s'
with flask.g.pymysql_db.cursor() as cursor:
cursor.execute(query, [filename])
res = cursor.fetchone()
return (False if (res is None) else True)<|docstring|>Check to see if there are duplicate file names<|endoftext|> |
17a5f45fc85a84abf63783b422f95fdf6187b8e51dd51d83307b740eba1deb31 | def check_title(title):
'\n Makes sure the title is valid,\n Allows all numbers and characters. Allows ".", "_", "-"\n '
return ((len(title) < 100) and (re.match('^[0-9a-zA-Z./\\-_: ]*$', title) != None)) | Makes sure the title is valid,
Allows all numbers and characters. Allows ".", "_", "-" | donut/modules/editor/helpers.py | check_title | dqu123/donut | 0 | python | def check_title(title):
'\n Makes sure the title is valid,\n Allows all numbers and characters. Allows ".", "_", "-"\n '
return ((len(title) < 100) and (re.match('^[0-9a-zA-Z./\\-_: ]*$', title) != None)) | def check_title(title):
'\n Makes sure the title is valid,\n Allows all numbers and characters. Allows ".", "_", "-"\n '
return ((len(title) < 100) and (re.match('^[0-9a-zA-Z./\\-_: ]*$', title) != None))<|docstring|>Makes sure the title is valid,
Allows all numbers and characters. Allows ".", "_", "-"<|endoftext|> |
dacac371d852423e3b023eace1c1b3279872ff7958d3c674fc8bdd507b552408 | def check_edit_page_permission():
'\n Checks if the user has permission to edit a page\n '
return (auth_utils.check_login() and auth_utils.check_permission(flask.session['username'], EditPermission.ABLE)) | Checks if the user has permission to edit a page | donut/modules/editor/helpers.py | check_edit_page_permission | dqu123/donut | 0 | python | def check_edit_page_permission():
'\n \n '
return (auth_utils.check_login() and auth_utils.check_permission(flask.session['username'], EditPermission.ABLE)) | def check_edit_page_permission():
'\n \n '
return (auth_utils.check_login() and auth_utils.check_permission(flask.session['username'], EditPermission.ABLE))<|docstring|>Checks if the user has permission to edit a page<|endoftext|> |
491b0834258b4cddd76ddbbcdfee78a8dd38332f3b0b2ed6d1e951139b9e1f1d | def call(func, args):
'\n func can be any callable\n args don\'t have to be wrapped\n macro has been applied\n\n used by many context parts\n not used by term_call because of macro arguments\n\n NOTE:\n we use (args, kwargs) because *args, **kwargs aren\'t universal\n an (obj, *args, **kwargs) signature can\'t pass an "obj" keyword\n '
(func, (args, kwargs)) = context.callable(func, args)
scope = context.unpack_args(func, (args, kwargs))
return context.call_func(func, scope) | func can be any callable
args don't have to be wrapped
macro has been applied
used by many context parts
not used by term_call because of macro arguments
NOTE:
we use (args, kwargs) because *args, **kwargs aren't universal
an (obj, *args, **kwargs) signature can't pass an "obj" keyword | twocode/context/core.py | call | MrCoft/twocode | 0 | python | def call(func, args):
'\n func can be any callable\n args don\'t have to be wrapped\n macro has been applied\n\n used by many context parts\n not used by term_call because of macro arguments\n\n NOTE:\n we use (args, kwargs) because *args, **kwargs aren\'t universal\n an (obj, *args, **kwargs) signature can\'t pass an "obj" keyword\n '
(func, (args, kwargs)) = context.callable(func, args)
scope = context.unpack_args(func, (args, kwargs))
return context.call_func(func, scope) | def call(func, args):
'\n func can be any callable\n args don\'t have to be wrapped\n macro has been applied\n\n used by many context parts\n not used by term_call because of macro arguments\n\n NOTE:\n we use (args, kwargs) because *args, **kwargs aren\'t universal\n an (obj, *args, **kwargs) signature can\'t pass an "obj" keyword\n '
(func, (args, kwargs)) = context.callable(func, args)
scope = context.unpack_args(func, (args, kwargs))
return context.call_func(func, scope)<|docstring|>func can be any callable
args don't have to be wrapped
macro has been applied
used by many context parts
not used by term_call because of macro arguments
NOTE:
we use (args, kwargs) because *args, **kwargs aren't universal
an (obj, *args, **kwargs) signature can't pass an "obj" keyword<|endoftext|> |
1070e67687d4d10307aa80c7536e8fc3fa8a5efc13b6f62a22981da35d9bfc6f | def call_method(obj, method, *args):
'\n an utility function\n it lacks **kwargs for safety\n '
return context.call(context.impl(obj.__type__, method), ([obj, *args], {})) | an utility function
it lacks **kwargs for safety | twocode/context/core.py | call_method | MrCoft/twocode | 0 | python | def call_method(obj, method, *args):
'\n an utility function\n it lacks **kwargs for safety\n '
return context.call(context.impl(obj.__type__, method), ([obj, *args], {})) | def call_method(obj, method, *args):
'\n an utility function\n it lacks **kwargs for safety\n '
return context.call(context.impl(obj.__type__, method), ([obj, *args], {}))<|docstring|>an utility function
it lacks **kwargs for safety<|endoftext|> |
e6b459c3b70090c8d8b14a9ae4eb2326769066a7df47535ce4a44c22f12293c0 | def call_func(func, scope):
'\n expects a scope\n args, kwargs packed\n wraps args and sets defaults as neither call nor term_call need to do it\n '
scope = {name: context.wrap(arg) for (name, arg) in scope.items()}
for arg in func.args:
if arg.default_:
if (arg.name not in scope):
scope[arg.name] = context.eval(arg.default_, type='expr')
try:
return_value = None
if func.native:
(args, kwargs) = context.pack_args(func, scope)
return_value = func.native(*args, **kwargs)
else:
frame = (func.frame.copy() if (func.frame is not None) else [context.scope.get_env()])
bound = (('this' in scope) and context.bound(func, scope['this'].__type__))
if bound:
frame.append(context.obj.Object(context.scope_types.ObjectScope, object=scope['this']))
scope = {key: context.obj.Var(value) for (key, value) in scope.items()}
frame.append(context.obj.Object(context.scope_types.Scope, __this__=scope))
frame.append(context.obj.Object(context.scope_types.Scope, __this__={}))
with context.FrameContext(frame):
context.eval(func.code, type='pass')
except context.exc.Return as exc:
return_value = exc.value
if (return_value is None):
return_value = context.wrap(None)
return return_value | expects a scope
args, kwargs packed
wraps args and sets defaults as neither call nor term_call need to do it | twocode/context/core.py | call_func | MrCoft/twocode | 0 | python | def call_func(func, scope):
'\n expects a scope\n args, kwargs packed\n wraps args and sets defaults as neither call nor term_call need to do it\n '
scope = {name: context.wrap(arg) for (name, arg) in scope.items()}
for arg in func.args:
if arg.default_:
if (arg.name not in scope):
scope[arg.name] = context.eval(arg.default_, type='expr')
try:
return_value = None
if func.native:
(args, kwargs) = context.pack_args(func, scope)
return_value = func.native(*args, **kwargs)
else:
frame = (func.frame.copy() if (func.frame is not None) else [context.scope.get_env()])
bound = (('this' in scope) and context.bound(func, scope['this'].__type__))
if bound:
frame.append(context.obj.Object(context.scope_types.ObjectScope, object=scope['this']))
scope = {key: context.obj.Var(value) for (key, value) in scope.items()}
frame.append(context.obj.Object(context.scope_types.Scope, __this__=scope))
frame.append(context.obj.Object(context.scope_types.Scope, __this__={}))
with context.FrameContext(frame):
context.eval(func.code, type='pass')
except context.exc.Return as exc:
return_value = exc.value
if (return_value is None):
return_value = context.wrap(None)
return return_value | def call_func(func, scope):
'\n expects a scope\n args, kwargs packed\n wraps args and sets defaults as neither call nor term_call need to do it\n '
scope = {name: context.wrap(arg) for (name, arg) in scope.items()}
for arg in func.args:
if arg.default_:
if (arg.name not in scope):
scope[arg.name] = context.eval(arg.default_, type='expr')
try:
return_value = None
if func.native:
(args, kwargs) = context.pack_args(func, scope)
return_value = func.native(*args, **kwargs)
else:
frame = (func.frame.copy() if (func.frame is not None) else [context.scope.get_env()])
bound = (('this' in scope) and context.bound(func, scope['this'].__type__))
if bound:
frame.append(context.obj.Object(context.scope_types.ObjectScope, object=scope['this']))
scope = {key: context.obj.Var(value) for (key, value) in scope.items()}
frame.append(context.obj.Object(context.scope_types.Scope, __this__=scope))
frame.append(context.obj.Object(context.scope_types.Scope, __this__={}))
with context.FrameContext(frame):
context.eval(func.code, type='pass')
except context.exc.Return as exc:
return_value = exc.value
if (return_value is None):
return_value = context.wrap(None)
return return_value<|docstring|>expects a scope
args, kwargs packed
wraps args and sets defaults as neither call nor term_call need to do it<|endoftext|> |
c4a8784122db69ab65e26b04182b655b09f28029d0591a8c17835b21dec1e6b2 | def unpack_args(func, args):
"\n uses the func's args to parse (args, kwargs) into a scope\n\n is transparent to moved values\n because term_call needs named slots to macro\n\n used by call and term_call\n "
(args, kwargs) = args
missing_pos = []
scope = {}
for arg in func.args:
if (not arg.pack):
if args:
scope[arg.name] = args.pop(0)
elif (arg.name in kwargs):
scope[arg.name] = kwargs.pop(arg.name)
else:
missing_pos.append(arg.name)
elif (arg.pack == 'args'):
scope[arg.name] = args
args = []
elif (arg.pack == 'kwargs'):
scope[arg.name] = kwargs
kwargs = {}
if kwargs:
raise TypeError('func{} missing {} required positional argument{}: {}'.format(context.unwrap(context.call_method(func, 'signature')), len(missing_pos), ('s' if (len(missing_pos) >= 2) else ''), name_enum))
if (False and missing_pos):
missing_pos = [utils.string.escape(name) for name in missing_pos]
if (len(missing_pos) == 1):
name_enum = missing_pos[0]
elif (len(missing_pos) == 2):
name_enum = '{} and {}'.format(missing_pos)
else:
name_enum = ((', '.join(missing_pos[:(- 1)]) + ', and ') + missing_pos[(- 1)])
raise TypeError('func{} missing {} required positional argument{}: {}'.format(context.unwrap(context.call_method(func, 'signature')), len(missing_pos), ('s' if (len(missing_pos) >= 2) else ''), name_enum))
if (args or kwargs):
raise SyntaxError('signature mismatch while unpacking arguments')
raise SyntaxError('unused arguments: {}'.format(' '.join(kwargs.keys())))
return scope | uses the func's args to parse (args, kwargs) into a scope
is transparent to moved values
because term_call needs named slots to macro
used by call and term_call | twocode/context/core.py | unpack_args | MrCoft/twocode | 0 | python | def unpack_args(func, args):
"\n uses the func's args to parse (args, kwargs) into a scope\n\n is transparent to moved values\n because term_call needs named slots to macro\n\n used by call and term_call\n "
(args, kwargs) = args
missing_pos = []
scope = {}
for arg in func.args:
if (not arg.pack):
if args:
scope[arg.name] = args.pop(0)
elif (arg.name in kwargs):
scope[arg.name] = kwargs.pop(arg.name)
else:
missing_pos.append(arg.name)
elif (arg.pack == 'args'):
scope[arg.name] = args
args = []
elif (arg.pack == 'kwargs'):
scope[arg.name] = kwargs
kwargs = {}
if kwargs:
raise TypeError('func{} missing {} required positional argument{}: {}'.format(context.unwrap(context.call_method(func, 'signature')), len(missing_pos), ('s' if (len(missing_pos) >= 2) else ), name_enum))
if (False and missing_pos):
missing_pos = [utils.string.escape(name) for name in missing_pos]
if (len(missing_pos) == 1):
name_enum = missing_pos[0]
elif (len(missing_pos) == 2):
name_enum = '{} and {}'.format(missing_pos)
else:
name_enum = ((', '.join(missing_pos[:(- 1)]) + ', and ') + missing_pos[(- 1)])
raise TypeError('func{} missing {} required positional argument{}: {}'.format(context.unwrap(context.call_method(func, 'signature')), len(missing_pos), ('s' if (len(missing_pos) >= 2) else ), name_enum))
if (args or kwargs):
raise SyntaxError('signature mismatch while unpacking arguments')
raise SyntaxError('unused arguments: {}'.format(' '.join(kwargs.keys())))
return scope | def unpack_args(func, args):
"\n uses the func's args to parse (args, kwargs) into a scope\n\n is transparent to moved values\n because term_call needs named slots to macro\n\n used by call and term_call\n "
(args, kwargs) = args
missing_pos = []
scope = {}
for arg in func.args:
if (not arg.pack):
if args:
scope[arg.name] = args.pop(0)
elif (arg.name in kwargs):
scope[arg.name] = kwargs.pop(arg.name)
else:
missing_pos.append(arg.name)
elif (arg.pack == 'args'):
scope[arg.name] = args
args = []
elif (arg.pack == 'kwargs'):
scope[arg.name] = kwargs
kwargs = {}
if kwargs:
raise TypeError('func{} missing {} required positional argument{}: {}'.format(context.unwrap(context.call_method(func, 'signature')), len(missing_pos), ('s' if (len(missing_pos) >= 2) else ), name_enum))
if (False and missing_pos):
missing_pos = [utils.string.escape(name) for name in missing_pos]
if (len(missing_pos) == 1):
name_enum = missing_pos[0]
elif (len(missing_pos) == 2):
name_enum = '{} and {}'.format(missing_pos)
else:
name_enum = ((', '.join(missing_pos[:(- 1)]) + ', and ') + missing_pos[(- 1)])
raise TypeError('func{} missing {} required positional argument{}: {}'.format(context.unwrap(context.call_method(func, 'signature')), len(missing_pos), ('s' if (len(missing_pos) >= 2) else ), name_enum))
if (args or kwargs):
raise SyntaxError('signature mismatch while unpacking arguments')
raise SyntaxError('unused arguments: {}'.format(' '.join(kwargs.keys())))
return scope<|docstring|>uses the func's args to parse (args, kwargs) into a scope
is transparent to moved values
because term_call needs named slots to macro
used by call and term_call<|endoftext|> |
1016c5a8bf91be1ff769f36c824171c2c859ee79b79fc8d5d369cd6c7f3132ba | def pack_args(func, scope):
'\n turns scope into (args, kwargs)\n\n used to call native functions\n '
(args, kwargs) = ([], {})
level = 0
for arg in func.args:
if (not arg.pack):
if (level == 0):
args.append(scope[arg.name])
else:
kwargs[arg.name] = scope[arg.name]
elif (arg.pack == 'args'):
args.extend(context.unwrap(scope[arg.name]))
level = 1
elif (arg.pack == 'kwargs'):
kwargs.update(context.unwrap(scope[arg.name]))
level = 2
del scope[arg.name]
if scope:
raise SyntaxError('signature mismatch while packing arguments')
return (args, kwargs) | turns scope into (args, kwargs)
used to call native functions | twocode/context/core.py | pack_args | MrCoft/twocode | 0 | python | def pack_args(func, scope):
'\n turns scope into (args, kwargs)\n\n used to call native functions\n '
(args, kwargs) = ([], {})
level = 0
for arg in func.args:
if (not arg.pack):
if (level == 0):
args.append(scope[arg.name])
else:
kwargs[arg.name] = scope[arg.name]
elif (arg.pack == 'args'):
args.extend(context.unwrap(scope[arg.name]))
level = 1
elif (arg.pack == 'kwargs'):
kwargs.update(context.unwrap(scope[arg.name]))
level = 2
del scope[arg.name]
if scope:
raise SyntaxError('signature mismatch while packing arguments')
return (args, kwargs) | def pack_args(func, scope):
'\n turns scope into (args, kwargs)\n\n used to call native functions\n '
(args, kwargs) = ([], {})
level = 0
for arg in func.args:
if (not arg.pack):
if (level == 0):
args.append(scope[arg.name])
else:
kwargs[arg.name] = scope[arg.name]
elif (arg.pack == 'args'):
args.extend(context.unwrap(scope[arg.name]))
level = 1
elif (arg.pack == 'kwargs'):
kwargs.update(context.unwrap(scope[arg.name]))
level = 2
del scope[arg.name]
if scope:
raise SyntaxError('signature mismatch while packing arguments')
return (args, kwargs)<|docstring|>turns scope into (args, kwargs)
used to call native functions<|endoftext|> |
d02618084fdeb955d873963b48668899ee7c8264518f29aeef4c7d171f8c1aa3 | def impl(type, name, signature=None):
'\n the way to check if a type implements a method\n\n when a native type wants to access its method without the option of it being overridden,\n use type.__fields__[name] or type.__base__.__fields__[name] instead\n\n GETATTR PROBLEM:\n the context used to ask for implementation through getattr\n classess offer their functions through __getattr__, but inherit their own methods as well\n a class which defined a repr stopped printing\n __getattr__ makes sense for scope access, we can still edit code for interfaces\n\n\n\n\n\n\n MATH PROBLEM:\n\n\n accessing add(a, b) is weird\n you cannot do impl because the first argument isn\'t "this"\n you cannot even delegate from that to the type because it isn\'t an inherited field for the same reason\n and getattr-ing it from the class risks accessing some property of the class instead\n\n still mention, though, that all the class history have their own fields\n\n\n # should __getattr__ be inherited?\n '
fields = context.inherit_fields(type)
if (not (name in fields)):
return None
func = fields[name]
try:
context.callable(func, ([], {}), inline_exc=True)
except InlineException:
return None
return func | the way to check if a type implements a method
when a native type wants to access its method without the option of it being overridden,
use type.__fields__[name] or type.__base__.__fields__[name] instead
GETATTR PROBLEM:
the context used to ask for implementation through getattr
classess offer their functions through __getattr__, but inherit their own methods as well
a class which defined a repr stopped printing
__getattr__ makes sense for scope access, we can still edit code for interfaces
MATH PROBLEM:
accessing add(a, b) is weird
you cannot do impl because the first argument isn't "this"
you cannot even delegate from that to the type because it isn't an inherited field for the same reason
and getattr-ing it from the class risks accessing some property of the class instead
still mention, though, that all the class history have their own fields
# should __getattr__ be inherited? | twocode/context/core.py | impl | MrCoft/twocode | 0 | python | def impl(type, name, signature=None):
'\n the way to check if a type implements a method\n\n when a native type wants to access its method without the option of it being overridden,\n use type.__fields__[name] or type.__base__.__fields__[name] instead\n\n GETATTR PROBLEM:\n the context used to ask for implementation through getattr\n classess offer their functions through __getattr__, but inherit their own methods as well\n a class which defined a repr stopped printing\n __getattr__ makes sense for scope access, we can still edit code for interfaces\n\n\n\n\n\n\n MATH PROBLEM:\n\n\n accessing add(a, b) is weird\n you cannot do impl because the first argument isn\'t "this"\n you cannot even delegate from that to the type because it isn\'t an inherited field for the same reason\n and getattr-ing it from the class risks accessing some property of the class instead\n\n still mention, though, that all the class history have their own fields\n\n\n # should __getattr__ be inherited?\n '
fields = context.inherit_fields(type)
if (not (name in fields)):
return None
func = fields[name]
try:
context.callable(func, ([], {}), inline_exc=True)
except InlineException:
return None
return func | def impl(type, name, signature=None):
'\n the way to check if a type implements a method\n\n when a native type wants to access its method without the option of it being overridden,\n use type.__fields__[name] or type.__base__.__fields__[name] instead\n\n GETATTR PROBLEM:\n the context used to ask for implementation through getattr\n classess offer their functions through __getattr__, but inherit their own methods as well\n a class which defined a repr stopped printing\n __getattr__ makes sense for scope access, we can still edit code for interfaces\n\n\n\n\n\n\n MATH PROBLEM:\n\n\n accessing add(a, b) is weird\n you cannot do impl because the first argument isn\'t "this"\n you cannot even delegate from that to the type because it isn\'t an inherited field for the same reason\n and getattr-ing it from the class risks accessing some property of the class instead\n\n still mention, though, that all the class history have their own fields\n\n\n # should __getattr__ be inherited?\n '
fields = context.inherit_fields(type)
if (not (name in fields)):
return None
func = fields[name]
try:
context.callable(func, ([], {}), inline_exc=True)
except InlineException:
return None
return func<|docstring|>the way to check if a type implements a method
when a native type wants to access its method without the option of it being overridden,
use type.__fields__[name] or type.__base__.__fields__[name] instead
GETATTR PROBLEM:
the context used to ask for implementation through getattr
classess offer their functions through __getattr__, but inherit their own methods as well
a class which defined a repr stopped printing
__getattr__ makes sense for scope access, we can still edit code for interfaces
MATH PROBLEM:
accessing add(a, b) is weird
you cannot do impl because the first argument isn't "this"
you cannot even delegate from that to the type because it isn't an inherited field for the same reason
and getattr-ing it from the class risks accessing some property of the class instead
still mention, though, that all the class history have their own fields
# should __getattr__ be inherited?<|endoftext|> |
fc246f575851c6b60b0e2a3028052608cfe14a93e8769f13fe02add531ec8389 | def test_create_user_with_email_successful(self):
'Test creating a new user with email is successful'
email = 'example@example.com'
password = 'test123'
user = get_user_model().objects.create_user(email=email, password=password)
self.assertEqual(user.email, email)
self.assertTrue(user.check_password(password)) | Test creating a new user with email is successful | core/tests/test_models.py | test_create_user_with_email_successful | maneeshbabu/recipe | 0 | python | def test_create_user_with_email_successful(self):
email = 'example@example.com'
password = 'test123'
user = get_user_model().objects.create_user(email=email, password=password)
self.assertEqual(user.email, email)
self.assertTrue(user.check_password(password)) | def test_create_user_with_email_successful(self):
email = 'example@example.com'
password = 'test123'
user = get_user_model().objects.create_user(email=email, password=password)
self.assertEqual(user.email, email)
self.assertTrue(user.check_password(password))<|docstring|>Test creating a new user with email is successful<|endoftext|> |
aa5d7fbba5ae685c4b3cb89e14b0d24d02702339bf49d1f4a05463d9e2864bb8 | def test_new_user_email_normalized(self):
'Test creating a new user with email is normalized'
email = 'example@example.com'
user = get_user_model().objects.create_user(email=email, password='test123')
self.assertEqual(user.email, email.lower()) | Test creating a new user with email is normalized | core/tests/test_models.py | test_new_user_email_normalized | maneeshbabu/recipe | 0 | python | def test_new_user_email_normalized(self):
email = 'example@example.com'
user = get_user_model().objects.create_user(email=email, password='test123')
self.assertEqual(user.email, email.lower()) | def test_new_user_email_normalized(self):
email = 'example@example.com'
user = get_user_model().objects.create_user(email=email, password='test123')
self.assertEqual(user.email, email.lower())<|docstring|>Test creating a new user with email is normalized<|endoftext|> |
0b186e5abb565543df89da96559cbbddef961d77dbc37d4440a83e947874ba24 | def test_new_user_invalid_email(self):
'Test creating a new user with invalid email raise exception'
with self.assertRaises(ValueError):
get_user_model().objects.create_user(email=None, password='test123') | Test creating a new user with invalid email raise exception | core/tests/test_models.py | test_new_user_invalid_email | maneeshbabu/recipe | 0 | python | def test_new_user_invalid_email(self):
with self.assertRaises(ValueError):
get_user_model().objects.create_user(email=None, password='test123') | def test_new_user_invalid_email(self):
with self.assertRaises(ValueError):
get_user_model().objects.create_user(email=None, password='test123')<|docstring|>Test creating a new user with invalid email raise exception<|endoftext|> |
94c70d931fb6aa2d6a5a40bd03204f2a7afa3991c789cabcca14528b7652f50c | def test_new_user_is_superuser(self):
'Test creating a new super user'
user = get_user_model().objects.create_superuser(email='example@example.com', password='test123')
self.assertTrue(user.is_superuser)
self.assertTrue(user.is_staff) | Test creating a new super user | core/tests/test_models.py | test_new_user_is_superuser | maneeshbabu/recipe | 0 | python | def test_new_user_is_superuser(self):
user = get_user_model().objects.create_superuser(email='example@example.com', password='test123')
self.assertTrue(user.is_superuser)
self.assertTrue(user.is_staff) | def test_new_user_is_superuser(self):
user = get_user_model().objects.create_superuser(email='example@example.com', password='test123')
self.assertTrue(user.is_superuser)
self.assertTrue(user.is_staff)<|docstring|>Test creating a new super user<|endoftext|> |
0a2f01db1ac07dbf888362c2339d68ad6ed0fc4852fe2f336aa2ae86bf087b76 | def fit(self, X, y=None):
'Fits ARIMA regressor to data.\n\n Args:\n X (pd.DataFrame): The input training data of shape [n_samples, n_features].\n y (pd.Series): The target training data of length [n_samples].\n\n Returns:\n self\n\n Raises:\n ValueError: If X was passed to `fit` but not passed in `predict`.\n '
(X, y) = self._manage_woodwork(X, y)
if (y is None):
raise ValueError('ARIMA Regressor requires y as input.')
X = self._remove_datetime(X, features=True)
if (X is not None):
X.ww.set_types({col: 'Double' for col in X.ww.select(['Boolean'], return_schema=True).columns})
y = self._remove_datetime(y)
(X, y) = self._match_indices(X, y)
if ((X is not None) and (not X.empty)):
self._component_obj.fit(y=y, X=X)
else:
self._component_obj.fit(y=y)
return self | Fits ARIMA regressor to data.
Args:
X (pd.DataFrame): The input training data of shape [n_samples, n_features].
y (pd.Series): The target training data of length [n_samples].
Returns:
self
Raises:
ValueError: If X was passed to `fit` but not passed in `predict`. | rayml/pipelines/components/estimators/regressors/arima_regressor.py | fit | gcode-ai/rayml | 0 | python | def fit(self, X, y=None):
'Fits ARIMA regressor to data.\n\n Args:\n X (pd.DataFrame): The input training data of shape [n_samples, n_features].\n y (pd.Series): The target training data of length [n_samples].\n\n Returns:\n self\n\n Raises:\n ValueError: If X was passed to `fit` but not passed in `predict`.\n '
(X, y) = self._manage_woodwork(X, y)
if (y is None):
raise ValueError('ARIMA Regressor requires y as input.')
X = self._remove_datetime(X, features=True)
if (X is not None):
X.ww.set_types({col: 'Double' for col in X.ww.select(['Boolean'], return_schema=True).columns})
y = self._remove_datetime(y)
(X, y) = self._match_indices(X, y)
if ((X is not None) and (not X.empty)):
self._component_obj.fit(y=y, X=X)
else:
self._component_obj.fit(y=y)
return self | def fit(self, X, y=None):
'Fits ARIMA regressor to data.\n\n Args:\n X (pd.DataFrame): The input training data of shape [n_samples, n_features].\n y (pd.Series): The target training data of length [n_samples].\n\n Returns:\n self\n\n Raises:\n ValueError: If X was passed to `fit` but not passed in `predict`.\n '
(X, y) = self._manage_woodwork(X, y)
if (y is None):
raise ValueError('ARIMA Regressor requires y as input.')
X = self._remove_datetime(X, features=True)
if (X is not None):
X.ww.set_types({col: 'Double' for col in X.ww.select(['Boolean'], return_schema=True).columns})
y = self._remove_datetime(y)
(X, y) = self._match_indices(X, y)
if ((X is not None) and (not X.empty)):
self._component_obj.fit(y=y, X=X)
else:
self._component_obj.fit(y=y)
return self<|docstring|>Fits ARIMA regressor to data.
Args:
X (pd.DataFrame): The input training data of shape [n_samples, n_features].
y (pd.Series): The target training data of length [n_samples].
Returns:
self
Raises:
ValueError: If X was passed to `fit` but not passed in `predict`.<|endoftext|> |
24e011fdc16d58976eca03370757fb0dd810cf365fd9e202a7daef8d4d92ae86 | def predict(self, X, y=None):
'Make predictions using fitted ARIMA regressor.\n\n Args:\n X (pd.DataFrame): Data of shape [n_samples, n_features].\n y (pd.Series): Target data.\n\n Returns:\n pd.Series: Predicted values.\n\n Raises:\n ValueError: If X was passed to `fit` but not passed in `predict`.\n '
(X, y) = self._manage_woodwork(X, y)
fh_ = self._set_forecast(X)
X = X.ww.select(exclude=['Datetime'])
X.ww.set_types({col: 'Double' for col in X.ww.select(['Boolean'], return_schema=True).columns})
if (not X.empty):
y_pred = self._component_obj.predict(fh=fh_, X=X)
else:
y_pred = self._component_obj.predict(fh=fh_)
y_pred.index = X.index
return infer_feature_types(y_pred) | Make predictions using fitted ARIMA regressor.
Args:
X (pd.DataFrame): Data of shape [n_samples, n_features].
y (pd.Series): Target data.
Returns:
pd.Series: Predicted values.
Raises:
ValueError: If X was passed to `fit` but not passed in `predict`. | rayml/pipelines/components/estimators/regressors/arima_regressor.py | predict | gcode-ai/rayml | 0 | python | def predict(self, X, y=None):
'Make predictions using fitted ARIMA regressor.\n\n Args:\n X (pd.DataFrame): Data of shape [n_samples, n_features].\n y (pd.Series): Target data.\n\n Returns:\n pd.Series: Predicted values.\n\n Raises:\n ValueError: If X was passed to `fit` but not passed in `predict`.\n '
(X, y) = self._manage_woodwork(X, y)
fh_ = self._set_forecast(X)
X = X.ww.select(exclude=['Datetime'])
X.ww.set_types({col: 'Double' for col in X.ww.select(['Boolean'], return_schema=True).columns})
if (not X.empty):
y_pred = self._component_obj.predict(fh=fh_, X=X)
else:
y_pred = self._component_obj.predict(fh=fh_)
y_pred.index = X.index
return infer_feature_types(y_pred) | def predict(self, X, y=None):
'Make predictions using fitted ARIMA regressor.\n\n Args:\n X (pd.DataFrame): Data of shape [n_samples, n_features].\n y (pd.Series): Target data.\n\n Returns:\n pd.Series: Predicted values.\n\n Raises:\n ValueError: If X was passed to `fit` but not passed in `predict`.\n '
(X, y) = self._manage_woodwork(X, y)
fh_ = self._set_forecast(X)
X = X.ww.select(exclude=['Datetime'])
X.ww.set_types({col: 'Double' for col in X.ww.select(['Boolean'], return_schema=True).columns})
if (not X.empty):
y_pred = self._component_obj.predict(fh=fh_, X=X)
else:
y_pred = self._component_obj.predict(fh=fh_)
y_pred.index = X.index
return infer_feature_types(y_pred)<|docstring|>Make predictions using fitted ARIMA regressor.
Args:
X (pd.DataFrame): Data of shape [n_samples, n_features].
y (pd.Series): Target data.
Returns:
pd.Series: Predicted values.
Raises:
ValueError: If X was passed to `fit` but not passed in `predict`.<|endoftext|> |
484094030ca9189f057724d29aa84176f8543299e4c72aeae106732fc6a142d1 | @property
def feature_importance(self):
"Returns array of 0's with a length of 1 as feature_importance is not defined for ARIMA regressor."
return np.zeros(1) | Returns array of 0's with a length of 1 as feature_importance is not defined for ARIMA regressor. | rayml/pipelines/components/estimators/regressors/arima_regressor.py | feature_importance | gcode-ai/rayml | 0 | python | @property
def feature_importance(self):
return np.zeros(1) | @property
def feature_importance(self):
return np.zeros(1)<|docstring|>Returns array of 0's with a length of 1 as feature_importance is not defined for ARIMA regressor.<|endoftext|> |
3ff0951c3877e743cec84dafd85bc1eafde22d51badd3a37c1cf48032b81aef1 | @abc.abstractmethod
def get_dataset(self):
'return a `torch.utils.data.Dataset` object'
raise NotImplementedError() | return a `torch.utils.data.Dataset` object | bichoice/data_processor.py | get_dataset | Dou-Meishi/bert-on-c3 | 0 | python | @abc.abstractmethod
def get_dataset(self):
raise NotImplementedError() | @abc.abstractmethod
def get_dataset(self):
raise NotImplementedError()<|docstring|>return a `torch.utils.data.Dataset` object<|endoftext|> |
b004e0a09ab569ca1dc374e7d8cdb3d3a572893734d70feeaf63291379541de9 | @abc.abstractmethod
def convert_example_to_features(self):
'return a `InputFeatures` object'
raise NotImplementedError() | return a `InputFeatures` object | bichoice/data_processor.py | convert_example_to_features | Dou-Meishi/bert-on-c3 | 0 | python | @abc.abstractmethod
def convert_example_to_features(self):
raise NotImplementedError() | @abc.abstractmethod
def convert_example_to_features(self):
raise NotImplementedError()<|docstring|>return a `InputFeatures` object<|endoftext|> |
6d17f7539a8459cdd2b51ebd88650438d039421fa4019ad3c60d636a63d2e64b | def get_dataset(self, fn, with_label=True):
'\n return C3 dataset as a binary classification problem.\n\n Args\n ----\n `fn` : path to csv file of the dataset\n\n `with_label` : whether that dataset is labeled.\n\n Return\n ------\n `out` : `TensorDataset` object.\n '
features = []
df = pd.read_csv(fn)
for i in tqdm(df.index, desc='tokenizing'):
example = df.iloc[i]
features.append(self.convert_example_to_features(example))
all_input_ids = torch.cat([torch.LongTensor([f.input_ids]) for f in features])
all_input_mask = torch.cat([torch.LongTensor([f.input_mask]) for f in features])
all_segment_ids = torch.cat([torch.LongTensor([f.segment_ids]) for f in features])
if with_label:
all_label_ids = torch.LongTensor(df.label.values)
return TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_label_ids)
else:
return TensorDataset(all_input_ids, all_input_mask, all_segment_ids) | return C3 dataset as a binary classification problem.
Args
----
`fn` : path to csv file of the dataset
`with_label` : whether that dataset is labeled.
Return
------
`out` : `TensorDataset` object. | bichoice/data_processor.py | get_dataset | Dou-Meishi/bert-on-c3 | 0 | python | def get_dataset(self, fn, with_label=True):
'\n return C3 dataset as a binary classification problem.\n\n Args\n ----\n `fn` : path to csv file of the dataset\n\n `with_label` : whether that dataset is labeled.\n\n Return\n ------\n `out` : `TensorDataset` object.\n '
features = []
df = pd.read_csv(fn)
for i in tqdm(df.index, desc='tokenizing'):
example = df.iloc[i]
features.append(self.convert_example_to_features(example))
all_input_ids = torch.cat([torch.LongTensor([f.input_ids]) for f in features])
all_input_mask = torch.cat([torch.LongTensor([f.input_mask]) for f in features])
all_segment_ids = torch.cat([torch.LongTensor([f.segment_ids]) for f in features])
if with_label:
all_label_ids = torch.LongTensor(df.label.values)
return TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_label_ids)
else:
return TensorDataset(all_input_ids, all_input_mask, all_segment_ids) | def get_dataset(self, fn, with_label=True):
'\n return C3 dataset as a binary classification problem.\n\n Args\n ----\n `fn` : path to csv file of the dataset\n\n `with_label` : whether that dataset is labeled.\n\n Return\n ------\n `out` : `TensorDataset` object.\n '
features = []
df = pd.read_csv(fn)
for i in tqdm(df.index, desc='tokenizing'):
example = df.iloc[i]
features.append(self.convert_example_to_features(example))
all_input_ids = torch.cat([torch.LongTensor([f.input_ids]) for f in features])
all_input_mask = torch.cat([torch.LongTensor([f.input_mask]) for f in features])
all_segment_ids = torch.cat([torch.LongTensor([f.segment_ids]) for f in features])
if with_label:
all_label_ids = torch.LongTensor(df.label.values)
return TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_label_ids)
else:
return TensorDataset(all_input_ids, all_input_mask, all_segment_ids)<|docstring|>return C3 dataset as a binary classification problem.
Args
----
`fn` : path to csv file of the dataset
`with_label` : whether that dataset is labeled.
Return
------
`out` : `TensorDataset` object.<|endoftext|> |
b90bb0e740db5878d3638ad6a2d904451c7a104e6cec52e0c47704cdf126d5b6 | def convert_example_to_features(self, example):
'\n convert a single example to a single `InputFeatures` object.\n\n [CLS] passage [SEP] question [SEP] choice_0 [SEP] chioce_1 [SEP]\n\n Args\n ----\n `example` : instance of `C3BinaryExample` or any other object that has same attributes.\n\n Return\n ------\n `out` : `InputFeatures` object\n '
tokens_a = self.tokenizer.tokenize(example.passage)
tokens_b = self.tokenizer.tokenize(example.question)
tokens_c = self.tokenizer.tokenize(example.choice_0)
tokens_d = self.tokenizer.tokenize(example.choice_1)
self._truncate_seq_tuple(tokens_a, tokens_b, tokens_c, tokens_d, max_length=(self.max_length - 5))
tokens = ((((((((['[CLS]'] + tokens_a) + ['[SEP]']) + tokens_b) + ['[SEP]']) + tokens_c) + ['[SEP]']) + tokens_d) + ['[SEP]'])
input_ids = self.tokenizer.convert_tokens_to_ids(tokens)
input_mask = ([1] * len(input_ids))
segment_ids = (([0] * (2 + len(tokens_a))) + ([1] * ((2 + len(tokens_b)) + len(tokens_c))))
input_ids += ([0] * (self.max_length - len(input_ids)))
input_mask += ([0] * (self.max_length - len(input_mask)))
segment_ids += ([0] * (self.max_length - len(segment_ids)))
assert (len(input_ids) == self.max_length)
assert (len(input_mask) == self.max_length)
assert (len(segment_ids) == self.max_length)
label = None
if hasattr(example, 'label'):
label = example.label
return InputFeatures(input_ids, input_mask, segment_ids, label) | convert a single example to a single `InputFeatures` object.
[CLS] passage [SEP] question [SEP] choice_0 [SEP] chioce_1 [SEP]
Args
----
`example` : instance of `C3BinaryExample` or any other object that has same attributes.
Return
------
`out` : `InputFeatures` object | bichoice/data_processor.py | convert_example_to_features | Dou-Meishi/bert-on-c3 | 0 | python | def convert_example_to_features(self, example):
'\n convert a single example to a single `InputFeatures` object.\n\n [CLS] passage [SEP] question [SEP] choice_0 [SEP] chioce_1 [SEP]\n\n Args\n ----\n `example` : instance of `C3BinaryExample` or any other object that has same attributes.\n\n Return\n ------\n `out` : `InputFeatures` object\n '
tokens_a = self.tokenizer.tokenize(example.passage)
tokens_b = self.tokenizer.tokenize(example.question)
tokens_c = self.tokenizer.tokenize(example.choice_0)
tokens_d = self.tokenizer.tokenize(example.choice_1)
self._truncate_seq_tuple(tokens_a, tokens_b, tokens_c, tokens_d, max_length=(self.max_length - 5))
tokens = ((((((((['[CLS]'] + tokens_a) + ['[SEP]']) + tokens_b) + ['[SEP]']) + tokens_c) + ['[SEP]']) + tokens_d) + ['[SEP]'])
input_ids = self.tokenizer.convert_tokens_to_ids(tokens)
input_mask = ([1] * len(input_ids))
segment_ids = (([0] * (2 + len(tokens_a))) + ([1] * ((2 + len(tokens_b)) + len(tokens_c))))
input_ids += ([0] * (self.max_length - len(input_ids)))
input_mask += ([0] * (self.max_length - len(input_mask)))
segment_ids += ([0] * (self.max_length - len(segment_ids)))
assert (len(input_ids) == self.max_length)
assert (len(input_mask) == self.max_length)
assert (len(segment_ids) == self.max_length)
label = None
if hasattr(example, 'label'):
label = example.label
return InputFeatures(input_ids, input_mask, segment_ids, label) | def convert_example_to_features(self, example):
'\n convert a single example to a single `InputFeatures` object.\n\n [CLS] passage [SEP] question [SEP] choice_0 [SEP] chioce_1 [SEP]\n\n Args\n ----\n `example` : instance of `C3BinaryExample` or any other object that has same attributes.\n\n Return\n ------\n `out` : `InputFeatures` object\n '
tokens_a = self.tokenizer.tokenize(example.passage)
tokens_b = self.tokenizer.tokenize(example.question)
tokens_c = self.tokenizer.tokenize(example.choice_0)
tokens_d = self.tokenizer.tokenize(example.choice_1)
self._truncate_seq_tuple(tokens_a, tokens_b, tokens_c, tokens_d, max_length=(self.max_length - 5))
tokens = ((((((((['[CLS]'] + tokens_a) + ['[SEP]']) + tokens_b) + ['[SEP]']) + tokens_c) + ['[SEP]']) + tokens_d) + ['[SEP]'])
input_ids = self.tokenizer.convert_tokens_to_ids(tokens)
input_mask = ([1] * len(input_ids))
segment_ids = (([0] * (2 + len(tokens_a))) + ([1] * ((2 + len(tokens_b)) + len(tokens_c))))
input_ids += ([0] * (self.max_length - len(input_ids)))
input_mask += ([0] * (self.max_length - len(input_mask)))
segment_ids += ([0] * (self.max_length - len(segment_ids)))
assert (len(input_ids) == self.max_length)
assert (len(input_mask) == self.max_length)
assert (len(segment_ids) == self.max_length)
label = None
if hasattr(example, 'label'):
label = example.label
return InputFeatures(input_ids, input_mask, segment_ids, label)<|docstring|>convert a single example to a single `InputFeatures` object.
[CLS] passage [SEP] question [SEP] choice_0 [SEP] chioce_1 [SEP]
Args
----
`example` : instance of `C3BinaryExample` or any other object that has same attributes.
Return
------
`out` : `InputFeatures` object<|endoftext|> |
37ae5333496f70b649937ad6aacd70d8c7e76157d4eab312f4ba290c63351652 | def _truncate_seq_tuple(self, *tokenList, max_length):
"\n Truncates a sequence tuple in place to the maximum length.\n\n This is a simple heuristic which will always truncate the\n longer sequence one token at a time. This makes more sense\n than truncating an equal percent of tokens from each, since if\n one sequence is very short then each token that's truncated\n likely contains more information than a longer sequence.\n "
while True:
lengthList = [len(a) for a in tokenList]
if (sum(lengthList) <= max_length):
break
i = np.argmax(lengthList)
tokenList[i].pop() | Truncates a sequence tuple in place to the maximum length.
This is a simple heuristic which will always truncate the
longer sequence one token at a time. This makes more sense
than truncating an equal percent of tokens from each, since if
one sequence is very short then each token that's truncated
likely contains more information than a longer sequence. | bichoice/data_processor.py | _truncate_seq_tuple | Dou-Meishi/bert-on-c3 | 0 | python | def _truncate_seq_tuple(self, *tokenList, max_length):
"\n Truncates a sequence tuple in place to the maximum length.\n\n This is a simple heuristic which will always truncate the\n longer sequence one token at a time. This makes more sense\n than truncating an equal percent of tokens from each, since if\n one sequence is very short then each token that's truncated\n likely contains more information than a longer sequence.\n "
while True:
lengthList = [len(a) for a in tokenList]
if (sum(lengthList) <= max_length):
break
i = np.argmax(lengthList)
tokenList[i].pop() | def _truncate_seq_tuple(self, *tokenList, max_length):
"\n Truncates a sequence tuple in place to the maximum length.\n\n This is a simple heuristic which will always truncate the\n longer sequence one token at a time. This makes more sense\n than truncating an equal percent of tokens from each, since if\n one sequence is very short then each token that's truncated\n likely contains more information than a longer sequence.\n "
while True:
lengthList = [len(a) for a in tokenList]
if (sum(lengthList) <= max_length):
break
i = np.argmax(lengthList)
tokenList[i].pop()<|docstring|>Truncates a sequence tuple in place to the maximum length.
This is a simple heuristic which will always truncate the
longer sequence one token at a time. This makes more sense
than truncating an equal percent of tokens from each, since if
one sequence is very short then each token that's truncated
likely contains more information than a longer sequence.<|endoftext|> |
7c927a2ca1c46b459bfb775494bdb68080f97f8cea03308a998481997479c426 | def __init__(self, name: str, specs: List[Tuple[(str, str)]]):
'Generic Python Dependency.\n\n Args:\n name (str): Name of package\n specs (List[Tuple[str, str]]): Package constraints.\n\n '
self._name = name
self._specs = specs | Generic Python Dependency.
Args:
name (str): Name of package
specs (List[Tuple[str, str]]): Package constraints. | micropy/packages/package.py | __init__ | MathijsNL/micropy-cli | 0 | python | def __init__(self, name: str, specs: List[Tuple[(str, str)]]):
'Generic Python Dependency.\n\n Args:\n name (str): Name of package\n specs (List[Tuple[str, str]]): Package constraints.\n\n '
self._name = name
self._specs = specs | def __init__(self, name: str, specs: List[Tuple[(str, str)]]):
'Generic Python Dependency.\n\n Args:\n name (str): Name of package\n specs (List[Tuple[str, str]]): Package constraints.\n\n '
self._name = name
self._specs = specs<|docstring|>Generic Python Dependency.
Args:
name (str): Name of package
specs (List[Tuple[str, str]]): Package constraints.<|endoftext|> |
e385523d9b8a9cb16f7661f7e32dfccf9c729e89b9b2cd329a08db98c1dffbef | def check_relative_filename(filename):
'Returns `filename`, checking whether it is relative.\n\n The file name must be relative and represent either the current directory\n or an entry within the current directory or any of its subdirectories. In\n other words, it may not point above the current directory. To specify the\n current directory, pass an empty string or a single dot (`.`). This\n function also checks whether the filename contains special characters. If\n the filename is invalid in any way (absolute, containing special\n characters, or pointing above the current directory), this function calls\n `fail` with a descriptive error message. Otherwise, it returns the\n normalized version of `filename`, using purely lexical simplifications (not\n resolving symbolic links).\n\n Args:\n filename (string): the filename to check\n\n Returns:\n the normalized version of the `filename` argument\n '
if paths.is_absolute(filename):
fail('filename {} is absolute'.format(filename))
filename = paths.normalize(filename)
if ((filename != '.') and (not filename[0].isalpha())):
fail('filename {} has to start with a letter'.format(filename))
for char in filename.elems():
if ((not char.isalnum()) and (char not in '-_./+$@%')):
fail('invalid character {} in filename {}'.format(char, filename))
return filename | Returns `filename`, checking whether it is relative.
The file name must be relative and represent either the current directory
or an entry within the current directory or any of its subdirectories. In
other words, it may not point above the current directory. To specify the
current directory, pass an empty string or a single dot (`.`). This
function also checks whether the filename contains special characters. If
the filename is invalid in any way (absolute, containing special
characters, or pointing above the current directory), this function calls
`fail` with a descriptive error message. Otherwise, it returns the
normalized version of `filename`, using purely lexical simplifications (not
resolving symbolic links).
Args:
filename (string): the filename to check
Returns:
the normalized version of the `filename` argument | elisp/util.bzl | check_relative_filename | phst/rules_elisp | 7 | python | def check_relative_filename(filename):
'Returns `filename`, checking whether it is relative.\n\n The file name must be relative and represent either the current directory\n or an entry within the current directory or any of its subdirectories. In\n other words, it may not point above the current directory. To specify the\n current directory, pass an empty string or a single dot (`.`). This\n function also checks whether the filename contains special characters. If\n the filename is invalid in any way (absolute, containing special\n characters, or pointing above the current directory), this function calls\n `fail` with a descriptive error message. Otherwise, it returns the\n normalized version of `filename`, using purely lexical simplifications (not\n resolving symbolic links).\n\n Args:\n filename (string): the filename to check\n\n Returns:\n the normalized version of the `filename` argument\n '
if paths.is_absolute(filename):
fail('filename {} is absolute'.format(filename))
filename = paths.normalize(filename)
if ((filename != '.') and (not filename[0].isalpha())):
fail('filename {} has to start with a letter'.format(filename))
for char in filename.elems():
if ((not char.isalnum()) and (char not in '-_./+$@%')):
fail('invalid character {} in filename {}'.format(char, filename))
return filename | def check_relative_filename(filename):
'Returns `filename`, checking whether it is relative.\n\n The file name must be relative and represent either the current directory\n or an entry within the current directory or any of its subdirectories. In\n other words, it may not point above the current directory. To specify the\n current directory, pass an empty string or a single dot (`.`). This\n function also checks whether the filename contains special characters. If\n the filename is invalid in any way (absolute, containing special\n characters, or pointing above the current directory), this function calls\n `fail` with a descriptive error message. Otherwise, it returns the\n normalized version of `filename`, using purely lexical simplifications (not\n resolving symbolic links).\n\n Args:\n filename (string): the filename to check\n\n Returns:\n the normalized version of the `filename` argument\n '
if paths.is_absolute(filename):
fail('filename {} is absolute'.format(filename))
filename = paths.normalize(filename)
if ((filename != '.') and (not filename[0].isalpha())):
fail('filename {} has to start with a letter'.format(filename))
for char in filename.elems():
if ((not char.isalnum()) and (char not in '-_./+$@%')):
fail('invalid character {} in filename {}'.format(char, filename))
return filename<|docstring|>Returns `filename`, checking whether it is relative.
The file name must be relative and represent either the current directory
or an entry within the current directory or any of its subdirectories. In
other words, it may not point above the current directory. To specify the
current directory, pass an empty string or a single dot (`.`). This
function also checks whether the filename contains special characters. If
the filename is invalid in any way (absolute, containing special
characters, or pointing above the current directory), this function calls
`fail` with a descriptive error message. Otherwise, it returns the
normalized version of `filename`, using purely lexical simplifications (not
resolving symbolic links).
Args:
filename (string): the filename to check
Returns:
the normalized version of the `filename` argument<|endoftext|> |
bbc99d3e6be7094e5c79449fc78fcf3b19a8a3ffab1e63127351b7cf2350fdfd | def runfile_location(ctx, file):
'Return the filename of the given file relative to the runfiles root.\n\n Args:\n ctx (ctx): the current rule context\n file (File): any file that’s included in the runfiles\n\n Returns:\n a string representing the filename of the file relative to the runfiles\n root\n '
return check_relative_filename(paths.join(ctx.workspace_name, file.short_path)) | Return the filename of the given file relative to the runfiles root.
Args:
ctx (ctx): the current rule context
file (File): any file that’s included in the runfiles
Returns:
a string representing the filename of the file relative to the runfiles
root | elisp/util.bzl | runfile_location | phst/rules_elisp | 7 | python | def runfile_location(ctx, file):
'Return the filename of the given file relative to the runfiles root.\n\n Args:\n ctx (ctx): the current rule context\n file (File): any file that’s included in the runfiles\n\n Returns:\n a string representing the filename of the file relative to the runfiles\n root\n '
return check_relative_filename(paths.join(ctx.workspace_name, file.short_path)) | def runfile_location(ctx, file):
'Return the filename of the given file relative to the runfiles root.\n\n Args:\n ctx (ctx): the current rule context\n file (File): any file that’s included in the runfiles\n\n Returns:\n a string representing the filename of the file relative to the runfiles\n root\n '
return check_relative_filename(paths.join(ctx.workspace_name, file.short_path))<|docstring|>Return the filename of the given file relative to the runfiles root.
Args:
ctx (ctx): the current rule context
file (File): any file that’s included in the runfiles
Returns:
a string representing the filename of the file relative to the runfiles
root<|endoftext|> |
fb398beac2b71560a6cd2cd97950a1ff2454146f7b741f95e6c4afe8bf1bbb3a | def cc_wrapper(ctx, cc_toolchain, feature_configuration, driver, deps):
'Builds a wrapper executable that starts Emacs.\n\n You can use `find_cpp_toolchain` and `cc_common.configure_features` to\n construct appropriate values for `cc_toolchain` and\n `feature_configuration`.\n\n Args:\n ctx (ctx): rule context\n cc_toolchain (Provider): the C++ toolchain to use to compile the wrapper\n feature_configuration (FeatureConfiguration): the features to use to\n compile the wrapper\n driver (File): C++ driver file to compile\n deps (list of Targets): `cc_library` targets to add as dependencies\n\n Returns:\n a pair `(executable, runfiles)` where `executable` is a `File` object\n representing the executable that starts Emacs and `runfiles` is a\n `runfiles` object for the runfiles that the executable will need\n '
infos = [dep[CcInfo] for dep in deps]
(_, objs) = cc_common.compile(name=ctx.label.name, actions=ctx.actions, feature_configuration=feature_configuration, cc_toolchain=cc_toolchain, srcs=[driver], compilation_contexts=[info.compilation_context for info in infos], user_compile_flags=COPTS)
bin = cc_common.link(name=ctx.label.name, actions=ctx.actions, feature_configuration=feature_configuration, cc_toolchain=cc_toolchain, compilation_outputs=objs, linking_contexts=[info.linking_context for info in infos], grep_includes=ctx.executable._grep_includes)
runfiles = ctx.runfiles()
for dep in deps:
runfiles = runfiles.merge(dep[DefaultInfo].default_runfiles)
return (bin.executable, runfiles) | Builds a wrapper executable that starts Emacs.
You can use `find_cpp_toolchain` and `cc_common.configure_features` to
construct appropriate values for `cc_toolchain` and
`feature_configuration`.
Args:
ctx (ctx): rule context
cc_toolchain (Provider): the C++ toolchain to use to compile the wrapper
feature_configuration (FeatureConfiguration): the features to use to
compile the wrapper
driver (File): C++ driver file to compile
deps (list of Targets): `cc_library` targets to add as dependencies
Returns:
a pair `(executable, runfiles)` where `executable` is a `File` object
representing the executable that starts Emacs and `runfiles` is a
`runfiles` object for the runfiles that the executable will need | elisp/util.bzl | cc_wrapper | phst/rules_elisp | 7 | python | def cc_wrapper(ctx, cc_toolchain, feature_configuration, driver, deps):
'Builds a wrapper executable that starts Emacs.\n\n You can use `find_cpp_toolchain` and `cc_common.configure_features` to\n construct appropriate values for `cc_toolchain` and\n `feature_configuration`.\n\n Args:\n ctx (ctx): rule context\n cc_toolchain (Provider): the C++ toolchain to use to compile the wrapper\n feature_configuration (FeatureConfiguration): the features to use to\n compile the wrapper\n driver (File): C++ driver file to compile\n deps (list of Targets): `cc_library` targets to add as dependencies\n\n Returns:\n a pair `(executable, runfiles)` where `executable` is a `File` object\n representing the executable that starts Emacs and `runfiles` is a\n `runfiles` object for the runfiles that the executable will need\n '
infos = [dep[CcInfo] for dep in deps]
(_, objs) = cc_common.compile(name=ctx.label.name, actions=ctx.actions, feature_configuration=feature_configuration, cc_toolchain=cc_toolchain, srcs=[driver], compilation_contexts=[info.compilation_context for info in infos], user_compile_flags=COPTS)
bin = cc_common.link(name=ctx.label.name, actions=ctx.actions, feature_configuration=feature_configuration, cc_toolchain=cc_toolchain, compilation_outputs=objs, linking_contexts=[info.linking_context for info in infos], grep_includes=ctx.executable._grep_includes)
runfiles = ctx.runfiles()
for dep in deps:
runfiles = runfiles.merge(dep[DefaultInfo].default_runfiles)
return (bin.executable, runfiles) | def cc_wrapper(ctx, cc_toolchain, feature_configuration, driver, deps):
'Builds a wrapper executable that starts Emacs.\n\n You can use `find_cpp_toolchain` and `cc_common.configure_features` to\n construct appropriate values for `cc_toolchain` and\n `feature_configuration`.\n\n Args:\n ctx (ctx): rule context\n cc_toolchain (Provider): the C++ toolchain to use to compile the wrapper\n feature_configuration (FeatureConfiguration): the features to use to\n compile the wrapper\n driver (File): C++ driver file to compile\n deps (list of Targets): `cc_library` targets to add as dependencies\n\n Returns:\n a pair `(executable, runfiles)` where `executable` is a `File` object\n representing the executable that starts Emacs and `runfiles` is a\n `runfiles` object for the runfiles that the executable will need\n '
infos = [dep[CcInfo] for dep in deps]
(_, objs) = cc_common.compile(name=ctx.label.name, actions=ctx.actions, feature_configuration=feature_configuration, cc_toolchain=cc_toolchain, srcs=[driver], compilation_contexts=[info.compilation_context for info in infos], user_compile_flags=COPTS)
bin = cc_common.link(name=ctx.label.name, actions=ctx.actions, feature_configuration=feature_configuration, cc_toolchain=cc_toolchain, compilation_outputs=objs, linking_contexts=[info.linking_context for info in infos], grep_includes=ctx.executable._grep_includes)
runfiles = ctx.runfiles()
for dep in deps:
runfiles = runfiles.merge(dep[DefaultInfo].default_runfiles)
return (bin.executable, runfiles)<|docstring|>Builds a wrapper executable that starts Emacs.
You can use `find_cpp_toolchain` and `cc_common.configure_features` to
construct appropriate values for `cc_toolchain` and
`feature_configuration`.
Args:
ctx (ctx): rule context
cc_toolchain (Provider): the C++ toolchain to use to compile the wrapper
feature_configuration (FeatureConfiguration): the features to use to
compile the wrapper
driver (File): C++ driver file to compile
deps (list of Targets): `cc_library` targets to add as dependencies
Returns:
a pair `(executable, runfiles)` where `executable` is a `File` object
representing the executable that starts Emacs and `runfiles` is a
`runfiles` object for the runfiles that the executable will need<|endoftext|> |
f184d12d088a5c997af0b9802f44833e4c88a38a55204db99dce7752cfb48a5b | def cpp_strings(strings):
'Formats the given string list as C++ initializer list.\n\n This function makes an effort to support strings with special characters.\n\n Args:\n strings (list of string): strings to be formatted\n\n Returns:\n a string containing C++ code representing the given string list\n '
return ', '.join([cpp_string(s) for s in strings]) | Formats the given string list as C++ initializer list.
This function makes an effort to support strings with special characters.
Args:
strings (list of string): strings to be formatted
Returns:
a string containing C++ code representing the given string list | elisp/util.bzl | cpp_strings | phst/rules_elisp | 7 | python | def cpp_strings(strings):
'Formats the given string list as C++ initializer list.\n\n This function makes an effort to support strings with special characters.\n\n Args:\n strings (list of string): strings to be formatted\n\n Returns:\n a string containing C++ code representing the given string list\n '
return ', '.join([cpp_string(s) for s in strings]) | def cpp_strings(strings):
'Formats the given string list as C++ initializer list.\n\n This function makes an effort to support strings with special characters.\n\n Args:\n strings (list of string): strings to be formatted\n\n Returns:\n a string containing C++ code representing the given string list\n '
return ', '.join([cpp_string(s) for s in strings])<|docstring|>Formats the given string list as C++ initializer list.
This function makes an effort to support strings with special characters.
Args:
strings (list of string): strings to be formatted
Returns:
a string containing C++ code representing the given string list<|endoftext|> |
c698180e9beede0d10b8edc12e9f783c65b02b70e22ba6c345e4fefe3d162c02 | def cpp_string(string):
'Formats the given string as C++ string literal.\n\n This function makes an effort to support strings with special characters.\n\n Args:\n string: any string\n\n Returns:\n a string containing a properly escaped C++ string literal\n '
delim = '#*?&'
open = (('R"' + delim) + '(')
close = ((')' + delim) + '"')
if (close in string):
fail('String {} can’t be transferred to C++'.format(string))
return ((open + string) + close) | Formats the given string as C++ string literal.
This function makes an effort to support strings with special characters.
Args:
string: any string
Returns:
a string containing a properly escaped C++ string literal | elisp/util.bzl | cpp_string | phst/rules_elisp | 7 | python | def cpp_string(string):
'Formats the given string as C++ string literal.\n\n This function makes an effort to support strings with special characters.\n\n Args:\n string: any string\n\n Returns:\n a string containing a properly escaped C++ string literal\n '
delim = '#*?&'
open = (('R"' + delim) + '(')
close = ((')' + delim) + '"')
if (close in string):
fail('String {} can’t be transferred to C++'.format(string))
return ((open + string) + close) | def cpp_string(string):
'Formats the given string as C++ string literal.\n\n This function makes an effort to support strings with special characters.\n\n Args:\n string: any string\n\n Returns:\n a string containing a properly escaped C++ string literal\n '
delim = '#*?&'
open = (('R"' + delim) + '(')
close = ((')' + delim) + '"')
if (close in string):
fail('String {} can’t be transferred to C++'.format(string))
return ((open + string) + close)<|docstring|>Formats the given string as C++ string literal.
This function makes an effort to support strings with special characters.
Args:
string: any string
Returns:
a string containing a properly escaped C++ string literal<|endoftext|> |
16e0e42979a77d177898fc1aacfbb54daea52e87ac230e15bf4f1c497ee0661b | def cpp_ints(ints):
'Formats the given integer list as C++ initializer list.\n\n Args:\n ints (list of int): numbers to be formatted\n\n Returns:\n a string containing C++ code representing the given number list\n '
return ', '.join([cpp_int(i) for i in ints]) | Formats the given integer list as C++ initializer list.
Args:
ints (list of int): numbers to be formatted
Returns:
a string containing C++ code representing the given number list | elisp/util.bzl | cpp_ints | phst/rules_elisp | 7 | python | def cpp_ints(ints):
'Formats the given integer list as C++ initializer list.\n\n Args:\n ints (list of int): numbers to be formatted\n\n Returns:\n a string containing C++ code representing the given number list\n '
return ', '.join([cpp_int(i) for i in ints]) | def cpp_ints(ints):
'Formats the given integer list as C++ initializer list.\n\n Args:\n ints (list of int): numbers to be formatted\n\n Returns:\n a string containing C++ code representing the given number list\n '
return ', '.join([cpp_int(i) for i in ints])<|docstring|>Formats the given integer list as C++ initializer list.
Args:
ints (list of int): numbers to be formatted
Returns:
a string containing C++ code representing the given number list<|endoftext|> |
087b8fb790f15ce799c4d0ff48fc41e5a6e83ca245a58be03a1df34939b32feb | def cpp_int(int):
'Format the given integer as C++ decimal literal.\n\n Args:\n int: an integer\n\n Returns:\n a string containing a C++ decimal literal\n '
if ((int < (- 32767)) or (int > 32767)):
fail('integer {} out of range'.format(int))
return str(int) | Format the given integer as C++ decimal literal.
Args:
int: an integer
Returns:
a string containing a C++ decimal literal | elisp/util.bzl | cpp_int | phst/rules_elisp | 7 | python | def cpp_int(int):
'Format the given integer as C++ decimal literal.\n\n Args:\n int: an integer\n\n Returns:\n a string containing a C++ decimal literal\n '
if ((int < (- 32767)) or (int > 32767)):
fail('integer {} out of range'.format(int))
return str(int) | def cpp_int(int):
'Format the given integer as C++ decimal literal.\n\n Args:\n int: an integer\n\n Returns:\n a string containing a C++ decimal literal\n '
if ((int < (- 32767)) or (int > 32767)):
fail('integer {} out of range'.format(int))
return str(int)<|docstring|>Format the given integer as C++ decimal literal.
Args:
int: an integer
Returns:
a string containing a C++ decimal literal<|endoftext|> |
6197161826094012278e075d0a178d28fa36b8ac46bcf35c25811533127d43d3 | @router.get('/task-status/{task_id}', dependencies=[Depends(BearerJWTAuthorizationService(permission_groups=[Group.admin]))], response_description='Task status reporting endpoint.', response_model=TaskStatus, status_code=200)
def get_task_status_details(task_id: str) -> TaskStatus:
'\n Entrypoint for celery task status monitoring.\n\n :param task_id: The celery task id.\n\n :return The task status report.\n '
return GetTaskStatusReportService().apply(task_id=task_id) | Entrypoint for celery task status monitoring.
:param task_id: The celery task id.
:return The task status report. | api/src/application/rest_api/task_status/controllers.py | get_task_status_details | iliaskaras/housing-units | 0 | python | @router.get('/task-status/{task_id}', dependencies=[Depends(BearerJWTAuthorizationService(permission_groups=[Group.admin]))], response_description='Task status reporting endpoint.', response_model=TaskStatus, status_code=200)
def get_task_status_details(task_id: str) -> TaskStatus:
'\n Entrypoint for celery task status monitoring.\n\n :param task_id: The celery task id.\n\n :return The task status report.\n '
return GetTaskStatusReportService().apply(task_id=task_id) | @router.get('/task-status/{task_id}', dependencies=[Depends(BearerJWTAuthorizationService(permission_groups=[Group.admin]))], response_description='Task status reporting endpoint.', response_model=TaskStatus, status_code=200)
def get_task_status_details(task_id: str) -> TaskStatus:
'\n Entrypoint for celery task status monitoring.\n\n :param task_id: The celery task id.\n\n :return The task status report.\n '
return GetTaskStatusReportService().apply(task_id=task_id)<|docstring|>Entrypoint for celery task status monitoring.
:param task_id: The celery task id.
:return The task status report.<|endoftext|> |
dab4af4512ae554a01b5873ae0098708c8d80d08fb6c0138469ade5edd842886 | def __init__(self, trace=None, crash_addr=None):
'\n :param trace : The basic block trace.\n :param crash_addr : If the input caused a crash, what address did it crash at?\n '
super(CrashMonitor, self).__init__()
self._trace = trace
self._crash_addr = crash_addr
self.last_state = None
self._crash_type = None
self._crash_state = None | :param trace : The basic block trace.
:param crash_addr : If the input caused a crash, what address did it crash at? | angr/exploration_techniques/crash_monitor.py | __init__ | analyst1001/angr | 2 | python | def __init__(self, trace=None, crash_addr=None):
'\n :param trace : The basic block trace.\n :param crash_addr : If the input caused a crash, what address did it crash at?\n '
super(CrashMonitor, self).__init__()
self._trace = trace
self._crash_addr = crash_addr
self.last_state = None
self._crash_type = None
self._crash_state = None | def __init__(self, trace=None, crash_addr=None):
'\n :param trace : The basic block trace.\n :param crash_addr : If the input caused a crash, what address did it crash at?\n '
super(CrashMonitor, self).__init__()
self._trace = trace
self._crash_addr = crash_addr
self.last_state = None
self._crash_type = None
self._crash_state = None<|docstring|>:param trace : The basic block trace.
:param crash_addr : If the input caused a crash, what address did it crash at?<|endoftext|> |
0507645531f7b1ee2ec5c998fd0f93e89019352c056aa20328de5307a4b5e7c5 | def _grab_concretization_results(self, state):
'\n Grabs the concretized result so we can add the constraint ourselves.\n '
if self._add_constraints(state):
addr = state.inspect.address_concretization_expr
result = state.inspect.address_concretization_result
if (result is None):
l.warning('addr concretization result is None')
return
state.preconstrainer.address_concretization.append((addr, result)) | Grabs the concretized result so we can add the constraint ourselves. | angr/exploration_techniques/crash_monitor.py | _grab_concretization_results | analyst1001/angr | 2 | python | def _grab_concretization_results(self, state):
'\n \n '
if self._add_constraints(state):
addr = state.inspect.address_concretization_expr
result = state.inspect.address_concretization_result
if (result is None):
l.warning('addr concretization result is None')
return
state.preconstrainer.address_concretization.append((addr, result)) | def _grab_concretization_results(self, state):
'\n \n '
if self._add_constraints(state):
addr = state.inspect.address_concretization_expr
result = state.inspect.address_concretization_result
if (result is None):
l.warning('addr concretization result is None')
return
state.preconstrainer.address_concretization.append((addr, result))<|docstring|>Grabs the concretized result so we can add the constraint ourselves.<|endoftext|> |
407458ecffa322986821d3706a4ea748019faf6f4d8d8bcb4a29e745ba597623 | def _dont_add_constraints(self, state):
'\n Obnoxious way to handle this, should ONLY be called from tracer.\n '
state.inspect.address_concretization_add_constraints = self._add_constraints(state) | Obnoxious way to handle this, should ONLY be called from tracer. | angr/exploration_techniques/crash_monitor.py | _dont_add_constraints | analyst1001/angr | 2 | python | def _dont_add_constraints(self, state):
'\n \n '
state.inspect.address_concretization_add_constraints = self._add_constraints(state) | def _dont_add_constraints(self, state):
'\n \n '
state.inspect.address_concretization_add_constraints = self._add_constraints(state)<|docstring|>Obnoxious way to handle this, should ONLY be called from tracer.<|endoftext|> |
322c9a3b3a765fd0667f903c8a4a4dda47643e1b3c064833210dec7d7ac147de | def __init__(self, seed: int=0, max_outputs: int=1, perturb_pct: float=0.5) -> None:
'\n In order to generate multiple different perturbations, you should set seed=None\n '
super().__init__(seed=seed, max_outputs=max_outputs)
self.perturb_pct = perturb_pct | In order to generate multiple different perturbations, you should set seed=None | transformations/visual_attack_letters/transformation.py | __init__ | Quetzalcohuatl/NL-Augmenter | 583 | python | def __init__(self, seed: int=0, max_outputs: int=1, perturb_pct: float=0.5) -> None:
'\n \n '
super().__init__(seed=seed, max_outputs=max_outputs)
self.perturb_pct = perturb_pct | def __init__(self, seed: int=0, max_outputs: int=1, perturb_pct: float=0.5) -> None:
'\n \n '
super().__init__(seed=seed, max_outputs=max_outputs)
self.perturb_pct = perturb_pct<|docstring|>In order to generate multiple different perturbations, you should set seed=None<|endoftext|> |
4974ff735b50a0eb2874f1ba9f5e4b3047be8a129996a828b7d994b5e279acd8 | def extract_ticker(body: str, re_string: str='[$][A-Za-z]*|[A-Z][A-Z]{1,}') -> Set[str]:
'Simple Regex to get tickers from text.'
ticks = set(re.findall(re_string, str(body)))
res = set()
for item in ticks:
if ((item not in block_words) and (item.lower() not in stop_words) and item):
try:
tic = item.replace('$', '').upper()
res.add(tic)
except Exception as e:
print(e)
return res | Simple Regex to get tickers from text. | src/ticker_counts.py | extract_ticker | mickmister/Reddit-Stock-Trends | 2 | python | def extract_ticker(body: str, re_string: str='[$][A-Za-z]*|[A-Z][A-Z]{1,}') -> Set[str]:
ticks = set(re.findall(re_string, str(body)))
res = set()
for item in ticks:
if ((item not in block_words) and (item.lower() not in stop_words) and item):
try:
tic = item.replace('$', ).upper()
res.add(tic)
except Exception as e:
print(e)
return res | def extract_ticker(body: str, re_string: str='[$][A-Za-z]*|[A-Z][A-Z]{1,}') -> Set[str]:
ticks = set(re.findall(re_string, str(body)))
res = set()
for item in ticks:
if ((item not in block_words) and (item.lower() not in stop_words) and item):
try:
tic = item.replace('$', ).upper()
res.add(tic)
except Exception as e:
print(e)
return res<|docstring|>Simple Regex to get tickers from text.<|endoftext|> |
5846c9f3efb2c00912e389b490621c88f981049ffe1628866c52c84b324ab67d | def __init__(__self__, *, account_name: pulumi.Input[str], body: pulumi.Input[str], container_name: pulumi.Input[str], database_name: pulumi.Input[str], resource_group_name: pulumi.Input[str], name: Optional[pulumi.Input[str]]=None):
'\n The set of arguments for constructing a SqlStoredProcedure resource.\n :param pulumi.Input[str] account_name: The name of the Cosmos DB Account to create the stored procedure within. Changing this forces a new resource to be created.\n :param pulumi.Input[str] body: The body of the stored procedure.\n :param pulumi.Input[str] container_name: The name of the Cosmos DB SQL Container to create the stored procedure within. Changing this forces a new resource to be created.\n :param pulumi.Input[str] database_name: The name of the Cosmos DB SQL Database to create the stored procedure within. Changing this forces a new resource to be created.\n :param pulumi.Input[str] resource_group_name: The name of the resource group in which the Cosmos DB SQL Database is created. Changing this forces a new resource to be created.\n :param pulumi.Input[str] name: Specifies the name of the Cosmos DB SQL Stored Procedure. Changing this forces a new resource to be created.\n '
pulumi.set(__self__, 'account_name', account_name)
pulumi.set(__self__, 'body', body)
pulumi.set(__self__, 'container_name', container_name)
pulumi.set(__self__, 'database_name', database_name)
pulumi.set(__self__, 'resource_group_name', resource_group_name)
if (name is not None):
pulumi.set(__self__, 'name', name) | The set of arguments for constructing a SqlStoredProcedure resource.
:param pulumi.Input[str] account_name: The name of the Cosmos DB Account to create the stored procedure within. Changing this forces a new resource to be created.
:param pulumi.Input[str] body: The body of the stored procedure.
:param pulumi.Input[str] container_name: The name of the Cosmos DB SQL Container to create the stored procedure within. Changing this forces a new resource to be created.
:param pulumi.Input[str] database_name: The name of the Cosmos DB SQL Database to create the stored procedure within. Changing this forces a new resource to be created.
:param pulumi.Input[str] resource_group_name: The name of the resource group in which the Cosmos DB SQL Database is created. Changing this forces a new resource to be created.
:param pulumi.Input[str] name: Specifies the name of the Cosmos DB SQL Stored Procedure. Changing this forces a new resource to be created. | sdk/python/pulumi_azure/cosmosdb/sql_stored_procedure.py | __init__ | henriktao/pulumi-azure | 109 | python | def __init__(__self__, *, account_name: pulumi.Input[str], body: pulumi.Input[str], container_name: pulumi.Input[str], database_name: pulumi.Input[str], resource_group_name: pulumi.Input[str], name: Optional[pulumi.Input[str]]=None):
'\n The set of arguments for constructing a SqlStoredProcedure resource.\n :param pulumi.Input[str] account_name: The name of the Cosmos DB Account to create the stored procedure within. Changing this forces a new resource to be created.\n :param pulumi.Input[str] body: The body of the stored procedure.\n :param pulumi.Input[str] container_name: The name of the Cosmos DB SQL Container to create the stored procedure within. Changing this forces a new resource to be created.\n :param pulumi.Input[str] database_name: The name of the Cosmos DB SQL Database to create the stored procedure within. Changing this forces a new resource to be created.\n :param pulumi.Input[str] resource_group_name: The name of the resource group in which the Cosmos DB SQL Database is created. Changing this forces a new resource to be created.\n :param pulumi.Input[str] name: Specifies the name of the Cosmos DB SQL Stored Procedure. Changing this forces a new resource to be created.\n '
pulumi.set(__self__, 'account_name', account_name)
pulumi.set(__self__, 'body', body)
pulumi.set(__self__, 'container_name', container_name)
pulumi.set(__self__, 'database_name', database_name)
pulumi.set(__self__, 'resource_group_name', resource_group_name)
if (name is not None):
pulumi.set(__self__, 'name', name) | def __init__(__self__, *, account_name: pulumi.Input[str], body: pulumi.Input[str], container_name: pulumi.Input[str], database_name: pulumi.Input[str], resource_group_name: pulumi.Input[str], name: Optional[pulumi.Input[str]]=None):
'\n The set of arguments for constructing a SqlStoredProcedure resource.\n :param pulumi.Input[str] account_name: The name of the Cosmos DB Account to create the stored procedure within. Changing this forces a new resource to be created.\n :param pulumi.Input[str] body: The body of the stored procedure.\n :param pulumi.Input[str] container_name: The name of the Cosmos DB SQL Container to create the stored procedure within. Changing this forces a new resource to be created.\n :param pulumi.Input[str] database_name: The name of the Cosmos DB SQL Database to create the stored procedure within. Changing this forces a new resource to be created.\n :param pulumi.Input[str] resource_group_name: The name of the resource group in which the Cosmos DB SQL Database is created. Changing this forces a new resource to be created.\n :param pulumi.Input[str] name: Specifies the name of the Cosmos DB SQL Stored Procedure. Changing this forces a new resource to be created.\n '
pulumi.set(__self__, 'account_name', account_name)
pulumi.set(__self__, 'body', body)
pulumi.set(__self__, 'container_name', container_name)
pulumi.set(__self__, 'database_name', database_name)
pulumi.set(__self__, 'resource_group_name', resource_group_name)
if (name is not None):
pulumi.set(__self__, 'name', name)<|docstring|>The set of arguments for constructing a SqlStoredProcedure resource.
:param pulumi.Input[str] account_name: The name of the Cosmos DB Account to create the stored procedure within. Changing this forces a new resource to be created.
:param pulumi.Input[str] body: The body of the stored procedure.
:param pulumi.Input[str] container_name: The name of the Cosmos DB SQL Container to create the stored procedure within. Changing this forces a new resource to be created.
:param pulumi.Input[str] database_name: The name of the Cosmos DB SQL Database to create the stored procedure within. Changing this forces a new resource to be created.
:param pulumi.Input[str] resource_group_name: The name of the resource group in which the Cosmos DB SQL Database is created. Changing this forces a new resource to be created.
:param pulumi.Input[str] name: Specifies the name of the Cosmos DB SQL Stored Procedure. Changing this forces a new resource to be created.<|endoftext|> |
13d198d9973f6a32f5b2128e75187ff20c1391945dfb4f71f60629627a50a832 | @property
@pulumi.getter(name='accountName')
def account_name(self) -> pulumi.Input[str]:
'\n The name of the Cosmos DB Account to create the stored procedure within. Changing this forces a new resource to be created.\n '
return pulumi.get(self, 'account_name') | The name of the Cosmos DB Account to create the stored procedure within. Changing this forces a new resource to be created. | sdk/python/pulumi_azure/cosmosdb/sql_stored_procedure.py | account_name | henriktao/pulumi-azure | 109 | python | @property
@pulumi.getter(name='accountName')
def account_name(self) -> pulumi.Input[str]:
'\n \n '
return pulumi.get(self, 'account_name') | @property
@pulumi.getter(name='accountName')
def account_name(self) -> pulumi.Input[str]:
'\n \n '
return pulumi.get(self, 'account_name')<|docstring|>The name of the Cosmos DB Account to create the stored procedure within. Changing this forces a new resource to be created.<|endoftext|> |
2ddc52ab86feb13191ce3532af97b43c989f25403ff1c07c74c74998b1a4fb89 | @property
@pulumi.getter
def body(self) -> pulumi.Input[str]:
'\n The body of the stored procedure.\n '
return pulumi.get(self, 'body') | The body of the stored procedure. | sdk/python/pulumi_azure/cosmosdb/sql_stored_procedure.py | body | henriktao/pulumi-azure | 109 | python | @property
@pulumi.getter
def body(self) -> pulumi.Input[str]:
'\n \n '
return pulumi.get(self, 'body') | @property
@pulumi.getter
def body(self) -> pulumi.Input[str]:
'\n \n '
return pulumi.get(self, 'body')<|docstring|>The body of the stored procedure.<|endoftext|> |
940c19c0701c89e4243ec9020feac8914502e66e991fa4120b709533fb241ad8 | @property
@pulumi.getter(name='containerName')
def container_name(self) -> pulumi.Input[str]:
'\n The name of the Cosmos DB SQL Container to create the stored procedure within. Changing this forces a new resource to be created.\n '
return pulumi.get(self, 'container_name') | The name of the Cosmos DB SQL Container to create the stored procedure within. Changing this forces a new resource to be created. | sdk/python/pulumi_azure/cosmosdb/sql_stored_procedure.py | container_name | henriktao/pulumi-azure | 109 | python | @property
@pulumi.getter(name='containerName')
def container_name(self) -> pulumi.Input[str]:
'\n \n '
return pulumi.get(self, 'container_name') | @property
@pulumi.getter(name='containerName')
def container_name(self) -> pulumi.Input[str]:
'\n \n '
return pulumi.get(self, 'container_name')<|docstring|>The name of the Cosmos DB SQL Container to create the stored procedure within. Changing this forces a new resource to be created.<|endoftext|> |
cc96bacea8a3e7dafa79786e9b4a7204401b33e63607557d1cd4a566ebd13def | @property
@pulumi.getter(name='databaseName')
def database_name(self) -> pulumi.Input[str]:
'\n The name of the Cosmos DB SQL Database to create the stored procedure within. Changing this forces a new resource to be created.\n '
return pulumi.get(self, 'database_name') | The name of the Cosmos DB SQL Database to create the stored procedure within. Changing this forces a new resource to be created. | sdk/python/pulumi_azure/cosmosdb/sql_stored_procedure.py | database_name | henriktao/pulumi-azure | 109 | python | @property
@pulumi.getter(name='databaseName')
def database_name(self) -> pulumi.Input[str]:
'\n \n '
return pulumi.get(self, 'database_name') | @property
@pulumi.getter(name='databaseName')
def database_name(self) -> pulumi.Input[str]:
'\n \n '
return pulumi.get(self, 'database_name')<|docstring|>The name of the Cosmos DB SQL Database to create the stored procedure within. Changing this forces a new resource to be created.<|endoftext|> |
51ff2e8bb6f0182c2ca1a8d8139619ee9f264a1dfa969e24d873676628c44a00 | @property
@pulumi.getter(name='resourceGroupName')
def resource_group_name(self) -> pulumi.Input[str]:
'\n The name of the resource group in which the Cosmos DB SQL Database is created. Changing this forces a new resource to be created.\n '
return pulumi.get(self, 'resource_group_name') | The name of the resource group in which the Cosmos DB SQL Database is created. Changing this forces a new resource to be created. | sdk/python/pulumi_azure/cosmosdb/sql_stored_procedure.py | resource_group_name | henriktao/pulumi-azure | 109 | python | @property
@pulumi.getter(name='resourceGroupName')
def resource_group_name(self) -> pulumi.Input[str]:
'\n \n '
return pulumi.get(self, 'resource_group_name') | @property
@pulumi.getter(name='resourceGroupName')
def resource_group_name(self) -> pulumi.Input[str]:
'\n \n '
return pulumi.get(self, 'resource_group_name')<|docstring|>The name of the resource group in which the Cosmos DB SQL Database is created. Changing this forces a new resource to be created.<|endoftext|> |
5b9c91e12caa896ee9335c863465694937a453c8e5e2025ccc7de4dd062afdc0 | @property
@pulumi.getter
def name(self) -> Optional[pulumi.Input[str]]:
'\n Specifies the name of the Cosmos DB SQL Stored Procedure. Changing this forces a new resource to be created.\n '
return pulumi.get(self, 'name') | Specifies the name of the Cosmos DB SQL Stored Procedure. Changing this forces a new resource to be created. | sdk/python/pulumi_azure/cosmosdb/sql_stored_procedure.py | name | henriktao/pulumi-azure | 109 | python | @property
@pulumi.getter
def name(self) -> Optional[pulumi.Input[str]]:
'\n \n '
return pulumi.get(self, 'name') | @property
@pulumi.getter
def name(self) -> Optional[pulumi.Input[str]]:
'\n \n '
return pulumi.get(self, 'name')<|docstring|>Specifies the name of the Cosmos DB SQL Stored Procedure. Changing this forces a new resource to be created.<|endoftext|> |
ce098d53de60d35fc785039f6a7ee29496d94b9a19a3ec943e5a27d05b8b3396 | def __init__(__self__, *, account_name: Optional[pulumi.Input[str]]=None, body: Optional[pulumi.Input[str]]=None, container_name: Optional[pulumi.Input[str]]=None, database_name: Optional[pulumi.Input[str]]=None, name: Optional[pulumi.Input[str]]=None, resource_group_name: Optional[pulumi.Input[str]]=None):
'\n Input properties used for looking up and filtering SqlStoredProcedure resources.\n :param pulumi.Input[str] account_name: The name of the Cosmos DB Account to create the stored procedure within. Changing this forces a new resource to be created.\n :param pulumi.Input[str] body: The body of the stored procedure.\n :param pulumi.Input[str] container_name: The name of the Cosmos DB SQL Container to create the stored procedure within. Changing this forces a new resource to be created.\n :param pulumi.Input[str] database_name: The name of the Cosmos DB SQL Database to create the stored procedure within. Changing this forces a new resource to be created.\n :param pulumi.Input[str] name: Specifies the name of the Cosmos DB SQL Stored Procedure. Changing this forces a new resource to be created.\n :param pulumi.Input[str] resource_group_name: The name of the resource group in which the Cosmos DB SQL Database is created. Changing this forces a new resource to be created.\n '
if (account_name is not None):
pulumi.set(__self__, 'account_name', account_name)
if (body is not None):
pulumi.set(__self__, 'body', body)
if (container_name is not None):
pulumi.set(__self__, 'container_name', container_name)
if (database_name is not None):
pulumi.set(__self__, 'database_name', database_name)
if (name is not None):
pulumi.set(__self__, 'name', name)
if (resource_group_name is not None):
pulumi.set(__self__, 'resource_group_name', resource_group_name) | Input properties used for looking up and filtering SqlStoredProcedure resources.
:param pulumi.Input[str] account_name: The name of the Cosmos DB Account to create the stored procedure within. Changing this forces a new resource to be created.
:param pulumi.Input[str] body: The body of the stored procedure.
:param pulumi.Input[str] container_name: The name of the Cosmos DB SQL Container to create the stored procedure within. Changing this forces a new resource to be created.
:param pulumi.Input[str] database_name: The name of the Cosmos DB SQL Database to create the stored procedure within. Changing this forces a new resource to be created.
:param pulumi.Input[str] name: Specifies the name of the Cosmos DB SQL Stored Procedure. Changing this forces a new resource to be created.
:param pulumi.Input[str] resource_group_name: The name of the resource group in which the Cosmos DB SQL Database is created. Changing this forces a new resource to be created. | sdk/python/pulumi_azure/cosmosdb/sql_stored_procedure.py | __init__ | henriktao/pulumi-azure | 109 | python | def __init__(__self__, *, account_name: Optional[pulumi.Input[str]]=None, body: Optional[pulumi.Input[str]]=None, container_name: Optional[pulumi.Input[str]]=None, database_name: Optional[pulumi.Input[str]]=None, name: Optional[pulumi.Input[str]]=None, resource_group_name: Optional[pulumi.Input[str]]=None):
'\n Input properties used for looking up and filtering SqlStoredProcedure resources.\n :param pulumi.Input[str] account_name: The name of the Cosmos DB Account to create the stored procedure within. Changing this forces a new resource to be created.\n :param pulumi.Input[str] body: The body of the stored procedure.\n :param pulumi.Input[str] container_name: The name of the Cosmos DB SQL Container to create the stored procedure within. Changing this forces a new resource to be created.\n :param pulumi.Input[str] database_name: The name of the Cosmos DB SQL Database to create the stored procedure within. Changing this forces a new resource to be created.\n :param pulumi.Input[str] name: Specifies the name of the Cosmos DB SQL Stored Procedure. Changing this forces a new resource to be created.\n :param pulumi.Input[str] resource_group_name: The name of the resource group in which the Cosmos DB SQL Database is created. Changing this forces a new resource to be created.\n '
if (account_name is not None):
pulumi.set(__self__, 'account_name', account_name)
if (body is not None):
pulumi.set(__self__, 'body', body)
if (container_name is not None):
pulumi.set(__self__, 'container_name', container_name)
if (database_name is not None):
pulumi.set(__self__, 'database_name', database_name)
if (name is not None):
pulumi.set(__self__, 'name', name)
if (resource_group_name is not None):
pulumi.set(__self__, 'resource_group_name', resource_group_name) | def __init__(__self__, *, account_name: Optional[pulumi.Input[str]]=None, body: Optional[pulumi.Input[str]]=None, container_name: Optional[pulumi.Input[str]]=None, database_name: Optional[pulumi.Input[str]]=None, name: Optional[pulumi.Input[str]]=None, resource_group_name: Optional[pulumi.Input[str]]=None):
'\n Input properties used for looking up and filtering SqlStoredProcedure resources.\n :param pulumi.Input[str] account_name: The name of the Cosmos DB Account to create the stored procedure within. Changing this forces a new resource to be created.\n :param pulumi.Input[str] body: The body of the stored procedure.\n :param pulumi.Input[str] container_name: The name of the Cosmos DB SQL Container to create the stored procedure within. Changing this forces a new resource to be created.\n :param pulumi.Input[str] database_name: The name of the Cosmos DB SQL Database to create the stored procedure within. Changing this forces a new resource to be created.\n :param pulumi.Input[str] name: Specifies the name of the Cosmos DB SQL Stored Procedure. Changing this forces a new resource to be created.\n :param pulumi.Input[str] resource_group_name: The name of the resource group in which the Cosmos DB SQL Database is created. Changing this forces a new resource to be created.\n '
if (account_name is not None):
pulumi.set(__self__, 'account_name', account_name)
if (body is not None):
pulumi.set(__self__, 'body', body)
if (container_name is not None):
pulumi.set(__self__, 'container_name', container_name)
if (database_name is not None):
pulumi.set(__self__, 'database_name', database_name)
if (name is not None):
pulumi.set(__self__, 'name', name)
if (resource_group_name is not None):
pulumi.set(__self__, 'resource_group_name', resource_group_name)<|docstring|>Input properties used for looking up and filtering SqlStoredProcedure resources.
:param pulumi.Input[str] account_name: The name of the Cosmos DB Account to create the stored procedure within. Changing this forces a new resource to be created.
:param pulumi.Input[str] body: The body of the stored procedure.
:param pulumi.Input[str] container_name: The name of the Cosmos DB SQL Container to create the stored procedure within. Changing this forces a new resource to be created.
:param pulumi.Input[str] database_name: The name of the Cosmos DB SQL Database to create the stored procedure within. Changing this forces a new resource to be created.
:param pulumi.Input[str] name: Specifies the name of the Cosmos DB SQL Stored Procedure. Changing this forces a new resource to be created.
:param pulumi.Input[str] resource_group_name: The name of the resource group in which the Cosmos DB SQL Database is created. Changing this forces a new resource to be created.<|endoftext|> |
b63b3d0c621c5a9d4a763213bc57171bccf4c439a0d838d7f9c5626abb89a685 | @property
@pulumi.getter(name='accountName')
def account_name(self) -> Optional[pulumi.Input[str]]:
'\n The name of the Cosmos DB Account to create the stored procedure within. Changing this forces a new resource to be created.\n '
return pulumi.get(self, 'account_name') | The name of the Cosmos DB Account to create the stored procedure within. Changing this forces a new resource to be created. | sdk/python/pulumi_azure/cosmosdb/sql_stored_procedure.py | account_name | henriktao/pulumi-azure | 109 | python | @property
@pulumi.getter(name='accountName')
def account_name(self) -> Optional[pulumi.Input[str]]:
'\n \n '
return pulumi.get(self, 'account_name') | @property
@pulumi.getter(name='accountName')
def account_name(self) -> Optional[pulumi.Input[str]]:
'\n \n '
return pulumi.get(self, 'account_name')<|docstring|>The name of the Cosmos DB Account to create the stored procedure within. Changing this forces a new resource to be created.<|endoftext|> |
b38d8cef50c57b202843a8add641e448cc2aadbf0f70057d50f6b5580ba372bd | @property
@pulumi.getter
def body(self) -> Optional[pulumi.Input[str]]:
'\n The body of the stored procedure.\n '
return pulumi.get(self, 'body') | The body of the stored procedure. | sdk/python/pulumi_azure/cosmosdb/sql_stored_procedure.py | body | henriktao/pulumi-azure | 109 | python | @property
@pulumi.getter
def body(self) -> Optional[pulumi.Input[str]]:
'\n \n '
return pulumi.get(self, 'body') | @property
@pulumi.getter
def body(self) -> Optional[pulumi.Input[str]]:
'\n \n '
return pulumi.get(self, 'body')<|docstring|>The body of the stored procedure.<|endoftext|> |
e2d10a4c822e6d1297272bc27d0fd94491a9e6c8338305089a7a4b04b63faf66 | @property
@pulumi.getter(name='containerName')
def container_name(self) -> Optional[pulumi.Input[str]]:
'\n The name of the Cosmos DB SQL Container to create the stored procedure within. Changing this forces a new resource to be created.\n '
return pulumi.get(self, 'container_name') | The name of the Cosmos DB SQL Container to create the stored procedure within. Changing this forces a new resource to be created. | sdk/python/pulumi_azure/cosmosdb/sql_stored_procedure.py | container_name | henriktao/pulumi-azure | 109 | python | @property
@pulumi.getter(name='containerName')
def container_name(self) -> Optional[pulumi.Input[str]]:
'\n \n '
return pulumi.get(self, 'container_name') | @property
@pulumi.getter(name='containerName')
def container_name(self) -> Optional[pulumi.Input[str]]:
'\n \n '
return pulumi.get(self, 'container_name')<|docstring|>The name of the Cosmos DB SQL Container to create the stored procedure within. Changing this forces a new resource to be created.<|endoftext|> |
6a141665388adee3f472eb48e381e60b79618f96c3aba6d39aa7b18923b34d5c | @property
@pulumi.getter(name='databaseName')
def database_name(self) -> Optional[pulumi.Input[str]]:
'\n The name of the Cosmos DB SQL Database to create the stored procedure within. Changing this forces a new resource to be created.\n '
return pulumi.get(self, 'database_name') | The name of the Cosmos DB SQL Database to create the stored procedure within. Changing this forces a new resource to be created. | sdk/python/pulumi_azure/cosmosdb/sql_stored_procedure.py | database_name | henriktao/pulumi-azure | 109 | python | @property
@pulumi.getter(name='databaseName')
def database_name(self) -> Optional[pulumi.Input[str]]:
'\n \n '
return pulumi.get(self, 'database_name') | @property
@pulumi.getter(name='databaseName')
def database_name(self) -> Optional[pulumi.Input[str]]:
'\n \n '
return pulumi.get(self, 'database_name')<|docstring|>The name of the Cosmos DB SQL Database to create the stored procedure within. Changing this forces a new resource to be created.<|endoftext|> |
5b9c91e12caa896ee9335c863465694937a453c8e5e2025ccc7de4dd062afdc0 | @property
@pulumi.getter
def name(self) -> Optional[pulumi.Input[str]]:
'\n Specifies the name of the Cosmos DB SQL Stored Procedure. Changing this forces a new resource to be created.\n '
return pulumi.get(self, 'name') | Specifies the name of the Cosmos DB SQL Stored Procedure. Changing this forces a new resource to be created. | sdk/python/pulumi_azure/cosmosdb/sql_stored_procedure.py | name | henriktao/pulumi-azure | 109 | python | @property
@pulumi.getter
def name(self) -> Optional[pulumi.Input[str]]:
'\n \n '
return pulumi.get(self, 'name') | @property
@pulumi.getter
def name(self) -> Optional[pulumi.Input[str]]:
'\n \n '
return pulumi.get(self, 'name')<|docstring|>Specifies the name of the Cosmos DB SQL Stored Procedure. Changing this forces a new resource to be created.<|endoftext|> |
5519de5a318bc767dda2f48d0f4ad4e582e65cdcd8aa29daa2052e0cf24e92ef | @property
@pulumi.getter(name='resourceGroupName')
def resource_group_name(self) -> Optional[pulumi.Input[str]]:
'\n The name of the resource group in which the Cosmos DB SQL Database is created. Changing this forces a new resource to be created.\n '
return pulumi.get(self, 'resource_group_name') | The name of the resource group in which the Cosmos DB SQL Database is created. Changing this forces a new resource to be created. | sdk/python/pulumi_azure/cosmosdb/sql_stored_procedure.py | resource_group_name | henriktao/pulumi-azure | 109 | python | @property
@pulumi.getter(name='resourceGroupName')
def resource_group_name(self) -> Optional[pulumi.Input[str]]:
'\n \n '
return pulumi.get(self, 'resource_group_name') | @property
@pulumi.getter(name='resourceGroupName')
def resource_group_name(self) -> Optional[pulumi.Input[str]]:
'\n \n '
return pulumi.get(self, 'resource_group_name')<|docstring|>The name of the resource group in which the Cosmos DB SQL Database is created. Changing this forces a new resource to be created.<|endoftext|> |
fd598af4399abd0b89ff2524d56d749ddcb4270604cf49ce4ffa58c9f9eee41f | @overload
def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions]=None, account_name: Optional[pulumi.Input[str]]=None, body: Optional[pulumi.Input[str]]=None, container_name: Optional[pulumi.Input[str]]=None, database_name: Optional[pulumi.Input[str]]=None, name: Optional[pulumi.Input[str]]=None, resource_group_name: Optional[pulumi.Input[str]]=None, __props__=None):
'\n Manages a SQL Stored Procedure within a Cosmos DB Account SQL Database.\n\n ## Example Usage\n\n ```python\n import pulumi\n import pulumi_azure as azure\n\n example_account = azure.cosmosdb.get_account(name="tfex-cosmosdb-account",\n resource_group_name="tfex-cosmosdb-account-rg")\n example_sql_database = azure.cosmosdb.SqlDatabase("exampleSqlDatabase",\n resource_group_name=example_account.resource_group_name,\n account_name=example_account.name,\n throughput=400)\n example_sql_container = azure.cosmosdb.SqlContainer("exampleSqlContainer",\n resource_group_name=azurerm_cosmosdb_account["example"]["resource_group_name"],\n account_name=azurerm_cosmosdb_account["example"]["name"],\n database_name=example_sql_database.name,\n partition_key_path="/id")\n example_sql_stored_procedure = azure.cosmosdb.SqlStoredProcedure("exampleSqlStoredProcedure",\n resource_group_name=azurerm_cosmosdb_account["example"]["resource_group_name"],\n account_name=azurerm_cosmosdb_account["example"]["name"],\n database_name=example_sql_database.name,\n container_name=example_sql_container.name,\n body=" \tfunction () { var context = getContext(); var response = context.getResponse(); response.setBody(\'Hello, World\'); }\n")\n ```\n\n ## Import\n\n CosmosDB SQL Stored Procedures can be imported using the `resource id`, e.g.\n\n ```sh\n $ pulumi import azure:cosmosdb/sqlStoredProcedure:SqlStoredProcedure db1 /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg1/providers/Microsoft.DocumentDB/databaseAccounts/account1/sqlDatabases/db1/containers/c1/storedProcedures/sp1\n ```\n\n :param str resource_name: The name of the resource.\n :param pulumi.ResourceOptions opts: Options for the resource.\n :param pulumi.Input[str] account_name: The name of the Cosmos DB Account to create the stored procedure within. Changing this forces a new resource to be created.\n :param pulumi.Input[str] body: The body of the stored procedure.\n :param pulumi.Input[str] container_name: The name of the Cosmos DB SQL Container to create the stored procedure within. Changing this forces a new resource to be created.\n :param pulumi.Input[str] database_name: The name of the Cosmos DB SQL Database to create the stored procedure within. Changing this forces a new resource to be created.\n :param pulumi.Input[str] name: Specifies the name of the Cosmos DB SQL Stored Procedure. Changing this forces a new resource to be created.\n :param pulumi.Input[str] resource_group_name: The name of the resource group in which the Cosmos DB SQL Database is created. Changing this forces a new resource to be created.\n '
... | Manages a SQL Stored Procedure within a Cosmos DB Account SQL Database.
## Example Usage
```python
import pulumi
import pulumi_azure as azure
example_account = azure.cosmosdb.get_account(name="tfex-cosmosdb-account",
resource_group_name="tfex-cosmosdb-account-rg")
example_sql_database = azure.cosmosdb.SqlDatabase("exampleSqlDatabase",
resource_group_name=example_account.resource_group_name,
account_name=example_account.name,
throughput=400)
example_sql_container = azure.cosmosdb.SqlContainer("exampleSqlContainer",
resource_group_name=azurerm_cosmosdb_account["example"]["resource_group_name"],
account_name=azurerm_cosmosdb_account["example"]["name"],
database_name=example_sql_database.name,
partition_key_path="/id")
example_sql_stored_procedure = azure.cosmosdb.SqlStoredProcedure("exampleSqlStoredProcedure",
resource_group_name=azurerm_cosmosdb_account["example"]["resource_group_name"],
account_name=azurerm_cosmosdb_account["example"]["name"],
database_name=example_sql_database.name,
container_name=example_sql_container.name,
body=" function () { var context = getContext(); var response = context.getResponse(); response.setBody('Hello, World'); }
")
```
## Import
CosmosDB SQL Stored Procedures can be imported using the `resource id`, e.g.
```sh
$ pulumi import azure:cosmosdb/sqlStoredProcedure:SqlStoredProcedure db1 /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg1/providers/Microsoft.DocumentDB/databaseAccounts/account1/sqlDatabases/db1/containers/c1/storedProcedures/sp1
```
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[str] account_name: The name of the Cosmos DB Account to create the stored procedure within. Changing this forces a new resource to be created.
:param pulumi.Input[str] body: The body of the stored procedure.
:param pulumi.Input[str] container_name: The name of the Cosmos DB SQL Container to create the stored procedure within. Changing this forces a new resource to be created.
:param pulumi.Input[str] database_name: The name of the Cosmos DB SQL Database to create the stored procedure within. Changing this forces a new resource to be created.
:param pulumi.Input[str] name: Specifies the name of the Cosmos DB SQL Stored Procedure. Changing this forces a new resource to be created.
:param pulumi.Input[str] resource_group_name: The name of the resource group in which the Cosmos DB SQL Database is created. Changing this forces a new resource to be created. | sdk/python/pulumi_azure/cosmosdb/sql_stored_procedure.py | __init__ | henriktao/pulumi-azure | 109 | python | @overload
def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions]=None, account_name: Optional[pulumi.Input[str]]=None, body: Optional[pulumi.Input[str]]=None, container_name: Optional[pulumi.Input[str]]=None, database_name: Optional[pulumi.Input[str]]=None, name: Optional[pulumi.Input[str]]=None, resource_group_name: Optional[pulumi.Input[str]]=None, __props__=None):
'\n Manages a SQL Stored Procedure within a Cosmos DB Account SQL Database.\n\n ## Example Usage\n\n ```python\n import pulumi\n import pulumi_azure as azure\n\n example_account = azure.cosmosdb.get_account(name="tfex-cosmosdb-account",\n resource_group_name="tfex-cosmosdb-account-rg")\n example_sql_database = azure.cosmosdb.SqlDatabase("exampleSqlDatabase",\n resource_group_name=example_account.resource_group_name,\n account_name=example_account.name,\n throughput=400)\n example_sql_container = azure.cosmosdb.SqlContainer("exampleSqlContainer",\n resource_group_name=azurerm_cosmosdb_account["example"]["resource_group_name"],\n account_name=azurerm_cosmosdb_account["example"]["name"],\n database_name=example_sql_database.name,\n partition_key_path="/id")\n example_sql_stored_procedure = azure.cosmosdb.SqlStoredProcedure("exampleSqlStoredProcedure",\n resource_group_name=azurerm_cosmosdb_account["example"]["resource_group_name"],\n account_name=azurerm_cosmosdb_account["example"]["name"],\n database_name=example_sql_database.name,\n container_name=example_sql_container.name,\n body=" \tfunction () { var context = getContext(); var response = context.getResponse(); response.setBody(\'Hello, World\'); }\n")\n ```\n\n ## Import\n\n CosmosDB SQL Stored Procedures can be imported using the `resource id`, e.g.\n\n ```sh\n $ pulumi import azure:cosmosdb/sqlStoredProcedure:SqlStoredProcedure db1 /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg1/providers/Microsoft.DocumentDB/databaseAccounts/account1/sqlDatabases/db1/containers/c1/storedProcedures/sp1\n ```\n\n :param str resource_name: The name of the resource.\n :param pulumi.ResourceOptions opts: Options for the resource.\n :param pulumi.Input[str] account_name: The name of the Cosmos DB Account to create the stored procedure within. Changing this forces a new resource to be created.\n :param pulumi.Input[str] body: The body of the stored procedure.\n :param pulumi.Input[str] container_name: The name of the Cosmos DB SQL Container to create the stored procedure within. Changing this forces a new resource to be created.\n :param pulumi.Input[str] database_name: The name of the Cosmos DB SQL Database to create the stored procedure within. Changing this forces a new resource to be created.\n :param pulumi.Input[str] name: Specifies the name of the Cosmos DB SQL Stored Procedure. Changing this forces a new resource to be created.\n :param pulumi.Input[str] resource_group_name: The name of the resource group in which the Cosmos DB SQL Database is created. Changing this forces a new resource to be created.\n '
... | @overload
def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions]=None, account_name: Optional[pulumi.Input[str]]=None, body: Optional[pulumi.Input[str]]=None, container_name: Optional[pulumi.Input[str]]=None, database_name: Optional[pulumi.Input[str]]=None, name: Optional[pulumi.Input[str]]=None, resource_group_name: Optional[pulumi.Input[str]]=None, __props__=None):
'\n Manages a SQL Stored Procedure within a Cosmos DB Account SQL Database.\n\n ## Example Usage\n\n ```python\n import pulumi\n import pulumi_azure as azure\n\n example_account = azure.cosmosdb.get_account(name="tfex-cosmosdb-account",\n resource_group_name="tfex-cosmosdb-account-rg")\n example_sql_database = azure.cosmosdb.SqlDatabase("exampleSqlDatabase",\n resource_group_name=example_account.resource_group_name,\n account_name=example_account.name,\n throughput=400)\n example_sql_container = azure.cosmosdb.SqlContainer("exampleSqlContainer",\n resource_group_name=azurerm_cosmosdb_account["example"]["resource_group_name"],\n account_name=azurerm_cosmosdb_account["example"]["name"],\n database_name=example_sql_database.name,\n partition_key_path="/id")\n example_sql_stored_procedure = azure.cosmosdb.SqlStoredProcedure("exampleSqlStoredProcedure",\n resource_group_name=azurerm_cosmosdb_account["example"]["resource_group_name"],\n account_name=azurerm_cosmosdb_account["example"]["name"],\n database_name=example_sql_database.name,\n container_name=example_sql_container.name,\n body=" \tfunction () { var context = getContext(); var response = context.getResponse(); response.setBody(\'Hello, World\'); }\n")\n ```\n\n ## Import\n\n CosmosDB SQL Stored Procedures can be imported using the `resource id`, e.g.\n\n ```sh\n $ pulumi import azure:cosmosdb/sqlStoredProcedure:SqlStoredProcedure db1 /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg1/providers/Microsoft.DocumentDB/databaseAccounts/account1/sqlDatabases/db1/containers/c1/storedProcedures/sp1\n ```\n\n :param str resource_name: The name of the resource.\n :param pulumi.ResourceOptions opts: Options for the resource.\n :param pulumi.Input[str] account_name: The name of the Cosmos DB Account to create the stored procedure within. Changing this forces a new resource to be created.\n :param pulumi.Input[str] body: The body of the stored procedure.\n :param pulumi.Input[str] container_name: The name of the Cosmos DB SQL Container to create the stored procedure within. Changing this forces a new resource to be created.\n :param pulumi.Input[str] database_name: The name of the Cosmos DB SQL Database to create the stored procedure within. Changing this forces a new resource to be created.\n :param pulumi.Input[str] name: Specifies the name of the Cosmos DB SQL Stored Procedure. Changing this forces a new resource to be created.\n :param pulumi.Input[str] resource_group_name: The name of the resource group in which the Cosmos DB SQL Database is created. Changing this forces a new resource to be created.\n '
...<|docstring|>Manages a SQL Stored Procedure within a Cosmos DB Account SQL Database.
## Example Usage
```python
import pulumi
import pulumi_azure as azure
example_account = azure.cosmosdb.get_account(name="tfex-cosmosdb-account",
resource_group_name="tfex-cosmosdb-account-rg")
example_sql_database = azure.cosmosdb.SqlDatabase("exampleSqlDatabase",
resource_group_name=example_account.resource_group_name,
account_name=example_account.name,
throughput=400)
example_sql_container = azure.cosmosdb.SqlContainer("exampleSqlContainer",
resource_group_name=azurerm_cosmosdb_account["example"]["resource_group_name"],
account_name=azurerm_cosmosdb_account["example"]["name"],
database_name=example_sql_database.name,
partition_key_path="/id")
example_sql_stored_procedure = azure.cosmosdb.SqlStoredProcedure("exampleSqlStoredProcedure",
resource_group_name=azurerm_cosmosdb_account["example"]["resource_group_name"],
account_name=azurerm_cosmosdb_account["example"]["name"],
database_name=example_sql_database.name,
container_name=example_sql_container.name,
body=" function () { var context = getContext(); var response = context.getResponse(); response.setBody('Hello, World'); }
")
```
## Import
CosmosDB SQL Stored Procedures can be imported using the `resource id`, e.g.
```sh
$ pulumi import azure:cosmosdb/sqlStoredProcedure:SqlStoredProcedure db1 /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg1/providers/Microsoft.DocumentDB/databaseAccounts/account1/sqlDatabases/db1/containers/c1/storedProcedures/sp1
```
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[str] account_name: The name of the Cosmos DB Account to create the stored procedure within. Changing this forces a new resource to be created.
:param pulumi.Input[str] body: The body of the stored procedure.
:param pulumi.Input[str] container_name: The name of the Cosmos DB SQL Container to create the stored procedure within. Changing this forces a new resource to be created.
:param pulumi.Input[str] database_name: The name of the Cosmos DB SQL Database to create the stored procedure within. Changing this forces a new resource to be created.
:param pulumi.Input[str] name: Specifies the name of the Cosmos DB SQL Stored Procedure. Changing this forces a new resource to be created.
:param pulumi.Input[str] resource_group_name: The name of the resource group in which the Cosmos DB SQL Database is created. Changing this forces a new resource to be created.<|endoftext|> |
193754e6a104aa2abbc67c1d6ef3e27227929c489f96cff0d5e35ce081da5c93 | @overload
def __init__(__self__, resource_name: str, args: SqlStoredProcedureArgs, opts: Optional[pulumi.ResourceOptions]=None):
'\n Manages a SQL Stored Procedure within a Cosmos DB Account SQL Database.\n\n ## Example Usage\n\n ```python\n import pulumi\n import pulumi_azure as azure\n\n example_account = azure.cosmosdb.get_account(name="tfex-cosmosdb-account",\n resource_group_name="tfex-cosmosdb-account-rg")\n example_sql_database = azure.cosmosdb.SqlDatabase("exampleSqlDatabase",\n resource_group_name=example_account.resource_group_name,\n account_name=example_account.name,\n throughput=400)\n example_sql_container = azure.cosmosdb.SqlContainer("exampleSqlContainer",\n resource_group_name=azurerm_cosmosdb_account["example"]["resource_group_name"],\n account_name=azurerm_cosmosdb_account["example"]["name"],\n database_name=example_sql_database.name,\n partition_key_path="/id")\n example_sql_stored_procedure = azure.cosmosdb.SqlStoredProcedure("exampleSqlStoredProcedure",\n resource_group_name=azurerm_cosmosdb_account["example"]["resource_group_name"],\n account_name=azurerm_cosmosdb_account["example"]["name"],\n database_name=example_sql_database.name,\n container_name=example_sql_container.name,\n body=" \tfunction () { var context = getContext(); var response = context.getResponse(); response.setBody(\'Hello, World\'); }\n")\n ```\n\n ## Import\n\n CosmosDB SQL Stored Procedures can be imported using the `resource id`, e.g.\n\n ```sh\n $ pulumi import azure:cosmosdb/sqlStoredProcedure:SqlStoredProcedure db1 /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg1/providers/Microsoft.DocumentDB/databaseAccounts/account1/sqlDatabases/db1/containers/c1/storedProcedures/sp1\n ```\n\n :param str resource_name: The name of the resource.\n :param SqlStoredProcedureArgs args: The arguments to use to populate this resource\'s properties.\n :param pulumi.ResourceOptions opts: Options for the resource.\n '
... | Manages a SQL Stored Procedure within a Cosmos DB Account SQL Database.
## Example Usage
```python
import pulumi
import pulumi_azure as azure
example_account = azure.cosmosdb.get_account(name="tfex-cosmosdb-account",
resource_group_name="tfex-cosmosdb-account-rg")
example_sql_database = azure.cosmosdb.SqlDatabase("exampleSqlDatabase",
resource_group_name=example_account.resource_group_name,
account_name=example_account.name,
throughput=400)
example_sql_container = azure.cosmosdb.SqlContainer("exampleSqlContainer",
resource_group_name=azurerm_cosmosdb_account["example"]["resource_group_name"],
account_name=azurerm_cosmosdb_account["example"]["name"],
database_name=example_sql_database.name,
partition_key_path="/id")
example_sql_stored_procedure = azure.cosmosdb.SqlStoredProcedure("exampleSqlStoredProcedure",
resource_group_name=azurerm_cosmosdb_account["example"]["resource_group_name"],
account_name=azurerm_cosmosdb_account["example"]["name"],
database_name=example_sql_database.name,
container_name=example_sql_container.name,
body=" function () { var context = getContext(); var response = context.getResponse(); response.setBody('Hello, World'); }
")
```
## Import
CosmosDB SQL Stored Procedures can be imported using the `resource id`, e.g.
```sh
$ pulumi import azure:cosmosdb/sqlStoredProcedure:SqlStoredProcedure db1 /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg1/providers/Microsoft.DocumentDB/databaseAccounts/account1/sqlDatabases/db1/containers/c1/storedProcedures/sp1
```
:param str resource_name: The name of the resource.
:param SqlStoredProcedureArgs args: The arguments to use to populate this resource's properties.
:param pulumi.ResourceOptions opts: Options for the resource. | sdk/python/pulumi_azure/cosmosdb/sql_stored_procedure.py | __init__ | henriktao/pulumi-azure | 109 | python | @overload
def __init__(__self__, resource_name: str, args: SqlStoredProcedureArgs, opts: Optional[pulumi.ResourceOptions]=None):
'\n Manages a SQL Stored Procedure within a Cosmos DB Account SQL Database.\n\n ## Example Usage\n\n ```python\n import pulumi\n import pulumi_azure as azure\n\n example_account = azure.cosmosdb.get_account(name="tfex-cosmosdb-account",\n resource_group_name="tfex-cosmosdb-account-rg")\n example_sql_database = azure.cosmosdb.SqlDatabase("exampleSqlDatabase",\n resource_group_name=example_account.resource_group_name,\n account_name=example_account.name,\n throughput=400)\n example_sql_container = azure.cosmosdb.SqlContainer("exampleSqlContainer",\n resource_group_name=azurerm_cosmosdb_account["example"]["resource_group_name"],\n account_name=azurerm_cosmosdb_account["example"]["name"],\n database_name=example_sql_database.name,\n partition_key_path="/id")\n example_sql_stored_procedure = azure.cosmosdb.SqlStoredProcedure("exampleSqlStoredProcedure",\n resource_group_name=azurerm_cosmosdb_account["example"]["resource_group_name"],\n account_name=azurerm_cosmosdb_account["example"]["name"],\n database_name=example_sql_database.name,\n container_name=example_sql_container.name,\n body=" \tfunction () { var context = getContext(); var response = context.getResponse(); response.setBody(\'Hello, World\'); }\n")\n ```\n\n ## Import\n\n CosmosDB SQL Stored Procedures can be imported using the `resource id`, e.g.\n\n ```sh\n $ pulumi import azure:cosmosdb/sqlStoredProcedure:SqlStoredProcedure db1 /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg1/providers/Microsoft.DocumentDB/databaseAccounts/account1/sqlDatabases/db1/containers/c1/storedProcedures/sp1\n ```\n\n :param str resource_name: The name of the resource.\n :param SqlStoredProcedureArgs args: The arguments to use to populate this resource\'s properties.\n :param pulumi.ResourceOptions opts: Options for the resource.\n '
... | @overload
def __init__(__self__, resource_name: str, args: SqlStoredProcedureArgs, opts: Optional[pulumi.ResourceOptions]=None):
'\n Manages a SQL Stored Procedure within a Cosmos DB Account SQL Database.\n\n ## Example Usage\n\n ```python\n import pulumi\n import pulumi_azure as azure\n\n example_account = azure.cosmosdb.get_account(name="tfex-cosmosdb-account",\n resource_group_name="tfex-cosmosdb-account-rg")\n example_sql_database = azure.cosmosdb.SqlDatabase("exampleSqlDatabase",\n resource_group_name=example_account.resource_group_name,\n account_name=example_account.name,\n throughput=400)\n example_sql_container = azure.cosmosdb.SqlContainer("exampleSqlContainer",\n resource_group_name=azurerm_cosmosdb_account["example"]["resource_group_name"],\n account_name=azurerm_cosmosdb_account["example"]["name"],\n database_name=example_sql_database.name,\n partition_key_path="/id")\n example_sql_stored_procedure = azure.cosmosdb.SqlStoredProcedure("exampleSqlStoredProcedure",\n resource_group_name=azurerm_cosmosdb_account["example"]["resource_group_name"],\n account_name=azurerm_cosmosdb_account["example"]["name"],\n database_name=example_sql_database.name,\n container_name=example_sql_container.name,\n body=" \tfunction () { var context = getContext(); var response = context.getResponse(); response.setBody(\'Hello, World\'); }\n")\n ```\n\n ## Import\n\n CosmosDB SQL Stored Procedures can be imported using the `resource id`, e.g.\n\n ```sh\n $ pulumi import azure:cosmosdb/sqlStoredProcedure:SqlStoredProcedure db1 /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg1/providers/Microsoft.DocumentDB/databaseAccounts/account1/sqlDatabases/db1/containers/c1/storedProcedures/sp1\n ```\n\n :param str resource_name: The name of the resource.\n :param SqlStoredProcedureArgs args: The arguments to use to populate this resource\'s properties.\n :param pulumi.ResourceOptions opts: Options for the resource.\n '
...<|docstring|>Manages a SQL Stored Procedure within a Cosmos DB Account SQL Database.
## Example Usage
```python
import pulumi
import pulumi_azure as azure
example_account = azure.cosmosdb.get_account(name="tfex-cosmosdb-account",
resource_group_name="tfex-cosmosdb-account-rg")
example_sql_database = azure.cosmosdb.SqlDatabase("exampleSqlDatabase",
resource_group_name=example_account.resource_group_name,
account_name=example_account.name,
throughput=400)
example_sql_container = azure.cosmosdb.SqlContainer("exampleSqlContainer",
resource_group_name=azurerm_cosmosdb_account["example"]["resource_group_name"],
account_name=azurerm_cosmosdb_account["example"]["name"],
database_name=example_sql_database.name,
partition_key_path="/id")
example_sql_stored_procedure = azure.cosmosdb.SqlStoredProcedure("exampleSqlStoredProcedure",
resource_group_name=azurerm_cosmosdb_account["example"]["resource_group_name"],
account_name=azurerm_cosmosdb_account["example"]["name"],
database_name=example_sql_database.name,
container_name=example_sql_container.name,
body=" function () { var context = getContext(); var response = context.getResponse(); response.setBody('Hello, World'); }
")
```
## Import
CosmosDB SQL Stored Procedures can be imported using the `resource id`, e.g.
```sh
$ pulumi import azure:cosmosdb/sqlStoredProcedure:SqlStoredProcedure db1 /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg1/providers/Microsoft.DocumentDB/databaseAccounts/account1/sqlDatabases/db1/containers/c1/storedProcedures/sp1
```
:param str resource_name: The name of the resource.
:param SqlStoredProcedureArgs args: The arguments to use to populate this resource's properties.
:param pulumi.ResourceOptions opts: Options for the resource.<|endoftext|> |
f131f73657d4d8a832f0479f33c124aa4cf1cd6afe358a7fc705bf8faeae0483 | @staticmethod
def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions]=None, account_name: Optional[pulumi.Input[str]]=None, body: Optional[pulumi.Input[str]]=None, container_name: Optional[pulumi.Input[str]]=None, database_name: Optional[pulumi.Input[str]]=None, name: Optional[pulumi.Input[str]]=None, resource_group_name: Optional[pulumi.Input[str]]=None) -> 'SqlStoredProcedure':
"\n Get an existing SqlStoredProcedure resource's state with the given name, id, and optional extra\n properties used to qualify the lookup.\n\n :param str resource_name: The unique name of the resulting resource.\n :param pulumi.Input[str] id: The unique provider ID of the resource to lookup.\n :param pulumi.ResourceOptions opts: Options for the resource.\n :param pulumi.Input[str] account_name: The name of the Cosmos DB Account to create the stored procedure within. Changing this forces a new resource to be created.\n :param pulumi.Input[str] body: The body of the stored procedure.\n :param pulumi.Input[str] container_name: The name of the Cosmos DB SQL Container to create the stored procedure within. Changing this forces a new resource to be created.\n :param pulumi.Input[str] database_name: The name of the Cosmos DB SQL Database to create the stored procedure within. Changing this forces a new resource to be created.\n :param pulumi.Input[str] name: Specifies the name of the Cosmos DB SQL Stored Procedure. Changing this forces a new resource to be created.\n :param pulumi.Input[str] resource_group_name: The name of the resource group in which the Cosmos DB SQL Database is created. Changing this forces a new resource to be created.\n "
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = _SqlStoredProcedureState.__new__(_SqlStoredProcedureState)
__props__.__dict__['account_name'] = account_name
__props__.__dict__['body'] = body
__props__.__dict__['container_name'] = container_name
__props__.__dict__['database_name'] = database_name
__props__.__dict__['name'] = name
__props__.__dict__['resource_group_name'] = resource_group_name
return SqlStoredProcedure(resource_name, opts=opts, __props__=__props__) | Get an existing SqlStoredProcedure resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param pulumi.Input[str] id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[str] account_name: The name of the Cosmos DB Account to create the stored procedure within. Changing this forces a new resource to be created.
:param pulumi.Input[str] body: The body of the stored procedure.
:param pulumi.Input[str] container_name: The name of the Cosmos DB SQL Container to create the stored procedure within. Changing this forces a new resource to be created.
:param pulumi.Input[str] database_name: The name of the Cosmos DB SQL Database to create the stored procedure within. Changing this forces a new resource to be created.
:param pulumi.Input[str] name: Specifies the name of the Cosmos DB SQL Stored Procedure. Changing this forces a new resource to be created.
:param pulumi.Input[str] resource_group_name: The name of the resource group in which the Cosmos DB SQL Database is created. Changing this forces a new resource to be created. | sdk/python/pulumi_azure/cosmosdb/sql_stored_procedure.py | get | henriktao/pulumi-azure | 109 | python | @staticmethod
def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions]=None, account_name: Optional[pulumi.Input[str]]=None, body: Optional[pulumi.Input[str]]=None, container_name: Optional[pulumi.Input[str]]=None, database_name: Optional[pulumi.Input[str]]=None, name: Optional[pulumi.Input[str]]=None, resource_group_name: Optional[pulumi.Input[str]]=None) -> 'SqlStoredProcedure':
"\n Get an existing SqlStoredProcedure resource's state with the given name, id, and optional extra\n properties used to qualify the lookup.\n\n :param str resource_name: The unique name of the resulting resource.\n :param pulumi.Input[str] id: The unique provider ID of the resource to lookup.\n :param pulumi.ResourceOptions opts: Options for the resource.\n :param pulumi.Input[str] account_name: The name of the Cosmos DB Account to create the stored procedure within. Changing this forces a new resource to be created.\n :param pulumi.Input[str] body: The body of the stored procedure.\n :param pulumi.Input[str] container_name: The name of the Cosmos DB SQL Container to create the stored procedure within. Changing this forces a new resource to be created.\n :param pulumi.Input[str] database_name: The name of the Cosmos DB SQL Database to create the stored procedure within. Changing this forces a new resource to be created.\n :param pulumi.Input[str] name: Specifies the name of the Cosmos DB SQL Stored Procedure. Changing this forces a new resource to be created.\n :param pulumi.Input[str] resource_group_name: The name of the resource group in which the Cosmos DB SQL Database is created. Changing this forces a new resource to be created.\n "
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = _SqlStoredProcedureState.__new__(_SqlStoredProcedureState)
__props__.__dict__['account_name'] = account_name
__props__.__dict__['body'] = body
__props__.__dict__['container_name'] = container_name
__props__.__dict__['database_name'] = database_name
__props__.__dict__['name'] = name
__props__.__dict__['resource_group_name'] = resource_group_name
return SqlStoredProcedure(resource_name, opts=opts, __props__=__props__) | @staticmethod
def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions]=None, account_name: Optional[pulumi.Input[str]]=None, body: Optional[pulumi.Input[str]]=None, container_name: Optional[pulumi.Input[str]]=None, database_name: Optional[pulumi.Input[str]]=None, name: Optional[pulumi.Input[str]]=None, resource_group_name: Optional[pulumi.Input[str]]=None) -> 'SqlStoredProcedure':
"\n Get an existing SqlStoredProcedure resource's state with the given name, id, and optional extra\n properties used to qualify the lookup.\n\n :param str resource_name: The unique name of the resulting resource.\n :param pulumi.Input[str] id: The unique provider ID of the resource to lookup.\n :param pulumi.ResourceOptions opts: Options for the resource.\n :param pulumi.Input[str] account_name: The name of the Cosmos DB Account to create the stored procedure within. Changing this forces a new resource to be created.\n :param pulumi.Input[str] body: The body of the stored procedure.\n :param pulumi.Input[str] container_name: The name of the Cosmos DB SQL Container to create the stored procedure within. Changing this forces a new resource to be created.\n :param pulumi.Input[str] database_name: The name of the Cosmos DB SQL Database to create the stored procedure within. Changing this forces a new resource to be created.\n :param pulumi.Input[str] name: Specifies the name of the Cosmos DB SQL Stored Procedure. Changing this forces a new resource to be created.\n :param pulumi.Input[str] resource_group_name: The name of the resource group in which the Cosmos DB SQL Database is created. Changing this forces a new resource to be created.\n "
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = _SqlStoredProcedureState.__new__(_SqlStoredProcedureState)
__props__.__dict__['account_name'] = account_name
__props__.__dict__['body'] = body
__props__.__dict__['container_name'] = container_name
__props__.__dict__['database_name'] = database_name
__props__.__dict__['name'] = name
__props__.__dict__['resource_group_name'] = resource_group_name
return SqlStoredProcedure(resource_name, opts=opts, __props__=__props__)<|docstring|>Get an existing SqlStoredProcedure resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param pulumi.Input[str] id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[str] account_name: The name of the Cosmos DB Account to create the stored procedure within. Changing this forces a new resource to be created.
:param pulumi.Input[str] body: The body of the stored procedure.
:param pulumi.Input[str] container_name: The name of the Cosmos DB SQL Container to create the stored procedure within. Changing this forces a new resource to be created.
:param pulumi.Input[str] database_name: The name of the Cosmos DB SQL Database to create the stored procedure within. Changing this forces a new resource to be created.
:param pulumi.Input[str] name: Specifies the name of the Cosmos DB SQL Stored Procedure. Changing this forces a new resource to be created.
:param pulumi.Input[str] resource_group_name: The name of the resource group in which the Cosmos DB SQL Database is created. Changing this forces a new resource to be created.<|endoftext|> |
99c3dcc26b07175131d55b74293c63071da520550ddd2c671aa82f9b7a8e7da1 | @property
@pulumi.getter(name='accountName')
def account_name(self) -> pulumi.Output[str]:
'\n The name of the Cosmos DB Account to create the stored procedure within. Changing this forces a new resource to be created.\n '
return pulumi.get(self, 'account_name') | The name of the Cosmos DB Account to create the stored procedure within. Changing this forces a new resource to be created. | sdk/python/pulumi_azure/cosmosdb/sql_stored_procedure.py | account_name | henriktao/pulumi-azure | 109 | python | @property
@pulumi.getter(name='accountName')
def account_name(self) -> pulumi.Output[str]:
'\n \n '
return pulumi.get(self, 'account_name') | @property
@pulumi.getter(name='accountName')
def account_name(self) -> pulumi.Output[str]:
'\n \n '
return pulumi.get(self, 'account_name')<|docstring|>The name of the Cosmos DB Account to create the stored procedure within. Changing this forces a new resource to be created.<|endoftext|> |
e5be7545c79eb3f6d89c205c0f4e735b40319c6a900b53fbae460613cbc29c97 | @property
@pulumi.getter
def body(self) -> pulumi.Output[str]:
'\n The body of the stored procedure.\n '
return pulumi.get(self, 'body') | The body of the stored procedure. | sdk/python/pulumi_azure/cosmosdb/sql_stored_procedure.py | body | henriktao/pulumi-azure | 109 | python | @property
@pulumi.getter
def body(self) -> pulumi.Output[str]:
'\n \n '
return pulumi.get(self, 'body') | @property
@pulumi.getter
def body(self) -> pulumi.Output[str]:
'\n \n '
return pulumi.get(self, 'body')<|docstring|>The body of the stored procedure.<|endoftext|> |
8603acab5da67626a50d5b12c33ba7b204dffeee6aa92649e8dc2371b9258f4b | @property
@pulumi.getter(name='containerName')
def container_name(self) -> pulumi.Output[str]:
'\n The name of the Cosmos DB SQL Container to create the stored procedure within. Changing this forces a new resource to be created.\n '
return pulumi.get(self, 'container_name') | The name of the Cosmos DB SQL Container to create the stored procedure within. Changing this forces a new resource to be created. | sdk/python/pulumi_azure/cosmosdb/sql_stored_procedure.py | container_name | henriktao/pulumi-azure | 109 | python | @property
@pulumi.getter(name='containerName')
def container_name(self) -> pulumi.Output[str]:
'\n \n '
return pulumi.get(self, 'container_name') | @property
@pulumi.getter(name='containerName')
def container_name(self) -> pulumi.Output[str]:
'\n \n '
return pulumi.get(self, 'container_name')<|docstring|>The name of the Cosmos DB SQL Container to create the stored procedure within. Changing this forces a new resource to be created.<|endoftext|> |
aabbd7f8474a215d0809ca633b55fa5bf522bb038245525d5c25452d13de1cfd | @property
@pulumi.getter(name='databaseName')
def database_name(self) -> pulumi.Output[str]:
'\n The name of the Cosmos DB SQL Database to create the stored procedure within. Changing this forces a new resource to be created.\n '
return pulumi.get(self, 'database_name') | The name of the Cosmos DB SQL Database to create the stored procedure within. Changing this forces a new resource to be created. | sdk/python/pulumi_azure/cosmosdb/sql_stored_procedure.py | database_name | henriktao/pulumi-azure | 109 | python | @property
@pulumi.getter(name='databaseName')
def database_name(self) -> pulumi.Output[str]:
'\n \n '
return pulumi.get(self, 'database_name') | @property
@pulumi.getter(name='databaseName')
def database_name(self) -> pulumi.Output[str]:
'\n \n '
return pulumi.get(self, 'database_name')<|docstring|>The name of the Cosmos DB SQL Database to create the stored procedure within. Changing this forces a new resource to be created.<|endoftext|> |
866058a95c8b6652968ab02a29786b6e1c348da5da9146196f9388aa6d063c6e | @property
@pulumi.getter
def name(self) -> pulumi.Output[str]:
'\n Specifies the name of the Cosmos DB SQL Stored Procedure. Changing this forces a new resource to be created.\n '
return pulumi.get(self, 'name') | Specifies the name of the Cosmos DB SQL Stored Procedure. Changing this forces a new resource to be created. | sdk/python/pulumi_azure/cosmosdb/sql_stored_procedure.py | name | henriktao/pulumi-azure | 109 | python | @property
@pulumi.getter
def name(self) -> pulumi.Output[str]:
'\n \n '
return pulumi.get(self, 'name') | @property
@pulumi.getter
def name(self) -> pulumi.Output[str]:
'\n \n '
return pulumi.get(self, 'name')<|docstring|>Specifies the name of the Cosmos DB SQL Stored Procedure. Changing this forces a new resource to be created.<|endoftext|> |
069b8e35510e2d944ae2fdc1fde6441b471c01ae6206fa60294afe76a9879c60 | @property
@pulumi.getter(name='resourceGroupName')
def resource_group_name(self) -> pulumi.Output[str]:
'\n The name of the resource group in which the Cosmos DB SQL Database is created. Changing this forces a new resource to be created.\n '
return pulumi.get(self, 'resource_group_name') | The name of the resource group in which the Cosmos DB SQL Database is created. Changing this forces a new resource to be created. | sdk/python/pulumi_azure/cosmosdb/sql_stored_procedure.py | resource_group_name | henriktao/pulumi-azure | 109 | python | @property
@pulumi.getter(name='resourceGroupName')
def resource_group_name(self) -> pulumi.Output[str]:
'\n \n '
return pulumi.get(self, 'resource_group_name') | @property
@pulumi.getter(name='resourceGroupName')
def resource_group_name(self) -> pulumi.Output[str]:
'\n \n '
return pulumi.get(self, 'resource_group_name')<|docstring|>The name of the resource group in which the Cosmos DB SQL Database is created. Changing this forces a new resource to be created.<|endoftext|> |
085e6621ff57c39b91689a53ea5acbdf6bcabcdea773e198f89383847c6b3bc3 | @staticmethod
def _validate_sample_fname(name):
'\n format name of sample data passed to function, accepts a named string\n argument and parses it to determine the sample data name, what type of\n extension it has, or other relevant information.\n\n Returns\n -------\n fileext : str\n The name of the sample data, with the file extension\n example: "IsolatedGalaxy.tar.gz"\n basename : str\n The name of the sample data, without the file extension\n example: "IsolatedGalaxy"\n extension : str\n name of extension of remote sample data\n example: "h5" or "tar"\n '
if (not isinstance(name, str)):
mylog.error('The argument %s passed to load_sample() is not a string.', name)
(base, ext) = os.path.splitext(name)
if (ext == ''):
fileext = f'{name}.tar.gz'
basename = name
extension = 'tar'
elif (ext == '.gz'):
fileext = name
basename = os.path.splitext(base)[0]
extension = 'tar'
elif (ext in ['.h5', '.hdf5']):
fileext = name
basename = base
extension = 'h5'
else:
mylog.info('extension of %s for dataset %s is unexpected. the `load_data`\n function may not work as expected', ext, name)
extension = ext
fileext = name
basename = base
return (fileext, basename, extension) | format name of sample data passed to function, accepts a named string
argument and parses it to determine the sample data name, what type of
extension it has, or other relevant information.
Returns
-------
fileext : str
The name of the sample data, with the file extension
example: "IsolatedGalaxy.tar.gz"
basename : str
The name of the sample data, without the file extension
example: "IsolatedGalaxy"
extension : str
name of extension of remote sample data
example: "h5" or "tar" | yt/utilities/sample_data.py | _validate_sample_fname | data-exp-lab/yt | 1 | python | @staticmethod
def _validate_sample_fname(name):
'\n format name of sample data passed to function, accepts a named string\n argument and parses it to determine the sample data name, what type of\n extension it has, or other relevant information.\n\n Returns\n -------\n fileext : str\n The name of the sample data, with the file extension\n example: "IsolatedGalaxy.tar.gz"\n basename : str\n The name of the sample data, without the file extension\n example: "IsolatedGalaxy"\n extension : str\n name of extension of remote sample data\n example: "h5" or "tar"\n '
if (not isinstance(name, str)):
mylog.error('The argument %s passed to load_sample() is not a string.', name)
(base, ext) = os.path.splitext(name)
if (ext == ):
fileext = f'{name}.tar.gz'
basename = name
extension = 'tar'
elif (ext == '.gz'):
fileext = name
basename = os.path.splitext(base)[0]
extension = 'tar'
elif (ext in ['.h5', '.hdf5']):
fileext = name
basename = base
extension = 'h5'
else:
mylog.info('extension of %s for dataset %s is unexpected. the `load_data`\n function may not work as expected', ext, name)
extension = ext
fileext = name
basename = base
return (fileext, basename, extension) | @staticmethod
def _validate_sample_fname(name):
'\n format name of sample data passed to function, accepts a named string\n argument and parses it to determine the sample data name, what type of\n extension it has, or other relevant information.\n\n Returns\n -------\n fileext : str\n The name of the sample data, with the file extension\n example: "IsolatedGalaxy.tar.gz"\n basename : str\n The name of the sample data, without the file extension\n example: "IsolatedGalaxy"\n extension : str\n name of extension of remote sample data\n example: "h5" or "tar"\n '
if (not isinstance(name, str)):
mylog.error('The argument %s passed to load_sample() is not a string.', name)
(base, ext) = os.path.splitext(name)
if (ext == ):
fileext = f'{name}.tar.gz'
basename = name
extension = 'tar'
elif (ext == '.gz'):
fileext = name
basename = os.path.splitext(base)[0]
extension = 'tar'
elif (ext in ['.h5', '.hdf5']):
fileext = name
basename = base
extension = 'h5'
else:
mylog.info('extension of %s for dataset %s is unexpected. the `load_data`\n function may not work as expected', ext, name)
extension = ext
fileext = name
basename = base
return (fileext, basename, extension)<|docstring|>format name of sample data passed to function, accepts a named string
argument and parses it to determine the sample data name, what type of
extension it has, or other relevant information.
Returns
-------
fileext : str
The name of the sample data, with the file extension
example: "IsolatedGalaxy.tar.gz"
basename : str
The name of the sample data, without the file extension
example: "IsolatedGalaxy"
extension : str
name of extension of remote sample data
example: "h5" or "tar"<|endoftext|> |
66ac017ace6a0d05bba933140c0a4032077c2771da192aeb2e467ea854717574 | def get_water_data(water_type, count=1, keep_valid_decimals=None):
'\n 返回该类型数据的最近统计数据的高斯分布数据\n :param water_type:水质数据类型\n :param count: 数量\n :param keep_valid_decimals 保留有效位数,如果不手动输入则按照默认值\n :return: 返回样式[30.648319731147538, 42.35755219891315]\n '
arr_mean = np.nanmean(water_data_dict[water_type]['data'])
arr_var = np.nanvar(water_data_dict[water_type]['data'])
return_list = []
for i in range(count):
d = (- 1000)
while ((d < water_data_dict[water_type]['min_data']) or (d > water_data_dict[water_type]['max_data'])):
d = np.random.normal(arr_mean, arr_var, 1)[0]
if keep_valid_decimals:
d = round(d, keep_valid_decimals)
else:
d = round(d, water_data_dict[water_type]['keep_valid_decimals'])
return_list.append(d)
return return_list | 返回该类型数据的最近统计数据的高斯分布数据
:param water_type:水质数据类型
:param count: 数量
:param keep_valid_decimals 保留有效位数,如果不手动输入则按照默认值
:return: 返回样式[30.648319731147538, 42.35755219891315] | utils/data_valid.py | get_water_data | ndkjing/usv | 0 | python | def get_water_data(water_type, count=1, keep_valid_decimals=None):
'\n 返回该类型数据的最近统计数据的高斯分布数据\n :param water_type:水质数据类型\n :param count: 数量\n :param keep_valid_decimals 保留有效位数,如果不手动输入则按照默认值\n :return: 返回样式[30.648319731147538, 42.35755219891315]\n '
arr_mean = np.nanmean(water_data_dict[water_type]['data'])
arr_var = np.nanvar(water_data_dict[water_type]['data'])
return_list = []
for i in range(count):
d = (- 1000)
while ((d < water_data_dict[water_type]['min_data']) or (d > water_data_dict[water_type]['max_data'])):
d = np.random.normal(arr_mean, arr_var, 1)[0]
if keep_valid_decimals:
d = round(d, keep_valid_decimals)
else:
d = round(d, water_data_dict[water_type]['keep_valid_decimals'])
return_list.append(d)
return return_list | def get_water_data(water_type, count=1, keep_valid_decimals=None):
'\n 返回该类型数据的最近统计数据的高斯分布数据\n :param water_type:水质数据类型\n :param count: 数量\n :param keep_valid_decimals 保留有效位数,如果不手动输入则按照默认值\n :return: 返回样式[30.648319731147538, 42.35755219891315]\n '
arr_mean = np.nanmean(water_data_dict[water_type]['data'])
arr_var = np.nanvar(water_data_dict[water_type]['data'])
return_list = []
for i in range(count):
d = (- 1000)
while ((d < water_data_dict[water_type]['min_data']) or (d > water_data_dict[water_type]['max_data'])):
d = np.random.normal(arr_mean, arr_var, 1)[0]
if keep_valid_decimals:
d = round(d, keep_valid_decimals)
else:
d = round(d, water_data_dict[water_type]['keep_valid_decimals'])
return_list.append(d)
return return_list<|docstring|>返回该类型数据的最近统计数据的高斯分布数据
:param water_type:水质数据类型
:param count: 数量
:param keep_valid_decimals 保留有效位数,如果不手动输入则按照默认值
:return: 返回样式[30.648319731147538, 42.35755219891315]<|endoftext|> |
cfa29680eb816eb1dc155c9141352e96ca047c2c9507002e973df97876e35f98 | def valid_water_data(water_type, data, keep_valid_decimals=None):
'\n 验证数据是否是合法值\n :param water_type: 水质数据类型\n :param data: 数据,浮点数\n :param keep_valid_decimals: 保留有效小数位数\n :return: 如果数据符合要求则返回原始数据,如果不符合要求范围则生成该数据\n '
if (water_data_dict[water_type]['min_data'] < data < water_data_dict[water_type]['max_data']):
return data
else:
arr_mean = np.nanmean(water_data_dict[water_type]['data'])
arr_var = np.nanvar(water_data_dict[water_type]['data'])
d = (- 1000)
while ((d < water_data_dict[water_type]['min_data']) or (d > water_data_dict[water_type]['max_data'])):
d = np.random.normal(arr_mean, arr_var, 1)[0]
if keep_valid_decimals:
d = round(d, keep_valid_decimals)
else:
d = round(d, water_data_dict[water_type]['keep_valid_decimals'])
return d | 验证数据是否是合法值
:param water_type: 水质数据类型
:param data: 数据,浮点数
:param keep_valid_decimals: 保留有效小数位数
:return: 如果数据符合要求则返回原始数据,如果不符合要求范围则生成该数据 | utils/data_valid.py | valid_water_data | ndkjing/usv | 0 | python | def valid_water_data(water_type, data, keep_valid_decimals=None):
'\n 验证数据是否是合法值\n :param water_type: 水质数据类型\n :param data: 数据,浮点数\n :param keep_valid_decimals: 保留有效小数位数\n :return: 如果数据符合要求则返回原始数据,如果不符合要求范围则生成该数据\n '
if (water_data_dict[water_type]['min_data'] < data < water_data_dict[water_type]['max_data']):
return data
else:
arr_mean = np.nanmean(water_data_dict[water_type]['data'])
arr_var = np.nanvar(water_data_dict[water_type]['data'])
d = (- 1000)
while ((d < water_data_dict[water_type]['min_data']) or (d > water_data_dict[water_type]['max_data'])):
d = np.random.normal(arr_mean, arr_var, 1)[0]
if keep_valid_decimals:
d = round(d, keep_valid_decimals)
else:
d = round(d, water_data_dict[water_type]['keep_valid_decimals'])
return d | def valid_water_data(water_type, data, keep_valid_decimals=None):
'\n 验证数据是否是合法值\n :param water_type: 水质数据类型\n :param data: 数据,浮点数\n :param keep_valid_decimals: 保留有效小数位数\n :return: 如果数据符合要求则返回原始数据,如果不符合要求范围则生成该数据\n '
if (water_data_dict[water_type]['min_data'] < data < water_data_dict[water_type]['max_data']):
return data
else:
arr_mean = np.nanmean(water_data_dict[water_type]['data'])
arr_var = np.nanvar(water_data_dict[water_type]['data'])
d = (- 1000)
while ((d < water_data_dict[water_type]['min_data']) or (d > water_data_dict[water_type]['max_data'])):
d = np.random.normal(arr_mean, arr_var, 1)[0]
if keep_valid_decimals:
d = round(d, keep_valid_decimals)
else:
d = round(d, water_data_dict[water_type]['keep_valid_decimals'])
return d<|docstring|>验证数据是否是合法值
:param water_type: 水质数据类型
:param data: 数据,浮点数
:param keep_valid_decimals: 保留有效小数位数
:return: 如果数据符合要求则返回原始数据,如果不符合要求范围则生成该数据<|endoftext|> |
39cd3b3c5a8dcd346b0f854bb503667e7a125e1f97510037550e7dcd984016e0 | @pytest.fixture
def response():
'Sample pytest fixture.\n\n See more at: http://doc.pytest.org/en/latest/fixture.html\n ' | Sample pytest fixture.
See more at: http://doc.pytest.org/en/latest/fixture.html | tests/test_port_checker.py | response | virogenesis/port_checker | 0 | python | @pytest.fixture
def response():
'Sample pytest fixture.\n\n See more at: http://doc.pytest.org/en/latest/fixture.html\n ' | @pytest.fixture
def response():
'Sample pytest fixture.\n\n See more at: http://doc.pytest.org/en/latest/fixture.html\n '<|docstring|>Sample pytest fixture.
See more at: http://doc.pytest.org/en/latest/fixture.html<|endoftext|> |
57d1077697496419ef3e17274ea12080618184034e5c5256c29cff02162972f7 | def test_content(response):
'Sample pytest test function with the pytest fixture as an argument.' | Sample pytest test function with the pytest fixture as an argument. | tests/test_port_checker.py | test_content | virogenesis/port_checker | 0 | python | def test_content(response):
| def test_content(response):
<|docstring|>Sample pytest test function with the pytest fixture as an argument.<|endoftext|> |
e105ee4e957b897ca5663772ed5ac5ec3dc3a2fc765b3ffb351dd99df40cf026 | def test_command_line_interface():
'Test the CLI.'
runner = CliRunner()
result = runner.invoke(cli.main)
assert (result.exit_code == 0)
assert ('port_checker.cli.main' in result.output)
help_result = runner.invoke(cli.main, ['--help'])
assert (help_result.exit_code == 0)
assert ('--help Show this message and exit.' in help_result.output) | Test the CLI. | tests/test_port_checker.py | test_command_line_interface | virogenesis/port_checker | 0 | python | def test_command_line_interface():
runner = CliRunner()
result = runner.invoke(cli.main)
assert (result.exit_code == 0)
assert ('port_checker.cli.main' in result.output)
help_result = runner.invoke(cli.main, ['--help'])
assert (help_result.exit_code == 0)
assert ('--help Show this message and exit.' in help_result.output) | def test_command_line_interface():
runner = CliRunner()
result = runner.invoke(cli.main)
assert (result.exit_code == 0)
assert ('port_checker.cli.main' in result.output)
help_result = runner.invoke(cli.main, ['--help'])
assert (help_result.exit_code == 0)
assert ('--help Show this message and exit.' in help_result.output)<|docstring|>Test the CLI.<|endoftext|> |
d79bcfa2855524151da3a9a2216622a7f0fb8aafc43e271b2a216d401984e6f6 | def test_ingredients(capsys):
'We use the capsys argument to capture printing to stdout.'
assert (port_checker.ingredients(10) == None)
captured = capsys.readouterr()
assert ('1.0 cups arepa flour' in captured.out)
assert ('1.0 cups cheese' in captured.out)
assert ('0.25 cups water' in captured.out) | We use the capsys argument to capture printing to stdout. | tests/test_port_checker.py | test_ingredients | virogenesis/port_checker | 0 | python | def test_ingredients(capsys):
assert (port_checker.ingredients(10) == None)
captured = capsys.readouterr()
assert ('1.0 cups arepa flour' in captured.out)
assert ('1.0 cups cheese' in captured.out)
assert ('0.25 cups water' in captured.out) | def test_ingredients(capsys):
assert (port_checker.ingredients(10) == None)
captured = capsys.readouterr()
assert ('1.0 cups arepa flour' in captured.out)
assert ('1.0 cups cheese' in captured.out)
assert ('0.25 cups water' in captured.out)<|docstring|>We use the capsys argument to capture printing to stdout.<|endoftext|> |
79a6956f58f20afa7d05b7fd97457dc73cf3d683931438f5e58925ad26539317 | def __init__(self, feature_detector, verbose=False, training_opt={}, algorithm='lbfgs'):
"\n Initialize the CRFSuite tagger\n :param feature_detector: The function that extracts features for each token of a sentence. This function should take\n 2 parameters: tokens and index which extract features at index position from tokens list. See the build in\n _get_features function for more detail.\n :param verbose: output the debugging messages during training.\n :type verbose: boolean\n :param training_opt: python-crfsuite training options\n :type training_opt : dictionary\n\n Set of possible training options (using LBFGS training algorithm).\n 'feature.minfreq' : The minimum frequency of features.\n 'feature.possible_states' : Force to generate possible state features.\n 'feature.possible_transitions' : Force to generate possible transition features.\n 'c1' : Coefficient for L1 regularization.\n 'c2' : Coefficient for L2 regularization.\n 'max_iterations' : The maximum number of iterations for L-BFGS optimization.\n 'num_memories' : The number of limited memories for approximating the inverse hessian matrix.\n 'epsilon' : Epsilon for testing the convergence of the objective.\n 'period' : The duration of iterations to test the stopping criterion.\n 'delta' : The threshold for the stopping criterion; an L-BFGS iteration stops when the\n improvement of the log likelihood over the last ${period} iterations is no greater than this threshold.\n 'linesearch' : The line search algorithm used in L-BFGS updates:\n { 'MoreThuente': More and Thuente's method,\n 'Backtracking': Backtracking method with regular Wolfe condition,\n 'StrongBacktracking': Backtracking method with strong Wolfe condition\n }\n 'max_linesearch' : The maximum number of trials for the line search algorithm.\n\n "
self._model_file = ''
self._tagger = pycrfsuite.Tagger()
self._feature_func = self._featfun_to_listfun(feature_detector)
self._verbose = verbose
self._training_options = training_opt
self._pattern = re.compile('\\d')
self._algorithm = algorithm | Initialize the CRFSuite tagger
:param feature_detector: The function that extracts features for each token of a sentence. This function should take
2 parameters: tokens and index which extract features at index position from tokens list. See the build in
_get_features function for more detail.
:param verbose: output the debugging messages during training.
:type verbose: boolean
:param training_opt: python-crfsuite training options
:type training_opt : dictionary
Set of possible training options (using LBFGS training algorithm).
'feature.minfreq' : The minimum frequency of features.
'feature.possible_states' : Force to generate possible state features.
'feature.possible_transitions' : Force to generate possible transition features.
'c1' : Coefficient for L1 regularization.
'c2' : Coefficient for L2 regularization.
'max_iterations' : The maximum number of iterations for L-BFGS optimization.
'num_memories' : The number of limited memories for approximating the inverse hessian matrix.
'epsilon' : Epsilon for testing the convergence of the objective.
'period' : The duration of iterations to test the stopping criterion.
'delta' : The threshold for the stopping criterion; an L-BFGS iteration stops when the
improvement of the log likelihood over the last ${period} iterations is no greater than this threshold.
'linesearch' : The line search algorithm used in L-BFGS updates:
{ 'MoreThuente': More and Thuente's method,
'Backtracking': Backtracking method with regular Wolfe condition,
'StrongBacktracking': Backtracking method with strong Wolfe condition
}
'max_linesearch' : The maximum number of trials for the line search algorithm. | src/classifiers/crf.py | __init__ | ciads-ut/transfer-learning-ner | 39 | python | def __init__(self, feature_detector, verbose=False, training_opt={}, algorithm='lbfgs'):
"\n Initialize the CRFSuite tagger\n :param feature_detector: The function that extracts features for each token of a sentence. This function should take\n 2 parameters: tokens and index which extract features at index position from tokens list. See the build in\n _get_features function for more detail.\n :param verbose: output the debugging messages during training.\n :type verbose: boolean\n :param training_opt: python-crfsuite training options\n :type training_opt : dictionary\n\n Set of possible training options (using LBFGS training algorithm).\n 'feature.minfreq' : The minimum frequency of features.\n 'feature.possible_states' : Force to generate possible state features.\n 'feature.possible_transitions' : Force to generate possible transition features.\n 'c1' : Coefficient for L1 regularization.\n 'c2' : Coefficient for L2 regularization.\n 'max_iterations' : The maximum number of iterations for L-BFGS optimization.\n 'num_memories' : The number of limited memories for approximating the inverse hessian matrix.\n 'epsilon' : Epsilon for testing the convergence of the objective.\n 'period' : The duration of iterations to test the stopping criterion.\n 'delta' : The threshold for the stopping criterion; an L-BFGS iteration stops when the\n improvement of the log likelihood over the last ${period} iterations is no greater than this threshold.\n 'linesearch' : The line search algorithm used in L-BFGS updates:\n { 'MoreThuente': More and Thuente's method,\n 'Backtracking': Backtracking method with regular Wolfe condition,\n 'StrongBacktracking': Backtracking method with strong Wolfe condition\n }\n 'max_linesearch' : The maximum number of trials for the line search algorithm.\n\n "
self._model_file =
self._tagger = pycrfsuite.Tagger()
self._feature_func = self._featfun_to_listfun(feature_detector)
self._verbose = verbose
self._training_options = training_opt
self._pattern = re.compile('\\d')
self._algorithm = algorithm | def __init__(self, feature_detector, verbose=False, training_opt={}, algorithm='lbfgs'):
"\n Initialize the CRFSuite tagger\n :param feature_detector: The function that extracts features for each token of a sentence. This function should take\n 2 parameters: tokens and index which extract features at index position from tokens list. See the build in\n _get_features function for more detail.\n :param verbose: output the debugging messages during training.\n :type verbose: boolean\n :param training_opt: python-crfsuite training options\n :type training_opt : dictionary\n\n Set of possible training options (using LBFGS training algorithm).\n 'feature.minfreq' : The minimum frequency of features.\n 'feature.possible_states' : Force to generate possible state features.\n 'feature.possible_transitions' : Force to generate possible transition features.\n 'c1' : Coefficient for L1 regularization.\n 'c2' : Coefficient for L2 regularization.\n 'max_iterations' : The maximum number of iterations for L-BFGS optimization.\n 'num_memories' : The number of limited memories for approximating the inverse hessian matrix.\n 'epsilon' : Epsilon for testing the convergence of the objective.\n 'period' : The duration of iterations to test the stopping criterion.\n 'delta' : The threshold for the stopping criterion; an L-BFGS iteration stops when the\n improvement of the log likelihood over the last ${period} iterations is no greater than this threshold.\n 'linesearch' : The line search algorithm used in L-BFGS updates:\n { 'MoreThuente': More and Thuente's method,\n 'Backtracking': Backtracking method with regular Wolfe condition,\n 'StrongBacktracking': Backtracking method with strong Wolfe condition\n }\n 'max_linesearch' : The maximum number of trials for the line search algorithm.\n\n "
self._model_file =
self._tagger = pycrfsuite.Tagger()
self._feature_func = self._featfun_to_listfun(feature_detector)
self._verbose = verbose
self._training_options = training_opt
self._pattern = re.compile('\\d')
self._algorithm = algorithm<|docstring|>Initialize the CRFSuite tagger
:param feature_detector: The function that extracts features for each token of a sentence. This function should take
2 parameters: tokens and index which extract features at index position from tokens list. See the build in
_get_features function for more detail.
:param verbose: output the debugging messages during training.
:type verbose: boolean
:param training_opt: python-crfsuite training options
:type training_opt : dictionary
Set of possible training options (using LBFGS training algorithm).
'feature.minfreq' : The minimum frequency of features.
'feature.possible_states' : Force to generate possible state features.
'feature.possible_transitions' : Force to generate possible transition features.
'c1' : Coefficient for L1 regularization.
'c2' : Coefficient for L2 regularization.
'max_iterations' : The maximum number of iterations for L-BFGS optimization.
'num_memories' : The number of limited memories for approximating the inverse hessian matrix.
'epsilon' : Epsilon for testing the convergence of the objective.
'period' : The duration of iterations to test the stopping criterion.
'delta' : The threshold for the stopping criterion; an L-BFGS iteration stops when the
improvement of the log likelihood over the last ${period} iterations is no greater than this threshold.
'linesearch' : The line search algorithm used in L-BFGS updates:
{ 'MoreThuente': More and Thuente's method,
'Backtracking': Backtracking method with regular Wolfe condition,
'StrongBacktracking': Backtracking method with strong Wolfe condition
}
'max_linesearch' : The maximum number of trials for the line search algorithm.<|endoftext|> |
0b6f3db7b2f76731d48d8687761a99c83acc4485c3661f15fb5a9afdaa9730cb | def _featfun_to_listfun(self, feature_func):
' Convert the feature function (which returns a dict) to the form\n that is used by CRF, ie. a function that returs a list.'
def listfun(tokens, index, history):
features = feature_func(tokens, index, history)
featurelist = []
for (k, v) in features.items():
featurelist.append(((k + '_') + unicode(v)))
return featurelist
return listfun | Convert the feature function (which returns a dict) to the form
that is used by CRF, ie. a function that returs a list. | src/classifiers/crf.py | _featfun_to_listfun | ciads-ut/transfer-learning-ner | 39 | python | def _featfun_to_listfun(self, feature_func):
' Convert the feature function (which returns a dict) to the form\n that is used by CRF, ie. a function that returs a list.'
def listfun(tokens, index, history):
features = feature_func(tokens, index, history)
featurelist = []
for (k, v) in features.items():
featurelist.append(((k + '_') + unicode(v)))
return featurelist
return listfun | def _featfun_to_listfun(self, feature_func):
' Convert the feature function (which returns a dict) to the form\n that is used by CRF, ie. a function that returs a list.'
def listfun(tokens, index, history):
features = feature_func(tokens, index, history)
featurelist = []
for (k, v) in features.items():
featurelist.append(((k + '_') + unicode(v)))
return featurelist
return listfun<|docstring|>Convert the feature function (which returns a dict) to the form
that is used by CRF, ie. a function that returs a list.<|endoftext|> |
e94ffdbcd37b4b3d6545ce59809366f387f2659cd76aeae5bedf4de6557c9fa0 | def tag_sents(self, sents):
"\n Tag a list of sentences. NB before using this function, user should specify the mode_file either by\n - Train a new model using ``train'' function\n - Use the pre-trained model which is set via ``set_model_file'' function\n :params sentences : list of sentences needed to tag.\n :type sentences : list(list(str))\n :return : list of tagged sentences.\n :rtype : list (list (tuple(str,str)))\n "
history = []
if (self._model_file == ''):
raise Exception(' No model file is found !! Please use train or set_model_file function')
result = []
for tokens in sents:
features = [self._feature_func(tokens, i, history) for i in range(len(tokens))]
labels = self._tagger.tag(features)
if (len(labels) != len(tokens)):
raise Exception(' Predicted Length Not Matched, Expect Errors !')
tagged_sent = list(zip(tokens, labels))
result.append(tagged_sent)
return result | Tag a list of sentences. NB before using this function, user should specify the mode_file either by
- Train a new model using ``train'' function
- Use the pre-trained model which is set via ``set_model_file'' function
:params sentences : list of sentences needed to tag.
:type sentences : list(list(str))
:return : list of tagged sentences.
:rtype : list (list (tuple(str,str))) | src/classifiers/crf.py | tag_sents | ciads-ut/transfer-learning-ner | 39 | python | def tag_sents(self, sents):
"\n Tag a list of sentences. NB before using this function, user should specify the mode_file either by\n - Train a new model using ``train function\n - Use the pre-trained model which is set via ``set_model_file function\n :params sentences : list of sentences needed to tag.\n :type sentences : list(list(str))\n :return : list of tagged sentences.\n :rtype : list (list (tuple(str,str)))\n "
history = []
if (self._model_file == ):
raise Exception(' No model file is found !! Please use train or set_model_file function')
result = []
for tokens in sents:
features = [self._feature_func(tokens, i, history) for i in range(len(tokens))]
labels = self._tagger.tag(features)
if (len(labels) != len(tokens)):
raise Exception(' Predicted Length Not Matched, Expect Errors !')
tagged_sent = list(zip(tokens, labels))
result.append(tagged_sent)
return result | def tag_sents(self, sents):
"\n Tag a list of sentences. NB before using this function, user should specify the mode_file either by\n - Train a new model using ``train function\n - Use the pre-trained model which is set via ``set_model_file function\n :params sentences : list of sentences needed to tag.\n :type sentences : list(list(str))\n :return : list of tagged sentences.\n :rtype : list (list (tuple(str,str)))\n "
history = []
if (self._model_file == ):
raise Exception(' No model file is found !! Please use train or set_model_file function')
result = []
for tokens in sents:
features = [self._feature_func(tokens, i, history) for i in range(len(tokens))]
labels = self._tagger.tag(features)
if (len(labels) != len(tokens)):
raise Exception(' Predicted Length Not Matched, Expect Errors !')
tagged_sent = list(zip(tokens, labels))
result.append(tagged_sent)
return result<|docstring|>Tag a list of sentences. NB before using this function, user should specify the mode_file either by
- Train a new model using ``train'' function
- Use the pre-trained model which is set via ``set_model_file'' function
:params sentences : list of sentences needed to tag.
:type sentences : list(list(str))
:return : list of tagged sentences.
:rtype : list (list (tuple(str,str)))<|endoftext|> |
28105b7d365eaa0f9bbafd5ea0d58b58276815a8432b2565cdcd1600d17e765e | def train(self, train_data, model_file):
'\n Train the CRF tagger using CRFSuite\n :params train_data : is the list of annotated sentences.\n :type train_data : list (list(tuple(str,str)))\n :params model_file : the model will be saved to this file.\n\n '
history = []
trainer = pycrfsuite.Trainer(verbose=self._verbose, algorithm=self._algorithm)
print(('Algorithm used by CRF: ' + self._algorithm))
trainer.set_params(self._training_options)
for sent in train_data:
(tokens, labels) = zip(*sent)
features = [self._feature_func(tokens, i, history) for i in range(len(tokens))]
trainer.append(features, labels)
trainer.train(model_file)
self.set_model_file(model_file) | Train the CRF tagger using CRFSuite
:params train_data : is the list of annotated sentences.
:type train_data : list (list(tuple(str,str)))
:params model_file : the model will be saved to this file. | src/classifiers/crf.py | train | ciads-ut/transfer-learning-ner | 39 | python | def train(self, train_data, model_file):
'\n Train the CRF tagger using CRFSuite\n :params train_data : is the list of annotated sentences.\n :type train_data : list (list(tuple(str,str)))\n :params model_file : the model will be saved to this file.\n\n '
history = []
trainer = pycrfsuite.Trainer(verbose=self._verbose, algorithm=self._algorithm)
print(('Algorithm used by CRF: ' + self._algorithm))
trainer.set_params(self._training_options)
for sent in train_data:
(tokens, labels) = zip(*sent)
features = [self._feature_func(tokens, i, history) for i in range(len(tokens))]
trainer.append(features, labels)
trainer.train(model_file)
self.set_model_file(model_file) | def train(self, train_data, model_file):
'\n Train the CRF tagger using CRFSuite\n :params train_data : is the list of annotated sentences.\n :type train_data : list (list(tuple(str,str)))\n :params model_file : the model will be saved to this file.\n\n '
history = []
trainer = pycrfsuite.Trainer(verbose=self._verbose, algorithm=self._algorithm)
print(('Algorithm used by CRF: ' + self._algorithm))
trainer.set_params(self._training_options)
for sent in train_data:
(tokens, labels) = zip(*sent)
features = [self._feature_func(tokens, i, history) for i in range(len(tokens))]
trainer.append(features, labels)
trainer.train(model_file)
self.set_model_file(model_file)<|docstring|>Train the CRF tagger using CRFSuite
:params train_data : is the list of annotated sentences.
:type train_data : list (list(tuple(str,str)))
:params model_file : the model will be saved to this file.<|endoftext|> |
db90e004f6a8a0e4d79448ab4d222af973220d9ebf693a6ac3eb23455fe44540 | def tag(self, tokens):
"\n Tag a sentence using Python CRFSuite Tagger. NB before using this function, user should specify the mode_file either by\n - Train a new model using ``train'' function\n - Use the pre-trained model which is set via ``set_model_file'' function\n :params tokens : list of tokens needed to tag.\n :type tokens : list(str)\n :return : list of tagged tokens.\n :rtype : list (tuple(str,str))\n "
return self.tag_sents([tokens])[0] | Tag a sentence using Python CRFSuite Tagger. NB before using this function, user should specify the mode_file either by
- Train a new model using ``train'' function
- Use the pre-trained model which is set via ``set_model_file'' function
:params tokens : list of tokens needed to tag.
:type tokens : list(str)
:return : list of tagged tokens.
:rtype : list (tuple(str,str)) | src/classifiers/crf.py | tag | ciads-ut/transfer-learning-ner | 39 | python | def tag(self, tokens):
"\n Tag a sentence using Python CRFSuite Tagger. NB before using this function, user should specify the mode_file either by\n - Train a new model using ``train function\n - Use the pre-trained model which is set via ``set_model_file function\n :params tokens : list of tokens needed to tag.\n :type tokens : list(str)\n :return : list of tagged tokens.\n :rtype : list (tuple(str,str))\n "
return self.tag_sents([tokens])[0] | def tag(self, tokens):
"\n Tag a sentence using Python CRFSuite Tagger. NB before using this function, user should specify the mode_file either by\n - Train a new model using ``train function\n - Use the pre-trained model which is set via ``set_model_file function\n :params tokens : list of tokens needed to tag.\n :type tokens : list(str)\n :return : list of tagged tokens.\n :rtype : list (tuple(str,str))\n "
return self.tag_sents([tokens])[0]<|docstring|>Tag a sentence using Python CRFSuite Tagger. NB before using this function, user should specify the mode_file either by
- Train a new model using ``train'' function
- Use the pre-trained model which is set via ``set_model_file'' function
:params tokens : list of tokens needed to tag.
:type tokens : list(str)
:return : list of tagged tokens.
:rtype : list (tuple(str,str))<|endoftext|> |
0f4152b3d0b7332f1491b03d8582d102b843ccd7822375f5b77db310fa46e1d7 | def __init__(self, dllpath='C:\\Windows\\System32\\wlmData.dll', debug=False):
'\n Wavelength meter class.\n Argument: Optional path to the dll. Default: "C:\\Windows\\System32\\wlmData.dll"\n\t\tThe one I am using: "C:\\Program Files (x86)\\HighFinesse\\Wavelength Meter WS7 1893\\Projects4\\wlmData.dll" \n\t\t"C:\\Program Files_(x86)\\HighFinesse\\Wavelength_Meter_WS7_1893\\Projects4\\wlmData.dll" \n '
self.channels = []
self.dllpath = dllpath
self.debug = debug
if (not debug):
self.dll = ctypes.WinDLL(dllpath)
self.dll.GetWavelengthNum.restype = ctypes.c_double
self.dll.GetFrequencyNum.restype = ctypes.c_double
self.dll.GetSwitcherMode.restype = ctypes.c_long | Wavelength meter class.
Argument: Optional path to the dll. Default: "C:\Windows\System32\wlmData.dll"
The one I am using: "C:\Program Files (x86)\HighFinesse\Wavelength Meter WS7 1893\Projects4\wlmData.dll"
"C:\Program Files_(x86)\HighFinesse\Wavelength_Meter_WS7_1893\Projects4\wlmData.dll" | wlm.py | __init__ | hemmerlinglab/Laser-Locking-and-Server | 0 | python | def __init__(self, dllpath='C:\\Windows\\System32\\wlmData.dll', debug=False):
'\n Wavelength meter class.\n Argument: Optional path to the dll. Default: "C:\\Windows\\System32\\wlmData.dll"\n\t\tThe one I am using: "C:\\Program Files (x86)\\HighFinesse\\Wavelength Meter WS7 1893\\Projects4\\wlmData.dll" \n\t\t"C:\\Program Files_(x86)\\HighFinesse\\Wavelength_Meter_WS7_1893\\Projects4\\wlmData.dll" \n '
self.channels = []
self.dllpath = dllpath
self.debug = debug
if (not debug):
self.dll = ctypes.WinDLL(dllpath)
self.dll.GetWavelengthNum.restype = ctypes.c_double
self.dll.GetFrequencyNum.restype = ctypes.c_double
self.dll.GetSwitcherMode.restype = ctypes.c_long | def __init__(self, dllpath='C:\\Windows\\System32\\wlmData.dll', debug=False):
'\n Wavelength meter class.\n Argument: Optional path to the dll. Default: "C:\\Windows\\System32\\wlmData.dll"\n\t\tThe one I am using: "C:\\Program Files (x86)\\HighFinesse\\Wavelength Meter WS7 1893\\Projects4\\wlmData.dll" \n\t\t"C:\\Program Files_(x86)\\HighFinesse\\Wavelength_Meter_WS7_1893\\Projects4\\wlmData.dll" \n '
self.channels = []
self.dllpath = dllpath
self.debug = debug
if (not debug):
self.dll = ctypes.WinDLL(dllpath)
self.dll.GetWavelengthNum.restype = ctypes.c_double
self.dll.GetFrequencyNum.restype = ctypes.c_double
self.dll.GetSwitcherMode.restype = ctypes.c_long<|docstring|>Wavelength meter class.
Argument: Optional path to the dll. Default: "C:\Windows\System32\wlmData.dll"
The one I am using: "C:\Program Files (x86)\HighFinesse\Wavelength Meter WS7 1893\Projects4\wlmData.dll"
"C:\Program Files_(x86)\HighFinesse\Wavelength_Meter_WS7_1893\Projects4\wlmData.dll"<|endoftext|> |
8e1fe875a3c6a1e89851602955d96ccd86941aedaf5cfb528369402515b35d45 | def call(self, x):
'\n -----------------------------------multi conv layer---------------------------------\n ↓ ----multi residual block------- ↑\n ↓ ↓ ↑ ↑\n x - > conv -> x -> max_pooling -> x(block_x) -> relu -> x -> resnet_conv -> x => x ↘ ↑\n ↓ + x -> relu -> x -> flatten -> x\n --------------residual add----------------↑ ↗\n '
for i in range(len(self.all_filters)):
x = getattr(self, ('conv' + str(i)))(x)
block_x = x = getattr(self, ('pool' + str(i)))(x)
for j in range(self.res_blocks):
x = tf.nn.relu(x)
x = getattr(self, ((('resblock' + str(i)) + 'conv') + str(j)))(x)
x = tf.add(block_x, x)
x = tf.nn.relu(x)
x = self.flatten(x)
return x | -----------------------------------multi conv layer---------------------------------
↓ ----multi residual block------- ↑
↓ ↓ ↑ ↑
x - > conv -> x -> max_pooling -> x(block_x) -> relu -> x -> resnet_conv -> x => x ↘ ↑
↓ + x -> relu -> x -> flatten -> x
--------------residual add----------------↑ ↗ | rls/nn/networks.py | call | LittleYoung-0/RLs | 2 | python | def call(self, x):
'\n -----------------------------------multi conv layer---------------------------------\n ↓ ----multi residual block------- ↑\n ↓ ↓ ↑ ↑\n x - > conv -> x -> max_pooling -> x(block_x) -> relu -> x -> resnet_conv -> x => x ↘ ↑\n ↓ + x -> relu -> x -> flatten -> x\n --------------residual add----------------↑ ↗\n '
for i in range(len(self.all_filters)):
x = getattr(self, ('conv' + str(i)))(x)
block_x = x = getattr(self, ('pool' + str(i)))(x)
for j in range(self.res_blocks):
x = tf.nn.relu(x)
x = getattr(self, ((('resblock' + str(i)) + 'conv') + str(j)))(x)
x = tf.add(block_x, x)
x = tf.nn.relu(x)
x = self.flatten(x)
return x | def call(self, x):
'\n -----------------------------------multi conv layer---------------------------------\n ↓ ----multi residual block------- ↑\n ↓ ↓ ↑ ↑\n x - > conv -> x -> max_pooling -> x(block_x) -> relu -> x -> resnet_conv -> x => x ↘ ↑\n ↓ + x -> relu -> x -> flatten -> x\n --------------residual add----------------↑ ↗\n '
for i in range(len(self.all_filters)):
x = getattr(self, ('conv' + str(i)))(x)
block_x = x = getattr(self, ('pool' + str(i)))(x)
for j in range(self.res_blocks):
x = tf.nn.relu(x)
x = getattr(self, ((('resblock' + str(i)) + 'conv') + str(j)))(x)
x = tf.add(block_x, x)
x = tf.nn.relu(x)
x = self.flatten(x)
return x<|docstring|>-----------------------------------multi conv layer---------------------------------
↓ ----multi residual block------- ↑
↓ ↓ ↑ ↑
x - > conv -> x -> max_pooling -> x(block_x) -> relu -> x -> resnet_conv -> x => x ↘ ↑
↓ + x -> relu -> x -> flatten -> x
--------------residual add----------------↑ ↗<|endoftext|> |
4754163215f74a117aeb5ab2619207df45729039325d42d652e58a398e89abac | def num_range(s: str) -> List[int]:
"Accept either a comma separated list of numbers 'a,b,c' or a range 'a-c' and return as a list of ints."
range_re = re.compile('^(\\d+)-(\\d+)$')
m = range_re.match(s)
if m:
return list(range(int(m.group(1)), (int(m.group(2)) + 1)))
vals = s.split(',')
return [int(x) for x in vals] | Accept either a comma separated list of numbers 'a,b,c' or a range 'a-c' and return as a list of ints. | phonemes/phoneme_generate.py | num_range | WillReynolds5/stylegan2-ada-pytorch | 0 | python | def num_range(s: str) -> List[int]:
range_re = re.compile('^(\\d+)-(\\d+)$')
m = range_re.match(s)
if m:
return list(range(int(m.group(1)), (int(m.group(2)) + 1)))
vals = s.split(',')
return [int(x) for x in vals] | def num_range(s: str) -> List[int]:
range_re = re.compile('^(\\d+)-(\\d+)$')
m = range_re.match(s)
if m:
return list(range(int(m.group(1)), (int(m.group(2)) + 1)))
vals = s.split(',')
return [int(x) for x in vals]<|docstring|>Accept either a comma separated list of numbers 'a,b,c' or a range 'a-c' and return as a list of ints.<|endoftext|> |
504f9fab65acb773b3df79f1c951e0a0c849cb216cfe02d4075e0b4394c428c1 | def new_view(window, **kwargs):
"Open a new view in the given `window`, returning the :class:`~sublime.View` object.\n\n This function takes many optional keyword arguments:\n\n :argument content: Text to be inserted into the new view. The text will be inserted even\n if the `read_only` option is ``True``.\n\n :argument encoding: The encoding that the view should use when saving.\n\n :argument line_endings: The kind of line endings to use.\n The given value will be passed to :class:`LineEnding`.\n\n :argument name: The name of the view. This will be shown as the title of the view's tab.\n\n :argument overwrite: If ``True``, the view will be in overwrite mode.\n\n :argument read_only: If ``True``, the view will be read-only.\n\n :argument scope: A scope name.\n The view will be assigned a syntax definition that corresponds to the given scope\n (as determined by :func:`~sublime_lib.get_syntax_for_scope`).\n Incompatible with the `syntax` option.\n\n :argument scratch: If ``True``, the view will be a scratch buffer.\n The user will not be prompted to save the view before closing it.\n\n :argument settings: A dictionary of names and values\n that will be applied to the new view's Settings object.\n\n :argument syntax: The resource path of a syntax definition that the view will use.\n Incompatible with the `scope` option.\n\n :raise ValueError: if both `scope` and `syntax` are specified.\n :raise ValueError: if `encoding` is not a Python encoding name.\n :raise ValueError: if `line_endings` cannot be converted to :class:`LineEnding`.\n\n .. versionchanged:: 1.2\n Added the `line_endings` argument.\n "
validate_view_options(kwargs)
view = window.new_file()
set_view_options(view, **kwargs)
return view | Open a new view in the given `window`, returning the :class:`~sublime.View` object.
This function takes many optional keyword arguments:
:argument content: Text to be inserted into the new view. The text will be inserted even
if the `read_only` option is ``True``.
:argument encoding: The encoding that the view should use when saving.
:argument line_endings: The kind of line endings to use.
The given value will be passed to :class:`LineEnding`.
:argument name: The name of the view. This will be shown as the title of the view's tab.
:argument overwrite: If ``True``, the view will be in overwrite mode.
:argument read_only: If ``True``, the view will be read-only.
:argument scope: A scope name.
The view will be assigned a syntax definition that corresponds to the given scope
(as determined by :func:`~sublime_lib.get_syntax_for_scope`).
Incompatible with the `syntax` option.
:argument scratch: If ``True``, the view will be a scratch buffer.
The user will not be prompted to save the view before closing it.
:argument settings: A dictionary of names and values
that will be applied to the new view's Settings object.
:argument syntax: The resource path of a syntax definition that the view will use.
Incompatible with the `scope` option.
:raise ValueError: if both `scope` and `syntax` are specified.
:raise ValueError: if `encoding` is not a Python encoding name.
:raise ValueError: if `line_endings` cannot be converted to :class:`LineEnding`.
.. versionchanged:: 1.2
Added the `line_endings` argument. | Backup/20190721144404/sublime_lib/st3/sublime_lib/view_utils.py | new_view | altundasbatu/SublimeTextSettings | 0 | python | def new_view(window, **kwargs):
"Open a new view in the given `window`, returning the :class:`~sublime.View` object.\n\n This function takes many optional keyword arguments:\n\n :argument content: Text to be inserted into the new view. The text will be inserted even\n if the `read_only` option is ``True``.\n\n :argument encoding: The encoding that the view should use when saving.\n\n :argument line_endings: The kind of line endings to use.\n The given value will be passed to :class:`LineEnding`.\n\n :argument name: The name of the view. This will be shown as the title of the view's tab.\n\n :argument overwrite: If ``True``, the view will be in overwrite mode.\n\n :argument read_only: If ``True``, the view will be read-only.\n\n :argument scope: A scope name.\n The view will be assigned a syntax definition that corresponds to the given scope\n (as determined by :func:`~sublime_lib.get_syntax_for_scope`).\n Incompatible with the `syntax` option.\n\n :argument scratch: If ``True``, the view will be a scratch buffer.\n The user will not be prompted to save the view before closing it.\n\n :argument settings: A dictionary of names and values\n that will be applied to the new view's Settings object.\n\n :argument syntax: The resource path of a syntax definition that the view will use.\n Incompatible with the `scope` option.\n\n :raise ValueError: if both `scope` and `syntax` are specified.\n :raise ValueError: if `encoding` is not a Python encoding name.\n :raise ValueError: if `line_endings` cannot be converted to :class:`LineEnding`.\n\n .. versionchanged:: 1.2\n Added the `line_endings` argument.\n "
validate_view_options(kwargs)
view = window.new_file()
set_view_options(view, **kwargs)
return view | def new_view(window, **kwargs):
"Open a new view in the given `window`, returning the :class:`~sublime.View` object.\n\n This function takes many optional keyword arguments:\n\n :argument content: Text to be inserted into the new view. The text will be inserted even\n if the `read_only` option is ``True``.\n\n :argument encoding: The encoding that the view should use when saving.\n\n :argument line_endings: The kind of line endings to use.\n The given value will be passed to :class:`LineEnding`.\n\n :argument name: The name of the view. This will be shown as the title of the view's tab.\n\n :argument overwrite: If ``True``, the view will be in overwrite mode.\n\n :argument read_only: If ``True``, the view will be read-only.\n\n :argument scope: A scope name.\n The view will be assigned a syntax definition that corresponds to the given scope\n (as determined by :func:`~sublime_lib.get_syntax_for_scope`).\n Incompatible with the `syntax` option.\n\n :argument scratch: If ``True``, the view will be a scratch buffer.\n The user will not be prompted to save the view before closing it.\n\n :argument settings: A dictionary of names and values\n that will be applied to the new view's Settings object.\n\n :argument syntax: The resource path of a syntax definition that the view will use.\n Incompatible with the `scope` option.\n\n :raise ValueError: if both `scope` and `syntax` are specified.\n :raise ValueError: if `encoding` is not a Python encoding name.\n :raise ValueError: if `line_endings` cannot be converted to :class:`LineEnding`.\n\n .. versionchanged:: 1.2\n Added the `line_endings` argument.\n "
validate_view_options(kwargs)
view = window.new_file()
set_view_options(view, **kwargs)
return view<|docstring|>Open a new view in the given `window`, returning the :class:`~sublime.View` object.
This function takes many optional keyword arguments:
:argument content: Text to be inserted into the new view. The text will be inserted even
if the `read_only` option is ``True``.
:argument encoding: The encoding that the view should use when saving.
:argument line_endings: The kind of line endings to use.
The given value will be passed to :class:`LineEnding`.
:argument name: The name of the view. This will be shown as the title of the view's tab.
:argument overwrite: If ``True``, the view will be in overwrite mode.
:argument read_only: If ``True``, the view will be read-only.
:argument scope: A scope name.
The view will be assigned a syntax definition that corresponds to the given scope
(as determined by :func:`~sublime_lib.get_syntax_for_scope`).
Incompatible with the `syntax` option.
:argument scratch: If ``True``, the view will be a scratch buffer.
The user will not be prompted to save the view before closing it.
:argument settings: A dictionary of names and values
that will be applied to the new view's Settings object.
:argument syntax: The resource path of a syntax definition that the view will use.
Incompatible with the `scope` option.
:raise ValueError: if both `scope` and `syntax` are specified.
:raise ValueError: if `encoding` is not a Python encoding name.
:raise ValueError: if `line_endings` cannot be converted to :class:`LineEnding`.
.. versionchanged:: 1.2
Added the `line_endings` argument.<|endoftext|> |
19a5ef60dde6dba5c17ca59f00504b1b858066c66a94321453ae1c0f9bfa5ef3 | def close_view(view, *, force=False):
'Close the given view, discarding unsaved changes if `force` is ``True``.\n\n If the view is invalid (e.g. already closed), do nothing.\n\n :raise ValueError: if the view has unsaved changes and `force` is not ``True``.\n :raise ValueError: if the view is not closed for any other reason.\n '
if (view.is_dirty() and (not view.is_scratch())):
if force:
view.set_scratch(True)
else:
raise ValueError('The view has unsaved changes.')
if (not view.close()):
raise ValueError('The view could not be closed.') | Close the given view, discarding unsaved changes if `force` is ``True``.
If the view is invalid (e.g. already closed), do nothing.
:raise ValueError: if the view has unsaved changes and `force` is not ``True``.
:raise ValueError: if the view is not closed for any other reason. | Backup/20190721144404/sublime_lib/st3/sublime_lib/view_utils.py | close_view | altundasbatu/SublimeTextSettings | 0 | python | def close_view(view, *, force=False):
'Close the given view, discarding unsaved changes if `force` is ``True``.\n\n If the view is invalid (e.g. already closed), do nothing.\n\n :raise ValueError: if the view has unsaved changes and `force` is not ``True``.\n :raise ValueError: if the view is not closed for any other reason.\n '
if (view.is_dirty() and (not view.is_scratch())):
if force:
view.set_scratch(True)
else:
raise ValueError('The view has unsaved changes.')
if (not view.close()):
raise ValueError('The view could not be closed.') | def close_view(view, *, force=False):
'Close the given view, discarding unsaved changes if `force` is ``True``.\n\n If the view is invalid (e.g. already closed), do nothing.\n\n :raise ValueError: if the view has unsaved changes and `force` is not ``True``.\n :raise ValueError: if the view is not closed for any other reason.\n '
if (view.is_dirty() and (not view.is_scratch())):
if force:
view.set_scratch(True)
else:
raise ValueError('The view has unsaved changes.')
if (not view.close()):
raise ValueError('The view could not be closed.')<|docstring|>Close the given view, discarding unsaved changes if `force` is ``True``.
If the view is invalid (e.g. already closed), do nothing.
:raise ValueError: if the view has unsaved changes and `force` is not ``True``.
:raise ValueError: if the view is not closed for any other reason.<|endoftext|> |
2f2f51d7d31febc41453374c45fac2a11bdac9ef9ff44473a2e171a371468a2b | def list_by_resource(self, resource_uri: str, **kwargs: Any) -> AsyncIterable['_models.DataCollectionRuleAssociationProxyOnlyResourceListResult']:
'Lists associations for the specified resource.\n\n Lists associations for the specified resource.\n\n :param resource_uri: The identifier of the resource.\n :type resource_uri: str\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: An iterator like instance of either DataCollectionRuleAssociationProxyOnlyResourceListResult or the result of cls(response)\n :rtype: ~azure.core.async_paging.AsyncItemPaged[~$(python-base-namespace).v2021_04_01.models.DataCollectionRuleAssociationProxyOnlyResourceListResult]\n :raises: ~azure.core.exceptions.HttpResponseError\n '
cls = kwargs.pop('cls', None)
error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError}
error_map.update(kwargs.pop('error_map', {}))
api_version = '2021-04-01'
accept = 'application/json'
def prepare_request(next_link=None):
header_parameters = {}
header_parameters['Accept'] = self._serialize.header('accept', accept, 'str')
if (not next_link):
url = self.list_by_resource.metadata['url']
path_format_arguments = {'resourceUri': self._serialize.url('resource_uri', resource_uri, 'str', skip_quote=True, min_length=1)}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query('api_version', api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {}
request = self._client.get(url, query_parameters, header_parameters)
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize('DataCollectionRuleAssociationProxyOnlyResourceListResult', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return ((deserialized.next_link or None), AsyncList(list_of_elem))
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = (await self._client._pipeline.run(request, stream=False, **kwargs))
response = pipeline_response.http_response
if (response.status_code not in [200]):
error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, response)
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data) | Lists associations for the specified resource.
Lists associations for the specified resource.
:param resource_uri: The identifier of the resource.
:type resource_uri: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either DataCollectionRuleAssociationProxyOnlyResourceListResult or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~$(python-base-namespace).v2021_04_01.models.DataCollectionRuleAssociationProxyOnlyResourceListResult]
:raises: ~azure.core.exceptions.HttpResponseError | sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/aio/operations/_data_collection_rule_associations_operations.py | list_by_resource | cochi2/azure-sdk-for-python | 2,728 | python | def list_by_resource(self, resource_uri: str, **kwargs: Any) -> AsyncIterable['_models.DataCollectionRuleAssociationProxyOnlyResourceListResult']:
'Lists associations for the specified resource.\n\n Lists associations for the specified resource.\n\n :param resource_uri: The identifier of the resource.\n :type resource_uri: str\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: An iterator like instance of either DataCollectionRuleAssociationProxyOnlyResourceListResult or the result of cls(response)\n :rtype: ~azure.core.async_paging.AsyncItemPaged[~$(python-base-namespace).v2021_04_01.models.DataCollectionRuleAssociationProxyOnlyResourceListResult]\n :raises: ~azure.core.exceptions.HttpResponseError\n '
cls = kwargs.pop('cls', None)
error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError}
error_map.update(kwargs.pop('error_map', {}))
api_version = '2021-04-01'
accept = 'application/json'
def prepare_request(next_link=None):
header_parameters = {}
header_parameters['Accept'] = self._serialize.header('accept', accept, 'str')
if (not next_link):
url = self.list_by_resource.metadata['url']
path_format_arguments = {'resourceUri': self._serialize.url('resource_uri', resource_uri, 'str', skip_quote=True, min_length=1)}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query('api_version', api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {}
request = self._client.get(url, query_parameters, header_parameters)
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize('DataCollectionRuleAssociationProxyOnlyResourceListResult', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return ((deserialized.next_link or None), AsyncList(list_of_elem))
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = (await self._client._pipeline.run(request, stream=False, **kwargs))
response = pipeline_response.http_response
if (response.status_code not in [200]):
error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, response)
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data) | def list_by_resource(self, resource_uri: str, **kwargs: Any) -> AsyncIterable['_models.DataCollectionRuleAssociationProxyOnlyResourceListResult']:
'Lists associations for the specified resource.\n\n Lists associations for the specified resource.\n\n :param resource_uri: The identifier of the resource.\n :type resource_uri: str\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: An iterator like instance of either DataCollectionRuleAssociationProxyOnlyResourceListResult or the result of cls(response)\n :rtype: ~azure.core.async_paging.AsyncItemPaged[~$(python-base-namespace).v2021_04_01.models.DataCollectionRuleAssociationProxyOnlyResourceListResult]\n :raises: ~azure.core.exceptions.HttpResponseError\n '
cls = kwargs.pop('cls', None)
error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError}
error_map.update(kwargs.pop('error_map', {}))
api_version = '2021-04-01'
accept = 'application/json'
def prepare_request(next_link=None):
header_parameters = {}
header_parameters['Accept'] = self._serialize.header('accept', accept, 'str')
if (not next_link):
url = self.list_by_resource.metadata['url']
path_format_arguments = {'resourceUri': self._serialize.url('resource_uri', resource_uri, 'str', skip_quote=True, min_length=1)}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query('api_version', api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {}
request = self._client.get(url, query_parameters, header_parameters)
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize('DataCollectionRuleAssociationProxyOnlyResourceListResult', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return ((deserialized.next_link or None), AsyncList(list_of_elem))
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = (await self._client._pipeline.run(request, stream=False, **kwargs))
response = pipeline_response.http_response
if (response.status_code not in [200]):
error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, response)
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)<|docstring|>Lists associations for the specified resource.
Lists associations for the specified resource.
:param resource_uri: The identifier of the resource.
:type resource_uri: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either DataCollectionRuleAssociationProxyOnlyResourceListResult or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~$(python-base-namespace).v2021_04_01.models.DataCollectionRuleAssociationProxyOnlyResourceListResult]
:raises: ~azure.core.exceptions.HttpResponseError<|endoftext|> |
979c3587a267b4acda65bf155e053c9c97462cb9234fba967cf3e86f9143f0d9 | def list_by_rule(self, resource_group_name: str, data_collection_rule_name: str, **kwargs: Any) -> AsyncIterable['_models.DataCollectionRuleAssociationProxyOnlyResourceListResult']:
'Lists associations for the specified data collection rule.\n\n Lists associations for the specified data collection rule.\n\n :param resource_group_name: The name of the resource group. The name is case insensitive.\n :type resource_group_name: str\n :param data_collection_rule_name: The name of the data collection rule. The name is case\n insensitive.\n :type data_collection_rule_name: str\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: An iterator like instance of either DataCollectionRuleAssociationProxyOnlyResourceListResult or the result of cls(response)\n :rtype: ~azure.core.async_paging.AsyncItemPaged[~$(python-base-namespace).v2021_04_01.models.DataCollectionRuleAssociationProxyOnlyResourceListResult]\n :raises: ~azure.core.exceptions.HttpResponseError\n '
cls = kwargs.pop('cls', None)
error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError}
error_map.update(kwargs.pop('error_map', {}))
api_version = '2021-04-01'
accept = 'application/json'
def prepare_request(next_link=None):
header_parameters = {}
header_parameters['Accept'] = self._serialize.header('accept', accept, 'str')
if (not next_link):
url = self.list_by_rule.metadata['url']
path_format_arguments = {'subscriptionId': self._serialize.url('self._config.subscription_id', self._config.subscription_id, 'str', min_length=1), 'resourceGroupName': self._serialize.url('resource_group_name', resource_group_name, 'str', max_length=90, min_length=1), 'dataCollectionRuleName': self._serialize.url('data_collection_rule_name', data_collection_rule_name, 'str')}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query('api_version', api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {}
request = self._client.get(url, query_parameters, header_parameters)
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize('DataCollectionRuleAssociationProxyOnlyResourceListResult', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return ((deserialized.next_link or None), AsyncList(list_of_elem))
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = (await self._client._pipeline.run(request, stream=False, **kwargs))
response = pipeline_response.http_response
if (response.status_code not in [200]):
error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, response)
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data) | Lists associations for the specified data collection rule.
Lists associations for the specified data collection rule.
:param resource_group_name: The name of the resource group. The name is case insensitive.
:type resource_group_name: str
:param data_collection_rule_name: The name of the data collection rule. The name is case
insensitive.
:type data_collection_rule_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either DataCollectionRuleAssociationProxyOnlyResourceListResult or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~$(python-base-namespace).v2021_04_01.models.DataCollectionRuleAssociationProxyOnlyResourceListResult]
:raises: ~azure.core.exceptions.HttpResponseError | sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/aio/operations/_data_collection_rule_associations_operations.py | list_by_rule | cochi2/azure-sdk-for-python | 2,728 | python | def list_by_rule(self, resource_group_name: str, data_collection_rule_name: str, **kwargs: Any) -> AsyncIterable['_models.DataCollectionRuleAssociationProxyOnlyResourceListResult']:
'Lists associations for the specified data collection rule.\n\n Lists associations for the specified data collection rule.\n\n :param resource_group_name: The name of the resource group. The name is case insensitive.\n :type resource_group_name: str\n :param data_collection_rule_name: The name of the data collection rule. The name is case\n insensitive.\n :type data_collection_rule_name: str\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: An iterator like instance of either DataCollectionRuleAssociationProxyOnlyResourceListResult or the result of cls(response)\n :rtype: ~azure.core.async_paging.AsyncItemPaged[~$(python-base-namespace).v2021_04_01.models.DataCollectionRuleAssociationProxyOnlyResourceListResult]\n :raises: ~azure.core.exceptions.HttpResponseError\n '
cls = kwargs.pop('cls', None)
error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError}
error_map.update(kwargs.pop('error_map', {}))
api_version = '2021-04-01'
accept = 'application/json'
def prepare_request(next_link=None):
header_parameters = {}
header_parameters['Accept'] = self._serialize.header('accept', accept, 'str')
if (not next_link):
url = self.list_by_rule.metadata['url']
path_format_arguments = {'subscriptionId': self._serialize.url('self._config.subscription_id', self._config.subscription_id, 'str', min_length=1), 'resourceGroupName': self._serialize.url('resource_group_name', resource_group_name, 'str', max_length=90, min_length=1), 'dataCollectionRuleName': self._serialize.url('data_collection_rule_name', data_collection_rule_name, 'str')}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query('api_version', api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {}
request = self._client.get(url, query_parameters, header_parameters)
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize('DataCollectionRuleAssociationProxyOnlyResourceListResult', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return ((deserialized.next_link or None), AsyncList(list_of_elem))
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = (await self._client._pipeline.run(request, stream=False, **kwargs))
response = pipeline_response.http_response
if (response.status_code not in [200]):
error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, response)
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data) | def list_by_rule(self, resource_group_name: str, data_collection_rule_name: str, **kwargs: Any) -> AsyncIterable['_models.DataCollectionRuleAssociationProxyOnlyResourceListResult']:
'Lists associations for the specified data collection rule.\n\n Lists associations for the specified data collection rule.\n\n :param resource_group_name: The name of the resource group. The name is case insensitive.\n :type resource_group_name: str\n :param data_collection_rule_name: The name of the data collection rule. The name is case\n insensitive.\n :type data_collection_rule_name: str\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: An iterator like instance of either DataCollectionRuleAssociationProxyOnlyResourceListResult or the result of cls(response)\n :rtype: ~azure.core.async_paging.AsyncItemPaged[~$(python-base-namespace).v2021_04_01.models.DataCollectionRuleAssociationProxyOnlyResourceListResult]\n :raises: ~azure.core.exceptions.HttpResponseError\n '
cls = kwargs.pop('cls', None)
error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError}
error_map.update(kwargs.pop('error_map', {}))
api_version = '2021-04-01'
accept = 'application/json'
def prepare_request(next_link=None):
header_parameters = {}
header_parameters['Accept'] = self._serialize.header('accept', accept, 'str')
if (not next_link):
url = self.list_by_rule.metadata['url']
path_format_arguments = {'subscriptionId': self._serialize.url('self._config.subscription_id', self._config.subscription_id, 'str', min_length=1), 'resourceGroupName': self._serialize.url('resource_group_name', resource_group_name, 'str', max_length=90, min_length=1), 'dataCollectionRuleName': self._serialize.url('data_collection_rule_name', data_collection_rule_name, 'str')}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query('api_version', api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {}
request = self._client.get(url, query_parameters, header_parameters)
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize('DataCollectionRuleAssociationProxyOnlyResourceListResult', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return ((deserialized.next_link or None), AsyncList(list_of_elem))
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = (await self._client._pipeline.run(request, stream=False, **kwargs))
response = pipeline_response.http_response
if (response.status_code not in [200]):
error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, response)
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)<|docstring|>Lists associations for the specified data collection rule.
Lists associations for the specified data collection rule.
:param resource_group_name: The name of the resource group. The name is case insensitive.
:type resource_group_name: str
:param data_collection_rule_name: The name of the data collection rule. The name is case
insensitive.
:type data_collection_rule_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either DataCollectionRuleAssociationProxyOnlyResourceListResult or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~$(python-base-namespace).v2021_04_01.models.DataCollectionRuleAssociationProxyOnlyResourceListResult]
:raises: ~azure.core.exceptions.HttpResponseError<|endoftext|> |
47b2ca68c53962f0400ef5596b48970d50120a637f0182dfc6b4ddef5dfa5a7b | async def get(self, resource_uri: str, association_name: str, **kwargs: Any) -> '_models.DataCollectionRuleAssociationProxyOnlyResource':
'Returns the specified association.\n\n Returns the specified association.\n\n :param resource_uri: The identifier of the resource.\n :type resource_uri: str\n :param association_name: The name of the association. The name is case insensitive.\n :type association_name: str\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: DataCollectionRuleAssociationProxyOnlyResource, or the result of cls(response)\n :rtype: ~$(python-base-namespace).v2021_04_01.models.DataCollectionRuleAssociationProxyOnlyResource\n :raises: ~azure.core.exceptions.HttpResponseError\n '
cls = kwargs.pop('cls', None)
error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError}
error_map.update(kwargs.pop('error_map', {}))
api_version = '2021-04-01'
accept = 'application/json'
url = self.get.metadata['url']
path_format_arguments = {'resourceUri': self._serialize.url('resource_uri', resource_uri, 'str', skip_quote=True, min_length=1), 'associationName': self._serialize.url('association_name', association_name, 'str')}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query('api_version', api_version, 'str')
header_parameters = {}
header_parameters['Accept'] = self._serialize.header('accept', accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = (await self._client._pipeline.run(request, stream=False, **kwargs))
response = pipeline_response.http_response
if (response.status_code not in [200]):
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('DataCollectionRuleAssociationProxyOnlyResource', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized | Returns the specified association.
Returns the specified association.
:param resource_uri: The identifier of the resource.
:type resource_uri: str
:param association_name: The name of the association. The name is case insensitive.
:type association_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: DataCollectionRuleAssociationProxyOnlyResource, or the result of cls(response)
:rtype: ~$(python-base-namespace).v2021_04_01.models.DataCollectionRuleAssociationProxyOnlyResource
:raises: ~azure.core.exceptions.HttpResponseError | sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/aio/operations/_data_collection_rule_associations_operations.py | get | cochi2/azure-sdk-for-python | 2,728 | python | async def get(self, resource_uri: str, association_name: str, **kwargs: Any) -> '_models.DataCollectionRuleAssociationProxyOnlyResource':
'Returns the specified association.\n\n Returns the specified association.\n\n :param resource_uri: The identifier of the resource.\n :type resource_uri: str\n :param association_name: The name of the association. The name is case insensitive.\n :type association_name: str\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: DataCollectionRuleAssociationProxyOnlyResource, or the result of cls(response)\n :rtype: ~$(python-base-namespace).v2021_04_01.models.DataCollectionRuleAssociationProxyOnlyResource\n :raises: ~azure.core.exceptions.HttpResponseError\n '
cls = kwargs.pop('cls', None)
error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError}
error_map.update(kwargs.pop('error_map', {}))
api_version = '2021-04-01'
accept = 'application/json'
url = self.get.metadata['url']
path_format_arguments = {'resourceUri': self._serialize.url('resource_uri', resource_uri, 'str', skip_quote=True, min_length=1), 'associationName': self._serialize.url('association_name', association_name, 'str')}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query('api_version', api_version, 'str')
header_parameters = {}
header_parameters['Accept'] = self._serialize.header('accept', accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = (await self._client._pipeline.run(request, stream=False, **kwargs))
response = pipeline_response.http_response
if (response.status_code not in [200]):
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('DataCollectionRuleAssociationProxyOnlyResource', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized | async def get(self, resource_uri: str, association_name: str, **kwargs: Any) -> '_models.DataCollectionRuleAssociationProxyOnlyResource':
'Returns the specified association.\n\n Returns the specified association.\n\n :param resource_uri: The identifier of the resource.\n :type resource_uri: str\n :param association_name: The name of the association. The name is case insensitive.\n :type association_name: str\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: DataCollectionRuleAssociationProxyOnlyResource, or the result of cls(response)\n :rtype: ~$(python-base-namespace).v2021_04_01.models.DataCollectionRuleAssociationProxyOnlyResource\n :raises: ~azure.core.exceptions.HttpResponseError\n '
cls = kwargs.pop('cls', None)
error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError}
error_map.update(kwargs.pop('error_map', {}))
api_version = '2021-04-01'
accept = 'application/json'
url = self.get.metadata['url']
path_format_arguments = {'resourceUri': self._serialize.url('resource_uri', resource_uri, 'str', skip_quote=True, min_length=1), 'associationName': self._serialize.url('association_name', association_name, 'str')}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query('api_version', api_version, 'str')
header_parameters = {}
header_parameters['Accept'] = self._serialize.header('accept', accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = (await self._client._pipeline.run(request, stream=False, **kwargs))
response = pipeline_response.http_response
if (response.status_code not in [200]):
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
deserialized = self._deserialize('DataCollectionRuleAssociationProxyOnlyResource', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized<|docstring|>Returns the specified association.
Returns the specified association.
:param resource_uri: The identifier of the resource.
:type resource_uri: str
:param association_name: The name of the association. The name is case insensitive.
:type association_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: DataCollectionRuleAssociationProxyOnlyResource, or the result of cls(response)
:rtype: ~$(python-base-namespace).v2021_04_01.models.DataCollectionRuleAssociationProxyOnlyResource
:raises: ~azure.core.exceptions.HttpResponseError<|endoftext|> |
c9442e8d28c9ade401c7ac8c84c9a84997d29691e82e6b03fe937d387000566a | async def create(self, resource_uri: str, association_name: str, body: Optional['_models.DataCollectionRuleAssociationProxyOnlyResource']=None, **kwargs: Any) -> '_models.DataCollectionRuleAssociationProxyOnlyResource':
'Creates or updates an association.\n\n Creates or updates an association.\n\n :param resource_uri: The identifier of the resource.\n :type resource_uri: str\n :param association_name: The name of the association. The name is case insensitive.\n :type association_name: str\n :param body: The payload.\n :type body: ~$(python-base-namespace).v2021_04_01.models.DataCollectionRuleAssociationProxyOnlyResource\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: DataCollectionRuleAssociationProxyOnlyResource, or the result of cls(response)\n :rtype: ~$(python-base-namespace).v2021_04_01.models.DataCollectionRuleAssociationProxyOnlyResource\n :raises: ~azure.core.exceptions.HttpResponseError\n '
cls = kwargs.pop('cls', None)
error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError}
error_map.update(kwargs.pop('error_map', {}))
api_version = '2021-04-01'
content_type = kwargs.pop('content_type', 'application/json')
accept = 'application/json'
url = self.create.metadata['url']
path_format_arguments = {'resourceUri': self._serialize.url('resource_uri', resource_uri, 'str', skip_quote=True, min_length=1), 'associationName': self._serialize.url('association_name', association_name, 'str')}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query('api_version', api_version, 'str')
header_parameters = {}
header_parameters['Content-Type'] = self._serialize.header('content_type', content_type, 'str')
header_parameters['Accept'] = self._serialize.header('accept', accept, 'str')
body_content_kwargs = {}
if (body is not None):
body_content = self._serialize.body(body, 'DataCollectionRuleAssociationProxyOnlyResource')
else:
body_content = None
body_content_kwargs['content'] = body_content
request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = (await self._client._pipeline.run(request, stream=False, **kwargs))
response = pipeline_response.http_response
if (response.status_code not in [200, 201]):
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if (response.status_code == 200):
deserialized = self._deserialize('DataCollectionRuleAssociationProxyOnlyResource', pipeline_response)
if (response.status_code == 201):
deserialized = self._deserialize('DataCollectionRuleAssociationProxyOnlyResource', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized | Creates or updates an association.
Creates or updates an association.
:param resource_uri: The identifier of the resource.
:type resource_uri: str
:param association_name: The name of the association. The name is case insensitive.
:type association_name: str
:param body: The payload.
:type body: ~$(python-base-namespace).v2021_04_01.models.DataCollectionRuleAssociationProxyOnlyResource
:keyword callable cls: A custom type or function that will be passed the direct response
:return: DataCollectionRuleAssociationProxyOnlyResource, or the result of cls(response)
:rtype: ~$(python-base-namespace).v2021_04_01.models.DataCollectionRuleAssociationProxyOnlyResource
:raises: ~azure.core.exceptions.HttpResponseError | sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/aio/operations/_data_collection_rule_associations_operations.py | create | cochi2/azure-sdk-for-python | 2,728 | python | async def create(self, resource_uri: str, association_name: str, body: Optional['_models.DataCollectionRuleAssociationProxyOnlyResource']=None, **kwargs: Any) -> '_models.DataCollectionRuleAssociationProxyOnlyResource':
'Creates or updates an association.\n\n Creates or updates an association.\n\n :param resource_uri: The identifier of the resource.\n :type resource_uri: str\n :param association_name: The name of the association. The name is case insensitive.\n :type association_name: str\n :param body: The payload.\n :type body: ~$(python-base-namespace).v2021_04_01.models.DataCollectionRuleAssociationProxyOnlyResource\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: DataCollectionRuleAssociationProxyOnlyResource, or the result of cls(response)\n :rtype: ~$(python-base-namespace).v2021_04_01.models.DataCollectionRuleAssociationProxyOnlyResource\n :raises: ~azure.core.exceptions.HttpResponseError\n '
cls = kwargs.pop('cls', None)
error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError}
error_map.update(kwargs.pop('error_map', {}))
api_version = '2021-04-01'
content_type = kwargs.pop('content_type', 'application/json')
accept = 'application/json'
url = self.create.metadata['url']
path_format_arguments = {'resourceUri': self._serialize.url('resource_uri', resource_uri, 'str', skip_quote=True, min_length=1), 'associationName': self._serialize.url('association_name', association_name, 'str')}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query('api_version', api_version, 'str')
header_parameters = {}
header_parameters['Content-Type'] = self._serialize.header('content_type', content_type, 'str')
header_parameters['Accept'] = self._serialize.header('accept', accept, 'str')
body_content_kwargs = {}
if (body is not None):
body_content = self._serialize.body(body, 'DataCollectionRuleAssociationProxyOnlyResource')
else:
body_content = None
body_content_kwargs['content'] = body_content
request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = (await self._client._pipeline.run(request, stream=False, **kwargs))
response = pipeline_response.http_response
if (response.status_code not in [200, 201]):
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if (response.status_code == 200):
deserialized = self._deserialize('DataCollectionRuleAssociationProxyOnlyResource', pipeline_response)
if (response.status_code == 201):
deserialized = self._deserialize('DataCollectionRuleAssociationProxyOnlyResource', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized | async def create(self, resource_uri: str, association_name: str, body: Optional['_models.DataCollectionRuleAssociationProxyOnlyResource']=None, **kwargs: Any) -> '_models.DataCollectionRuleAssociationProxyOnlyResource':
'Creates or updates an association.\n\n Creates or updates an association.\n\n :param resource_uri: The identifier of the resource.\n :type resource_uri: str\n :param association_name: The name of the association. The name is case insensitive.\n :type association_name: str\n :param body: The payload.\n :type body: ~$(python-base-namespace).v2021_04_01.models.DataCollectionRuleAssociationProxyOnlyResource\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: DataCollectionRuleAssociationProxyOnlyResource, or the result of cls(response)\n :rtype: ~$(python-base-namespace).v2021_04_01.models.DataCollectionRuleAssociationProxyOnlyResource\n :raises: ~azure.core.exceptions.HttpResponseError\n '
cls = kwargs.pop('cls', None)
error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError}
error_map.update(kwargs.pop('error_map', {}))
api_version = '2021-04-01'
content_type = kwargs.pop('content_type', 'application/json')
accept = 'application/json'
url = self.create.metadata['url']
path_format_arguments = {'resourceUri': self._serialize.url('resource_uri', resource_uri, 'str', skip_quote=True, min_length=1), 'associationName': self._serialize.url('association_name', association_name, 'str')}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query('api_version', api_version, 'str')
header_parameters = {}
header_parameters['Content-Type'] = self._serialize.header('content_type', content_type, 'str')
header_parameters['Accept'] = self._serialize.header('accept', accept, 'str')
body_content_kwargs = {}
if (body is not None):
body_content = self._serialize.body(body, 'DataCollectionRuleAssociationProxyOnlyResource')
else:
body_content = None
body_content_kwargs['content'] = body_content
request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = (await self._client._pipeline.run(request, stream=False, **kwargs))
response = pipeline_response.http_response
if (response.status_code not in [200, 201]):
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if (response.status_code == 200):
deserialized = self._deserialize('DataCollectionRuleAssociationProxyOnlyResource', pipeline_response)
if (response.status_code == 201):
deserialized = self._deserialize('DataCollectionRuleAssociationProxyOnlyResource', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized<|docstring|>Creates or updates an association.
Creates or updates an association.
:param resource_uri: The identifier of the resource.
:type resource_uri: str
:param association_name: The name of the association. The name is case insensitive.
:type association_name: str
:param body: The payload.
:type body: ~$(python-base-namespace).v2021_04_01.models.DataCollectionRuleAssociationProxyOnlyResource
:keyword callable cls: A custom type or function that will be passed the direct response
:return: DataCollectionRuleAssociationProxyOnlyResource, or the result of cls(response)
:rtype: ~$(python-base-namespace).v2021_04_01.models.DataCollectionRuleAssociationProxyOnlyResource
:raises: ~azure.core.exceptions.HttpResponseError<|endoftext|> |
b57249a0c619c5f6fcef301bfbd46640d2f2dc2a532e1420437f5284fff5dc42 | async def delete(self, resource_uri: str, association_name: str, **kwargs: Any) -> None:
'Deletes an association.\n\n Deletes an association.\n\n :param resource_uri: The identifier of the resource.\n :type resource_uri: str\n :param association_name: The name of the association. The name is case insensitive.\n :type association_name: str\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: None, or the result of cls(response)\n :rtype: None\n :raises: ~azure.core.exceptions.HttpResponseError\n '
cls = kwargs.pop('cls', None)
error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError}
error_map.update(kwargs.pop('error_map', {}))
api_version = '2021-04-01'
accept = 'application/json'
url = self.delete.metadata['url']
path_format_arguments = {'resourceUri': self._serialize.url('resource_uri', resource_uri, 'str', skip_quote=True, min_length=1), 'associationName': self._serialize.url('association_name', association_name, 'str')}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query('api_version', api_version, 'str')
header_parameters = {}
header_parameters['Accept'] = self._serialize.header('accept', accept, 'str')
request = self._client.delete(url, query_parameters, header_parameters)
pipeline_response = (await self._client._pipeline.run(request, stream=False, **kwargs))
response = pipeline_response.http_response
if (response.status_code not in [200, 204]):
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {}) | Deletes an association.
Deletes an association.
:param resource_uri: The identifier of the resource.
:type resource_uri: str
:param association_name: The name of the association. The name is case insensitive.
:type association_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: None, or the result of cls(response)
:rtype: None
:raises: ~azure.core.exceptions.HttpResponseError | sdk/monitor/azure-mgmt-monitor/azure/mgmt/monitor/v2021_04_01/aio/operations/_data_collection_rule_associations_operations.py | delete | cochi2/azure-sdk-for-python | 2,728 | python | async def delete(self, resource_uri: str, association_name: str, **kwargs: Any) -> None:
'Deletes an association.\n\n Deletes an association.\n\n :param resource_uri: The identifier of the resource.\n :type resource_uri: str\n :param association_name: The name of the association. The name is case insensitive.\n :type association_name: str\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: None, or the result of cls(response)\n :rtype: None\n :raises: ~azure.core.exceptions.HttpResponseError\n '
cls = kwargs.pop('cls', None)
error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError}
error_map.update(kwargs.pop('error_map', {}))
api_version = '2021-04-01'
accept = 'application/json'
url = self.delete.metadata['url']
path_format_arguments = {'resourceUri': self._serialize.url('resource_uri', resource_uri, 'str', skip_quote=True, min_length=1), 'associationName': self._serialize.url('association_name', association_name, 'str')}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query('api_version', api_version, 'str')
header_parameters = {}
header_parameters['Accept'] = self._serialize.header('accept', accept, 'str')
request = self._client.delete(url, query_parameters, header_parameters)
pipeline_response = (await self._client._pipeline.run(request, stream=False, **kwargs))
response = pipeline_response.http_response
if (response.status_code not in [200, 204]):
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {}) | async def delete(self, resource_uri: str, association_name: str, **kwargs: Any) -> None:
'Deletes an association.\n\n Deletes an association.\n\n :param resource_uri: The identifier of the resource.\n :type resource_uri: str\n :param association_name: The name of the association. The name is case insensitive.\n :type association_name: str\n :keyword callable cls: A custom type or function that will be passed the direct response\n :return: None, or the result of cls(response)\n :rtype: None\n :raises: ~azure.core.exceptions.HttpResponseError\n '
cls = kwargs.pop('cls', None)
error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError}
error_map.update(kwargs.pop('error_map', {}))
api_version = '2021-04-01'
accept = 'application/json'
url = self.delete.metadata['url']
path_format_arguments = {'resourceUri': self._serialize.url('resource_uri', resource_uri, 'str', skip_quote=True, min_length=1), 'associationName': self._serialize.url('association_name', association_name, 'str')}
url = self._client.format_url(url, **path_format_arguments)
query_parameters = {}
query_parameters['api-version'] = self._serialize.query('api_version', api_version, 'str')
header_parameters = {}
header_parameters['Accept'] = self._serialize.header('accept', accept, 'str')
request = self._client.delete(url, query_parameters, header_parameters)
pipeline_response = (await self._client._pipeline.run(request, stream=False, **kwargs))
response = pipeline_response.http_response
if (response.status_code not in [200, 204]):
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponseCommonV2, response)
raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})<|docstring|>Deletes an association.
Deletes an association.
:param resource_uri: The identifier of the resource.
:type resource_uri: str
:param association_name: The name of the association. The name is case insensitive.
:type association_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: None, or the result of cls(response)
:rtype: None
:raises: ~azure.core.exceptions.HttpResponseError<|endoftext|> |
a97dca17c2bc9270fb50902776a28ac4a960c5800a0b65c079dd644fee13a46b | def is_tool(name):
'Check whether `name` is on PATH and marked as executable.'
if (name == 'pysam'):
try:
import pysam
return True
except ImportError:
return False
return (which(name) is not None) | Check whether `name` is on PATH and marked as executable. | pycashier/_checks.py | is_tool | brocklab/pycashier | 1 | python | def is_tool(name):
if (name == 'pysam'):
try:
import pysam
return True
except ImportError:
return False
return (which(name) is not None) | def is_tool(name):
if (name == 'pysam'):
try:
import pysam
return True
except ImportError:
return False
return (which(name) is not None)<|docstring|>Check whether `name` is on PATH and marked as executable.<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.