code
stringlengths
10
174k
nl
stringlengths
3
129k
private static GraphicsConfiguration detectScreen(){ PointerInfo pointer=MouseInfo.getPointerInfo(); if (pointer != null) { return pointer.getDevice().getDefaultConfiguration(); } return null; }
Detect the preferred screen by where the mouse is the moment the method is called. This is for multi-monitor support.
@Override public void bindView(ViewHolder viewHolder,List payloads){ super.bindView(viewHolder,payloads); viewHolder.image.setIcon(mIcon); viewHolder.name.setText(mIcon.getName()); }
binds the data of this item onto the viewHolder
public static void routeSchedule(TransitSchedule schedule,Network network,Map<String,Router> routers){ Counter counterRoute=new Counter("route # "); log.info("Routing all routes with referenced links..."); if (routers == null) { log.error("No routers given, routing cannot be completed!"); return; } for ( TransitLine transitLine : schedule.getTransitLines().values()) { for ( TransitRoute transitRoute : transitLine.getRoutes().values()) { if (!routers.containsKey(transitRoute.getTransportMode())) { throw new RuntimeException("No router defined for " + transitRoute.getTransportMode()); } if (transitRoute.getStops().size() > 0) { Router modeDependentRouter=routers.get(transitRoute.getTransportMode()); counterRoute.incCounter(); List<TransitRouteStop> routeStops=transitRoute.getStops(); List<Id<Link>> linkIdSequence=new LinkedList<>(); linkIdSequence.add(routeStops.get(0).getStopFacility().getLinkId()); for (int i=0; i < routeStops.size() - 1; i++) { if (routeStops.get(i).getStopFacility().getLinkId() == null) { log.warn("stop facility " + routeStops.get(i).getStopFacility().getName() + " ("+ routeStops.get(i).getStopFacility().getId()+ ") not referenced!"); linkIdSequence=null; break; } if (routeStops.get(i + 1).getStopFacility().getLinkId() == null) { log.warn("stop facility " + routeStops.get(i - 1).getStopFacility().getName() + " ("+ routeStops.get(i + 1).getStopFacility().getId()+ " not referenced!"); linkIdSequence=null; break; } Id<Link> currentLinkId=Id.createLinkId(routeStops.get(i).getStopFacility().getLinkId().toString()); Link currentLink=network.getLinks().get(currentLinkId); Link nextLink=network.getLinks().get(routeStops.get(i + 1).getStopFacility().getLinkId()); LeastCostPathCalculator.Path leastCostPath=modeDependentRouter.calcLeastCostPath(currentLink.getToNode(),nextLink.getFromNode()); List<Id<Link>> path=null; if (leastCostPath != null) { path=PTMapperUtils.getLinkIdsFromPath(leastCostPath); } if (path != null) linkIdSequence.addAll(path); linkIdSequence.add(nextLink.getId()); } if (linkIdSequence != null) { transitRoute.setRoute(RouteUtils.createNetworkRoute(linkIdSequence,network)); } } else { log.warn("Route " + transitRoute.getId() + " on line "+ transitLine.getId()+ " has no stop sequence"); } } } log.info("Routing all routes with referenced links... done"); }
Generates link sequences (network route) for all transit routes in the schedule, modifies the schedule. All stopFacilities used by a route must have a link referenced.
public void addExtension(ASN1ObjectIdentifier oid,boolean critical,ASN1Encodable value) throws IOException { this.addExtension(oid,critical,value.toASN1Primitive().getEncoded(ASN1Encoding.DER)); }
Add an extension with the given oid and the passed in value to be included in the OCTET STRING associated with the extension.
public void initiateRead(){ if (DEBUG_SHOW_PUBLIC_CALLS && log.isDebugEnabled()) { log.debug("initiateRead"); } issueReadOnlyRequest(); }
not sure when or if this gets called, but will issue a read to get latest time
protected double findSplitNominalNominal(int index) throws Exception { double bestVal=Double.MAX_VALUE, currVal; double[][] counts=new double[m_Instances.attribute(index).numValues() + 1][m_Instances.numClasses()]; double[] sumCounts=new double[m_Instances.numClasses()]; double[][] bestDist=new double[3][m_Instances.numClasses()]; int numMissing=0; for (int i=0; i < m_Instances.numInstances(); i++) { Instance inst=m_Instances.instance(i); if (inst.isMissing(index)) { numMissing++; counts[m_Instances.attribute(index).numValues()][(int)inst.classValue()]+=inst.weight(); } else { counts[(int)inst.value(index)][(int)inst.classValue()]+=inst.weight(); } } for (int i=0; i < m_Instances.attribute(index).numValues(); i++) { for (int j=0; j < m_Instances.numClasses(); j++) { sumCounts[j]+=counts[i][j]; } } System.arraycopy(counts[m_Instances.attribute(index).numValues()],0,m_Distribution[2],0,m_Instances.numClasses()); for (int i=0; i < m_Instances.attribute(index).numValues(); i++) { for (int j=0; j < m_Instances.numClasses(); j++) { m_Distribution[0][j]=counts[i][j]; m_Distribution[1][j]=sumCounts[j] - counts[i][j]; } currVal=ContingencyTables.entropyConditionedOnRows(m_Distribution); if (currVal < bestVal) { bestVal=currVal; m_SplitPoint=(double)i; for (int j=0; j < 3; j++) { System.arraycopy(m_Distribution[j],0,bestDist[j],0,m_Instances.numClasses()); } } } if (numMissing == 0) { System.arraycopy(sumCounts,0,bestDist[2],0,m_Instances.numClasses()); } m_Distribution=bestDist; return bestVal; }
Finds best split for nominal attribute and nominal class and returns value.
@Override public int compareTo(WbXmlExtensionDef ext){ int result; if (this.value == null && ext.getValue() == null) { result=0; } else if (this.value == null) { result=1; } else if (ext.getValue() == null) { result=-1; } else { result=new Integer(ext.getValue().length()).compareTo(this.getValue().length()); if (result == 0) { result=this.value.compareTo(ext.getValue()); } } return result; }
Comparable method that first check lengths and then normal lexicographic order. This way larger extensions are checked first in compactation methods.
public boolean isFromSave(){ return myRequestor instanceof SavingRequestor; }
Returns true if the VFS change described by the event is the save of a document.
public void clear() throws IOException { try { Lock writeLock=lockManager.getWriteLock(); try { dataStore.clear(); valueCache.clear(); valueIDCache.clear(); namespaceCache.clear(); namespaceIDCache.clear(); initBNodeParams(); setNewRevision(); } finally { writeLock.release(); } } catch ( InterruptedException e) { IOException ioe=new IOException("Failed to acquire write lock"); ioe.initCause(e); throw ioe; } }
Removes all values from the ValueStore.
public void testMovePointRightPosLess(){ String a="1231212478987482988429808779810457634781384756794987"; String b="123121247898748298842980877981045763478138475679498700"; int aScale=28; int shift=30; int resScale=0; BigDecimal aNumber=new BigDecimal(new BigInteger(a),aScale); BigDecimal bNumber=aNumber.movePointRight(shift); assertTrue("incorrect scale",bNumber.scale() == resScale); assertTrue("incorrect value",bNumber.unscaledValue().toString().equals(b)); }
Move the decimal point to the right; the shift value is positive
public TaskList restoreApplicationSnapshotSession(URI id,VolumeGroupSnapshotSessionRestoreParam input){ UriBuilder uriBuilder=client.uriBuilder(APP_SUPPORT_RESTORE_SNAPSHOT_SESSION_URL); return client.postURI(TaskList.class,input,uriBuilder.build(id)); }
Restores a snapshot session of an application. API Call: POST /volume-groups/block/{id}/protection/snap-sessions/restore
@Override protected void onStart(){ super.onStart(); Log.d(TAG,"onStart() - the activity is about to become visible"); }
Hook method called after onCreate() or after onRestart() (when the activity is being restarted from stopped state). Should re-acquire resources relinquished when activity was stopped (onStop()) or acquire those resources for the first time after onCreate().
public FlexibleNode removeChild(FlexibleNode n){ int numChildren=getChildCount(); FlexibleNode[] newChild=new FlexibleNode[numChildren - 1]; int j=0; boolean found=false; for (int i=0; i < numChildren; i++) { if (child[i] != n) { newChild[j]=child[i]; j++; } else found=true; } if (!found) throw new IllegalArgumentException("Nonexistent child"); n.setParent(null); child=newChild; return n; }
remove child
public Vector2 ceil(){ return new Vector2(Math.ceil(x),Math.ceil(z)); }
Rounds the X and Y values of this Vector2 up to the nearest integer value.
private void changeSelectedModsAutoUpdate(final Boolean autoUpdate){ final OffExtModConfsBean confsBean=LEnv.LAUNCHER_SETTINGS.get(LSettings.OFF_EXT_MOD_CONFS).cloneBean(); for ( final int row : table.getSelectedModelRows()) confsBean.getModuleConfForFolder(((ExtModRefBean)table.getModel().getValueAt(row,extModRefColIdx)).getFolder(),true).setAutoUpdate(autoUpdate); LEnv.LAUNCHER_SETTINGS.set(LSettings.OFF_EXT_MOD_CONFS,confsBean); rebuildTable(); }
Changes the auto-update property of the selected official external modules.
@Override public int onStartCommand(Intent intent,int flags,int startId){ Log_OC.d(TAG,"Starting command with id " + startId); if (!intent.hasExtra(KEY_ACCOUNT) || !intent.hasExtra(KEY_UPLOAD_TYPE) || !(intent.hasExtra(KEY_LOCAL_FILE) || intent.hasExtra(KEY_FILE))) { Log_OC.e(TAG,"Not enough information provided in intent"); return Service.START_NOT_STICKY; } int uploadType=intent.getIntExtra(KEY_UPLOAD_TYPE,-1); if (uploadType == -1) { Log_OC.e(TAG,"Incorrect upload type provided"); return Service.START_NOT_STICKY; } Account account=intent.getParcelableExtra(KEY_ACCOUNT); if (!AccountUtils.exists(account,getApplicationContext())) { return Service.START_NOT_STICKY; } String[] localPaths=null, remotePaths=null, mimeTypes=null; OCFile[] files=null; if (uploadType == UPLOAD_SINGLE_FILE) { if (intent.hasExtra(KEY_FILE)) { files=new OCFile[]{intent.getParcelableExtra(KEY_FILE)}; } else { localPaths=new String[]{intent.getStringExtra(KEY_LOCAL_FILE)}; remotePaths=new String[]{intent.getStringExtra(KEY_REMOTE_FILE)}; mimeTypes=new String[]{intent.getStringExtra(KEY_MIME_TYPE)}; } } else { if (intent.hasExtra(KEY_FILE)) { files=(OCFile[])intent.getParcelableArrayExtra(KEY_FILE); } else { localPaths=intent.getStringArrayExtra(KEY_LOCAL_FILE); remotePaths=intent.getStringArrayExtra(KEY_REMOTE_FILE); mimeTypes=intent.getStringArrayExtra(KEY_MIME_TYPE); } } FileDataStorageManager storageManager=new FileDataStorageManager(account,getContentResolver()); boolean forceOverwrite=intent.getBooleanExtra(KEY_FORCE_OVERWRITE,false); boolean isInstant=intent.getBooleanExtra(KEY_INSTANT_UPLOAD,false); int localAction=intent.getIntExtra(KEY_LOCAL_BEHAVIOUR,LOCAL_BEHAVIOUR_COPY); if (intent.hasExtra(KEY_FILE) && files == null) { Log_OC.e(TAG,"Incorrect array for OCFiles provided in upload intent"); return Service.START_NOT_STICKY; } else if (!intent.hasExtra(KEY_FILE)) { if (localPaths == null) { Log_OC.e(TAG,"Incorrect array for local paths provided in upload intent"); return Service.START_NOT_STICKY; } if (remotePaths == null) { Log_OC.e(TAG,"Incorrect array for remote paths provided in upload intent"); return Service.START_NOT_STICKY; } if (localPaths.length != remotePaths.length) { Log_OC.e(TAG,"Different number of remote paths and local paths!"); return Service.START_NOT_STICKY; } files=new OCFile[localPaths.length]; for (int i=0; i < localPaths.length; i++) { files[i]=obtainNewOCFileToUpload(remotePaths[i],localPaths[i],((mimeTypes != null) ? mimeTypes[i] : null),storageManager); if (files[i] == null) { return Service.START_NOT_STICKY; } } } OwnCloudVersion ocv=AccountUtils.getServerVersion(account); boolean chunked=FileUploader.chunkedUploadIsSupported(ocv); AbstractList<String> requestedUploads=new Vector<>(); String uploadKey=null; UploadFileOperation newUpload=null; try { for ( OCFile file : files) { uploadKey=buildRemoteName(account,file.getRemotePath()); newUpload=new UploadFileOperation(account,file,chunked,isInstant,forceOverwrite,localAction,getApplicationContext()); if (isInstant) { newUpload.setRemoteFolderToBeCreated(); } mPendingUploads.putIfAbsent(uploadKey,newUpload); newUpload.addDatatransferProgressListener(this); newUpload.addDatatransferProgressListener((FileUploaderBinder)mBinder); requestedUploads.add(uploadKey); } } catch ( IllegalArgumentException e) { Log_OC.e(TAG,"Not enough information provided in intent: " + e.getMessage()); return START_NOT_STICKY; } catch ( IllegalStateException e) { Log_OC.e(TAG,"Bad information provided in intent: " + e.getMessage()); return START_NOT_STICKY; } catch ( Exception e) { Log_OC.e(TAG,"Unexpected exception while processing upload intent",e); return START_NOT_STICKY; } if (requestedUploads.size() > 0) { Message msg=mServiceHandler.obtainMessage(); msg.arg1=startId; msg.obj=requestedUploads; mServiceHandler.sendMessage(msg); } Log_OC.i(TAG,"mPendingUploads size:" + mPendingUploads.size()); return Service.START_NOT_STICKY; }
Entry point to add one or several files to the queue of uploads. New uploads are added calling to startService(), resulting in a call to this method. This ensures the service will keep on working although the caller activity goes away.
public OMSpline(double[] llPoints,int units,int lType){ super(llPoints,units,lType); }
Create an OMSpline from a list of float lat/lon pairs. <p> NOTES: <ul> <li>llPoints array is converted into radians IN PLACE for more efficient handling internally if it's not already in radians! For even better performance, you should send us an array already in radians format! <li>If you want the curve to be connected (as a potato), you need to ensure that the first and last coordinate pairs are the same. </ul>
public OverloadScanner(TranspilationHandler logHandler,JSweetContext context){ super(logHandler,context,null); this.types=Types.instance(context); }
Creates a new overload scanner.
public void connected(){ if (false) Log.v("ddm-hello","Connected!"); if (false) { byte[] data=new byte[]{0,1,2,3,4,-4,-3,-2,-1,127}; Chunk testChunk=new Chunk(ChunkHandler.type("TEST"),data,1,data.length - 2); DdmServer.sendChunk(testChunk); } }
Called when the DDM server connects. The handler is allowed to send messages to the server.
public String nextString(char quote) throws JSONException { char c; StringBuilder sb=new StringBuilder(); for (; ; ) { c=this.next(); switch (c) { case 0: case '\n': case '\r': throw this.syntaxError("Unterminated string"); case '\\': c=this.next(); switch (c) { case 'b': sb.append('\b'); break; case 't': sb.append('\t'); break; case 'n': sb.append('\n'); break; case 'f': sb.append('\f'); break; case 'r': sb.append('\r'); break; case 'u': sb.append((char)Integer.parseInt(this.next(4),16)); break; case '"': case '\'': case '\\': case '/': sb.append(c); break; default : throw this.syntaxError("Illegal escape."); } break; default : if (c == quote) { return sb.toString(); } sb.append(c); } } }
Return the characters up to the next close quote character. Backslash processing is done. The formal JSON format does not allow strings in single quotes, but an implementation is allowed to accept them.
public List<IMessage> deleteAfter(IMessage message,int amount) throws RateLimitException, DiscordException, MissingPermissionsException { return deleteAfter(indexOf(message),amount); }
Bulk deletes messages in a sub list created from the provided message to the end of the list. (Note: Only 100 messages can be deleted at a time).
public boolean isMotorEnabled(){ return motorEnabled; }
Returns true if the motor is enabled.
public Engine(org.jdom2.Element e){ super(e); org.jdom2.Attribute a; if ((a=e.getAttribute(Xml.MODEL)) != null) { _model=a.getValue(); } if ((a=e.getAttribute(Xml.HP)) != null) { setHp(a.getValue()); } if ((a=e.getAttribute(Xml.LENGTH)) != null) { setLength(a.getValue()); } if ((a=e.getAttribute(Xml.TYPE)) != null) { setTypeName(a.getValue()); } if ((a=e.getAttribute(Xml.WEIGHT_TONS)) != null) { setWeightTons(a.getValue()); } if ((a=e.getAttribute(Xml.B_UNIT)) != null) { setBunit(a.getValue().equals(Xml.TRUE)); } if ((a=e.getAttribute(Xml.CONSIST)) != null) { Consist c=EngineManager.instance().getConsistByName(a.getValue()); if (c != null) { setConsist(c); if ((a=e.getAttribute(Xml.LEAD_CONSIST)) != null && a.getValue().equals(Xml.TRUE)) { _consist.setLead(this); } if ((a=e.getAttribute(Xml.CONSIST_NUM)) != null) { _consist.setConsistNumber(Integer.parseInt(a.getValue())); } } else { log.error("Consist " + a.getValue() + " does not exist"); } } addPropertyChangeListeners(); }
Construct this Entry from XML. This member has to remain synchronized with the detailed DTD in operations-engines.dtd
public static boolean parseSQString(PsiBuilder b,int l){ PsiBuilder.Marker m=b.mark(); boolean r=PerlParserImpl.string_sq_parsed(b,l); if (r && ((PerlBuilder)b).isReparseSQString()) { m.collapse(PARSABLE_STRING_USE_VARS); } else { m.drop(); } return r; }
Parses SQ string depending on reparseSQString flag of PerlBuilder
private void grow(){ XYZAddressable[] oldBuckets=this.buckets; this.buckets=new XYZAddressable[this.buckets.length * 2]; this.refreshFields(); for ( XYZAddressable oldBucket : oldBuckets) { if (oldBucket == null) { continue; } int index=getIndex(oldBucket.getX(),oldBucket.getY(),oldBucket.getZ()); XYZAddressable bucket=this.buckets[index]; while (bucket != null) { bucket=this.buckets[index=getNextIndex(index)]; } this.buckets[index]=oldBucket; } }
Doubles the size of the backing array and redistributes all contained values accordingly.
public boolean stem(){ return stem(0); }
Stem the word placed into the Stemmer buffer through calls to add(). Returns true if the stemming process resulted in a word different from the input. You can retrieve the result with getResultLength()/getResultBuffer() or toString().
public Path rootDirectory(){ RootDirectorySystem root=SystemManager.getCurrentSystem(RootDirectorySystem.class); return root.rootDirectory(); }
Gets the root directory.
public RealVector generateDenseRandomVector(int dimension,int seedLength,Random random){ RealVector randomVector=new RealVector(dimension); randomVector.sparseToDense(); for (int q=0; q < dimension; q++) randomVector.coordinates[q]=(float)(random.nextFloat() - 0.5) / (float)dimension; return randomVector; }
Generates a basic dense vector with values assigned at random to a real value between -1 and 1
public OverrideUrlLoadingResult shouldOverrideUrlLoading(ExternalNavigationParams params){ Intent intent; try { intent=Intent.parseUri(params.getUrl(),Intent.URI_INTENT_SCHEME); } catch ( Exception ex) { Log.w(TAG,"Bad URI " + params.getUrl(),ex); return OverrideUrlLoadingResult.NO_OVERRIDE; } boolean hasBrowserFallbackUrl=false; String browserFallbackUrl=IntentUtils.safeGetStringExtra(intent,EXTRA_BROWSER_FALLBACK_URL); if (browserFallbackUrl != null && UrlUtilities.isValidForIntentFallbackNavigation(browserFallbackUrl)) { hasBrowserFallbackUrl=true; } else { browserFallbackUrl=null; } OverrideUrlLoadingResult result=shouldOverrideUrlLoadingInternal(params,intent,hasBrowserFallbackUrl,browserFallbackUrl); if (result == OverrideUrlLoadingResult.NO_OVERRIDE && hasBrowserFallbackUrl && (params.getRedirectHandler() == null || !params.getRedirectHandler().shouldNotOverrideUrlLoading())) { return clobberCurrentTabWithFallbackUrl(browserFallbackUrl,params); } return result; }
Determines whether the URL needs to be sent as an intent to the system, and sends it, if appropriate.
public void start(){ super.start(); setupPortrayals(); }
start the simulation, setting up the portrayals and charts for a new run
private static StringBuffer asRegEx(String stringMatcherPattern,StringBuffer out){ boolean escaped=false; boolean quoting=false; int i=0; while (i < stringMatcherPattern.length()) { char ch=stringMatcherPattern.charAt(i++); if (ch == '*' && !escaped) { if (quoting) { out.append("\\E"); quoting=false; } out.append(".*"); escaped=false; continue; } else if (ch == '?' && !escaped) { if (quoting) { out.append("\\E"); quoting=false; } out.append("."); escaped=false; continue; } else if (ch == '\\' && !escaped) { escaped=true; continue; } else if (ch == '\\' && escaped) { escaped=false; if (quoting) { out.append("\\E"); quoting=false; } out.append("\\\\"); continue; } if (!quoting) { out.append("\\Q"); quoting=true; } if (escaped && ch != '*' && ch != '?' && ch != '\\') out.append('\\'); out.append(ch); escaped=ch == '\\'; } if (quoting) out.append("\\E"); return out; }
Translates a StringMatcher pattern (using '*' and '?') to a regex pattern string
public double[] distributionForInstance(Instance instance) throws Exception { int num_classes=(int)(0.5 * numClasses); int num_features=(int)(0.5 * numFeatures); double[] dist=new double[num_classes]; double[] currentData=new double[numFeatures]; double[] ranking=new double[num_classes]; for (int j=0; j < num_features; j++) { currentData[j]=instance.value(num_classes + j); currentData[num_features + j]=1 - currentData[j]; } SortPair[] sortedActivations=ARTActivateCategories(currentData); java.util.Arrays.sort(sortedActivations); double diff_act=sortedActivations[0].getValue() - sortedActivations[numCategories - 2].getValue(); int largest_activ=1; double activ_change=0; for (int i=1; i < numCategories; i++) { activ_change=(sortedActivations[0].getValue() - sortedActivations[i].getValue()) / sortedActivations[0].getValue(); if (activ_change > threshold * diff_act) { break; } largest_activ=largest_activ + 1; } double[] best_matches=new double[largest_activ]; java.util.Arrays.fill(best_matches,1); for (int i=0; i < largest_activ; i++) { best_matches[i]=sortedActivations[i].getValue(); } double sum_mat=sumArray(best_matches); int currentCategory=0; for (int i=0; i < largest_activ; i++) { best_matches[i]=best_matches[i] / sum_mat; currentCategory=sortedActivations[i].getOriginalIndex(); for (int j=0; j < num_classes; j++) { ranking[j]=ranking[j] + best_matches[i] * weightsB[currentCategory][j]; } } if (m_userankstoclass) { return ARAMm_Ranking2Class(ranking); } return ranking; }
Calculates the class membership probabilities for the given test instance.
public static Duration inf(){ return INFINITE; }
Returns an infinite duration of Long.MAX_VALUE days.
@SuppressWarnings("unchecked") protected T reset(){ this.index=0; this.size=-1; return (T)this; }
Resets the entry state.
@Override public String globalInfo(){ return "Outputs the predictions as CSV."; }
Returns a string describing the output generator.
public Peer(Gondola gondola,CoreMember cmember,Channel slaveChannel){ this(gondola,cmember,slaveChannel.getRemoteMemberId()); this.channel=slaveChannel; this.slaveMode=true; }
This contructor is called in response to an incoming request from a slave.
public void onProgress(int downloadId,long bytesWritten,long totalBytes){ }
Invoked when downloading is in progress.
public static void updateOpenViews(final INaviEdge edge,final ArrayList<IComment> comments) throws CouldntSaveDataException { try { final Pair<INaviModule,INaviModule> modules=getModules(edge); if (modules.first() != modules.second()) { return; } if ((modules.first() != null) && (modules.second() != null) && modules.first().isLoaded()) { final List<INaviEdge> edgelist=new ArrayList<INaviEdge>(); final Quad<Integer,IAddress,Integer,IAddress> refEdgeData=getEdgeData(edge); for ( final INaviView view : modules.first().getContent().getViewContainer().getViews()) { edgelist.addAll(collectEdges(view,refEdgeData)); } for ( final INaviEdge updateEdge : edgelist) { updateEdge.initializeGlobalComment(comments); } } } catch ( final MaybeNullException exception) { } }
Pushes a new global edge comment to all open views.
@Override public void onDrawEye(Eye eye){ GLES20.glEnable(GLES20.GL_DEPTH_TEST); GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT); checkGLError("colorParam"); Matrix.multiplyMM(view,0,eye.getEyeView(),0,camera,0); Matrix.multiplyMV(lightPosInEyeSpace,0,view,0,LIGHT_POS_IN_WORLD_SPACE,0); float[] perspective=eye.getPerspective(Z_NEAR,Z_FAR); Matrix.multiplyMM(modelView,0,view,0,modelCube,0); Matrix.multiplyMM(modelViewProjection,0,perspective,0,modelView,0); Matrix.multiplyMM(modelView,0,view,0,modelFloor,0); Matrix.multiplyMM(modelViewProjection,0,perspective,0,modelView,0); drawFloor(); float[] videoMVP=new float[16]; Matrix.multiplyMM(videoMVP,0,view,0,videoScreenModelMatrix,0); Matrix.multiplyMM(videoMVP,0,perspective,0,videoMVP,0); mVideoRenderer.setMVPMatrix(videoMVP); if (renderSereo) mVideoRenderer.render(eye.getType()); else mVideoRenderer.render(1); }
Draws a frame for an eye.
public ReferenceMatch(IJavaElement enclosingElement,int accuracy,int offset,int length,boolean insideDocComment,SearchParticipant participant,IResource resource){ super(enclosingElement,accuracy,offset,length,participant,resource); setInsideDocComment(insideDocComment); }
Creates a new reference match.
public static byte[] serializeToBytes(final SerializableEntity entity){ try { try (BinarySerializer binarySerializer=new BinarySerializer()){ entity.serialize(binarySerializer); return binarySerializer.getBytes(); } } catch ( final Exception e) { throw new SerializationException(e); } }
Helper function that serializes a SerializableEntity to a byte array.
public RegexValidator(String regex,boolean caseSensitive){ this(new String[]{regex},caseSensitive); }
Construct a validator for a single regular expression with the specified case sensitivity.
public Long2LongOpenHashMap(final int expected,final float f){ if (f <= 0 || f > 1) throw new IllegalArgumentException("Load factor must be greater than 0 and smaller than or equal to 1"); if (expected < 0) throw new IllegalArgumentException("The expected number of elements must be nonnegative"); this.f=f; n=arraySize(expected,f); mask=n - 1; maxFill=maxFill(n,f); key=new long[n + 1]; value=new long[n + 1]; }
Creates a new hash map. <p>The actual table size will be the least power of two greater than <code>expected</code>/<code>f</code>.
public void testSingleMultiPolygonManyPointsHolesRoundTrip() throws SQLException { PolygonGenerator pgc=new PolygonGenerator(); pgc.setGeometryFactory(geometryFactory); pgc.setGenerationAlgorithm(PolygonGenerator.BOX); pgc.setNumberPoints(1000); pgc.setNumberHoles(4); MultiGenerator pg=new MultiGenerator(pgc); pg.setBoundingBox(new Envelope(0,10,0,10)); pg.setNumberGeometries(3); pg.setGeometryFactory(geometryFactory); MultiPolygon pt=(MultiPolygon)pg.create(); OraWriter ow=new OraWriter(); STRUCT st=ow.write(pt,getConnection()); OraReader or=new OraReader(); MultiPolygon pt2=(MultiPolygon)or.read(st); assertTrue("The input MultiPolygon is not the same as the output MultiPolygon",pt.equals(pt2)); }
Round Trip test for a single MultiPolygon with lotsa points
public boolean shouldPromoteGrandchildren(){ return false; }
Returns whether or not this View type should promote its grandchildren as Views. This is an optimization for Scrollable containers when using Nodes, where instead of having one ViewGroup containing a large number of draw commands (and thus being more expensive in the case of an invalidate or re-draw), we split them up into several draw commands.
public static int[] transformIntArray(Integer[] source){ int[] destin=new int[source.length]; for (int i=0; i < source.length; i++) { destin[i]=source[i]; } return destin; }
convert Integer array to int array
public static BufferedImage renderImageToOutput(String url,FSImageWriter fsw,String path,int width) throws IOException { BufferedImage image; OutputStream os=null; try { Java2DRenderer renderer=new Java2DRenderer(url,url,width); os=new BufferedOutputStream(new FileOutputStream(path)); image=renderer.getImage(); fsw.write(image,os); return image; } finally { if (os != null) { try { os.close(); } catch ( IOException e) { } } } }
Renders a document at a given URL and writes it out using the FSImageWriter provided (e.g. to a file or outputstream).
private Exception parametersMethodReturnedWrongType(FrameworkMethod parametersMethod) throws Exception { String className=getTestClass().getName(); String message=MessageFormat.format("{0}.{1}() must return an Iterable of arrays.",className,parametersMethod.getName()); return new Exception(message); }
Implements behavior from: org.junit.runners.Parameterized
public static <T extends SerializableEntity>Deserializer roundtripSerializableEntity(final T originalEntity,final AccountLookup accountLookup){ final JsonSerializer jsonSerializer=new JsonSerializer(true); originalEntity.serialize(jsonSerializer); return new JsonDeserializer(jsonSerializer.getObject(),new DeserializationContext(accountLookup)); }
Serializes originalEntity and returns a Deserializer that can deserialize it.
public IonSystemBuilder mutable(){ return copy(); }
Returns a mutable builder configured exactly like this one.
@Override public void run(){ amIActive=true; String inputHeader=null; String outputHeader=null; double zConvFactor=1; if (args.length <= 0) { showFeedback("Plugin parameters have not been set."); return; } inputHeader=args[0]; outputHeader=args[1]; zConvFactor=Double.parseDouble(args[2]); if ((inputHeader == null) || (outputHeader == null)) { showFeedback("One or more of the input parameters have not been set properly."); return; } try { int row, col; double z; double[] N=new double[8]; double fx, fy; float slope; float progress=0; int[] Dy={-1,0,1,1,1,0,-1,-1}; int[] Dx={1,1,1,0,-1,-1,-1,0}; final double radToDeg=180 / Math.PI; WhiteboxRaster inputFile=new WhiteboxRaster(inputHeader,"r"); inputFile.isReflectedAtEdges=true; int rows=inputFile.getNumberRows(); int cols=inputFile.getNumberColumns(); double gridRes=inputFile.getCellSizeX(); double eightGridRes=8 * gridRes; double noData=inputFile.getNoDataValue(); if (inputFile.getXYUnits().toLowerCase().contains("deg") || inputFile.getProjection().toLowerCase().contains("geog")) { double midLat=(inputFile.getNorth() - inputFile.getSouth()) / 2.0; if (midLat <= 90 && midLat >= -90) { zConvFactor=1.0 / (113200 * Math.cos(Math.toRadians(midLat))); } } WhiteboxRaster outputFile=new WhiteboxRaster(outputHeader,"rw",inputHeader,WhiteboxRaster.DataType.FLOAT,noData); outputFile.setPreferredPalette("spectrum.pal"); for (row=0; row < rows; row++) { for (col=0; col < cols; col++) { z=inputFile.getValue(row,col); if (z != noData) { for (int i=0; i < 8; i++) { N[i]=inputFile.getValue(row + Dy[i],col + Dx[i]); if (N[i] != noData) { N[i]=N[i] * zConvFactor; } else { N[i]=z * zConvFactor; } } fy=(N[6] - N[4] + 2 * (N[7] - N[3]) + N[0] - N[2]) / eightGridRes; fx=(N[2] - N[4] + 2 * (N[1] - N[5]) + N[0] - N[6]) / eightGridRes; slope=(float)(Math.atan(Math.sqrt(fx * fx + fy * fy)) * radToDeg); outputFile.setValue(row,col,slope); } else { outputFile.setValue(row,col,noData); } } if (cancelOp) { cancelOperation(); return; } progress=(float)(100f * row / (rows - 1)); updateProgress((int)progress); } outputFile.addMetadataEntry("Created by the " + getDescriptiveName() + " tool."); outputFile.addMetadataEntry("Created on " + new Date()); inputFile.close(); outputFile.close(); returnData(outputHeader); } catch ( OutOfMemoryError oe) { myHost.showFeedback("An out-of-memory error has occurred during operation."); } catch ( Exception e) { myHost.showFeedback("An error has occurred during operation. See log file for details."); myHost.logException("Error in " + getDescriptiveName(),e); } finally { updateProgress("Progress: ",0); amIActive=false; myHost.pluginComplete(); } }
Used to execute this plugin tool.
public static String convertUPCEtoUPCA(String upce){ char[] upceChars=new char[6]; upce.getChars(1,7,upceChars,0); StringBuilder result=new StringBuilder(12); result.append(upce.charAt(0)); char lastChar=upceChars[5]; switch (lastChar) { case '0': case '1': case '2': result.append(upceChars,0,2); result.append(lastChar); result.append("0000"); result.append(upceChars,2,3); break; case '3': result.append(upceChars,0,3); result.append("00000"); result.append(upceChars,3,2); break; case '4': result.append(upceChars,0,4); result.append("00000"); result.append(upceChars[4]); break; default : result.append(upceChars,0,5); result.append("0000"); result.append(lastChar); break; } result.append(upce.charAt(7)); return result.toString(); }
Expands a UPC-E value back into its full, equivalent UPC-A code value.
public Object clone() throws CloneNotSupportedException { mxCell clone=(mxCell)super.clone(); clone.setValue(cloneValue()); clone.setStyle(getStyle()); clone.setCollapsed(isCollapsed()); clone.setConnectable(isConnectable()); clone.setEdge(isEdge()); clone.setVertex(isVertex()); clone.setVisible(isVisible()); clone.setParent(null); clone.setSource(null); clone.setTarget(null); clone.children=null; clone.edges=null; mxGeometry geometry=getGeometry(); if (geometry != null) { clone.setGeometry((mxGeometry)geometry.clone()); } return clone; }
Returns a clone of the cell.
public JIPJVMException(final Throwable ex){ m_ex=ex; }
Constructs a new JIPJVMException
public List<Interval> merge(List<Interval> intervals){ List<Interval> res=new ArrayList<>(); if (intervals == null || intervals.size() == 0) { return res; } Collections.sort(intervals,null); Interval prev=null; for ( Interval i : intervals) { if (prev == null || prev.end < i.start) { res.add(i); prev=i; } else if (i.end > prev.end) { prev.end=i.end; } } return res; }
Sort and merge, O(nlogn) time. Sort the intervals according to the start value in asc order. For each of the intervals, 1) add to result directly if the result list is empty. 2) add to result directly if there is no overlap between current interval and previous interval. 3) If there is overlap, we already know current interval's start is larger than previous interval. We need to update the end of previous interval if current interval's end is larger.
protected Date compute(String dateString,String localeString){ if (dateString == null || localeString == null) { return null; } Locale locale=new Locale(localeString); Date date; try { date=((DateFormat)DateFormat.getDateInstance(DateFormat.SHORT,locale).clone()).parse(dateString); Calendar cal=Calendar.getInstance(locale); cal.setTime(date); return cal.getTime(); } catch ( ParseException e) { throw new FunctionInputException("invalid_argument.date",getFunctionName()); } }
Computes the result for a string input value and a locale string.
public TaskResourceRep removeInitiatorDecline(URI initiator,URI eventId){ return null; }
Decline method that is invoked when the removeInitiator event is declined NOTE: In order to maintain backwards compatibility, do not change the signature of this method.
public void testSetNCharacterStream() throws Exception { createTable("testSetNCharacterStream","(c1 NATIONAL CHARACTER(10), c2 NATIONAL CHARACTER(10), c3 NATIONAL CHARACTER(10)) ENGINE=InnoDB"); Properties props1=new Properties(); props1.put("useServerPrepStmts","false"); props1.put("useUnicode","true"); props1.put("characterEncoding","latin1"); Connection conn1=getConnectionWithProps(props1); com.mysql.jdbc.PreparedStatement pstmt1=(com.mysql.jdbc.PreparedStatement)conn1.prepareStatement("INSERT INTO testSetNCharacterStream (c1, c2, c3) VALUES (?, ?, ?)"); pstmt1.setNCharacterStream(1,null,0); pstmt1.setNCharacterStream(2,new StringReader("aaa"),3); pstmt1.setNCharacterStream(3,new StringReader("\'aaa\'"),5); pstmt1.execute(); ResultSet rs1=this.stmt.executeQuery("SELECT c1, c2, c3 FROM testSetNCharacterStream"); rs1.next(); assertEquals(null,rs1.getString(1)); assertEquals("aaa",rs1.getString(2)); assertEquals("\'aaa\'",rs1.getString(3)); rs1.close(); pstmt1.close(); conn1.close(); createTable("testSetNCharacterStream","(c1 NATIONAL CHARACTER(10), c2 NATIONAL CHARACTER(10), c3 NATIONAL CHARACTER(10)) ENGINE=InnoDB"); Properties props2=new Properties(); props2.put("useServerPrepStmts","false"); props2.put("useUnicode","true"); props2.put("characterEncoding","UTF-8"); Connection conn2=getConnectionWithProps(props2); com.mysql.jdbc.PreparedStatement pstmt2=(com.mysql.jdbc.PreparedStatement)conn2.prepareStatement("INSERT INTO testSetNCharacterStream (c1, c2, c3) VALUES (?, ?, ?)"); pstmt2.setNCharacterStream(1,null,0); pstmt2.setNCharacterStream(2,new StringReader("aaa"),3); pstmt2.setNCharacterStream(3,new StringReader("\'aaa\'"),5); pstmt2.execute(); ResultSet rs2=this.stmt.executeQuery("SELECT c1, c2, c3 FROM testSetNCharacterStream"); rs2.next(); assertEquals(null,rs2.getString(1)); assertEquals("aaa",rs2.getString(2)); assertEquals("\'aaa\'",rs2.getString(3)); rs2.close(); pstmt2.close(); conn2.close(); }
Tests for PreparedStatement.setNCharacterSteam()
protected void updateOverlayContents(LookAt lookAt,Camera camera){ latView.setText(formatLatitude(lookAt.latitude)); lonView.setText(formatLongitude(lookAt.longitude)); altView.setText(formatAltitude(camera.altitude)); }
Displays navigator state information in the status overlay views.
public static IJavaSearchScope createRelatedProjectsScope(IJavaProject project,int includeMask) throws CoreException { IJavaProject[] projects=getRelatedProjects(project); return SearchEngine.createJavaSearchScope(projects,includeMask); }
Creates a new search scope containing all projects which reference or are referenced by the specified project.
private void readObject(ObjectInputStream in) throws ClassNotFoundException, IOException { in.defaultReadObject(); dataUpdated(this); }
Custom deserialization method.
public void removeFirstLines(Document doc,int amount){ if (amount < 1) { amount=1; } Element firstToRemove=doc.getDefaultRootElement().getElement(0); Element lastToRemove=doc.getDefaultRootElement().getElement(amount - 1); int startOffset=firstToRemove.getStartOffset(); int endOffset=lastToRemove.getEndOffset(); try { doc.remove(startOffset,endOffset); } catch ( BadLocationException ex) { Logger.getLogger(ChannelTextPane.class.getName()).log(Level.SEVERE,null,ex); } }
Removes the given number of lines from the given Document.
private static String testTZ(String timeZoneName,Locale locale){ StringBuffer timeZoneResult=new StringBuffer(""); TimeZone tz=TimeZone.getTimeZone(timeZoneName); sdfEn.setTimeZone(tz); sdfEnShort.setTimeZone(tz); sdfLoc.setTimeZone(tz); sdfLocShort.setTimeZone(tz); String en, enShort, loc, locShort; en=sdfEn.format(date); enShort=sdfEnShort.format(date); loc=sdfLoc.format(date); locShort=sdfLocShort.format(date); String displayLanguage=locale.getDisplayLanguage(); String displayCountry=locale.getDisplayCountry(); if (loc.equals(en)) { timeZoneResult.append("["); timeZoneResult.append(displayLanguage); if (!"".equals(displayCountry)) { timeZoneResult.append(" "); timeZoneResult.append(displayCountry); } timeZoneResult.append("] timezone \""); timeZoneResult.append(timeZoneName); timeZoneResult.append("\" long name \"" + en); timeZoneResult.append("\" not localized!\n"); } if (!locShort.equals(enShort)) { timeZoneResult.append("["); timeZoneResult.append(displayLanguage); if (!"".equals(displayCountry)) { timeZoneResult.append(" "); timeZoneResult.append(displayCountry); } timeZoneResult.append("] timezone \""); timeZoneResult.append(timeZoneName); timeZoneResult.append("\" short name \"" + enShort); timeZoneResult.append("\" is localized \""); timeZoneResult.append(locShort); timeZoneResult.append("\"!\n"); } return timeZoneResult.toString(); }
Compares the english timezone name and timezone name in specified locale
public TimeSeriesPlotPanel(final TimeSeriesModel timeSeriesModel){ model=timeSeriesModel; setPreferredSize(PREFERRED_SIZE); setLayout(new BorderLayout()); addAddDeleteButtons(); addClearGraphDataButton(); addPreferencesButton(); add("Center",chartPanel); add("South",buttonPanel); init(); }
Construct a time series panel.
public void load(){ String swcPath=filePath(Swc.CATALOG_XML); File c=new File(swcPath); if (!c.exists()) { throw new SwcException.NotASwcDirectory(dir); } fileList=new HashSet<String>(); readFiles(fileList,"",new File(dir)); }
Populates the fileList.
private RVMMethod resolveInterfaceMethodInternal(RVMClass declaringClass){ RVMMethod it=declaringClass.findDeclaredMethod(name,descriptor); if (it != null) { resolvedMember=it; return resolvedMember; } for ( RVMClass intf : declaringClass.getDeclaredInterfaces()) { it=searchInterfaceMethods(intf); if (it != null) { resolvedMember=it; return resolvedMember; } } return null; }
Find the RVMMethod that this member reference refers to using the search order specified in JVM spec 5.4.3.4.
@Override public final double valueSparse(int indexOfIndex){ return 1; }
Returns an instance's attribute value in internal format. Does exactly the same thing as value() if applied to an Instance.
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.
int paramSize(){ int result=0; for ( Local<?> local : parameters) { result+=local.size(); } return result; }
Returns the number of registers to hold the parameters. This includes the 'this' parameter if it exists.
public void runTest() throws Throwable { Document doc; NodeList elementList; Node employeeNode; NodeList employeeList; Node child; String childName; int length; doc=(Document)load("staff",false); elementList=doc.getElementsByTagName("employee"); employeeNode=elementList.item(2); employeeList=employeeNode.getChildNodes(); child=employeeList.item(0); childName=child.getNodeName(); length=(int)employeeList.getLength(); if (equals(6,length)) { assertEqualsIgnoreCase("firstChildNoWhitespace","employeeId",childName); } else { assertEqualsIgnoreCase("firstChildWithWhitespace","#text",childName); } }
Runs the test case.
public static byte[] readAllLimited(InputStream inStr,int limit) throws IOException { ByteArrayOutputStream buf=new ByteArrayOutputStream(); pipeAllLimited(inStr,limit,buf); return buf.toByteArray(); }
Read from inStr up to a maximum number of bytes, throwing an exception if more the maximum amount of requested data is available.
protected static char[] encodeHex(final byte[] data,final char[] toDigits){ final int l=data.length; final char[] out=new char[l << 1]; for (int i=0, j=0; i < l; i++) { out[j++]=toDigits[(0xF0 & data[i]) >>> 4]; out[j++]=toDigits[0x0F & data[i]]; } return out; }
Converts an array of bytes into an array of characters representing the hexadecimal values of each byte in order. The returned array will be double the length of the passed array, as it takes two characters to represent any given byte.
@Override public void onConnectionFailed(ConnectionResult connectionResult){ ToastUtils.showShort("Could not connect to Google API Client: Error " + connectionResult.getErrorCode()); GooglePlacesActivity.this.finish(); }
Called when the Activity could not connect to Google Play services and the auto manager could resolve the error automatically. In this case the API is not available and notify the user.
public static double[][] arrayCopy(double[][] src){ double[][] dest=new double[src.length][]; for (int r=0; r < src.length; r++) { dest[r]=new double[src[r].length]; System.arraycopy(src[r],0,dest[r],0,src[r].length); } return dest; }
Copies all rows and columns between two double arrays
public static List<Ignite> allGridsx(){ return allGrids(false); }
Gets a list of all grids started so far.
public synchronized void remove(IAudioProcessor processor){ processors.remove(processor); buildFinalProcessor(); }
Removes the provided processor from the internal processor queue.
@Override public void onDestroy(){ if (mAdView != null) { mAdView.destroy(); } super.onDestroy(); }
Called before the activity is destroyed
public URIBuilder addParameter(final String param,final String value){ if (this.queryParams == null) { this.queryParams=new ArrayList<NameValuePair>(); } this.queryParams.add(new BasicNameValuePair(param,value)); this.encodedQuery=null; this.encodedSchemeSpecificPart=null; return this; }
Adds parameter to URI query. The parameter name and value are expected to be unescaped and may contain non ASCII characters.
public boolean copyFile(String source,String destination,boolean remountAsRw,boolean preserveFileAttributes){ CommandCapture command=null; boolean result=true; try { if (remountAsRw) { RootTools.remount(destination,"RW"); } if (checkUtil("cp")) { RootTools.log("cp command is available!"); if (preserveFileAttributes) { command=new CommandCapture(0,false,"cp -fp " + source + " "+ destination); Shell.startRootShell().add(command); commandWait(Shell.startRootShell(),command); result=command.getExitCode() == 0; } else { command=new CommandCapture(0,false,"cp -f " + source + " "+ destination); Shell.startRootShell().add(command); commandWait(Shell.startRootShell(),command); result=command.getExitCode() == 0; } } else { if (checkUtil("busybox") && hasUtil("cp","busybox")) { RootTools.log("busybox cp command is available!"); if (preserveFileAttributes) { command=new CommandCapture(0,false,"busybox cp -fp " + source + " "+ destination); Shell.startRootShell().add(command); commandWait(Shell.startRootShell(),command); } else { command=new CommandCapture(0,false,"busybox cp -f " + source + " "+ destination); Shell.startRootShell().add(command); commandWait(Shell.startRootShell(),command); } } else { if (checkUtil("cat")) { RootTools.log("cp is not available, use cat!"); int filePermission=-1; if (preserveFileAttributes) { Permissions permissions=getFilePermissionsSymlinks(source); filePermission=permissions.getPermissions(); } command=new CommandCapture(0,false,"cat " + source + " > "+ destination); Shell.startRootShell().add(command); commandWait(Shell.startRootShell(),command); if (preserveFileAttributes) { command=new CommandCapture(0,false,"chmod " + filePermission + " "+ destination); Shell.startRootShell().add(command); commandWait(Shell.startRootShell(),command); } } else { result=false; } } } if (remountAsRw) { RootTools.remount(destination,"RO"); } } catch ( Exception e) { e.printStackTrace(); result=false; } if (command != null) { result=command.getExitCode() == 0; } return result; }
Copys a file to a destination. Because cp is not available on all android devices, we have a fallback on the cat command
protected int nextInDocumentStart() throws IOException, XMLException { switch (current) { case 0x9: case 0xA: case 0xD: case 0x20: do { nextChar(); } while (current != -1 && XMLUtilities.isXMLSpace((char)current)); context=(depth == 0) ? TOP_LEVEL_CONTEXT : CONTENT_CONTEXT; return LexicalUnits.S; case '<': switch (nextChar()) { case '?': int c1=nextChar(); if (c1 == -1 || !XMLUtilities.isXMLNameFirstCharacter((char)c1)) { throw createXMLException("invalid.pi.target"); } context=PI_CONTEXT; int c2=nextChar(); if (c2 == -1 || !XMLUtilities.isXMLNameCharacter((char)c2)) { return LexicalUnits.PI_START; } int c3=nextChar(); if (c3 == -1 || !XMLUtilities.isXMLNameCharacter((char)c3)) { return LexicalUnits.PI_START; } int c4=nextChar(); if (c4 != -1 && XMLUtilities.isXMLNameCharacter((char)c4)) { do { nextChar(); } while (current != -1 && XMLUtilities.isXMLNameCharacter((char)current)); return LexicalUnits.PI_START; } if (c1 == 'x' && c2 == 'm' && c3 == 'l') { context=XML_DECL_CONTEXT; return LexicalUnits.XML_DECL_START; } if ((c1 == 'x' || c1 == 'X') && (c2 == 'm' || c2 == 'M') && (c3 == 'l' || c3 == 'L')) { throw createXMLException("xml.reserved"); } return LexicalUnits.PI_START; case '!': switch (nextChar()) { case '-': return readComment(); case 'D': context=DOCTYPE_CONTEXT; return readIdentifier("OCTYPE",LexicalUnits.DOCTYPE_START,-1); default : throw createXMLException("invalid.doctype"); } default : context=START_TAG_CONTEXT; depth++; return readName(LexicalUnits.START_TAG); } case -1: return LexicalUnits.EOF; default : if (depth == 0) { throw createXMLException("invalid.character"); } else { return nextInContent(); } } }
Reads the first token in the stream.
public static int min(int a,int b,int c){ if (a < b) return Math.min(a,c); else return Math.min(b,c); }
<p> min </p>
public static ChainingJsonStringParser parseJson(String json){ return new ChainingJsonStringParser(json); }
Parses a jCal data stream (JSON-encoded iCalendar objects).
@NonNull public static String cleanupTag(@NonNull final Object value,final char firstCharacter){ final String tag=((String)value); String cleanedTag=tag.trim().toLowerCase(); while (cleanedTag.startsWith("##") || cleanedTag.startsWith("@@")) { cleanedTag=cleanedTag.substring(1); } final StringBuffer sb=new StringBuffer(cleanedTag.length()); boolean first=true; for ( char c : cleanedTag.toCharArray()) { if (!Character.isLetter(c)) { if (!first && Character.isDigit(c)) { sb.append(c); } continue; } sb.append(c); first=false; } String s=sb.toString(); if (!s.startsWith("" + firstCharacter)) { s=firstCharacter + s; } if (!s.equals(tag)) { return s; } return tag; }
Return the original object if no cleanup is done, or for example "" if there are zero characters worth keeping after cleanup <p> Cleanup means conformance to "#tagnumberlowercasedigitsnotinfirstposition"
public boolean isType(int type){ if (this.type == 0) { return false; } return (this.type & typeToBitMask(type)) != 0; }
Returns true if this node is of given type, false if none of node's type(s) match to given type or node doesn't have type at all
private int init(File f) throws IOException { Runtime rt=Runtime.getRuntime(); long prePhraseTableLoadMemUsed=rt.totalMemory() - rt.freeMemory(); final long startTime=System.nanoTime(); LineNumberReader reader=IOTools.getReaderFromFile(f); int numScores=-1; for (String line; (line=reader.readLine()) != null; ) { List<List<String>> fields=StringUtils.splitFieldsFast(line,CompiledPhraseTable.FIELD_DELIM); assert fields.size() == 5 : String.format("phrase table line %d has %d fields: %s",reader.getLineNumber(),fields.size(),line); Sequence<IString> source=IStrings.toIStringSequence(fields.get(0)); Sequence<IString> target=IStrings.toIStringSequence(fields.get(1)); String targetConstellation=StringUtils.join(fields.get(3)); List<String> scoreList=fields.get(4); if (numScores < 0) { numScores=scoreList.size(); } else if (numScores != scoreList.size()) { throw new RuntimeException(String.format("Error (line %d): Each entry must have exactly the same number of translation\n" + "scores per line. Prior entries had %d, while the current entry has %d:",reader.getLineNumber(),numScores,scoreList.size())); } float[] scores; try { scores=IOTools.stringListToNumeric(scoreList); } catch ( NumberFormatException e) { e.printStackTrace(); throw new RuntimeException(String.format("Number format error on line %d",reader.getLineNumber())); } if (targetConstellation.equals("")) { addEntry(source,target,null,scores); } else { addEntry(source,target,PhraseAlignment.getPhraseAlignment(targetConstellation),scores); } if (source.size() > longestSourcePhrase) { longestSourcePhrase=source.size(); } if (target.size() > longestTargetPhrase) { longestTargetPhrase=target.size(); } } reader.close(); long postPhraseTableLoadMemUsed=rt.totalMemory() - rt.freeMemory(); double elapsedTime=((double)System.nanoTime() - startTime) / 1e9; System.err.printf("Done loading phrase table: %s (mem used: %d MiB time: %.3f s)%n",f.getAbsolutePath(),(postPhraseTableLoadMemUsed - prePhraseTableLoadMemUsed) / (1024 * 1024),elapsedTime); System.err.println("Longest foreign phrase: " + longestSourcePhrase); return numScores; }
Load the phrase table from file.
protected VersionInfo(String pckg,String module,String release,String time,String clsldr){ if (pckg == null) { throw new IllegalArgumentException("Package identifier must not be null."); } infoPackage=pckg; infoModule=(module != null) ? module : UNAVAILABLE; infoRelease=(release != null) ? release : UNAVAILABLE; infoTimestamp=(time != null) ? time : UNAVAILABLE; infoClassloader=(clsldr != null) ? clsldr : UNAVAILABLE; }
Instantiates version information.
private static List<Command> loadRewrites(ContentResolver contentResolver,Uri uri) throws IOException { InputStream inputStream=contentResolver.openInputStream(uri); List<Command> commands=new ArrayList<>(); if (inputStream != null) { BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line=reader.readLine()) != null) { addLine(commands,line); } inputStream.close(); } return commands; }
Loads the rewrites from an URI using a ContentResolver.
public void insert(T object,int index){ synchronized (mLock) { mObjects.add(index,object); } if (mNotifyOnChange) notifyItemInserted(index); }
Inserts the specified object at the specified index in the array.
public static int ESHUTDOWN(){ return Errno.ESHUTDOWN.intValue(); }
Cannot send after transport endpoint shutdown
public WBMPImageWriter(ImageWriterSpi originator){ super(originator); }
Constructs <code>WBMPImageWriter</code> based on the provided <code>ImageWriterSpi</code>.
public ArithmeticException(){ super(); }
Constructs an <code>ArithmeticException</code> with no detail message.
private boolean isLoggable(){ return Log.isLoggable(tag,level); }
Returns true if logging is turned on for this configuration.
public ImageLoadQueue(){ this._loadQueue=new LinkedList(); }
Intantiates a new queue.
public void onDrawerClosed(View view){ super.onDrawerClosed(view); }
Called when a drawer has settled in a completely closed state.
@Override public synchronized void initialize(){ if (!mRootDirectory.exists()) { if (!mRootDirectory.mkdirs()) { VinciLog.e("Unable to create cache dir %s",mRootDirectory.getAbsolutePath()); } return; } File[] files=mRootDirectory.listFiles(); if (files == null) { return; } for ( File file : files) { BufferedInputStream fis=null; try { fis=new BufferedInputStream(new FileInputStream(file)); CacheHeader entry=CacheHeader.readHeader(fis); entry.size=file.length(); putEntry(entry.key,entry); } catch ( IOException e) { if (file != null) { file.delete(); } } finally { try { if (fis != null) { fis.close(); } } catch ( IOException ignored) { } } } }
Initializes the DiskBasedCache by scanning for all files currently in the specified root directory. Creates the root directory if necessary.
public void cancelAnimations(){ if (mFlashAnim != null && mFlashAnim.isRunning()) { mFlashAnim.cancel(); } if (mCaptureAnimator != null && mCaptureAnimator.isStarted()) { mCaptureAnimator.cancel(); } }
Cancels on-going flash animation and capture animation, if any.
protected void writeLocation(String loc) throws IOException { hadAnnotations|=(loc != null); locOut.writeObject(loc); }
Overrides MarshalOutputStream.writeLocation implementation to write annotations to the location stream.
public int currentTexture(){ int textureUnitIndex=this.textureUnit - GLES20.GL_TEXTURE0; return this.textureId[textureUnitIndex]; }
Returns the name of the OpenGL texture 2D object currently bound to the active multitexture unit. The active multitexture unit may be determined by calling currentTextureUnit.
public boolean isInitialized(){ return (initialized); }
Check whether this VSDecoder has completed initialization
public long optLong(String key){ return this.optLong(key,0); }
Get an optional long value associated with a key, or zero if there is no such key or if the value is not a number. If the value is a string, an attempt will be made to evaluate it as a number.