auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> public void getRefTest() throws IOException, ParseException { <END> JSONObject jsonObject = MapboxTestUtils.parseTestStyle("getRefTest.json"); MBLayer layer = MBLayer.create(jsonObject); System.out.print("st"); }</code><technical_language>This test fixed in a commit</technical_language>

Target:
public void getRefTest() throws IOException, ParseException { JSONObject jsonObject = MapboxTestUtils.parseTestStyle("getRefTest.json"); MBStyle mbStyle = new MBStyle(jsonObject); MBLayer layer = mbStyle.layers().get(2); assertEquals("water", layer.getRef()); assertEquals("water", mbStyle.layer(layer.getRef()).getSourceLayer()); assertEquals("mapbox", mbStyle.layer(layer.getRef()).getSource()); assertEquals(11, mbStyle.layer(layer.getRef()).getMinZoom()); assertEquals(22, mbStyle.layer(layer.getRef()).getMaxZoom()); assertEquals("round", mbStyle.layer(layer.getRef()).getLayout().get("line-join")); }
Source:
<code>private void undeployLeftoverJobs() { try { final Map<JobId, Job> jobs = heliosClient.jobs().get(); if (jobs.size() > 0) { log.info("There are jobs in helios-solo left over by TemporaryJobs. " + "Undeploying and deleting them now. Jobs: {}", jobs.keySet()); } for (final JobId jobId : jobs.keySet()) { final JobStatus jobStatus = heliosClient.jobStatus(jobId).get(); final Map<String, TaskStatus> statuses = jobStatus.getTaskStatuses(); for (Map.Entry<String, TaskStatus> status : statuses.entrySet()) { final String host = status.getKey(); if (status.getValue().getGoal().equals(Goal.START)) { log.info("Job is still set to START on host {}. Undeploying it now.", jobId, host); final JobUndeployResponse undeployResponse = heliosClient.undeploy(jobId, host).get(); log.info("Undeploy response for job is {}.", jobId, undeployResponse.getStatus()); log.info("Waiting for job to actually be undeployed...", jobId); <START> awaitJobUndeployed(heliosClient, host, jobId, 400, TimeUnit.SECONDS); <END> log.info("Job successfully undeployed.", jobId); } } } } catch (Exception e) { log.warn("Exception occurred when trying to clean up leftover temp jobs.", e); } }</code><technical_language>400 seconds?</technical_language>

Target:
protected void undeployLeftoverJobs() { try { final Map<JobId, Job> jobs = heliosClient.jobs().get(); if (jobs.size() > 0) { log.info("There are leftover jobs deployed by helios-solo. " + "Undeploying and deleting them now. Jobs: {}", jobs.keySet()); } for (final JobId jobId : jobs.keySet()) { final JobStatus jobStatus = heliosClient.jobStatus(jobId).get(); final Map<String, TaskStatus> statuses = jobStatus.getTaskStatuses(); for (Map.Entry<String, TaskStatus> status : statuses.entrySet()) { final String host = status.getKey(); final Goal goal = status.getValue().getGoal(); if (goal != Goal.UNDEPLOY) { log.info("Job is still set to on host {}. Undeploying it now.", jobId, goal, host); final JobUndeployResponse undeployResponse = heliosClient.undeploy(jobId, host).get(); log.info("Undeploy response for job is {}.", jobId, undeployResponse.getStatus()); if (undeployResponse.getStatus() != JobUndeployResponse.Status.OK) { log.warn("Undeploy response for job was not OK. Not waiting for job to " + "actually be undeployed.", jobId); } } log.info("Waiting for job to actually be undeployed...", jobId); awaitJobUndeployed(heliosClient, host, jobId, jobUndeployWaitSeconds, TimeUnit.SECONDS); log.info("Job successfully undeployed.", jobId); } } } catch (Exception e) { log.warn("Exception occurred when trying to clean up leftover jobs.", e); } }
Source:
<code>public BlobHolder convert(BlobHolder blobHolder, Map<String, Serializable> parameters) throws ConversionException { List<Blob> blobs = new ArrayList<>(); blobs.add(new StringBlob("blob1","text/plain",AbstractBlob.UTF_8,"file1")); <START> blobs.add(new StringBlob("blob2","text/plain",AbstractBlob.UTF_8,"file2")); <END> return new SimpleCachableBlobHolder(blobs); }</code><technical_language>Space ,</technical_language>

Target:
public BlobHolder convert(BlobHolder blobHolder, Map<String, Serializable> parameters) throws ConversionException { List<Blob> blobs = new ArrayList<>(); blobs.add(new StringBlob("blob1", TEXT_PLAIN, UTF_8, "file1")); blobs.add(new StringBlob("blob2", TEXT_PLAIN, UTF_8, "file2")); return new SimpleCachableBlobHolder(blobs); }
Source:
<code>private List<SubscriptionEventTypeStats> createSubscriptionStat(final Subscription subscription, final boolean includeDistance) throws InconsistentStateException, ServiceTemporarilyUnavailableException { final List<EventType> eventTypes = getEventTypesForSubscription(subscription); <START> final List<PartitionEndStatistics> topicPartitions = loadPartitionEndStatistics(eventTypes); <END> final ZkSubscriptionClient subscriptionClient = createZkSubscriptionClient(subscription); final Optional<ZkSubscriptionNode> zkSubscriptionNode = subscriptionClient.getZkSubscriptionNode(); return loadStats(eventTypes, zkSubscriptionNode, subscriptionClient, topicPartitions, includeDistance); }</code><technical_language>I do this call includeDistance value. this method Kafka do this expensive seek operation. I thought in case of light-stats check offsets in Kafka</technical_language>

