JMockit is open-source software licensed under the MIT License. It is a collection of tools and APIs for use in developer testing, that is, tests written by developers using a testing framework such as JUnit or TestNG. The tools rely on the Java 5 SE instrumentation feature (the java.lang.instrument package), internally using the ASM library to modify bytecode at runtime. Therefore, tests using JMockit must be run under a Java 5+ SE JVM.
The following links provide a short overview of the different tools and APIs in the toolkit. The APIs (first three items) can be used for writing unit and integration tests. They enable the isolation of code under test from its dependencies, no matter what form they take or how they are obtained at runtime. The last two items are separate tools delivered in their own jar files, which can optionally be used while running test suites. The figure below is a clickable map with links to detailed documentation pages.
This toolkit was created mainly as an attempt to overcome certain limitations found in "conventional" mocking tools. Another goal was to provide simpler and more succinct APIs for writing developer tests. In addition, and differently from other testing tools which specifically target the use of mocks, JMockit also includes other tools designed to support the creation of large test suites. Between such tools the toolkit provides code coverage metrics, incremental re-execution of tests, and more.
The JMockit approach is an alternative to the conventional use of "mock objects" as provided by tools such as EasyMock and jMock.
Both of those tools are based on
java.lang.reflect.Proxy,
which requires an interface to be implemented.
Additionally, they support the creation of mock objects for classes through
CGLIB subclass generation. Because of that, said classes cannot be
final
and only overridable instance methods can be mocked.
Most importantly, however, when using these tools the dependencies of code under test (that is, the objects of other
classes on which a given class under test depends) must be controlled by the tests, so that mock instances can be
passed to the clients of those dependencies.
Therefore, dependencies can't simply be instantiated with the new
operator in a client class for which
we want to write unit tests.
Ultimately, the technical limitations of conventional mocking tools impose the following design restrictions on production code:
final
.
The problem with imposing restrictions on the design of production code is that there are good reasons for making
classes and methods final
, for directly obtaining instances of collaborators with the new
operator, and for using APIs based on static
methods.
There is nothing inherently wrong with using these three Java language keywords, after all.
In the first case, declaring classes or methods final
makes it clear that they are not intended for
extension by subclassing.
For example, in a correct application of the Template
Method design pattern, the "template" method itself (which implements an algorithm calling one or more
overridable methods) must not be overridable.
Also, from the point of view of API design, final
classes are the only ones which can be safely evolved.
For more on this, see this article.
In practice, most classes and methods in an application or even in a reusable class library are not designed with
extension by subclassing in mind, so it makes sense to declare them as final
; probably that's why most
other OO languages (C++, C#, etc.) make all methods non-overridable by default.
Another benefit of making Java classes or methods final
is that a good static analysis tool will be able
to provide more useful feedback.
The code inspections associated with the use of final
in IntelliJ IDEA, for example, led me numerous
times to simplify and even eliminate unused parts of the code base, when developing large business applications.
(For the curious, some of the relevant inspections are: "Class structure: 'protected' member in 'final' class",
"Declaration redundancy: redundant throws declaration", and "Initialization issues: overridable method call during
object construction".)
For an authoritative discussion on design for extension (which defends the judicious use of final
for
classes and methods), I refer readers to "Item 17: Design and document for inheritance or else prohibit it" in the
Effective Java book.
Another book which strongly recommends the use of final
for classes and methods is
Practical API Design
(see "Make Everything Final", in chapter 5).
In the second case, directly instantiating dependencies with new
facilitates the use of stateful
objects. In OO design, objects normally are not stateless. However, when dependencies are obtained or injected
through external means (such as a "Service Locator" or a DI framework) there is a tendency to make them stateless,
and with a single global instance. Such a practice leads to code that is more procedural and less object oriented.
Of course, this applies to dependencies whose interfaces have only one implementation in production code, or when the
selection of an implementation between many would not benefit from external configuration (for example, people
typically instantiate List
implementations directly, even though they code to the abstract interface
only); situations where one implementation must be selected through external configuration tend to be quite
rare (at least in my experience).
Related to this issue, I think, there is an widely observed misunderstanding of just what the phrase Program to
an interface, not an implementation (from the famous "Design Patterns" book) actually means.
Many seem to think that one should create a new separate Java interface (or abstract class) for any concrete
class which don't yet implement one. In reality, it was only meant as a recommendation to avoid declaring variables,
fields, parameters or return types as the implementation type when an abstract type already exists (for
example, don't declare variables of type ArrayList
if all you need is a List
).
The "Effective Java" book mentioned above also discusses this topic, in "Item 52: Refer to objects by their
interfaces".
In the third case, the use of classes containing only static
methods is the best choice when none of the
methods operate on any state (for example, the Math
class), or the actual state is stored in a separate
context object, such as the HTTP request context or the persistence context.
For this last situation, consider an application that has a persistence subsystem which provides access to a
relational database.
One possibility is to inject instances of work unit objects (an Hibernate Session
, or a JPA
EntityManager
) wherever they are needed, and use the persistence API directly.
A better approach, in my experience, is to use a static facade which encapsulates all access from the
application to the persistence subsystem.
The benefits of this are many, not the least of which is that it actually provides more flexibility than the
more direct, instance-based, approach.
Another recommended usage of static methods is presented in "Item 1: Consider static factory methods instead of
constructors", again in the "Effective Java" book.
The set of limitations listed above, which are found in conventional mocking tools, has come to be associated with the idea of "untestable code". Often, we see the restrictions resulting from those limitations considered as inevitable, or even as something that could be beneficial. The JMockit toolkit, which breaks away from these limitations and restrictions, shows that in fact there is no such thing as truly untestable code. There is, of course, code that is harder to test because it is too complicated and convoluted, lacks cohesion, and so on and so forth.
Therefore, by eliminating the technical limitations traditionally involved in the isolation of an unit from its dependencies, we get the benefit that no artificial design restrictions must be imposed on production code for the sake of unit testing. Additionally, it becomes possible to write unit tests for legacy code, without the need for any prior adaptation or refactoring. In short, with a less restrictive mock testing tool the testability of production code becomes much less of an issue, and developers get more freedom in using Java language features, as well as more design choices.
Another way of thinking about testability is to differentiate between intrinsic and extrinsic testability. In the first case, we can conclude that whatever makes the code more or less maintainable also makes it more or less easily testable, and vice-versa. For example, methods with higher cyclomatic complexity (basically, the number of different execution paths through the method) require more tests to be fully covered, while at the same time being more difficult to understand and change; in other words, intrinsic testability is not particularly useful as a separate measure for code quality, if it is nothing more than maintainability. In the second case, extrinsic testability, we are not really considering properties of the production code, but instead properties of the tools used to test that code. So, if a tool for testing code in isolation can provide an easy to use API that is able to deal with all possible isolation scenarios, then such extrinsic concerns for testability completely disappear.
The APIs for testing with mocks that are available in existing toolkits, even the more recent ones, have certain undesirable characteristics. Of course, this is partly a matter of personal taste, but some objective observations can certainly be made.
In the following discussion, five different mocking toolkits (besides JMockit) are considered, all in their latest stable releases as of May 9, 2011: EasyMock 3.0, jMock 2.5.1, Mockito 1.8.5, PowerMock 1.4.9, and Unitils 3.1. The code snippets below come from the sample JMockit test suites that compare the JMockit approach with those other toolkits.
mock = createMock(Collaborator.class)
in EasyMock;
final Subscriber subscriber = context.mock(Subscriber.class)
in jMock;
myServiceMock = createMock(MyService.class)
in PowerMock (which also supports declarative mocks with
the @Mock
annotation on instance fields);
List<String> mockedList = mock(List.class)
in Mockito (which, like PowerMock, has an optional
@Mock
annotation for instance fields).
Unitils follows the declarative approach, but using a generic type for declaring mock fields, eg
Mock<MessageService> mockMessageService
.
The approach in JMockit Expectations is always declarative, with the use of coding conventions and annotations for
instance fields as well as for test method parameters (the use of parameters to declare mocks is a
feature unique to JMockit, and as examples will show, an extremely convenient one).
expect(mock.voteForRemoval("Document"))
in EasyMock;
oneOf(subscriber).receive(message)
in jMock;
expect(myServiceMock.getAllPersons())
in PowerMock;
when(mockedList.get(0))
and verify(mockedList).get(0)
in Mockito;
mockMessageService.assertInvoked().sendMessage(alert1)
in Unitils.
In the JMockit Expectations & Verifications API, you always call the mocked method directly, without any need to
wrap or chain it with a mocking API specific call (there is only one exception to this, but it is rarely used).
void
methods, since calls to such methods cannot be wrapped in an API call like
expect(<call to mocked method>)
; both EasyMock and Mockito suffer from this problem, although that
is not the case with jMock or Unitils.
replay(mock)
to switch from record to replay, and
then later call verify(mock)
to switch from replay to verify (alternatively, there
is a base test class that provides replayAll()
and verifyAll()
helper methods).
PowerMock, when using the EasyMock API, also relies on calls to replayAll()
and
verifyAll()
.
Mockito and Unitils are better on this point, but at the cost of requiring explicit API calls for every invocation
to be recorded or verified.
jMock is similar to the JMockit Expectations syntax, where recorded invocations are those written inside an
Expectations code block (an anonymous inner class containing one instance initialization block but no
method implementations).
However, jMock has nothing like the Verifications block available in JMockit, and each Expectations
instance must be passed as argument in a call to the Mockery#checking
method, which transitions the
test from record to replay.
There are other less dramatic differences in style between JMockit and other mocking APIs, but the above items should be enough to show that many possibilities exist in the realm of mocking API design.
There are now other mocking tools for Java which also overcome the limitations of the conventional ones, between them PowerMock, jEasyTest, and MockInject. The one that comes closest to the feature set of JMockit is PowerMock, so I will briefly evaluate it here (besides, the other two are more limited and don't seem to be actively developed anymore).
@PrepareForTest({ClassA.class, ...})
annotation) and requiring specific API calls to deal with various kinds of language constructs that may be present in
the production code: static methods (mockStatic(ClassA.class)
),
constructors (suppress(constructor(ClassXyz.class))
),
constructor invocations (expectNew(AClass.class)
),
partial mocks (createPartialMock(ClassX.class, "methodToMock")
), etc.
@Mocked
annotation or by simply "un-mocking" the
members with no recorded expectations; that is, the developer simply declares some shared "mock fields" for the test
class, or some "local mock fields" and/or "mock parameters" for individual test methods (and in this last case the
@Mocked
annotation often won't be needed).
equals
and hashCode
,
overridden methods, and others, are currently not supported in PowerMock.
Also, there is no equivalent to JMockit's ability to capture instances and mock implementations of specified base
types as the test executes, without the test code itself having any knowledge of the actual implementation classes.
@PowerMockIgnore("package.to.be.ignored")
annotation on test classes.
Another recent mocking tool is Mockito. Although it does not attempt to overcome the limitations of older tools (jMock, EasyMock), it does introduce a new style of behavior testing with mocks. JMockit also supports this alternative style, through the Verifications API.
when(...)
) and verify (verify(...)
) phases.
This means that any invocation to a mock object in test code will also require a call to the mocking API.
Additionally, this will often lead to repetitive when(...)
and verify(mock)...
calls.
new NonStrictExpectations()
and
new Verifications()
constructor calls, but they occur only once per test (typically), and are completely
separate from the invocations to mocked methods and constructors.
when(mock.mockedMethod(args))...
while
in the verify phase this same call will be written as
verify(mock).mockedMethod(args)
.
Notice that in the first case the invocation to mockedMethod
is made directly on the
mock
object, while in the second case it is made on the object returned by verify(mock)
.
onInstance(mock)
call is
used, resulting in code like onInstance(mock).mockedMethod(args)
; most tests won't need to use this,
though.)
void
methods.
For example, you write when(mockedList.get(1)).thenThrow(new RuntimeException());
for a
non-void
method, and doThrow(new RuntimeException()).when(mockedList).clear();
for a
void
one.
With JMockit, it's always the same syntax:
mockedList.clear(); result = new RuntimeException();
.
spy
refers to an empty List
, then instead of writing
when(spy.get(0)).thenReturn("foo")
you will need to write doReturn("foo").when(spy).get(0)
.
With JMockit, the dynamic mocking feature provides similar functionality to spies, but without this issue
since real methods only get executed during the replay phase.
void
mocked method happened during the test, but the test requires a return value from that method
that is different from the default for the return type, then the Mockito test will have duplicate code: a
when(mock.someMethod()).thenReturn(xyz)
call in the record phase, and a
verify(mock).someMethod()
in the verify phase.
With JMockit, a strict expectation can always be recorded, which won't have to be explicitly verified.
Alternatively, an invocation count constraint (times = 1
) can be specified for any recorded
non-strict expectation (with Mockito such constraints can only be specified in a
verify(mock, constraint)
call).
verify
made on it:
InOrder inOrder = inOrder(mock1, mock2, ...)
.
In the second case, calls like verifyNoMoreInteractions(mock)
or
verifyZeroInteractions(mock1, mock2)
need to be made.
new VerificationsInOrder()
or new FullVerifications()
instead of new Verifications()
(or new FullVerificationsInOrder()
to combine both
requirements). No need to specify which mock objects are involved. No extra mocking API calls.
And as a bonus, by calling unverifiedInvocations()
inside an ordered verification block, you can
perform order-related verifications that are simply impossible in Mockito.
Finally, the JMockit Testing Toolkit has a wider scope and more ambitious goals than other mocking toolkits, in order to provide a complete and sophisticated developer testing solution. A good API for mocking, even without artificial limitations, is not enough for productive creation of tests. An IDE-agnostic, easy to use, and well integrated Code Coverage tool is also essential, and that's what JMockit Coverage aims to provide. Another piece of the developer testing toolset which will become more useful as the test suite grows in size is the ability to incrementally rerun tests after a localized change to production code; this is also included in the Coverage tool.
The JMockit Expectations mocking API provides a record-replay model for writing
behavior-based tests.
In this model, a test begins by setting one or more expectations on the invocations made
from code under test to its collaborators (dependencies).
The classes and instances for such dependencies are established through the declaration of one or
more mocked types inside the test class/method.
Such mocked types can be declared through instance fields of the test class or of an
Expectations
anonymous subclass inside a test method, and also through parameters
of test methods (even though JUnit and TestNG don't allow regular test methods to have parameters).
After expectations are defined in this recording phase, the test transitions to the
replay phase, when the code under test is exercised. The invocations that actually occur
on the mocked collaborators are handled according to the mocked type declarations and the
corresponding expectations recorded on them (if any).
At the end of the replay phase, those expectations for which one or more invocations were
expected are automatically verified so that missing invocations can be detected.
Expectations can be specified on any kind of method invocation (on interfaces, abstract classes, concrete final or non-final classes, and on static methods), as well as on class instantiation through any constructors. Private methods/constructors can also have expectations defined.
This API provides several ways to specify argument matching constraints on invocations, including the use of custom Hamcrest matchers. There are special methods and fields through which values to return or exceptions to throw can be specified for all kinds of mock invocations. Other API fields can be used to specify lower and/or upper limits on the number of expected and/or allowed invocations, respectively, for a given expectation.
public class JMockitExpectationsExampleTest
{
// Common mock fields can be declared here, and must be annotated with @Mocked.
@Test
public void testDoOperationAbc()
{
new Expectations()
{
// This is a local mock field; it can optionally be annotated with @Mocked.
DependencyXyz mock; // a mocked instance is automatically created and assigned
{
new DependencyXyz(); // records an expectation on a constructor invocation
mock.doSomething("test"); result = 123;
// The expectations above are strict, causing the whole dependency to be strictly verified.
// Therefore, invocations not recorded here will be considered unexpected, causing the test
// to fail if they occur while exercising the code under test.
// Non-strict expectations are also supported.
}
};
// In ServiceAbc#doOperationAbc(String s): "new DependencyXyz().doSomething(s);"
Object result = new ServiceAbc().doOperationAbc("test");
assertNotNull(result);
// That all expected invocations were actually executed in the replay phase is automatically
// verified at this point, through transparent integration with the JUnit/TestNG test runner.
}
}
This API is a natural extension of the Expectations API, where the record-replay model gets an extra phase and becomes the record-replay-verify model for behavior-based testing.
By default, all expectations recorded inside an Expectations
block are strict, which means
that for each expectation recorded a matching invocation must be executed during the replay phase of the test, and
in the same order as recorded.
Additionally, if during the replay phase an unexpected invocation (ie, one not matching a recorded strict
expectation) to one of the mocked types/instances is detected, then an assertion error will be thrown.
(The number of invocations for each strict expectation is flexible, though, since lower/upper limits can be specified
individually.)
Inside an Expectations
block, however, individual expectations can be marked as being
non-strict.
When all invocations to a given mocked type should be non-strict, the @NonStrict
annotation can be used.
Finally, if all expectations to be recorded (on one or more mocked types/instances in scope for the same test) should
be non-strict, the NonStrictExpectations
class can be used instead of
Expectations
.
A non-strict expectation, then, is one that by default can be invoked any number of times (including zero) during the replay phase, and in arbitrary order. Similarly, any unexpected invocation to a non-strict mocked type/instance does not cause an error to be thrown.
In this model, invocations to non-void methods that occur in the replay phase and that need a return value different
from the default one must still be recorded, as they normally would need if the expectations were strict.
All other invocations, on the other hand, can be verified to have occurred (or not) after the
replay phase, in the same place regular JUnit assertions would be.
This is done in the verification phase of the test, which is demarcated by a
Verifications
block (or a variant, such as VerificationsInOrder
).
It's also possible to have no expectations recorded for a given test, in which case there will be no
expectation block in the test method, but only the verification block.
public class JMockitVerificationsExampleTest
{
@Test // notice the "mock parameter", whose argument value will be created automatically
public void testDoAnotherOperation(final AnotherDependency anotherMock)
{
new NonStrictExpectations()
{
DependencyXyz mock; // mock instance created and assigned automatically
{
mock.doSomething("test"); result = 123; times = 1;
}
};
// In ServiceAbc#doAnotherOperationAbc(String s): "new DependencyXyz().doSomething(s);"
// and "new AnotherDependency().complexOperation(1, obj);".
new ServiceAbc().doAnotherOperation("test");
new Verifications()
{
{
anotherMock.complexOperation(anyInt, null);
}
};
}
}
This is a different kind of mocking API, which can be seen as complementary to the Expectations & Verifications API.
Instead of specifying expectations on the invocations made from code under test to its collaborators,
mock classes are defined and applied for the scope of a single test method or a whole test class.
Inside these mock classes, mock methods (indicated as such with the @Mock
annotation) are directly implemented with code that will be executed instead of the original code for the
corresponding mocked method/constructor.
In addition, constraints on the number of expected invocations for each mock method can be specified, and mock
methods can be made to be re-entrant.
public class JMockitAnnotationsExampleTest
{
@Test
public void testDoOperationAbc()
{
// A "mock-up" class, defined and applied at the same time:
new MockUp<DependencyXyz>()
{
@Mock(invocations = 1)
int doSomething(String value)
{
assertEquals("test", value);
return 123;
}
};
// In ServiceAbc#doOperationAbc(String s): "new DependencyXyz().doSomething(s);"
Object result = new ServiceAbc().doOperationAbc("test");
assertNotNull(result);
}
}
Existing OpenSource code coverage tools, such as Cobertura and EMMA are also less than ideal. Specifically, JMockit Coverage provides the following benefits.
jmockit-coverage-xyz.jar
file).
For the generation of the XHTML report, Java source files are automatically searched in all
"src" directories under the working directory.
If you have a suite of integration tests that directly or indirectly use the Hibernate 3 APIs,
you know those tests can be quite slow and fragile when compared to unit tests, because of their
dependence on database access, and on a large and complex ORM library such as Hibernate. And in
a project with hundreds of O/R mapped classes, SessionFactory
construction time
alone can take too many seconds for comfort. The advantages of such tests when compared to true
unit tests, on the other hand, are that they are relatively easier to write and actually test a
lot more (O/R mapping, HQL query strings, and the actual relational database).
The JMockit Hibernate Emulation component is a fake implementation of the Hibernate 3 Core APIs, which can be installed in place of the real implementation by simply having the component jar file (jmockit-hibernate3emul.jar) in the classpath, and allowing JMockit to be initialized before the first test is run. When those tests run with the emulation in effect, they won't use the O/R mapping information, nor will they access any real database. All persistence operations, including HQL queries, will be executed against the equivalent of an in-memory database.


6.12. Operators6.12.1. Standard Type OperatorsIn Chapter 4, we introduced a number of operators that apply to most objects, including the standard types. We will take a look at how some of those apply to lists. >>> list1 = ['abc', 123]
>>> list2 = ['xyz', 789]
>>> list3 = ['abc', 123]
>>> 1ist1 < list2
True
>>> list2 < list3
False
>>> list2 > list3 and list1 == list3
True When using the value comparison operators, comparing numbers and strings is straightforward, but not so much for lists, however. List comparisons are somewhat tricky, but logical. The comparison operators use the same algorithm as the cmp() built-in function. The algorithm basically works like this: the elements of both lists are compared until there is a determination of a winner. For example, in our example above, the output of 'abc' versus 'xyz' is determined immediately, with 'abc' < 'xyz', resulting in list1 < list2 and list2 >= list3. Tuple comparisons are performed in the same manner as lists. 6.12.2. Sequence Type OperatorsSlices ( [ ] and [ : ] )Slicing with lists is very similar to strings, but rather than using individual characters or substrings, slices of lists pull out an object or a group of objects that are elements of the list operated on. Focusing specifically on lists, we make the following definitions: >>> num_list = [43, -1.23, -2, 6.19e5] >>> str_list = ['jack', 'jumped', 'over', 'candlestick'] >>> mixup_list = [4.0, [1, 'x'], 'beef', -1.9+6j] Slicing operators obey the same rules regarding positive and negative indexes, starting and ending indexes, as well as missing indexes, which default to the beginning or to the end of a sequence. >>> num_list[1] -1.23 >>> >>> num_list[1:] [-1.23, -2, 619000.0] >>> >>> num_list[2:-1] [-2] >>> >>> str_list[2] 'over' >>> str_list[:2] ['jack', 'jumped'] >>> >>> mixup_list [4.0, [1, 'x'], 'beef', (-1.9+6j)] >>> mixup_list[1] [1, 'x'] Unlike strings, an element of a list might also be a sequence, implying that you can perform all the sequence operations or execute any sequence built-in functions on that element. In the example below, we show that not only can we take a slice of a slice, but we can also change it, and even to an object of a different type. You will also notice the similarity to multidimensional arrays. >>> mixup_list[1][1] 'x' >>> mixup_list[1][1] = -64.875 >>> mixup_list [4.0, [1, -64.875], 'beef', (-1.9+6j)] Here is another example using num_list: >>> num_list [43, -1.23, -2, 6.19e5] >>> >>> num_list[2:4] = [16.0, -49] >>> >>> num_list [43, -1.23, 16.0, -49] >>> >>> num_list[0] = [65535L, 2e30, 76.45-1.3j] >>> >>> num_list [[65535L, 2e+30, (76.45-1.3j)], -1.23, 16.0, -49] Notice how, in the last example, we replaced only a single element of the list, but we replaced it with a list. So as you can tell, removing, adding, and replacing things in lists are pretty freeform. Keep in mind that in order to splice elements of a list into another list, you have to make sure that the left-hand side of the assignment operator ( = ) is a slice, not just a single element. Membership ( in, not in )With lists (and tuples), we can check whether an object is a member of a list (or tuple). >>> mixup_list [4.0, [1, 'x'], 'beef', (-1.9+6j)] >>> >>> 'beef' in mixup_list True >>> >>> 'x' in mixup_list False >>> >>> 'x' in mixup_list[1] True >>> num_list [[65535L, 2e+030, (76.45-1.3j)], -1.23, 16.0, -49] >>> >>> -49 in num_list True >>> >>> 34 in num_list False >>> >>> [65535L, 2e+030, (76.45-1.3j)] in num_list True Note how 'x' is not a member of mixup_list. That is because 'x' itself is not actually a member of mixup_list. Rather, it is a member of mixup_uplist[1], which itself is a list. The membership operator is applicable in the same manner for tuples. Concatenation ( + )The concatenation operator allows us to join multiple lists together. Note in the examples below that there is a restriction of concatenating like objects. In other words, you can concatenate only objects of the same type. You cannot concatenate two different types even if both are sequences. >>> num_list = [43, -1.23, -2, 6.19e5] >>> str_list = ['jack', 'jumped', 'over', 'candlestick'] >>> mixup_list = [4.0, [1, 'x'], 'beef', -1.9+6j] >>> >>> num_list + mixup_list [43, -1.23, -2, 619000.0, 4.0, [1, 'x'], 'beef', (-1.9+6j)] >>> >>> str_list + num_list ['jack', 'jumped', 'over', 'candlestick', 43, -1.23, -2, 619000.0] As we will discover in Section 6.13, starting in Python 1.5.2, you can use the extend() method in place of the concatenation operator to append the contents of a list to another. Using extend() is advantageous over concatenation because it actually appends the elements of the new list to the original, rather than creating a new list from scratch like + does. extend() is also the method used by the augmented assignment or in-place concatenation operator (+=), which debuted in Python 2.0.
We would also like to point out that the concatenation operator does not facilitate adding individual elements to a list. The upcoming example illustrates a case where attempting to add a new item to the list results in failure. >>> num_list + 'new item' Traceback (innermost last): File "<stdin>", line 1, in ? TypeError: illegal argument type for built-in operation This example fails because we had different types to the left and right of the concatenation operator. A combination of (list + string) is not valid. Obviously, our intention was to add the 'new item' string to the list, but we did not go about it the proper way. Fortunately, we have a solution: Use the append() list built-in method (we will formally introduce append() and all other built-in methods in Section 6.13): >>> num_list.append('new item') Repetition ( *)Use of the repetition operator may make more sense with strings, but as a sequence type, lists and tuples can also benefit from this operation, if needed: >>> num_list * 2 [43, -1.23, -2, 619000.0, 43, -1.23, -2, 619000.0] >>> >>> num_list * 3 [43, -1.23, -2, 619000.0, 43, -1.23, -2, 619000.0, 43, -1.23, -2, 619000.0] Augmented assignment also works, beginning in Python 2.0: >>> hr = '-' >>> hr *= 30 >>> hr '------------------------------' 6.12.3. List Type Operators and List ComprehensionsThere are really no special list-only operators in Python. Lists can be used with most object and sequence operators. In addition, list objects have their own methods. One construct that lists do have however, are list comprehensions. These are a combination of using list square brackets and a for-loop inside, a piece of logic that dictates the contents of the list object to be created. We cover list comprehensions in Chapter 8, but we present a simple example here as well as a few more throughout the remainder of the the chapter: >>> [ i * 2 for i in [8, -2, 5] ] [16, -4, 10] >>> [ i for i in range(8) if i % 2 == 0 ] [0, 2, 4, 6] |


☰
HOME
DICE GAME
Restart
Player 1
Player 2
Edit Names
Player 1
Score:
0
Player 2
Score:
0
×
Player 1
WON!
Score :
0


Below are some utilities that may enhance your experience of online classes with EA Live. Please
note that none of these software/links are owned and/or operated by Eduatlas and hance, are
governed by their own terms and conditions. Users are advised to use their discretion before
downloading any of the below mentioned utilities.
Clicking on the links below will redirect you to a webpage outside EDUATLAS.
FREE SCREEN RECORDER
FREE CAM
Easily create screencasts, edit recorded videos, and upload to YouTube. No watermark or
time limits


{% extends 'index.html' %} {% load static %} {% block head_title %} Path to Product Based Companies | {{ block.super }} {% endblock head_title %} {% block part %}
Path to product based companies
Yeahh
As said I have a "Part" of plan.
Step 1
Learn a language (I know your mind. Please don't think abt Hindi, English, Telugu)
Step 2
DATA STRUCTURES AND ALGORITHMS
Step 3
Competitive Coding
This comes into action after first two steps. This polishes your skills learnt from above 2 steps. There are many coding platforms which you can try
Step 4
Theory Subjects
You don't need to study all 40+ subjects from 8 semester. No one gonna ask you to solve differential equations etc.( That doesn't mean company gonna recruit you irrespective of backlogs. So you need to clear them)
Step 5
Testing Yourself !!
yes you need to test yourself. After the test you will get to know places of improvements. There are platforms like
Final Part (Main Part)
Ok we are at main part. This depends on you. Just you.
you need to be consistent at your work. Its not like "aaj mai 10 questions solve kiye and ek maheene ke baadh fir se shuru karunga" nahhh!! That doesn't work
just solve 1-2 questions per day but do it everyday. Through out the month. Do it very consistently. Consistency is the key to success.


|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |
java.lang.Object org.joone.edit.NetStorageFormatManager
The NetStorageFormatManager is a contains NetStorageFormats. It is not a Singleton because it could be necessary to deal with different format managers, e.g. one for importing NeuralNets, one for exporting NeuralNets. If one NetStorageFormat matches the file extension of the NeuralNet file, then this NetStorageFormat can be used to store or restore the NeuralNet.
StorageFormat
| Constructor Summary | |
NetStorageFormatManager()
Create a new NetStorageFormatManager. |
| Method Summary | |
void |
addStorageFormat(NetStorageFormat newStorageFormat)
Add a NetStorageFormat that should be supported by this NetStorageFormatManager. |
boolean |
containsStorageFormat(NetStorageFormat checkStorageFormat)
Test, whether a NetStorageFormat is supported by this StorageFormat |
NetStorageFormat |
findStorageFormat(javax.swing.filechooser.FileFilter findFileFilter)
Find a NetStorageFormat that can be used according to a FileFilter to store a NeuralNet in a file or restore it from a file respectively. |
NetStorageFormat |
getDefaultStorageFormat()
Return the NetStorageFormat which is used as selected file format in a javax.swing.JFileChooser |
void |
registerFileFilters(javax.swing.JFileChooser fileChooser)
Register all FileFilters supported by NetStorageFormats |
void |
removeStorageFormat(NetStorageFormat oldStorageFormat)
Remove a StorageFormat that should no longer be supported by this StorageFormatManager. |
void |
setDefaultStorageFormat(NetStorageFormat newDefaultStorageFormat)
Set a NetStorageFormat as the default storage format which is selected in a javax.swing.JFileChooser. |
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
| Constructor Detail |
public NetStorageFormatManager()
| Method Detail |
public void addStorageFormat(NetStorageFormat newStorageFormat)
newStorageFormat
- new NetStorageFormat to be supportedpublic void removeStorageFormat(NetStorageFormat oldStorageFormat)
oldStorageFormat
- old NetStorageFormat no longer to be supportedpublic boolean containsStorageFormat(NetStorageFormat checkStorageFormat)
public void setDefaultStorageFormat(NetStorageFormat newDefaultStorageFormat)
newDefaultStorageFormat
- StorageFormat that should be selected in a JFileChooserpublic NetStorageFormat getDefaultStorageFormat()
public void registerFileFilters(javax.swing.JFileChooser fileChooser)
fileChooser
- javax.swing.JFileChooser to which FileFilters are addedpublic NetStorageFormat findStorageFormat(javax.swing.filechooser.FileFilter findFileFilter)
findFileFilter
- FileFilter used to identify a NetStorageFormat
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |


SimpleClusterResolver
Simple implementation of ClusterResolver that accepts a ClusterSpec.
Inherits From: ClusterResolver
tf.compat.v1.distribute.cluster_resolver.SimpleClusterResolver
tf.compat.v2.distribute.cluster_resolver.SimpleClusterResolver
__init__
__init__( cluster_spec, master='', task_type=None, task_id=None, environment='', num_accelerators=None, rpc_layer=None )
Creates a SimpleClusterResolver from a ClusterSpec.
environment
Returns the current environment which TensorFlow is running in.
There are two possible return values, "google" (when TensorFlow is running in a Google-internal environment) or an empty string (when TensorFlow is running elsewhere).
If you are implementing a ClusterResolver that works in both the Google environment and the open-source world (for instance, a TPU ClusterResolver or similar), you will have to return the appropriate string depending on the environment, which you will have to detect.
Otherwise, if you are implementing a ClusterResolver that will only work in open-source TensorFlow, you do not need to implement this property.
rpc_layer
task_id
task_type
cluster_spec
cluster_spec()
Returns the ClusterSpec passed into the constructor.
master
master( task_type=None, task_id=None, rpc_layer=None )
Returns the master address to use when creating a session.
task_type
: (Optional) The type of the TensorFlow task of the master.task_id
: (Optional) The index of the TensorFlow task of the master.rpc_layer
: (Optional) The RPC used by distributed TensorFlow.The name or URL of the session master.
If a task_type and task_id is given, this will override the master
string passed into the initialization function.
num_accelerators
num_accelerators( task_type=None, task_id=None, config_proto=None )
Returns the number of accelerator cores per worker.
The SimpleClusterResolver does not do automatic detection of accelerators, so a TensorFlow session will never be created, and thus all arguments are unused and we simply assume that the type of accelerator is a GPU and return the value in provided to us in the constructor.
task_type
: Unused.task_id
: Unused.config_proto
: Unused.


Method List
#match?
(class CallableStrategy)
#run
(class CallableStrategy)
#match?
(class ControllerStrategy)
#run
(class ControllerStrategy)
#call
(class Route)
#default
(class Route)
#match?
(class Route)
#to
(class Route)
#find
(class Router)
#include
(class Router)
#initialize
(class Router)
#inspect
(class Router)
#match
(class Router)
#redirect
(class Router)
find
(class Router)
register
(class Router)
#register
(class RouterStrategy)
#proceed
(class Adapter)
boot
(class Rango)
codename
(class Rango)
flat?
(class Rango)
framework
(class Rango)
import
(class Rango)
interactive
(class Rango)
logger
(class Rango)
version
(class Rango)


Thanks to our experience and expertise, we were entrusted with the development of a new website for Araxia’s capital city, Riyadh, in collaboration with a well-recognized local agency.
Design very few companies in the world have ventured on a project of such tremendous scope and complex
Creativity for us something personal.
Creativity for us something personal.
Creativity for us something personal.


| Module | Description |
|---|---|
| system |
Provides classes that describe the basic functionality
|
| system'calendar |
Provides classes that describe the basic functionality
|
| system'collections |
Provides classes that describe collections
|
| system'culture |
Provides classes that describe the basic functionality
|
| system'io |
Provides classes that describe the basic functionality
|
| system'math |
Provides classes that describe the basic functionality
|
| system'text |
Provides classes that describe the basic functionality
|
| Module | Description |
|---|---|
| system'drawing(not yet migrated) |
Provides classes to work graphic primitives
|
| Module | Description |
|---|---|
| system'dynamic |
Provides classes to work with dynamic code
|
| system'dynamic'expressions |
Provides classes to work with dynamic expression trees
|
| Module | Description |
|---|---|
| system'net(not yet migrated) |
Provides classes to work with sockets
|
| Module | Description |
|---|---|
| system'routines |
Provides classes to work with enumerations
|
| Module | Description |
|---|---|
| system'routines'stex |
Provides classes to work with strong-typed enumerations
|
| Module | Description |
|---|---|
| system'runtime |
Provides classes to work with runtime environment
|
| Module | Description |
|---|---|
| system'threading |
Provides classes to work with threads
|
| Module | Description |
|---|---|
| system'winforms(not yet migrated) |
Provides classes to work with GUI controls
|
| Module | Description |
|---|---|
| extensions |
Provides classes to extend basic functionality
|
| extensions'io(not yet migrated) |
Provides classes to extend i/o functionality
|
| extensions'math |
Provides classes to extend math functionality
|
| extensions'text |
Provides classes to extend text functionality
|
| Module | Description |
|---|---|
| extensions'dynamic(not yet migrated) |
Provides classes to extend dynamic operations
|
| Module | Description |
|---|---|
| extensions'routines |
Provides classes to extend collection operations
|
| Module | Description |
|---|---|
| extensions'scripting |
Provides classes to implement operations with scripts
|
| Module | Description |
|---|---|
| extensions'threading(not yet migrated) |
Provides classes to extend operations with threads
|
| Module | Description |
|---|---|
| forms (not yet migrated) |
Provides classes to build GUI
|
| Module | Description |
|---|---|
| algorithms(not yet migrated) |
Provides classes to implement basic algorithms
|
| Module | Description |
|---|---|
| cellular(not yet migrated) |
Provides classes to work with cellular state machines
|
| Module | Description |
|---|---|
| net(not yet migrated) |
Provides classes to implement communication operations
|
| Module | Description |
|---|---|
| sqlite(not yet migrated) |
Provides classes to operate with Sqlite databases
|
| Module | Description |
|---|---|
| xforms(not yet migrated) |
Provides classes to render GUI layout
|


Ben Martinson
Home
Experience
Education
Projects
Email<EMAIL_ADDRESS>Github: https://github.com/bmartinson5/