code
stringlengths
10
174k
nl
stringlengths
3
129k
public LocatorTransferManager(){ transfersAllowed=!sage.Sage.getBoolean("locator/suspend_transfers",false); failureRetryInterval=sage.Sage.getLong("locator/transfer_failure_retry_period_test",30000); }
Creates a new instance of LocatorTransferManager
public boolean contains(Object objA,Object objB){ SpatialKey a=(SpatialKey)objA; SpatialKey b=(SpatialKey)objB; if (a.isNull() || b.isNull()) { return false; } for (int i=0; i < dimensions; i++) { if (a.min(i) > b.min(i) || a.max(i) < b.max(i)) { return false; } } return true; }
Check whether a contains b.
public void configure(){ TrafficController tc=new LawicellTrafficController(); this.getSystemConnectionMemo().setTrafficController(tc); log.debug("Connecting port"); tc.connectPort(this); log.debug("send version request"); jmri.jmrix.can.CanMessage m=new jmri.jmrix.can.CanMessage(new int[]{'V',13,'S','4',13,'O',13},tc.getCanid()); m.setTranslated(true); tc.sendCanMessage(m,null); this.getSystemConnectionMemo().setProtocol(getOptionState(option1Name)); this.getSystemConnectionMemo().configureManagers(); }
set up all of the other objects to operate with a CAN RS adapter connected to this port
public boolean isDefault(){ Object oo=get_Value(COLUMNNAME_IsDefault); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; }
Get Default.
@Override protected void onStartLoading(){ onContentChanged(); if (mApps != null) { deliverResult(mApps); } if (mPackageObserver == null) { mPackageObserver=new PackageIntentReceiver(this); } boolean configChange=mLastConfig.applyNewConfig(getContext().getResources()); if (takeContentChanged() || mApps == null || configChange) { forceLoad(); } }
Handles a request to start the Loader.
public static IStub CreateStub(IDownloaderService itf){ return new Stub(itf); }
Returns a stub object that, when connected, will listen for marshalled IDownloaderService methods and translate them into calls to the supplied interface.
@Override public HitData rollHitLocation(int table,int side,int aimedLocation,int aimingMode,int cover){ int nArmorLoc=LOC_FRONT; boolean bSide=false; boolean bRearSide=false; boolean bRear=false; int motiveMod=getMotiveSideMod(side); if ((side == ToHitData.SIDE_FRONT) && isHullDown() && !m_bHasNoTurret) { nArmorLoc=LOC_TURRET; } if (side == ToHitData.SIDE_FRONTLEFT) { nArmorLoc=LOC_FRONTLEFT; bSide=true; } else if (side == ToHitData.SIDE_FRONTRIGHT) { nArmorLoc=LOC_FRONTRIGHT; bSide=true; } else if (side == ToHitData.SIDE_REARRIGHT) { nArmorLoc=LOC_REARRIGHT; bRearSide=true; } else if (side == ToHitData.SIDE_REARLEFT) { nArmorLoc=LOC_REARLEFT; bRearSide=true; } else if (side == ToHitData.SIDE_REAR) { nArmorLoc=LOC_REAR; bRear=true; } HitData rv=new HitData(nArmorLoc); boolean bHitAimed=false; if ((aimedLocation != LOC_NONE) && (aimingMode != IAimingModes.AIM_MODE_NONE)) { int roll=Compute.d6(2); if ((5 < roll) && (roll < 9)) { rv=new HitData(aimedLocation,side == ToHitData.SIDE_REAR,true); bHitAimed=true; } } if (!bHitAimed) { switch (Compute.d6(2)) { case 2: rv.setEffect(HitData.EFFECT_CRITICAL); break; case 3: if (bSide) { rv=new HitData(LOC_FRONT,false,HitData.EFFECT_VEHICLE_MOVE_DAMAGED); } else if (bRear) { rv=new HitData(LOC_REARLEFT,false,HitData.EFFECT_VEHICLE_MOVE_DAMAGED); } else if (bRearSide) { rv.setEffect(HitData.EFFECT_VEHICLE_MOVE_DAMAGED); } else { rv=new HitData(LOC_FRONTRIGHT,false,HitData.EFFECT_VEHICLE_MOVE_DAMAGED); } rv.setMotiveMod(motiveMod); break; case 4: rv.setEffect(HitData.EFFECT_VEHICLE_MOVE_DAMAGED); rv.setMotiveMod(motiveMod); break; case 5: if (bRear || !(bSide || bRearSide)) { rv.setEffect(HitData.EFFECT_VEHICLE_MOVE_DAMAGED); rv.setMotiveMod(motiveMod); } break; case 6: case 7: break; case 8: if ((bSide || bRearSide) && !game.getOptions().booleanOption("tacops_vehicle_effective")) { rv.setEffect(HitData.EFFECT_CRITICAL); } break; case 9: if (!game.getOptions().booleanOption("tacops_vehicle_effective")) { rv.setEffect(HitData.EFFECT_VEHICLE_MOVE_DAMAGED); rv.setMotiveMod(motiveMod); } break; case 10: if (!m_bHasNoTurret) { rv=new HitData(LOC_TURRET); } break; case 11: if (!m_bHasNoTurret) { rv=new HitData(LOC_TURRET); } break; case 12: if (m_bHasNoTurret) { rv.setEffect(HitData.EFFECT_CRITICAL); } else { rv=new HitData(LOC_TURRET,false,HitData.EFFECT_CRITICAL); } } } if (table == ToHitData.HIT_SWARM) { rv.setEffect(rv.getEffect() | HitData.EFFECT_CRITICAL); } return rv; }
Rolls up a hit location
public void ping(){ checkSocket(); this.socket.sendTextMessage("ping"); }
Test the connection. A pong message will be returned, this message will not be broadcast to the channel. This call is asynchronous, any error or success with be sent as a separate message to the listener.
public static boolean hasExtension(String extension){ if (extension == null || extension.isEmpty()) { return false; } return extensionToMimeTypeMap.containsKey(extension); }
Returns true if the given extension has a registered MIME type.
private void updateProgress(String progressLabel,int progress){ if (myHost != null && ((progress != previousProgress) || (!progressLabel.equals(previousProgressLabel)))) { myHost.updateProgress(progressLabel,progress); } else { System.out.println(progressLabel + " " + progress+ "%"); } previousProgress=progress; previousProgressLabel=progressLabel; }
Used to communicate a progress update between a plugin tool and the main Whitebox user interface.
public static INaviView create(final INaviModule container,final List<ReilInstruction> instructions){ Preconditions.checkNotNull(container,"IE01775: Container argument can not be null"); Preconditions.checkNotNull(instructions,"IE01779: Instructions argument can not be null"); final Collection<List<ReilInstruction>> instructionList=new ArrayList<List<ReilInstruction>>(); instructionList.add(instructions); return create(container,ReilGraphGenerator.createGraph(instructionList,new ArrayList<IAddress>())); }
Creates a REIL view object from a list of REIL instructions.
private InternalLocator(int port,File logF,File stateF,InternalLogWriter logWriter,InternalLogWriter securityLogWriter,InetAddress bindAddress,String hostnameForClients,java.util.Properties distributedSystemProperties,DistributionConfigImpl cfg,boolean startDistributedSystem){ this.logFile=logF; this.bindAddress=bindAddress; this.hostnameForClients=hostnameForClients; if (stateF == null) { this.stateFile=new File("locator" + port + "view.dat"); } else { this.stateFile=stateF; } File productUseFile=new File("locator" + port + "views.log"); this.productUseLog=new ProductUseLog(productUseFile); this.config=cfg; env=new Properties(); if (bindAddress != null && !bindAddress.isAnyLocalAddress()) { env.setProperty(BIND_ADDRESS,bindAddress.getHostAddress()); } if (distributedSystemProperties != null) { env.putAll(distributedSystemProperties); } env.setProperty(CACHE_XML_FILE,""); if (this.config == null) { this.config=new DistributionConfigImpl(env); this.env.clear(); this.env.putAll(this.config.getProps()); } final boolean hasLogFileButConfigDoesNot=this.logFile != null && this.config.getLogFile().toString().equals(DistributionConfig.DEFAULT_LOG_FILE.toString()); if (logWriter == null && hasLogFileButConfigDoesNot) { this.config.unsafeSetLogFile(this.logFile); } final boolean hasLogFile=this.config.getLogFile() != null && !this.config.getLogFile().equals(new File("")); final boolean hasSecurityLogFile=this.config.getSecurityLogFile() != null && !this.config.getSecurityLogFile().equals(new File("")); LogService.configureLoggers(hasLogFile,hasSecurityLogFile); if (hasLogFile || hasSecurityLogFile) { if (hasLogFile) { LogWriterAppenders.getOrCreateAppender(LogWriterAppenders.Identifier.MAIN,true,false,this.config,!startDistributedSystem); } if (hasSecurityLogFile) { LogWriterAppenders.getOrCreateAppender(LogWriterAppenders.Identifier.SECURITY,true,false,this.config,false); } else { } } if (logWriter == null) { logWriter=LogWriterFactory.createLogWriterLogger(false,false,this.config,!startDistributedSystem); if (logger.isDebugEnabled()) { logger.debug("LogWriter for locator is created."); } } if (securityLogWriter == null) { securityLogWriter=LogWriterFactory.createLogWriterLogger(false,true,this.config,false); ((LogWriterLogger)logWriter).setLogWriterLevel(this.config.getSecurityLogLevel()); securityLogWriter.fine("SecurityLogWriter for locator is created."); } SocketCreatorFactory.setDistributionConfig(this.config); this.locatorListener=WANServiceProvider.createLocatorMembershipListener(); if (locatorListener != null) { this.locatorListener.setConfig(this.getConfig()); } this.handler=new PrimaryHandler(this,locatorListener); ThreadGroup group=LoggingThreadGroup.createThreadGroup("Distribution locators",logger); stats=new LocatorStats(); server=new TcpServer(port,this.bindAddress,null,this.config,this.handler,new DelayedPoolStatHelper(),group,this.toString()); }
Creates a new <code>Locator</code> with the given port, log file, logger, and bind address.
public static <C>List<C> toList(final BOp op,final Class<C> clas){ final List<C> list=new LinkedList<C>(); final Iterator<C> it=visitAll(op,clas); while (it.hasNext()) { list.add(it.next()); } return list; }
Return a list containing references to all nodes of the given type (recursive, including annotations). <p> Note: This may be used to work around concurrent modification errors since the returned list is structurally independent of the original operator tree.
public TDoubleIntHashMap(TDoubleHashingStrategy strategy){ super(strategy); }
Creates a new <code>TDoubleIntHashMap</code> instance with the default capacity and load factor.
public void testAddDiffScalePosNeg(){ String a="1231212478987482988429808779810457634781384756794987"; int aScale=15; String b="747233429293018787918347987234564568"; int bScale=-10; String c="7472334294161400358170962860775454459810457634.781384756794987"; int cScale=15; BigDecimal aNumber=new BigDecimal(new BigInteger(a),aScale); BigDecimal bNumber=new BigDecimal(new BigInteger(b),bScale); BigDecimal result=aNumber.add(bNumber); assertEquals("incorrect value",c,result.toString()); assertEquals("incorrect scale",cScale,result.scale()); }
Add two numbers of different scales; the first is positive
public JSONArray toJSONArray(JSONArray names) throws JSONException { if (names == null || names.length() == 0) { return null; } JSONArray ja=new JSONArray(); for (int i=0; i < names.length(); i+=1) { ja.put(this.opt(names.getString(i))); } return ja; }
Produce a JSONArray containing the values of the members of this JSONObject.
public String toString(){ return "The detected network configuration is: " + getNatType() + "\n"+ "Your mapped public address is: "+ getPublicAddress(); }
Returns a readable representation of the report.
public <T>JsonStringMap<T> createMapDtoFromJson(String json,Class<T> dtoInterface){ final DtoProvider<T> dtoProvider=getDtoProvider(dtoInterface); final Map<String,JsonElement> map=gson.fromJson(json,mapTypeCache.get(JsonElement.class)); final Map<String,T> result=new LinkedHashMap<>(map.size()); for ( Map.Entry<String,JsonElement> e : map.entrySet()) { result.put(e.getKey(),dtoProvider.fromJson(e.getValue())); } return new JsonStringMapImpl<>(result); }
Parses the JSON data from the specified sting into map of objects of the specified type.
public static String remove(String seq,char... toRemove){ StringBuilder sb=new StringBuilder(); for (int i=0; i < seq.length(); i++) { final char ch=seq.charAt(i); boolean append=true; for (int j=0; j < toRemove.length; j++) { final char c=toRemove[j]; if (ch == c) { append=false; break; } } if (append) { sb.append(ch); } } return sb.toString(); }
Removes several character from a String.
public static synchronized void install(){ }
Installs the JSSE provider.
public Boolean isMemoryReservationLockedToMax(){ return memoryReservationLockedToMax; }
Gets the value of the memoryReservationLockedToMax property.
public void collect(Thread thread){ final StackTraceElement[] stackTrace=thread.getStackTrace(); collectByKey(GLOBAL,stackTrace); }
Override this method to collect based other criteria <p/> If the application knows that a certain type of task happens in a certain thread, it is possible to group the information by that type of task. <p/> Example collect the information grouped by request path, api call, or actor. <p/>It's advisable to either override this method or to call collectByKey directly <p/>Collecting per thread usually produces too much information. Some idle threads are also irrelevant for instance idle worker threads and skew the data.
public Object runSafely(Catbert.FastStack stack) throws Exception { if (stack.getUIMgr() != null && stack.getUIMgr().hasRemoteFSSupport()) { return Boolean.valueOf((((MiniClientSageRenderer)stack.getUIMgr().getRootPanel().getRenderEngine()).fsGetPathAttributes(getString(stack)) & MiniClientSageRenderer.FS_PATH_HIDDEN) != 0); } else return Boolean.valueOf(getFile(stack).isHidden()); }
Returns true if the specified local file path is marked as a hidden file
public void removeSignalMastLogic(SignalMastLogic sml){ if (sml == null) { return; } sml.dispose(); signalMastLogic.remove(sml); firePropertyChange("length",null,Integer.valueOf(signalMastLogic.size())); }
Completely remove the signalmast logic.
private Border createNonRolloverToggleBorder(){ return new EmptyBorder(0,0,0,0); }
Creates a non rollover border for Toggle buttons in the toolbar.
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:56:57.595 -0500",hash_original_method="8B17794307AD8B81CB01594F41A7E2A7",hash_generated_method="81847FD0050ED5980F3274ED23B91811") public static Reader newReader(ReadableByteChannel channel,CharsetDecoder decoder,int minBufferCapacity){ return new InputStreamReader(new ChannelInputStream(channel),decoder); }
Returns a reader that decodes bytes from a channel.
protected ActiveInfoStorageCalculatorViaMutualInfo(MutualInfoCalculatorMultiVariate miCalc){ construct(miCalc); }
Construct using the given (constructed but not initialised) MI calculator.
public void printDate(WriteStreamOld os) throws IOException { os.print(DAY_NAMES[(int)(_dayOfEpoch % 7 + 11) % 7]); os.write(','); os.write(' '); os.print((_dayOfMonth + 1) / 10); os.print((_dayOfMonth + 1) % 10); os.write(' '); os.print(MONTH_NAMES[(int)_month]); os.write(' '); os.print(_year); os.write(' '); os.print((_timeOfDay / 36000000) % 10); os.print((_timeOfDay / 3600000) % 10); os.write(':'); os.print((_timeOfDay / 600000) % 6); os.print((_timeOfDay / 60000) % 10); os.write(':'); os.print((_timeOfDay / 10000) % 6); os.print((_timeOfDay / 1000) % 10); if (_zoneName == null) { os.print(" GMT"); return; } long offset=_zoneOffset; if (offset < 0) { os.write(' '); os.write('-'); offset=-offset; } else { os.write(' '); os.write('+'); } os.print((offset / 36000000) % 10); os.print((offset / 3600000) % 10); os.print((offset / 600000) % 6); os.print((offset / 60000) % 10); os.write(' '); os.write('('); os.print(_zoneName); os.write(')'); }
Prints the date to a stream.
public static _PendingSetType fromString(final String value) throws SOAPSerializationException { return (_PendingSetType)Enumeration.fromString(value,_PendingSetType.VALUES_TO_INSTANCES); }
Gets the specific enumeration value in this class appropriate for the given XML attribute value. If no value is known, null is returned (_DEFAULT is not used; that value is for when the attribute is not present).
public void tryCommit(final Graph graph){ if (graph.features().graph().supportsTransactions()) graph.tx().commit(); }
Utility method that commits if the graph supports transactions.
public TypesAdapterFactory(){ if (modelPackage == null) { modelPackage=TypesPackage.eINSTANCE; } }
Creates an instance of the adapter factory. <!-- begin-user-doc --> <!-- end-user-doc -->
public boolean isCellEditable(int row,int col){ return !(col < getBayesIm().getNumParents(getNodeIndex())); }
Determines whether a cell is in the column range to allow for editing.
public Iterator<E> descendingIterator(){ return m.descendingKeySet().iterator(); }
Returns an iterator over the elements in this set in descending order.
@Override public Enumeration<String> enumerateMeasures(){ Vector<String> newVector=new Vector<String>(); if (m_ResultProducer instanceof AdditionalMeasureProducer) { Enumeration<String> en=((AdditionalMeasureProducer)m_ResultProducer).enumerateMeasures(); while (en.hasMoreElements()) { String mname=en.nextElement(); newVector.add(mname); } } return newVector.elements(); }
Returns an enumeration of any additional measure names that might be in the result producer
public void print(CtMethod method){ MethodInfo info=method.getMethodInfo2(); ConstPool pool=info.getConstPool(); CodeAttribute code=info.getCodeAttribute(); if (code == null) return; CodeIterator iterator=code.iterator(); while (iterator.hasNext()) { int pos; try { pos=iterator.next(); } catch ( BadBytecode e) { throw new RuntimeException(e); } stream.println(pos + ": " + instructionString(iterator,pos,pool)); } }
Prints the bytecode instructions of a given method.
private void updateProgress(String progressLabel,int progress){ if (myHost != null && ((progress != previousProgress) || (!progressLabel.equals(previousProgressLabel)))) { myHost.updateProgress(progressLabel,progress); } previousProgress=progress; previousProgressLabel=progressLabel; }
Used to communicate a progress update between a plugin tool and the main Whitebox user interface.
public static String constructOperationsMessage(ArrayList<Attribute> contents){ StringBuilder result=new StringBuilder(OPERATIONS); for ( Attribute content : contents) { result.append(REQUEST_DELIMITER).append(content.getName()); if (content.getValue() != null) { result.append(FIELDSEPARATOR).append(content.getValue()); } } return new String(result); }
constructs a request in a format that parseOperationsMessage can handle. An OperationsMessage has the format: <ul> <li> OPERATIONS </li> <li> " , " (delimiter) </li> <li> request/reponse </li> <li> any number of " , " , followed by additional request/response pairs </li> </ul> The meaning of request/response is context sensitive. If the SimpleOperationsServer client is sending the message, then it is a request. If the SimpleOperationsServer is sending the message, then it is a response.
public void testMixedInstances(){ runTestOnData(generateData(5,5,5)); }
tests constructing a vector from a mixed instance
private void applyFormattingHtmlMode(ToggleButton toggleButton,String tag){ if (mSourceViewContent == null) { return; } String htmlTag; if (tag.equals(getString(R.string.format_bar_tag_bold))) { htmlTag="b"; } else if (tag.equals(getString(R.string.format_bar_tag_italic))) { htmlTag="i"; } else if (tag.equals(getString(R.string.format_bar_tag_strikethrough))) { htmlTag="del"; } else if (tag.equals(getString(R.string.format_bar_tag_unorderedList))) { htmlTag="ul"; } else if (tag.equals(getString(R.string.format_bar_tag_orderedList))) { htmlTag="ol"; } else { htmlTag=tag; } int selectionStart=mSourceViewContent.getSelectionStart(); int selectionEnd=mSourceViewContent.getSelectionEnd(); if (selectionStart > selectionEnd) { int temp=selectionEnd; selectionEnd=selectionStart; selectionStart=temp; } boolean textIsSelected=selectionEnd > selectionStart; String startTag="<" + htmlTag + ">"; String endTag="</" + htmlTag + ">"; if (htmlTag.equals("ul") || htmlTag.equals("ol")) { startTag=startTag + "\n\t<li>"; endTag="</li>\n" + endTag; } Editable content=mSourceViewContent.getText(); if (textIsSelected) { content.insert(selectionStart,startTag); content.insert(selectionEnd + startTag.length(),endTag); toggleButton.setChecked(false); mSourceViewContent.setSelection(selectionEnd + startTag.length() + endTag.length()); } else if (toggleButton.isChecked()) { content.insert(selectionStart,startTag); mSourceViewContent.setSelection(selectionEnd + startTag.length()); } else { content.insert(selectionEnd,endTag); mSourceViewContent.setSelection(selectionEnd + endTag.length()); } }
In HTML mode, applies formatting to selected text, or inserts formatting tag at current cursor position
public static void addIsPreviousVersionOfDOIRelatedIdentifier(@NotNull DataCiteMetadata metadata,@NotNull DOI replacing){ DataCiteMetadata.RelatedIdentifiers.RelatedIdentifier rid=FACTORY.createDataCiteMetadataRelatedIdentifiersRelatedIdentifier(); rid.setRelatedIdentifierType(RelatedIdentifierType.DOI); rid.setValue(replacing.getDoiName()); rid.setRelationType(RelationType.IS_PREVIOUS_VERSION_OF); metadata.getRelatedIdentifiers().getRelatedIdentifier().add(rid); }
Add RelatedIdentifier describing the DOI of the resource replacing the resource being registered.
@Override protected void onStartLoading(){ if (mApps != null) { deliverResult(mApps); } if (mPackageObserver == null) { mPackageObserver=new PackageIntentReceiver(this); } boolean configChange=mLastConfig.applyNewConfig(getContext().getResources()); if (takeContentChanged() || mApps == null || configChange) { forceLoad(); } }
Handles a request to start the Loader.
@RequestMapping(value="/businessObjectFormats/generateDdlCollection",method=RequestMethod.POST,consumes={"application/xml","application/json"}) @Secured(SecurityFunctions.FN_BUSINESS_OBJECT_FORMATS_GENERATE_DDL_COLLECTION_POST) public BusinessObjectFormatDdlCollectionResponse generateBusinessObjectFormatDdlCollection(@RequestBody BusinessObjectFormatDdlCollectionRequest businessObjectFormatDdlCollectionRequest){ return businessObjectFormatService.generateBusinessObjectFormatDdlCollection(businessObjectFormatDdlCollectionRequest); }
Retrieves the DDL to initialize the specified type of the database system (e.g. Hive) by creating tables for a collection of business object formats. <p>Requires READ permission on ALL namespaces</p>
private void skipToEndOfLine(){ while (position < limit) { char c=in.charAt(position++); if (c == '\n' || c == '\r') { break; } } }
Advances the position until after the next newline character. If the line is terminated by "\r\n", the '\n' must be consumed as whitespace by the caller.
public void testCreateGenericMessageFromNoBodySectionAndUnknownContentType() throws Exception { JMSMappingInboundTransformer transformer=new JMSMappingInboundTransformer(idGenerator); Message message=Message.Factory.create(); message.setContentType("unknown-content-type"); EncodedMessage em=encodeMessage(message); javax.jms.Message jmsMessage=transformer.transform(em); assertNotNull("Message should not be null",jmsMessage); assertEquals("Unexpected message class type",ActiveMQMessage.class,jmsMessage.getClass()); }
Test that a message with no body section, and with the content type set to an unknown value results in a plain Message when not otherwise annotated to indicate the type of JMS message it is.
private boolean isQoSSettingsUpdate(final HttpServerRequest request){ return request.uri().equals(qosSettingsUri) && (HttpMethod.PUT == request.method() || HttpMethod.DELETE == request.method()); }
Indicates if the request is an update of the QoS Settings.
public void install(JTextComponent c){ if (!(c instanceof RTextArea)) throw new IllegalArgumentException("c must be instance of RTextArea"); super.install(c); }
Installs this caret on a text component.
public final Vec3D interpolateToSelf(ReadonlyVec3D v,float f){ x+=(v.x() - x) * f; y+=(v.y() - y) * f; z+=(v.z() - z) * f; return this; }
Interpolates the vector towards the given target vector, using linear interpolation.
public List<ValidationErrorMessage> validateValue(String value){ errorMessageIds.clear(); if (dataRestrictions.isRequired() && valueNullOrEmpty(value)) { errorMessageIds.add(new ValidationErrorMessage("required",id,null)); } else { if (!valueNullOrEmpty(value)) { for ( AbstractValidationRule rule : dataRestrictions.getValidationRules()) { if (!rule.validate(value)) { errorMessageIds.add(new ValidationErrorMessage(rule.getMessageId(),id,rule)); } } } } return errorMessageIds; }
Gets all errormessagecodes for this field's value. This list is filled after doing isValid() on this field
public String toString(){ return "PropertyBuilder ( " + " textualLineCount = " + this.textualLineCount + " properties = "+ this.properties+ " )"; }
Constructs a <code>String</code> with all attributes in name = value format.
public static boolean isFileNewer(File file,long timeMillis){ if (file == null) { throw new IllegalArgumentException("No specified file"); } if (!file.exists()) { return false; } return file.lastModified() > timeMillis; }
Tests if the specified <code>File</code> is newer than the specified time reference.
boolean bind(Environment env,Context ctx){ try { field=ctx.getField(env,id); if (field == null) { for (ClassDefinition cdef=ctx.field.getClassDefinition(); cdef != null; cdef=cdef.getOuterClass()) { if (cdef.findAnyMethod(env,id) != null) { env.error(where,"invalid.var",id,ctx.field.getClassDeclaration()); return false; } } env.error(where,"undef.var",id); return false; } type=field.getType(); if (!ctx.field.getClassDefinition().canAccess(env,field)) { env.error(where,"no.field.access",id,field.getClassDeclaration(),ctx.field.getClassDeclaration()); return false; } if (field.isLocal()) { LocalMember local=(LocalMember)field; if (local.scopeNumber < ctx.frameNumber) { implementation=ctx.makeReference(env,local); } } else { MemberDefinition f=field; if (f.reportDeprecated(env)) { env.error(where,"warn.field.is.deprecated",id,f.getClassDefinition()); } ClassDefinition fclass=f.getClassDefinition(); if (fclass != ctx.field.getClassDefinition()) { MemberDefinition f2=ctx.getApparentField(env,id); if (f2 != null && f2 != f) { ClassDefinition c=ctx.findScope(env,fclass); if (c == null) c=f.getClassDefinition(); if (f2.isLocal()) { env.error(where,"inherited.hides.local",id,c.getClassDeclaration()); } else { env.error(where,"inherited.hides.field",id,c.getClassDeclaration(),f2.getClassDeclaration()); } } } if (f.isStatic()) { Expression base=new TypeExpression(where,f.getClassDeclaration().getType()); implementation=new FieldExpression(where,null,f); } else { Expression base=ctx.findOuterLink(env,where,f); if (base != null) { implementation=new FieldExpression(where,base,f); } } } if (!ctx.canReach(env,field)) { env.error(where,"forward.ref",id,field.getClassDeclaration()); return false; } return true; } catch ( ClassNotFound e) { env.error(where,"class.not.found",e.name,ctx.field); } catch ( AmbiguousMember e) { env.error(where,"ambig.field",id,e.field1.getClassDeclaration(),e.field2.getClassDeclaration()); } return false; }
Bind to a field
public static <K,V>HashMap<K,V> hashMap(){ return new HashMap<K,V>(); }
Create a new HashMap.
public void store(String key,PreparedStatement ps,String query){ PreparedStatementHolder psh=new PreparedStatementHolder(key,ps,query); cache.put(key,psh); }
Store prepared statement.
public double max(){ return max; }
Returns the max endpoint of this interval.
public float lat(int y){ return originLat - y / dotsPerDeg; }
Computes the corresponding latitude for a given view y coordinate.
public NoSuchElementException(String s){ super(s); }
Constructs a <code>NoSuchElementException</code>, saving a reference to the error message string <tt>s</tt> for later retrieval by the <tt>getMessage</tt> method.
public void reportGpsGeofenceRemoveStatus(int geofenceId,int status){ if (DEBUG) Log.d(TAG,"Remove Callback: GPS : Id: " + geofenceId + " Status: "+ status); acquireWakeLock(); Message m=mGeofenceHandler.obtainMessage(REMOVE_GEOFENCE_CALLBACK); m.arg1=geofenceId; m.arg2=getGeofenceStatus(status); mGeofenceHandler.sendMessage(m); }
called from GpsLocationProvider remove geofence callback.
public void removePackage(String packageName,UserHandleCompat user){ final List<AppInfo> data=this.data; for (int i=data.size() - 1; i >= 0; i--) { AppInfo info=data.get(i); final ComponentName component=info.intent.getComponent(); if (info.user.equals(user) && packageName.equals(component.getPackageName())) { removed.add(info); data.remove(i); } } }
Remove the apps for the given apk identified by packageName.
public static String slurpGBURLNoExceptions(URL u){ try { return slurpGBURL(u); } catch ( Exception e) { e.printStackTrace(); return null; } }
Returns all the text at the given URL.
public static long binaryToLong(final boolean[] src,final int srcPos,final long dstInit,final int dstPos,final int nBools){ if ((src.length == 0 && srcPos == 0) || 0 == nBools) { return dstInit; } if (nBools - 1 + dstPos >= 64) { throw new IllegalArgumentException("nBools-1+dstPos is greather or equal to than 64"); } long out=dstInit; int shift=0; for (int i=0; i < nBools; i++) { shift=i + dstPos; final long bits=(src[i + srcPos] ? 1L : 0) << shift; final long mask=0x1L << shift; out=(out & ~mask) | bits; } return out; }
<p> Converts binary (represented as boolean array) into a long using the default (little endian, Lsb0) byte and bit ordering. </p>
@SuppressWarnings("unchecked") private static void addSetter(ClassNode classNode,String fieldName,String fieldNameForMethods,String fieldJavaType){ String setterSignature='(' + fieldJavaType + ')'+ 'V'; MethodNode setterNode=new MethodNode(Opcodes.ACC_PUBLIC,"set" + fieldNameForMethods,setterSignature,null,null); setterNode.instructions.add(new VarInsnNode(Opcodes.ALOAD,0)); int loadOpCode; if (fieldJavaType.equals(Character.toString(typeIdentifierBoolean)) || fieldJavaType.equals(Character.toString(typeIdentifierByte)) || fieldJavaType.equals(Character.toString(typeIdentifierChar))|| fieldJavaType.equals(Character.toString(typeIdentifierShort))|| fieldJavaType.equals(Character.toString(typeIdentifierInt))) { loadOpCode=Opcodes.ILOAD; } else if (fieldJavaType.equals(Character.toString(typeIdentifierLong))) { loadOpCode=Opcodes.LLOAD; } else if (fieldJavaType.equals(Character.toString(typeIdentifierFloat))) { loadOpCode=Opcodes.FLOAD; } else if (fieldJavaType.equals(Character.toString(typeIdentifierDouble))) { loadOpCode=Opcodes.DLOAD; } else { loadOpCode=Opcodes.ALOAD; } setterNode.instructions.add(new VarInsnNode(loadOpCode,1)); setterNode.instructions.add(new FieldInsnNode(Opcodes.PUTFIELD,classNode.name,fieldName,fieldJavaType)); setterNode.instructions.add(new InsnNode(Opcodes.RETURN)); classNode.methods.add(setterNode); }
Add public setter for given field
private static int findCodewordIndex(long symbol){ int first=0; int upto=SYMBOL_TABLE.length; while (first < upto) { int mid=(first + upto) >>> 1; if (symbol < SYMBOL_TABLE[mid]) { upto=mid; } else if (symbol > SYMBOL_TABLE[mid]) { first=mid + 1; } else { return mid; } } return -1; }
Use a binary search to find the index of the codeword corresponding to this symbol.
protected StateVectorImpl(){ super(); }
<!-- begin-user-doc --> <!-- end-user-doc -->
private static float[][] computeCoVariance(float[] points){ float[][] array=new float[2][2]; array[0][0]=0; array[0][1]=0; array[1][0]=0; array[1][1]=0; int count=points.length; for (int i=0; i < count; i++) { float x=points[i]; i++; float y=points[i]; array[0][0]+=x * x; array[0][1]+=x * y; array[1][0]=array[0][1]; array[1][1]+=y * y; } array[0][0]/=(count / 2); array[0][1]/=(count / 2); array[1][0]/=(count / 2); array[1][1]/=(count / 2); return array; }
Calculates the variance-covariance matrix of a set of points.
private void stackMoveHelper(GPR dest,Offset off){ stackMoveHelper(asm,dest,off); }
Move a value from the stack into a register using the shortest encoding and the appropriate width for 32/64
public void read(IXMLElement root) throws IOException { String name=root.getName(); String ns=root.getNamespace(); if (name.equals("document-content") && (ns == null || ns.equals(OFFICE_NAMESPACE))) { readDocumentContentElement(root); } else if (name.equals("document-styles") && (ns == null || ns.equals(OFFICE_NAMESPACE))) { readDocumentStylesElement(root); } else { if (DEBUG) { System.out.println("ODGStylesReader unsupported root element " + root); } } }
Reads a &lt;document-styles&gt; element from the specified XML element.
public List<String> findRepeatedDnaSequences(String s){ if (s == null || s.length() < 10) return Collections.EMPTY_LIST; List<String> res=new ArrayList<>(); Map<Integer,Boolean> map=new HashMap<>(); for (int t=0, i=0; i < s.length(); i++) { t=(t << 3 & 0x3FFFFFFF) | (s.charAt(i) & 7); if (map.containsKey(t)) { if (map.get(t)) { res.add(s.substring(i - 9,i + 1)); map.put(t,false); } } else { map.put(t,true); } } return res; }
To optimize space usage, map string to other key that won't collide Design a hash function according to observation A: 0x41, C: 0x43, G: 0x47, T: 0x54, last 3 bits are different 10 chars, each 3 bits, 10 x 3 = 30 bits < 32 Key: an int to record the bit mask of current substring, Value: a boolean, true means showed up before, false means already added Update the map
public FullTextQueryBuilder(IndexName indexName,FullTextIndexService service){ this.indexName=indexName; this.infos=service; this.buildContext=null; }
Construct directly for non-SQL and testing.
public void queryForCustomDayEvents(DateTime dateTime,String filename){ System.out.println("\n\n -> Querying Events"); ExecutorService executor=Executors.newFixedThreadPool(100); EventQueryResult result=new EventQueryResult(filename); try { _dbClient.queryTimeSeries(EventTimeSeries.class,dateTime,TimeSeriesMetadata.TimeBucket.HOUR,result,executor); System.out.println(" --- Job Exceution for Querying Events completed ---"); return; } catch ( DatabaseException e) { System.err.println("Exception Query " + e); log.error("Exception Query ",e); } }
Query events
protected void pushLeft(BinarySearchTreeNode<E> node){ while (node != null) { if (this.to == null || this.to.compareTo(node.comparable) >= 0) { this.stack.push(node); } node=node.left; } }
Pushes the left most nodes of the given subtree onto the stack.
public static boolean isObject(TypeElement element){ return element.getQualifiedName().contentEquals("java.lang.Object"); }
Check if the element is an element for 'java.lang.Object'
public String press(){ append("Button pressed for account " + accountId.getValue()); clear(); return (null); }
<p>Acknowledge that a row-specific button was pressed.</p>
public java.lang.StringBuilder append(int i){ return null; }
Appends the string representation of the int argument to this string buffer. The argument is converted to a string as if by the method String.valueOf, and the characters of that string are then appended to this string buffer.
public static boolean callsSensitiveSource(Stmt stmt){ for ( InfoKind infoK : getSourceInfoKinds(stmt)) { if (infoK.isSensitive()) return true; } return false; }
Return true if any of the infokinds for this infovalue call statement are defined as sensitive.
public Configuration configure(Document document) throws EPException { if (log.isDebugEnabled()) { log.debug("configuring from XML document"); } ConfigurationParser.doConfigure(this,document); return this; }
Use the mappings and properties specified in the given XML document. The format of the file is defined in <tt>esper-configuration-2.0.xsd</tt>.
public void load_args(){ load_args(0,state.argumentTypes.length); }
Pushes all of the arguments of the current method onto the stack.
public void putJSON(final String key,String value){ value=JSONObject.quote(value); value=value.substring(1,value.length() - 1); put(key,value); }
Add a String to the map. The content of the String is escaped to be usable in JSON output.
@Override public void addLayoutComponent(String name,Component comp){ }
Adds the specified component with the specified name to the layout.
public static Map<String,Object> fetchJSON(String url) throws IOException { ConnectionRequest cr=new ConnectionRequest(); cr.setFailSilently(true); cr.setPost(false); cr.setUrl(url); NetworkManager.getInstance().addToQueueAndWait(cr); if (cr.getResponseData() == null) { if (cr.failureException != null) { throw new IOException(cr.failureException.toString()); } else { throw new IOException("Server returned error code: " + cr.failureErrorCode); } } JSONParser jp=new JSONParser(); Map<String,Object> result=jp.parseJSON(new InputStreamReader(new ByteArrayInputStream(cr.getResponseData()),"UTF-8")); return result; }
Utility method that returns a JSON structure or throws an IOException in case of a failure. This method blocks the EDT legally and can be used synchronously. Notice that this method assumes all JSON data is UTF-8
Rules(Workspace workspace){ this.root=workspace.getRoot(); this.teamHook=workspace.getTeamHook(); }
Creates a new scheduling rule factory for the given workspace
public LookupResult(SourceUnit su,ClassNode cn){ this.su=su; this.cn=cn; if (su == null && cn == null) throw new IllegalArgumentException("Either the SourceUnit or the ClassNode must not be null."); if (su != null && cn != null) throw new IllegalArgumentException("SourceUnit and ClassNode cannot be set at the same time."); }
creates a new LookupResult. You are not supposed to supply a SourceUnit and a ClassNode at the same time
public int depth(){ return pointer; }
Get the depth of the stack.
public static Date round(Date date,Resolution resolution){ return new Date(round(date.getTime(),resolution)); }
Limit a date's resolution. For example, the date <code>2004-09-21 13:50:11</code> will be changed to <code>2004-09-01 00:00:00</code> when using <code>Resolution.MONTH</code>.
public ArrayOfDoublesAnotB buildAnotB(){ return new HeapArrayOfDoublesAnotB(numValues_,seed_); }
Creates an instance of ArrayOfDoublesAnotB based on the current configuration of the builder. The memory is not relevant to this, so it is ignored if set. The number of nominal entries is not relevant to this, so it is ignored.
public void createIndicators(CandleDataset source){ for ( IndicatorDataset indicator : indicators) { if (!IndicatorSeries.CandleSeries.equals(indicator.getType(0))) { for (int x=0; x < indicator.getSeriesCount(); x++) { IndicatorSeries series=indicator.getSeries(x); series.createSeries(source,0); } } } }
Method updateIndicators. Update all the indicators before notifying any strategy workers of this even.
public String localName(){ return theType.localName(); }
Return the local name of the element's type. Convenience method.
public synchronized int available(){ return count - pos; }
Returns the number of remaining bytes that can be read (or skipped over) from this input stream. <p> The value returned is <code>count&nbsp;- pos</code>, which is the number of bytes remaining to be read from the input buffer.
public double measureOutOfBagError(){ return m_OutOfBagError; }
Gets the out of bag error that was calculated as the classifier was built.
public VcfSortRefiner(VcfReader in) throws IOException { mIn=in; setNext(); }
Wraps around an existing VCF reader.
public final void testDisjunctiveWithContextAndResourceIdParameters(){ assertNotNull(Validators.disjunctive(getContext(),android.R.string.cancel,Validators.notEmpty("foo"),Validators.minLength("foo",1))); }
Tests the functionality of the disjunctive-method, which expects a context and a resource id as parameters.
public SnapshotInfo(String path,String prefix,String jvmInfo,int identifierSize,Date creationDate,int numberOfObjects,int numberOfGCRoots,int numberOfClasses,int numberOfClassLoaders,long usedHeapSize){ this.path=path; this.prefix=prefix; this.jvmInfo=jvmInfo; this.identifierSize=identifierSize; this.creationDate=creationDate != null ? new Date(creationDate.getTime()) : null; this.numberOfObjects=numberOfObjects; this.numberOfGCRoots=numberOfGCRoots; this.numberOfClasses=numberOfClasses; this.numberOfClassLoaders=numberOfClassLoaders; this.usedHeapSize=usedHeapSize; this.properties=new HashMap<String,Serializable>(); }
Construct a snapshot info.
private String choosePrefix(String ns,String prefix,boolean isAttribute){ if (prefix != null && ns.equals(nsb.getNamespaceUri(prefix))) return prefix; if (isAttribute) { if (ns.length() == 0) return null; } else { if (ns.equals(nsb.getNamespaceUri(""))) return null; } return nsb.getNonEmptyPrefix(ns); }
null means no prefix
@Override public boolean equals(Object o){ if (!(o instanceof Version)) return false; Version v=(Version)o; if (v == this) return true; if (numbers.length != v.numbers.length) return false; for (int i=0; i < numbers.length; i++) { if (numbers[i] != v.numbers[i]) return false; } return true; }
Compares two versions. Returns true if this instance is equal to o.
public FireworkEffectBuilder withFade(Iterable<Color> colors) throws IllegalArgumentException { Validate.notNull(colors,"Colors can't be null"); for ( Color color : colors) { this.fadeColors.add(color); } return this; }
Add fade colors to the firework effect.
protected void debugCodeCall(String methodName,String param){ if (trace.isDebugEnabled()) { trace.debugCode(getTraceObjectName() + "." + methodName+ "("+ quote(param)+ ");"); } }
Write trace information as a method call in the form objectName.methodName(param) where the parameter is formatted as a Java string.
public static void filterOutInitiatorsNotAssociatedWithVArray(URI virtualArrayURI,List<URI> newInitiators,DbClient dbClient){ Iterator<URI> it=newInitiators.iterator(); while (it.hasNext()) { URI uri=it.next(); Initiator initiator=dbClient.queryObject(Initiator.class,uri); if (initiator == null) { _log.info(String.format("Initiator %s was not found in DB. Will be eliminated from request payload.",uri.toString())); it.remove(); continue; } if (!isInitiatorInVArraysNetworks(virtualArrayURI,initiator,dbClient)) { _log.info(String.format("Initiator %s (%s) will be eliminated from the payload " + "because it was not associated with Virtual Array %s",initiator.getInitiatorPort(),initiator.getId().toString(),virtualArrayURI.toString())); it.remove(); } } }
Routine will examine the 'newInitiators' list and remove any that do not have any association to the VirtualArray.
private static String summarizeCompletedJob(Job job){ JobStatistics stats=job.getStatistics(); return String.format("Job took %,.3f seconds after a %,.3f second delay and processed %,d bytes (%s)",(stats.getEndTime() - stats.getStartTime()) / 1000.0,(stats.getStartTime() - stats.getCreationTime()) / 1000.0,stats.getTotalBytesProcessed(),toJobReferenceString(job.getJobReference())); }
Returns a summarization of a completed job's statistics for logging.
public DoubleFactor(DoubleFactor existingFactor){ matrix=new HashMap<Assignment,double[]>(existingFactor.matrix); }
Creates a new factor out of an existing one
public static final synchronized Cache basicGetCache(){ return cache; }
Return current cache without creating one.
private void updateVolumeInfoAfterCommitDeviceMigration(String originalVolumeName,VPlexMigrationInfo migrationInfo,List<VPlexClusterInfo> clusterInfoList,boolean rename){ VPlexVirtualVolumeInfo virtualVolumeInfo=findVirtualVolumeAfterDeviceMigration(originalVolumeName,migrationInfo,clusterInfoList); if (virtualVolumeInfo == null) { s_logger.warn("Could not find virtual volume {} after device migration",originalVolumeName); return; } if ((rename) && (volumeHasDefaultNamingConvention(originalVolumeName,false))) { String migrationTgtName=migrationInfo.getTarget(); if ((originalVolumeName.equals(virtualVolumeInfo.getName())) || (migrationTgtName.equals(virtualVolumeInfo.getName()))) { String volumeNameAfterMigration=virtualVolumeInfo.getName(); String volumePathAfterMigration=virtualVolumeInfo.getPath(); StringBuilder volumeNameBuilder=new StringBuilder(); volumeNameBuilder.append(migrationTgtName); if (!volumeNameBuilder.toString().endsWith(VPlexApiConstants.VIRTUAL_VOLUME_SUFFIX)) { volumeNameBuilder.append(VPlexApiConstants.VIRTUAL_VOLUME_SUFFIX); } virtualVolumeInfo=_vplexApiClient.renameResource(virtualVolumeInfo,volumeNameBuilder.toString()); s_logger.info(String.format("Renamed virtual volume after migration from name: %s path: %s to %s",volumeNameAfterMigration,volumePathAfterMigration,volumeNameBuilder.toString())); } migrationInfo.setVirtualVolumeInfo(virtualVolumeInfo); } else if (!originalVolumeName.equals(virtualVolumeInfo.getName())) { String newName=virtualVolumeInfo.getName(); virtualVolumeInfo=_vplexApiClient.renameResource(virtualVolumeInfo,originalVolumeName); s_logger.info("Renamed virtual volume {} back to its orginal name {}",newName,originalVolumeName); migrationInfo.setVirtualVolumeInfo(virtualVolumeInfo); } }
Updates the virtual volume information after a device migration is successfully committed. Note that the volume will be a local virtual volume as device migration is not supported for distributed volumes.