Target:
private List<SubscriptionEventTypeStats> createSubscriptionStat(final Subscription subscription, final boolean includeDistance) throws InconsistentStateException, ServiceTemporarilyUnavailableException { final List<EventType> eventTypes = getEventTypesForSubscription(subscription); final ZkSubscriptionClient subscriptionClient = createZkSubscriptionClient(subscription); final Optional<ZkSubscriptionNode> zkSubscriptionNode = subscriptionClient.getZkSubscriptionNode(); if (includeDistance) { return loadStats(eventTypes, zkSubscriptionNode, subscriptionClient); } else { return loadLightStats(eventTypes, zkSubscriptionNode); } }
Source:
<code>protected void buildVmCD() { XmlRpcStruct struct; if (vm.getVmPayload() != null && vm.getVmPayload().getType() == VmDeviceType.CDROM) { VmDevice vmDevice = new VmDevice(new VmDeviceId(Guid.NewGuid(), vm.getId()), VmDeviceType.DISK.getName(), VmDeviceType.CDROM.getName(), "", 0, (vm.getVmPayload() == null) ? null : vm.getVmPayload().getSpecParams(), true, true, true, ""); struct = new XmlRpcStruct(); addCdDetails(vmDevice, struct); addDevice(struct, vmDevice, ""); } else if (vm.isRunOnce() && !StringUtils.isEmpty(vm.getCdPath())) { VmDevice vmDevice = new VmDevice(new VmDeviceId(Guid.NewGuid(), vm.getId()), VmDeviceType.DISK.getName(), VmDeviceType.CDROM.getName(), "", 0, (vm.getVmPayload() == null) ? null : vm.getVmPayload().getSpecParams(), true, true, true, ""); struct = new XmlRpcStruct(); addCdDetails(vmDevice, struct); addDevice(struct, vmDevice, vm.getCdPath()); } else { List<VmDevice> vmDevices = DbFacade.getInstance() .getVmDeviceDAO() .getVmDeviceByVmIdTypeAndDevice(vm.getId(), VmDeviceType.DISK.getName(), VmDeviceType.CDROM.getName()); for (VmDevice vmDevice : vmDevices) { if (!vmDevice.getIsManaged()) { continue; } if (!VmPayload.isPayload(vmDevice.getSpecParams()) && vmDevices.size() > 1) { continue; } struct = new XmlRpcStruct(); String cdPath = vm.getCdPath(); addCdDetails(vmDevice, struct); addAddress(vmDevice, struct); <START> addDevice(struct, vmDevice, cdPath == null ? "" : cdPath); <END> break; } } }</code><technical_language>Please addDevice code, change encapsulated there. please contact shavivi this change affect payload</technical_language>

Target:
protected void buildVmCD() { XmlRpcStruct struct; if (vm.getVmPayload() != null && vm.getVmPayload().getType() == VmDeviceType.CDROM) { VmDevice vmDevice = new VmDevice(new VmDeviceId(Guid.NewGuid(), vm.getId()), VmDeviceType.DISK.getName(), VmDeviceType.CDROM.getName(), "", 0, (vm.getVmPayload() == null) ? null : vm.getVmPayload().getSpecParams(), true, true, true, ""); struct = new XmlRpcStruct(); addCdDetails(vmDevice, struct); addDevice(struct, vmDevice, ""); } else if (vm.isRunOnce() && !StringUtils.isEmpty(vm.getCdPath())) { VmDevice vmDevice = new VmDevice(new VmDeviceId(Guid.NewGuid(), vm.getId()), VmDeviceType.DISK.getName(), VmDeviceType.CDROM.getName(), "", 0, (vm.getVmPayload() == null) ? null : vm.getVmPayload().getSpecParams(), true, true, true, ""); struct = new XmlRpcStruct(); addCdDetails(vmDevice, struct); addDevice(struct, vmDevice, vm.getCdPath()); } else { List<VmDevice> vmDevices = DbFacade.getInstance() .getVmDeviceDao() .getVmDeviceByVmIdTypeAndDevice(vm.getId(), VmDeviceType.DISK.getName(), VmDeviceType.CDROM.getName()); for (VmDevice vmDevice : vmDevices) { if (!vmDevice.getIsManaged()) { continue; } if (!VmPayload.isPayload(vmDevice.getSpecParams()) && vmDevices.size() > 1) { continue; } struct = new XmlRpcStruct(); String cdPath = vm.getCdPath(); addCdDetails(vmDevice, struct); addAddress(vmDevice, struct); addDevice(struct, vmDevice, cdPath == null ? "" : cdPath); break; } } }
Source:
<code>public String toString() { return <START> MessageFormat.format(Messages.ConfigurationImpl_toString, nodeConfiguration); <END> }</code><technical_language>ConfigurationImpl_toString = Node configuration: {0}\nEdge configuration: {1} MessageFormat.format(Messages.ConfigurationImpl_toString, nodeConfiguration, edgeConfiguration);</technical_language>

Target:
public String toString() { return MessageFormat.format(Messages.ConfigurationImpl_toString, nodeConfiguration, edgeConfiguration); }
Source:
<code>public static DataSourceCredentials map(com.azure.search.documents.implementation.models.DataSourceCredentials obj) { if (obj == null) { return null; } <START> DataSourceCredentials dataSourceCredentials = new DataSourceCredentials(); <END> String _connectionString = obj.getConnectionString(); dataSourceCredentials.setConnectionString(_connectionString); return dataSourceCredentials; }</code><technical_language>this need a custom internal representation? This is a simple credential wrapping class</technical_language>

Target:
public static DataSourceCredentials map(com.azure.search.documents.implementation.models.DataSourceCredentials obj) { if (obj == null) { return null; } DataSourceCredentials dataSourceCredentials = new DataSourceCredentials(); String connectionString = obj.getConnectionString(); dataSourceCredentials.setConnectionString(connectionString); return dataSourceCredentials; }
Source:
<code>public void testInvalidBinaryDecodeFromHex1() { assertEvaluate("decode('\\xff', 'hex')", null); <START> } <END></code><technical_language>I suggest expectedException rule this suite test for a user-friendly error message</technical_language>

Target:
public void testInvalidBinaryDecodeFromHex1() { expectedException.expect(IllegalStateException.class); expectedException.expectMessage("Illegal hexadecimal character \\ at index 0"); assertEvaluate("decode('\\xff', 'hex')", null); }
Source:
<code>public Object convert(Class destClass, Object srcObject) { Class<?> srcObjectClass = srcObject.getClass(); LocalDateTime result; if (Date.class.isAssignableFrom(srcObjectClass)) { Instant instant = ((Date) srcObject).toInstant(); result = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()); } else if (Instant.class.isAssignableFrom(srcObjectClass)) { result = LocalDateTime.ofInstant(((Instant) srcObject), ZoneId.systemDefault()); } else if (Long.class.isAssignableFrom(srcObjectClass)) { Instant instant = Instant.ofEpochMilli((Long) srcObject); result = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()); } else { return super.convert(destClass, srcObject); } if (LocalTime.class.isAssignableFrom(destClass)) { return result.toLocalTime(); } else if (LocalDate.class.isAssignableFrom(destClass)) { return result.toLocalDate(); } <START> return result; <END> }</code><technical_language>return of result is hard follow code wise. return once, return result is retrieved</technical_language>

