code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
protected void sendProgrammingReply(ProgListener p,int value,int status){
int delay=20;
if (!mServiceMode) {
delay=100;
}
NotifyDelay r=new NotifyDelay(delay,p,value,status);
r.start();
}
| Internal routine to forward a programing reply. This is delayed to prevent overruns of the command station. |
public Bag(){
first=null;
n=0;
}
| Initializes an empty bag. |
public boolean isSuperclassOf(ReferenceBinding otherType){
while ((otherType=otherType.superclass()) != null) {
if (otherType.isEquivalentTo(this)) return true;
}
return false;
}
| Answer true if the receiver is in the superclass hierarchy of aType NOTE: Object.isSuperclassOf(Object) -> false |
public void addPinger(Pinger pinger){
if (!mPingers.contains(pinger)) {
mPingers.add(pinger);
notifyDataSetChanged();
}
}
| Add a pinger to the list. |
void selectType(Environment env,Context ctx,int tm){
if ((left.type == Type.tString) && !right.type.isType(TC_VOID)) {
type=Type.tString;
return;
}
else if ((right.type == Type.tString) && !left.type.isType(TC_VOID)) {
type=Type.tString;
return;
}
super.selectType(env,ctx,tm);
}
| Select the type |
public BatchUpdateException(Throwable cause){
this((cause == null ? null : cause.toString()),null,0,(int[])null,cause);
}
| Constructs a <code>BatchUpdateException</code> object initialized with a given <code>cause</code>. The <code>SQLState</code> and <code>updateCounts</code> are initialized to <code>null</code> and the vendor code is initialized to 0. The <code>reason</code> is initialized to <code>null</code> if <code>cause==null</code> or to <code>cause.toString()</code> if <code>cause!=null</code>. |
public static DistinguishedNameException convertToApi(org.oscm.internal.types.exception.DistinguishedNameException oldEx){
return convertExceptionToApi(oldEx,DistinguishedNameException.class);
}
| Convert source version Exception to target version Exception |
@SuppressWarnings("unchecked") public static <K extends Comparable<? super K>,V>ImmutableSortedMap<K,V> of(K k1,V v1,K k2,V v2){
return ofEntries(entryOf(k1,v1),entryOf(k2,v2));
}
| Returns an immutable sorted map containing the given entries, sorted by the natural ordering of their keys. |
public boolean saveParameters(){
log.config("");
if (!validateParameters()) return false;
for (int i=0; i < m_mFields.size(); i++) {
WEditor editor=(WEditor)m_wEditors.get(i);
WEditor editor2=(WEditor)m_wEditors2.get(i);
Object result=editor.getValue();
Object result2=null;
if (editor2 != null) result2=editor2.getValue();
MPInstancePara para=new MPInstancePara(Env.getCtx(),m_processInfo.getAD_PInstance_ID(),i);
GridField mField=(GridField)m_mFields.get(i);
para.setParameterName(mField.getColumnName());
if (result instanceof Timestamp || result2 instanceof Timestamp) {
para.setP_Date((Timestamp)result);
if (editor2 != null && result2 != null) para.setP_Date_To((Timestamp)result2);
}
else if (result instanceof Integer || result2 instanceof Integer) {
if (result != null) {
Integer ii=(Integer)result;
para.setP_Number(ii.intValue());
}
if (editor2 != null && result2 != null) {
Integer ii=(Integer)result2;
para.setP_Number_To(ii.intValue());
}
}
else if (result instanceof BigDecimal || result2 instanceof BigDecimal) {
para.setP_Number((BigDecimal)result);
if (editor2 != null && result2 != null) para.setP_Number_To((BigDecimal)result2);
}
else if (result instanceof Boolean) {
Boolean bb=(Boolean)result;
String value=bb.booleanValue() ? "Y" : "N";
para.setP_String(value);
}
else {
if (result != null) para.setP_String(result.toString());
if (editor2 != null && result2 != null) para.setP_String_To(result2.toString());
}
para.setInfo(editor.getDisplay());
if (editor2 != null) para.setInfo_To(editor2.getDisplay());
para.saveEx();
log.fine(para.toString());
}
return true;
}
| Save Parameter values |
public TrieNode find(String suffix){
TrieNode result;
Character c;
String newSuffix;
TrieNode child;
c=suffix.charAt(0);
newSuffix=suffix.substring(1);
child=m_Children.get(c);
if (child == null) {
result=null;
}
else if (newSuffix.length() == 0) {
result=child;
}
else {
result=child.find(newSuffix);
}
return result;
}
| returns the node with the given suffix |
private void processTokenResponse(String responseCode,String result){
String refreshToken;
String accessToken;
int timeToExpireSecond;
try {
IdentityProxy identityProxy=IdentityProxy.getInstance();
if (Constants.REQUEST_SUCCESSFUL.equals(responseCode)) {
JSONObject response=new JSONObject(result);
try {
accessToken=response.getString(Constants.ACCESS_TOKEN);
refreshToken=response.getString(Constants.REFRESH_TOKEN);
timeToExpireSecond=Integer.parseInt(response.getString(Constants.EXPIRE_LABEL));
Token token=new Token();
Date date=new Date();
String currentDate=dateFormat.format(date);
token.setDate(currentDate);
token.setRefreshToken(refreshToken);
token.setAccessToken(accessToken);
token.setExpired(false);
SharedPreferences mainPref=IdentityProxy.getInstance().getContext().getSharedPreferences(Constants.APPLICATION_PACKAGE,Context.MODE_PRIVATE);
Editor editor=mainPref.edit();
editor.putString(Constants.ACCESS_TOKEN,accessToken);
editor.putString(Constants.REFRESH_TOKEN,refreshToken);
editor.putString(USERNAME_LABEL,info.getUsername());
long expiresIn=date.getTime() + (timeToExpireSecond * 1000);
Date expireDate=new Date(expiresIn);
String strDate=dateFormat.format(expireDate);
token.setDate(strDate);
editor.putString(Constants.DATE_LABEL,strDate);
editor.commit();
identityProxy.receiveAccessToken(responseCode,Constants.SUCCESS_RESPONSE,token);
}
catch ( JSONException e) {
Log.e(TAG,"Invalid JSON format",e);
}
}
else if (responseCode != null) {
if (Constants.INTERNAL_SERVER_ERROR.equals(responseCode)) {
identityProxy.receiveAccessToken(responseCode,result,null);
}
else {
JSONObject mainObject=new JSONObject(result);
String errorDescription=mainObject.getString(Constants.ERROR_DESCRIPTION_LABEL);
identityProxy.receiveAccessToken(responseCode,errorDescription,null);
}
}
}
catch ( JSONException e) {
Log.e(TAG,"Invalid JSON",e);
}
}
| Processing token response from the server. |
@Deprecated public static long checksum(final byte[] data){
return FitsCheckSum.checksum(data);
}
| calculate the checksum for the block of data |
private void grow(){
if (keys == null || nkeys >= keys.length) {
String[] nk=new String[nkeys + 4];
String[] nv=new String[nkeys + 4];
if (keys != null) System.arraycopy(keys,0,nk,0,nkeys);
if (values != null) System.arraycopy(values,0,nv,0,nkeys);
keys=nk;
values=nv;
}
}
| Grow the key/value arrays as needed |
public Analyzer showAggregate(){
showAggregate=true;
return this;
}
| Enables the output of the metric value of the aggregate approximation set, produced by merging all individual seeds. |
public static int ECHRNG(){
return 44;
}
| Channel number out of range |
public void createDecSpecificInfoDescriptor(MP4DataStream bitstream) throws IOException {
decSpecificDataOffset=bitstream.getOffset();
dsid=new byte[size];
for (int b=0; b < size; b++) {
dsid[b]=(byte)bitstream.readBytes(1);
readed++;
}
decSpecificDataSize=size - readed;
}
| Loads the MP4DecSpecificInfoDescriptor from the input bitstream. |
public AsynchronousIndexWriteConfiguration(){
}
| <strong>De-serialization ctor</strong> |
public void displayState(String state){
updateSize();
if (log.isDebugEnabled()) {
if (getSignalMast() == null) {
log.debug("Display state " + state + ", disconnected");
}
else {
log.debug("Display state " + state + " for "+ getSignalMast().getSystemName());
}
}
if (isText()) {
if (getSignalMast().getHeld()) {
if (isText()) {
super.setText(Bundle.getMessage("Held"));
}
return;
}
else if (getLitMode() && !getSignalMast().getLit()) {
super.setText(Bundle.getMessage("Dark"));
return;
}
super.setText(state);
}
if (isIcon()) {
if ((state != null) && (getSignalMast() != null)) {
String s=getSignalMast().getAppearanceMap().getImageLink(state,useIconSet);
if ((getSignalMast().getHeld()) && (getSignalMast().getAppearanceMap().getSpecificAppearance(jmri.SignalAppearanceMap.HELD) != null)) {
s=getSignalMast().getAppearanceMap().getImageLink("$held",useIconSet);
}
else if (getLitMode() && !getSignalMast().getLit() && (getSignalMast().getAppearanceMap().getImageLink("$dark",useIconSet) != null)) {
s=getSignalMast().getAppearanceMap().getImageLink("$dark",useIconSet);
}
if (s.equals("")) {
return;
}
if (!s.contains("preference:")) {
s=s.substring(s.indexOf("resources"));
}
if (_iconMap == null) {
getIcons();
}
NamedIcon n=_iconMap.get(s);
super.setIcon(n);
updateSize();
setSize(n.getIconWidth(),n.getIconHeight());
}
}
else {
super.setIcon(null);
}
return;
}
| Drive the current state of the display from the state of the underlying SignalMast object. |
private void withStaticallyMockedEnvironmentAndFileApis() throws IOException {
mockStatic(Environment.class,File.class);
when(Environment.getExternalStorageDirectory()).thenReturn(mDirectory);
when(File.createTempFile(anyString(),anyString(),eq(mDirectory))).thenReturn(mImageFile);
}
| Mock static methods in android.jar |
public static boolean isImageFileCompatible(File f){
boolean result=true;
try {
BufferedImage img=ImageIO.read(f);
ColorLayout cl=new ColorLayout();
cl.extract(img);
}
catch ( Exception e) {
result=false;
}
return result;
}
| Just opens an image with Java and reports if false if there are problems. This method can be used to check for JPG etc. that are not supported by the employed Java version. |
public <T>T read(Class<? extends T> type,Reader source,boolean strict) throws Exception {
return read(type,NodeBuilder.read(source),strict);
}
| This <code>read</code> method will read the contents of the XML document from the provided source and convert it into an object of the specified type. If the XML source cannot be deserialized or there is a problem building the object graph an exception is thrown. The instance deserialized is returned. |
public static Pointer to(float values[]){
return new Pointer(FloatBuffer.wrap(values));
}
| Creates a new Pointer to the given values. The values may not be null. |
public InvocationSequenceData(Timestamp timeStamp,long platformIdent,long sensorTypeIdent,long methodIdent){
super(timeStamp,platformIdent,sensorTypeIdent,methodIdent);
}
| Creates a new instance. |
public RedundantBranchElimination(){
super("RedundantBranchElimination",new OptimizationPlanElement[]{new OptimizationPlanAtomicElement(new EnsureSSA()),new OptimizationPlanAtomicElement(new GlobalValueNumber()),new OptimizationPlanAtomicElement(new RBE())});
}
| Create this phase element as a composite of other elements |
public void alignItemsInColumns(int columns[]){
ArrayList<Integer> rows=new ArrayList<Integer>();
for (int i=0; i < columns.length; i++) {
rows.add(columns[i]);
}
int height=-5;
int row=0, rowHeight=0, columnsOccupied=0, rowColumns;
for (int i=0; i < children_.size(); i++) {
CCMenuItem item=(CCMenuItem)children_.get(i);
assert row < rows.size() : "Too many menu items for the amount of rows/columns.";
rowColumns=rows.get(row);
assert rowColumns != 0 : "Can't have zero columns on a row";
rowHeight=(int)Math.max(rowHeight,item.getContentSize().height);
++columnsOccupied;
if (columnsOccupied >= rowColumns) {
height+=rowHeight + 5;
columnsOccupied=0;
rowHeight=0;
++row;
}
}
assert columnsOccupied != 0 : "Too many rows/columns for available menu items.";
CGSize winSize=CCDirector.sharedDirector().winSize();
row=0;
rowHeight=0;
rowColumns=0;
float w=0, x=0, y=height / 2;
for (int i=0; i < children_.size(); i++) {
CCMenuItem item=(CCMenuItem)children_.get(i);
if (rowColumns == 0) {
rowColumns=rows.get(row);
w=winSize.width / (1 + rowColumns);
x=w;
}
rowHeight=Math.max(rowHeight,(int)item.getContentSize().height);
item.setPosition(CGPoint.make(x - winSize.width / 2,y - item.getContentSize().height / 2));
x+=w + 10;
++columnsOccupied;
if (columnsOccupied >= rowColumns) {
y-=rowHeight + 5;
columnsOccupied=0;
rowColumns=0;
rowHeight=0;
++row;
}
}
}
| align items in rows of columns |
public void testUrlEncoderEncodesNonPrintableNonAsciiCharacters() throws Exception {
assertEquals("%00",URLEncoder.encode("\u0000","UTF-8"));
assertEquals("%00",URLEncoder.encode("\u0000"));
assertEquals("%E2%82%AC",URLEncoder.encode("\u20AC","UTF-8"));
assertEquals("%E2%82%AC",URLEncoder.encode("\u20AC"));
assertEquals("%F0%A0%AE%9F",URLEncoder.encode("\ud842\udf9f","UTF-8"));
assertEquals("%F0%A0%AE%9F",URLEncoder.encode("\ud842\udf9f"));
}
| Android's URLEncoder.encode() failed for surrogate pairs, encoding them as two replacement characters ("??"). http://b/3436051 |
public ServiceCall<TranslationResult> translate(final String text,final Language source,final Language target){
return translate(Collections.singletonList(text),source,target);
}
| Translate text using source and target languages.<br> |
public static void displayImage(Context context,String url,ImageView image){
ImageLoader loader=getImageLoader(context);
ImageAware imageAware=new ImageViewAware(image,false);
loader.displayImage(url,imageAware);
}
| Downloads the image for the url |
public static ImageSource resource(int resId){
return new ImageSource(resId);
}
| Create an instance from a resource. The correct resource for the device screen resolution will be used. |
public Object runSafely(Catbert.FastStack stack) throws Exception {
MediaFile mf=getMediaFile(stack);
return Boolean.valueOf(mf != null && mf.isLocalFile());
}
| Returns true if the specified MediaFile is local to this system (i.e. doesn't need to be streamed from a server) |
@SuppressWarnings("unchecked") @Override public void eSet(int featureID,Object newValue){
switch (featureID) {
case UmplePackage.AUTO_TRANSITION___AUTO_TRANSITION_BLOCK_1:
getAutoTransitionBlock_1().clear();
getAutoTransitionBlock_1().addAll((Collection<? extends AutoTransitionBlock_>)newValue);
return;
case UmplePackage.AUTO_TRANSITION___ACTIVITY_1:
getActivity_1().clear();
getActivity_1().addAll((Collection<? extends Activity_>)newValue);
return;
}
super.eSet(featureID,newValue);
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public void load(Reader reader,G g) throws IOException {
this.current_graph=g;
this.graph_factory=null;
initializeData();
clearData();
parse(reader);
}
| Populates the specified graph with the data parsed from the reader. |
public synchronized void close() throws IOException {
if (journalWriter == null) {
return;
}
for ( Entry entry : new ArrayList<Entry>(lruEntries.values())) {
if (entry.currentEditor != null) {
entry.currentEditor.abort();
}
}
trimToSize();
journalWriter.close();
journalWriter=null;
}
| Closes this cache. Stored values will remain on the filesystem. |
private void addSubCollectionField(NutchDocument doc,String url){
for ( String collname : CollectionManager.getCollectionManager(getConf()).getSubCollections(url)) {
doc.add(FIELD_NAME,collname);
}
}
| "Mark" document to be a part of subcollection |
public String toString(){
if (null != m_value) {
return (m_value.toString());
}
else if (null != m_invalidValue) {
return m_invalidValue;
}
else {
return "";
}
}
| Method toString. |
public org.apache.nutch.storage.Host.Builder clearMetadata(){
metadata=null;
fieldSetFlags()[0]=false;
return this;
}
| Clears the value of the 'metadata' field |
public String format(String str,Object... objs){
return MessageFormatter.format(str,objs).getMessage();
}
| Format an slf4j message |
private void tryToAddDataPoint(){
if (traceData.size() == traceData.getBufferSize() && plotMode == PlotMode.N_STOP) return;
switch (updateMode) {
case X_OR_Y:
if ((chronological && currentYDataChanged) || (!chronological && (currentXDataChanged || currentYDataChanged))) addDataPoint();
break;
case X_AND_Y:
if ((chronological && currentYDataChanged) || (!chronological && (currentXDataChanged && currentYDataChanged))) addDataPoint();
break;
case X:
if ((chronological && currentYDataChanged) || (!chronological && currentXDataChanged)) addDataPoint();
break;
case Y:
if (currentYDataChanged) addDataPoint();
break;
case TRIGGER:
default :
break;
}
}
| Try to add a new data point to trace data. Whether it will be added or not is up to the update mode. |
private View makeAndAddHorizontalView(int position,int offset,int x,boolean fromLeft){
View child;
if (!mDataChanged) {
child=mRecycler.get(position);
if (child != null) {
int childLeft=child.getLeft();
mRightMost=Math.max(mRightMost,childLeft + child.getMeasuredWidth());
mLeftMost=Math.min(mLeftMost,childLeft);
setUpHorizontalChild(child,offset,x,fromLeft);
return child;
}
}
child=mAdapter.getView(position,null,this);
setUpHorizontalChild(child,offset,x,fromLeft);
return child;
}
| Obtain a view, either by pulling an existing view from the recycler or by getting a new one from the adapter. If we are animating, make sure there is enough information in the view's layout parameters to animate from the old to new positions. |
public final void print(double d) throws IOException {
print(String.valueOf(d));
}
| Prints an double |
public int size(){
return nodes.size();
}
| Returns the number of nodes in this lattice. |
protected void finalize() throws Throwable {
this.systemID=null;
this.encapsulatedException=null;
super.finalize();
}
| Cleans up the object when it's destroyed. |
public void addToken(char[] array,int start,int end,int tokenType,int startOffset){
super.addToken(array,start,end,tokenType,startOffset);
zzStartRead=zzMarkedPos;
}
| Adds the token specified to the current linked list of tokens. |
public void testPing() throws Exception {
testServlet("/ping-test");
testServlet("/ping-test-URL-path");
}
| Test the ping. |
protected void releaseBeanContextResources(){
super.releaseBeanContextResources();
releaseAllDelegatedServices();
proxy=null;
}
| Called before the parent context is updated. The implementation releases any service that is currently provided by the parent context. |
public BaseCheckBox(String label){
this();
setText(label);
}
| Creates a check box with the specified text label. |
@Override public void eUnset(int featureID){
switch (featureID) {
case N4JSPackage.EXPORT_SPECIFIER__ELEMENT:
setElement((IdentifierRef)null);
return;
case N4JSPackage.EXPORT_SPECIFIER__ALIAS:
setAlias(ALIAS_EDEFAULT);
return;
}
super.eUnset(featureID);
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public Object clone(){
DefaultMutableTreeNode newNode;
try {
newNode=(DefaultMutableTreeNode)super.clone();
newNode.children=null;
newNode.parent=null;
}
catch ( CloneNotSupportedException e) {
throw new Error(e.toString());
}
return newNode;
}
| Overridden to make clone public. Returns a shallow copy of this node; the new node has no parent or children and has a reference to the same user object, if any. |
public TransactionOutput addOutput(BigInteger value,ECKey pubkey){
return addOutput(new TransactionOutput(params,this,value,pubkey));
}
| Creates an output that pays to the given pubkey directly (no address) with the given value, adds it to this transaction, and returns the new output. |
public static long index(final int segment,final int displacement){
return start(segment) + displacement;
}
| Computes the index associated with given segment and displacement. |
private void dropTables(SQLiteDatabase paramSQLiteDatabase){
for ( String table : sTables) {
try {
paramSQLiteDatabase.execSQL("DROP TABLE IF EXISTS " + table);
}
catch ( Exception localException) {
localException.printStackTrace();
}
}
}
| Goes through all of the tables in sTables and drops each table if it exists. Altered to no longer make use of reflection. |
static public void assertNotSame(Object expected,Object actual){
assertNotSame(null,expected,actual);
}
| Asserts that two objects refer to the same object. If they are not the same an AssertionFailedError is thrown. |
@Override public void process(Number tuple){
RMin.this.process(tuple);
}
| Each tuple is compared to the min and a new min (if so) is stored. |
protected Context createContext(HttpServletRequest request,HttpServletResponse response){
VelocityContext context=new VelocityContext();
context.put(REQUEST,request);
context.put(RESPONSE,response);
return context;
}
| Returns a context suitable to pass to the handleRequest() method <br><br> Default implementation will create a VelocityContext object, put the HttpServletRequest and HttpServletResponse into the context accessable via the keys VelocityServlet.REQUEST and VelocityServlet.RESPONSE, respectively. |
public static ArrayModifiableDBIDs[] partitionsFromIntegerLabels(DBIDs ids,IntegerDataStore assignment,int k){
int[] sizes=new int[k];
for (DBIDIter iter=ids.iter(); iter.valid(); iter.advance()) {
sizes[assignment.intValue(iter)]+=1;
}
ArrayModifiableDBIDs[] clusters=new ArrayModifiableDBIDs[k];
for (int i=0; i < k; i++) {
clusters[i]=DBIDUtil.newArray(sizes[i]);
}
for (DBIDIter iter=ids.iter(); iter.valid(); iter.advance()) {
clusters[assignment.intValue(iter)].add(iter);
}
return clusters;
}
| Collect clusters from their [0;k-1] integer labels. |
private static String resovlePropConfigFile(String prop){
if (prop != null && prop.startsWith("file://")) {
try {
String filePath=prop.substring(7);
BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(filePath),"UTF-8"));
StringBuffer sb=new StringBuffer();
String str=br.readLine();
while (str != null) {
sb.append(str);
str=br.readLine();
}
return sb.toString();
}
catch ( IOException e) {
System.err.println("read classpath failed!");
throw new RuntimeException(" read classpath failed ",e);
}
}
return prop;
}
| To get the full list for classpath list, Note:sometimes the classpath will be very longer, especially when you are working on a Maven project. Since if classpath too long will cause command line too long issue, we use file to handle it in this case. |
public Matrix4f translationRotateScaleInvert(Vector3fc translation,Quaternionfc quat,Vector3fc scale){
return translationRotateScaleInvert(translation.x(),translation.y(),translation.z(),quat.x(),quat.y(),quat.z(),quat.w(),scale.x(),scale.y(),scale.z());
}
| Set <code>this</code> matrix to <tt>(T * R * S)<sup>-1</sup></tt>, where <tt>T</tt> is the given <code>translation</code>, <tt>R</tt> is a rotation transformation specified by the given quaternion, and <tt>S</tt> is a scaling transformation which scales the axes by <code>scale</code>. <p> This method is equivalent to calling: <tt>translationRotateScale(...).invert()</tt> |
public String closureClassName(){
return cloClsName;
}
| Gets closure class name (applicable only for TRANSFORM operations). |
public static void charge(int slotID,IStrictEnergyStorage storer){
IInventory inv=(TileEntityContainerBlock)storer;
if (inv.getStackInSlot(slotID) != null && storer.getEnergy() > 0) {
if (inv.getStackInSlot(slotID).getItem() instanceof IEnergizedItem) {
storer.setEnergy(storer.getEnergy() - EnergizedItemManager.charge(inv.getStackInSlot(slotID),storer.getEnergy()));
}
else if (MekanismUtils.useIC2() && inv.getStackInSlot(slotID).getItem() instanceof IElectricItem) {
double sent=ElectricItem.manager.charge(inv.getStackInSlot(slotID),(int)(storer.getEnergy() * general.TO_IC2),4,true,false) * general.FROM_IC2;
storer.setEnergy(storer.getEnergy() - sent);
}
else if (MekanismUtils.useRF() && inv.getStackInSlot(slotID).getItem() instanceof IEnergyContainerItem) {
ItemStack itemStack=inv.getStackInSlot(slotID);
IEnergyContainerItem item=(IEnergyContainerItem)inv.getStackInSlot(slotID).getItem();
int itemEnergy=(int)Math.round(Math.min(Math.sqrt(item.getMaxEnergyStored(itemStack)),item.getMaxEnergyStored(itemStack) - item.getEnergyStored(itemStack)));
int toTransfer=(int)Math.round(Math.min(itemEnergy,(storer.getEnergy() * general.TO_TE)));
storer.setEnergy(storer.getEnergy() - (item.receiveEnergy(itemStack,toTransfer,false) * general.FROM_TE));
}
}
}
| Universally charges an item, and updates the TileEntity's energy level. |
public ZkBinLogStateConfig build(){
ZkBinLogStateConfig zkBinLogStateConfig=new ZkBinLogStateConfig(this);
return zkBinLogStateConfig;
}
| Build the complete object with properties that were set. |
public boolean offerFirst(E e){
addFirst(e);
return true;
}
| Inserts the specified element at the front of this deque. |
public TermNode right(){
return (TermNode)super.getRequiredProperty(Annotations.RIGHT);
}
| Returns the right term. |
private void advanceIfCurrentPieceFullyRead(){
if (currentPiece != null && currentPieceIndex == currentPieceSize) {
currentPieceOffsetInRope+=currentPieceSize;
currentPieceIndex=0;
if (pieceIterator.hasNext()) {
currentPiece=pieceIterator.next();
currentPieceSize=currentPiece.size();
}
else {
currentPiece=null;
currentPieceSize=0;
}
}
}
| Skips to the next piece if we have read all the data in the current piece. Sets currentPiece to null if we have reached the end of the input. |
private MapSettings(){
this(megamek.common.preference.PreferenceManager.getClientPreferences().getBoardWidth(),megamek.common.preference.PreferenceManager.getClientPreferences().getBoardHeight(),megamek.common.preference.PreferenceManager.getClientPreferences().getMapWidth(),megamek.common.preference.PreferenceManager.getClientPreferences().getMapHeight());
}
| Creates new MapSettings |
public void addElement(int value){
if (!m_mutable) throw new RuntimeException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_NODESETDTM_NOT_MUTABLE,null));
super.addElement(value);
}
| Append a Node onto the vector. |
public DefaultStateContext(Stage stage,Message<E> message,MessageHeaders messageHeaders,ExtendedState extendedState,Transition<S,E> transition,StateMachine<S,E> stateMachine,State<S,E> source,State<S,E> target,Exception exception){
this.stage=stage;
this.message=message;
this.messageHeaders=messageHeaders;
this.extendedState=extendedState;
this.transition=transition;
this.stateMachine=stateMachine;
this.source=source;
this.target=target;
this.exception=exception;
this.sources=null;
this.targets=null;
}
| Instantiates a new default state context. |
@Override @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public InstanceStatus modifyInstance(String instanceId,ProvisioningSettings currentSettings,ProvisioningSettings newSettings) throws APPlatformException {
LOGGER.info("modifyInstance({})",LogAndExceptionConverter.getLogText(instanceId,currentSettings));
try {
newSettings.getParameters().put(PropertyHandler.STACK_NAME,currentSettings.getParameters().get(PropertyHandler.STACK_NAME));
PropertyHandler ph=new PropertyHandler(newSettings);
ph.setState(FlowState.MODIFICATION_REQUESTED);
InstanceStatus result=new InstanceStatus();
result.setChangedParameters(newSettings.getParameters());
return result;
}
catch ( Exception t) {
throw LogAndExceptionConverter.createAndLogPlatformException(t,Context.MODIFICATION);
}
}
| Starts the modification of an application instance. <p> The internal status <code>MODIFICATION_REQUESTED</code> is stored as a controller configuration setting. It is evaluated and handled by the status dispatcher, which is invoked at regular intervals by APP through the <code>getInstanceStatus</code> method. |
public void addDisconnectedEventListener(Executor executor,PeerDisconnectedEventListener listener){
disconnectedEventListeners.add(new ListenerRegistration(listener,executor));
}
| Registers a listener that is invoked when a peer is disconnected. |
public static Object invokeMethod(Object instance,Class<?> clazz,String methodName,Object... arguments) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException {
return getMethod(clazz,methodName,DataType.getPrimitive(arguments)).invoke(instance,arguments);
}
| Invokes a method of the target class on an object with the given arguments |
@PostConstruct public void postConstruct() throws Exception {
timeStarted=System.currentTimeMillis();
dateStarted=new Date(timeStarted);
if (log.isInfoEnabled()) {
log.info("|-CMR Management Service active...");
}
}
| Is executed after dependency injection is done to perform any initialization. |
public String toXML(boolean header){
XmlTextBuilder bdr;
String tagName="Sender";
bdr=new XmlTextBuilder();
if (header) bdr.setStandardHeader();
bdr.addOpeningTag(tagName);
bdr.addSimpleElement("Id",id);
bdr.addSimpleElement("Name",name);
bdr.addSimpleElement("FirstName",firstName);
bdr.addSimpleElement("SurName",surName);
bdr.addSimpleElement("SurName2",surName2);
bdr.addSimpleElement("EMail",email);
bdr.addSimpleElement("Certificate_Issuer",certificateIssuer);
bdr.addSimpleElement("Certificate_SN",certificateSN);
bdr.addSimpleElement("InQualityOf",inQuality);
bdr.addSimpleElement("Social_Name",socialName);
bdr.addSimpleElement("CIF",CIF);
bdr.addClosingTag(tagName);
return bdr.getText();
}
| Recoge los valores de la instancia en una cadena xml |
@DELETE @Produces(MediaType.APPLICATION_JSON) @Path("/{alertId}/notifications/{notificationId}") @Description("Deletes a notification having the given ID if it is associated with the given alert ID. Associated triggers are not deleted from the alert.") public Response deleteNotificationsById(@Context HttpServletRequest req,@PathParam("alertId") BigInteger alertId,@PathParam("notificationId") BigInteger notificationId){
if (alertId == null || alertId.compareTo(BigInteger.ZERO) < 1) {
throw new WebApplicationException("Alert Id cannot be null and must be a positive non-zero number.",Status.BAD_REQUEST);
}
if (notificationId == null || notificationId.compareTo(BigInteger.ZERO) < 1) {
throw new WebApplicationException("Notification Id cannot be null and must be a positive non-zero number.",Status.BAD_REQUEST);
}
Alert alert=alertService.findAlertByPrimaryKey(alertId);
if (alert == null) {
throw new WebApplicationException(Response.Status.NOT_FOUND.getReasonPhrase(),Response.Status.NOT_FOUND);
}
validateResourceAuthorization(req,alert.getOwner(),getRemoteUser(req));
List<Notification> listNotification=new ArrayList<Notification>(alert.getNotifications());
Iterator<Notification> it=listNotification.iterator();
while (it.hasNext()) {
Notification notification=it.next();
if (notification.getId().equals(notificationId)) {
it.remove();
alert.setNotifications(listNotification);
alert.setModifiedBy(getRemoteUser(req));
alertService.updateAlert(alert);
return Response.status(Status.OK).build();
}
}
throw new WebApplicationException(Response.Status.NOT_FOUND.getReasonPhrase(),Response.Status.NOT_FOUND);
}
| Deletes the notification. |
protected static IJavaElement handleToElement(final String project,final String handle,final boolean check){
return handleToElement(null,project,handle,check);
}
| Converts an input handle back to the corresponding java element. |
public MetadataOmittedITCase(String name){
super(name);
}
| Construct a new instance of this test case. |
@Deprecated public static Header[] parseHeaders(final InputStream is) throws IOException, HttpException {
LOG.trace("enter HeaderParser.parseHeaders(InputStream, String)");
return parseHeaders(is,"US-ASCII");
}
| Parses headers from the given stream. Headers with the same name are not combined. |
public boolean containsJoint(Joint joint){
return this.joints.contains(joint);
}
| Returns true if this world contains the given joint. |
private Builder(){
super(com.wipro.ats.bdre.imcrawler.mr.Contents.SCHEMA$);
}
| Creates a new Builder |
@Override public boolean supportsCreateDB(){
return false;
}
| Indicate that MySQL can create database from the URL. |
public ByteBuffer put(int index,byte b){
byteArray.set(index,b);
return this;
}
| Write a byte to the specified index of this buffer without changing the position. |
private boolean isParentProperty(MetaProperty metaProperty){
return parentProperty != null && metaProperty.getName().equals(parentProperty);
}
| Checks if specified property is a reference to entity's parent entity. Parent entity can be specified during creating of this screen. |
public void store(String filenameToSave,String comments) throws FileNotFoundException, FileAlreadyExistsException {
if (StringUtils.isEmpty(filenameToSave)) {
throw new FileNotFoundException();
}
if (filenameToSave.equals(filename)) {
throw new FileAlreadyExistsException(filenameToSave);
}
FileWriter fileWriter=null;
BufferedWriter bufferedWriter=null;
try {
fileWriter=new FileWriter(filenameToSave,false);
bufferedWriter=new BufferedWriter(fileWriter);
prop.store(bufferedWriter,comments);
}
catch ( IOException e) {
logger.error("Fail on store properties.",e);
}
finally {
IOUtils.closeQuite(fileWriter);
IOUtils.closeQuite(bufferedWriter);
}
}
| Store current properties to file. Always overwrite. |
private void closeRemoteResources(){
if (reader != null) {
try {
reader.close();
}
catch ( final IOException ignore) {
}
reader=null;
}
if (writer != null) {
writer.close();
writer=null;
}
if (socketOutstream != null) {
try {
socketOutstream.close();
}
catch ( final IOException ignore) {
}
socketOutstream=null;
}
if (socketInstream != null) {
try {
socketInstream.close();
}
catch ( final IOException ignore) {
}
socketInstream=null;
}
if (socket != null) {
try {
socket.close();
}
catch ( final IOException ignore) {
}
socket=null;
}
}
| Safely close remote resources |
public void delete(String key){
mStorage.deleteIfExists(key);
}
| Delete saved object for given key if it is exist. |
public boolean containsFieldValues(Object[] fieldValues){
return this.contents.contains(fieldValues);
}
| Does this set contain a Struct of the correct type with the specified values? |
public RingOfLife(){
super("emerald ring","ring","emerald-ring",null);
put("amount",1);
}
| Create a RingOfLife. |
public TimeoutException(){
}
| Creates a new exception. |
private boolean processEsbSystemMonitorMessage(String payload){
boolean messageProcessed=false;
try {
sqsNotificationEventService.processSystemMonitorNotificationEvent(payload);
messageProcessed=true;
}
catch ( Exception e) {
LOGGER.debug("Failed to process message from the JMS queue for a system monitor request. jmsQueueName=\"{}\" jmsMessagePayload={}",HerdJmsDestinationResolver.SQS_DESTINATION_HERD_INCOMING,payload,e);
}
return messageProcessed;
}
| Process the message as system monitor. |
public void updateCredentials(String login,String password){
sharedPreferences.edit().putString(application.getString(R.string.shared_prefs_login),login).putString(application.getString(R.string.shared_prefs_password),password).apply();
}
| Update the login and the password in the preferences. |
public static boolean isNotEmpty(String[] array){
return array != null && array.length > 0;
}
| Indica si un array tiene valores. |
@Override public String toString(){
StringBuilder outputString=new StringBuilder();
HashSet<String> printed_keys=new HashSet<>();
for (int i=0; i < DENSE_FEATURE_NAMES.size(); i++) {
outputString.append(String.format("%s=%.3f ",DENSE_FEATURE_NAMES.get(i),getDense(i)));
printed_keys.add(DENSE_FEATURE_NAMES.get(i));
}
ArrayList<String> keys=new ArrayList<>(sparseFeatures.keySet());
Collections.sort(keys);
keys.stream().filter(null).forEach(null);
return outputString.toString().trim();
}
| Outputs a list of feature names. All dense features are printed. Feature names are printed in the order they were read in. |
public Bundler putShortArray(String key,short[] value){
bundle.putShortArray(key,value);
return this;
}
| Inserts a short array value into the mapping of this Bundle, replacing any existing value for the given key. Either key or value may be null. |
public int hashCode(){
return getName().hashCode() + 31 * mask;
}
| Returns the hash code value for this CardPermission object. |
public static Number sign(Number a){
if (isFloatingPoint(a)) {
return Math.signum(a.doubleValue());
}
else {
return Long.signum(a.longValue());
}
}
| Returns the sign of the number. |
public double[][] convertToDoubleMatrix(InputStream input,int rows,int cols) throws IOException {
double[][] ret=null;
try {
ReaderTextCell reader=(ReaderTextCell)MatrixReaderFactory.createMatrixReader(InputInfo.TextCellInputInfo);
MatrixBlock mb=reader.readMatrixFromInputStream(input,rows,cols,ConfigurationManager.getBlocksize(),ConfigurationManager.getBlocksize(),(long)rows * cols);
ret=DataConverter.convertToDoubleMatrix(mb);
}
catch ( DMLRuntimeException rex) {
throw new IOException(rex);
}
return ret;
}
| Converts an input stream of a string matrix in textcell format into a dense double array. The number of rows and columns need to be specified because textcell only represents non-zero values and hence does not define the dimensions in the general case. |
FileMenu(){
super(I18n.tr("&File"));
MENU.add(createMenuItem(new FileMenuActions.SendFileAction()));
MENU.addSeparator();
MENU.add(createMenuItem(new FileMenuActions.OpenMagnetTorrentAction()));
MENU.add(createMenuItem(new FileMenuActions.CreateTorrentAction()));
if (!OSUtils.isMacOSX()) {
MENU.addSeparator();
MENU.add(createMenuItem(new FileMenuActions.CloseAction()));
MENU.add(createMenuItem(new FileMenuActions.ExitAction()));
}
}
| Creates a new <tt>FileMenu</tt>, using the <tt>key</tt> argument for setting the locale-specific title and accessibility text. |
public static String deviceToText(int hByte,int lByte){
int mask=0x01;
int x=lByte;
StringBuilder dev=new StringBuilder();
for (int i=8; i > 0; i--) {
if ((x & mask) != 0) {
dev.append(" " + i);
}
mask=mask << 1;
}
mask=0x01;
x=hByte;
for (int i=16; i > 8; i--) {
if ((x & mask) != 0) {
dev.append(" " + i);
}
mask=mask << 1;
}
return dev.toString();
}
| Translate Device Bits to Text |
final float sloppyFreq() throws IOException {
ensureFreq();
return freq;
}
| Returns the intermediate "sloppy freq" adjusted for edit distance |
public void testNynorskStemming() throws Exception {
Reader reader=new StringReader("gut guten gutar gutane gutens gutanes");
TokenStream stream=new MockTokenizer(MockTokenizer.WHITESPACE,false);
((Tokenizer)stream).setReader(reader);
stream=tokenFilterFactory("NorwegianMinimalStem","variant","nn").create(stream);
assertTokenStreamContents(stream,new String[]{"gut","gut","gut","gut","gut","gut"});
}
| Test stemming with variant set explicitly to Nynorsk |
@Override @Inline public void processNode(ObjectReference object){
buffer.insert(object.toAddress());
}
| Enqueue an object during a trace. |
public int computePastValue(int[][][] data,int rowNumber,int columnNumber,int t){
int pastVal=0;
for (int p=0; p < k; p++) {
pastVal*=base;
pastVal+=data[t - k + 1 + p][rowNumber][columnNumber];
}
return pastVal;
}
| Utility function to compute the combined embedded past values of x up to and including time step t (i.e. (x_{t-k+1}, ... ,x_{t-1},x_{t})) where x is a time-series for a given row and column in data |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.