code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
public static boolean imp(boolean left,boolean right){
return !(left == true && right == false);
}
| Implication: The statement A IMP B is the equivalent of the logical statement "If A Then B." A IMP B is False only if A is True and B is False. It is True in all other cases. |
public static Map<String,Object> updateShoppingListQuantitiesFromOrder(DispatchContext ctx,Map<String,? extends Object> context){
Map<String,Object> result=FastMap.newInstance();
Delegator delegator=ctx.getDelegator();
String orderId=(String)context.get("orderId");
try {
List<GenericValue> orderItems=EntityQuery.use(delegator).from("OrderItem").where("orderId",orderId).queryList();
for ( GenericValue orderItem : orderItems) {
String shoppingListId=orderItem.getString("shoppingListId");
String shoppingListItemSeqId=orderItem.getString("shoppingListItemSeqId");
if (UtilValidate.isNotEmpty(shoppingListId)) {
GenericValue shoppingListItem=EntityQuery.use(delegator).from("ShoppingListItem").where("shoppingListId",shoppingListId,"shoppingListItemSeqId",shoppingListItemSeqId).queryOne();
if (shoppingListItem != null) {
BigDecimal quantityPurchased=shoppingListItem.getBigDecimal("quantityPurchased");
BigDecimal orderQuantity=orderItem.getBigDecimal("quantity");
if (quantityPurchased != null) {
shoppingListItem.set("quantityPurchased",orderQuantity.add(quantityPurchased));
}
else {
shoppingListItem.set("quantityPurchased",orderQuantity);
}
shoppingListItem.store();
}
}
}
}
catch ( Exception e) {
Debug.logInfo("updateShoppingListQuantitiesFromOrder error:" + e.getMessage(),module);
}
return result;
}
| Given an orderId, this service will look through all its OrderItems and for each shoppingListItemId and shoppingListItemSeqId, update the quantity purchased in the ShoppingListItem entity. Used for tracking how many of shopping list items are purchased. This service is mounted as a seca on storeOrder. |
public boolean hasMisfiredTriggersInState(Connection conn,String state1,long ts,int count,List<TriggerKey> resultList) throws SQLException {
PreparedStatement ps=null;
ResultSet rs=null;
try {
ps=conn.prepareStatement(rtp(SELECT_HAS_MISFIRED_TRIGGERS_IN_STATE));
ps.setBigDecimal(1,new BigDecimal(String.valueOf(ts)));
ps.setString(2,state1);
rs=ps.executeQuery();
boolean hasReachedLimit=false;
while (rs.next() && (hasReachedLimit == false)) {
if (resultList.size() == count) {
hasReachedLimit=true;
}
else {
String triggerName=rs.getString(COL_TRIGGER_NAME);
String groupName=rs.getString(COL_TRIGGER_GROUP);
resultList.add(triggerKey(triggerName,groupName));
}
}
return hasReachedLimit;
}
finally {
closeResultSet(rs);
closeStatement(ps);
}
}
| <p> Get the names of all of the triggers in the given state that have misfired - according to the given timestamp. No more than count will be returned. </p> |
public static BufferedImage loadCompatibleImage(URL resource) throws IOException {
BufferedImage image=ImageIO.read(resource);
return toCompatibleImage(image);
}
| <p>Returns a new compatible image from a URL. The image is loaded from the specified location and then turned, if necessary into a compatible image.</p> |
@NotNull static DirectionResultPair convert(@NotNull Equation<Key,Value> equation,@NotNull MessageDigest md){
ProgressManager.checkCanceled();
Result<Key,Value> rhs=equation.rhs;
HResult hResult;
if (rhs instanceof Final) {
hResult=new HFinal(((Final<Key,Value>)rhs).value);
}
else {
Pending<Key,Value> pending=(Pending<Key,Value>)rhs;
Set<Product<Key,Value>> sumOrigin=pending.sum;
HComponent[] components=new HComponent[sumOrigin.size()];
int componentI=0;
for ( Product<Key,Value> prod : sumOrigin) {
HKey[] intProd=new HKey[prod.ids.size()];
int idI=0;
for ( Key key : prod.ids) {
intProd[idI]=asmKey(key,md);
idI++;
}
HComponent intIdComponent=new HComponent(prod.value,intProd);
components[componentI]=intIdComponent;
componentI++;
}
hResult=new HPending(components);
}
return new DirectionResultPair(mkDirectionKey(equation.id.direction),hResult);
}
| Converts an equation over asm keys into equation over small hash keys. |
@Override public boolean eIsSet(int featureID){
switch (featureID) {
case OrientedPackage.COMPONENT__INPUT_COMPONET_REFS:
return inputComponetRefs != null && !inputComponetRefs.isEmpty();
case OrientedPackage.COMPONENT__OUTPUT_COMPONET_REFS:
return outputComponetRefs != null && !outputComponetRefs.isEmpty();
case OrientedPackage.COMPONENT__INPUT_PORT_REFS:
return inputPortRefs != null && !inputPortRefs.isEmpty();
case OrientedPackage.COMPONENT__OUTPUT_PORT_REFS:
return outputPortRefs != null && !outputPortRefs.isEmpty();
case OrientedPackage.COMPONENT__ID:
return ID_EDEFAULT == null ? id != null : !ID_EDEFAULT.equals(id);
case OrientedPackage.COMPONENT__INPUT_CNT:
return inputCnt != INPUT_CNT_EDEFAULT;
case OrientedPackage.COMPONENT__OUTPUT_CNT:
return outputCnt != OUTPUT_CNT_EDEFAULT;
}
return false;
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
@Override public NotificationChain eInverseRemove(InternalEObject otherEnd,int featureID,NotificationChain msgs){
switch (featureID) {
case SexecPackage.EXECUTION_NODE__REACTIONS:
return ((InternalEList<?>)getReactions()).basicRemove(otherEnd,msgs);
case SexecPackage.EXECUTION_NODE__REACT_SEQUENCE:
return basicSetReactSequence(null,msgs);
}
return super.eInverseRemove(otherEnd,featureID,msgs);
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public Matrix4x4 invert(){
final double[] tmp=new double[12];
final double[] src=new double[16];
final double[] dst=new double[16];
final double[] mat=toArray(null);
for (int i=0; i < 4; i++) {
int i4=i << 2;
src[i]=mat[i4];
src[i + 4]=mat[i4 + 1];
src[i + 8]=mat[i4 + 2];
src[i + 12]=mat[i4 + 3];
}
tmp[0]=src[10] * src[15];
tmp[1]=src[11] * src[14];
tmp[2]=src[9] * src[15];
tmp[3]=src[11] * src[13];
tmp[4]=src[9] * src[14];
tmp[5]=src[10] * src[13];
tmp[6]=src[8] * src[15];
tmp[7]=src[11] * src[12];
tmp[8]=src[8] * src[14];
tmp[9]=src[10] * src[12];
tmp[10]=src[8] * src[13];
tmp[11]=src[9] * src[12];
double src0=src[0];
double src1=src[1];
double src2=src[2];
double src3=src[3];
double src4=src[4];
double src5=src[5];
double src6=src[6];
double src7=src[7];
dst[0]=tmp[0] * src5 + tmp[3] * src6 + tmp[4] * src7;
dst[0]-=tmp[1] * src5 + tmp[2] * src6 + tmp[5] * src7;
dst[1]=tmp[1] * src4 + tmp[6] * src6 + tmp[9] * src7;
dst[1]-=tmp[0] * src4 + tmp[7] * src6 + tmp[8] * src7;
dst[2]=tmp[2] * src4 + tmp[7] * src5 + tmp[10] * src7;
dst[2]-=tmp[3] * src4 + tmp[6] * src5 + tmp[11] * src7;
dst[3]=tmp[5] * src4 + tmp[8] * src5 + tmp[11] * src6;
dst[3]-=tmp[4] * src4 + tmp[9] * src5 + tmp[10] * src6;
dst[4]=tmp[1] * src1 + tmp[2] * src2 + tmp[5] * src3;
dst[4]-=tmp[0] * src1 + tmp[3] * src2 + tmp[4] * src3;
dst[5]=tmp[0] * src0 + tmp[7] * src2 + tmp[8] * src3;
dst[5]-=tmp[1] * src0 + tmp[6] * src2 + tmp[9] * src3;
dst[6]=tmp[3] * src0 + tmp[6] * src1 + tmp[11] * src3;
dst[6]-=tmp[2] * src0 + tmp[7] * src1 + tmp[10] * src3;
dst[7]=tmp[4] * src0 + tmp[9] * src1 + tmp[10] * src2;
dst[7]-=tmp[5] * src0 + tmp[8] * src1 + tmp[11] * src2;
tmp[0]=src2 * src7;
tmp[1]=src3 * src6;
tmp[2]=src1 * src7;
tmp[3]=src3 * src5;
tmp[4]=src1 * src6;
tmp[5]=src2 * src5;
tmp[6]=src0 * src7;
tmp[7]=src3 * src4;
tmp[8]=src0 * src6;
tmp[9]=src2 * src4;
tmp[10]=src0 * src5;
tmp[11]=src1 * src4;
src0=src[8];
src1=src[9];
src2=src[10];
src3=src[11];
src4=src[12];
src5=src[13];
src6=src[14];
src7=src[15];
dst[8]=tmp[0] * src5 + tmp[3] * src6 + tmp[4] * src7;
dst[8]-=tmp[1] * src5 + tmp[2] * src6 + tmp[5] * src7;
dst[9]=tmp[1] * src4 + tmp[6] * src6 + tmp[9] * src7;
dst[9]-=tmp[0] * src4 + tmp[7] * src6 + tmp[8] * src7;
dst[10]=tmp[2] * src4 + tmp[7] * src5 + tmp[10] * src7;
dst[10]-=tmp[3] * src4 + tmp[6] * src5 + tmp[11] * src7;
dst[11]=tmp[5] * src4 + tmp[8] * src5 + tmp[11] * src6;
dst[11]-=tmp[4] * src4 + tmp[9] * src5 + tmp[10] * src6;
dst[12]=tmp[2] * src2 + tmp[5] * src3 + tmp[1] * src1;
dst[12]-=tmp[4] * src3 + tmp[0] * src1 + tmp[3] * src2;
dst[13]=tmp[8] * src3 + tmp[0] * src0 + tmp[7] * src2;
dst[13]-=tmp[6] * src2 + tmp[9] * src3 + tmp[1] * src0;
dst[14]=tmp[6] * src1 + tmp[11] * src3 + tmp[3] * src0;
dst[14]-=tmp[10] * src3 + tmp[2] * src0 + tmp[7] * src1;
dst[15]=tmp[10] * src2 + tmp[4] * src0 + tmp[9] * src1;
dst[15]-=tmp[8] * src1 + tmp[11] * src2 + tmp[5] * src0;
double det=1.0 / (src[0] * dst[0] + src[1] * dst[1] + src[2] * dst[2] + src[3] * dst[3]);
for (int i=0, k=0; i < 4; i++) {
double[] m=matrix[i];
for (int j=0; j < 4; j++) {
m[j]=dst[k++] * det;
}
}
return this;
}
| Matrix Inversion using Cramer's Method Computes Adjoint matrix divided by determinant Code modified from http://www.intel.com/design/pentiumiii/sml/24504301.pdf |
public DeletionConstraintException(){
super();
}
| Constructs a new exception with <code>null</code> as its detail message. The cause is not initialized. |
public static void verify(final ClassReader cr,final ClassLoader loader,final boolean dump,final PrintWriter pw){
ClassNode cn=new ClassNode();
cr.accept(new CheckClassAdapter(cn,false),ClassReader.SKIP_DEBUG);
Type syperType=cn.superName == null ? null : Type.getObjectType(cn.superName);
List<MethodNode> methods=cn.methods;
List<Type> interfaces=new ArrayList<Type>();
for (Iterator<String> i=cn.interfaces.iterator(); i.hasNext(); ) {
interfaces.add(Type.getObjectType(i.next()));
}
for (int i=0; i < methods.size(); ++i) {
MethodNode method=methods.get(i);
SimpleVerifier verifier=new SimpleVerifier(Type.getObjectType(cn.name),syperType,interfaces,(cn.access & Opcodes.ACC_INTERFACE) != 0);
Analyzer<BasicValue> a=new Analyzer<BasicValue>(verifier);
if (loader != null) {
verifier.setClassLoader(loader);
}
try {
a.analyze(cn.name,method);
if (!dump) {
continue;
}
}
catch ( Exception e) {
e.printStackTrace(pw);
}
printAnalyzerResult(method,a,pw);
}
pw.flush();
}
| Checks a given class. |
@Override public String toString(){
StringBuffer sb=new StringBuffer("MWMArea[").append(get_ID()).append("-").append(getName()).append("]");
return sb.toString();
}
| String representation |
public final AC fill(){
return fill(curIx);
}
| Specifies that the current row/column's component should grow by default. It does not affect the size of the row/column. <p> For a more thorough explanation of what this constraint does see the white paper or cheat Sheet at www.migcomponents.com. |
@Override public String toString(){
StringBuilder sb=new StringBuilder("TAG: Tech [");
String[] techList=getTechList();
int length=techList.length;
for (int i=0; i < length; i++) {
sb.append(techList[i]);
if (i < length - 1) {
sb.append(", ");
}
}
sb.append("]");
return sb.toString();
}
| Human-readable description of the tag, for debugging. |
public void dynamicDisplay(int col){
if (gridTab == null || !gridTab.isOpen()) {
return;
}
if (col > 0) {
GridField changedField=gridTab.getField(col);
String columnName=changedField.getColumnName();
ArrayList<?> dependants=gridTab.getDependantFields(columnName);
if (dependants.size() == 0 && changedField.getCallout().length() > 0) {
return;
}
}
boolean noData=gridTab.getRowCount() == 0;
List<WEditor> list=renderer.getEditors();
for ( WEditor comp : list) {
GridField mField=comp.getGridField();
if (mField != null && mField.getIncluded_Tab_ID() <= 0) {
if (noData) {
comp.setReadWrite(false);
}
else {
boolean rw=mField.isEditable(true);
comp.setReadWrite(rw);
comp.dynamicDisplay();
}
comp.setVisible(mField.isDisplayed(true));
comp.repaintComponent(true);
}
}
}
| Validate display properties of fields of current row |
@Override public void visitVarDef(final JCVariableDecl tree){
if (tree.mods.annotations.isEmpty()) {
}
else if (tree.sym == null) {
Assert.error("Visiting tree node before memberEnter");
}
else if (tree.sym.getKind() == ElementKind.PARAMETER) {
}
else if (tree.sym.getKind() == ElementKind.FIELD) {
if (sigOnly) {
TypeAnnotationPosition pos=new TypeAnnotationPosition();
pos.type=TargetType.FIELD;
pos.pos=tree.pos;
separateAnnotationsKinds(tree.vartype,tree.sym.type,tree.sym,pos);
}
}
else if (tree.sym.getKind() == ElementKind.LOCAL_VARIABLE) {
TypeAnnotationPosition pos=new TypeAnnotationPosition();
pos.type=TargetType.LOCAL_VARIABLE;
pos.pos=tree.pos;
pos.onLambda=currentLambda;
separateAnnotationsKinds(tree.vartype,tree.sym.type,tree.sym,pos);
}
else if (tree.sym.getKind() == ElementKind.EXCEPTION_PARAMETER) {
TypeAnnotationPosition pos=new TypeAnnotationPosition();
pos.type=TargetType.EXCEPTION_PARAMETER;
pos.pos=tree.pos;
pos.onLambda=currentLambda;
separateAnnotationsKinds(tree.vartype,tree.sym.type,tree.sym,pos);
}
else if (tree.sym.getKind() == ElementKind.RESOURCE_VARIABLE) {
TypeAnnotationPosition pos=new TypeAnnotationPosition();
pos.type=TargetType.RESOURCE_VARIABLE;
pos.pos=tree.pos;
pos.onLambda=currentLambda;
separateAnnotationsKinds(tree.vartype,tree.sym.type,tree.sym,pos);
}
else if (tree.sym.getKind() == ElementKind.ENUM_CONSTANT) {
}
else {
Assert.error("Unhandled variable kind: " + tree + " of kind: "+ tree.sym.getKind());
}
push(tree);
scan(tree.mods);
scan(tree.vartype);
if (!sigOnly) {
scan(tree.init);
}
pop();
}
| Resolve declaration vs. type annotations in variable declarations and then determine the positions. |
@Override public void validate() throws SchedulerException {
super.validate();
if (repeatInterval < 1) {
throw new SchedulerException("Repeat Interval cannot be zero.");
}
}
| <p> Validates whether the properties of the <code>JobDetail</code> are valid for submission into a <code>Scheduler</code>. |
private AlarmEvent acknowledge(AlarmPoint alarm){
AlarmStatus oldStatus=alarm.currentStatus();
if (oldStatus.name(null).equals(AlarmPoint.STATUS_DEACTIVATED)) {
AlarmStatus newStatus=createStatus(AlarmPoint.STATUS_NORMAL);
return createEvent(alarm.identity().get(),oldStatus,newStatus,AlarmPoint.EVENT_ACKNOWLEDGEMENT);
}
else if (oldStatus.name(null).equals(AlarmPoint.STATUS_ACTIVATED)) {
AlarmStatus newStatus=createStatus(AlarmPoint.STATUS_ACKNOWLEDGED);
return createEvent(alarm.identity().get(),oldStatus,newStatus,AlarmPoint.EVENT_ACKNOWLEDGEMENT);
}
return null;
}
| StateMachine change for activate trigger. |
public static ResponseData parse(String responseData){
int index=responseData.indexOf(':');
String mainData, extraData;
if (-1 == index) {
mainData=responseData;
extraData="";
}
else {
mainData=responseData.substring(0,index);
extraData=index >= responseData.length() ? "" : responseData.substring(index + 1);
}
String[] fields=TextUtils.split(mainData,Pattern.quote("|"));
if (fields.length < 6) {
throw new IllegalArgumentException();
}
ResponseData data=new ResponseData();
data.extra=extraData;
data.responseCode=Integer.parseInt(fields[0]);
data.nonce=Integer.parseInt(fields[1]);
data.packageName=fields[2];
data.versionCode=fields[3];
data.userId=fields[4];
data.timestamp=Long.parseLong(fields[5]);
return data;
}
| Parses response string into ResponseData. |
public static Toast quickToast(Context context,String message,boolean longLength){
final Toast toast;
if (longLength) {
toast=Toast.makeText(context,message,Toast.LENGTH_LONG);
}
else {
toast=Toast.makeText(context,message,Toast.LENGTH_SHORT);
}
toast.show();
return toast;
}
| Display a toast with the given message. |
public boolean isCustomer(){
Object oo=get_Value(COLUMNNAME_IsCustomer);
if (oo != null) {
if (oo instanceof Boolean) return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
| Get Customer. |
public boolean isDrawHighlightArrowEnabled(){
return mDrawHighlightArrow;
}
| returns true if drawing the highlighting arrow is enabled, false if not |
private static void initMethodHandles() throws ClassNotFoundException {
corbaStubClass=Class.forName("javax.rmi.CORBA.Stub");
try {
connectMethod=corbaStubClass.getMethod("connect",new Class<?>[]{org.omg.CORBA.ORB.class});
}
catch ( NoSuchMethodException e) {
throw new IllegalStateException("No method definition for javax.rmi.CORBA.Stub.connect(org.omg.CORBA.ORB)");
}
Class<?> proClass=Class.forName("javax.rmi.PortableRemoteObject");
try {
toStubMethod=proClass.getMethod("toStub",new Class<?>[]{java.rmi.Remote.class});
}
catch ( NoSuchMethodException e) {
throw new IllegalStateException("No method definition for javax.rmi.PortableRemoteObject.toStub(java.rmi.Remote)");
}
}
| Initializes reflection method handles for RMI-IIOP. |
@Override public boolean isActive(){
return amIActive;
}
| Used by the Whitebox GUI to tell if this plugin is still running. |
void remove(final String id){
for (Iterator i=myStack.iterator(); i.hasNext(); ) {
final WindowInfoImpl info=(WindowInfoImpl)i.next();
if (id.equals(info.getId())) {
i.remove();
}
}
}
| Removes all <code>WindowInfo</code>s with the specified <code>id</code>. |
public CDefaultState(final CStateFactory<?,?> factory){
m_factory=factory;
}
| Creates a new default state object. |
public void disallowOut(int x,int y,int width,int height){
Rectangle r=new Rectangle(x,y,width,height);
leavingBarriers.add(r);
}
| Block teleporting from a rectangular area. |
public static void main(String[] args){
if (args.length != 1) {
usage();
return;
}
long passwordLength;
try {
passwordLength=Long.parseLong(args[0]);
if (passwordLength < 1) {
printMessageAndUsage("Length has to be positive");
return;
}
}
catch ( NumberFormatException ex) {
printMessageAndUsage("Unexpected number format" + args[0]);
return;
}
new SecureRandom().ints(passwordLength,0,PASSWORD_CHARS.size()).map(null).forEach(null);
}
| The main method for the PasswordGenerator program. Run program with empty argument list to see possible arguments. |
public ServerLocatorImpl(final boolean useHA,final DiscoveryGroupConfiguration groupConfiguration){
this(new Topology(null),useHA,groupConfiguration,null);
if (useHA) {
topology.setOwner(this);
}
}
| Create a ServerLocatorImpl using UDP discovery to lookup cluster |
private void drawAllDeployment(Graphics g){
Rectangle view=g.getClipBounds();
int drawX=(view.x / (int)(HEX_WC * scale)) - 1;
int drawY=(view.y / (int)(HEX_H * scale)) - 1;
int drawWidth=(view.width / (int)(HEX_WC * scale)) + 3;
int drawHeight=(view.height / (int)(HEX_H * scale)) + 3;
IBoard board=game.getBoard();
for (int i=0; i < drawHeight; i++) {
for (int j=0; j < drawWidth; j++) {
Coords c=new Coords(j + drawX,i + drawY);
Enumeration<IPlayer> allP=game.getPlayers();
IPlayer cp;
int pCount=0;
int bThickness=1 + 10 / game.getNoOfPlayers();
while (allP.hasMoreElements()) {
cp=allP.nextElement();
if (board.isLegalDeployment(c,cp.getStartingPos())) {
Color bC=new Color(PlayerColors.getColorRGB(cp.getColorIndex()));
drawHexBorder(g,getHexLocation(c),bC,(bThickness + 2) * pCount,bThickness);
pCount++;
}
}
}
}
}
| Draw indicators for the deployment zones of all players |
public void onViewRecycled(){
}
| Called when a view created by the adapter has been recycled. |
TermVectorFilteredLeafReader(LeafReader baseLeafReader,Terms filterTerms){
super(baseLeafReader);
this.filterTerms=filterTerms;
}
| <p>Construct a FilterLeafReader based on the specified base reader. <p>Note that base reader is closed if this FilterLeafReader is closed.</p> |
private synchronized boolean containsMapping(Object key,Object value){
int hash=Collections.secondaryHash(key);
HashtableEntry<K,V>[] tab=table;
int index=hash & (tab.length - 1);
for (HashtableEntry<K,V> e=tab[index]; e != null; e=e.next) {
if (e.hash == hash && e.key.equals(key)) {
return e.value.equals(value);
}
}
return false;
}
| Returns true if this map contains the specified mapping. |
public void onSurfaceChanged(GL10 gl,int width,int height){
gl.glViewport(0,0,width,height);
float ratio=(float)width / height;
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
gl.glFrustumf(-ratio,ratio,-1,1,1,10);
}
| Update view-port with the new surface |
public static BufferedImage createColorModelCompatibleImage(BufferedImage image){
ColorModel cm=image.getColorModel();
return new BufferedImage(cm,cm.createCompatibleWritableRaster(image.getWidth(),image.getHeight()),cm.isAlphaPremultiplied(),null);
}
| <p>Returns a new <code>BufferedImage</code> using the same color model as the image passed as a parameter. The returned image is only compatible with the image passed as a parameter. This does not mean the returned image is compatible with the hardware.</p> |
@RequestMapping(value="/foos",method=RequestMethod.POST,produces=MediaType.APPLICATION_JSON_VALUE) @Timed public ResponseEntity<Foo> createFoo(@RequestBody Foo foo) throws URISyntaxException {
log.debug("REST request to save Foo : {}",foo);
if (foo.getId() != null) {
return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("foo","idexists","A new foo cannot already have an ID")).body(null);
}
Foo result=fooRepository.save(foo);
return ResponseEntity.created(new URI("/api/foos/" + result.getId())).headers(HeaderUtil.createEntityCreationAlert("foo",result.getId().toString())).body(result);
}
| POST /foos -> Create a new foo. |
public MapWidget(Context context,String rootMapFolder){
this(null,context,rootMapFolder,10);
}
| Creates instance of map widget. Zoom level will be set to 10. |
@Override public Revision next(){
try {
int revCount, articleID;
revCount=result.getInt(3);
articleID=result.getInt(5);
if (articleID != this.currentArticleID) {
this.currentRevCounter=0;
this.currentArticleID=articleID;
}
if (revCount - 1 != this.currentRevCounter) {
logger.error("\nInvalid RevCounter -" + " [ArticleId " + articleID + ", RevisionId "+ result.getInt(4)+ ", RevisionCounter "+ result.getInt(3)+ "] - Expected: "+ (this.currentRevCounter + 1));
this.currentRevCounter=revCount;
this.previousRevision=null;
return null;
}
this.currentRevCounter=revCount;
this.primaryKey=result.getInt(1);
Revision revision=new Revision(revCount);
revision.setPrimaryKey(this.primaryKey);
if (!shouldLoadRevisionText) {
String currentRevision;
Diff diff;
RevisionDecoder decoder=new RevisionDecoder(config.getCharacterSet());
if (binaryData) {
decoder.setInput(result.getBinaryStream(2),true);
}
else {
decoder.setInput(result.getString(2));
}
diff=decoder.decode();
try {
currentRevision=diff.buildRevision(previousRevision);
}
catch ( Exception e) {
this.previousRevision=null;
logger.error("Reconstruction failed -" + " [ArticleId " + result.getInt(5) + ", RevisionId "+ result.getInt(4)+ ", RevisionCounter "+ result.getInt(3)+ "]");
return null;
}
previousRevision=currentRevision;
revision.setRevisionText(currentRevision);
}
else {
if (revApi == null) {
revApi=new RevisionApi(config);
}
revision.setRevisionApi(revApi);
}
revision.setRevisionID(result.getInt(4));
revision.setArticleID(articleID);
revision.setTimeStamp(new Timestamp(result.getLong(6)));
revision.setFullRevisionID(result.getInt(7));
revision.setContributorName(result.getString(8));
revision.setContributorId(result.getInt(9));
revision.setComment(result.getString(10));
revision.setMinor(result.getBoolean(11));
revision.setContributorIsRegistered(result.getBoolean(12));
return revision;
}
catch ( DecodingException e) {
throw new RuntimeException(e);
}
catch ( SQLException e) {
throw new RuntimeException(e);
}
catch ( IOException e) {
throw new RuntimeException(e);
}
catch ( WikiApiException e) {
throw new RuntimeException(e);
}
}
| Returns the next revision. |
LineOnOtherInfo lineOnOther(DisplaySide mySide,int line){
List<LineGap> lineGaps=gapList(mySide);
int ret=Collections.binarySearch(lineGaps,new LineGap(line));
if (ret == -1) {
return new LineOnOtherInfo(line,true);
}
LineGap lookup=lineGaps.get(0 <= ret ? ret : -ret - 2);
int start=lookup.start;
int end=lookup.end;
int delta=lookup.delta;
if (start <= line && line <= end && end != -1) {
return new LineOnOtherInfo(end + delta,false);
}
return new LineOnOtherInfo(line + delta,true);
}
| Helper method to retrieve the line number on the other side. Given a line number on one side, performs a binary search in the lineMap to find the corresponding LineGap record. A LineGap records gap information from the start of an actual gap up to the start of the next gap. In the following example, lineMapAtoB will have LineGap: {start: 1, end: -1, delta: 3} (end set to -1 to represent a dummy gap of length zero. The binary search only looks at start so setting it to -1 has no effect here.) lineMapBtoA will have LineGap: {start: 1, end: 3, delta: -3} These LineGaps control lines between 1 and 5. The "delta" is computed as the number to add on our side to get the line number on the other side given a line after the actual gap, so the result will be (line + delta). All lines within the actual gap (1 to 3) are considered corresponding to the last line above the region on the other side, which is 0 in this case. For these lines, we do (end + delta). For example, to get the line number on the left corresponding to 1 on the right (lineOnOther(REVISION, 1)), the method looks up in lineMapBtoA, finds the "delta" to be -3, and returns 3 + (-3) = 0 since 1 falls in the actual gap. On the other hand, the line corresponding to 5 on the right will be 5 + (-3) = 2, since 5 is in the region after the gap (but still controlled by the current LineGap). PARENT REVISION 0 | 0 - | 1 \ \ - | 2 | Actual insertion gap | - | 3 / | Region controlled by one LineGap 1 | 4 <- delta = 4 - 1 = 3 | 2 | 5 / - | 6 ... |
public void test_GET_accessPath_delete_NothingMatched() throws Exception {
doInsertbyURL("POST",packagePath + "test_delete_by_access_path.ttl");
final long result=countResults(doGetWithAccessPath(null,null,new URIImpl("http://xmlns.com/foaf/0.1/XXX")));
assertEquals(0,result);
}
| Get using an access path which does not match anything. |
public static void assertEquals(Object expected,Object actual){
Assert.assertEquals(expected,actual);
}
| Asserts that two objects are equal. If they are not an AssertionFailedError is thrown. |
public final LC height(String height){
setHeight(ConstraintParser.parseBoundSize(height,false,false));
return this;
}
| The height for the container as a min and/or preferred and/or maximum height. The value will override any value that is set on the container itself. <p> For a more thorough explanation of what this constraint does see the white paper or cheat Sheet at www.migcontainers.com. |
public void writePathsToStream(final ObjectOutput os) throws IOException {
if ((cached_current_path != null)) {
final GeneralPath[] paths=cached_current_path.get();
int count=0;
for (int i=0; i < paths.length; i++) {
if (paths[i] == null) {
count=i;
break;
}
}
os.writeObject(count);
for (int i=0; i < count; i++) {
final PathIterator pathIterator=paths[i].getPathIterator(new AffineTransform());
PathSerializer.serializePath(os,pathIterator);
}
}
}
| method to serialize all the paths in this object. This method is needed because GeneralPath does not implement Serializable so we need to serialize it ourself. The correct usage is to first serialize this object, cached_current_path is marked as transient so it will not be serilized, this method should then be called, so the paths are serialized directly after the main object in the same ObjectOutput. NOT PART OF API and subject to change (DO NOT USE) |
@Override public boolean hasMoreElements(){
int beginpos=m_CurrentPos;
while ((beginpos < m_Str.length) && ((m_Str[beginpos] < 'a') || (m_Str[beginpos] > 'z')) && ((m_Str[beginpos] < 'A') || (m_Str[beginpos] > 'Z'))) {
beginpos++;
}
m_CurrentPos=beginpos;
if ((beginpos < m_Str.length) && (((m_Str[beginpos] >= 'a') && (m_Str[beginpos] <= 'z')) || ((m_Str[beginpos] >= 'A') && (m_Str[beginpos] <= 'Z')))) {
return true;
}
else {
return false;
}
}
| returns whether there are more elements still |
public FixedsizeForgetfulHashSet(int size,int initialCapacity,float loadFactor){
map=new FixedsizeForgetfulHashMap<E,Object>(size,initialCapacity,loadFactor);
}
| Constructs a new, empty set, using the given initialCapacity & loadFactor. |
public static <X extends Throwable>void throwIf(final X e,final Predicate<X> p){
if (p.test(e)) throw ExceptionSoftener.<RuntimeException>uncheck(e);
}
| Throw the exception as upwards if the predicate holds, otherwise do nothing |
public Table instantiate(int nrows){
Table t=new Table(nrows,m_size);
for (int i=0; i < m_size; ++i) {
t.addColumn(m_names[i],m_types[i],m_dflts[i]);
}
return t;
}
| Instantiate this schema as a new Table instance. |
public static String convertPotentialStationIDToName(String s){
try {
int x=Integer.parseInt(s);
Channel c=Wizard.getInstance().getChannelForStationID(x);
if (c != null) return c.getName();
}
catch ( NumberFormatException nfe) {
}
return s;
}
| Returns the name for a channel if the passed in String is a station ID, otherwise just return the pased in String |
public Crosshair(double value,Paint paint,Stroke stroke){
ParamChecks.nullNotPermitted(paint,"paint");
ParamChecks.nullNotPermitted(stroke,"stroke");
this.visible=true;
this.value=value;
this.paint=paint;
this.stroke=stroke;
this.labelVisible=false;
this.labelGenerator=new StandardCrosshairLabelGenerator();
this.labelAnchor=RectangleAnchor.BOTTOM_LEFT;
this.labelXOffset=3.0;
this.labelYOffset=3.0;
this.labelFont=new Font("Tahoma",Font.PLAIN,12);
this.labelPaint=Color.black;
this.labelBackgroundPaint=new Color(0,0,255,63);
this.labelOutlineVisible=true;
this.labelOutlinePaint=Color.black;
this.labelOutlineStroke=new BasicStroke(0.5f);
this.pcs=new PropertyChangeSupport(this);
}
| Creates a new crosshair value with the specified value and line style. |
public ObjectState(S id,Collection<E> deferred){
super(id,deferred);
}
| Instantiates a new object state. |
public static String readFileContent(File file) throws IOException {
byte[] b=Files.readAllBytes(file.toPath());
return new String(b,"UTF-8");
}
| Read file. |
public void insert(final Object eKey,final Object element,final int position){
_elementOrder.add(position,eKey);
_elements.put(eKey,element);
}
| Inserts element at a position. |
public ArrayTestType clone(){
ArrayTestType result=new ArrayTestType();
result.Booleans=Booleans == null ? null : Booleans.clone();
result.SBytes=SBytes == null ? null : SBytes.clone();
result.Int16s=Int16s == null ? null : Int16s.clone();
result.UInt16s=UInt16s == null ? null : UInt16s.clone();
result.Int32s=Int32s == null ? null : Int32s.clone();
result.UInt32s=UInt32s == null ? null : UInt32s.clone();
result.Int64s=Int64s == null ? null : Int64s.clone();
result.UInt64s=UInt64s == null ? null : UInt64s.clone();
result.Floats=Floats == null ? null : Floats.clone();
result.Doubles=Doubles == null ? null : Doubles.clone();
result.Strings=Strings == null ? null : Strings.clone();
result.DateTimes=DateTimes == null ? null : DateTimes.clone();
result.Guids=Guids == null ? null : Guids.clone();
result.ByteStrings=ByteStrings == null ? null : ByteStrings.clone();
result.XmlElements=XmlElements == null ? null : XmlElements.clone();
result.NodeIds=NodeIds == null ? null : NodeIds.clone();
result.ExpandedNodeIds=ExpandedNodeIds == null ? null : ExpandedNodeIds.clone();
result.StatusCodes=StatusCodes == null ? null : StatusCodes.clone();
result.DiagnosticInfos=DiagnosticInfos == null ? null : DiagnosticInfos.clone();
result.QualifiedNames=QualifiedNames == null ? null : QualifiedNames.clone();
result.LocalizedTexts=LocalizedTexts == null ? null : LocalizedTexts.clone();
result.ExtensionObjects=ExtensionObjects == null ? null : ExtensionObjects.clone();
result.DataValues=DataValues == null ? null : DataValues.clone();
result.Variants=Variants == null ? null : Variants.clone();
result.EnumeratedValues=EnumeratedValues == null ? null : EnumeratedValues.clone();
return result;
}
| Deep clone |
public String toString(){
return "TAG_Short(\"" + name + "\"): val="+ value;
}
| Debug output. (see NBT_Tag) |
public double toDouble(){
return mNumerator / (double)mDenominator;
}
| Gets the rational value as type double. Will cause a divide-by-zero error if the denominator is 0. |
@Override public synchronized CompletableFuture<Void> leave(){
if (leaveFuture != null) return leaveFuture;
leaveFuture=new CompletableFuture<>();
context.getThreadContext().executor().execute(null);
return leaveFuture.whenComplete(null);
}
| Leaves the cluster. |
private static void checkIfLootingIsRewardable(Player player,Corpse corpse,SourceObject source,Item item){
if (item.isFromCorpse()) {
if (corpse.isItemLootingRewardable()) {
source.isLootingRewardable=true;
}
else {
if (player.getName().equals(corpse.getKiller())) {
source.isLootingRewardable=true;
}
}
}
}
| Determines if looting should be logged for the player |
public ProfileVisit id(String id){
this.id=id;
return this;
}
| Sets <strong>this</strong> visits id. |
protected POInfo initPO(Properties ctx){
POInfo poi=POInfo.getPOInfo(ctx,Table_ID,get_TrxName());
return poi;
}
| Load Meta Data |
public static boolean equals(byte[][][] left,byte[][][] right){
if (left.length != right.length) {
return false;
}
boolean result=true;
for (int i=left.length - 1; i >= 0; i--) {
if (left[i].length != right[i].length) {
return false;
}
for (int j=left[i].length - 1; j >= 0; j--) {
result&=ByteUtils.equals(left[i][j],right[i][j]);
}
}
return result;
}
| Compare two three-dimensional byte arrays. No null checks are performed. |
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. |
@Override protected EClass eStaticClass(){
return UmplePackage.eINSTANCE.getLinkingOp_();
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
private void writeQNameAttribute(java.lang.String namespace,java.lang.String attName,javax.xml.namespace.QName qname,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
java.lang.String attributeNamespace=qname.getNamespaceURI();
java.lang.String attributePrefix=xmlWriter.getPrefix(attributeNamespace);
if (attributePrefix == null) {
attributePrefix=registerPrefix(xmlWriter,attributeNamespace);
}
java.lang.String attributeValue;
if (attributePrefix.trim().length() > 0) {
attributeValue=attributePrefix + ":" + qname.getLocalPart();
}
else {
attributeValue=qname.getLocalPart();
}
if (namespace.equals("")) {
xmlWriter.writeAttribute(attName,attributeValue);
}
else {
registerPrefix(xmlWriter,namespace);
xmlWriter.writeAttribute(namespace,attName,attributeValue);
}
}
| Util method to write an attribute without the ns prefix |
private void pruneScrapViews(){
final int maxViews=mActiveViews.length;
final int viewTypeCount=mViewTypeCount;
final ArrayList<View>[] scrapViews=mScrapViews;
for (int i=0; i < viewTypeCount; ++i) {
final ArrayList<View> scrapPile=scrapViews[i];
int size=scrapPile.size();
final int extras=size - maxViews;
size--;
for (int j=0; j < extras; j++) {
removeDetachedView(scrapPile.remove(size--),false);
}
}
if (mTransientStateViews != null) {
for (int i=0; i < mTransientStateViews.size(); i++) {
final View v=mTransientStateViews.valueAt(i);
if (!ViewCompat.hasTransientState(v)) {
mTransientStateViews.removeAt(i);
i--;
}
}
}
}
| Makes sure that the size of mScrapViews does not exceed the size of mActiveViews. (This can happen if an adapter does not recycle its views). |
public void readXml(java.io.InputStream iStream) throws SQLException, IOException {
if (iStream != null) {
xmlReader.readXML(this,iStream);
if (curPosBfrWrite == 0) {
this.beforeFirst();
}
else {
this.absolute(curPosBfrWrite);
}
}
else {
throw new SQLException(resBundle.handleGetObject("webrowsetimpl.invalidrd").toString());
}
}
| Reads a stream based XML input to populate this <code>WebRowSet</code> object. |
public SnackbarCombinedCallback(@Nullable SnackbarCallback snackbarCallback,@Nullable Callback callback){
super(callback);
this.snackbarCallback=snackbarCallback;
}
| Create by combining an enhanced SnackbarCallback and a standard Callback. |
private void hideNotification(){
config().getNotificationProvider().hideAllNotifications();
}
| Hiding notifications |
public static void close(@Nullable URLClassLoader clsLdr,@Nullable IgniteLogger log){
if (clsLdr != null) try {
URLClassPath path=SharedSecrets.getJavaNetAccess().getURLClassPath(clsLdr);
Field ldrFld=path.getClass().getDeclaredField("loaders");
ldrFld.setAccessible(true);
Iterable ldrs=(Iterable)ldrFld.get(path);
for ( Object ldr : ldrs) if (ldr.getClass().getName().endsWith("JarLoader")) try {
Field jarFld=ldr.getClass().getDeclaredField("jar");
jarFld.setAccessible(true);
ZipFile jar=(ZipFile)jarFld.get(ldr);
jar.close();
}
catch ( Exception e) {
warn(log,"Failed to close resource: " + e.getMessage());
}
}
catch ( Exception e) {
warn(log,"Failed to close resource: " + e.getMessage());
}
}
| Closes class loader logging possible checked exception. Note: this issue for problem <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5041014"> http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5041014</a>. |
public static int sizeOfNullableSimpleString(String str){
if (str == null) {
return DataConstants.SIZE_BOOLEAN;
}
else {
return DataConstants.SIZE_BOOLEAN + sizeOfSimpleString(str);
}
}
| Size of a String as if it was a Nullable Simple String |
public <T>T mapTo(final Class<T> mappingClass,final JBBPMapperCustomFieldProcessor customFieldProcessor){
return JBBPMapper.map(this,mappingClass,customFieldProcessor);
}
| Map the structure fields to a class fields. |
private void buildIndex(){
if (indexBuilt) return;
Collections.sort(events);
for (int i=0; i < events.size(); i++) {
SweepLineEvent ev=(SweepLineEvent)events.get(i);
if (ev.isDelete()) {
ev.getInsertEvent().setDeleteEventIndex(i);
}
}
indexBuilt=true;
}
| Because Delete Events have a link to their corresponding Insert event, it is possible to compute exactly the range of events which must be compared to a given Insert event object. |
public static byte[] decodeWebSafe(byte[] source) throws Base64DecoderException {
return decodeWebSafe(source,0,source.length);
}
| Decodes web safe Base64 content in byte array format and returns the decoded data. Web safe encoding uses '-' instead of '+', '_' instead of '/' |
protected void updateListBoxSelectionForEvent(MouseEvent anEvent,boolean shouldScroll){
Point location=anEvent.getPoint();
if (list == null) return;
int index=list.locationToIndex(location);
if (index == -1) {
if (location.y < 0) index=0;
else index=comboBox.getModel().getSize() - 1;
}
if (list.getSelectedIndex() != index) {
list.setSelectedIndex(index);
if (shouldScroll) list.ensureIndexIsVisible(index);
}
}
| A utility method used by the event listeners. Given a mouse event, it changes the list selection to the list item below the mouse. |
private static boolean hasJDK8148748SublistBug(){
String ver=System.getProperty("java.class.version","45");
if (ver != null && ver.length() >= 2) {
ver=ver.substring(0,2);
if ("52".equals(ver)) {
String s=System.getProperty(Spliterators.class.getName() + ".jre.delegation.enabled",Boolean.TRUE.toString());
return (s == null) || s.trim().equalsIgnoreCase(Boolean.TRUE.toString());
}
}
return false;
}
| The Java 8 Spliterator for ArrayList.sublist() is currently not late-binding (https://bugs.openjdk.java.net/browse/JDK-8148748). We'd get test failures because of this when we run on Java 8 with Spliterator delegation enabled. This bug has been fixed in Java 9 ea build 112, so we require this as the minimum version for test runs on Java 9 (otherwise we'd also get failures on Java 9 since we do not test for class.version 53.0 here). |
public static void f(String tag,String msg,Throwable throwable){
if (sLevel > LEVEL_FATAL) {
return;
}
Log.wtf(tag,msg,throwable);
}
| Send a FATAL ERROR log message |
@Override public void run(){
TOP: while (!shutDown) {
SystemFailure.checkFailure();
try {
connected=false;
initialized=false;
if (!shutDown) {
connectToDS();
if (isListening()) {
Assert.assertTrue(system != null);
}
return;
}
}
catch ( IncompatibleSystemException ise) {
logger.fatal(ise.getMessage(),ise);
callAlertListener(new VersionMismatchAlert(RemoteGfManagerAgent.this,ise.getMessage()));
}
catch ( Exception e) {
for (Throwable cause=e; cause != null; cause=cause.getCause()) {
if (cause instanceof InterruptedException) {
if (shutDown) {
break TOP;
}
}
if (cause instanceof AuthenticationFailedException) {
shutDown=true;
securityLogWriter.warning(LocalizedStrings.RemoteGFManagerAgent_AN_AUTHENTICATIONFAILEDEXCEPTION_WAS_CAUGHT_WHILE_CONNECTING_TO_DS,e);
break TOP;
}
}
logger.debug("[RemoteGfManagerAgent] While connecting to DS",e);
}
try {
sleep(1000);
}
catch ( InterruptedException ignore) {
}
}
connected=false;
initialized=false;
}
| Keep trying to connect to the distributed system. If we have problems connecting, the agent will not be marked as "connected". |
public void testBoundedDoubles(){
AtomicInteger fails=new AtomicInteger(0);
ThreadLocalRandom r=ThreadLocalRandom.current();
long size=456;
for (double least=0.00011; least < 1.0e20; least*=9) {
for (double bound=least * 1.0011; bound < 1.0e20; bound*=17) {
final double lo=least, hi=bound;
r.doubles(size,lo,hi).parallel().forEach(null);
}
}
assertEquals(0,fails.get());
}
| Each of a parallel sized stream of bounded doubles is within bounds |
@DSSafe(DSCat.SAFE_LIST) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-09-03 14:59:51.956 -0400",hash_original_method="336EB9AA03C5B902D3CE726BD69F433F",hash_generated_method="21B764AD8B1C1E09B98A34736C8736B1") @Override public void flush(){
}
| Flushing this writer has no effect. |
public DiskAccessException(String msg,DiskStore ds){
this(msg,null,ds);
}
| Constructs a new <code>DiskAccessException</code> with a message string. |
public void clear(){
super.clear();
while (queue.poll() != null) {
}
}
| Clears this map. |
public static void append(Path self,InputStream stream) throws IOException {
OutputStream out=Files.newOutputStream(self,CREATE,APPEND);
try {
IOGroovyMethods.leftShift(out,stream);
}
finally {
closeWithWarning(out);
}
}
| Append binary data to the file. It <strong>will not</strong> be interpreted as text. |
@Override public void clearImageCache(){
_imageResourceLoader.clear();
}
| Empties the image cache entirely. |
private boolean openForWriting(){
File root=new File(Properties.CTG_DIR);
if (root.exists()) {
if (root.isDirectory()) {
if (!root.canWrite()) {
logger.error("Cannot write in " + root.getAbsolutePath());
return false;
}
}
else {
boolean deleted=root.delete();
if (!deleted) {
logger.error("Folder " + root + " is a file, and failed to delete it");
return false;
}
else {
if (!root.mkdirs()) {
logger.error("Failed to mkdir " + root.getAbsolutePath());
return false;
}
}
}
}
else {
if (!root.mkdirs()) {
logger.error("Failed to mkdir " + root.getAbsolutePath());
return false;
}
}
File testsFolder=getBestTestFolder();
if (!testsFolder.exists()) {
if (!testsFolder.mkdirs()) {
logger.error("Failed to mkdir " + testsFolder.getAbsolutePath());
return false;
}
}
File seedFolder=getSeedInFolder();
if (!seedFolder.exists()) {
if (!seedFolder.mkdirs()) {
logger.error("Failed to mkdir " + seedFolder.getAbsolutePath());
}
}
return true;
}
| Open connection to Storage Manager Note: Here we just make sure we can write on disk |
public CircularRedirectException(String message,Throwable cause){
super(message,cause);
}
| Creates a new CircularRedirectException with the specified detail message and cause. |
public OpMapVector(int blocksize,int increaseSize,int lengthPos){
m_blocksize=increaseSize;
m_mapSize=blocksize;
m_lengthPos=lengthPos;
m_map=new int[blocksize];
}
| Construct a OpMapVector, using the given block size. |
public String update() throws Exception {
try {
LOG.info("Updating extension " + id + " to latest version...");
extensionManager.update(id);
addActionMessage(getText("admin.extension.update.success",new String[]{id}));
}
catch ( Exception e) {
LOG.error(e);
addActionWarning(getText("admin.extension.update.error",new String[]{e.getMessage()}),e);
}
return SUCCESS;
}
| Update installed extension to latest version. </br> This involves migrating all associated resource mappings over to the new version. </br> If there are no associated resource mappings, the new version can simply be installed. |
protected void deploy(HttpServletResponse response,String contextPath,String warURL) throws IOException {
String context=contextPath;
boolean error=false;
if (context == null) {
File file=new File(warURL);
String fileName=file.getName();
if (fileName.endsWith(".war")) {
fileName=fileName.substring(0,fileName.lastIndexOf(".war"));
}
context="/" + fileName;
}
if (getContextHandler(context) != null) {
sendError(response,"An application is already deployed at this context : " + context);
error=true;
}
else if (!context.startsWith("/")) {
sendError(response,"The path does not start with a forward slash");
error=true;
}
if (error) {
return;
}
else {
String webappDestLocation=webAppDirectory + context + ".war";
File webappDest=new File(webappDestLocation);
URI uri=null;
try {
uri=new URI(warURL);
}
catch ( URISyntaxException e) {
sendError(response,"Cannot parse URL " + warURL);
Log.getLogger(this.getClass()).warn(e);
return;
}
File webappSource=new File(uri);
FileInputStream fileInputStream=new FileInputStream(webappSource);
FileOutputStream fileOutputStream=new FileOutputStream(webappDest);
int i=fileInputStream.read();
while (i != -1) {
fileOutputStream.write(i);
i=fileInputStream.read();
}
fileInputStream.close();
fileOutputStream.flush();
fileOutputStream.close();
WebAppContext webappcontext=new WebAppContext();
webappcontext.setContextPath(context);
webappcontext.setWar(webappDestLocation);
chc.addHandler(webappcontext);
try {
webappcontext.start();
}
catch ( Exception e) {
sendError(response,"Unexpected error when trying to start the webapp");
Log.getLogger(this.getClass()).warn(e);
return;
}
}
sendMessage(response,"Webapp deployed at context " + contextPath);
}
| Deploy the war to the given context path. |
public AttributeDefinitionBuilder skipField(){
this.hasField=false;
return this;
}
| Causes no field to be generated. |
@Override public void chartChanged(ChartChangeEvent event){
this.flag=true;
}
| Event handler. |
public void testCreatingLauncherWithJetty1() throws Exception {
SwtBotProjectDebug.launchGWTDevModeWithJettyThenTerminateIt(bot,PROJECT_NAME);
String persistedArgs=SwtBotProjectDebug.getTheProgramArgsTextBox(bot);
assertTrue(persistedArgs.contains("com.example.project.Project"));
}
| Create launcher with clicking on the GWT Development Mode with Jetty |
public static SimpleScheduleBuilder simpleSchedule(){
return new SimpleScheduleBuilder();
}
| Create a SimpleScheduleBuilder. |
private boolean processAttributeElement(HttpMessage message,int depth,String baseURL,Element element,String attributeName){
String localURL=element.getAttributeValue(attributeName);
if (localURL == null) {
return false;
}
processURL(message,depth,localURL,baseURL);
return true;
}
| Processes the attribute with the given name of a Jericho element, for an URL. If an URL is found, notifies the listeners. |
public void test1(){
final GridLayoutManager layoutManager=new GridLayoutManager(3,1,new Insets(0,0,0,0),0,0);
final JPanel panel=new JPanel(layoutManager);
final JButton button1=new JButton();
button1.setMinimumSize(new Dimension(9,7));
button1.setPreferredSize(new Dimension(50,10));
final JButton button2=new JButton();
button2.setMinimumSize(new Dimension(15,6));
button2.setPreferredSize(new Dimension(50,10));
panel.add(button1,new GridConstraints(0,0,1,1,GridConstraints.ANCHOR_CENTER,GridConstraints.FILL_BOTH,GridConstraints.SIZEPOLICY_CAN_GROW,GridConstraints.SIZEPOLICY_CAN_SHRINK,null,null,null,0));
panel.add(button2,new GridConstraints(2,0,1,1,GridConstraints.ANCHOR_CENTER,GridConstraints.FILL_BOTH,GridConstraints.SIZEPOLICY_CAN_GROW | GridConstraints.SIZEPOLICY_CAN_SHRINK,GridConstraints.SIZEPOLICY_FIXED,null,null,null,0));
assertEquals(20,panel.getPreferredSize().height);
assertEquals(50,panel.getPreferredSize().width);
assertEquals(17,panel.getMinimumSize().height);
assertEquals(50,panel.getMinimumSize().width);
panel.setSize(new Dimension(500,100));
panel.doLayout();
assertEquals(50,button1.getHeight());
assertEquals(50,button2.getHeight());
}
| button 1 <empty> button 2 |
public static boolean logoIsLoaded(){
return logo != null;
}
| Tells if a logo has been set. |
public Path removeTrailingSeparator(){
if (!hasTrailingSeparator()) {
return this;
}
return new Path(device,segments,separators & (HAS_LEADING | IS_UNC));
}
| Returns a path with the same segments as this path but with a trailing separator removed. Does nothing if this path does not have at least one segment. The device id is preserved. <p> If this path does not have a trailing separator, this path is returned. </p> |
public void peek(ByteBuffer dst) throws BufferUnderflowException {
if (dst.remaining() > remaining()) throw new BufferUnderflowException();
peekAvailable(dst);
}
| Peeks to dst. |
private int addPayments(MDunningLevel level){
String sql="SELECT C_Payment_ID, C_Currency_ID, PayAmt," + " paymentAvailable(C_Payment_ID), C_BPartner_ID " + "FROM C_Payment_v p "+ "WHERE AD_Client_ID=?"+ " AND IsAllocated='N' AND C_BPartner_ID IS NOT NULL"+ " AND C_Charge_ID IS NULL"+ " AND DocStatus IN ('CO','CL')"+ " AND EXISTS (SELECT * FROM C_DunningLevel dl "+ "WHERE dl.C_DunningLevel_ID=?"+ " AND dl.C_Dunning_ID IN "+ "(SELECT COALESCE(bp.C_Dunning_ID, bpg.C_Dunning_ID) "+ "FROM C_BPartner bp"+ " INNER JOIN C_BP_Group bpg ON (bp.C_BP_Group_ID=bpg.C_BP_Group_ID) "+ "WHERE p.C_BPartner_ID=bp.C_BPartner_ID))";
if (p_C_BPartner_ID != 0) sql+=" AND C_BPartner_ID=?";
else if (p_C_BP_Group_ID != 0) sql+=" AND EXISTS (SELECT * FROM C_BPartner bp " + "WHERE p.C_BPartner_ID=bp.C_BPartner_ID AND bp.C_BP_Group_ID=?)";
if (!level.isStatement()) sql+=" AND C_BPartner_ID IN (SELECT C_BPartner_ID FROM C_DunningRunEntry WHERE C_DunningRun_ID=" + m_run.get_ID() + ")";
if (p_OnlySOTrx) sql+=" AND IsReceipt='Y'";
if (p_AD_Org_ID != 0) sql+=" AND p.AD_Org_ID=" + p_AD_Org_ID;
int count=0;
PreparedStatement pstmt=null;
ResultSet rs=null;
try {
pstmt=DB.prepareStatement(sql,get_TrxName());
pstmt.setInt(1,getAD_Client_ID());
pstmt.setInt(2,level.getC_DunningLevel_ID());
if (p_C_BPartner_ID != 0) pstmt.setInt(3,p_C_BPartner_ID);
else if (p_C_BP_Group_ID != 0) pstmt.setInt(3,p_C_BP_Group_ID);
rs=pstmt.executeQuery();
while (rs.next()) {
int C_Payment_ID=rs.getInt(1);
int C_Currency_ID=rs.getInt(2);
BigDecimal PayAmt=rs.getBigDecimal(3).negate();
BigDecimal OpenAmt=rs.getBigDecimal(4).negate();
int C_BPartner_ID=rs.getInt(5);
if (Env.ZERO.compareTo(OpenAmt) == 0) continue;
if (createPaymentLine(C_Payment_ID,C_Currency_ID,PayAmt,OpenAmt,C_BPartner_ID,level.getC_DunningLevel_ID())) {
count++;
}
}
}
catch ( Exception e) {
log.log(Level.SEVERE,sql,e);
getProcessInfo().addLog(getProcessInfo().getAD_PInstance_ID(),null,null,e.getLocalizedMessage());
}
finally {
DB.close(rs,pstmt);
rs=null;
pstmt=null;
}
return count;
}
| Add Payments to Run |
public static IgniteUuid randomUuid(){
return new IgniteUuid(VM_ID,cntGen.incrementAndGet());
}
| Creates new pseudo-random ID. |
public static void createTable(SQLiteDatabase db,boolean ifNotExists){
String constraint=ifNotExists ? "IF NOT EXISTS " : "";
db.execSQL("CREATE TABLE " + constraint + "'HISTORY_ENTITY' ("+ "'_id' INTEGER PRIMARY KEY ,"+ "'CALCULATE_TIME' INTEGER,"+ "'RATE' INTEGER);");
}
| Creates the underlying database table. |
public void checkRank(double value,double rank){
for ( RankedObservation observation : test.data) {
if (observation.getValue() == value) {
Assert.assertEquals(rank,observation.getRank(),Settings.EPS);
}
}
}
| Asserts that any observations in the shared test with the specified value also have the specified rank. |
protected double organizationalMeasure(Graph<V,E> g,V v){
return 1.0;
}
| A measure of the organization of individuals within the subgraph centered on <code>v</code>. Burt's text suggests that this is in some sense a measure of how "replaceable" <code>v</code> is by some other element of this subgraph. Should be a number in the closed interval [0,1]. <p>This implementation returns 1. Users may wish to override this method in order to define their own behavior. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.