auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void onActivityResult(int requestCode, int resultCode, Intent intent) { switch (requestCode) { case CommCareHomeActivity.INIT_APP: if (resultCode == RESULT_OK) { if(!CommCareApplication._().getCurrentApp().areResourcesValidated()){ Intent i = new Intent(this, CommCareVerificationActivity.class); i.putExtra(KEY_LAUNCH_FROM_MANAGER, true); this.startActivityForResult(i, CommCareHomeActivity.MISSING_MEDIA_ACTIVITY); } else { Toast.makeText(this, "New app installed successfully", Toast.LENGTH_LONG).show(); } } else { Toast.makeText(this, "No app was installed!", Toast.LENGTH_LONG).show(); } break; case CommCareHomeActivity.MISSING_MEDIA_ACTIVITY: if (resultCode == RESULT_CANCELED) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Media Not Verified"); builder.setMessage(R.string.skipped_verification_warning) .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); AlertDialog dialog = builder.create(); dialog.show(); } else if (resultCode == RESULT_OK) { Toast.makeText(this, "Media Validated!", Toast.LENGTH_LONG).show(); } break; } }

Target:
protected void onActivityResult(int requestCode, int resultCode, Intent intent) { switch (requestCode) { case CommCareHomeActivity.INIT_APP: boolean installFailed = intent != null && intent.getBooleanExtra( CommCareSetupActivity.KEY_INSTALL_FAILED, false); if (resultCode == RESULT_OK && !installFailed) { if (!CommCareApplication._().getCurrentApp().areMMResourcesValidated()) { Intent i = new Intent(this, CommCareVerificationActivity.class); i.putExtra(KEY_LAUNCH_FROM_MANAGER, true); this.startActivityForResult(i, CommCareHomeActivity.MISSING_MEDIA_ACTIVITY); } } else { Toast.makeText(this, R.string.no_installation, Toast.LENGTH_LONG).show(); } break; case CommCareHomeActivity.MISSING_MEDIA_ACTIVITY: if (resultCode == RESULT_CANCELED) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.media_not_verified); builder.setMessage(R.string.skipped_verification_warning) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); AlertDialog dialog = builder.create(); dialog.show(); } else if (resultCode == RESULT_OK) { Toast.makeText(this, R.string.media_verified, Toast.LENGTH_LONG).show(); } break; case CommCareHomeActivity.CONNECTION_DIAGNOSTIC_ACTIVITY: return; } }
Source:
public void startApp() { System.out.println("START"); WebPublicKeyStore cs = WebPublicKeyStore.getTrustedKeyStore(); int numberOfKeys = cs.numberOfKeys(); if (numberOfKeys != 1) { System.out.println("FAIL - Number of keys (" + numberOfKeys + ") != 1"); } PublicKeyInfo keyInfo = cs.getKey(0); if (keyInfo.getOwner().length() == 0) { System.out.println("FAIL - Owner must be a string with length > 0"); } X509Certificate[] certificates = cs.getCertificates(keyInfo.getOwner()); X509Certificate aCert = certificates[0]; try { aCert.verify(aCert.getPublicKey()); } catch (CertificateException e) { System.out.println("FAIL - Verification should succeed"); e.printStackTrace(); } System.out.println("DONE"); }

Target:
public void startApp() { System.out.println("START"); WebPublicKeyStore cs = WebPublicKeyStore.getTrustedKeyStore(); int numberOfKeys = cs.numberOfKeys(); if (numberOfKeys < 1) { System.out.println("FAIL - Number of keys (" + numberOfKeys + ") < 1"); } PublicKeyInfo keyInfo = cs.getKey(0); if (keyInfo.getOwner().length() == 0) { System.out.println("FAIL - Owner must be a string with length > 0"); } X509Certificate[] certificates = cs.getCertificates(keyInfo.getOwner()); X509Certificate aCert = certificates[0]; try { aCert.verify(aCert.getPublicKey()); } catch (CertificateException e) { System.out.println("FAIL - Verification should succeed"); e.printStackTrace(); } System.out.println("DONE"); }
Source:
public void publishProvider(URL providerUrl) throws RpcException { providerUrl = providerUrl.removeParameters(PID_KEY, TIMESTAMP_KEY, Constants.BIND_IP_KEY, Constants.BIND_PORT_KEY, TIMESTAMP_KEY); try { String interfaceName = providerUrl.getParameter(INTERFACE_KEY); if (StringUtils.isNotEmpty(interfaceName)) { Class interfaceClass =Thread.currentThread().getContextClassLoader().loadClass(interfaceName); FullServiceDefinition fullServiceDefinition = ServiceDefinitionBuilder.buildFullDefinition(interfaceClass, providerUrl.getParameters()); metadataReport.storeProviderMetadata(new MetadataIdentifier(providerUrl.getServiceInterface(), providerUrl.getParameter(VERSION_KEY), providerUrl.getParameter(GROUP_KEY), PROVIDER_SIDE, providerUrl.getParameter(APPLICATION_KEY)), fullServiceDefinition); return; } logger.error("publishProvider interfaceName is empty . providerUrl: " + providerUrl.toFullString()); } catch (ClassNotFoundException e) { logger.error("publishProvider getServiceDescriptor error. providerUrl: " + providerUrl.toFullString(), e); } }

Target:
public void publishProvider(URL providerUrl) throws RpcException { providerUrl = providerUrl.removeParameters(PID_KEY, TIMESTAMP_KEY, Constants.BIND_IP_KEY, Constants.BIND_PORT_KEY, TIMESTAMP_KEY); try { String interfaceName = providerUrl.getParameter(INTERFACE_KEY); if (StringUtils.isNotEmpty(interfaceName)) { ClassLoader classLoader = null == Thread.currentThread().getContextClassLoader() ? this.getClass().getClassLoader() : Thread.currentThread().getContextClassLoader(); Class interfaceClass = Class.forName(interfaceName, true, classLoader); FullServiceDefinition fullServiceDefinition = ServiceDefinitionBuilder.buildFullDefinition(interfaceClass, providerUrl.getParameters()); metadataReport.storeProviderMetadata(new MetadataIdentifier(providerUrl.getServiceInterface(), providerUrl.getParameter(VERSION_KEY), providerUrl.getParameter(GROUP_KEY), PROVIDER_SIDE, providerUrl.getParameter(APPLICATION_KEY)), fullServiceDefinition); return; } logger.error("publishProvider interfaceName is empty . providerUrl: " + providerUrl.toFullString()); } catch (ClassNotFoundException e) { logger.error("publishProvider getServiceDescriptor error. providerUrl: " + providerUrl.toFullString(), e); } }
Source:
public void increaseBackpressure(int messageSize) { assert(m_expectedThreadId == Thread.currentThread().getId()); if (messageSize < 1) { throw new IllegalArgumentException("Message size must be > 0 but was " + messageSize); } m_pendingTxnBytes += messageSize; m_pendingTxnCount++; checkAndLogInvariants(); if (m_pendingTxnBytes > MAX_DESIRED_PENDING_BYTES || m_pendingTxnCount > MAX_DESIRED_PENDING_TXNS) { if (!m_hadBackPressure) { hostLog.info("TXN back pressure began"); m_hadBackPressure = true; for (ACGMember m : m_members) { m.onBackpressure(); } } } }

