code
stringlengths
10
174k
nl
stringlengths
3
129k
public String authenticate(String username,String password,String resource) throws XMPPException { String selectedMechanism=null; for ( String mechanism : mechanismsPreferences) { if (implementedMechanisms.containsKey(mechanism) && serverMechanisms.contains(mechanism)) { selectedMechanism=mechanism; break; } } if (selectedMechanism != null) { try { Class<? extends SASLMechanism> mechanismClass=implementedMechanisms.get(selectedMechanism); Constructor<? extends SASLMechanism> constructor=mechanismClass.getConstructor(SASLAuthentication.class); currentMechanism=constructor.newInstance(this); currentMechanism.authenticate(username,connection.getServiceName(),password); synchronized (this) { if (!saslNegotiated && !saslFailed) { try { wait(30000); } catch ( InterruptedException e) { } } } if (saslFailed) { if (errorCondition != null) { throw new XMPPException("SASL authentication " + selectedMechanism + " failed: "+ errorCondition); } else { throw new XMPPException("SASL authentication failed using mechanism " + selectedMechanism); } } if (saslNegotiated) { return bindResourceAndEstablishSession(resource); } else { return new NonSASLAuthentication(connection).authenticate(username,password,resource); } } catch ( XMPPException e) { throw e; } catch ( Exception e) { e.printStackTrace(); return new NonSASLAuthentication(connection).authenticate(username,password,resource); } } else { return new NonSASLAuthentication(connection).authenticate(username,password,resource); } }
Performs SASL authentication of the specified user. If SASL authentication was successful then resource binding and session establishment will be performed. This method will return the full JID provided by the server while binding a resource to the connection.<p> The server may assign a full JID with a username or resource different than the requested by this method.
public ScreenCapturePixelMatrixEditor(){ super(); initComponents(); layoutComponents(); }
Create a new screen capture pixel matrix editor.
public void startAnimation(){ resetAnimation(); }
Starts the progress bar animation. (This is an alias of resetAnimation() so it does the same thing.)
@Override public boolean isActive(){ return amIActive; }
Used by the Whitebox GUI to tell if this plugin is still running.
public static String hmac(String data,String key) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException { SecretKeySpec keySpec=new SecretKeySpec(key.getBytes("UTF-8"),"HmacSHA256"); Mac mac=Mac.getInstance("HmacSHA256"); mac.init(keySpec); return Hash.toHexString(mac.doFinal(data.getBytes("UTF-8"))); }
calculates the hamc
public void visitLocalVariable(String name,String desc,String signature,Label start,Label end,int index){ if (mv != null) { mv.visitLocalVariable(name,desc,signature,start,end,index); } }
Visits a local variable declaration.
public static final boolean exists(String code){ return mapping.containsKey(code.toLowerCase()); }
see if the given country in alpha-2 country code exists
public XMLElement(String fullName,String systemID,int lineNr){ this(fullName,null,systemID,lineNr); }
Creates an empty element.
public boolean hasMatch(){ return _match != null; }
Accessor to use to see if any formats matched well enough with the input data.
@Override public void execute(String[] params,Server server,Conversation conversation,IRCService service) throws CommandException { if (params.length == 2) { service.getConnection(server.getId()).joinChannel(params[1]); } else if (params.length == 3) { service.getConnection(server.getId()).joinChannel(params[1],params[2]); } else { throw new CommandException(service.getString(R.string.invalid_number_of_params)); } }
Execute /join
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); this.backgroundPaint=SerialUtilities.readPaint(stream); }
Provides serialization support.
BitMatrix buildFunctionPattern(){ int dimension=getDimensionForVersion(); BitMatrix bitMatrix=new BitMatrix(dimension); bitMatrix.setRegion(0,0,9,9); bitMatrix.setRegion(dimension - 8,0,8,9); bitMatrix.setRegion(0,dimension - 8,9,8); int max=alignmentPatternCenters.length; for (int x=0; x < max; x++) { int i=alignmentPatternCenters[x] - 2; for (int y=0; y < max; y++) { if ((x == 0 && (y == 0 || y == max - 1)) || (x == max - 1 && y == 0)) { continue; } bitMatrix.setRegion(alignmentPatternCenters[y] - 2,i,5,5); } } bitMatrix.setRegion(6,9,1,dimension - 17); bitMatrix.setRegion(9,6,dimension - 17,1); if (versionNumber > 6) { bitMatrix.setRegion(dimension - 11,0,3,6); bitMatrix.setRegion(0,dimension - 11,6,3); } return bitMatrix; }
See ISO 18004:2006 Annex E
public SnapshotsStatusRequestBuilder addSnapshots(String... snapshots){ request.snapshots(ObjectArrays.concat(request.snapshots(),snapshots,String.class)); return this; }
Adds additional snapshots to the list of snapshots to return
public static void encodeToFile(byte[] dataToEncode,String filename) throws java.io.IOException { if (dataToEncode == null) { throw new NullPointerException("Data to encode was null."); } Base64.OutputStream bos=null; try { bos=new Base64.OutputStream(new java.io.FileOutputStream(filename),Base64.ENCODE); bos.write(dataToEncode); } catch ( java.io.IOException e) { throw e; } finally { try { bos.close(); } catch ( Exception e) { } } }
Convenience method for encoding data to a file. <p>As of v 2.3, if there is a error, the method will throw an java.io.IOException. <b>This is new to v2.3!</b> In earlier versions, it just returned false, but in retrospect that's a pretty poor way to handle it.</p>
public static ComponentUI createUI(JComponent list){ return new PaletteListUI(); }
Returns a new instance of PaletteListUI. PaletteListUI delegates are allocated one per JList.
public DbUtils() throws Exception { super(); }
initializes the object.
default boolean matches(Repository repository,T entity){ return matches(entity); }
Defines a predicate for matching entities
public MultiStep(Steppable step,int n,boolean countdown){ if (n < 0) n=0; this.n=n; this.step=step; this.countdown=countdown; current=n; }
If countdown is true, then we call step.step(...) once every N times we're stepped. if countdown is false, then we call step.step(...) N times every time we're stepped.
public void generateOptimizedNonBooleanEqual(BlockScope currentScope,BranchLabel trueLabel,BranchLabel falseLabel,boolean valueRequired){ Constant inline; if ((inline=this.right.constant) != Constant.NotAConstant) { if ((((this.left.implicitConversion & IMPLICIT_CONVERSION_MASK) >> 4) == T_int) && (inline.intValue() == 0)) { this.left.generateCode(currentScope,valueRequired); return; } } if ((inline=this.left.constant) != Constant.NotAConstant) { if ((((this.left.implicitConversion & IMPLICIT_CONVERSION_MASK) >> 4) == T_int) && (inline.intValue() == 0)) { this.right.generateCode(currentScope,valueRequired); return; } } if (this.right instanceof NullLiteral) { if (this.left instanceof NullLiteral) { return; } else if (this.left instanceof NullLiteral) { this.right.generateCode(currentScope,valueRequired); return; } this.left.generateCode(currentScope,valueRequired); this.right.generateCode(currentScope,valueRequired); } }
Boolean generation for == with non-boolean operands
private void addProducedBindings(final TermNode t,final Set<IVariable<?>> producedBindings){ if (t instanceof VarNode) { producedBindings.add(((VarNode)t).getValueExpression()); } else if (t instanceof ConstantNode) { final ConstantNode cNode=(ConstantNode)t; final Constant<?> c=(Constant<?>)cNode.getValueExpression(); final IVariable<?> var=c.getVar(); if (var != null) { producedBindings.add(var); } } }
This handles the special case where we've wrapped a Var with a Constant because we know it's bound, perhaps by the exogenous bindings. If we don't handle this case then we get the join vars wrong.
public boolean isSingleSided(){ return isSingleSided; }
Tests whether the buffer is to be generated on a single side only.
public IdentityHashMap(Map<? extends K,? extends V> m){ this((int)((1 + m.size()) * 1.1)); putAll(m); }
Constructs a new identity hash map containing the keys-value mappings in the specified map.
public boolean isTwoDigitMode(){ return twoDigitMode; }
When set to true days will be rendered as 2 digits with 0 preceding single digit days
public void bitAnd() throws IOException { print("bitAnd",null); }
Description of the Method
public VerletParticle3D lock(){ isLocked=true; return this; }
Locks/immobilizes particle in space
private boolean logIfDefined(Object objToLog){ if (objToLog != null && !(objToLog instanceof Undefined)) { logger.info(Context.toString(objToLog)); return true; } else return false; }
Logs object's Context.toString(...) representation to INFO stream if it's defined.
@Override public boolean eIsSet(int featureID){ switch (featureID) { case GamlPackage.STATEMENT__KEY: return KEY_EDEFAULT == null ? key != null : !KEY_EDEFAULT.equals(key); case GamlPackage.STATEMENT__FIRST_FACET: return FIRST_FACET_EDEFAULT == null ? firstFacet != null : !FIRST_FACET_EDEFAULT.equals(firstFacet); case GamlPackage.STATEMENT__EXPR: return expr != null; case GamlPackage.STATEMENT__FACETS: return facets != null && !facets.isEmpty(); case GamlPackage.STATEMENT__BLOCK: return block != null; } return super.eIsSet(featureID); }
<!-- begin-user-doc --> <!-- end-user-doc -->
@Override public boolean supports(String view){ return getScriptEngine(view) != null; }
What extensions does the view engine support.
public static Vector<String> string2vector(final String string){ Vector<String> v; if (string != null) { v=new Vector<String>(Arrays.asList(CommonPattern.COMMA.split(string,0))); } else { v=new Vector<String>(); } return v; }
Simple conversion of a comma separated list to a Vector containing the order of the substrings.
public ProgressHelper(Executor executor){ super(); this.executor=executor; statistics=new DescriptiveStatistics(25); listeners=EventListenerSupport.create(ProgressListener.class); }
Constructs a new progress helper for generating progress reports for the given executor.
public boolean inMethod(){ return false; }
Will return false since this is an inline tag.
@Inject public ProjectSelectionDialog(N4JSProjectContentProvider n4jsProjectContentProvider){ super(UIUtils.getShell()); this.setContentProvider(n4jsProjectContentProvider); this.setLabelProvider(new N4JSProjectLabelProvider()); this.setInput(ResourcesPlugin.getWorkspace().getRoot()); this.setHelpAvailable(false); }
Create a new project selection dialog
void initToken(){ buffer=new StringBuilder(); }
Initialize the tokenizer.
private static final String decode(Set<? extends Integer> src){ if (src == null || src.isEmpty()) return ""; StringBuilder buffer=new StringBuilder(); for ( Integer i : src) { buffer.append(i.toString()).append(';'); } if (buffer.length() > 0) { buffer.setLength(buffer.length() - 1); } return buffer.toString(); }
Separates each field of the array by a semicolon
public void spritePause(boolean pause){ mSpriteSheet.setSpritePause(pause); }
indicates whether to start the SpriteAnimation paused.
public Point center(){ return rect.center; }
Get the center of the rectangle
@DataProvider(name="classProvider") public Object[][] classprovider(){ return TESTING_CLASSES; }
Provides classes to be tested.
private void stickyEventCommand(@NonNull MessageEvent messageEvent,@NonNull byte[] objectArray,@NonNull String className){ if (className.equals(String.class.getName())) { String action=new String(objectArray); Log.d(WearBusTools.BUSWEAR_TAG,"syncEvent action: " + action); if (action.equals(WearBusTools.ACTION_STICKY_CLEAR_ALL)) { removeAllStickyEventsLocal(); } else { Class classTmp=getClassForName(className); removeStickyEventLocal(classTmp); } } else { if (messageEvent.getPath().startsWith(WearBusTools.PREFIX_CLASS)) { Class classTmp=getClassForName(className); removeStickyEventLocal(classTmp); } else { Object obj=WearBusTools.getSendSimpleObject(objectArray,className); if (obj == null) { obj=findParcel(objectArray,className); } if (obj != null) { removeStickyEventLocal(obj); } } } }
Method used to find which command and if class/object is needed to retrieve it and call local method.
public ExtraProvider overrideImage(Uri image){ this.overriddenImage=image; return this; }
Provide a specific image for the linked package name.
@Override public Edge readEdge(final InputStream inputStream,final Function<Attachable<Edge>,Edge> edgeAttachMethod) throws IOException { throw Io.Exceptions.readerFormatIsForFullGraphSerializationOnly(this.getClass()); }
This method is not supported for this reader.
private void checkState(State st,String msg){ if (state != st) { throw new IllegalStateException(msg + " at " + st+ " state"); } }
Checks if the current state is the specified one.
@Override public boolean isActive(){ return amIActive; }
Used by the Whitebox GUI to tell if this plugin is still running.
public void spaceVertical(ArrayList<Integer> nodes){ if (m_bNeedsUndoAction) { addUndoAction(new spaceVerticalAction(nodes)); } int nMinY=-1; int nMaxY=-1; for (int iNode=0; iNode < nodes.size(); iNode++) { int nY=getPositionY(nodes.get(iNode)); if (nY < nMinY || iNode == 0) { nMinY=nY; } if (nY > nMaxY || iNode == 0) { nMaxY=nY; } } for (int iNode=0; iNode < nodes.size(); iNode++) { int nNode=nodes.get(iNode); m_nPositionY.set(nNode,(int)(nMinY + iNode * (nMaxY - nMinY) / (nodes.size() - 1.0))); } }
space out set of nodes evenly between top and bottom most node in the list
public void onCancelRealtimeBars(Contract contract){ if (m_realTimeBarsRequests.containsKey(contract.getId())) { synchronized (m_realTimeBarsRequests) { m_realTimeBarsRequests.remove(contract.getId()); } } }
Method onCancelRealtimeBars.
protected TEnumImpl(){ super(); }
<!-- begin-user-doc --> <!-- end-user-doc -->
public static String parseCharset(Map<String,String> headers){ String contentType=headers.get(HTTP.CONTENT_TYPE); if (contentType != null) { String[] params=contentType.split(";"); for (int i=1; i < params.length; i++) { String[] pair=params[i].trim().split("="); if (pair.length == 2) { if (pair[0].equals("charset")) { return pair[1]; } } } } return HTTP.DEFAULT_CONTENT_CHARSET; }
Returns the charset specified in the Content-Type of this header, or the HTTP default (ISO-8859-1) if none can be found.
public synchronized void clear(){ m_Results.clear(); m_Suffixes.clear(); m_Ordered.clear(); }
Empties the history.
protected byte[] computeSHAdigest(final byte[] value){ try { return MessageDigest.getInstance("SHA").digest(value); } catch ( Exception e) { throw new UnsupportedOperationException(e.toString()); } }
Returns the SHA-1 message digest of the given value.
public static Quantity toQuantity(final Supply supply,final int divisibility){ return new Quantity(supply.getRaw() * getMultipler(divisibility)); }
Converts a supply to a quantity.
public static int randGaussian(final int mean,final int sd){ return (int)(rand.nextGaussian() * sd + mean); }
Generates a normally distributed random number and rounds it.
public static long rotateLeft(long lng,int distance){ if (distance == 0) { return lng; } return ((lng << distance) | (lng >>> (-distance))); }
<p> Rotates the bits of <code>lng</code> to the left by the <code>distance</code> bits. </p>
public Picker quality(int minPixel,int maxPixel){ mSelectionSpec.setMinPixels(minPixel); mSelectionSpec.setMaxPixels(maxPixel); return this; }
Sets the limitation of a selectable image quality by pixel count within the specified range.
ValueImpl readValue(){ byte typeKey=readByte(); return readUntaggedValue(typeKey); }
Read a value, first byte describes type of value to read.
private void removeMapping(TreeStateNode node){ treePathMapping.remove(node.getTreePath()); }
Removes the mapping for a previously added node.
public Cookie(final String domain,final String name,final String value){ this(domain,name,value,null,null,false); }
Creates a cookie with the given name, value and domain attribute.
public static Short valueOf(String string,int radix) throws NumberFormatException { return valueOf(parseShort(string,radix)); }
Parses the specified string as a signed short value using the specified radix.
public synchronized UDAudio seekTo(Integer position){ if (position != null) { final MediaPlayer player=getMediaPlayer(); if (player != null) { try { player.seekTo(position); } catch ( Exception e) { e.printStackTrace(); } } } return this; }
seek to position
public boolean toOutline(){ int corners=vertices.size(); int maxSegs=corners * 3; List<Vec2D> newVerts=new ArrayList<Vec2D>(corners); Vec2D[] segments=new Vec2D[maxSegs]; Vec2D[] segEnds=new Vec2D[maxSegs]; float[] segAngles=new float[maxSegs]; Vec2D start=vertices.get(0).copy(); float lastAngle=MathUtils.PI; float a, b, c, d, e, f; double angleDif, bestAngleDif; int i, j=corners - 1, segs=0; if (corners > maxSegs) { return false; } for (i=0; i < corners; i++) { Vec2D pi=vertices.get(i); Vec2D pj=vertices.get(j); if (!pi.equals(pj)) { segments[segs]=pi; segEnds[segs++]=pj; } j=i; if (pi.y > start.y || (pi.y == start.y && pi.x < start.x)) { start.set(pi); } } if (segs == 0) { return false; } for (i=0; i < segs - 1; i++) { for (j=i + 1; j < segs; j++) { Line2D li=new Line2D(segments[i],segEnds[i]); Line2D lj=new Line2D(segments[j],segEnds[j]); LineIntersection isec=li.intersectLine(lj); if (isec.getType() == Type.INTERSECTING) { Vec2D ipos=isec.getPos(); if (!ipos.equals(segments[i]) && !ipos.equals(segEnds[i])) { if (segs == maxSegs) { return false; } segments[segs]=segments[i].copy(); segEnds[segs++]=ipos.copy(); segments[i]=ipos.copy(); } if (!ipos.equals(segments[j]) && !ipos.equals(segEnds[j])) { if (segs == maxSegs) { return false; } segments[segs]=segments[j].copy(); segEnds[segs++]=ipos.copy(); segments[j]=ipos.copy(); } } } } for (i=0; i < segs; i++) { segAngles[i]=segEnds[i].sub(segments[i]).positiveHeading(); } c=start.x; d=start.y; a=c - 1; b=d; e=0; f=0; newVerts.add(new Vec2D(c,d)); corners=1; while (true) { bestAngleDif=MathUtils.TWO_PI; for (i=0; i < segs; i++) { if (segments[i].x == c && segments[i].y == d && (segEnds[i].x != a || segEnds[i].y != b)) { angleDif=lastAngle - segAngles[i]; while (angleDif >= MathUtils.TWO_PI) { angleDif-=MathUtils.TWO_PI; } while (angleDif < 0) { angleDif+=MathUtils.TWO_PI; } if (angleDif < bestAngleDif) { bestAngleDif=angleDif; e=segEnds[i].x; f=segEnds[i].y; } } if (segEnds[i].x == c && segEnds[i].y == d && (segments[i].x != a || segments[i].y != b)) { angleDif=lastAngle - segAngles[i] + MathUtils.PI; while (angleDif >= MathUtils.TWO_PI) { angleDif-=MathUtils.TWO_PI; } while (angleDif < 0) { angleDif+=MathUtils.TWO_PI; } if (angleDif < bestAngleDif) { bestAngleDif=angleDif; e=segments[i].x; f=segments[i].y; } } } if (corners > 1 && c == newVerts.get(0).x && d == newVerts.get(0).y && e == newVerts.get(1).x && f == newVerts.get(1).y) { corners--; vertices=newVerts; return true; } if (bestAngleDif == MathUtils.TWO_PI || corners == maxSegs) { return false; } lastAngle-=bestAngleDif + MathUtils.PI; newVerts.add(new Vec2D(e,f)); corners++; a=c; b=d; c=e; d=f; } }
Attempts to remove all internal self-intersections and creates a new polygon only consisting of perimeter vertices. Ported from: http://alienryderflex.com/polygon_perimeter/
final String PrintVersion(String str){ StringBuffer buf=new StringBuffer(str.length()); for (int i=0; i < str.length(); i++) { switch (str.charAt(i)) { case '\"': buf.append("\\\""); break; case '\\': buf.append("\\\\"); break; case '\t': buf.append("\\t"); break; case '\n': buf.append("\\n"); break; case '\f': buf.append("\\f"); break; case '\r': buf.append("\\r"); break; default : buf.append(str.charAt(i)); break; } } ; return buf.toString(); }
toString() modified 23 Aug 2007 by LL to call PrintVersion so strings with special characters are printed properly.
public boolean isLeaf(){ if (below != null) { return false; } if (above != null) { return false; } return true; }
Determines if node is a leaf node (i.e., has no children).
public OutputDistribution(String var){ this.baseVar=var.replace("'",""); this.primes=var.replace(baseVar,""); inputRules=new ArrayList<AnchoredRule>(); }
Creates the output distribution for the output variable label
private static void processNotifications() throws Exception { try (final Statement statement=Database.INSTANCE.getListenerConnection().createStatement();final ResultSet result_set=statement.executeQuery(Config.INSTANCE.sql.getProperty("sql.jpgagent.dummy"))){ Config.INSTANCE.logger.debug("Kill jobs begin."); final PGConnection pg_connection=Database.INSTANCE.getListenerConnection().unwrap(PGConnection.class); final PGNotification notifications[]=pg_connection.getNotifications(); if (null != notifications) { for ( PGNotification notification : notifications) { if (notification.getName().equals("jpgagent_kill_job")) { int job_id=Integer.valueOf(notification.getParameter()); if (job_future_map.containsKey(job_id)) { Config.INSTANCE.logger.info("Killing job_id: {}.",job_id); job_future_map.get(job_id).cancel(true); } else { Config.INSTANCE.logger.info("Kill request for job_id: {} was submitted, but the job was not running.",job_id); } } } } } }
Processes notifications which may have been issued on channels that jpgAgent is listening on.
public ZipShort(byte[] bytes,int offset){ value=(bytes[offset + 1] << 8) & 0xFF00; value+=(bytes[offset] & 0xFF); }
Create instance from the two bytes starting at offset.
public static <T>T createRetrofitService(final Class<T> clazz,final String endPoint){ final RestAdapter restAdapter=new RestAdapter.Builder().setEndpoint(endPoint).build(); T service=restAdapter.create(clazz); return service; }
Creates a retrofit service from an arbitrary class (clazz)
public final boolean matchAction(String action){ return hasAction(action); }
Match this filter against an Intent's action. If the filter does not specify any actions, the match will always fail.
public static void renameFileReferencee(PsiElement element,String newPackageName){ if (element instanceof PerlNamespaceElement) { PerlPsiUtil.renameElement(element,newPackageName); } }
Renames file referencee element. Specific method required, cause somewhere we should put package name, and somewhere filename
private BakedBezierInterpolator(){ super(); }
Use getInstance instead of instantiating.
@Override public boolean equals(Object obj){ if (obj == this) { return true; } if (!(obj instanceof RC5ParameterSpec)) { return false; } RC5ParameterSpec ps=(RC5ParameterSpec)obj; return (version == ps.version) && (rounds == ps.rounds) && (wordSize == ps.wordSize)&& (Arrays.equals(iv,ps.iv)); }
Compares the specified object with this <code>RC5ParameterSpec</code> instance.
public static boolean isSameAnno(FeatureStructure aFirstFS,FeatureStructure aSeconFS){ for ( Feature f : getAllFeatures(aFirstFS)) { if (isBasicFeature(f)) { continue; } if (!isLinkMode(aFirstFS,f)) { try { FeatureStructure attachFs1=aFirstFS.getFeatureValue(f); FeatureStructure attachFs2=aSeconFS.getFeatureValue(f); if (!isSameAnno(attachFs1,attachFs2)) { return false; } } catch ( Exception e) { } if (getFeatureValue(aFirstFS,f) == null && getFeatureValue(aSeconFS,f) == null) { continue; } if (getFeatureValue(aFirstFS,f) == null && getFeatureValue(aSeconFS,f) != null) { return false; } if (getFeatureValue(aFirstFS,f) != null && getFeatureValue(aSeconFS,f) == null) { return false; } if (!getFeatureValue(aFirstFS,f).equals(getFeatureValue(aSeconFS,f))) { return false; } } } return true; }
Return true if these two annotations agree on every non slot features
ServerSessionContext registerIndexQuery(long index,Runnable query){ List<Runnable> queries=this.indexQueries.computeIfAbsent(index,null); queries.add(query); return this; }
Registers a session index query.
public <T extends Number & Comparable>NumberRange by(T stepSize){ return new NumberRange(NumberRange.comparableNumber((Number)from),NumberRange.comparableNumber((Number)to),stepSize,inclusive); }
Creates a new NumberRange with the same <code>from</code> and <code>to</code> as this IntRange but with a step size of <code>stepSize</code>.
public X509Name(String dirName){ this(DefaultReverse,DefaultLookUp,dirName); }
Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or some such, converting it into an ordered set of name attributes.
public boolean isAllowedToDelete(PlatformUser user){ if (user.equals(getPlatformUser())) { return true; } Organization org=getPlatformUser().getOrganization(); if (user.isOrganizationAdmin() && user.getOrganization().equals(org)) { return true; } return false; }
The given user is allowed to delete this review if the user is <ul> <li>the creator of the review</li> <li>a administrator of the organization which the creator belongs to</li> </ul>
public Rational(Rational R){ this.N=new Polynomial(R.N); this.D=new Polynomial(R.D); }
Constructs a new rational function by copying an existing rational function object.
@Override public void eUnset(int featureID){ switch (featureID) { case ImPackage.DELEGATING_GETTER_DECLARATION__DELEGATION_BASE_TYPE: setDelegationBaseType((SymbolTableEntryOriginal)null); return; case ImPackage.DELEGATING_GETTER_DECLARATION__DELEGATION_SUPER_CLASS_STEPS: setDelegationSuperClassSteps(DELEGATION_SUPER_CLASS_STEPS_EDEFAULT); return; case ImPackage.DELEGATING_GETTER_DECLARATION__DELEGATION_TARGET: setDelegationTarget((SymbolTableEntryOriginal)null); return; case ImPackage.DELEGATING_GETTER_DECLARATION__DELEGATION_TARGET_IS_ABSTRACT: setDelegationTargetIsAbstract(DELEGATION_TARGET_IS_ABSTRACT_EDEFAULT); return; } super.eUnset(featureID); }
<!-- begin-user-doc --> <!-- end-user-doc -->
private List<BigtableSource> splitIntoBundlesBasedOnSamples(long desiredBundleSizeBytes,List<SampleRowKeysResponse> sampleRowKeys){ if (sampleRowKeys.isEmpty()) { logger.info("Not splitting source {} because no sample row keys are available.",this); return Collections.singletonList(this); } logger.info("About to split into bundles of size {} with sampleRowKeys length {} first element {}",desiredBundleSizeBytes,sampleRowKeys.size(),sampleRowKeys.get(0)); ByteKey lastEndKey=ByteKey.EMPTY; long lastOffset=0; ImmutableList.Builder<BigtableSource> splits=ImmutableList.builder(); for ( SampleRowKeysResponse response : sampleRowKeys) { ByteKey responseEndKey=ByteKey.of(response.getRowKey()); long responseOffset=response.getOffsetBytes(); checkState(responseOffset >= lastOffset,"Expected response byte offset %s to come after the last offset %s",responseOffset,lastOffset); if (!range.overlaps(ByteKeyRange.of(lastEndKey,responseEndKey))) { lastOffset=responseOffset; lastEndKey=responseEndKey; continue; } ByteKey splitStartKey=lastEndKey; if (splitStartKey.compareTo(range.getStartKey()) < 0) { splitStartKey=range.getStartKey(); } ByteKey splitEndKey=responseEndKey; if (!range.containsKey(splitEndKey)) { splitEndKey=range.getEndKey(); } long sampleSizeBytes=responseOffset - lastOffset; List<BigtableSource> subSplits=splitKeyRangeIntoBundleSizedSubranges(sampleSizeBytes,desiredBundleSizeBytes,ByteKeyRange.of(splitStartKey,splitEndKey)); splits.addAll(subSplits); lastEndKey=responseEndKey; lastOffset=responseOffset; } if (!lastEndKey.isEmpty() && (range.getEndKey().isEmpty() || lastEndKey.compareTo(range.getEndKey()) < 0)) { splits.add(this.withStartKey(lastEndKey).withEndKey(range.getEndKey())); } List<BigtableSource> ret=splits.build(); logger.info("Generated {} splits. First split: {}",ret.size(),ret.get(0)); return ret; }
Helper that splits this source into bundles based on Cloud Bigtable sampled row keys.
public boolean isVerbose(){ return verbose; }
True iff verbose output should be printed.
public void runTest() throws Throwable { Document doc; Element element; String elementId="---"; doc=(Document)load("staffNS",false); element=doc.getElementById(elementId); assertNull("documentgetelementbyid01",element); }
Runs the test case.
private static void updateNetwork(WifiManager wifiManager,WifiConfiguration config){ Integer foundNetworkID=findNetworkInExistingConfig(wifiManager,config.SSID); if (foundNetworkID != null) { Log.i(TAG,"Removing old configuration for network " + config.SSID); wifiManager.removeNetwork(foundNetworkID); wifiManager.saveConfiguration(); } int networkId=wifiManager.addNetwork(config); if (networkId >= 0) { if (wifiManager.enableNetwork(networkId,true)) { Log.i(TAG,"Associating to network " + config.SSID); wifiManager.saveConfiguration(); } else { Log.w(TAG,"Failed to enable network " + config.SSID); } } else { Log.w(TAG,"Unable to add network " + config.SSID); } }
Update the network: either create a new network or modify an existing network
int queue(byte[] buffer,int offset,int len,boolean bCtrl){ int available_space; available_space=m_sbuf.getWriteRemaining(); if (len > available_space) { assert !bCtrl; len=available_space; } SSegment back=null; if (!m_slist.isEmpty()) { back=m_slist.get(m_slist.size() - 1); } if (back != null && (back.bCtrl == bCtrl) && (back.xmit == 0)) { back.len+=len; } else { long snd_buffered; snd_buffered=m_sbuf.getBuffered(); SSegment sseg=new SSegment(m_snd_una + snd_buffered,len,bCtrl); if (logger.isLoggable(Level.FINEST)) { logger.log(Level.FINEST,debugName + " enqueued send segment seq: " + sseg.seq+ " len: "+ sseg.len); } m_slist.add(sseg); } int written=m_sbuf.write(buffer,offset,len); return written; }
Enqueues data segment in the send buffer
private void populateMap(final AccessProfile accessProfile){ _logger.debug("Populating input attributes in the map."); _keyMap.put(VNXFileConstants.DEVICETYPE,accessProfile.getSystemType()); _keyMap.put(VNXFileConstants.DBCLIENT,_dbClient); _keyMap.put(VNXFileConstants.USERNAME,accessProfile.getUserName()); _keyMap.put(VNXFileConstants.USER_PASS_WORD,accessProfile.getPassword()); _keyMap.put(VNXFileConstants.URI,getServerUri(accessProfile)); _keyMap.put(VNXFileConstants.PORTNUMBER,accessProfile.getPortNumber()); _keyMap.put(Constants._Stats,new LinkedList<Stat>()); _keyMap.put(Constants.ACCESSPROFILE,accessProfile); _keyMap.put(Constants._serialID,accessProfile.getserialID()); _keyMap.put(Constants._nativeGUIDs,Sets.newHashSet()); _keyMap.put(VNXFileConstants.AUTHURI,getLoginUri(accessProfile)); String globalCacheKey=accessProfile.getserialID() + Constants._minusDelimiter + Constants._File; _keyMap.put(Constants._globalCacheKey,globalCacheKey); _keyMap.put(Constants.PROPS,accessProfile.getProps()); if (executor != null) { executor.setKeyMap(_keyMap); _logger.debug("Map set on executor...."); } }
Construct the map of input attributes which will be used during the execution and processing the result.
public static void dropTables(Connection conn){ try { Statement stmt=conn.createStatement(); try { stmt.execute("DROP TABLE Unpaidorder"); } catch ( SQLException ex) { } try { stmt.execute("DROP TABLE Customer"); } catch ( SQLException ex) { } try { stmt.execute("DROP TABLE Coffee"); } catch ( SQLException ex) { } } catch ( SQLException ex) { System.out.println("ERROR: " + ex.getMessage()); ex.printStackTrace(); } }
The dropTables method drops any existing in case the database already exists.
protected int mapDragOperationFromModifiers(MouseEvent e){ int mods=e.getModifiersEx(); int btns=mods & ButtonMask; if (!(btns == InputEvent.BUTTON1_DOWN_MASK || btns == InputEvent.BUTTON2_DOWN_MASK)) { return DnDConstants.ACTION_NONE; } return SunDragSourceContextPeer.convertModifiersToDropAction(mods,getSourceActions()); }
determine the drop action from the event
OutputStream saveUploadedFileDetails(final String name,final long size,final String mimeType,final SoftwareModule selectedSw){ File tempFile=null; try { tempFile=File.createTempFile("spUiArtifactUpload",null); @SuppressWarnings("squid:S2095") final OutputStream out=new FileOutputStream(tempFile); final String currentBaseSoftwareModuleKey=HawkbitCommonUtil.getFormattedNameVersion(selectedSw.getName(),selectedSw.getVersion()); final CustomFile customFile=new CustomFile(name,size,tempFile.getAbsolutePath(),selectedSw.getName(),selectedSw.getVersion(),mimeType); artifactUploadState.getFileSelected().add(customFile); processBtn.setEnabled(false); if (!artifactUploadState.getBaseSwModuleList().keySet().contains(currentBaseSoftwareModuleKey)) { artifactUploadState.getBaseSwModuleList().put(currentBaseSoftwareModuleKey,selectedSw); } return out; } catch ( final FileNotFoundException e) { LOG.error("Upload failed {}",e); throw new ArtifactUploadFailedException(i18n.get("message.file.not.found")); } catch ( final IOException e) { LOG.error("Upload failed {}",e); throw new ArtifactUploadFailedException(i18n.get("message.upload.failed")); } }
Save uploaded file details.
public static void main(String[] args){ try { Stemming.useStemmer(new IteratedLovinsStemmer(),args); } catch ( Exception e) { e.printStackTrace(); } }
Runs the stemmer with the given options
private StreamUtil(){ instanceNotAllowed(getClass()); }
Utility classes should not be instantiated.
public static boolean isLocalAssetUri(Uri uri){ final String scheme=getSchemeOrNull(uri); return LOCAL_ASSET_SCHEME.equals(scheme); }
Check if uri represents local asset
private boolean checkForIndex(File aIndexFolder){ File[] files=aIndexFolder.listFiles(); if (files == null) { return false; } boolean result=false; for ( File file : files) { if (file.isFile() && file.getName().startsWith("segments")) { result=true; break; } } return result; }
Checks if the folder is a Lucence index
public void unpair(BluetoothAdapter adapter,BluetoothDevice device){ int mask=PairReceiver.STATE_NONE_FLAG; long start=-1; String methodName=String.format("unpair(device=%s)",device); if (!adapter.isEnabled()) { fail(String.format("%s bluetooth not enabled",methodName)); } PairReceiver receiver=getPairReceiver(device,0,null,mask); int state=device.getBondState(); switch (state) { case BluetoothDevice.BOND_NONE: assertFalse(adapter.getBondedDevices().contains(device)); removeReceiver(receiver); return; case BluetoothDevice.BOND_BONDING: start=System.currentTimeMillis(); assertTrue(device.removeBond()); break; case BluetoothDevice.BOND_BONDED: assertTrue(adapter.getBondedDevices().contains(device)); start=System.currentTimeMillis(); assertTrue(device.removeBond()); break; default : removeReceiver(receiver); fail(String.format("%s invalid state: state=%d",methodName,state)); } long s=System.currentTimeMillis(); while (System.currentTimeMillis() - s < PAIR_UNPAIR_TIMEOUT) { if (device.getBondState() == BluetoothDevice.BOND_NONE && (receiver.getFiredFlags() & mask) == mask) { assertFalse(adapter.getBondedDevices().contains(device)); long finish=receiver.getCompletedTime(); if (start != -1 && finish != -1) { writeOutput(String.format("%s completed in %d ms",methodName,(finish - start))); } else { writeOutput(String.format("%s completed",methodName)); } removeReceiver(receiver); return; } } int firedFlags=receiver.getFiredFlags(); removeReceiver(receiver); fail(String.format("%s timeout: state=%d (expected %d), flags=0x%x (expected 0x%x)",methodName,state,BluetoothDevice.BOND_BONDED,firedFlags,mask)); }
Deletes a pairing with a remote device and checks to make sure that the devices are unpaired and that the correct actions were broadcast.
public boolean isBannedMethod(SootMethod m){ return banned_methods.contains(m); }
Used by the specification create to check if a method is legal to put in the spec. Must check the method, and all superclass definitions of the method.
public TextComponent(String text,BaseComponent... extras){ this.text=text; this.setExtra(Arrays.asList(extras)); }
Construct new TextComponent with given string and extra components.
public MemberCube(TClassifier tClassifier,MemberCollector memberCollector){ this.memberMatrixesByName=new HashMap<>(); addMembers(MemberMatrix.OWNED,tClassifier.getOwnedMembers()); if (tClassifier instanceof TClass) { addMembers(MemberMatrix.INHERITED,memberCollector.inheritedMembers((TClass)tClassifier)); } addMembers(MemberMatrix.IMPLEMENTED,memberCollector.membersOfImplementedInterfaces(tClassifier)); }
Creates the cube for the given classifier, using the passed member collector. The latter is passed as argument as it needed DI.
private void addMembers(List<String> newMembers){ if (newMembers.isEmpty()) { return; } int startIndex=-1; int endIndex=-1; for ( String name : newMembers) { Member member=new Member(name); member.setChangeListener(healthListener); memberMap.put(name,member); memberList.add(member); int index=memberList.indexOf(member); if (startIndex == -1) { startIndex=index; endIndex=index; } else { startIndex=Math.min(startIndex,index); endIndex=Math.max(endIndex,index); } } fireIntervalAdded(this,startIndex,endIndex); }
Add a group of new members.
public static void init(){ init("es"); }
loads the language files
public void delete(ScriptGroup group){ if (!currentTestPlan.getScriptGroups().remove(group)) { messages.warn("Could not remove Script Group " + group.getName() + "."); } else { messages.info("Script Group " + group.getName() + " has been removed."); } }
Deletes the script group from the workload. This does not persist the changes to the database.
@Override public URI toPropertyURI(final String property){ return toURI(property); }
Override to allow for colons in the id without URLEncoding them.
@POST @Consumes({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON}) @CheckPermission(roles={Role.TENANT_ADMIN},acls={ACL.OWN,ACL.ALL}) @Path("/{id}/restore") public TaskResourceRep restore(@PathParam("id") URI id,@QueryParam("syncDirection") String syncDirection){ ArgValidator.checkFieldUriType(id,BlockSnapshot.class,"id"); BlockSnapshot snapshot=(BlockSnapshot)queryResource(id); if (syncDirection != null) { validateSyncDirection(syncDirection); } Volume parentVolume=_permissionsHelper.getObjectById(snapshot.getParent(),Volume.class); checkForPendingTasks(Arrays.asList(parentVolume.getTenant().getURI()),Arrays.asList(parentVolume)); StorageSystem storage=_permissionsHelper.getObjectById(parentVolume.getStorageController(),StorageSystem.class); if (storage.checkIfVmax3()) { if (snapshot.getSettingsInstance() == null) { throw APIException.badRequests.snapshotNullSettingsInstance(snapshot.getLabel()); } } if (Type.openstack.name().equalsIgnoreCase(storage.getSystemType())) { throw APIException.methodNotAllowed.notSupportedWithReason(String.format("Snapshot restore is not possible on third-party storage systems")); } BlockServiceApi blockServiceApiImpl=BlockService.getBlockServiceImpl(parentVolume,_dbClient); blockServiceApiImpl.validateRestoreSnapshot(snapshot,parentVolume); String taskId=UUID.randomUUID().toString(); Operation op=new Operation(); op.setResourceType(ResourceOperationTypeEnum.RESTORE_VOLUME_SNAPSHOT); _dbClient.createTaskOpStatus(BlockSnapshot.class,snapshot.getId(),taskId,op); snapshot.getOpStatus().put(taskId,op); blockServiceApiImpl.restoreSnapshot(snapshot,parentVolume,syncDirection,taskId); auditOp(OperationTypeEnum.RESTORE_VOLUME_SNAPSHOT,true,AuditLogManager.AUDITOP_BEGIN,id.toString(),parentVolume.getId().toString(),snapshot.getStorageController().toString()); return toTask(snapshot,taskId,op); }
Call will restore this snapshot to the volume that it is associated with. If this snapshot was created from a volume in a consistency group, then all related snapshots will be restored to their respective volumes.
public void testMultivariateTEforCoupledDataFromFile() throws Exception { ArrayFileReader afr=new ArrayFileReader("demos/data/4ColsPairedOneStepNoisyDependence-1.txt"); double[][] data=afr.getDouble2DMatrix(); double[] col0=MatrixUtils.selectColumn(data,0); double[] col1=MatrixUtils.selectColumn(data,1); double[] col2=MatrixUtils.selectColumn(data,2); double[] col3=MatrixUtils.selectColumn(data,3); col0=MatrixUtils.normaliseIntoNewArray(col0); col1=MatrixUtils.normaliseIntoNewArray(col1); col2=MatrixUtils.normaliseIntoNewArray(col2); col3=MatrixUtils.normaliseIntoNewArray(col3); int kNNs=4; double expectedFromTRENTOOL0to2=0.1400645; double expectedFromTRENTOOL2to0=-0.0181459; double expectedFromTRENTOOL1to3=0.1639186; double expectedFromTRENTOOL3to1=0.0036976; TransferEntropyCalculatorKraskov teCalc=new TransferEntropyCalculatorKraskov(); teCalc.setProperty(ConditionalMutualInfoCalculatorMultiVariateKraskov.PROP_K,Integer.toString(kNNs)); teCalc.setProperty(ConditionalMutualInfoCalculatorMultiVariateKraskov.PROP_NORMALISE,"false"); teCalc.setProperty(ConditionalMutualInfoCalculatorMultiVariateKraskov.PROP_ADD_NOISE,"0"); System.out.println("Kraskov Cond MI as TE - multivariate coupled data 1, k=2,l=2"); System.out.println(" (0->2)"); teCalc.initialise(2,1,2,1,1); teCalc.setObservations(col0,col2); double result=teCalc.computeAverageLocalOfObservations(); System.out.printf(" %.5f\n",result); assertEquals(expectedFromTRENTOOL0to2,result,0.000001); System.out.println(" (2->0):"); teCalc.initialise(2,1,2,1,1); teCalc.setObservations(col2,col0); result=teCalc.computeAverageLocalOfObservations(); System.out.printf(" %.5f\n",result); assertEquals(expectedFromTRENTOOL2to0,result,0.000001); System.out.println(" (1->3):"); teCalc.initialise(2,1,2,1,1); teCalc.setObservations(col1,col3); result=teCalc.computeAverageLocalOfObservations(); System.out.printf(" %.5f\n",result); assertEquals(expectedFromTRENTOOL1to3,result,0.000001); System.out.println(" (3->1):"); teCalc.initialise(2,1,2,1,1); teCalc.setObservations(col3,col1); result=teCalc.computeAverageLocalOfObservations(); System.out.printf(" %.5f\n",result); assertEquals(expectedFromTRENTOOL3to1,result,0.000001); double expectedFromTRENTOOL0to1_k1l1=0.0072169; double expectedFromTRENTOOL1to2_k1l1=0.0011738; System.out.println(" (0->1) but with k=1,l=1:"); teCalc.initialise(1,1,1,1,1); teCalc.setObservations(col0,col1); result=teCalc.computeAverageLocalOfObservations(); System.out.printf(" %.5f\n",result); assertEquals(expectedFromTRENTOOL0to1_k1l1,result,0.000001); System.out.println(" (1->2) but with k=1,l=1:"); teCalc.initialise(1,1,1,1,1); teCalc.setObservations(col1,col2); result=teCalc.computeAverageLocalOfObservations(); System.out.printf(" %.5f\n",result); assertEquals(expectedFromTRENTOOL1to2_k1l1,result,0.000001); }
Test the computed multivariate TE against that calculated by Wibral et al.'s TRENTOOL on the same data. It's multivariate because we use embedding dimension 2 on both source and destination. To run TRENTOOL (http://www.trentool.de/) for this data, run its TEvalues.m matlab script on the multivariate source and dest data sets as: TEvalues(source, dest, 2, 1, 1, kraskovK, 0) with these values ensuring source-dest lag 1, history k=2, history embedding dimension l=2 on source as well. embedding lag 1, no dynamic correlation exclusion
public Set<String> addContent(String variable,Value value){ if (!paused) { curState.addToState(new Assignment(variable,value)); return update(); } else { log.info("system is paused, ignoring " + variable + "="+ value); return Collections.emptySet(); } }
Adds the content (expressed as a pair of variable=value) to the current dialogue state, and subsequently updates the dialogue state.
public void testGetSpeed_one(){ testSpeed(1,1); }
Tests when the slow speed and the normal speed are both one.