code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
public RegisterServer2Request clone(){
RegisterServer2Request result=new RegisterServer2Request();
result.RequestHeader=RequestHeader == null ? null : RequestHeader.clone();
result.Server=Server == null ? null : Server.clone();
return result;
}
| Deep clone |
public void restartPlayback(Context context){
Log.i("CAMERA","Restarting playback!!");
init(context);
startPlayback();
}
| NEW METHOD Restarts playback if goes down |
public String previousToken(){
if (hasPrevious()) {
return tokens[--tokenPos];
}
return null;
}
| Gets the previous token from the String. |
@POST @Produces({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON}) @Path("/{id}/deregister") @CheckPermission(roles={Role.TENANT_ADMIN}) public InitiatorRestRep deregisterInitiator(@PathParam("id") URI id){
Initiator initiator=queryResource(id);
ArgValidator.checkEntity(initiator,id,isIdEmbeddedInURL(id));
if (ComputeSystemHelper.isInitiatorInUse(_dbClient,id.toString())) {
throw APIException.badRequests.resourceHasActiveReferencesWithType(Initiator.class.getSimpleName(),initiator.getId(),ExportGroup.class.getSimpleName());
}
if (RegistrationStatus.REGISTERED.toString().equalsIgnoreCase(initiator.getRegistrationStatus())) {
initiator.setRegistrationStatus(RegistrationStatus.UNREGISTERED.toString());
_dbClient.persistObject(initiator);
auditOp(OperationTypeEnum.DEREGISTER_INITIATOR,true,null,initiator.getLabel(),initiator.getId().toString());
}
return map(initiator);
}
| Allows the user to deregister a registered initiator so that it is no longer used by the system. This simply sets the registration_status of the initiator to UNREGISTERED. |
public int indexOf(final AbstractInsnNode insn){
if (cache == null) {
cache=toArray();
}
return insn.index;
}
| Returns the index of the given instruction in this list. This method builds a cache of the instruction indexes to avoid scanning the whole list each time it is called. Once the cache is built, this method run in constant time. The cache is invalidated by all the methods that modify the list. |
public static Vector<Object> inputs(Vector<Object> subset,Integer... tab){
Vector<Object> result=new Vector<Object>();
for (int i=0; i < subset.size(); i++) {
BeanInstance temp=(BeanInstance)subset.elementAt(i);
if (checkTargetConstraint(temp,subset,tab)) {
result.add(temp);
}
}
return result;
}
| Returns a vector of BeanInstances that can be considered as inputs (or the left-hand side of a sub-flow) |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:33:19.764 -0500",hash_original_method="47CE65B8425CCCD6D64866E88AA89041",hash_generated_method="9066BCE4D54754916DEFAD52BAF6D753") public boolean restoreState(Bundle inState){
if (DebugFlags.NETWORK) {
Log.v(LOGTAG,"Network.restoreState()");
}
return mSslErrorHandler.restoreState(inState);
}
| Restores the state of network handlers (user SSL and HTTP-authentication preferences). |
public boolean isSetStoreName(){
return this.storeName != null;
}
| Returns true if field storeName is set (has been assigned a value) and false otherwise |
public static void wtf(String tag,String msg,Throwable tr){
println(ASSERT,tag,msg,tr);
}
| Prints a message at ASSERT priority. |
public NativePooledByteBufferOutputStream(NativeMemoryChunkPool pool,int initialCapacity){
super();
Preconditions.checkArgument(initialCapacity > 0);
mPool=Preconditions.checkNotNull(pool);
mCount=0;
mBufRef=CloseableReference.of(mPool.get(initialCapacity),mPool);
}
| Construct a new instance of this output stream with this initial capacity It is not an error to have this initial capacity be inaccurate. If the actual contents end up being larger than the initialCapacity, then we will reallocate memory if needed. If the actual contents are smaller, then we'll end up wasting some memory |
private static Object add(final Object array,final int index,final Object element,final Class<?> clss){
if (array == null) {
if (index != 0) {
throw new IndexOutOfBoundsException("Index: " + index + ", Length: 0");
}
final Object joinedArray=Array.newInstance(clss,1);
Array.set(joinedArray,0,element);
return joinedArray;
}
final int length=Array.getLength(array);
if (index > length || index < 0) {
throw new IndexOutOfBoundsException("Index: " + index + ", Length: "+ length);
}
final Object result=Array.newInstance(clss,length + 1);
System.arraycopy(array,0,result,0,index);
Array.set(result,index,element);
if (index < length) {
System.arraycopy(array,index,result,index + 1,length - index);
}
return result;
}
| Underlying implementation of add(array, index, element) methods. The last parameter is the class, which may not equal element.getClass for primitives. |
public Notification updateNotification(BigInteger alertId,BigInteger notificationId,Notification notification) throws IOException {
String requestUrl=RESOURCE + "/" + alertId.toString()+ "/notifications/"+ notificationId.toString();
ArgusResponse response=getClient().executeHttpRequest(ArgusHttpClient.RequestType.PUT,requestUrl,notification);
assertValidResponse(response,requestUrl);
return fromJson(response.getResult(),Notification.class);
}
| Updates an existing notification. |
private void showSoftKeyboard(View triggerView){
if (BuildConfig.DEBUG) Log.v("showSoftKeyboard()");
if (inputManager == null) {
inputManager=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
}
inputView=triggerView;
inputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
}
| Show the soft keyboard and store the view that triggered it |
public TermPayloadIterablePosting(BitIn _bitFileReader,int _numEntries,DocumentIndex doi) throws IOException {
super(_bitFileReader,_numEntries,doi);
}
| Create a new posting iterator |
private int insertTestDataOffsetDTTypes(PreparedStatement pstmt) throws Exception {
pstmt.setInt(1,1);
pstmt.setObject(2,testOffsetTime,JDBCType.VARCHAR);
pstmt.setObject(3,testOffsetTime);
pstmt.setObject(4,testOffsetDateTime,JDBCType.VARCHAR);
pstmt.setObject(5,testOffsetDateTime);
assertEquals(1,pstmt.executeUpdate());
if (pstmt instanceof CallableStatement) {
CallableStatement cstmt=(CallableStatement)pstmt;
cstmt.setInt("id",2);
cstmt.setObject("ot1",testOffsetTime,JDBCType.VARCHAR);
cstmt.setObject("ot2",testOffsetTime);
cstmt.setObject("odt1",testOffsetDateTime,JDBCType.VARCHAR);
cstmt.setObject("odt2",testOffsetDateTime);
assertEquals(1,cstmt.executeUpdate());
return 2;
}
return 1;
}
| Helper method for *SetObject* tests. Insert data into the given PreparedStatement, or any of its subclasses, with the following structure: 1 - `id` INT 2 - `ot1` VARCHAR 3 - `ot2` BLOB 4 - `odt1` VARCHAR 5 - `odt2` BLOB |
private Builder(){
}
| Prevent direct construction. |
public Method resolveFunction(String prefix,String localName){
if (this.fnmap != null) {
return this.fnmap.get(prefix + ":" + localName);
}
return theMethod;
}
| Resolves the specified local name and prefix into a Java.lang.Method. Returns null if the prefix and local name are not found. |
public void testTrivial(){
check("select * from table;","select * from table;");
}
| Test simple cases. |
public void addHeaderView(View v){
addHeaderView(v,null,true);
}
| Add a fixed view to appear at the top of the grid. If addHeaderView is called more than once, the views will appear in the order they were added. Views added using this call can take focus if they want. <p> NOTE: Call this before calling setAdapter. This is so HeaderGridView can wrap the supplied cursor with one that will also account for header views. |
public boolean closeIt(){
log.info(toString());
m_processMsg=ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_BEFORE_CLOSE);
if (m_processMsg != null) return false;
setDocAction(DOCACTION_None);
m_processMsg=ModelValidationEngine.get().fireDocValidate(this,ModelValidator.TIMING_AFTER_CLOSE);
if (m_processMsg != null) return false;
return true;
}
| Close Document. Cancel not delivered Qunatities |
@Override public void readFile(final String filename){
String lcFilename=filename.toLowerCase(Locale.ROOT);
if (lcFilename.endsWith(".xml") || lcFilename.endsWith(".xml.gz")) {
new XmlEventsReader(this.events).readFile(filename);
}
else if (lcFilename.endsWith(".txt") || lcFilename.endsWith(".txt.gz")) {
throw new RuntimeException("text events are no longer supported. Please use MATSim 0.6.1 or earlier to read text events.");
}
else {
throw new IllegalArgumentException("Cannot recognize the format of the events-file " + filename);
}
}
| Parses the specified events file. |
public TextBuilder(int capacity){
this();
while (capacity > _capacity) {
increaseCapacity();
}
}
| Creates a text builder of specified initial capacity. Unless the text length exceeds the specified capacity, operations on this text builder will not allocate memory. |
@Override public boolean isActive(){
return amIActive;
}
| Used by the Whitebox GUI to tell if this plugin is still running. |
private void showFeedback(String feedback){
if (myHost != null) {
myHost.showFeedback(feedback);
}
else {
System.out.println(feedback);
}
}
| Used to communicate feedback pop-up messages between a plugin tool and the main Whitebox user-interface. |
public String toStringRfc3339(){
StringBuilder sb=new StringBuilder();
Calendar dateTime=new GregorianCalendar(GMT);
long localTime=value + (tzShift * 60000L);
dateTime.setTimeInMillis(localTime);
appendInt(sb,dateTime.get(Calendar.YEAR),4);
sb.append('-');
appendInt(sb,dateTime.get(Calendar.MONTH) + 1,2);
sb.append('-');
appendInt(sb,dateTime.get(Calendar.DAY_OF_MONTH),2);
if (!dateOnly) {
sb.append('T');
appendInt(sb,dateTime.get(Calendar.HOUR_OF_DAY),2);
sb.append(':');
appendInt(sb,dateTime.get(Calendar.MINUTE),2);
sb.append(':');
appendInt(sb,dateTime.get(Calendar.SECOND),2);
if (dateTime.isSet(Calendar.MILLISECOND)) {
sb.append('.');
appendInt(sb,dateTime.get(Calendar.MILLISECOND),3);
}
if (tzShift == 0) {
sb.append('Z');
}
else {
int absTzShift=tzShift;
if (tzShift > 0) {
sb.append('+');
}
else {
sb.append('-');
absTzShift=-absTzShift;
}
int tzHours=absTzShift / 60;
int tzMinutes=absTzShift % 60;
appendInt(sb,tzHours,2);
sb.append(':');
appendInt(sb,tzMinutes,2);
}
}
return sb.toString();
}
| Formats the value as an RFC 3339 date/time string. |
public void copyIntoResetFrontier(final int off,final IArraySlice<Value> slice){
backing.put(off,slice.array(),slice.off(),slice.len());
}
| Copy a slice into the backing array. This method is intended for use by parallel threads. The backing array MUST have sufficient capacity. The threads MUST write to offsets that are known to not overlap. NO checking is done to ensure that the concurrent copy of these slices will not overlap. |
@Override protected void onMessageOnProducerThread(T msg){
synchronized (_lock) {
if (_pending == null) {
_pending=new ArrayList<>();
_queue.schedule(_flushRunnable,_interval,_timeUnit);
}
_pending.add(msg);
}
}
| Receives message and batches as needed. |
public NodesInfoRequestBuilder clear(){
request.clear();
return this;
}
| Clears all info flags. |
protected void skipIdentifier() throws IOException {
loop: for (; ; ) {
current=reader.read();
switch (current) {
case 0xD:
case 0xA:
case 0x20:
case 0x9:
current=reader.read();
break loop;
default :
if (current == -1) {
break loop;
}
}
}
}
| Skips characters in the given reader until a white space is encountered. |
public boolean hasListener(String listenerName){
synchronized (lockObj) {
if (listener == null) return false;
else if (listener.getName().equalsIgnoreCase(listenerName)) return true;
else if (listener instanceof CompositeListener) return ((CompositeListener)listener).hasListener(listenerName);
else return false;
}
}
| Returns true if listener type exists (value/max/min/maxactive) or listener exists by name. |
public CloneableIterator<byte[]> keys(final boolean up,final boolean rotating) throws IOException {
if (this.index == null) {
log.severe("this.index == null in keys(); closeDate=" + this.closeDate + ", now="+ new Date()+ this.heapFile == null ? "" : (" file = " + this.heapFile.toString()));
return null;
}
synchronized (this.index) {
return new RotateIterator<byte[]>(this.index.keys(up,null),null,this.index.size());
}
}
| iterator over all keys |
final public MutableString append(final double d){
return append(String.valueOf(d));
}
| Appends a double to this mutable string. |
int chunkSize(){
return mChunkSize;
}
| Get the chunk size. Should only be used for testing. |
private void stopExecutors(IgniteLogger log){
boolean interrupted=Thread.interrupted();
try {
stopExecutors0(log);
}
finally {
if (interrupted) Thread.currentThread().interrupt();
}
}
| Stops executor services if they has been started. |
public static Map<String,String> simpleCommandLineParser(String[] args){
Map<String,String> map=new HashMap<String,String>();
for (int i=0; i <= args.length; i++) {
String key=(i > 0 ? args[i - 1] : null);
String value=(i < args.length ? args[i] : null);
if (key == null || key.startsWith("-")) {
if (value != null && value.startsWith("-")) value=null;
if (key != null || value != null) map.put(key,value);
}
}
return map;
}
| Simple method which turns an array of command line arguments into a map, where each token starting with a '-' is a key and the following non '-' initial token, if there is one, is the value. For example, '-size 5 -verbose' will produce keys (-size,5) and (-verbose,null). |
public boolean isSetDomainId(){
return EncodingUtils.testBit(__isset_bitfield,__DOMAINID_ISSET_ID);
}
| Returns true if field domainId is set (has been assigned a value) and false otherwise |
public void ret(final int local){
mv.visitVarInsn(Opcodes.RET,local);
}
| Generates a RET instruction. |
public BaseNode(final List<ConditionNode> children){
this.children=new ArrayList<>(children);
}
| Creates a new base node object with the given children. |
public String localize() throws OperationNotPermittedException, ObjectNotFoundException {
setLocalizeVisible(true);
menuBean.setCurrentPageLink(MenuBean.LINK_SERVICE_EDIT);
localization=null;
setServiceAttributesToLocalization();
return null;
}
| Get localization an set the values the details page. |
public WrappedByteBuffer putUnsignedInt(long value){
this.putInt((int)value & 0xFFFFFFFF);
return this;
}
| Puts a four-byte array into the buffer at the current position. |
public WETriangleMesh(String name,int numV,int numF){
super(name,numV,numF);
}
| Creates a new mesh instance with the given initial buffer sizes. These numbers are no limits and the mesh can be smaller or grow later on. They're only used to initialise the underlying collections. |
@Override public void visit(int version,int access,String name,String signature,String superName,String[] interfaces){
LOGGER.debug("Visiting class: " + name);
this.className=name;
LOGGER.debug("Class Major Version: " + version);
cw.visit(version,ACC_PUBLIC + ACC_SUPER,generateWithName,null,name,null);
LOGGER.debug("Super class: " + superName);
LOGGER.debug("Generating new Class with name:" + generateWithName);
super.visit(version,access,name,signature,superName,interfaces);
}
| Called when a class is visited. This is the method called first |
public boolean isDownloadingFinished(){
return status.get() != DownloadArtifactInfo.Status.DOWNLOADING;
}
| Indicates if downloading finished or didn't. |
public boolean isAPSupported(){
return Util.getImplementation().isAPSupported();
}
| Indicates whether looking up an access point is supported by this device |
public TestSource(String className,Modifier... modifiers){
this.packageName=null;
this.className=className;
this.modifiers=modifiers;
}
| Creates a package-less class to be used as an static inner class |
public String list(){
users=userManager.getUsers(new User());
return SUCCESS;
}
| Fetch all users from database and put into local "users" variable for retrieval in the UI. |
private void unregisterListener(String request){
delete(request).then().assertThat().statusCode(200);
}
| Unregisters a listener. |
public void testRetrievalHeap() throws Exception {
double fullBegin=System.currentTimeMillis();
double averageQueryTimeMs=0;
double averageTraversalTimeMs=0;
for (int i=0; i < NUM_TESTS; i++) {
long queryBegin=System.currentTimeMillis();
this.rs=this.stmt.executeQuery("SELECT * FROM retrievalPerfTestHeap");
long queryEnd=System.currentTimeMillis();
averageQueryTimeMs+=((double)(queryEnd - queryBegin) / NUM_TESTS);
long traverseBegin=System.currentTimeMillis();
while (this.rs.next()) {
this.rs.getInt(1);
this.rs.getString(2);
}
long traverseEnd=System.currentTimeMillis();
averageTraversalTimeMs+=((double)(traverseEnd - traverseBegin) / NUM_TESTS);
}
double fullEnd=System.currentTimeMillis();
double fullTime=(fullEnd - fullBegin) / 1000;
double queriesPerSec=NUM_TESTS / fullTime;
double rowsPerSec=(NUM_ROWS * NUM_TESTS) / fullTime;
System.out.println("\nHEAP Table Retrieval\n");
System.out.println("Full test took: " + fullTime + " seconds.");
System.out.println("Queries/second: " + queriesPerSec);
System.out.println("Rows/second: " + rowsPerSec);
System.out.println("Avg. Query Exec Time: " + averageQueryTimeMs + " ms");
System.out.println("Avg. Traversal Time: " + averageTraversalTimeMs + " ms");
assertTrue(fullTime < 45);
}
| Tests retrieval from HEAP tables |
private static long shallowSizeOfArray(Object array){
long size=NUM_BYTES_ARRAY_HEADER;
final int len=Array.getLength(array);
if (len > 0) {
Class<?> arrayElementClazz=array.getClass().getComponentType();
if (arrayElementClazz.isPrimitive()) {
size+=(long)len * primitiveSizes.get(arrayElementClazz);
}
else {
size+=(long)NUM_BYTES_OBJECT_REF * len;
}
}
return alignObjectSize(size);
}
| Return shallow size of any <code>array</code>. |
public static File fromDataURI(String dataURI,String fileName){
return File.createIfSupported(fromDataURI(dataURI),fileName);
}
| Create a new File from the dataURI string |
public void validate(FacesContext facesContext,UIComponent uiComponent,Object value) throws ValidatorException {
if (value == null) {
return;
}
BigDecimal valueBigDecimal=(BigDecimal)value;
BigDecimal maxValue=new BigDecimal("100.00");
BigDecimal minValue=new BigDecimal("0");
if (valueBigDecimal.scale() > MAXIMUM_FRACTION_DIGIT) {
FacesMessage facesMessage=JSFUtils.getFacesMessage(uiComponent,facesContext,BaseBean.ERROR_REVENUESHARE_INVALID_FRACTIONAL_PART);
throw new ValidatorException(facesMessage);
}
if (valueBigDecimal.compareTo(maxValue) == 1) {
FacesMessage facesMessage=JSFUtils.getFacesMessage(uiComponent,facesContext,BaseBean.ERROR_REVENUESHARE_VALUE);
throw new ValidatorException(facesMessage);
}
if (valueBigDecimal.compareTo(minValue) == -1) {
FacesMessage facesMessage=JSFUtils.getFacesMessage(uiComponent,facesContext,BaseBean.ERROR_REVENUESHARE_VALUE);
throw new ValidatorException(facesMessage);
}
}
| Validate revenue share value. |
public void addContact(Contact contact){
addProperty(contact);
}
| Adds a contact to the to-do task. |
@Experimental public void registerHook(String event,String cmd){
String className=interpreterContext.getClassName();
registerHook(event,cmd,className);
}
| registerHook() wrapper for current repl |
public static void disableScreenshotFunctionality(Activity activity){
activity.getWindow().setFlags(LayoutParams.FLAG_SECURE,LayoutParams.FLAG_SECURE);
}
| Disable screenshot functionality. |
private String postExperimentInfo(){
StringBuffer text=new StringBuffer();
text.append(m_finishedCount + (m_splitByDataSet ? " data sets" : " runs") + " completed successfully. "+ m_failedCount+ " failures during running.\n");
System.err.print(text.toString());
return text.toString();
}
| Returns some post experiment information. |
private boolean isValidStatus(String statusStr){
boolean valid=false;
Status[] validStatus=Status.values();
for ( Status status : validStatus) {
if (status.name().toUpperCase().equals(statusStr.toUpperCase())) {
valid=true;
break;
}
}
return valid;
}
| Checks to see whether the provided status is one of the defined valid status(es). |
public void popIn(View v,long delay){
if (v.getVisibility() != View.VISIBLE) {
v.setVisibility(View.VISIBLE);
ScaleAnimation anim=new ScaleAnimation(0f,1f,0f,1f);
anim.setDuration(750);
anim.setStartOffset(delay);
anim.setInterpolator(new BounceInterpolator());
v.startAnimation(anim);
}
}
| Some quick little reusable animation functions |
@PrePersist protected void prePersist(){
this.orderState=OrderState.CREATED;
}
| Before the entity is persisted: <ul> <li>the orderState is set</li> </ul> |
public TenantConfigurationValueBuilder<T> createdAt(final Long createdAt){
this.configuration.createdAt=createdAt;
return this;
}
| sets the created at attribute |
public int lastIndexOfAny(CharSet charSet){
return lastIndexOfAny(charSet,0,length());
}
| Returns the index within this text of the last occurrence of any character in the specified character set. |
public void showDrawerButton(){
if (getActivity() instanceof AppCompatActivity) {
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(false);
}
mActionBarDrawerToggle.syncState();
}
| Changes the icon of the drawer to menu |
public static boolean isNil(final LuaValue target){
return target != null && target.type() == LuaValue.TNIL;
}
| is nil |
public MatPalette overridePalette(MatPalette palette){
return palette;
}
| Override this method to set the palette colors programmatically. |
public static synchronized void describe(String description,SafeBlock block){
isValidContext("describe");
ExampleGroupConfiguration config=new ExampleGroupConfiguration.Builder().description(description).executionFlag(DEFAULT).build();
contexts.get().current().addGroup(config,block);
}
| Defines a new example group. |
public static String createVltFilePath(Shell shell,String text,int style,String defaultFileName){
return createFilePath(shell,text,PreferenceConstants.DEFAULT_FOLDER_VLT,vltExtensions,style,defaultFileName);
}
| creating a filepath for vlt files |
public boolean isCommentOnly(){
return commentOnly;
}
| Returns true to indicate comments-only expression. |
public void print(String sTab){
for (int iValue=0; iValue < m_ADNodes.length; iValue++) {
System.out.print(sTab + iValue + ": ");
if (m_ADNodes[iValue] == null) {
if (iValue == m_nMCV) {
System.out.println("MCV");
}
else {
System.out.println("null");
}
}
else {
System.out.println();
m_ADNodes[iValue].print();
}
}
}
| print is used for debugging only, called from ADNode |
@Override public boolean isActive(){
return amIActive;
}
| Used by the Whitebox GUI to tell if this plugin is still running. |
private void selectWord(MouseEvent e){
if (selectedWordEvent != null && selectedWordEvent.getX() == e.getX() && selectedWordEvent.getY() == e.getY()) {
return;
}
Action a=null;
RTextArea textArea=getTextArea();
ActionMap map=textArea.getActionMap();
if (map != null) {
a=map.get(RTextAreaEditorKit.selectWordAction);
}
if (a == null) {
if (selectWord == null) {
selectWord=new RTextAreaEditorKit.SelectWordAction();
}
a=selectWord;
}
a.actionPerformed(new ActionEvent(textArea,ActionEvent.ACTION_PERFORMED,null,e.getWhen(),e.getModifiers()));
selectedWordEvent=e;
}
| Selects word based on the MouseEvent |
String formatNumberList(TransformerImpl transformer,long[] list,int contextNode) throws TransformerException {
String numStr;
FastStringBuffer formattedNumber=StringBufferPool.get();
try {
int nNumbers=list.length, numberWidth=1;
char numberType='1';
String formatToken, lastSepString=null, formatTokenString=null;
String lastSep=".";
boolean isFirstToken=true;
String formatValue=(null != m_format_avt) ? m_format_avt.evaluate(transformer.getXPathContext(),contextNode,this) : null;
if (null == formatValue) formatValue="1";
NumberFormatStringTokenizer formatTokenizer=new NumberFormatStringTokenizer(formatValue);
for (int i=0; i < nNumbers; i++) {
if (formatTokenizer.hasMoreTokens()) {
formatToken=formatTokenizer.nextToken();
if (Character.isLetterOrDigit(formatToken.charAt(formatToken.length() - 1))) {
numberWidth=formatToken.length();
numberType=formatToken.charAt(numberWidth - 1);
}
else if (formatTokenizer.isLetterOrDigitAhead()) {
formatTokenString=formatToken;
while (formatTokenizer.nextIsSep()) {
formatToken=formatTokenizer.nextToken();
formatTokenString+=formatToken;
}
if (!isFirstToken) lastSep=formatTokenString;
formatToken=formatTokenizer.nextToken();
numberWidth=formatToken.length();
numberType=formatToken.charAt(numberWidth - 1);
}
else {
lastSepString=formatToken;
while (formatTokenizer.hasMoreTokens()) {
formatToken=formatTokenizer.nextToken();
lastSepString+=formatToken;
}
}
}
if (null != formatTokenString && isFirstToken) {
formattedNumber.append(formatTokenString);
}
else if (null != lastSep && !isFirstToken) formattedNumber.append(lastSep);
getFormattedNumber(transformer,contextNode,numberType,numberWidth,list[i],formattedNumber);
isFirstToken=false;
}
while (formatTokenizer.isLetterOrDigitAhead()) {
formatTokenizer.nextToken();
}
if (lastSepString != null) formattedNumber.append(lastSepString);
while (formatTokenizer.hasMoreTokens()) {
formatToken=formatTokenizer.nextToken();
formattedNumber.append(formatToken);
}
numStr=formattedNumber.toString();
}
finally {
StringBufferPool.free(formattedNumber);
}
return numStr;
}
| Format a vector of numbers into a formatted string. |
protected void clearEvents(){
sCInterface.clearEvents();
for (int i=0; i < timeEvents.length; i++) {
timeEvents[i]=false;
}
}
| This method resets the incoming events (time events included). |
public void startMachine(MachineConfig machineConfig,String workspaceId) throws ServerException, ConflictException, BadRequestException, NotFoundException {
final WorkspaceImpl workspace=getWorkspace(workspaceId);
if (RUNNING != workspace.getStatus()) {
throw new ConflictException(format("Workspace '%s' is not running, new machine can't be started",workspaceId));
}
performAsyncStart(machineConfig,workspaceId);
}
| Starts machine in running workspace |
public void testBogusArguments() throws Exception {
IllegalArgumentException expected=expectThrows(IllegalArgumentException.class,null);
assertTrue(expected.getMessage().contains("Unknown parameters"));
}
| Test that bogus arguments result in exception |
private static int determineConsecutiveTextCount(CharSequence msg,int startpos){
int len=msg.length();
int idx=startpos;
while (idx < len) {
char ch=msg.charAt(idx);
int numericCount=0;
while (numericCount < 13 && isDigit(ch) && idx < len) {
numericCount++;
idx++;
if (idx < len) {
ch=msg.charAt(idx);
}
}
if (numericCount >= 13) {
return idx - startpos - numericCount;
}
if (numericCount > 0) {
continue;
}
ch=msg.charAt(idx);
if (!isText(ch)) {
break;
}
idx++;
}
return idx - startpos;
}
| Determines the number of consecutive characters that are encodable using text compaction. |
private <T>T[] copyElements(T[] a){
if (head < tail) {
System.arraycopy(elements,head,a,0,size());
}
else if (head > tail) {
int headPortionLen=elements.length - head;
System.arraycopy(elements,head,a,0,headPortionLen);
System.arraycopy(elements,0,a,headPortionLen,tail);
}
return a;
}
| Copies the elements from our element array into the specified array, in order (from first to last element in the deque). It is assumed that the array is large enough to hold all elements in the deque. |
public Object opt(int index){
return (index < 0 || index >= length()) ? null : get(index);
}
| Get the optional object value associated with an index. |
public boolean isInStandbyMode(){
return isInStandbyMode;
}
| Reports whether the <code>Scheduler</code> is in standby mode. |
private void initScrollbar(){
m_scrollbar.addAdjustmentListener(m_listener);
add(m_scrollbar,BorderLayout.EAST);
m_horizontalScrollbar.addAdjustmentListener(m_listener);
add(m_horizontalScrollbar,BorderLayout.SOUTH);
}
| Creates and initializes the scroll bar that is used to scroll through the data. |
public static void putLong(long val,byte[] buf,int off){
assert off + 4 <= buf.length;
buf[off]=long0(val);
buf[off + 1]=long1(val);
buf[off + 2]=long2(val);
buf[off + 3]=long3(val);
buf[off + 4]=long4(val);
buf[off + 5]=long5(val);
buf[off + 6]=long6(val);
buf[off + 7]=long7(val);
}
| Inserts the long value into the array at the requested offset. |
@Parameterized.Parameters public static Collection<Object[]> configs(){
return Arrays.asList(new Object[][]{{"inner","on","v2",true},{"left","on","v1",true},{"left","on","v2",true}});
}
| return all config combinations, where first setting specifies join type (inner or left), and the second setting specifies whether to force using coprocessors(on, off or unset). |
public void process(DistributionManager dm){
Assert.assertTrue(this.date != null);
System.out.println(format.format(this.date));
}
| Just prints out the date |
public boolean isNotIn(){
return isNotIn;
}
| Returns true for not-in, or false for in. |
public static boolean toBooleanValue(int i){
return i != 0;
}
| cast a int value to a boolean value (primitive value type) |
public String save() throws IOException {
Boolean encrypt=(Boolean)getConfiguration().get(Constants.ENCRYPT_PASSWORD);
if ("true".equals(getRequest().getParameter("encryptPass")) && (encrypt != null && encrypt)) {
String algorithm=(String)getConfiguration().get(Constants.ENC_ALGORITHM);
if (algorithm == null) {
log.debug("assuming testcase, setting algorithm to 'SHA'");
algorithm="SHA";
}
user.setPassword(StringUtil.encodePassword(user.getPassword(),algorithm));
}
Integer originalVersion=user.getVersion();
boolean isNew=("".equals(getRequest().getParameter("user.version")));
if (getRequest().isUserInRole(Constants.ADMIN_ROLE)) {
user.getRoles().clear();
String[] userRoles=getRequest().getParameterValues("userRoles");
for (int i=0; userRoles != null && i < userRoles.length; i++) {
String roleName=userRoles[i];
user.addRole(roleManager.getRole(roleName));
}
}
try {
user=userManager.saveUser(user);
}
catch ( AccessDeniedException ade) {
log.warn(ade.getMessage());
getResponse().sendError(HttpServletResponse.SC_FORBIDDEN);
return null;
}
catch ( UserExistsException e) {
List<String> args=new ArrayList<String>();
args.add(user.getUsername());
args.add(user.getEmail());
addActionError(getText("errors.existing.user",args.toArray(new String[]{})));
user.setVersion(originalVersion);
user.setPassword(user.getConfirmPassword());
return INPUT;
}
if (!"list".equals(from)) {
saveMessage(getText("user.saved"));
return "mainMenu";
}
else {
List<String> args=new ArrayList<String>();
args.add(user.getFullName());
if (isNew) {
saveMessage(getText("user.added",args.toArray(new String[]{})));
mailMessage.setSubject(getText("signup.email.subject"));
sendUserMessage(user,getText("newuser.email.message",args.toArray(new String[]{})),RequestUtil.getAppURL(getRequest()));
return SUCCESS;
}
else {
saveMessage(getText("user.updated.byAdmin",args.toArray(new String[]{})));
return INPUT;
}
}
}
| Save user |
public Vector4f normalize3(){
float invLength=(float)(1.0 / Math.sqrt(x * x + y * y + z * z));
x*=invLength;
y*=invLength;
z*=invLength;
w*=invLength;
return this;
}
| Normalize this vector by computing only the norm of <tt>(x, y, z)</tt>. |
long readLong() throws IOException {
return (((long)_is.read() << 56) | ((long)_is.read() << 48) | ((long)_is.read() << 40)| ((long)_is.read() << 32)| ((long)_is.read() << 24)| ((long)_is.read() << 16)| ((long)_is.read() << 8)| ((long)_is.read()));
}
| Parses a 64-bit int. |
public void zoomOut(){
if (mZoomOut != null) {
mZoomOut.apply(Zoom.ZOOM_AXIS_XY);
repaint();
}
}
| Do a chart zoom out. |
public Viennet2(){
super(2,3);
}
| Constructs the Viennet (2) problem. |
public static void startGooglePlay(Context context){
final String appPackageName=context.getPackageName();
try {
context.startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("market://details?id=" + appPackageName)));
}
catch ( android.content.ActivityNotFoundException anfe) {
context.startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse("http://play.google.com/store/apps/details?id=" + appPackageName)));
}
}
| Starts Google Play application for this application. |
protected void validateStartState(State currentState){
ValidationUtils.validateState(currentState);
ValidationUtils.validateTaskStage(currentState.taskState);
}
| This method validates a state object for internal consistency. |
public void swapComponents(){
JComponent tmp=myFirstComponent;
myFirstComponent=mySecondComponent;
mySecondComponent=tmp;
revalidate();
repaint();
}
| Swaps components. |
public double originalValue(double value) throws Exception {
if (m_Converter == null) {
throw new IllegalStateException("Coverter table not defined yet!");
}
for (int i=0; i < m_Converter.length; i++) {
if ((int)value == m_Converter[i]) {
return i;
}
}
return -1;
}
| Return the original internal class value given the randomized class value, i.e. the string presentations of the two indices are the same. It's useful when the filter is used within a classifier so that the filtering procedure should be transparent to the evaluation |
void loadFieldIds() throws IOException {
int count=mHeaderItem.fieldIdsSize;
mFieldIds=new FieldIdItem[count];
seek(mHeaderItem.fieldIdsOff);
for (int i=0; i < count; i++) {
mFieldIds[i]=new FieldIdItem();
mFieldIds[i].classIdx=readShort() & 0xffff;
mFieldIds[i].typeIdx=readShort() & 0xffff;
mFieldIds[i].nameIdx=readInt();
}
}
| Loads the field ID list. |
private boolean validateCorsOrigin(final HttpRequest request){
if (config.isAnyOriginSupported()) {
return true;
}
final String origin=request.headers().get(HttpHeaderNames.ORIGIN);
return origin == null || NULL_ORIGIN.equals(origin) && config.isNullOriginAllowed() || config.origins().contains(origin.toLowerCase(Locale.ENGLISH));
}
| Validates if origin matches the CORS requirements. |
private void updateProgress(int progress){
if (myHost != null && progress != previousProgress) {
myHost.updateProgress(progress);
}
previousProgress=progress;
}
| Used to communicate a progress update between a plugin tool and the main Whitebox user interface. |
private void updateSnapshotSessionLinkedTargets(BlockSnapshot snapshot,DbClient dbClient){
List<BlockSnapshot> snapshots=ControllerUtils.getSnapshotsPartOfReplicationGroup(snapshot,dbClient);
if (snapshots == null || snapshots.isEmpty()) {
return;
}
for ( BlockSnapshot existing : snapshots) {
List<BlockSnapshotSession> sessions=CustomQueryUtility.queryActiveResourcesByConstraint(dbClient,BlockSnapshotSession.class,ContainmentConstraint.Factory.getLinkedTargetSnapshotSessionConstraint(existing.getId()));
if (!sessions.isEmpty()) {
BlockSnapshotSession session=sessions.get(0);
session.getLinkedTargets().add(snapshot.getId().toString());
dbClient.updateObject(session);
break;
}
}
}
| If the snapshot is found to be part of a ReplicationGroup containing linked targets to an existing BlockSnapshotSession, we must update it with the ID of this snapshot. |
public static BufferedImage toCompatibleImage(BufferedImage image){
if (image.getColorModel().equals(getGraphicsConfiguration().getColorModel())) {
return image;
}
BufferedImage compatibleImage=getGraphicsConfiguration().createCompatibleImage(image.getWidth(),image.getHeight(),image.getTransparency());
Graphics g=compatibleImage.getGraphics();
g.drawImage(image,0,0,null);
g.dispose();
return compatibleImage;
}
| <p>Return a new compatible image that contains a copy of the specified image. This method ensures an image is compatible with the hardware, and therefore optimized for fast blitting operations.</p> |
public void done(){
if (isDone) throw new IllegalStateException("Can't call done() twice");
if (points.size() == 0) throw new IllegalArgumentException("Path must have at least one point");
isDone=true;
endPoints=new ArrayList<>(points.size());
segments=new ArrayList<>(points.size());
final double cutoffOffset=this.sinAngle * planetModel.getMinimumMagnitude();
GeoPoint lastPoint=null;
for ( final GeoPoint end : points) {
if (lastPoint != null) {
final Plane normalizedConnectingPlane=new Plane(lastPoint,end);
if (normalizedConnectingPlane == null) {
continue;
}
segments.add(new PathSegment(planetModel,lastPoint,end,normalizedConnectingPlane,cutoffOffset));
}
lastPoint=end;
}
if (segments.size() == 0) {
double lat=points.get(0).getLatitude();
double lon=points.get(0).getLongitude();
double upperLat=lat + cutoffAngle;
double upperLon=lon;
if (upperLat > Math.PI * 0.5) {
upperLon+=Math.PI;
if (upperLon > Math.PI) upperLon-=2.0 * Math.PI;
upperLat=Math.PI - upperLat;
}
double lowerLat=lat - cutoffAngle;
double lowerLon=lon;
if (lowerLat < -Math.PI * 0.5) {
lowerLon+=Math.PI;
if (lowerLon > Math.PI) lowerLon-=2.0 * Math.PI;
lowerLat=-Math.PI - lowerLat;
}
final GeoPoint upperPoint=new GeoPoint(planetModel,upperLat,upperLon);
final GeoPoint lowerPoint=new GeoPoint(planetModel,lowerLat,lowerLon);
final GeoPoint point=points.get(0);
final Plane normalPlane=Plane.constructNormalizedZPlane(upperPoint,lowerPoint,point);
final SegmentEndpoint onlyEndpoint=new SegmentEndpoint(point,normalPlane,upperPoint,lowerPoint);
endPoints.add(onlyEndpoint);
this.edgePoints=new GeoPoint[]{onlyEndpoint.circlePlane.getSampleIntersectionPoint(planetModel,normalPlane)};
return;
}
for (int i=0; i < segments.size(); i++) {
final PathSegment currentSegment=segments.get(i);
if (i == 0) {
final SegmentEndpoint startEndpoint=new SegmentEndpoint(currentSegment.start,currentSegment.startCutoffPlane,currentSegment.ULHC,currentSegment.LLHC);
endPoints.add(startEndpoint);
this.edgePoints=new GeoPoint[]{currentSegment.ULHC};
continue;
}
final PathSegment prevSegment=segments.get(i - 1);
final SidedPlane candidate1=SidedPlane.constructNormalizedThreePointSidedPlane(currentSegment.start,prevSegment.URHC,currentSegment.ULHC,currentSegment.LLHC);
final SidedPlane candidate2=SidedPlane.constructNormalizedThreePointSidedPlane(currentSegment.start,currentSegment.ULHC,currentSegment.LLHC,prevSegment.LRHC);
final SidedPlane candidate3=SidedPlane.constructNormalizedThreePointSidedPlane(currentSegment.start,currentSegment.LLHC,prevSegment.LRHC,prevSegment.URHC);
final SidedPlane candidate4=SidedPlane.constructNormalizedThreePointSidedPlane(currentSegment.start,prevSegment.LRHC,prevSegment.URHC,currentSegment.ULHC);
if (candidate1 == null && candidate2 == null && candidate3 == null && candidate4 == null) {
final SegmentEndpoint midEndpoint=new SegmentEndpoint(currentSegment.start,prevSegment.endCutoffPlane,currentSegment.startCutoffPlane,currentSegment.ULHC,currentSegment.LLHC);
endPoints.add(midEndpoint);
}
else {
endPoints.add(new SegmentEndpoint(currentSegment.start,prevSegment.endCutoffPlane,currentSegment.startCutoffPlane,prevSegment.URHC,prevSegment.LRHC,currentSegment.ULHC,currentSegment.LLHC,candidate1,candidate2,candidate3,candidate4));
}
}
final PathSegment lastSegment=segments.get(segments.size() - 1);
endPoints.add(new SegmentEndpoint(lastSegment.end,lastSegment.endCutoffPlane,lastSegment.URHC,lastSegment.LRHC));
}
| Complete the path. |
public boolean addressTypeUnique(){
return false;
}
| Are there any ambiguous addresses (short vs long) on this system? |
public void drawHeader(RecyclerView recyclerView,Canvas canvas,View header,Rect offset){
canvas.save();
if (recyclerView.getLayoutManager().getClipToPadding()) {
Rect clipRect=getClipRectForHeader(recyclerView,header);
canvas.clipRect(clipRect);
}
canvas.translate(offset.left,offset.top);
header.draw(canvas);
canvas.restore();
}
| Draws a header to a canvas, offsetting by some x and y amount |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.