Target:
public Object convert(Class destClass, Object srcObject) { LocalDateTime localDateTime = convertToLocalDateTime(srcObject); if (localDateTime != null) { if (LocalTime.class.isAssignableFrom(destClass)) { return localDateTime.toLocalTime(); } else if (LocalDate.class.isAssignableFrom(destClass)) { return localDateTime.toLocalDate(); } return localDateTime; } return super.convert(destClass, srcObject); }
Source:
<code>public List<Lifeline> getAllLifelines() { List<Lifeline> allLifelines = null; if (useCache) { if (allLifelinesCache != null) { allLifelines = Lists.newArrayList(allLifelinesCache); } } if (allOrderedLifelinesCache == null) { if (allLifelines == null) { allLifelines = Lists.newArrayList(); Collection<InstanceRole> allInstanceRoles = getAllInstanceRoles(); Function<ISequenceNode, Lifeline> lifelineFunction = new Function<ISequenceNode, Lifeline>() { public Lifeline apply(ISequenceNode from) { return from.getLifeline().get(); } }; allLifelines = Lists.newArrayList(Iterables.transform(allInstanceRoles, lifelineFunction)); if (useCache) { allLifelinesCache = <START> Lists.newArrayList(allLifelines); <END> } } Collections.sort(allLifelines, RangeHelper.lowerBoundOrdering().onResultOf(ISequenceEvent.VERTICAL_RANGE)); allOrderedLifelinesCache = allLifelines; } return allOrderedLifelinesCache; }</code><technical_language>Do copy: store allLifelines in cache: copy of collection. l250: cache sorted. For next sort (after a clearSortedCache), non-sorted caches pre-sorted sort faster</technical_language>

Target:
public List<Lifeline> getAllLifelines() { List<Lifeline> allLifelines = null; if (useCache) { if (allLifelinesCache != null) { allLifelines = Lists.newArrayList(allLifelinesCache); } } if (allOrderedLifelinesCache == null) { if (allLifelines == null) { allLifelines = Lists.newArrayList(); Collection<InstanceRole> allInstanceRoles = getAllInstanceRoles(); Function<ISequenceNode, Lifeline> lifelineFunction = new Function<ISequenceNode, Lifeline>() { public Lifeline apply(ISequenceNode from) { return from.getLifeline().get(); } }; allLifelines = Lists.newArrayList(Iterables.transform(allInstanceRoles, lifelineFunction)); if (useCache) { allLifelinesCache = allLifelines; } } Collections.sort(allLifelines, RangeHelper.lowerBoundOrdering().onResultOf(ISequenceEvent.VERTICAL_RANGE)); allOrderedLifelinesCache = Lists.newArrayList(allLifelines); } return allOrderedLifelinesCache; }
Source:
<code>Set<ExecutableElement> abstractBuildMethods() { <START> return ImmutableSet.copyOf(buildMethods).stream() <END> .filter(MoreElements.hasModifiers(Modifier.ABSTRACT)) .collect(Collectors.toSet()); }</code><technical_language>copyOf superfluous</technical_language>

Target:
Set<ExecutableElement> abstractBuildMethods() { return buildMethods.stream() .filter(MoreElements.hasModifiers(Modifier.ABSTRACT)) .collect(Collectors.toSet()); }
Source:
<code>StaticMethodInstanceFactory(Class<T> type, Method method) { super(method); this.type = requireNonNull(type, "type is null"); requireNonNull(method, "method is null"); <START> if (!Modifier.isStatic(method.getModifiers())) { <END> throw new IllegalArgumentException("Method not static " + method); } this.method = method; }</code><technical_language>I method return type checked for assignability type, failure message a fuller sentence > method "Foo.bar" is a valid factory method</technical_language>

Target:
StaticMethodInstanceFactory(Class<T> type, Method method) { super(method); this.type = requireNonNull(type, "type is null"); requireNonNull(method, "method is null"); if (!isStaticFactoryMethodFor(method, type)) { throw new IllegalArgumentException(format("Given method \"%s\" is not a valid factory method for %s", method, type)); } this.method = method; }
Source:
<code>public static String getCommonJsImportPath( Node requireCall, ModuleLoader.ResolutionMode resolutionMode) { if (resolutionMode == ModuleLoader.ResolutionMode.WEBPACK) { if (requireCall.getSecondChild().isNumber()) { <START> return String.valueOf(Double.valueOf(requireCall.getSecondChild().getDouble()).intValue()); <END> } else if (requireCall.getChildCount() >= 3 && requireCall.getChildAtIndex(2).isNumber()) { return String.valueOf( Double.valueOf(requireCall.getChildAtIndex(2).getDouble()).intValue()); } } return requireCall.getSecondChild().getString(); }</code><technical_language>below, simplify Double.valueOf(n.getDouble()).intValue() -> (int) n.getDouble()</technical_language>

Target:
public static String getCommonJsImportPath( Node requireCall, ModuleLoader.ResolutionMode resolutionMode) { if (resolutionMode == ModuleLoader.ResolutionMode.WEBPACK) { Node pathArgument = requireCall.getChildCount() >= 3 ? requireCall.getChildAtIndex(2) : requireCall.getSecondChild(); if (pathArgument.isNumber()) { return String.valueOf((int) pathArgument.getDouble()); } else { return pathArgument.getString(); } } return requireCall.getSecondChild().getString(); }
Source:
<code>public ValidationResult externalNetworkDetailsUnchanged(Network newNetwork) { return Objects.equals(network.getVlanId(), newNetwork.getVlanId()) && network.getStp() == newNetwork.getStp() <START> && network.isVmNetwork() == newNetwork.isVmNetwork() <END> ? ValidationResult.VALID : new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_EXTERNAL_NETWORK_DETAILS_CANNOT_BE_EDITED); }</code><technical_language>I suggested remove this line, I a check ProviderNetwork.providerId ProviderNetwork.externalId is changed</technical_language>