Target:
public void increaseBackpressure(int messageSize) { assert(m_expectedThreadId == Thread.currentThread().getId()); if (messageSize < 1) { throw new IllegalArgumentException("Message size must be > 0 but was " + messageSize); } m_pendingTxnBytes += messageSize; m_pendingTxnCount++; checkAndLogInvariants(); if (m_pendingTxnBytes > MAX_DESIRED_PENDING_BYTES || m_pendingTxnCount > MAX_DESIRED_PENDING_TXNS) { if (!m_hadBackPressure) { hostLog.debug("TXN back pressure began"); m_hadBackPressure = true; for (ACGMember m : m_members) { m.onBackpressure(); } } } }
Source:
protected Map<Object, Object> getRelationshipValues( Class<?> relationshipType, List<Object> joinFieldIds ) { if (joinFieldIds.isEmpty()) { return Collections.emptyMap(); } List<Object> uniqueIds = joinFieldIds.stream() .distinct() .collect(Collectors.toCollection(LinkedList::new)); List<Object> loaded = getEntityManager() .createQuery( String.format( "SELECT e FROM %s e WHERE %s IN (:idList)", relationshipType.getCanonicalName(), getEntityDictionary().getIdFieldName(relationshipType) ) ) .setParameter("idList", uniqueIds) .getResultList(); return loaded.stream() .map(obj -> new AbstractMap.SimpleImmutableEntry<>( getEntityDictionary().getValue(obj, "id", null), obj)) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); }

Target:
protected Map<Object, Object> getRelationshipValues( Class<?> relationshipType, List<Object> joinFieldIds ) { if (joinFieldIds.isEmpty()) { return Collections.emptyMap(); } List<Object> uniqueIds = joinFieldIds.stream() .distinct() .collect(Collectors.toCollection(LinkedList::new)); List<Object> loaded = getEntityManager() .createQuery( String.format( "SELECT e FROM %s e WHERE %s IN (:idList)", relationshipType.getCanonicalName(), getEntityDictionary().getIdFieldName(relationshipType) ) ) .setParameter("idList", uniqueIds) .getResultList(); return loaded.stream() .map(obj -> new AbstractMap.SimpleImmutableEntry<>(CoerceUtil.coerce((Object) getEntityDictionary(). getId(obj), getEntityDictionary().getIdType(relationshipType)), obj)) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); }
Source:
public Status read(String table, String key, Set<String> fields, Map<String, ByteIterator> result) { try { User user = (fields == null || fields.size() == 0) ? dataStore.get(key) : dataStore.get(key, fields.toArray(DUMMY_ARRAY)); for (int i = 0; i < fieldCount; i++) { String field = FIELDS[i + 1]; int fieldIndex = i + 1; String value = user.get(fieldIndex).toString(); result.put(field, new StringByteIterator(value)); } } catch (Exception e) { LOG.info("There is a problem in reading data from the table \n"+e.getMessage(), e); return Status.ERROR; } return Status.OK; }

Target:
public Status read(String table, String key, Set<String> fields, Map<String, ByteIterator> result) { try { User user = (fields == null || fields.size() == 0) ? dataStore.get(key) : dataStore.get(key, fields.toArray(DUMMY_ARRAY)); for (int fieldCount = 0; fieldCount < totalFieldCount; fieldCount++) { String field = FIELDS[fieldCount + 1]; int fieldIndex = fieldCount + 1; String value = user.get(fieldIndex).toString(); result.put(field, new StringByteIterator(value)); } } catch (Exception e) { LOG.info("There is a problem in reading data from the table \n {}", e.getMessage(), e); return Status.ERROR; } return Status.OK; }
Source:
public StatsDEmitterConfig( @JsonProperty("hostname") String hostname, @JsonProperty("port") Integer port, @JsonProperty("prefix") String prefix, @JsonProperty("separator") String separator, @JsonProperty("includeHost") Boolean includeHost, @JsonProperty("dimensionMapPath") String dimensionMapPath, @JsonProperty("blankHolder") String blankHolder, @JsonProperty("dogstatsd") Boolean dogstatsd, @JsonProperty("dogstatsdConstantTags") List<String> dogstatsdConstantTags ) { this.hostname = Preconditions.checkNotNull(hostname, "StatsD hostname cannot be null."); this.port = Preconditions.checkNotNull(port, "StatsD port cannot be null."); this.prefix = prefix != null ? prefix : ""; this.separator = separator != null ? separator : "."; this.includeHost = includeHost != null ? includeHost : false; this.dimensionMapPath = dimensionMapPath; this.blankHolder = blankHolder != null ? blankHolder : "-"; this.dogstatsd = dogstatsd != null ? dogstatsd : false; this.dogstatsdConstantTags = dogstatsdConstantTags != null ? dogstatsdConstantTags : new ArrayList<>(0); }

Target:
public StatsDEmitterConfig( @JsonProperty("hostname") String hostname, @JsonProperty("port") Integer port, @JsonProperty("prefix") String prefix, @JsonProperty("separator") String separator, @JsonProperty("includeHost") Boolean includeHost, @JsonProperty("dimensionMapPath") String dimensionMapPath, @JsonProperty("blankHolder") String blankHolder, @JsonProperty("dogstatsd") Boolean dogstatsd, @JsonProperty("dogstatsdConstantTags") List<String> dogstatsdConstantTags ) { this.hostname = Preconditions.checkNotNull(hostname, "StatsD hostname cannot be null."); this.port = Preconditions.checkNotNull(port, "StatsD port cannot be null."); this.prefix = prefix != null ? prefix : ""; this.separator = separator != null ? separator : "."; this.includeHost = includeHost != null ? includeHost : false; this.dimensionMapPath = dimensionMapPath; this.blankHolder = blankHolder != null ? blankHolder : "-"; this.dogstatsd = dogstatsd != null ? dogstatsd : false; this.dogstatsdConstantTags = dogstatsdConstantTags != null ? dogstatsdConstantTags : Collections.emptyList(); }
Source:
private void setCookieAndRecordMetrics(UserSession session) { writeSessionInfoToMetrics(session); response().setCookie(BridgeConstants.SESSION_TOKEN_HEADER, session.getSessionToken(), BridgeConstants.BRIDGE_SESSION_EXPIRE_IN_SECONDS, "/", bridgeConfig.getHostnameWithPostfix("webservices"), true, true); RequestInfo requestInfo = getRequestInfoBuilder(session) .withSignedInOn(DateUtils.getCurrentDateTime()).build(); cacheProvider.updateRequestInfo(requestInfo); }

