code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
public void printMemory(){
m_readLock.lock();
for ( final MemoryChunk chunk : m_chunks) {
chunk.print();
}
m_readLock.unlock();
}
| Prints the content of the memory to stdout. |
public static ImageSource uri(String uri){
if (uri == null) {
throw new NullPointerException("Uri must not be null");
}
if (!uri.contains("://")) {
if (uri.startsWith("/")) {
uri=uri.substring(1);
}
uri=FILE_SCHEME + uri;
}
return new ImageSource(Uri.parse(uri));
}
| Create an instance from a URI. If the URI does not start with a scheme, it's assumed to be the URI of a file. |
public GroupBuilder<T,UnionBuilder<T,E>> left(){
return new GroupBuilder<T,UnionBuilder<T,E>>(this);
}
| Return a builder for creating the left operand of the union |
public JSONObject increment(String key) throws JSONException {
Object value=this.opt(key);
if (value == null) {
this.put(key,1);
}
else if (value instanceof Integer) {
this.put(key,((Integer)value).intValue() + 1);
}
else if (value instanceof Long) {
this.put(key,((Long)value).longValue() + 1);
}
else if (value instanceof Double) {
this.put(key,((Double)value).doubleValue() + 1);
}
else if (value instanceof Float) {
this.put(key,((Float)value).floatValue() + 1);
}
else {
throw new JSONException("Unable to increment [" + quote(key) + "].");
}
return this;
}
| Increment a property of a JSONObject. If there is no such property, create one with a value of 1. If there is such a property, and if it is an Integer, Long, Double, or Float, then add one to it. |
public static cuComplex cuCmplx(float r,float i){
cuComplex res=new cuComplex();
res.x=r;
res.y=i;
return res;
}
| Creates a new complex number consisting of the given real and imaginary part. |
public Observable<String> exerciseZip(Observable<String> a,Observable<String> b){
return Observable.zip(a,b,null);
}
| Combine 2 streams into pairs using zip. a -> "one", "two", "red", "blue" b -> "fish", "fish", "fish", "fish" output -> "one fish", "two fish", "red fish", "blue fish" |
public int maximalSquare(char[][] matrix){
if (matrix == null) {
return 0;
}
int r=matrix.length;
int c=r == 0 ? 0 : matrix[0].length;
int[][] dp=new int[r + 1][c + 1];
int maxLen=0;
for (int i=1; i <= r; i++) {
for (int j=1; j <= c; j++) {
if (matrix[i - 1][j - 1] == '1') {
dp[i][j]=Math.min(Math.min(dp[i - 1][j],dp[i][j - 1]),dp[i - 1][j - 1]) + 1;
maxLen=Math.max(maxLen,dp[i][j]);
}
}
}
return maxLen * maxLen;
}
| DP, 2D matrix. The recurrence relation here is not easy to see. Use largest square's edge length formed including current grid. If the current grid is an 1,the edge length of current grid is the (minimum of its top, top-left, and left) + 1. Otherwise, if its 0, the edge length is still zero. |
public PermissionCollection newPermissionCollection(){
return new ExecOptionPermissionCollection();
}
| Returns a new PermissionCollection object for storing ExecOptionPermission objects. <p> A ExecOptionPermissionCollection stores a collection of ExecOptionPermission permissions. <p>ExecOptionPermission objects must be stored in a manner that allows them to be inserted in any order, but that also enables the PermissionCollection <code>implies</code> method to be implemented in an efficient (and consistent) manner. |
public void watchForAvailability(){
watch(true);
}
| Wait till the monitored Deployable is made available or throw an exception if the timeout period is reached. Equivalent to <code>watch(true)</code>. |
private static String extractIdFromUrl(String url){
int lastSlash=url.lastIndexOf('/');
if (lastSlash == -1 || lastSlash == (url.length() - 1)) {
throw new IllegalArgumentException("Id is in a strange format. " + url);
}
String oid=url.substring(lastSlash + 1);
return oid;
}
| Extracts the id of the item from the given url. The id found in GoogleBaseEntry is a URL that contains the real, numerical id of the item in Google Base. Parsing the URL is unfortunately the only way of getting a numerical id given a GoogleBaseEntry. |
public static Mapper<String> singleString(){
return singleString;
}
| Maps the first string column |
protected void applyStatus(IStatus status){
String msg=status.getMessage();
if (msg != null && msg.length() == 0) {
msg=null;
}
switch (status.getSeverity()) {
case IStatus.OK:
setMessage(msg,IMessageProvider.NONE);
setErrorMessage(null);
break;
case IStatus.WARNING:
setMessage(msg,IMessageProvider.WARNING);
setErrorMessage(null);
break;
case IStatus.INFO:
setMessage(msg,IMessageProvider.INFORMATION);
setErrorMessage(null);
break;
default :
setMessage(null);
setErrorMessage(msg);
break;
}
}
| Applies the status to the status line of the wizard page. |
public StrBuilder append(long value){
return append(String.valueOf(value));
}
| Appends a long value to the string builder using <code>String.valueOf</code>. |
public StrBuilder appendln(final char ch){
return append(ch).appendNewLine();
}
| Appends a char value followed by a new line to the string builder. |
public void put(String key,Boolean value){
mValues.put(key,value);
}
| Adds a value to the set. |
private Workflow.Method deleteStorageViewMethod(URI vplexURI,URI exportMaskURI){
return new Workflow.Method(DELETE_STORAGE_VIEW,vplexURI,exportMaskURI);
}
| Create a Workflow Method for deleteStorageView(). Args must match deleteStorageView except for extra stepId arg. |
public void addInternetScsiSendTargets(HostStorageSystem storageSystem,HostInternetScsiHba hba,String... addresses){
try {
storageSystem.addInternetScsiSendTargets(hba.getDevice(),createInternetScsiSendTargets(addresses));
}
catch ( HostConfigFault e) {
throw new VMWareException(e);
}
catch ( NotFound e) {
throw new VMWareException(e);
}
catch ( RuntimeFault e) {
throw new VMWareException(e);
}
catch ( RemoteException e) {
throw new VMWareException(e);
}
}
| Adds iSCSI send targets to the host storage system. |
private void testBug71396MultiSettingsCheck(String connProps,int maxRows,int limitClause,int expRowCount) throws SQLException {
Connection testConn=getConnectionWithProps(connProps);
Statement testStmt=testConn.createStatement();
if (maxRows > 0) {
testStmt.setMaxRows(maxRows);
}
testStmt.execute("SELECT 1");
testBug71396StatementCheck(testStmt,String.format("SELECT * FROM testBug71396 LIMIT %d",limitClause),expRowCount);
testBug71396PrepStatementCheck(testConn,String.format("SELECT * FROM testBug71396 LIMIT %d",limitClause),expRowCount,maxRows);
testStmt.close();
testConn.close();
}
| Executes a query containing the clause LIMIT with a Statement and a PreparedStatement, using a combination of Connection properties, maxRows value and limit clause value, and tests if the results count is the expected. |
private Base64(){
}
| Defeats instantiation. |
public void dumpAll(Iterator<? extends Object> data,Writer output){
dumpAll(data,output,null);
}
| Serialize a sequence of Java objects into a YAML stream. |
public void add(String documentId,HistoryEvent event){
if (historyLogger == null) {
LOGGER.error("Logging history event withouth an initialised logger");
return;
}
switch (loggerLevel) {
case "warn":
historyLogger.warn(DEFAULT_FORMAT,Instant.ofEpochMilli(event.getTimestamp()),documentId,event.getRecordable().getInternalId(),event.getReferrer(),event.getAction());
break;
case "error":
historyLogger.error(DEFAULT_FORMAT,Instant.ofEpochMilli(event.getTimestamp()),documentId,event.getRecordable().getInternalId(),event.getReferrer(),event.getAction());
break;
case "trace":
historyLogger.trace(DEFAULT_FORMAT,Instant.ofEpochMilli(event.getTimestamp()),documentId,event.getRecordable().getInternalId(),event.getReferrer(),event.getAction());
break;
case "info":
default :
historyLogger.info(DEFAULT_FORMAT,Instant.ofEpochMilli(event.getTimestamp()),documentId,event.getRecordable().getInternalId(),event.getReferrer(),event.getAction());
break;
}
}
| Add the event to the specific document. |
public synchronized <T>T unwrap(java.lang.Class<T> iface) throws java.sql.SQLException {
try {
if ("java.sql.Connection".equals(iface.getName()) || "java.sql.Wrapper.class".equals(iface.getName())) {
return iface.cast(this);
}
if (unwrappedInterfaces == null) {
unwrappedInterfaces=new HashMap<Class<?>,Object>();
}
Object cachedUnwrapped=unwrappedInterfaces.get(iface);
if (cachedUnwrapped == null) {
cachedUnwrapped=Proxy.newProxyInstance(this.mc.getClass().getClassLoader(),new Class<?>[]{iface},new ConnectionErrorFiringInvocationHandler(this.mc));
unwrappedInterfaces.put(iface,cachedUnwrapped);
}
return iface.cast(cachedUnwrapped);
}
catch ( ClassCastException cce) {
throw SQLError.createSQLException("Unable to unwrap to " + iface.toString(),SQLError.SQL_STATE_ILLEGAL_ARGUMENT,this.exceptionInterceptor);
}
}
| Returns an object that implements the given interface to allow access to non-standard methods, or standard methods not exposed by the proxy. The result may be either the object found to implement the interface or a proxy for that object. If the receiver implements the interface then that is the object. If the receiver is a wrapper and the wrapped object implements the interface then that is the object. Otherwise the object is the result of calling <code>unwrap</code> recursively on the wrapped object. If the receiver is not a wrapper and does not implement the interface, then an <code>SQLException</code> is thrown. |
public static void addOptionalFeatures(ImageRequestBuilder imageRequestBuilder,Config config){
if (config.usePostprocessor) {
final Postprocessor postprocessor;
switch (config.postprocessorType) {
case "use_slow_postprocessor":
postprocessor=DelayPostprocessor.getMediumPostprocessor();
break;
case "use_fast_postprocessor":
postprocessor=DelayPostprocessor.getFastPostprocessor();
break;
default :
postprocessor=DelayPostprocessor.getMediumPostprocessor();
}
imageRequestBuilder.setPostprocessor(postprocessor);
}
if (config.rotateUsingMetaData) {
imageRequestBuilder.setRotationOptions(RotationOptions.autoRotateAtRenderTime());
}
else {
imageRequestBuilder.setRotationOptions(RotationOptions.forceRotation(config.forcedRotationAngle));
}
}
| Utility method which adds optional configuration to ImageRequest |
@CanIgnoreReturnValue public static <T>T checkNotNull(T reference){
if (reference == null) {
throw new NullPointerException();
}
return reference;
}
| Ensures that an object reference passed as a parameter to the calling method is not null. |
Node(K key,Object value,Node<K,V> next){
this.key=key;
this.value=value;
this.next=next;
}
| Creates a new regular node. |
public static void run(AdSense adsense) throws Exception {
System.out.println("=================================================================");
System.out.println("Listing all dimensions for default account");
System.out.println("=================================================================");
Metadata dimensions=adsense.metadata().dimensions().list().execute();
if (dimensions.getItems() != null && !dimensions.getItems().isEmpty()) {
for ( ReportingMetadataEntry dimension : dimensions.getItems()) {
boolean firstProduct=true;
StringBuilder products=new StringBuilder();
for ( String product : dimension.getSupportedProducts()) {
if (!firstProduct) {
products.append(", ");
}
products.append(product);
firstProduct=false;
}
System.out.printf("Dimension id \"%s\" for product(s): [%s] was found.\n",dimension.getId(),products.toString());
}
}
else {
System.out.println("No dimensions found.");
}
System.out.println();
}
| Runs this sample. |
public void doTest(String filename,int dim,int iter) throws Exception {
System.out.println("Allocating arrays.");
double[] db=new double[dim];
float[] fl=new float[dim];
int[] in=new int[dim];
long[] ln=new long[dim];
short[] sh=new short[dim];
byte[] by=new byte[dim];
char[] ch=new char[dim];
boolean[] bl=new boolean[dim];
System.out.println("Initializing arrays -- may take a while");
int sign=1;
for (int i=0; i < dim; i+=1) {
double x=sign * Math.pow(10.,20 * Math.random() - 10);
db[i]=x;
fl[i]=(float)x;
if (Math.abs(x) < 1) {
x=1 / x;
}
in[i]=(int)x;
ln[i]=(long)x;
sh[i]=(short)x;
by[i]=(byte)x;
ch[i]=(char)x;
bl[i]=x > 0;
sign=-sign;
}
by[0]=Byte.MIN_VALUE;
by[1]=Byte.MAX_VALUE;
by[2]=0;
ch[0]=Character.MIN_VALUE;
ch[1]=Character.MAX_VALUE;
ch[2]=0;
sh[0]=Short.MAX_VALUE;
sh[1]=Short.MIN_VALUE;
sh[0]=0;
in[0]=Integer.MAX_VALUE;
in[1]=Integer.MIN_VALUE;
in[2]=0;
ln[0]=Long.MIN_VALUE;
ln[1]=Long.MAX_VALUE;
ln[2]=0;
fl[0]=Float.MIN_VALUE;
fl[1]=Float.MAX_VALUE;
fl[2]=Float.POSITIVE_INFINITY;
fl[3]=Float.NEGATIVE_INFINITY;
fl[4]=Float.NaN;
fl[5]=0;
db[0]=Double.MIN_VALUE;
db[1]=Double.MAX_VALUE;
db[2]=Double.POSITIVE_INFINITY;
db[3]=Double.NEGATIVE_INFINITY;
db[4]=Double.NaN;
db[5]=0;
double[] db2=new double[dim];
float[] fl2=new float[dim];
int[] in2=new int[dim];
long[] ln2=new long[dim];
short[] sh2=new short[dim];
byte[] by2=new byte[dim];
char[] ch2=new char[dim];
boolean[] bl2=new boolean[dim];
int[][][][] multi=new int[10][10][10][10];
int[][][][] multi2=new int[10][10][10][10];
for (int i=0; i < 10; i+=1) {
multi[i][i][i][i]=i;
}
standardFileTest(filename,iter,in,in2);
standardStreamTest(filename,iter,in,in2);
buffStreamSimpleTest(filename,iter,in,in2);
bufferedFileTest(filename,iter,db,db2,fl,fl2,ln,ln2,in,in2,sh,sh2,ch,ch2,by,by2,bl,bl2,multi,multi2);
bufferedStreamTest(filename,iter,db,db2,fl,fl2,ln,ln2,in,in2,sh,sh2,ch,ch2,by,by2,bl,bl2,multi,multi2);
}
| Usage: java nom.tam.util.test.BufferedFileTester file [dim [iter [flags]]] where file is the file to be read and written. dim is the dimension of the arrays to be written. iter is the number of times each tiledImageOperation is written. flags a string indicating what I/O to test O -- test old I/O (RandomAccessFile and standard streams) R -- BufferedFile (i.e., random access) S -- BufferedDataXPutStream X -- BufferedDataXPutStream using standard methods |
public void go(){
synchronized (monitor) {
this.returnValue=GO;
monitor.notifyAll();
}
}
| Resumes execution of script. |
protected void reset(){
}
| Resets the associated attribute value according to the current value. This should be overridden in descendant classes that associate the angle object with an attribute. |
public UndeployDeployableScriptCommand(Configuration configuration,String resourcePath,Deployable deployable){
super(configuration,resourcePath);
this.deployable=deployable;
}
| Sets configuration containing all needed information for building configuration scripts. |
PdfBoxRenderer(BaseDocument doc,UnicodeImplementation unicode,HttpStreamFactory httpStreamFactory,OutputStream os,FSUriResolver resolver,FSCache cache,SVGDrawer svgImpl,PageDimensions pageSize,float pdfVersion,String replacementText,boolean testMode){
_pdfDoc=new PDDocument();
_pdfDoc.setVersion(pdfVersion);
_svgImpl=svgImpl;
_dotsPerPoint=DEFAULT_DOTS_PER_POINT;
_testMode=testMode;
_outputDevice=new PdfBoxOutputDevice(DEFAULT_DOTS_PER_POINT,testMode);
_outputDevice.setWriter(_pdfDoc);
PdfBoxUserAgent userAgent=new PdfBoxUserAgent(_outputDevice);
if (httpStreamFactory != null) {
userAgent.setHttpStreamFactory(httpStreamFactory);
}
if (resolver != null) {
userAgent.setUriResolver(resolver);
}
if (cache != null) {
userAgent.setExternalCache(cache);
}
_sharedContext=new SharedContext();
_sharedContext.registerWithThread();
_sharedContext.setUserAgentCallback(userAgent);
_sharedContext.setCss(new StyleReference(userAgent));
userAgent.setSharedContext(_sharedContext);
_outputDevice.setSharedContext(_sharedContext);
PdfBoxFontResolver fontResolver=new PdfBoxFontResolver(_sharedContext,_pdfDoc);
_sharedContext.setFontResolver(fontResolver);
PdfBoxReplacedElementFactory replacedElementFactory=new PdfBoxReplacedElementFactory(_outputDevice,svgImpl);
_sharedContext.setReplacedElementFactory(replacedElementFactory);
_sharedContext.setTextRenderer(new PdfBoxTextRenderer());
_sharedContext.setDPI(DEFAULT_PDF_POINTS_PER_INCH * _dotsPerPoint);
_sharedContext.setDotsPerPixel(DEFAULT_DOTS_PER_PIXEL);
_sharedContext.setPrint(true);
_sharedContext.setInteractive(false);
this.getSharedContext().setDefaultPageSize(pageSize.w,pageSize.h,pageSize.isSizeInches);
if (replacementText != null) {
this.getSharedContext().setReplacementText(replacementText);
}
if (unicode.splitterFactory != null) {
this._splitterFactory=unicode.splitterFactory;
}
if (unicode.reorderer != null) {
this._reorderer=unicode.reorderer;
this._outputDevice.setBidiReorderer(_reorderer);
}
if (unicode.lineBreaker != null) {
_sharedContext.setLineBreaker(unicode.lineBreaker);
}
if (unicode.charBreaker != null) {
_sharedContext.setCharacterBreaker(unicode.charBreaker);
}
if (unicode.toLowerTransformer != null) {
_sharedContext.setUnicodeToLowerTransformer(unicode.toLowerTransformer);
}
if (unicode.toUpperTransformer != null) {
_sharedContext.setUnicodeToUpperTransformer(unicode.toUpperTransformer);
}
if (unicode.toTitleTransformer != null) {
_sharedContext.setUnicodeToTitleTransformer(unicode.toTitleTransformer);
}
this._defaultTextDirection=unicode.textDirection ? BidiSplitter.RTL : BidiSplitter.LTR;
if (doc.html != null) {
this.setDocumentFromStringP(doc.html,doc.baseUri);
}
else if (doc.document != null) {
this.setDocumentP(doc.document,doc.baseUri);
}
else if (doc.uri != null) {
this.setDocumentP(doc.uri);
}
else if (doc.file != null) {
try {
this.setDocumentP(doc.file);
}
catch ( IOException e) {
XRLog.exception("Problem trying to read input XHTML file",e);
throw new RuntimeException("File IO problem",e);
}
}
this._os=os;
}
| This method is constantly changing as options are added to the builder. |
public boolean isEsmeDeliveryAcknowledgement(){
return isEsmeDeliveryAcknowledgement(esmClass);
}
| Message Type. |
public QueryException(String message,int errorCode,String sqlState,Throwable cause){
super(message,cause);
this.message=message;
this.errorCode=errorCode;
this.sqlState=sqlState;
}
| Creates a query exception with a message and a cause. |
public static Class<?> mapSimpleType(RamlParamType param){
switch (param) {
case BOOLEAN:
return Boolean.class;
case DATE:
return Date.class;
case INTEGER:
return Long.class;
case NUMBER:
return BigDecimal.class;
case FILE:
return MultipartFile.class;
default :
return String.class;
}
}
| Maps simple types supported by RAML into primitives and other simple Java types |
public void put(String key,boolean value){
super.put(key,Boolean.valueOf(value));
}
| <p> Adds the given <code>boolean</code> value to the <code>StringKeyDirtyFlagMap</code>. </p> |
public ExtensionInfo(String extensionKey,Attributes attr) throws NullPointerException {
String s;
if (extensionKey != null) {
s=extensionKey + "-";
}
else {
s="";
}
String attrKey=s + Name.EXTENSION_NAME.toString();
name=attr.getValue(attrKey);
if (name != null) name=name.trim();
attrKey=s + Name.SPECIFICATION_TITLE.toString();
title=attr.getValue(attrKey);
if (title != null) title=title.trim();
attrKey=s + Name.SPECIFICATION_VERSION.toString();
specVersion=attr.getValue(attrKey);
if (specVersion != null) specVersion=specVersion.trim();
attrKey=s + Name.SPECIFICATION_VENDOR.toString();
specVendor=attr.getValue(attrKey);
if (specVendor != null) specVendor=specVendor.trim();
attrKey=s + Name.IMPLEMENTATION_VERSION.toString();
implementationVersion=attr.getValue(attrKey);
if (implementationVersion != null) implementationVersion=implementationVersion.trim();
attrKey=s + Name.IMPLEMENTATION_VENDOR.toString();
vendor=attr.getValue(attrKey);
if (vendor != null) vendor=vendor.trim();
attrKey=s + Name.IMPLEMENTATION_VENDOR_ID.toString();
vendorId=attr.getValue(attrKey);
if (vendorId != null) vendorId=vendorId.trim();
attrKey=s + Name.IMPLEMENTATION_URL.toString();
url=attr.getValue(attrKey);
if (url != null) url=url.trim();
}
| <p> Create and initialize an extension information object. The initialization uses the attributes passed as being the content of a manifest file to load the extension information from. Since manifest file may contain information on several extension they may depend on, the extension key parameter is prepanded to the attribute name to make the key used to retrieve the attribute from the manifest file <p> |
public void increaseNestingLevel(){
this.nestingLevel++;
}
| Increase this parameter's nesting level. |
private void writeQNameAttribute(java.lang.String namespace,java.lang.String attName,javax.xml.namespace.QName qname,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
java.lang.String attributeNamespace=qname.getNamespaceURI();
java.lang.String attributePrefix=xmlWriter.getPrefix(attributeNamespace);
if (attributePrefix == null) {
attributePrefix=registerPrefix(xmlWriter,attributeNamespace);
}
java.lang.String attributeValue;
if (attributePrefix.trim().length() > 0) {
attributeValue=attributePrefix + ":" + qname.getLocalPart();
}
else {
attributeValue=qname.getLocalPart();
}
if (namespace.equals("")) {
xmlWriter.writeAttribute(attName,attributeValue);
}
else {
registerPrefix(xmlWriter,namespace);
xmlWriter.writeAttribute(namespace,attName,attributeValue);
}
}
| Util method to write an attribute without the ns prefix |
public void addPage(@NotNull WizardPage<T> page,int index,boolean replace){
if (index >= wizardPages.size()) {
addPage(page);
return;
}
if (replace) {
setPage(page,index);
}
else {
List<WizardPage<T>> before=ListHelper.slice(wizardPages,0,index);
WizardPage<T> currentPage=wizardPages.get(index);
List<WizardPage<T>> after=ListHelper.slice(wizardPages,index + 1,wizardPages.size());
wizardPages.clear();
wizardPages.addAll(before);
addPage(page);
wizardPages.add(currentPage);
wizardPages.addAll(after);
}
}
| Add page to wizard at the specified position. |
public DecoderResult decode(boolean[][] image) throws FormatException, ChecksumException {
int dimension=image.length;
BitMatrix bits=new BitMatrix(dimension);
for (int i=0; i < dimension; i++) {
for (int j=0; j < dimension; j++) {
if (image[j][i]) {
bits.set(j,i);
}
}
}
return decode(bits);
}
| <p>Convenience method that can decode a PDF417 Code represented as a 2D array of booleans. "true" is taken to mean a black module.</p> |
public void paint(Graphics g,Shape allocation){
Rectangle a=(Rectangle)allocation;
painter.paint(g,a.x,a.y,a.width,a.height,this);
super.paint(g,a);
}
| Renders using the given rendering surface and area on that surface. This is implemented to delegate to the css box painter to paint the border and background prior to the interior. |
void jbInit() throws Exception {
this.setLayout(borderLayout1);
jPanel1.setLayout(borderLayout6);
jPanel4.setLayout(gridLayout1);
jPanel2.setLayout(borderLayout3);
jPanel3.setLayout(borderLayout5);
jPanel4.setBackground(Color.orange);
jPanel2.setBackground(Color.red);
jPanel3.setBackground(Color.pink);
gridLayout1.setVgap(5);
jPanel17.setLayout(borderLayout9);
jPanel16.setLayout(borderLayout8);
jPanel10.setLayout(gridLayout5);
flowLayout5.setVgap(0);
jPanel7.setLayout(flowLayout5);
flowLayout4.setHgap(2);
flowLayout4.setAlignment(0);
flowLayout4.setVgap(0);
jPanel8.setLayout(flowLayout4);
jPanel9.setLayout(gridLayout9);
jPanel18.setLayout(flowLayout1);
jPanel.setLayout(gridLayout8);
flowLayout1.setVgap(2);
flowLayout1.setHgap(2);
flowLayout5.setAlignment(0);
flowLayout5.setHgap(1);
jPanel15.setLayout(borderLayout7);
gridLayout1.setHgap(2);
jPanel13.setLayout(gridLayout2);
jPanel5.setLayout(borderLayout2);
this.add(jPanel1,BorderLayout.CENTER);
jPanel1.add(jPanel2,BorderLayout.NORTH);
jPanel2.add(jPanel5,BorderLayout.NORTH);
jPanel5.add(jPanel16,BorderLayout.NORTH);
jPanel16.add(jPanel8,BorderLayout.EAST);
jPanel8.add(jPanel9,null);
jPanel9.add(jButtonHelp,null);
jPanel16.add(jPanel7,BorderLayout.WEST);
jPanel7.add(jPanel10,null);
jPanel10.add(jButtonNew,null);
jPanel10.add(jButtonOpen,null);
jPanel10.add(jButtonSaveAs,null);
jPanel10.add(jButtonSave,null);
jPanel10.add(jButtonPrint,null);
jPanel10.add(jButtonClose,null);
jPanel5.add(jPanel17,BorderLayout.SOUTH);
jPanel17.add(jPanel18,BorderLayout.WEST);
jPanel18.add(jPanel,null);
jPanel.add(jButtonCopy,null);
jPanel.add(jButtonCut,null);
jPanel.add(jButtonPaste,null);
jPanel1.add(jPanel3,BorderLayout.CENTER);
jPanel3.add(jPanel15,BorderLayout.CENTER);
jPanel15.add(jScrollPane1,BorderLayout.CENTER);
jScrollPane1.getViewport().add(jTextArea1,null);
jPanel1.add(jPanel4,BorderLayout.SOUTH);
jPanel4.add(jPanel13,null);
jPanel13.add(statusBar,null);
jTextArea1.setPreferredSize(new Dimension(200,100));
}
| Method jbInit. |
@Override public void performRequest(String request){
if (request.compareTo("Show preview") == 0) {
showPreview();
return;
}
if (request.indexOf(":") < 0) {
return;
}
String tempI=request.substring(0,request.indexOf(':'));
int index=Integer.parseInt(tempI);
index--;
String req=request.substring(request.indexOf(')') + 1,request.length()).trim();
Object target=((BeanInstance)m_subFlow.elementAt(index)).getBean();
if (target instanceof Startable && req.equals(((Startable)target).getStartMessage())) {
try {
((Startable)target).start();
}
catch ( Exception ex) {
if (m_log != null) {
String compName=(target instanceof BeanCommon) ? ((BeanCommon)target).getCustomName() : "";
m_log.logMessage("Problem starting subcomponent " + compName);
}
}
}
else {
((UserRequestAcceptor)target).performRequest(req);
}
}
| Perform a particular request |
private String addAliasToIdentifier(String where,String alias){
String sqlkey="AND,OR,FROM,WHERE,JOIN,BY,GROUP,IN,INTO,SELECT,NOT,SET,UPDATE,DELETE,HAVING,IS,NULL,EXISTS,BETWEEN,LIKE,INNER,OUTER";
StringTokenizer st=new StringTokenizer(where);
String result="";
String token="";
int o=-1;
while (true) {
token=st.nextToken();
String test=token.startsWith("(") ? token.substring(1) : token;
if (sqlkey.indexOf(test) == -1) {
token=token.trim();
if (o != -1) result=result + " " + token;
else {
result=result + " ";
StringBuffer t=new StringBuffer();
for (int i=0; i < token.length(); i++) {
char c=token.charAt(i);
if (isOperator(c)) {
if (t.length() > 0) {
if (c == '(') result=result + t.toString();
else if (isIdentifier(t.toString()) && t.toString().indexOf('.') == -1) result=result + alias + "."+ t.toString();
else result=result + t.toString();
t=new StringBuffer();
}
result=result + c;
}
else {
t.append(c);
}
}
if (t.length() > 0) {
if ("SELECT".equalsIgnoreCase(t.toString().toUpperCase())) {
o=0;
result=result + t.toString();
}
else if (isIdentifier(t.toString()) && t.toString().indexOf('.') == -1) result=result + alias + "."+ t.toString();
else result=result + t.toString();
}
}
if (o != -1) {
for (int i=0; i < token.length(); i++) {
char c=token.charAt(i);
if (c == '(') o++;
if (c == ')') o--;
}
}
}
else {
result=result + " " + token;
if ("SELECT".equalsIgnoreCase(test)) {
o=0;
}
}
if (!st.hasMoreElements()) break;
}
return result;
}
| Add table alias to identifier in where clause |
public IntVector sortWithIndex(){
IntVector index=IntVector.seq(0,size() - 1);
sortWithIndex(0,size() - 1,index);
return index;
}
| Sorts the array in place with index returned |
private void writeQName(javax.xml.namespace.QName qname,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
java.lang.String namespaceURI=qname.getNamespaceURI();
if (namespaceURI != null) {
java.lang.String prefix=xmlWriter.getPrefix(namespaceURI);
if (prefix == null) {
prefix=generatePrefix(namespaceURI);
xmlWriter.writeNamespace(prefix,namespaceURI);
xmlWriter.setPrefix(prefix,namespaceURI);
}
if (prefix.trim().length() > 0) {
xmlWriter.writeCharacters(prefix + ":" + org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
}
else {
xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
}
}
else {
xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
}
}
| method to handle Qnames |
public boolean isUnboundedMax(){
return unboundedMax;
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public static Description createTestDescription(Class<?> clazz,String name,Annotation... annotations){
return new Description(clazz,formatDisplayName(name,clazz.getName()),annotations);
}
| Create a <code>Description</code> of a single test named <code>name</code> in the class <code>clazz</code>. Generally, this will be a leaf <code>Description</code>. |
@Override public void respond(String response){
getChannel().send().message(getUser(),response);
}
| Respond by send a message in the channel to the user that set the mode in <code>user: message</code> format |
protected void useClassAttributes(){
int[] indices;
StringBuilder range;
MekaClassAttributes catts;
String newName;
getOwner().addUndoPoint();
indices=m_PanelClassAttributes.getSelectedAttributes();
range=new StringBuilder();
for ( int index : indices) {
if (range.length() > 0) range.append(",");
range.append((index + 1));
}
catts=new MekaClassAttributes();
newName=getData().relationName().replaceFirst(" -C [0-9]+"," -C " + indices.length);
try {
catts.setAttributeIndices(range.toString());
filterData(catts,newName);
}
catch ( Exception e) {
System.err.println("Setting of class attributes failed:");
e.printStackTrace();
JOptionPane.showMessageDialog(PreprocessTab.this,"Setting of class attributes failed:\n" + e,"Error",JOptionPane.ERROR_MESSAGE);
}
}
| Sets the selected attributes as class attributes. |
public CButton(String text){
this(text,null);
}
| Creates a button with text. |
@Override public Pane createRootPane(){
BorderPane root=new BorderPane();
StackPane envView=new StackPane();
envViewCtrl=new VacuumEnvironmentViewCtrl(envView);
Parameter[] params=createParameters();
SimulationPaneBuilder builder=new SimulationPaneBuilder();
builder.defineParameters(params);
builder.defineStateView(envView);
builder.defineInitMethod(null);
builder.defineSimMethod(null);
simPaneCtrl=builder.getResultFor(root);
return root;
}
| Defines state view, parameters, and call-back functions and calls the simulation pane builder to create layout and controller objects. |
public T caseFieldAccessor(FieldAccessor object){
return null;
}
| Returns the result of interpreting the object as an instance of '<em>Field Accessor</em>'. <!-- begin-user-doc --> This implementation returns null; returning a non-null result will terminate the switch. <!-- end-user-doc --> |
public boolean wearsOutfitFromHere(final Player player){
final Outfit currentOutfit=player.getOutfit();
for ( final String outfitType : priceCalculator.dealtItems()) {
final List<Outfit> possibleOutfits=outfitTypes.get(outfitType);
for ( final Outfit possibleOutfit : possibleOutfits) {
if (possibleOutfit.isPartOf(currentOutfit)) {
return true;
}
}
}
return false;
}
| Checks whether or not the given player is currently wearing an outfit that may have been bought/lent from an NPC with this behaviour. |
public void write(@Nullable String spaceName,SwapKey key,byte[] val,@Nullable ClassLoader ldr) throws IgniteCheckedException {
assert key != null;
assert val != null;
try {
getSpi().store(spaceName,key,val,context(ldr));
}
catch ( IgniteSpiException e) {
throw new IgniteCheckedException("Failed to write to swap space [space=" + spaceName + ", key="+ key+ ", valLen="+ val.length+ ']',e);
}
}
| Writes value to swap. |
private void establecerElementosVista(HttpServletRequest request,GestionAuditoriaBI service,String module){
List modulos=(List)service.getModules();
request.setAttribute(AuditoriaConstants.LISTA_MODULOS_KEY,modulos);
List acciones=null;
if (module == null) acciones=(List)service.getActions(ArchivoModules.NONE_MODULE);
else acciones=(List)service.getActions(Integer.parseInt(module));
request.setAttribute(AuditoriaConstants.LISTA_ACCIONES_KEY,acciones);
List listaGrupos=getGestionControlUsuarios(request).getGrupos();
listaGrupos.remove(new GrupoVO(CritUsuarioVO.GLOBAL_GROUP));
listaGrupos.remove(new GrupoVO(CritUsuarioVO.GLOBAL_GROUP_ADM));
request.setAttribute(AuditoriaConstants.LISTA_GRUPOS_KEY,listaGrupos);
}
| Establece los elementos necesarios para mostrar en la vista |
public MapBackedDirectory(){
this(Collections.<K,V>emptyMap());
}
| Creates an empty directory backed by an empty Map |
public static void createIndex(Connection conn,String schema,String table,String columnList) throws SQLException {
init(conn);
PreparedStatement prep=conn.prepareStatement("INSERT INTO " + SCHEMA + ".INDEXES(SCHEMA, TABLE, COLUMNS) VALUES(?, ?, ?)");
prep.setString(1,schema);
prep.setString(2,table);
prep.setString(3,columnList);
prep.execute();
createTrigger(conn,schema,table);
indexExistingRows(conn,schema,table);
}
| Create a new full text index for a table and column list. Each table may only have one index at any time. |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:33:16.621 -0500",hash_original_method="6C96B3E47AB792BE3053A98B747C02B0",hash_generated_method="762C6F42E9E67BA3B76C7151964CBF27") public synchronized boolean hasCookies(boolean privateBrowsing){
if (!JniUtil.useChromiumHttpStack()) {
return hasCookies();
}
return nativeHasCookies(privateBrowsing);
}
| Return true if there are stored cookies. |
public StorageUnitAlternateKeyDto createStorageUnitKey(BusinessObjectDataKey businessObjectDataKey,String storageName){
StorageUnitAlternateKeyDto storageUnitKey=new StorageUnitAlternateKeyDto();
storageUnitKey.setNamespace(businessObjectDataKey.getNamespace());
storageUnitKey.setBusinessObjectDefinitionName(businessObjectDataKey.getBusinessObjectDefinitionName());
storageUnitKey.setBusinessObjectFormatUsage(businessObjectDataKey.getBusinessObjectFormatUsage());
storageUnitKey.setBusinessObjectFormatFileType(businessObjectDataKey.getBusinessObjectFormatFileType());
storageUnitKey.setBusinessObjectFormatVersion(businessObjectDataKey.getBusinessObjectFormatVersion());
storageUnitKey.setPartitionValue(businessObjectDataKey.getPartitionValue());
storageUnitKey.setSubPartitionValues(businessObjectDataKey.getSubPartitionValues());
storageUnitKey.setBusinessObjectDataVersion(businessObjectDataKey.getBusinessObjectDataVersion());
storageUnitKey.setStorageName(storageName);
return storageUnitKey;
}
| Creates a storage unit key from a business object data key and a storage name. |
public static <L,R>MutablePair<L,R> of(final L left,final R right){
return new MutablePair<L,R>(left,right);
}
| <p>Obtains an immutable pair of from two objects inferring the generic types.</p> <p>This factory allows the pair to be created using inference to obtain the generic types.</p> |
static int bitLengthForInt(int n){
return 32 - Integer.numberOfLeadingZeros(n);
}
| Package private method to return bit length for an integer. |
@Override public void run(){
amIActive=true;
String inputHeader=null;
String outputHeader=null;
String distanceOutputHeader=null;
int i;
int progress;
int row, col;
double z=0;
double distConvFactor=1.0;
double gridRes=0;
double currentVal=0;
double currentMaxVal=0;
double maxValDist=0;
double maxDist=0;
double lineSlope=0;
boolean saveDistance=false;
double azimuth=0;
double deltaX=0;
double deltaY=0;
double x=0;
int x1=0;
int x2=0;
double y=0;
int y1=0;
int y2=0;
double z1=0;
double z2=0;
double dist=0;
double slope=0;
double yIntercept=0;
int xStep=0;
int yStep=0;
double noData=0;
boolean flag=false;
double aSmallValue=-9999999;
maxDist=Double.MAX_VALUE;
if (args.length <= 0) {
showFeedback("Plugin parameters have not been set.");
return;
}
inputHeader=args[0];
outputHeader=args[1];
azimuth=Double.parseDouble(args[2]);
if (azimuth > 360 || azimuth < 0) {
azimuth=0.1;
}
if (azimuth == 0) {
azimuth=0.1;
}
if (azimuth == 180) {
azimuth=179.9;
}
if (azimuth == 360) {
azimuth=359.9;
}
if (azimuth < 180) {
lineSlope=Math.tan(Math.toRadians(90 - azimuth));
}
else {
lineSlope=Math.tan(Math.toRadians(270 - azimuth));
}
if (!args[3].toLowerCase().equals("not specified")) {
maxDist=Double.parseDouble(args[3]);
}
if (!args[4].toLowerCase().equals("not specified")) {
saveDistance=true;
distanceOutputHeader=args[4];
}
if ((inputHeader == null) || (outputHeader == null)) {
showFeedback("One or more of the input parameters have not been set properly.");
return;
}
try {
WhiteboxRaster DEM=new WhiteboxRaster(inputHeader,"r");
DEM.setForceAllDataInMemory(true);
int rows=DEM.getNumberRows();
int cols=DEM.getNumberColumns();
noData=DEM.getNoDataValue();
if (DEM.getXYUnits().toLowerCase().contains("deg") || DEM.getProjection().toLowerCase().contains("geog")) {
double midLat=(DEM.getNorth() - DEM.getSouth()) / 2.0;
if (midLat <= 90 && midLat >= -90) {
distConvFactor=(113200 * Math.cos(Math.toRadians(midLat)));
}
}
gridRes=(DEM.getCellSizeX() + DEM.getCellSizeY()) / 2 * distConvFactor;
WhiteboxRaster output=new WhiteboxRaster(outputHeader,"rw",inputHeader,WhiteboxRaster.DataType.FLOAT,noData);
output.setPreferredPalette("grey.pal");
output.setForceAllDataInMemory(true);
WhiteboxRaster outputDist=null;
if (saveDistance) {
outputDist=new WhiteboxRaster(distanceOutputHeader,"rw",inputHeader,WhiteboxRaster.DataType.FLOAT,noData);
outputDist.setPreferredPalette("blue_white_red.pal");
outputDist.setForceAllDataInMemory(true);
}
if (azimuth > 0 && azimuth <= 90) {
xStep=1;
yStep=1;
}
else if (azimuth <= 180) {
xStep=1;
yStep=-1;
}
else if (azimuth <= 270) {
xStep=-1;
yStep=-1;
}
else {
xStep=-1;
yStep=1;
}
for (row=0; row < rows; row++) {
for (col=0; col < cols; col++) {
currentVal=DEM.getValue(row,col);
if (currentVal != noData) {
yIntercept=-row - lineSlope * col;
currentMaxVal=aSmallValue;
maxValDist=aSmallValue;
x=col;
flag=true;
do {
x=x + xStep;
if (x < 0 || x >= cols) {
flag=false;
break;
}
y=(lineSlope * x + yIntercept) * -1;
if (y < 0 || y >= rows) {
flag=false;
break;
}
deltaX=(x - col) * gridRes;
deltaY=(y - row) * gridRes;
dist=Math.sqrt(deltaX * deltaX + deltaY * deltaY);
if (dist > maxDist) {
flag=false;
break;
}
y1=(int)(y);
y2=y1 + yStep * -1;
z1=DEM.getValue(y1,(int)x);
z2=DEM.getValue(y2,(int)x);
z=z1 + (y - y1) * (z2 - z1);
slope=(z - currentVal) / dist;
if (slope > currentMaxVal) {
currentMaxVal=slope;
maxValDist=dist;
}
else if (currentMaxVal < 0) {
maxValDist=dist;
}
}
while (flag);
y=-row;
flag=true;
do {
y=y + yStep;
if (-y < 0 || -y >= rows) {
flag=false;
break;
}
x=(y - yIntercept) / lineSlope;
if (x < 0 || x >= cols) {
flag=false;
break;
}
deltaX=(x - col) * gridRes;
deltaY=(-y - row) * gridRes;
dist=Math.sqrt(deltaX * deltaX + deltaY * deltaY);
if (dist > maxDist) {
flag=false;
break;
}
x1=(int)x;
x2=x1 + xStep;
if (x2 < 0 || x2 >= cols) {
flag=false;
break;
}
z1=DEM.getValue((int)-y,x1);
z2=DEM.getValue((int)y,x2);
z=z1 + (x - x1) * (z2 - z1);
slope=(z - currentVal) / dist;
if (slope > currentMaxVal) {
currentMaxVal=slope;
maxValDist=dist;
}
else if (currentMaxVal < 0) {
maxValDist=dist;
}
}
while (flag);
z=Math.toDegrees(Math.atan(currentMaxVal));
if (z < -89) {
z=0;
}
if (currentMaxVal != aSmallValue) {
output.setValue(row,col,z);
if (saveDistance) {
if (z < 0) {
maxValDist=maxValDist * -1;
}
outputDist.setValue(row,col,maxValDist);
}
}
else {
output.setValue(row,col,noData);
if (saveDistance) {
outputDist.setValue(row,col,noData);
}
}
}
}
if (cancelOp) {
cancelOperation();
return;
}
progress=(int)(100f * row / (rows - 1));
updateProgress(progress);
}
output.addMetadataEntry("Created by the " + getDescriptiveName() + " tool.");
output.addMetadataEntry("Created on " + new Date());
DEM.close();
output.close();
if (saveDistance) {
outputDist.close();
}
returnData(outputHeader);
}
catch ( OutOfMemoryError oe) {
myHost.showFeedback("An out-of-memory error has occurred during operation.");
}
catch ( Exception e) {
myHost.showFeedback("An error has occurred during operation. See log file for details.");
myHost.logException("Error in " + getDescriptiveName(),e);
}
finally {
updateProgress("Progress: ",0);
amIActive=false;
myHost.pluginComplete();
}
}
| Used to execute this plugin tool. |
@DSSafe(DSCat.SAFE_LIST) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-09-03 14:59:53.485 -0400",hash_original_method="B6CCE4550C29DDD6A02AB62B3A5D936A",hash_generated_method="979F94608D9916FD462CA7E4AAD1B55D") @Override public boolean accept(File file){
return file.canWrite();
}
| Checks to see if the file can be written to. |
private Map<SoftwareVersion,URL> parseDirectory(URL url,String input) throws IOException, RemoteRepositoryException {
Map<SoftwareVersion,URL> versions=new HashMap<SoftwareVersion,URL>();
ParserCallback callback=new ParserCallback(url,versions);
new HTMLEditor().getParser().parse(new StringReader(input.toString()),callback,true);
return versions;
}
| Parse the remote repository directory string |
public DouglasPeuckerSimplifier(Geometry inputGeom){
this.inputGeom=inputGeom;
}
| Creates a simplifier for a given geometry. |
public void reserveStock(MDDOrderLine[] lines){
BigDecimal Volume=Env.ZERO;
BigDecimal Weight=Env.ZERO;
for ( MDDOrderLine line : lines) {
MLocator locator_from=MLocator.get(getCtx(),line.getM_Locator_ID());
MLocator locator_to=MLocator.get(getCtx(),line.getM_LocatorTo_ID());
BigDecimal reserved_ordered=line.getQtyOrdered().subtract(line.getQtyReserved()).subtract(line.getQtyDelivered());
if (reserved_ordered.signum() == 0) {
MProduct product=line.getProduct();
if (product != null) {
Volume=Volume.add(product.getVolume().multiply(line.getQtyOrdered()));
Weight=Weight.add(product.getWeight().multiply(line.getQtyOrdered()));
}
continue;
}
log.fine("Line=" + line.getLine() + " - Ordered="+ line.getQtyOrdered()+ ",Reserved="+ line.getQtyReserved()+ ",Delivered="+ line.getQtyDelivered());
MProduct product=line.getProduct();
if (product != null) {
if (product.isStocked()) {
if (!MStorage.add(getCtx(),locator_to.getM_Warehouse_ID(),locator_to.getM_Locator_ID(),line.getM_Product_ID(),line.getM_AttributeSetInstance_ID(),line.getM_AttributeSetInstance_ID(),Env.ZERO,Env.ZERO,reserved_ordered,get_TrxName())) {
throw new AdempiereException();
}
if (!MStorage.add(getCtx(),locator_from.getM_Warehouse_ID(),locator_from.getM_Locator_ID(),line.getM_Product_ID(),line.getM_AttributeSetInstanceTo_ID(),line.getM_AttributeSetInstance_ID(),Env.ZERO,reserved_ordered,Env.ZERO,get_TrxName())) {
throw new AdempiereException();
}
}
line.setQtyReserved(line.getQtyReserved().add(reserved_ordered));
line.saveEx();
Volume=Volume.add(product.getVolume().multiply(line.getQtyOrdered()));
Weight=Weight.add(product.getWeight().multiply(line.getQtyOrdered()));
}
}
setVolume(Volume);
setWeight(Weight);
}
| Reserve Inventory. Counterpart: MMovement.completeIt() |
protected void addMapping(int hashIndex,int hashCode,K key,V value){
modCount++;
HashEntry<K,V> entry=createEntry(data[hashIndex],hashCode,key,value);
addEntry(entry,hashIndex);
size++;
checkCapacity();
}
| Adds a new key-value mapping into this map. <p/> This implementation calls <code>createEntry()</code>, <code>addEntry()</code> and <code>checkCapacity()</code>. It also handles changes to <code>modCount</code> and <code>size</code>. Subclasses could override to fully control adds to the map. |
private Hop simplifyWeightedSquaredLoss(Hop parent,Hop hi,int pos) throws HopsException {
Hop hnew=null;
if (hi instanceof AggUnaryOp && ((AggUnaryOp)hi).getDirection() == Direction.RowCol && ((AggUnaryOp)hi).getOp() == AggOp.SUM && hi.getInput().get(0) instanceof BinaryOp && hi.getInput().get(0).getDim2() > 1) {
BinaryOp bop=(BinaryOp)hi.getInput().get(0);
boolean appliedPattern=false;
if (bop.getOp() == OpOp2.MULT && bop.getInput().get(1) instanceof BinaryOp && bop.getInput().get(0).getDataType() == DataType.MATRIX && HopRewriteUtils.isEqualSize(bop.getInput().get(0),bop.getInput().get(1)) && ((BinaryOp)bop.getInput().get(1)).getOp() == OpOp2.POW && bop.getInput().get(1).getInput().get(1) instanceof LiteralOp && HopRewriteUtils.getDoubleValue((LiteralOp)bop.getInput().get(1).getInput().get(1)) == 2) {
Hop W=bop.getInput().get(0);
Hop tmp=bop.getInput().get(1).getInput().get(0);
if (tmp instanceof BinaryOp && ((BinaryOp)tmp).getOp() == OpOp2.MINUS && HopRewriteUtils.isEqualSize(tmp.getInput().get(0),tmp.getInput().get(1)) && tmp.getInput().get(0).getDataType() == DataType.MATRIX) {
int uvIndex=-1;
if (tmp.getInput().get(1) instanceof AggBinaryOp && HopRewriteUtils.isSingleBlock(tmp.getInput().get(1).getInput().get(0),true)) {
uvIndex=1;
}
else if (tmp.getInput().get(0) instanceof AggBinaryOp && HopRewriteUtils.isSingleBlock(tmp.getInput().get(0).getInput().get(0),true)) {
uvIndex=0;
}
if (uvIndex >= 0) {
Hop X=tmp.getInput().get((uvIndex == 0) ? 1 : 0);
Hop U=tmp.getInput().get(uvIndex).getInput().get(0);
Hop V=tmp.getInput().get(uvIndex).getInput().get(1);
if (!HopRewriteUtils.isTransposeOperation(V)) {
V=HopRewriteUtils.createTranspose(V);
}
else {
V=V.getInput().get(0);
}
if (HopRewriteUtils.isNonZeroIndicator(W,X)) {
W=new LiteralOp(1);
}
hnew=new QuaternaryOp(hi.getName(),DataType.SCALAR,ValueType.DOUBLE,OpOp4.WSLOSS,X,U,V,W,true);
HopRewriteUtils.setOutputParametersForScalar(hnew);
appliedPattern=true;
LOG.debug("Applied simplifyWeightedSquaredLoss1" + uvIndex + " (line "+ hi.getBeginLine()+ ")");
}
}
}
if (!appliedPattern && bop.getOp() == OpOp2.POW && bop.getInput().get(1) instanceof LiteralOp && HopRewriteUtils.getDoubleValue((LiteralOp)bop.getInput().get(1)) == 2 && bop.getInput().get(0) instanceof BinaryOp && bop.getInput().get(0).getDataType() == DataType.MATRIX && ((BinaryOp)bop.getInput().get(0)).getOp() == OpOp2.MINUS && HopRewriteUtils.isEqualSize(bop.getInput().get(0).getInput().get(0),bop.getInput().get(0).getInput().get(1)) && bop.getInput().get(0).getInput().get(0).getDataType() == DataType.MATRIX) {
Hop lleft=bop.getInput().get(0).getInput().get(0);
Hop lright=bop.getInput().get(0).getInput().get(1);
int wuvIndex=-1;
if (lright instanceof BinaryOp && lright.getInput().get(1) instanceof AggBinaryOp) {
wuvIndex=1;
}
else if (lleft instanceof BinaryOp && lleft.getInput().get(1) instanceof AggBinaryOp) {
wuvIndex=0;
}
if (wuvIndex >= 0) {
Hop X=bop.getInput().get(0).getInput().get((wuvIndex == 0) ? 1 : 0);
Hop tmp=bop.getInput().get(0).getInput().get(wuvIndex);
if (((BinaryOp)tmp).getOp() == OpOp2.MULT && tmp.getInput().get(0).getDataType() == DataType.MATRIX && HopRewriteUtils.isEqualSize(tmp.getInput().get(0),tmp.getInput().get(1)) && HopRewriteUtils.isSingleBlock(tmp.getInput().get(1).getInput().get(0),true)) {
Hop W=tmp.getInput().get(0);
Hop U=tmp.getInput().get(1).getInput().get(0);
Hop V=tmp.getInput().get(1).getInput().get(1);
if (!HopRewriteUtils.isTransposeOperation(V)) {
V=HopRewriteUtils.createTranspose(V);
}
else {
V=V.getInput().get(0);
}
hnew=new QuaternaryOp(hi.getName(),DataType.SCALAR,ValueType.DOUBLE,OpOp4.WSLOSS,X,U,V,W,false);
HopRewriteUtils.setOutputParametersForScalar(hnew);
appliedPattern=true;
LOG.debug("Applied simplifyWeightedSquaredLoss2" + wuvIndex + " (line "+ hi.getBeginLine()+ ")");
}
}
}
if (!appliedPattern && bop.getOp() == OpOp2.POW && bop.getInput().get(1) instanceof LiteralOp && HopRewriteUtils.getDoubleValue((LiteralOp)bop.getInput().get(1)) == 2 && bop.getInput().get(0) instanceof BinaryOp && bop.getInput().get(0).getDataType() == DataType.MATRIX && ((BinaryOp)bop.getInput().get(0)).getOp() == OpOp2.MINUS && HopRewriteUtils.isEqualSize(bop.getInput().get(0).getInput().get(0),bop.getInput().get(0).getInput().get(1)) && bop.getInput().get(0).getInput().get(0).getDataType() == DataType.MATRIX) {
Hop lleft=bop.getInput().get(0).getInput().get(0);
Hop lright=bop.getInput().get(0).getInput().get(1);
int uvIndex=-1;
if (lright instanceof AggBinaryOp && HopRewriteUtils.isSingleBlock(lright.getInput().get(0),true)) {
uvIndex=1;
}
else if (lleft instanceof AggBinaryOp && HopRewriteUtils.isSingleBlock(lleft.getInput().get(0),true)) {
uvIndex=0;
}
if (uvIndex >= 0) {
Hop X=bop.getInput().get(0).getInput().get((uvIndex == 0) ? 1 : 0);
Hop tmp=bop.getInput().get(0).getInput().get(uvIndex);
Hop W=new LiteralOp(1);
Hop U=tmp.getInput().get(0);
Hop V=tmp.getInput().get(1);
if (!HopRewriteUtils.isTransposeOperation(V)) {
V=HopRewriteUtils.createTranspose(V);
}
else {
V=V.getInput().get(0);
}
hnew=new QuaternaryOp(hi.getName(),DataType.SCALAR,ValueType.DOUBLE,OpOp4.WSLOSS,X,U,V,W,false);
HopRewriteUtils.setOutputParametersForScalar(hnew);
appliedPattern=true;
LOG.debug("Applied simplifyWeightedSquaredLoss3" + uvIndex + " (line "+ hi.getBeginLine()+ ")");
}
}
}
if (hnew != null) {
HopRewriteUtils.removeChildReferenceByPos(parent,hi,pos);
HopRewriteUtils.addChildReference(parent,hnew,pos);
hi=hnew;
}
return hi;
}
| Searches for weighted squared loss expressions and replaces them with a quaternary operator. Currently, this search includes the following three patterns: 1) sum (W * (X - U %*% t(V)) ^ 2) (post weighting) 2) sum ((X - W * (U %*% t(V))) ^ 2) (pre weighting) 3) sum ((X - (U %*% t(V))) ^ 2) (no weighting) NOTE: We include transpose into the pattern because during runtime we need to compute U%*% t(V) pointwise; having V and not t(V) at hand allows for a cache-friendly implementation without additional memory requirements for internal transpose. This rewrite is conceptually a static rewrite; however, the current MR runtime only supports U/V factors of rank up to the blocksize (1000). We enforce this contraint here during the general rewrite because this is an uncommon case. Also, the intention is to remove this constaint as soon as we generalized the runtime or hop/lop compilation. |
void listMetricDescriptors() throws IOException {
ListMetricDescriptorsResponse metricsResponse=this.monitoringService.projects().metricDescriptors().list(this.projectResource).execute();
this.outputStream.println("listMetricDescriptors response");
this.outputStream.println(metricsResponse.toPrettyString());
}
| Query to MetricDescriptors.list <p>This lists all the current metrics. Package-private to be accessible to tests. |
public void cancel(){
isCanceled.set(true);
}
| Informs this executor to stop processing and returns any results collected thus far. This method is thread-safe. |
public Map<String,String> systemInfo(){
HashMap<String,String> info=new HashMap<String,String>();
NaElement elem=new NaElement("system-get-node-info-iter");
NaElement attributesList=null;
try {
List outputElements=(List)server.getNaServer().invokeElem(elem).getChildByName("attributes-list").getChildren();
Iterator iter=outputElements.iterator();
while (iter.hasNext()) {
attributesList=(NaElement)iter.next();
for ( NaElement child : (List<NaElement>)attributesList.getChildren()) {
String name=child.getName();
info.put(name,child.getContent());
}
}
return info;
}
catch ( Exception e) {
String msg="Failed to get array system info";
log.error(msg,e);
throw new NetAppCException(msg,e);
}
}
| get array system-info. |
public MajorityLabelsetTest(String name){
super(name);
}
| Initializes the test. |
public void allocateLoadBalance(){
_loadBalanceAllocateCount.incrementAndGet();
}
| Allocate a connection for load balancing. |
public static void main(String[] args){
try (Ignite ignite=Ignition.start("examples/config/example-ignite.xml")){
System.out.println();
System.out.println(">>> Binary objects cache put-get example started.");
CacheConfiguration<Integer,Organization> cfg=new CacheConfiguration<>();
cfg.setCacheMode(CacheMode.PARTITIONED);
cfg.setName(CACHE_NAME);
cfg.setAtomicityMode(CacheAtomicityMode.ATOMIC);
try (IgniteCache<Integer,Organization> cache=ignite.getOrCreateCache(cfg)){
if (ignite.cluster().forDataNodes(cache.getName()).nodes().isEmpty()) {
System.out.println();
System.out.println(">>> This example requires remote cache node nodes to be started.");
System.out.println(">>> Please start at least 1 remote cache node.");
System.out.println(">>> Refer to example's javadoc for details on configuration.");
System.out.println();
return;
}
putGet(cache);
putGetBinary(cache);
putGetAll(cache);
putGetAllBinary(cache);
System.out.println();
}
finally {
ignite.destroyCache(CACHE_NAME);
}
}
}
| Executes example. |
public Task(String description,Date start,Date end){
this(description,new SimpleTimePeriod(start,end));
}
| Creates a new task. |
public static void w(String tag,String msg,Object... args){
if (sLevel > LEVEL_WARNING) {
return;
}
if (args.length > 0) {
msg=String.format(msg,args);
}
Log.w(tag,msg);
}
| Send a WARNING log message |
public StateMachineSecurityInterceptor(){
this(null,null);
}
| Instantiates a new state machine security interceptor. |
public void testRandomSortsOnLargeIndex() throws Exception {
final Collection<String> allFieldNames=getAllSortFieldNames();
final int initialDocs=TestUtil.nextInt(random(),100,200);
final int totalDocs=atLeast(500);
for (int i=1; i <= initialDocs; i++) {
SolrInputDocument doc=buildRandomDocument(i);
assertU(adoc(doc));
}
assertU(commit());
for ( String f : allFieldNames) {
for ( String order : new String[]{" asc"," desc"}) {
String sort=f + order + ("id".equals(f) ? "" : ", id" + order);
String rows="" + TestUtil.nextInt(random(),13,50);
SentinelIntSet ids=assertFullWalkNoDups(totalDocs,params("q","*:*","fl","id","rows",rows,"sort",sort));
assertEquals(initialDocs,ids.size());
}
}
for (int i=initialDocs + 1; i <= totalDocs; i++) {
SolrInputDocument doc=buildRandomDocument(i);
assertU(adoc(doc));
}
assertU(commit());
final int numRandomSorts=atLeast(3);
for (int i=0; i < numRandomSorts; i++) {
final String sort=buildRandomSort(allFieldNames);
final String rows="" + TestUtil.nextInt(random(),63,113);
final String fl=random().nextBoolean() ? "id" : "id,score";
final boolean matchAll=random().nextBoolean();
final String q=matchAll ? "*:*" : buildRandomQuery();
SentinelIntSet ids=assertFullWalkNoDups(totalDocs,params("q",q,"fl",fl,"rows",rows,"sort",sort));
if (matchAll) {
assertEquals(totalDocs,ids.size());
}
}
}
| randomized testing of a non-trivial number of docs using assertFullWalkNoDups |
protected void reOrganizeFeatures(){
double[] f;
Cluster best;
double v, minDistance;
for (int k=0; k < features.size(); k++) {
f=features.get(k);
best=clusters[0];
minDistance=clusters[0].getDistance(f);
for (int i=1; i < clusters.length; i++) {
v=clusters[i].getDistance(f);
if (minDistance > v) {
best=clusters[i];
minDistance=v;
}
}
best.assignMember(f);
}
}
| Re-shuffle all features. |
public int subtreeDepth() throws UnsupportedOperationException {
int sum=1;
for (int i=name.indexOf('.'); i >= 0; i=name.indexOf('.',i + 1)) {
++sum;
}
return sum;
}
| Return subtree depth of this name for purposes of determining NameConstraints minimum and maximum bounds and for calculating path lengths in name subtrees. |
@Override public QParser createParser(String qstr,SolrParams localParams,SolrParams params,SolrQueryRequest req){
return new SimpleQParser(qstr,localParams,params,req);
}
| Returns a QParser that will create a query by using Lucene's SimpleQueryParser. |
public VdcConfig toConfigParam(Properties vdcInfo){
log.info("copy {} to the sync config param",vdcInfo.getProperty(GeoServiceJob.VDC_SHORT_ID));
VdcConfig vdcConfig=new VdcConfig();
vdcConfig.setId(URIUtil.uri(vdcInfo.getProperty(GeoServiceJob.OPERATED_VDC_ID)));
vdcConfig.setShortId(vdcInfo.getProperty(GeoServiceJob.VDC_SHORT_ID));
vdcConfig.setSecretKey(vdcInfo.getProperty(GeoServiceJob.VDC_SECRETE_KEY));
String name=vdcInfo.getProperty(GeoServiceJob.VDC_NAME);
if ((name != null) && (!name.isEmpty())) {
vdcConfig.setName(name);
}
String description=vdcInfo.getProperty(GeoServiceJob.VDC_DESCRIPTION);
if ((description != null) && (!description.isEmpty())) {
vdcConfig.setDescription(description);
}
String endPnt=vdcInfo.getProperty(GeoServiceJob.VDC_API_ENDPOINT);
if (endPnt != null) {
vdcConfig.setApiEndpoint(endPnt);
}
vdcConfig.setGeoCommandEndpoint(vdcInfo.getProperty(GeoServiceJob.VDC_GEOCOMMAND_ENDPOINT));
vdcConfig.setGeoDataEndpoint(vdcInfo.getProperty(GeoServiceJob.VDC_GEODATA_ENDPOINT));
return vdcConfig;
}
| Build VdcConfig for a vdc for SyncVdcConfig call |
final public SyntaxTreeNode LetIn() throws ParseException {
SyntaxTreeNode zn[]=new SyntaxTreeNode[4];
SyntaxTreeNode tn;
Token t;
bpa("Case Other Arm");
t=jj_consume_token(LET);
zn[0]=new SyntaxTreeNode(mn,t);
zn[1]=LetDefinitions();
t=jj_consume_token(LETIN);
zn[2]=new SyntaxTreeNode(mn,t);
zn[3]=Expression();
epa();
{
if (true) return new SyntaxTreeNode(mn,N_LetIn,zn);
}
throw new Error("Missing return statement in function");
}
| LetIn ::= <LET> LetDefinitions() <LETIN> Expression() * It produces a SyntaxTreeNode tn with the four heirs "LET", LetDefinitions, "IN", Expression in tn.zero. |
public final String toString(byte[] buffer){
return toString(buffer,0,buffer.length);
}
| Convert the byte buffer to a string using this instance's character encoding. |
public static <T>T checkNotNull(T reference){
if (reference == null) {
throw new IllegalArgumentException();
}
return reference;
}
| Check if the reference is not null. This differs from Guava that throws Illegal Argument Exception |
public void add(final URI uri){
this.uris.add(uri);
}
| Adds a new URI to the list of redirects. |
@RequestMapping(value="/{id}",method=RequestMethod.DELETE) @ResponseBody public RestWrapper delete(@PathVariable("id") Integer processTemplateId,Principal principal){
RestWrapper restWrapper=null;
try {
processTemplateDAO.delete(processTemplateId);
restWrapper=new RestWrapper(null,RestWrapper.OK);
LOGGER.info("Record with ID:" + processTemplateId + " deleted from ProcessTemplate by User:"+ principal.getName());
}
catch ( Exception e) {
LOGGER.error(e);
restWrapper=new RestWrapper(e.getMessage(),RestWrapper.ERROR);
}
return restWrapper;
}
| This method calls proc DeleteProcess and deletes a record from process table corresponding to processId passed. |
public AccountHeaderBuilder withOnlySmallProfileImagesVisible(boolean onlySmallProfileImagesVisible){
this.mOnlySmallProfileImagesVisible=onlySmallProfileImagesVisible;
return this;
}
| define if only the small profile images should be visible |
public static boolean isGreater(Date d1,Date d2){
if (d1 == null || d2 == null) {
return false;
}
return d1.compareTo(d2) > 0;
}
| Returns <code>true</code> if the date d1 is greater than date d2. Returns <code>false</code> if either d1 or d2 are <code>null</code>. |
private ReplaceTokens.Token createPortToken(){
String port=getPropertyValue(ServletPropertySet.PORT);
if (port == null) {
port=JRun4xPropertySet.DEFAULT_PORT;
}
ReplaceTokens.Token tokenPort=new ReplaceTokens.Token();
tokenPort.setKey(ServletPropertySet.PORT);
tokenPort.setValue(port);
return tokenPort;
}
| Creates the port token for inclusion in jrun.xml . |
public Object runSafely(Catbert.FastStack stack) throws Exception {
String n=getString(stack);
String k=getString(stack);
String r=getString(stack);
if (!Sage.WINDOWS_OS) return "";
return Sage.readStringValue(Sage.getHKEYForName(r),k,n);
}
| Returns a string value from the Windows registry for the specified root, key and name(Windows only) Acceptable values for the Root are: "HKCR", "HKEY_CLASSES_ROOT", "HKCC", "HKEY_CURRENT_CONFIG", "HKCU", "HKEY_CURRENT_USER", "HKU", "HKEY_USERS", "HKLM" or "HKEY_LOCAL_MACHINE" (HKLM is the default if nothing matches) |
public AccountMetaData(final AccountStatus status,final AccountRemoteStatus remoteStatus,final List<AccountInfo> cosignatoryOf,final List<AccountInfo> cosignatories){
this.status=status;
this.remoteStatus=remoteStatus;
this.cosignatoryOf=cosignatoryOf;
this.cosignatories=cosignatories;
}
| Creates a new meta data. |
public boolean initialise(ServletContext servletContext){
boolean ok=super.initialise(servletContext);
if (ok) {
String displayName=getDisplayName();
log.debug("loaded outbound rule " + displayName + " ("+ from+ ", "+ to+ ')');
}
else {
log.debug("failed to load outbound rule");
}
if (errors.size() > 0) {
ok=false;
}
valid=ok;
return ok;
}
| Will initialise the outbound rule. |
public void doWindowOpen(Object parm){
if (parm instanceof String) {
jTextArea1.setText((String)parm);
}
}
| doWindowOpen() - |
private boolean isExcluded(String[] cargoFiles,String filename){
if (cargoFiles == null) {
return false;
}
for ( String cargoFile : cargoFiles) {
if (cargoFile.equals(filename)) {
return true;
}
}
return false;
}
| Check if file with name <code>filename</code> is one of cargo resources file. |
public Builder<V> dimensions(int dimensions){
this.dimensions=dimensions;
return this;
}
| Set the dimensions. |
public String toString(){
return representation;
}
| Returns the string representation. |
public AbstractSailImplConfig(){
}
| Create a new RepositoryConfigImpl. |
@Override public String toString(){
return "[SSL: " + super.toString() + "]";
}
| Provides a brief description of this SSL socket. |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.