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
1970c0483817a13578c4befb
train
function
@pytest.mark.unit def test_cell_nmoles(instance): """Test calculation of cell.""" result = instance.calculate( input_n_molecules=1, input_n_atoms=1, input_mass=input_mass, size=Q_(10, "Å"), n_moles=Q_(n_atoms / n_A, "mol"), ) assert abs(result["density"].magnitude...
@pytest.mark.unit def test_cell_nmoles(instance):
"""Test calculation of cell.""" result = instance.calculate( input_n_molecules=1, input_n_atoms=1, input_mass=input_mass, size=Q_(10, "Å"), n_moles=Q_(n_atoms / n_A, "mol"), ) assert abs(result["density"].magnitude - density) < 0.000001
_n_molecules=1, input_n_atoms=1, input_mass=input_mass, size=Q_(10, "Å"), density=Q_(density, "g/ml"), ) assert result["n_atoms"] == 100 @pytest.mark.unit def test_cell_nmoles(instance):
64
64
92
11
52
molssi-seamm/packmol_step
tests/test_calculate.py
Python
test_cell_nmoles
test_cell_nmoles
70
80
70
71
89c081c504d1057456c254fa1f8e67726ff7173e
bigcode/the-stack
train
bc96636127057e4407728ce0
train
function
@pytest.fixture def instance(): instance = packmol_step.Packmol() instance._id = (1,) return instance
@pytest.fixture def instance():
instance = packmol_step.Packmol() instance._id = (1,) return instance
^6 ml / m^3 input_mass = m_Ar * ureg.g / ureg.mol input_mass.ito("kg") molar_volume = 22.710954641485 # L rho_stp = m_Ar / molar_volume @pytest.fixture def instance():
64
64
28
6
57
molssi-seamm/packmol_step
tests/test_calculate.py
Python
instance
instance
24
28
24
25
d48c18dd516207d1458e90dcd5d52fb2015a2198
bigcode/the-stack
train
81121ba94feb81551fd97e3c
train
function
@pytest.mark.unit def test_density_nmolecules(instance): """Test calculation of cell.""" result = instance.calculate( input_n_molecules=1, input_n_atoms=1, input_mass=input_mass, density=Q_(density, "g/ml"), n_molecules=100, ) assert abs(result["size"].magnitude -...
@pytest.mark.unit def test_density_nmolecules(instance):
"""Test calculation of cell.""" result = instance.calculate( input_n_molecules=1, input_n_atoms=1, input_mass=input_mass, density=Q_(density, "g/ml"), n_molecules=100, ) assert abs(result["size"].magnitude - 10.0) < 0.000001
input_n_atoms=1, input_mass=input_mass, volume=Q_(1000, "Å**3"), n_molecules=100, ) assert abs(result["density"].magnitude - density) < 0.000001 @pytest.mark.unit def test_density_nmolecules(instance):
64
64
87
11
52
molssi-seamm/packmol_step
tests/test_calculate.py
Python
test_density_nmolecules
test_density_nmolecules
109
119
109
110
1aa5dba55c458d66c9baa5c136dd21faedff44da
bigcode/the-stack
train
00aaca0b1ba48e3b919e1f29
train
function
def sigmoid_focal_loss( inputs: torch.Tensor, targets: torch.Tensor, alpha: float = 0.25, gamma: float = 2, reduction: str = "none", ): """ Original implementation from https://github.com/facebookresearch/fvcore/blob/master/fvcore/nn/focal_loss.py . Loss used in RetinaNet for dense detec...
def sigmoid_focal_loss( inputs: torch.Tensor, targets: torch.Tensor, alpha: float = 0.25, gamma: float = 2, reduction: str = "none", ):
""" Original implementation from https://github.com/facebookresearch/fvcore/blob/master/fvcore/nn/focal_loss.py . Loss used in RetinaNet for dense detection: https://arxiv.org/abs/1708.02002. Args: inputs: A float tensor of arbitrary shape. The predictions for each example. ...
import torch import torch.nn.functional as F def sigmoid_focal_loss( inputs: torch.Tensor, targets: torch.Tensor, alpha: float = 0.25, gamma: float = 2, reduction: str = "none", ):
55
122
408
45
9
iselic/vision
torchvision/ops/focal_loss.py
Python
sigmoid_focal_loss
sigmoid_focal_loss
5
49
5
11
4de154ca348d1ddc824338b2f8f3f76df4721f24
bigcode/the-stack
train
eca9a35181da9108b86aa70e
train
class
class MainScreen: def __init__(self): self.reset() def update(self): if self.game_over: if pyxel.btnp(pyxel.KEY_R): self.reset() self.game_over = False return if pyxel.btn(pyxel.KEY_DOWN) or pyxel.btn(pyxel.GAMEPAD_1_DOWN): ...
class MainScreen:
def __init__(self): self.reset() def update(self): if self.game_over: if pyxel.btnp(pyxel.KEY_R): self.reset() self.game_over = False return if pyxel.btn(pyxel.KEY_DOWN) or pyxel.btn(pyxel.GAMEPAD_1_DOWN): self.leotti....
from combination_wall import ConbinationWall from constants import WIDTH, HEIGHT, UP, DOWN, NORMAL, SPECIAL from coin import Coin from wall import Wall import pyxel from leotti import Leotti from typing import List class MainScreen:
53
137
457
4
48
leocody/Super-Leotti-Bros
main_screen.py
Python
MainScreen
MainScreen
10
82
10
10
8afbd73ef2bbdc88e1b42642c59eccf688b8ad76
bigcode/the-stack
train
8492151088e03b23de25da53
train
function
def transliterate(string): capital_letters = {u'А': u'A', u'Б': u'B', u'В': u'V', u'Г': u'G', u'Д': u'D', u'Е': u'E', u'Ё': u'E', u'Ж': u'Zh', ...
def transliterate(string):
capital_letters = {u'А': u'A', u'Б': u'B', u'В': u'V', u'Г': u'G', u'Д': u'D', u'Е': u'E', u'Ё': u'E', u'Ж': u'Zh', u'З': u'Z', ...
# -*- coding: utf-8 -*- def transliterate(string):
13
200
669
5
8
Lavabar/Hack-VK-Sample-Name
translit_v1.py
Python
transliterate
transliterate
3
87
3
4
6f26595c9d7d5bf7809b0b7f937f2082fd937197
bigcode/the-stack
train
dcb757722d85c59fe3628ea1
train
function
def non_max_suppression(boxes, max_bbox_overlap, scores=None): """Suppress overlapping detections. Original code from [1]_ has been adapted to include confidence score. .. [1] http://www.pyimagesearch.com/2015/02/16/ faster-non-maximum-suppression-python/ Examples -------- ...
def non_max_suppression(boxes, max_bbox_overlap, scores=None):
"""Suppress overlapping detections. Original code from [1]_ has been adapted to include confidence score. .. [1] http://www.pyimagesearch.com/2015/02/16/ faster-non-maximum-suppression-python/ Examples -------- >>> boxes = [d.roi for d in detections] >>> sco...
# vim: expandtab:ts=4:sw=4 import numpy as np import cv2 def non_max_suppression(boxes, max_bbox_overlap, scores=None):
39
160
535
16
22
tenghehan/reid_without_id
deep_sort/sort/preprocessing.py
Python
non_max_suppression
non_max_suppression
6
73
6
6
7a4c07ca57435f7ee27c930aba248d7af7646f5d
bigcode/the-stack
train
73b883bfc6891456561d5b5b
train
class
class Solution: def countPairs(self, root: TreeNode, distance: int) -> int: return self._count(root, distance)[0] def _count(self, root, distance): if not root: return 0, {} if not root.left and not root.right: return 0, {0: 1} lc, ld = self._count(ro...
class Solution:
def countPairs(self, root: TreeNode, distance: int) -> int: return self._count(root, distance)[0] def _count(self, root, distance): if not root: return 0, {} if not root.left and not root.right: return 0, {0: 1} lc, ld = self._count(root.left, distanc...
class Solution:
3
64
184
3
0
YiqunPeng/leetcode_pro
solutions/1530_number_of_good_leaf_nodes_pairs.py
Python
Solution
Solution
1
20
1
1
3a7d1d37f548a42d7b83cdf5f261e94176f16b88
bigcode/the-stack
train
2996c7096022c778c1e173de
train
function
def selected_finer_threshold_by_park(park): if park == "QENP": return np.arange(0, 0.5, 0.1) elif park == "MFNP": return np.arange(0, 0.5, 0.1) elif park == "CRNP": return np.arange(0, 0.5, 0.1) elif park == "Gonarezhou": return np.arange(0, 1.5, 0.5) elif park == "AM...
def selected_finer_threshold_by_park(park):
if park == "QENP": return np.arange(0, 0.5, 0.1) elif park == "MFNP": return np.arange(0, 0.5, 0.1) elif park == "CRNP": return np.arange(0, 0.5, 0.1) elif park == "Gonarezhou": return np.arange(0, 1.5, 0.5) elif park == "AMWS": return np.arange(0, 0.5, 0.1) ...
5) # for full data return np.arange(0, 5, 0.3)# for rainy/dry data elif park == "SWS": return np.arange(0, 12, 0.5) # for full data else: raise Exception("Park '{}' not implemented.".format(park)) # used to predict on static data def selected_finer_threshold_by_park(park):
93
93
311
11
81
lily-x/PAWS-public
planning/util.py
Python
selected_finer_threshold_by_park
selected_finer_threshold_by_park
53
76
53
53
5e0f2e0c2884757fb40b24442a25efe4b7f40b64
bigcode/the-stack
train
8c35af4f35ffc9afb69c4dfa
train
function
def test_year_quarter_by_park(park): if park == "Gonarezhou" or park == "mbe" or park == "mbe_gun" or park == "CRNP": return 2018, 1 elif park == "AMWS": return 2017, 4 elif park == "MFNP" or park == "QENP": return 2015, None elif park == "Mondulkiri": return 2017, 4 ...
def test_year_quarter_by_park(park):
if park == "Gonarezhou" or park == "mbe" or park == "mbe_gun" or park == "CRNP": return 2018, 1 elif park == "AMWS": return 2017, 4 elif park == "MFNP" or park == "QENP": return 2015, None elif park == "Mondulkiri": return 2017, 4 elif park == "Dja": return 20...
# ============================ libraries ===================================== import numpy as np ### ========================== functions ===================================== def test_year_quarter_by_park(park):
28
64
179
11
17
lily-x/PAWS-public
planning/util.py
Python
test_year_quarter_by_park
test_year_quarter_by_park
6
22
6
6
1c5a6f33efd97bf3c0ad109ba7bed6f6a7cd850b
bigcode/the-stack
train
0617e8ba3b090f9410d94ab8
train
function
def selected_threshold_by_park(park): if park == "QENP": return np.arange(0, 8, 0.5) elif park == "MFNP": return np.arange(0, 8, 0.5) elif park == "CRNP": return np.arange(0, 1.2, 0.1) elif park == "Gonarezhou": return np.arange(0, 15, 1.5) elif park == "AMWS": ...
def selected_threshold_by_park(park):
if park == "QENP": return np.arange(0, 8, 0.5) elif park == "MFNP": return np.arange(0, 8, 0.5) elif park == "CRNP": return np.arange(0, 1.2, 0.1) elif park == "Gonarezhou": return np.arange(0, 15, 1.5) elif park == "AMWS": return np.arange(0, 1.2, 0.05) e...
"Mondulkiri": return 2017, 4 elif park == "Dja": return 2018, 1 elif park == "MPF": return 2017, 1 elif park == "SWS": return 2018, 1 else: raise Exception("Park '{}' not implemented.".format(park)) # TODO: kai says this may not be used anymore def selected_thre...
102
102
343
9
92
lily-x/PAWS-public
planning/util.py
Python
selected_threshold_by_park
selected_threshold_by_park
25
50
25
25
3f99cd244727487164366b35150e64a990805fac
bigcode/the-stack
train
51640cb6d5d9a95472353780
train
function
def prmt_cast_to_int_p(pointer): return cast(pointer, POINTER(c_int))
def prmt_cast_to_int_p(pointer):
return cast(pointer, POINTER(c_int))
malloc_wrapper = CDLL('%s/libmalloc_wrapper.so.0.1'%cwd) malloc_wrapper.prmt_malloc(byref(mem_pointer), n_bytes) return mem_pointer def prmt_cast_to_double_p(pointer): return cast(pointer, POINTER(c_double)) def prmt_cast_to_int_p(pointer):
64
64
18
9
55
kokizzu/prometeo
prometeo/old_mem/malloc_wrapper.py
Python
prmt_cast_to_int_p
prmt_cast_to_int_p
15
16
15
15
f4d89765a45a39de4c8ac8afbf8b208ef8dd78ff
bigcode/the-stack
train
f0da10ce3970b4d243e6513a
train
function
def prmt_cast_to_double_p(pointer): return cast(pointer, POINTER(c_double))
def prmt_cast_to_double_p(pointer):
return cast(pointer, POINTER(c_double))
(n_bytes): mem_pointer = c_void_p() cwd = os.getcwd() malloc_wrapper = CDLL('%s/libmalloc_wrapper.so.0.1'%cwd) malloc_wrapper.prmt_malloc(byref(mem_pointer), n_bytes) return mem_pointer def prmt_cast_to_double_p(pointer):
64
64
18
9
54
kokizzu/prometeo
prometeo/old_mem/malloc_wrapper.py
Python
prmt_cast_to_double_p
prmt_cast_to_double_p
12
13
12
12
da09b27aeefbeb8996356fb63a85f0a799dbd915
bigcode/the-stack
train
ffc41406ca32b848e6c99bfb
train
function
def prmt_malloc(n_bytes): mem_pointer = c_void_p() cwd = os.getcwd() malloc_wrapper = CDLL('%s/libmalloc_wrapper.so.0.1'%cwd) malloc_wrapper.prmt_malloc(byref(mem_pointer), n_bytes) return mem_pointer
def prmt_malloc(n_bytes):
mem_pointer = c_void_p() cwd = os.getcwd() malloc_wrapper = CDLL('%s/libmalloc_wrapper.so.0.1'%cwd) malloc_wrapper.prmt_malloc(byref(mem_pointer), n_bytes) return mem_pointer
from ctypes import * import os def prmt_malloc(n_bytes):
14
64
59
7
6
kokizzu/prometeo
prometeo/old_mem/malloc_wrapper.py
Python
prmt_malloc
prmt_malloc
4
9
4
4
5ae7a2d5149474da7c97ce03fa971eb571044d9c
bigcode/the-stack
train
ef2815a087f6eba6adf2337f
train
function
def update_line(num, data, line): line.set_data(data[..., :num]) return line,
def update_line(num, data, line):
line.set_data(data[..., :num]) return line,
import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation def update_line(num, data, line):
26
64
22
9
16
fizisist/computational-physics-portsmouth
GraphicsVisualisation/basic_animation_example.py
Python
update_line
update_line
6
8
6
6
5a0d2621de9d5b68b70b4d05c3c110219da61208
bigcode/the-stack
train
b51bc5b94ef743ad765a8837
train
class
class Migration(migrations.Migration): dependencies = [ ('web', '0004_auto_20180831_1901'), ] operations = [ migrations.AddField( model_name='data', name='Downloads', field=models.IntegerField(default=0, verbose_name='下载量'), ), migrations...
class Migration(migrations.Migration):
dependencies = [ ('web', '0004_auto_20180831_1901'), ] operations = [ migrations.AddField( model_name='data', name='Downloads', field=models.IntegerField(default=0, verbose_name='下载量'), ), migrations.AddField( model_name='data'...
# Generated by Django 2.0.5 on 2018-09-01 02:57 from django.db import migrations, models class Migration(migrations.Migration):
38
64
102
7
30
Organ-xiangjikeji/---
web/migrations/0005_auto_20180901_1057.py
Python
Migration
Migration
6
23
6
7
35f8ea6340ab1a622b93bd48c678c1cdfbe1b049
bigcode/the-stack
train
7a5e80c9ec19bbcfd2ec4b70
train
class
class Normalize(Layer): """Normalization layer as described in ParseNet paper. # Arguments scale: Default feature scale. # Input shape 4D tensor with shape: `(samples, channels, rows, cols)` if dim_ordering='th' or 4D tensor with shape: `(samples, rows, cols, channe...
class Normalize(Layer):
"""Normalization layer as described in ParseNet paper. # Arguments scale: Default feature scale. # Input shape 4D tensor with shape: `(samples, channels, rows, cols)` if dim_ordering='th' or 4D tensor with shape: `(samples, rows, cols, channels)` if dim_ordering='tf...
"""Some special pupropse layers for SSD.""" import keras.backend as K from keras.engine.topology import InputSpec from keras.engine.topology import Layer import numpy as np import tensorflow as tf class Normalize(Layer):
48
101
339
5
42
generalized-intelligence/Tegu
Network/SSD300/ssd_layers.py
Python
Normalize
Normalize
10
55
10
10
ca596ebe297d623285c38e6d0c826cb962468c38
bigcode/the-stack
train
f38c81a61517fb468121d7a6
train
class
class PriorBox(Layer): """Generate the prior boxes of designated sizes and aspect ratios. # Arguments img_size: Size of the input image as tuple (w, h). min_size: Minimum box size in pixels. max_size: Maximum box size in pixels. aspect_ratios: List of aspect ratios of boxes. ...
class PriorBox(Layer):
"""Generate the prior boxes of designated sizes and aspect ratios. # Arguments img_size: Size of the input image as tuple (w, h). min_size: Minimum box size in pixels. max_size: Maximum box size in pixels. aspect_ratios: List of aspect ratios of boxes. flip: Whether to c...
as input # References http://cs.unc.edu/~wliu/papers/parsenet.pdf #TODO Add possibility to have one scale for all features. """ def __init__(self,scale, **kwargs): if K.image_dim_ordering() == 'tf': self.axis = 3 else: self.axis = 1 sel...
255
256
1,432
6
249
generalized-intelligence/Tegu
Network/SSD300/ssd_layers.py
Python
PriorBox
PriorBox
58
199
58
58
0761d288a27c199eedb4108fdfc3b352437ad038
bigcode/the-stack
train
c98de1e205aeb69d8eaa8a26
train
class
class QuestionDetailViewTests(TestCase): def test_future_question(self): """ The detail view of a question with a pub_date in the future returns a 404 not found. """ future_question = create_question(question_text='Future question.', days=5) url = reverse('polls:detai...
class QuestionDetailViewTests(TestCase):
def test_future_question(self): """ The detail view of a question with a pub_date in the future returns a 404 not found. """ future_question = create_question(question_text='Future question.', days=5) url = reverse('polls:detail', args=(future_question.id,)) r...
.", days=-5) response = self.client.get(reverse('polls:index')) self.assertQuerysetEqual( response.context['latest_question_list'], ['<Question: Past question 2.>', '<Question: Past question 1.>'] ) class QuestionDetailViewTests(TestCase):
63
64
178
8
55
jousepandrex/Django
env/lib/python3.6/site-packages/polls/tests.py
Python
QuestionDetailViewTests
QuestionDetailViewTests
108
127
108
108
75348a652af2ec79e8abd4bdba610c0491cd40d8
bigcode/the-stack
train
974f5a6b8a3878abc088dd42
train
class
class QuestionIndexViewTests(TestCase): def test_no_questions(self): """ If no questions exist, an appropriate message is displayed. """ response = self.client.get(reverse('polls:index')) self.assertEqual(response.status_code, 200) self.assertContains(response, "No po...
class QuestionIndexViewTests(TestCase):
def test_no_questions(self): """ If no questions exist, an appropriate message is displayed. """ response = self.client.get(reverse('polls:index')) self.assertEqual(response.status_code, 200) self.assertContains(response, "No polls are available.") self.assert...
.timedelta(hours=23, minutes=59, seconds=59) recent_question = Question(pub_date=time) self.assertIs(recent_question.was_published_recently(), True) def create_question(question_text, days): """ Create a question with the given `question_text` and published the given number of `days` offse...
132
132
443
8
124
jousepandrex/Django
env/lib/python3.6/site-packages/polls/tests.py
Python
QuestionIndexViewTests
QuestionIndexViewTests
51
106
51
51
59167cf30cccf8556c91353f847b90f6cb468589
bigcode/the-stack
train
2dc542d1e2cbe70134de4a7b
train
function
def create_question(question_text, days): """ Create a question with the given `question_text` and published the given number of `days` offset to now (negative for questions published in the past, positive for questions that have yet to be published). """ time = timezone.now() + datetime.timedel...
def create_question(question_text, days):
""" Create a question with the given `question_text` and published the given number of `days` offset to now (negative for questions published in the past, positive for questions that have yet to be published). """ time = timezone.now() + datetime.timedelta(days=days) return Question.objects....
is within the last day. """ time = timezone.now() - datetime.timedelta(hours=23, minutes=59, seconds=59) recent_question = Question(pub_date=time) self.assertIs(recent_question.was_published_recently(), True) def create_question(question_text, days):
63
64
86
8
55
jousepandrex/Django
env/lib/python3.6/site-packages/polls/tests.py
Python
create_question
create_question
41
48
41
41
d5e0d3a5bad74d3f0b513837d5780f58fadde50e
bigcode/the-stack
train
9a72ae9204df08abbf588378
train
class
class QuestionModelTests(TestCase): def test_was_published_recently_with_future_question(self): """ was_published_recently() returns False for questions whose pub_date is in the future. """ time = timezone.now() + datetime.timedelta(days=30) future_question = Questio...
class QuestionModelTests(TestCase):
def test_was_published_recently_with_future_question(self): """ was_published_recently() returns False for questions whose pub_date is in the future. """ time = timezone.now() + datetime.timedelta(days=30) future_question = Question(pub_date=time) self.assertI...
import datetime from django.test import TestCase from django.utils import timezone from django.urls import reverse from .models import Question class QuestionModelTests(TestCase):
35
64
83
7
27
jousepandrex/Django
env/lib/python3.6/site-packages/polls/tests.py
Python
QuestionModelTests
QuestionModelTests
10
19
10
11
f1a356a4f892e16d91ab3ff1ed89fc40bce00d7b
bigcode/the-stack
train
7c67f8ac36860438925b378d
train
function
def test_was_published_recently_with_recent_question(self): """ was_published_recently() returns True for questions whose pub_date is within the last day. """ time = timezone.now() - datetime.timedelta(hours=23, minutes=59, seconds=59) recent_question = Question(pub_date=time) self.assertIs(...
def test_was_published_recently_with_recent_question(self):
""" was_published_recently() returns True for questions whose pub_date is within the last day. """ time = timezone.now() - datetime.timedelta(hours=23, minutes=59, seconds=59) recent_question = Question(pub_date=time) self.assertIs(recent_question.was_published_recently(), True)
is older than 1 day. """ time = timezone.now() - datetime.timedelta(days=1, seconds=1) old_question = Question(pub_date=time) self.assertIs(old_question.was_published_recently(), False) def test_was_published_recently_with_recent_question(self):
64
64
84
13
51
jousepandrex/Django
env/lib/python3.6/site-packages/polls/tests.py
Python
test_was_published_recently_with_recent_question
test_was_published_recently_with_recent_question
31
38
31
31
73d5759be46b875744ad704d5ca05377d0a4ce6d
bigcode/the-stack
train
7fcc60f7d375f2ceea40f472
train
function
def test_was_published_recently_with_old_question(self): """ was_published_recently() returns False for questions whose pub_date is older than 1 day. """ time = timezone.now() - datetime.timedelta(days=1, seconds=1) old_question = Question(pub_date=time) self.assertIs(old_question.was_publis...
def test_was_published_recently_with_old_question(self):
""" was_published_recently() returns False for questions whose pub_date is older than 1 day. """ time = timezone.now() - datetime.timedelta(days=1, seconds=1) old_question = Question(pub_date=time) self.assertIs(old_question.was_published_recently(), False)
whose pub_date is in the future. """ time = timezone.now() + datetime.timedelta(days=30) future_question = Question(pub_date=time) self.assertIs(future_question.was_published_recently(), False) def test_was_published_recently_with_old_question(self):
62
64
80
13
49
jousepandrex/Django
env/lib/python3.6/site-packages/polls/tests.py
Python
test_was_published_recently_with_old_question
test_was_published_recently_with_old_question
22
29
22
22
e7f84e0df6c7cbeca90bb77846de4324650b6a7e
bigcode/the-stack
train
f40efa95e5ecb5de925adfca
train
function
def set_url_and_password(rancher_url, server_url=None): admin_token = set_url_password_token(rancher_url, server_url) admin_client = rancher.Client(url=rancher_url + "/v3", token=admin_token, verify=False) auth_url = rancher_url + "/v3-public/localproviders/local?action=log...
def set_url_and_password(rancher_url, server_url=None):
admin_token = set_url_password_token(rancher_url, server_url) admin_client = rancher.Client(url=rancher_url + "/v3", token=admin_token, verify=False) auth_url = rancher_url + "/v3-public/localproviders/local?action=login" user, user_token = create_user(admin_client, aut...
file.close() def write_kubeconfig(): file = open(kubeconfig_path, "w") file.write(base64.b64decode(RANCHER_HA_KUBECONFIG).decode("utf-8")) file.close() def set_url_and_password(rancher_url, server_url=None):
64
64
155
14
50
danielmittelman/rancher
tests/validation/tests/v3_api/test_create_ha.py
Python
set_url_and_password
set_url_and_password
355
365
355
355
2a0c1f17d21ca72ddc1f4bb58ba8e910154a01b7
bigcode/the-stack
train
366dca699e72c647382ea7c7
train
function
def write_kubeconfig(): file = open(kubeconfig_path, "w") file.write(base64.b64decode(RANCHER_HA_KUBECONFIG).decode("utf-8")) file.close()
def write_kubeconfig():
file = open(kubeconfig_path, "w") file.write(base64.b64decode(RANCHER_HA_KUBECONFIG).decode("utf-8")) file.close()
(tls_command) if not valid_cert: run_command_with_stderr(ca_command) def write_encoded_certs(path, contents): file = open(path, "w") file.write(base64.b64decode(contents).decode("utf-8")) file.close() def write_kubeconfig():
64
64
47
6
58
danielmittelman/rancher
tests/validation/tests/v3_api/test_create_ha.py
Python
write_kubeconfig
write_kubeconfig
349
352
349
349
ed23fe339034e9187153134f6ad73fddeb3694c9
bigcode/the-stack
train
6ad8df4d9a582edd7b7b0290
train
function
def install_eks_ingress(): run_command_with_stderr(export_cmd + " && kubectl apply -f " + DATA_SUBDIR + "/eks_nlb.yml")
def install_eks_ingress():
run_command_with_stderr(export_cmd + " && kubectl apply -f " + DATA_SUBDIR + "/eks_nlb.yml")
cert-manager") run_command_with_stderr(export_cmd + " && " + "helm_v3 install cert-manager " "jetstack/cert-manager " "--namespace cert-manager " "--version {0}".format(CERT_MANAGER_VERSION)) time.sl...
64
64
36
7
57
danielmittelman/rancher
tests/validation/tests/v3_api/test_create_ha.py
Python
install_eks_ingress
install_eks_ingress
230
232
230
230
23561dccc5eefdf1326c6723b43381dcafb47635
bigcode/the-stack
train
a4028a5629d7f6419e11fb6b
train
function
def add_repo_create_namespace(repo=RANCHER_HELM_REPO): repo_name = "rancher-" + repo repo_url = "https://releases.rancher.com/server-charts/" + repo run_command_with_stderr("helm_v3 repo add " + repo_name + " " + repo_url) run_command_with_stderr("helm_v3 repo update") run_command_with_stderr(expor...
def add_repo_create_namespace(repo=RANCHER_HELM_REPO):
repo_name = "rancher-" + repo repo_url = "https://releases.rancher.com/server-charts/" + repo run_command_with_stderr("helm_v3 repo add " + repo_name + " " + repo_url) run_command_with_stderr("helm_v3 repo update") run_command_with_stderr(export_cmd + " && " + "kubectl c...
derr(export_cmd + " && " + kubectl_ingress).decode() AmazonWebServices().upsert_route_53_record_cname(RANCHER_HA_HOSTNAME, ingress_address) time.sleep(60) def add_repo...
64
64
105
15
49
danielmittelman/rancher
tests/validation/tests/v3_api/test_create_ha.py
Python
add_repo_create_namespace
add_repo_create_namespace
247
254
247
247
6ed733dee1e4d66aecde2e3cc205279527927c5b
bigcode/the-stack
train
64ab54fa155240b74af000f3
train
function
def create_resources(): # Create nlb and grab ARN & dns name lb = AmazonWebServices().create_network_lb(name=resource_prefix + "-nlb") lbArn = lb["LoadBalancers"][0]["LoadBalancerArn"] lbDns = lb["LoadBalancers"][0]["DNSName"] # Upsert the route53 record -- if it exists, update, if not, insert ...
def create_resources(): # Create nlb and grab ARN & dns name
lb = AmazonWebServices().create_network_lb(name=resource_prefix + "-nlb") lbArn = lb["LoadBalancers"][0]["LoadBalancerArn"] lbDns = lb["LoadBalancers"][0]["DNSName"] # Upsert the route53 record -- if it exists, update, if not, insert AmazonWebServices().upsert_route_53_record_cname(RANCHER_HA_HOSTN...
_roles[i], aws_node) aws_node.execute_command(docker_run_cmd) i += 1 validate_cluster(client, cluster, userToken=user_token) def test_upgrade_rancher_ha(precheck_upgrade_options): write_kubeconfig() add_repo_create_namespace() install_rancher(upgrade=True) def create_resources_eks():...
130
130
436
16
114
danielmittelman/rancher
tests/validation/tests/v3_api/test_create_ha.py
Python
create_resources
create_resources
170
209
170
171
a887e4b1144d4b9b3abfb79fb9b2b8abcc9b05cf
bigcode/the-stack
train
3e7e61ee3f6869538d659e53
train
function
def install_cert_manager(): manifests = "https://github.com/jetstack/cert-manager/releases/download/" \ "{0}/cert-manager.crds.yaml".format(CERT_MANAGER_VERSION) cm_repo = "https://charts.jetstack.io" run_command_with_stderr(export_cmd + " && kubectl apply -f " + manifests) run_command_...
def install_cert_manager():
manifests = "https://github.com/jetstack/cert-manager/releases/download/" \ "{0}/cert-manager.crds.yaml".format(CERT_MANAGER_VERSION) cm_repo = "https://charts.jetstack.io" run_command_with_stderr(export_cmd + " && kubectl apply -f " + manifests) run_command_with_stderr("helm_v3 repo ad...
in targets] AmazonWebServices().register_targets(targets_list, tg80Arn) targets_list = [dict(Id=target_id, Port=443) for target_id in targets] AmazonWebServices().register_targets(targets_list, tg443Arn) return aws_nodes def install_cert_manager():
64
64
179
5
58
danielmittelman/rancher
tests/validation/tests/v3_api/test_create_ha.py
Python
install_cert_manager
install_cert_manager
212
227
212
212
7aee667263e2487aacff3c5b4e52f53e60ad9544
bigcode/the-stack
train
bd4514d4e9b2fffb626508a5
train
function
def set_route53_with_eks_ingress(): kubectl_ingress = "kubectl get ingress -n cattle-system -o " \ "jsonpath=\"" \ "{.items[0].status.loadBalancer.ingress[0].hostname}\"" ingress_address = run_command_with_stderr(export_cmd ...
def set_route53_with_eks_ingress():
kubectl_ingress = "kubectl get ingress -n cattle-system -o " \ "jsonpath=\"" \ "{.items[0].status.loadBalancer.ingress[0].hostname}\"" ingress_address = run_command_with_stderr(export_cmd + " && " + ...
"--version {0}".format(CERT_MANAGER_VERSION)) time.sleep(120) def install_eks_ingress(): run_command_with_stderr(export_cmd + " && kubectl apply -f " + DATA_SUBDIR + "/eks_nlb.yml") def set_route53_with_eks_ingress():
64
64
110
10
54
danielmittelman/rancher
tests/validation/tests/v3_api/test_create_ha.py
Python
set_route53_with_eks_ingress
set_route53_with_eks_ingress
235
244
235
235
627a485100f62b2121a057f93591980f2d2b95fd
bigcode/the-stack
train
bf28974d98d8925622c17457
train
function
@pytest.fixture(scope='module') def precheck_certificate_options(): if RANCHER_HA_CERT_OPTION == 'byo-valid': if RANCHER_VALID_TLS_CERT == '' or \ RANCHER_VALID_TLS_KEY == '' or \ RANCHER_VALID_TLS_CERT is None or \ RANCHER_VALID_TLS_KEY is None: raise pytest.ski...
@pytest.fixture(scope='module') def precheck_certificate_options():
if RANCHER_HA_CERT_OPTION == 'byo-valid': if RANCHER_VALID_TLS_CERT == '' or \ RANCHER_VALID_TLS_KEY == '' or \ RANCHER_VALID_TLS_CERT is None or \ RANCHER_VALID_TLS_KEY is None: raise pytest.skip( 'Valid certificates not found in environment vari...
) print("cluster-ha-filled.yml: \n" + rkeconfig + "\n") clusterfilepath = DATA_SUBDIR + "/" + "cluster-ha-filled.yml" f = open(clusterfilepath, "w") f.write(rkeconfig) f.close() return clusterfilepath @pytest.fixture(scope='module') def precheck_certificate_options():
74
74
247
12
61
danielmittelman/rancher
tests/validation/tests/v3_api/test_create_ha.py
Python
precheck_certificate_options
precheck_certificate_options
414
436
414
415
ff1fce317ccdea509e5bd487e04aed54c30dbe41
bigcode/the-stack
train
3f359428fb6caf7af4433f40
train
function
def test_install_rancher_ha(precheck_certificate_options): cm_install = True extra_settings = [] if "byo-" in RANCHER_HA_CERT_OPTION: cm_install = False print("The hostname is: {}".format(RANCHER_HA_HOSTNAME)) # prepare an RKE cluster and other resources # if no kubeconfig file is provi...
def test_install_rancher_ha(precheck_certificate_options):
cm_install = True extra_settings = [] if "byo-" in RANCHER_HA_CERT_OPTION: cm_install = False print("The hostname is: {}".format(RANCHER_HA_HOSTNAME)) # prepare an RKE cluster and other resources # if no kubeconfig file is provided if RANCHER_HA_KUBECONFIG is None: if RANCHE...
"the CATTLE_TEST_URL need to end with .qa.rancher.space" if not check_if_ok(CATTLE_TEST_URL): print("skip deleting clusters within the setup") else: print("the CATTLE_TEST_URL is accessible") admin_token = get_user_token("admin", ADMIN_PASSWORD) client = get_client_for_token(adm...
195
195
652
13
182
danielmittelman/rancher
tests/validation/tests/v3_api/test_create_ha.py
Python
test_install_rancher_ha
test_install_rancher_ha
62
127
62
62
7a8d989d4a6fea1a0f840c9cc64f3389472defce
bigcode/the-stack
train
201acfad25aeb36774a761d0
train
function
def create_custom_cluster(admin_client): auth_url = RANCHER_SERVER_URL + \ "/v3-public/localproviders/local?action=login" wait_for_status_code(url=auth_url, expected_code=200) user, user_token = create_user(admin_client, auth_url) aws_nodes = \ AmazonWebServices().create_multiple_nodes(...
def create_custom_cluster(admin_client):
auth_url = RANCHER_SERVER_URL + \ "/v3-public/localproviders/local?action=login" wait_for_status_code(url=auth_url, expected_code=200) user, user_token = create_user(admin_client, auth_url) aws_nodes = \ AmazonWebServices().create_multiple_nodes( 5, random_test_name(resource...
admin_client = set_url_and_password(RANCHER_SERVER_URL) cluster = get_cluster_by_name(admin_client, "local") validate_cluster_state(admin_client, cluster, False) if RANCHER_ADD_CUSTOM_CLUSTER.upper() == "TRUE": print("creating an custom cluster") create_custom_cluster(admin_client) def crea...
73
73
245
7
66
danielmittelman/rancher
tests/validation/tests/v3_api/test_create_ha.py
Python
create_custom_cluster
create_custom_cluster
130
155
130
130
29d12939cbdd11191441c959a06b6db6e0acdb0a
bigcode/the-stack
train
fdca52cc4ada88f0b938346b
train
function
def install_rancher(type=RANCHER_HA_CERT_OPTION, repo=RANCHER_HELM_REPO, upgrade=False, extra_settings=None): operation = "install" if upgrade: operation = "upgrade" helm_rancher_cmd = \ export_cmd + " && helm_v3 " + operation + " rancher " + \ "rancher-" + repo...
def install_rancher(type=RANCHER_HA_CERT_OPTION, repo=RANCHER_HELM_REPO, upgrade=False, extra_settings=None):
operation = "install" if upgrade: operation = "upgrade" helm_rancher_cmd = \ export_cmd + " && helm_v3 " + operation + " rancher " + \ "rancher-" + repo + "/rancher " + \ "--version " + RANCHER_CHART_VERSION + " " + \ "--namespace cattle-system " + \ "--set ...
_record_cname(RANCHER_HA_HOSTNAME, ingress_address) time.sleep(60) def add_repo_create_namespace(repo=RANCHER_HELM_REPO): repo_name = "rancher-" + repo repo_url = "https://releases.rancher.com/server-charts/" + repo run_command_with_stderr("helm_v3...
159
159
533
33
126
danielmittelman/rancher
tests/validation/tests/v3_api/test_create_ha.py
Python
install_rancher
install_rancher
257
313
257
258
5c90a31db753a810c7a47dcc6944cc01e6ead714
bigcode/the-stack
train
f9b83207d32d5cca319a0d58
train
function
@pytest.fixture(scope='module') def precheck_upgrade_options(): if RANCHER_HA_KUBECONFIG == '' or RANCHER_HA_KUBECONFIG is None: raise pytest.skip('Kubeconfig is not found for upgrade!') if RANCHER_HA_HOSTNAME == '' or RANCHER_HA_HOSTNAME is None: raise pytest.skip('Hostname is not found for upg...
@pytest.fixture(scope='module') def precheck_upgrade_options():
if RANCHER_HA_KUBECONFIG == '' or RANCHER_HA_KUBECONFIG is None: raise pytest.skip('Kubeconfig is not found for upgrade!') if RANCHER_HA_HOSTNAME == '' or RANCHER_HA_HOSTNAME is None: raise pytest.skip('Hostname is not found for upgrade!')
A_CERT_OPTION == 'letsencrypt': if RANCHER_LETSENCRYPT_EMAIL == '' or \ RANCHER_LETSENCRYPT_EMAIL is None: raise pytest.skip( 'LetsEncrypt email is not found in environment variables') @pytest.fixture(scope='module') def precheck_upgrade_options():
64
64
88
12
52
danielmittelman/rancher
tests/validation/tests/v3_api/test_create_ha.py
Python
precheck_upgrade_options
precheck_upgrade_options
439
444
439
440
71d07c91c2fd4fbdd5d6ee6bad7d91df68c442db
bigcode/the-stack
train
0a57c5c2efa61a7674e78f5f
train
function
def print_kubeconfig(): kubeconfig_file = open(kubeconfig_path, "r") kubeconfig_contents = kubeconfig_file.read() kubeconfig_file.close() kubeconfig_contents_encoded = base64.b64encode( kubeconfig_contents.encode("utf-8")).decode("utf-8") print("\n\n" + kubeconfig_contents + "\n\n") prin...
def print_kubeconfig():
kubeconfig_file = open(kubeconfig_path, "r") kubeconfig_contents = kubeconfig_file.read() kubeconfig_file.close() kubeconfig_contents_encoded = base64.b64encode( kubeconfig_contents.encode("utf-8")).decode("utf-8") print("\n\n" + kubeconfig_contents + "\n\n") print("\nBase64 encoded: \n\...
user_token + "'\n" create_config_file(env_details) return admin_client def create_rke_cluster(config_path): rke_cmd = "rke --version && rke up --config " + config_path run_command_with_stderr(rke_cmd) def print_kubeconfig():
64
64
101
6
58
danielmittelman/rancher
tests/validation/tests/v3_api/test_create_ha.py
Python
print_kubeconfig
print_kubeconfig
373
380
373
373
cab02d20f965ce48799b77316758656db9f9edfe
bigcode/the-stack
train
cb50ae6be3ce06f8e9634526
train
function
def create_resources_eks(): cluster_name = resource_prefix + "-ekscluster" AmazonWebServices().create_eks_cluster(cluster_name) AmazonWebServices().wait_for_eks_cluster_state(cluster_name, "ACTIVE")
def create_resources_eks():
cluster_name = resource_prefix + "-ekscluster" AmazonWebServices().create_eks_cluster(cluster_name) AmazonWebServices().wait_for_eks_cluster_state(cluster_name, "ACTIVE")
_command(docker_run_cmd) i += 1 validate_cluster(client, cluster, userToken=user_token) def test_upgrade_rancher_ha(precheck_upgrade_options): write_kubeconfig() add_repo_create_namespace() install_rancher(upgrade=True) def create_resources_eks():
64
64
46
6
58
danielmittelman/rancher
tests/validation/tests/v3_api/test_create_ha.py
Python
create_resources_eks
create_resources_eks
164
167
164
164
cc835145162d289cf2ca898d7ac486ee41ea842c
bigcode/the-stack
train
7b7f46a2aaaff64de309ddf6
train
function
def create_rke_cluster_config(aws_nodes): configfile = "cluster-ha.yml" rkeconfig = readDataFile(DATA_SUBDIR, configfile) rkeconfig = rkeconfig.replace("$ip1", aws_nodes[0].public_ip_address) rkeconfig = rkeconfig.replace("$ip2", aws_nodes[1].public_ip_address) rkeconfig = rkeconfig.replace("$ip3",...
def create_rke_cluster_config(aws_nodes):
configfile = "cluster-ha.yml" rkeconfig = readDataFile(DATA_SUBDIR, configfile) rkeconfig = rkeconfig.replace("$ip1", aws_nodes[0].public_ip_address) rkeconfig = rkeconfig.replace("$ip2", aws_nodes[1].public_ip_address) rkeconfig = rkeconfig.replace("$ip3", aws_nodes[2].public_ip_address) rkec...
_file = open(kubeconfig_path, "r") kubeconfig_contents = kubeconfig_file.read() kubeconfig_file.close() kubeconfig_contents_encoded = base64.b64encode( kubeconfig_contents.encode("utf-8")).decode("utf-8") print("\n\n" + kubeconfig_contents + "\n\n") print("\nBase64 encoded: \n\n" + kubeconfi...
102
102
342
10
92
danielmittelman/rancher
tests/validation/tests/v3_api/test_create_ha.py
Python
create_rke_cluster_config
create_rke_cluster_config
383
411
383
383
f0056a6a7c986b31e3c80a9e796a59bb6958492f
bigcode/the-stack
train
9cf0fa0214ff81c656de25a0
train
function
def test_remove_rancher_ha(): assert CATTLE_TEST_URL.endswith(".qa.rancher.space"), \ "the CATTLE_TEST_URL need to end with .qa.rancher.space" if not check_if_ok(CATTLE_TEST_URL): print("skip deleting clusters within the setup") else: print("the CATTLE_TEST_URL is accessible") ...
def test_remove_rancher_ha():
assert CATTLE_TEST_URL.endswith(".qa.rancher.space"), \ "the CATTLE_TEST_URL need to end with .qa.rancher.space" if not check_if_ok(CATTLE_TEST_URL): print("skip deleting clusters within the setup") else: print("the CATTLE_TEST_URL is accessible") admin_token = get_user_token...
ANCHER_K3S_VERSION = os.environ.get("RANCHER_K3S_VERSION", "") kubeconfig_path = DATA_SUBDIR + "/kube_config_cluster-ha-filled.yml" export_cmd = "export KUBECONFIG=" + kubeconfig_path def test_remove_rancher_ha():
64
64
207
9
54
danielmittelman/rancher
tests/validation/tests/v3_api/test_create_ha.py
Python
test_remove_rancher_ha
test_remove_rancher_ha
39
59
39
39
b5eefb7197786e1ee16ab261418da946174b1428
bigcode/the-stack
train
a4eea229ea4cffd00ff89d6c
train
function
def write_encoded_certs(path, contents): file = open(path, "w") file.write(base64.b64decode(contents).decode("utf-8")) file.close()
def write_encoded_certs(path, contents):
file = open(path, "w") file.write(base64.b64decode(contents).decode("utf-8")) file.close()
+ " && kubectl -n cattle-system " \ "create secret generic tls-ca " \ "--from-file=" + ca_path run_command_with_stderr(tls_command) if not valid_cert: run_command_with_stderr(ca_command) def write_encoded_certs(path, contents):
64
64
38
9
55
danielmittelman/rancher
tests/validation/tests/v3_api/test_create_ha.py
Python
write_encoded_certs
write_encoded_certs
343
346
343
343
1cb6e0879699c4591ff46e1bf1fe589ad480ab02
bigcode/the-stack
train
4956be1a56c1a22ed994530d
train
function
def test_upgrade_rancher_ha(precheck_upgrade_options): write_kubeconfig() add_repo_create_namespace() install_rancher(upgrade=True)
def test_upgrade_rancher_ha(precheck_upgrade_options):
write_kubeconfig() add_repo_create_namespace() install_rancher(upgrade=True)
_run_cmd = \ get_custom_host_registration_cmd( client, cluster, node_roles[i], aws_node) aws_node.execute_command(docker_run_cmd) i += 1 validate_cluster(client, cluster, userToken=user_token) def test_upgrade_rancher_ha(precheck_upgrade_options):
64
64
34
13
51
danielmittelman/rancher
tests/validation/tests/v3_api/test_create_ha.py
Python
test_upgrade_rancher_ha
test_upgrade_rancher_ha
158
161
158
158
2b7d21db4ac57e42172e7dfd65c3590046874e7c
bigcode/the-stack
train
4fac7b62c860d156e77c3a82
train
function
def create_tls_secrets(valid_cert): cert_path = DATA_SUBDIR + "/tls.crt" key_path = DATA_SUBDIR + "/tls.key" ca_path = DATA_SUBDIR + "/cacerts.pem" if valid_cert: # write files from env var write_encoded_certs(cert_path, RANCHER_VALID_TLS_CERT) write_encoded_certs(key_path, RANC...
def create_tls_secrets(valid_cert):
cert_path = DATA_SUBDIR + "/tls.crt" key_path = DATA_SUBDIR + "/tls.key" ca_path = DATA_SUBDIR + "/cacerts.pem" if valid_cert: # write files from env var write_encoded_certs(cert_path, RANCHER_VALID_TLS_CERT) write_encoded_certs(key_path, RANCHER_VALID_TLS_KEY) else: ...
"--no-headers -o custom-columns=name:.metadata.name | " + \ "while read rancherpod; do kubectl -n cattle-system " + \ "exec $rancherpod -c rancher -- loglevel --set trace; done" run_command_with_stderr(set_trace_cmd) def create_tls_secrets(valid_cert):
74
74
247
8
66
danielmittelman/rancher
tests/validation/tests/v3_api/test_create_ha.py
Python
create_tls_secrets
create_tls_secrets
316
340
316
316
f7929807af2fafa6464f23f2fb4cf5cdcc87a382
bigcode/the-stack
train
5bb649eac2ffed3f577d8c82
train
function
def create_rke_cluster(config_path): rke_cmd = "rke --version && rke up --config " + config_path run_command_with_stderr(rke_cmd)
def create_rke_cluster(config_path):
rke_cmd = "rke --version && rke up --config " + config_path run_command_with_stderr(rke_cmd)
='" + rancher_url + "'\n" env_details += "env.ADMIN_TOKEN='" + admin_token + "'\n" env_details += "env.USER_TOKEN='" + user_token + "'\n" create_config_file(env_details) return admin_client def create_rke_cluster(config_path):
64
64
39
8
55
danielmittelman/rancher
tests/validation/tests/v3_api/test_create_ha.py
Python
create_rke_cluster
create_rke_cluster
368
370
368
368
0d88f8d97dc9fc4a1ae848773f5b3f0ab18fbab7
bigcode/the-stack
train
9dd00c7df9afc4f1515e7a89
train
class
class FunctionTests(SimpleTestCase): def test_urls(self): self.assertEqual( urlize('http://google.com'), '<a href="http://google.com" rel="nofollow">http://google.com</a>', ) self.assertEqual( urlize('http://google.com/'), '<a href="h...
class FunctionTests(SimpleTestCase):
def test_urls(self): self.assertEqual( urlize('http://google.com'), '<a href="http://google.com" rel="nofollow">http://google.com</a>', ) self.assertEqual( urlize('http://google.com/'), '<a href="http://google.com/" rel="nofollow">http:/...
@example.com"}) self.assertEqual( output, 'Email me at <a href="mailto:me@example.com">me@example.com</a>', ) @setup({'urlize08': '{{ a|urlize }}'}) def test_urlize08(self): output = self.engine.render_to_string('urlize08', {'a': "Email me at <me@example....
255
256
3,279
7
248
Yoann-Vie/esgi-hearthstone
tests/template_tests/filter_tests/test_urlize.py
Python
FunctionTests
FunctionTests
83
391
83
84
04865442f06fbe1e445e8b59591b14f55d54aaf6
bigcode/the-stack
train
30ecf37904e0b67d8df5dccd
train
class
class UrlizeTests(SimpleTestCase): @setup({'urlize01': '{% autoescape off %}{{ a|urlize }} {{ b|urlize }}{% endautoescape %}'}) def test_urlize01(self): output = self.engine.render_to_string( 'urlize01', {'a': 'http://example.com/?x=&y=', 'b': mark_safe('http://example.com...
class UrlizeTests(SimpleTestCase): @setup({'urlize01': '{% autoescape off %}{{ a|urlize }} {{ b|urlize }}{% endautoescape %}'})
def test_urlize01(self): output = self.engine.render_to_string( 'urlize01', {'a': 'http://example.com/?x=&y=', 'b': mark_safe('http://example.com?x=&amp;y=&lt;2&gt;')}, ) self.assertEqual( output, '<a href="http://example.com/?x=&amp;y="...
from django.template.defaultfilters import urlize from django.test import SimpleTestCase from django.utils.functional import lazy from django.utils.safestring import mark_safe from ..utils import setup class UrlizeTests(SimpleTestCase): @setup({'urlize01': '{% autoescape off %}{{ a|urlize }} {{ b|urlize }}...
84
256
976
43
40
Yoann-Vie/esgi-hearthstone
tests/template_tests/filter_tests/test_urlize.py
Python
UrlizeTests
UrlizeTests
9
80
9
11
3b7268dc11194fa52c21256a009320bd969d8b10
bigcode/the-stack
train
06ba476b6b0d5697cd822322
train
class
class OLSResults(RegressionResults): """ Results class for for an OLS model. Most of the methods and attributes are inherited from RegressionResults. The special methods that are only available for OLS are: - get_influence - outlier_test - el_test - conf_int_el See Also ------...
class OLSResults(RegressionResults):
""" Results class for for an OLS model. Most of the methods and attributes are inherited from RegressionResults. The special methods that are only available for OLS are: - get_influence - outlier_test - el_test - conf_int_el See Also -------- RegressionResults """ ...
son:', "%.3f" % dw), ('Jarque-Bera (JB):', "%.3f" % jb), ('Prob(JB):', "%.3f" % jbpv), ('Condition No.:', "%.0f" % condno) ]) # Summary from statsmodels.iolib import summary2 smry = summary2.Summary() smry.add_base(results=self, alpha=alph...
256
256
2,104
8
247
anishgoyal24/statsmodels
statsmodels/regression/linear_model.py
Python
OLSResults
OLSResults
2,533
2,793
2,533
2,533
385af7d3acd9ba6e5b8fbd18272b435b1e1db084
bigcode/the-stack
train
3812ccfe8a16175c4cf31996
train
function
def yule_walker(X, order=1, method="unbiased", df=None, inv=False, demean=True): """ Estimate AR(p) parameters from a sequence X using Yule-Walker equation. Unbiased or maximum-likelihood estimator (mle) See, for example: http://en.wikipedia.org/wiki/Autoregressive_moving_average_...
def yule_walker(X, order=1, method="unbiased", df=None, inv=False, demean=True):
""" Estimate AR(p) parameters from a sequence X using Yule-Walker equation. Unbiased or maximum-likelihood estimator (mle) See, for example: http://en.wikipedia.org/wiki/Autoregressive_moving_average_model Parameters ---------- X : array-like 1d array order : integer, opt...
to history, not if duplicate fit if not converged: results.history['params'].append(results.params) results.iter += 1 results.converged = converged return results def whiten(self, X): """ Whiten a series of columns according to an AR(p) cov...
228
229
764
26
202
anishgoyal24/statsmodels
statsmodels/regression/linear_model.py
Python
yule_walker
yule_walker
1,204
1,285
1,204
1,205
fa376e8edf953fd8bf0f8cabb34b9012650bdc81
bigcode/the-stack
train
04d632d8bd5489172b945d23
train
class
class GLSAR(GLS): __doc__ = """ A regression model with an AR(p) covariance structure. %(params)s rho : int Order of the autoregressive covariance %(extra_params)s Examples -------- >>> import statsmodels.api as sm >>> X = range(1,8) >>> X = sm.add_constant(X) >>> Y...
class GLSAR(GLS):
__doc__ = """ A regression model with an AR(p) covariance structure. %(params)s rho : int Order of the autoregressive covariance %(extra_params)s Examples -------- >>> import statsmodels.api as sm >>> X = range(1,8) >>> X = sm.add_constant(X) >>> Y = [1,3,4,5,8,10,9...
If a scalar, the same penalty weight applies to all variables in the model. If a vector, it must have the same length as `params`, and contains a penalty weight for each coefficient. Notes ----- Equivalent to fit_regularized with L1_wt = 0 (but implemented...
256
256
1,465
6
250
anishgoyal24/statsmodels
statsmodels/regression/linear_model.py
Python
GLSAR
GLSAR
1,043
1,201
1,043
1,043
58673463c41797c3cce6adad45d22b6f31448377
bigcode/the-stack
train
78f3799c820b9c4774300591
train
class
class RegressionResults(base.LikelihoodModelResults): r""" This class summarizes the fit of a linear regression model. It handles the output of contrasts, estimates of covariance, etc. Returns ------- **Attributes** aic Akaike's information criteria. For a model with a constant ...
class RegressionResults(base.LikelihoodModelResults):
r""" This class summarizes the fit of a linear regression model. It handles the output of contrasts, estimates of covariance, etc. Returns ------- **Attributes** aic Akaike's information criteria. For a model with a constant :math:`-2llf + 2(df\_model + 1)`. For a model wi...
, dtype=np.float64) if demean: X -= X.mean() # automatically demean's X n = df or X.shape[0] if method == "unbiased": # this is df_resid ie., n - p denom = lambda k: n - k else: denom = lambda k: n if X.ndim > 1 and X.shape[1] != 1: raise Valu...
256
256
11,425
9
247
anishgoyal24/statsmodels
statsmodels/regression/linear_model.py
Python
RegressionResults
RegressionResults
1,288
2,530
1,288
1,288
4d7da2b0e9ef2b9262348ae20dc3afb26c3a3a74
bigcode/the-stack
train
08f163647824a8c1a1086944
train
class
class GLS(RegressionModel): __doc__ = r""" Generalized least squares model with a general covariance structure. %(params)s sigma : scalar or array `sigma` is the weighting matrix of the covariance. The default is None for no scaling. If `sigma` is a scalar, it is assumed that `...
class GLS(RegressionModel):
__doc__ = r""" Generalized least squares model with a general covariance structure. %(params)s sigma : scalar or array `sigma` is the weighting matrix of the covariance. The default is None for no scaling. If `sigma` is a scalar, it is assumed that `sigma` is an n x n diagonal ...
). scale : scalar The variance parameter. exog : array-like The predictor variable matrix. dist_class : class A random number generator class. Must take 'loc' and 'scale' as arguments and return a random number generator implementing a...
256
256
1,886
6
249
anishgoyal24/statsmodels
statsmodels/regression/linear_model.py
Python
GLS
GLS
389
598
389
389
a6d1730d75d198990663dcfee4046688e80eae42
bigcode/the-stack
train
aeeb2554bf97bde0391fd7f6
train
class
class RegressionResultsWrapper(wrap.ResultsWrapper): _attrs = { 'chisq': 'columns', 'sresid': 'rows', 'weights': 'rows', 'wresid': 'rows', 'bcov_unscaled': 'cov', 'bcov_scaled': 'cov', 'HC0_se': 'columns', 'HC1_se': 'columns', 'HC2_se': 'colum...
class RegressionResultsWrapper(wrap.ResultsWrapper):
_attrs = { 'chisq': 'columns', 'sresid': 'rows', 'weights': 'rows', 'wresid': 'rows', 'bcov_unscaled': 'cov', 'bcov_scaled': 'cov', 'HC0_se': 'columns', 'HC1_se': 'columns', 'HC2_se': 'columns', 'HC3_se': 'columns', 'norm_resid'...
enth(f, lower_bound, self.params[param_num]) upperl = optimize.brenth(f, self.params[param_num], upper_bound) # ^ Seems to be faster than brentq in most cases return (lowerl, upperl) class RegressionResultsWrapper(wrap.ResultsWra...
64
64
163
9
55
anishgoyal24/statsmodels
statsmodels/regression/linear_model.py
Python
RegressionResultsWrapper
RegressionResultsWrapper
2,796
2,819
2,796
2,797
8fd61cf76517fde849f69dbbc1cc38faffbde3f2
bigcode/the-stack
train
a6404d8825dae5d2327e0373
train
function
def _get_sigma(sigma, nobs): """ Returns sigma (matrix, nobs by nobs) for GLS and the inverse of its Cholesky decomposition. Handles dimensions and checks integrity. If sigma is None, returns None, None. Otherwise returns sigma, cholsigmainv. """ if sigma is None: return None, None ...
def _get_sigma(sigma, nobs):
""" Returns sigma (matrix, nobs by nobs) for GLS and the inverse of its Cholesky decomposition. Handles dimensions and checks integrity. If sigma is None, returns None, None. Otherwise returns sigma, cholsigmainv. """ if sigma is None: return None, None sigma = np.asarray(sigma)...
zero_tol : float Coefficients below this threshold are treated as zero. References ---------- Friedman, Hastie, Tibshirani (2008). Regularization paths for generalized linear models via coordinate descent. Journal of Statistical Software 33(1), 1-22 Feb 201...
83
84
283
10
73
anishgoyal24/statsmodels
statsmodels/regression/linear_model.py
Python
_get_sigma
_get_sigma
147
169
147
147
3970879581564714e82eb244d2bff5967f16f194
bigcode/the-stack
train
31f30ab796ca3b0f12ea9f6b
train
class
class OLS(WLS): __doc__ = """ A simple ordinary least squares model. %(params)s %(extra_params)s Attributes ---------- weights : scalar Has an attribute weights = array(1.0) due to inheritance from WLS. See Also -------- GLS Examples -------- >>> import nu...
class OLS(WLS):
__doc__ = """ A simple ordinary least squares model. %(params)s %(extra_params)s Attributes ---------- weights : scalar Has an attribute weights = array(1.0) due to inheritance from WLS. See Also -------- GLS Examples -------- >>> import numpy as np >>...
ndarray, 1d A 1d weight vector used in the calculation of the Hessian. The hessian is obtained by `(exog.T * hessian_factor).dot(exog)` """ return self.weights def fit_regularized(self, method="elastic_net", alpha=0., L1_wt=1., start_params=None, pr...
256
256
2,195
6
249
anishgoyal24/statsmodels
statsmodels/regression/linear_model.py
Python
OLS
OLS
772
1,040
772
772
e759dc3d7d921b4769f3bc9bc6ee0e13b0af45d7
bigcode/the-stack
train
3447b87f607f2993d993a6cc
train
class
class RegressionModel(base.LikelihoodModel): """ Base class for linear regression models. Should not be directly called. Intended for subclassing. """ def __init__(self, endog, exog, **kwargs): super(RegressionModel, self).__init__(endog, exog, **kwargs) self._data_attr.extend(['pin...
class RegressionModel(base.LikelihoodModel):
""" Base class for linear regression models. Should not be directly called. Intended for subclassing. """ def __init__(self, endog, exog, **kwargs): super(RegressionModel, self).__init__(endog, exog, **kwargs) self._data_attr.extend(['pinv_wexog', 'wendog', 'wexog', 'weights']) ...
ky decomposition. Handles dimensions and checks integrity. If sigma is None, returns None, None. Otherwise returns sigma, cholsigmainv. """ if sigma is None: return None, None sigma = np.asarray(sigma).squeeze() if sigma.ndim == 0: sigma = np.repeat(sigma, nobs) if sigma.ndi...
256
256
1,683
8
247
anishgoyal24/statsmodels
statsmodels/regression/linear_model.py
Python
RegressionModel
RegressionModel
172
386
172
172
cae3c5b4d17aeb49bbdf3743648a798a0ecbb76e
bigcode/the-stack
train
86b700a6fe2a75173b2a646f
train
class
class WLS(RegressionModel): __doc__ = """ A regression model with diagonal but non-identity covariance structure. The weights are presumed to be (proportional to) the inverse of the variance of the observations. That is, if the variables are to be transformed by 1/sqrt(W) you must supply weights =...
class WLS(RegressionModel):
__doc__ = """ A regression model with diagonal but non-identity covariance structure. The weights are presumed to be (proportional to) the inverse of the variance of the observations. That is, if the variables are to be transformed by 1/sqrt(W) you must supply weights = 1/W. %(params)s we...
.ndim == 1: return self.cholsigmainv else: return np.diag(self.cholsigmainv) def fit_regularized(self, method="elastic_net", alpha=0., L1_wt=1., start_params=None, profile_scale=False, refit=False, **kwargs): # Docstring attach...
256
256
1,548
7
248
anishgoyal24/statsmodels
statsmodels/regression/linear_model.py
Python
WLS
WLS
601
769
601
601
1f83f9fa46f3d431a6594cdf2cb8c207235cb9be
bigcode/the-stack
train
cfab1702f0addc6b2dd04d40
train
function
@pytest.fixture(scope="module") def test_app(): app = create_app(FORCE_ENV_FOR_DYNACONF="testing") with app.app_context(): yield app # testing happens here
@pytest.fixture(scope="module") def test_app():
app = create_app(FORCE_ENV_FOR_DYNACONF="testing") with app.app_context(): yield app # testing happens here
sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, clear_mappers from src.events.factory.app import create_app from src.events.adapters.orm import Base from src.events.adapters import database from src.events.services.unit_of_work import SqlAlchemyUnitOfWork @pytest.fixture(scope="module") def ...
64
64
43
10
53
jonatasoli/the-eye
src/tests/conftest.py
Python
test_app
test_app
20
24
20
21
3889e8efc5687273ab83b47b964e7dc643b1b0b2
bigcode/the-stack
train
d62bf8d271478f1c5f96101c
train
function
@pytest.fixture def postgres_db(): engine = create_engine("postgresql://myuser:mypass@172.18.0.3/testdb") with engine.begin() as conn: Base.metadata.drop_all(bind=engine) Base.metadata.create_all(bind=engine)
@pytest.fixture def postgres_db():
engine = create_engine("postgresql://myuser:mypass@172.18.0.3/testdb") with engine.begin() as conn: Base.metadata.drop_all(bind=engine) Base.metadata.create_all(bind=engine)
from src.events.services.unit_of_work import SqlAlchemyUnitOfWork @pytest.fixture(scope="module") def test_app(): app = create_app(FORCE_ENV_FOR_DYNACONF="testing") with app.app_context(): yield app # testing happens here @pytest.fixture def postgres_db():
64
64
57
7
56
jonatasoli/the-eye
src/tests/conftest.py
Python
postgres_db
postgres_db
27
32
27
28
9aa8026857dd509672839425c6fb1df2cc5b1fe6
bigcode/the-stack
train
28ed45907698cbb5b05744ed
train
function
@pytest.fixture def uow_postgres(): return SqlAlchemyUnitOfWork( session_factory=database.session_factory( "postgresql://myuser:mypass@172.18.0.3/testdb" ) )
@pytest.fixture def uow_postgres():
return SqlAlchemyUnitOfWork( session_factory=database.session_factory( "postgresql://myuser:mypass@172.18.0.3/testdb" ) )
def postgres_db(): engine = create_engine("postgresql://myuser:mypass@172.18.0.3/testdb") with engine.begin() as conn: Base.metadata.drop_all(bind=engine) Base.metadata.create_all(bind=engine) @pytest.fixture def uow_postgres():
64
64
49
9
55
jonatasoli/the-eye
src/tests/conftest.py
Python
uow_postgres
uow_postgres
34
40
34
35
2cd8996cb617abc2b7948b8da4297b7bc7eeaf6b
bigcode/the-stack
train
0e8169fda6a389d3623e3f24
train
class
class ExpressRouteCircuitsOperations(object): """ExpressRouteCircuitsOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this opera...
class ExpressRouteCircuitsOperations(object):
"""ExpressRouteCircuitsOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.netw...
Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # ---------------------------------------------...
256
256
11,478
8
248
praveenkuttappan/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2020_08_01/operations/_express_route_circuits_operations.py
Python
ExpressRouteCircuitsOperations
ExpressRouteCircuitsOperations
28
1,073
28
28
d1ab9fccf9919481292953b57c6a0b1eff416b61
bigcode/the-stack
train
5b36e24ccebccd1edef45d96
train
function
def define_runtime(context_data): core_stdlib_internal( name = "microsoft.win32.registry.dll", version = "4.1.0.0", ref = "@core_sdk_v2.1.200//:core/shared/Microsoft.NETCore.App/2.0.7/Microsoft.Win32.Registry.dll", stdlib_path = "@core_sdk_v2.1.200//:core/shared/Microsoft.NETCore.App...
def define_runtime(context_data):
core_stdlib_internal( name = "microsoft.win32.registry.dll", version = "4.1.0.0", ref = "@core_sdk_v2.1.200//:core/shared/Microsoft.NETCore.App/2.0.7/Microsoft.Win32.Registry.dll", stdlib_path = "@core_sdk_v2.1.200//:core/shared/Microsoft.NETCore.App/2.0.7/Microsoft.Win32.Registry.dl...
load("@rules_mono//dotnet/private:rules/stdlib.bzl", "core_stdlib_internal") load("@rules_mono//dotnet/private:rules/libraryset.bzl", "core_libraryset") def define_runtime(context_data):
49
256
9,502
6
43
nolen777/rules_mono
dotnet/stdlib.core/v2.1.200/generated2.bzl
Python
define_runtime
define_runtime
4
787
4
4
1c5ebc17d24d5600f6811eeaac913563eb99910d
bigcode/the-stack
train
7207676bf412515c83ead2d5
train
function
def p_ss_atma(p_res_atma=250, q_liq_sm3day=50, mu_cP=1, B_m3m3=1.2, k_mD=40, h_m=10, r_e=240, r=0.1): """ функция расчета давления в произвольной точке пласта для стационарного решения уравнения фильтрации ...
def p_ss_atma(p_res_atma=250, q_liq_sm3day=50, mu_cP=1, B_m3m3=1.2, k_mD=40, h_m=10, r_e=240, r=0.1):
""" функция расчета давления в произвольной точке пласта для стационарного решения уравнения фильтрации p_res_atma - пластовое давление, давление на контуре питания q_liq_sm3day - дебит жидкости на поверхности в стандартных условиях mu_cP - вязкость нефти (в пластовых условиях) B_m3m3 - объе...
import seaborn as sns def p_ss_atma(p_res_atma=250, q_liq_sm3day=50, mu_cP=1, B_m3m3=1.2, k_mD=40, h_m=10, r_e=240, r=0.1):
73
73
246
66
6
ilyazat/welltest_examples
hw10/heatmap.py
Python
p_ss_atma
p_ss_atma
6
26
6
13
003952348760728d343c6b0d3515e3ab418d1d86
bigcode/the-stack
train
96d89b83d8a46d0b19bab57b
train
function
def p_ss_atma_two_zones(p_res_atma=250, q_liq_sm3day=50, mu_cP=1, B_m3m3=1.2, h_m=10, r_e=240, r=0.1, r_bound=100, k1_mD=30, ...
def p_ss_atma_two_zones(p_res_atma=250, q_liq_sm3day=50, mu_cP=1, B_m3m3=1.2, h_m=10, r_e=240, r=0.1, r_bound=100, k1_mD=30, ...
""" функция, использующая функцию p_ss_atma для расчета композитного двухслойного пласта. r_bound - расстояние от скважины до следующей зоны k1_mD, k2_mD - проницаемости зон от скважины до контура соответственно """ if r < r_bound: k_mD = k1_mD else: k_mD = k2_mD return p...
def p_ss_atma_two_zones(p_res_atma=250, q_liq_sm3day=50, mu_cP=1, B_m3m3=1.2, h_m=10, r_e=240, r=0.1, r_bound=100, k1_mD=30, ...
84
67
224
84
0
ilyazat/welltest_examples
hw10/heatmap.py
Python
p_ss_atma_two_zones
p_ss_atma_two_zones
29
48
29
38
43dac25a0d5294055f27b8604ded9f67d58442c1
bigcode/the-stack
train
1e432ffd6b038ba21bfcb156
train
function
def pplot(*args, **kwargs): """Long plot. Plots with a long default figsize""" figsize = kwargs.pop('figsize', dflt_figsize) if isinstance(args[0], (pd.DataFrame, pd.Series)): df, *args = args plot_func = getattr(df, 'plot') kwargs['figsize'] = figsize else: plot_func = p...
def pplot(*args, **kwargs):
"""Long plot. Plots with a long default figsize""" figsize = kwargs.pop('figsize', dflt_figsize) if isinstance(args[0], (pd.DataFrame, pd.Series)): df, *args = args plot_func = getattr(df, 'plot') kwargs['figsize'] = figsize else: plot_func = plt.plot if figsize: ...
from matplotlib.pylab import * import pandas as pd dflt_figsize = (16, 5) def pplot(*args, **kwargs):
32
64
110
9
23
thorwhalen/ut
pplot/misc.py
Python
pplot
pplot
7
18
7
7
5ea9bed07ac369dfc04d2dbafd99f08199637f19
bigcode/the-stack
train
b4aa322933d9d4b285a019f0
train
class
class BleakGATTDescriptorCoreBluetooth(BleakGATTDescriptor): """GATT Descriptor implementation for CoreBluetooth backend""" def __init__(self, obj: CBDescriptor, characteristic_uuid: str, characteristic_handle: int): super(BleakGATTDescriptorCoreBluetooth, self).__init__(obj) self.obj = obj ...
class BleakGATTDescriptorCoreBluetooth(BleakGATTDescriptor):
"""GATT Descriptor implementation for CoreBluetooth backend""" def __init__(self, obj: CBDescriptor, characteristic_uuid: str, characteristic_handle: int): super(BleakGATTDescriptorCoreBluetooth, self).__init__(obj) self.obj = obj self.__characteristic_uuid = characteristic_uuid ...
""" Interface class for the Bleak representation of a GATT Descriptor Created on 2019-06-28 by kevincar <kevincarrolldavis@gmail.com> """ from Foundation import CBDescriptor from bleak.backends.descriptor import BleakGATTDescriptor class BleakGATTDescriptorCoreBluetooth(BleakGATTDescriptor):
71
71
238
15
55
pybricks/bleak
bleak/backends/corebluetooth/descriptor.py
Python
BleakGATTDescriptorCoreBluetooth
BleakGATTDescriptorCoreBluetooth
12
42
12
12
19f6f9566be466663a94af4f3eb014e35a223a51
bigcode/the-stack
train
9ba1abecd33d0883832d855d
train
class
class OpeniocFilesList(komand.Action): SORTING_COLUMNS = { "FileName": 1, "Title": 2, "FileAddedDatetime": 3, "UploadedFrom": 4, "UploadedBy": 5, "ExtractingStatus": 6, } SORTING_DIRECTION = {"Ascending": 1, "Descending": 2} def __init__(self): su...
class OpeniocFilesList(komand.Action):
SORTING_COLUMNS = { "FileName": 1, "Title": 2, "FileAddedDatetime": 3, "UploadedFrom": 4, "UploadedBy": 5, "ExtractingStatus": 6, } SORTING_DIRECTION = {"Ascending": 1, "Descending": 2} def __init__(self): super(self.__class__, self).__init__( ...
import komand from .schema import OpeniocFilesListInput, OpeniocFilesListOutput, Input, Component # Custom imports below import urllib.parse import json class OpeniocFilesList(komand.Action):
45
95
317
10
34
lukaszlaszuk/insightconnect-plugins
plugins/trendmicro_apex/icon_trendmicro_apex/actions/openioc_files_list/action.py
Python
OpeniocFilesList
OpeniocFilesList
9
44
9
9
ad5907e7cab76a36e6e5a7734dc7343dbfdfaf87
bigcode/the-stack
train
ce9a0c54718f76a1fd561030
train
function
def sum_cosines(n): total = 0 for k in range(n + 1): total = math.cos(k) + total return total """ What comes in: A non-negative integer n. What goes out: The sum of the cosines of the integers 0, 1, 2, 3, ... n, inclusive, for the given n. Side effects: None. Example: ...
def sum_cosines(n):
total = 0 for k in range(n + 1): total = math.cos(k) + total return total """ What comes in: A non-negative integer n. What goes out: The sum of the cosines of the integers 0, 1, 2, 3, ... n, inclusive, for the given n. Side effects: None. Example: If n is 3, thi...
print(' actual: ', answer) print('Test 3') expect = 1.475015909922667 answer = sum_cosines(14) print('Test 3 expected:', expect) print(' actual: ', answer) def sum_cosines(n):
64
64
142
6
58
GMyoung/03-AccumulatorsAndFunctionsWithParameters
src/m7_summing.py
Python
sum_cosines
sum_cosines
47
60
47
47
ebf8f5865bb383e3a720841bdc4e4e3cdbbdf2ed
bigcode/the-stack
train
c889323623e50007ff6152ce
train
function
def main(): """ Calls the TEST functions in this module. """ run_test_sum_cosines() run_test_sum_square_roots()
def main():
""" Calls the TEST functions in this module. """ run_test_sum_cosines() run_test_sum_square_roots()
= total + number Authors: David Mutchler, Vibha Alangar, Matt Boutell, Dave Fisher, Mark Hays, Aaron Wilkin, their colleagues, and Yicheng Yang. """ # DONE: 1. PUT YOUR NAME IN THE ABOVE LINE. import math def main():
64
64
31
3
60
GMyoung/03-AccumulatorsAndFunctionsWithParameters
src/m7_summing.py
Python
main
main
11
14
11
11
8e1a3eb7f6c83f902fb5b58c94c806995bc5a0d5
bigcode/the-stack
train
4caa680707607efcd16637ff
train
function
def run_test_sum_cosines(): """ Tests the sum_cosines function. """ # ------------------------------------------------------------------------- # DONE: 2. Implement this function. # It TESTS the sum_cosines function defined below. # Include at least ** 3 ** tests. # # Use the s...
def run_test_sum_cosines():
""" Tests the sum_cosines function. """ # ------------------------------------------------------------------------- # DONE: 2. Implement this function. # It TESTS the sum_cosines function defined below. # Include at least ** 3 ** tests. # # Use the same 4-step process as in imp...
Boutell, Dave Fisher, Mark Hays, Aaron Wilkin, their colleagues, and Yicheng Yang. """ # DONE: 1. PUT YOUR NAME IN THE ABOVE LINE. import math def main(): """ Calls the TEST functions in this module. """ run_test_sum_cosines() run_test_sum_square_roots() def run_test_sum_cosines():
81
81
272
7
74
GMyoung/03-AccumulatorsAndFunctionsWithParameters
src/m7_summing.py
Python
run_test_sum_cosines
run_test_sum_cosines
17
45
17
17
f75dc2c71910fc55777846c40b2d8bcf7a1377d2
bigcode/the-stack
train
3ff2be68b59c99e61ca206a9
train
function
def sum_square_roots(n): root = 0 for k in range(n + 1): root = root + math.sqrt(2*k) return root """ What comes in: A non-negative integer n. What goes out: The sum of the square roots of the integers 2, 4, 6, 8, ... 2n inclusive, for the given n. So if n is 7, th...
def sum_square_roots(n):
root = 0 for k in range(n + 1): root = root + math.sqrt(2*k) return root """ What comes in: A non-negative integer n. What goes out: The sum of the square roots of the integers 2, 4, 6, 8, ... 2n inclusive, for the given n. So if n is 7, the last term of the sum is...
) print('answer:', answer) # Test 3 print('Test 3') expected = 27.302807779101823 answer = sum_square_roots(9) print('expected:', expected) print('answer:', answer) def sum_square_roots(n):
64
64
179
7
57
GMyoung/03-AccumulatorsAndFunctionsWithParameters
src/m7_summing.py
Python
sum_square_roots
sum_square_roots
106
122
106
106
0c24a1b825cf380d461c8b7c5beaf833b8201798
bigcode/the-stack
train
59792ba6671c518f039bf621
train
function
def run_test_sum_square_roots(): """ Tests the sum_square_roots function. """ # ------------------------------------------------------------------------- # DONE: 4. Implement this function. # It TESTS the sum_square_roots function defined below. # Include at least ** 3 ** tests. # ...
def run_test_sum_square_roots():
""" Tests the sum_square_roots function. """ # ------------------------------------------------------------------------- # DONE: 4. Implement this function. # It TESTS the sum_square_roots function defined below. # Include at least ** 3 ** tests. # # Use the same 4-step process...
this function. # Note that you should write its TEST function first (above). # That is called TEST-DRIVEN DEVELOPMENT (TDD). # # No fair running the code of sum_cosines to GENERATE # test cases; that would defeat the purpose of TESTING! # ----------------------------------------------...
80
81
272
8
72
GMyoung/03-AccumulatorsAndFunctionsWithParameters
src/m7_summing.py
Python
run_test_sum_square_roots
run_test_sum_square_roots
71
103
71
71
33b247d3058fa37d5552aa7fe386cbf31569c0bd
bigcode/the-stack
train
eb4dc71de2c1c03604bf52b2
train
class
class SelectionManager: def __init__(self, total, boxW=80, boxH=20, boxColor = 0xffffff, bgColor=0, offsetY=0, callback=print, menu=0): self.total = total + menu self.real = total self.boxW = boxW self.boxH = boxH self.boxColor = boxColor self.bgColor = bgColor ...
class SelectionManager:
def __init__(self, total, boxW=80, boxH=20, boxColor = 0xffffff, bgColor=0, offsetY=0, callback=print, menu=0): self.total = total + menu self.real = total self.boxW = boxW self.boxH = boxH self.boxColor = boxColor self.bgColor = bgColor self.offsetY = offsetY...
from m5stack import lcd, btnA, btnB class SelectionManager:
17
131
438
4
12
remixer-dec/M5Stack_Experiments
M5StickC/UIFlow/TwitchClient/selectionManager.py
Python
SelectionManager
SelectionManager
3
44
3
3
b7408b4aaa95931a201bbe84021cf051ee0503cd
bigcode/the-stack
train
be07833773d958efe8c0ddde
train
function
def get_indicators(client: Client, params: Dict[str, str], args: Dict[str, str]) -> Tuple[str, Dict[Any, Any], Dict[Any, Any]]: """Wrapper for retrieving indicators from the feed to the war-room. Args: client: Client object with request params: demisto.params() args: demisto.args() ...
def get_indicators(client: Client, params: Dict[str, str], args: Dict[str, str]) -> Tuple[str, Dict[Any, Any], Dict[Any, Any]]:
"""Wrapper for retrieving indicators from the feed to the war-room. Args: client: Client object with request params: demisto.params() args: demisto.args() Returns: Outputs. """ limit = int(args.get('limit', '10')) indicators = fetch_indicators(client, params)[:l...
: client: Client object. Returns: Outputs. """ client.build_iterator() return 'ok', {}, {} def get_indicators(client: Client, params: Dict[str, str], args: Dict[str, str]) -> Tuple[str, Dict[Any, Any], Dict[Any, Any]]:
63
64
152
36
27
ddi-danielsantander/content
Packs/FeedGCPWhitelist/Integrations/FeedGCPWhitelist/FeedGCPWhitelist.py
Python
get_indicators
get_indicators
73
89
73
73
0a7e087b324d01aa02ce7a3aaa7a8153814fa2c6
bigcode/the-stack
train
33bcab9bcbb36f17ac2e415b
train
function
def fetch_indicators(client: Client, params: Dict[str, str]) -> List[Dict]: """Retrieves indicators from the feed Args: client (Client): Client object with request params: demisto.params() to retrieve tags Returns: Indicators. """ feed_tags = argToList(params.get('feedTags'...
def fetch_indicators(client: Client, params: Dict[str, str]) -> List[Dict]:
"""Retrieves indicators from the feed Args: client (Client): Client object with request params: demisto.params() to retrieve tags Returns: Indicators. """ feed_tags = argToList(params.get('feedTags', '')) iterator = client.build_iterator() indicators = [] for in...
human_readable = tableToMarkdown('Indicators from GCP Whitelist Feed:', indicators, headers=['value', 'type'], removeNull=True) return human_readable, {}, {'raw_response': indicators} def fetch_indicators(client: Client, params: Dict[str, str]) -> List[Dict]:
64
64
173
20
44
ddi-danielsantander/content
Packs/FeedGCPWhitelist/Integrations/FeedGCPWhitelist/FeedGCPWhitelist.py
Python
fetch_indicators
fetch_indicators
92
119
92
92
273e3c9ce00b4b85f771f0b76453e002fe3b48ec
bigcode/the-stack
train
df6ea8f0ba80759873801926
train
function
def fetch_cidr(dns_address: str) -> List[Dict]: """Recursively builds a CIDR dictionary with the relevant ip and type Args: dns_address: the dns address to lookup Returns: CIDR list """ cidr_arr = [] regex_dns = r"(include:.*? )" regex_cidr = r"(ip.*?:.*? )" try: ...
def fetch_cidr(dns_address: str) -> List[Dict]:
"""Recursively builds a CIDR dictionary with the relevant ip and type Args: dns_address: the dns address to lookup Returns: CIDR list """ cidr_arr = [] regex_dns = r"(include:.*? )" regex_cidr = r"(ip.*?:.*? )" try: query_response_str = str(dns.resolver.query(d...
from CommonServerPython import * # IMPORTS import dns.resolver import re from typing import List, Dict, Callable, Tuple, Any # Disable insecure warnings requests.packages.urllib3.disable_warnings() # CONSTANTS GOOGLE_BASE_DNS = "_cloud-netblocks.googleusercontent.com" def fetch_cidr(dns_address: str) -> List[Dict]:
79
84
280
15
64
ddi-danielsantander/content
Packs/FeedGCPWhitelist/Integrations/FeedGCPWhitelist/FeedGCPWhitelist.py
Python
fetch_cidr
fetch_cidr
15
43
15
15
18142dfc3dee6345f670a0fca91b0651e3d8beed
bigcode/the-stack
train
620ef1fdcc75282500229904
train
function
def main(): """ PARSE AND VALIDATE INTEGRATION PARAMS """ verify_certificate = not demisto.params().get('insecure', False) proxy = demisto.params().get('proxy', False) command = demisto.command() LOG(f'Command being called is {demisto.command()}') try: client = Client( ...
def main():
""" PARSE AND VALIDATE INTEGRATION PARAMS """ verify_certificate = not demisto.params().get('insecure', False) proxy = demisto.params().get('proxy', False) command = demisto.command() LOG(f'Command being called is {demisto.command()}') try: client = Client( base_...
'value': indicator["ip"], 'type': indicator["type"], 'rawJSON': { 'value': indicator["ip"], 'type': indicator["type"], }, } if feed_tags: indicator_obj['fields'] = { 'tags': feed_tags ...
78
78
261
3
74
ddi-danielsantander/content
Packs/FeedGCPWhitelist/Integrations/FeedGCPWhitelist/FeedGCPWhitelist.py
Python
main
main
122
152
122
122
801706c981a95c36908742614df455690123bd9e
bigcode/the-stack
train
6d78885ba29b5889b6d8008b
train
function
def test_module(client: Client, *_) -> Tuple[str, Dict[Any, Any], Dict[Any, Any]]: """Builds the iterator to check that the feed is accessible. Args: client: Client object. Returns: Outputs. """ client.build_iterator() return 'ok', {}, {}
def test_module(client: Client, *_) -> Tuple[str, Dict[Any, Any], Dict[Any, Any]]:
"""Builds the iterator to check that the feed is accessible. Args: client: Client object. Returns: Outputs. """ client.build_iterator() return 'ok', {}, {}
def build_iterator(self): """Retrieves all entries from the feed. Returns: A list of objects, containing the data. """ return fetch_cidr(self._base_url) def test_module(client: Client, *_) -> Tuple[str, Dict[Any, Any], Dict[Any, Any]]:
64
64
66
23
41
ddi-danielsantander/content
Packs/FeedGCPWhitelist/Integrations/FeedGCPWhitelist/FeedGCPWhitelist.py
Python
test_module
test_module
61
70
61
61
b2a45b03fb0d10bcdcce9e4e0e62bad7ca32b69d
bigcode/the-stack
train
d06f1ca6ac792fcb5eede4be
train
class
class Client(BaseClient): """ Client will implement the service API, and should not contain any Demisto logic. Should only do requests and return data. """ def build_iterator(self): """Retrieves all entries from the feed. Returns: A list of objects, containing the data....
class Client(BaseClient):
""" Client will implement the service API, and should not contain any Demisto logic. Should only do requests and return data. """ def build_iterator(self): """Retrieves all entries from the feed. Returns: A list of objects, containing the data. """ retur...
:3] == "ip4") else FeedIndicatorType.IPv6CIDR cidr_ip = m[4:len(m) - 1] cidr_arr.append({"type": cidr_type, "ip": cidr_ip}) return cidr_arr class Client(BaseClient):
64
64
76
5
58
ddi-danielsantander/content
Packs/FeedGCPWhitelist/Integrations/FeedGCPWhitelist/FeedGCPWhitelist.py
Python
Client
Client
46
58
46
46
3a914c7800adde157ac2262bafcfd3c0ca6c75da
bigcode/the-stack
train
b11f2049647e735a2d902e8a
train
function
async def publish_event(business: Business, filing: Filing): """Publish the filing message onto the NATS filing subject.""" try: payload = {'filing': { 'identifier': business.identifier, 'legalName': business.legal_name, ...
async def publish_event(business: Business, filing: Filing):
"""Publish the filing message onto the NATS filing subject.""" try: payload = {'filing': { 'identifier': business.identifier, 'legalName': business.legal_name, 'filingId': filing.id, 'effective...
: a list of filing types. } """ filing_types = [] for k in legal_filings['filing'].keys(): if Filing.FILINGS.get(k, None): filing_types.append(k) return filing_types async def publish_event(business: Business, filing: Filing):
64
64
196
13
50
katiemcgoff/lear
queue_services/entity-filer/src/entity_filer/worker.py
Python
publish_event
publish_event
75
91
75
75
24d67812ed0d4a5a2b8b666f57531bca66d86601
bigcode/the-stack
train
44c72e259d2f4d6d2e76de5a
train
function
def process_filing(filing_msg: Dict, flask_app: Flask): # pylint: disable=too-many-branches """Render the filings contained in the submission.""" if not flask_app: raise QueueException('Flask App not available.') with flask_app.app_context(): filing_submission = Filing.find_by_id(filing_m...
def process_filing(filing_msg: Dict, flask_app: Flask): # pylint: disable=too-many-branches
"""Render the filings contained in the submission.""" if not flask_app: raise QueueException('Flask App not available.') with flask_app.app_context(): filing_submission = Filing.find_by_id(filing_msg['filing']['id']) if not filing_submission: raise QueueException ...
subject = APP_CONFIG.ENTITY_EVENT_PUBLISH_OPTIONS['subject'] await qsm.service.publish(subject, payload) except Exception as err: # pylint: disable=broad-except; we don't want to fail out the filing, so ignore all. capture_message('Queue Publish Event Error: filing.id=' + str(filing.id) + s...
126
126
423
26
100
katiemcgoff/lear
queue_services/entity-filer/src/entity_filer/worker.py
Python
process_filing
process_filing
94
154
94
94
07275e23b9e3c3d51a4374cfb80ad9fee44f6d11
bigcode/the-stack
train
235a7bc61897b0d5da32cdc0
train
function
def get_filing_types(legal_filings: dict): """Get the filing type fee codes for the filing. Returns: { list: a list of filing types. } """ filing_types = [] for k in legal_filings['filing'].keys(): if Filing.FILINGS.get(k, None): filing_types.append(k) return fil...
def get_filing_types(legal_filings: dict):
"""Get the filing type fee codes for the filing. Returns: { list: a list of filing types. } """ filing_types = [] for k in legal_filings['filing'].keys(): if Filing.FILINGS.get(k, None): filing_types.append(k) return filing_types
# pylint: disable=invalid-name APP_CONFIG = config.get_named_config(os.getenv('DEPLOYMENT_ENV', 'production')) FLASK_APP = Flask(__name__) FLASK_APP.config.from_object(APP_CONFIG) db.init_app(FLASK_APP) def get_filing_types(legal_filings: dict):
64
64
81
12
52
katiemcgoff/lear
queue_services/entity-filer/src/entity_filer/worker.py
Python
get_filing_types
get_filing_types
61
72
61
61
64f66ee5838b9234ad96dccc18761b00f8844092
bigcode/the-stack
train
2e2a18f0b971b61e1a0372a4
train
function
async def cb_subscription_handler(msg: nats.aio.client.Msg): """Use Callback to process Queue Msg objects.""" try: logger.info('Received raw message seq:%s, data= %s', msg.sequence, msg.data.decode()) filing_msg = json.loads(msg.data.decode('utf-8')) logger.debug('Extracted filing msg: ...
async def cb_subscription_handler(msg: nats.aio.client.Msg):
"""Use Callback to process Queue Msg objects.""" try: logger.info('Received raw message seq:%s, data= %s', msg.sequence, msg.data.decode()) filing_msg = json.loads(msg.data.decode('utf-8')) logger.debug('Extracted filing msg: %s', filing_msg) process_filing(filing_msg, FLASK_APP...
iling.process(business, filing, flask_app) elif filing.get('correction'): correction.process(filing_submission, filing) filing_submission.transaction_id = transaction.id filing_submission.set_processed() db.session.add(business) db.s...
88
88
294
14
73
katiemcgoff/lear
queue_services/entity-filer/src/entity_filer/worker.py
Python
cb_subscription_handler
cb_subscription_handler
157
175
157
157
ac0047eefef62f303b9198b38a89030a96a7d67d
bigcode/the-stack
train
45a7462ddb935a3e92043f6c
train
function
@make_category def one_pair(roll, filled_categories): best_pair = 0 for die_value, num_dice in enumerate(roll, 1): if num_dice >= 2: best_pair = die_value return best_pair * 2
@make_category def one_pair(roll, filled_categories):
best_pair = 0 for die_value, num_dice in enumerate(roll, 1): if num_dice >= 2: best_pair = die_value return best_pair * 2
ards_bonus=True) def fives(roll, filled_categories): return 5 * roll[4] @make_category(counts_towards_bonus=True) def sixes(roll, filled_categories): return 6 * roll[5] @make_category def one_pair(roll, filled_categories):
64
64
60
13
51
Porpoised/Yahtzee
yahtzotron/rulesets/yatzy.py
Python
one_pair
one_pair
34
41
34
35
8c3b76a1f672289815a736817a4806195b2201f3
bigcode/the-stack
train
3bb07b755197d68042cbe3ab
train
function
@make_category def yatzy(roll, filled_categories): if 5 in roll: return 50 return 0
@make_category def yatzy(roll, filled_categories):
if 5 in roll: return 50 return 0
, 1)): return 25 return 0 @make_category def chance(roll, filled_categories): return sum(die_value * num_dice for die_value, num_dice in enumerate(roll, 1)) @make_category def yatzy(roll, filled_categories):
64
64
30
13
51
Porpoised/Yahtzee
yahtzotron/rulesets/yatzy.py
Python
yatzy
yatzy
114
119
114
115
424eb839ecc18c1b69e6e3fa56cfb4f284873fbc
bigcode/the-stack
train
c2ef759b9eb49036c53fd313
train
function
@make_category def full_house(roll, filled_categories): doublet = None triplet = None for die_value, num_dice in enumerate(roll, 1): if num_dice == 2: doublet = die_value elif num_dice == 3: triplet = die_value if doublet is None or triplet is None: retu...
@make_category def full_house(roll, filled_categories):
doublet = None triplet = None for die_value, num_dice in enumerate(roll, 1): if num_dice == 2: doublet = die_value elif num_dice == 3: triplet = die_value if doublet is None or triplet is None: return 0 return 3 * triplet + 2 * doublet
_category def four_of_a_kind(roll, filled_categories): for die_value, num_dice in enumerate(roll, 1): if num_dice >= 4: return 4 * die_value return 0 @make_category def full_house(roll, filled_categories):
64
64
104
13
50
Porpoised/Yahtzee
yahtzotron/rulesets/yatzy.py
Python
full_house
full_house
76
90
76
77
54621d6f4941ed8529238fd5fd54d97638f7c195
bigcode/the-stack
train
c2d41f240f83dfd22cd7215a
train
function
@make_category def large_straight(roll, filled_categories): if all(roll[1:] >= (1, 1, 1, 1, 1)): return 25 return 0
@make_category def large_straight(roll, filled_categories):
if all(roll[1:] >= (1, 1, 1, 1, 1)): return 25 return 0
@make_category def small_straight(roll, filled_categories): if all(roll[:5] >= (1, 1, 1, 1, 1)): return 15 return 0 @make_category def large_straight(roll, filled_categories):
64
64
49
15
48
Porpoised/Yahtzee
yahtzotron/rulesets/yatzy.py
Python
large_straight
large_straight
101
106
101
102
d7e6260ec71937708d2f8d6178528eb49d8e53ee
bigcode/the-stack
train
07b5ba938a3d3a461c387255
train
function
@make_category def chance(roll, filled_categories): return sum(die_value * num_dice for die_value, num_dice in enumerate(roll, 1))
@make_category def chance(roll, filled_categories):
return sum(die_value * num_dice for die_value, num_dice in enumerate(roll, 1))
0 @make_category def large_straight(roll, filled_categories): if all(roll[1:] >= (1, 1, 1, 1, 1)): return 25 return 0 @make_category def chance(roll, filled_categories):
64
64
37
12
51
Porpoised/Yahtzee
yahtzotron/rulesets/yatzy.py
Python
chance
chance
109
111
109
110
3f4cf1365b42a302a691006f1d4ad809dba8bac7
bigcode/the-stack
train
7b204d01bb0974554ed8eb79
train
function
@make_category(counts_towards_bonus=True) def threes(roll, filled_categories): return 3 * roll[2]
@make_category(counts_towards_bonus=True) def threes(roll, filled_categories):
return 3 * roll[2]
(roll, filled_categories): return 1 * roll[0] @make_category(counts_towards_bonus=True) def twos(roll, filled_categories): return 2 * roll[1] @make_category(counts_towards_bonus=True) def threes(roll, filled_categories):
64
64
29
20
44
Porpoised/Yahtzee
yahtzotron/rulesets/yatzy.py
Python
threes
threes
14
16
14
15
3ca83822b56916ecc697fa62bc7f915b5b8ef14a
bigcode/the-stack
train
4266cec8ba3c1230c83ed980
train
function
@make_category def three_of_a_kind(roll, filled_categories): for die_value, num_dice in enumerate(roll, 1): if num_dice >= 3: return 3 * die_value return 0
@make_category def three_of_a_kind(roll, filled_categories):
for die_value, num_dice in enumerate(roll, 1): if num_dice >= 3: return 3 * die_value return 0
_pairs[0] best_pairs[0] = die_value if best_pairs[1] == 0: return 0 return 2 * best_pairs[0] + 2 * best_pairs[1] @make_category def three_of_a_kind(roll, filled_categories):
64
64
53
15
49
Porpoised/Yahtzee
yahtzotron/rulesets/yatzy.py
Python
three_of_a_kind
three_of_a_kind
58
64
58
59
0005e14f67966e8cfed63dafbf82a813015fa2f7
bigcode/the-stack
train
14ede44b1c2c4b0aa130ac99
train
function
@make_category(counts_towards_bonus=True) def fives(roll, filled_categories): return 5 * roll[4]
@make_category(counts_towards_bonus=True) def fives(roll, filled_categories):
return 5 * roll[4]
rees(roll, filled_categories): return 3 * roll[2] @make_category(counts_towards_bonus=True) def fours(roll, filled_categories): return 4 * roll[3] @make_category(counts_towards_bonus=True) def fives(roll, filled_categories):
64
64
29
20
44
Porpoised/Yahtzee
yahtzotron/rulesets/yatzy.py
Python
fives
fives
24
26
24
25
41ad98ec05299c6f37877602d746878d17315f82
bigcode/the-stack
train
d78d39bd24e2326cb78615e0
train
function
@make_category(counts_towards_bonus=True) def ones(roll, filled_categories): return 1 * roll[0]
@make_category(counts_towards_bonus=True) def ones(roll, filled_categories):
return 1 * roll[0]
from .base import make_category, Ruleset @make_category(counts_towards_bonus=True) def ones(roll, filled_categories):
29
64
28
19
9
Porpoised/Yahtzee
yahtzotron/rulesets/yatzy.py
Python
ones
ones
4
6
4
5
d33e3be18ab7be0f12ea5e9de0c2e9a5f5fd4d3e
bigcode/the-stack
train
479a4d117c84b9bb08789abb
train
function
@make_category(counts_towards_bonus=True) def fours(roll, filled_categories): return 4 * roll[3]
@make_category(counts_towards_bonus=True) def fours(roll, filled_categories):
return 4 * roll[3]
os(roll, filled_categories): return 2 * roll[1] @make_category(counts_towards_bonus=True) def threes(roll, filled_categories): return 3 * roll[2] @make_category(counts_towards_bonus=True) def fours(roll, filled_categories):
64
64
28
19
45
Porpoised/Yahtzee
yahtzotron/rulesets/yatzy.py
Python
fours
fours
19
21
19
20
44ba0f64e6ce51e8d79c9360662138ec45f2cd75
bigcode/the-stack
train
5234236cee1eaf00586930ec
train
function
@make_category(counts_towards_bonus=True) def twos(roll, filled_categories): return 2 * roll[1]
@make_category(counts_towards_bonus=True) def twos(roll, filled_categories):
return 2 * roll[1]
from .base import make_category, Ruleset @make_category(counts_towards_bonus=True) def ones(roll, filled_categories): return 1 * roll[0] @make_category(counts_towards_bonus=True) def twos(roll, filled_categories):
58
64
29
20
38
Porpoised/Yahtzee
yahtzotron/rulesets/yatzy.py
Python
twos
twos
9
11
9
10
9c040663955cf8558ef11b94c2c7da5aeda3e483
bigcode/the-stack
train
cf109d6e57bf036850f00cf7
train
function
@make_category def two_pairs(roll, filled_categories): best_pairs = [0, 0] for die_value, num_dice in enumerate(roll, 1): if num_dice >= 2: best_pairs[1] = best_pairs[0] best_pairs[0] = die_value if best_pairs[1] == 0: return 0 return 2 * best_pairs[0] + 2 * bes...
@make_category def two_pairs(roll, filled_categories):
best_pairs = [0, 0] for die_value, num_dice in enumerate(roll, 1): if num_dice >= 2: best_pairs[1] = best_pairs[0] best_pairs[0] = die_value if best_pairs[1] == 0: return 0 return 2 * best_pairs[0] + 2 * best_pairs[1]
, filled_categories): best_pair = 0 for die_value, num_dice in enumerate(roll, 1): if num_dice >= 2: best_pair = die_value return best_pair * 2 @make_category def two_pairs(roll, filled_categories):
64
64
105
13
50
Porpoised/Yahtzee
yahtzotron/rulesets/yatzy.py
Python
two_pairs
two_pairs
44
55
44
45
da921f9062635695bb67e431488e5bebd942a0ea
bigcode/the-stack
train
5dab013e7ef100e4a6314427
train
function
@make_category def small_straight(roll, filled_categories): if all(roll[:5] >= (1, 1, 1, 1, 1)): return 15 return 0
@make_category def small_straight(roll, filled_categories):
if all(roll[:5] >= (1, 1, 1, 1, 1)): return 15 return 0
_value elif num_dice == 3: triplet = die_value if doublet is None or triplet is None: return 0 return 3 * triplet + 2 * doublet @make_category def small_straight(roll, filled_categories):
64
64
49
15
48
Porpoised/Yahtzee
yahtzotron/rulesets/yatzy.py
Python
small_straight
small_straight
93
98
93
94
345ebe739af68cb71bed666024f87869419b0f22
bigcode/the-stack
train
65253ba116e5cd99032b4003
train
function
@make_category def four_of_a_kind(roll, filled_categories): for die_value, num_dice in enumerate(roll, 1): if num_dice >= 4: return 4 * die_value return 0
@make_category def four_of_a_kind(roll, filled_categories):
for die_value, num_dice in enumerate(roll, 1): if num_dice >= 4: return 4 * die_value return 0
def three_of_a_kind(roll, filled_categories): for die_value, num_dice in enumerate(roll, 1): if num_dice >= 3: return 3 * die_value return 0 @make_category def four_of_a_kind(roll, filled_categories):
64
64
53
15
48
Porpoised/Yahtzee
yahtzotron/rulesets/yatzy.py
Python
four_of_a_kind
four_of_a_kind
67
73
67
68
aaab488f4b88ddef904e2f5724960767f370f353
bigcode/the-stack
train
712e5f9f29c1cd64375b78f6
train
function
@make_category(counts_towards_bonus=True) def sixes(roll, filled_categories): return 6 * roll[5]
@make_category(counts_towards_bonus=True) def sixes(roll, filled_categories):
return 6 * roll[5]
(roll, filled_categories): return 4 * roll[3] @make_category(counts_towards_bonus=True) def fives(roll, filled_categories): return 5 * roll[4] @make_category(counts_towards_bonus=True) def sixes(roll, filled_categories):
64
64
29
20
44
Porpoised/Yahtzee
yahtzotron/rulesets/yatzy.py
Python
sixes
sixes
29
31
29
30
2694b556f00ddfe9c25d25ba8fa8bfd823caf36a
bigcode/the-stack
train
7587fb3bec8b1ac103f7aec9
train
function
def register(): params = Params() params.put("Version", version) params.put("TermsVersion", terms_version) params.put("TrainingVersion", training_version) params.put("GitCommit", get_git_commit(default="")) params.put("GitBranch", get_git_branch(default="")) params.put("GitRemote", get_git_remote(default...
def register():
params = Params() params.put("Version", version) params.put("TermsVersion", terms_version) params.put("TrainingVersion", training_version) params.put("GitCommit", get_git_commit(default="")) params.put("GitBranch", get_git_branch(default="")) params.put("GitRemote", get_git_remote(default="")) params.p...
import os import json from datetime import datetime, timedelta from selfdrive.swaglog import cloudlog from selfdrive.version import version, terms_version, training_version, get_git_commit, get_git_branch, get_git_remote from common.hardware import HARDWARE from common.api import api_get from common.params import Para...
90
173
578
3
86
Neptos/openpilot
selfdrive/registration.py
Python
register
register
14
65
14
14
3441408380116863bab55e9e4f2b631408df701c
bigcode/the-stack
train
15d808877bdd89ec7a98fef6
train
class
class Player(object): ''' Player object containing name and score ''' def __init__(self, name, score): self.name = name self.score = score def __repr__(self): object_dict = { "name": self.name, "score": self.score } return json.dumps(object_d...
class Player(object):
''' Player object containing name and score ''' def __init__(self, name, score): self.name = name self.score = score def __repr__(self): object_dict = { "name": self.name, "score": self.score } return json.dumps(object_dict) @staticmetho...
''' Sorting: Comparator ''' import json from functools import cmp_to_key class Player(object):
19
64
164
4
14
vineetjohn/ctci-hackerrank
solutions/comparator_sorting.py
Python
Player
Player
7
36
7
7
04b5c2b95be310bb97e9cb8eac7470fcd3674f06
bigcode/the-stack
train
7858e0329e4854c74e6d0f2c
train
function
def main(): ''' Main function ''' player_count = int(input()) data = [] for i in range(player_count): name, score = input().split() score = int(score) player = Player(name, score) data.append(player) data = sorted(data, key=cmp_to_key(Player.comparator)) for i i...
def main():
''' Main function ''' player_count = int(input()) data = [] for i in range(player_count): name, score = input().split() score = int(score) player = Player(name, score) data.append(player) data = sorted(data, key=cmp_to_key(Player.comparator)) for i in data: ...
return -1 if player_1.score < player_2.score: return 1 if player_1.name < player_2.name: return -1 if player_1.name > player_2.name: return 1 return 0 def main():
64
64
84
3
60
vineetjohn/ctci-hackerrank
solutions/comparator_sorting.py
Python
main
main
39
52
39
39
25e82f7a36288b03dc2097e1de2b0841fd6a623c
bigcode/the-stack
train