Target:
private void setCookieAndRecordMetrics(UserSession session) { writeSessionInfoToMetrics(session); boolean useSsl = bridgeConfig.getEnvironment() != Environment.LOCAL; response().setCookie(BridgeConstants.SESSION_TOKEN_HEADER, session.getSessionToken(), BridgeConstants.BRIDGE_SESSION_EXPIRE_IN_SECONDS, "/", bridgeConfig.get("webservices.url"), useSsl, useSsl); RequestInfo requestInfo = getRequestInfoBuilder(session) .withSignedInOn(DateUtils.getCurrentDateTime()).build(); cacheProvider.updateRequestInfo(requestInfo); }
Source:
protected void requestCredentialsUpdate(Context context) { try { OwnCloudClient client; OwnCloudAccount ocAccount = new OwnCloudAccount(getAccount(), context); client = (OwnCloudClientManagerFactory.getDefaultSingleton(). removeClientFor(ocAccount)); if (client != null) { OwnCloudCredentials cred = client.getCredentials(); if (cred != null) { AccountManager am = AccountManager.get(context); if (cred.authTokenExpires()) { am.invalidateAuthToken( getAccount().type, cred.getAuthToken() ); } else { am.clearPassword(getAccount()); } } } Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class); updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, getAccount()); updateAccountCredentials.putExtra( AuthenticatorActivity.EXTRA_ACTION, AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN); updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); startActivityForResult(updateAccountCredentials, UPDATE_CREDENTIALS_REQUEST_CODE); } catch (com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException e) { Toast.makeText(context, R.string.auth_account_does_not_exist, Toast.LENGTH_SHORT).show(); } }

Target:
protected void requestCredentialsUpdate(Context context) { try { OwnCloudClient client; OwnCloudAccount ocAccount = new OwnCloudAccount(getAccount(), context); client = (OwnCloudClientManagerFactory.getDefaultSingleton(). removeClientFor(ocAccount)); if (client != null) { OwnCloudCredentials cred = client.getCredentials(); if (cred != null) { AccountManager am = AccountManager.get(context); if (cred.authTokenExpires()) { am.invalidateAuthToken( getAccount().type, cred.getAuthToken() ); } else { am.clearPassword(getAccount()); } } } Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class); updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, getAccount()); updateAccountCredentials.putExtra( AuthenticatorActivity.EXTRA_ACTION, AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN); updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); startActivity(updateAccountCredentials); } catch (com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException e) { Toast.makeText(context, R.string.auth_account_does_not_exist, Toast.LENGTH_SHORT).show(); } }
Source:
public InsertByIdWithDurability<T> withExpiry(final Duration expiry) { return new ExecutableInsertByIdSupport<>(template, domainType, collection, persistTo, replicateTo, durabilityLevel, expiry); }

Target:
public InsertByIdWithDurability<T> withExpiry(final Duration expiry) { Assert.notNull(expiry, "expiry must not be null."); return new ExecutableInsertByIdSupport<>(template, domainType, collection, persistTo, replicateTo, durabilityLevel, expiry); }
Source:
private Handler<Void> handlerInContext(Handler<Void> handler) { return vv -> connection.getContext().runOnContext(v -> handler.handle(null)); }

Target:
private Handler<Void> handlerInContext(Handler<Void> handler) { return vv -> connection.getContext().runOnContext(handler); }
Source:
public void accepts( org.opengis.feature.FeatureVisitor visitor, org.opengis.util.ProgressListener progress) throws IOException { Name typeName = transformer.getSource().getName(); if (typeName != null) { try { SimpleFeatureSource fs = (SimpleFeatureSource) source.getDataStore().getFeatureSource(typeName); if (fs instanceof ContentFeatureSource) { ((ContentFeatureSource) fs).accepts(query, visitor, progress); return; } } catch (IOException e) { LOGGER.info("Failed to invoke method ContentFeatureSource.accepts()"); } } super.accepts(visitor, progress); }

Target:
public void accepts( org.opengis.feature.FeatureVisitor visitor, org.opengis.util.ProgressListener progress) throws IOException { Name typeName = transformer.getSource().getName(); if (isTypeCompatible(visitor, transformer.getSchema())) { source.getDataStore() .getFeatureSource(typeName) .getFeatures() .accepts(visitor, progress); } else { super.accepts(visitor, progress); } }
Source:
public String getName() { return name().toLowerCase(); }

Target:
public String getName() { return name().toLowerCase(Locale.ROOT); }
Source:
private static CasualtyDetails calculateRolledAaCasualties( final List<Unit> availableTargets, final AaPowerStrengthAndRolls unitPowerAndRollsMap, final DiceRoll dice, final IDelegateBridge bridge) { final int hits = dice.getHits(); final Collection<Unit> hitTargets; if (unitPowerAndRollsMap.calculateTotalRolls() == availableTargets.size() && hits < availableTargets.size()) { hitTargets = findRolledTargets(availableTargets, dice); } else if (hits < availableTargets.size()) { hitTargets = findRandomTargets(availableTargets, bridge, hits); } else { hitTargets = availableTargets; } return buildCasualtyDetails(availableTargets, hitTargets); }

Target:
private static Collection<Unit> calculateRolledAaCasualties( final List<Unit> availableTargets, final AaPowerStrengthAndRolls unitPowerAndRollsMap, final DiceRoll dice, final IDelegateBridge bridge) { if (unitPowerAndRollsMap.calculateTotalRolls() == availableTargets.size() && dice.getHits() < availableTargets.size()) { return findRolledTargets(availableTargets, dice); } else if (dice.getHits() < availableTargets.size()) { return findRandomTargets(availableTargets, bridge, dice.getHits()); } else { return availableTargets; } }
Source:
public static boolean isGridMenuEnabled(){ SharedPreferences properties = CommCareApplication._().getCurrentApp().getAppPreferences(); return properties.getString(GRID_MENUS_ENABLED, BuildConfig.DEBUG ? CommCarePreferences.YES : CommCarePreferences.NO).equals(CommCarePreferences.YES); }

