code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
private Instruction do_store(int index,Operand op1){
TypeReference type=op1.getType();
boolean Dual=(type.isLongType() || type.isDoubleType());
if (LOCALS_ON_STACK) {
replaceLocalsOnStack(index,type);
}
if (ELIM_COPY_LOCALS) {
if (op1 instanceof RegisterOperand) {
RegisterOperand rop1=(RegisterOperand)op1;
Register r1=rop1.getRegister();
if (lastInstr != null && ResultCarrier.conforms(lastInstr) && ResultCarrier.hasResult(lastInstr) && !r1.isLocal() && r1 == ResultCarrier.getResult(lastInstr).getRegister()) {
if (DBG_ELIMCOPY) db("eliminated copy " + op1 + " to"+ index);
RegisterOperand newop0=gc.makeLocal(index,rop1);
ResultCarrier.setResult(lastInstr,newop0);
if (Dual) {
setLocalDual(index,newop0);
}
else {
setLocal(index,newop0);
}
gc.getTemps().release(rop1);
return null;
}
}
}
RegisterOperand op0=(op1 instanceof RegisterOperand) ? gc.makeLocal(index,(RegisterOperand)op1) : gc.makeLocal(index,type);
Operand set=op0;
if (CP_IN_LOCALS) {
set=(op1 instanceof RegisterOperand) ? op0 : op1;
}
if (Dual) {
setLocalDual(index,set);
}
else {
setLocal(index,set);
}
Instruction s=Move.create(IRTools.getMoveOp(type),op0,op1);
setSourcePosition(s);
return s;
}
| Simulates a store into a given local variable of an int/long/double/float |
public void addInitiatorsUsingREST(StorageSystem storage,URI exportMaskURI,List<URI> volumeURIs,List<Initiator> initiatorList,TaskCompleter taskCompleter){
try {
ExportMask mask=_dbClient.queryObject(ExportMask.class,exportMaskURI);
XIVRestClient restExportOpr=getRestClient(storage);
final String storageIP=storage.getSmisProviderIP();
List<Initiator> userAddedInitiators=new ArrayList<Initiator>();
for ( Initiator initiator : initiatorList) {
final Host host=_dbClient.queryObject(Host.class,initiator.getHost());
if (!restExportOpr.createHostPort(storageIP,host.getLabel(),Initiator.normalizePort(initiator.getInitiatorPort()),initiator.getProtocol().toLowerCase())) {
userAddedInitiators.add(initiator);
}
}
mask.addToUserCreatedInitiators(userAddedInitiators);
ExportMaskUtils.sanitizeExportMaskContainers(_dbClient,mask);
_dbClient.updateObject(mask);
taskCompleter.ready(_dbClient);
}
catch ( Exception e) {
_log.error("Unexpected error: addInitiator failed.",e);
ServiceError error=XIVRestException.exceptions.methodFailed("addInitiator",e);
taskCompleter.error(_dbClient,error);
}
}
| Add Initiators to an existing Export Mask. |
public void findAndUndo(Object someObj){
if (someObj instanceof MouseDelegator) {
Debug.message("mousemodepanel","MouseModePanel removing MouseDelegator.");
if (someObj == getMouseDelegator()) {
setMouseDelegator(null);
}
}
}
| BeanContextMembershipListener method. Called when an object has been removed from the parent BeanContext. |
public Matrix copy(){
Matrix X=new Matrix(m,n);
double[][] C=X.getArray();
for (int i=0; i < m; i++) {
for (int j=0; j < n; j++) {
C[i][j]=A[i][j];
}
}
return X;
}
| Make a deep copy of a matrix |
@Override protected EClass eStaticClass(){
return GamlPackage.Literals.SEXPERIMENT;
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public static void createImageToStorage(String url,Label l,String cacheId,Image placeholder,byte priority){
createImageToStorage(url,l,cacheId,false,null,priority,placeholder,defaultMaintainAspectRatio);
}
| Constructs an image request that will automatically populate the given Label when the response arrives, it will cache the file locally to the Storage |
public static Number next(Number self){
return NumberNumberPlus.plus(self,ONE);
}
| Increment a Number by one. |
public int read(byte[] buf,int off,int len) throws TTransportException {
if (inputStream_ == null) {
throw new TTransportException(TTransportException.NOT_OPEN,"Cannot read from null inputStream");
}
int bytesRead;
try {
bytesRead=inputStream_.read(buf,off,len);
}
catch ( IOException iox) {
throw new TTransportException(TTransportException.UNKNOWN,iox);
}
if (bytesRead < 0) {
throw new TTransportException(TTransportException.END_OF_FILE);
}
return bytesRead;
}
| Reads from the underlying input stream if not null. |
public void actionPerformed(ActionEvent e){
if (e.getSource() == mRefresh) {
m_goal.updateGoal(true);
updateDisplay();
Container parent=getParent();
if (parent != null) parent.invalidate();
invalidate();
if (parent != null) parent.repaint();
else repaint();
}
}
| Action Listener. Update Display |
@SuppressWarnings("deprecation") static HttpUriRequest createHttpRequest(Request<?> request,Map<String,String> additionalHeaders) throws AuthFailureError, IOException {
switch (request.getMethod()) {
case Method.DEPRECATED_GET_OR_POST:
{
byte[] postBody=request.getPostBody();
if (postBody != null) {
HttpPost postRequest=new HttpPost(request.getUrl());
postRequest.addHeader(HEADER_CONTENT_TYPE,request.getPostBodyContentType());
HttpEntity entity;
entity=new ByteArrayEntity(postBody);
postRequest.setEntity(entity);
return postRequest;
}
else {
return new HttpGet(request.getUrl());
}
}
case Method.GET:
return new HttpGet(request.getUrl());
case Method.DELETE:
return new HttpDelete(request.getUrl());
case Method.POST:
{
HttpPost postRequest=new HttpPost(request.getUrl());
setEntityIfNonEmptyBody(postRequest,request);
return postRequest;
}
case Method.PUT:
{
HttpPut putRequest=new HttpPut(request.getUrl());
putRequest.addHeader(HEADER_CONTENT_TYPE,request.getBodyContentType());
setEntityIfNonEmptyBody(putRequest,request);
return putRequest;
}
case Method.HEAD:
return new HttpHead(request.getUrl());
case Method.OPTIONS:
return new HttpOptions(request.getUrl());
case Method.TRACE:
return new HttpTrace(request.getUrl());
case Method.PATCH:
{
HttpPatch patchRequest=new HttpPatch(request.getUrl());
setEntityIfNonEmptyBody(patchRequest,request);
return patchRequest;
}
default :
throw new IllegalStateException("Unknown request method.");
}
}
| Creates the appropriate subclass of HttpUriRequest for passed in request. |
public static long capacityRemainingBackward(GenericValue techDataCalendar,Timestamp dateFrom){
GenericValue techDataCalendarWeek=null;
try {
techDataCalendarWeek=techDataCalendar.getRelatedOne("TechDataCalendarWeek",true);
}
catch ( GenericEntityException e) {
Debug.logError("Pb reading Calendar Week associated with calendar" + e.getMessage(),module);
return 0;
}
Calendar cDateTrav=Calendar.getInstance();
cDateTrav.setTime(dateFrom);
Map<String,Object> position=dayEndCapacityAvailable(techDataCalendarWeek,cDateTrav.get(Calendar.DAY_OF_WEEK));
int moveDay=((Integer)position.get("moveDay")).intValue();
if (moveDay != 0) return 0;
Time startTime=(Time)position.get("startTime");
Double capacity=(Double)position.get("capacity");
Timestamp startAvailablePeriod=new Timestamp(UtilDateTime.getDayStart(dateFrom).getTime() + startTime.getTime() + cDateTrav.get(Calendar.ZONE_OFFSET)+ cDateTrav.get(Calendar.DST_OFFSET));
if (dateFrom.before(startAvailablePeriod)) return 0;
Timestamp endAvailablePeriod=new Timestamp(startAvailablePeriod.getTime() + capacity.longValue());
if (dateFrom.after(endAvailablePeriod)) return 0;
return dateFrom.getTime() - startAvailablePeriod.getTime();
}
| Used to request the remaining capacity available for dateFrom in a TechDataCalenda, If the dateFrom (param in) is not in an available TechDataCalendar period, the return value is zero. |
public void close(){
if (bdd != null) bdd.close();
}
| Close Database |
public static <K,V>ImmutableListMultimap<K,V> of(K k1,V v1){
ImmutableListMultimap.Builder<K,V> builder=ImmutableListMultimap.builder();
builder.put(k1,v1);
return builder.build();
}
| Returns an immutable multimap containing a single entry. |
public boolean isInitialLightingDone(){
return isInitialLightingDone;
}
| Check whether this cube's initial diffuse skylight has been calculated |
static void importPreferences(InputStream is) throws IOException, InvalidPreferencesFormatException {
try {
Document doc=loadPrefsDoc(is);
String xmlVersion=doc.getDocumentElement().getAttribute("EXTERNAL_XML_VERSION");
if (xmlVersion.compareTo(EXTERNAL_XML_VERSION) > 0) throw new InvalidPreferencesFormatException("Exported preferences file format version " + xmlVersion + " is not supported. This java installation can read"+ " versions "+ EXTERNAL_XML_VERSION+ " or older. You may need"+ " to install a newer version of JDK.");
Element xmlRoot=(Element)doc.getDocumentElement().getChildNodes().item(0);
Preferences prefsRoot=(xmlRoot.getAttribute("type").equals("user") ? Preferences.userRoot() : Preferences.systemRoot());
ImportSubtree(prefsRoot,xmlRoot);
}
catch ( SAXException e) {
throw new InvalidPreferencesFormatException(e);
}
}
| Import preferences from the specified input stream, which is assumed to contain an XML document in the format described in the Preferences spec. |
public void addConversation(Conversation conversation){
conversations.put(conversation.getName().toLowerCase(),conversation);
}
| Add a new conversation |
public static org.oscm.internal.vo.VOService convertToUp(org.oscm.vo.VOService oldVO){
if (oldVO == null) {
return null;
}
org.oscm.internal.vo.VOService newVO=new org.oscm.internal.vo.VOService();
newVO.setKey(oldVO.getKey());
newVO.setVersion(oldVO.getVersion());
newVO.setParameters(convertToUpVOParameter(oldVO.getParameters()));
newVO.setDescription(oldVO.getDescription());
newVO.setName(oldVO.getName());
newVO.setServiceId(oldVO.getServiceId());
newVO.setTechnicalId(oldVO.getTechnicalId());
newVO.setFeatureURL(oldVO.getFeatureURL());
newVO.setBaseURL(oldVO.getBaseURL());
newVO.setPriceModel(convertToUp(oldVO.getPriceModel()));
newVO.setStatus(EnumConverter.convert(oldVO.getStatus(),org.oscm.internal.types.enumtypes.ServiceStatus.class));
newVO.setAccessType(EnumConverter.convert(oldVO.getAccessType(),org.oscm.internal.types.enumtypes.ServiceAccessType.class));
newVO.setSellerId(oldVO.getSellerId());
newVO.setSellerName(oldVO.getSellerName());
newVO.setSellerKey(oldVO.getSellerKey());
newVO.setTags(oldVO.getTags());
newVO.setShortDescription(oldVO.getShortDescription());
newVO.setAverageRating(oldVO.getAverageRating());
newVO.setNumberOfReviews(oldVO.getNumberOfReviews());
newVO.setOfferingType(EnumConverter.convert(oldVO.getOfferingType(),org.oscm.internal.types.enumtypes.OfferingType.class));
newVO.setConfiguratorUrl(oldVO.getConfiguratorUrl());
newVO.setCustomTabUrl(oldVO.getCustomTabUrl());
newVO.setCustomTabName(oldVO.getCustomTabName());
return newVO;
}
| Convert source version VO to target version VO. |
@Override public double valueToJava2D(double value,Rectangle2D area,RectangleEdge edge){
double result;
double v=mapValueToFixedRange(value);
if (this.displayStart < this.displayEnd) {
result=trans(v,area,edge);
}
else {
double cutoff=(this.displayStart + this.displayEnd) / 2.0;
double length1=this.fixedRange.getUpperBound() - this.displayStart;
double length2=this.displayEnd - this.fixedRange.getLowerBound();
if (v > cutoff) {
result=transStart(v,area,edge,length1,length2);
}
else {
result=transEnd(v,area,edge,length1,length2);
}
}
return result;
}
| Translates a data value to a Java2D coordinate. |
@Override public void registerIndex(IndexMetadata indexMetadata){
throw new UnsupportedOperationException();
}
| Not allowed. |
public void deleteVideoSharings2(ContactId contact) throws RemoteException {
if (contact == null) {
throw new ServerApiIllegalArgumentException("contact must not be null!");
}
mRichcallService.tryToDeleteVideoSharings(contact);
}
| Delete video sharing associated with a given contact from history and abort/reject any associated ongoing session if such exists. |
private long calculateEffectiveBillingEndDate(long billingInvocationTime,long billingOffset){
Calendar cal=getCalendar();
cal.setTimeInMillis(subtractBillingOffset(billingInvocationTime,billingOffset));
cal.set(Calendar.DAY_OF_MONTH,normalizeCutOffDay(cal.get(Calendar.DAY_OF_MONTH)));
return cal.getTimeInMillis();
}
| Calculates the end of the last period, that may be calculated in the current billing run, based on the billing invocation time and the billing offset. The period end is always on a cut-off day, no period end for 29, 30, 31 days of month. Examples: <br/> 15.12.2012 02:30:0500, offset 2 days in ms <br/> 13.12.2012 00:00:00:0000 period end 31.01.2012 02:30:0500, offset 1 day in ms <br/> 28.01.2012 00:00:00:0000 period end |
public static byte[] fileReadToByteArray(String path){
SuperUserCommand superUserCommand=new SuperUserCommand("cat '" + path + "'");
superUserCommand.setHideInput(true);
superUserCommand.setHideStandardOutput(true);
superUserCommand.setBinaryStandardOutput(true);
superUserCommand.execute();
if (!superUserCommand.commandWasSuccessful()) return null;
return superUserCommand.getStandardOutputBinary();
}
| Gets all bytes from one file |
public static void isInRange(String member,BigDecimal inputValue,BigDecimal minValue,BigDecimal maxValue) throws ValidationException {
if (inputValue != null && minValue != null && inputValue.compareTo(minValue) == -1) {
ValidationException vf=new ValidationException(ReasonEnum.VALUE_NOT_IN_RANGE,member,new Object[]{inputValue});
logValidationFailure(vf);
throw vf;
}
if (inputValue != null && maxValue != null && inputValue.compareTo(maxValue) == 1) {
ValidationException vf=new ValidationException(ReasonEnum.VALUE_NOT_IN_RANGE,member,new Object[]{inputValue});
logValidationFailure(vf);
throw vf;
}
}
| Validates that the given input is in the range or not. |
private static CacheTypeMetadata metaForClass(Class cls){
CacheTypeMetadata meta=new CacheTypeMetadata();
meta.setKeyType(Integer.class);
meta.setValueType(cls);
meta.setAscendingFields(Collections.<String,Class<?>>singletonMap("val",Integer.class));
return meta;
}
| Create type metadata for class. |
private void returnData(Object ret){
if (myHost != null) {
myHost.returnData(ret);
}
}
| Used to communicate a return object from a plugin tool to the main Whitebox user-interface. |
public EchoReplyMessage(EchoReplyMessage other){
if (other.isSetHeader()) {
this.header=new AsyncMessageHeader(other.header);
}
}
| Performs a deep copy on <i>other</i>. |
private Element consistToXml(Consist consist){
Element e=new Element("consist");
e.setAttribute("id",consist.getConsistID());
e.setAttribute("consistNumber","" + consist.getConsistAddress().getNumber());
e.setAttribute("longAddress",consist.getConsistAddress().isLongAddress() ? "yes" : "no");
e.setAttribute("type",consist.getConsistType() == Consist.ADVANCED_CONSIST ? "DAC" : "CSAC");
ArrayList<DccLocoAddress> addressList=consist.getConsistList();
for (int i=0; i < addressList.size(); i++) {
DccLocoAddress locoaddress=addressList.get(i);
Element eng=new Element("loco");
eng.setAttribute("dccLocoAddress","" + locoaddress.getNumber());
eng.setAttribute("longAddress",locoaddress.isLongAddress() ? "yes" : "no");
eng.setAttribute("locoDir",consist.getLocoDirection(locoaddress) ? "normal" : "reverse");
int position=consist.getPosition(locoaddress);
if (position == Consist.POSITION_LEAD) {
eng.setAttribute("locoName","lead");
}
else if (position == Consist.POSITION_TRAIL) {
eng.setAttribute("locoName","rear");
}
else {
eng.setAttribute("locoName","mid");
eng.setAttribute("locoMidNumber","" + position);
}
e.addContent(eng);
}
return (e);
}
| convert a Consist to XML. |
public InstanceComparator(boolean includeClass,String range,boolean invert){
super();
m_Range=new Range();
setIncludeClass(includeClass);
setRange(range);
setInvert(invert);
}
| Initializes the comparator. |
public IntervalleObject merge(IntervalleObject with){
if (with == null) {
return this;
}
else {
Object lower=compareTo(getLowerBound(),with.getLowerBound()) < 0 ? getLowerBound() : with.getLowerBound();
Object upper=compareTo(getUpperBound(),with.getUpperBound()) > 0 ? getUpperBound() : with.getUpperBound();
return new IntervalleObject(lower,upper);
}
}
| create a new interval that merges the given intervals |
public boolean isRolePresent(Role role){
return id.getRoles().contains(role);
}
| Returns true if at least one member is filling the specified role |
public static void closeQuietly(LineIterator iterator){
if (iterator != null) {
iterator.close();
}
}
| Closes the iterator, handling null and ignoring exceptions. |
List createPolys(int nItems,double size,int nPts){
double overlapPct=0.2;
int nCells=(int)Math.sqrt(nItems);
List geoms=new ArrayList();
double width=nCells * (1 - overlapPct) * size;
double height=nCells * 2 * size;
double xInc=width / nCells;
double yInc=height / nCells;
for (int i=0; i < nCells; i++) {
for (int j=0; j < nCells; j++) {
Coordinate base=new Coordinate(i * xInc,j * yInc);
Geometry poly=createPoly(base,size,nPts);
geoms.add(poly);
}
}
return geoms;
}
| Creates a grid of circles with a small percentage of overlap in both directions. This approximated likely real-world cases well, and seems to produce close to worst-case performance for the Iterated algorithm. Sample times: 1000 items/100 pts - Cascaded: 2718 ms, Iterated 150 s |
private byte[] checkUserPassword(byte[] userPassword,byte[] firstDocIdValue,int keyBitLength,int revision,byte[] oValue,byte[] uValue,int pValue,boolean encryptMetadata) throws GeneralSecurityException, EncryptionUnsupportedByProductException, PDFParseException {
final byte[] generalKey=calculateGeneralEncryptionKey(userPassword,firstDocIdValue,keyBitLength,revision,oValue,pValue,encryptMetadata);
final byte[] calculatedUValue=calculateUValue(generalKey,firstDocIdValue,revision);
assert calculatedUValue.length == 32;
if (uValue.length != calculatedUValue.length) {
throw new PDFParseException("Improper U entry length; " + "expected 32, is " + uValue.length);
}
final int numSignificantBytes=revision == 2 ? 32 : 16;
for (int i=0; i < numSignificantBytes; ++i) {
if (uValue[i] != calculatedUValue[i]) {
return null;
}
}
return generalKey;
}
| Check to see whether a provided user password is correct with respect to an Encrypt dict configuration. Corresponds to algorithm 3.6 of the PDF Reference version 1.7 |
protected ByteVector write(final ClassWriter cw,final byte[] code,final int len,final int maxStack,final int maxLocals){
ByteVector v=new ByteVector();
v.data=value;
v.length=value.length;
return v;
}
| Returns the byte array form of this attribute. |
public void invalidate(){
isValid=false;
sessionContext=null;
}
| It invalidates a SSL session forbidding any resumption. |
public void load(){
directory=directory.replaceAll(" Grappl","Grappl");
File[] files=new File(directory).listFiles();
try {
if (files != null) {
for ( File file : files) {
try {
String[] pluginName=file.getName().split("\\.");
if (pluginName[1].equalsIgnoreCase(extension)) {
try {
ClassLoader classLoader=new URLClassLoader(new URL[]{file.toURI().toURL()});
String mainClassLocation="";
DataInputStream plgInfoStream=new DataInputStream(classLoader.getResourceAsStream("plginfo.dat"));
mainClassLocation=plgInfoStream.readLine();
if (!loadedPlugins.contains(mainClassLocation)) {
Class theClass=classLoader.loadClass(mainClassLocation);
try {
Object the=theClass.newInstance();
Method m=theClass.newInstance().getClass().getMethod("main");
m.invoke(the);
pluginsLoaded++;
}
catch ( Exception e) {
e.printStackTrace();
}
loadedPlugins.add(mainClassLocation);
}
}
catch ( MalformedURLException e) {
e.printStackTrace();
}
}
}
catch ( Exception e) {
e.printStackTrace();
}
}
}
}
catch ( Exception e) {
e.printStackTrace();
}
Application.getLog().log(pluginsLoaded + " plugin(s) loaded");
}
| Load the plugins |
@DSComment("From safe class list") @DSSafe(DSCat.SAFE_LIST) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:34:10.970 -0500",hash_original_method="7596573BC98218F8353DB810A415EA55",hash_generated_method="FC221DD174470D4245763A796A96A214") public PorterDuffColorFilter(int srcColor,PorterDuff.Mode mode){
native_instance=native_CreatePorterDuffFilter(srcColor,mode.nativeInt);
nativeColorFilter=nCreatePorterDuffFilter(native_instance,srcColor,mode.nativeInt);
}
| Create a colorfilter that uses the specified color and porter-duff mode. |
public void bindStage(Date currentDate,int stage){
mStage=stage;
mTitle.setText(itemView.getResources().getString(R.string.setting_stage,stage));
mInitialDate=currentDate;
initializeDuration(currentDate);
mButton.setEnabled(false);
mErrorLayout.setVisibility(View.GONE);
mErrorLayout.collapse();
}
| Bind a stage to this ViewHolder |
public static AttributeSet synchronizedView(AttributeSet attributeSet){
if (attributeSet == null) {
throw new NullPointerException();
}
return new SynchronizedAttributeSet(attributeSet);
}
| Creates a synchronized view of the given attribute set. |
private byte[] assembleReceiverReportPacket(){
final int FIXED_HEADER_SIZE=4;
byte V_P_RC=(byte)((RtcpPacket.VERSION << 6) | (RtcpPacket.PADDING << 5) | (0x00));
byte ss[]=RtcpPacketUtils.longToBytes(mRtcpSession.SSRC,4);
byte PT[]=RtcpPacketUtils.longToBytes(RtcpPacket.RTCP_RR,1);
byte receptionReportBlocks[]=new byte[0];
receptionReportBlocks=RtcpPacketUtils.append(receptionReportBlocks,assembleRTCPReceptionReport());
byte receptionReports=(byte)(receptionReportBlocks.length / 24);
V_P_RC=(byte)(V_P_RC | (byte)(receptionReports & 0x1F));
byte length[]=RtcpPacketUtils.longToBytes((FIXED_HEADER_SIZE + ss.length + receptionReportBlocks.length) / 4 - 1,2);
byte RRPacket[]=new byte[1];
RRPacket[0]=V_P_RC;
RRPacket=RtcpPacketUtils.append(RRPacket,PT);
RRPacket=RtcpPacketUtils.append(RRPacket,length);
RRPacket=RtcpPacketUtils.append(RRPacket,ss);
RRPacket=RtcpPacketUtils.append(RRPacket,receptionReportBlocks);
return RRPacket;
}
| assemble RTCP RR packet |
public Analyzer includeHypervolume(){
includeHypervolume=true;
return this;
}
| Enables the evaluation of the hypervolume metric. |
public boolean isBounded(){
return cuboid.isFinite();
}
| Checks if region bounds are bounded (non-infinite). |
@Override public Token nextToken(){
Token t=super.nextToken();
while (t.getType() == STLexer.NEWLINE || t.getType() == STLexer.INDENT) {
t=super.nextToken();
}
return t;
}
| Throw out \n and indentation tokens inside BIGSTRING_NO_NL |
public BootstrapService(final String username,final String password){
this.username=username;
this.password=password;
this.apiKey=null;
}
| Create bootstrap service |
public static VisitorData newVisitor(){
int visitorId=new SecureRandom().nextInt() & 0x7FFFFFFF;
long now=now();
return new VisitorData(visitorId,now,now,now,1);
}
| initializes a new visitor data, with new visitorid |
@Override public void eUnset(int featureID){
switch (featureID) {
case N4JSPackage.CASE_CLAUSE__EXPRESSION:
setExpression((Expression)null);
return;
}
super.eUnset(featureID);
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public void contributeToSymbols(ChooseByNameContributor contributor){
myGotoSymbolContributors.add(contributor);
}
| Registers a component which contributes items to the "Goto Symbol" list. |
public int length(){
int m=maxLength >> ADDRESS_BITS;
while (m > 0 && data[m] == 0) {
m--;
}
maxLength=(m << ADDRESS_BITS) + (64 - Long.numberOfLeadingZeros(data[m]));
return maxLength;
}
| Get the index of the highest set bit plus one, or 0 if no bits are set. |
private void refresh(){
String sql=m_sql;
int pos=m_sql.lastIndexOf(" ORDER BY ");
if (!showAll.isChecked()) {
sql=m_sql.substring(0,pos) + m_sqlNonZero;
if (m_sqlMinLife.length() > 0) sql+=m_sqlMinLife;
sql+=m_sql.substring(pos);
}
log.finest(sql);
PreparedStatement pstmt=null;
ResultSet rs=null;
try {
pstmt=DB.prepareStatement(sql,null);
pstmt.setInt(1,m_M_Product_ID);
if (m_M_Warehouse_ID != 0) pstmt.setInt(2,m_M_Warehouse_ID);
rs=pstmt.executeQuery();
m_table.loadTable(rs);
}
catch ( Exception e) {
log.log(Level.SEVERE,sql,e);
}
finally {
DB.close(rs,pstmt);
rs=null;
pstmt=null;
}
enableButtons();
}
| Refresh Query |
@Override public void close(){
CloseableReference.closeSafely(mPooledByteBufferRef);
}
| Closes the buffer enclosed by this class. |
public void clear(AbsoluteTableIdentifier absoluteTableIdentifier){
tableLockMap.remove(absoluteTableIdentifier);
tableBlocksMap.remove(absoluteTableIdentifier);
}
| remove all the details of a table this will be used in case of drop table |
public static boolean useEMCForceFlag(DbClient _dbClient,URI blockObjectURI){
boolean forceFlag=false;
BlockObject bo=Volume.fetchExportMaskBlockObject(_dbClient,blockObjectURI);
if (bo != null && BlockObject.checkForRP(_dbClient,bo.getId())) {
forceFlag=true;
}
return forceFlag;
}
| Figure out whether or not we need to use the EMC Force flag for the SMIS operation being performed on this volume. |
private int handleGH(String value,DoubleMetaphoneResult result,int index){
if (index > 0 && !isVowel(charAt(value,index - 1))) {
result.append('K');
index+=2;
}
else if (index == 0) {
if (charAt(value,index + 2) == 'I') {
result.append('J');
}
else {
result.append('K');
}
index+=2;
}
else if ((index > 1 && contains(value,index - 2,1,"B","H","D")) || (index > 2 && contains(value,index - 3,1,"B","H","D")) || (index > 3 && contains(value,index - 4,1,"B","H"))) {
index+=2;
}
else {
if (index > 2 && charAt(value,index - 1) == 'U' && contains(value,index - 3,1,"C","G","L","R","T")) {
result.append('F');
}
else if (index > 0 && charAt(value,index - 1) != 'I') {
result.append('K');
}
index+=2;
}
return index;
}
| Handles 'GH' cases |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:35:17.156 -0500",hash_original_method="BA9D4031BD488C1D379B1950A362F8D4",hash_generated_method="4894634EDDCA3FC9A62B97AC03EE312F") @DSSafe(DSCat.ANDROID_CALLBACK) @DSVerified public boolean dispatchKeyShortcutEvent(KeyEvent event){
if (mWindow.superDispatchKeyShortcutEvent(event)) {
return true;
}
return onKeyShortcut(event.getKeyCode(),event);
}
| Called to process a key shortcut event. You can override this to intercept all key shortcut events before they are dispatched to the window. Be sure to call this implementation for key shortcut events that should be handled normally. |
private void createAttachMenuBar(){
JMenuBar bar=new JMenuBar();
JMenu fileMenu=new JMenu("File");
for ( Action action : actionManager.getOpenSavePlotActions()) {
fileMenu.add(action);
}
fileMenu.addSeparator();
fileMenu.add(new CloseAction(this.getWorkspaceComponent()));
JMenu editMenu=new JMenu("Edit");
JMenuItem preferences=new JMenuItem("Preferences...");
editMenu.add(preferences);
JMenu helpMenu=new JMenu("Help");
ShowHelpAction helpAction=new ShowHelpAction("Pages/Plot/histogram.html");
JMenuItem helpItem=new JMenuItem(helpAction);
helpMenu.add(helpItem);
bar.add(fileMenu);
bar.add(helpMenu);
getParentFrame().setJMenuBar(bar);
}
| Creates the menu bar. |
public void remove(int index){
m_List.remove(index);
}
| Removes an element at the specified index from the list. |
public boolean isDescription(){
Object oo=get_Value(COLUMNNAME_IsDescription);
if (oo != null) {
if (oo instanceof Boolean) return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
| Get Description Only. |
public static IdealState buildIdealStateForHdfsDir(DFSClient hdfsClient,String hdfsDir,String resourceName,PartitionerType partitioner,int numReplicas,boolean enableZkCompression) throws ControllerException {
List<HdfsFileStatus> fileList;
try {
fileList=TerrapinUtil.getHdfsFileList(hdfsClient,hdfsDir);
}
catch ( IOException e) {
throw new ControllerException("Exception while listing files in " + hdfsDir,ControllerErrorCode.HDFS_ERROR);
}
Map<Integer,Set<String>> hdfsBlockMapping=Maps.newHashMapWithExpectedSize(fileList.size());
for ( HdfsFileStatus fileStatus : fileList) {
Integer partitionName=TerrapinUtil.extractPartitionName(fileStatus.getLocalName(),partitioner);
if (partitionName == null) {
LOG.info("Skipping " + fileStatus.getLocalName() + " for "+ hdfsDir);
continue;
}
String fullName=fileStatus.getFullName(hdfsDir);
BlockLocation[] locations=null;
try {
locations=hdfsClient.getBlockLocations(fullName,0,fileStatus.getLen());
}
catch ( Exception e) {
throw new ControllerException("Exception while getting block locations " + e.getMessage(),ControllerErrorCode.HDFS_ERROR);
}
Set<String> instanceSet=Sets.newHashSetWithExpectedSize(3);
BlockLocation firstLocation=locations[0];
String[] hosts=null;
try {
hosts=firstLocation.getHosts();
}
catch ( IOException e) {
throw new ControllerException("Exception while getting hosts " + e.getMessage(),ControllerErrorCode.HDFS_ERROR);
}
for ( String host : hosts) {
instanceSet.add(host);
}
hdfsBlockMapping.put(partitionName,instanceSet);
}
int bucketSize=TerrapinUtil.getBucketSize(hdfsBlockMapping.size(),enableZkCompression);
CustomModeISBuilder idealStateBuilder=new CustomModeISBuilder(resourceName);
for ( Map.Entry<Integer,Set<String>> mapping : hdfsBlockMapping.entrySet()) {
String partitionName=null;
if (bucketSize > 0) {
partitionName=resourceName + "_" + mapping.getKey();
}
else {
partitionName=resourceName + "$" + mapping.getKey();
}
Set<String> instanceSet=mapping.getValue();
for ( String instance : instanceSet) {
idealStateBuilder.assignInstanceAndState(partitionName,TerrapinUtil.getHelixInstanceFromHDFSHost(instance),"ONLINE");
}
}
idealStateBuilder.setStateModel("OnlineOffline");
idealStateBuilder.setNumReplica(numReplicas);
idealStateBuilder.setNumPartitions(hdfsBlockMapping.size());
IdealState is=idealStateBuilder.build();
if (bucketSize > 0) {
is.setBucketSize(bucketSize);
}
is.setRebalanceMode(IdealState.RebalanceMode.CUSTOMIZED);
if (enableZkCompression) {
TerrapinUtil.compressIdealState(is);
}
return is;
}
| Builds the helix ideal state for HDFS directory by finding the locations of HDFS blocks and creating an ideal state assignment based on those. |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:36:01.259 -0500",hash_original_method="B2A0BAE23B24F963FF842B8EAAF5D840",hash_generated_method="8291981AB63407AE29C5D4C7916DDECA") public boolean wpsKeypadSupported(){
return (wpsConfigMethodsSupported & WPS_CONFIG_KEYPAD) != 0;
}
| Returns true if WPS keypad configuration is supported |
private void returnData(Object ret){
if (myHost != null) {
myHost.returnData(ret);
}
}
| Used to communicate a return object from a plugin tool to the main Whitebox user-interface. |
public List<ReferenceType> findClassesByName(String name) throws NoSessionException {
ensureActiveSession();
return vm().classesByName(name);
}
| Return a ReferenceType object for the currently loaded class or interface whose fully-qualified class name is specified, else return null if there is none. In general, we must return a list of types, because multiple class loaders could have loaded a class with the same fully-qualified name. |
private boolean isValidUserGroup(ValidationFailureReason[] failureReason,String group){
List<UserGroup> objectList=CustomQueryUtility.queryActiveResourcesByConstraint(_dbClient,UserGroup.class,PrefixConstraint.Factory.getFullMatchConstraint(UserGroup.class,"label",group));
if (CollectionUtils.isEmpty(objectList)) {
_log.error("UserGroup {} is not present in DB",group);
failureReason[0]=ValidationFailureReason.USER_OR_GROUP_NOT_FOUND_FOR_TENANT;
return false;
}
else {
_log.debug("UserGroup {} is valid",group);
return true;
}
}
| Check the given group name matches the label of the active user group in the db or not. |
@Override protected boolean isSwitchFor(EPackage ePackage){
return ePackage == modelPackage;
}
| Checks whether this is a switch for the given package. <!-- begin-user-doc --> <!-- end-user-doc --> |
public BivariateDiscreteDiffusionModel(Parameter graphRate,int xDim,int yDim,double[] eVal,double[][] eVec){
super();
this.graphRate=graphRate;
this.xDim=xDim;
this.yDim=yDim;
this.totalDim=xDim * yDim;
this.eVal=eVal;
this.eVec=eVec;
addVariable(graphRate);
System.err.println("TEST00 = " + getCTMCProbability(0,0,0.0));
System.err.println("TEST01 = " + getCTMCProbability(0,1,0.0));
}
| Construct a discrete diffusion model. |
public String format(final LogEvent event){
final String message=event.getMessage();
if (null == message) {
return "";
}
else {
return message;
}
}
| Format log event into string. |
public static String format(String format,Object[] args){
StringBuilder answer=new StringBuilder(format.length() + (args.length * 20));
String[] argStrings=new String[args.length];
for (int i=0; i < args.length; ++i) {
if (args[i] == null) argStrings[i]="<null>";
else argStrings[i]=args[i].toString();
}
int lastI=0;
for (int i=format.indexOf('{',0); i >= 0; i=format.indexOf('{',lastI)) {
if (i != 0 && format.charAt(i - 1) == '\\') {
if (i != 1) answer.append(format.substring(lastI,i - 1));
answer.append('{');
lastI=i + 1;
}
else {
if (i > format.length() - 3) {
answer.append(format.substring(lastI,format.length()));
lastI=format.length();
}
else {
int argnum=(byte)Character.digit(format.charAt(i + 1),10);
if (argnum < 0 || format.charAt(i + 2) != '}') {
answer.append(format.substring(lastI,i + 1));
lastI=i + 1;
}
else {
answer.append(format.substring(lastI,i));
if (argnum >= argStrings.length) answer.append("<missing argument>");
else answer.append(argStrings[argnum]);
lastI=i + 3;
}
}
}
}
if (lastI < format.length()) answer.append(format.substring(lastI,format.length()));
return answer.toString();
}
| Generates a formatted text string given a source string containing "argument markers" of the form "{argNum}" where each argNum must be in the range 0..9. The result is generated by inserting the toString of each argument into the position indicated in the string. <p> To insert the "{" character into the output, use a single backslash character to escape it (i.e. "\{"). The "}" character does not need to be escaped. |
public Transform(Document doc,String algorithmURI) throws InvalidTransformException {
this(doc,algorithmURI,(NodeList)null);
}
| Generates a Transform object that implements the specified <code>Transform algorithm</code> URI. |
static public FunctionNode GT(final ValueExpressionNode t1,final ValueExpressionNode t2){
return new FunctionNode(FunctionRegistry.GT,null,new ValueExpressionNode[]{t1,t2});
}
| Return <code>t1 > t2</code> |
public boolean hasMoreElements(){
prep();
return rootValue != null || otherValue != null || (subMapValues != null && subMapValues.hasMoreElements());
}
| True if we have more elements. |
@Deprecated @SuppressWarnings("static-method") public final boolean isEmbeddable(){
return true;
}
| Always true now. |
void executeNSDecls(TransformerImpl transformer,String ignorePrefix) throws TransformerException {
try {
if (null != m_prefixTable) {
SerializationHandler rhandler=transformer.getResultTreeHandler();
int n=m_prefixTable.size();
for (int i=n - 1; i >= 0; i--) {
XMLNSDecl decl=(XMLNSDecl)m_prefixTable.get(i);
if (!decl.getIsExcluded() && !(null != ignorePrefix && decl.getPrefix().equals(ignorePrefix))) {
rhandler.startPrefixMapping(decl.getPrefix(),decl.getURI(),true);
}
}
}
}
catch ( org.xml.sax.SAXException se) {
throw new TransformerException(se);
}
}
| Send startPrefixMapping events to the result tree handler for all declared prefix mappings in the stylesheet. |
@Override public TemporaryTopic createTemporaryTopic() throws JMSException {
if (cri.getType() == ActiveMQRAConnectionFactory.QUEUE_CONNECTION || cri.getType() == ActiveMQRAConnectionFactory.XA_QUEUE_CONNECTION) {
throw new IllegalStateException("Cannot create temporary topic for javax.jms.QueueSession");
}
lock();
try {
Session session=getSessionInternal();
if (ActiveMQRASession.trace) {
ActiveMQRALogger.LOGGER.trace("createTemporaryTopic " + session);
}
TemporaryTopic temp=session.createTemporaryTopic();
if (ActiveMQRASession.trace) {
ActiveMQRALogger.LOGGER.trace("createdTemporaryTopic " + session + " temp="+ temp);
}
sf.addTemporaryTopic(temp);
return temp;
}
finally {
unlock();
}
}
| Create a temporary topic |
public Element store(Object o){
QuadOutputSignalHead p=(QuadOutputSignalHead)o;
Element element=new Element("signalhead");
element.setAttribute("class",this.getClass().getName());
element.setAttribute("systemName",p.getSystemName());
element.addContent(new Element("systemName").addContent(p.getSystemName()));
storeCommon(p,element);
element.addContent(addTurnoutElement(p.getGreen(),"green"));
element.addContent(addTurnoutElement(p.getYellow(),"yellow"));
element.addContent(addTurnoutElement(p.getRed(),"red"));
element.addContent(addTurnoutElement(p.getLunar(),"lunar"));
return element;
}
| Default implementation for storing the contents of a QuadOutputSignalHead |
@DSSafe(DSCat.SAFE_LIST) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-09-18 12:03:11.468 -0400",hash_original_method="382ABFEB62D05869A6A7FF602B7E67FB",hash_generated_method="382ABFEB62D05869A6A7FF602B7E67FB") void stop(){
if (mRunning) {
mTriggerPercentage=0;
mFinishTime=AnimationUtils.currentAnimationTimeMillis();
mRunning=false;
mParent.postInvalidate();
}
}
| Stop showing the progress animation. |
public static void executeApiTask(ExecutorService executorService,BaseIngestionRequestContext requestContext,IngestStrategyFactory ingestStrategyFactory,UnManagedVolumeService unManagedVolumeService,DbClient dbClient,Map<String,TaskResourceRep> taskMap,TaskList taskList){
IngestVolumesExportedSchedulingThread schedulingThread=new IngestVolumesExportedSchedulingThread(requestContext,ingestStrategyFactory,unManagedVolumeService,dbClient,taskMap);
try {
executorService.execute(schedulingThread);
}
catch ( Exception e) {
String message="Failed to start unmanaged volume ingestion tasks...";
_logger.error(message,e);
for ( TaskResourceRep taskRep : taskList.getTaskList()) {
taskRep.setMessage(message);
}
}
}
| Executes API Tasks on a separate thread by instantiating a IngestVolumesExportedSchedulingThread. |
public RippleDrawableFroyo(@NonNull ColorStateList color,@Nullable Drawable content,@Nullable Drawable mask){
this(new RippleState(null,null,null),null);
if (color == null) {
throw new IllegalArgumentException("RippleDrawable requires a non-null color");
}
if (content != null) {
addLayer(content,null,0,0,0,0,0);
}
if (mask != null) {
addLayer(mask,null,R.id.carbon_mask,0,0,0,0);
}
background=content;
setColor(color);
ensurePadding();
refreshPadding();
updateLocalState();
}
| Creates a new ripple drawable with the specified ripple color and optional content and mask drawables. |
public final void println(long l) throws IOException {
print(l);
write(_newlineBytes,0,_newlineBytes.length);
if (_isFlushOnNewline) {
flush();
}
}
| Prints a long followed by a newline. |
public void addAndComponent(final PlanLinkIdentifier delegate){
if (locked) throw new IllegalStateException("cannot modify a " + getClass().getSimpleName() + " after its areLinked() method has been called");
this.andDelegates.add(delegate);
}
| if one "and" component returns false, the plans are considered not being linked. Can be used for instance to forbid linking plans of persons not linked by a social tie. |
public void testEquals(){
@SuppressWarnings("unchecked") List<Constructor<F>> constructors=(List)Arrays.asList(clazz.getDeclaredConstructors());
constructors=getCompatibleConstructors(constructors,defaultArgs);
Assert.assertFalse(String.format("Expected at least one constructor to match default args (%s), but found none.",Arrays.asList(defaultArgs)),constructors.isEmpty());
constructors=getCompatibleConstructors(constructors,alternateArgs);
Assert.assertEquals(String.format("Expected only one constructor to match default and alternative args, but found %d.",constructors.size()),1,constructors.size());
Constructor<F> constructor=constructors.get(0);
try {
EqualsTester tester=equalsTesterProvider.get();
for (int i=0; i <= alternateArgs.length; i++) {
Object[] args=getArgs(defaultArgs,alternateArgs,i);
tester.newEqualityGroup(constructor.newInstance(args),constructor.newInstance(args));
}
tester.testEquals();
}
catch ( SecurityException e) {
Assert.fail("Could not access constructor for " + clazz + " with types: "+ Arrays.asList(constructor.getParameterTypes()));
}
catch ( InstantiationException e) {
Assert.fail("Failed to create a new " + clazz + " instance: "+ e);
}
catch ( IllegalAccessException e) {
Assert.fail("Failed to create a new " + clazz + " instance: "+ e);
}
catch ( InvocationTargetException e) {
Assert.fail("Failed to create a new " + clazz + " instance: "+ e);
}
}
| Constructs and tests that the N + 1 possible instances (where each of the N parameters are set to the alternative parameter one at a time) of objects of type F are equal to other instances created with the same arguments, but unequal to objects of the same type created with different arguments. |
private String truncateMessageForDB(String message){
if (message.length() > 4096) {
return message.substring(0,4090) + "...";
}
return message;
}
| Database status message length is limited to 4096 |
public JSONArray optJSONArray(int index){
Object o=this.opt(index);
return o instanceof JSONArray ? (JSONArray)o : null;
}
| Get the optional JSONArray associated with an index. |
@Override public void run(){
amIActive=true;
String inputHeader=null;
String outputHeader=null;
int col;
int row;
int numCols;
int numRows;
int[] dX={1,1,1,0,-1,-1,-1,0};
int[] dY={-1,0,1,1,1,0,-1,-1};
int a;
float progress;
int range;
boolean blnTextOutput=false;
double z;
int i;
if (args.length <= 0) {
showFeedback("Plugin parameters have not been set.");
return;
}
for (i=0; i < args.length; i++) {
if (i == 0) {
inputHeader=args[i];
}
else if (i == 1) {
outputHeader=args[i];
}
else if (i == 2) {
blnTextOutput=Boolean.parseBoolean(args[i]);
}
}
if ((inputHeader == null) || (outputHeader == null)) {
showFeedback("One or more of the input parameters have not been set properly.");
return;
}
try {
WhiteboxRaster image=new WhiteboxRaster(inputHeader,"r");
numRows=image.getNumberRows();
numCols=image.getNumberColumns();
double noData=image.getNoDataValue();
WhiteboxRaster output=new WhiteboxRaster(outputHeader,"rw",inputHeader,WhiteboxRaster.DataType.FLOAT,noData);
output.setPreferredPalette("spectrum.pal");
output.setDataScale(WhiteboxRaster.DataScale.CONTINUOUS);
range=(int)(image.getMaximumValue());
long[][] proportionData=new long[3][range + 1];
double[] proportion=new double[range + 1];
int cN, rN;
double zN;
boolean edge;
updateProgress("Loop 1 of 2:",0);
for (row=0; row < numRows; row++) {
for (col=0; col < numCols; col++) {
z=image.getValue(row,col);
if (z > 0) {
a=(int)(z);
proportionData[0][a]++;
edge=false;
for (i=0; i < 8; i++) {
cN=col + dX[i];
rN=row + dY[i];
zN=image.getValue(rN,cN);
if (zN != z) {
edge=true;
break;
}
}
if (edge) {
proportionData[1][a]++;
}
}
}
if (cancelOp) {
cancelOperation();
return;
}
progress=(float)(100f * row / (numRows - 1));
updateProgress("Loop 1 of 2:",(int)progress);
}
for (a=0; a <= range; a++) {
if (proportionData[1][a] > 1) {
proportion[a]=(double)proportionData[1][a] / proportionData[0][a];
}
}
double[] data=null;
updateProgress("Loop 2 of 2:",0);
for (row=0; row < numRows; row++) {
data=image.getRowValues(row);
for (col=0; col < numCols; col++) {
if (data[col] > 0) {
a=(int)(data[col]);
output.setValue(row,col,proportion[a]);
}
}
if (cancelOp) {
cancelOperation();
return;
}
progress=(float)(100f * row / (numRows - 1));
updateProgress("Loop 2 of 2:",(int)progress);
}
output.addMetadataEntry("Created by the " + getDescriptiveName() + " tool.");
output.addMetadataEntry("Created on " + new Date());
image.close();
output.close();
if (blnTextOutput) {
DecimalFormat df;
df=new DecimalFormat("0.0000");
String retstr="Edge Proportion\nPatch ID\tValue";
for (a=0; a <= range; a++) {
if (proportionData[1][a] > 0) {
retstr=retstr + "\n" + a+ "\t"+ df.format(proportion[a]);
}
}
returnData(retstr);
}
returnData(outputHeader);
}
catch ( OutOfMemoryError oe) {
myHost.showFeedback("An out-of-memory error has occurred during operation.");
}
catch ( Exception e) {
myHost.showFeedback("An error has occurred during operation. See log file for details.");
myHost.logException("Error in " + getDescriptiveName(),e);
}
finally {
updateProgress("Progress: ",0);
amIActive=false;
myHost.pluginComplete();
}
}
| Used to execute this plugin tool. |
public static void main(String[] args){
TestModifier tester=new TestModifier();
if (run(tester,ARGS,TEST,NEGATED_TEST) != 0) {
throw new Error("Javadoc error occured during execution.");
}
}
| The entry point of the test. |
@Override public synchronized void initialize(){
if (!mRootDirectory.exists()) {
if (!mRootDirectory.mkdirs()) {
VolleyLog.e("Unable to create cache dir %s",mRootDirectory.getAbsolutePath());
}
return;
}
File[] files=mRootDirectory.listFiles();
if (files == null) {
return;
}
for ( File file : files) {
FileInputStream fis=null;
try {
fis=new FileInputStream(file);
CacheHeader entry=CacheHeader.readHeader(fis);
entry.size=file.length();
putEntry(entry.key,entry);
}
catch ( IOException e) {
if (file != null) {
file.delete();
}
}
finally {
try {
if (fis != null) {
fis.close();
}
}
catch ( IOException ignored) {
}
}
}
}
| Initializes the DiskBasedCache by scanning for all files currently in the specified root directory. Creates the root directory if necessary. |
public boolean isHole(){
return isHole;
}
| Tests whether this ring is a hole. |
public static final double sigma(double a){
return 1.0 / (1.0 + Math.exp(-a));
}
| Sigmoid / Logistic function |
@Override public void connect(){
try {
Class.forName(databaseDriver).newInstance();
connection=DriverManager.getConnection(databaseUrl,connectionProperties);
logger.debug("JDBC connection Success");
}
catch ( Throwable t) {
DTThrowable.rethrow(t);
}
}
| Create connection with database using JDBC. |
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 readObject(ObjectInputStream s) throws ClassNotFoundException, IOException {
s.defaultReadObject();
setStyle(s.readInt());
seg=new Segment();
}
| Deserializes a caret. This is overridden to read the caret's style. |
@Override public void end(){
GLU.gluTessEndContour(this.tess);
}
| Called by the GLU tessellator to indicate the end of the current line loop. This recursively ends the current contour with the GLU tessellator specified during construction by calling gluTessEndContour(tessellator). |
public AvalonLogSystem(){
}
| default CTOR. Initializes itself using the property RUNTIME_LOG from the Velocity properties |
public PipedOutputStream(PipedInputStream snk) throws IOException {
connect(snk);
}
| Creates a piped output stream connected to the specified piped input stream. Data bytes written to this stream will then be available as input from <code>snk</code>. |
public static void validateCompositeData(CompositeData cd){
if (cd == null) {
throw new NullPointerException("Null CompositeData");
}
if (!isTypeMatched(stackTraceElementCompositeType,cd.getCompositeType())) {
throw new IllegalArgumentException("Unexpected composite type for StackTraceElement");
}
}
| Validate if the input CompositeData has the expected CompositeType (i.e. contain all attributes with expected names and types). |
public static void frustumM(float[] m,int offset,float left,float right,float bottom,float top,float near,float far){
if (left == right) {
throw new IllegalArgumentException("left == right");
}
if (top == bottom) {
throw new IllegalArgumentException("top == bottom");
}
if (near == far) {
throw new IllegalArgumentException("near == far");
}
if (near <= 0.0f) {
throw new IllegalArgumentException("near <= 0.0f");
}
if (far <= 0.0f) {
throw new IllegalArgumentException("far <= 0.0f");
}
final float r_width=1.0f / (right - left);
final float r_height=1.0f / (top - bottom);
final float r_depth=1.0f / (near - far);
final float x=2.0f * (near * r_width);
final float y=2.0f * (near * r_height);
final float A=2.0f * ((right + left) * r_width);
final float B=(top + bottom) * r_height;
final float C=(far + near) * r_depth;
final float D=2.0f * (far * near * r_depth);
m[offset + 0]=x;
m[offset + 5]=y;
m[offset + 8]=A;
m[offset + 9]=B;
m[offset + 10]=C;
m[offset + 14]=D;
m[offset + 11]=-1.0f;
m[offset + 1]=0.0f;
m[offset + 2]=0.0f;
m[offset + 3]=0.0f;
m[offset + 4]=0.0f;
m[offset + 6]=0.0f;
m[offset + 7]=0.0f;
m[offset + 12]=0.0f;
m[offset + 13]=0.0f;
m[offset + 15]=0.0f;
}
| Define a projection matrix in terms of six clip planes |
public boolean hasValue(){
return getValue() != null;
}
| Returns whether it has the value. |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 13:01:48.349 -0500",hash_original_method="65CFF0B218928C469B4491A10DEABC8E",hash_generated_method="9C1308D1F4C5EFBDC70FFAD2FAA828F3") public BasicHeaderElementIterator(final HeaderIterator headerIterator,final HeaderValueParser parser){
if (headerIterator == null) {
throw new IllegalArgumentException("Header iterator may not be null");
}
if (parser == null) {
throw new IllegalArgumentException("Parser may not be null");
}
this.headerIt=headerIterator;
this.parser=parser;
}
| Creates a new instance of BasicHeaderElementIterator |
@ToString public String toString(){
return "PT" + String.valueOf(getValue()) + "S";
}
| Gets this instance as a String in the ISO8601 duration format. <p> For example, "PT4S" represents 4 seconds. |
public static void hideKeyboard(Activity activity,IBinder windowToken){
InputMethodManager mgr=(InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(windowToken,0);
}
| This method is used to hide a keyboard after a user has finished typing the url. |
public void registerAboveContentView(View v,LayoutParams params){
if (!mBroadcasting) mViewAbove=v;
}
| Register the above content view. |
public void testLegacyIntReverse() throws IOException {
Directory dir=newDirectory();
RandomIndexWriter writer=new RandomIndexWriter(random(),dir);
Document doc=new Document();
doc.add(new LegacyIntField("value",300000,Field.Store.YES));
writer.addDocument(doc);
doc=new Document();
doc.add(new LegacyIntField("value",-1,Field.Store.YES));
writer.addDocument(doc);
doc=new Document();
doc.add(new LegacyIntField("value",4,Field.Store.YES));
writer.addDocument(doc);
IndexReader ir=UninvertingReader.wrap(writer.getReader(),Collections.singletonMap("value",Type.LEGACY_INTEGER));
writer.close();
IndexSearcher searcher=newSearcher(ir);
Sort sort=new Sort(new SortField("value",SortField.Type.INT,true));
TopDocs td=searcher.search(new MatchAllDocsQuery(),10,sort);
assertEquals(3,td.totalHits);
assertEquals("300000",searcher.doc(td.scoreDocs[0].doc).get("value"));
assertEquals("4",searcher.doc(td.scoreDocs[1].doc).get("value"));
assertEquals("-1",searcher.doc(td.scoreDocs[2].doc).get("value"));
TestUtil.checkReader(ir);
ir.close();
dir.close();
}
| Tests sorting on type legacy int in reverse |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.