Target:
public ValidationResult externalNetworkDetailsUnchanged(Network newNetwork) { ProviderNetwork providerNetwork = network.getProvidedBy(); ProviderNetwork newProviderNetwork = newNetwork.getProvidedBy(); return Objects.equals(network.getVlanId(), newNetwork.getVlanId()) && network.getStp() == newNetwork.getStp() && network.isVmNetwork() == newNetwork.isVmNetwork() && Objects.equals(providerNetwork.getProviderId(), newProviderNetwork.getProviderId()) && Objects.equals(providerNetwork.getExternalId(), newProviderNetwork.getExternalId()) ? ValidationResult.VALID : new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_EXTERNAL_NETWORK_DETAILS_CANNOT_BE_EDITED); }
Source:
<code>protected void cleanup(Context context) throws IOException, InterruptedException { <START> super.cleanup(context); <END> try { if (!sourceHasData && targetResultSet == null) { getTargetResultSet(context.getConfiguration(), null, null); } if(targetResultSet != null) { while (targetHasNext) { ImmutableBytesWritable targetKey = null; if (targetResultSet.getCurrentRow() != null) { targetKey = new ImmutableBytesWritable(); targetResultSet.getCurrentRow().getKey(targetKey); } logFailRowAndIncrementCounter(context, Counter.ONLY_IN_TARGET_TABLE_ROWS, targetKey); targetHasNext = targetResultSet.next(); } } } catch (SQLException e) { LOG.error("Unable to properly scan the peer table", e); } finally { try { targetResultSet.close(); targetResultSet = null; } catch (SQLException e) { LOG.error("Unable to close peer result set", e); } } }</code><technical_language>nit: while condition targetResultSet.next()</technical_language>

Target:
protected void cleanup(Context context) throws IOException, InterruptedException { super.cleanup(context); try { if(targetResultSet != null) { while (targetHasNext) { ImmutableBytesWritable targetKey = null; if (targetResultSet.getCurrentRow() != null) { targetKey = new ImmutableBytesWritable(); targetResultSet.getCurrentRow().getKey(targetKey); } logFailRowAndIncrementCounter(context, Counter.ONLY_IN_TARGET_TABLE_ROWS, targetKey); targetHasNext = targetResultSet.next(); } } } catch (SQLException e) { LOG.error("Unable to properly scan the peer table", e); } finally { try { if(targetResultSet != null) { targetResultSet.close(); targetResultSet = null; } } catch (SQLException e) { LOG.error("Unable to close peer result set", e); } } }
Source:
<code>public AccountStore getAccountStore() { String href = getAccountStoreHref(); AccountStore accountStore = null; if (href.contains("directories")) { accountStore = getDataStore().getResource(href, Directory.class); } else if (href.contains("groups")) { accountStore = getDataStore().getResource(href, Group.class); <START> } else if (href.contains("organizations")){ <END> accountStore = getDataStore().getResource(href, Organization.class); } return accountStore; }</code><technical_language>please do this way: href.contains("/organizations/") (note slash beginning end) please do: href.contains("/groups/") href.contains("/directories/") ? If group is called "my_organizations_group" this code group is organization. If add slashes "if (href.contains(...)) {" overcome problem</technical_language>

Target:
public AccountStore getAccountStore() { String href = getAccountStoreHref(); AccountStore accountStore = null; if (href.contains("/directories/")) { accountStore = getDataStore().getResource(href, Directory.class); } else if (href.contains("/groups/")) { accountStore = getDataStore().getResource(href, Group.class); } else if (href.contains("/organizations/")){ accountStore = getDataStore().getResource(href, Organization.class); } return accountStore; }
Source:
<code>public WorkState getState(String string) { <START> for (WorkState state : new CopyOnWriteArrayList<WorkState>(states)) { <END> if (state.getName().equals(string)) { return state; } } return null; }</code><technical_language>of need a concurrent data structure. if a regular list a linkedlist, variable local, subject comodification</technical_language>

Target:
public WorkState getState(String string) { for (WorkState state : states) { if (state.getName().equals(string)) { return state; } } return null; }
Source:
<code>private static void setupApplicationRoot() throws IOException { Path tempDir = Files.createTempDirectory(AppConfigurationInitialisationTest.class.getName()); tempDir.toFile().deleteOnExit(); <START> System.setProperty("application.user.root", tempDir.toString()); <END> }</code><technical_language>This sounds want do in a @BeforeClass annotated method</technical_language>

Target:
public static void setupApplicationRoot() throws IOException { Path tempDir = Files.createTempDirectory(AppConfigurationInitialisationTest.class.getName()); tempDir.toFile().deleteOnExit(); System.setProperty("application.user.root", tempDir.toString()); }
Source:
<code>public QuotaConfig(VerifiableProperties verifiableProperties) { storageQuotaConfig = new StorageQuotaConfig(verifiableProperties); requestQuotaThrottlingEnabled = verifiableProperties.getBoolean(REQUEST_QUOTA_THROTTLING_ENABLED, false); hostQuotaThrottlingEnabled = verifiableProperties.getBoolean(HOST_QUOTA_THROTTLING_ENABLED, false); requestQuotaEnforcerSourcePairInfoJson = verifiableProperties.getString(REQUEST_QUOTA_ENFORCER_SOURCE_PAIR_INFO_JSON, buildDefaultQuotaEnforcerSourceInfoPairJson()); hostQuotaEnforcerFactories = <START> Utils.splitString(verifiableProperties.getString(HOST_QUOTA_ENFORCER_FACTORIES, ""), ",", HashSet::new); <END> quotaManagerFactoryClass = verifiableProperties.getString(QUOTA_MANAGER_FACTORY_CLASS, DEFAULT_QUOTA_MANAGER_FACTORY_CLASS); quotaThrottlingMode = QuotaMode.valueOf(verifiableProperties.getString(QUOTA_THROTTLING_MODE, DEFAULT_QUOTA_THROTTLING_MODE)); }</code><technical_language>leaving a note. discussed host-level quotas. this is need configure running a redliner test Ambry frontends</technical_language>

Target:
public QuotaConfig(VerifiableProperties verifiableProperties) { storageQuotaConfig = new StorageQuotaConfig(verifiableProperties); requestQuotaThrottlingEnabled = verifiableProperties.getBoolean(REQUEST_QUOTA_THROTTLING_ENABLED, false); hostQuotaThrottlingEnabled = verifiableProperties.getBoolean(HOST_QUOTA_THROTTLING_ENABLED, false); requestQuotaEnforcerSourcePairInfoJson = verifiableProperties.getString(REQUEST_QUOTA_ENFORCER_SOURCE_PAIR_INFO_JSON, buildDefaultQuotaEnforcerSourceInfoPairJson().toString()); hostQuotaEnforcerFactories = Utils.splitString(verifiableProperties.getString(HOST_QUOTA_ENFORCER_FACTORIES, ""), ",", HashSet::new); quotaManagerFactoryClass = verifiableProperties.getString(QUOTA_MANAGER_FACTORY_CLASS, DEFAULT_QUOTA_MANAGER_FACTORY_CLASS); quotaThrottlingMode = QuotaMode.valueOf(verifiableProperties.getString(QUOTA_THROTTLING_MODE, DEFAULT_QUOTA_THROTTLING_MODE)); }
Source:
<code>public void registerCacheEventListener(CacheEventListener<? super K, ? super V> listener, EventOrdering ordering, EventFiring firing, EnumSet<EventType> forEventTypes) { boolean doRegister = forEventTypes.contains(EventType.EVICTED) || forEventTypes.contains(EventType.EXPIRED); EventListenerWrapper wrapper = new EventListenerWrapper(listener, firing, ordering, forEventTypes); if(wrapper.config.orderingMode() == EventOrdering.ORDERED) { orderedListenerCount.incrementAndGet(); } <START> if(aSyncListenersSet.contains(wrapper) || syncListenersSet.contains(wrapper)) { <END> throw new IllegalStateException("Cache Event Listener already registered: " + listener); } if (firing == EventFiring.ASYNCHRONOUS) { aSyncListenersSet.add(wrapper); } else { syncListenersSet.add(wrapper); } if (doRegister) { store.enableStoreEventNotifications(storeListener); } }</code><technical_language>need do here, observe result of calling add throw false</technical_language>

