code
stringlengths
130
281k
code_dependency
stringlengths
182
306k
public class class_name { ServerSessionManager registerConnection(String client, Connection connection) { ServerSessionContext session = clients.get(client); if (session != null) { session.setConnection(connection); } connections.put(client, connection); return this; } }
public class class_name { ServerSessionManager registerConnection(String client, Connection connection) { ServerSessionContext session = clients.get(client); if (session != null) { session.setConnection(connection); // depends on control dependency: [if], data = [none] } connections.put(client, connection); return this; } }
public class class_name { public void setTagOptions(java.util.Collection<TagOptionDetail> tagOptions) { if (tagOptions == null) { this.tagOptions = null; return; } this.tagOptions = new java.util.ArrayList<TagOptionDetail>(tagOptions); } }
public class class_name { public void setTagOptions(java.util.Collection<TagOptionDetail> tagOptions) { if (tagOptions == null) { this.tagOptions = null; // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } this.tagOptions = new java.util.ArrayList<TagOptionDetail>(tagOptions); } }
public class class_name { public void setResult(Object result) { if (resultSent) { throw new RuntimeException("You can only set the result once."); } this.resultSent = true; Channel channel = this.channel.get(); if (channel == null) { log.warn("The client is no longer connected."); return; } call.setResult(result); Invoke reply = new Invoke(); reply.setCall(call); reply.setTransactionId(transactionId); channel.write(reply); channel.getConnection().unregisterDeferredResult(this); } }
public class class_name { public void setResult(Object result) { if (resultSent) { throw new RuntimeException("You can only set the result once."); } this.resultSent = true; Channel channel = this.channel.get(); if (channel == null) { log.warn("The client is no longer connected."); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } call.setResult(result); Invoke reply = new Invoke(); reply.setCall(call); reply.setTransactionId(transactionId); channel.write(reply); channel.getConnection().unregisterDeferredResult(this); } }
public class class_name { public Set<String> getArtifactIds( String groupId ) { Entry parentEntry = backing.get( groupId.replace( '.', '/' ) ); if ( !( parentEntry instanceof DirectoryEntry ) ) { return Collections.emptySet(); } DirectoryEntry parentDir = (DirectoryEntry) parentEntry; Entry[] entries = backing.listEntries( parentDir ); Set<String> result = new HashSet<String>(); for ( int i = 0; i < entries.length; i++ ) { if ( entries[i] instanceof DirectoryEntry ) { result.add( entries[i].getName() ); } } return result; } }
public class class_name { public Set<String> getArtifactIds( String groupId ) { Entry parentEntry = backing.get( groupId.replace( '.', '/' ) ); if ( !( parentEntry instanceof DirectoryEntry ) ) { return Collections.emptySet(); // depends on control dependency: [if], data = [none] } DirectoryEntry parentDir = (DirectoryEntry) parentEntry; Entry[] entries = backing.listEntries( parentDir ); Set<String> result = new HashSet<String>(); for ( int i = 0; i < entries.length; i++ ) { if ( entries[i] instanceof DirectoryEntry ) { result.add( entries[i].getName() ); // depends on control dependency: [if], data = [none] } } return result; } }
public class class_name { protected void fireChange() { Object[] listeners = listenerList.getListenerList(); ChangeEvent event = new ChangeEvent(this); for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == ChangeListener.class) { ((ChangeListener)listeners[i + 1]).stateChanged(event); } } } }
public class class_name { protected void fireChange() { Object[] listeners = listenerList.getListenerList(); ChangeEvent event = new ChangeEvent(this); for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == ChangeListener.class) { ((ChangeListener)listeners[i + 1]).stateChanged(event); // depends on control dependency: [if], data = [none] } } } }
public class class_name { public JSONObject basicGeneral(byte[] image, HashMap<String, String> options) { AipRequest request = new AipRequest(); preOperation(request); String base64Content = Base64Util.encode(image); request.addBody("image", base64Content); if (options != null) { request.addBody(options); } request.setUri(OcrConsts.GENERAL_BASIC); postOperation(request); return requestServer(request); } }
public class class_name { public JSONObject basicGeneral(byte[] image, HashMap<String, String> options) { AipRequest request = new AipRequest(); preOperation(request); String base64Content = Base64Util.encode(image); request.addBody("image", base64Content); if (options != null) { request.addBody(options); // depends on control dependency: [if], data = [(options] } request.setUri(OcrConsts.GENERAL_BASIC); postOperation(request); return requestServer(request); } }
public class class_name { @Override public T addHandlers(ArchiveEventHandler... handlers) { for (ArchiveEventHandler handler : handlers) { this.handlers.add(handler); } return covariantReturn(); } }
public class class_name { @Override public T addHandlers(ArchiveEventHandler... handlers) { for (ArchiveEventHandler handler : handlers) { this.handlers.add(handler); // depends on control dependency: [for], data = [handler] } return covariantReturn(); } }
public class class_name { public String write(Geometry geometry) { try { JSONStringer b = new JSONStringer(); if (geometry.getClass().equals(GeometryCollection.class)) { writeFeatureCollection(b, (GeometryCollection) geometry); } else { writeFeature(b, geometry); } return b.toString(); } catch (JSONException e) { throw new GeoJsonException(e); } } }
public class class_name { public String write(Geometry geometry) { try { JSONStringer b = new JSONStringer(); if (geometry.getClass().equals(GeometryCollection.class)) { writeFeatureCollection(b, (GeometryCollection) geometry); // depends on control dependency: [if], data = [none] } else { writeFeature(b, geometry); // depends on control dependency: [if], data = [none] } return b.toString(); // depends on control dependency: [try], data = [none] } catch (JSONException e) { throw new GeoJsonException(e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public Response sendTransaction(Transaction transaction) throws PeerException { logger.debug("peer.sendTransaction"); // Send the transaction to the peer node via grpc // The rpc specification on the peer side is: // rpc ProcessTransaction(Transaction) returns (Response) {} Response response = peerClient.processTransaction(transaction.getTxBuilder().build()); if (response.getStatus() != Response.StatusCode.SUCCESS) { return response; } logger.debug(String.format("peer.sendTransaction: received %s", response.getMsg().toStringUtf8())); // Check transaction type here, as invoke is an asynchronous call, // whereas a deploy and a query are synchonous calls. As such, // invoke will emit 'submitted' and 'error', while a deploy/query // will emit 'complete' and 'error'. Fabric.Transaction.Type txType = transaction.getTxBuilder().getType(); switch (txType) { case CHAINCODE_DEPLOY: // async String txid = response.getMsg().toStringUtf8(); // Deploy transaction has been completed if (txid == null || txid.isEmpty()) { throw new ExecuteException("the deploy response is missing the transaction UUID"); } else if (!this.waitForDeployComplete(txid)) { throw new ExecuteException("the deploy request is submitted, but is not completed"); } else { return response; } case CHAINCODE_INVOKE: // async txid = response.getMsg().toStringUtf8(); // Invoke transaction has been submitted if (txid == null || txid.isEmpty()) { throw new ExecuteException("the invoke response is missing the transaction UUID"); } else if(!this.waitForInvokeComplete(txid)) { throw new ExecuteException("the invoke request is submitted, but is not completed"); } else { return response; } case CHAINCODE_QUERY: // sync return response; default: // not implemented throw new ExecuteException("processTransaction for this transaction type is not yet implemented!"); } } }
public class class_name { public Response sendTransaction(Transaction transaction) throws PeerException { logger.debug("peer.sendTransaction"); // Send the transaction to the peer node via grpc // The rpc specification on the peer side is: // rpc ProcessTransaction(Transaction) returns (Response) {} Response response = peerClient.processTransaction(transaction.getTxBuilder().build()); if (response.getStatus() != Response.StatusCode.SUCCESS) { return response; } logger.debug(String.format("peer.sendTransaction: received %s", response.getMsg().toStringUtf8())); // Check transaction type here, as invoke is an asynchronous call, // whereas a deploy and a query are synchonous calls. As such, // invoke will emit 'submitted' and 'error', while a deploy/query // will emit 'complete' and 'error'. Fabric.Transaction.Type txType = transaction.getTxBuilder().getType(); switch (txType) { case CHAINCODE_DEPLOY: // async String txid = response.getMsg().toStringUtf8(); // Deploy transaction has been completed if (txid == null || txid.isEmpty()) { throw new ExecuteException("the deploy response is missing the transaction UUID"); } else if (!this.waitForDeployComplete(txid)) { throw new ExecuteException("the deploy request is submitted, but is not completed"); } else { return response; // depends on control dependency: [if], data = [none] } case CHAINCODE_INVOKE: // async txid = response.getMsg().toStringUtf8(); // Invoke transaction has been submitted if (txid == null || txid.isEmpty()) { throw new ExecuteException("the invoke response is missing the transaction UUID"); } else if(!this.waitForInvokeComplete(txid)) { throw new ExecuteException("the invoke request is submitted, but is not completed"); } else { return response; // depends on control dependency: [if], data = [none] } case CHAINCODE_QUERY: // sync return response; default: // not implemented throw new ExecuteException("processTransaction for this transaction type is not yet implemented!"); } } }
public class class_name { public static String convert(String source, Charset srcCharset, Charset destCharset) { if(null == srcCharset) { srcCharset = StandardCharsets.ISO_8859_1; } if(null == destCharset) { destCharset = StandardCharsets.UTF_8; } if (StrUtil.isBlank(source) || srcCharset.equals(destCharset)) { return source; } return new String(source.getBytes(srcCharset), destCharset); } }
public class class_name { public static String convert(String source, Charset srcCharset, Charset destCharset) { if(null == srcCharset) { srcCharset = StandardCharsets.ISO_8859_1; // depends on control dependency: [if], data = [none] } if(null == destCharset) { destCharset = StandardCharsets.UTF_8; // depends on control dependency: [if], data = [none] } if (StrUtil.isBlank(source) || srcCharset.equals(destCharset)) { return source; // depends on control dependency: [if], data = [none] } return new String(source.getBytes(srcCharset), destCharset); } }
public class class_name { @Override protected Object doExec(Element element, Object scope, String propertyPath, Object... arguments) throws TemplateException { if (!propertyPath.equals(".") && ConverterRegistry.hasType(scope.getClass())) { throw new TemplateException("Operand is property path but scope is not an object."); } Object value = content.getObject(scope, propertyPath); if (value == null) { return null; } if (value instanceof URL) { value = ((URL) value).toExternalForm(); } if (!(value instanceof String)) { throw new TemplateException("Invalid element |%s|. HREF operand should be URL or string.", element); } return new AttrImpl("href", (String) value); } }
public class class_name { @Override protected Object doExec(Element element, Object scope, String propertyPath, Object... arguments) throws TemplateException { if (!propertyPath.equals(".") && ConverterRegistry.hasType(scope.getClass())) { throw new TemplateException("Operand is property path but scope is not an object."); } Object value = content.getObject(scope, propertyPath); if (value == null) { return null; // depends on control dependency: [if], data = [none] } if (value instanceof URL) { value = ((URL) value).toExternalForm(); // depends on control dependency: [if], data = [none] } if (!(value instanceof String)) { throw new TemplateException("Invalid element |%s|. HREF operand should be URL or string.", element); } return new AttrImpl("href", (String) value); } }
public class class_name { public void registerExecutor( String appId, String execId, ExecutorShuffleInfo executorInfo) { AppExecId fullId = new AppExecId(appId, execId); logger.info("Registered executor {} with {}", fullId, executorInfo); if (!knownManagers.contains(executorInfo.shuffleManager)) { throw new UnsupportedOperationException( "Unsupported shuffle manager of executor: " + executorInfo); } try { if (db != null) { byte[] key = dbAppExecKey(fullId); byte[] value = mapper.writeValueAsString(executorInfo).getBytes(StandardCharsets.UTF_8); db.put(key, value); } } catch (Exception e) { logger.error("Error saving registered executors", e); } executors.put(fullId, executorInfo); } }
public class class_name { public void registerExecutor( String appId, String execId, ExecutorShuffleInfo executorInfo) { AppExecId fullId = new AppExecId(appId, execId); logger.info("Registered executor {} with {}", fullId, executorInfo); if (!knownManagers.contains(executorInfo.shuffleManager)) { throw new UnsupportedOperationException( "Unsupported shuffle manager of executor: " + executorInfo); } try { if (db != null) { byte[] key = dbAppExecKey(fullId); byte[] value = mapper.writeValueAsString(executorInfo).getBytes(StandardCharsets.UTF_8); db.put(key, value); // depends on control dependency: [if], data = [none] } } catch (Exception e) { logger.error("Error saving registered executors", e); } // depends on control dependency: [catch], data = [none] executors.put(fullId, executorInfo); } }
public class class_name { private void handleEvent(XMLEvent event) { if(event.getEventType() == XMLStreamConstants.CHARACTERS) { Characters c = event.asCharacters(); lastContents += c.getData(); } else if(event.getEventType() == XMLStreamConstants.START_ELEMENT && isSpreadsheetTag(event.asStartElement().getName())) { StartElement startElement = event.asStartElement(); String tagLocalName = startElement.getName().getLocalPart(); if("row".equals(tagLocalName)) { Attribute rowNumAttr = startElement.getAttributeByName(new QName("r")); int rowIndex = currentRowNum; if(rowNumAttr != null) { rowIndex = Integer.parseInt(rowNumAttr.getValue()) - 1; currentRowNum = rowIndex; } Attribute isHiddenAttr = startElement.getAttributeByName(new QName("hidden")); boolean isHidden = isHiddenAttr != null && ("1".equals(isHiddenAttr.getValue()) || "true".equals(isHiddenAttr.getValue())); currentRow = new StreamingRow(rowIndex, isHidden); currentColNum = firstColNum; } else if("col".equals(tagLocalName)) { Attribute isHiddenAttr = startElement.getAttributeByName(new QName("hidden")); boolean isHidden = isHiddenAttr != null && ("1".equals(isHiddenAttr.getValue()) || "true".equals(isHiddenAttr.getValue())); if(isHidden) { Attribute minAttr = startElement.getAttributeByName(new QName("min")); Attribute maxAttr = startElement.getAttributeByName(new QName("max")); int min = Integer.parseInt(minAttr.getValue()) - 1; int max = Integer.parseInt(maxAttr.getValue()) - 1; for(int columnIndex = min; columnIndex <= max; columnIndex++) hiddenColumns.add(columnIndex); } } else if("c".equals(tagLocalName)) { Attribute ref = startElement.getAttributeByName(new QName("r")); if(ref != null) { String[] coord = splitCellRef(ref.getValue()); currentColNum = CellReference.convertColStringToIndex(coord[0]); currentCell = new StreamingCell(currentColNum, Integer.parseInt(coord[1]) - 1, use1904Dates); } else { currentCell = new StreamingCell(currentColNum, currentRowNum, use1904Dates); } setFormatString(startElement, currentCell); Attribute type = startElement.getAttributeByName(new QName("t")); if(type != null) { currentCell.setType(type.getValue()); } else { currentCell.setType("n"); } Attribute style = startElement.getAttributeByName(new QName("s")); if(style != null) { String indexStr = style.getValue(); try { int index = Integer.parseInt(indexStr); currentCell.setCellStyle(stylesTable.getStyleAt(index)); } catch(NumberFormatException nfe) { log.warn("Ignoring invalid style index {}", indexStr); } } else { currentCell.setCellStyle(stylesTable.getStyleAt(0)); } } else if("dimension".equals(tagLocalName)) { Attribute refAttr = startElement.getAttributeByName(new QName("ref")); String ref = refAttr != null ? refAttr.getValue() : null; if(ref != null) { // ref is formatted as A1 or A1:F25. Take the last numbers of this string and use it as lastRowNum for(int i = ref.length() - 1; i >= 0; i--) { if(!Character.isDigit(ref.charAt(i))) { try { lastRowNum = Integer.parseInt(ref.substring(i + 1)) - 1; } catch(NumberFormatException ignore) { } break; } } for(int i = 0; i < ref.length(); i++) { if(!Character.isAlphabetic(ref.charAt(i))) { firstColNum = CellReference.convertColStringToIndex(ref.substring(0, i)); break; } } } } else if("f".equals(tagLocalName)) { if (currentCell != null) { currentCell.setFormulaType(true); } } // Clear contents cache lastContents = ""; } else if(event.getEventType() == XMLStreamConstants.END_ELEMENT && isSpreadsheetTag(event.asEndElement().getName())) { EndElement endElement = event.asEndElement(); String tagLocalName = endElement.getName().getLocalPart(); if("v".equals(tagLocalName) || "t".equals(tagLocalName)) { currentCell.setRawContents(unformattedContents()); currentCell.setContentSupplier(formattedContents()); } else if("row".equals(tagLocalName) && currentRow != null) { rowCache.add(currentRow); currentRowNum++; } else if("c".equals(tagLocalName)) { currentRow.getCellMap().put(currentCell.getColumnIndex(), currentCell); currentCell = null; currentColNum++; } else if("f".equals(tagLocalName)) { if (currentCell != null) { currentCell.setFormula(lastContents); } } } } }
public class class_name { private void handleEvent(XMLEvent event) { if(event.getEventType() == XMLStreamConstants.CHARACTERS) { Characters c = event.asCharacters(); lastContents += c.getData(); // depends on control dependency: [if], data = [none] } else if(event.getEventType() == XMLStreamConstants.START_ELEMENT && isSpreadsheetTag(event.asStartElement().getName())) { StartElement startElement = event.asStartElement(); String tagLocalName = startElement.getName().getLocalPart(); if("row".equals(tagLocalName)) { Attribute rowNumAttr = startElement.getAttributeByName(new QName("r")); int rowIndex = currentRowNum; if(rowNumAttr != null) { rowIndex = Integer.parseInt(rowNumAttr.getValue()) - 1; // depends on control dependency: [if], data = [(rowNumAttr] currentRowNum = rowIndex; // depends on control dependency: [if], data = [none] } Attribute isHiddenAttr = startElement.getAttributeByName(new QName("hidden")); boolean isHidden = isHiddenAttr != null && ("1".equals(isHiddenAttr.getValue()) || "true".equals(isHiddenAttr.getValue())); currentRow = new StreamingRow(rowIndex, isHidden); // depends on control dependency: [if], data = [none] currentColNum = firstColNum; // depends on control dependency: [if], data = [none] } else if("col".equals(tagLocalName)) { Attribute isHiddenAttr = startElement.getAttributeByName(new QName("hidden")); boolean isHidden = isHiddenAttr != null && ("1".equals(isHiddenAttr.getValue()) || "true".equals(isHiddenAttr.getValue())); if(isHidden) { Attribute minAttr = startElement.getAttributeByName(new QName("min")); Attribute maxAttr = startElement.getAttributeByName(new QName("max")); int min = Integer.parseInt(minAttr.getValue()) - 1; int max = Integer.parseInt(maxAttr.getValue()) - 1; for(int columnIndex = min; columnIndex <= max; columnIndex++) hiddenColumns.add(columnIndex); } } else if("c".equals(tagLocalName)) { Attribute ref = startElement.getAttributeByName(new QName("r")); if(ref != null) { String[] coord = splitCellRef(ref.getValue()); currentColNum = CellReference.convertColStringToIndex(coord[0]); // depends on control dependency: [if], data = [none] currentCell = new StreamingCell(currentColNum, Integer.parseInt(coord[1]) - 1, use1904Dates); // depends on control dependency: [if], data = [none] } else { currentCell = new StreamingCell(currentColNum, currentRowNum, use1904Dates); // depends on control dependency: [if], data = [none] } setFormatString(startElement, currentCell); // depends on control dependency: [if], data = [none] Attribute type = startElement.getAttributeByName(new QName("t")); if(type != null) { currentCell.setType(type.getValue()); // depends on control dependency: [if], data = [(type] } else { currentCell.setType("n"); // depends on control dependency: [if], data = [none] } Attribute style = startElement.getAttributeByName(new QName("s")); if(style != null) { String indexStr = style.getValue(); try { int index = Integer.parseInt(indexStr); currentCell.setCellStyle(stylesTable.getStyleAt(index)); // depends on control dependency: [try], data = [none] } catch(NumberFormatException nfe) { log.warn("Ignoring invalid style index {}", indexStr); } // depends on control dependency: [catch], data = [none] } else { currentCell.setCellStyle(stylesTable.getStyleAt(0)); // depends on control dependency: [if], data = [(style] } } else if("dimension".equals(tagLocalName)) { Attribute refAttr = startElement.getAttributeByName(new QName("ref")); String ref = refAttr != null ? refAttr.getValue() : null; if(ref != null) { // ref is formatted as A1 or A1:F25. Take the last numbers of this string and use it as lastRowNum for(int i = ref.length() - 1; i >= 0; i--) { if(!Character.isDigit(ref.charAt(i))) { try { lastRowNum = Integer.parseInt(ref.substring(i + 1)) - 1; // depends on control dependency: [try], data = [none] } catch(NumberFormatException ignore) { } // depends on control dependency: [catch], data = [none] break; } } for(int i = 0; i < ref.length(); i++) { if(!Character.isAlphabetic(ref.charAt(i))) { firstColNum = CellReference.convertColStringToIndex(ref.substring(0, i)); // depends on control dependency: [if], data = [none] break; } } } } else if("f".equals(tagLocalName)) { if (currentCell != null) { currentCell.setFormulaType(true); // depends on control dependency: [if], data = [none] } } // Clear contents cache lastContents = ""; // depends on control dependency: [if], data = [none] } else if(event.getEventType() == XMLStreamConstants.END_ELEMENT && isSpreadsheetTag(event.asEndElement().getName())) { EndElement endElement = event.asEndElement(); String tagLocalName = endElement.getName().getLocalPart(); if("v".equals(tagLocalName) || "t".equals(tagLocalName)) { currentCell.setRawContents(unformattedContents()); // depends on control dependency: [if], data = [none] currentCell.setContentSupplier(formattedContents()); // depends on control dependency: [if], data = [none] } else if("row".equals(tagLocalName) && currentRow != null) { rowCache.add(currentRow); // depends on control dependency: [if], data = [none] currentRowNum++; // depends on control dependency: [if], data = [none] } else if("c".equals(tagLocalName)) { currentRow.getCellMap().put(currentCell.getColumnIndex(), currentCell); // depends on control dependency: [if], data = [none] currentCell = null; // depends on control dependency: [if], data = [none] currentColNum++; // depends on control dependency: [if], data = [none] } else if("f".equals(tagLocalName)) { if (currentCell != null) { currentCell.setFormula(lastContents); // depends on control dependency: [if], data = [none] } } } } }
public class class_name { @Nullable public static Node findNode(@NotNull final Node rootNode, @NotNull final XPath xPath, @NotNull final String expression) { Contract.requireArgNotNull("rootNode", rootNode); Contract.requireArgNotNull("xPath", xPath); Contract.requireArgNotNull("expression", expression); try { return (Node) xPath.compile(expression).evaluate(rootNode, XPathConstants.NODE); } catch (final XPathExpressionException ex) { throw new RuntimeException("Failed to read node: " + expression, ex); } } }
public class class_name { @Nullable public static Node findNode(@NotNull final Node rootNode, @NotNull final XPath xPath, @NotNull final String expression) { Contract.requireArgNotNull("rootNode", rootNode); Contract.requireArgNotNull("xPath", xPath); Contract.requireArgNotNull("expression", expression); try { return (Node) xPath.compile(expression).evaluate(rootNode, XPathConstants.NODE); // depends on control dependency: [try], data = [none] } catch (final XPathExpressionException ex) { throw new RuntimeException("Failed to read node: " + expression, ex); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public void marshall(ProjectStatus projectStatus, ProtocolMarshaller protocolMarshaller) { if (projectStatus == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(projectStatus.getState(), STATE_BINDING); protocolMarshaller.marshall(projectStatus.getReason(), REASON_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(ProjectStatus projectStatus, ProtocolMarshaller protocolMarshaller) { if (projectStatus == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(projectStatus.getState(), STATE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(projectStatus.getReason(), REASON_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 arrayCopy(ByteBuffer src, int srcPos, ByteBuffer dst, int dstPos, int length) { if (src.hasArray() && dst.hasArray()) { System.arraycopy(src.array(), src.arrayOffset() + srcPos, dst.array(), dst.arrayOffset() + dstPos, length); } else { if (src.limit() - srcPos < length || dst.limit() - dstPos < length) throw new IndexOutOfBoundsException(); for (int i = 0; i < length; i++) // TODO: ByteBuffer.put is polymorphic, and might be slow here dst.put(dstPos++, src.get(srcPos++)); } } }
public class class_name { public static void arrayCopy(ByteBuffer src, int srcPos, ByteBuffer dst, int dstPos, int length) { if (src.hasArray() && dst.hasArray()) { System.arraycopy(src.array(), src.arrayOffset() + srcPos, dst.array(), dst.arrayOffset() + dstPos, length); // depends on control dependency: [if], data = [none] } else { if (src.limit() - srcPos < length || dst.limit() - dstPos < length) throw new IndexOutOfBoundsException(); for (int i = 0; i < length; i++) // TODO: ByteBuffer.put is polymorphic, and might be slow here dst.put(dstPos++, src.get(srcPos++)); } } }
public class class_name { public static <T> T getLast(T[] objectArray) { if (ArrayIterate.notEmpty(objectArray)) { return objectArray[objectArray.length - 1]; } return null; } }
public class class_name { public static <T> T getLast(T[] objectArray) { if (ArrayIterate.notEmpty(objectArray)) { return objectArray[objectArray.length - 1]; // depends on control dependency: [if], data = [none] } return null; } }
public class class_name { public static int getPackedPositionType(final long packedPosition) { if (packedPosition == PACKED_POSITION_VALUE_NULL) { return PACKED_POSITION_TYPE_NULL; } return (packedPosition & PACKED_POSITION_MASK_TYPE) == PACKED_POSITION_MASK_TYPE ? PACKED_POSITION_TYPE_CHILD : PACKED_POSITION_TYPE_GROUP; } }
public class class_name { public static int getPackedPositionType(final long packedPosition) { if (packedPosition == PACKED_POSITION_VALUE_NULL) { return PACKED_POSITION_TYPE_NULL; // depends on control dependency: [if], data = [none] } return (packedPosition & PACKED_POSITION_MASK_TYPE) == PACKED_POSITION_MASK_TYPE ? PACKED_POSITION_TYPE_CHILD : PACKED_POSITION_TYPE_GROUP; } }
public class class_name { protected void handleComputeFields(int julianDay) { long d = julianDay - 347997; long m = (d * DAY_PARTS) / MONTH_PARTS; // Months (approx) int year = (int)((19 * m + 234) / 235) + 1; // Years (approx) long ys = startOfYear(year); // 1st day of year int dayOfYear = (int)(d - ys); // Because of the postponement rules, it's possible to guess wrong. Fix it. while (dayOfYear < 1) { year--; ys = startOfYear(year); dayOfYear = (int)(d - ys); } // Now figure out which month we're in, and the date within that month int yearType = yearType(year); int monthStart[][] = isLeapYear(year) ? LEAP_MONTH_START : MONTH_START; int month = 0; while (dayOfYear > monthStart[month][yearType]) { month++; } month--; int dayOfMonth = dayOfYear - monthStart[month][yearType]; internalSet(ERA, 0); internalSet(YEAR, year); internalSet(EXTENDED_YEAR, year); internalSet(MONTH, month); internalSet(DAY_OF_MONTH, dayOfMonth); internalSet(DAY_OF_YEAR, dayOfYear); } }
public class class_name { protected void handleComputeFields(int julianDay) { long d = julianDay - 347997; long m = (d * DAY_PARTS) / MONTH_PARTS; // Months (approx) int year = (int)((19 * m + 234) / 235) + 1; // Years (approx) long ys = startOfYear(year); // 1st day of year int dayOfYear = (int)(d - ys); // Because of the postponement rules, it's possible to guess wrong. Fix it. while (dayOfYear < 1) { year--; // depends on control dependency: [while], data = [none] ys = startOfYear(year); // depends on control dependency: [while], data = [none] dayOfYear = (int)(d - ys); // depends on control dependency: [while], data = [none] } // Now figure out which month we're in, and the date within that month int yearType = yearType(year); int monthStart[][] = isLeapYear(year) ? LEAP_MONTH_START : MONTH_START; int month = 0; while (dayOfYear > monthStart[month][yearType]) { month++; // depends on control dependency: [while], data = [none] } month--; int dayOfMonth = dayOfYear - monthStart[month][yearType]; internalSet(ERA, 0); internalSet(YEAR, year); internalSet(EXTENDED_YEAR, year); internalSet(MONTH, month); internalSet(DAY_OF_MONTH, dayOfMonth); internalSet(DAY_OF_YEAR, dayOfYear); } }
public class class_name { private void associateF2F() { quadViews.reset(); for( int i = 0; i < detector.getNumberOfSets(); i++ ) { SetMatches matches = setMatches[i]; // old left to new left assocSame.setSource(featsLeft0.location[i],featsLeft0.description[i]); assocSame.setDestination(featsLeft1.location[i], featsLeft1.description[i]); assocSame.associate(); setMatches(matches.match0to2, assocSame.getMatches(), featsLeft0.location[i].size); // old right to new right assocSame.setSource(featsRight0.location[i],featsRight0.description[i]); assocSame.setDestination(featsRight1.location[i], featsRight1.description[i]); assocSame.associate(); setMatches(matches.match1to3, assocSame.getMatches(), featsRight0.location[i].size); } } }
public class class_name { private void associateF2F() { quadViews.reset(); for( int i = 0; i < detector.getNumberOfSets(); i++ ) { SetMatches matches = setMatches[i]; // old left to new left assocSame.setSource(featsLeft0.location[i],featsLeft0.description[i]); // depends on control dependency: [for], data = [i] assocSame.setDestination(featsLeft1.location[i], featsLeft1.description[i]); // depends on control dependency: [for], data = [i] assocSame.associate(); // depends on control dependency: [for], data = [none] setMatches(matches.match0to2, assocSame.getMatches(), featsLeft0.location[i].size); // depends on control dependency: [for], data = [i] // old right to new right assocSame.setSource(featsRight0.location[i],featsRight0.description[i]); // depends on control dependency: [for], data = [i] assocSame.setDestination(featsRight1.location[i], featsRight1.description[i]); // depends on control dependency: [for], data = [i] assocSame.associate(); // depends on control dependency: [for], data = [none] setMatches(matches.match1to3, assocSame.getMatches(), featsRight0.location[i].size); // depends on control dependency: [for], data = [i] } } }
public class class_name { private boolean hasSelectedChildren(CmsTreeItem item) { for (String childId : m_childrens.get(item.getId())) { CmsTreeItem child = m_categories.get(childId); if (child.getCheckBox().isChecked() || hasSelectedChildren(child)) { return true; } } return false; } }
public class class_name { private boolean hasSelectedChildren(CmsTreeItem item) { for (String childId : m_childrens.get(item.getId())) { CmsTreeItem child = m_categories.get(childId); if (child.getCheckBox().isChecked() || hasSelectedChildren(child)) { return true; // depends on control dependency: [if], data = [none] } } return false; } }
public class class_name { public void setAsText(final String text) { StringTokenizer stok = new StringTokenizer(text, ",\r\n"); int[] theValue = new int[stok.countTokens()]; int i = 0; while (stok.hasMoreTokens()) { theValue[i++] = Integer.decode(stok.nextToken()).intValue(); } setValue(theValue); } }
public class class_name { public void setAsText(final String text) { StringTokenizer stok = new StringTokenizer(text, ",\r\n"); int[] theValue = new int[stok.countTokens()]; int i = 0; while (stok.hasMoreTokens()) { theValue[i++] = Integer.decode(stok.nextToken()).intValue(); // depends on control dependency: [while], data = [none] } setValue(theValue); } }
public class class_name { public void addChildren( AstNode first, AstNode second ) { if (first != null) { this.addLastChild(first); } if (second != null) { this.addLastChild(second); } } }
public class class_name { public void addChildren( AstNode first, AstNode second ) { if (first != null) { this.addLastChild(first); // depends on control dependency: [if], data = [(first] } if (second != null) { this.addLastChild(second); // depends on control dependency: [if], data = [(second] } } }
public class class_name { protected void fireReleased(Command command) { getState(command).down = false; if (!isActive()) { return; } for (int i = 0; i < listeners.size(); i++) { ((InputProviderListener) listeners.get(i)).controlReleased(command); } } }
public class class_name { protected void fireReleased(Command command) { getState(command).down = false; if (!isActive()) { return; // depends on control dependency: [if], data = [none] } for (int i = 0; i < listeners.size(); i++) { ((InputProviderListener) listeners.get(i)).controlReleased(command); // depends on control dependency: [for], data = [i] } } }
public class class_name { private Component createImageButton() { CssLayout layout = new CssLayout(); layout.addStyleName(OpenCmsTheme.USER_IMAGE); Image userImage = new Image(); userImage.setSource( new ExternalResource( OpenCms.getWorkplaceAppManager().getUserIconHelper().getBigIconPath(A_CmsUI.getCmsObject(), m_user))); layout.addComponent(userImage); if (!CmsAppWorkplaceUi.isOnlineProject() & (m_uploadListener != null)) { CmsUploadButton uploadButton = createImageUploadButton( null, FontOpenCms.UPLOAD_SMALL, m_user, m_uploadListener); layout.addComponent(uploadButton); if (CmsUserIconHelper.hasUserImage(m_user)) { Button deleteButton = new Button(FontOpenCms.TRASH_SMALL); deleteButton.addClickListener(new ClickListener() { private static final long serialVersionUID = 1L; public void buttonClick(ClickEvent event) { OpenCms.getWorkplaceAppManager().getUserIconHelper().deleteUserImage(A_CmsUI.getCmsObject()); m_context.updateUserInfo(); } }); layout.addComponent(deleteButton); } } return layout; } }
public class class_name { private Component createImageButton() { CssLayout layout = new CssLayout(); layout.addStyleName(OpenCmsTheme.USER_IMAGE); Image userImage = new Image(); userImage.setSource( new ExternalResource( OpenCms.getWorkplaceAppManager().getUserIconHelper().getBigIconPath(A_CmsUI.getCmsObject(), m_user))); layout.addComponent(userImage); if (!CmsAppWorkplaceUi.isOnlineProject() & (m_uploadListener != null)) { CmsUploadButton uploadButton = createImageUploadButton( null, FontOpenCms.UPLOAD_SMALL, m_user, m_uploadListener); layout.addComponent(uploadButton); // depends on control dependency: [if], data = [none] if (CmsUserIconHelper.hasUserImage(m_user)) { Button deleteButton = new Button(FontOpenCms.TRASH_SMALL); deleteButton.addClickListener(new ClickListener() { private static final long serialVersionUID = 1L; public void buttonClick(ClickEvent event) { OpenCms.getWorkplaceAppManager().getUserIconHelper().deleteUserImage(A_CmsUI.getCmsObject()); m_context.updateUserInfo(); } }); // depends on control dependency: [if], data = [none] layout.addComponent(deleteButton); // depends on control dependency: [if], data = [none] } } return layout; } }
public class class_name { @Override public boolean releasePeerLease(String recoveryIdentity) throws Exception { if (tc.isEntryEnabled()) Tr.entry(tc, "releasePeerLease", new Object[] { recoveryIdentity, this }); // Release the lock - if it is not null! FileLock fLock = null; FileChannel fChannel = null; if (_peerLeaseLock != null) { String recIdentity = _peerLeaseLock.getRecoveryIdentity(); if (recoveryIdentity.equals(recIdentity)) { fLock = _peerLeaseLock.getFileLock(); if (fLock != null) { fLock.release(); } // Close the channel fChannel = _peerLeaseLock.getFileChannel(); if (fChannel != null) fChannel.close(); _peerLeaseLock = null; } else { if (tc.isDebugEnabled()) Tr.debug(tc, "The locks identity which was " + recIdentity + " did not match the requested identity which was " + recoveryIdentity); } } else { if (tc.isDebugEnabled()) Tr.debug(tc, "The lease lock was unexpectedly null"); } if (tc.isEntryEnabled()) Tr.exit(tc, "releasePeerLease"); return true; } }
public class class_name { @Override public boolean releasePeerLease(String recoveryIdentity) throws Exception { if (tc.isEntryEnabled()) Tr.entry(tc, "releasePeerLease", new Object[] { recoveryIdentity, this }); // Release the lock - if it is not null! FileLock fLock = null; FileChannel fChannel = null; if (_peerLeaseLock != null) { String recIdentity = _peerLeaseLock.getRecoveryIdentity(); if (recoveryIdentity.equals(recIdentity)) { fLock = _peerLeaseLock.getFileLock(); // depends on control dependency: [if], data = [none] if (fLock != null) { fLock.release(); // depends on control dependency: [if], data = [none] } // Close the channel fChannel = _peerLeaseLock.getFileChannel(); // depends on control dependency: [if], data = [none] if (fChannel != null) fChannel.close(); _peerLeaseLock = null; // depends on control dependency: [if], data = [none] } else { if (tc.isDebugEnabled()) Tr.debug(tc, "The locks identity which was " + recIdentity + " did not match the requested identity which was " + recoveryIdentity); } } else { if (tc.isDebugEnabled()) Tr.debug(tc, "The lease lock was unexpectedly null"); } if (tc.isEntryEnabled()) Tr.exit(tc, "releasePeerLease"); return true; } }
public class class_name { private void addFilters(MpxjTreeNode parentNode, List<Filter> filters) { for (Filter field : filters) { final Filter f = field; MpxjTreeNode childNode = new MpxjTreeNode(field) { @Override public String toString() { return f.getName(); } }; parentNode.add(childNode); } } }
public class class_name { private void addFilters(MpxjTreeNode parentNode, List<Filter> filters) { for (Filter field : filters) { final Filter f = field; MpxjTreeNode childNode = new MpxjTreeNode(field) { @Override public String toString() { return f.getName(); } }; parentNode.add(childNode); // depends on control dependency: [for], data = [none] } } }
public class class_name { public void setLabel(String label) { this.label.setText(label); if (!getPlaceholder().isEmpty()) { this.label.setStyleName(CssName.ACTIVE); } } }
public class class_name { public void setLabel(String label) { this.label.setText(label); if (!getPlaceholder().isEmpty()) { this.label.setStyleName(CssName.ACTIVE); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static ByteBuffer putPaddedInt32AsString(ByteBuffer buffer, int value, int length) { // Ensure there is sufficient space in the buffer to hold the result. int charsRequired = BitHackUtils.getCharacterCountInt32(value); length = (charsRequired < length) ? length : charsRequired; // Take an explicit index into the buffer to start writing to, as the numbers will be written backwards. int index = buffer.position() + length - 1; // Record the start position, to remember if a minus sign was written or not, so that it does not get // overwritten by the zero padding. int start = buffer.position(); // Advance the buffer position manually, as the characters will be written to specific indexes backwards. buffer.position(buffer.position() + length); // Take care of the minus sign for negative numbers. if (value < 0) { buffer.put(MINUS_ASCII); start++; // Stop padding code overwriting minus sign. } else { value = -value; } // Write the digits least significant to most significant into the buffer. As the number was converted to be // negative the remainders will be negative too. do { int remainder = value % 10; value = value / 10; buffer.put(index--, ((byte) (ZERO_ASCII - remainder))); } while (value != 0); // Write out the padding zeros. while (index >= start) { buffer.put(index--, ZERO_ASCII); } return buffer; } }
public class class_name { public static ByteBuffer putPaddedInt32AsString(ByteBuffer buffer, int value, int length) { // Ensure there is sufficient space in the buffer to hold the result. int charsRequired = BitHackUtils.getCharacterCountInt32(value); length = (charsRequired < length) ? length : charsRequired; // Take an explicit index into the buffer to start writing to, as the numbers will be written backwards. int index = buffer.position() + length - 1; // Record the start position, to remember if a minus sign was written or not, so that it does not get // overwritten by the zero padding. int start = buffer.position(); // Advance the buffer position manually, as the characters will be written to specific indexes backwards. buffer.position(buffer.position() + length); // Take care of the minus sign for negative numbers. if (value < 0) { buffer.put(MINUS_ASCII); // depends on control dependency: [if], data = [none] start++; // Stop padding code overwriting minus sign. // depends on control dependency: [if], data = [none] } else { value = -value; // depends on control dependency: [if], data = [none] } // Write the digits least significant to most significant into the buffer. As the number was converted to be // negative the remainders will be negative too. do { int remainder = value % 10; value = value / 10; buffer.put(index--, ((byte) (ZERO_ASCII - remainder))); } while (value != 0); // Write out the padding zeros. while (index >= start) { buffer.put(index--, ZERO_ASCII); // depends on control dependency: [while], data = [(index] } return buffer; } }
public class class_name { public static String ticket(String key, String type) { if (isKeyParam(key)) { String[] keys = key.split(KEY_JOIN); if (keys.length == 2) { return apiHandler.ticket(keys[0], keys[1], type); } else if (keys.length == 1) { return apiHandler.ticket(keys[0], type); } } return key; } }
public class class_name { public static String ticket(String key, String type) { if (isKeyParam(key)) { String[] keys = key.split(KEY_JOIN); if (keys.length == 2) { return apiHandler.ticket(keys[0], keys[1], type); // depends on control dependency: [if], data = [none] } else if (keys.length == 1) { return apiHandler.ticket(keys[0], type); // depends on control dependency: [if], data = [none] } } return key; } }
public class class_name { public static void set_value(final Object[] valueArray, final Attribute attribute, final int dimX, final int dimY) throws DevFailed { if (valueArray.length > 0 && dimX == 1 && dimY == 0) { AttributeHelper.set_value(valueArray[0], attribute); } else if (valueArray.length > 1) { final Object value = valueArray[0]; if (value instanceof Short) { final short[] shortValues = new short[valueArray.length]; for (int i = 0; i < valueArray.length; i++) { shortValues[i] = ((Short) valueArray[i]).shortValue(); } if (dimY == 0) { attribute.set_value(shortValues, shortValues.length); } if (dimY > 0) { attribute.set_value(shortValues, shortValues.length / dimY, dimY); } } else if (value instanceof String) { final String[] stringValues = new String[valueArray.length]; for (int i = 0; i < valueArray.length; i++) { stringValues[i] = (String) valueArray[i]; } if (dimY == 0) { attribute.set_value(stringValues, stringValues.length); } if (dimY > 0) { attribute.set_value(stringValues, stringValues.length - dimY, dimY); } } else if (value instanceof Integer) { final int[] intValues = new int[valueArray.length]; for (int i = 0; i < valueArray.length; i++) { intValues[i] = ((Integer) valueArray[i]).intValue(); } if (dimY == 0) { attribute.set_value(intValues, intValues.length); } if (dimY > 0) { attribute.set_value(intValues, intValues.length / dimY, dimY); } } else if (value instanceof Long) { final long[] longValues = new long[valueArray.length]; for (int i = 0; i < valueArray.length; i++) { longValues[i] = ((Long) valueArray[i]).longValue(); } if (dimY == 0) { attribute.set_value(longValues, longValues.length); } if (dimY > 0) { attribute.set_value(longValues, longValues.length / dimY, dimY); } } else if (value instanceof Float) { final double[] floatValues = new double[valueArray.length]; for (int i = 0; i < valueArray.length; i++) { floatValues[i] = ((Float) valueArray[i]).doubleValue(); } if (dimY == 0) { attribute.set_value(floatValues, floatValues.length); } if (dimY > 0) { attribute.set_value(floatValues, floatValues.length / dimY, dimY); } } else if (value instanceof Boolean) { final boolean[] booleanValues = new boolean[valueArray.length]; for (int i = 0; i < valueArray.length; i++) { booleanValues[i] = ((Boolean) valueArray[i]).booleanValue(); } if (dimY == 0) { attribute.set_value(booleanValues, booleanValues.length); } if (dimY > 0) { attribute.set_value(booleanValues, booleanValues.length - dimY, dimY); } } else if (value instanceof Double) { final double[] doubleValues = new double[valueArray.length]; for (int i = 0; i < valueArray.length; i++) { doubleValues[i] = ((Double) valueArray[i]).doubleValue(); } if (dimY == 0) { attribute.set_value(doubleValues, doubleValues.length); } if (dimY > 0) { attribute.set_value(doubleValues, doubleValues.length / dimY, dimY); } } else if (value instanceof Byte) { final short[] byteValues = new short[valueArray.length]; for (int i = 0; i < valueArray.length; i++) { byteValues[i] = ((Byte) valueArray[i]).shortValue(); } if (dimY == 0) { attribute.set_value(byteValues, byteValues.length); } if (dimY > 0) { attribute.set_value(byteValues, byteValues.length / dimY, dimY); } } else if (value instanceof DevState) { final DevState[] devStateValues = new DevState[valueArray.length]; for (int i = 0; i < valueArray.length; i++) { devStateValues[i] = (DevState) valueArray[i]; } if (dimY == 0) { attribute.set_value(devStateValues, devStateValues.length); } if (dimY > 0) { attribute.set_value(devStateValues, devStateValues.length / dimY, dimY); } } else { Except.throw_exception("TANGO_WRONG_DATA_ERROR", "input type " + value.getClass() + " not supported", "AttributeHelper.insert(Object value,deviceAttributeWritten)"); } } } }
public class class_name { public static void set_value(final Object[] valueArray, final Attribute attribute, final int dimX, final int dimY) throws DevFailed { if (valueArray.length > 0 && dimX == 1 && dimY == 0) { AttributeHelper.set_value(valueArray[0], attribute); } else if (valueArray.length > 1) { final Object value = valueArray[0]; if (value instanceof Short) { final short[] shortValues = new short[valueArray.length]; for (int i = 0; i < valueArray.length; i++) { shortValues[i] = ((Short) valueArray[i]).shortValue(); // depends on control dependency: [for], data = [i] } if (dimY == 0) { attribute.set_value(shortValues, shortValues.length); // depends on control dependency: [if], data = [none] } if (dimY > 0) { attribute.set_value(shortValues, shortValues.length / dimY, dimY); // depends on control dependency: [if], data = [none] } } else if (value instanceof String) { final String[] stringValues = new String[valueArray.length]; for (int i = 0; i < valueArray.length; i++) { stringValues[i] = (String) valueArray[i]; // depends on control dependency: [for], data = [i] } if (dimY == 0) { attribute.set_value(stringValues, stringValues.length); // depends on control dependency: [if], data = [none] } if (dimY > 0) { attribute.set_value(stringValues, stringValues.length - dimY, dimY); // depends on control dependency: [if], data = [none] } } else if (value instanceof Integer) { final int[] intValues = new int[valueArray.length]; for (int i = 0; i < valueArray.length; i++) { intValues[i] = ((Integer) valueArray[i]).intValue(); // depends on control dependency: [for], data = [i] } if (dimY == 0) { attribute.set_value(intValues, intValues.length); // depends on control dependency: [if], data = [none] } if (dimY > 0) { attribute.set_value(intValues, intValues.length / dimY, dimY); // depends on control dependency: [if], data = [none] } } else if (value instanceof Long) { final long[] longValues = new long[valueArray.length]; for (int i = 0; i < valueArray.length; i++) { longValues[i] = ((Long) valueArray[i]).longValue(); // depends on control dependency: [for], data = [i] } if (dimY == 0) { attribute.set_value(longValues, longValues.length); // depends on control dependency: [if], data = [none] } if (dimY > 0) { attribute.set_value(longValues, longValues.length / dimY, dimY); // depends on control dependency: [if], data = [none] } } else if (value instanceof Float) { final double[] floatValues = new double[valueArray.length]; for (int i = 0; i < valueArray.length; i++) { floatValues[i] = ((Float) valueArray[i]).doubleValue(); // depends on control dependency: [for], data = [i] } if (dimY == 0) { attribute.set_value(floatValues, floatValues.length); // depends on control dependency: [if], data = [none] } if (dimY > 0) { attribute.set_value(floatValues, floatValues.length / dimY, dimY); // depends on control dependency: [if], data = [none] } } else if (value instanceof Boolean) { final boolean[] booleanValues = new boolean[valueArray.length]; for (int i = 0; i < valueArray.length; i++) { booleanValues[i] = ((Boolean) valueArray[i]).booleanValue(); // depends on control dependency: [for], data = [i] } if (dimY == 0) { attribute.set_value(booleanValues, booleanValues.length); // depends on control dependency: [if], data = [none] } if (dimY > 0) { attribute.set_value(booleanValues, booleanValues.length - dimY, dimY); // depends on control dependency: [if], data = [none] } } else if (value instanceof Double) { final double[] doubleValues = new double[valueArray.length]; for (int i = 0; i < valueArray.length; i++) { doubleValues[i] = ((Double) valueArray[i]).doubleValue(); // depends on control dependency: [for], data = [i] } if (dimY == 0) { attribute.set_value(doubleValues, doubleValues.length); // depends on control dependency: [if], data = [none] } if (dimY > 0) { attribute.set_value(doubleValues, doubleValues.length / dimY, dimY); // depends on control dependency: [if], data = [none] } } else if (value instanceof Byte) { final short[] byteValues = new short[valueArray.length]; for (int i = 0; i < valueArray.length; i++) { byteValues[i] = ((Byte) valueArray[i]).shortValue(); // depends on control dependency: [for], data = [i] } if (dimY == 0) { attribute.set_value(byteValues, byteValues.length); // depends on control dependency: [if], data = [none] } if (dimY > 0) { attribute.set_value(byteValues, byteValues.length / dimY, dimY); // depends on control dependency: [if], data = [none] } } else if (value instanceof DevState) { final DevState[] devStateValues = new DevState[valueArray.length]; for (int i = 0; i < valueArray.length; i++) { devStateValues[i] = (DevState) valueArray[i]; // depends on control dependency: [for], data = [i] } if (dimY == 0) { attribute.set_value(devStateValues, devStateValues.length); // depends on control dependency: [if], data = [none] } if (dimY > 0) { attribute.set_value(devStateValues, devStateValues.length / dimY, dimY); // depends on control dependency: [if], data = [none] } } else { Except.throw_exception("TANGO_WRONG_DATA_ERROR", "input type " + value.getClass() + " not supported", "AttributeHelper.insert(Object value,deviceAttributeWritten)"); // depends on control dependency: [if], data = [none] } } } }
public class class_name { private void accumulateNormal(final Element center, final Element pre, final Element post) { double cx = center.getDouble("x"); double cy = center.getDouble("y"); double cz = center.getDouble("z"); double ax = post.getDouble("x") - cx; double ay = post.getDouble("y") - cy; double az = post.getDouble("z") - cz; double a = Math.sqrt(ax * ax + ay * ay + az * az); if (a < EPSILON) { return; } double bx = pre.getDouble("x") - cx; double by = pre.getDouble("y") - cy; double bz = pre.getDouble("z") - cz; double b = Math.sqrt(bx * bx + by * by + bz * bz); if (b < EPSILON) { return; } double nx = ay * bz - az * by; double ny = az * bx - ax * bz; double nz = ax * by - ay * bx; double n = Math.sqrt(nx * nx + ny * ny + nz * nz); if (n < EPSILON) { return; } double sin = n / (a * b); double dot = ax * bx + ay * by + az * bz; double angle; if (dot < 0) { angle = Math.PI - Math.asin(sin); } else { angle = Math.asin(sin); } double factor = angle / n; nx *= factor; ny *= factor; nz *= factor; center.setDouble("nx", center.getDouble("nx") + nx); center.setDouble("ny", center.getDouble("ny") + ny); center.setDouble("nz", center.getDouble("nz") + nz); } }
public class class_name { private void accumulateNormal(final Element center, final Element pre, final Element post) { double cx = center.getDouble("x"); double cy = center.getDouble("y"); double cz = center.getDouble("z"); double ax = post.getDouble("x") - cx; double ay = post.getDouble("y") - cy; double az = post.getDouble("z") - cz; double a = Math.sqrt(ax * ax + ay * ay + az * az); if (a < EPSILON) { return; // depends on control dependency: [if], data = [none] } double bx = pre.getDouble("x") - cx; double by = pre.getDouble("y") - cy; double bz = pre.getDouble("z") - cz; double b = Math.sqrt(bx * bx + by * by + bz * bz); if (b < EPSILON) { return; // depends on control dependency: [if], data = [none] } double nx = ay * bz - az * by; double ny = az * bx - ax * bz; double nz = ax * by - ay * bx; double n = Math.sqrt(nx * nx + ny * ny + nz * nz); if (n < EPSILON) { return; // depends on control dependency: [if], data = [none] } double sin = n / (a * b); double dot = ax * bx + ay * by + az * bz; double angle; if (dot < 0) { angle = Math.PI - Math.asin(sin); // depends on control dependency: [if], data = [none] } else { angle = Math.asin(sin); // depends on control dependency: [if], data = [none] } double factor = angle / n; nx *= factor; ny *= factor; nz *= factor; center.setDouble("nx", center.getDouble("nx") + nx); center.setDouble("ny", center.getDouble("ny") + ny); center.setDouble("nz", center.getDouble("nz") + nz); } }
public class class_name { public static Color randomColor(Random random) { if (null == random) { random = RandomUtil.getRandom(); } return new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)); } }
public class class_name { public static Color randomColor(Random random) { if (null == random) { random = RandomUtil.getRandom(); // depends on control dependency: [if], data = [none] } return new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)); } }
public class class_name { private void adaptDividerMargin(@Nullable final Divider divider) { if (divider != null) { ViewGroup.LayoutParams layoutParams = divider.getLayoutParams(); if (layoutParams instanceof LayoutParams) { ((LayoutParams) layoutParams).leftMargin = dividerMargin; ((LayoutParams) layoutParams).rightMargin = dividerMargin; } } } }
public class class_name { private void adaptDividerMargin(@Nullable final Divider divider) { if (divider != null) { ViewGroup.LayoutParams layoutParams = divider.getLayoutParams(); if (layoutParams instanceof LayoutParams) { ((LayoutParams) layoutParams).leftMargin = dividerMargin; // depends on control dependency: [if], data = [none] ((LayoutParams) layoutParams).rightMargin = dividerMargin; // depends on control dependency: [if], data = [none] } } } }
public class class_name { public Optional<Sense> getSense(@NonNull String word, @NonNull POS pos, int senseNum, @NonNull Language language) { for (String lemma : Lemmatizers .getLemmatizer(language) .allPossibleLemmas(word, pos)) { for (Sense sense : db.getSenses(lemma.toLowerCase())) { if ((pos == POS.ANY || pos.isInstance( sense.getPOS())) && sense.getSenseNumber() == senseNum && sense.getLanguage() == language) { return Optional.of(sense); } } } return Optional.empty(); } }
public class class_name { public Optional<Sense> getSense(@NonNull String word, @NonNull POS pos, int senseNum, @NonNull Language language) { for (String lemma : Lemmatizers .getLemmatizer(language) .allPossibleLemmas(word, pos)) { for (Sense sense : db.getSenses(lemma.toLowerCase())) { if ((pos == POS.ANY || pos.isInstance( sense.getPOS())) && sense.getSenseNumber() == senseNum && sense.getLanguage() == language) { return Optional.of(sense); // depends on control dependency: [if], data = [none] } } } return Optional.empty(); } }
public class class_name { public static void cursorDoubleToContentValuesIfPresent(Cursor cursor, ContentValues values, String column) { final int index = cursor.getColumnIndex(column); if (index != -1 && !cursor.isNull(index)) { values.put(column, cursor.getDouble(index)); } } }
public class class_name { public static void cursorDoubleToContentValuesIfPresent(Cursor cursor, ContentValues values, String column) { final int index = cursor.getColumnIndex(column); if (index != -1 && !cursor.isNull(index)) { values.put(column, cursor.getDouble(index)); // depends on control dependency: [if], data = [(index] } } }
public class class_name { public static NaryTreebank readTreesInPtbFormat(Reader reader) throws IOException { NaryTreebank trees = new NaryTreebank(); while (true) { NaryTree tree = NaryTree.readTreeInPtbFormat(reader); if (tree != null) { tree.intern(); trees.add(tree); } if (tree == null) { break; } } return trees; } }
public class class_name { public static NaryTreebank readTreesInPtbFormat(Reader reader) throws IOException { NaryTreebank trees = new NaryTreebank(); while (true) { NaryTree tree = NaryTree.readTreeInPtbFormat(reader); if (tree != null) { tree.intern(); // depends on control dependency: [if], data = [none] trees.add(tree); // depends on control dependency: [if], data = [(tree] } if (tree == null) { break; } } return trees; } }
public class class_name { public void assertSubscriptions() { for (String channel : subscribers.keySet()) { try { subscribers.put(channel, null); subscribe(channel); } catch (Throwable e) { break; } } } }
public class class_name { public void assertSubscriptions() { for (String channel : subscribers.keySet()) { try { subscribers.put(channel, null); // depends on control dependency: [try], data = [none] subscribe(channel); // depends on control dependency: [try], data = [none] } catch (Throwable e) { break; } // depends on control dependency: [catch], data = [none] } } }
public class class_name { public static Map<String, State> getDatasetSpecificProps(Iterable<String> datasets, State state) { if (!Strings.isNullOrEmpty(state.getProp(DATASET_SPECIFIC_PROPS)) || !Strings.isNullOrEmpty(state.getProp(KAFKA_TOPIC_SPECIFIC_STATE))) { Map<String, State> datasetSpecificConfigMap = Maps.newHashMap(); JsonArray array = !Strings.isNullOrEmpty(state.getProp(DATASET_SPECIFIC_PROPS)) ? state.getPropAsJsonArray(DATASET_SPECIFIC_PROPS) : state.getPropAsJsonArray(KAFKA_TOPIC_SPECIFIC_STATE); // Iterate over the entire JsonArray specified by the config key for (JsonElement datasetElement : array) { // Check that each entry in the JsonArray is a JsonObject Preconditions.checkArgument(datasetElement.isJsonObject(), "The value for property " + DATASET_SPECIFIC_PROPS + " is malformed"); JsonObject object = datasetElement.getAsJsonObject(); // Only process JsonObjects that have a dataset identifier if (object.has(DATASET)) { JsonElement datasetNameElement = object.get(DATASET); Preconditions.checkArgument(datasetNameElement.isJsonPrimitive(), "The value for property " + DATASET_SPECIFIC_PROPS + " is malformed, the " + DATASET + " field must be a string"); // Iterate through each dataset that matches the value of the JsonObjects DATASET field for (String dataset : Iterables.filter(datasets, new DatasetPredicate(datasetNameElement.getAsString()))) { // If an entry already exists for a dataset, add it to the current state, else create a new state if (datasetSpecificConfigMap.containsKey(dataset)) { datasetSpecificConfigMap.get(dataset).addAll(StateUtils.jsonObjectToState(object, DATASET)); } else { datasetSpecificConfigMap.put(dataset, StateUtils.jsonObjectToState(object, DATASET)); } } } else { LOG.warn("Skipping JsonElement " + datasetElement + " as it is does not contain a field with key " + DATASET); } } return datasetSpecificConfigMap; } return Maps.newHashMap(); } }
public class class_name { public static Map<String, State> getDatasetSpecificProps(Iterable<String> datasets, State state) { if (!Strings.isNullOrEmpty(state.getProp(DATASET_SPECIFIC_PROPS)) || !Strings.isNullOrEmpty(state.getProp(KAFKA_TOPIC_SPECIFIC_STATE))) { Map<String, State> datasetSpecificConfigMap = Maps.newHashMap(); JsonArray array = !Strings.isNullOrEmpty(state.getProp(DATASET_SPECIFIC_PROPS)) ? state.getPropAsJsonArray(DATASET_SPECIFIC_PROPS) : state.getPropAsJsonArray(KAFKA_TOPIC_SPECIFIC_STATE); // Iterate over the entire JsonArray specified by the config key for (JsonElement datasetElement : array) { // Check that each entry in the JsonArray is a JsonObject Preconditions.checkArgument(datasetElement.isJsonObject(), "The value for property " + DATASET_SPECIFIC_PROPS + " is malformed"); // depends on control dependency: [for], data = [datasetElement] JsonObject object = datasetElement.getAsJsonObject(); // Only process JsonObjects that have a dataset identifier if (object.has(DATASET)) { JsonElement datasetNameElement = object.get(DATASET); Preconditions.checkArgument(datasetNameElement.isJsonPrimitive(), "The value for property " + DATASET_SPECIFIC_PROPS + " is malformed, the " + DATASET + " field must be a string"); // depends on control dependency: [if], data = [none] // Iterate through each dataset that matches the value of the JsonObjects DATASET field for (String dataset : Iterables.filter(datasets, new DatasetPredicate(datasetNameElement.getAsString()))) { // If an entry already exists for a dataset, add it to the current state, else create a new state if (datasetSpecificConfigMap.containsKey(dataset)) { datasetSpecificConfigMap.get(dataset).addAll(StateUtils.jsonObjectToState(object, DATASET)); // depends on control dependency: [if], data = [none] } else { datasetSpecificConfigMap.put(dataset, StateUtils.jsonObjectToState(object, DATASET)); // depends on control dependency: [if], data = [none] } } } else { LOG.warn("Skipping JsonElement " + datasetElement + " as it is does not contain a field with key " + DATASET); // depends on control dependency: [if], data = [none] } } return datasetSpecificConfigMap; // depends on control dependency: [if], data = [none] } return Maps.newHashMap(); } }
public class class_name { public static synchronized void addDefaultResource(String name) { if(!defaultResources.contains(name)) { defaultResources.add(name); for(Configuration conf : REGISTRY.keySet()) { if(conf.loadDefaults) { conf.reloadConfiguration(); } } } } }
public class class_name { public static synchronized void addDefaultResource(String name) { if(!defaultResources.contains(name)) { defaultResources.add(name); // depends on control dependency: [if], data = [none] for(Configuration conf : REGISTRY.keySet()) { if(conf.loadDefaults) { conf.reloadConfiguration(); // depends on control dependency: [if], data = [none] } } } } }
public class class_name { @Sensitive public Map<String, Object> obtainAccessToken(SocialLoginConfig config, String requestToken, String verifierOrPinValue) { String endpointUrl = config.getTokenEndpoint(); try { SocialUtil.validateEndpointWithQuery(endpointUrl); } catch (SocialLoginException e) { return createErrorResponse("TWITTER_BAD_ACCESS_TOKEN_URL", new Object[] { endpointUrl, TwitterLoginConfigImpl.KEY_accessTokenUrl, config.getUniqueId(), e.getLocalizedMessage() }); } // Create the Authorization header string necessary to authenticate the request String authzHeaderString = createAuthzHeaderForAuthorizedEndpoint(endpointUrl, requestToken); if (tc.isDebugEnabled()) { Tr.debug(tc, "Authz header string: " + authzHeaderString); } return executeRequest(config, requestMethod, authzHeaderString, endpointUrl, TwitterConstants.TWITTER_ENDPOINT_ACCESS_TOKEN, verifierOrPinValue); } }
public class class_name { @Sensitive public Map<String, Object> obtainAccessToken(SocialLoginConfig config, String requestToken, String verifierOrPinValue) { String endpointUrl = config.getTokenEndpoint(); try { SocialUtil.validateEndpointWithQuery(endpointUrl); // depends on control dependency: [try], data = [none] } catch (SocialLoginException e) { return createErrorResponse("TWITTER_BAD_ACCESS_TOKEN_URL", new Object[] { endpointUrl, TwitterLoginConfigImpl.KEY_accessTokenUrl, config.getUniqueId(), e.getLocalizedMessage() }); } // depends on control dependency: [catch], data = [none] // Create the Authorization header string necessary to authenticate the request String authzHeaderString = createAuthzHeaderForAuthorizedEndpoint(endpointUrl, requestToken); if (tc.isDebugEnabled()) { Tr.debug(tc, "Authz header string: " + authzHeaderString); // depends on control dependency: [if], data = [none] } return executeRequest(config, requestMethod, authzHeaderString, endpointUrl, TwitterConstants.TWITTER_ENDPOINT_ACCESS_TOKEN, verifierOrPinValue); } }
public class class_name { protected void dispatchOnRangeSelected(@NonNull final List<CalendarDay> days) { if (rangeListener != null) { rangeListener.onRangeSelected(MaterialCalendarView.this, days); } } }
public class class_name { protected void dispatchOnRangeSelected(@NonNull final List<CalendarDay> days) { if (rangeListener != null) { rangeListener.onRangeSelected(MaterialCalendarView.this, days); // depends on control dependency: [if], data = [none] } } }
public class class_name { public int compare(Object objA, Object objB) { if (!(objA instanceof DefBase) || !(objB instanceof DefBase)) { return 0; } else { return ((DefBase)objA).getName().compareTo(((DefBase)objB).getName()); } } }
public class class_name { public int compare(Object objA, Object objB) { if (!(objA instanceof DefBase) || !(objB instanceof DefBase)) { return 0; // depends on control dependency: [if], data = [none] } else { return ((DefBase)objA).getName().compareTo(((DefBase)objB).getName()); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void propertiesToControls() { m_comboSource.setSelectedItem(m_properties.getProperty(SOURCE_PARAM)); if (m_comboSource.getSelectedIndex() == -1) { m_comboSource.setSelectedIndex(0); m_properties.setProperty(SOURCE_PARAM, m_comboSource.getSelectedItem().toString()); } m_comboDestination.setSelectedItem(m_properties.getProperty(DESTINATION_PARAM)); if (m_comboDestination.getSelectedIndex() == -1) { m_comboDestination.setSelectedIndex(0); m_properties.setProperty(DESTINATION_PARAM, m_comboDestination.getSelectedItem().toString()); } super.propertiesToControls(); } }
public class class_name { public void propertiesToControls() { m_comboSource.setSelectedItem(m_properties.getProperty(SOURCE_PARAM)); if (m_comboSource.getSelectedIndex() == -1) { m_comboSource.setSelectedIndex(0); // depends on control dependency: [if], data = [none] m_properties.setProperty(SOURCE_PARAM, m_comboSource.getSelectedItem().toString()); // depends on control dependency: [if], data = [none] } m_comboDestination.setSelectedItem(m_properties.getProperty(DESTINATION_PARAM)); if (m_comboDestination.getSelectedIndex() == -1) { m_comboDestination.setSelectedIndex(0); // depends on control dependency: [if], data = [none] m_properties.setProperty(DESTINATION_PARAM, m_comboDestination.getSelectedItem().toString()); // depends on control dependency: [if], data = [none] } super.propertiesToControls(); } }
public class class_name { public ProxySelector proxySelector() { DefaultProxySelector dps = new DefaultProxySelector(); for (Proxy proxy : settings.getProxies()) { dps.add(MavenConverter.asProxy(proxy), proxy.getNonProxyHosts()); } return dps; } }
public class class_name { public ProxySelector proxySelector() { DefaultProxySelector dps = new DefaultProxySelector(); for (Proxy proxy : settings.getProxies()) { dps.add(MavenConverter.asProxy(proxy), proxy.getNonProxyHosts()); // depends on control dependency: [for], data = [proxy] } return dps; } }
public class class_name { public IpcLogEntry withHttpStatus(int httpStatus) { if (httpStatus >= 100 && httpStatus < 600) { this.httpStatus = httpStatus; if (status == null) { status = IpcStatus.forHttpStatus(httpStatus); } if (result == null) { result = status.result(); } } else { // If an invalid HTTP status code is passed in this.httpStatus = -1; } return this; } }
public class class_name { public IpcLogEntry withHttpStatus(int httpStatus) { if (httpStatus >= 100 && httpStatus < 600) { this.httpStatus = httpStatus; // depends on control dependency: [if], data = [none] if (status == null) { status = IpcStatus.forHttpStatus(httpStatus); // depends on control dependency: [if], data = [none] } if (result == null) { result = status.result(); // depends on control dependency: [if], data = [none] } } else { // If an invalid HTTP status code is passed in this.httpStatus = -1; // depends on control dependency: [if], data = [none] } return this; } }
public class class_name { public JobScheduleEnableOptions withOcpDate(DateTime ocpDate) { if (ocpDate == null) { this.ocpDate = null; } else { this.ocpDate = new DateTimeRfc1123(ocpDate); } return this; } }
public class class_name { public JobScheduleEnableOptions withOcpDate(DateTime ocpDate) { if (ocpDate == null) { this.ocpDate = null; // depends on control dependency: [if], data = [none] } else { this.ocpDate = new DateTimeRfc1123(ocpDate); // depends on control dependency: [if], data = [(ocpDate] } return this; } }
public class class_name { public void assertIsNotInstanceOfAny(Description description, Object actual, Class<?>[] types) { checkNotNullOrEmpty(types); if (isInstanceOfAny(actual, types)) { String format = "expecting <%s> not to be an instance of any of:<%s>"; throw failures.failure(description, new BasicErrorMessageFactory(format, actual, types)); } } }
public class class_name { public void assertIsNotInstanceOfAny(Description description, Object actual, Class<?>[] types) { checkNotNullOrEmpty(types); if (isInstanceOfAny(actual, types)) { String format = "expecting <%s> not to be an instance of any of:<%s>"; // depends on control dependency: [if], data = [none] throw failures.failure(description, new BasicErrorMessageFactory(format, actual, types)); } } }
public class class_name { public final List<Metric> poll(MetricFilter filter, boolean reset) { Map<String, Future<List<Metric>>> futures = new HashMap<>(); for (Map.Entry<String, MetricPoller> e : pollers.entrySet()) { PollCallable task = new PollCallable(e.getValue(), filter, reset); futures.put(e.getKey(), executor.submit(task)); } List<Metric> allMetrics = new ArrayList<>(); for (Map.Entry<String, Future<List<Metric>>> e : futures.entrySet()) { allMetrics.addAll(getMetrics(e.getKey(), e.getValue())); } return allMetrics; } }
public class class_name { public final List<Metric> poll(MetricFilter filter, boolean reset) { Map<String, Future<List<Metric>>> futures = new HashMap<>(); for (Map.Entry<String, MetricPoller> e : pollers.entrySet()) { PollCallable task = new PollCallable(e.getValue(), filter, reset); futures.put(e.getKey(), executor.submit(task)); // depends on control dependency: [for], data = [e] } List<Metric> allMetrics = new ArrayList<>(); for (Map.Entry<String, Future<List<Metric>>> e : futures.entrySet()) { allMetrics.addAll(getMetrics(e.getKey(), e.getValue())); // depends on control dependency: [for], data = [e] } return allMetrics; } }
public class class_name { private String footprint(Test test) { StringBuilder sb = new StringBuilder(); sb .append(test.getCategory()) .append(test.getName()) .append(test.getFlags()); for (String tag : test.getTags()) { sb.append(tag); } for (String ticket : test.getTickets()) { sb.append(ticket); } for (Map.Entry<String, String> entry : test.getData().entrySet()) { sb.append(entry.getKey()).append(entry.getValue()); } return FootprintGenerator.footprint(sb.toString()); } }
public class class_name { private String footprint(Test test) { StringBuilder sb = new StringBuilder(); sb .append(test.getCategory()) .append(test.getName()) .append(test.getFlags()); for (String tag : test.getTags()) { sb.append(tag); // depends on control dependency: [for], data = [tag] } for (String ticket : test.getTickets()) { sb.append(ticket); // depends on control dependency: [for], data = [ticket] } for (Map.Entry<String, String> entry : test.getData().entrySet()) { sb.append(entry.getKey()).append(entry.getValue()); // depends on control dependency: [for], data = [entry] } return FootprintGenerator.footprint(sb.toString()); } }
public class class_name { @Override public void remove(final TreeNode child) { if (children != null) { children.remove(child); if (child instanceof AbstractTreeNode) { ((AbstractTreeNode) child).parent = null; } } } }
public class class_name { @Override public void remove(final TreeNode child) { if (children != null) { children.remove(child); // depends on control dependency: [if], data = [none] if (child instanceof AbstractTreeNode) { ((AbstractTreeNode) child).parent = null; // depends on control dependency: [if], data = [none] } } } }
public class class_name { public static void main(String[] args) { Map<String,Object> properties = null; if (args != null) { properties = new Hashtable<String,Object>(); Utility.parseArgs(properties, args); } Application app = new MainApplication(null, properties, null); String strProcess = Utility.addURLParam(null, DBParams.PROCESS, ExportRecordsToXmlProcess.class.getName()); app.getTaskScheduler().addTask(new ProcessRunnerTask(app, strProcess, null)); //org.jbundle.personal.manual.ExportPictureRecord")); } }
public class class_name { public static void main(String[] args) { Map<String,Object> properties = null; if (args != null) { properties = new Hashtable<String,Object>(); // depends on control dependency: [if], data = [none] Utility.parseArgs(properties, args); // depends on control dependency: [if], data = [none] } Application app = new MainApplication(null, properties, null); String strProcess = Utility.addURLParam(null, DBParams.PROCESS, ExportRecordsToXmlProcess.class.getName()); app.getTaskScheduler().addTask(new ProcessRunnerTask(app, strProcess, null)); //org.jbundle.personal.manual.ExportPictureRecord")); } }
public class class_name { @Override public void store(Value v) { assert !v.isPersisted(); new File(_dir, getIceDirectory(v._key)).mkdirs(); // Nuke any prior file. FileOutputStream s = null; try { s = new FileOutputStream(getFile(v)); } catch( FileNotFoundException e ) { String info = "Key: " + v._key.toString() + "\nEncoded: " + getFile(v); throw new RuntimeException(Log.err("Encoding a key to a file failed!\n" + info, e)); } try { byte[] m = v.memOrLoad(); // we are not single threaded anymore assert m != null && m.length == v._max : "Trying to save partial file: value key=" + v._key + ", length to save=" + m + ", value max size=" + v._max; // Assert not saving partial files new AutoBuffer(s.getChannel(), false, Value.ICE).putA1(m, m.length).close(); v.setdsk(); // Set as write-complete to disk } finally { Utils.close(s); } } }
public class class_name { @Override public void store(Value v) { assert !v.isPersisted(); new File(_dir, getIceDirectory(v._key)).mkdirs(); // Nuke any prior file. FileOutputStream s = null; try { s = new FileOutputStream(getFile(v)); // depends on control dependency: [try], data = [none] } catch( FileNotFoundException e ) { String info = "Key: " + v._key.toString() + "\nEncoded: " + getFile(v); throw new RuntimeException(Log.err("Encoding a key to a file failed!\n" + info, e)); } // depends on control dependency: [catch], data = [none] try { byte[] m = v.memOrLoad(); // we are not single threaded anymore assert m != null && m.length == v._max : "Trying to save partial file: value key=" + v._key + ", length to save=" + m + ", value max size=" + v._max; // Assert not saving partial files // depends on control dependency: [try], data = [none] new AutoBuffer(s.getChannel(), false, Value.ICE).putA1(m, m.length).close(); // depends on control dependency: [try], data = [none] v.setdsk(); // Set as write-complete to disk // depends on control dependency: [try], data = [none] } finally { Utils.close(s); } } }
public class class_name { private static List<ILexLocation> removeDuplicates(List<ILexLocation> locations) { // Map merging function BinaryOperator<Vector<ILexLocation>> merge = (old, latest)-> { for (ILexLocation location : latest) { if (location.getHits() > 0) { // Remove objects with 0 hits in the equivalence class for(ILexLocation loc : old) if(loc.getHits() == 0) old.remove(loc); old.add(location); } else { // According to previous function if all are 0 hits that is OK // TODO: Check if that is expected! boolean allZeroHits = true; for(ILexLocation loc : old) if(loc.getHits() > 0) { allZeroHits = false; break; } if(allZeroHits) old.add(location); } } return old; }; // Remove duplicate hits Map<String, Vector<ILexLocation>> map = locations.stream() .collect(Collectors.toMap(loc -> ((ILexLocation)loc).getFile() + ((ILexLocation)loc).getModule() + "l" + ((ILexLocation)loc).getStartLine() + "p" + ((ILexLocation)loc).getStartPos(), loc -> new Vector<ILexLocation>(Arrays.asList(loc)), merge) ); return map.values() .parallelStream() .collect(ArrayList::new, ArrayList::addAll, ArrayList::addAll); } }
public class class_name { private static List<ILexLocation> removeDuplicates(List<ILexLocation> locations) { // Map merging function BinaryOperator<Vector<ILexLocation>> merge = (old, latest)-> { for (ILexLocation location : latest) { if (location.getHits() > 0) { // Remove objects with 0 hits in the equivalence class for(ILexLocation loc : old) if(loc.getHits() == 0) old.remove(loc); old.add(location); } else { // According to previous function if all are 0 hits that is OK // TODO: Check if that is expected! boolean allZeroHits = true; for(ILexLocation loc : old) if(loc.getHits() > 0) { allZeroHits = false; // depends on control dependency: [if], data = [none] break; } if(allZeroHits) old.add(location); } } return old; }; // Remove duplicate hits Map<String, Vector<ILexLocation>> map = locations.stream() .collect(Collectors.toMap(loc -> ((ILexLocation)loc).getFile() + ((ILexLocation)loc).getModule() + "l" + ((ILexLocation)loc).getStartLine() + "p" + ((ILexLocation)loc).getStartPos(), loc -> new Vector<ILexLocation>(Arrays.asList(loc)), merge) ); return map.values() .parallelStream() .collect(ArrayList::new, ArrayList::addAll, ArrayList::addAll); } }
public class class_name { @Override public DataSet<Vertex<K, VV>> createResult() { if (this.initialVertices == null) { throw new IllegalStateException("The input data set has not been set."); } // prepare the type information TypeInformation<K> keyType = ((TupleTypeInfo<?>) initialVertices.getType()).getTypeAt(0); TypeInformation<Tuple2<K, Message>> messageTypeInfo = new TupleTypeInfo<>(keyType, messageType); TypeInformation<Vertex<K, VV>> vertexType = initialVertices.getType(); TypeInformation<Either<Vertex<K, VV>, Tuple2<K, Message>>> intermediateTypeInfo = new EitherTypeInfo<>(vertexType, messageTypeInfo); TypeInformation<Either<NullValue, Message>> nullableMsgTypeInfo = new EitherTypeInfo<>(TypeExtractor.getForClass(NullValue.class), messageType); TypeInformation<Tuple2<K, Either<NullValue, Message>>> workSetTypeInfo = new TupleTypeInfo<>(keyType, nullableMsgTypeInfo); DataSet<Tuple2<K, Either<NullValue, Message>>> initialWorkSet = initialVertices.map( new InitializeWorkSet<K, VV, Message>()).returns(workSetTypeInfo); final DeltaIteration<Vertex<K, VV>, Tuple2<K, Either<NullValue, Message>>> iteration = initialVertices.iterateDelta(initialWorkSet, this.maximumNumberOfIterations, 0); setUpIteration(iteration); // join with the current state to get vertex values DataSet<Tuple2<Vertex<K, VV>, Either<NullValue, Message>>> verticesWithMsgs = iteration.getSolutionSet().join(iteration.getWorkset()) .where(0).equalTo(0) .with(new AppendVertexState<>()) .returns(new TupleTypeInfo<>( vertexType, nullableMsgTypeInfo)); VertexComputeUdf<K, VV, EV, Message> vertexUdf = new VertexComputeUdf<>(computeFunction, intermediateTypeInfo); CoGroupOperator<?, ?, Either<Vertex<K, VV>, Tuple2<K, Message>>> superstepComputation = verticesWithMsgs.coGroup(edgesWithValue) .where("f0.f0").equalTo(0) .with(vertexUdf); // compute the solution set delta DataSet<Vertex<K, VV>> solutionSetDelta = superstepComputation.flatMap( new ProjectNewVertexValue<>()).returns(vertexType); // compute the inbox of each vertex for the next superstep (new workset) DataSet<Tuple2<K, Either<NullValue, Message>>> allMessages = superstepComputation.flatMap( new ProjectMessages<>()).returns(workSetTypeInfo); DataSet<Tuple2<K, Either<NullValue, Message>>> newWorkSet = allMessages; // check if a combiner has been provided if (combineFunction != null) { MessageCombinerUdf<K, Message> combinerUdf = new MessageCombinerUdf<>(combineFunction, workSetTypeInfo); DataSet<Tuple2<K, Either<NullValue, Message>>> combinedMessages = allMessages .groupBy(0).reduceGroup(combinerUdf) .setCombinable(true); newWorkSet = combinedMessages; } // configure the compute function superstepComputation = superstepComputation.name("Compute Function"); if (this.configuration != null) { for (Tuple2<String, DataSet<?>> e : this.configuration.getBcastVars()) { superstepComputation = superstepComputation.withBroadcastSet(e.f1, e.f0); } } return iteration.closeWith(solutionSetDelta, newWorkSet); } }
public class class_name { @Override public DataSet<Vertex<K, VV>> createResult() { if (this.initialVertices == null) { throw new IllegalStateException("The input data set has not been set."); } // prepare the type information TypeInformation<K> keyType = ((TupleTypeInfo<?>) initialVertices.getType()).getTypeAt(0); TypeInformation<Tuple2<K, Message>> messageTypeInfo = new TupleTypeInfo<>(keyType, messageType); TypeInformation<Vertex<K, VV>> vertexType = initialVertices.getType(); TypeInformation<Either<Vertex<K, VV>, Tuple2<K, Message>>> intermediateTypeInfo = new EitherTypeInfo<>(vertexType, messageTypeInfo); TypeInformation<Either<NullValue, Message>> nullableMsgTypeInfo = new EitherTypeInfo<>(TypeExtractor.getForClass(NullValue.class), messageType); TypeInformation<Tuple2<K, Either<NullValue, Message>>> workSetTypeInfo = new TupleTypeInfo<>(keyType, nullableMsgTypeInfo); DataSet<Tuple2<K, Either<NullValue, Message>>> initialWorkSet = initialVertices.map( new InitializeWorkSet<K, VV, Message>()).returns(workSetTypeInfo); final DeltaIteration<Vertex<K, VV>, Tuple2<K, Either<NullValue, Message>>> iteration = initialVertices.iterateDelta(initialWorkSet, this.maximumNumberOfIterations, 0); setUpIteration(iteration); // join with the current state to get vertex values DataSet<Tuple2<Vertex<K, VV>, Either<NullValue, Message>>> verticesWithMsgs = iteration.getSolutionSet().join(iteration.getWorkset()) .where(0).equalTo(0) .with(new AppendVertexState<>()) .returns(new TupleTypeInfo<>( vertexType, nullableMsgTypeInfo)); VertexComputeUdf<K, VV, EV, Message> vertexUdf = new VertexComputeUdf<>(computeFunction, intermediateTypeInfo); CoGroupOperator<?, ?, Either<Vertex<K, VV>, Tuple2<K, Message>>> superstepComputation = verticesWithMsgs.coGroup(edgesWithValue) .where("f0.f0").equalTo(0) .with(vertexUdf); // compute the solution set delta DataSet<Vertex<K, VV>> solutionSetDelta = superstepComputation.flatMap( new ProjectNewVertexValue<>()).returns(vertexType); // compute the inbox of each vertex for the next superstep (new workset) DataSet<Tuple2<K, Either<NullValue, Message>>> allMessages = superstepComputation.flatMap( new ProjectMessages<>()).returns(workSetTypeInfo); DataSet<Tuple2<K, Either<NullValue, Message>>> newWorkSet = allMessages; // check if a combiner has been provided if (combineFunction != null) { MessageCombinerUdf<K, Message> combinerUdf = new MessageCombinerUdf<>(combineFunction, workSetTypeInfo); DataSet<Tuple2<K, Either<NullValue, Message>>> combinedMessages = allMessages .groupBy(0).reduceGroup(combinerUdf) .setCombinable(true); newWorkSet = combinedMessages; // depends on control dependency: [if], data = [none] } // configure the compute function superstepComputation = superstepComputation.name("Compute Function"); if (this.configuration != null) { for (Tuple2<String, DataSet<?>> e : this.configuration.getBcastVars()) { superstepComputation = superstepComputation.withBroadcastSet(e.f1, e.f0); } } return iteration.closeWith(solutionSetDelta, newWorkSet); } }
public class class_name { public Observable<ServiceResponse<ServerConnectionPolicyInner>> createOrUpdateWithServiceResponseAsync(String resourceGroupName, String serverName, ServerConnectionType connectionType) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (serverName == null) { throw new IllegalArgumentException("Parameter serverName is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } if (connectionType == null) { throw new IllegalArgumentException("Parameter connectionType is required and cannot be null."); } final String connectionPolicyName = "default"; ServerConnectionPolicyInner parameters = new ServerConnectionPolicyInner(); parameters.withConnectionType(connectionType); return service.createOrUpdate(this.client.subscriptionId(), resourceGroupName, serverName, connectionPolicyName, this.client.apiVersion(), this.client.acceptLanguage(), parameters, this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<ServerConnectionPolicyInner>>>() { @Override public Observable<ServiceResponse<ServerConnectionPolicyInner>> call(Response<ResponseBody> response) { try { ServiceResponse<ServerConnectionPolicyInner> clientResponse = createOrUpdateDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } }
public class class_name { public Observable<ServiceResponse<ServerConnectionPolicyInner>> createOrUpdateWithServiceResponseAsync(String resourceGroupName, String serverName, ServerConnectionType connectionType) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (serverName == null) { throw new IllegalArgumentException("Parameter serverName is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } if (connectionType == null) { throw new IllegalArgumentException("Parameter connectionType is required and cannot be null."); } final String connectionPolicyName = "default"; ServerConnectionPolicyInner parameters = new ServerConnectionPolicyInner(); parameters.withConnectionType(connectionType); return service.createOrUpdate(this.client.subscriptionId(), resourceGroupName, serverName, connectionPolicyName, this.client.apiVersion(), this.client.acceptLanguage(), parameters, this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<ServerConnectionPolicyInner>>>() { @Override public Observable<ServiceResponse<ServerConnectionPolicyInner>> call(Response<ResponseBody> response) { try { ServiceResponse<ServerConnectionPolicyInner> clientResponse = createOrUpdateDelegate(response); return Observable.just(clientResponse); // depends on control dependency: [try], data = [none] } catch (Throwable t) { return Observable.error(t); } // depends on control dependency: [catch], data = [none] } }); } }
public class class_name { private int convertFocusDirectionToLayoutDirectionExpose(int focusDirection) { int orientation = getOrientation(); switch (focusDirection) { case View.FOCUS_BACKWARD: return LayoutState.LAYOUT_START; case View.FOCUS_FORWARD: return LayoutState.LAYOUT_END; case View.FOCUS_UP: return orientation == VERTICAL ? LayoutState.LAYOUT_START : LayoutState.INVALID_LAYOUT; case View.FOCUS_DOWN: return orientation == VERTICAL ? LayoutState.LAYOUT_END : LayoutState.INVALID_LAYOUT; case View.FOCUS_LEFT: return orientation == HORIZONTAL ? LayoutState.LAYOUT_START : LayoutState.INVALID_LAYOUT; case View.FOCUS_RIGHT: return orientation == HORIZONTAL ? LayoutState.LAYOUT_END : LayoutState.INVALID_LAYOUT; default: if (DEBUG) { Log.d(TAG, "Unknown focus request:" + focusDirection); } return LayoutState.INVALID_LAYOUT; } } }
public class class_name { private int convertFocusDirectionToLayoutDirectionExpose(int focusDirection) { int orientation = getOrientation(); switch (focusDirection) { case View.FOCUS_BACKWARD: return LayoutState.LAYOUT_START; case View.FOCUS_FORWARD: return LayoutState.LAYOUT_END; case View.FOCUS_UP: return orientation == VERTICAL ? LayoutState.LAYOUT_START : LayoutState.INVALID_LAYOUT; case View.FOCUS_DOWN: return orientation == VERTICAL ? LayoutState.LAYOUT_END : LayoutState.INVALID_LAYOUT; case View.FOCUS_LEFT: return orientation == HORIZONTAL ? LayoutState.LAYOUT_START : LayoutState.INVALID_LAYOUT; case View.FOCUS_RIGHT: return orientation == HORIZONTAL ? LayoutState.LAYOUT_END : LayoutState.INVALID_LAYOUT; default: if (DEBUG) { Log.d(TAG, "Unknown focus request:" + focusDirection); // depends on control dependency: [if], data = [none] } return LayoutState.INVALID_LAYOUT; } } }
public class class_name { public static <T> Iterator<T> each(Iterator<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) { while (self.hasNext()) { Object arg = self.next(); closure.call(arg); } return self; } }
public class class_name { public static <T> Iterator<T> each(Iterator<T> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure closure) { while (self.hasNext()) { Object arg = self.next(); closure.call(arg); // depends on control dependency: [while], data = [none] } return self; } }
public class class_name { public static final void main(String [] args) { if (args.length != 2) { printUsage(); return; } String cmd = args[0]; String input = args[1]; if ("encrypt".equals(cmd)) { //$NON-NLS-1$ System.out.println(AesEncrypter.encrypt(input).substring("$CRYPT::".length())); //$NON-NLS-1$ } else if ("decrypt".equals(cmd)) { //$NON-NLS-1$ System.out.println(AesEncrypter.decrypt("$CRYPT::" + input)); //$NON-NLS-1$ } else { printUsage(); } } }
public class class_name { public static final void main(String [] args) { if (args.length != 2) { printUsage(); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } String cmd = args[0]; String input = args[1]; if ("encrypt".equals(cmd)) { //$NON-NLS-1$ System.out.println(AesEncrypter.encrypt(input).substring("$CRYPT::".length())); //$NON-NLS-1$ // depends on control dependency: [if], data = [none] } else if ("decrypt".equals(cmd)) { //$NON-NLS-1$ System.out.println(AesEncrypter.decrypt("$CRYPT::" + input)); //$NON-NLS-1$ // depends on control dependency: [if], data = [none] } else { printUsage(); // depends on control dependency: [if], data = [none] } } }
public class class_name { public EventImpl publishEvent(Event event, boolean async) { EventImpl eventImpl = (EventImpl) event; eventImpl.setReadOnly(true); EventImpl currentEvent = (EventImpl) CurrentEvent.get(); if (null != currentEvent) { eventImpl.setParent(currentEvent); } // Attempt to get the Topic object and cached TopicData but fallback // to the topic name if the Topic object wasn't populated Topic topic = eventImpl.getTopicObject(); String topicName = topic != null ? topic.getName() : eventImpl.getTopic(); TopicData topicData = topicCache.getTopicData(topic, topicName); eventImpl.setTopicData(topicData); // Required Java 2 Security check checkTopicPublishPermission(topicName); if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) { Tr.event(tc, "Publishing Event", topicName); } // Obtain list of matching handlers: returned list of handlers // must be thread safe! List<HandlerHolder> holders = topicData.getEventHandlers(); ExecutorService executor = topicData.getExecutorService(); if (async) { int i = 0; // Handle asynchronous events. Future<?>[] futures = new Future<?>[holders.size()]; for (HandlerHolder holder : holders) { holder.addEvent(eventImpl); futures[i++] = queueWorkRequest(holder, executor); } eventImpl.setFutures(futures); } else { // fire synchronous events for (HandlerHolder holder : holders) { holder.fireSynchronousEvent(eventImpl); } } return eventImpl; } }
public class class_name { public EventImpl publishEvent(Event event, boolean async) { EventImpl eventImpl = (EventImpl) event; eventImpl.setReadOnly(true); EventImpl currentEvent = (EventImpl) CurrentEvent.get(); if (null != currentEvent) { eventImpl.setParent(currentEvent); // depends on control dependency: [if], data = [currentEvent)] } // Attempt to get the Topic object and cached TopicData but fallback // to the topic name if the Topic object wasn't populated Topic topic = eventImpl.getTopicObject(); String topicName = topic != null ? topic.getName() : eventImpl.getTopic(); TopicData topicData = topicCache.getTopicData(topic, topicName); eventImpl.setTopicData(topicData); // Required Java 2 Security check checkTopicPublishPermission(topicName); if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) { Tr.event(tc, "Publishing Event", topicName); // depends on control dependency: [if], data = [none] } // Obtain list of matching handlers: returned list of handlers // must be thread safe! List<HandlerHolder> holders = topicData.getEventHandlers(); ExecutorService executor = topicData.getExecutorService(); if (async) { int i = 0; // Handle asynchronous events. Future<?>[] futures = new Future<?>[holders.size()]; for (HandlerHolder holder : holders) { holder.addEvent(eventImpl); // depends on control dependency: [for], data = [holder] futures[i++] = queueWorkRequest(holder, executor); // depends on control dependency: [for], data = [holder] } eventImpl.setFutures(futures); // depends on control dependency: [if], data = [none] } else { // fire synchronous events for (HandlerHolder holder : holders) { holder.fireSynchronousEvent(eventImpl); // depends on control dependency: [for], data = [holder] } } return eventImpl; } }
public class class_name { public void resetLabels() { AbstractInsnNode insn = first; while (insn != null) { if (insn instanceof LabelNode) { ((LabelNode) insn).resetLabel(); } insn = insn.next; } } }
public class class_name { public void resetLabels() { AbstractInsnNode insn = first; while (insn != null) { if (insn instanceof LabelNode) { ((LabelNode) insn).resetLabel(); // depends on control dependency: [if], data = [none] } insn = insn.next; // depends on control dependency: [while], data = [none] } } }
public class class_name { @SuppressWarnings( "unchecked" ) @Override public ConcurrentMap<String, Object> deserializeAttributes(final byte[] data ) { final Kryo kryo = _kryoPool.borrow(); Input in = null; try { in = kryo.getStreamFactory().getInput(data); return kryo.readObject(in, ConcurrentHashMap.class); } catch ( final RuntimeException e ) { throw new TranscoderDeserializationException( e ); } finally { closeSilently(in); kryo.reset(); // to be safe _kryoPool.release(kryo); } } }
public class class_name { @SuppressWarnings( "unchecked" ) @Override public ConcurrentMap<String, Object> deserializeAttributes(final byte[] data ) { final Kryo kryo = _kryoPool.borrow(); Input in = null; try { in = kryo.getStreamFactory().getInput(data); // depends on control dependency: [try], data = [none] return kryo.readObject(in, ConcurrentHashMap.class); // depends on control dependency: [try], data = [none] } catch ( final RuntimeException e ) { throw new TranscoderDeserializationException( e ); } finally { // depends on control dependency: [catch], data = [none] closeSilently(in); kryo.reset(); // to be safe _kryoPool.release(kryo); } } }
public class class_name { public String toECharts() { TriFunction<Integer, Integer, List<Stopwatch>, String> formatLevel = ( totalDepth, depth, items) -> { float factor = 100.0f / (totalDepth + 1); float showFactor = 1 + (totalDepth - depth) / (float) depth; float radiusFrom = depth * factor; float radiusTo = depth * factor + factor; if (depth == 1) { radiusFrom = 0; } StringBuilder sb = new StringBuilder(8 + items.size() * 128); sb.append('{'); sb.append("name: 'Total Cost',"); sb.append("type: 'pie',"); sb.append(String.format("radius: ['%s%%', '%s%%'],", radiusFrom, radiusTo)); sb.append(String.format( "label: {normal: {position: 'inner', formatter:" + "function(params) {" + " if (params.percent > %s) return params.data.name;" + " else return '';" + "}}},", showFactor)); sb.append("data: ["); items.sort((i, j) -> i.id().compareTo(j.id())); for (Stopwatch w : items) { sb.append('{'); sb.append("value:"); sb.append(w.totalCost() / 1000000.0); sb.append(','); sb.append("min:"); sb.append(w.minCost()); sb.append(','); sb.append("max:"); sb.append(w.maxCost()); sb.append(','); sb.append("id:'"); sb.append(w.id()); sb.append("',"); sb.append("name:'"); sb.append(w.name()); sb.append("',"); sb.append("times:"); sb.append(w.times()); sb.append('}'); sb.append(','); } if (!items.isEmpty()) { sb.deleteCharAt(sb.length() - 1); } sb.append("]}"); return sb.toString(); }; BiConsumer<List<Stopwatch>, List<Stopwatch>> fillOther = (itemsOfI, parents) -> { for (Stopwatch parent : parents) { Stream<Stopwatch> children = itemsOfI.stream().filter(c -> { return c.parent().equals(parent.id()); }); long sum = children.mapToLong(c -> c.totalCost()).sum(); if (sum < parent.totalCost()) { Stopwatch other = new Stopwatch("~", parent.id()); other.totalCost(parent.totalCost() - sum); itemsOfI.add(other); } } }; Map<String, Stopwatch> items = this.stopwatches; Map<Integer, List<Stopwatch>> levelItems = new HashMap<>(); int maxDepth = 1; for (Map.Entry<String, Stopwatch> e : items.entrySet()) { int depth = e.getKey().split("/").length; levelItems.putIfAbsent(depth, new LinkedList<>()); levelItems.get(depth).add(e.getValue().copy()); if (depth > maxDepth) { maxDepth = depth; } } StringBuilder sb = new StringBuilder(8 + items.size() * 128); sb.append("{"); sb.append("tooltip: {trigger: 'item', " + "formatter: function(params) {" + " return params.data.name + ' ' + params.percent + '% <br/>'" + " + 'cost: ' + params.data.value + ' (ms) <br/>'" + " + 'min: ' + params.data.min + ' (ns) <br/>'" + " + 'max: ' + params.data.max + ' (ns) <br/>'" + " + 'times: ' + params.data.times + '<br/>'" + " + params.data.id + '<br/>';" + "}"); sb.append("},"); sb.append("series: ["); for (int i = 1; levelItems.containsKey(i); i++) { List<Stopwatch> itemsOfI = levelItems.get(i); if (i > 1) { fillOther.accept(itemsOfI, levelItems.get(i - 1)); } sb.append(formatLevel.apply(maxDepth, i, itemsOfI)); sb.append(','); } if (!items.isEmpty()) { sb.deleteCharAt(sb.length() - 1); } sb.append("]}"); return sb.toString(); } }
public class class_name { public String toECharts() { TriFunction<Integer, Integer, List<Stopwatch>, String> formatLevel = ( totalDepth, depth, items) -> { float factor = 100.0f / (totalDepth + 1); float showFactor = 1 + (totalDepth - depth) / (float) depth; float radiusFrom = depth * factor; float radiusTo = depth * factor + factor; if (depth == 1) { radiusFrom = 0; // depends on control dependency: [if], data = [none] } StringBuilder sb = new StringBuilder(8 + items.size() * 128); sb.append('{'); sb.append("name: 'Total Cost',"); sb.append("type: 'pie',"); sb.append(String.format("radius: ['%s%%', '%s%%'],", radiusFrom, radiusTo)); sb.append(String.format( "label: {normal: {position: 'inner', formatter:" + "function(params) {" + " if (params.percent > %s) return params.data.name;" + " else return '';" + "}}},", showFactor)); sb.append("data: ["); items.sort((i, j) -> i.id().compareTo(j.id())); for (Stopwatch w : items) { sb.append('{'); // depends on control dependency: [for], data = [none] sb.append("value:"); // depends on control dependency: [for], data = [none] sb.append(w.totalCost() / 1000000.0); // depends on control dependency: [for], data = [w] sb.append(','); // depends on control dependency: [for], data = [none] sb.append("min:"); // depends on control dependency: [for], data = [none] sb.append(w.minCost()); // depends on control dependency: [for], data = [w] sb.append(','); // depends on control dependency: [for], data = [none] sb.append("max:"); // depends on control dependency: [for], data = [none] sb.append(w.maxCost()); // depends on control dependency: [for], data = [w] sb.append(','); // depends on control dependency: [for], data = [none] sb.append("id:'"); // depends on control dependency: [for], data = [none] sb.append(w.id()); // depends on control dependency: [for], data = [w] sb.append("',"); // depends on control dependency: [for], data = [none] sb.append("name:'"); // depends on control dependency: [for], data = [none] sb.append(w.name()); // depends on control dependency: [for], data = [w] sb.append("',"); // depends on control dependency: [for], data = [none] sb.append("times:"); // depends on control dependency: [for], data = [none] sb.append(w.times()); // depends on control dependency: [for], data = [w] sb.append('}'); // depends on control dependency: [for], data = [none] sb.append(','); // depends on control dependency: [for], data = [none] } if (!items.isEmpty()) { sb.deleteCharAt(sb.length() - 1); // depends on control dependency: [if], data = [none] } sb.append("]}"); return sb.toString(); }; BiConsumer<List<Stopwatch>, List<Stopwatch>> fillOther = (itemsOfI, parents) -> { for (Stopwatch parent : parents) { Stream<Stopwatch> children = itemsOfI.stream().filter(c -> { return c.parent().equals(parent.id()); }); long sum = children.mapToLong(c -> c.totalCost()).sum(); if (sum < parent.totalCost()) { Stopwatch other = new Stopwatch("~", parent.id()); other.totalCost(parent.totalCost() - sum); itemsOfI.add(other); } } }; Map<String, Stopwatch> items = this.stopwatches; Map<Integer, List<Stopwatch>> levelItems = new HashMap<>(); int maxDepth = 1; for (Map.Entry<String, Stopwatch> e : items.entrySet()) { int depth = e.getKey().split("/").length; levelItems.putIfAbsent(depth, new LinkedList<>()); levelItems.get(depth).add(e.getValue().copy()); if (depth > maxDepth) { maxDepth = depth; } } StringBuilder sb = new StringBuilder(8 + items.size() * 128); sb.append("{"); sb.append("tooltip: {trigger: 'item', " + "formatter: function(params) {" + " return params.data.name + ' ' + params.percent + '% <br/>'" + " + 'cost: ' + params.data.value + ' (ms) <br/>'" + " + 'min: ' + params.data.min + ' (ns) <br/>'" + " + 'max: ' + params.data.max + ' (ns) <br/>'" + " + 'times: ' + params.data.times + '<br/>'" + " + params.data.id + '<br/>';" + "}"); sb.append("},"); sb.append("series: ["); for (int i = 1; levelItems.containsKey(i); i++) { List<Stopwatch> itemsOfI = levelItems.get(i); if (i > 1) { fillOther.accept(itemsOfI, levelItems.get(i - 1)); } sb.append(formatLevel.apply(maxDepth, i, itemsOfI)); sb.append(','); } if (!items.isEmpty()) { sb.deleteCharAt(sb.length() - 1); } sb.append("]}"); return sb.toString(); } }
public class class_name { public void free(Connection connection) { try { if (!connection.isClosed()){ // ensure connections returned to pool as read-only setConnectionReadOnly(connection, true); connection.close(); } else { logger.debug("Ignoring attempt to close a previously closed connection"); } } catch (SQLException sqle) { logger.warn("Unable to close connection", sqle); } finally { if (logger.isDebugEnabled()) { logger.debug("Returned connection to pool (" + toString() + ")"); } } } }
public class class_name { public void free(Connection connection) { try { if (!connection.isClosed()){ // ensure connections returned to pool as read-only setConnectionReadOnly(connection, true); // depends on control dependency: [if], data = [none] connection.close(); // depends on control dependency: [if], data = [none] } else { logger.debug("Ignoring attempt to close a previously closed connection"); // depends on control dependency: [if], data = [none] } } catch (SQLException sqle) { logger.warn("Unable to close connection", sqle); } finally { if (logger.isDebugEnabled()) { logger.debug("Returned connection to pool (" + toString() + ")"); } } } }
public class class_name { private char checkKey(Object key) { if (key == null) { throw new NullPointerException("key cannot be null"); } else if (!(key instanceof Character)) { throw new IllegalArgumentException("key must be an Character"); } else { return ((Character)key).charValue(); } } }
public class class_name { private char checkKey(Object key) { if (key == null) { throw new NullPointerException("key cannot be null"); } else if (!(key instanceof Character)) { throw new IllegalArgumentException("key must be an Character"); } else { return ((Character)key).charValue(); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void marshall(Connector connector, ProtocolMarshaller protocolMarshaller) { if (connector == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(connector.getConnectorId(), CONNECTORID_BINDING); protocolMarshaller.marshall(connector.getVersion(), VERSION_BINDING); protocolMarshaller.marshall(connector.getStatus(), STATUS_BINDING); protocolMarshaller.marshall(connector.getCapabilityList(), CAPABILITYLIST_BINDING); protocolMarshaller.marshall(connector.getVmManagerName(), VMMANAGERNAME_BINDING); protocolMarshaller.marshall(connector.getVmManagerType(), VMMANAGERTYPE_BINDING); protocolMarshaller.marshall(connector.getVmManagerId(), VMMANAGERID_BINDING); protocolMarshaller.marshall(connector.getIpAddress(), IPADDRESS_BINDING); protocolMarshaller.marshall(connector.getMacAddress(), MACADDRESS_BINDING); protocolMarshaller.marshall(connector.getAssociatedOn(), ASSOCIATEDON_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(Connector connector, ProtocolMarshaller protocolMarshaller) { if (connector == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(connector.getConnectorId(), CONNECTORID_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(connector.getVersion(), VERSION_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(connector.getStatus(), STATUS_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(connector.getCapabilityList(), CAPABILITYLIST_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(connector.getVmManagerName(), VMMANAGERNAME_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(connector.getVmManagerType(), VMMANAGERTYPE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(connector.getVmManagerId(), VMMANAGERID_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(connector.getIpAddress(), IPADDRESS_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(connector.getMacAddress(), MACADDRESS_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(connector.getAssociatedOn(), ASSOCIATEDON_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 { private void initialize( Collection<String> toRemove, Collection<String> toAdd, String siteRoot, boolean removeAllNonExplicitlyAdded) { m_removeAllNonExplicitlyAdded = removeAllNonExplicitlyAdded; for (String removeKey : toRemove) { if (CmsUUID.isValidUUID(removeKey)) { m_updateSet.put(new CmsUUID(removeKey), Boolean.FALSE); } else if (removeKey.startsWith(PREFIX_TYPE)) { m_typeUpdateSet.put(removePrefix(removeKey), Boolean.FALSE); } } for (String addKey : toAdd) { if (CmsUUID.isValidUUID(addKey)) { m_updateSet.put(new CmsUUID(addKey), Boolean.TRUE); } else if (addKey.startsWith(PREFIX_TYPE)) { m_typeUpdateSet.put(removePrefix(addKey), Boolean.TRUE); } } if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(siteRoot)) { if (!siteRoot.endsWith("/")) { siteRoot += "/"; } String regex = "^(/system/|" + OpenCms.getSiteManager().getSharedFolder() + "|" + siteRoot + ").*"; m_pathPattern = Pattern.compile(regex); } } }
public class class_name { private void initialize( Collection<String> toRemove, Collection<String> toAdd, String siteRoot, boolean removeAllNonExplicitlyAdded) { m_removeAllNonExplicitlyAdded = removeAllNonExplicitlyAdded; for (String removeKey : toRemove) { if (CmsUUID.isValidUUID(removeKey)) { m_updateSet.put(new CmsUUID(removeKey), Boolean.FALSE); // depends on control dependency: [if], data = [none] } else if (removeKey.startsWith(PREFIX_TYPE)) { m_typeUpdateSet.put(removePrefix(removeKey), Boolean.FALSE); // depends on control dependency: [if], data = [none] } } for (String addKey : toAdd) { if (CmsUUID.isValidUUID(addKey)) { m_updateSet.put(new CmsUUID(addKey), Boolean.TRUE); // depends on control dependency: [if], data = [none] } else if (addKey.startsWith(PREFIX_TYPE)) { m_typeUpdateSet.put(removePrefix(addKey), Boolean.TRUE); // depends on control dependency: [if], data = [none] } } if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(siteRoot)) { if (!siteRoot.endsWith("/")) { siteRoot += "/"; // depends on control dependency: [if], data = [none] } String regex = "^(/system/|" + OpenCms.getSiteManager().getSharedFolder() + "|" + siteRoot + ").*"; m_pathPattern = Pattern.compile(regex); // depends on control dependency: [if], data = [none] } } }
public class class_name { public synchronized String getSignature() { if (signature == null) { CachedClass [] parameters = getParameterTypes(); final String name = getName(); StringBuilder buf = new StringBuilder(name.length()+parameters.length*10); buf.append(getReturnType().getName()); buf.append(' '); buf.append(name); buf.append('('); for (int i = 0; i < parameters.length; i++) { if (i > 0) { buf.append(", "); } buf.append(parameters[i].getName()); } buf.append(')'); signature = buf.toString(); } return signature; } }
public class class_name { public synchronized String getSignature() { if (signature == null) { CachedClass [] parameters = getParameterTypes(); final String name = getName(); StringBuilder buf = new StringBuilder(name.length()+parameters.length*10); buf.append(getReturnType().getName()); // depends on control dependency: [if], data = [none] buf.append(' '); // depends on control dependency: [if], data = [none] buf.append(name); // depends on control dependency: [if], data = [none] buf.append('('); // depends on control dependency: [if], data = [none] for (int i = 0; i < parameters.length; i++) { if (i > 0) { buf.append(", "); // depends on control dependency: [if], data = [none] } buf.append(parameters[i].getName()); // depends on control dependency: [for], data = [i] } buf.append(')'); // depends on control dependency: [if], data = [none] signature = buf.toString(); // depends on control dependency: [if], data = [none] } return signature; } }
public class class_name { private <T> String serializeToCsv(T obj) { if(obj == null) { return ""; } for (Method method: obj.getClass().getMethods()) { if ("java.util.List".equals(method.getReturnType().getName())) { try { @SuppressWarnings("rawtypes") java.util.List itemList = (java.util.List) method.invoke(obj); Object entry = itemList.get(0); List<String> stringList = new ArrayList<String>(); char delimiter = ','; String lineSep = "\n"; CsvMapper mapper = new CsvMapper(); mapper.enable(JsonGenerator.Feature.IGNORE_UNKNOWN); CsvSchema schema = mapper.schemaFor(entry.getClass()); for (int i = 0; i < itemList.size(); i++) { if (i == 0) { schema = schema.withHeader(); } else { schema = schema.withoutHeader(); } String csv = mapper.writer(schema .withColumnSeparator(delimiter) .withoutQuoteChar() .withLineSeparator(lineSep)).writeValueAsString(itemList.get(i)); stringList.add(csv); } return StringUtil.join(stringList.toArray(new String[0]), ""); } catch (JsonProcessingException e) { System.out.println(e); } catch (IllegalAccessException e) { System.out.println(e); } catch (IllegalArgumentException e) { System.out.println(e); } catch (InvocationTargetException e) { System.out.println(e); } } } return ""; } }
public class class_name { private <T> String serializeToCsv(T obj) { if(obj == null) { return ""; // depends on control dependency: [if], data = [none] } for (Method method: obj.getClass().getMethods()) { if ("java.util.List".equals(method.getReturnType().getName())) { try { @SuppressWarnings("rawtypes") java.util.List itemList = (java.util.List) method.invoke(obj); Object entry = itemList.get(0); List<String> stringList = new ArrayList<String>(); char delimiter = ','; String lineSep = "\n"; CsvMapper mapper = new CsvMapper(); mapper.enable(JsonGenerator.Feature.IGNORE_UNKNOWN); // depends on control dependency: [try], data = [none] CsvSchema schema = mapper.schemaFor(entry.getClass()); for (int i = 0; i < itemList.size(); i++) { if (i == 0) { schema = schema.withHeader(); // depends on control dependency: [if], data = [none] } else { schema = schema.withoutHeader(); // depends on control dependency: [if], data = [none] } String csv = mapper.writer(schema .withColumnSeparator(delimiter) .withoutQuoteChar() .withLineSeparator(lineSep)).writeValueAsString(itemList.get(i)); stringList.add(csv); // depends on control dependency: [for], data = [none] } return StringUtil.join(stringList.toArray(new String[0]), ""); // depends on control dependency: [try], data = [none] } catch (JsonProcessingException e) { System.out.println(e); } catch (IllegalAccessException e) { // depends on control dependency: [catch], data = [none] System.out.println(e); } catch (IllegalArgumentException e) { // depends on control dependency: [catch], data = [none] System.out.println(e); } catch (InvocationTargetException e) { // depends on control dependency: [catch], data = [none] System.out.println(e); } // depends on control dependency: [catch], data = [none] } } return ""; } }
public class class_name { public static void capture(Logger logger, Object callingObject, String methodName, FFDCProbeId probeId, Throwable throwable, Object[] data) { long ffdcTimestamp = System.currentTimeMillis(); final String className = logger.getName(); final StringBuilder sb = new StringBuilder(); sb.append("Level: "); sb.append(Version.getVersion()); sb.append(lineSeparator); final SimpleDateFormat recordFormatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss:SSS z"); sb.append("Time: "); sb.append(recordFormatter.format(ffdcTimestamp)); sb.append(lineSeparator); Thread currentThread = Thread.currentThread(); sb.append("Thread: "); sb.append(currentThread.getId()); sb.append(" ("); sb.append(currentThread.getName()); sb.append(")"); sb.append(lineSeparator); if (className != null) { sb.append("Class: "); sb.append(className); sb.append(lineSeparator); } if (callingObject != null) { sb.append("Instance: "); sb.append(Integer.toHexString(System.identityHashCode(callingObject))); sb.append(lineSeparator); } if (methodName != null) { sb.append("Method: "); sb.append(methodName); sb.append(lineSeparator); } sb.append("Probe: "); sb.append(probeId == null ? "null" : probeId); sb.append(lineSeparator); sb.append("Cause: "); sb.append(throwable == null ? "null" : throwable.toString()); sb.append(lineSeparator); try { ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); PrintStream stream = new PrintStream(byteOut, false, "UTF-8"); final Throwable displayThrowable; if (throwable != null) { displayThrowable = throwable; } else { displayThrowable = new Exception("Call stack"); } displayThrowable.printStackTrace(stream); stream.flush(); sb.append(byteOut.toString("UTF-8")); } catch (UnsupportedEncodingException e) { logger.error("Failed to generate FFDC call stack. Reason: ", e.getLocalizedMessage()); } if (data != null) { for (int i = 0; i < data.length; ++i) { Object item = data[i]; sb.append("Arg["); sb.append(i); sb.append("]: "); sb.append(item); sb.append(lineSeparator); } } for (Thread thread : Thread.getAllStackTraces().keySet()) { sb.append(getThreadInfo(thread)); } logger.error(LogMarker.FFDC.getValue(), sb.toString()); // Additionally output a javacore (to capture the full information to file) try { final String javacoreFilePath = Javacore.generateJavaCore(); logger.info("Javacore diagnostic information written to: "+javacoreFilePath); } catch (Throwable e) { logger.error("Failed to generate a javacore. Reason: {}", e.getLocalizedMessage()); } } }
public class class_name { public static void capture(Logger logger, Object callingObject, String methodName, FFDCProbeId probeId, Throwable throwable, Object[] data) { long ffdcTimestamp = System.currentTimeMillis(); final String className = logger.getName(); final StringBuilder sb = new StringBuilder(); sb.append("Level: "); sb.append(Version.getVersion()); sb.append(lineSeparator); final SimpleDateFormat recordFormatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss:SSS z"); sb.append("Time: "); sb.append(recordFormatter.format(ffdcTimestamp)); sb.append(lineSeparator); Thread currentThread = Thread.currentThread(); sb.append("Thread: "); sb.append(currentThread.getId()); sb.append(" ("); sb.append(currentThread.getName()); sb.append(")"); sb.append(lineSeparator); if (className != null) { sb.append("Class: "); // depends on control dependency: [if], data = [none] sb.append(className); // depends on control dependency: [if], data = [(className] sb.append(lineSeparator); // depends on control dependency: [if], data = [none] } if (callingObject != null) { sb.append("Instance: "); // depends on control dependency: [if], data = [none] sb.append(Integer.toHexString(System.identityHashCode(callingObject))); // depends on control dependency: [if], data = [(callingObject] sb.append(lineSeparator); // depends on control dependency: [if], data = [none] } if (methodName != null) { sb.append("Method: "); // depends on control dependency: [if], data = [none] sb.append(methodName); // depends on control dependency: [if], data = [(methodName] sb.append(lineSeparator); // depends on control dependency: [if], data = [none] } sb.append("Probe: "); sb.append(probeId == null ? "null" : probeId); sb.append(lineSeparator); sb.append("Cause: "); sb.append(throwable == null ? "null" : throwable.toString()); sb.append(lineSeparator); try { ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); PrintStream stream = new PrintStream(byteOut, false, "UTF-8"); final Throwable displayThrowable; if (throwable != null) { displayThrowable = throwable; // depends on control dependency: [if], data = [none] } else { displayThrowable = new Exception("Call stack"); // depends on control dependency: [if], data = [none] } displayThrowable.printStackTrace(stream); // depends on control dependency: [try], data = [none] stream.flush(); // depends on control dependency: [try], data = [none] sb.append(byteOut.toString("UTF-8")); // depends on control dependency: [try], data = [none] } catch (UnsupportedEncodingException e) { logger.error("Failed to generate FFDC call stack. Reason: ", e.getLocalizedMessage()); } // depends on control dependency: [catch], data = [none] if (data != null) { for (int i = 0; i < data.length; ++i) { Object item = data[i]; sb.append("Arg["); // depends on control dependency: [for], data = [none] sb.append(i); // depends on control dependency: [for], data = [i] sb.append("]: "); // depends on control dependency: [for], data = [none] sb.append(item); // depends on control dependency: [for], data = [none] sb.append(lineSeparator); // depends on control dependency: [for], data = [none] } } for (Thread thread : Thread.getAllStackTraces().keySet()) { sb.append(getThreadInfo(thread)); // depends on control dependency: [for], data = [thread] } logger.error(LogMarker.FFDC.getValue(), sb.toString()); // Additionally output a javacore (to capture the full information to file) try { final String javacoreFilePath = Javacore.generateJavaCore(); logger.info("Javacore diagnostic information written to: "+javacoreFilePath); // depends on control dependency: [try], data = [none] } catch (Throwable e) { logger.error("Failed to generate a javacore. Reason: {}", e.getLocalizedMessage()); } // depends on control dependency: [catch], data = [none] } }
public class class_name { Token parseRegex() throws ParseException { Token tok = this.parseTerm(); Token parent = null; while (this.read() == T_OR) { this.next(); // '|' if (parent == null) { parent = Token.createUnion(); parent.addChild(tok); tok = parent; } tok.addChild(this.parseTerm()); } return tok; } }
public class class_name { Token parseRegex() throws ParseException { Token tok = this.parseTerm(); Token parent = null; while (this.read() == T_OR) { this.next(); // '|' if (parent == null) { parent = Token.createUnion(); // depends on control dependency: [if], data = [none] parent.addChild(tok); // depends on control dependency: [if], data = [none] tok = parent; // depends on control dependency: [if], data = [none] } tok.addChild(this.parseTerm()); } return tok; } }
public class class_name { public void setBoardEnabled(boolean enable) { if (mEnabled != enable) { if (DBG) Log.v(TAG, "enable - " + enable); mEnabled = enable; } } }
public class class_name { public void setBoardEnabled(boolean enable) { if (mEnabled != enable) { if (DBG) Log.v(TAG, "enable - " + enable); mEnabled = enable; // depends on control dependency: [if], data = [none] } } }
public class class_name { RBBINode cloneTree() { RBBINode n; if (fType == RBBINode.varRef) { // If the current node is a variable reference, skip over it // and clone the definition of the variable instead. n = fLeftChild.cloneTree(); } else if (fType == RBBINode.uset) { n = this; } else { n = new RBBINode(this); if (fLeftChild != null) { n.fLeftChild = fLeftChild.cloneTree(); n.fLeftChild.fParent = n; } if (fRightChild != null) { n.fRightChild = fRightChild.cloneTree(); n.fRightChild.fParent = n; } } return n; } }
public class class_name { RBBINode cloneTree() { RBBINode n; if (fType == RBBINode.varRef) { // If the current node is a variable reference, skip over it // and clone the definition of the variable instead. n = fLeftChild.cloneTree(); // depends on control dependency: [if], data = [none] } else if (fType == RBBINode.uset) { n = this; // depends on control dependency: [if], data = [none] } else { n = new RBBINode(this); // depends on control dependency: [if], data = [none] if (fLeftChild != null) { n.fLeftChild = fLeftChild.cloneTree(); // depends on control dependency: [if], data = [none] n.fLeftChild.fParent = n; // depends on control dependency: [if], data = [none] } if (fRightChild != null) { n.fRightChild = fRightChild.cloneTree(); // depends on control dependency: [if], data = [none] n.fRightChild.fParent = n; // depends on control dependency: [if], data = [none] } } return n; } }
public class class_name { public JtxTransaction maybeRequestTransaction(final JtxTransactionMode txMode, final Object scope) { if (txMode == null) { return null; } JtxTransaction currentTx = txManager.getTransaction(); JtxTransaction requestedTx = txManager.requestTransaction(txMode, scope); if (currentTx == requestedTx) { return null; } return requestedTx; } }
public class class_name { public JtxTransaction maybeRequestTransaction(final JtxTransactionMode txMode, final Object scope) { if (txMode == null) { return null; // depends on control dependency: [if], data = [none] } JtxTransaction currentTx = txManager.getTransaction(); JtxTransaction requestedTx = txManager.requestTransaction(txMode, scope); if (currentTx == requestedTx) { return null; // depends on control dependency: [if], data = [none] } return requestedTx; } }
public class class_name { public void marshall(RelationalDatabaseBlueprint relationalDatabaseBlueprint, ProtocolMarshaller protocolMarshaller) { if (relationalDatabaseBlueprint == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(relationalDatabaseBlueprint.getBlueprintId(), BLUEPRINTID_BINDING); protocolMarshaller.marshall(relationalDatabaseBlueprint.getEngine(), ENGINE_BINDING); protocolMarshaller.marshall(relationalDatabaseBlueprint.getEngineVersion(), ENGINEVERSION_BINDING); protocolMarshaller.marshall(relationalDatabaseBlueprint.getEngineDescription(), ENGINEDESCRIPTION_BINDING); protocolMarshaller.marshall(relationalDatabaseBlueprint.getEngineVersionDescription(), ENGINEVERSIONDESCRIPTION_BINDING); protocolMarshaller.marshall(relationalDatabaseBlueprint.getIsEngineDefault(), ISENGINEDEFAULT_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(RelationalDatabaseBlueprint relationalDatabaseBlueprint, ProtocolMarshaller protocolMarshaller) { if (relationalDatabaseBlueprint == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(relationalDatabaseBlueprint.getBlueprintId(), BLUEPRINTID_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(relationalDatabaseBlueprint.getEngine(), ENGINE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(relationalDatabaseBlueprint.getEngineVersion(), ENGINEVERSION_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(relationalDatabaseBlueprint.getEngineDescription(), ENGINEDESCRIPTION_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(relationalDatabaseBlueprint.getEngineVersionDescription(), ENGINEVERSIONDESCRIPTION_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(relationalDatabaseBlueprint.getIsEngineDefault(), ISENGINEDEFAULT_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 extractValidationComponents(CharSequence content, File inputFile, Procedure1<Map<Tag, List<MutableTriple<File, Integer, String>>>> observer) { // // STEP 1: Extract the raw text // final Map<Tag, List<MutableTriple<File, Integer, String>>> components = new TreeMap<>(); final ContentParserInterceptor interceptor = new ContentParserInterceptor(new ParserInterceptor() { @Override public void tag(ParsingContext context, Tag tag, String dynamicName, String parameter, String blockValue) { if (tag.isOpeningTag() || tag.hasParameter()) { List<MutableTriple<File, Integer, String>> values = components.get(tag); if (values == null) { values = new ArrayList<>(); components.put(tag, values); } if (tag.isOpeningTag()) { values.add(new MutableTriple<>(context.getCurrentFile(), context.getLineNo(), Strings.nullToEmpty(blockValue).trim())); } else { values.add(new MutableTriple<>(context.getCurrentFile(), context.getLineNo(), Strings.nullToEmpty(parameter).trim())); } } } }); final ParsingContext rootContextForReplacements = new ParsingContext(true, true); initializeContext(rootContextForReplacements); parse(content, inputFile, 0, Stage.FIRST, rootContextForReplacements, interceptor); // // STEP 2: Do macro replacement in the captured elements. // final Collection<List<MutableTriple<File, Integer, String>>> allTexts = new ArrayList<>(components.values()); for (final List<MutableTriple<File, Integer, String>> values : allTexts) { for (final MutableTriple<File, Integer, String> pair : values) { final ContentParserInterceptor localInterceptor = new ContentParserInterceptor(interceptor); parse(pair.getRight(), inputFile, 0, Stage.SECOND, rootContextForReplacements, localInterceptor); final String newCapturedText = localInterceptor.getResult(); pair.setRight(newCapturedText); } } observer.apply(components); } }
public class class_name { public void extractValidationComponents(CharSequence content, File inputFile, Procedure1<Map<Tag, List<MutableTriple<File, Integer, String>>>> observer) { // // STEP 1: Extract the raw text // final Map<Tag, List<MutableTriple<File, Integer, String>>> components = new TreeMap<>(); final ContentParserInterceptor interceptor = new ContentParserInterceptor(new ParserInterceptor() { @Override public void tag(ParsingContext context, Tag tag, String dynamicName, String parameter, String blockValue) { if (tag.isOpeningTag() || tag.hasParameter()) { List<MutableTriple<File, Integer, String>> values = components.get(tag); if (values == null) { values = new ArrayList<>(); // depends on control dependency: [if], data = [none] components.put(tag, values); // depends on control dependency: [if], data = [none] } if (tag.isOpeningTag()) { values.add(new MutableTriple<>(context.getCurrentFile(), context.getLineNo(), Strings.nullToEmpty(blockValue).trim())); // depends on control dependency: [if], data = [none] } else { values.add(new MutableTriple<>(context.getCurrentFile(), context.getLineNo(), Strings.nullToEmpty(parameter).trim())); // depends on control dependency: [if], data = [none] } } } }); final ParsingContext rootContextForReplacements = new ParsingContext(true, true); initializeContext(rootContextForReplacements); parse(content, inputFile, 0, Stage.FIRST, rootContextForReplacements, interceptor); // // STEP 2: Do macro replacement in the captured elements. // final Collection<List<MutableTriple<File, Integer, String>>> allTexts = new ArrayList<>(components.values()); for (final List<MutableTriple<File, Integer, String>> values : allTexts) { for (final MutableTriple<File, Integer, String> pair : values) { final ContentParserInterceptor localInterceptor = new ContentParserInterceptor(interceptor); parse(pair.getRight(), inputFile, 0, Stage.SECOND, rootContextForReplacements, localInterceptor); // depends on control dependency: [for], data = [pair] final String newCapturedText = localInterceptor.getResult(); pair.setRight(newCapturedText); // depends on control dependency: [for], data = [pair] } } observer.apply(components); } }
public class class_name { public final boolean isPositiveUp(GridRecord gr) { int type = gr.getLevelType1(); if ((type == 1) || (type == 5)) { return false; } return true; } }
public class class_name { public final boolean isPositiveUp(GridRecord gr) { int type = gr.getLevelType1(); if ((type == 1) || (type == 5)) { return false; // depends on control dependency: [if], data = [none] } return true; } }
public class class_name { protected boolean checkIfModelMatches ( String groupId, String artifactId, String version, Model model ) { // try these first. String modelGroup = model.getGroupId(); String modelArtifactId = model.getArtifactId(); String modelVersion = model.getVersion(); try { if ( StringUtils.isEmpty( modelGroup ) ) { modelGroup = model.getParent().getGroupId(); } else { // MENFORCER-30, handle cases where the value is a property like ${project.parent.groupId} modelGroup = (String) helper.evaluate( modelGroup ); } if ( StringUtils.isEmpty( modelVersion ) ) { modelVersion = model.getParent().getVersion(); } else { // MENFORCER-30, handle cases where the value is a property like ${project.parent.version} modelVersion = (String) helper.evaluate( modelVersion ); } // Is this only required for Maven2? modelArtifactId = (String) helper.evaluate( modelArtifactId ); } catch ( NullPointerException e ) { // this is probably bad. I don't have a valid // group or version and I can't find a // parent???? // lets see if it's what we're looking for // anyway. } catch ( ExpressionEvaluationException e ) { // as above } return ( StringUtils.equals( groupId, modelGroup ) && StringUtils.equals( version, modelVersion ) && StringUtils .equals( artifactId, modelArtifactId ) ); } }
public class class_name { protected boolean checkIfModelMatches ( String groupId, String artifactId, String version, Model model ) { // try these first. String modelGroup = model.getGroupId(); String modelArtifactId = model.getArtifactId(); String modelVersion = model.getVersion(); try { if ( StringUtils.isEmpty( modelGroup ) ) { modelGroup = model.getParent().getGroupId(); // depends on control dependency: [if], data = [none] } else { // MENFORCER-30, handle cases where the value is a property like ${project.parent.groupId} modelGroup = (String) helper.evaluate( modelGroup ); // depends on control dependency: [if], data = [none] } if ( StringUtils.isEmpty( modelVersion ) ) { modelVersion = model.getParent().getVersion(); // depends on control dependency: [if], data = [none] } else { // MENFORCER-30, handle cases where the value is a property like ${project.parent.version} modelVersion = (String) helper.evaluate( modelVersion ); // depends on control dependency: [if], data = [none] } // Is this only required for Maven2? modelArtifactId = (String) helper.evaluate( modelArtifactId ); // depends on control dependency: [try], data = [none] } catch ( NullPointerException e ) { // this is probably bad. I don't have a valid // group or version and I can't find a // parent???? // lets see if it's what we're looking for // anyway. } // depends on control dependency: [catch], data = [none] catch ( ExpressionEvaluationException e ) { // as above } // depends on control dependency: [catch], data = [none] return ( StringUtils.equals( groupId, modelGroup ) && StringUtils.equals( version, modelVersion ) && StringUtils .equals( artifactId, modelArtifactId ) ); } }
public class class_name { public final QueryProgram grandQuery() throws RecognitionException { QueryProgram program = null; Token j=null; Token a=null; QueryMeta s1 =null; QueryMeta s2 =null; program = null; try { // druidG.g:136:2: ( (s1= queryStmnt ) ( WS j= ( JOIN | LEFT_JOIN | RIGHT_JOIN ) ( WS )? LPARAN ( WS )? (s2= queryStmnt ) ( WS )? RPARAN ( WS )? ON ( WS )? LPARAN ( WS )? (a= ID ) ( ( WS )? ',' ( WS )? a= ID )* ( WS )? RPARAN )? ( WS )? ( OPT_SEMI_COLON )? ) // druidG.g:136:4: (s1= queryStmnt ) ( WS j= ( JOIN | LEFT_JOIN | RIGHT_JOIN ) ( WS )? LPARAN ( WS )? (s2= queryStmnt ) ( WS )? RPARAN ( WS )? ON ( WS )? LPARAN ( WS )? (a= ID ) ( ( WS )? ',' ( WS )? a= ID )* ( WS )? RPARAN )? ( WS )? ( OPT_SEMI_COLON )? { // druidG.g:136:4: (s1= queryStmnt ) // druidG.g:136:5: s1= queryStmnt { pushFollow(FOLLOW_queryStmnt_in_grandQuery1034); s1=queryStmnt(); state._fsp--; } program = new QueryProgram();program.addStmnt(s1); // druidG.g:137:4: ( WS j= ( JOIN | LEFT_JOIN | RIGHT_JOIN ) ( WS )? LPARAN ( WS )? (s2= queryStmnt ) ( WS )? RPARAN ( WS )? ON ( WS )? LPARAN ( WS )? (a= ID ) ( ( WS )? ',' ( WS )? a= ID )* ( WS )? RPARAN )? int alt95=2; int LA95_0 = input.LA(1); if ( (LA95_0==WS) ) { int LA95_1 = input.LA(2); if ( (LA95_1==JOIN||LA95_1==LEFT_JOIN||LA95_1==RIGHT_JOIN) ) { alt95=1; } } switch (alt95) { case 1 : // druidG.g:137:5: WS j= ( JOIN | LEFT_JOIN | RIGHT_JOIN ) ( WS )? LPARAN ( WS )? (s2= queryStmnt ) ( WS )? RPARAN ( WS )? ON ( WS )? LPARAN ( WS )? (a= ID ) ( ( WS )? ',' ( WS )? a= ID )* ( WS )? RPARAN { match(input,WS,FOLLOW_WS_in_grandQuery1044); j=input.LT(1); if ( input.LA(1)==JOIN||input.LA(1)==LEFT_JOIN||input.LA(1)==RIGHT_JOIN ) { input.consume(); state.errorRecovery=false; } else { MismatchedSetException mse = new MismatchedSetException(null,input); throw mse; } program.addJoinType((j!=null?j.getText():null).toUpperCase()); // druidG.g:139:5: ( WS )? int alt85=2; int LA85_0 = input.LA(1); if ( (LA85_0==WS) ) { alt85=1; } switch (alt85) { case 1 : // druidG.g:139:5: WS { match(input,WS,FOLLOW_WS_in_grandQuery1069); } break; } match(input,LPARAN,FOLLOW_LPARAN_in_grandQuery1072); // druidG.g:139:16: ( WS )? int alt86=2; int LA86_0 = input.LA(1); if ( (LA86_0==WS) ) { alt86=1; } switch (alt86) { case 1 : // druidG.g:139:16: WS { match(input,WS,FOLLOW_WS_in_grandQuery1074); } break; } // druidG.g:139:20: (s2= queryStmnt ) // druidG.g:139:21: s2= queryStmnt { pushFollow(FOLLOW_queryStmnt_in_grandQuery1080); s2=queryStmnt(); state._fsp--; } program.addStmnt(s2); // druidG.g:139:60: ( WS )? int alt87=2; int LA87_0 = input.LA(1); if ( (LA87_0==WS) ) { alt87=1; } switch (alt87) { case 1 : // druidG.g:139:60: WS { match(input,WS,FOLLOW_WS_in_grandQuery1085); } break; } match(input,RPARAN,FOLLOW_RPARAN_in_grandQuery1088); // druidG.g:139:71: ( WS )? int alt88=2; int LA88_0 = input.LA(1); if ( (LA88_0==WS) ) { alt88=1; } switch (alt88) { case 1 : // druidG.g:139:71: WS { match(input,WS,FOLLOW_WS_in_grandQuery1090); } break; } match(input,ON,FOLLOW_ON_in_grandQuery1093); // druidG.g:140:5: ( WS )? int alt89=2; int LA89_0 = input.LA(1); if ( (LA89_0==WS) ) { alt89=1; } switch (alt89) { case 1 : // druidG.g:140:5: WS { match(input,WS,FOLLOW_WS_in_grandQuery1100); } break; } match(input,LPARAN,FOLLOW_LPARAN_in_grandQuery1103); // druidG.g:140:16: ( WS )? int alt90=2; int LA90_0 = input.LA(1); if ( (LA90_0==WS) ) { alt90=1; } switch (alt90) { case 1 : // druidG.g:140:16: WS { match(input,WS,FOLLOW_WS_in_grandQuery1105); } break; } // druidG.g:140:20: (a= ID ) // druidG.g:140:21: a= ID { a=(Token)match(input,ID,FOLLOW_ID_in_grandQuery1111); program.addJoinHook((a!=null?a.getText():null)); } // druidG.g:140:60: ( ( WS )? ',' ( WS )? a= ID )* loop93: while (true) { int alt93=2; int LA93_0 = input.LA(1); if ( (LA93_0==WS) ) { int LA93_1 = input.LA(2); if ( (LA93_1==91) ) { alt93=1; } } else if ( (LA93_0==91) ) { alt93=1; } switch (alt93) { case 1 : // druidG.g:140:61: ( WS )? ',' ( WS )? a= ID { // druidG.g:140:61: ( WS )? int alt91=2; int LA91_0 = input.LA(1); if ( (LA91_0==WS) ) { alt91=1; } switch (alt91) { case 1 : // druidG.g:140:61: WS { match(input,WS,FOLLOW_WS_in_grandQuery1116); } break; } match(input,91,FOLLOW_91_in_grandQuery1119); // druidG.g:140:69: ( WS )? int alt92=2; int LA92_0 = input.LA(1); if ( (LA92_0==WS) ) { alt92=1; } switch (alt92) { case 1 : // druidG.g:140:69: WS { match(input,WS,FOLLOW_WS_in_grandQuery1121); } break; } a=(Token)match(input,ID,FOLLOW_ID_in_grandQuery1126); program.addJoinHook((a!=null?a.getText():null)); } break; default : break loop93; } } // druidG.g:140:114: ( WS )? int alt94=2; int LA94_0 = input.LA(1); if ( (LA94_0==WS) ) { alt94=1; } switch (alt94) { case 1 : // druidG.g:140:114: WS { match(input,WS,FOLLOW_WS_in_grandQuery1132); } break; } match(input,RPARAN,FOLLOW_RPARAN_in_grandQuery1135); } break; } // druidG.g:142:4: ( WS )? int alt96=2; int LA96_0 = input.LA(1); if ( (LA96_0==WS) ) { alt96=1; } switch (alt96) { case 1 : // druidG.g:142:4: WS { match(input,WS,FOLLOW_WS_in_grandQuery1154); } break; } // druidG.g:142:8: ( OPT_SEMI_COLON )? int alt97=2; int LA97_0 = input.LA(1); if ( (LA97_0==OPT_SEMI_COLON) ) { alt97=1; } switch (alt97) { case 1 : // druidG.g:142:8: OPT_SEMI_COLON { match(input,OPT_SEMI_COLON,FOLLOW_OPT_SEMI_COLON_in_grandQuery1157); } break; } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return program; } }
public class class_name { public final QueryProgram grandQuery() throws RecognitionException { QueryProgram program = null; Token j=null; Token a=null; QueryMeta s1 =null; QueryMeta s2 =null; program = null; try { // druidG.g:136:2: ( (s1= queryStmnt ) ( WS j= ( JOIN | LEFT_JOIN | RIGHT_JOIN ) ( WS )? LPARAN ( WS )? (s2= queryStmnt ) ( WS )? RPARAN ( WS )? ON ( WS )? LPARAN ( WS )? (a= ID ) ( ( WS )? ',' ( WS )? a= ID )* ( WS )? RPARAN )? ( WS )? ( OPT_SEMI_COLON )? ) // druidG.g:136:4: (s1= queryStmnt ) ( WS j= ( JOIN | LEFT_JOIN | RIGHT_JOIN ) ( WS )? LPARAN ( WS )? (s2= queryStmnt ) ( WS )? RPARAN ( WS )? ON ( WS )? LPARAN ( WS )? (a= ID ) ( ( WS )? ',' ( WS )? a= ID )* ( WS )? RPARAN )? ( WS )? ( OPT_SEMI_COLON )? { // druidG.g:136:4: (s1= queryStmnt ) // druidG.g:136:5: s1= queryStmnt { pushFollow(FOLLOW_queryStmnt_in_grandQuery1034); s1=queryStmnt(); state._fsp--; } program = new QueryProgram();program.addStmnt(s1); // druidG.g:137:4: ( WS j= ( JOIN | LEFT_JOIN | RIGHT_JOIN ) ( WS )? LPARAN ( WS )? (s2= queryStmnt ) ( WS )? RPARAN ( WS )? ON ( WS )? LPARAN ( WS )? (a= ID ) ( ( WS )? ',' ( WS )? a= ID )* ( WS )? RPARAN )? int alt95=2; int LA95_0 = input.LA(1); if ( (LA95_0==WS) ) { int LA95_1 = input.LA(2); if ( (LA95_1==JOIN||LA95_1==LEFT_JOIN||LA95_1==RIGHT_JOIN) ) { alt95=1; // depends on control dependency: [if], data = [none] } } switch (alt95) { case 1 : // druidG.g:137:5: WS j= ( JOIN | LEFT_JOIN | RIGHT_JOIN ) ( WS )? LPARAN ( WS )? (s2= queryStmnt ) ( WS )? RPARAN ( WS )? ON ( WS )? LPARAN ( WS )? (a= ID ) ( ( WS )? ',' ( WS )? a= ID )* ( WS )? RPARAN { match(input,WS,FOLLOW_WS_in_grandQuery1044); j=input.LT(1); if ( input.LA(1)==JOIN||input.LA(1)==LEFT_JOIN||input.LA(1)==RIGHT_JOIN ) { input.consume(); // depends on control dependency: [if], data = [none] state.errorRecovery=false; // depends on control dependency: [if], data = [none] } else { MismatchedSetException mse = new MismatchedSetException(null,input); throw mse; } program.addJoinType((j!=null?j.getText():null).toUpperCase()); // druidG.g:139:5: ( WS )? int alt85=2; int LA85_0 = input.LA(1); if ( (LA85_0==WS) ) { alt85=1; // depends on control dependency: [if], data = [none] } switch (alt85) { case 1 : // druidG.g:139:5: WS { match(input,WS,FOLLOW_WS_in_grandQuery1069); } break; } match(input,LPARAN,FOLLOW_LPARAN_in_grandQuery1072); // druidG.g:139:16: ( WS )? int alt86=2; int LA86_0 = input.LA(1); if ( (LA86_0==WS) ) { alt86=1; // depends on control dependency: [if], data = [none] } switch (alt86) { case 1 : // druidG.g:139:16: WS { match(input,WS,FOLLOW_WS_in_grandQuery1074); } break; } // druidG.g:139:20: (s2= queryStmnt ) // druidG.g:139:21: s2= queryStmnt { pushFollow(FOLLOW_queryStmnt_in_grandQuery1080); s2=queryStmnt(); state._fsp--; } program.addStmnt(s2); // druidG.g:139:60: ( WS )? int alt87=2; int LA87_0 = input.LA(1); if ( (LA87_0==WS) ) { alt87=1; // depends on control dependency: [if], data = [none] } switch (alt87) { case 1 : // druidG.g:139:60: WS { match(input,WS,FOLLOW_WS_in_grandQuery1085); } break; } match(input,RPARAN,FOLLOW_RPARAN_in_grandQuery1088); // druidG.g:139:71: ( WS )? int alt88=2; int LA88_0 = input.LA(1); if ( (LA88_0==WS) ) { alt88=1; // depends on control dependency: [if], data = [none] } switch (alt88) { case 1 : // druidG.g:139:71: WS { match(input,WS,FOLLOW_WS_in_grandQuery1090); } break; } match(input,ON,FOLLOW_ON_in_grandQuery1093); // druidG.g:140:5: ( WS )? int alt89=2; int LA89_0 = input.LA(1); if ( (LA89_0==WS) ) { alt89=1; // depends on control dependency: [if], data = [none] } switch (alt89) { case 1 : // druidG.g:140:5: WS { match(input,WS,FOLLOW_WS_in_grandQuery1100); } break; } match(input,LPARAN,FOLLOW_LPARAN_in_grandQuery1103); // druidG.g:140:16: ( WS )? int alt90=2; int LA90_0 = input.LA(1); if ( (LA90_0==WS) ) { alt90=1; // depends on control dependency: [if], data = [none] } switch (alt90) { case 1 : // druidG.g:140:16: WS { match(input,WS,FOLLOW_WS_in_grandQuery1105); } break; } // druidG.g:140:20: (a= ID ) // druidG.g:140:21: a= ID { a=(Token)match(input,ID,FOLLOW_ID_in_grandQuery1111); program.addJoinHook((a!=null?a.getText():null)); } // druidG.g:140:60: ( ( WS )? ',' ( WS )? a= ID )* loop93: while (true) { int alt93=2; int LA93_0 = input.LA(1); if ( (LA93_0==WS) ) { int LA93_1 = input.LA(2); if ( (LA93_1==91) ) { alt93=1; // depends on control dependency: [if], data = [none] } } else if ( (LA93_0==91) ) { alt93=1; // depends on control dependency: [if], data = [none] } switch (alt93) { case 1 : // druidG.g:140:61: ( WS )? ',' ( WS )? a= ID { // druidG.g:140:61: ( WS )? int alt91=2; int LA91_0 = input.LA(1); if ( (LA91_0==WS) ) { alt91=1; // depends on control dependency: [if], data = [none] } switch (alt91) { case 1 : // druidG.g:140:61: WS { match(input,WS,FOLLOW_WS_in_grandQuery1116); } break; } match(input,91,FOLLOW_91_in_grandQuery1119); // druidG.g:140:69: ( WS )? int alt92=2; int LA92_0 = input.LA(1); if ( (LA92_0==WS) ) { alt92=1; // depends on control dependency: [if], data = [none] } switch (alt92) { case 1 : // druidG.g:140:69: WS { match(input,WS,FOLLOW_WS_in_grandQuery1121); } break; } a=(Token)match(input,ID,FOLLOW_ID_in_grandQuery1126); program.addJoinHook((a!=null?a.getText():null)); } break; default : break loop93; } } // druidG.g:140:114: ( WS )? int alt94=2; int LA94_0 = input.LA(1); if ( (LA94_0==WS) ) { alt94=1; // depends on control dependency: [if], data = [none] } switch (alt94) { case 1 : // druidG.g:140:114: WS { match(input,WS,FOLLOW_WS_in_grandQuery1132); } break; } match(input,RPARAN,FOLLOW_RPARAN_in_grandQuery1135); } break; } // druidG.g:142:4: ( WS )? int alt96=2; int LA96_0 = input.LA(1); if ( (LA96_0==WS) ) { alt96=1; // depends on control dependency: [if], data = [none] } switch (alt96) { case 1 : // druidG.g:142:4: WS { match(input,WS,FOLLOW_WS_in_grandQuery1154); } break; } // druidG.g:142:8: ( OPT_SEMI_COLON )? int alt97=2; int LA97_0 = input.LA(1); if ( (LA97_0==OPT_SEMI_COLON) ) { alt97=1; // depends on control dependency: [if], data = [none] } switch (alt97) { case 1 : // druidG.g:142:8: OPT_SEMI_COLON { match(input,OPT_SEMI_COLON,FOLLOW_OPT_SEMI_COLON_in_grandQuery1157); } break; } } } catch (RecognitionException re) { reportError(re); recover(input,re); } finally { // do for sure before leaving } return program; } }
public class class_name { public static DependsOn findAllowedByName(final List<DependsOn> allowed, final String pkgName) { if (allowed == null) { return null; } Utils4J.checkNotNull("pkgName", pkgName); for (int i = 0; i < allowed.size(); i++) { final DependsOn dep = allowed.get(i); if (pkgName.startsWith(dep.getPackageName())) { if (dep.isIncludeSubPackages()) { return dep; } else { if (pkgName.equals(dep.getPackageName())) { return dep; } } } } return null; } }
public class class_name { public static DependsOn findAllowedByName(final List<DependsOn> allowed, final String pkgName) { if (allowed == null) { return null; // depends on control dependency: [if], data = [none] } Utils4J.checkNotNull("pkgName", pkgName); for (int i = 0; i < allowed.size(); i++) { final DependsOn dep = allowed.get(i); if (pkgName.startsWith(dep.getPackageName())) { if (dep.isIncludeSubPackages()) { return dep; // depends on control dependency: [if], data = [none] } else { if (pkgName.equals(dep.getPackageName())) { return dep; // depends on control dependency: [if], data = [none] } } } } return null; } }
public class class_name { private void run() { onStart(); while (!isStopping && crawlFrontier.hasNextCandidate()) { CrawlCandidate currentCandidate = crawlFrontier.getNextCandidate(); String candidateUrl = currentCandidate.getRequestUrl().toString(); HttpClientContext context = HttpClientContext.create(); CloseableHttpResponse httpHeadResponse = null; boolean isUnsuccessfulRequest = false; try { // Send an HTTP HEAD request to determine its availability and content type httpHeadResponse = getHttpHeadResponse(candidateUrl, context); } catch (IOException exception) { callbackManager.call(CrawlEvent.REQUEST_ERROR, new RequestErrorEvent(currentCandidate, exception)); isUnsuccessfulRequest = true; } if (!isUnsuccessfulRequest) { String responseUrl = getFinalResponseUrl(context, candidateUrl); if (responseUrl.equals(candidateUrl)) { String responseMimeType = getResponseMimeType(httpHeadResponse); if (responseMimeType.equals(ContentType.TEXT_HTML.getMimeType())) { boolean isTimedOut = false; TimeoutException timeoutException = null; try { // Open URL in browser webDriver.get(candidateUrl); } catch (TimeoutException exception) { isTimedOut = true; timeoutException = exception; } // Ensure the HTTP client and Selenium have the same state syncHttpClientCookies(); if (isTimedOut) { callbackManager.call(CrawlEvent.PAGE_LOAD_TIMEOUT, new PageLoadTimeoutEvent(currentCandidate, timeoutException)); } else { String loadedPageUrl = webDriver.getCurrentUrl(); if (!loadedPageUrl.equals(candidateUrl)) { // Create a new crawl request for the redirected URL (JS redirect) handleRequestRedirect(currentCandidate, loadedPageUrl); } else { callbackManager.call(CrawlEvent.PAGE_LOAD, new PageLoadEvent(currentCandidate, webDriver)); } } } else { // URLs that point to non-HTML content should not be opened in the browser callbackManager.call(CrawlEvent.NON_HTML_CONTENT, new NonHtmlContentEvent(currentCandidate, responseMimeType)); } } else { // Create a new crawl request for the redirected URL handleRequestRedirect(currentCandidate, responseUrl); } } HttpClientUtils.closeQuietly(httpHeadResponse); performDelay(); } onStop(); } }
public class class_name { private void run() { onStart(); while (!isStopping && crawlFrontier.hasNextCandidate()) { CrawlCandidate currentCandidate = crawlFrontier.getNextCandidate(); String candidateUrl = currentCandidate.getRequestUrl().toString(); HttpClientContext context = HttpClientContext.create(); CloseableHttpResponse httpHeadResponse = null; boolean isUnsuccessfulRequest = false; try { // Send an HTTP HEAD request to determine its availability and content type httpHeadResponse = getHttpHeadResponse(candidateUrl, context); // depends on control dependency: [try], data = [none] } catch (IOException exception) { callbackManager.call(CrawlEvent.REQUEST_ERROR, new RequestErrorEvent(currentCandidate, exception)); isUnsuccessfulRequest = true; } // depends on control dependency: [catch], data = [none] if (!isUnsuccessfulRequest) { String responseUrl = getFinalResponseUrl(context, candidateUrl); if (responseUrl.equals(candidateUrl)) { String responseMimeType = getResponseMimeType(httpHeadResponse); if (responseMimeType.equals(ContentType.TEXT_HTML.getMimeType())) { boolean isTimedOut = false; TimeoutException timeoutException = null; try { // Open URL in browser webDriver.get(candidateUrl); // depends on control dependency: [try], data = [none] } catch (TimeoutException exception) { isTimedOut = true; timeoutException = exception; } // depends on control dependency: [catch], data = [none] // Ensure the HTTP client and Selenium have the same state syncHttpClientCookies(); // depends on control dependency: [if], data = [none] if (isTimedOut) { callbackManager.call(CrawlEvent.PAGE_LOAD_TIMEOUT, new PageLoadTimeoutEvent(currentCandidate, timeoutException)); // depends on control dependency: [if], data = [none] } else { String loadedPageUrl = webDriver.getCurrentUrl(); if (!loadedPageUrl.equals(candidateUrl)) { // Create a new crawl request for the redirected URL (JS redirect) handleRequestRedirect(currentCandidate, loadedPageUrl); // depends on control dependency: [if], data = [none] } else { callbackManager.call(CrawlEvent.PAGE_LOAD, new PageLoadEvent(currentCandidate, webDriver)); // depends on control dependency: [if], data = [none] } } } else { // URLs that point to non-HTML content should not be opened in the browser callbackManager.call(CrawlEvent.NON_HTML_CONTENT, new NonHtmlContentEvent(currentCandidate, responseMimeType)); // depends on control dependency: [if], data = [none] } } else { // Create a new crawl request for the redirected URL handleRequestRedirect(currentCandidate, responseUrl); // depends on control dependency: [if], data = [none] } } HttpClientUtils.closeQuietly(httpHeadResponse); // depends on control dependency: [while], data = [none] performDelay(); // depends on control dependency: [while], data = [none] } onStop(); } }
public class class_name { @Deprecated public static void markForDeletion(UIComponent component) { // flag this component as deleted component.getAttributes().put(MARK_DELETED, Boolean.TRUE); Iterator<UIComponent> iter = component.getFacetsAndChildren(); while (iter.hasNext()) { UIComponent child = iter.next(); if (child.getAttributes().containsKey(MARK_CREATED)) { child.getAttributes().put(MARK_DELETED, Boolean.TRUE); } } } }
public class class_name { @Deprecated public static void markForDeletion(UIComponent component) { // flag this component as deleted component.getAttributes().put(MARK_DELETED, Boolean.TRUE); Iterator<UIComponent> iter = component.getFacetsAndChildren(); while (iter.hasNext()) { UIComponent child = iter.next(); if (child.getAttributes().containsKey(MARK_CREATED)) { child.getAttributes().put(MARK_DELETED, Boolean.TRUE); // depends on control dependency: [if], data = [none] } } } }
public class class_name { @Override public boolean visit(VariableDeclarationStatement node) { for (int i = 0; i < node.fragments().size(); ++i) { String nodeType = node.getType().toString(); VariableDeclarationFragment frag = (VariableDeclarationFragment) node.fragments().get(i); state.getNames().add(frag.getName().getIdentifier()); state.getNameInstance().put(frag.getName().toString(), nodeType.toString()); } processType(node.getType(), TypeReferenceLocation.VARIABLE_DECLARATION, compilationUnit.getLineNumber(node.getStartPosition()), compilationUnit.getColumnNumber(node.getStartPosition()), node.getLength(), node.toString()); return super.visit(node); } }
public class class_name { @Override public boolean visit(VariableDeclarationStatement node) { for (int i = 0; i < node.fragments().size(); ++i) { String nodeType = node.getType().toString(); VariableDeclarationFragment frag = (VariableDeclarationFragment) node.fragments().get(i); state.getNames().add(frag.getName().getIdentifier()); // depends on control dependency: [for], data = [none] state.getNameInstance().put(frag.getName().toString(), nodeType.toString()); // depends on control dependency: [for], data = [none] } processType(node.getType(), TypeReferenceLocation.VARIABLE_DECLARATION, compilationUnit.getLineNumber(node.getStartPosition()), compilationUnit.getColumnNumber(node.getStartPosition()), node.getLength(), node.toString()); return super.visit(node); } }
public class class_name { public void parseServiceList(String message) { // We expect the service list to be in this format: // *245 service-list window-manager,core,ecmascript-service List<String> services; try { services = ImmutableList.copyOf(Splitter.on(',').split(message.split(" ")[2])); } catch (ArrayIndexOutOfBoundsException e) { connectionHandler.onException( new IllegalStateException(String.format("Invalid service list received: %s", message))); return; } logger.fine(String.format("Available services: %s", services)); connectionHandler.onServiceList(services); if (!services.contains("stp-1")) { connectionHandler.onException(new IllegalStateException("STP/0 is not supported!")); return; } switchToStp1(); } }
public class class_name { public void parseServiceList(String message) { // We expect the service list to be in this format: // *245 service-list window-manager,core,ecmascript-service List<String> services; try { services = ImmutableList.copyOf(Splitter.on(',').split(message.split(" ")[2])); // depends on control dependency: [try], data = [none] } catch (ArrayIndexOutOfBoundsException e) { connectionHandler.onException( new IllegalStateException(String.format("Invalid service list received: %s", message))); return; } // depends on control dependency: [catch], data = [none] logger.fine(String.format("Available services: %s", services)); connectionHandler.onServiceList(services); if (!services.contains("stp-1")) { connectionHandler.onException(new IllegalStateException("STP/0 is not supported!")); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } switchToStp1(); } }
public class class_name { public static String getCanonicalPath(String path) { if (Strings.isBlank(path)) return path; String[] pa = Strings.splitIgnoreBlank(path, "[\\\\/]"); LinkedList<String> paths = new LinkedList<String>(); for (String s : pa) { if ("..".equals(s)) { if (paths.size() > 0) paths.removeLast(); continue; } if (".".equals(s)) { // pass } else { paths.add(s); } } StringBuilder sb = Lang.concat("/", paths); if (path.startsWith("/")) sb.insert(0, '/'); if (path.endsWith("/")) sb.append('/'); return sb.toString(); } }
public class class_name { public static String getCanonicalPath(String path) { if (Strings.isBlank(path)) return path; String[] pa = Strings.splitIgnoreBlank(path, "[\\\\/]"); LinkedList<String> paths = new LinkedList<String>(); for (String s : pa) { if ("..".equals(s)) { if (paths.size() > 0) paths.removeLast(); continue; } if (".".equals(s)) { // pass } else { paths.add(s); // depends on control dependency: [if], data = [none] } } StringBuilder sb = Lang.concat("/", paths); if (path.startsWith("/")) sb.insert(0, '/'); if (path.endsWith("/")) sb.append('/'); return sb.toString(); } }
public class class_name { public static void setDefaultTooltipManager(final TooltipManager tooltipManager) { try { TooltipManager.getInstance(); Reflection.setFieldValue(ClassReflection.getDeclaredField(TooltipManager.class, "instance"), null, tooltipManager); } catch (final ReflectionException exception) { throw new GdxRuntimeException("Unable to set default tooltip manager.", exception); } } }
public class class_name { public static void setDefaultTooltipManager(final TooltipManager tooltipManager) { try { TooltipManager.getInstance(); // depends on control dependency: [try], data = [none] Reflection.setFieldValue(ClassReflection.getDeclaredField(TooltipManager.class, "instance"), null, tooltipManager); // depends on control dependency: [try], data = [none] } catch (final ReflectionException exception) { throw new GdxRuntimeException("Unable to set default tooltip manager.", exception); } // depends on control dependency: [catch], data = [none] } }
public class class_name { static void switchDollarSignPropsToBrackets(Node def, final AbstractCompiler compiler) { checkState(def.isObjectLit() || def.isClassMembers()); for (Node keyNode : def.children()) { Node value = keyNode.getFirstChild(); if (value != null && value.isFunction()) { NodeUtil.visitPostOrder( value.getLastChild(), new NodeUtil.Visitor() { @Override public void visit(Node n) { if (n.isString() && n.getString().equals("$") && n.getParent().isGetProp() && n.getGrandparent().isGetProp()) { Node dollarChildProp = n.getGrandparent(); dollarChildProp.setToken(Token.GETELEM); compiler.reportChangeToEnclosingScope(dollarChildProp); } } }); } } } }
public class class_name { static void switchDollarSignPropsToBrackets(Node def, final AbstractCompiler compiler) { checkState(def.isObjectLit() || def.isClassMembers()); for (Node keyNode : def.children()) { Node value = keyNode.getFirstChild(); if (value != null && value.isFunction()) { NodeUtil.visitPostOrder( value.getLastChild(), new NodeUtil.Visitor() { @Override public void visit(Node n) { if (n.isString() && n.getString().equals("$") && n.getParent().isGetProp() && n.getGrandparent().isGetProp()) { Node dollarChildProp = n.getGrandparent(); dollarChildProp.setToken(Token.GETELEM); // depends on control dependency: [if], data = [none] compiler.reportChangeToEnclosingScope(dollarChildProp); // depends on control dependency: [if], data = [none] } } }); // depends on control dependency: [if], data = [none] } } } }
public class class_name { public void addEmbeddedColumnInfo(EmbeddedColumnInfo embdColumnInfo) { if (this.embeddedColumnMetadatas == null) { this.embeddedColumnMetadatas = new ArrayList<EmbeddedColumnInfo>(); } if (!embeddedColumnMetadatas.contains(embdColumnInfo)) { embeddedColumnMetadatas.add(embdColumnInfo); } } }
public class class_name { public void addEmbeddedColumnInfo(EmbeddedColumnInfo embdColumnInfo) { if (this.embeddedColumnMetadatas == null) { this.embeddedColumnMetadatas = new ArrayList<EmbeddedColumnInfo>(); // depends on control dependency: [if], data = [none] } if (!embeddedColumnMetadatas.contains(embdColumnInfo)) { embeddedColumnMetadatas.add(embdColumnInfo); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void add(Object msg, ChannelPromise promise) { assert ctx.executor().inEventLoop(); if (msg == null) { throw new NullPointerException("msg"); } if (promise == null) { throw new NullPointerException("promise"); } // It is possible for writes to be triggered from removeAndFailAll(). To preserve ordering, // we should add them to the queue and let removeAndFailAll() fail them later. int messageSize = size(msg); PendingWrite write = PendingWrite.newInstance(msg, messageSize, promise); PendingWrite currentTail = tail; if (currentTail == null) { tail = head = write; } else { currentTail.next = write; tail = write; } size ++; bytes += messageSize; tracker.incrementPendingOutboundBytes(write.size); } }
public class class_name { public void add(Object msg, ChannelPromise promise) { assert ctx.executor().inEventLoop(); if (msg == null) { throw new NullPointerException("msg"); } if (promise == null) { throw new NullPointerException("promise"); } // It is possible for writes to be triggered from removeAndFailAll(). To preserve ordering, // we should add them to the queue and let removeAndFailAll() fail them later. int messageSize = size(msg); PendingWrite write = PendingWrite.newInstance(msg, messageSize, promise); PendingWrite currentTail = tail; if (currentTail == null) { tail = head = write; // depends on control dependency: [if], data = [none] } else { currentTail.next = write; // depends on control dependency: [if], data = [none] tail = write; // depends on control dependency: [if], data = [none] } size ++; bytes += messageSize; tracker.incrementPendingOutboundBytes(write.size); } }
public class class_name { public Observable<ServiceResponse<CommandPropertiesInner>> commandWithServiceResponseAsync(String groupName, String serviceName, String projectName, String taskName, CommandPropertiesInner parameters) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (groupName == null) { throw new IllegalArgumentException("Parameter groupName is required and cannot be null."); } if (serviceName == null) { throw new IllegalArgumentException("Parameter serviceName is required and cannot be null."); } if (projectName == null) { throw new IllegalArgumentException("Parameter projectName is required and cannot be null."); } if (taskName == null) { throw new IllegalArgumentException("Parameter taskName is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } if (parameters == null) { throw new IllegalArgumentException("Parameter parameters is required and cannot be null."); } Validator.validate(parameters); return service.command(this.client.subscriptionId(), groupName, serviceName, projectName, taskName, this.client.apiVersion(), parameters, this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<CommandPropertiesInner>>>() { @Override public Observable<ServiceResponse<CommandPropertiesInner>> call(Response<ResponseBody> response) { try { ServiceResponse<CommandPropertiesInner> clientResponse = commandDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } }
public class class_name { public Observable<ServiceResponse<CommandPropertiesInner>> commandWithServiceResponseAsync(String groupName, String serviceName, String projectName, String taskName, CommandPropertiesInner parameters) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (groupName == null) { throw new IllegalArgumentException("Parameter groupName is required and cannot be null."); } if (serviceName == null) { throw new IllegalArgumentException("Parameter serviceName is required and cannot be null."); } if (projectName == null) { throw new IllegalArgumentException("Parameter projectName is required and cannot be null."); } if (taskName == null) { throw new IllegalArgumentException("Parameter taskName is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); } if (parameters == null) { throw new IllegalArgumentException("Parameter parameters is required and cannot be null."); } Validator.validate(parameters); return service.command(this.client.subscriptionId(), groupName, serviceName, projectName, taskName, this.client.apiVersion(), parameters, this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<CommandPropertiesInner>>>() { @Override public Observable<ServiceResponse<CommandPropertiesInner>> call(Response<ResponseBody> response) { try { ServiceResponse<CommandPropertiesInner> clientResponse = commandDelegate(response); return Observable.just(clientResponse); // depends on control dependency: [try], data = [none] } catch (Throwable t) { return Observable.error(t); } // depends on control dependency: [catch], data = [none] } }); } }
public class class_name { public List<String> localText() { List<String> answer = new ArrayList<String>(); for (Iterator iter = InvokerHelper.asIterator(value); iter.hasNext(); ) { Object child = iter.next(); if (!(child instanceof Node)) { answer.add(child.toString()); } } return answer; } }
public class class_name { public List<String> localText() { List<String> answer = new ArrayList<String>(); for (Iterator iter = InvokerHelper.asIterator(value); iter.hasNext(); ) { Object child = iter.next(); if (!(child instanceof Node)) { answer.add(child.toString()); // depends on control dependency: [if], data = [none] } } return answer; } }
public class class_name { public Maybe<ApplicationInfo> getApplicationInfo(String clientId) { return db.findClientCredentials(clientId).map(creds -> { ApplicationInfo appInfo = null; if (creds != null) { appInfo = ApplicationInfo.loadFromClientCredentials(creds); } return appInfo; }); } }
public class class_name { public Maybe<ApplicationInfo> getApplicationInfo(String clientId) { return db.findClientCredentials(clientId).map(creds -> { ApplicationInfo appInfo = null; if (creds != null) { appInfo = ApplicationInfo.loadFromClientCredentials(creds); // depends on control dependency: [if], data = [(creds] } return appInfo; }); } }
public class class_name { @PUT @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Path("/{alertId}/notifications/{notificationId}") @Description("Updates a notification having the given notification ID if associated with the given alert ID.") public NotificationDto updateNotificationById(@Context HttpServletRequest req, @PathParam("alertId") BigInteger alertId, @PathParam("notificationId") BigInteger notificationId, NotificationDto notificationDto) { if (alertId == null || alertId.compareTo(BigInteger.ZERO) < 1) { throw new WebApplicationException("Alert Id cannot be null and must be a positive non-zero number.", Status.BAD_REQUEST); } if (notificationId == null || notificationId.compareTo(BigInteger.ZERO) < 1) { throw new WebApplicationException("Notification Id cannot be null and must be a positive non-zero number.", Status.BAD_REQUEST); } if (notificationDto == null) { throw new WebApplicationException("Null object cannot be updated.", Status.BAD_REQUEST); } PrincipalUser owner = validateAndGetOwner(req, getRemoteUser(req).getUserName()); Alert oldAlert = alertService.findAlertByPrimaryKey(alertId); if (oldAlert == null) { throw new WebApplicationException(Response.Status.NOT_FOUND.getReasonPhrase(), Response.Status.NOT_FOUND); } validateResourceAuthorization(req, oldAlert.getOwner(), owner); for (Notification notification : oldAlert.getNotifications()) { if (notificationId.equals(notification.getId())) { copyProperties(notification, notificationDto); oldAlert.setModifiedBy(getRemoteUser(req)); Alert alert = alertService.updateAlert(oldAlert); int index = alert.getNotifications().indexOf(notification); return NotificationDto.transformToDto(alert.getNotifications().get(index)); } } throw new WebApplicationException("The notification does not exist.", Response.Status.NOT_FOUND); } }
public class class_name { @PUT @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @Path("/{alertId}/notifications/{notificationId}") @Description("Updates a notification having the given notification ID if associated with the given alert ID.") public NotificationDto updateNotificationById(@Context HttpServletRequest req, @PathParam("alertId") BigInteger alertId, @PathParam("notificationId") BigInteger notificationId, NotificationDto notificationDto) { if (alertId == null || alertId.compareTo(BigInteger.ZERO) < 1) { throw new WebApplicationException("Alert Id cannot be null and must be a positive non-zero number.", Status.BAD_REQUEST); } if (notificationId == null || notificationId.compareTo(BigInteger.ZERO) < 1) { throw new WebApplicationException("Notification Id cannot be null and must be a positive non-zero number.", Status.BAD_REQUEST); } if (notificationDto == null) { throw new WebApplicationException("Null object cannot be updated.", Status.BAD_REQUEST); } PrincipalUser owner = validateAndGetOwner(req, getRemoteUser(req).getUserName()); Alert oldAlert = alertService.findAlertByPrimaryKey(alertId); if (oldAlert == null) { throw new WebApplicationException(Response.Status.NOT_FOUND.getReasonPhrase(), Response.Status.NOT_FOUND); } validateResourceAuthorization(req, oldAlert.getOwner(), owner); for (Notification notification : oldAlert.getNotifications()) { if (notificationId.equals(notification.getId())) { copyProperties(notification, notificationDto); // depends on control dependency: [if], data = [none] oldAlert.setModifiedBy(getRemoteUser(req)); // depends on control dependency: [if], data = [none] Alert alert = alertService.updateAlert(oldAlert); int index = alert.getNotifications().indexOf(notification); return NotificationDto.transformToDto(alert.getNotifications().get(index)); // depends on control dependency: [if], data = [none] } } throw new WebApplicationException("The notification does not exist.", Response.Status.NOT_FOUND); } }
public class class_name { private void startPartitions(List<Integer> partitionsToExecute, List<Integer> startedPartitions, List<Integer> finishedPartitions, PartitionPlanDescriptor currentPlan) { while (startedPartitions.size() < partitionsToExecute.size() && startedPartitions.size() - finishedPartitions.size() < currentPlan.getThreads()) { int nextPartitionNumber = partitionsToExecute.get(startedPartitions.size()); PartitionPlanConfig config = buildPartitionPlanConfig(currentPlan, nextPartitionNumber); Boolean nextPartitionStarted = null; StopLock stopLock = getStopLock(); // Store in local variable to facilitate Ctrl+Shift+G search in Eclipse synchronized (stopLock) { nextPartitionStarted = startPartition(config); } if (nextPartitionStarted) { startedPartitions.add(nextPartitionNumber); } else { // The partition wasn't started (probably because we're stopping). // Add the partitionNumber to both the started and finished lists, // so that the while-loop logic works as expected. startedPartitions.add(nextPartitionNumber); finishedPartitions.add(nextPartitionNumber); } } } }
public class class_name { private void startPartitions(List<Integer> partitionsToExecute, List<Integer> startedPartitions, List<Integer> finishedPartitions, PartitionPlanDescriptor currentPlan) { while (startedPartitions.size() < partitionsToExecute.size() && startedPartitions.size() - finishedPartitions.size() < currentPlan.getThreads()) { int nextPartitionNumber = partitionsToExecute.get(startedPartitions.size()); PartitionPlanConfig config = buildPartitionPlanConfig(currentPlan, nextPartitionNumber); Boolean nextPartitionStarted = null; StopLock stopLock = getStopLock(); // Store in local variable to facilitate Ctrl+Shift+G search in Eclipse synchronized (stopLock) { // depends on control dependency: [while], data = [none] nextPartitionStarted = startPartition(config); } if (nextPartitionStarted) { startedPartitions.add(nextPartitionNumber); // depends on control dependency: [if], data = [none] } else { // The partition wasn't started (probably because we're stopping). // Add the partitionNumber to both the started and finished lists, // so that the while-loop logic works as expected. startedPartitions.add(nextPartitionNumber); // depends on control dependency: [if], data = [none] finishedPartitions.add(nextPartitionNumber); // depends on control dependency: [if], data = [none] } } } }
public class class_name { @Override protected void configure() { try { InternalLoggerFactory.setDefaultFactory(new Slf4JLoggerFactory()); File appRoot = new File(System.getProperty(CadmiumListener.BASE_PATH_ENV), "maven"); FileUtils.forceMkdir(appRoot); String remoteMavenRepo = System.getProperty(MAVEN_REPOSITORY); ArtifactResolver resolver = new ArtifactResolver(remoteMavenRepo, appRoot.getAbsolutePath()); bind(ArtifactResolver.class).toInstance(resolver); bind(JBossAdminApi.class); Multibinder<ConfigurationListener> listenerBinder = Multibinder.newSetBinder(binder(), ConfigurationListener.class); listenerBinder.addBinding().to(JBossAdminApi.class); bind(IJBossUtil.class).to(JBossDelegator.class); } catch(Exception e) { logger.error("Failed to initialize maven artifact resolver.", e); } } }
public class class_name { @Override protected void configure() { try { InternalLoggerFactory.setDefaultFactory(new Slf4JLoggerFactory()); // depends on control dependency: [try], data = [none] File appRoot = new File(System.getProperty(CadmiumListener.BASE_PATH_ENV), "maven"); FileUtils.forceMkdir(appRoot); // depends on control dependency: [try], data = [none] String remoteMavenRepo = System.getProperty(MAVEN_REPOSITORY); ArtifactResolver resolver = new ArtifactResolver(remoteMavenRepo, appRoot.getAbsolutePath()); bind(ArtifactResolver.class).toInstance(resolver); // depends on control dependency: [try], data = [none] bind(JBossAdminApi.class); // depends on control dependency: [try], data = [none] Multibinder<ConfigurationListener> listenerBinder = Multibinder.newSetBinder(binder(), ConfigurationListener.class); listenerBinder.addBinding().to(JBossAdminApi.class); // depends on control dependency: [try], data = [none] bind(IJBossUtil.class).to(JBossDelegator.class); // depends on control dependency: [try], data = [none] } catch(Exception e) { logger.error("Failed to initialize maven artifact resolver.", e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { @Override public void destroy( SourcePipe originPipe, List<PipeRunner> pipeRunners, BadRecordsHandler badRecordsHandler, StatsAggregationHandler statsAggregationHandler ) throws StageException, PipelineRuntimeException { // We're no longer running running = false; // There are two ways a runner can be in use - used by real runner (e.g. when origin produced data) or when it's // processing "empty" batch when the runner was idle for too long. The first case is guarded by the framework - this // method won't be called until the execution successfully finished. However the second way with idle drivers is run // from a separate thread and hence we have to ensure here that it's "done" before moving on with the destroy phase. try { destroyLock.lock(); // Firstly destroy the runner, to make sure that any potential run away thread from origin will be denied // further processing. if (runnerPool != null) { runnerPool.destroy(); } int batchSize = configuration.get(Constants.MAX_BATCH_SIZE_KEY, Constants.MAX_BATCH_SIZE_DEFAULT); long lastBatchTime = offsetTracker.getLastBatchTime(); long start = System.currentTimeMillis(); FullPipeBatch pipeBatch; // Destroy origin pipe pipeBatch = new FullPipeBatch(null, null, batchSize, false); try { LOG.trace("Destroying origin pipe"); pipeBatch.skipStage(originPipe); originPipe.destroy(pipeBatch); } catch (RuntimeException e) { LOG.warn("Exception throw while destroying pipe", e); } // Now destroy the pipe runners // // We're destroying them in reverser order to make sure that the last runner to destroy is the one with id '0' // that holds reference to all class loaders. Runners with id >0 do not own their class loaders and hence needs to // be destroyed before the runner with id '0'. for (PipeRunner pipeRunner : Lists.reverse(pipeRunners)) { final FullPipeBatch finalPipeBatch = pipeBatch; pipeRunner.executeBatch(null, null, start, pipe -> { // Set the last batch time in the stage context of each pipe ((StageContext) pipe.getStage().getContext()).setLastBatchTime(lastBatchTime); String instanceName = pipe.getStage().getConfiguration().getInstanceName(); if (pipe instanceof StagePipe) { // Stage pipes are processed only if they are in event path if (pipe.getStage().getConfiguration().isInEventPath()) { LOG.trace("Stage pipe {} is in event path, running last process", instanceName); pipe.process(finalPipeBatch); } else { LOG.trace("Stage pipe {} is in data path, skipping it's processing.", instanceName); finalPipeBatch.skipStage(pipe); } } else { // Non stage pipes are executed always LOG.trace("Non stage pipe {}, running last process", instanceName); pipe.process(finalPipeBatch); } // And finally destroy the pipe try { LOG.trace("Running destroy for {}", instanceName); pipe.destroy(finalPipeBatch); } catch (RuntimeException e) { LOG.warn("Exception throw while destroying pipe", e); } }); badRecordsHandler.handle(null, null, pipeBatch.getErrorSink(), pipeBatch.getSourceResponseSink()); // Next iteration should have new and empty PipeBatch pipeBatch = new FullPipeBatch(null, null, batchSize, false); pipeBatch.skipStage(originPipe); } if (isStatsAggregationEnabled()) { List<Record> stats = new ArrayList<>(); statsAggregatorRequests.drainTo(stats); Object timeSeriesString = pipelineConfigBean.constants.get(MetricsEventRunnable.TIME_SERIES_ANALYSIS); boolean timeSeriesAnalysis = (timeSeriesString != null) ? (Boolean) timeSeriesString : true; String metricRegistryStr; try { metricRegistryStr = ObjectMapperFactory.get().writer().writeValueAsString(metrics); } catch (Exception e) { throw new RuntimeException(Utils.format("Error converting metric json to string: {}", e), e); } LOG.info("Queueing last batch of record to be sent to stats aggregator"); stats.add(AggregatorUtil.createMetricJsonRecord( runtimeInfo.getId(), runtimeInfo.getMasterSDCId(), pipelineConfiguration.getMetadata(), false, timeSeriesAnalysis, true, metricRegistryStr )); statsAggregationHandler.handle(null, null, stats); } } finally { destroyLock.unlock(); } } }
public class class_name { @Override public void destroy( SourcePipe originPipe, List<PipeRunner> pipeRunners, BadRecordsHandler badRecordsHandler, StatsAggregationHandler statsAggregationHandler ) throws StageException, PipelineRuntimeException { // We're no longer running running = false; // There are two ways a runner can be in use - used by real runner (e.g. when origin produced data) or when it's // processing "empty" batch when the runner was idle for too long. The first case is guarded by the framework - this // method won't be called until the execution successfully finished. However the second way with idle drivers is run // from a separate thread and hence we have to ensure here that it's "done" before moving on with the destroy phase. try { destroyLock.lock(); // Firstly destroy the runner, to make sure that any potential run away thread from origin will be denied // further processing. if (runnerPool != null) { runnerPool.destroy(); // depends on control dependency: [if], data = [none] } int batchSize = configuration.get(Constants.MAX_BATCH_SIZE_KEY, Constants.MAX_BATCH_SIZE_DEFAULT); long lastBatchTime = offsetTracker.getLastBatchTime(); long start = System.currentTimeMillis(); FullPipeBatch pipeBatch; // Destroy origin pipe pipeBatch = new FullPipeBatch(null, null, batchSize, false); try { LOG.trace("Destroying origin pipe"); // depends on control dependency: [try], data = [none] pipeBatch.skipStage(originPipe); // depends on control dependency: [try], data = [none] originPipe.destroy(pipeBatch); // depends on control dependency: [try], data = [none] } catch (RuntimeException e) { LOG.warn("Exception throw while destroying pipe", e); } // depends on control dependency: [catch], data = [none] // Now destroy the pipe runners // // We're destroying them in reverser order to make sure that the last runner to destroy is the one with id '0' // that holds reference to all class loaders. Runners with id >0 do not own their class loaders and hence needs to // be destroyed before the runner with id '0'. for (PipeRunner pipeRunner : Lists.reverse(pipeRunners)) { final FullPipeBatch finalPipeBatch = pipeBatch; pipeRunner.executeBatch(null, null, start, pipe -> { // Set the last batch time in the stage context of each pipe ((StageContext) pipe.getStage().getContext()).setLastBatchTime(lastBatchTime); String instanceName = pipe.getStage().getConfiguration().getInstanceName(); if (pipe instanceof StagePipe) { // Stage pipes are processed only if they are in event path if (pipe.getStage().getConfiguration().isInEventPath()) { LOG.trace("Stage pipe {} is in event path, running last process", instanceName); pipe.process(finalPipeBatch); } else { LOG.trace("Stage pipe {} is in data path, skipping it's processing.", instanceName); finalPipeBatch.skipStage(pipe); } } else { // Non stage pipes are executed always LOG.trace("Non stage pipe {}, running last process", instanceName); pipe.process(finalPipeBatch); } // And finally destroy the pipe try { LOG.trace("Running destroy for {}", instanceName); pipe.destroy(finalPipeBatch); } catch (RuntimeException e) { LOG.warn("Exception throw while destroying pipe", e); } }); badRecordsHandler.handle(null, null, pipeBatch.getErrorSink(), pipeBatch.getSourceResponseSink()); // Next iteration should have new and empty PipeBatch pipeBatch = new FullPipeBatch(null, null, batchSize, false); pipeBatch.skipStage(originPipe); } if (isStatsAggregationEnabled()) { List<Record> stats = new ArrayList<>(); statsAggregatorRequests.drainTo(stats); Object timeSeriesString = pipelineConfigBean.constants.get(MetricsEventRunnable.TIME_SERIES_ANALYSIS); boolean timeSeriesAnalysis = (timeSeriesString != null) ? (Boolean) timeSeriesString : true; String metricRegistryStr; try { metricRegistryStr = ObjectMapperFactory.get().writer().writeValueAsString(metrics); } catch (Exception e) { throw new RuntimeException(Utils.format("Error converting metric json to string: {}", e), e); } LOG.info("Queueing last batch of record to be sent to stats aggregator"); stats.add(AggregatorUtil.createMetricJsonRecord( runtimeInfo.getId(), runtimeInfo.getMasterSDCId(), pipelineConfiguration.getMetadata(), false, timeSeriesAnalysis, true, metricRegistryStr )); statsAggregationHandler.handle(null, null, stats); } } finally { destroyLock.unlock(); } } }
public class class_name { public java.util.List<String> getTagKeyList() { if (tagKeyList == null) { tagKeyList = new com.amazonaws.internal.SdkInternalList<String>(); } return tagKeyList; } }
public class class_name { public java.util.List<String> getTagKeyList() { if (tagKeyList == null) { tagKeyList = new com.amazonaws.internal.SdkInternalList<String>(); // depends on control dependency: [if], data = [none] } return tagKeyList; } }
public class class_name { public void setColor(Color newColor) { if (newColor != null) { color.set(newColor); } else { color.set(DefaultColor); } colorF = color.toFloatBits(); if (staticLight) dirty = true; } }
public class class_name { public void setColor(Color newColor) { if (newColor != null) { color.set(newColor); // depends on control dependency: [if], data = [(newColor] } else { color.set(DefaultColor); // depends on control dependency: [if], data = [none] } colorF = color.toFloatBits(); if (staticLight) dirty = true; } }
public class class_name { private void collectVertices(final AbstractJobVertex jv, final List<AbstractJobVertex> collector) { if (jv == null) { final Iterator<AbstractJobInputVertex> iter = getInputVertices(); while (iter.hasNext()) { collectVertices(iter.next(), collector); } } else { if (!collector.contains(jv)) { collector.add(jv); } else { return; } for (int i = 0; i < jv.getNumberOfForwardConnections(); i++) { collectVertices(jv.getForwardConnection(i).getConnectedVertex(), collector); } } } }
public class class_name { private void collectVertices(final AbstractJobVertex jv, final List<AbstractJobVertex> collector) { if (jv == null) { final Iterator<AbstractJobInputVertex> iter = getInputVertices(); while (iter.hasNext()) { collectVertices(iter.next(), collector); // depends on control dependency: [while], data = [none] } } else { if (!collector.contains(jv)) { collector.add(jv); // depends on control dependency: [if], data = [none] } else { return; // depends on control dependency: [if], data = [none] } for (int i = 0; i < jv.getNumberOfForwardConnections(); i++) { collectVertices(jv.getForwardConnection(i).getConnectedVertex(), collector); // depends on control dependency: [for], data = [i] } } } }
public class class_name { public JmxMessage parameter(Object arg, Class<?> argType) { if (mbeanInvocation == null) { throw new CitrusRuntimeException("Invalid access to operation parameter for JMX message"); } if (mbeanInvocation.getOperation() == null) { throw new CitrusRuntimeException("Invalid access to operation parameter before operation was set for JMX message"); } if (mbeanInvocation.getOperation().getParameter() == null) { mbeanInvocation.getOperation().setParameter(new ManagedBeanInvocation.Parameter()); } OperationParam operationParam = new OperationParam(); operationParam.setValueObject(arg); operationParam.setType(argType.getName()); mbeanInvocation.getOperation().getParameter().getParameter().add(operationParam); return this; } }
public class class_name { public JmxMessage parameter(Object arg, Class<?> argType) { if (mbeanInvocation == null) { throw new CitrusRuntimeException("Invalid access to operation parameter for JMX message"); } if (mbeanInvocation.getOperation() == null) { throw new CitrusRuntimeException("Invalid access to operation parameter before operation was set for JMX message"); } if (mbeanInvocation.getOperation().getParameter() == null) { mbeanInvocation.getOperation().setParameter(new ManagedBeanInvocation.Parameter()); // depends on control dependency: [if], data = [none] } OperationParam operationParam = new OperationParam(); operationParam.setValueObject(arg); operationParam.setType(argType.getName()); mbeanInvocation.getOperation().getParameter().getParameter().add(operationParam); return this; } }