code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
private static void attemptRetryOnException(String logPrefix,Request<?> request,VolleyError exception) throws VolleyError {
RetryPolicy retryPolicy=request.getRetryPolicy();
int oldTimeout=request.getTimeoutMs();
try {
retryPolicy.retry(exception);
}
catch ( VolleyError e) {
request.addMarker(String.format("%s-timeout-giveup [timeout=%s]",logPrefix,oldTimeout));
throw e;
}
request.addMarker(String.format("%s-retry [timeout=%s]",logPrefix,oldTimeout));
}
| Attempts to prepare the request for a retry. If there are no more attempts remaining in the request's retry policy, a timeout exception is thrown. |
public final CC growY(Float w){
ver.setGrow(w);
return this;
}
| Grow weight for the component vertically. <p> For a more thorough explanation of what this constraint does see the white paper or cheat Sheet at www.migcomponents.com. |
void addIndex(Index index){
indexes.add(index);
}
| Add this index to the table. |
@Override public void dragExit(DragSourceEvent dsde){
}
| as the hotspot exits a platform dependent drop site |
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 DefaultLmlParser(final LmlData data,final LmlSyntax syntax,final LmlTemplateReader templateReader,final LmlStyleSheet styleSheet,final boolean strict){
super(data,syntax,templateReader,styleSheet,strict);
}
| Creates a new strict parser with custom syntax, reader, style sheet and strict setting. |
public static boolean contains(Rectangle2D.Double r1,Rectangle2D.Double r2){
return (r2.x >= r1.x && r2.y >= r1.y && (r2.x + max(0,r2.width)) <= r1.x + max(0,r1.width) && (r2.y + max(0,r2.height)) <= r1.y + max(0,r1.height));
}
| Returns true, if rectangle 1 contains rectangle 2. <p> This method is similar to Rectangle2D.contains, but also returns true, when rectangle1 contains rectangle2 and either or both of them are empty. |
protected boolean hasZoom(){
return true;
}
| Has Zoom |
static int binSearch(int[] list,int nUsed,int chr){
int low=0;
int high=nUsed - 1;
while (low <= high) {
int mid=(low + high) >>> 1;
int midVal=list[mid];
if (midVal < chr) {
low=mid + 1;
}
else if (midVal > chr) {
high=mid - 1;
}
else {
return mid;
}
}
return -(low + 1);
}
| unfortunatly, Arrays.binarySearch() does not support search in a part of the array (not in jdk1.3 and jdk1.4). - so we have do provide our own implementation. |
public static ColumnCriterion createColumnCriterion(ParameterHandler handler,double minimalGain) throws OperatorException {
String criterionName=handler.getParameterAsString(PARAMETER_CRITERION);
Class<?> criterionClass=null;
for (int i=0; i < CRITERIA_NAMES.length; i++) {
if (CRITERIA_NAMES[i].equals(criterionName)) {
criterionClass=CRITERIA_CLASSES[i];
}
}
if (criterionClass == null && criterionName != null) {
try {
criterionClass=Tools.classForName(criterionName);
}
catch ( ClassNotFoundException e) {
throw new OperatorException("Cannot find criterion '" + criterionName + "' and cannot instantiate a class with this name.");
}
}
if (criterionClass != null) {
try {
ColumnCriterion criterion=(ColumnCriterion)criterionClass.newInstance();
if (criterion instanceof MinimalGainHandler) {
((MinimalGainHandler)criterion).setMinimalGain(minimalGain);
}
return criterion;
}
catch ( InstantiationException e) {
throw new OperatorException("Cannot instantiate criterion class '" + criterionClass.getName() + "'.");
}
catch ( IllegalAccessException e) {
throw new OperatorException("Cannot access criterion class '" + criterionClass.getName() + "'.");
}
}
else {
throw new OperatorException("No relevance criterion defined.");
}
}
| This method returns the criterion specified by the respective parameters. |
public static byte[] readFully(InputStream is) throws IOException {
byte[] buf=new byte[4096];
ByteArrayOutputStream os=new ByteArrayOutputStream(4096);
for (; ; ) {
int bytesRead=is.read(buf);
if (bytesRead == -1) break;
os.write(buf,0,bytesRead);
}
return os.toByteArray();
}
| Reads entire resource from an input stream |
private List<Set<IonIndependenceFacts>> findSepAndAssoc(Graph graph){
Set<IonIndependenceFacts> separations=new HashSet<>();
Set<IonIndependenceFacts> associations=new HashSet<>();
List<NodePair> allNodes=allNodePairs(graph.getNodes());
for ( NodePair pair : allNodes) {
Node x=pair.getFirst();
Node y=pair.getSecond();
List<Node> variables=new ArrayList<>(graph.getNodes());
variables.remove(x);
variables.remove(y);
List<Set<Node>> subsets=SearchGraphUtils.powerSet(variables);
IonIndependenceFacts indep=new IonIndependenceFacts(x,y,new HashSet<List<Node>>());
IonIndependenceFacts assoc=new IonIndependenceFacts(x,y,new HashSet<List<Node>>());
boolean addIndep=false;
boolean addAssoc=false;
for ( Graph pag : input) {
for ( Set<Node> subset : subsets) {
if (containsAll(pag,subset,pair)) {
Node pagX=pag.getNode(x.getName());
Node pagY=pag.getNode(y.getName());
ArrayList<Node> pagSubset=new ArrayList<>();
for ( Node node : subset) {
pagSubset.add(pag.getNode(node.getName()));
}
if (pag.isDSeparatedFrom(pagX,pagY,new ArrayList<>(pagSubset))) {
if (!pag.isAdjacentTo(pagX,pagY)) {
addIndep=true;
indep.addMoreZ(new ArrayList<>(subset));
}
}
else {
addAssoc=true;
assoc.addMoreZ(new ArrayList<>(subset));
}
}
}
}
if (addIndep) separations.add(indep);
if (addAssoc) associations.add(assoc);
}
List<Set<IonIndependenceFacts>> facts=new ArrayList<>(2);
facts.add(0,separations);
facts.add(1,associations);
return facts;
}
| Finds the association or seperation sets for every pair of nodes. |
public SemPm(Graph graph){
this(new SemGraph(graph));
}
| Constructs a BayesPm from the given Graph, which must be convertible first into a ProtoSemGraph and then into a SemGraph. |
public synchronized Iterator<E> iterator(){
ArrayList<E> v=new ArrayList<E>(this);
return v.iterator();
}
| Return an iterator over a clone of the listeners. |
public GPathResult find(final Closure closure){
return this;
}
| Returns <code>this</code>. |
private static void outputSetting(String setting){
if (out != null && !writtenSettings.contains(setting)) {
if (writtenSettings.size() == 0) {
out.println("# Settings for run " + (runIndex + 1));
}
out.println(setting);
writtenSettings.add(setting);
}
}
| Writes the given setting string to the settings output (if any) |
public static void registerSerDeser(Class<?> clazz,EntitySerDeser<?> entitySerDeser){
_serDeserMap.put(clazz,entitySerDeser);
}
| User can register their own field SerDeser |
public synchronized boolean visit(final int depth,final Value pred,final URI edge){
boolean ret=false;
if (this.depth.compareAndSet(-1,depth)) {
ret=true;
}
if (pred != null && this.depth() > 0 && this.depth() == depth) {
addPredecessor(pred,edge);
}
return ret;
}
| Note: This marks the vertex at the current traversal depth. |
public Shape modelToView(int p0,Position.Bias b0,int p1,Position.Bias b1,Shape a) throws BadLocationException {
return super.modelToView(p0,b0,p1,b1,adjustAllocation(a));
}
| Provides a mapping from the document model coordinate space to the coordinate space of the view mapped to it. |
@Override protected EClass eStaticClass(){
return EipPackage.Literals.SERVICE_INVOCATION;
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public boolean isOnMap(Projection proj){
OMRect bds=getBounds();
bds.generate(proj);
Shape s=bds.getShape();
return s.intersects(0,0,proj.getWidth(),proj.getHeight());
}
| Return true of current bounds covers the projection area. |
public static String bytesToHexString(final byte[] bytes){
return bytesToHexString(bytes,null);
}
| Convert a byte array to a hex-encoding string: "a33bff00..." |
public static int UTF16toUTF8(final CharSequence s,final int offset,final int length,byte[] out){
return UTF16toUTF8(s,offset,length,out,0);
}
| Encode characters from this String, starting at offset for length characters. It is the responsibility of the caller to make sure that the destination array is large enough. |
public void load(){
}
| Force a load if it makes sense for the group. |
public void onAsyncTaskCompleted(){
removeDialog(DIALOG_PROGRESS_ID);
setResult(RESULT_OK);
finish();
}
| Invokes when the associated AsyncTask completes. |
public static void safeIncr(String counterName){
com.twitter.heron.api.metric.GlobalMetrics.safeIncr(counterName);
}
| Thread safe created increment of counterName. (Slow) |
public ClientResponse post(URI uri,String body){
return client.resource(uri).type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON).post(ClientResponse.class,body);
}
| Simple post query. No header provided. |
@Deprecated public static String last(String list,String delimiter){
return last(list,delimiter,true);
}
| return last element of the list |
public Polygon2D center(){
return center(null);
}
| Centers the polygon around the world origin (0,0). |
@Override public boolean equals(Object o){
if (!sameClassAs(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);
}
| Returns true if <code>o</code> is equal to this. |
public boolean match(Element e,String pseudoE){
String attr=e.getAttribute(getLocalName());
String val=getValue();
int i=attr.indexOf(val);
if (i == -1) {
return false;
}
if (i != 0 && !Character.isSpaceChar(attr.charAt(i - 1))) {
return false;
}
int j=i + val.length();
return (j == attr.length() || (j < attr.length() && Character.isSpaceChar(attr.charAt(j))));
}
| Tests whether this condition matches the given element. |
public StringBuffer append(int i){
IntegralToString.appendInt(this,i);
return this;
}
| Adds the string representation of the specified integer to the end of this StringBuffer. |
public static byte[] encode(byte[] source,int off,int len,byte[] alphabet,int maxLineLength){
int lenDiv3=(len + 2) / 3;
int len43=lenDiv3 * 4;
byte[] outBuff=new byte[len43 + (len43 / maxLineLength)];
int d=0;
int e=0;
int len2=len - 2;
int lineLength=0;
for (; d < len2; d+=3, e+=4) {
int inBuff=((source[d + off] << 24) >>> 8) | ((source[d + 1 + off] << 24) >>> 16) | ((source[d + 2 + off] << 24) >>> 24);
outBuff[e]=alphabet[(inBuff >>> 18)];
outBuff[e + 1]=alphabet[(inBuff >>> 12) & 0x3f];
outBuff[e + 2]=alphabet[(inBuff >>> 6) & 0x3f];
outBuff[e + 3]=alphabet[(inBuff) & 0x3f];
lineLength+=4;
if (lineLength == maxLineLength) {
outBuff[e + 4]=NEW_LINE;
e++;
lineLength=0;
}
}
if (d < len) {
encode3to4(source,d + off,len - d,outBuff,e,alphabet);
lineLength+=4;
if (lineLength == maxLineLength) {
outBuff[e + 4]=NEW_LINE;
e++;
}
e+=4;
}
assert (e == outBuff.length);
return outBuff;
}
| Encodes a byte array into Base64 notation. |
private long copyImage(Graphics g,BufferedImage image,int x,int y){
long startTime=System.nanoTime();
for (int i=0; i < 100; ++i) {
g.drawImage(image,x,y,null);
}
Toolkit.getDefaultToolkit().sync();
long endTime=System.nanoTime();
return (endTime - startTime) / 1000000;
}
| Perform and time several drawImage() calls with the given parameters and return the number of milliseconds that the operation took. |
public boolean hasDefaultValue(){
return hasDefault;
}
| Returns whether this transform has a default value. |
public static String encodeUrlParameterValue(String value){
try {
value=URLEncoder.encode(value,Constants.ENCODING_ISO_8859_1);
}
catch ( UnsupportedEncodingException e) {
}
return value;
}
| Permite codificar un valor para enviar en una URL |
public static void writeStringASCII(ByteBuf stream,String str) throws UnsupportedEncodingException {
final byte[] bytes=str.getBytes("US-ASCII");
stream.writeInt(str.length());
stream.writeBytes(bytes);
}
| Writes an ASCII string to the stream, the first value will be an integer for the length of the string, followed by bytes |
public ComputeTaskTimeoutCheckedException(Throwable cause){
this(cause.getMessage(),cause);
}
| Creates new task timeout exception given throwable as a cause and source of error message. |
public RaceGUI(String appName){
UIManager.put("swing.boldMetal",Boolean.FALSE);
JFrame f=new JFrame(appName);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new BorderLayout());
track=new TrackView();
f.add(track,BorderLayout.CENTER);
controlPanel=new RaceControlPanel();
f.add(controlPanel,BorderLayout.SOUTH);
f.pack();
f.setVisible(true);
}
| Creates a new instance of RaceGUI |
public String inputOrderTipText(){
return "The input order to use.";
}
| Returns the tip text for this property |
private void grantMaxUserRoles(PlatformUser customerUser){
grantRole(customerUser,UserRoleType.ORGANIZATION_ADMIN);
if (customerUser.getOrganization().hasRole(OrganizationRoleType.TECHNOLOGY_PROVIDER)) {
grantRole(customerUser,UserRoleType.TECHNOLOGY_MANAGER);
}
if (customerUser.getOrganization().hasRole(OrganizationRoleType.SUPPLIER)) {
grantRole(customerUser,UserRoleType.SERVICE_MANAGER);
}
}
| Grants the max set of roles to the user as allowed by his organization. |
public void breadthFirstTraversal(){
if (root == null) return;
java.util.Queue<TreeNode<E>> queue=new java.util.LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
TreeNode<E> current=queue.element();
if (current.left != null) {
queue.add(current.left);
}
if (current.right != null) {
queue.add(current.right);
}
System.out.print(queue.remove().element + " ");
}
}
| Displays the nodes in a breadth-first traversal |
private void writeQName(javax.xml.namespace.QName qname,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
java.lang.String namespaceURI=qname.getNamespaceURI();
if (namespaceURI != null) {
java.lang.String prefix=xmlWriter.getPrefix(namespaceURI);
if (prefix == null) {
prefix=generatePrefix(namespaceURI);
xmlWriter.writeNamespace(prefix,namespaceURI);
xmlWriter.setPrefix(prefix,namespaceURI);
}
if (prefix.trim().length() > 0) {
xmlWriter.writeCharacters(prefix + ":" + org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
}
else {
xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
}
}
else {
xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
}
}
| method to handle Qnames |
public boolean equals(Object other){
if (!(other instanceof Association)) {
return false;
}
Association otherAssoc=(Association)other;
boolean isBasicEquals, isActionListEquals, isFileExtListEquals;
String otherDesc=otherAssoc.getDescription();
String otherIconFileName=otherAssoc.getIconFileName();
String otherMimeType=otherAssoc.getMimeType();
isBasicEquals=((description == null ? otherDesc == null : description.equals(otherDesc)) && (iconFileName == null ? otherIconFileName == null : iconFileName.equals(otherIconFileName)) && (mimeType == null ? otherMimeType == null : mimeType.equals(otherMimeType)));
if (!isBasicEquals) {
return false;
}
List<String> otherFileExtList=otherAssoc.getFileExtList();
isFileExtListEquals=false;
if ((fileExtensionList == null) && (otherFileExtList == null)) {
isFileExtListEquals=true;
}
else if ((fileExtensionList != null) && (otherFileExtList != null)) {
if ((fileExtensionList.containsAll(otherFileExtList)) && (otherFileExtList.containsAll(fileExtensionList))) {
isFileExtListEquals=true;
}
}
if (!isFileExtListEquals) {
return false;
}
List<Action> otherActionList=otherAssoc.getActionList();
isActionListEquals=false;
if ((actionList == null) && (otherActionList != null)) {
isActionListEquals=true;
}
else if ((actionList != null) && (otherActionList != null)) {
if ((actionList.containsAll(otherActionList)) && (otherActionList.containsAll(actionList))) {
isActionListEquals=true;
}
}
return isActionListEquals;
}
| Overrides the same method of <code>java.lang.Object</code>. <p> Determines whether or not two associations are equal. Two instances of <code>Association</code> are equal if the values of all the fields are the same. |
public void goToNextColor(){
mColorIndex=(mColorIndex + 1) % (mColors.length);
}
| Proceed to the next available ring color. This will automatically wrap back to the beginning of colors. |
private void checkArray(String msg,Object expected,Object result){
assertNotNull(msg + " Expected Null",expected);
assertNotNull(msg + " Result Null",result);
assertTrue(msg + " Result not array",result.getClass().isArray());
assertTrue(msg + " Expected not array",expected.getClass().isArray());
int resultLth=Array.getLength(result);
assertEquals(msg + " Size",Array.getLength(expected),resultLth);
assertEquals(msg + " Type",expected.getClass(),result.getClass());
for (int i=0; i < resultLth; i++) {
Object expectElement=Array.get(expected,i);
Object resultElement=Array.get(result,i);
assertEquals(msg + " Element " + i,expectElement,resultElement);
}
}
| Check that two arrays are the same. |
protected void configureRequestedContentTypeResolver(RequestedContentTypeResolverBuilder builder){
}
| Override to configure how the requested content type is resolved. |
public static GdbRun parse(GdbOutput gdbOutput) throws GdbParseException {
String output=gdbOutput.getOutput();
for ( String line : output.split("\n")) {
Matcher matcher=GDB_BREAKPOINT.matcher(line);
if (matcher.find()) {
String file=matcher.group(1);
String lineNumber=matcher.group(2);
Location location=new LocationImpl(file,Integer.parseInt(lineNumber));
return new GdbRun(new BreakpointImpl(location));
}
}
return new GdbRun(null);
}
| Factory method. |
public static int ENOMEDIUM(){
return 123;
}
| No medium found |
public void processData(Object result,boolean lastMsg,DistributedMember memberID){
boolean completelyDone=false;
if (lastMsg) {
this.totalLastMsgRecieved++;
}
if (this.totalLastMsgRecieved == this.recipients.size()) {
completelyDone=true;
}
((PartitionedRegionFunctionResultSender)resultSender).lastResult(result,completelyDone,this.reply,memberID);
}
| This function processes the result data it receives. Adds the result to resultCollector as it gets the objects. On getting the last msg from all the sender it will call endResult on ResultSender. |
public static _Fields findByThriftId(int fieldId){
switch (fieldId) {
case 1:
return HEADER;
case 2:
return COUNT;
default :
return null;
}
}
| Find the _Fields constant that matches fieldId, or null if its not found. |
public void resize(int maxSize){
if (maxSize <= 0) {
throw new IllegalArgumentException("maxSize <= 0");
}
synchronized (this) {
this.maxSize=maxSize;
}
trimToSize(maxSize);
}
| Sets the size of the cache. |
protected void addMapContent(MapHandler mapHandler,BranchGroup worldGroup,int contentMask){
Projection projection=null;
if (mapHandler != null) {
MapBean mapBean=(MapBean)mapHandler.get("com.bbn.openmap.MapBean");
if (mapBean != null) {
projection=mapBean.getProjection();
}
TransformGroup mapTransformGroup=new TransformGroup();
mapTransformGroup.setCapability(TransformGroup.ALLOW_TRANSFORM_READ);
mapTransformGroup.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);
Debug.message("3d","OM3DViewer: adding map content");
BoundingSphere bs=new BoundingSphere(ORIGIN,boundsDimension);
background.setApplicationBounds(bs);
mapTransformGroup.addChild(background);
createMapContent(mapTransformGroup,mapHandler,contentMask);
AmbientLight ambientLight=new AmbientLight();
ambientLight.setInfluencingBounds(bs);
worldGroup.addChild(ambientLight);
Behavior beh=getMotionBehavior((TransformGroup)getCamera().getNode(),projection);
beh.setSchedulingBounds(bs);
worldGroup.addChild(beh);
worldGroup.addChild(mapTransformGroup);
}
}
| This is the main function that gets called when the MapContentViewer is created, to create the world objects in the universe. It builds the objects to put in the J3D world from the objects contained within the MapHandler. This method calls setCameraLocation(), so you can modify where the camera is placed there, and then calls createMapContent() to have a BranchGroup created with 3D objects. You can modify those methods to adjust how things get created. |
boolean isExpanded(){
return mSubNodes != null;
}
| Gets info if node is expanded. |
@Override public Object eGet(int featureID,boolean resolve,boolean coreType){
switch (featureID) {
case EipPackage.INVOCABLE_ENDPOINT__NAME:
return getName();
case EipPackage.INVOCABLE_ENDPOINT__TO_CHANNELS:
return getToChannels();
case EipPackage.INVOCABLE_ENDPOINT__FROM_CHANNELS:
return getFromChannels();
case EipPackage.INVOCABLE_ENDPOINT__OWNED_SERVICE_INVOCATIONS:
return getOwnedServiceInvocations();
}
return super.eGet(featureID,resolve,coreType);
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
@Override public boolean isFeeValid(final Transaction transaction,final BlockHeight blockHeight){
final Amount minimumFee=this.calculateMinimumFee(transaction);
final long FORK_HEIGHT=92000;
final Amount maxCacheFee=Amount.fromNem(1000);
switch (transaction.getType()) {
case TransactionTypes.MULTISIG_SIGNATURE:
if (FORK_HEIGHT > blockHeight.getRaw()) {
return 0 == transaction.getFee().compareTo(minimumFee);
}
return 0 <= transaction.getFee().compareTo(minimumFee) && 0 >= transaction.getFee().compareTo(maxCacheFee);
}
return transaction.getFee().compareTo(minimumFee) >= 0;
}
| Determines whether the fee for the transaction at the specified block height is valid. |
@Override public void replaceNullIDs(VersionSource memberID){
if (this.getMemberID() == null) {
throw new AssertionError("Member id should not be null for persistent version tags");
}
}
| For a persistent version tag, the member id should not be null, because we can't fill the member id in later. |
public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
Sender sender=(Sender)context.getBean("sender");
String text=request.getParameter("text");
sender.send(text);
response.encodeRedirectUrl("/index.jsp");
System.out.println("send....");
}
| The doPost method of the servlet. <br> This method is called when a form has its tag value method equals to post. |
public AgentConfigImpl(File propFile){
this();
Properties props=new Properties();
if (propFile.exists()) {
try {
FileInputStream in=new FileInputStream(propFile);
props.load(in);
in.close();
}
catch ( java.io.IOException e) {
throw new GemFireIOException(LocalizedStrings.AgentConfigImpl_FAILED_READING_0.toLocalizedString(propFile),e);
}
}
else {
throw new IllegalArgumentException(LocalizedStrings.AgentConfigImpl_SPECIFIED_PROPERTIES_FILE_DOES_NOT_EXIST_0.toLocalizedString(propFile));
}
initialize(props);
}
| Constructs new instance of AgentConfig using the specified property file. |
@Override public synchronized void write(int b){
int inBufferPos=count - filledBufferSum;
if (inBufferPos == currentBuffer.length) {
needNewBuffer(count + 1);
inBufferPos=0;
}
currentBuffer[inBufferPos]=(byte)b;
count++;
}
| Write a byte to byte array. |
public void clear(){
map.clear();
}
| Removes all elements from the mapping of this Bundle. |
public boolean isEnableDecluttering(){
return this.enableDecluttering;
}
| Indicates whether this text should participate in decluttering. |
@Override public void exportGroupDelete(URI export,String opId) throws ControllerException {
blockRMI("exportGroupDelete",export,opId);
}
| Delete the export. |
@NotNull public OptionalLong findOptionalLong(@NotNull @SQL String sql,Object... args){
return findOptionalLong(SqlQuery.query(sql,args));
}
| Finds a unique result from database, converting the database row to long using default mechanisms. Returns empty if there are no results or if single null result is returned. |
public void waitForRequestSent(){
if (!delayResponse || !useLowLevel) {
Log.d(LOGTAG," Cant do this without delayReponse set ");
return;
}
synchronized (syncObj) {
try {
syncObj.wait();
}
catch ( InterruptedException e) {
}
}
}
| Enable this listeners Request object to read server responses. This should only be used in conjunction with setDelayResponse(true) |
public static BufferedWriter newWriter(Path self,String charset,boolean append,boolean writeBom) throws IOException {
boolean shouldWriteBom=writeBom && !self.toFile().exists();
if (append) {
BufferedWriter writer=Files.newBufferedWriter(self,Charset.forName(charset),CREATE,APPEND);
if (shouldWriteBom) {
IOGroovyMethods.writeUTF16BomIfRequired(writer,charset);
}
return writer;
}
else {
OutputStream out=Files.newOutputStream(self);
if (shouldWriteBom) {
IOGroovyMethods.writeUTF16BomIfRequired(out,charset);
}
return new BufferedWriter(new OutputStreamWriter(out,Charset.forName(charset)));
}
}
| Helper method to create a buffered writer for a file. If the given charset is "UTF-16BE" or "UTF-16LE" (or an equivalent alias), the requisite byte order mark is written to the stream before the writer is returned. |
public static String formatTrackLength(long timeMs){
long hours=TimeUnit.MILLISECONDS.toHours(timeMs);
long minutes=TimeUnit.MILLISECONDS.toMinutes(timeMs) - TimeUnit.HOURS.toMinutes(hours);
long seconds=TimeUnit.MILLISECONDS.toSeconds(timeMs) - TimeUnit.HOURS.toSeconds(hours) - TimeUnit.MINUTES.toSeconds(minutes);
if (hours > 0) {
return String.format("%02d:%02d:%02d",hours,minutes,seconds);
}
else if (minutes > 0) {
return String.format("%02d:%02d",minutes,seconds);
}
else if (seconds > 0) {
return String.format("%02ds",seconds);
}
else if (seconds == 0) {
return "-:--";
}
else {
return "N/A";
}
}
| Format milliseconds into an human-readable track length. Examples: - 01:48:24 for 1 hour, 48 minutes, 24 seconds - 24:02 for 24 minutes, 2 seconds - 52s for 52 seconds |
public TeXFormula(TeXFormula f){
if (f != null) {
addImpl(f);
}
}
| Creates a new TeXFormula that is a copy of the given TeXFormula. <p> <b>Both TeXFormula's are independent of one another!</b> |
public static StoredLagGraphParams serializableInstance(){
return new StoredLagGraphParams();
}
| Generates a simple exemplar of this class to test serialization. |
public StringFormatter(final String formatString){
staticParts=new ArrayList<String>();
parameterPositions=new ArrayList<String>();
parameter=new HashMap<String,String>();
String current=formatString;
int index;
boolean hasStart=false;
do {
if (hasStart) {
index=current.indexOf(PARAMETER_END);
}
else {
index=current.indexOf(PARAMETER_START);
}
if (index >= 0) {
if (hasStart) {
final String param=current.substring(PARAMETER_START.length(),index);
current=current.substring(index + PARAMETER_END.length());
parameter.put(param,"");
parameterPositions.add(param);
}
else {
final String s=current.substring(0,index);
current=current.substring(index);
staticParts.add(s);
}
hasStart=!hasStart;
}
}
while (index >= 0);
staticParts.add(current);
}
| Creates a new instance of StringFormatter. |
private static boolean isSourceNewer(URL source,ClassNode cls){
try {
long lastMod;
if (source.getProtocol().equals("file")) {
String path=source.getPath().replace('/',File.separatorChar).replace('|',':');
File file=new File(path);
lastMod=file.lastModified();
}
else {
URLConnection conn=source.openConnection();
lastMod=conn.getLastModified();
conn.getInputStream().close();
}
return lastMod > getTimeStamp(cls);
}
catch ( IOException e) {
return false;
}
}
| returns true if the source in URL is newer than the class NOTE: copied from GroovyClassLoader |
public MonoMap(Publisher<? extends T> source,Function<? super T,? extends R> mapper){
super(source);
this.mapper=Objects.requireNonNull(mapper,"mapper");
}
| Constructs a StreamMap instance with the given source and mapper. |
public final void swap(int first,int second){
E in=get(first);
set(first,get(second));
set(second,in);
}
| Swaps two elements in the vector. |
public static void openDesktop(File file){
if (!java.awt.Desktop.isDesktopSupported()) {
log.warn("desktop not supported");
return;
}
java.awt.Desktop desktop=java.awt.Desktop.getDesktop();
if (!desktop.isSupported(java.awt.Desktop.Action.OPEN)) {
log.warn("desktop open not supported");
return;
}
try {
desktop.open(file);
}
catch ( IOException e) {
e.printStackTrace();
}
}
| This method uses Desktop which is supported in Java 1.6. |
private void removeEntries(){
table.clear();
}
| Remove all entries from map |
private void initialiseDirectory(){
if (temporaryDirectoryName != null) return;
String hostName;
try {
hostName=InetAddress.getLocalHost().getHostName();
}
catch ( UnknownHostException e) {
hostName="localhost";
}
StringBuilder directoryNameStart=new StringBuilder(hostName);
directoryNameStart.append('_');
directoryNameStart.append(DATE_FORMAT.format(new Date()));
directoryNameStart.append('_');
directoryNameStart.append(Long.toString(Math.abs(System.nanoTime()) % 1000000,36));
temporaryDirectoryName=directoryNameStart.toString();
}
| This method checks if the temporaryDirectory path has been determined. If not, it creates a new unique directory path and creates this directory. |
@Override public void eSet(int featureID,Object newValue){
switch (featureID) {
case N4JSPackage.IDENTIFIER_REF__STRICT_MODE:
setStrictMode((Boolean)newValue);
return;
case N4JSPackage.IDENTIFIER_REF__ID:
setId((IdentifiableElement)newValue);
return;
case N4JSPackage.IDENTIFIER_REF__ID_AS_TEXT:
setIdAsText((String)newValue);
return;
}
super.eSet(featureID,newValue);
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public void visit(String name,Object value){
if (av != null) {
av.visit(name,value);
}
}
| Visits a primitive value of the annotation. |
public EntidadException(String message){
this(message,null);
}
| Construye un objeto de la clase. |
public GitlabMilestone createMilestone(Serializable projectId,GitlabMilestone milestone) throws IOException {
String title=milestone.getTitle();
String description=milestone.getDescription();
Date dateDue=milestone.getDueDate();
return createMilestone(projectId,title,description,dateDue);
}
| Creates a new project milestone. |
@Override public void flush(){
}
| Does nothing. |
public static String stripPrefixIgnoreCase(String str,String prefix){
if (str.length() >= prefix.length() && str.substring(0,prefix.length()).equalsIgnoreCase(prefix)) {
return str.substring(prefix.length());
}
return null;
}
| Case insensitive version of stripPrefix. Analogous to the c++ functions strcaseprefix and var_strcaseprefix. |
public static String cutFromIndexOf(String string,String substring){
int i=string.indexOf(substring);
if (i != -1) {
string=string.substring(i);
}
return string;
}
| Cuts the string from the first index of provided substring to the end. |
private boolean seekAndReadNextLabel() throws IOException {
readInputBuffer();
while (mInputBufferLength > 0 && mInputBufferPosition < mInputBufferLength) {
final byte b=mInputBuffer[mInputBufferPosition];
if (b == '>') {
mInputBufferPosition++;
return readLabel();
}
else {
if (b == '@') {
throw new NoTalkbackSlimException(ErrorType.FASTQ);
}
else if (!Character.isWhitespace((char)b)) {
throw new NoTalkbackSlimException(ErrorType.BAD_FASTA_LABEL,name() != null ? name() : "<none>");
}
}
mInputBufferPosition++;
readInputBuffer();
}
final String filename=mSourceIt instanceof FileStreamIterator ? ((FileStreamIterator)mSourceIt).currentFile().getPath() : "<Not known>";
Diagnostic.warning(WarningType.NOT_FASTA_FILE,filename);
return false;
}
| Will continue iterating through input buffer values until the previous character is the FASTA label indicator (>). Will then read the label. |
public void paintInternalFrameBorder(SynthContext context,Graphics g,int x,int y,int w,int h){
paintBorder(context,g,x,y,w,h,null);
}
| Paints the border of an internal frame. |
@Override public ActionNode copy(){
return new ActionNode(nodeId,actionValues);
}
| Copies the action node. Note that only the node content is copied, not its connection with other nodes. |
@Override public String findEnumValue(Enum<?> e){
Class<?> enumClass=e.getDeclaringClass();
String enumValue=e.name();
try {
XmlEnumValue xmlEnumValue=enumClass.getDeclaredField(enumValue).getAnnotation(XmlEnumValue.class);
return (xmlEnumValue != null) ? xmlEnumValue.value() : enumValue;
}
catch ( NoSuchFieldException e1) {
throw new IllegalStateException("Could not locate Enum entry '" + enumValue + "' (Enum class "+ enumClass.getName()+ ")",e1);
}
}
| <p> !!! 12-Oct-2009, tatu: This is hideously slow implementation, called potentially for every single enum value being serialized. Should improve... |
public static RemoteViews createRemoteViews(Context context,boolean showPlayIcon){
RemoteViews remoteViews=new RemoteViews(context.getPackageName(),R.layout.remote_view);
int iconRes=showPlayIcon ? R.drawable.ic_play : R.drawable.ic_stop;
remoteViews.setImageViewResource(R.id.play_pause,iconRes);
return remoteViews;
}
| Creates a RemoteViews that will be shown as the bottom bar of the custom tab. |
protected void addLogSegmentToCache(String name,LogSegmentMetadata metadata){
logSegmentCache.add(name,metadata);
if (!metadata.isInProgress() && (lastLedgerRollingTimeMillis < metadata.getCompletionTime())) {
lastLedgerRollingTimeMillis=metadata.getCompletionTime();
}
if (reportGetSegmentStats) {
long ts=System.currentTimeMillis();
if (metadata.isInProgress()) {
long elapsedMillis=ts - metadata.getFirstTxId();
long elapsedMicroSec=TimeUnit.MILLISECONDS.toMicros(elapsedMillis);
if (elapsedMicroSec > 0) {
if (elapsedMillis > metadataLatencyWarnThresholdMillis) {
LOG.warn("{} received inprogress log segment in {} millis: {}",new Object[]{getFullyQualifiedName(),elapsedMillis,metadata});
}
getInprogressSegmentStat.registerSuccessfulEvent(elapsedMicroSec);
}
else {
negativeGetInprogressSegmentStat.registerSuccessfulEvent(-elapsedMicroSec);
}
}
else {
long elapsedMillis=ts - metadata.getCompletionTime();
long elapsedMicroSec=TimeUnit.MILLISECONDS.toMicros(elapsedMillis);
if (elapsedMicroSec > 0) {
if (elapsedMillis > metadataLatencyWarnThresholdMillis) {
LOG.warn("{} received completed log segment in {} millis : {}",new Object[]{getFullyQualifiedName(),elapsedMillis,metadata});
}
getCompletedSegmentStat.registerSuccessfulEvent(elapsedMicroSec);
}
else {
negativeGetCompletedSegmentStat.registerSuccessfulEvent(-elapsedMicroSec);
}
}
}
}
| Add the segment <i>metadata</i> for <i>name</i> in the cache. |
public static double convertMillisToSeconds(double millis){
return millis / SECOND_TO_MILLIS;
}
| Converts time in milliseconds to time in seconds. |
@Override public void eUnset(int featureID){
switch (featureID) {
case UmplePackage.IMMUTABLE___IMMUTABLE_1:
setImmutable_1(IMMUTABLE_1_EDEFAULT);
return;
}
super.eUnset(featureID);
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
protected static int[] concat(@Nullable int[] arr,int... obj){
int[] newArr;
if (arr == null || arr.length == 0) newArr=obj;
else {
newArr=Arrays.copyOf(arr,arr.length + obj.length);
System.arraycopy(obj,0,newArr,arr.length,obj.length);
}
return newArr;
}
| Concatenates elements to an int array. |
@Override public void characters(char ch[],int start,int len) throws SAXException {
if (!cdataElement) {
if (mIgnoreChars) {
writeText4Links();
writeEscUTF16(new String(ch),start,len,false);
}
else {
collectText4Links(ch,start,len);
}
}
else {
writeText4Links();
for (int i=start; i < start + len; i++) {
write(ch[i]);
}
}
super.characters(ch,start,len);
}
| Write character data. <p> Pass the event on down the filter chain for further processing. |
public void register(Property predicate,SPINFunctionDriver driver){
drivers.put(predicate,driver);
}
| Registers a new SPINFunctionDriver for a given key predicate. For example, SPARQLMotion functions are recognized via sm:body. Any previous entry will be overwritten. |
public void simulateMethod(SootMethod method,ReferenceVariable thisVar,ReferenceVariable returnVar,ReferenceVariable params[]){
String subSignature=method.getSubSignature();
{
defaultMethod(method,thisVar,returnVar,params);
return;
}
}
| Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. |
protected void serializeDocType(DocumentType node,boolean bStart) throws SAXException {
String docTypeName=node.getNodeName();
String publicId=node.getPublicId();
String systemId=node.getSystemId();
String internalSubset=node.getInternalSubset();
if (internalSubset != null && !"".equals(internalSubset)) {
if (bStart) {
try {
Writer writer=fSerializer.getWriter();
StringBuffer dtd=new StringBuffer();
dtd.append("<!DOCTYPE ");
dtd.append(docTypeName);
if (null != publicId) {
dtd.append(" PUBLIC \"");
dtd.append(publicId);
dtd.append('\"');
}
if (null != systemId) {
if (null == publicId) {
dtd.append(" SYSTEM \"");
}
else {
dtd.append(" \"");
}
dtd.append(systemId);
dtd.append('\"');
}
dtd.append(" [ ");
dtd.append(fNewLine);
dtd.append(internalSubset);
dtd.append("]>");
dtd.append(new String(fNewLine));
writer.write(dtd.toString());
writer.flush();
}
catch ( IOException e) {
throw new SAXException(Utils.messages.createMessage(MsgKey.ER_WRITING_INTERNAL_SUBSET,null),e);
}
}
}
else {
if (bStart) {
if (fLexicalHandler != null) {
fLexicalHandler.startDTD(docTypeName,publicId,systemId);
}
}
else {
if (fLexicalHandler != null) {
fLexicalHandler.endDTD();
}
}
}
}
| Serializes a Document Type Node. |
@Override public void handlePut(Operation op){
super.setState(op,op.getBody(EchoServiceState.class));
op.complete();
}
| Replaces entire state with the request body. |
protected <T extends OperationResponse>void completeOperation(ServerStateMachine.Result result,OperationResponse.Builder<?,T> builder,Throwable error,CompletableFuture<T> future){
if (isOpen()) {
if (result != null) {
builder.withIndex(result.index);
builder.withEventIndex(result.eventIndex);
if (result.result instanceof Exception) {
error=(Exception)result.result;
}
}
if (error == null) {
future.complete(logResponse(builder.withStatus(Response.Status.OK).withResult(result.result).build()));
}
else if (error instanceof CompletionException && error.getCause() instanceof CopycatException) {
future.complete(logResponse(builder.withStatus(Response.Status.ERROR).withError(((CopycatException)error.getCause()).getType()).build()));
}
else if (error instanceof CopycatException) {
future.complete(logResponse(builder.withStatus(Response.Status.ERROR).withError(((CopycatException)error).getType()).build()));
}
else {
future.complete(logResponse(builder.withStatus(Response.Status.ERROR).withError(CopycatError.Type.INTERNAL_ERROR).build()));
}
}
}
| Completes an operation. |
public static void initialize(@NonNull Context context){
if (sInstance == null) {
sInstance=new AndroidContext(context);
}
}
| The android context object cannot be created until the android has created the application object. The AndroidContext object must be initialized before other singletons can use it. |
public EntailmentClassificationOutcome_Type(JCas jcas,Type casType){
super(jcas,casType);
casImpl.getFSClassRegistry().addGeneratorForType((TypeImpl)this.casType,getFSGenerator());
casFeat_outcome=jcas.getRequiredFeatureDE(casType,"outcome","uima.cas.String",featOkTst);
casFeatCode_outcome=(null == casFeat_outcome) ? JCas.INVALID_FEATURE_CODE : ((FeatureImpl)casFeat_outcome).getCode();
}
| initialize variables to correspond with Cas Type and Features |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.