code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
private boolean readBuffer() throws IOException {
if (_readBuffer == null || _source == null) {
_readOffset=0;
_readLength=0;
return false;
}
int readLength=_source.read(_readBuffer,0,_readBuffer.length);
_readOffset=0;
if (readLength > 0) {
_readLength=readLength;
_position+=readLength;
if (_isEnableReadTime) _readTime=CurrentTime.currentTime();
return true;
}
else {
_readLength=0;
return false;
}
}
| Fills the read buffer, flushing the write buffer. |
public String toString(){
return "ReadStream[" + _source + "]";
}
| Returns a printable representation of the read stream. |
public FtHttpResume(Direction direction,Uri file,String fileName,String mimeType,long size,Uri fileIcon,ContactId contact,String chatId,String fileTransferId,boolean groupTransfer,long timestamp,long timestampSent){
if (size <= 0 || file == null || fileName == null) throw new IllegalArgumentException("size invalid arguments (size=" + size + ") (file="+ file+ ") (fileName="+ fileName+ ")");
mDirection=direction;
mFile=file;
mFileName=fileName;
mSize=size;
mFileIcon=fileIcon;
mContact=contact;
mChatId=chatId;
mFileTransferId=fileTransferId;
mGroupTransfer=groupTransfer;
mTimestamp=timestamp;
mTimestampSent=timestampSent;
mMimeType=mimeType;
}
| Creates an instance of FtHttpResume Data Object |
public static String replaceChars(String s,char[] sub,char[] with){
char[] str=s.toCharArray();
for (int i=0; i < str.length; i++) {
char c=str[i];
for (int j=0; j < sub.length; j++) {
if (c == sub[j]) {
str[i]=with[j];
break;
}
}
}
return new String(str);
}
| Replaces all occurrences of a characters in a string. |
public int size(){
return this.elements.size();
}
| Returns size of a stack. |
public byte[] createJarFromFileContent(final String fileName,final String content) throws IOException {
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
JarOutputStream jarOutputStream=new JarOutputStream(byteArrayOutputStream);
JarEntry entry=new JarEntry(fileName);
entry.setTime(System.currentTimeMillis());
jarOutputStream.putNextEntry(entry);
jarOutputStream.write(content.getBytes());
jarOutputStream.closeEntry();
jarOutputStream.close();
return byteArrayOutputStream.toByteArray();
}
| Create a JAR using the given file contents and with the given file name. |
@PrePersist public void beforePersist(){
final String username=RequestContext.getUsername();
if (username == null) {
throw new IllegalArgumentException("Cannot persist a TransactionalEntity without a username " + "in the RequestContext for this thread.");
}
setCreatedBy(username);
setCreatedAt(new DateTime());
}
| A listener method which is invoked on instances of TransactionalEntity (or their subclasses) prior to initial persistence. Sets the <code>created</code> audit values for the entity. Attempts to obtain this thread's instance of a username from the RequestContext. If none exists, throws an IllegalArgumentException. The username is used to set the <code>createdBy</code> value. The <code>createdAt</code> value is set to the current timestamp. |
public static void init(Context context){
if (cameraManager == null) {
cameraManager=new CameraManager(context);
}
}
| Initializes this static object with the Context of the calling Activity. |
private boolean resumePreviousRollback(Workflow workflow){
if (workflow.isRollbackState() == false) {
return false;
}
Map<String,Step> stepMap=workflow.getStepMap();
for ( Step step : stepMap.values()) {
if (!step.isRollbackStep()) {
continue;
}
if (step.status.state == StepState.ERROR || step.status.state == StepState.CANCELLED) {
step.status.updateState(StepState.CREATED,null,"");
}
}
for ( Step step : stepMap.values()) {
if (step.isRollbackStep() && step.status.state == StepState.CREATED) {
_log.info(String.format("Retrying previous rollback step %s : %s",step.stepId,step.description));
queueWorkflowStep(workflow,step);
}
}
return true;
}
| Resume the error/cancelled steps in a previous rollback if possible. Returns true if rollback restarted; false if there was no previous rollback. |
@Override protected List<ProxyDistribution> loadBeans(final int startIndex,final int count){
Page<DistributionSet> distBeans;
final List<ProxyDistribution> proxyDistributions=new ArrayList<>();
if (startIndex == 0 && firstPageDistributionSets != null) {
distBeans=firstPageDistributionSets;
}
else if (pinnedControllerId != null) {
final DistributionSetFilterBuilder distributionSetFilterBuilder=new DistributionSetFilterBuilder().setIsDeleted(false).setIsComplete(true).setSearchText(searchText).setSelectDSWithNoTag(noTagClicked).setTagNames(distributionTags);
distBeans=getDistributionSetManagement().findDistributionSetsAllOrderedByLinkTarget(new OffsetBasedPageRequest(startIndex,count,sort),distributionSetFilterBuilder,pinnedControllerId);
}
else if (distributionTags.isEmpty() && Strings.isNullOrEmpty(searchText) && !noTagClicked) {
distBeans=getDistributionSetManagement().findDistributionSetsByDeletedAndOrCompleted(new OffsetBasedPageRequest(startIndex,count,sort),false,true);
}
else {
final DistributionSetFilter distributionSetFilter=new DistributionSetFilterBuilder().setIsDeleted(false).setIsComplete(true).setSearchText(searchText).setSelectDSWithNoTag(noTagClicked).setTagNames(distributionTags).build();
distBeans=getDistributionSetManagement().findDistributionSetsByFilters(new OffsetBasedPageRequest(startIndex,count,sort),distributionSetFilter);
}
for ( final DistributionSet distributionSet : distBeans) {
final ProxyDistribution proxyDistribution=new ProxyDistribution();
proxyDistribution.setName(distributionSet.getName());
proxyDistribution.setDescription(distributionSet.getDescription());
proxyDistribution.setId(distributionSet.getId());
proxyDistribution.setDistId(distributionSet.getId());
proxyDistribution.setVersion(distributionSet.getVersion());
proxyDistribution.setCreatedDate(SPDateTimeUtil.getFormattedDate(distributionSet.getCreatedAt()));
proxyDistribution.setLastModifiedDate(SPDateTimeUtil.getFormattedDate(distributionSet.getLastModifiedAt()));
proxyDistribution.setCreatedByUser(UserDetailsFormatter.loadAndFormatCreatedBy(distributionSet));
proxyDistribution.setModifiedByUser(UserDetailsFormatter.loadAndFormatLastModifiedBy(distributionSet));
proxyDistribution.setNameVersion(HawkbitCommonUtil.getFormattedNameVersion(distributionSet.getName(),distributionSet.getVersion()));
proxyDistributions.add(proxyDistribution);
}
return proxyDistributions;
}
| Load all the Distribution set. |
public boolean equals(Object o){
if (o == this) return true;
else if (o == null || getClass() != o.getClass()) return false;
JClass jClass=(JClass)o;
return getName().equals(jClass.getName());
}
| Returns true if equals. |
@BeforeClass public static void beforeClass(){
dbLogic=new DbLogicImpermanent();
dbLogic.createTestDb();
dbLogic.setIdGenerator(new SequentialIdGenerator());
}
| JUnit runs this before any tests in the class are run. This class uses a sequential ID generator so that IDs are deterministic. This is can also be helpful for interactive debugging. |
public void lock(boolean waitForBackup){
super.lock();
while (isBackingUp && waitForBackup && !(Thread.currentThread() == backupThread)) {
backupDone.awaitUninterruptibly();
}
}
| Acquire this lock, Optionally waiting for a backup to finish the first phase. Any operations that update metadata related to the distributed system state should pass true for this flag, because we need to make sure we get a point in time snapshot of the init files across members to for metadata consistentency. Updates which update only record changes to the local state on this member(eg, switching oplogs), do not need to wait for the backup. |
public ListenerSupport(Object sourceBean){
setSource(sourceBean);
}
| Construct a ListenerSupport object. |
@Override public boolean isActive(){
return amIActive;
}
| Used by the Whitebox GUI to tell if this plugin is still running. |
@Override public void eSet(int featureID,Object newValue){
switch (featureID) {
case DatatypePackage.DICTIONARY_PROPERTY_TYPE__KEY_TYPE:
setKeyType((PropertyType)newValue);
return;
case DatatypePackage.DICTIONARY_PROPERTY_TYPE__VALUE_TYPE:
setValueType((PropertyType)newValue);
return;
}
super.eSet(featureID,newValue);
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public void testProvidesChecksum(){
Em18RfidProtocol instance=new Em18RfidProtocol();
assertEquals(true,instance.providesChecksum());
}
| Test of providesChecksum method, of class Em18RfidProtocol. |
public void addInstruction(InstructionHandle handle){
if (firstInstruction == null) {
firstInstruction=lastInstruction=handle;
}
else {
if (VERIFY_INTEGRITY && handle != lastInstruction.getNext()) {
throw new IllegalStateException("Adding non-consecutive instruction");
}
lastInstruction=handle;
}
}
| Add an InstructionHandle to the basic block. |
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. |
public static void init(int logLevel,Printer... printers){
init(logLevel,new LogConfiguration.Builder().build(),printers);
}
| Initialize log system, should be called only once. |
private void fillToGalleryTop(){
int itemSpacing=mSpacing;
int galleryTop=getPaddingTop();
View prevIterationView=getChildAt(0);
int curPosition;
int curBottomEdge;
int numItems=mItemCount;
if (prevIterationView != null) {
curPosition=mFirstPosition - 1;
curBottomEdge=prevIterationView.getTop() - itemSpacing;
}
else {
curPosition=0;
curBottomEdge=getBottom() - getTop() - getPaddingBottom();
mShouldStopFling=true;
}
while (curBottomEdge > galleryTop && curPosition >= 0) {
prevIterationView=makeAndAddVerticalView(curPosition,curPosition - mSelectedPosition,curBottomEdge,false);
mFirstPosition=curPosition;
curBottomEdge=prevIterationView.getTop() - itemSpacing;
curPosition--;
}
}
| position child from seleted view to top most |
public ReadOnlyTextIcon(final PdfObject form,final int iconRot,final PdfObjectReader pdfObjectReader,final PdfObject res){
super(iconRot);
this.form=form;
currentpdffile=pdfObjectReader;
resources=res;
}
| new code to store the data to create the image when needed to the size needed offset = if 0 no change, 1 offset image, 2 invert image <br> NOTE if decipherAppObject ios not called this will cause problems. |
private void cmd_reloadFile(){
if (m_file == null) return;
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
m_data.clear();
rawData.setText("");
try {
Charset charset=(Charset)fCharset.getSelectedItem();
BufferedReader in=new BufferedReader(new InputStreamReader(new FileInputStream(m_file),charset),10240);
String s=null;
while ((s=in.readLine()) != null) {
m_data.add(s);
if (m_data.size() <= MAX_LOADED_LINES) {
rawData.append(s);
rawData.append("\n");
}
}
in.close();
rawData.setCaretPosition(0);
}
catch ( Exception e) {
log.log(Level.SEVERE,"",e);
bFile.setText(Msg.getMsg(Env.getCtx(),"FileImportFile"));
}
int index=1;
if (m_data.size() == 1) index=0;
int length=0;
if (m_data.size() > 0) length=m_data.get(index).toString().length();
info.setText(Msg.getMsg(Env.getCtx(),"Records") + "=" + m_data.size()+ ", "+ Msg.getMsg(Env.getCtx(),"Length")+ "="+ length+ " ");
setCursor(Cursor.getDefaultCursor());
log.config("Records=" + m_data.size() + ", Length="+ length);
}
| Reload/Load file |
@Deprecated public UpdateRequest scriptLang(String scriptLang){
updateOrCreateScript(null,null,scriptLang,null);
return this;
}
| The language of the script to execute. |
public boolean contains(float value){
return contains(new Float(value).toString());
}
| Returns true if the array contains this real value. |
public void dispose(){
mBlue=null;
super.dispose();
}
| Remove references to and from this object, so that it can eventually be garbage-collected. |
public VariantAllelicFractionAnnotation(){
this("VAF","Variant Allelic Fraction",AnnotationDataType.DOUBLE);
}
| Construct a new contrary observation fraction format annotation. |
ConfigurationError(String msg,Exception x){
super(msg);
this.exception=x;
}
| Construct a new instance with the specified detail string and exception. |
protected Connection newConnection(){
return new Connection(streamProvider);
}
| Allows the connections used by the server to be subclassed. This can be useful for storage per connection without an additional lookup. |
public CompletionWeight(final CompletionQuery query,final Automaton automaton) throws IOException {
super(query);
this.completionQuery=query;
this.automaton=automaton;
}
| Creates a weight for <code>query</code> with an <code>automaton</code>, using the <code>reader</code> for index stats |
protected void initInfo(int record_id,String value){
if (!(record_id == 0) && value != null && value.length() > 0) {
log.severe("Received both a record_id and a value: " + record_id + " - "+ value);
}
if (!(record_id == 0)) {
fieldID=record_id;
String trxName=Trx.createTrxName();
MInvoice mi=new MInvoice(Env.getCtx(),record_id,trxName);
fIsPaid.setSelected(mi.isPaid());
fIsSOTrx.setSelected(mi.isSOTrx());
mi=null;
Trx.get(trxName,false).close();
}
else {
String id;
id=Env.getContext(Env.getCtx(),p_WindowNo,p_TabNo,"C_BPartner_ID",true);
if (id != null && id.length() != 0 && (new Integer(id).intValue() > 0)) fBPartner_ID.setValue(new Integer(id));
id=Env.getContext(Env.getCtx(),p_WindowNo,p_TabNo,"C_Order_ID",true);
if (id != null && id.length() != 0 && (new Integer(id).intValue() > 0)) fOrder_ID.setValue(new Integer(id));
id=Env.getContext(Env.getCtx(),p_WindowNo,"IsSOTrx",true);
if (id != null && id.length() != 0 && (id == "Y" || id == "N")) {
fIsSOTrx.setSelected(id == "Y");
}
if (value != null && value.length() > 0) {
fDocumentNo.setValue(value);
}
else {
id=Env.getContext(Env.getCtx(),p_WindowNo,p_TabNo,"C_Invoice_ID",true);
if (id != null && id.length() != 0 && (new Integer(id).intValue() > 0)) {
fieldID=new Integer(id).intValue();
String trxName=Trx.createTrxName();
MInvoice mi=new MInvoice(Env.getCtx(),record_id,trxName);
fIsPaid.setSelected(mi.isPaid());
fIsSOTrx.setSelected(mi.isSOTrx());
mi=null;
Trx.get(trxName,false).close();
}
}
}
return;
}
| General Init |
@Override public XYItemRendererState initialise(Graphics2D g2,Rectangle2D dataArea,XYPlot plot,XYDataset dataset,PlotRenderingInfo info){
XYBarRendererState state=new XYBarRendererState(info);
ValueAxis rangeAxis=plot.getRangeAxisForDataset(plot.indexOf(dataset));
state.setG2Base(rangeAxis.valueToJava2D(this.base,dataArea,plot.getRangeAxisEdge()));
return state;
}
| Initialises the renderer and returns a state object that should be passed to all subsequent calls to the drawItem() method. Here we calculate the Java2D y-coordinate for zero, since all the bars have their bases fixed at zero. |
public boolean process(Set<? extends TypeElement> annotations,RoundEnvironment roundEnv){
if (!roundEnv.processingOver()) {
TypeElement stringElt=eltUtils.getTypeElement("java.lang.String");
PackageElement javaLangPkg=eltUtils.getPackageElement("java.lang");
PackageElement unnamedPkg=eltUtils.getPackageElement("");
PackageElement pkg=null;
if (!javaLangPkg.equals(pkg=eltUtils.getPackageOf(stringElt))) throw new RuntimeException("Unexpected package for String: " + pkg);
if (!javaLangPkg.equals(pkg=eltUtils.getPackageOf(javaLangPkg))) throw new RuntimeException("Unexpected package for java.lang: " + pkg);
if (!unnamedPkg.equals(pkg=eltUtils.getPackageOf(unnamedPkg))) throw new RuntimeException("Unexpected package for unnamed pkg: " + pkg);
}
return true;
}
| Check expected behavior on classes and packages. |
@Transactional(readOnly=true) public static Result list(String filter){
List<TodoItem> todos;
switch (filter) {
case "open":
case "done":
todos=TodoService.findByCompleted("done".equals(filter));
break;
case "all":
default :
todos=TodoService.findAll();
}
return ok(todolist.render(filter,todos));
}
| Gets the to-do list, filtered by the completion status (all, open and done). |
public void background(float x,float y,float z){
g.background(x,y,z);
}
| Set the background to an r, g, b or h, s, b value, based on the current colorMode. |
public static Resource newObjectFromJSONObject(JSONObject dataObject,List<Resource> included) throws Exception {
Resource realObject=null;
try {
realObject=deserializer.createObjectFromString(getTypeFromJson(dataObject));
}
catch ( Exception e) {
throw e;
}
try {
realObject=mapper.mapId(realObject,dataObject);
}
catch ( Exception e) {
Logger.debug("JSON data does not contain id");
}
try {
realObject=mapper.mapAttributes(realObject,dataObject.getJSONObject("attributes"));
}
catch ( Exception e) {
Logger.debug("JSON data does not contain attributes");
}
try {
realObject=mapper.mapRelations(realObject,dataObject.getJSONObject("relationships"),included);
}
catch ( Exception e) {
Logger.debug("JSON data does not contain relationships");
}
try {
assert realObject != null;
realObject.setMeta(mapper.getAttributeMapper().createMapFromJSONObject(dataObject.getJSONObject("meta")));
}
catch ( Exception e) {
Logger.debug("JSON data does not contain meta");
}
try {
realObject.setLinks(mapper.mapLinks(dataObject.getJSONObject("links")));
}
catch ( JSONException e) {
Logger.debug("JSON data does not contain links");
}
return realObject;
}
| Deserializes a json object of data to the registered class. |
static Object createObject(String factoryId,String propertiesFilename,String fallbackClassName) throws ConfigurationError {
Class factoryClass=lookUpFactoryClass(factoryId,propertiesFilename,fallbackClassName);
if (factoryClass == null) {
throw new ConfigurationError("Provider for " + factoryId + " cannot be found",null);
}
try {
Object instance=factoryClass.newInstance();
debugPrintln("created new instance of factory " + factoryId);
return instance;
}
catch ( Exception x) {
throw new ConfigurationError("Provider for factory " + factoryId + " could not be instantiated: "+ x,x);
}
}
| Finds the implementation Class object in the specified order. The specified order is the following: <ol> <li>query the system property using <code>System.getProperty</code> <li>read <code>$java.home/lib/<i>propertiesFilename</i></code> file <li>read <code>META-INF/services/<i>factoryId</i></code> file <li>use fallback classname </ol> |
public void close() throws IOException {
}
| Closing a <tt>ByteArrayOutputStream</tt> has no effect. The methods in this class can be called after the stream has been closed without generating an <tt>IOException</tt>. |
public final void testGetPublicKey() throws Exception {
TrustAnchor ta=TestUtils.getTrustAnchor();
if (ta == null) {
fail(getName() + ": not performed (could not create test TrustAnchor)");
}
PublicKey pk=testPublicKey;
PKIXCertPathValidatorResult vr=new PKIXCertPathValidatorResult(ta,null,pk);
assertSame(pk,vr.getPublicKey());
}
| Test for <code>getPublicKey()</code> method<br> Assertion: returns the subject's public key (never <code>null</code>) |
public void internalRunning() throws Exception {
endpoint.openClient();
started=true;
DiscoveryRunnable runnable=new DiscoveryRunnable();
runnable.run();
}
| This will start the DiscoveryRunnable and run it directly. This is useful for a test process where we need this execution blocking a thread. |
public void processingInstruction(String target,String data) throws SAXException {
if (m_firstTagNotEmitted) {
flush();
}
m_handler.processingInstruction(target,data);
}
| Pass the call on to the underlying handler |
private ServiceLib(){
}
| Prevent construction. |
@Override public boolean supportsSubqueriesInExists(){
debugCodeCall("supportsSubqueriesInExists");
return true;
}
| Returns whether SELECT in EXISTS is supported. |
private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException {
s.defaultReadObject();
if (nodes == null) {
throw new NullPointerException();
}
if (ambiguousTriples == null) {
ambiguousTriples=new HashSet<>();
}
if (highlightedEdges == null) {
highlightedEdges=new HashSet<>();
}
if (underLineTriples == null) {
underLineTriples=new HashSet<>();
}
if (dottedUnderLineTriples == null) {
dottedUnderLineTriples=new HashSet<>();
}
}
| Adds semantic checks to the default deserialization method. This method must have the standard signature for a readObject method, and the body of the method must begin with "s.defaultReadObject();". Other than that, any semantic checks can be specified and do not need to stay the same from version to version. A readObject method of this form may be added to any class, even if Tetrad sessions were previously saved out using a version of the class that didn't include it. (That's what the "s.defaultReadObject();" is for. See J. Bloch, Effective Java, for help. |
@Deprecated @Nullable public static PsiElement treeCrawlUp(PsiScopeProcessor processor,PsiElement elt){
if (elt == null || !elt.isValid()) return null;
PsiElement seeker=elt;
PsiElement cap=PyUtil.getConcealingParent(elt);
PyFunction capFunction=cap != null ? PsiTreeUtil.getParentOfType(cap,PyFunction.class,false) : null;
final boolean is_outside_param_list=PsiTreeUtil.getParentOfType(elt,PyParameterList.class) == null;
do {
ProgressManager.checkCanceled();
seeker=getPrevNodeOf(seeker);
if ((seeker instanceof NameDefiner) && ((NameDefiner)seeker).mustResolveOutside() && PsiTreeUtil.isAncestor(seeker,elt,true)) {
seeker=getPrevNodeOf(seeker);
}
while (true) {
PsiElement local_cap=PyUtil.getConcealingParent(seeker);
if (local_cap == null) break;
if (local_cap == cap) break;
if ((cap != null) && PsiTreeUtil.isAncestor(local_cap,cap,true)) break;
if ((local_cap != elt) && ((cap == null) || !PsiTreeUtil.isAncestor(local_cap,cap,true))) {
if (local_cap instanceof NameDefiner) {
seeker=local_cap;
}
else {
seeker=getPrevNodeOf(local_cap);
}
}
else {
break;
}
}
if (is_outside_param_list && refersFromMethodToClass(capFunction,seeker)) continue;
if (seeker instanceof PyComprehensionElement && !PsiTreeUtil.isAncestor(seeker,elt,false)) {
continue;
}
if (seeker != null) {
if (!processor.execute(seeker,ResolveState.initial())) {
if (processor instanceof ResolveProcessor) {
return ((ResolveProcessor)processor).getResult();
}
else {
return seeker;
}
}
}
}
while (seeker != null);
if (processor instanceof ResolveProcessor) {
return ((ResolveProcessor)processor).getResult();
}
return null;
}
| Crawls up the PSI tree, checking nodes as if crawling backwards through source lexemes. |
public HubToIntervalFramers(String sourceGroup,ISource source,Action action) throws AdeException {
m_sourceGroup=sourceGroup;
m_source=source;
m_action=action;
initIntervalFramers();
}
| Construct a new HubToIntervalFramers. |
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the GET method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
| The doGet method of the servlet. <br> This method is called when a form has its tag value method equals to get. |
private static PipelineOp addNamedSubqueryInclude(PipelineOp left,final NamedSubqueryInclude nsi,final Set<IVariable<?>> doneSet,final AST2BOpContext ctx){
final String name=nsi.getName();
if (log.isInfoEnabled()) log.info("include: solutionSet=" + name);
final IVariable<?>[] joinVars;
boolean release;
{
final NamedSubqueryRoot nsr=ctx.sa.getNamedSubqueryRoot(name);
if (nsr != null) {
@SuppressWarnings("unchecked") final Set<IVariable<?>> nsrDoneSet=(Set<IVariable<?>>)nsr.getProperty(NamedSubqueryRoot.Annotations.DONE_SET);
if (nsrDoneSet == null) {
throw new AssertionError("NamedSubqueryRoot doneSet not found: " + name);
}
doneSet.addAll(nsrDoneSet);
final VarNode[] joinvars=nsi.getJoinVars();
if (joinvars == null) {
throw new AssertionError();
}
joinVars=ASTUtil.convert(joinvars);
release=false;
}
else {
final ISolutionSetStats stats=ctx.sa.getSolutionSetStats(name);
doneSet.addAll(stats.getMaterialized());
if (isNamedSolutionSetScan(ctx,nsi)) {
return convertNamedSolutionSetScan(left,nsi,doneSet,ctx);
}
final Set<IVariable<?>> joinvars=ctx.sa.getJoinVars(nsi,name,new LinkedHashSet<IVariable<?>>());
joinVars=joinvars.toArray(new IVariable[]{});
@SuppressWarnings("rawtypes") final IVariable[] selectVars=null;
final INamedSolutionSetRef sourceSet=NamedSolutionSetRefUtility.newInstance(ctx.getNamespace(),ctx.getTimestamp(),name,IVariable.EMPTY);
final INamedSolutionSetRef generatedSet=NamedSolutionSetRefUtility.newInstance(ctx.queryId,name,joinVars);
final JoinTypeEnum joinType=JoinTypeEnum.Normal;
final IHashJoinUtilityFactory joinUtilFactory;
if (ctx.nativeHashJoins) {
joinUtilFactory=HTreeHashJoinUtility.factory;
}
else {
joinUtilFactory=JVMHashJoinUtility.factory;
}
left=applyQueryHints(new HashIndexOp(leftOrEmpty(left),new NV(BOp.Annotations.BOP_ID,ctx.nextId()),new NV(BOp.Annotations.EVALUATION_CONTEXT,BOpEvaluationContext.CONTROLLER),new NV(PipelineOp.Annotations.MAX_PARALLEL,1),new NV(PipelineOp.Annotations.LAST_PASS,true),new NV(PipelineOp.Annotations.SHARED_STATE,true),new NV(HashIndexOp.Annotations.JOIN_TYPE,joinType),new NV(HashIndexOp.Annotations.JOIN_VARS,joinVars),new NV(HashIndexOp.Annotations.SELECT,selectVars),new NV(HashIndexOp.Annotations.HASH_JOIN_UTILITY_FACTORY,joinUtilFactory),new NV(HashIndexOp.Annotations.NAMED_SET_SOURCE_REF,sourceSet),new NV(HashIndexOp.Annotations.NAMED_SET_REF,generatedSet),new NV(IPredicate.Annotations.RELATION_NAME,new String[]{ctx.getLexiconNamespace()})),nsi,ctx);
release=true;
}
}
final INamedSolutionSetRef namedSolutionSetRef=NamedSolutionSetRefUtility.newInstance(ctx.queryId,name,joinVars);
@SuppressWarnings("rawtypes") final Map<IConstraint,Set<IVariable<IV>>> needsMaterialization=new LinkedHashMap<IConstraint,Set<IVariable<IV>>>();
final IConstraint[] joinConstraints=getJoinConstraints(getJoinConstraints(nsi),needsMaterialization);
release=false;
if (ctx.nativeHashJoins) {
left=applyQueryHints(new HTreeSolutionSetHashJoinOp(leftOrEmpty(left),new NV(BOp.Annotations.BOP_ID,ctx.nextId()),new NV(BOp.Annotations.EVALUATION_CONTEXT,BOpEvaluationContext.CONTROLLER),new NV(PipelineOp.Annotations.SHARED_STATE,true),new NV(HTreeSolutionSetHashJoinOp.Annotations.NAMED_SET_REF,namedSolutionSetRef),new NV(HTreeSolutionSetHashJoinOp.Annotations.CONSTRAINTS,joinConstraints),new NV(HTreeSolutionSetHashJoinOp.Annotations.RELEASE,release)),nsi,ctx);
}
else {
left=applyQueryHints(new JVMSolutionSetHashJoinOp(leftOrEmpty(left),new NV(BOp.Annotations.BOP_ID,ctx.nextId()),new NV(BOp.Annotations.EVALUATION_CONTEXT,BOpEvaluationContext.CONTROLLER),new NV(PipelineOp.Annotations.SHARED_STATE,true),new NV(JVMSolutionSetHashJoinOp.Annotations.NAMED_SET_REF,namedSolutionSetRef),new NV(JVMSolutionSetHashJoinOp.Annotations.CONSTRAINTS,joinConstraints),new NV(JVMSolutionSetHashJoinOp.Annotations.RELEASE,release)),nsi,ctx);
}
left=addMaterializationSteps3(left,doneSet,needsMaterialization,nsi.getQueryHints(),ctx);
return left;
}
| Add a join against a pre-computed temporary solution set into a join group. <p> Note: Since the subquery solution set has already been computed and only contains bindings for solutions projected by the subquery, we do not need to adjust the visibility of bindings when we execute the hash join against the named solution set. |
private static UntarCompressionMethod compressionMethod(File file){
String fn=file.toString();
UntarCompressionMethod out=new UntarCompressionMethod();
if (fn.endsWith("gz")) {
out.setValue("gzip");
}
else if (fn.endsWith("bz2")) {
out.setValue("bzip2");
}
else if (fn.endsWith("tar")) {
out.setValue("none");
}
else {
throw new IllegalArgumentException("UntarJob doesn't know what to do with that file. " + "tar, gz, and bz2 files accepted.");
}
return out;
}
| Internal convenience method determines the archive type from the filename extension. |
private void deleteWorkFlowMatrixObject(final HashMap workflowsearchparams){
this.workFlowMatrixService.deleteWorkFlowforObject(workflowsearchparams);
}
| This method deletes the workflow matrix object |
private static void subsetsHelper(List<List<Integer>> res,List<Integer> list,int[] num,int pos){
res.add(new ArrayList<Integer>(list));
for (int i=pos; i < num.length; i++) {
if (i != pos && num[i] == num[i - 1]) continue;
list.add(num[i]);
subsetsHelper(res,list,num,i + 1);
list.remove(list.size() - 1);
}
}
| addRecursive list to result Backtrack from current position to the end of array Skip duplicates first addRecursive number to list and pass list and i+1 to next backtrack Reset list after that |
public void clearTable(){
super.clearTable();
}
| Clears the table and converts the download button into a wish list button. |
protected final void mergeNodes(PurityNode src,PurityNode dst){
Iterator it=(new LinkedList(edges.get(src))).iterator();
while (it.hasNext()) {
PurityEdge e=(PurityEdge)it.next();
PurityNode n=e.getTarget();
if (n.equals(src)) n=dst;
PurityEdge ee=cacheEdge(new PurityEdge(dst,e.getField(),n,e.isInside()));
edges.remove(src,e);
edges.put(dst,ee);
backEdges.remove(n,e);
backEdges.put(n,ee);
}
it=(new LinkedList(backEdges.get(src))).iterator();
while (it.hasNext()) {
PurityEdge e=(PurityEdge)it.next();
PurityNode n=e.getSource();
if (n.equals(src)) n=dst;
PurityEdge ee=cacheEdge(new PurityEdge(n,e.getField(),dst,e.isInside()));
edges.remove(n,e);
edges.put(n,ee);
backEdges.remove(src,e);
backEdges.put(dst,ee);
}
it=(new LinkedList(backLocals.get(src))).iterator();
while (it.hasNext()) {
Local l=(Local)it.next();
locals.remove(l,src);
backLocals.remove(src,l);
locals.put(l,dst);
backLocals.put(dst,l);
}
{
Set m=mutated.get(src);
mutated.remove(src);
mutated.putAll(dst,m);
}
if (ret.contains(src)) {
ret.remove(src);
ret.add(dst);
}
if (globEscape.contains(src)) {
globEscape.remove(src);
globEscape.add(dst);
}
nodes.remove(src);
nodes.add(dst);
paramNodes.remove(src);
if (dst.isParam()) paramNodes.add(dst);
}
| Utility function to merge node src into dst; src is removed |
public boolean contains(char point){
return start <= point && end >= point;
}
| Return <code>true</code> iff <code>point</code> is contained in this intervall. |
public static boolean isExternalStorageAvailable(){
String state=Environment.getExternalStorageState();
return Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state);
}
| Returns true if the external storage is available. |
public void addListener(INotifyChangedListener notifyChangedListener){
changeNotifier.addListener(notifyChangedListener);
}
| This adds a listener. <!-- begin-user-doc --> <!-- end-user-doc --> |
@Override protected void initListeners(){
}
| Initialize the View of the listener |
@DSComment("From safe class list") @DSSafe(DSCat.SAFE_LIST) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:56:31.930 -0500",hash_original_method="0EB66BA5E965B83E191719250E0A82FF",hash_generated_method="0D841C721535905DD0E9F7FAE6757EB9") @Override public String toString(){
return name;
}
| Returns a string containing a concise, human-readable description of this object. In this case, the enum constant's name is returned. |
void writeStub(IndentingWriter p) throws IOException {
p.pln("// Stub class generated by rmic, do not edit.");
p.pln("// Contents subject to change without notice.");
p.pln();
if (!packageName.equals("")) {
p.pln("package " + packageName + ";");
p.pln();
}
p.plnI("public final class " + stubClassSimpleName);
p.pln("extends " + REMOTE_STUB);
ClassDoc[] remoteInterfaces=remoteClass.remoteInterfaces();
if (remoteInterfaces.length > 0) {
p.p("implements ");
for (int i=0; i < remoteInterfaces.length; i++) {
if (i > 0) {
p.p(", ");
}
p.p(remoteInterfaces[i].qualifiedName());
}
p.pln();
}
p.pOlnI("{");
if (version == StubVersion.V1_1 || version == StubVersion.VCOMPAT) {
writeOperationsArray(p);
p.pln();
writeInterfaceHash(p);
p.pln();
}
if (version == StubVersion.VCOMPAT || version == StubVersion.V1_2) {
p.pln("private static final long serialVersionUID = " + STUB_SERIAL_VERSION_UID + ";");
p.pln();
if (methodFieldNames.length > 0) {
if (version == StubVersion.VCOMPAT) {
p.pln("private static boolean useNewInvoke;");
}
writeMethodFieldDeclarations(p);
p.pln();
p.plnI("static {");
p.plnI("try {");
if (version == StubVersion.VCOMPAT) {
p.plnI(REMOTE_REF + ".class.getMethod(\"invoke\",");
p.plnI("new java.lang.Class[] {");
p.pln(REMOTE + ".class,");
p.pln("java.lang.reflect.Method.class,");
p.pln("java.lang.Object[].class,");
p.pln("long.class");
p.pOln("});");
p.pO();
p.pln("useNewInvoke = true;");
}
writeMethodFieldInitializers(p);
p.pOlnI("} catch (java.lang.NoSuchMethodException e) {");
if (version == StubVersion.VCOMPAT) {
p.pln("useNewInvoke = false;");
}
else {
p.plnI("throw new java.lang.NoSuchMethodError(");
p.pln("\"stub class initialization failed\");");
p.pO();
}
p.pOln("}");
p.pOln("}");
p.pln();
}
}
writeStubConstructors(p);
p.pln();
if (remoteMethods.length > 0) {
p.pln("// methods from remote interfaces");
for (int i=0; i < remoteMethods.length; ++i) {
p.pln();
writeStubMethod(p,i);
}
}
p.pOln("}");
}
| Writes the stub class for the remote class to a stream. |
public T caseParameterizedTypeRefStructural(ParameterizedTypeRefStructural object){
return null;
}
| Returns the result of interpreting the object as an instance of '<em>Parameterized Type Ref Structural</em>'. <!-- begin-user-doc --> This implementation returns null; returning a non-null result will terminate the switch. <!-- end-user-doc --> |
private void validateSystemJobRunRequest(SystemJobRunRequest request){
Assert.hasText(request.getJobName(),"A job name must be specified.");
request.setJobName(request.getJobName().trim());
parameterHelper.validateParameters(request.getParameters());
}
| Validate a system job run request. This method also trims request parameters. |
public void addKdContainer(int index,double dist){
KdistanceContainer container=new KdistanceContainer(this);
container.setDistance(dist);
this.listOfkDContainers.add(index,container);
}
| Adds a new KdContainer to the SearchObject at index in the container list and also sets the distance value of the container to dist. |
public Buddy(String name){
this.name=name;
}
| Create a new buddy. |
public static int floatCompare(float a,float b,float precision){
if (java.lang.Math.abs(a - b) <= precision) return 0;
else if (a > b) return 1;
else return -1;
}
| Compare two floating point numbers. They are considered equal when their difference is less than or equal to the precision. |
private static void checkValidImportableFile(PsiElement anchor,VirtualFile file){
final QualifiedName qName=QualifiedNameFinder.findShortestImportableQName(anchor,file);
if (!PyClassRefactoringUtil.isValidQualifiedName(qName)) {
throw new IncorrectOperationException(PyBundle.message("refactoring.move.module.members.error.cannot.use.module.name.$0",file.getName()));
}
}
| Additionally contains referenced element. |
public void testSplit(){
DoubleBuffer buffer=new DoubleBuffer(10);
for (int i=0; i < 5; i++) {
buffer.setNext(-10);
assertFalse(buffer.isFull());
assertEquals(-10.0,buffer.getAverage());
double[] averageAndVariance=buffer.getAverageAndVariance();
assertEquals(-10.0,averageAndVariance[0]);
assertEquals(0.0,averageAndVariance[1]);
}
for (int i=1; i < 5; i++) {
buffer.setNext(10);
assertFalse(buffer.isFull());
double expectedAverage=((i * 10.0) - 50.0) / (i + 5);
assertEquals(buffer.toString(),expectedAverage,buffer.getAverage(),0.01);
double[] averageAndVariance=buffer.getAverageAndVariance();
assertEquals(expectedAverage,averageAndVariance[0]);
}
buffer.setNext(10);
assertTrue(buffer.isFull());
assertEquals(0.0,buffer.getAverage());
double[] averageAndVariance=buffer.getAverageAndVariance();
assertEquals(0.0,averageAndVariance[0]);
assertEquals(100.0,averageAndVariance[1]);
}
| Tests with 5 entries of -10 and 5 entries of 10. |
final public void EscapedDirective() throws ParseException {
ASTEscapedDirective jjtn000=new ASTEscapedDirective(this,JJTESCAPEDDIRECTIVE);
boolean jjtc000=true;
jjtree.openNodeScope(jjtn000);
try {
Token t=null;
t=jj_consume_token(ESCAPE_DIRECTIVE);
jjtree.closeNodeScope(jjtn000,true);
jjtc000=false;
t.image=escapedDirective(t.image);
}
finally {
if (jjtc000) {
jjtree.closeNodeScope(jjtn000,true);
}
}
}
| used to separate the notion of a valid directive that has been escaped, versus something that looks like a directive and is just schmoo. This is important to do as a separate production that creates a node, because we want this, in either case, to stop the further parsing of the Directive() tree. |
protected boolean isDirty(String location){
return VacuumEnvironment.LocationState.Dirty == getVacuumEnv().getLocationState(location);
}
| Checks whether the specified location is dirty. |
private void returnData(Object ret){
if (myHost != null) {
myHost.returnData(ret);
}
}
| Used to communicate a return object from a plugin tool to the main Whitebox user-interface. |
static List<String> evaluateExpansionPattern(String part,boolean enhancedSyntax){
List<String> stringList=StringUtil.split(part,",",true,false);
List<String> result=new LinkedList<String>();
if (stringList.size() == 1 && stringList.get(0).contains("..")) {
if (!evaluateRangeExpression(stringList.get(0),result,enhancedSyntax)) {
return Collections.emptyList();
}
}
else {
for ( String e : stringList) {
result.add(e);
}
}
return result;
}
| Evaluates a pattern like a,b,c or a..c. The string input is expected to be a comma separated list. Each element is either a string or a range. A range cen either be numeric (1..10) or a range between characters (a..z). <br> Valid patterns examples: "a", "a,b", "a..z", "1..999", "abc,def" |
protected final long buildTookInMillis(DfsOnlyRequest request){
return Math.max(1,System.currentTimeMillis() - request.nowInMillis);
}
| Builds how long it took to execute the dfs request. |
public JMenu createAlignMenu(){
JMenu alignSubMenu=new JMenu("Align");
alignSubMenu.add(actionManager.getAlignHorizontalAction());
alignSubMenu.add(actionManager.getAlignVerticalAction());
return alignSubMenu;
}
| Return the align sub menu. |
public CallInfoHeader createCallInfoHeader(URI callInfo){
if (callInfo == null) throw new NullPointerException("null arg callInfo");
CallInfo c=new CallInfo();
c.setInfo(callInfo);
return c;
}
| Creates a new CallInfoHeader based on the newly supplied callInfo value. |
public String toString(String pattern){
if (pattern == null) {
return toString();
}
return DateTimeFormat.forPattern(pattern).print(this);
}
| Output the year-month using the specified format pattern. |
private boolean isIntersect(){
return Math.sqrt(Math.pow(circle1.getCenterX() - circle2.getCenterX(),2) + Math.pow(circle1.getCenterY() - circle2.getCenterY(),2)) <= circle1.getRadius() + circle2.getRadius();
}
| Returns true if circles inIntersect |
@Override public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
case android.R.id.home:
if (conversationLayout.getVisibility() == LinearLayout.VISIBLE) {
hideConversationLayout();
invalidateOptionsMenu();
swipeRefresh.setEnabled(true);
refreshActivity();
}
else {
Intent intent=new Intent(this,MainActivity.class);
startActivity(intent);
}
break;
case R.id.refresh:
if (isFirstTimeRefresh) {
isFirstTimeRefresh=false;
tinydb.putBoolean("isFirstTimeRefresh",isFirstTimeRefresh);
Toast.makeText(getApplicationContext(),"You can also swipe down to refresh.",Toast.LENGTH_SHORT).show();
refreshActivity();
}
else {
refreshActivity();
}
break;
case R.id.edit:
editServer();
break;
case R.id.delete:
Intent deleteServer=new Intent(this,MainActivity.class);
deleteServer.putExtra("serverId",serverId);
recentList.clear();
pinnedRooms.clear();
saveRecentItems();
savePinnedItems();
startActivity(deleteServer);
break;
case R.id.disconnect:
server.setStatus(Status.DISCONNECTED);
server.setMayReconnect(false);
binder.getService().getConnection(serverId).quitServer();
server.clearConversations();
setResult(RESULT_OK);
invalidateOptionsMenu();
if (Math.random() * 100 < 80) {
showAd();
}
break;
case R.id.close:
Conversation conversationToClose=pagerAdapter.getItem(pager.getCurrentItem());
if (conversationToClose.getType() == Conversation.TYPE_CHANNEL) {
binder.getService().getConnection(serverId).partChannel(conversationToClose.getName());
if (Math.random() * 100 < 50) {
showAd();
}
}
else if (conversationToClose.getType() == Conversation.TYPE_QUERY) {
server.removeConversation(conversationToClose.getName());
onRemoveConversation(conversationToClose.getName());
if (Math.random() * 100 < 50) {
showAd();
}
}
else {
Toast.makeText(this,getResources().getString(R.string.close_server_window),Toast.LENGTH_SHORT).show();
}
break;
case R.id.join:
startActivityForResult(new Intent(this,JoinActivity.class),REQUEST_CODE_JOIN);
break;
case R.id.users:
Conversation conversationForUserList=pagerAdapter.getItem(pager.getCurrentItem());
if (conversationForUserList.getType() == Conversation.TYPE_CHANNEL) {
Intent intent=new Intent(this,UsersActivity.class);
intent.putExtra(Extra.USERS,binder.getService().getConnection(server.getId()).getUsersAsStringArray(conversationForUserList.getName()));
startActivityForResult(intent,REQUEST_CODE_USERS);
}
else {
Toast.makeText(this,getResources().getString(R.string.only_usable_from_channel),Toast.LENGTH_SHORT).show();
}
break;
}
return true;
}
| On menu item selected |
private static void checkStoragePoolValidForUnManagedVolumeUri(StringSetMap unManagedVolumeInformation,DbClient dbClient,URI unManagedVolumeUri) throws APIException {
String pool=PropertySetterUtil.extractValueFromStringSet(VolumeObjectProperties.STORAGE_POOL.toString(),unManagedVolumeInformation);
if (null == pool) {
throw APIException.internalServerErrors.storagePoolError("",VOLUME_TEXT,unManagedVolumeUri);
}
StoragePool poolObj=dbClient.queryObject(StoragePool.class,URI.create(pool));
if (null == poolObj) {
throw APIException.internalServerErrors.noStoragePool(pool,VOLUME_TEXT,unManagedVolumeUri);
}
}
| Check if valid storage Pool is associated with UnManaged Volume Uri is valid. |
void dispose() throws IOException {
_httpClient.close();
_httpContext.clear();
}
| Closes the client connections and prepares the client for garbage collection. |
public void close(RelayedCandidateDatagramSocket relayedCandidateSocket){
setSendKeepAliveMessageInterval(SEND_KEEP_ALIVE_MESSAGE_INTERVAL_NOT_SPECIFIED);
try {
sendRequest(MessageFactory.createRefreshRequest(0),false,null);
}
catch ( StunException sex) {
logger.log(Level.INFO,"Failed to send TURN Refresh request to delete Allocation",sex);
}
}
| Notifies this <tt>TurnCandidateHarvest</tt> that a specific <tt>RelayedCandidateDatagramSocket</tt> is closing and that this instance is to delete the associated TURN Allocation. <p> <b>Note</b>: The method is part of the internal API of <tt>RelayedCandidateDatagramSocket</tt> and <tt>TurnCandidateHarvest</tt> and is not intended for public use. </p> |
public static byte[] decodeHex(final char[] data){
final int len=data.length;
if ((len & 0x01) != 0) {
throw new IllegalArgumentException("Odd number of characters.");
}
final byte[] out=new byte[len >> 1];
for (int i=0, j=0; j < len; i++) {
int f=toDigit(data[j],j) << 4;
j++;
f=f | toDigit(data[j],j);
j++;
out[i]=(byte)(f & 0xFF);
}
return out;
}
| Converts an array of characters representing hexadecimal values into an array of bytes of those same values. The returned array will be half the length of the passed array, as it takes two characters to represent any given byte. An exception is thrown if the passed char array has an odd number of elements. |
public File createMergeProcedure(File dir,String loadName){
StringBuffer code=new StringBuffer();
code.append("function prepare() {\n").append(" dir = runtime.getContext().getServiceName();\n").append(" runtime.exec('echo prepare >> ' + dir + '/prepare.stat');\n").append("}\n").append("function begin() {\n").append(" runtime.exec('echo begin >> ' + dir + '/begin.stat');\n").append("}\n").append("function apply(csvinfo) {\n").append(" logger.info('Applying csv: table=' + csvinfo.baseTableMetadata.getName());").append(" if (csvinfo.key == '') {\n").append(" output_csv = csvinfo.baseTableMetadata.getName() + '.data';\n").append(" } else {\n").append(" output_csv = csvinfo.baseTableMetadata.getName() + '-' + csvinfo.key + '.data';\n").append(" }\n").append(" runtime.exec('echo ' + csvinfo.file.getName() + " + "'>> ' + dir + '/apply.stat');\n").append(" runtime.exec('cat ' + csvinfo.file.getAbsolutePath() + ' >> '").append(" + dir + '/' + output_csv);\n").append("}\n").append("function commit() {\n").append(" runtime.exec('echo commit >> ' + dir + '/commit.stat');\n").append("}\n").append("function release() {\n").append(" runtime.exec('echo release >> ' + dir + '/release.stat');\n").append("}");
File scriptFile=new File(dir,loadName);
fileIO.write(new FilePath(scriptFile.getAbsolutePath()),code.toString());
return scriptFile;
}
| Create a test Javascript procedure that follows load conventions and generates a write to a file for each call to the various load methods. |
public SimpleConstant(String name,String stringValue,String annotation){
this(name,stringValue);
this.annotation=annotation;
}
| Creates a Constant with the given characteristics. |
public DeprecatedAttribute(ConstPool cp){
super(cp,tag,new byte[0]);
}
| Constructs a Deprecated attribute. |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 13:00:48.378 -0500",hash_original_method="C1264636A1B4EA8B9B687011C8022954",hash_generated_method="C1264636A1B4EA8B9B687011C8022954") AttributeListAdapter(){
}
| Construct a new adapter. |
public void loadSelfFile(URL url,String encoding,boolean debug){
try {
loadSelfFile(Utils.openStream(url),encoding,MAX_FILE_SIZE,debug,true);
}
catch ( IOException exception) {
throw new SelfParseException("Parsing error occurred",exception);
}
}
| Load, compile, and add the state machine from the .self file. |
@Override public V remove(Object key){
int hash=hash(key);
return segmentFor(hash).r(key,hash,null);
}
| Removes the key (and its corresponding value) from this map. This method does nothing if the key is not in the map. |
public boolean canBeLongAddress(int address){
return (address >= 1);
}
| Address 1 and above can be long |
private void performSend(WalletData perWalletModelData,SendRequest sendRequest,CharSequence walletPassword){
String message=null;
boolean sendWasSuccessful=Boolean.FALSE;
try {
if (sendRequest != null && sendRequest.tx != null) {
log.debug("Sending from wallet " + perWalletModelData.getWalletFilename() + ", tx = "+ sendRequest.tx.toString());
}
if (useTestParameters) {
log.debug("Using test parameters - not really sending");
if (sayTestSendWasSuccessful) {
sendWasSuccessful=Boolean.TRUE;
log.debug("Using test parameters - saying send was successful");
}
else {
message="test - send failed";
log.debug("Using test parameters - saying send failed");
}
}
else {
transaction=this.bitcoinController.getMultiBitService().sendCoins(perWalletModelData,sendRequest,walletPassword);
if (transaction == null) {
message=controller.getLocaliser().getString("sendBitcoinNowAction.thereWereInsufficientFundsForTheSend");
log.error(message);
}
else {
sendWasSuccessful=Boolean.TRUE;
log.debug("Sent transaction was:\n" + transaction.toString());
}
}
}
catch ( KeyCrypterException e) {
log.error(e.getMessage(),e);
message=e.getMessage();
}
catch ( WalletSaveException e) {
log.error(e.getMessage(),e);
message=e.getMessage();
}
catch ( IOException e) {
log.error(e.getMessage(),e);
message=e.getMessage();
}
catch ( AddressFormatException e) {
log.error(e.getMessage(),e);
message=e.getMessage();
}
catch ( IllegalStateException e) {
log.error(e.getMessage(),e);
message=controller.getLocaliser().getString("sendBitcoinNowAction.pingFailure");
}
catch ( Exception e) {
log.error(e.getMessage(),e);
message=e.getMessage();
}
finally {
try {
this.bitcoinController.getFileHandler().savePerWalletModelData(perWalletModelData,false);
}
catch ( WalletSaveException e) {
log.error(e.getMessage(),e);
message=e.getMessage();
}
if (sendWasSuccessful) {
String successMessage=controller.getLocaliser().getString("sendBitcoinNowAction.bitcoinSentOk");
if (sendBitcoinConfirmPanel != null && (sendBitcoinConfirmPanel.isVisible() || useTestParameters)) {
sendBitcoinConfirmPanel.setMessageText(controller.getLocaliser().getString("sendBitcoinNowAction.bitcoinSentOk"));
sendBitcoinConfirmPanel.showOkButton();
sendBitcoinConfirmPanel.clearAfterSend();
}
else {
MessageManager.INSTANCE.addMessage(new Message(successMessage));
}
}
else {
log.error(message);
if (message != null && message.length() > MAX_LENGTH_OF_ERROR_MESSAGE) {
message=message.substring(0,MAX_LENGTH_OF_ERROR_MESSAGE) + "...";
}
String errorMessage=controller.getLocaliser().getString("sendBitcoinNowAction.bitcoinSendFailed");
if (sendBitcoinConfirmPanel != null && (sendBitcoinConfirmPanel.isVisible() || useTestParameters)) {
sendBitcoinConfirmPanel.setMessageText(errorMessage,message);
}
else {
MessageManager.INSTANCE.addMessage(new Message(errorMessage + " " + message));
}
}
perWalletModelData.setBusyTaskKey(null);
perWalletModelData.setBusy(false);
this.bitcoinController.fireWalletBusyChange(false);
log.debug("firing fireRecreateAllViews...");
controller.fireRecreateAllViews(false);
log.debug("firing fireRecreateAllViews...done");
}
}
| Send the transaction directly. |
protected void removeAttribute(Object id){
if (attributes != null) {
attributes.remove(id);
if (attributes.isEmpty()) {
attributes=null;
}
}
}
| Removes the specified attribute if it exist in this Element This method allows creating a key that is non-string to be used by subclasses that optimize attributes retrieval |
public static <T>Filter<T> collectionRejectFilter(Collection<T> objs){
return new CollectionAcceptFilter<T>(objs,false);
}
| The collectionRejectFilter rejects a certain collection. |
@Override public CreditCard menuItem(@AnyRes int menuItem){
if (menuItem == 0) {
Log.e("MenuItem","Impossible to set Menu Item to 0! Please Check it");
}
else {
mMenuItem=menuItem;
isMenuItem=true;
}
return this;
}
| Menu Item for set custom menu item to Swipeable Card. |
@Override public void acceptDataSet(DataSetEvent e){
m_busy=true;
if (m_log != null) {
m_log.statusMessage(statusMessagePrefix() + "Processing batch...");
}
try {
makeOutputStructure(new Instances(e.getDataSet(),0));
}
catch ( Exception ex) {
String msg=statusMessagePrefix() + "ERROR: unable to create output instances structure.";
if (m_log != null) {
m_log.statusMessage(msg);
m_log.logMessage("[SubstringLabeler] " + ex.getMessage());
}
stop();
ex.printStackTrace();
m_busy=false;
return;
}
Instances toProcess=e.getDataSet();
for (int i=0; i < toProcess.numInstances(); i++) {
Instance current=toProcess.instance(i);
Instance result=null;
try {
result=m_matches.makeOutputInstance(current,true);
}
catch ( Exception ex) {
ex.printStackTrace();
}
if (result != null) {
m_matches.getOutputStructure().add(result);
}
}
if (m_log != null) {
m_log.statusMessage(statusMessagePrefix() + "Finished.");
}
DataSetEvent d=new DataSetEvent(this,m_matches.getInputStructure());
notifyDataListeners(d);
m_busy=false;
}
| Accept and process a data set event |
@Override public String generateOutput(boolean textOnly){
Element figcaption=DomUtil.cloneAndProcessTree(figCaption);
if (textOnly) return DomUtil.getInnerText(figcaption);
Element figure=Document.get().createElement("FIGURE");
figure.appendChild(getProcessedNode());
if (!figCaption.getInnerHTML().isEmpty()) {
figure.appendChild(figcaption);
}
return figure.getString();
}
| WebFigure extends WebImage so it can use WebImage generated output and just handle the caption since an html figure is basically a placeholder for an image and a caption. |
public static void decimal(TextField campo){
campo.lengthProperty().addListener(null);
}
| Digitar apenas numeros e decimais com ponto(.) no campo de texto passado |
protected void compareDatasets(Instances data1,Instances data2) throws Exception {
if (m_CheckHeader) {
if (!data2.equalHeaders(data1)) {
throw new Exception("header has been modified\n" + data2.equalHeadersMsg(data1));
}
}
if (!(data2.numInstances() == data1.numInstances())) {
throw new Exception("number of instances has changed");
}
for (int i=0; i < data2.numInstances(); i++) {
Instance orig=data1.instance(i);
Instance copy=data2.instance(i);
for (int j=0; j < orig.numAttributes(); j++) {
if (orig.isMissing(j)) {
if (!copy.isMissing(j)) {
throw new Exception("instances have changed");
}
}
else {
if (m_CompareValuesAsString) {
if (!orig.toString(j).equals(copy.toString(j))) {
throw new Exception("instances have changed");
}
}
else {
if (Math.abs(orig.value(j) - copy.value(j)) > m_MaxDiffValues) {
throw new Exception("instances have changed");
}
}
}
if (Math.abs(orig.weight() - copy.weight()) > m_MaxDiffWeights) {
throw new Exception("instance weights have changed");
}
}
}
}
| Compare two datasets to see if they differ. |
@DSComment("Private Method") @DSBan(DSCat.PRIVATE_METHOD) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:56:20.722 -0500",hash_original_method="13DD8DB959754AD57AB3077389D7ADB3",hash_generated_method="60ED6C262BC16DB52818D9B130F3CC52") private static int upperIndex(int ch){
int index=-1;
if (ch >= 0xdf) {
if (ch <= 0x587) {
switch (ch) {
case 0xdf:
return 0;
case 0x149:
return 1;
case 0x1f0:
return 2;
case 0x390:
return 3;
case 0x3b0:
return 4;
case 0x587:
return 5;
}
}
else if (ch >= 0x1e96) {
if (ch <= 0x1e9a) {
index=6 + ch - 0x1e96;
}
else if (ch >= 0x1f50 && ch <= 0x1ffc) {
index=upperValues2[ch - 0x1f50];
if (index == 0) {
index=-1;
}
}
else if (ch >= 0xfb00) {
if (ch <= 0xfb06) {
index=90 + ch - 0xfb00;
}
else if (ch >= 0xfb13 && ch <= 0xfb17) {
index=97 + ch - 0xfb13;
}
}
}
}
return index;
}
| Return the index of the specified character into the upperValues table. The upperValues table contains three entries at each position. These three characters are the upper case conversion. If only two characters are used, the third character in the table is \u0000. |
protected void readBinaryChildren(ClassFile classFile,HashMap newElements,IBinaryType typeInfo){
ArrayList childrenHandles=new ArrayList();
BinaryType type=(BinaryType)classFile.getType();
ArrayList typeParameterHandles=new ArrayList();
if (typeInfo != null) {
generateAnnotationsInfos(type,typeInfo.getAnnotations(),typeInfo.getTagBits(),newElements);
generateTypeParameterInfos(type,typeInfo.getGenericSignature(),newElements,typeParameterHandles);
generateFieldInfos(type,typeInfo,newElements,childrenHandles);
generateMethodInfos(type,typeInfo,newElements,childrenHandles,typeParameterHandles);
generateInnerClassHandles(type,typeInfo,childrenHandles);
}
this.binaryChildren=new JavaElement[childrenHandles.size()];
childrenHandles.toArray(this.binaryChildren);
int typeParameterHandleSize=typeParameterHandles.size();
if (typeParameterHandleSize == 0) {
this.typeParameters=TypeParameter.NO_TYPE_PARAMETERS;
}
else {
this.typeParameters=new ITypeParameter[typeParameterHandleSize];
typeParameterHandles.toArray(this.typeParameters);
}
}
| Creates the handles for <code>BinaryMember</code>s defined in this <code>ClassFile</code> and adds them to the <code>JavaModelManager</code>'s cache. |
public void vetoableChange(PropertyChangeEvent e){
log.config(e.getPropertyName() + "=" + e.getNewValue());
if (e.getPropertyName().equals("C_BPartner_ID")) {
loadRMA();
}
dialog.tableChanged(null);
}
| Change Listener |
public int showDialog(Instances inst){
setInstances(inst);
return showDialog();
}
| Pops up the modal dialog and waits for Cancel or OK. |
public void cancel(){
MsgManager.getInstance().clearMsg(this);
}
| Close the view if it's showing, or don't show it if it isn't showing yet. You do not normally have to call this. Normally view will disappear on its own after the appropriate duration. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.