Target:
public void registerCacheEventListener(CacheEventListener<? super K, ? super V> listener, EventOrdering ordering, EventFiring firing, EnumSet<EventType> forEventTypes) { boolean doRegister = forEventTypes.contains(EventType.EVICTED) || forEventTypes.contains(EventType.EXPIRED); EventListenerWrapper wrapper = new EventListenerWrapper(listener, firing, ordering, forEventTypes); if(wrapper.config.orderingMode() == EventOrdering.ORDERED) { orderedListenerCount.incrementAndGet(); } if(aSyncListenersSet.contains(wrapper) || syncListenersSet.contains(wrapper)) { throw new IllegalStateException("Cache Event Listener already registered: " + listener); } if (firing == EventFiring.ASYNCHRONOUS) { aSyncListenersSet.add(wrapper); } else { syncListenersSet.add(wrapper); } if (doRegister) { store.enableStoreEventNotifications(storeListener); } synchronized (this) { if (eventThreadLocal instanceof NoOpEventThreadLocalImpl) { eventThreadLocal = new EventThreadLocalImpl(); } } }
Source:
<code>public void createControl(Composite parent) { fPane= new CreateTextFilePreviewer(parent, SWT.BORDER | SWT.FLAT); Dialog.applyDialogFont(fPane); fSourceViewer = new SourceViewer(fPane, null, SWT.V_SCROLL | SWT.H_SCROLL | SWT.MULTI | SWT.FULL_SELECTION); fSourceViewer.setEditable(false); <START> Control sourceViewerControl= fSourceViewer.getControl(); <END> sourceViewerControl.setFont(JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT)); IPreferenceStore preferenceStore= EditorsUI.getPreferenceStore(); Color bg = getColorFromStore(preferenceStore, AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND, sourceViewerControl.getDisplay()); Color fg = getColorFromStore(preferenceStore, AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND, sourceViewerControl.getDisplay()); Color selBg = getColorFromStore(preferenceStore, AbstractTextEditor.PREFERENCE_COLOR_SELECTION_BACKGROUND, sourceViewerControl.getDisplay()); Color selFg = getColorFromStore(preferenceStore, AbstractTextEditor.PREFERENCE_COLOR_SELECTION_FOREGROUND, sourceViewerControl.getDisplay()); sourceViewerControl.setBackground(bg); sourceViewerControl.setForeground(fg); if (sourceViewerControl instanceof StyledText) { StyledText styledText = (StyledText) sourceViewerControl; styledText.setSelectionBackground(selBg); styledText.setSelectionForeground(selFg); } disposeColors(); fForegroundColor= fg; fBackgroundColor= bg; fSelectionForegroundColor= selFg; fSelectionBackgroundColor= selBg; sourceViewerControl.addDisposeListener(e -> disposeColors()); fPane.setContent(sourceViewerControl); }</code><technical_language>need a StyledText for selection colors I StyledText sourceViewerControl = fSourceViewer.getTextWidget(); here. need instanceof test below</technical_language>

Target:
public void createControl(Composite parent) { fPane= new CreateTextFilePreviewer(parent, SWT.BORDER | SWT.FLAT); Dialog.applyDialogFont(fPane); fSourceViewer = new FileChangeSourceViewer(fPane, null, SWT.V_SCROLL | SWT.H_SCROLL | SWT.MULTI | SWT.FULL_SELECTION); fPane.setContent(fSourceViewer.getControl()); }
Source:
<code><START> public static Intent newIntent(Activity activity, EnrolledCoursesResponse courseData, CourseUpgradeResponse courseUpgradeData, String courseComponentId, String lastAccessedId, boolean isVideosMode) { Bundle courseBundle = new Bundle(); courseBundle.putSerializable(EXTRA_COURSE_DATA, courseData); courseBundle.putParcelable(EXTRA_COURSE_UPGRADE_DATA, courseUpgradeData); courseBundle.putString(EXTRA_COURSE_COMPONENT_ID, courseComponentId); final Intent intent = new Intent(activity, CourseOutlineActivity.class); intent.putExtra(EXTRA_BUNDLE, courseBundle); intent.putExtra(EXTRA_LAST_ACCESSED_ID, lastAccessedId); intent.putExtra(EXTRA_IS_VIDEOS_MODE, isVideosMode); return intent; } <END></code><technical_language>Need auto-format</technical_language>

Target:
public static Intent newIntent(Activity activity, EnrolledCoursesResponse courseData, CourseUpgradeResponse courseUpgradeData, String courseComponentId, String lastAccessedId, boolean isVideosMode) { final Bundle courseBundle = new Bundle(); courseBundle.putSerializable(EXTRA_COURSE_DATA, courseData); courseBundle.putParcelable(EXTRA_COURSE_UPGRADE_DATA, courseUpgradeData); courseBundle.putString(EXTRA_COURSE_COMPONENT_ID, courseComponentId); final Intent intent = new Intent(activity, CourseOutlineActivity.class); intent.putExtra(EXTRA_BUNDLE, courseBundle); intent.putExtra(EXTRA_LAST_ACCESSED_ID, lastAccessedId); intent.putExtra(EXTRA_IS_VIDEOS_MODE, isVideosMode); return intent; }
Source:
<code>public void setUp() { <START> filteringXmlStreamWriter = new FilteringXmlStreamWriter(xmlStreamWriterMock, null); <END> filteringXmlStreamWriter.nonXmlCharFilterer = nonXmlCharFiltererMock; when(nonXmlCharFiltererMock.filter("value")).thenReturn("filteredValue"); }</code><technical_language>avoided removing API break mentioned earlier</technical_language>

