code
stringlengths
10
174k
nl
stringlengths
3
129k
public void writeExpression(Expression oldExp){ Object oldValue=getValue(oldExp); if (get(oldValue) != null) { return; } bindings.put(oldValue,(Expression)cloneStatement(oldExp)); writeObject(oldValue); }
The implementation first checks to see if an expression with this value has already been written. If not, the expression is cloned, using the same procedure as <code>writeStatement</code>, and the value of this expression is reconciled with the value of the cloned expression by calling <code>writeObject</code>.
void verifyRecipient(Node nodeAssertion,Node nodeConfirmationData) throws AssertionValidationException { String acsFromRequest=XMLConverter.getStringAttValue(nodeConfirmationData,SamlXmlTags.ATTRIBUTE_RECIPIENT); if (!doesAcsMatch(acsFromRequest)) { String assertionId=XMLConverter.getStringAttValue(nodeAssertion,SamlXmlTags.ATTRIBUTE_ID); AssertionValidationException exception=new AssertionValidationException(String.format("Found incorrect recipient for assertion id=%s, expected is %s or %s, but was %s",assertionId,acsUrl,acsUrlHttps,acsFromRequest),AssertionValidationException.ReasonEnum.INVALID_RECIPIENT,new String[]{assertionId}); throw exception; } }
Verify that the Recipient attribute in any bearer <SubjectConfirmationData> matches the assertion consumer service URL to which the <Response> or artifact was delivered.
public short loadShort(){ return (short)0; }
Loads a short from the memory location pointed to by the current instance.
private boolean hasSignerAtNewLocation(){ boolean hasSigner=false; if (tenantName != null) { ILdapMessage message=null; try { String searchFilter=String.format("(objectclass=%s)",TRUSTED_CRED_OBJECT_CLASS); message=lookupObject(getTenantsDn(tenantName),LdapScope.SCOPE_ONE_LEVEL,searchFilter); if (message != null) { ILdapEntry[] entries=message.getEntries(); if (entries != null && entries.length > 0) { hasSigner=true; } } } finally { closeMessage(message); } } return hasSigner; }
This method will check if the system Tenant already has any signer under CN =<SystemTenant>,CN=Tenants,CN=IdentityManager,CN=Services,dc=vsphere,dc= local.
public void testIntegration2(){ boolean res; int originalAppIdValue=mAppIdValue; int originalContentTypeValue=mContentTypeValue; String originalAppIdName=mAppIdName; String originalContentTypeName=mContentTypeName; String originalClassName=mClassName; byte[] originalMessageBody=mMessageBody; Random rd=new Random(); IWapPushManager iwapman=getInterface(); IDataVerify dataverify=getVerifyInterface(); mClassName="com.android.smspush.unitTests.ReceiverActivity"; for (int i=0; i < OMA_CONTENT_TYPE_NAMES.length; i++) { mContentTypeName=OMA_CONTENT_TYPE_NAMES[i]; mAppIdValue=rd.nextInt(0x0FFFFFFF); mMessageBody=new byte[100 + rd.nextInt(100)]; rd.nextBytes(mMessageBody); byte[] pdu=createPDU(7); byte[] wappushPdu=retrieveWspBody(); try { dataverify.resetData(); iwapman.addPackage(Integer.toString(mAppIdValue),mContentTypeName,mPackageName,mClassName,WapPushManagerParams.APP_TYPE_ACTIVITY,false,false); dispatchWapPdu(wappushPdu,iwapman); iwapman.deletePackage(Integer.toString(mAppIdValue),mContentTypeName,mPackageName,mClassName); if (mContentTypeName.equals(WspTypeDecoder.CONTENT_TYPE_B_PUSH_CO)) { assertTrue(dataverify.verifyData(wappushPdu)); } else { assertTrue(dataverify.verifyData(mMessageBody)); } } catch ( RemoteException e) { } } mClassName=originalClassName; mAppIdName=originalAppIdName; mContentTypeName=originalContentTypeName; mAppIdValue=originalAppIdValue; mContentTypeValue=originalContentTypeValue; mMessageBody=originalMessageBody; }
Integration test 2, random mAppIdValue(int), all OMA content type
private void socksConnect(InetAddress applicationServerAddress,int applicationServerPort,int timeout) throws IOException { try { IoBridge.connect(fd,socksGetServerAddress(),socksGetServerPort(),timeout); } catch ( Exception e) { throw new SocketException("SOCKS connection failed",e); } socksRequestConnection(applicationServerAddress,applicationServerPort); lastConnectedAddress=applicationServerAddress; lastConnectedPort=applicationServerPort; }
Connect using a SOCKS server.
static void testLoadWithMalformedDoc(Path dir) throws IOException { try (DirectoryStream<Path> stream=Files.newDirectoryStream(dir,"*.xml")){ for ( Path file : stream) { System.out.println("testLoadWithMalformedDoc, file=" + file.getFileName()); try (InputStream in=Files.newInputStream(file)){ Properties props=new Properties(); try { props.loadFromXML(in); throw new RuntimeException("InvalidPropertiesFormatException not thrown"); } catch ( InvalidPropertiesFormatException x) { System.out.println(x); } } } } }
Test loadFromXML with malformed documents
private ArrayList<Track> parseTopTracks(String json){ ArrayList<Track> tracks=new ArrayList<>(); try { JsonNode jsonNode=this.objectMapper.readTree(json); for ( JsonNode trackNode : jsonNode.get("tracks")) { JsonNode albumNode=trackNode.get("album"); String albumName=albumNode.get("name").asText(); String artistName=trackNode.get("artists").get(0).get("name").asText(); String trackName=trackNode.get("name").asText(); tracks.add(new Track(trackName,new Album(albumName,new Artist(artistName)))); } } catch ( IOException e) { throw new RuntimeException("Failed to parse JSON",e); } return tracks; }
Parses an artist top tracks response from the <a href="https://developer.spotify.com/web-api/get-artists-top-tracks/">Spotify API</a>
public final static byte[] decode(char[] sArr){ int sLen=sArr != null ? sArr.length : 0; if (sLen == 0) return new byte[0]; int sepCnt=0; for (int i=0; i < sLen; i++) if (IA[sArr[i]] < 0) sepCnt++; if ((sLen - sepCnt) % 4 != 0) return null; int pad=0; for (int i=sLen; i > 1 && IA[sArr[--i]] <= 0; ) if (sArr[i] == '=') pad++; int len=((sLen - sepCnt) * 6 >> 3) - pad; byte[] dArr=new byte[len]; for (int s=0, d=0; d < len; ) { int i=0; for (int j=0; j < 4; j++) { int c=IA[sArr[s++]]; if (c >= 0) i|=c << (18 - j * 6); else j--; } dArr[d++]=(byte)(i >> 16); if (d < len) { dArr[d++]=(byte)(i >> 8); if (d < len) dArr[d++]=(byte)i; } } return dArr; }
Decodes a BASE64 encoded char array. All illegal characters will be ignored and can handle both arrays with and without line separators.
public static boolean checkDisabled(Plugin method){ if (!hasMethod()) { return true; } if (Method.isCompatible(method)) { Method=null; } return (Method == null); }
Verify is a plugin is disabled, only does this if we there is an existing payment method initialized in Register.
private boolean execute(boolean readResponse) throws IOException { try { httpEngine.sendRequest(); if (readResponse) { httpEngine.readResponse(); } return true; } catch ( IOException e) { if (handleFailure(e)) { return false; } else { throw e; } } }
Sends a request and optionally reads a response. Returns true if the request was successfully executed, and false if the request can be retried. Throws an exception if the request failed permanently.
private void openFirstUseDialog(){ try { Stage promptStage=new Stage(); AnchorPane preloaderPane=FXMLLoader.load(getClass().getResource(PRELOADER_FIRST_USE_PROMPT)); Button openButton=(Button)preloaderPane.lookup("#openButton"); Button okButton=(Button)preloaderPane.lookup("#okButton"); TextField musicottFolderTextField=(TextField)preloaderPane.lookup("#musicottFolderTextField"); String sep=File.separator; String userHome=System.getProperty("user.home"); String defaultMusicottLocation=userHome + sep + "Music"+ sep+ "Musicott"; musicottFolderTextField.setText(defaultMusicottLocation); okButton.setOnMouseClicked(null); openButton.setOnMouseClicked(null); Scene promptScene=new Scene(preloaderPane,SCENE_WIDTH,SCENE_HEIGHT); promptStage.setOnCloseRequest(null); promptStage.initModality(Modality.APPLICATION_MODAL); promptStage.initOwner(preloaderStage.getOwner()); promptStage.setResizable(false); promptStage.setScene(promptScene); promptStage.initStyle(StageStyle.UNDECORATED); promptStage.showAndWait(); } catch ( IOException e) { ErrorDemon.getInstance().showErrorDialog("Error opening Musicott's folder selection","",e); } }
Shows a window asking the user to enter the location of the application folder. The default location is <tt>~/Music/Musicott</tt>
public void runTest() throws Throwable { Document doc; NodeList nameList; Node nameNode; Node firstChild; String childValue; doc=(Document)load("hc_staff",false); nameList=doc.getElementsByTagName("strong"); nameNode=nameList.item(3); firstChild=nameNode.getFirstChild(); childValue=firstChild.getNodeValue(); assertEquals("documentGetElementsByTagNameValueAssert","Jeny Oconnor",childValue); }
Runs the test case.
public void deselect(OMGraphicList list){ super.deselect(list); if (selectedList != null) { System.out.println("Current selection list: " + selectedList.getDescription()); } }
Designate a list of OMGraphics as deselected.
public void put(IN4JSProject api,IN4JSProject impl){ final String apiId=api.getProjectId(); if (apiId == null) return; final String implId=impl.getImplementationId().orNull(); if (implId == null) { projectsWithUndefImplIds.add(impl); return; } ApiImplMapping.ApiImplAssociation assoc=assocs.get(apiId); if (assoc == null) { assoc=new ApiImplAssociation(api); assocs.put(apiId,assoc); } final IN4JSProject replaced=assoc.putImpl(impl); if (replaced != null && !Objects.equals(replaced,impl)) { putConflict(apiId,implId,replaced,impl); } }
Add a single API -> implementation association to the receiving mapping (if it is not present already).
private Integer parseDayIcon(JSONObject response) throws JSONException { JSONObject hourly=response.getJSONObject("hourly"); String icon=hourly.getString("icon"); return iconResources.get(icon); }
Reads the 24-hour forecast weather icon code from the API response.
private void triggerScanning(DataCollectionScanJob job) throws Exception { _logger.info("Started scanning Providers : triggerScanning()"); _jobScheduler.refreshProviderConnections(); List<URI> providerList=job.getProviders(); List<URI> allProviderURI=_dbClient.queryByType(StorageProvider.class,true); List<StorageProvider> allProviders=_dbClient.queryObject(StorageProvider.class,allProviderURI); allProviderURI=new ArrayList<URI>(); for ( StorageProvider provider : allProviders) { allProviderURI.add(provider.getId()); } Map<String,StorageSystemViewObject> storageSystemsCache=Collections.synchronizedMap(new HashMap<String,StorageSystemViewObject>()); boolean exceptionIntercepted=false; if (ControllerServiceImpl.Lock.SCAN_COLLECTION_LOCK.acquire(ControllerServiceImpl.Lock.SCAN_COLLECTION_LOCK.getRecommendedTimeout())) { try { boolean scanIsNeeded=false; boolean hasProviders=false; for ( StorageProvider provider : allProviders) { if (provider.connected() || provider.initializing()) { hasProviders=true; if (_jobScheduler.isProviderScanJobSchedulingNeeded(provider,ControllerServiceImpl.SCANNER,job.isSchedulerJob())) { scanIsNeeded=true; break; } } } if (!scanIsNeeded) { for ( StorageProvider provider : allProviders) { ScanTaskCompleter scanCompleter=job.findProviderTaskCompleter(provider.getId()); if (scanCompleter == null) { continue; } if (provider.connected() || provider.initializing()) { scanCompleter.statusReady(_dbClient,"SCAN is not needed"); } else { String errMsg="Failed to establish connection to the storage provider"; scanCompleter.error(_dbClient,DeviceControllerErrors.smis.unableToCallStorageProvider(errMsg)); provider.setLastScanStatusMessage(errMsg); _dbClient.persistObject(provider); } } if (!hasProviders) { _util.performBookKeeping(storageSystemsCache,allProviderURI); } _logger.info("Scan is not needed"); } else { List<URI> cacheProviders=new ArrayList<URI>(); for ( StorageProvider provider : allProviders) { if (provider.connected() || provider.initializing()) { ScanTaskCompleter scanCompleter=job.findProviderTaskCompleter(provider.getId()); if (scanCompleter == null) { String taskId=UUID.randomUUID().toString(); scanCompleter=new ScanTaskCompleter(StorageProvider.class,provider.getId(),taskId); job.addCompleter(scanCompleter); } try { scanCompleter.updateObjectState(_dbClient,DiscoveredDataObject.DataCollectionJobStatus.IN_PROGRESS); scanCompleter.setNextRunTime(_dbClient,System.currentTimeMillis() + DataCollectionJobScheduler.JobIntervals.get(ControllerServiceImpl.SCANNER).getInterval() * 1000); provider.setLastScanStatusMessage(""); _dbClient.persistObject(provider); _logger.info("provider.getInterfaceType():{}",provider.getInterfaceType()); performScan(provider.getId(),scanCompleter,storageSystemsCache); cacheProviders.add(provider.getId()); } catch ( Exception ex) { _logger.error("Scan failed for {}--->",provider.getId(),ex); scanCompleter.error(_dbClient,DeviceControllerErrors.dataCollectionErrors.scanFailed(ex.getLocalizedMessage(),ex)); } } else { if (null != provider.getStorageSystems() && !provider.getStorageSystems().isEmpty()) { provider.getStorageSystems().clear(); } if (providerList.contains(provider.getId())) { String errMsg="Failed to establish connection to the storage provider"; provider.setLastScanStatusMessage(errMsg); job.findProviderTaskCompleter(provider.getId()).error(_dbClient,DeviceControllerErrors.smis.unableToCallStorageProvider(errMsg)); } _dbClient.persistObject(provider); } } _util.performBookKeeping(storageSystemsCache,allProviderURI); for ( URI provider : cacheProviders) { job.findProviderTaskCompleter(provider).ready(_dbClient); _logger.info("Scan complete successfully for " + provider); } } } catch ( final Exception ex) { _logger.error("Scan failed for {} ",ex.getMessage()); exceptionIntercepted=true; throw ex; } finally { ControllerServiceImpl.Lock.SCAN_COLLECTION_LOCK.release(); try { if (!exceptionIntercepted) { triggerDiscoveryNew(storageSystemsCache); } } catch ( Exception ex) { _logger.error("Exception occurred while triggering discovery of new systems",ex); } } } else { job.setTaskError(_dbClient,DeviceControllerErrors.dataCollectionErrors.scanLockFailed()); _logger.debug("Not able to Acquire Scanning lock-->{}",Thread.currentThread().getId()); } }
1. refreshConnections - needs to get called on each Controller, before acquiring lock. 2. Try to acquire lock, if found 3. Acquiring lock is not made as a Blocking Call, hence Controllers will return immediately, if lock not found 3. If lock found, spawn a new thread to do triggerScanning. 4. Release lock immediately.
public void remoteReconfigCoordinator(String nodeId,String type) throws LocalRepositoryException { final String prefix=String.format("reconfigCoordinator(%s): on %s",type,nodeId); _log.debug(prefix); final String[] cmd={_SYSTOOL_CMD,_SYSTOOL_REMOTE_SYSTOOL,nodeId,_SYSTOOL_RECONFIG_COORDINATOR,type}; final Exec.Result result=Exec.sudo(_SYSTOOL_TIMEOUT,cmd); checkFailure(result,prefix); }
Reconfig remote coordinatorsvc to observer(default mode), or pariticpant(when active site is down) For DR standby site only.
@Override public synchronized void close() throws IOException { if (DBG) log("close() EX"); }
Closes the socket. It is not possible to reconnect or rebind to this socket thereafter which means a new socket instance has to be created.
@Override public boolean remove(Object value){ return _set.remove(unwrap(value)); }
Deletes a value from the set.
public GameDelegateBridge(final IDelegateBridge bridge){ m_bridge=bridge; m_historyWriter=new GameDelegateHistoryWriter(m_bridge.getHistoryWriter(),getData()); }
Creates new TripleADelegateBridge to wrap an existing IDelegateBridge
public void action(String action){ bot.sendIRC().action(channel.getName(),action); }
Send an action to the channel.
public DistributedLogClientBuilder periodicHandshakeIntervalMs(long intervalMs){ DistributedLogClientBuilder newBuilder=newBuilder(this); newBuilder._clientConfig.setPeriodicHandshakeIntervalMs(intervalMs); return newBuilder; }
Set the periodic handshake interval in milliseconds. Every <code>intervalMs</code>, the DL client will handshake with existing proxies again. If the interval is less than ownership sync interval, the handshake won't sync ownerships. Otherwise, it will.
public void start(){ if (description_file_loaded) { pause=false; if (graphics_on) this.repaint(); for (int i=0; i < control_systems.length; i++) { control_systems[i].trialInit(); } startrun=System.currentTimeMillis(); frames=0; } else { Dialog tmp; if (graphics_on) tmp=new DialogMessage(parent,"TBSim Error","You must load a description file first.\n" + "Use the `load' option under the `file' menu."); } }
Handle a start/resume event.
public MetaSentence(Session s,String sSentence,SerializerWrite serwrite,SerializerRead serread){ super(s); m_sSentence=sSentence; m_SerWrite=serwrite; m_SerRead=serread; }
Creates a new instance of MetaDataSentence
public SingleIsA_ createSingleIsA_(){ SingleIsA_Impl singleIsA_=new SingleIsA_Impl(); return singleIsA_; }
<!-- begin-user-doc --> <!-- end-user-doc -->
public GeneratorConfiguration createGeneratorConfiguration(){ GeneratorConfigurationImpl generatorConfiguration=new GeneratorConfigurationImpl(); return generatorConfiguration; }
<!-- begin-user-doc --> <!-- end-user-doc -->
public Collection<SynchronizingStorageEngine> values(){ return localStores.values(); }
Get a collection containing all the currently-registered stores
public WifiP2pDevice remove(String deviceAddress){ validateDeviceAddress(deviceAddress); return mDevices.remove(deviceAddress); }
Remove a device from the list
public int cell(int r,int c){ return board[r][c]; }
Return contents of cell[r][c].
public static ToHitData toHit(IGame game,int attackerId,Targetable target,MovePath md){ final Entity ae=game.getEntity(attackerId); if (target == null) { return new ToHitData(TargetRoll.IMPOSSIBLE,"Target is null"); } Entity te=null; if (target.getTargetType() == Targetable.TYPE_ENTITY) { te=(Entity)target; } Coords chargeSrc=ae.getPosition(); MoveStep chargeStep=null; if (ae instanceof Infantry) { return new ToHitData(TargetRoll.IMPOSSIBLE,"Infantry can't D.F.A."); } if (ae.getJumpType() == Mech.JUMP_BOOSTER) { return new ToHitData(TargetRoll.IMPOSSIBLE,"Can't D.F.A. using mechanical jump boosters."); } if (!md.contains(MoveStepType.DFA)) { return new ToHitData(TargetRoll.IMPOSSIBLE,"D.F.A. action not found in movement path"); } if (!md.contains(MoveStepType.START_JUMP)) { return new ToHitData(TargetRoll.IMPOSSIBLE,"D.F.A. must involve jumping"); } if ((te != null) && te.isAirborne()) { return new ToHitData(TargetRoll.IMPOSSIBLE,"Cannot D.F.A. an airborne target."); } if ((te != null) && (te instanceof Dropship)) { return new ToHitData(TargetRoll.IMPOSSIBLE,"Cannot D.F.A. a dropship."); } if ((te != null) && (Entity.NONE != te.getTransportId())) { return new ToHitData(TargetRoll.IMPOSSIBLE,"Target is a passenger."); } if (md.contains(MoveStepType.EVADE)) { return new ToHitData(TargetRoll.IMPOSSIBLE,"No evading while charging"); } if ((te != null) && (Entity.NONE != te.getSwarmTargetId())) { return new ToHitData(TargetRoll.IMPOSSIBLE,"Target is swarming a Mek."); } md.compile(game,ae); for (final Enumeration<MoveStep> i=md.getSteps(); i.hasMoreElements(); ) { final MoveStep step=i.nextElement(); if (!step.isLegal(md)) { break; } if (step.getType() == MoveStepType.DFA) { chargeStep=step; } else { chargeSrc=step.getPosition(); } } if ((chargeStep == null) || !target.getPosition().equals(chargeStep.getPosition())) { return new ToHitData(TargetRoll.IMPOSSIBLE,"Could not reach target with movement"); } if ((te != null) && (!te.isDone() && !te.isImmobile())) { return new ToHitData(TargetRoll.IMPOSSIBLE,"Target must be done with movement"); } return DfaAttackAction.toHit(game,attackerId,target,chargeSrc); }
Checks if a death from above attack can hit the target, including movement
private void registerListener(final String requestUrl,final String target,String[] methods,Integer expireTime,String filter,Integer queueExpireTime,Map<String,String> staticHeaders){ registerListener(requestUrl,target,methods,expireTime,filter,queueExpireTime,staticHeaders,null); }
Registers a listener with a filter and static headers.
public void invoke(BurlapInput in,BurlapOutput out) throws Exception { invoke(_service,in,out); }
Invoke the object with the request from the input stream.
private int[][] generateDistinctRandomSets(int n,int p,int maxNumSets,int[][] setsToAvoidOverlapWith){ if (true) { throw new RuntimeException("Not implemented yet"); } int maxPossibleNumSets=0; try { maxPossibleNumSets=MathsUtils.numOfSets(n,p); if (maxNumSets > maxPossibleNumSets) { maxNumSets=maxPossibleNumSets; return generateAllDistinctSets(n,p); } } catch ( Exception e) { } int[][] sets=new int[maxNumSets][p]; Vector<Integer> availableChoices=new Vector<Integer>(); for (int i=0; i < n; i++) { availableChoices.add(new Integer(i)); } Vector<Integer> thisSet=new Vector<Integer>(); Hashtable<Vector<Integer>,Integer> chosenSets=new Hashtable<Vector<Integer>,Integer>(); for (int s=0; s < maxNumSets; s++) { for (; ; ) { availableChoices.addAll(thisSet); if (setsToAvoidOverlapWith != null) { for (int i=0; i < p; i++) { availableChoices.remove(new Integer(setsToAvoidOverlapWith[s][p])); } } thisSet.clear(); for (int q=0; q < p; q++) { int randIndex=random.nextInt(n - q); Integer nextSelection=availableChoices.remove(randIndex); sets[s][q]=nextSelection.intValue(); } Arrays.sort(sets[s]); for (int q=0; q < p; q++) { thisSet.add(new Integer(sets[s][q])); } if (chosenSets.get(thisSet) == null) { chosenSets.put(thisSet,new Integer(0)); break; } } } return sets; }
Generate (up to) numSets distinct sets of p distinct values in [0..n-1]. Done using random guesses as this is designed for high dimension n where its highly unlikely we repeat a set (though this is checked). Here we avoid overlapping the sets with any elements of the corresponding row of setsToAvoidOverlapWith
@Override public Object eGet(int featureID,boolean resolve,boolean coreType){ switch (featureID) { case UmplePackage.CONDITION_RHS___COMPARISON_OPERATOR_1: return getComparison_operator_1(); case UmplePackage.CONDITION_RHS___RHS_1: return getRHS_1(); } return super.eGet(featureID,resolve,coreType); }
<!-- begin-user-doc --> <!-- end-user-doc -->
boolean implementsAlg(String serv,String alg,String attribute,String val){ String servAlg=serv + "." + alg; String prop=getPropertyIgnoreCase(servAlg); if (prop == null) { alg=getPropertyIgnoreCase("Alg.Alias." + servAlg); if (alg != null) { servAlg=serv + "." + alg; prop=getPropertyIgnoreCase(servAlg); } } if (prop != null) { if (attribute == null) { return true; } return checkAttribute(servAlg,attribute,val); } return false; }
Returns true if this provider implements the given algorithm. Caller must specify the cryptographic service and specify constraints via the attribute name and value.
public void clipRect(int x,int y,int width,int height){ clip(new Rectangle(x,y,width,height)); }
Intersects the current clip with the specified rectangle. The resulting clipping area is the intersection of the current clipping area and the specified rectangle. If there is no current clipping area, either because the clip has never been set, or the clip has been cleared using <code>setClip(null)</code>, the specified rectangle becomes the new clip. This method sets the user clip, which is independent of the clipping associated with device bounds and window visibility. This method can only be used to make the current clip smaller. To set the current clip larger, use any of the setClip methods. Rendering operations have no effect outside of the clipping area.
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.
private void shrinkFileIfPossible(int minPercent){ if (fileStore.isReadOnly()) { return; } long end=getFileLengthInUse(); long fileSize=fileStore.size(); if (end >= fileSize) { return; } if (minPercent > 0 && fileSize - end < BLOCK_SIZE) { return; } int savedPercent=(int)(100 - (end * 100 / fileSize)); if (savedPercent < minPercent) { return; } if (!closed) { sync(); } fileStore.truncate(end); }
Shrink the file if possible, and if at least a given percentage can be saved.
public static void main(String... a) throws Exception { TestBase.createCaller().init().test(); }
Run just this test.
public static <T>T eachLine(URL url,@ClosureParams(value=FromString.class,options={"String","String,Integer"}) Closure<T> closure) throws IOException { return eachLine(url,1,closure); }
Iterates through the lines read from the URL's associated input stream passing each line to the given 1 or 2 arg closure. The stream is closed before this method returns.
public void showDroidsafeTextMarkers(IEditorPart openedEditor,String className){ if (openedEditor != null && openedEditor instanceof ITextEditor && fProcessedClasses != null) { ITextEditor editor=(ITextEditor)openedEditor; if (fProcessedClasses.contains(className)) { if (fClassesNeedUpdate.contains(className)) { ClassMarkerProcessor classProcessor=get(className); classProcessor.updateTaintMarkers(editor); fClassesNeedUpdate.remove(className); } } else { fProcessedClasses.add(className); Map<String,Map<IntRange,Map<String,Set<CallLocationModel>>>> classTaintedDataMap=fTaintedDataMap.get(className); Map<String,Set<IntRange>> classUnreachableMethodMap=fUnreachableSourceMethodMap.get(className); if (classTaintedDataMap != null || classUnreachableMethodMap != null) { IEditorInput input=editor.getEditorInput(); if (input instanceof FileEditorInput) { ClassMarkerProcessor classProcessor=get(className); classProcessor.showDroidsafeTextMarkers(editor); } } } } }
Displays the annotations of the droidsafe text markers for the given class name in the given Java editor.
public DoubleMatrix2D like(int rows,int columns){ return new RCDoubleMatrix2D(rows,columns); }
Construct and returns a new empty matrix <i>of the same dynamic type</i> as the receiver, having the specified number of rows and columns. For example, if the receiver is an instance of type <tt>DenseDoubleMatrix2D</tt> the new matrix must also be of type <tt>DenseDoubleMatrix2D</tt>, if the receiver is an instance of type <tt>SparseDoubleMatrix2D</tt> the new matrix must also be of type <tt>SparseDoubleMatrix2D</tt>, etc. In general, the new matrix should have internal parametrization as similar as possible.
public static EnvironmentId parse(String fqn){ if (fqn == null) { throw new IllegalArgumentException("Null fqn isn't allowed."); } final Matcher matcher=ENV_FQN_PATTERN.matcher(fqn); if (matcher.matches()) { return new EnvironmentId(Scope.fromValue(matcher.group(1)),matcher.group(2),matcher.group(3)); } throw new IllegalArgumentException("Invalid fqn: " + fqn); }
Parse environment id, that is represented by fqn, in format <i>&lt;scope&gt;:/&lt;category&gt;/&lt;name&gt;</i>. Category is optional and may be empty string, e.g. <i>&lt;project&gt;://&lt;name&gt;</i>.
public void shiftLeft() throws IOException { writeCode(SHIFT_LEFT); }
SWFActions interface
public void addData(String name,InputStream data,long dataSize,String mimeType){ args.put(name,data); if (!filenames.containsKey(name)) { filenames.put(name,name); } filesizes.put(name,String.valueOf(dataSize)); mimeTypes.put(name,mimeType); }
Adds a binary argument to the arguments, notice the input stream will be read only during submission
@Field(41) public Pointer<Integer> pulVal(){ return this.io.getPointerField(this,41); }
VT_BYREF|VT_UI4<br> C type : ULONG
private void writeDataPage(ByteBuffer pageBuffer,int pageNumber) throws IOException { getPageChannel().writePage(pageBuffer,pageNumber); _addRowBufferH.possiblyInvalidate(pageNumber,pageBuffer); ++_modCount; }
Writes the given page data to the given page number, clears any other relevant buffers.
public static <T1,T2,T3,T4,T5,T6,R>QuadFunction<T3,T4,T5,T6,R> partial6(final T1 t1,final T2 t2,final HexFunction<T1,T2,T3,T4,T5,T6,R> hexFunc){ return null; }
Returns a QuadFunction with 2 arguments applied to the supplied HexFunction
public StateWrapper(final IInfluencingState<ApiLatticeElement,ObjectType> wrappedState){ Preconditions.checkNotNull(wrappedState,"IE02086: Wrapped state argument can not be null"); element=wrappedState.getElement(); object=wrappedState.getObject(); }
Creates a new wrapper object.
public ConversionException(final String message){ super(message); }
Construct a new exception with the specified message.
protected static Long max(Long l1,Long l2){ if (l1 == null && l2 == null) { return null; } if (l2 == null) { return l1; } if (l1 == null) { return l2; } return Math.max(l1,l2); }
Utility method to return the maximum of two Long values, either of which may be null.
public static BufferedImage createCompatibleImage(int width,int height){ return getGraphicsConfiguration().createCompatibleImage(width,height); }
<p>Returns a new opaque compatible image of the specified width and height.</p>
public static void main(final String[] args) throws Exception { int i=0; int flags=ClassReader.SKIP_DEBUG; boolean ok=true; if (args.length < 1 || args.length > 2) { ok=false; } if (ok && "-debug".equals(args[0])) { i=1; flags=0; if (args.length != 2) { ok=false; } } if (!ok) { System.err.println("Prints the ASM code to generate the given class."); System.err.println("Usage: ASMifier [-debug] " + "<fully qualified class name or class file name>"); return; } ClassReader cr; if (args[i].endsWith(".class") || args[i].indexOf('\\') > -1 || args[i].indexOf('/') > -1) { cr=new ClassReader(new FileInputStream(args[i])); } else { cr=new ClassReader(args[i]); } cr.accept(new TraceClassVisitor(null,new ASMifier(),new PrintWriter(System.out)),flags); }
Prints the ASM source code to generate the given class to the standard output. <p> Usage: ASMifier [-debug] &lt;binary class name or class file name&gt;
@Override public void onAlarm(Alarm alarm){ if (mCurrentScrollDir == DragController.SCROLL_LEFT) { mContent.scrollLeft(); mScrollHintDir=DragController.SCROLL_NONE; } else if (mCurrentScrollDir == DragController.SCROLL_RIGHT) { mContent.scrollRight(); mScrollHintDir=DragController.SCROLL_NONE; } else { return; } mCurrentScrollDir=DragController.SCROLL_NONE; mScrollPauseAlarm.setOnAlarmListener(new OnScrollFinishedListener(mDragObject)); mScrollPauseAlarm.setAlarm(DragController.RESCROLL_DELAY); }
Scroll hint has been shown long enough. Now scroll to appropriate page.
public void edit(){ if (this.selectedObject instanceof Placemark && this.selectedObject.hasUserProperty(EDITABLE)) { Placemark placemark=(Placemark)this.selectedObject; Bundle args=new Bundle(); args.putString("title","Select the " + placemark.getDisplayName() + "'s type"); if (placemark.hasUserProperty(AIRCRAFT_TYPE)) { args.putString("vehicleKey",AIRCRAFT_TYPE); args.putString("vehicleValue",(String)placemark.getUserProperty(AIRCRAFT_TYPE)); } else if (placemark.hasUserProperty(AUTOMOTIVE_TYPE)) { args.putString("vehicleKey",AUTOMOTIVE_TYPE); args.putString("vehicleValue",(String)placemark.getUserProperty(AUTOMOTIVE_TYPE)); } VehicleTypeDialog dialog=new VehicleTypeDialog(); dialog.setArguments(args); dialog.show(getSupportFragmentManager(),"aircraft_type"); } else { Toast.makeText(getApplicationContext(),(this.selectedObject == null ? "Object " : this.selectedObject.getDisplayName()) + " is not editable.",Toast.LENGTH_LONG).show(); } }
Edits the currently selected object.
public AsyncTimerOptions create(){ return new AsyncTimerOptions(); }
Creates a new async timer options.
public static String md5(String stringToHash){ if (stringToHash != null) { try { MessageDigest md=MessageDigest.getInstance("MD5"); byte[] bytes=md.digest(stringToHash.getBytes()); StringBuilder sb=new StringBuilder(2 * bytes.length); for (int i=0; i < bytes.length; i++) { int low=(bytes[i] & 0x0f); int high=((bytes[i] & 0xf0) >> 4); sb.append(Constants.HEXADECIMAL[high]); sb.append(Constants.HEXADECIMAL[low]); } return sb.toString(); } catch ( NoSuchAlgorithmException e) { return ""; } } else { return ""; } }
Convierte un string a hash md5
public static void printFeatures(String fname,List<Object> features,String layername){ if (!features.isEmpty()) { print(layername + "." + fname+ "="); for ( Object obj : features) { print(obj.toString()); } println(); } }
Print some featureclass names
private static String percentEncodeRfc3986(String string){ try { string=string.replace("+","%2B"); string=URLDecoder.decode(string,"UTF-8"); string=URLEncoder.encode(string,"UTF-8"); return string.replace("+","%20").replace("*","%2A").replace("%7E","~"); } catch ( Exception e) { return string; } }
Percent-encode values according the RFC 3986. The built-in Java URLEncoder does not encode according to the RFC, so we make the extra replacements.
@Override public String toString(){ StringBuilder sb=new StringBuilder(); sb.append("{"); sb.append(getContinuousScale().toString()); sb.append(",#"); sb.append(new Color(color1[0],color1[1],color1[2],color1[3]).getRGB()); sb.append(",#"); sb.append(new Color(color2[0],color2[1],color2[2],color2[3]).getRGB()); if (color3 != null) { sb.append(",#"); sb.append(new Color(color3[0],color3[1],color3[2],color3[3]).getRGB()); } sb.append("}"); return sb.toString(); }
Create a string representation suitable for writing to a text file
public TextCharacter withoutModifier(SGR modifier){ if (!modifiers.contains(modifier)) { return this; } EnumSet<SGR> newSet=EnumSet.copyOf(this.modifiers); newSet.remove(modifier); return new TextCharacter(character,foregroundColor,backgroundColor,newSet); }
Returns a copy of this TextCharacter with an SGR modifier removed. All of the currently active SGR codes will be carried over to the copy, except for the one specified. If the current TextCharacter doesn't have the SGR specified, it will return itself.
private static Intent createGeoUriIntent(String uri){ return new Intent(Intent.ACTION_VIEW,Uri.parse(uri)); }
Creates Intent for display exact location on the map with specified title and without searching. <p/> This may not work on different map that on google.
public static String toJson(final Object object){ return toJson(object,true); }
Recursively convert from native Rhino to JSON. <p> Recognizes JavaScript objects, arrays and primitives. <p> Special support for JavaScript dates: converts to {"$date": timestamp} in JSON. <p> Special support for MongoDB ObjectId: converts to {"$oid": "objectid"} in JSON. <p> Also recognizes JVM types: java.util.Map, java.util.Collection, java.util.Date.
public boolean isAuditLogDataAvailable(){ return (model.getAuditLogData() != null && model.getAuditLogData().length > 0); }
Checks if audit log data has been read.
private Promise<PrivateKey> fetchPreKey(){ return PromisesArray.of(ownKeys.getPreKeys()).random(); }
Fetching own random pre key
public void addHeaderView(View v){ addHeaderView(v,null,true); }
Add a fixed view to appear at the top of the list. If addHeaderView is called more than once, the views will appear in the order they were added. Views added using this call can take focus if they want. <p> NOTE: Call this before calling setAdapter. This is so ListView can wrap the supplied cursor with one that will also account for header and footer views.
public static void createTable(SQLiteDatabase db,boolean ifNotExists){ String constraint=ifNotExists ? "IF NOT EXISTS " : ""; db.execSQL("CREATE TABLE " + constraint + "'SISTER_CACHE' ("+ "'_id' INTEGER PRIMARY KEY AUTOINCREMENT ,"+ "'RESULT' TEXT,"+ "'PAGE' INTEGER,"+ "'TIME' INTEGER);"); }
Creates the underlying database table.
@Override protected final double blackVarianceImpl(final double maturity,final double strike){ final double vol=blackVolImpl(maturity,strike); final double variance=vol * vol * maturity; return variance; }
Returns the variance for the given strike and date calculating it from the volatility.
protected StoragePool checkPoolExistsInDB(String nativeGuid) throws IOException { StoragePool pool=null; List<StoragePool> poolInDB=CustomQueryUtility.getActiveStoragePoolByNativeGuid(_dbClient,nativeGuid); if (poolInDB != null && !poolInDB.isEmpty()) { pool=poolInDB.get(0); } return pool; }
Check if Pool exists in DB.
public void addListener(final ICodeNodeListener listener){ m_listeners.addListener(listener); }
Adds a listener object that is notified about changes in the code node.
void reset(){ synchronized (this) { databaseRef=null; } }
Stop and disable the database closer. This method is called after the database has been closed, or after a session has been created.
public FlowLayout(int align,int hgap,int vgap){ this.hgap=hgap; this.vgap=vgap; setAlignment(align); }
Creates a new flow layout manager with the indicated alignment and the indicated horizontal and vertical gaps. <p> The value of the alignment argument must be one of <code>FlowLayout.LEFT</code>, <code>FlowLayout.RIGHT</code>, <code>FlowLayout.CENTER</code>, <code>FlowLayout.LEADING</code>, or <code>FlowLayout.TRAILING</code>.
private final void updateBuffer(int offset){ fBufferOffset=offset; if (fBufferOffset + fBuffer.length > fRangeOffset + fRangeLength) fBufferLength=fRangeLength - (fBufferOffset - fRangeOffset); else fBufferLength=fBuffer.length; try { final String content=fDocument.get(fBufferOffset,fBufferLength); content.getChars(0,fBufferLength,fBuffer,0); } catch ( BadLocationException e) { } }
Fills the buffer with the contents of the document starting at the given offset.
public HeadlessConsole(){ logToSystem=true; }
Creates an Headless console
@Override public void close() throws IOException { coreContainer.shutdown(); }
Shutdown all cores within the EmbeddedSolrServer instance
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:27:51.605 -0500",hash_original_method="C19DA42AB571E96824BDE2AB4D9CB311",hash_generated_method="88B07071FEA72C990EF2B30E64B194D7") public static String convertKeypadLettersToDigits(String input){ if (input == null) { return input; } int len=input.length(); if (len == 0) { return input; } char[] out=input.toCharArray(); for (int i=0; i < len; i++) { char c=out[i]; out[i]=(char)KEYPAD_MAP.get(c,c); } return new String(out); }
Translates any alphabetic letters (i.e. [A-Za-z]) in the specified phone number into the equivalent numeric digits, according to the phone keypad letter mapping described in ITU E.161 and ISO/IEC 9995-8.
public void encodeByte(int b){ ensureFreeBytes(1); buf[offset++]=(byte)b; }
Encode a single byte.
public SearchObject(IconType icon,String keyword){ this.icon=icon; this.keyword=keyword; }
Plain search only, you may need to add searchfinish callback instead of redirecting to any links.
@Override protected void onRestoreInstanceState(@NonNull Bundle state){ ensureList(); super.onRestoreInstanceState(state); }
Ensures the expandable list view has been created before Activity restores all of the view states.
public T caseCompositeProcessor(CompositeProcessor object){ return null; }
Returns the result of interpreting the object as an instance of '<em>Composite Processor</em>'. <!-- begin-user-doc --> This implementation returns null; returning a non-null result will terminate the switch. <!-- end-user-doc -->
@OnClose public void onClose(final Session session,final CloseReason closeReason){ removeSession(session); }
Called when the connection closed.
public UserCredentialsListener(String userId){ this.userId=userId; }
Construct new listener.
public void addMember(Stream member){ memberSet.add(member); }
Add a single member to the equivalence class.
public static Function<String> jsonArray(Object... args){ return new JSONArgumentFunction<>("json_array",null,args); }
Wrapper for the json_array() SQL function
@Override protected EClass eStaticClass(){ return N4JSPackage.Literals.VARIABLE; }
<!-- begin-user-doc --> <!-- end-user-doc -->
public MemcacheClientBuilder<V> withConnections(final int connections){ if (connections < 1) { throw new IllegalArgumentException("connections must be at least 1"); } this.connections=connections; return this; }
Use multiple connections to each memcache server. This is likely not a useful thing in practice, unless the IO connection really becomes a bottleneck.
public void push(int value) throws IOException { print("push",new String[]{"" + value}); }
Description of the Method
private void executeList(String[] args) throws IOException, ServiceException, DocumentListException { DocumentListFeed feed=null; String msg=""; switch (args.length) { case 1: msg="List of docs: "; feed=docs.getDocsListFeed("all"); break; case 2: msg="List of all " + args[1] + ": "; feed=docs.getDocsListFeed(args[1]); break; case 3: if (args[1].equals("folder")) { msg="Contents of folder_id '" + args[2] + "': "; feed=docs.getFolderDocsListFeed(args[2]); } break; } if (feed != null) { output.println(msg); for (DocumentListEntry entry : feed.getEntries()) { printDocumentEntry(entry); } } else { printMessage(COMMAND_HELP_MESSAGE); } }
Execute 'list' command.
public static void writeField(final Field field,final Object target,final Object value) throws IllegalAccessException { FieldUtils.writeField(field,target,value,false); }
Write an accessible field.
public String toString(){ StringBuffer sb=new StringBuffer("MOrderTax[").append("C_Order_ID=").append(getC_Order_ID()).append(", C_Tax_ID=").append(getC_Tax_ID()).append(", Base=").append(getTaxBaseAmt()).append(", Tax=").append(getTaxAmt()).append("]"); return sb.toString(); }
String Representation
public Stream<Tuple2io<int[]>> read(String in) throws FileNotFoundException { return read(new FileInputStream(in)); }
Reads a file that complies with this format.
public final void XprintLatin1NoLf(String string) throws IOException { if (_source == null) { return; } if (string == null) { string="null"; } byte[] writeBuffer=_writeBuffer; int writeLength=_writeLength; int length=string.length(); int offset=0; int charsLength=CHARS_LENGTH; char[] chars=_chars; while (length > 0) { int sublen=Math.min(charsLength,writeBuffer.length - writeLength); if (sublen <= 0) { _source.write(writeBuffer,0,writeLength,false); _position+=writeLength; _isFlushRequired=true; writeLength=0; sublen=Math.min(charsLength,writeBuffer.length - writeLength); } sublen=Math.min(length,sublen); string.getChars(offset,sublen,chars,0); for (int i=0; i < sublen; i++) { byte value=(byte)chars[i]; if (value == '\r' || value == '\n') { length=0; break; } writeBuffer[writeLength++]=value; } offset+=sublen; length-=sublen; } _writeLength=writeLength; }
Prints the character buffer to the stream encoded as latin1.
public boolean isEncryptionEnabled(){ return encrypt; }
Check if encryption is activated. By default the encryption is not activated.
public GSAContextDisplaySelection(String encoding,String content,int startOffset,int endOffset){ this.encoding=encoding; this.content=content; this.startOffset=startOffset; this.endOffset=endOffset; }
Creates an immutable object representing a selection and surrounding text.
public CertificateValidity(DerInputStream in) throws IOException { DerValue derVal=in.getDerValue(); construct(derVal); }
Create the object, decoding the values from the passed DER stream.
public static void main(final String[] args){ DOMTestCase.doMain(hc_characterdatadeletedataend.class,args); }
Runs this test from the command line.
private void processJournal() throws IOException { deleteIfExists(journalFileTmp); for (Iterator<Entry> i=lruEntries.values().iterator(); i.hasNext(); ) { Entry entry=i.next(); if (entry.currentEditor == null) { for (int t=0; t < valueCount; t++) { size+=entry.lengths[t]; fileCount++; } } else { entry.currentEditor=null; for (int t=0; t < valueCount; t++) { deleteIfExists(entry.getCleanFile(t)); deleteIfExists(entry.getDirtyFile(t)); } i.remove(); } } }
Computes the initial size and collects garbage as a part of opening the cache. Dirty entries are assumed to be inconsistent and will be deleted.
public boolean empty(){ return m_firstFree == 0; }
Tests if this stack is empty.
public CategoryImageRetrieveStrategyAttributeImpl(final String attributeCode){ this.attributeCode=attributeCode; }
Construct image retrieve strategy