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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7fb61d062552b18a6bb1b2e7 | train | function | def is_valid_expression(expression):
"""Checks if the given math expression is syntactically valid.
Args:
expression: str. String representation of the math expression.
Returns:
bool. Whether the given math expression is syntactically valid.
"""
try:
Parser().parse(expressi... | def is_valid_expression(expression):
| """Checks if the given math expression is syntactically valid.
Args:
expression: str. String representation of the math expression.
Returns:
bool. Whether the given math expression is syntactically valid.
"""
try:
Parser().parse(expression)
except Exception:
ret... | _token_index < len(token_list):
text = token_list[self._next_token_index].text
if text in allowed_token_texts:
token = token_list[self._next_token_index]
self._next_token_index += 1
return token
return None
def is_valid_expression(expressio... | 64 | 64 | 75 | 6 | 57 | ReshuKumari/oppia | core/domain/expression_parser.py | Python | is_valid_expression | is_valid_expression | 610 | 623 | 610 | 610 | bfaa0453d50e75541c919a4fff11e8b79b61aee4 | bigcode/the-stack | train |
95fe0164530531f5ae449991 | train | class | class UnaryFunctionNode(Node):
"""Class representing the function node. The functions represented by this
class must have exactly one parameter.
"""
def __init__(self, token, child):
"""Initializes a UnaryFunctionNode object.
Args:
token: Token. The token representing the m... | class UnaryFunctionNode(Node):
| """Class representing the function node. The functions represented by this
class must have exactly one parameter.
"""
def __init__(self, token, child):
"""Initializes a UnaryFunctionNode object.
Args:
token: Token. The token representing the math function.
child... | Class representing the number node."""
def __init__(self, token):
"""Initializes a NumberNode object.
Args:
token: Token. The token representing a real number.
"""
self.token = token
super(NumberNode, self).__init__([])
class UnaryFunctionNode(Node):
| 63 | 64 | 99 | 6 | 57 | ReshuKumari/oppia | core/domain/expression_parser.py | Python | UnaryFunctionNode | UnaryFunctionNode | 391 | 404 | 391 | 391 | ee4485e69054fca4d16f063dbe10659bfb45f980 | bigcode/the-stack | train |
4ab7f2be97cc3a4c00e0259f | train | function | def is_algebraic(expression):
"""Checks if the given expression is algebraic. An algebraic expression must
contain at least one valid identifier (latin letter or greek symbol name).
Args:
expression: str. A math expression.
Returns:
bool. Whether the given expression contains at least ... | def is_algebraic(expression):
| """Checks if the given expression is algebraic. An algebraic expression must
contain at least one valid identifier (latin letter or greek symbol name).
Args:
expression: str. A math expression.
Returns:
bool. Whether the given expression contains at least one single latin
lette... | .append(character)
elif character in closers:
if len(stack) == 0:
return False
top_element = stack.pop()
if openers.index(top_element) != closers.index(character):
return False
return len(stack) == 0
def is_algebraic(expression):
| 64 | 64 | 129 | 7 | 56 | ReshuKumari/oppia | core/domain/expression_parser.py | Python | is_algebraic | is_algebraic | 83 | 102 | 83 | 83 | b8a518cf60e957cab20368b4c39a2d2cc88ca528 | bigcode/the-stack | train |
41d4cfc6a99c5a924c85d0aa | train | class | class DivisionOperatorNode(Node):
"""Class representing the division operator node."""
def __init__(self, left, right):
"""Initializes an DivisionOperatorNode object.
Args:
left: Node. Left child of the operator.
right: Node. Right child of the operator.
"""
... | class DivisionOperatorNode(Node):
| """Class representing the division operator node."""
def __init__(self, left, right):
"""Initializes an DivisionOperatorNode object.
Args:
left: Node. Left child of the operator.
right: Node. Right child of the operator.
"""
super(DivisionOperatorNode, s... | , right):
"""Initializes an MultiplicationOperatorNode object.
Args:
left: Node. Left child of the operator.
right: Node. Right child of the operator.
"""
super(MultiplicationOperatorNode, self).__init__([left, right])
class DivisionOperatorNode(Node):
| 64 | 64 | 80 | 6 | 58 | ReshuKumari/oppia | core/domain/expression_parser.py | Python | DivisionOperatorNode | DivisionOperatorNode | 336 | 346 | 336 | 336 | 40db26c9faed7899496209a1b5f042e813af49fc | bigcode/the-stack | train |
56357fecf7491dd7846c0cbd | train | class | class Node(python_utils.OBJECT):
"""Instances of the classes that inherit this class act as nodes of the
parse tree. These could be internal as well as leaf nodes. For leaf nodes,
the children parameter would be an empty list.
NOTE: This class is not supposed to be used independently, but should be
... | class Node(python_utils.OBJECT):
| """Instances of the classes that inherit this class act as nodes of the
parse tree. These could be internal as well as leaf nodes. For leaf nodes,
the children parameter would be an empty list.
NOTE: This class is not supposed to be used independently, but should be
inherited. If the child class re... | text):
"""Checks if the given token represents a valid math operator.
Args:
text: str. String representation of the token.
Returns:
bool. Whether the given string represents a valid math operator.
"""
return text in _VALID_OPERATORS
class Node(python_ut... | 64 | 64 | 185 | 8 | 55 | ReshuKumari/oppia | core/domain/expression_parser.py | Python | Node | Node | 276 | 294 | 276 | 276 | d0805b3ebe8c0f0b3e6ba7ada7bed81704ac75d5 | bigcode/the-stack | train |
3cacd5c38fcebe69dd9a2a49 | train | class | class Token(python_utils.OBJECT):
"""Class for tokens of the math expression."""
def __init__(self, text):
"""Initializes a Token object.
Args:
text: str. String representation of the token.
Raises:
Exception. Invalid token.
"""
self.text = text... | class Token(python_utils.OBJECT):
| """Class for tokens of the math expression."""
def __init__(self, text):
"""Initializes a Token object.
Args:
text: str. String representation of the token.
Raises:
Exception. Invalid token.
"""
self.text = text
# Categorize the token.
... | ):
"""Extracts all variables along with pi and e from a given expression.
Args:
expression: str. A math expression.
Returns:
list(str). A list containing all the variables present in the given
expression.
"""
if '=' in expression:
lhs, rhs = expression.split('=')
... | 141 | 141 | 470 | 8 | 133 | ReshuKumari/oppia | core/domain/expression_parser.py | Python | Token | Token | 202 | 273 | 202 | 202 | c623d51c6acbe74974db205f53f698c5348b074b | bigcode/the-stack | train |
ae29da242476f816b8fd3a40 | train | class | class NumberNode(Node):
"""Class representing the number node."""
def __init__(self, token):
"""Initializes a NumberNode object.
Args:
token: Token. The token representing a real number.
"""
self.token = token
super(NumberNode, self).__init__([])
| class NumberNode(Node):
| """Class representing the number node."""
def __init__(self, token):
"""Initializes a NumberNode object.
Args:
token: Token. The token representing a real number.
"""
self.token = token
super(NumberNode, self).__init__([])
|
symbol name.
"""
def __init__(self, token):
"""Initializes an IdentifierNode object.
Args:
token: Token. The token representing the identifier.
"""
self.token = token
super(IdentifierNode, self).__init__([])
class NumberNode(Node):
| 63 | 64 | 64 | 5 | 58 | ReshuKumari/oppia | core/domain/expression_parser.py | Python | NumberNode | NumberNode | 378 | 388 | 378 | 378 | 8039cd386ed8d78fc8d903c6e26744c3e1210efe | bigcode/the-stack | train |
2be52e83e8d58165812c4400 | train | function | def tokenize(expression):
"""Splits the given expression into separate tokens based on the grammar
definitions.
Args:
expression: str. A math expression.
Returns:
list(Token). A list containing token objects formed from the given math
expression.
Raises:
Exception.... | def tokenize(expression):
| """Splits the given expression into separate tokens based on the grammar
definitions.
Args:
expression: str. A math expression.
Returns:
list(Token). A list containing token objects formed from the given math
expression.
Raises:
Exception. Invalid token.
"""
... | []
for character in expression:
if character in openers:
stack.append(character)
elif character in closers:
if len(stack) == 0:
return False
top_element = stack.pop()
if openers.index(top_element) != closers.index(character):
... | 206 | 206 | 688 | 4 | 202 | ReshuKumari/oppia | core/domain/expression_parser.py | Python | tokenize | tokenize | 105 | 176 | 105 | 105 | c613ecf164269ef4a3f302ce4610e8c5f347ee79 | bigcode/the-stack | train |
2668fa785692e73d6be899cf | train | function | def get_variables(expression):
"""Extracts all variables along with pi and e from a given expression.
Args:
expression: str. A math expression.
Returns:
list(str). A list containing all the variables present in the given
expression.
"""
if '=' in expression:
lhs, rh... | def get_variables(expression):
| """Extracts all variables along with pi and e from a given expression.
Args:
expression: str. A math expression.
Returns:
list(str). A list containing all the variables present in the given
expression.
"""
if '=' in expression:
lhs, rhs = expression.split('=')
... | CLOSING_PARENS) and
(
token_list[i + 1].category in _OPENING_CATEGORIES or
token_list[i + 1].text in _OPENING_PARENS)):
final_token_list.append(Token('*'))
return final_token_list
def get_variables(expression):
| 64 | 64 | 137 | 5 | 58 | ReshuKumari/oppia | core/domain/expression_parser.py | Python | get_variables | get_variables | 179 | 199 | 179 | 179 | cb92779302045ffa690b6934e37801bfd5e2940c | bigcode/the-stack | train |
69cf3243f77f036f6f068760 | train | class | class PowerOperatorNode(Node):
"""Class representing the power operator node."""
def __init__(self, left, right):
"""Initializes an PowerOperatorNode object.
Args:
left: Node. Left child of the operator.
right: Node. Right child of the operator.
"""
supe... | class PowerOperatorNode(Node):
| """Class representing the power operator node."""
def __init__(self, left, right):
"""Initializes an PowerOperatorNode object.
Args:
left: Node. Left child of the operator.
right: Node. Right child of the operator.
"""
super(PowerOperatorNode, self).__in... | left, right):
"""Initializes an DivisionOperatorNode object.
Args:
left: Node. Left child of the operator.
right: Node. Right child of the operator.
"""
super(DivisionOperatorNode, self).__init__([left, right])
class PowerOperatorNode(Node):
| 64 | 64 | 79 | 6 | 58 | ReshuKumari/oppia | core/domain/expression_parser.py | Python | PowerOperatorNode | PowerOperatorNode | 349 | 359 | 349 | 349 | 8601e72fa805a31069999634e3771ee5c6fa7d35 | bigcode/the-stack | train |
0e4115f28c17a4cb72504533 | train | class | class AdditionOperatorNode(Node):
"""Class representing the addition operator node."""
def __init__(self, left, right):
"""Initializes an AdditionOperatorNode object.
Args:
left: Node. Left child of the operator.
right: Node. Right child of the operator.
"""
... | class AdditionOperatorNode(Node):
| """Class representing the addition operator node."""
def __init__(self, left, right):
"""Initializes an AdditionOperatorNode object.
Args:
left: Node. Left child of the operator.
right: Node. Right child of the operator.
"""
super(AdditionOperatorNode, s... | """Initializes a Node object. For ex. 'a + b' will have root node as
'+' and children as ['a', 'b'].
Args:
children: list(Node). Child nodes of the current node.
"""
self.children = children
class AdditionOperatorNode(Node):
| 64 | 64 | 79 | 6 | 57 | ReshuKumari/oppia | core/domain/expression_parser.py | Python | AdditionOperatorNode | AdditionOperatorNode | 297 | 307 | 297 | 297 | da0845c66344f5a8c99fe14ff26e4326a7d464e1 | bigcode/the-stack | train |
77f910642b65c7466e941e2f | train | class | class Parser(python_utils.OBJECT):
"""Class representing the math expression parser.
Implements a greedy, recursive-descent parser that tries to consume
as many tokens as possible while obeying the grammar.
More info about recursive-descent parsers:
https://en.wikipedia.org/wiki/Recursive_descent_pa... | class Parser(python_utils.OBJECT):
| """Class representing the math expression parser.
Implements a greedy, recursive-descent parser that tries to consume
as many tokens as possible while obeying the grammar.
More info about recursive-descent parsers:
https://en.wikipedia.org/wiki/Recursive_descent_parser
"""
def __init__(self... | node. An identifier could be a single
latin letter (uppercase/lowercase) or a greek letter represented by the
symbol name.
"""
def __init__(self, token):
"""Initializes an IdentifierNode object.
Args:
token: Token. The token representing the identifier.
"""
... | 256 | 256 | 1,597 | 8 | 248 | ReshuKumari/oppia | core/domain/expression_parser.py | Python | Parser | Parser | 407 | 607 | 407 | 407 | c8ab68a7b8e495ecfa777ebd27e4556e86a5b662 | bigcode/the-stack | train |
93b7673b30502b7ffdd23aa7 | train | function | def contains_balanced_brackets(expression):
"""Checks if the given expression contains a balanced bracket sequence.
Args:
expression: str. A math expression (algebraic/numeric).
Returns:
bool. Whether the given expression contains a balanced bracket sequence.
"""
openers, closers =... | def contains_balanced_brackets(expression):
| """Checks if the given expression contains a balanced bracket sequence.
Args:
expression: str. A math expression (algebraic/numeric).
Returns:
bool. Whether the given expression contains a balanced bracket sequence.
"""
openers, closers = '({[', ')}]'
stack = []
for charact... | _CATEGORY_NUMBER = 'number'
_TOKEN_CATEGORY_OPERATOR = 'operator'
_OPENING_CATEGORIES = (
_TOKEN_CATEGORY_IDENTIFIER,
_TOKEN_CATEGORY_FUNCTION,
_TOKEN_CATEGORY_NUMBER)
_CLOSING_CATEGORIES = (
_TOKEN_CATEGORY_IDENTIFIER,
_TOKEN_CATEGORY_NUMBER)
def contains_balanced_brackets(expression):
| 64 | 64 | 147 | 8 | 56 | ReshuKumari/oppia | core/domain/expression_parser.py | Python | contains_balanced_brackets | contains_balanced_brackets | 60 | 80 | 60 | 60 | c2593740a98fa60515a587ba4333f3622b42019f | bigcode/the-stack | train |
79634052081e48a2724016ba | train | class | class MultiplicationOperatorNode(Node):
"""Class representing the multiplication operator node."""
def __init__(self, left, right):
"""Initializes an MultiplicationOperatorNode object.
Args:
left: Node. Left child of the operator.
right: Node. Right child of the operato... | class MultiplicationOperatorNode(Node):
| """Class representing the multiplication operator node."""
def __init__(self, left, right):
"""Initializes an MultiplicationOperatorNode object.
Args:
left: Node. Left child of the operator.
right: Node. Right child of the operator.
"""
super(Multiplicat... | , right):
"""Initializes an SubtractionOperatorNode object.
Args:
left: Node. Left child of the operator.
right: Node. Right child of the operator.
"""
super(SubtractionOperatorNode, self).__init__([left, right])
class MultiplicationOperatorNode(Node):
| 64 | 64 | 82 | 7 | 57 | ReshuKumari/oppia | core/domain/expression_parser.py | Python | MultiplicationOperatorNode | MultiplicationOperatorNode | 323 | 333 | 323 | 323 | 7e09ce56f1e7798f036a76dd55299ca401a63b5e | bigcode/the-stack | train |
448e9c0396cc68b8b4fa35db | train | class | class SubtractionOperatorNode(Node):
"""Class representing the subtraction operator node."""
def __init__(self, left, right):
"""Initializes an SubtractionOperatorNode object.
Args:
left: Node. Left child of the operator.
right: Node. Right child of the operator.
... | class SubtractionOperatorNode(Node):
| """Class representing the subtraction operator node."""
def __init__(self, left, right):
"""Initializes an SubtractionOperatorNode object.
Args:
left: Node. Left child of the operator.
right: Node. Right child of the operator.
"""
super(SubtractionOperat... | left, right):
"""Initializes an AdditionOperatorNode object.
Args:
left: Node. Left child of the operator.
right: Node. Right child of the operator.
"""
super(AdditionOperatorNode, self).__init__([left, right])
class SubtractionOperatorNode(Node):
| 64 | 64 | 81 | 7 | 57 | ReshuKumari/oppia | core/domain/expression_parser.py | Python | SubtractionOperatorNode | SubtractionOperatorNode | 310 | 320 | 310 | 310 | dad1d22ce174b9d7f50e9874649e79ab6d8c0daf | bigcode/the-stack | train |
4f9a6f0c25dc6bf6aa9762b0 | train | class | class DynamicTemplate(Declarative):
""" An object which dynamically instantiates a template.
A DynamicTemplate allows a template to be instantiated using the
runtime scope available to RHS expressions.
Creating a DynamicTemplate without a parent is a programming error.
"""
#: The template obj... | class DynamicTemplate(Declarative):
| """ An object which dynamically instantiates a template.
A DynamicTemplate allows a template to be instantiated using the
runtime scope available to RHS expressions.
Creating a DynamicTemplate without a parent is a programming error.
"""
#: The template object to instantiate.
base = d_(Ty... | list of objects which should be tagged.
tags : tuple
A tuple of string tag names. This should be an empty tuple if
no named tags are available.
startag : str
The star tag name. This should be an empty string if there is
no star tag available.
Returns
-------
resul... | 199 | 199 | 664 | 7 | 191 | pberkes/enaml | enaml/core/dynamic_template.py | Python | DynamicTemplate | DynamicTemplate | 63 | 165 | 63 | 63 | 07d72eea107ef49cf6f40d55994a853b3ed1622d | bigcode/the-stack | train |
757d7fa3b0ecfc155d9367d8 | train | function | def make_tagged(items, tags, startag):
""" Create a Tagged object for the given items.
Parameters
----------
items : list
The list of objects which should be tagged.
tags : tuple
A tuple of string tag names. This should be an empty tuple if
no named tags are available.
... | def make_tagged(items, tags, startag):
| """ Create a Tagged object for the given items.
Parameters
----------
items : list
The list of objects which should be tagged.
tags : tuple
A tuple of string tag names. This should be an empty tuple if
no named tags are available.
startag : str
The star tag nam... | ative import Declarative, d_
from .template import Template
class Tagged(ObjectDict):
""" An empty ObjectDict subclass.
This subclass helps provide more informative error messages by
having a class name which reflects it's used.
"""
__slots__ = ()
def make_tagged(items, tags, startag):
| 66 | 67 | 226 | 11 | 55 | pberkes/enaml | enaml/core/dynamic_template.py | Python | make_tagged | make_tagged | 27 | 60 | 27 | 27 | 4be4d3593486f59d2e0ded6e854425dde15583dd | bigcode/the-stack | train |
952d200133e07e3da0f0a81b | train | class | class Tagged(ObjectDict):
""" An empty ObjectDict subclass.
This subclass helps provide more informative error messages by
having a class name which reflects it's used.
"""
__slots__ = ()
| class Tagged(ObjectDict):
| """ An empty ObjectDict subclass.
This subclass helps provide more informative error messages by
having a class name which reflects it's used.
"""
__slots__ = ()
| distributed with this software.
#------------------------------------------------------------------------------
from atom.api import Dict, List, Str, Tuple, Typed, observe
from enaml.application import ScheduledTask, schedule
from enaml.objectdict import ObjectDict
from .declarative import Declarative, d_
from .temp... | 64 | 64 | 42 | 5 | 58 | pberkes/enaml | enaml/core/dynamic_template.py | Python | Tagged | Tagged | 17 | 24 | 17 | 17 | b163b8b67920fb1c9b3638ea0078fe340fdc1fe4 | bigcode/the-stack | train |
fd31a8fe2db9d3530572615a | train | function | def create_user(**params):
return get_user_model().objects.create_user(**params)
| def create_user(**params):
| return get_user_model().objects.create_user(**params)
| from django.test import TestCase
from django.contrib.auth import get_user_model
from django.urls import reverse
from rest_framework.test import APIClient
from rest_framework import status
CREATE_USER_URL = reverse('user:create')
TOKEN_URL = reverse('user:token')
def create_user(**params):
| 60 | 64 | 18 | 6 | 54 | mnaovi/recipe-app-api-django | app/user/tests/test_user_api.py | Python | create_user | create_user | 11 | 12 | 11 | 11 | f46f028f41ce2b233963b1f3912f85be57710cce | bigcode/the-stack | train |
ac901361a5a63d4bdf488199 | train | class | class PublicUserApiTests(TestCase):
"""Test the users API(public)"""
def setUp(self):
self.client = APIClient()
def test_create_valid_user_success(self):
"""Test creating user with valid payload is successful"""
payload = {
'email': 'user@user.com',
'passwo... | class PublicUserApiTests(TestCase):
| """Test the users API(public)"""
def setUp(self):
self.client = APIClient()
def test_create_valid_user_success(self):
"""Test creating user with valid payload is successful"""
payload = {
'email': 'user@user.com',
'password': 'userpass',
'name':... | from django.test import TestCase
from django.contrib.auth import get_user_model
from django.urls import reverse
from rest_framework.test import APIClient
from rest_framework import status
CREATE_USER_URL = reverse('user:create')
TOKEN_URL = reverse('user:token')
def create_user(**params):
return get_user_model()... | 80 | 219 | 733 | 8 | 72 | mnaovi/recipe-app-api-django | app/user/tests/test_user_api.py | Python | PublicUserApiTests | PublicUserApiTests | 15 | 117 | 15 | 15 | 4815f67b166a1194f5bac2fa6d24eac9e43fd336 | bigcode/the-stack | train |
528a85c8bcb1eb05a255a8a7 | train | class | class Base(db.Model, object):
__abstract__ = True
@declared_attr
def __tablename__(self):
return self.__name__.lower()
| class Base(db.Model, object):
| __abstract__ = True
@declared_attr
def __tablename__(self):
return self.__name__.lower()
| License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.'''
from sqlalchemy.ext.declarative import declared_attr
from qsystem import db
class Base(db.Model, ob... | 64 | 64 | 35 | 7 | 56 | dheepak-aot/queue-management-1 | api/app/models/bookings/base.py | Python | Base | Base | 19 | 24 | 19 | 19 | c0a8102f0a74c11873e48a6a710f530c48b5d499 | bigcode/the-stack | train |
5d405f3d270a41763f427ab1 | train | class | class TestArrayTypeValidator(object):
def setup(self):
np = pytest.importorskip("numpy")
self.validators = {
'int_2_3': ArrayTypeValidator("array((2, 3), int)"),
'int_2': ArrayTypeValidator("array(2, int)"),
'int_e_3': ArrayTypeValidator("array((..., 3), int)"),
... | class TestArrayTypeValidator(object):
| def setup(self):
np = pytest.importorskip("numpy")
self.validators = {
'int_2_3': ArrayTypeValidator("array((2, 3), int)"),
'int_2': ArrayTypeValidator("array(2, int)"),
'int_e_3': ArrayTypeValidator("array((..., 3), int)"),
}
self.inputs = {
... | "foo(2, int)", "array(int, 2)",
"array(2, foo)", "array((2, 'foo'), int)",
])
def test_parse_array_type_errors(type_str):
_ = pytest.importorskip("numpy")
with pytest.raises(CodeModelTypeError):
parse_array_type(type_str)
@pytest.mark.parametrize("type_str", [
"array((2,3), int)", "array((2,)... | 235 | 235 | 784 | 7 | 228 | dwhswenson/codemodel | codemodel/tests/type_validation/test_array_validation.py | Python | TestArrayTypeValidator | TestArrayTypeValidator | 52 | 116 | 52 | 52 | 56b5b0729f243087450ea0f3718c3a04a186fb1c | bigcode/the-stack | train |
e3f090eff1a43f8058da9ec9 | train | function | @pytest.mark.parametrize("type_str", [
'int', 'str', 'foo', "array", "array(2, int", "foo(2, int)",
"array(int, 2)", "array(2, foo)", "array((2, 'foo'), int)",
])
def test_is_array_type_false(type_str):
_ = pytest.importorskip("numpy")
assert not is_array_type(type_str)
| @pytest.mark.parametrize("type_str", [
'int', 'str', 'foo', "array", "array(2, int", "foo(2, int)",
"array(int, 2)", "array(2, foo)", "array((2, 'foo'), int)",
])
def test_is_array_type_false(type_str):
| _ = pytest.importorskip("numpy")
assert not is_array_type(type_str)
| @pytest.mark.parametrize("type_str", [
'int', 'str', 'foo', "array", "array(2, int", "foo(2, int)",
"array(int, 2)", "array(2, foo)", "array((2, 'foo'), int)",
])
def test_is_array_type_false(type_str):
| 70 | 64 | 89 | 70 | 0 | dwhswenson/codemodel | codemodel/tests/type_validation/test_array_validation.py | Python | test_is_array_type_false | test_is_array_type_false | 43 | 49 | 43 | 47 | ad03d02737145fe56d8123bc663b05dfcf96fce5 | bigcode/the-stack | train |
9a3e1187627c434b9927da7a | train | function | @pytest.mark.parametrize("type_str, shape, dtype_str", [
("array((2,3), int)", (2,3), 'int'),
("array((2,), float)", (2,), 'float'),
("array(2, int32)", (2,), 'int32'),
("array((2, ...), int)", (2, ...), 'int'),
])
def test_parse_array_type(type_str, shape, dtype_str):
np = pytest.importorskip("nump... | @pytest.mark.parametrize("type_str, shape, dtype_str", [
("array((2,3), int)", (2,3), 'int'),
("array((2,), float)", (2,), 'float'),
("array(2, int32)", (2,), 'int32'),
("array((2, ...), int)", (2, ...), 'int'),
])
def test_parse_array_type(type_str, shape, dtype_str):
| np = pytest.importorskip("numpy")
dtype = np.dtype(dtype_str)
assert parse_array_type(type_str) == (shape, dtype)
| @pytest.mark.parametrize("type_str, shape, dtype_str", [
("array((2,3), int)", (2,3), 'int'),
("array((2,), float)", (2,), 'float'),
("array(2, int32)", (2,), 'int32'),
("array((2, ...), int)", (2, ...), 'int'),
])
def test_parse_array_type(type_str, shape, dtype_str):
| 93 | 64 | 125 | 93 | 0 | dwhswenson/codemodel | codemodel/tests/type_validation/test_array_validation.py | Python | test_parse_array_type | test_parse_array_type | 13 | 22 | 13 | 19 | ea92f92d8254b3a99f36e7dd05f425daa090f1a5 | bigcode/the-stack | train |
bf7d08b8e801c7c3c63f9c22 | train | function | @pytest.mark.parametrize("type_str", [
"array((2,3), int)", "array((2,), float)", "array(2, int32)",
"array((2, ...), int)"
])
def test_is_array_type_true(type_str):
_ = pytest.importorskip("numpy")
assert is_array_type(type_str)
| @pytest.mark.parametrize("type_str", [
"array((2,3), int)", "array((2,), float)", "array(2, int32)",
"array((2, ...), int)"
])
def test_is_array_type_true(type_str):
| _ = pytest.importorskip("numpy")
assert is_array_type(type_str)
| ModelTypeError):
parse_array_type(type_str)
@pytest.mark.parametrize("type_str", [
"array((2,3), int)", "array((2,), float)", "array(2, int32)",
"array((2, ...), int)"
])
def test_is_array_type_true(type_str):
| 64 | 64 | 71 | 53 | 11 | dwhswenson/codemodel | codemodel/tests/type_validation/test_array_validation.py | Python | test_is_array_type_true | test_is_array_type_true | 35 | 41 | 35 | 39 | dd48410f743dc98c0d2e6ada4219b425ce685d26 | bigcode/the-stack | train |
3ff4ef6cd350d683378d1aea | train | class | class TestArrayValidatorFactory(object):
def setup(self):
_ = pytest.importorskip("numpy")
self.type_str = {'good': 'array((2,), int)',
'bad': 'foo'}
self.inputs = {'good': '[1, 2]',
'bad': '[1]'}
self.result = {'good': True, 'bad': Fal... | class TestArrayValidatorFactory(object):
| def setup(self):
_ = pytest.importorskip("numpy")
self.type_str = {'good': 'array((2,), int)',
'bad': 'foo'}
self.inputs = {'good': '[1, 2]',
'bad': '[1]'}
self.result = {'good': True, 'bad': False}
self.factory = ArrayValidator... | 2'
validator = self.validators[name]
input_str = self.inputs[name]
expected = "np.array([1, 2], dtype='int64')\n"
tree = validator.to_ast(input_str)
assert astor.to_source(tree) == expected
class TestArrayValidatorFactory(object):
| 64 | 64 | 200 | 7 | 56 | dwhswenson/codemodel | codemodel/tests/type_validation/test_array_validation.py | Python | TestArrayValidatorFactory | TestArrayValidatorFactory | 118 | 139 | 118 | 118 | 8857203765f0d710d4845e687d81f403f0056fa3 | bigcode/the-stack | train |
17ad5278fe37d1f5b276fd83 | train | function | @pytest.mark.parametrize("type_str", [
"array", "array(2, int", "foo(2, int)", "array(int, 2)",
"array(2, foo)", "array((2, 'foo'), int)",
])
def test_parse_array_type_errors(type_str):
_ = pytest.importorskip("numpy")
with pytest.raises(CodeModelTypeError):
parse_array_type(type_str)
| @pytest.mark.parametrize("type_str", [
"array", "array(2, int", "foo(2, int)", "array(int, 2)",
"array(2, foo)", "array((2, 'foo'), int)",
])
def test_parse_array_type_errors(type_str):
| _ = pytest.importorskip("numpy")
with pytest.raises(CodeModelTypeError):
parse_array_type(type_str)
| , dtype)
@pytest.mark.parametrize("type_str", [
"array", "array(2, int", "foo(2, int)", "array(int, 2)",
"array(2, foo)", "array((2, 'foo'), int)",
])
def test_parse_array_type_errors(type_str):
| 64 | 64 | 87 | 61 | 3 | dwhswenson/codemodel | codemodel/tests/type_validation/test_array_validation.py | Python | test_parse_array_type_errors | test_parse_array_type_errors | 25 | 32 | 25 | 29 | 3834357347dc26bec8c201050c1dd9969e521849 | bigcode/the-stack | train |
f4534176a162bd8251e0f09a | train | function | def DenseNetImageNet201(input_shape=None,
bottleneck=True,
reduction=0.5,
dropout_rate=0.0,
weight_decay=1e-4,
include_top=True,
weights=None,
input_ten... | def DenseNetImageNet201(input_shape=None,
bottleneck=True,
reduction=0.5,
dropout_rate=0.0,
weight_decay=1e-4,
include_top=True,
weights=None,
input_ten... | return DenseNet(input_shape, depth=201, nb_dense_block=4, growth_rate=32,
nb_filter=64, nb_layers_per_block=[6, 12, 48, 32],
bottleneck=bottleneck, reduction=reduction,
dropout_rate=dropout_rate, weight_decay=weight_decay,
subsample_ini... | def DenseNetImageNet201(input_shape=None,
bottleneck=True,
reduction=0.5,
dropout_rate=0.0,
weight_decay=1e-4,
include_top=True,
weights=None,
input_ten... | 69 | 64 | 175 | 69 | 0 | szkocot/keras-contrib | keras_contrib/applications/densenet.py | Python | DenseNetImageNet201 | DenseNetImageNet201 | 486 | 503 | 486 | 496 | e6b28d0dd53b1b058d609eb25470fe6422d50f16 | bigcode/the-stack | train |
1032f06aa9bf114372478d2a | train | function | def __transition_up_block(ip, nb_filters, type='deconv', weight_decay=1E-4,
block_prefix=None):
'''Adds an upsampling block. Upsampling operation relies on the the type parameter.
# Arguments
ip: input keras tensor
nb_filters: integer, the dimensionality of the output ... | def __transition_up_block(ip, nb_filters, type='deconv', weight_decay=1E-4,
block_prefix=None):
| '''Adds an upsampling block. Upsampling operation relies on the the type parameter.
# Arguments
ip: input keras tensor
nb_filters: integer, the dimensionality of the output space
(i.e. the number output of filters in the convolution)
type: can be 'upsampling', 'subpixel', 'd... | = Activation('relu')(x)
x = Conv2D(int(nb_filter * compression), (1, 1), kernel_initializer='he_normal',
padding='same', use_bias=False, kernel_regularizer=l2(weight_decay),
name=name_or_none(block_prefix, '_conv2D'))(x)
if transition_pooling == 'avg':
... | 158 | 158 | 529 | 28 | 129 | szkocot/keras-contrib | keras_contrib/applications/densenet.py | Python | __transition_up_block | __transition_up_block | 708 | 756 | 708 | 709 | f7e90388ea3864fb9bc6b992aae82ef922114a30 | bigcode/the-stack | train |
3585e69fd9a273f1cd5689c8 | train | function | def DenseNetImageNet121(input_shape=None,
bottleneck=True,
reduction=0.5,
dropout_rate=0.0,
weight_decay=1e-4,
include_top=True,
weights='imagenet',
inp... | def DenseNetImageNet121(input_shape=None,
bottleneck=True,
reduction=0.5,
dropout_rate=0.0,
weight_decay=1e-4,
include_top=True,
weights='imagenet',
inp... | return DenseNet(input_shape, depth=121, nb_dense_block=4, growth_rate=32,
nb_filter=64, nb_layers_per_block=[6, 12, 24, 16],
bottleneck=bottleneck, reduction=reduction,
dropout_rate=dropout_rate, weight_decay=weight_decay,
subsample_ini... | def DenseNetImageNet121(input_shape=None,
bottleneck=True,
reduction=0.5,
dropout_rate=0.0,
weight_decay=1e-4,
include_top=True,
weights='imagenet',
inp... | 71 | 64 | 177 | 71 | 0 | szkocot/keras-contrib | keras_contrib/applications/densenet.py | Python | DenseNetImageNet121 | DenseNetImageNet121 | 446 | 463 | 446 | 456 | daef48e764d599598fec51d41a5f0d02342a41fa | bigcode/the-stack | train |
39c8458498417355d08c96a8 | train | function | def __transition_block(ip, nb_filter, compression=1.0, weight_decay=1e-4,
block_prefix=None, transition_pooling='max'):
'''
Adds a pointwise convolution layer (with batch normalization and relu),
and an average pooling layer. The number of output convolution filters
can be reduced... | def __transition_block(ip, nb_filter, compression=1.0, weight_decay=1e-4,
block_prefix=None, transition_pooling='max'):
| '''
Adds a pointwise convolution layer (with batch normalization and relu),
and an average pooling layer. The number of output convolution filters
can be reduced by appropriately reducing the compression parameter.
# Arguments
ip: input keras tensor
nb_filter: integer, the dimension... | else -1
x_list = [x]
for i in range(nb_layers):
cb = __conv_block(x, growth_rate, bottleneck, dropout_rate, weight_decay,
block_prefix=name_or_none(block_prefix, '_%i' % i))
x_list.append(cb)
x = concatenate([x, cb], axis=concat_axis)... | 148 | 148 | 495 | 34 | 113 | szkocot/keras-contrib | keras_contrib/applications/densenet.py | Python | __transition_block | __transition_block | 658 | 705 | 658 | 659 | a0ad94b842df9e15e28aa8e3d2aedf88399cba5b | bigcode/the-stack | train |
ce2e01d379004e72b735aad2 | train | function | def DenseNetImageNet264(input_shape=None,
bottleneck=True,
reduction=0.5,
dropout_rate=0.0,
weight_decay=1e-4,
include_top=True,
weights=None,
input_ten... | def DenseNetImageNet264(input_shape=None,
bottleneck=True,
reduction=0.5,
dropout_rate=0.0,
weight_decay=1e-4,
include_top=True,
weights=None,
input_ten... | return DenseNet(input_shape, depth=264, nb_dense_block=4, growth_rate=32,
nb_filter=64, nb_layers_per_block=[6, 12, 64, 48],
bottleneck=bottleneck, reduction=reduction,
dropout_rate=dropout_rate, weight_decay=weight_decay,
subsample_ini... | def DenseNetImageNet264(input_shape=None,
bottleneck=True,
reduction=0.5,
dropout_rate=0.0,
weight_decay=1e-4,
include_top=True,
weights=None,
input_ten... | 69 | 64 | 175 | 69 | 0 | szkocot/keras-contrib | keras_contrib/applications/densenet.py | Python | DenseNetImageNet264 | DenseNetImageNet264 | 506 | 523 | 506 | 516 | 25f81d1a6c71f8878f18be2be92032214cc3f900 | bigcode/the-stack | train |
90ac66c0401d91d4ec2cc2a3 | train | function | def DenseNetImageNet161(input_shape=None,
bottleneck=True,
reduction=0.5,
dropout_rate=0.0,
weight_decay=1e-4,
include_top=True,
weights='imagenet',
inp... | def DenseNetImageNet161(input_shape=None,
bottleneck=True,
reduction=0.5,
dropout_rate=0.0,
weight_decay=1e-4,
include_top=True,
weights='imagenet',
inp... | return DenseNet(input_shape, depth=161, nb_dense_block=4, growth_rate=48,
nb_filter=96, nb_layers_per_block=[6, 12, 36, 24],
bottleneck=bottleneck, reduction=reduction,
dropout_rate=dropout_rate, weight_decay=weight_decay,
subsample_ini... | def DenseNetImageNet161(input_shape=None,
bottleneck=True,
reduction=0.5,
dropout_rate=0.0,
weight_decay=1e-4,
include_top=True,
weights='imagenet',
inp... | 71 | 64 | 177 | 71 | 0 | szkocot/keras-contrib | keras_contrib/applications/densenet.py | Python | DenseNetImageNet161 | DenseNetImageNet161 | 526 | 543 | 526 | 536 | f150b36786dd02e529dee54311aaf284c1f30acc | bigcode/the-stack | train |
d5646daa809469a4c6f5486f | train | function | def __conv_block(ip, nb_filter, bottleneck=False, dropout_rate=None,
weight_decay=1e-4, block_prefix=None):
'''
Adds a convolution layer (with batch normalization and relu),
and optionally a bottleneck layer.
# Arguments
ip: Input tensor
nb_filter: integer, the dimensio... | def __conv_block(ip, nb_filter, bottleneck=False, dropout_rate=None,
weight_decay=1e-4, block_prefix=None):
| '''
Adds a convolution layer (with batch normalization and relu),
and optionally a bottleneck layer.
# Arguments
ip: Input tensor
nb_filter: integer, the dimensionality of the output space
(i.e. the number output of filters in the convolution)
bottleneck: if True, ad... | _shape, depth=161, nb_dense_block=4, growth_rate=48,
nb_filter=96, nb_layers_per_block=[6, 12, 36, 24],
bottleneck=bottleneck, reduction=reduction,
dropout_rate=dropout_rate, weight_decay=weight_decay,
subsample_initial_block=True, include_... | 159 | 159 | 530 | 30 | 128 | szkocot/keras-contrib | keras_contrib/applications/densenet.py | Python | __conv_block | __conv_block | 550 | 604 | 550 | 551 | 0fa0eeb63cbc6b44a433bf82e4cfc0d7105c8a9e | bigcode/the-stack | train |
d0d964658757ea621e8ca20c | train | function | def name_or_none(prefix, name):
return prefix + name if (prefix is not None and name is not None) else None
| def name_or_none(prefix, name):
| return prefix + name if (prefix is not None and name is not None) else None
| , reduction=reduction,
dropout_rate=dropout_rate, weight_decay=weight_decay,
subsample_initial_block=True, include_top=include_top,
weights=weights, input_tensor=input_tensor,
pooling=pooling, classes=classes, activation=activation)
def nam... | 64 | 64 | 28 | 8 | 56 | szkocot/keras-contrib | keras_contrib/applications/densenet.py | Python | name_or_none | name_or_none | 546 | 547 | 546 | 546 | 862a108f20bce88f64c05aab1ac4f862697a638d | bigcode/the-stack | train |
abeeb9c2d5be7758027a2022 | train | function | def DenseNetImageNet169(input_shape=None,
bottleneck=True,
reduction=0.5,
dropout_rate=0.0,
weight_decay=1e-4,
include_top=True,
weights='imagenet',
inp... | def DenseNetImageNet169(input_shape=None,
bottleneck=True,
reduction=0.5,
dropout_rate=0.0,
weight_decay=1e-4,
include_top=True,
weights='imagenet',
inp... | return DenseNet(input_shape, depth=169, nb_dense_block=4, growth_rate=32,
nb_filter=64, nb_layers_per_block=[6, 12, 32, 32],
bottleneck=bottleneck, reduction=reduction,
dropout_rate=dropout_rate, weight_decay=weight_decay,
subsample_ini... | def DenseNetImageNet169(input_shape=None,
bottleneck=True,
reduction=0.5,
dropout_rate=0.0,
weight_decay=1e-4,
include_top=True,
weights='imagenet',
inp... | 71 | 64 | 177 | 71 | 0 | szkocot/keras-contrib | keras_contrib/applications/densenet.py | Python | DenseNetImageNet169 | DenseNetImageNet169 | 466 | 483 | 466 | 476 | e8aa379d3fcebf141a92e333ff891d10150574e5 | bigcode/the-stack | train |
1d43ce7d9d58b7481a90bbc4 | train | function | def __create_fcn_dense_net(nb_classes, img_input, include_top, nb_dense_block=5,
growth_rate=12, reduction=0.0, dropout_rate=None,
weight_decay=1e-4, nb_layers_per_block=4,
nb_upsampling_conv=128, upsampling_type='deconv',
... | def __create_fcn_dense_net(nb_classes, img_input, include_top, nb_dense_block=5,
growth_rate=12, reduction=0.0, dropout_rate=None,
weight_decay=1e-4, nb_layers_per_block=4,
nb_upsampling_conv=128, upsampling_type='deconv',
... | ''' Build the DenseNet-FCN model
# Arguments
nb_classes: number of classes
img_input: tuple of shape (channels, rows, columns) or (rows, columns, channels)
include_top: flag to include the final Dense layer
nb_dense_block: number of dense blocks to add to end (generally = 3)
... | block_prefix='dense_%i' % (nb_dense_block - 1))
x = BatchNormalization(axis=concat_axis, epsilon=1.1e-5, name='final_bn')(x)
x = Activation('relu')(x)
if include_top:
if pooling == 'avg':
x = GlobalAveragePooling2D()(x)
... | 256 | 256 | 1,793 | 107 | 148 | szkocot/keras-contrib | keras_contrib/applications/densenet.py | Python | __create_fcn_dense_net | __create_fcn_dense_net | 911 | 1,089 | 911 | 917 | e5defb2ce8c0c3bd51fe990b4986eccd56fb1110 | bigcode/the-stack | train |
30fbff61afc58e81a808a3b7 | train | function | def preprocess_input(x, data_format=None):
"""Preprocesses a tensor encoding a batch of images.
# Arguments
x: input Numpy tensor, 4D.
data_format: data format of the image tensor.
# Returns
Preprocessed tensor.
"""
x = _preprocess_input(x, data_format=data_format)
x *=... | def preprocess_input(x, data_format=None):
| """Preprocesses a tensor encoding a batch of images.
# Arguments
x: input Numpy tensor, 4D.
data_format: data format of the image tensor.
# Returns
Preprocessed tensor.
"""
x = _preprocess_input(x, data_format=data_format)
x *= 0.017 # scale values
return x
| 48-no-top.h5')
DENSENET_169_WEIGHTS_PATH_NO_TOP = (r'https://github.com/titu1994/DenseNet/releases/'
r'download/v3.0/DenseNet-BC-169-32-no-top.h5')
def preprocess_input(x, data_format=None):
| 64 | 64 | 90 | 9 | 55 | szkocot/keras-contrib | keras_contrib/applications/densenet.py | Python | preprocess_input | preprocess_input | 91 | 103 | 91 | 91 | 4d1408ac4bef059d0af6438007a9e33f19245c07 | bigcode/the-stack | train |
6c7b80a1f40baa2591bcb804 | train | function | def DenseNet(input_shape=None,
depth=40,
nb_dense_block=3,
growth_rate=12,
nb_filter=-1,
nb_layers_per_block=-1,
bottleneck=False,
reduction=0.0,
dropout_rate=0.0,
weight_decay=1e-4,
subsamp... | def DenseNet(input_shape=None,
depth=40,
nb_dense_block=3,
growth_rate=12,
nb_filter=-1,
nb_layers_per_block=-1,
bottleneck=False,
reduction=0.0,
dropout_rate=0.0,
weight_decay=1e-4,
subsamp... | '''Instantiate the DenseNet architecture.
The model and the weights are compatible with both
TensorFlow and Theano. The dimension ordering
convention used by the model is the one
specified in your Keras config file.
# Arguments
input_shape: optional shape tuple, only to be specified
... | 48-no-top.h5')
DENSENET_169_WEIGHTS_PATH_NO_TOP = (r'https://github.com/titu1994/DenseNet/releases/'
r'download/v3.0/DenseNet-BC-169-32-no-top.h5')
def preprocess_input(x, data_format=None):
"""Preprocesses a tensor encoding a batch of images.
# Arguments
x: input ... | 256 | 256 | 2,069 | 111 | 144 | szkocot/keras-contrib | keras_contrib/applications/densenet.py | Python | DenseNet | DenseNet | 106 | 310 | 106 | 123 | 57a12c5a284ab5077263dc750b045ffc9edc5f72 | bigcode/the-stack | train |
89f4da6728682044b0130f45 | train | function | def DenseNetFCN(input_shape, nb_dense_block=5, growth_rate=16, nb_layers_per_block=4,
reduction=0.0, dropout_rate=0.0, weight_decay=1E-4,
init_conv_filters=48, include_top=True, weights=None, input_tensor=None,
classes=1, activation='softmax', upsampling_conv=128,
... | def DenseNetFCN(input_shape, nb_dense_block=5, growth_rate=16, nb_layers_per_block=4,
reduction=0.0, dropout_rate=0.0, weight_decay=1E-4,
init_conv_filters=48, include_top=True, weights=None, input_tensor=None,
classes=1, activation='softmax', upsampling_conv=128,
... | '''Instantiate the DenseNet FCN architecture.
Note that when using TensorFlow,
for best performance you should set
`image_data_format='channels_last'` in your Keras config
at ~/.keras/keras.json.
# Arguments
nb_dense_block: number of dense blocks to add to end (ge... | weights_loaded = True
if weights_loaded:
if K.backend() == 'theano':
convert_all_kernels_in_model(model)
if ((K.image_data_format() == 'channels_first') and
(K.backend() == 'tensorflow')):
warnings.warn('You are using the ... | 256 | 256 | 1,441 | 110 | 145 | szkocot/keras-contrib | keras_contrib/applications/densenet.py | Python | DenseNetFCN | DenseNetFCN | 313 | 443 | 313 | 318 | b3b72b742ddd0c0714727423df2cde5ec80a4a8f | bigcode/the-stack | train |
3b5b4cdc448f485b7e6f022b | train | function | def __create_dense_net(nb_classes, img_input, include_top, depth=40, nb_dense_block=3,
growth_rate=12, nb_filter=-1, nb_layers_per_block=-1,
bottleneck=False, reduction=0.0, dropout_rate=None,
weight_decay=1e-4, subsample_initial_block=False, pooling=... | def __create_dense_net(nb_classes, img_input, include_top, depth=40, nb_dense_block=3,
growth_rate=12, nb_filter=-1, nb_layers_per_block=-1,
bottleneck=False, reduction=0.0, dropout_rate=None,
weight_decay=1e-4, subsample_initial_block=False, pooling=... | ''' Build the DenseNet model
# Arguments
nb_classes: number of classes
img_input: tuple of shape (channels, rows, columns) or (rows, columns, channels)
include_top: flag to include the final Dense layer
depth: number or layers
nb_dense_block: number of dense blocks to ad... | _or_none(block_prefix, '_conv2D'))(ip)
x = SubPixelUpscaling(scale_factor=2,
name=name_or_none(block_prefix, '_subpixel'))(x)
x = Conv2D(nb_filters, (3, 3), activation='relu', padding='same',
kernel_regularizer=l2(weight_decay), use_bias=F... | 256 | 256 | 1,523 | 87 | 168 | szkocot/keras-contrib | keras_contrib/applications/densenet.py | Python | __create_dense_net | __create_dense_net | 759 | 908 | 759 | 763 | 591f346cdc6ff8af42b9797f920790df67bb5913 | bigcode/the-stack | train |
18871f1d676440ab5ebb7b98 | train | function | def __dense_block(x, nb_layers, nb_filter, growth_rate, bottleneck=False,
dropout_rate=None, weight_decay=1e-4, grow_nb_filters=True,
return_concat_list=False, block_prefix=None):
'''
Build a dense_block where the output of each conv_block is fed
to subsequent ones
#... | def __dense_block(x, nb_layers, nb_filter, growth_rate, bottleneck=False,
dropout_rate=None, weight_decay=1e-4, grow_nb_filters=True,
return_concat_list=False, block_prefix=None):
| '''
Build a dense_block where the output of each conv_block is fed
to subsequent ones
# Arguments
x: input keras tensor
nb_layers: the number of conv_blocks to append to the model
nb_filter: integer, the dimensionality of the output space
(i.e. the number output of f... | ottleneck_bn'))(x)
x = Activation('relu')(x)
x = Conv2D(nb_filter, (3, 3), kernel_initializer='he_normal', padding='same',
use_bias=False, name=name_or_none(block_prefix, '_conv2D'))(x)
if dropout_rate:
x = Dropout(dropout_rate)(x)
return x
def __dense_bl... | 128 | 128 | 427 | 47 | 80 | szkocot/keras-contrib | keras_contrib/applications/densenet.py | Python | __dense_block | __dense_block | 607 | 655 | 607 | 609 | 3a07f3a2c6d999a0b4e30c5d80c76cc3424e1399 | bigcode/the-stack | train |
f6a3052c8c881af55a4a9453 | train | function | def sentences_from_sentences_file(sentences_filename: str) -> Dict[int, List[str]]:
all_sentences = dict() # type: Dict[Tuple[int, int], str]
with open(sentences_filename) as f:
for line in f:
process_id_str, sentence_number_str, text = line.strip().split('\t', 3)[:3]
process_i... | def sentences_from_sentences_file(sentences_filename: str) -> Dict[int, List[str]]:
| all_sentences = dict() # type: Dict[Tuple[int, int], str]
with open(sentences_filename) as f:
for line in f:
process_id_str, sentence_number_str, text = line.strip().split('\t', 3)[:3]
process_id = int(process_id_str)
sentence_number = int(sentence_number_str)
... | from collections import defaultdict
from typing import Dict, List, Tuple
def sentences_from_sentences_file(sentences_filename: str) -> Dict[int, List[str]]:
| 33 | 64 | 167 | 19 | 13 | allenai/aristo-leaderboard | propara/evaluator/process/sentence_file.py | Python | sentences_from_sentences_file | sentences_from_sentences_file | 5 | 21 | 5 | 5 | ed7d273d29f18a5d379db802a74dadd63ca96e14 | bigcode/the-stack | train |
3f4cdc36fa1b7e318e0e8443 | train | class | class rconUpdatingPlayerInfo():
def __init__(self, database_info, date_today, server_rcon_info, threadID):
self.server_rcon_info = server_rcon_info
self.threadID = threadID
self.database_info = database_info
self.date_today = date_today
self.server_name = list(server_rcon_inf... | class rconUpdatingPlayerInfo():
| def __init__(self, database_info, date_today, server_rcon_info, threadID):
self.server_rcon_info = server_rcon_info
self.threadID = threadID
self.database_info = database_info
self.date_today = date_today
self.server_name = list(server_rcon_info.keys())[threadID]
self... | import re
from Core.Rcon_Plugins.Rcon_ListPlayers import Rcon_ListPlayers
from Core.Rcon_Plugins.Rcon_AdminListDisconnectPlayers import Rcon_AdminListDisconnectPlayers
from Core.SQL_Plugins.SQL_PlayerInfoReplace import SQL_PlayerInfoReplace
class rconUpdatingPlayerInfo():
| 61 | 186 | 622 | 7 | 53 | ChenjianS47/SquadPy | Core/Core_Rcon_UpdatingPlayerInfo.py | Python | rconUpdatingPlayerInfo | rconUpdatingPlayerInfo | 9 | 62 | 9 | 9 | 3e16d81593df5d31a823ea7bad2742525c0194f4 | bigcode/the-stack | train |
294768f1e778e9369752efce | train | class | class ShellError(Exception):
# TODO: Getting the correct help message needs work
def __init__(self, instance, msg):
self.help = instance.help
self.msg = msg
def __str__(self):
return self.msg
| class ShellError(Exception):
# TODO: Getting the correct help message needs work
| def __init__(self, instance, msg):
self.help = instance.help
self.msg = msg
def __str__(self):
return self.msg
| ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import print_function
from lunrclient.subcommand import SubCommand
import os
class ShellError(Exception):
# TODO: Getting the correct help message needs wor... | 64 | 64 | 53 | 17 | 46 | PythonGirlSam/python-lunrclient | lunrclient/shared.py | Python | ShellError | ShellError | 21 | 29 | 21 | 23 | add5f0334b688c3ee677d04eba4e74e89afda947 | bigcode/the-stack | train |
49c301da0920d062f1e1e123 | train | class | class Env(SubCommand):
"""
Display Available environment options
"""
def __init__(self):
# Give our sub command a name
self._name = 'env'
# let the base class setup methods in our class
SubCommand.__init__(self)
def help(self):
print("# Available environment... | class Env(SubCommand):
| """
Display Available environment options
"""
def __init__(self):
# Give our sub command a name
self._name = 'env'
# let the base class setup methods in our class
SubCommand.__init__(self)
def help(self):
print("# Available environment variables")
pr... | SubCommand
import os
class ShellError(Exception):
# TODO: Getting the correct help message needs work
def __init__(self, instance, msg):
self.help = instance.help
self.msg = msg
def __str__(self):
return self.msg
class Env(SubCommand):
| 64 | 64 | 210 | 5 | 58 | PythonGirlSam/python-lunrclient | lunrclient/shared.py | Python | Env | Env | 32 | 55 | 32 | 32 | 5b99799a776ed99dfed0f2f42e03383fb2c191da | bigcode/the-stack | train |
e1d7650d3be5b0e5697bc02a | train | class | class StaticRootS3Boto3Storage(S3Boto3Storage):
location = 'static'
| class StaticRootS3Boto3Storage(S3Boto3Storage):
| location = 'static'
| .com/questions/10390244/
# Full-fledge class: https://stackoverflow.com/a/18046120/104731
from storages.backends.s3boto3 import S3Boto3Storage # noqa E402
class StaticRootS3Boto3Storage(S3Boto3Storage):
| 64 | 64 | 22 | 16 | 47 | eueezy61/wavee | config/settings/production.py | Python | StaticRootS3Boto3Storage | StaticRootS3Boto3Storage | 94 | 95 | 94 | 94 | a51ef1edb51c08d6de77a3d6a2761a629306e79a | bigcode/the-stack | train |
ad2342c2e35bc4c8d50c866b | train | class | class MediaRootS3Boto3Storage(S3Boto3Storage):
location = 'media'
file_overwrite = False
| class MediaRootS3Boto3Storage(S3Boto3Storage):
| location = 'media'
file_overwrite = False
| /104731
from storages.backends.s3boto3 import S3Boto3Storage # noqa E402
class StaticRootS3Boto3Storage(S3Boto3Storage):
location = 'static'
class MediaRootS3Boto3Storage(S3Boto3Storage):
| 64 | 64 | 29 | 16 | 48 | eueezy61/wavee | config/settings/production.py | Python | MediaRootS3Boto3Storage | MediaRootS3Boto3Storage | 98 | 100 | 98 | 98 | 11f8cc38e3b6bf51f31bdb677532163b783e2597 | bigcode/the-stack | train |
d11176b5f2ad03f61d89937a | train | class | class ResourceTag:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
... | class ResourceTag:
| """
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
openapi_types = {
... | # coding: utf-8
import re
import six
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class ResourceTag:
| 32 | 256 | 902 | 4 | 27 | huaweicloud/huaweicloud-sdk-python-v3 | huaweicloud-sdk-smn/huaweicloudsdksmn/v2/model/resource_tag.py | Python | ResourceTag | ResourceTag | 11 | 139 | 11 | 13 | 1414fa3650b445920d61ac45e57c807c543f76bc | bigcode/the-stack | train |
b455a5bbe78633696884da8f | train | class | class SeqdbUpdater:
def __init__(self, seqdb, filename, normalize_names=True, load=False, hidb=None):
self.seqdb = seqdb
self.filename = Path(filename)
self.normalize_names = normalize_names
self.hidb = hidb
if load:
self.load()
def load(self):
if se... | class SeqdbUpdater:
| def __init__(self, seqdb, filename, normalize_names=True, load=False, hidb=None):
self.seqdb = seqdb
self.filename = Path(filename)
self.normalize_names = normalize_names
self.hidb = hidb
if load:
self.load()
def load(self):
if self.filename.is_file()... | # -*- Python -*-
# license
# license.
# ----------------------------------------------------------------------
import os, re, pprint
import logging; module_logger = logging.getLogger(__name__)
from pathlib import Path
from . import acmacs, open_file, hidb as hidb_m
# --------------------------------------------------... | 62 | 256 | 2,191 | 5 | 57 | acorg/seqdb-make-tree-signature-page | python/seqdb/update.py | Python | SeqdbUpdater | SeqdbUpdater | 13 | 179 | 13 | 14 | 536b2abc0f6d0ed9fadd95b94eb2120ca7ae09bd | bigcode/the-stack | train |
11454015e9be431e30646a74 | train | function | def test_distribmat():
harness = DistribmatTestHarness('statepoint.5.h5')
harness.main()
| def test_distribmat():
| harness = DistribmatTestHarness('statepoint.5.h5')
harness.main()
| , plot2])
plots.export_to_xml()
def _get_results(self):
outstr = super()._get_results()
su = openmc.Summary('summary.h5')
outstr += str(su.geometry.get_all_cells()[11])
return outstr
def test_distribmat():
| 64 | 64 | 25 | 6 | 57 | aprilnovak/openmc | tests/regression_tests/distribmat/test.py | Python | test_distribmat | test_distribmat | 102 | 104 | 102 | 102 | 3bf543febcc00e15f04cd9a544934284b6dca180 | bigcode/the-stack | train |
95ca69a4391d7de052eab2f6 | train | class | class DistribmatTestHarness(PyAPITestHarness):
def _build_inputs(self):
####################
# Materials
####################
moderator = openmc.Material(material_id=1)
moderator.set_density('g/cc', 1.0)
moderator.add_nuclide('H1', 2.0)
moderator.add_nuclide(... | class DistribmatTestHarness(PyAPITestHarness):
| def _build_inputs(self):
####################
# Materials
####################
moderator = openmc.Material(material_id=1)
moderator.set_density('g/cc', 1.0)
moderator.add_nuclide('H1', 2.0)
moderator.add_nuclide('O16', 1.0)
dense_fuel = openmc.Materi... | import openmc
from tests.testing_harness import TestHarness, PyAPITestHarness
class DistribmatTestHarness(PyAPITestHarness):
| 28 | 256 | 894 | 10 | 17 | aprilnovak/openmc | tests/regression_tests/distribmat/test.py | Python | DistribmatTestHarness | DistribmatTestHarness | 6 | 99 | 6 | 6 | 828e9eb940bfcb9694b0cee76845999904ac987e | bigcode/the-stack | train |
6577e01cb901cfbdb158df3e | train | function | def plot_decision(model, X, y, title, xlabel, ylabel):
cmap = ListedColormap(["#fafab0", "#9898ff", "#a0faa0"])
x_s = np.linspace(X[:, 0].min() - 0.2, X[:, 0].max() + 0.2);
y_s = np.linspace(X[:, 1].min() - 0.2, X[:, 1].max() + 0.2);
xx, yy = np.meshgrid(x_s, y_s);
X_s = np.c_[xx.ravel(), yy.ravel()... | def plot_decision(model, X, y, title, xlabel, ylabel):
| cmap = ListedColormap(["#fafab0", "#9898ff", "#a0faa0"])
x_s = np.linspace(X[:, 0].min() - 0.2, X[:, 0].max() + 0.2);
y_s = np.linspace(X[:, 1].min() - 0.2, X[:, 1].max() + 0.2);
xx, yy = np.meshgrid(x_s, y_s);
X_s = np.c_[xx.ravel(), yy.ravel()];
zz = model.predict(X_s).reshape(xx.shape);
p... | import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import ListedColormap
def plot_decision(model, X, y, title, xlabel, ylabel):
| 35 | 64 | 197 | 16 | 18 | cesar0205/machine_learning_algorithms | misc/plot_functions.py | Python | plot_decision | plot_decision | 7 | 19 | 7 | 7 | 71f122027366d2ade472f0e232bc9b95df534c74 | bigcode/the-stack | train |
2bca94411ab5422b8c7bf237 | train | function | def broadcast_dp_parameters(model, hcg):
data_parallel_group = hcg.get_data_parallel_group()
src_rank = hcg.get_data_parallel_group_src_rank()
sync_params_buffers(
model, data_parallel_group, src_rank, is_model_parallel=False)
| def broadcast_dp_parameters(model, hcg):
| data_parallel_group = hcg.get_data_parallel_group()
src_rank = hcg.get_data_parallel_group_src_rank()
sync_params_buffers(
model, data_parallel_group, src_rank, is_model_parallel=False)
|
def broadcast_mp_parameters(model, hcg):
model_parallel_group = hcg.get_model_parallel_group()
src_rank = hcg.get_model_parallel_group_src_rank()
sync_params_buffers(
model, model_parallel_group, src_rank, is_model_parallel=True)
def broadcast_dp_parameters(model, hcg):
| 64 | 64 | 54 | 9 | 55 | andreazanetti/Paddle | python/paddle/distributed/fleet/utils/hybrid_parallel_util.py | Python | broadcast_dp_parameters | broadcast_dp_parameters | 100 | 104 | 100 | 100 | e61b96e0926e70b3ebd3e93e9aa004af90fa35d5 | bigcode/the-stack | train |
1a61a309a0baba73323c086a | train | function | def fused_allreduce_gradients(parameter_list, hcg):
data_parallel_group = hcg.get_data_parallel_group()
logger.debug("dp start fuse allreduce gradients")
with framework.no_grad():
_apply_collective_grads(parameter_list, data_parallel_group)
| def fused_allreduce_gradients(parameter_list, hcg):
| data_parallel_group = hcg.get_data_parallel_group()
logger.debug("dp start fuse allreduce gradients")
with framework.no_grad():
_apply_collective_grads(parameter_list, data_parallel_group)
| _dp_parameters(model, hcg):
data_parallel_group = hcg.get_data_parallel_group()
src_rank = hcg.get_data_parallel_group_src_rank()
sync_params_buffers(
model, data_parallel_group, src_rank, is_model_parallel=False)
def fused_allreduce_gradients(parameter_list, hcg):
| 64 | 64 | 55 | 12 | 52 | andreazanetti/Paddle | python/paddle/distributed/fleet/utils/hybrid_parallel_util.py | Python | fused_allreduce_gradients | fused_allreduce_gradients | 107 | 111 | 107 | 107 | 95fe0f2724baa782abcfc686ad3c3286ea3c7b59 | bigcode/the-stack | train |
d5c1c8a2f6d8b83938589891 | train | function | def _broadcast_data_help(data, shape, dtype, hcg):
model_parallel_group = hcg.get_model_parallel_group()
src_rank = hcg.get_model_parallel_group_src_rank()
mp_rank = hcg.get_model_parallel_rank()
shape_gpu = paddle.to_tensor(shape, dtype="int32")
paddle.distributed.broadcast(
shape_gpu,
... | def _broadcast_data_help(data, shape, dtype, hcg):
| model_parallel_group = hcg.get_model_parallel_group()
src_rank = hcg.get_model_parallel_group_src_rank()
mp_rank = hcg.get_model_parallel_rank()
shape_gpu = paddle.to_tensor(shape, dtype="int32")
paddle.distributed.broadcast(
shape_gpu,
src=src_rank,
group=model_parallel_gro... | to div nranks
coalesced_grad = coalesced_grad / comm_group.nranks
paddle.distributed.all_reduce(coalesced_grad, group=comm_group)
_split_tensors(coalesced_grads_and_vars)
def _broadcast_data_help(data, shape, dtype, hcg):
| 64 | 64 | 150 | 14 | 50 | andreazanetti/Paddle | python/paddle/distributed/fleet/utils/hybrid_parallel_util.py | Python | _broadcast_data_help | _broadcast_data_help | 51 | 72 | 51 | 51 | fd19cde4c71c776f67cee2d079e0c4c5bdcab274 | bigcode/the-stack | train |
bad43c2e67f7b4bc919714bb | train | function | def broadcast_mp_parameters(model, hcg):
model_parallel_group = hcg.get_model_parallel_group()
src_rank = hcg.get_model_parallel_group_src_rank()
sync_params_buffers(
model, model_parallel_group, src_rank, is_model_parallel=True)
| def broadcast_mp_parameters(model, hcg):
| model_parallel_group = hcg.get_model_parallel_group()
src_rank = hcg.get_model_parallel_group_src_rank()
sync_params_buffers(
model, model_parallel_group, src_rank, is_model_parallel=True)
| .VarBase):
with framework.no_grad():
_broadcast_data_help(v, v.shape, v.dtype, hcg)
kwargs[k] = v
else:
logger.error("it doesn't support data type {}".format(type(v)))
return inputs, kwargs
def broadcast_mp_parameters(model, hcg):
| 64 | 64 | 54 | 9 | 54 | andreazanetti/Paddle | python/paddle/distributed/fleet/utils/hybrid_parallel_util.py | Python | broadcast_mp_parameters | broadcast_mp_parameters | 93 | 97 | 93 | 93 | 53dac07667dbca2bea4995b8dbe5bf7ded2ff11a | bigcode/the-stack | train |
bb838c8a39e27919cb660498 | train | function | def broadcast_input_data(hcg, *inputs, **kwargs):
for v in inputs:
if isinstance(v, core.VarBase):
with framework.no_grad():
_broadcast_data_help(v, v.shape, v.dtype, hcg)
else:
logger.error("it doesn't support data type {}".format(type(v)))
for k, v in k... | def broadcast_input_data(hcg, *inputs, **kwargs):
| for v in inputs:
if isinstance(v, core.VarBase):
with framework.no_grad():
_broadcast_data_help(v, v.shape, v.dtype, hcg)
else:
logger.error("it doesn't support data type {}".format(type(v)))
for k, v in kwargs.items():
if isinstance(v, core.VarBa... | :
input_data = paddle.zeros(shape_gpu, dtype=dtype)
else:
input_data = data
paddle.distributed.broadcast(
input_data,
src=src_rank,
group=model_parallel_group,
use_calc_stream=True)
def broadcast_input_data(hcg, *inputs, **kwargs):
| 64 | 64 | 137 | 13 | 51 | andreazanetti/Paddle | python/paddle/distributed/fleet/utils/hybrid_parallel_util.py | Python | broadcast_input_data | broadcast_input_data | 75 | 90 | 75 | 75 | 05824210d0de92c1e839cc46af86d3b0606acb20 | bigcode/the-stack | train |
d5eb1aee33945b70b9e638a2 | train | function | def _apply_collective_grads(parameters, comm_group):
grad_var_set = set()
grad_vars = []
sparse_grad_vars = []
for param in parameters:
if param.trainable and (param._grad_ivar() is not None):
g_var = param._grad_ivar()
assert not g_var._is_sparse(
), "Now, i... | def _apply_collective_grads(parameters, comm_group):
| grad_var_set = set()
grad_vars = []
sparse_grad_vars = []
for param in parameters:
if param.trainable and (param._grad_ivar() is not None):
g_var = param._grad_ivar()
assert not g_var._is_sparse(
), "Now, it doesn't support sparse parameters"
grad... |
import warnings
from paddle import framework
import paddle
from paddle.fluid import core
from paddle.fluid.dygraph.parallel import _split_tensors, sync_params_buffers, build_groups
from collections import OrderedDict
from .log_util import logger
def _apply_collective_grads(parameters, comm_group):
| 64 | 64 | 205 | 12 | 51 | andreazanetti/Paddle | python/paddle/distributed/fleet/utils/hybrid_parallel_util.py | Python | _apply_collective_grads | _apply_collective_grads | 27 | 48 | 27 | 27 | 457d8ebf69e6f73712b1d7e6175c1f5e93d187b2 | bigcode/the-stack | train |
b66279852fc9e5f92b3411eb | train | class | class DubinsCapture:
def __init__(self, x=[0,0,0], wMax=1.0, speed=1.0, dMax=1.0, uMode="max", dMode="min"):
self.x = x
self.wMax = wMax
self.speed = speed
self.dMax = dMax
self.uMode = uMode
self.dMode = dMode
def opt_ctrl(self, t, state, spat_deriv):
""... | class DubinsCapture:
| def __init__(self, x=[0,0,0], wMax=1.0, speed=1.0, dMax=1.0, uMode="max", dMode="min"):
self.x = x
self.wMax = wMax
self.speed = speed
self.dMax = dMax
self.uMode = uMode
self.dMode = dMode
def opt_ctrl(self, t, state, spat_deriv):
"""
:pa... | import heterocl as hcl
class DubinsCapture:
| 12 | 251 | 839 | 5 | 6 | SFU-MARS/optimized_dp | dynamics/DubinsCapture.py | Python | DubinsCapture | DubinsCapture | 3 | 76 | 3 | 3 | d1099b30e9ef969a8460305dce8d2e504537825a | bigcode/the-stack | train |
f53bcc4c8364ad2d17531d7d | train | function | def NeuralNet_TF_0L():
model = Sequential()
model.add(Dense(1, input_dim = 178))
model.compile(loss = 'mean_squared_error', optimizer = 'adam')
return model
| def NeuralNet_TF_0L():
| model = Sequential()
model.add(Dense(1, input_dim = 178))
model.compile(loss = 'mean_squared_error', optimizer = 'adam')
return model
| import datetime
import tensorflow as tf
from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.layers import Dense
from tensorflow.python.keras.callbacks import EarlyStopping
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
def NeuralNe... | 62 | 64 | 46 | 9 | 52 | sangttruong/GinRummy | models/NN/main.py | Python | NeuralNet_TF_0L | NeuralNet_TF_0L | 10 | 14 | 10 | 10 | 69ff02a79699fb3eb24571de9d8e80958108ba9b | bigcode/the-stack | train |
62fdf8e8b498f4bfe0ad2c3b | train | class | class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Article',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
(... | class Migration(migrations.Migration):
| initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Article',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('slug', models.SlugField(blank=True, max... | # Generated by Django 2.1.5 on 2019-02-28 06:56
from django.db import migrations, models
import django.db.models.deletion
import simple_history.models
class Migration(migrations.Migration):
| 50 | 246 | 823 | 7 | 42 | andela/ah-fulldeck | authors/apps/articles/migrations/0001_initial.py | Python | Migration | Migration | 8 | 102 | 8 | 9 | 71d91c0b24c29184d272bd67b7145b3cc5b88706 | bigcode/the-stack | train |
0ad2b8060c46a56c2a0edd3e | train | class | class DeleteCustomerView(DeleteView):
model = DirPartyModel
template_name = 'Customer/DeleteCustomer.html'
success_url = '/customer'
success_message = 'Se ha eliminado el proveedor'
def delete(self, request, *args, **kwargs):
"""
Calls the delete() method on the fetched object and t... | class DeleteCustomerView(DeleteView):
| model = DirPartyModel
template_name = 'Customer/DeleteCustomer.html'
success_url = '/customer'
success_message = 'Se ha eliminado el proveedor'
def delete(self, request, *args, **kwargs):
"""
Calls the delete() method on the fetched object and then
redirects to the success U... | 'party_form': party_form,
'electronic_formset': electronic_formset,
'postal_formset': postal_formset,
'Customer': Customer, },
context_instance=RequestContext(request... | 64 | 64 | 168 | 7 | 56 | alexharmenta/Inventationery | Inventationery/apps/Customer/views.py | Python | DeleteCustomerView | DeleteCustomerView | 230 | 251 | 230 | 230 | f338b4dab945be8e906af3b851ad8a1b2acd61f5 | bigcode/the-stack | train |
5a8af9b1eb6ef7b0f820db14 | train | function | @login_required
@permission_required('Ventas')
def updateCustomerView(request, AccountNum):
Customer = get_object_or_404(CustomerModel, AccountNum=AccountNum)
Party = Customer.Party
EA_list = []
PA_list = []
ElectronicFormSet = inlineformset_factory(
DirPartyModel, LogisticsElectronicAddres... | @login_required
@permission_required('Ventas')
def updateCustomerView(request, AccountNum):
| Customer = get_object_or_404(CustomerModel, AccountNum=AccountNum)
Party = Customer.Party
EA_list = []
PA_list = []
ElectronicFormSet = inlineformset_factory(
DirPartyModel, LogisticsElectronicAddressModel,
extra=1, max_num=5, fields='__all__')
PostalFormSet = inlineformset_fact... | ise la información de la dirección')
redirect_url = "/customer/update/" + str(customer.AccountNum)
return HttpResponseRedirect(redirect_url)
else:
messages.error(
request, "Ocurrió un error al crear el proveedor")
else:
# formulario inicial
... | 199 | 199 | 665 | 18 | 180 | alexharmenta/Inventationery | Inventationery/apps/Customer/views.py | Python | updateCustomerView | updateCustomerView | 138 | 225 | 138 | 140 | dd2902015182413ca178352620f805c6eaebd772 | bigcode/the-stack | train |
977e4a29d0d87e726665f726 | train | function | @login_required
@permission_required('Ventas')
def export_pdf(request):
response = HttpResponse(content_type='application/pdf')
# pdf_name = "proveedores.pdf" # llamado proveedores
# response['Content-Disposition'] = 'attachment; filename=%s' % pdf_name
buff = BytesIO()
doc = SimpleDocTemplate(buff... | @login_required
@permission_required('Ventas')
def export_pdf(request):
| response = HttpResponse(content_type='application/pdf')
# pdf_name = "proveedores.pdf" # llamado proveedores
# response['Content-Disposition'] = 'attachment; filename=%s' % pdf_name
buff = BytesIO()
doc = SimpleDocTemplate(buff,
pagesize=landscape(letter),
... | .writer(response)
writer.writerow(['Número de cuenta',
'Nombre',
'Tipo de proveedor',
'RFC',
'Moneda',
'Direccion principal',
'Contacto principal'])
customer_list = CustomerModel.objects... | 131 | 131 | 438 | 14 | 116 | alexharmenta/Inventationery | Inventationery/apps/Customer/views.py | Python | export_pdf | export_pdf | 286 | 334 | 286 | 288 | cc330c978e3002070aa93827f1ede877f3db7296 | bigcode/the-stack | train |
44f1264f0590a3205237261f | train | function | @login_required
@permission_required('Ventas')
def export_csv(request):
# Create the HttpResponse object with the appropriate CSV header.
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="proveedores.csv"'
writer = csv.writer(response)
writer.... | @login_required
@permission_required('Ventas')
def export_csv(request):
# Create the HttpResponse object with the appropriate CSV header.
| response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="proveedores.csv"'
writer = csv.writer(response)
writer.writerow(['Número de cuenta',
'Nombre',
'Tipo de proveedor',
'RFC',
... | request, *args, **kwargs):
return super(self.__class__, self).dispatch(request, *args, **kwargs)
# FBV: Export to csv
# ----------------------------------------------------------------------------
@login_required
@permission_required('Ventas')
def export_csv(request):
# Create the HttpResponse object wit... | 64 | 64 | 166 | 27 | 36 | alexharmenta/Inventationery | Inventationery/apps/Customer/views.py | Python | export_csv | export_csv | 256 | 281 | 256 | 259 | 41dfd93663518e2105d225aab49964782f86daa9 | bigcode/the-stack | train |
9f61074d47106e248b4fad20 | train | class | class CustomerListView(ListView):
model = CustomerModel
template_name = 'Customer/CustomerList.html'
context_object_name = 'customers'
def get_queryset(self):
queryset = super(CustomerListView, self).get_queryset()
queryset = CustomerModel.objects.all().order_by('AccountNum')
re... | class CustomerListView(ListView):
| model = CustomerModel
template_name = 'Customer/CustomerList.html'
context_object_name = 'customers'
def get_queryset(self):
queryset = super(CustomerListView, self).get_queryset()
queryset = CustomerModel.objects.all().order_by('AccountNum')
return queryset
@method_decorat... | .models import (
LogisticsPostalAddressModel)
from Inventationery.apps.LogisticsElectronicAddress.models import (
LogisticsElectronicAddressModel)
from .forms import (CustomerForm,
PartyForm,)
# CBV: View to list all customers ordered by AccountNum
# ---------------------------------------... | 64 | 64 | 108 | 7 | 56 | alexharmenta/Inventationery | Inventationery/apps/Customer/views.py | Python | CustomerListView | CustomerListView | 37 | 49 | 37 | 37 | c985f0e9ac5dfd388fa83c66faff8d38092c5b99 | bigcode/the-stack | train |
766d54604064635a6e2c0e5e | train | function | @login_required
@permission_required('Ventas')
def createCustomerView(request):
customer = CustomerModel()
party = DirPartyModel()
ElectronicFormSet = inlineformset_factory(
DirPartyModel, LogisticsElectronicAddressModel,
extra=1, max_num=5, fields='__all__')
PostalFormSet = inlineform... | @login_required
@permission_required('Ventas')
def createCustomerView(request):
| customer = CustomerModel()
party = DirPartyModel()
ElectronicFormSet = inlineformset_factory(
DirPartyModel, LogisticsElectronicAddressModel,
extra=1, max_num=5, fields='__all__')
PostalFormSet = inlineformset_factory(
DirPartyModel, LogisticsPostalAddressModel,
extra=1,... | isticsElectronicAddress.models import (
LogisticsElectronicAddressModel)
from .forms import (CustomerForm,
PartyForm,)
# CBV: View to list all customers ordered by AccountNum
# ----------------------------------------------------------------------------
class CustomerListView(ListView):
mo... | 175 | 175 | 586 | 15 | 159 | alexharmenta/Inventationery | Inventationery/apps/Customer/views.py | Python | createCustomerView | createCustomerView | 53 | 134 | 53 | 56 | 01d6eebc61bbfe7f2a473a91c9ceb24da2ab0d23 | bigcode/the-stack | train |
d00e6a1fbee8d02090aa8db7 | train | class | @mgr_utils.mock_record_keepalive
class DoNodeTakeOverTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase):
@mock.patch('ironic.drivers.modules.fake.FakeConsole.start_console')
@mock.patch('ironic.drivers.modules.fake.FakeDeploy.take_over')
@mock.patch('ironic.drivers.modules.fake.FakeDeploy.prepare')
... | @mgr_utils.mock_record_keepalive
class DoNodeTakeOverTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase):
@mock.patch('ironic.drivers.modules.fake.FakeConsole.start_console')
@mock.patch('ironic.drivers.modules.fake.FakeDeploy.take_over')
@mock.patch('ironic.drivers.modules.fake.FakeDeploy.prepare')
| def test__do_takeover(self, mock_prepare, mock_take_over,
mock_start_console):
self._start_service()
node = obj_utils.create_test_node(self.context, driver='fake-hardware')
task = task_manager.TaskManager(self.context, node.uuid)
self.service._do_takeover(t... | ported_obj = 'fake-backported-obj'
obj_name = 'fake-obj'
test_obj = mock.Mock()
test_obj.obj_name.return_value = obj_name
test_obj.obj_to_primitive.return_value = fake_backported_obj
fake_version_manifest = {obj_name: '1.0'}
result = self.conductor.object_backport_versio... | 205 | 205 | 684 | 79 | 126 | DhuldevValekar3/ironic | ironic/tests/unit/conductor/test_manager.py | Python | DoNodeTakeOverTestCase | DoNodeTakeOverTestCase | 8,650 | 8,721 | 8,650 | 8,655 | ec3fa774f19592811341e0db1ba1c3874591b90e | bigcode/the-stack | train |
971533a029e02eaaaf3d6780 | train | class | @mgr_utils.mock_record_keepalive
class ChangeNodePowerStateTestCase(mgr_utils.ServiceSetUpMixin,
db_base.DbTestCase):
@mock.patch.object(fake.FakePower, 'get_power_state', autospec=True)
def test_change_node_power_state_power_on(self, get_power_mock):
# Test change_no... | @mgr_utils.mock_record_keepalive
class ChangeNodePowerStateTestCase(mgr_utils.ServiceSetUpMixin,
db_base.DbTestCase):
@mock.patch.object(fake.FakePower, 'get_power_state', autospec=True)
| def test_change_node_power_state_power_on(self, get_power_mock):
# Test change_node_power_state including integration with
# conductor.utils.node_power_action and lower.
get_power_mock.return_value = states.POWER_OFF
node = obj_utils.create_test_node(self.context,
... | import six
from six.moves import queue
from ironic.common import boot_devices
from ironic.common import driver_factory
from ironic.common import exception
from ironic.common import images
from ironic.common import nova
from ironic.common import states
from ironic.common import swift
from ironic.conductor import manage... | 256 | 256 | 3,283 | 49 | 206 | DhuldevValekar3/ironic | ironic/tests/unit/conductor/test_manager.py | Python | ChangeNodePowerStateTestCase | ChangeNodePowerStateTestCase | 64 | 439 | 64 | 68 | f741b2b23be486326eb0e52c11b1451479e6118c | bigcode/the-stack | train |
3bc6fa381a5da5c13580d52b | train | class | @mgr_utils.mock_record_keepalive
class ConsoleTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase):
def test_set_console_mode_worker_pool_full(self):
node = obj_utils.create_test_node(self.context, driver='fake-hardware')
self._start_service()
with mock.patch.object(self.service,
... | @mgr_utils.mock_record_keepalive
class ConsoleTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase):
| def test_set_console_mode_worker_pool_full(self):
node = obj_utils.create_test_node(self.context, driver='fake-hardware')
self._start_service()
with mock.patch.object(self.service,
'_spawn_worker') as spawn_mock:
spawn_mock.side_effect = exception.N... | expected_calls = [mock.call(mock.ANY, mock.ANY,
{'provision_state': 'deploying',
'reserved': False},
'deploying',
'provision_updated_at',
... | 256 | 256 | 1,450 | 26 | 230 | DhuldevValekar3/ironic | ironic/tests/unit/conductor/test_manager.py | Python | ConsoleTestCase | ConsoleTestCase | 5,167 | 5,313 | 5,167 | 5,168 | 7d77c09d572ca809cd9702e3c1163df2f2c7a698 | bigcode/the-stack | train |
42fdc84cfa2874b8e6fab79a | train | class | class TestIndirectionApiConductor(db_base.DbTestCase):
def setUp(self):
super(TestIndirectionApiConductor, self).setUp()
self.conductor = manager.ConductorManager('test-host', 'test-topic')
def _test_object_action(self, is_classmethod, raise_exception,
return_object... | class TestIndirectionApiConductor(db_base.DbTestCase):
| def setUp(self):
super(TestIndirectionApiConductor, self).setUp()
self.conductor = manager.ConductorManager('test-host', 'test-topic')
def _test_object_action(self, is_classmethod, raise_exception,
return_object=False):
@obj_base.IronicObjectRegistry.register... | _once_with(self.node.uuid, 'fake-hardware',
'')
mock_fail_if.assert_called_once_with(
mock.ANY, {'uuid': self.node.uuid},
{states.DEPLOYING, states.CLEANING},
'provision_updated_at',
callback_method=conductor_utils.abort... | 234 | 234 | 781 | 13 | 221 | DhuldevValekar3/ironic | ironic/tests/unit/conductor/test_manager.py | Python | TestIndirectionApiConductor | TestIndirectionApiConductor | 8,548 | 8,647 | 8,548 | 8,549 | 47f753291106a3a9229160fa8a539d924d404ffc | bigcode/the-stack | train |
eb932d6f8421a3d41d870df6 | train | class | @mgr_utils.mock_record_keepalive
class DoNextDeployStepTestCase(mgr_utils.ServiceSetUpMixin,
db_base.DbTestCase):
def setUp(self):
super(DoNextDeployStepTestCase, self).setUp()
self.deploy_start = {
'step': 'deploy_start', 'priority': 50, 'interface': 'depl... | @mgr_utils.mock_record_keepalive
class DoNextDeployStepTestCase(mgr_utils.ServiceSetUpMixin,
db_base.DbTestCase):
| def setUp(self):
super(DoNextDeployStepTestCase, self).setUp()
self.deploy_start = {
'step': 'deploy_start', 'priority': 50, 'interface': 'deploy'}
self.deploy_end = {
'step': 'deploy_end', 'priority': 20, 'interface': 'deploy'}
self.deploy_steps = [self.deplo... | False)
mock_deploy.assert_called_once_with(mock.ANY, task)
self.assertFalse(mock_log.warning.called)
self.assertEqual(self.service.conductor.id,
task.node.conductor_affinity)
@mock.patch('ironic.conductor.manager._start_co... | 256 | 256 | 2,793 | 30 | 226 | DhuldevValekar3/ironic | ironic/tests/unit/conductor/test_manager.py | Python | DoNextDeployStepTestCase | DoNextDeployStepTestCase | 2,543 | 2,838 | 2,543 | 2,545 | e18a64b4e226e430fd80cf66851c21e2a0c6bb9e | bigcode/the-stack | train |
c641b7f511746cc48c764fd3 | train | class | @mgr_utils.mock_record_keepalive
class DestroyPortgroupTestCase(mgr_utils.ServiceSetUpMixin,
db_base.DbTestCase):
def test_destroy_portgroup(self):
node = obj_utils.create_test_node(self.context, driver='fake-hardware')
portgroup = obj_utils.create_test_portgroup(self.... | @mgr_utils.mock_record_keepalive
class DestroyPortgroupTestCase(mgr_utils.ServiceSetUpMixin,
db_base.DbTestCase):
| def test_destroy_portgroup(self):
node = obj_utils.create_test_node(self.context, driver='fake-hardware')
portgroup = obj_utils.create_test_portgroup(self.context,
node_id=node.id)
self.service.destroy_portgroup(self.context, portgroup)
... | =node.id)
self.service.destroy_port(self.context, port)
self.assertRaises(exception.PortNotFound,
self.dbapi.get_port_by_uuid,
port.uuid)
@mgr_utils.mock_record_keepalive
class DestroyPortgroupTestCase(mgr_utils.ServiceSetUpMixin,
... | 64 | 64 | 206 | 29 | 35 | DhuldevValekar3/ironic | ironic/tests/unit/conductor/test_manager.py | Python | DestroyPortgroupTestCase | DestroyPortgroupTestCase | 8,371 | 8,390 | 8,371 | 8,373 | a2a20c101157b5ae2d1b7d1b2270365651c56bc3 | bigcode/the-stack | train |
c4e73d7ea31d2d71fc5a399c | train | class | @mgr_utils.mock_record_keepalive
class NmiTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase):
@mock.patch.object(fake.FakeManagement, 'inject_nmi', autospec=True)
@mock.patch.object(fake.FakeManagement, 'validate', autospec=True)
def test_inject_nmi(self, mock_val, mock_nmi):
node = obj_util... | @mgr_utils.mock_record_keepalive
class NmiTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase):
@mock.patch.object(fake.FakeManagement, 'inject_nmi', autospec=True)
@mock.patch.object(fake.FakeManagement, 'validate', autospec=True)
| def test_inject_nmi(self, mock_val, mock_nmi):
node = obj_utils.create_test_node(self.context, driver='fake-hardware')
self.service.inject_nmi(self.context, node.uuid)
mock_val.assert_called_once_with(mock.ANY, mock.ANY)
mock_nmi.assert_called_once_with(mock.ANY, mock.ANY)
def t... | self.service.get_boot_device,
self.context, node.uuid)
# Compare true exception hidden by @messaging.expected_exceptions
self.assertEqual(exception.InvalidParameterValue, exc.exc_info[0])
def test_get_supported_boot_devices(self):
... | 164 | 164 | 549 | 63 | 101 | DhuldevValekar3/ironic | ironic/tests/unit/conductor/test_manager.py | Python | NmiTestCase | NmiTestCase | 6,045 | 6,092 | 6,045 | 6,049 | 80cda960473c4a755a10cf621452879b6f297854 | bigcode/the-stack | train |
799191d92e2f2c58490b7efc | train | class | @mock.patch.object(swift, 'SwiftAPI')
class StoreConfigDriveTestCase(db_base.DbTestCase):
def setUp(self):
super(StoreConfigDriveTestCase, self).setUp()
self.node = obj_utils.create_test_node(self.context,
driver='fake-hardware',
... | @mock.patch.object(swift, 'SwiftAPI')
class StoreConfigDriveTestCase(db_base.DbTestCase):
| def setUp(self):
super(StoreConfigDriveTestCase, self).setUp()
self.node = obj_utils.create_test_node(self.context,
driver='fake-hardware',
instance_info=None)
def test_store_configdrive(self, mock_swi... | (periodic_max_workers=1, group='conductor')
mapped_mock.return_value = True
acquire_mock.side_effect = (
self._get_acquire_side_effect([self.task] * 3))
self.task.spawn_after.side_effect = [None] * 3
# 3 nodes to be checked
get_nodeinfo_mock.return_value = (
... | 256 | 256 | 942 | 23 | 233 | DhuldevValekar3/ironic | ironic/tests/unit/conductor/test_manager.py | Python | StoreConfigDriveTestCase | StoreConfigDriveTestCase | 7,785 | 7,881 | 7,785 | 7,787 | a3eb285f1d1f633a0b757c7181b9f6ee1d95fcc4 | bigcode/the-stack | train |
0b3e5d29b454ae3059563ad2 | train | class | @mgr_utils.mock_record_keepalive
class DestroyVolumeConnectorTestCase(mgr_utils.ServiceSetUpMixin,
db_base.DbTestCase):
def test_destroy_volume_connector(self):
node = obj_utils.create_test_node(self.context, driver='fake-hardware',
... | @mgr_utils.mock_record_keepalive
class DestroyVolumeConnectorTestCase(mgr_utils.ServiceSetUpMixin,
db_base.DbTestCase):
| def test_destroy_volume_connector(self):
node = obj_utils.create_test_node(self.context, driver='fake-hardware',
power_state=states.POWER_OFF)
volume_connector = obj_utils.create_test_volume_connector(
self.context, node_id=node.id)
self... | heartbeat(
self.context, node.uuid, 'http://callback', '1.4.1')
calls = [
mock.call(mock.ANY, 'http://callback', '1.4.1'),
mock.call(mock.ANY, 'http://callback')
]
mock_heartbeat.assert_has_calls(calls)
self.assertFalse(log_mock.warning.called)
@mgr_ut... | 106 | 106 | 355 | 29 | 77 | DhuldevValekar3/ironic | ironic/tests/unit/conductor/test_manager.py | Python | DestroyVolumeConnectorTestCase | DestroyVolumeConnectorTestCase | 8,975 | 9,013 | 8,975 | 8,977 | f3dbdb8a04ba5b534fd05dda8522e84779c7d943 | bigcode/the-stack | train |
82a9dd11c8255ffd4e320e9d | train | class | @mgr_utils.mock_record_keepalive
class DestroyVolumeTargetTestCase(mgr_utils.ServiceSetUpMixin,
db_base.DbTestCase):
def test_destroy_volume_target(self):
node = obj_utils.create_test_node(self.context, driver='fake-hardware',
power... | @mgr_utils.mock_record_keepalive
class DestroyVolumeTargetTestCase(mgr_utils.ServiceSetUpMixin,
db_base.DbTestCase):
| def test_destroy_volume_target(self):
node = obj_utils.create_test_node(self.context, driver='fake-hardware',
power_state=states.POWER_OFF)
volume_target = obj_utils.create_test_volume_target(self.context,
... | aging.expected_exceptions
self.assertEqual(exception.VolumeConnectorTypeAndIdAlreadyExists,
exc.exc_info[0])
def test_update_volume_connector_node_power_on(self):
node = obj_utils.create_test_node(self.context, driver='fake-hardware',
... | 177 | 177 | 590 | 29 | 148 | DhuldevValekar3/ironic | ironic/tests/unit/conductor/test_manager.py | Python | DestroyVolumeTargetTestCase | DestroyVolumeTargetTestCase | 9,097 | 9,159 | 9,097 | 9,099 | 606af1e30259ccb99fbc13aec88c2289b2cd45fa | bigcode/the-stack | train |
979860c0c9453e2a967f135c | train | class | class DoNodeRescueTestCase(mgr_utils.CommonMixIn, mgr_utils.ServiceSetUpMixin,
db_base.DbTestCase):
@mock.patch('ironic.conductor.task_manager.acquire', autospec=True)
def test_do_node_rescue(self, mock_acquire):
self._start_service()
task = self._create_task(
... | class DoNodeRescueTestCase(mgr_utils.CommonMixIn, mgr_utils.ServiceSetUpMixin,
db_base.DbTestCase):
@mock.patch('ironic.conductor.task_manager.acquire', autospec=True)
| def test_do_node_rescue(self, mock_acquire):
self._start_service()
task = self._create_task(
node_attrs=dict(driver='fake-hardware',
provision_state=states.ACTIVE,
instance_info={}))
mock_acquire.side_effect = self._get_acqu... | _next_clean_steps(
task, skip_current_step=skip)
expected_index = 1 if skip else 0
self.assertEqual(expected_index, step_index)
def test__get_node_next_clean_steps(self):
self.__get_node_next_clean_steps()
def test__get_node_next_clean_steps_no_skip(self):
... | 256 | 256 | 3,250 | 45 | 211 | DhuldevValekar3/ironic | ironic/tests/unit/conductor/test_manager.py | Python | DoNodeRescueTestCase | DoNodeRescueTestCase | 4,609 | 4,914 | 4,609 | 4,611 | 14d9ffe8dddde3a2449ce60694972840816cacc3 | bigcode/the-stack | train |
1129321e8adb067199adbae2 | train | class | @mock.patch.object(task_manager, 'acquire')
@mock.patch.object(manager.ConductorManager, '_mapped_to_this_conductor')
@mock.patch.object(dbapi.IMPL, 'get_nodeinfo_list')
class ManagerSyncLocalStateTestCase(mgr_utils.CommonMixIn, db_base.DbTestCase):
def setUp(self):
super(ManagerSyncLocalStateTestCase, sel... | @mock.patch.object(task_manager, 'acquire')
@mock.patch.object(manager.ConductorManager, '_mapped_to_this_conductor')
@mock.patch.object(dbapi.IMPL, 'get_nodeinfo_list')
class ManagerSyncLocalStateTestCase(mgr_utils.CommonMixIn, db_base.DbTestCase):
| def setUp(self):
super(ManagerSyncLocalStateTestCase, self).setUp()
self.service = manager.ConductorManager('hostname', 'test-topic')
self.service.conductor = mock.Mock()
self.service.dbapi = self.dbapi
self.service.ring_manager = mock.Mock()
self.node = self._crea... | self.assertEqual(1, waiter_mock.call_count)
@mock.patch.object(queue, 'Queue', autospec=True)
def test__sync_power_states_node_prioritization(
self, queue_mock, sync_mock, spawn_mock, waiter_mock):
CONF.set_override('sync_power_state_workers', 1, group='conductor')
wit... | 256 | 256 | 1,515 | 62 | 194 | DhuldevValekar3/ironic | ironic/tests/unit/conductor/test_manager.py | Python | ManagerSyncLocalStateTestCase | ManagerSyncLocalStateTestCase | 7,617 | 7,782 | 7,617 | 7,621 | e8a39700d0e9e1b2a524253d18262a6a74675c7d | bigcode/the-stack | train |
c1bbdb4150e95267c574da38 | train | class | @mgr_utils.mock_record_keepalive
class NodeInspectHardware(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase):
@mock.patch('ironic.drivers.modules.fake.FakeInspect.inspect_hardware')
def test_inspect_hardware_ok(self, mock_inspect):
self._start_service()
node = obj_utils.create_test_node(self.con... | @mgr_utils.mock_record_keepalive
class NodeInspectHardware(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase):
@mock.patch('ironic.drivers.modules.fake.FakeInspect.inspect_hardware')
| def test_inspect_hardware_ok(self, mock_inspect):
self._start_service()
node = obj_utils.create_test_node(self.context, driver='fake-hardware',
provision_state=states.INSPECTING)
task = task_manager.TaskManager(self.context, node.uuid)
mock_i... | -After': '1800'}
expected_instance_info = {'configdrive': 'http://1.2.3.4'}
# set configs and mocks
CONF.set_override('configdrive_use_object_store', True,
group='deploy')
CONF.set_override('configdrive_swift_container', container_name,
... | 256 | 256 | 1,829 | 44 | 212 | DhuldevValekar3/ironic | ironic/tests/unit/conductor/test_manager.py | Python | NodeInspectHardware | NodeInspectHardware | 7,884 | 8,059 | 7,884 | 7,887 | 5fe90865b7fa9e964ea471f4f6ebc0f4eb6ef3cc | bigcode/the-stack | train |
3c80dd285c4db5a9a9c5e79d | train | class | @mock.patch.object(waiters, 'wait_for_all',
new=mock.MagicMock(return_value=(0, 0)))
@mock.patch.object(manager.ConductorManager, '_spawn_worker',
new=lambda self, fun, *args: fun(*args))
@mock.patch.object(manager, 'do_sync_power_state')
@mock.patch.object(task_manager, 'acquire')... | @mock.patch.object(waiters, 'wait_for_all',
new=mock.MagicMock(return_value=(0, 0)))
@mock.patch.object(manager.ConductorManager, '_spawn_worker',
new=lambda self, fun, *args: fun(*args))
@mock.patch.object(manager, 'do_sync_power_state')
@mock.patch.object(task_manager, 'acquire')... | def setUp(self):
super(ManagerSyncPowerStatesTestCase, self).setUp()
self.service = manager.ConductorManager('hostname', 'test-topic')
self.service.dbapi = self.dbapi
self.node = self._create_node()
self.filters = {'maintenance': False}
self.columns = ['uuid', 'driver... | .power_state)
self.assertFalse(node_power_action.called)
self.task.upgrade_lock.assert_called_once_with()
def test_correct_power_state_on_upgrade_lock(self, node_power_action):
def _fake_upgrade():
self.node.power_state = states.POWER_OFF
self.task.upgrade_lock.side_eff... | 256 | 256 | 2,216 | 129 | 127 | DhuldevValekar3/ironic | ironic/tests/unit/conductor/test_manager.py | Python | ManagerSyncPowerStatesTestCase | ManagerSyncPowerStatesTestCase | 6,799 | 7,040 | 6,799 | 6,808 | 935318091d2015b5aa4a70df3772c4408a826189 | bigcode/the-stack | train |
fe428accb8662c2152382111 | train | class | @mgr_utils.mock_record_keepalive
class DoNodeDeployTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase):
@mock.patch('ironic.drivers.modules.fake.FakeDeploy.deploy')
@mock.patch('ironic.drivers.modules.fake.FakeDeploy.prepare')
def test__do_node_deploy_driver_raises_prepare_error(self, mock_prepare,
... | @mgr_utils.mock_record_keepalive
class DoNodeDeployTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase):
@mock.patch('ironic.drivers.modules.fake.FakeDeploy.deploy')
@mock.patch('ironic.drivers.modules.fake.FakeDeploy.prepare')
| def test__do_node_deploy_driver_raises_prepare_error(self, mock_prepare,
mock_deploy):
self._start_service()
# test when driver.deploy.prepare raises an ironic error
mock_prepare.side_effect = exception.InstanceDeployFailure('test')
... | ,
'deploy_step_index': None},
deploy_step={})
mock_execute.side_effect = exception.AgentConnectionFailed(
reason='failed')
with task_manager.acquire(
self.context, node.uuid, shared=False) as task:
manager._do_next_de... | 256 | 256 | 5,615 | 60 | 196 | DhuldevValekar3/ironic | ironic/tests/unit/conductor/test_manager.py | Python | DoNodeDeployTestCase | DoNodeDeployTestCase | 1,985 | 2,540 | 1,985 | 1,988 | ee9ccc34ce2c3c4ddd57a8893c7663516efa2e2a | bigcode/the-stack | train |
77fe3c66ccd5e37c0b1830a2 | train | class | @mgr_utils.mock_record_keepalive
class ManagerTestProperties(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase):
def setUp(self):
super(ManagerTestProperties, self).setUp()
self.service = manager.ConductorManager('test-host', 'test-topic')
def _check_driver_properties(self, hw_type, expected):
... | @mgr_utils.mock_record_keepalive
class ManagerTestProperties(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase):
| def setUp(self):
super(ManagerTestProperties, self).setUp()
self.service = manager.ConductorManager('test-host', 'test-topic')
def _check_driver_properties(self, hw_type, expected):
self._start_service()
properties = self.service.get_driver_properties(self.context, hw_type)
... | _response([self.node] * 3))
mapped_mock.return_value = True
acquire_mock.side_effect = (
self._get_acquire_side_effect([self.task] * 3))
self.service._check_deploy_timeouts(self.context)
# Should only have ran 2.
self.assertEqual([mock.call(self.node.uuid, self.node... | 226 | 226 | 755 | 26 | 200 | DhuldevValekar3/ironic | ironic/tests/unit/conductor/test_manager.py | Python | ManagerTestProperties | ManagerTestProperties | 7,438 | 7,509 | 7,438 | 7,440 | aa2d98dc29b26d155a87e40f42cecfbeeb78fca0 | bigcode/the-stack | train |
38a85d397d161f8bb4679fe0 | train | class | @mgr_utils.mock_record_keepalive
class UpdatePortgroupTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase):
@mock.patch.object(n_flat.FlatNetwork, 'portgroup_changed', autospec=True)
@mock.patch.object(n_flat.FlatNetwork, 'validate', autospec=True)
def test_update_portgroup(self, mock_val, mock_pc):
... | @mgr_utils.mock_record_keepalive
class UpdatePortgroupTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase):
@mock.patch.object(n_flat.FlatNetwork, 'portgroup_changed', autospec=True)
@mock.patch.object(n_flat.FlatNetwork, 'validate', autospec=True)
| def test_update_portgroup(self, mock_val, mock_pc):
node = obj_utils.create_test_node(self.context, driver='fake-hardware')
portgroup = obj_utils.create_test_portgroup(self.context,
node_id=node.id,
... | exc.exc_info[0])
mock_valid.assert_called_once_with(mock.ANY, mock.ANY)
mock_detach.assert_called_once_with(mock.ANY, "interface")
@mock.patch.object(n_flat.FlatNetwork, 'vif_detach', autpspec=True)
def test_vif_detach_validate_error(self, mock_detach,
mo... | 256 | 256 | 1,802 | 64 | 192 | DhuldevValekar3/ironic | ironic/tests/unit/conductor/test_manager.py | Python | UpdatePortgroupTestCase | UpdatePortgroupTestCase | 6,233 | 6,408 | 6,233 | 6,236 | 3c6c3e693ce50e2e63e281c6ca0d196120e311d9 | bigcode/the-stack | train |
7a99ea978e4522a78bc07f9f | train | class | @mgr_utils.mock_record_keepalive
class UpdatePortTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase):
@mock.patch.object(conductor_utils, 'validate_port_physnet')
@mock.patch.object(n_flat.FlatNetwork, 'port_changed', autospec=True)
@mock.patch.object(n_flat.FlatNetwork, 'validate', autospec=True)
... | @mgr_utils.mock_record_keepalive
class UpdatePortTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase):
@mock.patch.object(conductor_utils, 'validate_port_physnet')
@mock.patch.object(n_flat.FlatNetwork, 'port_changed', autospec=True)
@mock.patch.object(n_flat.FlatNetwork, 'validate', autospec=True)
| def test_update_port(self, mock_val, mock_pc, mock_vpp):
node = obj_utils.create_test_node(self.context, driver='fake-hardware')
port = obj_utils.create_test_port(self.context,
node_id=node.id,
extra={'foo': 'bar'})... | .uuid)
@mock.patch.object(conductor_utils, 'validate_port_physnet')
def test_create_port_physnet_validation_failure_inconsistent(
self, mock_validate):
mock_validate.side_effect = exception.PortgroupPhysnetInconsistent(
portgroup='pg1', physical_networks='physnet1, physnet2')
... | 256 | 256 | 2,800 | 77 | 179 | DhuldevValekar3/ironic | ironic/tests/unit/conductor/test_manager.py | Python | UpdatePortTestCase | UpdatePortTestCase | 5,558 | 5,816 | 5,558 | 5,563 | bf4353f439555e74fee410a8a114a60359a80170 | bigcode/the-stack | train |
275cdbac6255996be1759d3e | train | class | @mgr_utils.mock_record_keepalive
class DestroyNodeTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase):
def test_destroy_node(self):
self._start_service()
for state in states.DELETE_ALLOWED_STATES:
node = obj_utils.create_test_node(self.context,
... | @mgr_utils.mock_record_keepalive
class DestroyNodeTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase):
| def test_destroy_node(self):
self._start_service()
for state in states.DELETE_ALLOWED_STATES:
node = obj_utils.create_test_node(self.context,
provision_state=state)
self.service.destroy_node(self.context, node.uuid)
se... | data = self.service.get_console_information(self.context,
node.uuid)
self.assertEqual(console_info, data)
def test_get_console_disabled(self):
node = obj_utils.create_test_node(self.context, driver='fake-hardware',
... | 256 | 256 | 1,396 | 27 | 229 | DhuldevValekar3/ironic | ironic/tests/unit/conductor/test_manager.py | Python | DestroyNodeTestCase | DestroyNodeTestCase | 5,316 | 5,484 | 5,316 | 5,318 | 3f96e365b960bb10add811845efe57cbec99736c | bigcode/the-stack | train |
28d7f88202460baa89e88773 | train | class | @mock.patch.object(task_manager, 'acquire')
@mock.patch.object(manager.ConductorManager, '_mapped_to_this_conductor')
@mock.patch.object(dbapi.IMPL, 'get_nodeinfo_list')
class ManagerCheckInspectWaitTimeoutsTestCase(mgr_utils.CommonMixIn,
db_base.DbTestCase):
def setUp(... | @mock.patch.object(task_manager, 'acquire')
@mock.patch.object(manager.ConductorManager, '_mapped_to_this_conductor')
@mock.patch.object(dbapi.IMPL, 'get_nodeinfo_list')
class ManagerCheckInspectWaitTimeoutsTestCase(mgr_utils.CommonMixIn,
db_base.DbTestCase):
| def setUp(self):
super(ManagerCheckInspectWaitTimeoutsTestCase, self).setUp()
self.config(inspect_wait_timeout=300, group='conductor')
self.service = manager.ConductorManager('hostname', 'test-topic')
self.service.dbapi = self.dbapi
self.node = self._create_node(provision_st... | .inspect_hardware')
def test_inspect_hardware_unexpected_error(self, mock_inspect):
self._start_service()
mock_inspect.side_effect = RuntimeError('x')
state = states.MANAGEABLE
node = obj_utils.create_test_node(self.context, driver='fake-hardware',
... | 256 | 256 | 2,013 | 65 | 191 | DhuldevValekar3/ironic | ironic/tests/unit/conductor/test_manager.py | Python | ManagerCheckInspectWaitTimeoutsTestCase | ManagerCheckInspectWaitTimeoutsTestCase | 8,062 | 8,280 | 8,062 | 8,066 | 4cfb1e65defcf70912e2d1f7a3dcf5eb8e75726a | bigcode/the-stack | train |
05183771859ed2a36fc4ac7c | train | class | @mgr_utils.mock_record_keepalive
class CreateNodeTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase):
def test_create_node(self):
node = obj_utils.get_test_node(self.context, driver='fake-hardware',
extra={'test': 'one'})
res = self.service.create_node(s... | @mgr_utils.mock_record_keepalive
class CreateNodeTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase):
| def test_create_node(self):
node = obj_utils.get_test_node(self.context, driver='fake-hardware',
extra={'test': 'one'})
res = self.service.create_node(self.context, node)
self.assertEqual({'test': 'one'}, res['extra'])
res = objects.Node.get_b... | [0])
node.refresh()
supported_mock.assert_called_once_with(mock.ANY, mock.ANY)
self.assertEqual(states.POWER_ON, node.power_state)
self.assertIsNone(node.target_power_state)
self.assertIsNone(node.last_error)
@mgr_utils.mock_record_keepalive
class CreateNodeTestCase(mgr_utils.Se... | 81 | 81 | 272 | 27 | 54 | DhuldevValekar3/ironic | ironic/tests/unit/conductor/test_manager.py | Python | CreateNodeTestCase | CreateNodeTestCase | 442 | 470 | 442 | 443 | 0ee8563fee09f28c338edc7b5521f2861e03b4e4 | bigcode/the-stack | train |
f03c0075ed0278cc45c8ddfc | train | class | @mgr_utils.mock_record_keepalive
class VendorPassthruTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase):
@mock.patch.object(task_manager.TaskManager, 'upgrade_lock')
@mock.patch.object(task_manager.TaskManager, 'spawn_after')
def test_vendor_passthru_async(self, mock_spawn,
... | @mgr_utils.mock_record_keepalive
class VendorPassthruTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase):
@mock.patch.object(task_manager.TaskManager, 'upgrade_lock')
@mock.patch.object(task_manager.TaskManager, 'spawn_after')
| def test_vendor_passthru_async(self, mock_spawn,
mock_upgrade):
node = obj_utils.create_test_node(self.context,
vendor_interface='fake')
info = {'bar': 'baz'}
self._start_service()
response = self.service.v... | self.assertEqual(alloc.uuid, node.instance_uuid)
def test_update_node_deleting_allocation_in_maintenance(self):
node = obj_utils.create_test_node(self.context,
provision_state='active',
maintenance=True)
alloc = ob... | 256 | 256 | 3,189 | 57 | 199 | DhuldevValekar3/ironic | ironic/tests/unit/conductor/test_manager.py | Python | VendorPassthruTestCase | VendorPassthruTestCase | 898 | 1,262 | 898 | 902 | dbe237425ecce60cbe3c21c01a3baa2817843825 | bigcode/the-stack | train |
8ed5cbafeae8a245b595f015 | train | class | @mgr_utils.mock_record_keepalive
@mock.patch.object(manager.ConductorManager, '_fail_if_in_state')
@mock.patch.object(manager.ConductorManager, '_mapped_to_this_conductor')
@mock.patch.object(dbapi.IMPL, 'get_offline_conductors')
class ManagerCheckOrphanNodesTestCase(mgr_utils.ServiceSetUpMixin,
... | @mgr_utils.mock_record_keepalive
@mock.patch.object(manager.ConductorManager, '_fail_if_in_state')
@mock.patch.object(manager.ConductorManager, '_mapped_to_this_conductor')
@mock.patch.object(dbapi.IMPL, 'get_offline_conductors')
class ManagerCheckOrphanNodesTestCase(mgr_utils.ServiceSetUpMixin,
... | def setUp(self):
super(ManagerCheckOrphanNodesTestCase, self).setUp()
self._start_service()
self.node = obj_utils.create_test_node(
self.context, id=1, uuid=uuidutils.generate_uuid(),
driver='fake-hardware', provision_state=states.DEPLOYING,
target_provis... | def test_destroy_portgroup(self):
node = obj_utils.create_test_node(self.context, driver='fake-hardware')
portgroup = obj_utils.create_test_portgroup(self.context,
node_id=node.id)
self.service.destroy_portgroup(self.context, portgroup)
... | 256 | 256 | 1,398 | 79 | 177 | DhuldevValekar3/ironic | ironic/tests/unit/conductor/test_manager.py | Python | ManagerCheckOrphanNodesTestCase | ManagerCheckOrphanNodesTestCase | 8,393 | 8,545 | 8,393 | 8,398 | 89629a8e3926de3ffd6cf751ba800ce509a84136 | bigcode/the-stack | train |
bc3eec3fefb4faa0eec1dd88 | train | class | @mgr_utils.mock_record_keepalive
class DoNodeAdoptionTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase):
@mock.patch('ironic.drivers.modules.fake.FakePower.validate')
@mock.patch('ironic.drivers.modules.fake.FakeBoot.validate')
@mock.patch('ironic.drivers.modules.fake.FakeConsole.start_console')
... | @mgr_utils.mock_record_keepalive
class DoNodeAdoptionTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase):
@mock.patch('ironic.drivers.modules.fake.FakePower.validate')
@mock.patch('ironic.drivers.modules.fake.FakeBoot.validate')
@mock.patch('ironic.drivers.modules.fake.FakeConsole.start_console')
... | def test__do_adoption_with_takeover(self,
mock_prepare,
mock_take_over,
mock_start_console,
mock_boot_validate,
mock... | = Exception()
node = obj_utils.create_test_node(self.context, driver='fake-hardware',
console_enabled=True)
task = task_manager.TaskManager(self.context, node.uuid)
self.service._do_takeover(task)
node.refresh()
self.assertIsNotNone(nod... | 255 | 256 | 2,273 | 111 | 144 | DhuldevValekar3/ironic | ironic/tests/unit/conductor/test_manager.py | Python | DoNodeAdoptionTestCase | DoNodeAdoptionTestCase | 8,724 | 8,972 | 8,724 | 8,731 | f4aaec0dbdaabca8a624ef13d29913b0ffbf6127 | bigcode/the-stack | train |
201b592010c937a375126c37 | train | class | @mgr_utils.mock_record_keepalive
class ManagerTestHardwareTypeProperties(mgr_utils.ServiceSetUpMixin,
db_base.DbTestCase):
def _check_hardware_type_properties(self, hardware_type, expected):
self.config(enabled_hardware_types=[hardware_type])
self.hardware_ty... | @mgr_utils.mock_record_keepalive
class ManagerTestHardwareTypeProperties(mgr_utils.ServiceSetUpMixin,
db_base.DbTestCase):
| def _check_hardware_type_properties(self, hardware_type, expected):
self.config(enabled_hardware_types=[hardware_type])
self.hardware_type = driver_factory.get_hardware_type(hardware_type)
self._start_service()
properties = self.service.get_driver_properties(self.context,
... | .context, "bad-driver")
# Compare true exception hidden by @messaging.expected_exceptions
self.assertEqual(exception.DriverNotFound, exc.exc_info[0])
@mgr_utils.mock_record_keepalive
class ManagerTestHardwareTypeProperties(mgr_utils.ServiceSetUpMixin,
db_base.DbTe... | 64 | 64 | 167 | 29 | 35 | DhuldevValekar3/ironic | ironic/tests/unit/conductor/test_manager.py | Python | ManagerTestHardwareTypeProperties | ManagerTestHardwareTypeProperties | 7,512 | 7,528 | 7,512 | 7,515 | 0aa6bbb8f3766341dfc1b889128c21b10fc85034 | bigcode/the-stack | train |
7365fdeb4748e15183deb9fd | train | class | @mgr_utils.mock_record_keepalive
class BootDeviceTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase):
@mock.patch.object(fake.FakeManagement, 'set_boot_device', autospec=True)
@mock.patch.object(fake.FakeManagement, 'validate', autospec=True)
def test_set_boot_device(self, mock_val, mock_sbd):
... | @mgr_utils.mock_record_keepalive
class BootDeviceTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase):
@mock.patch.object(fake.FakeManagement, 'set_boot_device', autospec=True)
@mock.patch.object(fake.FakeManagement, 'validate', autospec=True)
| def test_set_boot_device(self, mock_val, mock_sbd):
node = obj_utils.create_test_node(self.context, driver='fake-hardware')
self.service.set_boot_device(self.context, node.uuid,
boot_devices.PXE)
mock_val.assert_called_once_with(mock.ANY, mock.ANY)
... | ): do not wait for threads to be finished in unittests
CONF.set_override('send_sensor_data_wait_timeout', 0,
group='conductor')
_mapped_to_this_conductor_mock.return_value = True
get_nodeinfo_list_mock.return_value = [('fake_uuid', 'fake',
... | 207 | 207 | 693 | 63 | 144 | DhuldevValekar3/ironic | ironic/tests/unit/conductor/test_manager.py | Python | BootDeviceTestCase | BootDeviceTestCase | 5,981 | 6,042 | 5,981 | 5,985 | 9c7777dadf94d391ba642cbb7918b4f7db3bb092 | bigcode/the-stack | train |
88f141ee966aacc1cf1469ac | train | class | @mgr_utils.mock_record_keepalive
class CreatePortTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase):
@mock.patch.object(conductor_utils, 'validate_port_physnet')
def test_create_port(self, mock_validate):
node = obj_utils.create_test_node(self.context, driver='fake-hardware')
port = obj_... | @mgr_utils.mock_record_keepalive
class CreatePortTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase):
@mock.patch.object(conductor_utils, 'validate_port_physnet')
| def test_create_port(self, mock_validate):
node = obj_utils.create_test_node(self.context, driver='fake-hardware')
port = obj_utils.get_test_port(self.context, node_id=node.id,
extra={'foo': 'bar'})
res = self.service.create_port(self.context, port)
... | mock_sc.side_effect = Exception()
self.service.destroy_node(self.context, node.uuid)
mock_sc.assert_called_once_with(mock.ANY, mock.ANY)
self.assertRaises(exception.NodeNotFound,
self.dbapi.get_node_by_uuid,
node.uuid)
mock_noti... | 229 | 229 | 765 | 42 | 187 | DhuldevValekar3/ironic | ironic/tests/unit/conductor/test_manager.py | Python | CreatePortTestCase | CreatePortTestCase | 5,487 | 5,555 | 5,487 | 5,490 | 285b8013ae2586c03c7da733b47aefdfe1d2f5bb | bigcode/the-stack | train |
dd6b51731965b9b7cf3ccefa | train | class | @mgr_utils.mock_record_keepalive
class UpdateVolumeConnectorTestCase(mgr_utils.ServiceSetUpMixin,
db_base.DbTestCase):
def test_update_volume_connector(self):
node = obj_utils.create_test_node(self.context, driver='fake-hardware',
... | @mgr_utils.mock_record_keepalive
class UpdateVolumeConnectorTestCase(mgr_utils.ServiceSetUpMixin,
db_base.DbTestCase):
| def test_update_volume_connector(self):
node = obj_utils.create_test_node(self.context, driver='fake-hardware',
power_state=states.POWER_OFF)
volume_connector = obj_utils.create_test_volume_connector(
self.context, node_id=node.id, extra={'foo':... | driver='fake-hardware',
reservation='fake-reserv')
volume_connector = obj_utils.create_test_volume_connector(
self.context, node_id=node.id)
exc = self.assertRaises(messaging.rpc.ExpectedException,
self.service.destr... | 228 | 228 | 762 | 29 | 199 | DhuldevValekar3/ironic | ironic/tests/unit/conductor/test_manager.py | Python | UpdateVolumeConnectorTestCase | UpdateVolumeConnectorTestCase | 9,016 | 9,094 | 9,016 | 9,018 | 715269fd614494061c68460f28a93bee3e5b2f60 | bigcode/the-stack | train |
0c581817d5336c2f195b65e4 | train | class | @mgr_utils.mock_record_keepalive
class SensorsTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase):
def test__filter_out_unsupported_types_all(self):
self._start_service()
CONF.set_override('send_sensor_data_types', ['All'], group='conductor')
fake_sensors_data = {"t1": {'f1': 'v1'}, "... | @mgr_utils.mock_record_keepalive
class SensorsTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase):
| def test__filter_out_unsupported_types_all(self):
self._start_service()
CONF.set_override('send_sensor_data_types', ['All'], group='conductor')
fake_sensors_data = {"t1": {'f1': 'v1'}, "t2": {'f1': 'v1'}}
actual_result = (
self.service._filter_out_unsupported_types(fake_s... | port)
# Compare true exception hidden by @messaging.expected_exceptions
self.assertEqual(exception.Conflict, exc.exc_info[0])
mock_validate.assert_called_once_with(mock.ANY, port)
@mock.patch.object(conductor_utils, 'validate_port_physnet')
def test_update_port_physnet_validation_failu... | 256 | 256 | 1,631 | 26 | 230 | DhuldevValekar3/ironic | ironic/tests/unit/conductor/test_manager.py | Python | SensorsTestCase | SensorsTestCase | 5,819 | 5,974 | 5,819 | 5,821 | 6a1fc0bb986cee4593e80ccb1c9c047e3af0f37c | bigcode/the-stack | train |
e813eff2c660f2def650770c | train | class | @mgr_utils.mock_record_keepalive
class UpdateVolumeTargetTestCase(mgr_utils.ServiceSetUpMixin,
db_base.DbTestCase):
def test_update_volume_target(self):
node = obj_utils.create_test_node(self.context, driver='fake-hardware',
power_st... | @mgr_utils.mock_record_keepalive
class UpdateVolumeTargetTestCase(mgr_utils.ServiceSetUpMixin,
db_base.DbTestCase):
| def test_update_volume_target(self):
node = obj_utils.create_test_node(self.context, driver='fake-hardware',
power_state=states.POWER_OFF)
volume_target = obj_utils.create_test_volume_target(
self.context, node_id=node.id, extra={'foo': 'bar'})
... | ed(self):
node = obj_utils.create_test_node(self.context, driver='fake-hardware',
power_state=states.POWER_OFF)
volume_target = obj_utils.create_test_volume_target(self.context,
node_id=node.id)
... | 256 | 256 | 993 | 29 | 227 | DhuldevValekar3/ironic | ironic/tests/unit/conductor/test_manager.py | Python | UpdateVolumeTargetTestCase | UpdateVolumeTargetTestCase | 9,162 | 9,259 | 9,162 | 9,164 | 488e086e61d4eb6d63a588b8f8c10d2a7ee56a09 | bigcode/the-stack | train |
0c50538875b72dea9300149f | train | class | @mgr_utils.mock_record_keepalive
class DoNodeVerifyTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase):
@mock.patch('ironic.objects.node.NodeCorrectedPowerStateNotification')
@mock.patch('ironic.drivers.modules.fake.FakePower.get_power_state')
@mock.patch('ironic.drivers.modules.fake.FakePower.validat... | @mgr_utils.mock_record_keepalive
class DoNodeVerifyTestCase(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase):
@mock.patch('ironic.objects.node.NodeCorrectedPowerStateNotification')
@mock.patch('ironic.drivers.modules.fake.FakePower.get_power_state')
@mock.patch('ironic.drivers.modules.fake.FakePower.validat... | def test__do_node_verify(self, mock_validate, mock_get_power_state,
mock_notif):
self._start_service()
mock_get_power_state.return_value = states.POWER_OFF
# Required for exception handling
mock_notif.__name__ = 'NodeCorrectedPowerStateNotification'
... | .patch.object(fake.FakeRescue, 'clean_up', autospec=True)
def test__do_node_rescue_abort_clean_up_fail(self, clean_up_mock):
clean_up_mock.side_effect = Exception('Surprise')
node = obj_utils.create_test_node(
self.context, driver='fake-hardware',
provision_state=states.RESCU... | 241 | 241 | 805 | 78 | 163 | DhuldevValekar3/ironic | ironic/tests/unit/conductor/test_manager.py | Python | DoNodeVerifyTestCase | DoNodeVerifyTestCase | 4,917 | 5,012 | 4,917 | 4,921 | b6a922043841c8869c6cd924f546021c47650588 | bigcode/the-stack | train |
4df91fe036f42cef14e520c4 | train | class | @mgr_utils.mock_record_keepalive
class RaidTestCases(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase):
driver_name = 'fake-hardware'
raid_interface = None
def setUp(self):
super(RaidTestCases, self).setUp()
self.node = obj_utils.create_test_node(
self.context, driver=self.drive... | @mgr_utils.mock_record_keepalive
class RaidTestCases(mgr_utils.ServiceSetUpMixin, db_base.DbTestCase):
| driver_name = 'fake-hardware'
raid_interface = None
def setUp(self):
super(RaidTestCases, self).setUp()
self.node = obj_utils.create_test_node(
self.context, driver=self.driver_name,
raid_interface=self.raid_interface,
provision_state=states.MANAGEABLE)
... | portgroup.node_id
portgroup.node_id = update_node.id
exc = self.assertRaises(messaging.rpc.ExpectedException,
self.service.update_portgroup,
self.context, portgroup)
self.assertEqual(exception.PortgroupNotEmpty, exc.exc_info[0])
... | 130 | 130 | 434 | 26 | 104 | DhuldevValekar3/ironic | ironic/tests/unit/conductor/test_manager.py | Python | RaidTestCases | RaidTestCases | 6,411 | 6,460 | 6,411 | 6,413 | 8d211b3683d7e1bda3cc48a631470cfa6689fb9c | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.