code
stringlengths
10
174k
nl
stringlengths
3
129k
public ContourPath(ContourAttrib attr,int levelIndex,double[] x,double[] y){ xArr=x; yArr=y; this.levelIndex=levelIndex; attributes=attr; int np=xArr.length; if (Math.abs(x[0] - x[np - 1]) < kSmallX && Math.abs(y[0] - y[np - 1]) < kSmallY) { closed=true; x[np - 1]=x[0]; y[np - 1]=y[0]; } else...
Construct a contour path or line using the given arrays of X & Y values.
public WritableRaster createCompatibleWritableRaster(int w,int h){ if (w <= 0 || h <= 0) { throw new RasterFormatException("negative " + ((w <= 0) ? "width" : "height")); } SampleModel sm=sampleModel.createCompatibleSampleModel(w,h); return new ByteInterleavedRaster(sm,new Point(0,0)); }
Creates a Raster with the same layout but using a different width and height, and with new zeroed data arrays.
public Strftime(String origFormat,Locale locale){ String convertedFormat=convertDateFormat(origFormat); simpleDateFormat=new SimpleDateFormat(convertedFormat,locale); }
Create an instance of this date formatting class
public int[][] generateDistinctRandomSets(int n,int p,int maxNumSets){ int maxPossibleNumSets=0; try { maxPossibleNumSets=MathsUtils.numOfSets(n,p); if (maxNumSets > maxPossibleNumSets) { maxNumSets=maxPossibleNumSets; return generateAllDistinctSets(n,p); } } catch ( Exception e) { } ...
Generate (up to) numSets distinct sets of p distinct values in [0..n-1] Done using random guesses as this is designed for high dimension n where its highly unlikely we repeat a set (though this is checked)
private boolean checkPlayServices(){ GoogleApiAvailability apiAvailability=GoogleApiAvailability.getInstance(); int resultCode=apiAvailability.isGooglePlayServicesAvailable(this); if (resultCode != ConnectionResult.SUCCESS) { if (apiAvailability.isUserResolvableError(resultCode)) { apiAvailability.getEr...
Check the device to make sure it has the Google Play Services APK. If it doesn't, display a dialog that allows users to download the APK from the Google Play Store or enable it in the device's system settings.
public double mahalanobisDistance(NumberVector vec){ double agg=0.; for (int i=0; i < mean.length; i++) { double diff=vec.doubleValue(i) - mean[i]; agg+=diff / variance * diff; } return agg; }
Compute the Mahalanobis distance from the centroid for a given vector.
private static Map<UUID,AccessInformation> filterUser(Map<UUID,AccessInformation> map,String username){ if (username == null || username.isEmpty()) { return map; } Map<UUID,AccessInformation> res=new HashMap<>(); for ( Entry<UUID,AccessInformation> ent : map.entrySet()) { String accessuser=ent.getValue...
Returns a sub Map of the given map containing only AccessInformation about the given user.
public void removeAllListeners(){ statementListenerSet.removeAllListeners(); statementContext.getStatementResultService().setUpdateListeners(statementListenerSet,false); if (statementLifecycleSvc != null) { statementLifecycleSvc.dispatchStatementLifecycleEvent(new StatementLifecycleEvent(this,StatementLifecyc...
Remove all listeners to a statement.
private void updateProgress(String progressLabel,int progress){ if (myHost != null && ((progress != previousProgress) || (!progressLabel.equals(previousProgressLabel)))) { myHost.updateProgress(progressLabel,progress); } previousProgress=progress; previousProgressLabel=progressLabel; }
Used to communicate a progress update between a plugin tool and the main Whitebox user interface.
public ServerRegionProxy(Region r){ super(calcPool(r)); assert r instanceof LocalRegion; this.region=(LocalRegion)r; this.regionName=r.getFullPath(); }
Creates a server region proxy for the given region.
private static void reportTimer(){ final Timer timer=registry.timer(APP_PREFIX.tagged("what","incoming-request-time").tagged("endpoint","/v1/get_stuff")); final Context context=timer.time(); try { Thread.sleep(100); } catch ( final InterruptedException e) { e.printStackTrace(); } context.stop(); }...
A timer measures both the rate that a particular piece of code is called and the distribution of its duration. For example we want to measure the rate and handling duration of incoming requests.
private void computeSplitValues(){ float latMid=(bb.getLatMin() + bb.getLatMax()) / 2f; double width=(bb.getLonMax() - bb.getLonMin()) * Math.cos(latMid * Math.PI / 180.0); double height=bb.getLatMax() - bb.getLatMin(); if (height > width) { splitAtLat=true; splitValue=latMid; } else { splitAtLat...
Splits the bounding box, so that the new boxes have equal size and look square-like as much as possible.
public final boolean containsKey(String name){ return mMap.containsKey(name); }
Returns true iff a key of the given name exists in the format.
public void handleDecode(Result rawResult,Bitmap barcode){ inactivityTimer.onActivity(); lastResult=rawResult; ResultHandler resultHandler=ResultHandlerFactory.makeResultHandler(this,rawResult); boolean fromLiveScan=barcode != null; if (fromLiveScan) { historyManager.addHistoryItem(rawResult,resultHandler...
A valid barcode has been found, so give an indication of success and show the results.
public long readLongZeta(final int k) throws IOException { if (k < 1) throw new IllegalArgumentException("The shrinking factor " + k + " is not positive"); if (k == 3) { int preComp; if ((fill >= 16 || refill() >= 16) && (preComp=ZETA_3[current >> (fill - 16) & 0xFFFF]) != 0) { readBits+=preComp >> ...
Reads a long natural number in &zeta; coding.
public static int hsba(float h,float s,float b,float a){ return setAlpha(Color.HSBtoRGB(h,s,b),(int)(a * 255 + 0.5) & 0xFF); }
Get the color code for the given hue, saturation, and brightness values, translating from HSB color space to RGB color space.
private void returnData(Object ret){ if (myHost != null) { myHost.returnData(ret); } }
Used to communicate a return object from a plugin tool to the main Whitebox user-interface.
public Element merge(final Element element){ types.addAll(element.types); possibleValues.addAll(element.possibleValues); return this; }
Merges the other element into this element.
public void start(){ log.info("Initializing diagnostics scheduler"); ScheduledExecutorService service=Executors.newScheduledThreadPool(1); service.scheduleAtFixedRate(this,SERVICE_START_LAG,LAG_BETWEEN_RUNS_ALERTS,TimeUnit.SECONDS); }
Sets up the scheduler.
private HttpURLConnection doHTTPPostRequest(String location,String clientSessionId,Map<String,String> metadata,String postBody) throws CommunicationException { OutputStreamWriter writer=null; try { URL url=new URL(location); HttpURLConnection connection=(HttpURLConnection)url.openConnection(); connectio...
Does a POST request with HttpClient
public static void error(String msg,Throwable ex,boolean popup){ System.err.println(msg); if (ex != null) ex.printStackTrace(); if (Options.uiMode == UIMode.GUI) { MainWindow.log("ERROR: " + msg,true); if (ex != null) { if (popup == true) JOptionPane.showMessageDialog(MainWindow.main,msg + "...
Logs an error message to stderr. If the GUI is up, it will also be shown in a popup window, and the stack trace written to the messages area of the main window.
public ElementCache(int size,int overflow){ super(size,overflow); }
Constructs a new element cache of the given size.
public Object runSafely(Catbert.FastStack stack) throws Exception { String imageURL=getEditorial(stack).getImageURL(); return (imageURL == null || imageURL.length() == 0) ? Boolean.FALSE : Boolean.TRUE; }
Returns true if the specified editorial has an image that corresponds to it
public boolean hasExchange(){ return getExchange() != null; }
Returns whether it has the exchange symbol for the company or mutual fund.
@SuppressWarnings("unchecked") @Override public NotificationChain eInverseAdd(InternalEObject otherEnd,int featureID,NotificationChain msgs){ switch (featureID) { case DomPackage.COMPOSITE__CONTENTS: return ((InternalEList<InternalEObject>)(InternalEList<?>)getContents()).basicAdd(otherEnd,msgs); } return super.eIn...
<!-- begin-user-doc --> <!-- end-user-doc -->
void saveEditingState(Main main){ TileLayerServer osmts=map.getOpenStreetMapTilesOverlay().getRendererInfo(); EditState editState=new EditState(main.getApplicationContext(),this,osmts,main.getImageFileName(),viewBox,main.getFollowGPS()); new SavingHelper<EditState>().save(main,EDITSTATE_FILENAME,editState,false);...
Saves the current editing state (selected objects, editing mode, etc) to file.
public jMatrix minus(jMatrix B){ checkMatrixDimensions(B); jMatrix X=new jMatrix(m,n); double[][] C=X.getArray(); for (int i=0; i < m; i++) { for (int j=0; j < n; j++) { C[i][j]=A[i][j] - B.A[i][j]; } } return X; }
C = A - B
public static PsiFile findFileContext(PsiElement element){ return element.getContainingFile(); }
Finds the file context for a given element. If element is inside of an Bash file injection host (e.g. because the element is in an eval command) then the host file is returned.
public void muteDevice(org.wso2.emm.agent.beans.Operation operation){ operation.setStatus(resources.getString(R.string.operation_value_completed)); resultBuilder.build(operation); AudioManager audioManager=(AudioManager)context.getSystemService(Context.AUDIO_SERVICE); audioManager.setStreamVolume(AudioManager.S...
Mute the device.
public static <T>boolean moveForward(final List<T> list,final int[] indices){ if (indices.length == 0) return false; sortReversed(indices); if (indices[0] == list.size() - 1) return false; for ( final int idx : indices) { final T element=list.get(idx); list.set(idx,list.get(idx + 1)); list.set(...
Moves elements specified by their indices forward by 1. <p> If the specified indices contains the index of the last element, then nothing is moved (the last element cannot be moved forward). </p> <p> Implementation note: the received indices array might be rearranged. If this is unwanted, pass a copy of the original ar...
public boolean validate(InputNode node) throws Exception { Class expect=type.getType(); String name=entry.getKey(); if (name == null) { name=context.getName(expect); } if (!entry.isAttribute()) { return validateElement(node,name); } return validateAttribute(node,name); }
This method is used to read the key value from the node. The value read from the node is resolved using the template filter. If the key value can not be found according to the annotation attributes then the node is considered as null and is valid.
protected static long[] known_N_compute_B_and_K_slow(long N,double epsilon,double delta,int quantiles,double[] returnSamplingRate){ final int maxBuffers=50; final int maxHeight=50; final double N_double=N; long ret_b=1; long ret_k=N; double sampling_rate=1.0; long memory=N; final double logarithm=Math.l...
Computes the number of buffers and number of values per buffer such that quantiles can be determined with an approximation error no more than epsilon with a certain probability. Assumes that quantiles are to be computed over N values. The required sampling rate is computed and stored in the first element of the provide...
public ExpiringMap(int timeToLive){ this(timeToLive,DEFAULT_EXPIRATION_INTERVAL); }
Creates a new instance of ExpiringMap using the supplied time-to-live value and the default value for DEFAULT_EXPIRATION_INTERVAL
public static boolean isWindowShapingSupported(){ Toolkit curToolkit=Toolkit.getDefaultToolkit(); if (!(curToolkit instanceof SunToolkit)) { return false; } return ((SunToolkit)curToolkit).isWindowShapingSupported(); }
Returns whether the windowing system supports changing the shape of top-level windows. Note that this method may sometimes return true, but the native windowing system may still not support the concept of shaping (due to the bugs in the windowing system).
public T abbr(String value){ return attr("abbr",value); }
Sets the <code>abbr</code> attribute on the last started tag that has not been closed.
@SuppressWarnings("unchecked") protected final boolean type(final Class<?> dependencyType){ return this.dependencyType.isAssignableFrom(dependencyType); }
Tests if the specified type represents the requested dependency type.
@Override public String toString(){ return mItem.name; }
ToString() implementation
public PreparedLineStringIntersects(PreparedLineString prepLine){ this.prepLine=prepLine; }
Creates an instance of this operation.
protected void emit_TField_SemicolonKeyword_5_q(EObject semanticObject,ISynNavigable transition,List<INode> nodes){ acceptNodes(transition,nodes); }
Ambiguous syntax: ';'? This ambiguous syntax occurs at: typeRef=TypeRef (ambiguity) (rule end)
private void hideProgressIfLoop(List<Api.Tag> tags){ MediaView actualView=viewer != null ? viewer.getActualMediaView() : null; if (actualView instanceof AbstractProgressMediaView) { if (Iterables.any(tags,null)) { ((AbstractProgressMediaView)actualView).setProgressEnabled(false); } } }
If the current post is a loop, we'll check if it is a loop. If it is, we will hide the little video progress bar.
@Override public long downloadToStream(String uri,OutputStream outputStream,final BitmapUtils.BitmapLoadTask<?> task){ if (task == null || task.isCancelled() || task.getTargetContainer() == null) return -1; URLConnection urlConnection=null; BufferedInputStream bis=null; OtherUtils.trustAllHttpsURLConnection()...
Download bitmap to outputStream by uri.
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:35:49.180 -0500",hash_original_method="9DD74CD1F13AD5E4F4CF15160B046494",hash_generated_method="D646522144ACE816F1B9C19EDF69A0F0") public void forgetLoadedWallpaper(){ sGlobals.forgetLoadedWallpaper(); }
Remove all internal references to the last loaded wallpaper. Useful for apps that want to reduce memory usage when they only temporarily need to have the wallpaper. After calling, the next request for the wallpaper will require reloading it again from disk.
@Override public boolean onPreferenceClick(Preference preference){ if (preference == mLinkPref) { Intent intent=new Intent(Intent.ACTION_VIEW,Uri.parse(PasswordUIView.getAccountDashboardURL())); intent.setPackage(getActivity().getPackageName()); getActivity().startActivity(intent); } else { Intent ...
Preference was clicked. Either navigate to manage account site or launch the PasswordEditor depending on which preference it was.
private void zzScanError(int errorCode){ String message; try { message=ZZ_ERROR_MSG[errorCode]; } catch ( ArrayIndexOutOfBoundsException e) { message=ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR]; } throw new Error(message); }
Reports an error that occured while scanning. In a wellformed scanner (no or only correct usage of yypushback(int) and a match-all fallback rule) this method will only be called with things that "Can't Possibly Happen". If this method is called, something is seriously wrong (e.g. a JFlex bug producing a faulty scanner ...
public PeerNetwork clone(){ PeerNetwork clone=new BluetoothLEPeerNetwork(mBluetoothLEDevice); return clone; }
Return a copy of the PeerNetwork, referring to the same network locations.
public static void registerSerDeser(Class<?> clazz,EntitySerDeser<?> entitySerDeser){ _serDeserMap.put(clazz,entitySerDeser); }
User can register their own field SerDeser
public void testGetGeneratedKeysAllCases() throws Exception { System.out.println("Using Statement.executeUpdate()\n"); try { createGGKTables(); for (int i=0; i < tests.length; i++) { doGGKTestStatement(tests[i],true); } } finally { dropGGKTables(); } nextID=1; count=0; System.out.p...
Tests all forms of statements influencing getGeneratedKeys().
public static boolean equals(int[] array1,int[] array2){ if (array1 == array2) { return true; } if (array1 == null || array2 == null || array1.length != array2.length) { return false; } for (int i=0; i < array1.length; i++) { if (array1[i] != array2[i]) { return false; } } return tru...
Compares the two arrays.
public boolean removeAll(Collection<?> c){ return al.removeAll(c); }
Removes from this set all of its elements that are contained in the specified collection. If the specified collection is also a set, this operation effectively modifies this set so that its value is the <i>asymmetric set difference</i> of the two sets.
public void fill3DRect(int x,int y,int width,int height,boolean raised){ g.fill3DRect(x,y,width,height,raised); }
Paints a 3-D highlighted rectangle filled with the current color. The edges of the rectangle will be highlighted so that it appears as if the edges were beveled and lit from the upper left corner. The colors used for the highlighting effect will be determined from the current color.
private int registerSourceFile(String file){ if (sourceFiles.contains(file)) return -1; sourceFiles.add(file); this.size++; return sourceFiles.size() - 1; }
Register a new source file. This method is used to implement file inclusion. Each included file gets a unique identifier (which is the index in the array of source files).
public Iterator<Sensor> iterator(){ return getSelection().iterator(); }
Return an iterator over the selected sensors.
public boolean isSubsequenceB(String s,String t){ if (s.length() == 0) { return true; } for (int i=0; i < t.length(); i++) { if (s.charAt(0) == t.charAt(i)) { return isSubsequenceB(s.substring(1),t.substring(i + 1)); } } return false; }
Recursion. Recurrence relation: whether s is the subsequence of t can be divided into 2 parts: 1) the first character of s is found in t 2) the rest of s is the subsequence of the rest of t
@Override public void translate(final ITranslationEnvironment environment,final IInstruction instruction,final List<ReilInstruction> instructions) throws InternalTranslationException { TranslationHelpers.checkTranslationArguments(environment,instruction,instructions,"test"); if (instruction.getOperands().size() != ...
Translates a TEST instruction to REIL code.
public static boolean isSynchronized(int flags){ return (flags & AccSynchronized) != 0; }
Returns whether the given integer includes the <code>synchronized</code> modifier.
public void insert(int index,BigDecimal v){ if (v == null) { insertNull(index); } else { _insert(index,numberNode(v)); } }
Method for setting value of a field to specified numeric value.
public void dropTables(){ try (Connection connection=getConnection();Statement statement=connection.createStatement()){ executeDropStatements(statement); } catch ( SQLException e) { throw new TableModificationException(e); } }
Drop all tables in the schema. Note if the platform supports if exists that will be used in the statement, if not and the table doesn't exist an exception will be thrown.
private String deleteAllSrdfVolumesInCG(Map<URI,Volume> sourcesVolumeMap,final Workflow workflow,String waitFor,final List<VolumeDescriptor> sourceDescriptors){ Volume sourceVolume=sourcesVolumeMap.get(sourceDescriptors.get(0).getVolumeURI()); Volume targetVolume=getFirstTarget(sourceVolume); if (targetVolume == ...
Delete All SRDF Volumes in CG in one attempt.
private int parseNonceLen(final byte[] b,final int off) throws ParseException { nonceLen_=PrimitivesParser.parseByte(b,off); if (nonceLen_ < 0) { throw new BadCiphertextException("Invalid nonce length in ciphertext"); } return 1; }
Parse the length of the nonce in the provided bytes. It looks for a single byte in the provided bytes starting at the specified off. <p> If successful, it returns 1 indicating that a byte was parsed. On failure, it throws a parse exception.
public Vector2i mul(Vector2i v){ x+=v.x; y+=v.y; return this; }
Add the supplied vector by this one.
public void convertInfixToPostfix(String infixExp) throws Exception { m_originalInfix=infixExp; infixExp=Utils.removeSubstring(infixExp," "); infixExp=Utils.replaceSubstring(infixExp,"log","l"); infixExp=Utils.replaceSubstring(infixExp,"abs","b"); infixExp=Utils.replaceSubstring(infixExp,"cos","c"); infixEx...
Converts a string containing a mathematical expression in infix form to postfix form. The result is stored in the vector m_postfixExpVector
public boolean onKeyUp(int keyCode,KeyEvent event){ if (isShowing() && mDropDownList.getSelectedItemPosition() >= 0) { boolean consumed=mDropDownList.onKeyUp(keyCode,event); if (consumed && isConfirmKey(keyCode)) { dismiss(); } return consumed; } return false; }
Filter key down events. By forwarding key up events to this function, views using non-modal ListPopupWindow can have it handle key selection of items.
@NotNull public static Result parsePathExprQualifierForExprStatement(@NotNull PsiBuilder builder,@NotNull GroovyParser parser){ PsiBuilder.Marker marker=builder.mark(); IElementType qualifierType=PrimaryExpression.parsePrimaryExpression(builder,parser); if (qualifierType != GroovyElementTypes.WRONGWAY) { retu...
parses method calls with parentheses, property index access, etc
@Override public void init(Context context){ super.init(context); String s; s=context.getResolvedEntityAttribute(ACCEPT_LINE_REGEX); if (s != null) { acceptLineRegex=Pattern.compile(s); } s=context.getResolvedEntityAttribute(SKIP_LINE_REGEX); if (s != null) { skipLineRegex=Pattern.compile(s); } ...
Parses each of the entity attributes.
public void createPartControl(Composite parent){ text=new Text(parent,SWT.MULTI | SWT.VERTICAL); text.setToolTipText("Paste Stack Trace here and execute action!"); makeActions(); contributeToActionBars(); }
This is a callback that will allow us to create the viewer and initialize it.
public static void doEntryOperations(String keyPrefix) throws Exception { Region r1=cache.getRegion(Region.SEPARATOR + REGION_NAME); for (int i=0; i < PUTS_PER_SERVER; i++) { r1.put(keyPrefix + i,keyPrefix + "val-" + i); } }
Do PUT operations
public static int daysBetween(DateValue date1,DateValue date2){ return fixedFromGregorian(date1) - fixedFromGregorian(date2); }
Calculates the number of days between two dates.
public boolean saveImage(OutputStream output,String format,double scale){ try { Dimension d=new Dimension((int)(scale * getWidth()),(int)(scale * getHeight())); BufferedImage img=getNewOffscreenBuffer(d.width,d.height); Graphics2D g=(Graphics2D)img.getGraphics(); Point2D p=new Point2D.Double(0,0); ...
Saves a copy of this display as an image to the specified output stream.
public void rejectedExecution(Runnable r,ThreadPoolExecutor e){ throw new RejectedExecutionException("Task " + r.toString() + " rejected from "+ e.toString()); }
Always throws RejectedExecutionException.
public Point2D.Double chop(Point2D.Double from){ Rectangle2D.Double r=getBounds(); return Geom.angleToPoint(r,Geom.pointToAngle(r,from)); }
This is a default implementation that chops the point at the rectangle returned by getBounds() of the figure. <p> Figures which have a non-rectangular shape need to override this method. <p> FIXME Invoke chop on each child and return the closest point.
private static String which(String classname,ClassLoader loader){ String classnameAsResource=classname.replace('.','/') + ".class"; if (loader == null) loader=ClassLoader.getSystemClassLoader(); URL it=loader.getResource(classnameAsResource); return it != null ? it.toString() : null; }
<p>Search the specified classloader for the given classname.</p>
public static int doubleSubG(double d1,double d2){ if (d1 == d2) { ConstantPoolManager.getInstance().addDynamicConstant(d1); return 0; } else { if (Double.isNaN(d1) || Double.isNaN(d2)) { return 1; } return doubleSubHelper(d1,d2); } }
Replacement function for double comparison
public Source findSourceByQName(QName qName){ return qNameTable.get(qName); }
If CompilerAPI.resolveMultiName() is successful, the QName result should be associated with a Source object. This method allows for quick lookups given a qname.
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:55:10.978 -0500",hash_original_method="124CFAD93358C90C664BE8C1CAE8945E",hash_generated_method="4983D95CB1196E5796EB9C6C952CAE2F") public String encode(){ String dayString; if (day < 10) { dayString="0" + day; } else daySt...
Get canonical string representation.
public boolean exportPkcs8(){ return jrbPkcs8.isSelected(); }
Has the user chosen to export to PKCS #8?
public DOMUnsupportedException(String msg){ this(null,msg); }
Constructs a new DOMUnsupportedException with the given detail message.
public void removeAssignedVirtualArray(String virtualArrayURI){ if ((virtualArrayURI != null) && (_assignedVirtualArrays != null)) { _assignedVirtualArrays.remove(virtualArrayURI); updateVirtualArrayTags(); } }
Removes the passed VirtualArray URI from the set of VirtualArrays assigned to the resource by the user
@Detainted public Optional<O> extractUntyped(@Tainted Map<String,?> jsonMap){ Object value=jsonMap.get(name); I castedValue; try { castedValue=typeIn.cast(value); } catch ( ClassCastException e) { throw new FormFieldException(String.format("Type error: got: %s, expected: %s",value.getClass().getSimple...
Convert and validate a raw user-supplied value from an untyped JSON map.
public final void forceSize(int size){ if (size > data.length * 8) { throw new IllegalArgumentException("Size exceeds byte[] store"); } else { this.size=size; } }
Forces the number of bits in this <tt>BitVector</tt>.
private void fillData(final Table table,final List<DLItem> listOfData){ final boolean itemsContainImage=itemsContainImage(); for ( final DLItem item : listOfData) { final TableItem tableItem=new TableItem(table,SWT.NONE); tableItem.setData(item); if (item.getBackground() != null) { tableItem.setB...
Fill a table with data
@SuppressWarnings({"unchecked"}) public static <T>T deserialize(File serializedFile) throws IOException { FileInputStream fis=new FileInputStream(serializedFile); BufferedInputStream bufStr=new BufferedInputStream(fis); InputStream underlyingStream=null; if (serializedFile.getName().endsWith(".gz")) { under...
Loads serialized Object from disk. File can be uncompressed, gzipped or bz2-compressed. Compressed files must have a .gz or .bz2 suffix.
public static <E>void mergeSort(final E[] chunk){ if (chunk == null) throw new IllegalArgumentException(); if (chunk.length == 0) return; GenericSorting.mergeSort(0,chunk.length,new MyIntComparator((Comparable[])chunk),new MySwapper((Object[])chunk)); return; }
In place merge sort.
public PrivateKeyUnencryptedException(String message){ super(message); }
Creates a new PrivateKeyUnencryptedException with the specified message.
public boolean login() throws LoginException { if (ApplicationProperties.getProperty("tmtbl.authenticate.ldap.provider") == null) return false; sLog.debug("Performing ldap authentication ... "); if (getCallbackHandler() == null) throw new LoginException("Error: no CallbackHandler available "); Callback[] ca...
Authenticate the user
public float[] keys(){ float[] keys=new float[size()]; float[] k=_set; Object[] values=_values; for (int i=k.length, j=0; i-- > 0; ) { if (isFull(values,i)) { keys[j++]=k[i]; } } return keys; }
returns the keys of the map.
protected String makeTickLabel(double val){ return makeTickLabel(val,false); }
Converts the given value to a tick label string.
public void runEmpty(){ puller.switchOf(); System.out.println("Switched of Url Puller"); }
Switch of the URL Puller to empty the internal queue.
protected static boolean isArrayAccessExpression(Expression expression){ return expression instanceof BinaryExpression && isArrayOp(((BinaryExpression)expression).getOperation().getType()); }
Returns true for expressions of the form x[...]
public final void removeCols(int[] cols){ int[] rows=new int[dataBox.numRows()]; for (int i=0; i < dataBox.numRows(); i++) { rows[i]=i; } int[] retainedCols=new int[variables.size() - cols.length]; int i=-1; for (int j=0; j < variables.size(); j++) { if (Arrays.binarySearch(cols,j) < 0) { reta...
Removes the given columns from the data set.
public void info(String tag,String message){ stream.println(String.format(LOG_FORMAT,tag,message)); }
Logs the message to the stream.
public static void forceMkdir(File directory) throws IOException { if (directory.exists()) { if (!directory.isDirectory()) { String message="File " + directory + " exists and is "+ "not a directory. Unable to create directory."; throw new IOException(message); } } else { if (!directory.mkdi...
Makes a directory, including any necessary but nonexistent parent directories. If a file already exists with specified name but it is not a directory then an IOException is thrown. If the directory cannot be created (or does not already exist) then an IOException is thrown.
public RemoteFileChannel(String hostname,File file,int uploadId) throws IOException { this(hostname,file.getPath(),uploadId); }
Open a remote file as a <code>FileChannel</code> for read/write access.
public CCTouchHandler(CCTouchDelegateProtocol delegate,int priority){ assert delegate != null : "Touch delegate may not be nil"; delegate_=delegate; priority_=priority; enabledSelectors_=ccTouchSelectorFlag.ccTouchSelectorNoneBit.getFlag(); }
initializes a TouchHandler with a delegate and a priority
public SimpleNaiveBayesClassifier(IndexReader indexReader,Analyzer analyzer,Query query,String classFieldName,String... textFieldNames){ this.indexReader=indexReader; this.indexSearcher=new IndexSearcher(this.indexReader); this.textFieldNames=textFieldNames; this.classFieldName=classFieldName; this.analyzer=a...
Creates a new NaiveBayes classifier.
public void loadNeededImages(IGame game){ loaded=false; IBoard board=game.getBoard(); int width=board.getWidth(); int height=board.getHeight(); if ((width * height) > ImageCache.MAX_SIZE) { int max_dim=(int)Math.sqrt(ImageCache.MAX_SIZE); width=height=max_dim; } for (int y=0; y < height; y++) { ...
Load all the images we'll need for the game and place them in the tracker
public void put(K key,V value){ List<V> values=(List<V>)map.get(key); if (values == null) { values=new ArrayList<V>(); map.put(key,values); } values.add(value); valuesSize++; }
Puts a value for a key. If there is more then one value, each additional value will be added as another value for the key.
@Override public void writeValueEdit(Object value){ Object[] customer=(Object[])value; m_oId=customer[0]; m_jTaxID.setText((String)customer[1]); m_jSearchkey.setText((String)customer[2]); m_jName.setText((String)customer[3]); String test=m_jName.getText(); m_jNotes.setText((String)customer[4]); m_jVisib...
Edit object
@SuppressWarnings("deprecation") private static Throwable executeReflectionCodeThreaded(ReflectionCode code,PrintStream out){ RunnerThread runnerThread=new RunnerThread(null); runnerThread.setup(code); try { runnerThread.start(); runnerThread.join(timeout); if (!runnerThread.runFinished) { if (L...
Executes code.runReflectionCode(). If no exception is thrown, returns null. Otherwise, returns the exception thrown.
public static boolean putFloat(Context context,String key,float value){ SharedPreferences settings=context.getSharedPreferences(PREFERENCE_NAME,Context.MODE_PRIVATE); SharedPreferences.Editor editor=settings.edit(); editor.putFloat(key,value); return editor.commit(); }
put float preferences
public static void writeLines(File file,Collection<?> lines,String lineEnding) throws IOException { writeLines(file,null,lines,lineEnding,false); }
Writes the <code>toString()</code> value of each item in a collection to the specified <code>File</code> line by line. The default VM encoding and the specified line ending will be used.