code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
public static Float toFloat(Number self){
return self.floatValue();
}
| Transform a Number into a Float |
public void removeBindingListener(){
AbstractDocument doc=(AbstractDocument)document;
XBLManager xm=doc.getXBLManager();
if (xm instanceof DefaultXBLManager) {
DefaultXBLManager dxm=(DefaultXBLManager)xm;
dxm.removeBindingListener(bindingListener);
dxm.removeContentSelectionChangedListener(contentListener);
}
}
| Removes the BindingListener from the XBLManager. |
public RegexValidator(String regex){
this(regex,true);
}
| Construct a <i>case sensitive</i> validator for a single regular expression. |
private void cancelUploadForAccount(String accountName){
Iterator<String> it=mPendingUploads.keySet().iterator();
Log_OC.d(TAG,"Number of pending updloads= " + mPendingUploads.size());
while (it.hasNext()) {
String key=it.next();
Log_OC.d(TAG,"mPendingUploads CANCELLED " + key);
if (key.startsWith(accountName)) {
synchronized (mPendingUploads) {
mPendingUploads.remove(key);
}
}
}
}
| Remove uploads of an account |
public void testMultiplyDiffScalePosNeg(){
String a="1231212478987482988429808779810457634781384756794987";
int aScale=10;
String b="747233429293018787918347987234564568";
int bScale=-10;
String c="920003122862175749786430095741145455670101391569026662845893091880727173060570190220616";
int cScale=0;
BigDecimal aNumber=new BigDecimal(new BigInteger(a),aScale);
BigDecimal bNumber=new BigDecimal(new BigInteger(b),bScale);
BigDecimal result=aNumber.multiply(bNumber);
assertEquals("incorrect value",c,result.toString());
assertEquals("incorrect scale",cScale,result.scale());
}
| Multiply two numbers of different scales |
private void readFigTreeBlock(Map<String,Object> settings) throws ImportException, IOException {
String command=helper.readToken(";");
while (!command.equalsIgnoreCase("END")) {
if (command.equalsIgnoreCase("SET")) {
while (helper.getLastDelimiter() != ';') {
String key=helper.readToken("=;");
if (helper.getLastDelimiter() != '=') {
throw new ImportException("Subcommand, " + key + ", is missing a value in command, "+ command+ ", in FIGTREE block");
}
String value=helper.readToken(";");
settings.put(key,parseValue(value));
}
}
else {
throw new ImportException("Unknown command, " + command + ", in FIGTREE block");
}
command=helper.readToken(";");
}
findEndBlock();
}
| Reads a 'FigTree' block. |
@Override public void write(int b) throws IOException {
if (debug > 1) {
System.out.println("write " + b + " in CompressionResponseStream ");
}
if (closed) throw new IOException("Cannot write to a closed output stream");
if (bufferCount >= buffer.length) {
flushToGZip();
}
buffer[bufferCount++]=(byte)b;
}
| Write the specified byte to our output stream. |
public static boolean isVCardType(String mime){
mime=mime.toLowerCase();
return "text/vcard".equals(mime) || "text/x-vcard".equals(mime);
}
| Is a VCard type |
public DuplicateException(String message,Throwable cause){
super(message,cause);
}
| Creates a new instance of DuplicateException. |
static LiveCalc calculateLiveness(ParseTreeNode node){
return liveness(node,new LiveSet(node));
}
| Compute liveness for the given tree. |
public void map(Text key,Writable value,OutputCollector<Text,ObjectWritable> output,Reporter reporter) throws IOException {
ObjectWritable objWrite=new ObjectWritable();
objWrite.set(value);
output.collect(key,objWrite);
}
| Wraps all values in ObjectWritables. |
public void Initialise(SceModule module,int entry_addr,int attr,String pspfilename,int moduleid,int gp,boolean fromSyscall){
int rootStackSize=(fromSyscall ? 0x8000 : 0x40000);
if (module != null && module.module_start_thread_stacksize > 0) {
rootStackSize=module.module_start_thread_stacksize;
}
int rootMpidStack=module.mpiddata > 0 ? module.mpiddata : USER_PARTITION_ID;
int rootInitPriority=0x20;
if (module != null && module.module_start_thread_priority > 0) {
rootInitPriority=module.module_start_thread_priority;
}
if (log.isDebugEnabled()) {
log.debug(String.format("Creating root thread: entry=0x%08X, priority=%d, stackSize=0x%X, attr=0x%X",entry_addr,rootInitPriority,rootStackSize,attr));
}
currentThread=new SceKernelThreadInfo("root",entry_addr,rootInitPriority,rootStackSize,attr,rootMpidStack);
currentThread.moduleid=moduleid;
threadMap.put(currentThread.uid,currentThread);
if (!currentThread.isKernelMode()) {
currentThread.attr|=PSP_THREAD_ATTR_USER;
}
hleKernelSetThreadArguments(currentThread,pspfilename);
currentThread.cpuContext._gp=gp;
idle0.cpuContext._gp=gp;
idle1.cpuContext._gp=gp;
currentThread.status=PSP_THREAD_READY;
currentThread.status=PSP_THREAD_RUNNING;
currentThread.restoreContext();
}
| call this when resetting the emulator |
protected DataAttribute(boolean padding){
super(DATA);
this.padding=padding;
}
| Creates a new instance of this class. |
ByteSetting(Properties defaultProps,Properties props,String key,byte defaultByte){
super(defaultProps,props,key,String.valueOf(defaultByte),false,null,null);
}
| Creates a new <tt>SettingBool</tt> instance with the specified key and default value. |
public boolean isExclude(){
Object oo=get_Value(COLUMNNAME_IsExclude);
if (oo != null) {
if (oo instanceof Boolean) return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
| Get Exclude. |
private void coerceAcceptanceProbability(CoercableMCMCOperator op,double logr){
if (isCoercable(op)) {
final double p=op.getCoercableParameter();
final double i=schedule.getOptimizationTransform(MCMCOperator.Utils.getOperationCount(op));
final double target=op.getTargetAcceptanceProbability();
final double newp=p + ((1.0 / (i + 1.0)) * (Math.exp(logr) - target));
if (newp > -Double.MAX_VALUE && newp < Double.MAX_VALUE) {
op.setCoercableParameter(newp);
}
}
}
| Updates the proposal parameter, based on the target acceptance probability This method relies on the proposal parameter being a decreasing function of acceptance probability. |
public static boolean isDistinct(int[] array,int num){
for (int i=0; i < array.length; i++) {
if (num == array[i]) return false;
}
return true;
}
| Method isDistinct returns true if number is not in array false otherwise |
protected final IRegion alignRegion(IRegion region,IDocument document){
if (region == null) return null;
try {
int start=document.getLineOfOffset(region.getOffset());
int end=document.getLineOfOffset(region.getOffset() + region.getLength());
if (start > end) return null;
int offset=document.getLineOffset(start);
int endOffset;
if (document.getNumberOfLines() > end + 1) endOffset=document.getLineOffset(end + 1);
else endOffset=document.getLineOffset(end) + document.getLineLength(end);
return new Region(offset,endOffset - offset);
}
catch ( BadLocationException x) {
return null;
}
}
| Aligns <code>region</code> to start and end at a line offset. The region's start is decreased to the next line offset, and the end offset increased to the next line start or the end of the document. <code>null</code> is returned if <code>region</code> is <code>null</code> itself or if region's end line is less than its start line. |
public static byte[] decodeWebSafe(String s) throws Base64DecoderException {
byte[] bytes=s.getBytes();
return decodeWebSafe(bytes,0,bytes.length);
}
| Decodes data from web safe Base64 notation. Web safe encoding uses '-' instead of '+', '_' instead of '/' |
public void flush() throws Exception {
buffer.write(result);
buffer.clear();
result.flush();
}
| This is used to flush the writer when the XML if it has been buffered. The flush method is used by the node writer after an end element has been written. Flushing ensures that buffering does not affect the result of the node writer. |
@Override public boolean execute(String sql,int autoGeneratedKeys) throws SQLException {
try {
if (isDebugEnabled()) {
debugCode("execute(" + quote(sql) + ", "+ autoGeneratedKeys+ ");");
}
throw DbException.get(ErrorCode.METHOD_NOT_ALLOWED_FOR_PREPARED_STATEMENT);
}
catch ( Exception e) {
throw logAndConvert(e);
}
}
| Calling this method is not legal on a PreparedStatement. |
public static DatacenterBroker createBroker(){
DatacenterBroker broker=null;
try {
broker=new PowerDatacenterBroker("Broker");
}
catch ( Exception e) {
e.printStackTrace();
System.exit(0);
}
return broker;
}
| Creates the broker. |
@SuppressWarnings("nullness") ValueForKeyIterator(@Nullable Object key){
this.key=key;
next=keyToKeyHead.get(key);
}
| Constructs a new iterator over all values for the specified key. |
public SusiThought(JSONObject json){
this();
if (json.has(this.metadata_name)) this.put(this.metadata_name,json.getJSONObject(this.metadata_name));
if (json.has(this.data_name)) this.setData(json.getJSONArray(this.data_name));
if (json.has("actions")) this.put("actions",json.getJSONArray("actions"));
}
| create a clone of a json object as a SusiThought object |
public boolean isHandshakeComplete(){
return this.state.isHandshakeComplete();
}
| Is this a state in which the handshake has completed? |
protected void updateFunctionGroup2(int fns){
this.f5=((fns & CbusConstants.CBUS_F5) == CbusConstants.CBUS_F5);
this.f6=((fns & CbusConstants.CBUS_F6) == CbusConstants.CBUS_F6);
this.f7=((fns & CbusConstants.CBUS_F7) == CbusConstants.CBUS_F7);
this.f8=((fns & CbusConstants.CBUS_F8) == CbusConstants.CBUS_F8);
}
| Update the state of locomotive functions F5, F6, F7, F8 in response to a message from the hardware |
public int next(){
int node;
while ((node=super.next()) != END) {
node=makeNodeIdentity(node);
int parent=_parent(node);
int child=_firstch(parent);
int pos=0;
do {
int type=_type(child);
if (ELEMENT_NODE == type) pos++;
}
while ((pos < _pos) && (child=_nextsib(child)) != END);
if (node == child) return node;
}
return (END);
}
| Get the next node in the iteration. |
public static <T>List<T> synchronizedList(List<T> list){
if (list == null) {
throw new NullPointerException("list == null");
}
if (list instanceof RandomAccess) {
return new SynchronizedRandomAccessList<T>(list);
}
return new SynchronizedList<T>(list);
}
| Returns a wrapper on the specified List which synchronizes all access to the List. |
public ProductId(String value){
super(value);
}
| Creates a new product identifier property. |
public Vertex evaluateFunction(Vertex function,Map<Vertex,Vertex> variables,Network network,long startTime,long maxTime,int stack){
try {
if (function.getData() instanceof BinaryData) {
function=SelfDecompiler.getDecompiler().parseFunctionByteCode(function,(BinaryData)function.getData(),function.getNetwork());
return evaluateFunction(function,variables,network,startTime,maxTime,stack);
}
}
catch ( IOException exception) {
network.getBot().log(this,exception);
throw new SelfExecutionException(function,exception);
}
Vertex result=null;
Vertex returnPrimitive=network.createVertex(Primitive.RETURN);
List<Relationship> operations=function.orderedRelationships(Primitive.DO);
if (operations != null) {
for ( Relationship expression : operations) {
result=evaluateExpression(expression.getTarget(),variables,network,startTime,maxTime,stack);
if (variables.containsKey(returnPrimitive)) {
variables.remove(returnPrimitive);
return result;
}
}
}
if (result == null) {
result=function;
}
return result;
}
| Evaluate the function and return the result. |
public void addTitle(Title title){
getTitles().add(title);
}
| Adds a new title. |
public void velocitySolver(){
addSource(u,uOld);
addSource(v,vOld);
vorticityConfinement(uOld,vOld);
addSource(u,uOld);
addSource(v,vOld);
buoyancy(vOld);
addSource(v,vOld);
swap(u,uOld);
diffusion(0,u,uOld,viscosity);
swap(v,vOld);
diffusion(0,v,vOld,viscosity);
project(u,v,uOld,vOld);
swap(u,uOld);
swap(v,vOld);
advect(1,u,uOld,uOld,vOld);
advect(2,v,vOld,uOld,vOld);
project(u,v,uOld,vOld);
for (int i=0; i < size; i++) {
uOld[i]=vOld[i]=0;
}
}
| The basic velocity solving routine as described by Stam. |
public void requestPreviewFrame(Handler handler,int message){
if (camera != null && previewing) {
previewCallback.setHandler(handler,message);
if (useOneShotPreviewCallback) {
camera.setOneShotPreviewCallback(previewCallback);
}
else {
camera.setPreviewCallback(previewCallback);
}
}
}
| A single preview frame will be returned to the handler supplied. The data will arrive as byte[] in the message.obj field, with width and height encoded as message.arg1 and message.arg2, respectively. |
private void upgradeToTargetVolume(final Volume volume,final VirtualPool vpool,final VirtualPoolChangeParam cosChangeParam,final String taskId) throws InternalException {
VirtualPoolCapabilityValuesWrapper capabilities=new VirtualPoolCapabilityValuesWrapper();
capabilities.put(VirtualPoolCapabilityValuesWrapper.BLOCK_CONSISTENCY_GROUP,volume.getConsistencyGroup());
List<Recommendation> recommendations=getRecommendationsForVirtualPoolChangeRequest(volume,vpool,cosChangeParam);
if (recommendations.isEmpty()) {
throw APIException.badRequests.noStorageFoundForVolume();
}
Project project=_dbClient.queryObject(Project.class,volume.getProject());
VirtualArray varray=_dbClient.queryObject(VirtualArray.class,volume.getVirtualArray());
VolumeCreate param=new VolumeCreate(volume.getLabel(),String.valueOf(volume.getCapacity()),1,vpool.getId(),volume.getVirtualArray(),volume.getProject().getURI());
capabilities.put(VirtualPoolCapabilityValuesWrapper.RESOURCE_COUNT,new Integer(1));
if (volume.getIsComposite()) {
capabilities.put(VirtualPoolCapabilityValuesWrapper.IS_META_VOLUME,volume.getIsComposite());
capabilities.put(VirtualPoolCapabilityValuesWrapper.META_VOLUME_TYPE,volume.getCompositionType());
capabilities.put(VirtualPoolCapabilityValuesWrapper.META_VOLUME_MEMBER_COUNT,volume.getMetaMemberCount());
capabilities.put(VirtualPoolCapabilityValuesWrapper.META_VOLUME_MEMBER_SIZE,volume.getMetaMemberSize());
_log.debug(String.format("Capabilities : isMeta: %s, Meta Type: %s, Member size: %s, Count: %s",capabilities.getIsMetaVolume(),capabilities.getMetaVolumeType(),capabilities.getMetaVolumeMemberSize(),capabilities.getMetaVolumeMemberCount()));
}
Map<VpoolUse,List<Recommendation>> recommendationMap=new HashMap<VpoolUse,List<Recommendation>>();
recommendationMap.put(VpoolUse.ROOT,recommendations);
createVolumes(param,project,varray,vpool,recommendationMap,null,taskId,capabilities);
}
| Upgrade a local block volume to a protected SRDF volume |
static double expint(int p,final double result[]){
final double xs[]=new double[2];
final double as[]=new double[2];
final double ys[]=new double[2];
xs[0]=2.718281828459045;
xs[1]=1.4456468917292502E-16;
split(1.0,ys);
while (p > 0) {
if ((p & 1) != 0) {
quadMult(ys,xs,as);
ys[0]=as[0];
ys[1]=as[1];
}
quadMult(xs,xs,as);
xs[0]=as[0];
xs[1]=as[1];
p>>=1;
}
if (result != null) {
result[0]=ys[0];
result[1]=ys[1];
resplit(result);
}
return ys[0] + ys[1];
}
| Compute exp(p) for a integer p in extended precision. |
private void createStopFacilities(){
Map<Id<TransitStopFacility>,TransitStopFacility> stopFacilities=this.transitSchedule.getFacilities();
for ( OsmParser.OsmRelation relation : relations.values()) {
if (stop_area.matches(relation.tags)) {
String stopPostAreaId=relation.tags.get(OsmTag.NAME);
for ( OsmParser.OsmRelationMember member : relation.members) {
if (member.role.equals(OsmValue.STOP)) {
TransitStopFacility newStopFacility=createStopFacilityFromOsmNode(nodes.get(member.refId),stopPostAreaId);
if (!stopFacilities.containsValue(newStopFacility)) {
this.transitSchedule.addStopFacility(newStopFacility);
}
}
}
}
}
for ( OsmParser.OsmNode node : nodes.values()) {
if (stop_position.matches(node.tags)) {
if (!stopFacilities.containsKey(Id.create(node.id,TransitStopFacility.class))) {
this.transitSchedule.addStopFacility(createStopFacilityFromOsmNode(node));
}
}
}
}
| creates stop facilities from nodes and adds them to the schedule |
private List<ErrorInformation> validate(final PasswordData password,final PasswordData oldPassword,final UserInfoBean uiBean) throws PwmUnrecoverableException {
final List<ErrorInformation> internalResults=internalPwmPolicyValidator(password,oldPassword,uiBean);
if (pwmApplication != null) {
final List<ErrorInformation> externalResults=invokeExternalRuleMethods(pwmApplication.getConfig(),policy,password,uiBean);
internalResults.addAll(externalResults);
}
return internalResults;
}
| Validates a password against the configured rules of PWM. No directory operations are performed here. |
public void testConnectANTSensor_Cadence(){
if (!runTest) {
Log.d(TAG,BigTestUtils.DISABLE_MESSAGE);
return;
}
useANTSeonsor();
assertTrue(checkSensorsStatus_notRecording());
checkANTSensorsStatus(R.id.sensor_state_cadence);
}
| Tests connecting to a cadence ANT+ sensor. |
public TextEvaluator(String expr){
super(expr);
}
| Construct with a full predicate expression. |
private static void sort1(int[] x,int off,int len){
if (len < 7) {
for (int i=off; i < len + off; i++) for (int j=i; j > off && x[j - 1] > x[j]; j--) swap(x,j,j - 1);
return;
}
int m=off + (len >> 1);
if (len > 7) {
int l=off;
int n=off + len - 1;
if (len > 40) {
int s=len / 8;
l=med3(x,l,l + s,l + 2 * s);
m=med3(x,m - s,m,m + s);
n=med3(x,n - 2 * s,n - s,n);
}
m=med3(x,l,m,n);
}
int v=x[m];
int a=off, b=a, c=off + len - 1, d=c;
while (true) {
while (b <= c && x[b] <= v) {
if (x[b] == v) swap(x,a++,b);
b++;
}
while (c >= b && x[c] >= v) {
if (x[c] == v) swap(x,c,d--);
c--;
}
if (b > c) break;
swap(x,b++,c--);
}
int s, n=off + len;
s=Math.min(a - off,b - a);
vecswap(x,off,b - s,s);
s=Math.min(d - c,n - d - 1);
vecswap(x,b,n - s,s);
if ((s=b - a) > 1) sort1(x,off,s);
if ((s=d - c) > 1) sort1(x,n - s,s);
}
| Sorts the specified sub-array of integers into ascending order. |
private void initialize(){
HDRequest request=testStep.getRequest();
HDResponse response=testStep.getResponse();
String proxy=variables.getVariable("TANK_HTTP_PROXY");
if (StringUtils.isNotBlank(proxy)) {
try {
String[] proxyInfo=StringUtils.split(":");
int proxyPort=80;
if (proxy.startsWith("http://")) {
proxy=proxy.substring(7);
}
else if (proxy.startsWith("https://")) {
proxy=proxy.substring(8);
proxyPort=443;
}
if (proxyInfo.length > 2) {
LOG.error("Proxy should be specified as proxyHost:proxyPort.");
}
else {
if (proxyInfo.length == 2) {
proxyPort=NumberUtils.toInt(proxyInfo[1]);
}
String proxyHost=proxyInfo[0];
tsc.getHttpClient().setProxy(proxyHost,proxyPort);
}
}
catch ( Exception e) {
LOG.error("Error setting proxy " + proxy + ": "+ e,e);
}
}
host=processHost(request.getHost());
loggingKey=request.getLoggingKey();
method=request.getMethod();
path=processPath(request.getPath());
reqFormat=StringUtils.isEmpty(request.getReqFormat()) ? "nvp" : request.getReqFormat();
protocol=processProtocol(request.getProtocol());
port=processPort(request.getPort());
if (port == null) {
port="-1";
}
respFormat=StringUtils.isEmpty(response.getRespFormat()) ? "json" : response.getRespFormat();
baseRequest=HttpRequestFactory.getHttpRequest(reqFormat,tsc.getHttpClient());
baseRequest.setHost(host);
baseRequest.setProtocol(protocol);
baseRequest.setPort(port);
baseRequest.setPath(path);
List<Header> postDatas=request.getPostDatas();
List<Header> queryStringPairs=request.getQueryString();
List<Header> requestHeaders=request.getRequestHeaders();
processQueryString(queryStringPairs);
populateHeaders(requestHeaders);
baseResponse=HttpResponseFactory.getHttpResponse(respFormat);
populatePostData(postDatas);
if (!StringUtils.isBlank(request.getPayload()) && !reqFormat.equalsIgnoreCase(ScriptConstants.NVP_TYPE)) {
String payload=request.getPayload();
baseRequest.setBody(variables.evaluate(payload));
}
LogUtil.getLogEvent().setRequest(baseRequest);
tsc.getHttpClient().setProxy(null,-1);
}
| initializes the variables |
public void showSecondaryMenu(){
mSlidingMenu.showSecondaryMenu();
}
| Open the SlidingMenu and show the secondary menu view. Will default to the regular menu if there is only one. |
protected RuntimeException(@Nullable String message,@Nullable Throwable cause,boolean enableSuppression,boolean writableStackTrace){
super(message,cause,enableSuppression,writableStackTrace);
}
| Constructs a new runtime exception with the specified detail message, cause, suppression enabled or disabled, and writable stack trace enabled or disabled. |
public final void yyclose() throws java.io.IOException {
zzAtEOF=true;
zzEndRead=zzStartRead;
if (zzReader != null) zzReader.close();
}
| Closes the input stream. |
public void stressTest_multiTenancy_967() throws Exception {
doMultiTenancyStressTest(TimeUnit.HOURS.toMillis(1));
}
| Runs the stress test for an hour. This is the minimum required to have confidence that the problem is not demonstrated. Multiple hour runs are better. |
public static void start(){
assertStopped();
CLOCK_STATE.get().exit();
}
| Start the clock, entering non-harness code (mutator or MMTk). |
public ResponseWriter cloneWithWriter(Writer writer){
try {
return new XULResponseWriter(writer,getContentType(),getCharacterEncoding());
}
catch ( FacesException e) {
throw new IllegalStateException();
}
}
| <p>Create a new instance of this <code>ResponseWriter</code> using a different <code>Writer</code>. |
public void printTreeForHumans(final EvolutionState state,final int log){
printTreeForHumans(state,log,Output.V_VERBOSE);
}
| Prints out the tree in a readable Lisp-like fashion. O(n). The default version of this method simply calls child's printRootedTreeForHumans(...) method. |
public static void main(String[] args){
Scanner input=new Scanner(System.in);
System.out.print("Enter the side: ");
double side=input.nextDouble();
System.out.println("The area of the pentagon is " + area(side));
}
| Main Method |
public boolean isCollection(){
return true;
}
| This is used to determine if the label is a collection. If the label represents a collection then any original assignment to the field or method can be written to without the need to create a new collection. This allows obscure collections to be used and also allows initial entries to be maintained. |
private static int blend_lightest(int a,int b){
int f=(b & ALPHA_MASK) >>> 24;
return (low(((a & ALPHA_MASK) >>> 24) + f,0xff) << 24 | high(a & RED_MASK,((b & RED_MASK) >> 8) * f) & RED_MASK | high(a & GREEN_MASK,((b & GREEN_MASK) >> 8) * f) & GREEN_MASK | high(a & BLUE_MASK,((b & BLUE_MASK) * f) >> 8));
}
| only returns the blended lightest colour |
@Override public void write(byte[] source,int offset,int len){
if (len == 0) return;
if (this.ignoreWrites) return;
checkIfWritable();
if (this.doNotCopy && len > MIN_TO_COPY) {
moveBufferToChunks();
addToChunks(source,offset,len);
}
else {
int remainingSpace=this.buffer.capacity() - this.buffer.position();
if (remainingSpace < len) {
this.buffer.put(source,offset,remainingSpace);
offset+=remainingSpace;
len-=remainingSpace;
ensureCapacity(len);
}
this.buffer.put(source,offset,len);
}
}
| override OutputStream's write() |
private boolean isConnected(){
return this.connected;
}
| Method isConnected. |
private void itemsArrayToCombinedBuffer(T[] itemsArray){
final int extra=2;
minValue_=itemsArray[0];
maxValue_=itemsArray[1];
System.arraycopy(itemsArray,extra,combinedBuffer_,0,baseBufferCount_);
long bits=bitPattern_;
if (bits > 0) {
int index=extra + baseBufferCount_;
for (int level=0; bits != 0L; level++, bits>>>=1) {
if ((bits & 1L) > 0L) {
System.arraycopy(itemsArray,index,combinedBuffer_,(2 + level) * k_,k_);
index+=k_;
}
}
}
}
| Loads the Combined Buffer, min and max from the given items array. The Combined Buffer is always in non-compact form and must be pre-allocated. |
public static Configuration newConfiguration(){
return new Configuration();
}
| Creates new configuration with default values. |
public boolean isPreferred(){
return preferred;
}
| Gets the value of the preferred property. |
public static void overScrollBy(final PullToRefreshBase<?> view,final int deltaX,final int scrollX,final int deltaY,final int scrollY,final int scrollRange,final int fuzzyThreshold,final float scaleFactor,final boolean isTouchEvent){
final int deltaValue, currentScrollValue, scrollValue;
switch (view.getPullToRefreshScrollDirection()) {
case HORIZONTAL:
deltaValue=deltaX;
scrollValue=scrollX;
currentScrollValue=view.getScrollX();
break;
case VERTICAL:
default :
deltaValue=deltaY;
scrollValue=scrollY;
currentScrollValue=view.getScrollY();
break;
}
if (view.isPullToRefreshOverScrollEnabled() && !view.isRefreshing()) {
final Mode mode=view.getMode();
if (mode.permitsPullToRefresh() && !isTouchEvent && deltaValue != 0) {
final int newScrollValue=(deltaValue + scrollValue);
if (PullToRefreshBase.DEBUG) {
Log.d(LOG_TAG,"OverScroll. DeltaX: " + deltaX + ", ScrollX: "+ scrollX+ ", DeltaY: "+ deltaY+ ", ScrollY: "+ scrollY+ ", NewY: "+ newScrollValue+ ", ScrollRange: "+ scrollRange+ ", CurrentScroll: "+ currentScrollValue);
}
if (newScrollValue < (0 - fuzzyThreshold)) {
if (mode.showHeaderLoadingLayout()) {
if (currentScrollValue == 0) {
view.setState(State.OVERSCROLLING);
}
view.setHeaderScroll((int)(scaleFactor * (currentScrollValue + newScrollValue)));
}
}
else if (newScrollValue > (scrollRange + fuzzyThreshold)) {
if (mode.showFooterLoadingLayout()) {
if (currentScrollValue == 0) {
view.setState(State.OVERSCROLLING);
}
view.setHeaderScroll((int)(scaleFactor * (currentScrollValue + newScrollValue - scrollRange)));
}
}
else if (Math.abs(newScrollValue) <= fuzzyThreshold || Math.abs(newScrollValue - scrollRange) <= fuzzyThreshold) {
view.setState(State.RESET);
}
}
else if (isTouchEvent && State.OVERSCROLLING == view.getState()) {
view.setState(State.RESET);
}
}
}
| Helper method for Overscrolling that encapsulates all of the necessary function. This is the advanced version of the call. |
public static void w(String tag,String msg,Throwable throwable){
if (sLevel > LEVEL_WARNING) {
return;
}
Log.w(tag,msg,throwable);
}
| Send a WARNING log message |
public SectorGeometryList(SectorGeometryList list){
super(list);
}
| Constructs a sector geometry list that contains a specified list of sector geometries. |
@DSSafe(DSCat.SAFE_LIST) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:56:50.924 -0500",hash_original_method="ABFAE4540EC552EECBD4679559074925",hash_generated_method="EC935FFC09D2ED871BD2D5B3E5767FE7") @Override public String toString(){
return this.getClass().getName() + '(' + getName()+ ':'+ getTypeInternal()+ ')';
}
| Returns a string containing a concise, human-readable description of this field descriptor. |
public static String trim(String string){
if (string == null) {
return null;
}
return string.trim();
}
| Trims the given string. |
public static double approximateBinomialCoefficient(int n,int k){
final int m=max(k,n - k);
long temp=1;
for (int i=n, j=1; i > m; i--, j++) {
temp=temp * i / j;
}
return temp;
}
| Binomial coefficent, also known as "n choose k"). |
public static void read(File input,String toRead,Throwing.Specific.Consumer<InputStream,IOException> reader) throws IOException {
try (ZipFile file=new ZipFile(input);InputStream stream=file.getInputStream(file.getEntry(toRead))){
reader.accept(stream);
}
}
| Reads the given entry from the zip. |
public int height(){
return h;
}
| The height. |
public static void runTests(){
Robin robin=new Robin();
Deep deep=new Deep();
Large large=new Large();
robin.start();
deep.start();
large.start();
sleep(TEST_TIME * 1000);
quit=true;
try {
robin.join();
deep.join();
large.join();
}
catch ( InterruptedException ie) {
System.err.println("join was interrupted");
}
}
| Run the various tests for a set period. |
public javax.crypto.SecretKey engineLookupAndResolveSecretKey(Element element,String baseURI,StorageResolver storage){
return null;
}
| Method engineResolveSecretKey |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:55:42.517 -0500",hash_original_method="C8F2641055D76DBC203D7F98D786CB89",hash_generated_method="6AB1917E5D38181612CA9773841B44C8") public ToParser(String to){
super(to);
}
| Creates new ToParser |
public boolean dynamicNameExtractionActive(){
return null != getNameExtractionExpression();
}
| Indicates whether the name of the business transaction shell be extracted dynamically from the measurement data. |
public URL(String protocol,String host,int port,String file) throws MalformedURLException {
this(protocol,host,port,file,null);
}
| Creates a new URL of the given component parts. The URL uses the protocol's default port. |
@Override public boolean eIsSet(int featureID){
switch (featureID) {
case TypesPackage.TYPE_DEFS__TYPES:
return types != null && !types.isEmpty();
}
return super.eIsSet(featureID);
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public static int countLocksHeldByThread(int id){
int count=0;
for (int i=0; i < numLocks(); i++) {
Lock l=getLock(i);
if (l != null && l.active && l.ownerId == id && l.recursionCount > 0) {
count++;
}
}
return count;
}
| Count number of locks held by thread |
public ComponentBuilder append(String text){
return append(text,FormatRetention.ALL);
}
| Appends the text to the builder and makes it the current target for formatting. The text will have all the formatting from the previous part. |
public RVMMethod resolveInterfaceMethod() throws IncompatibleClassChangeError, NoSuchMethodError {
if (resolvedMember != null) return resolvedMember;
RVMClass declaringClass=(RVMClass)type.resolve();
if (!declaringClass.isResolved()) {
declaringClass.resolve();
}
if (!declaringClass.isInterface() && !isMiranda()) {
throw new IncompatibleClassChangeError();
}
RVMMethod ans=resolveInterfaceMethodInternal(declaringClass);
if (ans == null) {
throw new NoSuchMethodError(this.toString());
}
return ans;
}
| Find the RVMMethod that this member reference refers to using the search order specified in JVM spec 5.4.3.4. |
private void resizeNameColumn(int diff,boolean resizeStatisticPanels){
if (diff != 0) {
if (nameDim == null) {
nameDim=new Dimension(DIMENSION_HEADER_ATTRIBUTE_NAME.width + diff,DIMENSION_HEADER_ATTRIBUTE_NAME.height);
}
else {
int newWidth=nameDim.width + diff;
int minWidth=RESIZE_MARGIN_SHRINK;
int maxWidth=columnHeaderPanel.getWidth() - (DIMENSION_HEADER_MISSINGS.width + DIMENSION_HEADER_TYPE.width + DIMENSION_SEARCH_FIELD.width+ RESIZE_MARGIN_ENLARGE);
if (newWidth > maxWidth) {
newWidth=maxWidth;
}
if (newWidth < minWidth) {
newWidth=minWidth;
}
nameDim=new Dimension(newWidth,nameDim.height);
}
sortingLabelAttName.setMinimumSize(nameDim);
sortingLabelAttName.setPreferredSize(nameDim);
columnHeaderPanel.revalidate();
columnHeaderPanel.repaint();
}
if (resizeStatisticPanels) {
revalidateAttributePanels();
}
}
| Called when resizing event occurs to resize the attribute name column. Resizing is restricted to a mininmum and a maximum amount depending on the actual size of the header panel. |
public void seekEnd(long offset) throws IOException {
flushBuffer();
StreamImpl source=_source;
if (source != null) source.seekEnd(offset);
_position=offset;
}
| Seeks based on the end |
public void testHashcode(){
LogFormat f1=new LogFormat(10.0,"10",true);
LogFormat f2=new LogFormat(10.0,"10",true);
assertTrue(f1.equals(f2));
int h1=f1.hashCode();
int h2=f2.hashCode();
assertEquals(h1,h2);
}
| Two objects that are equal are required to return the same hashCode. |
public void replace(String statement) throws CannotCompileException {
thisClass.getClassFile();
final int bytecodeSize=3;
int pos=newPos;
int newIndex=iterator.u16bitAt(pos + 1);
int codeSize=canReplace();
int end=pos + codeSize;
for (int i=pos; i < end; ++i) iterator.writeByte(NOP,i);
ConstPool constPool=getConstPool();
pos=currentPos;
int methodIndex=iterator.u16bitAt(pos + 1);
String signature=constPool.getMethodrefType(methodIndex);
Javac jc=new Javac(thisClass);
ClassPool cp=thisClass.getClassPool();
CodeAttribute ca=iterator.get();
try {
CtClass[] params=Descriptor.getParameterTypes(signature,cp);
CtClass newType=cp.get(newTypeName);
int paramVar=ca.getMaxLocals();
jc.recordParams(newTypeName,params,true,paramVar,withinStatic());
int retVar=jc.recordReturnType(newType,true);
jc.recordProceed(new ProceedForNew(newType,newIndex,methodIndex));
checkResultValue(newType,statement);
Bytecode bytecode=jc.getBytecode();
storeStack(params,true,paramVar,bytecode);
jc.recordLocalVariables(ca,pos);
bytecode.addConstZero(newType);
bytecode.addStore(retVar,newType);
jc.compileStmnt(statement);
if (codeSize > 3) bytecode.addAload(retVar);
replace0(pos,bytecode,bytecodeSize);
}
catch ( CompileError e) {
throw new CannotCompileException(e);
}
catch ( NotFoundException e) {
throw new CannotCompileException(e);
}
catch ( BadBytecode e) {
throw new CannotCompileException("broken method");
}
}
| Replaces the <tt>new</tt> expression with the bytecode derived from the given source text. <p>$0 is available but the value is null. |
@Override public boolean eIsSet(int featureID){
switch (featureID) {
case DatatypePackage.ENUM_LITERAL__NAME:
return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name);
case DatatypePackage.ENUM_LITERAL__DESCRIPTION:
return DESCRIPTION_EDEFAULT == null ? description != null : !DESCRIPTION_EDEFAULT.equals(description);
}
return super.eIsSet(featureID);
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
private static int signedKeyChange(String uname,String server){
ClientUser user=users.get(uname);
if (user.isAllowsUnsignedChanges()) {
System.out.println("user " + uname + " allows unsigned key changes");
}
String newKeyData=user.getKeyData() + changeCtr;
DSAPrivateKey prKey=user.loadChangePrivKey();
if (prKey == null) {
System.out.println("no private key for " + uname);
return ConsistencyErr.KEYSTORE_ERR;
}
KeyPair newCk=null;
try {
newCk=Keys.generateDSAKeyPair();
}
catch ( NoSuchAlgorithmException e) {
Logging.error("[TestClient] " + e.getMessage());
user.unloadChangePrivKey();
return ClientUtils.INTERNAL_CLIENT_ERR;
}
byte[] sig=null;
try {
ULNChangeReq changeReq=ClientMessaging.buildULNChangeReqMsgProto(user.getUsername(),newKeyData,(DSAPublicKey)newCk.getPublic(),user.isAllowsUnsignedChanges(),user.isAllowsPublicVisibility());
sig=Signing.dsaSign(prKey,changeReq.toByteArray());
}
catch ( NoSuchAlgorithmException e) {
Logging.error("[TestClient] " + e.getMessage());
user.unloadChangePrivKey();
return ClientUtils.INTERNAL_CLIENT_ERR;
}
user.unloadChangePrivKey();
if (sig == null) {
Logging.error("Couldn't get a signature for the new key data");
return ClientUtils.INTERNAL_CLIENT_ERR;
}
user.setKeyData(newKeyData);
user.saveChangeKeyPair(newCk);
ClientMessaging.sendSignedULNChangeReqProto(user,sig,server);
newCk=null;
AbstractMessage serverMsg=ClientMessaging.receiveRegistrationRespProto();
if (serverMsg == null) {
return ServerErr.MALFORMED_SERVER_MSG_ERR;
}
else if (serverMsg instanceof ServerResp) {
return getServerErr((ServerResp)serverMsg);
}
else {
changeCtr++;
return ConsistencyErr.CHECK_PASSED;
}
}
| Performs a key change by generating a new key pair for the user and signing and sending the new key. |
public void test_write$BII_7() throws IOException, NoSuchAlgorithmException {
Support_OutputStream sos=new Support_OutputStream(MY_MESSAGE_LEN);
MessageDigest md=MessageDigest.getInstance(algorithmName[0]);
DigestOutputStream dos=new DigestOutputStream(sos,md);
dos.write(myMessage,0,MY_MESSAGE_LEN);
try {
dos.write(myMessage,0,MY_MESSAGE_LEN);
fail("Test 1: IOException expected.");
}
catch ( IOException e) {
}
}
| java.io.DigestOutputStream#write(byte[], int, int) |
public static Scenario loadScenario(final String configFile){
return loadScenario(loadConfig(configFile));
}
| binds to createScenario(createConfig(configFile)); |
private boolean matchStrings(String pattern,String str,Map<String,String> uriTemplateVariables){
AntPathStringMatcher matcher=new AntPathStringMatcher(pattern,str,uriTemplateVariables);
return matcher.matchStrings();
}
| Tests whether or not a string matches against a pattern. The pattern may contain two special characters:<br> '*' means zero or more characters<br> '?' means one and only one character |
public TreePopupListener(JPopupMenu popupMenu,JTree tree){
this.popup=popupMenu;
this.tree=tree;
}
| Instantiates a new popup listener. |
public ParameterTypeFile(String key,String description,String extension,boolean optional){
super(key,description,null);
setOptional(optional);
this.extensions=new String[]{extension};
}
| Creates a new parameter type for files with the given extension. If the extension is null no file filters will be used. If the parameter is not optional, it is set to be not expert. |
public ObjectReference loadObjectReference(Offset offset){
if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED);
return null;
}
| Loads a reference from the memory location pointed to by the current instance. |
public Builder rootView(ViewGroup rootView){
this.rootView=rootView;
return this;
}
| Pass the rootView of the Drawer which will be used to inflate the DrawerLayout in |
public Object extractMin(){
int numElem=this.numElem;
Object[] objects=this.objects;
Comparable[] keys=this.keys;
if (numElem == 0) return null;
keys[1 - 1]=keys[numElem - 1];
keys[numElem - 1]=null;
Object result=objects[1 - 1];
objects[1 - 1]=objects[numElem - 1];
objects[numElem - 1]=null;
numElem--;
if (numElem > 1) heapify(1,numElem);
this.numElem=numElem;
return result;
}
| Removes the first minimum element and its key from the heap, and returns the minimum element. Will return null if the heap is empty |
public static Set<Configuration> scanClusters(String netIf,String serviceName,String scenario){
log.info("Scanning over network {} for available configuration",netIf);
Set<Configuration> availableClusters=new HashSet<Configuration>();
try {
MulticastUtil multicastUtil=MulticastUtil.create(netIf);
Map<String,Map<String,String>> clusters=multicastUtil.list(serviceName);
for ( Map<String,String> cluster : clusters.values()) {
if (cluster != null && !cluster.isEmpty() && cluster.get(PropertyConstants.CONFIG_KEY_SCENARIO).equals(scenario)) {
Configuration config=new Configuration();
config.setConfigMap(cluster);
availableClusters.add(config);
log.info("Scan found cluster: {}/{}",config.getNetworkVip(),config.toString());
}
}
multicastUtil.close();
}
catch ( IOException e) {
log.error("Scan available cluster Configuration failed with exception: %s",e.getMessage());
}
log.info("Scan found {} cluster(s) for '{}'",availableClusters.size(),scenario);
return availableClusters;
}
| List cluster configurations scanned over network. |
ByteVector put11(final int b1,final int b2){
int length=this.length;
if (length + 2 > data.length) {
enlarge(2);
}
byte[] data=this.data;
data[length++]=(byte)b1;
data[length++]=(byte)b2;
this.length=length;
return this;
}
| Puts two bytes into this byte vector. The byte vector is automatically enlarged if necessary. |
public RedisQueue(final ConnectionManager connectionManager,final String name){
super(new RedisQueueCodec(),new CommandSyncService(connectionManager),null == name || name.trim().isEmpty() ? DEFAULT_NAME : name);
this.connectionManager=connectionManager;
}
| Instantiate a new Redis-backed queue using the provided connection manager and name. |
public static void deleteKey(String keyId,boolean deleteFromToken) throws Exception {
LOG.trace("Deleting key '{}', from token = ",keyId,deleteFromToken);
execute(new DeleteKey(keyId,deleteFromToken));
}
| Delete the key with the given ID from the signer database. Optionally, deletes it from the token as well. |
protected void clean_cache(){
for (int i=0; i < cache_size; i++) {
elements[i]=null;
}
;
elements=null;
last_used=null;
index=null;
}
| cleans the cache |
public JavaType uncheckedSimpleType(Class<?> cls){
return new SimpleType(cls);
}
| Method that will force construction of a simple type, without trying to check for more specialized types. <p> NOTE: no type modifiers are called on type either, so calling this method should only be used if caller really knows what it's doing... |
public long clearMetaKeyState(long state,int which){
if ((which & META_SHIFT_ON) != 0 && (state & META_CAP_LOCKED) != 0) {
state&=~META_SHIFT_MASK;
}
if ((which & META_ALT_ON) != 0 && (state & META_ALT_LOCKED) != 0) {
state&=~META_ALT_MASK;
}
if ((which & META_SYM_ON) != 0 && (state & META_SYM_LOCKED) != 0) {
state&=~META_SYM_MASK;
}
return state;
}
| Clears the state of the specified meta key if it is locked. |
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 SendPacket send(SendPacket packet){
SendDispatcher dispatcher=mSendDispatcher;
if (dispatcher == null) throw new NullPointerException("Connector's SendDispatcher is null.");
packet.setDispatcher(dispatcher);
dispatcher.send(packet);
return packet;
}
| Send a packet to send queue |
protected static void removeConnection(final ConnectionInfo conInfo){
getAllConnections().remove(conInfo);
}
| remove a connection from the list of all current connections |
@SuppressWarnings("unchecked") public ListIterator<AbstractInsnNode> iterator(int index){
return new InsnListIterator(index);
}
| Returns an iterator over the instructions in this list. |
public SitemapsMobileEntry(BaseEntry<?> sourceEntry){
super(sourceEntry);
getCategories().add(CATEGORY);
}
| Constructs a new entry by doing a copy from another BaseEntry instance. |
public static Result cvModel(MultiLabelClassifier h,Instances D,int numFolds,String top) throws Exception {
return cvModel(h,D,numFolds,top,"1");
}
| CVModel - Split D into train/test folds, and then train and evaluate on each one. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.