code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
public int hashCode(){
int hash=this.getClass().hashCode();
for (int x=0; x < rules.length; x++) if (rules[x] != null) hash+=rules[x].hashCode();
return hash;
}
| The hash code for the rule set. This isn't a very good hash code, but it has the benefit of not being O(n lg n) -- otherwise, we'd have to do something like sort the rules in the individual first and then do an ordered hash code of some sort, ick. |
@Nonnull public BugInstance addField(FieldDescriptor fieldDescriptor){
FieldAnnotation fieldAnnotation=FieldAnnotation.fromFieldDescriptor(fieldDescriptor);
add(fieldAnnotation);
return this;
}
| Add a field annotation for a FieldDescriptor. |
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 ASN1ValueCollection(int tagNumber,ASN1Type type){
super(tagNumber);
this.type=type;
}
| Constructs ASN1 collection type. |
public AddWorldParameterDialog(java.awt.Frame parent,boolean modal,Diagram diagram,Point clickPosition){
super(parent,modal);
initComponents();
DefaultComboBoxModel model=new DefaultComboBoxModel();
for ( UniformBinding binding : UniformBinding.values()) {
model.addElement(binding);
}
this.diagram=diagram;
this.clickPosition=clickPosition;
nameField.setModel(model);
}
| Creates new form AddMaterialParameter |
public TcpClient(){
this(SocketCreatorFactory.getSocketCreatorForComponent(SecurableCommunicationChannel.LOCATOR));
}
| Constructs a new TcpClient using the default (Locator) SocketCreator. SocketCreatorFactory should be initialized before invoking this method. |
public static boolean isInstallableEditing(EnumSet<EmbeddingFlags> flagSet){
return flagSet.isEmpty();
}
| Takes an EnumSet\<EmbeddingFlags\> representation of the fsType and returns whether or not the fsType is Installable Embedding. The fsType is Installable Editing iff none of the fsType bits are set. |
public void writeBody(OutputStream os,MimeBodyPart msg) throws IOException {
if (msg instanceof MimeMultipart) {
String ct=msg.getContentType().getValue();
if (ct.startsWith("application/vnd.wap.multipart.")) {
}
else {
writeMultipart(os,(MimeMultipart)msg);
}
}
else {
os.write(msg.getBody());
os.write("\r\n".getBytes());
}
}
| Writes the body of the message to the given stream. |
public void clear(){
final ReentrantLock lock=this.lock;
lock.lock();
try {
setArray(new Object[0]);
}
finally {
lock.unlock();
}
}
| Removes all of the elements from this list. The list will be empty after this call returns. |
public RequestLine parseSIPRequestLine(String requestLine) throws ParseException {
requestLine+="\n";
return new RequestLineParser(requestLine).parse();
}
| Parse the SIP Request Line |
public FilteringBatchMessageListenerAdapter(BatchMessageListener<K,V> delegate,RecordFilterStrategy<K,V> recordFilterStrategy){
super(delegate,recordFilterStrategy);
}
| Create an instance with the supplied strategy and delegate listener. |
public static String processLineBreaksHTML(String text){
if (text == null) {
String msg=Logging.getMessage("nullValue.StringIsNull");
Logging.logger().severe(msg);
throw new IllegalArgumentException(msg);
}
text=text.replaceAll("\n","");
text=text.replaceAll("(?i)<br\\s?.*?>","\n");
text=text.replaceAll("(?i)<p\\s?.*?>","");
text=text.replaceAll("(?i)</p>","\n\n");
return text;
}
| Remove new line characters then replace BR and P tags with appropriate new lines. |
public long allocateSlot(){
return toLong(bucketNum,lastSlot++);
}
| Returns a new slot in the bucket. |
@Override public boolean tileExists(String id){
return (tileExists(id,depthTree));
}
| Determine if a tile exists. |
@SuppressWarnings({"unchecked","rawtypes"}) static <E extends Comparable<E>>AutoSortedCollection<E> createAutoSortedCollection(int initial){
return new AutoListSortedCollection<>(new ObjectArrayList<>(initial),null);
}
| Construct new auto sorted collection using natural order. |
public void startPrefixMapping(String prefix,String uri) throws org.xml.sax.SAXException {
m_prefixMappings.addElement(prefix);
m_prefixMappings.addElement(uri);
}
| Receive notification of the start of a Namespace mapping. <p>By default, do nothing. Application writers may override this method in a subclass to take specific actions at the start of each element (such as allocating a new tree node or writing output to a file).</p> |
private void _serializeArray(Array array,StringBuilder sb,Set<Object> done) throws ConverterException {
_serializeList(array.toList(),sb,done);
}
| serialize a Array |
private EntityPropertyDiff generateClassDiffFor(Object diffObject,@Nullable Object firstValue,@Nullable Object secondValue,ViewProperty viewProperty,MetaProperty metaProperty,Stack<Object> diffBranch){
boolean isLinkChange=!ObjectUtils.equals(firstValue,secondValue);
isLinkChange=!(diffObject instanceof EmbeddableEntity) && isLinkChange;
EntityClassPropertyDiff classPropertyDiff=new EntityClassPropertyDiff(firstValue,secondValue,viewProperty,metaProperty,isLinkChange);
boolean isInternalChange=false;
diffBranch.push(diffObject);
List<EntityPropertyDiff> propertyDiffs=getPropertyDiffs(viewProperty.getView(),(Entity)firstValue,(Entity)secondValue,diffBranch);
diffBranch.pop();
if (!propertyDiffs.isEmpty()) {
isInternalChange=true;
classPropertyDiff.setPropertyDiffs(propertyDiffs);
}
if (isInternalChange || isLinkChange) return classPropertyDiff;
else return null;
}
| Generate class difference for selected not null object |
VPlexVirtualVolumeInfo findVirtualVolume(String volumeName,boolean fetchAtts) throws VPlexApiException {
if (volumeName == null) {
throw VPlexApiException.exceptions.cantFindRequestedVolumeNull();
}
VPlexVirtualVolumeInfo virtualVolumeInfo=null;
List<VPlexClusterInfo> clusterInfoList=getClusterInfoLite();
for ( VPlexClusterInfo clusterInfo : clusterInfoList) {
virtualVolumeInfo=findVirtualVolume(clusterInfo.getName(),volumeName,fetchAtts);
if (virtualVolumeInfo != null) {
break;
}
}
if (virtualVolumeInfo == null) {
throw VPlexApiException.exceptions.cantFindRequestedVolume(volumeName);
}
return virtualVolumeInfo;
}
| Find the virtual volume containing the passed name. |
public DefaultListModel(T... items){
this.items=createList(items);
}
| Creates a new instance of DefaultListModel |
public void testConstrBIScale(){
String a="1231212478987482988429808779810457634781384756794987";
BigInteger bA=new BigInteger(a);
int aScale=10;
BigDecimal aNumber=new BigDecimal(bA,aScale);
assertEquals("incorrect value",bA,aNumber.unscaledValue());
assertEquals("incorrect scale",aScale,aNumber.scale());
}
| new BigDecimal(BigInteger value, int scale) |
public static TypeReference newExceptionReference(int exceptionIndex){
return new TypeReference((THROWS << 24) | (exceptionIndex << 8));
}
| Returns a reference to the type of an exception, in a 'throws' clause of a method. |
public int read(byte[] b,int off,int len) throws IOException {
if (b == null) {
throw new NullPointerException();
}
if ((off < 0) || (len < 0) || (off + len > b.length)) {
throw new IndexOutOfBoundsException();
}
if (len == 0) {
return 0;
}
long pos=readUntil(pointer + len);
if (pos <= pointer) {
return -1;
}
byte[] buf=(byte[])data.get((int)(pointer >> SECTOR_SHIFT));
int nbytes=Math.min(len,SECTOR_SIZE - (int)(pointer & SECTOR_MASK));
System.arraycopy(buf,(int)(pointer & SECTOR_MASK),b,off,nbytes);
pointer+=nbytes;
return nbytes;
}
| Reads up to <code>len</code> bytes of data from the input stream into an array of bytes. An attempt is made to read as many as <code>len</code> bytes, but a smaller number may be read, possibly zero. The number of bytes actually read is returned as an integer. <p> This method blocks until input data is available, end of file is detected, or an exception is thrown. <p> If <code>b</code> is <code>null</code>, a <code>NullPointerException</code> is thrown. <p> If <code>off</code> is negative, or <code>len</code> is negative, or <code>off+len</code> is greater than the length of the array <code>b</code>, then an <code>IndexOutOfBoundsException</code> is thrown. <p> If <code>len</code> is zero, then no bytes are read and <code>0</code> is returned; otherwise, there is an attempt to read at least one byte. If no byte is available because the stream is at end of file, the value <code>-1</code> is returned; otherwise, at least one byte is read and stored into <code>b</code>. <p> The first byte read is stored into element <code>b[off]</code>, the next one into <code>b[off+1]</code>, and so on. The number of bytes read is, at most, equal to <code>len</code>. Let <i>k</i> be the number of bytes actually read; these bytes will be stored in elements <code>b[off]</code> through <code>b[off+</code><i>k</i><code>-1]</code>, leaving elements <code>b[off+</code><i>k</i><code>]</code> through <code>b[off+len-1]</code> unaffected. <p> In every case, elements <code>b[0]</code> through <code>b[off]</code> and elements <code>b[off+len]</code> through <code>b[b.length-1]</code> are unaffected. <p> If the first byte cannot be read for any reason other than end of file, then an <code>IOException</code> is thrown. In particular, an <code>IOException</code> is thrown if the input stream has been closed. |
public void removeKnot(int n){
if (numKnots <= 4) return;
if (n < numKnots - 1) {
System.arraycopy(xKnots,n + 1,xKnots,n,numKnots - n - 1);
System.arraycopy(yKnots,n + 1,yKnots,n,numKnots - n - 1);
System.arraycopy(knotTypes,n + 1,knotTypes,n,numKnots - n - 1);
}
numKnots--;
if (xKnots[1] > 0) xKnots[1]=0;
rebuildGradient();
}
| Remove a knot. |
@Override public boolean isActive(){
return amIActive;
}
| Used by the Whitebox GUI to tell if this plugin is still running. |
@Override protected void wrapUp() throws Exception {
m_b=-(m_bLow + m_bUp) / 2.0;
m_target=null;
m_error=null;
super.wrapUp();
}
| wrap up various variables to save memeory and do some housekeeping after optimization has finished. |
protected double switchedLog10(double val){
return this.smallLogFlag ? Math.log(val) / LOG10_VALUE : adjustedLog10(val);
}
| Returns the log10 value, depending on if values between 0 and 1 are being plotted. If negative values are not allowed and the lower bound is between 0 and 10 then a normal log is returned; otherwise the returned value is adjusted if the given value is less than 10. |
@Override public boolean performOperation(int generation){
return true;
}
| The default implementation returns true for every generation. |
private void populateXtremIOAccessProfile(AccessProfile accessProfile,StorageProvider providerInfo){
accessProfile.setSystemId(providerInfo.getId());
accessProfile.setSystemClazz(providerInfo.getClass());
accessProfile.setIpAddress(providerInfo.getIPAddress());
accessProfile.setUserName(providerInfo.getUserName());
accessProfile.setPassword(providerInfo.getPassword());
accessProfile.setSystemType(DiscoveredDataObject.Type.xtremio.name());
accessProfile.setPortNumber(providerInfo.getPortNumber());
accessProfile.setSslEnable(String.valueOf(providerInfo.getUseSSL()));
}
| inject details needed for Scanning |
@Override public byte[] serialize(){
byte[] payloadData=null;
if (payload != null) {
payload.setParent(this);
payloadData=payload.serialize();
}
int optionsLength=0;
if (this.options != null) optionsLength=this.options.length / 4;
this.headerLength=(byte)(5 + optionsLength);
this.totalLength=(short)(this.headerLength * 4 + ((payloadData == null) ? 0 : payloadData.length));
byte[] data=new byte[this.totalLength];
ByteBuffer bb=ByteBuffer.wrap(data);
bb.put((byte)(((this.version & 0xf) << 4) | (this.headerLength & 0xf)));
bb.put(this.diffServ);
bb.putShort(this.totalLength);
bb.putShort(this.identification);
bb.putShort((short)(((this.flags & IPV4_FLAGS_MASK) << IPV4_FLAGS_SHIFT) | (this.fragmentOffset & IPV4_OFFSET_MASK)));
bb.put(this.ttl);
bb.put((byte)this.protocol.getIpProtocolNumber());
bb.putShort(this.checksum);
bb.putInt(this.sourceAddress.getInt());
bb.putInt(this.destinationAddress.getInt());
if (this.options != null) bb.put(this.options);
if (payloadData != null) bb.put(payloadData);
if (this.checksum == 0) {
bb.rewind();
int accumulation=0;
for (int i=0; i < this.headerLength * 2; ++i) {
accumulation+=0xffff & bb.getShort();
}
accumulation=((accumulation >> 16) & 0xffff) + (accumulation & 0xffff);
this.checksum=(short)(~accumulation & 0xffff);
bb.putShort(10,this.checksum);
}
return data;
}
| Serializes the packet. Will compute and set the following fields if they are set to specific values at the time serialize is called: -checksum : 0 -headerLength : 0 -totalLength : 0 |
public boolean unlockIt(){
log.info(toString());
setProcessing(false);
return true;
}
| Unlock Document. |
protected PreOrPostCondition_Impl(){
super();
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public void paintCheckBoxMenuItemBackground(SynthContext context,Graphics g,int x,int y,int w,int h){
paintBackground(context,g,x,y,w,h,null);
}
| Paints the background of a check box menu item. |
public static int[] toIntArray(float[] array){
int[] result=new int[array.length];
for (int i=0; i < array.length; i++) {
result[i]=(int)array[i];
}
return result;
}
| Coverts given floats array to array of ints. |
public void add(File file,String pathForEntry,String password) throws IOException, UnsupportedEncodingException {
FileInputStream fis=new FileInputStream(file);
try {
add(pathForEntry,fis,password);
}
finally {
fis.close();
}
}
| Add un-encrypted + un-zipped file to encrypted zip file.<br> |
public void deleteConsistencyGroup(String cgName) throws VPlexApiException {
s_logger.info("Request to delete consistency group on VPlex at {}",_baseURI);
_cgMgr.deleteConsistencyGroup(cgName);
}
| Deletes the consistency group with the passed name. |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:29:04.392 -0500",hash_original_method="56717C4466E220164D65DBB18C5ECF92",hash_generated_method="2E212131A24D5A272E84C349FE7D0F17") public void transferTo(InputChannel outParameter){
if (outParameter == null) {
throw new IllegalArgumentException("outParameter must not be null");
}
nativeTransferTo(outParameter);
}
| Transfers ownership of the internal state of the input channel to another instance and invalidates this instance. This is used to pass an input channel as an out parameter in a binder call. |
public UnchangeableAllowingOnBehalfActingException(String message){
super(message);
}
| Constructs a new exception with the specified detail message. The cause is not initialized. |
public void remove(CFrame window){
if (windows.remove(window)) {
window.removeComponentListener(eventListener);
window.removeWindowListener(eventListener);
}
}
| Remove window |
protected final void destroyDefaultSetup(){
if (this.shell != null) {
executeCommand(shell,"exit");
this.shell.terminate();
this.shell=null;
}
disconnectAllFromDS();
Host.getHost(0).getVM(0).invoke("verify service stopped",null);
}
| Destroy all of the components created for the default setup. |
boolean computeSuperClasses(){
Set<OwlClass> ancestors=new HashSet<OwlClass>();
Set<OwlClass> frontier=new HashSet<OwlClass>(superClasses);
while (!frontier.isEmpty()) {
Set<OwlClass> next=new HashSet<OwlClass>();
for ( OwlClass ancestor : frontier) {
ancestors.add(ancestor);
next.addAll(ancestor.superClasses);
}
next.removeAll(ancestors);
frontier=next;
}
boolean newInfo=!ancestors.equals(superClasses);
superClasses=ancestors;
return newInfo;
}
| Apply RL rule scm-sco: subClassOf transitivity. Follows subClassOf chains to compute all the ancestor classes. Assumes the hierarchy is small enough that a simple BFS is fine. |
public void loadFile(String filename,AbstractFileLoader... loaders){
ArffPanel panel;
panel=new ArffPanel(filename,loaders);
panel.addChangeListener(this);
tabbedPane.addTab(panel.getTitle(),panel);
tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1);
}
| loads the specified file |
public void createVertexAndNormalBuffersOnly(){
mVertices.compact().position(0);
mNormals.compact().position(0);
createBuffer(mVertexBufferInfo,BufferType.FLOAT_BUFFER,mVertices,GLES20.GL_ARRAY_BUFFER);
createBuffer(mNormalBufferInfo,BufferType.FLOAT_BUFFER,mNormals,GLES20.GL_ARRAY_BUFFER);
GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER,0);
GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER,0);
}
| Creates the vertex and normal buffers only. This is typically used for a VertexAnimationObject3D's frames. |
public int size(){
return count;
}
| Returns the current size of the buffer. |
public int waitFor() throws InterruptedException {
if (vm == null) throw new IllegalStateException("can't wait for JavaVM that hasn't started");
int status=vm.waitFor();
outPipe.join();
errPipe.join();
return status;
}
| Waits for the subprocess to exit, joins the pipe threads to ensure that all output is collected, and returns its exit status. |
public PriorityQueue(Collection<? extends E> c){
if (c instanceof PriorityQueue) {
getFromPriorityQueue((PriorityQueue<? extends E>)c);
}
else if (c instanceof SortedSet) {
getFromSortedSet((SortedSet<? extends E>)c);
}
else {
initSize(c);
addAll(c);
}
}
| Constructs a priority queue that contains the elements of a collection. The constructed priority queue has the initial capacity of 110% of the size of the collection. The queue uses natural ordering to order its elements. |
public void endElement(StylesheetHandler handler,String uri,String localName,String rawName) throws org.xml.sax.SAXException {
ProcessorCharacters charProcessor=(ProcessorCharacters)handler.getProcessorFor(null,"text()","text");
charProcessor.setXslTextElement(null);
}
| Receive notification of the end of an element. |
public GCTimeCap(){
super(Options.set,"GC Time Cap","Try to limit reference counting collections to this time cap",1000000);
}
| Create the option. |
private CGraphFunctions(){
}
| You are not supposed to instantiate this class. |
public static void addPackage(String packagename){
packages.add(packagename);
}
| Adds the given package name to the list of known package names. |
public Builder cancelAndEdit(){
JobManager.instance().cancel(getJobId());
Builder builder=new Builder(this,false);
mTransient=false;
if (!isPeriodic()) {
long offset=System.currentTimeMillis() - mScheduledAt;
long minValue=1L;
builder.setExecutionWindow(Math.max(minValue,getStartMs() - offset),Math.max(minValue,getEndMs() - offset));
}
return builder;
}
| Cancel this request if it has been scheduled. Note that if the job isn't periodic, then the time passed since the job has been scheduled is subtracted from the time frame. For example a job should run between 4 and 6 seconds from now. You cancel the scheduled job after 2 seconds, then the job will run between 2 and 4 seconds after it's been scheduled again. |
@Xpect @ParameterParser(syntax="('at' arg1=OFFSET)?") public void scopeWithResource(@N4JSCommaSeparatedValuesExpectation IN4JSCommaSeparatedValuesExpectation expectation,ICrossEReferenceAndEObject arg1){
EObject eobj=arg1.getEObject();
IScope scope=scopeProvider.getScope(eobj,arg1.getCrossEReference());
for ( IEObjectDescription eo : scope.getAllElements()) {
eo.getEObjectURI();
}
URI uri=eobj == null ? null : eobj.eResource() == null ? null : eobj.eResource().getURI();
expectation.assertEquals(new ScopeAwareIterable(uri,false,scope),new IsInScopeWithOptionalPositionPredicate(converter,uri,false,scope));
}
| Compares scope including resource name but not line number. |
public List<JCAnnotation> translateAnnotations(List<JCAnnotation> trees){
for (List<JCAnnotation> l=trees; l.nonEmpty(); l=l.tail) l.head=translate(l.head);
return trees;
}
| Visitor method: translate a list of catch clauses in try statements. |
public void dumpToConsole(){
this.log.info("Dumping arrival delay histogram...");
System.out.println("delay; count");
for (int i=0; i < this.arrivalDelay.length; i++) {
System.out.println(i + "; " + this.arrivalDelay[i]);
}
this.log.info("Dumping departure delay histogram...");
System.out.println("delay; count");
for (int i=0; i < this.departureDelay.length; i++) {
System.out.println(i + "; " + this.departureDelay[i]);
}
}
| Write the resulting histogram to the console. |
@RequestMapping(value="/{cubeName}/build",method={RequestMethod.PUT}) @ResponseBody public JobInstance build(@PathVariable String cubeName,@RequestBody JobBuildRequest req){
return rebuild(cubeName,req);
}
| Build/Rebuild a cube segment |
public FileElement(String fileName){
this.filePath=fileName;
}
| Creates a new SourceElement. |
public static int uninstallSilent(Context context,String packageName,boolean isKeepData){
if (packageName == null || packageName.length() == 0) {
return DELETE_FAILED_INVALID_PACKAGE;
}
StringBuilder command=new StringBuilder().append("LD_LIBRARY_PATH=/vendor/lib:/system/lib pm uninstall").append(isKeepData ? " -k " : " ").append(packageName.replace(" ","\\ "));
CommandResult commandResult=ShellUtils.execCommand(command.toString(),!isSystemApplication(context),true);
if (commandResult.successMsg != null && (commandResult.successMsg.contains("Success") || commandResult.successMsg.contains("success"))) {
return DELETE_SUCCEEDED;
}
Log.e(TAG,new StringBuilder().append("uninstallSilent successMsg:").append(commandResult.successMsg).append(", ErrorMsg:").append(commandResult.errorMsg).toString());
if (commandResult.errorMsg == null) {
return DELETE_FAILED_INTERNAL_ERROR;
}
if (commandResult.errorMsg.contains("Permission denied")) {
return DELETE_FAILED_PERMISSION_DENIED;
}
return DELETE_FAILED_INTERNAL_ERROR;
}
| uninstall package silent by root <ul> <strong>Attentions:</strong> <li>Don't call this on the ui thread, it may costs some times.</li> <li>You should add <strong>android.permission.DELETE_PACKAGES</strong> in manifest, so no need to request root permission, if you are system app.</li> </ul> |
@SuppressFBWarnings(value="NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE",justification="no npe in getters") public CreateContainerCmd fillContainerConfig(CreateContainerCmd containerConfig){
if (StringUtils.isNotBlank(hostname)) {
containerConfig.withHostName(hostname);
}
String[] cmd=getDockerCommandArray();
if (cmd.length > 0) {
containerConfig.withCmd(cmd);
}
containerConfig.withPortBindings(Iterables.toArray(getPortMappings(),PortBinding.class));
if (BooleanUtils.isTrue(getBindAllPorts())) {
containerConfig.withPublishAllPorts(getBindAllPorts());
}
if (BooleanUtils.isTrue(getPrivileged())) {
containerConfig.withPrivileged(getPrivileged());
}
if (getCpuShares() != null && getCpuShares() > 0) {
containerConfig.withCpuShares(getCpuShares());
}
if (getMemoryLimit() != null && getMemoryLimit() > 0) {
Long memoryInByte=getMemoryLimit() * 1024 * 1024;
containerConfig.withMemory(memoryInByte);
}
if (CollectionUtils.isNotEmpty(getDnsHosts())) {
containerConfig.withDns(getDnsHosts().toArray(new String[getDnsHosts().size()]));
}
if (CollectionUtils.isNotEmpty(getVolumes())) {
ArrayList<Volume> vols=new ArrayList<>();
ArrayList<Bind> binds=new ArrayList<>();
for ( String vol : getVolumes()) {
final String[] group=vol.split(":");
if (group.length > 1) {
if (group[1].equals("/")) {
throw new IllegalArgumentException("Invalid bind mount: destination can't be '/'");
}
binds.add(Bind.parse(vol));
}
else if (vol.equals("/")) {
throw new IllegalArgumentException("Invalid volume: path can't be '/'");
}
else {
vols.add(new Volume(vol));
}
}
containerConfig.withVolumes(vols.toArray(new Volume[vols.size()]));
containerConfig.withBinds(binds.toArray(new Bind[binds.size()]));
}
if (CollectionUtils.isNotEmpty(getVolumesFrom())) {
ArrayList<VolumesFrom> volFrom=new ArrayList<>();
for ( String volFromStr : getVolumesFrom()) {
volFrom.add(new VolumesFrom(volFromStr));
}
containerConfig.withVolumesFrom(volFrom.toArray(new VolumesFrom[volFrom.size()]));
}
if (BooleanUtils.isTrue(getTty())) {
containerConfig.withTty(getTty());
}
if (CollectionUtils.isNotEmpty(getEnvironment())) {
containerConfig.withEnv(getEnvironment().toArray(new String[getEnvironment().size()]));
}
if (StringUtils.isNotBlank(getMacAddress())) {
containerConfig.withMacAddress(getMacAddress());
}
if (CollectionUtils.isNotEmpty(getExtraHosts())) {
containerConfig.withExtraHosts(getExtraHosts().toArray(new String[getExtraHosts().size()]));
}
if (StringUtils.isNotBlank(getNetworkMode())) {
containerConfig.withNetworkMode(getNetworkMode());
}
if (!getDevices().isEmpty()) {
containerConfig.withDevices(getDevices().stream().map(null).collect(Collectors.toList()));
}
if (StringUtils.isNotBlank(getCpusetCpus())) {
containerConfig.withCpusetCpus(getCpusetCpus());
}
if (StringUtils.isNotBlank(getCpusetMems())) {
containerConfig.withCpusetMems(getCpusetMems());
}
if (!getLinks().isEmpty()) {
containerConfig.withLinks(getLinks().stream().map(null).collect(Collectors.toList()));
}
return containerConfig;
}
| Fills user specified values |
private static long[] computeParameters(final LongIterator iterator){
long v=-1, prev=-1, c=0;
while (iterator.hasNext()) {
v=iterator.nextLong();
if (prev > v) throw new IllegalArgumentException("The list of values is not monotone: " + prev + " > "+ v);
prev=v;
c++;
}
return new long[]{c,v};
}
| Computes the number of elements and the last element returned by the given iterator. |
private void markFinalFieldsAsLiterals(){
for ( RVMField f : getStaticFields()) {
if (f.isFinal()) {
Offset fieldOffset=f.getOffset();
if (Statics.isReference(Statics.offsetAsSlot(fieldOffset))) {
Statics.markAsReferenceLiteral(fieldOffset);
}
else {
Statics.markAsNumericLiteral(f.getSize(),fieldOffset);
}
}
}
}
| Mark final fields as being available as literals |
public CategoryInfo(String id,String name,BufferedImage image,String texttip,Boolean catshowname,String colour,Integer catorder){
m_sID=id;
m_sName=name;
m_Image=image;
m_sTextTip=texttip;
m_bCatShowName=catshowname;
m_sColour=colour;
m_iCatOrder=catorder;
}
| Creates new CategoryInfo |
@Nullable public static PkiVerificationData verifyPaymentRequestPki(Protos.PaymentRequest paymentRequest,KeyStore trustStore) throws PaymentProtocolException {
List<X509Certificate> certs=null;
try {
final String pkiType=paymentRequest.getPkiType();
if ("none".equals(pkiType)) return null;
String algorithm;
if ("x509+sha256".equals(pkiType)) algorithm="SHA256withRSA";
else if ("x509+sha1".equals(pkiType)) algorithm="SHA1withRSA";
else throw new PaymentProtocolException.InvalidPkiType("Unsupported PKI type: " + pkiType);
Protos.X509Certificates protoCerts=Protos.X509Certificates.parseFrom(paymentRequest.getPkiData());
if (protoCerts.getCertificateCount() == 0) throw new PaymentProtocolException.InvalidPkiData("No certificates provided in message: server config error");
CertificateFactory certificateFactory=CertificateFactory.getInstance("X.509");
certs=Lists.newArrayList();
for ( ByteString bytes : protoCerts.getCertificateList()) certs.add((X509Certificate)certificateFactory.generateCertificate(bytes.newInput()));
CertPath path=certificateFactory.generateCertPath(certs);
PKIXParameters params=new PKIXParameters(trustStore);
params.setRevocationEnabled(false);
CertPathValidator validator=CertPathValidator.getInstance("PKIX");
PKIXCertPathValidatorResult result=(PKIXCertPathValidatorResult)validator.validate(path,params);
PublicKey publicKey=result.getPublicKey();
Signature signature=Signature.getInstance(algorithm);
signature.initVerify(publicKey);
Protos.PaymentRequest.Builder reqToCheck=paymentRequest.toBuilder();
reqToCheck.setSignature(ByteString.EMPTY);
signature.update(reqToCheck.build().toByteArray());
if (!signature.verify(paymentRequest.getSignature().toByteArray())) throw new PaymentProtocolException.PkiVerificationException("Invalid signature, this payment request is not valid.");
final X509Certificate cert=certs.get(0);
String displayName=X509Utils.getDisplayNameFromCertificate(cert,true);
if (displayName == null) throw new PaymentProtocolException.PkiVerificationException("Could not extract name from certificate");
return new PkiVerificationData(displayName,publicKey,result.getTrustAnchor());
}
catch ( InvalidProtocolBufferException e) {
throw new PaymentProtocolException.InvalidPkiData(e);
}
catch ( CertificateException e) {
throw new PaymentProtocolException.PkiVerificationException(e);
}
catch ( NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
catch ( InvalidAlgorithmParameterException e) {
throw new RuntimeException(e);
}
catch ( CertPathValidatorException e) {
throw new PaymentProtocolException.PkiVerificationException(e,certs);
}
catch ( InvalidKeyException e) {
throw new PaymentProtocolException.PkiVerificationException(e);
}
catch ( SignatureException e) {
throw new PaymentProtocolException.PkiVerificationException(e);
}
catch ( KeyStoreException e) {
throw new RuntimeException(e);
}
}
| Uses the provided PKI method to find the corresponding public key and verify the provided signature. |
public static JCExpression typeIn(JCExpression tree){
switch (tree.getTag()) {
case ANNOTATED_TYPE:
return ((JCAnnotatedType)tree).underlyingType;
case IDENT:
case TYPEIDENT:
case SELECT:
case TYPEARRAY:
case WILDCARD:
case TYPEPARAMETER:
case TYPEAPPLY:
case ERRONEOUS:
return tree;
default :
throw new AssertionError("Unexpected type tree: " + tree);
}
}
| Returns the underlying type of the tree if it is an annotated type, or the tree itself otherwise. |
public boolean isSet(_Fields field){
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case HEADER:
return isSetHeader();
case STORE_NAME:
return isSetStoreName();
case KEY:
return isSetKey();
case VERSIONED_VALUE:
return isSetVersionedValue();
case VALUE:
return isSetValue();
}
throw new IllegalStateException();
}
| Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise |
public static double hypot(double a,double b){
double r;
if (Math.abs(a) > Math.abs(b)) {
r=b / a;
r=Math.abs(a) * Math.sqrt(1 + r * r);
}
else if (b != 0) {
r=a / b;
r=Math.abs(b) * Math.sqrt(1 + r * r);
}
else {
r=0.0;
}
return r;
}
| sqrt(a^2 + b^2) without under/overflow. |
public static boolean isBetween(final float x,final float a,final float b){
return (a > b) ? x <= a && x >= b : x <= b && x >= a;
}
| Checks if x is between a and b (or equals a or b). |
public Compactor compactor(){
return compactor;
}
| Returns the log compactor. |
public static Ignite start(URL springCfgUrl,@Nullable ApplicationContext springCtx) throws IgniteCheckedException {
return IgnitionEx.start(springCfgUrl,null,new GridSpringResourceContextImpl(springCtx),null);
}
| Starts all grids specified within given Spring XML configuration file URL. If grid with given name is already started, then exception is thrown. In this case all instances that may have been started so far will be stopped too. <p> Usually Spring XML configuration file will contain only one Grid definition. Note that Grid configuration bean(s) is retrieved form configuration file by type, so the name of the Grid configuration bean is ignored. |
public static float[] closestPoint(float x,float y,float node1X,float node1Y,float node2X,float node2Y){
float dx=node2X - node1X;
float dy=node2Y - node1Y;
float cx, cy;
if (dx == 0.0d && dy == 0.0d) {
cx=node1X;
cy=node1Y;
}
else {
final double u=((x - node1X) * dx + (y - node1Y) * dy) / (dx * dx + dy * dy);
if (u < 0.0d) {
cx=node1X;
cy=node1Y;
}
else if (u > 1.0d) {
cx=node2X;
cy=node2Y;
}
else {
cx=(float)(node1X + u * dx);
cy=(float)(node1Y + u * dy);
}
}
return new float[]{cx,cy};
}
| Calculates the point on the line (node1X,node1Y)-(node2X,node2Y) that is closest to the point (x,y). |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:30:58.185 -0500",hash_original_method="BE93B3D03F00A664B96E561F38428949",hash_generated_method="3C77521596384CF49A716E87F62A934D") public void removeGpsStatusListener(GpsStatus.Listener listener){
try {
GpsStatusListenerTransport transport=mGpsStatusListeners.remove(listener);
if (transport != null) {
mService.removeGpsStatusListener(transport);
}
}
catch ( RemoteException e) {
Log.e(TAG,"RemoteException in unregisterGpsStatusListener: ",e);
}
}
| Removes a GPS status listener. |
private void showFeedback(String feedback){
if (myHost != null) {
myHost.showFeedback(feedback);
}
else {
System.out.println(feedback);
}
}
| Used to communicate feedback pop-up messages between a plugin tool and the main Whitebox user-interface. |
public void sync() throws SailException {
synchronized (syncSemaphore) {
if (persist && contentsChanged) {
logger.debug("syncing data to file...");
try {
IsolationLevels level=IsolationLevels.SNAPSHOT;
SailDataset explicit=store.getExplicitSailSource().dataset(level);
SailDataset inferred=store.getInferredSailSource().dataset(level);
try {
new FileIO(store.getValueFactory()).write(explicit,inferred,syncFile,dataFile);
}
finally {
explicit.close();
inferred.close();
}
contentsChanged=false;
logger.debug("Data synced to file");
}
catch ( IOException e) {
logger.error("Failed to sync to file",e);
throw new SailException(e);
}
}
}
}
| Synchronizes the contents of this repository with the data that is stored on disk. Data will only be written when the contents of the repository and data in the file are out of sync. |
private boolean isOverridden(OutputNode node,Object value) throws Exception {
return factory.setOverride(entry,value,node);
}
| This is used to determine whether the specified value has been overridden by the strategy. If the item has been overridden then no more serialization is require for that value, this is effectively telling the serialization process to stop writing. |
private void printCertFromStream(InputStream in,PrintStream out) throws Exception {
Collection<? extends Certificate> c=null;
try {
c=cf.generateCertificates(in);
}
catch ( CertificateException ce) {
throw new Exception(rb.getString("Failed.to.parse.input"),ce);
}
if (c.isEmpty()) {
throw new Exception(rb.getString("Empty.input"));
}
Certificate[] certs=c.toArray(new Certificate[c.size()]);
for (int i=0; i < certs.length; i++) {
X509Certificate x509Cert=null;
try {
x509Cert=(X509Certificate)certs[i];
}
catch ( ClassCastException cce) {
throw new Exception(rb.getString("Not.X.509.certificate"));
}
if (certs.length > 1) {
MessageFormat form=new MessageFormat(rb.getString("Certificate.i.1."));
Object[] source={new Integer(i + 1)};
out.println(form.format(source));
}
if (rfc) dumpCert(x509Cert,out);
else printX509Cert(x509Cert,out);
if (i < (certs.length - 1)) {
out.println();
}
}
}
| Reads a certificate (or certificate chain) and prints its contents in a human readable format. |
public HashConversion(String[] initData){
initFromStrings(initData);
}
| create a new hash converter which is initialized with avlues from an array of strings in the format "key=value" |
public void testConfigure() throws Exception {
configuration.configure(container);
assertTrue(configuration.getFileHandler().exists(configuration.getHome() + "/config.xml"));
assertTrue(configuration.getFileHandler().exists(configuration.getHome() + "/DefaultAuthenticatorInit.ldift"));
assertTrue(configuration.getFileHandler().exists(configuration.getHome() + "/applications/cargocpc.war"));
}
| Test configuration. |
@PostConstruct public void postConstruct() throws Exception {
if (log.isInfoEnabled()) {
log.info("|-Invocation Data Access Service active...");
}
}
| Is executed after dependency injection is done to perform any initialization. |
public static double[] toDoubleArray(long[] array){
double[] result=new double[array.length];
for (int i=0; i < array.length; i++) {
result[i]=(double)array[i];
}
return result;
}
| Coverts given longs array to array of doubles. |
public boolean isPropertyAgnostic(){
return isPropertyAgnostic;
}
| Returns true for types that accept any property name as a valid property (unchecked type). |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-03-25 15:47:23.137 -0400",hash_original_method="D3EA499101C50F733538C7F2C71C7FCD",hash_generated_method="D3EA499101C50F733538C7F2C71C7FCD") void initialize(CharSequence title,Drawable icon){
setClickable(true);
setFocusable(true);
if (mTextAppearance != -1) {
setTextAppearance(mTextAppearanceContext,mTextAppearance);
}
setTitle(title);
setIcon(icon);
}
| Initializes with the provided title and icon |
private void insert(ByteString byteString){
int depthBin=getDepthBinForLength(byteString.size());
int binEnd=minLengthByDepth[depthBin + 1];
if (prefixesStack.isEmpty() || prefixesStack.peek().size() >= binEnd) {
prefixesStack.push(byteString);
}
else {
int binStart=minLengthByDepth[depthBin];
ByteString newTree=prefixesStack.pop();
while (!prefixesStack.isEmpty() && prefixesStack.peek().size() < binStart) {
ByteString left=prefixesStack.pop();
newTree=new RopeByteString(left,newTree);
}
newTree=new RopeByteString(newTree,byteString);
while (!prefixesStack.isEmpty()) {
depthBin=getDepthBinForLength(newTree.size());
binEnd=minLengthByDepth[depthBin + 1];
if (prefixesStack.peek().size() < binEnd) {
ByteString left=prefixesStack.pop();
newTree=new RopeByteString(left,newTree);
}
else {
break;
}
}
prefixesStack.push(newTree);
}
}
| Push a string on the balance stack (BAP95). BAP95 uses an array and calls the elements in the array 'bins'. We instead use a stack, so the 'bins' of lengths are represented by differences between the elements of minLengthByDepth. <p>If the length bin for our string, and all shorter length bins, are empty, we just push it on the stack. Otherwise, we need to start concatenating, putting the given string in the "middle" and continuing until we land in an empty length bin that matches the length of our concatenation. |
private LinkedList<Diff> diff_main(String text1,String text2,boolean checklines,long deadline){
if (text1 == null || text2 == null) {
throw new IllegalArgumentException("Null inputs. (diff_main)");
}
LinkedList<Diff> diffs;
if (text1.equals(text2)) {
diffs=new LinkedList<Diff>();
if (text1.length() != 0) {
diffs.add(new Diff(Operation.EQUAL,text1));
}
return diffs;
}
int commonlength=diff_commonPrefix(text1,text2);
String commonprefix=text1.substring(0,commonlength);
text1=text1.substring(commonlength);
text2=text2.substring(commonlength);
commonlength=diff_commonSuffix(text1,text2);
String commonsuffix=text1.substring(text1.length() - commonlength);
text1=text1.substring(0,text1.length() - commonlength);
text2=text2.substring(0,text2.length() - commonlength);
diffs=diff_compute(text1,text2,checklines,deadline);
if (commonprefix.length() != 0) {
diffs.addFirst(new Diff(Operation.EQUAL,commonprefix));
}
if (commonsuffix.length() != 0) {
diffs.addLast(new Diff(Operation.EQUAL,commonsuffix));
}
diff_cleanupMerge(diffs);
return diffs;
}
| Find the differences between two texts. Simplifies the problem by stripping any common prefix or suffix off the texts before diffing. |
public AlternativeName(boolean which,byte[] encoding) throws IOException {
super(encoding);
this.which=which;
this.alternativeNames=(GeneralNames)GeneralNames.ASN1.decode(encoding);
}
| Creates the extension object on the base of its encoded form. |
public static boolean isEmbedded(){
return !isSimulation();
}
| Is this an Embedded Environment? Embedded environments are simply described as 'non-simulation' environments, and are therefore assumed to be running on the NI RoboRIO or standard FRC competition computer onboard the Robot. The only time a robot program is embedded is when it has been deployed to a robot and is running. |
public Lock tryExclusiveLock(){
if (lock.isActiveLock()) {
return null;
}
synchronized (this) {
if (lock.isActiveLock()) {
return null;
}
return createLock();
}
}
| Gets the exclusive lock, if available. This method will return <tt>null</tt> if the exclusive lock is not immediately available. |
public static double discharge(ItemStack itemStack,double amount){
if (itemStack != null) {
if (itemStack.getItem() instanceof IEnergizedItem) {
IEnergizedItem energizedItem=(IEnergizedItem)itemStack.getItem();
if (energizedItem.canSend(itemStack)) {
double energyToUse=Math.min(energizedItem.getMaxTransfer(itemStack),Math.min(energizedItem.getEnergy(itemStack),amount));
energizedItem.setEnergy(itemStack,energizedItem.getEnergy(itemStack) - energyToUse);
return energyToUse;
}
}
}
return 0;
}
| Discharges an IEnergizedItem with the defined amount of energy. |
public boolean isCancelled(){
return !this.send;
}
| Check if this packet is cancelled. |
public Document read(InputStream in,String systemId) throws DocumentException {
InputSource source=new InputSource(in);
source.setSystemId(systemId);
if (this.encoding != null) {
source.setEncoding(this.encoding);
}
return read(source);
}
| <p> Reads a Document from the given stream using SAX </p> |
public void testConstrDoubleMinus01(){
double a=-1.E-1;
int aScale=55;
BigInteger bA=new BigInteger("-1000000000000000055511151231257827021181583404541015625");
BigDecimal aNumber=new BigDecimal(a);
assertEquals("incorrect value",bA,aNumber.unscaledValue());
assertEquals("incorrect scale",aScale,aNumber.scale());
}
| new BigDecimal(-0.1) |
public ByteVector(byte[] values){
this.values=new byte[values.length];
System.arraycopy(values,0,this.values,0,values.length);
}
| Create an ByteVector consisting of the given Byte values. |
public void writeEntityToNBT(NBTTagCompound p_70014_1_){
p_70014_1_.setShort("xTile",(short)this.field_145791_d);
p_70014_1_.setShort("yTile",(short)this.field_145792_e);
p_70014_1_.setShort("zTile",(short)this.field_145789_f);
p_70014_1_.setShort("life",(short)this.ticksInGround);
p_70014_1_.setByte("inTile",(byte)Block.getIdFromBlock(this.field_145790_g));
p_70014_1_.setByte("inData",(byte)this.inData);
p_70014_1_.setByte("shake",(byte)this.arrowShake);
p_70014_1_.setByte("inGround",(byte)(this.inGround ? 1 : 0));
p_70014_1_.setByte("pickup",(byte)this.canBePickedUp);
p_70014_1_.setDouble("damage",this.damage);
}
| (abstract) Protected helper method to write subclass entity data to NBT. |
private static int searchSomeElements(BloomIndex<Integer> bfi,int startRange,int endRange,int nbSearchesToDo){
int minSearchSteps=10000000;
int maxSearchSteps=0;
long sumSearchSteps=0;
int nbSearches=0;
int nbFound=0;
int elem;
SearchStatistics stat=new SearchStatistics();
long sumSearchTime=0;
for (int i=0; i < nbSearchesToDo; i++) {
elem=(int)(Math.floor(Math.random() * (endRange - startRange) + startRange));
stat.clear();
long startTime=System.currentTimeMillis();
List<Integer> results=bfi.search(elem,stat);
long endTime=System.currentTimeMillis();
long diffTime=endTime - startTime;
sumSearchTime+=diffTime;
if (results.size() > 0) {
nbFound++;
}
nbSearches++;
if (stat.nbBFChecks < minSearchSteps) {
minSearchSteps=stat.nbBFChecks;
}
if (stat.nbBFChecks > maxSearchSteps) {
maxSearchSteps=stat.nbBFChecks;
}
sumSearchSteps+=stat.nbBFChecks;
}
System.out.print(" |Min steps| " + minSearchSteps + "| Max steps | "+ maxSearchSteps+ "| Avg steps | "+ (double)sumSearchSteps / nbSearches + "| Avg time millis | " + (double)sumSearchTime / nbSearches + "| Total time millis | " + sumSearchTime + "| Nb searches | " + nbSearches);
return nbFound;
}
| Search for nbInteger elements in the [startRange, endRange) |
private static void check(double[][] x,double[][] y){
jMatrix A=new jMatrix(x);
jMatrix B=new jMatrix(y);
check(A,B);
}
| Check norm of difference of arrays. |
public String toString(){
return String.valueOf(get());
}
| Returns the String representation of the current value. |
protected AutumnMessage(){
}
| Can be extended to contain all application's messages, but should not be initiated. |
public static Cleaner create(Object ob,Runnable thunk){
if (thunk == null) return null;
return add(new Cleaner(ob,thunk));
}
| Creates a new cleaner. |
public ASN1Explicit(int tagClass,int tagNumber,ASN1Type type){
super(tagClass,tagNumber);
this.type=type;
}
| Constructs explicitly tagged ASN.1 type. |
void error(String key,Object... args){
if (fatalErrors) {
String msg=getLocalizedString(key,args);
throw new PropagatedException(new IllegalStateException(msg));
}
warning(key,args);
out.println(getLocalizedString("msg.usage",ownName));
}
| Report a usage error. |
private static void sendExceptionSettings(final JFrame parent,final IDebugger debugger,final Collection<DebuggerException> exceptions){
Preconditions.checkNotNull(exceptions,"IE00679: Exceptions argument can not be null");
try {
debugger.setExceptionSettings(exceptions);
}
catch ( final DebugExceptionWrapper e) {
CUtilityFunctions.logException(e);
final String innerMessage="Could not send exceptions settings command";
final String innerDescription=CUtilityFunctions.createDescription("BinNavi could not send the exception settings command to the debug client.",new String[]{"There was a problem with the connection to the debug client."},new String[]{"The state of the debugged process remains unchanged."});
NaviErrorDialog.show(parent,innerMessage,innerDescription,e);
}
}
| Sends the list of exceptions which need special handling by the debug client. |
static SnmpOid makeOid(long l){
long[] x=new long[8];
x[0]=(l >> 56) & 0xFF;
x[1]=(l >> 48) & 0x00FF;
x[2]=(l >> 40) & 0x0000FF;
x[3]=(l >> 32) & 0x000000FF;
x[4]=(l >> 24) & 0x00000000FF;
x[5]=(l >> 16) & 0x0000000000FF;
x[6]=(l >> 8) & 0x000000000000FF;
x[7]=l & 0x00000000000000FF;
return new SnmpOid(x);
}
| Translate from a long to a Oid. Arc follow the long big-endian order. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.