code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
public static Uri importContent(String sessionId,String fileName,InputStream sourceStream) throws IOException {
String targetPath="/" + sessionId + "/upload/"+ fileName;
targetPath=createUniqueFilename(targetPath);
copyToVfs(sourceStream,targetPath);
return vfsUri(targetPath);
}
| Copy device content into vfs. All imported content is stored under /SESSION_NAME/ The original full path is retained to facilitate browsing The session content can be deleted when the session is over |
protected void cloneTo(BaseElement copy){
copy.node=node.cloneNode(true);
copy.attributes=attributes;
if (parent != null) {
copy.parent=(BaseElement)parent.clone();
copy.parent.children.remove(this);
copy.parent.children.add(copy);
}
copy.children.clear();
for ( BaseElement elem : children) {
copy.children.add((BaseElement)elem.clone());
}
}
| copy internal data structure to another one |
public void reset(){
parser.reset();
}
| Sets this parser back to the beginning of the raw data. |
protected static boolean isGet(HttpServletRequest request){
return request.getMethod().equals("GET");
}
| Checks if the given request is a GET. |
public static boolean bytesWriteObject(ActiveMQBuffer message,Object value){
if (value == null) {
throw new NullPointerException("Attempt to write a null value");
}
if (value instanceof String) {
bytesWriteUTF(message,(String)value);
}
else if (value instanceof Boolean) {
bytesWriteBoolean(message,(Boolean)value);
}
else if (value instanceof Character) {
bytesWriteChar(message,(Character)value);
}
else if (value instanceof Byte) {
bytesWriteByte(message,(Byte)value);
}
else if (value instanceof Short) {
bytesWriteShort(message,(Short)value);
}
else if (value instanceof Integer) {
bytesWriteInt(message,(Integer)value);
}
else if (value instanceof Long) {
bytesWriteLong(message,(Long)value);
}
else if (value instanceof Float) {
bytesWriteFloat(message,(Float)value);
}
else if (value instanceof Double) {
bytesWriteDouble(message,(Double)value);
}
else if (value instanceof byte[]) {
bytesWriteBytes(message,(byte[])value);
}
else {
return false;
}
return true;
}
| Returns true if it could send the Object to any known format |
private void rememberDeletedOffset(int offset){
fDeleteOffset=offset;
}
| Remembers the given offset as the deletion offset. |
@Override protected void doAction(){
BufferEntry bufferEntry=bufferSelectedEntry();
if (bufferEntry != null) {
Buffer.populate(bufferEntry);
kseFrame.updateControls(true);
}
}
| Do action. |
private void checkAxisIndices(List<Integer> indices){
if (indices == null) {
return;
}
int count=indices.size();
if (count == 0) {
throw new IllegalArgumentException("Empty list not permitted.");
}
Set<Integer> set=new HashSet<Integer>();
for ( Integer item : indices) {
if (set.contains(item)) {
throw new IllegalArgumentException("Indices must be unique.");
}
set.add(item);
}
}
| This method is used to perform argument checking on the list of axis indices passed to mapDatasetToDomainAxes() and mapDatasetToRangeAxes(). |
@Override public int hashCode(){
return Objects.hashCode(getOwnerType()) ^ Objects.hashCode(getRawType()) ^ Arrays.hashCode(getActualTypeArguments());
}
| Hash code. |
private ResultContentEvent newResultContentEvent(double[] prediction,InstanceContentEvent inEvent){
ResultContentEvent rce=new ResultContentEvent(inEvent.getInstanceIndex(),inEvent.getInstance(),inEvent.getClassId(),prediction,inEvent.isLastEvent());
rce.setClassifierIndex(this.processorId);
rce.setEvaluationIndex(inEvent.getEvaluationIndex());
return rce;
}
| Helper method to generate new ResultContentEvent based on an instance and its prediction result. |
public void addPropertiesFromString(String[] props){
try {
if (props[0].contains(":")) {
String[] split=props[0].split(":");
host=split[0];
port=new Integer(split[1]);
}
else {
host=props[0];
}
exchange=props[1];
exchangeType=props[2];
if (props[3] != null) {
routingKeys=props[3].split(":");
for ( String rKey : routingKeys) {
registry.bind(LogstreamUtil.LOG_TYPE,rKey);
}
}
}
catch ( Exception ex) {
throw new RuntimeException(ex);
}
}
| Supply the properties to the operator. The properties include hostname, exchange, exchangeType and colon separated routing keys specified in the following format hostName[:port], exchange, exchangeType, queueName, routingKey1[:routingKey2] The queue name is assumed to be same as routing key |
public boolean isNumberShared(ContactId contact){
return RcsStatus.ACTIVE.equals(getContactSharingStatus(contact));
}
| Is the number in the RCS buddy list |
private String extractJavadoc(IJavaElement element) throws CoreException {
if (element instanceof IMember) {
return JavadocContentAccess2.getHTMLContent((IMember)element,true,UrlContextProvider.get(WorkspaceIdProvider.getWorkspaceId(),element.getJavaProject().getPath().toString()));
}
else if (element instanceof IPackageDeclaration) {
return JavadocContentAccess2.getHTMLContent((IPackageDeclaration)element,UrlContextProvider.get(WorkspaceIdProvider.getWorkspaceId(),element.getJavaProject().getPath().toString()));
}
else if (element instanceof IPackageFragment) {
return JavadocContentAccess2.getHTMLContent((IPackageFragment)element,UrlContextProvider.get(WorkspaceIdProvider.getWorkspaceId(),element.getJavaProject().getPath().toString()));
}
return null;
}
| Extracts the Javadoc for the given Java element and returns it as HTML. |
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 |
public boolean voidIt(){
log.info("voidIt - " + toString());
return closeIt();
}
| Void Document. Same as Close. |
public BasicStatusLine(final ProtocolVersion version,int statusCode,final String reasonPhrase){
super();
if (version == null) {
throw new IllegalArgumentException("Protocol version may not be null.");
}
if (statusCode < 0) {
throw new IllegalArgumentException("Status code may not be negative.");
}
this.protoVersion=version;
this.statusCode=statusCode;
this.reasonPhrase=reasonPhrase;
}
| Creates a new status line with the given version, status, and reason. |
public void add(String key,String value){
if (key != null && value != null) {
Object params=urlParamsWithObjects.get(key);
if (params == null) {
params=new HashSet<String>();
this.put(key,params);
}
if (params instanceof List) {
((List<Object>)params).add(value);
}
else if (params instanceof Set) {
((Set<Object>)params).add(value);
}
}
}
| Adds string value to param which can have more than one value. |
public boolean isNavigationAtBottom(){
return (mSmallestWidthDp >= 600 || mInPortrait);
}
| Should a navigation bar appear at the bottom of the screen in the current device configuration? A navigation bar may appear on the right side of the screen in certain configurations. |
public InterfaceMaker(){
super(SOURCE);
}
| Create a new <code>InterfaceMaker</code>. A new <code>InterfaceMaker</code> object should be used for each generated interface, and should not be shared across threads. |
protected Criteria createCriteriaInternal(){
Criteria criteria=new Criteria();
return criteria;
}
| This method was generated by MyBatis Generator. This method corresponds to the database table customer |
public void initializeAtomsForDP(List<Datum> data,String filename,Random random){
omega=new ArrayList<>(K);
dof=new double[K];
beta=new double[K];
if (filename != null) {
try {
loc=BatchMixtureModel.initializeClustersFromFile(filename,K);
log.debug("loc : {}",loc);
if (loc.size() < K) {
loc=BatchMixtureModel.gonzalezInitializeMixtureCenters(loc,data,K,random);
}
}
catch ( FileNotFoundException e) {
log.debug("failed to initialized from file");
e.printStackTrace();
loc=BatchMixtureModel.gonzalezInitializeMixtureCenters(data,K,random);
}
}
else {
loc=BatchMixtureModel.gonzalezInitializeMixtureCenters(data,K,random);
}
for (int i=0; i < K; i++) {
beta[i]=1;
dof[i]=baseNu;
omega.add(0,AlgebraUtils.invertMatrix(baseOmegaInverse));
}
}
| Initializes atom (component) distributions. This method works great with DP mixture model. |
public void decayingCounters(){
if (Controller.options.LOGGING_LEVEL >= 2) {
printlnToLogWithTimePrefix("Decaying clock and decayable objects");
}
}
| This method logs when the decay organizer runs. |
public void test_GET_accessPath_delete_c() throws Exception {
if (TestMode.quads != getTestMode()) return;
doInsertbyURL("POST",packagePath + "test_delete_by_access_path.trig");
final long result=countResults(doGetWithAccessPath(null,null,null,new URIImpl("http://www.bigdata.com/")));
assertEquals(3,result);
}
| Get everything in a named graph (context). |
public Transaction intern(Transaction tx){
lock.lock();
try {
cleanPool();
Entry entry=memoryPool.get(tx.getHash());
if (entry != null) {
if (entry.tx != null) {
checkState(entry.addresses == null);
Transaction transaction=entry.tx.get();
if (transaction != null) {
tx=transaction;
}
return tx;
}
else {
checkNotNull(entry.addresses);
entry.tx=new WeakTransactionReference(tx,referenceQueue);
Set<PeerAddress> addrs=entry.addresses;
entry.addresses=null;
TransactionConfidence confidence=tx.getConfidence();
log.debug("Adding tx [{}] {} to the memory pool",confidence.numBroadcastPeers(),tx.getHashAsString());
for ( PeerAddress a : addrs) {
markBroadcast(a,tx);
}
return tx;
}
}
else {
log.debug("Provided with a downloaded transaction we didn't see announced yet: {}",tx.getHashAsString());
entry=new Entry();
entry.tx=new WeakTransactionReference(tx,referenceQueue);
memoryPool.put(tx.getHash(),entry);
return tx;
}
}
finally {
lock.unlock();
}
}
| Puts the tx into the table and returns either it, or a different Transaction object that has the same hash. Unlike seen and the other methods, this one does not imply that a tx has been announced by a peer and does not mark it as such. |
@AntDoc("A ceylon module to be compiled`") public void addConfiguredModule(Module module){
this.moduleset.addConfiguredModule(module);
}
| Adds a module to compile |
private static List<Throwable> expandFromMultiple(Throwable t){
return expandFromMultiple(t,new ArrayList<Throwable>());
}
| Expand from multi-exception wrappers. |
final public boolean isVisible(){
return isAdded() && !isHidden() && mView != null && mView.getWindowToken() != null && mView.getVisibility() == View.VISIBLE;
}
| Return true if the fragment is currently visible to the user. This means it: (1) has been added, (2) has its view attached to the window, and (3) is not hidden. |
@Bean(initMethod="start",destroyMethod="stop") @Profile(Constants.SPRING_PROFILE_DEVELOPMENT) public Server h2TCPServer() throws SQLException {
return Server.createTcpServer("-tcp","-tcpAllowOthers");
}
| Open the TCP port for the H2 database, so it is available remotely. |
public static byte[] loadVCFBytes(File vcfFile) throws FileNotFoundException, IOException {
return IOUtils.toByteArray(new FileInputStream(vcfFile));
}
| reads an extracted vcf and returns its contents as a byte array |
public static <T>void onNextDropped(T t){
}
| Take an unsignalled data and handle it. |
@Override public NotificationChain eInverseRemove(InternalEObject otherEnd,int featureID,NotificationChain msgs){
switch (featureID) {
case N4JSPackage.METHOD_DECLARATION__TYPE_VARS:
return ((InternalEList<?>)getTypeVars()).basicRemove(otherEnd,msgs);
case N4JSPackage.METHOD_DECLARATION__DECLARED_TYPE_REF:
return basicSetDeclaredTypeRef(null,msgs);
case N4JSPackage.METHOD_DECLARATION__BOGUS_TYPE_REF:
return basicSetBogusTypeRef(null,msgs);
case N4JSPackage.METHOD_DECLARATION__DECLARED_NAME:
return basicSetDeclaredName(null,msgs);
}
return super.eInverseRemove(otherEnd,featureID,msgs);
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public KeyChainGroup(NetworkParameters params){
this(params,null,new ArrayList<DeterministicKeyChain>(1),null,null);
}
| Creates a keychain group with no basic chain, and a single, lazily created HD chain. |
private void delete(Node x,Node y,Set<Node> subset,Graph graph,boolean log){
if (log) {
Edge oldEdge=graph.getEdge(x,y);
System.out.println(graph.getNumEdges() + ". DELETE " + oldEdge+ " "+ subset+ " ("+ nf.format(scoreGraph(graph).getPValue())+ ")");
}
graph.removeEdge(x,y);
for ( Node h : subset) {
if (Edges.isUndirectedEdge(graph.getEdge(x,h))) {
graph.removeEdge(x,h);
graph.addDirectedEdge(x,h);
if (log) {
Edge oldEdge=graph.getEdge(x,h);
TetradLogger.getInstance().log("directedEdges","--- Directing " + oldEdge + " to "+ graph.getEdge(x,h));
}
}
if (Edges.isUndirectedEdge(graph.getEdge(y,h))) {
graph.removeEdge(y,h);
graph.addDirectedEdge(y,h);
if (log) {
Edge oldEdge=graph.getEdge(y,h);
TetradLogger.getInstance().log("directedEdges","--- Directing " + oldEdge + " to "+ graph.getEdge(y,h));
}
}
}
}
| Do an actual deletion (Definition 13 from Chickering, 2002). |
public static byte[] decode(byte[] source,int off,int len){
int len34=len * 3 / 4;
byte[] outBuff=new byte[len34];
int outBuffPosn=0;
byte[] b4=new byte[4];
int b4Posn=0;
int i=0;
byte sbiCrop=0;
byte sbiDecode=0;
for (i=off; i < off + len; i++) {
sbiCrop=(byte)(source[i] & 0x7f);
sbiDecode=DECODABET[sbiCrop];
if (sbiDecode >= WHITE_SPACE_ENC) {
if (sbiDecode >= EQUALS_SIGN_ENC) {
b4[b4Posn++]=sbiCrop;
if (b4Posn > 3) {
outBuffPosn+=decode4to3(b4,0,outBuff,outBuffPosn);
b4Posn=0;
if (sbiCrop == EQUALS_SIGN) break;
}
}
}
else {
System.err.println("Bad Base64 input character at " + i + ": "+ source[i]+ "(decimal)");
return null;
}
}
byte[] out=new byte[outBuffPosn];
System.arraycopy(outBuff,0,out,0,outBuffPosn);
return out;
}
| Very low-level access to decoding ASCII characters in the form of a byte array. Does not support automatically gunzipping or any other "fancy" features. |
public void addFilterInfo(FilterInfo other){
if (other.cqs != null) {
if (this.cqs == null) {
this.cqs=new HashMap();
}
for ( Map.Entry<Long,Integer> entry : other.cqs.entrySet()) {
this.cqs.put(entry.getKey(),entry.getValue());
}
}
if (other.interestedClients != null) {
if (this.interestedClients == null) {
this.interestedClients=new HashSet();
}
this.interestedClients.addAll(other.interestedClients);
}
if (other.interestedClientsInv != null) {
if (this.interestedClientsInv == null) {
this.interestedClientsInv=new HashSet();
}
this.interestedClientsInv.addAll(other.interestedClientsInv);
}
}
| adds the content from another FilterInfo object. |
void reset(){
if (aadBuffer == null) {
aadBuffer=new ByteArrayOutputStream();
}
else {
aadBuffer.reset();
}
if (gctrPAndC != null) gctrPAndC.reset();
if (ghashAllToS != null) ghashAllToS.reset();
processed=0;
sizeOfAAD=0;
if (ibuffer != null) {
ibuffer.reset();
}
}
| Resets the cipher object to its original state. This is used when doFinal is called in the Cipher class, so that the cipher can be reused (with its original key and iv). |
private void addToken(int start,int end,int tokenType){
int so=start + offsetShift;
addToken(zzBuffer,start,end,tokenType,so);
}
| Adds the token specified to the current linked list of tokens. |
public final int length(){
return array.length;
}
| Returns the length of the array. |
public boolean equals(Object obj){
return (obj != null && obj instanceof MimeType && getStringValue().equals(((MimeType)obj).getStringValue()));
}
| Determine if this MIME type object is equal to the given object. The two are equal if the given object is not null, is an instance of class net.jini.print.data.MimeType, and has the same canonical form as this MIME type object (that is, has the same type, subtype, and parameters). Thus, if two MIME type objects are the same except for comments, they are considered equal. However, "text/plain" and "text/plain; charset=us-ascii" are not considered equal, even though they represent the same media type (because the default character set for plain text is US-ASCII). |
public static <T,K,V>MutableMap<K,V> toMap(Iterable<T> iterable,Function<? super T,? extends K> keyFunction,Function<? super T,? extends V> valueFunction){
return Iterate.addToMap(iterable,keyFunction,valueFunction,UnifiedMap.newMap());
}
| Iterate over the specified collection applying the specified Functions to each element to calculate a key and value, and return the results as a Map. |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-09-03 14:59:49.466 -0400",hash_original_method="32C7A1E0157D2C9087EAC41BD14B15D7",hash_generated_method="00FDB7FDFDC88CB2383D99F2E4B0637A") private boolean conditionCH0(String value,int index){
if (index != 0) {
return false;
}
else if (!contains(value,index + 1,5,"HARAC","HARIS") && !contains(value,index + 1,3,"HOR","HYM","HIA","HEM")) {
return false;
}
else if (contains(value,0,5,"CHORE")) {
return false;
}
else {
return true;
}
}
| Complex condition 0 for 'CH' |
protected static boolean isOn(String property){
return ("true,on,yes,1".indexOf(property) > -1);
}
| Tests if a string is either "true", "on", "yes" or "1" |
public PatchSetAttribute asPatchSetAttribute(RevWalk revWalk,Change change,PatchSet patchSet){
try (ReviewDb db=schema.open()){
return asPatchSetAttribute(db,revWalk,change,patchSet);
}
catch ( OrmException e) {
log.error("Cannot open database connection",e);
return new PatchSetAttribute();
}
}
| Create a PatchSetAttribute for the given patchset suitable for serialization to JSON. |
public synchronized void removeZoomListener(ZoomListener listener){
mZoomListeners.remove(listener);
}
| Removes a zoom listener. |
public static String trimAndNullIfEmpty(final String text){
String emptyStr=null;
if (null != text && !text.trim().isEmpty()) {
emptyStr=text.trim();
}
return emptyStr;
}
| Trim the text and convert into null in case of empty string. |
public final int offset(){
return _offset;
}
| Returns the relative offset of this member within its struct. |
public Xform(Integer formId,String xformXml){
this();
setFormId(formId);
setXformXml(xformXml);
setDateCreated(new Date());
setCreator(Context.getAuthenticatedUser());
}
| Creates an xform object form a formid with xforms xml. |
public void load(Element e,Object o) throws Exception {
throw new Exception("Method not coded");
}
| Create a set of configured objects from their XML description, using an auxiliary object. <P> For example, the auxilary object o might be a manager or GUI of some type that needs to be informed as each object is created. |
public void updateList(){
try {
sessions.clear();
Set<MultimediaStreamingSession> currentSessions=getMultimediaSessionApi().getStreamingSessions(StreamingSessionUtils.SERVICE_ID);
sessions=new ArrayList<>(currentSessions);
if (sessions.size() > 0) {
String[] items=new String[sessions.size()];
for (int i=0; i < items.length; i++) {
items[i]=getString(R.string.label_session,sessions.get(i).getSessionId());
}
setListAdapter(new ArrayAdapter<>(StreamingSessionList.this,android.R.layout.simple_list_item_1,items));
}
else {
setListAdapter(null);
}
}
catch ( RcsServiceException e) {
showExceptionThenExit(e);
}
}
| Update the displayed list |
public CalculatorScreen(final boolean openAPP) throws Exception {
super(null,openAPP ? SeleniumTestsContextManager.getThreadContext().getApp() : null);
}
| Opens log in page. |
private void disconnect(Throwable exception){
Connection c=Connections.getInstance(context).getConnection(clientHandle);
c.changeConnectionStatus(ConnectionStatus.DISCONNECTED);
c.addAction("Disconnect Failed - an error occured");
}
| A disconnect action was unsuccessful, notify user and update client history |
@Deprecated public static float signum(float f){
return Math.signum(f);
}
| Returns the signum function of the argument; zero if the argument is zero, 1.0f if the argument is greater than zero, -1.0f if the argument is less than zero. <p>Special Cases: <ul> <li> If the argument is NaN, then the result is NaN. <li> If the argument is positive zero or negative zero, then the result is the same as the argument. </ul> |
public void testGetScope() throws Exception {
Identity i=new IdentityStub("testGetScope");
assertNull(i.getScope());
IdentityScope s=IdentityScope.getSystemScope();
Identity i2=new IdentityStub("testGetScope2",s);
assertSame(s,i2.getScope());
}
| verify Identity.getScope() returns identity's scope |
public static String slurpURLNoExceptions(URL u){
try {
return slurpURL(u);
}
catch ( Exception e) {
e.printStackTrace();
return null;
}
}
| Returns all the text at the given URL. |
public void init(ActionListener doneAction,HashMap<String,NamedIcon> iconMap){
if (!jmri.util.ThreadingUtil.isGUIThread()) log.error("Not on GUI thread",new Exception("traceback"));
_update=true;
_supressDragging=true;
_currentIconMap=iconMap;
if (iconMap != null) {
checkCurrentMap(iconMap);
}
makeBottomPanel(doneAction);
}
| Init for update of existing track block _bottom3Panel has "Update Panel" button put into _bottom1Panel |
public static byte[] readDex(byte[] data) throws IOException {
if (data.length < 3) {
throw new IOException("File too small to be a dex/zip");
}
if ("dex".equals(new String(data,0,3,StandardCharsets.ISO_8859_1))) {
return data;
}
else if ("PK".equals(new String(data,0,2,StandardCharsets.ISO_8859_1))) {
try (ZipFile zipFile=new ZipFile(data)){
ZipEntry classes=zipFile.findFirstEntry("classes.dex");
if (classes != null) {
return toByteArray(zipFile.getInputStream(classes));
}
else {
throw new IOException("Can not find classes.dex in zip file");
}
}
}
throw new IOException("the src file not a .dex or zip file");
}
| read the dex file from byte array, if the byte array is a zip stream, it will return the content of classes.dex in the zip stream. |
public static String formatNumber(final BigDecimal number,final int fractionDigits,final boolean useGrouping){
return NumberUtil.formatNumber(number,fractionDigits,useGrouping);
}
| Formats a given number with given number of fraction digits <br> e.g. formatNumber(1000, 2, false) will return 1000.00 <br> formatNumber(1000, 2, true) will return 1,000.00 <br> |
public static NumberFormat makeNumberFormat(int digits){
switch (digits) {
case 0:
return NF0;
case 2:
return NF2;
case 3:
return NF3;
case 4:
return NF4;
case 6:
return NF6;
case 8:
return NF8;
}
final NumberFormat nf=NumberFormat.getInstance(Locale.US);
nf.setMaximumFractionDigits(digits);
nf.setMinimumFractionDigits(digits);
nf.setGroupingUsed(false);
return nf;
}
| Initialize a number format with ELKI standard options (US locale, no grouping). |
private void createReflectedImages(){
final int width=this.wrappedViewBitmap.getWidth();
final int height=this.wrappedViewBitmap.getHeight();
final Matrix matrix=new Matrix();
matrix.postScale(1,-1);
final int scaledDownHeight=(int)(height * originalScaledownFactor);
final int invertedHeight=height - scaledDownHeight - reflectionGap;
final int invertedBitmapSourceTop=scaledDownHeight - invertedHeight;
final Bitmap invertedBitmap=Bitmap.createBitmap(this.wrappedViewBitmap,0,invertedBitmapSourceTop,width,invertedHeight,matrix,true);
this.wrappedViewDrawingCanvas.drawBitmap(invertedBitmap,0,scaledDownHeight + reflectionGap,null);
final Paint paint=new Paint();
final LinearGradient shader=new LinearGradient(0,height * imageReflectionRatio + reflectionGap,0,height,0x70ffffff,0x00ffffff,Shader.TileMode.CLAMP);
paint.setShader(shader);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
this.wrappedViewDrawingCanvas.drawRect(0,height * (1 - imageReflectionRatio),width,height,paint);
}
| Creates the reflected images. |
private PrincipalUser _getJobOwner(BigInteger jobId){
Alert alert=null;
try {
alert=_alertService.findAlertByPrimaryKey(jobId);
}
catch ( Exception ex) {
}
return alert != null ? alert.getOwner() : null;
}
| Return the owner of the job. |
protected boolean beforeSave(boolean newRecord){
if (newRecord && getParent().isComplete()) {
log.saveError("ParentComplete",Msg.translate(getCtx(),"M_RequisitionLine"));
return false;
}
if (getLine() == 0) {
String sql="SELECT COALESCE(MAX(Line),0)+10 FROM M_RequisitionLine WHERE M_Requisition_ID=?";
int ii=DB.getSQLValueEx(get_TrxName(),sql,getM_Requisition_ID());
setLine(ii);
}
if (getM_Product_ID() != 0 && getC_Charge_ID() != 0) setC_Charge_ID(0);
if (getM_AttributeSetInstance_ID() != 0 && getC_Charge_ID() != 0) setM_AttributeSetInstance_ID(0);
if (getM_Product_ID() > 0 && getC_UOM_ID() <= 0) {
setC_UOM_ID(getM_Product().getC_UOM_ID());
}
if (getPriceActual().signum() == 0) setPrice();
setLineNetAmt();
return true;
}
| Before Save |
private float drawYAxisMarker(ChartValueSeries chartValueSeries,Canvas canvas,int xPosition,int yValue){
String marker=chartValueSeries.formatMarker(yValue);
Paint paint=chartValueSeries.getMarkerPaint();
Rect rect=getRect(paint,marker);
int yPosition=getY(chartValueSeries,yValue) + (int)(rect.height() / 2);
canvas.drawText(marker,xPosition,yPosition,paint);
return paint.measureText(marker);
}
| Draws a y axis marker. |
private Bitmap[] loadBitmaps(int arrayId){
int[] bitmapIds=getIntArray(arrayId);
Bitmap[] bitmaps=new Bitmap[bitmapIds.length];
for (int i=0; i < bitmapIds.length; i++) {
Drawable backgroundDrawable=mResources.getDrawable(bitmapIds[i]);
bitmaps[i]=((BitmapDrawable)backgroundDrawable).getBitmap();
}
return bitmaps;
}
| Loading all versions (interactive, ambient and low bit) into a bitmap array. The correct version will be pluck out at runtime. |
public boolean isOvershooting(){
return (mStartValue < mEndValue && getCurrentValue() > mEndValue) || (mStartValue > mEndValue && getCurrentValue() < mEndValue);
}
| Check if the spring is overshooting beyond its target. |
public static boolean boolValue(String propName,boolean dflt){
String sysProp=getProperty(propName);
return (sysProp != null && !sysProp.isEmpty()) ? Boolean.getBoolean(sysProp) : dflt;
}
| Returns boolean value from system property or provided function. |
public Object jjtAccept(SyntaxTreeBuilderVisitor visitor,Object data) throws VisitorException {
return visitor.visit(this,data);
}
| Accept the visitor. |
public ApproximationSetCollector(Algorithm algorithm,double[] epsilon){
super();
this.algorithm=algorithm;
this.epsilon=epsilon;
}
| Constructs a collector for recording approximation sets from the specified algorithm. |
public Boolean isAutoSubscribe(){
return autoSubscribe;
}
| Gets the value of the autoSubscribe property. |
public static void writeDeclaredField(final Object target,final String fieldName,final Object value,final boolean forceAccess) throws IllegalAccessException {
if (target == null) {
throw new IllegalArgumentException("target object must not be null");
}
Class<?> cls=target.getClass();
Field field=FieldUtils.getDeclaredField(cls,fieldName,forceAccess);
if (field == null) {
throw new IllegalArgumentException("Cannot locate declared field " + cls.getName() + "."+ fieldName);
}
FieldUtils.writeField(field,target,value);
}
| Write a public field. Only the specified class will be considered. |
protected int convertSizeToPowerOfTwo(int size){
if (size <= 4) return 4;
else if (size <= 8) return 8;
else if (size <= 16) return 16;
else if (size <= 32) return 32;
else if (size <= 64) return 64;
else if (size <= 128) return 128;
else if (size <= 256) return 256;
else if (size <= 512) return 512;
else if (size <= 1024) return 1024;
else return PLConstants.kTextureMaxSize;
}
| conversion methods |
public static PendingActionNotificationResponse createPendingTransferNotificationResponse(EppResource eppResource,Trid transferRequestTrid,boolean actionResult,DateTime processedDate){
assertIsContactOrDomain(eppResource);
return eppResource instanceof ContactResource ? ContactPendingActionNotificationResponse.create(eppResource.getForeignKey(),actionResult,transferRequestTrid,processedDate) : DomainPendingActionNotificationResponse.create(eppResource.getForeignKey(),actionResult,transferRequestTrid,processedDate);
}
| Create a pending action notification response indicating the resolution of a transfer. <p>The returned object will use the id and type of this resource, the trid of the resource's last transfer request, and the specified status and date. |
public boolean isProxyClass(String name){
return proxyClasses.get(name) != null;
}
| Returns <code>true</code> if the specified class is a proxy class recorded by <code>makeProxyClass()</code>. |
public void execute(TransformerImpl transformer) throws TransformerException {
try {
XPathContext xctxt=transformer.getXPathContext();
int sourceNode=xctxt.getCurrentNode();
XObject value=m_selectExpression.execute(xctxt,sourceNode,this);
SerializationHandler handler=transformer.getSerializationHandler();
if (null != value) {
int type=value.getType();
String s;
switch (type) {
case XObject.CLASS_BOOLEAN:
case XObject.CLASS_NUMBER:
case XObject.CLASS_STRING:
s=value.str();
handler.characters(s.toCharArray(),0,s.length());
break;
case XObject.CLASS_NODESET:
DTMIterator nl=value.iter();
DTMTreeWalker tw=new TreeWalker2Result(transformer,handler);
int pos;
while (DTM.NULL != (pos=nl.nextNode())) {
DTM dtm=xctxt.getDTMManager().getDTM(pos);
short t=dtm.getNodeType(pos);
if (t == DTM.DOCUMENT_NODE) {
for (int child=dtm.getFirstChild(pos); child != DTM.NULL; child=dtm.getNextSibling(child)) {
tw.traverse(child);
}
}
else if (t == DTM.ATTRIBUTE_NODE) {
SerializerUtils.addAttribute(handler,pos);
}
else {
tw.traverse(pos);
}
}
break;
case XObject.CLASS_RTREEFRAG:
SerializerUtils.outputResultTreeFragment(handler,value,transformer.getXPathContext());
break;
default :
s=value.str();
handler.characters(s.toCharArray(),0,s.length());
break;
}
}
}
catch (org.xml.sax.SAXException se) {
throw new TransformerException(se);
}
}
| The xsl:copy-of element can be used to insert a result tree fragment into the result tree, without first converting it to a string as xsl:value-of does (see [7.6.1 Generating Text with xsl:value-of]). |
private boolean recursiveExpand(TreeItem[] items,IProgressMonitor monitor,long cancelTime,int[] numItemsLeft){
boolean canceled=false;
for (int i=0; !canceled && i < items.length; i++) {
TreeItem item=items[i];
boolean visible=numItemsLeft[0]-- >= 0;
if (monitor.isCanceled() || (!visible && System.currentTimeMillis() > cancelTime)) {
canceled=true;
}
else {
Object itemData=item.getData();
if (itemData != null) {
if (!item.getExpanded()) {
FilteredTree.this.treeViewer.setExpandedState(itemData,true);
}
TreeItem[] children=item.getItems();
if (items.length > 0) {
canceled=recursiveExpand(children,monitor,cancelTime,numItemsLeft);
}
}
}
}
return canceled;
}
| Returns true if the job should be canceled (because of timeout or actual cancellation). |
public static StringConverterFactory create(){
return new StringConverterFactory();
}
| Create an instance of a simple converter factory used to convert response only for String returned object. Encoding to String will use UTF-8. |
public <T>T read(String localName,String uri,Class<T> cls) throws XMLStreamException {
return _xml.get(localName,uri,cls);
}
| Returns the object corresponding to the next nested element only if it has the specified local name and namespace URI; the actual object type is identified by the specified class parameter. |
public void snackBar(@StringRes int message,@StringRes int actionMessage,View.OnClickListener actionOnClick,int priority,boolean isDismissible){
snackBar.message(message,actionMessage,actionOnClick,priority,isDismissible,0);
}
| Adds a message to the SnackBar with all parameters except for secondsToTimeout. |
@Override protected Object executeInLock(String lockName,TransactionCallback txCallback) throws JobPersistenceException {
return executeInNonManagedTXLock(lockName,txCallback,null);
}
| Execute the given callback having optionally aquired the given lock. For <code>JobStoreTX</code>, because it manages its own transactions and only has the one datasource, this is the same behavior as executeInNonManagedTXLock(). |
public InvalidParameterException(String msg){
super(msg);
}
| Constructs an InvalidParameterException with the specified detail message. A detail message is a String that describes this particular exception. |
public final void writeUTF(String str) throws IOException {
writeUTF(str,this);
}
| Writes a string to the underlying output stream using <a href="DataInput.html#modified-utf-8">modified UTF-8</a> encoding in a machine-independent manner. <p> First, two bytes are written to the output stream as if by the <code>writeShort</code> method giving the number of bytes to follow. This value is the number of bytes actually written out, not the length of the string. Following the length, each character of the string is output, in sequence, using the modified UTF-8 encoding for the character. If no exception is thrown, the counter <code>written</code> is incremented by the total number of bytes written to the output stream. This will be at least two plus the length of <code>str</code>, and at most two plus thrice the length of <code>str</code>. |
public static final double[] minusEquals(final double[] v1,final double[] v2){
assert (v1.length == v2.length) : ERR_VEC_DIMENSIONS;
for (int i=0; i < v1.length; i++) {
v1[i]-=v2[i];
}
return v1;
}
| Computes v1 = v1 - v2, overwriting v1 |
private void updateProgress(int progress){
if (myHost != null && progress != previousProgress) {
myHost.updateProgress(progress);
}
previousProgress=progress;
}
| Used to communicate a progress update between a plugin tool and the main Whitebox user interface. |
private static void checkLineFeed(final InputStream input,final ByteArrayOutputStream baos,final Integer position) throws IOException {
if (input.read() != '\n') {
throw new HttpException(HttpURLConnection.HTTP_BAD_REQUEST,String.format("there is no LF after CR in header, line #%d: \"%s\"",position,new Utf8String(baos.toByteArray()).string()));
}
}
| Checks whether or not the next byte to read is a Line Feed. <p><i>Please note that this method assumes that the previous byte read was a Carriage Return.</i> |
protected boolean needsPropertyChangeSupport(ClassNode declaringClass,SourceUnit sourceUnit){
boolean foundAdd=false, foundRemove=false, foundFire=false;
ClassNode consideredClass=declaringClass;
while (consideredClass != null) {
for ( MethodNode method : consideredClass.getMethods()) {
foundAdd=foundAdd || method.getName().equals("addPropertyChangeListener") && method.getParameters().length == 1;
foundRemove=foundRemove || method.getName().equals("removePropertyChangeListener") && method.getParameters().length == 1;
foundFire=foundFire || method.getName().equals("firePropertyChange") && method.getParameters().length == 3;
if (foundAdd && foundRemove && foundFire) {
return false;
}
}
consideredClass=consideredClass.getSuperClass();
}
consideredClass=declaringClass.getSuperClass();
while (consideredClass != null) {
if (hasBindableAnnotation(consideredClass)) return false;
for ( FieldNode field : consideredClass.getFields()) {
if (hasBindableAnnotation(field)) return false;
}
consideredClass=consideredClass.getSuperClass();
}
if (foundAdd || foundRemove || foundFire) {
sourceUnit.getErrorCollector().addErrorAndContinue(new SimpleMessage("@Bindable cannot be processed on " + declaringClass.getName() + " because some but not all of addPropertyChangeListener, removePropertyChange, and firePropertyChange were declared in the current or super classes.",sourceUnit));
return false;
}
return true;
}
| Snoops through the declaring class and all parents looking for methods <code>void addPropertyChangeListener(PropertyChangeListener)</code>, <code>void removePropertyChangeListener(PropertyChangeListener)</code>, and <code>void firePropertyChange(String, Object, Object)</code>. If any are defined all must be defined or a compilation error results. |
public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
| The doPost method of the servlet. <br> This method is called when a form has its tag value method equals to post. |
private static int z(int digit){
if (digit == 0) {
return 0;
}
return (digit * 2 - 1) % 9 + 1;
}
| used in computing checksums, doubles and adds resulting digits. |
public static void main(final String[] args){
DOMTestCase.doMain(hc_notationssetnameditem1.class,args);
}
| Runs this test from the command line. |
private SecurityWarning(){
}
| The SecurityWarning class should not be instantiated |
public ST createSingleton(Token templateToken){
String template;
if (templateToken.getType() == GroupParser.BIGSTRING || templateToken.getType() == GroupParser.BIGSTRING_NO_NL) {
template=Misc.strip(templateToken.getText(),2);
}
else {
template=Misc.strip(templateToken.getText(),1);
}
CompiledST impl=compile(getFileName(),null,null,template,templateToken);
ST st=createStringTemplateInternally(impl);
st.groupThatCreatedThisInstance=this;
st.impl.hasFormalArgs=false;
st.impl.name=ST.UNKNOWN_NAME;
st.impl.defineImplicitlyDefinedTemplates(this);
return st;
}
| Create singleton template for use with dictionary values. |
public int compareTo(JumpingSolitaireState jss){
for (int i=0; i < filled.length; i++) {
if (!filled[i] && jss.filled[i]) {
return -1;
}
if (filled[i] && !jss.filled[i]) {
return +1;
}
}
return 0;
}
| Support some meaningful comparison. |
@Override public Void visitReturn(ReturnTree node,Void p){
if (node.getExpression() == null) {
return super.visitReturn(node,p);
}
Pair<Tree,AnnotatedTypeMirror> preAssCtxt=visitorState.getAssignmentContext();
try {
Tree enclosing=TreeUtils.enclosingOfKind(getCurrentPath(),new HashSet<Tree.Kind>(Arrays.asList(Tree.Kind.METHOD,Tree.Kind.LAMBDA_EXPRESSION)));
AnnotatedTypeMirror ret=null;
if (enclosing.getKind() == Tree.Kind.METHOD) {
MethodTree enclosingMethod=TreeUtils.enclosingMethod(getCurrentPath());
boolean valid=validateTypeOf(enclosing);
if (valid) {
ret=atypeFactory.getMethodReturnType(enclosingMethod,node);
}
}
else {
Pair<AnnotatedDeclaredType,AnnotatedExecutableType> result=atypeFactory.getFnInterfaceFromTree((LambdaExpressionTree)enclosing);
ret=result.second.getReturnType();
}
if (ret != null) {
visitorState.setAssignmentContext(Pair.of((Tree)node,ret));
commonAssignmentCheck(ret,node.getExpression(),"return.type.incompatible");
}
return super.visitReturn(node,p);
}
finally {
visitorState.setAssignmentContext(preAssCtxt);
}
}
| Checks that the type of the return expression is a subtype of the enclosing method required return type. If not, it issues a "return.type.incompatible" error. |
public void updateValue(String iconValue){
TrackIconUtils.setIconSpinner(spinner,iconValue);
textView.setText(recordingSettingsActivity.getString(TrackIconUtils.getIconActivityType(iconValue)));
textView.clearFocus();
}
| Updates the value of the dialog. |
private SAXParseException makeException(String message){
if (locator != null) {
return new SAXParseException(message,locator);
}
else {
return new SAXParseException(message,null,null,-1,-1);
}
}
| Construct an exception for the current context. |
private Vcenter createVcenter(VcenterCreateParam createParam,Boolean validateConnection){
Vcenter vcenter;
if (isSystemAdmin()) {
vcenter=createNewSystemVcenter(createParam,validateConnection);
}
else {
TenantOrg tenant=_dbClient.queryObject(TenantOrg.class,URI.create(getUserFromContext().getTenantId()));
vcenter=createNewTenantVcenter(tenant,createParam,validateConnection);
}
return vcenter;
}
| Creates the vCenter based on the User roles. If the User is a System Admin user, the system level vCenter is created. If the User is a Tenant Admin user, the tenant level vCenter is created. |
public final void unmarkResourceAbsent(long resourceID){
this.unmarkResourceAbsent(Long.toString(resourceID));
}
| Mark the resource as not-absent, effectively removing it from this absent-resource list. |
protected StringLiteralImpl(){
super();
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public boolean put(int key,Object value){
int i=indexOfInsertion(key);
if (i < 0) {
i=-i - 1;
this.values[i]=value;
return false;
}
if (this.distinct > this.highWaterMark) {
int newCapacity=chooseGrowCapacity(this.distinct + 1,this.minLoadFactor,this.maxLoadFactor);
rehash(newCapacity);
return put(key,value);
}
this.table[i]=key;
this.values[i]=value;
if (this.state[i] == FREE) this.freeEntries--;
this.state[i]=FULL;
this.distinct++;
if (this.freeEntries < 1) {
int newCapacity=chooseGrowCapacity(this.distinct + 1,this.minLoadFactor,this.maxLoadFactor);
rehash(newCapacity);
}
return true;
}
| Associates the given key with the given value. Replaces any old <tt>(key,someOtherValue)</tt> association, if existing. |
public ICUNormalizer2Filter(TokenStream input,Normalizer2 normalizer){
super(input);
this.normalizer=normalizer;
}
| Create a new Normalizer2Filter with the specified Normalizer2 |
void onStart(){
long now=U.currentTimeMillis();
lastStartTime=now;
long lastEndTime=this.lastEndTime == 0 ? createTime : this.lastEndTime;
lastIdleTime=now - lastEndTime;
totalIdleTime+=lastIdleTime;
running=true;
}
| Start callback. |
public ItemDroppingTeleporterBehaviour(final SpeakerNPC speakerNPC,final List<String> setZones,final String zoneStartsWithLimiter,final String repeatedText,final String itemName){
super(speakerNPC,setZones,zoneStartsWithLimiter,repeatedText);
this.speakerNPC=speakerNPC;
this.itemName=itemName;
}
| Creates a new ItemDroppingTeleporterBehaviour. |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.