code
stringlengths
10
174k
nl
stringlengths
3
129k
public void testFilterPlacement04(){ new Helper(){ { given=select(varNode(x),where(stmtPatternWithVar("x1"),stmtPatternWithVarOptional("x2"),stmtPatternWithVarOptional("x2"),stmtPatternWithVar("x2"),stmtPatternWithVars("x2","x3"),stmtPatternWithVarOptional("y2"),filterWithVars("x1","x2"),filterWithVar("y2"))); expected=select(varNode(x),where(stmtPatternWithVar("x1"),stmtPatternWithVarOptional("x2"),stmtPatternWithVarOptional("x2"),stmtPatternWithVar("x2"),filterWithVars("x1","x2"),stmtPatternWithVars("x2","x3"),stmtPatternWithVarOptional("y2"),filterWithVar("y2"))); } } .testWhileIgnoringExplainHints(); }
Test filter placement where one filter variables is bound in the first, one in the join group
@Benchmark public long factorialConditional(){ return factConditionl(n); }
Factorial benchmark using a conditional.
private boolean isValidState(String key){ if (key == null) { return false; } if (key.equals(rbean.getString("SignalHeadStateDark")) || key.equals(rbean.getString("SignalHeadStateHeld"))) { if (log.isDebugEnabled()) { log.debug(key + " is a valid state. "); } return true; } for (int i=0; i < _validKey.length; i++) { if (key.equals(_validKey[i])) { if (log.isDebugEnabled()) { log.debug(key + " is a valid state. "); } return true; } } if (log.isDebugEnabled()) { log.debug(key + " is NOT a valid state. "); } return false; }
Check that device supports the state valid state names returned by the bean are localized
public void paintSliderBackground(SynthContext context,Graphics g,int x,int y,int w,int h,int orientation){ paintBackground(context,g,x,y,w,h,orientation); }
Paints the background of a slider. This implementation invokes the method of the same name without the orientation.
public static void removePlayer(final String playerName,final StendhalRPZone zone){ final Player player=MockStendhalRPRuleProcessor.get().getPlayer(playerName); if (player != null) { unregisterPlayer(player,zone); } }
Remove a player from rule processor, world and zone.
protected final void insertSamlToken(SoapMessage message,String elementNamespace,String elementLocalName,SamlToken token) throws ParserException { Document messageDocument=message.getMessage().getSOAPPart(); NodeList targetElement=messageDocument.getElementsByTagNameNS(elementNamespace,elementLocalName); if (targetElement == null || targetElement.getLength() != 1) { String errMsg="Error inserting SAML token into the SOAP message. " + "No/Too many " + elementLocalName + " found."; log.debug(errMsg); throw new ParserException(errMsg); } Node copiedToken=token.importTo(messageDocument); targetElement.item(0).appendChild(copiedToken); }
Inserts SAML token into the SOAP message. Due to problems with JAXB marshaling/unmarshaling SAML tokens should be added to the message after it is marshalled to DOM. There should be only 1 <elementNamespace:elementLocalName /> node in the request.
public static void cancelTouchEvent(View view){ final long now=SystemClock.uptimeMillis(); MotionEvent event=MotionEvent.obtain(now,now,MotionEvent.ACTION_CANCEL,0.0f,0.0f,0); view.dispatchTouchEvent(event); event.recycle(); }
Dispatch a CANCEL event to view, force to stop responding to any touch event.
public BooleanSparseArrayDataRow(int size){ super(size); values=new boolean[size]; }
Creates a sparse array data row of the given size.
private void loadStringValue(JTextField comp,final String elementName){ String propValue=properties.getValue(elementName); if (propValue != null && !propValue.isEmpty()) { comp.setText(propValue); } }
Gets the String value of a property and loads it into a JTextField
@DSSafe(DSCat.SAFE_LIST) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-09-03 14:59:52.551 -0400",hash_original_method="C216811775A6723BB41E0D3A835823FC",hash_generated_method="2E1788EBA86DBE00B0A103790D8375CB") public static Tailer create(File file,TailerListener listener,long delayMillis,boolean end,int bufSize){ Tailer tailer=new Tailer(file,listener,delayMillis,end,bufSize); Thread thread=new Thread(tailer); thread.setDaemon(true); thread.start(); return tailer; }
Creates and starts a Tailer for the given file.
@Override public void updateStatus(JobContext jobContext) throws Exception { LogicalUnit logicalUnit=null; try { if (_status == JobStatus.IN_PROGRESS) { return; } DbClient dbClient=jobContext.getDbClient(); String opId=getTaskCompleter().getOpId(); StringBuilder logMsgBuilder=new StringBuilder(String.format("Updating status of job %s to %s, task: %s",this.getJobName(),_status.name(),opId)); if (_status == JobStatus.SUCCESS) { logicalUnit=(LogicalUnit)_javaResult.getBean("logicalunit"); if (null != logicalUnit.getLdevList() && !logicalUnit.getLdevList().isEmpty()) { Iterator<LDEV> ldevListItr=logicalUnit.getLdevList().iterator(); if (ldevListItr.hasNext()) { LDEV ldev=ldevListItr.next(); if (null != ldev && -1 != ldev.getTierLevel()) { logMsgBuilder.append(String.format("Task %s is successful to update volume %s tieringPolicy: %s",opId,logicalUnit.getObjectID(),ldev.getTierLevel())); } } } } else if (_status == JobStatus.FAILED && VOLUME_MODIFY_JOB.equalsIgnoreCase(getJobName())) { URI id=getTaskCompleter().getId(); logMsgBuilder.append(String.format("Task %s failed to update volume tieringPolicy: %s",opId,id.toString())); Volume volume=dbClient.queryObject(Volume.class,id); volume.setInactive(true); dbClient.persistObject(volume); } log.info(logMsgBuilder.toString()); } catch ( Exception e) { log.error("Caught an exception while trying to updating tieringPolicy of the volume",e); setErrorStatus("Encountered an internal error during tieringPolicy updation of volume: " + e.getMessage()); } finally { super.updateStatus(jobContext); } }
Called to update the job status when the volume expand job completes.
public void ImportHastusSchedule(String filename) throws IOException { final String[] SKIPPABLE={"Block","Note","From","To"}; final String COLON=":"; ArrayList<String> SkippedHeaders=new ArrayList<String>(); for ( String s : SKIPPABLE) SkippedHeaders.add(s); String currentRouteName=""; String currentDirectionName=""; Integer currentBranchNumber=0; String currentColumnWidths=""; ArrayList<String> currentStops=new ArrayList<String>(); ArrayList<String> currentCells=null; BufferedReader reader=new BufferedReader(new FileReader(filename)); String fileLine=reader.readLine(); do { if (fileLine.split(COLON).length > 1) { currentRouteName=fileLine.split(COLON)[1]; currentDirectionName=reader.readLine().split(COLON)[1]; currentColumnWidths=reader.readLine(); currentStops=SplitFixedWidth(reader.readLine(),getFixedColumnWidths(currentColumnWidths)); currentBranchNumber=0; } else { currentCells=SplitFixedWidth(fileLine,getFixedColumnWidths(currentColumnWidths)); boolean[] emptyCells=new boolean[currentCells.size()]; for (int i=0; i < currentCells.size(); i++) emptyCells[i]=(currentCells.get(i).isEmpty() || SkippedHeaders.contains(currentCells.get(i))); if (currentCells.size() > currentStops.size()) { System.err.println("ERROR: Stop header length doesn't match timetable length!"); } ArrayList<String> tempStops=new ArrayList<String>(); for (int i=0; i < currentCells.size(); i++) if (!(emptyCells[i])) tempStops.add(currentStops.get(i)); if (tempStops.size() == 1) { System.err.println("check here!"); } if (!(SearchForStopSequence(tempStops))) { ScheduledRoute newRoute=new ScheduledRoute(currentRouteName,currentDirectionName,"" + currentBranchNumber++,tempStops); int currentStopIndex=0; for (int i=0; i < currentCells.size(); i++) { if (!(emptyCells[i])) { String parsedArrivalTime=currentCells.get(i); newRoute.getStop(currentStopIndex++).AddTime(new Tuple<String,String>(parsedArrivalTime,"")); } } this.routes.add(newRoute); } else { int currentRouteIndex=MatchStopSequence(tempStops); int currentStopIndex=0; for (int i=0; i < currentCells.size(); i++) { String parsedArrivalTime=currentCells.get(i); if (!(emptyCells[i])) { this.routes.get(currentRouteIndex).getStop(currentStopIndex++).AddTime(new Tuple<String,String>(parsedArrivalTime,"")); } } } } fileLine=reader.readLine(); } while (fileLine != null); for ( ScheduledRoute R : this.routes) { System.out.println(R.id + "(" + R.direction+ "): "+ R.getStopSequence().toString()); } System.out.println("...done"); }
Imports a pre-processed HASTUS schedule, pre-processed in Excel to be similar to the GO schedule format. RESTRICTION: Data values cannot include the ":" character FORMAT (.txt) Route: [routename] Direction: [direction] [columnheader, a series of space-separated lines which denote fixed column-width (like ____ _____ ___ __ ____ ....)] [stops names] [stop times 1] [stop times 2] ...
@BeforeMethod(alwaysRun=true) public void doBeforeMethod(ITestContext tc,ITestResult tr,Method m) throws Exception { final String mname=m.getName(); currentTest=this.getClass().getName() + "." + mname; logger.info(String.format("************************ %s *******************",currentTest)); gondolaRc.start(); member1=gondolaRc.getMember(4); member2=gondolaRc.getMember(5); member3=gondolaRc.getMember(6); members=Stream.of(member1,member2,member3).collect(Collectors.toList()); startTimer=System.currentTimeMillis(); }
Starts all the threads in the GondolaRc instance and displays a header in the log, to make it easier to find the output of a test case.
public static OutputStream createOutputStream(File file,boolean zip,boolean append) throws IOException { return createOutputStream(file,zip,append,false); }
Creates an output stream for a file, wrapping in a <code>BufferedOutputStream</code> OutputStream and optionally a <code>GZIPOutputStream</code>.
@Override public boolean isActive(){ return amIActive; }
Used by the Whitebox GUI to tell if this plugin is still running.
public static float b2f(boolean inp){ return inp ? 1f : -1f; }
Convert the given boolean to float. "True" is 1.0; "false" is -1.0.
@Override public NotificationChain eInverseRemove(InternalEObject otherEnd,int featureID,NotificationChain msgs){ switch (featureID) { case ExpressionsPackage.BITWISE_AND_EXPRESSION__LEFT_OPERAND: return basicSetLeftOperand(null,msgs); case ExpressionsPackage.BITWISE_AND_EXPRESSION__RIGHT_OPERAND: return basicSetRightOperand(null,msgs); } return super.eInverseRemove(otherEnd,featureID,msgs); }
<!-- begin-user-doc --> <!-- end-user-doc -->
public Random(long seed,boolean debug){ super(seed); setDebug(debug); m_ID=nextID(); if (getDebug()) printStackTrace(); }
Creates a new random number generator using a single long seed. With optional debugging
public void updateUI(){ setUI((SeparatorUI)UIManager.getUI(this)); }
Resets the UI property to a value from the current look and feel.
private void doTestTopStatsWithRefinement(final boolean allStats) throws Exception { String stat_param=allStats ? "{!tag=s1}foo_i" : "{!tag=s1 min=true max=true count=true missing=true}foo_i"; ModifiableSolrParams coreParams=params("q","*:*","rows","0","stats","true","stats.field",stat_param); ModifiableSolrParams facetParams=new ModifiableSolrParams(coreParams); facetParams.add(params("facet","true","facet.limit","1","facet.pivot","{!stats=s1}place_t,company_t")); ModifiableSolrParams facetForceRefineParams=new ModifiableSolrParams(facetParams); facetForceRefineParams.add(params(FacetParams.FACET_OVERREQUEST_COUNT,"0",FacetParams.FACET_OVERREQUEST_RATIO,"0")); for ( ModifiableSolrParams params : new ModifiableSolrParams[]{coreParams,facetParams,facetForceRefineParams}) { ModifiableSolrParams q=new ModifiableSolrParams(params); q.set("shards",getShardsString()); QueryResponse rsp=queryServer(q); FieldStatsInfo fieldStatsInfo=rsp.getFieldStatsInfo().get("foo_i"); String msg=q.toString(); assertEquals(msg,3.0,fieldStatsInfo.getMin()); assertEquals(msg,91.0,fieldStatsInfo.getMax()); assertEquals(msg,10,(long)fieldStatsInfo.getCount()); assertEquals(msg,0,(long)fieldStatsInfo.getMissing()); if (allStats) { assertEquals(msg,248.0,fieldStatsInfo.getSum()); assertEquals(msg,15294.0,fieldStatsInfo.getSumOfSquares(),0.1E-7); assertEquals(msg,24.8,(double)fieldStatsInfo.getMean(),0.1E-7); assertEquals(msg,31.87405772027709,fieldStatsInfo.getStddev(),0.1E-7); } else { assertNull(msg,fieldStatsInfo.getSum()); assertNull(msg,fieldStatsInfo.getSumOfSquares()); assertNull(msg,fieldStatsInfo.getMean()); assertNull(msg,fieldStatsInfo.getStddev()); } if (params.getBool("facet",false)) { List<PivotField> placePivots=rsp.getFacetPivot().get("place_t,company_t"); assertEquals(1,placePivots.size()); PivotField dublinPivotField=placePivots.get(0); assertEquals("dublin",dublinPivotField.getValue()); assertEquals(4,dublinPivotField.getCount()); assertEquals(1,dublinPivotField.getPivot().size()); PivotField microsoftPivotField=dublinPivotField.getPivot().get(0); assertEquals("microsoft",microsoftPivotField.getValue()); assertEquals(4,microsoftPivotField.getCount()); FieldStatsInfo dublinMicrosoftStatsInfo=microsoftPivotField.getFieldStatsInfo().get("foo_i"); assertEquals(3.0D,dublinMicrosoftStatsInfo.getMin()); assertEquals(91.0D,dublinMicrosoftStatsInfo.getMax()); assertEquals(4,(long)dublinMicrosoftStatsInfo.getCount()); assertEquals(0,(long)dublinMicrosoftStatsInfo.getMissing()); if (!allStats) { assertNull(msg,dublinMicrosoftStatsInfo.getSum()); assertNull(msg,dublinMicrosoftStatsInfo.getSumOfSquares()); assertNull(msg,dublinMicrosoftStatsInfo.getMean()); assertNull(msg,dublinMicrosoftStatsInfo.getStddev()); } } } Object s0pivValue=clients.get(0).query(facetParams).getFacetPivot().get("place_t,company_t").get(0).getValue(); Object s1pivValue=clients.get(1).query(facetParams).getFacetPivot().get("place_t,company_t").get(0).getValue(); assertFalse("both shards have same top constraint, test is invalid" + "(did someone change the test data?) ==> " + s0pivValue + "=="+ s1pivValue,s0pivValue.equals(s1pivValue)); }
we need to ensure that stats never "overcount" the values from a single shard even if we hit that shard with a refinement request
@POST @Consumes({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON}) @Path("/{id}/deregister") @CheckPermission(roles={Role.SYSTEM_ADMIN,Role.RESTRICTED_SYSTEM_ADMIN}) public CustomConfigRestRep deregisterCustomConfig(@PathParam("id") URI id){ CustomConfig config=getCustomConfigById(id,true); if (config.getSystemDefault()) { throw APIException.badRequests.systemDefaultConfigCouldNotBeModifiedOrDeactivated(config.getId()); } config.setRegistered(false); _dbClient.updateAndReindexObject(config); auditOp(OperationTypeEnum.DEREGISTER_CONFIG,true,null,config.getId().toString(),config.getLabel(),config.getScope()); return DbObjectMapper.map(config); }
Deregister a config.
public static String atan(String[] params) throws FBSQLParseException { if (params.length != 1) throw new FBSQLParseException("Incorrect number of " + "parameters of function atan : " + params.length); return "atan(" + params[0] + ")"; }
Produce a function call for the <code>atan</code> UDF function. The syntax of the <code>atan</code> function is <code>{fn atan(float)}</code>.
protected ReplyProcessor21(DM dm,InternalDistributedSystem system,Collection initMembers,CancelCriterion cancelCriterion,boolean register){ if (!allowReplyFromSender()) { Assert.assertTrue(initMembers != null,"null initMembers"); Assert.assertTrue(system != null,"null system"); if (dm != null) { Assert.assertTrue(!initMembers.contains(dm.getId()),"dm present in initMembers but reply from sender is not allowed"); } } this.system=system; this.dmgr=dm; if (cancelCriterion == null) { cancelCriterion=dm.getCancelCriterion(); } this.latch=new StoppableCountDownLatch(cancelCriterion,1); int sz=initMembers.size(); this.members=new InternalDistributedMember[sz]; if (sz > 0) { int i=0; for (Iterator it=initMembers.iterator(); it.hasNext(); i++) { this.members[i]=(InternalDistributedMember)it.next(); } } this.done=false; this.shutdown=false; this.exception=null; if (register) { register(); } this.keeperCleanedUp=false; this.initTime=System.currentTimeMillis(); }
Construct new ReplyProcessor21.
public void addChild(FeatureTreeNode child) throws FeatureParsingException { if (this.isMetadataNode) { throw new FeatureParsingException("You can not add a child for metadata nodes. Node name " + this.name + ", value: "+ this.value+ "."); } if (child != null) { if (this.value == null) { this.children.add(child); child.parent=this; } else { throw new FeatureParsingException("You can not add a child for nodes with defined values. Node name " + this.name + ", value: "+ this.value+ "."); } } }
Add a child to the node
public static _Fields findByThriftId(int fieldId){ switch (fieldId) { case 1: return HEADER; case 2: return NODE_ID; case 3: return AUTH_SCHEME; case 4: return AUTH_CHALLENGE_RESPONSE; default : return null; } }
Find the _Fields constant that matches fieldId, or null if its not found.
private static RE brzozowski(Automaton fsm) throws InterruptedException { logger.debug("Brzozowski"); String singleton=fsm.getSingleton(); if (singleton != null) { return mkString(singleton); } if (fsm.isEmpty()) { logger.debug("Empty language"); } if (fsm.getAcceptStates().size() == 0) { logger.debug("No Accept States"); return empty; } if (fsm.getNumberOfStates() > 5000) { logger.debug("Way too many states, so minimizing"); fsm.minimize(); } int m=fsm.getNumberOfStates(); int idx=0; logger.debug("Have " + m + " states"); logger.debug("Allocating Arrays"); RE[][] a=new RE[m][m]; RE[] b=new RE[m]; logger.debug("Done Allocating Arrays"); Map<State,Integer> sm=new HashMap<State,Integer>(); State initial=fsm.getInitialState(); Set<State> available=fsm.getLiveStates(); logger.debug("Got Live States!"); Set<State> done=new HashSet<State>(); ArrayList<State> worklist=new ArrayList<State>(); idx=0; worklist.add(initial); while (!worklist.isEmpty()) { if (Thread.interrupted()) throw new InterruptedException(); State cur=worklist.remove(0); if (!done.contains(cur)) { sm.put(cur,idx); if (cur.isAccept()) { b[idx]=epsilon; } else { b[idx]=empty; } done.add(cur); idx++; for ( Transition t : cur.getTransitions()) { State dest=t.getDest(); if (available.contains(dest) && (!done.contains(dest))) { worklist.add(dest); } } } } for ( State s : fsm.getStates()) { int i=sm.get(s); for (int j=0; j < m; j++) a[i][j]=empty; for ( Transition t : s.getTransitions()) { int j=sm.get(t.getDest()); RE e=RE.mkRange(t.getMin(),t.getMax()); a[i][j]=a[i][j].union(e); } } for (int n=m - 1; n >= 0; n--) { b[n]=a[n][n].star().concat(b[n]); for (int j=0; j < n; j++) { a[n][j]=a[n][n].star().concat(a[n][j]); } for (int i=0; i < n; i++) { b[i]=b[i].union(a[i][n].concat(b[n])); for (int j=0; j < n; j++) { a[i][j]=a[i][j].union(a[i][n].concat(a[n][j])); } } for (int i=0; i < n; i++) { a[i][n]=empty; } } RE res=b[sm.get(fsm.getInitialState())]; return res; }
Converting a DFA to a Regular Expression. Translation of code from: http://cs.stackexchange.com/questions/2016/ \ how-to-convert-finite-automata-to-regular-expressions http://codepad.org/dbFztCCM
public Object call(int objectid,int methodid,Object[] args) throws RemoteException { boolean result; Object rvalue; String errmsg; try { Socket sock=new Socket(servername,port); OutputStream out=new BufferedOutputStream(sock.getOutputStream()); out.write(rmiCommand); out.write(endofline); out.write(endofline); ObjectOutputStream dout=new ObjectOutputStream(out); dout.writeInt(objectid); dout.writeInt(methodid); writeParameters(dout,args); dout.flush(); InputStream ins=new BufferedInputStream(sock.getInputStream()); skipHeader(ins); ObjectInputStream din=new ObjectInputStream(ins); result=din.readBoolean(); rvalue=null; errmsg=null; if (result) rvalue=din.readObject(); else errmsg=din.readUTF(); din.close(); dout.close(); sock.close(); if (rvalue instanceof RemoteRef) { RemoteRef ref=(RemoteRef)rvalue; rvalue=createProxy(ref.oid,ref.classname); } } catch ( ClassNotFoundException e) { throw new RemoteException(e); } catch ( IOException e) { throw new RemoteException(e); } catch ( Exception e) { throw new RemoteException(e); } if (result) return rvalue; else throw new RemoteException(errmsg); }
Calls a method on a remote object. It sends a POST request to the server (via an http proxy server if needed). <p>This method is called by only proxy objects.
public UpdateRequest refresh(boolean refresh){ this.refresh=refresh; return this; }
Should a refresh be executed post this update operation causing the operation to be searchable. Note, heavy indexing should not set this to <tt>true</tt>. Defaults to <tt>false</tt>.
public AsteroidsWithUI(){ super(new Asteroids(System.currentTimeMillis())); }
Creates a default Asteroids game.
public static double pow(double x,double y){ return Math.pow(x,y); }
Returns the value of the first argument raised to the power of the second argument.
@Override public void validate(){ }
empty method
public MemberName asNormalOriginal(){ byte normalVirtual=clazz.isInterface() ? REF_invokeInterface : REF_invokeVirtual; byte refKind=getReferenceKind(); byte newRefKind=refKind; MemberName result=this; switch (refKind) { case REF_invokeInterface: case REF_invokeVirtual: case REF_invokeSpecial: newRefKind=normalVirtual; break; } if (newRefKind == refKind) return this; result=clone().changeReferenceKind(newRefKind,refKind); assert (this.referenceKindIsConsistentWith(result.getReferenceKind())); return result; }
If this MN is a REF_invokeSpecial, return a clone with the "normal" kind REF_invokeVirtual; also switch either to REF_invokeInterface if clazz.isInterface. The end result is to get a fully virtualized version of the MN. (Note that resolving in the JVM will sometimes devirtualize, changing REF_invokeVirtual of a final to REF_invokeSpecial, and REF_invokeInterface in some corner cases to either of the previous two; this transform undoes that change under the assumption that it occurred.)
protected FloatBuffer computeCapNormals(ExtrudedBoundaryInfo boundary,FloatBuffer nBuf){ int nVerts=boundary.locations.size(); Vec4[] verts=boundary.capVertices; double avgX, avgY, avgZ; Vec4 va=verts[1].subtract3(verts[0]); Vec4 vb=verts[nVerts - 2].subtract3(verts[0]); avgX=(va.y * vb.z) - (va.z * vb.y); avgY=(va.z * vb.x) - (va.x * vb.z); avgZ=(va.x * vb.y) - (va.y * vb.x); for (int i=1; i < nVerts - 1; i++) { va=verts[i + 1].subtract3(verts[i]); vb=verts[i - 1].subtract3(verts[i]); avgX+=(va.y * vb.z) - (va.z * vb.y); avgY+=(va.z * vb.x) - (va.x * vb.z); avgZ+=(va.x * vb.y) - (va.y * vb.x); } avgX/=nVerts - 1; avgY/=nVerts - 1; avgZ/=nVerts - 1; double length=Math.sqrt(avgX * avgX + avgY * avgY + avgZ * avgZ); for (int i=0; i < nVerts; i++) { nBuf.put((float)(avgX / length)).put((float)(avgY / length)).put((float)(avgZ / length)); } nBuf.flip(); return nBuf; }
Compute normal vectors for an extruded polygon's cap vertices.
private void handleStartAction(SolrQueryRequest req,SolrQueryResponse rsp){ if (processStateManager.getState() == CdcrParams.ProcessState.STOPPED) { processStateManager.setState(CdcrParams.ProcessState.STARTED); processStateManager.synchronize(); } rsp.add(CdcrParams.CdcrAction.STATUS.toLower(),this.getStatus()); }
<p> Update and synchronize the process state. </p> <p> The process state manager must notify the replicator states manager of the change of state. </p>
public void testSerialization(){ DefaultPieDataset d1=new DefaultPieDataset(); d1.setValue("C1",new Double(234.2)); d1.setValue("C2",null); d1.setValue("C3",new Double(345.9)); d1.setValue("C4",new Double(452.7)); DefaultPieDataset d2=(DefaultPieDataset)TestUtilities.serialised(d1); assertEquals(d1,d2); }
Serialize an instance, restore it, and check for equality.
public Where<T,ID> raw(String rawStatement,ArgumentHolder... args){ for ( ArgumentHolder arg : args) { String columnName=arg.getColumnName(); if (columnName == null) { if (arg.getSqlType() == null) { throw new IllegalArgumentException("Either the column name or SqlType must be set on each argument"); } } else { arg.setMetaInfo(findColumnFieldType(columnName)); } } addClause(new Raw(rawStatement,args)); return this; }
Add a raw statement as part of the where that can be anything that the database supports. Using more structured methods is recommended but this gives more control over the query and allows you to utilize database specific features.
private static void startCMR(){ initLogger(); long startTime=System.nanoTime(); LOGGER.info("Central Measurement Repository is starting up!"); LOGGER.info("=============================================="); startRepository(); LOGGER.info("CMR started in " + Converter.nanoToMilliseconds(System.nanoTime() - startTime) + " ms"); }
Pseudo main method of class.
public String toString(){ String result=super.toString() + "SubjectAlternativeName [\n"; if (names == null) { result+=" null\n"; } else { for ( GeneralName name : names.names()) { result+=" " + name + "\n"; } } result+="]\n"; return result; }
Returns a printable representation of the SubjectAlternativeName.
protected String doIt() throws Exception { log.info("Selection=" + p_Selection + ", DateInvoiced="+ p_DateInvoiced+ ", AD_Org_ID="+ p_AD_Org_ID+ ", C_BPartner_ID="+ p_C_BPartner_ID+ ", M_InOut_ID="+ p_M_InOut_ID+ ", DocAction="+ p_docAction+ ", Consolidate="+ p_ConsolidateDocument); String sql=null; if (p_Selection) { sql="SELECT M_InOut.* FROM M_InOut, T_Selection " + "WHERE M_InOut.DocStatus='CO' AND M_InOut.IsSOTrx='Y' " + " AND M_InOut.M_InOut_ID = T_Selection.T_Selection_ID "+ " AND T_Selection.AD_PInstance_ID=? "+ "ORDER BY M_InOut.M_InOut_ID"; } else { sql="SELECT * FROM M_InOut o " + "WHERE DocStatus IN('CO','CL') AND IsSOTrx='Y'"; if (p_AD_Org_ID != 0) sql+=" AND AD_Org_ID=?"; if (p_C_BPartner_ID != 0) sql+=" AND C_BPartner_ID=?"; if (p_M_InOut_ID != 0) sql+=" AND M_InOut_ID=?"; sql+=" AND EXISTS (SELECT * FROM M_InOutLine ol " + "WHERE o.M_InOut_ID=ol.M_InOut_ID AND ol.IsInvoiced='N') " + "ORDER BY M_InOut_ID"; } PreparedStatement pstmt=null; try { pstmt=DB.prepareStatement(sql,get_TrxName()); int index=1; if (p_Selection) { pstmt.setInt(index,getAD_PInstance_ID()); } else { if (p_AD_Org_ID != 0) pstmt.setInt(index++,p_AD_Org_ID); if (p_C_BPartner_ID != 0) pstmt.setInt(index++,p_C_BPartner_ID); if (p_M_InOut_ID != 0) pstmt.setInt(index++,p_M_InOut_ID); } } catch ( Exception e) { log.log(Level.SEVERE,sql,e); } return generate(pstmt); }
Generate Invoices from Shipments
public StylesheetPIHandler(String baseID,String media,String title,String charset){ m_baseID=baseID; m_media=media; m_title=title; m_charset=charset; }
Construct a StylesheetPIHandler instance that will search for xml-stylesheet PIs based on the given criteria.
public boolean isMoreSpecific(Type from,Type to) throws ClassNotFound { return implicitCast(from,to); }
Returns true if "from" is a more specific type than "to"
public QueryEvaluationException(String msg){ super(msg); }
Creates a new TupleQueryResultHandlerException.
public void testEdgeCase(){ final int bits=3; final int size=1 << bits; final IntIndex ix0=new IntChunks(size - 1,bits); ix0.integrity(); final IntIndex ix1=new IntChunks(size,bits); ix1.integrity(); final IntIndex ix2=new IntChunks(size + 1,bits); ix2.integrity(); }
Tests allocations of chunks and fomula for computing how many chunks there are.
private void scheduleCacheCleanup(Context context){ if (!isAlarmActive(context)) { mAlarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,SystemClock.elapsedRealtime() + CLEANUP_SCHEDULER_TIME_INTERVAL,CLEANUP_SCHEDULER_TIME_INTERVAL,CacheCleanupReceiver.makeReceiverPendingIntent(context)); } }
Helper method that uses AlarmManager to schedule Cache Cleanup at regular intervals.
@Override public String toString(){ return super.toString(); }
Returns a String representation of this object.
public int read(long position,ByteBuf dst,int dstStart,int dstLength) throws IOException { final int bufferPosition=checkOffset(position,dstLength); final long srcAddress=PlatformDependent.directBufferAddress(lastMapped) + bufferPosition; if (dst.hasMemoryAddress()) { final long dstAddress=dst.memoryAddress() + dstStart; PlatformDependent.copyMemory(srcAddress,dstAddress,dstLength); } else if (dst.hasArray()) { final byte[] dstArray=dst.array(); PlatformDependent.copyMemory(srcAddress,dstArray,dstStart,dstLength); } else { throw new IllegalArgumentException("unsupported byte buffer"); } position+=dstLength; if (position > this.length) { this.length=position; } return dstLength; }
Reads a sequence of bytes from this file into the given buffer. <p> <p> Bytes are read starting at this file's specified position.
public GitConflictException(String message,Throwable cause){ super(message,cause); }
Construct a new GitConflictException based on message and cause
@DSComment("Package priviledge") @DSBan(DSCat.DEFAULT_MODIFIER) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 13:01:14.668 -0500",hash_original_method="666C086AB9DBFD99FFC100F4BBE01D6D",hash_generated_method="3F628D0222C9A381116CFF161912E138") Impl(File directory) throws IOException { boolean exists=directory.exists(); if (exists && !directory.isDirectory()) { throw new IOException(directory + " exists but is not a directory."); } if (exists) { initialFiles=directory.list(); if (initialFiles == null) { throw new IOException(directory + " exists but cannot list contents."); } Arrays.sort(initialFiles); size=initialFiles.length; } else { if (!directory.mkdirs()) { throw new IOException("Creation of " + directory + " directory failed."); } size=0; } this.directory=directory; }
Constructs a new cache backed by the given directory.
public FlyweightProcessingInstruction(String target,Map<String,String> values){ this.target=target; this.values=values; this.text=toString(values); }
<p> This will create a new PI with the given target and values </p>
public synchronized void decrementState(MentalState state){ if (this.state.ordinal() > state.ordinal()) { setState(state); } }
Ensure the maximum state.
private synchronized void addLookupToCache(String lookupName,LookupQualifier qualifier,Lookup lookup){ Hashtable<String,Lookup> lookupsByQualifier=_lookups.get(lookupName); if (null == lookupsByQualifier) { lookupsByQualifier=new Hashtable<String,Lookup>(); _lookups.put(lookupName,lookupsByQualifier); } lookupsByQualifier.put(qualifier.toString(),lookup); }
Method addLookupToCache.
@Override public boolean containsKey(Object key){ return _map.containsKey(unwrapKey(key)); }
Checks for the present of <tt>key</tt> in the keys of the map.
public boolean sphereInFrustumWithoutNearFar(Vector3 center,float radius){ for (int i=2; i < 6; i++) if ((planes[i].normal.x * center.x + planes[i].normal.y * center.y + planes[i].normal.z * center.z) < (-radius - planes[i].d)) return false; return true; }
Returns wheter the given sphere is in the frustum not checking wheter it is behind the near and far clipping plane.
protected void formatAnnotationMirror(AnnotationMirror am,StringBuilder sb){ sb.append("@"); sb.append(am.getAnnotationType().asElement().getSimpleName()); Map<? extends ExecutableElement,? extends AnnotationValue> args=am.getElementValues(); if (!args.isEmpty()) { sb.append("("); boolean oneValue=false; if (args.size() == 1) { Map.Entry<? extends ExecutableElement,? extends AnnotationValue> first=args.entrySet().iterator().next(); if (first.getKey().getSimpleName().contentEquals("value")) { formatAnnotationMirrorArg(first.getValue(),sb); oneValue=true; } } if (!oneValue) { boolean notfirst=false; for ( Map.Entry<? extends ExecutableElement,? extends AnnotationValue> arg : args.entrySet()) { if (notfirst) { sb.append(", "); } notfirst=true; sb.append(arg.getKey().getSimpleName() + "="); formatAnnotationMirrorArg(arg.getValue(),sb); } } sb.append(")"); } }
A helper method to output a single AnnotationMirror, without showing full package names.
int attribArgs(List<JCExpression> trees,Env<AttrContext> env,ListBuffer<Type> argtypes){ int kind=VAL; for ( JCExpression arg : trees) { Type argtype; if (allowPoly && deferredAttr.isDeferred(env,arg)) { argtype=deferredAttr.new DeferredType(arg,env); kind|=POLY; } else { argtype=chk.checkNonVoid(arg,attribTree(arg,env,unknownAnyPolyInfo)); } argtypes.append(argtype); } return kind; }
Attribute the arguments in a method call, returning the method kind.
public NotificationChain basicSet_lok(LocalArgumentsVariable new_lok,NotificationChain msgs){ LocalArgumentsVariable old_lok=_lok; _lok=new_lok; if (eNotificationRequired()) { ENotificationImpl notification=new ENotificationImpl(this,Notification.SET,N4JSPackage.N4_FIELD_ACCESSOR__LOK,old_lok,new_lok); if (msgs == null) msgs=notification; else msgs.add(notification); } return msgs; }
<!-- begin-user-doc --> <!-- end-user-doc -->
public void runTest() throws Throwable { Document doc; NodeList addressList; Node testNode; NamedNodeMap attributes; Attr streetAttr; String value; doc=(Document)load("hc_staff",true); addressList=doc.getElementsByTagName("acronym"); testNode=addressList.item(3); attributes=testNode.getAttributes(); streetAttr=(Attr)attributes.getNamedItem("class"); streetAttr.setValue("Y&ent1;"); value=streetAttr.getValue(); assertEquals("value","Y&ent1;",value); value=streetAttr.getNodeValue(); assertEquals("nodeValue","Y&ent1;",value); }
Runs the test case.
public static void correctTableFocusTraversal(JTable table){ table.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,Collections.singleton(AWTKeyStroke.getAWTKeyStroke("TAB"))); table.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,Collections.singleton(AWTKeyStroke.getAWTKeyStroke("shift TAB"))); }
Make JTable handle TAB key as all other components - move focus to next/previous components. <p>Default Swing behaviour for table is to move focus to next/previous cell inside the table.</p>
@DSComment("constructor") @DSSafe(DSCat.SAFE_OTHERS) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:56:19.811 -0500",hash_original_method="9D77FFE69AA84BF1048ED5CBD8EE386C",hash_generated_method="14BE1B47B3BDFB19FC4452BDB9ABB0DE") public String(byte[] data,Charset charset){ this(data,0,data.length,charset); }
Converts the byte array to a String using the given charset.
public SendablePhotoMessage.SendablePhotoMessageBuilder disableNotification(boolean disableNotification){ this.disableNotification=disableNotification; return this; }
*Optional Sets whether or not to disable any notification this message might usually cause. Defaults to False
public boolean isResponseAvailable(final int timeout) throws IOException { LOG.trace("enter HttpConnection.isResponseAvailable(int timeout: " + timeout + ")"); assertOpen(); boolean result=false; if (inputStream.available() > 0) { result=true; } else { try { socket.setSoTimeout(timeout); inputStream.mark(1); final int byteRead=inputStream.read(); if (byteRead != -1) { inputStream.reset(); LOG.debug("Input data available"); result=true; } else { LOG.debug("Input data not available"); } } catch ( final InterruptedIOException e) { if (!ExceptionUtil.isSocketTimeoutException(e)) { throw e; } if (LOG.isDebugEnabled()) { LOG.debug("Input data not available after " + timeout + " ms"); } } finally { try { socket.setSoTimeout(params.getSoTimeout()); } catch ( final IOException ioe) { LOG.debug("An error ocurred while resetting soTimeout, we will assume that" + " no response is available.",ioe); result=false; } } } return result; }
Tests if input data becomes available within the given period time in milliseconds.
@Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.tv_album_list); }
Called when the activity is first created.
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:31:36.474 -0500",hash_original_method="32065C4976C924BEAD40EDE2A514E0EE",hash_generated_method="CC87C1C88F7B8E80FD89EE1BFCFB11DF") public boolean isColumnStretchable(int columnIndex){ return mStretchAllColumns || mStretchableColumns.get(columnIndex); }
<p>Returns whether the specified column is stretchable or not.</p>
private static void calcNetForceExertedByXY(){ System.out.println("Checking setNetForce..."); Planet p1=new Planet(1.0,1.0,3.0,4.0,5.0,"jupiter.gif"); Planet p2=new Planet(2.0,1.0,3.0,4.0,4e11,"jupiter.gif"); Planet p3=new Planet(4.0,5.0,3.0,4.0,5.0,"jupiter.gif"); Planet p4=new Planet(3.0,2.0,3.0,4.0,5.0,"jupiter.gif"); Planet[] planets={p2,p3,p4}; double xNetForce=p1.calcNetForceExertedByX(planets); double yNetForce=p1.calcNetForceExertedByY(planets); checkEquals(133.4,round(xNetForce,2),"calcNetForceExertedByX()"); checkEquals(0.0,round(yNetForce,2),"calcNetForceExertedByY()"); System.out.println("Running test again, but with array that contains the target planet."); planets=new Planet[]{p1,p2,p3,p4}; xNetForce=p1.calcNetForceExertedByX(planets); yNetForce=p1.calcNetForceExertedByY(planets); checkEquals(133.4,round(xNetForce,2),"calcNetForceExertedByX()"); checkEquals(0.0,round(yNetForce,2),"calcNetForceExertedByY()"); }
Checks the Planet class to make sure setNetForce works.
private void popCurrentDoc(){ assert numSubsOnDoc == 0; assert docIDQueue.size() > 0; subsOnDoc[numSubsOnDoc++]=docIDQueue.pop(); docID=subsOnDoc[0].posEnum.docID(); while (docIDQueue.size() > 0 && docIDQueue.top().posEnum.docID() == docID) { subsOnDoc[numSubsOnDoc++]=docIDQueue.pop(); } }
Pops all enums positioned on the current (minimum) doc
public Object runSafely(Catbert.FastStack stack) throws Exception { return IOUtils.getFileAsString(getFile(stack)); }
Opens the file at the specified path and reads the entire contents of it and returns it as a String.
public String engineGetProperty(String key){ if (properties == null) { return null; } return properties.get(key); }
Method engineGetProperty
public void logInWithReadPermissions(Fragment fragment,Collection<String> permissions){ validateReadPermissions(permissions); LoginClient.Request loginRequest=createLoginRequest(permissions); startLogin(new FragmentStartActivityDelegate(fragment),loginRequest); }
Logs the user in with the requested read permissions.
Record makeRecord(String line){ if (line == null || "".equals(line)) return null; BreastCancerWRecord r=new BreastCancerWRecord(); String[] split=line.split(","); String col; for (int i=0; i < split.length; i++) { col=split[i].replaceAll("'",""); if (i == 0) { r.clumpThickness="?".equals(col) ? 0 : (Float.valueOf(col) - 1) / 9f; } else if (i == 1) { r.cellSizeUniformity="?".equals(col) ? 0 : (Float.valueOf(col) - 1) / 9f; } else if (i == 2) { r.cellShapeUniformity="?".equals(col) ? 0 : (Float.valueOf(col) - 1) / 9f; } else if (i == 3) { r.marginalAdhesion="?".equals(col) ? 0 : (Float.valueOf(col) - 1) / 9f; } else if (i == 4) { r.singleEpiCellSize="?".equals(col) ? 0 : (Float.valueOf(col) - 1) / 9f; } else if (i == 5) { r.bareNuclei="?".equals(col) ? 0 : (Float.valueOf(col) - 1) / 9f; } else if (i == 6) { r.blandChromatin="?".equals(col) ? 0 : (Float.valueOf(col) - 1) / 9f; } else if (i == 7) { r.normalNucleoli="?".equals(col) ? 0 : (Float.valueOf(col) - 1) / 9f; } else if (i == 8) { r.mitoses="?".equals(col) ? 0 : (Float.valueOf(col) - 1) / 9f; } else if (i == 9) { r.malignant="malignant".equals(col); } else { System.err.println("Too many columns!!!"); } } return r; }
Interpret a line from the data file into a Record instance. Handles missing values.
private void addToCache(JarInputStream fis,String mnemo){ String text=""; byte[] buf=new byte[4096]; int i=0; try { while ((i=fis.read(buf)) != -1) { text+=new String(buf,0,i); } } catch ( IOException ignored) { } helpcache.put(mnemo,text); }
load from specified JarInputStream
public ReportedData submitSearch(String serviceJID,Form completedForm) throws XMPPException { TranscriptSearch search=new TranscriptSearch(); search.setType(IQ.Type.GET); search.setTo(serviceJID); search.addExtension(completedForm.getDataFormToSend()); PacketCollector collector=connection.createPacketCollector(new PacketIDFilter(search.getPacketID())); connection.sendPacket(search); TranscriptSearch response=(TranscriptSearch)collector.nextResult(SmackConfiguration.getPacketReplyTimeout()); collector.cancel(); if (response == null) { throw new XMPPException("No response from server on status set."); } if (response.getError() != null) { throw new XMPPException(response.getError()); } return ReportedData.getReportedDataFrom(response); }
Submits the completed form and returns the result of the transcript search. The result will include all the data returned from the server so be careful with the amount of data that the search may return.
public static boolean cs_lusol(int order,Scs A,float[] b,float tol){ float[] x; Scss S; Scsn N; int n; boolean ok; if (!Scs_util.CS_CSC(A) || b == null) return (false); n=A.n; S=Scs_sqr.cs_sqr(order,A,false); N=Scs_lu.cs_lu(A,S,tol); x=new float[n]; ok=(S != null && N != null); if (ok) { Scs_ipvec.cs_ipvec(N.pinv,b,x,n); Scs_lsolve.cs_lsolve(N.L,x); Scs_usolve.cs_usolve(N.U,x); Scs_ipvec.cs_ipvec(S.q,x,b,n); } return (ok); }
Solves Ax=b, where A is square and nonsingular. b overwritten with solution. Partial pivoting if tol = 1.f
public void copySourceTemplatesFile(SdfReaderWrapper reader) throws IOException { if (mIsPaired) { SourceTemplateReadWriter.writeTemplateMappingFile(mLeft.directory(),SourceTemplateReadWriter.readTemplateMap(reader.left().path())); SourceTemplateReadWriter.writeTemplateMappingFile(mRight.directory(),SourceTemplateReadWriter.readTemplateMap(reader.right().path())); SourceTemplateReadWriter.copyMutationMappingFile(reader.left().path(),mLeft.directory()); SourceTemplateReadWriter.copyMutationMappingFile(reader.right().path(),mRight.directory()); } else { SourceTemplateReadWriter.writeTemplateMappingFile(mSingle.directory(),SourceTemplateReadWriter.readTemplateMap(reader.single().path())); SourceTemplateReadWriter.copyMutationMappingFile(reader.single().path(),mSingle.directory()); } }
Function to copy the source templates file into the resulting SDF files if it exists in the original SDF file.
@Override public String toString(){ StringBuilder b=new StringBuilder(); b.append("// <ExceptionalExecution, exception type=" + exception.getClass().getName()); b.append(">;"); return b.toString(); }
Warning: this method calls toString() of code under test, which may have arbitrary behavior. We use this method in randoop.test.SequenceTests.
public boolean hasThumbnailExt(){ return hasExtension(GphotoThumbnail.class); }
Returns whether it has the user portrait thumbnail.
public GraphicContext(){ }
Instantiates a new graphic context.
public DomainObjectException(String message,Throwable cause){ super(message,cause); }
Constructs a new exception with the specified detail message and cause.
public static <E,M,A>ProducerT<E,M,A> done(A r){ return ProducerT.producerT(FreeT.done(r)); }
A Generator that has finished.
public IsometricViewAction(final VisionWorld visionWorld){ super("Isometric view"); if (visionWorld == null) { throw new IllegalArgumentException("visionWorld must not be null"); } this.visionWorld=visionWorld; }
Create a new isometric view action.
public ProjectTodoStatusObject(int id){ this.id=id; }
This method was generated by MyBatis Generator. This method corresponds to the database table project_todo_status
public void enableOverview(boolean b){ if (overviewItem != null) { overviewItem.setEnabled(b); } }
Enable / disable the overview menu.
public Vector3 add(float x,float y,float z){ return this.set(this.x + x,this.y + y,this.z + z); }
Adds the given vector to this component
public HttpResponse send(final Method method,final String path,final HttpEntity payload){ try { return sendAsync(method,path,payload,null).get(); } catch ( InterruptedException|ExecutionException|IOException e) { throw new RuntimeException(e); } }
Sends a HTTP request synchronously on the given path with payload.
private void constructTimeSteps(){ int numTimeSteps=(1 + getStepsGenerated() - getFirstStepStored()) / getInterval(); this.timeSteps=new int[numTimeSteps]; for (int i=0; i < timeSteps.length; i++) { this.timeSteps[i]=getFirstStepStored() + i * getInterval(); } }
Constructs an array of integers that indicate the time steps of the data that will be simulated. Integers in this array must be >= 1 and must be in strictly increasing order--in other words, <code>timeSteps[i] < timeSteps[i+1]</code> for i = 0, ..., timeSteps.length - 1.
protected void failIfErrors() throws CompilationFailedException { if (hasErrors()) { throw new MultipleCompilationErrorsException(this); } }
Causes the current phase to fail by throwing a CompilationFailedException.
@Override public void menuAboutToShow(IMenuManager menuManager){ super.menuAboutToShow(menuManager); MenuManager submenuManager=null; submenuManager=new MenuManager(EipEditorPlugin.INSTANCE.getString("_UI_CreateChild_menu_item")); populateManager(submenuManager,createChildActions,null); menuManager.insertBefore("edit",submenuManager); submenuManager=new MenuManager(EipEditorPlugin.INSTANCE.getString("_UI_CreateSibling_menu_item")); populateManager(submenuManager,createSiblingActions,null); menuManager.insertBefore("edit",submenuManager); }
This populates the pop-up menu before it appears. <!-- begin-user-doc --> <!-- end-user-doc -->
LongEntry<VALUE> removeMapping(Object o){ if (!(o instanceof LongEntry)) return null; LongEntry<VALUE> entry=(LongEntry<VALUE>)o; int hash=hash(entry.key); int i=indexFor(hash,table.length); LongEntry<VALUE> prev=table[i]; LongEntry<VALUE> e=prev; while (e != null) { LongEntry<VALUE> next=e.next; if (e.hash == hash && e.equals(entry)) { modCount++; size--; if (prev == e) table[i]=next; else prev.next=next; return e; } prev=e; e=next; } return e; }
Special version of remove for EntrySet.
public final void yybegin(int newState){ zzLexicalState=newState; }
Enters a new lexical state
public void parsePersons(String filename){ LOG.info("Parsing persons from " + filename); Counter counter=new Counter(" persons # "); BufferedReader br=IOUtils.getBufferedReader(filename); try { String line=null; while ((line=br.readLine()) != null) { String serial=line.substring(0,9); String quarterType=line.substring(9,11); String person=line.substring(11,15); String age=line.substring(23,26); String gender=line.substring(26,27); String relationship=line.substring(27,29); String population=line.substring(32,33); String school=line.substring(83,84); String employment=line.substring(96,98); String sector=line.substring(99,102); String hours=line.substring(105,107); String workplace=line.substring(107,108); String mainPlaceOfWork=line.substring(109,117); String travel=line.substring(143,144); String income=line.substring(144,146); String enumeration=line.substring(146,147); String s=getComprehensiveQuarterType(quarterType) + "," + Integer.parseInt(age)+ ","+ getGender(gender)+ ","+ getRelationship(relationship)+ ","+ getPopulation(population)+ ","+ getSchool(school)+ ","+ getDerivedEmployment(employment)+ ","+ getMainPlaceOfWork(mainPlaceOfWork)+ ","+ getMainModeToPrimary(travel)+ ","+ getIncome(income); personMap.put(Id.create(serial + "_" + String.valueOf(Integer.parseInt(person)),Person.class),s); counter.incCounter(); } } catch ( IOException e) { throw new RuntimeException("Could not read from BufferedReader " + filename); } finally { try { br.close(); } catch ( IOException e) { throw new RuntimeException("Could not close BufferedReader " + filename); } } counter.printCounter(); LOG.info("Done parsing persons (" + personMap.size() + ")."); }
Each line contains the record of a person. The following segments are currently parsed (The first number indicates the position in the string, and the second number in brackets the number of characters): <ul> <li> Serial number - 1(9); <li> Type of living quarters comprehensive (code) - 10(2); <li> Person number - 12(4); <li> Age - 24(3); <li> Gender (code) - 27(1); <li> Relationship (code) - 28(2); <li> Population group (code) - 33(1); <li> Present school attendance (code) - 84(1); <li> Employment status (code) - 97(2); <li> Economic sector (code) - 100(3); [Currently not used] <li> Hours worked (code) - 106(2); [Currently not used] <li> Place of work (code) - 108(1); [Currently not used] <li> Main place of work (code) - 110(8); <li> Travel to school / place of work (code) - 144(1); <li> Income (code) - 145(2); <li> Place of enumeration - 147(1); [Currently not used] </ul>
@Override public void snmpV2Trap(SnmpOid trapOid,SnmpVarBindList varBindList) throws IOException, SnmpStatusException { if (SNMP_ADAPTOR_LOGGER.isLoggable(Level.FINER)) { SNMP_ADAPTOR_LOGGER.logp(Level.FINER,dbgTag,"snmpV2Trap","trapOid=" + trapOid); } SnmpPduRequest pdu=new SnmpPduRequest(); pdu.address=null; pdu.port=trapPort; pdu.type=pduV2TrapPdu; pdu.version=snmpVersionTwo; pdu.community=null; SnmpVarBindList fullVbl; if (varBindList != null) fullVbl=varBindList.clone(); else fullVbl=new SnmpVarBindList(2); SnmpTimeticks sysUpTimeValue=new SnmpTimeticks(getSysUpTime()); fullVbl.insertElementAt(new SnmpVarBind(snmpTrapOidOid,trapOid),0); fullVbl.insertElementAt(new SnmpVarBind(sysUpTimeOid,sysUpTimeValue),0); pdu.varBindList=new SnmpVarBind[fullVbl.size()]; fullVbl.copyInto(pdu.varBindList); sendTrapPdu(pdu); }
Sends a trap using SNMP V2 trap format. <BR>The trap is sent to each destination defined in the ACL file (if available). If no ACL file or no destinations are available, the trap is sent to the local host. <BR>The variable list included in the outgoing trap is composed of the following items: <UL> <LI><CODE>sysUpTime.0</CODE> with its current value</LI> <LI><CODE>snmpTrapOid.0</CODE> with the value specified by <CODE>trapOid</CODE></LI> <LI><CODE>all the (oid,values)</CODE> from the specified <CODE>varBindList</CODE></LI> </UL>
public boolean equivTo(Object c){ if (sourcename instanceof Value) return (c instanceof AbstractDataSource && ((Value)sourcename).equivTo(((AbstractDataSource)c).sourcename)); return (c instanceof AbstractDataSource && ((AbstractDataSource)c).sourcename.equals(sourcename)); }
Returns true if this object is structurally equivalent to c. AbstractDataSources are equal and equivalent if their sourcename is the same
public void accept(String key,String val,Integer arg) throws ConfigurationException { if (arg < min || arg > max) { throw new ConfigurationException(key,val,"Must be in [" + min + ":"+ max+ "]"); } }
Accepts all values in the range specified to the ctor.
public Shape apply(V v){ Icon icon=iconMap.get(v); if (icon != null && icon instanceof ImageIcon) { Image image=((ImageIcon)icon).getImage(); Shape shape=(Shape)shapeMap.get(image); if (shape == null) { shape=ImageShapeUtils.getShape(image,30); if (shape.getBounds().getWidth() > 0 && shape.getBounds().getHeight() > 0) { int width=image.getWidth(null); int height=image.getHeight(null); AffineTransform transform=AffineTransform.getTranslateInstance(-width / 2,-height / 2); shape=transform.createTransformedShape(shape); shapeMap.put(image,shape); } } return shape; } else { return delegate.apply(v); } }
get the shape from the image. If not available, get the shape from the delegate VertexShapeFunction
public Quagliarella(){ this(16); }
Constructs the Quagliarella problem.
public static <T>LazyPQueueX<T> fromIterable(Reducer<PQueue<T>> collector,Iterable<T> it){ if (it instanceof LazyPQueueX) return (LazyPQueueX<T>)it; if (it instanceof PQueue) return new LazyPQueueX<T>((PQueue<T>)it,collector); return new LazyPQueueX<T>(Flux.fromIterable(it),collector); }
Construct a LazyPStackX from an Iterable, using the specified Collector.
public void remove(String userId) throws ServerException { requireNonNull(userId,"Required non-null user id"); preferenceDao.remove(userId); }
Removes(clears) user's preferences.
public boolean isSourceAvailable(){ return sourceAvailable; }
Gets the value of the sourceAvailable property.
public boolean isFixedView(View v){ { ArrayList<FixedViewInfo> where=mHeaderViewInfos; int len=where.size(); for (int i=0; i < len; ++i) { FixedViewInfo info=where.get(i); if (info.view == v) { return true; } } } { ArrayList<FixedViewInfo> where=mFooterViewInfos; int len=where.size(); for (int i=0; i < len; ++i) { FixedViewInfo info=where.get(i); if (info.view == v) { return true; } } } return false; }
check this view is fixed view(ex>Header & Footer) or not.
public boolean equals(Object other){ if (other == null || !(other instanceof GF2nPolynomialElement)) { return false; } GF2nPolynomialElement otherElem=(GF2nPolynomialElement)other; if (mField != otherElem.mField) { if (!mField.getFieldPolynomial().equals(otherElem.mField.getFieldPolynomial())) { return false; } } return polynomial.equals(otherElem.polynomial); }
Compare this element with another object.
public boolean isZero(){ return value.isZero(); }
Test for zero. Equivalent to .EQ(Word.zero())