code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
public static Number minus(Character left,Number right){
return NumberNumberMinus.minus(Integer.valueOf(left),right);
}
| Subtract a Number from a Character. The ordinal value of the Character is used in the subtraction (the ordinal value is the unicode value which for simple character sets is the ASCII value). |
public static String createHandlerRequestPath(final CacheKey cacheKey,final HttpServletRequest request){
final String handlerQueryPath=getRequestHandlerPath(cacheKey.getGroupName(),cacheKey.getType());
return request.getServletPath() + handlerQueryPath;
}
| Computes the servlet context relative url to call this handler using a server-side invocation. Hides the details about creating a valid url and providing the authorization key required to invoke this handler. |
@Override public void postSolve(Contact contact,ContactImpulse impulse){
Object dataA=contact.getFixtureA().getBody().getUserData();
Object dataB=contact.getFixtureB().getBody().getUserData();
boolean hitCane=false;
if (dataA != null && !(dataA instanceof Gumball) && (Integer)dataA > TiltGameView.GUMBALL_PURPLE) {
hitCane=true;
}
else if (dataB != null && !(dataB instanceof Gumball) && (Integer)dataB > TiltGameView.GUMBALL_PURPLE) {
hitCane=true;
}
if (hitCane && impulse.normalImpulses[0] > 80) {
playBounceSound(impulse.normalImpulses[0]);
}
}
| Play a sound on impact (when a ball is dropped). The sound depends on the severity of the impact. |
@Dev public PlayerHasKilledNumberOfCreaturesCondition(Map<String,Integer> kills){
creatures=new HashMap<String,Integer>();
creatures.putAll(kills);
}
| creates a condition to kill each creature with the name specified in the map and the number as value |
public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, SystemException {
LogWriterI18n writer=TransactionUtils.getLogWriterI18n();
try {
XAResource xar=null;
XAResource xar1=null;
int loop=0;
Boolean isActive=Boolean.FALSE;
synchronized (this.resourceMap) {
Map.Entry entry;
Iterator iterator=resourceMap.entrySet().iterator();
while (iterator.hasNext()) {
try {
entry=(Map.Entry)iterator.next();
xar=(XAResource)entry.getKey();
isActive=(Boolean)entry.getValue();
if (loop == 0) xar1=xar;
loop++;
if (isActive.booleanValue()) {
xar.end(xid,XAResource.TMSUCCESS);
entry.setValue(Boolean.FALSE);
}
}
catch ( Exception e) {
if (VERBOSE) writer.info(LocalizedStrings.ONE_ARG,"GlobalTransaction::commit:Exception in delisting XAResource",e);
}
}
}
if (xar1 != null) xar1.commit(xid,true);
status=Status.STATUS_COMMITTED;
if (VERBOSE) writer.fine("GlobalTransaction::commit:Transaction committed successfully");
}
catch ( Exception e) {
status=Status.STATUS_ROLLING_BACK;
try {
rollback();
}
catch ( VirtualMachineError err) {
SystemFailure.initiateFailure(err);
throw err;
}
catch ( Throwable t) {
SystemFailure.checkFailure();
status=Status.STATUS_ROLLEDBACK;
String exception=LocalizedStrings.GlobalTransaction_GLOBALTRANSACTION_COMMIT_ERROR_IN_COMMITTING_BUT_TRANSACTION_COULD_NOT_BE_ROLLED_BACK_DUE_TO_EXCEPTION_0.toLocalizedString(t);
if (VERBOSE) writer.fine(exception,t);
SystemException sysEx=new SystemException(exception);
sysEx.initCause(t);
throw sysEx;
}
String exception=LocalizedStrings.GlobalTransaction_GLOBALTRANSACTION_COMMIT_ERROR_IN_COMMITTING_THE_TRANSACTION_TRANSACTION_ROLLED_BACK_EXCEPTION_0_1.toLocalizedString(new Object[]{e," " + (e instanceof XAException ? ("Error Code =" + ((XAException)e).errorCode) : "")});
if (VERBOSE) writer.fine(exception,e);
RollbackException rbEx=new RollbackException(exception);
rbEx.initCause(e);
throw rbEx;
}
finally {
TransactionManagerImpl.getTransactionManager().cleanGlobalTransactionMap(transactions);
transactions.clear();
}
}
| Delists the XAResources associated with the Global Transaction and Completes the Global transaction associated with the current thread. If any exception is encountered, rollback is called on the current transaction. Concurrency: Some paths invoke this method after taking a lock on "this" while other paths invoke this method without taking a lock on "this". Since both types of path do act on the resourceMap collection, it is being protected by a lock on resourceMap too. |
@Override protected EClass eStaticClass(){
return SGraphPackage.Literals.TRANSITION;
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
protected NamedList<NamedList> handleAnalysisRequest(FieldAnalysisRequest request,IndexSchema schema){
NamedList<NamedList> analysisResults=new SimpleOrderedMap<>();
NamedList<NamedList> fieldTypeAnalysisResults=new SimpleOrderedMap<>();
if (request.getFieldTypes() != null) {
for ( String fieldTypeName : request.getFieldTypes()) {
FieldType fieldType=schema.getFieldTypes().get(fieldTypeName);
fieldTypeAnalysisResults.add(fieldTypeName,analyzeValues(request,fieldType,null));
}
}
NamedList<NamedList> fieldNameAnalysisResults=new SimpleOrderedMap<>();
if (request.getFieldNames() != null) {
for ( String fieldName : request.getFieldNames()) {
FieldType fieldType=schema.getFieldType(fieldName);
fieldNameAnalysisResults.add(fieldName,analyzeValues(request,fieldType,fieldName));
}
}
analysisResults.add("field_types",fieldTypeAnalysisResults);
analysisResults.add("field_names",fieldNameAnalysisResults);
return analysisResults;
}
| Handles the resolved analysis request and returns the analysis breakdown response as a named list. |
public String replacePath(String inputURI){
if (inputURI.contains(TemporaryDirectoryManager.DIRECTORY_TEMPLATE) && passedInDirectoryName != null && !passedInDirectoryName.isEmpty()) {
final String mungedURI=inputURI.replace(TemporaryDirectoryManager.DIRECTORY_TEMPLATE,passedInDirectoryName);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("URI changed to " + mungedURI);
}
return mungedURI;
}
else {
LOGGER.debug("Returning inputURI unchanged: " + inputURI);
return inputURI;
}
}
| This method replaces (if found) the sub-string [UNIQUE] in any input String with the value determined by the implementation of this interface. |
private void showFeedback(String message){
if (myHost != null) {
myHost.showFeedback(message);
}
else {
System.out.println(message);
}
}
| Used to communicate feedback pop-up messages between a plugin tool and the main Whitebox user-interface. |
public ul addElement(String element){
addElementToRegistry(element);
return (this);
}
| Adds an Element to the element. |
public static Text createTextLeft(String title,Composite parent,FormToolkit toolkit){
Label createLabel=toolkit.createLabel(parent,title);
GridData gd=new GridData();
createLabel.setLayoutData(gd);
gd.verticalAlignment=SWT.TOP;
Text text=toolkit.createText(parent,"");
gd=new GridData(SWT.FILL,SWT.LEFT,true,false);
gd.horizontalIndent=30;
gd.verticalAlignment=SWT.TOP;
gd.horizontalAlignment=SWT.RIGHT;
gd.minimumWidth=200;
text.setLayoutData(gd);
return text;
}
| Creates a text component with left-aligned text |
public MethodRef(String declClass,String[] argTypes,String returnType,String methodName){
mDeclClass=declClass;
mArgTypes=argTypes;
mReturnType=returnType;
mMethodName=methodName;
}
| Initializes a new field reference. |
@SuppressWarnings({"unchecked"}) public static <T>T[] insertAt(T[] dest,T[] src,int offset,Class componentType){
T[] temp=(T[])Array.newInstance(componentType,dest.length + src.length - 1);
System.arraycopy(dest,0,temp,0,offset);
System.arraycopy(src,0,temp,offset,src.length);
System.arraycopy(dest,offset + 1,temp,src.length + offset,dest.length - offset - 1);
return temp;
}
| Inserts one array into another at given offset. |
@Override public boolean isEmpty(){
return size == 0;
}
| Checks whether the map is currently empty. |
public void add(T object){
synchronized (mLock) {
if (mOriginalValues != null) {
mOriginalValues.add(object);
}
else {
mObjects.add(object);
}
}
if (mNotifyOnChange) notifyDataSetChanged();
}
| Adds the specified object at the end of the array. |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:56:48.306 -0500",hash_original_method="C730C766F4F6CE91266CBA72D38C529A",hash_generated_method="023C0B2F9BE49BF16B5DD6A189CAE77F") private boolean inSamePackage(Class<?> c1,Class<?> c2){
String nameC1=c1.getName();
String nameC2=c2.getName();
int indexDotC1=nameC1.lastIndexOf('.');
int indexDotC2=nameC2.lastIndexOf('.');
if (indexDotC1 != indexDotC2) {
return false;
}
if (indexDotC1 == -1) {
return true;
}
return nameC1.regionMatches(0,nameC2,0,indexDotC1);
}
| Checks if two classes belong to the same package. |
public Matrix4d billboardCylindrical(Vector3dc objPos,Vector3dc targetPos,Vector3dc up){
double dirX=targetPos.x() - objPos.x();
double dirY=targetPos.y() - objPos.y();
double dirZ=targetPos.z() - objPos.z();
double leftX=up.y() * dirZ - up.z() * dirY;
double leftY=up.z() * dirX - up.x() * dirZ;
double leftZ=up.x() * dirY - up.y() * dirX;
double invLeftLen=1.0 / Math.sqrt(leftX * leftX + leftY * leftY + leftZ * leftZ);
leftX*=invLeftLen;
leftY*=invLeftLen;
leftZ*=invLeftLen;
dirX=leftY * up.z() - leftZ * up.y();
dirY=leftZ * up.x() - leftX * up.z();
dirZ=leftX * up.y() - leftY * up.x();
double invDirLen=1.0 / Math.sqrt(dirX * dirX + dirY * dirY + dirZ * dirZ);
dirX*=invDirLen;
dirY*=invDirLen;
dirZ*=invDirLen;
m00=leftX;
m01=leftY;
m02=leftZ;
m03=0.0;
m10=up.x();
m11=up.y();
m12=up.z();
m13=0.0;
m20=dirX;
m21=dirY;
m22=dirZ;
m23=0.0;
m30=objPos.x();
m31=objPos.y();
m32=objPos.z();
m33=1.0;
properties=PROPERTY_AFFINE;
return this;
}
| Set this matrix to a cylindrical billboard transformation that rotates the local +Z axis of a given object with position <code>objPos</code> towards a target position at <code>targetPos</code> while constraining a cylindrical rotation around the given <code>up</code> vector. <p> This method can be used to create the complete model transformation for a given object, including the translation of the object to its position <code>objPos</code>. |
public String trimChar(String str,final char ch){
Boolean b=true, e=true;
str=str.trim();
while (str.length() > 0 && (b || e)) {
if (str.charAt(0) == ch) str=str.substring(1,str.length());
else b=false;
if (str.charAt(str.length() - 1) == ch) str=str.substring(0,str.length() - 1);
else e=false;
}
return str;
}
| this function trims ch in string |
public void subscribeToBrokerServiceNoDiscount() throws Exception {
VendorData supplierData=setupNewSupplier("2013-01-01 08:00:00");
setCutOffDay(supplierData.getAdminKey(),1);
setDateFactory("2013-01-02 20:00:00");
VOServiceDetails supplService=createPublishActivateService(supplierData,TestPriceModel.EXAMPLE_RATA_WEEK_ROLES,"supplSrvForBroker");
updateOperatorRevenueShare(5.0D,supplService.getKey());
updatePartnerRevenueShares(15.0D,20.0D,supplService);
VendorData brokerData=setupNewBroker("2013-01-03 08:10:00");
CustomerData brokerCustomerData=registerCustomer(brokerData,"brokerCustomer");
updateMarketplaceRevenueShare(10.0D,brokerData.getMarketplaceId(0));
setDateFactory("2013-01-03 10:00:00");
VOServiceDetails brokerService=grantResalePermission(supplierData,supplService,brokerData);
brokerService=publishActivateService(brokerData,brokerService);
subscribe(brokerCustomerData.getAdminUser(),"brokerSubscr1",brokerService,"2013-01-04 00:00:00","ADMIN");
resetCutOffDay(supplierData.getAdminKey());
cacheTestData("subscribeToBrokerServiceNoDiscount",new TestData(supplierData,brokerData));
}
| Subscribe to broker service. Customer has no discount. |
@Override public boolean remove(Object obj){
return removeFirstOccurrenceImpl(obj);
}
| Removes the first equivalent element of the specified object. If the deque does not contain the element, it is unchanged and returns false. |
private static Review current(Cursor c){
Review review=new Review();
Syncing.from(c,review);
int col=c.getColumnIndex(RESTAURANT_ID);
if (col >= 0) {
review.restaurantId=c.getLong(col);
}
col=c.getColumnIndex(TYPE_ID);
if (col >= 0) {
review.type=Review.Type.get(c.getInt(col));
}
col=c.getColumnIndex(CONTACT_ID);
if (col >= 0) {
review.userId=c.getLong(col);
}
col=c.getColumnIndex(COMMENTS);
if (col >= 0) {
review.comments=c.getString(col);
}
col=c.getColumnIndex(RATING);
if (col >= 0) {
review.rating=c.getInt(col);
}
col=c.getColumnIndex(WRITTEN_ON);
if (col >= 0) {
review.writtenOn=c.getString(col);
}
return review;
}
| Get the current review from the cursor. |
@Override public void write(final String filename){
try {
this.openFile(filename);
this.handler.writeHeaderAndStartElement(this.writer);
this.handler.startPlans(this.population,this.writer);
this.handler.writeSeparator(this.writer);
this.writePersons();
this.handler.endPlans(this.writer);
log.info("Population written to: " + filename);
}
catch ( IOException e) {
throw new UncheckedIOException(e);
}
finally {
this.close();
counter.printCounter();
counter.reset();
}
}
| Writes all plans to the file. |
public void display() throws IOException, ObjectNotFoundException, OperationNotPermittedException, ValidationException, OrganizationAuthoritiesException {
VOPriceModel priceModel=model.getService().getPriceModel().getVo();
ExternalPriceModelDisplayHandler displayHandler=new ExternalPriceModelDisplayHandler();
displayHandler.setContent(priceModel.getPresentation());
displayHandler.setContentType(priceModel.getPresentationDataType());
displayHandler.display();
}
| Method is used in UI to show external price model details. |
public static void main(String[] args){
Log.printLine("Starting ContainerCloudSimExample1...");
try {
int num_user=1;
Calendar calendar=Calendar.getInstance();
boolean trace_flag=false;
CloudSim.init(num_user,calendar,trace_flag);
ContainerAllocationPolicy containerAllocationPolicy=new PowerContainerAllocationPolicySimple();
PowerContainerVmSelectionPolicy vmSelectionPolicy=new PowerContainerVmSelectionPolicyMaximumUsage();
HostSelectionPolicy hostSelectionPolicy=new HostSelectionPolicyFirstFit();
double overUtilizationThreshold=0.80;
double underUtilizationThreshold=0.70;
hostList=new ArrayList<ContainerHost>();
hostList=createHostList(ConstantsExamples.NUMBER_HOSTS);
cloudletList=new ArrayList<ContainerCloudlet>();
vmList=new ArrayList<ContainerVm>();
ContainerVmAllocationPolicy vmAllocationPolicy=new PowerContainerVmAllocationPolicyMigrationAbstractHostSelection(hostList,vmSelectionPolicy,hostSelectionPolicy,overUtilizationThreshold,underUtilizationThreshold);
int overBookingFactor=80;
ContainerDatacenterBroker broker=createBroker(overBookingFactor);
int brokerId=broker.getId();
cloudletList=createContainerCloudletList(brokerId,ConstantsExamples.NUMBER_CLOUDLETS);
containerList=createContainerList(brokerId,ConstantsExamples.NUMBER_CLOUDLETS);
vmList=createVmList(brokerId,ConstantsExamples.NUMBER_VMS);
String logAddress="~/Results";
@SuppressWarnings("unused") PowerContainerDatacenter e=(PowerContainerDatacenter)createDatacenter("datacenter",PowerContainerDatacenterCM.class,hostList,vmAllocationPolicy,containerAllocationPolicy,getExperimentName("ContainerCloudSimExample-1",String.valueOf(overBookingFactor)),ConstantsExamples.SCHEDULING_INTERVAL,logAddress,ConstantsExamples.VM_STARTTUP_DELAY,ConstantsExamples.CONTAINER_STARTTUP_DELAY);
broker.submitCloudletList(cloudletList.subList(0,containerList.size()));
broker.submitContainerList(containerList);
broker.submitVmList(vmList);
CloudSim.terminateSimulation(86400.00);
CloudSim.startSimulation();
CloudSim.stopSimulation();
List<ContainerCloudlet> newList=broker.getCloudletReceivedList();
printCloudletList(newList);
Log.printLine("ContainerCloudSimExample1 finished!");
}
catch ( Exception e) {
e.printStackTrace();
Log.printLine("Unwanted errors happen");
}
}
| Creates main() to run this example. |
public void testMultivariateMIforDependentVariablesFromFile() throws Exception {
ArrayFileReader afr=new ArrayFileReader("demos/data/4ColsPairedDirectDependence-1.txt");
double[][] data=afr.getDouble2DMatrix();
int[] kNNs={1,2,3,4,5,6,10,15};
double[] expectedFromMILCA_2={8.44056282,7.69813699,7.26909347,6.97095249,6.73728113,6.53105867,5.96391264,5.51627278};
System.out.println("Kraskov comparison 6 - multivariate dependent data 1");
checkMIForGivenData(MatrixUtils.selectColumns(data,new int[]{0,1,2,3}),kNNs,expectedFromMILCA_2);
}
| Test the computed multivariate MI against that calculated by Kraskov's own MILCA tool on the same data. To run Kraskov's tool (http://www.klab.caltech.edu/~kraskov/MILCA/) for this data, run: ./MIhigherdim <dataFile> 4 1 1 3000 <kNearestNeighbours> 0 |
public Map<String,String> toMap(){
return putIn(new HashMap<String,String>(values.length));
}
| Copies this record into a new Map. The new map is not connect |
public void doBucketsSyncOnPrimaryLoss(TestType typeOfTest){
IgnoredException.addIgnoredException("killing member's ds");
IgnoredException.addIgnoredException("killing member's ds");
Host host=Host.getHost(0);
VM vm0=host.getVM(0);
VM vm1=host.getVM(1);
VM vm2=host.getVM(2);
Set<VM> verifyVMs=new HashSet<VM>();
final String name=this.getUniqueName() + "Region";
verifyVMs.add(vm0);
verifyVMs.add(vm1);
verifyVMs.add(vm2);
disconnectAllFromDS();
try {
createRegion(vm0,name,typeOfTest);
createRegion(vm1,name,typeOfTest);
createRegion(vm2,name,typeOfTest);
createEntry1(vm0);
VM primaryOwner;
if (isPrimaryForBucket0(vm0)) primaryOwner=vm0;
else if (isPrimaryForBucket0(vm1)) primaryOwner=vm1;
else primaryOwner=vm2;
verifyVMs.remove(primaryOwner);
VM creatorVM=null;
InternalDistributedMember primaryID=getID(primaryOwner);
VersionSource primaryVersionID=getVersionID(primaryOwner);
for ( VM vm : verifyVMs) {
creatorVM=vm;
createEntry2(creatorVM,primaryID,primaryVersionID);
break;
}
verifyVMs.remove(creatorVM);
DistributedTestUtils.crashDistributedSystem(primaryOwner);
for ( VM vm : verifyVMs) {
verifySynchronized(vm,primaryID);
}
}
finally {
disconnectAllFromDS();
}
}
| We hit this problem in bug #45669. A primary was lost and we did not see secondary buckets perform a delta-GII. |
public void test_ConstructorIII(){
Date d1=new Date(70,0,1);
Date d2=new Date(0 + d1.getTimezoneOffset() * 60 * 1000);
assertTrue("Created incorrect date",d1.equals(d2));
Date date=new Date(99,5,22);
Calendar cal=new GregorianCalendar(1999,Calendar.JUNE,22);
assertTrue("Wrong time zone",date.equals(cal.getTime()));
}
| java.util.Date#Date(int, int, int) |
public String toString(){
return "[Place " + player.getMark() + " @ ("+ col+ ","+ row+ ")]";
}
| Return object in readable form. |
public NodeRepresentation(){
}
| Constructs an empty object |
public String metaphone(String txt){
boolean hard=false;
if ((txt == null) || (txt.length() == 0)) {
return "";
}
if (txt.length() == 1) {
return txt.toUpperCase();
}
char[] inwd=txt.toUpperCase().toCharArray();
StringBuffer local=new StringBuffer(40);
StringBuffer code=new StringBuffer(10);
switch (inwd[0]) {
case 'K':
case 'G':
case 'P':
if (inwd[1] == 'N') {
local.append(inwd,1,inwd.length - 1);
}
else {
local.append(inwd);
}
break;
case 'A':
if (inwd[1] == 'E') {
local.append(inwd,1,inwd.length - 1);
}
else {
local.append(inwd);
}
break;
case 'W':
if (inwd[1] == 'R') {
local.append(inwd,1,inwd.length - 1);
break;
}
if (inwd[1] == 'H') {
local.append(inwd,1,inwd.length - 1);
local.setCharAt(0,'W');
}
else {
local.append(inwd);
}
break;
case 'X':
inwd[0]='S';
local.append(inwd);
break;
default :
local.append(inwd);
}
int wdsz=local.length();
int n=0;
while ((code.length() < this.getMaxCodeLen()) && (n < wdsz)) {
char symb=local.charAt(n);
if ((symb != 'C') && (isPreviousChar(local,n,symb))) {
n++;
}
else {
switch (symb) {
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
if (n == 0) {
code.append(symb);
}
break;
case 'B':
if (isPreviousChar(local,n,'M') && isLastChar(wdsz,n)) {
break;
}
code.append(symb);
break;
case 'C':
if (isPreviousChar(local,n,'S') && !isLastChar(wdsz,n) && (this.frontv.indexOf(local.charAt(n + 1)) >= 0)) {
break;
}
if (regionMatch(local,n,"CIA")) {
code.append('X');
break;
}
if (!isLastChar(wdsz,n) && (this.frontv.indexOf(local.charAt(n + 1)) >= 0)) {
code.append('S');
break;
}
if (isPreviousChar(local,n,'S') && isNextChar(local,n,'H')) {
code.append('K');
break;
}
if (isNextChar(local,n,'H')) {
if ((n == 0) && (wdsz >= 3) && isVowel(local,2)) {
code.append('K');
}
else {
code.append('X');
}
}
else {
code.append('K');
}
break;
case 'D':
if (!isLastChar(wdsz,n + 1) && isNextChar(local,n,'G') && (this.frontv.indexOf(local.charAt(n + 2)) >= 0)) {
code.append('J');
n+=2;
}
else {
code.append('T');
}
break;
case 'G':
if (isLastChar(wdsz,n + 1) && isNextChar(local,n,'H')) {
break;
}
if (!isLastChar(wdsz,n + 1) && isNextChar(local,n,'H') && !isVowel(local,n + 2)) {
break;
}
if ((n > 0) && (regionMatch(local,n,"GN") || regionMatch(local,n,"GNED"))) {
break;
}
if (isPreviousChar(local,n,'G')) {
hard=true;
}
else {
hard=false;
}
if (!isLastChar(wdsz,n) && (this.frontv.indexOf(local.charAt(n + 1)) >= 0) && (!hard)) {
code.append('J');
}
else {
code.append('K');
}
break;
case 'H':
if (isLastChar(wdsz,n)) {
break;
}
if ((n > 0) && (this.varson.indexOf(local.charAt(n - 1)) >= 0)) {
break;
}
if (isVowel(local,n + 1)) {
code.append('H');
}
break;
case 'F':
case 'J':
case 'L':
case 'M':
case 'N':
case 'R':
code.append(symb);
break;
case 'K':
if (n > 0) {
if (!isPreviousChar(local,n,'C')) {
code.append(symb);
}
}
else {
code.append(symb);
}
break;
case 'P':
if (isNextChar(local,n,'H')) {
code.append('F');
}
else {
code.append(symb);
}
break;
case 'Q':
code.append('K');
break;
case 'S':
if (regionMatch(local,n,"SH") || regionMatch(local,n,"SIO") || regionMatch(local,n,"SIA")) {
code.append('X');
}
else {
code.append('S');
}
break;
case 'T':
if (regionMatch(local,n,"TIA") || regionMatch(local,n,"TIO")) {
code.append('X');
break;
}
if (regionMatch(local,n,"TCH")) {
break;
}
if (regionMatch(local,n,"TH")) {
code.append('0');
}
else {
code.append('T');
}
break;
case 'V':
code.append('F');
break;
case 'W':
case 'Y':
if (!isLastChar(wdsz,n) && isVowel(local,n + 1)) {
code.append(symb);
}
break;
case 'X':
code.append('K');
code.append('S');
break;
case 'Z':
code.append('S');
break;
}
n++;
}
if (code.length() > this.getMaxCodeLen()) {
code.setLength(this.getMaxCodeLen());
}
}
return code.toString();
}
| Find the metaphone value of a String. This is similar to the soundex algorithm, but better at finding similar sounding words. All input is converted to upper case. Limitations: Input format is expected to be a single ASCII word with only characters in the A - Z range, no punctuation or numbers. |
public int encodeMessage(byte[] outputBytes) throws SnmpTooBigException {
int encodingLength=0;
if (SNMP_LOGGER.isLoggable(Level.FINER)) {
SNMP_LOGGER.logp(Level.FINER,SnmpV3Message.class.getName(),"encodeMessage","Can't encode directly V3Message! Need a SecuritySubSystem");
}
throw new IllegalArgumentException("Can't encode");
}
| Encodes this message and puts the result in the specified byte array. For internal use only. |
public String minRadiusTipText(){
return "The lower boundary for the radius of the clusters.";
}
| Returns the tip text for this property |
public boolean isAutocomplete(){
Object oo=get_Value(COLUMNNAME_IsAutocomplete);
if (oo != null) {
if (oo instanceof Boolean) return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
| Get Autocomplete. |
public DaylightCondition(final DaylightPhase... daylightPhases){
super();
this.daylightPhases=Arrays.asList(daylightPhases);
}
| creates a new DaytimeCondition |
@Override public boolean markSupported(){
return false;
}
| We don't support marks. |
void minimizeLocalICs(){
List<InnerClass> diff=computeICdiff();
List<InnerClass> actualICs=innerClasses;
List<InnerClass> localICs;
if (diff.isEmpty()) {
localICs=null;
if (actualICs != null && actualICs.isEmpty()) {
if (verbose > 0) Utils.log.info("Warning: Dropping empty InnerClasses attribute from " + this);
}
}
else if (actualICs == null) {
localICs=Collections.emptyList();
}
else {
localICs=diff;
}
setInnerClasses(localICs);
if (verbose > 1 && localICs != null) Utils.log.fine("keeping local ICs in " + this + ": "+ localICs);
}
| When packing, anticipate the effect of expandLocalICs. Replace the local ICs by their symmetric difference with the globally implied ICs for this class; if this difference is empty, remove the local ICs altogether. <p> An empty local IC attribute is reserved to signal the unpacker to delete the attribute altogether, so a missing local IC attribute signals the unpacker to use the globally implied ICs changed. |
public static TypeReference createExactTrusted(ResolvedJavaType type){
if (type == null) {
return null;
}
return new TypeReference(type,true);
}
| Creates an exact type reference using the given type. |
public boolean isPrivateUserGroup(){
return isPrivateUserGroup(this.type,this.autoDelete,this.name);
}
| Returns true if this is a user's private group (personal or organization). |
private boolean journalRebuildRequired(){
final int REDUNDANT_OP_COMPACT_THRESHOLD=2000;
return redundantOpCount >= REDUNDANT_OP_COMPACT_THRESHOLD && redundantOpCount >= lruEntries.size();
}
| We only rebuild the journal when it will halve the size of the journal and eliminate at least 2000 ops. |
public ClassMarkerProcessor(ProjectMarkerProcessor projectProcessor,String className){
fProjectProcessor=projectProcessor;
fFile=DroidsafePluginUtilities.getFile(projectProcessor.getProject(),className);
fTaintedDataMap=projectProcessor.getTaintedDataMap(className);
fUnreachableSourceMethodMap=projectProcessor.getUnreachableSourceMethodMap(className);
}
| Constructs a ClassMarkerProcessor given a ProjectMarkerProcessor for the current project and the name for the underlying Java class. |
protected void configureExtraClasspathToken(WAR deployable,Element context){
getLogger().warn("Tomcat 5.x doesn't support extra classpath on WARs",this.getClass().getName());
}
| Configures the specified context element with the extra classpath (if any) of the given WAR. |
@Override public Object eGet(int featureID,boolean resolve,boolean coreType){
switch (featureID) {
case EipPackage.EIP_MODEL__OWNED_ROUTES:
return getOwnedRoutes();
case EipPackage.EIP_MODEL__OWNED_SERVICE_REFS:
return getOwnedServiceRefs();
}
return super.eGet(featureID,resolve,coreType);
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
@SuppressWarnings("rawtypes") public Object checkNotAllowedMethods(ProceedingJoinPoint pjp) throws Throwable {
Class targetClass=pjp.getTarget().getClass();
MethodSignature targetMethodSignature=(MethodSignature)pjp.getSignature();
String methodName=targetClass.getName() + "." + targetMethodSignature.getName();
configurationDaoHelper.checkNotAllowedMethod(methodName);
return pjp.proceed();
}
| Checks whether the requested operation is permitted. |
private static int guessCapacity(int capacity,Map<CharSequence,CharSequence> replacements){
if (capacity >= 0) {
return capacity;
}
boolean possiblyBigger=false;
for ( Map.Entry<CharSequence,CharSequence> entry : replacements.entrySet()) {
if (entry.getValue().length() > entry.getKey().length()) {
possiblyBigger=true;
break;
}
}
return possiblyBigger ? replacements.size() * 3 / 2 : replacements.size();
}
| Crude heuristic for setting the created StringBuilder capacity if not supplied: If at least one replacement text is bigger than the original text use a capacity 50% larger than the original; otherwise, use the original size. |
public void actionPerformed(ActionEvent e){
if (ADJUSTTIMER) {
long time=System.currentTimeMillis();
if (lastCall > 0) {
int nextDelay=(int)(previousDelay - time + lastCall + getRepaintInterval());
if (nextDelay < MINIMUM_DELAY) {
nextDelay=MINIMUM_DELAY;
}
timer.setInitialDelay(nextDelay);
previousDelay=nextDelay;
}
timer.start();
lastCall=time;
}
incrementAnimationIndex();
}
| Reacts to the timer's action events. |
@Catch({UnexpectedException.class,ViPRException.class}) public static void handleJsonError(Exception e){
if (request.isAjax() || StringUtils.endsWithIgnoreCase(request.action,"json")) {
Throwable cause=Common.unwrap(e);
String message=Common.getUserMessage(cause);
Logger.error(e,"AJAX request failed: %s.%s [%s]",request.controller,request.action,message);
error(message);
}
}
| Handles errors that might arise during JSON requests and returns the error message. |
public final char yycharat(int pos){
return zzBuffer[zzStartRead + pos];
}
| Returns the character at position <tt>pos</tt> from the matched text. It is equivalent to yytext().charAt(pos), but faster |
SpecialSegmentTreeNode(int left,int right){
super(left,right);
}
| Store additional information as a test. |
@Override public boolean isActive(){
return amIActive;
}
| Used by the Whitebox GUI to tell if this plugin is still running. |
private void updateProgress(String progressLabel,int progress){
if (myHost != null && ((progress != previousProgress) || (!progressLabel.equals(previousProgressLabel)))) {
myHost.updateProgress(progressLabel,progress);
}
previousProgress=progress;
previousProgressLabel=progressLabel;
}
| Used to communicate a progress update between a plugin tool and the main Whitebox user interface. |
public void propertyChange(java.beans.PropertyChangeEvent evt){
setText(evt.getNewValue().toString());
}
| Listening method, diplays results |
public boolean forwardIfCurrent(String first,char second){
int start=pos;
if (!forwardIfCurrent(first)) return false;
removeSpace();
boolean rtn=forwardIfCurrent(second);
if (!rtn) pos=start;
return rtn;
}
| Gibt zurueck ob first den folgenden Zeichen entspricht, gefolgt von Leerzeichen und second, wenn ja wird der Zeiger um die Laenge der uebereinstimmung nach vorne gestellt. |
protected void addVetoableChangeSupport(ClassNode declaringClass){
ClassNode vcsClassNode=ClassHelper.make(VetoableChangeSupport.class);
ClassNode vclClassNode=ClassHelper.make(VetoableChangeListener.class);
FieldNode vcsField=declaringClass.addField("this$vetoableChangeSupport",ACC_FINAL | ACC_PRIVATE | ACC_SYNTHETIC,vcsClassNode,ctorX(vcsClassNode,args(varX("this"))));
declaringClass.addMethod(new MethodNode("addVetoableChangeListener",ACC_PUBLIC,ClassHelper.VOID_TYPE,params(param(vclClassNode,"listener")),ClassNode.EMPTY_ARRAY,stmt(callX(fieldX(vcsField),"addVetoableChangeListener",args(varX("listener",vclClassNode))))));
declaringClass.addMethod(new MethodNode("addVetoableChangeListener",ACC_PUBLIC,ClassHelper.VOID_TYPE,params(param(ClassHelper.STRING_TYPE,"name"),param(vclClassNode,"listener")),ClassNode.EMPTY_ARRAY,stmt(callX(fieldX(vcsField),"addVetoableChangeListener",args(varX("name",ClassHelper.STRING_TYPE),varX("listener",vclClassNode))))));
declaringClass.addMethod(new MethodNode("removeVetoableChangeListener",ACC_PUBLIC,ClassHelper.VOID_TYPE,params(param(vclClassNode,"listener")),ClassNode.EMPTY_ARRAY,stmt(callX(fieldX(vcsField),"removeVetoableChangeListener",args(varX("listener",vclClassNode))))));
declaringClass.addMethod(new MethodNode("removeVetoableChangeListener",ACC_PUBLIC,ClassHelper.VOID_TYPE,params(param(ClassHelper.STRING_TYPE,"name"),param(vclClassNode,"listener")),ClassNode.EMPTY_ARRAY,stmt(callX(fieldX(vcsField),"removeVetoableChangeListener",args(varX("name",ClassHelper.STRING_TYPE),varX("listener",vclClassNode))))));
declaringClass.addMethod(new MethodNode("fireVetoableChange",ACC_PUBLIC,ClassHelper.VOID_TYPE,params(param(ClassHelper.STRING_TYPE,"name"),param(ClassHelper.OBJECT_TYPE,"oldValue"),param(ClassHelper.OBJECT_TYPE,"newValue")),new ClassNode[]{ClassHelper.make(PropertyVetoException.class)},stmt(callX(fieldX(vcsField),"fireVetoableChange",args(varX("name",ClassHelper.STRING_TYPE),varX("oldValue"),varX("newValue"))))));
declaringClass.addMethod(new MethodNode("getVetoableChangeListeners",ACC_PUBLIC,vclClassNode.makeArray(),Parameter.EMPTY_ARRAY,ClassNode.EMPTY_ARRAY,returnS(callX(fieldX(vcsField),"getVetoableChangeListeners"))));
declaringClass.addMethod(new MethodNode("getVetoableChangeListeners",ACC_PUBLIC,vclClassNode.makeArray(),params(param(ClassHelper.STRING_TYPE,"name")),ClassNode.EMPTY_ARRAY,returnS(callX(fieldX(vcsField),"getVetoableChangeListeners",args(varX("name",ClassHelper.STRING_TYPE))))));
}
| Adds the necessary field and methods to support vetoable change support. <p> Adds a new field: <code>"protected final java.beans.VetoableChangeSupport this$vetoableChangeSupport = new java.beans.VetoableChangeSupport(this)"</code> <p> Also adds support methods: <code>public void addVetoableChangeListener(java.beans.VetoableChangeListener)</code> <code>public void addVetoableChangeListener(String, java.beans.VetoableChangeListener)</code> <code>public void removeVetoableChangeListener(java.beans.VetoableChangeListener)</code> <code>public void removeVetoableChangeListener(String, java.beans.VetoableChangeListener)</code> <code>public java.beans.VetoableChangeListener[] getVetoableChangeListeners()</code> |
public static URI createURI(URI archiveFile,String entry) throws IllegalArgumentException {
URI result=URI.createHierarchicalURI("archive",archiveFile.toString() + "!",null,new String[]{entry},null,null);
return result;
}
| Creates a new archive URI that points to the given archive entry. The entry has to be a simple name, e.g. it may not contain any invalid segment characters. |
private void start(){
if (mDestinations == null || !mMapFragment.isInitialised()) {
return;
}
if (!mIsLive) {
startTracking();
}
}
| Call when the map or destinations are ready. Checks if both are initialised and calls startTracking if ready. |
public boolean isRefreshTokenRequested(){
return this.refreshTokenRequested;
}
| Get refresh token request flag |
private void proceedPrepare(){
for ( Map.Entry<UUID,Collection<UUID>> entry : txNodes.entrySet()) {
UUID nodeId=entry.getKey();
if (!nodes.containsKey(nodeId) && nodeId.equals(cctx.localNodeId())) continue;
if (failedNodeIds.contains(nodeId)) {
for ( UUID id : entry.getValue()) {
if (txNodes.containsKey(id) || id.equals(cctx.localNodeId())) continue;
MiniFuture fut=new MiniFuture(id);
add(fut);
GridCacheTxRecoveryRequest req=new GridCacheTxRecoveryRequest(tx,nodeTransactions(id),false,futureId(),fut.futureId(),tx.activeCachesDeploymentEnabled());
try {
cctx.io().send(id,req,tx.ioPolicy());
if (msgLog.isDebugEnabled()) {
msgLog.debug("Recovery fut, sent request to backup [txId=" + tx.nearXidVersion() + ", dhtTxId="+ tx.xidVersion()+ ", node="+ id+ ']');
}
}
catch ( ClusterTopologyCheckedException ignored) {
fut.onNodeLeft(id);
}
catch ( IgniteCheckedException e) {
if (msgLog.isDebugEnabled()) {
msgLog.debug("Recovery fut, failed to send request to backup [txId=" + tx.nearXidVersion() + ", dhtTxId="+ tx.xidVersion()+ ", node="+ id+ ", err="+ e+ ']');
}
fut.onError(e);
break;
}
}
}
else {
MiniFuture fut=new MiniFuture(nodeId);
add(fut);
GridCacheTxRecoveryRequest req=new GridCacheTxRecoveryRequest(tx,nodeTransactions(nodeId),false,futureId(),fut.futureId(),tx.activeCachesDeploymentEnabled());
try {
cctx.io().send(nodeId,req,tx.ioPolicy());
if (msgLog.isDebugEnabled()) {
msgLog.debug("Recovery fut, sent request to primary [txId=" + tx.nearXidVersion() + ", dhtTxId="+ tx.xidVersion()+ ", node="+ nodeId+ ']');
}
}
catch ( ClusterTopologyCheckedException ignored) {
fut.onNodeLeft(nodeId);
}
catch ( IgniteCheckedException e) {
if (msgLog.isDebugEnabled()) {
msgLog.debug("Recovery fut, failed to send request to primary [txId=" + tx.nearXidVersion() + ", dhtTxId="+ tx.xidVersion()+ ", node="+ nodeId+ ", err="+ e+ ']');
}
fut.onError(e);
break;
}
}
}
markInitialized();
}
| Process prepare after local check. |
private void validateOperatorAttribute(LogicalPlan dag,String name,int memory){
LogicalPlan.OperatorMeta oMeta=dag.getOperatorMeta(name);
Attribute.AttributeMap attrs=oMeta.getAttributes();
Assert.assertEquals((int)attrs.get(OperatorContext.MEMORY_MB),memory);
Assert.assertEquals("Application window id is 2 ",(int)attrs.get(OperatorContext.APPLICATION_WINDOW_COUNT),2);
Assert.assertEquals("Locality host is host1",attrs.get(OperatorContext.LOCALITY_HOST),"host1");
Assert.assertEquals(attrs.get(OperatorContext.PARTITIONER).getClass(),TestPartitioner.class);
Assert.assertEquals("Checkpoint window count ",(int)attrs.get(OperatorContext.CHECKPOINT_WINDOW_COUNT),120);
Assert.assertEquals("Operator is stateless ",attrs.get(OperatorContext.STATELESS),true);
Assert.assertEquals("SPIN MILLIS is set to 20 ",(int)attrs.get(OperatorContext.SPIN_MILLIS),20);
}
| Verify attributes populated on DummyOperator from Level1 module |
public static TimeOfDay hourAndMinuteFromDate(Date dateTime){
return hourAndMinuteFromDate(dateTime,null);
}
| Create a TimeOfDay from the given date (at the zero-second), in the system default TimeZone. |
private void createCache(Properties props) throws Exception {
DistributedSystem ds=getSystem(props);
assertNotNull(ds);
ds.disconnect();
ds=getSystem(props);
cache=CacheFactory.create(ds);
assertNotNull(cache);
}
| function to create cache * |
@Override public void forceRefetch(String url,WebPage page,boolean asap){
if (page.getFetchInterval() > maxInterval) page.setFetchInterval(Math.round(maxInterval * 0.9f));
page.setStatus((int)CrawlStatus.STATUS_UNFETCHED);
page.setRetriesSinceFetch(0);
page.setModifiedTime(0L);
if (asap) page.setFetchTime(System.currentTimeMillis());
}
| This method resets fetchTime, fetchInterval, modifiedTime, retriesSinceFetch and page signature, so that it forces refetching. |
public List<String> compile(File dir) throws ObjectStoreConfigException, IOException {
if (resolver == null) {
resolver=buildJavaNameResolver(pkgPrefix,memPrefix,ns,model,normalizer,cl);
}
List<String> classes=buildJavaFiles(dir);
saveConceptResources(dir);
if (!classes.isEmpty()) {
ClassPathBuilder cb=new ClassPathBuilder();
cb.append(getClass().getClassLoader()).append(cl);
List<File> classpath=cb.toFileList();
compiler.compile(classes,dir,classpath);
}
return classes;
}
| Build and compile concepts and behaivours to this directory. |
protected double lerp(double val){
return val * val * val* (val * (6f * val - 15f) + 10f);
}
| Produce a nice lerp between 0...1 |
@Override public void process(Map<K,V> tuple){
if (emitted) {
return;
}
V val=tuple.get(getKey());
if (val == null) {
return;
}
if (compareValue(val.doubleValue())) {
first.emit(cloneTuple(tuple));
emitted=true;
}
}
| Checks if required key,val pair exists in the HashMap. If so tuple is emitted, and emitted flag is set to true |
@Override protected void initData(){
this.registerReceiver();
}
| Initialize the Activity data |
public void createKinesisClient(String accessKey,String secretKey,String endPoint) throws Exception {
if (client == null) {
try {
client=new AmazonKinesisClient(new BasicAWSCredentials(accessKey,secretKey));
if (endPoint != null) {
client.setEndpoint(endPoint);
}
}
catch ( Exception e) {
throw new AmazonClientException("Unable to load credentials",e);
}
}
}
| Create the AmazonKinesisClient with the given credentials |
public static boolean assertNotNull(final Object obj){
if (obj == null) {
throw new ExamException("Is null");
}
return true;
}
| Assert that object isnt null. |
public final void testAddAllHelperTextIdsFromArray(){
CharSequence helperText1=getContext().getText(android.R.string.cancel);
CharSequence helperText2=getContext().getText(android.R.string.copy);
int[] helperTextIds=new int[2];
helperTextIds[0]=android.R.string.cancel;
helperTextIds[1]=android.R.string.copy;
PasswordEditText passwordEditText=new PasswordEditText(getContext());
passwordEditText.addAllHelperTextIds(helperTextIds);
passwordEditText.addAllHelperTextIds(helperTextIds);
Collection<CharSequence> helperTexts=passwordEditText.getHelperTexts();
assertEquals(helperTextIds.length,helperTexts.size());
Iterator<CharSequence> iterator=helperTexts.iterator();
assertEquals(helperText1,iterator.next());
assertEquals(helperText2,iterator.next());
}
| Tests the functionality of the method, which allows to add all helper texts by the ids, which are contained by an array. |
synchronized void addNamingListener(String nm,String filter,SearchControls ctls,NamingListener l) throws NamingException {
if (l instanceof ObjectChangeListener || l instanceof NamespaceChangeListener) {
NotifierArgs args=new NotifierArgs(nm,filter,ctls,l);
NamingEventNotifier notifier=notifiers.get(args);
if (notifier == null) {
notifier=new NamingEventNotifier(this,ctx,args,l);
notifiers.put(args,notifier);
}
else {
notifier.addNamingListener(l);
}
}
if (l instanceof UnsolicitedNotificationListener) {
if (unsolicited == null) {
unsolicited=new Vector<>(3);
}
unsolicited.addElement((UnsolicitedNotificationListener)l);
}
}
| Adds <tt>l</tt> to list of listeners interested in <tt>nm</tt> and filter. |
public static boolean isConfigured(){
return Logger.getRootLogger().getAllAppenders().hasMoreElements();
}
| Checks if Log4j is already configured within this VM or not. |
public static double floatToDoubleLower(float f){
if (Float.isNaN(f)) {
return Double.NaN;
}
if (Float.isInfinite(f)) {
if (f < 0) {
return Double.NEGATIVE_INFINITY;
}
else {
return Double.longBitsToDouble(0x47efffffffffffffL);
}
}
long bits=Double.doubleToRawLongBits((double)f);
if ((bits & 0x8000000000000000L) == 0) {
if (bits == 0L) {
return +0.0d;
}
if (f == Float.MIN_VALUE) {
return Double.longBitsToDouble(0x3690000000000001L);
}
if (Float.MIN_NORMAL > f) {
final long bits2=Double.doubleToRawLongBits((double)-Math.nextUp(-f));
bits=(bits >>> 1) + (bits2 >>> 1) + 1L;
}
else {
bits-=0xfffffffL;
}
return Double.longBitsToDouble(bits);
}
else {
if (bits == 0x8000000000000000L) {
return Double.longBitsToDouble(0xb690000000000000L);
}
if (f == -Float.MIN_VALUE) {
return Double.longBitsToDouble(0xb6a7ffffffffffffL);
}
if (-Float.MIN_NORMAL < f) {
final long bits2=Double.doubleToRawLongBits((double)-Math.nextUp(-f));
bits=(bits >>> 1) + (bits2 >>> 1) - 1L;
}
else {
bits+=0xfffffffL;
}
return Double.longBitsToDouble(bits);
}
}
| Return the largest double that rounds up to this float. Note: Probably not always correct - subnormal values are quite tricky. So some of the bounds might not be tight. |
@Override public void writeExternalIndexDropStmt(Table table,IIndex index,StringBuilder ddl){
ddl.append("DROP INDEX ");
printIdentifier(getIndexName(index),ddl);
printEndOfStatement(ddl);
}
| Index names in Oracle are unique to a schema and hence Oracle does not use the ON <tablename> clause |
public InterruptedNamingException(String explanation){
super(explanation);
}
| Constructs an instance of InterruptedNamingException using an explanation of the problem. All name resolution-related fields are initialized to null. |
@Override public int nextInt(){
return (int)nextLong();
}
| Generate the next item. this distribution will be skewed toward lower integers; e.g. 0 will be the most popular, 1 the next most popular, etc. |
public boolean noThrownExceptions(){
return exceptions.isEmpty();
}
| <p> noThrownExceptions </p> |
public WildcardID(String value){
assert (value != null && value.contains(WILDCARD) && value.length() < 10);
mValue=value;
try {
mPattern=Pattern.compile(value.replace(WILDCARD,REGEX_WILDCARD));
}
catch ( Exception e) {
throw new IllegalArgumentException("Invalid regex pattern for alias ID value [" + value + "]",e);
}
mWeight=calculateWeight();
}
| Wildcard identifier for matching to string identifiers containing single-character (*) wildcard values. Supports ordering from most-specific to least-specific using the build-in weighting calculation where identifier patterns containing fewer wildcards closer to the least significant digit will be weighted more heavily than identifier patterns containing more wildcards, or wildcard characters in the most significant digits. |
public boolean hasGainPercentage(){
return getGainPercentage() != null;
}
| Returns whether it has the percentage gain. |
static P11Key convertKey(Token token,Key key,String algo) throws InvalidKeyException {
return convertKey(token,key,algo,null);
}
| Convert an arbitrary key of algorithm into a P11Key of provider. Used in engineTranslateKey(), P11Cipher.init(), and P11Mac.init(). |
protected Anonymous_afterCode_1_Impl(){
super();
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public void output(OutputStream os) throws IOException, SpkacException {
OutputStreamWriter osw=null;
try {
osw=new OutputStreamWriter(os);
outputProperty(osw,SPKAC_PROPERTY,new String(Base64.encode(createSignedPublicKeyAndChallenge().getEncoded(ASN1Encoding.DER))));
outputProperty(osw,CN_PROPERTY,subject.getCN());
outputProperty(osw,OU_PROPERTY,subject.getOU());
outputProperty(osw,O_PROPERTY,subject.getO());
outputProperty(osw,L_PROPERTY,subject.getL());
outputProperty(osw,ST_PROPERTY,subject.getST());
outputProperty(osw,C_PROPERTY,subject.getC());
}
catch ( IOException ex) {
throw new SpkacException(res.getString("NoOutputSpkac.exception.message"),ex);
}
finally {
IOUtils.closeQuietly(osw);
}
}
| Output SPKAC. |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:55:22.162 -0500",hash_original_method="51201694E0EE76265BF39848EF10BE9C",hash_generated_method="49E6B3D175AEB85C0CC035D6E473FA9A") public boolean isSecure(){
return false;
}
| TCP Is not a secure protocol. |
public void appendOpenAnchorTag(String href,String style){
StringBuilder sb=new StringBuilder("<a");
if (href != null) {
sb.append(" href=\"");
sb.append(href);
sb.append("\"");
}
if (style != null) {
sb.append(" style=\"");
sb.append(style);
sb.append("\"");
}
sb.append(">");
text.append(sb.toString());
}
| Appends a tag that indicates that an anchor section begins. |
@PostMapping @ResponseBody public ResponseEntity<Response<RoleVO>> create(@RequestBody @Valid @NotNull RoleVO role,HttpServletRequest req,HttpServletResponse resp){
RoleVO createdRole=m.map(service.save(m.map(role,Role.class)),RoleVO.class);
resp.addHeader(HttpHeaders.LOCATION,getLocationForCreatedResource(req,createdRole.getId().toString()));
return buildResponse(HttpStatus.CREATED,translate(Messages.CREATED),Messages.CREATED);
}
| Documented here: https://openwms.atlassian.net/wiki/x/BIAWAQ |
@Override public void assign(String variable,String expression,Map<String,Object> transientState){
Object result=execute(expression,transientState);
state.put(variable,result);
}
| Execute an expression and assign the result to a variable. The variable is maintained in the context of this executor and is available to all subsequent expressions. |
public boolean contains(JComponent a,int b,int c){
boolean returnValue=((ComponentUI)(uis.elementAt(0))).contains(a,b,c);
for (int i=1; i < uis.size(); i++) {
((ComponentUI)(uis.elementAt(i))).contains(a,b,c);
}
return returnValue;
}
| Invokes the <code>contains</code> method on each UI handled by this object. |
public void update(byte[] input,int inOff,int length){
digest.update(input,inOff,length);
}
| update the internal digest with the byte array in |
public static KeyToken fromValues(byte[] token,byte[] address,int port){
return new KeyToken(token,address,port);
}
| Creates a new key for a token and an endpoint address. |
private void rebuild(){
List<SearchResultDataLine> existing=new ArrayList<SearchResultDataLine>(_list);
List<SearchResultDataLine> hidden=new ArrayList<SearchResultDataLine>(HIDDEN);
simpleClear();
if (isSorted()) {
for (int i=0; i < existing.size(); i++) {
addSorted(existing.get(i));
}
}
else {
for (int i=0; i < existing.size(); i++) {
add(existing.get(i));
}
}
Map<String,SearchResultDataLine> mergeMap=new HashMap<String,SearchResultDataLine>();
for (int i=0; i < hidden.size(); i++) {
SearchResultDataLine tl=hidden.get(i);
if (isSorted()) {
addSorted(tl);
}
else {
add(tl);
}
}
if (isSorted()) {
for ( SearchResultDataLine line : mergeMap.values()) addSorted(line);
}
else {
for ( SearchResultDataLine line : mergeMap.values()) add(line);
}
}
| Rebuilds the internal map to denote a new filter. |
public ScReplay createReplay(String instanceId,int expireTime) throws StorageCenterAPIException {
Parameters params=new Parameters();
params.add("description",NOTES_STRING);
params.add("expireTime",expireTime);
RestResult rr=restClient.post(String.format("StorageCenter/ScVolume/%s/CreateReplay",instanceId),params.toJson());
if (!checkResults(rr)) {
String msg=String.format("Error creating replay %s: %s",instanceId,rr.getErrorMsg());
LOG.warn(msg);
throw new StorageCenterAPIException(msg);
}
return gson.fromJson(rr.getResult(),ScReplay.class);
}
| Creates a replay on a volume. |
public <T>T read(T value,String source) throws Exception {
return read(value,source,true);
}
| This <code>read</code> method will read the contents of the XML document from the provided source and populate the object with the values deserialized. This is used as a means of injecting an object with values deserialized from an XML document. If the XML source cannot be deserialized or there is a problem building the object graph an exception is thrown. |
public static boolean isGzipRandomOutputFile(File file) throws FileNotFoundException {
return isGzipRandomOutputFile(new SeekableRandomAccessFile(file));
}
| Checks whether provided file is of type random access. |
public Animator build(){
final AnimatorSet animatorSet=getAnimatorSet();
final AnimatorSet result=animatorSet.clone();
setup(result);
return result;
}
| build a copy of given animator |
private void handleStaticStopTrees(StaticMetadata.StopTreeRequest request,TransportNetwork transportNetwork,TaskStatistics ts){
StaticMetadata staticMetadata=new StaticMetadata(request.request,transportNetwork);
if (request.request.bucket != null) {
try {
OutputStream os=StaticDataStore.getOutputStream(request.request,"query.json","application/octet-stream");
staticMetadata.writeStopTrees(os);
os.close();
}
catch ( IOException e) {
LOG.error("Error creating static stop trees",e);
}
deleteRequest(request);
}
else {
try {
PipedInputStream pis=new PipedInputStream();
PipedOutputStream pos=new PipedOutputStream(pis);
finishPriorityTask(request,pis);
staticMetadata.writeStopTrees(pos);
pos.close();
}
catch ( IOException e) {
LOG.error("Error writing static stop trees to broker",e);
}
}
}
| Produce static stop trees |
public static boolean DownloadFromUrl(String targetUrl,File file){
try {
URL url=new URL(targetUrl);
Log.d(LOG_TAG,"Download begining");
Log.d(LOG_TAG,"Download url:" + url);
Log.d(LOG_TAG,"Downloaded file name:" + file.getAbsolutePath());
URLConnection ucon=url.openConnection();
InputStream is=ucon.getInputStream();
BufferedInputStream bis=new BufferedInputStream(is);
ByteArrayBuffer baf=new ByteArrayBuffer(50);
int current=0;
while ((current=bis.read()) != -1) {
baf.append((byte)current);
}
FileOutputStream fos=new FileOutputStream(file);
fos.write(baf.toByteArray());
fos.close();
}
catch ( IOException e) {
Log.d(LOG_TAG,"Failed to download file with error: " + e);
return false;
}
return true;
}
| Download a given file from a target url to a given destination file. |
public void show(int top,int bottom,int left,int right){
Form f=Display.getInstance().getCurrent();
getUnselectedStyle().setMargin(TOP,top);
getUnselectedStyle().setMargin(BOTTOM,bottom);
getUnselectedStyle().setMargin(LEFT,left);
getUnselectedStyle().setMargin(RIGHT,right);
getUnselectedStyle().setMarginUnit(new byte[]{Style.UNIT_TYPE_PIXELS,Style.UNIT_TYPE_PIXELS,Style.UNIT_TYPE_PIXELS,Style.UNIT_TYPE_PIXELS});
getLayeredPane(f).addComponent(BorderLayout.center(this));
if (animateShow) {
int x=left + (f.getWidth() - right - left) / 2;
int y=top + (f.getHeight() - bottom - top) / 2;
setX(x);
setY(y);
setWidth(1);
setHeight(1);
getLayeredPane(f).animateLayout(400);
}
else {
getLayeredPane(f).revalidate();
}
}
| This method shows the form as a modal alert allowing us to produce a behavior of an alert/dialog box. This method will block the calling thread even if the calling thread is the EDT. Notice that this method will not release the block until dispose is called even if show() from another form is called! <p>Modal dialogs Allow the forms "content" to "hang in mid air" this is especially useful for dialogs where you would want the underlying form to "peek" from behind the form. |
public ColorStateList(int[][] states,int[] colors){
mStateSpecs=states;
mColors=colors;
if (states.length > 0) {
mDefaultColor=colors[0];
for (int i=0; i < states.length; i++) {
if (states[i].length == 0) {
mDefaultColor=colors[i];
}
}
}
}
| Creates a ColorStateList that returns the specified mapping from states to colors. |
public CUtexref(){
}
| Creates a new, uninitialized CUtexref |
private static int checkTypeArguments(final String signature,int pos){
pos=checkChar('<',signature,pos);
pos=checkTypeArgument(signature,pos);
while (getChar(signature,pos) != '>') {
pos=checkTypeArgument(signature,pos);
}
return pos + 1;
}
| Checks the type arguments in a class type signature. |
private void visitImplicitFirstFrame(){
int frameIndex=startFrame(0,descriptor.length() + 1,0);
if ((access & Opcodes.ACC_STATIC) == 0) {
if ((access & ACC_CONSTRUCTOR) == 0) {
frame[frameIndex++]=Frame.OBJECT | cw.addType(cw.thisName);
}
else {
frame[frameIndex++]=6;
}
}
int i=1;
loop: while (true) {
int j=i;
switch (descriptor.charAt(i++)) {
case 'Z':
case 'C':
case 'B':
case 'S':
case 'I':
frame[frameIndex++]=1;
break;
case 'F':
frame[frameIndex++]=2;
break;
case 'J':
frame[frameIndex++]=4;
break;
case 'D':
frame[frameIndex++]=3;
break;
case '[':
while (descriptor.charAt(i) == '[') {
++i;
}
if (descriptor.charAt(i) == 'L') {
++i;
while (descriptor.charAt(i) != ';') {
++i;
}
}
frame[frameIndex++]=Frame.OBJECT | cw.addType(descriptor.substring(j,++i));
break;
case 'L':
while (descriptor.charAt(i) != ';') {
++i;
}
frame[frameIndex++]=Frame.OBJECT | cw.addType(descriptor.substring(j + 1,i++));
break;
default :
break loop;
}
}
frame[1]=frameIndex - 3;
endFrame();
}
| Visit the implicit first frame of this method. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.