Target:
public static boolean isGridMenuEnabled(){ SharedPreferences properties = CommCareApplication._().getCurrentApp().getAppPreferences(); return properties.getString(GRID_MENUS_ENABLED, CommCarePreferences.NO).equals(CommCarePreferences.YES); }
Source:
private void handleRunningTestState(String testID) throws BenchFlowTestIDDoesNotExistException { logger.info("handleRunningTestState for " + testID); boolean exit = false; BenchFlowTestState testState; TestRunningState testRunningState = testModelDAO.getTestRunningState(testID); TestRunningState prevTestRunningState; setTimeoutIfNeeded(testID); while (!exit) { prevTestRunningState = testRunningState; try { testState = handleTestRunningState(testID); } catch (BenchFlowTestIDDoesNotExistException e) { e.printStackTrace(); break; } testRunningState = testModelDAO.getTestRunningState(testID); logger.info("handleRunningTestState: testState == " + testState); if (testState != null && (testState == WAITING || testState == TERMINATED)) { exit = true; } else if (prevTestRunningState != null && testRunningState != null && prevTestRunningState == TestRunningState.DETERMINE_EXECUTE_EXPERIMENTS && testRunningState == TestRunningState.HANDLE_EXPERIMENT_RESULT || testRunningState == TestRunningState.TERMINATING) { exit = true; } } }

Target:
private void handleRunningTestState(String testID) throws BenchFlowTestIDDoesNotExistException { logger.info("handleRunningTestState for " + testID); boolean exit = false; BenchFlowTestState testState; TestRunningState testRunningState; setTimeoutIfNeeded(testID); while (!exit) { try { testState = handleTestRunningState(testID); } catch (BenchFlowTestIDDoesNotExistException e) { e.printStackTrace(); break; } testRunningState = testModelDAO.getTestRunningState(testID); logger.info("handleRunningTestState: testState == " + testState); logger.info("handleRunningTestState: testRunningState == " + testRunningState); if (testState == WAITING || testState == TERMINATED) { exit = true; } else if (testRunningState == TestRunningState.HANDLE_EXPERIMENT_RESULT || testRunningState == TestRunningState.TERMINATING) { exit = true; } } }
Source:
public void shouldValidateMultipleIssuers() { String token = "eyJhbGciOiJIUzI1NiIsImN0eSI6IkpXVCJ9.eyJpc3MiOiJhdXRoMCJ9.mZ0m_N1J4PgeqWmi903JuUoDRZDBPB7HwkS4nVyWH1M"; DecodedJWT jwt = JWTVerifier.init(Algorithm.HMAC256("secret")) .withIssuer("otherIssuer", "auth0") .build() .verify(token); assertThat(jwt, is(notNullValue())); }

Target:
public void shouldValidateMultipleIssuers() { String auth0Token = "eyJhbGciOiJIUzI1NiIsImN0eSI6IkpXVCJ9.eyJpc3MiOiJhdXRoMCJ9.mZ0m_N1J4PgeqWmi903JuUoDRZDBPB7HwkS4nVyWH1M"; String otherIssuertoken = "eyJhbGciOiJIUzI1NiIsImN0eSI6IkpXVCJ9.eyJpc3MiOiJvdGhlcklzc3VlciJ9.k4BCOJJl-c0_Y-49VD_mtt-u0QABKSV5i3W-RKc74co"; JWTVerifier verifier = JWTVerifier.init(Algorithm.HMAC256("secret")) .withIssuer("otherIssuer", "auth0") .build(); assertThat(verifier.verify(auth0Token), is(notNullValue())); assertThat(verifier.verify(otherIssuertoken), is(notNullValue())); }
Source:
public void getUserBalancesShouldReturnTheRequest() throws Exception { final AtomicReference<Request> bodyRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); final RestAdapter adapter = new RestAdapter.Builder().setEndpoint(MOCK_URL).setClient(new Client() { @Override public Response execute(Request request) throws IOException { bodyRef.set(request); latch.countDown(); return null; } }).build(); final UserService userService = adapter.create(UserService.class); userService.getUserBalances(new RetrofitPromise<Balance>()); latch.await(); Assert.assertEquals(bodyRef.get().getUrl(), String.format("%s/v0/me", MOCK_URL)); Assert.assertEquals(bodyRef.get().getMethod(), "GET"); }

Target:
public void getUserBalancesShouldReturnTheRequest() throws Exception { final AtomicReference<Request> bodyRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); final RestAdapter adapter = new RestAdapter.Builder().setEndpoint(MOCK_URL).setClient(new Client() { @Override public Response execute(Request request) throws IOException { bodyRef.set(request); latch.countDown(); return null; } }).build(); final UserService userService = adapter.create(UserService.class); userService.getUserBalances(new RetrofitPromise<Balance>()); latch.await(); Assert.assertEquals(bodyRef.get().getMethod(), "GET"); Assert.assertEquals(bodyRef.get().getUrl(), String.format("%s/v0/me", MOCK_URL)); }
Source:
public void initialize(LdbcConfiguration conf) { String formatDateTimeString = DatagenParams.getDateTimeFormat(); gmtDateTimeFormatter = DateTimeFormatter.ofPattern(formatDateTimeString).withZone(DateUtils.UTC); String formatDateString = DatagenParams.getDateFormat(); gmtDateFormatter = DateTimeFormatter.ofPattern(formatDateString).withZone(DateUtils.UTC); }

Target:
public void initialize(LdbcConfiguration conf) { String formatDateTimeString = DatagenParams.getDateTimeFormat(); gmtDateTimeFormatter = DateTimeFormatter.ofPattern(formatDateTimeString).withZone(GMT); String formatDateString = DatagenParams.getDateFormat(); gmtDateFormatter = DateTimeFormatter.ofPattern(formatDateString).withZone(GMT); }
Source:
public OpenTxnsResponse open_txns(OpenTxnRequest rqst) throws TException { OpenTxnsResponse response = getTxnHandler().openTxns(rqst); List<Long> txnIds = response.getTxn_ids(); if (!listeners.isEmpty()) { MetaStoreListenerNotifier.notifyEvent(listeners, EventType.OPEN_TXN, new OpenTxnEvent(txnIds.iterator(), this)); } if (!transactionalListeners.isEmpty()) { MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventType.OPEN_TXN, new OpenTxnEvent(txnIds.iterator(), this)); } return response; }

