code
stringlengths
130
281k
code_dependency
stringlengths
182
306k
public class class_name { private boolean eq(final Object o1, final Object o2) { if (o1 == null && o2 == null) { return true; } if ((o1 == null && o2 != null) || (o1 != null && o2 == null)) { return false; } try { if (o1 instanceof Number && o2 instanceof Number) { return compareNumberNumber(o1, o2) == 0; } else if (o1 instanceof String && o2 instanceof String) { return compareStringString(o1, o2) == 0; } else if (o1 instanceof Date && o2 instanceof Date) { return compareDateDate(o1, o2) == 0; } else if (o1 instanceof Date && o2 instanceof String) { return compareDateString(o1, o2) == 0; } else if (o1 instanceof String && o2 instanceof Date) { return compareStringDate(o1, o2) == 0; } else if (o1 instanceof Boolean && o2 instanceof String) { return compareBooleanString((Boolean)o1, (String)o2) == 0; } else if (o1 instanceof String && o2 instanceof Boolean) { return compareStringBoolean((String)o1, (Boolean)o2) == 0; } else if (o1 instanceof Number && o2 instanceof String) { return compareNumberString((Number)o1, (String)o2) == 0; } else if (o1 instanceof String && o2 instanceof Number) { return compareStringNumber((String)o1, (Number)o2) == 0; } else { return compareStringString(o1.toString(), o2.toString()) == 0; } } catch (NumberFormatException nfe) { return false; } } }
public class class_name { private boolean eq(final Object o1, final Object o2) { if (o1 == null && o2 == null) { return true; // depends on control dependency: [if], data = [none] } if ((o1 == null && o2 != null) || (o1 != null && o2 == null)) { return false; // depends on control dependency: [if], data = [none] } try { if (o1 instanceof Number && o2 instanceof Number) { return compareNumberNumber(o1, o2) == 0; // depends on control dependency: [if], data = [none] } else if (o1 instanceof String && o2 instanceof String) { return compareStringString(o1, o2) == 0; // depends on control dependency: [if], data = [none] } else if (o1 instanceof Date && o2 instanceof Date) { return compareDateDate(o1, o2) == 0; // depends on control dependency: [if], data = [none] } else if (o1 instanceof Date && o2 instanceof String) { return compareDateString(o1, o2) == 0; // depends on control dependency: [if], data = [none] } else if (o1 instanceof String && o2 instanceof Date) { return compareStringDate(o1, o2) == 0; // depends on control dependency: [if], data = [none] } else if (o1 instanceof Boolean && o2 instanceof String) { return compareBooleanString((Boolean)o1, (String)o2) == 0; // depends on control dependency: [if], data = [none] } else if (o1 instanceof String && o2 instanceof Boolean) { return compareStringBoolean((String)o1, (Boolean)o2) == 0; // depends on control dependency: [if], data = [none] } else if (o1 instanceof Number && o2 instanceof String) { return compareNumberString((Number)o1, (String)o2) == 0; // depends on control dependency: [if], data = [none] } else if (o1 instanceof String && o2 instanceof Number) { return compareStringNumber((String)o1, (Number)o2) == 0; // depends on control dependency: [if], data = [none] } else { return compareStringString(o1.toString(), o2.toString()) == 0; // depends on control dependency: [if], data = [none] } } catch (NumberFormatException nfe) { return false; } // depends on control dependency: [catch], data = [none] } }
public class class_name { protected LocalityLevel getAllowedLocalityLevel(JobInProgress job, long currentTime) { JobInfo info = infos.get(job); if (info == null) { // Job not in infos (shouldn't happen) LOG.error("getAllowedLocalityLevel called on job " + job + ", which does not have a JobInfo in infos"); return LocalityLevel.ANY; } if (job.nonLocalMaps.size() > 0) { // Job doesn't have locality information return LocalityLevel.ANY; } // In the common case, compute locality level based on time waited switch(info.lastMapLocalityLevel) { case NODE: // Last task launched was node-local if (info.timeWaitedForLocalMap >= (localityDelayNodeLocal + localityDelayRackLocal)) return LocalityLevel.ANY; else if (info.timeWaitedForLocalMap >= localityDelayNodeLocal) return LocalityLevel.RACK; else return LocalityLevel.NODE; case RACK: // Last task launched was rack-local if (info.timeWaitedForLocalMap >= localityDelayRackLocal) return LocalityLevel.ANY; else return LocalityLevel.RACK; default: // Last task was non-local; can launch anywhere return LocalityLevel.ANY; } } }
public class class_name { protected LocalityLevel getAllowedLocalityLevel(JobInProgress job, long currentTime) { JobInfo info = infos.get(job); if (info == null) { // Job not in infos (shouldn't happen) LOG.error("getAllowedLocalityLevel called on job " + job + ", which does not have a JobInfo in infos"); // depends on control dependency: [if], data = [none] return LocalityLevel.ANY; // depends on control dependency: [if], data = [none] } if (job.nonLocalMaps.size() > 0) { // Job doesn't have locality information return LocalityLevel.ANY; // depends on control dependency: [if], data = [none] } // In the common case, compute locality level based on time waited switch(info.lastMapLocalityLevel) { case NODE: // Last task launched was node-local if (info.timeWaitedForLocalMap >= (localityDelayNodeLocal + localityDelayRackLocal)) return LocalityLevel.ANY; else if (info.timeWaitedForLocalMap >= localityDelayNodeLocal) return LocalityLevel.RACK; else return LocalityLevel.NODE; case RACK: // Last task launched was rack-local if (info.timeWaitedForLocalMap >= localityDelayRackLocal) return LocalityLevel.ANY; else return LocalityLevel.RACK; default: // Last task was non-local; can launch anywhere return LocalityLevel.ANY; } } }
public class class_name { @Override public final void forEach(BiConsumer<? super K, ? super V> action) { Objects.requireNonNull(action); int mc = this.modCount; Segment<K, V> segment; for (long segmentIndex = 0; segmentIndex >= 0; segmentIndex = nextSegmentIndex(segmentIndex, segment)) { (segment = segment(segmentIndex)).forEach(action); } if (mc != modCount) throw new ConcurrentModificationException(); } }
public class class_name { @Override public final void forEach(BiConsumer<? super K, ? super V> action) { Objects.requireNonNull(action); int mc = this.modCount; Segment<K, V> segment; for (long segmentIndex = 0; segmentIndex >= 0; segmentIndex = nextSegmentIndex(segmentIndex, segment)) { (segment = segment(segmentIndex)).forEach(action); // depends on control dependency: [for], data = [segmentIndex] } if (mc != modCount) throw new ConcurrentModificationException(); } }
public class class_name { private Authentication getAuthentication(SecurityContext securityContext) { // 用户未登录 Authentication authentication = securityContext.getAuthentication(); if (authentication == null) { authentication = new AnonymousAuthenticationToken(UUID.randomUUID().toString(), "anonymous", Collections.<GrantedAuthority> singletonList(new SimpleGrantedAuthority("ROLE_ANONYMOUS"))); } return authentication; } }
public class class_name { private Authentication getAuthentication(SecurityContext securityContext) { // 用户未登录 Authentication authentication = securityContext.getAuthentication(); if (authentication == null) { authentication = new AnonymousAuthenticationToken(UUID.randomUUID().toString(), "anonymous", Collections.<GrantedAuthority> singletonList(new SimpleGrantedAuthority("ROLE_ANONYMOUS"))); // depends on control dependency: [if], data = [none] } return authentication; } }
public class class_name { public static double JensenShannonDivergence(SparseArray x, SparseArray y) { if (x.isEmpty()) { throw new IllegalArgumentException("List x is empty."); } if (y.isEmpty()) { throw new IllegalArgumentException("List y is empty."); } Iterator<SparseArray.Entry> iterX = x.iterator(); Iterator<SparseArray.Entry> iterY = y.iterator(); SparseArray.Entry a = iterX.hasNext() ? iterX.next() : null; SparseArray.Entry b = iterY.hasNext() ? iterY.next() : null; double js = 0.0; while (a != null && b != null) { if (a.i < b.i) { double mi = a.x / 2; js += a.x * Math.log(a.x / mi); a = iterX.hasNext() ? iterX.next() : null; } else if (a.i > b.i) { double mi = b.x / 2; js += b.x * Math.log(b.x / mi); b = iterY.hasNext() ? iterY.next() : null; } else { double mi = (a.x + b.x) / 2; js += a.x * Math.log(a.x / mi) + b.x * Math.log(b.x / mi); a = iterX.hasNext() ? iterX.next() : null; b = iterY.hasNext() ? iterY.next() : null; } } return js / 2; } }
public class class_name { public static double JensenShannonDivergence(SparseArray x, SparseArray y) { if (x.isEmpty()) { throw new IllegalArgumentException("List x is empty."); } if (y.isEmpty()) { throw new IllegalArgumentException("List y is empty."); } Iterator<SparseArray.Entry> iterX = x.iterator(); Iterator<SparseArray.Entry> iterY = y.iterator(); SparseArray.Entry a = iterX.hasNext() ? iterX.next() : null; SparseArray.Entry b = iterY.hasNext() ? iterY.next() : null; double js = 0.0; while (a != null && b != null) { if (a.i < b.i) { double mi = a.x / 2; js += a.x * Math.log(a.x / mi); // depends on control dependency: [if], data = [none] a = iterX.hasNext() ? iterX.next() : null; // depends on control dependency: [if], data = [none] } else if (a.i > b.i) { double mi = b.x / 2; js += b.x * Math.log(b.x / mi); // depends on control dependency: [if], data = [none] b = iterY.hasNext() ? iterY.next() : null; // depends on control dependency: [if], data = [none] } else { double mi = (a.x + b.x) / 2; js += a.x * Math.log(a.x / mi) + b.x * Math.log(b.x / mi); // depends on control dependency: [if], data = [none] a = iterX.hasNext() ? iterX.next() : null; // depends on control dependency: [if], data = [none] b = iterY.hasNext() ? iterY.next() : null; // depends on control dependency: [if], data = [none] } } return js / 2; } }
public class class_name { private Map<String, String> lookupSystemProperties() { Map<String,String> ret = new HashMap<String, String>(); Enumeration propEnum = System.getProperties().propertyNames(); while (propEnum.hasMoreElements()) { String prop = (String) propEnum.nextElement(); if (prop.startsWith("jolokia.")) { String key = prop.substring("jolokia.".length()); ret.put(key,System.getProperty(prop)); } } return ret; } }
public class class_name { private Map<String, String> lookupSystemProperties() { Map<String,String> ret = new HashMap<String, String>(); Enumeration propEnum = System.getProperties().propertyNames(); while (propEnum.hasMoreElements()) { String prop = (String) propEnum.nextElement(); if (prop.startsWith("jolokia.")) { String key = prop.substring("jolokia.".length()); ret.put(key,System.getProperty(prop)); // depends on control dependency: [if], data = [none] } } return ret; } }
public class class_name { @Override public ViewDeclarationLanguage getViewDeclarationLanguage(String viewId) { if (!_initialized) { initialize(); } for (ViewDeclarationLanguageStrategy strategy : _supportedLanguages) { if (strategy.handles(viewId)) { return strategy.getViewDeclarationLanguage(); } } return null; } }
public class class_name { @Override public ViewDeclarationLanguage getViewDeclarationLanguage(String viewId) { if (!_initialized) { initialize(); // depends on control dependency: [if], data = [none] } for (ViewDeclarationLanguageStrategy strategy : _supportedLanguages) { if (strategy.handles(viewId)) { return strategy.getViewDeclarationLanguage(); // depends on control dependency: [if], data = [none] } } return null; } }
public class class_name { public void marshall(RemediationExecutionStep remediationExecutionStep, ProtocolMarshaller protocolMarshaller) { if (remediationExecutionStep == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(remediationExecutionStep.getName(), NAME_BINDING); protocolMarshaller.marshall(remediationExecutionStep.getState(), STATE_BINDING); protocolMarshaller.marshall(remediationExecutionStep.getErrorMessage(), ERRORMESSAGE_BINDING); protocolMarshaller.marshall(remediationExecutionStep.getStartTime(), STARTTIME_BINDING); protocolMarshaller.marshall(remediationExecutionStep.getStopTime(), STOPTIME_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(RemediationExecutionStep remediationExecutionStep, ProtocolMarshaller protocolMarshaller) { if (remediationExecutionStep == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(remediationExecutionStep.getName(), NAME_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(remediationExecutionStep.getState(), STATE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(remediationExecutionStep.getErrorMessage(), ERRORMESSAGE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(remediationExecutionStep.getStartTime(), STARTTIME_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(remediationExecutionStep.getStopTime(), STOPTIME_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 { protected File getFile(String imageUri) { String fileName = fileNameGenerator.generate(imageUri); File dir = cacheDir; if (!cacheDir.exists() && !cacheDir.mkdirs()) { if (reserveCacheDir != null && (reserveCacheDir.exists() || reserveCacheDir.mkdirs())) { dir = reserveCacheDir; } } return new File(dir, fileName); } }
public class class_name { protected File getFile(String imageUri) { String fileName = fileNameGenerator.generate(imageUri); File dir = cacheDir; if (!cacheDir.exists() && !cacheDir.mkdirs()) { if (reserveCacheDir != null && (reserveCacheDir.exists() || reserveCacheDir.mkdirs())) { dir = reserveCacheDir; // depends on control dependency: [if], data = [none] } } return new File(dir, fileName); } }
public class class_name { public java.util.List<DBClusterBacktrack> getDBClusterBacktracks() { if (dBClusterBacktracks == null) { dBClusterBacktracks = new com.amazonaws.internal.SdkInternalList<DBClusterBacktrack>(); } return dBClusterBacktracks; } }
public class class_name { public java.util.List<DBClusterBacktrack> getDBClusterBacktracks() { if (dBClusterBacktracks == null) { dBClusterBacktracks = new com.amazonaws.internal.SdkInternalList<DBClusterBacktrack>(); // depends on control dependency: [if], data = [none] } return dBClusterBacktracks; } }
public class class_name { public void start() { for ( QueueGroups group : QueueGroups.values() ) { final DelayQueue<ActivityHolder> thisQueue = queues.get(group); service.submit ( new Runnable() { @Override public void run() { try { while ( !Thread.currentThread().isInterrupted() ) { ActivityHolder holder = thisQueue.take(); try { Boolean result = holder.activity.call(); holder.activity.completed((result != null) && result); } catch ( Throwable e ) { log.error("Unhandled exception in background task", e); } } } catch ( InterruptedException dummy ) { Thread.currentThread().interrupt(); } } } ); } } }
public class class_name { public void start() { for ( QueueGroups group : QueueGroups.values() ) { final DelayQueue<ActivityHolder> thisQueue = queues.get(group); service.submit ( new Runnable() { @Override public void run() { try { while ( !Thread.currentThread().isInterrupted() ) { ActivityHolder holder = thisQueue.take(); try { Boolean result = holder.activity.call(); holder.activity.completed((result != null) && result); // depends on control dependency: [try], data = [none] } catch ( Throwable e ) { log.error("Unhandled exception in background task", e); } // depends on control dependency: [catch], data = [none] } } catch ( InterruptedException dummy ) { Thread.currentThread().interrupt(); } // depends on control dependency: [catch], data = [none] } } ); // depends on control dependency: [for], data = [none] } } }
public class class_name { synchronized void garbageCollect() { // Cancel task tracker reservation cancelReservedSlots(); // Remove the remaining speculative tasks counts totalSpeculativeReduceTasks.addAndGet(-speculativeReduceTasks); totalSpeculativeMapTasks.addAndGet(-speculativeMapTasks); garbageCollected = true; // Let the JobTracker know that a job is complete jobtracker.getInstrumentation().decWaitingMaps(getJobID(), pendingMaps()); jobtracker.getInstrumentation().decWaitingReduces(getJobID(), pendingReduces()); jobtracker.storeCompletedJob(this); jobtracker.finalizeJob(this); try { // Definitely remove the local-disk copy of the job file if (localJobFile != null) { localFs.delete(localJobFile, true); localJobFile = null; } // clean up splits for (int i = 0; i < maps.length; i++) { maps[i].clearSplit(); } // JobClient always creates a new directory with job files // so we remove that directory to cleanup // Delete temp dfs dirs created if any, like in case of // speculative exn of reduces. Path tempDir = jobtracker.getSystemDirectoryForJob(getJobID()); new CleanupQueue().addToQueue(new PathDeletionContext( FileSystem.get(conf), tempDir.toUri().getPath())); } catch (IOException e) { LOG.warn("Error cleaning up "+profile.getJobID()+": "+e); } cleanUpMetrics(); // free up the memory used by the data structures this.nonRunningMapCache = null; this.runningMapCache = null; this.nonRunningReduces = null; this.runningReduces = null; this.trackerMapStats = null; this.trackerReduceStats = null; } }
public class class_name { synchronized void garbageCollect() { // Cancel task tracker reservation cancelReservedSlots(); // Remove the remaining speculative tasks counts totalSpeculativeReduceTasks.addAndGet(-speculativeReduceTasks); totalSpeculativeMapTasks.addAndGet(-speculativeMapTasks); garbageCollected = true; // Let the JobTracker know that a job is complete jobtracker.getInstrumentation().decWaitingMaps(getJobID(), pendingMaps()); jobtracker.getInstrumentation().decWaitingReduces(getJobID(), pendingReduces()); jobtracker.storeCompletedJob(this); jobtracker.finalizeJob(this); try { // Definitely remove the local-disk copy of the job file if (localJobFile != null) { localFs.delete(localJobFile, true); // depends on control dependency: [if], data = [(localJobFile] localJobFile = null; // depends on control dependency: [if], data = [none] } // clean up splits for (int i = 0; i < maps.length; i++) { maps[i].clearSplit(); // depends on control dependency: [for], data = [i] } // JobClient always creates a new directory with job files // so we remove that directory to cleanup // Delete temp dfs dirs created if any, like in case of // speculative exn of reduces. Path tempDir = jobtracker.getSystemDirectoryForJob(getJobID()); new CleanupQueue().addToQueue(new PathDeletionContext( FileSystem.get(conf), tempDir.toUri().getPath())); // depends on control dependency: [try], data = [none] } catch (IOException e) { LOG.warn("Error cleaning up "+profile.getJobID()+": "+e); } // depends on control dependency: [catch], data = [none] cleanUpMetrics(); // free up the memory used by the data structures this.nonRunningMapCache = null; this.runningMapCache = null; this.nonRunningReduces = null; this.runningReduces = null; this.trackerMapStats = null; this.trackerReduceStats = null; } }
public class class_name { private static Integer[] getAdjustedMonthDays(int year) { Integer[] newMonths; try { newMonths = ADJUSTED_MONTH_DAYS.get(Integer.valueOf(year)); } catch (ArrayIndexOutOfBoundsException e) { newMonths = null; } if (newMonths == null) { if (isLeapYear(year)) { newMonths = DEFAULT_LEAP_MONTH_DAYS; } else { newMonths = DEFAULT_MONTH_DAYS; } } return newMonths; } }
public class class_name { private static Integer[] getAdjustedMonthDays(int year) { Integer[] newMonths; try { newMonths = ADJUSTED_MONTH_DAYS.get(Integer.valueOf(year)); // depends on control dependency: [try], data = [none] } catch (ArrayIndexOutOfBoundsException e) { newMonths = null; } // depends on control dependency: [catch], data = [none] if (newMonths == null) { if (isLeapYear(year)) { newMonths = DEFAULT_LEAP_MONTH_DAYS; // depends on control dependency: [if], data = [none] } else { newMonths = DEFAULT_MONTH_DAYS; // depends on control dependency: [if], data = [none] } } return newMonths; } }
public class class_name { boolean findContour( boolean mustHaveInner ) { // find the node with the largest angleBetween NodeInfo seed = listInfo.get(0); for (int i = 1; i < listInfo.size(); i++) { NodeInfo info = listInfo.get(i); if( info.angleBetween > seed.angleBetween ) { seed = info; } } // trace around the contour contour.reset(); contour.add( seed ); seed.contour = true; NodeInfo prev = seed; NodeInfo current = seed.right; while( current != null && current != seed && contour.size() < listInfo.size() ) { if( prev != current.left ) return false; contour.add( current ); current.contour = true; prev = current; current = current.right; } // fail if it is too small or was cycling return !(contour.size < 4 || (mustHaveInner && contour.size >= listInfo.size())); } }
public class class_name { boolean findContour( boolean mustHaveInner ) { // find the node with the largest angleBetween NodeInfo seed = listInfo.get(0); for (int i = 1; i < listInfo.size(); i++) { NodeInfo info = listInfo.get(i); if( info.angleBetween > seed.angleBetween ) { seed = info; // depends on control dependency: [if], data = [none] } } // trace around the contour contour.reset(); contour.add( seed ); seed.contour = true; NodeInfo prev = seed; NodeInfo current = seed.right; while( current != null && current != seed && contour.size() < listInfo.size() ) { if( prev != current.left ) return false; contour.add( current ); // depends on control dependency: [while], data = [( current] current.contour = true; // depends on control dependency: [while], data = [none] prev = current; // depends on control dependency: [while], data = [none] current = current.right; // depends on control dependency: [while], data = [none] } // fail if it is too small or was cycling return !(contour.size < 4 || (mustHaveInner && contour.size >= listInfo.size())); } }
public class class_name { public <T> void isNull(final T object, final String message, final Object... values) { if (object != null) { fail(String.format(message, values)); } } }
public class class_name { public <T> void isNull(final T object, final String message, final Object... values) { if (object != null) { fail(String.format(message, values)); // depends on control dependency: [if], data = [none] } } }
public class class_name { private void readPixels() { if (reader != null) { pixels = new int[reader.imgInfo.rows][reader.imgInfo.cols]; int rowCount = 0; while (reader.hasMoreRows()) { ImageLineInt row = reader.readRowInt(); int[] columnValues = new int[reader.imgInfo.cols]; System.arraycopy(row.getScanline(), 0, columnValues, 0, columnValues.length); pixels[rowCount++] = columnValues; } reader.close(); } } }
public class class_name { private void readPixels() { if (reader != null) { pixels = new int[reader.imgInfo.rows][reader.imgInfo.cols]; // depends on control dependency: [if], data = [none] int rowCount = 0; while (reader.hasMoreRows()) { ImageLineInt row = reader.readRowInt(); int[] columnValues = new int[reader.imgInfo.cols]; System.arraycopy(row.getScanline(), 0, columnValues, 0, columnValues.length); // depends on control dependency: [while], data = [none] pixels[rowCount++] = columnValues; // depends on control dependency: [while], data = [none] } reader.close(); // depends on control dependency: [if], data = [none] } } }
public class class_name { @SuppressWarnings({"rawtypes", "unchecked"}) public static Object getClone(Object source) { if (null == source) { return null; } Object target = BeanUtils.getOneLayerClone(source); try { // 此处使用了JAVA的内省机制(内省是 Java 语言对 Bean 类属性、事件的一种缺省处理方法) // 获得对像的BeanInfo 信息: BeanInfo bi = Introspector.getBeanInfo(source.getClass()); // 获得属性的描述器 PropertyDescriptor[] props = bi.getPropertyDescriptors(); for (int i = 0; i < props.length; ++i) { if (null != props[i].getReadMethod()) { Class propertyType = props[i].getPropertyType(); if (propertyType.equals(List.class)) { List newList = new ArrayList(); // 此处使用了JAVA的反射机制通过获得方法的引用去执行方法,其中source:为要执行的方法所属的对象, // 方法如果没有参数第二个参数则为null; List valueList = (List) props[i].getReadMethod().invoke(source); if (valueList == null) { valueList = new ArrayList(); } for (Object value : valueList) { Object cloneValue = null; if (value.getClass().getName().indexOf(ENTITY_CLASS_PACKAGE) >= 0) { cloneValue = BeanUtils.getOneLayerClone(value); } else { cloneValue = value; } newList.add(cloneValue); } props[i].getWriteMethod().invoke(target, newList); } if (propertyType.equals(Set.class)) { Set newSet = new HashSet(); Set valueSet = (Set) props[i].getReadMethod().invoke(source); if (valueSet == null) { valueSet = new HashSet(); } for (Object value : valueSet) { Object cloneValue = BeanUtils.getOneLayerClone(value); newSet.add(cloneValue); } props[i].getWriteMethod().invoke(target, newSet); } else { // 如果是array 跳过 //FIXME if (propertyType.equals(Arrays.class)) { continue; } if (propertyType.toString().startsWith(ENTITY_CLASS_PACKAGE)) { Object value = props[i].getReadMethod().invoke(source); Object cloneValue = BeanUtils.getOneLayerClone(value); props[i].getWriteMethod().invoke(target, cloneValue); } } } } } catch (Exception e) { logger.error("clone object exception object class:" + source.getClass(), e); } return target; } }
public class class_name { @SuppressWarnings({"rawtypes", "unchecked"}) public static Object getClone(Object source) { if (null == source) { return null; // depends on control dependency: [if], data = [none] } Object target = BeanUtils.getOneLayerClone(source); try { // 此处使用了JAVA的内省机制(内省是 Java 语言对 Bean 类属性、事件的一种缺省处理方法) // 获得对像的BeanInfo 信息: BeanInfo bi = Introspector.getBeanInfo(source.getClass()); // 获得属性的描述器 PropertyDescriptor[] props = bi.getPropertyDescriptors(); for (int i = 0; i < props.length; ++i) { if (null != props[i].getReadMethod()) { Class propertyType = props[i].getPropertyType(); if (propertyType.equals(List.class)) { List newList = new ArrayList(); // 此处使用了JAVA的反射机制通过获得方法的引用去执行方法,其中source:为要执行的方法所属的对象, // 方法如果没有参数第二个参数则为null; List valueList = (List) props[i].getReadMethod().invoke(source); if (valueList == null) { valueList = new ArrayList(); // depends on control dependency: [if], data = [none] } for (Object value : valueList) { Object cloneValue = null; if (value.getClass().getName().indexOf(ENTITY_CLASS_PACKAGE) >= 0) { cloneValue = BeanUtils.getOneLayerClone(value); // depends on control dependency: [if], data = [none] } else { cloneValue = value; // depends on control dependency: [if], data = [none] } newList.add(cloneValue); // depends on control dependency: [for], data = [none] } props[i].getWriteMethod().invoke(target, newList); // depends on control dependency: [if], data = [none] } if (propertyType.equals(Set.class)) { Set newSet = new HashSet(); Set valueSet = (Set) props[i].getReadMethod().invoke(source); if (valueSet == null) { valueSet = new HashSet(); // depends on control dependency: [if], data = [none] } for (Object value : valueSet) { Object cloneValue = BeanUtils.getOneLayerClone(value); newSet.add(cloneValue); // depends on control dependency: [for], data = [none] } props[i].getWriteMethod().invoke(target, newSet); // depends on control dependency: [if], data = [none] } else { // 如果是array 跳过 //FIXME if (propertyType.equals(Arrays.class)) { continue; } if (propertyType.toString().startsWith(ENTITY_CLASS_PACKAGE)) { Object value = props[i].getReadMethod().invoke(source); Object cloneValue = BeanUtils.getOneLayerClone(value); props[i].getWriteMethod().invoke(target, cloneValue); // depends on control dependency: [if], data = [none] } } } } } catch (Exception e) { logger.error("clone object exception object class:" + source.getClass(), e); } // depends on control dependency: [catch], data = [none] return target; } }
public class class_name { public final void setItsCatalog(final CatalogGs pCatalog) { this.itsCatalog = pCatalog; if (this.itsId == null) { this.itsId = new SeSrCaId(); } this.itsId.setItsCatalog(this.itsCatalog); } }
public class class_name { public final void setItsCatalog(final CatalogGs pCatalog) { this.itsCatalog = pCatalog; if (this.itsId == null) { this.itsId = new SeSrCaId(); // depends on control dependency: [if], data = [none] } this.itsId.setItsCatalog(this.itsCatalog); } }
public class class_name { public StartTaskRequest withContainerInstances(String... containerInstances) { if (this.containerInstances == null) { setContainerInstances(new com.amazonaws.internal.SdkInternalList<String>(containerInstances.length)); } for (String ele : containerInstances) { this.containerInstances.add(ele); } return this; } }
public class class_name { public StartTaskRequest withContainerInstances(String... containerInstances) { if (this.containerInstances == null) { setContainerInstances(new com.amazonaws.internal.SdkInternalList<String>(containerInstances.length)); // depends on control dependency: [if], data = [none] } for (String ele : containerInstances) { this.containerInstances.add(ele); // depends on control dependency: [for], data = [ele] } return this; } }
public class class_name { public void updateIndex(Iterator<Triangle> updatedTriangles) { // Gather the bounding box of the updated area BoundingBox updatedRegion = new BoundingBox(); while (updatedTriangles.hasNext()) { updatedRegion = updatedRegion.unionWith(updatedTriangles.next().getBoundingBox()); } if (updatedRegion.isNull()) // No update... return; // Bad news - the updated region lies outside the indexed region. // The whole index must be recalculated if (!indexRegion.contains(updatedRegion)) { init(indexDelaunay, (int) (indexRegion.getWidth() / x_size), (int) (indexRegion.getHeight() / y_size), indexRegion.unionWith(updatedRegion)); } else { // Find the cell region to be updated Vector2i minInvalidCell = getCellOf(updatedRegion.getMinPoint()); Vector2i maxInvalidCell = getCellOf(updatedRegion.getMaxPoint()); // And update it with fresh triangles Triangle adjacentValidTriangle = findValidTriangle(minInvalidCell); updateCellValues(minInvalidCell.getX(), minInvalidCell.getY(), maxInvalidCell.getX(), maxInvalidCell.getY(), adjacentValidTriangle); } } }
public class class_name { public void updateIndex(Iterator<Triangle> updatedTriangles) { // Gather the bounding box of the updated area BoundingBox updatedRegion = new BoundingBox(); while (updatedTriangles.hasNext()) { updatedRegion = updatedRegion.unionWith(updatedTriangles.next().getBoundingBox()); // depends on control dependency: [while], data = [none] } if (updatedRegion.isNull()) // No update... return; // Bad news - the updated region lies outside the indexed region. // The whole index must be recalculated if (!indexRegion.contains(updatedRegion)) { init(indexDelaunay, (int) (indexRegion.getWidth() / x_size), (int) (indexRegion.getHeight() / y_size), indexRegion.unionWith(updatedRegion)); // depends on control dependency: [if], data = [none] } else { // Find the cell region to be updated Vector2i minInvalidCell = getCellOf(updatedRegion.getMinPoint()); Vector2i maxInvalidCell = getCellOf(updatedRegion.getMaxPoint()); // And update it with fresh triangles Triangle adjacentValidTriangle = findValidTriangle(minInvalidCell); updateCellValues(minInvalidCell.getX(), minInvalidCell.getY(), maxInvalidCell.getX(), maxInvalidCell.getY(), adjacentValidTriangle); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void addReferenceListener(ReferenceListener listener) { if (this.listeners == null) { this.listeners = new LinkedList<>(); } final List<ReferenceListener> list = this.listeners; synchronized (list) { list.add(listener); } } }
public class class_name { public void addReferenceListener(ReferenceListener listener) { if (this.listeners == null) { this.listeners = new LinkedList<>(); // depends on control dependency: [if], data = [none] } final List<ReferenceListener> list = this.listeners; synchronized (list) { list.add(listener); } } }
public class class_name { public String changeSessionIdOnTomcatFailover( final String requestedSessionId ) { if ( !_sticky ) { return null; } final String localJvmRoute = _manager.getJvmRoute(); if ( localJvmRoute != null && !localJvmRoute.equals( getSessionIdFormat().extractJvmRoute( requestedSessionId ) ) ) { // the session might already be relocated, e.g. if some ajax calls are running concurrently. // if we'd run session takeover again, a new empty session would be created. // see https://github.com/magro/memcached-session-manager/issues/282 final String newSessionId = _memcachedNodesManager.changeSessionIdForTomcatFailover(requestedSessionId, _manager.getJvmRoute()); if (_manager.getSessionInternal(newSessionId) != null) { return newSessionId; } // the session might have been loaded already (by some valve), so let's check our session map MemcachedBackupSession session = _manager.getSessionInternal( requestedSessionId ); if ( session == null ) { session = loadFromMemcachedWithCheck( requestedSessionId ); } // checking valid() can expire() the session! if ( session != null && session.isValid() ) { return handleSessionTakeOver( session ); } else if (_manager.getSessionInternal(newSessionId) != null) { return newSessionId; } } return null; } }
public class class_name { public String changeSessionIdOnTomcatFailover( final String requestedSessionId ) { if ( !_sticky ) { return null; // depends on control dependency: [if], data = [none] } final String localJvmRoute = _manager.getJvmRoute(); if ( localJvmRoute != null && !localJvmRoute.equals( getSessionIdFormat().extractJvmRoute( requestedSessionId ) ) ) { // the session might already be relocated, e.g. if some ajax calls are running concurrently. // if we'd run session takeover again, a new empty session would be created. // see https://github.com/magro/memcached-session-manager/issues/282 final String newSessionId = _memcachedNodesManager.changeSessionIdForTomcatFailover(requestedSessionId, _manager.getJvmRoute()); if (_manager.getSessionInternal(newSessionId) != null) { return newSessionId; // depends on control dependency: [if], data = [none] } // the session might have been loaded already (by some valve), so let's check our session map MemcachedBackupSession session = _manager.getSessionInternal( requestedSessionId ); if ( session == null ) { session = loadFromMemcachedWithCheck( requestedSessionId ); // depends on control dependency: [if], data = [none] } // checking valid() can expire() the session! if ( session != null && session.isValid() ) { return handleSessionTakeOver( session ); // depends on control dependency: [if], data = [( session] } else if (_manager.getSessionInternal(newSessionId) != null) { return newSessionId; // depends on control dependency: [if], data = [none] } } return null; } }
public class class_name { public static String getAltField(String field, String streamId) { if (streamId == null) { return field; } return field + "/" + streamId; } }
public class class_name { public static String getAltField(String field, String streamId) { if (streamId == null) { return field; // depends on control dependency: [if], data = [none] } return field + "/" + streamId; } }
public class class_name { public GetDocumentResponse getDocument(GetDocumentRequest request) { checkNotNull(request, "request should not be null."); checkNotNull(request.getDocumentId(), "documentId should not be null."); InternalRequest internalRequest = this.createRequest(HttpMethodName.GET, request, DOC, request.getDocumentId()); GetDocumentResponse response; try { response = this.invokeHttpClient(internalRequest, GetDocumentResponse.class); } finally { try { internalRequest.getContent().close(); } catch (Exception e) { // ignore exception } } return response; } }
public class class_name { public GetDocumentResponse getDocument(GetDocumentRequest request) { checkNotNull(request, "request should not be null."); checkNotNull(request.getDocumentId(), "documentId should not be null."); InternalRequest internalRequest = this.createRequest(HttpMethodName.GET, request, DOC, request.getDocumentId()); GetDocumentResponse response; try { response = this.invokeHttpClient(internalRequest, GetDocumentResponse.class); // depends on control dependency: [try], data = [none] } finally { try { internalRequest.getContent().close(); // depends on control dependency: [try], data = [none] } catch (Exception e) { // ignore exception } // depends on control dependency: [catch], data = [none] } return response; } }
public class class_name { private boolean okayToSendServerStarted() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "okayToSendServerStarted", this); synchronized (lockObject) { if (!_sentServerStarted) { if ((_state == STATE_STARTED) && _mainImpl.isServerStarted()) { _sentServerStarted = true; } } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "okayToSendServerStarted", new Boolean(_sentServerStarted)); return _sentServerStarted; } }
public class class_name { private boolean okayToSendServerStarted() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "okayToSendServerStarted", this); synchronized (lockObject) { if (!_sentServerStarted) { if ((_state == STATE_STARTED) && _mainImpl.isServerStarted()) { _sentServerStarted = true; // depends on control dependency: [if], data = [none] } } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "okayToSendServerStarted", new Boolean(_sentServerStarted)); return _sentServerStarted; } }
public class class_name { @Override int write_attribute_asynch_i(final DeviceAttribute da, final boolean fwd, final int rid) throws DevFailed { synchronized (this) { final Iterator it = elements.iterator(); while (it.hasNext()) { final GroupElement e = (GroupElement) it.next(); if (e instanceof GroupDeviceElement || fwd) { e.write_attribute_asynch_i(da, fwd, rid); } } return rid; } } }
public class class_name { @Override int write_attribute_asynch_i(final DeviceAttribute da, final boolean fwd, final int rid) throws DevFailed { synchronized (this) { final Iterator it = elements.iterator(); while (it.hasNext()) { final GroupElement e = (GroupElement) it.next(); if (e instanceof GroupDeviceElement || fwd) { e.write_attribute_asynch_i(da, fwd, rid); // depends on control dependency: [if], data = [none] } } return rid; } } }
public class class_name { @Override public boolean readFrom(ByteBuffer src) { boolean complete = doActualRead(src); while (!complete && readyToReadData && chunked && src.hasRemaining()) { complete = doActualRead(src); } if (complete) { if (data != null) { data.flip(); } } return complete; } }
public class class_name { @Override public boolean readFrom(ByteBuffer src) { boolean complete = doActualRead(src); while (!complete && readyToReadData && chunked && src.hasRemaining()) { complete = doActualRead(src); // depends on control dependency: [while], data = [none] } if (complete) { if (data != null) { data.flip(); // depends on control dependency: [if], data = [none] } } return complete; } }
public class class_name { protected String endWithSlash( String prefix ) { prefix = StringUtils.defaultIfEmpty( prefix, "/" ); if ( ! prefix.endsWith( "/" ) ) { prefix = prefix + "/"; } return prefix; } }
public class class_name { protected String endWithSlash( String prefix ) { prefix = StringUtils.defaultIfEmpty( prefix, "/" ); if ( ! prefix.endsWith( "/" ) ) { prefix = prefix + "/"; // depends on control dependency: [if], data = [none] } return prefix; } }
public class class_name { public DirectedSparseMultigraph<TrajectoryEnvelope,Integer[]> getCurrentDependencies() { DirectedSparseMultigraph<TrajectoryEnvelope,Integer[]> depGraph = new DirectedSparseMultigraph<TrajectoryEnvelope,Integer[]>(); ConstraintNetwork cn = this.getConstraintSolvers()[0].getConstraintNetwork(); Constraint[] cons = cn.getConstraints(); for (Constraint con : cons) { if (con instanceof AllenIntervalConstraint) { AllenIntervalConstraint aic = (AllenIntervalConstraint)con; if (aic.getTypes()[0].equals(AllenIntervalConstraint.Type.BeforeOrMeets)) { //The two TEs involved in the constraint TrajectoryEnvelope mustWaitToStart = (TrajectoryEnvelope)aic.getTo(); TrajectoryEnvelope mustFinishBeforeOtherCanStart = (TrajectoryEnvelope)aic.getFrom(); TrajectoryEnvelope waitingEnvelope = null; //Find waitingEnvelope = previous of mustWaitToStart TrajectoryEnvelope root = mustWaitToStart; while (root.hasSuperEnvelope()) root = root.getSuperEnvelope(); for (Variable depVar : root.getRecursivelyDependentVariables()) { TrajectoryEnvelope depTE = (TrajectoryEnvelope)depVar; if (!depTE.hasSubEnvelopes() && depTE.getTrajectory().getSequenceNumberEnd() == mustWaitToStart.getSequenceNumberStart()-1) { waitingEnvelope = depTE; break; } } //Calculate waiting points Integer thresholdPoint = mustFinishBeforeOtherCanStart.getTrajectory().getSequenceNumberEnd(); Integer waitingPoint = null; //If there was no previous envelope, then make the robot stay in the start point of this one if (waitingEnvelope == null) { //System.out.println("IGNORE THIS DEPENDENCY, the following robot is parked anyway " + mustWaitToStart); waitingPoint = mustWaitToStart.getTrajectory().getSequenceNumberStart(); waitingEnvelope = mustWaitToStart; } else { waitingPoint = waitingEnvelope.getTrajectory().getSequenceNumberEnd(); } //Add edge in dep graph ArrayList<TrajectoryEnvelope> verts = new ArrayList<TrajectoryEnvelope>(); verts.add(waitingEnvelope); verts.add(mustFinishBeforeOtherCanStart); depGraph.addVertex(waitingEnvelope); depGraph.addVertex(mustFinishBeforeOtherCanStart); depGraph.addEdge(new Integer[] {waitingPoint,thresholdPoint}, waitingEnvelope, mustFinishBeforeOtherCanStart); } } } return depGraph; } }
public class class_name { public DirectedSparseMultigraph<TrajectoryEnvelope,Integer[]> getCurrentDependencies() { DirectedSparseMultigraph<TrajectoryEnvelope,Integer[]> depGraph = new DirectedSparseMultigraph<TrajectoryEnvelope,Integer[]>(); ConstraintNetwork cn = this.getConstraintSolvers()[0].getConstraintNetwork(); Constraint[] cons = cn.getConstraints(); for (Constraint con : cons) { if (con instanceof AllenIntervalConstraint) { AllenIntervalConstraint aic = (AllenIntervalConstraint)con; if (aic.getTypes()[0].equals(AllenIntervalConstraint.Type.BeforeOrMeets)) { //The two TEs involved in the constraint TrajectoryEnvelope mustWaitToStart = (TrajectoryEnvelope)aic.getTo(); TrajectoryEnvelope mustFinishBeforeOtherCanStart = (TrajectoryEnvelope)aic.getFrom(); TrajectoryEnvelope waitingEnvelope = null; //Find waitingEnvelope = previous of mustWaitToStart TrajectoryEnvelope root = mustWaitToStart; while (root.hasSuperEnvelope()) root = root.getSuperEnvelope(); for (Variable depVar : root.getRecursivelyDependentVariables()) { TrajectoryEnvelope depTE = (TrajectoryEnvelope)depVar; if (!depTE.hasSubEnvelopes() && depTE.getTrajectory().getSequenceNumberEnd() == mustWaitToStart.getSequenceNumberStart()-1) { waitingEnvelope = depTE; // depends on control dependency: [if], data = [none] break; } } //Calculate waiting points Integer thresholdPoint = mustFinishBeforeOtherCanStart.getTrajectory().getSequenceNumberEnd(); Integer waitingPoint = null; //If there was no previous envelope, then make the robot stay in the start point of this one if (waitingEnvelope == null) { //System.out.println("IGNORE THIS DEPENDENCY, the following robot is parked anyway " + mustWaitToStart); waitingPoint = mustWaitToStart.getTrajectory().getSequenceNumberStart(); // depends on control dependency: [if], data = [none] waitingEnvelope = mustWaitToStart; // depends on control dependency: [if], data = [none] } else { waitingPoint = waitingEnvelope.getTrajectory().getSequenceNumberEnd(); // depends on control dependency: [if], data = [none] } //Add edge in dep graph ArrayList<TrajectoryEnvelope> verts = new ArrayList<TrajectoryEnvelope>(); verts.add(waitingEnvelope); // depends on control dependency: [if], data = [none] verts.add(mustFinishBeforeOtherCanStart); // depends on control dependency: [if], data = [none] depGraph.addVertex(waitingEnvelope); // depends on control dependency: [if], data = [none] depGraph.addVertex(mustFinishBeforeOtherCanStart); // depends on control dependency: [if], data = [none] depGraph.addEdge(new Integer[] {waitingPoint,thresholdPoint}, waitingEnvelope, mustFinishBeforeOtherCanStart); // depends on control dependency: [if], data = [none] } } } return depGraph; } }
public class class_name { public void processDocument(BufferedReader document) throws IOException { Map<String, Integer> wordFreq = new HashMap<String, Integer>(); Map<String, SparseDoubleVector> wordDocSemantics = new HashMap<String, SparseDoubleVector>(); // Setup queues to track the set of previous and next words in a // context. Queue<String> prevWords = new ArrayDeque<String>(); Queue<String> nextWords = new ArrayDeque<String>(); Iterator<String> it = IteratorFactory.tokenizeOrdered(document); for (int i = 0; i < 4 && it.hasNext(); ++i) nextWords.offer(it.next()); // Compute the co-occurrance statistics of each focus word in the // document. while (!nextWords.isEmpty()) { // Slide over the context by one word. if (it.hasNext()) nextWords.offer(it.next()); // Get the focus word String focusWord = nextWords.remove(); if (!focusWord.equals(IteratorFactory.EMPTY_TOKEN)) { getIndexFor(focusWord); // Update the frequency count of the focus word. Integer focusFreq = wordFreq.get(focusWord); wordFreq.put(focusWord, (focusFreq == null) ? 1 : 1 + focusFreq.intValue()); // Get the temprorary semantics for the focus word, create a new // vector for them if needed. SparseDoubleVector focusSemantics = wordDocSemantics.get( focusWord); if (focusSemantics == null) { focusSemantics = new SparseHashDoubleVector( Integer.MAX_VALUE); wordDocSemantics.put(focusWord, focusSemantics); } // Process the previous words. int offset = 4 - prevWords.size(); for (String word : prevWords) { offset++; if (word.equals(IteratorFactory.EMPTY_TOKEN)) continue; int index = getIndexFor(word); focusSemantics.add(index, offset); } // Process the next words. offset = 5; for (String word : nextWords) { offset--; if (word.equals(IteratorFactory.EMPTY_TOKEN)) continue; int index = getIndexFor(word); focusSemantics.add(index, offset); } } prevWords.offer(focusWord); if (prevWords.size() > 4) prevWords.remove(); } // Add the temporary vectors for each word in this document to the // actual semantic fectors. for (Map.Entry<String, SparseDoubleVector> e : wordDocSemantics.entrySet()) { SparseDoubleVector focusSemantics = getSemanticVector( e.getKey()); // Get the non zero indices before hand so that they are cached // during the synchronized section. focusSemantics.getNonZeroIndices(); synchronized (focusSemantics) { VectorMath.add(focusSemantics, e.getValue()); } } // Store the total frequency counts of the words seen in this document // so far. for (Map.Entry<String, Integer> entry : wordFreq.entrySet()) { int count = entry.getValue().intValue(); AtomicInteger freq = totalWordFreq.putIfAbsent( entry.getKey(), new AtomicInteger(count)); if (freq != null) freq.addAndGet(count); } } }
public class class_name { public void processDocument(BufferedReader document) throws IOException { Map<String, Integer> wordFreq = new HashMap<String, Integer>(); Map<String, SparseDoubleVector> wordDocSemantics = new HashMap<String, SparseDoubleVector>(); // Setup queues to track the set of previous and next words in a // context. Queue<String> prevWords = new ArrayDeque<String>(); Queue<String> nextWords = new ArrayDeque<String>(); Iterator<String> it = IteratorFactory.tokenizeOrdered(document); for (int i = 0; i < 4 && it.hasNext(); ++i) nextWords.offer(it.next()); // Compute the co-occurrance statistics of each focus word in the // document. while (!nextWords.isEmpty()) { // Slide over the context by one word. if (it.hasNext()) nextWords.offer(it.next()); // Get the focus word String focusWord = nextWords.remove(); if (!focusWord.equals(IteratorFactory.EMPTY_TOKEN)) { getIndexFor(focusWord); // Update the frequency count of the focus word. Integer focusFreq = wordFreq.get(focusWord); wordFreq.put(focusWord, (focusFreq == null) ? 1 : 1 + focusFreq.intValue()); // Get the temprorary semantics for the focus word, create a new // vector for them if needed. SparseDoubleVector focusSemantics = wordDocSemantics.get( focusWord); if (focusSemantics == null) { focusSemantics = new SparseHashDoubleVector( Integer.MAX_VALUE); // depends on control dependency: [if], data = [none] wordDocSemantics.put(focusWord, focusSemantics); // depends on control dependency: [if], data = [none] } // Process the previous words. int offset = 4 - prevWords.size(); for (String word : prevWords) { offset++; // depends on control dependency: [for], data = [none] if (word.equals(IteratorFactory.EMPTY_TOKEN)) continue; int index = getIndexFor(word); focusSemantics.add(index, offset); // depends on control dependency: [for], data = [none] } // Process the next words. offset = 5; for (String word : nextWords) { offset--; // depends on control dependency: [for], data = [none] if (word.equals(IteratorFactory.EMPTY_TOKEN)) continue; int index = getIndexFor(word); focusSemantics.add(index, offset); // depends on control dependency: [for], data = [none] } } prevWords.offer(focusWord); if (prevWords.size() > 4) prevWords.remove(); } // Add the temporary vectors for each word in this document to the // actual semantic fectors. for (Map.Entry<String, SparseDoubleVector> e : wordDocSemantics.entrySet()) { SparseDoubleVector focusSemantics = getSemanticVector( e.getKey()); // Get the non zero indices before hand so that they are cached // during the synchronized section. focusSemantics.getNonZeroIndices(); synchronized (focusSemantics) { VectorMath.add(focusSemantics, e.getValue()); } } // Store the total frequency counts of the words seen in this document // so far. for (Map.Entry<String, Integer> entry : wordFreq.entrySet()) { int count = entry.getValue().intValue(); AtomicInteger freq = totalWordFreq.putIfAbsent( entry.getKey(), new AtomicInteger(count)); if (freq != null) freq.addAndGet(count); } } }
public class class_name { public static void addDeclaredMethodsFromAllInterfaces(ClassNode cNode, Map<String, MethodNode> methodsMap) { List cnInterfaces = Arrays.asList(cNode.getInterfaces()); ClassNode parent = cNode.getSuperClass(); while (parent != null && !parent.equals(ClassHelper.OBJECT_TYPE)) { ClassNode[] interfaces = parent.getInterfaces(); for (ClassNode iface : interfaces) { if (!cnInterfaces.contains(iface)) { methodsMap.putAll(iface.getDeclaredMethodsMap()); } } parent = parent.getSuperClass(); } } }
public class class_name { public static void addDeclaredMethodsFromAllInterfaces(ClassNode cNode, Map<String, MethodNode> methodsMap) { List cnInterfaces = Arrays.asList(cNode.getInterfaces()); ClassNode parent = cNode.getSuperClass(); while (parent != null && !parent.equals(ClassHelper.OBJECT_TYPE)) { ClassNode[] interfaces = parent.getInterfaces(); for (ClassNode iface : interfaces) { if (!cnInterfaces.contains(iface)) { methodsMap.putAll(iface.getDeclaredMethodsMap()); // depends on control dependency: [if], data = [none] } } parent = parent.getSuperClass(); // depends on control dependency: [while], data = [none] } } }
public class class_name { public void clearValidationStyles() { for (JQMFormWidget widget : widgetValidators.keySet()) { UIObject ui = widget.asWidget(); Collection<Validator> validators = widgetValidators.get(widget); for (Validator v : validators) { if (notifiedWidgets.containsKey(v)) { ui = notifiedWidgets.get(v); } removeStyles(v, ui); } } } }
public class class_name { public void clearValidationStyles() { for (JQMFormWidget widget : widgetValidators.keySet()) { UIObject ui = widget.asWidget(); Collection<Validator> validators = widgetValidators.get(widget); for (Validator v : validators) { if (notifiedWidgets.containsKey(v)) { ui = notifiedWidgets.get(v); // depends on control dependency: [if], data = [none] } removeStyles(v, ui); // depends on control dependency: [for], data = [v] } } } }
public class class_name { protected void appenHtmlFooter(StringBuffer buffer) { if (m_configuredFooter != null) { buffer.append(m_configuredFooter); } else { buffer.append(" </body>\r\n" + "</html>"); } } }
public class class_name { protected void appenHtmlFooter(StringBuffer buffer) { if (m_configuredFooter != null) { buffer.append(m_configuredFooter); // depends on control dependency: [if], data = [(m_configuredFooter] } else { buffer.append(" </body>\r\n" + "</html>"); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void setMailFromDefault(String sender) { m_mailFromDefault = sender; if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info(Messages.get().getBundle().key(Messages.LOG_DEFAULT_SENDER_1, m_mailFromDefault)); } } }
public class class_name { public void setMailFromDefault(String sender) { m_mailFromDefault = sender; if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info(Messages.get().getBundle().key(Messages.LOG_DEFAULT_SENDER_1, m_mailFromDefault)); // depends on control dependency: [if], data = [none] } } }
public class class_name { static final public RateOptions parseRateOptions(final boolean rate, final String spec) { if (!rate || spec.length() == 4) { return new RateOptions(false, Long.MAX_VALUE, RateOptions.DEFAULT_RESET_VALUE); } if (spec.length() < 6) { throw new BadRequestException("Invalid rate options specification: " + spec); } String[] parts = Tags .splitString(spec.substring(5, spec.length() - 1), ','); if (parts.length < 1 || parts.length > 3) { throw new BadRequestException( "Incorrect number of values in rate options specification, must be " + "counter[,counter max value,reset value], recieved: " + parts.length + " parts"); } final boolean counter = parts[0].endsWith("counter"); try { final long max = (parts.length >= 2 && parts[1].length() > 0 ? Long .parseLong(parts[1]) : Long.MAX_VALUE); try { final long reset = (parts.length >= 3 && parts[2].length() > 0 ? Long .parseLong(parts[2]) : RateOptions.DEFAULT_RESET_VALUE); final boolean drop_counter = parts[0].equals("dropcounter"); return new RateOptions(counter, max, reset, drop_counter); } catch (NumberFormatException e) { throw new BadRequestException( "Reset value of counter was not a number, received '" + parts[2] + "'"); } } catch (NumberFormatException e) { throw new BadRequestException( "Max value of counter was not a number, received '" + parts[1] + "'"); } } }
public class class_name { static final public RateOptions parseRateOptions(final boolean rate, final String spec) { if (!rate || spec.length() == 4) { return new RateOptions(false, Long.MAX_VALUE, RateOptions.DEFAULT_RESET_VALUE); // depends on control dependency: [if], data = [none] } if (spec.length() < 6) { throw new BadRequestException("Invalid rate options specification: " + spec); } String[] parts = Tags .splitString(spec.substring(5, spec.length() - 1), ','); if (parts.length < 1 || parts.length > 3) { throw new BadRequestException( "Incorrect number of values in rate options specification, must be " + "counter[,counter max value,reset value], recieved: " + parts.length + " parts"); } final boolean counter = parts[0].endsWith("counter"); try { final long max = (parts.length >= 2 && parts[1].length() > 0 ? Long .parseLong(parts[1]) : Long.MAX_VALUE); try { final long reset = (parts.length >= 3 && parts[2].length() > 0 ? Long .parseLong(parts[2]) : RateOptions.DEFAULT_RESET_VALUE); final boolean drop_counter = parts[0].equals("dropcounter"); return new RateOptions(counter, max, reset, drop_counter); // depends on control dependency: [try], data = [none] } catch (NumberFormatException e) { throw new BadRequestException( "Reset value of counter was not a number, received '" + parts[2] + "'"); } // depends on control dependency: [catch], data = [none] } catch (NumberFormatException e) { throw new BadRequestException( "Max value of counter was not a number, received '" + parts[1] + "'"); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public BitSet projectG2(BitSet set) { BitSet projection = new BitSet(secondGraphSize); RNode xNode = null; for (int x = set.nextSetBit(0); x >= 0; x = set.nextSetBit(x + 1)) { xNode = (RNode) graph.get(x); projection.set(xNode.rMap.id2); } return projection; } }
public class class_name { public BitSet projectG2(BitSet set) { BitSet projection = new BitSet(secondGraphSize); RNode xNode = null; for (int x = set.nextSetBit(0); x >= 0; x = set.nextSetBit(x + 1)) { xNode = (RNode) graph.get(x); // depends on control dependency: [for], data = [x] projection.set(xNode.rMap.id2); // depends on control dependency: [for], data = [none] } return projection; } }
public class class_name { @Override public EEnum getIfcDuctSilencerTypeEnum() { if (ifcDuctSilencerTypeEnumEEnum == null) { ifcDuctSilencerTypeEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(973); } return ifcDuctSilencerTypeEnumEEnum; } }
public class class_name { @Override public EEnum getIfcDuctSilencerTypeEnum() { if (ifcDuctSilencerTypeEnumEEnum == null) { ifcDuctSilencerTypeEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(973); // depends on control dependency: [if], data = [none] } return ifcDuctSilencerTypeEnumEEnum; } }
public class class_name { public final void setGoods(final InvItem pGoods) { this.goods = pGoods; if (this.itsId == null) { this.itsId = new CustomerGoodsSeenId(); } this.itsId.setGoods(this.goods); } }
public class class_name { public final void setGoods(final InvItem pGoods) { this.goods = pGoods; if (this.itsId == null) { this.itsId = new CustomerGoodsSeenId(); // depends on control dependency: [if], data = [none] } this.itsId.setGoods(this.goods); } }
public class class_name { @Override public URL[] findResources() { URL[] result = null; if (classesToScan != null && !classesToScan.isEmpty()) { result = findResourcesByContextLoader(); } // else // { // result = findResourcesByClasspath(); // } return result; } }
public class class_name { @Override public URL[] findResources() { URL[] result = null; if (classesToScan != null && !classesToScan.isEmpty()) { result = findResourcesByContextLoader(); // depends on control dependency: [if], data = [none] } // else // { // result = findResourcesByClasspath(); // } return result; } }
public class class_name { public List<RawProperty> removeExperimentalProperties(String name) { List<RawProperty> all = getExperimentalProperties(); List<RawProperty> toRemove = new ArrayList<RawProperty>(); for (RawProperty property : all) { if (property.getName().equalsIgnoreCase(name)) { toRemove.add(property); } } all.removeAll(toRemove); return Collections.unmodifiableList(toRemove); } }
public class class_name { public List<RawProperty> removeExperimentalProperties(String name) { List<RawProperty> all = getExperimentalProperties(); List<RawProperty> toRemove = new ArrayList<RawProperty>(); for (RawProperty property : all) { if (property.getName().equalsIgnoreCase(name)) { toRemove.add(property); // depends on control dependency: [if], data = [none] } } all.removeAll(toRemove); return Collections.unmodifiableList(toRemove); } }
public class class_name { public void terminate() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, "terminate"); } AsyncLibrary.shutdown(); groups.clear(); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.exit(tc, "terminate"); } } }
public class class_name { public void terminate() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.entry(tc, "terminate"); // depends on control dependency: [if], data = [none] } AsyncLibrary.shutdown(); groups.clear(); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) { Tr.exit(tc, "terminate"); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static Object concat(Object arr1, Object arr2) { int len1 = (arr1 == null) ? (-1) : Array.getLength(arr1); if (len1 <= 0) { return arr2; } int len2 = (arr2 == null) ? (-1) : Array.getLength(arr2); if (len2 <= 0) { return arr1; } Class commonComponentType = commonClass(arr1.getClass().getComponentType(), arr2.getClass().getComponentType()); Object newArray = Array.newInstance(commonComponentType, len1 + len2); System.arraycopy(arr1, 0, newArray, 0, len1); System.arraycopy(arr2, 0, newArray, len1, len2); return newArray; } }
public class class_name { public static Object concat(Object arr1, Object arr2) { int len1 = (arr1 == null) ? (-1) : Array.getLength(arr1); if (len1 <= 0) { return arr2; // depends on control dependency: [if], data = [none] } int len2 = (arr2 == null) ? (-1) : Array.getLength(arr2); if (len2 <= 0) { return arr1; // depends on control dependency: [if], data = [none] } Class commonComponentType = commonClass(arr1.getClass().getComponentType(), arr2.getClass().getComponentType()); Object newArray = Array.newInstance(commonComponentType, len1 + len2); System.arraycopy(arr1, 0, newArray, 0, len1); System.arraycopy(arr2, 0, newArray, len1, len2); return newArray; } }
public class class_name { public void updateJobStatus(final InternalJobStatus newJobStatus, String optionalMessage) { // Check if the new job status equals the old one if (this.jobStatus.getAndSet(newJobStatus) == newJobStatus) { return; } // The task caused the entire job to fail, save the error description if (newJobStatus == InternalJobStatus.FAILING) { this.errorDescription = optionalMessage; } // If this is the final failure state change, reuse the saved error description if (newJobStatus == InternalJobStatus.FAILED) { optionalMessage = this.errorDescription; } final Iterator<JobStatusListener> it = this.jobStatusListeners.iterator(); while (it.hasNext()) { it.next().jobStatusHasChanged(this, newJobStatus, optionalMessage); } } }
public class class_name { public void updateJobStatus(final InternalJobStatus newJobStatus, String optionalMessage) { // Check if the new job status equals the old one if (this.jobStatus.getAndSet(newJobStatus) == newJobStatus) { return; // depends on control dependency: [if], data = [none] } // The task caused the entire job to fail, save the error description if (newJobStatus == InternalJobStatus.FAILING) { this.errorDescription = optionalMessage; // depends on control dependency: [if], data = [none] } // If this is the final failure state change, reuse the saved error description if (newJobStatus == InternalJobStatus.FAILED) { optionalMessage = this.errorDescription; // depends on control dependency: [if], data = [none] } final Iterator<JobStatusListener> it = this.jobStatusListeners.iterator(); while (it.hasNext()) { it.next().jobStatusHasChanged(this, newJobStatus, optionalMessage); // depends on control dependency: [while], data = [none] } } }
public class class_name { @Override protected List<UniqueKey<? extends Command>> defineSubCommand() { // for (Object keyPart : getListKeyPart()) { // if (keyPart instanceof GroupRef) { final List<UniqueKey<? extends Command>> commandList = new ArrayList<>(); // GroupRef groupRef = (GroupRef) keyPart; final GroupRef groupRef = getKeyPart(GroupRef.class); setSequential(groupRef.sequential()); this.runIntoThread = groupRef.runInto(); this.runnablePriority = groupRef.priority(); for (final Ref ref : groupRef.children()) { if (ref instanceof GroupRef) { commandList.add(getCommandKey(GroupRefCommand.class, ref)); } else if (ref instanceof SingleRef) { commandList.add(getCommandKey(RefCommand.class, ref)); } else if (ref instanceof RealRef) { commandList.add(((RealRef) ref).key()); } } return commandList; // break; // } // } } }
public class class_name { @Override protected List<UniqueKey<? extends Command>> defineSubCommand() { // for (Object keyPart : getListKeyPart()) { // if (keyPart instanceof GroupRef) { final List<UniqueKey<? extends Command>> commandList = new ArrayList<>(); // GroupRef groupRef = (GroupRef) keyPart; final GroupRef groupRef = getKeyPart(GroupRef.class); setSequential(groupRef.sequential()); this.runIntoThread = groupRef.runInto(); this.runnablePriority = groupRef.priority(); for (final Ref ref : groupRef.children()) { if (ref instanceof GroupRef) { commandList.add(getCommandKey(GroupRefCommand.class, ref)); // depends on control dependency: [if], data = [none] } else if (ref instanceof SingleRef) { commandList.add(getCommandKey(RefCommand.class, ref)); // depends on control dependency: [if], data = [none] } else if (ref instanceof RealRef) { commandList.add(((RealRef) ref).key()); // depends on control dependency: [if], data = [none] } } return commandList; // break; // } // } } }
public class class_name { public static void zipDir(File directory, File zipfile) throws IOException { URI base = directory.toURI(); Deque<File> queue = new LinkedList<File>(); queue.push(directory); OutputStream out = new FileOutputStream(zipfile); Closeable res = out; try { ZipOutputStream zout = new ZipOutputStream(out); res = zout; while (!queue.isEmpty()) { directory = queue.pop(); for (File kid : directory.listFiles()) { String name = base.relativize(kid.toURI()).getPath(); if (kid.isDirectory()) { queue.push(kid); name = name.endsWith("/") ? name : name + "/"; zout.putNextEntry(new ZipEntry(name)); } else { zout.putNextEntry(new ZipEntry(name)); copy(kid, zout); zout.closeEntry(); } } } } finally { res.close(); } } }
public class class_name { public static void zipDir(File directory, File zipfile) throws IOException { URI base = directory.toURI(); Deque<File> queue = new LinkedList<File>(); queue.push(directory); OutputStream out = new FileOutputStream(zipfile); Closeable res = out; try { ZipOutputStream zout = new ZipOutputStream(out); res = zout; while (!queue.isEmpty()) { directory = queue.pop(); // depends on control dependency: [while], data = [none] for (File kid : directory.listFiles()) { String name = base.relativize(kid.toURI()).getPath(); if (kid.isDirectory()) { queue.push(kid); // depends on control dependency: [if], data = [none] name = name.endsWith("/") ? name : name + "/"; // depends on control dependency: [if], data = [none] zout.putNextEntry(new ZipEntry(name)); // depends on control dependency: [if], data = [none] } else { zout.putNextEntry(new ZipEntry(name)); // depends on control dependency: [if], data = [none] copy(kid, zout); // depends on control dependency: [if], data = [none] zout.closeEntry(); // depends on control dependency: [if], data = [none] } } } } finally { res.close(); } } }
public class class_name { public void addConnectionEventListener(ConnectionEventListener listener) { final boolean isTraceOn = TraceComponent.isAnyTracingEnabled(); if (isTraceOn && tc.isDebugEnabled()) Tr.debug(this, tc, "addConnectionEventListener", listener); if (listener == null) throw new NullPointerException( "Cannot add null ConnectionEventListener."); // Not synchronized because of the contract that add/remove event listeners will only // be used on ManagedConnection create/destroy, when the ManagedConnection is not // used by any other threads. // Add the listener to the end of the array -- if the array is full, // then need to create a new, bigger one // check if the array is already full if (numListeners >= ivEventListeners.length) { // there is not enough room for the listener in the array // create a new, bigger array // Use the standard interface for event listeners instead of J2C's. ConnectionEventListener[] tempArray = ivEventListeners; ivEventListeners = new ConnectionEventListener[numListeners + CEL_ARRAY_INCREMENT_SIZE]; // parms: arraycopy(Object source, int srcIndex, Object dest, int destIndex, int length) System.arraycopy(tempArray, 0, ivEventListeners, 0, tempArray.length); // point out in the trace that we had to do this - consider code changes if there // are new CELs to handle (change KNOWN_NUMBER_OF_CELS, new events?, ...) if (isTraceOn && tc.isDebugEnabled()) Tr.debug(this, tc, "received more ConnectionEventListeners than expected, " + "increased array size to " + ivEventListeners.length); } // add listener to the array, increment listener counter ivEventListeners[numListeners++] = listener; } }
public class class_name { public void addConnectionEventListener(ConnectionEventListener listener) { final boolean isTraceOn = TraceComponent.isAnyTracingEnabled(); if (isTraceOn && tc.isDebugEnabled()) Tr.debug(this, tc, "addConnectionEventListener", listener); if (listener == null) throw new NullPointerException( "Cannot add null ConnectionEventListener."); // Not synchronized because of the contract that add/remove event listeners will only // be used on ManagedConnection create/destroy, when the ManagedConnection is not // used by any other threads. // Add the listener to the end of the array -- if the array is full, // then need to create a new, bigger one // check if the array is already full if (numListeners >= ivEventListeners.length) { // there is not enough room for the listener in the array // create a new, bigger array // Use the standard interface for event listeners instead of J2C's. ConnectionEventListener[] tempArray = ivEventListeners; ivEventListeners = new ConnectionEventListener[numListeners + CEL_ARRAY_INCREMENT_SIZE]; // depends on control dependency: [if], data = [none] // parms: arraycopy(Object source, int srcIndex, Object dest, int destIndex, int length) System.arraycopy(tempArray, 0, ivEventListeners, 0, tempArray.length); // depends on control dependency: [if], data = [none] // point out in the trace that we had to do this - consider code changes if there // are new CELs to handle (change KNOWN_NUMBER_OF_CELS, new events?, ...) if (isTraceOn && tc.isDebugEnabled()) Tr.debug(this, tc, "received more ConnectionEventListeners than expected, " + "increased array size to " + ivEventListeners.length); } // add listener to the array, increment listener counter ivEventListeners[numListeners++] = listener; } }
public class class_name { private Object[] getMethodArgumentValues(WampMessage message, Object... providedArgs) throws Exception { MethodParameter[] parameters = getMethodParameters(); Object[] args = new Object[parameters.length]; int argIndex = 0; for (int i = 0; i < parameters.length; i++) { MethodParameter parameter = parameters[i]; parameter.initParameterNameDiscovery(this.parameterNameDiscoverer); GenericTypeResolver.resolveParameterType(parameter, getBean().getClass()); if (this.argumentResolvers.supportsParameter(parameter)) { try { args[i] = this.argumentResolvers.resolveArgument(parameter, message); continue; } catch (Exception ex) { if (this.logger.isTraceEnabled()) { this.logger.trace(getArgumentResolutionErrorMessage( "Error resolving argument", i), ex); } throw ex; } } if (providedArgs != null) { args[i] = this.methodParameterConverter.convert(parameter, providedArgs[argIndex]); if (args[i] != null) { argIndex++; continue; } } if (args[i] == null) { String error = getArgumentResolutionErrorMessage( "No suitable resolver for argument", i); throw new IllegalStateException(error); } } return args; } }
public class class_name { private Object[] getMethodArgumentValues(WampMessage message, Object... providedArgs) throws Exception { MethodParameter[] parameters = getMethodParameters(); Object[] args = new Object[parameters.length]; int argIndex = 0; for (int i = 0; i < parameters.length; i++) { MethodParameter parameter = parameters[i]; parameter.initParameterNameDiscovery(this.parameterNameDiscoverer); GenericTypeResolver.resolveParameterType(parameter, getBean().getClass()); if (this.argumentResolvers.supportsParameter(parameter)) { try { args[i] = this.argumentResolvers.resolveArgument(parameter, message); continue; } catch (Exception ex) { if (this.logger.isTraceEnabled()) { this.logger.trace(getArgumentResolutionErrorMessage( "Error resolving argument", i), ex); // depends on control dependency: [if], data = [none] } throw ex; } } if (providedArgs != null) { args[i] = this.methodParameterConverter.convert(parameter, providedArgs[argIndex]); if (args[i] != null) { argIndex++; continue; } } if (args[i] == null) { String error = getArgumentResolutionErrorMessage( "No suitable resolver for argument", i); throw new IllegalStateException(error); } } return args; } }
public class class_name { protected Set<String> queryQueueNames (String location, String brokerName, String queueNamePattern) throws Exception { Set<String> result = new TreeSet<>(); if ( location.equals("*") ) { // TBD222: stop using address (aka location) as the registry key for ( String oneLocation : this.brokerRegistry.keys() ) { result.addAll(this.queryQueueNames(oneLocation, brokerName, queueNamePattern)); // RECURSION } } else { if ( brokerName.equals("*") ) { String[] brokerNames = this.queryBrokerNames(location); for ( String oneBrokerName : brokerNames ) { result.addAll(this.queryQueueNames(location, oneBrokerName, queueNamePattern)); // RECURSION } } else { String[] names = this.jmxActiveMQUtil.queryQueueNames(location, brokerName, queueNamePattern); result.addAll(Arrays.asList(names)); } } return result; } }
public class class_name { protected Set<String> queryQueueNames (String location, String brokerName, String queueNamePattern) throws Exception { Set<String> result = new TreeSet<>(); if ( location.equals("*") ) { // TBD222: stop using address (aka location) as the registry key for ( String oneLocation : this.brokerRegistry.keys() ) { result.addAll(this.queryQueueNames(oneLocation, brokerName, queueNamePattern)); // RECURSION // depends on control dependency: [for], data = [oneLocation] } } else { if ( brokerName.equals("*") ) { String[] brokerNames = this.queryBrokerNames(location); for ( String oneBrokerName : brokerNames ) { result.addAll(this.queryQueueNames(location, oneBrokerName, queueNamePattern)); // RECURSION // depends on control dependency: [for], data = [oneBrokerName] } } else { String[] names = this.jmxActiveMQUtil.queryQueueNames(location, brokerName, queueNamePattern); result.addAll(Arrays.asList(names)); // depends on control dependency: [if], data = [none] } } return result; } }
public class class_name { public static void elementDivide(ZMatrixD1 input , double real , double imaginary, ZMatrixD1 output ) { if( input.numCols != output.numCols || input.numRows != output.numRows ) { throw new IllegalArgumentException("The 'input' and 'output' matrices do not have compatible dimensions"); } double norm = real*real + imaginary*imaginary; int N = input.getDataLength(); for (int i = 0; i < N; i += 2 ) { double inReal = input.data[i]; double inImag = input.data[i+1]; output.data[i] = (inReal*real + inImag*imaginary)/norm; output.data[i+1] = (inImag*real - inReal*imaginary)/norm; } } }
public class class_name { public static void elementDivide(ZMatrixD1 input , double real , double imaginary, ZMatrixD1 output ) { if( input.numCols != output.numCols || input.numRows != output.numRows ) { throw new IllegalArgumentException("The 'input' and 'output' matrices do not have compatible dimensions"); } double norm = real*real + imaginary*imaginary; int N = input.getDataLength(); for (int i = 0; i < N; i += 2 ) { double inReal = input.data[i]; double inImag = input.data[i+1]; output.data[i] = (inReal*real + inImag*imaginary)/norm; // depends on control dependency: [for], data = [i] output.data[i+1] = (inImag*real - inReal*imaginary)/norm; // depends on control dependency: [for], data = [i] } } }
public class class_name { public RuntimeEnvironmentBuilder addConfiguration(String name, String value) { if (name == null || value == null) { return this; } _runtimeEnvironment.addToConfiguration(name, value); return this; } }
public class class_name { public RuntimeEnvironmentBuilder addConfiguration(String name, String value) { if (name == null || value == null) { return this; // depends on control dependency: [if], data = [none] } _runtimeEnvironment.addToConfiguration(name, value); return this; } }
public class class_name { public static void closeClient(TServiceClient client) { if (client == null) { return; } try { TProtocol proto = client.getInputProtocol(); if (proto != null) { proto.getTransport().close(); } } catch (Throwable e) { logger.warn("close input transport fail", e); } try { TProtocol proto = client.getOutputProtocol(); if (proto != null) { proto.getTransport().close(); } } catch (Throwable e) { logger.warn("close output transport fail", e); } } }
public class class_name { public static void closeClient(TServiceClient client) { if (client == null) { return; // depends on control dependency: [if], data = [none] } try { TProtocol proto = client.getInputProtocol(); if (proto != null) { proto.getTransport().close(); // depends on control dependency: [if], data = [none] } } catch (Throwable e) { logger.warn("close input transport fail", e); } // depends on control dependency: [catch], data = [none] try { TProtocol proto = client.getOutputProtocol(); if (proto != null) { proto.getTransport().close(); // depends on control dependency: [if], data = [none] } } catch (Throwable e) { logger.warn("close output transport fail", e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public JTree resetTree(TreeTableModel treeTableModel) { tree = new TreeTableCellRenderer(treeTableModel); // Install a tableModel representing the visible rows in the tree. super.setModel(new TreeTableModelAdapter(treeTableModel, tree)); // Force the JTable and JTree to share their row selection models. ListToTreeSelectionModelWrapper selectionWrapper = new ListToTreeSelectionModelWrapper(); tree.setSelectionModel(selectionWrapper); setSelectionModel(selectionWrapper.getListSelectionModel()); // Make the tree and table row heights the same. if (tree.getRowHeight() < 1) { // Metal looks better like this. setRowHeight(18); } // Install the tree editor renderer and editor. setDefaultRenderer(TreeTableModel.class, tree); setDefaultEditor(TreeTableModel.class, new TreeTableCellEditor()); setShowGrid(true); setIntercellSpacing(new Dimension(1,1)); tree.setRootVisible(false); tree.setShowsRootHandles(true); DefaultTreeCellRenderer r = (DefaultTreeCellRenderer)tree.getCellRenderer(); r.setOpenIcon(null); r.setClosedIcon(null); r.setLeafIcon(null); return tree; } }
public class class_name { public JTree resetTree(TreeTableModel treeTableModel) { tree = new TreeTableCellRenderer(treeTableModel); // Install a tableModel representing the visible rows in the tree. super.setModel(new TreeTableModelAdapter(treeTableModel, tree)); // Force the JTable and JTree to share their row selection models. ListToTreeSelectionModelWrapper selectionWrapper = new ListToTreeSelectionModelWrapper(); tree.setSelectionModel(selectionWrapper); setSelectionModel(selectionWrapper.getListSelectionModel()); // Make the tree and table row heights the same. if (tree.getRowHeight() < 1) { // Metal looks better like this. setRowHeight(18); // depends on control dependency: [if], data = [none] } // Install the tree editor renderer and editor. setDefaultRenderer(TreeTableModel.class, tree); setDefaultEditor(TreeTableModel.class, new TreeTableCellEditor()); setShowGrid(true); setIntercellSpacing(new Dimension(1,1)); tree.setRootVisible(false); tree.setShowsRootHandles(true); DefaultTreeCellRenderer r = (DefaultTreeCellRenderer)tree.getCellRenderer(); r.setOpenIcon(null); r.setClosedIcon(null); r.setLeafIcon(null); return tree; } }
public class class_name { public synchronized void onPotentiallyIdle(final IdleMessage reason) { final DriverStatusManager driverStatusManagerImpl = this.driverStatusManager.get(); if (driverStatusManagerImpl.isClosing()) { LOG.log(IDLE_REASONS_LEVEL, "Ignoring idle call from [{0}] for reason [{1}]", new Object[] {reason.getComponentName(), reason.getReason()}); return; } LOG.log(IDLE_REASONS_LEVEL, "Checking for idle because {0} reported idleness for reason [{1}]", new Object[] {reason.getComponentName(), reason.getReason()}); boolean isIdle = true; for (final DriverIdlenessSource idlenessSource : this.idlenessSources) { final IdleMessage idleMessage = idlenessSource.getIdleStatus(); LOG.log(IDLE_REASONS_LEVEL, "[{0}] is reporting {1} because [{2}].", new Object[] {idleMessage.getComponentName(), idleMessage.isIdle() ? "idle" : "not idle", idleMessage.getReason()}); isIdle &= idleMessage.isIdle(); } LOG.log(IDLE_REASONS_LEVEL, "onPotentiallyIdle: isIdle: " + isIdle); if (isIdle) { LOG.log(Level.INFO, "All components indicated idle. Initiating Driver shutdown."); driverStatusManagerImpl.onComplete(); } } }
public class class_name { public synchronized void onPotentiallyIdle(final IdleMessage reason) { final DriverStatusManager driverStatusManagerImpl = this.driverStatusManager.get(); if (driverStatusManagerImpl.isClosing()) { LOG.log(IDLE_REASONS_LEVEL, "Ignoring idle call from [{0}] for reason [{1}]", new Object[] {reason.getComponentName(), reason.getReason()}); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } LOG.log(IDLE_REASONS_LEVEL, "Checking for idle because {0} reported idleness for reason [{1}]", new Object[] {reason.getComponentName(), reason.getReason()}); boolean isIdle = true; for (final DriverIdlenessSource idlenessSource : this.idlenessSources) { final IdleMessage idleMessage = idlenessSource.getIdleStatus(); LOG.log(IDLE_REASONS_LEVEL, "[{0}] is reporting {1} because [{2}].", new Object[] {idleMessage.getComponentName(), idleMessage.isIdle() ? "idle" : "not idle", idleMessage.getReason()}); // depends on control dependency: [for], data = [none] isIdle &= idleMessage.isIdle(); // depends on control dependency: [for], data = [none] } LOG.log(IDLE_REASONS_LEVEL, "onPotentiallyIdle: isIdle: " + isIdle); if (isIdle) { LOG.log(Level.INFO, "All components indicated idle. Initiating Driver shutdown."); // depends on control dependency: [if], data = [none] driverStatusManagerImpl.onComplete(); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void setProvisioningArtifacts(java.util.Collection<ProvisioningArtifact> provisioningArtifacts) { if (provisioningArtifacts == null) { this.provisioningArtifacts = null; return; } this.provisioningArtifacts = new java.util.ArrayList<ProvisioningArtifact>(provisioningArtifacts); } }
public class class_name { public void setProvisioningArtifacts(java.util.Collection<ProvisioningArtifact> provisioningArtifacts) { if (provisioningArtifacts == null) { this.provisioningArtifacts = null; // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } this.provisioningArtifacts = new java.util.ArrayList<ProvisioningArtifact>(provisioningArtifacts); } }
public class class_name { @Override public boolean isOpaque(SynthContext ctx) { // Force Table CellRenderers to be opaque if ("Table.cellRenderer".equals(ctx.getComponent().getName())) { return true; } Boolean opaque = (Boolean) get(ctx, "opaque"); return opaque == null ? false : opaque; } }
public class class_name { @Override public boolean isOpaque(SynthContext ctx) { // Force Table CellRenderers to be opaque if ("Table.cellRenderer".equals(ctx.getComponent().getName())) { return true; // depends on control dependency: [if], data = [none] } Boolean opaque = (Boolean) get(ctx, "opaque"); return opaque == null ? false : opaque; } }
public class class_name { public static String getConvertedStringValue(FacesContext context, UIComponent component, Converter converter, Object value) { if (converter == null) { if (value == null) { return ""; } else if (value instanceof String) { return (String) value; } else { return value.toString(); } } return converter.getAsString(context, component, value); } }
public class class_name { public static String getConvertedStringValue(FacesContext context, UIComponent component, Converter converter, Object value) { if (converter == null) { if (value == null) { return ""; // depends on control dependency: [if], data = [none] } else if (value instanceof String) { return (String) value; // depends on control dependency: [if], data = [none] } else { return value.toString(); // depends on control dependency: [if], data = [none] } } return converter.getAsString(context, component, value); } }
public class class_name { public static synchronized PortRange getTcpSourceInstance() { if (tcpSourcePortRange == null) { tcpSourcePortRange = new PortRange(); tcpSourcePortRange.init( CoGProperties.getDefault().getTcpSourcePortRange()); } return tcpSourcePortRange; } }
public class class_name { public static synchronized PortRange getTcpSourceInstance() { if (tcpSourcePortRange == null) { tcpSourcePortRange = new PortRange(); // depends on control dependency: [if], data = [none] tcpSourcePortRange.init( CoGProperties.getDefault().getTcpSourcePortRange()); // depends on control dependency: [if], data = [none] } return tcpSourcePortRange; } }
public class class_name { public ORecord saveRecord(final ORecord iRecord, final String iClusterName, final OPERATION_MODE iMode, boolean iForceCreate, final ORecordCallback<? extends Number> iRecordCreatedCallback, ORecordCallback<Integer> iRecordUpdatedCallback) { try { return database.saveAll(iRecord, iClusterName, iMode, iForceCreate, iRecordCreatedCallback, iRecordUpdatedCallback); } catch (Exception e) { // REMOVE IT FROM THE CACHE TO AVOID DIRTY RECORDS final ORecordId rid = (ORecordId) iRecord.getIdentity(); if (rid.isValid()) database.getLocalCache().freeRecord(rid); if (e instanceof ONeedRetryException) throw (ONeedRetryException) e; throw OException.wrapException( new ODatabaseException("Error during saving of record" + (iRecord != null ? " with rid " + iRecord.getIdentity() : "")), e); } } }
public class class_name { public ORecord saveRecord(final ORecord iRecord, final String iClusterName, final OPERATION_MODE iMode, boolean iForceCreate, final ORecordCallback<? extends Number> iRecordCreatedCallback, ORecordCallback<Integer> iRecordUpdatedCallback) { try { return database.saveAll(iRecord, iClusterName, iMode, iForceCreate, iRecordCreatedCallback, iRecordUpdatedCallback); // depends on control dependency: [try], data = [none] } catch (Exception e) { // REMOVE IT FROM THE CACHE TO AVOID DIRTY RECORDS final ORecordId rid = (ORecordId) iRecord.getIdentity(); if (rid.isValid()) database.getLocalCache().freeRecord(rid); if (e instanceof ONeedRetryException) throw (ONeedRetryException) e; throw OException.wrapException( new ODatabaseException("Error during saving of record" + (iRecord != null ? " with rid " + iRecord.getIdentity() : "")), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { void start(String nodeName, JqmEngineHandler h) { if (nodeName == null || nodeName.isEmpty()) { throw new IllegalArgumentException("nodeName cannot be null or empty"); } this.handler = h; // Set thread name - used in audits Thread.currentThread().setName("JQM engine;;" + nodeName); // First event if (this.handler != null) { this.handler.onNodeStarting(nodeName); } // Log: we are starting... jqmlogger.info("JQM engine version " + this.getVersion() + " for node " + nodeName + " is starting"); jqmlogger.info("Java version is " + System.getProperty("java.version") + ". JVM was made by " + System.getProperty("java.vendor") + " as " + System.getProperty("java.vm.name") + " version " + System.getProperty("java.vm.version")); // JNDI first - the engine itself uses JNDI to fetch its connections! Helpers.registerJndiIfNeeded(); // Database connection DbConn cnx = Helpers.getNewDbSession(); cnx.logDatabaseInfo(jqmlogger); // Node configuration is in the database try { node = Node.select_single(cnx, "node_select_by_key", nodeName); } catch (NoResultException e) { throw new JqmRuntimeException("the specified node name [" + nodeName + "] does not exist in the configuration. Please create this node before starting it", e); } // Check if double-start long toWait = (long) (1.1 * Long.parseLong(GlobalParameter.getParameter(cnx, "internalPollingPeriodMs", "60000"))); if (node.getLastSeenAlive() != null && Calendar.getInstance().getTimeInMillis() - node.getLastSeenAlive().getTimeInMillis() <= toWait) { long r = Calendar.getInstance().getTimeInMillis() - node.getLastSeenAlive().getTimeInMillis(); throw new JqmInitErrorTooSoon("Another engine named " + nodeName + " was running less than " + r / 1000 + " seconds ago. Either stop the other node, or if it already stopped, please wait " + (toWait - r) / 1000 + " seconds"); } SimpleDateFormat ft = new SimpleDateFormat("dd/MM/YYYY hh:mm:ss"); jqmlogger.debug("The last time an engine with this name was seen was: " + (node.getLastSeenAlive() == null ? "" : ft.format(node.getLastSeenAlive().getTime()))); // Prevent very quick multiple starts by immediately setting the keep-alive QueryResult qr = cnx.runUpdate("node_update_alive_by_id", node.getId()); cnx.commit(); if (qr.nbUpdated == 0) { throw new JqmInitErrorTooSoon("Another engine named " + nodeName + " is running"); } // Only start if the node configuration seems OK Helpers.checkConfiguration(nodeName, cnx); // Log parameters Helpers.dumpParameters(cnx, node); // The handler may take any actions it wishes here - such as setting log levels, starting Jetty... if (this.handler != null) { this.handler.onNodeConfigurationRead(node); } // Remote JMX server if (node.getJmxRegistryPort() != null && node.getJmxServerPort() != null && node.getJmxRegistryPort() > 0 && node.getJmxServerPort() > 0) { JmxAgent.registerAgent(node.getJmxRegistryPort(), node.getJmxServerPort(), node.getDns()); } else { jqmlogger.info( "JMX remote listener will not be started as JMX registry port and JMX server port parameters are not both defined"); } // JMX if (node.getJmxServerPort() != null && node.getJmxServerPort() > 0) { try { MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); name = new ObjectName("com.enioka.jqm:type=Node,name=" + this.node.getName()); mbs.registerMBean(this, name); } catch (Exception e) { throw new JqmInitError("Could not create JMX beans", e); } jqmlogger.info("JMX management bean for the engine was registered"); } else { loadJmxBeans = false; jqmlogger.info("JMX management beans will not be loaded as JMX server port is null or zero"); } // Security if (System.getSecurityManager() == null) { System.setSecurityManager(new SecurityManagerPayload()); } jqmlogger.info("Security manager was registered"); // Scheduler scheduler = new CronScheduler(this); // Cleanup purgeDeadJobInstances(cnx, this.node); // Runners runningJobInstanceManager = new RunningJobInstanceManager(); runnerManager = new RunnerManager(cnx); // Resource managers initResourceManagers(cnx); // Pollers syncPollers(cnx, this.node); jqmlogger.info("All required queues are now polled"); // Internal poller (stop notifications, keep alive) intPoller = new InternalPoller(this); intPollerThread = new Thread(intPoller); intPollerThread.start(); // Kill notifications killHook = new SignalHandler(this); Runtime.getRuntime().addShutdownHook(killHook); // Done cnx.close(); cnx = null; JqmEngine.latestNodeStartedName = node.getName(); if (this.handler != null) { this.handler.onNodeStarted(); } jqmlogger.info("End of JQM engine initialization"); } }
public class class_name { void start(String nodeName, JqmEngineHandler h) { if (nodeName == null || nodeName.isEmpty()) { throw new IllegalArgumentException("nodeName cannot be null or empty"); } this.handler = h; // Set thread name - used in audits Thread.currentThread().setName("JQM engine;;" + nodeName); // First event if (this.handler != null) { this.handler.onNodeStarting(nodeName); // depends on control dependency: [if], data = [none] } // Log: we are starting... jqmlogger.info("JQM engine version " + this.getVersion() + " for node " + nodeName + " is starting"); jqmlogger.info("Java version is " + System.getProperty("java.version") + ". JVM was made by " + System.getProperty("java.vendor") + " as " + System.getProperty("java.vm.name") + " version " + System.getProperty("java.vm.version")); // JNDI first - the engine itself uses JNDI to fetch its connections! Helpers.registerJndiIfNeeded(); // Database connection DbConn cnx = Helpers.getNewDbSession(); cnx.logDatabaseInfo(jqmlogger); // Node configuration is in the database try { node = Node.select_single(cnx, "node_select_by_key", nodeName); } catch (NoResultException e) { throw new JqmRuntimeException("the specified node name [" + nodeName + "] does not exist in the configuration. Please create this node before starting it", e); } // Check if double-start long toWait = (long) (1.1 * Long.parseLong(GlobalParameter.getParameter(cnx, "internalPollingPeriodMs", "60000"))); if (node.getLastSeenAlive() != null && Calendar.getInstance().getTimeInMillis() - node.getLastSeenAlive().getTimeInMillis() <= toWait) { long r = Calendar.getInstance().getTimeInMillis() - node.getLastSeenAlive().getTimeInMillis(); throw new JqmInitErrorTooSoon("Another engine named " + nodeName + " was running less than " + r / 1000 + " seconds ago. Either stop the other node, or if it already stopped, please wait " + (toWait - r) / 1000 + " seconds"); } SimpleDateFormat ft = new SimpleDateFormat("dd/MM/YYYY hh:mm:ss"); jqmlogger.debug("The last time an engine with this name was seen was: " + (node.getLastSeenAlive() == null ? "" : ft.format(node.getLastSeenAlive().getTime()))); // Prevent very quick multiple starts by immediately setting the keep-alive QueryResult qr = cnx.runUpdate("node_update_alive_by_id", node.getId()); cnx.commit(); if (qr.nbUpdated == 0) { throw new JqmInitErrorTooSoon("Another engine named " + nodeName + " is running"); } // Only start if the node configuration seems OK Helpers.checkConfiguration(nodeName, cnx); // Log parameters Helpers.dumpParameters(cnx, node); // The handler may take any actions it wishes here - such as setting log levels, starting Jetty... if (this.handler != null) { this.handler.onNodeConfigurationRead(node); } // Remote JMX server if (node.getJmxRegistryPort() != null && node.getJmxServerPort() != null && node.getJmxRegistryPort() > 0 && node.getJmxServerPort() > 0) { JmxAgent.registerAgent(node.getJmxRegistryPort(), node.getJmxServerPort(), node.getDns()); } else { jqmlogger.info( "JMX remote listener will not be started as JMX registry port and JMX server port parameters are not both defined"); } // JMX if (node.getJmxServerPort() != null && node.getJmxServerPort() > 0) { try { MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); name = new ObjectName("com.enioka.jqm:type=Node,name=" + this.node.getName()); // depends on control dependency: [try], data = [none] mbs.registerMBean(this, name); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new JqmInitError("Could not create JMX beans", e); } // depends on control dependency: [catch], data = [none] jqmlogger.info("JMX management bean for the engine was registered"); } else { loadJmxBeans = false; jqmlogger.info("JMX management beans will not be loaded as JMX server port is null or zero"); } // Security if (System.getSecurityManager() == null) { System.setSecurityManager(new SecurityManagerPayload()); } jqmlogger.info("Security manager was registered"); // Scheduler scheduler = new CronScheduler(this); // Cleanup purgeDeadJobInstances(cnx, this.node); // Runners runningJobInstanceManager = new RunningJobInstanceManager(); runnerManager = new RunnerManager(cnx); // Resource managers initResourceManagers(cnx); // Pollers syncPollers(cnx, this.node); jqmlogger.info("All required queues are now polled"); // Internal poller (stop notifications, keep alive) intPoller = new InternalPoller(this); intPollerThread = new Thread(intPoller); intPollerThread.start(); // Kill notifications killHook = new SignalHandler(this); Runtime.getRuntime().addShutdownHook(killHook); // Done cnx.close(); cnx = null; JqmEngine.latestNodeStartedName = node.getName(); if (this.handler != null) { this.handler.onNodeStarted(); } jqmlogger.info("End of JQM engine initialization"); } }
public class class_name { public static <E extends Comparable<E>> void sort(List<E> list) { while(!Sort.isSorted(list)) { FYShuffle.shuffle(list); } } }
public class class_name { public static <E extends Comparable<E>> void sort(List<E> list) { while(!Sort.isSorted(list)) { FYShuffle.shuffle(list); // depends on control dependency: [while], data = [none] } } }
public class class_name { public int doRecordChange(FieldInfo field, int iChangeType, boolean bDisplayOption) { // Read a valid record int iErrorCode = DBConstants.NORMAL_RETURN; switch (iChangeType) { case DBConstants.LOCK_TYPE: if (this.getMainRecord() != null) iErrorCode = this.getMainRecord().handleRecordChange(this.getMainFileKeyField(false), DBConstants.FIELD_CHANGED_TYPE, bDisplayOption); // Tell the main file that I changed (so it can lock/whatever) break; // case DBConstants.AFTER_REFRESH_TYPE: case DBConstants.UPDATE_TYPE: // If refresh is set, it is possible that first add is UPDATE_TYPE if (!this.getOwner().isRefreshedRecord()) break; // No first add case DBConstants.ADD_TYPE: boolean bOldSelect = this.enableReselect(false); if (this.getMainRecord() != null) { if (this.getMainRecord().getEditMode() == DBConstants.EDIT_ADD) { if (!m_bAddNewHeaderOnAdd) return this.getOwner().getTask().setLastError("Can't add detail without a header record"); m_bMainRecordChanged = true; } iErrorCode = this.getMainRecord().handleRecordChange(this.getMainFileKeyField(false), DBConstants.FIELD_CHANGED_TYPE, bDisplayOption); // Tell the main file that I changed (so it can lock/whatever) iErrorCode = DBConstants.NORMAL_RETURN; // Ignore error on lock main! } this.enableReselect(bOldSelect); break; case DBConstants.AFTER_ADD_TYPE: // Note: This code is not necessary, since the newly added record is now a member of the new header record a refresh is not necessary! // if (m_bMainRecordChanged) // iErrorCode = this.getMainFileKeyField(true).handleFieldChanged(bDisplayOption, DBConstants.SCREEN_MOVE); // Tell the main file that I changed (so it can lock/whatever) break; default: m_bMainRecordChanged = false; break; } if (iErrorCode != DBConstants.NORMAL_RETURN) return iErrorCode; return super.doRecordChange(field, iChangeType, bDisplayOption); // Initialize the record } }
public class class_name { public int doRecordChange(FieldInfo field, int iChangeType, boolean bDisplayOption) { // Read a valid record int iErrorCode = DBConstants.NORMAL_RETURN; switch (iChangeType) { case DBConstants.LOCK_TYPE: if (this.getMainRecord() != null) iErrorCode = this.getMainRecord().handleRecordChange(this.getMainFileKeyField(false), DBConstants.FIELD_CHANGED_TYPE, bDisplayOption); // Tell the main file that I changed (so it can lock/whatever) break; // case DBConstants.AFTER_REFRESH_TYPE: case DBConstants.UPDATE_TYPE: // If refresh is set, it is possible that first add is UPDATE_TYPE if (!this.getOwner().isRefreshedRecord()) break; // No first add case DBConstants.ADD_TYPE: boolean bOldSelect = this.enableReselect(false); if (this.getMainRecord() != null) { if (this.getMainRecord().getEditMode() == DBConstants.EDIT_ADD) { if (!m_bAddNewHeaderOnAdd) return this.getOwner().getTask().setLastError("Can't add detail without a header record"); m_bMainRecordChanged = true; // depends on control dependency: [if], data = [none] } iErrorCode = this.getMainRecord().handleRecordChange(this.getMainFileKeyField(false), DBConstants.FIELD_CHANGED_TYPE, bDisplayOption); // Tell the main file that I changed (so it can lock/whatever) // depends on control dependency: [if], data = [none] iErrorCode = DBConstants.NORMAL_RETURN; // Ignore error on lock main! // depends on control dependency: [if], data = [none] } this.enableReselect(bOldSelect); break; case DBConstants.AFTER_ADD_TYPE: // Note: This code is not necessary, since the newly added record is now a member of the new header record a refresh is not necessary! // if (m_bMainRecordChanged) // iErrorCode = this.getMainFileKeyField(true).handleFieldChanged(bDisplayOption, DBConstants.SCREEN_MOVE); // Tell the main file that I changed (so it can lock/whatever) break; default: m_bMainRecordChanged = false; break; } if (iErrorCode != DBConstants.NORMAL_RETURN) return iErrorCode; return super.doRecordChange(field, iChangeType, bDisplayOption); // Initialize the record } }
public class class_name { private int getArgIndex(final int arg) { int index = (access & Opcodes.ACC_STATIC) == 0 ? 1 : 0; for (int i = 0; i < arg; i++) { index += argumentTypes[i].getSize(); } return index; } }
public class class_name { private int getArgIndex(final int arg) { int index = (access & Opcodes.ACC_STATIC) == 0 ? 1 : 0; for (int i = 0; i < arg; i++) { index += argumentTypes[i].getSize(); // depends on control dependency: [for], data = [i] } return index; } }
public class class_name { private void update() { boolean hasEvents = false; // set the newly received key and motion events. synchronized (eventLock) { hasEvents = (keyEvent.size() > 0) || (motionEvent.size() > 0); processedKeyEvent.addAll(keyEvent); keyEvent.clear(); processedMotionEvent.addAll(motionEvent); motionEvent.clear(); } previousActive = active; if ((scene != null) && (mPicker != null)) { updatePicker(getMotionEvent(), active); } context.getEventManager().sendEvent(this, IControllerEvent.class, "onEvent", this, active); // reset the set key and motion events. synchronized (eventLock) { processedKeyEvent.clear(); processedMotionEvent.clear(); } } }
public class class_name { private void update() { boolean hasEvents = false; // set the newly received key and motion events. synchronized (eventLock) { hasEvents = (keyEvent.size() > 0) || (motionEvent.size() > 0); processedKeyEvent.addAll(keyEvent); keyEvent.clear(); processedMotionEvent.addAll(motionEvent); motionEvent.clear(); } previousActive = active; if ((scene != null) && (mPicker != null)) { updatePicker(getMotionEvent(), active); // depends on control dependency: [if], data = [none] } context.getEventManager().sendEvent(this, IControllerEvent.class, "onEvent", this, active); // reset the set key and motion events. synchronized (eventLock) { processedKeyEvent.clear(); processedMotionEvent.clear(); } } }
public class class_name { private static void sanityChecks() { Config config = getInstance(Config.class); List<String> warnings = new ArrayList<>(); if (!config.isAuthenticationCookieSecure()) { String warning = "Authentication cookie has secure flag set to false. It is highly recommended to set authentication.cookie.secure to true in an production environment."; warnings.add(warning); LOG.warn(warning); } if (config.getAuthenticationCookieName().equals(Default.AUTHENTICATION_COOKIE_NAME.toString())) { String warning = "Authentication cookie name has default value. Consider changing authentication.cookie.name to an application specific value."; warnings.add(warning); LOG.warn(warning); } if (config.getAuthenticationCookieSignKey().equals(config.getApplicationSecret())) { String warning = "Authentication cookie sign key is using application secret. It is highly recommended to set a dedicated value to authentication.cookie.signkey."; warnings.add(warning); LOG.warn(warning); } if (config.getAuthenticationCookieEncryptionKey().equals(config.getApplicationSecret())) { String warning = "Authentication cookie encryption is using application secret. It is highly recommended to set a dedicated value to authentication.cookie.encryptionkey."; warnings.add(warning); LOG.warn(warning); } if (!config.isSessionCookieSecure()) { String warning = "Session cookie has secure flag set to false. It is highly recommended to set session.cookie.secure to true in an production environment."; warnings.add(warning); LOG.warn(warning); } if (config.getSessionCookieName().equals(Default.SESSION_COOKIE_NAME.toString())) { String warning = "Session cookie name has default value. Consider changing session.cookie.name to an application specific value."; warnings.add(warning); LOG.warn(warning); } if (config.getSessionCookieSignKey().equals(config.getApplicationSecret())) { String warning = "Session cookie sign key is using application secret. It is highly recommended to set a dedicated value to session.cookie.signkey."; warnings.add(warning); LOG.warn(warning); } if (config.getSessionCookieEncryptionKey().equals(config.getApplicationSecret())) { String warning = "Session cookie encryption is using application secret. It is highly recommended to set a dedicated value to session.cookie.encryptionkey."; warnings.add(warning); LOG.warn(warning); } if (config.getFlashCookieName().equals(Default.FLASH_COOKIE_NAME.toString())) { String warning = "Flash cookie name has default value. Consider changing flash.cookie.name to an application specific value."; warnings.add(warning); LOG.warn(warning); } if (config.getFlashCookieSignKey().equals(config.getApplicationSecret())) { String warning = "Flash cookie sign key is using application secret. It is highly recommended to set a dedicated value to flash.cookie.signkey."; warnings.add(warning); LOG.warn(warning); } if (config.getFlashCookieEncryptionKey().equals(config.getApplicationSecret())) { String warning = "Flash cookie encryption key is using application secret. It is highly recommended to set a dedicated value to flash.cookie.encryptionkey."; warnings.add(warning); LOG.warn(warning); } getInstance(CacheProvider.class).getCache(CacheName.APPLICATION).put(Key.MANGOOIO_WARNINGS.toString(), warnings); } }
public class class_name { private static void sanityChecks() { Config config = getInstance(Config.class); List<String> warnings = new ArrayList<>(); if (!config.isAuthenticationCookieSecure()) { String warning = "Authentication cookie has secure flag set to false. It is highly recommended to set authentication.cookie.secure to true in an production environment."; // depends on control dependency: [if], data = [none] warnings.add(warning); // depends on control dependency: [if], data = [none] LOG.warn(warning); // depends on control dependency: [if], data = [none] } if (config.getAuthenticationCookieName().equals(Default.AUTHENTICATION_COOKIE_NAME.toString())) { String warning = "Authentication cookie name has default value. Consider changing authentication.cookie.name to an application specific value."; warnings.add(warning); // depends on control dependency: [if], data = [none] LOG.warn(warning); // depends on control dependency: [if], data = [none] } if (config.getAuthenticationCookieSignKey().equals(config.getApplicationSecret())) { String warning = "Authentication cookie sign key is using application secret. It is highly recommended to set a dedicated value to authentication.cookie.signkey."; warnings.add(warning); // depends on control dependency: [if], data = [none] LOG.warn(warning); // depends on control dependency: [if], data = [none] } if (config.getAuthenticationCookieEncryptionKey().equals(config.getApplicationSecret())) { String warning = "Authentication cookie encryption is using application secret. It is highly recommended to set a dedicated value to authentication.cookie.encryptionkey."; warnings.add(warning); // depends on control dependency: [if], data = [none] LOG.warn(warning); // depends on control dependency: [if], data = [none] } if (!config.isSessionCookieSecure()) { String warning = "Session cookie has secure flag set to false. It is highly recommended to set session.cookie.secure to true in an production environment."; // depends on control dependency: [if], data = [none] warnings.add(warning); // depends on control dependency: [if], data = [none] LOG.warn(warning); // depends on control dependency: [if], data = [none] } if (config.getSessionCookieName().equals(Default.SESSION_COOKIE_NAME.toString())) { String warning = "Session cookie name has default value. Consider changing session.cookie.name to an application specific value."; warnings.add(warning); // depends on control dependency: [if], data = [none] LOG.warn(warning); // depends on control dependency: [if], data = [none] } if (config.getSessionCookieSignKey().equals(config.getApplicationSecret())) { String warning = "Session cookie sign key is using application secret. It is highly recommended to set a dedicated value to session.cookie.signkey."; warnings.add(warning); // depends on control dependency: [if], data = [none] LOG.warn(warning); // depends on control dependency: [if], data = [none] } if (config.getSessionCookieEncryptionKey().equals(config.getApplicationSecret())) { String warning = "Session cookie encryption is using application secret. It is highly recommended to set a dedicated value to session.cookie.encryptionkey."; warnings.add(warning); // depends on control dependency: [if], data = [none] LOG.warn(warning); // depends on control dependency: [if], data = [none] } if (config.getFlashCookieName().equals(Default.FLASH_COOKIE_NAME.toString())) { String warning = "Flash cookie name has default value. Consider changing flash.cookie.name to an application specific value."; warnings.add(warning); // depends on control dependency: [if], data = [none] LOG.warn(warning); // depends on control dependency: [if], data = [none] } if (config.getFlashCookieSignKey().equals(config.getApplicationSecret())) { String warning = "Flash cookie sign key is using application secret. It is highly recommended to set a dedicated value to flash.cookie.signkey."; warnings.add(warning); // depends on control dependency: [if], data = [none] LOG.warn(warning); // depends on control dependency: [if], data = [none] } if (config.getFlashCookieEncryptionKey().equals(config.getApplicationSecret())) { String warning = "Flash cookie encryption key is using application secret. It is highly recommended to set a dedicated value to flash.cookie.encryptionkey."; warnings.add(warning); // depends on control dependency: [if], data = [none] LOG.warn(warning); // depends on control dependency: [if], data = [none] } getInstance(CacheProvider.class).getCache(CacheName.APPLICATION).put(Key.MANGOOIO_WARNINGS.toString(), warnings); } }
public class class_name { public boolean crossSeam(ProjectionPoint pt1, ProjectionPoint pt2) { if (ProjectionPointImpl.isInfinite(pt1) || ProjectionPointImpl.isInfinite(pt2)) { return true; } return false; /* opposite signed X values, larger then 5000 km LOOK ???? return (pt1.getX() * pt2.getX() < 0) && (Math.abs(pt1.getX() - pt2.getX()) > 5000.0); */ } }
public class class_name { public boolean crossSeam(ProjectionPoint pt1, ProjectionPoint pt2) { if (ProjectionPointImpl.isInfinite(pt1) || ProjectionPointImpl.isInfinite(pt2)) { return true; // depends on control dependency: [if], data = [none] } return false; /* opposite signed X values, larger then 5000 km LOOK ???? return (pt1.getX() * pt2.getX() < 0) && (Math.abs(pt1.getX() - pt2.getX()) > 5000.0); */ } }
public class class_name { DecommissionStatus generateDecommissioningReport() { List<InetSocketAddress> isas = null; ArrayList<String> suffixes = null; if (isAvatar) { suffixes = new ArrayList<String>(); suffixes.add("0"); suffixes.add("1"); } try { isas = DFSUtil.getClientRpcAddresses(conf, suffixes); sort(isas); } catch (Exception e) { // catch any exception encountered other than connecting to namenodes DecommissionStatus dInfo = new DecommissionStatus(e); LOG.error(e); return dInfo; } // Outer map key is datanode. Inner map key is namenode and the value is // decom status of the datanode for the corresponding namenode Map<String, Map<String, String>> statusMap = new HashMap<String, Map<String, String>>(); // Map of exceptions encountered when connecting to namenode // key is namenode and value is exception Map<String, Exception> decommissionExceptions = new HashMap<String, Exception>(); List<String> unreportedNamenode = new ArrayList<String>(); DecommissionStatusFetcher[] threads = new DecommissionStatusFetcher[isas.size()]; for (int i = 0; i < isas.size(); i++) { threads[i] = new DecommissionStatusFetcher(isas.get(i), statusMap); threads[i].start(); } for (DecommissionStatusFetcher thread : threads) { try { thread.join(); if (thread.e != null) { // catch exceptions encountered while connecting to namenodes decommissionExceptions.put(thread.isa.toString(), thread.e); unreportedNamenode.add(thread.isa.toString()); } } catch (InterruptedException ex) { LOG.warn(ex); } } updateUnknownStatus(statusMap, unreportedNamenode); getDecommissionNodeClusterState(statusMap); return new DecommissionStatus(statusMap, isas, getDatanodeHttpPort(conf), decommissionExceptions); } }
public class class_name { DecommissionStatus generateDecommissioningReport() { List<InetSocketAddress> isas = null; ArrayList<String> suffixes = null; if (isAvatar) { suffixes = new ArrayList<String>(); // depends on control dependency: [if], data = [none] suffixes.add("0"); suffixes.add("1"); // depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none] } try { isas = DFSUtil.getClientRpcAddresses(conf, suffixes); // depends on control dependency: [try], data = [none] sort(isas); // depends on control dependency: [try], data = [none] } catch (Exception e) { // catch any exception encountered other than connecting to namenodes DecommissionStatus dInfo = new DecommissionStatus(e); LOG.error(e); return dInfo; } // depends on control dependency: [catch], data = [none] // Outer map key is datanode. Inner map key is namenode and the value is // decom status of the datanode for the corresponding namenode Map<String, Map<String, String>> statusMap = new HashMap<String, Map<String, String>>(); // Map of exceptions encountered when connecting to namenode // key is namenode and value is exception Map<String, Exception> decommissionExceptions = new HashMap<String, Exception>(); List<String> unreportedNamenode = new ArrayList<String>(); DecommissionStatusFetcher[] threads = new DecommissionStatusFetcher[isas.size()]; for (int i = 0; i < isas.size(); i++) { threads[i] = new DecommissionStatusFetcher(isas.get(i), statusMap); // depends on control dependency: [for], data = [i] threads[i].start(); // depends on control dependency: [for], data = [i] } for (DecommissionStatusFetcher thread : threads) { try { thread.join(); // depends on control dependency: [try], data = [none] if (thread.e != null) { // catch exceptions encountered while connecting to namenodes decommissionExceptions.put(thread.isa.toString(), thread.e); // depends on control dependency: [if], data = [none] unreportedNamenode.add(thread.isa.toString()); // depends on control dependency: [if], data = [none] } } catch (InterruptedException ex) { LOG.warn(ex); } // depends on control dependency: [catch], data = [none] } updateUnknownStatus(statusMap, unreportedNamenode); getDecommissionNodeClusterState(statusMap); return new DecommissionStatus(statusMap, isas, getDatanodeHttpPort(conf), decommissionExceptions); } }
public class class_name { public Form getFormAncestor( Long electronicFormIdParam, boolean includeFieldDataParam, boolean includeTableFieldsParam) { if(electronicFormIdParam == null) { return null; } //Query using the descendantId directly... StringBuffer ancestorQuery = new StringBuffer( Form.JSONMapping.DESCENDANT_IDS); ancestorQuery.append(":\""); ancestorQuery.append(electronicFormIdParam); ancestorQuery.append("\""); //Search for the Ancestor... List<Form> ancestorForms = null; if(includeFieldDataParam) { ancestorForms = this.searchAndConvertHitsToFormWithAllFields( QueryBuilders.queryStringQuery(ancestorQuery.toString()), Index.DOCUMENT, DEFAULT_OFFSET, 1, new Long[]{}); } else { ancestorForms = this.searchAndConvertHitsToFormWithNoFields( QueryBuilders.queryStringQuery(ancestorQuery.toString()), Index.DOCUMENT, DEFAULT_OFFSET, 1, new Long[]{}); } Form returnVal = null; if(ancestorForms != null && !ancestorForms.isEmpty()) { returnVal = ancestorForms.get(0); } //No result... if(returnVal == null) { return null; } //Whether table field data should be included... if(!includeTableFieldsParam) { return returnVal; } //Populate the Table Fields... this.populateTableFields( false, includeFieldDataParam, returnVal.getFormFields()); return returnVal; } }
public class class_name { public Form getFormAncestor( Long electronicFormIdParam, boolean includeFieldDataParam, boolean includeTableFieldsParam) { if(electronicFormIdParam == null) { return null; // depends on control dependency: [if], data = [none] } //Query using the descendantId directly... StringBuffer ancestorQuery = new StringBuffer( Form.JSONMapping.DESCENDANT_IDS); ancestorQuery.append(":\""); ancestorQuery.append(electronicFormIdParam); ancestorQuery.append("\""); //Search for the Ancestor... List<Form> ancestorForms = null; if(includeFieldDataParam) { ancestorForms = this.searchAndConvertHitsToFormWithAllFields( QueryBuilders.queryStringQuery(ancestorQuery.toString()), Index.DOCUMENT, DEFAULT_OFFSET, 1, new Long[]{}); // depends on control dependency: [if], data = [none] } else { ancestorForms = this.searchAndConvertHitsToFormWithNoFields( QueryBuilders.queryStringQuery(ancestorQuery.toString()), Index.DOCUMENT, DEFAULT_OFFSET, 1, new Long[]{}); // depends on control dependency: [if], data = [none] } Form returnVal = null; if(ancestorForms != null && !ancestorForms.isEmpty()) { returnVal = ancestorForms.get(0); // depends on control dependency: [if], data = [none] } //No result... if(returnVal == null) { return null; // depends on control dependency: [if], data = [none] } //Whether table field data should be included... if(!includeTableFieldsParam) { return returnVal; // depends on control dependency: [if], data = [none] } //Populate the Table Fields... this.populateTableFields( false, includeFieldDataParam, returnVal.getFormFields()); return returnVal; } }
public class class_name { @JsonCreator public static synchronized Symbol from(@JsonProperty("string") final String string) { final WeakReference<Symbol> ref = symbols.get(checkNotNull(string)); if (ref != null) { final Symbol sym = ref.get(); if (sym != null) { return sym; } } final Symbol sym = new Symbol(string); symbols.put(string, new WeakReference<Symbol>(sym)); return sym; } }
public class class_name { @JsonCreator public static synchronized Symbol from(@JsonProperty("string") final String string) { final WeakReference<Symbol> ref = symbols.get(checkNotNull(string)); if (ref != null) { final Symbol sym = ref.get(); if (sym != null) { return sym; // depends on control dependency: [if], data = [none] } } final Symbol sym = new Symbol(string); symbols.put(string, new WeakReference<Symbol>(sym)); return sym; } }
public class class_name { public static String[] splitSuffix(String suffix) { String theSuffix = suffix; String[] parts; if (StringUtils.isBlank(theSuffix)) { // no suffix given - return empty list parts = new String[0]; } else { // remove leading slash if (theSuffix.startsWith(ESCAPED_SLASH)) { theSuffix = theSuffix.substring(ESCAPED_SLASH.length()); } // remove file extension theSuffix = StringUtils.substringBeforeLast(theSuffix, "."); // split the suffix to extract the paths of the selected components parts = StringUtils.split(theSuffix, SUFFIX_PART_DELIMITER); } return parts; } }
public class class_name { public static String[] splitSuffix(String suffix) { String theSuffix = suffix; String[] parts; if (StringUtils.isBlank(theSuffix)) { // no suffix given - return empty list parts = new String[0]; // depends on control dependency: [if], data = [none] } else { // remove leading slash if (theSuffix.startsWith(ESCAPED_SLASH)) { theSuffix = theSuffix.substring(ESCAPED_SLASH.length()); // depends on control dependency: [if], data = [none] } // remove file extension theSuffix = StringUtils.substringBeforeLast(theSuffix, "."); // depends on control dependency: [if], data = [none] // split the suffix to extract the paths of the selected components parts = StringUtils.split(theSuffix, SUFFIX_PART_DELIMITER); // depends on control dependency: [if], data = [none] } return parts; } }
public class class_name { public final EObject entryRuleXAnnotation() throws RecognitionException { EObject current = null; EObject iv_ruleXAnnotation = null; try { // InternalXbaseWithAnnotations.g:68:52: (iv_ruleXAnnotation= ruleXAnnotation EOF ) // InternalXbaseWithAnnotations.g:69:2: iv_ruleXAnnotation= ruleXAnnotation EOF { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXAnnotationRule()); } pushFollow(FOLLOW_1); iv_ruleXAnnotation=ruleXAnnotation(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { current =iv_ruleXAnnotation; } match(input,EOF,FOLLOW_2); if (state.failed) return current; } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } }
public class class_name { public final EObject entryRuleXAnnotation() throws RecognitionException { EObject current = null; EObject iv_ruleXAnnotation = null; try { // InternalXbaseWithAnnotations.g:68:52: (iv_ruleXAnnotation= ruleXAnnotation EOF ) // InternalXbaseWithAnnotations.g:69:2: iv_ruleXAnnotation= ruleXAnnotation EOF { if ( state.backtracking==0 ) { newCompositeNode(grammarAccess.getXAnnotationRule()); // depends on control dependency: [if], data = [none] } pushFollow(FOLLOW_1); iv_ruleXAnnotation=ruleXAnnotation(); state._fsp--; if (state.failed) return current; if ( state.backtracking==0 ) { current =iv_ruleXAnnotation; // depends on control dependency: [if], data = [none] } match(input,EOF,FOLLOW_2); if (state.failed) return current; } } catch (RecognitionException re) { recover(input,re); appendSkippedTokens(); } finally { } return current; } }
public class class_name { public long longValue(String name, String namespace) { String s = childValue(name, namespace); if (s != null) { return Long.parseLong(s); } throw new IllegalArgumentException(this + ": content: " + name); } }
public class class_name { public long longValue(String name, String namespace) { String s = childValue(name, namespace); if (s != null) { return Long.parseLong(s); // depends on control dependency: [if], data = [(s] } throw new IllegalArgumentException(this + ": content: " + name); } }
public class class_name { @Override public void marshal( final Object obj, final Result result ) { if (_transformer == null) { super.marshal( obj, result ); } else { String xml = _simpleMarshalToString( obj ); Source source = new StreamSource( new StringReader( xml ) ); _transformer.transform( source, result ); } } }
public class class_name { @Override public void marshal( final Object obj, final Result result ) { if (_transformer == null) { super.marshal( obj, result ); // depends on control dependency: [if], data = [none] } else { String xml = _simpleMarshalToString( obj ); Source source = new StreamSource( new StringReader( xml ) ); _transformer.transform( source, result ); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void dispose() { if (disposed) throw new IllegalStateException("Already disposed"); for (Iterator iterator = children.iterator(); iterator.hasNext();) { PicoContainer child = (PicoContainer) iterator.next(); child.dispose(); } Collection<ComponentAdapter> adapters = getComponentAdapters(); for (ComponentAdapter componentAdapter : adapters) { if (componentAdapter instanceof LifecycleStrategy) { ((LifecycleStrategy) componentAdapter).dispose(getInstance(componentAdapter)); } } disposed = true; } }
public class class_name { public void dispose() { if (disposed) throw new IllegalStateException("Already disposed"); for (Iterator iterator = children.iterator(); iterator.hasNext();) { PicoContainer child = (PicoContainer) iterator.next(); child.dispose(); // depends on control dependency: [for], data = [none] } Collection<ComponentAdapter> adapters = getComponentAdapters(); for (ComponentAdapter componentAdapter : adapters) { if (componentAdapter instanceof LifecycleStrategy) { ((LifecycleStrategy) componentAdapter).dispose(getInstance(componentAdapter)); // depends on control dependency: [if], data = [none] } } disposed = true; } }
public class class_name { @Override public int countByG_A_P(long groupId, boolean active, boolean primary) { FinderPath finderPath = FINDER_PATH_COUNT_BY_G_A_P; Object[] finderArgs = new Object[] { groupId, active, primary }; Long count = (Long)finderCache.getResult(finderPath, finderArgs, this); if (count == null) { StringBundler query = new StringBundler(4); query.append(_SQL_COUNT_COMMERCEWAREHOUSE_WHERE); query.append(_FINDER_COLUMN_G_A_P_GROUPID_2); query.append(_FINDER_COLUMN_G_A_P_ACTIVE_2); query.append(_FINDER_COLUMN_G_A_P_PRIMARY_2); String sql = query.toString(); Session session = null; try { session = openSession(); Query q = session.createQuery(sql); QueryPos qPos = QueryPos.getInstance(q); qPos.add(groupId); qPos.add(active); qPos.add(primary); count = (Long)q.uniqueResult(); finderCache.putResult(finderPath, finderArgs, count); } catch (Exception e) { finderCache.removeResult(finderPath, finderArgs); throw processException(e); } finally { closeSession(session); } } return count.intValue(); } }
public class class_name { @Override public int countByG_A_P(long groupId, boolean active, boolean primary) { FinderPath finderPath = FINDER_PATH_COUNT_BY_G_A_P; Object[] finderArgs = new Object[] { groupId, active, primary }; Long count = (Long)finderCache.getResult(finderPath, finderArgs, this); if (count == null) { StringBundler query = new StringBundler(4); query.append(_SQL_COUNT_COMMERCEWAREHOUSE_WHERE); // depends on control dependency: [if], data = [none] query.append(_FINDER_COLUMN_G_A_P_GROUPID_2); // depends on control dependency: [if], data = [none] query.append(_FINDER_COLUMN_G_A_P_ACTIVE_2); // depends on control dependency: [if], data = [none] query.append(_FINDER_COLUMN_G_A_P_PRIMARY_2); // depends on control dependency: [if], data = [none] String sql = query.toString(); Session session = null; try { session = openSession(); // depends on control dependency: [try], data = [none] Query q = session.createQuery(sql); QueryPos qPos = QueryPos.getInstance(q); qPos.add(groupId); // depends on control dependency: [try], data = [none] qPos.add(active); // depends on control dependency: [try], data = [none] qPos.add(primary); // depends on control dependency: [try], data = [none] count = (Long)q.uniqueResult(); // depends on control dependency: [try], data = [none] finderCache.putResult(finderPath, finderArgs, count); // depends on control dependency: [try], data = [none] } catch (Exception e) { finderCache.removeResult(finderPath, finderArgs); throw processException(e); } // depends on control dependency: [catch], data = [none] finally { closeSession(session); } } return count.intValue(); } }
public class class_name { public void shutdown() { LOGGER.entering(); if (launcher == null) { return; } if (!isRunning()) { return; } try { launcher.shutdown(); } catch (Exception e) { // NOSONAR LOGGER.log(Level.SEVERE, e.getMessage(), e); } LOGGER.exiting(); } }
public class class_name { public void shutdown() { LOGGER.entering(); if (launcher == null) { return; // depends on control dependency: [if], data = [none] } if (!isRunning()) { return; // depends on control dependency: [if], data = [none] } try { launcher.shutdown(); // depends on control dependency: [try], data = [none] } catch (Exception e) { // NOSONAR LOGGER.log(Level.SEVERE, e.getMessage(), e); } // depends on control dependency: [catch], data = [none] LOGGER.exiting(); } }
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.getPipelineId(), PIPELINEID_BINDING); protocolMarshaller.marshall(removeTagsRequest.getTagKeys(), TAGKEYS_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.getPipelineId(), PIPELINEID_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(removeTagsRequest.getTagKeys(), TAGKEYS_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 { static <T> FieldSetter<T> getFieldSetter(final Class<T> clazz, String fieldName) { try { Field field = clazz.getDeclaredField(fieldName); return new FieldSetter<T>(field); } catch (NoSuchFieldException e) { throw new AssertionError(e); // programmer error } } }
public class class_name { static <T> FieldSetter<T> getFieldSetter(final Class<T> clazz, String fieldName) { try { Field field = clazz.getDeclaredField(fieldName); return new FieldSetter<T>(field); // depends on control dependency: [try], data = [none] } catch (NoSuchFieldException e) { throw new AssertionError(e); // programmer error } // depends on control dependency: [catch], data = [none] } }
public class class_name { private Collection<Class<?>> findScribeless(ICalendar ical) { Set<Class<?>> unregistered = new HashSet<Class<?>>(); LinkedList<ICalComponent> components = new LinkedList<ICalComponent>(); components.add(ical); while (!components.isEmpty()) { ICalComponent component = components.removeLast(); Class<? extends ICalComponent> componentClass = component.getClass(); if (componentClass != RawComponent.class && index.getComponentScribe(componentClass) == null) { unregistered.add(componentClass); } for (Map.Entry<Class<? extends ICalProperty>, List<ICalProperty>> entry : component.getProperties()) { List<ICalProperty> properties = entry.getValue(); if (properties.isEmpty()) { continue; } Class<? extends ICalProperty> clazz = entry.getKey(); if (clazz != RawProperty.class && index.getPropertyScribe(clazz) == null) { unregistered.add(clazz); } } components.addAll(component.getComponents().values()); } return unregistered; } }
public class class_name { private Collection<Class<?>> findScribeless(ICalendar ical) { Set<Class<?>> unregistered = new HashSet<Class<?>>(); LinkedList<ICalComponent> components = new LinkedList<ICalComponent>(); components.add(ical); while (!components.isEmpty()) { ICalComponent component = components.removeLast(); Class<? extends ICalComponent> componentClass = component.getClass(); if (componentClass != RawComponent.class && index.getComponentScribe(componentClass) == null) { unregistered.add(componentClass); // depends on control dependency: [if], data = [none] } for (Map.Entry<Class<? extends ICalProperty>, List<ICalProperty>> entry : component.getProperties()) { List<ICalProperty> properties = entry.getValue(); if (properties.isEmpty()) { continue; } Class<? extends ICalProperty> clazz = entry.getKey(); if (clazz != RawProperty.class && index.getPropertyScribe(clazz) == null) { unregistered.add(clazz); } } components.addAll(component.getComponents().values()); } return unregistered; } }
public class class_name { public static <T extends BioPAXElement> Set<T> searchAndCollect( BioPAXElement ele, Pattern pattern, int index, Class<T> c) { Set<T> set = new HashSet<T>(); for (Match match : search(ele, pattern)) { set.add((T) match.get(index)); } return set; } }
public class class_name { public static <T extends BioPAXElement> Set<T> searchAndCollect( BioPAXElement ele, Pattern pattern, int index, Class<T> c) { Set<T> set = new HashSet<T>(); for (Match match : search(ele, pattern)) { set.add((T) match.get(index)); // depends on control dependency: [for], data = [match] } return set; } }
public class class_name { public static <T> MonadicObservableValue<T> monadic(ObservableValue<T> o) { if(o instanceof MonadicObservableValue) { return (MonadicObservableValue<T>) o; } else { return new MonadicWrapper<>(o); } } }
public class class_name { public static <T> MonadicObservableValue<T> monadic(ObservableValue<T> o) { if(o instanceof MonadicObservableValue) { return (MonadicObservableValue<T>) o; // depends on control dependency: [if], data = [none] } else { return new MonadicWrapper<>(o); // depends on control dependency: [if], data = [none] } } }
public class class_name { public Object truncate() { Object value = navigatePath(); if (maxDepth == 0) { return value; } if (! (value instanceof JSONObject)) { return value; } else { // Truncate all levels below return truncateJSONObject((JSONObject) value, maxDepth); } } }
public class class_name { public Object truncate() { Object value = navigatePath(); if (maxDepth == 0) { return value; // depends on control dependency: [if], data = [none] } if (! (value instanceof JSONObject)) { return value; // depends on control dependency: [if], data = [none] } else { // Truncate all levels below return truncateJSONObject((JSONObject) value, maxDepth); // depends on control dependency: [if], data = [none] } } }
public class class_name { Lexeme pollFirst(){ if(this.size == 1){ Lexeme first = this.head.lexeme; this.head = null; this.tail = null; this.size--; return first; }else if(this.size > 1){ Lexeme first = this.head.lexeme; this.head = this.head.next; this.size --; return first; }else{ return null; } } }
public class class_name { Lexeme pollFirst(){ if(this.size == 1){ Lexeme first = this.head.lexeme; this.head = null; // depends on control dependency: [if], data = [none] this.tail = null; // depends on control dependency: [if], data = [none] this.size--; // depends on control dependency: [if], data = [none] return first; // depends on control dependency: [if], data = [none] }else if(this.size > 1){ Lexeme first = this.head.lexeme; this.head = this.head.next; // depends on control dependency: [if], data = [none] this.size --; // depends on control dependency: [if], data = [none] return first; // depends on control dependency: [if], data = [none] }else{ return null; // depends on control dependency: [if], data = [none] } } }
public class class_name { public boolean isClassIncluded(String className) { boolean inclusionForced = false; boolean exclusionForced = false; for (ControlEntry controlEntry : controlList) { if (controlEntry.pattern.matcher(className).matches()) { switch (controlEntry.controlMode) { case INCLUDE: inclusionForced = true; break; case EXCLUDE: exclusionForced = true; break; default: } } } if (inclusionForced) { return true; } if (exclusionForced) { return false; } return true; } }
public class class_name { public boolean isClassIncluded(String className) { boolean inclusionForced = false; boolean exclusionForced = false; for (ControlEntry controlEntry : controlList) { if (controlEntry.pattern.matcher(className).matches()) { switch (controlEntry.controlMode) { case INCLUDE: inclusionForced = true; break; case EXCLUDE: exclusionForced = true; break; default: } } } if (inclusionForced) { return true; // depends on control dependency: [if], data = [none] } if (exclusionForced) { return false; // depends on control dependency: [if], data = [none] } return true; } }
public class class_name { public static Collection<CollisionCategory> imports(Configurer configurer, MapTileCollision map) { Check.notNull(configurer); Check.notNull(map); final Collection<Xml> children = configurer.getRoot().getChildren(NODE_CATEGORY); final Collection<CollisionCategory> categories = new ArrayList<>(children.size()); for (final Xml node : children) { final CollisionCategory category = imports(node, map); categories.add(category); } return categories; } }
public class class_name { public static Collection<CollisionCategory> imports(Configurer configurer, MapTileCollision map) { Check.notNull(configurer); Check.notNull(map); final Collection<Xml> children = configurer.getRoot().getChildren(NODE_CATEGORY); final Collection<CollisionCategory> categories = new ArrayList<>(children.size()); for (final Xml node : children) { final CollisionCategory category = imports(node, map); categories.add(category); // depends on control dependency: [for], data = [none] } return categories; } }
public class class_name { public Build withPhases(BuildPhase... phases) { if (this.phases == null) { setPhases(new java.util.ArrayList<BuildPhase>(phases.length)); } for (BuildPhase ele : phases) { this.phases.add(ele); } return this; } }
public class class_name { public Build withPhases(BuildPhase... phases) { if (this.phases == null) { setPhases(new java.util.ArrayList<BuildPhase>(phases.length)); // depends on control dependency: [if], data = [none] } for (BuildPhase ele : phases) { this.phases.add(ele); // depends on control dependency: [for], data = [ele] } return this; } }
public class class_name { public static void multCols(DMatrixRMaj A , double values[] ) { if( values.length < A.numCols ) { throw new IllegalArgumentException("Not enough elements in values."); } int index = 0; for (int row = 0; row < A.numRows; row++) { for (int col = 0; col < A.numCols; col++, index++) { A.data[index] *= values[col]; } } } }
public class class_name { public static void multCols(DMatrixRMaj A , double values[] ) { if( values.length < A.numCols ) { throw new IllegalArgumentException("Not enough elements in values."); } int index = 0; for (int row = 0; row < A.numRows; row++) { for (int col = 0; col < A.numCols; col++, index++) { A.data[index] *= values[col]; // depends on control dependency: [for], data = [col] } } } }
public class class_name { public void setVelocityPropertiesMap(Map<String, Object> velocityPropertiesMap) { if (velocityPropertiesMap != null) { this.velocityProperties.putAll(velocityPropertiesMap); } } }
public class class_name { public void setVelocityPropertiesMap(Map<String, Object> velocityPropertiesMap) { if (velocityPropertiesMap != null) { this.velocityProperties.putAll(velocityPropertiesMap); // depends on control dependency: [if], data = [(velocityPropertiesMap] } } }
public class class_name { public void marshall(StartFaceSearchRequest startFaceSearchRequest, ProtocolMarshaller protocolMarshaller) { if (startFaceSearchRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(startFaceSearchRequest.getVideo(), VIDEO_BINDING); protocolMarshaller.marshall(startFaceSearchRequest.getClientRequestToken(), CLIENTREQUESTTOKEN_BINDING); protocolMarshaller.marshall(startFaceSearchRequest.getFaceMatchThreshold(), FACEMATCHTHRESHOLD_BINDING); protocolMarshaller.marshall(startFaceSearchRequest.getCollectionId(), COLLECTIONID_BINDING); protocolMarshaller.marshall(startFaceSearchRequest.getNotificationChannel(), NOTIFICATIONCHANNEL_BINDING); protocolMarshaller.marshall(startFaceSearchRequest.getJobTag(), JOBTAG_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(StartFaceSearchRequest startFaceSearchRequest, ProtocolMarshaller protocolMarshaller) { if (startFaceSearchRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(startFaceSearchRequest.getVideo(), VIDEO_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(startFaceSearchRequest.getClientRequestToken(), CLIENTREQUESTTOKEN_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(startFaceSearchRequest.getFaceMatchThreshold(), FACEMATCHTHRESHOLD_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(startFaceSearchRequest.getCollectionId(), COLLECTIONID_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(startFaceSearchRequest.getNotificationChannel(), NOTIFICATIONCHANNEL_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(startFaceSearchRequest.getJobTag(), JOBTAG_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 { @Override public JavaFileObject getOverviewPath() { if (overviewpath != null && getFileManager() instanceof StandardJavaFileManager) { StandardJavaFileManager fm = (StandardJavaFileManager) getFileManager(); return fm.getJavaFileObjects(overviewpath).iterator().next(); } return null; } }
public class class_name { @Override public JavaFileObject getOverviewPath() { if (overviewpath != null && getFileManager() instanceof StandardJavaFileManager) { StandardJavaFileManager fm = (StandardJavaFileManager) getFileManager(); return fm.getJavaFileObjects(overviewpath).iterator().next(); // depends on control dependency: [if], data = [(overviewpath] } return null; } }
public class class_name { public String getTrainingText(TagFormat format, boolean reverse) { List<TaggedToken> taggedTokens = new ArrayList<TaggedToken>(getTaggedTokens()); if (reverse) Collections.reverse(taggedTokens); StringBuffer trainingText = new StringBuffer(); for (TaggedToken token : taggedTokens) { trainingText.append(token.getText(format)); trainingText.append(" "); } return trainingText.toString().trim(); } }
public class class_name { public String getTrainingText(TagFormat format, boolean reverse) { List<TaggedToken> taggedTokens = new ArrayList<TaggedToken>(getTaggedTokens()); if (reverse) Collections.reverse(taggedTokens); StringBuffer trainingText = new StringBuffer(); for (TaggedToken token : taggedTokens) { trainingText.append(token.getText(format)); // depends on control dependency: [for], data = [token] trainingText.append(" "); // depends on control dependency: [for], data = [none] } return trainingText.toString().trim(); } }
public class class_name { @Deprecated @Draft public void closeSelector(Selector selector) { if (selectors.remove(selector)) { context.close(selector); } } }
public class class_name { @Deprecated @Draft public void closeSelector(Selector selector) { if (selectors.remove(selector)) { context.close(selector); // depends on control dependency: [if], data = [none] } } }
public class class_name { @Override protected IIOMetadataNode getStandardChromaNode() { IIOMetadataNode chroma = new IIOMetadataNode("Chroma"); // Handle ColorSpaceType (RGB/CMYK/YCbCr etc)... Entry photometricTag = ifd.getEntryById(TIFF.TAG_PHOTOMETRIC_INTERPRETATION); int photometricValue = getValueAsInt(photometricTag); // No default for this tag! int numChannelsValue = getSamplesPerPixelWithFallback(); IIOMetadataNode colorSpaceType = new IIOMetadataNode("ColorSpaceType"); chroma.appendChild(colorSpaceType); switch (photometricValue) { case TIFFBaseline.PHOTOMETRIC_WHITE_IS_ZERO: case TIFFBaseline.PHOTOMETRIC_BLACK_IS_ZERO: case TIFFBaseline.PHOTOMETRIC_MASK: // It's really a transparency mask/alpha channel, but... colorSpaceType.setAttribute("name", "GRAY"); break; case TIFFBaseline.PHOTOMETRIC_RGB: case TIFFBaseline.PHOTOMETRIC_PALETTE: colorSpaceType.setAttribute("name", "RGB"); break; case TIFFExtension.PHOTOMETRIC_YCBCR: colorSpaceType.setAttribute("name", "YCbCr"); break; case TIFFExtension.PHOTOMETRIC_CIELAB: case TIFFExtension.PHOTOMETRIC_ICCLAB: case TIFFExtension.PHOTOMETRIC_ITULAB: colorSpaceType.setAttribute("name", "Lab"); break; case TIFFExtension.PHOTOMETRIC_SEPARATED: // TODO: May be CMYK, or something else... Consult InkSet and NumberOfInks! if (numChannelsValue == 3) { colorSpaceType.setAttribute("name", "CMY"); } else { colorSpaceType.setAttribute("name", "CMYK"); } break; case TIFFCustom.PHOTOMETRIC_LOGL: // ..? case TIFFCustom.PHOTOMETRIC_LOGLUV: colorSpaceType.setAttribute("name", "Luv"); break; case TIFFCustom.PHOTOMETRIC_CFA: case TIFFCustom.PHOTOMETRIC_LINEAR_RAW: // ...or is this RGB? colorSpaceType.setAttribute("name", "3CLR"); break; default: colorSpaceType.setAttribute("name", Integer.toHexString(numChannelsValue) + "CLR"); break; } // NumChannels IIOMetadataNode numChannels = new IIOMetadataNode("NumChannels"); chroma.appendChild(numChannels); if (photometricValue == TIFFBaseline.PHOTOMETRIC_PALETTE) { numChannels.setAttribute("value", "3"); } else { numChannels.setAttribute("value", Integer.toString(numChannelsValue)); } // BlackIsZero (defaults to TRUE) IIOMetadataNode blackIsZero = new IIOMetadataNode("BlackIsZero"); chroma.appendChild(blackIsZero); switch (photometricValue) { case TIFFBaseline.PHOTOMETRIC_WHITE_IS_ZERO: blackIsZero.setAttribute("value", "FALSE"); break; default: break; } Entry colorMapTag = ifd.getEntryById(TIFF.TAG_COLOR_MAP); if (colorMapTag != null) { int[] colorMapValues = (int[]) colorMapTag.getValue(); IIOMetadataNode palette = new IIOMetadataNode("Palette"); chroma.appendChild(palette); int count = colorMapValues.length / 3; for (int i = 0; i < count; i++) { IIOMetadataNode paletteEntry = new IIOMetadataNode("PaletteEntry"); paletteEntry.setAttribute("index", Integer.toString(i)); // TODO: See TIFFImageReader createIndexColorModel, to detect 8 bit colorMap paletteEntry.setAttribute("red", Integer.toString((colorMapValues[i] >> 8) & 0xff)); paletteEntry.setAttribute("green", Integer.toString((colorMapValues[i + count] >> 8) & 0xff)); paletteEntry.setAttribute("blue", Integer.toString((colorMapValues[i + count * 2] >> 8) & 0xff)); palette.appendChild(paletteEntry); } } return chroma; } }
public class class_name { @Override protected IIOMetadataNode getStandardChromaNode() { IIOMetadataNode chroma = new IIOMetadataNode("Chroma"); // Handle ColorSpaceType (RGB/CMYK/YCbCr etc)... Entry photometricTag = ifd.getEntryById(TIFF.TAG_PHOTOMETRIC_INTERPRETATION); int photometricValue = getValueAsInt(photometricTag); // No default for this tag! int numChannelsValue = getSamplesPerPixelWithFallback(); IIOMetadataNode colorSpaceType = new IIOMetadataNode("ColorSpaceType"); chroma.appendChild(colorSpaceType); switch (photometricValue) { case TIFFBaseline.PHOTOMETRIC_WHITE_IS_ZERO: case TIFFBaseline.PHOTOMETRIC_BLACK_IS_ZERO: case TIFFBaseline.PHOTOMETRIC_MASK: // It's really a transparency mask/alpha channel, but... colorSpaceType.setAttribute("name", "GRAY"); break; case TIFFBaseline.PHOTOMETRIC_RGB: case TIFFBaseline.PHOTOMETRIC_PALETTE: colorSpaceType.setAttribute("name", "RGB"); break; case TIFFExtension.PHOTOMETRIC_YCBCR: colorSpaceType.setAttribute("name", "YCbCr"); break; case TIFFExtension.PHOTOMETRIC_CIELAB: case TIFFExtension.PHOTOMETRIC_ICCLAB: case TIFFExtension.PHOTOMETRIC_ITULAB: colorSpaceType.setAttribute("name", "Lab"); break; case TIFFExtension.PHOTOMETRIC_SEPARATED: // TODO: May be CMYK, or something else... Consult InkSet and NumberOfInks! if (numChannelsValue == 3) { colorSpaceType.setAttribute("name", "CMY"); // depends on control dependency: [if], data = [none] } else { colorSpaceType.setAttribute("name", "CMYK"); // depends on control dependency: [if], data = [none] } break; case TIFFCustom.PHOTOMETRIC_LOGL: // ..? case TIFFCustom.PHOTOMETRIC_LOGLUV: colorSpaceType.setAttribute("name", "Luv"); break; case TIFFCustom.PHOTOMETRIC_CFA: case TIFFCustom.PHOTOMETRIC_LINEAR_RAW: // ...or is this RGB? colorSpaceType.setAttribute("name", "3CLR"); break; default: colorSpaceType.setAttribute("name", Integer.toHexString(numChannelsValue) + "CLR"); break; } // NumChannels IIOMetadataNode numChannels = new IIOMetadataNode("NumChannels"); chroma.appendChild(numChannels); if (photometricValue == TIFFBaseline.PHOTOMETRIC_PALETTE) { numChannels.setAttribute("value", "3"); // depends on control dependency: [if], data = [none] } else { numChannels.setAttribute("value", Integer.toString(numChannelsValue)); // depends on control dependency: [if], data = [none] } // BlackIsZero (defaults to TRUE) IIOMetadataNode blackIsZero = new IIOMetadataNode("BlackIsZero"); chroma.appendChild(blackIsZero); switch (photometricValue) { case TIFFBaseline.PHOTOMETRIC_WHITE_IS_ZERO: blackIsZero.setAttribute("value", "FALSE"); break; default: break; } Entry colorMapTag = ifd.getEntryById(TIFF.TAG_COLOR_MAP); if (colorMapTag != null) { int[] colorMapValues = (int[]) colorMapTag.getValue(); IIOMetadataNode palette = new IIOMetadataNode("Palette"); chroma.appendChild(palette); // depends on control dependency: [if], data = [none] int count = colorMapValues.length / 3; for (int i = 0; i < count; i++) { IIOMetadataNode paletteEntry = new IIOMetadataNode("PaletteEntry"); paletteEntry.setAttribute("index", Integer.toString(i)); // depends on control dependency: [for], data = [i] // TODO: See TIFFImageReader createIndexColorModel, to detect 8 bit colorMap paletteEntry.setAttribute("red", Integer.toString((colorMapValues[i] >> 8) & 0xff)); // depends on control dependency: [for], data = [i] paletteEntry.setAttribute("green", Integer.toString((colorMapValues[i + count] >> 8) & 0xff)); // depends on control dependency: [for], data = [i] paletteEntry.setAttribute("blue", Integer.toString((colorMapValues[i + count * 2] >> 8) & 0xff)); // depends on control dependency: [for], data = [i] palette.appendChild(paletteEntry); // depends on control dependency: [for], data = [none] } } return chroma; } }
public class class_name { public void marshall(PullRequestTarget pullRequestTarget, ProtocolMarshaller protocolMarshaller) { if (pullRequestTarget == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(pullRequestTarget.getRepositoryName(), REPOSITORYNAME_BINDING); protocolMarshaller.marshall(pullRequestTarget.getSourceReference(), SOURCEREFERENCE_BINDING); protocolMarshaller.marshall(pullRequestTarget.getDestinationReference(), DESTINATIONREFERENCE_BINDING); protocolMarshaller.marshall(pullRequestTarget.getDestinationCommit(), DESTINATIONCOMMIT_BINDING); protocolMarshaller.marshall(pullRequestTarget.getSourceCommit(), SOURCECOMMIT_BINDING); protocolMarshaller.marshall(pullRequestTarget.getMergeBase(), MERGEBASE_BINDING); protocolMarshaller.marshall(pullRequestTarget.getMergeMetadata(), MERGEMETADATA_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(PullRequestTarget pullRequestTarget, ProtocolMarshaller protocolMarshaller) { if (pullRequestTarget == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(pullRequestTarget.getRepositoryName(), REPOSITORYNAME_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(pullRequestTarget.getSourceReference(), SOURCEREFERENCE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(pullRequestTarget.getDestinationReference(), DESTINATIONREFERENCE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(pullRequestTarget.getDestinationCommit(), DESTINATIONCOMMIT_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(pullRequestTarget.getSourceCommit(), SOURCECOMMIT_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(pullRequestTarget.getMergeBase(), MERGEBASE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(pullRequestTarget.getMergeMetadata(), MERGEMETADATA_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 Properties parseXML(Document doc, String sectionName) { int found = -1; Properties results = new Properties(); NodeList config = null; if (sectionName == null){ config = doc.getElementsByTagName("default-config"); found = 0; } else { config = doc.getElementsByTagName("named-config"); if(config != null && config.getLength() > 0) { for (int i = 0; i < config.getLength(); i++) { Node node = config.item(i); if(node.getNodeType() == Node.ELEMENT_NODE ){ NamedNodeMap attributes = node.getAttributes(); if (attributes != null && attributes.getLength() > 0){ Node name = attributes.getNamedItem("name"); if (name.getNodeValue().equalsIgnoreCase(sectionName)){ found = i; break; } } } } } if (found == -1){ config = null; logger.warn("Did not find "+sectionName+" section in config file. Reverting to defaults."); } } if(config != null && config.getLength() > 0) { Node node = config.item(found); if(node.getNodeType() == Node.ELEMENT_NODE){ Element elementEntry = (Element)node; NodeList childNodeList = elementEntry.getChildNodes(); for (int j = 0; j < childNodeList.getLength(); j++) { Node node_j = childNodeList.item(j); if (node_j.getNodeType() == Node.ELEMENT_NODE) { Element piece = (Element) node_j; NamedNodeMap attributes = piece.getAttributes(); if (attributes != null && attributes.getLength() > 0){ results.put(attributes.item(0).getNodeValue(), piece.getTextContent()); } } } } } return results; } }
public class class_name { private Properties parseXML(Document doc, String sectionName) { int found = -1; Properties results = new Properties(); NodeList config = null; if (sectionName == null){ config = doc.getElementsByTagName("default-config"); // depends on control dependency: [if], data = [none] found = 0; // depends on control dependency: [if], data = [none] } else { config = doc.getElementsByTagName("named-config"); // depends on control dependency: [if], data = [none] if(config != null && config.getLength() > 0) { for (int i = 0; i < config.getLength(); i++) { Node node = config.item(i); if(node.getNodeType() == Node.ELEMENT_NODE ){ NamedNodeMap attributes = node.getAttributes(); if (attributes != null && attributes.getLength() > 0){ Node name = attributes.getNamedItem("name"); if (name.getNodeValue().equalsIgnoreCase(sectionName)){ found = i; // depends on control dependency: [if], data = [none] break; } } } } } if (found == -1){ config = null; // depends on control dependency: [if], data = [none] logger.warn("Did not find "+sectionName+" section in config file. Reverting to defaults."); // depends on control dependency: [if], data = [none] } } if(config != null && config.getLength() > 0) { Node node = config.item(found); if(node.getNodeType() == Node.ELEMENT_NODE){ Element elementEntry = (Element)node; NodeList childNodeList = elementEntry.getChildNodes(); for (int j = 0; j < childNodeList.getLength(); j++) { Node node_j = childNodeList.item(j); if (node_j.getNodeType() == Node.ELEMENT_NODE) { Element piece = (Element) node_j; NamedNodeMap attributes = piece.getAttributes(); if (attributes != null && attributes.getLength() > 0){ results.put(attributes.item(0).getNodeValue(), piece.getTextContent()); // depends on control dependency: [if], data = [(attributes] } } } } } return results; } }
public class class_name { public static void compress(String srcFilePath, String destFilePath) throws Exception { File src = new File(srcFilePath); if (!src.exists()) { throw new RuntimeException(srcFilePath + "不存在"); } File zipFile = new File(destFilePath); ZipOutputStream zos=null; try { FileOutputStream fos = new FileOutputStream(zipFile); CheckedOutputStream cos = new CheckedOutputStream(fos, new CRC32()); zos = new ZipOutputStream(cos); String baseDir = ""; compressbyType(src, zos, baseDir); }finally { if(zos!=null) { zos.close(); } } } }
public class class_name { public static void compress(String srcFilePath, String destFilePath) throws Exception { File src = new File(srcFilePath); if (!src.exists()) { throw new RuntimeException(srcFilePath + "不存在"); } File zipFile = new File(destFilePath); ZipOutputStream zos=null; try { FileOutputStream fos = new FileOutputStream(zipFile); CheckedOutputStream cos = new CheckedOutputStream(fos, new CRC32()); zos = new ZipOutputStream(cos); String baseDir = ""; compressbyType(src, zos, baseDir); }finally { if(zos!=null) { zos.close(); // depends on control dependency: [if], data = [none] } } } }
public class class_name { public void postArtifact(final Artifact artifact, final String user, final String password) throws GrapesCommunicationException, AuthenticationException { final Client client = getClient(user, password); final WebResource resource = client.resource(serverURL).path(RequestUtils.artifactResourcePath()); final ClientResponse response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, artifact); client.destroy(); if(ClientResponse.Status.CREATED.getStatusCode() != response.getStatus()){ final String message = "Failed to POST artifact"; if(LOG.isErrorEnabled()) { LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus())); } throw new GrapesCommunicationException(message, response.getStatus()); } } }
public class class_name { public void postArtifact(final Artifact artifact, final String user, final String password) throws GrapesCommunicationException, AuthenticationException { final Client client = getClient(user, password); final WebResource resource = client.resource(serverURL).path(RequestUtils.artifactResourcePath()); final ClientResponse response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, artifact); client.destroy(); if(ClientResponse.Status.CREATED.getStatusCode() != response.getStatus()){ final String message = "Failed to POST artifact"; if(LOG.isErrorEnabled()) { LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus())); // depends on control dependency: [if], data = [none] } throw new GrapesCommunicationException(message, response.getStatus()); } } }
public class class_name { private void processWay(Way way) { // The way has at least 2 way nodes if (way.getWayNodes().size() < 2) { LOGGER.finer("Found way with fewer than 2 way nodes. Way id: " + way.getId()); return; } // Geo tagging if (this.configuration.isGeoTags()) { this.geoTagger.storeAdministrativeBoundaries(way); } // Retrieve way nodes boolean validWay = true; LatLong[] wayNodes = new LatLong[way.getWayNodes().size()]; int i = 0; for (WayNode wayNode : way.getWayNodes()) { wayNodes[i] = findNodeByID(wayNode.getNodeId()); if (wayNodes[i] == null) { validWay = false; LOGGER.finer("Unknown way node " + wayNode.getNodeId() + " in way " + way.getId()); break; } i++; } // For a valid way all way nodes must be existent in the input data if (!validWay) { return; } //Calculate center of way dependent on its form LatLong centroid; if (way.isClosed() && way.getWayNodes().size() >= MIN_NODES_POLYGON) { // Closed way // Convert the way to a JTS polygon Coordinate[] coordinates = new Coordinate[wayNodes.length]; for (int j = 0; j < wayNodes.length; j++) { LatLong wayNode = wayNodes[j]; coordinates[j] = new Coordinate(wayNode.longitude, wayNode.latitude); } Polygon polygon = GEOMETRY_FACTORY.createPolygon(GEOMETRY_FACTORY.createLinearRing(coordinates), null); if (!polygon.isValid()) { return; } // Compute the centroid of the polygon Point center = polygon.getCentroid(); if (center == null) { return; } centroid = new LatLong(center.getY(), center.getX()); } else { // Non-closed way centroid = wayNodes[(wayNodes.length - 1) / 2]; } // Process the way processEntity(way, centroid.getLatitude(), centroid.getLongitude()); } }
public class class_name { private void processWay(Way way) { // The way has at least 2 way nodes if (way.getWayNodes().size() < 2) { LOGGER.finer("Found way with fewer than 2 way nodes. Way id: " + way.getId()); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } // Geo tagging if (this.configuration.isGeoTags()) { this.geoTagger.storeAdministrativeBoundaries(way); // depends on control dependency: [if], data = [none] } // Retrieve way nodes boolean validWay = true; LatLong[] wayNodes = new LatLong[way.getWayNodes().size()]; int i = 0; for (WayNode wayNode : way.getWayNodes()) { wayNodes[i] = findNodeByID(wayNode.getNodeId()); // depends on control dependency: [for], data = [wayNode] if (wayNodes[i] == null) { validWay = false; // depends on control dependency: [if], data = [none] LOGGER.finer("Unknown way node " + wayNode.getNodeId() + " in way " + way.getId()); // depends on control dependency: [if], data = [none] break; } i++; // depends on control dependency: [for], data = [none] } // For a valid way all way nodes must be existent in the input data if (!validWay) { return; // depends on control dependency: [if], data = [none] } //Calculate center of way dependent on its form LatLong centroid; if (way.isClosed() && way.getWayNodes().size() >= MIN_NODES_POLYGON) { // Closed way // Convert the way to a JTS polygon Coordinate[] coordinates = new Coordinate[wayNodes.length]; for (int j = 0; j < wayNodes.length; j++) { LatLong wayNode = wayNodes[j]; coordinates[j] = new Coordinate(wayNode.longitude, wayNode.latitude); // depends on control dependency: [for], data = [j] } Polygon polygon = GEOMETRY_FACTORY.createPolygon(GEOMETRY_FACTORY.createLinearRing(coordinates), null); if (!polygon.isValid()) { return; // depends on control dependency: [if], data = [none] } // Compute the centroid of the polygon Point center = polygon.getCentroid(); if (center == null) { return; // depends on control dependency: [if], data = [none] } centroid = new LatLong(center.getY(), center.getX()); // depends on control dependency: [if], data = [none] } else { // Non-closed way centroid = wayNodes[(wayNodes.length - 1) / 2]; // depends on control dependency: [if], data = [none] } // Process the way processEntity(way, centroid.getLatitude(), centroid.getLongitude()); } }
public class class_name { public synchronized Vector getExtentClasses() { if (extentClassNames.size() != extentClasses.size()) { extentClasses.clear(); for (Iterator iter = extentClassNames.iterator(); iter.hasNext();) { String classname = (String) iter.next(); Class extentClass; try { extentClass = ClassHelper.getClass(classname); } catch (ClassNotFoundException e) { throw new MetadataException( "Unable to load class [" + classname + "]. Make sure it is available on the classpath.", e); } extentClasses.add(extentClass); } } return extentClasses; } }
public class class_name { public synchronized Vector getExtentClasses() { if (extentClassNames.size() != extentClasses.size()) { extentClasses.clear(); // depends on control dependency: [if], data = [none] for (Iterator iter = extentClassNames.iterator(); iter.hasNext();) { String classname = (String) iter.next(); Class extentClass; try { extentClass = ClassHelper.getClass(classname); // depends on control dependency: [try], data = [none] } catch (ClassNotFoundException e) { throw new MetadataException( "Unable to load class [" + classname + "]. Make sure it is available on the classpath.", e); } // depends on control dependency: [catch], data = [none] extentClasses.add(extentClass); // depends on control dependency: [for], data = [none] } } return extentClasses; } }
public class class_name { public void setSuccessfulSet(java.util.Collection<EventDetails> successfulSet) { if (successfulSet == null) { this.successfulSet = null; return; } this.successfulSet = new java.util.ArrayList<EventDetails>(successfulSet); } }
public class class_name { public void setSuccessfulSet(java.util.Collection<EventDetails> successfulSet) { if (successfulSet == null) { this.successfulSet = null; // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } this.successfulSet = new java.util.ArrayList<EventDetails>(successfulSet); } }
public class class_name { AbstractFunction1<Connection, BoxedUnit> connectionFunction(final ConnectionRunnable block) { return new AbstractFunction1<Connection, BoxedUnit>() { public BoxedUnit apply(Connection connection) { try { block.run(connection); return BoxedUnit.UNIT; } catch (java.sql.SQLException e) { throw new RuntimeException("Connection runnable failed", e); } } }; } }
public class class_name { AbstractFunction1<Connection, BoxedUnit> connectionFunction(final ConnectionRunnable block) { return new AbstractFunction1<Connection, BoxedUnit>() { public BoxedUnit apply(Connection connection) { try { block.run(connection); // depends on control dependency: [try], data = [none] return BoxedUnit.UNIT; // depends on control dependency: [try], data = [none] } catch (java.sql.SQLException e) { throw new RuntimeException("Connection runnable failed", e); } // depends on control dependency: [catch], data = [none] } }; } }