code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
@DSComment("From safe class list") @DSSafe(DSCat.SAFE_LIST) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:34:06.242 -0500",hash_original_method="F4780612A05468EA5B4971365E65F2E9",hash_generated_method="3CA9ECB8B6579E2ED02777D3C810F04C") public boolean quickContains(int left,int top,int right,int bottom){
return (((left + right + top+ bottom+ getTaintInt())) == 1);
}
| Return true if the region is a single rectangle (not complex) and it contains the specified rectangle. Returning false is not a guarantee that the rectangle is not contained by this region, but return true is a guarantee that the rectangle is contained by this region. |
public void damageReport(VisualItem item,Rectangle2D region){
for (int i=0; i < m_displays.size(); ++i) {
Display d=getDisplay(i);
if (d.getPredicate().getBoolean(item)) {
d.damageReport(region);
}
}
}
| Report damage to associated displays, indicating a region that will need to be redrawn. |
public static String httpEngine(HttpServletRequest request,HttpServletResponse response){
LocalDispatcher dispatcher=(LocalDispatcher)request.getAttribute("dispatcher");
Delegator delegator=(Delegator)request.getAttribute("delegator");
String serviceName=request.getParameter("serviceName");
String serviceMode=request.getParameter("serviceMode");
String xmlContext=request.getParameter("serviceContext");
Map<String,Object> result=new HashMap<String,Object>();
Map<String,Object> context=null;
if (serviceName == null) result.put(ModelService.ERROR_MESSAGE,"Cannot have null service name");
if (serviceMode == null) serviceMode="SYNC";
if (!result.containsKey(ModelService.ERROR_MESSAGE)) {
if (xmlContext != null) {
try {
Object o=XmlSerializer.deserialize(xmlContext,delegator);
if (o instanceof Map<?,?>) context=UtilGenerics.checkMap(o);
else {
Debug.logError("Context not an instance of Map error",module);
result.put(ModelService.ERROR_MESSAGE,"Context not an instance of Map");
}
}
catch ( Exception e) {
Debug.logError(e,"Deserialization error",module);
result.put(ModelService.ERROR_MESSAGE,"Error occurred deserializing context: " + e.toString());
}
}
}
if (!result.containsKey(ModelService.ERROR_MESSAGE)) {
try {
ModelService model=dispatcher.getDispatchContext().getModelService(serviceName);
if (model.export || exportAll) {
if (serviceMode.equals("ASYNC")) {
dispatcher.runAsync(serviceName,context);
}
else {
result=dispatcher.runSync(serviceName,context);
}
}
else {
Debug.logWarning("Attempt to invoke a non-exported service: " + serviceName,module);
throw new GenericServiceException("Cannot find requested service");
}
}
catch ( GenericServiceException e) {
Debug.logError(e,"Service invocation error",module);
result.put(ModelService.ERROR_MESSAGE,"Service invocation error: " + e.toString());
}
}
StringBuilder errorMessage=new StringBuilder();
String resultString=null;
try {
resultString=XmlSerializer.serialize(result);
}
catch ( Exception e) {
Debug.logError(e,"Cannot serialize result",module);
if (result.containsKey(ModelService.ERROR_MESSAGE)) errorMessage.append(result.get(ModelService.ERROR_MESSAGE));
errorMessage.append("::");
errorMessage.append(e);
}
try {
PrintWriter out=response.getWriter();
response.setContentType("plain/text");
if (errorMessage.length() > 0) {
response.setContentLength(errorMessage.length());
out.write(errorMessage.toString());
}
else {
response.setContentLength(resultString.length());
out.write(resultString);
}
out.flush();
response.flushBuffer();
}
catch ( IOException e) {
Debug.logError(e,"Problems w/ getting the servlet writer.",module);
return "error";
}
return null;
}
| Event for handling HTTP services |
public ColladaMaterial(String ns){
super(ns);
}
| Construct an instance. |
protected void layoutContainer(){
Rectangle inBounds=p.getBounds();
Insets insets=p.getInsets();
inBounds.x+=insets.left;
inBounds.width-=insets.left;
inBounds.width-=insets.right;
inBounds.y+=insets.top;
inBounds.height-=insets.top;
inBounds.height-=insets.bottom;
backgroundBounds=(Rectangle)inBounds.clone();
occludingBounds=(Rectangle)inBounds.clone();
layoutCardinals();
layoutEast(p.getEast(),occludingBounds.x + occludingBounds.width,occludingBounds.y,occludingBounds.width,occludingBounds.height);
layoutWest(p.getWest(),occludingBounds.x,occludingBounds.y,occludingBounds.width,occludingBounds.height);
int southLeft=inBounds.x + getWidthAtYCardinal(p.getWest(),inBounds.y + inBounds.height - getHeightAtLeftCardinal(p.getSouth()));
int southRight=inBounds.x + inBounds.width - getWidthAtYCardinal(p.getEast(),inBounds.y + inBounds.height - getHeightAtRightCardinal(p.getSouth()));
layoutSouth(p.getSouth(),southLeft,occludingBounds.y + occludingBounds.height,southRight - southLeft,occludingBounds.height);
int northLeft=inBounds.x + getWidthAtYCardinal(p.getWest(),inBounds.y + getHeightAtLeftCardinal(p.getNorth()));
int northRight=inBounds.x + inBounds.width - getWidthAtYCardinal(p.getEast(),inBounds.y + getHeightAtRightCardinal(p.getNorth()));
layoutNorth(p.getNorth(),northLeft,occludingBounds.y,northRight - northLeft,occludingBounds.height);
layoutBackground();
}
| Layout the entire container. |
@Override public double nextPathAvailable(){
if (pathQueue.size() == 0) {
return latestPathStartTime;
}
else {
return pathQueue.element().getKey();
}
}
| Returns a sim time when the next path is available. |
private int readField(final ClassVisitor classVisitor,final Context context,int u){
char[] c=context.buffer;
int access=readUnsignedShort(u);
String name=readUTF8(u + 2,c);
String desc=readUTF8(u + 4,c);
u+=6;
String signature=null;
int anns=0;
int ianns=0;
Object value=null;
Attribute attributes=null;
for (int i=readUnsignedShort(u); i > 0; --i) {
String attrName=readUTF8(u + 2,c);
if ("ConstantValue".equals(attrName)) {
int item=readUnsignedShort(u + 8);
value=item == 0 ? null : readConst(item,c);
}
else if (SIGNATURES && "Signature".equals(attrName)) {
signature=readUTF8(u + 8,c);
}
else if ("Deprecated".equals(attrName)) {
access|=Opcodes.ACC_DEPRECATED;
}
else if ("Synthetic".equals(attrName)) {
access|=Opcodes.ACC_SYNTHETIC | ClassWriter.ACC_SYNTHETIC_ATTRIBUTE;
}
else if (ANNOTATIONS && "RuntimeVisibleAnnotations".equals(attrName)) {
anns=u + 8;
}
else if (ANNOTATIONS && "RuntimeInvisibleAnnotations".equals(attrName)) {
ianns=u + 8;
}
else {
Attribute attr=readAttribute(context.attrs,attrName,u + 8,readInt(u + 4),c,-1,null);
if (attr != null) {
attr.next=attributes;
attributes=attr;
}
}
u+=6 + readInt(u + 4);
}
u+=2;
FieldVisitor fv=classVisitor.visitField(access,name,desc,signature,value);
if (fv == null) {
return u;
}
if (ANNOTATIONS && anns != 0) {
for (int i=readUnsignedShort(anns), v=anns + 2; i > 0; --i) {
v=readAnnotationValues(v + 2,c,true,fv.visitAnnotation(readUTF8(v,c),true));
}
}
if (ANNOTATIONS && ianns != 0) {
for (int i=readUnsignedShort(ianns), v=ianns + 2; i > 0; --i) {
v=readAnnotationValues(v + 2,c,true,fv.visitAnnotation(readUTF8(v,c),false));
}
}
while (attributes != null) {
Attribute attr=attributes.next;
attributes.next=null;
fv.visitAttribute(attributes);
attributes=attr;
}
fv.visitEnd();
return u;
}
| Reads a field and makes the given visitor visit it. |
public List<String> hvals(final String key){
checkIsInMulti();
client.hvals(key);
final List<String> lresult=client.getMultiBulkReply();
return lresult;
}
| Return all the values in a hash. <p> <b>Time complexity:</b> O(N), where N is the total number of entries |
public STAXEventWriter(XMLEventConsumer consumer){
this.consumer=consumer;
}
| Constructs a <code>STAXEventWriter</code> that writes events to the provided event stream. |
public MockSpamd(int port) throws IOException {
socket=new ServerSocket(port);
}
| Init the mocked SPAMD daemon |
private boolean isIdentifierStartChar(){
return isIdentifierStartChar(_pos);
}
| Checks if character at current runtime position can be identifier start. |
public boolean isAnonymousVisible(){
return anonymousVisible;
}
| Returns whether the service represented by this entry is visible in the catalog to users who are not logged in. |
protected void onPeerFailure(Json msg){
HGPeerIdentity id=getThisPeer().getIdentity(getSender(msg));
this.future.result.exception=new ExceptionAtPeer(id,msg.at(CONTENT).asString());
getState().assign(WorkflowState.Failed);
}
| <p> Called by default by the framework in case a peer send a <code>Failure</code> performative and there's no transition defined for it. </p> <p> The default implementation of this method is to fail the whole activity. To change this behavior, you can either define appropriate transition for the <code>Failure</code> performative or simply override this method in your activity class. </p> |
public static void reverse(byte[] array){
int len=array.length - 1;
int len2=array.length / 2;
for (int i=0; i < len2; i++) {
byte tmp=array[i];
array[i]=array[len - i];
array[len - i]=tmp;
}
}
| Reverses the item order of the supplied byte array. |
public static void encodeFileToFile(String infile,String outfile) throws java.io.IOException {
String encoded=Base64.encodeFromFile(infile);
java.io.OutputStream out=null;
try {
out=new java.io.BufferedOutputStream(new java.io.FileOutputStream(outfile));
out.write(encoded.getBytes("US-ASCII"));
}
catch ( java.io.IOException e) {
throw e;
}
finally {
try {
out.close();
}
catch ( Exception ex) {
}
}
}
| Reads <tt>infile</tt> and encodes it to <tt>outfile</tt>. |
public static Map<Integer,Properties> collectProperties(Properties properties){
Map<Integer,Properties> ret=new HashMap<Integer,Properties>();
if (properties != null) {
for ( String name : properties.stringPropertyNames()) {
int index=getIndex(name);
if (index >= 0) {
Properties props=ret.get(index);
if (props == null) {
props=new Properties();
ret.put(index,props);
}
String newName=dropToken(name);
if (newName.length() > 0) {
props.setProperty(newName,properties.getProperty(name));
}
}
}
}
return ret;
}
| Collects Properties by the leading index. This means that the name of the properties must start with an Integer or else they are dropped. |
private void handleQuit(){
GUIMediator.applyWindowSettings();
GUIMediator.close(false);
}
| This method responds to a quit event by closing the application in the whichever method the user has configured (closing after completed file transfers by default). On OSX, this runs in a new ManagedThread to handle the possibility that event processing can become blocked if launched in the calling thread. |
private void writeAttribute(java.lang.String prefix,java.lang.String namespace,java.lang.String attName,java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
if (xmlWriter.getPrefix(namespace) == null) {
xmlWriter.writeNamespace(prefix,namespace);
xmlWriter.setPrefix(prefix,namespace);
}
xmlWriter.writeAttribute(namespace,attName,attValue);
}
| Util method to write an attribute with the ns prefix |
public TungstenProperties generateTHLParallelQueueProps(String schemaName,int channels) throws Exception {
prepareLogDir(schemaName);
PipelineConfigBuilder builder=new PipelineConfigBuilder();
builder.setProperty(ReplicatorConf.SERVICE_NAME,"test");
builder.setRole("master");
builder.setProperty(ReplicatorConf.METADATA_SCHEMA,schemaName);
builder.addPipeline("master","extract,feed,apply","thl,thl-queue");
builder.addStage("extract","dummy","thl-apply",null);
builder.addStage("feed","thl-extract","thl-queue-apply",null);
builder.addStage("apply","thl-queue-extract","dummy",null);
builder.addComponent("store","thl",THL.class);
builder.addProperty("store","thl","logDir",schemaName);
builder.addComponent("store","thl-queue",THLParallelQueue.class);
builder.addProperty("store","thl-queue","maxSize","5");
builder.addComponent("extractor","dummy",DummyExtractor.class);
builder.addProperty("extractor","dummy","nFrags","1");
builder.addComponent("applier","thl-apply",THLStoreApplier.class);
builder.addProperty("applier","thl-apply","storeName","thl");
builder.addComponent("extractor","thl-extract",THLStoreExtractor.class);
builder.addProperty("extractor","thl-extract","storeName","thl");
builder.addComponent("applier","thl-queue-apply",THLParallelQueueApplier.class);
builder.addProperty("applier","thl-queue-apply","storeName","thl-queue");
builder.addComponent("extractor","thl-queue-extract",THLParallelQueueExtractor.class);
builder.addProperty("extractor","thl-queue-extract","storeName","thl-queue");
builder.addComponent("applier","dummy",DummyApplier.class);
return builder.getConfig();
}
| Generate configuration properties for a three stage-pipeline that loads events into a THL then loads a parallel queue. Input is from a dummy extractor. |
private static final boolean compareAndSetNext(Node node,Node expect,Node update){
return unsafe.compareAndSwapObject(node,nextOffset,expect,update);
}
| CAS next field of a node. |
@VisibleForTesting protected void cancelAlarmOnSystem(Context context,PendingIntent operation){
AlarmManager alarmManager=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(operation);
}
| Cancel a previously set alarm on the system. This method can be overridden in tests. |
synchronized void initmessage(XNetReply l){
int oldState=internalState;
message(l);
internalState=oldState;
}
| initmessage is a package proteceted class which allows the Manger to send a feedback message at initilization without changing the state of the turnout with respect to whether or not a feedback request was sent. This is used only when the turnout is created by on layout feedback. |
private static String mungeName(String fname){
String result=fname;
result=result.replace("/",SLASH_SWAP);
return result;
}
| Some function names do not map into useful or even legal filenames. This method takes care of that. |
public Map<String,Object> next() throws IOException {
if (!atDocs) {
boolean found=advanceToDocs();
atDocs=true;
if (!found) return null;
}
int event=parser.nextEvent();
if (event == JSONParser.ARRAY_END) return null;
Object o=ObjectBuilder.getVal(parser);
return (Map<String,Object>)o;
}
| returns the next Tuple or null |
public SendMessageBatchResult sendMessageBatch(String queueUrl,List<SendMessageBatchRequestEntry> entries){
SendMessageBatchRequest sendMessageBatchRequest=new SendMessageBatchRequest(queueUrl,entries);
return sendMessageBatch(sendMessageBatchRequest);
}
| <p> Delivers up to ten messages to the specified queue. This is a batch version of SendMessage. The result of the send action on each message is reported individually in the response. Uploads message payloads to Amazon S3 when necessary. </p> <p> If the <code>DelaySeconds</code> parameter is not specified for an entry, the default for the queue is used. </p> <p> <b>IMPORTANT:</b>The following list shows the characters (in Unicode) that are allowed in your message, according to the W3C XML specification. For more information, go to http://www.faqs.org/rfcs/rfc1321.html. If you send any characters that are not included in the list, your request will be rejected. #x9 | #xA | #xD | [#x20 to #xD7FF] | [#xE000 to #xFFFD] | [#x10000 to #x10FFFF] </p> <p> <b>IMPORTANT:</b> Because the batch request can result in a combination of successful and unsuccessful actions, you should check for batch errors even when the call returns an HTTP status code of 200. </p> <p> <b>NOTE:</b>Some API actions take lists of parameters. These lists are specified using the param.n notation. Values of n are integers starting from 1. For example, a parameter list with two elements looks like this: </p> <p> <code>&Attribute.1=this</code> </p> <p> <code>&Attribute.2=that</code> </p> |
public MP3(File file){
this.file=file;
}
| Creates MP3 object using given file |
@Override public Future<DLSN> write(final LogRecord record){
final Stopwatch stopwatch=Stopwatch.createStarted();
return asyncWrite(record,true).addEventListener(new OpStatsListener<DLSN>(writeOpStatsLogger,stopwatch));
}
| Write a log record to the stream. |
public synchronized boolean containsAll(Collection c){
return super.containsAll(c);
}
| Returns true if this Vector contains all of the elements in the specified Collection. |
public static void e(String tag,String s){
if (LOG.ERROR >= LOGLEVEL) Log.e(tag,s);
}
| Error log message. |
public boolean isMatch(String input){
if (!isCaseSensitive) input=input.toLowerCase();
if (parts.length == 1) return (parts[0] == MATCH_ANY || parts[0].equals(input));
if (parts.length == 2) {
if (parts[0] == MATCH_ANY) return input.endsWith(parts[1]);
if (parts[parts.length - 1] == MATCH_ANY) return input.startsWith(parts[0]);
}
int pos=0;
int len=input.length();
boolean doMatchAny=false;
for ( String part : parts) {
if (part == MATCH_ANY) {
doMatchAny=true;
continue;
}
if (part == MATCH_ONE) {
doMatchAny=false;
pos++;
continue;
}
int ix=input.indexOf(part,pos);
if (ix == -1) return false;
if (!doMatchAny && ix != pos) return false;
pos=ix + part.length();
doMatchAny=false;
}
if ((parts[parts.length - 1] != MATCH_ANY) && (len != pos)) return false;
return true;
}
| tests if the input string matches the pattern |
public Person(){
this("Unknown","Unknown","Unknown","Unknown");
}
| Construct default Person object |
public static boolean isStrictfp(int flags){
return (flags & AccStrictfp) != 0;
}
| Returns whether the given integer includes the <code>strictfp</code> modifier. |
@Override public String index(){
return this.index;
}
| Returns index where failure occurred |
public static Color blend(Color color1,Color color2,double weight){
double w2=MathUtils.limit(weight,0.0,1.0);
double w1=1.0 - w2;
int r=(int)Math.round(w1 * color1.getRed() + w2 * color2.getRed());
int g=(int)Math.round(w1 * color1.getGreen() + w2 * color2.getGreen());
int b=(int)Math.round(w1 * color1.getBlue() + w2 * color2.getBlue());
int a=(int)Math.round(w1 * color1.getAlpha() + w2 * color2.getAlpha());
return new Color(r,g,b,a);
}
| Linearly blends two colors with a defined weight. |
private Cipher createRC4Cipher() throws NoSuchAlgorithmException, NoSuchPaddingException {
return Cipher.getInstance(CIPHER_RC4);
}
| Create a new RC4 cipher. Should always be available for supported platforms. |
public boolean equals(Object obj){
if (!(obj instanceof UseCandidateAttribute)) return false;
if (obj == this) return true;
UseCandidateAttribute useCandidateAtt=(UseCandidateAttribute)obj;
if (useCandidateAtt.getAttributeType() != getAttributeType() || useCandidateAtt.getDataLength() != getDataLength()) return false;
return true;
}
| Compares two STUN Attributes. Two attributes are considered equal when they have the same type, length and value. |
public long length() throws SerialException {
isValid();
return len;
}
| Retrieves the number of characters in this <code>SerialClob</code> object's array of characters. |
public String toString(){
StringBuilder stringBuilder=new StringBuilder();
stringBuilder.append(String.format("0x"));
for ( byte b : this.instance_uid) {
stringBuilder.append(String.format("%02x",b));
}
return stringBuilder.toString();
}
| toString() method |
static GLUhalfEdge MakeEdge(GLUhalfEdge eNext){
GLUhalfEdge e;
GLUhalfEdge eSym;
GLUhalfEdge ePrev;
e=new GLUhalfEdge(true);
eSym=new GLUhalfEdge(false);
if (!eNext.first) {
eNext=eNext.Sym;
}
ePrev=eNext.Sym.next;
eSym.next=ePrev;
ePrev.Sym.next=e;
e.next=eNext;
eNext.Sym.next=eSym;
e.Sym=eSym;
e.Onext=e;
e.Lnext=eSym;
e.Org=null;
e.Lface=null;
e.winding=0;
e.activeRegion=null;
eSym.Sym=e;
eSym.Onext=eSym;
eSym.Lnext=e;
eSym.Org=null;
eSym.Lface=null;
eSym.winding=0;
eSym.activeRegion=null;
return e;
}
| Utility Routines |
public void trimToSize(){
elements=cern.colt.Arrays.trimToCapacity(elements,size());
}
| Trims the capacity of the receiver to be the receiver's current size. Releases any superfluos internal memory. An application can use this operation to minimize the storage of the receiver. |
synchronized void storeTransaction(Transaction t){
if (t.getStatus() == Transaction.STATUS_PREPARED || t.getName() != null) {
Object[] v={t.getStatus(),t.getName()};
preparedTransactions.put(t.getId(),v);
}
}
| Store a transaction. |
public void addComponent(Component component) throws InvalidComponentException {
isComponentAddable(component);
components.add(component);
}
| Adds a component. |
public synchronized void close(){
if (closing) {
return;
}
if (userSessions.size() > 0) {
Session[] all=new Session[userSessions.size()];
userSessions.toArray(all);
for ( Session s : all) {
try {
s.rollback();
s.close();
}
catch ( DbException e) {
trace.error(e,"disconnecting session #{0}",s.getId());
}
}
}
repository.close();
if (queryExecutor != null) {
Threads.shutdownGracefully(queryExecutor,1000,1000,TimeUnit.MILLISECONDS);
}
closing=true;
}
| Close the database. |
public static Bit valueOf(boolean b){
return b ? TRUE : FALSE;
}
| Convert truth value to a bit. |
public static void main(final String[] args){
DOMTestCase.doMain(hc_nodedocumentfragmentnormalize2.class,args);
}
| Runs this test from the command line. |
@Override public boolean isSatisfiedBy(Assignment input){
if (!variable.isFilledBy(input) || !templateValue.isFilledBy(input)) {
return false;
}
BasicCondition grounded=new BasicCondition(this,input);
Value actualValue=input.getValue(grounded.variable.toString());
return grounded.isSatisfied(actualValue);
}
| Returns true if the condition is satisfied by the value assignment provided as argument, and false otherwise <p> This method uses an external ConditionCheck object to ease the process. |
public void testUnknownHandlingIgnoreWithFeature() throws Exception {
ObjectMapper mapper=new ObjectMapper();
mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,false);
TestBean result=null;
try {
result=mapper.readValue(new StringReader(JSON_UNKNOWN_FIELD),TestBean.class);
}
catch ( JsonMappingException jex) {
fail("Did not expect a problem, got: " + jex.getMessage());
}
assertNotNull(result);
assertEquals(1,result._a);
assertNull(result._unknown);
assertEquals(-1,result._b);
}
| Test for checking that it is also possible to simply suppress error reporting for unknown properties. |
public Object removeFromVisualization(IVisualAgent agent){
return environment.remove(agent.getVisualizationObject());
}
| Remove this agent from visualization. |
public void complete(ClassSymbol c) throws CompletionFailure {
if (completionFailureName == c.fullname) {
throw new CompletionFailure(c,"user-selected completion failure by class name");
}
JCCompilationUnit tree;
JavaFileObject filename=c.classfile;
JavaFileObject prev=log.useSource(filename);
try {
tree=parse(filename,filename.getCharContent(false));
}
catch ( IOException e) {
log.error("error.reading.file",filename,JavacFileManager.getMessage(e));
tree=make.TopLevel(List.<JCTree.JCAnnotation>nil(),null,List.<JCTree>nil());
}
finally {
log.useSource(prev);
}
if (!taskListener.isEmpty()) {
TaskEvent e=new TaskEvent(TaskEvent.Kind.ENTER,tree);
taskListener.started(e);
}
enter.complete(List.of(tree),c);
if (!taskListener.isEmpty()) {
TaskEvent e=new TaskEvent(TaskEvent.Kind.ENTER,tree);
taskListener.finished(e);
}
if (enter.getEnv(c) == null) {
boolean isPkgInfo=tree.sourcefile.isNameCompatible("package-info",JavaFileObject.Kind.SOURCE);
if (isPkgInfo) {
if (enter.getEnv(tree.packge) == null) {
JCDiagnostic diag=diagFactory.fragment("file.does.not.contain.package",c.location());
throw reader.new BadClassFile(c,filename,diag);
}
}
else {
JCDiagnostic diag=diagFactory.fragment("file.doesnt.contain.class",c.getQualifiedName());
throw reader.new BadClassFile(c,filename,diag);
}
}
implicitSourceFilesRead=true;
}
| Complete compiling a source file that has been accessed by the class file reader. |
private static PsiElement asOperationOrNull(PsiElement operationCandidate){
if (operationCandidate instanceof JSGraphQLPsiElement) {
if (operationCandidate instanceof JSGraphQLFragmentDefinitionPsiElement) {
return null;
}
if (operationCandidate instanceof JSGraphQLSelectionSetPsiElement) {
if (!((JSGraphQLSelectionSetPsiElement)operationCandidate).isAnonymousQuery()) {
return null;
}
}
return operationCandidate;
}
return null;
}
| Returns the operation candidate if it's an operation, or <code>null</code> |
private Rectangle interpolate(Rectangle startBounds,Rectangle finalBounds,double progress){
Rectangle bounds=new Rectangle();
bounds.setLocation(interpolate(startBounds.getLocation(),finalBounds.getLocation(),progress));
bounds.setSize(interpolate(startBounds.getSize(),finalBounds.getSize(),progress));
return bounds;
}
| Calculate interpolated bounds based on the initial and final bounds, and the state of progress. |
@Override public boolean equals(Object obj){
if (obj instanceof InOutParameter) {
obj=((InOutParameter)obj).getValue();
}
return ((obj == value) || (value != null && value.equals(obj)));
}
| Determines whether the in/out parameter value is equal in value to the specified Object. Note, this is not typically how an equals method should be coded, but then this is not your typical class either! <p/> |
public static GridLayout createFormGridLayout(boolean makeColumnsEqualWidth,int numColumns){
GridLayout layout=new GridLayout();
layout.marginHeight=FORM_BODY_MARGIN_HEIGHT;
layout.marginWidth=FORM_BODY_MARGIN_WIDTH;
layout.marginTop=FORM_BODY_MARGIN_TOP;
layout.marginBottom=FORM_BODY_MARGIN_BOTTOM;
layout.marginLeft=FORM_BODY_MARGIN_LEFT;
layout.marginRight=FORM_BODY_MARGIN_RIGHT;
layout.horizontalSpacing=FORM_BODY_HORIZONTAL_SPACING;
layout.verticalSpacing=FORM_BODY_VERTICAL_SPACING;
layout.makeColumnsEqualWidth=makeColumnsEqualWidth;
layout.numColumns=numColumns;
return layout;
}
| For form bodies. |
@Override public boolean equals(Object o){
if (o instanceof BasicEffect) {
if (!((BasicEffect)o).getVariable().equals(variableLabel)) {
return false;
}
else if (!((BasicEffect)o).getValue().equals(getValue())) {
return false;
}
else if (((BasicEffect)o).exclusive != exclusive) {
return false;
}
else if (((BasicEffect)o).isNegated() != negated) {
return false;
}
else if (((BasicEffect)o).priority != priority) {
return false;
}
return true;
}
return false;
}
| Returns true if the object o is a basic effect that is identical to the current instance, and false otherwise. |
public boolean checkAllMessagesContaining(boolean check,String message){
if (message == null || message.length() == 0) {
return checkAllMessages(check,false);
}
message=Utils.makeTextSafeForSQL(message);
SQLiteDatabase db=getWritableDatabase();
if (db != null) {
String likeQuery="";
String messageNoSpace=message.replaceAll("\\s","");
if (message.length() == 0 || messageNoSpace.length() == 0) likeQuery=(COL_MESSAGE + " LIKE '%" + message+ "%'");
if (likeQuery.length() == 0) {
message=message.replaceAll("[\n\"]"," ");
while (message.charAt(0) == ' ') {
message=message.substring(1);
}
String[] words=message.split("\\s");
for (int i=0; i < words.length; i++) {
if (i > 0) {
likeQuery+=" OR ";
}
likeQuery+=" " + COL_MESSAGE + " LIKE '%"+ words[i]+ "%' ";
}
}
String parentOnly=" AND (" + COL_BIGPARENT + " IS NULL OR "+ COL_BIGPARENT+ " NOT IN (SELECT "+ COL_MESSAGE_ID+ " FROM "+ TABLE+ " WHERE "+ COL_DELETED+ "="+ FALSE+ ") AND "+ COL_PARENT+ " NOT IN (SELECT "+ COL_MESSAGE_ID+ " FROM "+ TABLE+ " WHERE "+ COL_DELETED+ "="+ FALSE+ "))";
db.execSQL("UPDATE " + TABLE + " SET "+ COL_CHECKED+ "="+ (check ? TRUE : FALSE)+ " WHERE "+ COL_DELETED+ " ="+ FALSE+ " AND ("+ likeQuery+ ")"+ parentOnly+ ";");
return true;
}
return false;
}
| set the checked state of the all messages as true or false |
public boolean isFull(){
return height >= 2;
}
| Return true if the cap is full, i.e. it contains all points. |
final public boolean isTargetDefault(){
return getTargetGraph() == null;
}
| Return <code>true</code> iff the target is the "default graph". |
public void destroy() throws IllegalStateTransitionException {
if (state == AdapterState.DESTROYED) {
throw new IllegalStateTransitionException("Cannot destroy from the " + state + " state");
}
state=AdapterState.DESTROYED;
}
| Transition into the DESTROYED state. |
@Category(FlakyTest.class) @Test public void testModifyColocation() throws Throwable {
createColocatedPRs("region1");
closeCache();
IgnoredException ex=IgnoredException.addIgnoredException("DiskAccessException|IllegalStateException");
try {
createColocatedPRs("region2");
fail("Should have received an illegal state exception");
}
catch ( IllegalStateException expected) {
}
finally {
ex.remove();
}
closeCache();
createColocatedPRs("/region1");
closeCache();
ex=IgnoredException.addIgnoredException("DiskAccessException|IllegalStateException");
try {
createColocatedPRs(null);
fail("Should have received an illegal state exception");
}
catch ( IllegalStateException expected) {
}
finally {
ex.remove();
}
closeCache();
}
| Test that a user is not allowed to change the colocation of a PR with persistent data. |
public T caseTypeAlias(TypeAlias object){
return null;
}
| Returns the result of interpreting the object as an instance of '<em>Type Alias</em>'. <!-- begin-user-doc --> This implementation returns null; returning a non-null result will terminate the switch. <!-- end-user-doc --> |
public Writer write(Writer writer) throws JSONException {
return this.write(writer,0,0);
}
| Write the contents of the JSONArray as JSON text to a writer. For compactness, no whitespace is added. <p> Warning: This method assumes that the data structure is acyclical. |
public void warning(SAXParseException e) throws SAXException {
javax.xml.transform.ErrorListener errorListener=m_transformer.getErrorListener();
if (errorListener instanceof ErrorHandler) {
((ErrorHandler)errorListener).warning(e);
}
else {
try {
errorListener.warning(new javax.xml.transform.TransformerException(e));
}
catch ( javax.xml.transform.TransformerException te) {
throw e;
}
}
}
| Filter a warning event. |
public static AvatarBitmapTransformation transformationFor(final Context applicationContext,final AvatarSize avatarSize){
if (TRANSFORMATION_CACHE.get(avatarSize) == null) {
synchronized (AvatarBitmapTransformation.class) {
if (TRANSFORMATION_CACHE.get(avatarSize) == null) {
TRANSFORMATION_CACHE.put(avatarSize,new AvatarBitmapTransformation(applicationContext,avatarSize));
}
}
}
return TRANSFORMATION_CACHE.get(avatarSize);
}
| Gets an Avatar Bitmap Transformation object for a particular size |
public GemFireCheckedException(Throwable cause){
super();
this.initCause(cause);
}
| Creates a new <code>GemFireCheckedException</code> with the given cause and no detail message |
@SuppressWarnings({"regex","not.sef"}) public static String regexError(String s,int groups){
try {
Pattern p=Pattern.compile(s);
int actualGroups=getGroupCount(p);
if (actualGroups < groups) {
return regexErrorMessage(s,groups,actualGroups);
}
}
catch ( PatternSyntaxException e) {
return e.getMessage();
}
return null;
}
| Returns null if the argument is a syntactically valid regular expression with at least the given number of groups. Otherwise returns a string describing why the argument is not a regex. |
private void fetchEmotes(String room,Set<Integer> emotesets){
Set<Emoticon> result=new HashSet<>();
for ( int set : emotesets) {
Set<Emoticon> fetched=fetchEmoteSet(room,set);
for ( Emoticon emoteToAdd : fetched) {
for ( Emoticon emote : result) {
if (emote.equals(emoteToAdd)) {
emote.addInfos(emoteToAdd.getInfos());
break;
}
}
result.add(emoteToAdd);
}
}
EmoticonUpdate update=new EmoticonUpdate(result,Emoticon.Type.FFZ,Emoticon.SubType.EVENT,room);
listener.channelEmoticonsReceived(update);
}
| Fetches all emotes of the given emotesets, useable in the given room and sends them to the listener (removing previous EVENT emotes in that room). |
public static double[][] align(int[] real,double[] pred){
int missing=numberOfMissingLabels(real);
double[] _real=new double[real.length - missing];
double[] _pred=new double[real.length - missing];
int offset=0;
for (int i=0; i < real.length; i++) {
if (real[i] == -1 || pred[i] == -1.0 || Double.isNaN(pred[i])) {
offset++;
continue;
}
_real[i - offset]=real[i];
_pred[i - offset]=pred[i];
}
double[][] res=new double[2][0];
res[0]=_real;
res[1]=_pred;
return res;
}
| Helper function for missing values in the labels and missing predictions (i.e., from abstaining classifiers). Aligns the predictions with the real labels, discarding labels and predictions that are missing. |
public SVGPath ellipticalArc(double[] rxy,double ar,double la,double sp,double[] xy){
append(SVGConstants.PATH_ARC,rxy[0],rxy[1],ar,la,sp,xy[0],xy[1]);
return this;
}
| Elliptical arc curve to the given coordinates. |
private int loadEmotes(String json,String streamRestriction){
if (streamRestriction != null && streamRestriction.equals("$global$")) {
streamRestriction=null;
}
Set<Emoticon> emotes=parseEmotes(json,streamRestriction);
Set<String> bots=parseBots(json);
LOGGER.info("BTTV: Found " + emotes.size() + " emotes / "+ bots.size()+ " bots");
listener.receivedEmoticons(emotes);
listener.receivedBotNames(streamRestriction,bots);
return emotes.size();
}
| Load stuff from the given JSON in the context of the given channel restriction. The channel restriction can be "$global$" which means all channels. |
public static void checkState(boolean expression,Object errorMessage){
if (ExoPlayerLibraryInfo.ASSERTIONS_ENABLED && !expression) {
throw new IllegalStateException(String.valueOf(errorMessage));
}
}
| Ensures the truth of an expression involving the state of the calling instance. |
public double cleanPriceFromZSpread(final double zSpread,final DayCounter dc,final Compounding comp,final Frequency freq,final Date settlementDate){
final double p=dirtyPriceFromZSpread(zSpread,dc,comp,freq,settlementDate);
return p - accruedAmount(settlementDate);
}
| Clean price given Z-spread Z-spread compounding, frequency, daycount are taken into account The default bond settlement is used if no date is given. For details on Z-spread refer to: "Credit Spreads Explained", Lehman Brothers European Fixed Income Research - March 2004, D. O'Kane |
protected void checkCancel(IProgressMonitor monitor){
if (monitor.isCanceled()) {
throw new OperationCanceledException();
}
}
| This is how the workbench signals a click on the cancel button or if the workbench has been shut down in the meantime. |
private Object[] newElementArray(int s){
return new Object[s];
}
| Create a new element array |
public GraphWorkbench(){
this(new EdgeListGraph());
}
| Constructs a new workbench with an empty graph; useful if another graph will be set later. |
public HashMap(){
this.loadFactor=DEFAULT_LOAD_FACTOR;
threshold=(int)(DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR);
table=new Entry[DEFAULT_INITIAL_CAPACITY];
init();
}
| Constructs an empty <tt>HashMap</tt> with the default initial capacity (16) and the default load factor (0.75). |
public void testCameraPairwiseScenario22() throws Exception {
genericPairwiseTestCase(Flash.ON,Exposure.MAX,WhiteBalance.AUTO,SceneMode.ACTION,PictureSize.SMALL,Geotagging.OFF);
}
| Flash: On / Exposure: Max / WB: Auto Scene: Action / Pic: Small / Geo: off |
public void validate() throws InvalidMameArgumentsException {
Options mergedOptions=new Options();
for ( Option o : mameOptions.getAllOptions().getOptions()) {
mergedOptions.addOption(o);
}
for ( Option o : iaMameOptions.getOptions()) {
mergedOptions.addOption(o);
}
try {
CommandLineParser parser=new DefaultParser();
this.commandLine=parser.parse(mergedOptions,rawArgs);
}
catch ( ParseException e) {
throw (InvalidMameArgumentsException)new InvalidMameArgumentsException(e.getMessage()).initCause(e);
}
}
| Parse args in raw string and store usefull Arguments. |
@Override public boolean isEmpty(){
return size() == 0;
}
| Indicates whether set has any entries. |
protected boolean isValidHeader(HttpURLConnection connection){
String version=connection.getHeaderField(API_VERSION_FIELD);
return version != null && version.equals(SUPPORTED_SANTA_HEADER_API);
}
| Returns true if this application can handle requests of this version, false otherwise. The current API version can be retrieved through: <code>curl -sI 'http://santa-api.appspot.com/info' | grep X-Santa</code> |
public void testFileFileWithConfigOption() throws Exception {
Properties properties=loadProperties("test-file-configfile-file");
assertEquals("12345",properties.getProperty("cargo.servlet.port"));
}
| Test the Configuration Files option with copying of file in subdirectory. |
public BillReceipt linkBillToReceipt(BillReceiptInfo bri) throws InvalidAccountHeadException, ObjectNotFoundException {
BillReceipt billRecpt=null;
try {
if (bri != null) {
billRecpt=new BillReceipt();
EgBill egBill=egBillDAO.findById(Long.valueOf(bri.getBillReferenceNum()),false);
List<EgBillDetails> billDetList=egBillDetailsDAO.getBillDetailsByBill(egBill);
BigDecimal totalCollectedAmt=calculateTotalCollectedAmt(bri,billDetList);
billRecpt.setBillId(egBill);
billRecpt.setReceiptAmt(totalCollectedAmt);
billRecpt.setReceiptNumber(bri.getReceiptNum());
billRecpt.setReceiptDate(bri.getReceiptDate());
billRecpt.setCollectionStatus(bri.getReceiptStatus().getCode());
billRecpt.setIsCancelled(Boolean.FALSE);
billRecpt.setCreatedBy(bri.getCreatedBy());
billRecpt.setModifiedBy(bri.getModifiedBy());
billRecpt.setCreatedDate(new Date());
billRecpt.setModifiedDate(new Date());
egBillReceiptDAO.create(billRecpt);
}
}
catch ( ApplicationRuntimeException e) {
throw new ApplicationRuntimeException("Exception in linkBillToReceipt" + e);
}
return billRecpt;
}
| Api to link bill to receipt. |
public float key(){
return _map._set[_index];
}
| Provides access to the key of the mapping at the iterator's position. Note that you must <tt>advance()</tt> the iterator at least once before invoking this method. |
protected void clearFile(){
m_pathFile=null;
m_inputStreamFile=null;
}
| Elimina el fichero asociado al documento |
public void handleEntry(File file,boolean RPFDirFound){
try {
String[] filenames=file.list();
boolean dirTest=false;
boolean not14=false;
try {
java.lang.reflect.Method method=file.getClass().getDeclaredMethod("isDirectory",(Class[])null);
Object obj=method.invoke(file,(Object[])null);
if (obj instanceof Boolean) {
dirTest=((Boolean)obj).booleanValue();
}
}
catch ( NoSuchMethodException nsme) {
not14=true;
}
catch ( SecurityException se) {
not14=true;
}
catch ( IllegalAccessException iae) {
not14=true;
}
catch ( IllegalArgumentException iae2) {
not14=true;
}
catch ( java.lang.reflect.InvocationTargetException ite) {
not14=true;
}
if ((dirTest || not14) && filenames != null) {
if (Debug.debugging("maketocdetail")) {
Debug.output("RpfFileSearch.handleEntry(" + file + ", "+ RPFDirFound+ "), file is a directory");
}
File[] contents=new File[filenames.length];
for (int i=0; i < contents.length; i++) {
contents[i]=new File(file,filenames[i]);
}
for (int i=0; i < contents.length; i++) {
boolean rpf=false;
if (!RPFDirFound) {
rpf=filenames[i].equalsIgnoreCase("RPF");
}
handleEntry(contents[i],RPFDirFound || rpf);
}
}
else {
if (Debug.debugging("maketocdetail")) {
Debug.output("RpfFileSearch.handleEntry(" + file + ", "+ RPFDirFound+ "), adding to list...");
}
String parent=file.getParent();
if (RPFDirFound) {
if (parent != null) {
files.add(file.getParent() + File.separator + file.getName());
}
else {
files.add("." + File.separator + file.getName());
}
}
}
}
catch ( NullPointerException npe) {
}
catch ( SecurityException se) {
}
}
| Search, given a file, plus a flag to let it know if the RPF directory is somewhere above the file in the file sytem. |
public void save(OutputStream out) throws IOException {
reset();
try {
if (doctype != null) {
OutputStreamWriter w=new OutputStreamWriter(out,"UTF8");
w.write("<!DOCTYPE ");
w.write(doctype);
w.write(">\n");
w.flush();
}
Transformer t=TransformerFactory.newInstance().newTransformer();
t.transform(new DOMSource(document),new StreamResult(out));
}
catch ( TransformerException e) {
IOException error=new IOException(e.getMessage());
error.initCause(e);
throw error;
}
}
| Writes the contents of the DOMOutput into the specified output stream. |
public void stopDrawShadowTexture(){
GLES20.glColorMask(mCachedColorMask[0],mCachedColorMask[1],mCachedColorMask[2],mCachedColorMask[3]);
GLES20.glDepthMask(mCachedDepthMask[0]);
GLES20.glCullFace(GLES20.GL_BACK);
GLES20.glBindFramebuffer(GLES20.GL_FRAMEBUFFER,0);
}
| Must be call after using shadow complete |
public Linear(double[] priors,int large){
super(priors,large);
}
| Constructs a new Linear with the given default probability. |
public static byte[] decode(byte[] source) throws Base64DecoderException {
return decode(source,0,source.length);
}
| Decodes Base64 content in byte array format and returns the decoded byte array. |
public boolean containsKey(K key){
return root.containsKey(ord,key);
}
| Checks whether a certain entry exists. |
private static Array listToArrayRemoveEmpty(String list,String delimiter,boolean multiCharDelim){
if (!multiCharDelim || delimiter.length() == 0) return listToArrayRemoveEmpty(list,delimiter);
if (delimiter.length() == 1) return listToArrayRemoveEmpty(list,delimiter.charAt(0));
int len=list.length();
if (len == 0) return new ArrayImpl();
Array array=new ArrayImpl();
int from=0;
int index;
int dl=delimiter.length();
while ((index=list.indexOf(delimiter,from)) != -1) {
if (from < index) array.appendEL(list.substring(from,index));
from=index + dl;
}
if (from < len) array.appendEL(list.substring(from,len));
return array;
}
| casts a list to Array object remove Empty Elements |
public void changeGeneralConfig(String value){
WebElement generalConfigButton=driver.findElement(By.xpath((uiElementMapper.getElement("emm.configuration.general.tab.identifier"))));
WebElement inputGeneralConfig=driver.findElement(By.xpath((uiElementMapper.getElement("emm.configuration.general.input.monitoringFr.identifier"))));
WebElement buttonSaveConfig=driver.findElement(By.xpath((uiElementMapper.getElement("emm.configuration.general.button.save.identifier"))));
generalConfigButton.click();
inputGeneralConfig.sendKeys(value);
buttonSaveConfig.click();
}
| This page imitates the general configuration changing scenario. |
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 int numIslandsUnionFind(char[][] grid){
if (grid.length == 0 || grid[0].length == 0) {
return 0;
}
int m=grid.length, n=grid[0].length;
UnionFind uf=new UnionFind(m,n,grid);
for (int i=0; i < m; i++) {
for (int j=0; j < n; j++) {
if (grid[i][j] == '0') {
continue;
}
int p=i * n + j;
int q;
if (i > 0 && grid[i - 1][j] == '1') {
q=p - n;
uf.union(p,q);
}
if (i < m - 1 && grid[i + 1][j] == '1') {
q=p + n;
uf.union(p,q);
}
if (j > 0 && grid[i][j - 1] == '1') {
q=p - 1;
uf.union(p,q);
}
if (j < n - 1 && grid[i][j + 1] == '1') {
q=p + 1;
uf.union(p,q);
}
}
}
return uf.count;
}
| Union find. Build an Union Find data structure first. Then iterate all grids row by row. |
public GameDataComponent(final GameData data){
m_data=data;
}
| Creates new GameDataComponent |
public void runTest() throws Throwable {
Document doc;
NodeList childNodes;
ProcessingInstruction piNode;
String target;
doc=(Document)load("staff",false);
childNodes=doc.getChildNodes();
piNode=(ProcessingInstruction)childNodes.item(0);
target=piNode.getTarget();
assertEquals("processinginstructionGetTargetAssert","TEST-STYLE",target);
}
| Runs the test case. |
public NotificationChain basicSetAnnotationList(AnnotationList newAnnotationList,NotificationChain msgs){
AnnotationList oldAnnotationList=annotationList;
annotationList=newAnnotationList;
if (eNotificationRequired()) {
ENotificationImpl notification=new ENotificationImpl(this,Notification.SET,N4JSPackage.N4_CLASS_DECLARATION__ANNOTATION_LIST,oldAnnotationList,newAnnotationList);
if (msgs == null) msgs=notification;
else msgs.add(notification);
}
return msgs;
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public static List<Position> computeShiftedPositions(Position oldPosition,Position newPosition,Iterable<? extends Position> positions){
if (oldPosition == null || newPosition == null) {
String msg=Logging.getMessage("nullValue.PositionIsNull");
Logging.logger().severe(msg);
throw new IllegalArgumentException(msg);
}
if (positions == null) {
String msg=Logging.getMessage("nullValue.PositionsListIsNull");
Logging.logger().severe(msg);
throw new IllegalArgumentException(msg);
}
ArrayList<Position> newPositions=new ArrayList<Position>();
double elevDelta=newPosition.getElevation() - oldPosition.getElevation();
for ( Position pos : positions) {
Angle distance=LatLon.greatCircleDistance(oldPosition,pos);
Angle azimuth=LatLon.greatCircleAzimuth(oldPosition,pos);
LatLon newLocation=LatLon.greatCircleEndPosition(newPosition,azimuth,distance);
double newElev=pos.getElevation() + elevDelta;
newPositions.add(new Position(newLocation,newElev));
}
return newPositions;
}
| Computes a new set of positions translated from a specified reference position to a new reference position. |
@Deprecated public static CallSite bootstrapCurrent(Lookup caller,String name,MethodType type){
return realBootstrap(caller,name,CALL_TYPES.METHOD.ordinal(),type,false,true,false);
}
| bootstrap method for method calls with "this" as receiver |
public ActionSwitch(){
m_switchVal=0;
}
| Creates an empty action switch. |
public static void until(Callable<Boolean> condition,long timeout,TimeUnit timeUnit){
until(condition,timeout,timeUnit,50);
}
| Blocks until the given condition evaluates to true. The condition is evaluated every 50 milliseconds, so, the given condition should be an idempotent operation. If the condition is not met within the given timeout, an exception is thrown. |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.