uid
stringlengths
24
24
split
stringclasses
1 value
category
stringclasses
2 values
content
stringlengths
5
482k
signature
stringlengths
1
14k
suffix
stringlengths
1
482k
prefix
stringlengths
9
14k
prefix_token_count
int64
3
5.01k
prefix_token_budget
int64
64
256
element_token_count
int64
1
292k
signature_token_count
int64
1
5.01k
prefix_context_token_count
int64
0
255
repo
stringlengths
7
112
path
stringlengths
4
208
language
stringclasses
1 value
name
stringlengths
1
218
qualname
stringlengths
1
218
start_line
int64
1
26.7k
end_line
int64
1
26.7k
signature_start_line
int64
1
26.7k
signature_end_line
int64
1
26.7k
source_hash
stringlengths
40
40
source_dataset
stringclasses
1 value
source_split
stringclasses
1 value
9019f6b7a7dbb0a7bd6f7c56
train
class
@ctx.action_class('code') class CodeActions: def toggle_comment(): actions.key('ctrl-q')
@ctx.action_class('code') class CodeActions:
def toggle_comment(): actions.key('ctrl-q')
user.tabs'] @ctx.action_class('app') class AppActions: def tab_previous(): actions.key('ctrl-pageup') def tab_next(): actions.key('ctrl-pagedown') def tab_open(): actions.key('ctrl-n') @ctx.action_class('code') class CodeActions:
64
64
23
11
53
tpensyl-bw/knausj_talon
apps/platforms/win/notepad++/notepad++.py
Python
CodeActions
CodeActions
31
34
31
32
2bd5d0aff8d70e47f7fe0ebac465a8d93de67d4f
bigcode/the-stack
train
4a0999e763bc662441e38479
train
class
@ctx.action_class('app') class AppActions: def tab_previous(): actions.key('ctrl-pageup') def tab_next(): actions.key('ctrl-pagedown') def tab_open(): actions.key('ctrl-n')
@ctx.action_class('app') class AppActions:
def tab_previous(): actions.key('ctrl-pageup') def tab_next(): actions.key('ctrl-pagedown') def tab_open(): actions.key('ctrl-n')
free (GPL) source code editor os: windows and app.exe: notepad++.exe """ ctx.matches = r""" app: notepad_plus_plus """ ctx.tags = ['user.find_and_replace', 'user.line_commands', 'user.tabs'] @ctx.action_class('app') class AppActions:
64
64
50
11
53
tpensyl-bw/knausj_talon
apps/platforms/win/notepad++/notepad++.py
Python
AppActions
AppActions
22
29
22
23
40cee6cbd05d2ff0bc7d11ff748e5467487b09e8
bigcode/the-stack
train
a3820d2d9b66458f8b91aef7
train
class
class Strategy(object): def __init__(self, launch_shape, strategy, fspaces, key_parts): if launch_shape is not None: self._launch_domain = Rect(hi=launch_shape) else: self._launch_domain = None self._strategy = strategy self._fspaces = fspaces self._ke...
class Strategy(object):
def __init__(self, launch_shape, strategy, fspaces, key_parts): if launch_shape is not None: self._launch_domain = Rect(hi=launch_shape) else: self._launch_domain = None self._strategy = strategy self._fspaces = fspaces self._key_parts = key_parts ...
return new def union(self, other): if self.empty: self._class_ids = other._class_ids.copy() self._classes = other._classes.copy() else: for other_class in other._classes.values(): cls = other_class.copy() var1 = cls.pop() ...
136
137
459
4
132
magnatelee/legate.core
legate/core/solver.py
Python
Strategy
Strategy
99
166
99
99
0294627dc180b6e590e55eda9406b7dfcfa2ad6c
bigcode/the-stack
train
312d98f535e85d73977e2505
train
class
class Partitioner(object): def __init__(self, runtime, ops, must_be_single=False): self._runtime = runtime self._ops = ops self._must_be_single = must_be_single def _solve_broadcast_constraints( self, unknowns, constraints, broadcasts, partitions ): to_remove = Order...
class Partitioner(object):
def __init__(self, runtime, ops, must_be_single=False): self._runtime = runtime self._ops = ops self._must_be_single = must_be_single def _solve_broadcast_constraints( self, unknowns, constraints, broadcasts, partitions ): to_remove = OrderedSet() for unknown...
def get_projection(self, part): partition = self.get_partition(part) return partition.get_requirement(self.launch_ndim, part.store) def get_partition(self, part): assert not part.store.unbound if part not in self._strategy: raise ValueError(f"No strategy is found for {p...
256
256
989
5
251
magnatelee/legate.core
legate/core/solver.py
Python
Partitioner
Partitioner
169
330
169
169
c215de7181792d747de8bf3a8e1889d827b7705a
bigcode/the-stack
train
0419b55f5d0fad26ccef33c4
train
class
class EqClass(object): def __init__(self): # Maps a variable to the equivalent class id self._class_ids = {} self._next_class_id = 0 # Maps an equivalent class id to the class self._classes = {} @property def empty(self): return self._next_class_id == 0 ...
class EqClass(object):
def __init__(self): # Maps a variable to the equivalent class id self._class_ids = {} self._next_class_id = 0 # Maps an equivalent class id to the class self._classes = {} @property def empty(self): return self._next_class_id == 0 def _add(self, var1, va...
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under th...
169
169
564
5
163
magnatelee/legate.core
legate/core/solver.py
Python
EqClass
EqClass
23
96
23
23
26108ef925ebfea12f1ea67f40440dc2b73c61ec
bigcode/the-stack
train
3c71b33efe8818db47b5627a
train
class
@register class MaskPostProcess(object): __shared__ = ['export_onnx'] """ refer to: https://github.com/facebookresearch/detectron2/layers/mask_ops.py Get Mask output according to the output from model """ def __init__(self, binary_thresh=0.5, export_onnx=False): super(MaskPostProce...
@register class MaskPostProcess(object):
__shared__ = ['export_onnx'] """ refer to: https://github.com/facebookresearch/detectron2/layers/mask_ops.py Get Mask output according to the output from model """ def __init__(self, binary_thresh=0.5, export_onnx=False): super(MaskPostProcess, self).__init__() self.binary_...
_list[:, 0] origin_w = self.origin_shape_list[:, 1] zeros = paddle.zeros_like(origin_h) # clip bbox to [0, original_size] x1 = paddle.maximum(paddle.minimum(scaled_bbox[:, 0], origin_w), zeros) y1 = paddle.maximum(paddle.minimum(scaled_bbox[:, 1], origin_h), zeros) x2 = p...
256
256
933
9
246
Amanda-Barbara/PaddleDetection
ppdet/modeling/post_process.py
Python
MaskPostProcess
MaskPostProcess
180
265
180
181
8f769789597ae2ff5e7e9a0fcb20970e274e9ace
bigcode/the-stack
train
58a5daec0266040ced22b178
train
class
@register class DETRBBoxPostProcess(object): __shared__ = ['num_classes', 'use_focal_loss'] __inject__ = [] def __init__(self, num_classes=80, num_top_queries=100, use_focal_loss=False): super(DETRBBoxPostProcess, self).__init__() self.num_...
@register class DETRBBoxPostProcess(object):
__shared__ = ['num_classes', 'use_focal_loss'] __inject__ = [] def __init__(self, num_classes=80, num_top_queries=100, use_focal_loss=False): super(DETRBBoxPostProcess, self).__init__() self.num_classes = num_classes self.num_top_qu...
padh x2 = x2 - padw y2 = y2 - padh bboxes = paddle.concat([x1, y1, x2, y2], axis=1) scale_y = scale_factor[:, 0:1] scale_x = scale_factor[:, 1:2] scale_expand = paddle.concat( [scale_x, scale_y, scale_x, scale_y], axis=1) boxes_shape = bboxes.shape[:...
197
197
658
11
185
Amanda-Barbara/PaddleDetection
ppdet/modeling/post_process.py
Python
DETRBBoxPostProcess
DETRBBoxPostProcess
555
624
555
556
0c9b5ce896475d2f7081468e158a3dd28cfbee5b
bigcode/the-stack
train
e08d2da8c96cc0339509feed
train
class
@register class SparsePostProcess(object): __shared__ = ['num_classes'] def __init__(self, num_proposals, num_classes=80): super(SparsePostProcess, self).__init__() self.num_classes = num_classes self.num_proposals = num_proposals def __call__(self, box_cls, box_pred, scale_factor_...
@register class SparsePostProcess(object):
__shared__ = ['num_classes'] def __init__(self, num_proposals, num_classes=80): super(SparsePostProcess, self).__init__() self.num_classes = num_classes self.num_proposals = num_proposals def __call__(self, box_cls, box_pred, scale_factor_wh, img_whwh): """ Argument...
: scores, index = paddle.topk( scores, self.num_top_queries, axis=-1) labels = paddle.stack( [paddle.gather(l, i) for l, i in zip(labels, index)]) bbox_pred = paddle.stack( [paddle.gather(b, i) for b, i in zip(bb...
256
256
858
9
246
Amanda-Barbara/PaddleDetection
ppdet/modeling/post_process.py
Python
SparsePostProcess
SparsePostProcess
627
711
627
628
b09b5ccb4f1d81b5d20f59059daeda8d9bfa0405
bigcode/the-stack
train
ff87dd309a19fd3537116f08
train
class
@register class FCOSPostProcess(object): __inject__ = ['decode', 'nms'] def __init__(self, decode=None, nms=None): super(FCOSPostProcess, self).__init__() self.decode = decode self.nms = nms def __call__(self, fcos_head_outs, scale_factor): """ Decode the bbox and d...
@register class FCOSPostProcess(object):
__inject__ = ['decode', 'nms'] def __init__(self, decode=None, nms=None): super(FCOSPostProcess, self).__init__() self.decode = decode self.nms = nms def __call__(self, fcos_head_outs, scale_factor): """ Decode the bbox and do NMS in FCOS. """ locati...
_mask = paddle.cast(pred_mask >= self.binary_thresh, 'int32') pred_result[id_start:id_start + bbox_num[i], :im_h, : im_w] = pred_mask id_start += bbox_num[i] return pred_result @register class FCOSPostProcess(ob...
64
64
165
10
53
Amanda-Barbara/PaddleDetection
ppdet/modeling/post_process.py
Python
FCOSPostProcess
FCOSPostProcess
268
285
268
269
9a432bfb1783b76fc5dd8a4cf5faf3475db0a267
bigcode/the-stack
train
70b7eff6866677567f927ba5
train
class
@register class JDEBBoxPostProcess(nn.Layer): __shared__ = ['num_classes'] __inject__ = ['decode', 'nms'] def __init__(self, num_classes=1, decode=None, nms=None, return_idx=True): super(JDEBBoxPostProcess, self).__init__() self.num_classes = num_classes self.decode = decode ...
@register class JDEBBoxPostProcess(nn.Layer):
__shared__ = ['num_classes'] __inject__ = ['decode', 'nms'] def __init__(self, num_classes=1, decode=None, nms=None, return_idx=True): super(JDEBBoxPostProcess, self).__init__() self.num_classes = num_classes self.decode = decode self.nms = nms self.return_idx = retu...
paddle.maximum(paddle.minimum(bboxes[:, 1], origin_h - 1), zeros) x2 = paddle.maximum(paddle.minimum(bboxes[:, 2], origin_w - 1), zeros) y2 = paddle.maximum(paddle.minimum(bboxes[:, 3], origin_h - 1), zeros) x3 = paddle.maximum(paddle.minimum(bboxes[:, 4], origin_w - 1), zeros) y3 = pad...
227
227
758
12
214
Amanda-Barbara/PaddleDetection
ppdet/modeling/post_process.py
Python
JDEBBoxPostProcess
JDEBBoxPostProcess
391
463
391
392
18eb92af6e464898a88ee8b6b56eca4acf438d4f
bigcode/the-stack
train
0bb058be9909c404547564a4
train
class
@register class CenterNetPostProcess(TTFBox): """ Postprocess the model outputs to get final prediction: 1. Do NMS for heatmap to get top `max_per_img` bboxes. 2. Decode bboxes using center offset and box size. 3. Rescale decoded bboxes reference to the origin image shape. Args: ...
@register class CenterNetPostProcess(TTFBox):
""" Postprocess the model outputs to get final prediction: 1. Do NMS for heatmap to get top `max_per_img` bboxes. 2. Decode bboxes using center offset and box size. 3. Rescale decoded bboxes reference to the origin image shape. Args: max_per_img(int): the maximum number of p...
only support bs=1 now yolo_boxes_out = paddle.reshape( yolo_boxes[:, :4], shape=[1, len(boxes_idx), 4]) yolo_scores_out = paddle.reshape( yolo_boxes[:, 4:5], shape=[1, 1, len(boxes_idx)]) boxes_idx = boxes_idx[:, 1:] if self.return_idx: ...
255
256
948
12
243
Amanda-Barbara/PaddleDetection
ppdet/modeling/post_process.py
Python
CenterNetPostProcess
CenterNetPostProcess
466
552
466
467
70dc7c8d67c614adc4d0eab96e0730c74029b513
bigcode/the-stack
train
000ec908411ddd1d6341a84f
train
class
@register class S2ANetBBoxPostProcess(nn.Layer): __shared__ = ['num_classes'] __inject__ = ['nms'] def __init__(self, num_classes=15, nms_pre=2000, min_bbox_size=0, nms=None): super(S2ANetBBoxPostProcess, self).__init__() self.num_classes = num_classes self.nms_pre = nms_pre ...
@register class S2ANetBBoxPostProcess(nn.Layer):
__shared__ = ['num_classes'] __inject__ = ['nms'] def __init__(self, num_classes=15, nms_pre=2000, min_bbox_size=0, nms=None): super(S2ANetBBoxPostProcess, self).__init__() self.num_classes = num_classes self.nms_pre = nms_pre self.min_bbox_size = min_bbox_size self....
_i[:, None, :, :], bboxes_i[:, 2:], im_h, im_w) pred_mask = paddle.cast(pred_mask >= self.binary_thresh, 'int32') pred_result[id_start:id_start + bbox_num[i], :im_h, : im_w] = ...
256
256
1,178
14
241
Amanda-Barbara/PaddleDetection
ppdet/modeling/post_process.py
Python
S2ANetBBoxPostProcess
S2ANetBBoxPostProcess
288
388
288
289
faa61441195f819324c12376d6461556e83b9f6d
bigcode/the-stack
train
64374a46e779acc0d2bd2a99
train
function
def nms(dets, thresh): """Apply classic DPM-style greedy NMS.""" if dets.shape[0] == 0: return dets[[], :] scores = dets[:, 0] x1 = dets[:, 1] y1 = dets[:, 2] x2 = dets[:, 3] y2 = dets[:, 4] areas = (x2 - x1 + 1) * (y2 - y1 + 1) order = scores.argsort()[::-1] ndets = de...
def nms(dets, thresh):
"""Apply classic DPM-style greedy NMS.""" if dets.shape[0] == 0: return dets[[], :] scores = dets[:, 0] x1 = dets[:, 1] y1 = dets[:, 2] x2 = dets[:, 3] y2 = dets[:, 4] areas = (x2 - x1 + 1) * (y2 - y1 + 1) order = scores.argsort()[::-1] ndets = dets.shape[0] suppres...
0): bboxes = paddle.zeros([1, 6]).astype("float32") else: boxes = paddle.to_tensor(boxes.numpy()[keep]).astype("float32") classes = paddle.to_tensor(classes.numpy()[keep]).astype( "float32").unsqueeze(-1) scores = paddle.to...
148
148
495
8
139
Amanda-Barbara/PaddleDetection
ppdet/modeling/post_process.py
Python
nms
nms
714
767
714
714
584844a80b46c7a5b65d967ccf6b27428136b40f
bigcode/the-stack
train
aef7db4a8236096ddbace006
train
class
@register class BBoxPostProcess(object): __shared__ = ['num_classes', 'export_onnx'] __inject__ = ['decode', 'nms'] def __init__(self, num_classes=80, decode=None, nms=None, export_onnx=False): super(BBoxPostProcess, self).__init__() self.num_classes = num_classes s...
@register class BBoxPostProcess(object):
__shared__ = ['num_classes', 'export_onnx'] __inject__ = ['decode', 'nms'] def __init__(self, num_classes=80, decode=None, nms=None, export_onnx=False): super(BBoxPostProcess, self).__init__() self.num_classes = num_classes self.decode = decode self.nms = nm...
file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY ...
256
256
1,480
10
246
Amanda-Barbara/PaddleDetection
ppdet/modeling/post_process.py
Python
BBoxPostProcess
BBoxPostProcess
35
177
35
36
51c9b2949c35a976f5935133220db391757c70d9
bigcode/the-stack
train
fce97eb2559fe2901ce597c9
train
function
def tree(height=30, screen_width=200): star = (STAR, 3*STAR) if height % 2 != 0: height += 1 body = ['/_\\', '/_\_\\'] trunk = '[___]' begin = '/' end = '\\' pattern = '_/' j = 5 for i in range(7, height + 1, 2): middle = pattern + (i - j) * pattern line = ''....
def tree(height=30, screen_width=200):
star = (STAR, 3*STAR) if height % 2 != 0: height += 1 body = ['/_\\', '/_\_\\'] trunk = '[___]' begin = '/' end = '\\' pattern = '_/' j = 5 for i in range(7, height + 1, 2): middle = pattern + (i - j) * pattern line = ''.join([begin, middle[:-1], end]) ...
(range(0, len(string)), value) string = list(string) for idx in indexes: if string[idx] != ' ' and string[idx] == '_': string[idx] = random.choice(BALLS) return ''.join(string) def tree(height=30, screen_width=200):
64
64
176
11
53
Wyzzus/terminal-christmas-tree
terminal_tree.py
Python
tree
tree
28
47
28
28
edf675c4288e6c1a562581791f07b7ccdeb292bf
bigcode/the-stack
train
d931bb5c96a8a9220e7f4d6c
train
function
def balls(tree): for idx, _ in enumerate(tree[:-3], 2): tree[idx] = random_change_char(tree[idx], len(tree[idx])//8) return tree
def balls(tree):
for idx, _ in enumerate(tree[:-3], 2): tree[idx] = random_change_char(tree[idx], len(tree[idx])//8) return tree
end]) body.append(line) middle = middle.replace('/', '\\') line = ''.join([begin, middle[:-1], end]) body.append(line) j += 1 return [line.center(screen_width) for line in (*star, *body, trunk)] def balls(tree):
63
64
40
4
59
Wyzzus/terminal-christmas-tree
terminal_tree.py
Python
balls
balls
50
53
50
50
bac196e044749b03b1b3b101962cf4e15647bbae
bigcode/the-stack
train
26379da3df0ddebff15a83cd
train
function
def random_change_char(string, value): indexes = random.sample(range(0, len(string)), value) string = list(string) for idx in indexes: if string[idx] != ' ' and string[idx] == '_': string[idx] = random.choice(BALLS) return ''.join(string)
def random_change_char(string, value):
indexes = random.sample(range(0, len(string)), value) string = list(string) for idx in indexes: if string[idx] != ' ' and string[idx] == '_': string[idx] = random.choice(BALLS) return ''.join(string)
cyan': '\033[96m', 'green': '\033[92m', 'magenta': '\033[95m', 'white': '\033[97m', 'red': '\033[91m' } STAR = '🌟' def random_change_char(string, value):
64
64
66
8
56
Wyzzus/terminal-christmas-tree
terminal_tree.py
Python
random_change_char
random_change_char
19
25
19
19
e5da8b57915d3f4739fc65e17040177c7024595c
bigcode/the-stack
train
e89df7f661ff43206275cc84
train
function
def cli(): parser = argparse.ArgumentParser(prog="Python Christmas Tree by Chico Lucio from Ciencia Programada", epilog="Ctrl-C interrupts the Christmas :-(") parser.add_argument('-s', '--size', default=13, type=int, help="Tree height. If even it will...
def cli():
parser = argparse.ArgumentParser(prog="Python Christmas Tree by Chico Lucio from Ciencia Programada", epilog="Ctrl-C interrupts the Christmas :-(") parser.add_argument('-s', '--size', default=13, type=int, help="Tree height. If even it will be subtrac...
(string): random_ball = random.choice(BALLS) if string[pos] == STAR: string[pos] = ''.join([COLOR['yellow'], STAR, '\033[0m']) elif string[pos] == random_ball: string[pos] = ''.join([random.choice(list(COLOR.values())), random_ball, '\033[0m']) ...
90
90
301
3
86
Wyzzus/terminal-christmas-tree
terminal_tree.py
Python
cli
cli
69
94
69
69
e7d661790aafcab2e375bb858a4a21712f4ff547
bigcode/the-stack
train
c5db04c225ac11c8b63fbd0d
train
function
def colored_stars_balls(tree): for idx, _ in enumerate(tree): string = list(tree[idx]) for pos, _ in enumerate(string): random_ball = random.choice(BALLS) if string[pos] == STAR: string[pos] = ''.join([COLOR['yellow'], STAR, '\033[0m']) elif string...
def colored_stars_balls(tree):
for idx, _ in enumerate(tree): string = list(tree[idx]) for pos, _ in enumerate(string): random_ball = random.choice(BALLS) if string[pos] == STAR: string[pos] = ''.join([COLOR['yellow'], STAR, '\033[0m']) elif string[pos] == random_ball: ...
.center(screen_width) for line in (*star, *body, trunk)] def balls(tree): for idx, _ in enumerate(tree[:-3], 2): tree[idx] = random_change_char(tree[idx], len(tree[idx])//8) return tree def colored_stars_balls(tree):
64
64
118
8
55
Wyzzus/terminal-christmas-tree
terminal_tree.py
Python
colored_stars_balls
colored_stars_balls
56
66
56
56
de80fe99938de453715829affb4184591775efa3
bigcode/the-stack
train
12a65c095bf6831653b64673
train
class
class TestCompression(unittest.TestCase): def setUp(self): rospy.init_node("test_compression") def test_compress(self): bytes = list(range(128)) * 10000 string = str(bytearray(bytes)) encoded = pngcompression.encode(string) self.assertNotEqual(string, encoded) def ...
class TestCompression(unittest.TestCase):
def setUp(self): rospy.init_node("test_compression") def test_compress(self): bytes = list(range(128)) * 10000 string = str(bytearray(bytes)) encoded = pngcompression.encode(string) self.assertNotEqual(string, encoded) def test_compress_decompress(self): byt...
#!/usr/bin/env python import sys import rospy import rostest import unittest from rosbridge_library.internal import pngcompression class TestCompression(unittest.TestCase):
35
64
130
7
27
abiantorres/autonomous-vehicles-system-simulation
low_level_simulation/src/rosbridge_suite/rosbridge_library/test/internal/test_compression.py
Python
TestCompression
TestCompression
10
27
10
11
f2612f038880a1b6fc9caea7fac979f2637b1f82
bigcode/the-stack
train
4b64b4634ae6827a94a60db6
train
class
class Engine(object): """Engine that runs training and inference. Args - cur_epoch (int): Current epoch. - print_every (int): How frequently (# batches) to print loss. - validate_every (int): How frequently (# epochs) to run validation. """ def __init__(self, cur_epoch=0, print_every=1, validate_every=1)...
class Engine(object):
"""Engine that runs training and inference. Args - cur_epoch (int): Current epoch. - print_every (int): How frequently (# batches) to print loss. - validate_every (int): How frequently (# epochs) to run validation. """ def __init__(self, cur_epoch=0, print_every=1, validate_every=1): self.cur_epoch = c...
= args.categories, \ download = True, high = 128, low = 32, split=.97, voxels = False) dataloader_train = DataLoader(train_set, batch_size=args.batchsize, shuffle=True, \ num_workers=8) valid_set = ShapeNet_ODMS(root ='../../datasets/',categories = args.categories, \ download = True, train = False, high = 128, lo...
254
256
1,266
4
250
Bob-Yeah/kaolin
examples/SuperResolution/ODM-ShapeNet/train_Direct.py
Python
Engine
Engine
78
211
78
78
534c4a7afb3ff3e4ddf9024f50847a79b9eef306
bigcode/the-stack
train
58b3e2a741473071209378e8
train
class
class ResourceViewSet(viewsets.ModelViewSet): queryset = models.Resource.objects.all() serializer_class = basic_serializers.ResourceSerializer filter_backends = [django_filters.DjangoFilterBackend, drf_filters.OrderingFilter] filterset_class = filters.ResourceFilterSet ordering_fields = ["created_at...
class ResourceViewSet(viewsets.ModelViewSet):
queryset = models.Resource.objects.all() serializer_class = basic_serializers.ResourceSerializer filter_backends = [django_filters.DjangoFilterBackend, drf_filters.OrderingFilter] filterset_class = filters.ResourceFilterSet ordering_fields = ["created_at"] ordering = ["created_at"]
"""Try to assign a owner to the new source.""" source = serializer.save() # To give the source a owner, the request must be authenticated if not self.request.user.is_anonymous: source.users.add(self.request.user) source.save() class ResourceViewSet(viewsets.ModelViewSe...
64
64
73
10
54
arkhn/fhir-river
django/pyrog/api/views.py
Python
ResourceViewSet
ResourceViewSet
56
62
56
56
b66dc346d4bb2b2640250bb81213c3d02a60af62
bigcode/the-stack
train
c4fbdafbfe7bd6a307d173c4
train
class
class SourceViewSet(viewsets.ModelViewSet): queryset = models.Source.objects.all() serializer_class = basic_serializers.SourceSerializer filter_backends = [drf_filters.OrderingFilter] ordering_fields = ["created_at"] ordering = ["created_at"] @action(detail=False, methods=["post"], serializer_c...
class SourceViewSet(viewsets.ModelViewSet):
queryset = models.Source.objects.all() serializer_class = basic_serializers.SourceSerializer filter_backends = [drf_filters.OrderingFilter] ordering_fields = ["created_at"] ordering = ["created_at"] @action(detail=False, methods=["post"], serializer_class=MappingSerializer, url_path="import") ...
get_request_headers() headers["Cache-Control"] = "no-cache" try: token = self.request.session["oidc_access_token"] headers["Authorization"] = f"Bearer {token}" except KeyError: pass return headers class SourceViewSet(viewsets.ModelViewSet):
64
64
195
10
53
arkhn/fhir-river
django/pyrog/api/views.py
Python
SourceViewSet
SourceViewSet
30
53
30
30
5658a617c8f139dc5fba75f5f39811d90a4c943f
bigcode/the-stack
train
9ee4c5bdff850e619cf84287
train
class
class StaticInputViewSet(viewsets.ModelViewSet): queryset = models.StaticInput.objects.all() serializer_class = basic_serializers.StaticInputSerializer filter_backends = [django_filters.DjangoFilterBackend, drf_filters.OrderingFilter] filterset_class = filters.StaticInputFilterSet ordering_fields = ...
class StaticInputViewSet(viewsets.ModelViewSet):
queryset = models.StaticInput.objects.all() serializer_class = basic_serializers.StaticInputSerializer filter_backends = [django_filters.DjangoFilterBackend, drf_filters.OrderingFilter] filterset_class = filters.StaticInputFilterSet ordering_fields = ["created_at"] ordering = ["created_at"]
_serializers.InputGroupSerializer filter_backends = [django_filters.DjangoFilterBackend, drf_filters.OrderingFilter] filterset_class = filters.InputGroupFilterSet ordering_fields = ["created_at"] ordering = ["created_at"] class StaticInputViewSet(viewsets.ModelViewSet):
63
64
77
11
52
arkhn/fhir-river
django/pyrog/api/views.py
Python
StaticInputViewSet
StaticInputViewSet
92
98
92
92
c96e4bb7ae0f178e40d1a43ba764cd1144b7b26b
bigcode/the-stack
train
481c0176cf83a3ecd1005e75
train
class
class FhirProxyView(ProxyView): upstream = settings.FHIR_API_URL def get_request_headers(self): headers = super().get_request_headers() headers["Cache-Control"] = "no-cache" try: token = self.request.session["oidc_access_token"] headers["Authorization"] = f"Beare...
class FhirProxyView(ProxyView):
upstream = settings.FHIR_API_URL def get_request_headers(self): headers = super().get_request_headers() headers["Cache-Control"] = "no-cache" try: token = self.request.session["oidc_access_token"] headers["Authorization"] = f"Bearer {token}" except KeyErr...
as django_filters from pyrog import models from pyrog.api import filters from pyrog.api.serializers import basic as basic_serializers from pyrog.api.serializers.mapping import MappingSerializer, MappingWithPartialCredentialSerializer from revproxy.views import ProxyView class FhirProxyView(ProxyView):
64
64
84
9
54
arkhn/fhir-river
django/pyrog/api/views.py
Python
FhirProxyView
FhirProxyView
16
27
16
16
6c14379458b8ffa6c39570946c86698cf6020a55
bigcode/the-stack
train
8428de9b34d93e2ecd0d696a
train
class
class OwnerViewSet(viewsets.ModelViewSet): queryset = models.Owner.objects.all() serializer_class = basic_serializers.OwnerSerializer filter_backends = [django_filters.DjangoFilterBackend] filterset_class = filters.OwnerFilterSet def destroy(self, request, *args, **kwargs): try: ...
class OwnerViewSet(viewsets.ModelViewSet):
queryset = models.Owner.objects.all() serializer_class = basic_serializers.OwnerSerializer filter_backends = [django_filters.DjangoFilterBackend] filterset_class = filters.OwnerFilterSet def destroy(self, request, *args, **kwargs): try: return super().destroy(request, *args, **k...
FilterSet class FilterViewSet(viewsets.ModelViewSet): queryset = models.Filter.objects.all() serializer_class = basic_serializers.FilterSerializer filter_backends = [django_filters.DjangoFilterBackend] filterset_class = filters.FilterFilterSet class OwnerViewSet(viewsets.ModelViewSet):
64
64
102
10
53
arkhn/fhir-river
django/pyrog/api/views.py
Python
OwnerViewSet
OwnerViewSet
142
152
142
142
b09cb1c6273deb1adefd619013a1bf752a1f95b1
bigcode/the-stack
train
d13ab095f38d607f702f3eee
train
class
class AttributeViewSet(viewsets.ModelViewSet): queryset = models.Attribute.objects.all() serializer_class = basic_serializers.AttributeSerializer filter_backends = [django_filters.DjangoFilterBackend, drf_filters.OrderingFilter] filterset_class = filters.AttributeFilterSet ordering_fields = ["create...
class AttributeViewSet(viewsets.ModelViewSet):
queryset = models.Attribute.objects.all() serializer_class = basic_serializers.AttributeSerializer filter_backends = [django_filters.DjangoFilterBackend, drf_filters.OrderingFilter] filterset_class = filters.AttributeFilterSet ordering_fields = ["created_at"] ordering = ["created_at"]
izers.CredentialSerializer filter_backends = [django_filters.DjangoFilterBackend, drf_filters.OrderingFilter] filterset_class = filters.CredentialFilterSet ordering_fields = ["created_at"] ordering = ["created_at"] class AttributeViewSet(viewsets.ModelViewSet):
63
64
73
10
53
arkhn/fhir-river
django/pyrog/api/views.py
Python
AttributeViewSet
AttributeViewSet
74
80
74
74
bcdbe6f57a90d00b44b955608d180e092e8355ef
bigcode/the-stack
train
26c7ce7377c5033716b67779
train
class
class CredentialViewSet(viewsets.ModelViewSet): queryset = models.Credential.objects.all() serializer_class = basic_serializers.CredentialSerializer filter_backends = [django_filters.DjangoFilterBackend, drf_filters.OrderingFilter] filterset_class = filters.CredentialFilterSet ordering_fields = ["cr...
class CredentialViewSet(viewsets.ModelViewSet):
queryset = models.Credential.objects.all() serializer_class = basic_serializers.CredentialSerializer filter_backends = [django_filters.DjangoFilterBackend, drf_filters.OrderingFilter] filterset_class = filters.CredentialFilterSet ordering_fields = ["created_at"] ordering = ["created_at"]
_class = basic_serializers.ResourceSerializer filter_backends = [django_filters.DjangoFilterBackend, drf_filters.OrderingFilter] filterset_class = filters.ResourceFilterSet ordering_fields = ["created_at"] ordering = ["created_at"] class CredentialViewSet(viewsets.ModelViewSet):
63
64
79
10
53
arkhn/fhir-river
django/pyrog/api/views.py
Python
CredentialViewSet
CredentialViewSet
65
71
65
65
4f852bba4c72944c8c50524560079ea2ad5b7e7b
bigcode/the-stack
train
21c6b34672019d99bdc96112
train
class
class FilterViewSet(viewsets.ModelViewSet): queryset = models.Filter.objects.all() serializer_class = basic_serializers.FilterSerializer filter_backends = [django_filters.DjangoFilterBackend] filterset_class = filters.FilterFilterSet
class FilterViewSet(viewsets.ModelViewSet):
queryset = models.Filter.objects.all() serializer_class = basic_serializers.FilterSerializer filter_backends = [django_filters.DjangoFilterBackend] filterset_class = filters.FilterFilterSet
_at"] class ConditionViewSet(viewsets.ModelViewSet): queryset = models.Condition.objects.all() serializer_class = basic_serializers.ConditionSerializer filter_backends = [django_filters.DjangoFilterBackend] filterset_class = filters.ConditionFilterSet class FilterViewSet(viewsets.ModelViewSet):
64
64
51
10
53
arkhn/fhir-river
django/pyrog/api/views.py
Python
FilterViewSet
FilterViewSet
135
139
135
135
d07dbc13a3368f1909f0cf9442cdc0c2fe2ece5a
bigcode/the-stack
train
bf2b3823b10bcee223a8bcb3
train
class
class SQLInputViewSet(viewsets.ModelViewSet): queryset = models.SQLInput.objects.all() serializer_class = basic_serializers.SQLInputSerializer filter_backends = [django_filters.DjangoFilterBackend, drf_filters.OrderingFilter] filterset_class = filters.SQLInputFilterSet ordering_fields = ["created_at...
class SQLInputViewSet(viewsets.ModelViewSet):
queryset = models.SQLInput.objects.all() serializer_class = basic_serializers.SQLInputSerializer filter_backends = [django_filters.DjangoFilterBackend, drf_filters.OrderingFilter] filterset_class = filters.SQLInputFilterSet ordering_fields = ["created_at"] ordering = ["created_at"]
_serializers.StaticInputSerializer filter_backends = [django_filters.DjangoFilterBackend, drf_filters.OrderingFilter] filterset_class = filters.StaticInputFilterSet ordering_fields = ["created_at"] ordering = ["created_at"] class SQLInputViewSet(viewsets.ModelViewSet):
63
64
77
11
52
arkhn/fhir-river
django/pyrog/api/views.py
Python
SQLInputViewSet
SQLInputViewSet
101
107
101
101
f74651dc7861b6d7c52569aa2d6d830f669ea628
bigcode/the-stack
train
4dbbee1afa3f3f98799c539c
train
class
class InputGroupViewSet(viewsets.ModelViewSet): queryset = models.InputGroup.objects.all() serializer_class = basic_serializers.InputGroupSerializer filter_backends = [django_filters.DjangoFilterBackend, drf_filters.OrderingFilter] filterset_class = filters.InputGroupFilterSet ordering_fields = ["cr...
class InputGroupViewSet(viewsets.ModelViewSet):
queryset = models.InputGroup.objects.all() serializer_class = basic_serializers.InputGroupSerializer filter_backends = [django_filters.DjangoFilterBackend, drf_filters.OrderingFilter] filterset_class = filters.InputGroupFilterSet ordering_fields = ["created_at"] ordering = ["created_at"]
= basic_serializers.AttributeSerializer filter_backends = [django_filters.DjangoFilterBackend, drf_filters.OrderingFilter] filterset_class = filters.AttributeFilterSet ordering_fields = ["created_at"] ordering = ["created_at"] class InputGroupViewSet(viewsets.ModelViewSet):
63
64
77
11
52
arkhn/fhir-river
django/pyrog/api/views.py
Python
InputGroupViewSet
InputGroupViewSet
83
89
83
83
2abce9ecde9c9d01bbe9266f91d40ed50acc4ec5
bigcode/the-stack
train
55364addd0979e54441901d8
train
class
class ConditionViewSet(viewsets.ModelViewSet): queryset = models.Condition.objects.all() serializer_class = basic_serializers.ConditionSerializer filter_backends = [django_filters.DjangoFilterBackend] filterset_class = filters.ConditionFilterSet
class ConditionViewSet(viewsets.ModelViewSet):
queryset = models.Condition.objects.all() serializer_class = basic_serializers.ConditionSerializer filter_backends = [django_filters.DjangoFilterBackend] filterset_class = filters.ConditionFilterSet
_class = basic_serializers.JoinSerializer filter_backends = [django_filters.DjangoFilterBackend, drf_filters.OrderingFilter] filterset_class = filters.JoinFilterSet ordering_fields = ["created_at"] ordering = ["created_at"] class ConditionViewSet(viewsets.ModelViewSet):
63
64
51
10
53
arkhn/fhir-river
django/pyrog/api/views.py
Python
ConditionViewSet
ConditionViewSet
128
132
128
128
2f1297f89e40c6cadcbda478f2e1be2c0a38c406
bigcode/the-stack
train
2cea7acc04524f539d113c8e
train
class
class JoinViewSet(viewsets.ModelViewSet): queryset = models.Join.objects.all() serializer_class = basic_serializers.JoinSerializer filter_backends = [django_filters.DjangoFilterBackend, drf_filters.OrderingFilter] filterset_class = filters.JoinFilterSet ordering_fields = ["created_at"] ordering ...
class JoinViewSet(viewsets.ModelViewSet):
queryset = models.Join.objects.all() serializer_class = basic_serializers.JoinSerializer filter_backends = [django_filters.DjangoFilterBackend, drf_filters.OrderingFilter] filterset_class = filters.JoinFilterSet ordering_fields = ["created_at"] ordering = ["created_at"]
_class = basic_serializers.ColumnSerializer filter_backends = [django_filters.DjangoFilterBackend, drf_filters.OrderingFilter] filterset_class = filters.ColumnFilterSet ordering_fields = ["created_at"] ordering = ["created_at"] class JoinViewSet(viewsets.ModelViewSet):
63
64
73
10
53
arkhn/fhir-river
django/pyrog/api/views.py
Python
JoinViewSet
JoinViewSet
119
125
119
119
5a226ee3b44687779f3a8135b588f11bd1ffc9e6
bigcode/the-stack
train
786e461812c4b5e742f3b394
train
class
class ColumnViewSet(viewsets.ModelViewSet): queryset = models.Column.objects.all() serializer_class = basic_serializers.ColumnSerializer filter_backends = [django_filters.DjangoFilterBackend, drf_filters.OrderingFilter] filterset_class = filters.ColumnFilterSet ordering_fields = ["created_at"] o...
class ColumnViewSet(viewsets.ModelViewSet):
queryset = models.Column.objects.all() serializer_class = basic_serializers.ColumnSerializer filter_backends = [django_filters.DjangoFilterBackend, drf_filters.OrderingFilter] filterset_class = filters.ColumnFilterSet ordering_fields = ["created_at"] ordering = ["created_at"]
basic_serializers.SQLInputSerializer filter_backends = [django_filters.DjangoFilterBackend, drf_filters.OrderingFilter] filterset_class = filters.SQLInputFilterSet ordering_fields = ["created_at"] ordering = ["created_at"] class ColumnViewSet(viewsets.ModelViewSet):
63
64
73
10
53
arkhn/fhir-river
django/pyrog/api/views.py
Python
ColumnViewSet
ColumnViewSet
110
116
110
110
45ef2c31918b612c9fe9931821528874de30afe5
bigcode/the-stack
train
f595b609882e6dadb248ce5d
train
function
def test_motion(magnitudelimit=10): sky = LSPM.from_sky(magnitudelimit=magnitudelimit) sky.animate(os.path.join(directory, f'example-{label}-animation.mp4'), epochs=[0,10000], dt=500)
def test_motion(magnitudelimit=10):
sky = LSPM.from_sky(magnitudelimit=magnitudelimit) sky.animate(os.path.join(directory, f'example-{label}-animation.mp4'), epochs=[0,10000], dt=500)
_sky(magnitudelimit=10): sky = LSPM.from_sky(magnitudelimit=magnitudelimit) sky.allskyfinder() plt.savefig(os.path.join(directory,f'example-{label}-allsky.pdf')) def test_motion(magnitudelimit=10):
64
64
60
11
53
zkbt/the-friendly-stars
tests/test_constellations/test_lspm.py
Python
test_motion
test_motion
22
24
22
22
cb15541c12a0c88d194ff5963e5ae1345a22eb7f
bigcode/the-stack
train
996513af3914ea4c74173336
train
function
def test_cone(): cone = LSPM.from_cone('GJ1214', radius=1*u.deg) cone.finder() plt.savefig(os.path.join(directory, f'example-{label}-cone.pdf'))
def test_cone():
cone = LSPM.from_cone('GJ1214', radius=1*u.deg) cone.finder() plt.savefig(os.path.join(directory, f'example-{label}-cone.pdf'))
''' Test basic constellation abilities. ''' from thefriendlystars.imports import * from thefriendlystars.constellations import * label = 'lspm' directory = 'examples' mkdir(directory) def test_cone():
44
64
49
5
39
zkbt/the-friendly-stars
tests/test_constellations/test_lspm.py
Python
test_cone
test_cone
12
15
12
12
a73289df6817a77c3a15fb4886bad50d2dca1718
bigcode/the-stack
train
a303b70c609275a59c24ccd3
train
function
def test_sky(magnitudelimit=10): sky = LSPM.from_sky(magnitudelimit=magnitudelimit) sky.allskyfinder() plt.savefig(os.path.join(directory,f'example-{label}-allsky.pdf'))
def test_sky(magnitudelimit=10):
sky = LSPM.from_sky(magnitudelimit=magnitudelimit) sky.allskyfinder() plt.savefig(os.path.join(directory,f'example-{label}-allsky.pdf'))
mkdir(directory) def test_cone(): cone = LSPM.from_cone('GJ1214', radius=1*u.deg) cone.finder() plt.savefig(os.path.join(directory, f'example-{label}-cone.pdf')) def test_sky(magnitudelimit=10):
64
64
55
12
52
zkbt/the-friendly-stars
tests/test_constellations/test_lspm.py
Python
test_sky
test_sky
17
20
17
17
b9e8b8375c2402f444b5bfbd7ae31d45cde49270
bigcode/the-stack
train
94c040898b4fad2bf40eaeec
train
class
class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Category', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ...
class Migration(migrations.Migration):
initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Category', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100...
# -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2017-02-11 19:00 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):
61
112
376
7
53
marcionreis/djangoecommerce
catalog/migrations/0001_initial.py
Python
Migration
Migration
9
50
9
10
ab17fb0a1bab53d560c59c3de74ab371f7a12528
bigcode/the-stack
train
a3efd1aec691f36030fbf501
train
function
def train_ANN(data, log_path): """ """ X, y = data enc = OneHotEncoder() y = enc.fit_transform(y.reshape(-1, 1)).toarray() model = ANN([4, 4, 2], log_path) model.fit(X, y) return model
def train_ANN(data, log_path):
""" """ X, y = data enc = OneHotEncoder() y = enc.fit_transform(y.reshape(-1, 1)).toarray() model = ANN([4, 4, 2], log_path) model.fit(X, y) return model
0, 0.5], colors=["gray"], alpha=0.4) return ax def train_logit(data): """ """ X, y = data model = LogisticRegression() model.fit(X, y) return model def train_ANN(data, log_path):
64
64
71
9
54
skforest/intro_ds
ch12-ann/classification_example.py
Python
train_ANN
train_ANN
71
79
71
71
032b3ab1cfe21b950357e74c0784869bf9643599
bigcode/the-stack
train
2a7ef375b5c69263454b5a06
train
function
def train_logit(data): """ """ X, y = data model = LogisticRegression() model.fit(X, y) return model
def train_logit(data):
""" """ X, y = data model = LogisticRegression() model.fit(X, y) return model
.ravel(), X2.ravel()])[:, 1] Y = Y.reshape(X1.shape) ax.contourf(X1, X2, Y, levels=[0, 0.5], colors=["gray"], alpha=0.4) return ax def train_logit(data):
64
64
34
6
57
skforest/intro_ds
ch12-ann/classification_example.py
Python
train_logit
train_logit
62
68
62
62
5b0a0591a46826b32825715b371f7b7a796c0c2e
bigcode/the-stack
train
a5ae2aa65eeeb9cf13e8a0aa
train
function
def visualize(data): """ """ # 创建一个图形框 fig = plt.figure(figsize=(10, 10), dpi=80) fig1 = plt.figure(figsize=(10, 10), dpi=80) # 在图形框里画四幅图 for i in range(len(data)): ax = fig.add_subplot(2, 2, i+1) ax1 = fig1.add_subplot(2, 2, i+1) draw_data(ax, data[i]) # Wind...
def visualize(data):
""" """ # 创建一个图形框 fig = plt.figure(figsize=(10, 10), dpi=80) fig1 = plt.figure(figsize=(10, 10), dpi=80) # 在图形框里画四幅图 for i in range(len(data)): ax = fig.add_subplot(2, 2, i+1) ax1 = fig1.add_subplot(2, 2, i+1) draw_data(ax, data[i]) # Windows下的存储路径与Linux并不相同 ...
def train_ANN(data, log_path): """ """ X, y = data enc = OneHotEncoder() y = enc.fit_transform(y.reshape(-1, 1)).toarray() model = ANN([4, 4, 2], log_path) model.fit(X, y) return model def visualize(data):
75
75
253
4
70
skforest/intro_ds
ch12-ann/classification_example.py
Python
visualize
visualize
82
104
82
82
c0ea20507eb54b24449ca11ed72b46e9ba138a01
bigcode/the-stack
train
a2378357146a53f10f89ef3b
train
function
def draw_data(ax, data): """ 将数据可视化 """ X, y = data label1 = X[y > 0] ax.scatter(label1[:, 0], label1[:, 1], marker="o") label0 = X[y == 0] ax.scatter(label0[:, 0], label0[:, 1], marker="^", color="k") return ax
def draw_data(ax, data):
""" 将数据可视化 """ X, y = data label1 = X[y > 0] ax.scatter(label1[:, 0], label1[:, 1], marker="o") label0 = X[y == 0] ax.scatter(label0[:, 0], label0[:, 1], marker="^", color="k") return ax
aler.fit_transform(circles[0]), circles[1]) moons = (scaler.fit_transform(moons[0]), moons[1]) blocks = (scaler.fit_transform(blocks[0]), blocks[1]) return blobs, circles, moons, blocks def draw_data(ax, data):
64
64
91
7
56
skforest/intro_ds
ch12-ann/classification_example.py
Python
draw_data
draw_data
37
46
37
37
e40438234c9acdbca527a7ea8e0481b0db019494
bigcode/the-stack
train
27c5a71cce34328e2de9d36f
train
function
def draw_model(ax, model): """ 将模型的分离超平面可视化 """ x1 = np.linspace(ax.get_xlim()[0], ax.get_xlim()[1], 100) x2 = np.linspace(ax.get_ylim()[0], ax.get_ylim()[1], 100) X1, X2 = np.meshgrid(x1, x2) Y = model.predict_proba(np.c_[X1.ravel(), X2.ravel()])[:, 1] Y = Y.reshape(X1.shape) ax.con...
def draw_model(ax, model):
""" 将模型的分离超平面可视化 """ x1 = np.linspace(ax.get_xlim()[0], ax.get_xlim()[1], 100) x2 = np.linspace(ax.get_ylim()[0], ax.get_ylim()[1], 100) X1, X2 = np.meshgrid(x1, x2) Y = model.predict_proba(np.c_[X1.ravel(), X2.ravel()])[:, 1] Y = Y.reshape(X1.shape) ax.contourf(X1, X2, Y, levels=[0,...
] ax.scatter(label1[:, 0], label1[:, 1], marker="o") label0 = X[y == 0] ax.scatter(label0[:, 0], label0[:, 1], marker="^", color="k") return ax def draw_model(ax, model):
64
64
152
7
56
skforest/intro_ds
ch12-ann/classification_example.py
Python
draw_model
draw_model
49
59
49
49
712da48e8d57bcd2d32cfa5a04bba07a2aebd619
bigcode/the-stack
train
53e11a0577e69e572e2b41dd
train
function
def generate_data(n): """ """ np.random.seed(12046) blobs = make_blobs(n_samples=n, centers=[[-2, -2], [2, 2]]) circles = make_circles(n_samples=n, factor=.4, noise=.05) moons = make_moons(n_samples=n, noise=.05) blocks = np.random.rand(n, 2) - 0.5 y = (blocks[:, 0] * blocks[:, 1] < 0) +...
def generate_data(n):
""" """ np.random.seed(12046) blobs = make_blobs(n_samples=n, centers=[[-2, -2], [2, 2]]) circles = make_circles(n_samples=n, factor=.4, noise=.05) moons = make_moons(n_samples=n, noise=.05) blocks = np.random.rand(n, 2) - 0.5 y = (blocks[:, 0] * blocks[:, 1] < 0) + 0 blocks = (block...
神经网络解决分类问题 """ import os from mlp import ANN import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import make_blobs, make_circles, make_moons from sklearn.linear_model import LogisticRegression from sklearn.preprocessing import StandardScaler, OneHotEncoder def generate_data(n):
69
69
232
5
63
skforest/intro_ds
ch12-ann/classification_example.py
Python
generate_data
generate_data
18
34
18
18
4a6ead0e49a1222827ce5eca98fe8d02d81967b7
bigcode/the-stack
train
0d2e44d4f9a6ada6bc2a26fb
train
function
def eval_input_fn(X, y, batch_size): # dataset = tf.data.Dataset.from_tensor_slices((X,y)).batch(batch_size) # (x, ylabels) = dataset.make_one_shot_iterator().get_next() # return {'pixels': x}, tf.cast(ylabels, dtype=tf.int32) dataset = tf.data.Dataset.from_tensor_slices(({'pixels': X}, y.astype(np.int32))...
def eval_input_fn(X, y, batch_size): # dataset = tf.data.Dataset.from_tensor_slices((X,y)).batch(batch_size) # (x, ylabels) = dataset.make_one_shot_iterator().get_next() # return {'pixels': x}, tf.cast(ylabels, dtype=tf.int32)
dataset = tf.data.Dataset.from_tensor_slices(({'pixels': X}, y.astype(np.int32))) dataset = dataset.batch(batch_size) return dataset
def eval_input_fn(X, y, batch_size): # dataset = tf.data.Dataset.from_tensor_slices((X,y)).batch(batch_size) # (x, ylabels) = dataset.make_one_shot_iterator().get_next() # return {'pixels': x}, tf.cast(ylabels, dtype=tf.int32)
67
64
101
67
0
Melykuti/Ng_Machine_learning_exercises
ex4_premade.py
Python
eval_input_fn
eval_input_fn
76
82
76
79
e7f20ec2647c19cf9a8428e15ad0a153185238a9
bigcode/the-stack
train
9ab294a1d8612f88d9818f4c
train
function
def load_data(): data = scipy.io.loadmat('../machine-learning-ex4/ex4/ex4data1.mat') X = data['X']#.astype(np.float32) y = data['y'] y = y % 10 return X, y
def load_data():
data = scipy.io.loadmat('../machine-learning-ex4/ex4/ex4data1.mat') X = data['X']#.astype(np.float32) y = data['y'] y = y % 10 return X, y
# 20x20 Input Images of Digits hidden_layer_size == 25 # 25 hidden units num_labels == 10 # 10 labels, from 1 to 10 # (note that we have mapped "0" to label 10) ''' def load_data():
63
64
58
4
59
Melykuti/Ng_Machine_learning_exercises
ex4_premade.py
Python
load_data
load_data
53
58
53
53
9b0e90568c798fbe67d767f70f2e22da9eca38c7
bigcode/the-stack
train
1cad71294908afc24969754d
train
function
def model(X, y, batch_size): # Feature columns feature_columns = [tf.feature_column.numeric_column("pixels", shape=[400], dtype=tf.float32)] ''' We don't use one-hot encoding like we did in ex4.py, see https://stackoverflow.com/questions/47120637/typeerror-unsupported-callable-using-dataset-with-estimator...
def model(X, y, batch_size): # Feature columns
feature_columns = [tf.feature_column.numeric_column("pixels", shape=[400], dtype=tf.float32)] ''' We don't use one-hot encoding like we did in ex4.py, see https://stackoverflow.com/questions/47120637/typeerror-unsupported-callable-using-dataset-with-estimator-input-fn y_idcc = tf.feature_column.categorical_col...
_shot_iterator().get_next() # return {'pixels': x}, tf.cast(ylabels, dtype=tf.int32) dataset = tf.data.Dataset.from_tensor_slices(({'pixels': X}, y.astype(np.int32))) dataset = dataset.batch(batch_size) return dataset def model(X, y, batch_size): # Feature columns
73
73
245
14
58
Melykuti/Ng_Machine_learning_exercises
ex4_premade.py
Python
model
model
84
111
84
86
cb010d90e9172474a14c30af27f7ad6491c7806c
bigcode/the-stack
train
ae20fed78c29a972388e11e5
train
function
def train_input_fn(X, y, batch_size): dataset = tf.data.Dataset.from_tensor_slices(({'pixels': X}, y.astype(np.int32))) #dataset = dataset.shuffle(1000).repeat().batch(batch_size) dataset = dataset.repeat().batch(batch_size) return dataset#.make_one_shot_iterator().get_next()
def train_input_fn(X, y, batch_size):
dataset = tf.data.Dataset.from_tensor_slices(({'pixels': X}, y.astype(np.int32))) #dataset = dataset.shuffle(1000).repeat().batch(batch_size) dataset = dataset.repeat().batch(batch_size) return dataset#.make_one_shot_iterator().get_next()
.org/get_started/premade_estimators#create_input_functions But it is included in the Creating Custom Estimators tutorial: https://www.tensorflow.org/get_started/custom_estimators#write_an_input_function It seems to run both with and without it. ''' def train_input_fn(X, y, batch_size):
64
64
72
11
53
Melykuti/Ng_Machine_learning_exercises
ex4_premade.py
Python
train_input_fn
train_input_fn
70
74
70
70
db2f10f1fa535aba436ff36f13abb632defcd008
bigcode/the-stack
train
861bc04d17cc7013711d68fa
train
class
class Controller(utils.ControllerType): def __init__(self, connection_manager: utils.ConnectionManager, config_info: utils.ConfigInfo): self.connection_manager = connection_manager self.config_info = config_info self.tk_format = utils.TkFormat(self.config_info) # The queue is a list...
class Controller(utils.ControllerType):
def __init__(self, connection_manager: utils.ConnectionManager, config_info: utils.ConfigInfo): self.connection_manager = connection_manager self.config_info = config_info self.tk_format = utils.TkFormat(self.config_info) # The queue is a list of dictionaries commands:parameters ...
import WhiteReferenceHandler from tanager_feeder.command_handlers.restart_rs3_handler import RestartRS3Handler from tanager_feeder.command_handlers.restart_computer_handler import RestartComputerHandler from tanager_feeder.command_handlers.check_writeable_handler import CheckWriteableHandler from tanager_feeder.comman...
256
256
24,444
6
249
westernmarslab/tanager-feeder
tanager_feeder/controller/controller.py
Python
Controller
Controller
81
2,783
81
81
5013b166e8d986327580e4419bb525899661b7ca
bigcode/the-stack
train
886659a6700196476b83711b
train
class
class SecondTimer(object): def __init__(self, seconds): object.__init__(self) self.__executors = [] self.__seconds = seconds self.__elapsed = 0 def get_elapsed(self): return self.__elapsed def set_elapsed(self, elapsed): self.__elapsed = elapsed def get...
class SecondTimer(object):
def __init__(self, seconds): object.__init__(self) self.__executors = [] self.__seconds = seconds self.__elapsed = 0 def get_elapsed(self): return self.__elapsed def set_elapsed(self, elapsed): self.__elapsed = elapsed def get_seconds(self): ret...
import threading class SecondTimer(object):
8
64
215
5
2
thunder-/paprika
paprika/threads/SecondTimer.py
Python
SecondTimer
SecondTimer
4
40
4
4
a07a8b2193f22bfa674678b8d32d942736580c86
bigcode/the-stack
train
56c22063ddfb547ba54fdf71
train
function
def test_simple_map(anchore_db): init_distro_mappings() found = DistroMapping() found.from_distro = "centos" found.to_distro = "centos" found.flavor = "RHEL" mapper = VersionPreservingDistroMapper("centos", "7", None, found) logger.info("Mapped centos to: {}".format(mapper.mapping)) asse...
def test_simple_map(anchore_db):
init_distro_mappings() found = DistroMapping() found.from_distro = "centos" found.to_distro = "centos" found.flavor = "RHEL" mapper = VersionPreservingDistroMapper("centos", "7", None, found) logger.info("Mapped centos to: {}".format(mapper.mapping)) assert mapper.mapping == [DistroTuple...
from tests.integration.services.policy_engine.utils import init_distro_mappings from anchore_engine.subsys import logger from anchore_engine.db.entities.policy_engine import ( DistroMapping, DistroTuple, VersionPreservingDistroMapper, get_thread_scoped_session, ) logger.enable_test_logging() def test_s...
73
80
268
9
64
Nordix/anchore-engine
tests/integration/services/policy_engine/db/test_distro_mapping.py
Python
test_simple_map
test_simple_map
13
32
13
13
a8eb14ba1c8ad3bdc4f9f55fe653c88e4b342170
bigcode/the-stack
train
36ab965cecd4cd133a47d3e5
train
function
def test_distro_from(anchore_db): init_distro_mappings() session = get_thread_scoped_session() try: distros = DistroMapping.distros_for("centos", "7", "rhel") logger.info("Distros for centos 7 (rhel) = {}".format(distros)) assert distros is not None assert len(distros) == 1 ...
def test_distro_from(anchore_db):
init_distro_mappings() session = get_thread_scoped_session() try: distros = DistroMapping.distros_for("centos", "7", "rhel") logger.info("Distros for centos 7 (rhel) = {}".format(distros)) assert distros is not None assert len(distros) == 1 distros = DistroMapping.di...
os" found.flavor = "RHEL" mapper = VersionPreservingDistroMapper("fedora", "27", "centos", found) logger.info("Mapped fedora to: {}".format(mapper.mapping)) assert mapper.mapping == [DistroTuple(distro="centos", version="27", flavor="RHEL")] mapper = VersionPreservingDistroMapper("fedora", "27", "c...
148
149
499
10
138
Nordix/anchore-engine
tests/integration/services/policy_engine/db/test_distro_mapping.py
Python
test_distro_from
test_distro_from
35
79
35
35
9309ffc7e32300d9103526e8330e4f060cdf1466
bigcode/the-stack
train
a52d5b437f28acd6638b7889
train
class
class PreTrainedTokenizer(object): """ Base class for all tokenizers. Handle all the shared methods for tokenization and special tokens as well as methods dowloading/caching/loading pretrained tokenizers as well as adding tokens to the vocabulary. This class also contain the added tokens in a unified way o...
class PreTrainedTokenizer(object):
""" Base class for all tokenizers. Handle all the shared methods for tokenization and special tokens as well as methods dowloading/caching/loading pretrained tokenizers as well as adding tokens to the vocabulary. This class also contain the added tokens in a unified way on top of all tokenizers so we don't...
# # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under ...
256
256
9,830
7
249
deepbluesea/transformers
transformers/tokenization_utils.py
Python
PreTrainedTokenizer
PreTrainedTokenizer
39
983
39
39
88ebe05386f2314e315b65d9e4e644bd230c960a
bigcode/the-stack
train
2fd55e27da826f870e57ebf7
train
function
def create_model(weights): model = t2t_vit_14() checkpoint = load(weights, map_location='cpu')['state_dict_ema'] model.load_state_dict(checkpoint) return model
def create_model(weights):
model = t2t_vit_14() checkpoint = load(weights, map_location='cpu')['state_dict_ema'] model.load_state_dict(checkpoint) return model
"AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from torch import load from models.t2t_vit import t2t_vit_14 def create_model(weights):
64
64
44
5
58
alpkn/open_model_zoo
models/public/t2t-vit-14/model.py
Python
create_model
create_model
19
25
19
19
52d942079c66e02b821538ba7b3191ededbbcf96
bigcode/the-stack
train
a7943d4f8412a40618e96385
train
function
def supersum(k, n): """ Actual supersum function """ if k == 0: return n if (k, n) not in mem: mem[(k, n)] = sum([supersum(k - 1, nn) for nn in range(1, n + 1)]) return mem[(k, n)]
def supersum(k, n):
""" Actual supersum function """ if k == 0: return n if (k, n) not in mem: mem[(k, n)] = sum([supersum(k - 1, nn) for nn in range(1, n + 1)]) return mem[(k, n)]
Level One Description: https://community.topcoder.com/stat?c=problem_statement&pm=10240 """ mem = {} def solve(args): """ Solved by using simple memoization """ k, n = args return supersum(k, n) def supersum(k, n):
64
64
76
7
57
carrdelling/topcoder
dp/super_sum.py
Python
supersum
supersum
22
31
22
22
5368452c90fea532e24e4cb77f92d205e9528171
bigcode/the-stack
train
fdcb9b4f4def93b1f213952b
train
function
def solve(args): """ Solved by using simple memoization """ k, n = args return supersum(k, n)
def solve(args):
""" Solved by using simple memoization """ k, n = args return supersum(k, n)
""" Problem name: ShorterSuperSum Class: SRM 467, Division II Level One Description: https://community.topcoder.com/stat?c=problem_statement&pm=10240 """ mem = {} def solve(args):
49
64
29
4
45
carrdelling/topcoder
dp/super_sum.py
Python
solve
solve
14
19
14
14
9af11cac915200447f6a014745d7ad5574c58d80
bigcode/the-stack
train
9e4f998da699d243907c5179
train
class
class GetFileListTestCase(unittest.TestCase): getfilelist_hander = filemanager.FileManager(public_key, private_key) def test_getfilelist(self): self.getfilelist_hander.set_keys(public_key, private_key) prefix = '' limit = 100 marker = '' ret, resp = self.getfilelist_hand...
class GetFileListTestCase(unittest.TestCase):
getfilelist_hander = filemanager.FileManager(public_key, private_key) def test_getfilelist(self): self.getfilelist_hander.set_keys(public_key, private_key) prefix = '' limit = 100 marker = '' ret, resp = self.getfilelist_hander.getfilelist(bucket, prefix=prefix, limit=li...
, set_log_file from ufile.config import get_default from common import * public_key = PUBLIC_KEY #添加自己的账户公钥 private_key = PRIVATE_KEY #添加自己的账户私钥 bucket = PUBLIC_BUCKET #添加自己的空间名称 class GetFileListTestCase(unittest.TestCase):
64
64
152
10
53
NightRain233/ufile-sdk-python
test_ufile/test_getfilelist.py
Python
GetFileListTestCase
GetFileListTestCase
13
27
13
13
2580a9a0dd15db6231bcf194f7fc572754d2e87e
bigcode/the-stack
train
b5a2b87106ecc520d7e293aa
train
function
@app.route('/classify', methods=['POST']) def classify(): """ API that return your model predictions when TomoFun calls this API. """ # 接收 TomoFun 發來的Request if request.headers['x-api-key'] != API_KEY: return jsonify({'message': 'unknown api key'}) # 存成 wav file ts_now = datetime.datetime.n...
@app.route('/classify', methods=['POST']) def classify():
""" API that return your model predictions when TomoFun calls this API. """ # 接收 TomoFun 發來的Request if request.headers['x-api-key'] != API_KEY: return jsonify({'message': 'unknown api key'}) # 存成 wav file ts_now = datetime.datetime.now(TZ).strftime("%Y%m%d%H%M%S") file_name = ts_now + '...
name__) ####### PUT YOUR INFORMATION HERE ####### CAPTAIN_EMAIL = '' # 隊長信箱 SALT = 'StarRingChild' # 加密用字串 隨意輸入即可 此處輸入隊名 API_KEY = '' ######################################### @app.route('/classify', methods=['POST']) def classify():
71
71
238
13
58
KuanHaoHuang/tbrain-tomofun-audio-classification
app.py
Python
classify
classify
28
55
28
29
5c113215c260a9f9cd2c576feb1d97c11b08a9a7
bigcode/the-stack
train
1ec90e742913c86125a65573
train
function
def get_library_name(lib): return LIB_PREFIX + lib + '.' + ARCHIVE_EXT
def get_library_name(lib):
return LIB_PREFIX + lib + '.' + ARCHIVE_EXT
== 'nt': ARCHIVE_EXT = 'lib' LIB_PREFIX = 'Release/' DIR_PREFIX = 'src/duckdb' if not os.path.exists(DIR_PREFIX): # this is a build from within the tools/pythonpkg directory DIR_PREFIX = '../../' def get_library_name(lib):
64
64
19
6
58
sreeharshar84/duckdb
tools/pythonpkg/setup.py
Python
get_library_name
get_library_name
35
36
35
35
a92db8f44bbf2451e6b871a41deb914ee69d84ab
bigcode/the-stack
train
e599d6b356b6245b65d12c00
train
class
class CustomBuiltExtCommand(build_ext): def build_duckdb(self): cmake_bin = distutils.spawn.find_executable('cmake') if (cmake_bin is None): raise Exception('DuckDB needs cmake to build from source') wd = os.getcwd() os.chdir(DIR_PREFIX) if not os.path.exists('bu...
class CustomBuiltExtCommand(build_ext):
def build_duckdb(self): cmake_bin = distutils.spawn.find_executable('cmake') if (cmake_bin is None): raise Exception('DuckDB needs cmake to build from source') wd = os.getcwd() os.chdir(DIR_PREFIX) if not os.path.exists('build/release_notest'): os.mak...
third_party', 'libpg_query', get_library_name('pg_query')) RE2_LIB = os.path.join(BUILD_DIR, 'third_party', 're2', get_library_name('re2')) MINIZ_LIB = os.path.join(BUILD_DIR, 'third_party', 'miniz', get_library_name('miniz')) # wrapper that builds the main DuckDB library first class CustomBuiltExtCommand(build_ext):...
87
87
292
8
78
sreeharshar84/duckdb
tools/pythonpkg/setup.py
Python
CustomBuiltExtCommand
CustomBuiltExtCommand
54
87
54
54
bdfc1a6dabb198fca1fb500f292ea9142beed88e
bigcode/the-stack
train
a72618988e6f99244e20bf69
train
class
class CustomSdistCommand(sdist): def run(self): if os.path.exists('src/duckdb'): shutil.rmtree('src/duckdb') if not os.path.exists('src/duckdb/third_party'): os.makedirs('src/duckdb/third_party') shutil.copyfile('../../CMakeLists.txt', 'src/duckdb/CMakeLists.txt') ...
class CustomSdistCommand(sdist):
def run(self): if os.path.exists('src/duckdb'): shutil.rmtree('src/duckdb') if not os.path.exists('src/duckdb/third_party'): os.makedirs('src/duckdb/third_party') shutil.copyfile('../../CMakeLists.txt', 'src/duckdb/CMakeLists.txt') shutil.copyfile('../../third...
RE2_LIB, MINIZ_LIB]: if not os.path.isfile(library): raise Exception('Build failed: could not find required library file "%s"' % library) print(INCLUDE_DIR) build_ext.run(self) # create a distributable directory structure class CustomSdistCommand(sdist):
64
64
216
8
55
sreeharshar84/duckdb
tools/pythonpkg/setup.py
Python
CustomSdistCommand
CustomSdistCommand
90
103
90
90
edcb97c0708d1d9bc1db91a18f5f79f8df8e28c1
bigcode/the-stack
train
bbec165ff3bc71e6cd327781
train
function
def Keys(idempotency: str, type: str = "RANDOM_KEY", key: str = ""): req_data = {'type': type} if type == "RANDOM_KEY" and key != "": req_data['key'] = key print(req_data) data = Post("/pix/keys", req_data, {'X-Idempotency-Key': idempotency}) print(data) return Pix(**data)
def Keys(idempotency: str, type: str = "RANDOM_KEY", key: str = ""):
req_data = {'type': type} if type == "RANDOM_KEY" and key != "": req_data['key'] = key print(req_data) data = Post("/pix/keys", req_data, {'X-Idempotency-Key': idempotency}) print(data) return Pix(**data)
from junopy.utils.juno import * from junopy import Pix def Keys(idempotency: str, type: str = "RANDOM_KEY", key: str = ""):
38
64
93
23
14
robertons/junopy
junopy/services/pix.py
Python
Keys
Keys
6
16
6
7
82abbeb6243e857d18afca51e17e286e8a85a03f
bigcode/the-stack
train
af7b786e77385f971bab34c4
train
function
def StaticQRCode(idempotency: str, key: str, includeImage: bool = False, amount: float = 0, reference: str = '', additionalData: str = ''): req_data = { 'key': key, 'includeImage': includeImage } if amount > 0: req_data['amount'] = amount if reference != '': req_data['...
def StaticQRCode(idempotency: str, key: str, includeImage: bool = False, amount: float = 0, reference: str = '', additionalData: str = ''):
req_data = { 'key': key, 'includeImage': includeImage } if amount > 0: req_data['amount'] = amount if reference != '': req_data['reference'] = reference if additionalData != '': req_data['additionalData'] = additionalData data = Post("/pix/qrcodes/stat...
req_data, {'X-Idempotency-Key': idempotency}) print(data) return Pix(**data) def StaticQRCode(idempotency: str, key: str, includeImage: bool = False, amount: float = 0, reference: str = '', additionalData: str = ''):
64
64
143
39
25
robertons/junopy
junopy/services/pix.py
Python
StaticQRCode
StaticQRCode
19
37
19
20
035be3032c7331ad5b0eefa512706c8dfc93a30a
bigcode/the-stack
train
93b5123e8eb25a1b9526fa98
train
function
def parseHN(): page,html = fetch("https://news.ycombinator.com/newest") links = [] for link in html.find_all(class_="storylink"): links.append(link['href']) return links
def parseHN():
page,html = fetch("https://news.ycombinator.com/newest") links = [] for link in html.find_all(class_="storylink"): links.append(link['href']) return links
,0)) # no need to delay; pulling from random sites filename = f"page{i}.html" i += 1 print(f"Writing {filename}") with open(os.path.join(outputdir,filename), "w") as f: f.write(page) def parseHN():
64
64
50
4
60
skrilladeville/msds692
notes/code/scrape/crawlHN.py
Python
parseHN
parseHN
32
38
32
32
fa618ef324d926239ceebee2ca97ab1a26bf1f37
bigcode/the-stack
train
ca8151907961eea70ed07eb2
train
function
def crawl(links, outputdir): i = 0 for link in links: page,html = fetch(link,delay=(0,0)) # no need to delay; pulling from random sites filename = f"page{i}.html" i += 1 print(f"Writing {filename}") with open(os.path.join(outputdir,filename), "w") as f: f.writ...
def crawl(links, outputdir):
i = 0 for link in links: page,html = fetch(link,delay=(0,0)) # no need to delay; pulling from random sites filename = f"page{i}.html" i += 1 print(f"Writing {filename}") with open(os.path.join(outputdir,filename), "w") as f: f.write(page)
headers={'User-Agent': "Resistance is futile"}) except ValueError as e: print(str(e)) return '', BeautifulSoup('', "html.parser") html = response.text soup = BeautifulSoup(html, "html.parser") return (html,soup) def crawl(links, outputdir):
64
64
91
8
56
skrilladeville/msds692
notes/code/scrape/crawlHN.py
Python
crawl
crawl
22
30
22
22
5e20013327e40f30c87622f411b5a489fbd39749
bigcode/the-stack
train
8a8f69bdfd28d15847ce30fa
train
function
def fetch(url,delay=(1,3)): """ Simulate human random clicking x..y seconds then fetch URL. Returns the actual page source fetched and the HTML object. """ time.sleep(random.randint(delay[0],delay[1])) # wait random seconds try: response = requests.get(url, headers={'User-Agent': "Resist...
def fetch(url,delay=(1,3)):
""" Simulate human random clicking x..y seconds then fetch URL. Returns the actual page source fetched and the HTML object. """ time.sleep(random.randint(delay[0],delay[1])) # wait random seconds try: response = requests.get(url, headers={'User-Agent': "Resistance is futile"}) except...
import requests import time import random from bs4 import BeautifulSoup import sys, os def fetch(url,delay=(1,3)):
31
64
124
10
20
skrilladeville/msds692
notes/code/scrape/crawlHN.py
Python
fetch
fetch
7
20
7
7
648c287464f0873d3b949d574371f7f3add8b0a6
bigcode/the-stack
train
d9eb199f501f7c3f4452d6d0
train
function
def set_routine(p, *args, **kw): if len(args) > 1: p.err(''' incorrect number of arguments for solve(), must be at least 1 (solver), other must be keyword arguments''') solver = args[0] if len(args) != 0 else kw.get('solver', p.solver) routine = kw.pop('routine', 'solve') KW = ...
def set_routine(p, *args, **kw):
if len(args) > 1: p.err(''' incorrect number of arguments for solve(), must be at least 1 (solver), other must be keyword arguments''') solver = args[0] if len(args) != 0 else kw.get('solver', p.solver) routine = kw.pop('routine', 'solve') KW = p._init_kwargs.copy() KW.updat...
AB(MatrixProblem): _optionalData = [] probType = 'STAB' expectedArgs = ['graph'] allowedGoals = ['graph stability number'] showGoal = False def __init__(self, *args, **kw): MatrixProblem.__init__(self, *args, **kw) # TODO: simplify it, handle _init_kwargs in parent class ...
195
195
650
13
181
wangyum/anaconda
lib/python2.7/site-packages/openopt/kernel/STAB.py
Python
set_routine
set_routine
28
94
28
28
89896e72eeab91d746a879751f7a8fe45151671f
bigcode/the-stack
train
a5526550034af1a5191a728c
train
function
def encode(r, n, x, index2node): r.solution = [index2node[i] for i in range(n) if r.xf[x[i]] == 1] r.ff = len(r.solution)
def encode(r, n, x, index2node):
r.solution = [index2node[i] for i in range(n) if r.xf[x[i]] == 1] r.ff = len(r.solution)
val in kw.items(): setattr(p, key, val) p.finish = lambda r, p: encode(r, n, x, index2node) r = getattr(p, routine)(solver, **KW) return r def encode(r, n, x, index2node):
64
64
47
12
51
wangyum/anaconda
lib/python2.7/site-packages/openopt/kernel/STAB.py
Python
encode
encode
96
98
96
96
9354d15d3094e14cc51d3f5a3d5577a00106e61e
bigcode/the-stack
train
8ac78ebd8b1107490e010681
train
class
class STAB(MatrixProblem): _optionalData = [] probType = 'STAB' expectedArgs = ['graph'] allowedGoals = ['graph stability number'] showGoal = False def __init__(self, *args, **kw): MatrixProblem.__init__(self, *args, **kw) # TODO: simplify it, handle _init_kwargs in parent ...
class STAB(MatrixProblem):
_optionalData = [] probType = 'STAB' expectedArgs = ['graph'] allowedGoals = ['graph stability number'] showGoal = False def __init__(self, *args, **kw): MatrixProblem.__init__(self, *args, **kw) # TODO: simplify it, handle _init_kwargs in parent class self._init_kw...
from baseProblem import MatrixProblem class STAB(MatrixProblem):
13
64
161
6
6
wangyum/anaconda
lib/python2.7/site-packages/openopt/kernel/STAB.py
Python
STAB
STAB
3
22
3
3
305247f68f6e8398c9381e4d5d47aca4d47622c5
bigcode/the-stack
train
814f66bf50d3145feb1db6f6
train
class
class ProcessWithZeroDivisionErrorPipiline(object): def process_item(self, item, spider): 1 / 0
class ProcessWithZeroDivisionErrorPipiline(object):
def process_item(self, item, spider): 1 / 0
""" Some pipelines used for testing """ class ZeroDivisionErrorPipeline(object): def open_spider(self, spider): a = 1 / 0 def process_item(self, item, spider): return item class ProcessWithZeroDivisionErrorPipiline(object):
58
64
28
11
46
HEndo12345/scrapy
tests/pipelines.py
Python
ProcessWithZeroDivisionErrorPipiline
ProcessWithZeroDivisionErrorPipiline
15
18
15
16
88c666d73d79db7de6af950eb01ddaa996d3ce0d
bigcode/the-stack
train
f7a131a069a8184ce331ad56
train
class
class ZeroDivisionErrorPipeline(object): def open_spider(self, spider): a = 1 / 0 def process_item(self, item, spider): return item
class ZeroDivisionErrorPipeline(object):
def open_spider(self, spider): a = 1 / 0 def process_item(self, item, spider): return item
""" Some pipelines used for testing """ class ZeroDivisionErrorPipeline(object):
15
64
39
7
8
HEndo12345/scrapy
tests/pipelines.py
Python
ZeroDivisionErrorPipeline
ZeroDivisionErrorPipeline
6
12
6
7
09a46b3d3c198d5bfb5754d4613d387199530784
bigcode/the-stack
train
3f7b1c6475fc882fb4749f0e
train
class
class SimpleModel(): def __init__(self): self.model = XGBClassifier() def fit(self, x, y, val_x, val_y): eval_set = [(val_x,val_y)] self.model.fit(x, y, early_stopping_rounds=10, eval_metric="logloss", eval_set=eval_set, verbose=True) def predict(self, x): return s...
class SimpleModel():
def __init__(self): self.model = XGBClassifier() def fit(self, x, y, val_x, val_y): eval_set = [(val_x,val_y)] self.model.fit(x, y, early_stopping_rounds=10, eval_metric="logloss", eval_set=eval_set, verbose=True) def predict(self, x): return self.model.predict(x)
from xgboost import XGBClassifier class SimpleModel():
13
64
90
4
8
fahim5466/IDAO_2021_Final_Stage
submission/SimpleModel.py
Python
SimpleModel
SimpleModel
3
13
3
3
0e547cbb3b91d9398d8cf9ff5295ddd34c213d52
bigcode/the-stack
train
47dfeee3c309fcf4f645b442
train
class
@pytest.mark.usefixtures class TestModuleIntegrationCrossref(unittest.TestCase): @unittest.skip("todo") def test_handleEvent(self): sf = SpiderFoot(self.default_options) module = sfp_crossref() module.setup(sf, dict()) target_value = 'example target value' target_type ...
@pytest.mark.usefixtures class TestModuleIntegrationCrossref(unittest.TestCase): @unittest.skip("todo")
def test_handleEvent(self): sf = SpiderFoot(self.default_options) module = sfp_crossref() module.setup(sf, dict()) target_value = 'example target value' target_type = 'IP_ADDRESS' target = SpiderFootTarget(target_value, target_type) module.setTarget(target) ...
import pytest import unittest from modules.sfp_crossref import sfp_crossref from sflib import SpiderFoot from spiderfoot import SpiderFootEvent, SpiderFootTarget @pytest.mark.usefixtures class TestModuleIntegrationCrossref(unittest.TestCase): @unittest.skip("todo")
61
64
147
23
37
khiemtq-cyber/spiderfoot
test/integration/modules/test_sfp_crossref.py
Python
TestModuleIntegrationCrossref
TestModuleIntegrationCrossref
9
32
9
12
b5fbcf7f57f9eed5a3c4542ab035fde44858f050
bigcode/the-stack
train
22a7b2111bc0e7a3130f39c0
train
class
class SuppressionContract(Resource): """The details of the snoozed or dismissed rule; for example, the duration, name, and GUID associated with the rule. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The resource ID. :vartype id: str :iva...
class SuppressionContract(Resource):
"""The details of the snoozed or dismissed rule; for example, the duration, name, and GUID associated with the rule. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The resource ID. :vartype id: str :ivar name: The name of the resource. ...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
90
101
339
6
83
JonathanGailliez/azure-sdk-for-python
azure-mgmt-advisor/azure/mgmt/advisor/models/suppression_contract_py3.py
Python
SuppressionContract
SuppressionContract
15
51
15
15
9f0c16d1c5174959afaeec5f4f53f303163d01c5
bigcode/the-stack
train
d3ccb3ea39937807e3c966ce
train
class
class ServiceInstance(InstanceResource): """ PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact help@twilio.com. """ def __init__(self, version, payload, sid=None): """ ...
class ServiceInstance(InstanceResource):
""" PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact help@twilio.com. """ def __init__(self, version, payload, sid=None): """ Initialize the ServiceInstance ...
:param unicode friendly_name: A human readable description of this resource. :returns: Updated ServiceInstance :rtype: twilio.rest.preview.authy.service.ServiceInstance """ data = values.of({'FriendlyName': friendly_name, }) payload = self._version.update( '...
253
253
845
7
246
siyaochen/Tier1Health
app/env/lib/python3.7/site-packages/twilio/rest/preview/authy/service/__init__.py
Python
ServiceInstance
ServiceInstance
294
430
294
294
cc8db45c3cd4dc06e1f400a20b43439bd4693cd2
bigcode/the-stack
train
cc0fc2df8f3c912b093978c8
train
class
class ServicePage(Page): """ PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact help@twilio.com. """ def __init__(self, version, response, solution): """ Initializ...
class ServicePage(Page):
""" PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact help@twilio.com. """ def __init__(self, version, response, solution): """ Initialize the ServicePage ...
:rtype: twilio.rest.preview.authy.service.ServiceContext """ return ServiceContext(self._version, sid=sid, ) def __repr__(self): """ Provide a friendly representation :returns: Machine friendly representation :rtype: str """ return '<Twilio.P...
77
78
262
5
72
siyaochen/Tier1Health
app/env/lib/python3.7/site-packages/twilio/rest/preview/authy/service/__init__.py
Python
ServicePage
ServicePage
170
208
170
170
44abf7e08305b20f93f641981ff65ee5157f2707
bigcode/the-stack
train
06cb34e408ee062c8614a6a4
train
class
class ServiceContext(InstanceContext): """ PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact help@twilio.com. """ def __init__(self, version, sid): """ Initialize...
class ServiceContext(InstanceContext):
""" PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact help@twilio.com. """ def __init__(self, version, sid): """ Initialize the ServiceContext :param Ver...
twilio.rest.preview.authy.service.ServicePage """ super(ServicePage, self).__init__(version, response) # Path Solution self._solution = solution def get_instance(self, payload): """ Build an instance of ServiceInstance :param dict payload: Payload response...
158
159
532
7
151
siyaochen/Tier1Health
app/env/lib/python3.7/site-packages/twilio/rest/preview/authy/service/__init__.py
Python
ServiceContext
ServiceContext
211
291
211
211
614c17ed9975b86d099e1e4da80c3c7743a604c5
bigcode/the-stack
train
c35de004af052a1c9ce4a0d6
train
class
class ServiceList(ListResource): """ PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact help@twilio.com. """ def __init__(self, version): """ Initialize the Servic...
class ServiceList(ListResource):
""" PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you currently do not have developer preview access, please contact help@twilio.com. """ def __init__(self, version): """ Initialize the ServiceList :param Version ver...
# coding=utf-8 """ This code was generated by \ / _ _ _| _ _ | (_)\/(_)(_|\/| |(/_ v1.0.0 / / """ from twilio.base import deserialize from twilio.base import values from twilio.base.instance_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base....
120
256
1,171
6
113
siyaochen/Tier1Health
app/env/lib/python3.7/site-packages/twilio/rest/preview/authy/service/__init__.py
Python
ServiceList
ServiceList
18
167
18
18
041655f6a52ee61d39b2d1a2457e45ea22e1bf15
bigcode/the-stack
train
6622dc3bb322cd078ceb9388
train
function
def main(): player.start(song)
def main():
player.start(song)
from shared import player, run, song def main():
12
64
8
3
8
vrslev/playbacker
testing/play.py
Python
main
main
4
5
4
4
2bc95cf974e1ae84e3747915038d49714e68e9f4
bigcode/the-stack
train
5551d21eeed43eaea13f24ff
train
function
@composite def election_contexts(draw: _DrawType, num_candidates: int): """ Generates a `PrivateElectionContext` for an election with the given number of candidates. :param draw: Hidden argument, used by Hypothesis. :param num_candidates: Desired number of candidates for the election. """ k...
@composite def election_contexts(draw: _DrawType, num_candidates: int):
""" Generates a `PrivateElectionContext` for an election with the given number of candidates. :param draw: Hidden argument, used by Hypothesis. :param num_candidates: Desired number of candidates for the election. """ keypair = draw(elgamal_keypairs("keypair")) hash_header = draw(elemen...
"Jimmy Carter", "Ronald Reagan", "George Bush", "Bill Clinton", "George W. Bush", "Barack Obama", "Donald Trump", "Joe Biden", ] @composite def election_contexts(draw: _DrawType, num_candidates: int):
64
64
148
19
45
debugevent90901/ECECS407
mp4-electionguard/src/electionguardtest/simple_elections.py
Python
election_contexts
election_contexts
68
86
68
69
4a2a9b8ad42bb9ba09b089a91716134ed4909f4c
bigcode/the-stack
train
05138ecb5bc861099d3a1321
train
function
@composite def context_and_ballots(draw: _DrawType, num_ballots: int, num_candidates: int = 3): """ Generates a tuple of a PrivateElectionContext and a list of well-formed PlaintextBallots. If the number of candidates is 0, then it will be drawn at random from a large set. """ if num_candidates <= 0...
@composite def context_and_ballots(draw: _DrawType, num_ballots: int, num_candidates: int = 3):
""" Generates a tuple of a PrivateElectionContext and a list of well-formed PlaintextBallots. If the number of candidates is 0, then it will be drawn at random from a large set. """ if num_candidates <= 0: num_candidates = draw(integers(2, len(__presidents))) context = draw(election_cont...
return [ draw(plaintext_ballot(context, f"ballot%03d", False)) for _ in range(0, num_ballots) ] @composite def context_and_ballots(draw: _DrawType, num_ballots: int, num_candidates: int = 3):
63
64
131
29
34
debugevent90901/ECECS407
mp4-electionguard/src/electionguardtest/simple_elections.py
Python
context_and_ballots
context_and_ballots
155
165
155
156
21a552b8d6f36f79f090ff350aab7a203f2669f7
bigcode/the-stack
train
d46f61a3abd46ac67a843bc2
train
function
@composite def plaintext_ballot( draw: _DrawType, context: AnyElectionContext, ballot_id: str, well_formed: bool ): """ Generates a plaintext ballot, which might be blank or might have at most one vote for a candidate. :param draw: Hidden argument, used by Hypothesis. :param context: An electio...
@composite def plaintext_ballot( draw: _DrawType, context: AnyElectionContext, ballot_id: str, well_formed: bool ):
""" Generates a plaintext ballot, which might be blank or might have at most one vote for a candidate. :param draw: Hidden argument, used by Hypothesis. :param context: An election context, with the necessary crypto keys, etc. :param ballot_id: A string to use for this ballot's identifier. ...
pair")) hash_header = draw(elements_mod_q("hash_header")) max_candidates = draw(integers(min_value=1, max_value=num_candidates)) return PrivateElectionContext( "Test Election", __presidents[0:num_candidates], max_candidates, keypair, hash_header, ) @composite def ...
100
100
336
34
66
debugevent90901/ECECS407
mp4-electionguard/src/electionguardtest/simple_elections.py
Python
plaintext_ballot
plaintext_ballot
89
127
89
92
85a465e17ef3f0031e82d5000092c76dd7b4657b
bigcode/the-stack
train
77596249f008c76e62226150
train
function
@composite def plaintext_ballots(draw: _DrawType, context: AnyElectionContext, num_ballots: int): """ Generates a list of the requested number of ballots. All will be well-formed. """ return [ draw(plaintext_ballot(context, f"ballot{i:03d}", True)) for i in range(0, num_ballots) ]
@composite def plaintext_ballots(draw: _DrawType, context: AnyElectionContext, num_ballots: int):
""" Generates a list of the requested number of ballots. All will be well-formed. """ return [ draw(plaintext_ballot(context, f"ballot{i:03d}", True)) for i in range(0, num_ballots) ]
1 if shuffled_votes[i] == 1 else 0) for i in range(0, num_names) ] return PlaintextBallot(ballot_id, selections) @composite def plaintext_ballots(draw: _DrawType, context: AnyElectionContext, num_ballots: int):
64
64
84
26
38
debugevent90901/ECECS407
mp4-electionguard/src/electionguardtest/simple_elections.py
Python
plaintext_ballots
plaintext_ballots
130
138
130
131
adcf1c81c5040b8f80fd4e62177d073a950f6df9
bigcode/the-stack
train
240f10049368e285332a4ec2
train
function
@composite def context_and_arbitrary_ballots( draw: _DrawType, num_ballots: int, num_candidates: int = 3 ): """ Generates a tuple of a PrivateElectionContext and a list of PlaintextBallots, some of which might not be well-formed. """ if num_candidates <= 0: num_candidates = draw(integers...
@composite def context_and_arbitrary_ballots( draw: _DrawType, num_ballots: int, num_candidates: int = 3 ):
""" Generates a tuple of a PrivateElectionContext and a list of PlaintextBallots, some of which might not be well-formed. """ if num_candidates <= 0: num_candidates = draw(integers(2, len(__presidents))) context = draw(election_contexts(num_candidates)) ballots = draw(plaintext_arbit...
context = draw(election_contexts(num_candidates)) ballots = draw(plaintext_ballots(context, num_ballots)) return context, ballots @composite def context_and_arbitrary_ballots( draw: _DrawType, num_ballots: int, num_candidates: int = 3 ):
64
64
125
34
29
debugevent90901/ECECS407
mp4-electionguard/src/electionguardtest/simple_elections.py
Python
context_and_arbitrary_ballots
context_and_arbitrary_ballots
168
180
168
171
b9b4c8a8f2f5335b5c8b81deb1fc8ae04725382d
bigcode/the-stack
train
cf244bba8b0dcd5f7aa9df43
train
function
@composite def plaintext_arbitrary_ballots( draw: _DrawType, context: AnyElectionContext, num_ballots: int ): """ Generates a list of the requested number of ballots. Some will be well-formed and others might have overvotes. """ return [ draw(plaintext_ballot(context, f"ballot%03d", Fals...
@composite def plaintext_arbitrary_ballots( draw: _DrawType, context: AnyElectionContext, num_ballots: int ):
""" Generates a list of the requested number of ballots. Some will be well-formed and others might have overvotes. """ return [ draw(plaintext_ballot(context, f"ballot%03d", False)) for _ in range(0, num_ballots) ]
draw(plaintext_ballot(context, f"ballot{i:03d}", True)) for i in range(0, num_ballots) ] @composite def plaintext_arbitrary_ballots( draw: _DrawType, context: AnyElectionContext, num_ballots: int ):
63
64
96
31
32
debugevent90901/ECECS407
mp4-electionguard/src/electionguardtest/simple_elections.py
Python
plaintext_arbitrary_ballots
plaintext_arbitrary_ballots
141
152
141
144
366fe46f6af033d23dc722883431ecea2327bc58
bigcode/the-stack
train
50a9dae860cb27247c7cb62a
train
class
class Connection(BaseConnection): def close(self): self.rollback() self.__dbhandle = None self._closed = True def __enter__(self): return self def __exit__(self, etype, value, traceback): self.commit() self.close() def commit(self): self._raise_...
class Connection(BaseConnection):
def close(self): self.rollback() self.__dbhandle = None self._closed = True def __enter__(self): return self def __exit__(self, etype, value, traceback): self.commit() self.close() def commit(self): self._raise_if_already_closed() self....
LLC # # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file or at # https://developers.google.com/open-source/licenses/bsd from .autocommit_on_cursor import Cursor from .base_connection import BaseConnection class Connection(BaseConnection):
64
64
126
5
58
timgraham/python-spanner-django
spanner_dbapi/autocommit_on_connection.py
Python
Connection
Connection
11
37
11
11
f0408a7e5861b2bf4c635018a1639f2e62d4f74a
bigcode/the-stack
train
79aa92d8ff809ca8a4f4aa1d
train
class
class LogLevel(ExtendedEnum): DEBUG = "DEBUG" INFO = "INFO" WARNING = "WARNING" ERROR = "ERROR" CRITICAL = "CRITICAL"
class LogLevel(ExtendedEnum):
DEBUG = "DEBUG" INFO = "INFO" WARNING = "WARNING" ERROR = "ERROR" CRITICAL = "CRITICAL"
from maestro_cli.libs.extended.enum import ExtendedEnum class LogLevel(ExtendedEnum):
18
64
39
7
10
Farfetch/maestro
cli/maestro_cli/enums.py
Python
LogLevel
LogLevel
4
9
4
4
1e312f2b63aa29611867914ee3fd325b1a7d78a1
bigcode/the-stack
train
afd6da91c217dcb9ac2b38d2
train
function
@decorators.iterative_task(student_project_logic) def runStudentProjectUpdate(request, entities, context, *args, **kwargs): """AppEngine Task that updates StudentProject entities. Args: request: Django Request object entities: list of StudentProject entities to update context: the context of this task ...
@decorators.iterative_task(student_project_logic) def runStudentProjectUpdate(request, entities, context, *args, **kwargs):
"""AppEngine Task that updates StudentProject entities. Args: request: Django Request object entities: list of StudentProject entities to update context: the context of this task """ from soc.modules.gsoc.logic.models.mentor import logic as mentor_logic from soc.modules.gsoc.logic.models.organiz...
Args: request: Django Request object entities: list of Review entities to update context: the context of this task """ for entity in entities: entity.reviewer = None # store all Reviews db.put(entities) # task completed, return return @decorators.iterative_task(student_project_logic) de...
93
93
311
27
65
MatthewWilkes/mw4068-packaging
src/melange/src/soc/tasks/updates/module_conversion.py
Python
runStudentProjectUpdate
runStudentProjectUpdate
369
406
369
370
ecc98a73274442555c053c9d88e6cb89b65f0b50
bigcode/the-stack
train
e7c56c7e14e30730363018be
train
function
@decorators.iterative_task(grading_survey_group_logic) def runGradingSurveyGroupUpdate(request, entities, context, *args, **kwargs): """AppEngine Task that updates GradingSurveyGroup entities. Args: request: Django Request object entities: list of Document entities to update context: the context of thi...
@decorators.iterative_task(grading_survey_group_logic) def runGradingSurveyGroupUpdate(request, entities, context, *args, **kwargs):
"""AppEngine Task that updates GradingSurveyGroup entities. Args: request: Django Request object entities: list of Document entities to update context: the context of this task """ from soc.modules.gsoc.logic.models.program import logic as program_logic for entity in entities: entity.scope ...
= org_logic.getFromKeyName(org_key_name) cached_orgs[org_key_name] = org_entity entity.org = org_entity db.put(entities) # task completed, return return entities @decorators.iterative_task(grading_survey_group_logic) def runGradingSurveyGroupUpdate(request, entities, context, *args, **kwargs):
80
80
267
32
47
MatthewWilkes/mw4068-packaging
src/melange/src/soc/tasks/updates/module_conversion.py
Python
runGradingSurveyGroupUpdate
runGradingSurveyGroupUpdate
598
635
598
599
3fe75fb7b19145463e365678e655428a5efcc211
bigcode/the-stack
train
5fc770f1d650de60379387db
train
function
@decorators.iterative_task(program_logic) def runProgramConversionUpdate(request, entities, context, *args, **kwargs): """AppEngine Task that converts Programs into GSoCPrograms. Args: request: Django Request object entities: list of Program entities to convert context: the context of this task """ ...
@decorators.iterative_task(program_logic) def runProgramConversionUpdate(request, entities, context, *args, **kwargs):
"""AppEngine Task that converts Programs into GSoCPrograms. Args: request: Django Request object entities: list of Program entities to convert context: the context of this task """ from soc.modules.gsoc.models.program import GSoCProgram # get all the properties that are part of each Programs ...
task_url: The URL used to run this update task Returns: True iff the new task is successfully added to the Task Queue API """ new_task = taskqueue.Task(url=task_url) new_task.add() return True @decorators.iterative_task(program_logic) def runProgramConversionUpdate(request, entities, context, *args, *...
79
79
266
26
52
MatthewWilkes/mw4068-packaging
src/melange/src/soc/tasks/updates/module_conversion.py
Python
runProgramConversionUpdate
runProgramConversionUpdate
81
116
81
82
5d99ae90f23971ba5a5ba48950d4db4948fc1540
bigcode/the-stack
train
7cd59a904bed43eca385a1d1
train
function
@decorators.iterative_task(org_admin_logic) def runOrgAdminConversionUpdate(request, entities, context, *args, **kwargs): """AppEngine Task that converts OrgAdmins into GSoCOrgAdmins. Args: request: Django Request object entities: list of OrgAdmin entities to convert context: the context of this task ...
@decorators.iterative_task(org_admin_logic) def runOrgAdminConversionUpdate(request, entities, context, *args, **kwargs):
"""AppEngine Task that converts OrgAdmins into GSoCOrgAdmins. Args: request: Django Request object entities: list of OrgAdmin entities to convert context: the context of this task """ from soc.modules.gsoc.models.org_admin import GSoCOrgAdmin return _runOrgRoleConversionUpdate(entities, org_adm...
db.put(gsoc_orgs) # store all the new rankers db.put(gsoc_rankers) # task completed, return return @decorators.iterative_task(org_admin_logic) def runOrgAdminConversionUpdate(request, entities, context, *args, **kwargs):
64
64
113
28
35
MatthewWilkes/mw4068-packaging
src/melange/src/soc/tasks/updates/module_conversion.py
Python
runOrgAdminConversionUpdate
runOrgAdminConversionUpdate
180
192
180
181
978a731bb0f9857120d697aabde6dc2a8bb7175c
bigcode/the-stack
train
1d1693dec303d58791b7cfe3
train
function
@decorators.iterative_task(grading_record_logic) def runGradingProjectSurveyRecordUpdate(request, entities, context, *args, **kwargs): """AppEngine Task that updates GradingProjectSurveyRecord entities. Args: request: Django Request object entities: list of GradingP...
@decorators.iterative_task(grading_record_logic) def runGradingProjectSurveyRecordUpdate(request, entities, context, *args, **kwargs):
"""AppEngine Task that updates GradingProjectSurveyRecord entities. Args: request: Django Request object entities: list of GradingProjectSurveyRecord entities to update context: the context of this task """ entities = _runSurveyRecordUpdate(entities, grading_survey_logic) return _runOrgSurveyRe...
task """ entities = _runSurveyRecordUpdate(entities, project_survey_logic) return _runOrgSurveyRecordUpdate(entities) @decorators.iterative_task(grading_record_logic) def runGradingProjectSurveyRecordUpdate(request, entities, context, *args, **kwargs):
64
64
109
33
31
MatthewWilkes/mw4068-packaging
src/melange/src/soc/tasks/updates/module_conversion.py
Python
runGradingProjectSurveyRecordUpdate
runGradingProjectSurveyRecordUpdate
522
535
522
524
40603bc92710e3636fdf6b8c41c3d58fda8e128e
bigcode/the-stack
train
0647c8b100581b1b9167ac63
train
function
def _runOrgSurveyRecordUpdate(entities): """AppEngine Task that updates SurveyRecord entities which refer to an organization. In particular, these are GradingProjectSurvey and ProjectSurvey records. Args: entities: list of SurveyRecord entities to update """ from soc.modules.gsoc.logic.models.organiza...
def _runOrgSurveyRecordUpdate(entities):
"""AppEngine Task that updates SurveyRecord entities which refer to an organization. In particular, these are GradingProjectSurvey and ProjectSurvey records. Args: entities: list of SurveyRecord entities to update """ from soc.modules.gsoc.logic.models.organization import logic as org_logic cached_...
: survey_entity = survey_logic.getFromKeyName(survey_key_name) cached_surveys[survey_key_name] = survey_entity entity.survey = survey_entity db.put(entities) # task completed, return return entities def _runOrgSurveyRecordUpdate(entities):
64
64
169
10
53
MatthewWilkes/mw4068-packaging
src/melange/src/soc/tasks/updates/module_conversion.py
Python
_runOrgSurveyRecordUpdate
_runOrgSurveyRecordUpdate
569
595
569
569
862d588550f90ae4e8a7e3849610716ad462cfad
bigcode/the-stack
train
73c88d1d25eae7e0b1bb712a
train
function
def startUpdateWithUrl(request, task_url): """Spawns an update task for the given task URL. Args: request: Django Request object task_url: The URL used to run this update task Returns: True iff the new task is successfully added to the Task Queue API """ new_task = taskqueue.Task(url=task_url) ...
def startUpdateWithUrl(request, task_url):
"""Spawns an update task for the given task URL. Args: request: Django Request object task_url: The URL used to run this update task Returns: True iff the new task is successfully added to the Task Queue API """ new_task = taskqueue.Task(url=task_url) new_task.add() return True
.modules.gsoc.logic.models.student_project import logic as \ student_project_logic from soc.modules.gsoc.logic.models.student_proposal import logic as \ student_proposal_logic # batch size to use when going through the entities DEF_BATCH_SIZE = 10 def startUpdateWithUrl(request, task_url):
64
64
87
10
53
MatthewWilkes/mw4068-packaging
src/melange/src/soc/tasks/updates/module_conversion.py
Python
startUpdateWithUrl
startUpdateWithUrl
64
78
64
64
11c4d0ffa651cd5ef28a75c6a2bfc4b5883306a4
bigcode/the-stack
train
4c5684c28cd7afa15be32c5d
train
function
def _runSurveyUpdate(entities, logic): """AppEngine Task that updates Survey entities. Args: entities: list of Survey entities to update logic: concrete logic instance which the surveys are to be updated for Returns: A list of pairs that maps the old surveys with the corresponding new ones. """ ...
def _runSurveyUpdate(entities, logic):
"""AppEngine Task that updates Survey entities. Args: entities: list of Survey entities to update logic: concrete logic instance which the surveys are to be updated for Returns: A list of pairs that maps the old surveys with the corresponding new ones. """ from soc.modules.gsoc.logic.models.pro...
_logic) def runGradingProjectSurveyUpdate(request, entities, context, *args, **kwargs): """AppEngine Task that updates GradingProjectSurvey entities. Args: request: Django Request object entities: list of GradingProjectSurvey entities to update context: the context of this task """ return _runSurv...
92
92
307
10
82
MatthewWilkes/mw4068-packaging
src/melange/src/soc/tasks/updates/module_conversion.py
Python
_runSurveyUpdate
_runSurveyUpdate
448
491
448
448
4a06b098c44e01c5fcc60a91c226a2df85a3020f
bigcode/the-stack
train
52e5b1ac52594c49c1b00b27
train
function
@decorators.iterative_task(grading_survey_logic) def runGradingProjectSurveyUpdate(request, entities, context, *args, **kwargs): """AppEngine Task that updates GradingProjectSurvey entities. Args: request: Django Request object entities: list of GradingProjectSurvey entities to update context: the cont...
@decorators.iterative_task(grading_survey_logic) def runGradingProjectSurveyUpdate(request, entities, context, *args, **kwargs):
"""AppEngine Task that updates GradingProjectSurvey entities. Args: request: Django Request object entities: list of GradingProjectSurvey entities to update context: the context of this task """ return _runSurveyUpdate(entities, grading_survey_logic)
list of ProjectSurvey entities to update context: the context of this task """ return _runSurveyUpdate(entities, project_survey_logic) @decorators.iterative_task(grading_survey_logic) def runGradingProjectSurveyUpdate(request, entities, context, *args, **kwargs):
64
64
92
31
33
MatthewWilkes/mw4068-packaging
src/melange/src/soc/tasks/updates/module_conversion.py
Python
runGradingProjectSurveyUpdate
runGradingProjectSurveyUpdate
435
445
435
436
4a63eb72e56c4bee2899be4e82ea93c7a3fff804
bigcode/the-stack
train
aa9147c40772acfd398645e6
train
function
@decorators.iterative_task(review_logic) def runReviewUpdate(request, entities, context, *args, **kwargs): """AppEngine Task that updates Review entities. Args: request: Django Request object entities: list of Review entities to update context: the context of this task """ for entity in entities: ...
@decorators.iterative_task(review_logic) def runReviewUpdate(request, entities, context, *args, **kwargs):
"""AppEngine Task that updates Review entities. Args: request: Django Request object entities: list of Review entities to update context: the context of this task """ for entity in entities: entity.reviewer = None # store all Reviews db.put(entities) # task completed, return return
mentor.key()) entity.possible_mentors = new_mentors # store all StudentProposal db.put(entities) # task completed, return return @decorators.iterative_task(review_logic) def runReviewUpdate(request, entities, context, *args, **kwargs):
64
64
101
25
38
MatthewWilkes/mw4068-packaging
src/melange/src/soc/tasks/updates/module_conversion.py
Python
runReviewUpdate
runReviewUpdate
349
366
349
350
bdb920b50cbe280bf3e51bed18f1f5dd313cff61
bigcode/the-stack
train
35fcda0b3de0a4f5557f7089
train
function
@decorators.iterative_task(record_logic) def runSurveyRecordUpdate(request, entities, context, *args, **kwargs): """AppEngine Task that updates ProjectSurveyRecord entities. Args: request: Django Request object entities: list of SurveyRecord entities to update context: the context of this task """ ...
@decorators.iterative_task(record_logic) def runSurveyRecordUpdate(request, entities, context, *args, **kwargs):
"""AppEngine Task that updates ProjectSurveyRecord entities. Args: request: Django Request object entities: list of SurveyRecord entities to update context: the context of this task """ return _runSurveyRecordUpdate(entities, survey_logic)
gsoc_program' new_surveys.append(new_survey) # batch put the new Surveys db.put(new_surveys) # task completed, return return @decorators.iterative_task(record_logic) def runSurveyRecordUpdate(request, entities, context, *args, **kwargs):
64
64
83
26
37
MatthewWilkes/mw4068-packaging
src/melange/src/soc/tasks/updates/module_conversion.py
Python
runSurveyRecordUpdate
runSurveyRecordUpdate
494
504
494
495
77e1c7731662f2cb02321cd241c5bcc3ea85cab0
bigcode/the-stack
train
3f5d665d68189a6ea8ef85e1
train
function
@decorators.iterative_task(org_logic) def runOrgConversionUpdate(request, entities, context, *args, **kwargs): """AppEngine Task that converts Organizations into GSoCOrganizations. Also updates the RankerRoots that are associated with the Organization. Args: request: Django Request object entities: list...
@decorators.iterative_task(org_logic) def runOrgConversionUpdate(request, entities, context, *args, **kwargs):
"""AppEngine Task that converts Organizations into GSoCOrganizations. Also updates the RankerRoots that are associated with the Organization. Args: request: Django Request object entities: list of Organization entities to convert context: the context of this task """ from soc.modules.gsoc.logic...
_properties = {} for program_property in program_properties: # copy over all the information from the program entity gsoc_properties[program_property] = getattr(entity, program_property) # create the new GSoCProgram entity and prepare it to be stored gsoc_program_entity = GSoCProgram(key_name=...
145
145
485
26
118
MatthewWilkes/mw4068-packaging
src/melange/src/soc/tasks/updates/module_conversion.py
Python
runOrgConversionUpdate
runOrgConversionUpdate
119
177
119
120
614df9886865f83a24c290d6299e730672a5525e
bigcode/the-stack
train
c127fd2bf9b0fa1b0a27837b
train
function
@decorators.iterative_task(timeline_logic) def runTimelineConversionUpdate(request, entities, context, *args, **kwargs): """AppEngine Task that converts Timelines into GSoCTimelines. It also updates all GSoCPrograms with a reference to the new GSoCTimeline. Args: request: Django Request object entities:...
@decorators.iterative_task(timeline_logic) def runTimelineConversionUpdate(request, entities, context, *args, **kwargs):
"""AppEngine Task that converts Timelines into GSoCTimelines. It also updates all GSoCPrograms with a reference to the new GSoCTimeline. Args: request: Django Request object entities: list of Timeline entities to convert context: the context of this task """ from soc.modules.gsoc.models.timelin...
KeyNameFromFields(new_document_properties), **new_document_properties) documents.append(new_document_entity) if entity.home_for: # update the presence for which this document was the home page presence_entity.home = new_document_entity presences.append(presence_entity) # store all ...
121
121
404
27
93
MatthewWilkes/mw4068-packaging
src/melange/src/soc/tasks/updates/module_conversion.py
Python
runTimelineConversionUpdate
runTimelineConversionUpdate
702
749
702
703
33e10490ee78081c0c862dd6f9f32ec91de2a167
bigcode/the-stack
train