code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
public static void main(String... args) throws Exception {
new TestPerformance().test(args);
}
| This method is called when executing this sample application. |
public void update(Graphics g){
paint(g);
}
| Calls <code>paint(g)</code>. This method was overridden to prevent an unnecessary call to clear the background. |
public ClassDefinition makeClassDefinition(Environment toplevelEnv,long where,IdentifierToken name,String doc,int modifiers,IdentifierToken superClass,IdentifierToken interfaces[],ClassDefinition outerClass){
Identifier nm=name.getName();
long nmpos=name.getWhere();
Identifier pkgNm;
String mangledName=null;
ClassDefinition localContextClass=null;
Identifier localName=null;
if (nm.isQualified() || nm.isInner()) {
pkgNm=nm;
}
else if ((modifiers & (M_LOCAL | M_ANONYMOUS)) != 0) {
localContextClass=outerClass.getTopClass();
for (int i=1; ; i++) {
mangledName=i + (nm.equals(idNull) ? "" : SIG_INNERCLASS + nm);
if (localContextClass.getLocalClass(mangledName) == null) {
break;
}
}
Identifier outerNm=localContextClass.getName();
pkgNm=Identifier.lookupInner(outerNm,Identifier.lookup(mangledName));
if ((modifiers & M_ANONYMOUS) != 0) {
localName=idNull;
}
else {
localName=nm;
}
}
else if (outerClass != null) {
pkgNm=Identifier.lookupInner(outerClass.getName(),nm);
}
else {
pkgNm=nm;
}
ClassDeclaration c=toplevelEnv.getClassDeclaration(pkgNm);
if (c.isDefined()) {
toplevelEnv.error(nmpos,"class.multidef",c.getName(),c.getClassDefinition().getSource());
c=new ClassDeclaration(pkgNm);
}
if (superClass == null && !pkgNm.equals(idJavaLangObject)) {
superClass=new IdentifierToken(idJavaLangObject);
}
ClassDefinition sourceClass=new SourceClass(toplevelEnv,where,c,doc,modifiers,superClass,interfaces,(SourceClass)outerClass,localName);
if (outerClass != null) {
outerClass.addMember(toplevelEnv,new SourceMember(sourceClass));
if ((modifiers & (M_LOCAL | M_ANONYMOUS)) != 0) {
localContextClass.addLocalClass(sourceClass,mangledName);
}
}
return sourceClass;
}
| Create a new class. |
protected boolean isExpired(String url){
return getFromCache(url) == null;
}
| whether the element of the specified url has invalided |
public ICalWriter(File file,boolean append,ICalVersion targetVersion) throws IOException {
this((targetVersion == ICalVersion.V1_0) ? new FileWriter(file,append) : new Utf8Writer(file,append),targetVersion);
}
| Creates a new iCalendar writer. |
public IIRFilter(AnalogPrototype baseFilter,PassbandType type,double f1,double f2,double delta){
AnalogPrototype prototype;
switch (type) {
case LOWPASS:
prototype=baseFilter.lptolp(warp(f2,delta));
break;
case BANDPASS:
prototype=baseFilter.lptobp(warp(f1,delta),warp(f2,delta));
break;
case HIGHPASS:
prototype=baseFilter.lptohp(warp(f1,delta));
break;
default :
throw new IllegalStateException("Undefined passband type");
}
double[] tn=new double[2];
double[] td=new double[2];
tn[0]=1.0;
tn[1]=-1.0;
td[0]=1.0;
td[1]=1.0;
Rational S=new Rational(tn,td);
T=new Rational(1.0);
sections=new ArrayList<SecondOrderSection>();
for (int i=0; i < prototype.nSections(); i++) {
Rational R=prototype.getSection(i).map(S);
T.timesEquals(R);
double[] cn=R.numerator().coefficients();
double[] cd=R.denominator().coefficients();
double s=1.0;
if (cd[0] != 0.0) s=cd[0];
double b0=cn[0] / s;
double b1=0.0;
if (cn.length >= 2) b1=cn[1] / s;
double b2=0.0;
if (cn.length >= 3) b2=cn[2] / s;
double a1=0.0;
if (cd.length >= 2) a1=cd[1] / s;
double a2=0.0;
if (cd.length >= 3) a2=cd[2] / s;
sections.add(new SecondOrderSection(b0,b1,b2,a1,a2));
}
}
| Instantiates a new IIR filter. |
@Override public boolean equals(Object o){
if (!super.equals(o)) return false;
SpatialDistanceQuery other=(SpatialDistanceQuery)o;
return this.latCenter == other.latCenter && this.lonCenter == other.lonCenter && this.latMin == other.latMin && this.latMax == other.latMax && this.lonMin == other.lonMin && this.lonMax == other.lonMax && this.lon2Min == other.lon2Min && this.lon2Max == other.lon2Max && this.dist == other.dist && this.planetRadius == other.planetRadius && this.calcDist == other.calcDist && this.lonSource.equals(other.lonSource) && this.latSource.equals(other.latSource) && this.getBoost() == other.getBoost();
}
| Returns true if <code>o</code> is equal to this. |
@DSComment("Package priviledge") @DSBan(DSCat.DEFAULT_MODIFIER) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:57:15.978 -0500",hash_original_method="5D4518F727B3B1C5CE98EBC039D9AF6B",hash_generated_method="5086D8F7DF5A22081C0AACC30CB43003") final long now(){
return System.nanoTime();
}
| Returns current nanosecond time. |
public static byte[] readFileToByteArray(File file) throws IOException {
InputStream in=null;
try {
in=openInputStream(file);
return IOUtils.toByteArray(in,file.length());
}
finally {
IOUtils.closeQuietly(in);
}
}
| Reads the contents of a file into a byte array. The file is always closed. |
public Object runSafely(Catbert.FastStack stack) throws Exception {
String pluggy=getCapDevInput(stack).getTuningPlugin();
if (pluggy != null && pluggy.length() > 0) return SFIRTuner.getPrettyNameForFile(pluggy);
else return "";
}
| Gets the name of the tuning plugin used for this CaptureDeviceInput |
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. |
protected void UnaryExpr() throws javax.xml.transform.TransformerException {
int opPos=m_ops.getOp(OpMap.MAPINDEX_LENGTH);
boolean isNeg=false;
if (m_tokenChar == '-') {
nextToken();
appendOp(2,OpCodes.OP_NEG);
isNeg=true;
}
UnionExpr();
if (isNeg) m_ops.setOp(opPos + OpMap.MAPINDEX_LENGTH,m_ops.getOp(OpMap.MAPINDEX_LENGTH) - opPos);
}
| UnaryExpr ::= UnionExpr | '-' UnaryExpr |
public void addSubject(Subject subject){
getSubjects().add(subject);
}
| Adds a new subject. |
public int indexOf(Object obj){
final List<Node> l;
synchronized (this) {
l=this.list;
}
return l.indexOf(obj);
}
| Returns the index of Object if present, else -1. |
public static void main(String[] args){
new SuperHeroExample().run();
}
| Main method that runs the example. |
public TIntObjectHashMapDecorator(TIntObjectHashMap<V> map){
super();
this._map=map;
}
| Creates a wrapper that decorates the specified primitive map. |
public static Domain extractDomain(String topDomainFile){
return extractDomain(topDomainFile,true);
}
| Extract a dialogue domain from the XML specification |
public static IconManager instance(){
if (INSTANCE == null) {
synchronized (IconManager.class) {
if (INSTANCE == null) INSTANCE=new IconManager();
}
}
return INSTANCE;
}
| Returns the sole instance of this IconManager class. |
public static File showOpenFile(String extension,Shell parent){
return showOpenFile(extension,null,parent);
}
| Show a file open dialog that filters for files with the given extension. |
public boolean next() throws SQLException {
checkCursorMove();
boolean result=fbFetcher.next();
if (result) notifyRowUpdater();
return result;
}
| Moves the cursor down one row from its current position. A <code>ResultSet</code> cursor is initially positioned before the first row; the first call to the method <code>next</code> makes the first row the current row; the second call makes the second row the current row, and so on. <P>If an input stream is open for the current row, a call to the method <code>next</code> will implicitly close it. A <code>ResultSet</code> object's warning chain is cleared when a new row is read. |
public <T extends Enum<T>>Set<T> convertSet(Set<? extends Enum<?>> values,Class<T> targetClass){
Set<T> list=new HashSet<T>();
if (values == null) {
return null;
}
for ( Enum<?> e : values) {
T result=convert(e,targetClass);
if (result != null) {
list.add(result);
}
}
return list;
}
| Convert a set of enum values from internal to api or vice versa. |
public ServiceCompatibilityExceptionBean(ApplicationExceptionBean sup,Reason reason){
super(sup);
setReason(reason);
}
| Instantiates a <code>ServiceCompatibilityExceptionBean</code> based on the specified <code>ApplicationExceptionBean</code> and sets the given reason. |
public String findURIFromDoc(int owner){
int n=m_sourceTree.size();
for (int i=0; i < n; i++) {
SourceTree sTree=(SourceTree)m_sourceTree.elementAt(i);
if (owner == sTree.m_root) return sTree.m_url;
}
return null;
}
| Given a document, find the URL associated with that document. |
public void fillInNotifierBundle(Bundle m){
m.putInt("GsmSignalStrength",mGsmSignalStrength);
m.putInt("GsmBitErrorRate",mGsmBitErrorRate);
m.putInt("CdmaDbm",mCdmaDbm);
m.putInt("CdmaEcio",mCdmaEcio);
m.putInt("EvdoDbm",mEvdoDbm);
m.putInt("EvdoEcio",mEvdoEcio);
m.putInt("EvdoSnr",mEvdoSnr);
m.putInt("LteSignalStrength",mLteSignalStrength);
m.putInt("LteRsrp",mLteRsrp);
m.putInt("LteRsrq",mLteRsrq);
m.putInt("LteRssnr",mLteRssnr);
m.putInt("LteCqi",mLteCqi);
m.putInt("TdScdma",mTdScdmaRscp);
m.putBoolean("isGsm",Boolean.valueOf(isGsm));
}
| Set intent notifier Bundle based on SignalStrength |
private double[] scaledMixture(double[] b,double scale,double[] m1,double[] m2){
double[] y=new double[b.length];
for (int i=0; i < y.length; i++) {
y[i]=b[i] + scale * (m1[i] - m2[i]);
}
return y;
}
| calculate b + scale *(m1 - m2) |
public void comment(char ch[],int start,int length) throws org.xml.sax.SAXException {
int start_old=start;
if (m_inEntityRef) return;
if (m_elemContext.m_startTagOpen) {
closeStartTag();
m_elemContext.m_startTagOpen=false;
}
else if (m_needToCallStartDocument) {
startDocumentInternal();
m_needToCallStartDocument=false;
}
try {
final int limit=start + length;
boolean wasDash=false;
if (m_cdataTagOpen) closeCDATA();
if (shouldIndent()) indent();
final java.io.Writer writer=m_writer;
writer.write(COMMENT_BEGIN);
for (int i=start; i < limit; i++) {
if (wasDash && ch[i] == '-') {
writer.write(ch,start,i - start);
writer.write(" -");
start=i + 1;
}
wasDash=(ch[i] == '-');
}
if (length > 0) {
final int remainingChars=(limit - start);
if (remainingChars > 0) writer.write(ch,start,remainingChars);
if (ch[limit - 1] == '-') writer.write(' ');
}
writer.write(COMMENT_END);
}
catch ( IOException e) {
throw new SAXException(e);
}
m_startNewLine=true;
if (m_tracer != null) super.fireCommentEvent(ch,start_old,length);
}
| Receive notification of an XML comment anywhere in the document. This callback will be used for comments inside or outside the document element, including comments in the external DTD subset (if read). |
public void debug(IDebugSearch debug){
this.debug=debug;
}
| Install debugger to use. |
static Object unmaskNull(Object key){
return (key == NULL_KEY) ? null : key;
}
| Returns internal representation of null key back to caller as null. |
public void close(){
try {
conn.close();
}
catch ( SQLException e) {
throw convert(e);
}
}
| Close the database connection. |
public void fill(Shape shape){
defineShape(shape,false,true);
}
| Draws only the center of a closed AWT shape in SWF vectors using the settings of the current graphic context and places it on the SWF display list. The current paint is used to render the shape. |
@Override public boolean isActive(){
return amIActive;
}
| Used by the Whitebox GUI to tell if this plugin is still running. |
public void copy(int sx,int sy,int sw,int sh,int dx,int dy,int dw,int dh){
blend(this,sx,sy,sw,sh,dx,dy,dw,dh,REPLACE);
}
| Copy things from one area of this image to another area in the same image. |
protected float reportReturn(String methodCall,float value){
reportAllReturns(methodCall,"" + value);
return value;
}
| Conveniance method to report (for logging) that a method returned a float value. |
public void endElement(String uri,String localName,String qName) throws SAXException {
if (DEBUG) System.out.println("TransformerHandlerImpl#endElement: " + qName);
if (m_contentHandler != null) {
m_contentHandler.endElement(uri,localName,qName);
}
}
| Filter an end element event. |
public Boolean isTraversable(File f){
return null;
}
| Whether the directory is traversable or not. This might be useful, for example, if you want a directory to represent a compound document and don't want the user to descend into it. |
protected void addIgnoredType(Object tokenType){
ignoredTypes.add(tokenType);
}
| Adds a token type to the set of tokens that should be ignored in the tokenizer output. |
public static boolean isStatusServerError(int status){
return (status >= 500 && status < 600);
}
| Returns whether the status is a server error (i.e. 5xx). |
boolean boundaryApproxEquals(S2Loop b,double maxError){
if (numVertices() != b.numVertices()) {
return false;
}
int maxVertices=numVertices();
int iThis=firstLogicalVertex;
int iOther=b.firstLogicalVertex;
for (int i=0; i < maxVertices; ++i, ++iThis, ++iOther) {
if (!S2.approxEquals(vertex(iThis),b.vertex(iOther),maxError)) {
return false;
}
}
return true;
}
| Returns true if two loops have the same boundary except for vertex perturbations. More precisely, the vertices in the two loops must be in the same cyclic order, and corresponding vertex pairs must be separated by no more than maxError. Note: This method mostly useful only for testing purposes. |
@SuppressWarnings("unchecked") private UUID nodeForSplit(HadoopInputSplit split,Collection<UUID> topIds,Map<String,Collection<UUID>> nodes,Map<UUID,Integer> nodeLoads) throws IgniteCheckedException {
if (split instanceof HadoopFileBlock) {
HadoopFileBlock split0=(HadoopFileBlock)split;
if (IGFS_SCHEME.equalsIgnoreCase(split0.file().getScheme())) {
HadoopIgfsEndpoint endpoint=new HadoopIgfsEndpoint(split0.file().getAuthority());
IgfsEx igfs=null;
if (F.eq(ignite.name(),endpoint.grid())) igfs=(IgfsEx)((IgniteEx)ignite).igfsx(endpoint.igfs());
if (igfs != null && !igfs.isProxy(split0.file())) {
IgfsPath path=new IgfsPath(split0.file());
if (igfs.exists(path)) {
Collection<IgfsBlockLocation> blocks;
try {
blocks=igfs.affinity(path,split0.start(),split0.length());
}
catch ( IgniteException e) {
throw new IgniteCheckedException(e);
}
assert blocks != null;
if (blocks.size() == 1) return bestNode(blocks.iterator().next().nodeIds(),topIds,nodeLoads,false);
else {
Map<UUID,Long> nodeMap=new HashMap<>();
List<UUID> bestNodeIds=null;
long bestLen=-1L;
for ( IgfsBlockLocation block : blocks) {
for ( UUID blockNodeId : block.nodeIds()) {
if (topIds.contains(blockNodeId)) {
Long oldLen=nodeMap.get(blockNodeId);
long newLen=oldLen == null ? block.length() : oldLen + block.length();
nodeMap.put(blockNodeId,newLen);
if (bestNodeIds == null || bestLen < newLen) {
bestNodeIds=new ArrayList<>(1);
bestNodeIds.add(blockNodeId);
bestLen=newLen;
}
else if (bestLen == newLen) {
assert !F.isEmpty(bestNodeIds);
bestNodeIds.add(blockNodeId);
}
}
}
}
if (bestNodeIds != null) {
return bestNodeIds.size() == 1 ? bestNodeIds.get(0) : bestNode(bestNodeIds,topIds,nodeLoads,true);
}
}
}
}
}
}
Collection<UUID> blockNodes=null;
for ( String host : split.hosts()) {
Collection<UUID> hostNodes=nodes.get(host);
if (!F.isEmpty(hostNodes)) {
if (blockNodes == null) blockNodes=new ArrayList<>(hostNodes);
else blockNodes.addAll(hostNodes);
}
}
return bestNode(blockNodes,topIds,nodeLoads,false);
}
| Determine the best node for this split. |
public MaximizeWindowAction(Application app,@Nullable View view){
super(app,view);
ResourceBundleUtil labels=ResourceBundleUtil.getBundle("org.jhotdraw.app.Labels");
labels.configureAction(this,ID);
}
| Creates a new instance. |
static void checkTypeRefAndPath(int typeRef,TypePath typePath){
int mask=0;
switch (typeRef >>> 24) {
case TypeReference.CLASS_TYPE_PARAMETER:
case TypeReference.METHOD_TYPE_PARAMETER:
case TypeReference.METHOD_FORMAL_PARAMETER:
mask=0xFFFF0000;
break;
case TypeReference.FIELD:
case TypeReference.METHOD_RETURN:
case TypeReference.METHOD_RECEIVER:
case TypeReference.LOCAL_VARIABLE:
case TypeReference.RESOURCE_VARIABLE:
case TypeReference.INSTANCEOF:
case TypeReference.NEW:
case TypeReference.CONSTRUCTOR_REFERENCE:
case TypeReference.METHOD_REFERENCE:
mask=0xFF000000;
break;
case TypeReference.CLASS_EXTENDS:
case TypeReference.CLASS_TYPE_PARAMETER_BOUND:
case TypeReference.METHOD_TYPE_PARAMETER_BOUND:
case TypeReference.THROWS:
case TypeReference.EXCEPTION_PARAMETER:
mask=0xFFFFFF00;
break;
case TypeReference.CAST:
case TypeReference.CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT:
case TypeReference.METHOD_INVOCATION_TYPE_ARGUMENT:
case TypeReference.CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT:
case TypeReference.METHOD_REFERENCE_TYPE_ARGUMENT:
mask=0xFF0000FF;
break;
default :
throw new IllegalArgumentException("Invalid type reference sort 0x" + Integer.toHexString(typeRef >>> 24));
}
if ((typeRef & ~mask) != 0) {
throw new IllegalArgumentException("Invalid type reference 0x" + Integer.toHexString(typeRef));
}
if (typePath != null) {
for (int i=0; i < typePath.getLength(); ++i) {
int step=typePath.getStep(i);
if (step != TypePath.ARRAY_ELEMENT && step != TypePath.INNER_TYPE && step != TypePath.TYPE_ARGUMENT && step != TypePath.WILDCARD_BOUND) {
throw new IllegalArgumentException("Invalid type path step " + i + " in "+ typePath);
}
if (step != TypePath.TYPE_ARGUMENT && typePath.getStepArgument(i) != 0) {
throw new IllegalArgumentException("Invalid type path step argument for step " + i + " in "+ typePath);
}
}
}
}
| Checks the reference to a type in a type annotation. |
public MapRouteMovement(Settings settings){
super(settings);
String fileName=settings.getSetting(ROUTE_FILE_S);
int type=settings.getInt(ROUTE_TYPE_S);
allRoutes=MapRoute.readRoutes(fileName,type,getMap());
nextRouteIndex=0;
pathFinder=new DijkstraPathFinder(getOkMapNodeTypes());
this.route=this.allRoutes.get(this.nextRouteIndex).replicate();
if (this.nextRouteIndex >= this.allRoutes.size()) {
this.nextRouteIndex=0;
}
if (settings.contains(ROUTE_FIRST_STOP_S)) {
this.firstStopIndex=settings.getInt(ROUTE_FIRST_STOP_S);
if (this.firstStopIndex >= this.route.getNrofStops()) {
throw new SettingsError("Too high first stop's index (" + this.firstStopIndex + ") for route with only "+ this.route.getNrofStops()+ " stops");
}
}
}
| Creates a new movement model based on a Settings object's settings. |
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
XMLObject object=xo.getChild(CHAIN_PARAMETER);
Parameter chainParameter=(Parameter)object.getChild(0);
boolean jeffreys=xo.getAttribute(JEFFREYS,false);
boolean reverse=xo.getAttribute(REVERSE,false);
double shape=xo.getAttribute(SHAPE,1.0);
if (shape < 1.0) {
throw new XMLParseException("ExponentialMarkovModel: shape parameter must be >= 1.0");
}
if (shape == 1.0) {
System.out.println("Exponential markov model on parameter " + chainParameter.getParameterName() + " (jeffreys="+ jeffreys+ ", reverse="+ reverse+ ")");
}
else {
System.out.println("Gamma markov model on parameter " + chainParameter.getParameterName() + " (jeffreys="+ jeffreys+ ", reverse="+ reverse+ " shape="+ shape+ ")");
}
return new ExponentialMarkovModel(chainParameter,jeffreys,reverse,shape);
}
| Reads a gamma distribution model from a DOM Document element. |
public ExtendedClientConfiguration withLargePayloadSupportDisabled(){
setLargePayloadSupportDisabled();
return this;
}
| Disables support for large-payload messages. |
public static int[] randomNumber(int n){
int[] num=new int[n];
for (int i=0; i < num.length; i++) {
num[i]=(int)(rGen.nextDouble() * 10);
}
return num;
}
| generate random number of size n. |
public PaymentLineImpl(final String skuCode,final String skuName,final BigDecimal quantity,final BigDecimal unitPrice,final BigDecimal taxAmount,final boolean shipment){
this.skuName=skuName;
this.skuCode=skuCode;
this.quantity=quantity;
this.unitPrice=unitPrice;
this.taxAmount=taxAmount;
this.shipment=shipment;
}
| Construct payment line. |
public void send(final String text){
if (mRXCharacteristic == null) return;
if (!TextUtils.isEmpty(text) && mOutgoingBuffer == null) {
final byte[] buffer=mOutgoingBuffer=text.getBytes();
mBufferOffset=0;
final boolean writeRequest=(mRXCharacteristic.getProperties() & BluetoothGattCharacteristic.PROPERTY_WRITE) > 0;
if (!writeRequest) {
final int length=Math.min(buffer.length,MAX_PACKET_SIZE);
mBufferOffset+=length;
getApi().enqueue(BleProfileApi.Request.newWriteRequest(mRXCharacteristic,buffer,0,length));
}
else {
mBufferOffset=buffer.length;
getApi().enqueue(BleProfileApi.Request.newWriteRequest(mRXCharacteristic,buffer,0,buffer.length));
}
}
}
| Sends the given text to RX characteristic. |
private Object readResolve(){
if (list instanceof RandomAccess) {
return new UnmodifiableRandomAccessList<E>(list);
}
return this;
}
| Resolves UnmodifiableList instances to UnmodifiableRandomAccessList instances if the underlying list is a Random Access list. <p> This is necessary since UnmodifiableRandomAccessList instances are replaced with UnmodifiableList instances during serialization for compliance with JREs before 1.4. <p> |
protected void cacheIdeLocation(final File vstsDirectory,final String currentLocation){
final Map<String,String> locationEntries=new HashMap<String,String>();
final File locationsFile=new File(vstsDirectory,LOCATION_FILE);
final String ideName=ApplicationNamesInfo.getInstance().getProductName().toLowerCase();
BufferedReader bufferedReader=null;
BufferedWriter bufferedWriter=null;
String currentEntry=StringUtils.EMPTY;
try {
if (!locationsFile.exists()) {
locationsFile.createNewFile();
}
else {
String line;
bufferedReader=new BufferedReader(new FileReader(locationsFile));
while ((line=bufferedReader.readLine()) != null) {
final String[] entry=line.split(CSV_COMMA);
if (entry.length == 2) {
if (ideName.equals(entry[0])) {
currentEntry=entry[1];
}
locationEntries.put(entry[0],entry[1]);
}
}
bufferedReader.close();
}
if (!currentEntry.equals(currentLocation) && !currentLocation.isEmpty()) {
if (!currentEntry.isEmpty()) {
locationEntries.remove(ideName);
}
locationEntries.put(ideName,currentLocation);
bufferedWriter=new BufferedWriter(new FileWriter(locationsFile.getPath()));
for ( String key : locationEntries.keySet()) {
bufferedWriter.write(key + CSV_COMMA + locationEntries.get(key)+ "\n");
}
bufferedWriter.close();
}
}
catch ( FileNotFoundException e) {
logger.warn("A FileNotFoundException was caught while trying to cache the IDE location",e);
}
catch ( IOException e) {
logger.warn("An IOException was caught while trying to cache the IDE location",e);
}
catch ( Exception e) {
logger.warn("An Exception was caught while trying to cache the IDE location",e);
}
finally {
try {
if (bufferedReader != null) {
bufferedReader.close();
}
if (bufferedWriter != null) {
bufferedWriter.close();
}
}
catch ( IOException e) {
logger.warn("An IOException was caught while trying to close the buffered reader/writer",e);
}
}
}
| Create the locations.csv file if it doesn't exist or check it for the IDE location. If no location is found or they mismatch, insert the new location into the file. |
public Uri addVideoSharing(String sharingId,ContactId contact,Direction direction,VideoContent content,VideoSharing.State state,VideoSharing.ReasonCode reasonCode,long timestamp){
if (logger.isActivated()) {
logger.debug("Add new video sharing for contact " + contact + ": sharingId="+ sharingId+ ", state="+ state+ ", reasonCode="+ reasonCode);
}
ContentValues values=new ContentValues();
values.put(VideoSharingData.KEY_SHARING_ID,sharingId);
values.put(VideoSharingData.KEY_CONTACT,contact.toString());
values.put(VideoSharingData.KEY_DIRECTION,direction.toInt());
values.put(VideoSharingData.KEY_STATE,state.toInt());
values.put(VideoSharingData.KEY_REASON_CODE,reasonCode.toInt());
values.put(VideoSharingData.KEY_TIMESTAMP,timestamp);
values.put(VideoSharingData.KEY_DURATION,0);
values.put(VideoSharingData.KEY_VIDEO_ENCODING,content.getEncoding());
values.put(VideoSharingData.KEY_WIDTH,content.getWidth());
values.put(VideoSharingData.KEY_HEIGHT,content.getHeight());
return mLocalContentResolver.insert(VideoSharingData.CONTENT_URI,values);
}
| Add a new video sharing in the call history |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-09-03 14:59:48.435 -0400",hash_original_method="23C617289A8DDF6F6B3FD3C27ABAC8B4",hash_generated_method="563DF64068815DA3B76300343AB1AD9F") public RefinedSoundex(){
this(US_ENGLISH_MAPPING);
}
| Creates an instance of the RefinedSoundex object using the default US English mapping. |
public void write(OutputStream out) throws TransformerException {
write(out,(Integer)null);
}
| Writes the xCal document to an output stream. |
public static float intersectRayTriangleFront(Vector3fc origin,Vector3fc dir,Vector3fc v0,Vector3fc v1,Vector3fc v2,float epsilon){
return intersectRayTriangleFront(origin.x(),origin.y(),origin.z(),dir.x(),dir.y(),dir.z(),v0.x(),v0.y(),v0.z(),v1.x(),v1.y(),v1.z(),v2.x(),v2.y(),v2.z(),epsilon);
}
| Determine whether the ray with the given <code>origin</code> and the given <code>dir</code> intersects the frontface of the triangle consisting of the three vertices <code>v0</code>, <code>v1</code> and <code>v2</code> and return the value of the parameter <i>t</i> in the ray equation <i>p(t) = origin + t * dir</i> of the point of intersection. <p> This is an implementation of the <a href="http://www.cs.virginia.edu/~gfx/Courses/2003/ImageSynthesis/papers/Acceleration/Fast%20MinimumStorage%20RayTriangle%20Intersection.pdf"> Fast, Minimum Storage Ray/Triangle Intersection</a> method. <p> This test implements backface culling, that is, it will return <code>false</code> when the triangle is in clockwise winding order assuming a <i>right-handed</i> coordinate system when seen along the ray's direction, even if the ray intersects the triangle. This is in compliance with how OpenGL handles backface culling with default frontface/backface settings. |
public void testRemoveQuotes(){
assertEquals(null,Utils.removeQuotes(null));
assertEquals("",Utils.removeQuotes(""));
assertEquals("",Utils.removeQuotes(" "));
assertEquals("a",Utils.removeQuotes("a"));
assertEquals("one",Utils.removeQuotes(" \u2018one\' "));
assertEquals("two",Utils.removeQuotes("`two\u2019 "));
assertEquals("three",Utils.removeQuotes("\u201Cthree\u00B4"));
assertEquals("four",Utils.removeQuotes("\"four\u201D\""));
assertEquals("five",Utils.removeQuotes("\"\'\u0060\u00B4five\u00B4\u0060\'\""));
}
| Test the removeQuotes() method. |
public static SortedSet<String> extractOutcomeLabelsFromFeatureVectorFiles(File... files) throws IOException {
SortedSet<String> result=new TreeSet<>();
for ( File file : files) {
result.addAll(extractOutcomeLabels(file));
}
return result;
}
| Extract all outcomes from featureVectorsFiles (training, test) that are in LIBSVM format - each line is a feature vector and the first token is the outcome label |
public ResultSetTableModel(ResultSet rs,int rows){
super();
m_Listeners=new HashSet<TableModelListener>();
m_Helper=new ResultSetHelper(rs,rows);
m_Data=m_Helper.getCells();
}
| initializes the model, retrieves only the given amount of rows (0 means all). |
public static Drawable decideIcon(ImageHolder imageHolder,Context ctx,int iconColor,boolean tint){
if (imageHolder == null) {
return null;
}
else {
return imageHolder.decideIcon(ctx,iconColor,tint);
}
}
| a small static helper which catches nulls for us |
static void addTemporalLevelConstraintToConstants(HashSet params,SetOfLevelConstraints constrs){
Iterator iter=params.iterator();
while (iter.hasNext()) {
LevelNode node=(LevelNode)iter.next();
if (node.getKind() == ConstantDeclKind) {
constrs.put(node,Levels[ActionLevel]);
}
;
}
}
| The following method adds to constrs a level constaint that the level of C < TemporalLevel for every declared CONSTANT C in the set params of nodes. * Called when level checking an ASSUME statement or an ASSUME/PROVE to prevent a declared constant that appears in it from being instantiated by a temporal formula. Added by LL on 1 Mar 2009 |
public static byte[] toByteArray(Bitmap bitmap,Bitmap.CompressFormat format,int quality){
ByteArrayOutputStream out=null;
try {
out=new ByteArrayOutputStream();
bitmap.compress(format,quality,out);
return out.toByteArray();
}
finally {
CloseableUtils.close(out);
}
}
| Compress the bitmap to the byte array as the specified format and quality. |
public static Vector2 toVector2(Vector3 o){
return new Vector2(o.x,o.z);
}
| Returns a Vector2 object using the X and Z values of the given Vector3. The x of the Vector3 becomes the x of the Vector2, and the z of this Vector3 becomes the y of the Vector2m. |
@Override public int size(){
return map.size();
}
| Returns the number of elements in this set (its cardinality). |
public boolean remove(int val){
if (!keyMap.containsKey(val)) {
return false;
}
else {
int valueKey=keyMap.get(val);
keyMap.remove(val);
if (valueKey != valueMap.size() - 1) {
valueMap.put(valueKey,valueMap.get(valueMap.size() - 1));
keyMap.put(valueMap.get(valueMap.size() - 1),valueKey);
valueMap.remove(valueMap.size() - 1);
}
else {
valueMap.remove(valueKey);
}
count=keyMap.size();
return true;
}
}
| Removes a value from the set. Returns true if the set contained the specified element. |
public Bundler putFloatArray(String key,float[] value){
bundle.putFloatArray(key,value);
return this;
}
| Inserts a float array value into the mapping of this Bundle, replacing any existing value for the given key. Either key or value may be null. |
public static boolean isJavaFile(IResource resource){
if (resource == null || (resource.getType() != IResource.FILE)) {
return false;
}
String ex=resource.getFileExtension();
return "java".equalsIgnoreCase(ex);
}
| Checks whether the given resource is a Java source file. |
public boolean isVarargs(){
if (this.modifiers == null) {
unsupportedIn2();
}
return this.variableArity;
}
| Returns whether this declaration declares the last parameter of a variable arity method (added in JLS3 API). <p> Note that the binding for the type <code>Foo</code>in the vararg method declaration <code>void fun(Foo... args)</code> is always for the type as written; i.e., the type binding for <code>Foo</code>. However, if you navigate from the method declaration to its method binding to the type binding for its last parameter, the type binding for the vararg parameter is always an array type (i.e., <code>Foo[]</code>) reflecting the way vararg methods get compiled. </p> |
public static void run(AdSenseHost service,String callbackToken) throws Exception {
System.out.println("=================================================================");
System.out.println("Verifying association session");
System.out.println("=================================================================");
AssociationSession associationSession=service.associationsessions().verify(callbackToken).execute();
System.out.printf("Association for account \"%s\" has status \"%s\" and ID \"%s\".\n",associationSession.getAccountId(),associationSession.getStatus(),associationSession.getId());
System.out.println();
}
| Runs this sample. |
public synchronized long size(){
return size;
}
| Returns the number of bytes currently being used to store the values in this cache. This may be greater than the max size if a background deletion is pending. |
static ConstantSize valueOf(String encodedValueAndUnit,boolean horizontal){
String[] split=ConstantSize.splitValueAndUnit(encodedValueAndUnit);
String encodedValue=split[0];
String encodedUnit=split[1];
Unit unit=Unit.valueOf(encodedUnit,horizontal);
double value=Double.parseDouble(encodedValue);
if (unit.requiresIntegers) {
checkArgument(value == (int)value,"%s value %s must be an integer.",unit,encodedValue);
}
return new ConstantSize(value,unit);
}
| Creates and returns a ConstantSize from the given encoded size and unit description. |
public static byte[] decode(String encoded) throws CoderException {
return Base64Encoder.decode(encoded);
}
| decodes a Base64 String to a Plain String |
public boolean isClosed(){
return journalWriter == null;
}
| Returns true if this cache has been closed. |
@Override public void readSettings(){
SharedPreferences sharedPreferences=this.getSharedPreferences(getString(R.string.sp_widget_clock_day_setting),Context.MODE_PRIVATE);
setLocation(new Location(sharedPreferences.getString(getString(R.string.key_location),getString(R.string.local)),null));
Location location=DatabaseHelper.getInstance(this).searchLocation(getLocation());
if (location != null) {
setLocation(location);
}
}
| <br> life cycle. |
@Override public void process(V tuple){
nval+=tuple.doubleValue();
}
| Adds to the numerator value |
public boolean isCanContainNotifications(){
return canContainNotifications;
}
| Ruft den Wert der canContainNotifications-Eigenschaft ab. |
private boolean removePermitted(Collection removeInstances){
for ( Object removeInstance : removeInstances) {
Entity next=(Entity)removeInstance;
if (!removePermitted(next.getMetaClass())) return false;
}
return true;
}
| Checks if the user have permissions to remove all of the requested entities. |
public int normalize(int dimensions,double value,double min,double max){
if (value < min || value > max) {
throw new IllegalArgumentException(min + "<" + value+ "<"+ max);
}
double x=(value - min) / (max - min);
return (int)(x * getMaxValue(dimensions));
}
| Normalize a value so that it is between the minimum and maximum for the given number of dimensions. |
void flush(VcfWriter writer) throws IOException {
if (mPrevRecord != null) {
if (!mPrevDense) {
writeCount(writer,mPrevRecord);
}
else {
mVcfFilterStatistics.increment(Stat.DENSITY_WINDOW_COUNT);
}
}
mPrevRecord=null;
mPrevDense=false;
}
| Writes any remaining SNP lines |
public void skip() throws Exception {
reader.skipElement(this);
}
| This method is used to skip all child elements from this element. This allows elements to be effectively skipped such that when parsing a document if an element is not required then that element can be completely removed from the XML. |
public LongAdder(){
}
| Creates a new adder with initial sum of zero. |
public boolean doAccessibleAction(int i){
if (i < 0 || i >= getAccessibleActionCount()) {
return false;
}
AccessibleContext ac=getCurrentAccessibleContext();
if (i == 0) {
if (JTree.this.isExpanded(path)) {
JTree.this.collapsePath(path);
}
else {
JTree.this.expandPath(path);
}
return true;
}
else if (ac != null) {
AccessibleAction aa=ac.getAccessibleAction();
if (aa != null) {
return aa.doAccessibleAction(i - 1);
}
}
return false;
}
| Perform the specified Action on the tree node. If this node is not a leaf, there is at least one action which can be done (toggle expand), in addition to any available on the object behind the TreeCellRenderer. |
private static HashSet<IAddress> fillJumpTargets(final Collection<ReilInstruction> reilInstructions){
final HashSet<IAddress> jumpTargets=new HashSet<IAddress>();
for ( final ReilInstruction reilInstruction : reilInstructions) {
if (reilInstruction.getMnemonic().equals(ReilHelpers.OPCODE_JCC)) {
final String jumpTarget=reilInstruction.getThirdOperand().getValue();
if (Convert.isDecString(jumpTarget)) {
jumpTargets.add(toReilAddress(jumpTarget));
}
else if (reilInstruction.getThirdOperand().getType() == OperandType.SUB_ADDRESS) {
jumpTargets.add(toReilAddress(jumpTarget.split("\\.")));
}
}
}
return jumpTargets;
}
| Takes a list of REIL instructions and tries to deduces as many jump targets as possible from them. |
@Override public void run(){
try {
sendHeartbeat(false);
}
catch ( Exception e) {
log.error("Error to process heartbeat: ",e);
}
}
| Called by scheduler. |
@Override public DriverTask createVolumeSnapshot(List<VolumeSnapshot> snapshots,StorageCapabilities storageCapabilities){
LOG.info("Creating {} snapshots...",snapshots.size());
return snapshotHelper.createVolumeSnapshot(snapshots,storageCapabilities);
}
| Create volume snapshots. |
public boolean hasFilterSupplier(){
return this.filterSupplier != null;
}
| If this method will contain a "Filter check" after being routed through the Filter object. |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 13:01:08.183 -0500",hash_original_method="9CCB74C876B98AB8C259B415A5496084",hash_generated_method="C9DBF3B4EDCAC34471E10F51BA381E6E") public void invalidate(){
isValid=false;
sessionContext=null;
}
| It invalidates a SSL session forbidding any resumption. |
static public void assertTrue(boolean condition){
assertTrue(null,condition);
}
| Asserts that a condition is true. If it isn't it throws an AssertionFailedError. |
private void buildTree(int left,int right,int axis,SortDBIDsBySingleDimension comp){
int middle=(left + right) >>> 1;
comp.setDimension(axis);
QuickSelectDBIDs.quickSelect(sorted,comp,left,right,middle);
final int next=(axis + 1) % dims;
if (left + leafsize < middle) {
buildTree(left,middle,next,comp);
}
++middle;
if (middle + leafsize < right) {
buildTree(middle,right,next,comp);
}
}
| Recursively build the tree by partial sorting. O(n log n) complexity. Apparently there exists a variant in only O(n log log n)? Please contribute! |
public static String convertForStoring(ClassAndVariables cam){
StringBuilder sb=new StringBuilder(150);
sb.append(cam.dclass.fullyQualifiedName());
sb.append(',').append(cam.hasSerialVersionUID);
if (cam.hasSerialVersionUID) {
sb.append(',').append(cam.serialVersionUID);
}
List<CompiledField> fields=new ArrayList<CompiledField>(cam.variables.values());
Collections.sort(fields);
for ( CompiledField field : fields) {
sb.append(',').append(field.name()).append(':').append(field.descriptor());
}
return sb.toString();
}
| convert a ClassAndMethods into a string that can then be used to instantiate a ClassAndVariableDetails |
public PartialTrie(final Iterable<? extends T> elements,final int log2BucketSize,final TransformationStrategy<? super T> transformationStrategy,final ProgressLogger pl){
Iterator<? extends T> iterator=elements.iterator();
Node node;
LongArrayBitVector curr=LongArrayBitVector.getInstance();
int pos, prefix;
int bucketMask=(1 << log2BucketSize) - 1;
if (iterator.hasNext()) {
pl.start("Building trie...");
LongArrayBitVector prev=LongArrayBitVector.copy(transformationStrategy.toBitVector(iterator.next()));
pl.lightUpdate();
LongArrayBitVector prevDelimiter=LongArrayBitVector.getInstance();
long count=1;
Node root=null;
long maxLength=prev.length();
while (iterator.hasNext()) {
curr.replace(transformationStrategy.toBitVector(iterator.next()));
pl.lightUpdate();
prefix=(int)curr.longestCommonPrefixLength(prev);
if (prefix == prev.length() && prefix == curr.length()) throw new IllegalArgumentException("The input bit vectors are not distinct");
if (prefix == prev.length() || prefix == curr.length()) throw new IllegalArgumentException("The input bit vectors are not prefix-free");
if (prev.getBoolean(prefix)) throw new IllegalArgumentException("The input bit vectors are not lexicographically sorted");
if ((count & bucketMask) == 0) {
if (root == null) {
root=new Node(null,null,prev.copy());
prevDelimiter.replace(prev);
}
else {
prefix=(int)prev.longestCommonPrefixLength(prevDelimiter);
pos=0;
node=root;
Node n=null;
while (node != null) {
final long pathLength=node.path.length();
if (prefix < pathLength) {
n=new Node(node.left,node.right,node.path.copy(prefix + 1,pathLength));
node.path.length(prefix);
node.path.trim();
node.left=n;
node.right=new Node(null,null,prev.copy(pos + prefix + 1,prev.length()));
break;
}
prefix-=pathLength + 1;
pos+=pathLength + 1;
node=node.right;
if (ASSERTS) assert node == null || prefix >= 0 : prefix + " <= " + 0;
}
if (ASSERTS) assert node != null;
prevDelimiter.replace(prev);
}
}
prev.replace(curr);
maxLength=Math.max(maxLength,prev.length());
count++;
}
pl.done();
this.root=root;
if (root != null) {
if (ASSERTS) {
iterator=elements.iterator();
long c=1;
while (iterator.hasNext()) {
curr.replace(transformationStrategy.toBitVector(iterator.next()));
if ((c++ & bucketMask) == 0) {
if (!iterator.hasNext()) break;
node=root;
pos=0;
while (node != null) {
prefix=(int)curr.subVector(pos).longestCommonPrefixLength(node.path);
assert prefix == node.path.length() : "Error at delimiter " + (c - 1) / (1 << log2BucketSize);
pos+=node.path.length() + 1;
if (pos <= curr.length()) node=curr.getBoolean(pos - 1) ? node.right : node.left;
else {
assert node.left == null && node.right == null;
break;
}
}
}
}
}
pl.expectedUpdates=count;
pl.start("Reducing paths...");
iterator=elements.iterator();
final Node stack[]=new Node[(int)maxLength];
final int[] len=new int[(int)maxLength];
stack[0]=root;
int last=0;
boolean first=true;
while (iterator.hasNext()) {
curr.replace(transformationStrategy.toBitVector(iterator.next()));
pl.lightUpdate();
if (!first) {
prefix=(int)prev.longestCommonPrefixLength(curr);
while (last > 0 && len[last] > prefix) last--;
}
else first=false;
node=stack[last];
pos=len[last];
for (; ; ) {
final LongArrayBitVector path=node.path;
prefix=(int)curr.subVector(pos).longestCommonPrefixLength(path);
if (prefix < path.length()) {
if (path.getBoolean(prefix)) node.prefixLeft=prefix;
else if (node.prefixRight == MAX_PREFIX) node.prefixRight=prefix;
break;
}
pos+=path.length() + 1;
if (pos > curr.length()) break;
node=curr.getBoolean(pos - 1) ? node.right : node.left;
len[++last]=pos;
stack[last]=node;
}
prev.replace(curr);
}
pl.done();
}
}
else {
this.root=null;
}
}
| Creates a partial compacted trie using given elements, bucket size and transformation strategy. |
protected StateType attemptSetState(Set<StateType> prerequisiteState,StateType newState){
if (prerequisiteState == null || newState == null) throw new IllegalArgumentException("null arg");
return setState(newState,null,prerequisiteState);
}
| Attempts to change the state. The state will be changed only if current state is one of the expected states. |
private final void resetTokenMark(int mark){
int qsz=m_compiler.getTokenQueueSize();
m_processor.m_queueMark=(mark > 0) ? ((mark <= qsz) ? mark - 1 : mark) : 0;
if (m_processor.m_queueMark < qsz) {
m_processor.m_token=(String)m_compiler.getTokenQueue().elementAt(m_processor.m_queueMark++);
m_processor.m_tokenChar=m_processor.m_token.charAt(0);
}
else {
m_processor.m_token=null;
m_processor.m_tokenChar=0;
}
}
| Reset token queue mark and m_token to a given position. |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-09-03 15:00:56.807 -0400",hash_original_method="1DF5A4F82AD71DE648728A6F6545B094",hash_generated_method="EB053A6377C6B19C32A3194D9A8E16A3") @Override public void putNextEntry(ZipEntry ze) throws IOException {
super.putNextEntry(ze);
}
| Writes the specified ZIP entry to the underlying stream. The previous entry is closed if it is still open. |
public boolean attemptRequest(String url,String stream){
synchronized (pendingRequest) {
if (!pendingRequest.containsKey(url)) {
pendingRequest.put(url,stream);
return true;
}
return false;
}
}
| Checks if a request with the given url can be made. Returns true if no request with that url is currently waiting for a response, false otherwise. This also saves the stream this request url is associated with, so it can more easily be retrieved when the reponse comes in. |
@SkipValidation private void prepareDisplayInfo(){
if (LOGGER.isDebugEnabled()) LOGGER.debug("Entered into method prepareDisplayInfo");
dcbDispInfo=new DCBDisplayInfo();
dcbDispInfo.setReasonCategoryCodes(Collections.<String>emptyList());
List<String> reasonList=new ArrayList<String>();
reasonList.addAll(DEMAND_REASON_ORDER_MAP.keySet());
dcbDispInfo.setReasonMasterCodes(reasonList);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("DCB Display Info : " + dcbDispInfo);
LOGGER.debug("Number of Demand Reasons : " + (reasonList != null ? reasonList.size() : ZERO));
LOGGER.debug("Exit from method prepareDisplayInfo");
}
}
| To set DcbDispInfo with ReasonCategoryCodes as Tax and Penalty. Here reasonMasterCodes could also be set to DcbDispInfo. |
@Override public Map<String,Model> unmarshal(ModelsType modelsType){
Map<String,Model> map=new HashMap<String,Model>();
for ( Model m : modelsType.getModels()) {
map.put(m.getKey(),m);
}
return map;
}
| Map XML type to Java |
public static Intent createTagShareIntent(Context context,String tagName,String category,String appDownloadLink){
final String messageShare=context.getString(R.string.share_tag_message_format,tagName,category,appDownloadLink);
return createShareIntentForTag(context,messageShare);
}
| Creates an intent for sharing the app |
public void execute() throws Exception {
execute(true,true);
}
| generates the props-file for the GenericObjectEditor and stores it |
protected static String decode(String url){
StringBuilder stringBuilder=new StringBuilder(url);
Stack<Integer> nonDecodedPercentIndices=new Stack<Integer>();
int i=0;
while (i < stringBuilder.length() - 2) {
char curr=stringBuilder.charAt(i);
if (curr == '%') {
if (CharUtils.isHex(stringBuilder.charAt(i + 1)) && CharUtils.isHex(stringBuilder.charAt(i + 2))) {
char decodedChar=String.format("%s",(char)Short.parseShort(stringBuilder.substring(i + 1,i + 3),16)).charAt(0);
stringBuilder.delete(i,i + 3);
stringBuilder.insert(i,decodedChar);
if (decodedChar == '%') {
i--;
}
else if (!nonDecodedPercentIndices.isEmpty() && CharUtils.isHex(decodedChar) && CharUtils.isHex(stringBuilder.charAt(i - 1))&& i - nonDecodedPercentIndices.peek() == 2) {
i=nonDecodedPercentIndices.pop() - 1;
}
else if (!nonDecodedPercentIndices.isEmpty() && i == stringBuilder.length() - 2) {
i=nonDecodedPercentIndices.pop() - 1;
}
}
else {
nonDecodedPercentIndices.add(i);
}
}
i++;
}
return stringBuilder.toString();
}
| Decodes the url by iteratively removing hex characters with backtracking. For example: %2525252525252525 becomes % |
public void findAndUndo(Object someObj){
if (someObj instanceof LayerHandler) {
logger.fine("LayersPanel removing LayerHandler");
if (getLayerHandler() == (LayerHandler)someObj) {
setLayerHandler(null);
}
}
if (controls != null && someObj != this) {
controls.findAndUndo(someObj);
}
if (someObj instanceof Layer) {
paneLookUp.remove((Layer)someObj);
}
}
| BeanContextMembershipListener method. Called when an object has been removed from the parent BeanContext. If a LayerHandler is removed, and it's the current one being listened to, then the layers in the panel will be wiped clean. |
private List<OozieWorkflowJob> retrieveOozieJobs(String clusterId) throws Exception {
String masterIpAddress=getEmrClusterMasterIpAddress(clusterId);
int jobsToInclude=herdStringHelper.getConfigurationValueAsInteger(ConfigurationValue.EMR_OOZIE_JOBS_TO_INCLUDE_IN_CLUSTER_STATUS);
List<WorkflowJob> jobsFound=oozieDao.getRunningEmrOozieJobsByName(masterIpAddress,OozieDaoImpl.HERD_OOZIE_WRAPPER_WORKFLOW_NAME,1,jobsToInclude);
List<OozieWorkflowJob> oozieWorkflowJobs=new ArrayList<>();
for ( WorkflowJob workflowJob : jobsFound) {
WorkflowAction clientWorkflowAction=emrHelper.getClientWorkflowAction(workflowJob);
OozieWorkflowJob resultOozieWorkflowJob=new OozieWorkflowJob();
resultOozieWorkflowJob.setId(workflowJob.getId());
if (clientWorkflowAction == null) {
resultOozieWorkflowJob.setStatus(OozieDaoImpl.OOZIE_WORKFLOW_JOB_STATUS_DM_PREP);
}
else {
resultOozieWorkflowJob.setStartTime(toXmlGregorianCalendar(clientWorkflowAction.getStartTime()));
resultOozieWorkflowJob.setStatus(workflowJob.getStatus().toString());
}
oozieWorkflowJobs.add(resultOozieWorkflowJob);
}
return oozieWorkflowJobs;
}
| Retrieves the List of running oozie workflow jobs on the cluster. |
@NoInline private static void arraycopyPiecemeal(int[] src,int srcIdx,int[] dst,int dstIdx,int len){
if (srcIdx < dstIdx) {
srcIdx+=len;
dstIdx+=len;
while (len-- != 0) {
dst[--dstIdx]=src[--srcIdx];
}
}
else {
while (len-- != 0) {
dst[dstIdx++]=src[srcIdx++];
}
}
}
| Perform element-by-element arraycopy for array of ints. Used when bulk copy is not possible. |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.