id
stringlengths
7
14
source
stringlengths
135
41.2k
target
stringlengths
36
20.4k
28822832_6
class ConfigFilesRetrieverImpl implements ConfigFilesRetriever { static boolean isRelevantConfiguration(final String entryName, final String parentName, ExtendedSlingSettingsService slingSettings) { if (!entryName.endsWith(".yaml") && !entryName.equals("config") /* name 'config' without .yaml allowed for b...
Set<String> currentRunmodes = new HashSet<String>( Arrays.asList("samplecontent", "author", "netcentric", "crx3tar", "crx2", "local")); slingSettings = new ExtendedSlingSettingsServiceImpl(currentRunmodes); // testing 'or' combinations with Assert.assertTrue((ConfigFilesR...
28858344_28
class HexUtil { public static String convertStringToHexString(String data) { return conventBytesToHexString(data.getBytes()); } private HexUtil(); public static String conventBytesToHexString(byte[] data); public static String convertBytesToHexString(byte[] data, int offset, ...
String res = HexUtil.convertStringToHexString("hello world"); assertEquals("68656c6c6f20776f726c64", res); } }
28874374_2
class DeviceUtils { public static String getDeviceID() { Context context = Appaloosa.getApplicationContext(); if(deviceHasPhoneCapabilities(context)) { return getImei(); } else { return getAndroidId(context); } } private static boolean deviceHasPhone...
mShadowTelephonyManager.setPhoneType(TelephonyManager.PHONE_TYPE_GSM); mShadowTelephonyManager.setDeviceId(IMEI); mShadowApplication.grantPermissions(Manifest.permission.READ_PHONE_STATE); assertEquals(IMEI, DeviceUtils.getDeviceID()); } }
28892813_1
class ImageParser { public static int parseElixir(BufferedImage image) throws BotBadBaseException { return parseElixirFromBinary(imageToBinary(image)); } static boolean hasDE(BufferedImage image); public static int parseGold(BufferedImage image); static int parseGoldFromBinary(BufferedImage binary); static in...
int fail = 0; for (int i = 0; i < imageNames.length; i++) { String s = imageNames[i]; BufferedImage image = ImageIO.read(TestImageParser.class.getResourceAsStream(imageLocation + s)); int elixir = ImageParser.parseElixir(image); try { Assert.assertEquals(expectedElixir[i], elixir); } catch...
28900548_16
class FileUtils { @SuppressFBWarnings("OBL_UNSATISFIED_OBLIGATION_EXCEPTION_EDGE") public static void copy(File src, File dest) throws IOException { if (dest.delete()) { LOGGER.debug("Removed " + dest.getPath() + " during copying"); } InputStream input = null; FileOu...
public void copy() throws IOException { File a = File.createTempFile("file-1", "tmp"); File b = File.createTempFile("file-2", "tmp"); Assert.assertTrue(a.isFile()); Assert.assertTrue(b.isFile()); try { FileUtils.write(a, "Hello world".getBytes("UTF-8")); ...
28901545_0
class DateUtils { public static String transform(Date sourceDate, DateFormat format, TimeZone sourceTimeZone, TimeZone targetTimeZone) { Long targetTime = sourceDate.getTime() - sourceTimeZone.getRawOffset() + targetTimeZone.getRawOffset(); return DateUtils.getTime(new Date(targetTime), format); } public st...
Date startDate = new Date("07/16/2013 00:00:00"); String transformedStartDate = DateUtils.transform(startDate, dateFormat, sourceTimeZone, targetTimeZone); assertEquals(transformedStartDate, "07/16/2013 04:00:00 AM"); Date endDate = new Date("07/16/2013 23:59:59"); String transformedEndDate = DateUtils.transf...
28923365_4
class KmsTextEncryptor implements TextEncryptor { @Override public String decrypt(final String encryptedText) { if (encryptedText == null || encryptedText.isEmpty()) { return EMPTY_STRING; } else { final EncryptedToken token = EncryptedToken.parse(encryptedText); ...
assertThat(textEncryptor.decrypt(null)).isEqualTo(""); } }
28963937_2
class FramedGraph implements AutoCloseable { @SuppressWarnings("unchecked") public <V> FramedGraphTraversal<V> V(Class<V> clazz) { return new FramedGraphTraversal(traversal.V(), this).labels(clazz, P.within(registry.labels(clazz))); } public FramedGraph(Graph graph, Package pakkage); pub...
Person p = graph.v(alice.id()); assertEquals(alice.id(), p.vertex().id()); assertEquals("alice", p.getName()); } }
28969897_4
class DeployMessage implements BrokerMessage { public String toString() { String serializedMessage = null; try { Gson gson = GsonParserBuilder.getInstance(); serializedMessage = gson.toJson(this); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return seriali...
DeployMessageType type = DeployMessageType.REQUEST_TO_INSTALL_PART; byte[] bytearray = new byte[] { 4, 4, 56, 35, 64, (byte) 0xfe6, 4 }; App uapp = new App(); uapp.setAppId("10"); uapp.setApplicationProfile("ciao"); uapp.setDescription("descrizione app"); uapp.setMultipart(true); uapp.setName("nome")...
28970369_10
class MessageBirdClient { public MessageResponse sendMessage(final Message message) throws UnauthorizedException, GeneralException { return messageBirdService.sendPayLoad(MESSAGESPATH, message, MessageResponse.class); } public MessageBirdClient(final MessageBirdService messageBirdService); pu...
final String body = "Body test message Über € " + messageBirdMSISDN; final MessageResponse mr = messageBirdClient.sendMessage("originator", body, Collections.singletonList(messageBirdMSISDN)); assertNotNull(mr.getId()); // Deleting of a message is not yet supported in test mode ...
28972188_9
class KeycloakOauthPolicy extends AbstractMappedPolicy<KeycloakOauthConfigBean> { @Override protected void doApply(final ApiRequest request, final IPolicyContext context, final KeycloakOauthConfigBean config, final IPolicyChain<ApiRequest> chain) { final String rawToken = getRawAuthToken(r...
ForwardAuthInfo authInfo = new ForwardAuthInfo(); authInfo.setHeaders("X-TEST"); authInfo.setField("email"); config.getForwardAuthInfo().add(authInfo); token.setEmail("apiman@apiman.io"); String encoded = generateAndSerializeToken(); apiRequest.getHeaders().put("...
28979951_107
class DatastoreAccess implements AutoCloseable { public synchronized <T extends DataObject> boolean putSynchronous( final InstanceIdentifier<T> path, final T data, final LogicalDatastoreType logicalDatastoreType) { LOG.debug("Put synchronous {}", path); try { put(path, data,...
WriteTransaction transaction = mock(WriteTransaction.class); doReturn(CommitInfo.emptyFluentFuture()).when(transaction).commit(); InstanceIdentifier identifier = mock(InstanceIdentifier.class); DataObject dataObject = mock(DataObject.class); when(transactionChain.newWriteOnlyTra...
28991592_45
class EntryList implements Iterable<SimpleImmutableEntry<K, V>> { public int size() { return this.entries.size(); } public EntryList(); public EntryList( final int initialCapacity ); public EntryList( final Collection<? extends SimpleImmutableEntry<K, V>> c ); public EntryList( fin...
SimpleImmutableEntry<String, String> entry = new SimpleImmutableEntry<>( "key", "value" ); List<SimpleImmutableEntry<String, String>> collection = Arrays.asList( entry ); EntryList<String, String> list = new ImmutableEntryList<>( collection ); Assert.assertEquals( 1, list.size() ); }...
28992330_18
class PercentEscaper extends UnicodeEscaper { @Override public String escape(String s) { int slen = s.length(); for (int index = 0; index < slen; index++) { char c = s.charAt(index); if (c >= safeOctets.length || !safeOctets[c]) { return escapeSlow(s, index); } } return s;...
PercentEscaper escaper = new PercentEscaper(PercentEscaper.SAFE_PLUS_RESERVED_CHARS_URLENCODER, false); String actual = escaper.escape("Hello there"); Assert.assertEquals("Hello%20there", actual); } }
29008657_5
class HttpHeaderStatisticInjector implements WriterInterceptor { public String serializeStatistics(Statistics statistics) { JsonObjectBuilder stats = Json.createObjectBuilder(); stats.add("pipelineName", statistics.getPipelineName()); final String handlerName = statistics.getRejectedExecuti...
Statistics stats = new Statistics("test", 0, 1, 2, 3, 4, 5, 6, 7, 8, "duke", 9); String result = this.cut.serializeStatistics(stats); assertNotNull(result); } }
29027682_0
class VaultTokenRenewalAutoConfiguration { @Scheduled(fixedRateString="${vault.token.renew.rate:60000}") // <-- Default to renew token every 60 seconds public void refreshVaultToken() { try { logger.info("Renewing Vault token " + obscuredToken + " for " + renewTTL + " milliseconds."); rest.postForObject(ref...
this.configClientProperties.setUri(new String[] { "https://foobar" }); given(rest.postForObject(anyString(), any(HttpEntity.class), any())).willReturn("foo"); ReflectionTestUtils.setField(config, "rest", this.rest); await().atMost(Duration.FIVE_SECONDS).untilAsserted(() -> { verify(config, atLeast(4)).refre...
29056247_1
class TVGapsUtil { public static Map<String, List<Pair<Integer>>> getTVGaps(Future<H2PersistenceManager> dao) throws Exception { String allShowsQuery = "mediatype='tv' order by title, season, episode"; Collection<MediaFile> files = dao.get().getMediaFileDAO().query(allShowsQuery); return ge...
List<MediaFile> files = new ArrayList<>(); files.add(newMediaFile("Series1", 1, 1)); files.add(newMediaFile("Series1", 1, 2)); files.add(newMediaFile("Series1", 1, 5)); files.add(newMediaFile("Series1", 1, 6)); files.add(newMediaFile("Series1", 1, 8)); files.add(n...
29060759_6
class DynamicRoundRobinLoadBalancer extends RoundRobinLoadBalancer { @Override protected synchronized Processor chooseProcessor(List<Processor> processors, Exchange exchange) { Processor answer = null; Processor defaultSelection = super.chooseProcessor(processors, exchange); Determinis...
ProcessorHolder processorHolder1 = new ProcessorHolder(); processorHolder1.setProcessor(Mockito.mock(Processor.class)); ProcessorHolder processorHolder2 = new ProcessorHolder(); processorHolder2.setProcessor(Mockito.mock(Processor.class)); RouteStatistics stat1 = new RouteStati...
29064349_8
class JavafxMainWindowView extends JavafxView<MainWindowPresenter, MainWindowDisplay> implements MainWindowView { @Override public void setWindowTitle(final String windowTitle) { stage.setTitle(windowTitle); } public JavafxMainWindowView(final Stage stage, final GuiTaskRunner task...
final String expected = "meh"; view.setWindowTitle(expected); final String actual = stage.getTitle(); assertThat(actual).isEqualTo(expected); } }
29089479_3
class MonetaServlet extends HttpServlet { @Override public void init(ServletConfig config) throws ServletException { super.init(config); MonetaEnvironment.setConfiguration(new MonetaConfiguration()); if (config == null) return; String IgnoredContextPathNodesStr = config.getInitParameter(CONFIG_IGNORED...
MockServletConfig config = new MockServletConfig(); servlet.init(config); Assert.assertTrue(MonetaEnvironment.getConfiguration().getIgnoredContextPathNodes()==null); config.getInitParmMap().put(MonetaServlet.CONFIG_IGNORED_CONTEXT_PATH_NODES, ""); servlet.init(config); Assert.assertTrue(MonetaEnvi...
29128975_17
class ParseObservable { @NonNull @CheckReturnValue public static Single<File> getFile(@NonNull final ParseFile file) { return RxTask.single(() -> file.getFileInBackground()); } @NonNull @CheckReturnValue public static Observable<R> find(@NonNull final ParseQuery<R> query); @NonNull @Ch...
rx.parse2.ParseObservable.getFile(mocker(ParseFile.class) .when(it -> it.getFileInBackground()) .thenReturn(it -> Task.forResult(new File("/"))) .mock()) .test() .assertNoErrors() .assertComplete(); }...
29140204_6
class FtpBuildProcessAdapter extends SyncBuildProcessAdapter { @Override public BuildFinishedStatus runProcess() { FTPClient clientToDisconnect = null; try { final URL targetUrl = new URL(myTarget); final String host = targetUrl.getHost(); final int port = targetUrl.getPort(); fina...
myRunnerParameters.put(FTPRunnerConstants.PARAM_TRANSFER_MODE, FTPRunnerConstants.TRANSFER_MODE_BINARY); File sourceXml = new File("src/test/resources/data.xml"); if (!sourceXml.exists()) { sourceXml = new File("deploy-runner-agent/src/test/resources/data.xml"); } Map<File, String> map = new...
29201308_0
class BinaryData extends InputStream { public void close() throws IOException { // force nothing more to be read from the in-memory data, let the garbage collected free up its memory, // but avoid NPEs by setting inMemoryData to a small zero-byte array. inMemoryData = new byte[0]; i...
// because our tests use ByteArrayInputStream, close has no effect on it. // But close does have an effect on our in-memory data - closing the stream closes reads to the in-memory data BinaryData binaryData = new BinaryData(buildByteArray("123"), buildInputStream("")); // show we can st...
29228340_0
class SphinxManager { public static String getCommand(String string){ int index = string.indexOf("invocabot"); // If "invocabot" is not in string. if (index == -1) return null; // If "invocabot" is last word in string. String words[] = string.split(" "); if (words[words.le...
setUp(); //ARRANGE String input = "hi my name is julio schedule an appointment with chris at twelve p m tomorrow"; String desiredOutput = null; //ACT String output = SphinxManager.getCommand(input); //ASSERT assertEquals(desiredOutput, output); tearDown(); } }
29235999_0
class DConnectServiceSpec { public Swagger findProfileSpec(final String profileName) { if (profileName == null) { return null; } synchronized (mProfileSpecs) { return mProfileSpecs.get(profileName.toLowerCase()); } } public DConnectServiceSpec(Devic...
DevicePluginContext pluginContext = Mockito.mock(DevicePluginContext.class); String jsonString = FileLoader.readString("testProfile.json"); DConnectServiceSpec spec = new DConnectServiceSpec(pluginContext); spec.addProfileSpec("testProfile", jsonString); Operation operation = ...
29241103_0
class PluginUrlUtils { public static boolean isHostArte(String host) { return host.equals("www.arte.tv"); } public static String toPluginUrlArte(Uri playUri); public static String toPluginUrlTwitch(Uri playUri); } class PluginUrlUtilsTest { @Test public void isHostArte() throws Exce...
assertTrue(PluginUrlUtils.isHostArte("www.arte.tv")); } }
29248824_25
class OracleRdbmsSpecifics implements RdbmsSpecifics { public DataRdbms getData(final Object object) { if (object instanceof Timestamp) { final DateFormat df = new SimpleDateFormat(TIMESTAMP_PATTERN); final String dateString = df.format(object); return new GenericDataRdbms("to_timestamp('", dateString, "',...
final DataRdbms data = instance.getData("valeur espace"); Assert.assertEquals(data.getValue(), "valeur espace"); Assert.assertEquals(data.getParameter(), "'valeur espace'"); } }
29251742_4
class UrlUtil { public static String buildUrlWithQueryParams(@NonNull Logger logger, @NonNull String baseUrl, @NonNull Map<String, String> queryParams) { final Uri.Builder uriBuilder = Uri.parse(baseUrl).buildUpon(); for (Map.Entry<String, String> en...
String baseURL = "http://www.fakex.com/course"; Map<String, String> queryParams = new HashMap<>(); queryParams.put("search_query", "mobile linux"); String expected = "http://www.fakex.com/course?search_query=mobile%20linux"; String output = UrlUtil.buildUrlWithQueryParams(logger...
29281445_29
class Dockers { static public boolean isContainerRunning( String name) { final String output = new LocalExec(Contexts.currentContext()) .command("docker") .args("ps") .runCaptureOutput() .asString() .trim(); S...
DockerTestHelper.assumeDockerIsPresent(); boolean containerRunning = Dockers.isContainerRunning("nosuchcontainer"); assertThat(containerRunning, is(false)); } }
29349352_0
class DocProcessor extends AbstractProcessor<CtElement> { public void process(CtElement element) { if (element instanceof CtType || element instanceof CtField || element instanceof CtExecutable) { Set<ModifierKind> modifiers = ((CtModifiable) element).getModifiers(); if (modifiers.contains(PUBLIC) || modifier...
final String[] args = { "-i", "src/test/resources/src/DocTest.java", "-o", "target/spooned/", "-c" // It's mandatory here to enable comments }; final Launcher launcher = new Launcher(); launcher.setArgs(args); launcher.run(); final Factory factory = launcher.getFactory(); final ProcessingMan...
29349453_21
class AeolusConfig { public String getNimbusHost() { return (String)this.config.get(NIMBUS_HOST); } public Integer getNimbusPort(); public int getNimbusPortValue(); } class AeolusConfigTest { @Test public void testNimbusHost() {
AeolusConfig config = new AeolusConfig(); String hostName = "dummy"; config.config.put(AeolusConfig.NIMBUS_HOST, hostName); Assert.assertEquals(hostName, config.getNimbusHost()); } }
29350019_17
class ImageRetinaApiImpl extends BaseRetinaApi implements Images { @Override public ByteArrayInputStream getImage(Integer scalar, ImagePlotShape shape, ImageEncoding imageEncoding, Double sparsity, Model model) throws JsonProcessingException, ApiException { validateRequiredModels(model); ...
when(api.getImageForExpression(eq(TERM_1_JSON), eq(NOT_NULL_RETINA), isNull(Integer.class), isNull(String.class), isNull(String.class), isNull(Double.class))).thenReturn(new ByteArrayInputStream(new byte[1])); imageRetinaApiImpl.getImage(TERM_1_JSON); verify(api, times(1)).getImageForExpression(...
29351988_0
class MyClass { public static Integer add(Integer a, Integer b){ return a + b; } } class MyClassTest { @Test public void testAdd(){
Integer a = new Integer(2); Integer b = new Integer(2); Integer result = new Integer(4); assertEquals(result, MyClass.add(a, b)); } }
29397245_126
class KmarkProcessor { public static String process(final String input) { try { return new KmarkProcessor().process(new StringReader(input)); } catch (IOException ignore) { //never happen, it's string reader return null; } } private KmarkProcessor(); public static String escape...
assertEquals(readTestFile("kmark/out11.out"), KmarkProcessor.process(readTestFile("kmark/in11.md"))); } }
29432931_27
class Experiment { public boolean hasForcedChoice() { return forcedChoice != null; } Experiment(Sixpack sixpack, String name, Set<Alternative> alternatives, Alternative forcedChoice, Double trafficFraction); public ParticipatingExperiment participate(); public PrefetchedExperiment prefe...
String name = "test-experiment"; Alternative test = new Alternative("test"); Experiment experiment = new ExperimentBuilder(mockSixpack) .withName(name) .withAlternatives(test) .build(); assertFalse(experiment.hasForcedChoice()); a...
29476598_13
class StorageWriter implements IWriter { public boolean writeNonDefaultDataObject(Object object, String fileName) { try { ISerializer serializer = null; try { serializer = serializerQueue.take(); } catch (InterruptedException e1) { Thread.interrupted(); } if (null == serializer) { log.err...
doThrow(InterruptedException.class).when(serializerQueue).take(); storageWriter.writeNonDefaultDataObject(new Object(), "myFile"); verifyZeroInteractions(writingChannelManager, streamProvider, extendedByteBufferOutputStream); } }
29481791_16
class Factory { public static Map<URI, Object> instantiate(final Iterable<? extends Statement> model, final URI... ids) { final Map<Resource, URI> types = Maps.newLinkedHashMap(); final Multimap<Resource, Statement> stmt = ArrayListMultimap.create(); for (final Statement statem...
Assert.assertEquals(ALICE, Factory.instantiate(// ImmutableMap.<String, Object>of("name", "Alice", "age", 84), // new URIImpl(FactoryTest.BASE + "#create"), Object.class)); } }
29500340_0
class FeedService { public Observable<List<FeedItem>> feed(String username) { return user.findId(username).toObservable() .flatMap(userid -> { if (StringUtils.hasText(userid)) { return Observable.from(repo.findByUserid(userid)); } else { return Observable.just(singletonFeed("Unknown user: ...
List<FeedItem> feedItems = Arrays.asList(new FeedItem(USERID, USERNAME, FEEDTEXT, Date.from(LocalDateTime.now().plusDays(1).toInstant(ZoneOffset.UTC))), new FeedItem(USERID, USERNAME, FEEDTEXT + "2")); when(repo.findByUserid(eq(USERID)))//, isA(PageRequest.class))) .thenReturn(toFuture(feedItems)); when(user....
29523538_11
class LogLevelServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.debug("getting log level"); synchronized (mutex) { try { String currentLevel...
Server server = Help.getServer(LogLevelServlet.class); server.start(); try { String[] levels = {"DEBUG", "INFO", "WARN", "WARNING", "ERROR", "FATAL"}; for (String level : levels) { String url = String.format("http://127.0.0.1:%d/admin/log?level=%s", Help.P...
29557376_87
class LazyString implements ImmutableList<Character>,Higher<lazyString,Character>, Serializable { @Override public LazyString plus(Character value) { return fromLazySeq(string.plus(value)); } public static LazyString fromLazySeq(LazySeq<Character> string); public static LazyString fromIter...
assertThat(empty.plus('a'),equalTo(LazyString.of("a"))); assertThat(str.plus('a'),equalTo(LazyString.of("ahello world"))); } }
29582902_1
class TransformerFactory { static String qualifiedTransformerName(String className) { String pkg = TransformerFactory.class.getPackage().getName(); String suffix = Transformer.class.getSimpleName(); StringBuilder sb = new StringBuilder(); sb.append(pkg); sb.append('.'); sb.append(className); ...
assertThat(TransformerFactory.qualifiedTransformerName("Foo"), is(equalTo(getClass().getPackage().getName() + "." + "Foo" + Transformer.class.getSimpleName()))); assertThat(TransformerFactory.qualifiedTransformerName("FooTransformer"), is(equalTo(getClass().getPackage().getName() + ...
29603580_64
class GepardEmbedder { public void setupJBehaveEmbedder(final JBehaveTestCase testCase) { embedder.embedderControls().doVerboseFailures(true).doGenerateViewAfterStories(false).useThreads(1); embedder.useEmbedderMonitor(new NullEmbedderMonitor()); Configuration configuration = configurationF...
//GIVEN in setup Configuration configuration = Mockito.mock(Configuration.class); given(configurationFactory.create(testCase)).willReturn(configuration); //WHEN underTest.setupJBehaveEmbedder(testCase); //THEN verify(instanceStepsFactoryCreator).createForTestCase(...
29629640_158
class Wallet extends BaseTaggableObject implements NewBestBlockListener, TransactionReceivedInBlockListener, PeerFilterProvider, KeyBag, TransactionBag, ReorganizeListener { @VisibleForTesting boolean isTxConsistent(final Transaction tx, final boolean isSpent) { boolean isActuallySpent = true; ...
Wallet wallet = new Wallet(PARAMS); TransactionOutput to = createMock(TransactionOutput.class); EasyMock.expect(to.isAvailableForSpending()).andReturn(true); EasyMock.expect(to.isMineOrWatched(wallet)).andReturn(true); EasyMock.expect(to.getSpentBy()).andReturn(new TransactionInp...
29653587_37
class HackerNewsClient implements ItemManager, UserManager { @Override public void getStories(@FetchMode String filter, @CacheMode int cacheMode, final ResponseListener<Item[]> listener) { if (listener == null) { return; } Observable.defer(() -> ge...
when(TestRestServiceFactory.hnRestService.topStoriesRx()) .thenReturn(Observable.just(new int[]{1, 2})); client.getStories(ItemManager.TOP_FETCH_MODE, ItemManager.MODE_DEFAULT, storiesListener); verify(TestRestServiceFactory.hnRestService).topStoriesRx(); verify(storiesLi...
29740272_0
class SvnScmProvider extends ScmProvider { @CheckForNull public Instant forkDate(Path rootBaseDir, String referenceBranch) { try { return findFork.findDate(rootBaseDir, referenceBranch); } catch (SVNException e) { LOG.warn("Unable to find fork date with '" + referenceBranch + "'", e); ret...
assertThat(new SvnScmProvider(config, new SvnBlameCommand(config), findFork).forkDate(Paths.get(""), "branch")).isNull(); } }
29740615_47
class SessionScheduler { public int doWork() { switch (state) { case DISCONNECTED: { if (duringDay) { reply = library.initiate(sessionConfiguration); state = State.CONNECTING; ret...
sessionScheduler.doWork(); verify(library, never()).initiate(sessionConfiguration); } }
29748259_89
class TsdrHsqlDBPersistenceServiceImpl implements TSDRMetricPersistenceService, TSDRLogPersistenceService, TSDRBinaryPersistenceService { @Override public void storeLog(TSDRLogRecord logRecord) { try { store.store(logRecord); } catch (SQLException e) { LOG.error(...
TSDRLogRecord logRecord = HsqlDBStoreTest.createLogRecord(); impl.storeLog(logRecord); Mockito.verify(store, Mockito.atLeast(1)).store(logRecord); } }
29807428_0
class AssetConverter implements NativeConverter<Asset, ResourceLocation> { @Override public Asset toNova(ResourceLocation resource) { return new Asset(resource.getResourceDomain(), resource.getResourcePath()); } public static AssetConverter instance(); @Override public Class<Asset> getNovaSide(); @Override pu...
assertThat(converter.toNova(new ResourceLocation("nova", "stuff"))).isEqualTo(new Asset("nova", "stuff")); assertThat(converter.toNova(new ResourceLocation("nova:otherStuff"))).isEqualTo(new Asset("nova", "otherStuff")); assertThat(converter.toNova(new ResourceLocation("nova:otherStuff"))).isEqualTo(new Asset("no...
29876931_134
class FragaSvarServiceImpl implements FragaSvarService { @Override public Map<String, Long> getNbrOfUnhandledFragaSvarForCareUnits(List<String> vardenheterIds, Set<String> intygsTyper) { Map<String, Long> resultsMap = new HashMap<>(); if (vardenheterIds == null || vardenheterIds.isEmpty()) { ...
List<GroupableItem> queryResult = new ArrayList<>(); when(fragasvarRepositoryMock.getUnhandledWithEnhetIdsAndIntygstyper(anyList(), anySet())).thenReturn(queryResult); Map<String, Long> resultMap = new HashMap<>(); resultMap.put("HSA1", 2L); when(statisticsGroupByUtil.toSekret...
29888015_19
class XmlParser implements TextParser { @Override public Component parse(String source) { try { source = "<span>" + source + "</span>"; JAXBContext context = JAXBContext.newInstance(Element.class); Unmarshaller unmarshaller = context.createUnmarshaller(); Element tag = (Element) unmarshal...
Component component = TextParsers.XML.parse("<hover action=\"show_text\" value=\"bar\">foo</hover>"); TextComponent expected = TextComponent.of("").append(TextComponent.of("foo") .hoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, TextComponent.of("bar")))); Assert.assertEquals(e...
29904381_32
class LatexSectionTitleRenderer extends AbstractOfxLatexRenderer implements OfxLatexRenderer { public void render(Title title){render(null,title);public void render(Title title){render(null,title);} public void render(Title title){render(null,title);public LatexSectionTitleRenderer(CrossMediaManager cmm, DefaultSett...
section.setId(null); renderer.render(section,title); List<String> content = renderer.getContent(); OfxContentDebugger.debug(content); Assert.assertEquals(2, content.size()); } }
29917329_63
class QuestionnaireParser { public QuestionnaireParsingResult parse(String pathname) throws IOException { EncodersQLLexer lexer = new EncodersQLLexer(new ANTLRFileStream(pathname)); EncodersQLParser parser = new EncodersQLParser(new CommonTokenStream(lexer)); final List<SyntaxError> syntaxErrors = new ArrayLis...
QuestionnaireParsingResult result = parser.parse(RESOURCE_ROOT + "ql/input_form.ql"); assertThat(result, is(notNullValue())); List<SyntaxError> syntaxErrors = result.getSyntaxErrors(); assertThat(syntaxErrors.toString(), syntaxErrors.size(), is(0)); Questionnaire questionnaire = result.getQuestionnaire(); ...
29917907_8
class LettuceManagementImpl implements LettuceManagement { @Override public String setHash(String hashName, Map<String, String> map) { LOG.debug("Set hash map {}", hashName); return this.redisConnection.hmset(hashName, map); } @Override public boolean setHashEntry(String hashName, String key, String ...
when(this.redisConnection.hmset((String) Matchers.anyObject(), Matchers.anyMap())).thenReturn(OK); assertTrue("Hash map set", OK.equals(this.lettuceManagement.setHash(MAPNAME, TEST_MAP))); } }
29918398_1
class BoardView extends HorizontalScrollView implements AutoScroller.AutoScrollListener { public void setBoardListener(BoardListener listener) { mBoardListener = listener; } public BoardView(Context context); public BoardView(Context context, AttributeSet attrs); public BoardView(Contex...
BoardView.BoardListener boardListener = mock(BoardView.BoardListener.class); subject.setBoardListener(boardListener); createColumnsAndDrag(adapter); verify(boardListener).onItemChangedPosition(anyInt(), anyInt(), anyInt(), anyInt()); } }
29959880_93
class StringHelper { public static boolean isValidEmail(final String email) { return EMAIL_PATTERN.matcher(email.trim().toLowerCase()).matches(); } public static String getDataTypeFromFileName(String fileName); public static String addNumberToFileName(String fileName, int number); public s...
String validEmail = "blablubb.de"; assertThat(StringHelper.isValidEmail(validEmail)).isFalse(); } }
29964541_11
class AmbariClusterImpl extends BasicStartableImpl implements AmbariCluster { protected Map<String, Map> mergeMaps(Map<String, Map> configuration, Map<String, Map> servicesConfig) { if (servicesConfig == null) { return configuration; } MutableMap<String, Map> newConfigurationMa...
Map<String, Map> tmpMap = ambariCluster.mergeMaps(null, newMap); assertEquals(tmpMap.get("oozie-site").get("oozie.service.ProxyUserService.proxyuser.hue.hosts"), "localhost"); } }
29969855_12
class UUIDAggregateIdentifierFactory implements AggregateIdentifierFactory { @Override public final AggregateIdentifier create() { return new UUIDAggregateIdentifier(); } @Override public final AggregateIdentifier fromString(final String aggregateId); private UUIDAggregateIdentifierFactory testee; } class U...
assertThat(testee.create()).isInstanceOf(UUIDAggregateIdentifier.class); } }
29974632_50
class CredentialsConfig extends SimpleComponent<CredentialsConfig> implements PasswordsConfig<CredentialsConfig> { @Override public CredentialsConfig merge(final CredentialsConfig config) { // empty password value means 'use existing value' - see control-point-widget.js return super.merge(confi...
Assert.assertEquals(new CredentialsConfig("new user", "pass"), new CredentialsConfig("new user", "").merge(decryptedValue)); } }
29993866_0
class TopicCreator { public void maybeCreateTopic(String topicName) throws ExecutionException, InterruptedException { Collection<NewTopic> topics = new ArrayList<>(); topics.add(new NewTopic(topicName, 1, (short) 1)); if (topicName.toLowerCase().startsWith("test")) { ...
TopicCreator tc = new TopicCreator(admin); tc.maybeCreateTopic("test.is.a.test.topic"); verify(admin, times(1)).createTopics(any()); } }
29996210_0
class EnvironmentVariablesPropertiesSource implements PropertiesSource { @Override public Map<String,String> getProperties() { Map<String,String> envVars = System.getenv(); if (!Collections.isEmpty(envVars)) { return new LinkedHashMap<>(envVars); } return java.uti...
setEnvironmentVariable("my_special_key", "my_special_value"); Map<String, String> props = new EnvironmentVariablesPropertiesSource().getProperties(); assertEquals(props.get("my_special_key"), "my_special_value"); } }
30000823_1
class RdRandException extends RuntimeException { public RdRandStatus getStatus() { return status; } public RdRandException(RdRandStatus status); private RdRandException rdRandException; private RdRandStatus testStatus; } class RdRandExceptionTest { private RdRandException rdRandException; private RdRand...
rdRandException = new RdRandException(testStatus); assertTrue(testStatus == rdRandException.getStatus()); } }
30008530_24
class StaticCoordinator extends ZkCoordinator { @Override public synchronized Map<String, Integer> getRebalanceCount() { Map<String, Integer> countMap = new HashMap<String, Integer>(); try { for (String topic : m_allTopicPartitions.keySet()) { int count = 0; int toTake = getToTakePartitions(topic).siz...
String groupId1 = "test_group1"; String topic0 = "Topic.test-0"; String topic1 = "Topic.test-1"; List<String> topics1 = new ArrayList<String>(); topics1.add(topic0); topics1.add(topic1); String consumerId0 = "D-00456-consumerId-0"; String consumerId1 = "D-00456-consumerId-1"; String path0 = "/broker...
30044052_147
class ScalaSnippetExecutor extends AbstractSnippetExecutor<ScalaSnippetExecutorOptions> { protected String buildSourceCode(final CodeSnippet codeSnippet) throws IOException { final StringBuilder sourceCode = new StringBuilder(); if (hasImports(codeSnippet)) { sourceCode.append(getImpor...
final CodeSnippet snippet = new CodeSnippet(); snippet.getProperties().put(CLASS_NAME_PROPERTY, "TestScala"); snippet.setCode("def main(args: Array[String]) {\n\tprintln(\"Hello\")\n}"); final String expected = IOUtils.read(ScalaSnippetExecutorTest.class.getResourceAsStream("/com/twasy...
30073725_6
class Connect { public List<Data> getData() throws ConnectException { final InputStream inputStream; try { inputStream = mRequestBuilder.create().connect().getInputStream(); return mParser.getModels(inputStream); } catch (IOException e) { throw new Connec...
assertEquals(Collections.EMPTY_LIST, new Connect(mRequestBuilder, mParser).getData()); } }
30084378_190
class TLParsingTask extends AbstractParsingTask implements Supplier<TLParsingResult> { @Override public TLParsingResult get() { TLParsingResult result = new TLParsingResult(); TrustStatusListType jaxbObject = getJAXBObject(); parseSchemeInformation(result, jaxbObject.getSchemeInformation()); parseTrustSe...
TLParsingTask task = new TLParsingTask(IE_TL, new TLSource()); TLParsingResult result = task.get(); assertNotNull(result); assertEquals(5, result.getVersion()); assertEquals(18, result.getSequenceNumber()); assertNotNull(result.getIssueDate()); assertNotNull(result.getNextUpdateDate()); assertEquals("IE...
30120639_1
class ObjectStore { @SuppressWarnings("unchecked") public E insert(E e) { OID id = odb.store(e); odb.commit(); E attached = (E) odb.getObjectFromId(id); odb.disconnect(attached); return attached; } public ObjectStore(String name, Class<E> objectType); public Collection<E> getAll(); public E get(Str...
ObjectStore<XdccRequest> store = new ObjectStore<XdccRequest>( "requests.neodatis", XdccRequest.class) { @Override public List<XdccRequest> searchByExample(XdccRequest e) { // TODO Auto-generated method stub return null; } @Override protected Class<XdccRequest> getEntityType() { retur...
30124869_20
class ReduceOperation { public static void reduce(OWLOntology ontology, OWLReasonerFactory reasonerFactory) throws OWLOntologyCreationException { reduce(ontology, reasonerFactory, getDefaultOptions()); } public static Map<String, String> getDefaultOptions(); public static void reduce( OWLOntol...
OWLReasonerFactory reasonerFactory = new org.semanticweb.elk.owlapi.ElkReasonerFactory(); OWLOntology ontologyA = loadOntology("/reduce-named-only-test.ofn"); Map<String, String> optionsA = new HashMap<String, String>(); optionsA.put("named-classes-only", "true"); ReduceOperation.reduce(ontologyA, ...
30125753_6
class Utils { public static boolean isValidEmail(String email) { if (email == null) { return false; } final String emailPattern = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; Matcher matcher; Pattern pattern = Pattern....
boolean invalid = Utils.isValidEmail("jay@twitter"); boolean expected = false; // Log.i(TAG, "formattedSize: " + formattedSize + " expected: " + expected); // use this method because float is not precise assertEquals("Email invalid", expected, invalid); } }
30182457_0
class AllegroNiceApi extends AbstractService implements IAllegroNiceApi { @Override public SysStatusType getStatus() { return systemService.getStatus(); } private AllegroNiceApi(Builder builder); private ServicePort createAllegro(Builder builder); private URL getWsdlLocation(); @...
assertNotNull(api.getStatus()); } }
30195197_51
class OWLGraphWrapperEdgesExtended extends OWLGraphWrapperEdges { public boolean isOWLObjectInSubsets(OWLObject testObject, Collection<String> subsets) { return !Collections.disjoint(subsets, this.getSubsets(testObject)); } public OWLGraphWrapperEdgesExtended(OWLOntology ontology); protected OW...
Collection<String> testSubsets = new ArrayList<String>(); testSubsets.add("test_subset1"); //FOO:0006 is part of the subset test_subset1 OWLClass testClass = wrapper.getOWLClassByIdentifier("FOO:0006"); assertTrue("FOO:0006 is not seen as belonging to test_subset1", wrapper.isOWLObjectInSubsets(testClass...
30242992_10
class Value extends Expression { @Override public final String toHaskell() { return "(" + this.value + ")"; } public Value(final Type type, final String value); @Override public final Type inferType(); public final String getValue(); @Override public final String toString(); ...
final Expression v = new Value(this.integer, "10"); assertEquals(this.integer.prettyPrint(), v.inferType().prettyPrint()); assertEquals("(10)", v.toHaskell()); } }
30258802_2399
class OptionsHelper { public static String applyRule(String ruleName, String serverOptStr, boolean value) throws OptionsException { throwOptionsExceptionIfConditionFails(isNotBlank(serverOptStr), "Null or Empty server options spec"); if (isBlank(ruleName)) { if (value) { return OPTPFX + server...
try { OptionsHelper.applyRule(null, null, "string"); fail("Expected Exception!"); } catch (Throwable e) { assertEquals(OptionsException.class, e.getClass()); } try { OptionsHelper.applyRule("notnull", null, "string"); fail("Expe...
30259183_8
class BarcodeDimension { public double getXOffset() { return xOffset; } public BarcodeDimension(double w, double h); public BarcodeDimension(double w, double h, double wpq, double hpq, double xoffset, double yoffset); public double getHeight(); public double ...
System.out.println("getXOffset"); assertEquals(5, new BarcodeDimension(100, 200, 110, 204, 5, 2).getXOffset(), 0.0); assertEquals(0, new BarcodeDimension(100, 200).getXOffset(), 0.0); } }
30322187_24
class IntentUtils { public static boolean verifyIntentActions(final Intent intent) { boolean result = true; final List<Actions> actions = intent.getActions(); if (actions == null || actions.size() != NUM_OF_SUPPORTED_ACTION) { LOG.warn("Intent's action is either null or not equa...
boolean result; Mockito.when(intentMock.getActions()).thenReturn(null); result = IntentUtils.verifyIntentActions(intentMock); Assert.assertFalse(result); Mockito.when(intentMock.getActions()).thenReturn(actionsMock); Mockito.when(actionsMock.size()).thenReturn(0); ...
30330883_1
class VncRenderService implements RenderProtocol { public DoubleProperty zoomLevelProperty() { return zoomLevel; } public VncRenderService(); public VncRenderService(VncConnection con); public void setEventConsumer(BiConsumer<ServerDecoderEvent, ImageRect> c); public ProtocolConfiguration getConfig...
VncRenderService service = new VncRenderService(null); assertEquals(1.0, service.zoomLevelProperty().get(), 0.01); service.zoomLevelProperty().set(0.0); assertNotEquals(0.0, service.zoomLevelProperty().get(), 0.01); service.zoomLevelProperty().set(Double.MAX_VALUE); assertNotEquals(Double.MAX_V...
30333472_14
class BusinessDateTime extends AbstractDateTime implements ReadableDateTime, Serializable { public BusinessDateTime plusSeconds(int seconds) { if (seconds == 0) { return this; } else { return move(seconds, Constants.NANOS_PER_SECOND); } } public BusinessDateTime(DateTime dateTime, ...
DateTime start = new DateTime(2014, 12, 11, 16, 59, 57, 0); DateTime expected = new DateTime(2014, 12, 11, 17, 0, 0, 0); BusinessDateTime businessStart = new BusinessDateTime(start); assertEquals("Thursday 16:59:57.0 plus 3 Seconds should return Thursday 17:00:00.0", expected, ...
30405191_19
class BNFProcessor { public Grammar processString(String inString) { return processStream(new ByteArrayInputStream((inString).getBytes()) ); } public Grammar processStream(InputStream inStream); public Grammar processFile(String fileName); private Grammar processAntrlStream(CharStream inSt...
Grammar grammar = Fixture.grammarResource( BNFProcessor.class, "/cypher.xml"); // not doing this at the moment because two of the rules get an unnecessary { } round a single item // LOGGER.debug("Original grammar \n{}", xmlout(grammar)); String firstBNF = makeSQLBNF(grammar); LOGGER.debug("Generated \n{}", f...
30405521_62
class RequiredPackagesInstallStep extends AbstractInstallStep { protected List<Optional<Package>> resolvePackages(Collection<Package> installablePackages, List<String> minimumPackages) { return minimumPackages .stream() .map(pkgName -> installablePackages .stream() ...
// setup installable packages form Packages.txt final LocalPackageList localPackageList = new LocalPackageList(new Source(), new File("target/test-classes/Packages.txt")); List<Package> installablePackages = parsePackagesList(localPackageList).collect(Collectors.toList()); assertEquals(36, installableP...
30417900_2
class SecurityUtils { public static boolean isAuthenticated() { SecurityContext securityContext = SecurityContextHolder.getContext(); Collection<? extends GrantedAuthority> authorities = securityContext.getAuthentication().getAuthorities(); if (authorities != null) { for (Grante...
SecurityContext securityContext = SecurityContextHolder.createEmptyContext(); Collection<GrantedAuthority> authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS)); securityContext.setAuthentication(new UsernamePasswordAuthenticationTok...
30419413_26
class TlvDecoder { public static Tlv[] decode(ByteBuffer input) throws TlvException { try { List<Tlv> tlvs = new ArrayList<>(); while (input.remaining() > 0) { input.order(ByteOrder.BIG_ENDIAN); // decode type int typeByte = input.g...
String dataStr = "0011223344556677889900"; byte[] bytes = Hex.decodeHex(dataStr.toCharArray()); ByteBuffer b = ByteBuffer.wrap(bytes); try { TlvDecoder.decode(b); fail(); } catch (TlvException ex) { // this is very weak assertion since the for...
30422535_28
class PermissionCheckerImpl implements PermissionChecker { @Override public boolean isAllowedTo(Operation operation, Resource resource, Persona persona) { if (null == resource) { throw new IllegalArgumentException("Resource to be checked is invalid (null)."); } if (null == ...
// persona jdoe registers himself HawkularUser jdoe = userService.getOrCreateById(UUID.randomUUID().toString()); // jdoe creates a resource as acme, acme is has all rights on this resource, including SuperUser and // Administrator String id = UUID.randomUUID().toString(); ...
30425951_0
class Source { public static String formatAligned(String fmt, Object... lines) { final String FORMAT_ELEMENT_SYMBOL = "##"; final int hashStartIndex = fmt.indexOf(FORMAT_ELEMENT_SYMBOL); final int hashEndIndex = hashStartIndex + FORMAT_ELEMENT_SYMBOL.length(); final Str...
final String EXPECTED = " line1\n" + " line2\n" + " line3"; String fmt = " ##"; String actual = Source.formatAligned(fmt, "line1", "line2", "line3"); assertEquals(EXPECTED, actual); } }
30438494_3
class CharUtils { public static boolean isHex(char a) { return (a >= '0' && a <= '9') || (a >= 'a' && a <= 'f') || (a >= 'A' && a <= 'F'); } private CharUtils(); public static boolean isAlpha(char a); public static boolean isNumeric(char a); public static boolean isAlphaNumeric(char a); public sta...
char[] arr = { 'a', 'A', '0', '9' }; for (char a : arr) { Assert.assertTrue(CharUtils.isHex(a)); } char[] arr2 = { '~', ';', 'Z', 'g' }; for (char a : arr2) { Assert.assertFalse(CharUtils.isHex(a)); } } }
30448037_0
class LocalNetwork { @Override public String toString() { return getClass().getSimpleName() + "(" + interfaceIp.toString() + "\\" + networkPrefixLength + ")"; } public LocalNetwork(InetAddress interfaceIp, int networkPrefixLength); public InetAddress getInterfaceIp(); public InetAddr...
InetAddress test = InetAddress.getByAddress(testAdress); LocalNetwork localNetwork = new LocalNetwork(test, 0); Assert.assertTrue(localNetwork.toString().indexOf("192.168.127.127") >= 0); } }
30449481_69
class ResultSet implements Iterable<Result> { public CompletableFuture<Void> allItemsAvailableAsync() { final CompletableFuture<Void> allAvailable = new CompletableFuture<>(); readCompleted.thenRun(() -> allAvailable.complete(null)); readCompleted.exceptionally(t -> { allAvailab...
final CompletableFuture<Void> all = resultSet.allItemsAvailableAsync(); assertThat(all.isDone(), is(false)); final AtomicBoolean atLeastOnce = new AtomicBoolean(false); addToQueue(1000, 1, true, true); while (!readCompleted.isDone()) { atLeastOnce.set(true); ...
30515411_4
class MoreSuppliers { public static <T, X extends Throwable> CloseableThrowableSupplier<T, X> lazyEx(ThrowableSupplier<T, X> delegate) { return lazyEx(delegate, true); } public static CloseableSupplier<T> lazy(Supplier<T> delegate); public static CloseableSupplier<T> lazy(Supplier<T> delegate,...
int[] counter = {0}; CloseableThrowableSupplier<String, RuntimeException> supplier = lazyEx(() -> { counter[0]++; return null; }); assertNull(supplier.get()); assertNull(supplier.get()); assertEquals(counter[0], 1); supplier.tryClose(); ...
30520538_2
class XformInstanceResource extends BaseResource<OpenmrsObject> { static void adjustXformDocument(Document doc, int patientId, int userId, Date dateEntered) throws SAXException, IOException { Element root = doc.getDocumentElement(); // This element sets the encounter's patient_id column. X...
Document expected = getXmlResource(getClass(), "expected-instance-add.xml"); Document doc = getXmlResource(getClass(), "original-instance-add.xml"); XformInstanceResource.adjustXformDocument(doc, 8, 1, Utils.parse8601("2014-11-15T12:34:56.789Z")); assertXmlEqual(expected, doc); } }
30535152_0
class CentralFileResolver implements FileResolver { @Override public InputStream openInputStream(String fileId) throws IOException { Path fileName = resolvePath(fileId); logger.trace("Reading data from file {}", fileName); InputStream ret; if (!Files.exists(fileName)) { throw new FileNotFoundException(fil...
InputStream in = fr.openInputStream(checksum); char[] read = IOUtils.toCharArray(in); assertEquals(inData.length, read.length); for (int i = 0; i < read.length; i++) { assertEquals(inData[i], read[i]); } } }
30564046_0
class Credentials { public boolean isDemoCredentials() { return this.equals(Credentials.createDemoCredentials()); } public Credentials(String serverURL, String username, String password); public static Credentials createDemoCredentials(); public String getServerURL(); public String g...
Credentials credentials = new Credentials("server", "user", "pwd"); assertThat(credentials.isDemoCredentials(), is(false)); } }
30567918_8
class OBridge { public void generate(OBridgeConfiguration c) { // populate objects table PopulateObjectsTable.run(c); // generate objects EntityObjectGenerator.generate(c); // generate converters ConverterObjectGenerator.generate(c); // generate contexts ...
Properties p = new Properties(); p.load(getClass().getClassLoader().getResourceAsStream("datasource.properties")); OBridgeConfiguration oBridgeConfiguration = new OBridgeConfiguration(); oBridgeConfiguration.setJdbcUrl(p.getProperty("connectionString")); oBridgeConfiguration.se...
30607695_1
class DummySearchService implements SearchService { @Override public ListenableFuture<SearchResponse> extendedSearch(ExtendedSearchRequest request) { SearchResponse response = new SearchResponse(); response.setResultList(Arrays.asList( "result 1", "result 2", ...
ListenableFuture<SearchResponse> result = service.extendedSearch(new ExtendedSearchRequest()); Assert.assertEquals(Arrays.asList("result 1", "result 2", "result 3"), result.get().getResultList()); } }
30649762_4
class SubDomainDynamicExtractor extends DomainValueDynamicExtractor { public String extract(AttributeDetail attributeDetail, String url, Document articleDoc) throws Exception { String domain = super.extract(attributeDetail, url, articleDoc); if(domain.equals(UNKOWN_DOMAN)){ return null;...
String url = "abc.somesite.com/aStory"; AttributeDetail detail = new AttributeDetail(); detail.extractor_args = Arrays.asList("1"); SubDomainDynamicExtractor extr = new SubDomainDynamicExtractor(); assertEquals("abc", extr.extract(detail, url, null)); } }
30705823_1
class Main { public void run(String[] args) throws ClientException { try { List<String> remainingArgs = readActionAndOptions(args); switch (action) { case UPLOAD: doUpload(remainingArgs); break; case DELETE: ...
MainRunner runner = new MainRunner(null, 45); runner.run("--help"); assertThat(runner.stdout, containsString("Usage: java -jar larsClient.jar action [options] [arguments] ...")); assertThat(runner.stdout, containsString("Show help for larsClient.")); assertThat(runner.stdout, con...
30761550_41
class ReconnectingClient extends AbstractRawMemcacheClient { @Override public boolean isConnected() { return client.isConnected(); } public ReconnectingClient( final BackoffFunction backoffFunction, final ScheduledExecutorService scheduledExecutorService, final HostAndPort address, ...
FakeClient delegate1 = new FakeClient(true, true); FakeClient delegate2 = new FakeClient(true, false); BackoffFunction backoffFunction = mock(BackoffFunction.class); when(backoffFunction.getBackoffTimeMillis(0)).thenReturn(0L); when(backoffFunction.getBackoffTimeMillis(1)).thenReturn(123L); Co...
30764186_37
class JCloudsCloud extends Cloud implements SlaveOptions.Holder { @Restricted(NoExternalUse.class) @RequirePOST public void doProvision(StaplerRequest req, StaplerResponse rsp, @QueryParameter String name) throws IOException { // Temporary workaround for https://issues.jenkins-ci.org/browse/JENKIN...
final JCloudsSlaveTemplate template = j.dummySlaveTemplate("asdf"); final JCloudsCloud cloudProvision = getCloudWhereUserIsAuthorizedTo(Cloud.PROVISION, template); j.executeOnServer(new DoProvision(cloudProvision, template)); final JCloudsCloud itemConfigure = getCloudWhereUserIsAuthor...
30803699_35
class LynxConfig implements Serializable, Cloneable { public boolean hasFilter() { return !"".equals(filter) || !TraceLevel.VERBOSE.equals(filterTraceLevel); } public LynxConfig(); public LynxConfig setMaxNumberOfTracesToShow(int maxNumberOfTracesToShow); public LynxConfig setFilter(String filter); ...
LynxConfig lynxConfig = new LynxConfig(); assertFalse(lynxConfig.hasFilter()); } }
30818918_39
class GenerateMojo extends AbstractMojo { @VisibleForTesting void generateParser(File cupFile) throws IOException, MojoExecutionException { String javaPackage = findJavaPackage(cupFile); // compiling the generated source in target/generated-sources/cup is // the whole point of this plugin. mavenPr...
mojo.symbolInterface = true; ClassLoader classLoader = getClass().getClassLoader(); File file = new File(classLoader.getResource("test.cup").getFile()); mojo.generateParser(file); File expectedDestDir = new File(tempTargetGeneratedCupDirectory, "/foo/bar"); verify(mockCupInvoker) .invok...
30822986_0
class ArbiterCliRunner { public void runMain(String...args) throws Exception { JCommander jcmdr = new JCommander(this); try { jcmdr.parse(args); } catch(ParameterException e) { System.err.println(e.getMessage()); //User provides invalid input -> print th...
ArbiterCliRunner cliRunner = new ArbiterCliRunner(); //Define: network config (hyperparameter space) MultiLayerSpace mls = new MultiLayerSpace.Builder() .optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT) .updater(new SgdSpace(new ContinuousParam...
30837244_6
class DesiredYawCalculator { public double getYaw(double droneHeading, double phoneHeading) { double difference = phoneHeading - droneHeading; if (difference > 180) { difference = difference - 180 * 2; } else if (difference < -180) { difference = difference + 180 * ...
double yaw = desiredYaw.getYaw(170, -170); assertEquals(20d, yaw); } }
30840080_2
class NetworkBlogUrlValidator implements BlogUrlValidator { @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) static Single<String> checkGhostBlog(@NonNull String blogUrl, @NonNull OkHttpClient client) { final String adminPagePath = "/ghost/"; St...
String blogUrl = HTTPS + server.getHostName() + ":" + server.getPort() + "/THIS_DOESNT_EXIST"; server.useHttps(Helpers.LOCALHOST_SOCKET_FACTORY, false); server.enqueue(new MockResponse().setResponseCode(404)); OkHttpClient httpClient = Helpers.getProdHttpClient(); try { ...