code
stringlengths
10
174k
nl
stringlengths
3
129k
public CropImageOptions(){ DisplayMetrics dm=Resources.getSystem().getDisplayMetrics(); cropShape=CropImageView.CropShape.RECTANGLE; snapRadius=TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,3,dm); touchRadius=TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,24,dm); guidelines=CropImageView.Guidelines.ON_TOUCH; scaleType=CropImageView.ScaleType.FIT_CENTER; showCropOverlay=true; showProgressBar=true; autoZoomEnabled=true; multiTouchEnabled=false; maxZoom=4; initialCropWindowPaddingRatio=0.1f; fixAspectRatio=false; aspectRatioX=1; aspectRatioY=1; borderLineThickness=TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,3,dm); borderLineColor=Color.argb(170,255,255,255); borderCornerThickness=TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,2,dm); borderCornerOffset=TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,5,dm); borderCornerLength=TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,14,dm); borderCornerColor=Color.WHITE; guidelinesThickness=TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,1,dm); guidelinesColor=Color.argb(170,255,255,255); backgroundColor=Color.argb(119,0,0,0); minCropWindowWidth=(int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,42,dm); minCropWindowHeight=(int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,42,dm); minCropResultWidth=40; minCropResultHeight=40; maxCropResultWidth=99999; maxCropResultHeight=99999; activityTitle=""; activityMenuIconColor=0; outputUri=Uri.EMPTY; outputCompressFormat=Bitmap.CompressFormat.JPEG; outputCompressQuality=90; outputRequestWidth=0; outputRequestHeight=0; outputRequestSizeOptions=CropImageView.RequestSizeOptions.NONE; noOutputImage=false; initialCropWindowRectangle=null; initialRotation=-1; allowRotation=true; allowCounterRotation=false; rotationDegrees=90; }
Init options with defaults.
public final ByteBuffer putChar(char value){ return putShort((short)value); }
Writes the given char to the current position and increases the position by 2. <p> The char is converted to bytes using the current byte order. </p>
public TaskResults<T> executeParallelFailFast(){ Preconditions.checkArgument(!CollectionUtil.isCollectionEmpty(tasks),"No task found for execution"); Set<TaskResult<T>> results=executeParallel(tasks,true); tasks.clear(); return new TaskResults<>(results); }
Executes tasks in parallel. Fails fast if any execution failed Returns results of tasks completed so far
private String[] parseStringArrayFromList(String value) throws TokenException { if (value == null) { throw new TokenException("List of strings cannot be null"); } StringTokenizer st=new StringTokenizer(value,","); String[] tokens=new String[st.countTokens()]; int i=0; while (st.hasMoreTokens()) { tokens[i++]=st.nextToken().trim(); } return tokens; }
Create an array of sub-strings from a given comma-separated string. The contents of each string in the returned array will be trimmed of leading and trailing spaces.
protected InferenceVariableImpl(){ super(); }
<!-- begin-user-doc --> <!-- end-user-doc -->
void error(String key) throws SAXException { hadError=true; if (eh == null) return; eh.error(new SAXParseException(localizer.message(key),locator)); }
Report a no arguments error from a key.
@NonNull public Item newItemFromCursor(@NonNull Cursor cursor){ return Item_Schema.INSTANCE.newModelFromCursor(connection,cursor,0); }
Retrieves a model from a cursor.
public boolean isDirty(){ for (int i=0, size=PANE_ITEMS_LIST.size(); i < size; i++) { PaneItem currentItem=PANE_ITEMS_LIST.get(i); if (currentItem.isDirty()) return true; } return false; }
Determines if any of the panes stored within this OptionPane require saving.
protected void selectValue(int value){ if (value > 256) { log.error("Saw unreasonable internal value: " + value); } for (int i=0; i < _valueArray.length; i++) { if (_valueArray[i] == value) { _value.setSelectedIndex(i); return; } } log.debug("Create new item with value " + value + " count was "+ _value.getItemCount()+ " in "+ label()); _value.addItem("Reserved value " + value); int[] oldArray=_valueArray; _valueArray=new int[oldArray.length + 1]; for (int i=0; i < oldArray.length; i++) { _valueArray[i]=oldArray[i]; } _valueArray[oldArray.length]=value; _value.setSelectedItem("Reserved value " + value); }
Set to a specific value. This searches for the displayed value, and sets the enum to that particular one. If the value is larger than any defined, a new one is created.
public boolean isRotationNeeded(final String data,final File file){ m_usedRotation=-1; if (null != m_strategies) { final int length=m_strategies.length; for (int i=0; i < length; i++) { if (true == m_strategies[i].isRotationNeeded(data,file)) { m_usedRotation=i; return true; } } } return false; }
check if now a log rotation is neccessary. This object is initialised with several rotation strategy objects. The <code>isRotationNeeded</code> method checks the first rotation strategy object. If a rotation is needed, this result is returned. If not the next rotation strategy object is asked and so on.
public void testEncrytion() throws Exception { String testString="secret"; String someRandomString="and now, for something completly different"; String encryptedString=encryptor.encrypt(testString); String decryptedString=encryptor.decrypt(encryptedString); assertEquals(testString,decryptedString); assertFalse(testString.equals(someRandomString)); }
Tests encryption / decryption
private static File[] findConfigurationFilesKo(){ final String testSrc=System.getProperty("test.src"); final File dir=new File(testSrc); final FilenameFilter filter=new ConfigFilenameFilter("management_test","ko.properties"); return dir.listFiles(filter); }
Get all "management*ko.properties" files in the directory indicated by the "test.src" management property.
public AABB(){ lowerBound=new Vec2(); upperBound=new Vec2(); }
Creates the default object, with vertices at 0,0 and 0,0.
public static DBHandler acquireDB() throws GBException { try { if (dbLock.tryLock(30,TimeUnit.SECONDS)) { return lockHandler; } } catch ( InterruptedException ex) { Log.i(TAG,"Interrupted while waiting for DB lock"); } throw new GBException("Unable to access the database."); }
Returns the DBHandler instance for reading/writing or throws GBException when that was not successful If acquiring was successful, callers must call #releaseDB when they are done (from the same thread that acquired the lock! Callers must not hold a reference to the returned instance because it will be invalidated at some point.
private int upgradeQualityForEncryption(int quality){ int encryptionStatus=mDPM.getStorageEncryptionStatus(); boolean encrypted=(encryptionStatus == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVE) || (encryptionStatus == DevicePolicyManager.ENCRYPTION_STATUS_ACTIVATING); if (encrypted) { if (quality < CryptKeeperSettings.MIN_PASSWORD_QUALITY) { quality=CryptKeeperSettings.MIN_PASSWORD_QUALITY; } } return quality; }
Mix in "encryption minimums" to any given quality value. This prevents users from downgrading the pattern/pin/password to a level below the minimums. ASSUMPTION: Setting quality is sufficient (e.g. minimum lengths will be set appropriately.)
@RequestMapping({"/create-link","/create-speak"}) public ModelAndView createArticle(@RequestParam(value="c",required=false) String content,@RequestParam(value="t",required=false) String title){ return new CreateArticleModelAndView(zoneService,null).preFilled(content,title); }
request parameter are used for bookmarklet pre-filled, so name is short.
final boolean unlink(Index<K,V> succ){ return !indexesDeletedNode() && casRight(succ,succ.right); }
Tries to CAS right field to skip over apparent successor succ. Fails (forcing a retraversal by caller) if this node is known to be deleted.
public EjbCapabilityContainerTest(String testName,EnvironmentTestData testData) throws Exception { super(testName,testData); }
Initializes the test case.
public VCardFloatFormatter(int decimals){ setMaximumFractionDigits(decimals); if (decimals > 0) { setMinimumFractionDigits(1); } DecimalFormatSymbols symbols=new DecimalFormatSymbols(); symbols.setDecimalSeparator('.'); symbols.setMinusSign('-'); setDecimalFormatSymbols(symbols); }
Creates a new formatter.
static XMLName formProperty(String uri,String localName){ return formProperty(XmlNode.Namespace.create(uri),localName); }
TODO: marked deprecated by original author
private Planet claimPlanet(EntityPlayer player){ UUID playerUUID=EntityPlayer.getUUID(player.getGameProfile()); int quadrantID=random.nextInt(theGalaxy.getQuadrants().size()); for ( Quadrant quadrant : theGalaxy.getQuadrants()) { if (quadrant.getId() == quadrantID) { for ( Star star : quadrant.getStars()) { if (star.getPlanets().size() > 0) { boolean isClaimed=false; for ( Planet planet : star.getPlanets()) { if (planet.hasOwner() && !planet.getOwnerUUID().equals(playerUUID)) { isClaimed=true; break; } } if (!isClaimed) { int planetID=random.nextInt(star.getPlanets().size()); Planet planet=(Planet)star.getPlanets().toArray()[planetID]; buildHomeworld(planet,player); return planet; } } } } } return null; }
Claims a planet as the given players homeworld
boolean excluded(int elemIndex){ return (exclusions != null) && exclusions.get(elem.getIndex()); }
Return true if the element that is contained at the index specified by the parameter is part of the exclusions specified in the DTD for the element currently on the TagStack.
public final boolean flagPhoto(final long photoId) throws AbelanaClientException, AbelanaClientException { if (isConnectedToServerOrTryToConnect()) { FlagRequest flagRequest=new FlagRequest(); flagRequest.photoId=photoId; try { StatusResponse statusResponse=mBlockingStub.flagPhoto(flagRequest); if (statusResponse.error != null && statusResponse.error.code.equals("403")) { throw new AbelanaClientException(mContext.getString(R.string.abelana_auth_error_message)); } return statusResponse.error == null; } catch ( RuntimeException e) { Log.e("AbelanaClient",e.getMessage()); throw new AbelanaClientException(mContext.getString(R.string.server_connection_error)); } } else { throw new AbelanaClientException(mContext.getString(R.string.server_connection_error)); } }
Flags a photo as inappropriate.
public static double[][] increment(int m,int n,double[] begin,double[] pitch){ if (begin.length != n || pitch.length != n) throw new IllegalArgumentException("Length of 3rd and 4th arguments must = second argument"); double[][] array=new double[m][n]; for (int i=0; i < m; i++) { for (int j=0; j < n; j++) { array[i][j]=begin[j] + i * pitch[j]; } } return array; }
Generates an mxn matrix. Each column is a sequence of succesive values. Each column has it's own starting value and step size.
public V first(K key){ key=sanitizeKey(key); List<V> values=map.get(key); return (values == null) ? null : values.get(0); }
Gets the first value that's associated with a key.
public double untransform(double value){ return value; }
Untransform a value
public void drawingComplete(OMGraphic omg,OMAction action){ if (timerButton.isSelected()) { timer.restart(); } if (omg instanceof OMPoint) { OMPoint p=(OMPoint)omg; GLPoint mp=new GLPoint(p.getLat(),p.getLon(),p.getRadius(),true); mp.setName("Added Node " + (pointCount++)); mp.setStationary(true); mp.showPalette(); points.put(mp.getName(),mp); manageGraphics(); } else if (omg instanceof OMPoly) { OMPoly poly=(OMPoly)omg; PathGLPoint pmp=new PathGLPoint(poly,5,true); pmp.setName("Added Node " + (pointCount++)); pmp.showPalette(); points.put(pmp.getName(),pmp); manageGraphics(); } addNodeButton.setEnabled(true); addPathButton.setEnabled(true); }
The method where a graphic, and an action to take on the graphic, arrives.
public static float smoothstep(float t){ return t * t * (3.0f - 2.0f * t); }
Smooth a value between 0 and 1.
public float filter(float in){ final float yn=a0 * (b0 * in + b1 * in1 + b2 * in2 - a1 * out1 - a2 * out2); in2=in1; in1=in; out2=out1; out1=yn; return yn; }
Applies filter to a single sample value.
public HeatmapFacetCounter.Heatmap calcFacets(IndexReaderContext context,Bits topAcceptDocs,Shape inputShape,final int facetLevel,int maxCells) throws IOException { return HeatmapFacetCounter.calcFacets(this,context,topAcceptDocs,inputShape,facetLevel,maxCells); }
Computes spatial facets in two dimensions as a grid of numbers. The data is often visualized as a so-called "heatmap".
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.
@Override protected void paintComponent(final Graphics g){ super.paintComponent(g); if (hasFocus()) { g.setColor(JBColor.black); DarculaUIUtil.paintFocusRing(g,0,0,getWidth(),getHeight()); } }
We are overriding this method to paint a focus rectangle around the control.
public void valueChanged(TreeSelectionEvent e){ firePropertyChange(AccessibleContext.ACCESSIBLE_SELECTION_PROPERTY,Boolean.valueOf(false),Boolean.valueOf(true)); }
Tree Selection Listener value change method. Used to fire the property change
public boolean isHeaderPartition(){ return (this.partitionPackType == PartitionPackType.HeaderPartitionPack); }
Checks if this is a header partition.
public InputStream newInputStream(int index) throws IOException { synchronized (DiskLruCache.this) { if (entry.currentEditor != this) { throw new IllegalStateException(); } if (!entry.readable) { return null; } try { return new FileInputStream(entry.getCleanFile(index)); } catch ( FileNotFoundException e) { return null; } } }
Returns an unbuffered input stream to read the last committed value, or null if no value has been committed.
public LongArrayList(){ this(10); }
Constructs an empty list.
public DateTimeFormatterBuilder append(DateTimeParser parser){ checkParser(parser); return append0(null,parser); }
Appends just a parser. With no matching printer, a printer cannot be built from this builder.
protected void determineActiveAttributes(){ if (this.isHighlighted()) { if (this.getHighlightAttributes() != null) this.activeAttributes.copy(this.getHighlightAttributes()); else { if (this.getAttributes() != null) this.activeAttributes.copy(this.getAttributes()); else this.activeAttributes.copy(defaultAttributes); } } else if (this.getAttributes() != null) { this.activeAttributes.copy(this.getAttributes()); } else { this.activeAttributes.copy(defaultAttributes); } this.determineScrollbarAttributes(); }
Determines which attributes -- normal, highlight or default -- to use each frame.
public <T extends BinarySearchTreeSearchCriteria<E>>T search(T criteria){ if (this.root == null) return criteria; BinarySearchTreeNode<E> node=this.root; while (node != null) { int result=criteria.evaluate(node.comparable); if (result < 0) { node=node.left; } else if (result > 0) { node=node.right; } else { break; } } return criteria; }
Performs a binary search on this tree given the criteria.
@Override public int hashCode(){ int result=0; Iterator<?> it=iterator(); while (it.hasNext()) { Object next=it.next(); result+=next == null ? 0 : next.hashCode(); } return result; }
Returns the hash code for this set. Two set which are equal must return the same value. This implementation calculates the hash code by adding each element's hash code.
public double[] toRealPoint(int scale){ if (mChart instanceof XYChart) { XYChart chart=(XYChart)mChart; return chart.toRealPoint(oldX,oldY,scale); } return null; }
Transforms the currently selected screen point to a real point.
@Override public boolean onOptionsItemSelected(MenuItem item){ switch (item.getItemId()) { case android.R.id.home: finish(); break; case R.id.action_add_header: if (headerPosition < 0) { headerPosition=0; } headerPosition++; mAdapter.addHeader("header " + headerPosition); mList.scrollToPosition(0); return true; case R.id.action_remove_header: if (headerPosition <= 0) { return true; } headerPosition--; mAdapter.removeHeader(headerPosition); mList.scrollToPosition(0); return true; case R.id.action_add_footer: if (footerPosition < 0) { footerPosition=0; } footerPosition++; mAdapter.addFooter("footer " + footerPosition); mList.scrollToPosition(mAdapter.getItemCount() - 1); return true; case R.id.action_remove_footer: if (footerPosition <= 0) { return true; } footerPosition--; mAdapter.removeFooter(footerPosition); mList.scrollToPosition(mAdapter.getItemCount() - 1); return true; case R.id.action_change_mode: mAdapter.changeMode(++mode); if (mode > YfListMode.MODE_EMPTY) { mode=YfListMode.MODE_DATA; } return true; case R.id.action_clear_data: mCurrentPage=1; headerPosition=0; footerPosition=0; mAdapter.removeAllHeader(); mAdapter.removeAllFooters(); mAdapter.setData(null); return true; case R.id.action_set_data: mCurrentPage=1; mData.clear(); for (int i=0; i < 20; i++) { mData.add("item " + i); } headerPosition=0; footerPosition=0; mAdapter.removeAllHeader(); mAdapter.removeAllFooters(); mAdapter.setData(mData); return true; } return super.onOptionsItemSelected(item); }
add test method
private void pushBack(){ lookahead=previous; st.pushBack(); }
push back the lookahead token and restore the lookahead token to the previous token.
public int function(int position,int[] genome){ return functionSub(position); }
Determine the function number from the given genome and position (float version).
public synchronized void addVetoableChangeListener(VetoableChangeListener l){ m_vetoableChangeSupport.addVetoableChangeListener(l); }
Add Vetoable change listener for row changes
public List<Throwable> nestedCauses(){ return causes; }
Gets nested causes for this multi-exception.
public long optLong(int index){ return this.optLong(index,0); }
Get the optional long value associated with an index. Zero is returned if there is no value for the index, or if the value is not a number and cannot be converted to a number.
public static RelationalOpExpression le(String propertyName,Object value){ return new RelationalOpExpression(getPropExpr(propertyName),"<=",new ConstantExpression(value)); }
Less-or-equals between a property and a constant.
public boolean equals(DisplayMetrics other){ return equalsPhysical(other) && scaledDensity == other.scaledDensity && noncompatScaledDensity == other.noncompatScaledDensity; }
Returns true if these display metrics equal the other display metrics.
@Override public void updateObject(int columnIndex,Object x,int scale) throws SQLException { try { if (isDebugEnabled()) { debugCode("updateObject(" + columnIndex + ", x, "+ scale+ ");"); } update(columnIndex,convertToUnknownValue(x)); } catch ( Exception e) { throw logAndConvert(e); } }
Updates a column in the current or insert row.
public static Collection flatten(short[] self){ return flatten(toList(self),new ArrayList()); }
Flatten an array. This array and any nested arrays or collections have their contents (recursively) added to the new collection.
@Override public void dispose(){ GL30 gl=Gdx.gl30; gl.glBindBuffer(GL20.GL_ARRAY_BUFFER,0); gl.glDeleteBuffer(bufferHandle); bufferHandle=0; if (gl.glIsVertexArray(vaoHandle)) { tmpHandle.clear(); tmpHandle.put(vaoHandle); tmpHandle.flip(); gl.glDeleteVertexArrays(1,tmpHandle); } }
Disposes of all resources this VertexBufferObject uses.
Deque<Expr> clone_stk(Set<Expr> phis,Deque<Expr> stk,Edge p){ if (phis.isEmpty() || stk.isEmpty()) return stk; Deque<Expr> copy=new ArrayDeque<Expr>(); for ( Expr e : stk) copy.add(phis.contains(e) ? e.args[findPhiArg(e,p)] : e); return copy; }
clone the stack layout for a predecessor edge, replacing phi's with the argument coming from that edge.
public BillingAdapterNotFoundException(){ }
Constructs a new exception with <code>null</code> as its detail message. The cause is not initialized.
public double optDouble(int index){ return this.optDouble(index,Double.NaN); }
Get the optional double value associated with an index. NaN is returned if there is no value for the index, or if the value is not a number and cannot be converted to a number.
public boolean generate(Projection proj){ Debug.message("eomg","EditableOMCircle.generate()"); if (circle != null) circle.generate(proj); for (int i=0; i < gPoints.length; i++) { GrabPoint gp=gPoints[i]; if (gp != null) { gp.generate(proj); } } return true; }
Use the current projection to place the graphics on the screen. Has to be called to at least assure the graphics that they are ready for rendering. Called when the graphic position changes.
protected void createShapePositions(DrawContext dc){ Globe globe=dc.getGlobe(); List<Position> leftPositions=new ArrayList<Position>(); List<Position> rightPositions=new ArrayList<Position>(); List<Position> arrowHeadPositions=new ArrayList<Position>(); double halfWidth=this.createArrowHeadPositions(leftPositions,rightPositions,arrowHeadPositions,globe); this.createLinePositions(leftPositions,rightPositions,halfWidth,globe); Collections.reverse(leftPositions); List<Position> allPositions=new ArrayList<Position>(leftPositions); allPositions.addAll(arrowHeadPositions); allPositions.addAll(rightPositions); this.arrowPositions=allPositions; this.paths[0].setPositions(allPositions); }
Create the list of positions that describe the arrow.
public KeyedValues(KeyedValues other){ if (other.isSetKey()) { this.key=org.apache.thrift.TBaseHelper.copyBinary(other.key); ; } if (other.isSetValues()) { List<VersionedValue> __this__values=new ArrayList<VersionedValue>(); for ( VersionedValue other_element : other.values) { __this__values.add(new VersionedValue(other_element)); } this.values=__this__values; } }
Performs a deep copy on <i>other</i>.
public void close(){ parser.close(); }
Frees any resources this parser may be holding.
private void postTransform(float[] matrix){ float[] tmp=new float[9]; multiply(tmp,mValues,matrix); mValues=tmp; }
Adds the given transformation to the current Matrix <p/>This in effect does this = this*matrix
public String performStringSubstitution(String expression,boolean reportUndefinedVariables,boolean resolveVariables,IStringVariableManager manager) throws CoreException { substitute(expression,reportUndefinedVariables,resolveVariables,manager); List<HashSet<String>> resolvedVariableSets=new ArrayList<HashSet<String>>(); while (fSubs) { HashSet<String> resolved=substitute(fResult.toString(),reportUndefinedVariables,true,manager); for (int i=resolvedVariableSets.size() - 1; i >= 0; i--) { HashSet<String> prevSet=resolvedVariableSets.get(i); if (prevSet.equals(resolved)) { HashSet<String> conflictingSet=new HashSet<String>(); for (; i < resolvedVariableSets.size(); i++) { conflictingSet.addAll(resolvedVariableSets.get(i)); } StringBuffer problemVariableList=new StringBuffer(); for ( String string : conflictingSet) { problemVariableList.append(string); problemVariableList.append(", "); } problemVariableList.setLength(problemVariableList.length() - 2); throw new CoreException(new Status(IStatus.ERROR,VariablesPlugin.getUniqueIdentifier(),VariablesPlugin.REFERENCE_CYCLE_ERROR,NLS.bind(VariablesMessages.StringSubstitutionEngine_4,new String[]{problemVariableList.toString()}),null)); } } resolvedVariableSets.add(resolved); } return fResult.toString(); }
Performs recursive string substitution and returns the resulting string.
public static void powInPlace(double[] a,double c){ for (int i=0; i < a.length; i++) { a[i]=Math.pow(a[i],c); } }
Scales the values in this array by c.
public ConnectionConfig(jmri.jmrix.SerialPortAdapter p){ super(p); }
Ctor for an object being created during load process; Swing init is deferred.
public ImageFetcher(Context context,int imageSize){ super(context,imageSize); init(context); }
Initialize providing a single target image size (used for both width and height);
@Override public boolean isVisible(){ return (getSceneHints().getCullHint() != CullHint.Always); }
Is this visible
public void unregisterInterestRegistrationListener(InterestRegistrationListener listener){ getCacheClientNotifier().unregisterInterestRegistrationListener(listener); }
Unregisters an existing <code>InterestRegistrationListener</code> from the set of <code>InterestRegistrationListener</code>s.
private void completeTaskAsUnsupported(TaskCompleter completer){ StackTraceElement[] stackTrace=Thread.currentThread().getStackTrace(); String methodName=stackTrace[2].getMethodName(); ServiceCoded code=DeviceControllerErrors.ceph.operationIsUnsupported(methodName); completer.error(_dbClient,code); }
Method calls the completer with error message indicating that the caller's method is unsupported
public void throwException(){ mv.visitInsn(Opcodes.ATHROW); }
Generates the instruction to throw an exception.
private synchronized void updateEndpoint(SystemConfiguration config,Logger logger,long previousRefresh){ long diff=System.currentTimeMillis() - previousRefresh; if (diff > MIN_SESSION_REFRESH_THRESHOLD_MILLIS) { lastRefresh=System.currentTimeMillis(); PostMethod post=new PostMethod(config.getValue(Property.GOC_ENDPOINT.getName(),Property.GOC_ENDPOINT.getDefaultValue()) + "/services/oauth2/token"); try { post.addParameter("grant_type","password"); post.addParameter("client_id",URLEncoder.encode(config.getValue(Property.GOC_CLIENT_ID.getName(),Property.GOC_CLIENT_ID.getDefaultValue()),UTF_8)); post.addParameter("client_secret",URLEncoder.encode(config.getValue(Property.GOC_CLIENT_SECRET.getName(),Property.GOC_CLIENT_SECRET.getDefaultValue()),UTF_8)); post.addParameter("username",config.getValue(Property.GOC_USER.getName(),Property.GOC_USER.getDefaultValue())); post.addParameter("password",config.getValue(Property.GOC_PWD.getName(),Property.GOC_PWD.getDefaultValue())); HttpClient httpclient=getHttpClient(config); int respCode=httpclient.executeMethod(post); if (respCode == 200) { JsonObject authResponse=new Gson().fromJson(post.getResponseBodyAsString(),JsonObject.class); String endpoint=authResponse.get("instance_url").getAsString(); String token=authResponse.get("access_token").getAsString(); logger.info("Success - getting access_token for endpoint '{}'",endpoint); logger.debug("access_token '{}'",token); theEndpointInfo=new EndpointInfo(endpoint,token); } else { logger.error("Failure - getting oauth2 token, check username/password: '{}'",post.getResponseBodyAsString()); } } catch ( Exception e) { logger.error("Failure - exception getting access_token '{}'",e); } finally { if (theEndpointInfo == null) { theEndpointInfo=new EndpointInfo(config.getValue(Property.GOC_ENDPOINT.getName(),Property.GOC_ENDPOINT.getDefaultValue()),NO_TOKEN); } post.releaseConnection(); } } }
Update the global 'theEndpointInfo' state with a valid endpointInfo if login is successful or a dummy value if not successful.
Span(float start,float end){ mStart=start; mEnd=end; }
Create a half-open interval including <code>start</code> but not including <code>end</code>.
@Override protected EClass eStaticClass(){ return SRuntimePackage.Literals.REFERENCE_SLOT; }
<!-- begin-user-doc --> <!-- end-user-doc -->
public static String encodeWithinPath(final String unescaped) throws URIException { return encodeWithinPath(unescaped,URI.getDefaultProtocolCharset()); }
Escape and encode a string regarded as within the path component of an URI with the default protocol charset. The path may consist of a sequence of path segments separated by a single slash "/" character. Within a path segment, the characters "/", ";", "=", and "?" are reserved.
private Process createProcess(final File sourceFile) throws IOException { notNull(sourceFile); final String[] commandLine=getCommandLine(sourceFile.getPath()); LOG.debug("CommandLine arguments: {}",Arrays.asList(commandLine)); return new ProcessBuilder(commandLine).redirectErrorStream(true).start(); }
Creates process responsible for running lessc shell command by reading the file content from the sourceFilePath
public static int binarySearch(byte[] a,byte key){ int low=0; int high=a.length - 1; while (low <= high) { int mid=(low + high) >> 1; byte midVal=a[mid]; if (midVal < key) low=mid + 1; else if (midVal > key) high=mid - 1; else return mid; } return -(low + 1); }
Searches the specified array of bytes for the specified value using the binary search algorithm. The array <strong>must</strong> be sorted (as by the <tt>sort</tt> method, above) prior to making this call. If it is not sorted, the results are undefined. If the array contains multiple elements with the specified value, there is no guarantee which one will be found.
public OperationCanceledException(){ super(); }
Creates a new exception.
@Override protected void drawData(){ ArrayList<DataSet> dataSets=mData.getDataSets(); for (int i=0; i < mData.getDataSetCount(); i++) { DataSet dataSet=dataSets.get(i); ArrayList<Entry> entries=dataSet.getYVals(); float[] valuePoints=generateTransformedValues(entries,0f); ArrayList<Integer> colors=mCt.getDataSetColors(i % mCt.getColors().size()); Paint paint=mRenderPaint; for (int j=0; j < valuePoints.length - 2; j+=2) { paint.setColor(colors.get(j % colors.size())); if (isOffContentRight(valuePoints[j])) break; if (j != 0 && isOffContentLeft(valuePoints[j - 1])) continue; mDrawCanvas.drawLine(valuePoints[j],valuePoints[j + 1],valuePoints[j + 2],valuePoints[j + 3],paint); } if (mDrawFilled) { paint.setAlpha(85); Path filled=new Path(); filled.moveTo(0,entries.get(0).getVal()); for (int x=1; x < entries.size(); x++) { filled.lineTo(x,entries.get(x).getVal()); } filled.lineTo(entries.size() - 1,mYChartMin); filled.lineTo(0f,mYChartMin); filled.close(); transformPath(filled); mDrawCanvas.drawPath(filled,paint); paint.setAlpha(255); } } }
draws the given y values to the screen
public static DefaultMapAdapter adapt(Map map,ObjectWrapperWithAPISupport wrapper){ return new DefaultMapAdapter(map,wrapper); }
Factory method for creating new adapter instances.
public static void dropTable(SQLiteDatabase db,boolean ifExists){ String sql="DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "'USER'"; db.execSQL(sql); }
Drops the underlying database table.
public String globalInfo(){ return "The class that splits a node into two such that the overall sum " + "of squared distances of points to their centres on both sides " + "of the (axis-parallel) splitting plane is minimum.\n\n"+ "For more information see also:\n\n"+ getTechnicalInformation().toString(); }
Returns a string describing this nearest neighbour search algorithm.
public String nextValue() throws IOException { Token tkn=nextToken(); String ret=null; switch (tkn.type) { case TT_TOKEN: case TT_EORECORD: ret=tkn.content.toString(); break; case TT_EOF: ret=null; break; case TT_INVALID: default : throw new IOException("(line " + getLineNumber() + ") invalid parse sequence"); } return ret; }
Parses the CSV according to the given strategy and returns the next csv-value as string.
private void addAutoTieringPolicyCapability(StorageCapabilities storageCapabilities,URI autoTieringPolicyURI){ if (!NullColumnValueGetter.isNullURI(autoTieringPolicyURI)) { AutoTieringPolicy autoTieringPolicy=dbClient.queryObject(AutoTieringPolicy.class,autoTieringPolicyURI); if (autoTieringPolicy == null) { throw DeviceControllerException.exceptions.objectNotFound(autoTieringPolicyURI); } AutoTieringPolicyCapabilityDefinition capabilityDefinition=new AutoTieringPolicyCapabilityDefinition(); Map<String,List<String>> capabilityProperties=new HashMap<>(); capabilityProperties.put(AutoTieringPolicyCapabilityDefinition.PROPERTY_NAME.POLICY_ID.name(),Arrays.asList(autoTieringPolicy.getPolicyName())); capabilityProperties.put(AutoTieringPolicyCapabilityDefinition.PROPERTY_NAME.PROVISIONING_TYPE.name(),Arrays.asList(autoTieringPolicy.getProvisioningType())); CapabilityInstance autoTieringCapability=new CapabilityInstance(capabilityDefinition.getId(),autoTieringPolicy.getPolicyName(),capabilityProperties); CommonStorageCapabilities commonCapabilities=storageCapabilities.getCommonCapabilitis(); if (commonCapabilities == null) { commonCapabilities=new CommonStorageCapabilities(); storageCapabilities.setCommonCapabilitis(commonCapabilities); } List<DataStorageServiceOption> dataStorageSvcOptions=commonCapabilities.getDataStorage(); if (dataStorageSvcOptions == null) { dataStorageSvcOptions=new ArrayList<>(); commonCapabilities.setDataStorage(dataStorageSvcOptions); } DataStorageServiceOption dataStorageSvcOption=new DataStorageServiceOption(Arrays.asList(autoTieringCapability)); dataStorageSvcOptions.add(dataStorageSvcOption); } }
Create the auto tiering policy capability and add it to the passed storage capabilities
public GeographicCell(int m0,int m1,int n0,int n1){ super(m0,m1,n0,n1); }
Constructs a new Geographic Cell, but otherwise does nothing.
private List<?> internalCalculateIndex(CompositeData value){ return Collections.unmodifiableList(Arrays.asList(value.getAll(this.indexNamesArray))); }
Returns the index for value, assuming value is valid for this <tt>TabularData</tt> instance (ie value is not null, and its composite type is equal to row type). The index is a List, and not an array, so that an index.equals(otherIndex) call will actually compare contents, not just the objects references as is done for an array object. The returned List is unmodifiable so that once a row has been put into the dataMap, its index cannot be modified, for example by a user that would attempt to modify an index contained in the Set returned by keySet().
public Builder withFlushOnCommit(boolean flushOnCommit){ storage.flushOnCommit=flushOnCommit; return this; }
Sets whether to flush buffers to disk when entries are committed to a segment, returning the builder for method chaining. <p> When flush-on-commit is enabled, log entry buffers will be automatically flushed to disk each time an entry is committed in a given segment.
public String globalInfo(){ return "A filter that adds new attributes with user specified type and constant value. " + "Numeric, nominal, string and date attributes can be created. " + "Attribute name, and value can be set with environment variables. Date "+ "attributes can also specify a formatting string by which to parse "+ "the supplied date value. Alternatively, a current time stamp can "+ "be specified by supplying the special string \"now\" as the value "+ "for a date attribute."; }
Returns a string describing this filter
private EvidenceBuilder(final int evidenceType,final byte[] additional,final byte[] data){ final Packet p=init(evidenceType); p.setCommand(LOG_ATOMIC); p.setAdditional(additional); p.setData(data); hasData=true; send(p); }
Instantiates a new log, creates atomically the evidence with additional and data.
public RemovalContext fail(Exception cause){ this.cause=cause; return this; }
Sets the context into failed state.
public static void overScrollBy(final PullToRefreshBase<?> view,final int deltaX,final int scrollX,final int deltaY,final int scrollY,final int scrollRange,final int fuzzyThreshold,final float scaleFactor,final boolean isTouchEvent){ final int deltaValue, currentScrollValue, scrollValue; switch (view.getPullToRefreshScrollDirection()) { case HORIZONTAL: deltaValue=deltaX; scrollValue=scrollX; currentScrollValue=view.getScrollX(); break; case VERTICAL: default : deltaValue=deltaY; scrollValue=scrollY; currentScrollValue=view.getScrollY(); break; } if (view.isPullToRefreshOverScrollEnabled() && !view.isRefreshing()) { final Mode mode=view.getMode(); if (mode.permitsPullToRefresh() && !isTouchEvent && deltaValue != 0) { final int newScrollValue=(deltaValue + scrollValue); if (PullToRefreshBase.DEBUG) { Log.d(LOG_TAG,"OverScroll. DeltaX: " + deltaX + ", ScrollX: "+ scrollX+ ", DeltaY: "+ deltaY+ ", ScrollY: "+ scrollY+ ", NewY: "+ newScrollValue+ ", ScrollRange: "+ scrollRange+ ", CurrentScroll: "+ currentScrollValue); } if (newScrollValue < (0 - fuzzyThreshold)) { if (mode.showHeaderLoadingLayout()) { if (currentScrollValue == 0) { view.setState(State.OVERSCROLLING); } view.setHeaderScroll((int)(scaleFactor * (currentScrollValue + newScrollValue))); } } else if (newScrollValue > (scrollRange + fuzzyThreshold)) { if (mode.showFooterLoadingLayout()) { if (currentScrollValue == 0) { view.setState(State.OVERSCROLLING); } view.setHeaderScroll((int)(scaleFactor * (currentScrollValue + newScrollValue - scrollRange))); } } else if (Math.abs(newScrollValue) <= fuzzyThreshold || Math.abs(newScrollValue - scrollRange) <= fuzzyThreshold) { view.setState(State.RESET); } } else if (isTouchEvent && State.OVERSCROLLING == view.getState()) { view.setState(State.RESET); } } }
Helper method for Overscrolling that encapsulates all of the necessary function. This is the advanced version of the call.
public static SortedProperties fromLines(String s){ SortedProperties p=new SortedProperties(); for ( String line : StringUtils.arraySplit(s,'\n',true)) { int idx=line.indexOf('='); if (idx > 0) { p.put(line.substring(0,idx),line.substring(idx + 1)); } } return p; }
Convert a String to a map.
public final void readResources(final PdfObject Resources,final boolean resetList) throws PdfException { if (resetList) { pdfFontFactory.resetfontsInFile(); } currentPdfFile.checkResolved(Resources); cache.readResources(Resources,resetList); }
read page header and extract page metadata
public static String trimLine(String line){ int idx=line.indexOf("//"); if (idx != -1) { line=line.substring(0,idx); } return line.trim(); }
trims a line and removes comments
public static void addFollowInDumpMenu(final JPopupMenu menu,final CGraphModel model,final NaviNode node,final Object clickedObject,final double y){ Preconditions.checkNotNull(menu,"IE02371: menu argument can not be null"); Preconditions.checkNotNull(model,"IE02372: model argument can not be null"); Preconditions.checkNotNull(node,"IE02373: node argument can not be null"); final int line=node.positionToRow(y); if (line == -1) { return; } final INaviCodeNode codeNode=(INaviCodeNode)node.getRawNode(); final INaviInstruction instruction=CCodeNodeHelpers.lineToInstruction(codeNode,line); if (instruction != null) { final IDebugger debugger=CGraphDebugger.getDebugger(model.getDebuggerProvider(),instruction); if ((debugger != null) && (clickedObject instanceof COperandTreeNode)) { final TargetProcessThread activeThread=debugger.getProcessManager().getActiveThread(); if (activeThread != null) { final CDebugPerspectiveModel viewModel=(CDebugPerspectiveModel)model.getGraphPanel().getViewModel().getModel(PerspectiveType.DebugPerspective); final COperandTreeNode treeNode=(COperandTreeNode)clickedObject; final boolean added=addFollowInDumpMenu(menu,viewModel,debugger,activeThread,instruction.getModule(),treeNode); if (added) { menu.addSeparator(); } } } } }
Adds the menu that follow in dump menu for the clicked instruction.
public static Response createCreatePermissionResponse(){ Response permissionSuccessResponse=new Response(); permissionSuccessResponse.setMessageType(Message.CREATEPERMISSION_RESPONSE); return permissionSuccessResponse; }
Creates a create permission success response.
public static byte[] asUnsignedByteArray(int length,BigInteger value){ byte[] bytes=value.toByteArray(); if (bytes[0] == 0) { if (bytes.length - 1 > length) { throw new IllegalArgumentException("standard length exceeded for value"); } byte[] tmp=new byte[length]; System.arraycopy(bytes,1,tmp,tmp.length - (bytes.length - 1),bytes.length - 1); return tmp; } else { if (bytes.length == length) { return bytes; } if (bytes.length > length) { throw new IllegalArgumentException("standard length exceeded for value"); } byte[] tmp=new byte[length]; System.arraycopy(bytes,0,tmp,tmp.length - bytes.length,bytes.length); return tmp; } }
Return the passed in value as an unsigned byte array.
public final void updateConfig(ProjectConfig update) throws ServerException, ValueStorageException, ProjectTypeConstraintException, InvalidValueException { final ProjectJson projectJson=new ProjectJson(); ProjectTypes types=new ProjectTypes(update.getTypeId(),update.getMixinTypes()); types.removeTransient(); projectJson.setType(types.primary.getId()); projectJson.setBuilders(update.getBuilders()); projectJson.setRunners(update.getRunners()); projectJson.setDescription(update.getDescription()); ArrayList<String> ms=new ArrayList<>(); ms.addAll(types.mixins.keySet()); projectJson.setMixinTypes(ms); HashMap<String,AttributeValue> checkVariables=new HashMap<>(); for ( String attributeName : update.getAttributes().keySet()) { AttributeValue attributeValue=update.getAttributes().get(attributeName); Attribute definition=null; for ( ProjectType t : types.all.values()) { definition=t.getAttribute(attributeName); if (definition != null) break; } if (definition != null && definition.isVariable()) { Variable var=(Variable)definition; if (attributeValue == null && var.isRequired()) { throw new ProjectTypeConstraintException("Required attribute value is initialized with null value " + var.getId()); } if (attributeValue != null) { final ValueProviderFactory valueProviderFactory=var.getValueProviderFactory(); if (valueProviderFactory != null) { valueProviderFactory.newInstance(baseFolder).setValues(var.getName(),attributeValue.getList()); } if (valueProviderFactory == null) { projectJson.getAttributes().put(definition.getName(),attributeValue.getList()); } } checkVariables.put(attributeName,attributeValue); } } for ( ProjectType t : types.all.values()) { for ( Attribute attr : t.getAttributes()) { if (attr.isVariable()) { if (!checkVariables.containsKey(attr.getName()) && attr.isRequired()) { throw new ProjectTypeConstraintException("Required attribute value is initialized with null value " + attr.getId()); } } else { projectJson.getAttributes().put(attr.getName(),attr.getValue().getList()); } } } if (projectJson.getBuilders().getDefault() == null) projectJson.getBuilders().setDefault(types.primary.getDefaultBuilder()); if (projectJson.getRunners().getDefault() == null) projectJson.getRunners().setDefault(types.primary.getDefaultRunner()); projectJson.save(this); }
Updates Project Config making all necessary validations
private VOService createServiceWithParameter(List<VOParameter> params) throws Exception { return setup.createAndActivateService("marketPlace",technicalServiceWithParameter,mpLocal,params); }
create marketplace service with parameters
public void testSetCursorStyle() throws Exception { withTerminalSized(5,5); assertEquals(TerminalEmulator.CURSOR_STYLE_BLOCK,mTerminal.getCursorStyle()); enterString("\033[3 q"); assertEquals(TerminalEmulator.CURSOR_STYLE_UNDERLINE,mTerminal.getCursorStyle()); enterString("\033[5 q"); assertEquals(TerminalEmulator.CURSOR_STYLE_BAR,mTerminal.getCursorStyle()); enterString("\033[0 q"); assertEquals(TerminalEmulator.CURSOR_STYLE_BLOCK,mTerminal.getCursorStyle()); enterString("\033[6 q"); assertEquals(TerminalEmulator.CURSOR_STYLE_BAR,mTerminal.getCursorStyle()); enterString("\033[4 q"); assertEquals(TerminalEmulator.CURSOR_STYLE_UNDERLINE,mTerminal.getCursorStyle()); enterString("\033[1 q"); assertEquals(TerminalEmulator.CURSOR_STYLE_BLOCK,mTerminal.getCursorStyle()); enterString("\033[4 q"); assertEquals(TerminalEmulator.CURSOR_STYLE_UNDERLINE,mTerminal.getCursorStyle()); enterString("\033[2 q"); assertEquals(TerminalEmulator.CURSOR_STYLE_BLOCK,mTerminal.getCursorStyle()); }
Test the cursor shape changes using DECSCUSR.
protected void fireBaseAttributeListeners(String pn){ if (targetListeners != null) { LinkedList ll=(LinkedList)targetListeners.get(pn); if (ll != null) { Iterator it=ll.iterator(); while (it.hasNext()) { AnimationTargetListener l=(AnimationTargetListener)it.next(); l.baseValueChanged((AnimationTarget)e,null,pn,true); } } } }
Fires the listeners registered for changes to the base value of the given CSS property.
@Override public void invalidate(){ bufferHandle=Gdx.gl20.glGenBuffer(); isDirty=true; vaoDirty=true; }
Invalidates the VertexBufferObject so a new OpenGL buffer handle is created. Use this in case of a context loss.
public static <T,R>Function<T,R> memoizeFunction(Function1<T,R> fn,Cacheable<R> cache){ return null; }
Convert a Function into one that caches it's result