Target:
public OpenTxnsResponse open_txns(OpenTxnRequest rqst) throws TException { OpenTxnsResponse response = getTxnHandler().openTxns(rqst); List<Long> txnIds = response.getTxn_ids(); if (txnIds != null && listeners != null && !listeners.isEmpty()) { MetaStoreListenerNotifier.notifyEvent(listeners, EventType.OPEN_TXN, new OpenTxnEvent(txnIds, this)); } return response; }
Source:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; BigFraction otherValue = ((ILScore)obj).getValue(); return this.value.equals(otherValue); }

Target:
public boolean equals(Object obj) { if (obj == null) return false; if (getClass() != obj.getClass()) return false; BigFraction otherValue = ((ILScore)obj).getValue(); return this.value.equals(otherValue); }
Source:
private <T> T getEntity(Response r, Class<T> clazz) { try { String response = r.readEntity(String.class); int responseCode = getResponseCode(response); if (responseCode == CatalogResponse.ResponseMessage.ENTITY_NOT_FOUND.getCode()) { return null; } else if(responseCode == CatalogResponse.ResponseMessage.EXCEPTION.getCode()) { throw new RuntimeException("Error occurred "+ getResponseMessage(response)); } else { ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.readTree(response); return mapper.treeToValue(node.get("entity"), clazz); } } catch (Exception ex) { throw new RuntimeException(ex); } }

Target:
private <T> T getEntity(Response r, Class<T> clazz) { try { String response = r.readEntity(String.class); int responseCode = getResponseCode(response); if (responseCode == CatalogResponse.ResponseMessage.ENTITY_NOT_FOUND.getCode()) { return null; } else if(responseCode != CatalogResponse.ResponseMessage.SUCCESS.getCode()) { throw new RuntimeException("Error occurred "+ getResponseMessage(response)); } else { ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.readTree(response); return mapper.treeToValue(node.get("entity"), clazz); } } catch (IOException ex) { throw new RuntimeException(ex); } }
Source:
private boolean isSpanAnnotation(BratAnnotation ann) { if (ann instanceof SpanAnnotation && (nameTypes == null || nameTypes.size() == 0 || nameTypes.contains(ann.getType()))) { return true; } return false; }

Target:
private boolean isSpanAnnotation(BratAnnotation ann) { if (ann instanceof SpanAnnotation && (nameTypes == null || nameTypes.contains(ann.getType()))) { return true; } return false; }
Source:
public HiveMetadataFactory( HiveClientConfig hiveClientConfig, ExtendedHiveMetastore metastore, HdfsEnvironment hdfsEnvironment, HivePartitionManager partitionManager, @ForHiveClient ExecutorService executorService, TypeManager typeManager, LocationService locationService, TableParameterCodec tableParameterCodec, JsonCodec<PartitionUpdate> partitionUpdateCodec, TypeTranslator typeTranslator, NodeVersion nodeVersion) { this( metastore, hdfsEnvironment, partitionManager, hiveClientConfig.getDateTimeZone(), hiveClientConfig.getMaxConcurrentFileRenames(), hiveClientConfig.getAllowCorruptWritesForTesting(), hiveClientConfig.isSkipDeletionForAlter(), hiveClientConfig.isBucketWritingEnabled(), hiveClientConfig.getWritesToNonManagedTablesEnabled(), hiveClientConfig.getCreatesOfNonManagedTablesEnabled(), hiveClientConfig.getPerTransactionMetastoreCacheMaximumSize(), typeManager, locationService, tableParameterCodec, partitionUpdateCodec, executorService, typeTranslator, nodeVersion.toString(), hiveClientConfig.getMaxPartitionsPerScan()); }

Target:
public HiveMetadataFactory( HiveClientConfig hiveClientConfig, ExtendedHiveMetastore metastore, HdfsEnvironment hdfsEnvironment, HivePartitionManager partitionManager, @ForHiveClient ExecutorService executorService, TypeManager typeManager, LocationService locationService, TableParameterCodec tableParameterCodec, JsonCodec<PartitionUpdate> partitionUpdateCodec, TypeTranslator typeTranslator, NodeVersion nodeVersion) { this( metastore, hdfsEnvironment, partitionManager, hiveClientConfig.getDateTimeZone(), hiveClientConfig.getMaxConcurrentFileRenames(), hiveClientConfig.getAllowCorruptWritesForTesting(), hiveClientConfig.isSkipDeletionForAlter(), hiveClientConfig.isBucketWritingEnabled(), hiveClientConfig.getWritesToNonManagedTablesEnabled(), hiveClientConfig.getCreatesOfNonManagedTablesEnabled(), hiveClientConfig.getPerTransactionMetastoreCacheMaximumSize(), hiveClientConfig.getMaxPartitionsPerScan(), typeManager, locationService, tableParameterCodec, partitionUpdateCodec, executorService, typeTranslator, nodeVersion.toString()); }
Source:
private static boolean isCloudStackOnlyVag(SolidFireConnection sfConnection, SolidFireVag sfVag) { long[] volumeIds = sfVag.getVolumeIds(); if (volumeIds == null || volumeIds.length == 0) { return true; } List<Long> knownSfAccountsForCs = new ArrayList<>(); for (long volumeId : volumeIds) { SolidFireVolume sfVolume = getVolume(sfConnection, volumeId); long sfAccountId = sfVolume.getAccountId(); if (!knownSfAccountsForCs.contains(sfAccountId)) { SolidFireAccount sfAccount = getAccountById(sfConnection, sfAccountId); if (sfAccount.getName().startsWith(SF_CS_ACCOUNT_PREFIX)) { knownSfAccountsForCs.add(sfAccountId); } else { return false; } } } return true; }

Target:
private static boolean isCloudStackOnlyVag(SolidFireConnection sfConnection, SolidFireVag sfVag) { long[] volumeIds = sfVag.getVolumeIds(); if (ArrayUtils.isEmpty(volumeIds)) { return true; } List<Long> knownSfAccountsForCs = new ArrayList<>(); for (long volumeId : volumeIds) { SolidFireVolume sfVolume = getVolume(sfConnection, volumeId); long sfAccountId = sfVolume.getAccountId(); if (!knownSfAccountsForCs.contains(sfAccountId)) { SolidFireAccount sfAccount = getAccountById(sfConnection, sfAccountId); if (sfAccount.getName().startsWith(SF_CS_ACCOUNT_PREFIX)) { knownSfAccountsForCs.add(sfAccountId); } else { return false; } } } return true; }
Source:
protected static boolean nonFatal(Throwable throwable) { return throwable instanceof StackOverflowError || !(throwable instanceof VirtualMachineError || throwable instanceof ThreadDeath || throwable instanceof InterruptedException || throwable instanceof LinkageError); }

