id
stringlengths
7
14
source
stringlengths
135
41.2k
target
stringlengths
36
20.4k
1584558_0
class HiddenSingleMaskFactory extends SDKMaskFactory { public static boolean isHiddenSingle(SDKSquare s, SDKBoard board) { LinkedList<SDKSquare> zsqrs = board.getSquaresInZone(s); zsqrs.remove(s); LinkedList<SDKSquare> csqrs = board.getSquaresInCol(s.col); csqrs.remove(s); LinkedList<SDKSquare> rsqrs = boar...
int[][] test = {{0,0,0,0,0,0,0,0,0}, {0,0,5,0,8,0,4,0,0}, {0,4,6,7,2,9,0,5,1}, {9,6,0,3,5,0,0,8,0}, {0,0,0,0,6,0,9,3,5}, {0,8,3,0,1,4,0,2,7}, {1,7,0,5,0,0,2,0,3}, {0,0,9,0,0,1,0,6,8}, {0,5,4,2,3,8,7,0,0}}; SDKBoard board = new SDKBoard(); board.loadSimpleBoard(test); board.updateConstrai...
1589946_11
class AttributeModelAdapter { public static AttributeSearchResponse fromCatalogAPI(AttributeResponse result) { AttributeSearchResponse attributeSearchResponse = new AttributeSearchResponse(); if (inputIsValid(result)) { return attributeSearchResponse; } AttributeRespo...
AttributeResponse attributeResponse = generateAttributeResponse(); AttributeSearchResponse attributeSearchResponse = AttributeModelAdapter.fromCatalogAPI(attributeResponse); assertTrue(responsesAreEqual(generateExpectedAttributeSearchResponse(), attributeSearchResponse)); } }
1592475_4
class ResultTraverser { public void traverse( Object instance, Selector selector, HierarchicalModel<?> model, YogaRequestContext context ) throws IOException { if (instance != null) { if (instance instanceof Iterable) { traverseIterable( (Iter...
HashMap<Object,Object> map = new HashMap<Object, Object>(); map.put("someKey", "someValue"); map.put("anotherKey", "anotherValue"); BasicTestDataLeaf input = new BasicTestDataLeaf(); input.setId(10); input.setName("name"); input.setOther("other"); map.put(...
1603876_2
class FlagManager { public FeatureFlags getFlag(String flagName) { return (FeatureFlags) invokeStaticMethod("valueOf", new Object[] { flagName }, String.class); } private FlagManager(Class<?> featureFlagsClass); public void init(); public static FlagManager get(Class<?> featureFlagsClass); ...
FeatureFlags flag = manager.getFlag("ONE"); assertEquals("get flag ONE", Flags.ONE, flag); flag = manager.getFlag("THREE"); assertEquals("get flag THREE", Flags.THREE, flag); flag = manager.getFlag("YOU SHALL NOT EXIST"); assertEquals("get flag YOU SHALL NOT EXIST", null, flag); } }
1604565_0
class MultiGraph implements Graph { public Iterable<Vertex> getVertices() { Collection<Iterable<Vertex>> base = new LinkedList<Iterable<Vertex>>(); for (int pos = 0; pos < bases.length; pos++) { base.add(new MultiVertexIterable(pos)); } return new MultiIterable<Vertex>...
int count = 0; Set<Object> ids = new HashSet<Object>(); for (Vertex v : graph.getVertices()) { assertTrue(v instanceof MultiVertex); ids.add(v.getId()); count++; } assertEquals(5, count); assertEquals(5, ids.size()); assertTru...
1605107_158
class DemTile { @Deprecated public void computeGeoCorners(final SLCImage meta, final Orbit orbit, final Window tile) throws Exception { double[] phiAndLambda; final double l0 = tile.linelo; final double lN = tile.linehi; final double p0 = tile.pixlo; final double pN = ...
demTile.computeGeoCorners(masterMeta, masterOrbit, masterTileWindow); double phiMin_EXPECTED = 0.65198531114095126; Assert.assertEquals(phiMin_EXPECTED, demTile.phiMin, DELTA_08); double phiMax_EXPECTED = 0.65803878531122906; Assert.assertEquals(phiMax_EXPECTED, demTile.phiMax...
1608936_6
class ArrayHelper { public static <T> int indexOf(T[] array, T element) { for ( int i = 0; i < array.length; i++ ) { if ( array[i].equals( element ) ) { return i; } } return -1; } public static String[] toStringArray(Collection coll); public static String[][] to2DStringArray(Collection coll); pub...
Object[] array = new Integer[]{ 1, 2, 3 }; Object element = 3; int expResult = 2; int result = ArrayHelper.indexOf( array, element ); assertEquals( expResult, result ); } }
1613090_15
class LazyHCatRecord extends HCatRecord { @Override public Object get(int fieldNum) { try { StructField fref = soi.getAllStructFieldRefs().get(fieldNum); return HCatRecordSerDe.serializeField( soi.getStructFieldData(wrappedObject, fref), fref....
HCatRecord r = new LazyHCatRecord(getHCatRecord(), getObjectInspector()); Assert.assertEquals(INT_CONST, ((Integer) r.get(0)).intValue()); Assert.assertEquals(LONG_CONST, ((Long) r.get(1)).longValue()); Assert.assertEquals(DOUBLE_CONST, ((Double) r.get(2)).doubleValue(), 0); Asse...
1619254_27
class SimpleDegree implements Degree { public Degree min(Degree comp) { return new SimpleDegree( Math.min(this.getValue(), comp.getValue()) ); } public SimpleDegree(); public SimpleDegree(double degree); public SimpleDegree(String degree); public void setValue(double value); pu...
SimpleDegree s1 = new SimpleDegree(0.6); SimpleDegree s2 = new SimpleDegree(0.3); Degree s4 = s1.min(s2); assertEquals(new SimpleDegree(0.6),s1); assertEquals(new SimpleDegree(0.3),s2); assertEquals(s2,s4); } }
1619733_7
class Parser { public Database parse( File file ) throws IOException { // Read the file into a single string ... String ddl = readFile(file); // Create the object that will parse the file ... DdlParsers parsers = new DdlParsers(); AstNode node = parsers.parse(ddl, file.getN...
database = parser.parse(testFile("create_schema.ddl")); assertThat(database.getName(), is("POSTGRES")); Schema schema = database.getSchema("hollywood", false); assertThat(schema.getName(), is("hollywood")); Table table = schema.getTable("films", false); assertThat(table.g...
1626780_5
class SqlDao implements AutoCloseable { public SubjectRef getOrCreateSubjectRef(String type, String name) throws SQLException { final SubjectRef ret = SubjectRef.unresolved(type, name); allocateSubjectRef(ret); return ret; } public SqlDao(SqlDataStore ds); protected String ge...
try (SqlDao dao = sqlStore.getDao()) { assertFalse(dao.getSubjectRef("group", "admin").isPresent()); SubjectRef created = dao.getOrCreateSubjectRef("group", "admin"); SubjectRef fetched = dao.getSubjectRef("group", "admin").get(); assertEquals(created.getId(), fet...
1628050_3
class APIAuthentication { public static void validate (APICredential cred, SecretKey secretKey, byte[]... payLoad) throws NoSuchAlgorithmException, InvalidKeyException { if (!VERSION.equals(cred.getVersion())) throw new IllegalArgumentException ("unsupported.version"); assertNotNull(pay...
try { byte[] payLoad = UUID.randomUUID().toString().getBytes(); KeyGenerator gen = KeyGenerator.getInstance("HmacSHA256"); SecretKey badSecretKey = gen.generateKey(); APIAuthentication.validate( APICredential.builder() .version(APIA...
1639726_10
class SOAPMailSender extends MailSender { public MimeMessage createMessage(String from, String to, String cc, String subject, SOAPMessage soapMessage) throws ConnectionException { return createMessage(from, to, cc, subject, soapMessage, createSession()); } public SOAPMailSender(String...
SOAPMessage soapMessage = null; MimeMessage mimeMsg = null; MimeHeaders mimeHeaders = new MimeHeaders(); InputStream contentStream = FIXTURE_LOADER.getResourceAsStream("mime_message_content.dat"); mimeHeaders.setHeader("Content-Type", "text/xml; charset=utf-8"); ...
1644461_572
class SqlQueryParser implements QueryParser { protected NamedSelector parseNamedSelector( TokenStream tokens, TypeSystem typeSystem ) { SelectorName name = parseSelectorName(tokens, typeSystem); SelectorName alias = null; if (tokens.canConsume...
NamedSelector selector = parser.parseNamedSelector(tokens("name AS alias"), typeSystem); assertThat(selector.name(), is(selectorName("name"))); assertThat(selector.alias(), is(selectorName("alias"))); assertThat(selector.aliasOrName(), is(selectorName("alias"))); } }
1644585_55
class HasJsonPath extends TypeSafeMatcher<JsonNode> { @Override public void describeTo(Description description) { description.appendText("a JSON object matching JSONpath \"" + jsonPath + "\""); if (matcher != null) { description.appendText(" with "); matcher.des...
// bugfix for issue #47 hasJsonPath = new HasJsonPath<Object>("$.foo"); StringDescription sd = new StringDescription(); hasJsonPath.describeTo(sd); assertThat(sd.toString(), is("a JSON object matching JSONpath \"$.foo\"")); } }
1645877_7
class GenericDataSource implements DataSource { @Override public String getResourceName() { return resourceName; } public GenericDataSource(InputStream inputStream, String resourceName); @Override public URI getUri(); @Override public InputStream getInputStream(); } class GenericDataSourceTest { @Test ...
GenericDataSource staticDataSource = new GenericDataSource(null, "resource"); assertThat(staticDataSource.getResourceName(), IsEqual.equalTo("resource")); } }
1660918_16
class Dependencies { public static boolean areEquivalent(Dependency l, Dependency r) { if (l == r) { return true; } if ((l == null) && (r == null)) { return true; } else if ((l == null) || (r == null)) { return false; } retur...
Dependency depOne = DependencyBuilder.create().setGroupId("org.jboss.errai").setArtifactId("errai-cdi-client") .setPackaging("jar"); Dependency depTwo = DependencyBuilder.create().setGroupId("org.jboss.errai").setArtifactId("errai-cdi-client") .setPackaging("test-jar"); A...
1666060_2
class HoltWintersComputer { public double getAlpha() { return alpha; } public HoltWintersComputer(double alpha); public HoltWintersComputer(double alpha, double beta); public HoltWintersComputer(double alpha, double beta, double gamma, int period); public void addNextValue(doub...
// series<-ts(c(315.42, 316.31, 316.50, 317.56, 318.13, 318.00, 316.39, 314.65, 313.68, 313.18, 314.66, 315.43)) double[] series = {315.42, 316.31, 316.50, 317.56, 318.13, 318.00, 316.39, 314.65, 313.68, 313.18, 314.66, 315.43}; // smooth<-HoltWinters(co2, alpha=0.8, beta=FALSE, gamma=FALSE) ...
1670551_43
class TupleQuery extends TwigQuery { public void add(final NodeQuery query, final NodeBooleanClause.Occur occur) { super.addChild(query, occur); } public TupleQuery(); public TupleQuery(final int level); public TupleQuery(final boolean disableCoord); public TupleQuery(final int level, final boolea...
this.addDocument("\"bbb\" . "); final Query query = tuple() .optional(nbq(must("ddd")), nbq(must("eee"))) .getLuceneProxyQuery(); final BooleanQuery q = new BooleanQuery(); q.add(new TermQuery(new Term(DEFAULT_TEST_FIELD, "bbb")), BooleanClause.Occur.SHOULD); q.add(query, BooleanClause...
1672467_0
class Utf8StringUtils { public static List<String> utf8byteSizeSplit(String s, int maxChunkBytes) { if (maxChunkBytes < 6) { throw new IllegalArgumentException("Max UTF-8 chunk size cannot be less than 6"); } byte[] bytes = s.getBytes(UTF8); List<String> result = new Ar...
int runs = 10 + random.nextInt(10); System.out.println("Running " + runs + " random UTF-8 string-split tests..."); for (int r=0; r<runs; r++) { String source = RandomStringUtils.random(100000); int size = 6 + random.nextInt(1000); List<String> splitList = Utf8...
1676303_13
class ComplianceActivityUnmarshaller implements Unmarshaller<Activity> { @Override public final Activity unmarshall(final String s) { try { return mapper.readValue(s, ComplianceActivity.class).toActivity(); } catch (final IOException | UncheckedIOException e) { logger.wa...
final String s = "{\"user_undelete\":{\"id\":796250066,\"timestamp_ms\":\"1432228149062\"}}"; final Activity result = unmarshaller.unmarshall(s); assertEquals(ComplianceActivity.Verb.USER_UNDELETE, result.getVerb()); assertEquals("796250066", result.getActor().getId()); assertEqu...
1688262_32
class SafeCast { public static int toInt(Object o, int def) { if (!(o instanceof Integer)) { return def; } return (Integer) o; } public static long toLong(Object o, long def); public static byte toByte(Object o, byte def); public static float toFloat(Object o, float def); public static byte[] toByteAr...
assertTrue("Unable to process valid cast", SafeCast.toInt(new Integer(22), 7) == 22); assertTrue("Default did not work (wrong type)", SafeCast.toInt(new Long(22), 7) == 7); assertTrue("Default did not work (null)", SafeCast.toInt(null, 9) == 9); } }
1707059_12
class Enunciate implements Runnable { protected Graph<String, DefaultEdge> buildModuleGraph(Map<String, ? extends EnunciateModule> modules) { Graph<String, DefaultEdge> graph = new DefaultDirectedGraph<String, DefaultEdge>(DefaultEdge.class); for (String moduleName : modules.keySet()) { graph.addVertex...
final Map<String, TestModule> myModules = new HashMap<String, TestModule>(); List<String> moduleCallOrder = new ArrayList<String>(); myModules.put("a", new TestModule("a", moduleCallOrder)); myModules.put("b", new TestModule("b", moduleCallOrder)); myModules.put("c", new TestModule("c", moduleCallOr...
1710792_5
class PythonJob { static BoxerUnboxer<?,? extends Writable> createOutputType(String type) { if ("text".equals(type)) { return new TextBoxerUnboxer(); } else if ("long".equals(type)) { return new LongBoxerUnboxer(); } else if ("double".equals(type)) { return new DoubleBoxerUnboxe...
assertTrue(PythonJob.createOutputType("json") instanceof JsonBoxerUnboxer); } }
1711412_0
class SassCompilingFilter implements Filter { public void setCompiler(Compiler compiler) { this.compiler = compiler; } public void init(FilterConfig filterConfig); public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain); private void wa...
com.darrinholst.sass_java.Compiler compiler = mock(Compiler.class); filter.setCompiler(compiler); initFilter(); verify(compiler).compile(); } }
1711467_210
class TableProcessor extends AbstractEntityFieldProcessor { @Override public void process(Class clazz, EntityMetadata metadata) { if (LOG.isDebugEnabled()) LOG.debug("Processing @Entity(" + clazz.getName() + ") for Persistence Object."); populateMetadata(metadata, clazz, puProp...
final String persistenceUnit = "rdbms"; EntityMetadata metadata; PersistenceUnitMetadata puMetadata = new PersistenceUnitMetadata(); puMetadata.setPersistenceUnitName(persistenceUnit); Map<String, Object> props = new HashMap<String, Object>(); props.put(Constants.PERSI...
1720284_21
class StatusesServiceImpl implements StatusesService { @Override public List<Status> getStatus(Repository repository, String sha1) { if (repository == null) { throw new NullPointerException("Repository can't be null"); } if (sha1 == null) { throw new NullPointerException("SHA1 can't be null"); } log...
assertThat(service.getStatus(test, "ac61d48e3020f61c4d7a19709494f37065c87d34")).containsExactly(Status.NEW); } }
1724015_6
class MavenUtil { static String artifactToMvn(Artifact artifact) { return artifactToMvn(RepositoryUtils.toArtifact(artifact)); } static String mvnToAether(String name); private static boolean present(String part); static String aetherToMvn(String name); static String pathFromMaven(Stri...
assertEquals("mvn:org.foo/org.foo.bar/1.0-SNAPSHOT", artifactToMvn(new DefaultArtifact("org.foo:org.foo.bar:1.0-SNAPSHOT"))); assertEquals("mvn:org.foo/org.foo.bar/1.0-SNAPSHOT/kar", artifactToMvn(new DefaultArtifact("org.foo:org.foo.bar:kar:1.0-SNAPSHOT"))); assertEquals("mvn:org.foo/org.foo.ba...
1742658_4
class TextAreaItem extends FormItem<String> { @Override public void resetMetaData() { super.resetMetaData(); textArea.setValue(null); } public TextAreaItem(String name, String title); public TextAreaItem(String name, String title, boolean required); private void setup(); ...
TextAreaItem tai = new TextAreaItem("a", "b"); Assert.assertFalse("Precondition", tai.isModified()); ValueChangeEvent<String> event = new ValueChangeEvent<String>("Some value") {}; tai.valueChangeHandler.onValueChange(event); Assert.assertTrue(tai.isModified()); tai.reset...
1743723_2
class ScriptingServiceImpl extends AbstractService implements ScriptingService { @Override public synchronized List<ScriptContext> load(File scriptDescriptor) throws Exception { Preconditions.checkNotNull(scriptDescriptor, "scriptDescriptor"); final JAXBContext c = JAXBContext.newInstance(ScriptInfo.class, ...
final List<ScriptContext> contexts = service.load(new File( "src/test/resources/scripting/testcase.xml")); Assert.assertEquals(1, contexts.size()); final ScriptContext context = contexts.get(0); Class<?> clazz = context.getClassLoader().loadClass( "test.ScriptingCompilerTest"); Assert.assertNotNull(cl...
1757703_8
class Utils { public static <T> List<T> moveValuesToIndex(List<? extends T> values, List<? extends T> moveValues, int index, boolean allowAdd) { int size = values.size(); if (index > size) { throw new ArrayIndexOutOfBoundsException("Index: " + index + ", Size: " + values.size()); ...
List<String> values = Arrays.asList("1", "2", "3", "4"); List<String> moveValues = Arrays.asList("1", "2"); List<String> expected = Arrays.asList("3", "1", "2", "4"); boolean allowAdd = false; assertEquals(expected, Utils.moveValuesToIndex(values, moveValues, 3, allowAdd...
1767164_19
class ValidationController { @RequestMapping(value = "{canonicalClassName:.+}", method = RequestMethod.GET) public ModelConstraint getConstraintsForClassName(@PathVariable String canonicalClassName, @RequestParam(required = false) String locale) { Locale loc = null; try { if (loca...
this.validationController.getConstraintsForClassName("knownClassName", "fr"); verify(this.validationService).getConstraintsForClassName(eq("knownClassName"), any(Locale.class)); } }
1767458_8
class TripItTemplate extends AbstractOAuth1ApiBinding implements TripIt { public List<Trip> getUpcomingTrips() { return getRestTemplate().getForObject("https://api.tripit.com/v1/list/trip/traveler/true/past/false?format=json", TripList.class).getList(); } public TripItTemplate(String consumerKey, String consume...
mockServer.expect(requestTo("https://api.tripit.com/v1/list/trip/traveler/true/past/false?format=json")) .andExpect(method(GET)) .andRespond(withSuccess(new ClassPathResource("no-trips.json", getClass()), MediaType.APPLICATION_JSON)); List<Trip> trips = tripIt.getUpcomingTrips(); assertNotNull(trips); a...
1767567_18
class JavaSourceParser { public static Map<String, String[]> methodToParamNamesMap( String javaSrcFile, Class<?> clazz) { Map<String, String[]> map = new HashMap<String, String[]>(); try { JavaDocBuilder builder = new JavaDocBuilder(); builder.addSource(new File(javaSrcFile)); JavaClass jc = buil...
Class<?> clazz = JavaSourceSample.class; String javaSrcFile = getTestSourcePath(clazz); Map<String, String[]> map = JavaSourceParser.methodToParamNamesMap(javaSrcFile, clazz); Assert.assertNotNull("Map should not be null", map); dump(map); Assert.assertTrue("Should have found 'dosomething' method", ma...
1768217_49
class TimelineTemplate extends AbstractTwitterOperations implements TimelineOperations { public List<Tweet> getUserTimeline() { return getUserTimeline(20, 0, 0); } public TimelineTemplate(RestTemplate restTemplate, boolean isAuthorizedForUser, boolean isAuthorizedForApp); public List<Tweet> getHomeTimeline();...
mockServer.expect(requestTo("https://api.twitter.com/1.1/statuses/user_timeline.json?count=15&user_id=2&include_entities=true")) .andExpect(method(GET)) .andRespond(withSuccess(jsonResource("timeline"), APPLICATION_JSON)); List<Tweet> timeline = twitter.timelineOperations().getUserTimeline(2, 15); assertT...
1768307_34
class Sql2o { @Deprecated public Query createQuery(String query, boolean returnGeneratedKeys) { return new Connection(this, true).createQuery(query, returnGeneratedKeys); } public Sql2o(String jndiLookup); public Sql2o(String url, String user, String pass); public Sql2o(String url, ...
createAndFillUserTable(); ResultSetIterable<User> allUsers = sql2o.createQuery("select * from User").executeAndFetchLazy(User.class); Iterator<User> usersIterator = allUsers.iterator(); // call hasNext a few times, should have no effect usersIterator.hasNext(); usersIt...
1768380_12
class FacebookAdapter implements ApiAdapter<Facebook> { public void setConnectionValues(Facebook facebook, ConnectionValues values) { User profile = facebook.fetchObject("me", User.class, "id", "name", "link"); values.setProviderUserId(profile.getId()); values.setDisplayName(profile.getName()); values.setProf...
User user = new User("12345678", "Craig Walls", "Craig", "Walls", null, null); Field linkField = user.getClass().getDeclaredField("link"); linkField.setAccessible(true); linkField.set(user, "https://www.facebook.com/975041837"); Mockito.when(facebook.fetchObject("me", User.class, "id", "name", "link")).thenRe...
1772628_1
class BusinessSLA { public BusinessServiceLevel computeServiceLevel(long responseTime,Date timeStamp){ //assume that the service is at it best shape BusinessServiceLevel sl=BusinessServiceLevel.GOLD; //check if its gold if(goldPeriod.inPeriod(timeStamp)&&responseTime>maxGold){ //it s not so its silver ...
BusinessSLA sla= new BusinessSLA(70, 80, 85, new HoursPeriod(0, 1440), new HoursPeriod(420, 1320), new HoursPeriod(600, 1080), "smarttravel.com", "meteo_service","slaName"); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_HH:mm"); int responseTime=84; Date timeStamp=format.parse("2012-08-21_1...
1772983_15
class RateLimiterUtils extends CounterAbstractPolicy { public Boolean getFinalresult(String val) throws Exception { List<String> expression = simplifyExpression(val, new LinkedList<String>()); int cnt = 0; Boolean lastoutput = null; String lastlogicalOperation = null; for (String a : expression) { if...
Boolean flag; flag = limiterUtils.getFinalresult("1>2&&3>6"); assertEquals("\"1>2||3>6\" should be false", false, flag); flag = limiterUtils.getFinalresult(" 1 > 3 && 4 > 6 && 5 >7 "); assertEquals("\" 1 > 3 || 4 > 6 || 5 >7 \" should be false", false, flag); flag = limiterUtils.getFinalresul...
1783046_2
class KubernetesDiscoveryService implements DiscoveryService { @Override public Set<String> discoverMembers() { LOGGER.debug("CELLAR KUBERNETES: query pods with labeled with [{}={}]", kubernetesPodLabelKey, kubernetesPodLabelValue); Set<String> members = new HashSet<String>(); try { ...
reset(kubernetesClient); expect(kubernetesClient.pods()).andThrow(new RuntimeException("Test exception")); replay(kubernetesClient); // Should return empty set because exception was caught and logged assertTrue(service.discoverMembers().isEmpty()); } }
1783083_0
class HtmlDimensions { public static String formatSize(String size) { if (size != null) { String incomingSize = size.trim(); if (incomingSize.length() > 0) { char lastChar = incomingSize.charAt(incomingSize.length() - 1); if (Character.isDigit(lastCha...
assertEquals("100px", HtmlDimensions.formatSize("100")); assertEquals("100px", HtmlDimensions.formatSize("100 ")); assertEquals("100px", HtmlDimensions.formatSize(" 100")); assertEquals("100px", HtmlDimensions.formatSize(" 100 ")); assertEquals("t100px", HtmlDimensions.for...
1784501_0
class ColumnType { @Override public boolean equals(Object t) { if (t == null || getClass() != t.getClass()) { return false; } else { ColumnType other = (ColumnType) t; return m_type == other.getType() && Objects.equals(m_typeCode, other.getTypeCode()); } } public ColumnType(fina...
ColumnType typeBool = new ColumnType(-7, "bool"); ColumnType typeBoolean = new ColumnType(16, "boolean"); ColumnType typeBool2 = new ColumnType(-7, "bool"); assertEquals("Expected bool types are equal", typeBool, typeBool2); assertNotSame("Expected bool and boolean are not equal", typeBool, typeB...
1795594_16
class BucketNameValidatorRepo { public static Validator<String> getBucketNameValidator(final String restrictionValue) { if (restrictionValue != null && "extended".equalsIgnoreCase(restrictionValue)) { return extendedValidator; } else if (restrictionValue != null && "dns-compliant".equalsIgnoreCase(rest...
String restriction = "extended"; String largeName = String.format("%0" + 10 + "d", 0).replace("0", "abcdefghij"); assertTrue("expected that a " + largeName.length() + "-character name would be okay", BucketNameValidatorRepo.getBucketNameValidator(restriction) .check(largeName)); largeName = Stri...
1797376_538
class XYSeries extends Series implements Cloneable, Serializable { public void updateByIndex(int index, Number y) { XYDataItem item = getRawDataItem(index); // figure out if we need to iterate through all the y-values boolean iterate = false; double oldY = item.getYValue(); ...
XYSeries s1 = new XYSeries("S1"); s1.add(1.0, 1.1); s1.add(2.0, 2.2); s1.add(3.0, 3.3); assertEquals(1.1, s1.getMinY(), EPSILON); assertEquals(3.3, s1.getMaxY(), EPSILON); s1.updateByIndex(0, -5.0); assertEquals(-5.0, s1.getMinY(), EPSILON); asse...
1810705_22
class SiteSwitcherRequestFilter extends OncePerRequestFilter { public String getServerName() { return serverName; } public SiteSwitcherRequestFilter(); public SiteSwitcherRequestFilter(SiteUrlFactory normalSiteUrlFactory, SiteUrlFactory mobileSiteUrlFactory, SiteUrlFactory tabletSiteUrlFactory, SitePrefere...
device.setDeviceType(DeviceType.MOBILE); SiteSwitcherRequestFilter urlPath = new SiteSwitcherRequestFilter(); MockFilterConfig filterConfig = new MockFilterConfig(); filterConfig.addInitParameter("switcherMode", "urlPath"); filterConfig.addInitParameter("mobilePath", "/mob"); filterConfig.addInitParameter("...
1810897_0
class HomeController { @RequestMapping(value = "states", method = RequestMethod.GET, produces = "application/json") public @ResponseBody List<State> fetchStatesJson() { logger.info("fetching JSON states"); return getStates(); } @RequestMapping(method = RequestMethod.GET) public String home(); @RequestMapping...
List<State> states = controller.fetchStatesJson(); assertNotNull(states); assertEquals(50, states.size()); assertEquals("ALABAMA", states.get(0).getName()); } }
1812602_16
class ObjectNameWithRefFilter implements ObjectFilter { @Override public List<DescribeSObjectResult> filter(List<DescribeSObjectResult> dsrs) { for (DescribeSObjectResult dsr : dsrs) { objectMap.put(dsr.getName(), dsr); } filterObjectAndReferences(objectNames); retu...
DescribeSObjectResult dsrIn = new DescribeSObjectResult(); dsrIn.setName("Object_Name_In__c"); DescribeSObjectResult dsrRef = new DescribeSObjectResult(); dsrRef.setName("RefObject__c"); Field refField = new Field(); refField.setName("RefField__c"); ...
1814028_2
class MockSocket { public static UniversalMockRecorder expectCall() { return StaticConnectionFactory.expectCall(); } protected MockSocket(); public static void reset(); public static List<RequestSocketData> recordedConnections(); public static SocketData emptyResponse(); public static SocketData data(byte[...
expectCall().andReturn(new DefaultSocketData("HTTP/1.0 200 OK\n\nTest".getBytes())); HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(ADDRESS); HttpResponse response = httpclient.execute(httpget); assertEquals("Test", printStream(response.getEntity().getContent())); } }
1839196_7
class FXForm extends AbstractFXForm { public void setSource(T source) { this.source.set(source); } public FXForm(); public FXForm(T source); public FXForm(FactoryProvider editorFactoryProvider); public FXForm(T source, FactoryProvider editorFactoryProvider); public FXForm(Fact...
TestBean testBean = new TestBean(); FXForm fxForm = new FXForm(testBean); Assert.assertEquals(4, fxForm.getElements().size()); fxForm.setSource(null); Assert.assertEquals(0, fxForm.getElements().size()); } }
1860892_0
class TopBar extends JPanel { protected void fireStartTask() { fireEvent(new Event() { @Override public void fire(final Listener listener) { listener.startTask(); } }); } public TopBar(final UIEventsExecutor executor, final TopBarModel model, final ErrorLogScreen errorLogScreen, NewAndNoteworth...
menuOperator.pushStartTaskmenu(); Assert.assertThat(exexex.happened, notNullValue()); } }
1862490_2
class Expressions { public static String resolve(final Properties props, final String expression) { if (expression == null) return null; final StringBuilder builder = new StringBuilder(); final char[] chars = expression.toCharArray(); final int len = chars.length; int state ...
Assert.assertEquals("test property value", Expressions.resolve(PROPERTIES, "${test.property}")); Assert.assertEquals("defaultValue", Expressions.resolve(PROPERTIES, "${invalid.property:defaultValue}")); } }
1862492_0
class OutputStreamHandler extends WriterHandler { public void setWriter(final Writer writer) { synchronized (outputLock) { super.setWriter(writer); final OutputStream oldStream = this.outputStream; outputStream = null; safeFlush(oldStream); safeCl...
handler = new ConsoleHandler(Target.CONSOLE, NO_FORMATTER); handler.setErrorManager(AssertingErrorManager.of()); handler.setWriter(out); handler.setEncoding("UTF-8"); assertThat(handler.getEncoding(), is("UTF-8")); handler.publish(new ExtLogRecord(Level.INFO, "Hello World...
1863627_0
class AssignmentFromZK implements Assignment, IZkChildListener, IZkStateListener, IZkDataListener { @Override public ClusterNode assignClusterNode() { lock.lock(); try { while (!currentlyOwningTask.get()) { taskAcquired.awaitUninterruptibly(); } }...
TaskSetup taskSetup = new TaskSetup(zookeeperAddress); final String clusterName = "test-s4-cluster"; taskSetup.clean(clusterName); taskSetup.setup(clusterName, 10); final CountDownLatch latch = new CountDownLatch(10); for (int i = 0; i < 10; i++) { Runnable ru...
1867246_60
class SAMLProcessingFilter extends AbstractAuthenticationProcessingFilter { public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { try { SAMLMessageContext context = contextProvider.getLocalEntity(request, respons...
Authentication token = new UsernamePasswordAuthenticationToken("user", "pass"); AuthenticationManager manager = createMock(AuthenticationManager.class); processingFiler.setAuthenticationManager(manager); expect(request.getContextPath()).andReturn("/saml"); expect(processor.retr...
1870998_31
class AgeUtils { public static Period getAge(LocalDate birthDate) { return getAge(birthDate, LocalDate.now()); } public static int getFullAge(Date birthDate); public static int getFullAge(Calendar birthDate); public static int getFullAge(LocalDate birthDate); public static int getFullAge(LocalDate fro...
LocalDate now = LocalDate.now(); int currentYear = now.getYear(); LocalDate birthDate = LocalDate.of(2010, 2, 1); Period age = AgeUtils.getAge(birthDate); // P6Y1M21D Assert.assertEquals(currentYear - birthDate.getYear(), age.getYears()); Assert.assertEquals(now.getMonthValue() - birthDate.getMo...
1872106_0
class CustomerManagerEJB { static boolean nameIsValid(String name) { return name.matches("[\\p{L}-]+"); } @TransactionAttribute(TransactionAttributeType.REQUIRED) public void createCustomer(String name); @TransactionAttribute(TransactionAttributeType.NEVER) @SuppressWarnings("unchecked") publi...
assertTrue(CustomerManagerEJB.nameIsValid("Jan")); assertFalse(CustomerManagerEJB.nameIsValid("Jan1")); assertTrue(CustomerManagerEJB.nameIsValid("Jan-Piet")); assertFalse(CustomerManagerEJB.nameIsValid("Jan_Piet")); assertTrue(CustomerManagerEJB.nameIsValid("gefräßig")); } ...
1875775_1
class TaglibReader { public FaceletTaglibType getTaglib() { return taglib; } public TaglibReader(); public HashMap<String, FaceletTaglibTagType> getTagMap(); FaceletTaglibType parseTablib(); InputStream getStream(); public List<FaceletTaglibTagAttributeType> getDefaultAttribute...
TaglibReader taglibReader = new TaglibReader(); Assert.assertNotNull(taglibReader.getTaglib()); } }
1878370_11
class JavaSourceAssert { public static JavaMethod assertMethodExists(File java, CharSequence methodSignature) throws IOException { JavaDocBuilder builder = new JavaDocBuilder(); JavaSource src = builder.addSource(java); JavaClass jc = getClassName(src, java); Map<String, JavaMethod...
File java = getSampleDataJavaSource("SampleInterface.java"); JavaSourceAssert.assertMethodExists(java, "public void notexists()"); } }
1886360_35
class Library { public static int[] listTotients(int n) { if (n < 0) throw new IllegalArgumentException("Negative array size"); int[] result = new int[n + 1]; for (int i = 0; i <= n; i++) result[i] = i; for (int i = 2; i <= n; i++) { if (result[i] == i) { // i is prime for (int j = i; j <= n;...
int[] totients = Library.listTotients(1000); for (int i = 1; i < totients.length; i++) assertEquals(Library.totient(i), totients[i]); } }
1889681_12
class MantisConnector { @Nonnull Collection<FilterData> getFilters(@Nonnull ProjectData project) throws RemoteException { return Arrays.asList(connectPortType.mc_filter_get(USERNAME, PASSWORD, project.getId())); } MantisConnector(); @Nonnull Collection<ProjectData> getProjects(); @N...
MantisConnector connector = new MantisConnector(); List<ProjectData> filteredProjects = getFilteredProjects(connector); for (ProjectData project : filteredProjects) { Collection<FilterData> filters = connector.getFilters(project); assertTrue( filter...
1894664_13
class SearchTemplate extends AbstractYammerOperations implements SearchOperations { public SearchResults search(String searchString){ return search(searchString, 1); } public SearchTemplate(RestTemplate restTemplate); public SearchResults search(String searchString, int page); public SearchResults search(Str...
mockServer.expect(requestTo("https://www.yammer.com/api/v1/search.json?search=foo&page=2&number_per_page=20")).andExpect(method(GET)) .andRespond(withSuccess(jsonResource("testdata/yammer-search-results"), APPLICATION_JSON)); SearchResults searchResults = yammerTemplate.searchOperations().search("foo",2); asser...
1905463_3
class MockingPropertyResolver implements PredefinedVariableResolver.NewVariableEncounteredListener { public Object getValue(Object target, Object property) throws GenericElEvaluationException, PropertyNotFoundException { return this.getValue(target, property, getTypeOfCollectionOrBean(target, p...
assertThat(resolver.getValue(new Object[0], 456) // SUPPRESS CHECKSTYLE , is(instanceOf(MockObjectOfUnknownType.class))); } }
1913648_0
class SyncDB { public Map<String,Integer> getMods () { return new HashMap<String,Integer>(_mods); } protected SyncDB(Platform platform); public int version(); public boolean hasUnsyncedChanges(); public Map<String,String> getDelta(); public void noteSync(int version, Map<String,I...
Protocol.Session session = testSession(); TestDB one = new TestDB(), two = new TestDB(); one.trueBool.update(true); one.maxInt.update(42); one.maxLong.update(400L); one.serverString.update("foo"); one.unionSet.add("one"); one.unionSet.add("two"); ...
1925457_60
class Strings { public static String getDegreesMinutesSeconds(double decimaldegrees, boolean isLatitude) { String cardinality = (decimaldegrees<0) ? "S":"N"; if(!isLatitude){ cardinality = (decimaldegrees<0) ? "W":"E"; } //Remove negative sign decimaldegrees = ...
double lat = 11.812244d; String expected = "11° 48' 44.0784\" N"; String actual = Strings.getDegreesMinutesSeconds(lat, true); assertThat("Degree Decimals converted to Degree Minute Seconds", actual, is(expected)); } }
1931685_3
class Route { public StompletActivator match(String destination) { Matcher routeMatcher = this.regexp.matcher( destination ); if (routeMatcher.matches()) { Map<String, String> matches = new HashMap<String, String>(); for (int i = 0; i < this.segmentNames.length; ++i) { ...
Route route = new Route( "/stocks/:exchange/:stock", null ); StompletActivator match = route.match( "/stocks/NASDAQ/AAPL" ); assertNotNull( match ); assertEquals( "NASDAQ", match.get( "exchange" ) ); assertEquals( "AAPL", match.get( "stock" ) ); match = ...
1933490_4
class World { public String getName() { return name; } public World( String name, int moons ); public World(); public int getMoons(); @Override public String toString(); public void addRocketRouteTo( World otherWorld ); public boolean canBeReachedFrom( World otherWorld )...
World w = new World(); assertNull(w.getName()); } }
1944249_13
class Editor { public void setText(@Nonnull String text) { Check.isMainThread(); onTextChanged(EditorState.create(text, text.length())); } @Inject public Editor(@Nonnull Application application, @Nonnull SharedPreferences preferences, @Nonnull Engine engine); public void init(); ...
EditorState viewState = setTextAndGet("test"); Assert.assertEquals("test", viewState.getTextString()); Assert.assertEquals(4, viewState.selection); viewState = setTextAndGet("testtest"); Assert.assertEquals("testtest", viewState.getTextString()); Assert.assertEquals(8, ...
1946637_20
class Decoder { public static String path(final CharSequence path) { return decode(path, false); } public static String query(final CharSequence query); public static String decode(final CharSequence path, final boolean query); } class DecoderTest { @Test public void pathQuotationMark() ...
assertEquals("/foo\"bar", Decoder.path("/foo%22bar")); assertEquals("/foo\"bar", Decoder.path("/foo\"bar")); } }
1951088_0
class PhotosetsInterface { public Photoset getInfo(String photosetId) throws FlickrException, IOException, JSONException { List<Parameter> parameters = new ArrayList<Parameter>(); parameters.add(new Parameter("method", METHOD_GET_INFO)); boolean signed = OAuthUtils.hasSigned(); if (signed) { parameters...
Photoset photoset = f.getPhotosetsInterface().getInfo(PHOTOSET_ID); assertNotNull(photoset); assertEquals(PHOTOSET_ID, photoset.getId()); } }
1953808_0
class WorldMap implements Updatable<PositionUpdate<T>> { public Collection<T> getAllAt(WorldPosition position) { Collection<T> objects = positions.get(position); if (objects == null) { return Collections.emptyList(); } else { return Collections.unmodifiableCollection(objects); } } public void put(T o...
WorldMap<String> map = new WorldMap<>(); Collection<String> objects = map.getAllAt(new WorldPosition(62135, -18635)); assertNotNull(objects); assertTrue(objects.isEmpty()); } }
1956196_2
class DateDisplay { int getStyle(String style) { int formatType = -1; if("long".equals(style)) { formatType = DateFormat.LONG; } else if("medium".equals(style)) { formatType = DateFormat.MEDIUM; } else if("full".equals(style)) { for...
DateDisplay component = new DateDisplay(); assertEquals(component.getStyle("long"), DateFormat.LONG); assertEquals(component.getStyle("short"), DateFormat.SHORT); assertEquals(component.getStyle("full"), DateFormat.FULL); assertEquals(component.getStyle("medium"), DateFormat.MEDIUM)...
1961837_10
class RequestStrategyImplAnyInteresting implements RequestStrategy { @Override public Piece choosePiece(BitSet interesting, Piece[] pieces) { List<Piece> onlyInterestingPieces = new ArrayList<Piece>(); for (Piece p : pieces) { if (interesting.get(p.getIndex())) onlyInterestingPieces.add(p); } ...
Piece actual = myRequestStrategy.choosePiece(new BitSet(), myPieces); Assert.assertNull(actual); } }
1970932_193
class OptionHelper { public static String substVars(String val, PropertyContainer pc1) { return substVars(val, pc1, null); } public static Object instantiateByClassName(String className, Class<?> superClass, Context context); public static Object instantiateBy...
String noSubst = "hello world"; String result = OptionHelper.substVars(noSubst, context); assertEquals(noSubst, result); } }
1971346_2
class MessagePackGenerator extends GeneratorBase { @Override public void close() throws IOException { try { flush(); } finally { if (isEnabled(Feature.AUTO_CLOSE_TARGET)) { MessagePacker messagePacker = getMessagePacker(); ...
File tempFile = createTempFile(); OutputStream out = new FileOutputStream(tempFile); MessagePackFactory messagePackFactory = new MessagePackFactory(); ObjectMapper objectMapper = new ObjectMapper(messagePackFactory); objectMapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET,...
1971919_26
class ReplicationSink { public void replicateEntries(HLog.Entry[] entries) throws IOException { if (entries.length == 0) { return; } // Very simple optimization where we batch sequences of rows going // to the same table. try { long totalReplicated = 0; // Map of table => ...
HLog.Entry[] entries = new HLog.Entry[3]; for(int i = 0; i < 3; i++) { entries[i] = createEntry(TABLE_NAME1, i, KeyValue.Type.Put); } SINK.replicateEntries(entries); entries = new HLog.Entry[3]; entries[0] = createEntry(TABLE_NAME1, 0, KeyValue.Type.DeleteColumn); entries[1] = createE...
1980382_73
class FsEntryHBaseCommon { public static byte typeVal(Object o) { if (o instanceof Long || o instanceof Integer) { return LONG; } else if (o instanceof String) { return STRING; } else if (o instanceof Date) { return DATE; } else if (o instanceof Map || o instanceof List)...
assertEquals(DATE, typeVal(new Date())); } }
1981819_4
class CategoryStringGenerator { public static List<String> getPostgresCategoryString(String searchString, Map<String, String> mapPrefix, String prefixSplit ) { List<String> finalList = new ArrayList<String>(); if (searchString == null || !(searchString.trim().length() > 0)) { finalL...
List<String> result = CategoryStringGenerator.getPostgresCategoryString(SINGLE_CAT, Collections.EMPTY_MAP, null ); assertEquals( result.size(), 1 ); assertEquals(result.get( 0 ), SINGLE_CAT_RESULT); } }
1982584_1
class PGNUtils { public static String toNormalizedSAN(final String pChaine) { assert pChaine != null; final StringBuilder res = new StringBuilder(pChaine); // Le marqueur 'P' pour les pions est possible avec PGN, pas avec SAN... if (res.charAt(0) == 'P') { res.deleteCharAt(0); } ...
assertEquals("e3", toNormalizedSAN("e3")); assertEquals("e3", toNormalizedSAN("Pe3")); assertEquals("a8Q", toNormalizedSAN("a8Q")); assertEquals("a8Q", toNormalizedSAN("a8=Q")); assertEquals("Rd6", toNormalizedSAN("Rd6")); assertEquals("Rd6", toNormalizedSAN("Rd6?")); assertEquals("Rd6", toN...
1984080_19
class RoadSegment extends DefaultWeightedEdge implements Iterable<Vehicle> { public void outFlow(double dt, double simulationTime, long iterationCount) { updateSignalPointsBeforeOutflow(simulationTime); for (final LaneSegment laneSegment : laneSegments) { laneSegment.outFlow(dt, simulat...
RoadSegment.resetNextId(); Vehicle.resetNextId(); final int laneCount = 1; final RoadSegment r0 = new RoadSegment(1000.0, laneCount); final RoadSegment r1 = new RoadSegment(5000.0, laneCount); // join r0 and r1 so vehicles move from r0 to r1 Link.addJoin(r0, r1);...
2003641_100
class SpecFilter { public OpenAPI filter(OpenAPI openAPI, OpenAPISpecFilter filter, Map<String, List<String>> params, Map<String, String> cookies, Map<String, List<String>> headers) { OpenAPI filteredOpenAPI = filterOpenAPI(filter, openAPI, params, cookies, headers); if (filteredOpenAPI == null) { ...
final OpenAPI openAPI = getOpenAPI(RESOURCE_DEPRECATED_OPERATIONS); final RemoveUnreferencedDefinitionsFilter remover = new RemoveUnreferencedDefinitionsFilter(); final OpenAPI filtered = new SpecFilter().filter(openAPI, remover, null, null, null); Operation operation = filtered.getPath...
2008119_4
class EntityResource extends ServerResource { @Get("json") public Representation getEntity() { // extract necessary information from the context CollabinateReader reader = (CollabinateReader)getContext() .getAttributes().get("collabinateReader"); String tenantId = getAttribute("tenantId"); String entity...
Tag etag = get().getEntity().getTag(); Request request = getRequest(Method.DELETE, null); Conditions conditions = new Conditions(); conditions.getMatch().add(etag); request.setConditions(conditions); assertEquals(Status.SUCCESS_NO_CONTENT, getResponse(request).getStatus()); } }
2009311_17
class ReadOnlyInterceptor implements Serializable { @AroundInvoke public Object markReadOnly(InvocationContext ic) throws Exception { try { return ic.proceed(); } finally { utTransactionHolder.getUserTransaction().setRollbackOnly(); } } public ReadOnlyInterceptor(); public ReadOnly...
transactionFactory.expectNoTransaction(); transactionFactory.expectBeginTransaction(); transactionFactory.expectSetRollbackOnly(); transactionFactory.expectRollbackTransaction(); transactionFactory.replay(); try { // a mock that expects two proceed calls and returns the read only interc...
2009635_0
class PkgInt { public int unpack(int i) { return ( (this.data[i>>this.indexShift] >> ((i&this.shiftMask)<<this.bitShift)) & this.unitMask ); } public PkgInt( int indexShift, int shiftMask, int bitShift, int unitMa...
int[] data = new int[] { PkgInt.pack4bits(0, 1, 2, 3, 4, 5, 6, 7), PkgInt.pack4bits(8, 9, 10, 11, 12, 13, 14, 15) }; PkgInt pkg = new PkgInt( PkgInt.INDEX_SHIFT_4BITS, PkgInt.SHIFT_MASK_4BITS, PkgInt.BIT_SHI...
2011647_130
class ATransformable3D implements IGraphNodeMember { public Quaternion getOrientation(Quaternion quat) { quat.setAll(mOrientation); return quat; } public ATransformable3D(); protected void markModelMatrixDirty(); public boolean onRecalculateModelMatrix(Matrix4 parentMatrix); ...
Quaternion result = transformable.getOrientation(); assertEquals(1, result.w, 1e-10); assertEquals(0, result.x, 1e-10); assertEquals(0, result.y, 1e-10); assertEquals(0, result.z, 1e-10); } }
2023409_11
class LogRepositoryReadJdbc implements LogRepositoryRead { @Override public void getStatementsGroupByFilledSQL(final LogSearchCriteria searchCriteria, final ResultSetAnalyzer analyzer) { final StringBuilder sql = new StringBuilder( "select * from (select min(id) as ID, state...
final List<StatementFullyExecutedLog> logs = insert3Logs(); final StatementFullyExecutedLog log1 = logs.get(0); repositoryUpdate.addTxCompletionLog(new TxCompleteLog(log1.getConnectionUuid(), System.currentTimeMillis(), TxCompletionType.COMMIT, 321, "mythread", null)); f...
2036666_0
class DefaultCouchManager implements LocalCouch { public static int findFreePort() throws IOException { ServerSocket server = new ServerSocket(0); int port = server.getLocalPort(); server.close(); return port; } public void setCouchDownloader(CouchDownloader couchDownloader); p...
int port = DefaultCouchManager.findFreePort(); System.out.println("Port: " + port); assertTrue(port > 0); } }
2037955_0
class JsonSerDe extends AbstractSerDe { @Override public Object deserialize(Writable w) throws SerDeException { Text rowText = (Text) w; deserializedDataSize = rowText.getBytes().length; // Try parsing row into JSON object Object jObj = null; try { ...
JsonSerDe instance = new JsonSerDe(); initialize(instance); System.out.println("deserialize"); Writable w = new Text("{\"one\":true,\"three\":[\"red\",\"yellow\",\"orange\"],\"two\":19.5,\"four\":\"poop\"}"); JSONObject result = (JSONObject) instance.deserialize(w); ...
2038852_35
class HostValidator implements ResourceValidator<Host> { @Override public ValidatorResult validate(Host host, Object ctx) { return validator.validate(host, ctx); } public HostValidator(); @Override public Validator<Host> getValidator(); private HostValidator hv; private Host hos...
host.setClusterId(null); res = hv.validate(host, POST); assertFalse(resultMessage(res, POST), res.passedValidation()); } }
2044534_5
class AbstractMessageHandler implements CommunicationsHandler { private boolean write(ByteBuffer[] buffers) { try { long written = handler.getChannel().write(buffers); if (getLog().isTraceEnabled()) { getLog().trace(format("%s bytes written", written)); }...
final NoSecurityImpl wireSecurity = new NoSecurityImpl(); MsgHandler msgHandler = new MsgHandler(wireSecurity); SocketChannelHandler handler = mock(SocketChannelHandler.class); SocketChannel channel = mock(SocketChannel.class); final List<SerializedMsg> msgs = new ArrayList<Seri...
2046220_5
class CodeGenParser { public DBDatabase loadDbModel() { DBDatabase db = new InMemoryDatabase(); try { con = openJDBCConnection(config); populateDatabase(db); } catch (SQLException e) { throw new RuntimeException("Unable to read database m...
final DBDatabase db = parser.loadDbModel(); final DBTable departments = db.getTable("DEPARTMENTS"); final DBTable employees = db.getTable("EMPLOYEES"); assertNotNull("Expected DEPARTMENTS table.", departments); assertNotNull("Expected EMPLOYEES table.", employees); final Lis...
2055952_0
class Datapoint { public String toString() { return "X=" + mX + ", Y=" + mY; } public Datapoint(); public Datapoint(long x, long y); } class DatapointTest { @Test public void toStringReturnsValue() throws Exception {
Datapoint p1 = new Datapoint(); Datapoint p2 = new Datapoint(12, 45); String s1 = p1.toString(); String s2 = p2.toString(); assertTrue(p1.mX == 0); assertTrue(p1.mY == 0); assertTrue(s1.equals("X=" + p1.mX + ", Y=" + p1.mY)); assertTrue(s2.equals("X=" + p2.mX + ", Y=" + p2.mY)); } }
2058044_1
class TypeConverter { public static Value asResource(java.net.URI uri) { return Values.literal(uri.toString()); } public static Value asLiteral(Object o); public static Value asLiteral(Date date); public static Value asLiteral(java.net.URI uri); public static Value asLiteral(Integer i); public static Value a...
URI b = null; try { b = new URI("http://stardog.com"); } catch (URISyntaxException e) { // TODO Auto-generated catch block e.printStackTrace(); } Value resource = TypeConverter.asResource(b); assertNotNull(resource); } }
2064018_16
class Annotate { public static List<Annotation> readLabelFile(final Reader fileReader) throws IOException { List<Annotation> annotations = new ArrayList<Annotation>(); BufferedReader reader = new BufferedReader(fileReader); String line; while ((line = reader.readLine())...
URL url = AnnotateTest.class.getResource("/test-labels.txt"); Reader reader = new InputStreamReader(url.openStream()); List<Annotation> annotations = Annotate.readLabelFile(reader); Annotation a1 = annotations.get(0); assertEquals(new CIDR("0.0.0.0/8"), a1.getCidr()); as...
2073724_0
class BWPalette extends ColorPalette { @Override public int getColorInt(float intensity) { return (intensity > 0.5) ? 0xffffffff: 0xff000000; } @Override public int[] getColorsInt(); } class BWPaletteTest { @Test public void getColorInt() throws Exception {
BWPalette bwp = new BWPalette(); //return black for < 0.5, white otherwise assertEquals(0xff000000, bwp.getColorInt(0.1f)); assertEquals(0xffffffff, bwp.getColorInt(0.9f)); } }
2080454_21
class SongTo extends TrackTo implements AlbumAndSongInfo { @Override public boolean equals(final Object other) { if (!(other instanceof SongTo)) return false; SongTo castOther = (SongTo) other; return new EqualsBuilder().appendSuper(super.equals(other)) .append(getType(), castOther.getType()) .appen...
Date dateAdded = new Date(); Date dateModified = new Date(); Date skipDate = new Date(); SongTo song1 = new SongTo("Invisible", "Rainbow in the Dark", "Dio", "Dio", 1983, "Dio", "Rock", false, dateAdded, dateModified, new RatingTo(100), 100, skipDate, 0, true, new RatingTo(100), false, 7, 1, 100); ...
2088736_251
class InjectionAnnotations extends AbstractAnnotations implements FluentLabelProvider { @Override public By buildBy() { if (mobileElement) { return defaultElementByBuilder.buildBy(); } By fieldBy = fieldAnnotations.buildBy(); By classBy = classAnnotations.buildBy(); ...
Field accessibilityField = this.getClass().getDeclaredField("iosAccessibilityId"); InjectionAnnotations annotations = new InjectionAnnotations(accessibilityField, getIosCapablities()); By by = annotations.buildBy(); assertThat(by).isInstanceOf(ContentMappedBy.class) .isEq...
2090979_0
class TcpConnectionFactoryFactoryBean extends AbstractFactoryBean<AbstractConnectionFactory> implements Lifecycle, BeanNameAware, ApplicationEventPublisherAware, ApplicationContextAware { public void setHost(String host) { Assert.notNull(host, "Host may not be null"); this.host = host; } public TcpConnectionF...
TcpConnectionFactoryFactoryBean fb = new TcpConnectionFactoryFactoryBean(); fb.setHost("foo"); fb.setBeanFactory(mock(BeanFactory.class)); fb.afterPropertiesSet(); // INT-3578 IllegalArgumentException on 'readDelay' assertThat(TestUtils.getPropertyValue(fb.getObject(), "readDelay")).isEqualTo(100L); } }
2101910_9
class DbImpl implements DB { @Override public Snapshot getSnapshot() { checkBackgroundException(); mutex.lock(); try { return new SnapshotImpl(versions.getCurrent(), versions.getLastSequence()); } finally { mutex.unlock(); } } ...
DbStringWrapper db = new DbStringWrapper(new Options(), databaseDir); // Try with both a short key and a long key for (int i = 0; i < 2; i++) { String key = (i == 0) ? "foo" : longString(200, 'x'); db.put(key, "v1"); Snapshot s1 = db.getSnapshot(); ...
2111687_3
class LessCompiler { public String compile(URL sourceURL) throws UnableToCompleteException { // TODO: this won't work if the .less file is in a jar... LessCompilerContext context = new LessCompilerContext(logger, sourceURL.getFile()); try { Function<LessCompilerContext, String> compiler = LessCom...
String output = compile("nested-imports.less"); assertThat(output, not(equalTo("undefined"))); } }
2112231_3
class BracketSettingsReader { public static void readInto(SettingsMap settingsMap, String rawSettings) { String[] settings = rawSettings.split(";"); for (String setting : settings) { String[] settingParts = setting.split("=", 2); String settingName = settingParts...
SettingsMap settingsMap = new SimpleSettingsMap("Test", false); BracketSettingsReader.readInto(settingsMap, "Author=Some Author;Description=Some description"); assertEquals("Some Author", settingsMap.getSetting(WorldStandardValues.AUTHOR)); assertEquals("Some description", settingsMap....