Target:
public void setUp() { filteringXmlStreamWriter = new FilteringXmlStreamWriter(xmlStreamWriterMock); filteringXmlStreamWriter.nonXmlCharFilterer = nonXmlCharFiltererMock; when(nonXmlCharFiltererMock.filter("value")).thenReturn("filteredValue"); }
Source:
<code>protected void refreshVisuals() { <START> final DDiagramElement diagElement = this.resolveDiagramElement(); <END> if (primaryShape != null) { final boolean firstRegion = isFirstRegionPart(); if (firstRegion && primaryShape.getBorder() instanceof LineBorder || !firstRegion && primaryShape.getBorder() instanceof MarginBorder) { configureBorder(primaryShape); } if (diagElement instanceof DNodeContainer) { final DNodeContainer container = (DNodeContainer) diagElement; if (primaryShape instanceof GradientRoundedRectangle && container.getOwnedStyle() instanceof FlatContainerStyle) { if (((GradientRoundedRectangle) primaryShape).getBackgroundStyle() != ((FlatContainerStyle) container.getOwnedStyle()).getBackgroundStyle()) { ((AbstractDiagramContainerEditPart) this).reInitFigure(); } } } } super.refreshVisuals(); }</code><technical_language>moved is used, this potentially costly operation is done needed</technical_language>

Target:
protected void refreshVisuals() { if (primaryShape != null) { final boolean firstRegion = isFirstRegionPart(); if (firstRegion && primaryShape.getBorder() instanceof LineBorder || !firstRegion && primaryShape.getBorder() instanceof MarginBorder) { configureBorder(primaryShape); } final DDiagramElement diagElement = this.resolveDiagramElement(); if (diagElement instanceof DNodeContainer) { final DNodeContainer container = (DNodeContainer) diagElement; if (primaryShape instanceof GradientRoundedRectangle && container.getOwnedStyle() instanceof FlatContainerStyle) { if (((GradientRoundedRectangle) primaryShape).getBackgroundStyle() != ((FlatContainerStyle) container.getOwnedStyle()).getBackgroundStyle()) { ((AbstractDiagramContainerEditPart) this).reInitFigure(); } } } } super.refreshVisuals(); }
Source:
<code>private void testConnection(URL url) throws IOException { try { URLConnection connection = (URLConnection) ProxyConfiguration.open(url); <START> connection.setConnectTimeout(20000); END> connection.connect(); if(connection instanceof HttpURLConnection) { int responseCode = ((HttpURLConnection)connection).getResponseCode(); if(HttpURLConnection.HTTP_OK != responseCode) { throw new HttpRetryException("Invalid response code (" + responseCode + ") from URL: " + url.toString(), responseCode); } } else { Util.copyStreamAndClose(connection.getInputStream(),new NullOutputStream()); } } catch (SSLHandshakeException e) { if (e.getMessage().contains("PKIX path building failed")) throw new IOException("Failed to validate the SSL certificate of "+url,e); } }</code><technical_language>Is this fixed 20 seconds deliberately? reuse default ProxyConfiguration</technical_language>

Target:
private void testConnection(URL url) throws IOException { try { URLConnection connection = (URLConnection) ProxyConfiguration.open(url); if(connection instanceof HttpURLConnection) { int responseCode = ((HttpURLConnection)connection).getResponseCode(); if(HttpURLConnection.HTTP_OK != responseCode) { throw new HttpRetryException("Invalid response code (" + responseCode + ") from URL: " + url, responseCode); } } else { Util.copyStreamAndClose(connection.getInputStream(),new NullOutputStream()); } } catch (SSLHandshakeException e) { if (e.getMessage().contains("PKIX path building failed")) throw new IOException("Failed to validate the SSL certificate of "+url,e); } }
Source:
<code>private static List<String> getCompileFilePaths(@NotNull JpsModule module, @NotNull ElixirTarget target, @NotNull CompileContext context, Collection<File> files){ <START> if(JavaBuilderUtil.isCompileJavaIncrementally(context)){ <END> return getCompileFilePathsDefault(module, target); } return ContainerUtil.map(files, new Function<File, String>() { @Override public String fun(File file) { return file.getAbsolutePath(); } }); }</code><technical_language>[x] this do this is building Java? Is this copied another project this code is based on</technical_language>

Target:
private static List<String> getCompileFilePaths(@NotNull JpsModule module, @NotNull ElixirTarget target, @NotNull CompileContext context, Collection<File> files){ if(context.getScope().isBuildIncrementally(target.getTargetType())){ return getCompileFilePathsDefault(module, target); } return ContainerUtil.map(files, new Function<File, String>() { @Override public String fun(File file) { return file.getAbsolutePath(); } }); }
Source:
<code>public String getDescription() { <START> StringBuffer sb = new StringBuffer("a union between \""); <END> Joiner joiner = Joiner.on("\", \""); List<String> descriptionList = Lists.transform(vfsList, new Function<VFS, String>() { @Override public String apply(VFS vfs) { return vfs.getDescription(); }}); try { joiner.appendTo(sb, descriptionList); } catch (IOException e) { throw new AssertionError(e); } return sb.append("\"").toString(); }</code><technical_language>StringBuilder</technical_language>

Target:
public String getDescription() { StringBuilder sb = new StringBuilder("a union between \""); Joiner joiner = Joiner.on("\", \""); List<String> descriptionList = Lists.transform(vfsList, new Function<VFS, String>() { @Override public String apply(VFS vfs) { return vfs.getDescription(); }}); joiner.appendTo(sb, descriptionList); return sb.append("\"").toString(); }
Source:
<code>private void loadImages(final IDockerConnection connection) { final Job loadImagesJob = new Job(DVMessages .getFormattedString("ImagesLoadJob.msg", connection.getUri())) { @Override protected IStatus run(final IProgressMonitor monitor) { connection.getImages(true); return Status.OK_STATUS; } }; <START> loadImagesJob.addJobChangeListener(new <END> JobChangeAdapter() { @Override public void done(IJobChangeEvent event) { Display.getDefault().asyncExec(() -> { viewer.refresh(); }); } }); loadImagesJob.schedule(); }</code><technical_language>this exact ? viewer.refresh() runs, connection.getImages(true) completed. I avoid touching this if benefit</technical_language>

Target:
private void loadImages(final IDockerConnection connection) { final Job loadImagesJob = new Job(DVMessages .getFormattedString("ImagesLoadJob.msg", connection.getUri())) { @Override protected IStatus run(final IProgressMonitor monitor) { connection.getImages(true); Display.getDefault().asyncExec(() -> { viewer.refresh(); }); return Status.OK_STATUS; } }; loadImagesJob.schedule(); }
Source:
<code><START> public int hashCode() { <END> final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; }</code><technical_language>I I this code in another PR this week, standardized in a utility class something</technical_language>