Target:
protected static boolean nonFatal(Throwable throwable) { return throwable instanceof StackOverflowError || !(throwable instanceof VirtualMachineError || throwable instanceof ThreadDeath || throwable instanceof InterruptedException || throwable instanceof LinkageError || throwable instanceof CancellationException); }
Source:
public static boolean isPrimitive(Type type) { return indexOf(type, 0) != -1; }

Target:
public static boolean isPrimitive(Type type) { return type instanceof Class<?> && ((Class<?>)type).isPrimitive(); }
Source:
public void testShallowFile() throws Exception { FileRepository repository = createBareRepository(); ObjectDirectory dir = repository.getObjectDatabase(); String commit = "d3148f9410b071edd4a4c85d2a43d1fa2574b0d2"; try (PrintWriter writer = new PrintWriter( new File(repository.getDirectory(), Constants.SHALLOW))) { writer.println(commit); } Set<ObjectId> shallowCommits = dir.getShallowCommits(); assertTrue(shallowCommits.remove(ObjectId.fromString(commit))); assertTrue(shallowCommits.isEmpty()); try (PrintWriter writer = new PrintWriter( new File(repository.getDirectory(), Constants.SHALLOW))) { writer.println("X3148f9410b071edd4a4c85d2a43d1fa2574b0d2"); } try { dir.getShallowCommits(); Assert.fail(); } catch (IOException ex) { } }

Target:
public void testShallowFile() throws Exception { FileRepository repository = createBareRepository(); ObjectDirectory dir = repository.getObjectDatabase(); String commit = "d3148f9410b071edd4a4c85d2a43d1fa2574b0d2"; try (PrintWriter writer = new PrintWriter( new File(repository.getDirectory(), Constants.SHALLOW))) { writer.println(commit); } Set<ObjectId> shallowCommits = dir.getShallowCommits(); assertTrue(shallowCommits.remove(ObjectId.fromString(commit))); assertTrue(shallowCommits.isEmpty()); }
Source:
public void run() { try { int batchSize = config.getBatchSize(); TimelineMetrics metrics = new TimelineMetrics(); while (eventsQueue.size() > 0 && !exec.isShutdown()) { try { final TimelineMetric metricEvent = eventsQueue.poll( config.getWaitForEventTime(), TimeUnit.MILLISECONDS ); if (metricEvent != null) { metrics.addOrMergeTimelineMetric(metricEvent); if (metrics.getMetrics().size() == batchSize) { emitMetrics(metrics); log.debug( "sent [%d] events", metrics.getMetrics().size() ); metrics = new TimelineMetrics(); } } } catch (InterruptedException e) { log.error(e, e.getMessage()); if (e instanceof InterruptedException) { Thread.currentThread().interrupt(); } } if (metrics.getMetrics().size() > 0) { emitMetrics(metrics); log.debug( "sent [%d] events", metrics.getMetrics().size() ); } } } catch (Exception e) { log.error(e, e.getMessage()); if (e instanceof InterruptedException) { Thread.currentThread().interrupt(); } } }

Target:
public void run() { try { int batchSize = config.getBatchSize(); TimelineMetrics metrics = new TimelineMetrics(); while (eventsQueue.size() > 0 && !exec.isShutdown()) { try { final TimelineMetric metricEvent = eventsQueue.poll( config.getWaitForEventTime(), TimeUnit.MILLISECONDS ); if (metricEvent != null) { metrics.addOrMergeTimelineMetric(metricEvent); if (metrics.getMetrics().size() == batchSize) { emitMetrics(metrics); log.debug( "sent [%d] events", metrics.getMetrics().size() ); metrics = new TimelineMetrics(); } } } catch (InterruptedException e) { log.error(e, e.getMessage()); Thread.currentThread().interrupt(); } } if (metrics.getMetrics().size() > 0) { emitMetrics(metrics); log.debug( "sent [%d] events", metrics.getMetrics().size() ); } } catch (Exception e) { log.error(e, e.getMessage()); if (e instanceof InterruptedException) { Thread.currentThread().interrupt(); } } }
Source:
public ResultScanner getScanner(Scan scan) throws IOException { AnviltopServices.ReadTableRequest.Builder request = scanAdapter.adapt(scan); request.setProjectId(options.getProjectId()); request.setTableName(tableName.getQualifierAsString()); try { AnviltopResultScanner scanner = client.readTable(request.build()); return anviltopResultScannerAdapter.adapt(scanner); } catch (ServiceException e) { throw new IOException( makeGenericExceptionMessage( "getScanner", options.getProjectId(), tableName.getQualifierAsString(), new byte[0]), e); } }

Target:
public ResultScanner getScanner(Scan scan) throws IOException { AnviltopServices.ReadTableRequest.Builder request = scanAdapter.adapt(scan); request.setProjectId(options.getProjectId()); request.setTableName(tableName.getQualifierAsString()); try { AnviltopResultScanner scanner = client.readTable(request.build()); return anviltopResultScannerAdapter.adapt(scanner); } catch (ServiceException e) { throw new IOException( makeGenericExceptionMessage( "getScanner", options.getProjectId(), tableName.getQualifierAsString()), e); } }
Source:
public List<DataManipulator<?, ?>> getCustomManipulators() { final List<DataManipulator<?, ?>> list = Lists.newArrayList(); list.addAll(this.manipulators.stream() .map(DataManipulator::copy) .collect(Collectors.toList())); return list; }

Target:
public List<DataManipulator<?, ?>> getCustomManipulators() { final List<DataManipulator<?, ?>> list = Lists.newArrayList(); for (DataManipulator<?, ?> manipulator : this.manipulators) { list.add(manipulator.copy()); } return list; }
Source:
public MetricAggregator provide() { return new SuccessRateAggregator(); }

