code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
int loadInt() throws IOException {
is.readFully(buf,0,4);
return luacLittleEndian ? (buf[3] << 24) | ((0xff & buf[2]) << 16) | ((0xff & buf[1]) << 8)| (0xff & buf[0]) : (buf[0] << 24) | ((0xff & buf[1]) << 16) | ((0xff & buf[2]) << 8)| (0xff & buf[3]);
}
| Load a 4-byte int value from the input stream |
public static void registerFirewallContentObserver(Context context,ContentObserver observer){
context.getContentResolver().registerContentObserver(Uri.parse(String.format(FIREWALL_URI_STR,"")),true,observer);
}
| Register firewall content provider observer |
private byte[] readLineBytesSlowly(){
ByteArrayOutputStream bout=null;
while (true) {
ensureFill();
byte b=buf[count++];
if (b == '\r') {
ensureFill();
byte c=buf[count++];
if (c == '\n') {
break;
}
if (bout == null) {
bout=new ByteArrayOutputStream(16);
}
bout.write(b);
bout.write(c);
}
else {
if (bout == null) {
bout=new ByteArrayOutputStream(16);
}
bout.write(b);
}
}
return bout == null ? new byte[0] : bout.toByteArray();
}
| Slow path in case a line of bytes cannot be read in one #fill() operation. This is still faster than creating the StrinbBuilder, String, then encoding as byte[] in Protocol, then decoding back into a String. |
public void addCommonBits(Geometry geom){
Translater trans=new Translater(commonCoord);
geom.apply(trans);
geom.geometryChanged();
}
| Adds the common coordinate bits back into a Geometry. The coordinates of the Geometry are changed. |
public X509Name(String dirName){
this(DefaultReverse,DefaultLookUp,dirName);
}
| Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or some such, converting it into an ordered set of name attributes. |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:33:39.977 -0500",hash_original_method="8F1CC5D4BDA427578EB68B001E341FDD",hash_generated_method="1276A69927832A306A1F253BA90ADEA6") public Builder detectNetwork(){
return enable(DETECT_NETWORK);
}
| Enable detection of network operations. |
public static CartFragment newInstance(boolean showTabBar){
CartFragment fragment=new CartFragment();
Bundle args=new Bundle();
args.putBoolean(SHOW_TAB_BAR,showTabBar);
fragment.setArguments(args);
return fragment;
}
| Use this factory method to create a new instance of this fragment using the provided parameters. |
private void updateProgress(int progress){
if (myHost != null && progress != previousProgress) {
myHost.updateProgress(progress);
}
previousProgress=progress;
}
| Used to communicate a progress update between a plugin tool and the main Whitebox user interface. |
public boolean isUndefined(final Field destination,final Field source){
info=null;
for ( IOperationAnalyzer analyzer : analyzers) if (analyzer.verifyConditions(destination,source)) info=analyzer.getInfoOperation(destination,source);
if (isNull(info)) info=undefinedOperation();
boolean conversionMethodExists=conversionAnalyzer.fieldsToCheck(destination,source);
OperationType operationType=info.getOperationType();
if (operationType.isUndefined() && !conversionMethodExists) return true;
if (conversionMethodExists) info.setInstructionType(operationType.isBasic() ? OperationType.BASIC_CONVERSION : OperationType.CONVERSION);
return false;
}
| This method analyzes the fields, calculates the info and returns true if operation is undefined. |
public void addHeaderView(View header){
if (header == null) {
throw new IllegalArgumentException("header is null");
}
mHeaderViews.add(header);
}
| addHead to RecyclerView |
protected static Instances toInstances(JSONNode json,boolean onlyHeader){
Instances result;
JSONNode header;
JSONNode attributes;
JSONNode data;
ArrayList<Attribute> atts;
Attribute att;
Instance inst;
int i;
int classIndex;
boolean[] classAtt;
header=json.getChild(HEADER);
if (header == null) {
System.err.println("No '" + HEADER + "' section!");
return null;
}
data=json.getChild(DATA);
if (data == null) {
System.err.println("No '" + DATA + "' section!");
return null;
}
attributes=header.getChild(ATTRIBUTES);
if (attributes == null) {
System.err.println("No '" + ATTRIBUTES + "' array!");
return null;
}
atts=new ArrayList<Attribute>();
classAtt=new boolean[1];
classIndex=-1;
for (i=0; i < attributes.getChildCount(); i++) {
att=toAttribute((JSONNode)attributes.getChildAt(i),classAtt);
if (att == null) {
System.err.println("Could not convert attribute #" + (i + 1) + "!");
return null;
}
if (classAtt[0]) classIndex=i;
atts.add(att);
}
result=new Instances(header.getChild(RELATION).getValue("unknown").toString(),atts,(onlyHeader ? 0 : data.getChildCount()));
result.setClassIndex(classIndex);
if (!onlyHeader) {
for (i=0; i < data.getChildCount(); i++) {
inst=toInstance((JSONNode)data.getChildAt(i),result);
if (inst == null) {
System.err.println("Could not convert instance #" + (i + 1) + "!");
return null;
}
result.add(inst);
}
}
return result;
}
| Turns a JSON object, if possible, into an Instances object. |
public int increment(){
assert (error == null);
return isPair ? 2 : 1;
}
| Returns the number of UTF-16 characters consumed by the previous parse. |
public HttpClient(String url){
this.url=url;
}
| Creates a new HttpClient object. |
private void highlightLine(final NaviNode node,final INaviCodeNode codeNode,final double y){
final double yPos=y - node.getY();
final int row=node.positionToRow(yPos);
final INaviInstruction instruction=CCodeNodeHelpers.lineToInstruction(codeNode,row);
if (instruction == null) {
return;
}
if (m_highlightedInstructions.contains(instruction)) {
codeNode.setInstructionColor(instruction,CHighlightLayers.HIGHLIGHTING_LAYER,null);
m_highlightedInstructions.remove(instruction);
}
else {
codeNode.setInstructionColor(instruction,CHighlightLayers.HIGHLIGHTING_LAYER,new Color(0x36D0FE));
m_highlightedInstructions.add(instruction);
}
}
| Highlights or unhighlights a line in a code node. |
public String toString(){
return this.getClass().getName() + "(" + tau+ ")";
}
| Returns a String representation of the receiver. |
private static long mixK1(long k1){
k1*=C1;
k1=Long.rotateLeft(k1,31);
k1*=C2;
return k1;
}
| Self mix of k1 |
private void invalidateCachedDurationForContainerSuites(){
myDuration=null;
myDurationIsCached=false;
final SMTestProxy containerSuite=getParent();
if (containerSuite != null) {
containerSuite.invalidateCachedDurationForContainerSuites();
}
}
| Recursively invalidates cached duration for container(parent) suites |
public void enableUserDefinedRPC(){
int enabledRpc=scannerParam.getTargetParamsEnabledRPC();
enabledRpc|=ScannerParam.RPC_USERDEF;
scannerParam.setTargetParamsEnabledRPC(enabledRpc);
}
| Force UserDefinedRPC setting |
public static String requestPath(URL url){
String fileOnly=url.getFile();
if (fileOnly == null) {
return "/";
}
else if (!fileOnly.startsWith("/")) {
return "/" + fileOnly;
}
else {
return fileOnly;
}
}
| Returns the path to request, like the '/' in 'GET / HTTP/1.1'. Never empty, even if the request URL is. Includes the query component if it exists. |
protected Packet(short packettype){
sig=new byte[]{'X','B','M','C'};
minver=0;
majver=2;
this.packettype=packettype;
}
| This is an Abstract class and cannot be instanced. Please use one of the Packet implementation Classes (PacketXXX). Implements an XBMC Event Client Packet. Type is to be specified at creation time, Payload can be added with the various appendPayload methods. Packet can be sent through UDP-Socket with method "send". |
public static void write(CharSequence data,Writer output) throws IOException {
if (data != null) {
write(data.toString(),output);
}
}
| Writes chars from a <code>CharSequence</code> to a <code>Writer</code>. |
void removePhiInput(int j){
assert (OP_phi == this.op);
Expr[] a=new Expr[args.length - 1];
System.arraycopy(args,0,a,0,j);
System.arraycopy(args,j + 1,a,j,args.length - j - 1);
args=a;
Edge[] ed=new Edge[pred.length - 1];
System.arraycopy(pred,0,ed,0,j);
System.arraycopy(pred,j + 1,ed,j,pred.length - j - 1);
pred=ed;
}
| Remove an input expression/edge from a phi node. This occurs when the input is copy-propagated, or if the input edge is unreachable. |
private void copyAndShift(Object src,long off,int len){
ensureCapacity(pos + len);
GridUnsafe.copyMemory(src,off,null,data + pos,len);
shift(len);
}
| Copy source object to the stream shifting position afterwards. |
public String toString(){
return ":" + getValue();
}
| Returns a text representation of this object. |
public static long parseOctal(byte[] header,int offset,int length){
long result=0;
boolean stillPadding=true;
int end=offset + length;
for (int i=offset; i < end; ++i) {
if (header[i] == 0) {
break;
}
if (header[i] == (byte)' ' || header[i] == '0') {
if (stillPadding) {
continue;
}
if (header[i] == (byte)' ') {
break;
}
}
stillPadding=false;
result=(result << 3) + (header[i] - '0');
}
return result;
}
| Parse an octal string from a header buffer. This is used for the file permission mode value. |
private PartialTextMatchRule(final String field,final String value){
super();
if (!RESOLVER.isField(field)) {
throw new IllegalArgumentException("Invalid partial text rule - " + field + " is not a supported field");
}
this.field=field;
this.value=value;
}
| Create new instance. |
public static Double toRef(double d){
return new Double(d);
}
| cast a double value to his (CFML) reference type Double |
public TimeSeriesTableModel(TimeSeries series,boolean editable){
this.series=series;
this.series.addChangeListener(this);
this.editable=editable;
}
| Creates a table model based on a time series. |
public DividerItemDecoration(Context context){
final TypedArray styledAttributes=context.obtainStyledAttributes(ATTRS);
mDivider=styledAttributes.getDrawable(0);
styledAttributes.recycle();
}
| Default divider will be used |
public ColumnInfo(String colHeader,String colSQL,Class<?> colClass){
this(colHeader,colSQL,colClass,true,false,null);
}
| Create Info Column (r/o and not color column) |
public void ifPresentOrElse(Consumer<? super T> action,Runnable emptyAction){
if (value != null) {
action.accept(value);
}
else {
emptyAction.run();
}
}
| If a value is present, performs the given action with the value, otherwise performs the given empty-based action. |
public void reset(){
packetCount=0;
octetCount=0;
setLong(packetCount,20,24);
setLong(octetCount,24,28);
delta=now=oldnow=0;
}
| Resets the reports (total number of bytes sent, number of packets sent, etc.) |
public static void bindBack(Form currentForm,LazyValue<Form> destination){
new SwipeBackSupport().bind(currentForm,destination);
}
| Binds support for swiping to the given forms |
public void testForInfiniteLoop(){
MonthlyCalendar monthlyCalendar=new MonthlyCalendar();
for (int i=1; i < 9; i++) {
monthlyCalendar.setDayExcluded(i,true);
}
Calendar c=Calendar.getInstance();
c.set(2007,11,8,12,0,0);
monthlyCalendar.getNextIncludedTime(c.getTime().getTime());
}
| Tests whether greater than the 7th of the month causes infinite looping. See: QUARTZ-636 |
public DriverPropertyInfo(String name,String value){
this.name=name;
this.value=value;
}
| Constructs a <code>DriverPropertyInfo</code> object with a given name and value. The <code>description</code> and <code>choices</code> are initialized to <code>null</code> and <code>required</code> is initialized to <code>false</code>. |
public Timeline end(){
if (isBuilt) throw new RuntimeException("You can't push anything to a timeline once it is started");
if (current == this) throw new RuntimeException("Nothing to end...");
current=current.parent;
return this;
}
| Closes the last nested timeline. |
static void errorMissingAttribute(String systemID,int lineNr,String elementName,String attributeName) throws XMLValidationException {
throw new XMLValidationException(XMLValidationException.MISSING_ATTRIBUTE,systemID,lineNr,elementName,attributeName,null,"Element " + elementName + " expects an attribute named "+ attributeName);
}
| Throws an XMLValidationException to indicate that an attribute is missing. |
private boolean pushLimitIntoOrder(Mutable<ILogicalOperator> opRef,Mutable<ILogicalOperator> opRef2,IOptimizationContext context) throws AlgebricksException {
PhysicalOptimizationConfig physicalOptimizationConfig=context.getPhysicalOptimizationConfig();
LimitOperator limitOp=(LimitOperator)opRef.getValue();
OrderOperator orderOp=(OrderOperator)opRef2.getValue();
long topK=-1;
if (orderOp.getPhysicalOperator().getOperatorTag() != PhysicalOperatorTag.STABLE_SORT) {
return false;
}
if (limitOp.getMaxObjects().getValue().getExpressionTag() == LogicalExpressionTag.CONSTANT) {
topK=AccessMethodUtils.getInt64Constant(limitOp.getMaxObjects());
if (topK > Integer.MAX_VALUE) {
return false;
}
if (topK < 0) {
topK=0;
}
}
else {
return false;
}
if (limitOp.getOffset().getValue() != null) {
if (limitOp.getOffset().getValue().getExpressionTag() == LogicalExpressionTag.CONSTANT) {
long offset=AccessMethodUtils.getInt64Constant(limitOp.getOffset());
if (offset < 0) {
offset=0;
}
if (offset >= Integer.MAX_VALUE - topK) {
return false;
}
topK+=offset;
}
else {
return false;
}
}
OrderOperator newOrderOp=new OrderOperator(orderOp.getOrderExpressions(),(int)topK);
newOrderOp.setPhysicalOperator(new StableSortPOperator(physicalOptimizationConfig.getMaxFramesExternalSort(),newOrderOp.getTopK()));
newOrderOp.getInputs().addAll(orderOp.getInputs());
newOrderOp.setExecutionMode(orderOp.getExecutionMode());
newOrderOp.recomputeSchema();
newOrderOp.computeDeliveredPhysicalProperties(context);
opRef2.setValue(newOrderOp);
context.computeAndSetTypeEnvironmentForOperator(newOrderOp);
context.addToDontApplySet(this,limitOp);
return true;
}
| Generate new ORDER operator that uses TopKSort module and replaces the old ORDER operator. |
public static void main(String[] args) throws IOException, SAXException, ParserConfigurationException {
final Pattern filter=getRequiredPerformanceCountersFilter();
System.err.println("required counter pattern: " + filter);
final CounterSet counterSet=new CounterSet();
for ( String s : args) {
final File file=new File(s);
readCountersFromFile(file,counterSet,filter,new DefaultInstrumentFactory(60,PeriodEnum.Minutes,false));
}
System.out.println("counters: " + counterSet.asXML(null));
}
| Utility may be used to read the required performance counters for the load balancer from zero or more files specified on the command line. The results are written using the XML interchange format on stdout. |
public synchronized void attachManagedResources(String routerPath,Router router){
if (SCHEMA_BASE_PATH.equals(routerPath)) {
this.schemaRouter=router;
}
else {
throw new SolrException(ErrorCode.SERVER_ERROR,routerPath + " not supported by the RestManager");
}
int numAttached=0;
for ( String resourceId : managed.keySet()) {
if (resourceId.startsWith(routerPath)) {
String path=resourceId.substring(routerPath.length());
attachManagedResource(managed.get(resourceId),path,router);
++numAttached;
}
}
log.info("Attached {} ManagedResource endpoints to Restlet router: {}",numAttached,routerPath);
}
| Attach managed resource paths to the given Restlet Router. |
protected double updateCloudetProcessingWithoutSchedulingFutureEventsForce(){
double currentTime=CloudSim.clock();
double minTime=Double.MAX_VALUE;
double timeDiff=currentTime - getLastProcessTime();
double timeFrameDatacenterEnergy=0.0;
Log.printLine("\n\n--------------------------------------------------------------\n\n");
Log.formatLine("Power data center: New resource usage for the time frame starting at %.2f:",currentTime);
for ( PowerContainerHost host : this.<PowerContainerHost>getHostList()) {
Log.printLine();
double time=host.updateContainerVmsProcessing(currentTime);
if (time < minTime) {
minTime=time;
}
Log.formatLine("%.2f: [Host #%d] utilization is %.2f%%",currentTime,host.getId(),host.getUtilizationOfCpu() * 100);
}
if (timeDiff > 0) {
Log.formatLine("\nEnergy consumption for the last time frame from %.2f to %.2f:",getLastProcessTime(),currentTime);
for ( PowerContainerHost host : this.<PowerContainerHost>getHostList()) {
double previousUtilizationOfCpu=host.getPreviousUtilizationOfCpu();
double utilizationOfCpu=host.getUtilizationOfCpu();
double timeFrameHostEnergy=host.getEnergyLinearInterpolation(previousUtilizationOfCpu,utilizationOfCpu,timeDiff);
timeFrameDatacenterEnergy+=timeFrameHostEnergy;
Log.printLine();
Log.formatLine("%.2f: [Host #%d] utilization at %.2f was %.2f%%, now is %.2f%%",currentTime,host.getId(),getLastProcessTime(),previousUtilizationOfCpu * 100,utilizationOfCpu * 100);
Log.formatLine("%.2f: [Host #%d] energy is %.2f W*sec",currentTime,host.getId(),timeFrameHostEnergy);
}
Log.formatLine("\n%.2f: Data center's energy is %.2f W*sec\n",currentTime,timeFrameDatacenterEnergy);
getDatacenterEnergyList().add(timeFrameDatacenterEnergy);
}
setPower(getPower() + timeFrameDatacenterEnergy);
String[] msg={Double.toString(currentTime),Double.toString(getPower())};
try {
getDatacenterEnergyWriter().writeTofile(msg);
}
catch ( IOException e) {
e.printStackTrace();
}
checkCloudletCompletion();
int numberOfActiveHosts=0;
for ( PowerContainerHost host : this.<PowerContainerHost>getHostList()) {
for ( ContainerVm vm : host.getCompletedVms()) {
getVmAllocationPolicy().deallocateHostForVm(vm);
getContainerVmList().remove(vm);
Log.printLine(String.format("VM #%d has been deallocated from host #%d",vm.getId(),host.getId()));
}
if (host.getVmList().size() != 0) {
numberOfActiveHosts++;
}
}
updateNumberOfVmsContainers();
getActiveHostList().add((double)numberOfActiveHosts);
int numberOfActiveVms=getNumberOfVms();
getActiveVmList().add((double)numberOfActiveVms);
int numberOfContainers=getNumberOfContainers();
Log.print(String.format("The number of Containers Up and running is %d",numberOfContainers));
Log.printLine();
Log.print(String.format("The number of Vms Up and running is %d",numberOfActiveVms));
Log.printLine();
Log.print(String.format("The number of Hosts Up and running is %d",numberOfActiveHosts));
Log.printLine();
setLastProcessTime(currentTime);
return minTime;
}
| Update cloudet processing without scheduling future events. |
@Override public boolean filter(long tweet){
return bipartiteGraph.getRightNodeDegree(tweet) < minEngagement;
}
| filter magic |
@Override public int read() throws IOException {
if (buf == null) {
throw new IOException();
}
if (pos < buf.length) {
return (buf[pos++] & 0xFF);
}
return in.read();
}
| Reads a single byte from this stream and returns it as an integer in the range from 0 to 255. If the pushback buffer does not contain any available bytes then a byte from the source input stream is returned. Blocks until one byte has been read, the end of the source stream is detected or an exception is thrown. |
public void estimateActivities(String filename,double radius){
int lineCounter=0;
int lineMultiplier=1;
try {
Scanner input=new Scanner(new BufferedReader(new FileReader(new File(filename))));
input.nextLine();
while (input.hasNextLine()) {
if (lineCounter == lineMultiplier) {
log.info("Number of activities processed: " + lineCounter);
lineMultiplier*=2;
}
String[] line=input.nextLine().split(",");
double x=Double.parseDouble(line[1]);
double y=Double.parseDouble(line[2]);
int position=line[3].indexOf("H");
int hour=Integer.parseInt(line[3].substring(position - 2,position));
Collection<MyGridCell> cells=grid.getDisk(x,y,radius);
float value=((float)1) / ((float)cells.size());
for ( MyGridCell cell : cells) {
cell.addToTotalCount(value);
cell.addToHourCount(hour,value);
}
lineCounter++;
}
}
catch ( FileNotFoundException e) {
e.printStackTrace();
}
log.info("Number of activities processed: " + lineCounter + " (Completed)");
}
| Assumes a comma-separated file format. |
public int nextInt(){
return nextInt(this.mean);
}
| Returns a random number from the distribution. |
public static boolean isValidIfd(int ifdId){
return ifdId == IfdId.TYPE_IFD_0 || ifdId == IfdId.TYPE_IFD_1 || ifdId == IfdId.TYPE_IFD_EXIF || ifdId == IfdId.TYPE_IFD_INTEROPERABILITY || ifdId == IfdId.TYPE_IFD_GPS;
}
| Returns true if the given IFD is a valid IFD. |
public boolean isValid(){
return (min <= max);
}
| Test whether the result is defined. |
@Override public boolean equals(Object obj){
if (obj == this) {
return true;
}
if (!(obj instanceof IntervalXYDelegate)) {
return false;
}
IntervalXYDelegate that=(IntervalXYDelegate)obj;
if (this.autoWidth != that.autoWidth) {
return false;
}
if (this.intervalPositionFactor != that.intervalPositionFactor) {
return false;
}
if (this.fixedIntervalWidth != that.fixedIntervalWidth) {
return false;
}
return true;
}
| Tests the delegate for equality with an arbitrary object. The equality test considers two delegates to be equal if they would calculate the same intervals for any given dataset (for this reason, the dataset itself is NOT included in the equality test, because it is just a reference back to the current 'owner' of the delegate). |
protected void onGLContextCreated(GL10 gl){
}
| This event is fired when OpenGL context is created |
public SearchRequestBuilder addAggregation(AbstractAggregationBuilder aggregation){
sourceBuilder().aggregation(aggregation);
return this;
}
| Adds an get to the search operation. |
public CTagSortingHandler(){
super(CTagTransferable.TAG_FLAVOR);
}
| Creates a new tag D&D handler object. |
public boolean isCostingLevelOrg(){
return COSTINGLEVEL_Organization.equals(getCostingLevel());
}
| Is Org Costing Level |
protected void createShape(DrawContext dc){
Globe globe=dc.getGlobe();
Vec4 pt1=globe.computePointFromLocation(this.position1);
Vec4 pt2=globe.computePointFromLocation(this.position2);
Vec4 pt3=globe.computePointFromLocation(this.position3);
LatLon mid=LatLon.interpolateGreatCircle(0.5,this.position1,this.position2);
Vec4 ptMid=globe.computePointFromLocation(mid);
Vec4 offset=pt3.subtract3(ptMid);
double width=pt1.subtract3(pt2).getLength3();
double length=offset.getLength3();
double distance=Math.min(width,length) * this.getCurvature();
Vec4 ptCorner1=pt1.add3(offset);
Vec4 ptCorner2=pt2.add3(offset);
List<Position> positions=new ArrayList<Position>();
int intervals=this.getIntervals();
positions.add(this.position1);
this.computeRoundCorner(globe,positions,pt1,ptCorner1,pt3,distance,intervals);
positions.add(this.position3);
this.computeRoundCorner(globe,positions,pt3,ptCorner2,pt2,distance,intervals);
positions.add(this.position2);
this.path=this.createPath();
this.path.setPositions(positions);
}
| Create a Path to render the line. |
@Override public void updateTimestamp(String columnLabel,Timestamp x) throws SQLException {
try {
if (isDebugEnabled()) {
debugCode("updateTimestamp(" + quote(columnLabel) + ", x);");
}
update(columnLabel,x == null ? (Value)ValueNull.INSTANCE : ValueTimestamp.get(x));
}
catch ( Exception e) {
throw logAndConvert(e);
}
}
| Updates a column in the current or insert row. |
protected void addFragment(int containerViewId,Fragment fragment,boolean addToBackStack){
if (containerViewId > -1 && fragment != null) {
FragmentTransaction ft=getSupportFragmentManager().beginTransaction();
ft.add(containerViewId,fragment,fragment.getClass().getName());
if (addToBackStack) {
ft.addToBackStack(null);
}
ft.commit();
}
}
| Adds a fragment to a container view |
private boolean bothLinksHaveSameLinkStats(Link linkA,Link linkB){
boolean bothLinksHaveSameLinkStats=true;
if (!linkA.getAllowedModes().equals(linkB.getAllowedModes())) {
bothLinksHaveSameLinkStats=false;
}
if (linkA.getFreespeed() != linkB.getFreespeed()) {
bothLinksHaveSameLinkStats=false;
}
if (linkA.getCapacity() != linkB.getCapacity()) {
bothLinksHaveSameLinkStats=false;
}
if (linkA.getNumberOfLanes() != linkB.getNumberOfLanes()) {
bothLinksHaveSameLinkStats=false;
}
return bothLinksHaveSameLinkStats;
}
| Compare link attributes. Return whether they are the same or not. |
protected final void writeOut(byte[] data) throws IOException {
writeOut(data,0,data.length);
}
| Write bytes to output or random access file. |
protected boolean testRanges(char ch){
int range_size=ranges.size();
if (range_size == 0) {
return false;
}
else if (range_size == 1) {
return ranges.get(0).includes(ch);
}
else {
int pos=find(ch);
if ((pos != range_size) && ranges.get(pos).includes(ch)) {
return true;
}
if ((pos != 0) && ranges.get(pos - 1).includes(ch)) {
return true;
}
return false;
}
}
| Tests to see if a single character matches the character set, but only looks at the ranges representation. |
private void testLobStaysOpenUntilCommitted() throws Exception {
Connection conn=getConnection();
stat=conn.createStatement();
stat.execute("create table test(id identity, c clob, b blob)");
PreparedStatement prep=conn.prepareStatement("insert into test values(null, ?, ?)");
prep.setString(1,"");
prep.setBytes(2,new byte[0]);
prep.execute();
Random r=new Random(1);
char[] chars=new char[100000];
for (int i=0; i < chars.length; i++) {
chars[i]=(char)r.nextInt(10000);
}
String d=new String(chars);
prep.setCharacterStream(1,new StringReader(d),-1);
byte[] bytes=new byte[100000];
r.nextBytes(bytes);
prep.setBinaryStream(2,new ByteArrayInputStream(bytes),-1);
prep.execute();
conn.setAutoCommit(false);
ResultSet rs=stat.executeQuery("select * from test order by id");
rs.next();
Clob c1=rs.getClob(2);
Blob b1=rs.getBlob(3);
rs.next();
Clob c2=rs.getClob(2);
Blob b2=rs.getBlob(3);
assertFalse(rs.next());
rs.close();
assertEquals(0,c1.length());
assertEquals(0,b1.length());
assertEquals(chars.length,c2.length());
assertEquals(bytes.length,b2.length());
assertEquals("",c1.getSubString(1,0));
assertEquals(new byte[0],b1.getBytes(1,0));
assertEquals(d,c2.getSubString(1,(int)c2.length()));
assertEquals(bytes,b2.getBytes(1,(int)b2.length()));
stat.execute("drop table test");
conn.close();
}
| According to the JDBC spec, BLOB and CLOB objects must stay open even if the result set is closed (see ResultSet.close). |
private static CreateVmResponse checkCreateVmResponse(CreateVmResponse createVmResponse) throws RpcException {
logger.info("Checking {}",createVmResponse);
switch (createVmResponse.getResult()) {
case OK:
break;
case DISK_NOT_FOUND:
throw new DiskNotFoundException(createVmResponse.getError());
case IMAGE_NOT_FOUND:
throw new ImageNotFoundException(createVmResponse.getError());
case INVALID_RESERVATION:
throw new InvalidReservationException(createVmResponse.getError());
case NETWORK_NOT_FOUND:
throw new NetworkNotFoundException(createVmResponse.getError());
case SYSTEM_ERROR:
throw new SystemErrorException(createVmResponse.getError());
default :
throw new RpcException(String.format("Unknown result: %s",createVmResponse.getResult()));
}
return createVmResponse;
}
| This method validates a CreateVmResponse object, raising an exception if the response reflects an operation failure. |
private void close(){
Window window=getWindow();
if (window != null) {
window.dispatchEvent(new WindowEvent(window,WindowEvent.WINDOW_CLOSING));
}
}
| Closes the Window. |
public NotBoundException(String s){
super(s);
}
| Constructs a <code>NotBoundException</code> with the specified detail message. |
public static InputStream toInputStream(String input){
return toInputStream(input,Charset.defaultCharset());
}
| Convert the specified string to an input stream, encoded as bytes using the default character encoding of the platform. |
protected static ExifParser parse(InputStream inputStream,int options,ExifInterface iRef) throws IOException, ExifInvalidFormatException {
return new ExifParser(inputStream,options,iRef);
}
| Parses the the given InputStream with the given options |
protected static void drawDataPoint(double x,double y,double xprev,double yprev,int size,int shape,Graphics gx){
drawDataPoint(x,y,size,shape,gx);
gx.drawLine((int)x,(int)y,(int)xprev,(int)yprev);
}
| Draws a data point at a given set of panel coordinates at a given size and connects a line to the previous point. |
public void notifySelectedAreasChanged(boolean isSet){
if (isSet) {
if (sasPanelState == sasPanelState.GONE) {
slideSas(SasPanelState.FULL);
}
}
else {
slideSas(SasPanelState.GONE);
}
}
| Notifies the activity that the selected areas have been changed by the user. |
public ByDay(Integer num,DayOfWeek day){
this.num=num;
this.day=day;
}
| Creates a BYDAY rule. |
@Override protected EClass eStaticClass(){
return SGraphPackage.Literals.CHOICE;
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
static boolean paramNameMatchesRegex(String paramName,String paramRegex){
assert paramRegex.charAt(0) == '/';
assert paramRegex.charAt(paramRegex.length() - 1) == '/';
assert paramRegex.length() > 2;
String regex=paramRegex.substring(1,paramRegex.length() - 1);
return Pattern.compile(regex).matcher(paramName).find();
}
| Returns whether a given parameterization matches a given regex. The regex should be in "/regex/" format. |
@Override public void close(){
setHosting(false);
}
| Sets hosting to false and returns without closing. Calling closeAdvisor will actually close this advisor. |
public boolean isDisplayValues(){
return mDisplayValues;
}
| Returns if the values should be displayed as text. |
private boolean journalRebuildRequired(){
final int redundantOpCompactThreshold=2000;
return redundantOpCount >= redundantOpCompactThreshold && redundantOpCount >= lruEntries.size();
}
| We only rebuild the journal when it will halve the size of the journal and eliminate at least 2000 ops. |
public boolean verify(byte[] signature){
if (forSigning) {
throw new IllegalStateException("RainbowDigestSigner not initialised for verification");
}
byte[] hash=new byte[messDigest.getDigestSize()];
messDigest.doFinal(hash,0);
return messSigner.verifySignature(hash,signature);
}
| This function verifies the signature of the message that has been updated, with the aid of the public key. |
public void doFilter(ServletRequest request,ServletResponse response,FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest httpRequest=(HttpServletRequest)request;
String entidad=null;
if (SesionHelper.authenticate(httpRequest)) {
entidad=SesionHelper.getEntidad(httpRequest);
}
if (entidad != null) {
httpRequest.getSession().setAttribute(ConstantesGestionUsuariosAdministracion.PARAMETRO_ID_ENTIDAD,entidad);
}
String oEntidad=(String)httpRequest.getSession().getAttribute(ConstantesGestionUsuariosAdministracion.PARAMETRO_ID_ENTIDAD);
MultiEntityContextHolder.setEntity(oEntidad);
filterChain.doFilter(request,response);
}
| Metodo que comprueba si existe la variable de la entidad sino para incluirla como ThreadLocal. |
protected static String copyRequestAttributeToURLParam(HttpServletRequest httpRequest,String attribute,String url){
String value=(String)httpRequest.getAttribute(attribute);
if (value != null) {
if (url.indexOf(attribute) == -1) {
char appendChar=(url.indexOf('?') == -1) ? '?' : '&';
url+=(appendChar + attribute + "="+ value);
}
}
return url;
}
| Copy the value of the given attribute from the given request as parameter to the given URL. |
private float strokeWidth(long width){
if (prefs != null) return Math.min(prefs.getMaxStrokeWidth(),STROKE_FACTOR / width);
return STROKE_FACTOR / width;
}
| Return a stroke width value that increases with zoom and is capped at a configurable value |
private Offer findOffer(final Long id){
return ofy().load().type(Offer.class).id(id).now();
}
| Searches an entity by ID. |
public static void makeFiles(ArrayList<File> d) throws FileNotFoundException {
for (int i=0; i < d.size(); i++) {
makeFiles(3,d.get(i),"TestJavafile",".java");
makeFiles(2,d.get(i),"TestTextfile",".txt");
makeFiles(2,d.get(i),"TestDatfile",".dat");
}
}
| Creates and adds files to a list |
protected void addBackupsToRestoreRequestBuffer(FbService service,ServiceRequestBuffer restoreSPB){
for ( PathSizeStruct pathSize : backupPaths) {
restoreSPB.addArgument(isc_spb_bkp_file,pathSize.getPath());
}
}
| Adds the list of backups to be used for the restore operation |
public void addTypeEqualities(TypeVariable target,AnnotatedTypeMirror type,Set<AnnotationMirror> hierarchies){
final Equalities equalities=targetToRecords.get(target).equalities;
final Set<AnnotationMirror> equalityTops=equalities.types.get(type);
if (equalityTops == null) {
equalities.types.put(type,new HashSet<>(hierarchies));
}
else {
equalityTops.addAll(hierarchies);
}
}
| Add a constraint indicating that target is equal to type in the given hierarchies |
private void toString(StringBuilder acc,int prec,boolean expand){
if (this.meta != null && !expand) {
acc.append(this.meta);
return;
}
boolean paren=op.getPrec() < prec;
if (paren) acc.append('(');
toString(acc,expand);
if (paren) acc.append(')');
}
| This handles adding parens, as necessary. |
public Duration minus(long amount){
return withDurationAdded(amount,-1);
}
| Returns a new duration with this length minus that specified. This instance is immutable and is not altered. <p> If the addition is zero, this instance is returned. |
static public Cylinder computeBoundingCylinder(Globe globe,double verticalExaggeration,Sector sector){
if (globe == null) {
String msg=Logging.getMessage("nullValue.GlobeIsNull");
Logging.logger().severe(msg);
throw new IllegalArgumentException(msg);
}
if (sector == null) {
String msg=Logging.getMessage("nullValue.SectorIsNull");
Logging.logger().severe(msg);
throw new IllegalArgumentException(msg);
}
double[] minAndMaxElevations=globe.getMinAndMaxElevations(sector);
return computeBoundingCylinder(globe,verticalExaggeration,sector,minAndMaxElevations[0],minAndMaxElevations[1]);
}
| Returns a cylinder that minimally surrounds the specified sector at a specified vertical exaggeration. |
@Override public V put(int key,@NotNull V value){
return put(key,value,false);
}
| Maps the specified <tt>key</tt> to the specified <tt>value</tt> in this table. Neither the key nor the value can be <tt>null</tt>. <p/> <p> The value can be retrieved by calling the <tt>get</tt> method with a key that is equal to the original key. |
public static DAOPortfolio newInstance(){
try {
final DAOPortfolio returnInstance=new DAOPortfolio();
DAOPortfolio code=null;
for (Iterator<Decode> iterCodes=returnInstance.getCodesDecodes().iterator(); iterCodes.hasNext(); ) {
code=(DAOPortfolio)iterCodes.next();
Portfolio portfolio=(Portfolio)code.getObject();
if (portfolio.getIsDefault()) return code;
}
if (null == code) {
code=returnInstance;
}
return code;
}
catch ( ValueTypeException e) {
return null;
}
}
| Method newInstance. |
public CActionOpenScriptingDialog(final JFrame parent){
super("New Scripting Window");
m_parent=Preconditions.checkNotNull(parent,"IE01846: Parent argument can not be null");
putValue(MNEMONIC_KEY,(int)"HK_MENU_SCRIPTING".charAt(0));
}
| Creates a new action object. |
public GemFireCheckedException(String message,Throwable cause){
super(message);
this.initCause(cause);
}
| Creates a new <code>GemFireException</code> with the given detail message and cause. |
protected IssueCommentsEntry insertComment(URL commentsFeedUrl,IssueCommentsEntry entry) throws IOException, ServiceException {
return service.insert(commentsFeedUrl,entry);
}
| Inserts a comment entry to the comments feed. |
@Override protected InfixExpression createCorrectOddnessCheck(ASTRewrite rewrite,Expression numberExpression){
Assert.isNotNull(rewrite);
Assert.isNotNull(numberExpression);
final AST ast=rewrite.getAST();
InfixExpression andOddnessCheck=ast.newInfixExpression();
ParenthesizedExpression parenthesizedExpression=ast.newParenthesizedExpression();
InfixExpression andExpression=ast.newInfixExpression();
andExpression.setLeftOperand((Expression)rewrite.createMoveTarget(numberExpression));
andExpression.setOperator(AND);
andExpression.setRightOperand(ast.newNumberLiteral("1"));
parenthesizedExpression.setExpression(andExpression);
andOddnessCheck.setLeftOperand(parenthesizedExpression);
andOddnessCheck.setOperator(EQUALS);
andOddnessCheck.setRightOperand(ast.newNumberLiteral("1"));
return andOddnessCheck;
}
| Creates the new <CODE>InfixExpression</CODE> <CODE>(x & 1) == 1</CODE>. |
static void appendConstant(final StringBuffer buf,final Object cst){
if (cst == null) {
buf.append("null");
}
else if (cst instanceof String) {
appendString(buf,(String)cst);
}
else if (cst instanceof Type) {
buf.append("Type.getType(\"");
buf.append(((Type)cst).getDescriptor());
buf.append("\")");
}
else if (cst instanceof Handle) {
buf.append("new Handle(");
Handle h=(Handle)cst;
buf.append("Opcodes.").append(HANDLE_TAG[h.getTag()]).append(", \"");
buf.append(h.getOwner()).append("\", \"");
buf.append(h.getName()).append("\", \"");
buf.append(h.getDesc()).append("\")");
}
else if (cst instanceof Byte) {
buf.append("new Byte((byte)").append(cst).append(')');
}
else if (cst instanceof Boolean) {
buf.append(((Boolean)cst).booleanValue() ? "Boolean.TRUE" : "Boolean.FALSE");
}
else if (cst instanceof Short) {
buf.append("new Short((short)").append(cst).append(')');
}
else if (cst instanceof Character) {
int c=((Character)cst).charValue();
buf.append("new Character((char)").append(c).append(')');
}
else if (cst instanceof Integer) {
buf.append("new Integer(").append(cst).append(')');
}
else if (cst instanceof Float) {
buf.append("new Float(\"").append(cst).append("\")");
}
else if (cst instanceof Long) {
buf.append("new Long(").append(cst).append("L)");
}
else if (cst instanceof Double) {
buf.append("new Double(\"").append(cst).append("\")");
}
else if (cst instanceof byte[]) {
byte[] v=(byte[])cst;
buf.append("new byte[] {");
for (int i=0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append(v[i]);
}
buf.append('}');
}
else if (cst instanceof boolean[]) {
boolean[] v=(boolean[])cst;
buf.append("new boolean[] {");
for (int i=0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append(v[i]);
}
buf.append('}');
}
else if (cst instanceof short[]) {
short[] v=(short[])cst;
buf.append("new short[] {");
for (int i=0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append("(short)").append(v[i]);
}
buf.append('}');
}
else if (cst instanceof char[]) {
char[] v=(char[])cst;
buf.append("new char[] {");
for (int i=0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append("(char)").append((int)v[i]);
}
buf.append('}');
}
else if (cst instanceof int[]) {
int[] v=(int[])cst;
buf.append("new int[] {");
for (int i=0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append(v[i]);
}
buf.append('}');
}
else if (cst instanceof long[]) {
long[] v=(long[])cst;
buf.append("new long[] {");
for (int i=0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append(v[i]).append('L');
}
buf.append('}');
}
else if (cst instanceof float[]) {
float[] v=(float[])cst;
buf.append("new float[] {");
for (int i=0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append(v[i]).append('f');
}
buf.append('}');
}
else if (cst instanceof double[]) {
double[] v=(double[])cst;
buf.append("new double[] {");
for (int i=0; i < v.length; i++) {
buf.append(i == 0 ? "" : ",").append(v[i]).append('d');
}
buf.append('}');
}
}
| Appends a string representation of the given constant to the given buffer. |
protected void basicProcess(final DM dm,final boolean waitForGrantor){
final boolean isDebugEnabled_DLS=logger.isTraceEnabled(LogMarker.DLS);
if (isDebugEnabled_DLS) {
logger.trace(LogMarker.DLS,"[basicProcess] {}",this);
}
final DLockQueryReplyMessage replyMsg=new DLockQueryReplyMessage();
replyMsg.setProcessorId(this.processorId);
replyMsg.setRecipient(getSender());
replyMsg.replyCode=DLockQueryReplyMessage.NOT_GRANTOR;
replyMsg.lesseeThread=null;
replyMsg.leaseId=DLockService.INVALID_LEASE_ID;
replyMsg.leaseExpireTime=0;
try {
if (svc == null || svc.isDestroyed()) return;
if (waitForGrantor) {
try {
this.grantor=DLockGrantor.waitForGrantor(this.svc);
}
catch ( InterruptedException e) {
Thread.currentThread().interrupt();
this.grantor=null;
}
}
if (grantor == null || grantor.isDestroyed()) {
return;
}
if (lockBatch) {
throw new UnsupportedOperationException("DLockQueryProcessor does not support lock batches");
}
else {
DLockGrantToken grantToken;
try {
grantToken=grantor.handleLockQuery(this);
}
catch ( InterruptedException e) {
Thread.currentThread().interrupt();
grantToken=null;
}
if (grantToken != null) {
synchronized (grantToken) {
if (!grantToken.isDestroyed()) {
replyMsg.lesseeThread=grantToken.getRemoteThread();
replyMsg.leaseId=grantToken.getLockId();
replyMsg.leaseExpireTime=grantToken.getLeaseExpireTime();
}
}
}
}
replyMsg.replyCode=DLockQueryReplyMessage.OK;
}
catch ( LockGrantorDestroyedException ignore) {
}
catch ( LockServiceDestroyedException ignore) {
}
catch ( RuntimeException e) {
replyMsg.setException(new ReplyException(e));
if (isDebugEnabled_DLS) {
logger.trace(LogMarker.DLS,"[basicProcess] caught RuntimeException",e);
}
}
catch ( VirtualMachineError err) {
SystemFailure.initiateFailure(err);
throw err;
}
catch ( Error e) {
SystemFailure.checkFailure();
replyMsg.setException(new ReplyException(e));
if (isDebugEnabled_DLS) {
logger.trace(LogMarker.DLS,"[basicProcess] caught Error",e);
}
}
finally {
if (dm.getId().equals(getSender())) {
replyMsg.setSender(getSender());
replyMsg.dmProcess(dm);
}
else {
dm.putOutgoing(replyMsg);
}
}
}
| Perform basic processing of this message. <p> this.svc and this.grantor must be set before calling this method. |
private static String searchDirectories(final File[] paths,final String[] exeNames){
for ( final File path : paths) {
if (path.exists()) {
for ( final File subDirectory : path.listFiles()) {
if (StringUtils.startsWith(subDirectory.getName(),TF_DIRECTORY_PREFIX) && subDirectory.isDirectory()) {
final String verifiedPath=checkTfPath(subDirectory.getPath(),exeNames);
if (verifiedPath != null) {
return verifiedPath;
}
}
}
}
}
return null;
}
| Search thru given directories to find one of the given acceptable tf commands |
public void testZipDeflateInflateStress() throws Exception {
final int DATA_SIZE=16384;
Random random=new Random(42);
for (int j=1; j <= 2; j++) {
byte[] input=new byte[DATA_SIZE];
if (j == 1) {
random.nextBytes(input);
}
else {
int pos=0;
while (pos < input.length) {
byte what=(byte)random.nextInt(256);
int howMany=random.nextInt(32);
if (pos + howMany >= input.length) {
howMany=input.length - pos;
}
Arrays.fill(input,pos,pos + howMany,what);
pos+=howMany;
}
}
for (int i=1; i <= 9; i++) {
System.out.println("ZipDeflateInflateStress test (" + j + ","+ i+ ")...");
byte[] zipped=new byte[2 * DATA_SIZE];
Deflater deflater=new Deflater(i);
deflater.setInput(input);
deflater.finish();
deflater.deflate(zipped);
deflater.end();
byte[] output=new byte[DATA_SIZE];
Inflater inflater=new Inflater();
inflater.setInput(zipped);
inflater.finished();
inflater.inflate(output);
inflater.end();
assertEquals(input,output);
}
}
}
| Native memory allocated by Deflater in system_server. The fix reduced some internal ZLIB buffers in size, so this test is trying to execute a lot of deflating to ensure that things are still working properly. http://b/1185084 |
@Override public void undo(){
File tempFile;
Instances inst;
ObjectInputStream ooi;
if (canUndo()) {
tempFile=m_UndoList.get(m_UndoList.size() - 1);
try {
ooi=new ObjectInputStream(new BufferedInputStream(new FileInputStream(tempFile)));
inst=(Instances)ooi.readObject();
ooi.close();
setInstances(inst);
notifyListener(new TableModelEvent(this,TableModelEvent.HEADER_ROW));
notifyListener(new TableModelEvent(this));
}
catch ( Exception e) {
e.printStackTrace();
}
tempFile.delete();
m_UndoList.remove(m_UndoList.size() - 1);
}
}
| undoes the last action |
public void sendReject(long refSeqNum,long sessionRejectReason,CharSequence text) throws IOException {
prepare(txMessage,Reject);
txMessage.addField(RefSeqNum).setInt(refSeqNum);
txMessage.addField(SessionRejectReason).setInt(sessionRejectReason);
txMessage.addField(Text).setString(text);
send(txMessage);
}
| Send a Reject(3) message. |
public void updateAccess(boolean chat,boolean editor,boolean commercial,boolean user,boolean subs,boolean follow){
boolean empty=currentUsername.isEmpty() || currentToken.isEmpty();
access.setVisible(!empty);
accessLabel.setVisible(!empty);
StringBuilder b=new StringBuilder("<html><body style='line-height:28px;'>");
b.append(accessStatusImage(chat)).append(" Chat access<br />");
b.append(accessStatusImage(user)).append(" Read user info<br />");
b.append(accessStatusImage(editor)).append(" Editor access<br />");
b.append(accessStatusImage(commercial)).append(" Run commercials<br />");
b.append(accessStatusImage(subs)).append(" Show subscribers<br />");
b.append(accessStatusImage(follow)).append(" Follow channels");
access.setText(b.toString());
update();
}
| Update the text showing what scopes are available. |
public void beginSnapshotting(String workspaceId) throws NotFoundException, ConflictException {
try (StripedLocks.WriteLock ignored=stripedLocks.acquireWriteLock(workspaceId)){
getRunningState(workspaceId).status=SNAPSHOTTING;
}
}
| Changes workspace runtimes status from RUNNING to SNAPSHOTTING. |
public GetEventsParams withUntilSecond(long untilSecond){
this.untilSecond=untilSecond;
return this;
}
| Adds until time filter to this parameters. |
private Function<String,TagState> newTagRetriever(TaggingClient client){
return null;
}
| Builds a function to retrieve tags given and endpoint. |
@Override public boolean eIsSet(int featureID){
switch (featureID) {
case N4JSPackage.FUNCTION_DEFINITION__DEFINED_TYPE:
return definedType != null;
case N4JSPackage.FUNCTION_DEFINITION__FPARS:
return fpars != null && !fpars.isEmpty();
case N4JSPackage.FUNCTION_DEFINITION__RETURN_TYPE_REF:
return returnTypeRef != null;
case N4JSPackage.FUNCTION_DEFINITION__GENERATOR:
return generator != GENERATOR_EDEFAULT;
case N4JSPackage.FUNCTION_DEFINITION__DECLARED_ASYNC:
return declaredAsync != DECLARED_ASYNC_EDEFAULT;
}
return super.eIsSet(featureID);
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.