Target:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + name.hashCode(); result = prime * result + value.hashCode(); return result; }
Source:
<code>public void getVolumeSnapshotSchedule(AsyncQuery aQuery, Guid volumeId) { aQuery.converterCallback = new IAsyncConverter() { @Override public Object Convert(Object source, AsyncQuery asyncQuery) { <START> return source != null ? source : null; <END> } }; Frontend.getInstance().runQuery(VdcQueryType.GetGlusterVolumeSnapshotScheduleByVolumeId, new IdQueryParameters(volumeId), aQuery); }</code><technical_language>This converter effect</technical_language>

Target:
public void getVolumeSnapshotSchedule(AsyncQuery aQuery, Guid volumeId) { aQuery.converterCallback = new IAsyncConverter() { @Override public Object Convert(Object source, AsyncQuery asyncQuery) { return source; } }; Frontend.getInstance().runQuery(VdcQueryType.GetGlusterVolumeSnapshotScheduleByVolumeId, new IdQueryParameters(volumeId), aQuery); }
Source:
<code><START> public void diskSpaceRequirementsTest() throws StoreException { <END> DiskSpaceRequirements requirements = store.getDiskSpaceRequirements(); if (!isLogSegmented) { assertNull("Expected null DiskSpaceRequirements for non segmented log", requirements); return; } assertEquals(SEGMENT_CAPACITY, requirements.getSegmentSizeInBytes()); assertEquals((LOG_CAPACITY / SEGMENT_CAPACITY) - 3, requirements.getSegmentsNeeded()); assertEquals(0, requirements.getSwapSegmentsInUse()); }</code><technical_language>doc</technical_language>

Target:
public void diskSpaceRequirementsTest() throws Exception { int segmentsAllocated = 3; doDiskSpaceRequirementsTest(segmentsAllocated, 0); File tempFile = File.createTempFile("sample-swap", LogSegmentNameHelper.SUFFIX + BlobStoreCompactor.TEMP_LOG_SEGMENT_NAME_SUFFIX, tempDir); doDiskSpaceRequirementsTest(segmentsAllocated, 1); assertTrue("Could not delete temp file", tempFile.delete()); addCuratedData(SEGMENT_CAPACITY); segmentsAllocated += 1; doDiskSpaceRequirementsTest(segmentsAllocated, 0); File.createTempFile("sample-swap", LogSegmentNameHelper.SUFFIX + BlobStoreCompactor.TEMP_LOG_SEGMENT_NAME_SUFFIX, tempDir).deleteOnExit(); File.createTempFile("sample-swap", LogSegmentNameHelper.SUFFIX + BlobStoreCompactor.TEMP_LOG_SEGMENT_NAME_SUFFIX, tempDir).deleteOnExit(); addCuratedData(SEGMENT_CAPACITY); segmentsAllocated += 1; doDiskSpaceRequirementsTest(segmentsAllocated, 2); }
Source:
<code>public void execute(CommandLine options) throws Exception { super.execute(options); List<String> args = options.getArgList(); Path inputFile = new Path(args.get(0)); Map<String, Long> columnSizes = getColumnSizeInBytes(inputFile); Map<String, Float> columnRatio = getColumnRatio(columnSizes); if (args.size() > 1) { for (String inputColumn : args.subList(1, args.size())) { long size = 0; float ratio = 0; for (String column : columnSizes.keySet()) { if (column.equals(inputColumn) || column.startsWith(inputColumn + ".")) { size += columnSizes.get(column); ratio += columnRatio.get(column); } } <START> Main.out.println(inputColumn + "->" + " Size In Bytes: " + size + " Size In Ratio: " + ratio); <END> } } else { for (String column : columnSizes.keySet()) { Main.out.println(column + "->" + " Size In Bytes: " + columnSizes.get(column) + " Size In Ratio: " + columnRatio.get(column)); } } }</code><technical_language>suggestion Main.out.println(inputColumn + "-> Size In Bytes: " + size + " Size In Ratio: " + ratio);</technical_language>

Target:
public void execute(CommandLine options) throws Exception { super.execute(options); List<String> args = options.getArgList(); Path inputFile = new Path(args.get(0)); Map<String, Long> columnSizes = getColumnSizeInBytes(inputFile); Map<String, Float> columnRatio = getColumnRatio(columnSizes); if (args.size() > 1) { for (String inputColumn : args.subList(1, args.size())) { long size = 0; float ratio = 0; for (String column : columnSizes.keySet()) { if (column.equals(inputColumn) || column.startsWith(inputColumn + ".")) { size += columnSizes.get(column); ratio += columnRatio.get(column); } } Main.out.println(inputColumn + "-> Size In Bytes: " + size + " Size In Ratio: " + ratio); } } else { for (String column : columnSizes.keySet()) { Main.out.println(column + "->" + " Size In Bytes: " + columnSizes.get(column) + " Size In Ratio: " + columnRatio.get(column)); } } }
Source:
<code>public void profileChangePassword(WebContext ctx) { U userAccount = getUser().getUserObject(getUserClass()); userAccount = userAccount.getMapper().refreshOrFail(userAccount); assertNotNew(userAccount); if (ctx.ensureSafePOST()) { try { String oldPassword = ctx.get(PARAM_OLD_PASSWORD).asString(); String newPassword = ctx.get(PARAM_NEW_PASSWORD).asString(); String confirmation = ctx.get(PARAM_CONFIRMATION).asString(); validateOldPassword(oldPassword, userAccount); userAccount.getUserAccountData() .getLogin() .verifyPassword(newPassword, confirmation, userAccount.getUserAccountData().getMinPasswordLength()); userAccount.getUserAccountData().getLogin().setCleartextPassword(newPassword); userAccount.getMapper().update(userAccount); auditLog.neutral("AuditLog.passwordChange").causedByCurrentUser().forCurrentUser().log(); showSavedMessage(); ctx.respondWith().redirectToGet("/profile"); return; } catch (Exception e) { auditLog.neutral("AuditLog.passwordChangeFailed").causedByCurrentUser().forCurrentUser().log(); UserContext.handle(e); } } <START> ctx.respondWith().template("/templates/biz/biz/tenants/profile-change-password.html.pasta", userAccount); <END> }</code><technical_language>dublicate biz</technical_language>