Target:
public MetricAggregator provide() { return new MetricAggregator<Number>() { private long passNum = 0; private long failNum = 0; @Override public void append(Number calculated) { if (calculated.intValue() != 0) passNum++; else failNum++; } @Override public Double getAggregated() { if ((failNum + passNum) == 0) return new Double(0.0); else return new Double((double) (passNum) / (double) (failNum + passNum)); } @Override public void reset() { } @Override public String getName() { return "aggSR"; } }; }
Source:
private void initializeDefaultListeners() { ExitCodeListener exitCodeListener = new ExitCodeListener(this); m_testListeners.put(ExitCodeListener.class, exitCodeListener); if (m_useDefaultListeners) { addListener((ITestNGListener) exitCodeListener); addReporter(SuiteHTMLReporter.class); addReporter(Main.class); addReporter(FailedReporter.class); addReporter(XMLReporter.class); if (System.getProperty("oldTestngEmailableReporter") != null) { addReporter(EmailableReporter.class); } else if (System.getProperty("noEmailableReporter") == null) { addReporter(EmailableReporter2.class); } addReporter(JUnitReportReporter.class); if (m_verbose != null && m_verbose > 4) { addListener(new VerboseReporter("[TestNG] ")); } } }

Target:
private void initializeDefaultListeners() { addListener((ITestNGListener) new ExitCodeListener(this)); if (m_useDefaultListeners) { addReporter(SuiteHTMLReporter.class); addReporter(Main.class); addReporter(FailedReporter.class); addReporter(XMLReporter.class); if (System.getProperty("oldTestngEmailableReporter") != null) { addReporter(EmailableReporter.class); } else if (System.getProperty("noEmailableReporter") == null) { addReporter(EmailableReporter2.class); } addReporter(JUnitReportReporter.class); if (m_verbose != null && m_verbose > 4) { addListener(new VerboseReporter("[TestNG] ")); } } }
Source:
public void actionPerformed(ActionEvent event) { if (event.getParameters() == null) { Log.error(getClass(), localization.canNotOpenFileWithoutParams()); return; } final String pathToOpen = event.getParameters().get(FILE_PARAM_ID); if (pathToOpen == null) { Log.error(getClass(), localization.fileToOpenIsNotSpecified()); return; } appContext .getWorkspaceRoot() .getFile(pathToOpen) .then( optionalFile -> { if (optionalFile.isPresent()) { if (actionCompletedCallback != null) { actionCompletedCallback.onSuccess(null); } editorAgent.openEditor( optionalFile.get(), new EditorAgent.OpenEditorCallback() { @Override public void onEditorOpened(EditorPartPresenter editor) { new Timer() { @Override public void run() { scrollToLine(editor, event.getParameters().get(LINE_PARAM_ID)); } }.schedule(300); } @Override public void onInitializationFailed() @Override public void onEditorActivated(EditorPartPresenter editor) { new Timer() { @Override public void run() { scrollToLine(editor, event.getParameters().get(LINE_PARAM_ID)); } }.schedule(300); } }); } else { if (actionCompletedCallback != null) { actionCompletedCallback.onFailure(null); } notificationManager.notify( localization.unableOpenResource(pathToOpen), FAIL, FLOAT_MODE); } }); }

Target:
public void actionPerformed(ActionEvent event) { if (event.getParameters() == null) { Log.error(getClass(), localization.canNotOpenFileWithoutParams()); return; } final String pathToOpen = event.getParameters().get(FILE_PARAM_ID); if (pathToOpen == null) { Log.error(getClass(), localization.fileToOpenIsNotSpecified()); return; } appContext .getWorkspaceRoot() .getFile(pathToOpen) .then( optionalFile -> { if (optionalFile.isPresent()) { if (actionCompletedCallback != null) { actionCompletedCallback.onSuccess(null); } editorAgent.openEditor( optionalFile.get(), new EditorAgent.OpenEditorCallback() { @Override public void onEditorOpened(EditorPartPresenter editor) { scrollToLine(editor, event.getParameters().get(LINE_PARAM_ID)); } @Override public void onInitializationFailed() @Override public void onEditorActivated(EditorPartPresenter editor) { scrollToLine(editor, event.getParameters().get(LINE_PARAM_ID)); } }); } else { if (actionCompletedCallback != null) { actionCompletedCallback.onFailure(null); } notificationManager.notify( localization.unableOpenResource(pathToOpen), FAIL, FLOAT_MODE); } }); }
Source:
public IndexDefinition createIndexDefinition( Label label, String... propertyKeys ) { KernelTransaction transaction = safeAcquireTransaction( transactionSupplier ); try ( Statement ignore = transaction.acquireStatement() ) { try { IndexDefinition indexDefinition = new IndexDefinitionImpl( this, label, propertyKeys, false ); TokenWrite tokenWrite = transaction.tokenWrite(); int labelId = tokenWrite.labelGetOrCreateForName( indexDefinition.getLabel().name() ); int[] propertyKeyIds = getOrCreatePropertyKeyIds( tokenWrite, indexDefinition ); LabelSchemaDescriptor descriptor = SchemaDescriptorFactory.forLabel( labelId, propertyKeyIds ); transaction.schemaWrite().indexCreate( descriptor ); return indexDefinition; } catch ( IllegalTokenNameException e ) { throw new IllegalArgumentException( e ); } catch ( SchemaKernelException e ) { throw new ConstraintViolationException( e.getUserMessage( new SilentTokenNameLookup( transaction.tokenRead() ) ), e ); } } }

Target:
public IndexDefinition createIndexDefinition( Label label, String... propertyKeys ) { KernelTransaction transaction = safeAcquireTransaction( transactionSupplier ); try ( Statement ignore = transaction.acquireStatement() ) { try { IndexDefinition indexDefinition = new IndexDefinitionImpl( this, label, propertyKeys, false ); TokenWrite tokenWrite = transaction.tokenWrite(); int labelId = tokenWrite.labelGetOrCreateForName( indexDefinition.getLabel().name() ); int[] propertyKeyIds = getOrCreatePropertyKeyIds( tokenWrite, indexDefinition ); LabelSchemaDescriptor descriptor = SchemaDescriptorFactory.forLabel( labelId, propertyKeyIds ); transaction.schemaWrite().indexCreate( descriptor ); return indexDefinition; } catch ( IllegalTokenNameException e ) { throw new IllegalArgumentException( e ); } catch ( InvalidTransactionTypeKernelException | SchemaKernelException e ) { throw new ConstraintViolationException( e.getUserMessage( new SilentTokenNameLookup( transaction.tokenRead() ) ), e ); } } }
Source:
private int computeSellValue(Item item, boolean total) { int value = 0; int currentStock; int defaultStock = 0; int stockDiff = 0; if(container.contains(item)) { currentStock = container.computeAmountForId(item.getId()); if(amountMap[container.computeIndexForId(item.getId()).getAsInt()].isPresent()) defaultStock = amountMap[container.computeIndexForId(item.getId()).getAsInt()].getAsInt(); if((currentStock - defaultStock) > 10) stockDiff = 10; else if((currentStock - defaultStock) < -10) stockDiff = -10; else stockDiff = currentStock - defaultStock; } double lowAlch = item.getItemDef().getValue() * 0.4; for(int i = 0; i < (total ? item.getAmount() : 1); i++) { value += lowAlch - ((stockDiff * 0.075) * lowAlch); if(stockDiff < 10) stockDiff++; } return value <= 0 ? 1 : value; }

