code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
@RequestProcessing(value="/admin",method=HTTPRequestMethod.GET) @Before(adviceClass={StopwatchStartAdvice.class,AdminCheck.class}) @After(adviceClass=StopwatchEndAdvice.class) public void showIndex(final HTTPRequestContext context,final HttpServletRequest request,final HttpServletResponse response) throws Exception {
final AbstractFreeMarkerRenderer renderer=new SkinRenderer();
context.setRenderer(renderer);
renderer.setTemplateName("admin/index.ftl");
final Map<String,Object> dataModel=renderer.getDataModel();
filler.fillHeaderAndFooter(request,response,dataModel);
}
| Shows admin index. |
public boolean isCompleteForPhotoCaptureEvent(){
return (mMode != null) && (mFilename != null) && (mExifInterface != null)&& (mIsFrontFacing != null)&& (mIsHdr != null)&& (mZoom != null)&& (mFlashSetting != null)&& (mGridLinesOn != null)&& (mTimerSeconds != null)&& (mTouchCoordinate != null)&& (mVolumeButtonShutter != null);
}
| Returns whether all the fields in the CaptureSessionStatsCollector are set or not. |
@DSSink({DSSinkKind.NETWORK}) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:36:28.933 -0500",hash_original_method="5FC4A2324FC6DD99D16BF2BD98355D7B",hash_generated_method="F6F0B09859D5F33E88782A14F5B94A7F") public void sendDtmf(int code){
sendDtmf(code,null);
}
| Sends a DTMF code. According to <a href="http://tools.ietf.org/html/rfc2833">RFC 2883</a>, event 0--9 maps to decimal value 0--9, '*' to 10, '#' to 11, event 'A'--'D' to 12--15, and event flash to 16. Currently, event flash is not supported. |
public void add(String keyword,byte id){
int key=getStringMapKey(keyword);
map[key]=new Keyword(keyword.toCharArray(),id,map[key]);
}
| Adds a key-value mapping. |
@Override public String toBundleName(String baseName,Locale locale){
String newBaseName=baseName;
String lang=locale.getLanguage();
if (lang.length() > 0) {
if (baseName.startsWith(JRE.getUtilResourcesPackage()) || baseName.startsWith(JRE.getTextResourcesPackage())) {
assert JRE.getUtilResourcesPackage().length() == JRE.getTextResourcesPackage().length();
int index=JRE.getUtilResourcesPackage().length();
if (baseName.indexOf(DOTCLDR,index) > 0) {
index+=DOTCLDR.length();
}
newBaseName=baseName.substring(0,index + 1) + lang + baseName.substring(index);
}
}
return super.toBundleName(newBaseName,locale);
}
| Changes baseName to its per-language package name and calls the super class implementation. For example, if the baseName is "sun.text.resources.FormatData" and locale is ja_JP, the baseName is changed to "sun.text.resources.ja.FormatData". If baseName contains "cldr", such as "sun.text.resources.cldr.FormatData", the name is changed to "sun.text.resources.cldr.jp.FormatData". |
private void showFeedback(String message){
if (myHost != null) {
myHost.showFeedback(message);
}
else {
System.out.println(message);
}
}
| Used to communicate feedback pop-up messages between a plugin tool and the main Whitebox user-interface. |
public PartialResponseWriter(ResponseWriter writer){
super(writer);
}
| <p class="changed_added_2_0">Create a <code>PartialResponseWriter</code>.</p> |
public DrawerBuilder addStickyDrawerItems(@NonNull IDrawerItem... stickyDrawerItems){
if (this.mStickyDrawerItems == null) {
this.mStickyDrawerItems=new ArrayList<>();
}
Collections.addAll(this.mStickyDrawerItems,stickyDrawerItems);
return this;
}
| Add a initial DrawerItem or a DrawerItem Array for the StickyDrawerFooter |
@Override public void connectStorage(URI storage) throws ControllerException {
StorageSystem storageObj=null;
try {
storageObj=_dbClient.queryObject(StorageSystem.class,storage);
}
catch ( Exception e) {
throw DeviceControllerException.exceptions.connectStorageFailedDb(e);
}
if (storageObj == null) {
throw DeviceControllerException.exceptions.connectStorageFailedNull();
}
BlockStorageDevice storageDevice=getDevice(storageObj.getSystemType());
storageDevice.doConnect(storageObj);
_log.info("Adding to storage device to work pool: {}",storageObj.getId());
}
| Creates a connection to monitor events generated by the storage identified by the passed URI. |
public static String s1(int v){
char[] result=new char[3];
if (v < 0) {
result[0]='-';
v=-v;
}
else {
result[0]='+';
}
for (int i=0; i < 2; i++) {
result[2 - i]=Character.forDigit(v & 0x0f,16);
v>>=4;
}
return new String(result);
}
| Formats an <code>int</code> as a 1-byte signed hex value. |
public SimpleQueryStringBuilder defaultOperator(Operator defaultOperator){
this.operator=defaultOperator;
return this;
}
| Specify the default operator for the query. Defaults to "OR" if no operator is specified |
public CompositeShapePainter(Shape shape){
if (shape == null) {
throw new IllegalArgumentException();
}
this.shape=shape;
}
| Constructs a new empty <tt>CompositeShapePainter</tt>. |
static String readLine(BufferedReader in,File inputFile){
String line=null;
try {
line=in.readLine();
}
catch ( Exception e) {
System.err.println("Can't read from '" + inputFile + "': "+ e);
System.exit(1);
}
return line;
}
| Reads a single line from the specified input stream, handling any exception by reporting the error and exiting the program. |
public boolean isImplicationDefiniteClause(){
return isDefiniteClause() && cachedNegativeSymbols.size() >= 1;
}
| Determine if an implication definite clause. An implication definite clause is disjunction of literals of which exactly 1 is positive and there is 1 or more negative literals. |
public Timex3_Type(JCas jcas,Type casType){
super(jcas,casType);
casImpl.getFSClassRegistry().addGeneratorForType((TypeImpl)this.casType,getFSGenerator());
casFeat_filename=jcas.getRequiredFeatureDE(casType,"filename","uima.cas.String",featOkTst);
casFeatCode_filename=(null == casFeat_filename) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_filename).getCode();
casFeat_sentId=jcas.getRequiredFeatureDE(casType,"sentId","uima.cas.Integer",featOkTst);
casFeatCode_sentId=(null == casFeat_sentId) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_sentId).getCode();
casFeat_firstTokId=jcas.getRequiredFeatureDE(casType,"firstTokId","uima.cas.Integer",featOkTst);
casFeatCode_firstTokId=(null == casFeat_firstTokId) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_firstTokId).getCode();
casFeat_allTokIds=jcas.getRequiredFeatureDE(casType,"allTokIds","uima.cas.String",featOkTst);
casFeatCode_allTokIds=(null == casFeat_allTokIds) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_allTokIds).getCode();
casFeat_timexId=jcas.getRequiredFeatureDE(casType,"timexId","uima.cas.String",featOkTst);
casFeatCode_timexId=(null == casFeat_timexId) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_timexId).getCode();
casFeat_timexInstance=jcas.getRequiredFeatureDE(casType,"timexInstance","uima.cas.Integer",featOkTst);
casFeatCode_timexInstance=(null == casFeat_timexInstance) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_timexInstance).getCode();
casFeat_timexType=jcas.getRequiredFeatureDE(casType,"timexType","uima.cas.String",featOkTst);
casFeatCode_timexType=(null == casFeat_timexType) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_timexType).getCode();
casFeat_timexValue=jcas.getRequiredFeatureDE(casType,"timexValue","uima.cas.String",featOkTst);
casFeatCode_timexValue=(null == casFeat_timexValue) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_timexValue).getCode();
casFeat_foundByRule=jcas.getRequiredFeatureDE(casType,"foundByRule","uima.cas.String",featOkTst);
casFeatCode_foundByRule=(null == casFeat_foundByRule) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_foundByRule).getCode();
casFeat_timexQuant=jcas.getRequiredFeatureDE(casType,"timexQuant","uima.cas.String",featOkTst);
casFeatCode_timexQuant=(null == casFeat_timexQuant) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_timexQuant).getCode();
casFeat_timexFreq=jcas.getRequiredFeatureDE(casType,"timexFreq","uima.cas.String",featOkTst);
casFeatCode_timexFreq=(null == casFeat_timexFreq) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_timexFreq).getCode();
casFeat_timexMod=jcas.getRequiredFeatureDE(casType,"timexMod","uima.cas.String",featOkTst);
casFeatCode_timexMod=(null == casFeat_timexMod) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_timexMod).getCode();
casFeat_emptyValue=jcas.getRequiredFeatureDE(casType,"emptyValue","uima.cas.String",featOkTst);
casFeatCode_emptyValue=(null == casFeat_emptyValue) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_emptyValue).getCode();
}
| initialize variables to correspond with Cas Type and Features |
public void compose(StylesheetRoot sroot) throws TransformerException {
resolvePrefixTables();
ElemTemplateElement t=getFirstChildElem();
m_hasTextLitOnly=((t != null) && (t.getXSLToken() == Constants.ELEMNAME_TEXTLITERALRESULT) && (t.getNextSiblingElem() == null));
StylesheetRoot.ComposeState cstate=sroot.getComposeState();
cstate.pushStackMark();
}
| This function is called after everything else has been recomposed, and allows the template to set remaining values that may be based on some other property that depends on recomposition. |
public T caseUnknownTypeRef(UnknownTypeRef object){
return null;
}
| Returns the result of interpreting the object as an instance of '<em>Unknown Type Ref</em>'. <!-- begin-user-doc --> This implementation returns null; returning a non-null result will terminate the switch. <!-- end-user-doc --> |
public static ImageSource resource(int resId){
return new ImageSource(resId);
}
| Create an instance from a resource. The correct resource for the device screen resolution will be used. |
public void appendToDoc(String text,Font f,Color fg,Color bg,boolean underline,boolean setFG){
if (text != null) {
int fontIndex=f == null ? 0 : (getFontIndex(fontList,f) + 1);
if (fontIndex != lastFontIndex) {
document.append("\\f").append(fontIndex);
lastFontIndex=fontIndex;
lastWasControlWord=true;
}
if (f != null) {
int fontSize=fixFontSize(f.getSize2D());
if (fontSize != lastFontSize) {
document.append("\\fs").append(fontSize);
lastFontSize=fontSize;
lastWasControlWord=true;
}
if (f.isBold() != lastBold) {
document.append(lastBold ? "\\b0" : "\\b");
lastBold=!lastBold;
lastWasControlWord=true;
}
if (f.isItalic() != lastItalic) {
document.append(lastItalic ? "\\i0" : "\\i");
lastItalic=!lastItalic;
lastWasControlWord=true;
}
}
else {
if (lastFontSize != DEFAULT_FONT_SIZE) {
document.append("\\fs").append(DEFAULT_FONT_SIZE);
lastFontSize=DEFAULT_FONT_SIZE;
lastWasControlWord=true;
}
if (lastBold) {
document.append("\\b0");
lastBold=false;
lastWasControlWord=true;
}
if (lastItalic) {
document.append("\\i0");
lastItalic=false;
lastWasControlWord=true;
}
}
if (underline) {
document.append("\\ul");
lastWasControlWord=true;
}
if (setFG) {
int fgIndex=0;
if (fg != null) {
fgIndex=getIndex(colorList,fg) + 1;
}
if (fgIndex != lastFGIndex) {
document.append("\\cf").append(fgIndex);
lastFGIndex=fgIndex;
lastWasControlWord=true;
}
}
if (bg != null) {
int pos=getIndex(colorList,bg);
document.append("\\highlight").append(pos + 1);
lastWasControlWord=true;
}
if (lastWasControlWord) {
document.append(' ');
lastWasControlWord=false;
}
escapeAndAdd(document,text);
if (bg != null) {
document.append("\\highlight0");
lastWasControlWord=true;
}
if (underline) {
document.append("\\ul0");
lastWasControlWord=true;
}
}
}
| Appends styled text to the RTF document being generated. |
public boolean userCanViewDept(int connectedUserId,String entidad) throws Exception {
boolean can=false;
try {
can=hasUserDeptAuth(connectedUserId,USER_ACTION_ID_VIEW,ISicresAdminDefsKeys.NULL_ID,ISicresAdminDefsKeys.NULL_ID,ISicresAdminDefsKeys.NULL_ID,entidad);
}
catch ( Exception e) {
_logger.error(e);
throw e;
}
return can;
}
| Obtiene si el usuario conectado tiene permiso de consulta de departamento. |
public XMLEncoder(OutputStream out){
this(out,"UTF-8",true,0);
}
| Creates a new XML encoder to write out <em>JavaBeans</em> to the stream <code>out</code> using an XML encoding. |
public static Dog maxDog(Dog[] dogs){
Dog maxDog=dogs[0];
for ( Dog d : dogs) {
if (d.size > maxDog.size) {
maxDog=d;
}
}
return maxDog;
}
| Returns the max dog in a dog array |
@Override public void markAsMapped(Address start,int bytes){
int startChunk=addressToMmapChunksDown(start);
int endChunk=addressToMmapChunksUp(start.plus(bytes));
for (int i=startChunk; i <= endChunk; i++) mapped[i]=MAPPED;
}
| Mark a range of pages as having (already) been mapped. This is useful where the VM has performed the mapping of the pages itself. |
@Override public void logoutRequest(Message arg0,HttpServletRequest request,HttpServletResponse response,String tenant){
Validate.notEmpty(tenant);
LogoutState loState=new LogoutState(request,response,sessionManager,null,null);
ValidationResult vr=new ValidationResult(arg0.getValidationResult().getResponseCode(),arg0.getStatus(),arg0.getSubstatus());
loState.setValidationResult(vr);
this.setLogoutState(loState);
this.getLogoutState().setProcessingState(ProcessingState.PARSED);
loState.getIdmAccessor().setTenant(tenant);
Session lotusSession=findSessionIdByExtSessionId(arg0.getSessionIndex());
if (lotusSession == null) {
logger.warn("No session found matching external session: {}",arg0.getSessionIndex());
return;
}
loState.setSessionId(lotusSession.getId());
loState.setIssuerValue(lotusSession.getExtIDPUsed().getEntityID());
loState.removeResponseHeaders();
try {
SamlServiceImpl.sendSLORequestsToOtherParticipants(tenant,loState);
}
catch ( IOException e) {
logger.error("Caught IOException in sending logout request to service providers.");
}
}
| Callback function at receiving a logout request from the trusted IDP. This function will find corresponding lotus login session, send a slo request to each of the session participants. The client library sloconstroller will respond to slo requester when get back from this function. |
@Override public int insert(String elem){
int firstIndex=(int)(elem.charAt(0) - 'a');
int lastIndex=(int)(elem.charAt(elem.length() - 2) - 'a');
storage[firstIndex * 26 + lastIndex]=elem;
return 1;
}
| Insert element into collection. <p> Should the count of attempted slots reach the array size, declare that the element cannot be added (either because of a poor hash function or because the array is full). <p> If element already exists within collection, return its position. That is, no duplicates are allowed, yet we silently ignore requests to repeatedly add the same element into the collection. |
public LinkedIntegerMap(){
m_values=new LinkedHashMap<>();
}
| Creates new IntegerMap |
private List<Node> possibleParents(Node x,List<Node> nodes,IKnowledge knowledge){
List<Node> possibleParents=new LinkedList<>();
String _x=x.getName();
for ( Node z : nodes) {
String _z=z.getName();
if (possibleParentOf(_z,_x,knowledge)) {
possibleParents.add(z);
}
}
return possibleParents;
}
| Removes from the list of nodes any that cannot be parents of x given the background knowledge. |
public File createPDF(){
try {
File temp=File.createTempFile(get_TableName() + get_ID() + "_",".pdf");
return createPDF(temp);
}
catch ( Exception e) {
log.severe("Could not create PDF - " + e.getMessage());
}
return null;
}
| Create PDF |
public static void main(String[] args){
String a=args[0].replaceAll(" ","");
a=a.replaceAll("[+]","#+#");
a=a.replaceAll("[-]","#-#");
a=a.replaceAll("[*]","#*#");
a=a.replaceAll("[/]","#/#");
args=a.split("#");
if (args.length != 3) {
System.out.println("Usage: java Calculator operand1 operator operand2");
System.exit(0);
}
int result=0;
switch (args[1].charAt(0)) {
case '+':
result=Integer.parseInt(args[0]) + Integer.parseInt(args[2]);
break;
case '-':
result=Integer.parseInt(args[0]) - Integer.parseInt(args[2]);
break;
case '*':
result=Integer.parseInt(args[0]) * Integer.parseInt(args[2]);
break;
case '/':
result=Integer.parseInt(args[0]) / Integer.parseInt(args[2]);
break;
}
System.out.println(args[0] + ' ' + args[1]+ ' '+ args[2]+ " = "+ result);
}
| Main method |
protected void initAdapter(){
try {
XmlParser parse=new XmlParser(getContext(),mChangeLogFileResourceId);
ChangeLog chg=new ChangeLog();
if (chg != null) {
mAdapter=new ChangeLogAdapter(getContext(),chg.getRows());
mAdapter.setmRowLayoutId(mRowLayoutId);
mAdapter.setmRowHeaderLayoutId(mRowHeaderLayoutId);
new ParseAsyncTask(mAdapter,parse).execute();
setAdapter(mAdapter);
}
else {
setAdapter(null);
}
}
catch ( Exception e) {
Log.e(TAG,getResources().getString(R.string.changelog_internal_error_parsing),e);
}
}
| Init adapter |
private boolean hasChar(){
return this.pos < this.len;
}
| Are there any characters left to parse? |
private static void addAndCreateSourceEntry(IJavaProject javaProject,String directoryName,String outputDirectoryName) throws CoreException {
IFolder srcFolder=javaProject.getProject().getFolder(directoryName);
ResourceUtils.createFolderStructure(javaProject.getProject(),srcFolder.getProjectRelativePath());
IPath workspaceRelOutPath=null;
if (outputDirectoryName != null) {
IFolder outFolder=javaProject.getProject().getFolder(outputDirectoryName);
ResourceUtils.createFolderStructure(javaProject.getProject(),outFolder.getProjectRelativePath());
workspaceRelOutPath=outFolder.getFullPath();
}
JavaProjectUtilities.addRawClassPathEntry(javaProject,JavaCore.newSourceEntry(srcFolder.getFullPath(),ClasspathEntry.EXCLUDE_NONE,workspaceRelOutPath));
}
| Create a source entry (including the dir structure) and add it to the raw classpath. |
@SuppressWarnings("unchecked") public static <K,V>Map<K,V> of(){
return (Map<K,V>)ImmutableCollections.Map0.EMPTY_MAP;
}
| Returns an immutable map containing zero mappings. See <a href="#immutable">Immutable Map Static Factory Methods</a> for details. |
@Override public boolean isActive(){
return amIActive;
}
| Used by the Whitebox GUI to tell if this plugin is still running. |
private BarcodeFormat parseBarCodeString(String c){
if ("aztec".equals(c)) {
return BarcodeFormat.AZTEC;
}
else if ("ean13".equals(c)) {
return BarcodeFormat.EAN_13;
}
else if ("ean8".equals(c)) {
return BarcodeFormat.EAN_8;
}
else if ("ean8".equals(c)) {
return BarcodeFormat.EAN_8;
}
else if ("qr".equals(c)) {
return BarcodeFormat.QR_CODE;
}
else if ("ean8".equals(c)) {
return BarcodeFormat.EAN_8;
}
else if ("pdf417".equals(c)) {
return BarcodeFormat.PDF_417;
}
else if ("upce".equals(c)) {
return BarcodeFormat.UPC_E;
}
else if ("datamatrix".equals(c)) {
return BarcodeFormat.DATA_MATRIX;
}
else if ("code39".equals(c)) {
return BarcodeFormat.CODE_39;
}
else if ("code93".equals(c)) {
return BarcodeFormat.CODE_93;
}
else if ("interleaved2of5".equals(c)) {
return BarcodeFormat.ITF;
}
else if ("codabar".equals(c)) {
return BarcodeFormat.CODABAR;
}
else if ("code128".equals(c)) {
return BarcodeFormat.CODE_128;
}
else if ("maxicode".equals(c)) {
return BarcodeFormat.MAXICODE;
}
else if ("rss14".equals(c)) {
return BarcodeFormat.RSS_14;
}
else if ("rssexpanded".equals(c)) {
return BarcodeFormat.RSS_EXPANDED;
}
else if ("upca".equals(c)) {
return BarcodeFormat.UPC_A;
}
else if ("upceanextension".equals(c)) {
return BarcodeFormat.UPC_EAN_EXTENSION;
}
else {
android.util.Log.v("RCTCamera","Unsupported code.. [" + c + "]");
return null;
}
}
| Parse barcodes as BarcodeFormat constants. Supports all iOS codes except [code138, code39mod43, itf14] Additionally supports [codabar, code128, maxicode, rss14, rssexpanded, upca, upceanextension] |
public static int[][] add(int[][] input1,int[][] input2) throws Exception {
int rows=input1.length;
int columns=input1[0].length;
if (input2.length != rows) {
throw new Exception("Row length of arrays are not equal");
}
if (input2[0].length != columns) {
throw new Exception("Column length of arrays are not equal");
}
int[][] returnValues=new int[rows][columns];
for (int r=0; r < rows; r++) {
for (int c=0; c < columns; c++) {
returnValues[r][c]=input1[r][c] + input2[r][c];
}
}
return returnValues;
}
| Adds two matrices together |
public void draw(Shape s){
System.out.println("draw(Shape)");
}
| Strokes the outline of a <code>Shape</code> using the settings of the current <code>Graphics2D</code> context. The rendering attributes applied include the <code>Clip</code>, <code>Transform</code>, <code>Paint</code>, <code>Composite</code> and <code>Stroke</code> attributes. |
static void tick(){
if (Timings.isTimingsEnabled()) {
boolean violated=Timings.fullServerTickTimer.isViolated();
for ( Timing timing : TIMINGS) {
if (timing.isSpecial()) {
continue;
}
timing.tick(violated);
}
TimingsHistory.playerTicks+=Server.getInstance().getOnlinePlayers().size();
TimingsHistory.timedTicks++;
}
}
| Called every tick to count the number of times a timer caused TPS loss. |
public void remove(){
src.remove();
}
| Removes the last visited block for the file version. |
public synchronized void closeDriver(){
if (camera != null) {
camera.release();
camera=null;
}
}
| Closes the camera driver if still in use. |
public int sceKernelPollSema(int semaid,int signal){
if (signal <= 0) {
log.warn(String.format("sceKernelPollSema id=0x%X, signal=%d: bad signal",semaid,signal));
return ERROR_KERNEL_ILLEGAL_COUNT;
}
SceKernelSemaInfo sema=semaMap.get(semaid);
return hleKernelPollSema(sema,signal);
}
| This is attempt to signal the sema and always return immediately |
private int allocateBPOneToOne() throws Exception {
int count=0;
for (int p=0; p < m_payments.length; p++) {
MPayment payment=m_payments[p];
if (payment.isAllocated()) continue;
BigDecimal allocatedAmt=payment.getAllocatedAmt();
log.info(payment + ", Allocated=" + allocatedAmt);
if (allocatedAmt != null && allocatedAmt.signum() != 0) continue;
BigDecimal availableAmt=payment.getPayAmt().add(payment.getDiscountAmt()).add(payment.getWriteOffAmt()).add(payment.getOverUnderAmt());
if (!payment.isReceipt()) availableAmt=availableAmt.negate();
log.fine("Available=" + availableAmt);
for (int i=0; i < m_invoices.length; i++) {
MInvoice invoice=m_invoices[i];
if (invoice == null || invoice.isPaid()) continue;
if (payment.getC_Currency_ID() == invoice.getC_Currency_ID()) {
BigDecimal openAmt=invoice.getOpenAmt(true,null);
if (!invoice.isSOTrx()) openAmt=openAmt.negate();
BigDecimal difference=availableAmt.subtract(openAmt).abs();
log.fine(invoice + ", Open=" + openAmt+ " - Difference="+ difference);
if (difference.signum() == 0) {
Timestamp dateAcct=payment.getDateAcct();
if (invoice.getDateAcct().after(dateAcct)) dateAcct=invoice.getDateAcct();
if (!createAllocation(payment.getC_Currency_ID(),"1:1 (" + availableAmt + ")",dateAcct,availableAmt,null,null,null,invoice.getC_BPartner_ID(),payment.getC_Payment_ID(),invoice.getC_Invoice_ID(),invoice.getAD_Org_ID())) {
throw new AdempiereSystemError("Cannot create Allocation");
}
processAllocation();
count++;
m_invoices[i]=null;
m_payments[p]=null;
payment=null;
break;
}
}
else {
}
}
}
return count;
}
| Allocate Payment:Invoice 1:1 |
public void incExceptionsOccured(){
this.stats.incInt(exceptionsOccuredId,1);
}
| Increments the number of exceptions occured by 1. |
public static int missilesHit(int missiles,int nMod){
return Compute.missilesHit(missiles,nMod,false);
}
| Maintain backwards compatability. |
private TXEntryState txWriteExistingEntry(final EntryEventImpl event,Object expectedOldValue) throws EntryNotFoundException {
assert !event.isExpiration();
final Object entryKey=event.getKey();
final LocalRegion region=event.getRegion();
final Operation op=event.getOperation();
TXEntryState tx=txReadEntry(event.getKeyInfo(),region,true,expectedOldValue,true);
assert tx != null;
if (tx.existsLocally()) {
final boolean invalidatingInvalidEntry=op.isInvalidate() && Token.isInvalid(tx.getValueInVM(entryKey));
if (!invalidatingInvalidEntry) {
tx.updateForWrite(nextModSerialNum());
}
}
else if (region.isProxy() && !op.isLocal() && !tx.hasOp()) {
tx.updateForWrite(nextModSerialNum());
}
else {
throw new EntryNotFoundException(entryKey.toString());
}
return tx;
}
| Write an existing entry. This form takes an expectedOldValue which, if not null, must be equal to the current value of the entry. If it is not, an EntryNotFoundException is thrown. |
private static void attemptRetryOnException(String logPrefix,Request<?> request,VolleyError exception) throws VolleyError {
RetryPolicy retryPolicy=request.getRetryPolicy();
int oldTimeout=request.getTimeoutMs();
try {
retryPolicy.retry(exception);
}
catch ( VolleyError e) {
request.addMarker(String.format("%s-timeout-giveup [timeout=%s]",logPrefix,oldTimeout));
throw e;
}
request.addMarker(String.format("%s-retry [timeout=%s]",logPrefix,oldTimeout));
}
| Attempts to prepare the request for a retry. If there are no more attempts remaining in the request's retry policy, a timeout exception is thrown. |
public static OFGroup createL3Interface(U32 id){
return OFGroup.of(0 | (id.getRaw() & 0x0FffFFff) | (OFDPAGroupType.L3_INTERFACE << 28));
}
| Only bits 0-27 of id are used. Bits 28-31 are ignored. |
public void displayLineCount(final int linecount){
setCharPosition(null);
setLineNumber(linecount + 1);
}
| Update the line and char display to show the line count. |
public static String stringForQuery(SQLiteDatabase db,String query,String[] selectionArgs){
SQLiteStatement prog=db.compileStatement(query);
try {
return stringForQuery(prog,selectionArgs);
}
finally {
prog.close();
}
}
| Utility method to run the query on the db and return the value in the first column of the first row. |
@Override public void paintComponent(Graphics g){
locations.clear();
g.setColor(background_color);
g.fillRect(0,0,getWidth(),getHeight());
g.setColor(foreground_color);
Graphics2D g2=(Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
FontMetrics fontMetrics=g.getFontMetrics(FONT);
int fontHeight=fontMetrics.getHeight();
g.setFont(FONT);
int topTextY=fontMetrics.getAscent();
int vMargin=fontHeight + MARGIN;
int hMargin=MARGIN;
double width=getWidth() - hMargin * 2;
double height=getHeight() - vMargin * 2;
boolean drawLowerLine=height > -vMargin;
int nowTextX=0;
if (history != null && hoverEntry == -1) {
Integer viewers=history.get(endTime).getViewers();
long ago=System.currentTimeMillis() - endTime;
String text;
if (ago > CONSIDERED_AS_NOW) {
text="latest: " + Helper.formatViewerCount(viewers);
}
else {
text="now: " + Helper.formatViewerCount(viewers);
}
if (viewers == -1) {
text="Stream offline";
}
nowTextX=getWidth() - fontMetrics.stringWidth(text);
g.drawString(text,nowTextX,topTextY);
}
if (history == null || history.size() < 2) {
String text="No viewer history yet";
int textWidth=fontMetrics.stringWidth(text);
int y=getHeight() / 2 + fontMetrics.getDescent();
int x=(getWidth() - textWidth) / 2;
boolean drawInfoText=false;
if (history != null && y < topTextY + fontHeight + 4 && x + textWidth + 7 > nowTextX) {
if (drawLowerLine || nowTextX > textWidth + 5) {
if (drawLowerLine) {
y=getHeight() - 2;
}
else {
y=topTextY;
}
x=0;
drawInfoText=true;
}
}
else {
drawInfoText=true;
}
if (drawInfoText) {
g.drawString(text,x,y);
}
return;
}
String maxValueText="max: " + Helper.formatViewerCount(maxValue);
int maxValueEnd=fontMetrics.stringWidth(maxValueText);
boolean displayMaxValue=true;
if (hoverEntry != -1) {
Integer viewers=history.get(hoverEntry).getViewers();
Date d=new Date(hoverEntry);
String text="Viewers: " + Helper.formatViewerCount(viewers) + " ("+ sdf.format(d)+ ")";
if (viewers == -1) {
text="Stream offline (" + sdf.format(d) + ")";
}
int x=getWidth() - fontMetrics.stringWidth(text);
if (maxValueEnd > x) {
displayMaxValue=false;
}
g.drawString(text,x,topTextY);
}
String minText="min: " + Helper.formatViewerCount(minValue);
int minTextWidth=fontMetrics.stringWidth(minText);
if (drawLowerLine) {
String timeText=makeTimesText(startTime,endTime);
int timeTextWidth=fontMetrics.stringWidth(timeText);
int textX=getWidth() - timeTextWidth;
g.drawString(timeText,textX,getHeight() - 1);
if (minValue >= 1000 && timeTextWidth + minTextWidth > width) {
minText="min: " + minValue / 1000 + "k";
}
}
if (isShowingInfo()) {
if (displayMaxValue) {
g.drawString(maxValueText,0,topTextY);
}
if (drawLowerLine) {
g.drawString(minText,0,getHeight() - 1);
}
else if (maxValueEnd + minTextWidth + 29 < nowTextX) {
g.drawString(minText,maxValueEnd + 10,topTextY);
}
}
if (height < 5) {
return;
}
int range=maxValue - minValue;
if (showFullRange) {
range=maxValue;
}
if (range == 0) {
range=1;
}
double pixelPerViewer=height / range;
double pixelPerTime=width / duration;
int prevX=-1;
int prevY=-1;
Iterator<Entry<Long,StreamInfoHistoryItem>> it=history.entrySet().iterator();
while (it.hasNext()) {
Entry<Long,StreamInfoHistoryItem> entry=it.next();
long time=entry.getKey();
if (time < startTime || time > endTime) {
continue;
}
long offsetTime=time - startTime;
int viewers=entry.getValue().getViewers();
if (viewers == -1) {
viewers=0;
}
int x=(int)(hMargin + offsetTime * pixelPerTime);
int y;
if (showFullRange) {
y=(int)(-vMargin + getHeight() - (viewers) * pixelPerViewer);
}
else {
y=(int)(-vMargin + getHeight() - (viewers - minValue) * pixelPerViewer);
}
if (prevX != -1) {
g.drawLine(x,y,prevX,prevY);
}
prevX=x;
prevY=y;
locations.put(new Point(x,y),time);
}
for ( Point point : locations.keySet()) {
int x=point.x;
int y=point.y;
long seconds=locations.get(point);
StreamInfoHistoryItem historyObject=history.get(seconds);
if (seconds == hoverEntry) {
g.setColor(HOVER_COLOR);
}
else {
if (!historyObject.isOnline()) {
g.setColor(OFFLINE_COLOR);
}
else {
g.setColor(colors.get(seconds));
}
}
g.fillOval(x - POINT_SIZE / 2,y - POINT_SIZE / 2,POINT_SIZE,POINT_SIZE);
}
}
| Draw the text and graph. |
public List<String> explainMismatch(Issue issue){
Objects.requireNonNull(issue);
List<String> result=new LinkedList<>();
for ( IssuePropertyMatcher propertyMatcher : propertyMatchers) {
if (!propertyMatcher.matches(issue)) result.add(propertyMatcher.getMessage(issue));
}
return result;
}
| Returns a list of explanations for each mismatched property matcher for the given issue. |
private String generatePageSQLStatement(boolean tableExists,Map<String,Set<Integer>> dataSourceToUse){
StringBuffer output=new StringBuffer();
output.append("CREATE TABLE IF NOT EXISTS " + GeneratorConstants.TABLE_TPLID_PAGEID + " ("+ "templateId INTEGER UNSIGNED NOT NULL,"+ "pageId INTEGER UNSIGNED NOT NULL, UNIQUE(templateId, pageId));\r\n");
output.append(this.generateSQLStatementForDataInTable(dataSourceToUse,GeneratorConstants.TABLE_TPLID_PAGEID));
if (!tableExists) {
output.append("CREATE INDEX pageIdx ON " + GeneratorConstants.TABLE_TPLID_PAGEID + "(pageId);");
output.append("\r\n");
}
return output.toString();
}
| Generate sql statement for table template id -> page id |
private ImageWriter lookupImageWriterForFormat(String imageFormat){
ImageWriter writer=null;
Iterator iter=ImageIO.getImageWritersByFormatName(imageFormat);
if (iter.hasNext()) {
writer=(ImageWriter)iter.next();
}
return writer;
}
| Utility method to find an imagewriter. |
private void createVMs(Host host){
for (int i=0; i < 4; i++) {
vm[i]=host.getVM(i);
}
}
| this function creates vms in given host |
GridResourceField(@NotNull Field field,@NotNull Annotation ann){
this.field=field;
this.ann=ann;
field.setAccessible(true);
}
| Creates new bean. |
private static void savePgr(DispatchContext dctx,GenericValue pgr){
Map<String,GenericValue> context=UtilMisc.<String,GenericValue>toMap("paymentGatewayResponse",pgr);
LocalDispatcher dispatcher=dctx.getDispatcher();
Delegator delegator=dctx.getDelegator();
try {
dispatcher.addRollbackService("savePaymentGatewayResponse",context,true);
delegator.create(pgr);
}
catch ( Exception e) {
Debug.logError(e,module);
}
}
| Saves either a PaymentGatewayResponse or PaymentGatewayRespMsg value and ensures that the value is persisted even in the event of a rollback. |
protected void onAddEditTextToDialogView(View dialogView,EditText editText){
ViewGroup container=(ViewGroup)dialogView.findViewById(com.android.internal.R.id.edittext_container);
if (container != null) {
container.addView(editText,ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
}
}
| Adds the EditText widget of this preference to the dialog's view. |
@Override public void sendRedirect(String location){
this.request.setAttribute(ATTR_KEY,location);
}
| This method captures the redirect request and stores it to the Request so it can be leveraged later. |
@Override public void process(final DM dm,ReplyProcessor21 processor){
final boolean isDebugEnabled=logger.isTraceEnabled(LogMarker.DM);
final long startTime=getTimestamp();
if (isDebugEnabled) {
logger.trace(LogMarker.DM,"GetReplyMessage process invoking reply processor with processorId: {}",this.processorId);
}
if (processor == null) {
if (isDebugEnabled) {
logger.debug("GetReplyMessage processor not found");
}
return;
}
if (this.versionTag != null) {
this.versionTag.replaceNullIDs(this.getSender());
}
processor.process(this);
if (isDebugEnabled) {
logger.debug("{} Processed {}",processor,this);
}
dm.getStats().incReplyMessageTime(DistributionStats.getStatTime() - startTime);
}
| Processes this message. This method is invoked by the receiver of the message. |
private VarSymbol enterConstant(String name,Type type){
VarSymbol c=new VarSymbol(PUBLIC | STATIC | FINAL,names.fromString(name),type,predefClass);
c.setData(type.constValue());
predefClass.members().enter(c);
return c;
}
| Enter a constant into symbol table. |
public synchronized StringBuffer reverse(){
reverse0();
return this;
}
| Reverses the order of characters in this buffer. |
private void returnData(Object ret){
if (myHost != null) {
myHost.returnData(ret);
}
}
| Used to communicate a return object from a plugin tool to the main Whitebox user-interface. |
public static void reindex(Connection conn) throws SQLException {
init(conn);
removeAllTriggers(conn,TRIGGER_PREFIX);
FullTextSettings setting=FullTextSettings.getInstance(conn);
setting.getWordList().clear();
Statement stat=conn.createStatement();
stat.execute("TRUNCATE TABLE " + SCHEMA + ".WORDS");
stat.execute("TRUNCATE TABLE " + SCHEMA + ".ROWS");
stat.execute("TRUNCATE TABLE " + SCHEMA + ".MAP");
ResultSet rs=stat.executeQuery("SELECT * FROM " + SCHEMA + ".INDEXES");
while (rs.next()) {
String schema=rs.getString("SCHEMA");
String table=rs.getString("TABLE");
createTrigger(conn,schema,table);
indexExistingRows(conn,schema,table);
}
}
| Re-creates the full text index for this database. Calling this method is usually not needed, as the index is kept up-to-date automatically. |
public Object jjtAccept(SyntaxTreeBuilderVisitor visitor,Object data) throws VisitorException {
return visitor.visit(this,data);
}
| Accept the visitor. |
static int findBestSampleSize(int actualWidth,int actualHeight,int desiredWidth,int desiredHeight){
double wr=(double)actualWidth / desiredWidth;
double hr=(double)actualHeight / desiredHeight;
double ratio=Math.min(wr,hr);
float n=1.0f;
while ((n * 2) <= ratio) {
n*=2;
}
return (int)n;
}
| Returns the largest power-of-two divisor for use in downscaling a bitmap that will not result in the scaling past the desired dimensions. |
IVariableBinding resolveField(FieldAccess fieldAccess){
return null;
}
| Resolves the given field access and returns the binding for it. <p> The implementation of <code>FieldAccess.resolveFieldBinding</code> forwards to this method. How the field resolves is often a function of the context in which the field access node is embedded as well as the field access subtree itself. </p> <p> The default implementation of this method returns <code>null</code>. Subclasses may reimplement. </p> |
public ReporterTableAction(String actionName){
super(actionName);
if (reportManager == null) {
setEnabled(false);
}
}
| Create an action with a specific title. <P> Note that the argument is the Action title, not the title of the resulting frame. Perhaps this should be changed? |
@Override public boolean onCreateOptionsMenu(Menu menu){
mTerminalView.showContextMenu();
return false;
}
| Hook system menu to show context menu instead. |
public static RendererPreferences preparePreferences(GLPanel glPanel){
RendererPreferences result=new RendererPreferences(glPanel);
result.setPreferences();
IEclipsePreferences prefs=PreferencesIds.getInstanceNode();
prefs.addPreferenceChangeListener(result);
return result;
}
| Create a new updater for the user's Eclipse preferences, and configure it to keep the OGL renderer up to date. |
private void emitDeserializerImpl(List<Type> expandedTypes,int depth,StringBuilder builder,String inVar,String outVar,String i){
Type type=expandedTypes.get(depth);
String childInVar=inVar + "_";
String childInVarIterator=childInVar + "_iterator";
String childOutVar=outVar + "_";
Class<?> rawClass=getRawClass(type);
if (isList(rawClass)) {
builder.append(i).append(getImplName(type,false)).append(" ").append(outVar).append(" = null;\n");
builder.append(i).append("if (").append(inVar).append(" != null && ").append(inVar).append(".isNull() == null) {\n");
builder.append(i).append(" ").append(outVar).append(" = new ").append(getImplName(type,true)).append("();\n");
builder.append(i).append(" for (int ").append(childInVarIterator).append(" = 0; ").append(childInVarIterator).append(" < ").append(inVar).append(".isArray().size(); ").append(childInVarIterator).append("++) {\n");
builder.append(i).append(" JSONValue ").append(childInVar).append(" = ").append(inVar).append(".isArray().get(").append(childInVarIterator).append(");\n");
emitDeserializerImpl(expandedTypes,depth + 1,builder,childInVar,childOutVar,i + " ");
builder.append(i).append(" ").append(outVar).append(".add(").append(childOutVar).append(");\n");
builder.append(i).append(" }\n");
builder.append(i).append("}\n");
}
else if (isMap(rawClass)) {
String entryVar="key" + depth;
String entriesVar="keySet" + depth;
builder.append(i).append(getImplName(type,false)).append(" ").append(outVar).append(" = null;\n");
builder.append(i).append("if (").append(inVar).append(" != null && ").append(inVar).append(".isNull() == null) {\n");
builder.append(i).append(" ").append(outVar).append(" = new ").append(getImplName(type,true)).append("();\n");
builder.append(i).append(" java.util.Set<String> ").append(entriesVar).append(" = ").append(inVar).append(".isObject().keySet();\n");
builder.append(i).append(" for (String ").append(entryVar).append(" : ").append(entriesVar).append(") {\n");
builder.append(i).append(" JSONValue ").append(childInVar).append(" = ").append(inVar).append(".isObject().get(").append(entryVar).append(");\n");
emitDeserializerImpl(expandedTypes,depth + 1,builder,childInVar,childOutVar,i + " ");
builder.append(i).append(" ").append(outVar).append(".put(").append(entryVar).append(", ").append(childOutVar).append(");\n");
builder.append(i).append(" }\n");
builder.append(i).append("}\n");
}
else if (rawClass.isEnum()) {
String primitiveName=rawClass.getCanonicalName();
builder.append(i).append(primitiveName).append(" ").append(outVar).append(" = ").append(primitiveName).append(".valueOf(").append(inVar).append(".isString().stringValue());\n");
}
else if (getEnclosingTemplate().isDtoInterface(rawClass)) {
String className=getImplName(rawClass,false);
builder.append(i).append(className).append(" ").append(outVar).append(" = ").append(getImplNameForDto(rawClass)).append(".fromJsonObject(").append(inVar).append(");\n");
}
else if (rawClass.equals(String.class)) {
String primitiveName=rawClass.getSimpleName();
builder.append(i).append(primitiveName).append(" ").append(outVar).append(" = ").append(inVar).append(".isString() != null ? ").append(inVar).append(".isString().stringValue() : null;\n");
}
else if (isNumber(rawClass)) {
String primitiveName=rawClass.getSimpleName();
String typeCast=rawClass.equals(double.class) || rawClass.equals(Double.class) ? "" : "(" + getPrimitiveName(rawClass) + ")";
if (rawClass.isPrimitive()) {
builder.append(i).append(primitiveName).append(" ").append(outVar).append(" = ").append(typeCast).append(inVar).append(".isNumber().doubleValue();\n");
}
else {
if (isInteger(rawClass)) {
builder.append(i).append(primitiveName).append(" ").append(outVar).append(" = ").append(inVar).append(".isNumber() != null ? ((Double)").append(inVar).append(".isNumber().doubleValue()).intValue() : null;\n");
}
else if (isFloat(rawClass)) {
builder.append(i).append(primitiveName).append(" ").append(outVar).append(" = ").append(inVar).append(".isNumber() != null ? ((Double)").append(inVar).append(".isNumber().doubleValue()).floatValue() : null;\n");
}
else if (isLong(rawClass)) {
builder.append(i).append(primitiveName).append(" ").append(outVar).append(" = ").append(inVar).append(".isNumber() != null ? ((Double)").append(inVar).append(".isNumber().doubleValue()).longValue() : null;\n");
}
else if (isDouble(rawClass)) {
builder.append(i).append(primitiveName).append(" ").append(outVar).append(" = ").append(inVar).append(".isNumber() != null ? ((Double)").append(inVar).append(".isNumber().doubleValue()).doubleValue() : null;\n");
}
}
}
else if (isBoolean(rawClass)) {
String primitiveName=rawClass.getSimpleName();
if (rawClass.isPrimitive()) {
builder.append(i).append(primitiveName).append(" ").append(outVar).append(" = ").append(inVar).append(".isBoolean().booleanValue();\n");
}
else {
builder.append(i).append(primitiveName).append(" ").append(outVar).append(" = ").append(inVar).append(".isBoolean() != null ? ").append(inVar).append(".isBoolean().booleanValue() : null;\n");
}
}
else if (isAny(rawClass)) {
builder.append(i).append("JSONValue ").append(outVar).append(" = ");
appendCopyJsonExpression(inVar,builder).append(";\n");
}
else {
final Class<?> dtoImplementation=getEnclosingTemplate().getDtoImplementation(rawClass);
if (dtoImplementation != null) {
String className=getImplName(rawClass,false);
builder.append(i).append(className).append(" ").append(outVar).append(" = ").append(dtoImplementation.getCanonicalName()).append(".fromJsonObject(").append(inVar).append(");\n");
}
else {
throw new IllegalArgumentException("Unable to generate client implementation for DTO interface " + getDtoInterface().getCanonicalName() + ". Type "+ rawClass+ " is not allowed to use in DTO interface.");
}
}
}
| Produces code to deserialize the type with the given variable names. |
public ImageWarp(BufferedImage bi,GeoCoordTransformation transform,WorldFile worldFile){
if (bi != null) {
iwidth=bi.getWidth();
iheight=bi.getHeight();
setGeoTrans(transform);
setImageBounds(worldFile);
pixels=getPixels(bi,0,0,iwidth,iheight);
bi=null;
}
}
| Create an image warp with some additional transform information. |
public BoxDataSet(BoxDataSet dataSet){
name=dataSet.name;
variables=new LinkedList<>(dataSet.variables);
dataBox=dataSet.dataBox.copy();
selection=new HashSet<>(dataSet.selection);
multipliers=new HashMap<>(dataSet.multipliers);
knowledge=dataSet.knowledge.copy();
}
| Makes of copy of the given data set. |
public ExporterException(final String msg){
super(msg);
}
| Creates a new exception object. |
void newbuf(){
if (toCopy != null) {
throw new RuntimeException("BUG: Invalid newbuf() before copy()");
}
LengthRecordNode temp=new LengthRecordNode();
temp.currentMessage=mMessage;
temp.currentPosition=mPosition;
temp.next=stack;
stack=temp;
stackSize=stackSize + 1;
mMessage=new ByteArrayOutputStream();
mPosition=0;
}
| Create a new message buffer and push it into the stack. |
public SaveFileAction(Application app,@Nullable View view){
this(app,view,false);
}
| Creates a new instance. |
public BlockParams(){
this.translateX=0.0;
this.translateY=0.0;
this.generateEntities=false;
}
| Creates a new instance. |
public Response onCommand(SMTPSession session,Request request){
return NOT_SUPPORTED;
}
| Handler method called upon receipt of a EXPN command. This method informs the client that the command is not implemented. |
public String toString(){
return "TAG_End";
}
| Debug output. (see NBT_Tag) |
public static boolean isTargetTag(final Component source){
if (source instanceof DragAndDropWrapper) {
final String wrapperData=((DragAndDropWrapper)source).getData().toString();
final String id=wrapperData.replace(SPUIDefinitions.TARGET_TAG_BUTTON,"");
if (wrapperData.contains(SPUIDefinitions.TARGET_TAG_BUTTON) && !id.trim().isEmpty()) {
return true;
}
}
return false;
}
| Checks if component is a target tag. |
public MutablePair(final L left,final R right){
super();
this.left=left;
this.right=right;
}
| Create a new pair instance. |
public PluginValidationException(String msg,String rmtMsg,UUID nodeId){
super(msg);
this.nodeId=nodeId;
this.rmtMsg=rmtMsg;
}
| Constructs invalid plugin exception. |
public IMultiPoint nearest(IMultiPoint target){
OneHelperKDNode top=((OneHelperKDNode)getRoot());
if (top == null || target == null) return null;
DimensionalNode parent=parent(target);
IMultiPoint result=parent.point;
double smallest=target.distance(result);
double best[]=new double[]{smallest};
double raw[]=target.raw();
IMultiPoint betterOne=top.nearest(raw,best);
if (betterOne != null) {
return betterOne;
}
return result;
}
| Find the nearest point in the KDtree to the given point while using multiple threads as helpers. <p> Only returns null if the tree was initially empty. Otherwise, must return some point that belongs to the tree. <p> If tree is empty or if the target is <code>null</code> then <code>null</code> is returned. |
private void executeMove(@NonNull DecoEvent event){
if ((event.getEventType() != DecoEvent.EventType.EVENT_MOVE) && (event.getEventType() != DecoEvent.EventType.EVENT_COLOR_CHANGE)) {
return;
}
if (mChartSeries != null) {
if (mChartSeries.size() <= event.getIndexPosition()) {
throw new IllegalArgumentException("Invalid index: Position out of range (Index: " + event.getIndexPosition() + " Series Count: "+ mChartSeries.size()+ ")");
}
final int index=event.getIndexPosition();
if (index >= 0 && index < mChartSeries.size()) {
ChartSeries item=mChartSeries.get(event.getIndexPosition());
if (event.getEventType() == DecoEvent.EventType.EVENT_COLOR_CHANGE) {
item.startAnimateColorChange(event);
}
else {
item.startAnimateMove(event);
}
}
else {
Log.e(TAG,"Ignoring move request: Invalid array index. Index: " + index + " Size: "+ mChartSeries.size());
}
}
}
| Execute a move event |
public boolean hasLinkedFromUrl(){
return hasValue();
}
| Returns whether it has the value. |
public String toString(){
return "fp=" + filePosition + ", bs="+ bufferStart+ ", de="+ dataEnd+ ", ds="+ dataSize+ ", bl="+ buffer.length+ ", readonly="+ readonly+ ", bm="+ bufferModified;
}
| Create a string representation of this object. |
private Builder read(Schema schema,Instance value) throws Exception {
Instantiator creator=schema.getInstantiator();
if (creator.isDefault()) {
return new Builder(this,criteria,schema,value);
}
return new Injector(this,criteria,schema,value);
}
| This <code>read</code> method performs deserialization of the XML schema class type by traversing the contacts and instantiating them using details from the provided XML element. Because this will convert a non-primitive value it delegates to other converters to perform deserialization of lists and primitives. <p> If any of the required contacts are not present within the provided XML element this will terminate deserialization and throw an exception. The annotation missing is reported in the exception. |
private ProtocolInfo readProtocol(InputStream input) throws IOException {
return mapper.readValue(input,ProtocolInfo.class);
}
| Parses the given JSON file, returning the parsed ProtocolInfo. The JSON format is conveniently and intentionally identical to a serialized ProtocolInfo object, which is identical to the JSON format used by the protocol REST service built into the Guacamole web application. |
public StringBuilder prefixes(StringBuilder query){
query.append("PREFIX wdata: <").append(entityData).append(">\n");
query.append("PREFIX wd: <").append(entity).append(">\n");
query.append("PREFIX wds: <").append(statement).append(">\n");
query.append("PREFIX wdv: <").append(value).append(">\n");
query.append("PREFIX wdref: <").append(reference).append(">\n");
for ( PropertyType p : PropertyType.values()) {
query.append("PREFIX ").append(p.prefix()).append(": <").append(prop).append(p.suffix()).append(">\n");
}
return query;
}
| Add the prefixes for all related uris. |
public static boolean hasNBT(int id){
switch (id) {
case 54:
case 130:
case 142:
case 27:
case 137:
case 52:
case 154:
case 84:
case 25:
case 144:
case 138:
case 176:
case 177:
case 63:
case 119:
case 68:
case 323:
case 117:
case 116:
case 28:
case 66:
case 157:
case 61:
case 62:
case 140:
case 146:
case 149:
case 150:
case 158:
case 23:
case 123:
case 124:
case 29:
case 33:
case 151:
case 178:
case 210:
case 211:
return true;
default :
return false;
}
}
| Check if an id might have nbt |
public OFHello(){
super();
this.type=OFType.HELLO;
this.length=U16.t(MINIMUM_LENGTH);
}
| Construct a ofp_hello message |
public static <FF extends FileFormat>Optional<FF> matchFileName(String fileName,Iterable<FF> fileFormats){
int lastPathSepIdx=Math.max(fileName.lastIndexOf('/'),fileName.lastIndexOf('\\'));
if (lastPathSepIdx >= 0) {
fileName=fileName.substring(lastPathSepIdx + 1);
}
int dotIdx;
while ((dotIdx=fileName.lastIndexOf('.')) >= 0) {
String ext=fileName.substring(dotIdx + 1);
for ( FF fileFormat : fileFormats) {
if (fileFormat.hasDefaultFileExtension(ext)) {
return Optional.of(fileFormat);
}
}
for ( FF fileFormat : fileFormats) {
if (fileFormat.hasFileExtension(ext)) {
return Optional.of(fileFormat);
}
}
fileName=fileName.substring(0,dotIdx);
}
return Optional.empty();
}
| Tries to match the specified file name with the file extensions of the supplied file formats. |
public ParameterizedHashMap(int initialCapacity,Equality keyEquality){
this(initialCapacity,DEFAULT_LOAD_FACTOR,keyEquality);
}
| Constructs an empty <tt>ParameterizedHashMap</tt> with the specified initial capacity, key equality, and the default load factor (0.75). |
public static ITypeBinding normalizeForDeclarationUse(ITypeBinding binding,AST ast){
if (binding.isNullType()) return ast.resolveWellKnownType("java.lang.Object");
if (binding.isPrimitive()) return binding;
binding=normalizeTypeBinding(binding);
if (binding == null || !binding.isWildcardType()) return binding;
ITypeBinding bound=binding.getBound();
if (bound == null || !binding.isUpperbound()) {
ITypeBinding[] typeBounds=binding.getTypeBounds();
if (typeBounds.length > 0) {
return typeBounds[0];
}
else {
return binding.getErasure();
}
}
else {
return bound;
}
}
| Normalizes the binding so that it can be used as a type inside a declaration (e.g. variable declaration, method return type, parameter type, ...). For null bindings, java.lang.Object is returned. For void bindings, <code>null</code> is returned. |
private void updateProgress(String progressLabel,int progress){
if (myHost != null && ((progress != previousProgress) || (!progressLabel.equals(previousProgressLabel)))) {
myHost.updateProgress(progressLabel,progress);
}
previousProgress=progress;
previousProgressLabel=progressLabel;
}
| Used to communicate a progress update between a plugin tool and the main Whitebox user interface. |
private void awaitAcks() throws IOException {
try {
igfsCtx.data().awaitAllAcksReceived(fileInfo.id());
}
catch ( IgniteCheckedException e) {
throw new IOException("Failed to wait for flush acknowledge: " + fileInfo.id,e);
}
}
| Await acknowledgments. |
public AccessTokenUnavailableException(final String message,final Throwable cause){
super(message,cause);
}
| Create a complex instance with a cause included as well as the specified message |
private void namespace(Detail detail) throws Exception {
NamespaceList scope=detail.getNamespaceList();
Namespace namespace=detail.getNamespace();
if (namespace != null) {
decorator.add(namespace);
}
if (scope != null) {
Namespace[] list=scope.value();
for ( Namespace name : list) {
decorator.add(name);
}
}
}
| This is used to acquire the namespace annotations that apply to the scanned class. Namespace annotations are added only if they have not already been extracted from a more specialized class. When scanned all the namespace definitions are used to qualify the XML that is produced from serializing the class. |
private E dequeue(){
int n=size - 1;
if (n < 0) return null;
else {
Object[] array=queue;
E result=(E)array[0];
E x=(E)array[n];
array[n]=null;
Comparator<? super E> cmp=comparator;
if (cmp == null) siftDownComparable(0,x,array,n);
else siftDownUsingComparator(0,x,array,n,cmp);
size=n;
return result;
}
}
| Mechanics for poll(). Call only while holding lock. |
public EmpiricalMeasurementDistribution(double[] distribution,double actualValue){
super(actualValue,0);
this.distribution=distribution;
int countWhereActualIsNotGreater=0;
for (int i=0; i < distribution.length; i++) {
if (distribution[i] >= actualValue) {
countWhereActualIsNotGreater++;
}
}
pValue=(double)countWhereActualIsNotGreater / (double)distribution.length;
}
| Construct an instance with the given distribution of surrogates |
public static byte parseByte(final byte[] b,final int off){
final int size=1;
final int len=b.length - off;
if (len >= size) {
return b[off];
}
else {
throw new ParseException("Not enough bytes to parse a byte.");
}
}
| Parse a single byte in the provided bytes. It looks for a byte in the provided bytes starting at the specified off. <p> If successful, it returns the value of the parsed byte. On failure, it throws a parse exception. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.