code
stringlengths
130
281k
code_dependency
stringlengths
182
306k
public class class_name { public void copyWeightsToLayer(org.deeplearning4j.nn.api.Layer layer) throws InvalidKerasConfigurationException { if (this.getNumParams() > 0) { String dl4jLayerName = layer.conf().getLayer().getLayerName(); String kerasLayerName = this.getLayerName(); String msg = "Error when attempting to copy weights from Keras layer " + kerasLayerName + " to DL4J layer " + dl4jLayerName; if (getWeights() == null) throw new InvalidKerasConfigurationException(msg + "(weights is null)"); Set<String> paramsInLayer = new HashSet<>(layer.paramTable().keySet()); Set<String> paramsInKerasLayer = new HashSet<>(this.weights.keySet()); /* Check for parameters in layer for which we don't have weights. */ paramsInLayer.removeAll(paramsInKerasLayer); if (!paramsInLayer.isEmpty()) { String joinedParamsInLayer = StringUtils.join(paramsInLayer, ", "); throw new InvalidKerasConfigurationException( msg + "(no stored weights for parameters: " + joinedParamsInLayer + ")"); } /* Check for parameters NOT in layer for which we DO have weights. */ paramsInKerasLayer.removeAll(layer.paramTable().keySet()); if (!paramsInKerasLayer.isEmpty()) { String joinedParamsInKerasLayer = StringUtils.join(paramsInKerasLayer, ", "); throw new InvalidKerasConfigurationException( msg + "(found no parameters named: " + joinedParamsInKerasLayer + ")"); } /* Copy weights. */ for (String paramName : layer.paramTable().keySet()) { try { layer.setParam(paramName, this.weights.get(paramName)); } catch (Exception e) { log.error(e.getMessage()); throw new InvalidKerasConfigurationException(e.getMessage() + "\nTried to set weights for layer with name " + this.getLayerName() + ", of " + layer.conf().getLayer().getClass() + ".\n" + "Failed to set weights for parameter " + paramName + "\n" + "Expected shape for this parameter: " + layer.getParam(paramName).shapeInfoToString() + ", \ngot: " + this.weights.get(paramName).shapeInfoToString()); } } } } }
public class class_name { public void copyWeightsToLayer(org.deeplearning4j.nn.api.Layer layer) throws InvalidKerasConfigurationException { if (this.getNumParams() > 0) { String dl4jLayerName = layer.conf().getLayer().getLayerName(); String kerasLayerName = this.getLayerName(); String msg = "Error when attempting to copy weights from Keras layer " + kerasLayerName + " to DL4J layer " + dl4jLayerName; if (getWeights() == null) throw new InvalidKerasConfigurationException(msg + "(weights is null)"); Set<String> paramsInLayer = new HashSet<>(layer.paramTable().keySet()); Set<String> paramsInKerasLayer = new HashSet<>(this.weights.keySet()); /* Check for parameters in layer for which we don't have weights. */ paramsInLayer.removeAll(paramsInKerasLayer); if (!paramsInLayer.isEmpty()) { String joinedParamsInLayer = StringUtils.join(paramsInLayer, ", "); throw new InvalidKerasConfigurationException( msg + "(no stored weights for parameters: " + joinedParamsInLayer + ")"); } /* Check for parameters NOT in layer for which we DO have weights. */ paramsInKerasLayer.removeAll(layer.paramTable().keySet()); if (!paramsInKerasLayer.isEmpty()) { String joinedParamsInKerasLayer = StringUtils.join(paramsInKerasLayer, ", "); throw new InvalidKerasConfigurationException( msg + "(found no parameters named: " + joinedParamsInKerasLayer + ")"); } /* Copy weights. */ for (String paramName : layer.paramTable().keySet()) { try { layer.setParam(paramName, this.weights.get(paramName)); // depends on control dependency: [try], data = [none] } catch (Exception e) { log.error(e.getMessage()); throw new InvalidKerasConfigurationException(e.getMessage() + "\nTried to set weights for layer with name " + this.getLayerName() + ", of " + layer.conf().getLayer().getClass() + ".\n" + "Failed to set weights for parameter " + paramName + "\n" + "Expected shape for this parameter: " + layer.getParam(paramName).shapeInfoToString() + ", \ngot: " + this.weights.get(paramName).shapeInfoToString()); } // depends on control dependency: [catch], data = [none] } } } }
public class class_name { public List<CmsSearchField> getSearchFields() { I_CmsSearchIndex index = OpenCms.getSearchManager().getIndex(getParamIndexName()); List<CmsSearchField> result = new ArrayList<CmsSearchField>(); Iterator<CmsSearchField> i = index.getFieldConfiguration().getFields().iterator(); while (i.hasNext()) { CmsLuceneField field = (CmsLuceneField)i.next(); if (field.isIndexed() && field.isDisplayed()) { // only include indexed (ie. searchable) fields result.add(field); } } return result; } }
public class class_name { public List<CmsSearchField> getSearchFields() { I_CmsSearchIndex index = OpenCms.getSearchManager().getIndex(getParamIndexName()); List<CmsSearchField> result = new ArrayList<CmsSearchField>(); Iterator<CmsSearchField> i = index.getFieldConfiguration().getFields().iterator(); while (i.hasNext()) { CmsLuceneField field = (CmsLuceneField)i.next(); if (field.isIndexed() && field.isDisplayed()) { // only include indexed (ie. searchable) fields result.add(field); // depends on control dependency: [if], data = [none] } } return result; } }
public class class_name { private Map<String, ColumnDefinition> makeColumnMap(ColumnDefinition[] columns) { Map<String, ColumnDefinition> map = new HashMap<String, ColumnDefinition>(); for (ColumnDefinition def : columns) { map.put(def.getName(), def); } return map; } }
public class class_name { private Map<String, ColumnDefinition> makeColumnMap(ColumnDefinition[] columns) { Map<String, ColumnDefinition> map = new HashMap<String, ColumnDefinition>(); for (ColumnDefinition def : columns) { map.put(def.getName(), def); // depends on control dependency: [for], data = [def] } return map; } }
public class class_name { public static int minutesDiff(Date earlierDate, Date laterDate) { if (earlierDate == null || laterDate == null) { return 0; } return (int) ((laterDate.getTime() / MINUTE_MILLIS) - (earlierDate.getTime() / MINUTE_MILLIS)); } }
public class class_name { public static int minutesDiff(Date earlierDate, Date laterDate) { if (earlierDate == null || laterDate == null) { return 0; // depends on control dependency: [if], data = [none] } return (int) ((laterDate.getTime() / MINUTE_MILLIS) - (earlierDate.getTime() / MINUTE_MILLIS)); } }
public class class_name { public Object getNextElement() { Object element = null; while (currentIndex+1 < endIndex && element == null) { currentIndex++; element = getElement(); } return element; } }
public class class_name { public Object getNextElement() { Object element = null; while (currentIndex+1 < endIndex && element == null) { currentIndex++; // depends on control dependency: [while], data = [none] element = getElement(); // depends on control dependency: [while], data = [none] } return element; } }
public class class_name { public void addNewMessageToSend(MessageID messageID, Collection<Address> destinations, long initialSequenceNumber, boolean deliverToMyself) { MessageInfo messageInfo = new MessageInfo(destinations, initialSequenceNumber, deliverToMyself); if (deliverToMyself) { messageInfo.setProposeReceived(messageID.getAddress()); } sentMessages.put(messageID, messageInfo); } }
public class class_name { public void addNewMessageToSend(MessageID messageID, Collection<Address> destinations, long initialSequenceNumber, boolean deliverToMyself) { MessageInfo messageInfo = new MessageInfo(destinations, initialSequenceNumber, deliverToMyself); if (deliverToMyself) { messageInfo.setProposeReceived(messageID.getAddress()); // depends on control dependency: [if], data = [none] } sentMessages.put(messageID, messageInfo); } }
public class class_name { private static List<SessionStatus> getEndStates() { List<SessionStatus> endStatesRet = new ArrayList<SessionStatus>(); for (SessionStatus s : SessionStatus.values()) { if (s != SessionStatus.RUNNING) { endStatesRet.add(s); } } return endStatesRet; } }
public class class_name { private static List<SessionStatus> getEndStates() { List<SessionStatus> endStatesRet = new ArrayList<SessionStatus>(); for (SessionStatus s : SessionStatus.values()) { if (s != SessionStatus.RUNNING) { endStatesRet.add(s); // depends on control dependency: [if], data = [(s] } } return endStatesRet; } }
public class class_name { public OpenStackRequest<R> queryString(String queryString) { if (queryString != null) { String[] params = queryString.split("&"); for (String param : params) { String[] s = param.split("="); if (s[0] != null && s[1] != null) { queryParam(s[0], s[1]); } } } return this; } }
public class class_name { public OpenStackRequest<R> queryString(String queryString) { if (queryString != null) { String[] params = queryString.split("&"); for (String param : params) { String[] s = param.split("="); if (s[0] != null && s[1] != null) { queryParam(s[0], s[1]); // depends on control dependency: [if], data = [(s[0]] } } } return this; } }
public class class_name { public static <E> List<E> newArrayList(E... values) { List<E> list = new ArrayList<E>(values.length); for (E e : values) { list.add(e); } return list; } }
public class class_name { public static <E> List<E> newArrayList(E... values) { List<E> list = new ArrayList<E>(values.length); for (E e : values) { list.add(e); // depends on control dependency: [for], data = [e] } return list; } }
public class class_name { public void dispatch_event(final EventData eventData) { final TangoPipe tangoPipe = this; if (EventUtil.graphicAvailable()) { // Causes doRun.run() to be executed asynchronously // on the AWT event dispatching thread. Runnable do_work_later = new Runnable() { public void run() { fireTangoPipeEvent(tangoPipe, eventData); } }; SwingUtilities.invokeLater(do_work_later); } else fireTangoPipeEvent(tangoPipe, eventData); } }
public class class_name { public void dispatch_event(final EventData eventData) { final TangoPipe tangoPipe = this; if (EventUtil.graphicAvailable()) { // Causes doRun.run() to be executed asynchronously // on the AWT event dispatching thread. Runnable do_work_later = new Runnable() { public void run() { fireTangoPipeEvent(tangoPipe, eventData); } }; SwingUtilities.invokeLater(do_work_later); // depends on control dependency: [if], data = [none] } else fireTangoPipeEvent(tangoPipe, eventData); } }
public class class_name { @Nullable Object resolveTypeReference(Element element) { if (element instanceof TypeElement) { TypeElement typeElement = (TypeElement) element; return resolveTypeReferenceForTypeElement(typeElement); } return null; } }
public class class_name { @Nullable Object resolveTypeReference(Element element) { if (element instanceof TypeElement) { TypeElement typeElement = (TypeElement) element; return resolveTypeReferenceForTypeElement(typeElement); // depends on control dependency: [if], data = [none] } return null; } }
public class class_name { final public void DotSuffix() throws ParseException { /*@bgen(jjtree) DotSuffix */ AstDotSuffix jjtn000 = new AstDotSuffix(JJTDOTSUFFIX); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000);Token t = null; try { jj_consume_token(DOT); t = jj_consume_token(IDENTIFIER); jjtree.closeNodeScope(jjtn000, true); jjtc000 = false; jjtn000.setImage(t.image); } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); } } } }
public class class_name { final public void DotSuffix() throws ParseException { /*@bgen(jjtree) DotSuffix */ AstDotSuffix jjtn000 = new AstDotSuffix(JJTDOTSUFFIX); boolean jjtc000 = true; jjtree.openNodeScope(jjtn000);Token t = null; try { jj_consume_token(DOT); t = jj_consume_token(IDENTIFIER); jjtree.closeNodeScope(jjtn000, true); jjtc000 = false; jjtn000.setImage(t.image); } finally { if (jjtc000) { jjtree.closeNodeScope(jjtn000, true); // depends on control dependency: [if], data = [none] } } } }
public class class_name { private final static void removeFolders(String folder, List<String> folderTemplates, int numberOfDaysToKeepTempFolders) { long dateToRemoveFiledAfter = (new Date()).getTime() - (numberOfDaysToKeepTempFolders * MILLISECONDS_IN_DAY); File tempFolder = new File(folder); File[] folderChildren = tempFolder.listFiles(); if(null == folderChildren) { log.debug("Folder '" + tempFolder.getName() + "' was empty. Nothing to delete"); return; } for (File currentFile : folderChildren) { if (currentFile.isDirectory()) { for (String folderTemplate : folderTemplates) { if (currentFile.getName().contains(folderTemplate) && (currentFile.lastModified() < dateToRemoveFiledAfter)) { try { currentFile.delete(); FileUtils.deleteDirectory(currentFile); log.debug("Folder '" + currentFile.getName() + "' deleted..."); } catch (Exception e) { log.fatal("Error deleting folder '" + currentFile.getName() + "'"); } } } } } } }
public class class_name { private final static void removeFolders(String folder, List<String> folderTemplates, int numberOfDaysToKeepTempFolders) { long dateToRemoveFiledAfter = (new Date()).getTime() - (numberOfDaysToKeepTempFolders * MILLISECONDS_IN_DAY); File tempFolder = new File(folder); File[] folderChildren = tempFolder.listFiles(); if(null == folderChildren) { log.debug("Folder '" + tempFolder.getName() + "' was empty. Nothing to delete"); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } for (File currentFile : folderChildren) { if (currentFile.isDirectory()) { for (String folderTemplate : folderTemplates) { if (currentFile.getName().contains(folderTemplate) && (currentFile.lastModified() < dateToRemoveFiledAfter)) { try { currentFile.delete(); // depends on control dependency: [try], data = [none] FileUtils.deleteDirectory(currentFile); // depends on control dependency: [try], data = [none] log.debug("Folder '" + currentFile.getName() + "' deleted..."); // depends on control dependency: [try], data = [none] } catch (Exception e) { log.fatal("Error deleting folder '" + currentFile.getName() + "'"); } // depends on control dependency: [catch], data = [none] } } } } } }
public class class_name { Block[] getFileBlocks(String src) { waitForReady(); byte[][] components = INodeDirectory.getPathComponents(src); readLock(); try { INode targetNode = rootDir.getNode(components); if (targetNode == null) return null; if(targetNode.isDirectory()) return null; return ((INodeFile)targetNode).getBlocks(); } finally { readUnlock(); } } }
public class class_name { Block[] getFileBlocks(String src) { waitForReady(); byte[][] components = INodeDirectory.getPathComponents(src); readLock(); try { INode targetNode = rootDir.getNode(components); if (targetNode == null) return null; if(targetNode.isDirectory()) return null; return ((INodeFile)targetNode).getBlocks(); // depends on control dependency: [try], data = [none] } finally { readUnlock(); } } }
public class class_name { private static void rejectDefinedAttributeWithDefaultValue(ResourceTransformationDescriptionBuilder builder, AttributeDefinition... attrs) { for (AttributeDefinition attr : attrs) { builder.getAttributeBuilder() .setDiscard(new DiscardAttributeValueChecker(attr.getDefaultValue()), attr) .addRejectCheck(DEFINED, attr); } } }
public class class_name { private static void rejectDefinedAttributeWithDefaultValue(ResourceTransformationDescriptionBuilder builder, AttributeDefinition... attrs) { for (AttributeDefinition attr : attrs) { builder.getAttributeBuilder() .setDiscard(new DiscardAttributeValueChecker(attr.getDefaultValue()), attr) .addRejectCheck(DEFINED, attr); // depends on control dependency: [for], data = [none] } } }
public class class_name { public static Archiver createArchiver(FileType fileType) { if (fileType == FileType.UNKNOWN) { throw new IllegalArgumentException("Unknown file type"); } if (fileType.isArchive() && fileType.isCompressed()) { return createArchiver(fileType.getArchiveFormat(), fileType.getCompressionType()); } else if (fileType.isArchive()) { return createArchiver(fileType.getArchiveFormat()); } else { throw new IllegalArgumentException("Unknown archive file extension " + fileType); } } }
public class class_name { public static Archiver createArchiver(FileType fileType) { if (fileType == FileType.UNKNOWN) { throw new IllegalArgumentException("Unknown file type"); } if (fileType.isArchive() && fileType.isCompressed()) { return createArchiver(fileType.getArchiveFormat(), fileType.getCompressionType()); // depends on control dependency: [if], data = [none] } else if (fileType.isArchive()) { return createArchiver(fileType.getArchiveFormat()); // depends on control dependency: [if], data = [none] } else { throw new IllegalArgumentException("Unknown archive file extension " + fileType); } } }
public class class_name { public void marshall(CreateVirtualServiceRequest createVirtualServiceRequest, ProtocolMarshaller protocolMarshaller) { if (createVirtualServiceRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(createVirtualServiceRequest.getClientToken(), CLIENTTOKEN_BINDING); protocolMarshaller.marshall(createVirtualServiceRequest.getMeshName(), MESHNAME_BINDING); protocolMarshaller.marshall(createVirtualServiceRequest.getSpec(), SPEC_BINDING); protocolMarshaller.marshall(createVirtualServiceRequest.getTags(), TAGS_BINDING); protocolMarshaller.marshall(createVirtualServiceRequest.getVirtualServiceName(), VIRTUALSERVICENAME_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(CreateVirtualServiceRequest createVirtualServiceRequest, ProtocolMarshaller protocolMarshaller) { if (createVirtualServiceRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(createVirtualServiceRequest.getClientToken(), CLIENTTOKEN_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(createVirtualServiceRequest.getMeshName(), MESHNAME_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(createVirtualServiceRequest.getSpec(), SPEC_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(createVirtualServiceRequest.getTags(), TAGS_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(createVirtualServiceRequest.getVirtualServiceName(), VIRTUALSERVICENAME_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public void deltaForget(long time) { forgetCount.incrementAndGet(); if (time > 0) { forgetTotalTime.addAndGet(time); if (time > forgetMaxTime.get()) forgetMaxTime.set(time); } } }
public class class_name { public void deltaForget(long time) { forgetCount.incrementAndGet(); if (time > 0) { forgetTotalTime.addAndGet(time); // depends on control dependency: [if], data = [(time] if (time > forgetMaxTime.get()) forgetMaxTime.set(time); } } }
public class class_name { public final ChartHelper getChartHelper() { if ((this.chartHelper == null) && (this.parent != null)) { this.chartHelper = new ChartHelper(parent); } return chartHelper; } }
public class class_name { public final ChartHelper getChartHelper() { if ((this.chartHelper == null) && (this.parent != null)) { this.chartHelper = new ChartHelper(parent); // depends on control dependency: [if], data = [none] } return chartHelper; } }
public class class_name { @Override public void executionRecoveryJob(){ if (logger.isDebugEnabled()) { logger.debug("ExecutionRecoveryJob woke up at " + new Date()); } try { executionRecoveryService.doRecovery(); } catch (Exception e){ logger.error("Can't run queue recovery job.",e); } } }
public class class_name { @Override public void executionRecoveryJob(){ if (logger.isDebugEnabled()) { logger.debug("ExecutionRecoveryJob woke up at " + new Date()); // depends on control dependency: [if], data = [none] } try { executionRecoveryService.doRecovery(); // depends on control dependency: [try], data = [none] } catch (Exception e){ logger.error("Can't run queue recovery job.",e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public PolicyFactory toFactory() { ImmutableSet.Builder<String> textContainerSet = ImmutableSet.builder(); for (Map.Entry<String, Boolean> textContainer : this.textContainers.entrySet()) { if (Boolean.TRUE.equals(textContainer.getValue())) { textContainerSet.add(textContainer.getKey()); } } CompiledState compiled = compilePolicies(); return new PolicyFactory( compiled.compiledPolicies, textContainerSet.build(), ImmutableMap.copyOf(compiled.globalAttrPolicies), preprocessor, postprocessor); } }
public class class_name { public PolicyFactory toFactory() { ImmutableSet.Builder<String> textContainerSet = ImmutableSet.builder(); for (Map.Entry<String, Boolean> textContainer : this.textContainers.entrySet()) { if (Boolean.TRUE.equals(textContainer.getValue())) { textContainerSet.add(textContainer.getKey()); // depends on control dependency: [if], data = [none] } } CompiledState compiled = compilePolicies(); return new PolicyFactory( compiled.compiledPolicies, textContainerSet.build(), ImmutableMap.copyOf(compiled.globalAttrPolicies), preprocessor, postprocessor); } }
public class class_name { final List<DBColumn> getPrimaryKeyColumnList() { final List<DBColumn> primaryKeyColumnList = new ArrayList<DBColumn>(); final Set<String> columnNameSet = getAllColumnNames(); for (String columnName : columnNameSet) { final D6ModelClassFieldInfo fieldInfo = getFieldInfo(columnName); final Field field = fieldInfo.field; final DBColumn dbColumn = field.getAnnotation(DBColumn.class); if (dbColumn.isPrimaryKey()) { primaryKeyColumnList.add(dbColumn); } } return primaryKeyColumnList; } }
public class class_name { final List<DBColumn> getPrimaryKeyColumnList() { final List<DBColumn> primaryKeyColumnList = new ArrayList<DBColumn>(); final Set<String> columnNameSet = getAllColumnNames(); for (String columnName : columnNameSet) { final D6ModelClassFieldInfo fieldInfo = getFieldInfo(columnName); final Field field = fieldInfo.field; final DBColumn dbColumn = field.getAnnotation(DBColumn.class); if (dbColumn.isPrimaryKey()) { primaryKeyColumnList.add(dbColumn); // depends on control dependency: [if], data = [none] } } return primaryKeyColumnList; } }
public class class_name { public void setSectionIconsVisible(final boolean VISIBLE) { if (null == sectionIconsVisible) { _sectionIconsVisible = VISIBLE; fireTileEvent(REDRAW_EVENT); } else { sectionIconsVisible.set(VISIBLE); } } }
public class class_name { public void setSectionIconsVisible(final boolean VISIBLE) { if (null == sectionIconsVisible) { _sectionIconsVisible = VISIBLE; // depends on control dependency: [if], data = [none] fireTileEvent(REDRAW_EVENT); // depends on control dependency: [if], data = [none] } else { sectionIconsVisible.set(VISIBLE); // depends on control dependency: [if], data = [none] } } }
public class class_name { private static String getUpdateSql() { if (updateSql == null) { updateSql = "UPDATE " + LOCK_TABLE + " SET " + EXPIRATION_TIME_COLUMN + EQ + "?, " + LOCK_TYPE_COLUMN + EQ + "?" + " WHERE " + ENTITY_TYPE_COLUMN + EQ + "?" + " AND " + ENTITY_KEY_COLUMN + EQ + "?" + " AND " + LOCK_OWNER_COLUMN + EQ + "?" + " AND " + EXPIRATION_TIME_COLUMN + EQ + "?" + " AND " + LOCK_TYPE_COLUMN + EQ + "?"; } return updateSql; } }
public class class_name { private static String getUpdateSql() { if (updateSql == null) { updateSql = "UPDATE " + LOCK_TABLE + " SET " + EXPIRATION_TIME_COLUMN + EQ + "?, " + LOCK_TYPE_COLUMN + EQ + "?" + " WHERE " + ENTITY_TYPE_COLUMN + EQ + "?" + " AND " + ENTITY_KEY_COLUMN + EQ + "?" + " AND " + LOCK_OWNER_COLUMN + EQ + "?" + " AND " + EXPIRATION_TIME_COLUMN + EQ + "?" + " AND " + LOCK_TYPE_COLUMN + EQ + "?"; // depends on control dependency: [if], data = [none] } return updateSql; } }
public class class_name { private void makeIncoming() { if (stays == null && move == null) { for (BitSet in : ins) { in.clear(); } stays = new BitSet(); move = new BitSet(); for (int i = 0; i < hosts.length; i++) { if (hosts[i] != null && hosts[i].isInstantiated()) { int newPos = hosts[i].getValue(); if (oldPos[i] != -1 && newPos != oldPos[i]) { //The VM has move ins[newPos].set(i); move.set(i); } else if (newPos == oldPos[i]) { stays.set(i); } } } } } }
public class class_name { private void makeIncoming() { if (stays == null && move == null) { for (BitSet in : ins) { in.clear(); // depends on control dependency: [for], data = [in] } stays = new BitSet(); // depends on control dependency: [if], data = [none] move = new BitSet(); // depends on control dependency: [if], data = [none] for (int i = 0; i < hosts.length; i++) { if (hosts[i] != null && hosts[i].isInstantiated()) { int newPos = hosts[i].getValue(); if (oldPos[i] != -1 && newPos != oldPos[i]) { //The VM has move ins[newPos].set(i); // depends on control dependency: [if], data = [none] move.set(i); // depends on control dependency: [if], data = [none] } else if (newPos == oldPos[i]) { stays.set(i); // depends on control dependency: [if], data = [none] } } } } } }
public class class_name { public static String substring(String input, int beginIndex, int endIndex) { if (beginIndex < 0) { beginIndex = 0; } if (endIndex < 0 || endIndex > input.length()) { endIndex = input.length(); } if (endIndex < beginIndex) { return ""; } return input.substring(beginIndex, endIndex); } }
public class class_name { public static String substring(String input, int beginIndex, int endIndex) { if (beginIndex < 0) { beginIndex = 0; // depends on control dependency: [if], data = [none] } if (endIndex < 0 || endIndex > input.length()) { endIndex = input.length(); // depends on control dependency: [if], data = [none] } if (endIndex < beginIndex) { return ""; // depends on control dependency: [if], data = [none] } return input.substring(beginIndex, endIndex); } }
public class class_name { void setButtonsLocation(int location) { if (currentButtonsLocation == location) { mainBreakButtons.setVisible(location == 0 && isMainToolBarHidden()); return; } currentButtonsLocation = location; switch (location) { case 0: requestBreakButtons.setVisible(false); responseBreakButtons.setVisible(false); setToolbarButtonsVisible(true); // If the user decided to disable the main toolbar, the break // buttons have to be force to be displayed in the break panel mainBreakButtons.setVisible(isMainToolBarHidden()); break; case 1: case 2: requestBreakButtons.setVisible(true); responseBreakButtons.setVisible(true); setToolbarButtonsVisible(location == 2); mainBreakButtons.setVisible(false); break; default: setToolbarButtonsVisible(true); } } }
public class class_name { void setButtonsLocation(int location) { if (currentButtonsLocation == location) { mainBreakButtons.setVisible(location == 0 && isMainToolBarHidden()); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } currentButtonsLocation = location; switch (location) { case 0: requestBreakButtons.setVisible(false); responseBreakButtons.setVisible(false); setToolbarButtonsVisible(true); // If the user decided to disable the main toolbar, the break // buttons have to be force to be displayed in the break panel mainBreakButtons.setVisible(isMainToolBarHidden()); break; case 1: case 2: requestBreakButtons.setVisible(true); responseBreakButtons.setVisible(true); setToolbarButtonsVisible(location == 2); mainBreakButtons.setVisible(false); break; default: setToolbarButtonsVisible(true); } } }
public class class_name { public void updateDeployedComponents() { try { // Get the SLEE Component Repo ComponentRepository componentRepository = sleeContainerDeployer.getSleeContainer().getComponentRepository(); // First we'll put the components in a temp Collection ConcurrentLinkedQueue<String> newDeployedComponents = new ConcurrentLinkedQueue<String>(); // Get the deployed Profile Specifications for (ComponentID componentID: componentRepository.getProfileSpecificationIDs()) { newDeployedComponents.add(componentID.toString()); } // Get the deployed Event Types for (ComponentID componentID: componentRepository.getEventComponentIDs()) { newDeployedComponents.add(componentID.toString()); } // Get the deployed Resource Adaptor Types for (ComponentID componentID: componentRepository.getResourceAdaptorTypeIDs()) { newDeployedComponents.add(componentID.toString()); } // Get the deployed Resource Adaptors for (ComponentID componentID: componentRepository.getResourceAdaptorIDs()) { newDeployedComponents.add(componentID.toString()); } // Get the deployed Service Building Blocks (SBBs) for (ComponentID componentID: componentRepository.getSbbIDs()) { newDeployedComponents.add(componentID.toString()); } // Get the deployed Services for (ComponentID componentID: componentRepository.getServiceIDs()) { newDeployedComponents.add(componentID.toString()); } // Get the deployed Libraries for (ComponentID componentID: componentRepository.getLibraryIDs()) { newDeployedComponents.add(componentID.toString()); } ResourceManagement resourceManagement = sleeContainerDeployer.getSleeContainer().getResourceManagement(); // Get the existing Resource Adaptor Entity links String[] entityNames = resourceManagement.getResourceAdaptorEntities(); for (String entityName : entityNames) { newDeployedComponents.addAll(Arrays.asList(resourceManagement.getLinkNames(entityName))); } // All good.. Make the temp the good one. deployedComponents = newDeployedComponents; } catch (Exception e) { logger.warn("Failure while updating deployed components.", e); } } }
public class class_name { public void updateDeployedComponents() { try { // Get the SLEE Component Repo ComponentRepository componentRepository = sleeContainerDeployer.getSleeContainer().getComponentRepository(); // First we'll put the components in a temp Collection ConcurrentLinkedQueue<String> newDeployedComponents = new ConcurrentLinkedQueue<String>(); // Get the deployed Profile Specifications for (ComponentID componentID: componentRepository.getProfileSpecificationIDs()) { newDeployedComponents.add(componentID.toString()); // depends on control dependency: [for], data = [componentID] } // Get the deployed Event Types for (ComponentID componentID: componentRepository.getEventComponentIDs()) { newDeployedComponents.add(componentID.toString()); // depends on control dependency: [for], data = [componentID] } // Get the deployed Resource Adaptor Types for (ComponentID componentID: componentRepository.getResourceAdaptorTypeIDs()) { newDeployedComponents.add(componentID.toString()); // depends on control dependency: [for], data = [componentID] } // Get the deployed Resource Adaptors for (ComponentID componentID: componentRepository.getResourceAdaptorIDs()) { newDeployedComponents.add(componentID.toString()); // depends on control dependency: [for], data = [componentID] } // Get the deployed Service Building Blocks (SBBs) for (ComponentID componentID: componentRepository.getSbbIDs()) { newDeployedComponents.add(componentID.toString()); // depends on control dependency: [for], data = [componentID] } // Get the deployed Services for (ComponentID componentID: componentRepository.getServiceIDs()) { newDeployedComponents.add(componentID.toString()); // depends on control dependency: [for], data = [componentID] } // Get the deployed Libraries for (ComponentID componentID: componentRepository.getLibraryIDs()) { newDeployedComponents.add(componentID.toString()); // depends on control dependency: [for], data = [componentID] } ResourceManagement resourceManagement = sleeContainerDeployer.getSleeContainer().getResourceManagement(); // Get the existing Resource Adaptor Entity links String[] entityNames = resourceManagement.getResourceAdaptorEntities(); for (String entityName : entityNames) { newDeployedComponents.addAll(Arrays.asList(resourceManagement.getLinkNames(entityName))); // depends on control dependency: [for], data = [entityName] } // All good.. Make the temp the good one. deployedComponents = newDeployedComponents; // depends on control dependency: [try], data = [none] } catch (Exception e) { logger.warn("Failure while updating deployed components.", e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static InternalServerError of(int errorCode, Throwable cause) { if (_localizedErrorMsg()) { return of(errorCode, cause, defaultMessage(INTERNAL_SERVER_ERROR)); } else { touchPayload().errorCode(errorCode).cause(cause); return _INSTANCE; } } }
public class class_name { public static InternalServerError of(int errorCode, Throwable cause) { if (_localizedErrorMsg()) { return of(errorCode, cause, defaultMessage(INTERNAL_SERVER_ERROR)); // depends on control dependency: [if], data = [none] } else { touchPayload().errorCode(errorCode).cause(cause); // depends on control dependency: [if], data = [none] return _INSTANCE; // depends on control dependency: [if], data = [none] } } }
public class class_name { protected BufferedImage create_BACKGROUND_Image(final int WIDTH, final String TITLE, final String UNIT_STRING, BufferedImage image) { if (WIDTH <= 0) { return null; } if (image == null) { image = UTIL.createImage(WIDTH, WIDTH, Transparency.TRANSLUCENT); } final Graphics2D G2 = image.createGraphics(); G2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); final int IMAGE_WIDTH = image.getWidth(); final int IMAGE_HEIGHT = image.getHeight(); switch (getFrameType()) { case SQUARE: BACKGROUND_FACTORY.createLinearBackground(WIDTH, WIDTH, getBackgroundColor(), getModel().getCustomBackground(), getModel().getTextureColor(), image); break; case ROUND: default: BACKGROUND_FACTORY.createRadialBackground(WIDTH, getBackgroundColor(), getModel().getCustomBackground(), getModel().getTextureColor(), image); break; } // Draw the custom layer if selected if (isCustomLayerVisible()) { G2.drawImage(UTIL.getScaledInstance(getCustomLayer(), IMAGE_WIDTH, IMAGE_HEIGHT, RenderingHints.VALUE_INTERPOLATION_BICUBIC), 0, 0, null); } final FontRenderContext RENDER_CONTEXT = new FontRenderContext(null, true, true); if (!TITLE.isEmpty()) { // Use custom label color if selected if (isLabelColorFromThemeEnabled()) { G2.setColor(getModel().getBackgroundColor().LABEL_COLOR); } else { G2.setColor(getModel().getLabelColor()); } // Use custom font if selected if (isTitleAndUnitFontEnabled()) { G2.setFont(new Font(getTitleAndUnitFont().getFamily(), 0, (int) (0.04672897196261682 * IMAGE_WIDTH))); } else { G2.setFont(new Font("Verdana", 0, (int) (0.04672897196261682 * IMAGE_WIDTH))); } final TextLayout TITLE_LAYOUT = new TextLayout(TITLE, G2.getFont(), RENDER_CONTEXT); final Rectangle2D TITLE_BOUNDARY = TITLE_LAYOUT.getBounds(); G2.drawString(TITLE, (float) ((IMAGE_WIDTH - TITLE_BOUNDARY.getWidth()) / 2.0), 0.3f * IMAGE_HEIGHT + TITLE_LAYOUT.getAscent() - TITLE_LAYOUT.getDescent()); } if (!UNIT_STRING.isEmpty()) { // Use custom label color if selected if (isLabelColorFromThemeEnabled()) { G2.setColor(getModel().getBackgroundColor().LABEL_COLOR); } else { G2.setColor(getModel().getLabelColor()); } // Use custom font if selected if (isTitleAndUnitFontEnabled()) { G2.setFont(new Font(getTitleAndUnitFont().getFamily(), 0, (int) (0.04672897196261682 * IMAGE_WIDTH))); } else { G2.setFont(new Font("Verdana", 0, (int) (0.04672897196261682 * IMAGE_WIDTH))); } final TextLayout UNIT_LAYOUT = new TextLayout(UNIT_STRING, G2.getFont(), RENDER_CONTEXT); final Rectangle2D UNIT_BOUNDARY = UNIT_LAYOUT.getBounds(); G2.drawString(UNIT_STRING, (float) ((IMAGE_WIDTH - UNIT_BOUNDARY.getWidth()) / 2.0), 0.38f * IMAGE_HEIGHT + UNIT_LAYOUT.getAscent() - UNIT_LAYOUT.getDescent()); } G2.dispose(); return image; } }
public class class_name { protected BufferedImage create_BACKGROUND_Image(final int WIDTH, final String TITLE, final String UNIT_STRING, BufferedImage image) { if (WIDTH <= 0) { return null; // depends on control dependency: [if], data = [none] } if (image == null) { image = UTIL.createImage(WIDTH, WIDTH, Transparency.TRANSLUCENT); // depends on control dependency: [if], data = [none] } final Graphics2D G2 = image.createGraphics(); G2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); final int IMAGE_WIDTH = image.getWidth(); final int IMAGE_HEIGHT = image.getHeight(); switch (getFrameType()) { case SQUARE: BACKGROUND_FACTORY.createLinearBackground(WIDTH, WIDTH, getBackgroundColor(), getModel().getCustomBackground(), getModel().getTextureColor(), image); break; case ROUND: default: BACKGROUND_FACTORY.createRadialBackground(WIDTH, getBackgroundColor(), getModel().getCustomBackground(), getModel().getTextureColor(), image); break; } // Draw the custom layer if selected if (isCustomLayerVisible()) { G2.drawImage(UTIL.getScaledInstance(getCustomLayer(), IMAGE_WIDTH, IMAGE_HEIGHT, RenderingHints.VALUE_INTERPOLATION_BICUBIC), 0, 0, null); } final FontRenderContext RENDER_CONTEXT = new FontRenderContext(null, true, true); if (!TITLE.isEmpty()) { // Use custom label color if selected if (isLabelColorFromThemeEnabled()) { G2.setColor(getModel().getBackgroundColor().LABEL_COLOR); } else { G2.setColor(getModel().getLabelColor()); } // Use custom font if selected if (isTitleAndUnitFontEnabled()) { G2.setFont(new Font(getTitleAndUnitFont().getFamily(), 0, (int) (0.04672897196261682 * IMAGE_WIDTH))); } else { G2.setFont(new Font("Verdana", 0, (int) (0.04672897196261682 * IMAGE_WIDTH))); } final TextLayout TITLE_LAYOUT = new TextLayout(TITLE, G2.getFont(), RENDER_CONTEXT); final Rectangle2D TITLE_BOUNDARY = TITLE_LAYOUT.getBounds(); G2.drawString(TITLE, (float) ((IMAGE_WIDTH - TITLE_BOUNDARY.getWidth()) / 2.0), 0.3f * IMAGE_HEIGHT + TITLE_LAYOUT.getAscent() - TITLE_LAYOUT.getDescent()); } if (!UNIT_STRING.isEmpty()) { // Use custom label color if selected if (isLabelColorFromThemeEnabled()) { G2.setColor(getModel().getBackgroundColor().LABEL_COLOR); } else { G2.setColor(getModel().getLabelColor()); } // Use custom font if selected if (isTitleAndUnitFontEnabled()) { G2.setFont(new Font(getTitleAndUnitFont().getFamily(), 0, (int) (0.04672897196261682 * IMAGE_WIDTH))); } else { G2.setFont(new Font("Verdana", 0, (int) (0.04672897196261682 * IMAGE_WIDTH))); } final TextLayout UNIT_LAYOUT = new TextLayout(UNIT_STRING, G2.getFont(), RENDER_CONTEXT); final Rectangle2D UNIT_BOUNDARY = UNIT_LAYOUT.getBounds(); G2.drawString(UNIT_STRING, (float) ((IMAGE_WIDTH - UNIT_BOUNDARY.getWidth()) / 2.0), 0.38f * IMAGE_HEIGHT + UNIT_LAYOUT.getAscent() - UNIT_LAYOUT.getDescent()); } G2.dispose(); return image; } }
public class class_name { protected void dontNotifyRequestListenersForRequestInternal(final SpiceRequest<?> request) { lockSendRequestsToService.lock(); try { final boolean requestNotPassedToServiceYet = removeListenersOfCachedRequestToLaunch(request); Ln.v("Removed from requests to launch list : " + requestNotPassedToServiceYet); // if the request was already passed to service, bind to // service and // unregister listeners. if (!requestNotPassedToServiceYet) { removeListenersOfPendingCachedRequest(request); Ln.v("Removed from pending requests list"); } } catch (final InterruptedException e) { Ln.e(e, "Interrupted while removing listeners."); } finally { lockSendRequestsToService.unlock(); } } }
public class class_name { protected void dontNotifyRequestListenersForRequestInternal(final SpiceRequest<?> request) { lockSendRequestsToService.lock(); try { final boolean requestNotPassedToServiceYet = removeListenersOfCachedRequestToLaunch(request); Ln.v("Removed from requests to launch list : " + requestNotPassedToServiceYet); // depends on control dependency: [try], data = [none] // if the request was already passed to service, bind to // service and // unregister listeners. if (!requestNotPassedToServiceYet) { removeListenersOfPendingCachedRequest(request); // depends on control dependency: [if], data = [none] Ln.v("Removed from pending requests list"); // depends on control dependency: [if], data = [none] } } catch (final InterruptedException e) { Ln.e(e, "Interrupted while removing listeners."); } finally { // depends on control dependency: [catch], data = [none] lockSendRequestsToService.unlock(); } } }
public class class_name { public Observable<ComapiResult<List<Conversation>>> getConversations(final boolean isPublic) { final String token = getToken(); if (sessionController.isCreatingSession()) { return getTaskQueue().queueGetConversationsExt(isPublic ? Scope.PUBLIC : Scope.PARTICIPANT); } else if (TextUtils.isEmpty(token)) { return Observable.error(getSessionStateErrorDescription()); } else { return doGetConversations(token, dataMgr.getSessionDAO().session().getProfileId(), isPublic ? Scope.PUBLIC : Scope.PARTICIPANT); } } }
public class class_name { public Observable<ComapiResult<List<Conversation>>> getConversations(final boolean isPublic) { final String token = getToken(); if (sessionController.isCreatingSession()) { return getTaskQueue().queueGetConversationsExt(isPublic ? Scope.PUBLIC : Scope.PARTICIPANT); // depends on control dependency: [if], data = [none] } else if (TextUtils.isEmpty(token)) { return Observable.error(getSessionStateErrorDescription()); // depends on control dependency: [if], data = [none] } else { return doGetConversations(token, dataMgr.getSessionDAO().session().getProfileId(), isPublic ? Scope.PUBLIC : Scope.PARTICIPANT); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static String underscoresToCamelCase(String input, boolean capitializeNextLetter) { StringBuilder result = new StringBuilder(); for (int i = 0; i < input.length(); i++) { char ch = input.charAt(i); if ('a' <= ch && ch <= 'z') { if (capitializeNextLetter) { result.append((char) (ch + ('A' - 'a'))); } else { result.append(ch); } capitializeNextLetter = false; } else if ('A' <= ch && ch <= 'Z') { if (i == 0 && !capitializeNextLetter) { // Force first letter to lower-case unless explicitly told to // capitalize it. result.append((char) (ch + ('a' - 'A'))); } else { // Capital letters after the first are left as-is. result.append(ch); } capitializeNextLetter = false; } else if ('0' <= ch && ch <= '9') { result.append(ch); capitializeNextLetter = true; } else { capitializeNextLetter = true; } } return result.toString(); } }
public class class_name { public static String underscoresToCamelCase(String input, boolean capitializeNextLetter) { StringBuilder result = new StringBuilder(); for (int i = 0; i < input.length(); i++) { char ch = input.charAt(i); if ('a' <= ch && ch <= 'z') { if (capitializeNextLetter) { result.append((char) (ch + ('A' - 'a'))); // depends on control dependency: [if], data = [none] } else { result.append(ch); // depends on control dependency: [if], data = [none] } capitializeNextLetter = false; // depends on control dependency: [if], data = [none] } else if ('A' <= ch && ch <= 'Z') { if (i == 0 && !capitializeNextLetter) { // Force first letter to lower-case unless explicitly told to // capitalize it. result.append((char) (ch + ('a' - 'A'))); // depends on control dependency: [if], data = [none] } else { // Capital letters after the first are left as-is. result.append(ch); // depends on control dependency: [if], data = [none] } capitializeNextLetter = false; // depends on control dependency: [if], data = [none] } else if ('0' <= ch && ch <= '9') { result.append(ch); // depends on control dependency: [if], data = [none] capitializeNextLetter = true; // depends on control dependency: [if], data = [none] } else { capitializeNextLetter = true; // depends on control dependency: [if], data = [none] } } return result.toString(); } }
public class class_name { @Override public void handleMessageToClient(WebSocketSession session, Message<?> message) { if (!(message instanceof WampMessage)) { logger.error("Expected WampMessage. Ignoring " + message + "."); return; } boolean closeWebSocketSession = false; try { String json = ((WampMessage) message).toJson(this.jsonFactory); session.sendMessage(new TextMessage(json)); } catch (SessionLimitExceededException ex) { // Bad session, just get out throw ex; } catch (Throwable ex) { // Could be part of normal workflow (e.g. browser tab closed) logger.debug("Failed to send WebSocket message to client in session " + session.getId() + ".", ex); closeWebSocketSession = true; } finally { if (closeWebSocketSession) { try { session.close(CloseStatus.PROTOCOL_ERROR); } catch (IOException ex) { // Ignore } } } } }
public class class_name { @Override public void handleMessageToClient(WebSocketSession session, Message<?> message) { if (!(message instanceof WampMessage)) { logger.error("Expected WampMessage. Ignoring " + message + "."); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } boolean closeWebSocketSession = false; try { String json = ((WampMessage) message).toJson(this.jsonFactory); session.sendMessage(new TextMessage(json)); // depends on control dependency: [try], data = [none] } catch (SessionLimitExceededException ex) { // Bad session, just get out throw ex; } // depends on control dependency: [catch], data = [none] catch (Throwable ex) { // Could be part of normal workflow (e.g. browser tab closed) logger.debug("Failed to send WebSocket message to client in session " + session.getId() + ".", ex); closeWebSocketSession = true; } // depends on control dependency: [catch], data = [none] finally { if (closeWebSocketSession) { try { session.close(CloseStatus.PROTOCOL_ERROR); // depends on control dependency: [try], data = [none] } catch (IOException ex) { // Ignore } // depends on control dependency: [catch], data = [none] } } } }
public class class_name { public EClass getIfcTubeBundleType() { if (ifcTubeBundleTypeEClass == null) { ifcTubeBundleTypeEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(624); } return ifcTubeBundleTypeEClass; } }
public class class_name { public EClass getIfcTubeBundleType() { if (ifcTubeBundleTypeEClass == null) { ifcTubeBundleTypeEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(624); // depends on control dependency: [if], data = [none] } return ifcTubeBundleTypeEClass; } }
public class class_name { public Cursor swapCursor(Cursor newCursor) { if (newCursor == mCursor) { return null; } Cursor oldCursor = mCursor; if (oldCursor != null) { if (mChangeObserver != null) oldCursor.unregisterContentObserver(mChangeObserver); if (mDataSetObserver != null) oldCursor.unregisterDataSetObserver(mDataSetObserver); } mCursor = newCursor; if (newCursor != null) { if (mChangeObserver != null) newCursor.registerContentObserver(mChangeObserver); if (mDataSetObserver != null) newCursor.registerDataSetObserver(mDataSetObserver); mRowIDColumn = newCursor.getColumnIndexOrThrow("_id"); mDataValid = true; // notify the observers about the new cursor notifyDataSetChanged(); } else { mRowIDColumn = -1; mDataValid = false; // notify the observers about the lack of a data set notifyDataSetInvalidated(); } return oldCursor; } }
public class class_name { public Cursor swapCursor(Cursor newCursor) { if (newCursor == mCursor) { return null; // depends on control dependency: [if], data = [none] } Cursor oldCursor = mCursor; if (oldCursor != null) { if (mChangeObserver != null) oldCursor.unregisterContentObserver(mChangeObserver); if (mDataSetObserver != null) oldCursor.unregisterDataSetObserver(mDataSetObserver); } mCursor = newCursor; if (newCursor != null) { if (mChangeObserver != null) newCursor.registerContentObserver(mChangeObserver); if (mDataSetObserver != null) newCursor.registerDataSetObserver(mDataSetObserver); mRowIDColumn = newCursor.getColumnIndexOrThrow("_id"); // depends on control dependency: [if], data = [none] mDataValid = true; // depends on control dependency: [if], data = [none] // notify the observers about the new cursor notifyDataSetChanged(); // depends on control dependency: [if], data = [none] } else { mRowIDColumn = -1; // depends on control dependency: [if], data = [none] mDataValid = false; // depends on control dependency: [if], data = [none] // notify the observers about the lack of a data set notifyDataSetInvalidated(); // depends on control dependency: [if], data = [none] } return oldCursor; } }
public class class_name { public DateMidnight plusYears(int years) { if (years == 0) { return this; } long instant = getChronology().years().add(getMillis(), years); return withMillis(instant); } }
public class class_name { public DateMidnight plusYears(int years) { if (years == 0) { return this; // depends on control dependency: [if], data = [none] } long instant = getChronology().years().add(getMillis(), years); return withMillis(instant); } }
public class class_name { public static String mapToString(Map<String, ?> map) { StringBuilder sb = new StringBuilder(); sb.append("{\n"); for (String key : map.keySet()) { if (map.get(key) != null) { sb.append(key + ": " + map.get(key) + "\n "); } else { continue; } } sb.append("}"); return sb.toString(); } }
public class class_name { public static String mapToString(Map<String, ?> map) { StringBuilder sb = new StringBuilder(); sb.append("{\n"); for (String key : map.keySet()) { if (map.get(key) != null) { sb.append(key + ": " + map.get(key) + "\n "); // depends on control dependency: [if], data = [none] } else { continue; } } sb.append("}"); return sb.toString(); } }
public class class_name { private boolean estimateClose() { // estimate 2D motion if (!planeMotion.process(planeSamples.toList())) return false; // save solutions closeMotionKeyToCurr = planeMotion.getModelParameters(); closeInlierCount = planeMotion.getMatchSet().size(); // mark inliers as used for (int i = 0; i < closeInlierCount; i++) { int index = planeMotion.getInputIndex(i); VoTrack p = tracksOnPlane.get(index).getCookie(); p.lastInlier = tick; } return true; } }
public class class_name { private boolean estimateClose() { // estimate 2D motion if (!planeMotion.process(planeSamples.toList())) return false; // save solutions closeMotionKeyToCurr = planeMotion.getModelParameters(); closeInlierCount = planeMotion.getMatchSet().size(); // mark inliers as used for (int i = 0; i < closeInlierCount; i++) { int index = planeMotion.getInputIndex(i); VoTrack p = tracksOnPlane.get(index).getCookie(); p.lastInlier = tick; // depends on control dependency: [for], data = [none] } return true; } }
public class class_name { @Override public final void handleRequest(final Request request) { if (!beforeHandleRequest(request)) { return; } setChangedInLastRequest(false); if (isDisabled() || isReadOnly()) { // Protect against client-side tampering of disabled/read-only fields. return; } if (isPresent(request)) { // Only process on a POST if (!"POST".equals(request.getMethod())) { LOG.warn("Input component on a request that is not a POST. Will be ignored."); return; } boolean changed = doHandleRequest(request); if (changed) { setChangedInLastRequest(true); doHandleChanged(); } } } }
public class class_name { @Override public final void handleRequest(final Request request) { if (!beforeHandleRequest(request)) { return; // depends on control dependency: [if], data = [none] } setChangedInLastRequest(false); if (isDisabled() || isReadOnly()) { // Protect against client-side tampering of disabled/read-only fields. return; // depends on control dependency: [if], data = [none] } if (isPresent(request)) { // Only process on a POST if (!"POST".equals(request.getMethod())) { LOG.warn("Input component on a request that is not a POST. Will be ignored."); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } boolean changed = doHandleRequest(request); if (changed) { setChangedInLastRequest(true); // depends on control dependency: [if], data = [none] doHandleChanged(); // depends on control dependency: [if], data = [none] } } } }
public class class_name { private static MyNode compactForm(MyNode n) { if (n.node.getNodeType() == Node.TEXT_NODE) { n.out = n.node.getNodeValue().trim(); } else { n.out = n.node.getNodeName(); if (n.out.startsWith("m:")) { n.out = n.out.substring(2); } if ("annotation-xml".equals(n.out)) { n.out = ""; } if ("pquery".equals(n.out) || "cquery".equals(n.out)) { n.out = ""; } if ("mws:qvar".equals(n.out)) { final String qname = n.node.getAttributes().getNamedItem("name").toString(); if (n.qVar == null) { n.out = "\\qvar{x_0}"; n.qVar = new HashMap<>(); n.qVar.put(qname, 0); } else { Integer qInt = n.qVar.get(qname); if (qInt == null) { n.out = "\\qvar{x_" + n.qVar.size() + "}"; n.qVar.put(qname, n.qVar.size()); } else { n.out = "\\qqvar{x_" + qInt + "}"; } } } if (n.node.hasChildNodes()) { String sChild = ""; for (Node childNode = n.node.getFirstChild(); childNode != null; childNode = childNode.getNextSibling()) { MyNode ret = compactForm(new MyNode(childNode, n.qVar)); String cn = ret.out; n.qVar = ret.qVar; if (!cn.isEmpty()) { sChild += cn + ";"; } } if (sChild.endsWith(";")) { sChild = sChild.substring(0, sChild.length() - 1).trim(); } if (!sChild.isEmpty() && sChild.codePointAt(0) != 8290 && sChild.codePointAt(0) != 8289) { if ("m:annotation-xml".equals(n.node.getNodeName())) { n.out += sChild; } else { n.out += '[' + sChild + ']'; } } } } if ("mo".equals(n.out)) { //Remove empty mo elements n.out = ""; } return n; } }
public class class_name { private static MyNode compactForm(MyNode n) { if (n.node.getNodeType() == Node.TEXT_NODE) { n.out = n.node.getNodeValue().trim(); } else { n.out = n.node.getNodeName(); if (n.out.startsWith("m:")) { n.out = n.out.substring(2); // depends on control dependency: [if], data = [none] } if ("annotation-xml".equals(n.out)) { n.out = ""; // depends on control dependency: [if], data = [none] } if ("pquery".equals(n.out) || "cquery".equals(n.out)) { n.out = ""; // depends on control dependency: [if], data = [none] } if ("mws:qvar".equals(n.out)) { final String qname = n.node.getAttributes().getNamedItem("name").toString(); if (n.qVar == null) { n.out = "\\qvar{x_0}"; // depends on control dependency: [if], data = [none] n.qVar = new HashMap<>(); n.qVar.put(qname, 0); } else { // depends on control dependency: [if], data = [none] Integer qInt = n.qVar.get(qname); if (qInt == null) { n.out = "\\qvar{x_" + n.qVar.size() + "}"; // depends on control dependency: [if], data = [none] n.qVar.put(qname, n.qVar.size()); } else { // depends on control dependency: [if], data = [none] n.out = "\\qqvar{x_" + qInt + "}"; } } } if (n.node.hasChildNodes()) { String sChild = ""; for (Node childNode = n.node.getFirstChild(); childNode != null; childNode = childNode.getNextSibling()) { MyNode ret = compactForm(new MyNode(childNode, n.qVar)); String cn = ret.out; n.qVar = ret.qVar; // depends on control dependency: [for], data = [none] if (!cn.isEmpty()) { sChild += cn + ";"; // depends on control dependency: [if], data = [none] } } if (sChild.endsWith(";")) { sChild = sChild.substring(0, sChild.length() - 1).trim(); // depends on control dependency: [if], data = [none] } if (!sChild.isEmpty() && sChild.codePointAt(0) != 8290 && sChild.codePointAt(0) != 8289) { if ("m:annotation-xml".equals(n.node.getNodeName())) { n.out += sChild; // depends on control dependency: [if], data = [none] } else { n.out += '[' + sChild + ']'; // depends on control dependency: [if], data = [none] } } } } if ("mo".equals(n.out)) { //Remove empty mo elements n.out = ""; // depends on control dependency: [if], data = [none] } return n; // depends on control dependency: [if], data = [none] } }
public class class_name { protected AbcNode getParseTree(String abcString) { long startTime = System.currentTimeMillis(); AbcGrammar grammar = AbcGrammar.getInstance(); // AbcGrammar parser = Parboiled.createParser(AbcGrammar.class); ParsingResult<?> result = RecoveringParseRunner.run(grammar.AbcFile(), abcString); if (DEBUG) { System.out.println("Parse : "+(System.currentTimeMillis() - startTime) + "ms"); } if (result.hasErrors()) { System.err.println("Parse errors: " + result.parseErrors.size()); /*Iterator it = result.parseErrors.iterator(); while (it.hasNext()) { ParseError pe = (ParseError) it.next(); System.err.println("- " + pe.getErrorMessage() + "("+pe.getStartIndex()+"->"+pe.getEndIndex()+")"); }*/ } AbcNode abcRoot = new AbcNode(result.parseTreeRoot, result.inputBuffer, result.parseErrors, new AbcInputBuffer(abcString.toCharArray())); if (result.hasErrors() || DEBUG) debugTree(abcRoot); return abcRoot; } }
public class class_name { protected AbcNode getParseTree(String abcString) { long startTime = System.currentTimeMillis(); AbcGrammar grammar = AbcGrammar.getInstance(); // AbcGrammar parser = Parboiled.createParser(AbcGrammar.class); ParsingResult<?> result = RecoveringParseRunner.run(grammar.AbcFile(), abcString); if (DEBUG) { System.out.println("Parse : "+(System.currentTimeMillis() - startTime) + "ms"); // depends on control dependency: [if], data = [none] } if (result.hasErrors()) { System.err.println("Parse errors: " + result.parseErrors.size()); // depends on control dependency: [if], data = [none] /*Iterator it = result.parseErrors.iterator(); while (it.hasNext()) { ParseError pe = (ParseError) it.next(); System.err.println("- " + pe.getErrorMessage() + "("+pe.getStartIndex()+"->"+pe.getEndIndex()+")"); }*/ } AbcNode abcRoot = new AbcNode(result.parseTreeRoot, result.inputBuffer, result.parseErrors, new AbcInputBuffer(abcString.toCharArray())); if (result.hasErrors() || DEBUG) debugTree(abcRoot); return abcRoot; } }
public class class_name { public static Pattern createPattern(final String pattern, final int flags) { if (pattern == null) { LOGGER.debug("Pattern cannot be null"); return MATCH_NOTHING_PATTERN; } try { return Pattern.compile(pattern, flags); } catch (final PatternSyntaxException exception) { LOGGER.debug("Pattern [{}] is not a valid regex.", pattern); return MATCH_NOTHING_PATTERN; } } }
public class class_name { public static Pattern createPattern(final String pattern, final int flags) { if (pattern == null) { LOGGER.debug("Pattern cannot be null"); // depends on control dependency: [if], data = [none] return MATCH_NOTHING_PATTERN; // depends on control dependency: [if], data = [none] } try { return Pattern.compile(pattern, flags); // depends on control dependency: [try], data = [none] } catch (final PatternSyntaxException exception) { LOGGER.debug("Pattern [{}] is not a valid regex.", pattern); return MATCH_NOTHING_PATTERN; } // depends on control dependency: [catch], data = [none] } }
public class class_name { @Override public ServerEvaluationCall addVariableAs(String name, Object value) { if (value == null) return this; Class<?> as = value.getClass(); AbstractWriteHandle writeHandle = null; if (AbstractWriteHandle.class.isAssignableFrom(as)) { writeHandle = (AbstractWriteHandle) value; } else { ContentHandle<?> contentHandle = handleRegistry.makeHandle(as); Utilities.setHandleContent(contentHandle, value); writeHandle = contentHandle; } return addVariable(name, writeHandle); } }
public class class_name { @Override public ServerEvaluationCall addVariableAs(String name, Object value) { if (value == null) return this; Class<?> as = value.getClass(); AbstractWriteHandle writeHandle = null; if (AbstractWriteHandle.class.isAssignableFrom(as)) { writeHandle = (AbstractWriteHandle) value; // depends on control dependency: [if], data = [none] } else { ContentHandle<?> contentHandle = handleRegistry.makeHandle(as); Utilities.setHandleContent(contentHandle, value); // depends on control dependency: [if], data = [none] writeHandle = contentHandle; // depends on control dependency: [if], data = [none] } return addVariable(name, writeHandle); } }
public class class_name { public HpackHeaderField getEntry(int index) { if (index <= 0 || index > length()) { throw new IndexOutOfBoundsException(); } int i = head - index; if (i < 0) { return hpackHeaderFields[i + hpackHeaderFields.length]; } else { return hpackHeaderFields[i]; } } }
public class class_name { public HpackHeaderField getEntry(int index) { if (index <= 0 || index > length()) { throw new IndexOutOfBoundsException(); } int i = head - index; if (i < 0) { return hpackHeaderFields[i + hpackHeaderFields.length]; // depends on control dependency: [if], data = [none] } else { return hpackHeaderFields[i]; // depends on control dependency: [if], data = [none] } } }
public class class_name { public Optional<FileStatus> getFileStatus(final FileSystem fs, final Path path) throws IOException { try { return this.fileStatusCache.get(fs.makeQualified(path), new Callable<Optional<FileStatus>>() { @Override public Optional<FileStatus> call() throws Exception { try { return Optional.of(fs.getFileStatus(path)); } catch (FileNotFoundException fnfe) { return Optional.absent(); } } }); } catch (ExecutionException ee) { throw new IOException(ee.getCause()); } } }
public class class_name { public Optional<FileStatus> getFileStatus(final FileSystem fs, final Path path) throws IOException { try { return this.fileStatusCache.get(fs.makeQualified(path), new Callable<Optional<FileStatus>>() { @Override public Optional<FileStatus> call() throws Exception { try { return Optional.of(fs.getFileStatus(path)); // depends on control dependency: [try], data = [none] } catch (FileNotFoundException fnfe) { return Optional.absent(); } // depends on control dependency: [catch], data = [none] } }); } catch (ExecutionException ee) { throw new IOException(ee.getCause()); } } }
public class class_name { public void moveToBack(Object parent, String name) { Element parentElement = getGroup(parent); if (parentElement == null) { throw new IllegalArgumentException("moveToBack failed: could not find parent group."); } Element element = getElement(parent, name); if (element == null) { throw new IllegalArgumentException("moveToBack failed: could not find element within group."); } if (parentElement.getFirstChildElement() != element) { parentElement.insertFirst(element); } } }
public class class_name { public void moveToBack(Object parent, String name) { Element parentElement = getGroup(parent); if (parentElement == null) { throw new IllegalArgumentException("moveToBack failed: could not find parent group."); } Element element = getElement(parent, name); if (element == null) { throw new IllegalArgumentException("moveToBack failed: could not find element within group."); } if (parentElement.getFirstChildElement() != element) { parentElement.insertFirst(element); // depends on control dependency: [if], data = [element)] } } }
public class class_name { public ListCustomVerificationEmailTemplatesResult withCustomVerificationEmailTemplates(CustomVerificationEmailTemplate... customVerificationEmailTemplates) { if (this.customVerificationEmailTemplates == null) { setCustomVerificationEmailTemplates(new com.amazonaws.internal.SdkInternalList<CustomVerificationEmailTemplate>( customVerificationEmailTemplates.length)); } for (CustomVerificationEmailTemplate ele : customVerificationEmailTemplates) { this.customVerificationEmailTemplates.add(ele); } return this; } }
public class class_name { public ListCustomVerificationEmailTemplatesResult withCustomVerificationEmailTemplates(CustomVerificationEmailTemplate... customVerificationEmailTemplates) { if (this.customVerificationEmailTemplates == null) { setCustomVerificationEmailTemplates(new com.amazonaws.internal.SdkInternalList<CustomVerificationEmailTemplate>( customVerificationEmailTemplates.length)); // depends on control dependency: [if], data = [none] } for (CustomVerificationEmailTemplate ele : customVerificationEmailTemplates) { this.customVerificationEmailTemplates.add(ele); // depends on control dependency: [for], data = [ele] } return this; } }
public class class_name { public final void dirCopy(File in, File out, boolean skipHiddenFiles) throws IOException { assert in != null; assert out != null; getLog().debug(in.toString() + "->" + out.toString()); //$NON-NLS-1$ getLog().debug("Ignore hidden files: " + skipHiddenFiles); //$NON-NLS-1$ out.mkdirs(); final LinkedList<File> candidates = new LinkedList<>(); candidates.add(in); File[] children; while (!candidates.isEmpty()) { final File f = candidates.removeFirst(); getLog().debug("Scanning: " + f); //$NON-NLS-1$ if (f.isDirectory()) { children = f.listFiles(); if (children != null && children.length > 0) { // Non empty directory for (final File c : children) { if (!skipHiddenFiles || !c.isHidden()) { getLog().debug("Discovering: " + c); //$NON-NLS-1$ candidates.add(c); } } } } else { // not a directory final File targetFile = toOutput(in, f, out); targetFile.getParentFile().mkdirs(); fileCopy(f, targetFile); } } } }
public class class_name { public final void dirCopy(File in, File out, boolean skipHiddenFiles) throws IOException { assert in != null; assert out != null; getLog().debug(in.toString() + "->" + out.toString()); //$NON-NLS-1$ getLog().debug("Ignore hidden files: " + skipHiddenFiles); //$NON-NLS-1$ out.mkdirs(); final LinkedList<File> candidates = new LinkedList<>(); candidates.add(in); File[] children; while (!candidates.isEmpty()) { final File f = candidates.removeFirst(); getLog().debug("Scanning: " + f); //$NON-NLS-1$ if (f.isDirectory()) { children = f.listFiles(); if (children != null && children.length > 0) { // Non empty directory for (final File c : children) { if (!skipHiddenFiles || !c.isHidden()) { getLog().debug("Discovering: " + c); //$NON-NLS-1$ // depends on control dependency: [if], data = [none] candidates.add(c); // depends on control dependency: [if], data = [none] } } } } else { // not a directory final File targetFile = toOutput(in, f, out); targetFile.getParentFile().mkdirs(); fileCopy(f, targetFile); } } } }
public class class_name { private void addLibraryInternal(final JobID jobID, final Path name, final long size, final DataInput in) throws IOException { if (size > (long) Integer.MAX_VALUE) { throw new IOException("Submitted jar file " + name + " is too large"); } // Map the entire jar file to memory final byte[] buf = new byte[(int) size]; in.readFully(buf); // Reset and calculate message digest from jar file this.md.reset(); this.md.update(buf); // Construct internal jar name from digest final String cacheName = StringUtils.byteToHexString(md.digest()) + ".jar"; final Path storePath = new Path(this.libraryCachePath + "/" + cacheName); synchronized (this.fs) { // Check if file already exists in our library cache, if not write it to the cache directory if (!this.fs.exists(storePath)) { final FSDataOutputStream fos = this.fs.create(storePath, false); fos.write(buf, 0, buf.length); fos.close(); } } // Create mapping for client path and cache name final LibraryTranslationKey key = new LibraryTranslationKey(jobID, name); this.clientPathToCacheName.putIfAbsent(key, cacheName); } }
public class class_name { private void addLibraryInternal(final JobID jobID, final Path name, final long size, final DataInput in) throws IOException { if (size > (long) Integer.MAX_VALUE) { throw new IOException("Submitted jar file " + name + " is too large"); } // Map the entire jar file to memory final byte[] buf = new byte[(int) size]; in.readFully(buf); // Reset and calculate message digest from jar file this.md.reset(); this.md.update(buf); // Construct internal jar name from digest final String cacheName = StringUtils.byteToHexString(md.digest()) + ".jar"; final Path storePath = new Path(this.libraryCachePath + "/" + cacheName); synchronized (this.fs) { // Check if file already exists in our library cache, if not write it to the cache directory if (!this.fs.exists(storePath)) { final FSDataOutputStream fos = this.fs.create(storePath, false); fos.write(buf, 0, buf.length); // depends on control dependency: [if], data = [none] fos.close(); // depends on control dependency: [if], data = [none] } } // Create mapping for client path and cache name final LibraryTranslationKey key = new LibraryTranslationKey(jobID, name); this.clientPathToCacheName.putIfAbsent(key, cacheName); } }
public class class_name { public void clear() { for (int i = 0; i < _values.length; i++) { _keys[i] = null; _values[i] = 0; } _size = 0; } }
public class class_name { public void clear() { for (int i = 0; i < _values.length; i++) { _keys[i] = null; // depends on control dependency: [for], data = [i] _values[i] = 0; // depends on control dependency: [for], data = [i] } _size = 0; } }
public class class_name { List<SPFPersona> getAvailablePersonas() { SQLiteDatabase db = getReadableDatabase(); String table = Contract.TABLE_PERSONAS; String[] columns = { Contract.COLUMN_PERSONA }; String selection = null; String[] selectionArgs = null; String groupBy = null; String having = null; String orderBy = null; Cursor c = db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy); List<SPFPersona> availablePersonas = new ArrayList<SPFPersona>(); while (c.moveToNext()) { String p = c.getString(c.getColumnIndex(Contract.COLUMN_PERSONA)); SPFPersona pers = new SPFPersona(p); availablePersonas.add(pers); } c.close(); return availablePersonas; } }
public class class_name { List<SPFPersona> getAvailablePersonas() { SQLiteDatabase db = getReadableDatabase(); String table = Contract.TABLE_PERSONAS; String[] columns = { Contract.COLUMN_PERSONA }; String selection = null; String[] selectionArgs = null; String groupBy = null; String having = null; String orderBy = null; Cursor c = db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy); List<SPFPersona> availablePersonas = new ArrayList<SPFPersona>(); while (c.moveToNext()) { String p = c.getString(c.getColumnIndex(Contract.COLUMN_PERSONA)); SPFPersona pers = new SPFPersona(p); availablePersonas.add(pers); // depends on control dependency: [while], data = [none] } c.close(); return availablePersonas; } }
public class class_name { public void register(final Class<? extends OCompression> compression) { try { final OCompression tempInstance = compression.newInstance(); final String name = tempInstance.name(); if (compressions.containsKey(name)) throw new IllegalArgumentException("Compression with name '" + name + "' was already registered"); if (compressionClasses.containsKey(tempInstance.name())) throw new IllegalArgumentException("Compression with name '" + name + "' was already registered"); compressionClasses.put(name, compression); } catch (Exception e) { OLogManager.instance().error(this, "Cannot register storage compression algorithm '%s'", e, compression); } } }
public class class_name { public void register(final Class<? extends OCompression> compression) { try { final OCompression tempInstance = compression.newInstance(); final String name = tempInstance.name(); if (compressions.containsKey(name)) throw new IllegalArgumentException("Compression with name '" + name + "' was already registered"); if (compressionClasses.containsKey(tempInstance.name())) throw new IllegalArgumentException("Compression with name '" + name + "' was already registered"); compressionClasses.put(name, compression); // depends on control dependency: [try], data = [none] } catch (Exception e) { OLogManager.instance().error(this, "Cannot register storage compression algorithm '%s'", e, compression); } // depends on control dependency: [catch], data = [none] } }
public class class_name { String getLogicalScope(CharacterFilter filter, char delimiter, int reporterIndex) { if (logicalScopeStrings.length == 0 || (reporterIndex < 0 || reporterIndex >= logicalScopeStrings.length)) { return createLogicalScope(filter, delimiter); } else { if (logicalScopeStrings[reporterIndex] == null) { logicalScopeStrings[reporterIndex] = createLogicalScope(filter, delimiter); } return logicalScopeStrings[reporterIndex]; } } }
public class class_name { String getLogicalScope(CharacterFilter filter, char delimiter, int reporterIndex) { if (logicalScopeStrings.length == 0 || (reporterIndex < 0 || reporterIndex >= logicalScopeStrings.length)) { return createLogicalScope(filter, delimiter); // depends on control dependency: [if], data = [none] } else { if (logicalScopeStrings[reporterIndex] == null) { logicalScopeStrings[reporterIndex] = createLogicalScope(filter, delimiter); // depends on control dependency: [if], data = [none] } return logicalScopeStrings[reporterIndex]; // depends on control dependency: [if], data = [none] } } }
public class class_name { @SneakyThrows public static <T, R> Function<T, R> doIf(final Predicate<Object> condition, final Supplier<R> trueFunction, final Supplier<R> falseFunction) { return t -> { try { if (condition.test(t)) { return trueFunction.get(); } return falseFunction.get(); } catch (final Throwable e) { LOGGER.warn(e.getMessage(), e); return falseFunction.get(); } }; } }
public class class_name { @SneakyThrows public static <T, R> Function<T, R> doIf(final Predicate<Object> condition, final Supplier<R> trueFunction, final Supplier<R> falseFunction) { return t -> { try { if (condition.test(t)) { return trueFunction.get(); // depends on control dependency: [if], data = [none] } return falseFunction.get(); // depends on control dependency: [try], data = [none] } catch (final Throwable e) { LOGGER.warn(e.getMessage(), e); return falseFunction.get(); } // depends on control dependency: [catch], data = [none] }; } }
public class class_name { public static double logpdf(double val, double shape, double location, double scale) { if(val < location) { return Double.NEGATIVE_INFINITY; } val = (val - location) / scale; final double lval = FastMath.log(val); if(lval == Double.POSITIVE_INFINITY) { return Double.NEGATIVE_INFINITY; } return FastMath.log(shape / scale) + (shape - 1.) * lval // - 2. * FastMath.log1p(FastMath.exp(lval * shape)); } }
public class class_name { public static double logpdf(double val, double shape, double location, double scale) { if(val < location) { return Double.NEGATIVE_INFINITY; // depends on control dependency: [if], data = [none] } val = (val - location) / scale; final double lval = FastMath.log(val); if(lval == Double.POSITIVE_INFINITY) { return Double.NEGATIVE_INFINITY; // depends on control dependency: [if], data = [none] } return FastMath.log(shape / scale) + (shape - 1.) * lval // - 2. * FastMath.log1p(FastMath.exp(lval * shape)); } }
public class class_name { @SuppressWarnings({ "unchecked", "rawtypes" }) private EventDispatcher getEventDispatcher(Class<?> eventType, boolean createIfNotExists) { EventDispatcher<?> dispatcher = this.eventType2dispatcherMap.get(eventType); if (dispatcher == null) { Class<?> parentType = eventType.getSuperclass(); if (createIfNotExists) { EventDispatcher<?> parent; if (parentType == null) { assert (eventType == Object.class); parent = null; } else { parent = getEventDispatcher(parentType, true); } dispatcher = new EventDispatcher(parent, this.queueFactory); this.eventType2dispatcherMap.put(eventType, dispatcher); } else { return getEventDispatcher(parentType, false); } } return dispatcher; } }
public class class_name { @SuppressWarnings({ "unchecked", "rawtypes" }) private EventDispatcher getEventDispatcher(Class<?> eventType, boolean createIfNotExists) { EventDispatcher<?> dispatcher = this.eventType2dispatcherMap.get(eventType); if (dispatcher == null) { Class<?> parentType = eventType.getSuperclass(); if (createIfNotExists) { EventDispatcher<?> parent; if (parentType == null) { assert (eventType == Object.class); // depends on control dependency: [if], data = [none] parent = null; // depends on control dependency: [if], data = [none] } else { parent = getEventDispatcher(parentType, true); // depends on control dependency: [if], data = [(parentType] } dispatcher = new EventDispatcher(parent, this.queueFactory); // depends on control dependency: [if], data = [none] this.eventType2dispatcherMap.put(eventType, dispatcher); // depends on control dependency: [if], data = [none] } else { return getEventDispatcher(parentType, false); // depends on control dependency: [if], data = [none] } } return dispatcher; } }
public class class_name { public static void writeToFile(InputStream uploadedInputStream, String uploadedFileLocation) throws IOException { File file = new File(uploadedFileLocation); file.getParentFile().mkdirs(); int read = 0; byte[] bytes = new byte[1024]; try (OutputStream out = new FileOutputStream(file)) { while ((read = uploadedInputStream.read(bytes)) != -1) { out.write(bytes, 0, read); } out.flush(); } } }
public class class_name { public static void writeToFile(InputStream uploadedInputStream, String uploadedFileLocation) throws IOException { File file = new File(uploadedFileLocation); file.getParentFile().mkdirs(); int read = 0; byte[] bytes = new byte[1024]; try (OutputStream out = new FileOutputStream(file)) { while ((read = uploadedInputStream.read(bytes)) != -1) { out.write(bytes, 0, read); // depends on control dependency: [while], data = [none] } out.flush(); } } }
public class class_name { public static JsonObject matchCommand(JsonObject commandsJson, String commandName, String storageService) { for (String key : commandsJson.keySet()) { if (key.equals(storageService)) { JsonObject commandCats = commandsJson.getJsonObject(key); if (commandCats.containsKey(commandName)) { return commandCats.getJsonObject(commandName); } } } return null; } }
public class class_name { public static JsonObject matchCommand(JsonObject commandsJson, String commandName, String storageService) { for (String key : commandsJson.keySet()) { if (key.equals(storageService)) { JsonObject commandCats = commandsJson.getJsonObject(key); if (commandCats.containsKey(commandName)) { return commandCats.getJsonObject(commandName); // depends on control dependency: [if], data = [none] } } } return null; } }
public class class_name { public static ModbusResponse createModbusResponse(int functionCode) { ModbusResponse response; switch (functionCode) { case Modbus.READ_COILS: response = new ReadCoilsResponse(); break; case Modbus.READ_INPUT_DISCRETES: response = new ReadInputDiscretesResponse(); break; case Modbus.READ_MULTIPLE_REGISTERS: response = new ReadMultipleRegistersResponse(); break; case Modbus.READ_INPUT_REGISTERS: response = new ReadInputRegistersResponse(); break; case Modbus.WRITE_COIL: response = new WriteCoilResponse(); break; case Modbus.WRITE_SINGLE_REGISTER: response = new WriteSingleRegisterResponse(); break; case Modbus.WRITE_MULTIPLE_COILS: response = new WriteMultipleCoilsResponse(); break; case Modbus.WRITE_MULTIPLE_REGISTERS: response = new WriteMultipleRegistersResponse(); break; case Modbus.READ_EXCEPTION_STATUS: response = new ReadExceptionStatusResponse(); break; case Modbus.READ_SERIAL_DIAGNOSTICS: response = new ReadSerialDiagnosticsResponse(); break; case Modbus.READ_COMM_EVENT_COUNTER: response = new ReadCommEventCounterResponse(); break; case Modbus.READ_COMM_EVENT_LOG: response = new ReadCommEventLogResponse(); break; case Modbus.REPORT_SLAVE_ID: response = new ReportSlaveIDResponse(); break; case Modbus.READ_FILE_RECORD: response = new ReadFileRecordResponse(); break; case Modbus.WRITE_FILE_RECORD: response = new WriteFileRecordResponse(); break; case Modbus.MASK_WRITE_REGISTER: response = new MaskWriteRegisterResponse(); break; case Modbus.READ_WRITE_MULTIPLE: response = new ReadWriteMultipleResponse(); break; case Modbus.READ_FIFO_QUEUE: response = new ReadFIFOQueueResponse(); break; case Modbus.READ_MEI: response = new ReadMEIResponse(); break; default: if ((functionCode & 0x80) != 0) { response = new ExceptionResponse(functionCode); } else { response = new ExceptionResponse(); } break; } return response; } }
public class class_name { public static ModbusResponse createModbusResponse(int functionCode) { ModbusResponse response; switch (functionCode) { case Modbus.READ_COILS: response = new ReadCoilsResponse(); break; case Modbus.READ_INPUT_DISCRETES: response = new ReadInputDiscretesResponse(); break; case Modbus.READ_MULTIPLE_REGISTERS: response = new ReadMultipleRegistersResponse(); break; case Modbus.READ_INPUT_REGISTERS: response = new ReadInputRegistersResponse(); break; case Modbus.WRITE_COIL: response = new WriteCoilResponse(); break; case Modbus.WRITE_SINGLE_REGISTER: response = new WriteSingleRegisterResponse(); break; case Modbus.WRITE_MULTIPLE_COILS: response = new WriteMultipleCoilsResponse(); break; case Modbus.WRITE_MULTIPLE_REGISTERS: response = new WriteMultipleRegistersResponse(); break; case Modbus.READ_EXCEPTION_STATUS: response = new ReadExceptionStatusResponse(); break; case Modbus.READ_SERIAL_DIAGNOSTICS: response = new ReadSerialDiagnosticsResponse(); break; case Modbus.READ_COMM_EVENT_COUNTER: response = new ReadCommEventCounterResponse(); break; case Modbus.READ_COMM_EVENT_LOG: response = new ReadCommEventLogResponse(); break; case Modbus.REPORT_SLAVE_ID: response = new ReportSlaveIDResponse(); break; case Modbus.READ_FILE_RECORD: response = new ReadFileRecordResponse(); break; case Modbus.WRITE_FILE_RECORD: response = new WriteFileRecordResponse(); break; case Modbus.MASK_WRITE_REGISTER: response = new MaskWriteRegisterResponse(); break; case Modbus.READ_WRITE_MULTIPLE: response = new ReadWriteMultipleResponse(); break; case Modbus.READ_FIFO_QUEUE: response = new ReadFIFOQueueResponse(); break; case Modbus.READ_MEI: response = new ReadMEIResponse(); break; default: if ((functionCode & 0x80) != 0) { response = new ExceptionResponse(functionCode); // depends on control dependency: [if], data = [none] } else { response = new ExceptionResponse(); // depends on control dependency: [if], data = [none] } break; } return response; } }
public class class_name { public boolean proofStep(ResolutionState state) { Functor isOp = state.getGoalStack().poll().getFunctor(); // Evaluate the second argument as a fully instantiated numeric value. Term expressionValue = BuiltInUtils.evaluateAsNumeric(isOp.getArgument(1)); // This is used to record variables bound during the unification, so that they may be undone if the resolution // state is backtracked over. List<Variable> boundVariables = new LinkedList<Variable>(); // Unify against the LHS. boolean matched = state.getUnifier().unifyInternal(isOp.getArgument(0), expressionValue, boundVariables, boundVariables); for (Variable binding : boundVariables) { state.getVariableBindings().offer(binding); } return matched; } }
public class class_name { public boolean proofStep(ResolutionState state) { Functor isOp = state.getGoalStack().poll().getFunctor(); // Evaluate the second argument as a fully instantiated numeric value. Term expressionValue = BuiltInUtils.evaluateAsNumeric(isOp.getArgument(1)); // This is used to record variables bound during the unification, so that they may be undone if the resolution // state is backtracked over. List<Variable> boundVariables = new LinkedList<Variable>(); // Unify against the LHS. boolean matched = state.getUnifier().unifyInternal(isOp.getArgument(0), expressionValue, boundVariables, boundVariables); for (Variable binding : boundVariables) { state.getVariableBindings().offer(binding); // depends on control dependency: [for], data = [binding] } return matched; } }
public class class_name { public void setRelationships(java.util.Collection<Relationship> relationships) { if (relationships == null) { this.relationships = null; return; } this.relationships = new java.util.ArrayList<Relationship>(relationships); } }
public class class_name { public void setRelationships(java.util.Collection<Relationship> relationships) { if (relationships == null) { this.relationships = null; // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } this.relationships = new java.util.ArrayList<Relationship>(relationships); } }
public class class_name { private static String getName(String name, Field field) { if (isEmpty(name)) { name = field.getName(); } return name; } }
public class class_name { private static String getName(String name, Field field) { if (isEmpty(name)) { name = field.getName(); // depends on control dependency: [if], data = [none] } return name; } }
public class class_name { public void marshall(CreateGovCloudAccountRequest createGovCloudAccountRequest, ProtocolMarshaller protocolMarshaller) { if (createGovCloudAccountRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(createGovCloudAccountRequest.getEmail(), EMAIL_BINDING); protocolMarshaller.marshall(createGovCloudAccountRequest.getAccountName(), ACCOUNTNAME_BINDING); protocolMarshaller.marshall(createGovCloudAccountRequest.getRoleName(), ROLENAME_BINDING); protocolMarshaller.marshall(createGovCloudAccountRequest.getIamUserAccessToBilling(), IAMUSERACCESSTOBILLING_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(CreateGovCloudAccountRequest createGovCloudAccountRequest, ProtocolMarshaller protocolMarshaller) { if (createGovCloudAccountRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(createGovCloudAccountRequest.getEmail(), EMAIL_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(createGovCloudAccountRequest.getAccountName(), ACCOUNTNAME_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(createGovCloudAccountRequest.getRoleName(), ROLENAME_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(createGovCloudAccountRequest.getIamUserAccessToBilling(), IAMUSERACCESSTOBILLING_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static <T extends Executable> Predicate<T> executableHasSameParameterTypesAs(T reference) { return candidate -> { if (candidate == null) { return false; } Class<?>[] candidateParameterTypes = candidate.getParameterTypes(); Class<?>[] referenceParameterTypes = reference.getParameterTypes(); if (candidateParameterTypes.length != referenceParameterTypes.length) { return false; } for (int i = 0; i < candidateParameterTypes.length; i++) { if (!candidateParameterTypes[i].equals(referenceParameterTypes[i])) { return false; } } return true; }; } }
public class class_name { public static <T extends Executable> Predicate<T> executableHasSameParameterTypesAs(T reference) { return candidate -> { if (candidate == null) { return false; } Class<?>[] candidateParameterTypes = candidate.getParameterTypes(); Class<?>[] referenceParameterTypes = reference.getParameterTypes(); if (candidateParameterTypes.length != referenceParameterTypes.length) { return false; } for (int i = 0; i < candidateParameterTypes.length; i++) { if (!candidateParameterTypes[i].equals(referenceParameterTypes[i])) { return false; // depends on control dependency: [if], data = [none] } } return true; }; } }
public class class_name { public Map<String, Object> getModuleFieldsFilters() { final Map<String, Object> params = new HashMap<String, Object>(); for(final Filter filter: filters){ params.putAll(filter.moduleFilterFields()); } return params; } }
public class class_name { public Map<String, Object> getModuleFieldsFilters() { final Map<String, Object> params = new HashMap<String, Object>(); for(final Filter filter: filters){ params.putAll(filter.moduleFilterFields()); // depends on control dependency: [for], data = [filter] } return params; } }
public class class_name { public void setProviders(Map<String, IPermissionTargetProvider> providers) { this.providers.clear(); for (Map.Entry<String, IPermissionTargetProvider> provider : providers.entrySet()) { this.providers.put(provider.getKey(), provider.getValue()); } } }
public class class_name { public void setProviders(Map<String, IPermissionTargetProvider> providers) { this.providers.clear(); for (Map.Entry<String, IPermissionTargetProvider> provider : providers.entrySet()) { this.providers.put(provider.getKey(), provider.getValue()); // depends on control dependency: [for], data = [provider] } } }
public class class_name { public boolean generateAndSort(final Iterator<? extends T> iterator, final TransformationStrategy<? super T> transform, final long seed) { // We cache all variables for faster access final int[] d = this.d; final int[] e = new int[3]; cleanUpIfNecessary(); /* We build the XOR'd edge list and compute the degree of each vertex. */ for(int k = 0; k < numEdges; k++) { bitVectorToEdge(transform.toBitVector(iterator.next()), seed, numVertices, partSize, e); xorEdge(k, e[0], e[1], e[2], false); d[e[0]]++; d[e[1]]++; d[e[2]]++; } if (iterator.hasNext()) throw new IllegalStateException("This " + HypergraphSorter.class.getSimpleName() + " has " + numEdges + " edges, but the provided iterator returns more"); return sort(); } }
public class class_name { public boolean generateAndSort(final Iterator<? extends T> iterator, final TransformationStrategy<? super T> transform, final long seed) { // We cache all variables for faster access final int[] d = this.d; final int[] e = new int[3]; cleanUpIfNecessary(); /* We build the XOR'd edge list and compute the degree of each vertex. */ for(int k = 0; k < numEdges; k++) { bitVectorToEdge(transform.toBitVector(iterator.next()), seed, numVertices, partSize, e); // depends on control dependency: [for], data = [none] xorEdge(k, e[0], e[1], e[2], false); // depends on control dependency: [for], data = [k] d[e[0]]++; // depends on control dependency: [for], data = [none] d[e[1]]++; // depends on control dependency: [for], data = [none] d[e[2]]++; // depends on control dependency: [for], data = [none] } if (iterator.hasNext()) throw new IllegalStateException("This " + HypergraphSorter.class.getSimpleName() + " has " + numEdges + " edges, but the provided iterator returns more"); return sort(); } }
public class class_name { @FFDCIgnore({ IOException.class, InterruptedException.class }) public static List<String> executeProgramWithInput(String input, String... commandLine) throws OperatingSystemException { try { ProcessBuilder builder = new ProcessBuilder(); builder.command(commandLine); Process process = builder.start(); if (input != null) { try (OutputStream os = process.getOutputStream()) { try (OutputStreamWriter osw = new OutputStreamWriter(os)) { try (BufferedWriter bw = new BufferedWriter(osw)) { bw.write(input); bw.flush(); } } } } List<String> lines = new ArrayList<String>(); try (InputStream is = process.getInputStream()) { try (InputStreamReader isr = new InputStreamReader(is)) { try (BufferedReader br = new BufferedReader(isr)) { String line; while ((line = br.readLine()) != null) { lines.add(line); } } } } int returnCode = process.waitFor(); if (returnCode != 0) { throw new OperatingSystemException(Tr.formatMessage(tc, "os.execute.error", commandLine, returnCode, lines)); } return lines; } catch (IOException e) { throw new OperatingSystemException(e); } catch (InterruptedException e) { throw new OperatingSystemException(e); } } }
public class class_name { @FFDCIgnore({ IOException.class, InterruptedException.class }) public static List<String> executeProgramWithInput(String input, String... commandLine) throws OperatingSystemException { try { ProcessBuilder builder = new ProcessBuilder(); builder.command(commandLine); Process process = builder.start(); if (input != null) { try (OutputStream os = process.getOutputStream()) { try (OutputStreamWriter osw = new OutputStreamWriter(os)) { try (BufferedWriter bw = new BufferedWriter(osw)) { bw.write(input); bw.flush(); // depends on control dependency: [if], data = [none] } } } } List<String> lines = new ArrayList<String>(); try (InputStream is = process.getInputStream()) { try (InputStreamReader isr = new InputStreamReader(is)) { try (BufferedReader br = new BufferedReader(isr)) { String line; while ((line = br.readLine()) != null) { lines.add(line); // depends on control dependency: [while], data = [none] } } } } int returnCode = process.waitFor(); if (returnCode != 0) { throw new OperatingSystemException(Tr.formatMessage(tc, "os.execute.error", commandLine, returnCode, lines)); } return lines; } catch (IOException e) { throw new OperatingSystemException(e); } catch (InterruptedException e) { throw new OperatingSystemException(e); } } }
public class class_name { public static List<String> tokenize_path(String path) { String[] tokens = path.split(SEPARATOR); java.util.ArrayList<String> rtn = new ArrayList<>(); for (String str : tokens) { if (!str.isEmpty()) { rtn.add(str); } } return rtn; } }
public class class_name { public static List<String> tokenize_path(String path) { String[] tokens = path.split(SEPARATOR); java.util.ArrayList<String> rtn = new ArrayList<>(); for (String str : tokens) { if (!str.isEmpty()) { rtn.add(str); // depends on control dependency: [if], data = [none] } } return rtn; } }
public class class_name { public Set<String> getNamesPerSurname(final String surname) { if (surname == null) { return Collections.emptySet(); } if (!surnameIndex.containsKey(surname)) { return Collections.emptySet(); } return Collections.unmodifiableSet(surnameIndex.get(surname).keySet()); } }
public class class_name { public Set<String> getNamesPerSurname(final String surname) { if (surname == null) { return Collections.emptySet(); // depends on control dependency: [if], data = [none] } if (!surnameIndex.containsKey(surname)) { return Collections.emptySet(); // depends on control dependency: [if], data = [none] } return Collections.unmodifiableSet(surnameIndex.get(surname).keySet()); } }
public class class_name { @VisibleForTesting static boolean viewMatches(URI view, String requested) { // test that the requested options are a subset of the final options Map<String, String> requestedOptions = optionsForUri(URI.create(requested)); Map<String, String> finalOptions = optionsForUri(view); for (Map.Entry<String, String> entry : requestedOptions.entrySet()) { if (!finalOptions.containsKey(entry.getKey()) || !finalOptions.get(entry.getKey()).equals(entry.getValue())) { return false; } } return true; } }
public class class_name { @VisibleForTesting static boolean viewMatches(URI view, String requested) { // test that the requested options are a subset of the final options Map<String, String> requestedOptions = optionsForUri(URI.create(requested)); Map<String, String> finalOptions = optionsForUri(view); for (Map.Entry<String, String> entry : requestedOptions.entrySet()) { if (!finalOptions.containsKey(entry.getKey()) || !finalOptions.get(entry.getKey()).equals(entry.getValue())) { return false; // depends on control dependency: [if], data = [none] } } return true; } }
public class class_name { protected void loadCharacterData() { frc = new FontRenderContext(null, true, true); float totalWidth = 0; for (char c = 0; c < 256; c++) { String s = "" + c; LineMetrics lm = font.getLineMetrics(s, frc); Rectangle2D bounds = font.getStringBounds(s, frc); CharData cd = new CharData(c, lm.getAscent(), (float) bounds.getWidth(), fontGeneratorOptions.fontSize); charData[c] = cd; totalWidth += cd.getFullWidth(fontGeneratorOptions); } int split = 1; while (totalWidth / split > fontGeneratorOptions.fontSize * split) split++; //size = (int) Math.max(totalWidth / (split - 1), options.fontSize * (split - 1)); size = roundUp((int) totalWidth / (split - 1)); } }
public class class_name { protected void loadCharacterData() { frc = new FontRenderContext(null, true, true); float totalWidth = 0; for (char c = 0; c < 256; c++) { String s = "" + c; LineMetrics lm = font.getLineMetrics(s, frc); Rectangle2D bounds = font.getStringBounds(s, frc); CharData cd = new CharData(c, lm.getAscent(), (float) bounds.getWidth(), fontGeneratorOptions.fontSize); charData[c] = cd; // depends on control dependency: [for], data = [c] totalWidth += cd.getFullWidth(fontGeneratorOptions); // depends on control dependency: [for], data = [none] } int split = 1; while (totalWidth / split > fontGeneratorOptions.fontSize * split) split++; //size = (int) Math.max(totalWidth / (split - 1), options.fontSize * (split - 1)); size = roundUp((int) totalWidth / (split - 1)); } }
public class class_name { public void setWorkingDirectory(Path dir) { if (!dir.isAbsolute()) { FileSystem.LogForCollect .info("set job working directory to non absolute path: " + dir + " working directory: " + getWorkingDirectory()); } dir = new Path(getWorkingDirectory(), dir); set("mapred.working.dir", dir.toString()); } }
public class class_name { public void setWorkingDirectory(Path dir) { if (!dir.isAbsolute()) { FileSystem.LogForCollect .info("set job working directory to non absolute path: " + dir + " working directory: " + getWorkingDirectory()); // depends on control dependency: [if], data = [none] } dir = new Path(getWorkingDirectory(), dir); set("mapred.working.dir", dir.toString()); } }
public class class_name { public void processResponseEvent(HttpClientNIOResponseEvent event, HttpClientNIORequestActivityImpl activity) { HttpClientNIORequestActivityHandle ah = new HttpClientNIORequestActivityHandle(activity.getId()); if (tracer.isFineEnabled()) tracer.fine("==== FIRING ResponseEvent EVENT TO LOCAL SLEE, Event: " + event + " ===="); try { resourceAdaptorContext.getSleeEndpoint().fireEvent(ah, fireableEventType, event, null, null, EVENT_FLAGS); } catch (Throwable e) { tracer.severe(e.getMessage(), e); } } }
public class class_name { public void processResponseEvent(HttpClientNIOResponseEvent event, HttpClientNIORequestActivityImpl activity) { HttpClientNIORequestActivityHandle ah = new HttpClientNIORequestActivityHandle(activity.getId()); if (tracer.isFineEnabled()) tracer.fine("==== FIRING ResponseEvent EVENT TO LOCAL SLEE, Event: " + event + " ===="); try { resourceAdaptorContext.getSleeEndpoint().fireEvent(ah, fireableEventType, event, null, null, EVENT_FLAGS); // depends on control dependency: [try], data = [none] } catch (Throwable e) { tracer.severe(e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public String[] decodeSequences(final String[] preds) { final List<String> decodedSequences = new ArrayList<>(); for (String pred : preds) { pred = startPattern.matcher(pred).replaceAll("B-$1"); pred = contPattern.matcher(pred).replaceAll("I-$1"); pred = lastPattern.matcher(pred).replaceAll("I-$1"); pred = unitPattern.matcher(pred).replaceAll("B-$1"); pred = otherPattern.matcher(pred).replaceAll("O"); decodedSequences.add(pred); } return decodedSequences.toArray(new String[decodedSequences.size()]); } }
public class class_name { public String[] decodeSequences(final String[] preds) { final List<String> decodedSequences = new ArrayList<>(); for (String pred : preds) { pred = startPattern.matcher(pred).replaceAll("B-$1"); // depends on control dependency: [for], data = [pred] pred = contPattern.matcher(pred).replaceAll("I-$1"); // depends on control dependency: [for], data = [pred] pred = lastPattern.matcher(pred).replaceAll("I-$1"); // depends on control dependency: [for], data = [pred] pred = unitPattern.matcher(pred).replaceAll("B-$1"); // depends on control dependency: [for], data = [pred] pred = otherPattern.matcher(pred).replaceAll("O"); // depends on control dependency: [for], data = [pred] decodedSequences.add(pred); // depends on control dependency: [for], data = [pred] } return decodedSequences.toArray(new String[decodedSequences.size()]); } }
public class class_name { public EClass getBRS() { if (brsEClass == null) { brsEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(222); } return brsEClass; } }
public class class_name { public EClass getBRS() { if (brsEClass == null) { brsEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(222); // depends on control dependency: [if], data = [none] } return brsEClass; } }
public class class_name { public Diff build() { final DOMDifferenceEngine d = new DOMDifferenceEngine(); final CollectResultsListener collectResultsListener = new CollectResultsListener(comparisonResultsToCheck); d.addDifferenceListener(collectResultsListener); if (nodeMatcher != null) { d.setNodeMatcher(nodeMatcher); } d.setDifferenceEvaluator(differenceEvaluator); d.setComparisonController(comparisonController); for (ComparisonListener comparisonListener : comparisonListeners) { d.addComparisonListener(comparisonListener); } for (ComparisonListener comparisonListener : differenceListeners) { d.addDifferenceListener(comparisonListener); } if (namespaceContext != null) { d.setNamespaceContext(namespaceContext); } if (attributeFilter != null) { d.setAttributeFilter(attributeFilter); } if (nodeFilter != null) { d.setNodeFilter(nodeFilter); } if (documentBuilderFactory != null) { d.setDocumentBuilderFactory(documentBuilderFactory); } d.compare(wrap(controlSource), wrap(testSource)); return formatter == null ? new Diff(controlSource, testSource, collectResultsListener.getDifferences()) : new Diff(controlSource, testSource, formatter, collectResultsListener.getDifferences()); } }
public class class_name { public Diff build() { final DOMDifferenceEngine d = new DOMDifferenceEngine(); final CollectResultsListener collectResultsListener = new CollectResultsListener(comparisonResultsToCheck); d.addDifferenceListener(collectResultsListener); if (nodeMatcher != null) { d.setNodeMatcher(nodeMatcher); // depends on control dependency: [if], data = [(nodeMatcher] } d.setDifferenceEvaluator(differenceEvaluator); d.setComparisonController(comparisonController); for (ComparisonListener comparisonListener : comparisonListeners) { d.addComparisonListener(comparisonListener); // depends on control dependency: [for], data = [comparisonListener] } for (ComparisonListener comparisonListener : differenceListeners) { d.addDifferenceListener(comparisonListener); // depends on control dependency: [for], data = [comparisonListener] } if (namespaceContext != null) { d.setNamespaceContext(namespaceContext); // depends on control dependency: [if], data = [(namespaceContext] } if (attributeFilter != null) { d.setAttributeFilter(attributeFilter); // depends on control dependency: [if], data = [(attributeFilter] } if (nodeFilter != null) { d.setNodeFilter(nodeFilter); // depends on control dependency: [if], data = [(nodeFilter] } if (documentBuilderFactory != null) { d.setDocumentBuilderFactory(documentBuilderFactory); // depends on control dependency: [if], data = [(documentBuilderFactory] } d.compare(wrap(controlSource), wrap(testSource)); return formatter == null ? new Diff(controlSource, testSource, collectResultsListener.getDifferences()) : new Diff(controlSource, testSource, formatter, collectResultsListener.getDifferences()); } }
public class class_name { boolean isUniqueWithColumns(int[] cols) { if (constType != UNIQUE || core.mainCols.length != cols.length) { return false; } return ArrayUtil.haveEqualSets(core.mainCols, cols, cols.length); } }
public class class_name { boolean isUniqueWithColumns(int[] cols) { if (constType != UNIQUE || core.mainCols.length != cols.length) { return false; // depends on control dependency: [if], data = [none] } return ArrayUtil.haveEqualSets(core.mainCols, cols, cols.length); } }
public class class_name { public static String resolveUrl(String genericUrl, MessageParameters parameters) { Preconditions.checkState(parameters.isResolved(), "Not all mandatory message parameters were resolved."); StringBuilder path = new StringBuilder(genericUrl); StringBuilder queryParameters = new StringBuilder(); for (MessageParameter<?> pathParameter : parameters.getPathParameters()) { if (pathParameter.isResolved()) { int start = path.indexOf(':' + pathParameter.getKey()); final String pathValue = Preconditions.checkNotNull(pathParameter.getValueAsString()); // only replace path parameters if they are present if (start != -1) { path.replace(start, start + pathParameter.getKey().length() + 1, pathValue); } } } boolean isFirstQueryParameter = true; for (MessageQueryParameter<?> queryParameter : parameters.getQueryParameters()) { if (queryParameter.isResolved()) { if (isFirstQueryParameter) { queryParameters.append('?'); isFirstQueryParameter = false; } else { queryParameters.append('&'); } queryParameters.append(queryParameter.getKey()); queryParameters.append('='); queryParameters.append(queryParameter.getValueAsString()); } } path.append(queryParameters); return path.toString(); } }
public class class_name { public static String resolveUrl(String genericUrl, MessageParameters parameters) { Preconditions.checkState(parameters.isResolved(), "Not all mandatory message parameters were resolved."); StringBuilder path = new StringBuilder(genericUrl); StringBuilder queryParameters = new StringBuilder(); for (MessageParameter<?> pathParameter : parameters.getPathParameters()) { if (pathParameter.isResolved()) { int start = path.indexOf(':' + pathParameter.getKey()); final String pathValue = Preconditions.checkNotNull(pathParameter.getValueAsString()); // only replace path parameters if they are present if (start != -1) { path.replace(start, start + pathParameter.getKey().length() + 1, pathValue); // depends on control dependency: [if], data = [(start] } } } boolean isFirstQueryParameter = true; for (MessageQueryParameter<?> queryParameter : parameters.getQueryParameters()) { if (queryParameter.isResolved()) { if (isFirstQueryParameter) { queryParameters.append('?'); // depends on control dependency: [if], data = [none] isFirstQueryParameter = false; // depends on control dependency: [if], data = [none] } else { queryParameters.append('&'); // depends on control dependency: [if], data = [none] } queryParameters.append(queryParameter.getKey()); // depends on control dependency: [if], data = [none] queryParameters.append('='); // depends on control dependency: [if], data = [none] queryParameters.append(queryParameter.getValueAsString()); // depends on control dependency: [if], data = [none] } } path.append(queryParameters); return path.toString(); } }
public class class_name { public String getUrlForPageReference(String pageReference) { String url = pageReferenceToPageUrlMap.get(pageReference); if (url == null) { fail("No url is found for page name: '" + pageReference + "'. Available page references are: " + pageReferenceToPageUrlMap.keySet().toString()); } return url; } }
public class class_name { public String getUrlForPageReference(String pageReference) { String url = pageReferenceToPageUrlMap.get(pageReference); if (url == null) { fail("No url is found for page name: '" + pageReference + "'. Available page references are: " + pageReferenceToPageUrlMap.keySet().toString()); // depends on control dependency: [if], data = [none] } return url; } }
public class class_name { public static void topBorderLabel( final LabelPositionCollector labels, final GeometryFactory geometryFactory, final Polygon rotatedBounds, final String unit, final double x, final AffineTransform worldToScreenTransform, final MathTransform toLabelProjection, final GridLabelFormat labelFormat) { Envelope envelopeInternal = rotatedBounds.getEnvelopeInternal(); LineString lineString = geometryFactory.createLineString(new Coordinate[]{ new Coordinate(x, envelopeInternal.centre().y), new Coordinate(x, envelopeInternal.getMaxY()) }); Geometry intersections = lineString.intersection(rotatedBounds.getExteriorRing()); if (intersections.getNumPoints() > 0) { Coordinate borderIntersection = intersections.getGeometryN(0).getCoordinates()[0]; double[] screenPoints = new double[2]; worldToScreenTransform .transform(new double[]{borderIntersection.x, borderIntersection.y}, 0, screenPoints, 0, 1); double[] labelProj = transformToLabelProjection(toLabelProjection, borderIntersection); labels.add(new GridLabel(createLabel(labelProj[0], unit, labelFormat), (int) screenPoints[0], (int) screenPoints[1], TOP)); } } }
public class class_name { public static void topBorderLabel( final LabelPositionCollector labels, final GeometryFactory geometryFactory, final Polygon rotatedBounds, final String unit, final double x, final AffineTransform worldToScreenTransform, final MathTransform toLabelProjection, final GridLabelFormat labelFormat) { Envelope envelopeInternal = rotatedBounds.getEnvelopeInternal(); LineString lineString = geometryFactory.createLineString(new Coordinate[]{ new Coordinate(x, envelopeInternal.centre().y), new Coordinate(x, envelopeInternal.getMaxY()) }); Geometry intersections = lineString.intersection(rotatedBounds.getExteriorRing()); if (intersections.getNumPoints() > 0) { Coordinate borderIntersection = intersections.getGeometryN(0).getCoordinates()[0]; double[] screenPoints = new double[2]; worldToScreenTransform .transform(new double[]{borderIntersection.x, borderIntersection.y}, 0, screenPoints, 0, 1); // depends on control dependency: [if], data = [none] double[] labelProj = transformToLabelProjection(toLabelProjection, borderIntersection); labels.add(new GridLabel(createLabel(labelProj[0], unit, labelFormat), (int) screenPoints[0], (int) screenPoints[1], TOP)); // depends on control dependency: [if], data = [none] } } }
public class class_name { private Map<ScopeService, Service> createServices(final Set<ScopeService> services) { Map<ScopeService, Service> actualServices = Maps.newTreeMap(); for (ScopeService requiredService : services) { if (availableServices.containsKey(requiredService)) { for (ScopeService availableService : availableServices.keySet()) { if (availableService == requiredService) { actualServices.put(requiredService, requiredService.newInstance(this)); } } } } return actualServices; } }
public class class_name { private Map<ScopeService, Service> createServices(final Set<ScopeService> services) { Map<ScopeService, Service> actualServices = Maps.newTreeMap(); for (ScopeService requiredService : services) { if (availableServices.containsKey(requiredService)) { for (ScopeService availableService : availableServices.keySet()) { if (availableService == requiredService) { actualServices.put(requiredService, requiredService.newInstance(this)); // depends on control dependency: [if], data = [none] } } } } return actualServices; } }
public class class_name { public boolean await(Object taskGroupId, long timeout, TimeUnit unit) { CountDownLatch latch = taskKeyToLatch.get(taskGroupId); if (latch == null) throw new IllegalArgumentException( "Unknown task group: " + taskGroupId); try { if (latch.await(timeout, unit)) { // Once finished, remove the key so it can be associated with a // new task taskKeyToLatch.remove(taskGroupId); return true; } return false; } catch (InterruptedException ie) { throw new IllegalStateException("Not all tasks finished", ie); } } }
public class class_name { public boolean await(Object taskGroupId, long timeout, TimeUnit unit) { CountDownLatch latch = taskKeyToLatch.get(taskGroupId); if (latch == null) throw new IllegalArgumentException( "Unknown task group: " + taskGroupId); try { if (latch.await(timeout, unit)) { // Once finished, remove the key so it can be associated with a // new task taskKeyToLatch.remove(taskGroupId); // depends on control dependency: [if], data = [none] return true; // depends on control dependency: [if], data = [none] } return false; // depends on control dependency: [try], data = [none] } catch (InterruptedException ie) { throw new IllegalStateException("Not all tasks finished", ie); } // depends on control dependency: [catch], data = [none] } }
public class class_name { private static OptionalEntity<RelatedQuery> getEntity(final CreateForm form, final String username, final long currentTime) { switch (form.crudMode) { case CrudMode.CREATE: return OptionalEntity.of(new RelatedQuery()).map(entity -> { entity.setCreatedBy(username); entity.setCreatedTime(currentTime); return entity; }); case CrudMode.EDIT: if (form instanceof EditForm) { return ComponentUtil.getComponent(RelatedQueryService.class).getRelatedQuery(((EditForm) form).id); } break; default: break; } return OptionalEntity.empty(); } }
public class class_name { private static OptionalEntity<RelatedQuery> getEntity(final CreateForm form, final String username, final long currentTime) { switch (form.crudMode) { case CrudMode.CREATE: return OptionalEntity.of(new RelatedQuery()).map(entity -> { entity.setCreatedBy(username); entity.setCreatedTime(currentTime); return entity; }); case CrudMode.EDIT: if (form instanceof EditForm) { return ComponentUtil.getComponent(RelatedQueryService.class).getRelatedQuery(((EditForm) form).id); // depends on control dependency: [if], data = [none] } break; default: break; } return OptionalEntity.empty(); } }
public class class_name { public StringColumn set(Selection rowSelection, String newValue) { for (int row : rowSelection) { set(row, newValue); } return this; } }
public class class_name { public StringColumn set(Selection rowSelection, String newValue) { for (int row : rowSelection) { set(row, newValue); // depends on control dependency: [for], data = [row] } return this; } }
public class class_name { public boolean isCrossPartitionQuery(@NonNull List<String> partitionKeys) { if (partitionKeys.isEmpty()) { return true; } return partitionKeys.stream().filter(this::isCrossPartitionQuery) .findFirst() .map(p -> true) .orElse(hasKeywordOr()); } }
public class class_name { public boolean isCrossPartitionQuery(@NonNull List<String> partitionKeys) { if (partitionKeys.isEmpty()) { return true; // depends on control dependency: [if], data = [none] } return partitionKeys.stream().filter(this::isCrossPartitionQuery) .findFirst() .map(p -> true) .orElse(hasKeywordOr()); } }
public class class_name { public static String getFormattedCount(Long count) { final String unit; final Double dbl; final DecimalFormat format = new DecimalFormat("#.#"); if (count < 1000) { return format.format(count); } else if (count < 1000000) { unit = "k"; dbl = count / 1000.0; } else if (count < 1000000000) { unit = "m"; dbl = count / 1000000.0; } else { unit = "b"; dbl = count / 1000000000.0; } return format.format(dbl) + unit; } }
public class class_name { public static String getFormattedCount(Long count) { final String unit; final Double dbl; final DecimalFormat format = new DecimalFormat("#.#"); if (count < 1000) { return format.format(count); // depends on control dependency: [if], data = [(count] } else if (count < 1000000) { unit = "k"; // depends on control dependency: [if], data = [none] dbl = count / 1000.0; // depends on control dependency: [if], data = [none] } else if (count < 1000000000) { unit = "m"; // depends on control dependency: [if], data = [none] dbl = count / 1000000.0; // depends on control dependency: [if], data = [none] } else { unit = "b"; // depends on control dependency: [if], data = [none] dbl = count / 1000000000.0; // depends on control dependency: [if], data = [none] } return format.format(dbl) + unit; } }
public class class_name { boolean makeAccessibleWithUnsafe(AccessibleObject ao) { if (theUnsafe != null && overrideField != null) { try { Method method = unsafeClass.getMethod("objectFieldOffset", Field.class); long overrideOffset = (Long) method.invoke(theUnsafe, overrideField); // long overrideOffset = theUnsafe.objectFieldOffset(overrideField); Method putBooleanMethod = unsafeClass.getMethod("putBoolean", Object.class, long.class, boolean.class); putBooleanMethod.invoke(theUnsafe, ao, overrideOffset, true); // theUnsafe.putBoolean(ao, overrideOffset, true); return true; } catch (Exception ignored) { // do nothing } } return false; } }
public class class_name { boolean makeAccessibleWithUnsafe(AccessibleObject ao) { if (theUnsafe != null && overrideField != null) { try { Method method = unsafeClass.getMethod("objectFieldOffset", Field.class); long overrideOffset = (Long) method.invoke(theUnsafe, overrideField); // long overrideOffset = theUnsafe.objectFieldOffset(overrideField); Method putBooleanMethod = unsafeClass.getMethod("putBoolean", Object.class, long.class, boolean.class); putBooleanMethod.invoke(theUnsafe, ao, overrideOffset, true); // theUnsafe.putBoolean(ao, overrideOffset, true); // depends on control dependency: [try], data = [none] return true; // depends on control dependency: [try], data = [none] } catch (Exception ignored) { // do nothing } // depends on control dependency: [catch], data = [none] } return false; } }
public class class_name { public void removeWorstFit() { // find the observation with the most error int worstIndex=-1; double worstError = -1; for( int i = 0; i < y.numRows; i++ ) { double predictedObs = 0; for( int j = 0; j < coef.numRows; j++ ) { predictedObs += A.get(i,j)*coef.get(j,0); } double error = Math.abs(predictedObs- y.get(i,0)); if( error > worstError ) { worstError = error; worstIndex = i; } } // nothing left to remove, so just return if( worstIndex == -1 ) return; // remove that observation removeObservation(worstIndex); // update A solver.removeRowFromA(worstIndex); // solve for the parameters again solver.solve(y,coef); } }
public class class_name { public void removeWorstFit() { // find the observation with the most error int worstIndex=-1; double worstError = -1; for( int i = 0; i < y.numRows; i++ ) { double predictedObs = 0; for( int j = 0; j < coef.numRows; j++ ) { predictedObs += A.get(i,j)*coef.get(j,0); // depends on control dependency: [for], data = [j] } double error = Math.abs(predictedObs- y.get(i,0)); if( error > worstError ) { worstError = error; // depends on control dependency: [if], data = [none] worstIndex = i; // depends on control dependency: [if], data = [none] } } // nothing left to remove, so just return if( worstIndex == -1 ) return; // remove that observation removeObservation(worstIndex); // update A solver.removeRowFromA(worstIndex); // solve for the parameters again solver.solve(y,coef); } }
public class class_name { @Override public void destroy() { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Destroy " + getExternalName()); } // Destroy the server socket if (this.endPoint != null) { this.endPoint.destroyServerSocket(); } // disconnect from the factory if (null != this.channelFactory) { this.channelFactory.removeChannel(this.channelName); } } }
public class class_name { @Override public void destroy() { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Destroy " + getExternalName()); // depends on control dependency: [if], data = [none] } // Destroy the server socket if (this.endPoint != null) { this.endPoint.destroyServerSocket(); // depends on control dependency: [if], data = [none] } // disconnect from the factory if (null != this.channelFactory) { this.channelFactory.removeChannel(this.channelName); // depends on control dependency: [if], data = [none] } } }
public class class_name { private void setCalTypeAttributes(Variable image, int calType) { String longName = "image values"; //String unit = ""; switch (calType) { case Calibrator.CAL_ALB: longName = "albedo"; //unit = "%"; break; case Calibrator.CAL_BRIT: longName = "brightness values"; break; case Calibrator.CAL_TEMP: longName = "temperature"; //unit = "K"; break; case Calibrator.CAL_RAD: longName = "pixel radiance values"; //unit = "mW/m2/sr/cm-1"; break; case Calibrator.CAL_RAW: longName = "raw image values"; break; default: break; } image.addAttribute(new Attribute("long_name", longName)); if (calUnit != null) { image.addAttribute(new Attribute(CDM.UNITS, calUnit)); } if (calScale != 1.f) { image.addAttribute(new Attribute("scale_factor", calScale)); } } }
public class class_name { private void setCalTypeAttributes(Variable image, int calType) { String longName = "image values"; //String unit = ""; switch (calType) { case Calibrator.CAL_ALB: longName = "albedo"; //unit = "%"; break; case Calibrator.CAL_BRIT: longName = "brightness values"; break; case Calibrator.CAL_TEMP: longName = "temperature"; //unit = "K"; break; case Calibrator.CAL_RAD: longName = "pixel radiance values"; //unit = "mW/m2/sr/cm-1"; break; case Calibrator.CAL_RAW: longName = "raw image values"; break; default: break; } image.addAttribute(new Attribute("long_name", longName)); if (calUnit != null) { image.addAttribute(new Attribute(CDM.UNITS, calUnit)); // depends on control dependency: [if], data = [none] } if (calScale != 1.f) { image.addAttribute(new Attribute("scale_factor", calScale)); // depends on control dependency: [if], data = [none] } } }
public class class_name { public T error(int errorRes) { if (view!=null && view instanceof TextView) { ((TextView) view).setError(context.getString(errorRes)); } return self(); } }
public class class_name { public T error(int errorRes) { if (view!=null && view instanceof TextView) { ((TextView) view).setError(context.getString(errorRes)); // depends on control dependency: [if], data = [none] } return self(); } }
public class class_name { public void marshall(RegexPatternSetSummary regexPatternSetSummary, ProtocolMarshaller protocolMarshaller) { if (regexPatternSetSummary == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(regexPatternSetSummary.getRegexPatternSetId(), REGEXPATTERNSETID_BINDING); protocolMarshaller.marshall(regexPatternSetSummary.getName(), NAME_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(RegexPatternSetSummary regexPatternSetSummary, ProtocolMarshaller protocolMarshaller) { if (regexPatternSetSummary == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(regexPatternSetSummary.getRegexPatternSetId(), REGEXPATTERNSETID_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(regexPatternSetSummary.getName(), NAME_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static void divideElements(final int j, final int numRows , final double[] u, final int startU , final double realA, final double imagA ) { double mag2 = realA*realA + imagA*imagA; int index = (startU+j)*2; for( int i = j; i < numRows; i++ ) { double realU = u[index]; double imagU = u[index+1]; // u[i+startU] /= u_0; u[index++] = (realU*realA + imagU*imagA)/mag2; u[index++] = (imagU*realA - realU*imagA)/mag2; } } }
public class class_name { public static void divideElements(final int j, final int numRows , final double[] u, final int startU , final double realA, final double imagA ) { double mag2 = realA*realA + imagA*imagA; int index = (startU+j)*2; for( int i = j; i < numRows; i++ ) { double realU = u[index]; double imagU = u[index+1]; // u[i+startU] /= u_0; u[index++] = (realU*realA + imagU*imagA)/mag2; // depends on control dependency: [for], data = [none] u[index++] = (imagU*realA - realU*imagA)/mag2; // depends on control dependency: [for], data = [none] } } }
public class class_name { public static URI getRelativePath(final URI base, final URI ref) { final String baseScheme = base.getScheme(); final String refScheme = ref.getScheme(); final String baseAuth = base.getAuthority(); final String refAuth = ref.getAuthority(); if (!(((baseScheme == null && refScheme == null) || (baseScheme != null && refScheme != null && baseScheme.equals(refScheme))) && ((baseAuth == null && refAuth == null) || (baseAuth != null && refAuth != null && baseAuth.equals(refAuth))))) { return ref; } URI rel; if (base.getPath().equals(ref.getPath()) && ref.getFragment() != null) { rel = toURI(""); } else { final StringBuilder upPathBuffer = new StringBuilder(128); final StringBuilder downPathBuffer = new StringBuilder(128); String basePath = base.normalize().getPath(); if (basePath.endsWith("/")) { basePath = basePath + "dummy"; } String refPath = ref.normalize().getPath(); final StringTokenizer baseTokenizer = new StringTokenizer(basePath, URI_SEPARATOR); final StringTokenizer refTokenizer = new StringTokenizer(refPath, URI_SEPARATOR); while (baseTokenizer.countTokens() > 1 && refTokenizer.countTokens() > 1) { final String baseToken = baseTokenizer.nextToken(); final String refToken = refTokenizer.nextToken(); //if OS is Windows, we need to ignore case when comparing path names. final boolean equals = OS_NAME.toLowerCase().contains(OS_NAME_WINDOWS) ? baseToken.equalsIgnoreCase(refToken) : baseToken.equals(refToken); if (!equals) { if (baseToken.endsWith(COLON) || refToken.endsWith(COLON)) { //the two files are in different disks under Windows return ref; } upPathBuffer.append(".."); upPathBuffer.append(URI_SEPARATOR); downPathBuffer.append(refToken); downPathBuffer.append(URI_SEPARATOR); break; } } while (baseTokenizer.countTokens() > 1) { baseTokenizer.nextToken(); upPathBuffer.append(".."); upPathBuffer.append(URI_SEPARATOR); } while (refTokenizer.hasMoreTokens()) { downPathBuffer.append(refTokenizer.nextToken()); if (refTokenizer.hasMoreTokens()) { downPathBuffer.append(URI_SEPARATOR); } } upPathBuffer.append(downPathBuffer); try { rel = new URI(null, null, upPathBuffer.toString(), null, null); } catch (final URISyntaxException e) { throw new IllegalArgumentException(e); } } return setFragment(rel, ref.getFragment()); } }
public class class_name { public static URI getRelativePath(final URI base, final URI ref) { final String baseScheme = base.getScheme(); final String refScheme = ref.getScheme(); final String baseAuth = base.getAuthority(); final String refAuth = ref.getAuthority(); if (!(((baseScheme == null && refScheme == null) || (baseScheme != null && refScheme != null && baseScheme.equals(refScheme))) && ((baseAuth == null && refAuth == null) || (baseAuth != null && refAuth != null && baseAuth.equals(refAuth))))) { return ref; // depends on control dependency: [if], data = [none] } URI rel; if (base.getPath().equals(ref.getPath()) && ref.getFragment() != null) { rel = toURI(""); // depends on control dependency: [if], data = [none] } else { final StringBuilder upPathBuffer = new StringBuilder(128); final StringBuilder downPathBuffer = new StringBuilder(128); String basePath = base.normalize().getPath(); if (basePath.endsWith("/")) { basePath = basePath + "dummy"; // depends on control dependency: [if], data = [none] } String refPath = ref.normalize().getPath(); final StringTokenizer baseTokenizer = new StringTokenizer(basePath, URI_SEPARATOR); final StringTokenizer refTokenizer = new StringTokenizer(refPath, URI_SEPARATOR); while (baseTokenizer.countTokens() > 1 && refTokenizer.countTokens() > 1) { final String baseToken = baseTokenizer.nextToken(); final String refToken = refTokenizer.nextToken(); //if OS is Windows, we need to ignore case when comparing path names. final boolean equals = OS_NAME.toLowerCase().contains(OS_NAME_WINDOWS) ? baseToken.equalsIgnoreCase(refToken) : baseToken.equals(refToken); if (!equals) { if (baseToken.endsWith(COLON) || refToken.endsWith(COLON)) { //the two files are in different disks under Windows return ref; // depends on control dependency: [if], data = [none] } upPathBuffer.append(".."); // depends on control dependency: [if], data = [none] upPathBuffer.append(URI_SEPARATOR); // depends on control dependency: [if], data = [none] downPathBuffer.append(refToken); // depends on control dependency: [if], data = [none] downPathBuffer.append(URI_SEPARATOR); // depends on control dependency: [if], data = [none] break; } } while (baseTokenizer.countTokens() > 1) { baseTokenizer.nextToken(); // depends on control dependency: [while], data = [none] upPathBuffer.append(".."); // depends on control dependency: [while], data = [none] upPathBuffer.append(URI_SEPARATOR); // depends on control dependency: [while], data = [none] } while (refTokenizer.hasMoreTokens()) { downPathBuffer.append(refTokenizer.nextToken()); // depends on control dependency: [while], data = [none] if (refTokenizer.hasMoreTokens()) { downPathBuffer.append(URI_SEPARATOR); // depends on control dependency: [if], data = [none] } } upPathBuffer.append(downPathBuffer); // depends on control dependency: [if], data = [none] try { rel = new URI(null, null, upPathBuffer.toString(), null, null); // depends on control dependency: [try], data = [none] } catch (final URISyntaxException e) { throw new IllegalArgumentException(e); } // depends on control dependency: [catch], data = [none] } return setFragment(rel, ref.getFragment()); } }
public class class_name { public int doSetData(Object data, boolean bDisplayOption, int iMoveMode) { if (!m_bReadOnly) { Object bookmark = null; BaseBuffer buffer = null; // In case a temp buffer is needed boolean bSuccess = false; Object oldBuff = this.getOwner().getData(); // Get a copy of the old key field Record record = this.getOwner().getRecord(); if (record.getEditMode() != Constants.EDIT_ADD) { // Current record (but no changes) - save the bookmark only for possible re-read. try { bookmark = record.getHandle(DBConstants.DATA_SOURCE_HANDLE); } catch (DBException e) { bookmark = null; } } int result = super.doSetData(data, bDisplayOption, iMoveMode); // Do the rest of the behaviors if (result != DBConstants.NORMAL_RETURN) return result; // If error if ((!this.getOwner().isJustModified()) || (data == null)) return result; // If no change or set to null String iOldKeySeq = record.getKeyArea(-1).getKeyName(); record.setKeyArea(keyName); if ((!record.isModified(true)) && ((record.getEditMode() == Constants.EDIT_ADD) || (record.getEditMode() == Constants.EDIT_NONE))) // Modified or valid record { // This is a new record and this is the first mod try { buffer = new VectorBuffer(null); record.getKeyArea(keyName).setupKeyBuffer(buffer, DBConstants.FILE_KEY_AREA); // Save the keys bSuccess = this.seek(record); // Read this record (display if found) record.setKeyArea(iOldKeySeq); // Set the key order back if (!bSuccess) { // Not found, restore the data and the new key record.addNew(); // This may wipe out the keys if (buffer != null) buffer.resetPosition(); // Just to be careful record.getKeyArea(keyName).reverseKeyBuffer(buffer, DBConstants.FILE_KEY_AREA); // Restore the keys result = DBConstants.NORMAL_RETURN; // Everything went okay } else { // Record found - good if (record.getRecordOwner().isBatch()) { // Special case - Can't display this record return DBConstants.DUPLICATE_KEY; } } } catch (DBException e) { return e.getErrorCode(); // Never } } else if (record.getKeyArea(keyName).getUniqueKeyCode() == DBConstants.UNIQUE) { // Data already entered, see if this entry makes a duplicate key! buffer = new VectorBuffer(null); try { buffer.fieldsToBuffer(record, BaseBuffer.ALL_FIELDS); // Save the entire record bSuccess = this.seek(record); // See if this key already exists if (bookmark != null) { if (record.setHandle(bookmark, DBConstants.DATA_SOURCE_HANDLE) != null) // Set the pointer back to the old key record.edit(); else record.addNew(); // Never } else record.addNew();// This is a new record, and they entered non-key data already record.setKeyArea(iOldKeySeq); // Set the key order back buffer.bufferToFields(record, DBConstants.DONT_DISPLAY, DBConstants.READ_MOVE); // Restore the data for (int iFieldSeq = DBConstants.MAIN_FIELD; iFieldSeq < record.getFieldCount() + DBConstants.MAIN_FIELD; iFieldSeq++) { // Redisplay all the fields record.getField(iFieldSeq).displayField(); } } catch (DBException e) { return e.getErrorCode(); // Never } if (bSuccess) { this.getOwner().setData(oldBuff, bDisplayOption, iMoveMode); // Restore a copy of the old key field result = DBConstants.DUPLICATE_KEY; // Can't enter this key, you'll get a dup key! } else result = DBConstants.NORMAL_RETURN; // Good, this is a valid key } return result; } else { // Read only Record record = this.getOwner().getRecord(); int result = super.doSetData(data, bDisplayOption, iMoveMode); // Do the rest of the behaviors if (result != DBConstants.NORMAL_RETURN) return result; // If error or no change if (!this.getOwner().isJustModified()) return result; // If error or no change String strOldKeySeq = Constants.BLANK; strOldKeySeq = record.getKeyArea(-1).getKeyName(); record.setKeyArea(keyName); if (!record.isModified(true)) // Modified or valid (Need valid for secondary lookups) { try { if ((data == null) || (data.equals(Constants.BLANK))) { record.addNew(); // Clear the fields! } else { // This is a new record and this is the first mod boolean bSuccess = this.seek(record); // Read this record (display if found) if (!bSuccess) record.initRecord(bDisplayOption); // Clear the fields! } } catch (DBException e) { return e.getErrorCode(); // Never } finally { record.setKeyArea(strOldKeySeq); // Set the key order back } } return result; } } }
public class class_name { public int doSetData(Object data, boolean bDisplayOption, int iMoveMode) { if (!m_bReadOnly) { Object bookmark = null; BaseBuffer buffer = null; // In case a temp buffer is needed boolean bSuccess = false; Object oldBuff = this.getOwner().getData(); // Get a copy of the old key field Record record = this.getOwner().getRecord(); if (record.getEditMode() != Constants.EDIT_ADD) { // Current record (but no changes) - save the bookmark only for possible re-read. try { bookmark = record.getHandle(DBConstants.DATA_SOURCE_HANDLE); // depends on control dependency: [try], data = [none] } catch (DBException e) { bookmark = null; } // depends on control dependency: [catch], data = [none] } int result = super.doSetData(data, bDisplayOption, iMoveMode); // Do the rest of the behaviors if (result != DBConstants.NORMAL_RETURN) return result; // If error if ((!this.getOwner().isJustModified()) || (data == null)) return result; // If no change or set to null String iOldKeySeq = record.getKeyArea(-1).getKeyName(); record.setKeyArea(keyName); // depends on control dependency: [if], data = [none] if ((!record.isModified(true)) && ((record.getEditMode() == Constants.EDIT_ADD) || (record.getEditMode() == Constants.EDIT_NONE))) // Modified or valid record { // This is a new record and this is the first mod try { buffer = new VectorBuffer(null); // depends on control dependency: [try], data = [none] record.getKeyArea(keyName).setupKeyBuffer(buffer, DBConstants.FILE_KEY_AREA); // Save the keys // depends on control dependency: [try], data = [none] bSuccess = this.seek(record); // Read this record (display if found) // depends on control dependency: [try], data = [none] record.setKeyArea(iOldKeySeq); // Set the key order back // depends on control dependency: [try], data = [none] if (!bSuccess) { // Not found, restore the data and the new key record.addNew(); // This may wipe out the keys // depends on control dependency: [if], data = [none] if (buffer != null) buffer.resetPosition(); // Just to be careful record.getKeyArea(keyName).reverseKeyBuffer(buffer, DBConstants.FILE_KEY_AREA); // Restore the keys // depends on control dependency: [if], data = [none] result = DBConstants.NORMAL_RETURN; // Everything went okay // depends on control dependency: [if], data = [none] } else { // Record found - good if (record.getRecordOwner().isBatch()) { // Special case - Can't display this record return DBConstants.DUPLICATE_KEY; // depends on control dependency: [if], data = [none] } } } catch (DBException e) { return e.getErrorCode(); // Never } // depends on control dependency: [catch], data = [none] } else if (record.getKeyArea(keyName).getUniqueKeyCode() == DBConstants.UNIQUE) { // Data already entered, see if this entry makes a duplicate key! buffer = new VectorBuffer(null); // depends on control dependency: [if], data = [none] try { buffer.fieldsToBuffer(record, BaseBuffer.ALL_FIELDS); // Save the entire record // depends on control dependency: [try], data = [none] bSuccess = this.seek(record); // See if this key already exists // depends on control dependency: [try], data = [none] if (bookmark != null) { if (record.setHandle(bookmark, DBConstants.DATA_SOURCE_HANDLE) != null) // Set the pointer back to the old key record.edit(); else record.addNew(); // Never } else record.addNew();// This is a new record, and they entered non-key data already record.setKeyArea(iOldKeySeq); // Set the key order back // depends on control dependency: [try], data = [none] buffer.bufferToFields(record, DBConstants.DONT_DISPLAY, DBConstants.READ_MOVE); // Restore the data // depends on control dependency: [try], data = [none] for (int iFieldSeq = DBConstants.MAIN_FIELD; iFieldSeq < record.getFieldCount() + DBConstants.MAIN_FIELD; iFieldSeq++) { // Redisplay all the fields record.getField(iFieldSeq).displayField(); // depends on control dependency: [for], data = [iFieldSeq] } } catch (DBException e) { return e.getErrorCode(); // Never } // depends on control dependency: [catch], data = [none] if (bSuccess) { this.getOwner().setData(oldBuff, bDisplayOption, iMoveMode); // Restore a copy of the old key field // depends on control dependency: [if], data = [none] result = DBConstants.DUPLICATE_KEY; // Can't enter this key, you'll get a dup key! // depends on control dependency: [if], data = [none] } else result = DBConstants.NORMAL_RETURN; // Good, this is a valid key } return result; // depends on control dependency: [if], data = [none] } else { // Read only Record record = this.getOwner().getRecord(); int result = super.doSetData(data, bDisplayOption, iMoveMode); // Do the rest of the behaviors if (result != DBConstants.NORMAL_RETURN) return result; // If error or no change if (!this.getOwner().isJustModified()) return result; // If error or no change String strOldKeySeq = Constants.BLANK; strOldKeySeq = record.getKeyArea(-1).getKeyName(); // depends on control dependency: [if], data = [none] record.setKeyArea(keyName); // depends on control dependency: [if], data = [none] if (!record.isModified(true)) // Modified or valid (Need valid for secondary lookups) { try { if ((data == null) || (data.equals(Constants.BLANK))) { record.addNew(); // Clear the fields! // depends on control dependency: [if], data = [none] } else { // This is a new record and this is the first mod boolean bSuccess = this.seek(record); // Read this record (display if found) if (!bSuccess) record.initRecord(bDisplayOption); // Clear the fields! } } catch (DBException e) { return e.getErrorCode(); // Never } finally { // depends on control dependency: [catch], data = [none] record.setKeyArea(strOldKeySeq); // Set the key order back } } return result; // depends on control dependency: [if], data = [none] } } }
public class class_name { public final String getApiMessageId() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "getApiMessageId"); String value = null; /* The ApiMessageId is held as hexBinary & so we need to convert to an */ /* ID:xxxx format. */ byte[] binValue = (byte[]) getApi().getField(JsApiAccess.MESSAGEID); if (binValue != null) { /* It'll be more economical to get the length right immediately */ StringBuffer sbuf = new StringBuffer((binValue.length * 2) + 3); /* Insert the ID: then add on the binary value as a hex string */ sbuf.append(ID_STRING); HexString.binToHex(binValue, 0, binValue.length, sbuf); /* Return the String representation */ value = sbuf.toString(); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "getApiMessageId", value); return value; } }
public class class_name { public final String getApiMessageId() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "getApiMessageId"); String value = null; /* The ApiMessageId is held as hexBinary & so we need to convert to an */ /* ID:xxxx format. */ byte[] binValue = (byte[]) getApi().getField(JsApiAccess.MESSAGEID); if (binValue != null) { /* It'll be more economical to get the length right immediately */ StringBuffer sbuf = new StringBuffer((binValue.length * 2) + 3); /* Insert the ID: then add on the binary value as a hex string */ sbuf.append(ID_STRING); // depends on control dependency: [if], data = [none] HexString.binToHex(binValue, 0, binValue.length, sbuf); // depends on control dependency: [if], data = [(binValue] /* Return the String representation */ value = sbuf.toString(); // depends on control dependency: [if], data = [none] } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "getApiMessageId", value); return value; } }
public class class_name { public UOWCoordinator getUOWCoord() { if (tc.isEntryEnabled()) Tr.entry(tc, "getUOWCoord", this); UOWCoordinator uow = (UOWCoordinator)_coord; if (uow == null) { // see if there is a global tran ... if (_currentTM != null) { if (tc.isDebugEnabled()) Tr.debug(tc, "getting possible global transaction", _currentTM); try { uow = (UOWCoordinator) _currentTM.getTransaction(); } catch (SystemException se) { // No FFDC needed as our implementation will never throw exception } } } if (tc.isEntryEnabled()) Tr.exit(tc, "getUOWCoord", uow); return uow; } }
public class class_name { public UOWCoordinator getUOWCoord() { if (tc.isEntryEnabled()) Tr.entry(tc, "getUOWCoord", this); UOWCoordinator uow = (UOWCoordinator)_coord; if (uow == null) { // see if there is a global tran ... if (_currentTM != null) { if (tc.isDebugEnabled()) Tr.debug(tc, "getting possible global transaction", _currentTM); try { uow = (UOWCoordinator) _currentTM.getTransaction(); // depends on control dependency: [try], data = [none] } catch (SystemException se) { // No FFDC needed as our implementation will never throw exception } // depends on control dependency: [catch], data = [none] } } if (tc.isEntryEnabled()) Tr.exit(tc, "getUOWCoord", uow); return uow; } }
public class class_name { private ResourceGrant waitForJTGrant( ResourceTracker resourceTracker, SessionDriver sessionDriver, List<ResourceGrant> previousGrants) throws IOException, InterruptedException { LOG.info("Waiting for JT grant for " + attemptJobId); ResourceRequest req = resourceTracker.newJobTrackerRequest(); for (ResourceGrant prev: previousGrants) { LOG.info("Adding " + prev.getNodeName() + " to excluded hosts"); req.addToExcludeHosts(prev.getAddress().getHost()); } resourceTracker.recordRequest(req); List<ResourceRequest> newRequests = resourceTracker.getWantedResources(); sessionDriver.requestResources(newRequests); final List<ResourceGrant> grants = new ArrayList<ResourceGrant>(); ResourceTracker.ResourceProcessor proc = new ResourceTracker.ResourceProcessor() { @Override public boolean processAvailableResource(ResourceGrant resource) { grants.add(resource); final boolean consumed = true; return consumed; } }; while (true) { // Try to get JT grant while periodically checking for session driver // exceptions. long timeout = 60 * 1000; // 1 min. resourceTracker.processAvailableGrants(proc, 1, timeout); IOException e = sessionDriver.getFailed(); if (e != null) { throw e; } if (!grants.isEmpty()) { return grants.get(0); } } } }
public class class_name { private ResourceGrant waitForJTGrant( ResourceTracker resourceTracker, SessionDriver sessionDriver, List<ResourceGrant> previousGrants) throws IOException, InterruptedException { LOG.info("Waiting for JT grant for " + attemptJobId); ResourceRequest req = resourceTracker.newJobTrackerRequest(); for (ResourceGrant prev: previousGrants) { LOG.info("Adding " + prev.getNodeName() + " to excluded hosts"); req.addToExcludeHosts(prev.getAddress().getHost()); } resourceTracker.recordRequest(req); List<ResourceRequest> newRequests = resourceTracker.getWantedResources(); sessionDriver.requestResources(newRequests); final List<ResourceGrant> grants = new ArrayList<ResourceGrant>(); ResourceTracker.ResourceProcessor proc = new ResourceTracker.ResourceProcessor() { @Override public boolean processAvailableResource(ResourceGrant resource) { grants.add(resource); final boolean consumed = true; return consumed; } }; while (true) { // Try to get JT grant while periodically checking for session driver // exceptions. long timeout = 60 * 1000; // 1 min. resourceTracker.processAvailableGrants(proc, 1, timeout); IOException e = sessionDriver.getFailed(); if (e != null) { throw e; } if (!grants.isEmpty()) { return grants.get(0); // depends on control dependency: [if], data = [none] } } } }