Target:
private int computeSellValue(Item item, boolean total) { int stockDiff = 0; if(container.contains(item)) { int currentStock = container.computeAmountForId(item.getId()); var index = container.computeIndexForId(item.getId()); int defaultStock = index.isPresent() ? amountMap[index.getAsInt()].orElse(0): 0; if((currentStock - defaultStock) > 10) { stockDiff = 10; } else if((currentStock - defaultStock) < -10) { stockDiff = -10; } else { stockDiff = currentStock - defaultStock; } } double lowAlch = item.getItemDef().getValue() * 0.4; int value = 0; for(int i = 0; i < (total ? item.getAmount() : 1); i++) { value += lowAlch - ((stockDiff * 0.075) * lowAlch); if(stockDiff < 10) stockDiff++; } return value <= 0 ? 1 : value; }
Source:
private List<Task> getBaselineTasks() { List<Task> tasks = new ArrayList<Task>(); for (MCMCWrapper model : d_models.values()) { tasks.add(model.getActivityTask()); } return tasks; }

Target:
private List<Task> getBaselineTasks() { List<Task> tasks = new ArrayList<Task>(); for (MCMCWrapper model : d_models.values()) { if(model.getModel() instanceof AbstractBaselineModel) { tasks.add(model.getActivityTask()); } } return tasks; }
Source:
public AdapterPair adapterTrimIlluminaPairedReads(final SAMRecord read1, final SAMRecord read2, final int minMatchBases, final double maxErrorRate) { final AdapterPair ret = ClippingUtility.adapterTrimIlluminaPairedReads(read1, read2, minMatchBases, maxErrorRate, adapters.get()); if (ret != null && !thresholdReached) { if(!preAdapterPrunedRecords.containsKey(ret)) { preAdapterPrunedRecords.put(ret, new ArrayList<>()); } preAdapterPrunedRecords.get(ret).add(read1); preAdapterPrunedRecords.get(ret).add(read2); tallyFoundAdapter(ret); } return ret; }

Target:
public AdapterPair adapterTrimIlluminaPairedReads(final SAMRecord read1, final SAMRecord read2, final int minMatchBases, final double maxErrorRate) { final AdapterPair ret = ClippingUtility.adapterTrimIlluminaPairedReads(read1, read2, minMatchBases, maxErrorRate, adapters.get()); tallyAndFixAdapters(ret, read1, read2); return ret; }
Source:
public static PDPrintStyle getLineStyle (JSONObject oskariStyle) { PDPrintStyle style = new PDPrintStyle(); JSONObject stroke = JSONHelper.optJSONObject(oskariStyle, "stroke", () -> new JSONObject()); setStrokeStyle(style, stroke); setLabelStyle(style, oskariStyle); style.setLineCap(LINE_CAP_STYLE.getOrDefault(JSONHelper.optString(stroke,"lineCap"), 0)); return style; }

Target:
public static PDPrintStyle getLineStyle (JSONObject oskariStyle) { JSONObject stroke = oskariStyle.optJSONObject("stroke"); PDPrintStyle style = new PDPrintStyle(); setStrokeStyle(style, stroke); setLabelStyle(style, oskariStyle); return style; }
Source:
public Page(String wikiName) { this.wikiName = wikiName; this.wikiPath = null; }

Target:
public Page(String wikiName) { this.wikiName = wikiName; }
Source:
public void assertWorkDir(Map<String, String> i) throws CorruptObjectException, IOException { TreeWalk walk = new TreeWalk(db); walk.setRecursive(true); walk.addTree(new FileTreeIterator(db)); String expectedValue; String path; int nrFiles = 0; FileTreeIterator ft; while (walk.next()) { ft = walk.getTree(0, FileTreeIterator.class); path = ft.getEntryPathString(); expectedValue = i.get(path); assertNotNull("found unexpected file for path " + path + " in workdir", expectedValue); File file = new File(db.getWorkTree(), path); assertTrue(file.exists()); if (file.isFile()) { FileInputStream is = new FileInputStream(file); byte[] buffer = new byte[(int) file.length()]; int offset = 0; int numRead = 0; while (offset < buffer.length && (numRead = is.read(buffer, offset, buffer.length - offset)) >= 0) { offset += numRead; } is.close(); assertArrayEquals("unexpected content for path " + path + " in workDir. ", buffer, i.get(path).getBytes()); nrFiles++; } } assertEquals("WorkDir has not the right size.", i.size(), nrFiles); }

Target:
public void assertWorkDir(Map<String, String> i) throws CorruptObjectException, IOException { TreeWalk walk = new TreeWalk(db); walk.setRecursive(false); walk.addTree(new FileTreeIterator(db)); String expectedValue; String path; int nrFiles = 0; FileTreeIterator ft; while (walk.next()) { ft = walk.getTree(0, FileTreeIterator.class); path = ft.getEntryPathString(); expectedValue = i.get(path); File file = new File(db.getWorkTree(), path); assertTrue(file.exists()); if (file.isFile()) { assertNotNull("found unexpected file for path " + path + " in workdir", expectedValue); FileInputStream is = new FileInputStream(file); byte[] buffer = new byte[(int) file.length()]; int offset = 0; int numRead = 0; while (offset < buffer.length && (numRead = is.read(buffer, offset, buffer.length - offset)) >= 0) { offset += numRead; } is.close(); assertArrayEquals("unexpected content for path " + path + " in workDir. ", buffer, i.get(path).getBytes()); nrFiles++; } else if (file.isDirectory()) { if (file.list().length == 0) { assertEquals("found unexpected empty folder for path " + path + " in workDir. ", "/", i.get(path)); nrFiles++; } } if (walk.isSubtree()) { walk.enterSubtree(); } } assertEquals("WorkDir has not the right size.", i.size(), nrFiles); }