code
stringlengths
10
174k
nl
stringlengths
3
129k
@Override public String toString(){ StringBuilder result=new StringBuilder(); result.append("Token["); switch (ttype) { case TT_EOF: result.append("EOF"); break; case TT_EOL: result.append("EOL"); break; case TT_NUMBER: result.append("n="); result.append(nval); break; case TT_WORD: result.append(sval); break; default : if (ttype == TT_UNKNOWN || tokenTypes[ttype] == TOKEN_QUOTE) { result.append(sval); } else { result.append('\''); result.append((char)ttype); result.append('\''); } } result.append("], line "); result.append(lineNumber); return result.toString(); }
Returns the state of this tokenizer in a readable format.
public ConstExpConstModel(Parameter N0Parameter,Parameter N1Parameter,Parameter growthRateParameter,Parameter timeParameter,Parameter epochParameter,boolean useNumericalIntegrator,Type units){ this(ConstExpConstModelParser.CONST_EXP_CONST_MODEL,N0Parameter,N1Parameter,growthRateParameter,timeParameter,epochParameter,useNumericalIntegrator,units); }
Construct demographic model with default settings
public void put(String key,File files[]) throws FileNotFoundException { put(key,files,null,null); }
Adds files array to the request.
public void testMoveRenameFileSourceAndDestinationMissingPartially() throws Exception { create(igfsSecondary,paths(DIR,SUBDIR,DIR_NEW,SUBDIR_NEW),paths(FILE)); create(igfs,paths(DIR,DIR_NEW),null); igfs.rename(FILE,FILE_NEW); checkExist(igfs,SUBDIR,SUBDIR_NEW); checkExist(igfs,igfsSecondary,FILE_NEW); checkNotExist(igfs,igfsSecondary,FILE); }
Test move and rename in case source and destination exist partially and the path being renamed is a file.
public static int encode(byte[] data,OutputStream out) throws IOException { return encoder.encode(data,0,data.length,out); }
Encode the byte data to base 64 writing it to the given output stream.
protected boolean parseNameTest(PsiBuilder builder){ if (builder.getTokenType() == XPathTokenTypes.STAR) { return parseWildcard(builder); } else if (builder.getTokenType() == XPathTokenTypes.NCNAME) { builder.advanceLexer(); if (builder.getTokenType() == XPathTokenTypes.COL) { builder.advanceLexer(); if (builder.getTokenType() != XPathTokenTypes.STAR) { if (builder.getTokenType() != XPathTokenTypes.NCNAME) { builder.error("* or NCName expected"); } else { builder.advanceLexer(); } } else { builder.advanceLexer(); } } return true; } return false; }
[37] NameTest ::= '*' | NCName ':' '*' | QName
private void deleteConfig(HttpServletRequest request,InstructionalOfferingConfigEditForm frm) throws Exception { org.hibernate.Session hibSession=null; Transaction tx=null; try { InstrOfferingConfigDAO iocDao=new InstrOfferingConfigDAO(); hibSession=iocDao.getSession(); tx=hibSession.beginTransaction(); Long configId=frm.getConfigId(); InstrOfferingConfig ioc=iocDao.get(configId); InstructionalOffering io=ioc.getInstructionalOffering(); deleteSubpart(request,hibSession,ioc,new HashMap()); io.removeConfiguration(ioc); io.computeLabels(hibSession); if (!ioc.isUnlimitedEnrollment().booleanValue()) io.setLimit(new Integer(io.getLimit().intValue() - ioc.getLimit().intValue())); ChangeLog.addChange(hibSession,sessionContext,io,io.getCourseName() + " [" + ioc.getName()+ "]",ChangeLog.Source.INSTR_CFG_EDIT,ChangeLog.Operation.DELETE,io.getControllingCourseOffering().getSubjectArea(),null); Event.deleteFromEvents(hibSession,ioc); Exam.deleteFromExams(hibSession,ioc); hibSession.saveOrUpdate(io); String className=ApplicationProperty.ExternalActionInstrOffrConfigChange.value(); ExternalInstrOffrConfigChangeAction configChangeAction=null; if (className != null && className.trim().length() > 0) { configChangeAction=(ExternalInstrOffrConfigChangeAction)(Class.forName(className).newInstance()); if (!configChangeAction.validateConfigChangeCanOccur(io,hibSession)) { throw new Exception("Configuration change violates rules for Add On, rolling back the change."); } } hibSession.flush(); tx.commit(); hibSession.refresh(io); if (configChangeAction != null) { configChangeAction.performExternalInstrOffrConfigChangeAction(io,hibSession); } } catch ( Exception e) { try { if (tx != null && tx.isActive()) tx.rollback(); } catch ( Exception e1) { } Debug.error(e); throw (e); } }
Deletes configuration and associated prefs
private void loadProfile(String userId,String name){ final Intent userProfileIntent=new Intent(getActivity(),UserProfileActivity.class); userProfileIntent.putExtra(AppConstants.Keys.USER_ID,userId); userProfileIntent.putExtra(AppConstants.Keys.USER_NAME,name); userProfileIntent.putExtra(AppConstants.Keys.SERVICE_SCREEN_TYPE,AppConstants.ServiceScreenType.PROFILE); startActivity(userProfileIntent); }
This loads the profile of the user
int doFinal(byte[] input,int inputOffset,int inputLen,byte[] output,int outputOffset) throws ShortBufferException, IllegalBlockSizeException, BadPaddingException { return cipher.doFinal(input,inputOffset,inputLen,output,outputOffset); }
Encrypts or decrypts data in a single-part operation, or finishes a multiple-part operation. The data is encrypted or decrypted, depending on how this cipher was initialized. <p>The first <code>inputLen</code> bytes in the <code>input</code> buffer, starting at <code>inputOffset</code>, and any input bytes that may have been buffered during a previous <code>update</code> operation, are processed, with padding (if requested) being applied. The result is stored in the <code>output</code> buffer, starting at <code>outputOffset</code>. <p>The cipher is reset to its initial state (uninitialized) after this call.
public boolean isOverwriteMode(){ return !isInserting; }
Tells whether the input is in overwrite or insert mode
private void writeAttribute(java.lang.String prefix,java.lang.String namespace,java.lang.String attName,java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { if (xmlWriter.getPrefix(namespace) == null) { xmlWriter.writeNamespace(prefix,namespace); xmlWriter.setPrefix(prefix,namespace); } xmlWriter.writeAttribute(namespace,attName,attValue); }
Util method to write an attribute with the ns prefix
public javax.naming.Binding nextElement(){ try { return next(); } catch ( NamingException ne) { throw new NoSuchElementException(); } }
Returns the next binding in the list.
public static void i(String tag,String msg,Object... args){ if (sLevel > LEVEL_INFO) { return; } if (args.length > 0) { msg=String.format(msg,args); } Log.i(tag,msg); }
Send an INFO log message
public void cancel(){ cancelled=true; }
Since cancel is async, it just means that we will eventually, and rather quickly, stop emitting values. We do this to follow the reactive streams specifications that cancel should mean that the observable eventually stops emitting items.
public void findAndInit(Object someObj){ super.findAndInit(someObj); if (someObj instanceof MapBean || someObj instanceof InformationDelegator) { drawingTool.findAndInit(someObj); } if (someObj instanceof MouseDelegator) { setMouseDelegator((MouseDelegator)someObj); drawingTool.findAndInit(someObj); } if (someObj instanceof OMGraphicDeleteTool) { ((OMGraphicDeleteTool)someObj).findAndInit(getDrawingTool()); } }
Called by findAndInit(Iterator) so subclasses can find objects, too.
public PaymentGatewayPayPoint(){ System.setProperty("java.protocol.handler.pkgs","com.sun.net.ssl.internal.www.protocol"); Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); m_sCommerceID=AppConfig.getInstance().getProperty("payment.commerceid"); AltEncrypter cypher=new AltEncrypter("cypherkey" + AppConfig.getInstance().getProperty("payment.commerceid")); this.m_sCommercePassword=cypher.decrypt(AppConfig.getInstance().getProperty("payment.commercepassword").substring(6)); m_bTestMode=AppConfig.getInstance().getBoolean("payment.testmode"); m_sCurrency=(Locale.getDefault().getCountry().isEmpty()) ? Currency.getInstance("EUR").getCurrencyCode() : Currency.getInstance(Locale.getDefault()).getCurrencyCode(); }
Creates a new instance of PaymentGatewaySECPay
public void init() throws IOException { mailbox.connect(); this.initialized=true; }
Connects to Gmail and loads the base information required for the sync.
protected POInfo initPO(Properties ctx){ POInfo poi=POInfo.getPOInfo(ctx,Table_ID,get_TrxName()); return poi; }
Load Meta Data
@Override protected EClass eStaticClass(){ return TypeRefsPackage.Literals.TYPE_REF; }
<!-- begin-user-doc --> <!-- end-user-doc -->
public final Exercise.Type type(){ return type; }
Returns the exercise type
@Override public void run(){ amIActive=true; String inputHeader=null; String outputHeader=null; int row, col; float progress=0; double z, z2, zMin; int x, y, a, b, i; double h=0; int whichCell; double infVal=9999999; int[] dX=new int[]{-1,-1,0,1,1,1,0,-1}; int[] dY=new int[]{0,-1,-1,-1,0,1,1,1}; int[] Gx=new int[]{1,1,0,1,1,1,0,1}; int[] Gy=new int[]{0,1,1,1,0,1,1,1}; double gridRes; if (args.length <= 0) { showFeedback("Plugin parameters have not been set."); return; } inputHeader=args[0]; outputHeader=args[1]; if ((inputHeader == null) || (outputHeader == null)) { showFeedback("One or more of the input parameters have not been set properly."); return; } try { WhiteboxRaster image=new WhiteboxRaster(inputHeader,"r"); int rows=image.getNumberRows(); int cols=image.getNumberColumns(); double noData=image.getNoDataValue(); gridRes=(image.getCellSizeX() + image.getCellSizeY()) / 2; WhiteboxRaster outputImage=new WhiteboxRaster(outputHeader,"rw",inputHeader,WhiteboxRaster.DataType.FLOAT,infVal); outputImage.setPreferredPalette("spectrum.pal"); WhiteboxRaster Rx=new WhiteboxRaster(outputHeader.replace(".dep","_temp1.dep"),"rw",inputHeader,WhiteboxRaster.DataType.FLOAT,0); Rx.isTemporaryFile=true; WhiteboxRaster Ry=new WhiteboxRaster(outputHeader.replace(".dep","_temp2.dep"),"rw",inputHeader,WhiteboxRaster.DataType.FLOAT,0); Ry.isTemporaryFile=true; double[] data; for (row=0; row < rows; row++) { data=image.getRowValues(row); for (col=0; col < cols; col++) { if (data[col] != 0) { outputImage.setValue(row,col,0); } } if (cancelOp) { cancelOperation(); return; } progress=(float)(100f * row / (rows - 1)); updateProgress((int)progress); } for (row=0; row < rows; row++) { for (col=0; col < cols; col++) { z=outputImage.getValue(row,col); if (z != 0) { zMin=infVal; whichCell=-1; for (i=0; i <= 3; i++) { x=col + dX[i]; y=row + dY[i]; z2=outputImage.getValue(y,x); if (z2 != noData) { switch (i) { case 0: h=2 * Rx.getValue(y,x) + 1; break; case 1: h=2 * (Rx.getValue(y,x) + Ry.getValue(y,x) + 1); break; case 2: h=2 * Ry.getValue(y,x) + 1; break; case 3: h=2 * (Rx.getValue(y,x) + Ry.getValue(y,x) + 1); break; } z2+=h; if (z2 < zMin) { zMin=z2; whichCell=i; } } } if (zMin < z) { outputImage.setValue(row,col,zMin); x=col + dX[whichCell]; y=row + dY[whichCell]; Rx.setValue(row,col,Rx.getValue(y,x) + Gx[whichCell]); Ry.setValue(row,col,Ry.getValue(y,x) + Gy[whichCell]); } } } if (cancelOp) { cancelOperation(); return; } progress=(float)(100f * row / (rows - 1)); updateProgress((int)progress); } for (row=rows - 1; row >= 0; row--) { for (col=cols - 1; col >= 0; col--) { z=outputImage.getValue(row,col); if (z != 0) { zMin=infVal; whichCell=-1; for (i=4; i <= 7; i++) { x=col + dX[i]; y=row + dY[i]; z2=outputImage.getValue(y,x); if (z2 != noData) { switch (i) { case 5: h=2 * (Rx.getValue(y,x) + Ry.getValue(y,x) + 1); break; case 4: h=2 * Rx.getValue(y,x) + 1; break; case 6: h=2 * Ry.getValue(y,x) + 1; break; case 7: h=2 * (Rx.getValue(y,x) + Ry.getValue(y,x) + 1); break; } z2+=h; if (z2 < zMin) { zMin=z2; whichCell=i; } } } if (zMin < z) { outputImage.setValue(row,col,zMin); x=col + dX[whichCell]; y=row + dY[whichCell]; Rx.setValue(row,col,Rx.getValue(y,x) + Gx[whichCell]); Ry.setValue(row,col,Ry.getValue(y,x) + Gy[whichCell]); } } } if (cancelOp) { cancelOperation(); return; } progress=(float)(100f * (rows - 1 - row) / (rows - 1)); updateProgress((int)progress); } for (row=0; row < rows; row++) { for (col=0; col < cols; col++) { z=image.getValue(row,col); if (z != noData) { z=outputImage.getValue(row,col); outputImage.setValue(row,col,Math.sqrt(z) * gridRes); } else { outputImage.setValue(row,col,noData); } } if (cancelOp) { cancelOperation(); return; } progress=(float)(100f * row / (rows - 1)); updateProgress((int)progress); } outputImage.addMetadataEntry("Created by the " + getDescriptiveName() + " tool."); outputImage.addMetadataEntry("Created on " + new Date()); image.close(); outputImage.close(); Rx.close(); Ry.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 JavaType constructSimpleType(Class<?> rawType,JavaType[] parameterTypes){ TypeVariable<?>[] typeVars=rawType.getTypeParameters(); if (typeVars.length != parameterTypes.length) { throw new IllegalArgumentException("Parameter type mismatch for " + rawType.getName() + ": expected "+ typeVars.length+ " parameters, was given "+ parameterTypes.length); } String[] names=new String[typeVars.length]; for (int i=0, len=typeVars.length; i < len; ++i) { names[i]=typeVars[i].getName(); } JavaType resultType=new SimpleType(rawType,names,parameterTypes,null,null); return resultType; }
Method for constructing a type instance with specified parameterization.
@Override public void entityChanged(final Object property){ super.entityChanged(property); if (property == Chest.PROP_OPEN) { proceedChangedState(entity); openChanged=true; } }
An entity was changed.
public DragGestureRecognizer createDefaultDragGestureRecognizer(Component c,int actions,DragGestureListener dgl){ return Toolkit.getDefaultToolkit().createDragGestureRecognizer(MouseDragGestureRecognizer.class,this,c,actions,dgl); }
Creates a new <code>DragGestureRecognizer</code> that implements the default abstract subclass of <code>DragGestureRecognizer</code> for this <code>DragSource</code>, and sets the specified <code>Component</code> and <code>DragGestureListener</code> on the newly created object. For this <code>DragSource</code> the default is <code>MouseDragGestureRecognizer</code>. <P>
public PipedReader(PipedWriter src) throws IOException { this(src,DEFAULT_PIPE_SIZE); }
Creates a <code>PipedReader</code> so that it is connected to the piped writer <code>src</code>. Data written to <code>src</code> will then be available as input from this stream.
public static File ensureLogDirectoryExists(){ if (mLogDirectory == null) { return null; } if (!mLogDirectory.exists()) { mLogDirectory.mkdirs(); } return mLogDirectory; }
Check if the log directory exists. Create it if it s not created
public String stem(String s){ if (stem(s.toCharArray(),s.length())) return toString(); else return s; }
Stem a word provided as a String. Returns the result as a String.
protected boolean err(){ return status != STATUS_OK; }
Returns true if an error was encountered during reading/decoding
public DeleteRequest parent(String parent){ if (routing == null) { routing=parent; } return this; }
Sets the parent id of this document. Will simply set the routing to this value, as it is only used for routing with delete requests.
public AndQueryBuilder add(QueryBuilder filterBuilder){ filters.add(filterBuilder); return this; }
Adds a filter to the list of filters to "and".
public static boolean match(String s,String... sa){ for ( String st : sa) { if (st.equalsIgnoreCase(s)) return true; } return false; }
Checks if any of the strings from the given array matches the given string
public static void text(double x,double y,String text){ if (text == null) throw new NullPointerException(); offscreen.setFont(font); FontMetrics metrics=offscreen.getFontMetrics(); double xs=scaleX(x); double ys=scaleY(y); int ws=metrics.stringWidth(text); int hs=metrics.getDescent(); offscreen.drawString(text,(float)(xs - ws / 2.0),(float)(ys + hs)); draw(); }
Write the given text string in the current font, centered at (<em>x</em>, <em>y</em>).
static void extractGenericsConnections(Map<String,GenericsType> connections,ClassNode type,ClassNode target){ if (target == null || type == target || !isUsingGenericsOrIsArrayUsingGenerics(target)) return; if (type == null || type == UNKNOWN_PARAMETER_TYPE) return; if (type.isArray() && target.isArray()) { extractGenericsConnections(connections,type.getComponentType(),target.getComponentType()); } else if (target.isGenericsPlaceHolder() || type.equals(target) || !implementsInterfaceOrIsSubclassOf(type,target)) { if (target.isGenericsPlaceHolder()) { connections.put(target.getGenericsTypes()[0].getName(),new GenericsType(type)); } else { extractGenericsConnections(connections,type.getGenericsTypes(),target.getGenericsTypes()); } } else { Map<String,ClassNode> genSpec=GenericsUtils.createGenericsSpec(type); ClassNode superClass=getNextSuperClass(type,target); if (superClass != null) { ClassNode corrected; if (missesGenericsTypes(type)) { corrected=superClass.getPlainNodeReference(); } else { corrected=GenericsUtils.correctToGenericsSpecRecurse(genSpec,superClass); } extractGenericsConnections(connections,corrected,target); } else { throw new GroovyBugError("The type " + type + " seems not to normally extend "+ target+ ". Sorry, I cannot handle this."); } } }
use supplied type to make a connection from usage to declaration The method operates in two modes. * For type !instanceof target a structural compare will be done (for example Dummy&lt;T&gt; and List&lt;R&gt; to get T=R) * If type equals target, a structural match is done as well (for example Colection&lt;U&gt; and Collection&lt;E&gt; to get U=E) * otherwise we climb the hierarchy to find a case of type equals target to then execute the structural match, while applying possibly existing generics contexts on the way (for example for IntRange and Collection&lt;E&gt; to get E=Integer, since IntRange is an AbstractList&lt;Integer&gt;) Should the target not have any generics this method does nothing.
public FunctionInvocationTargetException(Throwable cause){ super(cause); }
Construct an instance of FunctionInvocationTargetException
private CharSequence formatDuration(long millis){ if (millis >= DateUtils.HOUR_IN_MILLIS) { int hours=(int)TimeUnit.MILLISECONDS.toHours(millis + TimeUnit.MINUTES.toMillis(30)); return resources.getQuantityString(R.plurals.dl__duration_hours,hours,hours); } else if (millis >= DateUtils.MINUTE_IN_MILLIS) { int minutes=(int)TimeUnit.MILLISECONDS.toMinutes(millis + TimeUnit.SECONDS.toMillis(30)); return resources.getQuantityString(R.plurals.dl__duration_minutes,minutes,minutes); } else { int seconds=(int)TimeUnit.MILLISECONDS.toSeconds(millis + 500); return resources.getQuantityString(R.plurals.dl__duration_seconds,seconds,seconds); } }
Return given duration in a human-friendly format. For example, "4 minutes" or "1 second". Returns only largest meaningful unit of time, from seconds up to hours.
public double[][] rankedAttributes() throws Exception { if (m_attributeRanking == null) { throw new Exception("Ranking has not been performed"); } return m_attributeRanking; }
get the final ranking of the attributes.
public void endAdding(GL10 gl){ checkState(STATE_ADDING,STATE_INITIALIZED); gl.glBindTexture(GL10.GL_TEXTURE_2D,mTextureID); GLUtils.texImage2D(GL10.GL_TEXTURE_2D,0,mBitmap,0); mBitmap.recycle(); mBitmap=null; mCanvas=null; }
Call to end adding labels. Must be called before drawing starts.
public static void verifyVirtualPoolChangeForTechRefresh(VirtualPool srcVpool,VirtualPool tgtVpool){ String[] exclude=new String[]{PROTOCOLS,PROVISIONING_TYPE,ARRAY_INFO,DRIVE_TYPE,AUTO_TIER_POLICY_NAME,HOST_IO_LIMIT_IOPS,HOST_IO_LIMIT_BANDWIDTH,VMAX_COMPRESSION_ENABLED,MATCHED_POOLS,INVALID_MATCHED_POOLS,ASSIGNED_STORAGE_POOLS,LABEL,DESCRIPTION,STATUS,TAGS,CREATION_TIME,NON_DISRUPTIVE_EXPANSION}; if (!VirtualPoolChangeAnalyzer.analyzeChanges(srcVpool,tgtVpool,null,exclude,null).isEmpty()) { throw APIException.badRequests.vPoolChangeNotValid(srcVpool.getId(),tgtVpool.getId()); } }
Verifies the Vpool change for a tech refresh of a VPlex virtual volume. The Vpool should only specify a simple change such as the type of disk drive.
public DocumentQuery(URL feedUrl){ super(feedUrl); }
Constructs a new query object that targets a feed. The initial state of the query contains no parameters, meaning all entries in the feed would be returned if the query was executed immediately after construction.
static <T>List<T> cast(Iterable<T> iterable){ return (List<T>)iterable; }
Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557
private void addAttributesButtonsTo(JToolBar bar,DrawingEditor editor){ JButton b; b=bar.add(new PickAttributesAction(editor)); b.setFocusable(false); b=bar.add(new ApplyAttributesAction(editor)); b.setFocusable(false); bar.addSeparator(); addColorButtonsTo(bar,editor); bar.addSeparator(); addStrokeButtonsTo(bar,editor); bar.addSeparator(); ButtonFactory.addFontButtonsTo(bar,editor); }
Creates toolbar buttons and adds them to the specified JToolBar
@Override public boolean equals(Object o){ if (o instanceof ChannelInfo) { ChannelInfo other=(ChannelInfo)o; if (this.channelId != null) { if (this.channelId.equals(other.channelId)) return true; } else if (this.channelName != null && this.channelNumber != null) { return this.channelName.equals(other.channelName) && this.channelNumber.equals(other.channelNumber) && this.majorNumber == other.majorNumber && this.minorNumber == other.minorNumber; } Log.d(Util.T,"Could not compare channel values, no data to compare against"); Log.d(Util.T,"This channel info: \n" + this.rawData.toString()); Log.d(Util.T,"Other channel info: \n" + other.rawData.toString()); return false; } return super.equals(o); }
Compares two ChannelInfo objects.
static public String format(byte[] p){ return jmri.util.StringUtil.hexStringFromBytes(p); }
Convert NMRA packet to a readable form
private void closeConnectionQuietly(){ if (connection != null) { try { connection.disconnect(); } catch ( Exception e) { Log.e(TAG,"Unexpected error while disconnecting",e); } connection=null; } }
Closes the current connection quietly, if there is one.
public void updateEllipse(float latPoint,float lonPoint,float majorAxisSpan,float minorAxisSpan,int units,float rotationAngle,LinkProperties properties,int graphicUpdateMask) throws IOException { writeGraphicGestureHeader(graphicUpdateMask); LinkEllipse.write(latPoint,lonPoint,majorAxisSpan,minorAxisSpan,units,rotationAngle,properties,link.dos); }
Write an ellipse in the response.
@Override public void addTemporaryTopic(final TemporaryTopic temp){ if (ActiveMQRASessionFactoryImpl.trace) { ActiveMQRALogger.LOGGER.trace("addTemporaryTopic(" + temp + ")"); } synchronized (tempTopics) { tempTopics.add(temp); } }
Add temporary topic
@operator(value=ZERO,concept={IConcept.EQUATION,IConcept.MATH},doc=@doc("An internal placeholder function")) public static Double f(final IScope scope,final IExpression var){ return Double.NaN; }
Placeholder for zero-order equations. The expression on the right allows to pass the variable directly (maybe useful one day).
private void exportExcel(){ RModel model=table.getRModel(); if (model == null) { return; } try { RModelExcelExporter exporter=new RModelExcelExporter((RModel)model); exporter.export(null,null); } catch ( Exception e) { ADialog.error(0,this,"Error",e.getLocalizedMessage()); if (CLogMgt.isLevelFinest()) e.printStackTrace(); } }
Export to Excel
@Override public void onReceivedError(WebView view,int errorCode,String description,String failingUrl){ if (!isCurrentlyLoading) { return; } LOG.d(TAG,"CordovaWebViewClient.onReceivedError: Error code=%s Description=%s URL=%s",errorCode,description,failingUrl); if (errorCode == WebViewClient.ERROR_UNSUPPORTED_SCHEME) { parentEngine.client.clearLoadTimeoutTimer(); if (view.canGoBack()) { view.goBack(); return; } else { super.onReceivedError(view,errorCode,description,failingUrl); } } parentEngine.client.onReceivedError(errorCode,description,failingUrl); }
Report an error to the host application. These errors are unrecoverable (i.e. the main resource is unavailable). The errorCode parameter corresponds to one of the ERROR_* constants.
static final public boolean parseBoolean(int what){ return (what != 0); }
<p>Convert an integer to a boolean. Because of how Java handles upgrading numbers, this will also cover byte and char (as they will upgrade to an int without any sort of explicit cast).</p> <p>The preprocessor will convert boolean(what) to parseBoolean(what).</p>
public void onSurfaceDestroyed(){ if (DEBUG) Log.v(TAG,"onSurfaceDestroyed:"); if (mDrawer != null) { mDrawer.release(); mDrawer=null; } if (mSTexture != null) { mSTexture.release(); mSTexture=null; } release(); }
when GLSurface context is soon destroyed
public SequenceIndex(){ mBins=new TreeMap<>(); mLinearIndex=new long[5]; }
Construct a default SequenceIndex
private void sequenceCommand(CommandRequest request,ServerSessionContext session,CompletableFuture<CommandResponse> future){ if (request.sequence() > session.nextRequestSequence()) { session.registerRequest(request.sequence(),null); } else { applyCommand(request,session,future); } }
Sequences the given command to the log.
public cudaChannelFormatDesc(){ }
Creates an uninitialized cudaChannelFormatDesc
public boolean isSelected(ButtonModel m){ return (m == selection); }
Returns whether a <code>ButtonModel</code> is selected.
private boolean scheduleNext(){ final String tag="Scheduled session[" + taskid + "]"; try { LOG.finer(tag + ": scheduling next session for " + delayBeforeNext+ "ms"); if (cancelled || !notifyStateChange(SCHEDULED,"scan-scheduled")) { LOG.finer(tag + " stopped: do not reschedule"); return false; } final SessionTask nextTask=new SessionTask(delayBeforeNext); if (!scheduleSession(nextTask,delayBeforeNext)) return false; LOG.finer(tag + ": next session successfully scheduled"); } catch ( Exception x) { if (LOG.isLoggable(Level.FINEST)) { LOG.log(Level.FINEST,tag + " failed to schedule next session: " + x,x); } else if (LOG.isLoggable(Level.FINE)) { LOG.fine(tag + " failed to schedule next session: " + x); } } return true; }
Schedule an identical task for next iteration.
public Process exec(String prog,String[] envp) throws java.io.IOException { return exec(prog,envp,null); }
Execute prog in a separate platform process The new process uses the environment provided in envp
@Override public void put(byte[] tableKey,StreamSource rowSource,Result<Boolean> result){ putImpl(tableKey,rowSource,PutType.PUT,result); }
Puts the row for replication. Put is only called for the owning servers. Each owner and its backups get a copy.
public static void changeToTheme(Activity activity){ activity.finish(); activity.startActivity(new Intent(activity,activity.getClass())); }
Set the theme of the Activity, and restart it by creating a new Activity of the same type.
protected POInfo initPO(Properties ctx){ POInfo poi=POInfo.getPOInfo(ctx,Table_ID,get_TrxName()); return poi; }
Load Meta Data
public byte[] serialize(){ byte[] payloadData=null; if (payload != null) { payload.setParent(this); payloadData=payload.serialize(); } this.length=(short)(8 + ((payloadData == null) ? 0 : payloadData.length)); byte[] data=new byte[this.length]; ByteBuffer bb=ByteBuffer.wrap(data); bb.putShort((short)this.sourcePort.getPort()); bb.putShort((short)this.destinationPort.getPort()); bb.putShort(this.length); bb.putShort(this.checksum); if (payloadData != null) bb.put(payloadData); if (this.parent != null && this.parent instanceof IPv4) ((IPv4)this.parent).setProtocol(IpProtocol.UDP); if (this.checksum == 0) { bb.rewind(); int accumulation=0; if (this.parent != null && this.parent instanceof IPv4) { IPv4 ipv4=(IPv4)this.parent; accumulation+=((ipv4.getSourceAddress().getInt() >> 16) & 0xffff) + (ipv4.getSourceAddress().getInt() & 0xffff); accumulation+=((ipv4.getDestinationAddress().getInt() >> 16) & 0xffff) + (ipv4.getDestinationAddress().getInt() & 0xffff); accumulation+=ipv4.getProtocol().getIpProtocolNumber() & 0xff; accumulation+=this.length & 0xffff; } for (int i=0; i < this.length / 2; ++i) { accumulation+=0xffff & bb.getShort(); } if (this.length % 2 > 0) { accumulation+=(bb.get() & 0xff) << 8; } accumulation=((accumulation >> 16) & 0xffff) + (accumulation & 0xffff); this.checksum=(short)(~accumulation & 0xffff); bb.putShort(6,this.checksum); } return data; }
Serializes the packet. Will compute and set the following fields if they are set to specific values at the time serialize is called: -checksum : 0 -length : 0
public String toString(){ StringBuffer buffer=new StringBuffer(); buffer.append(toString(getClass())); buffer.append("[UseDefault="); buffer.append(isUseDefault()); buffer.append(", UseLocaleFormat="); buffer.append(useLocaleFormat); if (pattern != null) { buffer.append(", Pattern="); buffer.append(pattern); } if (locale != null) { buffer.append(", Locale="); buffer.append(locale); } buffer.append(']'); return buffer.toString(); }
Provide a String representation of this number converter.
public static boolean isCompleted(Operation op){ return (null == op || null == op.getCompletion()); }
Returns true if operation still needs to be completed.
public void firePropertyChange(java.beans.PropertyChangeEvent propertyChangeEvent){ if (propertyChangeEvent == null) { String msg=Logging.getMessage("nullValue.PropertyChangeEventIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } this.getChangeSupport().firePropertyChange(propertyChangeEvent); }
Fire a property change event.
void add(RuleRec rec){ list.add(rec); }
Added a RuleRec to the Rule record list.
protected void pack(){ Component component=getComponent(); if (component instanceof Window) { ((Window)component).pack(); } }
Causes the <code>Popup</code> to be sized to fit the preferred size of the <code>Component</code> it contains.
public ManagerServiceImpl(final GenericDAO<Manager,Long> genericDao){ super(genericDao); }
Create service to manage the administrative of web shop
private void updateProgress(int progress){ if (myHost != null && progress != previousProgress) { myHost.updateProgress(progress); } previousProgress=progress; }
Used to communicate a progress update between a plugin tool and the main Whitebox user interface.
public Tradingdays findTradingdaysByDateRange(final ZonedDateTime startDate,final ZonedDateTime endDate) throws PersistentModelException { return m_tradingdayHome.findTradingdaysByDateRange(startDate,endDate); }
Method findTradingdaysByDateRange.
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:33:43.033 -0500",hash_original_method="ECD2E5721BC163A0054AA741832C3882",hash_generated_method="14A5AF88A2506E99D7DB3789702FBF82") private static void modifyFieldIfSet(final Field field,final TypedProperties properties,final String propertyName){ if (field.getType() == java.lang.String.class) { int stringInfo=properties.getStringInfo(propertyName); switch (stringInfo) { case TypedProperties.STRING_SET: break; case TypedProperties.STRING_NULL: try { field.set(null,null); } catch ( IllegalAccessException ex) { throw new IllegalArgumentException("Cannot set field for " + propertyName,ex); } return; case TypedProperties.STRING_NOT_SET: return; case TypedProperties.STRING_TYPE_MISMATCH: throw new IllegalArgumentException("Type of " + propertyName + " "+ " does not match field type ("+ field.getType()+ ")"); default : throw new IllegalStateException("Unexpected getStringInfo(" + propertyName + ") return value "+ stringInfo); } } Object value=properties.get(propertyName); if (value != null) { if (!fieldTypeMatches(field,value.getClass())) { throw new IllegalArgumentException("Type of " + propertyName + " ("+ value.getClass()+ ") "+ " does not match field type ("+ field.getType()+ ")"); } try { field.set(null,value); } catch (IllegalAccessException ex) { throw new IllegalArgumentException("Cannot set field for " + propertyName,ex); } } }
Looks up the property that corresponds to the field, and sets the field's value if the types match.
public OptionsBean obtenerTiposInformesCombo(Entidad entidad) throws RPAdminException { MultiEntityContextHolder.setEntity(entidad.getIdentificador()); OptionsBean options=new OptionsBean(); ResourceBundle rs=ResourceBundle.getBundle("ieci.tecdoc.sgm.rpadmin.manager.tipoInforme"); Enumeration keys=rs.getKeys(); while (keys.hasMoreElements()) { OptionBean option=new OptionBean(); String key=keys.nextElement().toString(); String value=rs.getString(key); option.setCodigo(key); option.setDescripcion(value); options.add(option); } return options; }
Obtiene los tipos de perfiles de informes y los devuelve en un bean
public IteratorSpliterator(Iterator<? extends T> iterator,long size,int characteristics){ this.collection=null; this.it=iterator; this.est=size; this.characteristics=(characteristics & Spliterator.CONCURRENT) == 0 ? characteristics | Spliterator.SIZED | Spliterator.SUBSIZED : characteristics; }
Creates a spliterator using the given iterator for traversal, and reporting the given initial size and characteristics.
public KMLPolygonImpl(KMLTraversalContext tc,KMLPlacemark placemark,KMLAbstractGeometry geom){ if (tc == null) { String msg=Logging.getMessage("nullValue.TraversalContextIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } if (placemark == null) { String msg=Logging.getMessage("nullValue.ParentIsNull"); Logging.logger().severe(msg); throw new IllegalArgumentException(msg); } this.parent=placemark; KMLPolygon polygon=(KMLPolygon)geom; this.setAltitudeMode(WorldWind.CLAMP_TO_GROUND); String altMode=polygon.getAltitudeMode(); if (!WWUtil.isEmpty(altMode)) { if ("relativeToGround".equals(altMode)) this.setAltitudeMode(WorldWind.RELATIVE_TO_GROUND); else if ("absolute".equals(altMode)) this.setAltitudeMode(WorldWind.ABSOLUTE); } KMLLinearRing outerBoundary=polygon.getOuterBoundary(); if (outerBoundary != null) { Position.PositionList coords=outerBoundary.getCoordinates(); if (coords != null && coords.list != null) this.setOuterBoundary(outerBoundary.getCoordinates().list); } Iterable<? extends KMLLinearRing> innerBoundaries=polygon.getInnerBoundaries(); if (innerBoundaries != null) { for ( KMLLinearRing ring : innerBoundaries) { Position.PositionList coords=ring.getCoordinates(); if (coords != null && coords.list != null) this.addInnerBoundary(ring.getCoordinates().list); } } if (placemark.getName() != null) this.setValue(AVKey.DISPLAY_NAME,placemark.getName()); if (placemark.getDescription() != null) this.setValue(AVKey.DESCRIPTION,placemark.getDescription()); if (placemark.getSnippetText() != null) this.setValue(AVKey.SHORT_DESCRIPTION,placemark.getSnippetText()); this.setValue(AVKey.CONTEXT,this.parent); }
Create an instance.
private void fillBuf() throws IOException { int result=in.read(buf,0,buf.length); if (result == -1) { throw new EOFException(); } pos=0; end=result; }
Reads new input data into the buffer. Call only with pos == end or end == -1, depending on the desired outcome if the function throws.
public SpecialInvokeExpr newSpecialInvokeExpr(Local base,SootMethodRef method,Value arg){ return new JSpecialInvokeExpr(base,method,Arrays.asList(new Value[]{arg})); }
Constructs a NewSpecialInvokeExpr(Local base, SootMethodRef method, List of Immediate) grammar chunk.
public Builder(String headVar){ this.headVar=headVar; table=new HashMap<Assignment,CategoricalTable.Builder>(); }
Constructs a new conditional categorical table with the given variable name.
@Override public int removeAllByHostHashes(final Set<String> hosthashes){ for ( String h : hosthashes) { if (this.hostHash.equals(h)) { int s=this.size(); this.clear(); return s; } } return 0; }
delete all urls which are stored for given host hashes
public RESTLoginCommandImpl(final ShoppingCartCommandRegistry registry,final CustomerService customerService,final ShopService shopService,final PriceService priceService,final PricingPolicyProvider pricingPolicyProvider,final ProductService productService,final CartRepository cartRepository){ super(registry,customerService,shopService,priceService,pricingPolicyProvider,productService); this.cartRepository=cartRepository; }
Construct command.
public File configFile(String path){ return dataFile(CONFIG_DIR + "/" + path); }
Constructs an absolute path to a file within the config folder of the data dir.
public ImageCacheParams(File rootDirectory,int maxCacheSizeInBytes){ diskCacheDir=rootDirectory; memCacheSize=maxCacheSizeInBytes; }
Create a set of image cache parameters that can be provided to
public boolean shouldRemoteUiBeVisible(int state,int idleReason) throws TransientNetworkDisconnectionException, NoConnectionException { switch (state) { case MediaStatus.PLAYER_STATE_PLAYING: case MediaStatus.PLAYER_STATE_PAUSED: case MediaStatus.PLAYER_STATE_BUFFERING: return true; case MediaStatus.PLAYER_STATE_IDLE: if (!isRemoteStreamLive()) { return false; } return idleReason == MediaStatus.IDLE_REASON_CANCELED; default : break; } return false; }
A helper method to determine if, given a player state and an idle reason (if the state is idle) will warrant having a UI for remote presentation of the remote content.
@Ignore public void testIngestTemplateThreaded(){ File temp=null; try { temp=File.createTempFile("testFile2","csv"); } catch ( IOException e) { e.printStackTrace(); fail(); } ByteBuffer data=sourceBuffer.asReadOnlyBuffer(); Pipe linesRing=new Pipe(linesRingConfig); Pipe fieldsRing=new Pipe(fieldsRingConfig); Pipe flatFileRing=new Pipe(flatFileRingConfig); GraphManager gm=new GraphManager(); LineSplitterByteBufferStage lineSplitter=new LineSplitterByteBufferStage(gm,data,linesRing); FieldSplitterStage fieldSplitter=new FieldSplitterStage(gm,linesRing,fieldsRing); MetaMessagesToCSVStage csvBuilderStage=new MetaMessagesToCSVStage(gm,fieldsRing,flatFileRing); FileChannel outputFileChannel; try { outputFileChannel=new RandomAccessFile(temp,"rws").getChannel(); } catch ( FileNotFoundException e1) { throw new RuntimeException(e1); } FileWriteStage fileWriter=new FileWriteStage(gm,flatFileRing,outputFileChannel); StageScheduler ss=new ThreadPerStageScheduler(gm); ss.startup(); boolean ok=ss.awaitTermination(10,TimeUnit.SECONDS); assertEquals("File size does not match:" + temp.getAbsolutePath(),sourceBuffer.remaining(),temp.length()); byte[] expected=new byte[sourceBuffer.remaining()]; byte[] rebuilt=new byte[sourceBuffer.remaining()]; try { InputStream testStream=SmallCSVParseTest.class.getResourceAsStream(TEST_FILE); testStream.read(expected); testStream.close(); } catch ( Exception e) { e.printStackTrace(); fail(); } try { InputStream builtStream=new FileInputStream(temp); builtStream.read(rebuilt); builtStream.close(); } catch ( Exception e) { e.printStackTrace(); fail(); } }
This is the example you are looking for TODO: AAA, this test is broken and needs to be fixed ASAP, part of the stage migration.
public T caseTClass(TClass object){ return null; }
Returns the result of interpreting the object as an instance of '<em>TClass</em>'. <!-- begin-user-doc --> This implementation returns null; returning a non-null result will terminate the switch. <!-- end-user-doc -->
public static JSONArray toJSONArray(JSONTokener x) throws JSONException { return toJSONArray(rowToJSONArray(x),x); }
Produce a JSONArray of JSONObjects from a comma delimited text string, using the first row as a source of names.
public boolean connect(){ try { mService.clientConnect(mClientIf,mDevice.getAddress(),false); return true; } catch ( RemoteException e) { Log.e(TAG,"",e); return false; } }
Connect back to remote device. <p>This method is used to re-connect to a remote device after the connection has been dropped. If the device is not in range, the re-connection will be triggered once the device is back in range.
public static boolean injectIterationCount(double iterations,boolean condition){ return injectBranchProbability(1. - 1. / iterations,condition); }
Injects an average iteration count of a loop into the probability information of a loop exit condition. The iteration count specifies how often the condition is checked, i.e. in for and while loops it is one more than the body iteration count, and in do-while loops it is equal to the body iteration count. The iteration count must be >= 1.0. Example usage (it specifies that the expected iteration count of the loop condition is 500, so the iteration count of the loop body is 499): <code> for (int i = 0; injectIterationCount(500, i < array.length); i++) { // ... } </code>
public FilterExprIterator(){ super(null); }
Create a FilterExprIterator object.
private static String createLibraryPrefix(){ OSType osType=calculateOS(); switch (osType) { case ANDROID: case APPLE: case LINUX: case SUN: return "lib"; case WINDOWS: return ""; default : break; } return ""; }
Returns the prefix for dynamically linked libraries on the current OS. That is, returns <code>"lib"</code> on Apple, Linux and Sun, and the empty String on Windows.
public static void showException(final Throwable exception){ final Dialog dialog=new Dialog(); dialog.setTitle(ResourceManager.getLabel(ResourceManager.EXCEPTION)); final String msg=exception.getMessage(); final String className=exception.getClass().getName(); final boolean noMessage=msg == null || msg.trim().length() == 0; dialog.getMessageArea().setTitle(noMessage ? className : msg).setText(noMessage ? "" : className).setIcon(Display.getCurrent().getSystemImage(SWT.ICON_ERROR)).setException(exception); dialog.getFooterArea().setExpanded(true); dialog.setButtonType(OpalDialogType.CLOSE); dialog.show(); }
Display a dialog box with an exception
public synchronized void flush() throws IOException { checkNotClosed(); trimToSize(); journalWriter.flush(); }
Force buffered operations to the filesystem.
public Graph search(){ this.logger.log("info","Starting Fast Adjacency Search."); Graph graph=new EdgeListGraphSingleConnections(test.getVariables()); sepsets=new SepsetMap(); sepsets.setReturnEmptyIfNotSet(true); int _depth=depth; if (_depth == -1) { _depth=1000; } Map<Node,Set<Node>> adjacencies=new ConcurrentSkipListMap<>(); List<Node> nodes=graph.getNodes(); for ( Node node : nodes) { adjacencies.put(node,new HashSet<Node>()); } double alpha=test.getAlpha(); for (double _alpha=0.9; _alpha > alpha; _alpha/=2.0) { System.out.println("_alpha = " + _alpha); searchAtDepth0(nodes,test,adjacencies); test.setAlpha(_alpha); boolean didIt=false; for (int d=didIt ? 1 : 0; d <= _depth; d++) { boolean more; more=searchAtDepth(nodes,test,adjacencies,d); if (!more) { break; } } } test.setAlpha(alpha); if (verbose) { out.println("Finished with search, constructing Graph..."); } for (int i=0; i < nodes.size(); i++) { for (int j=i + 1; j < nodes.size(); j++) { Node x=nodes.get(i); Node y=nodes.get(j); if (adjacencies.get(x).contains(y)) { graph.addUndirectedEdge(x,y); } } } if (verbose) { out.println("Finished constructing Graph."); } if (verbose) { this.logger.log("info","Finishing Fast Adjacency Search."); } return graph; }
Discovers all adjacencies in data. The procedure is to remove edges in the graph which connect pairs of variables which are independent conditional on some other set of variables in the graph (the "sepset"). These are removed in tiers. First, edges which are independent conditional on zero other variables are removed, then edges which are independent conditional on one other variable are removed, then two, then three, and so on, until no more edges can be removed from the graph. The edges which remain in the graph after this procedure are the adjacencies in the data.
public final ADFContext push(ADFContext obj){ if (onStack == stack.length) { ADFContext[] newstack=new ADFContext[stack.length * 2]; System.arraycopy(stack,0,newstack,0,stack.length); stack=newstack; } stack[onStack++]=obj; return obj; }
Pushes an ADFContext onto the main stack. The best way to get an ADFContext to push onto the stack is with get(). Returns obj.
void modCenter(int modulus){ mod(modulus); for (int j=0; j < coeffs.length; j++) { while (coeffs[j] < modulus / 2) { coeffs[j]+=modulus; } while (coeffs[j] >= modulus / 2) { coeffs[j]-=modulus; } } }
Reduces all coefficients to the interval [-modulus/2, modulus/2)
public Gateway createGateway(){ GatewayImpl gateway=new GatewayImpl(); return gateway; }
<!-- begin-user-doc --> <!-- end-user-doc -->
private void printStatusMessages(AbstractTestSuiteChromosome<? extends ExecutableChromosome> suite,int coveredBranches,double fitness){ if (coveredBranches > maxCoveredBranches) { maxCoveredBranches=coveredBranches; logger.info("(Branches) Best individual covers " + coveredBranches + "/"+ (totalBranches * 2)+ " branches"); logger.info("Fitness: " + fitness + ", size: "+ suite.size()+ ", length: "+ suite.totalLengthOfTestCases()); } if (fitness < bestFitness) { logger.info("(Fitness) Best individual covers " + coveredBranches + "/"+ (totalBranches * 2)+ " branches"); bestFitness=fitness; logger.info("Fitness: " + fitness + ", size: "+ suite.size()+ ", length: "+ suite.totalLengthOfTestCases()); } }
Some useful debug information
public boolean isBuilt(){ return _built; }
Used to determine if this train has been built.
public ConditionalRoute createConditionalRoute(){ ConditionalRouteImpl conditionalRoute=new ConditionalRouteImpl(); return conditionalRoute; }
<!-- begin-user-doc --> <!-- end-user-doc -->
public String toString(){ return "TerminalFactory for type " + type + " from provider "+ provider.getName(); }
Returns a string representation of this TerminalFactory.
public UnitName createUnitName(){ UnitNameImpl unitName=new UnitNameImpl(); return unitName; }
<!-- begin-user-doc --> <!-- end-user-doc -->
protected String doIt() throws Exception { log.info("M_Product_ID=" + p_M_Product_ID); if (p_M_Product_ID == 0) throw new AdempiereUserError("@NotFound@: @M_Product_ID@ = " + p_M_Product_ID); MProduct product=MProduct.get(getCtx(),p_M_Product_ID); if (product.get_ID() != p_M_Product_ID) throw new AdempiereUserError("@NotFound@: @M_Product_ID@ = " + p_M_Product_ID); if (MCostDetail.processProduct(product,get_TrxName())) return "@OK@"; return "@Error@"; }
Perform process.