auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public String getRequestUri() { START return wrapped.getRequestPath(); END } please leave it that way - it's intentionally referencing the deprecated version.

Target:
public String getRequestUri() { return wrapped.getRequestUri(); }
Source:
public TemplateEngineFreemarkerAuthenticityTokenDirective(Context context) { START this.authenticityToken = context.getSession().getAuthenticityToken(); END } please do this in the execute method. Otherwise you are always adding the __AT to the session - even if it is not needed...

Target:
public TemplateEngineFreemarkerAuthenticityTokenDirective(Context context) { this.context = context; }
Source:
START public void clearLevel(String loggerName) END { java.util.logging.Logger logger = loggers.get(loggerName); if (logger == null) { logger = java.util.logging.Logger.getLogger(loggerName); } logger.setLevel(null); } is `loggerName` `@Nullable`?

Target:
public synchronized void clearLevel(String loggerName) { java.util.logging.Logger logger = loggers.remove(loggerName); if (logger != null) { logger.setLevel(null); } }
Source:
static Binder proxy(Binder binder) { return (Binder) Proxy.newProxyInstance( ForbidInstallBinder.class.getClassLoader(), START new Class[] {Binder.class}, END new ForbidInstallBinder(binder)); } This needs `Class<?>`

Target:
static Binder proxy(Binder binder) { return (Binder) Proxy.newProxyInstance( ForbidInstallBinder.class.getClassLoader(), new Class<?>[] {Binder.class}, new ForbidInstallBinder(binder)); }
Source:
public void testCreateAnnouncementLocation() { URI baseURI = URI.create("http://example.com:8080"); URI baseWithSlash = URI.create("http://example.com:8080/"); String nodeId = "ffff"; URI expected = URI.create("http://example.com:8080/v1/announcement/" + nodeId); START assertEquals(expected, HttpDiscoveryAnnouncementClient.createAnnouncementLocation(baseURI, nodeId)); END assertEquals(expected, HttpDiscoveryAnnouncementClient.createAnnouncementLocation(baseWithSlash, nodeId)); } Static import `createAnnouncementLocation`

Target:
public void testCreateAnnouncementLocation() { String nodeId = "ffff"; URI expected = URI.create("http://example.com:8080/v1/announcement/" + nodeId); assertEquals(createAnnouncementLocation(URI.create("http://example.com:8080"), nodeId), expected); assertEquals(createAnnouncementLocation(URI.create("http://example.com:8080/"), nodeId), expected); }
Source:
public void testCreateAnnouncementLocation() { String nodeId = "ffff"; URI expected = URI.create("http://example.com:8080/v1/announcement/" + nodeId); START assertEquals(expected, createAnnouncementLocation(URI.create("http://example.com:8080"), nodeId)); END assertEquals(expected, createAnnouncementLocation(URI.create("http://example.com:8080/"), nodeId)); } The actual/equals are flipped

