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
|
---|---|---|---|---|---|---|---|---|---|
8a655791799b4fddaedc980287faba153a8dcc96d95554aff1849cae36133f0e | @bp.route('/readyz')
def readyz():
'Status check to verify the service is ready to respond.'
return (jsonify({'message': 'api is ready'}), 200) | Status check to verify the service is ready to respond. | mhr_api/src/mhr_api/resources/v1/ops.py | readyz | cameron-freshworks/ppr | 0 | python | @bp.route('/readyz')
def readyz():
return (jsonify({'message': 'api is ready'}), 200) | @bp.route('/readyz')
def readyz():
return (jsonify({'message': 'api is ready'}), 200)<|docstring|>Status check to verify the service is ready to respond.<|endoftext|> |
9a9964cdcf902d79ccfbcd5d48286c7ca5041ac9d2aab0c0feb9cff93c75335f | def remove(self, key: str) -> None:
'Safely remove an arbitrary key from telemetry metadata'
self._values.pop(key, None) | Safely remove an arbitrary key from telemetry metadata | servo/telemetry.py | remove | opsani/servox | 4 | python | def remove(self, key: str) -> None:
self._values.pop(key, None) | def remove(self, key: str) -> None:
self._values.pop(key, None)<|docstring|>Safely remove an arbitrary key from telemetry metadata<|endoftext|> |
3ef7bb3f01ccd5e6ecd2306ba8dfaa1edfe3d31ebac0fede234210900b62aebc | def sort_string(self, string: str) -> None:
'\n Test:\n "cat"\n "act"\n tca\n\n index cl c pi pc\n 1 0 \'a\' 0 \'c\'\n -1\n 2 2 \'t\' 1 \'c\'\n 0 \'a\'\n\n Quicksort - nlog n -->\n Pros:\n - unstability is fine\n - in place\n Cons:\n - right idea of a pivot, --> risking quadratic runtoime\n\n Selection and Bubble\n\n TimSort(can\'t use built-in)\n HeapSort(can\'t use built-in)\n\n\n '
for index in range(1, len(string)):
char = string[index]
current_loc = index
for previous_index in range((current_loc - 1), (- 1), (- 1)):
prev_char = string[previous_index]
if (char < prev_char):
string[previous_index] = char
string[current_loc] = prev_char
current_loc = previous_index
return string | Test:
"cat"
"act"
tca
index cl c pi pc
1 0 'a' 0 'c'
-1
2 2 't' 1 'c'
0 'a'
Quicksort - nlog n -->
Pros:
- unstability is fine
- in place
Cons:
- right idea of a pivot, --> risking quadratic runtoime
Selection and Bubble
TimSort(can't use built-in)
HeapSort(can't use built-in) | array_str_problems/is_unique.py | sort_string | UPstartDeveloper/Problem_Solving_Practice | 0 | python | def sort_string(self, string: str) -> None:
'\n Test:\n "cat"\n "act"\n tca\n\n index cl c pi pc\n 1 0 \'a\' 0 \'c\'\n -1\n 2 2 \'t\' 1 \'c\'\n 0 \'a\'\n\n Quicksort - nlog n -->\n Pros:\n - unstability is fine\n - in place\n Cons:\n - right idea of a pivot, --> risking quadratic runtoime\n\n Selection and Bubble\n\n TimSort(can\'t use built-in)\n HeapSort(can\'t use built-in)\n\n\n '
for index in range(1, len(string)):
char = string[index]
current_loc = index
for previous_index in range((current_loc - 1), (- 1), (- 1)):
prev_char = string[previous_index]
if (char < prev_char):
string[previous_index] = char
string[current_loc] = prev_char
current_loc = previous_index
return string | def sort_string(self, string: str) -> None:
'\n Test:\n "cat"\n "act"\n tca\n\n index cl c pi pc\n 1 0 \'a\' 0 \'c\'\n -1\n 2 2 \'t\' 1 \'c\'\n 0 \'a\'\n\n Quicksort - nlog n -->\n Pros:\n - unstability is fine\n - in place\n Cons:\n - right idea of a pivot, --> risking quadratic runtoime\n\n Selection and Bubble\n\n TimSort(can\'t use built-in)\n HeapSort(can\'t use built-in)\n\n\n '
for index in range(1, len(string)):
char = string[index]
current_loc = index
for previous_index in range((current_loc - 1), (- 1), (- 1)):
prev_char = string[previous_index]
if (char < prev_char):
string[previous_index] = char
string[current_loc] = prev_char
current_loc = previous_index
return string<|docstring|>Test:
"cat"
"act"
tca
index cl c pi pc
1 0 'a' 0 'c'
-1
2 2 't' 1 'c'
0 'a'
Quicksort - nlog n -->
Pros:
- unstability is fine
- in place
Cons:
- right idea of a pivot, --> risking quadratic runtoime
Selection and Bubble
TimSort(can't use built-in)
HeapSort(can't use built-in)<|endoftext|> |
816d725df754742c342fa50295a8420711752eabbc767d1716c1c62208323452 | def is_unique(self, string: str) -> bool:
'\n Time: O(n^2)\n Space: O(1)\n '
for index in range(len(string)):
char = string[index]
for previous in range((index - 1), (- 1), (- 1)):
if (char == string[previous]):
return False
return True | Time: O(n^2)
Space: O(1) | array_str_problems/is_unique.py | is_unique | UPstartDeveloper/Problem_Solving_Practice | 0 | python | def is_unique(self, string: str) -> bool:
'\n Time: O(n^2)\n Space: O(1)\n '
for index in range(len(string)):
char = string[index]
for previous in range((index - 1), (- 1), (- 1)):
if (char == string[previous]):
return False
return True | def is_unique(self, string: str) -> bool:
'\n Time: O(n^2)\n Space: O(1)\n '
for index in range(len(string)):
char = string[index]
for previous in range((index - 1), (- 1), (- 1)):
if (char == string[previous]):
return False
return True<|docstring|>Time: O(n^2)
Space: O(1)<|endoftext|> |
60f5d97e3c073fd5df1d859ab623d5d0b07fdfd2180d18313659beffa4073a33 | def l2norm(X, dim, eps=1e-08):
'\n L2-normalize columns of X\n '
norm = (torch.pow(X, 2).sum(dim=dim, keepdim=True).sqrt() + eps)
X = torch.div(X, norm)
return X | L2-normalize columns of X | models/nafs.py | l2norm | TencentYoutuResearch/PersonReID-YouReID | 29 | python | def l2norm(X, dim, eps=1e-08):
'\n \n '
norm = (torch.pow(X, 2).sum(dim=dim, keepdim=True).sqrt() + eps)
X = torch.div(X, norm)
return X | def l2norm(X, dim, eps=1e-08):
'\n \n '
norm = (torch.pow(X, 2).sum(dim=dim, keepdim=True).sqrt() + eps)
X = torch.div(X, norm)
return X<|docstring|>L2-normalize columns of X<|endoftext|> |
973e2648cc063b224d76ebcbc2373c61c29e91ab1547b84928d72db0d0262576 | def compute_similarity(x1, x2, dim=1, eps=1e-08):
'\n Returns cosine similarity between x1 and x2, computed along dim.\n '
w12 = torch.sum((x1 * x2), dim)
w1 = torch.norm(x1, 2, dim)
w2 = torch.norm(x2, 2, dim)
return (w12 / (w1 * w2).clamp(min=eps)).squeeze() | Returns cosine similarity between x1 and x2, computed along dim. | models/nafs.py | compute_similarity | TencentYoutuResearch/PersonReID-YouReID | 29 | python | def compute_similarity(x1, x2, dim=1, eps=1e-08):
'\n \n '
w12 = torch.sum((x1 * x2), dim)
w1 = torch.norm(x1, 2, dim)
w2 = torch.norm(x2, 2, dim)
return (w12 / (w1 * w2).clamp(min=eps)).squeeze() | def compute_similarity(x1, x2, dim=1, eps=1e-08):
'\n \n '
w12 = torch.sum((x1 * x2), dim)
w1 = torch.norm(x1, 2, dim)
w2 = torch.norm(x2, 2, dim)
return (w12 / (w1 * w2).clamp(min=eps)).squeeze()<|docstring|>Returns cosine similarity between x1 and x2, computed along dim.<|endoftext|> |
b0641da6fd6b8f16f23d040ff487fca0095ef6608c4a9fd9921d10223c96d41b | def func_attention_MxN(local_img_query, txt_i_key_expand, txt_i_value_expand, eps=1e-08):
'\n query: (batch, queryL, d)\n context: (batch, sourceL, d)\n '
(batch_size, queryL, sourceL) = (txt_i_key_expand.size(0), local_img_query.size(1), txt_i_key_expand.size(1))
local_img_query_norm = l2norm(local_img_query, dim=(- 1))
txt_i_key_expand_norm = l2norm(txt_i_key_expand, dim=(- 1))
local_img_queryT = torch.transpose(local_img_query_norm, 1, 2)
attn = torch.bmm(txt_i_key_expand_norm, local_img_queryT)
attn = nn.LeakyReLU(0.1)(attn)
attn = l2norm(attn, 2)
attn = torch.transpose(attn, 1, 2).contiguous()
attn = attn.view((batch_size * queryL), sourceL)
attn = nn.Softmax(dim=1)((attn * config.get('model_config')['lambda_softmax']))
attn = attn.view(batch_size, queryL, sourceL)
if (config.get('model_config')['focal_type'] == 'equal'):
funcH = focal_equal(attn, batch_size, queryL, sourceL)
elif (config.get('model_config')['focal_type'] == 'prob'):
funcH = focal_prob(attn, batch_size, queryL, sourceL)
else:
funcH = None
if (funcH is not None):
tmp_attn = (funcH * attn)
attn_sum = torch.sum(tmp_attn, dim=(- 1), keepdim=True)
attn = (tmp_attn / attn_sum)
txt_i_valueT = torch.transpose(txt_i_value_expand, 1, 2)
attnT = torch.transpose(attn, 1, 2).contiguous()
weightedContext = torch.bmm(txt_i_valueT, attnT)
weightedContext = torch.transpose(weightedContext, 1, 2)
return weightedContext | query: (batch, queryL, d)
context: (batch, sourceL, d) | models/nafs.py | func_attention_MxN | TencentYoutuResearch/PersonReID-YouReID | 29 | python | def func_attention_MxN(local_img_query, txt_i_key_expand, txt_i_value_expand, eps=1e-08):
'\n query: (batch, queryL, d)\n context: (batch, sourceL, d)\n '
(batch_size, queryL, sourceL) = (txt_i_key_expand.size(0), local_img_query.size(1), txt_i_key_expand.size(1))
local_img_query_norm = l2norm(local_img_query, dim=(- 1))
txt_i_key_expand_norm = l2norm(txt_i_key_expand, dim=(- 1))
local_img_queryT = torch.transpose(local_img_query_norm, 1, 2)
attn = torch.bmm(txt_i_key_expand_norm, local_img_queryT)
attn = nn.LeakyReLU(0.1)(attn)
attn = l2norm(attn, 2)
attn = torch.transpose(attn, 1, 2).contiguous()
attn = attn.view((batch_size * queryL), sourceL)
attn = nn.Softmax(dim=1)((attn * config.get('model_config')['lambda_softmax']))
attn = attn.view(batch_size, queryL, sourceL)
if (config.get('model_config')['focal_type'] == 'equal'):
funcH = focal_equal(attn, batch_size, queryL, sourceL)
elif (config.get('model_config')['focal_type'] == 'prob'):
funcH = focal_prob(attn, batch_size, queryL, sourceL)
else:
funcH = None
if (funcH is not None):
tmp_attn = (funcH * attn)
attn_sum = torch.sum(tmp_attn, dim=(- 1), keepdim=True)
attn = (tmp_attn / attn_sum)
txt_i_valueT = torch.transpose(txt_i_value_expand, 1, 2)
attnT = torch.transpose(attn, 1, 2).contiguous()
weightedContext = torch.bmm(txt_i_valueT, attnT)
weightedContext = torch.transpose(weightedContext, 1, 2)
return weightedContext | def func_attention_MxN(local_img_query, txt_i_key_expand, txt_i_value_expand, eps=1e-08):
'\n query: (batch, queryL, d)\n context: (batch, sourceL, d)\n '
(batch_size, queryL, sourceL) = (txt_i_key_expand.size(0), local_img_query.size(1), txt_i_key_expand.size(1))
local_img_query_norm = l2norm(local_img_query, dim=(- 1))
txt_i_key_expand_norm = l2norm(txt_i_key_expand, dim=(- 1))
local_img_queryT = torch.transpose(local_img_query_norm, 1, 2)
attn = torch.bmm(txt_i_key_expand_norm, local_img_queryT)
attn = nn.LeakyReLU(0.1)(attn)
attn = l2norm(attn, 2)
attn = torch.transpose(attn, 1, 2).contiguous()
attn = attn.view((batch_size * queryL), sourceL)
attn = nn.Softmax(dim=1)((attn * config.get('model_config')['lambda_softmax']))
attn = attn.view(batch_size, queryL, sourceL)
if (config.get('model_config')['focal_type'] == 'equal'):
funcH = focal_equal(attn, batch_size, queryL, sourceL)
elif (config.get('model_config')['focal_type'] == 'prob'):
funcH = focal_prob(attn, batch_size, queryL, sourceL)
else:
funcH = None
if (funcH is not None):
tmp_attn = (funcH * attn)
attn_sum = torch.sum(tmp_attn, dim=(- 1), keepdim=True)
attn = (tmp_attn / attn_sum)
txt_i_valueT = torch.transpose(txt_i_value_expand, 1, 2)
attnT = torch.transpose(attn, 1, 2).contiguous()
weightedContext = torch.bmm(txt_i_valueT, attnT)
weightedContext = torch.transpose(weightedContext, 1, 2)
return weightedContext<|docstring|>query: (batch, queryL, d)
context: (batch, sourceL, d)<|endoftext|> |
2cd4eaaf583c78d25ef4d4b9dbd73afd391ac48aef82e26210fe801ad846c8e3 | def focal_equal(attn, batch_size, queryL, sourceL):
'\n consider the confidence g(x) for each fragment as equal\n sigma_{j} (xi - xj) = sigma_{j} xi - sigma_{j} xj\n attn: (batch, queryL, sourceL)\n '
funcF = ((attn * sourceL) - torch.sum(attn, dim=(- 1), keepdim=True))
fattn = torch.where((funcF > 0), torch.ones_like(attn), torch.zeros_like(attn))
return fattn | consider the confidence g(x) for each fragment as equal
sigma_{j} (xi - xj) = sigma_{j} xi - sigma_{j} xj
attn: (batch, queryL, sourceL) | models/nafs.py | focal_equal | TencentYoutuResearch/PersonReID-YouReID | 29 | python | def focal_equal(attn, batch_size, queryL, sourceL):
'\n consider the confidence g(x) for each fragment as equal\n sigma_{j} (xi - xj) = sigma_{j} xi - sigma_{j} xj\n attn: (batch, queryL, sourceL)\n '
funcF = ((attn * sourceL) - torch.sum(attn, dim=(- 1), keepdim=True))
fattn = torch.where((funcF > 0), torch.ones_like(attn), torch.zeros_like(attn))
return fattn | def focal_equal(attn, batch_size, queryL, sourceL):
'\n consider the confidence g(x) for each fragment as equal\n sigma_{j} (xi - xj) = sigma_{j} xi - sigma_{j} xj\n attn: (batch, queryL, sourceL)\n '
funcF = ((attn * sourceL) - torch.sum(attn, dim=(- 1), keepdim=True))
fattn = torch.where((funcF > 0), torch.ones_like(attn), torch.zeros_like(attn))
return fattn<|docstring|>consider the confidence g(x) for each fragment as equal
sigma_{j} (xi - xj) = sigma_{j} xi - sigma_{j} xj
attn: (batch, queryL, sourceL)<|endoftext|> |
e59be8cd01f000216770f08a326c4e10f62fd95c17071d7a293cb3448e0eff29 | def focal_prob(attn, batch_size, queryL, sourceL):
'\n consider the confidence g(x) for each fragment as the sqrt\n of their similarity probability to the query fragment\n sigma_{j} (xi - xj)gj = sigma_{j} xi*gj - sigma_{j} xj*gj\n attn: (batch, queryL, sourceL)\n '
xi = attn.unsqueeze((- 1)).contiguous()
xj = attn.unsqueeze(2).contiguous()
xj_confi = torch.sqrt(xj)
xi = xi.view((batch_size * queryL), sourceL, 1)
xj = xj.view((batch_size * queryL), 1, sourceL)
xj_confi = xj_confi.view((batch_size * queryL), 1, sourceL)
term1 = torch.bmm(xi, xj_confi)
term2 = (xj * xj_confi)
funcF = torch.sum((term1 - term2), dim=(- 1))
funcF = funcF.view(batch_size, queryL, sourceL)
fattn = torch.where((funcF > 0), torch.ones_like(attn), torch.zeros_like(attn))
return fattn | consider the confidence g(x) for each fragment as the sqrt
of their similarity probability to the query fragment
sigma_{j} (xi - xj)gj = sigma_{j} xi*gj - sigma_{j} xj*gj
attn: (batch, queryL, sourceL) | models/nafs.py | focal_prob | TencentYoutuResearch/PersonReID-YouReID | 29 | python | def focal_prob(attn, batch_size, queryL, sourceL):
'\n consider the confidence g(x) for each fragment as the sqrt\n of their similarity probability to the query fragment\n sigma_{j} (xi - xj)gj = sigma_{j} xi*gj - sigma_{j} xj*gj\n attn: (batch, queryL, sourceL)\n '
xi = attn.unsqueeze((- 1)).contiguous()
xj = attn.unsqueeze(2).contiguous()
xj_confi = torch.sqrt(xj)
xi = xi.view((batch_size * queryL), sourceL, 1)
xj = xj.view((batch_size * queryL), 1, sourceL)
xj_confi = xj_confi.view((batch_size * queryL), 1, sourceL)
term1 = torch.bmm(xi, xj_confi)
term2 = (xj * xj_confi)
funcF = torch.sum((term1 - term2), dim=(- 1))
funcF = funcF.view(batch_size, queryL, sourceL)
fattn = torch.where((funcF > 0), torch.ones_like(attn), torch.zeros_like(attn))
return fattn | def focal_prob(attn, batch_size, queryL, sourceL):
'\n consider the confidence g(x) for each fragment as the sqrt\n of their similarity probability to the query fragment\n sigma_{j} (xi - xj)gj = sigma_{j} xi*gj - sigma_{j} xj*gj\n attn: (batch, queryL, sourceL)\n '
xi = attn.unsqueeze((- 1)).contiguous()
xj = attn.unsqueeze(2).contiguous()
xj_confi = torch.sqrt(xj)
xi = xi.view((batch_size * queryL), sourceL, 1)
xj = xj.view((batch_size * queryL), 1, sourceL)
xj_confi = xj_confi.view((batch_size * queryL), 1, sourceL)
term1 = torch.bmm(xi, xj_confi)
term2 = (xj * xj_confi)
funcF = torch.sum((term1 - term2), dim=(- 1))
funcF = funcF.view(batch_size, queryL, sourceL)
fattn = torch.where((funcF > 0), torch.ones_like(attn), torch.zeros_like(attn))
return fattn<|docstring|>consider the confidence g(x) for each fragment as the sqrt
of their similarity probability to the query fragment
sigma_{j} (xi - xj)gj = sigma_{j} xi*gj - sigma_{j} xj*gj
attn: (batch, queryL, sourceL)<|endoftext|> |
0f20e175353547fc029c2ba0e0125666c875d6baf054b84358d51202429713cc | def compute_weiTexts(local_img_query, local_img_value, local_text_key, local_text_value, text_length):
'\n Compute weighted text embeddings\n :param image_embeddings: Tensor with dtype torch.float32, [n_img, n_region, d]\n :param text_embeddings: Tensor with dtype torch.float32, [n_txt, n_word, d]\n :param text_length: list, contain length of each sentence, [batch_size]\n :param labels: Tensor with dtype torch.int32, [batch_size]\n :return: i2t_similarities: Tensor, [n_img, n_txt]\n t2i_similarities: Tensor, [n_img, n_txt]\n '
n_img = local_img_query.shape[0]
n_txt = local_text_key.shape[0]
t2i_similarities = []
i2t_similarities = []
for i in range(n_txt):
n_word = text_length[i]
txt_i_key = local_text_key[(i, :n_word, :)].unsqueeze(0).contiguous()
txt_i_value = local_text_value[(i, :n_word, :)].unsqueeze(0).contiguous()
txt_i_key_expand = txt_i_key.repeat(n_img, 1, 1)
txt_i_value_expand = txt_i_value.repeat(n_img, 1, 1)
weiText = func_attention_MxN(local_img_query, txt_i_key_expand, txt_i_value_expand)
weiText = l2norm(weiText, dim=2)
i2t_sim = compute_similarity(local_img_value, weiText, dim=2)
i2t_sim = i2t_sim.mean(dim=1, keepdim=True)
i2t_similarities.append(i2t_sim)
weiImage = func_attention_MxN(txt_i_key_expand, local_img_query, local_img_value)
weiImage = l2norm(weiImage, dim=2)
t2i_sim = compute_similarity(txt_i_value_expand, weiImage, dim=2)
t2i_sim = t2i_sim.mean(dim=1, keepdim=True)
t2i_similarities.append(t2i_sim)
i2t_similarities = torch.cat(i2t_similarities, 1)
t2i_similarities = torch.cat(t2i_similarities, 1)
return (i2t_similarities, t2i_similarities) | Compute weighted text embeddings
:param image_embeddings: Tensor with dtype torch.float32, [n_img, n_region, d]
:param text_embeddings: Tensor with dtype torch.float32, [n_txt, n_word, d]
:param text_length: list, contain length of each sentence, [batch_size]
:param labels: Tensor with dtype torch.int32, [batch_size]
:return: i2t_similarities: Tensor, [n_img, n_txt]
t2i_similarities: Tensor, [n_img, n_txt] | models/nafs.py | compute_weiTexts | TencentYoutuResearch/PersonReID-YouReID | 29 | python | def compute_weiTexts(local_img_query, local_img_value, local_text_key, local_text_value, text_length):
'\n Compute weighted text embeddings\n :param image_embeddings: Tensor with dtype torch.float32, [n_img, n_region, d]\n :param text_embeddings: Tensor with dtype torch.float32, [n_txt, n_word, d]\n :param text_length: list, contain length of each sentence, [batch_size]\n :param labels: Tensor with dtype torch.int32, [batch_size]\n :return: i2t_similarities: Tensor, [n_img, n_txt]\n t2i_similarities: Tensor, [n_img, n_txt]\n '
n_img = local_img_query.shape[0]
n_txt = local_text_key.shape[0]
t2i_similarities = []
i2t_similarities = []
for i in range(n_txt):
n_word = text_length[i]
txt_i_key = local_text_key[(i, :n_word, :)].unsqueeze(0).contiguous()
txt_i_value = local_text_value[(i, :n_word, :)].unsqueeze(0).contiguous()
txt_i_key_expand = txt_i_key.repeat(n_img, 1, 1)
txt_i_value_expand = txt_i_value.repeat(n_img, 1, 1)
weiText = func_attention_MxN(local_img_query, txt_i_key_expand, txt_i_value_expand)
weiText = l2norm(weiText, dim=2)
i2t_sim = compute_similarity(local_img_value, weiText, dim=2)
i2t_sim = i2t_sim.mean(dim=1, keepdim=True)
i2t_similarities.append(i2t_sim)
weiImage = func_attention_MxN(txt_i_key_expand, local_img_query, local_img_value)
weiImage = l2norm(weiImage, dim=2)
t2i_sim = compute_similarity(txt_i_value_expand, weiImage, dim=2)
t2i_sim = t2i_sim.mean(dim=1, keepdim=True)
t2i_similarities.append(t2i_sim)
i2t_similarities = torch.cat(i2t_similarities, 1)
t2i_similarities = torch.cat(t2i_similarities, 1)
return (i2t_similarities, t2i_similarities) | def compute_weiTexts(local_img_query, local_img_value, local_text_key, local_text_value, text_length):
'\n Compute weighted text embeddings\n :param image_embeddings: Tensor with dtype torch.float32, [n_img, n_region, d]\n :param text_embeddings: Tensor with dtype torch.float32, [n_txt, n_word, d]\n :param text_length: list, contain length of each sentence, [batch_size]\n :param labels: Tensor with dtype torch.int32, [batch_size]\n :return: i2t_similarities: Tensor, [n_img, n_txt]\n t2i_similarities: Tensor, [n_img, n_txt]\n '
n_img = local_img_query.shape[0]
n_txt = local_text_key.shape[0]
t2i_similarities = []
i2t_similarities = []
for i in range(n_txt):
n_word = text_length[i]
txt_i_key = local_text_key[(i, :n_word, :)].unsqueeze(0).contiguous()
txt_i_value = local_text_value[(i, :n_word, :)].unsqueeze(0).contiguous()
txt_i_key_expand = txt_i_key.repeat(n_img, 1, 1)
txt_i_value_expand = txt_i_value.repeat(n_img, 1, 1)
weiText = func_attention_MxN(local_img_query, txt_i_key_expand, txt_i_value_expand)
weiText = l2norm(weiText, dim=2)
i2t_sim = compute_similarity(local_img_value, weiText, dim=2)
i2t_sim = i2t_sim.mean(dim=1, keepdim=True)
i2t_similarities.append(i2t_sim)
weiImage = func_attention_MxN(txt_i_key_expand, local_img_query, local_img_value)
weiImage = l2norm(weiImage, dim=2)
t2i_sim = compute_similarity(txt_i_value_expand, weiImage, dim=2)
t2i_sim = t2i_sim.mean(dim=1, keepdim=True)
t2i_similarities.append(t2i_sim)
i2t_similarities = torch.cat(i2t_similarities, 1)
t2i_similarities = torch.cat(t2i_similarities, 1)
return (i2t_similarities, t2i_similarities)<|docstring|>Compute weighted text embeddings
:param image_embeddings: Tensor with dtype torch.float32, [n_img, n_region, d]
:param text_embeddings: Tensor with dtype torch.float32, [n_txt, n_word, d]
:param text_length: list, contain length of each sentence, [batch_size]
:param labels: Tensor with dtype torch.int32, [batch_size]
:return: i2t_similarities: Tensor, [n_img, n_txt]
t2i_similarities: Tensor, [n_img, n_txt]<|endoftext|> |
71f2fbcd4cd295bc6b6eb12eb3cfc67a6d30b386244cf2e755ed7930852149ba | def conv3x3(in_planes, out_planes, stride=1):
'3x3 convolution with padding'
'Imported from https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py L26 - L29'
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False) | 3x3 convolution with padding | models/nafs.py | conv3x3 | TencentYoutuResearch/PersonReID-YouReID | 29 | python | def conv3x3(in_planes, out_planes, stride=1):
'Imported from https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py L26 - L29'
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False) | def conv3x3(in_planes, out_planes, stride=1):
'Imported from https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py L26 - L29'
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)<|docstring|>3x3 convolution with padding<|endoftext|> |
b6482a1d9025898a7cbb0490806609df8637e5f600fc4193cba38bdbf2c332ae | def conv1x1(in_planes, out_planes, stride=1):
'1x1 convolution'
'Imported from https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py L32 - L34'
return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False) | 1x1 convolution | models/nafs.py | conv1x1 | TencentYoutuResearch/PersonReID-YouReID | 29 | python | def conv1x1(in_planes, out_planes, stride=1):
'Imported from https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py L32 - L34'
return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False) | def conv1x1(in_planes, out_planes, stride=1):
'Imported from https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py L32 - L34'
return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)<|docstring|>1x1 convolution<|endoftext|> |
ae9e824bf713ae8aa049bb58a12f1c7bea50ba2af7ffa04453759d8285a2fd39 | def get_index_pair_list(self, x, permu):
'\n Split feature map according to height dimension.\n :param x: Tensor with dtype torch.float32, [batchsize, num_channels, height, width]\n :param permu: List with integers, e.g. [0, 1, 2]\n \n :return: List of pairs [(start1, end1), (start2, end2)...] \n '
(batchsize, num_channels, height, width) = x.data.size()
number_slice = len(permu)
height_per_slice = (height // number_slice)
index_pair_list = [((height_per_slice * i), (height_per_slice * (i + 1))) for i in range((number_slice - 1))]
index_pair_list.append(((height_per_slice * (number_slice - 1)), height))
return index_pair_list | Split feature map according to height dimension.
:param x: Tensor with dtype torch.float32, [batchsize, num_channels, height, width]
:param permu: List with integers, e.g. [0, 1, 2]
:return: List of pairs [(start1, end1), (start2, end2)...] | models/nafs.py | get_index_pair_list | TencentYoutuResearch/PersonReID-YouReID | 29 | python | def get_index_pair_list(self, x, permu):
'\n Split feature map according to height dimension.\n :param x: Tensor with dtype torch.float32, [batchsize, num_channels, height, width]\n :param permu: List with integers, e.g. [0, 1, 2]\n \n :return: List of pairs [(start1, end1), (start2, end2)...] \n '
(batchsize, num_channels, height, width) = x.data.size()
number_slice = len(permu)
height_per_slice = (height // number_slice)
index_pair_list = [((height_per_slice * i), (height_per_slice * (i + 1))) for i in range((number_slice - 1))]
index_pair_list.append(((height_per_slice * (number_slice - 1)), height))
return index_pair_list | def get_index_pair_list(self, x, permu):
'\n Split feature map according to height dimension.\n :param x: Tensor with dtype torch.float32, [batchsize, num_channels, height, width]\n :param permu: List with integers, e.g. [0, 1, 2]\n \n :return: List of pairs [(start1, end1), (start2, end2)...] \n '
(batchsize, num_channels, height, width) = x.data.size()
number_slice = len(permu)
height_per_slice = (height // number_slice)
index_pair_list = [((height_per_slice * i), (height_per_slice * (i + 1))) for i in range((number_slice - 1))]
index_pair_list.append(((height_per_slice * (number_slice - 1)), height))
return index_pair_list<|docstring|>Split feature map according to height dimension.
:param x: Tensor with dtype torch.float32, [batchsize, num_channels, height, width]
:param permu: List with integers, e.g. [0, 1, 2]
:return: List of pairs [(start1, end1), (start2, end2)...]<|endoftext|> |
488de074bd08745a129f8ca33840ec20eaf9ca85386371661b9b73441a93e717 | def height_shuffle(self, x, permu):
'\n Shuffle the feature map according to height dimension.\n '
(batchsize, num_channels, height, width) = x.data.size()
result = torch.zeros(batchsize, num_channels, height, width).cuda()
number_slice = len(permu)
height_per_slice = (height // number_slice)
index_pair_list = [((height_per_slice * i), (height_per_slice * (i + 1))) for i in range((number_slice - 1))]
index_pair_list.append(((height_per_slice * (number_slice - 1)), height))
index_pair_list_shuffled = []
for i in range(number_slice):
index_pair_list_shuffled.append(index_pair_list[permu[i]])
start = 0
for i in range(len(index_pair_list_shuffled)):
index_pair = index_pair_list_shuffled[i]
length = (index_pair[1] - index_pair[0])
result[(:, :, start:(start + length), :)] = x[(:, :, index_pair[0]:index_pair[1], :)]
start = (start + length)
return result | Shuffle the feature map according to height dimension. | models/nafs.py | height_shuffle | TencentYoutuResearch/PersonReID-YouReID | 29 | python | def height_shuffle(self, x, permu):
'\n \n '
(batchsize, num_channels, height, width) = x.data.size()
result = torch.zeros(batchsize, num_channels, height, width).cuda()
number_slice = len(permu)
height_per_slice = (height // number_slice)
index_pair_list = [((height_per_slice * i), (height_per_slice * (i + 1))) for i in range((number_slice - 1))]
index_pair_list.append(((height_per_slice * (number_slice - 1)), height))
index_pair_list_shuffled = []
for i in range(number_slice):
index_pair_list_shuffled.append(index_pair_list[permu[i]])
start = 0
for i in range(len(index_pair_list_shuffled)):
index_pair = index_pair_list_shuffled[i]
length = (index_pair[1] - index_pair[0])
result[(:, :, start:(start + length), :)] = x[(:, :, index_pair[0]:index_pair[1], :)]
start = (start + length)
return result | def height_shuffle(self, x, permu):
'\n \n '
(batchsize, num_channels, height, width) = x.data.size()
result = torch.zeros(batchsize, num_channels, height, width).cuda()
number_slice = len(permu)
height_per_slice = (height // number_slice)
index_pair_list = [((height_per_slice * i), (height_per_slice * (i + 1))) for i in range((number_slice - 1))]
index_pair_list.append(((height_per_slice * (number_slice - 1)), height))
index_pair_list_shuffled = []
for i in range(number_slice):
index_pair_list_shuffled.append(index_pair_list[permu[i]])
start = 0
for i in range(len(index_pair_list_shuffled)):
index_pair = index_pair_list_shuffled[i]
length = (index_pair[1] - index_pair[0])
result[(:, :, start:(start + length), :)] = x[(:, :, index_pair[0]:index_pair[1], :)]
start = (start + length)
return result<|docstring|>Shuffle the feature map according to height dimension.<|endoftext|> |
8d5c7b4017039b3c2a76237f46a59f1e6a1e85d2171fe523deff7f85db3ad45a | def recover_shuffle(self, x, permu):
'\n Recover the feature map to the original order.\n '
dic = {}
recover_permu = []
for i in range(len(permu)):
dic[permu[i]] = i
all_key = list(dic.keys())
all_key.sort()
for i in range(len(all_key)):
recover_permu.append(dic[all_key[i]])
return self.height_shuffle(x, recover_permu) | Recover the feature map to the original order. | models/nafs.py | recover_shuffle | TencentYoutuResearch/PersonReID-YouReID | 29 | python | def recover_shuffle(self, x, permu):
'\n \n '
dic = {}
recover_permu = []
for i in range(len(permu)):
dic[permu[i]] = i
all_key = list(dic.keys())
all_key.sort()
for i in range(len(all_key)):
recover_permu.append(dic[all_key[i]])
return self.height_shuffle(x, recover_permu) | def recover_shuffle(self, x, permu):
'\n \n '
dic = {}
recover_permu = []
for i in range(len(permu)):
dic[permu[i]] = i
all_key = list(dic.keys())
all_key.sort()
for i in range(len(all_key)):
recover_permu.append(dic[all_key[i]])
return self.height_shuffle(x, recover_permu)<|docstring|>Recover the feature map to the original order.<|endoftext|> |
437e61eeddff389833df4570443e425d3e73e0fa221bc1ced6676abcec29cf6e | def compute_cmpc_loss(self, image_embeddings, text_embeddings, labels):
'\n Cross-Modal Projection Classfication loss(CMPC)\n :param image_embeddings: Tensor with dtype torch.float32\n :param text_embeddings: Tensor with dtype torch.float32\n :param labels: Tensor with dtype torch.int32\n :return:\n '
criterion = nn.CrossEntropyLoss(reduction='mean')
self.W_norm = F.normalize(self.W, p=2, dim=0)
image_norm = (image_embeddings / image_embeddings.norm(dim=1, keepdim=True))
text_norm = (text_embeddings / text_embeddings.norm(dim=1, keepdim=True))
image_proj_text = (torch.sum((image_embeddings * text_norm), dim=1, keepdim=True) * text_norm)
text_proj_image = (torch.sum((text_embeddings * image_norm), dim=1, keepdim=True) * image_norm)
image_logits = torch.matmul(image_proj_text, self.W_norm)
text_logits = torch.matmul(text_proj_image, self.W_norm)
'\n ipt_loss = criterion(input=image_logits, target=labels)\n tpi_loss = criterion(input=text_logits, target=labels)\n cmpc_loss = ipt_loss + tpi_loss\n '
cmpc_loss = (criterion(image_logits, labels) + criterion(text_logits, labels))
image_pred = torch.argmax(image_logits, dim=1)
text_pred = torch.argmax(text_logits, dim=1)
image_precision = torch.mean((image_pred == labels).float())
text_precision = torch.mean((text_pred == labels).float())
return (cmpc_loss, image_precision, text_precision) | Cross-Modal Projection Classfication loss(CMPC)
:param image_embeddings: Tensor with dtype torch.float32
:param text_embeddings: Tensor with dtype torch.float32
:param labels: Tensor with dtype torch.int32
:return: | models/nafs.py | compute_cmpc_loss | TencentYoutuResearch/PersonReID-YouReID | 29 | python | def compute_cmpc_loss(self, image_embeddings, text_embeddings, labels):
'\n Cross-Modal Projection Classfication loss(CMPC)\n :param image_embeddings: Tensor with dtype torch.float32\n :param text_embeddings: Tensor with dtype torch.float32\n :param labels: Tensor with dtype torch.int32\n :return:\n '
criterion = nn.CrossEntropyLoss(reduction='mean')
self.W_norm = F.normalize(self.W, p=2, dim=0)
image_norm = (image_embeddings / image_embeddings.norm(dim=1, keepdim=True))
text_norm = (text_embeddings / text_embeddings.norm(dim=1, keepdim=True))
image_proj_text = (torch.sum((image_embeddings * text_norm), dim=1, keepdim=True) * text_norm)
text_proj_image = (torch.sum((text_embeddings * image_norm), dim=1, keepdim=True) * image_norm)
image_logits = torch.matmul(image_proj_text, self.W_norm)
text_logits = torch.matmul(text_proj_image, self.W_norm)
'\n ipt_loss = criterion(input=image_logits, target=labels)\n tpi_loss = criterion(input=text_logits, target=labels)\n cmpc_loss = ipt_loss + tpi_loss\n '
cmpc_loss = (criterion(image_logits, labels) + criterion(text_logits, labels))
image_pred = torch.argmax(image_logits, dim=1)
text_pred = torch.argmax(text_logits, dim=1)
image_precision = torch.mean((image_pred == labels).float())
text_precision = torch.mean((text_pred == labels).float())
return (cmpc_loss, image_precision, text_precision) | def compute_cmpc_loss(self, image_embeddings, text_embeddings, labels):
'\n Cross-Modal Projection Classfication loss(CMPC)\n :param image_embeddings: Tensor with dtype torch.float32\n :param text_embeddings: Tensor with dtype torch.float32\n :param labels: Tensor with dtype torch.int32\n :return:\n '
criterion = nn.CrossEntropyLoss(reduction='mean')
self.W_norm = F.normalize(self.W, p=2, dim=0)
image_norm = (image_embeddings / image_embeddings.norm(dim=1, keepdim=True))
text_norm = (text_embeddings / text_embeddings.norm(dim=1, keepdim=True))
image_proj_text = (torch.sum((image_embeddings * text_norm), dim=1, keepdim=True) * text_norm)
text_proj_image = (torch.sum((text_embeddings * image_norm), dim=1, keepdim=True) * image_norm)
image_logits = torch.matmul(image_proj_text, self.W_norm)
text_logits = torch.matmul(text_proj_image, self.W_norm)
'\n ipt_loss = criterion(input=image_logits, target=labels)\n tpi_loss = criterion(input=text_logits, target=labels)\n cmpc_loss = ipt_loss + tpi_loss\n '
cmpc_loss = (criterion(image_logits, labels) + criterion(text_logits, labels))
image_pred = torch.argmax(image_logits, dim=1)
text_pred = torch.argmax(text_logits, dim=1)
image_precision = torch.mean((image_pred == labels).float())
text_precision = torch.mean((text_pred == labels).float())
return (cmpc_loss, image_precision, text_precision)<|docstring|>Cross-Modal Projection Classfication loss(CMPC)
:param image_embeddings: Tensor with dtype torch.float32
:param text_embeddings: Tensor with dtype torch.float32
:param labels: Tensor with dtype torch.int32
:return:<|endoftext|> |
fdced31a79afef6404ceeefa5db87de1c8116ac23b3f1e780200c0e1b302bded | def compute_cmpm_loss(self, image_embeddings, text_embeddings, labels):
'\n Cross-Modal Projection Matching Loss(CMPM)\n :param image_embeddings: Tensor with dtype torch.float32\n :param text_embeddings: Tensor with dtype torch.float32\n :param labels: Tensor with dtype torch.int32\n :return:\n i2t_loss: cmpm loss for image projected to text\n t2i_loss: cmpm loss for text projected to image\n pos_avg_sim: average cosine-similarity for positive pairs\n neg_avg_sim: averate cosine-similarity for negative pairs\n '
batch_size = image_embeddings.shape[0]
labels_reshape = torch.reshape(labels, (batch_size, 1))
labels_dist = (labels_reshape - labels_reshape.t())
labels_mask = (labels_dist == 0)
image_norm = (image_embeddings / image_embeddings.norm(dim=1, keepdim=True))
text_norm = (text_embeddings / text_embeddings.norm(dim=1, keepdim=True))
image_proj_text = torch.matmul(image_embeddings, text_norm.t())
text_proj_image = torch.matmul(text_embeddings, image_norm.t())
labels_mask_norm = (labels_mask.float() / labels_mask.float().norm(dim=1))
i2t_pred = F.softmax(image_proj_text, dim=1)
i2t_loss = (i2t_pred * (F.log_softmax(image_proj_text, dim=1) - torch.log((labels_mask_norm + self.epsilon))))
t2i_pred = F.softmax(text_proj_image, dim=1)
t2i_loss = (t2i_pred * (F.log_softmax(text_proj_image, dim=1) - torch.log((labels_mask_norm + self.epsilon))))
cmpm_loss = (torch.mean(torch.sum(i2t_loss, dim=1)) + torch.mean(torch.sum(t2i_loss, dim=1)))
sim_cos = torch.matmul(image_norm, text_norm.t())
pos_avg_sim = torch.mean(torch.masked_select(sim_cos, labels_mask))
neg_avg_sim = torch.mean(torch.masked_select(sim_cos, (labels_mask == 0)))
return (cmpm_loss, pos_avg_sim, neg_avg_sim) | Cross-Modal Projection Matching Loss(CMPM)
:param image_embeddings: Tensor with dtype torch.float32
:param text_embeddings: Tensor with dtype torch.float32
:param labels: Tensor with dtype torch.int32
:return:
i2t_loss: cmpm loss for image projected to text
t2i_loss: cmpm loss for text projected to image
pos_avg_sim: average cosine-similarity for positive pairs
neg_avg_sim: averate cosine-similarity for negative pairs | models/nafs.py | compute_cmpm_loss | TencentYoutuResearch/PersonReID-YouReID | 29 | python | def compute_cmpm_loss(self, image_embeddings, text_embeddings, labels):
'\n Cross-Modal Projection Matching Loss(CMPM)\n :param image_embeddings: Tensor with dtype torch.float32\n :param text_embeddings: Tensor with dtype torch.float32\n :param labels: Tensor with dtype torch.int32\n :return:\n i2t_loss: cmpm loss for image projected to text\n t2i_loss: cmpm loss for text projected to image\n pos_avg_sim: average cosine-similarity for positive pairs\n neg_avg_sim: averate cosine-similarity for negative pairs\n '
batch_size = image_embeddings.shape[0]
labels_reshape = torch.reshape(labels, (batch_size, 1))
labels_dist = (labels_reshape - labels_reshape.t())
labels_mask = (labels_dist == 0)
image_norm = (image_embeddings / image_embeddings.norm(dim=1, keepdim=True))
text_norm = (text_embeddings / text_embeddings.norm(dim=1, keepdim=True))
image_proj_text = torch.matmul(image_embeddings, text_norm.t())
text_proj_image = torch.matmul(text_embeddings, image_norm.t())
labels_mask_norm = (labels_mask.float() / labels_mask.float().norm(dim=1))
i2t_pred = F.softmax(image_proj_text, dim=1)
i2t_loss = (i2t_pred * (F.log_softmax(image_proj_text, dim=1) - torch.log((labels_mask_norm + self.epsilon))))
t2i_pred = F.softmax(text_proj_image, dim=1)
t2i_loss = (t2i_pred * (F.log_softmax(text_proj_image, dim=1) - torch.log((labels_mask_norm + self.epsilon))))
cmpm_loss = (torch.mean(torch.sum(i2t_loss, dim=1)) + torch.mean(torch.sum(t2i_loss, dim=1)))
sim_cos = torch.matmul(image_norm, text_norm.t())
pos_avg_sim = torch.mean(torch.masked_select(sim_cos, labels_mask))
neg_avg_sim = torch.mean(torch.masked_select(sim_cos, (labels_mask == 0)))
return (cmpm_loss, pos_avg_sim, neg_avg_sim) | def compute_cmpm_loss(self, image_embeddings, text_embeddings, labels):
'\n Cross-Modal Projection Matching Loss(CMPM)\n :param image_embeddings: Tensor with dtype torch.float32\n :param text_embeddings: Tensor with dtype torch.float32\n :param labels: Tensor with dtype torch.int32\n :return:\n i2t_loss: cmpm loss for image projected to text\n t2i_loss: cmpm loss for text projected to image\n pos_avg_sim: average cosine-similarity for positive pairs\n neg_avg_sim: averate cosine-similarity for negative pairs\n '
batch_size = image_embeddings.shape[0]
labels_reshape = torch.reshape(labels, (batch_size, 1))
labels_dist = (labels_reshape - labels_reshape.t())
labels_mask = (labels_dist == 0)
image_norm = (image_embeddings / image_embeddings.norm(dim=1, keepdim=True))
text_norm = (text_embeddings / text_embeddings.norm(dim=1, keepdim=True))
image_proj_text = torch.matmul(image_embeddings, text_norm.t())
text_proj_image = torch.matmul(text_embeddings, image_norm.t())
labels_mask_norm = (labels_mask.float() / labels_mask.float().norm(dim=1))
i2t_pred = F.softmax(image_proj_text, dim=1)
i2t_loss = (i2t_pred * (F.log_softmax(image_proj_text, dim=1) - torch.log((labels_mask_norm + self.epsilon))))
t2i_pred = F.softmax(text_proj_image, dim=1)
t2i_loss = (t2i_pred * (F.log_softmax(text_proj_image, dim=1) - torch.log((labels_mask_norm + self.epsilon))))
cmpm_loss = (torch.mean(torch.sum(i2t_loss, dim=1)) + torch.mean(torch.sum(t2i_loss, dim=1)))
sim_cos = torch.matmul(image_norm, text_norm.t())
pos_avg_sim = torch.mean(torch.masked_select(sim_cos, labels_mask))
neg_avg_sim = torch.mean(torch.masked_select(sim_cos, (labels_mask == 0)))
return (cmpm_loss, pos_avg_sim, neg_avg_sim)<|docstring|>Cross-Modal Projection Matching Loss(CMPM)
:param image_embeddings: Tensor with dtype torch.float32
:param text_embeddings: Tensor with dtype torch.float32
:param labels: Tensor with dtype torch.int32
:return:
i2t_loss: cmpm loss for image projected to text
t2i_loss: cmpm loss for text projected to image
pos_avg_sim: average cosine-similarity for positive pairs
neg_avg_sim: averate cosine-similarity for negative pairs<|endoftext|> |
34993951c26366c7b2d046b26e618e5d6fe8af92cd3b707e244db14f29b7c150 | def Signature(*args, **kwargs):
"\n ``@Signature`` is a decorator to implement the function-argument annotations in Python-2.7,\n as needed by the ``@Function`` decorator.\n This is only needed when you have not yet migrated to Python 3.x.\n\n Note: Although this is aimed at enabling ``@Function`` syntax with type annotations\n in Python 2.7, ``@Signature`` is independent of CNTK and can be used for any argument annotation.\n\n Args:\n *args: types of arguments of the function that this decorator is applied to, in the same order.\n **kwargs: types of arguments with optional names, e.g. `x=Tensor[42]`. Use this second form for\n longer argument lists.\n\n Example::\n\n # Python 3:\n @Function\n def f(x: Tensor[42]):\n return sigmoid(x)\n\n # Python 2.7:\n @Function\n @Signature(Tensor[42])\n def f(x):\n return sigmoid(x)\n\n # note that this:\n @Function\n @Signature(x:int)\n def sqr(x):\n return x*x\n # is identical to:\n def sqr(x):\n return x*x\n sqr.__annotations__ = {'x': int}``\n "
def add_annotations(f):
(param_names, annotations) = get_python_function_arguments(f)
if annotations:
raise ValueError('@Signature cannot be applied to functions that already have annotations')
annotations = {}
if ((len(args) + len(kwargs)) != len(param_names)):
raise TypeError('{} annotations provided for function to be decorated, but function has {} parameters'.format((len(args) + len(kwargs)), len(param_names)))
params_dict = {name: name for name in param_names}
f.__annotations__ = map_function_arguments(param_names, params_dict, *args, **kwargs)
return f
return add_annotations | ``@Signature`` is a decorator to implement the function-argument annotations in Python-2.7,
as needed by the ``@Function`` decorator.
This is only needed when you have not yet migrated to Python 3.x.
Note: Although this is aimed at enabling ``@Function`` syntax with type annotations
in Python 2.7, ``@Signature`` is independent of CNTK and can be used for any argument annotation.
Args:
*args: types of arguments of the function that this decorator is applied to, in the same order.
**kwargs: types of arguments with optional names, e.g. `x=Tensor[42]`. Use this second form for
longer argument lists.
Example::
# Python 3:
@Function
def f(x: Tensor[42]):
return sigmoid(x)
# Python 2.7:
@Function
@Signature(Tensor[42])
def f(x):
return sigmoid(x)
# note that this:
@Function
@Signature(x:int)
def sqr(x):
return x*x
# is identical to:
def sqr(x):
return x*x
sqr.__annotations__ = {'x': int}`` | bindings/python/cntk/layers/typing.py | Signature | Wootai/CNTK | 0 | python | def Signature(*args, **kwargs):
"\n ``@Signature`` is a decorator to implement the function-argument annotations in Python-2.7,\n as needed by the ``@Function`` decorator.\n This is only needed when you have not yet migrated to Python 3.x.\n\n Note: Although this is aimed at enabling ``@Function`` syntax with type annotations\n in Python 2.7, ``@Signature`` is independent of CNTK and can be used for any argument annotation.\n\n Args:\n *args: types of arguments of the function that this decorator is applied to, in the same order.\n **kwargs: types of arguments with optional names, e.g. `x=Tensor[42]`. Use this second form for\n longer argument lists.\n\n Example::\n\n # Python 3:\n @Function\n def f(x: Tensor[42]):\n return sigmoid(x)\n\n # Python 2.7:\n @Function\n @Signature(Tensor[42])\n def f(x):\n return sigmoid(x)\n\n # note that this:\n @Function\n @Signature(x:int)\n def sqr(x):\n return x*x\n # is identical to:\n def sqr(x):\n return x*x\n sqr.__annotations__ = {'x': int}``\n "
def add_annotations(f):
(param_names, annotations) = get_python_function_arguments(f)
if annotations:
raise ValueError('@Signature cannot be applied to functions that already have annotations')
annotations = {}
if ((len(args) + len(kwargs)) != len(param_names)):
raise TypeError('{} annotations provided for function to be decorated, but function has {} parameters'.format((len(args) + len(kwargs)), len(param_names)))
params_dict = {name: name for name in param_names}
f.__annotations__ = map_function_arguments(param_names, params_dict, *args, **kwargs)
return f
return add_annotations | def Signature(*args, **kwargs):
"\n ``@Signature`` is a decorator to implement the function-argument annotations in Python-2.7,\n as needed by the ``@Function`` decorator.\n This is only needed when you have not yet migrated to Python 3.x.\n\n Note: Although this is aimed at enabling ``@Function`` syntax with type annotations\n in Python 2.7, ``@Signature`` is independent of CNTK and can be used for any argument annotation.\n\n Args:\n *args: types of arguments of the function that this decorator is applied to, in the same order.\n **kwargs: types of arguments with optional names, e.g. `x=Tensor[42]`. Use this second form for\n longer argument lists.\n\n Example::\n\n # Python 3:\n @Function\n def f(x: Tensor[42]):\n return sigmoid(x)\n\n # Python 2.7:\n @Function\n @Signature(Tensor[42])\n def f(x):\n return sigmoid(x)\n\n # note that this:\n @Function\n @Signature(x:int)\n def sqr(x):\n return x*x\n # is identical to:\n def sqr(x):\n return x*x\n sqr.__annotations__ = {'x': int}``\n "
def add_annotations(f):
(param_names, annotations) = get_python_function_arguments(f)
if annotations:
raise ValueError('@Signature cannot be applied to functions that already have annotations')
annotations = {}
if ((len(args) + len(kwargs)) != len(param_names)):
raise TypeError('{} annotations provided for function to be decorated, but function has {} parameters'.format((len(args) + len(kwargs)), len(param_names)))
params_dict = {name: name for name in param_names}
f.__annotations__ = map_function_arguments(param_names, params_dict, *args, **kwargs)
return f
return add_annotations<|docstring|>``@Signature`` is a decorator to implement the function-argument annotations in Python-2.7,
as needed by the ``@Function`` decorator.
This is only needed when you have not yet migrated to Python 3.x.
Note: Although this is aimed at enabling ``@Function`` syntax with type annotations
in Python 2.7, ``@Signature`` is independent of CNTK and can be used for any argument annotation.
Args:
*args: types of arguments of the function that this decorator is applied to, in the same order.
**kwargs: types of arguments with optional names, e.g. `x=Tensor[42]`. Use this second form for
longer argument lists.
Example::
# Python 3:
@Function
def f(x: Tensor[42]):
return sigmoid(x)
# Python 2.7:
@Function
@Signature(Tensor[42])
def f(x):
return sigmoid(x)
# note that this:
@Function
@Signature(x:int)
def sqr(x):
return x*x
# is identical to:
def sqr(x):
return x*x
sqr.__annotations__ = {'x': int}``<|endoftext|> |
3156dc69e9e56e3ae8a7cc41d905dc9e147e7bd156a7fa2d058216bce8ae10dc | def worker(base):
'\n Process one project by calling set of commands.\n '
x = Commands(base)
logger.debug(((str(os.getpid()) + ' ') + str(x)))
x.run()
base.fill(x.retcodes, x.outputs, x.failed)
return base | Process one project by calling set of commands. | Resources/Code/open-grok/opengrok-1.1-rc41/tools/src/main/python/sync.py | worker | briancabbott/xtrax | 2 | python | def worker(base):
'\n \n '
x = Commands(base)
logger.debug(((str(os.getpid()) + ' ') + str(x)))
x.run()
base.fill(x.retcodes, x.outputs, x.failed)
return base | def worker(base):
'\n \n '
x = Commands(base)
logger.debug(((str(os.getpid()) + ' ') + str(x)))
x.run()
base.fill(x.retcodes, x.outputs, x.failed)
return base<|docstring|>Process one project by calling set of commands.<|endoftext|> |
e2fdcd951ce79121ced815f4780e5fe283890666c7d408a570f4871afac251a0 | def target_function(s: str):
'Generate a training data point.'
return [s.replace(' ', '\n'), (len(s) - s.count(' '))] | Generate a training data point. | examples/software_synthesis/replace_space_with_newline.py | target_function | nbro/pyshgp | 51 | python | def target_function(s: str):
return [s.replace(' ', '\n'), (len(s) - s.count(' '))] | def target_function(s: str):
return [s.replace(' ', '\n'), (len(s) - s.count(' '))]<|docstring|>Generate a training data point.<|endoftext|> |
d7bf5de42a7fefda38a55146177bbce6b3ce433f164acdbbafeeb7a3fe852072 | def synthetic_input():
'Generate a string to use as input to a trining data point.'
size = (randint(0, 19) + 2)
s = ''
for ndx in range(size):
if (random() < 0.2):
s += ' '
else:
s += choice(_possible_chars)
return s | Generate a string to use as input to a trining data point. | examples/software_synthesis/replace_space_with_newline.py | synthetic_input | nbro/pyshgp | 51 | python | def synthetic_input():
size = (randint(0, 19) + 2)
s =
for ndx in range(size):
if (random() < 0.2):
s += ' '
else:
s += choice(_possible_chars)
return s | def synthetic_input():
size = (randint(0, 19) + 2)
s =
for ndx in range(size):
if (random() < 0.2):
s += ' '
else:
s += choice(_possible_chars)
return s<|docstring|>Generate a string to use as input to a trining data point.<|endoftext|> |
e10ef32d87721461a79b64e9f59f4112610544249c6fbc80e8b1503d4e4f7a32 | def random_char():
'Return a random character.'
return Char(choice(_possible_chars)) | Return a random character. | examples/software_synthesis/replace_space_with_newline.py | random_char | nbro/pyshgp | 51 | python | def random_char():
return Char(choice(_possible_chars)) | def random_char():
return Char(choice(_possible_chars))<|docstring|>Return a random character.<|endoftext|> |
1e3a6e989ddf78dd238978a9097bf883ff28e7bea71b4c0426adf26505886e45 | def enumerate_assignments(max_context_number):
'\n enumerate all possible assignments of contexts to clusters for a fixed\n number of contexts. Has the hard assumption that the first context belongs\n to cluster #1, to remove redundant assignments that differ in labeling.\n\n :param max_context_number: int\n :return: list of lists, each a function that takes in a context id\n number and returns a cluster id number\n '
cluster_assignments = [{}]
for contextNumber in range(0, max_context_number):
cluster_assignments = augment_assignments(cluster_assignments, contextNumber)
return cluster_assignments | enumerate all possible assignments of contexts to clusters for a fixed
number of contexts. Has the hard assumption that the first context belongs
to cluster #1, to remove redundant assignments that differ in labeling.
:param max_context_number: int
:return: list of lists, each a function that takes in a context id
number and returns a cluster id number | ClusteringModel/dpvi.py | enumerate_assignments | nicktfranklin/StructuredBandits | 8 | python | def enumerate_assignments(max_context_number):
'\n enumerate all possible assignments of contexts to clusters for a fixed\n number of contexts. Has the hard assumption that the first context belongs\n to cluster #1, to remove redundant assignments that differ in labeling.\n\n :param max_context_number: int\n :return: list of lists, each a function that takes in a context id\n number and returns a cluster id number\n '
cluster_assignments = [{}]
for contextNumber in range(0, max_context_number):
cluster_assignments = augment_assignments(cluster_assignments, contextNumber)
return cluster_assignments | def enumerate_assignments(max_context_number):
'\n enumerate all possible assignments of contexts to clusters for a fixed\n number of contexts. Has the hard assumption that the first context belongs\n to cluster #1, to remove redundant assignments that differ in labeling.\n\n :param max_context_number: int\n :return: list of lists, each a function that takes in a context id\n number and returns a cluster id number\n '
cluster_assignments = [{}]
for contextNumber in range(0, max_context_number):
cluster_assignments = augment_assignments(cluster_assignments, contextNumber)
return cluster_assignments<|docstring|>enumerate all possible assignments of contexts to clusters for a fixed
number of contexts. Has the hard assumption that the first context belongs
to cluster #1, to remove redundant assignments that differ in labeling.
:param max_context_number: int
:return: list of lists, each a function that takes in a context id
number and returns a cluster id number<|endoftext|> |
bdad88e241feed98866f53f0ac49dc119411d1fe442ed29e16e466df47e8ecca | def count_hypothesis_space(n_contexts):
'\n Determine the number of unique hypotheses in the clustering space\n '
return len(enumerate_assignments(n_contexts)) | Determine the number of unique hypotheses in the clustering space | ClusteringModel/dpvi.py | count_hypothesis_space | nicktfranklin/StructuredBandits | 8 | python | def count_hypothesis_space(n_contexts):
'\n \n '
return len(enumerate_assignments(n_contexts)) | def count_hypothesis_space(n_contexts):
'\n \n '
return len(enumerate_assignments(n_contexts))<|docstring|>Determine the number of unique hypotheses in the clustering space<|endoftext|> |
39ff8000ea9bdefa363ec20d70141058ff10c08fd2c9c68c11b59fecf9a4bd8d | def __init__(self, k, n_arms=8, mu_init=0.0, var_init=1.0, alpha=1.0, cluster_class=NoiseCluster, kernel=None):
'\n Parameters\n ----------\n\n k: int\n number of particles\n\n mu_init: float (default 0.0)\n prior for mu\n\n var_init: float (default 1.0)\n initial value of sigma\n\n alpha: float (default 1.0)\n concentration parameter for the CRP\n '
self.k = k
self.hypothesis_kwargs = dict(n_arms=n_arms, alpha=alpha, mu_init=mu_init, var_init=var_init, cluster_class=cluster_class, kernel=kernel)
self.hypotheses = list([Hypothesis(**self.hypothesis_kwargs)])
self.w = list([1.0])
self.visited_blocks = set()
self.experience = list() | Parameters
----------
k: int
number of particles
mu_init: float (default 0.0)
prior for mu
var_init: float (default 1.0)
initial value of sigma
alpha: float (default 1.0)
concentration parameter for the CRP | ClusteringModel/dpvi.py | __init__ | nicktfranklin/StructuredBandits | 8 | python | def __init__(self, k, n_arms=8, mu_init=0.0, var_init=1.0, alpha=1.0, cluster_class=NoiseCluster, kernel=None):
'\n Parameters\n ----------\n\n k: int\n number of particles\n\n mu_init: float (default 0.0)\n prior for mu\n\n var_init: float (default 1.0)\n initial value of sigma\n\n alpha: float (default 1.0)\n concentration parameter for the CRP\n '
self.k = k
self.hypothesis_kwargs = dict(n_arms=n_arms, alpha=alpha, mu_init=mu_init, var_init=var_init, cluster_class=cluster_class, kernel=kernel)
self.hypotheses = list([Hypothesis(**self.hypothesis_kwargs)])
self.w = list([1.0])
self.visited_blocks = set()
self.experience = list() | def __init__(self, k, n_arms=8, mu_init=0.0, var_init=1.0, alpha=1.0, cluster_class=NoiseCluster, kernel=None):
'\n Parameters\n ----------\n\n k: int\n number of particles\n\n mu_init: float (default 0.0)\n prior for mu\n\n var_init: float (default 1.0)\n initial value of sigma\n\n alpha: float (default 1.0)\n concentration parameter for the CRP\n '
self.k = k
self.hypothesis_kwargs = dict(n_arms=n_arms, alpha=alpha, mu_init=mu_init, var_init=var_init, cluster_class=cluster_class, kernel=kernel)
self.hypotheses = list([Hypothesis(**self.hypothesis_kwargs)])
self.w = list([1.0])
self.visited_blocks = set()
self.experience = list()<|docstring|>Parameters
----------
k: int
number of particles
mu_init: float (default 0.0)
prior for mu
var_init: float (default 1.0)
initial value of sigma
alpha: float (default 1.0)
concentration parameter for the CRP<|endoftext|> |
f39da8dcd16be0a7ed4fb62e36bd7a31418c1062a660833fb7eb797b93f62361 | def _get_var_prior(self, block, arm):
" this is a special case function that returns the prior probability\n of each cluster and it's variance for the "
pass | this is a special case function that returns the prior probability
of each cluster and it's variance for the | ClusteringModel/dpvi.py | _get_var_prior | nicktfranklin/StructuredBandits | 8 | python | def _get_var_prior(self, block, arm):
" this is a special case function that returns the prior probability\n of each cluster and it's variance for the "
pass | def _get_var_prior(self, block, arm):
" this is a special case function that returns the prior probability\n of each cluster and it's variance for the "
pass<|docstring|>this is a special case function that returns the prior probability
of each cluster and it's variance for the<|endoftext|> |
f333f2bea4077b7fb06dd44c53e91312391d593c1c83049d735f748b9c5ed237 | def helper_force_authenticate(request, user):
'\n In addition to calling `force_authenticate`, set\n the organisation as it would happen in the middleware\n '
force_authenticate(request, user=user)
request.organisation = user.staffprofile.organisation | In addition to calling `force_authenticate`, set
the organisation as it would happen in the middleware | app/organisation/tests.py | helper_force_authenticate | DOSSIER-dev/DOSSIER-Sources | 7 | python | def helper_force_authenticate(request, user):
'\n In addition to calling `force_authenticate`, set\n the organisation as it would happen in the middleware\n '
force_authenticate(request, user=user)
request.organisation = user.staffprofile.organisation | def helper_force_authenticate(request, user):
'\n In addition to calling `force_authenticate`, set\n the organisation as it would happen in the middleware\n '
force_authenticate(request, user=user)
request.organisation = user.staffprofile.organisation<|docstring|>In addition to calling `force_authenticate`, set
the organisation as it would happen in the middleware<|endoftext|> |
3c4e6f2e9a9b890580e1863b5e5d46ed6138eae24cac050abb35cad75e9264fb | def test_unique_username(self):
'\n Test that unique usernames are enforced at the api level, BUT an\n update of a user must be possible keeping the same username\n '
factory = APIRequestFactory()
request = factory.post('/staffer/', {'isActive': True, 'isManager': False, 'user': {'username': '[email protected]', 'firstname': 'alice', 'lastname': 'abc', 'email': '[email protected]'}}, format='json')
helper_force_authenticate(request, user=self.alice)
view = StafferViewSet.as_view({'post': 'create'})
response = view(request)
self.assertEqual(response.status_code, 400)
id_ = self.alice.id
request = factory.put('/staffer/', {'isActive': True, 'isManager': True, 'user': {'username': '[email protected]', 'firstname': 'New Alice', 'lastname': 'abcxyz', 'email': '[email protected]'}}, format='json')
helper_force_authenticate(request, user=self.alice)
view = StafferViewSet.as_view({'put': 'update'})
response = view(request, pk=id_)
self.assertEqual(response.status_code, 200)
alice = User.objects.get(id=id_)
self.assertEqual(alice.first_name, 'New Alice')
self.assertEqual(alice.last_name, 'abcxyz')
self.assertEqual(alice.email, '[email protected]') | Test that unique usernames are enforced at the api level, BUT an
update of a user must be possible keeping the same username | app/organisation/tests.py | test_unique_username | DOSSIER-dev/DOSSIER-Sources | 7 | python | def test_unique_username(self):
'\n Test that unique usernames are enforced at the api level, BUT an\n update of a user must be possible keeping the same username\n '
factory = APIRequestFactory()
request = factory.post('/staffer/', {'isActive': True, 'isManager': False, 'user': {'username': '[email protected]', 'firstname': 'alice', 'lastname': 'abc', 'email': '[email protected]'}}, format='json')
helper_force_authenticate(request, user=self.alice)
view = StafferViewSet.as_view({'post': 'create'})
response = view(request)
self.assertEqual(response.status_code, 400)
id_ = self.alice.id
request = factory.put('/staffer/', {'isActive': True, 'isManager': True, 'user': {'username': '[email protected]', 'firstname': 'New Alice', 'lastname': 'abcxyz', 'email': '[email protected]'}}, format='json')
helper_force_authenticate(request, user=self.alice)
view = StafferViewSet.as_view({'put': 'update'})
response = view(request, pk=id_)
self.assertEqual(response.status_code, 200)
alice = User.objects.get(id=id_)
self.assertEqual(alice.first_name, 'New Alice')
self.assertEqual(alice.last_name, 'abcxyz')
self.assertEqual(alice.email, '[email protected]') | def test_unique_username(self):
'\n Test that unique usernames are enforced at the api level, BUT an\n update of a user must be possible keeping the same username\n '
factory = APIRequestFactory()
request = factory.post('/staffer/', {'isActive': True, 'isManager': False, 'user': {'username': '[email protected]', 'firstname': 'alice', 'lastname': 'abc', 'email': '[email protected]'}}, format='json')
helper_force_authenticate(request, user=self.alice)
view = StafferViewSet.as_view({'post': 'create'})
response = view(request)
self.assertEqual(response.status_code, 400)
id_ = self.alice.id
request = factory.put('/staffer/', {'isActive': True, 'isManager': True, 'user': {'username': '[email protected]', 'firstname': 'New Alice', 'lastname': 'abcxyz', 'email': '[email protected]'}}, format='json')
helper_force_authenticate(request, user=self.alice)
view = StafferViewSet.as_view({'put': 'update'})
response = view(request, pk=id_)
self.assertEqual(response.status_code, 200)
alice = User.objects.get(id=id_)
self.assertEqual(alice.first_name, 'New Alice')
self.assertEqual(alice.last_name, 'abcxyz')
self.assertEqual(alice.email, '[email protected]')<|docstring|>Test that unique usernames are enforced at the api level, BUT an
update of a user must be possible keeping the same username<|endoftext|> |
87ab883d5ea16f53daafe9d368972109a08ddfa561aa4767772d523aba1596c9 | def __init__(self, value: Union[(List[T], tuple, range, 'Array')]) -> None:
'\n Array class for the apysc library.\n\n Parameters\n ----------\n value : list or tuple or range or Array\n Initial array value.\n\n References\n ----------\n - Array document\n - https://simon-ritchie.github.io/apysc/array.html\n - Array class comparison interfaces document\n - https://simon-ritchie.github.io/apysc/array_comparison.html\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 2, 3])\n >>> arr\n Array([1, 2, 3])\n\n >>> arr[0]\n 1\n\n >>> arr[1]\n 2\n\n >>> arr = ap.Array((4, 5, 6))\n >>> arr\n Array([4, 5, 6])\n\n >>> arr = ap.Array(range(3))\n >>> arr\n Array([0, 1, 2])\n '
import apysc as ap
with ap.DebugInfo(callable_='__init__', locals_=locals(), module_name=__name__, class_=Array):
from apysc._expression import expression_variables_util
from apysc._expression import var_names
from apysc._expression.event_handler_scope import TemporaryNotHandlerScope
with TemporaryNotHandlerScope():
TYPE_NAME: str = var_names.ARRAY
self._validate_acceptable_value_type(value=value)
value = self._convert_range_to_list(value=value)
value_: Union[(List[Any], tuple, 'Array')] = value
self._initial_value = value_
self._type_name = TYPE_NAME
self._value = self._get_list_value(value=value)
self.variable_name = expression_variables_util.get_next_variable_name(type_name=TYPE_NAME)
self._append_constructor_expression() | Array class for the apysc library.
Parameters
----------
value : list or tuple or range or Array
Initial array value.
References
----------
- Array document
- https://simon-ritchie.github.io/apysc/array.html
- Array class comparison interfaces document
- https://simon-ritchie.github.io/apysc/array_comparison.html
Examples
--------
>>> import apysc as ap
>>> arr: ap.Array = ap.Array([1, 2, 3])
>>> arr
Array([1, 2, 3])
>>> arr[0]
1
>>> arr[1]
2
>>> arr = ap.Array((4, 5, 6))
>>> arr
Array([4, 5, 6])
>>> arr = ap.Array(range(3))
>>> arr
Array([0, 1, 2]) | apysc/_type/array.py | __init__ | simon-ritchie/apysc | 16 | python | def __init__(self, value: Union[(List[T], tuple, range, 'Array')]) -> None:
'\n Array class for the apysc library.\n\n Parameters\n ----------\n value : list or tuple or range or Array\n Initial array value.\n\n References\n ----------\n - Array document\n - https://simon-ritchie.github.io/apysc/array.html\n - Array class comparison interfaces document\n - https://simon-ritchie.github.io/apysc/array_comparison.html\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 2, 3])\n >>> arr\n Array([1, 2, 3])\n\n >>> arr[0]\n 1\n\n >>> arr[1]\n 2\n\n >>> arr = ap.Array((4, 5, 6))\n >>> arr\n Array([4, 5, 6])\n\n >>> arr = ap.Array(range(3))\n >>> arr\n Array([0, 1, 2])\n '
import apysc as ap
with ap.DebugInfo(callable_='__init__', locals_=locals(), module_name=__name__, class_=Array):
from apysc._expression import expression_variables_util
from apysc._expression import var_names
from apysc._expression.event_handler_scope import TemporaryNotHandlerScope
with TemporaryNotHandlerScope():
TYPE_NAME: str = var_names.ARRAY
self._validate_acceptable_value_type(value=value)
value = self._convert_range_to_list(value=value)
value_: Union[(List[Any], tuple, 'Array')] = value
self._initial_value = value_
self._type_name = TYPE_NAME
self._value = self._get_list_value(value=value)
self.variable_name = expression_variables_util.get_next_variable_name(type_name=TYPE_NAME)
self._append_constructor_expression() | def __init__(self, value: Union[(List[T], tuple, range, 'Array')]) -> None:
'\n Array class for the apysc library.\n\n Parameters\n ----------\n value : list or tuple or range or Array\n Initial array value.\n\n References\n ----------\n - Array document\n - https://simon-ritchie.github.io/apysc/array.html\n - Array class comparison interfaces document\n - https://simon-ritchie.github.io/apysc/array_comparison.html\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 2, 3])\n >>> arr\n Array([1, 2, 3])\n\n >>> arr[0]\n 1\n\n >>> arr[1]\n 2\n\n >>> arr = ap.Array((4, 5, 6))\n >>> arr\n Array([4, 5, 6])\n\n >>> arr = ap.Array(range(3))\n >>> arr\n Array([0, 1, 2])\n '
import apysc as ap
with ap.DebugInfo(callable_='__init__', locals_=locals(), module_name=__name__, class_=Array):
from apysc._expression import expression_variables_util
from apysc._expression import var_names
from apysc._expression.event_handler_scope import TemporaryNotHandlerScope
with TemporaryNotHandlerScope():
TYPE_NAME: str = var_names.ARRAY
self._validate_acceptable_value_type(value=value)
value = self._convert_range_to_list(value=value)
value_: Union[(List[Any], tuple, 'Array')] = value
self._initial_value = value_
self._type_name = TYPE_NAME
self._value = self._get_list_value(value=value)
self.variable_name = expression_variables_util.get_next_variable_name(type_name=TYPE_NAME)
self._append_constructor_expression()<|docstring|>Array class for the apysc library.
Parameters
----------
value : list or tuple or range or Array
Initial array value.
References
----------
- Array document
- https://simon-ritchie.github.io/apysc/array.html
- Array class comparison interfaces document
- https://simon-ritchie.github.io/apysc/array_comparison.html
Examples
--------
>>> import apysc as ap
>>> arr: ap.Array = ap.Array([1, 2, 3])
>>> arr
Array([1, 2, 3])
>>> arr[0]
1
>>> arr[1]
2
>>> arr = ap.Array((4, 5, 6))
>>> arr
Array([4, 5, 6])
>>> arr = ap.Array(range(3))
>>> arr
Array([0, 1, 2])<|endoftext|> |
85d692c1ce8e108acdd4388568e906e48cb7ff5faa1e7d4bf18ced6f034102ea | def _convert_range_to_list(self, *, value: Any) -> Union[(List[Any], tuple, 'Array')]:
'\n Convert argument value to list that if specified\n value is range type.\n\n Parameters\n ----------\n value : list or tuple or range or Array\n Target value.\n\n Returns\n -------\n value : list or tuple or Array\n Converted value.\n '
if isinstance(value, range):
return list(value)
return value | Convert argument value to list that if specified
value is range type.
Parameters
----------
value : list or tuple or range or Array
Target value.
Returns
-------
value : list or tuple or Array
Converted value. | apysc/_type/array.py | _convert_range_to_list | simon-ritchie/apysc | 16 | python | def _convert_range_to_list(self, *, value: Any) -> Union[(List[Any], tuple, 'Array')]:
'\n Convert argument value to list that if specified\n value is range type.\n\n Parameters\n ----------\n value : list or tuple or range or Array\n Target value.\n\n Returns\n -------\n value : list or tuple or Array\n Converted value.\n '
if isinstance(value, range):
return list(value)
return value | def _convert_range_to_list(self, *, value: Any) -> Union[(List[Any], tuple, 'Array')]:
'\n Convert argument value to list that if specified\n value is range type.\n\n Parameters\n ----------\n value : list or tuple or range or Array\n Target value.\n\n Returns\n -------\n value : list or tuple or Array\n Converted value.\n '
if isinstance(value, range):
return list(value)
return value<|docstring|>Convert argument value to list that if specified
value is range type.
Parameters
----------
value : list or tuple or range or Array
Target value.
Returns
-------
value : list or tuple or Array
Converted value.<|endoftext|> |
8fd17662a575d75892facf839f72fb384d480380552754ef3547debf06c12a67 | def _append_constructor_expression(self) -> None:
'\n Append constructor expression.\n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_constructor_expression, locals_=locals(), module_name=__name__, class_=Array):
from apysc._type import value_util
expression: str = f'var {self.variable_name} = '
if isinstance(self._initial_value, Array):
expression += f'{self._initial_value.variable_name};'
else:
value_str: str = value_util.get_value_str_for_expression(value=self._value)
expression += f'{value_str};'
ap.append_js_expression(expression=expression) | Append constructor expression. | apysc/_type/array.py | _append_constructor_expression | simon-ritchie/apysc | 16 | python | def _append_constructor_expression(self) -> None:
'\n \n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_constructor_expression, locals_=locals(), module_name=__name__, class_=Array):
from apysc._type import value_util
expression: str = f'var {self.variable_name} = '
if isinstance(self._initial_value, Array):
expression += f'{self._initial_value.variable_name};'
else:
value_str: str = value_util.get_value_str_for_expression(value=self._value)
expression += f'{value_str};'
ap.append_js_expression(expression=expression) | def _append_constructor_expression(self) -> None:
'\n \n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_constructor_expression, locals_=locals(), module_name=__name__, class_=Array):
from apysc._type import value_util
expression: str = f'var {self.variable_name} = '
if isinstance(self._initial_value, Array):
expression += f'{self._initial_value.variable_name};'
else:
value_str: str = value_util.get_value_str_for_expression(value=self._value)
expression += f'{value_str};'
ap.append_js_expression(expression=expression)<|docstring|>Append constructor expression.<|endoftext|> |
b497c72909468f7f953dcc4d5f78bb837fa8379bea94347ad392da0e865f2c49 | def _get_list_value(self, *, value: Union[(List[Any], tuple, 'Array')]) -> List[Any]:
'\n Get a list value from specified list, tuple, or Array value.\n\n Parameters\n ----------\n value : list or tuple or Array\n Specified list, tuple, or Array value.\n\n Returns\n -------\n list_val : list\n Converted list value.\n '
if isinstance(value, tuple):
return list(value)
if isinstance(value, Array):
return value._value
return value | Get a list value from specified list, tuple, or Array value.
Parameters
----------
value : list or tuple or Array
Specified list, tuple, or Array value.
Returns
-------
list_val : list
Converted list value. | apysc/_type/array.py | _get_list_value | simon-ritchie/apysc | 16 | python | def _get_list_value(self, *, value: Union[(List[Any], tuple, 'Array')]) -> List[Any]:
'\n Get a list value from specified list, tuple, or Array value.\n\n Parameters\n ----------\n value : list or tuple or Array\n Specified list, tuple, or Array value.\n\n Returns\n -------\n list_val : list\n Converted list value.\n '
if isinstance(value, tuple):
return list(value)
if isinstance(value, Array):
return value._value
return value | def _get_list_value(self, *, value: Union[(List[Any], tuple, 'Array')]) -> List[Any]:
'\n Get a list value from specified list, tuple, or Array value.\n\n Parameters\n ----------\n value : list or tuple or Array\n Specified list, tuple, or Array value.\n\n Returns\n -------\n list_val : list\n Converted list value.\n '
if isinstance(value, tuple):
return list(value)
if isinstance(value, Array):
return value._value
return value<|docstring|>Get a list value from specified list, tuple, or Array value.
Parameters
----------
value : list or tuple or Array
Specified list, tuple, or Array value.
Returns
-------
list_val : list
Converted list value.<|endoftext|> |
c16774ddb8da3f564893e782c2aa6ff9d864ce88c550bee966f2f8a9e7af4759 | def _validate_acceptable_value_type(self, *, value: Union[(List[Any], tuple, range, 'Array')]) -> None:
"\n Validate that specified value is acceptable type or not.\n\n Parameters\n ----------\n value : list or tuple or range or Array\n Iterable value to check.\n\n Raises\n ------\n ValueError\n If specified value's type is not list, tuple, or Array.\n "
if isinstance(value, (list, tuple, range, Array)):
return
raise ValueError(f'''Not acceptable value type is specified.
Specified value type: {type(value)}
Acceptable types: list, tuple, range, and Array''') | Validate that specified value is acceptable type or not.
Parameters
----------
value : list or tuple or range or Array
Iterable value to check.
Raises
------
ValueError
If specified value's type is not list, tuple, or Array. | apysc/_type/array.py | _validate_acceptable_value_type | simon-ritchie/apysc | 16 | python | def _validate_acceptable_value_type(self, *, value: Union[(List[Any], tuple, range, 'Array')]) -> None:
"\n Validate that specified value is acceptable type or not.\n\n Parameters\n ----------\n value : list or tuple or range or Array\n Iterable value to check.\n\n Raises\n ------\n ValueError\n If specified value's type is not list, tuple, or Array.\n "
if isinstance(value, (list, tuple, range, Array)):
return
raise ValueError(f'Not acceptable value type is specified.
Specified value type: {type(value)}
Acceptable types: list, tuple, range, and Array') | def _validate_acceptable_value_type(self, *, value: Union[(List[Any], tuple, range, 'Array')]) -> None:
"\n Validate that specified value is acceptable type or not.\n\n Parameters\n ----------\n value : list or tuple or range or Array\n Iterable value to check.\n\n Raises\n ------\n ValueError\n If specified value's type is not list, tuple, or Array.\n "
if isinstance(value, (list, tuple, range, Array)):
return
raise ValueError(f'Not acceptable value type is specified.
Specified value type: {type(value)}
Acceptable types: list, tuple, range, and Array')<|docstring|>Validate that specified value is acceptable type or not.
Parameters
----------
value : list or tuple or range or Array
Iterable value to check.
Raises
------
ValueError
If specified value's type is not list, tuple, or Array.<|endoftext|> |
1828ca587f32942e6ded0bc477bcc1e37f4351fb6a36786c4e8c7f8e613a913f | @property
def value(self) -> Union[(List[Any], tuple, 'Array')]:
'\n Get a current array value.\n\n Returns\n -------\n value : list\n Current array value.\n\n References\n ----------\n - apysc basic data classes common value interface\n - https://bit.ly/3Be1aij\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 2, 3])\n >>> arr.value = [4, 5, 6]\n >>> arr.value\n [4, 5, 6]\n '
return self._value | Get a current array value.
Returns
-------
value : list
Current array value.
References
----------
- apysc basic data classes common value interface
- https://bit.ly/3Be1aij
Examples
--------
>>> import apysc as ap
>>> arr: ap.Array = ap.Array([1, 2, 3])
>>> arr.value = [4, 5, 6]
>>> arr.value
[4, 5, 6] | apysc/_type/array.py | value | simon-ritchie/apysc | 16 | python | @property
def value(self) -> Union[(List[Any], tuple, 'Array')]:
'\n Get a current array value.\n\n Returns\n -------\n value : list\n Current array value.\n\n References\n ----------\n - apysc basic data classes common value interface\n - https://bit.ly/3Be1aij\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 2, 3])\n >>> arr.value = [4, 5, 6]\n >>> arr.value\n [4, 5, 6]\n '
return self._value | @property
def value(self) -> Union[(List[Any], tuple, 'Array')]:
'\n Get a current array value.\n\n Returns\n -------\n value : list\n Current array value.\n\n References\n ----------\n - apysc basic data classes common value interface\n - https://bit.ly/3Be1aij\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 2, 3])\n >>> arr.value = [4, 5, 6]\n >>> arr.value\n [4, 5, 6]\n '
return self._value<|docstring|>Get a current array value.
Returns
-------
value : list
Current array value.
References
----------
- apysc basic data classes common value interface
- https://bit.ly/3Be1aij
Examples
--------
>>> import apysc as ap
>>> arr: ap.Array = ap.Array([1, 2, 3])
>>> arr.value = [4, 5, 6]
>>> arr.value
[4, 5, 6]<|endoftext|> |
28c8cb8250d1026c8d45381acb3f4219660498e7e7d3d4d59fe3089b5a5a3124 | @value.setter
def value(self, value: Union[(List[Any], tuple, 'Array')]) -> None:
'\n Set array value.\n\n Parameters\n ----------\n value : list or tuple or Array\n Iterable value (list, tuple, or Array) to set.\n\n References\n ----------\n apysc basic data classes common value interface\n https://bit.ly/3Be1aij\n '
import apysc as ap
with ap.DebugInfo(callable_='value', locals_=locals(), module_name=__name__, class_=Array):
self._validate_acceptable_value_type(value=value)
self._value = self._get_list_value(value=value)
self._append_value_setter_expression(value=value) | Set array value.
Parameters
----------
value : list or tuple or Array
Iterable value (list, tuple, or Array) to set.
References
----------
apysc basic data classes common value interface
https://bit.ly/3Be1aij | apysc/_type/array.py | value | simon-ritchie/apysc | 16 | python | @value.setter
def value(self, value: Union[(List[Any], tuple, 'Array')]) -> None:
'\n Set array value.\n\n Parameters\n ----------\n value : list or tuple or Array\n Iterable value (list, tuple, or Array) to set.\n\n References\n ----------\n apysc basic data classes common value interface\n https://bit.ly/3Be1aij\n '
import apysc as ap
with ap.DebugInfo(callable_='value', locals_=locals(), module_name=__name__, class_=Array):
self._validate_acceptable_value_type(value=value)
self._value = self._get_list_value(value=value)
self._append_value_setter_expression(value=value) | @value.setter
def value(self, value: Union[(List[Any], tuple, 'Array')]) -> None:
'\n Set array value.\n\n Parameters\n ----------\n value : list or tuple or Array\n Iterable value (list, tuple, or Array) to set.\n\n References\n ----------\n apysc basic data classes common value interface\n https://bit.ly/3Be1aij\n '
import apysc as ap
with ap.DebugInfo(callable_='value', locals_=locals(), module_name=__name__, class_=Array):
self._validate_acceptable_value_type(value=value)
self._value = self._get_list_value(value=value)
self._append_value_setter_expression(value=value)<|docstring|>Set array value.
Parameters
----------
value : list or tuple or Array
Iterable value (list, tuple, or Array) to set.
References
----------
apysc basic data classes common value interface
https://bit.ly/3Be1aij<|endoftext|> |
e1f0fb252076526cdafd77e386e3e9c65f272fb3557db8b2182091f59b3ab032 | def _append_value_setter_expression(self, *, value: Union[(List[Any], tuple, 'Array')]) -> None:
"\n Append value's setter expression.\n\n Parameters\n ----------\n value : list or tuple or Array\n Iterable value (list, tuple, or Array) to set.\n "
import apysc as ap
with ap.DebugInfo(callable_=self._append_value_setter_expression, locals_=locals(), module_name=__name__, class_=Array):
from apysc._type import value_util
expression: str = f'{self.variable_name} = '
if isinstance(value, Array):
expression += f'{value.variable_name};'
else:
value_str: str = value_util.get_value_str_for_expression(value=value)
expression += f'{value_str};'
ap.append_js_expression(expression=expression) | Append value's setter expression.
Parameters
----------
value : list or tuple or Array
Iterable value (list, tuple, or Array) to set. | apysc/_type/array.py | _append_value_setter_expression | simon-ritchie/apysc | 16 | python | def _append_value_setter_expression(self, *, value: Union[(List[Any], tuple, 'Array')]) -> None:
"\n Append value's setter expression.\n\n Parameters\n ----------\n value : list or tuple or Array\n Iterable value (list, tuple, or Array) to set.\n "
import apysc as ap
with ap.DebugInfo(callable_=self._append_value_setter_expression, locals_=locals(), module_name=__name__, class_=Array):
from apysc._type import value_util
expression: str = f'{self.variable_name} = '
if isinstance(value, Array):
expression += f'{value.variable_name};'
else:
value_str: str = value_util.get_value_str_for_expression(value=value)
expression += f'{value_str};'
ap.append_js_expression(expression=expression) | def _append_value_setter_expression(self, *, value: Union[(List[Any], tuple, 'Array')]) -> None:
"\n Append value's setter expression.\n\n Parameters\n ----------\n value : list or tuple or Array\n Iterable value (list, tuple, or Array) to set.\n "
import apysc as ap
with ap.DebugInfo(callable_=self._append_value_setter_expression, locals_=locals(), module_name=__name__, class_=Array):
from apysc._type import value_util
expression: str = f'{self.variable_name} = '
if isinstance(value, Array):
expression += f'{value.variable_name};'
else:
value_str: str = value_util.get_value_str_for_expression(value=value)
expression += f'{value_str};'
ap.append_js_expression(expression=expression)<|docstring|>Append value's setter expression.
Parameters
----------
value : list or tuple or Array
Iterable value (list, tuple, or Array) to set.<|endoftext|> |
65cec69070a3b147f8716971b9b7de691aed3a21afa6f08d86f4f0c0548cfef0 | def append(self, value: T) -> None:
'\n Add any value to the end of this array.\n This behaves same as push method.\n\n Parameters\n ----------\n value : *\n Any value to append.\n\n References\n ----------\n - Array class append and push interfaces document\n - https://simon-ritchie.github.io/apysc/array_append_and_push.html\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 2, 3])\n >>> arr.append(4)\n >>> arr\n Array([1, 2, 3, 4])\n '
import apysc as ap
with ap.DebugInfo(callable_=self.append, locals_=locals(), module_name=__name__, class_=Array):
self._value.append(value)
self._append_push_and_append_expression(value=value) | Add any value to the end of this array.
This behaves same as push method.
Parameters
----------
value : *
Any value to append.
References
----------
- Array class append and push interfaces document
- https://simon-ritchie.github.io/apysc/array_append_and_push.html
Examples
--------
>>> import apysc as ap
>>> arr: ap.Array = ap.Array([1, 2, 3])
>>> arr.append(4)
>>> arr
Array([1, 2, 3, 4]) | apysc/_type/array.py | append | simon-ritchie/apysc | 16 | python | def append(self, value: T) -> None:
'\n Add any value to the end of this array.\n This behaves same as push method.\n\n Parameters\n ----------\n value : *\n Any value to append.\n\n References\n ----------\n - Array class append and push interfaces document\n - https://simon-ritchie.github.io/apysc/array_append_and_push.html\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 2, 3])\n >>> arr.append(4)\n >>> arr\n Array([1, 2, 3, 4])\n '
import apysc as ap
with ap.DebugInfo(callable_=self.append, locals_=locals(), module_name=__name__, class_=Array):
self._value.append(value)
self._append_push_and_append_expression(value=value) | def append(self, value: T) -> None:
'\n Add any value to the end of this array.\n This behaves same as push method.\n\n Parameters\n ----------\n value : *\n Any value to append.\n\n References\n ----------\n - Array class append and push interfaces document\n - https://simon-ritchie.github.io/apysc/array_append_and_push.html\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 2, 3])\n >>> arr.append(4)\n >>> arr\n Array([1, 2, 3, 4])\n '
import apysc as ap
with ap.DebugInfo(callable_=self.append, locals_=locals(), module_name=__name__, class_=Array):
self._value.append(value)
self._append_push_and_append_expression(value=value)<|docstring|>Add any value to the end of this array.
This behaves same as push method.
Parameters
----------
value : *
Any value to append.
References
----------
- Array class append and push interfaces document
- https://simon-ritchie.github.io/apysc/array_append_and_push.html
Examples
--------
>>> import apysc as ap
>>> arr: ap.Array = ap.Array([1, 2, 3])
>>> arr.append(4)
>>> arr
Array([1, 2, 3, 4])<|endoftext|> |
c1cfa417f687b42b0e4433618fffee955545e508c4cb1daefc3d1d0c81e9a296 | def push(self, value: T) -> None:
'\n Add any value to the end of this array.\n This behaves same as append method.\n\n Parameters\n ----------\n value : *\n Any value to append.\n\n References\n ----------\n - Array class append and push interfaces document\n - https://simon-ritchie.github.io/apysc/array_append_and_push.html\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 2, 3])\n >>> arr.push(4)\n >>> arr\n Array([1, 2, 3, 4])\n '
import apysc as ap
with ap.DebugInfo(callable_=self.push, locals_=locals(), module_name=__name__, class_=Array):
self.append(value=value) | Add any value to the end of this array.
This behaves same as append method.
Parameters
----------
value : *
Any value to append.
References
----------
- Array class append and push interfaces document
- https://simon-ritchie.github.io/apysc/array_append_and_push.html
Examples
--------
>>> import apysc as ap
>>> arr: ap.Array = ap.Array([1, 2, 3])
>>> arr.push(4)
>>> arr
Array([1, 2, 3, 4]) | apysc/_type/array.py | push | simon-ritchie/apysc | 16 | python | def push(self, value: T) -> None:
'\n Add any value to the end of this array.\n This behaves same as append method.\n\n Parameters\n ----------\n value : *\n Any value to append.\n\n References\n ----------\n - Array class append and push interfaces document\n - https://simon-ritchie.github.io/apysc/array_append_and_push.html\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 2, 3])\n >>> arr.push(4)\n >>> arr\n Array([1, 2, 3, 4])\n '
import apysc as ap
with ap.DebugInfo(callable_=self.push, locals_=locals(), module_name=__name__, class_=Array):
self.append(value=value) | def push(self, value: T) -> None:
'\n Add any value to the end of this array.\n This behaves same as append method.\n\n Parameters\n ----------\n value : *\n Any value to append.\n\n References\n ----------\n - Array class append and push interfaces document\n - https://simon-ritchie.github.io/apysc/array_append_and_push.html\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 2, 3])\n >>> arr.push(4)\n >>> arr\n Array([1, 2, 3, 4])\n '
import apysc as ap
with ap.DebugInfo(callable_=self.push, locals_=locals(), module_name=__name__, class_=Array):
self.append(value=value)<|docstring|>Add any value to the end of this array.
This behaves same as append method.
Parameters
----------
value : *
Any value to append.
References
----------
- Array class append and push interfaces document
- https://simon-ritchie.github.io/apysc/array_append_and_push.html
Examples
--------
>>> import apysc as ap
>>> arr: ap.Array = ap.Array([1, 2, 3])
>>> arr.push(4)
>>> arr
Array([1, 2, 3, 4])<|endoftext|> |
8cd17358659156cb8449b3d2c90b88462e848426fee24e4d16419695f6310d79 | def _append_push_and_append_expression(self, *, value: T) -> None:
'\n Append push and append method expression.\n\n Parameters\n ----------\n value : *\n Any value to append.\n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_push_and_append_expression, locals_=locals(), module_name=__name__, class_=Array):
from apysc._type import value_util
value_str: str = value_util.get_value_str_for_expression(value=value)
expression: str = f'{self.variable_name}.push({value_str});'
ap.append_js_expression(expression=expression) | Append push and append method expression.
Parameters
----------
value : *
Any value to append. | apysc/_type/array.py | _append_push_and_append_expression | simon-ritchie/apysc | 16 | python | def _append_push_and_append_expression(self, *, value: T) -> None:
'\n Append push and append method expression.\n\n Parameters\n ----------\n value : *\n Any value to append.\n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_push_and_append_expression, locals_=locals(), module_name=__name__, class_=Array):
from apysc._type import value_util
value_str: str = value_util.get_value_str_for_expression(value=value)
expression: str = f'{self.variable_name}.push({value_str});'
ap.append_js_expression(expression=expression) | def _append_push_and_append_expression(self, *, value: T) -> None:
'\n Append push and append method expression.\n\n Parameters\n ----------\n value : *\n Any value to append.\n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_push_and_append_expression, locals_=locals(), module_name=__name__, class_=Array):
from apysc._type import value_util
value_str: str = value_util.get_value_str_for_expression(value=value)
expression: str = f'{self.variable_name}.push({value_str});'
ap.append_js_expression(expression=expression)<|docstring|>Append push and append method expression.
Parameters
----------
value : *
Any value to append.<|endoftext|> |
621de9050b0e0fa3300f46f3ca1e7085450d84c14dce128f25188071a85d30d4 | def extend(self, other_arr: Union[(List[T], tuple, 'Array')]) -> None:
"\n Concatenate argument array to this one. Argument array's\n values will positioned after this array's values.\n This method is similar to concat method, but there is a\n difference in whether the same variable will be\n updated (extend) or returned as a different variable (concat).\n\n Parameters\n ----------\n other_arr : list or tuple or Array\n Other array-like value to concatenate.\n\n References\n ----------\n - Array class extend and concat interfaces document\n - https://bit.ly/3r1TdIu\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 2, 3])\n >>> arr.extend([4, 5, 6])\n >>> arr\n Array([1, 2, 3, 4, 5, 6])\n "
import apysc as ap
with ap.DebugInfo(callable_=self.extend, locals_=locals(), module_name=__name__, class_=Array):
self._validate_acceptable_value_type(value=other_arr)
if isinstance(other_arr, Array):
self._value.extend(other_arr.value)
else:
self._value.extend(other_arr)
self._append_extend_expression(other_arr=other_arr) | Concatenate argument array to this one. Argument array's
values will positioned after this array's values.
This method is similar to concat method, but there is a
difference in whether the same variable will be
updated (extend) or returned as a different variable (concat).
Parameters
----------
other_arr : list or tuple or Array
Other array-like value to concatenate.
References
----------
- Array class extend and concat interfaces document
- https://bit.ly/3r1TdIu
Examples
--------
>>> import apysc as ap
>>> arr: ap.Array = ap.Array([1, 2, 3])
>>> arr.extend([4, 5, 6])
>>> arr
Array([1, 2, 3, 4, 5, 6]) | apysc/_type/array.py | extend | simon-ritchie/apysc | 16 | python | def extend(self, other_arr: Union[(List[T], tuple, 'Array')]) -> None:
"\n Concatenate argument array to this one. Argument array's\n values will positioned after this array's values.\n This method is similar to concat method, but there is a\n difference in whether the same variable will be\n updated (extend) or returned as a different variable (concat).\n\n Parameters\n ----------\n other_arr : list or tuple or Array\n Other array-like value to concatenate.\n\n References\n ----------\n - Array class extend and concat interfaces document\n - https://bit.ly/3r1TdIu\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 2, 3])\n >>> arr.extend([4, 5, 6])\n >>> arr\n Array([1, 2, 3, 4, 5, 6])\n "
import apysc as ap
with ap.DebugInfo(callable_=self.extend, locals_=locals(), module_name=__name__, class_=Array):
self._validate_acceptable_value_type(value=other_arr)
if isinstance(other_arr, Array):
self._value.extend(other_arr.value)
else:
self._value.extend(other_arr)
self._append_extend_expression(other_arr=other_arr) | def extend(self, other_arr: Union[(List[T], tuple, 'Array')]) -> None:
"\n Concatenate argument array to this one. Argument array's\n values will positioned after this array's values.\n This method is similar to concat method, but there is a\n difference in whether the same variable will be\n updated (extend) or returned as a different variable (concat).\n\n Parameters\n ----------\n other_arr : list or tuple or Array\n Other array-like value to concatenate.\n\n References\n ----------\n - Array class extend and concat interfaces document\n - https://bit.ly/3r1TdIu\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 2, 3])\n >>> arr.extend([4, 5, 6])\n >>> arr\n Array([1, 2, 3, 4, 5, 6])\n "
import apysc as ap
with ap.DebugInfo(callable_=self.extend, locals_=locals(), module_name=__name__, class_=Array):
self._validate_acceptable_value_type(value=other_arr)
if isinstance(other_arr, Array):
self._value.extend(other_arr.value)
else:
self._value.extend(other_arr)
self._append_extend_expression(other_arr=other_arr)<|docstring|>Concatenate argument array to this one. Argument array's
values will positioned after this array's values.
This method is similar to concat method, but there is a
difference in whether the same variable will be
updated (extend) or returned as a different variable (concat).
Parameters
----------
other_arr : list or tuple or Array
Other array-like value to concatenate.
References
----------
- Array class extend and concat interfaces document
- https://bit.ly/3r1TdIu
Examples
--------
>>> import apysc as ap
>>> arr: ap.Array = ap.Array([1, 2, 3])
>>> arr.extend([4, 5, 6])
>>> arr
Array([1, 2, 3, 4, 5, 6])<|endoftext|> |
c534c0e7fce3873d2f5c85d41c08a28f96610d51189755779c6f4ebe45c3c3fc | def _append_extend_expression(self, *, other_arr: Union[(List[T], tuple, 'Array')]) -> None:
'\n Append extend method expression.\n\n Parameters\n ----------\n other_arr : list or tuple or Array\n Other array-like value to concatenate.\n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_extend_expression, locals_=locals(), module_name=__name__, class_=Array):
from apysc._type import value_util
value_str: str = value_util.get_value_str_for_expression(value=other_arr)
expression: str = f'{self.variable_name} = {self.variable_name}.concat({value_str});'
ap.append_js_expression(expression=expression) | Append extend method expression.
Parameters
----------
other_arr : list or tuple or Array
Other array-like value to concatenate. | apysc/_type/array.py | _append_extend_expression | simon-ritchie/apysc | 16 | python | def _append_extend_expression(self, *, other_arr: Union[(List[T], tuple, 'Array')]) -> None:
'\n Append extend method expression.\n\n Parameters\n ----------\n other_arr : list or tuple or Array\n Other array-like value to concatenate.\n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_extend_expression, locals_=locals(), module_name=__name__, class_=Array):
from apysc._type import value_util
value_str: str = value_util.get_value_str_for_expression(value=other_arr)
expression: str = f'{self.variable_name} = {self.variable_name}.concat({value_str});'
ap.append_js_expression(expression=expression) | def _append_extend_expression(self, *, other_arr: Union[(List[T], tuple, 'Array')]) -> None:
'\n Append extend method expression.\n\n Parameters\n ----------\n other_arr : list or tuple or Array\n Other array-like value to concatenate.\n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_extend_expression, locals_=locals(), module_name=__name__, class_=Array):
from apysc._type import value_util
value_str: str = value_util.get_value_str_for_expression(value=other_arr)
expression: str = f'{self.variable_name} = {self.variable_name}.concat({value_str});'
ap.append_js_expression(expression=expression)<|docstring|>Append extend method expression.
Parameters
----------
other_arr : list or tuple or Array
Other array-like value to concatenate.<|endoftext|> |
e7a0d452f02a87894df7c307228ca3f5985a95ae02952b6f1ca91e81357b44d0 | def concat(self, other_arr: Union[(List[T], tuple, 'Array')]) -> 'Array':
"\n Concatenate arugment array to this one. Argument array's\n values will positioned after this array's values.\n This method is similar to extend method, but there is a\n difference in whether the same variable will be\n updated (extend) or returned as a different variable (concat).\n\n Parameters\n ----------\n other_arr : list or tuple or Array\n Other array-like value to concatenate.\n\n Returns\n -------\n concatenated : Array\n Concatenated array value.\n\n References\n ----------\n - Array class extend and concat interfaces document\n - https://bit.ly/3r1TdIu\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 2, 3])\n >>> arr = arr.concat([4, 5, 6])\n >>> arr\n Array([1, 2, 3, 4, 5, 6])\n "
import apysc as ap
with ap.DebugInfo(callable_=self.concat, locals_=locals(), module_name=__name__, class_=Array):
concatenated: Array = self._copy()
concatenated.extend(other_arr)
self._append_concat_expression(concatenated=concatenated, other_arr=other_arr)
return concatenated | Concatenate arugment array to this one. Argument array's
values will positioned after this array's values.
This method is similar to extend method, but there is a
difference in whether the same variable will be
updated (extend) or returned as a different variable (concat).
Parameters
----------
other_arr : list or tuple or Array
Other array-like value to concatenate.
Returns
-------
concatenated : Array
Concatenated array value.
References
----------
- Array class extend and concat interfaces document
- https://bit.ly/3r1TdIu
Examples
--------
>>> import apysc as ap
>>> arr: ap.Array = ap.Array([1, 2, 3])
>>> arr = arr.concat([4, 5, 6])
>>> arr
Array([1, 2, 3, 4, 5, 6]) | apysc/_type/array.py | concat | simon-ritchie/apysc | 16 | python | def concat(self, other_arr: Union[(List[T], tuple, 'Array')]) -> 'Array':
"\n Concatenate arugment array to this one. Argument array's\n values will positioned after this array's values.\n This method is similar to extend method, but there is a\n difference in whether the same variable will be\n updated (extend) or returned as a different variable (concat).\n\n Parameters\n ----------\n other_arr : list or tuple or Array\n Other array-like value to concatenate.\n\n Returns\n -------\n concatenated : Array\n Concatenated array value.\n\n References\n ----------\n - Array class extend and concat interfaces document\n - https://bit.ly/3r1TdIu\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 2, 3])\n >>> arr = arr.concat([4, 5, 6])\n >>> arr\n Array([1, 2, 3, 4, 5, 6])\n "
import apysc as ap
with ap.DebugInfo(callable_=self.concat, locals_=locals(), module_name=__name__, class_=Array):
concatenated: Array = self._copy()
concatenated.extend(other_arr)
self._append_concat_expression(concatenated=concatenated, other_arr=other_arr)
return concatenated | def concat(self, other_arr: Union[(List[T], tuple, 'Array')]) -> 'Array':
"\n Concatenate arugment array to this one. Argument array's\n values will positioned after this array's values.\n This method is similar to extend method, but there is a\n difference in whether the same variable will be\n updated (extend) or returned as a different variable (concat).\n\n Parameters\n ----------\n other_arr : list or tuple or Array\n Other array-like value to concatenate.\n\n Returns\n -------\n concatenated : Array\n Concatenated array value.\n\n References\n ----------\n - Array class extend and concat interfaces document\n - https://bit.ly/3r1TdIu\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 2, 3])\n >>> arr = arr.concat([4, 5, 6])\n >>> arr\n Array([1, 2, 3, 4, 5, 6])\n "
import apysc as ap
with ap.DebugInfo(callable_=self.concat, locals_=locals(), module_name=__name__, class_=Array):
concatenated: Array = self._copy()
concatenated.extend(other_arr)
self._append_concat_expression(concatenated=concatenated, other_arr=other_arr)
return concatenated<|docstring|>Concatenate arugment array to this one. Argument array's
values will positioned after this array's values.
This method is similar to extend method, but there is a
difference in whether the same variable will be
updated (extend) or returned as a different variable (concat).
Parameters
----------
other_arr : list or tuple or Array
Other array-like value to concatenate.
Returns
-------
concatenated : Array
Concatenated array value.
References
----------
- Array class extend and concat interfaces document
- https://bit.ly/3r1TdIu
Examples
--------
>>> import apysc as ap
>>> arr: ap.Array = ap.Array([1, 2, 3])
>>> arr = arr.concat([4, 5, 6])
>>> arr
Array([1, 2, 3, 4, 5, 6])<|endoftext|> |
38abeb100602f3692ec03b197c62f4d17b0f99c77d614e0381fc5aed77b2b0c4 | def _append_concat_expression(self, *, concatenated: VariableNameInterface, other_arr: Union[(List[T], tuple, 'Array')]) -> None:
'\n Append concat method expression.\n\n Parameters\n ----------\n concatenated : Array\n Concatenated array value.\n other_arr : list or tuple or Array\n Other array-like value to concatenate.\n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_concat_expression, locals_=locals(), module_name=__name__, class_=Array):
from apysc._type import value_util
value_str: str = value_util.get_value_str_for_expression(value=other_arr)
expression: str = f'var {concatenated.variable_name} = {self.variable_name}.concat({value_str});'
ap.append_js_expression(expression=expression) | Append concat method expression.
Parameters
----------
concatenated : Array
Concatenated array value.
other_arr : list or tuple or Array
Other array-like value to concatenate. | apysc/_type/array.py | _append_concat_expression | simon-ritchie/apysc | 16 | python | def _append_concat_expression(self, *, concatenated: VariableNameInterface, other_arr: Union[(List[T], tuple, 'Array')]) -> None:
'\n Append concat method expression.\n\n Parameters\n ----------\n concatenated : Array\n Concatenated array value.\n other_arr : list or tuple or Array\n Other array-like value to concatenate.\n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_concat_expression, locals_=locals(), module_name=__name__, class_=Array):
from apysc._type import value_util
value_str: str = value_util.get_value_str_for_expression(value=other_arr)
expression: str = f'var {concatenated.variable_name} = {self.variable_name}.concat({value_str});'
ap.append_js_expression(expression=expression) | def _append_concat_expression(self, *, concatenated: VariableNameInterface, other_arr: Union[(List[T], tuple, 'Array')]) -> None:
'\n Append concat method expression.\n\n Parameters\n ----------\n concatenated : Array\n Concatenated array value.\n other_arr : list or tuple or Array\n Other array-like value to concatenate.\n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_concat_expression, locals_=locals(), module_name=__name__, class_=Array):
from apysc._type import value_util
value_str: str = value_util.get_value_str_for_expression(value=other_arr)
expression: str = f'var {concatenated.variable_name} = {self.variable_name}.concat({value_str});'
ap.append_js_expression(expression=expression)<|docstring|>Append concat method expression.
Parameters
----------
concatenated : Array
Concatenated array value.
other_arr : list or tuple or Array
Other array-like value to concatenate.<|endoftext|> |
e101f423203bc79139b96512ca2637c9b81a38e5f19504f0f6d283a98d8ded96 | def insert(self, index: Union[(int, Int)], value: T) -> None:
'\n Insert value to this array at a specified index.\n This behaves same as insert_at method.\n\n Parameters\n ----------\n index : int or Int\n Index to append value to.\n value : *\n Any value to append.\n\n References\n ----------\n - Array class insert and insert_at interfaces document\n - https://bit.ly/3G9LBtQ\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 3])\n >>> arr.insert(index=1, value=2)\n >>> arr\n Array([1, 2, 3])\n '
import apysc as ap
with ap.DebugInfo(callable_=self.insert, locals_=locals(), module_name=__name__, class_=Array):
from apysc._validation import number_validation
number_validation.validate_integer(integer=index)
if isinstance(index, ap.Int):
index_: int = int(index.value)
else:
index_ = index
value_: Any
if isinstance(value, ap.Int):
value_ = int(value.value)
else:
value_ = value
self._value.insert(index_, value_)
self._append_insert_expression(index=index, value=value) | Insert value to this array at a specified index.
This behaves same as insert_at method.
Parameters
----------
index : int or Int
Index to append value to.
value : *
Any value to append.
References
----------
- Array class insert and insert_at interfaces document
- https://bit.ly/3G9LBtQ
Examples
--------
>>> import apysc as ap
>>> arr: ap.Array = ap.Array([1, 3])
>>> arr.insert(index=1, value=2)
>>> arr
Array([1, 2, 3]) | apysc/_type/array.py | insert | simon-ritchie/apysc | 16 | python | def insert(self, index: Union[(int, Int)], value: T) -> None:
'\n Insert value to this array at a specified index.\n This behaves same as insert_at method.\n\n Parameters\n ----------\n index : int or Int\n Index to append value to.\n value : *\n Any value to append.\n\n References\n ----------\n - Array class insert and insert_at interfaces document\n - https://bit.ly/3G9LBtQ\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 3])\n >>> arr.insert(index=1, value=2)\n >>> arr\n Array([1, 2, 3])\n '
import apysc as ap
with ap.DebugInfo(callable_=self.insert, locals_=locals(), module_name=__name__, class_=Array):
from apysc._validation import number_validation
number_validation.validate_integer(integer=index)
if isinstance(index, ap.Int):
index_: int = int(index.value)
else:
index_ = index
value_: Any
if isinstance(value, ap.Int):
value_ = int(value.value)
else:
value_ = value
self._value.insert(index_, value_)
self._append_insert_expression(index=index, value=value) | def insert(self, index: Union[(int, Int)], value: T) -> None:
'\n Insert value to this array at a specified index.\n This behaves same as insert_at method.\n\n Parameters\n ----------\n index : int or Int\n Index to append value to.\n value : *\n Any value to append.\n\n References\n ----------\n - Array class insert and insert_at interfaces document\n - https://bit.ly/3G9LBtQ\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 3])\n >>> arr.insert(index=1, value=2)\n >>> arr\n Array([1, 2, 3])\n '
import apysc as ap
with ap.DebugInfo(callable_=self.insert, locals_=locals(), module_name=__name__, class_=Array):
from apysc._validation import number_validation
number_validation.validate_integer(integer=index)
if isinstance(index, ap.Int):
index_: int = int(index.value)
else:
index_ = index
value_: Any
if isinstance(value, ap.Int):
value_ = int(value.value)
else:
value_ = value
self._value.insert(index_, value_)
self._append_insert_expression(index=index, value=value)<|docstring|>Insert value to this array at a specified index.
This behaves same as insert_at method.
Parameters
----------
index : int or Int
Index to append value to.
value : *
Any value to append.
References
----------
- Array class insert and insert_at interfaces document
- https://bit.ly/3G9LBtQ
Examples
--------
>>> import apysc as ap
>>> arr: ap.Array = ap.Array([1, 3])
>>> arr.insert(index=1, value=2)
>>> arr
Array([1, 2, 3])<|endoftext|> |
0077cac3ad4c8a0fdf222459a1fdd97dc65df93ff7f4f8b5bd0d642da7bcbb36 | def insert_at(self, index: Union[(int, Int)], value: T) -> None:
'\n Insert value to this array at a specified index.\n This behaves same as insert method.\n\n Parameters\n ----------\n index : int or Int\n Index to append value to.\n value : *\n Any value to append.\n\n References\n ----------\n - Array class insert and insert_at interfaces document\n - https://bit.ly/3G9LBtQ\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 3])\n >>> arr.insert_at(index=1, value=2)\n >>> arr\n Array([1, 2, 3])\n '
import apysc as ap
with ap.DebugInfo(callable_=self.insert_at, locals_=locals(), module_name=__name__, class_=Array):
self.insert(index=index, value=value) | Insert value to this array at a specified index.
This behaves same as insert method.
Parameters
----------
index : int or Int
Index to append value to.
value : *
Any value to append.
References
----------
- Array class insert and insert_at interfaces document
- https://bit.ly/3G9LBtQ
Examples
--------
>>> import apysc as ap
>>> arr: ap.Array = ap.Array([1, 3])
>>> arr.insert_at(index=1, value=2)
>>> arr
Array([1, 2, 3]) | apysc/_type/array.py | insert_at | simon-ritchie/apysc | 16 | python | def insert_at(self, index: Union[(int, Int)], value: T) -> None:
'\n Insert value to this array at a specified index.\n This behaves same as insert method.\n\n Parameters\n ----------\n index : int or Int\n Index to append value to.\n value : *\n Any value to append.\n\n References\n ----------\n - Array class insert and insert_at interfaces document\n - https://bit.ly/3G9LBtQ\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 3])\n >>> arr.insert_at(index=1, value=2)\n >>> arr\n Array([1, 2, 3])\n '
import apysc as ap
with ap.DebugInfo(callable_=self.insert_at, locals_=locals(), module_name=__name__, class_=Array):
self.insert(index=index, value=value) | def insert_at(self, index: Union[(int, Int)], value: T) -> None:
'\n Insert value to this array at a specified index.\n This behaves same as insert method.\n\n Parameters\n ----------\n index : int or Int\n Index to append value to.\n value : *\n Any value to append.\n\n References\n ----------\n - Array class insert and insert_at interfaces document\n - https://bit.ly/3G9LBtQ\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 3])\n >>> arr.insert_at(index=1, value=2)\n >>> arr\n Array([1, 2, 3])\n '
import apysc as ap
with ap.DebugInfo(callable_=self.insert_at, locals_=locals(), module_name=__name__, class_=Array):
self.insert(index=index, value=value)<|docstring|>Insert value to this array at a specified index.
This behaves same as insert method.
Parameters
----------
index : int or Int
Index to append value to.
value : *
Any value to append.
References
----------
- Array class insert and insert_at interfaces document
- https://bit.ly/3G9LBtQ
Examples
--------
>>> import apysc as ap
>>> arr: ap.Array = ap.Array([1, 3])
>>> arr.insert_at(index=1, value=2)
>>> arr
Array([1, 2, 3])<|endoftext|> |
d763e748ae76221b80facedbd9de35786fe7ac660033645b218010342c389069 | def _append_insert_expression(self, *, index: Union[(int, Int)], value: T) -> None:
'\n Append insert method expression.\n\n Parameters\n ----------\n index : int or Int\n Index to append value to.\n value : *\n Any value to append.\n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_insert_expression, locals_=locals(), module_name=__name__, class_=Array):
from apysc._type import value_util
value_str: str = value_util.get_value_str_for_expression(value=value)
index_str: str = value_util.get_value_str_for_expression(value=index)
expression: str = f'{self.variable_name}.splice({index_str}, 0, {value_str});'
ap.append_js_expression(expression=expression) | Append insert method expression.
Parameters
----------
index : int or Int
Index to append value to.
value : *
Any value to append. | apysc/_type/array.py | _append_insert_expression | simon-ritchie/apysc | 16 | python | def _append_insert_expression(self, *, index: Union[(int, Int)], value: T) -> None:
'\n Append insert method expression.\n\n Parameters\n ----------\n index : int or Int\n Index to append value to.\n value : *\n Any value to append.\n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_insert_expression, locals_=locals(), module_name=__name__, class_=Array):
from apysc._type import value_util
value_str: str = value_util.get_value_str_for_expression(value=value)
index_str: str = value_util.get_value_str_for_expression(value=index)
expression: str = f'{self.variable_name}.splice({index_str}, 0, {value_str});'
ap.append_js_expression(expression=expression) | def _append_insert_expression(self, *, index: Union[(int, Int)], value: T) -> None:
'\n Append insert method expression.\n\n Parameters\n ----------\n index : int or Int\n Index to append value to.\n value : *\n Any value to append.\n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_insert_expression, locals_=locals(), module_name=__name__, class_=Array):
from apysc._type import value_util
value_str: str = value_util.get_value_str_for_expression(value=value)
index_str: str = value_util.get_value_str_for_expression(value=index)
expression: str = f'{self.variable_name}.splice({index_str}, 0, {value_str});'
ap.append_js_expression(expression=expression)<|docstring|>Append insert method expression.
Parameters
----------
index : int or Int
Index to append value to.
value : *
Any value to append.<|endoftext|> |
b0fd9e9fde4efb55c147bba72d6bf13511c4c2e7eb163209db37885e3665e6f1 | def pop(self) -> T:
"\n Remove this array's last value and return it.\n\n Returns\n -------\n value : *\n Removed value.\n\n References\n ----------\n - Array class pop interface document\n - https://simon-ritchie.github.io/apysc/array_pop.html\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 2, 3])\n >>> popped_val: int = arr.pop()\n >>> popped_val\n 3\n\n >>> arr\n Array([1, 2])\n "
import apysc as ap
with ap.DebugInfo(callable_=self.pop, locals_=locals(), module_name=__name__, class_=Array):
value: T = self._value.pop()
self._append_pop_expression(value=value)
return value | Remove this array's last value and return it.
Returns
-------
value : *
Removed value.
References
----------
- Array class pop interface document
- https://simon-ritchie.github.io/apysc/array_pop.html
Examples
--------
>>> import apysc as ap
>>> arr: ap.Array = ap.Array([1, 2, 3])
>>> popped_val: int = arr.pop()
>>> popped_val
3
>>> arr
Array([1, 2]) | apysc/_type/array.py | pop | simon-ritchie/apysc | 16 | python | def pop(self) -> T:
"\n Remove this array's last value and return it.\n\n Returns\n -------\n value : *\n Removed value.\n\n References\n ----------\n - Array class pop interface document\n - https://simon-ritchie.github.io/apysc/array_pop.html\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 2, 3])\n >>> popped_val: int = arr.pop()\n >>> popped_val\n 3\n\n >>> arr\n Array([1, 2])\n "
import apysc as ap
with ap.DebugInfo(callable_=self.pop, locals_=locals(), module_name=__name__, class_=Array):
value: T = self._value.pop()
self._append_pop_expression(value=value)
return value | def pop(self) -> T:
"\n Remove this array's last value and return it.\n\n Returns\n -------\n value : *\n Removed value.\n\n References\n ----------\n - Array class pop interface document\n - https://simon-ritchie.github.io/apysc/array_pop.html\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 2, 3])\n >>> popped_val: int = arr.pop()\n >>> popped_val\n 3\n\n >>> arr\n Array([1, 2])\n "
import apysc as ap
with ap.DebugInfo(callable_=self.pop, locals_=locals(), module_name=__name__, class_=Array):
value: T = self._value.pop()
self._append_pop_expression(value=value)
return value<|docstring|>Remove this array's last value and return it.
Returns
-------
value : *
Removed value.
References
----------
- Array class pop interface document
- https://simon-ritchie.github.io/apysc/array_pop.html
Examples
--------
>>> import apysc as ap
>>> arr: ap.Array = ap.Array([1, 2, 3])
>>> popped_val: int = arr.pop()
>>> popped_val
3
>>> arr
Array([1, 2])<|endoftext|> |
c64859a7d7e38c81983971a8f23deabe931f2c7dae00d719696b0fc4fc10b8de | def _append_pop_expression(self, *, value: T) -> None:
'\n Append pop method expression.\n\n Parameters\n ----------\n value : *\n Removed value.\n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_pop_expression, locals_=locals(), module_name=__name__, class_=Array):
expression: str = f'{self.variable_name}.pop();'
if isinstance(value, VariableNameInterface):
expression = f'{value.variable_name} = {expression}'
ap.append_js_expression(expression=expression) | Append pop method expression.
Parameters
----------
value : *
Removed value. | apysc/_type/array.py | _append_pop_expression | simon-ritchie/apysc | 16 | python | def _append_pop_expression(self, *, value: T) -> None:
'\n Append pop method expression.\n\n Parameters\n ----------\n value : *\n Removed value.\n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_pop_expression, locals_=locals(), module_name=__name__, class_=Array):
expression: str = f'{self.variable_name}.pop();'
if isinstance(value, VariableNameInterface):
expression = f'{value.variable_name} = {expression}'
ap.append_js_expression(expression=expression) | def _append_pop_expression(self, *, value: T) -> None:
'\n Append pop method expression.\n\n Parameters\n ----------\n value : *\n Removed value.\n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_pop_expression, locals_=locals(), module_name=__name__, class_=Array):
expression: str = f'{self.variable_name}.pop();'
if isinstance(value, VariableNameInterface):
expression = f'{value.variable_name} = {expression}'
ap.append_js_expression(expression=expression)<|docstring|>Append pop method expression.
Parameters
----------
value : *
Removed value.<|endoftext|> |
0e01d07779710bc3cdf225b5c5296556dc091fe68ef7124e9e866866ec43cb2a | def remove(self, value: T) -> None:
'\n Remove specified value from this array.\n\n Parameters\n ----------\n value : Any\n Value to remove.\n\n References\n ----------\n - Array class remove and remove_at interfaces document\n - https://bit.ly/3zDO6Cl\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 3, 5])\n >>> arr.remove(3)\n >>> arr\n Array([1, 5])\n '
import apysc as ap
with ap.DebugInfo(callable_=self.remove, locals_=locals(), module_name=__name__, class_=Array):
self._value.remove(value)
self._append_remove_expression(value=value) | Remove specified value from this array.
Parameters
----------
value : Any
Value to remove.
References
----------
- Array class remove and remove_at interfaces document
- https://bit.ly/3zDO6Cl
Examples
--------
>>> import apysc as ap
>>> arr: ap.Array = ap.Array([1, 3, 5])
>>> arr.remove(3)
>>> arr
Array([1, 5]) | apysc/_type/array.py | remove | simon-ritchie/apysc | 16 | python | def remove(self, value: T) -> None:
'\n Remove specified value from this array.\n\n Parameters\n ----------\n value : Any\n Value to remove.\n\n References\n ----------\n - Array class remove and remove_at interfaces document\n - https://bit.ly/3zDO6Cl\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 3, 5])\n >>> arr.remove(3)\n >>> arr\n Array([1, 5])\n '
import apysc as ap
with ap.DebugInfo(callable_=self.remove, locals_=locals(), module_name=__name__, class_=Array):
self._value.remove(value)
self._append_remove_expression(value=value) | def remove(self, value: T) -> None:
'\n Remove specified value from this array.\n\n Parameters\n ----------\n value : Any\n Value to remove.\n\n References\n ----------\n - Array class remove and remove_at interfaces document\n - https://bit.ly/3zDO6Cl\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 3, 5])\n >>> arr.remove(3)\n >>> arr\n Array([1, 5])\n '
import apysc as ap
with ap.DebugInfo(callable_=self.remove, locals_=locals(), module_name=__name__, class_=Array):
self._value.remove(value)
self._append_remove_expression(value=value)<|docstring|>Remove specified value from this array.
Parameters
----------
value : Any
Value to remove.
References
----------
- Array class remove and remove_at interfaces document
- https://bit.ly/3zDO6Cl
Examples
--------
>>> import apysc as ap
>>> arr: ap.Array = ap.Array([1, 3, 5])
>>> arr.remove(3)
>>> arr
Array([1, 5])<|endoftext|> |
1d61729a5f0e9391d8d0a868caadc202f886a36e8cf20cd209d838ff5a30415e | def _append_remove_expression(self, *, value: T) -> None:
'\n Append remove method expression.\n\n Parameters\n ----------\n value : Any\n Value to remove.\n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_remove_expression, locals_=locals(), module_name=__name__, class_=Array):
from apysc._expression import expression_variables_util
from apysc._expression import var_names
from apysc._type import value_util
index_var_name: str = expression_variables_util.get_next_variable_name(type_name=var_names.INDEX)
value_str: str = value_util.get_value_str_for_expression(value=value)
expression: str = f'''var {index_var_name} = _.indexOf({self.variable_name}, {value_str});
{self.variable_name}.splice({index_var_name}, 1);'''
ap.append_js_expression(expression=expression) | Append remove method expression.
Parameters
----------
value : Any
Value to remove. | apysc/_type/array.py | _append_remove_expression | simon-ritchie/apysc | 16 | python | def _append_remove_expression(self, *, value: T) -> None:
'\n Append remove method expression.\n\n Parameters\n ----------\n value : Any\n Value to remove.\n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_remove_expression, locals_=locals(), module_name=__name__, class_=Array):
from apysc._expression import expression_variables_util
from apysc._expression import var_names
from apysc._type import value_util
index_var_name: str = expression_variables_util.get_next_variable_name(type_name=var_names.INDEX)
value_str: str = value_util.get_value_str_for_expression(value=value)
expression: str = f'var {index_var_name} = _.indexOf({self.variable_name}, {value_str});
{self.variable_name}.splice({index_var_name}, 1);'
ap.append_js_expression(expression=expression) | def _append_remove_expression(self, *, value: T) -> None:
'\n Append remove method expression.\n\n Parameters\n ----------\n value : Any\n Value to remove.\n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_remove_expression, locals_=locals(), module_name=__name__, class_=Array):
from apysc._expression import expression_variables_util
from apysc._expression import var_names
from apysc._type import value_util
index_var_name: str = expression_variables_util.get_next_variable_name(type_name=var_names.INDEX)
value_str: str = value_util.get_value_str_for_expression(value=value)
expression: str = f'var {index_var_name} = _.indexOf({self.variable_name}, {value_str});
{self.variable_name}.splice({index_var_name}, 1);'
ap.append_js_expression(expression=expression)<|docstring|>Append remove method expression.
Parameters
----------
value : Any
Value to remove.<|endoftext|> |
0ec127df0e87f1589d4b8aa8ca900ffa936476920472084711218a2955df3706 | def remove_at(self, index: Union[(int, Int)]) -> None:
'\n Remove specified index value from this array.\n\n Parameters\n ----------\n index : int or Int\n Index to remove value.\n\n References\n ----------\n - Array class remove and remove_at interfaces document\n - https://bit.ly/3zDO6Cl\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 2, 3])\n >>> arr.remove_at(1)\n >>> arr\n Array([1, 3])\n '
import apysc as ap
with ap.DebugInfo(callable_=self.remove_at, locals_=locals(), module_name=__name__, class_=Array):
self._validate_index_type_is_int(index=index)
if isinstance(index, ap.Int):
index_: int = int(index.value)
else:
index_ = index
if (index_ in self._value):
del self._value[index_]
self._append_remove_at_expression(index=index) | Remove specified index value from this array.
Parameters
----------
index : int or Int
Index to remove value.
References
----------
- Array class remove and remove_at interfaces document
- https://bit.ly/3zDO6Cl
Examples
--------
>>> import apysc as ap
>>> arr: ap.Array = ap.Array([1, 2, 3])
>>> arr.remove_at(1)
>>> arr
Array([1, 3]) | apysc/_type/array.py | remove_at | simon-ritchie/apysc | 16 | python | def remove_at(self, index: Union[(int, Int)]) -> None:
'\n Remove specified index value from this array.\n\n Parameters\n ----------\n index : int or Int\n Index to remove value.\n\n References\n ----------\n - Array class remove and remove_at interfaces document\n - https://bit.ly/3zDO6Cl\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 2, 3])\n >>> arr.remove_at(1)\n >>> arr\n Array([1, 3])\n '
import apysc as ap
with ap.DebugInfo(callable_=self.remove_at, locals_=locals(), module_name=__name__, class_=Array):
self._validate_index_type_is_int(index=index)
if isinstance(index, ap.Int):
index_: int = int(index.value)
else:
index_ = index
if (index_ in self._value):
del self._value[index_]
self._append_remove_at_expression(index=index) | def remove_at(self, index: Union[(int, Int)]) -> None:
'\n Remove specified index value from this array.\n\n Parameters\n ----------\n index : int or Int\n Index to remove value.\n\n References\n ----------\n - Array class remove and remove_at interfaces document\n - https://bit.ly/3zDO6Cl\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 2, 3])\n >>> arr.remove_at(1)\n >>> arr\n Array([1, 3])\n '
import apysc as ap
with ap.DebugInfo(callable_=self.remove_at, locals_=locals(), module_name=__name__, class_=Array):
self._validate_index_type_is_int(index=index)
if isinstance(index, ap.Int):
index_: int = int(index.value)
else:
index_ = index
if (index_ in self._value):
del self._value[index_]
self._append_remove_at_expression(index=index)<|docstring|>Remove specified index value from this array.
Parameters
----------
index : int or Int
Index to remove value.
References
----------
- Array class remove and remove_at interfaces document
- https://bit.ly/3zDO6Cl
Examples
--------
>>> import apysc as ap
>>> arr: ap.Array = ap.Array([1, 2, 3])
>>> arr.remove_at(1)
>>> arr
Array([1, 3])<|endoftext|> |
acd2e44bcc221bb2900d814f1e89f7b823375629849cc55498a82f2b904ae9f6 | def _append_remove_at_expression(self, *, index: Union[(int, Int)]) -> None:
'\n Append remove_at method expression.\n\n Parameters\n ----------\n index : int or Int\n Index to remove value.\n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_remove_at_expression, locals_=locals(), module_name=__name__, class_=Array):
from apysc._type import value_util
index_str: str = value_util.get_value_str_for_expression(value=index)
expression: str = f'{self.variable_name}.splice({index_str}, 1);'
ap.append_js_expression(expression=expression) | Append remove_at method expression.
Parameters
----------
index : int or Int
Index to remove value. | apysc/_type/array.py | _append_remove_at_expression | simon-ritchie/apysc | 16 | python | def _append_remove_at_expression(self, *, index: Union[(int, Int)]) -> None:
'\n Append remove_at method expression.\n\n Parameters\n ----------\n index : int or Int\n Index to remove value.\n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_remove_at_expression, locals_=locals(), module_name=__name__, class_=Array):
from apysc._type import value_util
index_str: str = value_util.get_value_str_for_expression(value=index)
expression: str = f'{self.variable_name}.splice({index_str}, 1);'
ap.append_js_expression(expression=expression) | def _append_remove_at_expression(self, *, index: Union[(int, Int)]) -> None:
'\n Append remove_at method expression.\n\n Parameters\n ----------\n index : int or Int\n Index to remove value.\n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_remove_at_expression, locals_=locals(), module_name=__name__, class_=Array):
from apysc._type import value_util
index_str: str = value_util.get_value_str_for_expression(value=index)
expression: str = f'{self.variable_name}.splice({index_str}, 1);'
ap.append_js_expression(expression=expression)<|docstring|>Append remove_at method expression.
Parameters
----------
index : int or Int
Index to remove value.<|endoftext|> |
d9c3ffdbedcc360049c8b3741812c037e601cb0bd05fd5546e54b2be7a38488a | def reverse(self) -> None:
'\n Reverse this array in place.\n\n References\n ----------\n - Array class reverse interface document\n - https://simon-ritchie.github.io/apysc/array_reverse.html\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 2, 3])\n >>> arr.reverse()\n >>> arr\n Array([3, 2, 1])\n '
import apysc as ap
with ap.DebugInfo(callable_=self.reverse, locals_=locals(), module_name=__name__, class_=Array):
self._value.reverse()
self._append_reverse_expression() | Reverse this array in place.
References
----------
- Array class reverse interface document
- https://simon-ritchie.github.io/apysc/array_reverse.html
Examples
--------
>>> import apysc as ap
>>> arr: ap.Array = ap.Array([1, 2, 3])
>>> arr.reverse()
>>> arr
Array([3, 2, 1]) | apysc/_type/array.py | reverse | simon-ritchie/apysc | 16 | python | def reverse(self) -> None:
'\n Reverse this array in place.\n\n References\n ----------\n - Array class reverse interface document\n - https://simon-ritchie.github.io/apysc/array_reverse.html\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 2, 3])\n >>> arr.reverse()\n >>> arr\n Array([3, 2, 1])\n '
import apysc as ap
with ap.DebugInfo(callable_=self.reverse, locals_=locals(), module_name=__name__, class_=Array):
self._value.reverse()
self._append_reverse_expression() | def reverse(self) -> None:
'\n Reverse this array in place.\n\n References\n ----------\n - Array class reverse interface document\n - https://simon-ritchie.github.io/apysc/array_reverse.html\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 2, 3])\n >>> arr.reverse()\n >>> arr\n Array([3, 2, 1])\n '
import apysc as ap
with ap.DebugInfo(callable_=self.reverse, locals_=locals(), module_name=__name__, class_=Array):
self._value.reverse()
self._append_reverse_expression()<|docstring|>Reverse this array in place.
References
----------
- Array class reverse interface document
- https://simon-ritchie.github.io/apysc/array_reverse.html
Examples
--------
>>> import apysc as ap
>>> arr: ap.Array = ap.Array([1, 2, 3])
>>> arr.reverse()
>>> arr
Array([3, 2, 1])<|endoftext|> |
d9492865d710613a2d3c7c6e54c25ad3693a18b11b7cdce2f9e2de6bfb9e0857 | def _append_reverse_expression(self) -> None:
'\n Append reverse method expression.\n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_reverse_expression, locals_=locals(), module_name=__name__, class_=Array):
expression: str = f'{self.variable_name}.reverse();'
ap.append_js_expression(expression=expression) | Append reverse method expression. | apysc/_type/array.py | _append_reverse_expression | simon-ritchie/apysc | 16 | python | def _append_reverse_expression(self) -> None:
'\n \n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_reverse_expression, locals_=locals(), module_name=__name__, class_=Array):
expression: str = f'{self.variable_name}.reverse();'
ap.append_js_expression(expression=expression) | def _append_reverse_expression(self) -> None:
'\n \n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_reverse_expression, locals_=locals(), module_name=__name__, class_=Array):
expression: str = f'{self.variable_name}.reverse();'
ap.append_js_expression(expression=expression)<|docstring|>Append reverse method expression.<|endoftext|> |
46fee2cc7e9b51ff5d4237dc489250d466093bb38082dc754bb770631e0b9ee9 | def sort(self, *, ascending: bool=True) -> None:
'\n Sort this array in place.\n\n Parameters\n ----------\n ascending : bool, default True\n Sort by ascending or not. If False is specified,\n values will be descending.\n\n References\n ----------\n - Array class sort interface document\n - https://simon-ritchie.github.io/apysc/array_sort.html\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([3, 5, 1, 4, 2])\n >>> arr.sort()\n >>> arr\n Array([1, 2, 3, 4, 5])\n\n >>> arr.sort(ascending=False)\n >>> arr\n Array([5, 4, 3, 2, 1])\n '
import apysc as ap
with ap.DebugInfo(callable_=self.sort, locals_=locals(), module_name=__name__, class_=Array):
self._value.sort()
self._append_sort_expression()
if (not ascending):
self.reverse() | Sort this array in place.
Parameters
----------
ascending : bool, default True
Sort by ascending or not. If False is specified,
values will be descending.
References
----------
- Array class sort interface document
- https://simon-ritchie.github.io/apysc/array_sort.html
Examples
--------
>>> import apysc as ap
>>> arr: ap.Array = ap.Array([3, 5, 1, 4, 2])
>>> arr.sort()
>>> arr
Array([1, 2, 3, 4, 5])
>>> arr.sort(ascending=False)
>>> arr
Array([5, 4, 3, 2, 1]) | apysc/_type/array.py | sort | simon-ritchie/apysc | 16 | python | def sort(self, *, ascending: bool=True) -> None:
'\n Sort this array in place.\n\n Parameters\n ----------\n ascending : bool, default True\n Sort by ascending or not. If False is specified,\n values will be descending.\n\n References\n ----------\n - Array class sort interface document\n - https://simon-ritchie.github.io/apysc/array_sort.html\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([3, 5, 1, 4, 2])\n >>> arr.sort()\n >>> arr\n Array([1, 2, 3, 4, 5])\n\n >>> arr.sort(ascending=False)\n >>> arr\n Array([5, 4, 3, 2, 1])\n '
import apysc as ap
with ap.DebugInfo(callable_=self.sort, locals_=locals(), module_name=__name__, class_=Array):
self._value.sort()
self._append_sort_expression()
if (not ascending):
self.reverse() | def sort(self, *, ascending: bool=True) -> None:
'\n Sort this array in place.\n\n Parameters\n ----------\n ascending : bool, default True\n Sort by ascending or not. If False is specified,\n values will be descending.\n\n References\n ----------\n - Array class sort interface document\n - https://simon-ritchie.github.io/apysc/array_sort.html\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([3, 5, 1, 4, 2])\n >>> arr.sort()\n >>> arr\n Array([1, 2, 3, 4, 5])\n\n >>> arr.sort(ascending=False)\n >>> arr\n Array([5, 4, 3, 2, 1])\n '
import apysc as ap
with ap.DebugInfo(callable_=self.sort, locals_=locals(), module_name=__name__, class_=Array):
self._value.sort()
self._append_sort_expression()
if (not ascending):
self.reverse()<|docstring|>Sort this array in place.
Parameters
----------
ascending : bool, default True
Sort by ascending or not. If False is specified,
values will be descending.
References
----------
- Array class sort interface document
- https://simon-ritchie.github.io/apysc/array_sort.html
Examples
--------
>>> import apysc as ap
>>> arr: ap.Array = ap.Array([3, 5, 1, 4, 2])
>>> arr.sort()
>>> arr
Array([1, 2, 3, 4, 5])
>>> arr.sort(ascending=False)
>>> arr
Array([5, 4, 3, 2, 1])<|endoftext|> |
14600cafa973bb9c1fea288f13985faf2b3890bec36b32bed46282210b6d5d40 | def _append_sort_expression(self) -> None:
'\n Append sort method expression.\n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_sort_expression, locals_=locals(), module_name=__name__, class_=Array):
expression: str = f'{self.variable_name}.sort();'
ap.append_js_expression(expression=expression) | Append sort method expression. | apysc/_type/array.py | _append_sort_expression | simon-ritchie/apysc | 16 | python | def _append_sort_expression(self) -> None:
'\n \n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_sort_expression, locals_=locals(), module_name=__name__, class_=Array):
expression: str = f'{self.variable_name}.sort();'
ap.append_js_expression(expression=expression) | def _append_sort_expression(self) -> None:
'\n \n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_sort_expression, locals_=locals(), module_name=__name__, class_=Array):
expression: str = f'{self.variable_name}.sort();'
ap.append_js_expression(expression=expression)<|docstring|>Append sort method expression.<|endoftext|> |
40bdbdcf9688ec54d807460ea0084644de3f902510a16de70e7b8032292baff1 | def slice(self, *, start: Optional[Union[(int, Int)]]=None, end: Optional[Union[(int, Int)]]=None) -> 'Array':
'\n Slice this array by specified start and end indexes.\n\n Parameters\n ----------\n start : int or Int or None, default None\n Slicing start index.\n end : int or Int or None, default None\n Slicing end index (this index will not be including).\n\n Returns\n -------\n sliced_arr : Array\n Sliced array.\n\n References\n ----------\n - Array class slice interface document\n - https://simon-ritchie.github.io/apysc/array_slice.html\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 2, 3, 4])\n >>> arr.slice(start=1, end=3)\n Array([2, 3])\n\n >>> arr.slice(start=1)\n Array([2, 3, 4])\n\n >>> arr.slice(end=2)\n Array([1, 2])\n '
import apysc as ap
with ap.DebugInfo(callable_=self.slice, locals_=locals(), module_name=__name__, class_=Array):
if isinstance(start, ap.Int):
start_: Optional[int] = int(start.value)
else:
start_ = start
if isinstance(end, ap.Int):
end_: Optional[int] = int(end.value)
else:
end_ = end
sliced_arr: Array = self._copy()
sliced_arr._value = self._value[slice(start_, end_)]
self._append_slice_expression(sliced_arr=sliced_arr, start=start, end=end)
return sliced_arr | Slice this array by specified start and end indexes.
Parameters
----------
start : int or Int or None, default None
Slicing start index.
end : int or Int or None, default None
Slicing end index (this index will not be including).
Returns
-------
sliced_arr : Array
Sliced array.
References
----------
- Array class slice interface document
- https://simon-ritchie.github.io/apysc/array_slice.html
Examples
--------
>>> import apysc as ap
>>> arr: ap.Array = ap.Array([1, 2, 3, 4])
>>> arr.slice(start=1, end=3)
Array([2, 3])
>>> arr.slice(start=1)
Array([2, 3, 4])
>>> arr.slice(end=2)
Array([1, 2]) | apysc/_type/array.py | slice | simon-ritchie/apysc | 16 | python | def slice(self, *, start: Optional[Union[(int, Int)]]=None, end: Optional[Union[(int, Int)]]=None) -> 'Array':
'\n Slice this array by specified start and end indexes.\n\n Parameters\n ----------\n start : int or Int or None, default None\n Slicing start index.\n end : int or Int or None, default None\n Slicing end index (this index will not be including).\n\n Returns\n -------\n sliced_arr : Array\n Sliced array.\n\n References\n ----------\n - Array class slice interface document\n - https://simon-ritchie.github.io/apysc/array_slice.html\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 2, 3, 4])\n >>> arr.slice(start=1, end=3)\n Array([2, 3])\n\n >>> arr.slice(start=1)\n Array([2, 3, 4])\n\n >>> arr.slice(end=2)\n Array([1, 2])\n '
import apysc as ap
with ap.DebugInfo(callable_=self.slice, locals_=locals(), module_name=__name__, class_=Array):
if isinstance(start, ap.Int):
start_: Optional[int] = int(start.value)
else:
start_ = start
if isinstance(end, ap.Int):
end_: Optional[int] = int(end.value)
else:
end_ = end
sliced_arr: Array = self._copy()
sliced_arr._value = self._value[slice(start_, end_)]
self._append_slice_expression(sliced_arr=sliced_arr, start=start, end=end)
return sliced_arr | def slice(self, *, start: Optional[Union[(int, Int)]]=None, end: Optional[Union[(int, Int)]]=None) -> 'Array':
'\n Slice this array by specified start and end indexes.\n\n Parameters\n ----------\n start : int or Int or None, default None\n Slicing start index.\n end : int or Int or None, default None\n Slicing end index (this index will not be including).\n\n Returns\n -------\n sliced_arr : Array\n Sliced array.\n\n References\n ----------\n - Array class slice interface document\n - https://simon-ritchie.github.io/apysc/array_slice.html\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 2, 3, 4])\n >>> arr.slice(start=1, end=3)\n Array([2, 3])\n\n >>> arr.slice(start=1)\n Array([2, 3, 4])\n\n >>> arr.slice(end=2)\n Array([1, 2])\n '
import apysc as ap
with ap.DebugInfo(callable_=self.slice, locals_=locals(), module_name=__name__, class_=Array):
if isinstance(start, ap.Int):
start_: Optional[int] = int(start.value)
else:
start_ = start
if isinstance(end, ap.Int):
end_: Optional[int] = int(end.value)
else:
end_ = end
sliced_arr: Array = self._copy()
sliced_arr._value = self._value[slice(start_, end_)]
self._append_slice_expression(sliced_arr=sliced_arr, start=start, end=end)
return sliced_arr<|docstring|>Slice this array by specified start and end indexes.
Parameters
----------
start : int or Int or None, default None
Slicing start index.
end : int or Int or None, default None
Slicing end index (this index will not be including).
Returns
-------
sliced_arr : Array
Sliced array.
References
----------
- Array class slice interface document
- https://simon-ritchie.github.io/apysc/array_slice.html
Examples
--------
>>> import apysc as ap
>>> arr: ap.Array = ap.Array([1, 2, 3, 4])
>>> arr.slice(start=1, end=3)
Array([2, 3])
>>> arr.slice(start=1)
Array([2, 3, 4])
>>> arr.slice(end=2)
Array([1, 2])<|endoftext|> |
aa88234ce74b2c77c80b76e13069429f79d1657dc4e9423b8a2ed402da045480 | def _append_slice_expression(self, *, sliced_arr: VariableNameInterface, start: Optional[Union[(int, Int)]], end: Optional[Union[(int, Int)]]) -> None:
'\n Append slice method expression.\n\n Parameters\n ----------\n sliced_arr : Array\n Sliced array.\n start : int or Int or None\n Slicing start index.\n end : int or Int or None\n Slicing end index.\n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_slice_expression, locals_=locals(), module_name=__name__, class_=Array):
if (start is None):
start = 0
expression: str = f'var {sliced_arr.variable_name} = {self.variable_name}.slice({start}'
if (end is not None):
expression += f', {end}'
expression += ');'
ap.append_js_expression(expression=expression) | Append slice method expression.
Parameters
----------
sliced_arr : Array
Sliced array.
start : int or Int or None
Slicing start index.
end : int or Int or None
Slicing end index. | apysc/_type/array.py | _append_slice_expression | simon-ritchie/apysc | 16 | python | def _append_slice_expression(self, *, sliced_arr: VariableNameInterface, start: Optional[Union[(int, Int)]], end: Optional[Union[(int, Int)]]) -> None:
'\n Append slice method expression.\n\n Parameters\n ----------\n sliced_arr : Array\n Sliced array.\n start : int or Int or None\n Slicing start index.\n end : int or Int or None\n Slicing end index.\n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_slice_expression, locals_=locals(), module_name=__name__, class_=Array):
if (start is None):
start = 0
expression: str = f'var {sliced_arr.variable_name} = {self.variable_name}.slice({start}'
if (end is not None):
expression += f', {end}'
expression += ');'
ap.append_js_expression(expression=expression) | def _append_slice_expression(self, *, sliced_arr: VariableNameInterface, start: Optional[Union[(int, Int)]], end: Optional[Union[(int, Int)]]) -> None:
'\n Append slice method expression.\n\n Parameters\n ----------\n sliced_arr : Array\n Sliced array.\n start : int or Int or None\n Slicing start index.\n end : int or Int or None\n Slicing end index.\n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_slice_expression, locals_=locals(), module_name=__name__, class_=Array):
if (start is None):
start = 0
expression: str = f'var {sliced_arr.variable_name} = {self.variable_name}.slice({start}'
if (end is not None):
expression += f', {end}'
expression += ');'
ap.append_js_expression(expression=expression)<|docstring|>Append slice method expression.
Parameters
----------
sliced_arr : Array
Sliced array.
start : int or Int or None
Slicing start index.
end : int or Int or None
Slicing end index.<|endoftext|> |
bad3649734137dddf6dccf74f95d8156184d68beabb5b37ddae211985d5da692 | def __getitem__(self, index: Union[(int, Int)]) -> T:
"\n Get a specified index single value.\n\n Parameters\n ----------\n index : int or Int\n Array's index to get value. Currently not supported tuple\n value (e.g., slicing).\n\n Returns\n -------\n value : *\n Specified index's value.\n\n Raises\n ------\n ValueError\n If specified index type is not int and Int.\n "
import apysc as ap
with ap.DebugInfo(callable_='__getitem__', locals_=locals(), module_name=__name__, class_=Array):
self._validate_index_type_is_int(index=index)
index_: int = self._get_builtin_int_from_index(index=index)
value: Any
if (len(self._value) <= index):
value = ap.AnyValue(None)
else:
value = self._value[index_]
self._append_getitem_expression(index=index, value=value)
return value | Get a specified index single value.
Parameters
----------
index : int or Int
Array's index to get value. Currently not supported tuple
value (e.g., slicing).
Returns
-------
value : *
Specified index's value.
Raises
------
ValueError
If specified index type is not int and Int. | apysc/_type/array.py | __getitem__ | simon-ritchie/apysc | 16 | python | def __getitem__(self, index: Union[(int, Int)]) -> T:
"\n Get a specified index single value.\n\n Parameters\n ----------\n index : int or Int\n Array's index to get value. Currently not supported tuple\n value (e.g., slicing).\n\n Returns\n -------\n value : *\n Specified index's value.\n\n Raises\n ------\n ValueError\n If specified index type is not int and Int.\n "
import apysc as ap
with ap.DebugInfo(callable_='__getitem__', locals_=locals(), module_name=__name__, class_=Array):
self._validate_index_type_is_int(index=index)
index_: int = self._get_builtin_int_from_index(index=index)
value: Any
if (len(self._value) <= index):
value = ap.AnyValue(None)
else:
value = self._value[index_]
self._append_getitem_expression(index=index, value=value)
return value | def __getitem__(self, index: Union[(int, Int)]) -> T:
"\n Get a specified index single value.\n\n Parameters\n ----------\n index : int or Int\n Array's index to get value. Currently not supported tuple\n value (e.g., slicing).\n\n Returns\n -------\n value : *\n Specified index's value.\n\n Raises\n ------\n ValueError\n If specified index type is not int and Int.\n "
import apysc as ap
with ap.DebugInfo(callable_='__getitem__', locals_=locals(), module_name=__name__, class_=Array):
self._validate_index_type_is_int(index=index)
index_: int = self._get_builtin_int_from_index(index=index)
value: Any
if (len(self._value) <= index):
value = ap.AnyValue(None)
else:
value = self._value[index_]
self._append_getitem_expression(index=index, value=value)
return value<|docstring|>Get a specified index single value.
Parameters
----------
index : int or Int
Array's index to get value. Currently not supported tuple
value (e.g., slicing).
Returns
-------
value : *
Specified index's value.
Raises
------
ValueError
If specified index type is not int and Int.<|endoftext|> |
1bf7c2138d5d0f701384ea6b2d623e5162da655499e0596d6601b4c5e1c6a26f | def _get_builtin_int_from_index(self, *, index: Union[(int, Int)]) -> int:
"\n Get Python builtin integer from index value.\n\n Parameters\n ----------\n index : int or Int\n Specified array's index.\n\n Returns\n -------\n builtin_int_index : int\n Python builtin integer index value.\n "
import apysc as ap
if isinstance(index, ap.Int):
return int(index.value)
return index | Get Python builtin integer from index value.
Parameters
----------
index : int or Int
Specified array's index.
Returns
-------
builtin_int_index : int
Python builtin integer index value. | apysc/_type/array.py | _get_builtin_int_from_index | simon-ritchie/apysc | 16 | python | def _get_builtin_int_from_index(self, *, index: Union[(int, Int)]) -> int:
"\n Get Python builtin integer from index value.\n\n Parameters\n ----------\n index : int or Int\n Specified array's index.\n\n Returns\n -------\n builtin_int_index : int\n Python builtin integer index value.\n "
import apysc as ap
if isinstance(index, ap.Int):
return int(index.value)
return index | def _get_builtin_int_from_index(self, *, index: Union[(int, Int)]) -> int:
"\n Get Python builtin integer from index value.\n\n Parameters\n ----------\n index : int or Int\n Specified array's index.\n\n Returns\n -------\n builtin_int_index : int\n Python builtin integer index value.\n "
import apysc as ap
if isinstance(index, ap.Int):
return int(index.value)
return index<|docstring|>Get Python builtin integer from index value.
Parameters
----------
index : int or Int
Specified array's index.
Returns
-------
builtin_int_index : int
Python builtin integer index value.<|endoftext|> |
5ebbb7a00c2918a2357526d49ec3c92d636584d5cdd04393dfc3e99a89357f4b | def _validate_index_type_is_int(self, *, index: Union[(int, Int)]) -> None:
'\n Validate whether index value type is int (or Int) or not.\n\n Parameters\n ----------\n index : int or Int\n Index value to check.\n\n Raises\n ------\n ValueError\n If index type is not int or Int type.\n '
if isinstance(index, (int, Int)):
return
raise ValueError('Currently indexing is only supported int or Int types. If you need to slice array please use slice method.') | Validate whether index value type is int (or Int) or not.
Parameters
----------
index : int or Int
Index value to check.
Raises
------
ValueError
If index type is not int or Int type. | apysc/_type/array.py | _validate_index_type_is_int | simon-ritchie/apysc | 16 | python | def _validate_index_type_is_int(self, *, index: Union[(int, Int)]) -> None:
'\n Validate whether index value type is int (or Int) or not.\n\n Parameters\n ----------\n index : int or Int\n Index value to check.\n\n Raises\n ------\n ValueError\n If index type is not int or Int type.\n '
if isinstance(index, (int, Int)):
return
raise ValueError('Currently indexing is only supported int or Int types. If you need to slice array please use slice method.') | def _validate_index_type_is_int(self, *, index: Union[(int, Int)]) -> None:
'\n Validate whether index value type is int (or Int) or not.\n\n Parameters\n ----------\n index : int or Int\n Index value to check.\n\n Raises\n ------\n ValueError\n If index type is not int or Int type.\n '
if isinstance(index, (int, Int)):
return
raise ValueError('Currently indexing is only supported int or Int types. If you need to slice array please use slice method.')<|docstring|>Validate whether index value type is int (or Int) or not.
Parameters
----------
index : int or Int
Index value to check.
Raises
------
ValueError
If index type is not int or Int type.<|endoftext|> |
98db2444a0eb3d82ac30b7230567c6a87fe4f5df8dbd1f1d370cb7011bdc1b8a | def _append_getitem_expression(self, *, index: Union[(int, Int)], value: T) -> None:
"\n Append __getitem__ expression.\n\n Parameters\n ----------\n index : int or Int\n Array's index to get value.\n value : *\n Specified index's value.\n "
import apysc as ap
with ap.DebugInfo(callable_=self._append_getitem_expression, locals_=locals(), module_name=__name__, class_=Array):
from apysc._type import value_util
value_: VariableNameInterface
if (not isinstance(value, VariableNameInterface)):
value_ = ap.AnyValue(None)
else:
value_ = value
index_str: str = value_util.get_value_str_for_expression(value=index)
expression: str = f'var {value_.variable_name} = {self.variable_name}[{index_str}];'
ap.append_js_expression(expression=expression) | Append __getitem__ expression.
Parameters
----------
index : int or Int
Array's index to get value.
value : *
Specified index's value. | apysc/_type/array.py | _append_getitem_expression | simon-ritchie/apysc | 16 | python | def _append_getitem_expression(self, *, index: Union[(int, Int)], value: T) -> None:
"\n Append __getitem__ expression.\n\n Parameters\n ----------\n index : int or Int\n Array's index to get value.\n value : *\n Specified index's value.\n "
import apysc as ap
with ap.DebugInfo(callable_=self._append_getitem_expression, locals_=locals(), module_name=__name__, class_=Array):
from apysc._type import value_util
value_: VariableNameInterface
if (not isinstance(value, VariableNameInterface)):
value_ = ap.AnyValue(None)
else:
value_ = value
index_str: str = value_util.get_value_str_for_expression(value=index)
expression: str = f'var {value_.variable_name} = {self.variable_name}[{index_str}];'
ap.append_js_expression(expression=expression) | def _append_getitem_expression(self, *, index: Union[(int, Int)], value: T) -> None:
"\n Append __getitem__ expression.\n\n Parameters\n ----------\n index : int or Int\n Array's index to get value.\n value : *\n Specified index's value.\n "
import apysc as ap
with ap.DebugInfo(callable_=self._append_getitem_expression, locals_=locals(), module_name=__name__, class_=Array):
from apysc._type import value_util
value_: VariableNameInterface
if (not isinstance(value, VariableNameInterface)):
value_ = ap.AnyValue(None)
else:
value_ = value
index_str: str = value_util.get_value_str_for_expression(value=index)
expression: str = f'var {value_.variable_name} = {self.variable_name}[{index_str}];'
ap.append_js_expression(expression=expression)<|docstring|>Append __getitem__ expression.
Parameters
----------
index : int or Int
Array's index to get value.
value : *
Specified index's value.<|endoftext|> |
692fa3ff75d62cd645ee4cbd08246cde095e178b53f9a847cf2ac4fe777ea8d1 | def __setitem__(self, index: Union[(int, Int)], value: T) -> None:
"\n Set value to a specified index.\n\n Parameters\n ----------\n index : int or Int\n Array's index to set value. Currently not supported tuple\n value (e.g., slicing).\n value : *\n Any value to set.\n\n Raises\n ------\n ValueError\n If specified index type is not int and Int.\n "
import apysc as ap
with ap.DebugInfo(callable_='__setitem__', locals_=locals(), module_name=__name__, class_=Array):
self._validate_index_type_is_int(index=index)
index_: int = self._get_builtin_int_from_index(index=index)
self._value[index_] = value
self._append_setitem_expression(index=index, value=value) | Set value to a specified index.
Parameters
----------
index : int or Int
Array's index to set value. Currently not supported tuple
value (e.g., slicing).
value : *
Any value to set.
Raises
------
ValueError
If specified index type is not int and Int. | apysc/_type/array.py | __setitem__ | simon-ritchie/apysc | 16 | python | def __setitem__(self, index: Union[(int, Int)], value: T) -> None:
"\n Set value to a specified index.\n\n Parameters\n ----------\n index : int or Int\n Array's index to set value. Currently not supported tuple\n value (e.g., slicing).\n value : *\n Any value to set.\n\n Raises\n ------\n ValueError\n If specified index type is not int and Int.\n "
import apysc as ap
with ap.DebugInfo(callable_='__setitem__', locals_=locals(), module_name=__name__, class_=Array):
self._validate_index_type_is_int(index=index)
index_: int = self._get_builtin_int_from_index(index=index)
self._value[index_] = value
self._append_setitem_expression(index=index, value=value) | def __setitem__(self, index: Union[(int, Int)], value: T) -> None:
"\n Set value to a specified index.\n\n Parameters\n ----------\n index : int or Int\n Array's index to set value. Currently not supported tuple\n value (e.g., slicing).\n value : *\n Any value to set.\n\n Raises\n ------\n ValueError\n If specified index type is not int and Int.\n "
import apysc as ap
with ap.DebugInfo(callable_='__setitem__', locals_=locals(), module_name=__name__, class_=Array):
self._validate_index_type_is_int(index=index)
index_: int = self._get_builtin_int_from_index(index=index)
self._value[index_] = value
self._append_setitem_expression(index=index, value=value)<|docstring|>Set value to a specified index.
Parameters
----------
index : int or Int
Array's index to set value. Currently not supported tuple
value (e.g., slicing).
value : *
Any value to set.
Raises
------
ValueError
If specified index type is not int and Int.<|endoftext|> |
e3478eb441b4ead0cf6f7574cc499b8474e6baeb5a340432f2942553c47a45f5 | def _append_setitem_expression(self, *, index: Union[(int, Int)], value: T) -> None:
"\n Append __setitem__ method expression.\n\n Parameters\n ----------\n index : int or Int\n Array's index to set value. Currently not supported tuple\n value (e.g., slicing).\n value : *\n Any value to set.\n "
import apysc as ap
with ap.DebugInfo(callable_=self._append_setitem_expression, locals_=locals(), module_name=__name__, class_=Array):
from apysc._type import value_util
index_str: str = value_util.get_value_str_for_expression(value=index)
value_str: str = value_util.get_value_str_for_expression(value=value)
expression: str = f'{self.variable_name}[{index_str}] = {value_str};'
ap.append_js_expression(expression=expression) | Append __setitem__ method expression.
Parameters
----------
index : int or Int
Array's index to set value. Currently not supported tuple
value (e.g., slicing).
value : *
Any value to set. | apysc/_type/array.py | _append_setitem_expression | simon-ritchie/apysc | 16 | python | def _append_setitem_expression(self, *, index: Union[(int, Int)], value: T) -> None:
"\n Append __setitem__ method expression.\n\n Parameters\n ----------\n index : int or Int\n Array's index to set value. Currently not supported tuple\n value (e.g., slicing).\n value : *\n Any value to set.\n "
import apysc as ap
with ap.DebugInfo(callable_=self._append_setitem_expression, locals_=locals(), module_name=__name__, class_=Array):
from apysc._type import value_util
index_str: str = value_util.get_value_str_for_expression(value=index)
value_str: str = value_util.get_value_str_for_expression(value=value)
expression: str = f'{self.variable_name}[{index_str}] = {value_str};'
ap.append_js_expression(expression=expression) | def _append_setitem_expression(self, *, index: Union[(int, Int)], value: T) -> None:
"\n Append __setitem__ method expression.\n\n Parameters\n ----------\n index : int or Int\n Array's index to set value. Currently not supported tuple\n value (e.g., slicing).\n value : *\n Any value to set.\n "
import apysc as ap
with ap.DebugInfo(callable_=self._append_setitem_expression, locals_=locals(), module_name=__name__, class_=Array):
from apysc._type import value_util
index_str: str = value_util.get_value_str_for_expression(value=index)
value_str: str = value_util.get_value_str_for_expression(value=value)
expression: str = f'{self.variable_name}[{index_str}] = {value_str};'
ap.append_js_expression(expression=expression)<|docstring|>Append __setitem__ method expression.
Parameters
----------
index : int or Int
Array's index to set value. Currently not supported tuple
value (e.g., slicing).
value : *
Any value to set.<|endoftext|> |
95320aff7233a77f603cefe30fffc7831727921412de714d07e664aeb7f86bd7 | def __delitem__(self, index: Union[(int, Int)]) -> None:
"\n Delete specified index value from this array.\n\n Parameters\n ----------\n index : int or Int\n Array's index to delete. Currently not supported tuple\n value (e.g., slicing).\n\n Raises\n ------\n ValueError\n If specified index type is not int and Int.\n "
import apysc as ap
with ap.DebugInfo(callable_='__delitem__', locals_=locals(), module_name=__name__, class_=Array):
self.remove_at(index=index) | Delete specified index value from this array.
Parameters
----------
index : int or Int
Array's index to delete. Currently not supported tuple
value (e.g., slicing).
Raises
------
ValueError
If specified index type is not int and Int. | apysc/_type/array.py | __delitem__ | simon-ritchie/apysc | 16 | python | def __delitem__(self, index: Union[(int, Int)]) -> None:
"\n Delete specified index value from this array.\n\n Parameters\n ----------\n index : int or Int\n Array's index to delete. Currently not supported tuple\n value (e.g., slicing).\n\n Raises\n ------\n ValueError\n If specified index type is not int and Int.\n "
import apysc as ap
with ap.DebugInfo(callable_='__delitem__', locals_=locals(), module_name=__name__, class_=Array):
self.remove_at(index=index) | def __delitem__(self, index: Union[(int, Int)]) -> None:
"\n Delete specified index value from this array.\n\n Parameters\n ----------\n index : int or Int\n Array's index to delete. Currently not supported tuple\n value (e.g., slicing).\n\n Raises\n ------\n ValueError\n If specified index type is not int and Int.\n "
import apysc as ap
with ap.DebugInfo(callable_='__delitem__', locals_=locals(), module_name=__name__, class_=Array):
self.remove_at(index=index)<|docstring|>Delete specified index value from this array.
Parameters
----------
index : int or Int
Array's index to delete. Currently not supported tuple
value (e.g., slicing).
Raises
------
ValueError
If specified index type is not int and Int.<|endoftext|> |
6b1e45d3da1c229c9702cf24b075cf64591f8edc52d3b555f8899bad2390e048 | @property
def length(self) -> Int:
"\n Get length of this array.\n\n Returns\n -------\n length : Int\n This array's length.\n\n References\n ----------\n - Array class length interface document\n - https://simon-ritchie.github.io/apysc/array_length.html\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 2, 3])\n >>> arr.length\n Int(3)\n "
import apysc as ap
with ap.DebugInfo(callable_='length', locals_=locals(), module_name=__name__, class_=Array):
length: ap.Int = ap.Int(len(self._value))
self._append_length_expression(length=length)
return length | Get length of this array.
Returns
-------
length : Int
This array's length.
References
----------
- Array class length interface document
- https://simon-ritchie.github.io/apysc/array_length.html
Examples
--------
>>> import apysc as ap
>>> arr: ap.Array = ap.Array([1, 2, 3])
>>> arr.length
Int(3) | apysc/_type/array.py | length | simon-ritchie/apysc | 16 | python | @property
def length(self) -> Int:
"\n Get length of this array.\n\n Returns\n -------\n length : Int\n This array's length.\n\n References\n ----------\n - Array class length interface document\n - https://simon-ritchie.github.io/apysc/array_length.html\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 2, 3])\n >>> arr.length\n Int(3)\n "
import apysc as ap
with ap.DebugInfo(callable_='length', locals_=locals(), module_name=__name__, class_=Array):
length: ap.Int = ap.Int(len(self._value))
self._append_length_expression(length=length)
return length | @property
def length(self) -> Int:
"\n Get length of this array.\n\n Returns\n -------\n length : Int\n This array's length.\n\n References\n ----------\n - Array class length interface document\n - https://simon-ritchie.github.io/apysc/array_length.html\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 2, 3])\n >>> arr.length\n Int(3)\n "
import apysc as ap
with ap.DebugInfo(callable_='length', locals_=locals(), module_name=__name__, class_=Array):
length: ap.Int = ap.Int(len(self._value))
self._append_length_expression(length=length)
return length<|docstring|>Get length of this array.
Returns
-------
length : Int
This array's length.
References
----------
- Array class length interface document
- https://simon-ritchie.github.io/apysc/array_length.html
Examples
--------
>>> import apysc as ap
>>> arr: ap.Array = ap.Array([1, 2, 3])
>>> arr.length
Int(3)<|endoftext|> |
e854a428c8253c9338dc2f4db790dfd32af9767843299b8383c7e74ca4536c14 | def _append_length_expression(self, *, length: Int) -> None:
'\n Append length method expression.\n\n Parameters\n ----------\n length : Int\n Created length Int variable.\n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_length_expression, locals_=locals(), module_name=__name__, class_=Array):
expression: str = f'{length.variable_name} = {self.variable_name}.length;'
ap.append_js_expression(expression=expression) | Append length method expression.
Parameters
----------
length : Int
Created length Int variable. | apysc/_type/array.py | _append_length_expression | simon-ritchie/apysc | 16 | python | def _append_length_expression(self, *, length: Int) -> None:
'\n Append length method expression.\n\n Parameters\n ----------\n length : Int\n Created length Int variable.\n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_length_expression, locals_=locals(), module_name=__name__, class_=Array):
expression: str = f'{length.variable_name} = {self.variable_name}.length;'
ap.append_js_expression(expression=expression) | def _append_length_expression(self, *, length: Int) -> None:
'\n Append length method expression.\n\n Parameters\n ----------\n length : Int\n Created length Int variable.\n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_length_expression, locals_=locals(), module_name=__name__, class_=Array):
expression: str = f'{length.variable_name} = {self.variable_name}.length;'
ap.append_js_expression(expression=expression)<|docstring|>Append length method expression.
Parameters
----------
length : Int
Created length Int variable.<|endoftext|> |
fc3209e61f5768b3180f7fa211f601601f5f90e0c05bab6569e3c423da6f0c2f | def __len__(self) -> None:
"\n This method is disabled and can't use from Array instance.\n "
raise Exception("Array instance can't apply len function. Please use length property instead.") | This method is disabled and can't use from Array instance. | apysc/_type/array.py | __len__ | simon-ritchie/apysc | 16 | python | def __len__(self) -> None:
"\n \n "
raise Exception("Array instance can't apply len function. Please use length property instead.") | def __len__(self) -> None:
"\n \n "
raise Exception("Array instance can't apply len function. Please use length property instead.")<|docstring|>This method is disabled and can't use from Array instance.<|endoftext|> |
8bd38c404f933e74ce1d73654a8fedf39b92f4b7d627d784a0690d9e62d6f47b | def join(self, sep: Union[(str, String)]) -> String:
"\n Join this array values with specified separator string.\n\n Parameters\n ----------\n sep : str or String\n Separator string.\n\n Returns\n -------\n joined : String\n Joined string.\n\n References\n ----------\n - Array class join interface document\n - https://simon-ritchie.github.io/apysc/array_join.html\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 2, 3])\n >>> arr.join(sep=', ')\n String('1, 2, 3')\n "
import apysc as ap
with ap.DebugInfo(callable_=self.join, locals_=locals(), module_name=__name__, class_=Array):
if isinstance(sep, ap.String):
sep_: str = sep._value
else:
sep_ = sep
values_: List[Any] = [str(value) for value in self._value]
joined: ap.String = ap.String(sep_.join(values_))
self._append_join_expression(joined=joined, sep=sep)
return joined | Join this array values with specified separator string.
Parameters
----------
sep : str or String
Separator string.
Returns
-------
joined : String
Joined string.
References
----------
- Array class join interface document
- https://simon-ritchie.github.io/apysc/array_join.html
Examples
--------
>>> import apysc as ap
>>> arr: ap.Array = ap.Array([1, 2, 3])
>>> arr.join(sep=', ')
String('1, 2, 3') | apysc/_type/array.py | join | simon-ritchie/apysc | 16 | python | def join(self, sep: Union[(str, String)]) -> String:
"\n Join this array values with specified separator string.\n\n Parameters\n ----------\n sep : str or String\n Separator string.\n\n Returns\n -------\n joined : String\n Joined string.\n\n References\n ----------\n - Array class join interface document\n - https://simon-ritchie.github.io/apysc/array_join.html\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 2, 3])\n >>> arr.join(sep=', ')\n String('1, 2, 3')\n "
import apysc as ap
with ap.DebugInfo(callable_=self.join, locals_=locals(), module_name=__name__, class_=Array):
if isinstance(sep, ap.String):
sep_: str = sep._value
else:
sep_ = sep
values_: List[Any] = [str(value) for value in self._value]
joined: ap.String = ap.String(sep_.join(values_))
self._append_join_expression(joined=joined, sep=sep)
return joined | def join(self, sep: Union[(str, String)]) -> String:
"\n Join this array values with specified separator string.\n\n Parameters\n ----------\n sep : str or String\n Separator string.\n\n Returns\n -------\n joined : String\n Joined string.\n\n References\n ----------\n - Array class join interface document\n - https://simon-ritchie.github.io/apysc/array_join.html\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 2, 3])\n >>> arr.join(sep=', ')\n String('1, 2, 3')\n "
import apysc as ap
with ap.DebugInfo(callable_=self.join, locals_=locals(), module_name=__name__, class_=Array):
if isinstance(sep, ap.String):
sep_: str = sep._value
else:
sep_ = sep
values_: List[Any] = [str(value) for value in self._value]
joined: ap.String = ap.String(sep_.join(values_))
self._append_join_expression(joined=joined, sep=sep)
return joined<|docstring|>Join this array values with specified separator string.
Parameters
----------
sep : str or String
Separator string.
Returns
-------
joined : String
Joined string.
References
----------
- Array class join interface document
- https://simon-ritchie.github.io/apysc/array_join.html
Examples
--------
>>> import apysc as ap
>>> arr: ap.Array = ap.Array([1, 2, 3])
>>> arr.join(sep=', ')
String('1, 2, 3')<|endoftext|> |
2b2e1e013d8c73b08f2ca0d326661e7f72862b1c4d37798230fd12c411b08e5c | def _append_join_expression(self, *, joined: String, sep: Union[(str, String)]) -> None:
'\n Append join method expression.\n\n Parameters\n ----------\n joined : String\n Joined string.\n sep : str or String\n Separator string.\n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_join_expression, locals_=locals(), module_name=__name__, class_=Array):
from apysc._type import value_util
sep_str: str = value_util.get_value_str_for_expression(value=sep)
expression: str = f'{joined.variable_name} = {self.variable_name}.join({sep_str});'
ap.append_js_expression(expression=expression) | Append join method expression.
Parameters
----------
joined : String
Joined string.
sep : str or String
Separator string. | apysc/_type/array.py | _append_join_expression | simon-ritchie/apysc | 16 | python | def _append_join_expression(self, *, joined: String, sep: Union[(str, String)]) -> None:
'\n Append join method expression.\n\n Parameters\n ----------\n joined : String\n Joined string.\n sep : str or String\n Separator string.\n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_join_expression, locals_=locals(), module_name=__name__, class_=Array):
from apysc._type import value_util
sep_str: str = value_util.get_value_str_for_expression(value=sep)
expression: str = f'{joined.variable_name} = {self.variable_name}.join({sep_str});'
ap.append_js_expression(expression=expression) | def _append_join_expression(self, *, joined: String, sep: Union[(str, String)]) -> None:
'\n Append join method expression.\n\n Parameters\n ----------\n joined : String\n Joined string.\n sep : str or String\n Separator string.\n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_join_expression, locals_=locals(), module_name=__name__, class_=Array):
from apysc._type import value_util
sep_str: str = value_util.get_value_str_for_expression(value=sep)
expression: str = f'{joined.variable_name} = {self.variable_name}.join({sep_str});'
ap.append_js_expression(expression=expression)<|docstring|>Append join method expression.
Parameters
----------
joined : String
Joined string.
sep : str or String
Separator string.<|endoftext|> |
3dddd1f13c57c954db461dc43b932715cbfb996a7e024051b6966518ca383747 | def __str__(self) -> str:
'\n String conversion method.\n\n Returns\n -------\n string : str\n Converted value string.\n '
if (not hasattr(self, '_value')):
return '[]'
return str(self._value) | String conversion method.
Returns
-------
string : str
Converted value string. | apysc/_type/array.py | __str__ | simon-ritchie/apysc | 16 | python | def __str__(self) -> str:
'\n String conversion method.\n\n Returns\n -------\n string : str\n Converted value string.\n '
if (not hasattr(self, '_value')):
return '[]'
return str(self._value) | def __str__(self) -> str:
'\n String conversion method.\n\n Returns\n -------\n string : str\n Converted value string.\n '
if (not hasattr(self, '_value')):
return '[]'
return str(self._value)<|docstring|>String conversion method.
Returns
-------
string : str
Converted value string.<|endoftext|> |
e8ab82942ca89db0cbc773cc1463e073acb72d32c8261a2c0dc6af1aab031d7d | def __repr__(self) -> str:
'\n Get a representation string of this instance.\n\n Returns\n -------\n repr_str : str\n Representation string of this instance.\n '
if (not hasattr(self, '_value')):
repr_str: str = 'Array([])'
else:
repr_str = f'Array({repr(self._value)})'
return repr_str | Get a representation string of this instance.
Returns
-------
repr_str : str
Representation string of this instance. | apysc/_type/array.py | __repr__ | simon-ritchie/apysc | 16 | python | def __repr__(self) -> str:
'\n Get a representation string of this instance.\n\n Returns\n -------\n repr_str : str\n Representation string of this instance.\n '
if (not hasattr(self, '_value')):
repr_str: str = 'Array([])'
else:
repr_str = f'Array({repr(self._value)})'
return repr_str | def __repr__(self) -> str:
'\n Get a representation string of this instance.\n\n Returns\n -------\n repr_str : str\n Representation string of this instance.\n '
if (not hasattr(self, '_value')):
repr_str: str = 'Array([])'
else:
repr_str = f'Array({repr(self._value)})'
return repr_str<|docstring|>Get a representation string of this instance.
Returns
-------
repr_str : str
Representation string of this instance.<|endoftext|> |
aed6aa4fc410773833be4fc9ca6684173bbe0084127ce4176af42e3bb9a6b21e | def index_of(self, value: T) -> Int:
"\n Search specified value's index and return it.\n\n Parameters\n ----------\n value : *\n Any value to search.\n\n Returns\n -------\n index : Int\n Found position of index. If value is not contains,\n -1 will be returned.\n\n References\n ----------\n - Array class index_of interface document\n - https://simon-ritchie.github.io/apysc/array_index_of.html\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 3, 5])\n >>> arr.index_of(3)\n Int(1)\n "
import apysc as ap
with ap.DebugInfo(callable_=self.index_of, locals_=locals(), module_name=__name__, class_=Array):
index: ap.Int = ap.Int((- 1))
try:
index_: int = self._value.index(value)
except Exception:
index_ = (- 1)
index._value = index_
self._append_index_of_expression(index=index, value=value)
return index | Search specified value's index and return it.
Parameters
----------
value : *
Any value to search.
Returns
-------
index : Int
Found position of index. If value is not contains,
-1 will be returned.
References
----------
- Array class index_of interface document
- https://simon-ritchie.github.io/apysc/array_index_of.html
Examples
--------
>>> import apysc as ap
>>> arr: ap.Array = ap.Array([1, 3, 5])
>>> arr.index_of(3)
Int(1) | apysc/_type/array.py | index_of | simon-ritchie/apysc | 16 | python | def index_of(self, value: T) -> Int:
"\n Search specified value's index and return it.\n\n Parameters\n ----------\n value : *\n Any value to search.\n\n Returns\n -------\n index : Int\n Found position of index. If value is not contains,\n -1 will be returned.\n\n References\n ----------\n - Array class index_of interface document\n - https://simon-ritchie.github.io/apysc/array_index_of.html\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 3, 5])\n >>> arr.index_of(3)\n Int(1)\n "
import apysc as ap
with ap.DebugInfo(callable_=self.index_of, locals_=locals(), module_name=__name__, class_=Array):
index: ap.Int = ap.Int((- 1))
try:
index_: int = self._value.index(value)
except Exception:
index_ = (- 1)
index._value = index_
self._append_index_of_expression(index=index, value=value)
return index | def index_of(self, value: T) -> Int:
"\n Search specified value's index and return it.\n\n Parameters\n ----------\n value : *\n Any value to search.\n\n Returns\n -------\n index : Int\n Found position of index. If value is not contains,\n -1 will be returned.\n\n References\n ----------\n - Array class index_of interface document\n - https://simon-ritchie.github.io/apysc/array_index_of.html\n\n Examples\n --------\n >>> import apysc as ap\n >>> arr: ap.Array = ap.Array([1, 3, 5])\n >>> arr.index_of(3)\n Int(1)\n "
import apysc as ap
with ap.DebugInfo(callable_=self.index_of, locals_=locals(), module_name=__name__, class_=Array):
index: ap.Int = ap.Int((- 1))
try:
index_: int = self._value.index(value)
except Exception:
index_ = (- 1)
index._value = index_
self._append_index_of_expression(index=index, value=value)
return index<|docstring|>Search specified value's index and return it.
Parameters
----------
value : *
Any value to search.
Returns
-------
index : Int
Found position of index. If value is not contains,
-1 will be returned.
References
----------
- Array class index_of interface document
- https://simon-ritchie.github.io/apysc/array_index_of.html
Examples
--------
>>> import apysc as ap
>>> arr: ap.Array = ap.Array([1, 3, 5])
>>> arr.index_of(3)
Int(1)<|endoftext|> |
857b1bb9ed8c7297c6eefd578717b0219b8b2c79db7b1248dd8f06865c4b8cdc | def _append_index_of_expression(self, *, index: Int, value: T) -> None:
'\n Append index_of method expression.\n\n Parameters\n ----------\n index : Int\n Found position of index. If value is not contains,\n -1 will be set.\n value : *\n Any value to search.\n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_index_of_expression, locals_=locals(), module_name=__name__, class_=Array):
from apysc._type import value_util
value_str: str = value_util.get_value_str_for_expression(value=value)
expression: str = f'{index.variable_name} = {self.variable_name}.indexOf({value_str});'
ap.append_js_expression(expression=expression) | Append index_of method expression.
Parameters
----------
index : Int
Found position of index. If value is not contains,
-1 will be set.
value : *
Any value to search. | apysc/_type/array.py | _append_index_of_expression | simon-ritchie/apysc | 16 | python | def _append_index_of_expression(self, *, index: Int, value: T) -> None:
'\n Append index_of method expression.\n\n Parameters\n ----------\n index : Int\n Found position of index. If value is not contains,\n -1 will be set.\n value : *\n Any value to search.\n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_index_of_expression, locals_=locals(), module_name=__name__, class_=Array):
from apysc._type import value_util
value_str: str = value_util.get_value_str_for_expression(value=value)
expression: str = f'{index.variable_name} = {self.variable_name}.indexOf({value_str});'
ap.append_js_expression(expression=expression) | def _append_index_of_expression(self, *, index: Int, value: T) -> None:
'\n Append index_of method expression.\n\n Parameters\n ----------\n index : Int\n Found position of index. If value is not contains,\n -1 will be set.\n value : *\n Any value to search.\n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_index_of_expression, locals_=locals(), module_name=__name__, class_=Array):
from apysc._type import value_util
value_str: str = value_util.get_value_str_for_expression(value=value)
expression: str = f'{index.variable_name} = {self.variable_name}.indexOf({value_str});'
ap.append_js_expression(expression=expression)<|docstring|>Append index_of method expression.
Parameters
----------
index : Int
Found position of index. If value is not contains,
-1 will be set.
value : *
Any value to search.<|endoftext|> |
7ea36e656157dbf97925317e0157af529d09cce6a4270b02ad396b0ab4a0a5c7 | def __eq__(self, other: Any) -> Any:
'\n Equal comparison method.\n\n Parameters\n ----------\n other : *\n Other value to compare. list or Array types are acceptable.\n\n Returns\n -------\n result : Boolean\n Comparison result.\n '
import apysc as ap
with ap.DebugInfo(callable_='__eq__', locals_=locals(), module_name=__name__, class_=Array):
result: ap.Boolean
if isinstance(other, Array):
result = ap.Boolean((self._value == other._value))
else:
result = ap.Boolean((self._value == other))
other = self._convert_other_val_to_array(other=other)
if isinstance(other, VariableNameInterface):
self._append_eq_expression(result=result, other=other)
return result | Equal comparison method.
Parameters
----------
other : *
Other value to compare. list or Array types are acceptable.
Returns
-------
result : Boolean
Comparison result. | apysc/_type/array.py | __eq__ | simon-ritchie/apysc | 16 | python | def __eq__(self, other: Any) -> Any:
'\n Equal comparison method.\n\n Parameters\n ----------\n other : *\n Other value to compare. list or Array types are acceptable.\n\n Returns\n -------\n result : Boolean\n Comparison result.\n '
import apysc as ap
with ap.DebugInfo(callable_='__eq__', locals_=locals(), module_name=__name__, class_=Array):
result: ap.Boolean
if isinstance(other, Array):
result = ap.Boolean((self._value == other._value))
else:
result = ap.Boolean((self._value == other))
other = self._convert_other_val_to_array(other=other)
if isinstance(other, VariableNameInterface):
self._append_eq_expression(result=result, other=other)
return result | def __eq__(self, other: Any) -> Any:
'\n Equal comparison method.\n\n Parameters\n ----------\n other : *\n Other value to compare. list or Array types are acceptable.\n\n Returns\n -------\n result : Boolean\n Comparison result.\n '
import apysc as ap
with ap.DebugInfo(callable_='__eq__', locals_=locals(), module_name=__name__, class_=Array):
result: ap.Boolean
if isinstance(other, Array):
result = ap.Boolean((self._value == other._value))
else:
result = ap.Boolean((self._value == other))
other = self._convert_other_val_to_array(other=other)
if isinstance(other, VariableNameInterface):
self._append_eq_expression(result=result, other=other)
return result<|docstring|>Equal comparison method.
Parameters
----------
other : *
Other value to compare. list or Array types are acceptable.
Returns
-------
result : Boolean
Comparison result.<|endoftext|> |
9dad4f485d2e78e673f81c64288684560dc08ee94e97972f70a1405df2e18097 | def _convert_other_val_to_array(self, *, other: Any) -> Any:
"\n If comparison's other value is list value, then convert it to\n Array instance.\n\n Parameters\n ----------\n other : *\n Other value to compare.\n\n Returns\n -------\n converted_val : *\n Converted value. If other value is list, then this will\n be Array type. Otherwise this will be returned directly\n (not to be converted).\n "
import apysc as ap
with ap.DebugInfo(callable_=self._convert_other_val_to_array, locals_=locals(), module_name=__name__, class_=Array):
if isinstance(other, list):
return Array(other)
return other | If comparison's other value is list value, then convert it to
Array instance.
Parameters
----------
other : *
Other value to compare.
Returns
-------
converted_val : *
Converted value. If other value is list, then this will
be Array type. Otherwise this will be returned directly
(not to be converted). | apysc/_type/array.py | _convert_other_val_to_array | simon-ritchie/apysc | 16 | python | def _convert_other_val_to_array(self, *, other: Any) -> Any:
"\n If comparison's other value is list value, then convert it to\n Array instance.\n\n Parameters\n ----------\n other : *\n Other value to compare.\n\n Returns\n -------\n converted_val : *\n Converted value. If other value is list, then this will\n be Array type. Otherwise this will be returned directly\n (not to be converted).\n "
import apysc as ap
with ap.DebugInfo(callable_=self._convert_other_val_to_array, locals_=locals(), module_name=__name__, class_=Array):
if isinstance(other, list):
return Array(other)
return other | def _convert_other_val_to_array(self, *, other: Any) -> Any:
"\n If comparison's other value is list value, then convert it to\n Array instance.\n\n Parameters\n ----------\n other : *\n Other value to compare.\n\n Returns\n -------\n converted_val : *\n Converted value. If other value is list, then this will\n be Array type. Otherwise this will be returned directly\n (not to be converted).\n "
import apysc as ap
with ap.DebugInfo(callable_=self._convert_other_val_to_array, locals_=locals(), module_name=__name__, class_=Array):
if isinstance(other, list):
return Array(other)
return other<|docstring|>If comparison's other value is list value, then convert it to
Array instance.
Parameters
----------
other : *
Other value to compare.
Returns
-------
converted_val : *
Converted value. If other value is list, then this will
be Array type. Otherwise this will be returned directly
(not to be converted).<|endoftext|> |
fa08a277914900c39b07f04c096fba6901a49f3f21bc6cbbdf304dc7b73816ad | def _append_eq_expression(self, *, result: Boolean, other: VariableNameInterface) -> None:
'\n Append an __eq__ expression.\n\n Parameters\n ----------\n result : Boolean\n Result boolean value.\n other : Array\n Array other value to compare.\n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_eq_expression, locals_=locals(), module_name=__name__, class_=Array):
expression: str = f'{result.variable_name} = _.isEqual({self.variable_name}, {other.variable_name});'
ap.append_js_expression(expression=expression) | Append an __eq__ expression.
Parameters
----------
result : Boolean
Result boolean value.
other : Array
Array other value to compare. | apysc/_type/array.py | _append_eq_expression | simon-ritchie/apysc | 16 | python | def _append_eq_expression(self, *, result: Boolean, other: VariableNameInterface) -> None:
'\n Append an __eq__ expression.\n\n Parameters\n ----------\n result : Boolean\n Result boolean value.\n other : Array\n Array other value to compare.\n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_eq_expression, locals_=locals(), module_name=__name__, class_=Array):
expression: str = f'{result.variable_name} = _.isEqual({self.variable_name}, {other.variable_name});'
ap.append_js_expression(expression=expression) | def _append_eq_expression(self, *, result: Boolean, other: VariableNameInterface) -> None:
'\n Append an __eq__ expression.\n\n Parameters\n ----------\n result : Boolean\n Result boolean value.\n other : Array\n Array other value to compare.\n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_eq_expression, locals_=locals(), module_name=__name__, class_=Array):
expression: str = f'{result.variable_name} = _.isEqual({self.variable_name}, {other.variable_name});'
ap.append_js_expression(expression=expression)<|docstring|>Append an __eq__ expression.
Parameters
----------
result : Boolean
Result boolean value.
other : Array
Array other value to compare.<|endoftext|> |
94ec59720e6a186d6dfaba290db4829d36699cb35b7bcbaacbc510f7810a6c96 | def __ne__(self, other: Any) -> Any:
'\n Not equal comparison method.\n\n Parameters\n ----------\n other : *\n Other value to compare. list or Array types are acceptable.\n\n Returns\n -------\n result : Boolean\n Comparison result.\n '
import apysc as ap
with ap.DebugInfo(callable_='__ne__', locals_=locals(), module_name=__name__, class_=Array):
other = self._convert_other_val_to_array(other=other)
result: ap.Boolean = (self == other)
result = result.not_
if isinstance(other, VariableNameInterface):
self._append_ne_expression(result=result, other=other)
return result | Not equal comparison method.
Parameters
----------
other : *
Other value to compare. list or Array types are acceptable.
Returns
-------
result : Boolean
Comparison result. | apysc/_type/array.py | __ne__ | simon-ritchie/apysc | 16 | python | def __ne__(self, other: Any) -> Any:
'\n Not equal comparison method.\n\n Parameters\n ----------\n other : *\n Other value to compare. list or Array types are acceptable.\n\n Returns\n -------\n result : Boolean\n Comparison result.\n '
import apysc as ap
with ap.DebugInfo(callable_='__ne__', locals_=locals(), module_name=__name__, class_=Array):
other = self._convert_other_val_to_array(other=other)
result: ap.Boolean = (self == other)
result = result.not_
if isinstance(other, VariableNameInterface):
self._append_ne_expression(result=result, other=other)
return result | def __ne__(self, other: Any) -> Any:
'\n Not equal comparison method.\n\n Parameters\n ----------\n other : *\n Other value to compare. list or Array types are acceptable.\n\n Returns\n -------\n result : Boolean\n Comparison result.\n '
import apysc as ap
with ap.DebugInfo(callable_='__ne__', locals_=locals(), module_name=__name__, class_=Array):
other = self._convert_other_val_to_array(other=other)
result: ap.Boolean = (self == other)
result = result.not_
if isinstance(other, VariableNameInterface):
self._append_ne_expression(result=result, other=other)
return result<|docstring|>Not equal comparison method.
Parameters
----------
other : *
Other value to compare. list or Array types are acceptable.
Returns
-------
result : Boolean
Comparison result.<|endoftext|> |
8d0e0dbab63ee1de3b5fcb2cec805cc89d282d2c3749aec6d37912c54cec68df | def _append_ne_expression(self, *, result: Boolean, other: VariableNameInterface) -> None:
'\n Append a __ne__ expression.\n\n Parameters\n ----------\n result : Boolean\n Result boolean value.\n other : Array\n Array other value to compare.\n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_ne_expression, locals_=locals(), module_name=__name__, class_=Array):
expression: str = f'{result.variable_name} = !_.isEqual({self.variable_name}, {other.variable_name});'
ap.append_js_expression(expression=expression) | Append a __ne__ expression.
Parameters
----------
result : Boolean
Result boolean value.
other : Array
Array other value to compare. | apysc/_type/array.py | _append_ne_expression | simon-ritchie/apysc | 16 | python | def _append_ne_expression(self, *, result: Boolean, other: VariableNameInterface) -> None:
'\n Append a __ne__ expression.\n\n Parameters\n ----------\n result : Boolean\n Result boolean value.\n other : Array\n Array other value to compare.\n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_ne_expression, locals_=locals(), module_name=__name__, class_=Array):
expression: str = f'{result.variable_name} = !_.isEqual({self.variable_name}, {other.variable_name});'
ap.append_js_expression(expression=expression) | def _append_ne_expression(self, *, result: Boolean, other: VariableNameInterface) -> None:
'\n Append a __ne__ expression.\n\n Parameters\n ----------\n result : Boolean\n Result boolean value.\n other : Array\n Array other value to compare.\n '
import apysc as ap
with ap.DebugInfo(callable_=self._append_ne_expression, locals_=locals(), module_name=__name__, class_=Array):
expression: str = f'{result.variable_name} = !_.isEqual({self.variable_name}, {other.variable_name});'
ap.append_js_expression(expression=expression)<|docstring|>Append a __ne__ expression.
Parameters
----------
result : Boolean
Result boolean value.
other : Array
Array other value to compare.<|endoftext|> |
e1ec15f8895cf77f0c63e859f9618841d12f7a1d352bc75c4116c2c1955044d8 | def __bool__(self) -> bool:
'\n Get a boolean value whether this array is empty or not.\n\n Returns\n -------\n result : bool\n If this array is empty, True will be returned.\n '
return bool(self._value) | Get a boolean value whether this array is empty or not.
Returns
-------
result : bool
If this array is empty, True will be returned. | apysc/_type/array.py | __bool__ | simon-ritchie/apysc | 16 | python | def __bool__(self) -> bool:
'\n Get a boolean value whether this array is empty or not.\n\n Returns\n -------\n result : bool\n If this array is empty, True will be returned.\n '
return bool(self._value) | def __bool__(self) -> bool:
'\n Get a boolean value whether this array is empty or not.\n\n Returns\n -------\n result : bool\n If this array is empty, True will be returned.\n '
return bool(self._value)<|docstring|>Get a boolean value whether this array is empty or not.
Returns
-------
result : bool
If this array is empty, True will be returned.<|endoftext|> |
d949d07c59392d7d1d8bf4dc1d0beddb39518ad3c08b7a2be9e8aecea37a98eb | def _make_snapshot(self, *, snapshot_name: str) -> None:
"\n Make values' snapshot.\n\n Parameters\n ----------\n snapshot_name : str\n Target snapshot name.\n "
self._set_single_snapshot_val_to_dict(dict_name='_value_snapshots', value=[*self._value], snapshot_name=snapshot_name) | Make values' snapshot.
Parameters
----------
snapshot_name : str
Target snapshot name. | apysc/_type/array.py | _make_snapshot | simon-ritchie/apysc | 16 | python | def _make_snapshot(self, *, snapshot_name: str) -> None:
"\n Make values' snapshot.\n\n Parameters\n ----------\n snapshot_name : str\n Target snapshot name.\n "
self._set_single_snapshot_val_to_dict(dict_name='_value_snapshots', value=[*self._value], snapshot_name=snapshot_name) | def _make_snapshot(self, *, snapshot_name: str) -> None:
"\n Make values' snapshot.\n\n Parameters\n ----------\n snapshot_name : str\n Target snapshot name.\n "
self._set_single_snapshot_val_to_dict(dict_name='_value_snapshots', value=[*self._value], snapshot_name=snapshot_name)<|docstring|>Make values' snapshot.
Parameters
----------
snapshot_name : str
Target snapshot name.<|endoftext|> |
044a3b3c2d9e7042cb03f83391420f5f5741fe2e8e614ea1397fa964fdcc6253 | def _revert(self, *, snapshot_name: str) -> None:
'\n Revert values if snapshot exists.\n\n Parameters\n ----------\n snapshot_name : str\n Target snapshot name.\n '
if (not self._snapshot_exists(snapshot_name=snapshot_name)):
return
self._value = self._value_snapshots[snapshot_name] | Revert values if snapshot exists.
Parameters
----------
snapshot_name : str
Target snapshot name. | apysc/_type/array.py | _revert | simon-ritchie/apysc | 16 | python | def _revert(self, *, snapshot_name: str) -> None:
'\n Revert values if snapshot exists.\n\n Parameters\n ----------\n snapshot_name : str\n Target snapshot name.\n '
if (not self._snapshot_exists(snapshot_name=snapshot_name)):
return
self._value = self._value_snapshots[snapshot_name] | def _revert(self, *, snapshot_name: str) -> None:
'\n Revert values if snapshot exists.\n\n Parameters\n ----------\n snapshot_name : str\n Target snapshot name.\n '
if (not self._snapshot_exists(snapshot_name=snapshot_name)):
return
self._value = self._value_snapshots[snapshot_name]<|docstring|>Revert values if snapshot exists.
Parameters
----------
snapshot_name : str
Target snapshot name.<|endoftext|> |
7d440573dbebfac3b861a12d6b54227b81a0548931fe2c57a16830878c7decfb | def test_process_match(self):
'\n Tests the process method for a matching email.\n '
mock_doc_id = 1
email = {'Message-ID': 'abc', 'Subject': 'This is a Critical Alert'}
doc_obj = DocumentObj(data=email)
mailchute = MailChute.objects.get(pk=1)
mailchute.munger.process = Mock(return_value=mock_doc_id)
doc_id = mailchute.process(doc_obj)
mailchute.munger.process.assert_called_once_with(doc_obj)
(self.assertEqual(doc_id, mock_doc_id), None) | Tests the process method for a matching email. | Incident-Response/Tools/cyphon/cyphon/sifter/mailsifter/mailchutes/tests/test_models.py | test_process_match | sn0b4ll/Incident-Playbook | 1 | python | def test_process_match(self):
'\n \n '
mock_doc_id = 1
email = {'Message-ID': 'abc', 'Subject': 'This is a Critical Alert'}
doc_obj = DocumentObj(data=email)
mailchute = MailChute.objects.get(pk=1)
mailchute.munger.process = Mock(return_value=mock_doc_id)
doc_id = mailchute.process(doc_obj)
mailchute.munger.process.assert_called_once_with(doc_obj)
(self.assertEqual(doc_id, mock_doc_id), None) | def test_process_match(self):
'\n \n '
mock_doc_id = 1
email = {'Message-ID': 'abc', 'Subject': 'This is a Critical Alert'}
doc_obj = DocumentObj(data=email)
mailchute = MailChute.objects.get(pk=1)
mailchute.munger.process = Mock(return_value=mock_doc_id)
doc_id = mailchute.process(doc_obj)
mailchute.munger.process.assert_called_once_with(doc_obj)
(self.assertEqual(doc_id, mock_doc_id), None)<|docstring|>Tests the process method for a matching email.<|endoftext|> |
35402a7bacc5f3660bc7abdb4fd4dd5806cdb995a675d099929bc0013048a5e4 | def test_process_nonmatch(self):
'\n Tests the process method for a nonmatching email.\n '
email = {'Message-ID': 'abc', 'Subject': 'This is an Urgent Alert'}
doc_obj = DocumentObj(data=email)
mailchute = MailChute.objects.get(pk=1)
mailchute.munger.process = Mock(return_value=None)
doc_id = mailchute.process(doc_obj)
self.assertEqual(doc_id, None) | Tests the process method for a nonmatching email. | Incident-Response/Tools/cyphon/cyphon/sifter/mailsifter/mailchutes/tests/test_models.py | test_process_nonmatch | sn0b4ll/Incident-Playbook | 1 | python | def test_process_nonmatch(self):
'\n \n '
email = {'Message-ID': 'abc', 'Subject': 'This is an Urgent Alert'}
doc_obj = DocumentObj(data=email)
mailchute = MailChute.objects.get(pk=1)
mailchute.munger.process = Mock(return_value=None)
doc_id = mailchute.process(doc_obj)
self.assertEqual(doc_id, None) | def test_process_nonmatch(self):
'\n \n '
email = {'Message-ID': 'abc', 'Subject': 'This is an Urgent Alert'}
doc_obj = DocumentObj(data=email)
mailchute = MailChute.objects.get(pk=1)
mailchute.munger.process = Mock(return_value=None)
doc_id = mailchute.process(doc_obj)
self.assertEqual(doc_id, None)<|docstring|>Tests the process method for a nonmatching email.<|endoftext|> |
be30c1ff09303df1ae2671ceee9db01af73a6aacf9b96fdf604d3f370fdf8b43 | def test_process_no_sieve(self):
'\n Tests the process method for a chute with no sieve.\n '
mock_doc_id = 1
email = {'Message-ID': 'abc', 'Subject': 'This is an Urgent Alert'}
doc_obj = DocumentObj(data=email)
mailchute = MailChute.objects.get(pk=3)
mailchute.enabled = True
mailchute.munger.process = Mock(return_value=mock_doc_id)
doc_id = mailchute.process(doc_obj)
mailchute.munger.process.assert_called_once_with(doc_obj)
self.assertEqual(doc_id, mock_doc_id) | Tests the process method for a chute with no sieve. | Incident-Response/Tools/cyphon/cyphon/sifter/mailsifter/mailchutes/tests/test_models.py | test_process_no_sieve | sn0b4ll/Incident-Playbook | 1 | python | def test_process_no_sieve(self):
'\n \n '
mock_doc_id = 1
email = {'Message-ID': 'abc', 'Subject': 'This is an Urgent Alert'}
doc_obj = DocumentObj(data=email)
mailchute = MailChute.objects.get(pk=3)
mailchute.enabled = True
mailchute.munger.process = Mock(return_value=mock_doc_id)
doc_id = mailchute.process(doc_obj)
mailchute.munger.process.assert_called_once_with(doc_obj)
self.assertEqual(doc_id, mock_doc_id) | def test_process_no_sieve(self):
'\n \n '
mock_doc_id = 1
email = {'Message-ID': 'abc', 'Subject': 'This is an Urgent Alert'}
doc_obj = DocumentObj(data=email)
mailchute = MailChute.objects.get(pk=3)
mailchute.enabled = True
mailchute.munger.process = Mock(return_value=mock_doc_id)
doc_id = mailchute.process(doc_obj)
mailchute.munger.process.assert_called_once_with(doc_obj)
self.assertEqual(doc_id, mock_doc_id)<|docstring|>Tests the process method for a chute with no sieve.<|endoftext|> |
e20ff89af2648436bc7e697eebe914b4c62c3c80486bd5ce861adf785e6b73bc | def test_match_with_default(self):
'\n Tests the process_email receiver for an email that matches an\n existing MailChute.\n '
doc_obj = self.doc_obj
doc_obj.data['Subject'] = 'critical alert'
mock_config = {'DEFAULT_MUNGER': 'default_mail', 'DEFAULT_MUNGER_ENABLED': True}
with patch('distilleries.models.Distillery.save_data', return_value='id_123') as mock_save:
with patch.dict('sifter.mailsifter.mailchutes.models.conf.MAILSIFTER', mock_config):
with patch('sifter.mailsifter.mailchutes.models.MailChuteManager._process_with_default') as mock_catch_email:
MailChute.objects.process(doc_obj)
self.assertIs(mock_save.called, True)
self.assertIs(mock_catch_email.called, False) | Tests the process_email receiver for an email that matches an
existing MailChute. | Incident-Response/Tools/cyphon/cyphon/sifter/mailsifter/mailchutes/tests/test_models.py | test_match_with_default | sn0b4ll/Incident-Playbook | 1 | python | def test_match_with_default(self):
'\n Tests the process_email receiver for an email that matches an\n existing MailChute.\n '
doc_obj = self.doc_obj
doc_obj.data['Subject'] = 'critical alert'
mock_config = {'DEFAULT_MUNGER': 'default_mail', 'DEFAULT_MUNGER_ENABLED': True}
with patch('distilleries.models.Distillery.save_data', return_value='id_123') as mock_save:
with patch.dict('sifter.mailsifter.mailchutes.models.conf.MAILSIFTER', mock_config):
with patch('sifter.mailsifter.mailchutes.models.MailChuteManager._process_with_default') as mock_catch_email:
MailChute.objects.process(doc_obj)
self.assertIs(mock_save.called, True)
self.assertIs(mock_catch_email.called, False) | def test_match_with_default(self):
'\n Tests the process_email receiver for an email that matches an\n existing MailChute.\n '
doc_obj = self.doc_obj
doc_obj.data['Subject'] = 'critical alert'
mock_config = {'DEFAULT_MUNGER': 'default_mail', 'DEFAULT_MUNGER_ENABLED': True}
with patch('distilleries.models.Distillery.save_data', return_value='id_123') as mock_save:
with patch.dict('sifter.mailsifter.mailchutes.models.conf.MAILSIFTER', mock_config):
with patch('sifter.mailsifter.mailchutes.models.MailChuteManager._process_with_default') as mock_catch_email:
MailChute.objects.process(doc_obj)
self.assertIs(mock_save.called, True)
self.assertIs(mock_catch_email.called, False)<|docstring|>Tests the process_email receiver for an email that matches an
existing MailChute.<|endoftext|> |
9fc5b534919a26c12bd7c442e19cfdb7c998f0f9bb1b8f146ba7672c127e57b0 | def test_no_match_without_default(self):
"\n Tests the process_email receiver for an email that doesn't match\n an existing MailChute when a default MailMunger is not enabled.\n "
doc_obj = self.doc_obj
doc_obj.data['Subject'] = 'nothing to see here'
mock_config = {'DEFAULT_MUNGER': 'default_mail', 'DEFAULT_MUNGER_ENABLED': False}
with patch('distilleries.models.Distillery.save_data') as mock_save:
with patch.dict('sifter.mailsifter.mailchutes.models.conf.MAILSIFTER', mock_config):
with patch('sifter.mailsifter.mailchutes.models.MailChuteManager._process_with_default') as mock_catch_email:
MailChute.objects.process(doc_obj)
self.assertIs(mock_save.called, False)
self.assertIs(mock_catch_email.called, False) | Tests the process_email receiver for an email that doesn't match
an existing MailChute when a default MailMunger is not enabled. | Incident-Response/Tools/cyphon/cyphon/sifter/mailsifter/mailchutes/tests/test_models.py | test_no_match_without_default | sn0b4ll/Incident-Playbook | 1 | python | def test_no_match_without_default(self):
"\n Tests the process_email receiver for an email that doesn't match\n an existing MailChute when a default MailMunger is not enabled.\n "
doc_obj = self.doc_obj
doc_obj.data['Subject'] = 'nothing to see here'
mock_config = {'DEFAULT_MUNGER': 'default_mail', 'DEFAULT_MUNGER_ENABLED': False}
with patch('distilleries.models.Distillery.save_data') as mock_save:
with patch.dict('sifter.mailsifter.mailchutes.models.conf.MAILSIFTER', mock_config):
with patch('sifter.mailsifter.mailchutes.models.MailChuteManager._process_with_default') as mock_catch_email:
MailChute.objects.process(doc_obj)
self.assertIs(mock_save.called, False)
self.assertIs(mock_catch_email.called, False) | def test_no_match_without_default(self):
"\n Tests the process_email receiver for an email that doesn't match\n an existing MailChute when a default MailMunger is not enabled.\n "
doc_obj = self.doc_obj
doc_obj.data['Subject'] = 'nothing to see here'
mock_config = {'DEFAULT_MUNGER': 'default_mail', 'DEFAULT_MUNGER_ENABLED': False}
with patch('distilleries.models.Distillery.save_data') as mock_save:
with patch.dict('sifter.mailsifter.mailchutes.models.conf.MAILSIFTER', mock_config):
with patch('sifter.mailsifter.mailchutes.models.MailChuteManager._process_with_default') as mock_catch_email:
MailChute.objects.process(doc_obj)
self.assertIs(mock_save.called, False)
self.assertIs(mock_catch_email.called, False)<|docstring|>Tests the process_email receiver for an email that doesn't match
an existing MailChute when a default MailMunger is not enabled.<|endoftext|> |
628ecafe090a1cb6b08fa6e7f898de8b2800dcaab05633c32e42846af7e99bde | def test_no_match_with_default(self):
"\n Tests the process_email receiver for an email that doesn't match\n an existing MailChute when a default MailMunger is enabled.\n "
doc_obj = self.doc_obj
doc_obj.data['Subject'] = 'nothing to see here'
mock_config = {'DEFAULT_MUNGER': 'default_mail', 'DEFAULT_MUNGER_ENABLED': True}
with patch.dict('sifter.mailsifter.mailchutes.models.conf.MAILSIFTER', mock_config):
with patch('sifter.mailsifter.mailchutes.models.MailChuteManager._process_with_default') as mock_default_process:
MailChute.objects.process(doc_obj)
mock_default_process.assert_called_once_with(doc_obj) | Tests the process_email receiver for an email that doesn't match
an existing MailChute when a default MailMunger is enabled. | Incident-Response/Tools/cyphon/cyphon/sifter/mailsifter/mailchutes/tests/test_models.py | test_no_match_with_default | sn0b4ll/Incident-Playbook | 1 | python | def test_no_match_with_default(self):
"\n Tests the process_email receiver for an email that doesn't match\n an existing MailChute when a default MailMunger is enabled.\n "
doc_obj = self.doc_obj
doc_obj.data['Subject'] = 'nothing to see here'
mock_config = {'DEFAULT_MUNGER': 'default_mail', 'DEFAULT_MUNGER_ENABLED': True}
with patch.dict('sifter.mailsifter.mailchutes.models.conf.MAILSIFTER', mock_config):
with patch('sifter.mailsifter.mailchutes.models.MailChuteManager._process_with_default') as mock_default_process:
MailChute.objects.process(doc_obj)
mock_default_process.assert_called_once_with(doc_obj) | def test_no_match_with_default(self):
"\n Tests the process_email receiver for an email that doesn't match\n an existing MailChute when a default MailMunger is enabled.\n "
doc_obj = self.doc_obj
doc_obj.data['Subject'] = 'nothing to see here'
mock_config = {'DEFAULT_MUNGER': 'default_mail', 'DEFAULT_MUNGER_ENABLED': True}
with patch.dict('sifter.mailsifter.mailchutes.models.conf.MAILSIFTER', mock_config):
with patch('sifter.mailsifter.mailchutes.models.MailChuteManager._process_with_default') as mock_default_process:
MailChute.objects.process(doc_obj)
mock_default_process.assert_called_once_with(doc_obj)<|docstring|>Tests the process_email receiver for an email that doesn't match
an existing MailChute when a default MailMunger is enabled.<|endoftext|> |
1b200908ca17697afccd2bd9c5e914cf08fbdf6a779ac4246bb2b7bbb7576e00 | def test_no_match_missing_munger(self):
"\n Tests the process_email receiver for an email that doesn't match\n an existing MailChute when a default MailChute is enabled but\n the defaul MailMunger can't be found.\n "
doc_obj = self.doc_obj
doc_obj.data['Subject'] = 'nothing to see here'
mock_config = {'DEFAULT_MUNGER': 'missing_munger', 'DEFAULT_MUNGER_ENABLED': True}
with patch.dict('sifter.mailsifter.mailchutes.models.conf.MAILSIFTER', mock_config):
with LogCapture() as log_capture:
msg = 'Default MailMunger "missing_munger" is not configured.'
MailChute.objects.process(doc_obj)
log_capture.check(('sifter.chutes.models', 'ERROR', msg)) | Tests the process_email receiver for an email that doesn't match
an existing MailChute when a default MailChute is enabled but
the defaul MailMunger can't be found. | Incident-Response/Tools/cyphon/cyphon/sifter/mailsifter/mailchutes/tests/test_models.py | test_no_match_missing_munger | sn0b4ll/Incident-Playbook | 1 | python | def test_no_match_missing_munger(self):
"\n Tests the process_email receiver for an email that doesn't match\n an existing MailChute when a default MailChute is enabled but\n the defaul MailMunger can't be found.\n "
doc_obj = self.doc_obj
doc_obj.data['Subject'] = 'nothing to see here'
mock_config = {'DEFAULT_MUNGER': 'missing_munger', 'DEFAULT_MUNGER_ENABLED': True}
with patch.dict('sifter.mailsifter.mailchutes.models.conf.MAILSIFTER', mock_config):
with LogCapture() as log_capture:
msg = 'Default MailMunger "missing_munger" is not configured.'
MailChute.objects.process(doc_obj)
log_capture.check(('sifter.chutes.models', 'ERROR', msg)) | def test_no_match_missing_munger(self):
"\n Tests the process_email receiver for an email that doesn't match\n an existing MailChute when a default MailChute is enabled but\n the defaul MailMunger can't be found.\n "
doc_obj = self.doc_obj
doc_obj.data['Subject'] = 'nothing to see here'
mock_config = {'DEFAULT_MUNGER': 'missing_munger', 'DEFAULT_MUNGER_ENABLED': True}
with patch.dict('sifter.mailsifter.mailchutes.models.conf.MAILSIFTER', mock_config):
with LogCapture() as log_capture:
msg = 'Default MailMunger "missing_munger" is not configured.'
MailChute.objects.process(doc_obj)
log_capture.check(('sifter.chutes.models', 'ERROR', msg))<|docstring|>Tests the process_email receiver for an email that doesn't match
an existing MailChute when a default MailChute is enabled but
the defaul MailMunger can't be found.<|endoftext|> |
658bf221afadb81ef0ac14116cb0069922985d1af190ee4c7d91e18bd79dbb21 | def parse_arguments(parser: Any=None, ci_values: List[str]=None) -> Any:
"\n Standard argparse wrapper for interpreting command line arguments.\n\n Args:\n parser: if there's an existing parser, provide it, else, this will\n create a new one.\n ci_values: use for testing purposes only.\n "
if (not parser):
parser = argparse.ArgumentParser()
parser.add_argument('--config', help='location of the config file', required=True)
parser.add_argument('--key_name', default='Project')
parser.add_argument('--key_value', default='RNA-Seq1')
parser.add_argument('--gene_list', default=None)
if ci_values:
args = parser.parse_args(ci_values)
else:
args = parse_arguments()
return args | Standard argparse wrapper for interpreting command line arguments.
Args:
parser: if there's an existing parser, provide it, else, this will
create a new one.
ci_values: use for testing purposes only. | edgePy/data_import/mongodb/mongo_import.py | parse_arguments | r-bioinformatics/edgePy | 79 | python | def parse_arguments(parser: Any=None, ci_values: List[str]=None) -> Any:
"\n Standard argparse wrapper for interpreting command line arguments.\n\n Args:\n parser: if there's an existing parser, provide it, else, this will\n create a new one.\n ci_values: use for testing purposes only.\n "
if (not parser):
parser = argparse.ArgumentParser()
parser.add_argument('--config', help='location of the config file', required=True)
parser.add_argument('--key_name', default='Project')
parser.add_argument('--key_value', default='RNA-Seq1')
parser.add_argument('--gene_list', default=None)
if ci_values:
args = parser.parse_args(ci_values)
else:
args = parse_arguments()
return args | def parse_arguments(parser: Any=None, ci_values: List[str]=None) -> Any:
"\n Standard argparse wrapper for interpreting command line arguments.\n\n Args:\n parser: if there's an existing parser, provide it, else, this will\n create a new one.\n ci_values: use for testing purposes only.\n "
if (not parser):
parser = argparse.ArgumentParser()
parser.add_argument('--config', help='location of the config file', required=True)
parser.add_argument('--key_name', default='Project')
parser.add_argument('--key_value', default='RNA-Seq1')
parser.add_argument('--gene_list', default=None)
if ci_values:
args = parser.parse_args(ci_values)
else:
args = parse_arguments()
return args<|docstring|>Standard argparse wrapper for interpreting command line arguments.
Args:
parser: if there's an existing parser, provide it, else, this will
create a new one.
ci_values: use for testing purposes only.<|endoftext|> |
693e4d7f39cfddc8ef19c6b88db0f8fe9e5452296a7b5bb78c5e8b86581406c0 | def translate_gene_list(self, database: str) -> None:
'\n If there was a list of genes provided, convert them to ENSG symbols.\n\n Args:\n database: name of the database\n\n '
if self.input_gene_file:
input_genes = get_genelist_from_file(self.input_gene_file)
(ensg_genes, gene_symbols) = translate_genes(input_genes, self.mongo_reader, database=database)
self.gene_list = ensg_genes | If there was a list of genes provided, convert them to ENSG symbols.
Args:
database: name of the database | edgePy/data_import/mongodb/mongo_import.py | translate_gene_list | r-bioinformatics/edgePy | 79 | python | def translate_gene_list(self, database: str) -> None:
'\n If there was a list of genes provided, convert them to ENSG symbols.\n\n Args:\n database: name of the database\n\n '
if self.input_gene_file:
input_genes = get_genelist_from_file(self.input_gene_file)
(ensg_genes, gene_symbols) = translate_genes(input_genes, self.mongo_reader, database=database)
self.gene_list = ensg_genes | def translate_gene_list(self, database: str) -> None:
'\n If there was a list of genes provided, convert them to ENSG symbols.\n\n Args:\n database: name of the database\n\n '
if self.input_gene_file:
input_genes = get_genelist_from_file(self.input_gene_file)
(ensg_genes, gene_symbols) = translate_genes(input_genes, self.mongo_reader, database=database)
self.gene_list = ensg_genes<|docstring|>If there was a list of genes provided, convert them to ENSG symbols.
Args:
database: name of the database<|endoftext|> |
6ef126c986ef2213871fadb25485e45170de1d612cb2ede5ee78b2d08b6046c9 | def get_data_from_mongo(self, database: str, rpkm_flag: bool=False) -> Tuple[(List[str], Dict[(Hashable, Any)], List[str], Dict[(Hashable, Any)])]:
'\n Run the queries to get the samples, from mongo, and then use that data to retrieve\n the counts.\n\n Args:\n database: name of the database to retrieve data from.\n rpkm_flag: takes the rpkm values from the mongodb, instead of the raw counts\n\n Returns:\n the list of samples, the data itself,\n the gene list and the categories of the samples.\n\n '
if (self.input_gene_file and (not self.gene_list)):
self.translate_gene_list(database)
query: Dict[(Hashable, Any)] = {}
if (self.search_key and self.search_value):
if (self.search_value == 'regex'):
query = {self.search_key: {'$regex': 'myocyte|fibroblast'}}
elif isinstance(self.search_value, list):
query[self.search_key] = {'$in': self.search_value}
else:
query[self.search_key] = self.search_value
elif (self.search_key and (not self.search_value)):
query[self.search_key] = {'$exists': True}
elif ((not self.search_key) and (not self.search_value)):
pass
else:
raise Exception("Invalid input - you can't specify a key_value without specifying a key_name")
projection: Dict[(Hashable, Any)] = {'sample_name': 1, '_id': 0}
if (self.search_key and (not (self.search_key == 'sample_name'))):
projection[self.search_key] = 1
cursor = self.mongo_reader.find_as_cursor(database=database, collection='samples', query=query, projection=projection)
sample_names = set()
sample_category = {}
for result in cursor:
log.info(result)
sample_names.add(result['sample_name'])
sample_category[result['sample_name']] = (result[self.search_key] if self.search_key else result['sample_name'])
log.info(f'Get data for sample_names {list(sample_names)}')
query = {'sample_name': {'$in': list(sample_names)}}
if self.gene_list:
log.info(self.gene_list)
query['gene'] = {'$in': list(self.gene_list)}
cursor = self.mongo_reader.find_as_cursor(database=database, collection='RNASeq', query=query, projection={'_id': 0})
log.info(f'Importing data from mongo ({self.mongo_host})...')
dataset: Dict[(Hashable, Dict[(Hashable, Optional[int])])] = {}
gene_list = set()
sample_list = set()
for (count, result) in enumerate(cursor):
if ((count % 100000) == 0):
log.info(f'{count} rows processed.')
sample = result['sample_name']
rpkm = (get_canonical_rpkm(result) if rpkm_flag else get_canonical_raw(result))
gene = result['gene']
if (sample not in dataset):
dataset[sample] = {}
dataset[sample][gene] = rpkm
sample_list.add(sample)
gene_list.add(gene)
return (sorted(sample_list), dataset, sorted(gene_list), sample_category) | Run the queries to get the samples, from mongo, and then use that data to retrieve
the counts.
Args:
database: name of the database to retrieve data from.
rpkm_flag: takes the rpkm values from the mongodb, instead of the raw counts
Returns:
the list of samples, the data itself,
the gene list and the categories of the samples. | edgePy/data_import/mongodb/mongo_import.py | get_data_from_mongo | r-bioinformatics/edgePy | 79 | python | def get_data_from_mongo(self, database: str, rpkm_flag: bool=False) -> Tuple[(List[str], Dict[(Hashable, Any)], List[str], Dict[(Hashable, Any)])]:
'\n Run the queries to get the samples, from mongo, and then use that data to retrieve\n the counts.\n\n Args:\n database: name of the database to retrieve data from.\n rpkm_flag: takes the rpkm values from the mongodb, instead of the raw counts\n\n Returns:\n the list of samples, the data itself,\n the gene list and the categories of the samples.\n\n '
if (self.input_gene_file and (not self.gene_list)):
self.translate_gene_list(database)
query: Dict[(Hashable, Any)] = {}
if (self.search_key and self.search_value):
if (self.search_value == 'regex'):
query = {self.search_key: {'$regex': 'myocyte|fibroblast'}}
elif isinstance(self.search_value, list):
query[self.search_key] = {'$in': self.search_value}
else:
query[self.search_key] = self.search_value
elif (self.search_key and (not self.search_value)):
query[self.search_key] = {'$exists': True}
elif ((not self.search_key) and (not self.search_value)):
pass
else:
raise Exception("Invalid input - you can't specify a key_value without specifying a key_name")
projection: Dict[(Hashable, Any)] = {'sample_name': 1, '_id': 0}
if (self.search_key and (not (self.search_key == 'sample_name'))):
projection[self.search_key] = 1
cursor = self.mongo_reader.find_as_cursor(database=database, collection='samples', query=query, projection=projection)
sample_names = set()
sample_category = {}
for result in cursor:
log.info(result)
sample_names.add(result['sample_name'])
sample_category[result['sample_name']] = (result[self.search_key] if self.search_key else result['sample_name'])
log.info(f'Get data for sample_names {list(sample_names)}')
query = {'sample_name': {'$in': list(sample_names)}}
if self.gene_list:
log.info(self.gene_list)
query['gene'] = {'$in': list(self.gene_list)}
cursor = self.mongo_reader.find_as_cursor(database=database, collection='RNASeq', query=query, projection={'_id': 0})
log.info(f'Importing data from mongo ({self.mongo_host})...')
dataset: Dict[(Hashable, Dict[(Hashable, Optional[int])])] = {}
gene_list = set()
sample_list = set()
for (count, result) in enumerate(cursor):
if ((count % 100000) == 0):
log.info(f'{count} rows processed.')
sample = result['sample_name']
rpkm = (get_canonical_rpkm(result) if rpkm_flag else get_canonical_raw(result))
gene = result['gene']
if (sample not in dataset):
dataset[sample] = {}
dataset[sample][gene] = rpkm
sample_list.add(sample)
gene_list.add(gene)
return (sorted(sample_list), dataset, sorted(gene_list), sample_category) | def get_data_from_mongo(self, database: str, rpkm_flag: bool=False) -> Tuple[(List[str], Dict[(Hashable, Any)], List[str], Dict[(Hashable, Any)])]:
'\n Run the queries to get the samples, from mongo, and then use that data to retrieve\n the counts.\n\n Args:\n database: name of the database to retrieve data from.\n rpkm_flag: takes the rpkm values from the mongodb, instead of the raw counts\n\n Returns:\n the list of samples, the data itself,\n the gene list and the categories of the samples.\n\n '
if (self.input_gene_file and (not self.gene_list)):
self.translate_gene_list(database)
query: Dict[(Hashable, Any)] = {}
if (self.search_key and self.search_value):
if (self.search_value == 'regex'):
query = {self.search_key: {'$regex': 'myocyte|fibroblast'}}
elif isinstance(self.search_value, list):
query[self.search_key] = {'$in': self.search_value}
else:
query[self.search_key] = self.search_value
elif (self.search_key and (not self.search_value)):
query[self.search_key] = {'$exists': True}
elif ((not self.search_key) and (not self.search_value)):
pass
else:
raise Exception("Invalid input - you can't specify a key_value without specifying a key_name")
projection: Dict[(Hashable, Any)] = {'sample_name': 1, '_id': 0}
if (self.search_key and (not (self.search_key == 'sample_name'))):
projection[self.search_key] = 1
cursor = self.mongo_reader.find_as_cursor(database=database, collection='samples', query=query, projection=projection)
sample_names = set()
sample_category = {}
for result in cursor:
log.info(result)
sample_names.add(result['sample_name'])
sample_category[result['sample_name']] = (result[self.search_key] if self.search_key else result['sample_name'])
log.info(f'Get data for sample_names {list(sample_names)}')
query = {'sample_name': {'$in': list(sample_names)}}
if self.gene_list:
log.info(self.gene_list)
query['gene'] = {'$in': list(self.gene_list)}
cursor = self.mongo_reader.find_as_cursor(database=database, collection='RNASeq', query=query, projection={'_id': 0})
log.info(f'Importing data from mongo ({self.mongo_host})...')
dataset: Dict[(Hashable, Dict[(Hashable, Optional[int])])] = {}
gene_list = set()
sample_list = set()
for (count, result) in enumerate(cursor):
if ((count % 100000) == 0):
log.info(f'{count} rows processed.')
sample = result['sample_name']
rpkm = (get_canonical_rpkm(result) if rpkm_flag else get_canonical_raw(result))
gene = result['gene']
if (sample not in dataset):
dataset[sample] = {}
dataset[sample][gene] = rpkm
sample_list.add(sample)
gene_list.add(gene)
return (sorted(sample_list), dataset, sorted(gene_list), sample_category)<|docstring|>Run the queries to get the samples, from mongo, and then use that data to retrieve
the counts.
Args:
database: name of the database to retrieve data from.
rpkm_flag: takes the rpkm values from the mongodb, instead of the raw counts
Returns:
the list of samples, the data itself,
the gene list and the categories of the samples.<|endoftext|> |
0fe1259603a9a23db385de48a7d8ce3bcf3bddf2613253f61d7cfbd52fb5796e | def __sub__(self, widget):
'\n\t\tRemove subwindow and unassigned it from widget\n\t\t:param widget:\n\t\t:return:\n\t\t'
widget.close()
self += widget
self.removeSubWindow(widget.subwindow)
del widget.subwindow
logger.debug('Widget sub window removed. MDI area sub windows: %s', self.subWindowList())
return self | Remove subwindow and unassigned it from widget
:param widget:
:return: | pyforms/gui/Controls/ControlMdiArea.py | __sub__ | Jess3Jane/pyforms | 0 | python | def __sub__(self, widget):
'\n\t\tRemove subwindow and unassigned it from widget\n\t\t:param widget:\n\t\t:return:\n\t\t'
widget.close()
self += widget
self.removeSubWindow(widget.subwindow)
del widget.subwindow
logger.debug('Widget sub window removed. MDI area sub windows: %s', self.subWindowList())
return self | def __sub__(self, widget):
'\n\t\tRemove subwindow and unassigned it from widget\n\t\t:param widget:\n\t\t:return:\n\t\t'
widget.close()
self += widget
self.removeSubWindow(widget.subwindow)
del widget.subwindow
logger.debug('Widget sub window removed. MDI area sub windows: %s', self.subWindowList())
return self<|docstring|>Remove subwindow and unassigned it from widget
:param widget:
:return:<|endoftext|> |
4f2b57c0c2981f20180175e25918f6f9fa364d59dbf5c218bd9df58d2cf35529 | def __add__(self, widget):
'\n\t\tShow widget on mdi area.\n\n\t\tIf widget does not have a subwindow assigned, create a new subwindow without enabling the WA_DeleteOnClose event.\n\t\tThis will allow subwindow to be hidden instead of destroyed. Otherwise, the closeEvent.accept() will cause\n\t\tthe "Internal c++ Object Already Deleted" problem.\n\n\t\tIf widget already has a subwindow, just show them (both the subwindow and the widget inside)!\n\t\t:param widget:\n\t\t:return:\n\t\t'
if (not hasattr(widget, 'subwindow')):
subwindow = QMdiSubWindow()
subwindow.setWidget(widget)
rect = widget.geometry()
widget.subwindow = self.addSubWindow(subwindow)
subwindow.setGeometry(rect)
widget.subwindow.show()
widget.show()
widget.closeEvent = (lambda x: self._subWindowClosed(x))
widget.setFocus()
logger.debug('Sub window opened. MDI area sub windows: %s', self.subWindowList())
return self | Show widget on mdi area.
If widget does not have a subwindow assigned, create a new subwindow without enabling the WA_DeleteOnClose event.
This will allow subwindow to be hidden instead of destroyed. Otherwise, the closeEvent.accept() will cause
the "Internal c++ Object Already Deleted" problem.
If widget already has a subwindow, just show them (both the subwindow and the widget inside)!
:param widget:
:return: | pyforms/gui/Controls/ControlMdiArea.py | __add__ | Jess3Jane/pyforms | 0 | python | def __add__(self, widget):
'\n\t\tShow widget on mdi area.\n\n\t\tIf widget does not have a subwindow assigned, create a new subwindow without enabling the WA_DeleteOnClose event.\n\t\tThis will allow subwindow to be hidden instead of destroyed. Otherwise, the closeEvent.accept() will cause\n\t\tthe "Internal c++ Object Already Deleted" problem.\n\n\t\tIf widget already has a subwindow, just show them (both the subwindow and the widget inside)!\n\t\t:param widget:\n\t\t:return:\n\t\t'
if (not hasattr(widget, 'subwindow')):
subwindow = QMdiSubWindow()
subwindow.setWidget(widget)
rect = widget.geometry()
widget.subwindow = self.addSubWindow(subwindow)
subwindow.setGeometry(rect)
widget.subwindow.show()
widget.show()
widget.closeEvent = (lambda x: self._subWindowClosed(x))
widget.setFocus()
logger.debug('Sub window opened. MDI area sub windows: %s', self.subWindowList())
return self | def __add__(self, widget):
'\n\t\tShow widget on mdi area.\n\n\t\tIf widget does not have a subwindow assigned, create a new subwindow without enabling the WA_DeleteOnClose event.\n\t\tThis will allow subwindow to be hidden instead of destroyed. Otherwise, the closeEvent.accept() will cause\n\t\tthe "Internal c++ Object Already Deleted" problem.\n\n\t\tIf widget already has a subwindow, just show them (both the subwindow and the widget inside)!\n\t\t:param widget:\n\t\t:return:\n\t\t'
if (not hasattr(widget, 'subwindow')):
subwindow = QMdiSubWindow()
subwindow.setWidget(widget)
rect = widget.geometry()
widget.subwindow = self.addSubWindow(subwindow)
subwindow.setGeometry(rect)
widget.subwindow.show()
widget.show()
widget.closeEvent = (lambda x: self._subWindowClosed(x))
widget.setFocus()
logger.debug('Sub window opened. MDI area sub windows: %s', self.subWindowList())
return self<|docstring|>Show widget on mdi area.
If widget does not have a subwindow assigned, create a new subwindow without enabling the WA_DeleteOnClose event.
This will allow subwindow to be hidden instead of destroyed. Otherwise, the closeEvent.accept() will cause
the "Internal c++ Object Already Deleted" problem.
If widget already has a subwindow, just show them (both the subwindow and the widget inside)!
:param widget:
:return:<|endoftext|> |
3d725d36cc3b27082f37685692929099b14b59714d6239d9b90737c41fc7961d | def _subWindowClosed(self, closeEvent):
"\n\t\tPerform actions when subwindow is closed.\n\t\tIn this case, we don't want subwindow to be removed nor destroyed in order to reutilize later.\n\t\tThe closeEvent.accept() will just hide the subwindow.\n\t\t:param closeEvent:\n\t\t:return:\n\t\t"
try:
window = self.activeSubWindow()
if window:
widget = window.widget()
widget.before_close_event()
elif hasattr(window, 'before_close_event'):
widget.before_close_event()
closeEvent.accept()
logger.debug('Sub window closed. MDI area sub windows: %s', self.subWindowList())
except Exception as err:
logger.warning(str(err)) | Perform actions when subwindow is closed.
In this case, we don't want subwindow to be removed nor destroyed in order to reutilize later.
The closeEvent.accept() will just hide the subwindow.
:param closeEvent:
:return: | pyforms/gui/Controls/ControlMdiArea.py | _subWindowClosed | Jess3Jane/pyforms | 0 | python | def _subWindowClosed(self, closeEvent):
"\n\t\tPerform actions when subwindow is closed.\n\t\tIn this case, we don't want subwindow to be removed nor destroyed in order to reutilize later.\n\t\tThe closeEvent.accept() will just hide the subwindow.\n\t\t:param closeEvent:\n\t\t:return:\n\t\t"
try:
window = self.activeSubWindow()
if window:
widget = window.widget()
widget.before_close_event()
elif hasattr(window, 'before_close_event'):
widget.before_close_event()
closeEvent.accept()
logger.debug('Sub window closed. MDI area sub windows: %s', self.subWindowList())
except Exception as err:
logger.warning(str(err)) | def _subWindowClosed(self, closeEvent):
"\n\t\tPerform actions when subwindow is closed.\n\t\tIn this case, we don't want subwindow to be removed nor destroyed in order to reutilize later.\n\t\tThe closeEvent.accept() will just hide the subwindow.\n\t\t:param closeEvent:\n\t\t:return:\n\t\t"
try:
window = self.activeSubWindow()
if window:
widget = window.widget()
widget.before_close_event()
elif hasattr(window, 'before_close_event'):
widget.before_close_event()
closeEvent.accept()
logger.debug('Sub window closed. MDI area sub windows: %s', self.subWindowList())
except Exception as err:
logger.warning(str(err))<|docstring|>Perform actions when subwindow is closed.
In this case, we don't want subwindow to be removed nor destroyed in order to reutilize later.
The closeEvent.accept() will just hide the subwindow.
:param closeEvent:
:return:<|endoftext|> |
a113a64c67eabf955b5dbeaf638689a03aa2ec93f8876f53bc364c1ec31a28f1 | def wrap(func: _Callable, *, delay: bool=None, strict: StrictModeT=STRICT_MODE) -> _Callable:
'Wrap a callable to automatically enforce type-coercion.\n\n Parameters\n ----------\n func\n The callable for which you wish to ensure type-safety\n delay\n Delay annotation resolution until the first call\n strict\n Turn on "validator mode": e.g. validate incoming data rather than coerce.\n\n See Also\n --------\n :py:func:`inspect.signature`\n :py:meth:`inspect.Signature.bind`\n '
if isinstance(delay, bool):
warnings.warn('The `delay` argument is no longer required and is deprecated. It will be removed in a future version.', category=DeprecationWarning)
protos = protocols(func, strict=cast(bool, strict))
params = cached_signature(func).parameters
enforcer = resolver.binder.get_enforcer(parameters=params, protocols=protos)
@functools.wraps(func)
def func_wrapper(*args, **kwargs):
(args, kwargs) = enforcer(*args, **kwargs)
return func(*args, **kwargs)
return cast(_Callable, func_wrapper) | Wrap a callable to automatically enforce type-coercion.
Parameters
----------
func
The callable for which you wish to ensure type-safety
delay
Delay annotation resolution until the first call
strict
Turn on "validator mode": e.g. validate incoming data rather than coerce.
See Also
--------
:py:func:`inspect.signature`
:py:meth:`inspect.Signature.bind` | typic/api.py | wrap | wyfo/typical | 157 | python | def wrap(func: _Callable, *, delay: bool=None, strict: StrictModeT=STRICT_MODE) -> _Callable:
'Wrap a callable to automatically enforce type-coercion.\n\n Parameters\n ----------\n func\n The callable for which you wish to ensure type-safety\n delay\n Delay annotation resolution until the first call\n strict\n Turn on "validator mode": e.g. validate incoming data rather than coerce.\n\n See Also\n --------\n :py:func:`inspect.signature`\n :py:meth:`inspect.Signature.bind`\n '
if isinstance(delay, bool):
warnings.warn('The `delay` argument is no longer required and is deprecated. It will be removed in a future version.', category=DeprecationWarning)
protos = protocols(func, strict=cast(bool, strict))
params = cached_signature(func).parameters
enforcer = resolver.binder.get_enforcer(parameters=params, protocols=protos)
@functools.wraps(func)
def func_wrapper(*args, **kwargs):
(args, kwargs) = enforcer(*args, **kwargs)
return func(*args, **kwargs)
return cast(_Callable, func_wrapper) | def wrap(func: _Callable, *, delay: bool=None, strict: StrictModeT=STRICT_MODE) -> _Callable:
'Wrap a callable to automatically enforce type-coercion.\n\n Parameters\n ----------\n func\n The callable for which you wish to ensure type-safety\n delay\n Delay annotation resolution until the first call\n strict\n Turn on "validator mode": e.g. validate incoming data rather than coerce.\n\n See Also\n --------\n :py:func:`inspect.signature`\n :py:meth:`inspect.Signature.bind`\n '
if isinstance(delay, bool):
warnings.warn('The `delay` argument is no longer required and is deprecated. It will be removed in a future version.', category=DeprecationWarning)
protos = protocols(func, strict=cast(bool, strict))
params = cached_signature(func).parameters
enforcer = resolver.binder.get_enforcer(parameters=params, protocols=protos)
@functools.wraps(func)
def func_wrapper(*args, **kwargs):
(args, kwargs) = enforcer(*args, **kwargs)
return func(*args, **kwargs)
return cast(_Callable, func_wrapper)<|docstring|>Wrap a callable to automatically enforce type-coercion.
Parameters
----------
func
The callable for which you wish to ensure type-safety
delay
Delay annotation resolution until the first call
strict
Turn on "validator mode": e.g. validate incoming data rather than coerce.
See Also
--------
:py:func:`inspect.signature`
:py:meth:`inspect.Signature.bind`<|endoftext|> |
b1655950c3e45f0c9a1946d396dffb128dcacfe4f6b53d68cf09c0779ec2482e | def wrap_cls(klass: Type[ObjectT], *, delay: bool=False, strict: StrictModeT=STRICT_MODE, jsonschema: bool=True, serde: SerdeFlags=SerdeFlags(), always: bool=None) -> Type[WrappedObjectT[ObjectT]]:
'Wrap a class to automatically enforce type-coercion on init.\n\n Notes\n -----\n While `Coercer.wrap` will work with classes alone, it changes the signature of the\n object to a function, there-by breaking inheritance. This follows a similar pattern to\n :func:`dataclasses.dataclasses`, which executes the function when wrapped, preserving\n the signature of the target class.\n\n Parameters\n ----------\n klass\n The class you wish to patch with coercion.\n delay\n Delay annotation resolution until first initialization.\n strict\n Turn on "validator mode": e.g. validate incoming data rather than coerce.\n jsonschema\n Generate a JSON Schema entry for this object.\n serde\n Optional settings for serialization/deserialization\n '
def cls_wrapper(cls_: Type[ObjectT]) -> Type[WrappedObjectT[ObjectT]]:
if isinstance(delay, bool):
warnings.warn('The `delay` argument is no longer required and is deprecated.It will be removed in a future version.', category=DeprecationWarning)
setattr(cls_, '__delayed__', False)
return _resolve_class(cls_, strict=strict, jsonschema=jsonschema, serde=serde, always=always)
wrapped: Type[WrappedObjectT[ObjectT]] = cls_wrapper(klass)
return wrapped | Wrap a class to automatically enforce type-coercion on init.
Notes
-----
While `Coercer.wrap` will work with classes alone, it changes the signature of the
object to a function, there-by breaking inheritance. This follows a similar pattern to
:func:`dataclasses.dataclasses`, which executes the function when wrapped, preserving
the signature of the target class.
Parameters
----------
klass
The class you wish to patch with coercion.
delay
Delay annotation resolution until first initialization.
strict
Turn on "validator mode": e.g. validate incoming data rather than coerce.
jsonschema
Generate a JSON Schema entry for this object.
serde
Optional settings for serialization/deserialization | typic/api.py | wrap_cls | wyfo/typical | 157 | python | def wrap_cls(klass: Type[ObjectT], *, delay: bool=False, strict: StrictModeT=STRICT_MODE, jsonschema: bool=True, serde: SerdeFlags=SerdeFlags(), always: bool=None) -> Type[WrappedObjectT[ObjectT]]:
'Wrap a class to automatically enforce type-coercion on init.\n\n Notes\n -----\n While `Coercer.wrap` will work with classes alone, it changes the signature of the\n object to a function, there-by breaking inheritance. This follows a similar pattern to\n :func:`dataclasses.dataclasses`, which executes the function when wrapped, preserving\n the signature of the target class.\n\n Parameters\n ----------\n klass\n The class you wish to patch with coercion.\n delay\n Delay annotation resolution until first initialization.\n strict\n Turn on "validator mode": e.g. validate incoming data rather than coerce.\n jsonschema\n Generate a JSON Schema entry for this object.\n serde\n Optional settings for serialization/deserialization\n '
def cls_wrapper(cls_: Type[ObjectT]) -> Type[WrappedObjectT[ObjectT]]:
if isinstance(delay, bool):
warnings.warn('The `delay` argument is no longer required and is deprecated.It will be removed in a future version.', category=DeprecationWarning)
setattr(cls_, '__delayed__', False)
return _resolve_class(cls_, strict=strict, jsonschema=jsonschema, serde=serde, always=always)
wrapped: Type[WrappedObjectT[ObjectT]] = cls_wrapper(klass)
return wrapped | def wrap_cls(klass: Type[ObjectT], *, delay: bool=False, strict: StrictModeT=STRICT_MODE, jsonschema: bool=True, serde: SerdeFlags=SerdeFlags(), always: bool=None) -> Type[WrappedObjectT[ObjectT]]:
'Wrap a class to automatically enforce type-coercion on init.\n\n Notes\n -----\n While `Coercer.wrap` will work with classes alone, it changes the signature of the\n object to a function, there-by breaking inheritance. This follows a similar pattern to\n :func:`dataclasses.dataclasses`, which executes the function when wrapped, preserving\n the signature of the target class.\n\n Parameters\n ----------\n klass\n The class you wish to patch with coercion.\n delay\n Delay annotation resolution until first initialization.\n strict\n Turn on "validator mode": e.g. validate incoming data rather than coerce.\n jsonschema\n Generate a JSON Schema entry for this object.\n serde\n Optional settings for serialization/deserialization\n '
def cls_wrapper(cls_: Type[ObjectT]) -> Type[WrappedObjectT[ObjectT]]:
if isinstance(delay, bool):
warnings.warn('The `delay` argument is no longer required and is deprecated.It will be removed in a future version.', category=DeprecationWarning)
setattr(cls_, '__delayed__', False)
return _resolve_class(cls_, strict=strict, jsonschema=jsonschema, serde=serde, always=always)
wrapped: Type[WrappedObjectT[ObjectT]] = cls_wrapper(klass)
return wrapped<|docstring|>Wrap a class to automatically enforce type-coercion on init.
Notes
-----
While `Coercer.wrap` will work with classes alone, it changes the signature of the
object to a function, there-by breaking inheritance. This follows a similar pattern to
:func:`dataclasses.dataclasses`, which executes the function when wrapped, preserving
the signature of the target class.
Parameters
----------
klass
The class you wish to patch with coercion.
delay
Delay annotation resolution until first initialization.
strict
Turn on "validator mode": e.g. validate incoming data rather than coerce.
jsonschema
Generate a JSON Schema entry for this object.
serde
Optional settings for serialization/deserialization<|endoftext|> |
721d3ee29e38b8eff9ec97b16da0f3c4163bc6068a57d4de3f78348e1e003d22 | def typed(_cls_or_callable=None, *, delay: bool=False, strict: bool=None, always: bool=None):
'A convenience function which automatically selects the correct wrapper.\n\n Parameters\n ----------\n delay\n Optionally delay annotation resolution until first call.\n strict\n Turn on "validator mode": e.g. validate incoming data rather than coerce.\n always\n Whether classes should always coerce values on their attributes.\n\n Returns\n -------\n The target object, appropriately wrapped.\n '
strict = (STRICT_MODE if (strict is None) else strict)
def _typed(obj: Union[(Callable, Type[ObjectT])]):
if inspect.isclass(obj):
return wrap_cls(obj, delay=delay, strict=strict, always=always)
elif callable(obj):
return wrap(obj, delay=delay, strict=strict)
else:
raise TypeError(f'{__name__} requires a callable or class. Provided: {type(obj)}: {obj}')
return (_typed(_cls_or_callable) if (_cls_or_callable is not None) else _typed) | A convenience function which automatically selects the correct wrapper.
Parameters
----------
delay
Optionally delay annotation resolution until first call.
strict
Turn on "validator mode": e.g. validate incoming data rather than coerce.
always
Whether classes should always coerce values on their attributes.
Returns
-------
The target object, appropriately wrapped. | typic/api.py | typed | wyfo/typical | 157 | python | def typed(_cls_or_callable=None, *, delay: bool=False, strict: bool=None, always: bool=None):
'A convenience function which automatically selects the correct wrapper.\n\n Parameters\n ----------\n delay\n Optionally delay annotation resolution until first call.\n strict\n Turn on "validator mode": e.g. validate incoming data rather than coerce.\n always\n Whether classes should always coerce values on their attributes.\n\n Returns\n -------\n The target object, appropriately wrapped.\n '
strict = (STRICT_MODE if (strict is None) else strict)
def _typed(obj: Union[(Callable, Type[ObjectT])]):
if inspect.isclass(obj):
return wrap_cls(obj, delay=delay, strict=strict, always=always)
elif callable(obj):
return wrap(obj, delay=delay, strict=strict)
else:
raise TypeError(f'{__name__} requires a callable or class. Provided: {type(obj)}: {obj}')
return (_typed(_cls_or_callable) if (_cls_or_callable is not None) else _typed) | def typed(_cls_or_callable=None, *, delay: bool=False, strict: bool=None, always: bool=None):
'A convenience function which automatically selects the correct wrapper.\n\n Parameters\n ----------\n delay\n Optionally delay annotation resolution until first call.\n strict\n Turn on "validator mode": e.g. validate incoming data rather than coerce.\n always\n Whether classes should always coerce values on their attributes.\n\n Returns\n -------\n The target object, appropriately wrapped.\n '
strict = (STRICT_MODE if (strict is None) else strict)
def _typed(obj: Union[(Callable, Type[ObjectT])]):
if inspect.isclass(obj):
return wrap_cls(obj, delay=delay, strict=strict, always=always)
elif callable(obj):
return wrap(obj, delay=delay, strict=strict)
else:
raise TypeError(f'{__name__} requires a callable or class. Provided: {type(obj)}: {obj}')
return (_typed(_cls_or_callable) if (_cls_or_callable is not None) else _typed)<|docstring|>A convenience function which automatically selects the correct wrapper.
Parameters
----------
delay
Optionally delay annotation resolution until first call.
strict
Turn on "validator mode": e.g. validate incoming data rather than coerce.
always
Whether classes should always coerce values on their attributes.
Returns
-------
The target object, appropriately wrapped.<|endoftext|> |
e135311b8c0eb8f8a0187a405ac756145494886d4be306331b7c1f2317708c6f | def resolve():
'Resolve any delayed annotations.\n\n If this is not called, annotations will be resolved on first call\n of the wrapped class or callable.\n\n Examples\n --------\n >>> import typic\n >>>\n >>> @typic.klass(delay=True)\n ... class Duck:\n ... color: str\n ...\n >>> typic.resolve()\n '
warnings.warn('Delayed type resolution is handled automatically as of v2.3.0. This function is now a no-op and will be removed in a future version.', category=DeprecationWarning) | Resolve any delayed annotations.
If this is not called, annotations will be resolved on first call
of the wrapped class or callable.
Examples
--------
>>> import typic
>>>
>>> @typic.klass(delay=True)
... class Duck:
... color: str
...
>>> typic.resolve() | typic/api.py | resolve | wyfo/typical | 157 | python | def resolve():
'Resolve any delayed annotations.\n\n If this is not called, annotations will be resolved on first call\n of the wrapped class or callable.\n\n Examples\n --------\n >>> import typic\n >>>\n >>> @typic.klass(delay=True)\n ... class Duck:\n ... color: str\n ...\n >>> typic.resolve()\n '
warnings.warn('Delayed type resolution is handled automatically as of v2.3.0. This function is now a no-op and will be removed in a future version.', category=DeprecationWarning) | def resolve():
'Resolve any delayed annotations.\n\n If this is not called, annotations will be resolved on first call\n of the wrapped class or callable.\n\n Examples\n --------\n >>> import typic\n >>>\n >>> @typic.klass(delay=True)\n ... class Duck:\n ... color: str\n ...\n >>> typic.resolve()\n '
warnings.warn('Delayed type resolution is handled automatically as of v2.3.0. This function is now a no-op and will be removed in a future version.', category=DeprecationWarning)<|docstring|>Resolve any delayed annotations.
If this is not called, annotations will be resolved on first call
of the wrapped class or callable.
Examples
--------
>>> import typic
>>>
>>> @typic.klass(delay=True)
... class Duck:
... color: str
...
>>> typic.resolve()<|endoftext|> |
e6cde6310148ff726b984352a96a91d2c95922766bf9b0674e515a6f1f00e8bb | def constrained(_klass=None, *, values: Union[(Type, Tuple[(Type, ...)])]=None, **constraints):
'A wrapper to indicate a \'constrained\' type.\n\n Parameters\n ----------\n values\n For container-types, you can pass in other constraints for the values to be\n validated against. Can be a single constraint for all values or a tuple of\n constraints to choose from.\n\n **constraints\n The restrictions to apply to values being cast as the decorated type.\n\n Examples\n --------\n >>> import typic\n >>>\n >>> @typic.constrained(max_length=10)\n ... class ShortStr(str):\n ... \'\'\'A short string.\'\'\'\n ... ...\n ...\n >>> ShortStr(\'foo\')\n \'foo\'\n >>> ShortStr(\'waytoomanycharacters\')\n Traceback (most recent call last):\n ...\n typic.constraints.error.ConstraintValueError: Given value <\'waytoomanycharacters\'> fails constraints: (type=str, nullable=False, max_length=10)\n >>> @typic.constrained(values=ShortStr, max_items=2)\n ... class SmallMap(dict):\n ... \'\'\'A small map that only allows short strings.\'\'\'\n ...\n >>> import json\n >>> print(json.dumps(typic.schema(SmallMap, primitive=True), indent=2))\n {\n "type": "object",\n "title": "SmallMap",\n "description": "A small map that only allows short strings.",\n "additionalProperties": {\n "type": "string",\n "maxLength": 10\n },\n "maxProperties": 2\n }\n\n\n See Also\n --------\n :py:mod:`typic.constraints.array`\n\n :py:mod:`typic.constraints.common`\n\n :py:mod:`typic.constraints.error`\n\n :py:mod:`typic.constraints.mapping`\n\n :py:mod:`typic.constraints.number`\n\n :py:mod:`typic.constraints.text`\n '
def constr_wrapper(cls_: Type[ObjectT]) -> Type[ObjectT]:
nonlocal constraints
nonlocal values
cdict = dict(cls_.__dict__)
cdict.pop('__dict__', None)
cdict.pop('__weakref__', None)
constr_cls = _get_constraint_cls(cls_)
if (not constr_cls):
raise TypeError(f"can't constrain type {cls_.__name__!r}")
args: Tuple[(Type, ...)] = ()
if (values and (constr_cls.type in {list, dict, set, tuple, frozenset})):
args = _handle_constraint_values(constraints, values, args)
if (constr_cls.type == dict):
args = _handle_constraint_keys(constraints, args)
if args:
cdict['__args__'] = args
constraints_inst = constr_cls(**constraints)
bases = inspect.getmro(cls_)
def new(_new):
@functools.wraps(_new)
def __constrained_new(*args, **kwargs):
result = _new(*args, **kwargs)
return constraints_inst.validate(result)
return __constrained_new
def init(_init):
@functools.wraps(_init)
def __constrained_init(self, *args, **kwargs):
_init(self, *args, **kwargs)
constraints_inst.validate(self)
return __constrained_init
name = cls_.__name__
if isbuiltintype(cls_):
name = f'Constrained{cls_.__name__.capitalize()}'
cdict.update(__constraints__=constraints_inst, __parent__=constraints_inst.type, __module__=cls_.__module__, **({'__new__': new(cls_.__new__)} if (constraints_inst.type in {str, bytes, int, float}) else {'__init__': init(cls_.__init__)}))
cls: Type[ObjectT] = cast(Type[ObjectT], type(name, bases, cdict))
return cls
return (constr_wrapper(_klass) if _klass else constr_wrapper) | A wrapper to indicate a 'constrained' type.
Parameters
----------
values
For container-types, you can pass in other constraints for the values to be
validated against. Can be a single constraint for all values or a tuple of
constraints to choose from.
**constraints
The restrictions to apply to values being cast as the decorated type.
Examples
--------
>>> import typic
>>>
>>> @typic.constrained(max_length=10)
... class ShortStr(str):
... '''A short string.'''
... ...
...
>>> ShortStr('foo')
'foo'
>>> ShortStr('waytoomanycharacters')
Traceback (most recent call last):
...
typic.constraints.error.ConstraintValueError: Given value <'waytoomanycharacters'> fails constraints: (type=str, nullable=False, max_length=10)
>>> @typic.constrained(values=ShortStr, max_items=2)
... class SmallMap(dict):
... '''A small map that only allows short strings.'''
...
>>> import json
>>> print(json.dumps(typic.schema(SmallMap, primitive=True), indent=2))
{
"type": "object",
"title": "SmallMap",
"description": "A small map that only allows short strings.",
"additionalProperties": {
"type": "string",
"maxLength": 10
},
"maxProperties": 2
}
See Also
--------
:py:mod:`typic.constraints.array`
:py:mod:`typic.constraints.common`
:py:mod:`typic.constraints.error`
:py:mod:`typic.constraints.mapping`
:py:mod:`typic.constraints.number`
:py:mod:`typic.constraints.text` | typic/api.py | constrained | wyfo/typical | 157 | python | def constrained(_klass=None, *, values: Union[(Type, Tuple[(Type, ...)])]=None, **constraints):
'A wrapper to indicate a \'constrained\' type.\n\n Parameters\n ----------\n values\n For container-types, you can pass in other constraints for the values to be\n validated against. Can be a single constraint for all values or a tuple of\n constraints to choose from.\n\n **constraints\n The restrictions to apply to values being cast as the decorated type.\n\n Examples\n --------\n >>> import typic\n >>>\n >>> @typic.constrained(max_length=10)\n ... class ShortStr(str):\n ... \'\'\'A short string.\'\'\'\n ... ...\n ...\n >>> ShortStr(\'foo\')\n \'foo\'\n >>> ShortStr(\'waytoomanycharacters\')\n Traceback (most recent call last):\n ...\n typic.constraints.error.ConstraintValueError: Given value <\'waytoomanycharacters\'> fails constraints: (type=str, nullable=False, max_length=10)\n >>> @typic.constrained(values=ShortStr, max_items=2)\n ... class SmallMap(dict):\n ... \'\'\'A small map that only allows short strings.\'\'\'\n ...\n >>> import json\n >>> print(json.dumps(typic.schema(SmallMap, primitive=True), indent=2))\n {\n "type": "object",\n "title": "SmallMap",\n "description": "A small map that only allows short strings.",\n "additionalProperties": {\n "type": "string",\n "maxLength": 10\n },\n "maxProperties": 2\n }\n\n\n See Also\n --------\n :py:mod:`typic.constraints.array`\n\n :py:mod:`typic.constraints.common`\n\n :py:mod:`typic.constraints.error`\n\n :py:mod:`typic.constraints.mapping`\n\n :py:mod:`typic.constraints.number`\n\n :py:mod:`typic.constraints.text`\n '
def constr_wrapper(cls_: Type[ObjectT]) -> Type[ObjectT]:
nonlocal constraints
nonlocal values
cdict = dict(cls_.__dict__)
cdict.pop('__dict__', None)
cdict.pop('__weakref__', None)
constr_cls = _get_constraint_cls(cls_)
if (not constr_cls):
raise TypeError(f"can't constrain type {cls_.__name__!r}")
args: Tuple[(Type, ...)] = ()
if (values and (constr_cls.type in {list, dict, set, tuple, frozenset})):
args = _handle_constraint_values(constraints, values, args)
if (constr_cls.type == dict):
args = _handle_constraint_keys(constraints, args)
if args:
cdict['__args__'] = args
constraints_inst = constr_cls(**constraints)
bases = inspect.getmro(cls_)
def new(_new):
@functools.wraps(_new)
def __constrained_new(*args, **kwargs):
result = _new(*args, **kwargs)
return constraints_inst.validate(result)
return __constrained_new
def init(_init):
@functools.wraps(_init)
def __constrained_init(self, *args, **kwargs):
_init(self, *args, **kwargs)
constraints_inst.validate(self)
return __constrained_init
name = cls_.__name__
if isbuiltintype(cls_):
name = f'Constrained{cls_.__name__.capitalize()}'
cdict.update(__constraints__=constraints_inst, __parent__=constraints_inst.type, __module__=cls_.__module__, **({'__new__': new(cls_.__new__)} if (constraints_inst.type in {str, bytes, int, float}) else {'__init__': init(cls_.__init__)}))
cls: Type[ObjectT] = cast(Type[ObjectT], type(name, bases, cdict))
return cls
return (constr_wrapper(_klass) if _klass else constr_wrapper) | def constrained(_klass=None, *, values: Union[(Type, Tuple[(Type, ...)])]=None, **constraints):
'A wrapper to indicate a \'constrained\' type.\n\n Parameters\n ----------\n values\n For container-types, you can pass in other constraints for the values to be\n validated against. Can be a single constraint for all values or a tuple of\n constraints to choose from.\n\n **constraints\n The restrictions to apply to values being cast as the decorated type.\n\n Examples\n --------\n >>> import typic\n >>>\n >>> @typic.constrained(max_length=10)\n ... class ShortStr(str):\n ... \'\'\'A short string.\'\'\'\n ... ...\n ...\n >>> ShortStr(\'foo\')\n \'foo\'\n >>> ShortStr(\'waytoomanycharacters\')\n Traceback (most recent call last):\n ...\n typic.constraints.error.ConstraintValueError: Given value <\'waytoomanycharacters\'> fails constraints: (type=str, nullable=False, max_length=10)\n >>> @typic.constrained(values=ShortStr, max_items=2)\n ... class SmallMap(dict):\n ... \'\'\'A small map that only allows short strings.\'\'\'\n ...\n >>> import json\n >>> print(json.dumps(typic.schema(SmallMap, primitive=True), indent=2))\n {\n "type": "object",\n "title": "SmallMap",\n "description": "A small map that only allows short strings.",\n "additionalProperties": {\n "type": "string",\n "maxLength": 10\n },\n "maxProperties": 2\n }\n\n\n See Also\n --------\n :py:mod:`typic.constraints.array`\n\n :py:mod:`typic.constraints.common`\n\n :py:mod:`typic.constraints.error`\n\n :py:mod:`typic.constraints.mapping`\n\n :py:mod:`typic.constraints.number`\n\n :py:mod:`typic.constraints.text`\n '
def constr_wrapper(cls_: Type[ObjectT]) -> Type[ObjectT]:
nonlocal constraints
nonlocal values
cdict = dict(cls_.__dict__)
cdict.pop('__dict__', None)
cdict.pop('__weakref__', None)
constr_cls = _get_constraint_cls(cls_)
if (not constr_cls):
raise TypeError(f"can't constrain type {cls_.__name__!r}")
args: Tuple[(Type, ...)] = ()
if (values and (constr_cls.type in {list, dict, set, tuple, frozenset})):
args = _handle_constraint_values(constraints, values, args)
if (constr_cls.type == dict):
args = _handle_constraint_keys(constraints, args)
if args:
cdict['__args__'] = args
constraints_inst = constr_cls(**constraints)
bases = inspect.getmro(cls_)
def new(_new):
@functools.wraps(_new)
def __constrained_new(*args, **kwargs):
result = _new(*args, **kwargs)
return constraints_inst.validate(result)
return __constrained_new
def init(_init):
@functools.wraps(_init)
def __constrained_init(self, *args, **kwargs):
_init(self, *args, **kwargs)
constraints_inst.validate(self)
return __constrained_init
name = cls_.__name__
if isbuiltintype(cls_):
name = f'Constrained{cls_.__name__.capitalize()}'
cdict.update(__constraints__=constraints_inst, __parent__=constraints_inst.type, __module__=cls_.__module__, **({'__new__': new(cls_.__new__)} if (constraints_inst.type in {str, bytes, int, float}) else {'__init__': init(cls_.__init__)}))
cls: Type[ObjectT] = cast(Type[ObjectT], type(name, bases, cdict))
return cls
return (constr_wrapper(_klass) if _klass else constr_wrapper)<|docstring|>A wrapper to indicate a 'constrained' type.
Parameters
----------
values
For container-types, you can pass in other constraints for the values to be
validated against. Can be a single constraint for all values or a tuple of
constraints to choose from.
**constraints
The restrictions to apply to values being cast as the decorated type.
Examples
--------
>>> import typic
>>>
>>> @typic.constrained(max_length=10)
... class ShortStr(str):
... '''A short string.'''
... ...
...
>>> ShortStr('foo')
'foo'
>>> ShortStr('waytoomanycharacters')
Traceback (most recent call last):
...
typic.constraints.error.ConstraintValueError: Given value <'waytoomanycharacters'> fails constraints: (type=str, nullable=False, max_length=10)
>>> @typic.constrained(values=ShortStr, max_items=2)
... class SmallMap(dict):
... '''A small map that only allows short strings.'''
...
>>> import json
>>> print(json.dumps(typic.schema(SmallMap, primitive=True), indent=2))
{
"type": "object",
"title": "SmallMap",
"description": "A small map that only allows short strings.",
"additionalProperties": {
"type": "string",
"maxLength": 10
},
"maxProperties": 2
}
See Also
--------
:py:mod:`typic.constraints.array`
:py:mod:`typic.constraints.common`
:py:mod:`typic.constraints.error`
:py:mod:`typic.constraints.mapping`
:py:mod:`typic.constraints.number`
:py:mod:`typic.constraints.text`<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.