code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
public static boolean hasNfc(final Context context){
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD_MR1) {
final NfcManager manager=(NfcManager)context.getSystemService(Context.NFC_SERVICE);
final NfcAdapter adapter=manager.getDefaultAdapter();
return (adapter != null && adapter.isEnabled());
}
return false;
}
| Tests if the device has NFC capability. |
private void process(){
log.fine("Start Rows=" + m_rows.size());
int gSize=groups.size();
int[] groupBys=new int[gSize];
Object[] groupBysValue=new Object[gSize];
Object INITVALUE=new Object();
for (int i=0; i < gSize; i++) {
groupBys[i]=groups.get(i).intValue();
groupBysValue[i]=INITVALUE;
log.fine("GroupBy level=" + i + " col="+ groupBys[i]);
}
if (gSize > 0) {
ArrayList<Object> newRow=new ArrayList<Object>();
for (int c=0; c < cols.size(); c++) newRow.add("");
m_rows.add(newRow);
}
int fSize=functions.size();
int[] funcCols=new int[fSize];
String[] funcFuns=new String[fSize];
int index=0;
Iterator<Integer> it=functions.keySet().iterator();
while (it.hasNext()) {
Object key=it.next();
funcCols[index]=((Integer)key).intValue();
funcFuns[index]=functions.get(key).toString();
log.fine("Function " + funcFuns[index] + " col="+ funcCols[index]);
index++;
}
BigDecimal[][] funcVals=new BigDecimal[fSize][gSize + 1];
int totalIndex=gSize;
log.fine("FunctionValues = [ " + fSize + " * "+ (gSize + 1)+ " ]");
for (int f=0; f < fSize; f++) for (int g=0; g < gSize + 1; g++) funcVals[f][g]=Env.ZERO;
rows.clear();
for (int r=0; r < m_rows.size(); r++) {
ArrayList<Object> row=m_rows.get(r);
boolean[] haveBreak=new boolean[groupBys.length];
for (int level=0; level < groupBys.length; level++) {
int idx=groupBys[level];
if (groupBysValue[level] == INITVALUE) haveBreak[level]=false;
else if (!groupBysValue[level].equals(row.get(idx))) haveBreak[level]=true;
else haveBreak[level]=false;
if (level > 0 && haveBreak[level - 1]) haveBreak[level]=true;
}
for (int level=groupBys.length - 1; level >= 0; level--) {
int idx=groupBys[level];
if (groupBysValue[level] == INITVALUE) groupBysValue[level]=row.get(idx);
else if (haveBreak[level]) {
ArrayList<Object> newRow=new ArrayList<Object>();
for (int c=0; c < cols.size(); c++) {
if (c == idx) {
if (groupBysValue[c] == null || groupBysValue[c].toString().length() == 0) newRow.add("=");
else newRow.add(groupBysValue[c]);
}
else {
boolean found=false;
for (int fc=0; fc < funcCols.length; fc++) {
if (c == funcCols[fc]) {
newRow.add(funcVals[fc][level]);
funcVals[fc][level]=Env.ZERO;
found=true;
}
}
if (!found) newRow.add(null);
}
}
m_groupRows.add(new Integer(rows.size()));
rows.add(newRow);
groupBysValue[level]=row.get(idx);
}
}
for (int fc=0; fc < funcCols.length; fc++) {
int col=funcCols[fc];
Object value=row.get(col);
BigDecimal bd=Env.ZERO;
if (value == null) ;
else if (value instanceof BigDecimal) bd=(BigDecimal)value;
else {
try {
bd=new BigDecimal(value.toString());
}
catch ( Exception e) {
}
}
for (int level=0; level < gSize + 1; level++) {
if (funcFuns[fc].equals(RModel.FUNCTION_SUM)) funcVals[fc][level]=funcVals[fc][level].add(bd);
else if (funcFuns[fc].equals(RModel.FUNCTION_COUNT)) funcVals[fc][level]=funcVals[fc][level].add(ONE);
}
}
rows.add(row);
}
if (functions.size() > 0) {
ArrayList<Object> newRow=new ArrayList<Object>();
for (int c=0; c < cols.size(); c++) {
boolean found=false;
for (int fc=0; fc < funcCols.length; fc++) {
if (c == funcCols[fc]) {
newRow.add(funcVals[fc][totalIndex]);
found=true;
}
}
if (!found) newRow.add(null);
}
if (gSize > 0) rows.remove(rows.size() - 1);
m_groupRows.add(new Integer(rows.size()));
rows.add(newRow);
}
log.fine("End Rows=" + rows.size());
m_rows.clear();
}
| Process Data Copy data in m_rows to rows and perform functions |
public void loadUrl(String url,JSONObject props) throws JSONException {
LOG.d("App","App.loadUrl(" + url + ","+ props+ ")");
int wait=0;
boolean openExternal=false;
boolean clearHistory=false;
HashMap<String,Object> params=new HashMap<String,Object>();
if (props != null) {
JSONArray keys=props.names();
for (int i=0; i < keys.length(); i++) {
String key=keys.getString(i);
if (key.equals("wait")) {
wait=props.getInt(key);
}
else if (key.equalsIgnoreCase("openexternal")) {
openExternal=props.getBoolean(key);
}
else if (key.equalsIgnoreCase("clearhistory")) {
clearHistory=props.getBoolean(key);
}
else {
Object value=props.get(key);
if (value == null) {
}
else if (value.getClass().equals(String.class)) {
params.put(key,(String)value);
}
else if (value.getClass().equals(Boolean.class)) {
params.put(key,(Boolean)value);
}
else if (value.getClass().equals(Integer.class)) {
params.put(key,(Integer)value);
}
}
}
}
if (wait > 0) {
try {
synchronized (this) {
this.wait(wait);
}
}
catch ( InterruptedException e) {
e.printStackTrace();
}
}
this.webView.showWebPage(url,openExternal,clearHistory,params);
}
| Load the url into the webview. |
public void or(Criteria criteria){
oredCriteria.add(criteria);
}
| This method was generated by MyBatis Generator. This method corresponds to the database table PUBLIC.SAMPLETABLE1 |
public XmlReplacement(String file,String xpathExpression,String attributeName,Boolean ignoreIfNonExisting,String value){
this.file=file;
this.xpathExpression=xpathExpression;
this.attributeName=attributeName;
this.ignoreIfNonExisting=ignoreIfNonExisting;
this.value=value;
}
| Saves the attributes for this XML replacement. |
public boolean isEmpty(){
return parameters.isEmpty();
}
| Determine whether or not this list is empty. |
public static boolean vPoolSpecifiesFileReplication(final VirtualPool virtualPool){
return (virtualPool.getFileReplicationType() != null && FileReplicationType.validFileReplication(virtualPool.getFileReplicationType()));
}
| Returns whether or not the passed VirtualPool specifies Protection |
public void bar(@Nullable Object o){
}
| the only difference with DoesntWork.foo() is that the parameter is annotated as Nullable |
private void initAtpTab(){
m_tableAtp=ListboxFactory.newDataTable();
m_tableAtp.setMultiSelection(false);
ArrayList<Info_Column> list=new ArrayList<Info_Column>();
list.add(new Info_Column(" ","M_Product_ID",IDColumn.class));
list.add(new Info_Column(Msg.translate(Env.getCtx(),"M_Warehouse_ID"),"Warehouse",String.class));
list.add(new Info_Column(Msg.translate(Env.getCtx(),"M_Locator_ID"),"Locator",String.class));
list.add(new Info_Column(Msg.getMsg(Env.getCtx(),"Date",true),"Date",Timestamp.class));
list.add(new Info_Column(Msg.translate(Env.getCtx(),"QtyAvailable"),"QtyAvailable",Double.class,true,true,null));
list.add(new Info_Column(Msg.translate(Env.getCtx(),"QtyOnHand"),"QtyOnHand",Double.class));
list.add(new Info_Column(Msg.getMsg(Env.getCtx(),"ExpectedChange",true),"DeltaQty",Double.class));
list.add(new Info_Column(Msg.translate(Env.getCtx(),"C_BPartner_ID"),"BP_Name",String.class));
list.add(new Info_Column(Msg.translate(Env.getCtx(),"QtyOrdered"),"QtyOrdered",Double.class));
list.add(new Info_Column(Msg.translate(Env.getCtx(),"QtyReserved"),"QtyReserved",Double.class));
list.add(new Info_Column(Msg.translate(Env.getCtx(),"M_AttributeSetInstance_ID"),"PASI",String.class));
list.add(new Info_Column(Msg.translate(Env.getCtx(),"DocumentNo"),"DocumentNo",String.class));
m_layoutATP=new Info_Column[list.size()];
list.toArray(m_layoutATP);
}
| Query ATP |
public static int listFindNoCase(String list,String value,String delimiter,boolean trim){
Array arr=trim ? listToArrayTrim(list,delimiter) : listToArray(list,delimiter);
int len=arr.size();
for (int i=1; i <= len; i++) {
if (((String)arr.get(i,"")).equalsIgnoreCase(value)) return i - 1;
}
return -1;
}
| finds a value inside a list, do not ignore case |
public TargetInformationReply(final int packetId,final int errorCode,final TargetInformation targetInformation){
super(packetId,errorCode);
if (success()) {
Preconditions.checkNotNull(targetInformation,"IE01053: Target information argument can not be null");
}
else {
if (targetInformation != null) {
throw new IllegalArgumentException("IE01074: Target information must be null");
}
}
this.targetInformation=targetInformation;
}
| Creates a new target information reply. |
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 Document read(File file) throws DocumentException, IOException, XmlPullParserException {
String systemID=file.getAbsolutePath();
return read(new BufferedReader(new FileReader(file)),systemID);
}
| <p> Reads a Document from the given <code>File</code> </p> |
public void dequeueGroupFileInfo(String fileTransferId,String fileInfo,boolean displayedReportEnabled,boolean deliveredReportEnabled,GroupFileTransferImpl groupFileTransfer) throws PayloadException, NetworkException, SessionNotEstablishedException {
GroupChatSession session=mImService.getGroupChatSession(mChatId);
if (session == null) {
mImService.rejoinGroupChatAsPartOfSendOperation(mChatId);
}
else if (session.isMediaEstablished()) {
session.sendFileInfo(groupFileTransfer,fileTransferId,fileInfo,displayedReportEnabled,deliveredReportEnabled);
}
else if (session.isInitiatedByRemote()) {
if (sLogger.isActivated()) {
sLogger.debug("Group chat session with chatId '" + mChatId + "' is pending for acceptance, accept it.");
}
session.acceptSession();
}
else {
throw new SessionNotEstablishedException("The existing group chat session with chatId '" + mChatId + "' is not established right now!");
}
}
| Dequeue group file info |
public static void parser(PrintStream out,parse_action_table action_table,parse_reduce_table reduce_table,int start_st,production start_prod,boolean compact_reduces) throws internal_error {
long start_time=System.currentTimeMillis();
out.println();
out.println("//----------------------------------------------------");
out.println("// The following code was generated by " + version.title_str);
out.println("// " + new Date());
out.println("//----------------------------------------------------");
out.println();
emit_package(out);
for (int i=0; i < import_list.size(); i++) out.println("import " + import_list.elementAt(i) + ";");
out.println();
out.println("public class " + parser_class_name + " extends java_cup.runtime.lr_parser {");
out.println();
out.println(" /** constructor */");
out.println(" public " + parser_class_name + "() {super();}");
emit_production_table(out);
do_action_table(out,action_table,compact_reduces);
do_reduce_table(out,reduce_table);
out.println(" /** instance of action encapsulation class */");
out.println(" protected " + pre("actions") + " action_obj;");
out.println();
out.println(" /** action encapsulation object initializer */");
out.println(" protected void init_actions()");
out.println(" {");
out.println(" action_obj = new " + pre("actions") + "();");
out.println(" }");
out.println();
out.println(" /** invoke a user supplied parse action */");
out.println(" public java_cup.runtime.symbol do_action(");
out.println(" int act_num,");
out.println(" java_cup.runtime.lr_parser parser,");
out.println(" java.util.Stack stack,");
out.println(" int top)");
out.println(" throws java.lang.Exception");
out.println(" {");
out.println(" /* call code in generated class */");
out.println(" return action_obj." + pre("do_action(") + "act_num, parser, stack, top);");
out.println(" }");
out.println("");
out.println(" /** start state */");
out.println(" public int start_state() {return " + start_st + ";}");
out.println(" /** start production */");
out.println(" public int start_production() {return " + start_production.index() + ";}");
out.println();
out.println(" /** EOF symbol index */");
out.println(" public int EOF_sym() {return " + terminal.EOF.index() + ";}");
out.println();
out.println(" /** error symbol index */");
out.println(" public int error_sym() {return " + terminal.error.index() + ";}");
out.println();
if (init_code != null) {
out.println();
out.println(" /** user initialization */");
out.println(" public void user_init() throws java.lang.Exception");
out.println(" {");
out.println(init_code);
out.println(" }");
}
if (scan_code != null) {
out.println();
out.println(" /** scan to get the next token */");
out.println(" public java_cup.runtime.token scan()");
out.println(" throws java.lang.Exception");
out.println(" {");
out.println(scan_code);
out.println(" }");
}
if (parser_code != null) {
out.println();
out.println(parser_code);
}
out.println("};");
emit_action_code(out,start_prod);
parser_time=System.currentTimeMillis() - start_time;
}
| Emit the parser subclass with embedded tables. |
public void addVideoSharingInvitationRejected(ContactId contact,VideoContent content,ReasonCode reasonCode,long timestamp){
String sessionId=SessionIdGenerator.getNewId();
mRichCallLog.addVideoSharing(sessionId,contact,Direction.INCOMING,content,VideoSharing.State.REJECTED,reasonCode,timestamp);
mBroadcaster.broadcastInvitation(sessionId);
}
| Add and broadcast video sharing invitation rejections |
public MJournal reverseCorrectIt(int GL_JournalBatch_ID){
log.info(toString());
MJournal reverse=new MJournal(this);
reverse.setGL_JournalBatch_ID(GL_JournalBatch_ID);
reverse.setDateDoc(getDateDoc());
reverse.setC_Period_ID(getC_Period_ID());
reverse.setDateAcct(getDateAcct());
reverse.addDescription("(->" + getDocumentNo() + ")");
reverse.setReversal_ID(getGL_Journal_ID());
if (!reverse.save()) return null;
addDescription("(" + reverse.getDocumentNo() + "<-)");
reverse.copyLinesFrom(this,null,'C');
setProcessed(true);
setReversal_ID(reverse.getGL_Journal_ID());
setDocAction(DOCACTION_None);
return reverse;
}
| Reverse Correction. As if nothing happened - same date |
private void initLocation(){
MCountry country=m_location.getCountry();
log.fine(country.getName() + ", Region=" + country.isHasRegion()+ " "+ country.getCaptureSequence()+ ", C_Location_ID="+ m_location.getC_Location_ID());
if (country.getC_Country_ID() != s_oldCountry_ID) {
fRegion.removeAllItems();
if (country.isHasRegion()) {
for ( MRegion region : MRegion.getRegions(Env.getCtx(),country.getC_Country_ID())) {
fRegion.addItem(region);
}
if (m_location.getCountry().get_Translation(MCountry.COLUMNNAME_RegionName) != null && m_location.getCountry().get_Translation(MCountry.COLUMNNAME_RegionName).trim().length() > 0) lRegion.setText(m_location.getCountry().get_Translation(MCountry.COLUMNNAME_RegionName));
else lRegion.setText(Msg.getMsg(Env.getCtx(),"Region"));
}
s_oldCountry_ID=m_location.getC_Country_ID();
}
if (m_location.getC_Region_ID() > 0 && m_location.getC_Region().getC_Country_ID() == country.getC_Country_ID()) {
fRegion.setSelectedItem(m_location.getC_Region());
}
else {
fRegion.setSelectedItem(null);
m_location.setC_Region_ID(0);
}
if (country.isHasRegion() && m_location.getC_Region_ID() > 0) {
Env.setContext(Env.getCtx(),m_WindowNo,Env.TAB_INFO,"C_Region_ID",String.valueOf(m_location.getC_Region_ID()));
}
else {
Env.setContext(Env.getCtx(),m_WindowNo,Env.TAB_INFO,"C_Region_ID","0");
}
Env.setContext(Env.getCtx(),m_WindowNo,Env.TAB_INFO,"C_Country_ID",String.valueOf(country.get_ID()));
fCityAutoCompleter.fillList();
gbc.anchor=GridBagConstraints.NORTHWEST;
gbc.gridy=0;
gbc.gridx=0;
gbc.gridwidth=1;
gbc.insets=fieldInsets;
gbc.fill=GridBagConstraints.HORIZONTAL;
gbc.weightx=0;
gbc.weighty=0;
mainPanel.removeAll();
mainPanel.add(Box.createVerticalStrut(5),gbc);
int line=1;
String ds=country.getCaptureSequence();
if (ds == null || ds.length() == 0) {
log.log(Level.SEVERE,"CaptureSequence empty - " + country);
ds="";
}
isCityMandatory=false;
isRegionMandatory=false;
isAddress1Mandatory=false;
isAddress2Mandatory=false;
isAddress3Mandatory=false;
isAddress4Mandatory=false;
isPostalMandatory=false;
isPostalAddMandatory=false;
StringTokenizer st=new StringTokenizer(ds,"@",false);
while (st.hasMoreTokens()) {
String s=st.nextToken();
if (s.startsWith("CO")) {
addLine(line++,lCountry,fCountry);
if (m_location.getCountry().isPostcodeLookup()) {
addLine(line++,lOnline,fOnline);
}
}
else if (s.startsWith("A1")) {
addLine(line++,lAddress1,fAddress1);
isAddress1Mandatory=s.endsWith("!");
}
else if (s.startsWith("A2")) {
addLine(line++,lAddress2,fAddress2);
isAddress2Mandatory=s.endsWith("!");
}
else if (s.startsWith("A3")) {
addLine(line++,lAddress3,fAddress3);
isAddress3Mandatory=s.endsWith("!");
}
else if (s.startsWith("A4")) {
addLine(line++,lAddress4,fAddress4);
isAddress4Mandatory=s.endsWith("!");
}
else if (s.startsWith("C")) {
addLine(line++,lCity,fCity);
isCityMandatory=s.endsWith("!");
}
else if (s.startsWith("P")) {
addLine(line++,lPostal,fPostal);
isPostalMandatory=s.endsWith("!");
}
else if (s.startsWith("A")) {
addLine(line++,lPostalAdd,fPostalAdd);
isPostalAddMandatory=s.endsWith("!");
}
else if (s.startsWith("R") && m_location.getCountry().isHasRegion()) {
addLine(line++,lRegion,fRegion);
isRegionMandatory=s.endsWith("!");
}
}
if (m_location.getC_Location_ID() != 0) {
fAddress1.setText(m_location.getAddress1());
fAddress2.setText(m_location.getAddress2());
fAddress3.setText(m_location.getAddress3());
fAddress4.setText(m_location.getAddress4());
fCity.setText(m_location.getCity());
fPostal.setText(m_location.getPostal());
fPostalAdd.setText(m_location.getPostal_Add());
if (m_location.getCountry().isHasRegion()) {
if (m_location.getCountry().get_Translation(MCountry.COLUMNNAME_RegionName) != null && m_location.getCountry().get_Translation(MCountry.COLUMNNAME_RegionName).trim().length() > 0) lRegion.setText(m_location.getCountry().get_Translation(MCountry.COLUMNNAME_RegionName));
else lRegion.setText(Msg.getMsg(Env.getCtx(),"Region"));
fRegion.setSelectedItem(m_location.getRegion());
}
if (!fCountry.getSelectedItem().equals(country)) fCountry.setSelectedItem(country);
}
pack();
}
| Dynamic Init & fill fields - Called when Country changes! |
public synchronized void onGlobalCounterChanged(int value){
globalCounter.change(value);
if (!isAppVisible.get()) {
globalTempCounter.change(value);
}
}
| Notify from Modules about global counters changed |
@NotNull private Collection<PyPresenterTestMemberEntry> launchAndGetMembers(@NotNull final String classUnderRefactoring,@NotNull final String destinationClass){
final PyPullUpPresenterImpl sut=configureByClass(classUnderRefactoring);
EasyMock.expect(myView.getSelectedParent()).andReturn(getClassByName(destinationClass)).anyTimes();
myMocksControl.replay();
sut.launch();
return getMembers();
}
| Launches presenter and returns members it displayed to user |
public static String toString(final byte[] input,final String encoding) throws IOException {
return new String(input,Charsets.toCharset(encoding));
}
| Get the contents of a <code>byte[]</code> as a String using the specified character encoding. <p> Character encoding names can be found at <a href="http://www.iana.org/assignments/character-sets">IANA</a>. |
public void initTuner(boolean controlI2C) throws UsbException {
writeDemodRegister(mDeviceHandle,Page.ONE,(short)0xB1,(short)0x1A,1);
writeDemodRegister(mDeviceHandle,Page.ZERO,(short)0x08,(short)0x4D,1);
setIFFrequency(R820T_IF_FREQUENCY);
writeDemodRegister(mDeviceHandle,Page.ONE,(short)0x15,(short)0x01,1);
initializeRegisters(controlI2C);
setTVStandard(controlI2C);
systemFrequencySelect(0,controlI2C);
}
| Initializes the tuner section. |
public FrInterruptRequest(int interruptNumber,boolean NMI,int icr){
this.interruptNumber=interruptNumber;
isNMI=NMI;
this.icr=icr;
}
| Create an Interrupt Request |
protected boolean storeSecretKey(Context context,String keystoreAlias,SecretKey secretKey){
SharedPreferences.Editor editor=getSharedPreferences(context).edit();
if (secretKey == null) {
editor.remove(getSharedPreferenceKey(keystoreAlias));
editor.apply();
return true;
}
else {
try {
byte[] wrappedKey=mSecretKeyWrapper.wrap(secretKey);
String encoded=Base64.encodeToString(wrappedKey,Base64.DEFAULT);
editor.putString(getSharedPreferenceKey(keystoreAlias),encoded);
editor.apply();
return true;
}
catch ( GeneralSecurityException|IOException|RuntimeException e) {
Log.e(TAG,"save failed",e);
}
}
return false;
}
| Use the SecretKeyWrapper secure storage to write the key in a securely wrapped format |
public int costInline(int thresh,Environment env,Context ctx){
if (implementation != null) return implementation.costInline(thresh,env,ctx);
if (ctx == null) {
return 3 + ((right == null) ? 0 : right.costInline(thresh,env,ctx));
}
ClassDefinition ctxClass=ctx.field.getClassDefinition();
try {
if (ctxClass.permitInlinedAccess(env,field.getClassDeclaration()) && ctxClass.permitInlinedAccess(env,field)) {
if (right == null) {
return 3;
}
else {
ClassDeclaration rt=env.getClassDeclaration(right.type);
if (ctxClass.permitInlinedAccess(env,rt)) {
return 3 + right.costInline(thresh,env,ctx);
}
}
}
}
catch ( ClassNotFound e) {
}
return thresh;
}
| The cost of inlining this expression |
public void testDetectLanguageHe(){
LOGGER.debug("detectLanguage he");
LanguageDetector instance=LanguageDetector.getInstance();
Document doc;
try {
doc=Jsoup.parse(new File(PATH + "he.wikipedia.org-wiki_20140701.html"),UTF_8);
LOGGER.debug("start detection");
assertEquals("he",instance.detectLanguage(doc.text()).getDetectedLanguage());
assertEquals("he",instance.detectLanguage(doc.text().toLowerCase()).getDetectedLanguage());
assertEquals("he",instance.detectLanguage(doc.text().toUpperCase()).getDetectedLanguage());
LOGGER.debug("detection ended");
}
catch ( IOException ex) {
LOGGER.error(ex);
}
catch ( NullPointerException npe) {
LOGGER.error("error while fetching page " + npe);
}
}
| Test of detectLanguage method, of class LanguageDetector with he pages. |
public static String urlEncodeArgs(Map<String,? extends Object> args){
return urlEncodeArgs(args,true);
}
| URL Encodes a Map of arguements |
private IFolder createFolder(IFolder folderHandle,IProgressMonitor monitor) throws CoreException {
folderHandle.create(false,true,monitor);
if (monitor.isCanceled()) {
throw new OperationCanceledException();
}
return folderHandle;
}
| Creates a folder resource for the given folder handle. |
public void handleException(ParseException ex,SIPMessage sipMessage,Class hdrClass,String header,String message) throws ParseException {
if (sipStack.isLoggingEnabled()) sipStack.getStackLogger().logException(ex);
if ((hdrClass != null) && (hdrClass.equals(From.class) || hdrClass.equals(To.class) || hdrClass.equals(CSeq.class)|| hdrClass.equals(Via.class)|| hdrClass.equals(CallID.class)|| hdrClass.equals(RequestLine.class)|| hdrClass.equals(StatusLine.class))) {
if (sipStack.isLoggingEnabled()) {
sipStack.getStackLogger().logDebug("Encountered Bad Message \n" + sipMessage.toString());
}
String msgString=sipMessage.toString();
if (!msgString.startsWith("SIP/") && !msgString.startsWith("ACK ")) {
SIPMessage badReqRes=createBadReqRes(msgString,ex);
if (badReqRes != null) {
if (sipStack.isLoggingEnabled()) {
sipStack.getStackLogger().logDebug("Sending automatic 400 Bad Request:");
sipStack.getStackLogger().logDebug(msgString);
}
try {
this.sendMessage(badReqRes,this.getPeerInetAddress(),this.getPeerPort(),false);
}
catch ( IOException e) {
if (sipStack.isLoggingEnabled()) this.sipStack.getStackLogger().logException(e);
}
}
else {
if (sipStack.isLoggingEnabled()) {
sipStack.getStackLogger().logDebug("Could not formulate automatic 400 Bad Request");
}
}
}
throw ex;
}
else {
sipMessage.addUnparsed(header);
}
}
| Exception processor for exceptions detected from the parser. (This is invoked by the parser when an error is detected). |
@Override public void run(){
amIActive=true;
String inputHeader=null;
String outputHeader=null;
int row, col;
double z;
double noData;
int progress;
int i;
double minVal, maxVal;
int numBins=1024;
if (args.length <= 0) {
showFeedback("Plugin parameters have not been set.");
return;
}
inputHeader=args[0];
outputHeader=args[1];
minVal=Double.parseDouble(args[2]);
maxVal=Double.parseDouble(args[3]);
numBins=Integer.parseInt(args[4]);
int numBinsLessOne=numBins - 1;
if ((inputHeader == null) || (outputHeader == null)) {
showFeedback("One or more of the input parameters have not been set properly.");
return;
}
try {
WhiteboxRaster image=new WhiteboxRaster(inputHeader,"r");
int nRows=image.getNumberRows();
int nCols=image.getNumberColumns();
noData=image.getNoDataValue();
double scaleFactor=numBins / (maxVal - minVal);
WhiteboxRaster output=new WhiteboxRaster(outputHeader,"rw",inputHeader,WhiteboxRaster.DataType.INTEGER,noData);
output.setPreferredPalette(image.getPreferredPalette());
double[] data=null;
for (row=0; row < nRows; row++) {
data=image.getRowValues(row);
for (col=0; col < nCols; col++) {
if (data[col] != noData) {
z=(int)(data[col] - minVal) * scaleFactor;
if (z < 0) {
z=0;
}
if (z > numBinsLessOne) {
z=numBinsLessOne;
}
output.setValue(row,col,z);
}
else {
output.setValue(row,col,noData);
}
}
if (cancelOp) {
cancelOperation();
return;
}
progress=(int)(100f * row / (nRows - 1));
updateProgress(progress);
}
image.close();
output.addMetadataEntry("Created by the " + getDescriptiveName() + " tool.");
output.addMetadataEntry("Created on " + new Date());
output.close();
returnData(outputHeader);
}
catch ( OutOfMemoryError oe) {
myHost.showFeedback("An out-of-memory error has occurred during operation.");
}
catch ( Exception e) {
myHost.showFeedback("An error has occurred during operation. See log file for details.");
myHost.logException("Error in " + getDescriptiveName(),e);
showFeedback(e.getMessage());
}
finally {
updateProgress("Progress: ",0);
amIActive=false;
myHost.pluginComplete();
}
}
| Used to execute this plugin tool. |
protected CommandOutput receiveOutput(String shellId,String commandId) throws WinRMException {
StrBuilder stdout=new StrBuilder();
StrBuilder stderr=new StrBuilder();
int exitCode=0;
int sequenceId=0;
boolean done=false;
while (!done) {
ReceiveData data=newReceiveOutput(shellId,commandId,sequenceId).execute();
stdout.append(data.getStdout());
stderr.append(data.getStderr());
if (data.getExitCode() != null) {
exitCode=data.getExitCode();
}
done=data.isDone();
sequenceId++;
}
return new CommandOutput(stdout.toString(),stderr.toString(),exitCode);
}
| Receives output from the remote shell command. |
@SuppressWarnings("unchecked") public SimpleLexicon(short[] numSubStates,int smoothingCutoff,double[] smoothParam,Smoother smoother,double threshold,StateSetTreeList trainTrees){
this(numSubStates,threshold);
init(trainTrees);
}
| Create a blank Lexicon object. Fill it by calling tallyStateSetTree for each training tree, then calling optimize(). |
public Object runSafely(Catbert.FastStack stack) throws Exception {
if (stack.getUIMgrSafe() == null) return null;
PseudoMenu currUI=stack.getUIMgrSafe().getCurrUI();
if (currUI != null) currUI.repaint();
return null;
}
| Redraws all UI elements on the current menu |
public String toString(){
int old=data.position();
try {
data.position(0);
return data.asCharBuffer().toString();
}
finally {
data.position(old);
}
}
| Return string representation of the array's contents. |
public void writeEnum(final int fieldNumber,final int value) throws IOException {
writeTag(fieldNumber,WireFormat.WIRETYPE_VARINT);
writeEnumNoTag(value);
}
| Write an enum field, including tag, to the stream. Caller is responsible for converting the enum value to its numeric value. |
public Bindings add(String property,JComboBox combo,int defaultValue){
combo.addActionListener(this);
return add(new JComboBoxBinding(property,combo,defaultValue));
}
| Handles JComboBox |
public SuffixText(Composite parent,int style){
super(parent,style);
this.setLayout(new SuffixLayout());
suffixText=createSuffixText();
editableText=new Text(this,SWT.NONE);
configureListeners();
this.setBackground(getDisplay().getSystemColor(SWT.COLOR_LIST_BACKGROUND));
this.setCursor(getDisplay().getSystemCursor(SWT.CURSOR_IBEAM));
}
| Create the suffix text. |
Writer write(Writer writer,int indentFactor,int indent) throws JSONException {
try {
boolean commanate=false;
final int length=this.length();
Iterator keys=this.keys();
writer.write('{');
if (length == 1) {
Object key=keys.next();
writer.write(quote(key.toString()));
writer.write(':');
if (indentFactor > 0) {
writer.write(' ');
}
writeValue(writer,this.map.get(key),indentFactor,indent);
}
else if (length != 0) {
final int newindent=indent + indentFactor;
while (keys.hasNext()) {
Object key=keys.next();
if (commanate) {
writer.write(',');
}
if (indentFactor > 0) {
writer.write('\n');
}
indent(writer,newindent);
writer.write(quote(key.toString()));
writer.write(':');
if (indentFactor > 0) {
writer.write(' ');
}
writeValue(writer,this.map.get(key),indentFactor,newindent);
commanate=true;
}
if (indentFactor > 0) {
writer.write('\n');
}
indent(writer,indent);
}
writer.write('}');
return writer;
}
catch ( IOException exception) {
throw new JSONException(exception);
}
}
| Write the contents of the JSONObject as JSON text to a writer. For compactness, no whitespace is added. <p> Warning: This method assumes that the data structure is acyclical. |
protected boolean[] instanceWeights(boolean nominalPredictor,boolean numericPredictor,boolean stringPredictor,boolean datePredictor,boolean relationalPredictor,boolean multiInstance){
print("clusterer uses instance weights");
printAttributeSummary(nominalPredictor,numericPredictor,stringPredictor,datePredictor,relationalPredictor,multiInstance);
print("...");
int numTrain=2 * getNumInstances(), missingLevel=0;
boolean predictorMissing=false;
boolean[] result=new boolean[2];
Instances train=null;
Clusterer[] clusterers=null;
ClusterEvaluation evaluationB=null;
ClusterEvaluation evaluationI=null;
boolean built=false;
boolean evalFail=false;
try {
train=makeTestDataset(42,numTrain,nominalPredictor ? getNumNominal() + 1 : 0,numericPredictor ? getNumNumeric() + 1 : 0,stringPredictor ? getNumString() : 0,datePredictor ? getNumDate() : 0,relationalPredictor ? getNumRelational() : 0,multiInstance);
if (nominalPredictor && !multiInstance) {
train.deleteAttributeAt(0);
}
if (missingLevel > 0) {
addMissing(train,missingLevel,predictorMissing);
}
clusterers=AbstractClusterer.makeCopies(getClusterer(),2);
evaluationB=new ClusterEvaluation();
evaluationI=new ClusterEvaluation();
clusterers[0].buildClusterer(train);
evaluationB.setClusterer(clusterers[0]);
}
catch ( Exception ex) {
throw new Error("Error setting up for tests: " + ex.getMessage());
}
try {
for (int i=0; i < train.numInstances(); i++) {
train.instance(i).setWeight(0);
}
Random random=new Random(1);
for (int i=0; i < train.numInstances() / 2; i++) {
int inst=Math.abs(random.nextInt()) % train.numInstances();
int weight=Math.abs(random.nextInt()) % 10 + 1;
train.instance(inst).setWeight(weight);
}
clusterers[1].buildClusterer(train);
built=true;
evaluationI.setClusterer(clusterers[1]);
if (evaluationB.equals(evaluationI)) {
evalFail=true;
throw new Exception("evalFail");
}
println("yes");
result[0]=true;
}
catch ( Exception ex) {
println("no");
result[0]=false;
if (m_Debug) {
println("\n=== Full Report ===");
if (evalFail) {
println("Results don't differ between non-weighted and " + "weighted instance models.");
println("Here are the results:\n");
println("\nboth methods\n");
println(evaluationB.clusterResultsToString());
}
else {
print("Problem during");
if (built) {
print(" testing");
}
else {
print(" training");
}
println(": " + ex.getMessage() + "\n");
}
println("Here is the dataset:\n");
println("=== Train Dataset ===\n" + train.toString() + "\n");
println("=== Train Weights ===\n");
for (int i=0; i < train.numInstances(); i++) {
println(" " + (i + 1) + " "+ train.instance(i).weight());
}
}
}
return result;
}
| Checks whether the clusterer can handle instance weights. This test compares the clusterer performance on two datasets that are identical except for the training weights. If the results change, then the clusterer must be using the weights. It may be possible to get a false positive from this test if the weight changes aren't significant enough to induce a change in clusterer performance (but the weights are chosen to minimize the likelihood of this). |
public void mutableMultiply(double c){
for ( KernelPoint kp : points) kp.mutableMultiply(c);
}
| Alters all the KernelPoint objects contained in this set by the same constant value |
protected void paintComponent(Graphics g){
if (ui != null) {
Graphics scratchGraphics=(g == null) ? null : g.create();
try {
ui.update(scratchGraphics,this);
}
finally {
scratchGraphics.dispose();
}
}
}
| Calls the UI delegate's paint method, if the UI delegate is non-<code>null</code>. We pass the delegate a copy of the <code>Graphics</code> object to protect the rest of the paint code from irrevocable changes (for example, <code>Graphics.translate</code>). <p> If you override this in a subclass you should not make permanent changes to the passed in <code>Graphics</code>. For example, you should not alter the clip <code>Rectangle</code> or modify the transform. If you need to do these operations you may find it easier to create a new <code>Graphics</code> from the passed in <code>Graphics</code> and manipulate it. Further, if you do not invoker super's implementation you must honor the opaque property, that is if this component is opaque, you must completely fill in the background in a non-opaque color. If you do not honor the opaque property you will likely see visual artifacts. <p> The passed in <code>Graphics</code> object might have a transform other than the identify transform installed on it. In this case, you might get unexpected results if you cumulatively apply another transform. |
protected Object createElementInfo(){
return new JarPackageFragmentRootInfo();
}
| Returns a new element info for this element. |
public synchronized static boolean removeGlobalUnitConverter(UnitConverter unit){
return CONVERTERS.remove(unit);
}
| Removed the converter. |
private void hideActionBarIfNeeded(){
ActionBar actionBar=getActionBar();
if (actionBar != null && !isHardwareKeyboardPresent() && mHideActionBarOnSoftKeyboardUp && mIsKeyboardOpen && actionBar.isShowing()) {
getActionBar().hide();
}
}
| Hide the action bar if needed. |
public static double sin(double a){
return 0.0d;
}
| Returns the trigonometric sine of an angle. Special cases: If the argument is NaN or an infinity, then the result is NaN. If the argument is positive zero, then the result is positive zero; if the argument is negative zero, then the result is negative zero. |
public boolean isShowFlowgraphViews(){
return m_flowgraphViewsCheckbox.isSelected();
}
| Returns whether flow graph views should be shown. |
@Override public ModbusRequest readRequest(AbstractModbusListener listener) throws ModbusIOException {
ModbusRequest req;
try {
byteInputStream.reset();
synchronized (byteInputStream) {
byte[] buffer=byteInputStream.getBuffer();
if (!headless) {
if (dataInputStream.read(buffer,0,6) == -1) {
throw new EOFException("Premature end of stream (Header truncated)");
}
int transaction=ModbusUtil.registerToShort(buffer,0) & 0x0000FFFF;
int protocol=ModbusUtil.registerToShort(buffer,2);
int count=ModbusUtil.registerToShort(buffer,4);
if (dataInputStream.read(buffer,6,count) == -1) {
throw new ModbusIOException("Premature end of stream (Message truncated)");
}
logger.debug("Read: {}",ModbusUtil.toHex(buffer,0,count + 6));
byteInputStream.reset(buffer,(6 + count));
byteInputStream.skip(6);
int unit=byteInputStream.readByte();
int functionCode=byteInputStream.readUnsignedByte();
byteInputStream.reset();
req=ModbusRequest.createModbusRequest(functionCode);
req.setUnitID(unit);
req.setHeadless(false);
req.setTransactionID(transaction);
req.setProtocolID(protocol);
req.setDataLength(count);
req.readFrom(byteInputStream);
}
else {
int unit=dataInputStream.readByte();
int function=dataInputStream.readByte();
req=ModbusRequest.createModbusRequest(function);
req.setUnitID(unit);
req.setHeadless(true);
req.readData(dataInputStream);
dataInputStream.readShort();
if (logger.isDebugEnabled()) {
logger.debug("Read: {}",req.getHexMessage());
}
}
}
return req;
}
catch ( EOFException eoex) {
throw new ModbusIOException("End of File",true);
}
catch ( SocketTimeoutException x) {
throw new ModbusIOException("Timeout reading request",x);
}
catch ( SocketException sockex) {
throw new ModbusIOException("Socket Exception",sockex);
}
catch ( IOException ex) {
throw new ModbusIOException("I/O exception - failed to read",ex);
}
}
| readRequest -- Read a Modbus TCP encoded request. The packet has a 6 byte header containing the protocol, transaction ID and length. |
public BackButtonBuilder<T> backButton(String text){
if (!(parent instanceof SubInlineMenuBuilder)) {
throw new UnsupportedOperationException("Back buttons are only allowed for sub menus!");
}
return new BackButtonBuilder<>(this,buttons().size(),text);
}
| Creates a new back button builder with provided text |
public static void deinitialize(){
INSTANCE.codenameOneRunning=false;
synchronized (lock) {
lock.notifyAll();
}
}
| Closes down the EDT and Codename One, under normal conditions this method is completely unnecessary since exiting the application will shut down Codename One. However, if the application is minimized and the user wishes to free all resources without exiting the application then this method can be used. Once this method is used Codename One will no longer work and Display.init(Object) should be invoked again for any further Codename One call! Notice that minimize (being a Codename One method) MUST be invoked before invoking this method! |
@Path(TriggerCommonParams.PATH_PROCESSES) public Process redirectToProcess(){
return new Process();
}
| Redirects to trigger process endpoints |
public DateMidnight withWeekyear(int weekyear){
return withMillis(getChronology().weekyear().set(getMillis(),weekyear));
}
| Returns a copy of this date with the weekyear field updated. <p> The weekyear is the year that matches with the weekOfWeekyear field. In the standard ISO8601 week algorithm, the first week of the year is that in which at least 4 days are in the year. As a result of this definition, day 1 of the first week may be in the previous year. The weekyear allows you to query the effective year for that day. <p> DateMidnight is immutable, so there are no set methods. Instead, this method returns a new instance with the value of weekyear changed. |
void paintComponent(Graphics g){
RectangularShape rectangle;
int radius=RapidLookAndFeel.CORNER_DEFAULT_RADIUS;
switch (position) {
case SwingConstants.LEFT:
rectangle=new RoundRectangle2D.Double(0,0,button.getWidth() + radius,button.getHeight(),radius,radius);
break;
case SwingConstants.CENTER:
rectangle=new Rectangle2D.Double(0,0,button.getWidth(),button.getHeight());
break;
default :
rectangle=new RoundRectangle2D.Double(-radius,0,button.getWidth() + radius,button.getHeight(),radius,radius);
break;
}
RapidLookTools.drawButton(button,g,rectangle);
}
| Draws the component background. |
public void add(String key,String value){
String k=normalize(key);
List<String> l=map.get(k);
if (l == null) {
l=new LinkedList<String>();
map.put(k,l);
}
l.add(value);
}
| adds the given value to the list of headers for the given key. If the mapping does not already exist, then it is created |
public void startElement(String elementNamespaceURI,String elementLocalName,String elementName) throws SAXException {
super.startElement(elementNamespaceURI,elementLocalName,elementName);
}
| From XSLTC |
public List subList(int fromIndex,int toIndex){
throw new UnsupportedOperationException();
}
| <b>Not supported</b> - Throws <tt>UnsupportedOperationException</tt> exception. |
public PaintContext createContext(ColorModel cm,Rectangle deviceBounds,Rectangle2D userBounds,AffineTransform xform,RenderingHints hints){
if (patternTransform != null) {
xform=new AffineTransform(xform);
xform.concatenate(patternTransform);
}
if ((lastContext != null) && lastContext.getColorModel().equals(cm)) {
double[] p=new double[6];
double[] q=new double[6];
xform.getMatrix(p);
lastContext.getUsr2Dev().getMatrix(q);
if ((p[0] == q[0]) && (p[1] == q[1]) && (p[2] == q[2])&& (p[3] == q[3])) {
if ((p[4] == q[4]) && (p[5] == q[5])) return lastContext;
else return new PatternPaintContextWrapper(lastContext,(int)(q[4] - p[4] + 0.5),(int)(q[5] - p[5] + 0.5));
}
}
lastContext=new PatternPaintContext(cm,xform,hints,tile,patternRegion,overflow);
return lastContext;
}
| Creates and returns a context used to generate the pattern. |
public DefaultResourceLoader(ClassLoader classLoader){
this.classLoader=classLoader;
}
| Create a new DefaultResourceLoader. |
@Override protected boolean showCriteriaParameter(){
return false;
}
| Returns false. |
private boolean hasMatchingDo(){
Assert.isTrue(fToken == Symbols.TokenWHILE);
nextToken();
switch (fToken) {
case Symbols.TokenRBRACE:
skipScope();
case Symbols.TokenSEMICOLON:
skipToStatementStart(false,false);
return fToken == Symbols.TokenDO;
}
return false;
}
| while(condition); is ambiguous when parsed backwardly, as it is a valid statement by its own, so we have to check whether there is a matching do. A <code>do</code> can either be separated from the while by a block, or by a single statement, which limits our search distance. |
public void trim(final int ego){
this.alters[ego].trim();
}
| Memory optimisation: shrinks storing arrays so that they do not contain unused slots. |
public static void main(String... a) throws Exception {
TestBase.createCaller().init().test();
}
| Run just this test. |
public void copyMeta(GridMetadataAwareAdapter from){
assert from != null;
copyMeta(from.allMeta());
}
| Copies all metadata from another instance. |
public synchronized static LinkedHashMap<String,ArrayList<String>> predictAddressTags(Context context,final String elementType,final long elementOsmId,final ElementSearch es,final LinkedHashMap<String,ArrayList<String>> current,int maxRank){
Address newAddress=null;
loadLastAddresses(context);
if (lastAddresses != null && lastAddresses.size() > 0) {
newAddress=new Address(elementType,elementOsmId,lastAddresses.get(0).tags);
if (newAddress.tags.containsKey(Tags.KEY_ADDR_HOUSENUMBER)) {
newAddress.tags.put(Tags.KEY_ADDR_HOUSENUMBER,Util.getArrayList(""));
}
Log.d("Address","seeding with last addresses");
}
if (newAddress == null) {
newAddress=new Address(elementType,elementOsmId,new LinkedHashMap<String,ArrayList<String>>());
Log.d("Address","nothing to seed with, creating new");
}
for ( String k : current.keySet()) {
Log.d("Address","Adding in existing tag " + k);
newAddress.tags.put(k,current.get(k));
}
boolean hasPlace=newAddress.tags.containsKey(Tags.KEY_ADDR_PLACE);
boolean hasNumber=current.containsKey(Tags.KEY_ADDR_HOUSENUMBER);
StorageDelegator storageDelegator=Application.getDelegator();
if (es != null) {
ArrayList<String> streetNames=new ArrayList<String>(Arrays.asList(es.getStreetNames()));
if ((streetNames != null && streetNames.size() > 0) || hasPlace) {
LinkedHashMap<String,ArrayList<String>> tags=newAddress.tags;
Log.d(DEBUG_TAG,"tags.get(Tags.KEY_ADDR_STREET)) " + tags.get(Tags.KEY_ADDR_STREET));
String street;
if (!hasPlace) {
ArrayList<String> addrStreetValues=tags.get(Tags.KEY_ADDR_STREET);
int rank=-1;
boolean hasAddrStreet=addrStreetValues != null && addrStreetValues.size() > 0 && !addrStreetValues.get(0).equals("");
if (hasAddrStreet) {
rank=streetNames.indexOf(addrStreetValues.get(0));
}
Log.d(DEBUG_TAG,(hasAddrStreet ? "rank " + rank + " for "+ addrStreetValues.get(0) : "no addrStreet tag"));
if (!hasAddrStreet || rank > maxRank || rank < 0) {
tags.put(Tags.KEY_ADDR_STREET,Util.getArrayList(streetNames.get(0)));
}
addrStreetValues=tags.get(Tags.KEY_ADDR_STREET);
if (addrStreetValues != null && addrStreetValues.size() > 0) {
street=tags.get(Tags.KEY_ADDR_STREET).get(0);
}
else {
street="";
}
try {
newAddress.setSide(es.getStreetId(street));
}
catch ( OsmException e) {
newAddress.side=Side.UNKNOWN;
}
}
else {
ArrayList<String> addrPlaceValues=tags.get(Tags.KEY_ADDR_PLACE);
if (addrPlaceValues != null && addrPlaceValues.size() > 0) {
street=tags.get(Tags.KEY_ADDR_PLACE).get(0);
}
else {
street="";
}
newAddress.side=Side.UNKNOWN;
}
Log.d(DEBUG_TAG,"side " + newAddress.getSide());
Side side=newAddress.getSide();
if (!hasNumber && street != null && lastAddresses != null) {
TreeMap<Integer,Address> list=getHouseNumbers(street,side,lastAddresses);
if (list.size() == 0) {
try {
Log.d(DEBUG_TAG,"street " + street);
long streetId=-1;
if (!hasPlace) {
streetId=es.getStreetId(street);
}
for ( Node n : storageDelegator.getCurrentStorage().getNodes()) {
seedAddressList(street,streetId,n,lastAddresses);
}
for ( Way w : storageDelegator.getCurrentStorage().getWays()) {
seedAddressList(street,streetId,w,lastAddresses);
}
list=getHouseNumbers(street,side,lastAddresses);
}
catch ( OsmException e) {
e.printStackTrace();
}
}
if (list.size() >= 2) {
try {
int firstNumber=list.firstKey();
int lastNumber=list.lastKey();
int inc=1;
float incTotal=0;
float incCount=0;
ArrayList<Integer> numbers=new ArrayList<Integer>(list.keySet());
for (int i=0; i < numbers.size() - 1; i++) {
int diff=numbers.get(i + 1).intValue() - numbers.get(i).intValue();
if (diff > 0 && diff <= 2) {
incTotal=incTotal + diff;
incCount++;
}
}
inc=Math.round(incTotal / incCount);
int nearest=-1;
int prev=-1;
int post=-1;
double distanceFirst=0;
double distanceLast=0;
double distance=Double.MAX_VALUE;
for (int i=0; i < numbers.size(); i++) {
int number=Integer.valueOf(numbers.get(i));
Address a=list.get(number);
double newDistance=GeoMath.haversineDistance(newAddress.lon,newAddress.lat,a.lon,a.lat);
if (newDistance <= distance) {
distance=newDistance;
nearest=number;
prev=numbers.get(Math.max(0,i - 1));
post=numbers.get(Math.min(numbers.size() - 1,i + 1));
}
if (i == 0) {
distanceFirst=newDistance;
}
else if (i == numbers.size() - 1) {
distanceLast=newDistance;
}
}
double distanceTotal=GeoMath.haversineDistance(list.get(firstNumber).lon,list.get(firstNumber).lat,list.get(lastNumber).lon,list.get(lastNumber).lat);
if (nearest == firstNumber) {
if (distanceLast > distanceTotal) {
inc=-inc;
}
}
else if (nearest == lastNumber) {
if (distanceFirst < distanceTotal) {
inc=-inc;
}
}
else {
double distanceNearestFirst=GeoMath.haversineDistance(list.get(firstNumber).lon,list.get(firstNumber).lat,list.get(nearest).lon,list.get(nearest).lat);
if (distanceFirst < distanceNearestFirst) {
inc=-inc;
}
}
Log.d("TagEditor","First " + firstNumber + " last "+ lastNumber+ " nearest "+ nearest+ " inc "+ inc+ " prev "+ prev+ " post "+ post+ " side "+ side);
for ( String key : list.get(nearest).tags.keySet()) {
if (!tags.containsKey(key)) {
tags.put(key,list.get(nearest).tags.get(key));
}
}
int newNumber=Math.max(1,nearest + inc);
if (numbers.contains(Integer.valueOf(newNumber))) {
if (!numbers.contains(Integer.valueOf(Math.max(1,newNumber + inc)))) {
newNumber=Math.max(1,newNumber + inc);
}
else if (!numbers.contains(Integer.valueOf(Math.max(1,newNumber - inc)))) {
newNumber=Math.max(1,newNumber - inc);
}
}
tags.put(Tags.KEY_ADDR_HOUSENUMBER,Util.getArrayList("" + newNumber));
}
catch ( NumberFormatException nfe) {
tags.put(Tags.KEY_ADDR_HOUSENUMBER,Util.getArrayList(""));
}
}
else if (list.size() == 1) {
for ( String key : list.get(list.firstKey()).tags.keySet()) {
if (!tags.containsKey(key)) {
tags.put(key,list.get(list.firstKey()).tags.get(key));
}
}
}
else if (list.size() == 0) {
tags.put(Tags.KEY_ADDR_HOUSENUMBER,Util.getArrayList(""));
}
}
}
else {
Preferences prefs=new Preferences(Application.getCurrentApplication());
Set<String> addressTags=prefs.addressTags();
for ( String key : addressTags) {
newAddress.tags.put(key,Util.getArrayList(""));
}
}
}
if (elementType.equals(Node.NAME)) {
boolean isOnBuilding=false;
for ( Way w : storageDelegator.getCurrentStorage().getWays((Node)storageDelegator.getOsmElement(Node.NAME,elementOsmId))) {
if (w.hasTagKey(Tags.KEY_BUILDING)) {
isOnBuilding=true;
}
else if (w.getParentRelations() != null) {
for ( Relation r : w.getParentRelations()) {
if (r.hasTagKey(Tags.KEY_BUILDING) || r.hasTag(Tags.KEY_TYPE,Tags.VALUE_BUILDING)) {
isOnBuilding=true;
break;
}
}
}
if (isOnBuilding) {
break;
}
}
if (isOnBuilding && !newAddress.tags.containsKey(Tags.KEY_ENTRANCE)) {
newAddress.tags.put(Tags.KEY_ENTRANCE,Util.getArrayList("yes"));
}
}
return newAddress.tags;
}
| Predict address tags This uses a file to cache/save the address information over invocations of the TagEditor, if the cache doesn't have entries for a specific street/place an attempt to extract the information from the downloaded data is made |
public static PlaceholderFragment newInstance(){
PlaceholderFragment fragment=new PlaceholderFragment();
Bundle args=new Bundle();
fragment.setArguments(args);
return fragment;
}
| Returns a new instance of this fragment for the given section number. |
public MTreeNode(int capacity,boolean isLeaf){
super(capacity,isLeaf,MTreeEntry.class);
}
| Creates a new MTreeNode with the specified parameters. |
static char[][] translatedNames(char[][] names){
if (names == null) return null;
int length=names.length;
char[][] newNames=new char[length][];
for (int i=0; i < length; i++) {
newNames[i]=translatedName(names[i]);
}
return newNames;
}
| Returns the Java Model representation of the given names which are provided in diet class file format, or <code>null</code> if the given names are <code>null</code>. <p><code>ClassFileReader</code> format is similar to "java/lang/Object", and corresponding Java Model format is "java.lang.Object". |
public void cleanActivityList(List<Activity> list,QuadTree<ClusterPoint> qt){
if (list.size() > 1) {
int index=1;
while (index < list.size()) {
Activity a=list.get(index - 1);
Cluster ca=((List<ClusterPoint>)qt.getDisk(a.getLocation().getCoordinate().x,a.getLocation().getCoordinate().y,0)).get(0).getCluster();
Activity b=list.get(index);
Cluster cb=((List<ClusterPoint>)qt.getDisk(b.getLocation().getCoordinate().x,b.getLocation().getCoordinate().y,0)).get(0).getCluster();
if (ca != null && cb != null) {
if (ca.getClusterId().equalsIgnoreCase(cb.getClusterId())) {
a.setEndTime(b.getEndTime());
list.remove(index);
}
else {
index++;
}
}
else {
index++;
}
}
}
else {
log.warn("Could not thin the list. There is only one element in the list.");
}
for ( Activity a : list) {
Cluster c=((List<ClusterPoint>)qt.getDisk(a.getLocation().getCoordinate().x,a.getLocation().getCoordinate().y,0)).get(0).getCluster();
if (c != null) {
a.getLocation().setCoordinate(c.getCenterOfGravity().getCoordinate());
}
}
}
| This method merges all consecutive activities that share the same cluster, and then adjust the activity locations to that of the cluster to which it belongs, if the activity actually do belong to a cluster. Activities not belonging to any cluster will thus <i>not</i> be discarded. |
public static long longEncode(long geohash,int level){
final short precision=(short)(geohash & 15);
if (precision == level) {
return geohash;
}
else if (precision > level) {
return ((geohash >>> (((precision - level) * 5) + 4)) << 4) | level;
}
return ((geohash >>> 4) << (((level - precision) * 5) + 4) | level);
}
| Encode an existing geohash long to the provided precision |
public double interpolate(Coord coord){
if (sg != null && coord != null) return interpolate(coord.getX(),coord.getY());
log.warn("Either the spatial grid is not initialized or the coordinates are zero!");
return Double.NaN;
}
| Interpolates the value at the given coordinate. |
public UnchangeableAllowingOnBehalfActingException(Object[] params){
super(params);
}
| Constructs a new exception with the specified message parameters. |
public MusicTrack(PlayMusicManager playMusicManager){
super(playMusicManager);
}
| Creates a data item |
public static void updateQtyBatchs(Properties ctx,I_PP_Order order,boolean override){
BigDecimal qtyBatchSize=order.getQtyBatchSize();
if (qtyBatchSize.signum() == 0 || override) {
int AD_Workflow_ID=order.getAD_Workflow_ID();
if (AD_Workflow_ID <= 0) return;
MWorkflow wf=MWorkflow.get(ctx,AD_Workflow_ID);
qtyBatchSize=wf.getQtyBatchSize().setScale(0,RoundingMode.UP);
order.setQtyBatchSize(qtyBatchSize);
}
BigDecimal QtyBatchs;
if (qtyBatchSize.signum() == 0) QtyBatchs=Env.ONE;
else QtyBatchs=order.getQtyOrdered().divide(qtyBatchSize,0,BigDecimal.ROUND_UP);
order.setQtyBatchs(QtyBatchs);
}
| Set QtyBatchSize and QtyBatchs using Workflow and QtyEntered |
@Pointcut("execution(* java.lang.Object.*(..))") public void objectMethod(){
}
| Method execution pointcuts |
public static final Bitmap createBlurredBitmap(final Bitmap sentBitmap){
if (sentBitmap == null) {
return null;
}
final Bitmap mBitmap=sentBitmap.copy(sentBitmap.getConfig(),true);
final int w=mBitmap.getWidth();
final int h=mBitmap.getHeight();
final int[] pix=new int[w * h];
mBitmap.getPixels(pix,0,w,0,0,w,h);
final int wm=w - 1;
final int hm=h - 1;
final int wh=w * h;
final int div=DEFAULT_BLUR_RADIUS + DEFAULT_BLUR_RADIUS + 1;
final int r[]=new int[wh];
final int g[]=new int[wh];
final int b[]=new int[wh];
final int vmin[]=new int[Math.max(w,h)];
int rsum, gsum, bsum, x, y, i, p, yp, yi, yw;
int divsum=div + 1 >> 1;
divsum*=divsum;
final int dv[]=new int[256 * divsum];
for (i=0; i < 256 * divsum; i++) {
dv[i]=i / divsum;
}
yw=yi=0;
final int[][] stack=new int[div][3];
int stackpointer;
int stackstart;
int[] sir;
int rbs;
final int r1=DEFAULT_BLUR_RADIUS + 1;
int routsum, goutsum, boutsum;
int rinsum, ginsum, binsum;
for (y=0; y < h; y++) {
rinsum=ginsum=binsum=routsum=goutsum=boutsum=rsum=gsum=bsum=0;
for (i=-DEFAULT_BLUR_RADIUS; i <= DEFAULT_BLUR_RADIUS; i++) {
p=pix[yi + Math.min(wm,Math.max(i,0))];
sir=stack[i + DEFAULT_BLUR_RADIUS];
sir[0]=(p & 0xff0000) >> 16;
sir[1]=(p & 0x00ff00) >> 8;
sir[2]=p & 0x0000ff;
rbs=r1 - Math.abs(i);
rsum+=sir[0] * rbs;
gsum+=sir[1] * rbs;
bsum+=sir[2] * rbs;
if (i > 0) {
rinsum+=sir[0];
ginsum+=sir[1];
binsum+=sir[2];
}
else {
routsum+=sir[0];
goutsum+=sir[1];
boutsum+=sir[2];
}
}
stackpointer=DEFAULT_BLUR_RADIUS;
for (x=0; x < w; x++) {
r[yi]=dv[rsum];
g[yi]=dv[gsum];
b[yi]=dv[bsum];
rsum-=routsum;
gsum-=goutsum;
bsum-=boutsum;
stackstart=stackpointer - DEFAULT_BLUR_RADIUS + div;
sir=stack[stackstart % div];
routsum-=sir[0];
goutsum-=sir[1];
boutsum-=sir[2];
if (y == 0) {
vmin[x]=Math.min(x + DEFAULT_BLUR_RADIUS + 1,wm);
}
p=pix[yw + vmin[x]];
sir[0]=(p & 0xff0000) >> 16;
sir[1]=(p & 0x00ff00) >> 8;
sir[2]=p & 0x0000ff;
rinsum+=sir[0];
ginsum+=sir[1];
binsum+=sir[2];
rsum+=rinsum;
gsum+=ginsum;
bsum+=binsum;
stackpointer=(stackpointer + 1) % div;
sir=stack[stackpointer % div];
routsum+=sir[0];
goutsum+=sir[1];
boutsum+=sir[2];
rinsum-=sir[0];
ginsum-=sir[1];
binsum-=sir[2];
yi++;
}
yw+=w;
}
for (x=0; x < w; x++) {
rinsum=ginsum=binsum=routsum=goutsum=boutsum=rsum=gsum=bsum=0;
yp=-DEFAULT_BLUR_RADIUS * w;
for (i=-DEFAULT_BLUR_RADIUS; i <= DEFAULT_BLUR_RADIUS; i++) {
yi=Math.max(0,yp) + x;
sir=stack[i + DEFAULT_BLUR_RADIUS];
sir[0]=r[yi];
sir[1]=g[yi];
sir[2]=b[yi];
rbs=r1 - Math.abs(i);
rsum+=r[yi] * rbs;
gsum+=g[yi] * rbs;
bsum+=b[yi] * rbs;
if (i > 0) {
rinsum+=sir[0];
ginsum+=sir[1];
binsum+=sir[2];
}
else {
routsum+=sir[0];
goutsum+=sir[1];
boutsum+=sir[2];
}
if (i < hm) {
yp+=w;
}
}
yi=x;
stackpointer=DEFAULT_BLUR_RADIUS;
for (y=0; y < h; y++) {
pix[yi]=0xff000000 | dv[rsum] << 16 | dv[gsum] << 8 | dv[bsum];
rsum-=routsum;
gsum-=goutsum;
bsum-=boutsum;
stackstart=stackpointer - DEFAULT_BLUR_RADIUS + div;
sir=stack[stackstart % div];
routsum-=sir[0];
goutsum-=sir[1];
boutsum-=sir[2];
if (x == 0) {
vmin[y]=Math.min(y + r1,hm) * w;
}
p=x + vmin[y];
sir[0]=r[p];
sir[1]=g[p];
sir[2]=b[p];
rinsum+=sir[0];
ginsum+=sir[1];
binsum+=sir[2];
rsum+=rinsum;
gsum+=ginsum;
bsum+=binsum;
stackpointer=(stackpointer + 1) % div;
sir=stack[stackpointer];
routsum+=sir[0];
goutsum+=sir[1];
boutsum+=sir[2];
rinsum-=sir[0];
ginsum-=sir[1];
binsum-=sir[2];
yi+=w;
}
}
mBitmap.setPixels(pix,0,w,0,0,w,h);
return mBitmap;
}
| Takes a bitmap and creates a new slightly blurry version of it. |
public static void loadProject(final JTree tree,final INaviProject project){
Preconditions.checkNotNull(tree,"IE01435: Tree argument can not be null");
Preconditions.checkNotNull(project,"IE01436: Project argument can not be null");
loadProjectThreaded(SwingUtilities.getWindowAncestor(tree),project,tree);
}
| Loads a project while showing a progress dialog. |
private void updateProgress(String progressLabel,int progress){
if (myHost != null && ((progress != previousProgress) || (!progressLabel.equals(previousProgressLabel)))) {
myHost.updateProgress(progressLabel,progress);
}
previousProgress=progress;
previousProgressLabel=progressLabel;
}
| Used to communicate a progress update between a plugin tool and the main Whitebox user interface. |
private Data(){
}
| This utility class cannot be instantiated |
@Override public void cancel() throws SQLException {
try {
debugCodeCall("cancel");
checkClosed();
CommandInterface c=executingCommand;
try {
if (c != null) {
c.cancel();
cancelled=true;
}
}
finally {
setExecutingStatement(null);
}
}
catch ( Exception e) {
throw logAndConvert(e);
}
}
| Cancels a currently running statement. This method must be called from within another thread than the execute method. Operations on large objects are not interrupted, only operations that process many rows. |
private static int lowerBound(int from,final int to,final int pos,final IntComparator comp){
int len=to - from;
while (len > 0) {
int half=len / 2;
int middle=from + half;
if (comp.compare(middle,pos) < 0) {
from=middle + 1;
len-=half + 1;
}
else {
len=half;
}
}
return from;
}
| Performs a binary search on an already-sorted range: finds the first position where an element can be inserted without violating the ordering. Sorting is by a user-supplied comparison function. |
public T link(String value){
return attr("link",value);
}
| Sets the <code>link</code> attribute on the last started tag that has not been closed. |
public void init() throws ServletException {
}
| Initialization of the servlet. <br> |
@Override protected EClass eStaticClass(){
return UmplePackage.eINSTANCE.getAnonymous_afterCode_2_();
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public void write(long position,ByteBuf src,int srcStart,int srcLength) throws IOException {
final int bufferPosition=checkOffset(position,srcLength);
final long destAddress=PlatformDependent.directBufferAddress(lastMapped) + bufferPosition;
if (src.hasMemoryAddress()) {
final long srcAddress=src.memoryAddress() + srcStart;
PlatformDependent.copyMemory(srcAddress,destAddress,srcLength);
}
else if (src.hasArray()) {
final byte[] srcArray=src.array();
PlatformDependent.copyMemory(srcArray,srcStart,destAddress,srcLength);
}
else {
throw new IllegalArgumentException("unsupported byte buffer");
}
position+=srcLength;
if (position > this.length) {
this.length=position;
}
}
| Writes a sequence of bytes to this file from the given buffer. <p> <p> Bytes are written starting at this file's specified position, |
public void requestUpdate(){
synchronized (updateLock) {
updateOnce=true;
}
}
| Asks Display2D to update itself next iteration regardless of the current redrawing/updating rule. |
public final View findNextFocus(ViewGroup root,View focused,int direction){
return findNextFocus(root,focused,null,direction);
}
| Find the next view to take focus in root's descendants, starting from the view that currently is focused. |
public void printUnit(JCCompilationUnit tree,JCClassDecl cdef) throws IOException {
docComments=tree.docComments;
printDocComment(tree);
if (tree.pid != null) {
print("package ");
printExpr(tree.pid);
print(";");
println();
}
boolean firstImport=true;
for (List<JCTree> l=tree.defs; l.nonEmpty() && (cdef == null || l.head.hasTag(IMPORT)); l=l.tail) {
if (l.head.hasTag(IMPORT)) {
JCImport imp=(JCImport)l.head;
Name name=TreeInfo.name(imp.qualid);
if (name == name.table.names.asterisk || cdef == null || isUsed(TreeInfo.symbol(imp.qualid),cdef)) {
if (firstImport) {
firstImport=false;
println();
}
printStat(imp);
}
}
else {
printStat(l.head);
}
}
if (cdef != null) {
printStat(cdef);
println();
}
}
| Print unit consisting of package clause and import statements in toplevel, followed by class definition. if class definition == null, print all definitions in toplevel. |
public static SpannableString typeface(Context context,int strResId,int style){
if (sDefaultTypefaceCollection == null) {
throw new IllegalStateException("Default typeface collection not initialized. Forgot to call init()?");
}
return typeface(context.getString(strResId),sDefaultTypefaceCollection,style);
}
| Return spannable string with typeface in certain style see: http://stackoverflow.com/questions/8607707/how-to-set-a-custom-font-in-the-actionbar-title |
public static NodeSelection empty(){
return EMPTY;
}
| Creates a new instance representing the empty selection. |
public static Io.Builder<GraphSONIo> build(){
return build(GraphSONVersion.V1_0);
}
| Create a new builder using the default version of GraphSON. |
String[] createdAssumptions(){
Boolean sufficesSelected=useSufficesButton.getSelection();
Vector<String[]> vec=new Vector<String[]>();
int lastAddedAssump=state.assumeReps.size();
if (state.splitChosen()) {
lastAddedAssump--;
}
for (int i=state.firstAddedAssumption; i < lastAddedAssump; i++) {
NodeRepresentation rep=state.assumeReps.elementAt(i);
String newDecls=null;
while (rep.onSameLineAsNext) {
if (newDecls != null) {
newDecls=newDecls + ", ";
}
else {
newDecls="";
}
newDecls=newDecls + rep.nodeText[0];
i++;
rep=state.assumeReps.elementAt(i);
}
if (newDecls == null) {
vec.add(rep.primedNodeText());
}
else {
vec.add(new String[]{newDecls + ", " + rep.nodeText[0]});
}
}
Vector<String> resVec=new Vector<String>();
for (int i=0; i < vec.size(); i++) {
String[] strArray=vec.elementAt(i);
for (int j=0; j < strArray.length; j++) {
String str=strArray[j];
if ((j == strArray.length - 1) && (i != vec.size() - 1)) {
str=str + ",";
}
resVec.add(str);
}
}
String[] result=new String[resVec.size()];
for (int i=0; i < result.length; i++) {
result[i]=resVec.elementAt(i);
}
return result;
}
| Returns string array such that applying stringArrayToString to it produces the text of the list of assumptions in createdAssumps of the spec of MakeProof. |
private static boolean isLdapRef(Object obj){
if (!(obj instanceof Reference)) {
return false;
}
String thisClassName=LdapCtxFactory.class.getName();
Reference ref=(Reference)obj;
return thisClassName.equals(ref.getFactoryClassName());
}
| Returns true if argument is an LDAP reference. |
private void initializeListeners(){
addMouseListener(m_listener);
addMouseMotionListener(m_listener);
addKeyListener(m_listener);
addFocusListener(m_listener);
m_caret.addCaretListener(m_listener);
}
| Initializes the listeners that handle keyboard and mouse input. |
public int[] coefficients(){
IntArrayList coefficients=new IntArrayList();
for (int i=0, c; i < list.size(); i++) if ((c=(int)list.getLong(i)) != 0) coefficients.add(c);
return coefficients.toIntArray();
}
| Returns an array containing the coefficients in variable increasing order. <p>Mainly for debugging purposes. |
@Override public void accept(double value){
++count;
simpleSum+=value;
sumWithCompensation(value);
min=Math.min(min,value);
max=Math.max(max,value);
}
| Records another value into the summary information. |
private void notifyRegisterChanged(){
for ( final IRegistersChangedListener listener : reglisteners) {
listener.registerDataChanged();
}
}
| Notifies the register listeners about changes in the register values. |
public void add(int v){
_add(numberNode(v));
}
| Method for setting value of a field to specified numeric value. |
public @Test final void testCreationNegative(){
thrown.expect(IllegalArgumentException.class);
new Email(null,null);
}
| Test construction of Email entities. |
public static void printHelp(){
Debug.output("");
Debug.output("usage: java com.bbn.openmap.image.ImageMaster [-file <properties file> || -url <properties file>] [-masterprops || -serverprops");
Debug.output(" -file requires a complete path to a ImageMaster properties file.");
Debug.output(" -url requires an URL to a ImageMaster properties file.");
Debug.output(" -masterprops prints out an example of a ImageMaster properties file.");
Debug.output(" -serverprops prints out an example of a ImageServer properties file.");
Debug.output("");
System.exit(1);
}
| <b>printHelp </b> should print a usage statement which reflects the command line needs of the ImageServer. |
public static PolygonRDD SpatialRangeQuery(PolygonRDD polygonRDD,Envelope envelope,Integer condition){
JavaRDD<Polygon> result=polygonRDD.getRawPolygonRDD().filter(new PolygonRangeFilter(envelope,condition));
return new PolygonRDD(result);
}
| Spatial range query on top of PolygonRDD |
public void add(String name,String value){
if (headerBuilder == null) {
headerBuilder=new Headers.Builder();
}
headerBuilder.add(name,value);
}
| We have already handled etag, and will add 'If-Match' & 'Range' value if it works. |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.