code
stringlengths
10
174k
nl
stringlengths
3
129k
public TransformVariablesBrs(BBOBFunction function){ super(function); }
Constructs a new instance of the Buche-Rastrigin scaling transformation.
public static final String genPreferenceFilename(Context context){ return String.format("%s_%s",context.getString(R.string.afc_lib_name),_Uid); }
Generates global preference filename of this library.
public String EdgesToString(){ String s=""; int ne=0; for (int i=0; i < this.nNodes; i++) { for (int j=0; j < this.nNodes; j++) { double e=this.getEdges().getDoubleValue(i,j); if (e != 0.0) { s=s + i + " "+ j+ " \t"+ e+ "\n"; ne++; } } } return s; }
Returns a string representation of the set of edges in this graph
private void destroyHandles() throws ResourceException { if (ActiveMQRAManagedConnection.trace) { ActiveMQRALogger.LOGGER.trace("destroyHandles()"); } try { if (connection != null) { connection.stop(); } } catch ( Throwable t) { ActiveMQRALogger.LOGGER.trace("Ignored error stopping connection",t); } for ( ActiveMQRASession session : handles) { session.destroy(); } handles.clear(); }
Destroy all handles.
public void processQuoteLikeStringOpener(IElementType tokenType){ allowSharpQuote=true; isEscaped=false; pushState(); if (tokenType == RESERVED_Q) { yybegin(LEX_QUOTE_LIKE_OPENER_Q); } else if (tokenType == RESERVED_QQ) { yybegin(LEX_QUOTE_LIKE_OPENER_QQ); } else if (tokenType == RESERVED_QX) { yybegin(LEX_QUOTE_LIKE_OPENER_QX); } else if (tokenType == RESERVED_QW) { yybegin(LEX_QUOTE_LIKE_OPENER_QW); } else { throw new RuntimeException("Unable to switch state by token " + tokenType); } }
Quote-like string procesors
public void removePanListener(PanListener listener){ mTouchHandler.removePanListener(listener); }
Removes a pan listener.
public void write(ClassFile classFile,OutputStream s) throws IOException { this.classFile=classFile; out.reset(); write(); out.writeTo(s); }
Write a ClassFile data structure to a stream.
@CheckReturnValue public <T>Subject4<A,B,C,T> asWithPrecursor(Function3<A,B,C,T> mapping,Function<T,String> typeToString){ final Shrink<Tuple4<A,B,C,T>> shrink=null; final AsString<Tuple4<A,B,C,T>> desc=null; final Source<Tuple4<A,B,C,T>> gen=Source.of(generatePrecursorValueTuple(mapping)).withShrinker(shrink).describedAs(desc); return new PrecursorTheoryBuilder3<A,B,C,T>(this.state,gen,this.assumptions); }
Converts theory to one about a different type using the given function retaining all precursor values
private void initializeMessagesAndWake(Bundle b,boolean newIntent){ SmsMmsMessage message=new SmsMmsMessage(getApplicationContext(),b); message.locateMessageId(); if (newIntent) { smsPopupPager.addMessage(message); wakeApp(); } else { if (message != null) { new LoadUnreadMessagesAsyncTask().execute(message); } } }
Setup messages within the popup given an intent bundle
public static boolean isConditionalComment(@NotNull PsiElement host){ return parseConditionalCommentBoundaries(host) != null; }
Allows to check if given element is a <a href="http://msdn.microsoft.com/en-us/library/ms537512(v=vs.85).aspx">conditional comment</a>.
protected void updateFunctionGroup3(int fns){ this.f9=((fns & CbusConstants.CBUS_F9) == CbusConstants.CBUS_F9); this.f10=((fns & CbusConstants.CBUS_F10) == CbusConstants.CBUS_F10); this.f11=((fns & CbusConstants.CBUS_F11) == CbusConstants.CBUS_F11); this.f12=((fns & CbusConstants.CBUS_F12) == CbusConstants.CBUS_F12); }
Update the state of locomotive functions F9, F10, F11, F12 in response to a message from the hardware
public OrderedThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,IoEventQueueHandler eventQueueHandler){ this(corePoolSize,maximumPoolSize,keepAliveTime,unit,Executors.defaultThreadFactory(),eventQueueHandler); }
Creates a default ThreadPool, with default values : - A default ThreadFactory
@Override public Iterator<List<T>> iterator(){ return new SimpleCombinationIterator<T>(this); }
Creates an iterator of the simple combinations (without repetitions)
public double[] evaluateModel(Classifier classifier,Instances data,Object... forPredictionsPrinting) throws Exception { AbstractOutput classificationOutput=null; double predictions[]=new double[data.numInstances()]; if (forPredictionsPrinting.length > 0) { classificationOutput=(AbstractOutput)forPredictionsPrinting[0]; } if (classifier instanceof BatchPredictor) { Instances dataPred=new Instances(data); for (int i=0; i < data.numInstances(); i++) { dataPred.instance(i).setClassMissing(); } double[][] preds=((BatchPredictor)classifier).distributionsForInstances(dataPred); for (int i=0; i < data.numInstances(); i++) { double[] p=preds[i]; predictions[i]=evaluationForSingleInstance(p,data.instance(i),true); if (classificationOutput != null) { classificationOutput.printClassification(p,data.instance(i),i); } } } else { for (int i=0; i < data.numInstances(); i++) { predictions[i]=evaluateModelOnceAndRecordPrediction(classifier,data.instance(i)); if (classificationOutput != null) { classificationOutput.printClassification(classifier,data.instance(i),i); } } } return predictions; }
Evaluates the classifier on a given set of instances. Note that the data must have exactly the same format (e.g. order of attributes) as the data used to train the classifier! Otherwise the results will generally be meaningless.
protected void drawPath(GeneralPath path,Color fillColor,Paint fillPaint,Color penColor,boolean shadow){ if (fillColor != null || fillPaint != null) { if (shadow) { g.setColor(mxConstants.SHADOW_COLOR); g.translate(mxConstants.SHADOW_OFFSETX,mxConstants.SHADOW_OFFSETY); g.fill(path); g.translate(-mxConstants.SHADOW_OFFSETX,-mxConstants.SHADOW_OFFSETY); } if (fillPaint != null) { g.setPaint(fillPaint); } else { g.setColor(fillColor); } g.fill(path); } if (penColor != null) { g.setColor(penColor); g.draw(path); } }
Draws a path for the given parameters.
ForwardBuilder(BuilderParams buildParams,boolean searchAllCertStores){ super(buildParams); trustAnchors=buildParams.trustAnchors(); trustedCerts=new HashSet<X509Certificate>(trustAnchors.size()); trustedSubjectDNs=new HashSet<X500Principal>(trustAnchors.size()); for ( TrustAnchor anchor : trustAnchors) { X509Certificate trustedCert=anchor.getTrustedCert(); if (trustedCert != null) { trustedCerts.add(trustedCert); trustedSubjectDNs.add(trustedCert.getSubjectX500Principal()); } else { trustedSubjectDNs.add(anchor.getCA()); } } this.searchAllCertStores=searchAllCertStores; }
Initialize the builder with the input parameters.
public void addLowerLineSegment(ILineSegment lower){ if (lower.getEnd().equals(point)) { lowerSegments.append(lower); } else { throw new IllegalArgumentException("Improper attempt to add line segment whose lower point does not match EventPoint."); } }
Add this line segment but only if its Lower (i.e., End) is reflective of this eventPoint.
private void handleHtmlMakeNotebook(RequestAndResponse requestAndResponse) throws IOException, ServletException { final String note=requestAndResponse.request.getParameter(DbLogic.Constants.note); final boolean isPublic=getCheckBoxValue(requestAndResponse,"isPublic"); final String csrft=requestAndResponse.getParameter("csrft"); if (isTheCsrftWrong(requestAndResponse,csrft)) { requestAndResponse.response.sendRedirect("/couldNotCreateNote"); return; } String noteId=null; final Errors errors=new Errors(); try { final Long time=new Long(System.currentTimeMillis()); User user=null; final String userId=getEffectiveUserId(requestAndResponse); if (userId == null && allowSaveIfNotSignedIn) { user=createAnonUser(); if (user == null) { requestAndResponse.response.sendRedirect("/couldNotCreateNote"); return; } else { mapSessionToUser(requestAndResponse,user.getId()); } } else { user=dbLogic.getUserById(userId); if (user != null && user.getIsAccountClosed()) { user=null; } } if (user == null) { requestAndResponse.response.sendRedirect("/couldNotCreateNote"); return; } else if (user.getIsAccountClosed()) { requestAndResponse.print(servletText.errorAccountIsClosed()); return; } if (!EntryAttributeValidator.isNotebookTitleValid(note)) { returnJson400(requestAndResponse,servletText.errorNoteIsInvalid()); return; } boolean addSampleNote=!doesUserHaveAnyNotebooks(requestAndResponse); final Entry entry=dbLogic.createEntryNoteBook(user,note,time,null,null,false,false,isPublic,isUserAnAdmin(requestAndResponse),addSampleNote,errors); if (entry == null) { requestAndResponse.response.sendRedirect("/couldNotCreateNote"); return; } noteId=entry.getId(); dbLogic.commit(); } catch ( final PersistenceException e) { requestAndResponse.response.sendRedirect("/couldNotCreateNote"); return; } requestAndResponse.response.sendRedirect("/notebook/" + noteId); }
Part of the HTML API. Creates a note and forwards to an url to display it.
public Object runSafely(Catbert.FastStack stack) throws Exception { String profile=getString(stack); return (Permissions.hasPermission(Permissions.PERMISSION_SECURITY,stack.getUIMgr()) && Permissions.removeSecurityProfile(profile)) ? Boolean.TRUE : Boolean.FALSE; }
Removes the security profile with the specified name. You cannot remove the Administrator profile. If a user session is currently active under the profile being removed; it will continue to remain active under that profile with the current permissions until that user session expires.
public Builder userCredentials(String username,String password){ this.userCredentials=new UserCredentials(username,password); return this; }
Sets the default user credentials to be used for operations. If user credentials are not given for an operation, these credentials will be used.
public void modifyParameters(EvolutionState state,ParameterDatabase database,int run,Individual metaIndividual){ if (!(metaIndividual instanceof DoubleVectorIndividual)) state.output.fatal("Meta-individual is not a DoubleVectorIndividual."); DoubleVectorIndividual individual=(DoubleVectorIndividual)metaIndividual; FloatVectorSpecies species=(FloatVectorSpecies)individual.species; double[] genome=individual.genome; Parameter pb=base.push(P_PARAM); for (int i=0; i < genome.length; i++) { Parameter p=pb.push("" + i); String param=state.parameters.getString(p,null); if (param == null) state.output.fatal("Meta parameter number " + i + " missing.",p); database.set(new Parameter(param),"" + map(state,genome,species,i)); } }
Override this method to revise the provided parameter database to reflect the "parameters" specified in the given meta-individual. 'Run' is the current run number for this individual's evaluation.
public ReceiptHeader createReceiptHeaderWithInstrument(String receiptNum,char receiptType,String statusCode,String refNum,InstrumentType instrumentType,String instrumentNum,Double instrumentAmount,Date instrumentDate,String instrumentStatusCode,String glCode,String functionName,String userName) throws NumberFormatException { return createReceiptHeaderWithInstrument(receiptNum,receiptType,statusCode,refNum,instrumentType,instrumentNum,instrumentAmount,instrumentDate,instrumentStatusCode,glCode,functionName,userName,"testCounter"); }
Creates a receipt header along with associated instrument header attached to it
@DSComment("get string associated resolution") @DSSafe(DSCat.SAFE_OTHERS) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:34:56.595 -0500",hash_original_method="A33400D9D27D1859CAE2B97E545C2635",hash_generated_method="42C3E3BCE3653378560C9036E33DF328") public CharSequence loadLabel(PackageManager pm){ if (nonLocalizedLabel != null) { return nonLocalizedLabel; } CharSequence label; if (resolvePackageName != null && labelRes != 0) { label=pm.getText(resolvePackageName,labelRes,null); if (label != null) { return label.toString().trim(); } } ComponentInfo ci=activityInfo != null ? activityInfo : serviceInfo; ApplicationInfo ai=ci.applicationInfo; if (labelRes != 0) { label=pm.getText(ci.packageName,labelRes,ai); if (label != null) { return label.toString().trim(); } } CharSequence data=ci.loadLabel(pm); if (data != null) data=data.toString().trim(); return data; }
Retrieve the current textual label associated with this resolution. This will call back on the given PackageManager to load the label from the application.
public void runTest() throws Throwable { Document doc; NamedNodeMap attributes; Node element; Attr attribute; NodeList elementList; String attrName; doc=(Document)load("staffNS",false); elementList=doc.getElementsByTagNameNS("http://www.nist.gov","address"); element=elementList.item(1); attributes=element.getAttributes(); attribute=(Attr)attributes.getNamedItemNS("http://www.nist.gov","domestic"); attrName=attribute.getNodeName(); assertEquals("namednodemapgetnameditemns02","emp:domestic",attrName); }
Runs the test case.
public void render(int text_fill_type,Graphics2D g2,float scaling,boolean isFormGlyph){ }
draw the glyph
@Override public void onMessage(Message message){ if (ActiveMQRAMessageListener.trace) { ActiveMQRALogger.LOGGER.trace("onMessage(" + message + ")"); } message=consumer.wrapMessage(message); listener.onMessage(message); }
On message
public void upsertDBCredential(DBCredential cred){ if (cred == null) return; if (this.credCache.containsKey(cred.getAppUser() + "||" + cred.getDbGroupName())) this.credCache.remove(cred.getAppUser() + "||" + cred.getDbGroupName()); String sql1="update " + CRED_TABLENAME + " set username=?,credential=?,verified=1 where owner=? and dbgroupname=?"; String sql2="insert into " + CRED_TABLENAME + " (owner,dbgroupname,username,credential,verified) values(?,?,?,?,1)"; String pString=cred.getAppUser() == null ? "NULL" : cred.getAppUser(); pString+="::" + cred.getDbGroupName() + "::"+ cred.getUsername()+ "::"+ cred.getPassword()+ "::"+ Math.random(); Connection conn=null; PreparedStatement pstmt=null; boolean findOne=false; try { conn=getConnection(); findOne=this.retrieveDBCredential(conn,cred.getAppUser(),cred.getDbGroupName()) != null; if (findOne) { pstmt=conn.prepareStatement(sql1); pstmt.setString(1,cred.getUsername()); pstmt.setString(2,keyTool.encrypt(pString)); pstmt.setString(3,cred.getAppUser()); pstmt.setString(4,cred.getDbGroupName().toLowerCase()); pstmt.execute(); conn.commit(); pstmt.close(); pstmt=null; } else { pstmt=conn.prepareStatement(sql2); pstmt.setString(1,cred.getAppUser()); pstmt.setString(2,cred.getDbGroupName().toLowerCase()); pstmt.setString(3,cred.getUsername()); pstmt.setString(4,keyTool.encrypt(pString)); pstmt.execute(); conn.commit(); pstmt.close(); pstmt=null; } } catch ( Exception ex) { if (conn != null) try { conn.rollback(); } catch ( Exception iex) { } throw new RuntimeException(ex); } finally { DBUtils.close(pstmt); DBUtils.close(conn); } }
Store db credential per user/db base
public Wildcards wildcard(Wildcards.Flag... setFlags){ int flags=this.flags; for ( Wildcards.Flag flag : setFlags) flags=flag.wildcard(flags); if (flags == this.flags) return this; else return new Wildcards(flags); }
return a Wildcards object that has the given flags wildcarded <p> <b>NOTE:</b> NOT a mutator function. 'this' wildcard object stays unmodified. </b>
EdgeMap<Block> findLoops(Deque<Block> code,Map<Block,Block> idom,SetMap<Block,Edge> pred){ EdgeMap<Block> loops=new EdgeMap<Block>(); for ( Block b : code) for ( Edge s : b.succ()) if (isLoop(s,idom)) { verboseStatus("backedge " + s); Block h=s.to; Set<Block> loop=loops.get(h); Set<Block> work=new TreeSet<Block>(); for ( Edge p : pred.get(h)) { if (isLoop(p,idom) && !loop.contains(p.from) && p.from != h) { loop.add(p.from); work.add(p.from); } } while (!work.isEmpty()) { Block x=getBlock(work); for ( Edge p : pred.get(x)) { if (p.from != h && !loop.contains(p.from)) { loop.add(p.from); work.add(p.from); } } } } return loops; }
loop code layout the loop is defined by the back edge from T->H. H (header) is the source of the back edge. We want H at the bottom of the loop and T at the top. Lay the blocks out in DFS order starting with T and skipping any blocks that aren't part of the loop. prefer to have fall-through blocks that are part of the loop.
public GridCacheVersion nextForLoad(GridCacheVersion ver){ return next(ver.topologyVersion(),false,true,dataCenterId); }
Gets next version for cache store load and reload operations.
protected List<QoSSentinel> createQoSSentinels(JsonObject qosSettings){ List<QoSSentinel> sentinels=new ArrayList<>(); if (qosSettings.containsKey(JSON_FIELD_SENTINELS)) { JsonObject jsonSentinels=qosSettings.getJsonObject(JSON_FIELD_SENTINELS); for ( String sentinelName : jsonSentinels.fieldNames()) { log.debug("Creating a new QoS sentinel object for metric: " + sentinelName); JsonObject jsonSentinel=jsonSentinels.getJsonObject(sentinelName); QoSSentinel sentinel=new QoSSentinel(sentinelName); QoSSentinel oldSentinel=getOldSentinel(sentinelName); if (oldSentinel != null) { sentinel.setLowestPercentileValue(oldSentinel.getLowestPercentileValue()); } if (jsonSentinel.containsKey("percentile")) { sentinel.setPercentile(jsonSentinel.getInteger("percentile")); } sentinels.add(sentinel); } } return sentinels; }
Creates the QoS sentinel objects from the given JsonObject and returns them in a list.
protected ShoppingCartItemGroup(long groupNumber,String groupName,ShoppingCartItemGroup parentGroup){ this(UtilFormatOut.formatPaddedNumber(groupNumber,2),groupName,parentGroup); }
Note that to avoid foreign key issues when the groups are created a parentGroup should have a lower number than the child group.
protected void doFloodBDDP(DatapathId pinSwitch,OFPacketIn pi,FloodlightContext cntx){ TopologyInstance ti=getCurrentInstance(false); Set<DatapathId> switches=ti.getSwitchesInOpenflowDomain(pinSwitch); if (switches == null) { switches=new HashSet<DatapathId>(); switches.add(pinSwitch); } for ( DatapathId sid : switches) { IOFSwitch sw=switchService.getSwitch(sid); if (sw == null) continue; Collection<OFPort> enabledPorts=sw.getEnabledPortNumbers(); if (enabledPorts == null) continue; Set<OFPort> ports=new HashSet<OFPort>(); ports.addAll(enabledPorts); Set<OFPort> portsKnownToTopo=ti.getPortsWithLinks(sid); if (portsKnownToTopo != null) { for ( OFPort p : portsKnownToTopo) { NodePortTuple npt=new NodePortTuple(sid,p); if (ti.isBroadcastDomainPort(npt) == false) { ports.remove(p); } } } Set<OFPort> portsToEliminate=getPortsToEliminateForBDDP(sid); if (portsToEliminate != null) { ports.removeAll(portsToEliminate); } if (pinSwitch == sid) { ports.remove((pi.getVersion().compareTo(OFVersion.OF_12) < 0 ? pi.getInPort() : pi.getMatch().get(MatchField.IN_PORT))); } doMultiActionPacketOut(pi.getData(),sw,ports,cntx); } }
The BDDP packets are forwarded out of all the ports out of an openflowdomain. Get all the switches in the same openflow domain as the sw (disabling tunnels). Then get all the external switch ports and send these packets out.
public boolean processAgentEvent(Event e){ ((DistAnalysisTrip)this.trips.getFirst()).processAgentEvent(e); return ((DistAnalysisTrip)this.trips.getFirst()).isFinished(); }
returns true true if the trip is finished
public ResourceNode(String nodeName,Object object,String eTag){ this(nodeName,object,eTag,""); }
Creates an instance of a ResourceNode.
private static boolean rectEquals(Rect r,int left,int top,int right,int bottom){ return !(r.left != left || r.top != top || r.right != right || r.bottom != bottom); }
Check if a rect edges are equal to changed values
public RecordBuffer<R> remove(int... itemsToRemoveSorted){ return remove(Ints.asList(itemsToRemoveSorted)); }
Removes the records at the specified indices.
public void stepCompleted(StepEvent event){ synchronized (sync) { nSteps++; } println("Got StepEvent " + nSteps + " at line "+ event.location().method()+ ":"+ event.location().lineNumber()); if (nSteps == 1) { timerThread.start(); } }
event handlers
public boolean addAll(Collection<? extends E> c){ hashCodeUpToDate=false; Object[] a=c.toArray(); int numNew=a.length; ensureCapacityInternal(size + numNew); System.arraycopy(a,0,elementData,size,numNew); size+=numNew; return numNew != 0; }
Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's Iterator. The behavior of this operation is undefined if the specified collection is modified while the operation is in progress. (This implies that the behavior of this call is undefined if the specified collection is this list, and this list is nonempty.)
public NotificationChain basicSetTitle(TagTitle newTitle,NotificationChain msgs){ TagTitle oldTitle=title; title=newTitle; if (eNotificationRequired()) { ENotificationImpl notification=new ENotificationImpl(this,Notification.SET,DomPackage.INLINE_TAG__TITLE,oldTitle,newTitle); if (msgs == null) msgs=notification; else msgs.add(notification); } return msgs; }
<!-- begin-user-doc --> <!-- end-user-doc -->
public void init(ModeledAuthenticatedUser currentUser,ActiveConnectionRecord activeConnectionRecord,boolean includeSensitiveInformation){ super.init(currentUser); this.connectionRecord=activeConnectionRecord; this.connection=activeConnectionRecord.getConnection(); this.sharingProfileIdentifier=activeConnectionRecord.getSharingProfileIdentifier(); this.identifier=activeConnectionRecord.getUUID().toString(); this.startDate=activeConnectionRecord.getStartDate(); if (includeSensitiveInformation) { this.remoteHost=activeConnectionRecord.getRemoteHost(); this.tunnel=activeConnectionRecord.getTunnel(); this.username=activeConnectionRecord.getUsername(); } }
Initializes this TrackedActiveConnection, copying the data associated with the given active connection record. At a minimum, the identifier of this active connection will be set, the start date, and the identifier of the associated connection will be copied. If requested, sensitive information like the associated username will be copied, as well.
public Vertex discover(Vertex source,Vertex vertex,Vertex vertex2,Vertex vertex3,Vertex vertex4,Vertex vertex5){ return discover(true,true,null,vertex,vertex2,vertex3,vertex4,vertex5); }
Discover the meaning of the word. Called from Self.
public FinnishLightStemFilterFactory(Map<String,String> args){ super(args); if (!args.isEmpty()) { throw new IllegalArgumentException("Unknown parameters: " + args); } }
Creates a new FinnishLightStemFilterFactory
public void unsetParamValue(){ this.paramValue=null; }
Description: <br>
protected void update(boolean applyConstraints){ Vec3D delta=b.sub(a); float dist=delta.magnitude() + EPS; float normDistStrength=(dist - restLength) / (dist * (a.invWeight + b.invWeight)) * strength; if (!a.isLocked && !isALocked) { a.addSelf(delta.scale(normDistStrength * a.invWeight)); if (applyConstraints) { a.applyConstraints(); } } if (!b.isLocked && !isBLocked) { b.addSelf(delta.scale(-normDistStrength * b.invWeight)); if (applyConstraints) { b.applyConstraints(); } } }
Updates both particle positions (if not locked) based on their current distance, weight and spring configuration
@Override @CallSuper public void onActionStateChanged(int position,int actionState){ mActionState=actionState; alreadySelected=mAdapter.isSelected(position); if (FlexibleAdapter.DEBUG) Log.v(TAG,"onActionStateChanged position=" + position + " mode="+ mAdapter.getMode()+ " actionState="+ (actionState == ItemTouchHelper.ACTION_STATE_SWIPE ? "Swipe(1)" : "Drag(2)")); if (actionState == ItemTouchHelper.ACTION_STATE_DRAG) { if (!alreadySelected) { if (mLongClickSkipped || mAdapter.getMode() == SelectableAdapter.MODE_MULTI) { if ((shouldAddSelectionInActionMode() || mAdapter.getMode() != SelectableAdapter.MODE_MULTI) && mAdapter.mItemLongClickListener != null && mAdapter.isSelectable(position)) { mAdapter.mItemLongClickListener.onItemLongClick(position); alreadySelected=true; } } if (!alreadySelected) { mAdapter.toggleSelection(position); } } if (!itemView.isActivated()) { toggleActivation(); } } else if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE && shouldActivateViewWhileSwiping() && !alreadySelected) { mAdapter.toggleSelection(position); toggleActivation(); } }
Here we handle the event of when the ItemTouchHelper first registers an item as being moved or swiped. <p>In this implementations, View activation is automatically handled in case of Drag: The Item will be added to the selection list if not selected yet and mode MULTI is activated.</p>
@Override protected void shutdownInput() throws IOException { shutdownInput=true; try { Libcore.os.shutdown(fd,SHUT_RD); } catch ( ErrnoException errnoException) { throw errnoException.rethrowAsSocketException(); } }
Shutdown the input portion of the socket.
public RainbowTest(String name){ super(name); }
Constructs the test.
public void addChangingListener(OnWheelChangedListener listener){ changingListeners.add(listener); }
Adds wheel changing listener
@Override public void updateBinaryStream(int columnIndex,InputStream x,int length) throws SQLException { updateBinaryStream(columnIndex,x,(long)length); }
Updates a column in the current or insert row.
public static boolean endsWithIgnoreCase(String src,String subS){ String sub=subS.toLowerCase(); int sublen=sub.length(); int j=0; int i=src.length() - sublen; if (i < 0) { return false; } while (j < sublen) { char source=Character.toLowerCase(src.charAt(i)); if (sub.charAt(j) != source) { return false; } j++; i++; } return true; }
Tests if this string ends with the specified suffix.
public void testSerialization() throws Exception { DoubleAdder x=new DoubleAdder(); DoubleAdder y=serialClone(x); assertNotSame(x,y); x.add(-22.0); DoubleAdder z=serialClone(x); assertEquals(-22.0,x.sum()); assertEquals(0.0,y.sum()); assertEquals(-22.0,z.sum()); }
a deserialized serialized adder holds same value
public static void main(final String[] args){ DOMTestCase.doMain(localName01.class,args); }
Runs this test from the command line.
public static BufferedImage createColorModelCompatibleImage(BufferedImage image){ ColorModel cm=image.getColorModel(); return new BufferedImage(cm,cm.createCompatibleWritableRaster(image.getWidth(),image.getHeight()),cm.isAlphaPremultiplied(),null); }
<p>Returns a new <code>BufferedImage</code> using the same color model as the image passed as a parameter. The returned image is only compatible with the image passed as a parameter. This does not mean the returned image is compatible with the hardware.</p>
public Object key(){ int dr=+1; int dc=+1; int offRL=+1; int offRH=+2; int offCL=+1; int offCH=+2; boolean rFirst=true; int d=board[0][0]; if (board[0][MaxC] < d) { dr=+1; dc=-1; offCL=2; offCH=1; d=board[0][MaxC]; rFirst=false; } if (board[MaxR][MaxC] < d) { dr=-1; dc=-1; offCL=2; offCH=1; offRL=2; offRH=1; d=board[MaxR][MaxC]; rFirst=true; } if (board[MaxR][0] < d) { dr=-1; dc=+1; offRL=2; offRH=1; d=board[MaxR][0]; rFirst=false; } StringBuilder sb=new StringBuilder(10); if (rFirst) { for (int r=-dr + offRL; dr * r <= dr + offRH; r+=dr) { for (int c=-dc + offCL; dc * c <= dc + offCH; c+=dc) { sb.append(board[r][c]); } } } else { for (int c=-dc + offCL; dc * c <= dc + offCH; c+=dc) { for (int r=-dr + offRL; dr * r <= dr + offRH; r+=dr) { sb.append(board[r][c]); } } } return sb.toString(); }
Return key that satisfies rotational symmetry. Considering the four corners of the board, select the lowest digit and then read off the remaining eight positions in a fixed order as an integer. Return that value.
public static String seconds2HH_mm_ss(long seconds){ long h=0; long m=0; long s=0; long temp=seconds % 3600; if (seconds > 3600) { h=seconds / 3600; if (temp != 0) { if (temp > 60) { m=temp / 60; if (temp % 60 != 0) { s=temp % 60; } } else { s=temp; } } } else { m=seconds / 60; if (seconds % 60 != 0) { s=seconds % 60; } } String dh=h < 10 ? "0" + h : h + ""; String dm=m < 10 ? "0" + m : m + ""; String ds=s < 10 ? "0" + s : s + ""; return dh + ":" + dm+ ":"+ ds; }
format seconds to HH:mm:ss String
private void processIcons(SolrInputDocument doc,boolean allAttr,Collection<IconEntry> icons){ processIcons(doc,allAttr,null,null,icons); }
Add icons metadata to Solr doc when corresponding schema attributes are enabled.
public void changeWindowsConfig(String value){ WebElement windowsConfigButton=driver.findElement(By.xpath((uiElementMapper.getElement("emm.configuration.widows.tab.identifier")))); WebElement inputWindowsConfig=driver.findElement(By.xpath((uiElementMapper.getElement("emm.configuration.windows.input.identifier")))); WebElement buttonSaveConfig=driver.findElement(By.xpath((uiElementMapper.getElement("emm.configuration.windows.button.save.identifier")))); windowsConfigButton.click(); inputWindowsConfig.sendKeys(value); buttonSaveConfig.click(); }
This page imitates the windows configuration changing scenario.
protected URLConnection openConnection(URL url) throws IOException { URLConnection conn=url.openConnection(); conn.setDoOutput(true); if (_basicAuth != null) conn.setRequestProperty("Authorization",_basicAuth); else if (_user != null && _password != null) { _basicAuth="Basic " + base64(_user + ":" + _password); conn.setRequestProperty("Authorization",_basicAuth); } return conn; }
Creates the URL connection.
public DirectReplyProcessor(DM dm,InternalDistributedMember member){ this(dm,Collections.singleton(member)); }
Creates a new <code>ReplyProcessor</code> that wants replies from a single member of a distributed system.
private DigestValue resolveValue(AbstractValueType value,HashChainType currentChain) throws Exception { LOG.trace("resolveValue({})",value); if (value instanceof DataRefType) { return resolveDataRef((DataRefType)value,currentChain); } else if (value instanceof StepRefType) { return resolveStepRef((StepRefType)value,currentChain); } else if (value instanceof HashValueType) { return resolveHashValue((HashValueType)value,currentChain); } else { throw new IllegalArgumentException("Unknown value type"); } }
Calculates digest of the value in a hash step.
@Override public void visitTypeParameter(JCTypeParameter tree){ TypeVar a=(tree.type != null) ? (TypeVar)tree.type : new TypeVar(tree.name,env.info.scope.owner,syms.botType); tree.type=a; if (chk.checkUnique(tree.pos(),a.tsym,env.info.scope)) { env.info.scope.enter(a.tsym); } result=a; }
Class enter visitor method for type parameters. Enter a symbol for type parameter in local scope, after checking that it is unique.
protected BaseVO(long key,int version){ this.key=key; this.version=version; }
Constructs a value object with the given key and version.
@Override public boolean needsMaterialization(){ return false; }
Does not need materialization to answer BNode interface methods.
public File outputRamlToFile(String path,Boolean createPathIfMissing,Boolean removeOldOutput) throws FileNotFoundException { if (this.raml == null) { return null; } FileOutputStream fos=null; File file=getRamlOutputFile(path); try { prepareDirectories(file,createPathIfMissing,removeOldOutput); logger.info("Saving generated raml to " + file.getAbsolutePath()); fos=new FileOutputStream(file); fos.write(outputRamlToString().getBytes()); fos.flush(); } catch ( FileNotFoundException e) { logger.error("Could not save raml - directory enclosing " + file.getAbsolutePath() + " does not exist",e); throw e; } catch ( IOException e) { logger.error(e.getMessage(),e); } finally { if (fos != null) { try { fos.close(); } catch ( IOException e) { logger.error(e.getMessage(),e); } } } return file; }
Emits the RAML model into its string representation and saves it as a file in the specified path
public InstanceExistsException(List<LocalizedText> messages){ super(messages); }
Constructs a new exception with the specified localized text messages. The cause is not initialized.
@Override public boolean supportsDb(String type){ return true; }
No database tables used, so all supported
private void verifyPasswordStrength(){ if (isEnabled() && !constraints.isEmpty() && !TextUtils.isEmpty(getText())) { float score=getPasswordStrength(); adaptHelperText(score); } else { setHelperText(regularHelperText); } }
Verifies the strength of the current password, depending on the constraints, which have been added and adapts the appearance of the view accordingly.
public DTMAxisIterator includeSelf(){ _includeSelf=true; return this; }
Set the flag to include the start node in the iteration.
public GPIndividual map(EvolutionState state,GEIndividual ind,int threadnum,HashMap ercMapsForFancyPrint){ GPIndividual newind=((GPIndividual)(gpspecies.i_prototype)).lightClone(); newind.fitness=ind.fitness; newind.evaluated=false; newind.species=gpspecies; if (makeTrees(state,ind,newind.trees,threadnum,ercMapsForFancyPrint) < 0) return null; else return newind; }
Returns a dummy GPIndividual with a single tree which was built by mapping over the elements of the given GEIndividual. Null is returned if an error occurs, specifically, if all elements were consumed and the tree had still not been completed. If you pass in a non-null HashMap for ercMapsForFancyPrint, then ercMapsForFancyPrint will be loaded with key->ERCvalue pairs of ERC mappings used in this map.
public static boolean checkContentCanBePulledDown(PtrFrameLayout frame,View content,View header){ return !canChildScrollUp(content); }
Default implement for check can perform pull to refresh
public void addTransaction(Transaction t){ addTransaction(t,true); }
Adds a transaction to this block. The nonce and merkle root are invalid after this.
public EnvironmentMap(HashMap global){ _global=global; }
Creates a new environment map.
public CActionAutomaticLayouting(final ZyGraph graph){ super("Automatic Layouting"); m_graph=Preconditions.checkNotNull(graph,"IE02809: graph argument can not be null"); putValue(ACCELERATOR_KEY,HotKeys.GRAPH_AUTOMATIC_LAYOUT_HK.getKeyStroke()); }
Creates a new action object.
private void saveDebugger(){ try { m_addressSpace.getConfiguration().setDebuggerTemplate(m_debuggerCombo.getSelectedDebugger()); } catch ( final CouldntSaveDataException e) { CUtilityFunctions.logException(e); final String innerMessage="E00155: " + "Could not save address space debugger"; final String innerDescription=CUtilityFunctions.createDescription(String.format("The new debugger of the address space '%s' could not be saved.",m_addressSpace.getConfiguration().getName()),new String[]{"There was a problem with the database connection."},new String[]{"The address space keeps its old debugger."}); NaviErrorDialog.show(SwingUtilities.getWindowAncestor(this),innerMessage,innerDescription,e); } }
Saves the configured address space debugger to the database.
public final void testIsStatePreserved2(){ byte[] encodedKey=new byte[]{(byte)1,(byte)2,(byte)3,(byte)4}; EncodedKeySpec meks=new MyEncodedKeySpec(encodedKey); byte[] ek=meks.getEncoded(); ek[3]=(byte)5; byte[] ek1=meks.getEncoded(); assertTrue(ek1[3] == (byte)4); }
Tests that internal state of the object can not be modified using returned value of <code>getEncoded()</code> method
@Override protected void readProcess() throws IOException, InterruptedException { if (log.isInfoEnabled()) log.info("begin"); for (int i=0; i < 10 && !getActiveProcess().isAlive(); i++) { if (log.isInfoEnabled()) log.info("waiting for the readerFuture to be set."); Thread.sleep(100); } if (log.isInfoEnabled()) log.info("running"); final String banner=readLine(); if (log.isInfoEnabled()) log.info("banner: " + banner); long n=0; while (true) { final String blank=readLine(); assert blank.trim().length() == 0 : "Expecting a blank line"; final String header=readLine(); final String data=readLine(); try { lastModified.set(System.currentTimeMillis()); final Map<String,String> fields=SysstatUtil.getDataMap(header,data); if (log.isInfoEnabled()) { StringBuilder sb=new StringBuilder(); for ( Map.Entry<String,String> e : fields.entrySet()) { sb.append(e.getKey()); sb.append("="); sb.append(e.getValue()); sb.append(", "); } log.info(sb.toString()); log.info(header + ";" + data); } if (fields.containsKey(PIDSTAT_FIELD_CPU_PERCENT)) { vals.put(IProcessCounters.CPU_PercentUserTime,Double.parseDouble(fields.get(PIDSTAT_FIELD_CPU_PERCENT_USR))); vals.put(IProcessCounters.CPU_PercentSystemTime,Double.parseDouble(fields.get(PIDSTAT_FIELD_CPU_PERCENT_SYSTEM))); vals.put(IProcessCounters.CPU_PercentProcessorTime,Double.parseDouble(fields.get(PIDSTAT_FIELD_CPU_PERCENT))); } else if (fields.containsKey("RSS")) { vals.put(IProcessCounters.Memory_minorFaultsPerSec,Double.parseDouble(fields.get(PIDSTAT_FIELD_MEM_MINOR_FAULTS_PERS))); vals.put(IProcessCounters.Memory_majorFaultsPerSec,Double.parseDouble(fields.get(PIDSTAT_FIELD_MEM_MAJOR_FAULTS_PERS))); vals.put(IProcessCounters.Memory_virtualSize,Long.parseLong(fields.get(PIDSTAT_FIELD_MEM_VIRTUAL_SIZE))); vals.put(IProcessCounters.Memory_residentSetSize,Long.parseLong(fields.get(PIDSTAT_FIELD_MEM_RESIDENT_SET_SIZE))); vals.put(IProcessCounters.Memory_percentMemorySize,Double.parseDouble(fields.get(PIDSTAT_FIELD_MEM_SIZE_PERCENT))); } else if (perProcessIOData && header.contains("kB_rd/s")) { vals.put(IProcessCounters.PhysicalDisk_BytesReadPerSec,Double.parseDouble(fields.get(PIDSTAT_FIELD_DISK_KB_READ_PERS))); vals.put(IProcessCounters.PhysicalDisk_BytesWrittenPerSec,Double.parseDouble(fields.get(PIDSTAT_FIELD_DISK_KB_WRITTEN_PERS))); } else { log.warn("Could not identify event type from header: [" + header + "]"); continue; } } catch ( Exception ex) { log.warn(ex.getMessage() + "\nheader: " + header+ "\n data: "+ data); } n++; } }
The input arrives as an initial banner and a sequence of data reporting events, each of which is three lines. The first line is blank. The second line gives the headers for the event. The third line gives the data for the event. The 2nd and 3rd lines carry a timestamp as the first value. <p> When you request more than one kind of reporting, the three line set simply repeats for each class of events that are to be reported. E.g., cpu and io. This code diagnoses the event types by examining the header line.
public static void main(String... a) throws Exception { TestBase.createCaller().init().test(); }
Run just this test.
public StringElement addElement(String hashcode,Element element){ addElementToRegistry(hashcode,element); return (this); }
Adds an Element to the element.
@Override public NotificationChain eInverseRemove(InternalEObject otherEnd,int featureID,NotificationChain msgs){ switch (featureID) { case N4JSPackage.CATCH_BLOCK__CATCH_VARIABLE: return basicSetCatchVariable(null,msgs); } return super.eInverseRemove(otherEnd,featureID,msgs); }
<!-- begin-user-doc --> <!-- end-user-doc -->
public Object put(Object key,Object value){ internalPut((CompositeData)value); return value; }
This method simply calls <tt>put((CompositeData) value)</tt> and therefore ignores its <var>key</var> parameter which can be <tt>null</tt>.
public ColorRGBA(Scalar scalar){ super(scalar); }
Instantiate a 3- or 4-channel RGB(A) color from a Scalar value
protected double kernelHelper2(int n,char[] s,int endIndexS,char[] t,int endIndexT){ if (endIndexS < 0 || endIndexT < 0) { return getReturnValue(n); } int adr=0; if (m_useRecursionCache) { adr=m_multX * n + m_multY * endIndexS + m_multZ * endIndexT; if (cachekh2K[adr % maxCache] == adr + 1) { return cachekh2[adr % maxCache]; } } char x=s[endIndexS]; if (x == t[endIndexT]) { double ret=m_lambda * (kernelHelper2(n,s,endIndexS,t,endIndexT - 1) + m_lambda * kernelHelper(n - 1,s,endIndexS - 1,t,endIndexT - 1)); if (m_useRecursionCache) { cachekh2K[adr % maxCache]=adr + 1; cachekh2[adr % maxCache]=ret; } return ret; } else { double ret=m_lambda * kernelHelper2(n,s,endIndexS,t,endIndexT - 1); if (m_useRecursionCache) { cachekh2K[adr % maxCache]=adr + 1; cachekh2[adr % maxCache]=ret; } return ret; } }
helper function for the evaluation of the kernel K'' see section 'Efficient Computation of SSK' in [1]
public static SailRepository createRepository(final Properties props,final String file,final Option... args){ return new SailRepository(createSail(props,file,args)); }
Create a new bigdata instance using the specified options. Since no journal file is specified this must be an in-memory instance.
public static View createView(final Module module,final List<ReilInstruction> instructions){ Preconditions.checkNotNull(module,"Error: Module argument can not be null"); Preconditions.checkNotNull(instructions,"Error: Instructions argument can not be null"); final INaviView view=CReilViewCreator.create(module.getNative(),convert(instructions)); return ObjectFinders.getObject(view,module.getViews()); }
Creates a new REIL view from a list of REIL instructions.
private void updateProgress(int progress){ if (myHost != null && progress != previousProgress) { myHost.updateProgress(progress); } previousProgress=progress; }
Used to communicate a progress update between a plugin tool and the main Whitebox user interface.
void beginScratchInterval(Register r,Instruction begin){ if (DEBUG) { System.out.println("beginScratchInterval " + r + " "+ regAllocState.getDFN(begin)); } PhysicalInterval p=new PhysicalInterval(r); p.begin=begin; ArrayList<Interval> v=findOrCreateIntervalSet(r); v.add(p); pending.put(r,p); }
Begin a new interval of scratch-ness for a physical register.
public void resetLabels(){ AbstractInsnNode insn=first; while (insn != null) { if (insn instanceof LabelNode) { ((LabelNode)insn).resetLabel(); } insn=insn.next; } }
Reset all labels in the instruction list. This method should be called before reusing same instructions list between several <code>ClassWriter</code>s.
private void revalidateAttributePanels(){ int pages=model.getNumberOfPages(); Vector<Integer> pagesVector=new Vector<>(); for (int j=1; j <= pages; j++) { pagesVector.add(j); } if (pagesComboBox.getSelectedItem() != null) { pagesComboBox.setModel(new DefaultComboBoxModel<>(pagesVector)); pagesComboBox.removeItemListener(pageComboListener); pagesComboBox.setSelectedItem(model.getCurrentPageIndex() + 1); pagesComboBox.addItemListener(pageComboListener); } else { pagesComboBox.setModel(new DefaultComboBoxModel<>(pagesVector)); } updatePagingDisplay(); int index=0; List<AbstractAttributeStatisticsModel> orderedList=controller.getPagedAndVisibleAttributeStatisticsModels(); for ( AbstractAttributeStatisticsModel statModel : orderedList) { mapOfAttributeStatisticsPanels.get(index++).setModel(statModel,true); } int i=0; for ( AbstractAttributeStatisticsModel statModel : orderedList) { mapOfAttributeStatisticsPanels.get(i).setVisible(true); statModel.setAlternating(i % 2 == 1); i++; } for (; i < Math.min(model.getTotalSize(),MetaDataStatisticsModel.PAGE_SIZE); i++) { mapOfAttributeStatisticsPanels.get(i).setVisible(false); } if (model.getVisibleSize() == 0 && model.isFiltering()) { labelNoAttributes.setVisible(true); } else { labelNoAttributes.setVisible(false); } for ( AttributeStatisticsPanel asp : mapOfAttributeStatisticsPanels.values()) { asp.updateNameColumnWidth(nameDim); } revalidate(); repaint(); }
Reorders the attribute panels according to the current sorting and respect filtering.
@PluginFactory public static ConsoleAppender createAppender(@PluginElement("Layout") Layout<? extends Serializable> layout,@PluginElement("Filters") final Filter filter,@PluginAttribute("target") final String t,@PluginAttribute("name") final String name,@PluginAttribute("follow") final String follow,@PluginAttribute("ignoreExceptions") final String ignore){ if (name == null) { LOGGER.error("No name provided for ConsoleAppender"); return null; } if (layout == null) { layout=PatternLayout.createLayout(null,null,null,null,null); } final boolean isFollow=Boolean.parseBoolean(follow); final boolean ignoreExceptions=Booleans.parseBoolean(ignore,true); final Target target=t == null ? Target.SYSTEM_OUT : Target.valueOf(t); return new ConsoleAppender(name,layout,filter,getManager(isFollow,target,layout),ignoreExceptions); }
Create a Console Appender.
public TableDefinition(Session s,String tablename,String[] fieldname,String[] fieldtran,Datas[] fielddata,Formats[] fieldformat,int[] idinx){ this(s,tablename,fieldname,fieldtran,fielddata,fieldformat,idinx,null); }
Creates a new instance of TableDefinition
private Object _deserialize(Element element) throws ConverterException { String nodeName=element.getNodeName().toLowerCase(); if (nodeName.equals("null")) { return null; } else if (nodeName.equals("string")) { return _deserializeString(element); } else if (nodeName.equals("number")) { try { Node data=element.getFirstChild(); if (data == null) return new Double(0); return Caster.toDouble(data.getNodeValue()); } catch ( Exception e) { throw toConverterException(e); } } else if (nodeName.equals("boolean")) { try { return Caster.toBoolean(element.getAttribute("value")); } catch ( PageException e) { throw toConverterException(e); } } else if (nodeName.equals("array")) { return _deserializeArray(element); } else if (nodeName.equals("component") || nodeName.equals("class")) { return _deserializeComponent(element); } else if (nodeName.equals("struct")) { return _deserializeStruct(element); } else if (nodeName.equals("recordset")) { return _deserializeQuery(element); } else if (nodeName.equalsIgnoreCase("dateTime")) { try { return DateCaster.toDateAdvanced(element.getFirstChild().getNodeValue(),timeZone); } catch ( Exception e) { throw toConverterException(e); } } else if (nodeName.equals("binary")) { return _deserializeBinary(element); } else throw new ConverterException("can't deserialize Element of type [" + nodeName + "] to a Object representation"); }
deserialize a WDDX Package (XML Element) to a runtime object
private static byte[] generateSeed(){ try { ByteArrayOutputStream seedBuffer=new ByteArrayOutputStream(); DataOutputStream seedBufferOut=new DataOutputStream(seedBuffer); seedBufferOut.writeLong(System.currentTimeMillis()); seedBufferOut.writeLong(System.nanoTime()); seedBufferOut.writeInt(Process.myPid()); seedBufferOut.writeInt(Process.myUid()); seedBufferOut.write(BUILD_FINGERPRINT_AND_DEVICE_SERIAL); seedBufferOut.close(); return seedBuffer.toByteArray(); } catch ( IOException e) { throw new SecurityException("Failed to generate seed",e); } }
Generates a device- and invocation-specific seed to be mixed into the Linux PRNG.
public SpeakerNPC(final String name){ baseSpeed=0.2; createPath(); lastMessageTurn=0; setName(name); createDialog(); createDefaultReplies(); put("title_type","npc"); setSize(1,1); setPerceptionRange(5); updateModifiedAttributes(); }
Creates a new SpeakerNPC.
public static InputStream post(URL url,String name1,Object value1) throws IOException { return new ClientHttpRequest(url).post(name1,value1); }
post the POST request specified URL, with the specified parameter
public static boolean dirExists(File dir){ long start=System.currentTimeMillis(); while (System.currentTimeMillis() - start < MS_RETRY) { File refreshed=Errors.rethrow().get(null); if (refreshed.exists() && refreshed.isDirectory()) { return true; } else { Errors.rethrow().run(null); } } return false; }
Returns true if the given directory exists, and waits up to 500ms for the directory to exist.
public void addRoleName(String roleName){ if (roleNames == null) { roleNames=New.arrayList(); } roleNames.add(roleName); }
Add the specified role to the list of roles.
public void parse(InputStream is){ setPasswordMap(parseRulesFile(is)); }
Initialize rules through file input stream. This is a convenience for first calling setPasswordMap(parseRulesFile(is)).
public CSVParser(){ this(DEFAULT_SEPARATOR,DEFAULT_QUOTE_CHARACTER,DEFAULT_ESCAPE_CHARACTER); }
Constructs CSVParser using a comma for the separator.
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.