Target:
public void testCreateAnnouncementLocation() { String nodeId = "ffff"; URI expected = URI.create("http://example.com:8080/v1/announcement/" + nodeId); assertEquals(createAnnouncementLocation(URI.create("http://example.com:8080"), nodeId), expected); assertEquals(createAnnouncementLocation(URI.create("http://example.com:8080/"), nodeId), expected); }
Source:
private static boolean isPreserveAuthorization(Request request) { START return request.getAttributes().get(PRESERVE_AUTHORIZATION_KEY) == TRUE; END } I'd use `equals` to make it clear we don't care about identity semantics (readers won't have to verify the value that is being set), but it's fine either way ```java TRUE.equals(request.getAttributes().get(PRESERVE_AUTHORIZATION_KEY));

Target:
private static boolean isPreserveAuthorization(Request request) { return TRUE.equals(request.getAttributes().get(PRESERVE_AUTHORIZATION_KEY)); }
Source:
START DecayTDigest(TDigest digest, double alpha, Ticker ticker) END { this(digest, alpha, ticker, TimeUnit.NANOSECONDS.toSeconds(ticker.read())); } `private`? `@VisibleForTesting`?

Target:
private DecayTDigest(TDigest digest, double alpha, Ticker ticker) { this(digest, alpha, ticker, TimeUnit.NANOSECONDS.toSeconds(ticker.read())); }
Source:
public void testEmpty() { List<Object> response = client.execute( prepareGet().setUri(uriFor("/v1/person")).build(), createJsonResponseHandler(listCodec)); START assertEquals(response, Collections.emptyList()); END } `ImmutableList.of()`

Target:
public void testEmpty() { List<Object> response = client.execute( prepareGet().setUri(uriFor("/v1/person")).build(), createJsonResponseHandler(listCodec)); assertEquals(response, ImmutableList.of()); }
Source:
START public DecayTDigest(double compression, double alpha, Ticker ticker) END { digest = new TDigest(compression); this.alpha = alpha; this.ticker = ticker; landmarkInSeconds = TimeUnit.NANOSECONDS.toSeconds(ticker.read()); } should this be package protected?

Target:
DecayTDigest(double compression, double alpha, Ticker ticker) { digest = new TDigest(compression); this.alpha = alpha; this.ticker = ticker; landmarkInSeconds = TimeUnit.NANOSECONDS.toSeconds(ticker.read()); }
Source:
public void testDoesNotAllowCircularDependencies() throws Exception { START Bootstrap bootstrap = new Bootstrap((Module) binder -> { END binder.bind(InstanceA.class); binder.bind(InstanceB.class); }); try { bootstrap.initialize().getInstance(InstanceA.class); fail("should not allow circular dependencies"); } catch (ProvisionException e) { assertContains(e.getErrorMessages().iterator().next().getMessage(), "circular dependencies are disabled"); } } Is the `(Module)` needed?

Target:
public void testDoesNotAllowCircularDependencies() throws Exception { Bootstrap bootstrap = new Bootstrap(binder -> { binder.bind(InstanceA.class); binder.bind(InstanceB.class); }); try { bootstrap.initialize().getInstance(InstanceA.class); fail("should not allow circular dependencies"); } catch (ProvisionException e) { assertContains(e.getErrorMessages().iterator().next().getMessage(), "circular dependencies are disabled"); } }
Source:
public Request(URI uri, String method, ListMultimap<String, String> headers, BodyGenerator bodyGenerator) { this(uri, method, headers, bodyGenerator, true); START } END Add message telling people to use the builder.

Target:
public Request(URI uri, String method, ListMultimap<String, String> headers, BodyGenerator bodyGenerator) { this(uri, method, headers, bodyGenerator, true, false); }
Source:
public static boolean isPem(String data) { START if (CERT_PATTERN.matcher(data).find()) { END return true; } if (PUBLIC_KEY_PATTERN.matcher(data).find()) { return true; } if (PRIVATE_KEY_PATTERN.matcher(data).find()) { return true; } return false; } Why not ```java return CERT_PATTERN.matcher(data).find() || PUBLIC_KEY_PATTERN.matcher(data).find() || PRIVATE_KEY_PATTERN.matcher(data).find();

Target:
public static boolean isPem(String data) { return CERT_PATTERN.matcher(data).find() || PUBLIC_KEY_PATTERN.matcher(data).find() || PRIVATE_KEY_PATTERN.matcher(data).find(); }
Source:
START TestJettyHttpsClientPem() END { super("localhost", getResource("server.keystore").toString()); } Make public since it will be constructed by TestNG (which probably bypasses security just fine but seems bad to rely on that)

Target:
public TestJettyHttpsClientPem() { super("localhost", getResource("server.keystore").toString()); }
Source:
private static HttpServer createServer(NodeInfo nodeInfo, HttpServerInfo httpServerInfo, HttpServerConfig config) { START return createServer(new DummyServlet(Optional.empty()), nodeInfo, httpServerInfo, config); END } This is what the default constructor already does.

Target:
private static HttpServer createServer(NodeInfo nodeInfo, HttpServerInfo httpServerInfo, HttpServerConfig config) { return createServer(new DummyServlet(), nodeInfo, httpServerInfo, config); }
Source:
private void createAndStartServer() throws Exception { START createAndStartServer(new DummyServlet(Optional.empty())); END } Use the default constructor for all of these

Target:
private void createAndStartServer() throws Exception { createAndStartServer(new DummyServlet()); }
Source:
public void tearDown() throws IOException { START if (!file.delete()) { END throw new IOException("Error deleting " + file.getAbsolutePath()); } } Do you want to check `exists`?

Target:
public void tearDown() throws IOException { if (file.exists() && !file.delete()) { throw new IOException("Error deleting " + file.getAbsolutePath()); } }
Source:
private static void closeQuietly(LifeCycle service) { try { if (service != null) { service.stop(); } } START catch (InterruptedException ie) { END Thread.currentThread().interrupt(); } catch (Exception ignored) { } } We can name this `e`, as we do elsewhere. I thought it needed to be `ignored` to prevent a warning, but apparently that's only a problem if the catch block is empty.

Target:
private static void closeQuietly(LifeCycle service) { try { if (service != null) { service.stop(); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (Exception ignored) { } }
Source:
public void flush() { BufferedReader in = new BufferedReader(new StringReader(getBuffer().toString())); while (true) { try { String line = in.readLine(); if (line == null) { break; } if (logger.isInfoEnabled()) { START logger.info(line); END } } catch (IOException e) { throw new Error(e); // should never get here } } getBuffer().setLength(0); } I don't think we need the "if" check. Just always log at info. The logger is going to check enabled anyway.... the "is enabled" is only useful when the log line does work

Target:
public void flush() { BufferedReader in = new BufferedReader(new StringReader(getBuffer().toString())); while (true) { try { String line = in.readLine(); if (line == null) { break; } logger.info(line); } catch (IOException e) { throw new Error(e); // should never get here } } getBuffer().setLength(0); }
Source:
private static byte[] base64Decode(String base64) { START return Base64.getMimeDecoder().decode(base64.getBytes(US_ASCII)); END } You could static import `getMimeDecoder` to match the other file

Target:
private static byte[] base64Decode(String base64) { return getMimeDecoder().decode(base64.getBytes(US_ASCII)); }
Source:
public String toString() { START return MoreObjects.toStringHelper(this) END .add("configurationBinding", configurationBinding) .toString(); } Static import

Target:
public String toString() { return toStringHelper(this) .add("configurationBinding", configurationBinding) .toString(); }
Source:
public synchronized void onComplete(Result result) { Throwable throwable = result.getFailure(); if (throwable != null) { future.failed(throwable); } else { START currentBuffer = null; END currentBufferPosition = 0; future.completed(result.getResponse(), new GatheringByteArrayInputStream(buffers, size)); } } Set `currentBuffer` to `new byte[0]` so `currentBuffer` is never null. This is a common trick to consolidate all checks to size checks (without nulls), but you have to be careful to not add the zero byte array to your outputs :)

Target:
public synchronized void onComplete(Result result) { Throwable throwable = result.getFailure(); if (throwable != null) { future.failed(throwable); } else { currentBuffer = new byte[0]; currentBufferPosition = 0; future.completed(result.getResponse(), new GatheringByteArrayInputStream(buffers, size)); buffers = new ArrayList<>(); size = 0; } }
Source:
protected void setup(Binder binder) { T configuration = buildConfigObject(config); if (predicate.test(configuration)) { if (module instanceof ConfigurationAwareModule) { START install((ConfigurationAwareModule) module); END } else { binder.install(module); } } } Can you add a version in the parent that takes a normal Module? The current way of only taking ConditionalModule is confusing and leads to mistakes.

Target:
protected void setup(Binder binder) { T configuration = buildConfigObject(config); if (predicate.test(configuration)) { install(module); } }
Source:
public List<Long> getQuantiles(List<Double> quantiles) { List<Long> accumulator = new ArrayList<Long>(quantiles.size()); START for (Double q : quantiles) { END accumulator.add(getQuantile(q)); } return accumulator; } this can be `double q`

Target:
public List<Long> getQuantiles(List<Double> quantiles) { List<Long> accumulator = new ArrayList<Long>(quantiles.size()); for (double q : quantiles) { accumulator.add(getQuantile(q)); } return accumulator; }
Source:
START public static ThreadPoolExecutor newBoundedThreadPool(int maxThreads, ThreadFactory threadFactory) END { BlockingQueue<Runnable> queue = new RefusingQueue<>(); return new ThreadPoolExecutor( 0, maxThreads, 60, TimeUnit.SECONDS, queue, threadFactory, (runnable, executor) -> queue.add(runnable)); } Can you add: ``` java newBoundedThreadPool(int minThreads, int maxThreads, ThreadFactory threadFactory) newBoundedThreadPool(int minThreads, int maxThreads, ThreadFactory threadFactory, Duration keepAlive) ```

Target:
public static ThreadPoolExecutor newBoundedThreadPool(int maxThreads, ThreadFactory threadFactory) { return newBoundedThreadPool(0, maxThreads, threadFactory); }
Source:
public RequestStats() { START allResponse = new CounterStat(); END informationalResponse = new CounterStat(); successfulResponse = new CounterStat(); redirectionResponse = new CounterStat(); clientErrorResponse = new CounterStat(); serverErrorResponse = new CounterStat(); requestFailed = new CounterStat(); requestCanceled = new CounterStat(); requestTime = new TimeStat(); responseTime = new TimeStat(); readBytes = new DistributionStat(); writtenBytes = new DistributionStat(); } These can be in the field declaration.

Target:
public RequestStats() { }
Source:
private void setDelta(int bucket, int value) { int slot = bucketToSlot(bucket); // clear the old value byte clearMask = (byte) (BUCKET_MASK << shiftForBucket(bucket)); START deltas[slot] &= (byte) ~clearMask; END // set the new value byte setMask = (byte) (value << shiftForBucket(bucket)); deltas[slot] |= setMask; } This cast is unnecessary. `deltas` is a byte array, so it's irrelevant that the negated mask is promoted to an int. I think this is just a case of an overly aggressive inspection.

Target:
private void setDelta(int bucket, int value) { int slot = bucketToSlot(bucket); // clear the old value byte clearMask = (byte) (BUCKET_MASK << shiftForBucket(bucket)); deltas[slot] &= ~clearMask; // set the new value byte setMask = (byte) (value << shiftForBucket(bucket)); deltas[slot] |= setMask; }
Source:
START public static String getServicePrincipal(String serviceName) END throws UnknownHostException { requireNonNull(serviceName, "serviceName is null"); String fqdn = InetAddress.getLocalHost().getCanonicalHostName(); checkState(!fqdn.equalsIgnoreCase("localhost"), "Fully qualified host name for localhost is not retrieved"); return String.format("%s/%s", serviceName, fqdn.toLowerCase(Locale.US)); } Remove this as server has its own impl.

Target:
public static String getServicePrincipal(String serviceName) throws UnknownHostException { requireNonNull(serviceName, "serviceName is null"); String fqdn = InetAddress.getLocalHost().getCanonicalHostName(); checkState(!fqdn.equalsIgnoreCase("localhost"), "Fully qualified host name for localhost is not retrieved"); return format("%s/%s", serviceName, fqdn.toLowerCase(Locale.US)); }
Source:
public Authentication findAuthentication(String type, URI uri, String realm) { if (authentication.matches(type, uri, realm)) { return authentication; } START throw new UnsupportedOperationException(String.format("Authentication type %s is not supported", type)); END } Static import `format`

Target:
public Authentication findAuthentication(String type, URI uri, String realm) { if (authentication.matches(type, uri, realm)) { return authentication; } return null; }
Source:
public void close() { try { START context.dispose(); END loginContext.logout(); } catch (GSSException | LoginException e) { throw new AuthenticationException(e); } } This won't call `logout()` if `dispose()` fails.

Target:
public void close() { try { try { context.dispose(); } finally { loginContext.logout(); } } catch (GSSException | LoginException e) { throw new AuthenticationException(e); } }
Source:
public static String getServicePrincipal(String serviceName, String hostName) throws UnknownHostException { requireNonNull(serviceName, "serviceName is null"); requireNonNull(hostName, "hostName is null"); InetAddress address = InetAddress.getByName(hostName); String fqdn; if (address.getHostName().toLowerCase().startsWith("localhost")) { return getServicePrincipal(serviceName); } fqdn = address.getCanonicalHostName(); START return String.format("%s/%s", serviceName, fqdn.toLowerCase(Locale.US)); END } Static import `format`

Target:
public static String getServicePrincipal(String serviceName, String hostName) throws UnknownHostException { requireNonNull(serviceName, "serviceName is null"); requireNonNull(hostName, "hostName is null"); InetAddress address = InetAddress.getByName(hostName); String fqdn; if ("localhost".equalsIgnoreCase(address.getHostName())) { return getServicePrincipal(serviceName); } fqdn = address.getCanonicalHostName(); return format("%s/%s", serviceName, fqdn.toLowerCase(Locale.US)); }
Source:
START private static int decodeBucketIndex(int entry) END { return entry >>> (Integer.SIZE - EXTENDED_PREFIX_BITS); } this can be implemented with: decodeBucketIndex(EXTENDED_PREFIX_BITS, entry)?

Target:
private static int decodeBucketIndex(int entry) { return decodeBucketIndex(EXTENDED_PREFIX_BITS, entry); }
Source:
public String getLevel(String loggerName) { START java.util.logging.Logger logger = getLogger(loggerName); END return getEffectiveLevel(logger).toString(); } Inline this

Target:
public String getLevel(String loggerName) { return logging.getLevel(loggerName).toString(); }
Source:
public static double alpha(int indexBitLength) { double alpha; switch (indexBitLength) { case 4: START alpha = 0.673; END break; case 5: alpha = 0.697; break; case 6: alpha = 0.709; break; default: alpha = (0.7213 / (1 + 1.079 / numberOfBuckets(indexBitLength))); } return alpha; } Return directly

Target:
public static double alpha(int indexBitLength) { switch (indexBitLength) { case 4: return 0.673; case 5: return 0.697; case 6: return 0.709; default: return (0.7213 / (1 + 1.079 / numberOfBuckets(indexBitLength))); } }
Source:
public void addInstance(Object instance) throws Exception { State currentState = state.get(); if ((currentState == State.STOPPING) || (currentState == State.STOPPED)) { throw new IllegalStateException(); } else { startInstance(instance); if (methodsMap.get(instance.getClass()).hasFor(PreDestroy.class)) { if (!managedInstances.contains(instance)) { START managedInstances.add(instance); END } } } } This is not thread safe. There is no way to do an "addIfAbsent" in a thread safe way using a ConcurrentLinkedQueue. You will have to either use external coordination (e.g., synchronize, lock, etc.) or change the users of managedInstance to de-duplicate on read.

Target:
public void addInstance(Object instance) throws Exception { State currentState = state.get(); if ((currentState == State.STOPPING) || (currentState == State.STOPPED)) { throw new IllegalStateException(); } else { startInstance(instance); if (methodsMap.get(instance.getClass()).hasFor(PreDestroy.class)) { managedInstances.add(instance); } } }
Source:
public void close() { Closeables.closeQuietly(ioPool); START Closeables.closeQuietly(httpClient); END } I think you want to do this in the reverse order

Target:
public void close() { Closeables.closeQuietly(httpClient); Closeables.closeQuietly(ioPool); }
Source:
public int indexOfByte(int b) { START checkArgument((b >> Byte.SIZE) == 0, "byte value out of range"); END for (int i = 0; i < size; i++) { if (getByteUnchecked(i) == b) { return i; } } return -1; } if the advantage of this compare to `0 <= b && b < 256`?

Target:
public int indexOfByte(int b) { checkArgument((b >> Byte.SIZE) == 0, "byte value out of range"); return indexOfByte((byte) b); }
Source:
public Slice slice(int index, int length) { if ((index == 0) && (length == length())) { return this; } checkIndexLength(index, length); if (length == 0) { return Slices.EMPTY_SLICE; } if (reference == COMPACT) { return new Slice(base, address + index, length, retainedSize, NOT_COMPACT); } START else { END return new Slice(base, address + index, length, retainedSize, reference); } } Nit: the `else` is redundant, remove it (thus the original line will remain unchanged)

Target:
public Slice slice(int index, int length) { if ((index == 0) && (length == length())) { return this; } checkIndexLength(index, length); if (length == 0) { return Slices.EMPTY_SLICE; } if (reference == COMPACT) { return new Slice(base, address + index, length, retainedSize, NOT_COMPACT); } return new Slice(base, address + index, length, retainedSize, reference); }
Source:
public static Slice allocateDirect(int capacity) { START checkSliceCapacity(capacity); END if (capacity == 0) { return EMPTY_SLICE; } return wrappedBuffer(ByteBuffer.allocateDirect(capacity)); } Move this below the `if (capacity == 0)` check. It can help avoid that extra comparison if the requested capacity is 0.

Target:
public static Slice allocateDirect(int capacity) { if (capacity == 0) { return EMPTY_SLICE; } return wrappedBuffer(ByteBuffer.allocateDirect(capacity)); }
Source:
public static long hash(long seed, InputStream in) throws IOException { XxHash64 hash = new XxHash64(seed); byte[] buffer = new byte[8192]; while (true) { START int n = in.read(buffer); END if (n == -1) { break; } hash.update(buffer, 0, n); } return hash.hash(); } Maybe call this "readBytes" or "length"

Target:
public static long hash(long seed, InputStream in) throws IOException { XxHash64 hash = new XxHash64(seed); byte[] buffer = new byte[8192]; while (true) { int length = in.read(buffer); if (length == -1) { break; } hash.update(buffer, 0, length); } return hash.hash(); }
Source:
public void start() { try { START this.server.start(); END } catch (Exception e) { LOGGER.error("Fail to start the Jetty server... please check the availability of the port."); throw Throwables.propagate(e); } } You don't block here until the server finishes by calling server.join() ? http://www.eclipse.org/jetty/documentation/current/embedding-jetty.html BTW: nice work Cedric, you have made the code of Kasper a lot cleaner & well tested, I am impressed :)

Target:
public void start() { try { this.server.start(); } catch (final Exception e) { LOGGER.error("Fail to start the Jetty server... please check the availability of the port."); Throwables.propagate(e); } }
Source:
public boolean isPublic(final Class<? extends T> clazz) { final XKasperPublic annotation = checkNotNull(clazz).getAnnotation(XKasperPublic.class); START return null != annotation; END } `return (null != checkNotNull(clazz).getAnnotation(XKasperPublic.class));` ?

Target:
public boolean isPublic(final Class<? extends T> clazz) { return (null != checkNotNull(clazz).getAnnotation(XKasperPublic.class)); }
Source:
public Optional<InterceptorChain<Command, CommandResponse>> create(final TypeToken<?> type) { final Class<?> commandClass = type.getRawType(); final boolean isPublicCommand = commandClass.isAnnotationPresent(XKasperPublic.class); START SecurityStrategy securityStrategy = isPublicCommand ? END new DefaultPublicSecurityStrategy(securityConfiguration) : new DefaultSecurityStrategy(securityConfiguration); final Interceptor<Command, CommandResponse> interceptor = new CommandSecurityInterceptor(securityStrategy); return Optional.of(InterceptorChain.makeChain(interceptor)); } final

Target:
public Optional<InterceptorChain<Command, CommandResponse>> create(final TypeToken<?> type) { final Class<?> commandClass = type.getRawType(); final SecurityStrategy securityStrategy; if (commandClass.isAnnotationPresent(XKasperPublic.class)) { securityStrategy = new DefaultPublicSecurityStrategy(securityConfiguration); } else { securityStrategy = new DefaultSecurityStrategy(securityConfiguration); } final Interceptor<Command, CommandResponse> interceptor = new CommandSecurityInterceptor<>(securityStrategy); return Optional.of(InterceptorChain.makeChain(interceptor)); }
Source:
public QueryFactoryBuilder use(final BeanAdapter beanAdapter) { checkNotNull(beanAdapter); final TypeToken adapterForType = TypeToken.of(beanAdapter.getClass()) .getSupertype(BeanAdapter.class) .resolveType(BeanAdapter.class.getTypeParameters()[0]); START beanAdapters.putIfAbsent(adapterForType.getRawType(), beanAdapter); END return this; } `ReflectionGenericsResolver.getParameterTypeFromClass(BeanAdapter1.class, BeanAdapter.class, 0)` should work https://github.com/viadeo/kasper-framework/blob/master/kasper-common/src/main/java/com/viadeo/kasper/tools/ReflectionGenericsResolver.java#L45-L52 ex : https://github.com/viadeo/kasper-framework/blob/master/kasper-common/src/main/java/com/viadeo/kasper/query/exposition/adapters/DefaultTypeAdapters.java#L198-L199

Target:
public QueryFactoryBuilder use(final BeanAdapter beanAdapter) { checkNotNull(beanAdapter); final TypeToken adapterForType = TypeToken.of(beanAdapter.getClass()) .getSupertype(BeanAdapter.class) .resolveType(BeanAdapter.class.getTypeParameters()[0]); beanAdapters.putIfAbsent(adapterForType.getType(), beanAdapter); return this; }
Source:
public KasperResponse(final KasperResponse response) { this.status = response.status; START this.reason = response.reason; END } Could rather call this(response.status, response.reason) to be sure to do the checks which throws the IllegalStateException.

Target:
public KasperResponse(final KasperResponse response) { this(response.status, response.reason); }
Source:
public HTTPKasperResponse asHttp(){ START if (TransportMode.HTTP.equals(getTransportMode()) { END return (HTTPKasperResponse) this; } throw new KasperException("Not an HTTP response"); } :warning: misses closing parenthesis! `if (HTTPKasperResponse.class.isAssignableFrom(this.getClass())) {`

Target:
public HTTPKasperResponse asHttp(){ if (TransportMode.HTTP.equals(getTransportMode())) { return (HTTPKasperResponse) this; } throw new KasperException("Not an HTTP response"); }
Source:
private void handleAddLabel() { START int i = 1; END } Please remove this.

Target:
private void handleAddLabel() { }
Source:
START public List<Integer> getCurrentPositionOfSounds() { END List<Integer> positionList = new ArrayList<>(); for (MediaPlayer mediaPlayer : mediaPlayers) { int position = mediaPlayer.isPlaying() ? mediaPlayer.getCurrentPosition() : mediaPlayer.getDuration(); positionList.add(position); } return positionList; } Please rename this function. Maybe it is useful to map sounds to positions.

Target:
private List<Integer> getCurrentPositionOfSounds() { List<Integer> positionList = new ArrayList<>(); for (MediaPlayer mediaPlayer : mediaPlayers) { positionList.add(mediaPlayer.getCurrentPosition()); } return positionList; }
Source:
public static Collection<Object[]> data() { return Arrays.asList(new Object[][] { {"GlideToBrick", R.string.brick_glide, new GlideToBrick(), START R.id.brick_glide_to_edit_text_x, R.id.brick_glide_to_edit_text_y, "1+2", END 42, "1 + 2 ", "42 "}, {"PlaceAtBrick", R.string.brick_place_at, new PlaceAtBrick(), R.id.brick_place_at_edit_text_x, R.id.brick_place_at_edit_text_y, "1+2", 42, "1 + 2 ", "42 "} }); } Since the input and the expected outcomes are everywhere the same, you could possibly move them into the test cases. (to reduce the overhead)

Target:
public static Collection<Object[]> data() { return Arrays.asList(new Object[][] { {"GlideToBrick", R.string.brick_glide, new GlideToBrick()}, {"PlaceAtBrick", R.string.brick_place_at, new PlaceAtBrick()} }); }
Source:
public void testLeftBubblePosition() { START Float expectedXLeft = EXPECTED_X_STD_LEFT; Float expectedYLeft = EXPECTED_Y_STD; END ShowBubbleActor bubbleActor = new ShowBubbleActor(OBJECT_NAME, sprite, Constants.SAY_BRICK); assertEquals(expectedXLeft, bubbleActor.calculateLeftImageX(CALC_X_LEFT)); assertEquals(expectedYLeft, bubbleActor.calculateImageY(CALC_Y_LEFT)); } This is unnecessary since you just need those variables to compare with your result. Just use your defined constants here.

Target:
public void testLeftBubblePosition() { ShowBubbleActor bubbleActor = new ShowBubbleActor(OBJECT_NAME, sprite, Constants.SAY_BRICK); assertEquals(EXPECTED_X_STD_LEFT, bubbleActor.calculateLeftImageX(CALC_X_LEFT)); assertEquals(EXPECTED_Y_STD, bubbleActor.calculateImageY(CALC_Y_LEFT)); }
Source:
public static ProjectManager getInstance() { START return INSTANCE; END } ``` [2019-10-01T07:16:01.665Z] /home/catroid/jenkins_slave/workspace/Catroid_PR-3353/catroid/src/main/java/org/catrobat/catroid/ProjectManager.java:98: error: cannot find symbol [2019-10-01T07:16:01.665Z] return INSTANCE; [2019-10-01T07:16:01.665Z] ^ [2019-10-01T07:16:01.665Z] symbol: variable INSTANCE [2019-10-01T07:16:01.665Z] location: class ProjectManager ```

Target:
public static ProjectManager getInstance() { return instance; }
Source:
START public List<UUID> getKeyList(List<? extends UserData> userDataList) { END List<UUID> keyList = new ArrayList<>(); for (UserData userData : userDataList) { keyList.add(userData.getDeviceKey()); } return keyList; } can be private

Target:
private List<UUID> getKeyList(List<? extends UserData> userDataList) { List<UUID> keyList = new ArrayList<>(); for (UserData userData : userDataList) { keyList.add(userData.getDeviceKey()); } return keyList; }
Source:
public void testRegistrationOk() throws WebconnectionException { authenticator.performCatrobatRegister(testEmail, "de", "at", sharedPreferences.edit()); verify(listenerMock, never()).onError(anyInt(), anyString()); verify(listenerMock, atLeastOnce()).onSuccess(); token = sharedPreferences.getString(Constants.TOKEN, Constants.NO_TOKEN); START boolean tokenOk = new CatrobatServerCalls().checkToken(token, testUser, BASE_URL_TEST_HTTPS); END assertTrue(tokenOk); } you probably don't need to introduce an extra local var for this. assertTrue on the value you assign to `tokenOk` saves you a line

Target:
public void testRegistrationOk() throws WebconnectionException { authenticator.performCatrobatRegister(testEmail, "de", "at"); verify(listenerMock, never()).onError(anyInt(), anyString()); verify(listenerMock, atLeastOnce()).onSuccess(); token = sharedPreferences.getString(Constants.TOKEN, Constants.NO_TOKEN); assertTrue(new CatrobatServerCalls().checkToken(token, testUser, BASE_URL_TEST_HTTPS)); }
Source:
protected void onPreExecute() { super.onPreExecute(); START if (contextWeakReference.get() == null) { END return; } String title = contextWeakReference.get().getString(R.string.please_wait); String message = contextWeakReference.get().getString(R.string.loading); progressDialog = ProgressDialog.show(contextWeakReference.get(), title, message); } Please read up on the correct usage of `WeakReference`. `get()` returns a regular reference, true, but unless you save this returned value somewhere, the `WeakReference` you hold does not prevent the garbage collector from collecting the context your weak reference points to. So you have to introduce a new local var, write the result of `contextWeakReference.get()` to it and use this regular reference for the remainder of this method. Otherwise you risk running into a NPE

Target:
protected void onPreExecute() { Context context = contextWeakReference.get(); if (context == null) { return; } String title = context.getString(R.string.please_wait); String message = context.getString(R.string.loading); progressDialog = ProgressDialog.show(context, title, message); }
Source:
public void testAddJumpStitchPoint() { START EmbroideryStream stream = new DSTStream(); END stream.addJump(); stream.addStitchPoint(0, 0); assertEquals(1, stream.getPointList().size()); assertTrue(stream.getPointList().get(0).isJumpPoint()); } Please move to a `@before` function

Target:
public void testAddJumpStitchPoint() { stream.addJump(); stream.addStitchPoint(0, 0); assertEquals(1, stream.getPointList().size()); assertTrue(stream.getPointList().get(0).isJumpPoint()); }
Source:
START protected void getTags() { END GetTagsTask getTagsTask = new GetTagsTask(); getTagsTask.setOnTagsResponseListener(this); getTagsTask.execute(); } Please revert to private

Target:
private void getTags() { GetTagsTask getTagsTask = new GetTagsTask(); getTagsTask.setOnTagsResponseListener(this); getTagsTask.execute(); }
Source:
public void testBrickFieldValidValue() throws InterpretationException { START assertSame(BRICK_FORMULA_VALUE, brickFormula.interpretInteger(sprite)); END } equals!

Target:
public void testBrickFieldValidValue() throws InterpretationException { assertEquals(BRICK_FORMULA_VALUE, brickFormula.interpretInteger(sprite)); }
Source:
public void tearDown() throws IOException { firstProject = null; START secondProject = null; END } This is just setting the object reference to null. As you saved the XML with XStream, the saved project is still remaining

Target:
public void tearDown() throws IOException { }
Source:
public boolean getGlobalVariableConflicts(List<UserVariable> project1GlobalVars, List<UserVariable> project2GlobalVars) { List<UserVariable> conflicts = new ArrayList<>(); for (UserVariable project1GlobalVar : project1GlobalVars) { for (UserVariable project2GlobalVar : project2GlobalVars) { if (project1GlobalVar.getName().equals(project2GlobalVar.getName()) && !project1GlobalVar.getValue() .equals(project2GlobalVar.getValue())) { conflicts.add(project1GlobalVar); } } } START return conflicts.isEmpty(); END } You could optimize this in a way like don't saving an extra list with the conflicts added. This should may be implemented in a ticket to resolve tickets. Just to understand, you are creating a new list and afterwards you are just returning a property of this list. Think about something like (Pseudo Code): ``` WHILE iterate_over_lists: IF conflict_found RETURN true; END IF END WHILE return false;

Target:
public boolean getGlobalVariableConflicts(List<UserVariable> project1GlobalVars, List<UserVariable> project2GlobalVars) { List<UserVariable> conflicts = new ArrayList<>(); for (UserVariable project1GlobalVar : project1GlobalVars) { for (UserVariable project2GlobalVar : project2GlobalVars) { if (project1GlobalVar.getName().equals(project2GlobalVar.getName())) { conflicts.add(project1GlobalVar); } } } return !conflicts.isEmpty(); }
Source:
public boolean getGlobalListConflicts(List<UserList> project1GlobalLists, List<UserList> project2GlobalLists) { List<UserList> conflicts = new ArrayList<>(); for (UserList project1GlobalList : project1GlobalLists) { for (UserList project2GlobalList : project2GlobalLists) { if (project1GlobalList.getName().equals(project2GlobalList.getName()) && !project1GlobalList.getList() .equals(project2GlobalList.getList())) { conflicts.add(project1GlobalList); } } } return conflicts.isEmpty(); START } END You actually don't need a whole Project Object becaus you only work with lists of project, please change the functionality to only work with lists, by now

Target:
public boolean getGlobalListConflicts(List<UserList> project1GlobalLists, List<UserList> project2GlobalLists) { List<UserList> conflicts = new ArrayList<>(); for (UserList project1GlobalList : project1GlobalLists) { for (UserList project2GlobalList : project2GlobalLists) { if (project1GlobalList.getName().equals(project2GlobalList.getName())) { conflicts.add(project1GlobalList); } } } return !conflicts.isEmpty(); }
Source:
public List<Sprite> getAllClonesOfSprite(Sprite sprite) { List<Sprite> clonesOfSprite = new ArrayList<Sprite>(); Pattern pattern = createCloneRegexPattern(sprite.getName()); for (Sprite spriteOfStage : sprites) { START Matcher matcher = pattern.matcher(spriteOfStage.getName()); END if (spriteOfStage.isClone && matcher.matches()) { clonesOfSprite.add(spriteOfStage); } } return clonesOfSprite; } You could skip this if `spriteOfStage.isClone` is false

Target:
public List<Sprite> getAllClonesOfSprite(Sprite sprite) { List<Sprite> clonesOfSprite = new ArrayList<>(); Pattern pattern = createCloneRegexPattern(sprite.getName()); for (Sprite spriteOfStage : sprites) { if (!spriteOfStage.isClone) { continue; } Matcher matcher = pattern.matcher(spriteOfStage.getName()); if (matcher.matches()) { clonesOfSprite.add(spriteOfStage); } } return clonesOfSprite; }
Source:
private @Nullable String getColorFormulaString() { Formula formula = getFormulaWithBrickField(BrickField.COLOR); FormulaElement formulaTree = formula.getFormulaTree(); START boolean formulaIsString = formulaTree.getElementType() == FormulaElement.ElementType.STRING; END return formulaIsString ? formulaTree.getValue() : null; } please replace with if else construct

Target:
private @Nullable String getColorFormulaString() { Formula formula = getFormulaWithBrickField(BrickField.COLOR); FormulaElement formulaTree = formula.getFormulaTree(); if (formulaTree.getElementType() == FormulaElement.ElementType.STRING) { return formulaTree.getValue(); } else { return null; } }
Source:
public void setUp() { START Context context = InstrumentationRegistry.getTargetContext().getApplicationContext(); END sensorNames.addAll(Arrays.asList(context.getResources().getStringArray(R.array.nxt_sensor_chooser))); sensorCodes.addAll(Arrays.asList(NXTSensor.Sensor.getSensorCodes())); sensorName = context.getString(sensorNameStringId); } `...getTargetContext();` should be enough to return the current instrumented applications contex

Target:
public void setUp() { Context context = InstrumentationRegistry.getTargetContext(); sensorNames.addAll(Arrays.asList(context.getResources().getStringArray(R.array.nxt_sensor_chooser))); sensorCodes.addAll(Arrays.asList(NXTSensor.Sensor.getSensorCodes())); sensorName = context.getString(sensorNameStringId); }
Source:
public void testBrickFieldValidValue() throws InterpretationException { assertSame(BRICK_FORMULA_VALUE, brickFormula.interpretInteger(sprite)); START assertSame(BRICK_FORMULA_VALUE, cloneBrickFormula.interpretInteger(sprite)); END } if you delete second line here, you can add the assert from testBrickFieldEquals to do the same thing but in one `assertSame(brickFormula.interpretInteger(sprite), cloneBrickFormula.interpretInteger(sprite));` So you are interpreting the correct value first, and then check the cloned one

Target:
public void testBrickFieldValidValue() throws InterpretationException { assertSame(BRICK_FORMULA_VALUE, brickFormula.interpretInteger(sprite)); }
Source:
public boolean act(float delta) { if (userVariable == null) { return true; } if (firstStart) { firstStart = false; writeActionFinished = false; START new WriteVariableOnDeviceAction.WriteTask().execute(userVariable); END } return writeActionFinished; } in ReadVariableOnDeviceAction you have at this point "new ReadTask().execute(userVariable);" so it would be consistent if you would write "new WriteTask().execute(userVariable);"

Target:
public boolean act(float delta) { if (userVariable == null) { return true; } if (firstStart) { firstStart = false; writeActionFinished = false; new WriteTask().execute(userVariable); } return writeActionFinished; }
Source:
public void setUp() { directory = new File(InstrumentationRegistry.getTargetContext().getCacheDir(), "DeviceValues"); directory.mkdir(); START sprite = new Sprite("_sprite_"); END userVariable = new UserVariable("globalVarX", initialValue); localUserVariable = new UserVariable("localVarY", initialValue); sprite.addUserVariable(localUserVariable); accessor = new DeviceVariableAccessor(directory); } remove sprite and remove global/local, only test the accessor

Target:
public void setUp() { directory = new File(InstrumentationRegistry.getTargetContext().getCacheDir(), "DeviceValues"); directory.mkdir(); userVariable = new UserVariable("globalVarX", initialValue); accessor = new DeviceVariableAccessor(directory); }
Source:
public void writeVariable(UserVariable userVariable) throws IOException { if (checkDeviceVariableKeyEmpty(userVariable)) { addKeyToUserVariable(userVariable); } if (!deviceVariablesFile.exists()) { deviceVariablesFile.createNewFile(); } synchronized (LOCK) { HashMap deviceVariableMap = readMapFromJson(); if (deviceVariableMap == null) { deviceVariableMap = new HashMap<>(); } deviceVariableMap.put(userVariable.getDeviceValueKey(), userVariable.getValue()); writeMapToJson(deviceVariableMap); } START } END this blows up when .getValue() returns NaN

Target:
public void writeVariable(UserVariable userVariable) throws IOException { synchronized (LOCK) { if (!deviceVariablesFile.exists()) { deviceVariablesFile.createNewFile(); } HashMap deviceVariableMap = readMapFromJson(); if (deviceVariableMap == null) { deviceVariableMap = new HashMap<>(); } deviceVariableMap.put(userVariable.getDeviceValueKey(), userVariable.getValue()); writeMapToJson(deviceVariableMap); } }
Source:
public void delete(Scene sceneToDelete) throws IOException { StorageOperations.deleteDir(sceneToDelete.getDirectory()); START File projectDirectory = ProjectManager.getInstance().getCurrentProject().getDirectory(); END DeviceVariableAccessor accessor = new DeviceVariableAccessor(projectDirectory); for (Sprite sprite: sceneToDelete.getSpriteList()) { try { accessor.deleteAllLocalVariables(sprite); } catch (IOException e) { Log.i(TAG, e.getMessage()); } } } instead of adding this removal procedure to every delete here and there id rather have a cleanup once eg. on project load.

Target:
public void delete(Scene sceneToDelete) throws IOException { StorageOperations.deleteDir(sceneToDelete.getDirectory()); }
Source:
public void onActivityResult(int requestCode, int resultCode, Intent data) { //Register your intent with "queueIntent" if (intentListeners.indexOfKey(requestCode) >= 0) { IntentListener asker = intentListeners.get(requestCode); asker.onIntentResult(resultCode, data); intentListeners.remove(requestCode); } else if (requestCode == REQUEST_EXPORT_EMBROIDERY_FILE) { if (resultCode == RESULT_OK) { START Log.d(TAG, "Exported embroidery file"); END } } else { stageResourceHolder.onActivityResult(requestCode, resultCode, data); } } please remove this

Target:
public void onActivityResult(int requestCode, int resultCode, Intent data) { //Register your intent with "queueIntent" if (intentListeners.indexOfKey(requestCode) >= 0) { IntentListener asker = intentListeners.get(requestCode); asker.onIntentResult(resultCode, data); intentListeners.remove(requestCode); } else { stageResourceHolder.onActivityResult(requestCode, resultCode, data); } }
Source:
public T remove(int index) { try { T removedObject = super.remove(index); comparingSet.remove(removedObject); return removedObject; START } catch (IndexOutOfBoundsException ioobException) { END throw new IndexOutOfBoundsException(); } } same again. please throw original exception.

Target:
public T remove(int index) { try { T removedObject = super.remove(index); comparingSet.remove(removedObject); return removedObject; } catch (IndexOutOfBoundsException ioobException) { throw ioobException; } }
Source:
public T set(int index, T element) { try { if (element.equals(this.get(index))) { return element; } T oldObject = null; if (comparingSet.add(element)) { oldObject = super.set(index, element); comparingSet.remove(oldObject); } return oldObject; } catch (IndexOutOfBoundsException ioobException) { START throw new IndexOutOfBoundsException(); END } } same again: do not create a new empty exception but reuse the old one.

Target:
public T set(int index, T element) { try { if (element.equals(this.get(index))) { return element; } T oldObject = null; if (comparingSet.add(element)) { oldObject = super.set(index, element); comparingSet.remove(oldObject); } return oldObject; } catch (IndexOutOfBoundsException ioobException) { throw ioobException; } }
Source:
public void cancelCall() { if (call != null) { okHttpClient.getDispatcher().getExecutorService().execute(new Runnable() { @Override public void run() { WebRequestListener listener = getListenerAndSetReferenceToNull(); if (listener != null) { call.cancel(); listener.onCancelledCall(); } START } END }); } } why does this have to be run as a thread on some okHttpClient provided stack?

Target:
public void cancelCall() { if (call != null) { okHttpClient.getDispatcher().getExecutorService().execute(new Runnable() { @Override public void run() { call.cancel(); } }); } }
Source:
public boolean hasBackCameraFlash() { START if (hasBackCamera()) { END return backCameraInformation.flashAvailable; } return false; } you can use "early return" here: ``` return hasBackCamera() && backCameraInformation.flashAvailable: ``` Java evaluates the right hand side of the condition first, so even no null pointer exception can occur here.

Target:
public boolean hasBackCameraFlash() { return (hasBackCamera() && backCameraInformation.flashAvailable); }
Source:
public static void pauseFlash() { START Log.d(TAG, "pauseFlash()"); END if (!paused && isAvailable()) { paused = true; if (isOn()) { startAgain = true; flashOff(); } } } just remove the log altogether, as this was clearly added for debugging purposes. I think it is just bad practice to use log for debugging instead of Android Studio's debugger. breakpoints ftw! :smile:

Target:
public static void pauseFlash() { if (!paused && isAvailable()) { paused = true; if (isOn()) { startAgain = true; flashOff(); } } }
Source:
public static void flashOff() { START Log.d(TAG, "flashOff()"); END if (!isAvailable()) { return; } CameraManager.getInstance().setFlashParams(paramsOff); currentFlashValue = false; } another log that can be removed (I know it's not part of your commit, but please do it anyway).

Target:
public static void flashOff() { if (!isAvailable()) { return; } CameraManager.getInstance().setFlashParams(paramsOff); currentFlashValue = false; }
Source:
public void setUp() { Project project = new Project(InstrumentationRegistry.getTargetContext(), projectName); ProjectManager.getInstance().setCurrentProject(project); fileGenerator = new DSTFileGenerator(); START dstFile = new File(Constants.CACHE_DIR + "/" + projectName + ".dst"); END } please use dstFile = new File(Constants.CACHE_DIR, projectName + ".dst") instead

Target:
public void setUp() { Project project = new Project(InstrumentationRegistry.getTargetContext(), projectName); ProjectManager.getInstance().setCurrentProject(project); fileGenerator = new DSTFileGenerator(); }
Source:
public void onBackPressed() { if (coordinatesChanged) { showSaveChangesDialog(this); } else { START super.onBackPressed(); END } } please rename to finishWithResult or something similar. since its not saving anything, and also finishing the activity

Target:
public void onBackPressed() { showSaveChangesDialog(this); }
Source:
public void onResume() { super.onResume(); setShowProgressBar(false); adapter.items.get(0).subtitle = Utils.getCurrentProjectName(getActivity()); adapter.notifyDataSetChanged(); String projectName = getActivity().getIntent().getStringExtra(StatusBarNotificationManager.EXTRA_PROJECT_NAME); if (projectName != null) { loadDownloadedProject(projectName); START getActivity().getIntent().removeExtra(StatusBarNotificationManager.EXTRA_PROJECT_NAME); END } } remove this line please

Target:
public void onResume() { super.onResume(); setShowProgressBar(false); adapter.items.get(0).subtitle = Utils.getCurrentProjectName(getActivity()); adapter.notifyDataSetChanged(); String projectName = getActivity().getIntent().getStringExtra(StatusBarNotificationManager.EXTRA_PROJECT_NAME); if (projectName != null) { loadDownloadedProject(projectName); } }
Source:
public IfLogicEndBrick(IfLogicBeginBrick ifLogicBeginBrick, IfLogicElseBrick ifElseBrick) { START this.ifElseBrick = ifElseBrick; END this.ifBeginBrick = ifLogicBeginBrick; } Please also swap these two lines :laughing:

Target:
public IfLogicEndBrick(IfLogicBeginBrick ifLogicBeginBrick, IfLogicElseBrick ifElseBrick) { this.ifBeginBrick = ifLogicBeginBrick; this.ifElseBrick = ifElseBrick; }
Source:
private static Boolean isNewStitchPoint(PointF point) { START if (point.x != stitchPoints.get(lastIndex).x || point.y != stitchPoints.get(lastIndex).y) { END return true; } return false; } or just simply: return stitchPoints.get(stitchPoints.size() - 1).equals(point) besides that, maybe remove lastIndex, because this is really unnecessary and errorprone to manually keep the size of that list in a seperate variable.

Target:
private Boolean isNewStitchPoint(PointF point) { return !stitchPoints.get(stitchPoints.size() - 1).equals(point); }