Target:
public void profileChangePassword(WebContext ctx) { U userAccount = getUser().getUserObject(getUserClass()); userAccount = userAccount.getMapper().refreshOrFail(userAccount); assertNotNew(userAccount); if (ctx.ensureSafePOST()) { try { String oldPassword = ctx.get(PARAM_OLD_PASSWORD).asString(); String newPassword = ctx.get(PARAM_NEW_PASSWORD).asString(); String confirmation = ctx.get(PARAM_CONFIRMATION).asString(); validateOldPassword(oldPassword, userAccount); userAccount.getUserAccountData() .getLogin() .verifyPassword(newPassword, confirmation, userAccount.getUserAccountData().getMinPasswordLength()); userAccount.getUserAccountData().getLogin().setCleartextPassword(newPassword); userAccount.getMapper().update(userAccount); auditLog.neutral("AuditLog.passwordChange").causedByCurrentUser().forCurrentUser().log(); showSavedMessage(); ctx.respondWith().redirectToGet("/profile"); return; } catch (Exception e) { auditLog.neutral("AuditLog.passwordChangeFailed").causedByCurrentUser().forCurrentUser().log(); UserContext.handle(e); } } ctx.respondWith().template("/templates/biz/tenants/profile-change-password.html.pasta", userAccount); }
Source:
<code>public void test500DoesNotRetry() { AWSUtils utils = createMock(AWSUtils.class); HttpCommand command = createMock(HttpCommand.class); replay(utils, command); AWSServerErrorRetryHandler retry = new AWSServerErrorRetryHandler(utils, ImmutableSet.<String> of()); <START> assert !retry.shouldRetryRequest(command, HttpResponse.builder().statusCode(INTERNAL_SERVER_ERROR.getStatusCode()).build()); <END> verify(utils, command); }</code><technical_language>testng assertFalse</technical_language>

Target:
public void test500DoesNotRetry() { AWSUtils utils = createMock(AWSUtils.class); HttpCommand command = createMock(HttpCommand.class); replay(utils, command); AWSServerErrorRetryHandler retry = new AWSServerErrorRetryHandler(utils, ImmutableSet.<String> of()); assertFalse(retry.shouldRetryRequest(command, HttpResponse.builder().statusCode(INTERNAL_SERVER_ERROR.getStatusCode()).build())); verify(utils, command); }
Source:
<code>void store(Iterable<Event> events) { final Iterable<EEntity> entities = Iterables.transform(events, EventToEEntity.instance()); <START> store(newLinkedList(entities)); <END> }</code><technical_language>long append new items, newArrayList(..)</technical_language>

Target:
void store(Iterable<Event> events) { final Iterable<EEntity> entities = Iterables.transform(events, EventToEEntity.instance()); store(newArrayList(entities)); }
Source:
<code>public static Total of(String total) { notNull(total, "total"); <START> return Total.valueOf(total.toUpperCase()); <END> }</code><technical_language>please throw some descriptive exception</technical_language>

Target:
public static Total of(String total) { notNull(total, "total"); try { return Total.valueOf(total.toUpperCase()); } catch (IllegalArgumentException e) { throw new UnsupportedOperationException( format("Unknown value for Grid's total: \"%s\", supported values are: [%s]", total, StringUtils.arrayToCommaDelimitedString(Total.values())), e); } }
Source:
<code>public void testTimestampMicrosConversion() throws Exception { TimestampMicrosConversion conversion = new TimestampMicrosConversion(); long instant = May_28_2015_21_46_53_221.getTimeInMillis() * 1000 + 843; Timestamp May_28_2015_21_46_53_221_843_ts = Timestamp.newBuilder().setSeconds(1432849613L).setNanos(221843000) .build(); Assert.assertEquals("Known timestamp should be correct", May_28_2015_21_46_53_221_843_ts, conversion.fromLong(instant, TIMESTAMP_MICROS_SCHEMA, LogicalTypes.timestampMicros())); try { conversion.toLong(May_28_2015_21_46_53_221_843_ts, TIMESTAMP_MICROS_SCHEMA, LogicalTypes.timestampMicros()); Assert.fail("Should not convert DateTime to long"); } catch (UnsupportedOperationException e) { } try { <START> conversion.fromLong((long) -1.0, TIMESTAMP_MICROS_SCHEMA, LogicalTypes.timestampMicros()); <END> } catch (IllegalArgumentException e) { } }</code><technical_language>for micros test</technical_language>

Target:
public void testTimestampMicrosConversion() { TimestampMicrosConversion conversion = new TimestampMicrosConversion(); Timestamp May_28_2015_21_46_53_221_843_ts = Timestamp.newBuilder().setSeconds(1432849613L).setNanos(221843000) .build(); Timestamp Jan_2_1900_3_4_5_678_901_ts = Timestamp.newBuilder().setSeconds(-2208891355L).setNanos(678901000).build(); long instant = May_28_2015_21_46_53_221.getTimeInMillis() * 1000 + 843; Timestamp tsFromInstant = conversion.fromLong(instant, TIMESTAMP_MICROS_SCHEMA, LogicalTypes.timestampMicros()); long roundTrip = conversion.toLong(tsFromInstant, TIMESTAMP_MICROS_SCHEMA, LogicalTypes.timestampMicros()); Assert.assertEquals("Round-trip conversion should work", instant, roundTrip); Assert.assertEquals("Known timestamp should be correct", May_28_2015_21_46_53_221_843_ts, conversion.fromLong(instant, TIMESTAMP_MICROS_SCHEMA, LogicalTypes.timestampMicros())); Assert.assertEquals("Known timestamp should be correct", instant, (long) conversion .toLong(May_28_2015_21_46_53_221_843_ts, TIMESTAMP_MICROS_SCHEMA, LogicalTypes.timestampMicros())); instant = Jan_2_1900_3_4_5_678.getTimeInMillis() * 1000 + 901; tsFromInstant = conversion.fromLong(instant, TIMESTAMP_MICROS_SCHEMA, LogicalTypes.timestampMicros()); roundTrip = conversion.toLong(tsFromInstant, TIMESTAMP_MICROS_SCHEMA, LogicalTypes.timestampMicros()); Assert.assertEquals("Round-trip conversion should work", instant, roundTrip); Assert.assertEquals("Known timestamp should be correct", Jan_2_1900_3_4_5_678_901_ts, conversion.fromLong(instant, TIMESTAMP_MICROS_SCHEMA, LogicalTypes.timestampMicros())); Assert.assertEquals("Known timestamp should be correct", instant, (long) conversion.toLong(Jan_2_1900_3_4_5_678_901_ts, TIMESTAMP_MICROS_SCHEMA, LogicalTypes.timestampMicros())); }