code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
public Counter<String> generateTags(String[] doc,int n,StringBuilder explain){
Map<String,Double> p=new Hashtable<String,Double>();
Map<String,Double> prwd=new Hashtable<String,Double>();
Counter<String> nwd=new Counter<String>();
for ( String w : doc) {
nwd.inc(w,1);
}
for ( Entry<String,Long> e : nwd) {
if (!ntw.columns().contains(e.getKey())) continue;
double prw=prw(e.getKey());
prwd.put(e.getKey(),e.getValue() * prw);
}
Counter<String> tags=nwd;
tags.clear();
boolean warned=true;
for (int i=0; i < n; i++) {
String reason=sample(prwd);
if (reason == null) {
if (warned == false) LOG.info("reason == null, prwd.size()=" + prwd.size() + " doc.length="+ doc.length);
warned=true;
continue;
}
p.clear();
for ( String tag : ntw.rows(reason)) {
p.put(tag,ptr(tag,reason));
}
if (p.size() > 0) {
String tag=sample(p);
tags.inc(tag,1);
if (explain != null) {
explain.append("from " + reason + " => "+ tag+ "<br>");
}
}
}
return tags;
}
| Generate a tag according to TAM's generative process. We do not generate via NOISE. |
public static X509Certificate loadCertificate(String asciiCrt) throws CertificateParsingException {
return loadCertificate(new ByteArrayInputStream(asciiCrt.getBytes(US_ASCII)));
}
| Loads an ASCII-armored public X.509 certificate. |
public static String toSQLName(Class<?> table){
if (table.isAnnotationPresent(Table.class)) {
Table annotation=table.getAnnotation(Table.class);
if ("".equals(annotation.name())) {
return NamingHelper.toSQLNameDefault(table.getSimpleName());
}
return annotation.name();
}
return NamingHelper.toSQLNameDefault(table.getSimpleName());
}
| Maps a Java Class to the name of the class. |
private boolean conditionM0(String value,int index){
if (charAt(value,index + 1) == 'M') {
return true;
}
return contains(value,index - 1,3,"UMB") && ((index + 1) == value.length() - 1 || contains(value,index + 2,2,"ER"));
}
| Complex condition 0 for 'M' |
private final int inCache(final long index){
if (index >= this.cacheindex && index < this.cacheindex + this.cachecount) {
return (int)(index - this.cacheindex);
}
return -1;
}
| checks if the index is inside the cache |
@SuppressWarnings("unchecked") public int partition(int left,int right,int pivotIndex){
Comparable<E> pivot=ar[pivotIndex];
Comparable<E> tmp;
tmp=ar[right];
ar[right]=ar[pivotIndex];
ar[pivotIndex]=tmp;
int store=left;
for (int idx=left; idx < right; idx++) {
if (ar[idx].compareTo((E)pivot) <= 0) {
tmp=ar[idx];
ar[idx]=ar[store];
ar[store]=tmp;
store++;
}
}
tmp=ar[right];
ar[right]=ar[store];
ar[store]=tmp;
return store;
}
| In linear time, group an array into two parts, those less than a certain value (left), and those greater than or equal to a certain value (right). |
Set<Pair<String,String>> resolveCacheNames(final String entityOperation,final String entityName){
final Map<String,Set<Pair<String,String>>> entOperations=this.entityOperationCache.get(entityName);
if (entOperations != null) {
return entOperations.get(entityOperation);
}
return null;
}
| Resolve caches names for invalidation for given entity and operation. |
@Override public boolean isActive(){
return amIActive;
}
| Used by the Whitebox GUI to tell if this plugin is still running. |
@Override public Object clone() throws CloneNotSupportedException {
DefaultXYZDataset clone=(DefaultXYZDataset)super.clone();
clone.seriesKeys=new java.util.ArrayList(this.seriesKeys);
clone.seriesList=new ArrayList(this.seriesList.size());
for (int i=0; i < this.seriesList.size(); i++) {
double[][] data=(double[][])this.seriesList.get(i);
double[] x=data[0];
double[] y=data[1];
double[] z=data[2];
double[] xx=new double[x.length];
double[] yy=new double[y.length];
double[] zz=new double[z.length];
System.arraycopy(x,0,xx,0,x.length);
System.arraycopy(y,0,yy,0,y.length);
System.arraycopy(z,0,zz,0,z.length);
clone.seriesList.add(i,new double[][]{xx,yy,zz});
}
return clone;
}
| Creates an independent copy of this dataset. |
public boolean isStateActive(State state){
switch (state) {
case main_region_B:
return stateVector[0] == State.main_region_B;
case main_region_C:
return stateVector[0] == State.main_region_C;
case main_region_D:
return stateVector[0] == State.main_region_D;
case main_region_A:
return stateVector[0] == State.main_region_A;
default :
return false;
}
}
| Returns true if the given state is currently active otherwise false. |
public boolean isEnabled(){
return enabled;
}
| Ruft den Wert der enabled-Eigenschaft ab. |
protected Node newNode(){
return new SVGOMSwitchElement();
}
| Returns a new uninitialized instance of this object's class. |
public Mono<T> mono(String key,Executor ex){
return Mono.fromFuture(pipes.oneOrErrorAsync(key,ex).getFuture());
}
| Asynchronously extract a single data point from the named Queue. |
public void doPrepare(){
synchronized (LAYERWORKER_LOCK) {
if (layerWorkerQueue) {
return;
}
ISwingWorker<OMGraphicList> currentLayerWorker=layerWorker;
if (currentLayerWorker != null) {
layerWorkerQueue=true;
if (interruptable) {
currentLayerWorker.interrupt();
}
return;
}
setLayerWorker(createLayerWorker());
}
}
| A method that will launch a LayerWorker thread to call the prepare method. This method will set in motion all the steps needed to create and render the current OMGraphicList with the current projection. Nothing more needs to be called, because the LayerWorker will be started, it will call prepare(). Inside the prepare() method, the OMGraphicList should be created and the OMGraphics generated for the current projection that can be picked up in the getProjection() method, and the LayerWorker will call workerComplete() which will call repaint() on this layer. |
public static <K,V>Map<K,V> requireKeys(Map<K,V> map,K requiredKeyA,K requiredKeyB){
requireKeys(map,requiredKeyA);
requireKeys(map,requiredKeyB);
return map;
}
| Checks if the provided map contains all the provided required key(s). |
private void updateProgress(String progressLabel,int progress){
if (myHost != null && ((progress != previousProgress) || (!progressLabel.equals(previousProgressLabel)))) {
myHost.updateProgress(progressLabel,progress);
}
previousProgress=progress;
previousProgressLabel=progressLabel;
}
| Used to communicate a progress update between a plugin tool and the main Whitebox user interface. |
public Option(String description,String name,int numArguments,String synopsis){
m_Description=description;
m_Name=name;
m_NumArguments=numArguments;
m_Synopsis=synopsis;
}
| Creates new option with the given parameters. |
@Override public String toString(){
NumberFormat numberFormatter=NumberFormat.getNumberInstance();
numberFormatter.setMaximumFractionDigits(0);
numberFormatter.setMinimumIntegerDigits(2);
StringBuffer buffer=new StringBuffer();
buffer.append("base calendar: [");
if (getBaseCalendar() != null) {
buffer.append(getBaseCalendar().toString());
}
else {
buffer.append("null");
}
buffer.append("], time range: '");
buffer.append(numberFormatter.format(rangeStartingHourOfDay));
buffer.append(":");
buffer.append(numberFormatter.format(rangeStartingMinute));
buffer.append(":");
buffer.append(numberFormatter.format(rangeStartingSecond));
buffer.append(":");
numberFormatter.setMinimumIntegerDigits(3);
buffer.append(numberFormatter.format(rangeStartingMillis));
numberFormatter.setMinimumIntegerDigits(2);
buffer.append(" - ");
buffer.append(numberFormatter.format(rangeEndingHourOfDay));
buffer.append(":");
buffer.append(numberFormatter.format(rangeEndingMinute));
buffer.append(":");
buffer.append(numberFormatter.format(rangeEndingSecond));
buffer.append(":");
numberFormatter.setMinimumIntegerDigits(3);
buffer.append(numberFormatter.format(rangeEndingMillis));
buffer.append("', inverted: " + invertTimeRange + "]");
return buffer.toString();
}
| Returns a string representing the properties of the <CODE>DailyCalendar</CODE> |
@DSSink({DSSinkKind.SMS_MMS}) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:58:28.775 -0500",hash_original_method="5C5D2075C67DB185E1C8FAD979C1C6EE",hash_generated_method="82AFFDC08ABE282C4377A87122DA1464") public boolean copyMessageToIccEf(int status,byte[] pdu,byte[] smsc){
if (DBG) log("copyMessageToIccEf: status=" + status + " ==> "+ "pdu=("+ Arrays.toString(pdu)+ "), smsm=("+ Arrays.toString(smsc)+ ")");
enforceReceiveAndSend("Copying message to SIM");
synchronized (mLock) {
mSuccess=false;
Message response=mHandler.obtainMessage(EVENT_UPDATE_DONE);
mPhone.mCM.writeSmsToSim(status,IccUtils.bytesToHexString(smsc),IccUtils.bytesToHexString(pdu),response);
try {
mLock.wait();
}
catch ( InterruptedException e) {
log("interrupted while trying to update by index");
}
}
return mSuccess;
}
| Copy a raw SMS PDU to the SIM. |
public RollCommand(Server server){
super(server,"roll","Rolls some dice. Usage: /roll [XdY]");
}
| Creates new RollCommand |
public static double angle(Geo p0,Geo p1,Geo p2){
return Math.PI - p0.cross(p1).distance(p1.cross(p2));
}
| Given 3 points on a sphere, p0, p1, p2, return the angle between them in radians. |
public DrawerBuilder withStatusBarColor(@ColorInt int statusBarColor){
this.mStatusBarColor=statusBarColor;
return this;
}
| Set the statusBarColor color for this activity |
public static void main(final String[] args){
DOMTestCase.doMain(hc_attrinsertbefore1.class,args);
}
| Runs this test from the command line. |
public MultiDimIntTable(int[] dims){
reset(dims);
}
| Constructs a new multidimensional table of integer cells, with the given (fixed) dimensions. Each dimension must be an integer greater than zero. |
public static void dropTable(SQLiteDatabase db,boolean ifExists){
String sql="DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\"PARENT\"";
db.execSQL(sql);
}
| Drops the underlying database table. |
@Override public boolean isEnabled(){
return false;
}
| Flag to test if this Authenticator is enabled |
@MainThread public void start(){
mRestartOnDisconnect=true;
if (mThread != null) {
return;
}
Log.d(TAG,"Starting socket notification client");
mThread=new SocketThread();
mThread.start();
}
| Starts and connects the client. After this call any received socket push will be broadcast as a local broadcast. |
public static byte[] toRawSignatureBytes(BigInteger[] rs) throws IOException {
ByteArrayOutputStream bos=new ByteArrayOutputStream(64);
byte[] r=toUnsignedByteArray(rs[0]);
byte[] s=toUnsignedByteArray(rs[1]);
bos.write(r);
bos.write(s);
return bos.toByteArray();
}
| From Big Integers r,s to byte[] UAF_ALG_SIGN_SECP256K1_ECDSA_SHA256_RAW 0x05 An ECDSA signature on the secp256k1 curve which must have raw R and S buffers, encoded in big-endian order. I.e.[R (32 bytes), S (32 bytes)] |
private static ValueLob createBlob(InputStream in,long length){
try {
long remaining=Long.MAX_VALUE;
if (length >= 0 && length < remaining) {
remaining=length;
}
int len=getBufferSize(remaining);
byte[] buff;
if (len >= Integer.MAX_VALUE) {
buff=IOUtils.readBytesAndClose(in,-1);
len=buff.length;
}
else {
buff=DataUtils.newBytes(len);
len=IOUtils.readFully(in,buff,len);
}
if (len <= getMaxLengthInplaceLob()) {
byte[] small=DataUtils.newBytes(len);
System.arraycopy(buff,0,small,0,len);
return ValueLob.createSmallLob(Value.BLOB,small);
}
ValueLob lob=new ValueLob(Value.BLOB,null);
lob.createFromStream(buff,len,in,remaining);
return lob;
}
catch ( IOException e) {
throw DbException.convertIOException(e,null);
}
}
| Create a BLOB value from a stream. |
private static boolean isBeforeDot(String src,int index){
int ch;
int cc;
int len=src.length();
for (int i=index + Character.charCount(src.codePointAt(index)); i < len; i+=Character.charCount(ch)) {
ch=src.codePointAt(i);
if (ch == '\u0307') {
return true;
}
else {
cc=Normalizer.getCombiningClass(ch);
if ((cc == 0) || (cc == COMBINING_CLASS_ABOVE)) {
return false;
}
}
}
return false;
}
| Implements the "Before_Dot" condition Specification: C is followed by <code>U+0307 COMBINING DOT ABOVE</code>. Any sequence of characters with a combining class that is neither 0 nor 230 may intervene between the current character and the combining dot above. Regular Expression: After C: ([{cc!=230}&{cc!=0}])*[\u0307] |
public ConcurrentSkipListSet(Comparator<? super E> comparator){
m=new ConcurrentSkipListMap<E,Object>(comparator);
}
| Constructs a new, empty set that orders its elements according to the specified comparator. |
public static MigrationRestRep map(final Migration from){
if (from == null) {
return null;
}
MigrationRestRep to=new MigrationRestRep();
DbObjectMapper.mapDataObjectFields(from,to);
to.setVolume(DbObjectMapper.toRelatedResource(ResourceTypeEnum.VOLUME,from.getVolume()));
to.setSource(DbObjectMapper.toRelatedResource(ResourceTypeEnum.VOLUME,from.getSource()));
to.setTarget(DbObjectMapper.toRelatedResource(ResourceTypeEnum.VOLUME,from.getTarget()));
to.setStartTime(from.getStartTime());
to.setPercentageDone(from.getPercentDone());
to.setStatus(from.getMigrationStatus());
return to;
}
| Maps the passed migration instance to its corresponding REST response. |
public static void multiplyMV(float[] output,int outputOffset,float[] lhs,int lhsOffset,float[] rhs,int rhsOffset){
output[outputOffset + 0]=lhs[lhsOffset + 0] * rhs[rhsOffset + 0] + lhs[lhsOffset + 4] * rhs[rhsOffset + 1] + lhs[lhsOffset + 8] * rhs[rhsOffset + 2] + lhs[lhsOffset + 12] * rhs[rhsOffset + 3];
output[outputOffset + 1]=lhs[lhsOffset + 1] * rhs[rhsOffset + 0] + lhs[lhsOffset + 5] * rhs[rhsOffset + 1] + lhs[lhsOffset + 9] * rhs[rhsOffset + 2] + lhs[lhsOffset + 13] * rhs[rhsOffset + 3];
output[outputOffset + 2]=lhs[lhsOffset + 2] * rhs[rhsOffset + 0] + lhs[lhsOffset + 6] * rhs[rhsOffset + 1] + lhs[lhsOffset + 10] * rhs[rhsOffset + 2] + lhs[lhsOffset + 14] * rhs[rhsOffset + 3];
output[outputOffset + 3]=lhs[lhsOffset + 3] * rhs[rhsOffset + 0] + lhs[lhsOffset + 7] * rhs[rhsOffset + 1] + lhs[lhsOffset + 11] * rhs[rhsOffset + 2] + lhs[lhsOffset + 15] * rhs[rhsOffset + 3];
}
| Multiply a 4 element vector by a 4x4 matrix and store the result in a 4 element column vector. In matrix notation: result = lhs x rhs The same float array may be passed for resultVec, lhsMat, and/or rhsVec. However, the resultVec element values are undefined if the resultVec elements overlap either the lhsMat or rhsVec elements. |
public static final boolean shouldLogSlowQuery(long elapsedTimeMillis){
int slowQueryMillis=10000;
return slowQueryMillis >= 0 && elapsedTimeMillis >= slowQueryMillis;
}
| Determines whether a query should be logged. Reads the "db.log.slow_query_threshold" system property, which can be changed by the user at any time. If the value is zero, then all queries will be considered slow. If the value does not exist or is negative, then no queries will be considered slow. This value can be changed dynamically while the system is running. For example, "adb shell setprop db.log.slow_query_threshold 200" will log all queries that take 200ms or longer to run. |
public static Bitmap imageWithText(Context context,Bitmap bitmap,GenerateParams params){
TextView view=new TextView(context);
view.setText(params.text);
view.setTextColor(params.color);
view.setBackgroundColor(params.background);
view.setTypeface(null,Typeface.BOLD);
view.setGravity(Gravity.CENTER);
view.setTextSize(20);
Canvas canvas=new Canvas(bitmap);
view.measure(makeMeasureSpec(canvas.getWidth(),EXACTLY),makeMeasureSpec(canvas.getHeight(),EXACTLY));
view.layout(0,0,canvas.getWidth(),canvas.getHeight());
view.draw(canvas);
return bitmap;
}
| OP's original implementation fixed for real centering |
public double computeAverageActiveInfoStorageOfObservations(){
double active=0.0;
double activeCont=0.0;
for (int nextVal=0; nextVal < base; nextVal++) {
double p_next=(double)nextCount[nextVal] / (double)observations;
for (int prevVal=0; prevVal < base_power_k; prevVal++) {
if (nextPastCount[nextVal][prevVal] != 0) {
double logTerm=(double)nextPastCount[nextVal][prevVal] / (double)pastCount[prevVal] / p_next;
double localValue=Math.log(logTerm) / log_2;
activeCont=(nextPastCount[nextVal][prevVal] / (double)observations) * localValue;
}
else {
activeCont=0.0;
}
active+=activeCont;
}
}
return active;
}
| Returns the average active information storage from the observed values which have been passed in previously. |
public IBEA(Problem problem,NondominatedPopulation archive,Initialization initialization,Variation variation,IndicatorFitnessEvaluator fitnessEvaluator){
super(problem,new Population(),archive,initialization);
this.variation=variation;
this.fitnessEvaluator=fitnessEvaluator;
fitnessComparator=new FitnessComparator(fitnessEvaluator.areLargerValuesPreferred());
selection=new TournamentSelection(fitnessComparator);
}
| Constructs a new IBEA instance. |
public static Geometry[] toGeometryArray(Collection geometries){
if (geometries == null) return null;
Geometry[] geometryArray=new Geometry[geometries.size()];
return (Geometry[])geometries.toArray(geometryArray);
}
| Converts the <code>List</code> to an array. |
public String toString(){
return new String(super.toString() + " with current value: " + getStateLabel(getValue()));
}
| Provides a string representation of the control |
public static boolean isFedora(){
getLinuxRelease();
return linuxRelease != null && linuxRelease.contains("Fedora");
}
| Returns whether the output of <code>cat /etc/redhat-release/code> shell command contains "Fedora" |
public T userId(String value){
setString(USER_ID,value);
return (T)this;
}
| <div class="ind"> <strong> Optional. </strong> <p>This is intended to be a known identifier for a user provided by the site owner/tracking library user. It may not itself be PII. The value should never be persisted in GA cookies or other Analytics provided storage.</p> <table> <tbody><tr> <th>Parameter</th> <th>Value Type</th> <th>Default Value</th> <th>Max Length</th> <th>Supported Hit Types</th> </tr> <tr> <td><code>uid</code></td> <td>text</td> <td><span class="none">None</span> </td> <td><span class="none">None</span> </td> <td>all</td> </tr> </tbody></table> <div> Example value: <code>as8eknlll</code><br> Example usage: <code>uid=as8eknlll</code> </div> </div> |
public static boolean isStopword(String str){
return m_Stopwords.is(str.toLowerCase());
}
| Returns true if the given string is a stop word. |
public void clearSurface(SurfaceHolder surfaceHolder){
if (surfaceHolder == null) {
throw new IllegalArgumentException("Invalid surface holder");
}
final Surface surface=surfaceHolder.getSurface();
if (surface == null) {
throw new IllegalArgumentException("Surface could not be retrieved from surface holder");
}
if (surface.isValid() == false) {
throw new IllegalStateException("Surface is not valid");
}
if (mMANativeHelper != null) {
mMANativeHelper.clearPreviewSurface(surface);
}
else {
Log.w(TAG,"Native helper was not ready!");
}
}
| Clears the preview surface |
public static void sendCurrentWarning(Object source,Throwable e){
WarningSystem warning=getCurrent();
if (warning != null) warning.sendWarning(source,e);
else {
e.printStackTrace();
log.log(Level.WARNING,e.toString(),e);
}
}
| Sends a warning to the current service. |
public void removeLoader(EditToolLoader loader){
String[] classnames=loader.getEditableClasses();
if (classnames != null) {
for (int i=0; i < classnames.length; i++) {
EditToolLoader etl=(EditToolLoader)loaders.get(classnames[i].intern());
if (etl == loader) {
loaders.remove(classnames[i]);
}
else {
if (DEBUG) {
Debug.output("DrawingTool.removeLoader: loader to be removed isn't the current loader for " + classnames[i] + ", ignored.");
}
}
}
rawLoaders.remove(loader);
firePropertyChange(LoadersProperty,null,rawLoaders);
possibleEditableClasses=null;
}
}
| Remove an EditToolLoader from the Hashtable of loaders that the OMDrawingTool can use to create/modify OMGraphics. |
public void reportSuccess(long waitTime){
mSumOfWaitTime+=waitTime;
mSuccessfulRequests++;
}
| Called whenever image request finishes successfully, that is whenever final image is set. |
public static boolean deleteFiles(File directory){
boolean result=true;
if (directory.isDirectory()) {
File[] list=directory.listFiles();
for (int i=list.length; i-- > 0; ) {
File file=list[i];
if (file.isFile()) {
result=result && file.delete();
}
}
}
return result;
}
| Deletes all files and directories in the specified directory. Nothing happens when the specified File is not a directory. |
private static void initializeComponents(){
frame.setTitle("LGoodDatePicker Independent Calendar Panel Demo " + InternalUtilities.getProjectVersionString());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
JPanel mainPanel=new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel,BoxLayout.Y_AXIS));
frame.getContentPane().add(mainPanel);
container.setLayout(new GridBagLayout());
mainPanel.add(informationLabel);
mainPanel.add(new JLabel(" "));
mainPanel.add(new JLabel(" "));
mainPanel.add(container);
informationLabel.setOpaque(true);
informationLabel.setBackground(Color.white);
informationLabel.setBorder(new CompoundBorder(new LineBorder(Color.black),new EmptyBorder(2,4,2,4)));
informationLabel.setText("The selected date will be displayed here.");
informationLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
frame.pack();
frame.validate();
frame.setSize(640,480);
frame.setLocationRelativeTo(null);
}
| initializeComponents, This will set up our form, panels, and the layout managers. Most of this code only exists to make the demo program look pretty. |
protected boolean isMapKey(){
return false;
}
| Thrift maps are made up of name value pairs, are we parsing a thrift map name (e.g. left hand side of a map entry) here? |
protected void onBeforeClusterItemRendered(T item,MarkerOptions markerOptions){
}
| Called before the marker for a ClusterItem is added to the map. |
@DSSink({DSSinkKind.SENSITIVE_UNCATEGORIZED}) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 13:02:20.772 -0500",hash_original_method="778ABE3A69AA8FF60B65094F75FB879B",hash_generated_method="D1720953CA111AD0C30DE369B4C6B058") public static byte[] readFullyNoClose(InputStream in) throws IOException {
ByteArrayOutputStream bytes=new ByteArrayOutputStream();
byte[] buffer=new byte[1024];
int count;
while ((count=in.read(buffer)) != -1) {
bytes.write(buffer,0,count);
}
return bytes.toByteArray();
}
| Returns a byte[] containing the remainder of 'in'. |
public LocalTime withMillisOfDay(int millis){
return withLocalMillis(getChronology().millisOfDay().set(getLocalMillis(),millis));
}
| Returns a copy of this time with the millis of day field updated. <p> LocalTime is immutable, so there are no set methods. Instead, this method returns a new instance with the value of millis of day changed. |
private void usageError(String errorMsg) throws AdeUsageException {
System.out.flush();
System.err.println("Usage:");
System.err.println("\tVerifyLinuxTraining <analysis_group> <start date> <end date> ");
System.err.println();
System.err.println("Determines if the date range includes sufficient methods to allow training for the analysis group");
System.err.println();
System.err.flush();
throw new AdeUsageException(errorMsg);
}
| Output error related to the invocation of VerifyLinuxTraining |
public void releaseTargetVersionLock(){
_coordinator.releaseTargetVersionLock();
}
| calls coordinator client to release a target version lock. |
public static long copyLarge(InputStream input,OutputStream output,final long inputOffset,final long length,byte[] buffer) throws IOException {
if (inputOffset > 0) {
skipFully(input,inputOffset);
}
if (length == 0) {
return 0;
}
final int bufferLength=buffer.length;
int bytesToRead=bufferLength;
if (length > 0 && length < bufferLength) {
bytesToRead=(int)length;
}
int read;
long totalRead=0;
while (bytesToRead > 0 && EOF != (read=input.read(buffer,0,bytesToRead))) {
output.write(buffer,0,read);
totalRead+=read;
if (length > 0) {
bytesToRead=(int)Math.min(length - totalRead,bufferLength);
}
}
return totalRead;
}
| Copy some or all bytes from a large (over 2GB) <code>InputStream</code> to an <code>OutputStream</code>, optionally skipping input bytes. <p> This method uses the provided buffer, so there is no need to use a <code>BufferedInputStream</code>. <p> |
public FilteredTollHandler(final double simulationEndTime,final int numberOfTimeBins,final String userGroup){
this(simulationEndTime,numberOfTimeBins,null,null,userGroup);
LOGGER.info("Usergroup filtering is used, result will include all links but persons from given user group only.");
LOGGER.warn("User group will be identified for Munich scenario only, i.e. Urban, (Rev)Commuter and Freight.");
}
| User group filtering will be used, result will include all links but persons from given user group only. |
@Deprecated public static boolean isIdentical(OfflinePlayer player,OfflinePlayer compareTo){
return areIdentical(player,compareTo);
}
| Returns whether the ident of two offline players are identical |
private void readTextPropertiesElement(IXMLElement elem,HashMap<AttributeKey,Object> a) throws IOException {
}
| Reads a <style:text-properties> element from the specified XML element. <p> The properties described in this section can be contained within text styles (see section 14.8.1), but also within other styles, like paragraph styles (see section 14.8.2) or cell styles (see section 14.12.4) They are contained in a <style:text-properties> element. |
private void sendPatchToIncrementImageReplicatedCount(final State current){
try {
ImageService.DatastoreCountRequest requestBody=constructDatastoreCountRequest(1);
sendRequest(((CloudStoreHelperProvider)getHost()).getCloudStoreHelper().createPatch(ImageServiceFactory.SELF_LINK + "/" + current.image).setBody(requestBody).setCompletion(null));
}
catch ( Exception e) {
ServiceUtils.logSevere(this,"Exception thrown while sending patch to image service to increment count: %s",e);
}
}
| Sends patch to update replicatedDatastore in image cloud store entity. |
public IpcSharedMemoryInitResponse(Exception err){
this.err=err;
}
| Constructs an error response. |
private void createSubFamilySignatures(String dirName,Map<String,String> familyIdFamilyNameMap,SignatureLibraryRelease release) throws IOException {
for ( Resource modelFile : modelFiles) {
File subFamilyDir=new File(modelFile.getFile().getPath() + "/books/" + dirName);
if (subFamilyDir.exists() && subFamilyDir.getAbsoluteFile() != null) {
String[] children=subFamilyDir.getAbsoluteFile().list(new DirectoryFilenameFilter());
if (children != null) {
for ( String signatureAcc : children) {
signatureAcc=dirName + ":" + signatureAcc;
String signatureName=familyIdFamilyNameMap.get(signatureAcc);
release.addSignature(createSignature(signatureAcc,signatureName,release));
}
}
else {
LOGGER.debug("Either dir does not exist or is not a directory.");
}
}
}
}
| Creates sub family signatures. |
public GridLayout(String group){
super(group);
analyze=true;
}
| Create a new GridLayout without preset dimensions. The layout will attempt to analyze an input graph to determine grid parameters. |
public EchoReplyMessage(EchoReplyMessage other){
if (other.isSetHeader()) {
this.header=new AsyncMessageHeader(other.header);
}
}
| Performs a deep copy on <i>other</i>. |
public ParsedGraphQuery(String sourceString,TupleExpr tupleExpr,Map<String,String> namespaces){
this(sourceString,tupleExpr);
queryNamespaces=namespaces;
}
| Creates a new graph query. |
public int type(){
return tag;
}
| Get the user-defined tag of this event |
protected URI unwrap(URI uri){
return uri;
}
| This implementation returns the given URI. Subclasses may override this behavior. |
@Deprecated public Map<String,String> queryHostIPAddressesMap(){
if (!hostIPv4AddressMap.isEmpty()) {
return hostIPv4AddressMap;
}
return hostIPv6AddressMap;
}
| The method is deprecated. Use InternalDbClient.queryHostIPAddressMap(VirtualDataCenter) |
public AlgVectorTest(String name){
super(name);
}
| Constructs the <code>AlgVectorTest</code>. |
synchronized void queueEvent(EventObject event,Vector<? extends NamingListener> vector){
if (eventQueue == null) eventQueue=new EventQueue();
@SuppressWarnings("unchecked") Vector<NamingListener> v=(Vector<NamingListener>)vector.clone();
eventQueue.enqueue(event,v);
}
| Add the event and vector of listeners to the queue to be delivered. An event dispatcher thread dequeues events from the queue and dispatches them to the registered listeners. Package private; used by NamingEventNotifier to fire events |
public CloseSessionRequest clone(){
CloseSessionRequest result=new CloseSessionRequest();
result.RequestHeader=RequestHeader == null ? null : RequestHeader.clone();
result.DeleteSubscriptions=DeleteSubscriptions;
return result;
}
| Deep clone |
@Override public PrefixQueryBuilder boost(float boost){
this.boost=boost;
return this;
}
| Sets the boost for this query. Documents matching this query will (in addition to the normal weightings) have their score multiplied by the boost provided. |
public GraphHistory(){
graphs=new LinkedList<>();
index=-1;
}
| Constructs a graph history. |
void applyAudioSettings(){
AudioManager am=new AudioManager(mContext);
am.reloadAudioSettings();
}
| Informs the audio service of changes to the settings so that they can be re-read and applied. |
public boolean addAttributeAlways(String uri,String localName,String rawName,String type,String value,boolean xslAttribute){
boolean was_added;
int index;
if (uri == null || localName == null || uri.length() == 0) index=m_attributes.getIndex(rawName);
else {
index=m_attributes.getIndex(uri,localName);
}
if (index >= 0) {
String old_value=null;
if (m_tracer != null) {
old_value=m_attributes.getValue(index);
if (value.equals(old_value)) old_value=null;
}
m_attributes.setValue(index,value);
was_added=false;
if (old_value != null) firePseudoAttributes();
}
else {
if (xslAttribute) {
final int colonIndex=rawName.indexOf(':');
if (colonIndex > 0) {
String prefix=rawName.substring(0,colonIndex);
NamespaceMappings.MappingRecord existing_mapping=m_prefixMap.getMappingFromPrefix(prefix);
if (existing_mapping != null && existing_mapping.m_declarationDepth == m_elemContext.m_currentElemDepth && !existing_mapping.m_uri.equals(uri)) {
prefix=m_prefixMap.lookupPrefix(uri);
if (prefix == null) {
prefix=m_prefixMap.generateNextPrefix();
}
rawName=prefix + ':' + localName;
}
}
try {
String prefixUsed=ensureAttributesNamespaceIsDeclared(uri,localName,rawName);
}
catch ( SAXException e) {
e.printStackTrace();
}
}
m_attributes.addAttribute(uri,localName,rawName,type,value);
was_added=true;
if (m_tracer != null) firePseudoAttributes();
}
return was_added;
}
| Adds the given attribute to the set of attributes, even if there is no currently open element. This is useful if a SAX startPrefixMapping() should need to add an attribute before the element name is seen. This method is a copy of its super classes method, except that some tracing of events is done. This is so the tracing is only done for stream serializers, not for SAX ones. |
public link addElement(String element){
addElementToRegistry(element);
return (this);
}
| Adds an Element to the element. |
protected int countDocsWithClass() throws IOException {
Terms terms=MultiFields.getTerms(this.indexReader,this.classFieldName);
int docCount;
if (terms == null || terms.getDocCount() == -1) {
TotalHitCountCollector classQueryCountCollector=new TotalHitCountCollector();
BooleanQuery.Builder q=new BooleanQuery.Builder();
q.add(new BooleanClause(new WildcardQuery(new Term(classFieldName,String.valueOf(WildcardQuery.WILDCARD_STRING))),BooleanClause.Occur.MUST));
if (query != null) {
q.add(query,BooleanClause.Occur.MUST);
}
indexSearcher.search(q.build(),classQueryCountCollector);
docCount=classQueryCountCollector.getTotalHits();
}
else {
docCount=terms.getDocCount();
}
return docCount;
}
| count the number of documents in the index having at least a value for the 'class' field |
public Object runSafely(Catbert.FastStack stack) throws Exception {
return Wizard.getInstance().getAllUserStores();
}
| Gets all existing Stores that UserRecord objects have been created under in the database. |
public double scalarProjectOnto(Vec2D otherVector){
return dot(otherVector) / otherVector.magnitude();
}
| Calculate the Scalar Projection of this Vector onto another Vector |
@Override public void createGroupSnapshots(StorageSystem storage,List<URI> snapshotList,Boolean createInactive,Boolean readOnly,TaskCompleter taskCompleter) throws DeviceControllerException {
try {
URI snapshot=snapshotList.get(0);
BlockSnapshot snapshotObj=_dbClient.queryObject(BlockSnapshot.class,snapshot);
Volume volume=_dbClient.queryObject(Volume.class,snapshotObj.getParent());
if (ControllerUtils.isNotInRealVNXRG(volume,_dbClient)) {
throw DeviceControllerException.exceptions.groupSnapshotNotSupported(volume.getReplicationGroupInstance());
}
ReplicationUtils.checkReplicationGroupAccessibleOrFail(storage,snapshotObj,_dbClient,_helper,_cimPath);
TenantOrg tenant=_dbClient.queryObject(TenantOrg.class,volume.getTenant().getURI());
String tenantName=tenant.getLabel();
String snapLabelToUse=_nameGenerator.generate(tenantName,snapshotObj.getLabel(),snapshot.toString(),'-',SmisConstants.MAX_SNAPSHOT_NAME_LENGTH);
String groupName=ConsistencyGroupUtils.getSourceConsistencyGroupName(snapshotObj,_dbClient);
CIMObjectPath cgPath=_cimPath.getReplicationGroupPath(storage,groupName);
CIMObjectPath replicationSvc=_cimPath.getControllerReplicationSvcPath(storage);
CIMArgument[] inArgs=_helper.getCreateGroupReplicaInputArgumentsForVNX(storage,cgPath,createInactive,snapLabelToUse,SYNC_TYPE.SNAPSHOT.getValue());
CIMArgument[] outArgs=new CIMArgument[5];
_helper.invokeMethod(storage,replicationSvc,SmisConstants.CREATE_GROUP_REPLICA,inArgs,outArgs);
CIMObjectPath job=_cimPath.getCimObjectPathFromOutputArgs(outArgs,SmisConstants.JOB);
if (job != null) {
ControllerServiceImpl.enqueueJob(new QueueJob(new SmisBlockCreateCGSnapshotJob(job,storage.getId(),!createInactive,null,taskCompleter)));
}
}
catch ( Exception e) {
_log.info("Problem making SMI-S call: ",e);
ServiceError error=DeviceControllerErrors.smis.unableToCallStorageProvider(e.getMessage());
taskCompleter.error(_dbClient,error);
setInactive(((BlockSnapshotCreateCompleter)taskCompleter).getSnapshotURIs(),true);
}
}
| Should implement create of a snapshot from a source volume that is part of a consistency group. |
@Override protected void check(){
super.check();
if (m_Classifier == null) {
throw new IllegalStateException("No classifier set!");
}
if (m_ClassIndex == -1) {
throw new IllegalStateException("No class index set!");
}
if (m_Evaluation == null) {
throw new IllegalStateException("No evaluation set");
}
}
| Checks whether classifier, class index and evaluation are provided. |
public static String obtainEncodingStringFromFile(String filename) throws IOException {
String encoding="UTF-8";
FileInputStream fis=new FileInputStream(filename);
BufferedInputStream bis=new BufferedInputStream(fis);
if (bis.markSupported()) {
String line=null;
bis.mark(ENOUGH);
DataInputStream dis=new DataInputStream(bis);
line=dis.readLine();
line=line.replace("'","\"");
if (line.matches(XML_FIRST_LINE_REGEX)) {
encoding=extractEncoding(line);
}
bis.reset();
}
fis.close();
bis.close();
return encoding;
}
| Helper method to obtain the content encoding from an file. |
public void copyMove(String path,boolean shouldMove){
shouldMoveCopiedFile=shouldMove;
copyMoveSourceFile=new File(path);
if (!copyMoveSourceFile.exists()) {
Toast.makeText(mContext,R.string.cant_copy_this_file_folder,Toast.LENGTH_SHORT).show();
return;
}
mIsPasteShown=true;
((MainActivity)getActivity()).showFolderFragmentActionItems(currentDir,getActivity().getMenuInflater(),((MainActivity)getActivity()).getMenu(),true);
}
| Stores the specified file/folder's path in a temp variable and displays the "Paste" option in the ActionBar. |
public boolean restoreJsonForUser(String userId,InputStreamReader streamReader,boolean reuseIds,boolean isAdmin,Errors errors){
boolean result=reallyRestoreJsonForUser(userId,streamReader,reuseIds,isAdmin,errors);
if (!result) {
rollback();
}
else {
commit();
}
return result;
}
| API method. This method starts its own transactions. Restores a JSON stream of a user's entries and sources. |
public Namespace addNamespace(String prefix,String uri){
Namespace namespace=createNamespace(prefix,uri);
push(namespace);
return namespace;
}
| Adds a new namespace to the stack |
public Import peek(){
return stack.peek();
}
| Return the current import. |
boolean hasReadBinaryChildren(){
return this.binaryChildren != null;
}
| Returns true iff the <code>readBinaryChildren</code> has already been called. |
public LinkedIntegerMap(final LinkedIntegerMap<T>[] integerMaps){
m_values=new LinkedHashMap<>();
for ( final LinkedIntegerMap<T> integerMap : integerMaps) {
this.add(integerMap);
}
}
| This will make a new IntegerMap. The Objects will be linked, but the integers mapped to them will not be linked. |
public static Blob toBlob(Connection conn,Object value) throws PageException, SQLException {
if (value instanceof Blob) return (Blob)value;
if (SystemUtil.JAVA_VERSION >= SystemUtil.JAVA_VERSION_1_6) {
try {
Blob blob=conn.createBlob();
blob.setBytes(1,Caster.toBinary(value));
return blob;
}
catch ( Throwable t) {
return BlobImpl.toBlob(value);
}
}
if (isOracle(conn)) {
Blob blob=OracleBlob.createBlob(conn,Caster.toBinary(value),null);
if (blob != null) return blob;
}
return BlobImpl.toBlob(value);
}
| create a blog Object |
public final short addAndGet(int index,short delta){
return this.addAndGet(index,delta,false);
}
| Atomically adds a delta to an element, and gets the new value. |
public boolean isClean(File file) throws IOException {
String raw=new String(Files.readAllBytes(file.toPath()),encoding);
String unix=LineEnding.toUnix(raw);
int totalNewLines=(int)unix.codePoints().filter(null).count();
int windowsNewLines=raw.length() - unix.length();
if (lineEndingPolicy.isUnix(file)) {
if (windowsNewLines != 0) {
return false;
}
}
else {
if (windowsNewLines != totalNewLines) {
return false;
}
}
String formatted=applySteps(unix,file);
return formatted.equals(unix);
}
| Returns true iff the given file's formatting is up-to-date. |
public form(String action,String method,Element element){
addElement(element);
setAction(action);
setMethod(method);
}
| Default URL Encoded utf-8 form Use the set* methods to set the values of the attributes. |
public void saveSelectionDetail(){
int row=p_table.getSelectedRow();
if (row == -1) return;
Integer ID=getSelectedRowKey();
Env.setContext(Env.getCtx(),p_WindowNo,Env.TAB_INFO,"A_Asset_ID",ID == null ? "0" : ID.toString());
}
| Save Selection Details Get Location/Partner Info |
public FileListener(Printer printer,File inputFile,ConstructLengths constructLengths,Set<Rules> enabledRules) throws IOException {
this.printer=printer;
this.inputFile=inputFile;
this.constructLengths=constructLengths;
this.reader=new LineNumberReader(Files.newBufferedReader(inputFile.toPath()));
this.enabledRules=enabledRules;
}
| Constructs a file listener with the specified printer, input file, and max lengths restrictions. |
private static void checkLen(int expectedLen,int actual) throws DimensionMismatchException {
if (expectedLen != actual) {
throw new DimensionMismatchException(actual,expectedLen);
}
}
| Check two lengths are equal. |
private void initialize(Object[] sorted){
keys.removeAllElements();
data.removeAllElements();
int n=sorted.length;
for (int i=0; i < n; i+=2) {
keys.addElement(sorted[i]);
data.addElement(sorted[i + 1]);
}
}
| Initialize with a set of already sorted keys (data from an existing SmallAttributeSet). |
public void withdraw(double amount){
balance-=amount;
}
| Decrease balance by amount |
protected Node newNode(){
return new SVGOMMaskElement();
}
| Returns a new uninitialized instance of this object's class. |
@edu.umd.cs.findbugs.annotations.SuppressFBWarnings(value="EI_EXPOSE_REP") public String[] validBaudRates(){
return validSpeeds;
}
| Get an array of valid baud rates. |
private int validatePreloadOrder(CacheConfiguration[] cfgs) throws IgniteCheckedException {
int maxOrder=0;
for ( CacheConfiguration cfg : cfgs) {
int rebalanceOrder=cfg.getRebalanceOrder();
if (rebalanceOrder > 0) {
if (cfg.getCacheMode() == LOCAL) throw new IgniteCheckedException("Rebalance order set for local cache (fix configuration and restart the " + "node): " + U.maskName(cfg.getName()));
if (cfg.getRebalanceMode() == CacheRebalanceMode.NONE) throw new IgniteCheckedException("Only caches with SYNC or ASYNC rebalance mode can be set as rebalance " + "dependency for other caches [cacheName=" + U.maskName(cfg.getName()) + ", rebalanceMode="+ cfg.getRebalanceMode()+ ", rebalanceOrder="+ cfg.getRebalanceOrder()+ ']');
maxOrder=Math.max(maxOrder,rebalanceOrder);
}
else if (rebalanceOrder < 0) throw new IgniteCheckedException("Rebalance order cannot be negative for cache (fix configuration and restart " + "the node) [cacheName=" + U.maskName(cfg.getName()) + ", rebalanceOrder="+ rebalanceOrder+ ']');
}
return maxOrder;
}
| Checks that preload-order-dependant caches has SYNC or ASYNC preloading mode. |
public List<Object> syncAndReturnAll(){
List<Object> unformatted=client.getAll();
List<Object> formatted=new ArrayList<Object>();
for ( Object o : unformatted) {
try {
formatted.add(generateResponse(o).get());
}
catch ( JedisDataException e) {
formatted.add(e);
}
}
return formatted;
}
| Syncronize pipeline by reading all responses. This operation close the pipeline. Whenever possible try to avoid using this version and use Pipeline.sync() as it won't go through all the responses and generate the right response type (usually it is a waste of time). |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.