id stringlengths 7 14 | source stringlengths 135 41.2k | target stringlengths 36 20.4k |
|---|---|---|
129740723_0 | class ReaderFromFile {
public ArrayList<Integer> getDepots() {
return depots;
}
public ReaderFromFile(String fileName);
private void setProblemSpecification();
public ArrayList<Point> getClientCoords();
public ArrayList<Integer> getClientDemands();
public int getNumberOfClients();
public CVRPSpecificatio... | setFile("./input/tests/correctTest.vrp");
assertEquals(reader.getDepots().size(), 1);
}
} |
129769092_246 | class CommonUtils {
public static boolean allHaveSameLength(Object... arrays) {
if (arrays.length < 1) {
return true;
}
int length = Array.getLength(arrays[0]);
for (Object array : arrays) {
if (Array.getLength(array) != length) {
return fals... | int i = 1;
String s = "s";
assertThat(allHaveSameLength(i, s), is(false));
}
} |
129771138_842 | class ConsentEntity extends InstanceDependableEntity implements Authorisable {
public boolean isWrongConsentData() {
return CollectionUtils.isEmpty(psuDataList)
|| tppInformation == null
|| tppInformation.getTppInfo() == null;
}
@PostLoad public void consentPo... | // Given
ConsentEntity aisConsent = buildConsent(Collections.emptyList(), TPP_INFO, false);
// When
boolean actual = aisConsent.isWrongConsentData();
// Then
assertTrue(actual);
}
} |
129848791_18 | class WeaverObserveOnComponentAbstract implements WeaverObserveOnComponent<T> {
protected String getSchedulerName() {
Object[] args = getJoinPoint().getArgs();
if (args == null || args.length == 0)
return null;
RxScheduler rxScheduler = RxScheduler.fromClass(args[0].getClass());
return rxScheduler != null... | when(proceedingJoinPoint.getArgs()).thenReturn(new Object[]{Schedulers.io()});
assertEquals(RxScheduler.IO.name(), weaverComponent.getSchedulerName());
}
} |
129892661_69 | class LotteryTicket {
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
LotteryTicket other = (LotteryTicket) obj;
if (lotteryNumbers == null) {
... | PlayerDetails details1 = new PlayerDetails("bob@foo.bar", "1212-121212", "+34332322");
LotteryNumbers numbers1 = LotteryNumbers.create(new HashSet<>(Arrays.asList(1, 2, 3, 4)));
LotteryTicket ticket1 = new LotteryTicket(new LotteryTicketId(), details1, numbers1);
PlayerDetails details2 = new PlayerDetai... |
129954828_55 | class JerseyInvocation implements javax.ws.rs.client.Invocation {
ClientRequest request() {
return requestContext;
}
private JerseyInvocation(final Builder builder);
private JerseyInvocation(final Builder builder, final boolean copyRequestContext);
private static Map<String, EntityPrese... | final Client client = ClientBuilder.newClient();
final Invocation.Builder builder = client.target("http://localhost:8080/mypath").request();
final JerseyInvocation invocation = (JerseyInvocation) builder
.header("foo", "bar").header("foo", null).header("bar", "foo")
... |
129972128_93 | class ApiRequest {
JSONObject getBody() {
return body;
}
private ApiRequest(Builder builder);
RequestMethod getRequestMethod();
String getPath();
Map<String, String> getHeaders();
}
class ApiRequestTest {
@Test
public void setBody_verifyBody() {
| JSONObject body = new JSONObject();
ApiRequest apiRequest = new ApiRequest.Builder(ApiRequest.RequestMethod.POST, "/")
.setBody(body)
.build();
assertEquals(body, apiRequest.getBody());
}
} |
130000911_104 | class RLP {
public static byte[] encode(Object input) {
Value val = new Value(input);
if (val.isList()) {
List<Object> inputArray = val.asList();
if (inputArray.isEmpty()) {
return encodeLength(inputArray.size(), OFFSET_SHORT_LIST);
}
... | String result = Hex.toHexString(encode(0xED));
String expected = "81ed";
assertEquals(expected, result);
}
} |
130200142_1 | class AppController extends Application {
public String getMeasureId() {
return String.format("%s_measure_%s_%s", Utils.getAndroidID(getContentResolver()), Utils.getUniversalTimestamp(), Utils.getSaltString(16));
}
@Override public void onCreate();
public String getAzureConnection();
publi... | String valid = String.format("%s_measure_%s_%s", "AndroidUUID", Utils.getUniversalTimestamp(), Utils.getSaltString(16));
String invalidId = "9e58cfb935e72628_measure1_1545035746888_CetMsJLZJvUsTboi";
String[] array = valid.split("_");
Assert.assertEquals("Measure ID schema is not corre... |
130308047_3 | class LogAwareExceptionHandler implements ExceptionHandler {
@Override
public void onException(String summary, Throwable error) {
zlgSupplier.get().w(summary, error);
}
LogAwareExceptionHandler(Supplier<Zlg> zlgSupplier);
}
class LogAwareExceptionHandlerTest {
@Test
public void test() {
| final MockLogTarget logTarget = new MockLogTarget();
final LogAwareExceptionHandler handler = new LogAwareExceptionHandler(logTarget::logger);
final String summary = "summary";
final Throwable error = new RuntimeException("error");
handler.onException(summary, error);
logTarget.entries... |
130383787_0 | class DataService {
public List<CardBin> getCardBins(){
CardBinRequest.Builder request = CardBinRequest.newBuilder();
request.setUserName(rpcUserName);
request.setPassword(rpcPassword);
CardBinResponse response = client.execute(CARD_BIN_SERVICE_NAME, request.build(), CardBinResponse.class);
return response.... | assertEquals(service.getCardBins().size(), 4856);
}
} |
130464600_4 | class CannedPropertyValidators {
public static StringPropertyValidationRules textValidator() {
return new StringPropertyValidationRules(false, 32);
}
public static BooleanPropertyValidationRules boolValidator();
public static PinPropertyValidationRules pinValidator();
public static PinProp... | StringPropertyValidationRules validator = CannedPropertyValidators.textValidator();
assertFalse(validator.hasChoices());
assertThat(validator.choices()).isEmpty();
assertTrue(validator.isValueValid(""));
assertTrue(validator.isValueValid("This is text"));
assertFalse(vali... |
130481756_44 | class AssetResponseHttpMessageConverter implements HttpMessageConverter<AssetResponse> {
@Override
public void write(AssetResponse assetResponse, @Nullable MediaType mediaType,
HttpOutputMessage httpOutputMessage) throws IOException {
// Get meta data
Asset asset = assetResponse.getAsset();
AssetMetaData me... | AssetResponse assetResponse = new AssetResponse(asset);
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
conv.write(assetResponse, MediaType.TEXT_PLAIN, outputMessage);
assertEquals(asset.getMetaData().getContentType(),
outputMessage.getHeaders().getContentType().toString());
assertTrue(... |
130492560_2 | class JsonNodeSerde implements Serde<JsonNode>, Serializer<JsonNode>, Deserializer<JsonNode> {
@Override
public JsonNode deserialize(String topic, byte[] data) {
if (data == null) {
return null;
}
try {
return mapper.readTree(data);
} catch (Exception e) ... | byte[] json = StreamUtils.copyToByteArray(getClass().getResourceAsStream("JsonNodeSerdeTest.json"));
JsonNode node = new JsonNodeSerde().deserialize(null, json);
assertThat(node.get("schema").get("name").textValue()).isEqualTo("fb-connect.public.players.Envelope");
assertThat(node.get("... |
130509793_1 | class MessageUtil {
public static String colored(String message) {
return message != null ? ChatColor.translateAlternateColorCodes('&', message) : null;
}
private MessageUtil();
public static List<String> colored(List<String> messages);
}
class MessageUtilTest {
@Test
public void coloredListTest(... | List<String> expected = Arrays.asList("§7Hello!", "§cHow are you?", "§6I'm fine, thanks!");
List<String> actual = MessageUtil.colored(
Arrays.asList("&7Hello!", null, "&cHow are you?", null, "&6I'm fine, thanks!"));
Assert.assertEquals(expected, actual);
}
} |
130510170_0 | class HtmlUtils {
public static String getHtmlCharset(byte[] htmlContent) {
String charset = Charset.defaultCharset().name();
return getHtmlCharset(htmlContent, charset);
}
public static String getHtmlCharset(byte[] htmlContent, String defaultCharset);
public static String getHeadStr(S... | for (String currentCharset : charsets) {
String html = "<html><meta charset=\"" + currentCharset + "\"/><body></body></html>";
String charset = HtmlUtils.getHtmlCharset(html.getBytes(currentCharset));
Assert.assertEquals(currentCharset, charset);
}
}
} |
130603282_52 | class AdapterWorkerManagement {
public void stopStreamAdapter(AdapterStreamDescription adapterStreamDescription) throws AdapterException {
stopAdapter(adapterStreamDescription);
}
public Collection<Protocol> getAllProtocols();
public Protocol getProtocol(String id);
public Collection<Adap... | String expected = "Adapter with id http://test.de was not found in this container and cannot be stopped.";
AdapterStreamDescription asd = new GenericAdapterStreamDescription();
asd.setUri("http://test.de");
AdapterWorkerManagement adapterManagement = new AdapterWorkerManagement();
... |
130709430_86 | class ExpectedLevelResolver implements Function<LogDefinition, LogLevel> {
@Override
public LogLevel apply(LogDefinition definition) {
return min(definition.getLevel(), definition.getIfEnabledLevel());
}
public static ExpectedLevelResolver getInstance();
private LogLevel min(LogLevel level... | // given
LogDefinition definition = givenLogDefinition(ERROR, WARN);
// when
LogLevel level = expectedLevelResolver.apply(definition);
// then
assertThat(level, is(WARN));
}
} |
130728684_27 | class CredHubCredentialsGenerator implements CredentialGenerator {
@Override
public Mono<Void> deleteString(String applicationId, String serviceInstanceId, String descriptor) {
return credHubOperations.credentials()
.deleteByName(new SimpleCredentialName(applicationId, serviceInstanceId, descriptor));
}
publ... | given(this.credHubOperations.credentials())
.willReturn(credHubCredentialOperations);
given(this.credHubCredentialOperations.deleteByName(any()))
.willReturn(Mono.empty());
StepVerifier.create(generator.deleteString("foo", "bar", "hello"))
.verifyComplete();
verify(credHubCredentialOperations).delet... |
130898702_15 | class HelmPathUtils {
public String filename(final TokenMatcher.State state) {
return match(state, "filename");
}
public String contentFilePath(final TokenMatcher.State state);
public String extension(final TokenMatcher.State state);
private String match(final TokenMatcher.State state, final String name... | Map<String, String> map = new HashMap<>();
map.put("filename", FILENAME);
when(state.getTokens()).thenReturn(map);
String result = underTest.filename(state);
assertThat(result, is(equalTo(FILENAME)));
}
} |
130912988_0 | class Query {
public Expression getExpression() {
return expression;
}
public Query();
public Query(Expression expression);
public Query purge();
public void setExpression(Expression expression);
public int getSkip();
public Query skip(int skip);
public int getLimit();
... | //Should handle multiple spaces properly
final var searchQuery = parse("hi my name is ryan");
assertThat(searchQuery.getExpression())
.asInstanceOf(type(SearchQuery.class))
.extracting(SearchQuery::getTerm)
.isEqualTo("hi my name is ryan"... |
131008831_23 | class NetworkingModule extends ReactContextBaseJavaModule {
@ReactMethod
/**
* @param timeout value of 0 results in no timeout
*/
public void sendRequest(
String method,
String url,
final int requestId,
ReadableArray headers,
ReadableMap data,
final String responseType,
... | RCTDeviceEventEmitter emitter = mock(RCTDeviceEventEmitter.class);
ReactApplicationContext context = mock(ReactApplicationContext.class);
when(context.getJSModule(any(Class.class))).thenReturn(emitter);
OkHttpClient httpClient = mock(OkHttpClient.class);
when(httpClient.newCall(any(Request.class)))... |
131024664_16 | class ThresholdFactory {
public static ThresholdSha256Condition constructMOfNCondition(
final int thresholdM, int numSubCondtionsN, final List<Condition> subconditions
) {
Objects.requireNonNull(subconditions, "subconditions must not be null!");
if (thresholdM < 0) {
throw new IllegalArgumentE... | try {
ThresholdFactory.constructMOfNCondition(1, 2, null);
} catch (NullPointerException e) {
assertThat(e.getMessage(), is("subconditions must not be null!"));
throw e;
}
}
} |
131061409_9 | class Position implements Comparable<Position> {
public static Position of(String contig, int pos, ImmutableMap<String, Integer> contigs) {
return new AutoValue_Position(contig, pos, contigs);
}
public static ImmutableList<Position> fromFile(Path file);
public static ImmutableList<Position> fromFile(Path ... | ImmutableMap<String, Integer> contigs = ImmutableMap.of("chr1", 0, "chr10", 1, "chr11", 2);
assertThrows(NullPointerException.class, () -> Position.of(null, 0, contigs));
assertThrows(NullPointerException.class, () -> Position.of("chr1", 0, null));
}
} |
131105127_23 | class RandomGen implements FieldDataProvider<Object, GENERATED_INSTANCE> {
public GENERATED_INSTANCE generate() {
return generate(null);
}
private RandomGen(
InstanceProvider<GENERATED_INSTANCE> pInstanceProvider,
Map<String, FieldDataProvider<GENERATED_INSTANCE, ?>> pDataProviders,
List<OnGenerateCallbac... | // Given
LoremIpsumFieldDataProvider<TestPerson> loremIpsumFieldDataProvider = mock(LoremIpsumFieldDataProvider.class);
given(mFactory.getLoremIpsumFieldDataProvider(20, 22)).willReturn(loremIpsumFieldDataProvider);
final String EXPECTED_VALUE = "Lorem ipsum and stuff";
given(loremIpsumFieldDataProvider.gener... |
131139519_0 | class Env extends NativeObject implements Closeable {
public Stat stat() {
MDBX_stat rc = new MDBX_stat();
mdbx_env_stat(pointer(), rc, JNI.SIZEOF_STAT);
return new Stat(rc);
}
public Env(String path);
public Env();
public static String version();
private static long create();
public void open(String ... | String path = tmp.newFolder().getCanonicalPath();
try (Env env = new Env()) {
env.open(path);
env.setMapSize(1048576L);
try (Database db = env.openDatabase()) {
db.put(new byte[]{1}, new byte[]{1});
db.put(new byte[]{2}, new byte[]{1});
Stat stat = env.stat();
S... |
131246500_63 | class UZExceptionUtil {
public static UZException getExceptionPlayback(String msg) {
Exception exception = new Exception(UZException.ERR_24 + " " + msg);
UZException uzException = new UZException();
uzException.setErrorCode(UZException.ERR_CODE_24);
uzException.setException(exceptio... | String testMessage = "Test Message";
UZException testException = UZExceptionUtil.getExceptionPlayback(testMessage);
assertNotNull(testException);
assertNotNull(testException.getMessage());
assertNotNull(testException.getException());
assertEquals(testException.getErrorCod... |
131336637_12 | class ExpressionParser {
VariableNode variableNode() {
consume("${");
char c = 0;
StringBuilder varName = new StringBuilder();
Expression defaultExpr = null;
LOOP:
while ((c = la()) >= 0) {
switch (c) {
case 0:
throw... | VariableNode node = new ExpressionParser("${my.var:tacos${my.other.var:42}}").variableNode();
Assertions.assertThat(node).isNotNull();
Assertions.assertThat(node.getVariableName()).isEqualTo("my.var");
Expression defaultExpr1 = node.getDefaultExpression();
assertThat(defaultExpr... |
131477673_6 | class ServerConfiguration {
@Bean
public Server server(){
Server server = new Server();
if(server.getPort()==0){
int nonSecurePort = Integer.valueOf(propertyResolver.getProperty("server.port", propertyResolver.getProperty("port", "8080")));
server.setPort(nonSecurePort)... | assertNotNull(server);
assertEquals(8092,server.getPort());
assertEquals(10,server.getHeartTime());
assertEquals(1000,server.getMaxCount());
assertEquals("127.0.0.1",server.getIp());
assertEquals("dev",server.getTag());
assertEquals("redisProxy",server.getServiceI... |
131537435_0 | class DisjointSet {
protected R find(R e) {
R parent = matches.get(e);
if (parent == null) {
return null;
}
if (!parent.equals(e)) {
R tmp = find(parent);
if (!parent.equals(tmp)) {
parent = tmp;
matches.put(e, par... | Integer root1 = ds.find(0);
Integer root2 = ds.find(1);
assertNotEquals(root1, root2);
for (int i = 0; i < 10; i++) {
assertEquals((i % 2) == 0 ? root1 : root2, ds.find(i));
}
}
} |
131561161_1 | class AkkaEngineProvider implements ReactiveStreamsEngine {
public static AkkaEngine provider() {
AkkaEngine engine = null;
// Double checked locking to initialize the weak reference the first time this method
// is invoked.
if (cachedEngine == null) {
synchronized (mutex) {
if (cached... | AkkaEngine engine = AkkaEngineProvider.provider();
ActorSystem system = ((ActorMaterializer) engine.materializer).system();
Publisher<Done> publisher =
Source.tick(
Duration.create(100, TimeUnit.MILLISECONDS),
Duration.create(100, TimeUnit.MILLISECONDS),
Done.get... |
131745127_9 | class Time {
public static LocalDate parseDate(String date) {
if (date == null) {
throw new IllegalArgumentException("Date must not be null.");
}
String datePattern = "[0-3]?[0-9]-[0-1]?[0-9]-[1-2][0-9]{3}";
if (!date.matches(datePattern)) {
throw ne... | String date = "27-07-2000";
LocalDate parsedDate = Time.parseDate(date);
assertEquals("Failed to parse year from date", 2000, parsedDate.getYear());
assertEquals("Failed to parse month from date", 7, parsedDate.getMonth().getValue());
assertEquals("Failed to parse day from date... |
131759992_13 | class AsyncTrampoline {
public static <T> CompletionStage<T> asyncWhile(
final Predicate<? super T> shouldContinue,
final Function<? super T, ? extends CompletionStage<T>> fn,
final T initialValue) {
return TrampolineInternal.trampoline(shouldContinue, fn, initialValue);
}
private AsyncTr... | Assert.assertEquals(
AsyncTrampoline.<Integer>asyncWhile(
i -> i != null && i < 10,
i -> {
Integer next;
if (i == null) {
next = 5;
} else if (i == 4) {
next = null;
} else {
next ... |
131884789_3 | class Race {
public static void start(Context context, String[] urls, Listener listener) {
Prober prober = new GoProber(context);
start(prober, urls, listener);
}
static void start(Prober prober, String[] urls, Listener listener);
}
class RaceTest {
@Test
public void HalfFail() throws Exception {... | final int N = 7;
String[] urls = new String[N];
for (int i = 0; i < N; ++i) {
urls[i] = String.format("%d", i);
}
Semaphore done = new Semaphore(0);
Race.start(new HalfProber(), urls, (int index) -> {
assertTrue(index >= 0);
assertTrue(index < N);
// Only the even-numbere... |
131964676_7 | class FileSelectorArrayRow extends JPanel {
public static File fallback(File currentDir){
while(!currentDir.exists() && currentDir.getParentFile() != null){
currentDir = currentDir.getParentFile();
}
return currentDir;
}
FileSelectorArrayRow(FileSelectorArrayPanel pa... | final File inputNormal = new File(Directories.getPluginDirectory());
final File inputNormal2 = new File("/sys/kernel");
final File inputNoParent = new File("/");
final File inputNoParentOver = new File("/sys");
final File inputNonExistent = new File(Directories.getXdgJrdBaseDir()... |
132126497_30 | class AttributeValidator extends BaseValidator {
@Override
public ValidationResults validate(Rule rule) {
ValidationResults results = new ValidationResults();
checkEmptyOrNullNames(rule, results);
checkName(rule, results);
checkUniquenessOfAttributes(rule, results);
chec... | // given
Rule rule = new Rule(new LinkedHashSet<>(Arrays.asList(
new Attribute("ruleName", String.class, "ruleName"),
new Attribute("startDate", ZonedDateTime.class, ZonedDateTime.parse("2012-01-05T00:00:00+12:34"))
)), Collections.emptyList(), null, Collections.e... |
132161673_0 | class KafkaComputerLauncher extends ComputerLauncher {
public void setEnableSSL(boolean enableSSL) {
this.enableSSL = enableSSL;
}
public KafkaComputerLauncher();
public KafkaComputerLauncher(String kafkaUsername, String sslTruststoreLocation, String sslKeystoreLocation);
@DataBoundConst... | GlobalKafkaConfiguration g = GlobalKafkaConfiguration.get();
String kafkaURL = kafka.getBootstrapServers().split("//")[1];
String zookeeperURL = kafka.getContainerIpAddress() + ":" + kafka.getMappedPort(2181);
g.setBrokerURL(kafkaURL);
g.setZookeeperURL(zookeeperURL);
g.s... |
132241610_0 | class App implements RequestHandler<Object, Object> {
public Object handleRequest(final Object input, final Context context) {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
headers.put("X-Custom-Header", "application/json");
try {
... | App app = new App();
GatewayResponse result = (GatewayResponse) app.handleRequest(null, null);
assertEquals(result.getStatusCode(), 200);
assertEquals(result.getHeaders().get("Content-Type"), "application/json");
String content = result.getBody();
assertNotNull(content);
... |
132370832_55 | class UnitQueryWithinUnittype {
public static boolean match(
String fixedOp, String varOp, Parameter.Operator op, Parameter.ParameterDataType type) {
// If fixedOp == null, varOp can match only if null and operator is EQ, or the opposite.
if (fixedOp == null) {
return (Parameter.Operator.EQ.equal... | // Given:
final String fixedOp = "1";
final String varOp = "2";
final Parameter.Operator op = Parameter.Operator.LT;
final Parameter.ParameterDataType dataType = Parameter.ParameterDataType.NUMBER;
// When:
boolean match = UnitQueryWithinUnittype.match(fixedOp, varOp, op, dataType);
//... |
132376292_19 | class CloudflareAccessService {
public void processAuthRequest(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
try {
if(isRequestFilteringDisabled()) {
log.debug("Plugin filters are disabled or not configured yet, bypassing auth process");
... | HttpServletRequest httpRequest = mock(HttpServletRequest.class);
when(httpRequest.getHeader(CloudflareToken.CF_ACCESS_JWT_HEADER)).thenReturn(authContext.getValidToken());
when(httpRequest.getRequestURI()).thenReturn(AuthenticationErrorServlet.PATH);
HttpServletResponse httpResponse = mock(HttpServletResponse.... |
132562896_2 | class RefererService {
public String buildRedirectUri(String referer, String targetPath) {
if(isInvalidTargetPath(targetPath)) {
throw new BadTargetPathException("Illegal target_path");
}
return UriComponentsBuilder.fromUriString(referer)
.replacePath(targetPath... | String redirectUri = refererService.buildRedirectUri("http://my_custom_referer", "/my_custom_path");
assertThat(redirectUri, is(equalTo("http://my_custom_referer/my_custom_path")));
}
} |
132573384_9 | class SongPublicationService {
public void publishSong(final Song song) {
songsRepository.storeSong(song);
publicationNotifier.onSongPublished(song);
}
public Optional<Song> getSong(final String songIdentifier);
private static final Song SONG;
@Mock
private SongsRepository son... | songPublicationService.publishSong(SONG);
verify(songsRepository).storeSong(SONG);
verify(publicationNotifier).onSongPublished(SONG);
}
} |
132587382_43 | class Partner {
public static synchronized Partner get(Context context) {
if (!sSearched) {
PackageManager pm = context.getPackageManager();
final Intent intent = new Intent(ACTION_PARTNER_CUSTOMIZATION);
List<ResolveInfo> receivers;
if (VERSION.SDK_INT >= VE... | Partner partner = Partner.get(mContext);
assertNull("Partner should be null", partner);
}
} |
132600378_21 | class CommentUtils {
public static boolean isEndMatchWithInlineCommentedCDATA(String trimmedContent)
{
if (trimmedContent.endsWith(CDATA_SIMPLE_END))
{
int offset = trimmedContent.length()- 4;
while (trimmedContent.charAt(offset) <= ' ' &&
trimmedCont... | org.junit.Assert.assertTrue(CommentUtils.isEndMatchWithInlineCommentedCDATA("fkdjslkfjsl //"+CommentUtils.CDATA_SIMPLE_END));
org.junit.Assert.assertTrue(CommentUtils.isEndMatchWithInlineCommentedCDATA("fkdjslkfjsl // "+CommentUtils.CDATA_SIMPLE_END));
org.junit.Assert.assertTrue(CommentUtils.is... |
132620967_162 | class PropertyUtils {
public static String stringProperty(Configuration conf, Property property) {
return conf.get(property.key(), (String) property.defaultValue());
}
private PropertyUtils();
public static boolean booleanProperty(Configuration conf, Property property);
public static int intProperty(C... | when(property.key()).thenReturn("unset");
when(property.defaultValue()).thenReturn("default");
assertThat(stringProperty(conf, property)).isEqualTo("default");
}
} |
132733058_1 | class SkeletonBuffer {
@Override
public String toString() {
if (document.getFxomRoot() == null) {
return I18N.getString("skeleton.empty");
} else {
construct();
StringBuilder code = new StringBuilder();
code.append(header);
code.appen... | EditorController editorController = new EditorController();
final URL fxmlURL = SkeletonBufferTest.class.getResource("ControllerWithSimplePackage.fxml");
final String fxmlText = FXOMDocument.readContentFromURL(fxmlURL);
editorController.setFxmlTextAndLocation(fxmlText, fxmlURL, false);
... |
132811956_1179 | class OlapUnitResourceConverter extends ResourceConverterImpl<OlapUnit, ClientOlapUnit> {
@Override
protected ClientOlapUnit resourceSpecificFieldsToClient(ClientOlapUnit client, OlapUnit serverObject,
ToClientConversionOptions options) {
client.setMdxQuery(serverObject.getMdxQuery());
... | ClientOlapUnit clientObject = new ClientOlapUnit();
OlapUnit serverObject = new OlapUnitImpl();
serverObject.setMdxQuery(EXPECTED_MDX_QUERY);
serverObject.setOlapClientConnection(serverConnection);
final ClientOlapUnit result = converter.resourceSpecificFieldsToClient(clientObjec... |
132873186_1 | class InsertedMethods {
static boolean endsWith(String str, int len, int hashCode) {
if (str.length() < len) return false;
return str.substring(str.length() - len).hashCode() == hashCode;
}
public static boolean startsWith(String str, int len, int hashCode);
}
class InsertedMethodsTest ... | assertTrue(InsertedMethods.endsWith("ich hasse Menschen", "Menschen".length(), "Menschen".hashCode()));
assertTrue(InsertedMethods.endsWith("hasse", "hasse".length(), "hasse".hashCode()));
assertFalse(InsertedMethods.endsWith("cancer", "aidsfgd".length(), "aidsfgd".hashCode()));
}
} |
132938098_42 | class StringHelper {
public static String truncate(String input, int length)
{
if (input != null)
{
if (input.length() > length)
{
return input.substring(0, length);
}
else
{
return input;
}
}
else
{
return null;
}
}
private St... | // Tests the suite of truncate methods
assertEquals("This", StringHelper.truncate(sentence, 4));
assertEquals("Foo", StringHelper.truncate("Foo", 4));
assertNull(StringHelper.truncate(null, 50));
assertEquals("nce.", StringHelper.truncateAtEnd(sentence, 4));
assertEquals("Foo", StringH... |
132952801_3 | class GraphQLTemplate {
public <T> GraphQLResponseEntity<T> mutate(GraphQLRequestEntity requestEntity, Class<T> responseClass) throws GraphQLException {
return execute(GraphQLMethod.MUTATE, requestEntity, responseClass);
}
public GraphQLTemplate();
public GraphQLTemplate(final ObjectMapperFa... | server.enqueue(new MockResponse().setBody("{\n" +
" \"data\": {\n" +
" \"test\": {\n" +
" \"testString\": \"String\"\n" +
" }\n" +
" }," +
" \"errors\": null" +
"}"
));
s... |
133016017_1 | class Puller {
void pull(String elementId,
Queue<Item> queue,
CompletableFuture resultFuture,
int count) {
dbClient.getNextAfterId(elementId)
.thenAccept(item -> {
if (isValid(item)) {
queue.offer(item);
if (queue.size() == count) {
resultFuture.co... | CountDownLatch l = new CountDownLatch(1);
Puller puller = new Puller();
CompletionStage<Queue<Item>> list = puller.list(10);
list.thenAccept(q -> {
MatcherAssert.assertThat(q, Matchers.allOf(
Matchers.hasSize(10),
Matchers.contains(
Matchers.hasProperty("id", Matchers.equalTo("2")),
... |
133022875_117 | class SumFunction extends AggregateFunction<JsonNode, Double> {
@Override
public Double compute() {
return sum;
}
@Override public AggregateFunction addValue(JsonNode value);
@Override public AggregateFunction<JsonNode, Double> merge(AggregateFunction<JsonNode, Double> newValue);
}
class... | SumFunction sumFunction =new SumFunction();
assertThat(sumFunction.compute()).isEqualTo(0);
}
} |
133025905_1 | class CrawlStatusUpdaterBolt extends AbstractStatusUpdaterBolt implements
RemovalListener<String, List<Tuple>>, BulkProcessor.Listener {
protected String getIndexName(Metadata md) {
String crawlId = md.getFirstValue("n52.crawl.id");
return indexName.replace("*", crawlId.toLowerCase());
}
... | String statusIndex = "crawlstatus";
CrawlStatusUpdaterBolt bolt = new CrawlStatusUpdaterBolt(statusIndex);
Metadata md = new Metadata();
md.setValue("n52.crawl.id", "tEstCrawl");
assertEquals(bolt.getIndexName(md), "crawlstatus");
}
} |
133030793_0 | class SimpleSelector extends AbstractSelector {
@SuppressWarnings("unchecked")
public void registerCandidates(Class<?> candidateType, Set candidates) {
Collection existed = this.candidatesByType.get(candidateType);
if (existed == null) {
this.candidatesByType.put(candidateType, candidates);
} else {
exis... | // Given
SimpleSelector simpleSelector = new SimpleSelector();
Set<Handler> handlers = new HashSet<>();
handlers.add(new NoAnno1Handler());
handlers.add(new NoAnno2Handler());
simpleSelector.registerCandidates(Handler.class, handlers);
// When
Handler winner = simpleSelector.select(new Object(), Handle... |
133047162_129 | class Message {
public Optional<String> header(final String name) {
if ( name == null ) {
throw new NullPointerException("null name");
}
return headers(name).stream().findFirst();
}
private T self();
public abstract String item();
public abstract Request request();
public R map(final Function<T, R> m... | assertThat(new MessageMock()
.header("TEST-header", "value")
)
.hasHeader("test-header", "value");
}
} |
133134007_2489 | class ApiClient extends JavaTimeFormatter {
public List<Pair> parameterToPairs(String collectionFormat, String name, Object value){
List<Pair> params = new ArrayList<Pair>();
// preconditions
if (name == null || name.isEmpty() || value == null) return params;
Collection valueCollection;
if (val... | Map<String, String> collectionFormatMap = new HashMap<String, String>();
collectionFormatMap.put("csv", ",");
collectionFormatMap.put("tsv", "\t");
collectionFormatMap.put("ssv", " ");
collectionFormatMap.put("pipes", "\\|");
collectionFormatMap.put("", ","); // no format... |
133145968_1 | class MembershipRecord implements Externalizable {
public boolean isOverrides(MembershipRecord r0) {
if (r0 == null) {
return isAlive() || isLeaving();
}
if (!Objects.equals(member.id(), r0.member.id())) {
throw new IllegalArgumentException("Can't compare records for different members");
... | MembershipRecord r1Dead1 = new MembershipRecord(member, DEAD, 1);
assertFalse(r1Dead1.isOverrides(r0Null));
assertTrue(r1Dead1.isOverrides(r0Alive0));
assertTrue(r1Dead1.isOverrides(r0Alive1));
assertTrue(r1Dead1.isOverrides(r0Alive2));
assertTrue(r1Dead1.isOverrides(r0Suspect0));
assertT... |
133151090_2 | class EventManager implements IEventManager {
public boolean hasEventHandler(Class eventHandlerClass) {
Optional<IEventHandler> eventHandler = getEventHandlers().stream().filter(h -> h.getClass().getName().equalsIgnoreCase(eventHandlerClass.getName())).findFirst();
return eventHandler.isPresent();
... | Assertions.assertTrue(eventManager.hasEventHandler(SimpleEventHandler.class), "should fine a eventHandler for class SimpleEventHandler");
}
} |
133386452_9 | class QRCodeUtils {
public static String createHotspotInfo(String ssid, int port, String password) throws JSONException {
JSONObject hotspotQRCode = new JSONObject();
hotspotQRCode.put(SSID, ssid);
hotspotQRCode.put(PORT, port);
if (password == null) {
hotspotQRCode.put... | String ssid = "DeviceSSID";
int port = 3;
String password = "password";
String hotspotInfo = QRCodeUtils.createHotspotInfo(ssid, port, password);
JSONObject hotspotInfoJson = new JSONObject(hotspotInfo);
assertTrue(hotspotInfoJson.get(QRCodeUtils.SSID).equals(ssid));
... |
133447770_225 | class DefaultMediaClock implements MediaClock {
@Override
public PlaybackParameters setPlaybackParameters(PlaybackParameters playbackParameters) {
if (rendererClock != null) {
playbackParameters = rendererClock.setPlaybackParameters(playbackParameters);
}
standaloneMediaClock.setPlaybackParameter... | mediaClock.setPlaybackParameters(TEST_PLAYBACK_PARAMETERS);
mediaClock.setPlaybackParameters(TEST_PLAYBACK_PARAMETERS);
verify(listener, times(2)).onPlaybackParametersChanged(TEST_PLAYBACK_PARAMETERS);
}
} |
133448635_2 | class BaseSwitchController implements SwitchController {
protected static HashMap<String, String> mapSimpleTable(
String rawPacket, String[] colNames, String[] mapNames) {
HashMap<String, String> colMap = new HashMap<>();
String[] lines = rawPacket.split("\n");
int headerLine = 0;
if (lines.len... | String raw = "Port Name Status Vlan Duplex Speed Type\n"
+ "Gi1/0/1 connected routed a-full a-100 10/100/1000BaseTX";
String[] colNames = {"Port", "Name", "Status", "Vlan", "Duplex", "Speed", "Type"};
String[] mapNames = {"i... |
133662794_5 | class GeoHashUtil {
public static List<String> coverBoundingBox(String geometryWKT, int length) {
List<String> list = new ArrayList<>();
Geometry geometry;
try {
geometry = reader.read(geometryWKT);
// returns the bounding box
Envelope e = geometry.getEnvelopeInternal();
Coverage c = GeoHash.coverB... | List<String> results = GeoHashUtil.coverBoundingBox(52.449732623925755,113.309593200683594,52.45559096922489,3.3178329467773445, 5);
String[] resultArr = results.toArray(new String[results.size()]);
System.out.println(results);
String[] expectedArr = new String[] { "9yzf6", "9yzf7", "9yzfd", "9yzfe", "9yzff", "... |
133752946_16 | class RedisMsInstService implements IMsInstService {
@Override
public Boolean removeMsInst(Long instId) {
String key = String.valueOf(instId);
TacInst tacInst = hashOperations.get(getMainKey(), key);
if (tacInst != null) {
hashOperations.delete(getMainKey() + tacInst.getMsC... | Boolean success = redisMsInstService.removeMsInst(1L);
assertTrue(success);
TacInst tacMsInst = redisMsInstService.getTacMsInst(1L);
assertNull(tacMsInst);
}
} |
133753413_102 | class InjectSetter {
public InjectSetter(Inject inject)
{
this.inject = inject;
}
public InjectSetter(Inject inject);
public void injectSetter(ClassFile targetClass, Class<?> targetApiClass, Field field, String exportedName, Number setter);
public int getInjectedSetters();
}
class InjectSetterTest {
@Te... | Inject inject = mock(Inject.class);
when(inject.findImportMethodOnApi(any(Class.class), anyString(), any(Boolean.class)))
.thenReturn(APIClass.class.getDeclaredMethod("setTest", int.class));
when(inject.createLoadForTypeIndex(any(Instructions.class), any(Type.class), anyInt()))
.thenReturn(mock(Instructio... |
133849229_5 | class Elasticsearch implements SearchPlatform {
@Override
public boolean isSearchPlatformConfiguration(String indexName, File file) {
return file.isFile() && file.getName().equals("index-shape.json");
}
@Override public void beforeStart(final Map<String, Object> configuration);
@Override p... | File configFile = tempFolder.newFile("index-shape.json");
assertTrue(platform.isSearchPlatformConfiguration(INDEX_NAME, configFile));
}
} |
134143184_310 | class SystemService {
public void replaceAnchor(byte[] anchorBytes) throws InvalidAnchorInstanceException, AnchorUploadException,
MalformedAnchorException, ConfigurationDownloadException,
ConfigurationVerifier.ConfigurationVerificationException {
uploadAnchor(anchorBytes, true);
... | byte[] anchorBytes = FileUtils.readFileToByteArray(ANCHOR_FILE);
try {
systemService.replaceAnchor(anchorBytes);
} catch (Exception e) {
fail("Should not fail");
}
}
} |
134160731_57 | class ExpressionConfigSourceInterceptor implements ConfigSourceInterceptor {
@Override
public ConfigValue getValue(final ConfigSourceInterceptorContext context, final String name) {
return getValue(context, name, 1);
}
private ConfigValue getValue(final ConfigSourceInterceptorContext context, ... | SmallRyeConfig config = buildConfig("my.prop", "1234", "expression", "${my.prop}${my.prop}");
assertEquals("12341234", config.getValue("expression", String.class));
}
} |
134287037_0 | class WorkflowFacade {
public <T extends DiagramElement> Optional<T> findDiagramElement(EObject semanticElement, Class<T> clazz) {
return findDiagramElement(semanticElement).map(elem -> safeCast(elem, clazz));
}
public WorkflowFacade(Resource coffeeResource, Resource notationResource);
public Resource getSema... | Resource coffeeResource = loadResource("SuperBrewer3000.coffee");
Resource notationResource = loadResource("SuperBrewer3000.coffeenotation");
WorkflowFacade facade = new WorkflowFacade(coffeeResource, notationResource);
Machine machine = (Machine) coffeeResource.getContents().get(0);
Workflow workflow = mach... |
134362666_15 | class RMap extends RCollection {
public void putTTL(String key, String mkey, byte[] value, int ttl) throws KitDBException {
byte[] mkey_b = mkey.getBytes(charset);
checkTxStart();
try (CloseLock ignored = checkClose()) {
byte[] key_b = getKey(key);
LockEntity lockEnt... | String head = "putTTL0";
RMap map = db.getMap();
int num = 10 * 10000;
try {
log.debug("start");
for (int i = 0; i < num; i++) {
map.putTTL(head, "hello" + i, ("world" + i).getBytes(), 4);
if (i == num - 10) {
T... |
134390462_249 | class BasicSoundPlayer implements Runnable, SoundPlayer {
@Override
public AudioInputStream getAudioStream() {
return this.audioStream;
}
protected BasicSoundPlayer(byte[] audioData, AudioFormat format, int loopCount);
@Override public void run();
private void runListener();
@Override public void start();
... | byte[] in = new byte[getFormat().getFrameSize() * 100];
byte[] out = new byte[in.length];
fillBuffer(in);
BasicSoundPlayer player = new BasicSoundPlayer(in, getFormat(), 1);
try (AudioInputStream ais = player.getAudioStream()) {
player.start();
int amount = readAll(out, ais);
Assertions.assertEqu... |
134450682_60 | class LinkageProblemCauseAnnotator {
public static void annotate(
ClassPathBuilder classPathBuilder,
ClassPathResult rootResult,
Iterable<LinkageProblem> linkageProblems)
throws IOException {
checkNotNull(classPathBuilder);
checkNotNull(rootResult);
checkNotNull(linkageProblems);
... | DependencyGraphBuilder dependencyGraphBuilder =
new DependencyGraphBuilder(
ImmutableList.of(
"https://repo.spring.io/milestone", RepositoryUtility.CENTRAL.getUrl()));
ClassPathBuilder classPathBuilderWithSpring = new ClassPathBuilder(dependencyGraphBuilder);
// io.proj... |
134457882_12 | class HashUtils {
public static String byte2hex(byte[] byteArray) {
StringBuilder sb = new StringBuilder();
for (byte b : byteArray) {
sb.append(String.format("%02X", b));
}
return sb.toString();
}
public static byte[] getShaHash(String input);
public static byte[] hashPassword(String pa... | byte[] byteArray = new byte[1];
byteArray[0] = -1;
assertEquals("FF", HashUtils.byte2hex(byteArray));
}
} |
134469679_364 | class RecordWriter {
public static void putFromJson(final String json, final Record record) {
final JsonObject jsonObject = gson.fromJson(json, JsonObject.class);
// JSON data from CCL is presumed to be all upper-case
final String recordNameUpper = record.getName().toUpperCase(Locale.getDef... | final String json = "{\"REPLY\":{\"VAR_LIST\":[{\"F8_FIELD\":987.654000},{\"F8_FIELD\":321.098000}]}}";
final Structure listStructure = mockStructure(F8_FIELD);
final Field listField = mockField("VAR_LIST", DataType.DYNAMIC_LIST, listStructure);
when(listField.getListSize()).thenReturn(... |
134503849_73 | class SiteToSiteSender {
public TransactionCompletion sendFiles() throws IOException {
Transaction transaction = siteToSiteClient.createTransaction(TransferDirection.SEND);
try {
DataPacketDto.getDataPacketStream(input).forEachOrdered(d -> {
try {
tra... | DataPacketDto dataPacketDto = new DataPacketDto("test-data".getBytes(StandardCharsets.UTF_8)).putAttribute("key", "value");
objectMapper.writeValue(data, Arrays.stream(new DataPacketDto[]{dataPacketDto}).collect(Collectors.toList()));
assertEquals(transactionCompletion, senderSupplier.get().send... |
134537813_83 | class BufferStreamApi extends BaseStreamApi implements NeovimBufferApi {
@Override
public CompletableFuture<Object> getVar(String name) {
return sendWithGenericResponse(
prepareMessage(GET_VAR).addArgument(name)
);
}
public BufferStreamApi(ReactiveRpcStreamer reactiveR... | // Happy case
var varVal = "value";
assertNormalBehavior(
() -> CompletableFuture.completedFuture(new ResponseMessage(1, null, varVal)),
() -> bufferStreamApi.getVar("name"),
request -> assertMethodAndArguments(request, NeovimBufferApi.GET_VAR, buf... |
134601948_44 | class X509SvidValidator {
public static void verifyChain(
@NonNull final List<X509Certificate> chain,
@NonNull final BundleSource<X509Bundle> x509BundleSource)
throws CertificateException, BundleNotFoundException {
val trustDomain = CertificateUtils.getTrustDomain(chain... | HashSet<X509Certificate> x509Authorities = new HashSet<>();
x509Authorities.add(otherRootCa.getCertificate());
val x509Bundle = new X509Bundle(TrustDomain.of("example.org"), x509Authorities);
try {
X509SvidValidator.verifyChain(chain, x509Bundle);
fail("exception... |
134685359_4 | class YamlSourceFormatter {
public String format(String source) {
return format(source, null);
}
public String format(String source, YamlSourceFormatterConfig config);
private String appendOrphanedComments(String result, CommentsRescueContext context, SnakeYamlConfig internalConfig);
priva... | /* prepare */
String source = "# I am line 1\napiVersion: v1\n# I am line 3\nkind: Pod\nmetadata:\n name: busybox-sleep";
String expected = "# I am line 1\napiVersion: v1\n# I am line 3\nkind: Pod\nmetadata:\n name: busybox-sleep";
/* execute */
String result = formatt... |
134724121_6 | class AnnotationELPProcessor {
static String buildNonBooleanOutcomeMessage(Object outcome, String expression) {
return "Expression " + expression + " should evaluate to boolean but evaluated to " +
(outcome == null? " null" : (outcome.getClass() + " " + outcome));
}
public static Stri... | String msg = AnnotationELPProcessor.buildNonBooleanOutcomeMessage(null, "abc");
assertEquals("Expression abc should evaluate to boolean but evaluated to null", msg);
}
} |
134827539_27 | class GattCallbackLogger implements LogControl {
public void onServicesDiscovered(BluetoothGatt gatt,
int status) {
if (loggingEnabled) {
final String methodName = "onServicesDiscovered()";
int index = 1;
int max = 3;
lo... | cut.setLoggingEnabled(false);
cut.onServicesDiscovered(gatt, 1);
verifyLogNotCalled();
cut.setLoggingEnabled(true);
cut.onServicesDiscovered(gatt, 1);
verifyLogEngine().log(Mockito.anyString());
}
} |
134843777_1 | class PdfContentImagePreprocessor {
public boolean removeImagesAlphaChannel(PDDocument document) {
this.document = document;
imagesWereChanged = false;
try {
removeImagesAlphaChannelUnsafe();
return imagesWereChanged;
} catch (Exception e) {
retur... | InputStream stream = AlterPDFParserTest.class.getResourceAsStream("/test-documents/transp_scanned.pdf");
PDDocument doc = PDDocument.load(stream);
PdfContentImagePreprocessor preproc = new PdfContentImagePreprocessor();
boolean hasReplaced = preproc.removeImagesAlphaChannel(doc);
... |
134900749_22 | class OpenMetricsExporter implements Exporter {
@Override
public StringBuilder exportOneMetric(MetricRegistry.Type scope, MetricID metricID) {
alreadyExportedNames.set(new HashSet<>());
MetricRegistry registry = MetricRegistries.get(scope);
Map<MetricID, Metric> metricMap = registry.get... | OpenMetricsExporter exporter = new OpenMetricsExporter();
MetricRegistry baseRegistry = MetricRegistries.get(MetricRegistry.Type.BASE);
Gauge gauge = new MGaugeImpl(JmxWorker.instance(), "java.lang:type=Runtime/Uptime");
Metadata metadata = new ExtendedMetadata("jvm.uptime", "display na... |
134901201_9 | class FilteredIndexView implements IndexView {
public boolean accepts(DotName className) {
final boolean accept;
final MatchHandler match = new MatchHandler(className);
if (match.isQualifiedNameExcluded()) {
/*
* A FQCN or pattern that *fully* matched the FQCN was ... | Map<String, Object> properties = new HashMap<>();
properties.put(OASConfig.SCAN_CLASSES, "(?:pkgA.My(Bean|Class))$");
properties.put(OASConfig.SCAN_EXCLUDE_PACKAGES, "com.example");
OpenApiConfig config = IndexScannerTestBase.dynamicConfig(properties);
FilteredIndexView view = ne... |
134973177_0 | class StringUtil {
@Nullable
public static String compressText(String text) {
String repeatedSequence = "";
int maxRepeat = 0;
String[] split = text.split("\n");
for (String s1 : split) {
int repeat = 0;
for (String s2 : split) {
if (!"".... | Assert.assertEquals("【悲報】", StringUtil.compressText("【悲報】\n【悲報】\n【悲報】\n【悲報】"));
Assert.assertEquals("【悲報】", StringUtil.compressText("【悲報】 \n【悲報】\n【悲報】 \n【悲報】 "));
Assert.assertNull(StringUtil.compressText("【悲報】\n【悲報】\n【悲報】"));
Assert.assertEquals("[゚д゚]", StringUtil.compressText("[... |
135174794_16 | class SlangSensor implements Sensor {
@Override
public void execute(SensorContext sensorContext) {
DurationStatistics statistics = new DurationStatistics(sensorContext.config());
FileSystem fileSystem = sensorContext.fileSystem();
FilePredicate mainFilePredicate = fileSystem.predicates().and(
fil... | InputFile inputFile = createInputFile("file1.slang", "" +
"fun f() { print(\"string literal\"); print(\"string literal\"); print(\"string literal\"); }");
context.fileSystem().add(inputFile);
CheckFactory checkFactory = checkFactory("S1192");
sensor(checkFactory).execute(context);
Collection<I... |
135205277_5 | class DispatchManager extends Thread {
public synchronized void subscribe(String name, DispatchChannel dispatchChannel) {
Optional<DispatchChannel> previous = Optional.fromNullable(subscriptions.get(name));
subscriptions.put(name, dispatchChannel);
try {
pubSubConnection.subscribe(name);
} cat... | DispatchChannel fooChannel = mock(DispatchChannel.class);
DispatchChannel barChannel = mock(DispatchChannel.class);
dispatchManager.subscribe("foo", fooChannel);
dispatchManager.subscribe("bar", barChannel);
pubSubReplyInputStream.write(new PubSubReply(PubSubReply.Type.SUBSCRIBE, "foo", Optional.<... |
135256100_4 | class CssRuleSensor implements Sensor {
@Override
public void execute(SensorContext context) {
reportOldNodeProperty(context);
List<InputFile> inputFiles = getInputFiles(context);
if (inputFiles.isEmpty()) {
LOG.info("No CSS, PHP, HTML or VueJS files are found in the project. CSS analysis is ski... | addInputFile("invalid-json-response.css");
sensor.execute(context);
assertThat(String.join("\n", logTester.logs(LoggerLevel.DEBUG)))
.contains("Failed to parse response");
assertThat(String.join("\n", logTester.logs(LoggerLevel.ERROR)))
.contains("Failure during CSS analysis");
}
} |
135262635_18 | class RSQLQueryDslSupport extends RSQLJPASupport {
public static BooleanExpression toPredicate(final String rsqlQuery, final Path qClazz) {
return toPredicate(rsqlQuery, qClazz, null);
}
public RSQLQueryDslSupport();
public RSQLQueryDslSupport(Map<String, EntityManager> entityManagerMap);
public static Bool... | String rsql = "name=notlike='ber'";
List<User> users = (List<User>) userRepository.findAll(toPredicate(rsql, QUser.user));
long count = users.size();
log.info("rsql: {} -> count: {}", rsql, count);
assertThat(rsql, count, is(8l));
rsql = "company.name=notlike='Inc'";
users = (List<User>) userRepository.f... |
135270285_2 | class FileUtil {
public static BufferedWriter asBufferedWriter(String fileName) throws IOException {
Validate.notBlank(fileName, "filename is blank");
return Files.newBufferedWriter(getPath(fileName), Charsets.UTF_8);
}
public static byte[] toByteArray(final File file);
public static String toString(final Fil... |
Path tempPath = FileUtil.createTempFile();
try (BufferedWriter bw = FileUtil.asBufferedWriter(tempPath.toString())) {
assertThat(bw).isNotNull();
}
try (BufferedWriter bw = FileUtil.asBufferedWriter(tempPath)) {
assertThat(bw).isNotNull();
}
}
} |
135332674_4 | class DecrypterManager {
public synchronized void decryptSaved(CapillaryHandler handler, Object extra) {
List<byte[]> ciphertexts = ciphertextStorage.get();
ciphertextStorage.clear();
for (byte[] data : ciphertexts) {
decrypt(data, handler, extra);
}
}
DecrypterManager(
Context con... | // Lock the screen.
when(utils.isScreenLocked(context)).thenReturn(true);
// No saved ciphertexts.
decrypterManager.decryptSaved(handler, extra);
verifyZeroInteractions(handler);
// Save ciphertexts.
int ciphertextCount = 10;
ciphertextBuilder.setIsAuthKey(true);
byte[] ciphertextB... |
135337255_5 | class OrderBook {
public SortedSet<WorkingOrder> findMatches(WorkingOrder order) {
// Matching only compares price on the opposite side, not entry time
MatchingOrderDecorator compare = new MatchingOrderDecorator(order, order.getSource());
SortedSet<WorkingOrder> matches = null;
switch (order.getSide(... | Instant entryTime1 = clock.instant();
final WorkingOrder order1 = new WorkingOrder(
new TestOrder("C1", symbol, Side.Sell, 3, OrdType.Limit, new BigDecimal("12.95")), userId,
"Order" + 1, entryTime1);
orderBook.addOrder(order1);
Instant entryTime2 = clock.instant();
final WorkingOrd... |
135401010_56 | class DefaultObjectFactory implements ObjectFactory, Serializable {
@Override
public <T> T create(Class<T> type) {
return create(type, null, null);
}
@SuppressWarnings("unchecked") @Override public T create(Class<T> type, List<Class<?>> constructorArgTypes, List<Object> constructorArgs);
@Override publi... | DefaultObjectFactory defaultObjectFactory = new DefaultObjectFactory();
SortedSet sortedSet = defaultObjectFactory.create(SortedSet.class);
Assert.assertTrue(" sortedSet should be TreeSet", sortedSet instanceof TreeSet);
}
} |
135418301_0 | class Parse {
public static HashMap<String, Integer> parseJ48(String treeResult)
{
HashMap<String, Integer> hm = new HashMap<String, Integer>();
//Split the string at each new line char (Regex to take into account different line end chars depending on OS)
String[] lines = treeResult.spl... | System.out.println("parseJ48");
String treeResult = "J48 pruned tree\r\n------------------\r\n\r\n"
+ "GP: physician-fee-freeze = n: democrat (253.41/3.75)\r\n"
+ "GP: physician-fee-freeze = y\r\n"
+ "| GP: synfuels-corporation-cutback = n: republican (145.71/4.0)\r... |
135513706_41 | class ChordStructureGenerator implements IChordStructureGenerator {
public List<ProgressionType> getProgressionTypes(QueueItem queueItem) {
List<ProgressionType> progressionTypes = new ArrayList<ProgressionType>();
for (ProgressionUnit progressionUnit : queueItem.getProgression().getStructure()) ... |
setupTest();
List<ProgressionUnit.ProgressionType> progressionTypes = chordStructureGenerator.getProgressionTypes(mQueueItem);
List<ProgressionUnit.ProgressionType> expected = new ArrayList<ProgressionUnit.ProgressionType>();
expected.add(ProgressionUnit.ProgressionType.VERSE);
... |
135566897_8 | class AbstractAnsibleRulesDefinition implements RulesDefinition {
protected abstract String getRuleDefinitionPath()protected abstract String getRuleDefinitionPath();
protected abstract String getRuleDefinitionPath()@Override public void define(RulesDefinition.Context context);
protected abstract String getRuleDefinit... | AbstractAnsibleRulesDefinition definition = new AnsibleExtraRulesDefinition();
assertEquals("org/sonar/l10n/ansible/rules/ansible-extras", definition.getRuleDefinitionPath());
testDefineWithExistingRules(definition, true);
}
} |
135579677_293 | class BooleanResponse extends FFDCResponseBase {
@Override
public boolean equals(Object objectToCompare)
{
if (this == objectToCompare)
{
return true;
}
if (!(objectToCompare instanceof BooleanResponse))
{
return false;
}
if (!... | Map<String, Object> propertyMap;
BooleanResponse testObject = new BooleanResponse();
assertTrue(testObject.getExceptionProperties() == null);
propertyMap = null;
testObject = new BooleanResponse();
testObject.setExceptionProperties(propertyMap);
assertT... |
135676228_1 | class BaseConfigurationFactory implements ConfigurationFactory<T, U> {
@Override
public Pair<T, U> build(ConfigurationSourceProvider provider, String path) throws IOException, ConfigurationException {
try (InputStream input = provider.open(requireNonNull(path))) {
final JsonNode node = obje... | try {
factory.build(emptyFile);
failBecauseExceptionWasNotThrown(ConfigurationParsingException.class);
} catch (ConfigurationParsingException e) {
assertThat(e.getMessage())
.containsOnlyOnce(" * GJEXConfiguration at " + emptyFile.toString() + " mu... |
135796936_4 | class BookController {
@PostMapping
public ResponseEntity<Void> createNewBook(@Valid @RequestBody BookRequest bookRequest, UriComponentsBuilder uriComponentsBuilder) {
Long primaryKey = bookService.createNewBook(bookRequest);
UriComponents uriComponents = uriComponentsBuilder.path("/api/books/{id}").build... |
BookRequest bookRequest = new BookRequest();
bookRequest.setAuthor("Duke");
bookRequest.setIsbn("1337");
bookRequest.setTitle("Java 11");
when(bookService.createNewBook(bookRequestArgumentCaptor.capture())).thenReturn(1L);
this.mockMvc
.perform(post("/api/books")
.contentType(Me... |
135928914_9 | class TicketRegistryDecorator extends AbstractTicketRegistry {
@Override
public int serviceTicketCount() {
if (this.ticketRegistry instanceof TicketRegistryState) {
return ((TicketRegistryState) this.ticketRegistry).serviceTicketCount();
}
logger.debug("Ticket registry {} do... | TicketRegistry registryState = Mockito.mock(TicketRegistry.class, withSettings().extraInterfaces(TicketRegistryState.class));
when(((TicketRegistryState)registryState).serviceTicketCount()).thenReturn(123);
decorator = new TicketRegistryDecorator(registryState, cache);
assertEquals(123, ... |
135972985_19 | class GanderIMDB implements GanderStorage {
public static GanderIMDB getInstance() {
return INSTANCE;
}
private GanderIMDB();
@Override public TransactionDao getTransactionDao();
}
class GanderIMDBTest {
@Test
public void getInstance_shouldReturnSingleton() {
| assertThat(GanderIMDB.getInstance()).isEqualTo(GanderIMDB.getInstance());
}
} |
136013354_0 | class MavlinkPacketReader {
public MavlinkPacket next() throws IOException {
while (in.next()) {
byte[] frame = in.frame();
switch (frame[0] & 0xff) {
case MavlinkPacket.MAGIC_V1:
return MavlinkPacket.fromV1Bytes(frame);
case Mavli... | MavlinkPacket expected = MavlinkPacket.createSignedMavlink2Packet(
0, 0, 0, 0, 0, new byte[255], 0, 0, new byte[32]);
InputStream in = new ByteArrayInputStream(expected.getRawBytes());
MavlinkPacketReader reader = new MavlinkPacketReader(in);
MavlinkPacket actual = reade... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.