code
stringlengths
130
281k
code_dependency
stringlengths
182
306k
public class class_name { private static void unpackFile(InputStream in, File file) { byte[] buffer = new byte[4096]; try { OutputStream out = new FileOutputStream(file); int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); } out.close(); } catch (IOException e) { throw new RuntimeException(e); } } }
public class class_name { private static void unpackFile(InputStream in, File file) { byte[] buffer = new byte[4096]; try { OutputStream out = new FileOutputStream(file); int read; while ((read = in.read(buffer)) != -1) { out.write(buffer, 0, read); // depends on control dependency: [while], data = [none] } out.close(); // depends on control dependency: [try], data = [none] } catch (IOException e) { throw new RuntimeException(e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { protected static boolean getBooleanProperty(TreeLogger logger, PropertyOracle propertyOracle, String propertyName, boolean defaultValue) { try { SelectionProperty prop = propertyOracle.getSelectionProperty(logger, propertyName); String propVal = prop.getCurrentValue(); return Boolean.parseBoolean(propVal); } catch (BadPropertyValueException e) { // return the default value } return defaultValue; } }
public class class_name { protected static boolean getBooleanProperty(TreeLogger logger, PropertyOracle propertyOracle, String propertyName, boolean defaultValue) { try { SelectionProperty prop = propertyOracle.getSelectionProperty(logger, propertyName); String propVal = prop.getCurrentValue(); return Boolean.parseBoolean(propVal); // depends on control dependency: [try], data = [none] } catch (BadPropertyValueException e) { // return the default value } // depends on control dependency: [catch], data = [none] return defaultValue; } }
public class class_name { private static void setMetaStoreURI( Configuration conf, Map<String, String> match) { try { // If the host is set, construct a new MetaStore URI and set the property // in the Configuration. Otherwise, do not change the MetaStore URI. String host = match.get(URIPattern.HOST); if (host != null && !NOT_SET.equals(host)) { int port; try { port = Integer.parseInt(match.get(URIPattern.PORT)); } catch (NumberFormatException e) { port = UNSPECIFIED_PORT; } conf.set(HIVE_METASTORE_URI_PROP, new URI("thrift", null, host, port, null, null, null).toString()); } } catch (URISyntaxException ex) { throw new DatasetOperationException( "Could not build metastore URI", ex); } } }
public class class_name { private static void setMetaStoreURI( Configuration conf, Map<String, String> match) { try { // If the host is set, construct a new MetaStore URI and set the property // in the Configuration. Otherwise, do not change the MetaStore URI. String host = match.get(URIPattern.HOST); if (host != null && !NOT_SET.equals(host)) { int port; try { port = Integer.parseInt(match.get(URIPattern.PORT)); // depends on control dependency: [try], data = [none] } catch (NumberFormatException e) { port = UNSPECIFIED_PORT; } // depends on control dependency: [catch], data = [none] conf.set(HIVE_METASTORE_URI_PROP, new URI("thrift", null, host, port, null, null, null).toString()); // depends on control dependency: [if], data = [none] } } catch (URISyntaxException ex) { throw new DatasetOperationException( "Could not build metastore URI", ex); } // depends on control dependency: [catch], data = [none] } }
public class class_name { static OcAgentTraceServiceExportRpcHandler create(TraceServiceStub stub) { OcAgentTraceServiceExportRpcHandler exportRpcHandler = new OcAgentTraceServiceExportRpcHandler(); ExportResponseObserver exportResponseObserver = new ExportResponseObserver(exportRpcHandler); try { StreamObserver<ExportTraceServiceRequest> exportRequestObserver = stub.export(exportResponseObserver); exportRpcHandler.setExportRequestObserver(exportRequestObserver); } catch (StatusRuntimeException e) { exportRpcHandler.onComplete(e); } return exportRpcHandler; } }
public class class_name { static OcAgentTraceServiceExportRpcHandler create(TraceServiceStub stub) { OcAgentTraceServiceExportRpcHandler exportRpcHandler = new OcAgentTraceServiceExportRpcHandler(); ExportResponseObserver exportResponseObserver = new ExportResponseObserver(exportRpcHandler); try { StreamObserver<ExportTraceServiceRequest> exportRequestObserver = stub.export(exportResponseObserver); exportRpcHandler.setExportRequestObserver(exportRequestObserver); // depends on control dependency: [try], data = [none] } catch (StatusRuntimeException e) { exportRpcHandler.onComplete(e); } // depends on control dependency: [catch], data = [none] return exportRpcHandler; } }
public class class_name { private static int getStyle(TextStyle style) { final int value; if (TextStyle.NORMAL == style) { value = Font.TRUETYPE_FONT; } else if (TextStyle.BOLD == style) { value = Font.BOLD; } else if (TextStyle.ITALIC == style) { value = Font.ITALIC; } else { throw new LionEngineException(style); } return value; } }
public class class_name { private static int getStyle(TextStyle style) { final int value; if (TextStyle.NORMAL == style) { value = Font.TRUETYPE_FONT; // depends on control dependency: [if], data = [none] } else if (TextStyle.BOLD == style) { value = Font.BOLD; // depends on control dependency: [if], data = [none] } else if (TextStyle.ITALIC == style) { value = Font.ITALIC; // depends on control dependency: [if], data = [none] } else { throw new LionEngineException(style); } return value; } }
public class class_name { public static void registerSubscription(Subscription subscription) { mSubscriptions.add(subscription); if (isConnected()) { executeQuery(subscription.getQuery()); } } }
public class class_name { public static void registerSubscription(Subscription subscription) { mSubscriptions.add(subscription); if (isConnected()) { executeQuery(subscription.getQuery()); // depends on control dependency: [if], data = [none] } } }
public class class_name { public Vector3f orthogonalize(Vector3fc v, Vector3f dest) { /* * http://lolengine.net/blog/2013/09/21/picking-orthogonal-vector-combing-coconuts */ float rx, ry, rz; if (Math.abs(v.x()) > Math.abs(v.z())) { rx = -v.y(); ry = v.x(); rz = 0.0f; } else { rx = 0.0f; ry = -v.z(); rz = v.y(); } float invLen = 1.0f / (float) Math.sqrt(rx * rx + ry * ry + rz * rz); dest.x = rx * invLen; dest.y = ry * invLen; dest.z = rz * invLen; return dest; } }
public class class_name { public Vector3f orthogonalize(Vector3fc v, Vector3f dest) { /* * http://lolengine.net/blog/2013/09/21/picking-orthogonal-vector-combing-coconuts */ float rx, ry, rz; if (Math.abs(v.x()) > Math.abs(v.z())) { rx = -v.y(); // depends on control dependency: [if], data = [none] ry = v.x(); // depends on control dependency: [if], data = [none] rz = 0.0f; // depends on control dependency: [if], data = [none] } else { rx = 0.0f; // depends on control dependency: [if], data = [none] ry = -v.z(); // depends on control dependency: [if], data = [none] rz = v.y(); // depends on control dependency: [if], data = [none] } float invLen = 1.0f / (float) Math.sqrt(rx * rx + ry * ry + rz * rz); dest.x = rx * invLen; dest.y = ry * invLen; dest.z = rz * invLen; return dest; } }
public class class_name { private void updateServiceLocalCache() { try { LOG.info("Update local cache now..."); zkClient.getChildren(NaviCommonConstant.ZOOKEEPER_BASE_PATH); LOG.info("Zookeeper global root path is " + NaviCommonConstant.ZOOKEEPER_BASE_PATH); ServiceLocalCache.prepare(); if (ArrayUtil.isEmpty(RpcClientConf.ZK_WATCH_NAMESPACE_PATHS)) { LOG.info("Zookeeper watched name space is empty"); return; } LOG.info("Zookeeper watched name spaces are " + Arrays.toString(RpcClientConf.ZK_WATCH_NAMESPACE_PATHS)); for (String watchedNameSpacePath : RpcClientConf.ZK_WATCH_NAMESPACE_PATHS) { try { List<String> serviceChildren = zkClient.getChildren(ZkPathUtil.buildPath( NaviCommonConstant.ZOOKEEPER_BASE_PATH, watchedNameSpacePath)); LOG.info("======>Find " + serviceChildren.size() + " interfaces under service path - " + ZkPathUtil.buildPath(NaviCommonConstant.ZOOKEEPER_BASE_PATH, watchedNameSpacePath)); if (CollectionUtil.isNotEmpty(serviceChildren)) { for (String service : serviceChildren) { String servicePath = ZkPathUtil.buildPath( NaviCommonConstant.ZOOKEEPER_BASE_PATH, watchedNameSpacePath, service); List<String> serverList = zkClient.getChildren(servicePath); LOG.info(serverList.size() + " servers available for " + servicePath + ", server list = " + Arrays.toString(serverList.toArray(new String[] {}))); if (CollectionUtil.isNotEmpty(serverList)) { Collections.sort(serverList); // order by natural ServiceLocalCache.set(servicePath, serverList); } } } else { LOG.warn("No services registered"); } } catch (NoAuthException e) { LOG.error( "[FATAL ERROR]No auth error! Please check zookeeper digest auth code!!! " + e.getMessage(), e); } catch (NoNodeException e) { LOG.error("Node not found, " + e.getMessage()); } } ServiceLocalCache.switchCache(); } catch (Exception e) { LOG.error(e.getMessage(), e); } finally { try { ServiceLocalCache.done(); } catch (Exception e2) { LOG.error(e2.getMessage(), e2); } } } }
public class class_name { private void updateServiceLocalCache() { try { LOG.info("Update local cache now..."); // depends on control dependency: [try], data = [none] zkClient.getChildren(NaviCommonConstant.ZOOKEEPER_BASE_PATH); // depends on control dependency: [try], data = [none] LOG.info("Zookeeper global root path is " + NaviCommonConstant.ZOOKEEPER_BASE_PATH); // depends on control dependency: [try], data = [none] ServiceLocalCache.prepare(); // depends on control dependency: [try], data = [none] if (ArrayUtil.isEmpty(RpcClientConf.ZK_WATCH_NAMESPACE_PATHS)) { LOG.info("Zookeeper watched name space is empty"); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } LOG.info("Zookeeper watched name spaces are " + Arrays.toString(RpcClientConf.ZK_WATCH_NAMESPACE_PATHS)); // depends on control dependency: [try], data = [none] for (String watchedNameSpacePath : RpcClientConf.ZK_WATCH_NAMESPACE_PATHS) { try { List<String> serviceChildren = zkClient.getChildren(ZkPathUtil.buildPath( NaviCommonConstant.ZOOKEEPER_BASE_PATH, watchedNameSpacePath)); LOG.info("======>Find " + serviceChildren.size() + " interfaces under service path - " // depends on control dependency: [try], data = [none] + ZkPathUtil.buildPath(NaviCommonConstant.ZOOKEEPER_BASE_PATH, watchedNameSpacePath)); // depends on control dependency: [try], data = [none] if (CollectionUtil.isNotEmpty(serviceChildren)) { for (String service : serviceChildren) { String servicePath = ZkPathUtil.buildPath( NaviCommonConstant.ZOOKEEPER_BASE_PATH, watchedNameSpacePath, service); List<String> serverList = zkClient.getChildren(servicePath); LOG.info(serverList.size() + " servers available for " + servicePath + ", server list = " + Arrays.toString(serverList.toArray(new String[] {}))); // depends on control dependency: [for], data = [service] if (CollectionUtil.isNotEmpty(serverList)) { Collections.sort(serverList); // order by natural // depends on control dependency: [if], data = [none] ServiceLocalCache.set(servicePath, serverList); // depends on control dependency: [if], data = [none] } } } else { LOG.warn("No services registered"); // depends on control dependency: [if], data = [none] } } catch (NoAuthException e) { LOG.error( "[FATAL ERROR]No auth error! Please check zookeeper digest auth code!!! " + e.getMessage(), e); } catch (NoNodeException e) { // depends on control dependency: [catch], data = [none] LOG.error("Node not found, " + e.getMessage()); } // depends on control dependency: [catch], data = [none] } ServiceLocalCache.switchCache(); // depends on control dependency: [try], data = [none] } catch (Exception e) { LOG.error(e.getMessage(), e); } finally { // depends on control dependency: [catch], data = [none] try { ServiceLocalCache.done(); // depends on control dependency: [try], data = [none] } catch (Exception e2) { LOG.error(e2.getMessage(), e2); } // depends on control dependency: [catch], data = [none] } } }
public class class_name { public static Object createOptional(final Object value) { if ((OPTIONAL_CLASS == null) || (OFNULLABLE == null)) { throw new IllegalStateException("Unreachable Code executed. You just found a bug. Please report!"); } try { return OFNULLABLE.invoke(null, value); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } } }
public class class_name { public static Object createOptional(final Object value) { if ((OPTIONAL_CLASS == null) || (OFNULLABLE == null)) { throw new IllegalStateException("Unreachable Code executed. You just found a bug. Please report!"); } try { return OFNULLABLE.invoke(null, value); // depends on control dependency: [try], data = [none] } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { // depends on control dependency: [catch], data = [none] throw new RuntimeException(e); } catch (InvocationTargetException e) { // depends on control dependency: [catch], data = [none] throw new RuntimeException(e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public final static String getDefaultType() { String cstype; cstype = AccessController.doPrivileged(new PrivilegedAction<String>() { public String run() { return Security.getProperty(CERTSTORE_TYPE); } }); if (cstype == null) { cstype = "LDAP"; } return cstype; } }
public class class_name { public final static String getDefaultType() { String cstype; cstype = AccessController.doPrivileged(new PrivilegedAction<String>() { public String run() { return Security.getProperty(CERTSTORE_TYPE); } }); if (cstype == null) { cstype = "LDAP"; // depends on control dependency: [if], data = [none] } return cstype; } }
public class class_name { protected String getSecurityName(String loginName, String urAuthenticatedId) throws EntryNotFoundException, RegistryException { UserRegistry ur = getUserRegistry(); if (ur != null && ur.getType() != "CUSTOM") { // Preserve the existing behavior for CUSTOM user registries String securityName = ur.getUserSecurityName(urAuthenticatedId); if (securityName != null) { return securityName; } } // If a loginName was provided, use it. if (loginName != null) { return loginName; } if (ur != null) { return ur.getUserSecurityName(urAuthenticatedId); } else { throw new NullPointerException("No user registry"); } } }
public class class_name { protected String getSecurityName(String loginName, String urAuthenticatedId) throws EntryNotFoundException, RegistryException { UserRegistry ur = getUserRegistry(); if (ur != null && ur.getType() != "CUSTOM") { // Preserve the existing behavior for CUSTOM user registries String securityName = ur.getUserSecurityName(urAuthenticatedId); if (securityName != null) { return securityName; // depends on control dependency: [if], data = [none] } } // If a loginName was provided, use it. if (loginName != null) { return loginName; } if (ur != null) { return ur.getUserSecurityName(urAuthenticatedId); } else { throw new NullPointerException("No user registry"); } } }
public class class_name { private Set<ModelDescription> scanBundleForModels(Bundle bundle) { Set<ModelDescription> models = new HashSet<ModelDescription>(); if (!shouldSkipBundle(bundle)) { models = loadModelsOfBundle(bundle); } return models; } }
public class class_name { private Set<ModelDescription> scanBundleForModels(Bundle bundle) { Set<ModelDescription> models = new HashSet<ModelDescription>(); if (!shouldSkipBundle(bundle)) { models = loadModelsOfBundle(bundle); // depends on control dependency: [if], data = [none] } return models; } }
public class class_name { public EEnum getIfcPlateTypeEnum() { if (ifcPlateTypeEnumEEnum == null) { ifcPlateTypeEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(871); } return ifcPlateTypeEnumEEnum; } }
public class class_name { public EEnum getIfcPlateTypeEnum() { if (ifcPlateTypeEnumEEnum == null) { ifcPlateTypeEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(871); // depends on control dependency: [if], data = [none] } return ifcPlateTypeEnumEEnum; } }
public class class_name { public <T> Iterable<T> sort( Class<T> componentClass, Iterable<T> iterable ) { if (iterable instanceof List) { sort((List) iterable); return iterable; } if (iterable instanceof Collection) { return sort(componentClass, (Collection) iterable); } if ( iterable == null ) { return Collections.EMPTY_LIST; } List<T> list = Lists.list(iterable); sort(list); return list; } }
public class class_name { public <T> Iterable<T> sort( Class<T> componentClass, Iterable<T> iterable ) { if (iterable instanceof List) { sort((List) iterable); // depends on control dependency: [if], data = [none] return iterable; // depends on control dependency: [if], data = [none] } if (iterable instanceof Collection) { return sort(componentClass, (Collection) iterable); // depends on control dependency: [if], data = [none] } if ( iterable == null ) { return Collections.EMPTY_LIST; // depends on control dependency: [if], data = [none] } List<T> list = Lists.list(iterable); sort(list); return list; } }
public class class_name { private void doUpdateRO(final Collection<String> remove, final Collection<Document> add) throws IOException { SecurityHelper.doPrivilegedIOExceptionAction(new PrivilegedExceptionAction<Object>() { @SuppressWarnings("resource") public Object run() throws Exception { // make sure a reader is available during long updates if (add.size() > handler.getBufferSize()) { try { releaseMultiReader(); } catch (IOException e) { // do not fail if an exception is thrown here LOG.warn("unable to prepare index reader " + "for queries during update", e); } } synchronized (updateMonitor) { ReadOnlyIndexReader[] readers = null; try { for (Iterator<String> it = remove.iterator(); it.hasNext(); ) { Term idTerm = new Term(FieldNames.UUID, it.next()); int num = volatileIndex.removeDocument(idTerm); if (num == 0) { for (int i = indexes.size() - 1; i >= 0; i--) { // only look in registered indexes PersistentIndex idx = indexes.get(i); if (indexNames.contains(idx.getName())) { num = idx.removeDocument(idTerm); if (num > 0) { if (LOG.isDebugEnabled()) LOG.debug(idTerm.text() + " has been found in the persisted index " + i); break; } } } } else if (LOG.isDebugEnabled()) { LOG.debug(idTerm.text() + " has been found in the volatile index"); } } // try to avoid getting index reader for each doc IndexReader indexReader = null; for (Iterator<Document> it = add.iterator(); it.hasNext(); ) { Document doc = it.next(); if (doc != null) { // check if this item should be placed in own volatile index // usually it must be indexed, but exception if it exists in persisted index boolean addDoc = true; // make this check safe if something goes wrong String uuid = doc.get(FieldNames.UUID); // if remove contains uuid, node should be re-indexed // if not, than should be checked if node present in the last persisted index if (!remove.contains(uuid)) { // if index list changed, get the reader on the latest index // or if index reader is not current if (indexReader == null) { try { readers = getReadOnlyIndexReaders(false, false); indexReader = new MultiReader(readers); } catch (Throwable e)//NOSONAR { // this is safe index reader retrieval. The last index already closed, possibly merged or // any other exception that occurs here LOG.warn("Could not create the MultiReader :" + e.getLocalizedMessage()); LOG.debug("Could not create the MultiReader", e); } } if ((indexReader != null && !indexReader.isCurrent())) { // safe release reader if (indexReader != null) { for (ReadOnlyIndexReader reader : readers) { reader.release(); } } try { readers = getReadOnlyIndexReaders(false, false); indexReader = new MultiReader(readers); } catch (Throwable e)//NOSONAR { // this is safe index reader retrieval. The last index already closed, possibly merged or // any other exception that occurs here LOG.warn("Could not create the MultiReader :" + e.getLocalizedMessage()); LOG.debug("Could not create the MultiReader", e); } } // if indexReader exists (it is possible that no persisted indexes exists on start) if (indexReader != null) { TermDocs termDocs = null; try { // reader from resisted index should be termDocs = indexReader.termDocs(new Term(FieldNames.UUID, uuid)); // node should be indexed if not found in persistent index addDoc = !termDocs.next(); } catch (Exception e) { LOG.debug("Some exception occured, during index check"); } finally { if (termDocs != null) termDocs.close(); } } } if (addDoc) { volatileIndex.addDocuments(new Document[]{doc}); } else if (LOG.isDebugEnabled()) { LOG.debug("Could find the document {} in the last persisted index", uuid); } } } } finally { // don't forget to release a reader anyway if (readers != null) { for (ReadOnlyIndexReader reader : readers) { reader.release(); } } releaseMultiReader(); } } return null; } }); } }
public class class_name { private void doUpdateRO(final Collection<String> remove, final Collection<Document> add) throws IOException { SecurityHelper.doPrivilegedIOExceptionAction(new PrivilegedExceptionAction<Object>() { @SuppressWarnings("resource") public Object run() throws Exception { // make sure a reader is available during long updates if (add.size() > handler.getBufferSize()) { try { releaseMultiReader(); // depends on control dependency: [try], data = [none] } catch (IOException e) { // do not fail if an exception is thrown here LOG.warn("unable to prepare index reader " + "for queries during update", e); } // depends on control dependency: [catch], data = [none] } synchronized (updateMonitor) { ReadOnlyIndexReader[] readers = null; try { for (Iterator<String> it = remove.iterator(); it.hasNext(); ) { Term idTerm = new Term(FieldNames.UUID, it.next()); int num = volatileIndex.removeDocument(idTerm); if (num == 0) { for (int i = indexes.size() - 1; i >= 0; i--) { // only look in registered indexes PersistentIndex idx = indexes.get(i); if (indexNames.contains(idx.getName())) { num = idx.removeDocument(idTerm); // depends on control dependency: [if], data = [none] if (num > 0) { if (LOG.isDebugEnabled()) LOG.debug(idTerm.text() + " has been found in the persisted index " + i); break; } } } } else if (LOG.isDebugEnabled()) { LOG.debug(idTerm.text() + " has been found in the volatile index"); // depends on control dependency: [if], data = [none] } } // try to avoid getting index reader for each doc IndexReader indexReader = null; for (Iterator<Document> it = add.iterator(); it.hasNext(); ) { Document doc = it.next(); if (doc != null) { // check if this item should be placed in own volatile index // usually it must be indexed, but exception if it exists in persisted index boolean addDoc = true; // make this check safe if something goes wrong String uuid = doc.get(FieldNames.UUID); // if remove contains uuid, node should be re-indexed // if not, than should be checked if node present in the last persisted index if (!remove.contains(uuid)) { // if index list changed, get the reader on the latest index // or if index reader is not current if (indexReader == null) { try { readers = getReadOnlyIndexReaders(false, false); // depends on control dependency: [try], data = [none] indexReader = new MultiReader(readers); // depends on control dependency: [try], data = [none] } catch (Throwable e)//NOSONAR { // this is safe index reader retrieval. The last index already closed, possibly merged or // any other exception that occurs here LOG.warn("Could not create the MultiReader :" + e.getLocalizedMessage()); LOG.debug("Could not create the MultiReader", e); } // depends on control dependency: [catch], data = [none] } if ((indexReader != null && !indexReader.isCurrent())) { // safe release reader if (indexReader != null) { for (ReadOnlyIndexReader reader : readers) { reader.release(); // depends on control dependency: [for], data = [reader] } } try { readers = getReadOnlyIndexReaders(false, false); // depends on control dependency: [try], data = [none] indexReader = new MultiReader(readers); // depends on control dependency: [try], data = [none] } catch (Throwable e)//NOSONAR { // this is safe index reader retrieval. The last index already closed, possibly merged or // any other exception that occurs here LOG.warn("Could not create the MultiReader :" + e.getLocalizedMessage()); LOG.debug("Could not create the MultiReader", e); } // depends on control dependency: [catch], data = [none] } // if indexReader exists (it is possible that no persisted indexes exists on start) if (indexReader != null) { TermDocs termDocs = null; try { // reader from resisted index should be termDocs = indexReader.termDocs(new Term(FieldNames.UUID, uuid)); // depends on control dependency: [try], data = [none] // node should be indexed if not found in persistent index addDoc = !termDocs.next(); // depends on control dependency: [try], data = [none] } catch (Exception e) { LOG.debug("Some exception occured, during index check"); } // depends on control dependency: [catch], data = [none] finally { if (termDocs != null) termDocs.close(); } } } if (addDoc) { volatileIndex.addDocuments(new Document[]{doc}); // depends on control dependency: [if], data = [none] } else if (LOG.isDebugEnabled()) { LOG.debug("Could find the document {} in the last persisted index", uuid); // depends on control dependency: [if], data = [none] } } } } finally { // don't forget to release a reader anyway if (readers != null) { for (ReadOnlyIndexReader reader : readers) { reader.release(); // depends on control dependency: [for], data = [reader] } } releaseMultiReader(); } } return null; } }); } }
public class class_name { public void setPoolManagerRef(WsByteBufferPoolManagerImpl oManagerRef) { this.oWsByteBufferPoolManager = oManagerRef; this.trusted = oManagerRef.isTrustedUsers(); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "setPoolManagerRef: trusted=" + this.trusted); } } }
public class class_name { public void setPoolManagerRef(WsByteBufferPoolManagerImpl oManagerRef) { this.oWsByteBufferPoolManager = oManagerRef; this.trusted = oManagerRef.isTrustedUsers(); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "setPoolManagerRef: trusted=" + this.trusted); // depends on control dependency: [if], data = [none] } } }
public class class_name { private static void generateAllCombinations( List<Filter> result, List<Filter> andList, List<Filter> nonAndList ) { List<Filter> children = ((AndFilter) andList.get(0)).getFilters(); if (result.isEmpty()) { for (Filter child : children) { List<Filter> a = Lists.newArrayList(nonAndList); a.add(child); result.add(new OrFilter(a)); } } else { List<Filter> work = new ArrayList<>(result); result.clear(); for (Filter child : children) { for (Filter or : work) { List<Filter> a = Lists.newArrayList((((OrFilter) or).getFilters())); a.add(child); result.add(new OrFilter(a)); } } } if (andList.size() > 1) { generateAllCombinations(result, andList.subList(1, andList.size()), nonAndList); } } }
public class class_name { private static void generateAllCombinations( List<Filter> result, List<Filter> andList, List<Filter> nonAndList ) { List<Filter> children = ((AndFilter) andList.get(0)).getFilters(); if (result.isEmpty()) { for (Filter child : children) { List<Filter> a = Lists.newArrayList(nonAndList); a.add(child); // depends on control dependency: [for], data = [child] result.add(new OrFilter(a)); // depends on control dependency: [for], data = [none] } } else { List<Filter> work = new ArrayList<>(result); result.clear(); // depends on control dependency: [if], data = [none] for (Filter child : children) { for (Filter or : work) { List<Filter> a = Lists.newArrayList((((OrFilter) or).getFilters())); a.add(child); // depends on control dependency: [for], data = [none] result.add(new OrFilter(a)); // depends on control dependency: [for], data = [none] } } } if (andList.size() > 1) { generateAllCombinations(result, andList.subList(1, andList.size()), nonAndList); // depends on control dependency: [if], data = [none] } } }
public class class_name { public int doRecordChange(FieldInfo field, int iChangeType, boolean bDisplayOption) { // Read a valid record double dMainValue, dCurrentValue; int iErrorCode = super.doRecordChange(field, iChangeType, bDisplayOption); // Initialize the record if (iErrorCode != DBConstants.NORMAL_RETURN) return iErrorCode; switch (iChangeType) { case DBConstants.CONTROL_BREAK_TYPE: if (!m_bResetOnBreak) break; if (m_fldBreak != null) { if (m_objLastBreakValue != FIRST_TIME) if ((m_fldBreak.getData() == m_objLastBreakValue) || ((m_fldBreak.getData() != null) && (m_fldBreak.getData().equals(m_objLastBreakValue)))) break; // Break value is the same, don't break. m_objLastBreakValue = m_fldBreak.getData(); } iErrorCode = this.resetCount(); // Set in main file's field break; case DBConstants.AFTER_REQUERY_TYPE: m_bEOFHit = false; m_dTotalToVerify = 0; if ((m_bRecountOnSelect) || (m_bResetOnBreak)) { boolean bResetCount = true; if (m_bVerifyOnEOF) // Only have to reset field on requery if I don't verify on eof if (m_fldMain != null) if (m_fldMain.getRecord() != null) if ((m_fldMain.getRecord().getEditMode() == DBConstants.EDIT_CURRENT) || (m_fldMain.getRecord().getEditMode() == DBConstants.EDIT_IN_PROGRESS)) bResetCount = false; // Don't reset a field on a current record (since that would cause the record to be re-written for no reason AND may trigger unnecessary changes) if (bResetCount) iErrorCode = this.resetCount(); // Set in main file's field if (m_fldBreak != null) m_objLastBreakValue = FIRST_TIME; // Reset to first time } break; case DBConstants.SELECT_EOF_TYPE: m_bEOFHit = true; if (m_bVerifyOnEOF) iErrorCode = this.setCount(m_dTotalToVerify, false, DBConstants.INIT_MOVE); // Set in main file's field break; case DBConstants.MOVE_NEXT_TYPE: dMainValue = this.getCount(); // Set in main file's field dCurrentValue = this.getFieldValue(); // New(current) value dMainValue += dCurrentValue; m_dTotalToVerify += dCurrentValue; if (m_fldBreak != null) if (m_objLastBreakValue == FIRST_TIME) m_objLastBreakValue = m_fldBreak.getData(); // First value = first value to compare if ((m_bVerifyOnEOF) && (!m_bResetOnBreak)) // Don't total until the end unless this is a break counter break; // Don't update the total until I hit EOF iErrorCode = this.setCount(dMainValue, true, DBConstants.INIT_MOVE); // Set in main file's field break; case DBConstants.AFTER_REFRESH_TYPE: // New blank record created m_dOldValue = this.getFieldValue(); // Old value (in case of change) break; case DBConstants.AFTER_ADD_TYPE: dMainValue = this.getCount(); // Set in main file's field dCurrentValue = this.getFieldValue(); // New(current) value m_dOldValue = dCurrentValue; // In case record is set to refresh on write (so an update is coming) dMainValue += dCurrentValue; m_dTotalToVerify += dCurrentValue; if ((m_bVerifyOnEOF == false) || (m_bEOFHit)) iErrorCode = this.setCount(dMainValue, false, DBConstants.SCREEN_MOVE); // Set in main file's field break; case DBConstants.AFTER_UPDATE_TYPE: dMainValue = this.getCount(); // Set in main file's field dCurrentValue = this.getFieldValue(); // New(current) value dMainValue += dCurrentValue - m_dOldValue; // New(current) value m_dTotalToVerify += dCurrentValue - m_dOldValue; // New(current) value if ((m_bVerifyOnEOF == false) || (m_bEOFHit)) iErrorCode = this.setCount(dMainValue, false, DBConstants.SCREEN_MOVE); // Set in main file's field break; case DBConstants.AFTER_DELETE_TYPE: dMainValue = this.getCount(); // Set in main file's field dMainValue -= m_dOldValue; // New(current) value m_dTotalToVerify -= m_dOldValue; if ((m_bVerifyOnEOF == false) || (m_bEOFHit)) iErrorCode = this.setCount(dMainValue, false, DBConstants.SCREEN_MOVE); // Set in main file's field break; } return iErrorCode; } }
public class class_name { public int doRecordChange(FieldInfo field, int iChangeType, boolean bDisplayOption) { // Read a valid record double dMainValue, dCurrentValue; int iErrorCode = super.doRecordChange(field, iChangeType, bDisplayOption); // Initialize the record if (iErrorCode != DBConstants.NORMAL_RETURN) return iErrorCode; switch (iChangeType) { case DBConstants.CONTROL_BREAK_TYPE: if (!m_bResetOnBreak) break; if (m_fldBreak != null) { if (m_objLastBreakValue != FIRST_TIME) if ((m_fldBreak.getData() == m_objLastBreakValue) || ((m_fldBreak.getData() != null) && (m_fldBreak.getData().equals(m_objLastBreakValue)))) break; // Break value is the same, don't break. m_objLastBreakValue = m_fldBreak.getData(); // depends on control dependency: [if], data = [none] } iErrorCode = this.resetCount(); // Set in main file's field break; case DBConstants.AFTER_REQUERY_TYPE: m_bEOFHit = false; m_dTotalToVerify = 0; if ((m_bRecountOnSelect) || (m_bResetOnBreak)) { boolean bResetCount = true; if (m_bVerifyOnEOF) // Only have to reset field on requery if I don't verify on eof if (m_fldMain != null) if (m_fldMain.getRecord() != null) if ((m_fldMain.getRecord().getEditMode() == DBConstants.EDIT_CURRENT) || (m_fldMain.getRecord().getEditMode() == DBConstants.EDIT_IN_PROGRESS)) bResetCount = false; // Don't reset a field on a current record (since that would cause the record to be re-written for no reason AND may trigger unnecessary changes) if (bResetCount) iErrorCode = this.resetCount(); // Set in main file's field if (m_fldBreak != null) m_objLastBreakValue = FIRST_TIME; // Reset to first time } break; case DBConstants.SELECT_EOF_TYPE: m_bEOFHit = true; if (m_bVerifyOnEOF) iErrorCode = this.setCount(m_dTotalToVerify, false, DBConstants.INIT_MOVE); // Set in main file's field break; case DBConstants.MOVE_NEXT_TYPE: dMainValue = this.getCount(); // Set in main file's field dCurrentValue = this.getFieldValue(); // New(current) value dMainValue += dCurrentValue; m_dTotalToVerify += dCurrentValue; if (m_fldBreak != null) if (m_objLastBreakValue == FIRST_TIME) m_objLastBreakValue = m_fldBreak.getData(); // First value = first value to compare if ((m_bVerifyOnEOF) && (!m_bResetOnBreak)) // Don't total until the end unless this is a break counter break; // Don't update the total until I hit EOF iErrorCode = this.setCount(dMainValue, true, DBConstants.INIT_MOVE); // Set in main file's field break; case DBConstants.AFTER_REFRESH_TYPE: // New blank record created m_dOldValue = this.getFieldValue(); // Old value (in case of change) break; case DBConstants.AFTER_ADD_TYPE: dMainValue = this.getCount(); // Set in main file's field dCurrentValue = this.getFieldValue(); // New(current) value m_dOldValue = dCurrentValue; // In case record is set to refresh on write (so an update is coming) dMainValue += dCurrentValue; m_dTotalToVerify += dCurrentValue; if ((m_bVerifyOnEOF == false) || (m_bEOFHit)) iErrorCode = this.setCount(dMainValue, false, DBConstants.SCREEN_MOVE); // Set in main file's field break; case DBConstants.AFTER_UPDATE_TYPE: dMainValue = this.getCount(); // Set in main file's field dCurrentValue = this.getFieldValue(); // New(current) value dMainValue += dCurrentValue - m_dOldValue; // New(current) value m_dTotalToVerify += dCurrentValue - m_dOldValue; // New(current) value if ((m_bVerifyOnEOF == false) || (m_bEOFHit)) iErrorCode = this.setCount(dMainValue, false, DBConstants.SCREEN_MOVE); // Set in main file's field break; case DBConstants.AFTER_DELETE_TYPE: dMainValue = this.getCount(); // Set in main file's field dMainValue -= m_dOldValue; // New(current) value m_dTotalToVerify -= m_dOldValue; if ((m_bVerifyOnEOF == false) || (m_bEOFHit)) iErrorCode = this.setCount(dMainValue, false, DBConstants.SCREEN_MOVE); // Set in main file's field break; } return iErrorCode; } }
public class class_name { public static void build( final Key jobKey, final Key modelKey, final DRFParams drfParams, final Data localData, int ntrees, int numSplitFeatures, int[] rowsPerChunks) { Timer t_alltrees = new Timer(); Tree[] trees = new Tree[ntrees]; Log.info(Log.Tag.Sys.RANDF,"Building "+ntrees+" trees"); Log.info(Log.Tag.Sys.RANDF,"Number of split features: "+ numSplitFeatures); Log.info(Log.Tag.Sys.RANDF,"Starting RF computation with "+ localData.rows()+" rows "); Random rnd = Utils.getRNG(localData.seed() + ROOT_SEED_ADD); Sampling sampler = createSampler(drfParams, rowsPerChunks); byte producerId = (byte) H2O.SELF.index(); for (int i = 0; i < ntrees; ++i) { long treeSeed = rnd.nextLong() + TREE_SEED_INIT; // make sure that enough bits is initialized trees[i] = new Tree(jobKey, modelKey, localData, producerId, drfParams.max_depth, drfParams.stat_type, numSplitFeatures, treeSeed, i, drfParams._exclusiveSplitLimit, sampler, drfParams._verbose, drfParams.regression, !drfParams._useNonLocalData, ((SpeeDRFModel)UKV.get(modelKey)).score_pojo); } Log.info("Invoking the tree build tasks on all nodes."); DRemoteTask.invokeAll(trees); Log.info(Log.Tag.Sys.RANDF,"All trees ("+ntrees+") done in "+ t_alltrees); } }
public class class_name { public static void build( final Key jobKey, final Key modelKey, final DRFParams drfParams, final Data localData, int ntrees, int numSplitFeatures, int[] rowsPerChunks) { Timer t_alltrees = new Timer(); Tree[] trees = new Tree[ntrees]; Log.info(Log.Tag.Sys.RANDF,"Building "+ntrees+" trees"); Log.info(Log.Tag.Sys.RANDF,"Number of split features: "+ numSplitFeatures); Log.info(Log.Tag.Sys.RANDF,"Starting RF computation with "+ localData.rows()+" rows "); Random rnd = Utils.getRNG(localData.seed() + ROOT_SEED_ADD); Sampling sampler = createSampler(drfParams, rowsPerChunks); byte producerId = (byte) H2O.SELF.index(); for (int i = 0; i < ntrees; ++i) { long treeSeed = rnd.nextLong() + TREE_SEED_INIT; // make sure that enough bits is initialized trees[i] = new Tree(jobKey, modelKey, localData, producerId, drfParams.max_depth, drfParams.stat_type, numSplitFeatures, treeSeed, i, drfParams._exclusiveSplitLimit, sampler, drfParams._verbose, drfParams.regression, !drfParams._useNonLocalData, ((SpeeDRFModel)UKV.get(modelKey)).score_pojo); // depends on control dependency: [for], data = [i] } Log.info("Invoking the tree build tasks on all nodes."); DRemoteTask.invokeAll(trees); Log.info(Log.Tag.Sys.RANDF,"All trees ("+ntrees+") done in "+ t_alltrees); } }
public class class_name { private int index() { ElementImpl parent = (ElementImpl) getParent(); if (parent == null) { return -1; } Node n = parent.node.getFirstChild(); int index = 0; int twinsCount = 0; boolean indexFound = false; while (n != null) { if (n == node) { indexFound = true; } if (n.getNodeType() == Node.ELEMENT_NODE && n.getNodeName().equals(node.getNodeName())) { ++twinsCount; if (!indexFound) { ++index; } } n = n.getNextSibling(); } return twinsCount > 1 ? index : -1; } }
public class class_name { private int index() { ElementImpl parent = (ElementImpl) getParent(); if (parent == null) { return -1; // depends on control dependency: [if], data = [none] } Node n = parent.node.getFirstChild(); int index = 0; int twinsCount = 0; boolean indexFound = false; while (n != null) { if (n == node) { indexFound = true; // depends on control dependency: [if], data = [none] } if (n.getNodeType() == Node.ELEMENT_NODE && n.getNodeName().equals(node.getNodeName())) { ++twinsCount; // depends on control dependency: [if], data = [none] if (!indexFound) { ++index; // depends on control dependency: [if], data = [none] } } n = n.getNextSibling(); // depends on control dependency: [while], data = [none] } return twinsCount > 1 ? index : -1; } }
public class class_name { public void marshall(UpgradeAppliedSchemaRequest upgradeAppliedSchemaRequest, ProtocolMarshaller protocolMarshaller) { if (upgradeAppliedSchemaRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(upgradeAppliedSchemaRequest.getPublishedSchemaArn(), PUBLISHEDSCHEMAARN_BINDING); protocolMarshaller.marshall(upgradeAppliedSchemaRequest.getDirectoryArn(), DIRECTORYARN_BINDING); protocolMarshaller.marshall(upgradeAppliedSchemaRequest.getDryRun(), DRYRUN_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(UpgradeAppliedSchemaRequest upgradeAppliedSchemaRequest, ProtocolMarshaller protocolMarshaller) { if (upgradeAppliedSchemaRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(upgradeAppliedSchemaRequest.getPublishedSchemaArn(), PUBLISHEDSCHEMAARN_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(upgradeAppliedSchemaRequest.getDirectoryArn(), DIRECTORYARN_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(upgradeAppliedSchemaRequest.getDryRun(), DRYRUN_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 String getSHA1(String token, String timestamp, String nonce, String encrypt) throws AesException { try { String[] array = new String[]{token, timestamp, nonce, encrypt}; StringBuilder sb = new StringBuilder(); // 字符串排序 Arrays.sort(array); for (int i = 0; i < 4; i++) { sb.append(array[i]); } String str = sb.toString(); // SHA1签名生成 MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(str.getBytes()); byte[] digest = md.digest(); StringBuilder hex = new StringBuilder(); String shaHex; for (byte aDigest : digest) { shaHex = Integer.toHexString(aDigest & 0xFF); if (shaHex.length() < 2) { hex.append(0); } hex.append(shaHex); } return hex.toString(); } catch (Exception e) { throw new AesException(AesException.ComputeSignatureError); } } }
public class class_name { public static String getSHA1(String token, String timestamp, String nonce, String encrypt) throws AesException { try { String[] array = new String[]{token, timestamp, nonce, encrypt}; StringBuilder sb = new StringBuilder(); // 字符串排序 Arrays.sort(array); for (int i = 0; i < 4; i++) { sb.append(array[i]); } String str = sb.toString(); // SHA1签名生成 MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(str.getBytes()); byte[] digest = md.digest(); StringBuilder hex = new StringBuilder(); String shaHex; for (byte aDigest : digest) { shaHex = Integer.toHexString(aDigest & 0xFF); if (shaHex.length() < 2) { hex.append(0); // depends on control dependency: [if], data = [none] } hex.append(shaHex); } return hex.toString(); } catch (Exception e) { throw new AesException(AesException.ComputeSignatureError); } } }
public class class_name { private static boolean longLongCompareMagnitude(long hi0, long lo0, long hi1, long lo1) { if(hi0!=hi1) { return hi0<hi1; } return (lo0+Long.MIN_VALUE) <(lo1+Long.MIN_VALUE); } }
public class class_name { private static boolean longLongCompareMagnitude(long hi0, long lo0, long hi1, long lo1) { if(hi0!=hi1) { return hi0<hi1; // depends on control dependency: [if], data = [none] } return (lo0+Long.MIN_VALUE) <(lo1+Long.MIN_VALUE); } }
public class class_name { public static Object getTarget(final Object proxy) { if (!AopUtils.isAopProxy(proxy)) { return proxy; } if (AopUtils.isJdkDynamicProxy(proxy)) { return getProxyTargetObject(proxy, "h"); } else { return getProxyTargetObject(proxy, "CGLIB$CALLBACK_0"); } } }
public class class_name { public static Object getTarget(final Object proxy) { if (!AopUtils.isAopProxy(proxy)) { return proxy; // depends on control dependency: [if], data = [none] } if (AopUtils.isJdkDynamicProxy(proxy)) { return getProxyTargetObject(proxy, "h"); // depends on control dependency: [if], data = [none] } else { return getProxyTargetObject(proxy, "CGLIB$CALLBACK_0"); // depends on control dependency: [if], data = [none] } } }
public class class_name { public int getMessageLength(){ if(this.identifierRegex == null){ return 1; } try { return this.identifierRegex.getBytes("UTF-16BE").length + 1; } catch (UnsupportedEncodingException e) { log.error("Unable to decode UTF-16BE String: {}", e); return 1; } } }
public class class_name { public int getMessageLength(){ if(this.identifierRegex == null){ return 1; // depends on control dependency: [if], data = [none] } try { return this.identifierRegex.getBytes("UTF-16BE").length + 1; // depends on control dependency: [try], data = [none] } catch (UnsupportedEncodingException e) { log.error("Unable to decode UTF-16BE String: {}", e); return 1; } // depends on control dependency: [catch], data = [none] } }
public class class_name { @Override public void expandStatements(final Document doc, final ProtoNetwork pn, final boolean stmtExpand) { final ProtoNetworkBuilder pnb = new ProtoNetworkBuilder(doc); final ArrayList<ExpansionRule<Statement>> rules = sizedArrayList(2); if (stmtExpand) { rules.add(distributedRule); } else { rules.add(extractRule); } rules.add(reciprocalRule); final StatementTable st = pn.getStatementTable(); final List<TableStatement> ts = st.getStatements(); final Map<Integer, Statement> index = st.getIndexedStatements(); for (int i = 0, n = ts.size(); i < n; i++) { final Statement stmt = index.get(i); if (stmt == null) { continue; } // check each statement expansion rule for (ExpansionRule<Statement> rule : rules) { if (!rule.match(stmt)) { continue; } final List<Statement> stmtExp = rule.expand(stmt); for (final Statement exp : stmtExp) { if (exp.isSubjectOnly()) { createNode(exp.getSubject(), i, pn, pnb); } else if (exp.isStatementTriple()) { createEdge(exp, i, pn, pnb); } else { throw new UnsupportedOperationException( "Cannot provide a nested statement as an " + "expansion."); } } } } } }
public class class_name { @Override public void expandStatements(final Document doc, final ProtoNetwork pn, final boolean stmtExpand) { final ProtoNetworkBuilder pnb = new ProtoNetworkBuilder(doc); final ArrayList<ExpansionRule<Statement>> rules = sizedArrayList(2); if (stmtExpand) { rules.add(distributedRule); // depends on control dependency: [if], data = [none] } else { rules.add(extractRule); // depends on control dependency: [if], data = [none] } rules.add(reciprocalRule); final StatementTable st = pn.getStatementTable(); final List<TableStatement> ts = st.getStatements(); final Map<Integer, Statement> index = st.getIndexedStatements(); for (int i = 0, n = ts.size(); i < n; i++) { final Statement stmt = index.get(i); if (stmt == null) { continue; } // check each statement expansion rule for (ExpansionRule<Statement> rule : rules) { if (!rule.match(stmt)) { continue; } final List<Statement> stmtExp = rule.expand(stmt); for (final Statement exp : stmtExp) { if (exp.isSubjectOnly()) { createNode(exp.getSubject(), i, pn, pnb); // depends on control dependency: [if], data = [none] } else if (exp.isStatementTriple()) { createEdge(exp, i, pn, pnb); // depends on control dependency: [if], data = [none] } else { throw new UnsupportedOperationException( "Cannot provide a nested statement as an " + "expansion."); } } } } } }
public class class_name { public void addAll( T[] array , int first , int length ) { if( length <= 0 ) return; Element<T> a = requestNew(); a.object = array[first]; if( this.first == null ) { this.first = a; } else if( last != null ) { last.next = a; a.previous = last; } for (int i = 1; i < length; i++) { Element<T> b = requestNew(); b.object = array[first+i]; a.next = b; b.previous = a; a = b; } last = a; size += length; } }
public class class_name { public void addAll( T[] array , int first , int length ) { if( length <= 0 ) return; Element<T> a = requestNew(); a.object = array[first]; if( this.first == null ) { this.first = a; // depends on control dependency: [if], data = [none] } else if( last != null ) { last.next = a; // depends on control dependency: [if], data = [none] a.previous = last; // depends on control dependency: [if], data = [none] } for (int i = 1; i < length; i++) { Element<T> b = requestNew(); b.object = array[first+i]; // depends on control dependency: [for], data = [i] a.next = b; // depends on control dependency: [for], data = [none] b.previous = a; // depends on control dependency: [for], data = [none] a = b; // depends on control dependency: [for], data = [none] } last = a; size += length; } }
public class class_name { public BeanMappingObject getBeanMapObject(Class src, Class target, boolean autoRegister) { BeanMappingObject object = autoRepository.getBeanMappingObject(src, target); if (object == null && autoRegister) { if (isMap(src)) {// 判断是否为map接口的子类 autoRepository.registerMap(target); } else { autoRepository.registerMap(src); } object = getFromRepository(src, target, this.autoRepository); } return object; } }
public class class_name { public BeanMappingObject getBeanMapObject(Class src, Class target, boolean autoRegister) { BeanMappingObject object = autoRepository.getBeanMappingObject(src, target); if (object == null && autoRegister) { if (isMap(src)) {// 判断是否为map接口的子类 autoRepository.registerMap(target); // depends on control dependency: [if], data = [none] } else { autoRepository.registerMap(src); // depends on control dependency: [if], data = [none] } object = getFromRepository(src, target, this.autoRepository); // depends on control dependency: [if], data = [none] } return object; } }
public class class_name { public static String unescapeNewlines(String str) { boolean hadSlash = false; final int len = str.length(); StringWriter out = new StringWriter(len); for (int i = 0; i < len; i++) { char c = str.charAt(i); if (hadSlash) { switch (c) { case 'n': out.write('\n'); break; case '\\': out.write('\\'); break; default: out.write(c); } hadSlash = false; } else { if (c == '\\') hadSlash = true; else out.write(c); } } return out.toString(); } }
public class class_name { public static String unescapeNewlines(String str) { boolean hadSlash = false; final int len = str.length(); StringWriter out = new StringWriter(len); for (int i = 0; i < len; i++) { char c = str.charAt(i); if (hadSlash) { switch (c) { case 'n': out.write('\n'); break; case '\\': out.write('\\'); break; default: out.write(c); } hadSlash = false; // depends on control dependency: [if], data = [none] } else { if (c == '\\') hadSlash = true; else out.write(c); } } return out.toString(); } }
public class class_name { private void mergeReleased(List<Segment> segments, List<OffsetPredicate> predicates, Segment compactSegment) { for (int i = 0; i < segments.size(); i++) { mergeReleasedEntries(segments.get(i), predicates.get(i), compactSegment); } } }
public class class_name { private void mergeReleased(List<Segment> segments, List<OffsetPredicate> predicates, Segment compactSegment) { for (int i = 0; i < segments.size(); i++) { mergeReleasedEntries(segments.get(i), predicates.get(i), compactSegment); // depends on control dependency: [for], data = [i] } } }
public class class_name { public static String replaceTabsWithSpaces(String text, int tabSize) { String tabText = ""; for (int i = 0; i < tabSize; i++) { tabText += " "; } return text.replaceAll("\t", " "); } }
public class class_name { public static String replaceTabsWithSpaces(String text, int tabSize) { String tabText = ""; for (int i = 0; i < tabSize; i++) { tabText += " "; // depends on control dependency: [for], data = [none] } return text.replaceAll("\t", " "); } }
public class class_name { public JSONResult getConfig() { if (attempts == 0) { try { resolve(); } catch(Exception e) { // discard exception } } if (config == null) { logger.info("{} => no response", url); return null; } logger.info("{} => {}", url, config.get("FireREST").getString()); return config; } }
public class class_name { public JSONResult getConfig() { if (attempts == 0) { try { resolve(); // depends on control dependency: [try], data = [none] } catch(Exception e) { // discard exception } // depends on control dependency: [catch], data = [none] } if (config == null) { logger.info("{} => no response", url); // depends on control dependency: [if], data = [none] return null; // depends on control dependency: [if], data = [none] } logger.info("{} => {}", url, config.get("FireREST").getString()); return config; } }
public class class_name { public void marshall(Instance instance, ProtocolMarshaller protocolMarshaller) { if (instance == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(instance.getBoundingBox(), BOUNDINGBOX_BINDING); protocolMarshaller.marshall(instance.getConfidence(), CONFIDENCE_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(Instance instance, ProtocolMarshaller protocolMarshaller) { if (instance == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(instance.getBoundingBox(), BOUNDINGBOX_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(instance.getConfidence(), CONFIDENCE_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 RepositoryTrigger withEvents(RepositoryTriggerEventEnum... events) { java.util.ArrayList<String> eventsCopy = new java.util.ArrayList<String>(events.length); for (RepositoryTriggerEventEnum value : events) { eventsCopy.add(value.toString()); } if (getEvents() == null) { setEvents(eventsCopy); } else { getEvents().addAll(eventsCopy); } return this; } }
public class class_name { public RepositoryTrigger withEvents(RepositoryTriggerEventEnum... events) { java.util.ArrayList<String> eventsCopy = new java.util.ArrayList<String>(events.length); for (RepositoryTriggerEventEnum value : events) { eventsCopy.add(value.toString()); // depends on control dependency: [for], data = [value] } if (getEvents() == null) { setEvents(eventsCopy); // depends on control dependency: [if], data = [none] } else { getEvents().addAll(eventsCopy); // depends on control dependency: [if], data = [none] } return this; } }
public class class_name { public static boolean isAllASCII(final InputStream in) throws IOException { boolean ret = true; int read = -1; do { read = in.read(); if (read > 0x7F) { ret = false; break; } } while (read != -1); return ret; } }
public class class_name { public static boolean isAllASCII(final InputStream in) throws IOException { boolean ret = true; int read = -1; do { read = in.read(); if (read > 0x7F) { ret = false; // depends on control dependency: [if], data = [none] break; } } while (read != -1); return ret; } }
public class class_name { private static String checkP2WPKH(byte[] scriptPubKey) { if ((scriptPubKey.length==22) && (scriptPubKey[0]==0) && (scriptPubKey[1]==0x14)){ byte[] keyhash = Arrays.copyOfRange(scriptPubKey, 2, 22); return "P2WPKH_"+BitcoinUtil.convertByteArrayToHexString(keyhash); } return null; } }
public class class_name { private static String checkP2WPKH(byte[] scriptPubKey) { if ((scriptPubKey.length==22) && (scriptPubKey[0]==0) && (scriptPubKey[1]==0x14)){ byte[] keyhash = Arrays.copyOfRange(scriptPubKey, 2, 22); return "P2WPKH_"+BitcoinUtil.convertByteArrayToHexString(keyhash); // depends on control dependency: [if], data = [none] } return null; } }
public class class_name { protected WritableDataStore<Meta> initializeMeta(Relation<V> relation, double[][] means) { NumberVectorDistanceFunction<? super V> df = getDistanceFunction(); // The actual storage final WritableDataStore<Meta> metas = DataStoreUtil.makeStorage(relation.getDBIDs(), DataStoreFactory.HINT_HOT | DataStoreFactory.HINT_TEMP, Meta.class); // Build the metadata, track the two nearest cluster centers. for(DBIDIter id = relation.iterDBIDs(); id.valid(); id.advance()) { Meta c = new Meta(k); V fv = relation.get(id); for(int i = 0; i < k; i++) { final double d = c.dists[i] = df.distance(fv, DoubleVector.wrap(means[i])); if(i > 0) { if(d < c.dists[c.primary]) { c.primary = i; } else if(d > c.dists[c.secondary]) { c.secondary = i; } } } metas.put(id, c); } return metas; } }
public class class_name { protected WritableDataStore<Meta> initializeMeta(Relation<V> relation, double[][] means) { NumberVectorDistanceFunction<? super V> df = getDistanceFunction(); // The actual storage final WritableDataStore<Meta> metas = DataStoreUtil.makeStorage(relation.getDBIDs(), DataStoreFactory.HINT_HOT | DataStoreFactory.HINT_TEMP, Meta.class); // Build the metadata, track the two nearest cluster centers. for(DBIDIter id = relation.iterDBIDs(); id.valid(); id.advance()) { Meta c = new Meta(k); V fv = relation.get(id); for(int i = 0; i < k; i++) { final double d = c.dists[i] = df.distance(fv, DoubleVector.wrap(means[i])); if(i > 0) { if(d < c.dists[c.primary]) { c.primary = i; // depends on control dependency: [if], data = [none] } else if(d > c.dists[c.secondary]) { c.secondary = i; // depends on control dependency: [if], data = [none] } } } metas.put(id, c); // depends on control dependency: [for], data = [id] } return metas; } }
public class class_name { private Link getAnchorLink(Element element) { SyntheticLinkResource resource = new SyntheticLinkResource(resourceResolver); ValueMap resourceProps = resource.getValueMap(); // get link metadata from data element boolean foundMetadata = getAnchorMetadataFromData(resourceProps, element); if (!foundMetadata) { // support for legacy metadata stored in single "data" attribute foundMetadata = getAnchorLegacyMetadataFromSingleData(resourceProps, element); if (!foundMetadata) { // support for legacy metadata stored in rel attribute getAnchorLegacyMetadataFromRel(resourceProps, element); } } // build anchor via linkhandler return linkHandler.get(resource).build(); } }
public class class_name { private Link getAnchorLink(Element element) { SyntheticLinkResource resource = new SyntheticLinkResource(resourceResolver); ValueMap resourceProps = resource.getValueMap(); // get link metadata from data element boolean foundMetadata = getAnchorMetadataFromData(resourceProps, element); if (!foundMetadata) { // support for legacy metadata stored in single "data" attribute foundMetadata = getAnchorLegacyMetadataFromSingleData(resourceProps, element); // depends on control dependency: [if], data = [none] if (!foundMetadata) { // support for legacy metadata stored in rel attribute getAnchorLegacyMetadataFromRel(resourceProps, element); // depends on control dependency: [if], data = [none] } } // build anchor via linkhandler return linkHandler.get(resource).build(); } }
public class class_name { public final Period add(final Period period) { DateTime newPeriodStart; DateTime newPeriodEnd; if (period == null) { newPeriodStart = getStart(); newPeriodEnd = getEnd(); } else { if (getStart().before(period.getStart())) { newPeriodStart = getStart(); } else { newPeriodStart = period.getStart(); } if (getEnd().after(period.getEnd())) { newPeriodEnd = getEnd(); } else { newPeriodEnd = period.getEnd(); } } return new Period(newPeriodStart, newPeriodEnd); } }
public class class_name { public final Period add(final Period period) { DateTime newPeriodStart; DateTime newPeriodEnd; if (period == null) { newPeriodStart = getStart(); // depends on control dependency: [if], data = [none] newPeriodEnd = getEnd(); // depends on control dependency: [if], data = [none] } else { if (getStart().before(period.getStart())) { newPeriodStart = getStart(); // depends on control dependency: [if], data = [none] } else { newPeriodStart = period.getStart(); // depends on control dependency: [if], data = [none] } if (getEnd().after(period.getEnd())) { newPeriodEnd = getEnd(); // depends on control dependency: [if], data = [none] } else { newPeriodEnd = period.getEnd(); // depends on control dependency: [if], data = [none] } } return new Period(newPeriodStart, newPeriodEnd); } }
public class class_name { public Byte getAsByte(String key) { Object value = mValues.get(key); try { return value != null ? ((Number) value).byteValue() : null; } catch (ClassCastException e) { if (value instanceof CharSequence) { try { return Byte.valueOf(value.toString()); } catch (NumberFormatException e2) { logger.severe("Cannot parse Byte value for " + value + " at key " + key); return null; } } else { logger.log(Level.SEVERE, "Cannot cast value for " + key + " to a Byte: " + value, e); return null; } } } }
public class class_name { public Byte getAsByte(String key) { Object value = mValues.get(key); try { return value != null ? ((Number) value).byteValue() : null; // depends on control dependency: [try], data = [none] } catch (ClassCastException e) { if (value instanceof CharSequence) { try { return Byte.valueOf(value.toString()); // depends on control dependency: [try], data = [none] } catch (NumberFormatException e2) { logger.severe("Cannot parse Byte value for " + value + " at key " + key); return null; } // depends on control dependency: [catch], data = [none] } else { logger.log(Level.SEVERE, "Cannot cast value for " + key + " to a Byte: " + value, e); // depends on control dependency: [if], data = [none] return null; // depends on control dependency: [if], data = [none] } } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static <T> Collection<T> grep(Collection<T> self, Object filter) { Collection<T> answer = createSimilarCollection(self); BooleanReturningMethodInvoker bmi = new BooleanReturningMethodInvoker("isCase"); for (T element : self) { if (bmi.invoke(filter, element)) { answer.add(element); } } return answer; } }
public class class_name { public static <T> Collection<T> grep(Collection<T> self, Object filter) { Collection<T> answer = createSimilarCollection(self); BooleanReturningMethodInvoker bmi = new BooleanReturningMethodInvoker("isCase"); for (T element : self) { if (bmi.invoke(filter, element)) { answer.add(element); // depends on control dependency: [if], data = [none] } } return answer; } }
public class class_name { @Nullable protected HttpEntity getHttpEntity(ClientRequest jerseyRequest) { if (jerseyRequest.getEntity() == null) { return null; } return chunkedEncodingEnabled ? new JerseyRequestHttpEntity(jerseyRequest) : new BufferedJerseyRequestHttpEntity(jerseyRequest); } }
public class class_name { @Nullable protected HttpEntity getHttpEntity(ClientRequest jerseyRequest) { if (jerseyRequest.getEntity() == null) { return null; // depends on control dependency: [if], data = [none] } return chunkedEncodingEnabled ? new JerseyRequestHttpEntity(jerseyRequest) : new BufferedJerseyRequestHttpEntity(jerseyRequest); } }
public class class_name { protected void printFeatures(IN wi, Collection<String> features) { if (flags.printFeatures == null || writtenNum > flags.printFeaturesUpto) { return; } try { if (cliqueWriter == null) { cliqueWriter = new PrintWriter(new FileOutputStream("feats" + flags.printFeatures + ".txt"), true); writtenNum = 0; } } catch (Exception ioe) { throw new RuntimeException(ioe); } if (writtenNum >= flags.printFeaturesUpto) { return; } if (wi instanceof CoreLabel) { cliqueWriter.print(wi.get(TextAnnotation.class) + ' ' + wi.get(PartOfSpeechAnnotation.class) + ' ' + wi.get(CoreAnnotations.GoldAnswerAnnotation.class) + '\t'); } else { cliqueWriter.print(wi.get(CoreAnnotations.TextAnnotation.class) + wi.get(CoreAnnotations.GoldAnswerAnnotation.class) + '\t'); } boolean first = true; for (Object feat : features) { if (first) { first = false; } else { cliqueWriter.print(" "); } cliqueWriter.print(feat); } cliqueWriter.println(); writtenNum++; } }
public class class_name { protected void printFeatures(IN wi, Collection<String> features) { if (flags.printFeatures == null || writtenNum > flags.printFeaturesUpto) { return; // depends on control dependency: [if], data = [none] } try { if (cliqueWriter == null) { cliqueWriter = new PrintWriter(new FileOutputStream("feats" + flags.printFeatures + ".txt"), true); // depends on control dependency: [if], data = [none] writtenNum = 0; // depends on control dependency: [if], data = [none] } } catch (Exception ioe) { throw new RuntimeException(ioe); } // depends on control dependency: [catch], data = [none] if (writtenNum >= flags.printFeaturesUpto) { return; // depends on control dependency: [if], data = [none] } if (wi instanceof CoreLabel) { cliqueWriter.print(wi.get(TextAnnotation.class) + ' ' + wi.get(PartOfSpeechAnnotation.class) + ' ' + wi.get(CoreAnnotations.GoldAnswerAnnotation.class) + '\t'); // depends on control dependency: [if], data = [none] } else { cliqueWriter.print(wi.get(CoreAnnotations.TextAnnotation.class) + wi.get(CoreAnnotations.GoldAnswerAnnotation.class) + '\t'); // depends on control dependency: [if], data = [none] } boolean first = true; for (Object feat : features) { if (first) { first = false; // depends on control dependency: [if], data = [none] } else { cliqueWriter.print(" "); // depends on control dependency: [if], data = [none] } cliqueWriter.print(feat); // depends on control dependency: [for], data = [feat] } cliqueWriter.println(); writtenNum++; } }
public class class_name { void takeMastership(int partitionId) { synchronized(m_dataSourcesByPartition) { Map<String, ExportDataSource> partitionDataSourceMap = m_dataSourcesByPartition.get(partitionId); // this case happens when there are no export tables if (partitionDataSourceMap == null) { return; } for( ExportDataSource eds: partitionDataSourceMap.values()) { eds.takeMastership(); } } } }
public class class_name { void takeMastership(int partitionId) { synchronized(m_dataSourcesByPartition) { Map<String, ExportDataSource> partitionDataSourceMap = m_dataSourcesByPartition.get(partitionId); // this case happens when there are no export tables if (partitionDataSourceMap == null) { return; // depends on control dependency: [if], data = [none] } for( ExportDataSource eds: partitionDataSourceMap.values()) { eds.takeMastership(); // depends on control dependency: [for], data = [eds] } } } }
public class class_name { @Override public void contextInitialized( final ServletContextEvent servletContextEvent) { logger.info("Rebuilding Search Index..."); // Build the session factory. SessionFactory factory = createSessionFactory(); // Build the hibernate session. Session session = factory.openSession(); // Create the fulltext session. FullTextSession fullTextSession = Search.getFullTextSession(session); try { fullTextSession .createIndexer() .startAndWait(); } catch (InterruptedException e) { logger.warn("Search reindex interrupted. Good luck!"); logger.trace("Error:", e); } finally { // Close everything and release the lock file. session.close(); factory.close(); } } }
public class class_name { @Override public void contextInitialized( final ServletContextEvent servletContextEvent) { logger.info("Rebuilding Search Index..."); // Build the session factory. SessionFactory factory = createSessionFactory(); // Build the hibernate session. Session session = factory.openSession(); // Create the fulltext session. FullTextSession fullTextSession = Search.getFullTextSession(session); try { fullTextSession .createIndexer() .startAndWait(); // depends on control dependency: [try], data = [none] } catch (InterruptedException e) { logger.warn("Search reindex interrupted. Good luck!"); logger.trace("Error:", e); } finally { // depends on control dependency: [catch], data = [none] // Close everything and release the lock file. session.close(); factory.close(); } } }
public class class_name { public static void installBinderService(final ServiceTarget serviceTarget, final String name, final Service<?> service, final ServiceName dependency) { final BindInfo bindInfo = ContextNames.bindInfoFor(name); final BinderService binderService = new BinderService(bindInfo.getBindName()); binderService.getManagedObjectInjector().inject(new ValueManagedReferenceFactory(service)); final ServiceBuilder serviceBuilder = serviceTarget.addService(bindInfo.getBinderServiceName(), binderService) .addDependency(bindInfo.getParentContextServiceName(), ServiceBasedNamingStore.class, binderService.getNamingStoreInjector()) // we set it in passive mode so that missing dependencies (which is possible/valid when it's a backup HornetQ server and the services // haven't been activated on it due to the presence of a different live server) don't cause jms-topic/jms-queue add operations // to fail .setInitialMode(ServiceController.Mode.PASSIVE); if (dependency != null) { serviceBuilder.requires(dependency); } serviceBuilder.install(); } }
public class class_name { public static void installBinderService(final ServiceTarget serviceTarget, final String name, final Service<?> service, final ServiceName dependency) { final BindInfo bindInfo = ContextNames.bindInfoFor(name); final BinderService binderService = new BinderService(bindInfo.getBindName()); binderService.getManagedObjectInjector().inject(new ValueManagedReferenceFactory(service)); final ServiceBuilder serviceBuilder = serviceTarget.addService(bindInfo.getBinderServiceName(), binderService) .addDependency(bindInfo.getParentContextServiceName(), ServiceBasedNamingStore.class, binderService.getNamingStoreInjector()) // we set it in passive mode so that missing dependencies (which is possible/valid when it's a backup HornetQ server and the services // haven't been activated on it due to the presence of a different live server) don't cause jms-topic/jms-queue add operations // to fail .setInitialMode(ServiceController.Mode.PASSIVE); if (dependency != null) { serviceBuilder.requires(dependency); // depends on control dependency: [if], data = [(dependency] } serviceBuilder.install(); } }
public class class_name { public static String convertCamelToUpperCase(String _str) { if (isEmpty(_str) || isAllUpperCase(_str)) { return _str; } StringBuffer sb = new StringBuffer(String.valueOf(_str.charAt(0)).toUpperCase()); for (int i = 1; i < _str.length(); i++) { char c = _str.charAt(i); if (c >= 'A' && c <= 'Z') { sb.append('_'); } sb.append(c); } return sb.toString().toUpperCase(); } }
public class class_name { public static String convertCamelToUpperCase(String _str) { if (isEmpty(_str) || isAllUpperCase(_str)) { return _str; // depends on control dependency: [if], data = [none] } StringBuffer sb = new StringBuffer(String.valueOf(_str.charAt(0)).toUpperCase()); for (int i = 1; i < _str.length(); i++) { char c = _str.charAt(i); if (c >= 'A' && c <= 'Z') { sb.append('_'); // depends on control dependency: [if], data = [none] } sb.append(c); // depends on control dependency: [for], data = [none] } return sb.toString().toUpperCase(); } }
public class class_name { protected void removeExecutor(final Executor e) { final Runnable task = new Runnable() { @Override public void run() { synchronized (Computer.this) { executors.remove(e); addNewExecutorIfNecessary(); if (!isAlive()) { AbstractCIBase ciBase = Jenkins.getInstanceOrNull(); if (ciBase != null) { // TODO confirm safe to assume non-null and use getInstance() ciBase.removeComputer(Computer.this); } } } } }; if (!Queue.tryWithLock(task)) { // JENKINS-28840 if we couldn't get the lock push the operation to a separate thread to avoid deadlocks threadPoolForRemoting.submit(Queue.wrapWithLock(task)); } } }
public class class_name { protected void removeExecutor(final Executor e) { final Runnable task = new Runnable() { @Override public void run() { synchronized (Computer.this) { executors.remove(e); addNewExecutorIfNecessary(); if (!isAlive()) { AbstractCIBase ciBase = Jenkins.getInstanceOrNull(); if (ciBase != null) { // TODO confirm safe to assume non-null and use getInstance() ciBase.removeComputer(Computer.this); // depends on control dependency: [if], data = [none] } } } } }; if (!Queue.tryWithLock(task)) { // JENKINS-28840 if we couldn't get the lock push the operation to a separate thread to avoid deadlocks threadPoolForRemoting.submit(Queue.wrapWithLock(task)); // depends on control dependency: [if], data = [none] } } }
public class class_name { private static Field getField(final Class cls, final String fieldName, boolean declared) { $.checkNotEmpty(fieldName); List<Field> fields = getFieldsList(cls, declared); for (int i = 0; i < fields.size(); i++) { if (fieldName.equals(fields.get(i).getName())) { return fields.get(i); } } return null; } }
public class class_name { private static Field getField(final Class cls, final String fieldName, boolean declared) { $.checkNotEmpty(fieldName); List<Field> fields = getFieldsList(cls, declared); for (int i = 0; i < fields.size(); i++) { if (fieldName.equals(fields.get(i).getName())) { return fields.get(i); // depends on control dependency: [if], data = [none] } } return null; } }
public class class_name { @Override public void addSourceTargetSet(UnicodeSet inputFilter, UnicodeSet sourceSet, UnicodeSet targetSet) { synchronized (UppercaseTransliterator.class) { if (sourceTargetUtility == null) { sourceTargetUtility = new SourceTargetUtility(new Transform<String,String>() { @Override public String transform(String source) { return UCharacter.foldCase(source, true); } }); } } sourceTargetUtility.addSourceTargetSet(this, inputFilter, sourceSet, targetSet); } }
public class class_name { @Override public void addSourceTargetSet(UnicodeSet inputFilter, UnicodeSet sourceSet, UnicodeSet targetSet) { synchronized (UppercaseTransliterator.class) { if (sourceTargetUtility == null) { sourceTargetUtility = new SourceTargetUtility(new Transform<String,String>() { @Override public String transform(String source) { return UCharacter.foldCase(source, true); } }); // depends on control dependency: [if], data = [none] } } sourceTargetUtility.addSourceTargetSet(this, inputFilter, sourceSet, targetSet); } }
public class class_name { @Override public void initialize() { if (detectChanges) { try { watcher = FileSystems.getDefault().newWatchService(); } catch (IOException e) { log.error("Can't start watcher service.", e); return; } } generateSqlInfos(); if (detectChanges) { // Path監視用のスレッド実行 es = Executors.newSingleThreadExecutor(); es.execute(this::watchPath); } } }
public class class_name { @Override public void initialize() { if (detectChanges) { try { watcher = FileSystems.getDefault().newWatchService(); // depends on control dependency: [try], data = [none] } catch (IOException e) { log.error("Can't start watcher service.", e); return; } // depends on control dependency: [catch], data = [none] } generateSqlInfos(); if (detectChanges) { // Path監視用のスレッド実行 es = Executors.newSingleThreadExecutor(); // depends on control dependency: [if], data = [none] es.execute(this::watchPath); // depends on control dependency: [if], data = [none] } } }
public class class_name { public boolean validate(DependencyExplorerOutput output, InvalidKeys invalidKeys) { Collection<Map.Entry<Key<?>, String>> invalidRequiredKeys = invalidKeys.getInvalidRequiredKeys(); for (Map.Entry<Key<?>, String> error : invalidRequiredKeys) { reportError(output, error.getKey(), error.getValue()); } return !cycleFinder.findAndReportCycles(output.getGraph()) && invalidRequiredKeys.isEmpty(); } }
public class class_name { public boolean validate(DependencyExplorerOutput output, InvalidKeys invalidKeys) { Collection<Map.Entry<Key<?>, String>> invalidRequiredKeys = invalidKeys.getInvalidRequiredKeys(); for (Map.Entry<Key<?>, String> error : invalidRequiredKeys) { reportError(output, error.getKey(), error.getValue()); // depends on control dependency: [for], data = [error] } return !cycleFinder.findAndReportCycles(output.getGraph()) && invalidRequiredKeys.isEmpty(); } }
public class class_name { public static String encode(final List<LatLng> path) { long lastLat = 0; long lastLng = 0; final StringBuilder result = new StringBuilder(); for (final LatLng point : path) { long lat = Math.round(point.lat * 1e5); long lng = Math.round(point.lng * 1e5); long dLat = lat - lastLat; long dLng = lng - lastLng; encode(dLat, result); encode(dLng, result); lastLat = lat; lastLng = lng; } return result.toString(); } }
public class class_name { public static String encode(final List<LatLng> path) { long lastLat = 0; long lastLng = 0; final StringBuilder result = new StringBuilder(); for (final LatLng point : path) { long lat = Math.round(point.lat * 1e5); long lng = Math.round(point.lng * 1e5); long dLat = lat - lastLat; long dLng = lng - lastLng; encode(dLat, result); // depends on control dependency: [for], data = [none] encode(dLng, result); // depends on control dependency: [for], data = [none] lastLat = lat; // depends on control dependency: [for], data = [none] lastLng = lng; // depends on control dependency: [for], data = [none] } return result.toString(); } }
public class class_name { static boolean polylineRelateMultiPoint_(Polyline polyline_a, MultiPoint multipoint_b, double tolerance, String scl, ProgressTracker progress_tracker) { RelationalOperationsMatrix relOps = new RelationalOperationsMatrix(); relOps.resetMatrix_(); relOps.setPredicates_(scl); relOps.setLinePointPredicates_(); Envelope2D env_a = new Envelope2D(), env_b = new Envelope2D(); polyline_a.queryEnvelope2D(env_a); multipoint_b.queryEnvelope2D(env_b); boolean bRelationKnown = false; boolean b_disjoint = RelationalOperations.envelopeDisjointEnvelope_( env_a, env_b, tolerance, progress_tracker); if (b_disjoint) { relOps.linePointDisjointPredicates_(polyline_a); bRelationKnown = true; } if (!bRelationKnown) { // Quick rasterize test to see whether the the geometries are // disjoint, or if one is contained in the other. int relation = RelationalOperations .tryRasterizedContainsOrDisjoint_(polyline_a, multipoint_b, tolerance, false); if (relation == RelationalOperations.Relation.disjoint) { relOps.linePointDisjointPredicates_(polyline_a); bRelationKnown = true; } } if (!bRelationKnown) { EditShape edit_shape = new EditShape(); int geom_a = edit_shape.addGeometry(polyline_a); int geom_b = edit_shape.addGeometry(multipoint_b); relOps.setEditShapeCrackAndCluster_(edit_shape, tolerance, progress_tracker); relOps.m_cluster_index_a = relOps.m_topo_graph .createUserIndexForClusters(); markClusterEndPoints_(geom_a, relOps.m_topo_graph, relOps.m_cluster_index_a); relOps.computeMatrixTopoGraphClusters_(geom_a, geom_b); relOps.m_topo_graph .deleteUserIndexForClusters(relOps.m_cluster_index_a); relOps.m_topo_graph.removeShape(); } boolean bRelation = relationCompare_(relOps.m_matrix, relOps.m_scl); return bRelation; } }
public class class_name { static boolean polylineRelateMultiPoint_(Polyline polyline_a, MultiPoint multipoint_b, double tolerance, String scl, ProgressTracker progress_tracker) { RelationalOperationsMatrix relOps = new RelationalOperationsMatrix(); relOps.resetMatrix_(); relOps.setPredicates_(scl); relOps.setLinePointPredicates_(); Envelope2D env_a = new Envelope2D(), env_b = new Envelope2D(); polyline_a.queryEnvelope2D(env_a); multipoint_b.queryEnvelope2D(env_b); boolean bRelationKnown = false; boolean b_disjoint = RelationalOperations.envelopeDisjointEnvelope_( env_a, env_b, tolerance, progress_tracker); if (b_disjoint) { relOps.linePointDisjointPredicates_(polyline_a); // depends on control dependency: [if], data = [none] bRelationKnown = true; // depends on control dependency: [if], data = [none] } if (!bRelationKnown) { // Quick rasterize test to see whether the the geometries are // disjoint, or if one is contained in the other. int relation = RelationalOperations .tryRasterizedContainsOrDisjoint_(polyline_a, multipoint_b, tolerance, false); if (relation == RelationalOperations.Relation.disjoint) { relOps.linePointDisjointPredicates_(polyline_a); // depends on control dependency: [if], data = [none] bRelationKnown = true; // depends on control dependency: [if], data = [none] } } if (!bRelationKnown) { EditShape edit_shape = new EditShape(); int geom_a = edit_shape.addGeometry(polyline_a); int geom_b = edit_shape.addGeometry(multipoint_b); relOps.setEditShapeCrackAndCluster_(edit_shape, tolerance, progress_tracker); // depends on control dependency: [if], data = [none] relOps.m_cluster_index_a = relOps.m_topo_graph .createUserIndexForClusters(); // depends on control dependency: [if], data = [none] markClusterEndPoints_(geom_a, relOps.m_topo_graph, relOps.m_cluster_index_a); // depends on control dependency: [if], data = [none] relOps.computeMatrixTopoGraphClusters_(geom_a, geom_b); // depends on control dependency: [if], data = [none] relOps.m_topo_graph .deleteUserIndexForClusters(relOps.m_cluster_index_a); // depends on control dependency: [if], data = [none] relOps.m_topo_graph.removeShape(); // depends on control dependency: [if], data = [none] } boolean bRelation = relationCompare_(relOps.m_matrix, relOps.m_scl); return bRelation; } }
public class class_name { private static boolean matchDns(String hostname, String tlsDnsPattern) throws SSLException { boolean hostIsIp = Utils.isIPv4(hostname) || Utils.isIPv6(hostname); StringTokenizer hostnameSt = new StringTokenizer(hostname.toLowerCase(Locale.ROOT), "."); StringTokenizer templateSt = new StringTokenizer(tlsDnsPattern.toLowerCase(Locale.ROOT), "."); if (hostnameSt.countTokens() != templateSt.countTokens()) { return false; } try { while (hostnameSt.hasMoreTokens()) { if (!matchWildCards(hostIsIp, hostnameSt.nextToken(), templateSt.nextToken())) { return false; } } } catch (SSLException exception) { throw new SSLException( normalizedHostMsg(hostname) + " doesn't correspond to certificate CN \"" + tlsDnsPattern + "\" : wildcards not possible for IPs"); } return true; } }
public class class_name { private static boolean matchDns(String hostname, String tlsDnsPattern) throws SSLException { boolean hostIsIp = Utils.isIPv4(hostname) || Utils.isIPv6(hostname); StringTokenizer hostnameSt = new StringTokenizer(hostname.toLowerCase(Locale.ROOT), "."); StringTokenizer templateSt = new StringTokenizer(tlsDnsPattern.toLowerCase(Locale.ROOT), "."); if (hostnameSt.countTokens() != templateSt.countTokens()) { return false; } try { while (hostnameSt.hasMoreTokens()) { if (!matchWildCards(hostIsIp, hostnameSt.nextToken(), templateSt.nextToken())) { return false; // depends on control dependency: [if], data = [none] } } } catch (SSLException exception) { throw new SSLException( normalizedHostMsg(hostname) + " doesn't correspond to certificate CN \"" + tlsDnsPattern + "\" : wildcards not possible for IPs"); } return true; } }
public class class_name { @JSConstructor public static Scriptable jsConstructor(Context cx, Object[] args, Function ctorObj, boolean inNewExpr) { File result = new File(); if (args.length == 0 || args[0] == Context.getUndefinedValue()) { result.name = ""; result.file = null; } else { result.name = Context.toString(args[0]); result.file = new java.io.File(result.name); } return result; } }
public class class_name { @JSConstructor public static Scriptable jsConstructor(Context cx, Object[] args, Function ctorObj, boolean inNewExpr) { File result = new File(); if (args.length == 0 || args[0] == Context.getUndefinedValue()) { result.name = ""; result.file = null; // depends on control dependency: [if], data = [none] } else { result.name = Context.toString(args[0]); // depends on control dependency: [if], data = [none] result.file = new java.io.File(result.name); // depends on control dependency: [if], data = [none] } return result; } }
public class class_name { void updateServer(ServerHeartbeat server, UpdateServerHeartbeat update) { if (server.isSelf()) { return; } String externalId = update.getExternalId(); updateExternal(server, externalId); // XXX: validation server.setSeedIndex(update.getSeedIndex()); if (server.onHeartbeatUpdate(update)) { if (server.isUp()) { onServerStart(server); } else { onServerStop(server); } } } }
public class class_name { void updateServer(ServerHeartbeat server, UpdateServerHeartbeat update) { if (server.isSelf()) { return; // depends on control dependency: [if], data = [none] } String externalId = update.getExternalId(); updateExternal(server, externalId); // XXX: validation server.setSeedIndex(update.getSeedIndex()); if (server.onHeartbeatUpdate(update)) { if (server.isUp()) { onServerStart(server); // depends on control dependency: [if], data = [none] } else { onServerStop(server); // depends on control dependency: [if], data = [none] } } } }
public class class_name { protected boolean accept(char c){ // Whitespace if(c == '\t' || c == '\n' || c == '\f' || c == '\r' || c == ' '){ return true; } // ASCII letters, numbers and control characters if(c >= '\u0021' && c <= '\u007f'){ return true; } // Latin-1 supplement letters if((c >= '\u00c0' && c <= '\u00d6') || (c >= '\u00d8' && c <= '\u00f6') || (c >= '\u00f8' && c <= '\u00ff')){ return true; } // Unicode letters if((c >= '\u0100' && c <= '\u1fff') || (c == '\u20ac' || c == '\u2122')){ return true; } return false; } }
public class class_name { protected boolean accept(char c){ // Whitespace if(c == '\t' || c == '\n' || c == '\f' || c == '\r' || c == ' '){ return true; // depends on control dependency: [if], data = [none] } // ASCII letters, numbers and control characters if(c >= '\u0021' && c <= '\u007f'){ return true; // depends on control dependency: [if], data = [none] } // Latin-1 supplement letters if((c >= '\u00c0' && c <= '\u00d6') || (c >= '\u00d8' && c <= '\u00f6') || (c >= '\u00f8' && c <= '\u00ff')){ return true; // depends on control dependency: [if], data = [none] } // Unicode letters if((c >= '\u0100' && c <= '\u1fff') || (c == '\u20ac' || c == '\u2122')){ return true; // depends on control dependency: [if], data = [none] } return false; } }
public class class_name { public void insertBlock(AbstractBaseDTNode<I, D> blockRoot) { blockRoot.removeFromBlockList(); blockRoot.setNextElement(next); if (getNextElement() != null) { next.setPrevElement(blockRoot); } blockRoot.setPrevElement(this); next = blockRoot; } }
public class class_name { public void insertBlock(AbstractBaseDTNode<I, D> blockRoot) { blockRoot.removeFromBlockList(); blockRoot.setNextElement(next); if (getNextElement() != null) { next.setPrevElement(blockRoot); // depends on control dependency: [if], data = [none] } blockRoot.setPrevElement(this); next = blockRoot; } }
public class class_name { private byte[] pbkdf2(final String password, final byte[] salt, int iterations) { try { Mac mac = Mac.getInstance(hmacAlgorithm); Key key; if (password == null || password.isEmpty()) { key = new EmptySecretKey(hmacAlgorithm); } else { key = new SecretKeySpec(password.getBytes(), hmacAlgorithm); } mac.init(key); mac.update(salt); mac.update("\00\00\00\01".getBytes()); // Append INT(1) byte[] un = mac.doFinal(); mac.update(un); byte[] uprev = mac.doFinal(); xor(un, uprev); for (int i = 2; i < iterations; ++i) { mac.update(uprev); uprev = mac.doFinal(); xor(un, uprev); } return un; } catch (InvalidKeyException e) { if (password == null || password.isEmpty()) { throw new UnsupportedOperationException("This JVM does not support empty HMAC keys (empty passwords). " + "Please set a bucket password or upgrade your JVM."); } else { throw new RuntimeException("Failed to generate HMAC hash for password", e); } } catch (Throwable t) { throw new RuntimeException(t); } } }
public class class_name { private byte[] pbkdf2(final String password, final byte[] salt, int iterations) { try { Mac mac = Mac.getInstance(hmacAlgorithm); Key key; if (password == null || password.isEmpty()) { key = new EmptySecretKey(hmacAlgorithm); // depends on control dependency: [if], data = [none] } else { key = new SecretKeySpec(password.getBytes(), hmacAlgorithm); // depends on control dependency: [if], data = [(password] } mac.init(key); // depends on control dependency: [try], data = [none] mac.update(salt); // depends on control dependency: [try], data = [none] mac.update("\00\00\00\01".getBytes()); // Append INT(1) // depends on control dependency: [try], data = [none] byte[] un = mac.doFinal(); mac.update(un); // depends on control dependency: [try], data = [none] byte[] uprev = mac.doFinal(); xor(un, uprev); // depends on control dependency: [try], data = [none] for (int i = 2; i < iterations; ++i) { mac.update(uprev); // depends on control dependency: [for], data = [none] uprev = mac.doFinal(); // depends on control dependency: [for], data = [none] xor(un, uprev); // depends on control dependency: [for], data = [none] } return un; // depends on control dependency: [try], data = [none] } catch (InvalidKeyException e) { if (password == null || password.isEmpty()) { throw new UnsupportedOperationException("This JVM does not support empty HMAC keys (empty passwords). " + "Please set a bucket password or upgrade your JVM."); } else { throw new RuntimeException("Failed to generate HMAC hash for password", e); } } catch (Throwable t) { // depends on control dependency: [catch], data = [none] throw new RuntimeException(t); } // depends on control dependency: [catch], data = [none] } }
public class class_name { @FFDCIgnore({ IllegalStateException.class, Exception.class }) public BundleLifecycleStatus uninstallBundles(final BundleContext bundleContext, final BundleList removeBundles, final BundleInstallStatus installStatus, ShutdownHookManager shutdownHook) { final List<Bundle> bundlesToUninstall = new ArrayList<Bundle>(); removeBundles.foreach(new FeatureResourceHandler() { @Override @FFDCIgnore({ Exception.class }) public boolean handle(FeatureResource fr) { try { Bundle b = removeBundles.getBundle(bundleContext, fr); // We found the bundle we want to uninstall if (b != null && b.getBundleId() > 0) { bundlesToUninstall.add(b); } } catch (Exception e) { installStatus.addInstallException("UNINSTALL " + fr.getLocation(), e); } return true; } }); // sort the bundle in reverse start-level order so that // start-phase is consistently honored Collections.sort(bundlesToUninstall, Collections.reverseOrder(BundleInstallStatus.sortByStartLevel)); for (Bundle bundleToUninstall : bundlesToUninstall) { try { bundleToUninstall.uninstall(); } catch (IllegalStateException e) { // ok: bundle already uninstalled or the framework is stopping, // determine if we should continue on to the next: // (if the bundle was uninstalled, but the framework is in perfect health), // or not (if the framework is stopping and we should just get done early). if (!!!FrameworkState.isValid()) { break; } } catch (Exception e) { installStatus.addInstallException("UNINSTALL " + bundleToUninstall.getLocation(), e); } } // Refresh bundles: provide a listener for notification of when refresh is complete RefreshBundlesListener listener = new RefreshBundlesListener(shutdownHook); FrameworkWiring wiring = adaptSystemBundle(bundleContext, FrameworkWiring.class); if (wiring != null) { wiring.refreshBundles(null, listener); // wait for refresh operation to complete listener.waitForComplete(); } return listener.getStatus(); } }
public class class_name { @FFDCIgnore({ IllegalStateException.class, Exception.class }) public BundleLifecycleStatus uninstallBundles(final BundleContext bundleContext, final BundleList removeBundles, final BundleInstallStatus installStatus, ShutdownHookManager shutdownHook) { final List<Bundle> bundlesToUninstall = new ArrayList<Bundle>(); removeBundles.foreach(new FeatureResourceHandler() { @Override @FFDCIgnore({ Exception.class }) public boolean handle(FeatureResource fr) { try { Bundle b = removeBundles.getBundle(bundleContext, fr); // We found the bundle we want to uninstall if (b != null && b.getBundleId() > 0) { bundlesToUninstall.add(b); // depends on control dependency: [if], data = [(b] } } catch (Exception e) { installStatus.addInstallException("UNINSTALL " + fr.getLocation(), e); } // depends on control dependency: [catch], data = [none] return true; } }); // sort the bundle in reverse start-level order so that // start-phase is consistently honored Collections.sort(bundlesToUninstall, Collections.reverseOrder(BundleInstallStatus.sortByStartLevel)); for (Bundle bundleToUninstall : bundlesToUninstall) { try { bundleToUninstall.uninstall(); // depends on control dependency: [try], data = [none] } catch (IllegalStateException e) { // ok: bundle already uninstalled or the framework is stopping, // determine if we should continue on to the next: // (if the bundle was uninstalled, but the framework is in perfect health), // or not (if the framework is stopping and we should just get done early). if (!!!FrameworkState.isValid()) { break; } } catch (Exception e) { // depends on control dependency: [catch], data = [none] installStatus.addInstallException("UNINSTALL " + bundleToUninstall.getLocation(), e); } // depends on control dependency: [catch], data = [none] } // Refresh bundles: provide a listener for notification of when refresh is complete RefreshBundlesListener listener = new RefreshBundlesListener(shutdownHook); FrameworkWiring wiring = adaptSystemBundle(bundleContext, FrameworkWiring.class); if (wiring != null) { wiring.refreshBundles(null, listener); // depends on control dependency: [if], data = [none] // wait for refresh operation to complete listener.waitForComplete(); // depends on control dependency: [if], data = [none] } return listener.getStatus(); } }
public class class_name { public void save(Map<String, Object> data) throws PersistenceException { logger.debug("enter - save(Map)"); try { Class<?> cls = persistent.getClass(); state = new HashMap<String, Object>(); while( cls != null && !cls.getName().equals(Object.class.getName()) ) { Field[] fields = cls.getDeclaredFields(); for( Field f : fields ) { int m = f.getModifiers(); if( Modifier.isTransient(m) || Modifier.isStatic(m) ) { continue; } f.setAccessible(true); state.put(f.getName(), f.get(persistent)); } cls = cls.getSuperclass(); } for( String key: data.keySet() ) { state.put(key, data.get(key)); } } catch( IllegalAccessException e ) { throw new PersistenceException(e.getMessage()); } finally { logger.debug("exit - save(Map)"); } } }
public class class_name { public void save(Map<String, Object> data) throws PersistenceException { logger.debug("enter - save(Map)"); try { Class<?> cls = persistent.getClass(); state = new HashMap<String, Object>(); while( cls != null && !cls.getName().equals(Object.class.getName()) ) { Field[] fields = cls.getDeclaredFields(); for( Field f : fields ) { int m = f.getModifiers(); if( Modifier.isTransient(m) || Modifier.isStatic(m) ) { continue; } f.setAccessible(true); // depends on control dependency: [for], data = [f] state.put(f.getName(), f.get(persistent)); // depends on control dependency: [for], data = [f] } cls = cls.getSuperclass(); // depends on control dependency: [while], data = [none] } for( String key: data.keySet() ) { state.put(key, data.get(key)); // depends on control dependency: [for], data = [key] } } catch( IllegalAccessException e ) { throw new PersistenceException(e.getMessage()); } finally { logger.debug("exit - save(Map)"); } } }
public class class_name { @SuppressWarnings("unchecked") private void siftDown (int k, E x) { int half = size >>> 1; // loop while a non-leaf while (k < half) { int child = (k << 1) + 1; // assume left child is least E c = (E)queue[child]; int right = child + 1; if (right < size && c.compareTo((E)queue[right]) > 0) c = (E)queue[child = right]; if (x.compareTo(c) <= 0) break; queue[k] = c; k = child; } queue[k] = x; } }
public class class_name { @SuppressWarnings("unchecked") private void siftDown (int k, E x) { int half = size >>> 1; // loop while a non-leaf while (k < half) { int child = (k << 1) + 1; // assume left child is least E c = (E)queue[child]; int right = child + 1; if (right < size && c.compareTo((E)queue[right]) > 0) c = (E)queue[child = right]; if (x.compareTo(c) <= 0) break; queue[k] = c; // depends on control dependency: [while], data = [none] k = child; // depends on control dependency: [while], data = [none] } queue[k] = x; } }
public class class_name { @Deprecated public static byte[] encodeToBytes(byte[] bytes) { try { char[] chars = Base64.encode(bytes); String string = new String(chars); return string.getBytes(DEFAULT_ENCODING); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } } }
public class class_name { @Deprecated public static byte[] encodeToBytes(byte[] bytes) { try { char[] chars = Base64.encode(bytes); String string = new String(chars); return string.getBytes(DEFAULT_ENCODING); // depends on control dependency: [try], data = [none] } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } // depends on control dependency: [catch], data = [none] } }
public class class_name { List<ColumnOrSuperColumn> getSlice(ColumnParent colParent, SlicePredicate slicePred, ByteBuffer key) { m_logger.debug("Fetching {}.{} from {}", new Object[]{Utils.toString(key), toString(slicePred), toString(colParent)}); List<ColumnOrSuperColumn> columnList = null; boolean bSuccess = false; for (int attempts = 1; !bSuccess; attempts++) { try { // Attempt to retrieve a slice list. Date startDate = new Date(); columnList = m_client.get_slice(key, colParent, slicePred, ConsistencyLevel.ONE); timing("get_slice", startDate); if (attempts > 1) { m_logger.info("get_slice() succeeded on attempt #{}", attempts); } bSuccess = true; } catch (InvalidRequestException ex) { // No point in retrying this one. String errMsg = "get_slice() failed for table: " + colParent.getColumn_family(); m_bFailed = true; m_logger.error(errMsg, ex); throw new RuntimeException(errMsg, ex); } catch (Exception ex) { // Abort if all retries exceeded. if (attempts >= m_max_read_attempts) { String errMsg = "All retries exceeded; abandoning get_slice() for table: " + colParent.getColumn_family(); m_bFailed = true; m_logger.error(errMsg, ex); throw new RuntimeException(errMsg, ex); } // Report retry as a warning. m_logger.warn("get_slice() attempt #{} failed: {}", attempts, ex); try { Thread.sleep(attempts * m_retry_wait_millis); } catch (InterruptedException e1) { // ignore } reconnect(ex); } } return columnList; } }
public class class_name { List<ColumnOrSuperColumn> getSlice(ColumnParent colParent, SlicePredicate slicePred, ByteBuffer key) { m_logger.debug("Fetching {}.{} from {}", new Object[]{Utils.toString(key), toString(slicePred), toString(colParent)}); List<ColumnOrSuperColumn> columnList = null; boolean bSuccess = false; for (int attempts = 1; !bSuccess; attempts++) { try { // Attempt to retrieve a slice list. Date startDate = new Date(); columnList = m_client.get_slice(key, colParent, slicePred, ConsistencyLevel.ONE); // depends on control dependency: [try], data = [none] timing("get_slice", startDate); // depends on control dependency: [try], data = [none] if (attempts > 1) { m_logger.info("get_slice() succeeded on attempt #{}", attempts); // depends on control dependency: [if], data = [none] } bSuccess = true; // depends on control dependency: [try], data = [none] } catch (InvalidRequestException ex) { // No point in retrying this one. String errMsg = "get_slice() failed for table: " + colParent.getColumn_family(); m_bFailed = true; m_logger.error(errMsg, ex); throw new RuntimeException(errMsg, ex); } catch (Exception ex) { // depends on control dependency: [catch], data = [none] // Abort if all retries exceeded. if (attempts >= m_max_read_attempts) { String errMsg = "All retries exceeded; abandoning get_slice() for table: " + colParent.getColumn_family(); // depends on control dependency: [if], data = [none] m_bFailed = true; // depends on control dependency: [if], data = [none] m_logger.error(errMsg, ex); // depends on control dependency: [if], data = [none] throw new RuntimeException(errMsg, ex); } // Report retry as a warning. m_logger.warn("get_slice() attempt #{} failed: {}", attempts, ex); try { Thread.sleep(attempts * m_retry_wait_millis); // depends on control dependency: [try], data = [none] } catch (InterruptedException e1) { // ignore } // depends on control dependency: [catch], data = [none] reconnect(ex); } // depends on control dependency: [catch], data = [none] } return columnList; } }
public class class_name { private URI handleLocalDita(final URI href, final AttributesImpl atts) { final URI attValue = href; final int sharpIndex = attValue.toString().indexOf(SHARP); URI pathFromMap; URI retAttValue; if (sharpIndex != -1) { // href value refer to an id in a topic if (sharpIndex == 0) { pathFromMap = toURI(filePath); } else { pathFromMap = toURI(filePath).resolve(attValue.toString().substring(0, sharpIndex)); } XMLUtils.addOrSetAttribute(atts, ATTRIBUTE_NAME_OHREF, toURI(pathFromMap + attValue.toString().substring(sharpIndex)).toString()); final String topicID = getTopicID(attValue.getFragment()); final int index = attValue.toString().indexOf(SLASH, sharpIndex); final String elementId = index != -1 ? attValue.toString().substring(index) : ""; final URI pathWithTopicID = setFragment(dirPath.toURI().resolve(pathFromMap), topicID); if (util.findId(pathWithTopicID)) {// topicId found retAttValue = toURI(SHARP + util.getIdValue(pathWithTopicID) + elementId); } else {// topicId not found retAttValue = toURI(SHARP + util.addId(pathWithTopicID) + elementId); } } else { // href value refer to a topic pathFromMap = toURI(filePath).resolve(attValue.toString()); URI absolutePath = dirPath.toURI().resolve(pathFromMap); XMLUtils.addOrSetAttribute(atts, ATTRIBUTE_NAME_OHREF, pathFromMap.toString()); if (util.findId(absolutePath)) { retAttValue = toURI(SHARP + util.getIdValue(absolutePath)); } else { final String fileId = util.getFirstTopicId(absolutePath, false); final URI key = setFragment(absolutePath, fileId); if (util.findId(key)) { util.addId(absolutePath, util.getIdValue(key)); retAttValue = toURI(SHARP + util.getIdValue(key)); } else { retAttValue = toURI(SHARP + util.addId(absolutePath)); util.addId(key, util.getIdValue(absolutePath)); } } } return retAttValue; } }
public class class_name { private URI handleLocalDita(final URI href, final AttributesImpl atts) { final URI attValue = href; final int sharpIndex = attValue.toString().indexOf(SHARP); URI pathFromMap; URI retAttValue; if (sharpIndex != -1) { // href value refer to an id in a topic if (sharpIndex == 0) { pathFromMap = toURI(filePath); // depends on control dependency: [if], data = [none] } else { pathFromMap = toURI(filePath).resolve(attValue.toString().substring(0, sharpIndex)); // depends on control dependency: [if], data = [none] } XMLUtils.addOrSetAttribute(atts, ATTRIBUTE_NAME_OHREF, toURI(pathFromMap + attValue.toString().substring(sharpIndex)).toString()); // depends on control dependency: [if], data = [(sharpIndex] final String topicID = getTopicID(attValue.getFragment()); final int index = attValue.toString().indexOf(SLASH, sharpIndex); final String elementId = index != -1 ? attValue.toString().substring(index) : ""; final URI pathWithTopicID = setFragment(dirPath.toURI().resolve(pathFromMap), topicID); if (util.findId(pathWithTopicID)) {// topicId found retAttValue = toURI(SHARP + util.getIdValue(pathWithTopicID) + elementId); // depends on control dependency: [if], data = [none] } else {// topicId not found retAttValue = toURI(SHARP + util.addId(pathWithTopicID) + elementId); // depends on control dependency: [if], data = [none] } } else { // href value refer to a topic pathFromMap = toURI(filePath).resolve(attValue.toString()); // depends on control dependency: [if], data = [none] URI absolutePath = dirPath.toURI().resolve(pathFromMap); XMLUtils.addOrSetAttribute(atts, ATTRIBUTE_NAME_OHREF, pathFromMap.toString()); // depends on control dependency: [if], data = [none] if (util.findId(absolutePath)) { retAttValue = toURI(SHARP + util.getIdValue(absolutePath)); // depends on control dependency: [if], data = [none] } else { final String fileId = util.getFirstTopicId(absolutePath, false); final URI key = setFragment(absolutePath, fileId); if (util.findId(key)) { util.addId(absolutePath, util.getIdValue(key)); // depends on control dependency: [if], data = [none] retAttValue = toURI(SHARP + util.getIdValue(key)); // depends on control dependency: [if], data = [none] } else { retAttValue = toURI(SHARP + util.addId(absolutePath)); // depends on control dependency: [if], data = [none] util.addId(key, util.getIdValue(absolutePath)); // depends on control dependency: [if], data = [none] } } } return retAttValue; } }
public class class_name { Iterator<Subscriber> getSubscribers(Object event) { ImmutableSet<Class<?>> eventTypes = flattenHierarchy(event.getClass()); List<Iterator<Subscriber>> subscriberIterators = Lists.newArrayListWithCapacity(eventTypes.size()); for (Class<?> eventType : eventTypes) { CopyOnWriteArraySet<Subscriber> eventSubscribers = subscribers.get(eventType); if (eventSubscribers != null) { // eager no-copy snapshot subscriberIterators.add(eventSubscribers.iterator()); } } return Iterators.concat(subscriberIterators.iterator()); } }
public class class_name { Iterator<Subscriber> getSubscribers(Object event) { ImmutableSet<Class<?>> eventTypes = flattenHierarchy(event.getClass()); List<Iterator<Subscriber>> subscriberIterators = Lists.newArrayListWithCapacity(eventTypes.size()); for (Class<?> eventType : eventTypes) { CopyOnWriteArraySet<Subscriber> eventSubscribers = subscribers.get(eventType); if (eventSubscribers != null) { // eager no-copy snapshot subscriberIterators.add(eventSubscribers.iterator()); // depends on control dependency: [if], data = [(eventSubscribers] } } return Iterators.concat(subscriberIterators.iterator()); } }
public class class_name { public List<Response> bulk(List<?> objects, boolean newEdits) { assertNotEmpty(objects, "objects"); HttpResponse response = null; try { final String newEditsVal = newEdits ? "\"new_edits\": true, " : "\"new_edits\": false, "; final String json = String.format("{%s%s%s}", newEditsVal, "\"docs\": ", getGson().toJson(objects)); final URI uri = buildUri(getDBUri()).path("_bulk_docs").build(); response = post(uri, json); return getResponseList(response); } finally { close(response); } } }
public class class_name { public List<Response> bulk(List<?> objects, boolean newEdits) { assertNotEmpty(objects, "objects"); HttpResponse response = null; try { final String newEditsVal = newEdits ? "\"new_edits\": true, " : "\"new_edits\": false, "; final String json = String.format("{%s%s%s}", newEditsVal, "\"docs\": ", getGson().toJson(objects)); final URI uri = buildUri(getDBUri()).path("_bulk_docs").build(); response = post(uri, json); // depends on control dependency: [try], data = [none] return getResponseList(response); // depends on control dependency: [try], data = [none] } finally { close(response); } } }
public class class_name { @Override public boolean hasNext() { currentObject = fetchObject(); if (count < fetchSize && fetchSize > 0 && currentObject != null) { count++; return true; } scrollComplete = true; return false; } }
public class class_name { @Override public boolean hasNext() { currentObject = fetchObject(); if (count < fetchSize && fetchSize > 0 && currentObject != null) { count++; // depends on control dependency: [if], data = [none] return true; // depends on control dependency: [if], data = [none] } scrollComplete = true; return false; } }
public class class_name { <T> T _deserialize(String body, Class<T> clazz) { if(body == null || body.isEmpty()){ throw new ServiceException(ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR, ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR.getMessageTemplate(), "the message body is empty"); } try { return deserialize(body.getBytes(), clazz); } catch (IOException e) { throw new ServiceException(ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR, e, ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR.getMessageTemplate(), "unrecognized message, deserialize failed."); } } }
public class class_name { <T> T _deserialize(String body, Class<T> clazz) { if(body == null || body.isEmpty()){ throw new ServiceException(ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR, ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR.getMessageTemplate(), "the message body is empty"); } try { return deserialize(body.getBytes(), clazz); // depends on control dependency: [try], data = [none] } catch (IOException e) { throw new ServiceException(ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR, e, ErrorCode.REMOTE_DIRECTORY_SERVER_ERROR.getMessageTemplate(), "unrecognized message, deserialize failed."); } // depends on control dependency: [catch], data = [none] } }
public class class_name { private static VarValueDef asValueDef( String valueName, JsonObject json) { try { VarValueDef valueDef = new VarValueDef( ObjectUtils.toObject( valueName)); // Get the type of this value boolean failure = json.getBoolean( FAILURE_KEY, false); boolean once = json.getBoolean( ONCE_KEY, false); valueDef.setType ( failure? VarValueDef.Type.FAILURE : once? VarValueDef.Type.ONCE : VarValueDef.Type.VALID); if( failure && json.containsKey( PROPERTIES_KEY)) { throw new SystemInputException( "Failure type values can't define properties"); } // Get annotations for this value Optional.ofNullable( json.getJsonObject( HAS_KEY)) .ifPresent( has -> has.keySet().stream().forEach( key -> valueDef.setAnnotation( key, has.getString( key)))); // Get the condition for this value Optional.ofNullable( json.getJsonObject( WHEN_KEY)) .ifPresent( object -> valueDef.setCondition( asValidCondition( object))); // Get properties for this value Optional.ofNullable( json.getJsonArray( PROPERTIES_KEY)) .map( properties -> toIdentifiers( properties)) .ifPresent( properties -> valueDef.addProperties( properties)); return valueDef; } catch( SystemInputException e) { throw new SystemInputException( String.format( "Error defining value=%s", valueName), e); } } }
public class class_name { private static VarValueDef asValueDef( String valueName, JsonObject json) { try { VarValueDef valueDef = new VarValueDef( ObjectUtils.toObject( valueName)); // Get the type of this value boolean failure = json.getBoolean( FAILURE_KEY, false); boolean once = json.getBoolean( ONCE_KEY, false); valueDef.setType ( failure? VarValueDef.Type.FAILURE : once? VarValueDef.Type.ONCE : VarValueDef.Type.VALID); // depends on control dependency: [try], data = [none] if( failure && json.containsKey( PROPERTIES_KEY)) { throw new SystemInputException( "Failure type values can't define properties"); } // Get annotations for this value Optional.ofNullable( json.getJsonObject( HAS_KEY)) .ifPresent( has -> has.keySet().stream().forEach( key -> valueDef.setAnnotation( key, has.getString( key)))); // depends on control dependency: [try], data = [none] // Get the condition for this value Optional.ofNullable( json.getJsonObject( WHEN_KEY)) .ifPresent( object -> valueDef.setCondition( asValidCondition( object))); // depends on control dependency: [try], data = [none] // Get properties for this value Optional.ofNullable( json.getJsonArray( PROPERTIES_KEY)) .map( properties -> toIdentifiers( properties)) .ifPresent( properties -> valueDef.addProperties( properties)); // depends on control dependency: [try], data = [none] return valueDef; // depends on control dependency: [try], data = [none] } catch( SystemInputException e) { throw new SystemInputException( String.format( "Error defining value=%s", valueName), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static void main(String[] args) { try { if (args.length != 4) { System.out.println("Usage: MpxjBatchConvert <source directory> <source suffix> <target directory> <target suffix>"); } else { File sourceDirectory = new File(args[0]); final String sourceSuffix = args[1]; String targetDirectory = args[2]; String targetSuffix = args[3]; File[] fileList = sourceDirectory.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.getName().endsWith(sourceSuffix); } }); if (fileList != null) { MpxjConvert convert = new MpxjConvert(); for (File file : fileList) { String oldName = file.getName(); String newName = oldName.substring(0, oldName.length() - sourceSuffix.length()) + targetSuffix; File newFile = new File(targetDirectory, newName); convert.process(file.getCanonicalPath(), newFile.getCanonicalPath()); } } } System.exit(0); } catch (Exception ex) { System.out.println(); System.out.print("Conversion Error: "); ex.printStackTrace(System.out); System.out.println(); System.exit(1); } } }
public class class_name { public static void main(String[] args) { try { if (args.length != 4) { System.out.println("Usage: MpxjBatchConvert <source directory> <source suffix> <target directory> <target suffix>"); // depends on control dependency: [if], data = [none] } else { File sourceDirectory = new File(args[0]); final String sourceSuffix = args[1]; String targetDirectory = args[2]; String targetSuffix = args[3]; File[] fileList = sourceDirectory.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.getName().endsWith(sourceSuffix); } }); if (fileList != null) { MpxjConvert convert = new MpxjConvert(); for (File file : fileList) { String oldName = file.getName(); String newName = oldName.substring(0, oldName.length() - sourceSuffix.length()) + targetSuffix; File newFile = new File(targetDirectory, newName); convert.process(file.getCanonicalPath(), newFile.getCanonicalPath()); // depends on control dependency: [for], data = [file] } } } System.exit(0); // depends on control dependency: [try], data = [none] } catch (Exception ex) { System.out.println(); System.out.print("Conversion Error: "); ex.printStackTrace(System.out); System.out.println(); System.exit(1); } // depends on control dependency: [catch], data = [none] } }
public class class_name { protected List<String> getTypeNames(CmsGalleryDataBean data) { List<String> types = new ArrayList<String>(); for (CmsResourceTypeBean info : data.getTypes()) { types.add(info.getType()); } return types; } }
public class class_name { protected List<String> getTypeNames(CmsGalleryDataBean data) { List<String> types = new ArrayList<String>(); for (CmsResourceTypeBean info : data.getTypes()) { types.add(info.getType()); // depends on control dependency: [for], data = [info] } return types; } }
public class class_name { public void marshall(Toolchain toolchain, ProtocolMarshaller protocolMarshaller) { if (toolchain == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(toolchain.getSource(), SOURCE_BINDING); protocolMarshaller.marshall(toolchain.getRoleArn(), ROLEARN_BINDING); protocolMarshaller.marshall(toolchain.getStackParameters(), STACKPARAMETERS_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(Toolchain toolchain, ProtocolMarshaller protocolMarshaller) { if (toolchain == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(toolchain.getSource(), SOURCE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(toolchain.getRoleArn(), ROLEARN_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(toolchain.getStackParameters(), STACKPARAMETERS_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 String decodePPM(byte[] data, int context) { try { BitInputStream in = new BitInputStream(new ByteArrayInputStream(data)); StringBuilder out = new StringBuilder(); String contextStr = ""; while (true) { TrieNode fromNode = inner.matchPredictor(getRight(contextStr, context)); if (0 == fromNode.getNumberOfChildren()) return ""; long seek = in.peekLongCoord(fromNode.getCursorCount()); TrieNode toNode = fromNode.traverse(seek + fromNode.getCursorIndex()); String newSegment = toNode.getString(fromNode); Interval interval = fromNode.intervalTo(toNode); Bits bits = interval.toBits(); if (verbose) { System.out.println(String.format( "Using prefix \"%s\", seek to %s pos, path \"%s\" run %s -> %s, input buffer = %s", fromNode.getDebugString(), seek, toNode.getDebugString(fromNode), interval, bits, in.peek(24))); } in.expect(bits); if (toNode.isStringTerminal()) { if (verbose) System.out.println("Inserting null char to terminate string"); newSegment += END_OF_STRING; } if (!newSegment.isEmpty()) { if (newSegment.endsWith("\u0000")) { out.append(newSegment.substring(0, newSegment.length() - 1)); if (verbose) System.out.println(String.format("Null char reached")); break; } else { contextStr += newSegment; out.append(newSegment); } } else if (in.availible() == 0) { if (verbose) System.out.println(String.format("No More Data")); break; } else if (toNode.getChar() == END_OF_STRING) { if (verbose) System.out.println(String.format("End code")); break; //throw new RuntimeException("Cannot decode text"); } else if (toNode.getChar() == FALLBACK) { contextStr = fromNode.getString().substring(1); } else if (toNode.getChar() == ESCAPE) { Bits charBits = in.read(16); char exotic = (char) charBits.toLong(); out.append(new String(new char[]{exotic})); if (verbose) { System.out.println(String.format( "Read exotic byte %s -> %s, input buffer = %s", exotic, charBits, in.peek(24))); } } else { if (verbose) System.out.println(String.format("Cannot decode text")); break; //throw new RuntimeException("Cannot decode text"); } } return out.toString(); } catch (IOException e) { throw new RuntimeException(e); } } }
public class class_name { public String decodePPM(byte[] data, int context) { try { BitInputStream in = new BitInputStream(new ByteArrayInputStream(data)); StringBuilder out = new StringBuilder(); String contextStr = ""; while (true) { TrieNode fromNode = inner.matchPredictor(getRight(contextStr, context)); if (0 == fromNode.getNumberOfChildren()) return ""; long seek = in.peekLongCoord(fromNode.getCursorCount()); TrieNode toNode = fromNode.traverse(seek + fromNode.getCursorIndex()); String newSegment = toNode.getString(fromNode); Interval interval = fromNode.intervalTo(toNode); Bits bits = interval.toBits(); if (verbose) { System.out.println(String.format( "Using prefix \"%s\", seek to %s pos, path \"%s\" run %s -> %s, input buffer = %s", fromNode.getDebugString(), seek, toNode.getDebugString(fromNode), interval, bits, in.peek(24))); // depends on control dependency: [if], data = [none] } in.expect(bits); // depends on control dependency: [while], data = [none] if (toNode.isStringTerminal()) { if (verbose) System.out.println("Inserting null char to terminate string"); newSegment += END_OF_STRING; // depends on control dependency: [if], data = [none] } if (!newSegment.isEmpty()) { if (newSegment.endsWith("\u0000")) { out.append(newSegment.substring(0, newSegment.length() - 1)); // depends on control dependency: [if], data = [none] if (verbose) System.out.println(String.format("Null char reached")); break; } else { contextStr += newSegment; // depends on control dependency: [if], data = [none] out.append(newSegment); // depends on control dependency: [if], data = [none] } } else if (in.availible() == 0) { if (verbose) System.out.println(String.format("No More Data")); break; } else if (toNode.getChar() == END_OF_STRING) { if (verbose) System.out.println(String.format("End code")); break; //throw new RuntimeException("Cannot decode text"); } else if (toNode.getChar() == FALLBACK) { contextStr = fromNode.getString().substring(1); // depends on control dependency: [if], data = [none] } else if (toNode.getChar() == ESCAPE) { Bits charBits = in.read(16); char exotic = (char) charBits.toLong(); out.append(new String(new char[]{exotic})); // depends on control dependency: [if], data = [none] if (verbose) { System.out.println(String.format( "Read exotic byte %s -> %s, input buffer = %s", exotic, charBits, in.peek(24))); // depends on control dependency: [if], data = [none] } } else { if (verbose) System.out.println(String.format("Cannot decode text")); break; //throw new RuntimeException("Cannot decode text"); } } return out.toString(); // depends on control dependency: [try], data = [none] } catch (IOException e) { throw new RuntimeException(e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { private static Subject setCallerSubject(Subject s) { Subject currentCallerSubject = null; SubjectManagerService sms = smServiceRef.getService(); if (sms != null) { if (s == null) { s = new Subject(); } currentCallerSubject = sms.getCallerSubject(); sms.setCallerSubject(s); } return currentCallerSubject; } }
public class class_name { private static Subject setCallerSubject(Subject s) { Subject currentCallerSubject = null; SubjectManagerService sms = smServiceRef.getService(); if (sms != null) { if (s == null) { s = new Subject(); // depends on control dependency: [if], data = [none] } currentCallerSubject = sms.getCallerSubject(); // depends on control dependency: [if], data = [none] sms.setCallerSubject(s); // depends on control dependency: [if], data = [none] } return currentCallerSubject; } }
public class class_name { public static Cookie getCookie(String name, HttpServletRequest request) { Cookie[] cookies = request.getCookies(); if (ArrayUtils.isNotEmpty(cookies)) { for (Cookie cookie : cookies) { if (cookie.getName().equals(name)) { return cookie; } } } return null; } }
public class class_name { public static Cookie getCookie(String name, HttpServletRequest request) { Cookie[] cookies = request.getCookies(); if (ArrayUtils.isNotEmpty(cookies)) { for (Cookie cookie : cookies) { if (cookie.getName().equals(name)) { return cookie; // depends on control dependency: [if], data = [none] } } } return null; } }
public class class_name { public void rebind(final Name name, Object object) throws NamingException { check(name, JndiPermission.ACTION_REBIND); if(namingStore instanceof WritableNamingStore) { final Name absoluteName = getAbsoluteName(name); if (object instanceof Referenceable) { object = ((Referenceable) object).getReference(); } getWritableNamingStore().rebind(absoluteName, object); } else { throw NamingLogger.ROOT_LOGGER.readOnlyNamingContext(); } } }
public class class_name { public void rebind(final Name name, Object object) throws NamingException { check(name, JndiPermission.ACTION_REBIND); if(namingStore instanceof WritableNamingStore) { final Name absoluteName = getAbsoluteName(name); if (object instanceof Referenceable) { object = ((Referenceable) object).getReference(); // depends on control dependency: [if], data = [none] } getWritableNamingStore().rebind(absoluteName, object); } else { throw NamingLogger.ROOT_LOGGER.readOnlyNamingContext(); } } }
public class class_name { private void fixScaleTrans() { fixTrans(); matrix.getValues(m); if (getImageWidth() < viewWidth) { m[Matrix.MTRANS_X] = (viewWidth - getImageWidth()) / 2; } if (getImageHeight() < viewHeight) { m[Matrix.MTRANS_Y] = (viewHeight - getImageHeight()) / 2; } matrix.setValues(m); } }
public class class_name { private void fixScaleTrans() { fixTrans(); matrix.getValues(m); if (getImageWidth() < viewWidth) { m[Matrix.MTRANS_X] = (viewWidth - getImageWidth()) / 2; // depends on control dependency: [if], data = [none] } if (getImageHeight() < viewHeight) { m[Matrix.MTRANS_Y] = (viewHeight - getImageHeight()) / 2; // depends on control dependency: [if], data = [none] } matrix.setValues(m); } }
public class class_name { private static String decodeUrl(String url) { if (url == null) { return null; } try { return URLDecoder.decode(url, CHARSET_UTF8); } catch (UnsupportedEncodingException e) { return url; } } }
public class class_name { private static String decodeUrl(String url) { if (url == null) { return null; // depends on control dependency: [if], data = [none] } try { return URLDecoder.decode(url, CHARSET_UTF8); // depends on control dependency: [try], data = [none] } catch (UnsupportedEncodingException e) { return url; } // depends on control dependency: [catch], data = [none] } }
public class class_name { public Iterator<Operator<Term>> traverse(Clause clause, boolean reverse) { /*log.fine("Traversing clause " + clause.toString(interner, true, false));*/ Functor head = clause.getHead(); Functor[] body = clause.getBody(); Queue<Operator<Term>> queue = (!reverse) ? new StackQueue<Operator<Term>>() : new LinkedList<Operator<Term>>(); // Create a nested scope in the symbol table for the clause, under its functor name/arity. int predicateName; int clauseIndex; if (clause.isQuery()) { predicateName = -1; } else { predicateName = head.getName(); } Integer numberOfClauses = (Integer) rootSymbolTable.get(predicateName, CLAUSE_NO_SYMBOL_FIELD); if (numberOfClauses == null) { numberOfClauses = 0; } rootSymbolTable.put(predicateName, CLAUSE_NO_SYMBOL_FIELD, numberOfClauses + 1); clauseIndex = numberOfClauses; SymbolTable<Integer, String, Object> predicateScopedSymbolTable = rootSymbolTable.enterScope(predicateName); /*log.fine(indenter.generateTraceIndent(2) + "Enter predicate scope " + predicateName);*/ clauseScopedSymbolTable = predicateScopedSymbolTable.enterScope(clauseIndex); /*log.fine(indenter.generateTraceIndent(2) + "Enter clause scope " + clauseIndex);*/ // For the head functor, clear the top-level flag, set in head context. if (head != null) { head.setReversable(new ContextOperator(clauseScopedSymbolTable, 0, createHeadOperator(head, clause))); head.setTermTraverser(this); queue.offer(head); /*log.fine("Set SKT as traverser on " + head.toString(interner, true, false));*/ /*log.fine("Created: " + ("head operator " + 0 + " on " + head.toString(interner, true, false)));*/ } // For the body functors, set the top-level flag, clear in head context. if (body != null) { for (int i = 0; i < body.length; i++) { Functor bodyFunctor = body[i]; bodyFunctor.setReversable(new ContextOperator(clauseScopedSymbolTable, i + 1, createBodyOperator(bodyFunctor, i, body, clause))); bodyFunctor.setTermTraverser(this); queue.offer(bodyFunctor); /*log.fine("Set SKT as traverser on " + bodyFunctor.toString(interner, true, false));*/ /*log.fine("Created: " + ("body operator " + (i + 1) + " on " + bodyFunctor.toString(interner, true, false)));*/ } } return queue.iterator(); } }
public class class_name { public Iterator<Operator<Term>> traverse(Clause clause, boolean reverse) { /*log.fine("Traversing clause " + clause.toString(interner, true, false));*/ Functor head = clause.getHead(); Functor[] body = clause.getBody(); Queue<Operator<Term>> queue = (!reverse) ? new StackQueue<Operator<Term>>() : new LinkedList<Operator<Term>>(); // Create a nested scope in the symbol table for the clause, under its functor name/arity. int predicateName; int clauseIndex; if (clause.isQuery()) { predicateName = -1; // depends on control dependency: [if], data = [none] } else { predicateName = head.getName(); // depends on control dependency: [if], data = [none] } Integer numberOfClauses = (Integer) rootSymbolTable.get(predicateName, CLAUSE_NO_SYMBOL_FIELD); if (numberOfClauses == null) { numberOfClauses = 0; // depends on control dependency: [if], data = [none] } rootSymbolTable.put(predicateName, CLAUSE_NO_SYMBOL_FIELD, numberOfClauses + 1); clauseIndex = numberOfClauses; SymbolTable<Integer, String, Object> predicateScopedSymbolTable = rootSymbolTable.enterScope(predicateName); /*log.fine(indenter.generateTraceIndent(2) + "Enter predicate scope " + predicateName);*/ clauseScopedSymbolTable = predicateScopedSymbolTable.enterScope(clauseIndex); /*log.fine(indenter.generateTraceIndent(2) + "Enter clause scope " + clauseIndex);*/ // For the head functor, clear the top-level flag, set in head context. if (head != null) { head.setReversable(new ContextOperator(clauseScopedSymbolTable, 0, createHeadOperator(head, clause))); // depends on control dependency: [if], data = [(head] head.setTermTraverser(this); // depends on control dependency: [if], data = [none] queue.offer(head); // depends on control dependency: [if], data = [(head] /*log.fine("Set SKT as traverser on " + head.toString(interner, true, false));*/ /*log.fine("Created: " + ("head operator " + 0 + " on " + head.toString(interner, true, false)));*/ } // For the body functors, set the top-level flag, clear in head context. if (body != null) { for (int i = 0; i < body.length; i++) { Functor bodyFunctor = body[i]; bodyFunctor.setReversable(new ContextOperator(clauseScopedSymbolTable, i + 1, createBodyOperator(bodyFunctor, i, body, clause))); // depends on control dependency: [for], data = [none] bodyFunctor.setTermTraverser(this); // depends on control dependency: [for], data = [none] queue.offer(bodyFunctor); // depends on control dependency: [for], data = [none] /*log.fine("Set SKT as traverser on " + bodyFunctor.toString(interner, true, false));*/ /*log.fine("Created: " + ("body operator " + (i + 1) + " on " + bodyFunctor.toString(interner, true, false)));*/ } } return queue.iterator(); } }
public class class_name { private static List<String> parseExecParameters(String paramText) { final String SafeParamStringValuePattern = "#(SQL_PARSER_SAFE_PARAMSTRING)"; // Find all quoted strings. // Mask out strings that contain whitespace or commas // that must not be confused with parameter separators. // "Safe" strings that don't contain these characters don't need to be masked // but they DO need to be found and explicitly skipped so that their closing // quotes don't trigger a false positive for the START of an unsafe string. // Skipping is accomplished by resetting paramText to an offset substring // after copying the skipped (or substituted) text to a string builder. ArrayList<String> originalString = new ArrayList<>(); Matcher stringMatcher = SingleQuotedString.matcher(paramText); StringBuilder safeText = new StringBuilder(); while (stringMatcher.find()) { // Save anything before the found string. safeText.append(paramText.substring(0, stringMatcher.start())); String asMatched = stringMatcher.group(); if (SingleQuotedStringContainingParameterSeparators.matcher(asMatched).matches()) { // The matched string is unsafe, provide cover for it in safeText. originalString.add(asMatched); safeText.append(SafeParamStringValuePattern); } else { // The matched string is safe. Add it to safeText. safeText.append(asMatched); } paramText = paramText.substring(stringMatcher.end()); stringMatcher = SingleQuotedString.matcher(paramText); } // Save anything after the last found string. safeText.append(paramText); ArrayList<String> params = new ArrayList<>(); int subCount = 0; int neededSubs = originalString.size(); // Split the params at the separators String[] split = safeText.toString().split("[\\s,]+"); for (String fragment : split) { if (fragment.isEmpty()) { continue; // ignore effects of leading or trailing separators } // Replace each substitution in order exactly once. if (subCount < neededSubs) { // Substituted strings will normally take up an entire parameter, // but some cases like parameters containing escaped single quotes // may require multiple serial substitutions. while (fragment.indexOf(SafeParamStringValuePattern) > -1) { fragment = fragment.replace(SafeParamStringValuePattern, originalString.get(subCount)); ++subCount; } } params.add(fragment); } assert(subCount == neededSubs); return params; } }
public class class_name { private static List<String> parseExecParameters(String paramText) { final String SafeParamStringValuePattern = "#(SQL_PARSER_SAFE_PARAMSTRING)"; // Find all quoted strings. // Mask out strings that contain whitespace or commas // that must not be confused with parameter separators. // "Safe" strings that don't contain these characters don't need to be masked // but they DO need to be found and explicitly skipped so that their closing // quotes don't trigger a false positive for the START of an unsafe string. // Skipping is accomplished by resetting paramText to an offset substring // after copying the skipped (or substituted) text to a string builder. ArrayList<String> originalString = new ArrayList<>(); Matcher stringMatcher = SingleQuotedString.matcher(paramText); StringBuilder safeText = new StringBuilder(); while (stringMatcher.find()) { // Save anything before the found string. safeText.append(paramText.substring(0, stringMatcher.start())); // depends on control dependency: [while], data = [none] String asMatched = stringMatcher.group(); if (SingleQuotedStringContainingParameterSeparators.matcher(asMatched).matches()) { // The matched string is unsafe, provide cover for it in safeText. originalString.add(asMatched); // depends on control dependency: [if], data = [none] safeText.append(SafeParamStringValuePattern); // depends on control dependency: [if], data = [none] } else { // The matched string is safe. Add it to safeText. safeText.append(asMatched); // depends on control dependency: [if], data = [none] } paramText = paramText.substring(stringMatcher.end()); // depends on control dependency: [while], data = [none] stringMatcher = SingleQuotedString.matcher(paramText); // depends on control dependency: [while], data = [none] } // Save anything after the last found string. safeText.append(paramText); ArrayList<String> params = new ArrayList<>(); int subCount = 0; int neededSubs = originalString.size(); // Split the params at the separators String[] split = safeText.toString().split("[\\s,]+"); for (String fragment : split) { if (fragment.isEmpty()) { continue; // ignore effects of leading or trailing separators } // Replace each substitution in order exactly once. if (subCount < neededSubs) { // Substituted strings will normally take up an entire parameter, // but some cases like parameters containing escaped single quotes // may require multiple serial substitutions. while (fragment.indexOf(SafeParamStringValuePattern) > -1) { fragment = fragment.replace(SafeParamStringValuePattern, originalString.get(subCount)); // depends on control dependency: [while], data = [none] ++subCount; // depends on control dependency: [while], data = [none] } } params.add(fragment); // depends on control dependency: [for], data = [fragment] } assert(subCount == neededSubs); return params; } }
public class class_name { public ListDocumentsRequest withDocumentFilterList(DocumentFilter... documentFilterList) { if (this.documentFilterList == null) { setDocumentFilterList(new com.amazonaws.internal.SdkInternalList<DocumentFilter>(documentFilterList.length)); } for (DocumentFilter ele : documentFilterList) { this.documentFilterList.add(ele); } return this; } }
public class class_name { public ListDocumentsRequest withDocumentFilterList(DocumentFilter... documentFilterList) { if (this.documentFilterList == null) { setDocumentFilterList(new com.amazonaws.internal.SdkInternalList<DocumentFilter>(documentFilterList.length)); // depends on control dependency: [if], data = [none] } for (DocumentFilter ele : documentFilterList) { this.documentFilterList.add(ele); // depends on control dependency: [for], data = [ele] } return this; } }
public class class_name { public void write(Parameters parameters) throws IOException { if (parameters != null) { for (Parameter pv : parameters.getParameterValueMap().values()) { if (pv.isAssigned()) { write(pv); } } } } }
public class class_name { public void write(Parameters parameters) throws IOException { if (parameters != null) { for (Parameter pv : parameters.getParameterValueMap().values()) { if (pv.isAssigned()) { write(pv); // depends on control dependency: [if], data = [none] } } } } }
public class class_name { public static boolean isChineseNumber(final String text, final int start, final int len){ for(int i=start; i<start+len; i++){ char c = text.charAt(i); boolean isChineseNumber = false; for(char chineseNumber : chineseNumbers){ if(c == chineseNumber){ isChineseNumber = true; break; } } if(!isChineseNumber){ return false; } } //指定的字符串已经识别为中文数字串 //下面要判断中文数字串是否完整 if(start>0){ //判断前一个字符,如果为中文数字字符则识别失败 char c = text.charAt(start-1); for(char chineseNumber : chineseNumbers){ if(c == chineseNumber){ return false; } } } if(start+len < text.length()){ //判断后一个字符,如果为中文数字字符则识别失败 char c = text.charAt(start+len); for(char chineseNumber : chineseNumbers){ if(c == chineseNumber){ return false; } } } if(LOGGER.isDebugEnabled()) { LOGGER.debug("识别出中文数字:" + text.substring(start, start + len)); } return true; } }
public class class_name { public static boolean isChineseNumber(final String text, final int start, final int len){ for(int i=start; i<start+len; i++){ char c = text.charAt(i); boolean isChineseNumber = false; for(char chineseNumber : chineseNumbers){ if(c == chineseNumber){ isChineseNumber = true; // depends on control dependency: [if], data = [none] break; } } if(!isChineseNumber){ return false; // depends on control dependency: [if], data = [none] } } //指定的字符串已经识别为中文数字串 //下面要判断中文数字串是否完整 if(start>0){ //判断前一个字符,如果为中文数字字符则识别失败 char c = text.charAt(start-1); for(char chineseNumber : chineseNumbers){ if(c == chineseNumber){ return false; // depends on control dependency: [if], data = [none] } } } if(start+len < text.length()){ //判断后一个字符,如果为中文数字字符则识别失败 char c = text.charAt(start+len); for(char chineseNumber : chineseNumbers){ if(c == chineseNumber){ return false; // depends on control dependency: [if], data = [none] } } } if(LOGGER.isDebugEnabled()) { LOGGER.debug("识别出中文数字:" + text.substring(start, start + len)); // depends on control dependency: [if], data = [none] } return true; } }
public class class_name { private void drawElements(Bbox bounds, String url) { if (bounds != null && url != null) { drawRedRectangle(bounds, container); drawImageFromUrl(url, bounds, container); } } }
public class class_name { private void drawElements(Bbox bounds, String url) { if (bounds != null && url != null) { drawRedRectangle(bounds, container); // depends on control dependency: [if], data = [(bounds] drawImageFromUrl(url, bounds, container); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static String escapeAssertion(String s) { //Replace the first dot, because the string doesn't start with "m=" // and is not covered by the regex. if (s.startsWith("r") || s.startsWith("p")) { s = s.replaceFirst("\\.", "_"); } String regex = "(\\|| |=|\\)|\\(|&|<|>|,|\\+|-|!|\\*|\\/)(r|p)\\."; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(s); StringBuffer sb = new StringBuffer(); while (m.find()) { m.appendReplacement(sb, m.group().replace(".", "_") ); } m.appendTail(sb); return sb.toString(); } }
public class class_name { public static String escapeAssertion(String s) { //Replace the first dot, because the string doesn't start with "m=" // and is not covered by the regex. if (s.startsWith("r") || s.startsWith("p")) { s = s.replaceFirst("\\.", "_"); // depends on control dependency: [if], data = [none] } String regex = "(\\|| |=|\\)|\\(|&|<|>|,|\\+|-|!|\\*|\\/)(r|p)\\."; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(s); StringBuffer sb = new StringBuffer(); while (m.find()) { m.appendReplacement(sb, m.group().replace(".", "_") ); } m.appendTail(sb); return sb.toString(); } }
public class class_name { @CheckReturnValue @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static Flowable<Long> rangeLong(long start, long count) { if (count < 0) { throw new IllegalArgumentException("count >= 0 required but it was " + count); } if (count == 0) { return empty(); } if (count == 1) { return just(start); } long end = start + (count - 1); if (start > 0 && end < 0) { throw new IllegalArgumentException("Overflow! start + count is bigger than Long.MAX_VALUE"); } return RxJavaPlugins.onAssembly(new FlowableRangeLong(start, count)); } }
public class class_name { @CheckReturnValue @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public static Flowable<Long> rangeLong(long start, long count) { if (count < 0) { throw new IllegalArgumentException("count >= 0 required but it was " + count); } if (count == 0) { return empty(); // depends on control dependency: [if], data = [none] } if (count == 1) { return just(start); // depends on control dependency: [if], data = [none] } long end = start + (count - 1); if (start > 0 && end < 0) { throw new IllegalArgumentException("Overflow! start + count is bigger than Long.MAX_VALUE"); } return RxJavaPlugins.onAssembly(new FlowableRangeLong(start, count)); } }
public class class_name { public static String queryString(Connection con, String def, String query, Object... param) throws SQLException { PreparedStatement stmt = null; try { stmt = con.prepareStatement(query); stmt.setMaxRows(1); for (int i = 0; i < param.length; i++) { stmt.setObject(i + 1, param[i]); } return queryString(stmt, def); } finally { close(stmt); } } }
public class class_name { public static String queryString(Connection con, String def, String query, Object... param) throws SQLException { PreparedStatement stmt = null; try { stmt = con.prepareStatement(query); // depends on control dependency: [try], data = [none] stmt.setMaxRows(1); // depends on control dependency: [try], data = [none] for (int i = 0; i < param.length; i++) { stmt.setObject(i + 1, param[i]); // depends on control dependency: [for], data = [i] } return queryString(stmt, def); // depends on control dependency: [try], data = [none] } finally { close(stmt); } } }
public class class_name { @SafeVarargs public static <T extends Throwable, C extends Class<? extends T>> T findCause(Throwable root, C... ofClasses) { for (C c : ofClasses) { Throwable t = root; while (t != null) { if (c.isInstance(t)) { return c.cast(t); } t = t.getCause(); } } return null; } }
public class class_name { @SafeVarargs public static <T extends Throwable, C extends Class<? extends T>> T findCause(Throwable root, C... ofClasses) { for (C c : ofClasses) { Throwable t = root; while (t != null) { if (c.isInstance(t)) { return c.cast(t); // depends on control dependency: [if], data = [none] } t = t.getCause(); // depends on control dependency: [while], data = [none] } } return null; } }
public class class_name { private List<String> getDefaultTextValue(FormField field) { // Get the Id String fieldId = field.getName(); // Create new HashMap 'fieldAttributes' and new list 'definedValues' Map<String, String> fieldAttributes = new HashMap<String, String>(); List<String> definedValues = new ArrayList<String>(); //Store all values in the FormFiled field into the Map 'fieldAttributes' fieldAttributes.putAll(field.getFormControl().getAttributesMap()); // Places a key, Control Type, for each FormControlType fieldAttributes.put("Control Type", field.getFormControl().getFormControlType().name()); //Handles Submit Fields if (field.getFormControl().getFormControlType().isSubmit()) { List<String> submitFields = new ArrayList<String>(); for (String value : field.getPredefinedValues()){ String finalValue = this.valueGenerator.getValue(uri, url, fieldId, value, definedValues, envAttributes, fieldAttributes); submitFields.add(finalValue); } return submitFields; } // Get its value(s) List<String> values = field.getValues(); String defaultValue; //If the field has a value attribute present(Predefined value) //Should store the value being submitted to be passed to the ValueGenerator if(field.getFormControl().getAttributesMap().containsKey("value")){ defaultValue = field.getFormControl().getAttributesMap().get("value"); } if (log.isDebugEnabled()) { log.debug("Existing values: " + values); } // If there are no values at all or only an empty value if (values.isEmpty() || (values.size() == 1 && values.get(0).isEmpty())) { defaultValue = DEFAULT_EMPTY_VALUE; // Check if we can use predefined values Collection<String> predefValues = field.getPredefinedValues(); if (!predefValues.isEmpty()) { //Store those predefined values in a list for the DefaultValueGenerator definedValues.addAll(predefValues); // Try first elements Iterator<String> iterator = predefValues.iterator(); defaultValue = iterator.next(); // If there are more values, don't use the first, as it usually is a "No select" // item if (iterator.hasNext()) { defaultValue = iterator.next(); } } } else { defaultValue = values.get(0); } //Get the default value used in DefaultValueGenerator String finalValue = this.valueGenerator.getValue(uri, url, fieldId, defaultValue, definedValues, envAttributes, fieldAttributes); log.debug("Generated: " + finalValue + "For field " + field.getName()); values = new ArrayList<>(1); values.add(finalValue); return values; } }
public class class_name { private List<String> getDefaultTextValue(FormField field) { // Get the Id String fieldId = field.getName(); // Create new HashMap 'fieldAttributes' and new list 'definedValues' Map<String, String> fieldAttributes = new HashMap<String, String>(); List<String> definedValues = new ArrayList<String>(); //Store all values in the FormFiled field into the Map 'fieldAttributes' fieldAttributes.putAll(field.getFormControl().getAttributesMap()); // Places a key, Control Type, for each FormControlType fieldAttributes.put("Control Type", field.getFormControl().getFormControlType().name()); //Handles Submit Fields if (field.getFormControl().getFormControlType().isSubmit()) { List<String> submitFields = new ArrayList<String>(); for (String value : field.getPredefinedValues()){ String finalValue = this.valueGenerator.getValue(uri, url, fieldId, value, definedValues, envAttributes, fieldAttributes); submitFields.add(finalValue); // depends on control dependency: [for], data = [none] } return submitFields; // depends on control dependency: [if], data = [none] } // Get its value(s) List<String> values = field.getValues(); String defaultValue; //If the field has a value attribute present(Predefined value) //Should store the value being submitted to be passed to the ValueGenerator if(field.getFormControl().getAttributesMap().containsKey("value")){ defaultValue = field.getFormControl().getAttributesMap().get("value"); // depends on control dependency: [if], data = [none] } if (log.isDebugEnabled()) { log.debug("Existing values: " + values); // depends on control dependency: [if], data = [none] } // If there are no values at all or only an empty value if (values.isEmpty() || (values.size() == 1 && values.get(0).isEmpty())) { defaultValue = DEFAULT_EMPTY_VALUE; // depends on control dependency: [if], data = [none] // Check if we can use predefined values Collection<String> predefValues = field.getPredefinedValues(); if (!predefValues.isEmpty()) { //Store those predefined values in a list for the DefaultValueGenerator definedValues.addAll(predefValues); // depends on control dependency: [if], data = [none] // Try first elements Iterator<String> iterator = predefValues.iterator(); defaultValue = iterator.next(); // depends on control dependency: [if], data = [none] // If there are more values, don't use the first, as it usually is a "No select" // item if (iterator.hasNext()) { defaultValue = iterator.next(); // depends on control dependency: [if], data = [none] } } } else { defaultValue = values.get(0); // depends on control dependency: [if], data = [none] } //Get the default value used in DefaultValueGenerator String finalValue = this.valueGenerator.getValue(uri, url, fieldId, defaultValue, definedValues, envAttributes, fieldAttributes); log.debug("Generated: " + finalValue + "For field " + field.getName()); values = new ArrayList<>(1); values.add(finalValue); return values; } }
public class class_name { private static Set getCryptoImpls(String serviceType) { Set result = new TreeSet(); // All all providers Provider[] providers = Security.getProviders(); for (int i = 0; i < providers.length; i++) { // Get services provided by each provider Set keys = providers[i].keySet(); for (Object okey : providers[i].keySet()) { String key = (String) okey; key = key.split(" ")[0]; if (key.startsWith(serviceType + ".")) { result.add(key.substring(serviceType.length() + 1)); } else if (key.startsWith("Alg.Alias." + serviceType + ".")) { // This is an alias result.add(key.substring(serviceType.length() + 11)); } } } return result; } }
public class class_name { private static Set getCryptoImpls(String serviceType) { Set result = new TreeSet(); // All all providers Provider[] providers = Security.getProviders(); for (int i = 0; i < providers.length; i++) { // Get services provided by each provider Set keys = providers[i].keySet(); for (Object okey : providers[i].keySet()) { String key = (String) okey; key = key.split(" ")[0]; // depends on control dependency: [for], data = [none] if (key.startsWith(serviceType + ".")) { result.add(key.substring(serviceType.length() + 1)); // depends on control dependency: [if], data = [none] } else if (key.startsWith("Alg.Alias." + serviceType + ".")) { // This is an alias result.add(key.substring(serviceType.length() + 11)); // depends on control dependency: [if], data = [none] } } } return result; } }
public class class_name { public GraphType transpose(GraphType orig, GraphToolkit<GraphType, EdgeType, VertexType> toolkit) { GraphType trans = toolkit.createGraph(); // For each vertex in original graph, create an equivalent // vertex in the transposed graph, // ensuring that vertex labels in the transposed graph // match vertex labels in the original graph for (Iterator<VertexType> i = orig.vertexIterator(); i.hasNext();) { VertexType v = i.next(); // Make a duplicate of original vertex // (Ensuring that transposed graph has same labeling as original) VertexType dupVertex = toolkit.duplicateVertex(v); dupVertex.setLabel(v.getLabel()); trans.addVertex(v); // Keep track of correspondence between equivalent vertices m_origToTransposeMap.put(v, dupVertex); m_transposeToOrigMap.put(dupVertex, v); } trans.setNumVertexLabels(orig.getNumVertexLabels()); // For each edge in the original graph, create a reversed edge // in the transposed graph for (Iterator<EdgeType> i = orig.edgeIterator(); i.hasNext();) { EdgeType e = i.next(); VertexType transSource = m_origToTransposeMap.get(e.getTarget()); VertexType transTarget = m_origToTransposeMap.get(e.getSource()); EdgeType dupEdge = trans.createEdge(transSource, transTarget); dupEdge.setLabel(e.getLabel()); // Copy auxiliary information for edge toolkit.copyEdge(e, dupEdge); } trans.setNumEdgeLabels(orig.getNumEdgeLabels()); return trans; } }
public class class_name { public GraphType transpose(GraphType orig, GraphToolkit<GraphType, EdgeType, VertexType> toolkit) { GraphType trans = toolkit.createGraph(); // For each vertex in original graph, create an equivalent // vertex in the transposed graph, // ensuring that vertex labels in the transposed graph // match vertex labels in the original graph for (Iterator<VertexType> i = orig.vertexIterator(); i.hasNext();) { VertexType v = i.next(); // Make a duplicate of original vertex // (Ensuring that transposed graph has same labeling as original) VertexType dupVertex = toolkit.duplicateVertex(v); dupVertex.setLabel(v.getLabel()); // depends on control dependency: [for], data = [none] trans.addVertex(v); // depends on control dependency: [for], data = [none] // Keep track of correspondence between equivalent vertices m_origToTransposeMap.put(v, dupVertex); // depends on control dependency: [for], data = [none] m_transposeToOrigMap.put(dupVertex, v); // depends on control dependency: [for], data = [none] } trans.setNumVertexLabels(orig.getNumVertexLabels()); // For each edge in the original graph, create a reversed edge // in the transposed graph for (Iterator<EdgeType> i = orig.edgeIterator(); i.hasNext();) { EdgeType e = i.next(); VertexType transSource = m_origToTransposeMap.get(e.getTarget()); VertexType transTarget = m_origToTransposeMap.get(e.getSource()); EdgeType dupEdge = trans.createEdge(transSource, transTarget); dupEdge.setLabel(e.getLabel()); // depends on control dependency: [for], data = [none] // Copy auxiliary information for edge toolkit.copyEdge(e, dupEdge); // depends on control dependency: [for], data = [none] } trans.setNumEdgeLabels(orig.getNumEdgeLabels()); return trans; } }
public class class_name { public long getPID() { long currentPID = cachedPID.get(); if (currentPID != 0) { return currentPID; } try { currentPID = detectPID(); } catch (Throwable cause) { logger.info("Unable to detect process ID!", cause); } if (currentPID == 0) { currentPID = System.nanoTime(); if (!cachedPID.compareAndSet(0, currentPID)) { currentPID = cachedPID.get(); } } else { cachedPID.set(currentPID); } return currentPID; } }
public class class_name { public long getPID() { long currentPID = cachedPID.get(); if (currentPID != 0) { return currentPID; // depends on control dependency: [if], data = [none] } try { currentPID = detectPID(); // depends on control dependency: [try], data = [none] } catch (Throwable cause) { logger.info("Unable to detect process ID!", cause); } // depends on control dependency: [catch], data = [none] if (currentPID == 0) { currentPID = System.nanoTime(); // depends on control dependency: [if], data = [none] if (!cachedPID.compareAndSet(0, currentPID)) { currentPID = cachedPID.get(); // depends on control dependency: [if], data = [none] } } else { cachedPID.set(currentPID); // depends on control dependency: [if], data = [(currentPID] } return currentPID; } }
public class class_name { public List<JAXBElement<? extends AbstractGeometryType>> get_Geometry() { if (_Geometry == null) { _Geometry = new ArrayList<JAXBElement<? extends AbstractGeometryType>>(); } return this._Geometry; } }
public class class_name { public List<JAXBElement<? extends AbstractGeometryType>> get_Geometry() { if (_Geometry == null) { _Geometry = new ArrayList<JAXBElement<? extends AbstractGeometryType>>(); // depends on control dependency: [if], data = [none] } return this._Geometry; } }
public class class_name { public static int indexOf( String[] array, String s ) { for (int index = 0; index < array.length; index++) { if( s.equals( array[index] ) ) { return index; } } return -1; } }
public class class_name { public static int indexOf( String[] array, String s ) { for (int index = 0; index < array.length; index++) { if( s.equals( array[index] ) ) { return index; // depends on control dependency: [if], data = [none] } } return -1; } }
public class class_name { public void marshall(RemoveTagsRequest removeTagsRequest, ProtocolMarshaller protocolMarshaller) { if (removeTagsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(removeTagsRequest.getResourceId(), RESOURCEID_BINDING); protocolMarshaller.marshall(removeTagsRequest.getTagsList(), TAGSLIST_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(RemoveTagsRequest removeTagsRequest, ProtocolMarshaller protocolMarshaller) { if (removeTagsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(removeTagsRequest.getResourceId(), RESOURCEID_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(removeTagsRequest.getTagsList(), TAGSLIST_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 byte[][] readSocket(ZMQ.Socket socket, int nb) { byte[][] inputs = new byte[nb][]; // Try to resynchronize if drifts if (socket==heartbeatSocket) { if (heartbeatDrift>0) { System.err.println("------> try to resynchronize heartbeat (" + heartbeatDrift + ")"); for (int i=0 ; i<heartbeatDrift ; i++) heartbeatSocket.recv(0); heartbeatDrift = 0; } } else if (socket==eventSocket) { if (eventDrift>0) { System.err.println("------> try to resynchronize event (" + eventDrift + ")"); for (int i=0 ; i<eventDrift ; i++) eventSocket.recv(0); eventDrift = 0; } } // Read the socket for nb blocks for (int i=0 ; i<nb ; i++) { inputs[i] = socket.recv(0); } return inputs; } }
public class class_name { private byte[][] readSocket(ZMQ.Socket socket, int nb) { byte[][] inputs = new byte[nb][]; // Try to resynchronize if drifts if (socket==heartbeatSocket) { if (heartbeatDrift>0) { System.err.println("------> try to resynchronize heartbeat (" + heartbeatDrift + ")"); // depends on control dependency: [if], data = [none] for (int i=0 ; i<heartbeatDrift ; i++) heartbeatSocket.recv(0); heartbeatDrift = 0; // depends on control dependency: [if], data = [none] } } else if (socket==eventSocket) { if (eventDrift>0) { System.err.println("------> try to resynchronize event (" + eventDrift + ")"); // depends on control dependency: [if], data = [none] for (int i=0 ; i<eventDrift ; i++) eventSocket.recv(0); eventDrift = 0; // depends on control dependency: [if], data = [none] } } // Read the socket for nb blocks for (int i=0 ; i<nb ; i++) { inputs[i] = socket.recv(0); // depends on control dependency: [for], data = [i] } return inputs; } }
public class class_name { private void reverseAfter(int i) { int start = i+1; int end = n-1; while (start < end) { swap(index,start,end); start++; end--; } } }
public class class_name { private void reverseAfter(int i) { int start = i+1; int end = n-1; while (start < end) { swap(index,start,end); // depends on control dependency: [while], data = [end)] start++; // depends on control dependency: [while], data = [none] end--; // depends on control dependency: [while], data = [none] } } }
public class class_name { public static void copyStream(Reader inStream, Writer outStream, boolean ignoreErrors) { char[] data = new char[BUFFER]; int count; try { while((count = inStream.read(data, 0, BUFFER)) != -1) { outStream.write(data, 0, count); } } catch (IOException e) { if (!ignoreErrors) e.printStackTrace(); } } }
public class class_name { public static void copyStream(Reader inStream, Writer outStream, boolean ignoreErrors) { char[] data = new char[BUFFER]; int count; try { while((count = inStream.read(data, 0, BUFFER)) != -1) { outStream.write(data, 0, count); // depends on control dependency: [while], data = [none] } } catch (IOException e) { if (!ignoreErrors) e.printStackTrace(); } // depends on control dependency: [catch], data = [none] } }