code
stringlengths
10
174k
nl
stringlengths
3
129k
@CallSuper protected void onCompletion(){ Toro.sInstance.onPlaybackCompletion(this.player); }
Complete the playback
private void updateZoningMap(List<NetworkFCZoneInfo> lastReferenceZoneInfo,URI exportGroupURI,List<URI> exportMaskURIs){ List<URI> emURIs=new ArrayList<URI>(); if (exportMaskURIs == null || exportMaskURIs.isEmpty()) { ExportGroup exportGroup=_dbClient.queryObject(ExportGroup.class,exportGroupURI); List<ExportMask> exportMasks=ExportMaskUtils.getExportMasks(_dbClient,exportGroup); if (exportGroup != null && !exportMasks.isEmpty()) { for ( ExportMask mask : exportMasks) { emURIs.add(mask.getId()); } } } else { emURIs.addAll(exportMaskURIs); } for ( URI emURI : emURIs) { ExportMask exportMask=_dbClient.queryObject(ExportMask.class,emURI); if (exportMask != null && !exportMask.getInactive() && !exportMask.fetchDeviceDataMapEntry(ExportMask.DeviceDataMapKeys.ImmutableZoningMap.name()).contains(Boolean.TRUE.toString())) { for ( NetworkFCZoneInfo zoneInfo : lastReferenceZoneInfo) { StringSetMap existingZoningMap=exportMask.getZoningMap(); if (exportMask.getVolumes() == null) { continue; } Set<String> exportMaskVolumes=exportMask.getVolumes().keySet(); if (existingZoningMap != null && zoneInfo.getVolumeId() != null && exportMaskVolumes.contains(zoneInfo.getVolumeId().toString()) && zoneInfo.getEndPoints().size() == 2) { Initiator initiator=NetworkUtil.findInitiatorInDB(zoneInfo.getEndPoints().get(0),_dbClient); List<StoragePort> storagePorts=NetworkUtil.findStoragePortsInDB(zoneInfo.getEndPoints().get(1),_dbClient); for ( StoragePort storagePort : storagePorts) { if (initiator != null && storagePort != null) { for ( String initiatorId : existingZoningMap.keySet()) { if (initiator.getId().toString().equals(initiatorId)) { StringSet ports=existingZoningMap.get(initiatorId); if (ports != null) { if (ports.contains(storagePort.getId().toString())) { ports.remove(storagePort.getId().toString()); if (ports.isEmpty()) { exportMask.removeZoningMapEntry(initiatorId); _log.info("Removing zoning map entry for initiator {}, in exportmask {}",initiatorId,emURI); } else { exportMask.addZoningMapEntry(initiatorId,ports); _log.info("Removing storagePort " + storagePort.getId() + " from zoning map for initiator "+ initiatorId+ " in export mask "+ emURI); } } } } } } } } _dbClient.persistObject(exportMask); } } } }
This method updates zoning map. This will mostly be called when volume(s) is/are removed from the ExportMask which is shared across two/more varrays and varrays do not have same storage ports which results in creating zoning based on the ports in the varray. lastReferenceZoneInfo contains the zones that were removed from the device, according to this if there is initiator in the zoningMap with just one storage port for which zone is removed then that entry is removed from the zoningMap. If initiator has more than one storage port in the zoningMap for the initiator then only storage port for which zone is removed is removed from the zoning map. ExportMasks with ImmutableZoningMap set are skipped.
private static void copySingleProjectToLocation(String projectName,Path target) throws RuntimeException { File fromFile=new File(new File("probands/" + projectName + "/").getAbsolutePath()); if (fromFile.exists() == false || fromFile.isDirectory() == false) { throw new RuntimeException("can't obtain proper proband " + projectName); } Path toPath=target.resolve(projectName); File toFile=toPath.toFile(); if (toFile.exists()) { if (!toFile.isDirectory()) { throw new RuntimeException("desired location is occupied " + toPath.toAbsolutePath().toString()); } LOGGER.info("re using existing locaiton " + toPath.toAbsolutePath().toString()); } else { if (!toFile.mkdirs()) { throw new RuntimeException("can't create directory at desired location " + toPath.toAbsolutePath().toString()); } } try { FileCopier.copy(fromFile.toPath(),toPath); } catch ( IOException ieo) { throw new RuntimeException("errros copying probands to the external location",ieo); } }
Copies given folder structure form resources to the given location in the file system. Symlinks are not followed.
public List<FeedItem> loadAllDeepFromCursor(Cursor cursor){ int count=cursor.getCount(); List<FeedItem> list=new ArrayList<FeedItem>(count); if (cursor.moveToFirst()) { if (identityScope != null) { identityScope.lock(); identityScope.reserveRoom(count); } try { do { list.add(loadCurrentDeep(cursor,false)); } while (cursor.moveToNext()); } finally { if (identityScope != null) { identityScope.unlock(); } } } return list; }
Reads all available rows from the given cursor and returns a list of new ImageTO objects.
public void testSSLPubSub() throws Exception { MqttAndroidClient mqttClient=null; IMqttToken connectToken=null; IMqttToken disconnectToken=null; IMqttToken subToken=null; IMqttDeliveryToken pubToken=null; try { mqttClient=new MqttAndroidClient(mContext,mqttSSLServerURI,"testSSLPubSub"); MqttConnectOptions options=new MqttConnectOptions(); options.setSocketFactory(mqttClient.getSSLSocketFactory(this.getContext().getAssets().open("test.bks"),keyStorePwd)); MqttV3Receiver mqttV3Receiver=new MqttV3Receiver(mqttClient,null); mqttClient.setCallback(mqttV3Receiver); connectToken=mqttClient.connect(options); connectToken.waitForCompletion(waitForCompletionTime); String[] topicNames=new String[]{"testSSLPubSub" + "/Topic"}; int[] topicQos={0}; MqttMessage mqttMessage=new MqttMessage(("message for testSSLPubSub").getBytes()); byte[] message=mqttMessage.getPayload(); subToken=mqttClient.subscribe(topicNames,topicQos,null,null); subToken.waitForCompletion(waitForCompletionTime); pubToken=mqttClient.publish(topicNames[0],message,0,false,null,null); pubToken.waitForCompletion(waitForCompletionTime); TimeUnit.MILLISECONDS.sleep(6000); boolean ok=mqttV3Receiver.validateReceipt(topicNames[0],0,message); if (!ok) { fail("Receive failed"); } } catch ( Exception exception) { fail("Failed:" + "testSSLPubSub" + " exception="+ exception); } finally { disconnectToken=mqttClient.disconnect(null,null); disconnectToken.waitForCompletion(waitForCompletionTime); if (mqttClient != null) { mqttClient.close(); } } }
An SSL connection with server cert authentication, simple pub/sub of an message
public boolean reverseAccrualIt(){ m_processMsg=ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_BEFORE_REVERSEACCRUAL); if (m_processMsg != null) return false; boolean ok_reverse=(reverseAccrualIt(getGL_JournalBatch_ID()) != null); if (!ok_reverse) return false; m_processMsg=ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_AFTER_REVERSEACCRUAL); if (m_processMsg != null) return false; return ok_reverse; }
Reverse Accrual (sane batch). Flip Dr/Cr - Use Today's date
public static void flushMethod(){ try { ((LocalRegion)region).getDiskRegion().forceFlush(); } catch ( Exception ex) { ex.printStackTrace(); } }
Force flush the data to disk
public Property basicGetProperty(){ return property; }
<!-- begin-user-doc --> <!-- end-user-doc -->
public int currentSegment(float[] coords){ if (isDone()) { throw new NoSuchElementException("line iterator out of bounds"); } int type; if (index == 0) { coords[0]=(float)line.getX1(); coords[1]=(float)line.getY1(); type=SEG_MOVETO; } else { coords[0]=(float)line.getX2(); coords[1]=(float)line.getY2(); type=SEG_LINETO; } if (affine != null) { affine.transform(coords,0,coords,0,1); } return type; }
Returns the coordinates and type of the current path segment in the iteration. The return value is the path segment type: SEG_MOVETO, SEG_LINETO, SEG_QUADTO, SEG_CUBICTO, or SEG_CLOSE. A float array of length 6 must be passed in and may be used to store the coordinates of the point(s). Each point is stored as a pair of float x,y coordinates. SEG_MOVETO and SEG_LINETO types will return one point, SEG_QUADTO will return two points, SEG_CUBICTO will return 3 points and SEG_CLOSE will not return any points.
private boolean zzRefill() throws java.io.IOException { if (zzStartRead > 0) { System.arraycopy(zzBuffer,zzStartRead,zzBuffer,0,zzEndRead - zzStartRead); zzEndRead-=zzStartRead; zzCurrentPos-=zzStartRead; zzMarkedPos-=zzStartRead; zzStartRead=0; } if (zzCurrentPos >= zzBuffer.length) { char newBuffer[]=new char[zzCurrentPos * 2]; System.arraycopy(zzBuffer,0,newBuffer,0,zzBuffer.length); zzBuffer=newBuffer; } int numRead=zzReader.read(zzBuffer,zzEndRead,zzBuffer.length - zzEndRead); if (numRead > 0) { zzEndRead+=numRead; return false; } if (numRead == 0) { int c=zzReader.read(); if (c == -1) { return true; } else { zzBuffer[zzEndRead++]=(char)c; return false; } } return true; }
Refills the input buffer.
public void treeNodesRemoved(TreeModelEvent e){ if (e != null) { int changedIndexs[]; int maxCounter; TreePath parentPath=SwingUtilities2.getTreePath(e,getModel()); FHTreeStateNode changedParentNode=getNodeForPath(parentPath,false,false); changedIndexs=e.getChildIndices(); if (changedParentNode != null && changedIndexs != null && (maxCounter=changedIndexs.length) > 0) { Object[] children=e.getChildren(); boolean isVisible=(changedParentNode.isVisible() && changedParentNode.isExpanded()); for (int counter=maxCounter - 1; counter >= 0; counter--) { changedParentNode.removeChildAtModelIndex(changedIndexs[counter],isVisible); } if (isVisible) { if (treeSelectionModel != null) treeSelectionModel.resetRowSelection(); if (treeModel.getChildCount(changedParentNode.getUserObject()) == 0 && changedParentNode.isLeaf()) { changedParentNode.collapse(false); } visibleNodesChanged(); } else if (changedParentNode.isVisible()) visibleNodesChanged(); } } }
<p>Invoked after nodes have been removed from the tree. Note that if a subtree is removed from the tree, this method may only be invoked once for the root of the removed subtree, not once for each individual set of siblings removed.</p> <p>e.path() returns the former parent of the deleted nodes.</p> <p>e.childIndices() returns the indices the nodes had before they were deleted in ascending order.</p>
public void onChanging(InputEvent evt){ if (!evt.isChangingBySelectBack()) { refresh(evt.getValue()); } }
Event handler responsible to reducing number of items Method is invoked each time something is typed in the combobox
static Bundle loadBundle(BundleContext context) throws BundleException, IOException { for ( Bundle bundle : context.getBundles()) { if (OsgiExecImp.BUNDLE_SYMBOLIC_NAME.equals(bundle.getSymbolicName())) { return bundle; } } URLClassLoader classLoader=(URLClassLoader)OsgiExecImp.class.getClassLoader(); for ( URL url : classLoader.getURLs()) { String name=url.getFile(); if (name != null) { if (name.contains("/goomph")) { return context.installBundle(FileMisc.asUrl(new File(name))); } else if (name.contains("/" + JavaExecWinFriendly.LONG_CLASSPATH_JAR_PREFIX)) { String content=ZipMisc.read(new File(name),"META-INF/MANIFEST.MF"); try (InputStream input=new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8))){ Manifest manifest=new Manifest(input); String classpath=manifest.getMainAttributes().getValue("Class-Path"); for ( String piece : classpath.split(" ")) { if (piece.contains("/goomph")) { return context.installBundle(piece); } } } } } } throw new IllegalArgumentException("Unable to find goomph jar"); }
Returns this bundle within the given OSGi context, initializing it if necessary.
public static void sort(short[] array,int start,int end){ DualPivotQuicksort.sort(array,start,end); }
Sorts the specified range in the array in ascending numerical order.
public static IProject createSimpleProject(String projectName,String... natureIds) throws CoreException { IProject project=ResourcesPlugin.getWorkspace().getRoot().getProject(projectName); if (project.exists()) { project.delete(true,true,npm()); } project.create(npm()); project.open(npm()); if (natureIds != null) { IProjectDescription desc=project.getDescription(); desc.setNatureIds(natureIds); project.setDescription(desc,npm()); } return project; }
Creates a simple project.
public static void llenarInformacionError(InformacionError ie,int codigoError,Exception e){ llenarInformacionError(ie,codigoError + "",e); }
introducir la informacion de la excepcion en ie
public CustomShortcutSet(@NotNull Shortcut... shortcuts){ myShortcuts=shortcuts.length == 0 ? Shortcut.EMPTY_ARRAY : shortcuts.clone(); }
Creates <code>CustomShortcutSet</code> which contains specified keyboard and mouse shortcuts.
public static void join(byte[] baggageBytes){ join(DetachedBaggage.deserialize(baggageBytes)); }
Deserialize the provided baggage and merge its contents into the current thread's baggage.
public void reverse(){ short tmp; int limit=size / 2; int j=size - 1; short[] theElements=elements; for (int i=0; i < limit; ) { tmp=theElements[i]; theElements[i++]=theElements[j]; theElements[j--]=tmp; } }
Reverses the elements of the receiver. Last becomes first, second last becomes second first, and so on.
public void openDriver(SurfaceHolder holder) throws IOException { if (camera == null) { camera=Camera.open(); if (camera == null) { throw new IOException(); } camera.setPreviewDisplay(holder); if (!initialized) { initialized=true; configManager.initFromCameraParameters(camera); } configManager.setDesiredCameraParameters(camera); FlashlightManager.enableFlashlight(); } }
Opens the camera driver and initializes the hardware parameters.
public font addElement(String hashcode,String element){ addElementToRegistry(hashcode,element); return (this); }
Adds an Element to the element.
public void nextGeneration(){ generation++; }
Increase the generation number by one.
public static void main(String[] args) throws IOException { InputStream is=new BufferedInputStream(new FileInputStream(args[0])); try { if (BlockCompressedInputStream.isValidFile(is)) { is=new BlockCompressedInputStream(is); System.out.println(tbiIndexToUniqueString(is)); } else { System.out.println(bamIndexToUniqueString(is)); } } finally { is.close(); } }
prints the index file in string form
protected AbstractMatrix3D vDice(int axis0,int axis1,int axis2){ int d=3; if (axis0 < 0 || axis0 >= d || axis1 < 0 || axis1 >= d || axis2 < 0 || axis2 >= d || axis0 == axis1 || axis0 == axis2 || axis1 == axis2) { throw new IllegalArgumentException("Illegal Axes: " + axis0 + ", "+ axis1+ ", "+ axis2); } int[] shape=shape(); this.slices=shape[axis0]; this.rows=shape[axis1]; this.columns=shape[axis2]; int[] strides=new int[3]; strides[0]=this.sliceStride; strides[1]=this.rowStride; strides[2]=this.columnStride; this.sliceStride=strides[axis0]; this.rowStride=strides[axis1]; this.columnStride=strides[axis2]; this.isNoView=false; return this; }
Self modifying version of viewDice().
@SuppressWarnings({"unchecked"}) public static <T>OperatorSwitchThenUnsubscribe<T> instance(){ return (OperatorSwitchThenUnsubscribe<T>)Holder.INSTANCE; }
Returns a singleton instance of the operator for non delayed.
public int ping() throws RecoverPointException { String mgmtIPAddress=_endpoint.toASCIIString(); if (null == mgmtIPAddress) { throw RecoverPointException.exceptions.noRecoverPointEndpoint(); } try { logger.info("RecoverPoint service: Checking RP access for endpoint: " + _endpoint.toASCIIString()); functionalAPI.getAccountSettings(); logger.info("Successful ping for Mgmt IP: " + mgmtIPAddress); return 0; } catch ( Exception e) { throw RecoverPointException.exceptions.failedToPingMgmtIP(mgmtIPAddress,getCause(e)); } }
tests credentials to ensure they are correct, and that the RP site is up and running
public static boolean isChildRecordFoundError(Exception e){ if (DB.isPostgreSQL()) return isSQLState(e,"23503"); return isErrorCode(e,2292); }
Check if "child record found" exception (aka ORA-02292)
public static int readInts(final File f,final LongIndex a,final long offset,final long addend) throws IOException { return readInts(f,0,(int)f.length() / 4,a,offset,addend); }
Read an array of longs from a file.
String writeToNamedTmpFile(String filename,String... data) throws IOException { return writeToNamedTmpFile(filename,Joiner.on('\n').join(data).getBytes(UTF_8)); }
Writes the data to a named temporary file and then returns a path to the file.
private Uri insertWifiMeasurement(final Uri baseUri,final ContentValues values){ if (values.containsKey(Schema.COL_BEGIN_POSITION_ID) && values.containsKey(Schema.COL_END_POSITION_ID) && values.containsKey(Schema.COL_TIMESTAMP)) { final long rowId=mDbHelper.getWritableDatabase().insert(Schema.TBL_WIFIS,null,values); if (rowId > 0) { final Uri wifiUri=ContentUris.withAppendedId(baseUri,rowId); getContext().getContentResolver().notifyChange(ContentProvider.CONTENT_URI_WIFI,null); return wifiUri; } } else { throw new IllegalArgumentException("mandatory column missing"); } return null; }
Inserts a wifi measurement
public void writeURL(String url) throws IOException { writeUTF('U',url); }
Writes a URL to the stream.
public boolean only_stack_locals(){ return soot.PhaseOptions.getBoolean(options,"only-stack-locals"); }
Only Stack Locals -- . Only propagate copies through locals that represent stack locations in the original bytecode.
public static void convertUTMCoordinatesToGeographic(int zone,String hemisphere,DoubleBuffer buffer){ if (zone < 1 || zone > 60) { String message=Logging.getMessage("generic.ZoneIsInvalid",zone); Logging.logger().severe(message); throw new IllegalArgumentException(message); } if (!AVKey.NORTH.equals(hemisphere) && !AVKey.SOUTH.equals(hemisphere)) { String message=Logging.getMessage("generic.HemisphereIsInvalid",hemisphere); Logging.logger().severe(message); throw new IllegalArgumentException(message); } if (buffer == null) { String message=Logging.getMessage("nullValue.BufferIsNull"); Logging.logger().severe(message); throw new IllegalArgumentException(message); } if ((buffer.remaining() % 2) != 0) { String message=Logging.getMessage("generic.BufferSize",buffer.remaining()); Logging.logger().severe(message); throw new IllegalArgumentException(message); } while (buffer.hasRemaining()) { buffer.mark(); double easting=buffer.get(); double northing=buffer.get(); LatLon location=UTMCoord.locationFromUTMCoord(zone,hemisphere,easting,northing,null); buffer.reset(); buffer.put(location.getLongitude().degrees); buffer.put(location.getLatitude().degrees); } }
Converts the specified buffer of UTM tuples to geographic coordinates, according to the specified UTM zone and hemisphere. The buffer must be organized as pairs of tightly packed UTM tuples in the order <code>(easting, northing)</code>. Each UTM tuple is replaced with its corresponding geographic location in the order <code>(longitude, latitude)</code>. Geographic locations are expressed in degrees. Tuples are replaced starting at the buffer's position and ending at its limit.
public NodeFigure(){ RectangleFigure rf=new RectangleFigure(); setDecorator(rf); createConnectors(); set(DECORATOR_INSETS,new Insets2D.Double(6,10,6,10)); ResourceBundleUtil labels=ResourceBundleUtil.getBundle("org.jhotdraw.samples.net.Labels"); setText(labels.getString("nodeDefaultName")); setAttributeEnabled(DECORATOR_INSETS,false); }
Creates a new instance.
public Adapter createEObjectAdapter(){ return null; }
Creates a new adapter for the default case. <!-- begin-user-doc --> This default implementation returns null. <!-- end-user-doc -->
public void loadMedia(MediaInfo media,boolean autoPlay,int position,JSONObject customData) throws TransientNetworkDisconnectionException, NoConnectionException { loadMedia(media,null,autoPlay,position,customData); }
Loads a media. For this to succeed, you need to have successfully launched the application.
@Override public int numPendingOutput(){ return m_attributeFilter.numPendingOutput(); }
Returns the number of instances pending output
private static void readJson() throws IOException { String str="{\"message\":\"Hi\",\"place\":{\"name\":\"World!\"}}"; InputStream in=new ByteArrayInputStream(str.getBytes(Charset.forName("UTF-8"))); JsonReader reader=new JsonReader(new InputStreamReader(in,"UTF-8")); while (reader.hasNext()) { JsonToken jsonToken=reader.peek(); if (jsonToken == JsonToken.BEGIN_OBJECT) { reader.beginObject(); } else if (jsonToken == JsonToken.END_OBJECT) { reader.endObject(); } if (jsonToken == JsonToken.STRING) { System.out.print(reader.nextString() + " "); } else { reader.skipValue(); } } reader.close(); }
Example to readJson using StreamingAPI
public static void print(PrintWriter self,Object value){ self.print(InvokerHelper.toString(value)); }
Print a value formatted Groovy style to the print writer.
public boolean isDescendentOf(Node node1,Node node2){ return (node1 == node2) || isProperDescendentOf(node1,node2); }
Determines whether one node is a descendent of another.
public void reset(){ token=null; status=S_INIT; handlerStatusStack=null; }
Reset the parser to the initial state without resetting the underlying reader.
public static SimpleNode parse(Reader reader,String templateName) throws ParseException { return RuntimeSingleton.parse(reader,templateName); }
Parse the input and return the root of AST node structure. <br><br> In the event that it runs out of parsers in the pool, it will create and let them be GC'd dynamically, logging that it has to do that. This is considered an exceptional condition. It is expected that the user will set the PARSER_POOL_SIZE property appropriately for their application. We will revisit this.
public boolean isURL(){ return url != null; }
public void launchInBrowser() { if (isURL()) { try { browserLauncher = new BrowserLauncher(); browserLauncher.openURLinBrowser(url.toString()); } catch (BrowserLaunchingInitializingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnsupportedOperatingSystemException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
private TennisBall(int ttl,boolean ping){ this.ttl=ttl; this.ping=ping; }
Creates a new ball with the specified TTL value and PING/PONG state.
private String installCode(){ return "if (typeof(" + jsLookupTable + ") == 'undefined'){"+ jsLookupTable+ "=[]}"; }
Stock Javascript code that is included before all javascript requests to create a lookup table for the JS objects if one hasn't been created yet.
public boolean isInStandbyMode(){ return schedThread.isPaused(); }
<p> Reports whether the <code>Scheduler</code> is paused. </p>
@DSSafe(DSCat.SAFE_LIST) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-09-03 14:59:52.816 -0400",hash_original_method="DA70D8E8EFCF4CE896E4E17AB2D27792",hash_generated_method="808C5618E8DCBABF47C90F606652224D") @Override public synchronized void reset() throws IOException { if (!markSupported) { throw new UnsupportedOperationException("Mark not supported"); } if (mark < 0) { throw new IOException("No position has been marked"); } if (position > mark + readlimit) { throw new IOException("Marked position [" + mark + "] is no longer valid - passed the read limit ["+ readlimit+ "]"); } position=mark; eof=false; }
Reset the stream to the point when mark was last called.
public void waitForSchemaAgreement(String targetSchemaVersion,int nodeCount){ long start=System.currentTimeMillis(); Map<String,List<String>> versions=null; while (System.currentTimeMillis() - start < MAX_SCHEMA_WAIT_MS) { log.info("schema version to sync to: {}, required node count: {}",targetSchemaVersion,nodeCount); versions=getSchemaVersions(); if (versions.size() == 1) { if (!versions.containsKey(targetSchemaVersion)) { log.warn("Unable to converge to target version. Schema versions:{}, target version:{}",versions,targetSchemaVersion); return; } if (nodeCount != -1) { List<String> hosts=null; for ( Entry<String,List<String>> entry : versions.entrySet()) { hosts=entry.getValue(); } if (hosts != null && hosts.size() == nodeCount) { log.info("schema versions converged to target version {}, required node count achieved: {}",targetSchemaVersion,nodeCount); return; } } else { log.info("schema versions converged to target version {}, no check for node count",targetSchemaVersion); return; } } log.info("waiting for schema change ..."); try { Thread.sleep(SCHEMA_RETRY_SLEEP_MILLIS); } catch ( InterruptedException ex) { } } log.warn("Unable to converge schema versions: {}",versions); }
Waits for schema change to propagate through all nodes of cluster It doesn't check if all nodes are of this version when nodeCount == -1
public void testSenderWithSpringXmlUsingSpring2NamespacesWithEmbeddedBrokerConfiguredViaXml() throws Exception { String config="spring-embedded-xbean.xml"; assertSenderConfig(config); }
Spring configured test case that tests the remotely deployed xsd http://people.apache.org/repository/org.apache.activemq/xsds/activemq-core-4.1-SNAPSHOT.xsd
protected void parseSkew() throws ParseException, IOException { current=reader.read(); if (current != 'e') { reportCharacterExpectedError('e',current); skipTransform(); return; } current=reader.read(); if (current != 'w') { reportCharacterExpectedError('w',current); skipTransform(); return; } current=reader.read(); boolean skewX=false; switch (current) { case 'X': skewX=true; case 'Y': break; default : reportCharacterExpectedError('X',current); skipTransform(); return; } current=reader.read(); skipSpaces(); if (current != '(') { reportCharacterExpectedError('(',current); skipTransform(); return; } current=reader.read(); skipSpaces(); float sk=parseFloat(); skipSpaces(); if (current != ')') { reportCharacterExpectedError(')',current); skipTransform(); return; } if (skewX) { fragmentIdentifierHandler.skewX(sk); } else { fragmentIdentifierHandler.skewY(sk); } }
Parses a skew transform. 'e' is assumed to be the current character.
public void addProperty(String name,String value){ properties.put(name,value); }
Adds a property.
public static long convert(String stringValue){ if (Strings.isNullOrEmpty(stringValue) || TypeUtils.MISSING_INDICATORS.contains(stringValue)) { return (long)ColumnType.LONG_INT.getMissingValue(); } Matcher matcher=COMMA_PATTERN.matcher(stringValue); return Long.parseLong(matcher.replaceAll("")); }
Returns a float that is parsed from the given String <p> We remove any commas before parsing
public ProportionVectors(FlagConfig flagConfig){ Random random=new Random(randomSeed); while (true) { this.vectorStart=VectorFactory.generateRandomVector(flagConfig.vectortype(),flagConfig.dimension(),flagConfig.seedlength(),random); this.vectorEnd=VectorFactory.generateRandomVector(flagConfig.vectortype(),flagConfig.dimension(),flagConfig.seedlength(),random); if (this.vectorStart.measureOverlap(this.vectorEnd) < 0.1) break; VerbatimLogger.info("Bookend vectors too similar to each other ... repeating generation.\n"); } }
Constructs an instance from the given flag config.
public void exit(){ synchronized (statemachine) { statemachine.exit(); } }
exit() will be delegated thread-safely to the wrapped state machine.
public NokiaGroupGraphic(byte[] bitmapData){ super(SmsPort.NOKIA_CLI_LOGO,SmsPort.ZERO); bitmapData_=bitmapData; }
Creates a group graphic SMS message <p> The given byte array must be in the Nokia OTA image format.
private JsonObject readConfig(File f){ try { return (new JsonParser()).parse(new FileReader(f)).getAsJsonObject(); } catch ( JsonIOException e) { Log.error("IOException while reading remote config."); e.printStackTrace(); return null; } catch ( FileNotFoundException e) { Log.error("Couldn't find remote config."); e.printStackTrace(); return null; } catch ( Exception e) { Log.error("Syntax error in remote config."); e.printStackTrace(); return null; } }
Parses the MCEF configuration file.
private static double distance(double[] subseries,double[] series,int from,int to,double nThreshold) throws Exception { double[] subsequence=tp.znorm(tp.subseriesByCopy(series,from,to),nThreshold); Double sum=0D; for (int i=0; i < subseries.length; i++) { double tmp=subseries[i] - subsequence[i]; sum=sum + tmp * tmp; } return Math.sqrt(sum); }
Calculates the Euclidean distance between two points. Don't use this unless you need that.
@SuppressWarnings("unchecked") public static <O>Map<String,? extends Attribute<O,?>> createAttributes(Class<O> pojoClass){ final Map<String,Attribute<O,?>> attributes=new TreeMap<String,Attribute<O,?>>(); Class currentClass=pojoClass; while (currentClass != null && currentClass != Object.class) { for ( Field field : Arrays.asList(currentClass.getDeclaredFields())) { try { int modifiers=field.getModifiers(); Class<? extends Attribute<O,?>> attributeClass; if (!isStatic(modifiers) && !isPrivate(modifiers)) { if (!field.getDeclaringClass().getPackage().getName().equals(pojoClass.getPackage().getName()) && !(isProtected(modifiers) || isPublic(modifiers))) { continue; } Class<?> fieldType=field.getType(); if (fieldType.isPrimitive()) { Class<?> wrapperType=getWrapperForPrimitive(fieldType); attributeClass=generateSimpleAttributeForField(pojoClass,wrapperType,field.getName(),field.getName()); } else if (Iterable.class.isAssignableFrom(fieldType)) { ParameterizedType parameterizedType=(ParameterizedType)field.getGenericType(); Type[] actualTypeArguments=parameterizedType.getActualTypeArguments(); if (actualTypeArguments.length != 1) { throw new UnsupportedOperationException(); } Class<?> genericType=(Class<?>)actualTypeArguments[0]; attributeClass=generateMultiValueNullableAttributeForField(pojoClass,genericType,field.getName(),true,field.getName()); } else if (fieldType.isArray()) { Class<?> componentType=fieldType.getComponentType(); if (componentType.isPrimitive()) { Class<?> wrapperType=getWrapperForPrimitive(componentType); attributeClass=generateMultiValueNullableAttributeForField(pojoClass,wrapperType,field.getName(),false,field.getName()); } else { attributeClass=generateMultiValueNullableAttributeForField(pojoClass,componentType,field.getName(),true,field.getName()); } } else { attributeClass=generateSimpleNullableAttributeForField(pojoClass,fieldType,field.getName(),field.getName()); } Attribute<O,?> attribute=attributeClass.newInstance(); attributes.put(attribute.getAttributeName(),attribute); } } catch ( Throwable e) { throw new IllegalStateException("Failed to create attribute for field: " + field.toGenericString(),e); } } currentClass=currentClass.getSuperclass(); } return attributes; }
Auto-generates and instantiates a set of attributes which read values from the fields in the given POJO class. <p> Attributes will be generated for all non-private fields declared directly in the POJO class, and for inherited fields as well, as long as the access modifiers on inherited fields in their superclass(es) allow those fields to be accessed from the package of the POJO class. So if the POJO class is in the same package as a superclass, then attributes will be generated for package-private, protected, and public fields in the superclass. If the POJO class is in a different package from the superclass, then attributes will be generated for protected and public fields in the superclass.
GuiProgressListener(JProgressBar progressBar,JTextComponent textComponent){ this.progressBar=checkNotNull(progressBar); this.textComponent=checkNotNull(textComponent); }
Creates a new GuiProgressListener that updates the given progress bar and text component.
protected byte[] hexStringToByteArray(String hexString){ int len=hexString.length(); byte[] data=new byte[len / 2]; for (int i=0; i < len; i+=2) { data[i / 2]=(byte)((Character.digit(hexString.charAt(i),16) << 4) + Character.digit(hexString.charAt(i + 1),16)); } return data; }
Converts hex values from strings to byte arra
private String generateFileForFramework(Framework fw,Width arch) throws Exception { File tempfile=File.createTempFile("JObjC-SOR-" + fw.name + "-"+ arch+ "-",".mm"); PrintWriter out=new PrintWriter(new FileWriter(tempfile)); out.println("#include<iostream>"); printHeaderLines(fw,arch,out); out.println(""); out.println("int main(int argc, char** argv){"); printStructInfos(fw,arch,out); out.println("\treturn 0;"); out.println("}"); out.close(); return tempfile.getAbsolutePath(); }
Generates Objective-C file and returns absolute path name.
public RealmSampleUserItem withEnabled(boolean enabled){ this.mEnabled=enabled; return this; }
set if this item is enabled
private void createFromAssets(String dbName,File dbfile,InputStream assetFileInputStream){ OutputStream out=null; try { Log.v("info","Copying pre-populated DB content"); String dbPath=dbfile.getAbsolutePath(); dbPath=dbPath.substring(0,dbPath.lastIndexOf("/") + 1); File dbPathFile=new File(dbPath); if (!dbPathFile.exists()) dbPathFile.mkdirs(); File newDbFile=new File(dbPath + dbName); out=new FileOutputStream(newDbFile); byte[] buf=new byte[1024]; int len; while ((len=assetFileInputStream.read(buf)) > 0) out.write(buf,0,len); Log.v("info","Copied pre-populated DB content to: " + newDbFile.getAbsolutePath()); } catch ( IOException e) { Log.v("createFromAssets","No pre-populated DB found, error=" + e.getMessage()); } finally { if (out != null) { try { out.close(); } catch ( IOException ignored) { } } } }
If a prepopulated DB file exists in the assets folder it is copied to the dbPath. Only runs the first time the app runs.
@Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); mListName=getArguments().getString(Constants.KEY_LIST_NAME); }
Initialize instance variables with data from bundle
public void removeListener(EnvLoaderListener listener){ super.removeListener(listener); ArrayList<EnvLoaderListener> listeners=_listeners; if (_listeners == null) return; synchronized (listeners) { for (int i=listeners.size() - 1; i >= 0; i--) { EnvLoaderListener oldListener=listeners.get(i); if (listener == oldListener) { listeners.remove(i); return; } else if (oldListener == null) { listeners.remove(i); } } } }
Adds a listener to detect environment lifecycle changes.
protected IElementType parseCloseAngle(){ if (myOpenedAngles.isEmpty()) { return POD_SYMBOL; } int bufferEnd=getBufferEnd(); int tokenStart=getTokenStart(); int run=tokenStart; CharSequence buffer=getBuffer(); int lastIndex=myOpenedAngles.size() - 1; int anglesNumber=myOpenedAngles.get(lastIndex); if (anglesNumber == 1) { myOpenedAngles.remove(lastIndex); return POD_ANGLE_RIGHT; } int endOffset=tokenStart + anglesNumber; if (tokenStart > 0 && Character.isWhitespace(buffer.charAt(tokenStart - 1))) { while (run < bufferEnd && run < endOffset && buffer.charAt(run) == '>') { run++; } if (run == endOffset) { setTokenEnd(run); myOpenedAngles.remove(lastIndex); return POD_ANGLE_RIGHT; } } return POD_SYMBOL; }
Pre-parses closing angles
private void addTrackFromGpxFile(){ EndToEndTestUtils.deleteAllTracks(); deleteExternalStorageFiles(TrackFileFormat.GPX); createOneGpxFile(); importTracks(TrackFileFormat.GPX); checkImportSuccess(); checkTrackFromGpxFile(); }
Adds one track by importing it from a GPX file.
public boolean isInSegment(double angle){ return angle >= mStartAngle && angle <= mEndAngle; }
Checks if angle falls in segment.
public void testAdd(){ try { LinkedBlockingQueue q=new LinkedBlockingQueue(SIZE); for (int i=0; i < SIZE; ++i) { assertTrue(q.add(new Integer(i))); } assertEquals(0,q.remainingCapacity()); q.add(new Integer(SIZE)); shouldThrow(); } catch ( IllegalStateException success) { } }
add succeeds if not full; throws ISE if full
public DictionaryInfo forceSave(Dictionary<?> newDict,DictionaryInfo newDictInfo) throws IOException { initDictInfo(newDict,newDictInfo); logger.info("force to save dict directly"); return saveNewDict(newDictInfo); }
Save the dictionary as it is. More often you should consider using its alternative trySaveNewDict to save dict space
int minInsertionsDP(String s){ int n=s.length(); int[][] dp=new int[n][n]; for (int gap=1; gap < n; gap++) { for (int l=0, h=gap; h < n; l++, h++) { dp[l][h]=s.charAt(l) == s.charAt(h) ? dp[l + 1][h - 1] : Math.min(dp[l][h - 1],dp[l + 1][h]) + 1; } } return dp[0][n - 1]; }
DP, bottom-up Fill a table in diagonal direction
public void next(){ pos++; }
moves the internal pointer to the next position, no check if the next position is still valid
public void show(Animation anim){ show(true,anim); }
Make the badge visible in the UI.
public synchronized boolean removeSuspendedResponse(WorkerCategory category,Response response){ Deque<Response> deque=workersByCategory.get(category); if (deque == null) { return false; } if (deque.remove(response)) { nWaitingConsumers-=1; LOG.debug("Removed closed connection from queue."); return true; } return false; }
When we notice that a long poll connection has closed, we remove it here.
private void installProperties(){ System.setProperty("http.agent",UserAgentGenerator.getUserAgent()); if (OSUtils.isMacOSX()) { System.setProperty("apple.laf.useScreenMenuBar","true"); } }
Installs any system properties.
@Override protected void processData(int offsetInchunk,byte[] buf,int off,int len){ if (skipBytes && offsetInchunk < 4) { for (int oc=offsetInchunk; oc < 4 && len > 0; oc++, off++, len--) skippedBytes[oc]=buf[off]; } if (len > 0) { deflatedChunksSet.processBytes(buf,off,len); if (alsoBuffer) { System.arraycopy(buf,off,getChunkRaw().data,read,len); } } }
Delegates to ChunkReaderDeflatedSet.processData()
public void test_getLowestSetBitNeg(){ byte aBytes[]={-1,-128,56,100,-2,-76,89,45,91,3,-15,35,26}; int aSign=-1; int iNumber=1; BigInteger aNumber=new BigInteger(aSign,aBytes); int result=aNumber.getLowestSetBit(); assertTrue("incorrect value",result == iNumber); }
java.math.BigInteger#getLowestSetBit() getLowestSetBit for negative BigInteger
@Override public void mark(int markLimit){ }
Since we do not support marking just yet, we do nothing.
@Override public void close() throws IOException { if (null != dictionaryFileReader) { dictionaryFileReader.close(); dictionaryFileReader=null; } }
Closes this stream and releases any system resources associated with it. If the stream is already closed then invoking this method has no effect.
public PathfindingAction(final Module module){ super("Pathfinder"); m_module=module; setEnabled(module.isLoaded()); m_module.addListener(m_updater); }
Creates a new pathfinding action object.
private GraphNode[] fillGraphModel(GraphModel graph){ GraphNode[] nodes=new GraphNode[7]; GraphBuilder builder=graph.getBuilder(); nodes[0]=builder.newNode(new MockElement("Package1")); nodes[1]=builder.newNode(new MockElement("Package2")); nodes[2]=builder.newNode(new MockElement("Package3")); nodes[3]=builder.newNode(new MockElement("DirectoryElement1")); nodes[4]=builder.newNode(new MockElement("Source1")); nodes[5]=builder.newNode(new MockElement("DirectoryElement2")); nodes[6]=builder.newNode(new MockElement("Source2")); graph.addEdge(MockRelation.DIRECTORY,nodes[0],nodes[1]); graph.addEdge(MockRelation.DIRECTORY,nodes[1],nodes[2]); graph.addEdge(MockRelation.CLASSFILE,nodes[2],nodes[3]); graph.addEdge(MockRelation.CLASS,nodes[3],nodes[4]); graph.addEdge(MockRelation.CLASSFILE,nodes[0],nodes[5]); graph.addEdge(MockRelation.CLASS,nodes[5],nodes[6]); return nodes; }
Creates new GraphNodes, adds edges and puts them in the provided graph so that it can be used in tests.
public static String join(String[] array,String separator){ int len=array.length; if (len == 0) return ""; StringBuilder out=new StringBuilder(); out.append(array[0]); for (int i=1; i < len; i++) { out.append(separator).append(array[i]); } return out.toString(); }
Join an array of strings with the given separator. <p> Note: This might be replaced by utility method from commons-lang or guava someday if one of those libraries is added as dependency. </p>
public double length(){ return Math.sqrt(x * x + y * y + z * z); }
<p> computes the length of the vector. </p>
public void processPendingDeletes(Index index,Settings indexSettings,TimeValue timeout) throws IOException { logger.debug("{} processing pending deletes",index); final long startTimeNS=System.nanoTime(); final List<ShardLock> shardLocks=nodeEnv.lockAllForIndex(index,indexSettings,timeout.millis()); try { Map<ShardId,ShardLock> locks=new HashMap<>(); for ( ShardLock lock : shardLocks) { locks.put(lock.getShardId(),lock); } final List<PendingDelete> remove; synchronized (pendingDeletes) { remove=pendingDeletes.remove(index); } if (remove != null && remove.isEmpty() == false) { CollectionUtil.timSort(remove); final long maxSleepTimeMs=10 * 1000; long sleepTime=10; do { if (remove.isEmpty()) { break; } Iterator<PendingDelete> iterator=remove.iterator(); while (iterator.hasNext()) { PendingDelete delete=iterator.next(); if (delete.deleteIndex) { assert delete.shardId == -1; logger.debug("{} deleting index store reason [{}]",index,"pending delete"); try { nodeEnv.deleteIndexDirectoryUnderLock(index,indexSettings); iterator.remove(); } catch ( IOException ex) { logger.debug("{} retry pending delete",ex,index); } } else { assert delete.shardId != -1; ShardLock shardLock=locks.get(new ShardId(delete.index,delete.shardId)); if (shardLock != null) { try { deleteShardStore("pending delete",shardLock,delete.settings); iterator.remove(); } catch ( IOException ex) { logger.debug("{} retry pending delete",ex,shardLock.getShardId()); } } else { logger.warn("{} no shard lock for pending delete",delete.shardId); iterator.remove(); } } } if (remove.isEmpty() == false) { logger.warn("{} still pending deletes present for shards {} - retrying",index,remove.toString()); try { Thread.sleep(sleepTime); sleepTime=Math.min(maxSleepTimeMs,sleepTime * 2); logger.debug("{} schedule pending delete retry after {} ms",index,sleepTime); } catch ( InterruptedException e) { Thread.interrupted(); return; } } } while ((System.nanoTime() - startTimeNS) < timeout.nanos()); } } finally { IOUtils.close(shardLocks); } }
Processes all pending deletes for the given index. This method will acquire all locks for the given index and will process all pending deletes for this index. Pending deletes might occur if the OS doesn't allow deletion of files because they are used by a different process ie. on Windows where files might still be open by a virus scanner. On a shared filesystem a replica might not have been closed when the primary is deleted causing problems on delete calls so we schedule there deletes later.
public LargeValueFormatter(String appendix){ this(); mText=appendix; }
Creates a formatter that appends a specified text to the result string
public void commitChanges(Collection<Synapse> synapses){ double uB=Utils.doubleParsable(tfUpBound); if (!Double.isNaN(uB)) { for ( Synapse s : synapses) { s.setUpperBound(uB); } } double lB=Utils.doubleParsable(tfLowBound); if (!Double.isInfinite(lB)) { for ( Synapse s : synapses) { s.setLowerBound(lB); } } double increment=Utils.doubleParsable(tfIncrement); if (!Double.isNaN(increment)) { for ( Synapse s : synapses) { s.setIncrement(increment); } } double delay=Utils.doubleParsable(tfDelay); if (!Double.isNaN(delay)) { int dly=(int)delay; for ( Synapse s : synapses) { s.setDelay(dly); } } boolean frozen=frozenDD.getSelectedIndex() == YesNoNull.getTRUE(); if (frozenDD.getSelectedIndex() != YesNoNull.getNULL()) { for ( Synapse s : synapses) { s.setFrozen(frozen); } } }
Uses the values from text fields to alter corresponding values in the synapse(s) being edited. Called externally to apply changes.
@SuppressWarnings("unchecked") private void validateAndPopulate(Boolean allowNonUpnFormat) throws InvalidTokenException { JAXBElement<AssertionType> jaxbParserResult=null; try { Unmarshaller unmarshaller=_jaxbContext.createUnmarshaller(); unmarshaller.setSchema(SAML_SCHEMA); jaxbParserResult=(JAXBElement<AssertionType>)unmarshaller.unmarshal(_parsedToken); } catch ( JAXBException e) { _log.info(PARSING_TOKEN_ERROR_MSG,e); throw new MalformedTokenException(PARSING_TOKEN_ERROR_MSG,e); } AssertionType assertion=jaxbParserResult.getValue(); parseAssertionAttributes(assertion); parseConditions(assertion.getConditions(),allowNonUpnFormat); parseSubject(assertion.getSubject()); parseIssuer(assertion.getIssuer()); parseAuthnStatement(assertion.getAuthnStatementOrAttributeStatement()); if (assertion.getAuthnStatementOrAttributeStatement() != null) { parseAttributeStatement(assertion.getAuthnStatementOrAttributeStatement()); } if (assertion.getAdvice() != null) { parseAdvice(assertion.getAdvice()); } _log.debug("Token fields are successfully populated"); }
Parses the xml string representing the SAML token.<br> Validates that the schema format is correct and the token fields are semantically correct.<br> Populates the class members with the values provided in the token.<br>
public boolean containsValue(V v){ for ( LinkedList<V> l : boxedHashMap.values()) { if (l.contains(v)) { return true; } } return false; }
Returns <tt>true</tt> if this map maps one or more keys to the specified value.
private static void sort(int[] a,int left,int right,boolean leftmost){ int length=right - left + 1; if (length < INSERTION_SORT_THRESHOLD) { if (leftmost) { for (int i=left, j=i; i < right; j=++i) { int ai=a[i + 1]; while (ai < a[j]) { a[j + 1]=a[j]; if (j-- == left) { break; } } a[j + 1]=ai; } } else { do { if (left >= right) { return; } } while (a[++left] >= a[left - 1]); for (int k=left; ++left <= right; k=++left) { int a1=a[k], a2=a[left]; if (a1 < a2) { a2=a1; a1=a[left]; } while (a1 < a[--k]) { a[k + 2]=a[k]; } a[++k + 1]=a1; while (a2 < a[--k]) { a[k + 1]=a[k]; } a[k + 1]=a2; } int last=a[right]; while (last < a[--right]) { a[right + 1]=a[right]; } a[right + 1]=last; } return; } int seventh=(length >> 3) + (length >> 6) + 1; int e3=(left + right) >>> 1; int e2=e3 - seventh; int e1=e2 - seventh; int e4=e3 + seventh; int e5=e4 + seventh; if (a[e2] < a[e1]) { int t=a[e2]; a[e2]=a[e1]; a[e1]=t; } if (a[e3] < a[e2]) { int t=a[e3]; a[e3]=a[e2]; a[e2]=t; if (t < a[e1]) { a[e2]=a[e1]; a[e1]=t; } } if (a[e4] < a[e3]) { int t=a[e4]; a[e4]=a[e3]; a[e3]=t; if (t < a[e2]) { a[e3]=a[e2]; a[e2]=t; if (t < a[e1]) { a[e2]=a[e1]; a[e1]=t; } } } if (a[e5] < a[e4]) { int t=a[e5]; a[e5]=a[e4]; a[e4]=t; if (t < a[e3]) { a[e4]=a[e3]; a[e3]=t; if (t < a[e2]) { a[e3]=a[e2]; a[e2]=t; if (t < a[e1]) { a[e2]=a[e1]; a[e1]=t; } } } } int less=left; int great=right; if (a[e1] != a[e2] && a[e2] != a[e3] && a[e3] != a[e4] && a[e4] != a[e5]) { int pivot1=a[e2]; int pivot2=a[e4]; a[e2]=a[left]; a[e4]=a[right]; while (a[++less] < pivot1) ; while (a[--great] > pivot2) ; outer: for (int k=less - 1; ++k <= great; ) { int ak=a[k]; if (ak < pivot1) { a[k]=a[less]; a[less]=ak; ++less; } else if (ak > pivot2) { while (a[great] > pivot2) { if (great-- == k) { break outer; } } if (a[great] < pivot1) { a[k]=a[less]; a[less]=a[great]; ++less; } else { a[k]=a[great]; } a[great]=ak; --great; } } a[left]=a[less - 1]; a[less - 1]=pivot1; a[right]=a[great + 1]; a[great + 1]=pivot2; sort(a,left,less - 2,leftmost); sort(a,great + 2,right,false); if (less < e1 && e5 < great) { while (a[less] == pivot1) { ++less; } while (a[great] == pivot2) { --great; } outer: for (int k=less - 1; ++k <= great; ) { int ak=a[k]; if (ak == pivot1) { a[k]=a[less]; a[less]=ak; ++less; } else if (ak == pivot2) { while (a[great] == pivot2) { if (great-- == k) { break outer; } } if (a[great] == pivot1) { a[k]=a[less]; a[less]=pivot1; ++less; } else { a[k]=a[great]; } a[great]=ak; --great; } } } sort(a,less,great,false); } else { int pivot=a[e3]; for (int k=less; k <= great; ++k) { if (a[k] == pivot) { continue; } int ak=a[k]; if (ak < pivot) { a[k]=a[less]; a[less]=ak; ++less; } else { while (a[great] > pivot) { --great; } if (a[great] < pivot) { a[k]=a[less]; a[less]=a[great]; ++less; } else { a[k]=pivot; } a[great]=ak; --great; } } sort(a,left,less - 1,leftmost); sort(a,great + 1,right,false); } }
Sorts the specified range of the array by Dual-Pivot Quicksort.
public FastAdapterDialog<Item> add(int position,List<Item> items){ mFastItemAdapter.add(position,items); return this; }
add a list of items at the given position within the existing items
public CViewSearcherDialog(final Window owner,final IViewContainer viewContainer,final IAddress address){ super(owner,"Select a graph",ModalityType.APPLICATION_MODAL); Preconditions.checkNotNull(viewContainer,"IE02057: View container can't be null"); m_viewContainer=viewContainer; createGui(); new CDialogEscaper(this); GuiHelper.centerChildToParent(owner,this,true); if (address != null) { m_offsetField.setText(address.toHexString()); search(address.toLong()); } }
Creates a new dialog.
public static void main(final String[] args){ DOMTestCase.doMain(hc_attrname.class,args); }
Runs this test from the command line.
@Override public void write(byte[] buffer,int offset,int length) throws IOException { while ((mByteToSkip > 0 || mByteToCopy > 0 || mState != STATE_JPEG_DATA) && length > 0) { if (mByteToSkip > 0) { int byteToProcess=length > mByteToSkip ? mByteToSkip : length; length-=byteToProcess; mByteToSkip-=byteToProcess; offset+=byteToProcess; } if (mByteToCopy > 0) { int byteToProcess=length > mByteToCopy ? mByteToCopy : length; out.write(buffer,offset,byteToProcess); mSize+=byteToProcess; length-=byteToProcess; mByteToCopy-=byteToProcess; offset+=byteToProcess; } if (length == 0) { return; } switch (mState) { case STATE_SOI: int byteRead=requestByteToBuffer(2,buffer,offset,length); offset+=byteRead; length-=byteRead; if (mBuffer.position() < 2) { return; } mBuffer.rewind(); if (mBuffer.getShort() != JpegHeader.SOI) { throw new IOException("Not a valid jpeg image, cannot write exif"); } out.write(mBuffer.array(),0,2); mSize+=2; mState=STATE_FRAME_HEADER; mBuffer.rewind(); break; case STATE_FRAME_HEADER: byteRead=requestByteToBuffer(4,buffer,offset,length); offset+=byteRead; length-=byteRead; if (mBuffer.position() == 2) { short tag=mBuffer.getShort(); if (tag == JpegHeader.EOI) { out.write(mBuffer.array(),0,2); mSize+=2; mBuffer.rewind(); } } if (mBuffer.position() < 4) { return; } mBuffer.rewind(); short marker=mBuffer.getShort(); if (marker == JpegHeader.APP1 || marker == JpegHeader.APP0) { out.write(mBuffer.array(),0,4); mSize+=4; mByteToCopy=(mBuffer.getShort() & 0x0000ffff) - 2; } else { writeMpoData(); out.write(mBuffer.array(),0,4); mSize+=4; mState=STATE_JPEG_DATA; } mBuffer.rewind(); break; } } if (length > 0) { out.write(buffer,offset,length); mSize+=length; } }
Writes the image out. The input data should be a valid JPEG format. After writing, it's Exif header will be replaced by the given header.
public static <T,R>int highSum(Function<T,Integer> f1,Function<R,Integer> f2,T data1,R data2){ return f1.apply(data1) + f2.apply(data2); }
A higher order function - sums the results of two other functions, passed to it as parameters.
public HashCodeBuilder append(final double[] array){ if (array == null) { iTotal=iTotal * iConstant; } else { for ( final double element : array) { append(element); } } return this; }
<p> Append a <code>hashCode</code> for a <code>double</code> array. </p>
public boolean isError(final OneDriveErrorCodes expectedCode){ if (code.equalsIgnoreCase(expectedCode.toString())) { return true; } OneDriveInnerError innerError=innererror; while (null != innerError) { if (innerError.code.equalsIgnoreCase(expectedCode.toString())) { return true; } innerError=innerError.innererror; } return false; }
Determine if the given error code is the one that is expected.
public static Play copy(Play play){ Play copy=new Play(play.playId,play.gameId,play.gameName); copy.setDate(play.getDate()); copy.quantity=play.quantity; copy.length=play.length; copy.location=play.location; copy.setIncomplete(play.Incomplete()); copy.setNoWinStats(play.NoWinStats()); copy.comments=play.comments; copy.startTime=play.startTime; for ( Player player : play.getPlayers()) { copy.addPlayer(new Player(player)); } return copy; }
Copy the semantic play information to a new play. Does not include data related to syncing.
public ScMappingProfile[] findMappingProfiles(String serverId,String volumeId) throws StorageCenterAPIException { PayloadFilter filter=new PayloadFilter(); filter.append("server",serverId); filter.append("volume",volumeId); RestResult rr=restClient.post("StorageCenter/ScMappingProfile/GetList",filter.toJson()); if (checkResults(rr)) { return gson.fromJson(rr.getResult(),ScMappingProfile[].class); } String message=String.format("Error getting mapping profiles from server %s and volume %s: %s",serverId,volumeId,rr.getErrorMsg()); throw new StorageCenterAPIException(message); }
Finds mapping between a server and volume.
private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException { s.defaultReadObject(); }
Adds semantic checks to the default deserialization method. This method must have the standard signature for a readObject method, and the body of the method must begin with "s.defaultReadObject();". Other than that, any semantic checks can be specified and do not need to stay the same from version to version. A readObject method of this form may be added to any class, even if Tetrad sessions were previously saved out using a version of the class that didn't include it. (That's what the "s.defaultReadObject();" is for. See J. Bloch, Effective Java, for help.
public JSONArray put(int value){ this.put(new Integer(value)); return this; }
Append an int value. This increases the array's length by one.