code
stringlengths
4
1.01M
language
stringclasses
2 values
# Spongiuspinus Martin, 1971 GENUS #### Status ACCEPTED #### According to Interim Register of Marine and Nonmarine Genera #### Published in Boln R. Soc. esp. Hist. Nat. (Geol. ) 69: 224. #### Original name null ### Remarks null
Java
# Macaranga lancifolia Pax SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
Java
# Atriplex arabicum Ehrenb. ex Boiss. SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
Java
# Metasphaeria urostigymatis Speg. SPECIES #### Status SYNONYM #### According to Index Fungorum #### Published in null #### Original name Metasphaeria urostigymatis Speg. ### Remarks null
Java
# Sericographis haplostachya Nees SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
Java
# Rhyssostelma Decne. GENUS #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
Java
# Usnea comosa f. isidiella Räsänen FORM #### Status ACCEPTED #### According to Index Fungorum #### Published in Ann. bot. Soc. Zool. -Bot. fenn. Vanamo 2(1): 9 (1932) #### Original name Usnea comosa f. isidiella Räsänen ### Remarks null
Java
# Rhodymenia preissiana Sonder SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
Java
# Sphacelotheca furcata var. furcata Maire VARIETY #### Status ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Sphacelotheca furcata var. furcata Maire ### Remarks null
Java
# Rubus semiapiculatus var. malaconeurus (Sudre) Sudre VARIETY #### Status DOUBTFUL #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
Java
<?php /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * */ /** * Locale test case. */ class LocaleTest extends PHPUnit_Framework_TestCase { /** * @var Locale */ private $Locale; /** * Prepares the environment before running a test. */ protected function setUp() { parent::setUp(); $this->Locale = new Locale('EN', 'US'); } /** * Cleans up the environment after running a test. */ protected function tearDown() { $this->Locale = null; parent::tearDown(); } /** * Constructs the test case. */ public function __construct() { } /** * Tests Locale->__construct() */ public function test__construct() { $this->Locale->__construct('EN', 'US'); } /** * Tests Locale->equals() */ public function testEquals() { $locale = new Locale('EN', 'US'); $this->assertTrue($this->Locale->equals($locale)); } /** * Tests Locale->getCountry() */ public function testGetCountry() { $this->assertEquals('US', $this->Locale->getCountry()); } /** * Tests Locale->getLanguage() */ public function testGetLanguage() { $this->assertEquals('EN', $this->Locale->getLanguage()); } }
Java
module Dapp module Config class Config < Directive::Base def dev_mode @_dev_mode = true end def _dev_mode !!@_dev_mode end def after_parsing! do_all!('_after_parsing!') end def validate! do_all!('_validate!') end end end end
Java
using System; using System.IO; namespace Glass.Mapper.Sc { public class RenderingResult: IDisposable { private readonly TextWriter _writer; private readonly string _firstPart; private readonly string _lastPart; public RenderingResult(TextWriter writer, string firstPart, string lastPart) { _writer = writer; _firstPart = firstPart; _lastPart = lastPart; _writer.Write(_firstPart); } public void Dispose() { _writer.Write(_lastPart); } } }
Java
# Eupteron acuminatum (Wight) Miq. SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
Java
/** * Created by Jacky.Gao on 2017-02-09. */ import {alert} from '../MsgBox.js'; export default class EditPropertyConditionDialog{ constructor(conditions){ this.conditions=conditions; this.dialog=$(`<div class="modal fade" role="dialog" aria-hidden="true" style="z-index: 11001"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true"> &times; </button> <h4 class="modal-title"> ${window.i18n.dialog.editPropCondition.title} </h4> </div> <div class="modal-body"></div> <div class="modal-footer"></div> </div> </div> </div>`); const body=this.dialog.find('.modal-body'),footer=this.dialog.find(".modal-footer"); this.init(body,footer); } init(body,footer){ const _this=this; this.joinGroup=$(`<div class="form-group"><label>${window.i18n.dialog.editPropCondition.relation}</label></div>`); this.joinSelect=$(`<select class="form-control" style="display: inline-block;width:430px;"> <option value="and">${window.i18n.dialog.editPropCondition.and}</option> <option value="or">${window.i18n.dialog.editPropCondition.or}</option> </select>`); this.joinGroup.append(this.joinSelect); body.append(this.joinGroup); const leftGroup=$(`<div class="form-group"><label>${window.i18n.dialog.editPropCondition.leftValue}</label></div>`); this.leftTypeSelect=$(`<select class="form-control" style="display: inline-block;width: inherit"> <option value="current">${window.i18n.dialog.editPropCondition.currentValue}</option> <option value="property">${window.i18n.dialog.editPropCondition.property}</option> <option value="expression">${window.i18n.dialog.editPropCondition.expression}</option> </select>`); leftGroup.append(this.leftTypeSelect); this.propertyGroup=$(`<span style="margin-left: 10px"><label>${window.i18n.dialog.editPropCondition.propName}</label></span>`); this.propertySelect=$(`<select class="form-control" style="display: inline-block;width:320px;"></select>`); this.propertyGroup.append(this.propertySelect); leftGroup.append(this.propertyGroup); body.append(leftGroup); this.exprGroup=$(`<span style="margin-left: 10px"><label>${window.i18n.dialog.editPropCondition.expr}</label></span>`); this.exprEditor=$(`<input type="text" style="display: inline-block;width:320px;" class="form-control">`); this.exprGroup.append(this.exprEditor); leftGroup.append(this.exprGroup); this.exprEditor.change(function(){ const val=$(this).val(); const url=window._server+'/designer/conditionScriptValidation'; $.ajax({ url, type:'POST', data:{content:val}, success:function(errors){ if(errors.length>0){ alert(`${val} ${window.i18n.dialog.editPropCondition.syntaxError}`); } } }); }); this.leftTypeSelect.change(function(){ const val=$(this).val(); if(val==='current'){ _this.exprGroup.hide(); _this.propertyGroup.hide(); }else if(val==='property'){ _this.exprGroup.hide(); _this.propertyGroup.show(); }else{ _this.propertyGroup.hide(); _this.exprGroup.show(); } }); const operatorGroup=$(`<div class="form-group"><label>${window.i18n.dialog.editPropCondition.operator}</label></div>`); this.operatorSelect=$(`<select class="form-control" style="display: inline-block;width:490px;"> <option value=">">${window.i18n.dialog.editPropCondition.greater}</option> <option value=">=">${window.i18n.dialog.editPropCondition.greaterEquals}</option> <option value="<">${window.i18n.dialog.editPropCondition.less}</option> <option value="<=">${window.i18n.dialog.editPropCondition.lessEquals}</option> <option value="==">${window.i18n.dialog.editPropCondition.equals}</option> <option value="!=">${window.i18n.dialog.editPropCondition.notEquals}</option> <option value="in">${window.i18n.dialog.editPropCondition.in}</option> <option value="like">${window.i18n.dialog.editPropCondition.like}</option> </select>`); operatorGroup.append(this.operatorSelect); body.append(operatorGroup); const valueGroup=$(`<div class="form-group"><label>${window.i18n.dialog.editPropCondition.valueExpr}</label></div>`); this.valueEditor=$(`<input type="text" class="form-control" style="display: inline-block;width:477px;">`); valueGroup.append(this.valueEditor); body.append(valueGroup); this.valueEditor.change(function(){ const val=$(this).val(); const url=window._server+'/designer/conditionScriptValidation'; $.ajax({ url, type:'POST', data:{content:val}, success:function(errors){ if(errors.length>0){ alert(`${val} ${window.i18n.dialog.editPropCondition.syntaxError}`); } } }); }); const button=$(`<button class="btn btn-default">${window.i18n.dialog.editPropCondition.ok}</button>`); button.click(function(){ let property=_this.propertySelect.val(),op=_this.operatorSelect.val(),value=_this.valueEditor.val(),join=_this.joinSelect.val(),type=_this.leftTypeSelect.val(),expr=_this.exprEditor.val(); if (type === 'property') { if (property === '') { alert(`${window.i18n.dialog.editPropCondition.selectProp}`); return; } } else if(type==='expression') { if(expr===''){ alert(`${window.i18n.dialog.editPropCondition.leftValueExpr}`); return; } property=expr; }else{ property = null; } if(type==='current'){ type="property"; } if (op === '') { alert(`${window.i18n.dialog.editPropCondition.selectOperator}`); return; } if (value === '') { alert(`${window.i18n.dialog.editPropCondition.inputExpr}`); return; } if (_this.condition) { if (_this.condition.join) { _this.callback.call(_this,type, property, op, value, join); } else { _this.callback.call(_this,type, property, op, value); } } else if (_this.conditions.length > 0) { _this.callback.call(_this,type, property, op, value, join); } else { _this.callback.call(_this,type, property, op, value); } _this.dialog.modal('hide'); }); footer.append(button); } show(callback,fields,condition){ this.callback=callback; this.condition=condition; this.type='current'; if(condition){ this.type=condition.type; if(condition.join){ this.joinGroup.show(); }else{ this.joinGroup.hide(); } }else{ if(this.conditions.length>0){ this.joinGroup.show(); }else{ this.joinGroup.hide(); } } this.propertySelect.empty(); for(let field of fields){ this.propertySelect.append(`<option>${field.name}</option>`); } if(condition){ if(this.type==='expression'){ this.leftTypeSelect.val("expression"); this.exprEditor.val(condition.left); this.propertyGroup.hide(); this.exprGroup.show(); }else{ if(condition.left && condition.left!==''){ this.propertySelect.val(condition.left); this.leftTypeSelect.val("property"); this.propertyGroup.show(); }else{ this.leftTypeSelect.val("current"); this.propertyGroup.hide(); } this.exprGroup.hide(); } this.operatorSelect.val(condition.operation || condition.op); this.valueEditor.val(condition.right); this.joinSelect.val(condition.join); }else{ this.leftTypeSelect.val("current"); this.propertyGroup.hide(); this.exprGroup.hide(); } this.dialog.modal('show'); } }
Java
from collections import defaultdict import codecs def count(corpus, output_file): debug = False dic = defaultdict(int) other = set() fout = codecs.open(output_file, 'w', 'utf8') for line in open(corpus, 'r'): words = line.split() for word in words: if len(word) % 3 == 0: for i in xrange(len(word) / 3): dic[word[i:i+3]] += 1 else: other.add(word) fout.write('%i %i\n' % (len(dic), len(other))) record_list = [(y, x) for x, y in dic.items()] record_list.sort() record_list.reverse() i = 0 for x, y in record_list: #print y.decode('utf8'), x try: yy = y.decode('GBK') except: print y yy = 'N/A' fout.write('%s %i\n' % (yy, x)) i += 1 if i > 10 and debug: break other_list = list(other) other_list.sort() for item in other_list: #print item.decode('utf8') item2 = item.decode('utf8') fout.write(item2) fout.write('\n') i += 1 if i > 20 and debug: break fout.close() if __name__ =='__main__': count('data/train.zh_parsed', 'output/count.zh') count('data/train.ja_parsed', 'output/count.ja')
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_102) on Wed Nov 02 19:53:02 IST 2016 --> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>org.apache.solr.update.processor Class Hierarchy (Solr 6.3.0 API)</title> <meta name="date" content="2016-11-02"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="org.apache.solr.update.processor Class Hierarchy (Solr 6.3.0 API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li class="navBarCell1Rev">Tree</li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../org/apache/solr/update/package-tree.html">Prev</a></li> <li><a href="../../../../../org/apache/solr/util/package-tree.html">Next</a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/apache/solr/update/processor/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 class="title">Hierarchy For Package org.apache.solr.update.processor</h1> <span class="packageHierarchyLabel">Package Hierarchies:</span> <ul class="horizontal"> <li><a href="../../../../../overview-tree.html">All Packages</a></li> </ul> </div> <div class="contentContainer"> <h2 title="Class Hierarchy">Class Hierarchy</h2> <ul> <li type="circle">java.lang.<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><span class="typeNameLink">Object</span></a> <ul> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/AtomicUpdateDocumentMerger.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">AtomicUpdateDocumentMerger</span></a></li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/DistributedUpdateProcessor.RequestReplicationTracker.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">DistributedUpdateProcessor.RequestReplicationTracker</span></a></li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/FieldMutatingUpdateProcessorFactory.SelectorParams.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">FieldMutatingUpdateProcessorFactory.SelectorParams</span></a></li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/Signature.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">Signature</span></a> <ul> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/Lookup3Signature.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">Lookup3Signature</span></a></li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/MD5Signature.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">MD5Signature</span></a> <ul> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/TextProfileSignature.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">TextProfileSignature</span></a></li> </ul> </li> </ul> </li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/TemplateUpdateProcessorFactory.Resolved.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">TemplateUpdateProcessorFactory.Resolved</span></a></li> <li type="circle">java.lang.<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Throwable.html?is-external=true" title="class or interface in java.lang"><span class="typeNameLink">Throwable</span></a> (implements java.io.<a href="https://docs.oracle.com/javase/8/docs/api/java/io/Serializable.html?is-external=true" title="class or interface in java.io">Serializable</a>) <ul> <li type="circle">java.lang.<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Exception.html?is-external=true" title="class or interface in java.lang"><span class="typeNameLink">Exception</span></a> <ul> <li type="circle">java.lang.<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/RuntimeException.html?is-external=true" title="class or interface in java.lang"><span class="typeNameLink">RuntimeException</span></a> <ul> <li type="circle">org.apache.solr.common.<a href="../../../../../../solr-solrj/org/apache/solr/common/SolrException.html?is-external=true" title="class or interface in org.apache.solr.common"><span class="typeNameLink">SolrException</span></a> <ul> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/DistributedUpdateProcessor.DistributedUpdatesAsyncException.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">DistributedUpdateProcessor.DistributedUpdatesAsyncException</span></a></li> </ul> </li> </ul> </li> </ul> </li> </ul> </li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/UpdateRequestProcessor.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">UpdateRequestProcessor</span></a> <ul> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/DistributedUpdateProcessor.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">DistributedUpdateProcessor</span></a> <ul> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/CdcrUpdateProcessor.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">CdcrUpdateProcessor</span></a></li> </ul> </li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/FieldMutatingUpdateProcessor.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">FieldMutatingUpdateProcessor</span></a> <ul> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/AllValuesOrNoneFieldMutatingUpdateProcessor.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">AllValuesOrNoneFieldMutatingUpdateProcessor</span></a></li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/FieldValueMutatingUpdateProcessor.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">FieldValueMutatingUpdateProcessor</span></a></li> </ul> </li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/RegexpBoostProcessor.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">RegexpBoostProcessor</span></a></li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/TolerantUpdateProcessor.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">TolerantUpdateProcessor</span></a></li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/URLClassifyProcessor.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">URLClassifyProcessor</span></a></li> </ul> </li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/UpdateRequestProcessorChain.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">UpdateRequestProcessorChain</span></a> (implements org.apache.solr.util.plugin.<a href="../../../../../org/apache/solr/util/plugin/PluginInfoInitialized.html" title="interface in org.apache.solr.util.plugin">PluginInfoInitialized</a>)</li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/UpdateRequestProcessorChain.ProcessorInfo.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">UpdateRequestProcessorChain.ProcessorInfo</span></a></li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/UpdateRequestProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">UpdateRequestProcessorFactory</span></a> (implements org.apache.solr.util.plugin.<a href="../../../../../org/apache/solr/util/plugin/NamedListInitializedPlugin.html" title="interface in org.apache.solr.util.plugin">NamedListInitializedPlugin</a>) <ul> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/AbstractDefaultValueUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">AbstractDefaultValueUpdateProcessorFactory</span></a> <ul> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/DefaultValueUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">DefaultValueUpdateProcessorFactory</span></a></li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/TimestampUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">TimestampUpdateProcessorFactory</span></a></li> </ul> </li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/AddSchemaFieldsUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">AddSchemaFieldsUpdateProcessorFactory</span></a> (implements org.apache.solr.util.plugin.<a href="../../../../../org/apache/solr/util/plugin/SolrCoreAware.html" title="interface in org.apache.solr.util.plugin">SolrCoreAware</a>)</li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/CdcrUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">CdcrUpdateProcessorFactory</span></a> (implements org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/DistributingUpdateProcessorFactory.html" title="interface in org.apache.solr.update.processor">DistributingUpdateProcessorFactory</a>)</li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/ClassificationUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">ClassificationUpdateProcessorFactory</span></a></li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/CloneFieldUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">CloneFieldUpdateProcessorFactory</span></a> (implements org.apache.solr.util.plugin.<a href="../../../../../org/apache/solr/util/plugin/SolrCoreAware.html" title="interface in org.apache.solr.util.plugin">SolrCoreAware</a>)</li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/DistributedUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">DistributedUpdateProcessorFactory</span></a> (implements org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/DistributingUpdateProcessorFactory.html" title="interface in org.apache.solr.update.processor">DistributingUpdateProcessorFactory</a>)</li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/DocBasedVersionConstraintsProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">DocBasedVersionConstraintsProcessorFactory</span></a> (implements org.apache.solr.util.plugin.<a href="../../../../../org/apache/solr/util/plugin/SolrCoreAware.html" title="interface in org.apache.solr.util.plugin">SolrCoreAware</a>, org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/UpdateRequestProcessorFactory.RunAlways.html" title="interface in org.apache.solr.update.processor">UpdateRequestProcessorFactory.RunAlways</a>)</li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/DocExpirationUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">DocExpirationUpdateProcessorFactory</span></a> (implements org.apache.solr.util.plugin.<a href="../../../../../org/apache/solr/util/plugin/SolrCoreAware.html" title="interface in org.apache.solr.util.plugin">SolrCoreAware</a>)</li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/FieldMutatingUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">FieldMutatingUpdateProcessorFactory</span></a> (implements org.apache.solr.util.plugin.<a href="../../../../../org/apache/solr/util/plugin/SolrCoreAware.html" title="interface in org.apache.solr.util.plugin">SolrCoreAware</a>) <ul> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/ConcatFieldUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">ConcatFieldUpdateProcessorFactory</span></a></li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/CountFieldValuesUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">CountFieldValuesUpdateProcessorFactory</span></a></li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/FieldLengthUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">FieldLengthUpdateProcessorFactory</span></a></li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/FieldValueSubsetUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">FieldValueSubsetUpdateProcessorFactory</span></a> <ul> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/FirstFieldValueUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">FirstFieldValueUpdateProcessorFactory</span></a></li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/LastFieldValueUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">LastFieldValueUpdateProcessorFactory</span></a></li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/MaxFieldValueUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">MaxFieldValueUpdateProcessorFactory</span></a></li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/MinFieldValueUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">MinFieldValueUpdateProcessorFactory</span></a></li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/UniqFieldsUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">UniqFieldsUpdateProcessorFactory</span></a></li> </ul> </li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/HTMLStripFieldUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">HTMLStripFieldUpdateProcessorFactory</span></a></li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/IgnoreFieldUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">IgnoreFieldUpdateProcessorFactory</span></a></li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/ParseBooleanFieldUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">ParseBooleanFieldUpdateProcessorFactory</span></a></li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/ParseDateFieldUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">ParseDateFieldUpdateProcessorFactory</span></a></li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/ParseNumericFieldUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">ParseNumericFieldUpdateProcessorFactory</span></a> <ul> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/ParseDoubleFieldUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">ParseDoubleFieldUpdateProcessorFactory</span></a></li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/ParseFloatFieldUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">ParseFloatFieldUpdateProcessorFactory</span></a></li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/ParseIntFieldUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">ParseIntFieldUpdateProcessorFactory</span></a></li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/ParseLongFieldUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">ParseLongFieldUpdateProcessorFactory</span></a></li> </ul> </li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/PreAnalyzedUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">PreAnalyzedUpdateProcessorFactory</span></a></li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/RegexReplaceProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">RegexReplaceProcessorFactory</span></a></li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/RemoveBlankFieldUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">RemoveBlankFieldUpdateProcessorFactory</span></a></li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/TrimFieldUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">TrimFieldUpdateProcessorFactory</span></a></li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/TruncateFieldUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">TruncateFieldUpdateProcessorFactory</span></a></li> </ul> </li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/FieldNameMutatingUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">FieldNameMutatingUpdateProcessorFactory</span></a></li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/IgnoreCommitOptimizeUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">IgnoreCommitOptimizeUpdateProcessorFactory</span></a></li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/LogUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">LogUpdateProcessorFactory</span></a> (implements org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/UpdateRequestProcessorFactory.RunAlways.html" title="interface in org.apache.solr.update.processor">UpdateRequestProcessorFactory.RunAlways</a>)</li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/NoOpDistributingUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">NoOpDistributingUpdateProcessorFactory</span></a> (implements org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/DistributingUpdateProcessorFactory.html" title="interface in org.apache.solr.update.processor">DistributingUpdateProcessorFactory</a>)</li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/RegexpBoostProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">RegexpBoostProcessorFactory</span></a></li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/RunUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">RunUpdateProcessorFactory</span></a></li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/SignatureUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">SignatureUpdateProcessorFactory</span></a> (implements org.apache.solr.util.plugin.<a href="../../../../../org/apache/solr/util/plugin/SolrCoreAware.html" title="interface in org.apache.solr.util.plugin">SolrCoreAware</a>)</li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/SimpleUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">SimpleUpdateProcessorFactory</span></a> <ul> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/TemplateUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">TemplateUpdateProcessorFactory</span></a></li> </ul> </li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/StatelessScriptUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">StatelessScriptUpdateProcessorFactory</span></a> (implements org.apache.solr.util.plugin.<a href="../../../../../org/apache/solr/util/plugin/SolrCoreAware.html" title="interface in org.apache.solr.util.plugin">SolrCoreAware</a>)</li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/TolerantUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">TolerantUpdateProcessorFactory</span></a> (implements org.apache.solr.util.plugin.<a href="../../../../../org/apache/solr/util/plugin/SolrCoreAware.html" title="interface in org.apache.solr.util.plugin">SolrCoreAware</a>, org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/UpdateRequestProcessorFactory.RunAlways.html" title="interface in org.apache.solr.update.processor">UpdateRequestProcessorFactory.RunAlways</a>)</li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/URLClassifyProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">URLClassifyProcessorFactory</span></a></li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/UUIDUpdateProcessorFactory.html" title="class in org.apache.solr.update.processor"><span class="typeNameLink">UUIDUpdateProcessorFactory</span></a></li> </ul> </li> </ul> </li> </ul> <h2 title="Interface Hierarchy">Interface Hierarchy</h2> <ul> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/DistributingUpdateProcessorFactory.html" title="interface in org.apache.solr.update.processor"><span class="typeNameLink">DistributingUpdateProcessorFactory</span></a></li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/FieldMutatingUpdateProcessor.FieldNameSelector.html" title="interface in org.apache.solr.update.processor"><span class="typeNameLink">FieldMutatingUpdateProcessor.FieldNameSelector</span></a></li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/ScriptEngineCustomizer.html" title="interface in org.apache.solr.update.processor"><span class="typeNameLink">ScriptEngineCustomizer</span></a></li> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/UpdateRequestProcessorFactory.RunAlways.html" title="interface in org.apache.solr.update.processor"><span class="typeNameLink">UpdateRequestProcessorFactory.RunAlways</span></a></li> </ul> <h2 title="Enum Hierarchy">Enum Hierarchy</h2> <ul> <li type="circle">java.lang.<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><span class="typeNameLink">Object</span></a> <ul> <li type="circle">java.lang.<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Enum.html?is-external=true" title="class or interface in java.lang"><span class="typeNameLink">Enum</span></a>&lt;E&gt; (implements java.lang.<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html?is-external=true" title="class or interface in java.lang">Comparable</a>&lt;T&gt;, java.io.<a href="https://docs.oracle.com/javase/8/docs/api/java/io/Serializable.html?is-external=true" title="class or interface in java.io">Serializable</a>) <ul> <li type="circle">org.apache.solr.update.processor.<a href="../../../../../org/apache/solr/update/processor/DistributedUpdateProcessor.DistribPhase.html" title="enum in org.apache.solr.update.processor"><span class="typeNameLink">DistributedUpdateProcessor.DistribPhase</span></a></li> </ul> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li>Use</li> <li class="navBarCell1Rev">Tree</li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../org/apache/solr/update/package-tree.html">Prev</a></li> <li><a href="../../../../../org/apache/solr/util/package-tree.html">Next</a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/apache/solr/update/processor/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small> <i>Copyright &copy; 2000-2016 Apache Software Foundation. All Rights Reserved.</i> <script src='../../../../../prettify.js' type='text/javascript'></script> <script type='text/javascript'> (function(){ var oldonload = window.onload; if (typeof oldonload != 'function') { window.onload = prettyPrint; } else { window.onload = function() { oldonload(); prettyPrint(); } } })(); </script> </small></p> </body> </html>
Java
/* * Copyright 2017 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thoughtworks.go.config.materials.git; import com.googlecode.junit.ext.JunitExtRunner; import com.thoughtworks.go.domain.materials.Modification; import com.thoughtworks.go.domain.materials.RevisionContext; import com.thoughtworks.go.domain.materials.TestSubprocessExecutionContext; import com.thoughtworks.go.domain.materials.git.GitCommand; import com.thoughtworks.go.domain.materials.git.GitTestRepo; import com.thoughtworks.go.domain.materials.mercurial.StringRevision; import com.thoughtworks.go.helper.TestRepo; import com.thoughtworks.go.util.SystemEnvironment; import com.thoughtworks.go.util.TestFileUtil; import org.hamcrest.Matchers; import org.hamcrest.core.Is; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.thoughtworks.go.domain.materials.git.GitTestRepo.*; import static com.thoughtworks.go.util.command.ProcessOutputStreamConsumer.inMemoryConsumer; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @RunWith(JunitExtRunner.class) public class GitMaterialShallowCloneTest { private GitTestRepo repo; private File workingDir; @Before public void setup() throws Exception { repo = new GitTestRepo(); workingDir = TestFileUtil.createUniqueTempFolder("working"); } @After public void teardown() throws Exception { TestRepo.internalTearDown(); } @Test public void defaultShallowFlagIsOff() throws Exception { assertThat(new GitMaterial(repo.projectRepositoryUrl()).isShallowClone(), is(false)); assertThat(new GitMaterial(repo.projectRepositoryUrl(), null).isShallowClone(), is(false)); assertThat(new GitMaterial(repo.projectRepositoryUrl(), true).isShallowClone(), is(true)); assertThat(new GitMaterial(new GitMaterialConfig(repo.projectRepositoryUrl())).isShallowClone(), is(false)); assertThat(new GitMaterial(new GitMaterialConfig(repo.projectRepositoryUrl(), GitMaterialConfig.DEFAULT_BRANCH, true)).isShallowClone(), is(true)); assertThat(new GitMaterial(new GitMaterialConfig(repo.projectRepositoryUrl(), GitMaterialConfig.DEFAULT_BRANCH, false)).isShallowClone(), is(false)); TestRepo.internalTearDown(); } @Test public void shouldGetLatestModificationWithShallowClone() throws IOException { GitMaterial material = new GitMaterial(repo.projectRepositoryUrl(), true); List<Modification> mods = material.latestModification(workingDir, context()); assertThat(mods.size(), is(1)); assertThat(mods.get(0).getComment(), Matchers.is("Added 'run-till-file-exists' ant target")); assertThat(localRepoFor(material).isShallow(), is(true)); assertThat(localRepoFor(material).containsRevisionInBranch(REVISION_0), is(false)); assertThat(localRepoFor(material).currentRevision(), is(REVISION_4.getRevision())); } @Test public void shouldGetModificationSinceANotInitiallyClonedRevision() { GitMaterial material = new GitMaterial(repo.projectRepositoryUrl(), true); List<Modification> modifications = material.modificationsSince(workingDir, REVISION_0, context()); assertThat(modifications.size(), is(4)); assertThat(modifications.get(0).getRevision(), is(REVISION_4.getRevision())); assertThat(modifications.get(0).getComment(), is("Added 'run-till-file-exists' ant target")); assertThat(modifications.get(1).getRevision(), is(REVISION_3.getRevision())); assertThat(modifications.get(1).getComment(), is("adding build.xml")); assertThat(modifications.get(2).getRevision(), is(REVISION_2.getRevision())); assertThat(modifications.get(2).getComment(), is("Created second.txt from first.txt")); assertThat(modifications.get(3).getRevision(), is(REVISION_1.getRevision())); assertThat(modifications.get(3).getComment(), is("Added second line")); } @Test public void shouldBeAbleToUpdateToRevisionNotFetched() { GitMaterial material = new GitMaterial(repo.projectRepositoryUrl(), true); material.updateTo(inMemoryConsumer(), workingDir, new RevisionContext(REVISION_3, REVISION_2, 2), context()); assertThat(localRepoFor(material).currentRevision(), is(REVISION_3.getRevision())); assertThat(localRepoFor(material).containsRevisionInBranch(REVISION_2), is(true)); assertThat(localRepoFor(material).containsRevisionInBranch(REVISION_3), is(true)); } @Test public void configShouldIncludesShallowFlag() { GitMaterialConfig shallowConfig = (GitMaterialConfig) new GitMaterial(repo.projectRepositoryUrl(), true).config(); assertThat(shallowConfig.isShallowClone(), is(true)); GitMaterialConfig normalConfig = (GitMaterialConfig) new GitMaterial(repo.projectRepositoryUrl(), null).config(); assertThat(normalConfig.isShallowClone(), is(false)); } @Test public void xmlAttributesShouldIncludesShallowFlag() { GitMaterial material = new GitMaterial(repo.projectRepositoryUrl(), true); assertThat(material.getAttributesForXml().get("shallowClone"), Is.<Object>is(true)); } @Test public void attributesShouldIncludeShallowFlag() { GitMaterial material = new GitMaterial(repo.projectRepositoryUrl(), true); Map gitConfig = (Map) (material.getAttributes(false).get("git-configuration")); assertThat(gitConfig.get("shallow-clone"), Is.<Object>is(true)); } @Test public void shouldConvertExistingRepoToFullRepoWhenShallowCloneIsOff() { GitMaterial material = new GitMaterial(repo.projectRepositoryUrl(), true); material.latestModification(workingDir, context()); assertThat(localRepoFor(material).isShallow(), is(true)); material = new GitMaterial(repo.projectRepositoryUrl(), false); material.latestModification(workingDir, context()); assertThat(localRepoFor(material).isShallow(), is(false)); } @Test public void withShallowCloneShouldGenerateANewMaterialWithOverriddenShallowConfig() { GitMaterial original = new GitMaterial(repo.projectRepositoryUrl(), false); assertThat(original.withShallowClone(true).isShallowClone(), is(true)); assertThat(original.withShallowClone(false).isShallowClone(), is(false)); assertThat(original.isShallowClone(), is(false)); } @Test public void updateToANewRevisionShouldNotResultInUnshallowing() throws IOException { GitMaterial material = new GitMaterial(repo.projectRepositoryUrl(), true); material.updateTo(inMemoryConsumer(), workingDir, new RevisionContext(REVISION_4, REVISION_4, 1), context()); assertThat(localRepoFor(material).isShallow(), is(true)); List<Modification> modifications = repo.addFileAndPush("newfile", "add new file"); StringRevision newRevision = new StringRevision(modifications.get(0).getRevision()); material.updateTo(inMemoryConsumer(), workingDir, new RevisionContext(newRevision, newRevision, 1), context()); assertThat(new File(workingDir, "newfile").exists(), is(true)); assertThat(localRepoFor(material).isShallow(), is(true)); } @Test public void shouldUnshallowServerSideRepoCompletelyOnRetrievingModificationsSincePreviousRevision() { SystemEnvironment mockSystemEnvironment = mock(SystemEnvironment.class); GitMaterial material = new GitMaterial(repo.projectRepositoryUrl(), true); when(mockSystemEnvironment.get(SystemEnvironment.GO_SERVER_SHALLOW_CLONE)).thenReturn(false); material.modificationsSince(workingDir, REVISION_4, new TestSubprocessExecutionContext(mockSystemEnvironment, true)); assertThat(localRepoFor(material).isShallow(), is(false)); } @Test public void shouldNotUnshallowOnServerSideIfShallowClonePropertyIsOnAndRepoIsAlreadyShallow() { SystemEnvironment mockSystemEnvironment = mock(SystemEnvironment.class); GitMaterial material = new GitMaterial(repo.projectRepositoryUrl(), true); when(mockSystemEnvironment.get(SystemEnvironment.GO_SERVER_SHALLOW_CLONE)).thenReturn(true); material.modificationsSince(workingDir, REVISION_4, new TestSubprocessExecutionContext(mockSystemEnvironment, false)); assertThat(localRepoFor(material).isShallow(), is(true)); } private TestSubprocessExecutionContext context() { return new TestSubprocessExecutionContext(); } private GitCommand localRepoFor(GitMaterial material) { return new GitCommand(material.getFingerprint(), workingDir, GitMaterialConfig.DEFAULT_BRANCH, false, new HashMap<>()); } }
Java
package wei_chih.service.handler.wei_chih; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.IOException; import java.net.Socket; import java.security.KeyPair; import java.security.PublicKey; import java.security.SignatureException; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Level; import java.util.logging.Logger; import message.Operation; import message.OperationType; import service.Key; import service.KeyManager; import service.handler.ConnectionHandler; import wei_chih.service.Config; import wei_chih.service.SocketServer; import wei_chih.utility.MerkleTree; import wei_chih.utility.Utils; import wei_chih.message.wei_chih.Request; import wei_chih.message.wei_chih.Acknowledgement; /** * * @author Chienweichih */ public class WeiChihHandler extends ConnectionHandler { private static final ReentrantLock LOCK; private static final MerkleTree[] merkleTree; private static final String[] digestBeforeUpdate; private static final Operation[] lastOP; private static final Integer[] sequenceNumbers; static { merkleTree = new MerkleTree[Config.SERVICE_NUM]; digestBeforeUpdate = new String[Config.SERVICE_NUM]; lastOP = new Operation[Config.SERVICE_NUM]; sequenceNumbers = new Integer[Config.SERVICE_NUM]; for (int i = 0; i < Config.SERVICE_NUM; ++i) { merkleTree[i] = new MerkleTree(new File(SocketServer.dataDirPath)); digestBeforeUpdate[i] = ""; lastOP[i] = new Operation(OperationType.DOWNLOAD, "", merkleTree[i].getRootHash()); sequenceNumbers[i] = 0; } LOCK = new ReentrantLock(); } public WeiChihHandler(Socket socket, KeyPair keyPair) { super(socket, keyPair); } @Override protected void handle(DataOutputStream out, DataInputStream in) { PublicKey clientPubKey = KeyManager.getInstance().getPublicKey(Key.CLIENT); int portIndex = 0; if (Math.abs(socket.getPort() - Config.SERVICE_PORT[0]) < 10) { portIndex = socket.getPort() - Config.SERVICE_PORT[0]; } else if (Math.abs(socket.getLocalPort() - Config.SERVICE_PORT[0]) < 10) { portIndex = socket.getLocalPort() - Config.SERVICE_PORT[0]; } try { Request req = Request.parse(Utils.receive(in)); LOCK.lock(); if (!req.validate(clientPubKey)) { throw new SignatureException("REQ validation failure"); } Operation op = req.getOperation(); switch (op.getType()) { case UPLOAD: digestBeforeUpdate[portIndex] = merkleTree[portIndex].getDigest(op.getPath()); merkleTree[portIndex].update(op.getPath(), op.getMessage()); case DOWNLOAD: // both upload and download, so no break if (0 != op.getClientID().compareTo(String.valueOf(sequenceNumbers[portIndex]))) { throw new java.security.InvalidParameterException(); } sequenceNumbers[portIndex]++; default: } File file = new File(SocketServer.dataDirPath + op.getPath()); String rootHash = merkleTree[portIndex].getRootHash(); String fileHash = null; if (file.exists()) { fileHash = Utils.digest(file, Config.DIGEST_ALGORITHM); } Acknowledgement ack = new Acknowledgement(rootHash, fileHash, req); ack.sign(keyPair); Utils.send(out, ack.toString()); switch (op.getType()) { case DOWNLOAD: lastOP[portIndex] = op; if (portIndex + Config.SERVICE_PORT[0] == Config.SERVICE_PORT[0]) { Utils.send(out, file); } break; case UPLOAD: lastOP[portIndex] = op; if (portIndex + Config.SERVICE_PORT[0] == Config.SERVICE_PORT[0]) { file = new File(Config.DOWNLOADS_DIR_PATH + op.getPath()); Utils.receive(in, file); String digest = Utils.digest(file, Config.DIGEST_ALGORITHM); if (0 != op.getMessage().compareTo(digest)) { throw new java.io.IOException(); } } break; case AUDIT: file = new File(Config.ATTESTATION_DIR_PATH + "/service-provider/voting"); switch (lastOP[portIndex].getType()) { case DOWNLOAD: Utils.write(file, rootHash); break; case UPLOAD: MerkleTree prevMerkleTree = new MerkleTree(merkleTree[portIndex]); prevMerkleTree.update(lastOP[portIndex].getPath(), digestBeforeUpdate[portIndex]); Utils.Serialize(file, prevMerkleTree); break; default: throw new java.lang.Error(); } Utils.send(out, file); break; default: } socket.close(); } catch (IOException | SignatureException ex) { Logger.getLogger(WeiChihHandler.class.getName()).log(Level.SEVERE, null, ex); } finally { if (LOCK != null) { LOCK.unlock(); } } } }
Java
//// [/lib/initial-buildOutput.txt] /lib/tsc --b /src/core --verbose 12:01:00 AM - Projects in this build: * src/core/tsconfig.json 12:01:00 AM - Project 'src/core/tsconfig.json' is out of date because output file 'src/core/anotherModule.js' does not exist 12:01:00 AM - Building project '/src/core/tsconfig.json'... exitCode:: ExitStatus.Success //// [/src/core/anotherModule.js] "use strict"; exports.__esModule = true; exports.World = "hello"; //// [/src/core/index.js] "use strict"; exports.__esModule = true; exports.someString = "HELLO WORLD"; function leftPad(s, n) { return s + n; } exports.leftPad = leftPad; function multiply(a, b) { return a * b; } exports.multiply = multiply; //// [/src/core/tsconfig.json] { "compilerOptions": { "incremental": true, "module": "commonjs" } } //// [/src/core/tsconfig.tsbuildinfo] { "program": { "fileInfos": { "../../lib/lib.d.ts": { "version": "3858781397-/// <reference no-default-lib=\"true\"/>\ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array<T> { length: number; [n: number]: T; }\ninterface ReadonlyArray<T> {}\ndeclare const console: { log(msg: any): void; };", "signature": "3858781397-/// <reference no-default-lib=\"true\"/>\ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array<T> { length: number; [n: number]: T; }\ninterface ReadonlyArray<T> {}\ndeclare const console: { log(msg: any): void; };" }, "./anothermodule.ts": { "version": "-2676574883-export const World = \"hello\";\r\n", "signature": "-8396256275-export declare const World = \"hello\";\r\n" }, "./index.ts": { "version": "-18749805970-export const someString: string = \"HELLO WORLD\";\r\nexport function leftPad(s: string, n: number) { return s + n; }\r\nexport function multiply(a: number, b: number) { return a * b; }\r\n", "signature": "1874987148-export declare const someString: string;\r\nexport declare function leftPad(s: string, n: number): string;\r\nexport declare function multiply(a: number, b: number): number;\r\n" }, "./some_decl.d.ts": { "version": "-9253692965-declare const dts: any;\r\n", "signature": "-9253692965-declare const dts: any;\r\n" } }, "options": { "incremental": true, "module": 1, "configFilePath": "./tsconfig.json" }, "referencedMap": {}, "exportedModulesMap": {}, "semanticDiagnosticsPerFile": [ "../../lib/lib.d.ts", "./anothermodule.ts", "./index.ts", "./some_decl.d.ts" ] }, "version": "FakeTSVersion" }
Java
/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2012-2019 Couchbase, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "histogram.h" #include <string> using namespace cbc; using std::string; void Histogram::install(lcb_INSTANCE *inst, FILE *out) { lcb_STATUS rc; output = out; lcb_enable_timings(inst); rc = lcb_cntl(inst, LCB_CNTL_GET, LCB_CNTL_KVTIMINGS, &hg); lcb_assert(rc == LCB_SUCCESS); lcb_assert(hg != NULL); (void)rc; } void Histogram::installStandalone(FILE *out) { if (hg != NULL) { return; } hg = lcb_histogram_create(); output = out; } void Histogram::write() { if (hg == NULL) { return; } lcb_histogram_print(hg, output); } void Histogram::record(lcb_U64 duration) { if (hg == NULL) { return; } lcb_histogram_record(hg, duration); }
Java
# frozen_string_literal: true require_relative "ruby/version" module XTF module Ruby class Error < StandardError; end # placeholder end end
Java
/* -------------------------------------------------------------------------- */ /* Copyright 2002-2020, OpenNebula Project, OpenNebula Systems */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); you may */ /* not use this file except in compliance with the License. You may obtain */ /* a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ /* See the License for the specific language governing permissions and */ /* limitations under the License. */ /* -------------------------------------------------------------------------- */ define(function(require){ return 'acls-tab'; });
Java
/* Copyright 2016-2017 Vector Creations Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package gomatrixserverlib import ( "encoding/binary" "fmt" "sort" "unicode/utf8" "github.com/tidwall/gjson" ) // CanonicalJSON re-encodes the JSON in a canonical encoding. The encoding is // the shortest possible encoding using integer values with sorted object keys. // https://matrix.org/docs/spec/server_server/unstable.html#canonical-json func CanonicalJSON(input []byte) ([]byte, error) { if !gjson.Valid(string(input)) { return nil, fmt.Errorf("invalid json") } return CanonicalJSONAssumeValid(input), nil } // CanonicalJSONAssumeValid is the same as CanonicalJSON, but assumes the // input is valid JSON func CanonicalJSONAssumeValid(input []byte) []byte { input = CompactJSON(input, make([]byte, 0, len(input))) return SortJSON(input, make([]byte, 0, len(input))) } // SortJSON reencodes the JSON with the object keys sorted by lexicographically // by codepoint. The input must be valid JSON. func SortJSON(input, output []byte) []byte { result := gjson.ParseBytes(input) RawJSON := RawJSONFromResult(result, input) return sortJSONValue(result, RawJSON, output) } // sortJSONValue takes a gjson.Result and sorts it. inputJSON must be the // raw JSON bytes that gjson.Result points to. func sortJSONValue(input gjson.Result, inputJSON, output []byte) []byte { if input.IsArray() { return sortJSONArray(input, inputJSON, output) } if input.IsObject() { return sortJSONObject(input, inputJSON, output) } // If its neither an object nor an array then there is no sub structure // to sort, so just append the raw bytes. return append(output, inputJSON...) } // sortJSONArray takes a gjson.Result and sorts it, assuming its an array. // inputJSON must be the raw JSON bytes that gjson.Result points to. func sortJSONArray(input gjson.Result, inputJSON, output []byte) []byte { sep := byte('[') // Iterate over each value in the array and sort it. input.ForEach(func(_, value gjson.Result) bool { output = append(output, sep) sep = ',' RawJSON := RawJSONFromResult(value, inputJSON) output = sortJSONValue(value, RawJSON, output) return true // keep iterating }) if sep == '[' { // If sep is still '[' then the array was empty and we never wrote the // initial '[', so we write it now along with the closing ']'. output = append(output, '[', ']') } else { // Otherwise we end the array by writing a single ']' output = append(output, ']') } return output } // sortJSONObject takes a gjson.Result and sorts it, assuming its an object. // inputJSON must be the raw JSON bytes that gjson.Result points to. func sortJSONObject(input gjson.Result, inputJSON, output []byte) []byte { type entry struct { key string // The parsed key string rawKey []byte // The raw, unparsed key JSON string value gjson.Result } var entries []entry // Iterate over each key/value pair and add it to a slice // that we can sort input.ForEach(func(key, value gjson.Result) bool { entries = append(entries, entry{ key: key.String(), rawKey: RawJSONFromResult(key, inputJSON), value: value, }) return true // keep iterating }) // Sort the slice based on the *parsed* key sort.Slice(entries, func(a, b int) bool { return entries[a].key < entries[b].key }) sep := byte('{') for _, entry := range entries { output = append(output, sep) sep = ',' // Append the raw unparsed JSON key, *not* the parsed key output = append(output, entry.rawKey...) output = append(output, ':') RawJSON := RawJSONFromResult(entry.value, inputJSON) output = sortJSONValue(entry.value, RawJSON, output) } if sep == '{' { // If sep is still '{' then the object was empty and we never wrote the // initial '{', so we write it now along with the closing '}'. output = append(output, '{', '}') } else { // Otherwise we end the object by writing a single '}' output = append(output, '}') } return output } // CompactJSON makes the encoded JSON as small as possible by removing // whitespace and unneeded unicode escapes func CompactJSON(input, output []byte) []byte { var i int for i < len(input) { c := input[i] i++ // The valid whitespace characters are all less than or equal to SPACE 0x20. // The valid non-white characters are all greater than SPACE 0x20. // So we can check for whitespace by comparing against SPACE 0x20. if c <= ' ' { // Skip over whitespace. continue } // Add the non-whitespace character to the output. output = append(output, c) if c == '"' { // We are inside a string. for i < len(input) { c = input[i] i++ // Check if this is an escape sequence. if c == '\\' { escape := input[i] i++ if escape == 'u' { // If this is a unicode escape then we need to handle it specially output, i = compactUnicodeEscape(input, output, i) } else if escape == '/' { // JSON does not require escaping '/', but allows encoders to escape it as a special case. // Since the escape isn't required we remove it. output = append(output, escape) } else { // All other permitted escapes are single charater escapes that are already in their shortest form. output = append(output, '\\', escape) } } else { output = append(output, c) } if c == '"' { break } } } } return output } // compactUnicodeEscape unpacks a 4 byte unicode escape starting at index. // If the escape is a surrogate pair then decode the 6 byte \uXXXX escape // that follows. Returns the output slice and a new input index. func compactUnicodeEscape(input, output []byte, index int) ([]byte, int) { const ( ESCAPES = "uuuuuuuubtnufruuuuuuuuuuuuuuuuuu" HEX = "0123456789ABCDEF" ) // If there aren't enough bytes to decode the hex escape then return. if len(input)-index < 4 { return output, len(input) } // Decode the 4 hex digits. c := readHexDigits(input[index:]) index += 4 if c < ' ' { // If the character is less than SPACE 0x20 then it will need escaping. escape := ESCAPES[c] output = append(output, '\\', escape) if escape == 'u' { output = append(output, '0', '0', byte('0'+(c>>4)), HEX[c&0xF]) } } else if c == '\\' || c == '"' { // Otherwise the character only needs escaping if it is a QUOTE '"' or BACKSLASH '\\'. output = append(output, '\\', byte(c)) } else if c < 0xD800 || c >= 0xE000 { // If the character isn't a surrogate pair then encoded it directly as UTF-8. var buffer [4]byte n := utf8.EncodeRune(buffer[:], rune(c)) output = append(output, buffer[:n]...) } else { // Otherwise the escaped character was the first part of a UTF-16 style surrogate pair. // The next 6 bytes MUST be a '\uXXXX'. // If there aren't enough bytes to decode the hex escape then return. if len(input)-index < 6 { return output, len(input) } // Decode the 4 hex digits from the '\uXXXX'. surrogate := readHexDigits(input[index+2:]) index += 6 // Reconstruct the UCS4 codepoint from the surrogates. codepoint := 0x10000 + (((c & 0x3FF) << 10) | (surrogate & 0x3FF)) // Encode the charater as UTF-8. var buffer [4]byte n := utf8.EncodeRune(buffer[:], rune(codepoint)) output = append(output, buffer[:n]...) } return output, index } // Read 4 hex digits from the input slice. // Taken from https://github.com/NegativeMjark/indolentjson-rust/blob/8b959791fe2656a88f189c5d60d153be05fe3deb/src/readhex.rs#L21 func readHexDigits(input []byte) uint32 { hex := binary.BigEndian.Uint32(input) // subtract '0' hex -= 0x30303030 // strip the higher bits, maps 'a' => 'A' hex &= 0x1F1F1F1F mask := hex & 0x10101010 // subtract 'A' - 10 - '9' - 9 = 7 from the letters. hex -= mask >> 1 hex += mask >> 4 // collect the nibbles hex |= hex >> 4 hex &= 0xFF00FF hex |= hex >> 8 return hex & 0xFFFF } // RawJSONFromResult extracts the raw JSON bytes pointed to by result. // input must be the json bytes that were used to generate result func RawJSONFromResult(result gjson.Result, input []byte) (RawJSON []byte) { // This is lifted from gjson README. Basically, result.Raw is a copy of // the bytes we want, but its more efficient to take a slice. // If Index is 0 then for some reason we can't extract it from the original // JSON bytes. if result.Index > 0 { RawJSON = input[result.Index : result.Index+len(result.Raw)] } else { RawJSON = []byte(result.Raw) } return }
Java
# Geranium pyrenaicum var. patulivillosum Hausskn. & Bornm. ex Bornm. VARIETY #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
Java
# Tragacantha canoatra Kuntze SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
Java
-- MySQL dump 10.13 Distrib 5.5.37, for debian-linux-gnu (x86_64) -- -- Host: localhost Database: AirAlliance -- ------------------------------------------------------ -- Server version 5.5.37-0ubuntu0.12.04.1 /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `flight` -- DROP TABLE IF EXISTS `flight`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `flight` ( `id` int(11) NOT NULL, `name` varchar(10) NOT NULL, `source_sector_id` int(11) NOT NULL, `dest_sector_id` int(11) NOT NULL, PRIMARY KEY (`id`), KEY `fk_flight_sector_source` (`source_sector_id`), KEY `fk_flight_sector_dest` (`dest_sector_id`), CONSTRAINT `fk_flight_sector_dest` FOREIGN KEY (`dest_sector_id`) REFERENCES `sector` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_flight_sector_source` FOREIGN KEY (`source_sector_id`) REFERENCES `sector` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `flight` -- LOCK TABLES `flight` WRITE; /*!40000 ALTER TABLE `flight` DISABLE KEYS */; INSERT INTO `flight` VALUES (1,'AA056',1,3),(2,'AA032',5,6),(3,'AA087',20,4),(4,'AA003',19,17),(5,'AA004',10,13),(6,'AA045',2,5),(7,'AA033',8,11),(8,'AA089',12,9),(9,'AA099',7,16),(10,'AA098',15,14); /*!40000 ALTER TABLE `flight` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `guest` -- DROP TABLE IF EXISTS `guest`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `guest` ( `id` int(10) NOT NULL AUTO_INCREMENT, `firstname` varchar(20) NOT NULL, `lastname` varchar(20) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `guest` -- LOCK TABLES `guest` WRITE; /*!40000 ALTER TABLE `guest` DISABLE KEYS */; INSERT INTO `guest` VALUES (1,'Frank','Jennings'),(2,'Florence','Justina'),(3,'Randy','Pauch'),(4,'Dorris','Lessing'),(5,'Orhan','Pamuk'),(6,'Harold','Pinter'),(7,'Toni','Morrison'),(8,'Dario','Fo'),(9,'Ivan','Bunin'),(10,'Henri','Bergson'); /*!40000 ALTER TABLE `guest` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `itinerary` -- DROP TABLE IF EXISTS `itinerary`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `itinerary` ( `id` int(11) NOT NULL AUTO_INCREMENT, `guest_id` int(11) NOT NULL, `flight_id` int(11) NOT NULL, `schedule_id` int(11) NOT NULL, PRIMARY KEY (`id`), KEY `fk_itinerary_guest` (`guest_id`), KEY `fk_itinerary_flight` (`flight_id`), KEY `fk_itinerary_schedule` (`schedule_id`), CONSTRAINT `fk_itinerary_schedule` FOREIGN KEY (`schedule_id`) REFERENCES `schedule` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_itinerary_flight` FOREIGN KEY (`flight_id`) REFERENCES `flight` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_itinerary_guest` FOREIGN KEY (`guest_id`) REFERENCES `guest` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `itinerary` -- LOCK TABLES `itinerary` WRITE; /*!40000 ALTER TABLE `itinerary` DISABLE KEYS */; INSERT INTO `itinerary` VALUES (1,4,6,5),(2,1,10,9),(3,6,1,1),(4,9,8,7),(5,3,3,3),(6,2,4,8),(7,7,7,4),(8,5,9,6),(9,10,5,2),(10,8,2,10); /*!40000 ALTER TABLE `itinerary` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `schedule` -- DROP TABLE IF EXISTS `schedule`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `schedule` ( `id` int(11) NOT NULL AUTO_INCREMENT, `guest_id` int(11) NOT NULL, `flight_id` int(11) NOT NULL, `schedule_date` date NOT NULL, PRIMARY KEY (`id`), KEY `fk_schedule_guest` (`guest_id`), KEY `fk_schedule_flight` (`flight_id`), CONSTRAINT `fk_schedule_flight` FOREIGN KEY (`flight_id`) REFERENCES `flight` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `fk_schedule_guest` FOREIGN KEY (`guest_id`) REFERENCES `guest` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `schedule` -- LOCK TABLES `schedule` WRITE; /*!40000 ALTER TABLE `schedule` DISABLE KEYS */; INSERT INTO `schedule` VALUES (1,4,4,'2008-11-01'),(2,6,1,'2008-11-04'),(3,2,10,'2008-10-04'),(4,3,9,'2008-10-21'),(5,5,8,'2008-10-20'),(6,1,7,'2008-10-03'),(7,8,6,'2008-10-04'),(8,9,3,'2008-10-07'),(9,7,2,'2008-10-15'),(10,10,5,'2008-10-17'); /*!40000 ALTER TABLE `schedule` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `sector` -- DROP TABLE IF EXISTS `sector`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `sector` ( `id` int(11) NOT NULL AUTO_INCREMENT, `sector` varchar(10) NOT NULL, PRIMARY KEY (`id`), KEY `sector` (`sector`) ) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `sector` -- LOCK TABLES `sector` WRITE; /*!40000 ALTER TABLE `sector` DISABLE KEYS */; INSERT INTO `sector` VALUES (15,'ANG'),(1,'BLR'),(3,'BOM'),(9,'CAL'),(20,'CAL'),(10,'CHI'),(19,'DEL'),(4,'FRA'),(17,'JAV'),(14,'LON'),(11,'MAL'),(2,'MAS'),(5,'PEK'),(7,'SCA'),(8,'SFO'),(6,'SIN'),(12,'SPB'),(13,'SYD'),(16,'TOK'),(18,'VIS'); /*!40000 ALTER TABLE `sector` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2014-05-15 1:13:28
Java
package ru.stqa.pft.addressbook.tests; import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.testng.annotations.Test; import ru.stqa.pft.addressbook.model.ContactData; import ru.stqa.pft.addressbook.tests.TestBase; import java.util.Arrays; import java.util.stream.Collectors; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; /** * Created by mocius on 2017-04-16. */ public class ContactPhone extends TestBase { @Test public void testContactPhones(){ app.goTo().homePage(); ContactData contact = app.contactHelper().all().iterator().next(); ContactData contactInfoFromEditForm = app.contactHelper().infoFromEditForm(contact); assertThat(contact.getAllPhones(), equalTo(mergePhones(contactInfoFromEditForm))); } private <T> String mergePhones(ContactData contact) { return Arrays.asList(contact.getHomePhone(), contact.getMobilePhone(),contact.getWorkPhone()).stream(). filter((s) -> ! s.equals("")).map(ContactPhone::cleaned) .collect(Collectors.joining("\n")); } public static String cleaned(String phone){ return phone.replaceAll("\\s", "").replaceAll("[-()]", ""); } }
Java
package com.oauth.services.security; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.keygen.BytesKeyGenerator; import org.springframework.security.crypto.keygen.KeyGenerators; import org.springframework.security.crypto.password.StandardPasswordEncoder; /** * Created by yichen.wei on 6/24/17. */ public class Test { public static void main(String args[]) { BytesKeyGenerator saltGenerator = KeyGenerators.secureRandom(); // StandardPasswordEncoder encode = new StandardPasswordEncoder("SHA-256", ""); // StandardPasswordEncoder encode = new StandardPasswordEncoder(""); StandardPasswordEncoder encode = new StandardPasswordEncoder(); System.out.println("abcfwef..."); //a8ba715d5a076c99b95995d357651df5c296bf308abaa154a54d2418885ec622e9fe8624f2e06524 //be1e54adbd1c5c5d58a714fad7d529c73198c8c51e1f9d43edc79dac4784b5e93460605fe7082b0d //910a6df88a99d5d81f3376628f3fd6a91a2152a366f2d450ef9220ff32f0c74952f754da62cd5a13 System.out.println(encode.encode("abcdef")); // System.out.println(encode.encode("mypass")); String salt = saltGenerator.generateKey().toString(); System.out.println(salt); System.out.println(saltGenerator.getKeyLength()); BCryptPasswordEncoder bc = new BCryptPasswordEncoder(); System.out.println(bc.encode("admin")); } }
Java
<?php /** * Created by PhpStorm. * User: Bartosz Bartniczak <kontakt@bartoszbartniczak.pl> */ namespace BartoszBartniczak\EventSourcing\Shop\User\Event; use BartoszBartniczak\EventSourcing\Event\Id; class UserAccountHasBeenActivated extends Event { /** * @var string */ protected $activationToken; /** * @inheritDoc */ public function __construct(Id $eventId, \DateTime $dateTime, string $userEmail, string $activationToken) { parent::__construct($eventId, $dateTime, $userEmail); $this->activationToken = $activationToken; } /** * @return string */ public function getActivationToken(): string { return $this->activationToken; } }
Java
# Phoma maculata (Cooke & Harkn.) Sacc. SPECIES #### Status SYNONYM #### According to Index Fungorum #### Published in null #### Original name null ### Remarks null
Java
package net.distilledcode.httpclient.impl.metatype.reflection; import org.apache.http.client.config.RequestConfig; import org.junit.Test; import java.util.Map; import static org.hamcrest.CoreMatchers.allOf; import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.junit.Assert.assertThat; public class InvokersTest { private static class TestBean { private boolean featureEnabled = true; // getters public String getFooBar() { return null; } public void getFooBarVoid() {} // setters public void setBarFoo(String fooBar) {} public void setBarFooNoArgs() {} // boolean switch (only called for enabling, disabled by default public void enableFeature() { featureEnabled = true; } // boolean switch (only called for disabling, enabled by default void disableFeature() { featureEnabled = false; } } @Test public void invokeMethods() throws Exception { // builder.setMaxRedirects(5) Invokers.Invoker<Void> setMaxRedirects = new Invokers.Invoker<>(RequestConfig.Builder.class.getDeclaredMethod("setMaxRedirects", int.class)); RequestConfig.Builder builder = RequestConfig.custom(); setMaxRedirects.invoke(builder, 17); // requestConfig.getMaxRedirects() Invokers.Invoker<Integer> getMaxRedirects = new Invokers.Invoker<>(RequestConfig.class.getDeclaredMethod("getMaxRedirects")); RequestConfig requestConfig = builder.build(); assertThat(getMaxRedirects.invoke(requestConfig), is(17)); } @Test public void beanGetters() throws Exception { Map<String, Invokers.Invoker<?>> testBeanGetters = Invokers.beanGetters(TestBean.class); assertThat(testBeanGetters.keySet(), allOf( hasItem("foo.bar"), not(hasItem("foo.bar.void")) )); } @Test public void beanSetters() throws Exception { Map<String, Invokers.Invoker<?>> testBeanGetters = Invokers.beanSetters(TestBean.class); assertThat(testBeanGetters.keySet(), allOf( hasItem("bar.foo"), not(hasItem("bar.foo.no.args")) )); } @Test public void conditionalSetter() throws Exception { Invokers.Invoker<?> featureDisabler = Invokers.conditionalNoArgsSetter(TestBean.class.getDeclaredMethod("disableFeature"), false); TestBean testBean = new TestBean(); assertThat(testBean.featureEnabled, is(true)); featureDisabler.invoke(testBean, false); assertThat(testBean.featureEnabled, is(false)); } @Test public void conditionalSetterIgnored() throws Exception { Invokers.Invoker<?> featureDisabler = Invokers.conditionalNoArgsSetter(TestBean.class.getDeclaredMethod("disableFeature"), true); TestBean testBean = new TestBean(); assertThat(testBean.featureEnabled, is(true)); featureDisabler.invoke(testBean, false); assertThat(testBean.featureEnabled, is(true)); } }
Java
--TEST-- swoole_coroutine_server: (length protocol) 1 --SKIPIF-- <?php require __DIR__ . '/../include/skipif.inc'; ?> --FILE-- <?php require __DIR__ . '/../include/bootstrap.php'; use SwooleTest\LengthServer; class TestServer_5 extends LengthServer { protected $show_lost_package = true; function onWorkerStart() { global $pm; $pm->wakeup(); } function onClose() { parent::onClose(); $this->serv->shutdown(); } } TestServer_5::$random_bytes = true; TestServer_5::$pkg_num = IS_IN_TRAVIS ? 1000 : 10000; $pm = new ProcessManager; $pm->parentFunc = function ($pid) use ($pm) { $client = new swoole_client(SWOOLE_SOCK_TCP); if (!$client->connect('127.0.0.1', $pm->getFreePort())) { exit("connect failed\n"); } $bytes = 0; $pkg_bytes = 0; for ($i = 0; $i < TestServer_5::$pkg_num; $i++) { // if ($i % 1000 == 0) // { // echo "#{$i} send package. sid={$sid}, length=" . ($len + 10) . ", total bytes={$pkg_bytes}\n"; // } if (!$client->send(TestServer_5::getPacket())) { echo "send [$i] failed.\n"; break; } $bytes += 2; } $recv = $client->recv(); echo $recv; //echo "send ".TestServer::PKG_NUM." packet sucess, send $bytes bytes\n"; $client->close(); }; $pm->childFunc = function () use ($pm) { go(function () use ($pm) { $serv = new TestServer_5($pm->getFreePort(), false); $serv->start(); }); swoole_event::wait(); }; $pm->childFirst(); $pm->run(); ?> --EXPECTF-- end Total count=%d, bytes=%d
Java
# Physalis lathyroides f. parvifolia Chodat & Hassl. FORM #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
Java
# Antennaria luzuloides ssp. aberrans (E.E. Nelson) Bayer & Stebbins SUBSPECIES #### Status ACCEPTED #### According to Integrated Taxonomic Information System #### Published in Canad. J. Bot. 71:1597. 1993 #### Original name null ### Remarks null
Java
/* * Copyright 2013 Square Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package flowless; import android.os.Parcelable; import android.support.annotation.NonNull; /** * Used by History to convert your key objects to and from instances of * {@link android.os.Parcelable}. */ public interface KeyParceler { @NonNull Parcelable toParcelable(@NonNull Object key); @NonNull Object toKey(@NonNull Parcelable parcelable); }
Java
select ST_Length(ST_Linestring(1,1, 1,2, 2,2, 2,1)), ST_Length(ST_Linestring(1,1, 1,4, 4,4, 4,1)), ST_Length(ST_Linestring(1,1, 1,7, 7,7, 7,1)) from onerow; select ST_Area(ST_Polygon(1,1, 1,2, 2,2, 2,1)), ST_Area(ST_Polygon(1,1, 1,4, 4,4, 4,1)) from onerow; select ST_Contains(ST_Polygon(1, 1, 1, 4, 4, 4, 4, 1), ST_Point(2, 3)), ST_Contains(ST_Polygon(1, 1, 1, 4, 4, 4, 4, 1), ST_Point(8, 8)) from onerow; select ST_CoordDim(ST_Point(0., 3.)), ST_CoordDim(ST_PointZ(0., 3., 1)) from onerow; select ST_Crosses(st_linestring(2,0, 2,3), ST_Polygon(1,1, 1,4, 4,4, 4,1)), ST_Crosses(st_linestring(8,7, 7,8), ST_Polygon(1,1, 1,4, 4,4, 4,1)) from onerow; select ST_Dimension(ST_Point(0,0)), ST_Dimension(ST_LineString(1.5,2.5, 3.0,2.2)) from onerow; select ST_Disjoint(st_point(1,1), ST_Point(1,1)), ST_Disjoint(st_point(2,0), ST_Point(1,1)) from onerow; select ST_EnvIntersects(st_point(1,1), ST_Point(1,1)), ST_EnvIntersects(st_point(2,0), ST_Point(1,1)) from onerow; select ST_Equals(st_point(1,1), ST_Point(1,1)), ST_Equals(st_point(2,0), ST_Point(1,1)) from onerow; select ST_Intersects(st_point(1,1), ST_Point(1,1)), ST_Intersects(st_point(2,0), ST_Point(1,1)) from onerow; select ST_Is3D(ST_Point(0., 3.)), ST_Is3D(ST_PointZ(0., 3., 1)) from onerow; select ST_Overlaps(st_polygon(2,0, 2,3, 3,0), ST_Polygon(1,1, 1,4, 4,4, 4,1)), ST_Overlaps(st_polygon(2,0, 2,1, 3,1), ST_Polygon(1,1, 1,4, 4,4, 4,1)) from onerow; select ST_Touches(ST_Point(1, 3), ST_Polygon(1, 1, 1, 4, 4, 4, 4, 1)), ST_Touches(ST_Point(8, 8), ST_Polygon(1, 1, 1, 4, 4, 4, 4, 1)) from onerow; select ST_Within(ST_Point(2, 3), ST_Polygon(1, 1, 1, 4, 4, 4, 4, 1)), ST_Within(ST_Point(8, 8), ST_Polygon(1, 1, 1, 4, 4, 4, 4, 1)) from onerow;
Java
/* * Copyright 2012 Michael Bischoff * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.jpaw.util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInput; import java.io.DataOutput; import java.io.Externalizable; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInput; import java.io.ObjectOutput; import java.io.OutputStream; import java.nio.charset.Charset; /** * Functionality which corresponds to String, but for byte arrays. * Essential feature is that the class is immutable, so you can use it in messaging without making deep copies. * Mimicking {@link java.lang.String}, the class contains offset and length fields to allow sharing of the buffer. * <p> * This should really exist in Java SE already. * * @author Michael Bischoff * */ public final class ByteArray implements Externalizable, Cloneable { private static final long serialVersionUID = 2782729564297256974L; public static final Charset CHARSET_UTF8 = Charset.forName("UTF-8"); // default character set is available on all platforms private static final int MAGIC_LENGTH_INDICATING_32_BIT_SIZE = 247; // if a single byte length of this value is written in the // serialized form, it indicates a full four byte length must be read instead. Not used 0 or 255 due to their frequent use. private final byte[] buffer; private final int offset; private final int length; private ByteArray extraFieldJustRequiredForDeserialization = null; // transient temporary field private static final byte[] ZERO_JAVA_BYTE_ARRAY = new byte[0]; public static final ByteArray ZERO_BYTE_ARRAY = new ByteArray(ZERO_JAVA_BYTE_ARRAY); /** No-arg constructor required for Serializable interface. */ @Deprecated public ByteArray() { this(ZERO_JAVA_BYTE_ARRAY); } /** Constructs a ByteArray from a source byte[], which is defensively copied. */ public ByteArray(final byte[] source) { if (source == null || source.length == 0) { buffer = ZERO_JAVA_BYTE_ARRAY; offset = 0; length = 0; } else { buffer = source.clone(); // benchmarks have shown that clone() is equally fast as System.arraycopy for all lengths > 0 offset = 0; length = buffer.length; } } // construct a ByteArray from a trusted source byte[] // this method is always called with unsafeTrustedReuseOfJavaByteArray = true, the parameter is only required in order to distinguish the constructor // from the copying one private ByteArray(final byte[] source, final boolean unsafeTrustedReuseOfJavaByteArray) { if (source == null || source.length == 0) { buffer = ZERO_JAVA_BYTE_ARRAY; offset = 0; length = 0; } else { buffer = unsafeTrustedReuseOfJavaByteArray ? source : source.clone(); offset = 0; length = buffer.length; } } /** Constructs a ByteArray from a ByteArrayOutputStream, which has just been contructed by some previous process. * @throws IOException */ public static ByteArray fromByteArrayOutputStream(final ByteArrayOutputStream baos) throws IOException { baos.flush(); return new ByteArray(baos.toByteArray(), true); } /** Writes the contents of this ByteArray to an OutputStream. */ public void toOutputStream(final OutputStream os) throws IOException { os.write(buffer, offset, length); } /** Constructs a ByteArray from the provided DataInput, with a predefined length. */ public static ByteArray fromDataInput(final DataInput in, final int len) throws IOException { if (len <= 0) return ZERO_BYTE_ARRAY; final byte[] tmp = new byte[len]; in.readFully(tmp); return new ByteArray(tmp, true); } /** read bytes from an input stream, up to maxBytes (or all which exist, if maxBytes = 0). */ public static ByteArray fromInputStream(final InputStream is, final int maxBytes) throws IOException { final ByteBuilder tmp = maxBytes > 0 ? new ByteBuilder(maxBytes, CHARSET_UTF8) : new ByteBuilder(); tmp.readFromInputStream(is, maxBytes); if (tmp.length() == 0) return ZERO_BYTE_ARRAY; return new ByteArray(tmp.getCurrentBuffer(), 0, tmp.length()); } /** Constructs a ByteArray from the provided ByteBuilder. */ public static ByteArray fromByteBuilder(final ByteBuilder in) { if (in == null || in.length() == 0) return ZERO_BYTE_ARRAY; return new ByteArray(in.getCurrentBuffer(), 0, in.length()); } /** Constructs a ByteArray from the provided String, using the UTF8 character set. */ public static ByteArray fromString(final String in) { return fromString(in, CHARSET_UTF8); } /** Constructs a ByteArray from the provided String, using the specified character set. */ public static ByteArray fromString(final String in, final Charset cs) { if (in == null || in.length() == 0) return ZERO_BYTE_ARRAY; return new ByteArray(in.getBytes(cs), true); // we know these bytes are never changed, so no extra copy required } /** returns the byte array as a string. Unlike toString(), which uses the JVM default character set, this method always uses UTF-8. */ public String asString() { return asString(CHARSET_UTF8); } /** returns the byte array as a string, using a specified character set. */ public String asString(final Charset cs) { return new String(buffer, offset, length, cs); } /** construct a ByteArray from a source byte[], with offset and length. source may not be null. */ public ByteArray(final byte[] source, final int offset, final int length) { if (source == null || offset < 0 || length < 0 || offset + length > source.length) throw new IllegalArgumentException(); buffer = new byte[length]; System.arraycopy(source, offset, buffer, 0, length); this.offset = 0; this.length = length; } /** Construct a ByteArray from another one. Could also just assign it due to immutability. * The only benefit of this constructor is that it converts a null parameter into the non-null empty ByteArray. */ public ByteArray(final ByteArray source) { if (source == null) { buffer = ZERO_JAVA_BYTE_ARRAY; offset = 0; length = 0; } else { buffer = source.buffer; // no array copy required due to immutability offset = source.offset; length = source.length; } } /** Construct a ByteArray from a source byte[], with offset and length. source may not be null. * Similar to the subArray member method. */ public ByteArray(final ByteArray source, final int offset, final int length) { if (source == null || offset < 0 || length < 0 || offset + length > source.length) throw new IllegalArgumentException(); this.buffer = source.buffer; // no array copy required due to immutability this.offset = source.offset + offset; this.length = length; } /** Returns a ByteArray which contains a subsequence of the bytes of this one. The underlying buffer is shared. * Functionality wise this corresponds to String.substring (before Java 6) or ByteBuffer.slice. */ public ByteArray subArray(final int xoffset, final int xlength) { // create a new ByteArray sharing the same buffer return new ByteArray(this, xoffset, xlength); } /** Returns a ByteArray which contains a subsequence of the bytes of this one. The underlying buffer is not shared. * Use this variant if the original ByteArray holds a much larger byte[] and can be GCed afterwards. */ public ByteArray subArrayUnshared(final int xoffset, final int xlength) { if (xoffset < 0 || xlength < 0 || xoffset + xlength > this.length) throw new IllegalArgumentException(); final byte[] newBuffer = new byte[xlength]; System.arraycopy(buffer, xoffset, newBuffer, 0, xlength); // create a new ByteArray using the new buffer return new ByteArray(newBuffer, true); } @Override public ByteArray clone() { return new ByteArray(this); } public int length() { return this.length; } // public int getOffset() { // return this.offset; // } // // /** Returns the internal buffer of this object. It may only be used for read-only access. // * Java is missing a "const" specifier for arrays as it is available in C and C++. // * // * Java-purists will complain against exposing this internal state of an immutable object, but as long as // * access is possible via reflection anyway, just with performance penalty, it would be outright stupid // * to force people to use reflection, or even defensive copies. Instead I hope the name of the method // * documents the intended use. // */ // public byte /* const */[] unsafe$getConstBufferOfConstBytes() { // return this.buffer; // } public int indexOf(final byte x) { int i = 0; while (i < length) { if (buffer[offset + i] == x) return i; ++i; } return -1; } public int indexOf(final byte x, final int fromIndex) { int i = fromIndex >= 0 ? fromIndex : 0; while (i < length) { if (buffer[offset + i] == x) return i; ++i; } return -1; } public int lastIndexOf(final byte x) { int i = length; while (i > 0) { if (buffer[offset + --i] == x) return i; } return -1; } public int lastIndexOf(final byte x, final int fromIndex) { int i = fromIndex >= length ? length - 1 : fromIndex; while (i >= 0) { if (buffer[offset + i] == x) return i; --i; } return -1; } public byte byteAt(final int pos) { if (pos < 0 || pos >= length) throw new IllegalArgumentException(); return buffer[offset + pos]; } /** Provides the contents of this ByteArray to some InputStream. */ public ByteArrayInputStream asByteArrayInputStream() { return new ByteArrayInputStream(buffer, offset, length()); } // return a defensive copy of the contents public byte[] getBytes() { final byte[] result = new byte[length]; System.arraycopy(buffer, offset, result, 0, length); return result; } // return a defensive copy of part of the contents. Shorthand for subArray(offset, length).getBytes(), // which would create a temporary object public byte[] getBytes(final int xoffset, final int xlength) { if (xoffset < 0 || xlength < 0 || xoffset + xlength > this.length) throw new IllegalArgumentException(); final byte[] result = new byte[xlength]; System.arraycopy(buffer, xoffset + this.offset, result, 0, xlength); return result; } private boolean contentEqualsSub(final byte[] dst, final int dstOffset, final int dstLength) { if (length != dstLength) return false; for (int i = 0; i < dstLength; ++i) { if (buffer[offset + i] != dst[dstOffset + i]) return false; } return true; } // following: all arguments must be not null public boolean contentEquals(final ByteArray that) { return contentEqualsSub(that.buffer, that.offset, that.length); } public boolean contentEquals(final byte[] that) { return contentEqualsSub(that, 0, that.length); } public boolean contentEquals(final byte[] that, final int thatOffset, final int thatLength) { if (thatOffset < 0 || thatLength < 0 || thatOffset + thatLength > that.length) throw new IllegalArgumentException(); return contentEqualsSub(that, thatOffset, thatLength); } // returns if the two instances share the same backing buffer (for debugging) public boolean shareBuffer(final ByteArray that) { return buffer == that.buffer; } @Override public int hashCode() { int hash = 997; for (int i = 0; i < length; ++i) { hash = 29 * hash + buffer[offset + i]; } return hash; } // two ByteArrays are considered equal if they have the same visible contents @Override public boolean equals(final Object that) { if (this == that) return true; if (that == null || getClass() != that.getClass()) return false; final ByteArray xthat = (ByteArray)that; // same as contentEqualsSub(..) now if (this.length != xthat.length) return false; for (int i = 0; i < length; ++i) { if (buffer[offset + i] != xthat.buffer[xthat.offset + i]) return false; } return true; } // support function to allow dumping contents to DataOutput without the need to expose our internal buffer public void writeToDataOutput(final DataOutput out) throws IOException { out.write(buffer, offset, length); } public String hexdump(final int startAt, final int maxlength) { if (length <= startAt) return ""; // no data to dump return ByteUtil.dump(buffer, offset + startAt, (maxlength > 0 && maxlength < length) ? maxlength : length); } @Override public void writeExternal(final ObjectOutput out) throws IOException { //writeBytes(out, buffer, offset, length); if (length < 256 && length != MAGIC_LENGTH_INDICATING_32_BIT_SIZE) { out.writeByte(length); } else { out.writeByte(MAGIC_LENGTH_INDICATING_32_BIT_SIZE); out.writeInt(length); } out.write(buffer, offset, length); } // support function to allow ordinary byte[] to be written in same fashion public static void writeBytes(final ObjectOutput out, final byte[] buffer, final int offset, final int length) throws IOException { if (length < 256 && length != MAGIC_LENGTH_INDICATING_32_BIT_SIZE) { out.writeByte(length); } else { out.writeByte(MAGIC_LENGTH_INDICATING_32_BIT_SIZE); out.writeInt(length); } out.write(buffer, offset, length); } public static byte[] readBytes(final ObjectInput in) throws IOException { int newlength = in.readByte(); if (newlength < 0) newlength += 256; // want full unsigned range if (newlength == MAGIC_LENGTH_INDICATING_32_BIT_SIZE) // magic to indicate four byte length newlength = in.readInt(); // System.out.println("ByteArray.readExternal() with length " + newlength); if (newlength == 0) return ZERO_JAVA_BYTE_ARRAY; final byte[] localBuffer = new byte[newlength]; int done = 0; while (done < newlength) { final int nRead = in.read(localBuffer, done, newlength - done); // may return less bytes than requested! if (nRead <= 0) throw new IOException("deserialization of ByteArray returned " + nRead + " while expecting " + (newlength - done)); done += nRead; } return localBuffer; } // factory method to read from objectInput via above helper function public static ByteArray read(final ObjectInput in) throws IOException { return new ByteArray(readBytes(in), true); } // a direct implementation of this method would conflict with the immutability / "final" attributes of the field // Weird Java language design again. If readExternal() is kind of a constructor, why are assignments to final fields not allowed here? // alternatives around are to add artificial fields and use readResolve / proxies or to discard the "final" attributes, // or using reflection to set the values (!?). Bleh! // We're using kind of Bloch's "proxy" pattern (Essential Java, #78), namely a single-sided variant with just a single additonal member field, // which lets us preserve the immutability // see also http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6379948 for discussion around this @Override public void readExternal(final ObjectInput in) throws IOException { extraFieldJustRequiredForDeserialization = new ByteArray(readBytes(in), true); } public Object readResolve() { // System.out.println("ByteArray.readResolve()"); if (extraFieldJustRequiredForDeserialization == null) throw new RuntimeException("readResolve() called on instance not obtained via readExternal()"); return extraFieldJustRequiredForDeserialization; } // factory method to construct a byte array from a prevalidated base64 byte sequence. returns null if length is suspicious public static ByteArray fromBase64(final byte[] data, final int offset, final int length) { if (length == 0) return ZERO_BYTE_ARRAY; final byte[] tmp = Base64.decode(data, offset, length); if (tmp == null) return null; return new ByteArray(tmp, true); } public void appendBase64(final ByteBuilder b) { Base64.encodeToByte(b, buffer, offset, length); } public void appendToRaw(final ByteBuilder b) { b.write(buffer, offset, length); } /** Returns the contents of this ByteArray as a base64 encoded string. * @since 1.2.12 */ public String asBase64() { final ByteBuilder tmp = new ByteBuilder(0, null); Base64.encodeToByte(tmp, buffer, offset, length); return tmp.toString(); } // returns the String representation of the visible bytes portion @Override public String toString() { return new String(buffer, offset, length); } }
Java
/* * Copyright (C) 2014 Jörg Prante * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.xbib.elasticsearch.plugin.jdbc.feeder; import org.elasticsearch.cluster.metadata.MetaData; import org.elasticsearch.common.logging.ESLogger; import org.elasticsearch.common.logging.ESLoggerFactory; import org.elasticsearch.common.metrics.MeterMetric; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.loader.JsonSettingsLoader; import org.elasticsearch.common.unit.ByteSizeValue; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.common.xcontent.support.XContentMapValues; import org.elasticsearch.river.RiverName; import org.xbib.elasticsearch.plugin.jdbc.RiverRunnable; import org.xbib.elasticsearch.plugin.jdbc.classloader.uri.URIClassLoader; import org.xbib.elasticsearch.plugin.jdbc.client.Ingest; import org.xbib.elasticsearch.plugin.jdbc.client.IngestFactory; import org.xbib.elasticsearch.plugin.jdbc.client.transport.BulkTransportClient; import org.xbib.elasticsearch.plugin.jdbc.cron.CronExpression; import org.xbib.elasticsearch.plugin.jdbc.cron.CronThreadPoolExecutor; import org.xbib.elasticsearch.plugin.jdbc.state.RiverStatesMetaData; import org.xbib.elasticsearch.plugin.jdbc.util.RiverServiceLoader; import org.xbib.elasticsearch.river.jdbc.RiverFlow; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.io.Reader; import java.io.Writer; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentLinkedDeque; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import static org.elasticsearch.common.collect.Lists.newLinkedList; import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; /** * Standalone feeder for JDBC */ public class JDBCFeeder { private final static ESLogger logger = ESLoggerFactory.getLogger("JDBCFeeder"); /** * Register metadata factory in Elasticsearch for being able to decode * ClusterStateResponse with RiverStatesMetadata */ static { MetaData.registerFactory(RiverStatesMetaData.TYPE, RiverStatesMetaData.FACTORY); } protected Reader reader; protected Writer writer; protected PrintStream printStream; protected IngestFactory ingestFactory; /** * This ingest is the client for the river flow state operations */ private Ingest ingest; private RiverFlow riverFlow; private List<Map<String, Object>> definitions; private ThreadPoolExecutor threadPoolExecutor; private volatile Thread feederThread; private volatile boolean closed; /** * Constructor for running this from command line */ public JDBCFeeder() { Runtime.getRuntime().addShutdownHook(shutdownHook()); } public void exec() throws Exception { readFrom(new InputStreamReader(System.in, "UTF-8")) .writeTo(new OutputStreamWriter(System.out, "UTF-8")) .errorsTo(System.err) .start(); } @SuppressWarnings("unchecked") public JDBCFeeder readFrom(Reader reader) { this.reader = reader; try { Map<String, Object> map = XContentFactory.xContent(XContentType.JSON).createParser(reader).mapOrderedAndClose(); Settings settings = settingsBuilder() .put(new JsonSettingsLoader().load(jsonBuilder().map(map).string())) .build(); this.definitions = newLinkedList(); Object pipeline = map.get("jdbc"); if (pipeline instanceof Map) { definitions.add((Map<String, Object>) pipeline); } if (pipeline instanceof List) { definitions.addAll((List<Map<String, Object>>) pipeline); } // before running, create the river flow createRiverFlow(map, settings); } catch (IOException e) { logger.error(e.getMessage(), e); } return this; } protected RiverFlow createRiverFlow(Map<String, Object> spec, Settings settings) throws IOException { String strategy = XContentMapValues.nodeStringValue(spec.get("strategy"), "simple"); this.riverFlow = RiverServiceLoader.newRiverFlow(strategy); logger.debug("strategy {}: river flow class {}, spec = {} settings = {}", strategy, riverFlow.getClass().getName(), spec, settings.getAsMap()); this.ingestFactory = createIngestFactory(settings); // out private ingest, needed for having a client in the river flow this.ingest = ingestFactory.create(); riverFlow.setRiverName(new RiverName("jdbc", "feeder")) .setSettings(settings) .setClient(ingest.client()) .setIngestFactory(ingestFactory) .setMetric(new MeterMetric(Executors.newScheduledThreadPool(1), TimeUnit.SECONDS)) .setQueue(new ConcurrentLinkedDeque<Map<String, Object>>()); return riverFlow; } public JDBCFeeder writeTo(Writer writer) { this.writer = writer; return this; } public JDBCFeeder errorsTo(PrintStream printStream) { this.printStream = printStream; return this; } public JDBCFeeder start() throws Exception { this.closed = false; if (ingest.getConnectedNodes().isEmpty()) { throw new IOException("no nodes connected, can't continue"); } this.feederThread = new Thread(new RiverRunnable(riverFlow, definitions)); List<Future<?>> futures = schedule(feederThread); // wait for all threads to finish for (Future<?> future : futures) { future.get(); } ingest.shutdown(); return this; } private List<Future<?>> schedule(Thread thread) { Settings settings = riverFlow.getSettings(); String[] schedule = settings.getAsArray("schedule"); List<Future<?>> futures = newLinkedList(); Long seconds = settings.getAsTime("interval", TimeValue.timeValueSeconds(0)).seconds(); if (schedule != null && schedule.length > 0) { CronThreadPoolExecutor cronThreadPoolExecutor = new CronThreadPoolExecutor(settings.getAsInt("threadpoolsize", 1)); for (String cron : schedule) { futures.add(cronThreadPoolExecutor.schedule(thread, new CronExpression(cron))); } this.threadPoolExecutor = cronThreadPoolExecutor; logger.debug("scheduled feeder instance with cron expressions {}", Arrays.asList(schedule)); } else if (seconds > 0L) { ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(settings.getAsInt("threadpoolsize", 4)); futures.add(scheduledThreadPoolExecutor.scheduleAtFixedRate(thread, 0L, seconds, TimeUnit.SECONDS)); logger.debug("scheduled feeder instance at fixed rate of {} seconds", seconds); this.threadPoolExecutor = scheduledThreadPoolExecutor; } else { this.threadPoolExecutor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); futures.add(threadPoolExecutor.submit(thread)); logger.debug("started feeder instance"); } return futures; } /** * Shut down feeder instance by Ctrl-C * * @return shutdown thread */ public Thread shutdownHook() { return new Thread() { public void run() { try { shutdown(); } catch (Exception e) { e.printStackTrace(printStream); } } }; } public synchronized void shutdown() throws Exception { if (closed) { return; } closed = true; if (threadPoolExecutor != null) { threadPoolExecutor.shutdownNow(); threadPoolExecutor = null; } if (feederThread != null) { feederThread.interrupt(); } if (!ingest.isShutdown()) { ingest.shutdown(); } reader.close(); writer.close(); printStream.close(); } private IngestFactory createIngestFactory(final Settings settings) { return new IngestFactory() { @Override public Ingest create() { Integer maxbulkactions = settings.getAsInt("max_bulk_actions", 10000); Integer maxconcurrentbulkrequests = settings.getAsInt("max_concurrent_bulk_requests", Runtime.getRuntime().availableProcessors() * 2); ByteSizeValue maxvolume = settings.getAsBytesSize("max_bulk_volume", ByteSizeValue.parseBytesSizeValue("10m")); TimeValue maxrequestwait = settings.getAsTime("max_request_wait", TimeValue.timeValueSeconds(60)); TimeValue flushinterval = settings.getAsTime("flush_interval", TimeValue.timeValueSeconds(5)); File home = new File(settings.get("home", ".")); BulkTransportClient ingest = new BulkTransportClient(); Settings clientSettings = ImmutableSettings.settingsBuilder() .put("cluster.name", settings.get("elasticsearch.cluster", "elasticsearch")) .put("host", settings.get("elasticsearch.host", "localhost")) .put("port", settings.getAsInt("elasticsearch.port", 9300)) .put("sniff", settings.getAsBoolean("elasticsearch.sniff", false)) .put("name", "feeder") // prevents lookup of names.txt, we don't have it, and marks this node as "feeder". See also module load skipping in JDBCRiverPlugin .put("client.transport.ignore_cluster_name", true) // ignore cluster name setting .put("client.transport.ping_timeout", settings.getAsTime("elasticsearch.timeout", TimeValue.timeValueSeconds(10))) // ping timeout .put("client.transport.nodes_sampler_interval", settings.getAsTime("elasticsearch.timeout", TimeValue.timeValueSeconds(5))) // for sniff sampling .put("path.plugins", ".dontexist") // pointing to a non-exiting folder means, this disables loading site plugins // adding our custom class loader is tricky, actions may not be registered to ActionService .classLoader(getClassLoader(getClass().getClassLoader(), home)) .build(); ingest.maxActionsPerBulkRequest(maxbulkactions) .maxConcurrentBulkRequests(maxconcurrentbulkrequests) .maxVolumePerBulkRequest(maxvolume) .maxRequestWait(maxrequestwait) .flushIngestInterval(flushinterval) .newClient(clientSettings); return ingest; } }; } /** * We have to add Elasticsearch to our classpath, but exclude all jvm plugins * for starting our TransportClient. * * @param home ES_HOME * @return a custom class loader with our dependencies */ private ClassLoader getClassLoader(ClassLoader parent, File home) { URIClassLoader classLoader = new URIClassLoader(parent); File[] libs = new File(home + "/lib").listFiles(); if (libs != null) { for (File file : libs) { if (file.getName().toLowerCase().endsWith(".jar")) { classLoader.addURI(file.toURI()); } } } return classLoader; } }
Java
/* * Copyright @ 2015 Atlassian Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.service.neomedia.stats; import org.jitsi.service.neomedia.*; import java.util.*; /** * An extended interface for accessing the statistics of a {@link MediaStream}. * * The reason to extend the {@link MediaStreamStats} interface rather than * adding methods into it is to allow the implementation to reside in a separate * class. This is desirable in order to: * 1. Help to keep the old interface for backward compatibility. * 2. Provide a "clean" place where future code can be added, thus avoiding * further cluttering of the already overly complicated * {@link org.jitsi.impl.neomedia.MediaStreamStatsImpl}. * * @author Boris Grozev */ public interface MediaStreamStats2 extends MediaStreamStats { /** * @return the instance which keeps aggregate statistics for the associated * {@link MediaStream} in the receive direction. */ ReceiveTrackStats getReceiveStats(); /** * @return the instance which keeps aggregate statistics for the associated * {@link MediaStream} in the send direction. */ SendTrackStats getSendStats(); /** * @return the instance which keeps statistics for a particular SSRC in the * receive direction. */ ReceiveTrackStats getReceiveStats(long ssrc); /** * @return the instance which keeps statistics for a particular SSRC in the * send direction. */ SendTrackStats getSendStats(long ssrc); /** * @return all per-SSRC statistics for the send direction. */ Collection<? extends SendTrackStats> getAllSendStats(); /** * @return all per-SSRC statistics for the receive direction. */ Collection<? extends ReceiveTrackStats> getAllReceiveStats(); /** * Clears send ssrc stats. * @param ssrc the ssrc to clear. */ void clearSendSsrc(long ssrc); }
Java
/* * Licensed to Metamarkets Group Inc. (Metamarkets) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Metamarkets licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.druid.data.input.impl; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Lists; import io.druid.TestObjectMapper; import org.junit.Assert; import org.junit.Test; import javax.validation.constraints.Null; import java.io.IOException; import java.util.Arrays; public class DelimitedParseSpecTest { private final ObjectMapper jsonMapper = new TestObjectMapper(); @Test public void testSerde() throws IOException { DelimitedParseSpec spec = new DelimitedParseSpec( new TimestampSpec("abc", "iso", null,null), new DimensionsSpec(DimensionsSpec.getDefaultSchemas(Arrays.asList("abc")), null, null), "\u0001", "\u0002", Arrays.asList("abc") ); final DelimitedParseSpec serde = jsonMapper.readValue( jsonMapper.writeValueAsString(spec), DelimitedParseSpec.class ); Assert.assertEquals("abc", serde.getTimestampSpec().getTimestampColumn()); Assert.assertEquals("iso", serde.getTimestampSpec().getTimestampFormat()); Assert.assertEquals(Arrays.asList("abc"), serde.getColumns()); Assert.assertEquals("\u0001", serde.getDelimiter()); Assert.assertEquals("\u0002", serde.getListDelimiter()); Assert.assertEquals(Arrays.asList("abc"), serde.getDimensionsSpec().getDimensionNames()); } @Test(expected = IllegalArgumentException.class) public void testColumnMissing() throws Exception { final ParseSpec spec = new DelimitedParseSpec( new TimestampSpec( "timestamp", "auto", null, null ), new DimensionsSpec( DimensionsSpec.getDefaultSchemas(Arrays.asList("a", "b")), Lists.<String>newArrayList(), Lists.<SpatialDimensionSchema>newArrayList() ), ",", " ", Arrays.asList("a") ); } @Test(expected = IllegalArgumentException.class) public void testComma() throws Exception { final ParseSpec spec = new DelimitedParseSpec( new TimestampSpec( "timestamp", "auto", null, null ), new DimensionsSpec( DimensionsSpec.getDefaultSchemas(Arrays.asList("a,", "b")), Lists.<String>newArrayList(), Lists.<SpatialDimensionSchema>newArrayList() ), ",", null, Arrays.asList("a") ); } @Test(expected = NullPointerException.class) public void testDefaultColumnList(){ final DelimitedParseSpec spec = new DelimitedParseSpec( new TimestampSpec( "timestamp", "auto", null, null ), new DimensionsSpec( DimensionsSpec.getDefaultSchemas(Arrays.asList("a", "b")), Lists.<String>newArrayList(), Lists.<SpatialDimensionSchema>newArrayList() ), ",", null, // pass null columns not allowed null ); } }
Java
# Dovyalis engleri Gilg SPECIES #### Status ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
Java
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.elasticloadbalancing.model; import java.io.Serializable; /** * */ public class RegisterInstancesWithLoadBalancerResult implements Serializable, Cloneable { /** * The updated list of instances for the load balancer. */ private com.amazonaws.internal.ListWithAutoConstructFlag<Instance> instances; /** * The updated list of instances for the load balancer. * * @return The updated list of instances for the load balancer. */ public java.util.List<Instance> getInstances() { if (instances == null) { instances = new com.amazonaws.internal.ListWithAutoConstructFlag<Instance>(); instances.setAutoConstruct(true); } return instances; } /** * The updated list of instances for the load balancer. * * @param instances The updated list of instances for the load balancer. */ public void setInstances(java.util.Collection<Instance> instances) { if (instances == null) { this.instances = null; return; } com.amazonaws.internal.ListWithAutoConstructFlag<Instance> instancesCopy = new com.amazonaws.internal.ListWithAutoConstructFlag<Instance>(instances.size()); instancesCopy.addAll(instances); this.instances = instancesCopy; } /** * The updated list of instances for the load balancer. * <p> * <b>NOTE:</b> This method appends the values to the existing list (if * any). Use {@link #setInstances(java.util.Collection)} or {@link * #withInstances(java.util.Collection)} if you want to override the * existing values. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param instances The updated list of instances for the load balancer. * * @return A reference to this updated object so that method calls can be chained * together. */ public RegisterInstancesWithLoadBalancerResult withInstances(Instance... instances) { if (getInstances() == null) setInstances(new java.util.ArrayList<Instance>(instances.length)); for (Instance value : instances) { getInstances().add(value); } return this; } /** * The updated list of instances for the load balancer. * <p> * Returns a reference to this object so that method calls can be chained together. * * @param instances The updated list of instances for the load balancer. * * @return A reference to this updated object so that method calls can be chained * together. */ public RegisterInstancesWithLoadBalancerResult withInstances(java.util.Collection<Instance> instances) { if (instances == null) { this.instances = null; } else { com.amazonaws.internal.ListWithAutoConstructFlag<Instance> instancesCopy = new com.amazonaws.internal.ListWithAutoConstructFlag<Instance>(instances.size()); instancesCopy.addAll(instances); this.instances = instancesCopy; } return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getInstances() != null) sb.append("Instances: " + getInstances() ); sb.append("}"); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getInstances() == null) ? 0 : getInstances().hashCode()); return hashCode; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof RegisterInstancesWithLoadBalancerResult == false) return false; RegisterInstancesWithLoadBalancerResult other = (RegisterInstancesWithLoadBalancerResult)obj; if (other.getInstances() == null ^ this.getInstances() == null) return false; if (other.getInstances() != null && other.getInstances().equals(this.getInstances()) == false) return false; return true; } @Override public RegisterInstancesWithLoadBalancerResult clone() { try { return (RegisterInstancesWithLoadBalancerResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException( "Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
Java
package com.example.godtemper.db; import java.util.ArrayList; import java.util.List; import com.example.godtemper.model.City; import com.example.godtemper.model.County; import com.example.godtemper.model.Province; import android.R.integer; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; public class GodTemperDB { /** * Êý¾Ý¿âÃû */ public static final String DB_NAME = "GodTemper"; /** * Êý¾Ý¿â°æ±¾ */ public static final int VERSION = 1; private static GodTemperDB godTemperDB; private SQLiteDatabase db; private GodTemperDB(Context context){ GodTemperOpenHelper dbHelper = new GodTemperOpenHelper(context, DB_NAME, null, VERSION); db = dbHelper.getWritableDatabase(); } /** * »ñÈ¡godTemperDBµÄʵÀý * @param context * @return */ public synchronized static GodTemperDB getInstance(Context context){ if(godTemperDB == null){ godTemperDB = new GodTemperDB(context); } return godTemperDB; } /** * ½«ProvinceʵÀý´æ´¢µ½Êý¾Ý¿â * @param province */ public void saveProvince(Province province){ if(province != null){ ContentValues values = new ContentValues(); values.put("province_name", province.getProvinceName()); values.put("province_code", province.getProvinceCode()); db.insert("Province", null, values); } } /** * ´ÓÊý¾Ý¿â¶Áȡȫ¹úËùÓÐÊ¡·ÝµÄÐÅÏ¢ * @return */ public List<Province>loadProvinces(){ List<Province>list = new ArrayList<Province>(); Cursor cursor = db.query("Province", null, null, null, null, null, null); if(cursor.moveToFirst()){ do{ Province province = new Province(); province.setId(cursor.getInt(cursor.getColumnIndex("id"))); province.setProvinceName(cursor.getString(cursor.getColumnIndex("province_name"))); province.setProvinceCode(cursor.getString(cursor.getColumnIndex("province_code"))); list.add(province); }while(cursor.moveToNext()); } return list; } /** * ½«CityʵÀý´æ´¢µ½Êý¾Ý¿â * @param city */ public void saveCity(City city) { if(city!=null){ ContentValues values = new ContentValues(); values.put("city_name", city.getCityName()); values.put("city_code", city.getCityCode()); values.put("province_id", city.getProvinceId()); db.insert("City", null, values); } } /** * ´ÓÊý¾Ý¿â¶ÁȡijʡÏÂËùÓеijÇÊÐÐÅÏ¢ * @param provinceId * @return */ public List<City> loadCities(int provinceId) { List<City>list = new ArrayList<City>(); Cursor cursor = db.query("City", null, "province_id = ?", new String[]{String.valueOf(provinceId)}, null,null,null); if(cursor.moveToFirst()){ do{ City city = new City(); city.setId(cursor.getInt(cursor.getColumnIndex("id"))); city.setCityName(cursor.getString(cursor.getColumnIndex("city_name"))); city.setCityCode(cursor.getString(cursor.getColumnIndex("city_code"))); city.setProvinceId(provinceId); list.add(city); }while(cursor.moveToNext()); } return list; } /** * ½«CountyʵÀý´æ´¢µ½Êý¾Ý¿â */ public void saveCounty(County county){ if(county != null){ ContentValues values = new ContentValues(); values.put("county_name", county.getCountyName()); values.put("county_code", county.getCountyCode()); values.put("city_id", county.getCityId()); db.insert("County", null, values); } } /** * ´ÓÊý¾Ý¿â¶Áȡij³ÇÊÐÏÂËùÓÐÏØµÄÐÅÏ¢ */ public List<County>loadCounties (int cityId){ List<County>list = new ArrayList<County>(); Cursor cursor = db.query("County", null, "city_id = ?", new String[]{String.valueOf(cityId)}, null, null, null); if(cursor.moveToFirst()){ do{ County county = new County(); county.setId(cursor.getInt(cursor.getColumnIndex("id"))); county.setCountyName(cursor.getString(cursor.getColumnIndex("county_name"))); county.setCountyCode(cursor.getString(cursor.getColumnIndex("county_code"))); county.setCityId(cityId); list.add(county); }while(cursor.moveToNext()); } return list; } }
Java
<?php return array( //'配置项'=>'配置值' /* 调试设定 */ 'SHOW_PAGE_TRACE' =>false, // 显示页面Trace信息 // 'SHOW_RUN_TIME'=>true, // 运行时间显示 // 'SHOW_ADV_TIME'=>true, // 显示详细的运行时间 // 'SHOW_DB_TIMES'=>true, // 显示数据库查询和写入次数 // 'SHOW_CACHE_TIMES'=>true, // 显示缓存操作次数 // 'SHOW_USE_MEM'=>true, // 显示内存开销 // 'SHOW_LOAD_FILE' =>true, // 显示加载文件数 // 'SHOW_FUN_TIMES'=>true , // 显示函数调用次数 /* 数据库设置 */ 'DB_TYPE' => 'mysql', // 数据库类型 'DB_HOST' => '127.0.0.1', // 服务器地址 'DB_NAME' => 'ts', // 数据库名 'DB_USER' => 'root', // 用户名 'DB_PWD' => '123456', // 密码 'DB_PORT' => '3306', // 端口 'DB_PREFIX' => 'treesys_', // 数据库表前缀 'DB_FIELDTYPE_CHECK' => false, // 是否进行字段类型检查 'DB_FIELDS_CACHE' => true, // 启用字段缓存 'DB_CHARSET' => 'utf8', // 数据库编码默认采用utf8 'DB_DEPLOY_TYPE' => 0, // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器) 'DB_RW_SEPARATE' => false, // 数据库读写是否分离 主从式有效 'DB_MASTER_NUM' => 1, // 读写分离后 主服务器数量 'DB_SQL_BUILD_CACHE' => true, // 数据库查询的SQL创建缓存 'DB_SQL_BUILD_QUEUE' => 'file', // SQL缓存队列的缓存方式 支持 file xcache和apc 'DB_SQL_BUILD_LENGTH' => 20, // SQL缓存的队列长度 'VAR_PAGE' =>'p', //分页参数 ); ?>
Java
'use strict'; module.exports = function(config) { config.set({ files: [ 'tests/main.js', {pattern: 'app/js/**/*.js', included: false}, {pattern: 'app/bower_components/**/*.js', included: false}, {pattern: 'tests/specs/**/*.js', included: false}, {pattern: 'tests/fixtures/**/*.js', included: false} ], basePath: '../', frameworks: ['jasmine', 'requirejs'], reporters: ['progress'], runnerPort: 9000, singleRun: true, browsers: ['PhantomJS', 'Chrome'], logLevel: 'ERROR' }); };
Java
# Ericameria viscidiflora var. stenophylla (A.Gray) L.C.Anderson VARIETY #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
Java
/* * Copyright 2012 Delving B.V. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package models.cms import com.mongodb.casbah.Imports.{ MongoCollection, MongoDB } import com.mongodb.casbah.query.Imports._ import org.bson.types.ObjectId import com.novus.salat.dao.SalatDAO import models.HubMongoContext._ import com.mongodb.casbah.commons.MongoDBObject import models.{ OrganizationConfiguration, MultiModel } import play.api.i18n.Lang /** * * @author Manuel Bernhardt <bernhardt.manuel@gmail.com> */ case class CMSPage( _id: ObjectId = new ObjectId(), key: String, // the key of this page (unique across all version sets of pages) userName: String, // who created the page lang: String, // 2-letters ISO code of the page language title: String, // title of the page in this language content: String, // actual page content (text) isSnippet: Boolean = false, // is this a snippet in the welcome page or not published: Boolean = false // is this page published, i.e. visible? ) case class MenuEntry( _id: ObjectId = new ObjectId(), menuKey: String, // key of the menu this entry belongs to parentMenuKey: Option[String] = None, // parent menu key. if none is provided this entry is not part of a sub-menu position: Int, // position of this menu entry inside of the menu title: Map[String, String], // title of this menu entry, per language targetPageKey: Option[String] = None, // key of the page this menu entry links to, if any targetMenuKey: Option[String] = None, // key of the target menu this entry links to, if any targetUrl: Option[String] = None, // URL this menu entry links to, if any published: Boolean = false // is this entry published, i.e. visible ? ) case class ListEntry(page: CMSPage, menuEntry: MenuEntry) /** Represents a menu, which is not persisted at the time being **/ case class Menu( key: String, parentMenuKey: Option[String], title: Map[String, String]) object CMSPage extends MultiModel[CMSPage, CMSPageDAO] { def connectionName: String = "CMSPages" def initIndexes(collection: MongoCollection) { addIndexes(collection, Seq(MongoDBObject("_id" -> 1, "language" -> 1))) } def initDAO(collection: MongoCollection, connection: MongoDB)(implicit configuration: OrganizationConfiguration): CMSPageDAO = new CMSPageDAO(collection) } class CMSPageDAO(collection: MongoCollection)(implicit configuration: OrganizationConfiguration) extends SalatDAO[CMSPage, ObjectId](collection) { def entryList(lang: Lang, menuKey: Option[String]): List[ListEntry] = { val allEntries = MenuEntry.dao.findAll().toList val relevantEntries = if (menuKey.isEmpty) allEntries.filterNot(_.menuKey == "news") else allEntries.filter(_.menuKey == menuKey.get) val entries = relevantEntries.flatMap( menuEntry => find(MongoDBObject( "lang" -> lang.language, "key" -> menuEntry.targetPageKey )).toList.map( page => ListEntry(page, menuEntry) ) ) entries.groupBy(_.page.key).map(m => m._2.sortBy(_.page._id).reverse.head).toList } def findByKey(key: String): List[CMSPage] = find(MongoDBObject("key" -> key)).$orderby(MongoDBObject("_id" -> -1)).toList def findByKeyAndLanguage(key: String, lang: String): List[CMSPage] = find(queryByKeyAndLanguage(key, lang)).$orderby(MongoDBObject("_id" -> -1)).toList def create(key: String, lang: String, userName: String, title: String, content: String, published: Boolean): CMSPage = { val page = CMSPage(key = key, userName = userName, title = title, content = content, isSnippet = false, lang = lang, published = published) val inserted = insert(page) page.copy(_id = inserted.get) } def delete(key: String, lang: String) { remove(MongoDBObject("key" -> key, "lang" -> lang)) } val MAX_VERSIONS = 20 def removeOldVersions(key: String, lang: String) { val versions = findByKeyAndLanguage(key, lang) if (versions.length > MAX_VERSIONS) { val id = versions(MAX_VERSIONS - 1)._id find(("_id" $lt id) ++ queryByKeyAndLanguage(key, lang)).foreach(remove) } } private def queryByKeyAndLanguage(key: String, lang: String) = MongoDBObject("key" -> key, "lang" -> lang) } object MenuEntry extends MultiModel[MenuEntry, MenuEntryDAO] { def connectionName: String = "CMSMenuEntries" def initIndexes(collection: MongoCollection) { addIndexes(collection, Seq(MongoDBObject("menuKey" -> 1))) addIndexes(collection, Seq(MongoDBObject("menuKey" -> 1, "parentKey" -> 1))) } def initDAO(collection: MongoCollection, connection: MongoDB)(implicit configuration: OrganizationConfiguration): MenuEntryDAO = new MenuEntryDAO(collection) } class MenuEntryDAO(collection: MongoCollection) extends SalatDAO[MenuEntry, ObjectId](collection) { def findOneByKey(menuKey: String) = findOne(MongoDBObject("menuKey" -> menuKey)) def findOneByMenuKeyAndTargetMenuKey(menuKey: String, targetMenuKey: String) = findOne(MongoDBObject("menuKey" -> menuKey, "targetMenuKey" -> targetMenuKey)) def findOneByTargetPageKey(targetPageKey: String) = findOne(MongoDBObject("targetPageKey" -> targetPageKey)) def findOneByMenuAndPage(orgId: String, menuKey: String, pageKey: String) = findOne(MongoDBObject("orgId" -> orgId, "menuKey" -> menuKey, "targetPageKey" -> pageKey)) def findEntries(orgId: String, menuKey: String, parentKey: String) = { find(MongoDBObject("orgId" -> orgId, "menuKey" -> menuKey, "parentKey" -> parentKey)).$orderby(MongoDBObject("position" -> 1)) } def findEntries(menuKey: String) = find(MongoDBObject("menuKey" -> menuKey)).$orderby(MongoDBObject("position" -> 1)) def findAll() = find(MongoDBObject()) /** * Adds a page to a menu (root menu). If the menu entry already exists, updates the position and title. */ def savePage(menuKey: String, targetPageKey: String, position: Int, title: String, lang: String, published: Boolean) { findOneByTargetPageKey(targetPageKey) match { case Some(existing) => val updatedEntry = existing.copy(position = position, menuKey = menuKey, title = existing.title + (lang -> title), published = published) save(updatedEntry) // update position of siblings by shifting them to the right update(MongoDBObject("menuKey" -> menuKey, "published" -> published) ++ ("position" $gte (position)) ++ ("targetPageKey" $ne (targetPageKey)), $inc("position" -> 1)) case None => val newEntry = MenuEntry(menuKey = menuKey, parentMenuKey = None, position = position, targetPageKey = Some(targetPageKey), title = Map(lang -> title), published = published) insert(newEntry) } } def removePage(targetPageKey: String, lang: String) { findOne(MongoDBObject("targetPageKey" -> targetPageKey)) match { case Some(entry) => val updated = entry.copy(title = (entry.title.filterNot(_._1 == lang))) if (updated.title.isEmpty) { removeById(updated._id) } else { save(updated) } case None => // nothing } } }
Java
// Copyright 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "exegesis/x86/cleanup_instruction_set_fix_operands.h" #include <algorithm> #include <iterator> #include <string> #include <vector> #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/container/node_hash_map.h" #include "absl/status/status.h" #include "absl/strings/str_cat.h" #include "exegesis/base/cleanup_instruction_set.h" #include "exegesis/proto/instructions.pb.h" #include "exegesis/util/instruction_syntax.h" #include "exegesis/x86/cleanup_instruction_set_utils.h" #include "glog/logging.h" #include "src/google/protobuf/repeated_field.h" #include "util/gtl/map_util.h" namespace exegesis { namespace x86 { namespace { using ::google::protobuf::RepeatedPtrField; // Mapping from memory operands to their sizes as used in the Intel assembly // syntax. const std::pair<const char*, const char*> kOperandToPointerSize[] = { {"m8", "BYTE"}, {"m16", "WORD"}, {"m32", "DWORD"}, {"m64", "QWORD"}}; // List of RSI-indexed source arrays. const char* kRSIIndexes[] = {"BYTE PTR [RSI]", "WORD PTR [RSI]", "DWORD PTR [RSI]", "QWORD PTR [RSI]"}; // List of RDI-indexed destination arrays. const char* kRDIIndexes[] = {"BYTE PTR [RDI]", "WORD PTR [RDI]", "DWORD PTR [RDI]", "QWORD PTR [RDI]"}; } // namespace absl::Status FixOperandsOfCmpsAndMovs(InstructionSetProto* instruction_set) { CHECK(instruction_set != nullptr); const absl::flat_hash_set<std::string> kMnemonics = {"CMPS", "MOVS"}; const absl::flat_hash_set<std::string> kSourceOperands( std::begin(kRSIIndexes), std::begin(kRSIIndexes)); const absl::flat_hash_set<std::string> kDestinationOperands( std::begin(kRDIIndexes), std::begin(kRDIIndexes)); const absl::flat_hash_map<std::string, std::string> operand_to_pointer_size( std::begin(kOperandToPointerSize), std::end(kOperandToPointerSize)); absl::Status status = absl::OkStatus(); for (InstructionProto& instruction : *instruction_set->mutable_instructions()) { InstructionFormat* const vendor_syntax = GetOrAddUniqueVendorSyntaxOrDie(&instruction); if (!kMnemonics.contains(vendor_syntax->mnemonic())) { continue; } if (vendor_syntax->operands_size() != 2) { status = absl::InvalidArgumentError( "Unexpected number of operands of a CMPS/MOVS instruction."); LOG(ERROR) << status; continue; } std::string pointer_size; if (!gtl::FindCopy(operand_to_pointer_size, vendor_syntax->operands(0).name(), &pointer_size) && !kSourceOperands.contains(vendor_syntax->operands(0).name()) && !kDestinationOperands.contains(vendor_syntax->operands(0).name())) { status = absl::InvalidArgumentError( absl::StrCat("Unexpected operand of a CMPS/MOVS instruction: ", vendor_syntax->operands(0).name())); LOG(ERROR) << status; continue; } CHECK_EQ(vendor_syntax->operands_size(), 2); // The correct syntax for MOVS is MOVSB BYTE PTR [RDI],BYTE PTR [RSI] // (destination is the right operand, as expected in the Intel syntax), // while for CMPS LLVM only supports CMPSB BYTE PTR [RSI],BYTE PTR [RDI]. // The following handles this. constexpr const char* const kIndexings[] = {"[RDI]", "[RSI]"}; const int dest = vendor_syntax->mnemonic() == "MOVS" ? 0 : 1; const int src = 1 - dest; vendor_syntax->mutable_operands(0)->set_name( absl::StrCat(pointer_size, " PTR ", kIndexings[dest])); vendor_syntax->mutable_operands(0)->set_usage( dest == 0 ? InstructionOperand::USAGE_WRITE : InstructionOperand::USAGE_READ); vendor_syntax->mutable_operands(1)->set_name( absl::StrCat(pointer_size, " PTR ", kIndexings[src])); vendor_syntax->mutable_operands(1)->set_usage( InstructionOperand::USAGE_READ); } return status; } REGISTER_INSTRUCTION_SET_TRANSFORM(FixOperandsOfCmpsAndMovs, 2000); absl::Status FixOperandsOfInsAndOuts(InstructionSetProto* instruction_set) { constexpr char kIns[] = "INS"; constexpr char kOuts[] = "OUTS"; const absl::flat_hash_map<std::string, std::string> operand_to_pointer_size( std::begin(kOperandToPointerSize), std::end(kOperandToPointerSize)); absl::Status status = absl::OkStatus(); for (InstructionProto& instruction : *instruction_set->mutable_instructions()) { InstructionFormat* const vendor_syntax = GetOrAddUniqueVendorSyntaxOrDie(&instruction); const bool is_ins = vendor_syntax->mnemonic() == kIns; const bool is_outs = vendor_syntax->mnemonic() == kOuts; if (!is_ins && !is_outs) { continue; } if (vendor_syntax->operands_size() != 2) { status = absl::InvalidArgumentError( "Unexpected number of operands of an INS/OUTS instruction."); LOG(ERROR) << status; continue; } std::string pointer_size; if (!gtl::FindCopy(operand_to_pointer_size, vendor_syntax->operands(0).name(), &pointer_size) && !gtl::FindCopy(operand_to_pointer_size, vendor_syntax->operands(1).name(), &pointer_size)) { status = absl::InvalidArgumentError( absl::StrCat("Unexpected operands of an INS/OUTS instruction: ", vendor_syntax->operands(0).name(), ", ", vendor_syntax->operands(1).name())); LOG(ERROR) << status; continue; } CHECK_EQ(vendor_syntax->operands_size(), 2); if (is_ins) { vendor_syntax->mutable_operands(0)->set_name( absl::StrCat(pointer_size, " PTR [RDI]")); vendor_syntax->mutable_operands(0)->set_usage( InstructionOperand::USAGE_WRITE); vendor_syntax->mutable_operands(1)->set_name("DX"); vendor_syntax->mutable_operands(1)->set_usage( InstructionOperand::USAGE_READ); } else { CHECK(is_outs); vendor_syntax->mutable_operands(0)->set_name("DX"); vendor_syntax->mutable_operands(0)->set_usage( InstructionOperand::USAGE_READ); vendor_syntax->mutable_operands(1)->set_name( absl::StrCat(pointer_size, " PTR [RSI]")); vendor_syntax->mutable_operands(1)->set_usage( InstructionOperand::USAGE_READ); } } return status; } REGISTER_INSTRUCTION_SET_TRANSFORM(FixOperandsOfInsAndOuts, 2000); absl::Status FixOperandsOfLddqu(InstructionSetProto* instruction_set) { constexpr char kMemOperand[] = "mem"; constexpr char kM128Operand[] = "m128"; constexpr char kLddquEncoding[] = "F2 0F F0 /r"; for (InstructionProto& instruction : *instruction_set->mutable_instructions()) { if (instruction.raw_encoding_specification() != kLddquEncoding) continue; InstructionFormat* const vendor_syntax = GetOrAddUniqueVendorSyntaxOrDie(&instruction); for (InstructionOperand& operand : *vendor_syntax->mutable_operands()) { if (operand.name() == kMemOperand) { operand.set_name(kM128Operand); } } } return absl::OkStatus(); } REGISTER_INSTRUCTION_SET_TRANSFORM(FixOperandsOfLddqu, 2000); absl::Status FixOperandsOfLodsScasAndStos( InstructionSetProto* instruction_set) { // Note that we're matching only the versions with operands. These versions // use the mnemonics without the size suffix. By matching exactly these names, // we can easily avoid the operand-less versions. constexpr char kLods[] = "LODS"; constexpr char kScas[] = "SCAS"; constexpr char kStos[] = "STOS"; const absl::flat_hash_map<std::string, std::string> operand_to_pointer_size( std::begin(kOperandToPointerSize), std::end(kOperandToPointerSize)); const absl::flat_hash_map<std::string, std::string> kOperandToRegister = { {"m8", "AL"}, {"m16", "AX"}, {"m32", "EAX"}, {"m64", "RAX"}}; absl::Status status = absl::OkStatus(); for (InstructionProto& instruction : *instruction_set->mutable_instructions()) { InstructionFormat* const vendor_syntax = GetOrAddUniqueVendorSyntaxOrDie(&instruction); const bool is_lods = vendor_syntax->mnemonic() == kLods; const bool is_stos = vendor_syntax->mnemonic() == kStos; const bool is_scas = vendor_syntax->mnemonic() == kScas; if (!is_lods && !is_stos && !is_scas) { continue; } if (vendor_syntax->operands_size() != 1) { status = absl::InvalidArgumentError( "Unexpected number of operands of a LODS/STOS instruction."); LOG(ERROR) << status; continue; } std::string register_operand; std::string pointer_size; if (!gtl::FindCopy(kOperandToRegister, vendor_syntax->operands(0).name(), &register_operand) || !gtl::FindCopy(operand_to_pointer_size, vendor_syntax->operands(0).name(), &pointer_size)) { status = absl::InvalidArgumentError( absl::StrCat("Unexpected operand of a LODS/STOS instruction: ", vendor_syntax->operands(0).name())); LOG(ERROR) << status; continue; } vendor_syntax->clear_operands(); if (is_stos) { auto* const operand = vendor_syntax->add_operands(); operand->set_name(absl::StrCat(pointer_size, " PTR [RDI]")); operand->set_encoding(InstructionOperand::IMPLICIT_ENCODING); operand->set_usage(InstructionOperand::USAGE_READ); } auto* const operand = vendor_syntax->add_operands(); operand->set_encoding(InstructionOperand::IMPLICIT_ENCODING); operand->set_name(register_operand); operand->set_usage(InstructionOperand::USAGE_READ); if (is_lods) { auto* const operand = vendor_syntax->add_operands(); operand->set_encoding(InstructionOperand::IMPLICIT_ENCODING); operand->set_name(absl::StrCat(pointer_size, " PTR [RSI]")); operand->set_usage(InstructionOperand::USAGE_READ); } if (is_scas) { auto* const operand = vendor_syntax->add_operands(); operand->set_encoding(InstructionOperand::IMPLICIT_ENCODING); operand->set_name(absl::StrCat(pointer_size, " PTR [RDI]")); operand->set_usage(InstructionOperand::USAGE_READ); } } return status; } REGISTER_INSTRUCTION_SET_TRANSFORM(FixOperandsOfLodsScasAndStos, 2000); absl::Status FixOperandsOfSgdtAndSidt(InstructionSetProto* instruction_set) { CHECK(instruction_set != nullptr); const absl::flat_hash_set<std::string> kEncodings = {"0F 01 /0", "0F 01 /1"}; constexpr char kMemoryOperandName[] = "m"; constexpr char kUpdatedMemoryOperandName[] = "m16&64"; for (InstructionProto& instruction : *instruction_set->mutable_instructions()) { if (kEncodings.contains(instruction.raw_encoding_specification())) { InstructionFormat* const vendor_syntax = GetOrAddUniqueVendorSyntaxOrDie(&instruction); for (InstructionOperand& operand : *vendor_syntax->mutable_operands()) { if (operand.name() == kMemoryOperandName) { operand.set_name(kUpdatedMemoryOperandName); } } } } return absl::OkStatus(); } REGISTER_INSTRUCTION_SET_TRANSFORM(FixOperandsOfSgdtAndSidt, 2000); absl::Status FixOperandsOfVMovq(InstructionSetProto* instruction_set) { CHECK(instruction_set != nullptr); constexpr char kVMovQEncoding[] = "VEX.128.F3.0F.WIG 7E /r"; constexpr char kRegisterOrMemoryOperand[] = "xmm2/m64"; ::google::protobuf::RepeatedPtrField<InstructionProto>* const instructions = instruction_set->mutable_instructions(); for (InstructionProto& instruction : *instructions) { if (instruction.raw_encoding_specification() != kVMovQEncoding) continue; InstructionFormat* const vendor_syntax = GetOrAddUniqueVendorSyntaxOrDie(&instruction); if (vendor_syntax->operands_size() != 2) { return absl::InvalidArgumentError( absl::StrCat("Unexpected number of operands of a VMOVQ instruction: ", instruction.DebugString())); } vendor_syntax->mutable_operands(1)->set_name(kRegisterOrMemoryOperand); } return absl::OkStatus(); } REGISTER_INSTRUCTION_SET_TRANSFORM(FixOperandsOfVMovq, 2000); absl::Status FixRegOperands(InstructionSetProto* instruction_set) { CHECK(instruction_set != nullptr); constexpr char kR8Operand[] = "r8"; constexpr char kR16Operand[] = "r16"; constexpr char kR32Operand[] = "r32"; constexpr char kR64Operand[] = "r64"; constexpr char kRegOperand[] = "reg"; // The mnemonics for which we add new entries. const absl::flat_hash_set<std::string> kExpandToAllSizes = {"LAR"}; // The mnemonics for which we just replace reg with r8/r16/r32. const absl::flat_hash_set<std::string> kRenameToReg8 = {"VPBROADCASTB"}; const absl::flat_hash_set<std::string> kRenameToReg16 = {"VPBROADCASTW"}; const absl::flat_hash_set<std::string> kRenameToReg32 = { "EXTRACTPS", "MOVMSKPD", "MOVMSKPS", "PEXTRB", "PEXTRW", "PMOVMSKB", "VMOVMSKPD", "VMOVMSKPS", "VPEXTRB", "VPEXTRW", "VPMOVMSKB"}; // We can't safely add new entries to 'instructions' while we iterate over it. // Instead, we collect the instructions in a separate vector and add it to the // proto at the end. std::vector<InstructionProto> new_instruction_protos; ::google::protobuf::RepeatedPtrField<InstructionProto>* const instructions = instruction_set->mutable_instructions(); absl::Status status = absl::OkStatus(); for (InstructionProto& instruction : *instructions) { InstructionFormat* const vendor_syntax = GetOrAddUniqueVendorSyntaxOrDie(&instruction); const std::string& mnemonic = vendor_syntax->mnemonic(); for (auto& operand : *vendor_syntax->mutable_operands()) { if (operand.name() == kRegOperand) { if (kExpandToAllSizes.contains(mnemonic)) { // This is a bit hacky. To avoid complicated matching of registers, we // just override the existing entry in the instruction set proto, add // the modified proto to new_instruction_protos except for the last // modification which we keep in the instruction set proto. // // This is safe as long as there is only one reg operand per entry // (which is true in the current version of the data). operand.set_name(kR32Operand); new_instruction_protos.push_back(instruction); operand.set_name(kR64Operand); instruction.set_raw_encoding_specification( "REX.W + " + instruction.raw_encoding_specification()); } else if (kRenameToReg8.contains(mnemonic)) { operand.set_name(kR8Operand); } else if (kRenameToReg16.contains(mnemonic)) { operand.set_name(kR16Operand); } else if (kRenameToReg32.contains(mnemonic)) { operand.set_name(kR32Operand); } else { status = absl::InvalidArgumentError( absl::StrCat("Unexpected instruction mnemonic: ", mnemonic)); LOG(ERROR) << status; continue; } } } } std::copy(new_instruction_protos.begin(), new_instruction_protos.end(), ::google::protobuf::RepeatedPtrFieldBackInserter(instructions)); return status; } REGISTER_INSTRUCTION_SET_TRANSFORM(FixRegOperands, 2000); absl::Status RenameOperands(InstructionSetProto* instruction_set) { CHECK(instruction_set != nullptr); const absl::flat_hash_map<std::string, std::string> kOperandRenaming = { // Synonyms (different names used for the same type in different parts of // the manual). {"m80dec", "m80bcd"}, {"r8/m8", "r/m8"}, {"r16/m16", "r/m16"}, {"r32/m32", "r/m32"}, {"r64/m64", "r/m64"}, {"ST", "ST(0)"}, // Variants that depend on the mode of the CPU. The 32- and 64-bit modes // always use the larger of the two values. {"m14/28byte", "m28byte"}, {"m94/108byte", "m108byte"}}; for (InstructionProto& instruction : *instruction_set->mutable_instructions()) { InstructionFormat* const vendor_syntax = GetOrAddUniqueVendorSyntaxOrDie(&instruction); for (auto& operand : *vendor_syntax->mutable_operands()) { const std::string* renaming = gtl::FindOrNull(kOperandRenaming, operand.name()); if (renaming != nullptr) { operand.set_name(*renaming); } } } return absl::OkStatus(); } REGISTER_INSTRUCTION_SET_TRANSFORM(RenameOperands, 2000); absl::Status RemoveImplicitST0Operand(InstructionSetProto* instruction_set) { CHECK(instruction_set != nullptr); static constexpr char kImplicitST0Operand[] = "ST(0)"; const absl::flat_hash_set<std::string> kUpdatedInstructionEncodings = { "D8 C0+i", "D8 C8+i", "D8 E0+i", "D8 E8+i", "D8 F0+i", "D8 F8+i", "DB E8+i", "DB F0+i", "DE C0+i", "DE C8+i", "DE E0+i", "DE E8+i", "DE F0+i", "DE F8+i", "DF E8+i", "DF F0+i", }; for (InstructionProto& instruction : *instruction_set->mutable_instructions()) { if (!kUpdatedInstructionEncodings.contains( instruction.raw_encoding_specification())) { continue; } RepeatedPtrField<InstructionOperand>* const operands = GetOrAddUniqueVendorSyntaxOrDie(&instruction)->mutable_operands(); operands->erase(std::remove_if(operands->begin(), operands->end(), [](const InstructionOperand& operand) { return operand.name() == kImplicitST0Operand; }), operands->end()); } return absl::OkStatus(); } REGISTER_INSTRUCTION_SET_TRANSFORM(RemoveImplicitST0Operand, 2000); absl::Status RemoveImplicitOperands(InstructionSetProto* instruction_set) { CHECK(instruction_set != nullptr); const absl::flat_hash_set<absl::string_view> kImplicitXmmOperands = { "<EAX>", "<XMM0>", "<XMM0-2>", "<XMM0-6>", "<XMM0-7>", "<XMM4-6>"}; for (InstructionProto& instruction : *instruction_set->mutable_instructions()) { RepeatedPtrField<InstructionOperand>* const operands = GetOrAddUniqueVendorSyntaxOrDie(&instruction)->mutable_operands(); operands->erase( std::remove_if( operands->begin(), operands->end(), [&kImplicitXmmOperands](const InstructionOperand& operand) { return kImplicitXmmOperands.contains(operand.name()); }), operands->end()); } return absl::OkStatus(); } REGISTER_INSTRUCTION_SET_TRANSFORM(RemoveImplicitOperands, 2000); } // namespace x86 } // namespace exegesis
Java
require 'spec_helper' describe Rtime::Executor do let :executor do Rtime::Executor.new end describe 'execute' do it 'needs arguments to execute' do expect { executor.execute }.to raise_error ArgumentError end it 'times the executed process' do expect(executor.timer).to receive(:time).and_call_original executor.execute 'true' end it 'returns a filled Rtime::Result' do result = executor.execute('true', name: 'the name') expect(result).to be_a Rtime::Result expect(result.start).to be_a Time expect(result.pid).to respond_to :to_int expect(result.duration).to be_a Float expect(result.exitstatus).to eq 0 expect(result.name).to eq 'the name' end end describe 'measure' do it 'needs a name argument to execute' do expect { executor.measure do end }.to raise_error ArgumentError end it 'needs a block to call' do expect { executor.measure('foo') }.to raise_error ArgumentError end it 'measures times of a block' do executed = false result = executor.measure('the name') do executed = true end expect(executed).to eq true expect(result).to be_a Rtime::Result expect(result.start).to be_a Time expect(result.pid).to eq $$ expect(result.duration).to be_a Float expect(result.exitstatus).to eq 0 expect(result.name).to eq 'the name' end end end
Java
package org.axway.grapes.server.webapp.resources; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.GenericType; import com.sun.jersey.api.client.WebResource; import com.yammer.dropwizard.auth.basic.BasicAuthProvider; import com.yammer.dropwizard.testing.ResourceTest; import org.axway.grapes.commons.api.ServerAPI; import org.axway.grapes.server.GrapesTestUtils; import org.axway.grapes.server.config.GrapesServerConfig; import org.axway.grapes.server.core.options.FiltersHolder; import org.axway.grapes.server.db.RepositoryHandler; import org.axway.grapes.server.db.datamodel.DbCredential; import org.axway.grapes.server.db.datamodel.DbSearch; import org.axway.grapes.server.webapp.auth.GrapesAuthenticator; import org.eclipse.jetty.http.HttpStatus; import org.junit.Test; import javax.ws.rs.core.MediaType; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.mockito.Matchers.anyObject; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class WebSearchResourceTest extends ResourceTest { private RepositoryHandler repositoryHandler; @Override protected void setUpResources() throws Exception { repositoryHandler = GrapesTestUtils.getRepoHandlerMock(); final GrapesServerConfig config = mock(GrapesServerConfig.class); final WebSearchResource resource = new WebSearchResource(repositoryHandler, config); addProvider(new BasicAuthProvider<DbCredential>(new GrapesAuthenticator(repositoryHandler), "test auth")); addResource(resource); } @Test public void getSearchResult() throws Exception { List<String> moduleIds = new ArrayList<>(); moduleIds.add("testSearch_id_1"); moduleIds.add("testSearch_id_2"); List<String> artifactIds = new ArrayList<>(); artifactIds.add("testSearch_artifact_id_1"); artifactIds.add("testSearch_artifact_id_2"); DbSearch search = new DbSearch(); search.setModules(moduleIds); search.setArtifacts(artifactIds); when(repositoryHandler.getSearchResult(eq("testSearch"), (FiltersHolder) anyObject())).thenReturn(search); final WebResource resource = client().resource("/" + ServerAPI.SEARCH_RESOURCE + "/testSearch"); final ClientResponse response = resource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); assertNotNull(response); assertEquals(HttpStatus.OK_200, response.getStatus()); final String results = response.getEntity(new GenericType<String>() { }); assertEquals("{\"modules\":[\"testSearch_id_1\",\"testSearch_id_2\"],\"artifacts\":[\"testSearch_artifact_id_1\",\"testSearch_artifact_id_2\"]}", results); } @Test public void getNullSearchResult() { DbSearch search = new DbSearch(); when(repositoryHandler.getSearchResult(eq("testSearch"), (FiltersHolder) anyObject())).thenReturn(search); final WebResource resource = client().resource("/" + ServerAPI.SEARCH_RESOURCE + "/testSearch"); final ClientResponse response = resource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); assertNotNull(response); assertEquals(HttpStatus.OK_200, response.getStatus()); final String results = response.getEntity(new GenericType<String>() { }); assertEquals("{\"modules\":null,\"artifacts\":null}", results); } @Test public void getModulesSearchResult() { DbSearch search = new DbSearch(); List<String> moduleIds = new ArrayList<>(); moduleIds.add("testSearch_id_1"); moduleIds.add("testSearch_id_2"); search.setModules(moduleIds); when(repositoryHandler.getSearchResult(eq("testSearch"), (FiltersHolder) anyObject())).thenReturn(search); final WebResource resource = client().resource("/" + ServerAPI.SEARCH_RESOURCE + "/testSearch"); final ClientResponse response = resource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); assertNotNull(response); assertEquals(HttpStatus.OK_200, response.getStatus()); final String results = response.getEntity(new GenericType<String>() { }); assertEquals("{\"modules\":[\"testSearch_id_1\",\"testSearch_id_2\"],\"artifacts\":null}", results); } @Test public void getArtifactsSearchResult() { DbSearch search = new DbSearch(); List<String> artifactIds = new ArrayList<>(); artifactIds.add("testSearch_artifact_id_1"); artifactIds.add("testSearch_artifact_id_2"); search.setArtifacts(artifactIds); when(repositoryHandler.getSearchResult(eq("testSearch"), (FiltersHolder) anyObject())).thenReturn(search); final WebResource resource = client().resource("/" + ServerAPI.SEARCH_RESOURCE + "/testSearch"); final ClientResponse response = resource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); assertNotNull(response); assertEquals(HttpStatus.OK_200, response.getStatus()); final String results = response.getEntity(new GenericType<String>() { }); assertEquals("{\"modules\":null,\"artifacts\":[\"testSearch_artifact_id_1\",\"testSearch_artifact_id_2\"]}", results); } }
Java
// Copyright 2012 Google Inc. All Rights Reserved // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Author: tomasz.kaftal@gmail.com (Tomasz Kaftal) // // This file contains the benchmark manager class which is responsible for // carrying out the benchmarking process from cursor reception to DOT graph // drawing. #ifndef SUPERSONIC_BENCHMARK_MANAGER_BENCHMARK_MANAGER_H_ #define SUPERSONIC_BENCHMARK_MANAGER_BENCHMARK_MANAGER_H_ #include <memory> #include "supersonic/benchmark/infrastructure/benchmark_listener.h" #include "supersonic/benchmark/infrastructure/cursor_statistics.h" #include "supersonic/benchmark/infrastructure/node.h" #include "supersonic/benchmark/infrastructure/tree_builder.h" #include "supersonic/benchmark/dot/dot_drawer.h" #include "supersonic/utils/macros.h" namespace supersonic { class Cursor; // Enum, whose values describe the possible graph generation destinations. enum Destination { DOT_FILE, DOT_STRING }; // Structure containing options for graph visualisation, currently // the destination enum and possibly a file name. struct GraphVisualisationOptions { explicit GraphVisualisationOptions(Destination destination) : destination(destination) {} GraphVisualisationOptions(Destination destination, const string& file_name) : destination(destination), file_name(file_name) {} Destination destination; string file_name; }; // BenchmarkDataWrapper contains the instances of objects necessary to run // a benchmark on a cursor. class BenchmarkDataWrapper { public: // Takes ownership of cursor, tree builder and node. BenchmarkDataWrapper( unique_ptr<Cursor> cursor, unique_ptr<BenchmarkTreeBuilder> builder, unique_ptr<BenchmarkTreeNode> node) : cursor_(std::move(cursor)), tree_builder_(std::move(builder)), node_(std::move(node)) {} // Caller takes ownership of the result. unique_ptr<Cursor> move_cursor() { return std::move(cursor_); } // No ownership transfer. BenchmarkTreeNode* node() { return node_.get(); } private: unique_ptr<Cursor> cursor_; unique_ptr<BenchmarkTreeBuilder> tree_builder_; unique_ptr<BenchmarkTreeNode> node_; }; // Transforms the cursor tree, whose root is passed as the argument, by // attaching spy cursors in between benchmarked nodes. The result is // a BenchmarkDataWrapper object, which stores the transformed cursor. In // this use case the caller then takes over the cursor and proceeds // to carrying out computations on it. The data wrapper must not be destroyed // before the benchmarking has been completed, that is before the graph has // been created using the CreateGraph() function, and before the lifetime of // the cursor ends. // // Caller takes ownership of the result data wrapper. The transformed cursor // resident in the wrapper will take ownership of the argument cursor. The // caller will have to drain the transformed cursor before proceeding to // graph creation. unique_ptr<BenchmarkDataWrapper> SetUpBenchmarkForCursor(unique_ptr<Cursor> cursor); // CreateGraph() is used to finalise the benchmarking process by drawing // a performance graph. It accepts the name of the benchmark, a pointer to // the benchmark node accessible from BenchmarkDataWrapper and created when // a call to SetUpBenchmarkForCursor() is made, and an options structure. // Depending on the options the type of the performed visualisation will vary, // while options' destination field will determine the semantics of the result // string: // // DOT_FILE - an empty string, // DOT_STRING - the generated DOT code, // GRAPHVIZ_RPC - url to the generated DOT graph. // // The caller is responsible for draining the benchmarked cursor manually before // calling CreateGraph(). // // Does not take ownership of the node. string CreateGraph( const string& benchmark_name, BenchmarkTreeNode* node, GraphVisualisationOptions options); // PerformBenchmark() is an all-in-one function which runs a benchmark on // the given cursor. The benchmark will be labelled with benchmark_name and // visualised using options. The function will drain the cursor by calling // its Next() function with the specified block size until the data have been // depleted. The returned value will depend on the options argument analogously // to CreateGraph(). // // Takes ownership of the cursor and destroys it when the benchmark graph // is ready. string PerformBenchmark( const string& benchmark_name, unique_ptr<Cursor> cursor, rowcount_t max_block_size, GraphVisualisationOptions options); } // namespace supersonic #endif // SUPERSONIC_BENCHMARK_MANAGER_BENCHMARK_MANAGER_H_
Java
@echo off echo ¿ªÊ¼Ìá½»´úÂëµ½±¾µØ²Ö¿â echo µ±Ç°Ä¿Â¼ÊÇ£º%cd% echo ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ mvn clean package install echo; echo Åú´¦ÀíÖ´ÐÐÍê±Ï£¡ echo; pause;
Java
// Code generated by MockGen. DO NOT EDIT. // Source: github.com/cri-o/cri-o/internal/lib/sandbox (interfaces: NamespaceIface) // Package sandboxmock is a generated GoMock package. package sandboxmock import ( sandbox "github.com/cri-o/cri-o/internal/lib/sandbox" gomock "github.com/golang/mock/gomock" reflect "reflect" ) // MockNamespaceIface is a mock of NamespaceIface interface type MockNamespaceIface struct { ctrl *gomock.Controller recorder *MockNamespaceIfaceMockRecorder } // MockNamespaceIfaceMockRecorder is the mock recorder for MockNamespaceIface type MockNamespaceIfaceMockRecorder struct { mock *MockNamespaceIface } // NewMockNamespaceIface creates a new mock instance func NewMockNamespaceIface(ctrl *gomock.Controller) *MockNamespaceIface { mock := &MockNamespaceIface{ctrl: ctrl} mock.recorder = &MockNamespaceIfaceMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use func (m *MockNamespaceIface) EXPECT() *MockNamespaceIfaceMockRecorder { return m.recorder } // Close mocks base method func (m *MockNamespaceIface) Close() error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Close") ret0, _ := ret[0].(error) return ret0 } // Close indicates an expected call of Close func (mr *MockNamespaceIfaceMockRecorder) Close() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Close", reflect.TypeOf((*MockNamespaceIface)(nil).Close)) } // Get mocks base method func (m *MockNamespaceIface) Get() *sandbox.Namespace { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Get") ret0, _ := ret[0].(*sandbox.Namespace) return ret0 } // Get indicates an expected call of Get func (mr *MockNamespaceIfaceMockRecorder) Get() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockNamespaceIface)(nil).Get)) } // Initialize mocks base method func (m *MockNamespaceIface) Initialize() sandbox.NamespaceIface { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Initialize") ret0, _ := ret[0].(sandbox.NamespaceIface) return ret0 } // Initialize indicates an expected call of Initialize func (mr *MockNamespaceIfaceMockRecorder) Initialize() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Initialize", reflect.TypeOf((*MockNamespaceIface)(nil).Initialize)) } // Initialized mocks base method func (m *MockNamespaceIface) Initialized() bool { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Initialized") ret0, _ := ret[0].(bool) return ret0 } // Initialized indicates an expected call of Initialized func (mr *MockNamespaceIfaceMockRecorder) Initialized() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Initialized", reflect.TypeOf((*MockNamespaceIface)(nil).Initialized)) } // Path mocks base method func (m *MockNamespaceIface) Path() string { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Path") ret0, _ := ret[0].(string) return ret0 } // Path indicates an expected call of Path func (mr *MockNamespaceIfaceMockRecorder) Path() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Path", reflect.TypeOf((*MockNamespaceIface)(nil).Path)) } // Remove mocks base method func (m *MockNamespaceIface) Remove() error { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Remove") ret0, _ := ret[0].(error) return ret0 } // Remove indicates an expected call of Remove func (mr *MockNamespaceIfaceMockRecorder) Remove() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Remove", reflect.TypeOf((*MockNamespaceIface)(nil).Remove)) } // Type mocks base method func (m *MockNamespaceIface) Type() sandbox.NSType { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Type") ret0, _ := ret[0].(sandbox.NSType) return ret0 } // Type indicates an expected call of Type func (mr *MockNamespaceIfaceMockRecorder) Type() *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Type", reflect.TypeOf((*MockNamespaceIface)(nil).Type)) }
Java
#!/usr/bin/env ruby # Encoding: utf-8 # # Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # This example gets all account budget proposals. To add an account budget # proposal, run AddAccountBudgetProposal.rb. require 'optparse' require 'google/ads/google_ads' def get_account_budget_proposals(customer_id) # GoogleAdsClient will read a config file from # ENV['HOME']/google_ads_config.rb when called without parameters client = Google::Ads::GoogleAds::GoogleAdsClient.new ga_service = client.service.google_ads search_query = <<~QUERY SELECT account_budget_proposal.id, account_budget_proposal.account_budget, account_budget_proposal.billing_setup, account_budget_proposal.status, account_budget_proposal.proposed_name, account_budget_proposal.proposed_notes, account_budget_proposal.proposed_purchase_order_number, account_budget_proposal.proposal_type, account_budget_proposal.approval_date_time, account_budget_proposal.creation_date_time FROM account_budget_proposal QUERY response = ga_service.search( customer_id: customer_id, query: search_query, page_size: PAGE_SIZE, ) response.each do |row| account_budget_proposal = row.account_budget_proposal puts sprintf('Account budget proposal with ID %s, status %s, '\ 'account_budget %s, billing_setup %s, proposed_name %s, '\ 'proposed_notes %s, proposed_po_number %s, proposal_type %s, '\ 'approval_date_time %s, creation_date_time %s', account_budget_proposal.id, account_budget_proposal.account_budget, account_budget_proposal.billing_setup, account_budget_proposal.status, account_budget_proposal.proposed_name, account_budget_proposal.proposed_notes, account_budget_proposal.proposed_purchase_order_number, account_budget_proposal.proposal_type, account_budget_proposal.approval_date_time, account_budget_proposal.creation_date_time ) end end if __FILE__ == $0 PAGE_SIZE = 1000 options = {} # The following parameter(s) should be provided to run the example. You can # either specify these by changing the INSERT_XXX_ID_HERE values below, or on # the command line. # # Parameters passed on the command line will override any parameters set in # code. # # Running the example with -h will print the command line usage. options[:customer_id] = 'INSERT_CUSTOMER_ID_HERE' options[:ad_group_id] = nil OptionParser.new do |opts| opts.banner = sprintf('Usage: %s [options]', File.basename(__FILE__)) opts.separator '' opts.separator 'Options:' opts.on('-C', '--customer-id CUSTOMER-ID', String, 'Customer ID') do |v| options[:customer_id] = v end opts.separator '' opts.separator 'Help:' opts.on_tail('-h', '--help', 'Show this message') do puts opts exit end end.parse! begin get_account_budget_proposals(options.fetch(:customer_id).tr("-", "")) rescue Google::Ads::GoogleAds::Errors::GoogleAdsError => e e.failure.errors.each do |error| STDERR.printf("Error with message: %s\n", error.message) if error.location error.location.field_path_elements.each do |field_path_element| STDERR.printf("\tOn field: %s\n", field_path_element.field_name) end end error.error_code.to_h.each do |k, v| next if v == :UNSPECIFIED STDERR.printf("\tType: %s\n\tCode: %s\n", k, v) end end raise end end
Java
fuzzy-computing-machine ======================= 코리아카지노ゑゑゑ【 ENP7­。­C­0­M 】→ゑ\\코리아카지노\코리아카지노〉〈《 / ☆○◇□△­。­▽♤♥ /》\\코리아카지노ゑゑゑ【 ENP7­。­C­0­M 】→ゑ\\코리아카지노\코리아카지노ゑゑゑ【 ENP7­。­C­0­M 】→ゑ\\코리아카지노ゑゑゑ【 ENP7­。­C­0­M 】→ゑ\\코리아카지노\코리아카지노ゑゑゑ【 ENP7­。­C­0­M 】→ゑ\\코리아카지노ゑゑゑ【 ENP7­。­C­0­M 】→ゑ\\코리아카지노\코리아카지노ゑゑゑ【 ENP7­。­C­0­M 】→ゑ\\코리아카지노ゑゑゑ【 ENP7­。­C­0­M 】→ゑ\\코리아카지노\코리아카지노ゑゑゑ【 ENP7­。­C­0­M 】→ゑ\\코리아카지노ゑゑゑ【 ENP7­。­C­0­M 】→ゑ\\코리아카지노\코리아카지노ゑゑゑ【 ENP7­。­C­0­M 】→ゑ\\코리아카지노ゑゑゑ【 ENP7­。­C­0­M 】→ゑ\\코리아카지노\코리아카지노ゑゑゑ【 ENP7­。­C­0­M 】→ゑ\\코리아카지노ゑゑゑ【 ENP7­。­C­0­M 】→ゑ\\코리아카지노\코리아카지노ゑゑゑ【 ENP7­。­C­0­M 】→ゑ\\코리아카지노ゑゑゑ【 ENP7­。­C­0­M 】→ゑ\\코리아카지노\코리아카지노ゑゑゑ【 ENP7­。­C­0­M 】→ゑ\\코리아카지노ゑゑゑ【 ENP7­。­C­0­M 】→ゑ\\코리아카지노\코리아카지노ゑゑゑ【 ENP7­。­C­0­M 】→ゑ\\코리아카지노ゑゑゑ【 ENP7­。­C­0­M 】→ゑ\\코리아카지노\코리아카지노ゑゑゑ【 ENP7­。­C­0­M 】→ゑ\\코리아카지노ゑゑゑ【 ENP7­。­C­0­M 】→ゑ\\코리아카지노\코리아카지노ゑゑゑ【 ENP7­。­C­0­M 】→ゑ\\코리아카지노ゑゑゑ【 ENP7­。­C­0­M 】→ゑ\\코리아카지노\코리아카지노ゑゑゑ【 ENP7­。­C­0­M 】→ゑ\\코리아카지노ベジ
Java
# Avena fatua var. sativa VARIETY #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
Java
// Copyright 2017 The Oppia Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Factory for creating new frontend instances of Interaction * domain objects. */ oppia.factory('InteractionObjectFactory', [ 'AnswerGroupObjectFactory', 'HintObjectFactory', 'OutcomeObjectFactory', 'SolutionObjectFactory', function( AnswerGroupObjectFactory, HintObjectFactory, OutcomeObjectFactory, SolutionObjectFactory) { var Interaction = function( answerGroups, confirmedUnclassifiedAnswers, customizationArgs, defaultOutcome, hints, id, solution) { this.answerGroups = answerGroups; this.confirmedUnclassifiedAnswers = confirmedUnclassifiedAnswers; this.customizationArgs = customizationArgs; this.defaultOutcome = defaultOutcome; this.hints = hints; this.id = id; this.solution = solution; }; Interaction.prototype.toBackendDict = function() { return { answer_groups: this.answerGroups.map(function(answerGroup) { return answerGroup.toBackendDict(); }), confirmed_unclassified_answers: this.confirmedUnclassifiedAnswers, customization_args: this.customizationArgs, default_outcome: this.defaultOutcome ? this.defaultOutcome.toBackendDict() : null, hints: this.hints.map(function(hint) { return hint.toBackendDict(); }), id: this.id, solution: this.solution ? this.solution.toBackendDict() : null }; }; Interaction.createFromBackendDict = function(interactionDict) { var defaultOutcome; if (interactionDict.default_outcome) { defaultOutcome = OutcomeObjectFactory.createFromBackendDict( interactionDict.default_outcome); } else { defaultOutcome = null; } return new Interaction( generateAnswerGroupsFromBackend(interactionDict.answer_groups), interactionDict.confirmed_unclassified_answers, interactionDict.customization_args, defaultOutcome, generateHintsFromBackend(interactionDict.hints), interactionDict.id, interactionDict.solution ? ( generateSolutionFromBackend(interactionDict.solution)) : null); }; var generateAnswerGroupsFromBackend = function(answerGroupBackendDicts) { return answerGroupBackendDicts.map(function( answerGroupBackendDict) { return AnswerGroupObjectFactory.createFromBackendDict( answerGroupBackendDict); }); }; var generateHintsFromBackend = function(hintBackendDicts) { return hintBackendDicts.map(function(hintBackendDict) { return HintObjectFactory.createFromBackendDict(hintBackendDict); }); }; var generateSolutionFromBackend = function(solutionBackendDict) { return SolutionObjectFactory.createFromBackendDict(solutionBackendDict); }; return Interaction; } ]);
Java
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.client.documentation; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.LatchedActionListener; import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.get.GetRequest; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.index.IndexRequest; import org.elasticsearch.action.support.WriteRequest; import org.elasticsearch.action.support.master.AcknowledgedResponse; import org.elasticsearch.client.ESRestHighLevelClientTestCase; import org.elasticsearch.client.MachineLearningGetResultsIT; import org.elasticsearch.client.MachineLearningIT; import org.elasticsearch.client.MlTestStateCleaner; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.client.core.PageParams; import org.elasticsearch.client.indices.CreateIndexRequest; import org.elasticsearch.client.ml.CloseJobRequest; import org.elasticsearch.client.ml.CloseJobResponse; import org.elasticsearch.client.ml.DeleteCalendarEventRequest; import org.elasticsearch.client.ml.DeleteCalendarJobRequest; import org.elasticsearch.client.ml.DeleteCalendarRequest; import org.elasticsearch.client.ml.DeleteDataFrameAnalyticsRequest; import org.elasticsearch.client.ml.DeleteDatafeedRequest; import org.elasticsearch.client.ml.DeleteExpiredDataRequest; import org.elasticsearch.client.ml.DeleteExpiredDataResponse; import org.elasticsearch.client.ml.DeleteFilterRequest; import org.elasticsearch.client.ml.DeleteForecastRequest; import org.elasticsearch.client.ml.DeleteJobRequest; import org.elasticsearch.client.ml.DeleteJobResponse; import org.elasticsearch.client.ml.DeleteModelSnapshotRequest; import org.elasticsearch.client.ml.DeleteTrainedModelRequest; import org.elasticsearch.client.ml.EstimateModelMemoryRequest; import org.elasticsearch.client.ml.EstimateModelMemoryResponse; import org.elasticsearch.client.ml.EvaluateDataFrameRequest; import org.elasticsearch.client.ml.EvaluateDataFrameResponse; import org.elasticsearch.client.ml.ExplainDataFrameAnalyticsRequest; import org.elasticsearch.client.ml.ExplainDataFrameAnalyticsResponse; import org.elasticsearch.client.ml.FindFileStructureRequest; import org.elasticsearch.client.ml.FindFileStructureResponse; import org.elasticsearch.client.ml.FlushJobRequest; import org.elasticsearch.client.ml.FlushJobResponse; import org.elasticsearch.client.ml.ForecastJobRequest; import org.elasticsearch.client.ml.ForecastJobResponse; import org.elasticsearch.client.ml.GetBucketsRequest; import org.elasticsearch.client.ml.GetBucketsResponse; import org.elasticsearch.client.ml.GetCalendarEventsRequest; import org.elasticsearch.client.ml.GetCalendarEventsResponse; import org.elasticsearch.client.ml.GetCalendarsRequest; import org.elasticsearch.client.ml.GetCalendarsResponse; import org.elasticsearch.client.ml.GetCategoriesRequest; import org.elasticsearch.client.ml.GetCategoriesResponse; import org.elasticsearch.client.ml.GetDataFrameAnalyticsRequest; import org.elasticsearch.client.ml.GetDataFrameAnalyticsResponse; import org.elasticsearch.client.ml.GetDataFrameAnalyticsStatsRequest; import org.elasticsearch.client.ml.GetDataFrameAnalyticsStatsResponse; import org.elasticsearch.client.ml.GetDatafeedRequest; import org.elasticsearch.client.ml.GetDatafeedResponse; import org.elasticsearch.client.ml.GetDatafeedStatsRequest; import org.elasticsearch.client.ml.GetDatafeedStatsResponse; import org.elasticsearch.client.ml.GetFiltersRequest; import org.elasticsearch.client.ml.GetFiltersResponse; import org.elasticsearch.client.ml.GetInfluencersRequest; import org.elasticsearch.client.ml.GetInfluencersResponse; import org.elasticsearch.client.ml.GetJobRequest; import org.elasticsearch.client.ml.GetJobResponse; import org.elasticsearch.client.ml.GetJobStatsRequest; import org.elasticsearch.client.ml.GetJobStatsResponse; import org.elasticsearch.client.ml.GetModelSnapshotsRequest; import org.elasticsearch.client.ml.GetModelSnapshotsResponse; import org.elasticsearch.client.ml.GetOverallBucketsRequest; import org.elasticsearch.client.ml.GetOverallBucketsResponse; import org.elasticsearch.client.ml.GetRecordsRequest; import org.elasticsearch.client.ml.GetRecordsResponse; import org.elasticsearch.client.ml.GetTrainedModelsRequest; import org.elasticsearch.client.ml.GetTrainedModelsResponse; import org.elasticsearch.client.ml.GetTrainedModelsStatsRequest; import org.elasticsearch.client.ml.GetTrainedModelsStatsResponse; import org.elasticsearch.client.ml.MlInfoRequest; import org.elasticsearch.client.ml.MlInfoResponse; import org.elasticsearch.client.ml.OpenJobRequest; import org.elasticsearch.client.ml.OpenJobResponse; import org.elasticsearch.client.ml.PostCalendarEventRequest; import org.elasticsearch.client.ml.PostCalendarEventResponse; import org.elasticsearch.client.ml.PostDataRequest; import org.elasticsearch.client.ml.PostDataResponse; import org.elasticsearch.client.ml.PreviewDatafeedRequest; import org.elasticsearch.client.ml.PreviewDatafeedResponse; import org.elasticsearch.client.ml.PutCalendarJobRequest; import org.elasticsearch.client.ml.PutCalendarRequest; import org.elasticsearch.client.ml.PutCalendarResponse; import org.elasticsearch.client.ml.PutDataFrameAnalyticsRequest; import org.elasticsearch.client.ml.PutDataFrameAnalyticsResponse; import org.elasticsearch.client.ml.PutDatafeedRequest; import org.elasticsearch.client.ml.PutDatafeedResponse; import org.elasticsearch.client.ml.PutFilterRequest; import org.elasticsearch.client.ml.PutFilterResponse; import org.elasticsearch.client.ml.PutJobRequest; import org.elasticsearch.client.ml.PutJobResponse; import org.elasticsearch.client.ml.PutTrainedModelRequest; import org.elasticsearch.client.ml.PutTrainedModelResponse; import org.elasticsearch.client.ml.RevertModelSnapshotRequest; import org.elasticsearch.client.ml.RevertModelSnapshotResponse; import org.elasticsearch.client.ml.SetUpgradeModeRequest; import org.elasticsearch.client.ml.StartDataFrameAnalyticsRequest; import org.elasticsearch.client.ml.StartDataFrameAnalyticsResponse; import org.elasticsearch.client.ml.StartDatafeedRequest; import org.elasticsearch.client.ml.StartDatafeedResponse; import org.elasticsearch.client.ml.StopDataFrameAnalyticsRequest; import org.elasticsearch.client.ml.StopDataFrameAnalyticsResponse; import org.elasticsearch.client.ml.StopDatafeedRequest; import org.elasticsearch.client.ml.StopDatafeedResponse; import org.elasticsearch.client.ml.UpdateDatafeedRequest; import org.elasticsearch.client.ml.UpdateFilterRequest; import org.elasticsearch.client.ml.UpdateJobRequest; import org.elasticsearch.client.ml.UpdateModelSnapshotRequest; import org.elasticsearch.client.ml.UpdateModelSnapshotResponse; import org.elasticsearch.client.ml.calendars.Calendar; import org.elasticsearch.client.ml.calendars.ScheduledEvent; import org.elasticsearch.client.ml.calendars.ScheduledEventTests; import org.elasticsearch.client.ml.datafeed.ChunkingConfig; import org.elasticsearch.client.ml.datafeed.DatafeedConfig; import org.elasticsearch.client.ml.datafeed.DatafeedStats; import org.elasticsearch.client.ml.datafeed.DatafeedUpdate; import org.elasticsearch.client.ml.datafeed.DelayedDataCheckConfig; import org.elasticsearch.client.ml.dataframe.Classification; import org.elasticsearch.client.ml.dataframe.DataFrameAnalysis; import org.elasticsearch.client.ml.dataframe.DataFrameAnalyticsConfig; import org.elasticsearch.client.ml.dataframe.DataFrameAnalyticsDest; import org.elasticsearch.client.ml.dataframe.DataFrameAnalyticsSource; import org.elasticsearch.client.ml.dataframe.DataFrameAnalyticsState; import org.elasticsearch.client.ml.dataframe.DataFrameAnalyticsStats; import org.elasticsearch.client.ml.dataframe.OutlierDetection; import org.elasticsearch.client.ml.dataframe.QueryConfig; import org.elasticsearch.client.ml.dataframe.Regression; import org.elasticsearch.client.ml.dataframe.evaluation.Evaluation; import org.elasticsearch.client.ml.dataframe.evaluation.EvaluationMetric; import org.elasticsearch.client.ml.dataframe.evaluation.classification.AccuracyMetric; import org.elasticsearch.client.ml.dataframe.evaluation.classification.MulticlassConfusionMatrixMetric; import org.elasticsearch.client.ml.dataframe.evaluation.classification.MulticlassConfusionMatrixMetric.ActualClass; import org.elasticsearch.client.ml.dataframe.evaluation.classification.MulticlassConfusionMatrixMetric.PredictedClass; import org.elasticsearch.client.ml.dataframe.evaluation.regression.MeanSquaredErrorMetric; import org.elasticsearch.client.ml.dataframe.evaluation.regression.RSquaredMetric; import org.elasticsearch.client.ml.dataframe.evaluation.softclassification.AucRocMetric; import org.elasticsearch.client.ml.dataframe.evaluation.softclassification.BinarySoftClassification; import org.elasticsearch.client.ml.dataframe.evaluation.softclassification.ConfusionMatrixMetric; import org.elasticsearch.client.ml.dataframe.evaluation.softclassification.ConfusionMatrixMetric.ConfusionMatrix; import org.elasticsearch.client.ml.dataframe.evaluation.softclassification.PrecisionMetric; import org.elasticsearch.client.ml.dataframe.evaluation.softclassification.RecallMetric; import org.elasticsearch.client.ml.dataframe.explain.FieldSelection; import org.elasticsearch.client.ml.dataframe.explain.MemoryEstimation; import org.elasticsearch.client.ml.filestructurefinder.FileStructure; import org.elasticsearch.client.ml.inference.InferenceToXContentCompressor; import org.elasticsearch.client.ml.inference.MlInferenceNamedXContentProvider; import org.elasticsearch.client.ml.inference.TrainedModelConfig; import org.elasticsearch.client.ml.inference.TrainedModelDefinition; import org.elasticsearch.client.ml.inference.TrainedModelDefinitionTests; import org.elasticsearch.client.ml.inference.TrainedModelInput; import org.elasticsearch.client.ml.inference.TrainedModelStats; import org.elasticsearch.client.ml.inference.trainedmodel.RegressionConfig; import org.elasticsearch.client.ml.inference.trainedmodel.TargetType; import org.elasticsearch.client.ml.job.config.AnalysisConfig; import org.elasticsearch.client.ml.job.config.AnalysisLimits; import org.elasticsearch.client.ml.job.config.DataDescription; import org.elasticsearch.client.ml.job.config.DetectionRule; import org.elasticsearch.client.ml.job.config.Detector; import org.elasticsearch.client.ml.job.config.Job; import org.elasticsearch.client.ml.job.config.JobUpdate; import org.elasticsearch.client.ml.job.config.MlFilter; import org.elasticsearch.client.ml.job.config.ModelPlotConfig; import org.elasticsearch.client.ml.job.config.Operator; import org.elasticsearch.client.ml.job.config.RuleCondition; import org.elasticsearch.client.ml.job.process.DataCounts; import org.elasticsearch.client.ml.job.process.ModelSnapshot; import org.elasticsearch.client.ml.job.results.AnomalyRecord; import org.elasticsearch.client.ml.job.results.Bucket; import org.elasticsearch.client.ml.job.results.CategoryDefinition; import org.elasticsearch.client.ml.job.results.Influencer; import org.elasticsearch.client.ml.job.results.OverallBucket; import org.elasticsearch.client.ml.job.stats.JobStats; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.unit.ByteSizeUnit; import org.elasticsearch.common.unit.ByteSizeValue; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.NamedXContentRegistry; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.index.query.MatchAllQueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.aggregations.AggregatorFactories; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.fetch.subphase.FetchSourceContext; import org.elasticsearch.tasks.TaskId; import org.junit.After; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.closeTo; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.lessThan; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.core.Is.is; public class MlClientDocumentationIT extends ESRestHighLevelClientTestCase { @After public void cleanUp() throws IOException { new MlTestStateCleaner(logger, highLevelClient().machineLearning()).clearMlMetadata(); } public void testCreateJob() throws Exception { RestHighLevelClient client = highLevelClient(); // tag::put-job-detector Detector.Builder detectorBuilder = new Detector.Builder() .setFunction("sum") // <1> .setFieldName("total") // <2> .setDetectorDescription("Sum of total"); // <3> // end::put-job-detector // tag::put-job-analysis-config List<Detector> detectors = Collections.singletonList(detectorBuilder.build()); // <1> AnalysisConfig.Builder analysisConfigBuilder = new AnalysisConfig.Builder(detectors) // <2> .setBucketSpan(TimeValue.timeValueMinutes(10)); // <3> // end::put-job-analysis-config // tag::put-job-data-description DataDescription.Builder dataDescriptionBuilder = new DataDescription.Builder() .setTimeField("timestamp"); // <1> // end::put-job-data-description { String id = "job_1"; // tag::put-job-config Job.Builder jobBuilder = new Job.Builder(id) // <1> .setAnalysisConfig(analysisConfigBuilder) // <2> .setDataDescription(dataDescriptionBuilder) // <3> .setDescription("Total sum of requests"); // <4> // end::put-job-config // tag::put-job-request PutJobRequest request = new PutJobRequest(jobBuilder.build()); // <1> // end::put-job-request // tag::put-job-execute PutJobResponse response = client.machineLearning().putJob(request, RequestOptions.DEFAULT); // end::put-job-execute // tag::put-job-response Date createTime = response.getResponse().getCreateTime(); // <1> // end::put-job-response assertThat(createTime.getTime(), greaterThan(0L)); } { String id = "job_2"; Job.Builder jobBuilder = new Job.Builder(id) .setAnalysisConfig(analysisConfigBuilder) .setDataDescription(dataDescriptionBuilder) .setDescription("Total sum of requests"); PutJobRequest request = new PutJobRequest(jobBuilder.build()); // tag::put-job-execute-listener ActionListener<PutJobResponse> listener = new ActionListener<PutJobResponse>() { @Override public void onResponse(PutJobResponse response) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::put-job-execute-listener // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::put-job-execute-async client.machineLearning().putJobAsync(request, RequestOptions.DEFAULT, listener); // <1> // end::put-job-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testGetJob() throws Exception { RestHighLevelClient client = highLevelClient(); Job job = MachineLearningIT.buildJob("get-machine-learning-job1"); client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT); Job secondJob = MachineLearningIT.buildJob("get-machine-learning-job2"); client.machineLearning().putJob(new PutJobRequest(secondJob), RequestOptions.DEFAULT); { // tag::get-job-request GetJobRequest request = new GetJobRequest("get-machine-learning-job1", "get-machine-learning-job*"); // <1> request.setAllowNoJobs(true); // <2> // end::get-job-request // tag::get-job-execute GetJobResponse response = client.machineLearning().getJob(request, RequestOptions.DEFAULT); // end::get-job-execute // tag::get-job-response long numberOfJobs = response.count(); // <1> List<Job> jobs = response.jobs(); // <2> // end::get-job-response assertEquals(2, response.count()); assertThat(response.jobs(), hasSize(2)); assertThat(response.jobs().stream().map(Job::getId).collect(Collectors.toList()), containsInAnyOrder(job.getId(), secondJob.getId())); } { GetJobRequest request = new GetJobRequest("get-machine-learning-job1", "get-machine-learning-job*"); // tag::get-job-execute-listener ActionListener<GetJobResponse> listener = new ActionListener<GetJobResponse>() { @Override public void onResponse(GetJobResponse response) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::get-job-execute-listener // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::get-job-execute-async client.machineLearning().getJobAsync(request, RequestOptions.DEFAULT, listener); // <1> // end::get-job-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testDeleteJob() throws Exception { RestHighLevelClient client = highLevelClient(); String jobId = "my-first-machine-learning-job"; Job job = MachineLearningIT.buildJob(jobId); client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT); Job secondJob = MachineLearningIT.buildJob("my-second-machine-learning-job"); client.machineLearning().putJob(new PutJobRequest(secondJob), RequestOptions.DEFAULT); { //tag::delete-job-request DeleteJobRequest deleteJobRequest = new DeleteJobRequest("my-first-machine-learning-job"); // <1> //end::delete-job-request //tag::delete-job-request-force deleteJobRequest.setForce(false); // <1> //end::delete-job-request-force //tag::delete-job-request-wait-for-completion deleteJobRequest.setWaitForCompletion(true); // <1> //end::delete-job-request-wait-for-completion //tag::delete-job-execute DeleteJobResponse deleteJobResponse = client.machineLearning().deleteJob(deleteJobRequest, RequestOptions.DEFAULT); //end::delete-job-execute //tag::delete-job-response Boolean isAcknowledged = deleteJobResponse.getAcknowledged(); // <1> TaskId task = deleteJobResponse.getTask(); // <2> //end::delete-job-response assertTrue(isAcknowledged); assertNull(task); } { //tag::delete-job-execute-listener ActionListener<DeleteJobResponse> listener = new ActionListener<DeleteJobResponse>() { @Override public void onResponse(DeleteJobResponse deleteJobResponse) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::delete-job-execute-listener // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); DeleteJobRequest deleteJobRequest = new DeleteJobRequest("my-second-machine-learning-job"); // tag::delete-job-execute-async client.machineLearning().deleteJobAsync(deleteJobRequest, RequestOptions.DEFAULT, listener); // <1> // end::delete-job-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testOpenJob() throws Exception { RestHighLevelClient client = highLevelClient(); Job job = MachineLearningIT.buildJob("opening-my-first-machine-learning-job"); client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT); Job secondJob = MachineLearningIT.buildJob("opening-my-second-machine-learning-job"); client.machineLearning().putJob(new PutJobRequest(secondJob), RequestOptions.DEFAULT); { // tag::open-job-request OpenJobRequest openJobRequest = new OpenJobRequest("opening-my-first-machine-learning-job"); // <1> openJobRequest.setTimeout(TimeValue.timeValueMinutes(10)); // <2> // end::open-job-request // tag::open-job-execute OpenJobResponse openJobResponse = client.machineLearning().openJob(openJobRequest, RequestOptions.DEFAULT); // end::open-job-execute // tag::open-job-response boolean isOpened = openJobResponse.isOpened(); // <1> String node = openJobResponse.getNode(); // <2> // end::open-job-response assertThat(node, notNullValue()); } { // tag::open-job-execute-listener ActionListener<OpenJobResponse> listener = new ActionListener<OpenJobResponse>() { @Override public void onResponse(OpenJobResponse openJobResponse) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::open-job-execute-listener OpenJobRequest openJobRequest = new OpenJobRequest("opening-my-second-machine-learning-job"); // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::open-job-execute-async client.machineLearning().openJobAsync(openJobRequest, RequestOptions.DEFAULT, listener); // <1> // end::open-job-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testCloseJob() throws Exception { RestHighLevelClient client = highLevelClient(); { Job job = MachineLearningIT.buildJob("closing-my-first-machine-learning-job"); client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT); client.machineLearning().openJob(new OpenJobRequest(job.getId()), RequestOptions.DEFAULT); // tag::close-job-request CloseJobRequest closeJobRequest = new CloseJobRequest("closing-my-first-machine-learning-job", "otherjobs*"); // <1> closeJobRequest.setForce(false); // <2> closeJobRequest.setAllowNoJobs(true); // <3> closeJobRequest.setTimeout(TimeValue.timeValueMinutes(10)); // <4> // end::close-job-request // tag::close-job-execute CloseJobResponse closeJobResponse = client.machineLearning().closeJob(closeJobRequest, RequestOptions.DEFAULT); // end::close-job-execute // tag::close-job-response boolean isClosed = closeJobResponse.isClosed(); // <1> // end::close-job-response } { Job job = MachineLearningIT.buildJob("closing-my-second-machine-learning-job"); client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT); client.machineLearning().openJob(new OpenJobRequest(job.getId()), RequestOptions.DEFAULT); // tag::close-job-execute-listener ActionListener<CloseJobResponse> listener = new ActionListener<CloseJobResponse>() { @Override public void onResponse(CloseJobResponse closeJobResponse) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::close-job-execute-listener CloseJobRequest closeJobRequest = new CloseJobRequest("closing-my-second-machine-learning-job"); // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::close-job-execute-async client.machineLearning().closeJobAsync(closeJobRequest, RequestOptions.DEFAULT, listener); // <1> // end::close-job-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testUpdateJob() throws Exception { RestHighLevelClient client = highLevelClient(); String jobId = "test-update-job"; Job tempJob = MachineLearningIT.buildJob(jobId); Job job = new Job.Builder(tempJob) .setAnalysisConfig(new AnalysisConfig.Builder(tempJob.getAnalysisConfig()) .setCategorizationFieldName("categorization-field") .setDetector(0, new Detector.Builder().setFieldName("total") .setFunction("sum") .setPartitionFieldName("mlcategory") .setDetectorDescription(randomAlphaOfLength(10)) .build())) .build(); client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT); { List<DetectionRule> detectionRules = Arrays.asList( new DetectionRule.Builder(Arrays.asList(RuleCondition.createTime(Operator.GT, 100L))).build()); Map<String, Object> customSettings = new HashMap<>(); customSettings.put("custom-setting-1", "custom-value"); // tag::update-job-detector-options JobUpdate.DetectorUpdate detectorUpdate = new JobUpdate.DetectorUpdate(0, // <1> "detector description", // <2> detectionRules); // <3> // end::update-job-detector-options // tag::update-job-options JobUpdate update = new JobUpdate.Builder(jobId) // <1> .setDescription("My description") // <2> .setAnalysisLimits(new AnalysisLimits(1000L, null)) // <3> .setBackgroundPersistInterval(TimeValue.timeValueHours(3)) // <4> .setCategorizationFilters(Arrays.asList("categorization-filter")) // <5> .setDetectorUpdates(Arrays.asList(detectorUpdate)) // <6> .setGroups(Arrays.asList("job-group-1")) // <7> .setResultsRetentionDays(10L) // <8> .setModelPlotConfig(new ModelPlotConfig(true, null, true)) // <9> .setModelSnapshotRetentionDays(7L) // <10> .setCustomSettings(customSettings) // <11> .setRenormalizationWindowDays(3L) // <12> .build(); // end::update-job-options // tag::update-job-request UpdateJobRequest updateJobRequest = new UpdateJobRequest(update); // <1> // end::update-job-request // tag::update-job-execute PutJobResponse updateJobResponse = client.machineLearning().updateJob(updateJobRequest, RequestOptions.DEFAULT); // end::update-job-execute // tag::update-job-response Job updatedJob = updateJobResponse.getResponse(); // <1> // end::update-job-response assertEquals(update.getDescription(), updatedJob.getDescription()); } { // tag::update-job-execute-listener ActionListener<PutJobResponse> listener = new ActionListener<PutJobResponse>() { @Override public void onResponse(PutJobResponse updateJobResponse) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::update-job-execute-listener UpdateJobRequest updateJobRequest = new UpdateJobRequest(new JobUpdate.Builder(jobId).build()); // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::update-job-execute-async client.machineLearning().updateJobAsync(updateJobRequest, RequestOptions.DEFAULT, listener); // <1> // end::update-job-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testPutDatafeed() throws Exception { RestHighLevelClient client = highLevelClient(); { // We need to create a job for the datafeed request to be valid String jobId = "put-datafeed-job-1"; Job job = MachineLearningIT.buildJob(jobId); client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT); String id = "datafeed-1"; // tag::put-datafeed-config DatafeedConfig.Builder datafeedBuilder = new DatafeedConfig.Builder(id, jobId) // <1> .setIndices("index_1", "index_2"); // <2> // end::put-datafeed-config AggregatorFactories.Builder aggs = AggregatorFactories.builder(); // tag::put-datafeed-config-set-aggregations datafeedBuilder.setAggregations(aggs); // <1> // end::put-datafeed-config-set-aggregations // Clearing aggregation to avoid complex validation rules datafeedBuilder.setAggregations((String) null); // tag::put-datafeed-config-set-chunking-config datafeedBuilder.setChunkingConfig(ChunkingConfig.newAuto()); // <1> // end::put-datafeed-config-set-chunking-config // tag::put-datafeed-config-set-frequency datafeedBuilder.setFrequency(TimeValue.timeValueSeconds(30)); // <1> // end::put-datafeed-config-set-frequency // tag::put-datafeed-config-set-query datafeedBuilder.setQuery(QueryBuilders.matchAllQuery()); // <1> // end::put-datafeed-config-set-query // tag::put-datafeed-config-set-query-delay datafeedBuilder.setQueryDelay(TimeValue.timeValueMinutes(1)); // <1> // end::put-datafeed-config-set-query-delay // tag::put-datafeed-config-set-delayed-data-check-config datafeedBuilder.setDelayedDataCheckConfig(DelayedDataCheckConfig .enabledDelayedDataCheckConfig(TimeValue.timeValueHours(1))); // <1> // end::put-datafeed-config-set-delayed-data-check-config // no need to accidentally trip internal validations due to job bucket size datafeedBuilder.setDelayedDataCheckConfig(null); List<SearchSourceBuilder.ScriptField> scriptFields = Collections.emptyList(); // tag::put-datafeed-config-set-script-fields datafeedBuilder.setScriptFields(scriptFields); // <1> // end::put-datafeed-config-set-script-fields // tag::put-datafeed-config-set-scroll-size datafeedBuilder.setScrollSize(1000); // <1> // end::put-datafeed-config-set-scroll-size // tag::put-datafeed-request PutDatafeedRequest request = new PutDatafeedRequest(datafeedBuilder.build()); // <1> // end::put-datafeed-request // tag::put-datafeed-execute PutDatafeedResponse response = client.machineLearning().putDatafeed(request, RequestOptions.DEFAULT); // end::put-datafeed-execute // tag::put-datafeed-response DatafeedConfig datafeed = response.getResponse(); // <1> // end::put-datafeed-response assertThat(datafeed.getId(), equalTo("datafeed-1")); } { // We need to create a job for the datafeed request to be valid String jobId = "put-datafeed-job-2"; Job job = MachineLearningIT.buildJob(jobId); client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT); String id = "datafeed-2"; DatafeedConfig datafeed = new DatafeedConfig.Builder(id, jobId).setIndices("index_1", "index_2").build(); PutDatafeedRequest request = new PutDatafeedRequest(datafeed); // tag::put-datafeed-execute-listener ActionListener<PutDatafeedResponse> listener = new ActionListener<PutDatafeedResponse>() { @Override public void onResponse(PutDatafeedResponse response) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::put-datafeed-execute-listener // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::put-datafeed-execute-async client.machineLearning().putDatafeedAsync(request, RequestOptions.DEFAULT, listener); // <1> // end::put-datafeed-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testUpdateDatafeed() throws Exception { RestHighLevelClient client = highLevelClient(); Job job = MachineLearningIT.buildJob("update-datafeed-job"); client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT); String datafeedId = job.getId() + "-feed"; DatafeedConfig datafeed = DatafeedConfig.builder(datafeedId, job.getId()).setIndices("foo").build(); client.machineLearning().putDatafeed(new PutDatafeedRequest(datafeed), RequestOptions.DEFAULT); { AggregatorFactories.Builder aggs = AggregatorFactories.builder(); List<SearchSourceBuilder.ScriptField> scriptFields = Collections.emptyList(); // tag::update-datafeed-config DatafeedUpdate.Builder datafeedUpdateBuilder = new DatafeedUpdate.Builder(datafeedId) // <1> .setAggregations(aggs) // <2> .setIndices("index_1", "index_2") // <3> .setChunkingConfig(ChunkingConfig.newAuto()) // <4> .setFrequency(TimeValue.timeValueSeconds(30)) // <5> .setQuery(QueryBuilders.matchAllQuery()) // <6> .setQueryDelay(TimeValue.timeValueMinutes(1)) // <7> .setScriptFields(scriptFields) // <8> .setScrollSize(1000); // <9> // end::update-datafeed-config // Clearing aggregation to avoid complex validation rules datafeedUpdateBuilder.setAggregations((String) null); // tag::update-datafeed-request UpdateDatafeedRequest request = new UpdateDatafeedRequest(datafeedUpdateBuilder.build()); // <1> // end::update-datafeed-request // tag::update-datafeed-execute PutDatafeedResponse response = client.machineLearning().updateDatafeed(request, RequestOptions.DEFAULT); // end::update-datafeed-execute // tag::update-datafeed-response DatafeedConfig updatedDatafeed = response.getResponse(); // <1> // end::update-datafeed-response assertThat(updatedDatafeed.getId(), equalTo(datafeedId)); } { DatafeedUpdate datafeedUpdate = new DatafeedUpdate.Builder(datafeedId).setIndices("index_1", "index_2").build(); UpdateDatafeedRequest request = new UpdateDatafeedRequest(datafeedUpdate); // tag::update-datafeed-execute-listener ActionListener<PutDatafeedResponse> listener = new ActionListener<PutDatafeedResponse>() { @Override public void onResponse(PutDatafeedResponse response) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::update-datafeed-execute-listener // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::update-datafeed-execute-async client.machineLearning().updateDatafeedAsync(request, RequestOptions.DEFAULT, listener); // <1> // end::update-datafeed-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testGetDatafeed() throws Exception { RestHighLevelClient client = highLevelClient(); Job job = MachineLearningIT.buildJob("get-datafeed-job"); client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT); String datafeedId = job.getId() + "-feed"; DatafeedConfig datafeed = DatafeedConfig.builder(datafeedId, job.getId()).setIndices("foo").build(); client.machineLearning().putDatafeed(new PutDatafeedRequest(datafeed), RequestOptions.DEFAULT); { // tag::get-datafeed-request GetDatafeedRequest request = new GetDatafeedRequest(datafeedId); // <1> request.setAllowNoDatafeeds(true); // <2> // end::get-datafeed-request // tag::get-datafeed-execute GetDatafeedResponse response = client.machineLearning().getDatafeed(request, RequestOptions.DEFAULT); // end::get-datafeed-execute // tag::get-datafeed-response long numberOfDatafeeds = response.count(); // <1> List<DatafeedConfig> datafeeds = response.datafeeds(); // <2> // end::get-datafeed-response assertEquals(1, numberOfDatafeeds); assertEquals(1, datafeeds.size()); } { GetDatafeedRequest request = new GetDatafeedRequest(datafeedId); // tag::get-datafeed-execute-listener ActionListener<GetDatafeedResponse> listener = new ActionListener<GetDatafeedResponse>() { @Override public void onResponse(GetDatafeedResponse response) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::get-datafeed-execute-listener // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::get-datafeed-execute-async client.machineLearning().getDatafeedAsync(request, RequestOptions.DEFAULT, listener); // <1> // end::get-datafeed-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testDeleteDatafeed() throws Exception { RestHighLevelClient client = highLevelClient(); String jobId = "test-delete-datafeed-job"; Job job = MachineLearningIT.buildJob(jobId); client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT); String datafeedId = "test-delete-datafeed"; DatafeedConfig datafeed = DatafeedConfig.builder(datafeedId, jobId).setIndices("foo").build(); client.machineLearning().putDatafeed(new PutDatafeedRequest(datafeed), RequestOptions.DEFAULT); { // tag::delete-datafeed-request DeleteDatafeedRequest deleteDatafeedRequest = new DeleteDatafeedRequest(datafeedId); deleteDatafeedRequest.setForce(false); // <1> // end::delete-datafeed-request // tag::delete-datafeed-execute AcknowledgedResponse deleteDatafeedResponse = client.machineLearning().deleteDatafeed( deleteDatafeedRequest, RequestOptions.DEFAULT); // end::delete-datafeed-execute // tag::delete-datafeed-response boolean isAcknowledged = deleteDatafeedResponse.isAcknowledged(); // <1> // end::delete-datafeed-response } // Recreate datafeed to allow second deletion client.machineLearning().putDatafeed(new PutDatafeedRequest(datafeed), RequestOptions.DEFAULT); { // tag::delete-datafeed-execute-listener ActionListener<AcknowledgedResponse> listener = new ActionListener<AcknowledgedResponse>() { @Override public void onResponse(AcknowledgedResponse acknowledgedResponse) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::delete-datafeed-execute-listener // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); DeleteDatafeedRequest deleteDatafeedRequest = new DeleteDatafeedRequest(datafeedId); // tag::delete-datafeed-execute-async client.machineLearning().deleteDatafeedAsync(deleteDatafeedRequest, RequestOptions.DEFAULT, listener); // <1> // end::delete-datafeed-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testPreviewDatafeed() throws Exception { RestHighLevelClient client = highLevelClient(); Job job = MachineLearningIT.buildJob("preview-datafeed-job"); client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT); String datafeedId = job.getId() + "-feed"; String indexName = "preview_data_2"; createIndex(indexName); DatafeedConfig datafeed = DatafeedConfig.builder(datafeedId, job.getId()) .setIndices(indexName) .build(); client.machineLearning().putDatafeed(new PutDatafeedRequest(datafeed), RequestOptions.DEFAULT); { // tag::preview-datafeed-request PreviewDatafeedRequest request = new PreviewDatafeedRequest(datafeedId); // <1> // end::preview-datafeed-request // tag::preview-datafeed-execute PreviewDatafeedResponse response = client.machineLearning().previewDatafeed(request, RequestOptions.DEFAULT); // end::preview-datafeed-execute // tag::preview-datafeed-response BytesReference rawPreview = response.getPreview(); // <1> List<Map<String, Object>> semiParsedPreview = response.getDataList(); // <2> // end::preview-datafeed-response assertTrue(semiParsedPreview.isEmpty()); } { PreviewDatafeedRequest request = new PreviewDatafeedRequest(datafeedId); // tag::preview-datafeed-execute-listener ActionListener<PreviewDatafeedResponse> listener = new ActionListener<PreviewDatafeedResponse>() { @Override public void onResponse(PreviewDatafeedResponse response) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::preview-datafeed-execute-listener // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::preview-datafeed-execute-async client.machineLearning().previewDatafeedAsync(request, RequestOptions.DEFAULT, listener); // <1> // end::preview-datafeed-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testStartDatafeed() throws Exception { RestHighLevelClient client = highLevelClient(); Job job = MachineLearningIT.buildJob("start-datafeed-job"); client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT); String datafeedId = job.getId() + "-feed"; String indexName = "start_data_2"; createIndex(indexName); DatafeedConfig datafeed = DatafeedConfig.builder(datafeedId, job.getId()) .setIndices(indexName) .build(); client.machineLearning().putDatafeed(new PutDatafeedRequest(datafeed), RequestOptions.DEFAULT); client.machineLearning().openJob(new OpenJobRequest(job.getId()), RequestOptions.DEFAULT); { // tag::start-datafeed-request StartDatafeedRequest request = new StartDatafeedRequest(datafeedId); // <1> // end::start-datafeed-request // tag::start-datafeed-request-options request.setEnd("2018-08-21T00:00:00Z"); // <1> request.setStart("2018-08-20T00:00:00Z"); // <2> request.setTimeout(TimeValue.timeValueMinutes(10)); // <3> // end::start-datafeed-request-options // tag::start-datafeed-execute StartDatafeedResponse response = client.machineLearning().startDatafeed(request, RequestOptions.DEFAULT); // end::start-datafeed-execute // tag::start-datafeed-response boolean started = response.isStarted(); // <1> String node = response.getNode(); // <2> // end::start-datafeed-response assertTrue(started); assertThat(node, notNullValue()); } { StartDatafeedRequest request = new StartDatafeedRequest(datafeedId); // tag::start-datafeed-execute-listener ActionListener<StartDatafeedResponse> listener = new ActionListener<StartDatafeedResponse>() { @Override public void onResponse(StartDatafeedResponse response) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::start-datafeed-execute-listener // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::start-datafeed-execute-async client.machineLearning().startDatafeedAsync(request, RequestOptions.DEFAULT, listener); // <1> // end::start-datafeed-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testStopDatafeed() throws Exception { RestHighLevelClient client = highLevelClient(); { // tag::stop-datafeed-request StopDatafeedRequest request = new StopDatafeedRequest("datafeed_id1", "datafeed_id*"); // <1> // end::stop-datafeed-request request = StopDatafeedRequest.stopAllDatafeedsRequest(); // tag::stop-datafeed-request-options request.setAllowNoDatafeeds(true); // <1> request.setForce(true); // <2> request.setTimeout(TimeValue.timeValueMinutes(10)); // <3> // end::stop-datafeed-request-options // tag::stop-datafeed-execute StopDatafeedResponse response = client.machineLearning().stopDatafeed(request, RequestOptions.DEFAULT); // end::stop-datafeed-execute // tag::stop-datafeed-response boolean stopped = response.isStopped(); // <1> // end::stop-datafeed-response assertTrue(stopped); } { StopDatafeedRequest request = StopDatafeedRequest.stopAllDatafeedsRequest(); // tag::stop-datafeed-execute-listener ActionListener<StopDatafeedResponse> listener = new ActionListener<StopDatafeedResponse>() { @Override public void onResponse(StopDatafeedResponse response) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::stop-datafeed-execute-listener // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::stop-datafeed-execute-async client.machineLearning().stopDatafeedAsync(request, RequestOptions.DEFAULT, listener); // <1> // end::stop-datafeed-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testGetDatafeedStats() throws Exception { RestHighLevelClient client = highLevelClient(); Job job = MachineLearningIT.buildJob("get-machine-learning-datafeed-stats1"); client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT); Job secondJob = MachineLearningIT.buildJob("get-machine-learning-datafeed-stats2"); client.machineLearning().putJob(new PutJobRequest(secondJob), RequestOptions.DEFAULT); String datafeedId1 = job.getId() + "-feed"; String indexName = "datafeed_stats_data_2"; createIndex(indexName); DatafeedConfig datafeed = DatafeedConfig.builder(datafeedId1, job.getId()) .setIndices(indexName) .build(); client.machineLearning().putDatafeed(new PutDatafeedRequest(datafeed), RequestOptions.DEFAULT); String datafeedId2 = secondJob.getId() + "-feed"; DatafeedConfig secondDatafeed = DatafeedConfig.builder(datafeedId2, secondJob.getId()) .setIndices(indexName) .build(); client.machineLearning().putDatafeed(new PutDatafeedRequest(secondDatafeed), RequestOptions.DEFAULT); { //tag::get-datafeed-stats-request GetDatafeedStatsRequest request = new GetDatafeedStatsRequest("get-machine-learning-datafeed-stats1-feed", "get-machine-learning-datafeed*"); // <1> request.setAllowNoDatafeeds(true); // <2> //end::get-datafeed-stats-request //tag::get-datafeed-stats-execute GetDatafeedStatsResponse response = client.machineLearning().getDatafeedStats(request, RequestOptions.DEFAULT); //end::get-datafeed-stats-execute //tag::get-datafeed-stats-response long numberOfDatafeedStats = response.count(); // <1> List<DatafeedStats> datafeedStats = response.datafeedStats(); // <2> //end::get-datafeed-stats-response assertEquals(2, response.count()); assertThat(response.datafeedStats(), hasSize(2)); assertThat(response.datafeedStats().stream().map(DatafeedStats::getDatafeedId).collect(Collectors.toList()), containsInAnyOrder(datafeed.getId(), secondDatafeed.getId())); } { GetDatafeedStatsRequest request = new GetDatafeedStatsRequest("*"); // tag::get-datafeed-stats-execute-listener ActionListener<GetDatafeedStatsResponse> listener = new ActionListener<GetDatafeedStatsResponse>() { @Override public void onResponse(GetDatafeedStatsResponse response) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::get-datafeed-stats-execute-listener // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::get-datafeed-stats-execute-async client.machineLearning().getDatafeedStatsAsync(request, RequestOptions.DEFAULT, listener); // <1> // end::get-datafeed-stats-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testGetBuckets() throws IOException, InterruptedException { RestHighLevelClient client = highLevelClient(); String jobId = "test-get-buckets"; Job job = MachineLearningIT.buildJob(jobId); client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT); // Let us index a bucket IndexRequest indexRequest = new IndexRequest(".ml-anomalies-shared"); indexRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); indexRequest.source("{\"job_id\":\"test-get-buckets\", \"result_type\":\"bucket\", \"timestamp\": 1533081600000," + "\"bucket_span\": 600,\"is_interim\": false, \"anomaly_score\": 80.0}", XContentType.JSON); client.index(indexRequest, RequestOptions.DEFAULT); { // tag::get-buckets-request GetBucketsRequest request = new GetBucketsRequest(jobId); // <1> // end::get-buckets-request // tag::get-buckets-timestamp request.setTimestamp("2018-08-17T00:00:00Z"); // <1> // end::get-buckets-timestamp // Set timestamp to null as it is incompatible with other args request.setTimestamp(null); // tag::get-buckets-anomaly-score request.setAnomalyScore(75.0); // <1> // end::get-buckets-anomaly-score // tag::get-buckets-desc request.setDescending(true); // <1> // end::get-buckets-desc // tag::get-buckets-end request.setEnd("2018-08-21T00:00:00Z"); // <1> // end::get-buckets-end // tag::get-buckets-exclude-interim request.setExcludeInterim(true); // <1> // end::get-buckets-exclude-interim // tag::get-buckets-expand request.setExpand(true); // <1> // end::get-buckets-expand // tag::get-buckets-page request.setPageParams(new PageParams(100, 200)); // <1> // end::get-buckets-page // Set page params back to null so the response contains the bucket we indexed request.setPageParams(null); // tag::get-buckets-sort request.setSort("anomaly_score"); // <1> // end::get-buckets-sort // tag::get-buckets-start request.setStart("2018-08-01T00:00:00Z"); // <1> // end::get-buckets-start // tag::get-buckets-execute GetBucketsResponse response = client.machineLearning().getBuckets(request, RequestOptions.DEFAULT); // end::get-buckets-execute // tag::get-buckets-response long count = response.count(); // <1> List<Bucket> buckets = response.buckets(); // <2> // end::get-buckets-response assertEquals(1, buckets.size()); } { GetBucketsRequest request = new GetBucketsRequest(jobId); // tag::get-buckets-execute-listener ActionListener<GetBucketsResponse> listener = new ActionListener<GetBucketsResponse>() { @Override public void onResponse(GetBucketsResponse getBucketsResponse) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::get-buckets-execute-listener // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::get-buckets-execute-async client.machineLearning().getBucketsAsync(request, RequestOptions.DEFAULT, listener); // <1> // end::get-buckets-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testFlushJob() throws Exception { RestHighLevelClient client = highLevelClient(); Job job = MachineLearningIT.buildJob("flushing-my-first-machine-learning-job"); client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT); client.machineLearning().openJob(new OpenJobRequest(job.getId()), RequestOptions.DEFAULT); Job secondJob = MachineLearningIT.buildJob("flushing-my-second-machine-learning-job"); client.machineLearning().putJob(new PutJobRequest(secondJob), RequestOptions.DEFAULT); client.machineLearning().openJob(new OpenJobRequest(secondJob.getId()), RequestOptions.DEFAULT); { // tag::flush-job-request FlushJobRequest flushJobRequest = new FlushJobRequest("flushing-my-first-machine-learning-job"); // <1> // end::flush-job-request // tag::flush-job-request-options flushJobRequest.setCalcInterim(true); // <1> flushJobRequest.setAdvanceTime("2018-08-31T16:35:07+00:00"); // <2> flushJobRequest.setStart("2018-08-31T16:35:17+00:00"); // <3> flushJobRequest.setEnd("2018-08-31T16:35:27+00:00"); // <4> flushJobRequest.setSkipTime("2018-08-31T16:35:00+00:00"); // <5> // end::flush-job-request-options // tag::flush-job-execute FlushJobResponse flushJobResponse = client.machineLearning().flushJob(flushJobRequest, RequestOptions.DEFAULT); // end::flush-job-execute // tag::flush-job-response boolean isFlushed = flushJobResponse.isFlushed(); // <1> Date lastFinalizedBucketEnd = flushJobResponse.getLastFinalizedBucketEnd(); // <2> // end::flush-job-response } { // tag::flush-job-execute-listener ActionListener<FlushJobResponse> listener = new ActionListener<FlushJobResponse>() { @Override public void onResponse(FlushJobResponse FlushJobResponse) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::flush-job-execute-listener FlushJobRequest flushJobRequest = new FlushJobRequest("flushing-my-second-machine-learning-job"); // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::flush-job-execute-async client.machineLearning().flushJobAsync(flushJobRequest, RequestOptions.DEFAULT, listener); // <1> // end::flush-job-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testDeleteForecast() throws Exception { RestHighLevelClient client = highLevelClient(); Job job = MachineLearningIT.buildJob("deleting-forecast-for-job"); client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT); client.machineLearning().openJob(new OpenJobRequest(job.getId()), RequestOptions.DEFAULT); PostDataRequest.JsonBuilder builder = new PostDataRequest.JsonBuilder(); for(int i = 0; i < 30; i++) { Map<String, Object> hashMap = new HashMap<>(); hashMap.put("total", randomInt(1000)); hashMap.put("timestamp", (i+1)*1000); builder.addDoc(hashMap); } PostDataRequest postDataRequest = new PostDataRequest(job.getId(), builder); client.machineLearning().postData(postDataRequest, RequestOptions.DEFAULT); client.machineLearning().flushJob(new FlushJobRequest(job.getId()), RequestOptions.DEFAULT); ForecastJobResponse forecastJobResponse = client.machineLearning(). forecastJob(new ForecastJobRequest(job.getId()), RequestOptions.DEFAULT); String forecastId = forecastJobResponse.getForecastId(); GetRequest request = new GetRequest(".ml-anomalies-" + job.getId()); request.id(job.getId() + "_model_forecast_request_stats_" + forecastId); assertBusy(() -> { GetResponse getResponse = highLevelClient().get(request, RequestOptions.DEFAULT); assertTrue(getResponse.isExists()); assertTrue(getResponse.getSourceAsString().contains("finished")); }, 30, TimeUnit.SECONDS); { // tag::delete-forecast-request DeleteForecastRequest deleteForecastRequest = new DeleteForecastRequest("deleting-forecast-for-job"); // <1> // end::delete-forecast-request // tag::delete-forecast-request-options deleteForecastRequest.setForecastIds(forecastId); // <1> deleteForecastRequest.timeout("30s"); // <2> deleteForecastRequest.setAllowNoForecasts(true); // <3> // end::delete-forecast-request-options // tag::delete-forecast-execute AcknowledgedResponse deleteForecastResponse = client.machineLearning().deleteForecast(deleteForecastRequest, RequestOptions.DEFAULT); // end::delete-forecast-execute // tag::delete-forecast-response boolean isAcknowledged = deleteForecastResponse.isAcknowledged(); // <1> // end::delete-forecast-response } { // tag::delete-forecast-execute-listener ActionListener<AcknowledgedResponse> listener = new ActionListener<AcknowledgedResponse>() { @Override public void onResponse(AcknowledgedResponse DeleteForecastResponse) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::delete-forecast-execute-listener DeleteForecastRequest deleteForecastRequest = DeleteForecastRequest.deleteAllForecasts(job.getId()); deleteForecastRequest.setAllowNoForecasts(true); // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::delete-forecast-execute-async client.machineLearning().deleteForecastAsync(deleteForecastRequest, RequestOptions.DEFAULT, listener); // <1> // end::delete-forecast-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testGetJobStats() throws Exception { RestHighLevelClient client = highLevelClient(); Job job = MachineLearningIT.buildJob("get-machine-learning-job-stats1"); client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT); Job secondJob = MachineLearningIT.buildJob("get-machine-learning-job-stats2"); client.machineLearning().putJob(new PutJobRequest(secondJob), RequestOptions.DEFAULT); { // tag::get-job-stats-request GetJobStatsRequest request = new GetJobStatsRequest("get-machine-learning-job-stats1", "get-machine-learning-job-*"); // <1> request.setAllowNoJobs(true); // <2> // end::get-job-stats-request // tag::get-job-stats-execute GetJobStatsResponse response = client.machineLearning().getJobStats(request, RequestOptions.DEFAULT); // end::get-job-stats-execute // tag::get-job-stats-response long numberOfJobStats = response.count(); // <1> List<JobStats> jobStats = response.jobStats(); // <2> // end::get-job-stats-response assertEquals(2, response.count()); assertThat(response.jobStats(), hasSize(2)); assertThat(response.jobStats().stream().map(JobStats::getJobId).collect(Collectors.toList()), containsInAnyOrder(job.getId(), secondJob.getId())); } { GetJobStatsRequest request = new GetJobStatsRequest("get-machine-learning-job-stats1", "get-machine-learning-job-*"); // tag::get-job-stats-execute-listener ActionListener<GetJobStatsResponse> listener = new ActionListener<GetJobStatsResponse>() { @Override public void onResponse(GetJobStatsResponse response) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::get-job-stats-execute-listener // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::get-job-stats-execute-async client.machineLearning().getJobStatsAsync(request, RequestOptions.DEFAULT, listener); // <1> // end::get-job-stats-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testForecastJob() throws Exception { RestHighLevelClient client = highLevelClient(); Job job = MachineLearningIT.buildJob("forecasting-my-first-machine-learning-job"); client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT); client.machineLearning().openJob(new OpenJobRequest(job.getId()), RequestOptions.DEFAULT); PostDataRequest.JsonBuilder builder = new PostDataRequest.JsonBuilder(); for(int i = 0; i < 30; i++) { Map<String, Object> hashMap = new HashMap<>(); hashMap.put("total", randomInt(1000)); hashMap.put("timestamp", (i+1)*1000); builder.addDoc(hashMap); } PostDataRequest postDataRequest = new PostDataRequest(job.getId(), builder); client.machineLearning().postData(postDataRequest, RequestOptions.DEFAULT); client.machineLearning().flushJob(new FlushJobRequest(job.getId()), RequestOptions.DEFAULT); { // tag::forecast-job-request ForecastJobRequest forecastJobRequest = new ForecastJobRequest("forecasting-my-first-machine-learning-job"); // <1> // end::forecast-job-request // tag::forecast-job-request-options forecastJobRequest.setExpiresIn(TimeValue.timeValueHours(48)); // <1> forecastJobRequest.setDuration(TimeValue.timeValueHours(24)); // <2> forecastJobRequest.setMaxModelMemory(new ByteSizeValue(30, ByteSizeUnit.MB)); // <3> // end::forecast-job-request-options // tag::forecast-job-execute ForecastJobResponse forecastJobResponse = client.machineLearning().forecastJob(forecastJobRequest, RequestOptions.DEFAULT); // end::forecast-job-execute // tag::forecast-job-response boolean isAcknowledged = forecastJobResponse.isAcknowledged(); // <1> String forecastId = forecastJobResponse.getForecastId(); // <2> // end::forecast-job-response assertTrue(isAcknowledged); assertNotNull(forecastId); } { // tag::forecast-job-execute-listener ActionListener<ForecastJobResponse> listener = new ActionListener<ForecastJobResponse>() { @Override public void onResponse(ForecastJobResponse forecastJobResponse) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::forecast-job-execute-listener ForecastJobRequest forecastJobRequest = new ForecastJobRequest("forecasting-my-first-machine-learning-job"); // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::forecast-job-execute-async client.machineLearning().forecastJobAsync(forecastJobRequest, RequestOptions.DEFAULT, listener); // <1> // end::forecast-job-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testGetOverallBuckets() throws IOException, InterruptedException { RestHighLevelClient client = highLevelClient(); String jobId1 = "test-get-overall-buckets-1"; String jobId2 = "test-get-overall-buckets-2"; Job job1 = MachineLearningGetResultsIT.buildJob(jobId1); Job job2 = MachineLearningGetResultsIT.buildJob(jobId2); client.machineLearning().putJob(new PutJobRequest(job1), RequestOptions.DEFAULT); client.machineLearning().putJob(new PutJobRequest(job2), RequestOptions.DEFAULT); // Let us index some buckets BulkRequest bulkRequest = new BulkRequest(); bulkRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); { IndexRequest indexRequest = new IndexRequest(".ml-anomalies-shared"); indexRequest.source("{\"job_id\":\"test-get-overall-buckets-1\", \"result_type\":\"bucket\", \"timestamp\": 1533081600000," + "\"bucket_span\": 600,\"is_interim\": false, \"anomaly_score\": 60.0}", XContentType.JSON); bulkRequest.add(indexRequest); } { IndexRequest indexRequest = new IndexRequest(".ml-anomalies-shared"); indexRequest.source("{\"job_id\":\"test-get-overall-buckets-2\", \"result_type\":\"bucket\", \"timestamp\": 1533081600000," + "\"bucket_span\": 3600,\"is_interim\": false, \"anomaly_score\": 100.0}", XContentType.JSON); bulkRequest.add(indexRequest); } client.bulk(bulkRequest, RequestOptions.DEFAULT); { // tag::get-overall-buckets-request GetOverallBucketsRequest request = new GetOverallBucketsRequest(jobId1, jobId2); // <1> // end::get-overall-buckets-request // tag::get-overall-buckets-bucket-span request.setBucketSpan(TimeValue.timeValueHours(24)); // <1> // end::get-overall-buckets-bucket-span // tag::get-overall-buckets-end request.setEnd("2018-08-21T00:00:00Z"); // <1> // end::get-overall-buckets-end // tag::get-overall-buckets-exclude-interim request.setExcludeInterim(true); // <1> // end::get-overall-buckets-exclude-interim // tag::get-overall-buckets-overall-score request.setOverallScore(75.0); // <1> // end::get-overall-buckets-overall-score // tag::get-overall-buckets-start request.setStart("2018-08-01T00:00:00Z"); // <1> // end::get-overall-buckets-start // tag::get-overall-buckets-top-n request.setTopN(2); // <1> // end::get-overall-buckets-top-n // tag::get-overall-buckets-execute GetOverallBucketsResponse response = client.machineLearning().getOverallBuckets(request, RequestOptions.DEFAULT); // end::get-overall-buckets-execute // tag::get-overall-buckets-response long count = response.count(); // <1> List<OverallBucket> overallBuckets = response.overallBuckets(); // <2> // end::get-overall-buckets-response assertEquals(1, overallBuckets.size()); assertThat(overallBuckets.get(0).getOverallScore(), is(closeTo(80.0, 0.001))); } { GetOverallBucketsRequest request = new GetOverallBucketsRequest(jobId1, jobId2); // tag::get-overall-buckets-execute-listener ActionListener<GetOverallBucketsResponse> listener = new ActionListener<GetOverallBucketsResponse>() { @Override public void onResponse(GetOverallBucketsResponse getOverallBucketsResponse) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::get-overall-buckets-execute-listener // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::get-overall-buckets-execute-async client.machineLearning().getOverallBucketsAsync(request, RequestOptions.DEFAULT, listener); // <1> // end::get-overall-buckets-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testGetRecords() throws IOException, InterruptedException { RestHighLevelClient client = highLevelClient(); String jobId = "test-get-records"; Job job = MachineLearningIT.buildJob(jobId); client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT); // Let us index a record IndexRequest indexRequest = new IndexRequest(".ml-anomalies-shared"); indexRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); indexRequest.source("{\"job_id\":\"test-get-records\", \"result_type\":\"record\", \"timestamp\": 1533081600000," + "\"bucket_span\": 600,\"is_interim\": false, \"record_score\": 80.0}", XContentType.JSON); client.index(indexRequest, RequestOptions.DEFAULT); { // tag::get-records-request GetRecordsRequest request = new GetRecordsRequest(jobId); // <1> // end::get-records-request // tag::get-records-desc request.setDescending(true); // <1> // end::get-records-desc // tag::get-records-end request.setEnd("2018-08-21T00:00:00Z"); // <1> // end::get-records-end // tag::get-records-exclude-interim request.setExcludeInterim(true); // <1> // end::get-records-exclude-interim // tag::get-records-page request.setPageParams(new PageParams(100, 200)); // <1> // end::get-records-page // Set page params back to null so the response contains the record we indexed request.setPageParams(null); // tag::get-records-record-score request.setRecordScore(75.0); // <1> // end::get-records-record-score // tag::get-records-sort request.setSort("probability"); // <1> // end::get-records-sort // tag::get-records-start request.setStart("2018-08-01T00:00:00Z"); // <1> // end::get-records-start // tag::get-records-execute GetRecordsResponse response = client.machineLearning().getRecords(request, RequestOptions.DEFAULT); // end::get-records-execute // tag::get-records-response long count = response.count(); // <1> List<AnomalyRecord> records = response.records(); // <2> // end::get-records-response assertEquals(1, records.size()); } { GetRecordsRequest request = new GetRecordsRequest(jobId); // tag::get-records-execute-listener ActionListener<GetRecordsResponse> listener = new ActionListener<GetRecordsResponse>() { @Override public void onResponse(GetRecordsResponse getRecordsResponse) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::get-records-execute-listener // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::get-records-execute-async client.machineLearning().getRecordsAsync(request, RequestOptions.DEFAULT, listener); // <1> // end::get-records-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testPostData() throws Exception { RestHighLevelClient client = highLevelClient(); Job job = MachineLearningIT.buildJob("test-post-data"); client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT); client.machineLearning().openJob(new OpenJobRequest(job.getId()), RequestOptions.DEFAULT); { // tag::post-data-request PostDataRequest.JsonBuilder jsonBuilder = new PostDataRequest.JsonBuilder(); // <1> Map<String, Object> mapData = new HashMap<>(); mapData.put("total", 109); jsonBuilder.addDoc(mapData); // <2> jsonBuilder.addDoc("{\"total\":1000}"); // <3> PostDataRequest postDataRequest = new PostDataRequest("test-post-data", jsonBuilder); // <4> // end::post-data-request // tag::post-data-request-options postDataRequest.setResetStart("2018-08-31T16:35:07+00:00"); // <1> postDataRequest.setResetEnd("2018-08-31T16:35:17+00:00"); // <2> // end::post-data-request-options postDataRequest.setResetEnd(null); postDataRequest.setResetStart(null); // tag::post-data-execute PostDataResponse postDataResponse = client.machineLearning().postData(postDataRequest, RequestOptions.DEFAULT); // end::post-data-execute // tag::post-data-response DataCounts dataCounts = postDataResponse.getDataCounts(); // <1> // end::post-data-response assertEquals(2, dataCounts.getInputRecordCount()); } { // tag::post-data-execute-listener ActionListener<PostDataResponse> listener = new ActionListener<PostDataResponse>() { @Override public void onResponse(PostDataResponse postDataResponse) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::post-data-execute-listener PostDataRequest.JsonBuilder jsonBuilder = new PostDataRequest.JsonBuilder(); Map<String, Object> mapData = new HashMap<>(); mapData.put("total", 109); jsonBuilder.addDoc(mapData); PostDataRequest postDataRequest = new PostDataRequest("test-post-data", jsonBuilder); // <1> // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::post-data-execute-async client.machineLearning().postDataAsync(postDataRequest, RequestOptions.DEFAULT, listener); // <1> // end::post-data-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testFindFileStructure() throws Exception { RestHighLevelClient client = highLevelClient(); Path anInterestingFile = createTempFile(); String contents = "{\"logger\":\"controller\",\"timestamp\":1478261151445,\"level\":\"INFO\"," + "\"pid\":42,\"thread\":\"0x7fff7d2a8000\",\"message\":\"message 1\",\"class\":\"ml\"," + "\"method\":\"core::SomeNoiseMaker\",\"file\":\"Noisemaker.cc\",\"line\":333}\n" + "{\"logger\":\"controller\",\"timestamp\":1478261151445," + "\"level\":\"INFO\",\"pid\":42,\"thread\":\"0x7fff7d2a8000\",\"message\":\"message 2\",\"class\":\"ml\"," + "\"method\":\"core::SomeNoiseMaker\",\"file\":\"Noisemaker.cc\",\"line\":333}\n"; Files.write(anInterestingFile, Collections.singleton(contents), StandardCharsets.UTF_8); { // tag::find-file-structure-request FindFileStructureRequest findFileStructureRequest = new FindFileStructureRequest(); // <1> findFileStructureRequest.setSample(Files.readAllBytes(anInterestingFile)); // <2> // end::find-file-structure-request // tag::find-file-structure-request-options findFileStructureRequest.setLinesToSample(500); // <1> findFileStructureRequest.setExplain(true); // <2> // end::find-file-structure-request-options // tag::find-file-structure-execute FindFileStructureResponse findFileStructureResponse = client.machineLearning().findFileStructure(findFileStructureRequest, RequestOptions.DEFAULT); // end::find-file-structure-execute // tag::find-file-structure-response FileStructure structure = findFileStructureResponse.getFileStructure(); // <1> // end::find-file-structure-response assertEquals(2, structure.getNumLinesAnalyzed()); } { // tag::find-file-structure-execute-listener ActionListener<FindFileStructureResponse> listener = new ActionListener<FindFileStructureResponse>() { @Override public void onResponse(FindFileStructureResponse findFileStructureResponse) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::find-file-structure-execute-listener FindFileStructureRequest findFileStructureRequest = new FindFileStructureRequest(); findFileStructureRequest.setSample(Files.readAllBytes(anInterestingFile)); // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::find-file-structure-execute-async client.machineLearning().findFileStructureAsync(findFileStructureRequest, RequestOptions.DEFAULT, listener); // <1> // end::find-file-structure-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testGetInfluencers() throws IOException, InterruptedException { RestHighLevelClient client = highLevelClient(); String jobId = "test-get-influencers"; Job job = MachineLearningIT.buildJob(jobId); client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT); // Let us index a record IndexRequest indexRequest = new IndexRequest(".ml-anomalies-shared"); indexRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); indexRequest.source("{\"job_id\":\"test-get-influencers\", \"result_type\":\"influencer\", \"timestamp\": 1533081600000," + "\"bucket_span\": 600,\"is_interim\": false, \"influencer_score\": 80.0, \"influencer_field_name\": \"my_influencer\"," + "\"influencer_field_value\":\"foo\"}", XContentType.JSON); client.index(indexRequest, RequestOptions.DEFAULT); { // tag::get-influencers-request GetInfluencersRequest request = new GetInfluencersRequest(jobId); // <1> // end::get-influencers-request // tag::get-influencers-desc request.setDescending(true); // <1> // end::get-influencers-desc // tag::get-influencers-end request.setEnd("2018-08-21T00:00:00Z"); // <1> // end::get-influencers-end // tag::get-influencers-exclude-interim request.setExcludeInterim(true); // <1> // end::get-influencers-exclude-interim // tag::get-influencers-influencer-score request.setInfluencerScore(75.0); // <1> // end::get-influencers-influencer-score // tag::get-influencers-page request.setPageParams(new PageParams(100, 200)); // <1> // end::get-influencers-page // Set page params back to null so the response contains the influencer we indexed request.setPageParams(null); // tag::get-influencers-sort request.setSort("probability"); // <1> // end::get-influencers-sort // tag::get-influencers-start request.setStart("2018-08-01T00:00:00Z"); // <1> // end::get-influencers-start // tag::get-influencers-execute GetInfluencersResponse response = client.machineLearning().getInfluencers(request, RequestOptions.DEFAULT); // end::get-influencers-execute // tag::get-influencers-response long count = response.count(); // <1> List<Influencer> influencers = response.influencers(); // <2> // end::get-influencers-response assertEquals(1, influencers.size()); } { GetInfluencersRequest request = new GetInfluencersRequest(jobId); // tag::get-influencers-execute-listener ActionListener<GetInfluencersResponse> listener = new ActionListener<GetInfluencersResponse>() { @Override public void onResponse(GetInfluencersResponse getInfluencersResponse) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::get-influencers-execute-listener // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::get-influencers-execute-async client.machineLearning().getInfluencersAsync(request, RequestOptions.DEFAULT, listener); // <1> // end::get-influencers-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testGetCategories() throws IOException, InterruptedException { RestHighLevelClient client = highLevelClient(); String jobId = "test-get-categories"; Job job = MachineLearningIT.buildJob(jobId); client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT); // Let us index a category IndexRequest indexRequest = new IndexRequest(".ml-anomalies-shared"); indexRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); indexRequest.source("{\"job_id\": \"test-get-categories\", \"category_id\": 1, \"terms\": \"AAL\"," + " \"regex\": \".*?AAL.*\", \"max_matching_length\": 3, \"examples\": [\"AAL\"]}", XContentType.JSON); client.index(indexRequest, RequestOptions.DEFAULT); { // tag::get-categories-request GetCategoriesRequest request = new GetCategoriesRequest(jobId); // <1> // end::get-categories-request // tag::get-categories-category-id request.setCategoryId(1L); // <1> // end::get-categories-category-id // tag::get-categories-page request.setPageParams(new PageParams(100, 200)); // <1> // end::get-categories-page // Set page params back to null so the response contains the category we indexed request.setPageParams(null); // tag::get-categories-execute GetCategoriesResponse response = client.machineLearning().getCategories(request, RequestOptions.DEFAULT); // end::get-categories-execute // tag::get-categories-response long count = response.count(); // <1> List<CategoryDefinition> categories = response.categories(); // <2> // end::get-categories-response assertEquals(1, categories.size()); } { GetCategoriesRequest request = new GetCategoriesRequest(jobId); // tag::get-categories-execute-listener ActionListener<GetCategoriesResponse> listener = new ActionListener<GetCategoriesResponse>() { @Override public void onResponse(GetCategoriesResponse getcategoriesResponse) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::get-categories-execute-listener // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::get-categories-execute-async client.machineLearning().getCategoriesAsync(request, RequestOptions.DEFAULT, listener); // <1> // end::get-categories-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testDeleteExpiredData() throws IOException, InterruptedException { RestHighLevelClient client = highLevelClient(); String jobId = "test-delete-expired-data"; MachineLearningIT.buildJob(jobId); { // tag::delete-expired-data-request DeleteExpiredDataRequest request = new DeleteExpiredDataRequest( // <1> null, // <2> 1000.0f, // <3> TimeValue.timeValueHours(12) // <4> ); // end::delete-expired-data-request // tag::delete-expired-data-execute DeleteExpiredDataResponse response = client.machineLearning().deleteExpiredData(request, RequestOptions.DEFAULT); // end::delete-expired-data-execute // tag::delete-expired-data-response boolean deleted = response.getDeleted(); // <1> // end::delete-expired-data-response assertTrue(deleted); } { // tag::delete-expired-data-execute-listener ActionListener<DeleteExpiredDataResponse> listener = new ActionListener<DeleteExpiredDataResponse>() { @Override public void onResponse(DeleteExpiredDataResponse deleteExpiredDataResponse) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::delete-expired-data-execute-listener // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); DeleteExpiredDataRequest deleteExpiredDataRequest = new DeleteExpiredDataRequest(); // tag::delete-expired-data-execute-async client.machineLearning().deleteExpiredDataAsync(deleteExpiredDataRequest, RequestOptions.DEFAULT, listener); // <1> // end::delete-expired-data-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testDeleteModelSnapshot() throws IOException, InterruptedException { RestHighLevelClient client = highLevelClient(); String jobId = "test-delete-model-snapshot"; String snapshotId = "1541587919"; Job job = MachineLearningIT.buildJob(jobId); client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT); // Let us index a snapshot IndexRequest indexRequest = new IndexRequest(".ml-anomalies-shared"); indexRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); indexRequest.source("{\"job_id\":\"" + jobId + "\", \"timestamp\":1541587919000, " + "\"description\":\"State persisted due to job close at 2018-11-07T10:51:59+0000\", " + "\"snapshot_id\":\"" + snapshotId + "\", \"snapshot_doc_count\":1, \"model_size_stats\":{" + "\"job_id\":\"" + jobId + "\", \"result_type\":\"model_size_stats\",\"model_bytes\":51722, " + "\"total_by_field_count\":3, \"total_over_field_count\":0, \"total_partition_field_count\":2," + "\"bucket_allocation_failures_count\":0, \"memory_status\":\"ok\", \"log_time\":1541587919000, " + "\"timestamp\":1519930800000}, \"latest_record_time_stamp\":1519931700000," + "\"latest_result_time_stamp\":1519930800000, \"retain\":false}", XContentType.JSON); { client.index(indexRequest, RequestOptions.DEFAULT); // tag::delete-model-snapshot-request DeleteModelSnapshotRequest request = new DeleteModelSnapshotRequest(jobId, snapshotId); // <1> // end::delete-model-snapshot-request // tag::delete-model-snapshot-execute AcknowledgedResponse response = client.machineLearning().deleteModelSnapshot(request, RequestOptions.DEFAULT); // end::delete-model-snapshot-execute // tag::delete-model-snapshot-response boolean isAcknowledged = response.isAcknowledged(); // <1> // end::delete-model-snapshot-response assertTrue(isAcknowledged); } { client.index(indexRequest, RequestOptions.DEFAULT); // tag::delete-model-snapshot-execute-listener ActionListener<AcknowledgedResponse> listener = new ActionListener<AcknowledgedResponse>() { @Override public void onResponse(AcknowledgedResponse acknowledgedResponse) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::delete-model-snapshot-execute-listener // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); DeleteModelSnapshotRequest deleteModelSnapshotRequest = new DeleteModelSnapshotRequest(jobId, "1541587919"); // tag::delete-model-snapshot-execute-async client.machineLearning().deleteModelSnapshotAsync(deleteModelSnapshotRequest, RequestOptions.DEFAULT, listener); // <1> // end::delete-model-snapshot-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testGetModelSnapshots() throws IOException, InterruptedException { RestHighLevelClient client = highLevelClient(); String jobId = "test-get-model-snapshots"; Job job = MachineLearningIT.buildJob(jobId); client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT); // Let us index a snapshot IndexRequest indexRequest = new IndexRequest(".ml-anomalies-shared"); indexRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); indexRequest.source("{\"job_id\":\"test-get-model-snapshots\", \"timestamp\":1541587919000, " + "\"description\":\"State persisted due to job close at 2018-11-07T10:51:59+0000\", " + "\"snapshot_id\":\"1541587919\", \"snapshot_doc_count\":1, \"model_size_stats\":{" + "\"job_id\":\"test-get-model-snapshots\", \"result_type\":\"model_size_stats\",\"model_bytes\":51722, " + "\"total_by_field_count\":3, \"total_over_field_count\":0, \"total_partition_field_count\":2," + "\"bucket_allocation_failures_count\":0, \"memory_status\":\"ok\", \"log_time\":1541587919000, " + "\"timestamp\":1519930800000}, \"latest_record_time_stamp\":1519931700000," + "\"latest_result_time_stamp\":1519930800000, \"retain\":false}", XContentType.JSON); client.index(indexRequest, RequestOptions.DEFAULT); { // tag::get-model-snapshots-request GetModelSnapshotsRequest request = new GetModelSnapshotsRequest(jobId); // <1> // end::get-model-snapshots-request // tag::get-model-snapshots-snapshot-id request.setSnapshotId("1541587919"); // <1> // end::get-model-snapshots-snapshot-id // Set snapshot id to null as it is incompatible with other args request.setSnapshotId(null); // tag::get-model-snapshots-desc request.setDesc(true); // <1> // end::get-model-snapshots-desc // tag::get-model-snapshots-end request.setEnd("2018-11-07T21:00:00Z"); // <1> // end::get-model-snapshots-end // tag::get-model-snapshots-page request.setPageParams(new PageParams(100, 200)); // <1> // end::get-model-snapshots-page // Set page params back to null so the response contains the snapshot we indexed request.setPageParams(null); // tag::get-model-snapshots-sort request.setSort("latest_result_time_stamp"); // <1> // end::get-model-snapshots-sort // tag::get-model-snapshots-start request.setStart("2018-11-07T00:00:00Z"); // <1> // end::get-model-snapshots-start // tag::get-model-snapshots-execute GetModelSnapshotsResponse response = client.machineLearning().getModelSnapshots(request, RequestOptions.DEFAULT); // end::get-model-snapshots-execute // tag::get-model-snapshots-response long count = response.count(); // <1> List<ModelSnapshot> modelSnapshots = response.snapshots(); // <2> // end::get-model-snapshots-response assertEquals(1, modelSnapshots.size()); } { GetModelSnapshotsRequest request = new GetModelSnapshotsRequest(jobId); // tag::get-model-snapshots-execute-listener ActionListener<GetModelSnapshotsResponse> listener = new ActionListener<GetModelSnapshotsResponse>() { @Override public void onResponse(GetModelSnapshotsResponse getModelSnapshotsResponse) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::get-model-snapshots-execute-listener // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::get-model-snapshots-execute-async client.machineLearning().getModelSnapshotsAsync(request, RequestOptions.DEFAULT, listener); // <1> // end::get-model-snapshots-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testRevertModelSnapshot() throws IOException, InterruptedException { RestHighLevelClient client = highLevelClient(); String jobId = "test-revert-model-snapshot"; String snapshotId = "1541587919"; Job job = MachineLearningIT.buildJob(jobId); client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT); // Let us index a snapshot String documentId = jobId + "_model_snapshot_" + snapshotId; IndexRequest indexRequest = new IndexRequest(".ml-anomalies-shared").id(documentId); indexRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); indexRequest.source("{\"job_id\":\"test-revert-model-snapshot\", \"timestamp\":1541587919000, " + "\"description\":\"State persisted due to job close at 2018-11-07T10:51:59+0000\", " + "\"snapshot_id\":\"1541587919\", \"snapshot_doc_count\":1, \"model_size_stats\":{" + "\"job_id\":\"test-revert-model-snapshot\", \"result_type\":\"model_size_stats\",\"model_bytes\":51722, " + "\"total_by_field_count\":3, \"total_over_field_count\":0, \"total_partition_field_count\":2," + "\"bucket_allocation_failures_count\":0, \"memory_status\":\"ok\", \"log_time\":1541587919000, " + "\"timestamp\":1519930800000}, \"latest_record_time_stamp\":1519931700000," + "\"latest_result_time_stamp\":1519930800000, \"retain\":false, " + "\"quantiles\":{\"job_id\":\"test-revert-model-snapshot\", \"timestamp\":1541587919000, " + "\"quantile_state\":\"state\"}}", XContentType.JSON); client.index(indexRequest, RequestOptions.DEFAULT); { // tag::revert-model-snapshot-request RevertModelSnapshotRequest request = new RevertModelSnapshotRequest(jobId, snapshotId); // <1> // end::revert-model-snapshot-request // tag::revert-model-snapshot-delete-intervening-results request.setDeleteInterveningResults(true); // <1> // end::revert-model-snapshot-delete-intervening-results // tag::revert-model-snapshot-execute RevertModelSnapshotResponse response = client.machineLearning().revertModelSnapshot(request, RequestOptions.DEFAULT); // end::revert-model-snapshot-execute // tag::revert-model-snapshot-response ModelSnapshot modelSnapshot = response.getModel(); // <1> // end::revert-model-snapshot-response assertEquals(snapshotId, modelSnapshot.getSnapshotId()); assertEquals("State persisted due to job close at 2018-11-07T10:51:59+0000", modelSnapshot.getDescription()); assertEquals(51722, modelSnapshot.getModelSizeStats().getModelBytes()); } { RevertModelSnapshotRequest request = new RevertModelSnapshotRequest(jobId, snapshotId); // tag::revert-model-snapshot-execute-listener ActionListener<RevertModelSnapshotResponse> listener = new ActionListener<RevertModelSnapshotResponse>() { @Override public void onResponse(RevertModelSnapshotResponse revertModelSnapshotResponse) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::revert-model-snapshot-execute-listener // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::revert-model-snapshot-execute-async client.machineLearning().revertModelSnapshotAsync(request, RequestOptions.DEFAULT, listener); // <1> // end::revert-model-snapshot-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testUpdateModelSnapshot() throws IOException, InterruptedException { RestHighLevelClient client = highLevelClient(); String jobId = "test-update-model-snapshot"; String snapshotId = "1541587919"; String documentId = jobId + "_model_snapshot_" + snapshotId; Job job = MachineLearningIT.buildJob(jobId); client.machineLearning().putJob(new PutJobRequest(job), RequestOptions.DEFAULT); // Let us index a snapshot IndexRequest indexRequest = new IndexRequest(".ml-anomalies-shared").id(documentId); indexRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); indexRequest.source("{\"job_id\":\"test-update-model-snapshot\", \"timestamp\":1541587919000, " + "\"description\":\"State persisted due to job close at 2018-11-07T10:51:59+0000\", " + "\"snapshot_id\":\"1541587919\", \"snapshot_doc_count\":1, \"model_size_stats\":{" + "\"job_id\":\"test-update-model-snapshot\", \"result_type\":\"model_size_stats\",\"model_bytes\":51722, " + "\"total_by_field_count\":3, \"total_over_field_count\":0, \"total_partition_field_count\":2," + "\"bucket_allocation_failures_count\":0, \"memory_status\":\"ok\", \"log_time\":1541587919000, " + "\"timestamp\":1519930800000}, \"latest_record_time_stamp\":1519931700000," + "\"latest_result_time_stamp\":1519930800000, \"retain\":false}", XContentType.JSON); client.index(indexRequest, RequestOptions.DEFAULT); { // tag::update-model-snapshot-request UpdateModelSnapshotRequest request = new UpdateModelSnapshotRequest(jobId, snapshotId); // <1> // end::update-model-snapshot-request // tag::update-model-snapshot-description request.setDescription("My Snapshot"); // <1> // end::update-model-snapshot-description // tag::update-model-snapshot-retain request.setRetain(true); // <1> // end::update-model-snapshot-retain // tag::update-model-snapshot-execute UpdateModelSnapshotResponse response = client.machineLearning().updateModelSnapshot(request, RequestOptions.DEFAULT); // end::update-model-snapshot-execute // tag::update-model-snapshot-response boolean acknowledged = response.getAcknowledged(); // <1> ModelSnapshot modelSnapshot = response.getModel(); // <2> // end::update-model-snapshot-response assertTrue(acknowledged); assertEquals("My Snapshot", modelSnapshot.getDescription()); } { UpdateModelSnapshotRequest request = new UpdateModelSnapshotRequest(jobId, snapshotId); // tag::update-model-snapshot-execute-listener ActionListener<UpdateModelSnapshotResponse> listener = new ActionListener<UpdateModelSnapshotResponse>() { @Override public void onResponse(UpdateModelSnapshotResponse updateModelSnapshotResponse) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::update-model-snapshot-execute-listener // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::update-model-snapshot-execute-async client.machineLearning().updateModelSnapshotAsync(request, RequestOptions.DEFAULT, listener); // <1> // end::update-model-snapshot-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testPutCalendar() throws IOException, InterruptedException { RestHighLevelClient client = highLevelClient(); // tag::put-calendar-request Calendar calendar = new Calendar("public_holidays", Collections.singletonList("job_1"), "A calendar for public holidays"); PutCalendarRequest request = new PutCalendarRequest(calendar); // <1> // end::put-calendar-request // tag::put-calendar-execute PutCalendarResponse response = client.machineLearning().putCalendar(request, RequestOptions.DEFAULT); // end::put-calendar-execute // tag::put-calendar-response Calendar newCalendar = response.getCalendar(); // <1> // end::put-calendar-response assertThat(newCalendar.getId(), equalTo("public_holidays")); // tag::put-calendar-execute-listener ActionListener<PutCalendarResponse> listener = new ActionListener<PutCalendarResponse>() { @Override public void onResponse(PutCalendarResponse response) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::put-calendar-execute-listener // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::put-calendar-execute-async client.machineLearning().putCalendarAsync(request, RequestOptions.DEFAULT, listener); // <1> // end::put-calendar-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } public void testPutCalendarJob() throws IOException, InterruptedException { RestHighLevelClient client = highLevelClient(); Calendar calendar = new Calendar("holidays", Collections.singletonList("job_1"), "A calendar for public holidays"); PutCalendarRequest putRequest = new PutCalendarRequest(calendar); client.machineLearning().putCalendar(putRequest, RequestOptions.DEFAULT); { // tag::put-calendar-job-request PutCalendarJobRequest request = new PutCalendarJobRequest("holidays", // <1> "job_2", "job_group_1"); // <2> // end::put-calendar-job-request // tag::put-calendar-job-execute PutCalendarResponse response = client.machineLearning().putCalendarJob(request, RequestOptions.DEFAULT); // end::put-calendar-job-execute // tag::put-calendar-job-response Calendar updatedCalendar = response.getCalendar(); // <1> // end::put-calendar-job-response assertThat(updatedCalendar.getJobIds(), containsInAnyOrder("job_1", "job_2", "job_group_1")); } { PutCalendarJobRequest request = new PutCalendarJobRequest("holidays", "job_4"); // tag::put-calendar-job-execute-listener ActionListener<PutCalendarResponse> listener = new ActionListener<PutCalendarResponse>() { @Override public void onResponse(PutCalendarResponse putCalendarsResponse) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::put-calendar-job-execute-listener // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::put-calendar-job-execute-async client.machineLearning().putCalendarJobAsync(request, RequestOptions.DEFAULT, listener); // <1> // end::put-calendar-job-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testDeleteCalendarJob() throws IOException, InterruptedException { RestHighLevelClient client = highLevelClient(); Calendar calendar = new Calendar("holidays", Arrays.asList("job_1", "job_group_1", "job_2"), "A calendar for public holidays"); PutCalendarRequest putRequest = new PutCalendarRequest(calendar); client.machineLearning().putCalendar(putRequest, RequestOptions.DEFAULT); { // tag::delete-calendar-job-request DeleteCalendarJobRequest request = new DeleteCalendarJobRequest("holidays", // <1> "job_1", "job_group_1"); // <2> // end::delete-calendar-job-request // tag::delete-calendar-job-execute PutCalendarResponse response = client.machineLearning().deleteCalendarJob(request, RequestOptions.DEFAULT); // end::delete-calendar-job-execute // tag::delete-calendar-job-response Calendar updatedCalendar = response.getCalendar(); // <1> // end::delete-calendar-job-response assertThat(updatedCalendar.getJobIds(), containsInAnyOrder("job_2")); } { DeleteCalendarJobRequest request = new DeleteCalendarJobRequest("holidays", "job_2"); // tag::delete-calendar-job-execute-listener ActionListener<PutCalendarResponse> listener = new ActionListener<PutCalendarResponse>() { @Override public void onResponse(PutCalendarResponse deleteCalendarsResponse) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::delete-calendar-job-execute-listener // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::delete-calendar-job-execute-async client.machineLearning().deleteCalendarJobAsync(request, RequestOptions.DEFAULT, listener); // <1> // end::delete-calendar-job-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testGetCalendar() throws IOException, InterruptedException { RestHighLevelClient client = highLevelClient(); Calendar calendar = new Calendar("holidays", Collections.singletonList("job_1"), "A calendar for public holidays"); PutCalendarRequest putRequest = new PutCalendarRequest(calendar); client.machineLearning().putCalendar(putRequest, RequestOptions.DEFAULT); { // tag::get-calendars-request GetCalendarsRequest request = new GetCalendarsRequest(); // <1> // end::get-calendars-request // tag::get-calendars-id request.setCalendarId("holidays"); // <1> // end::get-calendars-id // tag::get-calendars-page request.setPageParams(new PageParams(10, 20)); // <1> // end::get-calendars-page // reset page params request.setPageParams(null); // tag::get-calendars-execute GetCalendarsResponse response = client.machineLearning().getCalendars(request, RequestOptions.DEFAULT); // end::get-calendars-execute // tag::get-calendars-response long count = response.count(); // <1> List<Calendar> calendars = response.calendars(); // <2> // end::get-calendars-response assertEquals(1, calendars.size()); } { GetCalendarsRequest request = new GetCalendarsRequest("holidays"); // tag::get-calendars-execute-listener ActionListener<GetCalendarsResponse> listener = new ActionListener<GetCalendarsResponse>() { @Override public void onResponse(GetCalendarsResponse getCalendarsResponse) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::get-calendars-execute-listener // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::get-calendars-execute-async client.machineLearning().getCalendarsAsync(request, RequestOptions.DEFAULT, listener); // <1> // end::get-calendars-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testDeleteCalendar() throws IOException, InterruptedException { RestHighLevelClient client = highLevelClient(); Calendar calendar = new Calendar("holidays", Collections.singletonList("job_1"), "A calendar for public holidays"); PutCalendarRequest putCalendarRequest = new PutCalendarRequest(calendar); client.machineLearning().putCalendar(putCalendarRequest, RequestOptions.DEFAULT); // tag::delete-calendar-request DeleteCalendarRequest request = new DeleteCalendarRequest("holidays"); // <1> // end::delete-calendar-request // tag::delete-calendar-execute AcknowledgedResponse response = client.machineLearning().deleteCalendar(request, RequestOptions.DEFAULT); // end::delete-calendar-execute // tag::delete-calendar-response boolean isAcknowledged = response.isAcknowledged(); // <1> // end::delete-calendar-response assertTrue(isAcknowledged); // tag::delete-calendar-execute-listener ActionListener<AcknowledgedResponse> listener = new ActionListener<AcknowledgedResponse>() { @Override public void onResponse(AcknowledgedResponse response) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::delete-calendar-execute-listener // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::delete-calendar-execute-async client.machineLearning().deleteCalendarAsync(request, RequestOptions.DEFAULT, listener); // <1> // end::delete-calendar-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } public void testGetCalendarEvent() throws IOException, InterruptedException { RestHighLevelClient client = highLevelClient(); Calendar calendar = new Calendar("holidays", Collections.singletonList("job_1"), "A calendar for public holidays"); PutCalendarRequest putRequest = new PutCalendarRequest(calendar); client.machineLearning().putCalendar(putRequest, RequestOptions.DEFAULT); List<ScheduledEvent> events = Collections.singletonList(ScheduledEventTests.testInstance(calendar.getId(), null)); client.machineLearning().postCalendarEvent(new PostCalendarEventRequest("holidays", events), RequestOptions.DEFAULT); { // tag::get-calendar-events-request GetCalendarEventsRequest request = new GetCalendarEventsRequest("holidays"); // <1> // end::get-calendar-events-request // tag::get-calendar-events-page request.setPageParams(new PageParams(10, 20)); // <1> // end::get-calendar-events-page // tag::get-calendar-events-start request.setStart("2018-08-01T00:00:00Z"); // <1> // end::get-calendar-events-start // tag::get-calendar-events-end request.setEnd("2018-08-02T00:00:00Z"); // <1> // end::get-calendar-events-end // tag::get-calendar-events-jobid request.setJobId("job_1"); // <1> // end::get-calendar-events-jobid // reset params request.setPageParams(null); request.setJobId(null); request.setStart(null); request.setEnd(null); // tag::get-calendar-events-execute GetCalendarEventsResponse response = client.machineLearning().getCalendarEvents(request, RequestOptions.DEFAULT); // end::get-calendar-events-execute // tag::get-calendar-events-response long count = response.count(); // <1> List<ScheduledEvent> scheduledEvents = response.events(); // <2> // end::get-calendar-events-response assertEquals(1, scheduledEvents.size()); } { GetCalendarEventsRequest request = new GetCalendarEventsRequest("holidays"); // tag::get-calendar-events-execute-listener ActionListener<GetCalendarEventsResponse> listener = new ActionListener<GetCalendarEventsResponse>() { @Override public void onResponse(GetCalendarEventsResponse getCalendarsResponse) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::get-calendar-events-execute-listener // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::get-calendar-events-execute-async client.machineLearning().getCalendarEventsAsync(request, RequestOptions.DEFAULT, listener); // <1> // end::get-calendar-events-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testPostCalendarEvent() throws IOException, InterruptedException { RestHighLevelClient client = highLevelClient(); Calendar calendar = new Calendar("holidays", Collections.singletonList("job_1"), "A calendar for public holidays"); PutCalendarRequest putRequest = new PutCalendarRequest(calendar); client.machineLearning().putCalendar(putRequest, RequestOptions.DEFAULT); { List<ScheduledEvent> events = Collections.singletonList(ScheduledEventTests.testInstance(calendar.getId(), null)); // tag::post-calendar-event-request PostCalendarEventRequest request = new PostCalendarEventRequest("holidays", // <1> events); // <2> // end::post-calendar-event-request // tag::post-calendar-event-execute PostCalendarEventResponse response = client.machineLearning().postCalendarEvent(request, RequestOptions.DEFAULT); // end::post-calendar-event-execute // tag::post-calendar-event-response List<ScheduledEvent> scheduledEvents = response.getScheduledEvents(); // <1> // end::post-calendar-event-response assertEquals(1, scheduledEvents.size()); } { List<ScheduledEvent> events = Collections.singletonList(ScheduledEventTests.testInstance()); PostCalendarEventRequest request = new PostCalendarEventRequest("holidays", events); // <1> // tag::post-calendar-event-execute-listener ActionListener<PostCalendarEventResponse> listener = new ActionListener<PostCalendarEventResponse>() { @Override public void onResponse(PostCalendarEventResponse postCalendarsResponse) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::post-calendar-event-execute-listener // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::post-calendar-event-execute-async client.machineLearning().postCalendarEventAsync(request, RequestOptions.DEFAULT, listener); // <1> // end::post-calendar-event-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testDeleteCalendarEvent() throws IOException, InterruptedException { RestHighLevelClient client = highLevelClient(); Calendar calendar = new Calendar("holidays", Arrays.asList("job_1", "job_group_1", "job_2"), "A calendar for public holidays"); PutCalendarRequest putRequest = new PutCalendarRequest(calendar); client.machineLearning().putCalendar(putRequest, RequestOptions.DEFAULT); List<ScheduledEvent> events = Arrays.asList(ScheduledEventTests.testInstance(calendar.getId(), null), ScheduledEventTests.testInstance(calendar.getId(), null)); client.machineLearning().postCalendarEvent(new PostCalendarEventRequest("holidays", events), RequestOptions.DEFAULT); GetCalendarEventsResponse getCalendarEventsResponse = client.machineLearning().getCalendarEvents(new GetCalendarEventsRequest("holidays"), RequestOptions.DEFAULT); { // tag::delete-calendar-event-request DeleteCalendarEventRequest request = new DeleteCalendarEventRequest("holidays", // <1> "EventId"); // <2> // end::delete-calendar-event-request request = new DeleteCalendarEventRequest("holidays", getCalendarEventsResponse.events().get(0).getEventId()); // tag::delete-calendar-event-execute AcknowledgedResponse response = client.machineLearning().deleteCalendarEvent(request, RequestOptions.DEFAULT); // end::delete-calendar-event-execute // tag::delete-calendar-event-response boolean acknowledged = response.isAcknowledged(); // <1> // end::delete-calendar-event-response assertThat(acknowledged, is(true)); } { DeleteCalendarEventRequest request = new DeleteCalendarEventRequest("holidays", getCalendarEventsResponse.events().get(1).getEventId()); // tag::delete-calendar-event-execute-listener ActionListener<AcknowledgedResponse> listener = new ActionListener<AcknowledgedResponse>() { @Override public void onResponse(AcknowledgedResponse deleteCalendarEventResponse) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::delete-calendar-event-execute-listener // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::delete-calendar-event-execute-async client.machineLearning().deleteCalendarEventAsync(request, RequestOptions.DEFAULT, listener); // <1> // end::delete-calendar-event-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testGetDataFrameAnalytics() throws Exception { createIndex(DF_ANALYTICS_CONFIG.getSource().getIndex()[0]); RestHighLevelClient client = highLevelClient(); client.machineLearning().putDataFrameAnalytics(new PutDataFrameAnalyticsRequest(DF_ANALYTICS_CONFIG), RequestOptions.DEFAULT); { // tag::get-data-frame-analytics-request GetDataFrameAnalyticsRequest request = new GetDataFrameAnalyticsRequest("my-analytics-config"); // <1> // end::get-data-frame-analytics-request // tag::get-data-frame-analytics-execute GetDataFrameAnalyticsResponse response = client.machineLearning().getDataFrameAnalytics(request, RequestOptions.DEFAULT); // end::get-data-frame-analytics-execute // tag::get-data-frame-analytics-response List<DataFrameAnalyticsConfig> configs = response.getAnalytics(); // end::get-data-frame-analytics-response assertThat(configs, hasSize(1)); } { GetDataFrameAnalyticsRequest request = new GetDataFrameAnalyticsRequest("my-analytics-config"); // tag::get-data-frame-analytics-execute-listener ActionListener<GetDataFrameAnalyticsResponse> listener = new ActionListener<>() { @Override public void onResponse(GetDataFrameAnalyticsResponse response) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::get-data-frame-analytics-execute-listener // Replace the empty listener by a blocking listener in test CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::get-data-frame-analytics-execute-async client.machineLearning().getDataFrameAnalyticsAsync(request, RequestOptions.DEFAULT, listener); // <1> // end::get-data-frame-analytics-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testGetDataFrameAnalyticsStats() throws Exception { createIndex(DF_ANALYTICS_CONFIG.getSource().getIndex()[0]); RestHighLevelClient client = highLevelClient(); client.machineLearning().putDataFrameAnalytics(new PutDataFrameAnalyticsRequest(DF_ANALYTICS_CONFIG), RequestOptions.DEFAULT); { // tag::get-data-frame-analytics-stats-request GetDataFrameAnalyticsStatsRequest request = new GetDataFrameAnalyticsStatsRequest("my-analytics-config"); // <1> // end::get-data-frame-analytics-stats-request // tag::get-data-frame-analytics-stats-execute GetDataFrameAnalyticsStatsResponse response = client.machineLearning().getDataFrameAnalyticsStats(request, RequestOptions.DEFAULT); // end::get-data-frame-analytics-stats-execute // tag::get-data-frame-analytics-stats-response List<DataFrameAnalyticsStats> stats = response.getAnalyticsStats(); // end::get-data-frame-analytics-stats-response assertThat(stats, hasSize(1)); } { GetDataFrameAnalyticsStatsRequest request = new GetDataFrameAnalyticsStatsRequest("my-analytics-config"); // tag::get-data-frame-analytics-stats-execute-listener ActionListener<GetDataFrameAnalyticsStatsResponse> listener = new ActionListener<>() { @Override public void onResponse(GetDataFrameAnalyticsStatsResponse response) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::get-data-frame-analytics-stats-execute-listener // Replace the empty listener by a blocking listener in test CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::get-data-frame-analytics-stats-execute-async client.machineLearning().getDataFrameAnalyticsStatsAsync(request, RequestOptions.DEFAULT, listener); // <1> // end::get-data-frame-analytics-stats-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testPutDataFrameAnalytics() throws Exception { createIndex(DF_ANALYTICS_CONFIG.getSource().getIndex()[0]); RestHighLevelClient client = highLevelClient(); { // tag::put-data-frame-analytics-query-config QueryConfig queryConfig = new QueryConfig(new MatchAllQueryBuilder()); // end::put-data-frame-analytics-query-config // tag::put-data-frame-analytics-source-config DataFrameAnalyticsSource sourceConfig = DataFrameAnalyticsSource.builder() // <1> .setIndex("put-test-source-index") // <2> .setQueryConfig(queryConfig) // <3> .setSourceFiltering(new FetchSourceContext(true, new String[] { "included_field_1", "included_field_2" }, new String[] { "excluded_field" })) // <4> .build(); // end::put-data-frame-analytics-source-config // tag::put-data-frame-analytics-dest-config DataFrameAnalyticsDest destConfig = DataFrameAnalyticsDest.builder() // <1> .setIndex("put-test-dest-index") // <2> .build(); // end::put-data-frame-analytics-dest-config // tag::put-data-frame-analytics-outlier-detection-default DataFrameAnalysis outlierDetection = OutlierDetection.createDefault(); // <1> // end::put-data-frame-analytics-outlier-detection-default // tag::put-data-frame-analytics-outlier-detection-customized DataFrameAnalysis outlierDetectionCustomized = OutlierDetection.builder() // <1> .setMethod(OutlierDetection.Method.DISTANCE_KNN) // <2> .setNNeighbors(5) // <3> .setFeatureInfluenceThreshold(0.1) // <4> .setComputeFeatureInfluence(true) // <5> .setOutlierFraction(0.05) // <6> .setStandardizationEnabled(true) // <7> .build(); // end::put-data-frame-analytics-outlier-detection-customized // tag::put-data-frame-analytics-classification DataFrameAnalysis classification = Classification.builder("my_dependent_variable") // <1> .setLambda(1.0) // <2> .setGamma(5.5) // <3> .setEta(5.5) // <4> .setMaxTrees(50) // <5> .setFeatureBagFraction(0.4) // <6> .setNumTopFeatureImportanceValues(3) // <7> .setPredictionFieldName("my_prediction_field_name") // <8> .setTrainingPercent(50.0) // <9> .setRandomizeSeed(1234L) // <10> .setClassAssignmentObjective(Classification.ClassAssignmentObjective.MAXIMIZE_ACCURACY) // <11> .setNumTopClasses(1) // <12> .build(); // end::put-data-frame-analytics-classification // tag::put-data-frame-analytics-regression DataFrameAnalysis regression = org.elasticsearch.client.ml.dataframe.Regression.builder("my_dependent_variable") // <1> .setLambda(1.0) // <2> .setGamma(5.5) // <3> .setEta(5.5) // <4> .setMaxTrees(50) // <5> .setFeatureBagFraction(0.4) // <6> .setNumTopFeatureImportanceValues(3) // <7> .setPredictionFieldName("my_prediction_field_name") // <8> .setTrainingPercent(50.0) // <9> .setRandomizeSeed(1234L) // <10> .setLossFunction(Regression.LossFunction.MSE) // <11> .setLossFunctionParameter(1.0) // <12> .build(); // end::put-data-frame-analytics-regression // tag::put-data-frame-analytics-analyzed-fields FetchSourceContext analyzedFields = new FetchSourceContext( true, new String[] { "included_field_1", "included_field_2" }, new String[] { "excluded_field" }); // end::put-data-frame-analytics-analyzed-fields // tag::put-data-frame-analytics-config DataFrameAnalyticsConfig config = DataFrameAnalyticsConfig.builder() .setId("my-analytics-config") // <1> .setSource(sourceConfig) // <2> .setDest(destConfig) // <3> .setAnalysis(outlierDetection) // <4> .setAnalyzedFields(analyzedFields) // <5> .setModelMemoryLimit(new ByteSizeValue(5, ByteSizeUnit.MB)) // <6> .setDescription("this is an example description") // <7> .build(); // end::put-data-frame-analytics-config // tag::put-data-frame-analytics-request PutDataFrameAnalyticsRequest request = new PutDataFrameAnalyticsRequest(config); // <1> // end::put-data-frame-analytics-request // tag::put-data-frame-analytics-execute PutDataFrameAnalyticsResponse response = client.machineLearning().putDataFrameAnalytics(request, RequestOptions.DEFAULT); // end::put-data-frame-analytics-execute // tag::put-data-frame-analytics-response DataFrameAnalyticsConfig createdConfig = response.getConfig(); // end::put-data-frame-analytics-response assertThat(createdConfig.getId(), equalTo("my-analytics-config")); } { PutDataFrameAnalyticsRequest request = new PutDataFrameAnalyticsRequest(DF_ANALYTICS_CONFIG); // tag::put-data-frame-analytics-execute-listener ActionListener<PutDataFrameAnalyticsResponse> listener = new ActionListener<>() { @Override public void onResponse(PutDataFrameAnalyticsResponse response) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::put-data-frame-analytics-execute-listener // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::put-data-frame-analytics-execute-async client.machineLearning().putDataFrameAnalyticsAsync(request, RequestOptions.DEFAULT, listener); // <1> // end::put-data-frame-analytics-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testDeleteDataFrameAnalytics() throws Exception { createIndex(DF_ANALYTICS_CONFIG.getSource().getIndex()[0]); RestHighLevelClient client = highLevelClient(); client.machineLearning().putDataFrameAnalytics(new PutDataFrameAnalyticsRequest(DF_ANALYTICS_CONFIG), RequestOptions.DEFAULT); { // tag::delete-data-frame-analytics-request DeleteDataFrameAnalyticsRequest request = new DeleteDataFrameAnalyticsRequest("my-analytics-config"); // <1> // end::delete-data-frame-analytics-request //tag::delete-data-frame-analytics-request-options request.setForce(false); // <1> request.setTimeout(TimeValue.timeValueMinutes(1)); // <2> //end::delete-data-frame-analytics-request-options // tag::delete-data-frame-analytics-execute AcknowledgedResponse response = client.machineLearning().deleteDataFrameAnalytics(request, RequestOptions.DEFAULT); // end::delete-data-frame-analytics-execute // tag::delete-data-frame-analytics-response boolean acknowledged = response.isAcknowledged(); // end::delete-data-frame-analytics-response assertThat(acknowledged, is(true)); } client.machineLearning().putDataFrameAnalytics(new PutDataFrameAnalyticsRequest(DF_ANALYTICS_CONFIG), RequestOptions.DEFAULT); { DeleteDataFrameAnalyticsRequest request = new DeleteDataFrameAnalyticsRequest("my-analytics-config"); // tag::delete-data-frame-analytics-execute-listener ActionListener<AcknowledgedResponse> listener = new ActionListener<>() { @Override public void onResponse(AcknowledgedResponse response) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::delete-data-frame-analytics-execute-listener // Replace the empty listener by a blocking listener in test CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::delete-data-frame-analytics-execute-async client.machineLearning().deleteDataFrameAnalyticsAsync(request, RequestOptions.DEFAULT, listener); // <1> // end::delete-data-frame-analytics-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testStartDataFrameAnalytics() throws Exception { createIndex(DF_ANALYTICS_CONFIG.getSource().getIndex()[0]); highLevelClient().index( new IndexRequest(DF_ANALYTICS_CONFIG.getSource().getIndex()[0]).source(XContentType.JSON, "total", 10000) .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE), RequestOptions.DEFAULT); RestHighLevelClient client = highLevelClient(); client.machineLearning().putDataFrameAnalytics(new PutDataFrameAnalyticsRequest(DF_ANALYTICS_CONFIG), RequestOptions.DEFAULT); { // tag::start-data-frame-analytics-request StartDataFrameAnalyticsRequest request = new StartDataFrameAnalyticsRequest("my-analytics-config"); // <1> // end::start-data-frame-analytics-request // tag::start-data-frame-analytics-execute StartDataFrameAnalyticsResponse response = client.machineLearning().startDataFrameAnalytics(request, RequestOptions.DEFAULT); // end::start-data-frame-analytics-execute // tag::start-data-frame-analytics-response boolean acknowledged = response.isAcknowledged(); String node = response.getNode(); // <1> // end::start-data-frame-analytics-response assertThat(acknowledged, is(true)); assertThat(node, notNullValue()); } assertBusy( () -> assertThat(getAnalyticsState(DF_ANALYTICS_CONFIG.getId()), equalTo(DataFrameAnalyticsState.STOPPED)), 30, TimeUnit.SECONDS); { StartDataFrameAnalyticsRequest request = new StartDataFrameAnalyticsRequest("my-analytics-config"); // tag::start-data-frame-analytics-execute-listener ActionListener<StartDataFrameAnalyticsResponse> listener = new ActionListener<>() { @Override public void onResponse(StartDataFrameAnalyticsResponse response) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::start-data-frame-analytics-execute-listener // Replace the empty listener by a blocking listener in test CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::start-data-frame-analytics-execute-async client.machineLearning().startDataFrameAnalyticsAsync(request, RequestOptions.DEFAULT, listener); // <1> // end::start-data-frame-analytics-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } assertBusy( () -> assertThat(getAnalyticsState(DF_ANALYTICS_CONFIG.getId()), equalTo(DataFrameAnalyticsState.STOPPED)), 30, TimeUnit.SECONDS); } public void testStopDataFrameAnalytics() throws Exception { createIndex(DF_ANALYTICS_CONFIG.getSource().getIndex()[0]); highLevelClient().index( new IndexRequest(DF_ANALYTICS_CONFIG.getSource().getIndex()[0]).source(XContentType.JSON, "total", 10000) .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE), RequestOptions.DEFAULT); RestHighLevelClient client = highLevelClient(); client.machineLearning().putDataFrameAnalytics(new PutDataFrameAnalyticsRequest(DF_ANALYTICS_CONFIG), RequestOptions.DEFAULT); { // tag::stop-data-frame-analytics-request StopDataFrameAnalyticsRequest request = new StopDataFrameAnalyticsRequest("my-analytics-config"); // <1> request.setForce(false); // <2> // end::stop-data-frame-analytics-request // tag::stop-data-frame-analytics-execute StopDataFrameAnalyticsResponse response = client.machineLearning().stopDataFrameAnalytics(request, RequestOptions.DEFAULT); // end::stop-data-frame-analytics-execute // tag::stop-data-frame-analytics-response boolean acknowledged = response.isStopped(); // end::stop-data-frame-analytics-response assertThat(acknowledged, is(true)); } assertBusy( () -> assertThat(getAnalyticsState(DF_ANALYTICS_CONFIG.getId()), equalTo(DataFrameAnalyticsState.STOPPED)), 30, TimeUnit.SECONDS); { StopDataFrameAnalyticsRequest request = new StopDataFrameAnalyticsRequest("my-analytics-config"); // tag::stop-data-frame-analytics-execute-listener ActionListener<StopDataFrameAnalyticsResponse> listener = new ActionListener<>() { @Override public void onResponse(StopDataFrameAnalyticsResponse response) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::stop-data-frame-analytics-execute-listener // Replace the empty listener by a blocking listener in test CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::stop-data-frame-analytics-execute-async client.machineLearning().stopDataFrameAnalyticsAsync(request, RequestOptions.DEFAULT, listener); // <1> // end::stop-data-frame-analytics-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } assertBusy( () -> assertThat(getAnalyticsState(DF_ANALYTICS_CONFIG.getId()), equalTo(DataFrameAnalyticsState.STOPPED)), 30, TimeUnit.SECONDS); } public void testEvaluateDataFrame() throws Exception { String indexName = "evaluate-test-index"; CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName) .mapping(XContentFactory.jsonBuilder().startObject() .startObject("properties") .startObject("label") .field("type", "keyword") .endObject() .startObject("p") .field("type", "double") .endObject() .endObject() .endObject()); BulkRequest bulkRequest = new BulkRequest(indexName) .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE) .add(new IndexRequest().source(XContentType.JSON, "dataset", "blue", "label", false, "p", 0.1)) // #0 .add(new IndexRequest().source(XContentType.JSON, "dataset", "blue", "label", false, "p", 0.2)) // #1 .add(new IndexRequest().source(XContentType.JSON, "dataset", "blue", "label", false, "p", 0.3)) // #2 .add(new IndexRequest().source(XContentType.JSON, "dataset", "blue", "label", false, "p", 0.4)) // #3 .add(new IndexRequest().source(XContentType.JSON, "dataset", "blue", "label", false, "p", 0.7)) // #4 .add(new IndexRequest().source(XContentType.JSON, "dataset", "blue", "label", true, "p", 0.2)) // #5 .add(new IndexRequest().source(XContentType.JSON, "dataset", "blue", "label", true, "p", 0.3)) // #6 .add(new IndexRequest().source(XContentType.JSON, "dataset", "blue", "label", true, "p", 0.4)) // #7 .add(new IndexRequest().source(XContentType.JSON, "dataset", "blue", "label", true, "p", 0.8)) // #8 .add(new IndexRequest().source(XContentType.JSON, "dataset", "blue", "label", true, "p", 0.9)); // #9 RestHighLevelClient client = highLevelClient(); client.indices().create(createIndexRequest, RequestOptions.DEFAULT); client.bulk(bulkRequest, RequestOptions.DEFAULT); { // tag::evaluate-data-frame-evaluation-softclassification Evaluation evaluation = new BinarySoftClassification( // <1> "label", // <2> "p", // <3> // Evaluation metrics // <4> PrecisionMetric.at(0.4, 0.5, 0.6), // <5> RecallMetric.at(0.5, 0.7), // <6> ConfusionMatrixMetric.at(0.5), // <7> AucRocMetric.withCurve()); // <8> // end::evaluate-data-frame-evaluation-softclassification // tag::evaluate-data-frame-request EvaluateDataFrameRequest request = new EvaluateDataFrameRequest( // <1> indexName, // <2> new QueryConfig(QueryBuilders.termQuery("dataset", "blue")), // <3> evaluation); // <4> // end::evaluate-data-frame-request // tag::evaluate-data-frame-execute EvaluateDataFrameResponse response = client.machineLearning().evaluateDataFrame(request, RequestOptions.DEFAULT); // end::evaluate-data-frame-execute // tag::evaluate-data-frame-response List<EvaluationMetric.Result> metrics = response.getMetrics(); // <1> // end::evaluate-data-frame-response // tag::evaluate-data-frame-results-softclassification PrecisionMetric.Result precisionResult = response.getMetricByName(PrecisionMetric.NAME); // <1> double precision = precisionResult.getScoreByThreshold("0.4"); // <2> ConfusionMatrixMetric.Result confusionMatrixResult = response.getMetricByName(ConfusionMatrixMetric.NAME); // <3> ConfusionMatrix confusionMatrix = confusionMatrixResult.getScoreByThreshold("0.5"); // <4> // end::evaluate-data-frame-results-softclassification assertThat( metrics.stream().map(EvaluationMetric.Result::getMetricName).collect(Collectors.toList()), containsInAnyOrder(PrecisionMetric.NAME, RecallMetric.NAME, ConfusionMatrixMetric.NAME, AucRocMetric.NAME)); assertThat(precision, closeTo(0.6, 1e-9)); assertThat(confusionMatrix.getTruePositives(), equalTo(2L)); // docs #8 and #9 assertThat(confusionMatrix.getFalsePositives(), equalTo(1L)); // doc #4 assertThat(confusionMatrix.getTrueNegatives(), equalTo(4L)); // docs #0, #1, #2 and #3 assertThat(confusionMatrix.getFalseNegatives(), equalTo(3L)); // docs #5, #6 and #7 } { EvaluateDataFrameRequest request = new EvaluateDataFrameRequest( indexName, new QueryConfig(QueryBuilders.termQuery("dataset", "blue")), new BinarySoftClassification( "label", "p", PrecisionMetric.at(0.4, 0.5, 0.6), RecallMetric.at(0.5, 0.7), ConfusionMatrixMetric.at(0.5), AucRocMetric.withCurve())); // tag::evaluate-data-frame-execute-listener ActionListener<EvaluateDataFrameResponse> listener = new ActionListener<>() { @Override public void onResponse(EvaluateDataFrameResponse response) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::evaluate-data-frame-execute-listener // Replace the empty listener by a blocking listener in test CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::evaluate-data-frame-execute-async client.machineLearning().evaluateDataFrameAsync(request, RequestOptions.DEFAULT, listener); // <1> // end::evaluate-data-frame-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testEvaluateDataFrame_Classification() throws Exception { String indexName = "evaluate-classification-test-index"; CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName) .mapping(XContentFactory.jsonBuilder().startObject() .startObject("properties") .startObject("actual_class") .field("type", "keyword") .endObject() .startObject("predicted_class") .field("type", "keyword") .endObject() .endObject() .endObject()); BulkRequest bulkRequest = new BulkRequest(indexName) .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE) .add(new IndexRequest().source(XContentType.JSON, "actual_class", "cat", "predicted_class", "cat")) // #0 .add(new IndexRequest().source(XContentType.JSON, "actual_class", "cat", "predicted_class", "cat")) // #1 .add(new IndexRequest().source(XContentType.JSON, "actual_class", "cat", "predicted_class", "cat")) // #2 .add(new IndexRequest().source(XContentType.JSON, "actual_class", "cat", "predicted_class", "dog")) // #3 .add(new IndexRequest().source(XContentType.JSON, "actual_class", "cat", "predicted_class", "fox")) // #4 .add(new IndexRequest().source(XContentType.JSON, "actual_class", "dog", "predicted_class", "cat")) // #5 .add(new IndexRequest().source(XContentType.JSON, "actual_class", "dog", "predicted_class", "dog")) // #6 .add(new IndexRequest().source(XContentType.JSON, "actual_class", "dog", "predicted_class", "dog")) // #7 .add(new IndexRequest().source(XContentType.JSON, "actual_class", "dog", "predicted_class", "dog")) // #8 .add(new IndexRequest().source(XContentType.JSON, "actual_class", "ant", "predicted_class", "cat")); // #9 RestHighLevelClient client = highLevelClient(); client.indices().create(createIndexRequest, RequestOptions.DEFAULT); client.bulk(bulkRequest, RequestOptions.DEFAULT); { // tag::evaluate-data-frame-evaluation-classification Evaluation evaluation = new org.elasticsearch.client.ml.dataframe.evaluation.classification.Classification( // <1> "actual_class", // <2> "predicted_class", // <3> // Evaluation metrics // <4> new AccuracyMetric(), // <5> new org.elasticsearch.client.ml.dataframe.evaluation.classification.PrecisionMetric(), // <6> new org.elasticsearch.client.ml.dataframe.evaluation.classification.RecallMetric(), // <7> new MulticlassConfusionMatrixMetric(3)); // <8> // end::evaluate-data-frame-evaluation-classification EvaluateDataFrameRequest request = new EvaluateDataFrameRequest(indexName, null, evaluation); EvaluateDataFrameResponse response = client.machineLearning().evaluateDataFrame(request, RequestOptions.DEFAULT); // tag::evaluate-data-frame-results-classification AccuracyMetric.Result accuracyResult = response.getMetricByName(AccuracyMetric.NAME); // <1> double accuracy = accuracyResult.getOverallAccuracy(); // <2> org.elasticsearch.client.ml.dataframe.evaluation.classification.PrecisionMetric.Result precisionResult = response.getMetricByName(org.elasticsearch.client.ml.dataframe.evaluation.classification.PrecisionMetric.NAME); // <3> double precision = precisionResult.getAvgPrecision(); // <4> org.elasticsearch.client.ml.dataframe.evaluation.classification.RecallMetric.Result recallResult = response.getMetricByName(org.elasticsearch.client.ml.dataframe.evaluation.classification.RecallMetric.NAME); // <5> double recall = recallResult.getAvgRecall(); // <6> MulticlassConfusionMatrixMetric.Result multiclassConfusionMatrix = response.getMetricByName(MulticlassConfusionMatrixMetric.NAME); // <7> List<ActualClass> confusionMatrix = multiclassConfusionMatrix.getConfusionMatrix(); // <8> long otherClassesCount = multiclassConfusionMatrix.getOtherActualClassCount(); // <9> // end::evaluate-data-frame-results-classification assertThat(accuracyResult.getMetricName(), equalTo(AccuracyMetric.NAME)); assertThat(accuracy, equalTo(0.6)); assertThat( precisionResult.getMetricName(), equalTo(org.elasticsearch.client.ml.dataframe.evaluation.classification.PrecisionMetric.NAME)); assertThat(precision, equalTo(0.675)); assertThat( recallResult.getMetricName(), equalTo(org.elasticsearch.client.ml.dataframe.evaluation.classification.RecallMetric.NAME)); assertThat(recall, equalTo(0.45)); assertThat(multiclassConfusionMatrix.getMetricName(), equalTo(MulticlassConfusionMatrixMetric.NAME)); assertThat( confusionMatrix, equalTo( List.of( new ActualClass( "ant", 1L, List.of(new PredictedClass("ant", 0L), new PredictedClass("cat", 1L), new PredictedClass("dog", 0L)), 0L), new ActualClass( "cat", 5L, List.of(new PredictedClass("ant", 0L), new PredictedClass("cat", 3L), new PredictedClass("dog", 1L)), 1L), new ActualClass( "dog", 4L, List.of(new PredictedClass("ant", 0L), new PredictedClass("cat", 1L), new PredictedClass("dog", 3L)), 0L)))); assertThat(otherClassesCount, equalTo(0L)); } } public void testEvaluateDataFrame_Regression() throws Exception { String indexName = "evaluate-classification-test-index"; CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName) .mapping(XContentFactory.jsonBuilder().startObject() .startObject("properties") .startObject("actual_value") .field("type", "double") .endObject() .startObject("predicted_value") .field("type", "double") .endObject() .endObject() .endObject()); BulkRequest bulkRequest = new BulkRequest(indexName) .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE) .add(new IndexRequest().source(XContentType.JSON, "actual_value", 1.0, "predicted_value", 1.0)) // #0 .add(new IndexRequest().source(XContentType.JSON, "actual_value", 1.0, "predicted_value", 0.9)) // #1 .add(new IndexRequest().source(XContentType.JSON, "actual_value", 2.0, "predicted_value", 2.0)) // #2 .add(new IndexRequest().source(XContentType.JSON, "actual_value", 1.5, "predicted_value", 1.4)) // #3 .add(new IndexRequest().source(XContentType.JSON, "actual_value", 1.2, "predicted_value", 1.3)) // #4 .add(new IndexRequest().source(XContentType.JSON, "actual_value", 1.7, "predicted_value", 2.0)) // #5 .add(new IndexRequest().source(XContentType.JSON, "actual_value", 2.1, "predicted_value", 2.1)) // #6 .add(new IndexRequest().source(XContentType.JSON, "actual_value", 2.5, "predicted_value", 2.7)) // #7 .add(new IndexRequest().source(XContentType.JSON, "actual_value", 0.8, "predicted_value", 1.0)) // #8 .add(new IndexRequest().source(XContentType.JSON, "actual_value", 2.5, "predicted_value", 2.4)); // #9 RestHighLevelClient client = highLevelClient(); client.indices().create(createIndexRequest, RequestOptions.DEFAULT); client.bulk(bulkRequest, RequestOptions.DEFAULT); { // tag::evaluate-data-frame-evaluation-regression Evaluation evaluation = new org.elasticsearch.client.ml.dataframe.evaluation.regression.Regression( // <1> "actual_value", // <2> "predicted_value", // <3> // Evaluation metrics // <4> new MeanSquaredErrorMetric(), // <5> new RSquaredMetric()); // <6> // end::evaluate-data-frame-evaluation-regression EvaluateDataFrameRequest request = new EvaluateDataFrameRequest(indexName, null, evaluation); EvaluateDataFrameResponse response = client.machineLearning().evaluateDataFrame(request, RequestOptions.DEFAULT); // tag::evaluate-data-frame-results-regression MeanSquaredErrorMetric.Result meanSquaredErrorResult = response.getMetricByName(MeanSquaredErrorMetric.NAME); // <1> double meanSquaredError = meanSquaredErrorResult.getError(); // <2> RSquaredMetric.Result rSquaredResult = response.getMetricByName(RSquaredMetric.NAME); // <3> double rSquared = rSquaredResult.getValue(); // <4> // end::evaluate-data-frame-results-regression assertThat(meanSquaredError, closeTo(0.021, 1e-3)); assertThat(rSquared, closeTo(0.941, 1e-3)); } } public void testExplainDataFrameAnalytics() throws Exception { createIndex("explain-df-test-source-index"); BulkRequest bulkRequest = new BulkRequest("explain-df-test-source-index") .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); for (int i = 0; i < 10; ++i) { bulkRequest.add(new IndexRequest().source(XContentType.JSON, "timestamp", 123456789L, "total", 10L)); } RestHighLevelClient client = highLevelClient(); client.bulk(bulkRequest, RequestOptions.DEFAULT); { // tag::explain-data-frame-analytics-id-request ExplainDataFrameAnalyticsRequest request = new ExplainDataFrameAnalyticsRequest("existing_job_id"); // <1> // end::explain-data-frame-analytics-id-request // tag::explain-data-frame-analytics-config-request DataFrameAnalyticsConfig config = DataFrameAnalyticsConfig.builder() .setSource(DataFrameAnalyticsSource.builder().setIndex("explain-df-test-source-index").build()) .setAnalysis(OutlierDetection.createDefault()) .build(); request = new ExplainDataFrameAnalyticsRequest(config); // <1> // end::explain-data-frame-analytics-config-request // tag::explain-data-frame-analytics-execute ExplainDataFrameAnalyticsResponse response = client.machineLearning().explainDataFrameAnalytics(request, RequestOptions.DEFAULT); // end::explain-data-frame-analytics-execute // tag::explain-data-frame-analytics-response List<FieldSelection> fieldSelection = response.getFieldSelection(); // <1> MemoryEstimation memoryEstimation = response.getMemoryEstimation(); // <2> // end::explain-data-frame-analytics-response assertThat(fieldSelection.size(), equalTo(2)); assertThat(fieldSelection.stream().map(FieldSelection::getName).collect(Collectors.toList()), contains("timestamp", "total")); ByteSizeValue expectedMemoryWithoutDisk = memoryEstimation.getExpectedMemoryWithoutDisk(); // <1> ByteSizeValue expectedMemoryWithDisk = memoryEstimation.getExpectedMemoryWithDisk(); // <2> // We are pretty liberal here as this test does not aim at verifying concrete numbers but rather end-to-end user workflow. ByteSizeValue lowerBound = new ByteSizeValue(1, ByteSizeUnit.KB); ByteSizeValue upperBound = new ByteSizeValue(1, ByteSizeUnit.GB); assertThat(expectedMemoryWithoutDisk, allOf(greaterThan(lowerBound), lessThan(upperBound))); assertThat(expectedMemoryWithDisk, allOf(greaterThan(lowerBound), lessThan(upperBound))); } { DataFrameAnalyticsConfig config = DataFrameAnalyticsConfig.builder() .setSource(DataFrameAnalyticsSource.builder().setIndex("explain-df-test-source-index").build()) .setAnalysis(OutlierDetection.createDefault()) .build(); ExplainDataFrameAnalyticsRequest request = new ExplainDataFrameAnalyticsRequest(config); // tag::explain-data-frame-analytics-execute-listener ActionListener<ExplainDataFrameAnalyticsResponse> listener = new ActionListener<>() { @Override public void onResponse(ExplainDataFrameAnalyticsResponse response) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::explain-data-frame-analytics-execute-listener // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::explain-data-frame-analytics-execute-async client.machineLearning().explainDataFrameAnalyticsAsync(request, RequestOptions.DEFAULT, listener); // <1> // end::explain-data-frame-analytics-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testGetTrainedModels() throws Exception { putTrainedModel("my-trained-model"); RestHighLevelClient client = highLevelClient(); { // tag::get-trained-models-request GetTrainedModelsRequest request = new GetTrainedModelsRequest("my-trained-model") // <1> .setPageParams(new PageParams(0, 1)) // <2> .setIncludeDefinition(false) // <3> .setDecompressDefinition(false) // <4> .setAllowNoMatch(true) // <5> .setTags("regression") // <6> .setForExport(false); // <7> // end::get-trained-models-request request.setTags((List<String>)null); // tag::get-trained-models-execute GetTrainedModelsResponse response = client.machineLearning().getTrainedModels(request, RequestOptions.DEFAULT); // end::get-trained-models-execute // tag::get-trained-models-response List<TrainedModelConfig> models = response.getTrainedModels(); // end::get-trained-models-response assertThat(models, hasSize(1)); } { GetTrainedModelsRequest request = new GetTrainedModelsRequest("my-trained-model"); // tag::get-trained-models-execute-listener ActionListener<GetTrainedModelsResponse> listener = new ActionListener<>() { @Override public void onResponse(GetTrainedModelsResponse response) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::get-trained-models-execute-listener // Replace the empty listener by a blocking listener in test CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::get-trained-models-execute-async client.machineLearning().getTrainedModelsAsync(request, RequestOptions.DEFAULT, listener); // <1> // end::get-trained-models-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testPutTrainedModel() throws Exception { TrainedModelDefinition definition = TrainedModelDefinitionTests.createRandomBuilder(TargetType.REGRESSION).build(); // tag::put-trained-model-config TrainedModelConfig trainedModelConfig = TrainedModelConfig.builder() .setDefinition(definition) // <1> .setCompressedDefinition(InferenceToXContentCompressor.deflate(definition)) // <2> .setModelId("my-new-trained-model") // <3> .setInput(new TrainedModelInput("col1", "col2", "col3", "col4")) // <4> .setDescription("test model") // <5> .setMetadata(new HashMap<>()) // <6> .setTags("my_regression_models") // <7> .setInferenceConfig(new RegressionConfig("value", 0)) // <8> .build(); // end::put-trained-model-config trainedModelConfig = TrainedModelConfig.builder() .setDefinition(definition) .setInferenceConfig(new RegressionConfig(null, null)) .setModelId("my-new-trained-model") .setInput(new TrainedModelInput("col1", "col2", "col3", "col4")) .setDescription("test model") .setMetadata(new HashMap<>()) .setTags("my_regression_models") .build(); RestHighLevelClient client = highLevelClient(); { // tag::put-trained-model-request PutTrainedModelRequest request = new PutTrainedModelRequest(trainedModelConfig); // <1> // end::put-trained-model-request // tag::put-trained-model-execute PutTrainedModelResponse response = client.machineLearning().putTrainedModel(request, RequestOptions.DEFAULT); // end::put-trained-model-execute // tag::put-trained-model-response TrainedModelConfig model = response.getResponse(); // end::put-trained-model-response assertThat(model.getModelId(), equalTo(trainedModelConfig.getModelId())); highLevelClient().machineLearning() .deleteTrainedModel(new DeleteTrainedModelRequest("my-new-trained-model"), RequestOptions.DEFAULT); } { PutTrainedModelRequest request = new PutTrainedModelRequest(trainedModelConfig); // tag::put-trained-model-execute-listener ActionListener<PutTrainedModelResponse> listener = new ActionListener<>() { @Override public void onResponse(PutTrainedModelResponse response) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::put-trained-model-execute-listener // Replace the empty listener by a blocking listener in test CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::put-trained-model-execute-async client.machineLearning().putTrainedModelAsync(request, RequestOptions.DEFAULT, listener); // <1> // end::put-trained-model-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); highLevelClient().machineLearning() .deleteTrainedModel(new DeleteTrainedModelRequest("my-new-trained-model"), RequestOptions.DEFAULT); } } public void testGetTrainedModelsStats() throws Exception { putTrainedModel("my-trained-model"); RestHighLevelClient client = highLevelClient(); { // tag::get-trained-models-stats-request GetTrainedModelsStatsRequest request = new GetTrainedModelsStatsRequest("my-trained-model") // <1> .setPageParams(new PageParams(0, 1)) // <2> .setAllowNoMatch(true); // <3> // end::get-trained-models-stats-request // tag::get-trained-models-stats-execute GetTrainedModelsStatsResponse response = client.machineLearning().getTrainedModelsStats(request, RequestOptions.DEFAULT); // end::get-trained-models-stats-execute // tag::get-trained-models-stats-response List<TrainedModelStats> models = response.getTrainedModelStats(); // end::get-trained-models-stats-response assertThat(models, hasSize(1)); } { GetTrainedModelsStatsRequest request = new GetTrainedModelsStatsRequest("my-trained-model"); // tag::get-trained-models-stats-execute-listener ActionListener<GetTrainedModelsStatsResponse> listener = new ActionListener<>() { @Override public void onResponse(GetTrainedModelsStatsResponse response) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::get-trained-models-stats-execute-listener // Replace the empty listener by a blocking listener in test CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::get-trained-models-stats-execute-async client.machineLearning() .getTrainedModelsStatsAsync(request, RequestOptions.DEFAULT, listener); // <1> // end::get-trained-models-stats-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testDeleteTrainedModel() throws Exception { RestHighLevelClient client = highLevelClient(); { putTrainedModel("my-trained-model"); // tag::delete-trained-model-request DeleteTrainedModelRequest request = new DeleteTrainedModelRequest("my-trained-model"); // <1> // end::delete-trained-model-request // tag::delete-trained-model-execute AcknowledgedResponse response = client.machineLearning().deleteTrainedModel(request, RequestOptions.DEFAULT); // end::delete-trained-model-execute // tag::delete-trained-model-response boolean deleted = response.isAcknowledged(); // end::delete-trained-model-response assertThat(deleted, is(true)); } { putTrainedModel("my-trained-model"); DeleteTrainedModelRequest request = new DeleteTrainedModelRequest("my-trained-model"); // tag::delete-trained-model-execute-listener ActionListener<AcknowledgedResponse> listener = new ActionListener<>() { @Override public void onResponse(AcknowledgedResponse response) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::delete-trained-model-execute-listener // Replace the empty listener by a blocking listener in test CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::delete-trained-model-execute-async client.machineLearning().deleteTrainedModelAsync(request, RequestOptions.DEFAULT, listener); // <1> // end::delete-trained-model-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testCreateFilter() throws Exception { RestHighLevelClient client = highLevelClient(); { // tag::put-filter-config MlFilter.Builder filterBuilder = MlFilter.builder("my_safe_domains") // <1> .setDescription("A list of safe domains") // <2> .setItems("*.google.com", "wikipedia.org"); // <3> // end::put-filter-config // tag::put-filter-request PutFilterRequest request = new PutFilterRequest(filterBuilder.build()); // <1> // end::put-filter-request // tag::put-filter-execute PutFilterResponse response = client.machineLearning().putFilter(request, RequestOptions.DEFAULT); // end::put-filter-execute // tag::put-filter-response MlFilter createdFilter = response.getResponse(); // <1> // end::put-filter-response assertThat(createdFilter.getId(), equalTo("my_safe_domains")); } { MlFilter.Builder filterBuilder = MlFilter.builder("safe_domains_async") .setDescription("A list of safe domains") .setItems("*.google.com", "wikipedia.org"); PutFilterRequest request = new PutFilterRequest(filterBuilder.build()); // tag::put-filter-execute-listener ActionListener<PutFilterResponse> listener = new ActionListener<PutFilterResponse>() { @Override public void onResponse(PutFilterResponse response) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::put-filter-execute-listener // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::put-filter-execute-async client.machineLearning().putFilterAsync(request, RequestOptions.DEFAULT, listener); // <1> // end::put-filter-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testGetFilters() throws IOException, InterruptedException { RestHighLevelClient client = highLevelClient(); String filterId = "get-filter-doc-test"; MlFilter.Builder filterBuilder = MlFilter.builder(filterId).setDescription("test").setItems("*.google.com", "wikipedia.org"); client.machineLearning().putFilter(new PutFilterRequest(filterBuilder.build()), RequestOptions.DEFAULT); { // tag::get-filters-request GetFiltersRequest request = new GetFiltersRequest(); // <1> // end::get-filters-request // tag::get-filters-filter-id request.setFilterId("get-filter-doc-test"); // <1> // end::get-filters-filter-id // tag::get-filters-page-params request.setFrom(100); // <1> request.setSize(200); // <2> // end::get-filters-page-params request.setFrom(null); request.setSize(null); // tag::get-filters-execute GetFiltersResponse response = client.machineLearning().getFilter(request, RequestOptions.DEFAULT); // end::get-filters-execute // tag::get-filters-response long count = response.count(); // <1> List<MlFilter> filters = response.filters(); // <2> // end::get-filters-response assertEquals(1, filters.size()); } { GetFiltersRequest request = new GetFiltersRequest(); request.setFilterId(filterId); // tag::get-filters-execute-listener ActionListener<GetFiltersResponse> listener = new ActionListener<GetFiltersResponse>() { @Override public void onResponse(GetFiltersResponse getfiltersResponse) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::get-filters-execute-listener // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::get-filters-execute-async client.machineLearning().getFilterAsync(request, RequestOptions.DEFAULT, listener); // <1> // end::get-filters-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testUpdateFilter() throws IOException, InterruptedException { RestHighLevelClient client = highLevelClient(); String filterId = "update-filter-doc-test"; MlFilter.Builder filterBuilder = MlFilter.builder(filterId).setDescription("test").setItems("*.google.com", "wikipedia.org"); client.machineLearning().putFilter(new PutFilterRequest(filterBuilder.build()), RequestOptions.DEFAULT); { // tag::update-filter-request UpdateFilterRequest request = new UpdateFilterRequest(filterId); // <1> // end::update-filter-request // tag::update-filter-description request.setDescription("my new description"); // <1> // end::update-filter-description // tag::update-filter-add-items request.setAddItems(Arrays.asList("*.bing.com", "*.elastic.co")); // <1> // end::update-filter-add-items // tag::update-filter-remove-items request.setRemoveItems(Arrays.asList("*.google.com")); // <1> // end::update-filter-remove-items // tag::update-filter-execute PutFilterResponse response = client.machineLearning().updateFilter(request, RequestOptions.DEFAULT); // end::update-filter-execute // tag::update-filter-response MlFilter updatedFilter = response.getResponse(); // <1> // end::update-filter-response assertEquals(request.getDescription(), updatedFilter.getDescription()); } { UpdateFilterRequest request = new UpdateFilterRequest(filterId); // tag::update-filter-execute-listener ActionListener<PutFilterResponse> listener = new ActionListener<PutFilterResponse>() { @Override public void onResponse(PutFilterResponse putFilterResponse) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::update-filter-execute-listener // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::update-filter-execute-async client.machineLearning().updateFilterAsync(request, RequestOptions.DEFAULT, listener); // <1> // end::update-filter-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testDeleteFilter() throws Exception { RestHighLevelClient client = highLevelClient(); String filterId = createFilter(client); { // tag::delete-filter-request DeleteFilterRequest request = new DeleteFilterRequest(filterId); // <1> // end::delete-filter-request // tag::delete-filter-execute AcknowledgedResponse response = client.machineLearning().deleteFilter(request, RequestOptions.DEFAULT); // end::delete-filter-execute // tag::delete-filter-response boolean isAcknowledged = response.isAcknowledged(); // <1> // end::delete-filter-response assertTrue(isAcknowledged); } filterId = createFilter(client); { DeleteFilterRequest request = new DeleteFilterRequest(filterId); // tag::delete-filter-execute-listener ActionListener<AcknowledgedResponse> listener = new ActionListener<AcknowledgedResponse>() { @Override public void onResponse(AcknowledgedResponse response) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::delete-filter-execute-listener // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::delete-filter-execute-async client.machineLearning().deleteFilterAsync(request, RequestOptions.DEFAULT, listener); //<1> // end::delete-filter-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testGetMlInfo() throws Exception { RestHighLevelClient client = highLevelClient(); { // tag::get-ml-info-request MlInfoRequest request = new MlInfoRequest(); // <1> // end::get-ml-info-request // tag::get-ml-info-execute MlInfoResponse response = client.machineLearning() .getMlInfo(request, RequestOptions.DEFAULT); // end::get-ml-info-execute // tag::get-ml-info-response final Map<String, Object> info = response.getInfo();// <1> // end::get-ml-info-response assertTrue(info.containsKey("defaults")); assertTrue(info.containsKey("limits")); } { MlInfoRequest request = new MlInfoRequest(); // tag::get-ml-info-execute-listener ActionListener<MlInfoResponse> listener = new ActionListener<MlInfoResponse>() { @Override public void onResponse(MlInfoResponse response) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::get-ml-info-execute-listener // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::get-ml-info-execute-async client.machineLearning() .getMlInfoAsync(request, RequestOptions.DEFAULT, listener); // <1> // end::get-ml-info-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testSetUpgradeMode() throws Exception { RestHighLevelClient client = highLevelClient(); { // tag::set-upgrade-mode-request SetUpgradeModeRequest request = new SetUpgradeModeRequest(true); // <1> request.setTimeout(TimeValue.timeValueMinutes(10)); // <2> // end::set-upgrade-mode-request // Set to false so that the cluster setting does not have to be unset at the end of the test. request.setEnabled(false); // tag::set-upgrade-mode-execute AcknowledgedResponse acknowledgedResponse = client.machineLearning().setUpgradeMode(request, RequestOptions.DEFAULT); // end::set-upgrade-mode-execute // tag::set-upgrade-mode-response boolean acknowledged = acknowledgedResponse.isAcknowledged(); // <1> // end::set-upgrade-mode-response assertThat(acknowledged, is(true)); } { SetUpgradeModeRequest request = new SetUpgradeModeRequest(false); // tag::set-upgrade-mode-execute-listener ActionListener<AcknowledgedResponse> listener = new ActionListener<AcknowledgedResponse>() { @Override public void onResponse(AcknowledgedResponse acknowledgedResponse) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::set-upgrade-mode-execute-listener // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::set-upgrade-mode-execute-async client.machineLearning() .setUpgradeModeAsync(request, RequestOptions.DEFAULT, listener); // <1> // end::set-upgrade-mode-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } public void testEstimateModelMemory() throws Exception { RestHighLevelClient client = highLevelClient(); { // tag::estimate-model-memory-request Detector.Builder detectorBuilder = new Detector.Builder() .setFunction("count") .setPartitionFieldName("status"); AnalysisConfig.Builder analysisConfigBuilder = new AnalysisConfig.Builder(Collections.singletonList(detectorBuilder.build())) .setBucketSpan(TimeValue.timeValueMinutes(10)) .setInfluencers(Collections.singletonList("src_ip")); EstimateModelMemoryRequest request = new EstimateModelMemoryRequest(analysisConfigBuilder.build()); // <1> request.setOverallCardinality(Collections.singletonMap("status", 50L)); // <2> request.setMaxBucketCardinality(Collections.singletonMap("src_ip", 30L)); // <3> // end::estimate-model-memory-request // tag::estimate-model-memory-execute EstimateModelMemoryResponse estimateModelMemoryResponse = client.machineLearning().estimateModelMemory(request, RequestOptions.DEFAULT); // end::estimate-model-memory-execute // tag::estimate-model-memory-response ByteSizeValue modelMemoryEstimate = estimateModelMemoryResponse.getModelMemoryEstimate(); // <1> long estimateInBytes = modelMemoryEstimate.getBytes(); // end::estimate-model-memory-response assertThat(estimateInBytes, greaterThan(10000000L)); } { AnalysisConfig analysisConfig = AnalysisConfig.builder(Collections.singletonList(Detector.builder().setFunction("count").build())).build(); EstimateModelMemoryRequest request = new EstimateModelMemoryRequest(analysisConfig); // tag::estimate-model-memory-execute-listener ActionListener<EstimateModelMemoryResponse> listener = new ActionListener<EstimateModelMemoryResponse>() { @Override public void onResponse(EstimateModelMemoryResponse estimateModelMemoryResponse) { // <1> } @Override public void onFailure(Exception e) { // <2> } }; // end::estimate-model-memory-execute-listener // Replace the empty listener by a blocking listener in test final CountDownLatch latch = new CountDownLatch(1); listener = new LatchedActionListener<>(listener, latch); // tag::estimate-model-memory-execute-async client.machineLearning() .estimateModelMemoryAsync(request, RequestOptions.DEFAULT, listener); // <1> // end::estimate-model-memory-execute-async assertTrue(latch.await(30L, TimeUnit.SECONDS)); } } private String createFilter(RestHighLevelClient client) throws IOException { MlFilter.Builder filterBuilder = MlFilter.builder("my_safe_domains") .setDescription("A list of safe domains") .setItems("*.google.com", "wikipedia.org"); PutFilterRequest putFilterRequest = new PutFilterRequest(filterBuilder.build()); PutFilterResponse putFilterResponse = client.machineLearning().putFilter(putFilterRequest, RequestOptions.DEFAULT); MlFilter createdFilter = putFilterResponse.getResponse(); assertThat(createdFilter.getId(), equalTo("my_safe_domains")); return createdFilter.getId(); } private void createIndex(String indexName) throws IOException { CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName); createIndexRequest.mapping(XContentFactory.jsonBuilder().startObject() .startObject("properties") .startObject("timestamp") .field("type", "date") .endObject() .startObject("total") .field("type", "long") .endObject() .endObject() .endObject()); highLevelClient().indices().create(createIndexRequest, RequestOptions.DEFAULT); } private DataFrameAnalyticsState getAnalyticsState(String configId) throws IOException { GetDataFrameAnalyticsStatsResponse statsResponse = highLevelClient().machineLearning().getDataFrameAnalyticsStats( new GetDataFrameAnalyticsStatsRequest(configId), RequestOptions.DEFAULT); assertThat(statsResponse.getAnalyticsStats(), hasSize(1)); DataFrameAnalyticsStats stats = statsResponse.getAnalyticsStats().get(0); return stats.getState(); } private void putTrainedModel(String modelId) throws IOException { TrainedModelDefinition definition = TrainedModelDefinitionTests.createRandomBuilder(TargetType.REGRESSION).build(); TrainedModelConfig trainedModelConfig = TrainedModelConfig.builder() .setDefinition(definition) .setModelId(modelId) .setInferenceConfig(new RegressionConfig("value", 0)) .setInput(new TrainedModelInput(Arrays.asList("col1", "col2", "col3", "col4"))) .setDescription("test model") .build(); highLevelClient().machineLearning().putTrainedModel(new PutTrainedModelRequest(trainedModelConfig), RequestOptions.DEFAULT); } @Override protected NamedXContentRegistry xContentRegistry() { return new NamedXContentRegistry(new MlInferenceNamedXContentProvider().getNamedXContentParsers()); } private static final DataFrameAnalyticsConfig DF_ANALYTICS_CONFIG = DataFrameAnalyticsConfig.builder() .setId("my-analytics-config") .setSource(DataFrameAnalyticsSource.builder() .setIndex("put-test-source-index") .build()) .setDest(DataFrameAnalyticsDest.builder() .setIndex("put-test-dest-index") .build()) .setAnalysis(OutlierDetection.createDefault()) .build(); }
Java
package org.tmarciniak.mtp.model; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import org.apache.commons.lang3.builder.ToStringBuilder; /** * @author tomasz.marciniak * * Immutable class representing trade message */ @Entity @Table public final class TradeMessage implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "trade_message_id_seq") @SequenceGenerator(name = "trade_message_id_seq", sequenceName = "trade_message_id_seq", allocationSize = 1) private long id; private String userId; private String currencyFrom; private String currencyTo; private BigDecimal amountBuy; private BigDecimal amountSell; private BigDecimal rate; private Date timePlaced; private String originatingCountry; public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getCurrencyFrom() { return currencyFrom; } public void setCurrencyFrom(String currencyFrom) { this.currencyFrom = currencyFrom; } public String getCurrencyTo() { return currencyTo; } public void setCurrencyTo(String currencyTo) { this.currencyTo = currencyTo; } public BigDecimal getAmountBuy() { return amountBuy; } public void setAmountBuy(BigDecimal amountBuy) { this.amountBuy = amountBuy; } public BigDecimal getAmountSell() { return amountSell; } public void setAmountSell(BigDecimal amountSell) { this.amountSell = amountSell; } public BigDecimal getRate() { return rate; } public void setRate(BigDecimal rate) { this.rate = rate; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((amountBuy == null) ? 0 : amountBuy.hashCode()); result = prime * result + ((amountSell == null) ? 0 : amountSell.hashCode()); result = prime * result + ((currencyFrom == null) ? 0 : currencyFrom.hashCode()); result = prime * result + ((currencyTo == null) ? 0 : currencyTo.hashCode()); result = prime * result + (int) (id ^ (id >>> 32)); result = prime * result + ((originatingCountry == null) ? 0 : originatingCountry .hashCode()); result = prime * result + ((rate == null) ? 0 : rate.hashCode()); result = prime * result + ((timePlaced == null) ? 0 : timePlaced.hashCode()); result = prime * result + ((userId == null) ? 0 : userId.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TradeMessage other = (TradeMessage) obj; if (amountBuy == null) { if (other.amountBuy != null) return false; } else if (!amountBuy.equals(other.amountBuy)) return false; if (amountSell == null) { if (other.amountSell != null) return false; } else if (!amountSell.equals(other.amountSell)) return false; if (currencyFrom == null) { if (other.currencyFrom != null) return false; } else if (!currencyFrom.equals(other.currencyFrom)) return false; if (currencyTo == null) { if (other.currencyTo != null) return false; } else if (!currencyTo.equals(other.currencyTo)) return false; if (id != other.id) return false; if (originatingCountry == null) { if (other.originatingCountry != null) return false; } else if (!originatingCountry.equals(other.originatingCountry)) return false; if (rate == null) { if (other.rate != null) return false; } else if (!rate.equals(other.rate)) return false; if (timePlaced == null) { if (other.timePlaced != null) return false; } else if (!timePlaced.equals(other.timePlaced)) return false; if (userId == null) { if (other.userId != null) return false; } else if (!userId.equals(other.userId)) return false; return true; } public Date getTimePlaced() { return new Date(timePlaced.getTime()); } public void setTimePlaced(Date timePlaced) { this.timePlaced = timePlaced; } public String getOriginatingCountry() { return originatingCountry; } public void setOriginatingCountry(String originatingCountry) { this.originatingCountry = originatingCountry; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } public long getId() { return id; } public void setId(long id) { this.id = id; } }
Java
/* * Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.polly; import javax.annotation.Generated; import com.amazonaws.services.polly.model.*; /** * Abstract implementation of {@code AmazonPollyAsync}. Convenient method forms pass through to the corresponding * overload that takes a request object and an {@code AsyncHandler}, which throws an * {@code UnsupportedOperationException}. */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class AbstractAmazonPollyAsync extends AbstractAmazonPolly implements AmazonPollyAsync { protected AbstractAmazonPollyAsync() { } @Override public java.util.concurrent.Future<DeleteLexiconResult> deleteLexiconAsync(DeleteLexiconRequest request) { return deleteLexiconAsync(request, null); } @Override public java.util.concurrent.Future<DeleteLexiconResult> deleteLexiconAsync(DeleteLexiconRequest request, com.amazonaws.handlers.AsyncHandler<DeleteLexiconRequest, DeleteLexiconResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<DescribeVoicesResult> describeVoicesAsync(DescribeVoicesRequest request) { return describeVoicesAsync(request, null); } @Override public java.util.concurrent.Future<DescribeVoicesResult> describeVoicesAsync(DescribeVoicesRequest request, com.amazonaws.handlers.AsyncHandler<DescribeVoicesRequest, DescribeVoicesResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<GetLexiconResult> getLexiconAsync(GetLexiconRequest request) { return getLexiconAsync(request, null); } @Override public java.util.concurrent.Future<GetLexiconResult> getLexiconAsync(GetLexiconRequest request, com.amazonaws.handlers.AsyncHandler<GetLexiconRequest, GetLexiconResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<ListLexiconsResult> listLexiconsAsync(ListLexiconsRequest request) { return listLexiconsAsync(request, null); } @Override public java.util.concurrent.Future<ListLexiconsResult> listLexiconsAsync(ListLexiconsRequest request, com.amazonaws.handlers.AsyncHandler<ListLexiconsRequest, ListLexiconsResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<PutLexiconResult> putLexiconAsync(PutLexiconRequest request) { return putLexiconAsync(request, null); } @Override public java.util.concurrent.Future<PutLexiconResult> putLexiconAsync(PutLexiconRequest request, com.amazonaws.handlers.AsyncHandler<PutLexiconRequest, PutLexiconResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } @Override public java.util.concurrent.Future<SynthesizeSpeechResult> synthesizeSpeechAsync(SynthesizeSpeechRequest request) { return synthesizeSpeechAsync(request, null); } @Override public java.util.concurrent.Future<SynthesizeSpeechResult> synthesizeSpeechAsync(SynthesizeSpeechRequest request, com.amazonaws.handlers.AsyncHandler<SynthesizeSpeechRequest, SynthesizeSpeechResult> asyncHandler) { throw new java.lang.UnsupportedOperationException(); } }
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_21) on Sat May 11 22:08:47 BST 2013 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>Uses of Class com.hp.hpl.jena.sparql.lang.sparql_10.TokenMgrError (Apache Jena ARQ)</title> <meta name="date" content="2013-05-11"> <link rel="stylesheet" type="text/css" href="../../../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class com.hp.hpl.jena.sparql.lang.sparql_10.TokenMgrError (Apache Jena ARQ)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../../com/hp/hpl/jena/sparql/lang/sparql_10/TokenMgrError.html" title="class in com.hp.hpl.jena.sparql.lang.sparql_10">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../../index.html?com/hp/hpl/jena/sparql/lang/sparql_10/class-use/TokenMgrError.html" target="_top">Frames</a></li> <li><a href="TokenMgrError.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class com.hp.hpl.jena.sparql.lang.sparql_10.TokenMgrError" class="title">Uses of Class<br>com.hp.hpl.jena.sparql.lang.sparql_10.TokenMgrError</h2> </div> <div class="classUseContainer">No usage of com.hp.hpl.jena.sparql.lang.sparql_10.TokenMgrError</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../../../com/hp/hpl/jena/sparql/lang/sparql_10/TokenMgrError.html" title="class in com.hp.hpl.jena.sparql.lang.sparql_10">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../../../index.html?com/hp/hpl/jena/sparql/lang/sparql_10/class-use/TokenMgrError.html" target="_top">Frames</a></li> <li><a href="TokenMgrError.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Licenced under the Apache License, Version 2.0</small></p> </body> </html>
Java
package dk.itu.pervasive.mobile.data; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.preference.PreferenceManager; import android.provider.MediaStore; import android.util.Log; import android.widget.Toast; import dk.itu.pervasive.mobile.R; import java.io.FileOutputStream; /** * @author Tony Beltramelli www.tonybeltramelli.com */ public class DataManager { public static final String PREF_KEY_SAVE = "save"; public static final String PREF_KEY_USERNAME = "username"; public static final String PREF_KEY_SURFACE_ADDRESS = "surfaceAddress"; public static final String PREF_KEY_STICKER_ID = "stickerID"; private static DataManager _instance = null; private Activity _context; private String _username = ""; private String _surfaceAddress = ""; private String _stickerID = ""; private DataManager() { } public static DataManager getInstance() { if (_instance == null) { _instance = new DataManager(); } return _instance; } public void saveData() { _username = PreferenceManager.getDefaultSharedPreferences(_context).getString(PREF_KEY_USERNAME, _context.getResources().getString(R.string.preference_user_name_default)); _surfaceAddress = PreferenceManager.getDefaultSharedPreferences(_context).getString(PREF_KEY_SURFACE_ADDRESS, _context.getResources().getString(R.string.preference_surface_address_default)); _stickerID = PreferenceManager.getDefaultSharedPreferences(_context).getString(PREF_KEY_STICKER_ID, _context.getResources().getString(R.string.preference_sticker_id_default)); Log.wtf("save data", _username + ", " + _surfaceAddress + ", " + _stickerID); } public String getPathFromUri(Uri uri) { String[] projection = { MediaStore.Images.Media.DATA }; Cursor cursor = _context.getContentResolver().query(uri, projection, null, null, null); int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); } public void saveImage(String imageName, byte[] bytes) { FileOutputStream fos; try { fos = _context.openFileOutput(imageName, Context.MODE_PRIVATE); fos.write(bytes); fos.close(); } catch (Exception e) { e.printStackTrace(); } } public void displayMessage(final String message) { _context.runOnUiThread(new Runnable() { public void run() { Toast.makeText(_context, message, Toast.LENGTH_SHORT).show(); } }); } public String getUsername() { return _username; } public String getSurfaceAddress() { return _surfaceAddress; } public String getStickerID() { return _stickerID; } public void setContext(Activity context) { _context = context; saveData(); } public Context getContext(){ return _context; } }
Java
/* * Copyright (c) 2005-2011 Grameen Foundation USA * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. * * See also http://www.apache.org/licenses/LICENSE-2.0.html for an * explanation of the license and how it is applied. */ package org.mifos.accounts.struts.actionforms; import static org.mifos.framework.util.helpers.DateUtils.dateFallsBeforeDate; import static org.mifos.framework.util.helpers.DateUtils.getDateAsSentFromBrowser; import java.sql.Date; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Locale; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.commons.lang.StringUtils; import org.apache.struts.Globals; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.joda.time.LocalDate; import org.mifos.accounts.servicefacade.AccountTypeDto; import org.mifos.accounts.util.helpers.AccountConstants; import org.mifos.application.admin.servicefacade.InvalidDateException; import org.mifos.application.master.business.MifosCurrency; import org.mifos.config.AccountingRules; import org.mifos.framework.business.util.helpers.MethodNameConstants; import org.mifos.framework.struts.actionforms.BaseActionForm; import org.mifos.framework.util.helpers.Constants; import org.mifos.framework.util.helpers.DateUtils; import org.mifos.framework.util.helpers.DoubleConversionResult; import org.mifos.framework.util.helpers.SessionUtils; import org.mifos.security.login.util.helpers.LoginConstants; import org.mifos.security.util.ActivityMapper; import org.mifos.security.util.UserContext; public class AccountApplyPaymentActionForm extends BaseActionForm { private String input; private String transactionDateDD; private String transactionDateMM; private String transactionDateYY; private String amount; private Short currencyId; private String receiptId; private String receiptDateDD; private String receiptDateMM; private String receiptDateYY; /* * Among other things, this field holds the PaymentTypes value for disbursements. */ private String paymentTypeId; private String waiverInterest; private String globalAccountNum; private String accountId; private String prdOfferingName; private boolean amountCannotBeZero = true; private java.util.Date lastPaymentDate; private String accountForTransfer; private Short transferPaymentTypeId; public boolean amountCannotBeZero() { return this.amountCannotBeZero; } public void setAmountCannotBeZero(boolean amountCannotBeZero) { this.amountCannotBeZero = amountCannotBeZero; } public String getPrdOfferingName() { return prdOfferingName; } public void setPrdOfferingName(String prdOfferingName) { this.prdOfferingName = prdOfferingName; } public String getAmount() { return amount; } public void setAmount(String amount) { this.amount = amount; } public String getInput() { return input; } @Override public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { String methodCalled = request.getParameter(MethodNameConstants.METHOD); ActionErrors errors = new ActionErrors(); if (methodCalled != null && methodCalled.equals("preview")) { validateTransfer(errors); validateTransactionDate(errors); validatePaymentType(errors); validateReceiptDate(errors); String accountType = (String) request.getSession().getAttribute(Constants.ACCOUNT_TYPE); validateAccountType(errors, accountType); validateAmount(errors); validateModeOfPaymentSecurity(request, errors); } if (!errors.isEmpty()) { request.setAttribute(Globals.ERROR_KEY, errors); request.setAttribute("methodCalled", methodCalled); } return errors; } private void validateModeOfPaymentSecurity(HttpServletRequest request, ActionErrors errors){ UserContext userContext = (UserContext) SessionUtils.getAttribute(Constants.USER_CONTEXT_KEY, request.getSession()); if(getPaymentTypeId().equals("4") && !ActivityMapper.getInstance().isModeOfPaymentSecurity(userContext)){ errors.add(AccountConstants.LOAN_TRANSFER_PERMISSION, new ActionMessage(AccountConstants.LOAN_TRANSFER_PERMISSION, getLocalizedMessage("accounts.mode_of_payment_permission"))); } } private void validateTransfer(ActionErrors errors) { if (paymentTypeId.equals(String.valueOf(transferPaymentTypeId)) && StringUtils.isBlank(accountForTransfer)) { errors.add(AccountConstants.NO_ACCOUNT_FOR_TRANSFER, new ActionMessage(AccountConstants.NO_ACCOUNT_FOR_TRANSFER)); } } private void validateAccountType(ActionErrors errors, String accountType) { if (accountType != null && accountType.equals(AccountTypeDto.LOAN_ACCOUNT.name())) { if (getAmount() == null || getAmount().equals("")) { errors.add(AccountConstants.ERROR_MANDATORY, new ActionMessage(AccountConstants.ERROR_MANDATORY, getLocalizedMessage("accounts.amt"))); } } } private void validatePaymentType(ActionErrors errors) { if (StringUtils.isEmpty(getPaymentTypeId())) { errors.add(AccountConstants.ERROR_MANDATORY, new ActionMessage(AccountConstants.ERROR_MANDATORY, getLocalizedMessage("accounts.mode_of_payment"))); } } private void validateReceiptDate(ActionErrors errors) { if (getReceiptDate() != null && !getReceiptDate().equals("")) { ActionErrors validationErrors = validateDate(getReceiptDate(), getLocalizedMessage("accounts.receiptdate")); if (null != validationErrors && !validationErrors.isEmpty()) { errors.add(validationErrors); } } } private void validateTransactionDate(ActionErrors errors) { String fieldName = "accounts.date_of_trxn"; ActionErrors validationErrors = validateDate(getTransactionDate(), getLocalizedMessage(fieldName)); if (null != validationErrors && !validationErrors.isEmpty()) { errors.add(validationErrors); } if (null != getTransactionDate()){ validationErrors = validatePaymentDate(getTransactionDate(), getLocalizedMessage(fieldName)); if (validationErrors != null && !validationErrors.isEmpty()) { errors.add(validationErrors); } } } //exposed for testing public ActionErrors validatePaymentDate(String transactionDate, String fieldName) { ActionErrors errors = null; try { if (lastPaymentDate != null && dateFallsBeforeDate(getDateAsSentFromBrowser(transactionDate), lastPaymentDate)) { errors = new ActionErrors(); errors.add(AccountConstants.ERROR_PAYMENT_DATE_BEFORE_LAST_PAYMENT, new ActionMessage(AccountConstants.ERROR_PAYMENT_DATE_BEFORE_LAST_PAYMENT, fieldName)); } } catch (InvalidDateException ide) { errors = new ActionErrors(); //dont add a message, since it was already added in validateDate() } return errors; } protected ActionErrors validateDate(String date, String fieldName) { ActionErrors errors = null; java.sql.Date sqlDate = null; if (date != null && !date.equals("")) { try { sqlDate = getDateAsSentFromBrowser(date); if (DateUtils.whichDirection(sqlDate) > 0) { errors = new ActionErrors(); errors.add(AccountConstants.ERROR_FUTUREDATE, new ActionMessage(AccountConstants.ERROR_FUTUREDATE, fieldName)); } } catch (InvalidDateException ide) { errors = new ActionErrors(); errors.add(AccountConstants.ERROR_INVALIDDATE, new ActionMessage(AccountConstants.ERROR_INVALIDDATE, fieldName)); } } else { errors = new ActionErrors(); errors.add(AccountConstants.ERROR_MANDATORY, new ActionMessage(AccountConstants.ERROR_MANDATORY, fieldName)); } return errors; } protected Locale getUserLocale(HttpServletRequest request) { Locale locale = null; HttpSession session = request.getSession(); if (session != null) { UserContext userContext = (UserContext) session.getAttribute(LoginConstants.USERCONTEXT); if (null != userContext) { locale = userContext.getCurrentLocale(); } } return locale; } protected void validateAmount(ActionErrors errors) { MifosCurrency currency = null; if (getCurrencyId() != null && AccountingRules.isMultiCurrencyEnabled()) { currency = AccountingRules.getCurrencyByCurrencyId(getCurrencyId()); } DoubleConversionResult conversionResult = validateAmount(getAmount(), currency , AccountConstants.ACCOUNT_AMOUNT, errors, ""); if (amountCannotBeZero() && conversionResult.getErrors().size() == 0 && !(conversionResult.getDoubleValue() > 0.0)) { addError(errors, AccountConstants.ACCOUNT_AMOUNT, AccountConstants.ERRORS_MUST_BE_GREATER_THAN_ZERO, getLocalizedMessage(AccountConstants.ACCOUNT_AMOUNT)); } } public void setInput(String input) { this.input = input; } public String getPaymentTypeId() { return paymentTypeId; } public void setPaymentTypeId(String paymentTypeId) { this.paymentTypeId = paymentTypeId; } public String getReceiptDate() { return compileDateString(receiptDateDD, receiptDateMM, receiptDateYY); } public void setReceiptDate(String receiptDate) throws InvalidDateException { if (StringUtils.isBlank(receiptDate)) { receiptDateDD = null; receiptDateMM = null; receiptDateYY = null; } else { Calendar cal = new GregorianCalendar(); java.sql.Date date = getDateAsSentFromBrowser(receiptDate); cal.setTime(date); receiptDateDD = Integer.toString(cal.get(Calendar.DAY_OF_MONTH)); receiptDateMM = Integer.toString(cal.get(Calendar.MONTH) + 1); receiptDateYY = Integer.toString(cal.get(Calendar.YEAR)); } } public String getReceiptId() { return receiptId; } public void setReceiptId(String receiptId) { this.receiptId = receiptId; } public String getTransactionDate() { return compileDateString(transactionDateDD, transactionDateMM, transactionDateYY); } public void setTransactionDate(String receiptDate) throws InvalidDateException { if (StringUtils.isBlank(receiptDate)) { transactionDateDD = null; transactionDateMM = null; transactionDateYY = null; } else { Calendar cal = new GregorianCalendar(); java.sql.Date date = getDateAsSentFromBrowser(receiptDate); cal.setTime(date); transactionDateDD = Integer.toString(cal.get(Calendar.DAY_OF_MONTH)); transactionDateMM = Integer.toString(cal.get(Calendar.MONTH) + 1); transactionDateYY = Integer.toString(cal.get(Calendar.YEAR)); } } public String getAccountId() { return accountId; } public void setAccountId(String accountId) { this.accountId = accountId; } public String getGlobalAccountNum() { return globalAccountNum; } public void setGlobalAccountNum(String globalAccountNum) { this.globalAccountNum = globalAccountNum; } protected void clear() throws InvalidDateException { this.amount = null; this.paymentTypeId = null; setReceiptDate(null); this.receiptId = null; } public String getReceiptDateDD() { return receiptDateDD; } public void setReceiptDateDD(String receiptDateDD) { this.receiptDateDD = receiptDateDD; } public String getReceiptDateMM() { return receiptDateMM; } public void setReceiptDateMM(String receiptDateMM) { this.receiptDateMM = receiptDateMM; } public String getReceiptDateYY() { return receiptDateYY; } public void setReceiptDateYY(String receiptDateYY) { this.receiptDateYY = receiptDateYY; } public String getTransactionDateDD() { return transactionDateDD; } public void setTransactionDateDD(String transactionDateDD) { this.transactionDateDD = transactionDateDD; } public String getTransactionDateMM() { return transactionDateMM; } public void setTransactionDateMM(String transactionDateMM) { this.transactionDateMM = transactionDateMM; } public String getTransactionDateYY() { return transactionDateYY; } public void setTransactionDateYY(String transactionDateYY) { this.transactionDateYY = transactionDateYY; } public Short getCurrencyId() { return this.currencyId; } public void setCurrencyId(Short currencyId) { this.currencyId = currencyId; } public String getWaiverInterest() { return waiverInterest; } public void setWaiverInterest(String waiverInterest) { this.waiverInterest = waiverInterest; } public LocalDate getReceiptDateAsLocalDate() throws InvalidDateException { Date receiptDateStr = getDateAsSentFromBrowser(getReceiptDate()); return (receiptDateStr != null) ? new LocalDate(receiptDateStr.getTime()) : null; } public LocalDate getTrxnDateAsLocalDate() throws InvalidDateException { return new LocalDate(getTrxnDate().getTime()); } public Date getTrxnDate() throws InvalidDateException { return getDateAsSentFromBrowser(getTransactionDate()); } public void setLastPaymentDate(java.util.Date lastPaymentDate) { this.lastPaymentDate = lastPaymentDate; } public String getAccountForTransfer() { return accountForTransfer; } public void setAccountForTransfer(String accountForTransfer) { this.accountForTransfer = accountForTransfer; } public Short getTransferPaymentTypeId() { return transferPaymentTypeId; } public void setTransferPaymentTypeId(Short transferPaymentTypeId) { this.transferPaymentTypeId = transferPaymentTypeId; } }
Java
package org.apache.activemq.nob.filestore.uuiddir; import org.apache.activemq.nob.filestore.BrokerFilenameDecoder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.UUID; /** * Decoder of filenames in a UUID-based filesystem store of broker configuration files. This store only supports * broker IDs in the form of UUIDs. * * Created by art on 2/19/15. */ public class UUIDDirectoryStoreFilenameDecoder implements BrokerFilenameDecoder { public static final String XBEAN_FILE_PATH_SUFFIX = "-xbean.xml"; private static final Logger DEFAULT_LOGGER = LoggerFactory.getLogger(UUIDDirectoryStoreFilenameDecoder.class); private Logger LOG = DEFAULT_LOGGER; /** * Decode the pathname as a UUID if it is a regular file (i.e. not a directory) and return the UUID. * * @param brokerPath path to the candidate broker. * @return */ @Override public String extractIdFromFilename(File brokerPath) { String result = null; if ( ! brokerPath.isDirectory() ) { try { UUID uuid = UUID.fromString(brokerPath.getName()); if (uuid != null) { result = uuid.toString(); } } catch ( IllegalArgumentException illegalArgExc ) { LOG.debug("invalid UUID {}", brokerPath.getName()); } } return result; } /** * Locate the path to the xbean configuration file for the broker at the given path. This method validates the * broker path as it must to determine the broker ID. * * @param brokerPath path to the broker. * @return path to the xbean configuration file, even if it does not exist. */ @Override public File getBrokerXbeanFile(File brokerPath) { File result = null; String brokerId = this.extractIdFromFilename(brokerPath); if ( brokerId != null ) { result = new File(brokerPath.getPath() + XBEAN_FILE_PATH_SUFFIX); } return result; } }
Java
package antw.logger; import java.util.Date; import org.apache.tools.ant.BuildEvent; import antw.common.util.Constants; import antw.common.util.StringUtil; import antw.common.util.TimeUtil; import antw.logger.model.Project; import antw.logger.model.Target; public class TreeLogger extends LoggerAdapter { protected Project _lastProject = new Project(""); protected int _spaceCount = 2; protected Date _start; protected final LoggerContext _context; private boolean _junitTaskWasRunning; public TreeLogger(LoggerContext context) { _context = context; } @Override public void targetStarted(BuildEvent event) { Target target = _context.getTarget(event); if (!target.getProject().equals(_lastProject)) { switchToSubProject(_lastProject, target.getProject()); switchFromSubProject(_lastProject, target.getProject()); printProject(target.getProject()); } _lastProject = target.getProject(); space(_spaceCount + 2); out("%-40s %-40s%n", new Object[] { "|--- " + target.getName(), "[" + target.getCounter() + " times; " + TimeUtil.formatTimeDuration(System.currentTimeMillis() - _start.getTime()) + "]" }); } private void printProject(Project project) { space(_spaceCount + 2); out("|"); space(_spaceCount + 1); out(project.getName()); } private void switchFromSubProject(Project lastProject, Project project) { if (lastProject.isSubProject()) { if (!project.isSubProject()) { space(_spaceCount + 1); _spaceCount -= 2; out("/"); } } } private void switchToSubProject(Project lastProject, Project currentProject) { if (!lastProject.isSubProject()) { if (currentProject.isSubProject()) { _spaceCount += 2; space(_spaceCount + 1); out("\\"); } } } @Override public void buildStarted(BuildEvent event) { newLine(); _start = new Date(); } @Override public void buildFinished(BuildEvent event) { if (event.getException() != null) { newLine(3); err(event.getException(), false); newLine(3); out("BUILD FAILED :("); out("Total Time: " + _context.getProjects().getDurationAsString()); } else { newLine(3); out("BUILD SUCCESSFUL :)"); out("Total Time: " + _context.getProjects().getDurationAsString()); } newLine(2); } @Override public void messageLogged(BuildEvent event) { if (event.getTask() != null) { if ("junit".equals(event.getTask().getTaskType())) { if (!_junitTaskWasRunning) { switchToTestSuite(); } if (event.getPriority() <= org.apache.tools.ant.Project.MSG_INFO) { String message = event.getMessage(); if (message.contains(Constants.TEST_SUITE_LABEL)) { printTestSuite(message); } else if (message.contains(Constants.TEST_CASE_LABEL)) { printTestCase(message); } } _junitTaskWasRunning = true; } else { if (_junitTaskWasRunning) { switchFromTestSuite(); } _junitTaskWasRunning = false; } } } private void switchFromTestSuite() { space(_spaceCount + 1); _spaceCount -= 2; out("/"); } private void printTestCase(String message) { space(_spaceCount + 2); out("|--- " + StringUtil.remove(Constants.TEST_CASE_LABEL, message)); } private void switchToTestSuite() { _spaceCount += 2; space(_spaceCount + 1); out("\\"); } private void printTestSuite(String testStuite) { space(_spaceCount + 2); out("|"); space(_spaceCount + 1); out(StringUtil.remove(Constants.TEST_SUITE_LABEL, testStuite)); } }
Java
<<<<<<< HEAD <?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2014 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- /** * ThinkPHP惯例配置文件 * 该文件请不要修改,如果要覆盖惯例配置的值,可在应用配置文件中设定和惯例不符的配置项 * 配置名称大小写任意,系统会统一转换成小写 * 所有配置参数都可以在生效前动态改变 */ defined('THINK_PATH') or exit(); return array( /* 应用设定 */ 'APP_USE_NAMESPACE' => true, // 应用类库是否使用命名空间 'APP_SUB_DOMAIN_DEPLOY' => false, // 是否开启子域名部署 'APP_SUB_DOMAIN_RULES' => array(), // 子域名部署规则 'APP_DOMAIN_SUFFIX' => '', // 域名后缀 如果是com.cn net.cn 之类的后缀必须设置 'ACTION_SUFFIX' => '', // 操作方法后缀 'MULTI_MODULE' => true, // 是否允许多模块 如果为false 则必须设置 DEFAULT_MODULE 'MODULE_DENY_LIST' => array('Common','Runtime'), 'CONTROLLER_LEVEL' => 1, 'APP_AUTOLOAD_LAYER' => 'Controller,Model', // 自动加载的应用类库层 关闭APP_USE_NAMESPACE后有效 'APP_AUTOLOAD_PATH' => '', // 自动加载的路径 关闭APP_USE_NAMESPACE后有效 /* Cookie设置 */ 'COOKIE_EXPIRE' => 0, // Cookie有效期 'COOKIE_DOMAIN' => '', // Cookie有效域名 'COOKIE_PATH' => '/', // Cookie路径 'COOKIE_PREFIX' => '', // Cookie前缀 避免冲突 'COOKIE_SECURE' => false, // Cookie安全传输 'COOKIE_HTTPONLY' => '', // Cookie httponly设置 /* 默认设定 */ 'DEFAULT_M_LAYER' => 'Model', // 默认的模型层名称 'DEFAULT_C_LAYER' => 'Controller', // 默认的控制器层名称 'DEFAULT_V_LAYER' => 'View', // 默认的视图层名称 'DEFAULT_LANG' => 'zh-cn', // 默认语言 'DEFAULT_THEME' => '', // 默认模板主题名称 'DEFAULT_MODULE' => 'Home', // 默认模块 'DEFAULT_CONTROLLER' => 'Index', // 默认控制器名称 'DEFAULT_ACTION' => 'index', // 默认操作名称 'DEFAULT_CHARSET' => 'utf-8', // 默认输出编码 'DEFAULT_TIMEZONE' => 'PRC', // 默认时区 'DEFAULT_AJAX_RETURN' => 'JSON', // 默认AJAX 数据返回格式,可选JSON XML ... 'DEFAULT_JSONP_HANDLER' => 'jsonpReturn', // 默认JSONP格式返回的处理方法 'DEFAULT_FILTER' => 'htmlspecialchars', // 默认参数过滤方法 用于I函数... /* 数据库设置 */ 'DB_TYPE' => '', // 数据库类型 'DB_HOST' => '', // 服务器地址 'DB_NAME' => '', // 数据库名 'DB_USER' => '', // 用户名 'DB_PWD' => '', // 密码 'DB_PORT' => '', // 端口 'DB_PREFIX' => '', // 数据库表前缀 'DB_PARAMS' => array(), // 数据库连接参数 'DB_DEBUG' => TRUE, // 数据库调试模式 开启后可以记录SQL日志 'DB_FIELDS_CACHE' => true, // 启用字段缓存 'DB_CHARSET' => 'utf8', // 数据库编码默认采用utf8 'DB_DEPLOY_TYPE' => 0, // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器) 'DB_RW_SEPARATE' => false, // 数据库读写是否分离 主从式有效 'DB_MASTER_NUM' => 1, // 读写分离后 主服务器数量 'DB_SLAVE_NO' => '', // 指定从服务器序号 /* 数据缓存设置 */ 'DATA_CACHE_TIME' => 0, // 数据缓存有效期 0表示永久缓存 'DATA_CACHE_COMPRESS' => false, // 数据缓存是否压缩缓存 'DATA_CACHE_CHECK' => false, // 数据缓存是否校验缓存 'DATA_CACHE_PREFIX' => '', // 缓存前缀 'DATA_CACHE_TYPE' => 'File', // 数据缓存类型,支持:File|Db|Apc|Memcache|Shmop|Sqlite|Xcache|Apachenote|Eaccelerator 'DATA_CACHE_PATH' => TEMP_PATH,// 缓存路径设置 (仅对File方式缓存有效) 'DATA_CACHE_KEY' => '', // 缓存文件KEY (仅对File方式缓存有效) 'DATA_CACHE_SUBDIR' => false, // 使用子目录缓存 (自动根据缓存标识的哈希创建子目录) 'DATA_PATH_LEVEL' => 1, // 子目录缓存级别 /* 错误设置 */ 'ERROR_MESSAGE' => '页面错误!请稍后再试~',//错误显示信息,非调试模式有效 'ERROR_PAGE' => '', // 错误定向页面 'SHOW_ERROR_MSG' => false, // 显示错误信息 'TRACE_MAX_RECORD' => 100, // 每个级别的错误信息 最大记录数 /* 日志设置 */ 'LOG_RECORD' => false, // 默认不记录日志 'LOG_TYPE' => 'File', // 日志记录类型 默认为文件方式 'LOG_LEVEL' => 'EMERG,ALERT,CRIT,ERR',// 允许记录的日志级别 'LOG_FILE_SIZE' => 2097152, // 日志文件大小限制 'LOG_EXCEPTION_RECORD' => false, // 是否记录异常信息日志 /* SESSION设置 */ 'SESSION_AUTO_START' => true, // 是否自动开启Session 'SESSION_OPTIONS' => array(), // session 配置数组 支持type name id path expire domain 等参数 'SESSION_TYPE' => '', // session hander类型 默认无需设置 除非扩展了session hander驱动 'SESSION_PREFIX' => '', // session 前缀 //'VAR_SESSION_ID' => 'session_id', //sessionID的提交变量 /* 模板引擎设置 */ 'TMPL_CONTENT_TYPE' => 'text/html', // 默认模板输出类型 'TMPL_ACTION_ERROR' => THINK_PATH.'Tpl/dispatch_jump.tpl', // 默认错误跳转对应的模板文件 'TMPL_ACTION_SUCCESS' => THINK_PATH.'Tpl/dispatch_jump.tpl', // 默认成功跳转对应的模板文件 'TMPL_EXCEPTION_FILE' => THINK_PATH.'Tpl/think_exception.tpl',// 异常页面的模板文件 'TMPL_DETECT_THEME' => false, // 自动侦测模板主题 'TMPL_TEMPLATE_SUFFIX' => '.html', // 默认模板文件后缀 'TMPL_FILE_DEPR' => '/', //模板文件CONTROLLER_NAME与ACTION_NAME之间的分割符 // 布局设置 'TMPL_ENGINE_TYPE' => 'Think', // 默认模板引擎 以下设置仅对使用Think模板引擎有效 'TMPL_CACHFILE_SUFFIX' => '.php', // 默认模板缓存后缀 'TMPL_DENY_FUNC_LIST' => 'echo,exit', // 模板引擎禁用函数 'TMPL_DENY_PHP' => false, // 默认模板引擎是否禁用PHP原生代码 'TMPL_L_DELIM' => '{', // 模板引擎普通标签开始标记 'TMPL_R_DELIM' => '}', // 模板引擎普通标签结束标记 'TMPL_VAR_IDENTIFY' => 'array', // 模板变量识别。留空自动判断,参数为'obj'则表示对象 'TMPL_STRIP_SPACE' => true, // 是否去除模板文件里面的html空格与换行 'TMPL_CACHE_ON' => true, // 是否开启模板编译缓存,设为false则每次都会重新编译 'TMPL_CACHE_PREFIX' => '', // 模板缓存前缀标识,可以动态改变 'TMPL_CACHE_TIME' => 0, // 模板缓存有效期 0 为永久,(以数字为值,单位:秒) 'TMPL_LAYOUT_ITEM' => '{__CONTENT__}', // 布局模板的内容替换标识 'LAYOUT_ON' => false, // 是否启用布局 'LAYOUT_NAME' => 'layout', // 当前布局名称 默认为layout // Think模板引擎标签库相关设定 'TAGLIB_BEGIN' => '<', // 标签库标签开始标记 'TAGLIB_END' => '>', // 标签库标签结束标记 'TAGLIB_LOAD' => true, // 是否使用内置标签库之外的其它标签库,默认自动检测 'TAGLIB_BUILD_IN' => 'cx', // 内置标签库名称(标签使用不必指定标签库名称),以逗号分隔 注意解析顺序 'TAGLIB_PRE_LOAD' => '', // 需要额外加载的标签库(须指定标签库名称),多个以逗号分隔 /* URL设置 */ 'URL_CASE_INSENSITIVE' => true, // 默认false 表示URL区分大小写 true则表示不区分大小写 'URL_MODEL' => 1, // URL访问模式,可选参数0、1、2、3,代表以下四种模式: // 0 (普通模式); 1 (PATHINFO 模式); 2 (REWRITE 模式); 3 (兼容模式) 默认为PATHINFO 模式 'URL_PATHINFO_DEPR' => '/', // PATHINFO模式下,各参数之间的分割符号 'URL_PATHINFO_FETCH' => 'ORIG_PATH_INFO,REDIRECT_PATH_INFO,REDIRECT_URL', // 用于兼容判断PATH_INFO 参数的SERVER替代变量列表 'URL_REQUEST_URI' => 'REQUEST_URI', // 获取当前页面地址的系统变量 默认为REQUEST_URI 'URL_HTML_SUFFIX' => 'html', // URL伪静态后缀设置 'URL_DENY_SUFFIX' => 'ico|png|gif|jpg', // URL禁止访问的后缀设置 'URL_PARAMS_BIND' => true, // URL变量绑定到Action方法参数 'URL_PARAMS_BIND_TYPE' => 0, // URL变量绑定的类型 0 按变量名绑定 1 按变量顺序绑定 'URL_PARAMS_FILTER' => false, // URL变量绑定过滤 'URL_PARAMS_FILTER_TYPE'=> '', // URL变量绑定过滤方法 如果为空 调用DEFAULT_FILTER 'URL_ROUTER_ON' => false, // 是否开启URL路由 'URL_ROUTE_RULES' => array(), // 默认路由规则 针对模块 'URL_MAP_RULES' => array(), // URL映射定义规则 /* 系统变量名称设置 */ 'VAR_MODULE' => 'm', // 默认模块获取变量 'VAR_ADDON' => 'addon', // 默认的插件控制器命名空间变量 'VAR_CONTROLLER' => 'c', // 默认控制器获取变量 'VAR_ACTION' => 'a', // 默认操作获取变量 'VAR_AJAX_SUBMIT' => 'ajax', // 默认的AJAX提交变量 'VAR_JSONP_HANDLER' => 'callback', 'VAR_PATHINFO' => 's', // 兼容模式PATHINFO获取变量例如 ?s=/module/action/id/1 后面的参数取决于URL_PATHINFO_DEPR 'VAR_TEMPLATE' => 't', // 默认模板切换变量 'VAR_AUTO_STRING' => false, // 输入变量是否自动强制转换为字符串 如果开启则数组变量需要手动传入变量修饰符获取变量 'HTTP_CACHE_CONTROL' => 'private', // 网页缓存控制 'CHECK_APP_DIR' => true, // 是否检查应用目录是否创建 'FILE_UPLOAD_TYPE' => 'Local', // 文件上传方式 'DATA_CRYPT_TYPE' => 'Think', // 数据加密方式 ); ======= <?php // +---------------------------------------------------------------------- // | ThinkPHP [ WE CAN DO IT JUST THINK IT ] // +---------------------------------------------------------------------- // | Copyright (c) 2006-2014 http://thinkphp.cn All rights reserved. // +---------------------------------------------------------------------- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) // +---------------------------------------------------------------------- // | Author: liu21st <liu21st@gmail.com> // +---------------------------------------------------------------------- /** * ThinkPHP惯例配置文件 * 该文件请不要修改,如果要覆盖惯例配置的值,可在应用配置文件中设定和惯例不符的配置项 * 配置名称大小写任意,系统会统一转换成小写 * 所有配置参数都可以在生效前动态改变 */ defined('THINK_PATH') or exit(); return array( /* 应用设定 */ 'APP_USE_NAMESPACE' => true, // 应用类库是否使用命名空间 'APP_SUB_DOMAIN_DEPLOY' => false, // 是否开启子域名部署 'APP_SUB_DOMAIN_RULES' => array(), // 子域名部署规则 'APP_DOMAIN_SUFFIX' => '', // 域名后缀 如果是com.cn net.cn 之类的后缀必须设置 'ACTION_SUFFIX' => '', // 操作方法后缀 'MULTI_MODULE' => true, // 是否允许多模块 如果为false 则必须设置 DEFAULT_MODULE 'MODULE_DENY_LIST' => array('Common','Runtime'), 'CONTROLLER_LEVEL' => 1, 'APP_AUTOLOAD_LAYER' => 'Controller,Model', // 自动加载的应用类库层 关闭APP_USE_NAMESPACE后有效 'APP_AUTOLOAD_PATH' => '', // 自动加载的路径 关闭APP_USE_NAMESPACE后有效 /* Cookie设置 */ 'COOKIE_EXPIRE' => 0, // Cookie有效期 'COOKIE_DOMAIN' => '', // Cookie有效域名 'COOKIE_PATH' => '/', // Cookie路径 'COOKIE_PREFIX' => '', // Cookie前缀 避免冲突 'COOKIE_SECURE' => false, // Cookie安全传输 'COOKIE_HTTPONLY' => '', // Cookie httponly设置 /* 默认设定 */ 'DEFAULT_M_LAYER' => 'Model', // 默认的模型层名称 'DEFAULT_C_LAYER' => 'Controller', // 默认的控制器层名称 'DEFAULT_V_LAYER' => 'View', // 默认的视图层名称 'DEFAULT_LANG' => 'zh-cn', // 默认语言 'DEFAULT_THEME' => '', // 默认模板主题名称 'DEFAULT_MODULE' => 'Home', // 默认模块 'DEFAULT_CONTROLLER' => 'Index', // 默认控制器名称 'DEFAULT_ACTION' => 'index', // 默认操作名称 'DEFAULT_CHARSET' => 'utf-8', // 默认输出编码 'DEFAULT_TIMEZONE' => 'PRC', // 默认时区 'DEFAULT_AJAX_RETURN' => 'JSON', // 默认AJAX 数据返回格式,可选JSON XML ... 'DEFAULT_JSONP_HANDLER' => 'jsonpReturn', // 默认JSONP格式返回的处理方法 'DEFAULT_FILTER' => 'htmlspecialchars', // 默认参数过滤方法 用于I函数... /* 数据库设置 */ 'DB_TYPE' => '', // 数据库类型 'DB_HOST' => '', // 服务器地址 'DB_NAME' => '', // 数据库名 'DB_USER' => '', // 用户名 'DB_PWD' => '', // 密码 'DB_PORT' => '', // 端口 'DB_PREFIX' => '', // 数据库表前缀 'DB_PARAMS' => array(), // 数据库连接参数 'DB_DEBUG' => TRUE, // 数据库调试模式 开启后可以记录SQL日志 'DB_FIELDS_CACHE' => true, // 启用字段缓存 'DB_CHARSET' => 'utf8', // 数据库编码默认采用utf8 'DB_DEPLOY_TYPE' => 0, // 数据库部署方式:0 集中式(单一服务器),1 分布式(主从服务器) 'DB_RW_SEPARATE' => false, // 数据库读写是否分离 主从式有效 'DB_MASTER_NUM' => 1, // 读写分离后 主服务器数量 'DB_SLAVE_NO' => '', // 指定从服务器序号 /* 数据缓存设置 */ 'DATA_CACHE_TIME' => 0, // 数据缓存有效期 0表示永久缓存 'DATA_CACHE_COMPRESS' => false, // 数据缓存是否压缩缓存 'DATA_CACHE_CHECK' => false, // 数据缓存是否校验缓存 'DATA_CACHE_PREFIX' => '', // 缓存前缀 'DATA_CACHE_TYPE' => 'File', // 数据缓存类型,支持:File|Db|Apc|Memcache|Shmop|Sqlite|Xcache|Apachenote|Eaccelerator 'DATA_CACHE_PATH' => TEMP_PATH,// 缓存路径设置 (仅对File方式缓存有效) 'DATA_CACHE_KEY' => '', // 缓存文件KEY (仅对File方式缓存有效) 'DATA_CACHE_SUBDIR' => false, // 使用子目录缓存 (自动根据缓存标识的哈希创建子目录) 'DATA_PATH_LEVEL' => 1, // 子目录缓存级别 /* 错误设置 */ 'ERROR_MESSAGE' => '页面错误!请稍后再试~',//错误显示信息,非调试模式有效 'ERROR_PAGE' => '', // 错误定向页面 'SHOW_ERROR_MSG' => false, // 显示错误信息 'TRACE_MAX_RECORD' => 100, // 每个级别的错误信息 最大记录数 /* 日志设置 */ 'LOG_RECORD' => false, // 默认不记录日志 'LOG_TYPE' => 'File', // 日志记录类型 默认为文件方式 'LOG_LEVEL' => 'EMERG,ALERT,CRIT,ERR',// 允许记录的日志级别 'LOG_FILE_SIZE' => 2097152, // 日志文件大小限制 'LOG_EXCEPTION_RECORD' => false, // 是否记录异常信息日志 /* SESSION设置 */ 'SESSION_AUTO_START' => true, // 是否自动开启Session 'SESSION_OPTIONS' => array(), // session 配置数组 支持type name id path expire domain 等参数 'SESSION_TYPE' => '', // session hander类型 默认无需设置 除非扩展了session hander驱动 'SESSION_PREFIX' => '', // session 前缀 //'VAR_SESSION_ID' => 'session_id', //sessionID的提交变量 /* 模板引擎设置 */ 'TMPL_CONTENT_TYPE' => 'text/html', // 默认模板输出类型 'TMPL_ACTION_ERROR' => THINK_PATH.'Tpl/dispatch_jump.tpl', // 默认错误跳转对应的模板文件 'TMPL_ACTION_SUCCESS' => THINK_PATH.'Tpl/dispatch_jump.tpl', // 默认成功跳转对应的模板文件 'TMPL_EXCEPTION_FILE' => THINK_PATH.'Tpl/think_exception.tpl',// 异常页面的模板文件 'TMPL_DETECT_THEME' => false, // 自动侦测模板主题 'TMPL_TEMPLATE_SUFFIX' => '.html', // 默认模板文件后缀 'TMPL_FILE_DEPR' => '/', //模板文件CONTROLLER_NAME与ACTION_NAME之间的分割符 // 布局设置 'TMPL_ENGINE_TYPE' => 'Think', // 默认模板引擎 以下设置仅对使用Think模板引擎有效 'TMPL_CACHFILE_SUFFIX' => '.php', // 默认模板缓存后缀 'TMPL_DENY_FUNC_LIST' => 'echo,exit', // 模板引擎禁用函数 'TMPL_DENY_PHP' => false, // 默认模板引擎是否禁用PHP原生代码 'TMPL_L_DELIM' => '{', // 模板引擎普通标签开始标记 'TMPL_R_DELIM' => '}', // 模板引擎普通标签结束标记 'TMPL_VAR_IDENTIFY' => 'array', // 模板变量识别。留空自动判断,参数为'obj'则表示对象 'TMPL_STRIP_SPACE' => true, // 是否去除模板文件里面的html空格与换行 'TMPL_CACHE_ON' => true, // 是否开启模板编译缓存,设为false则每次都会重新编译 'TMPL_CACHE_PREFIX' => '', // 模板缓存前缀标识,可以动态改变 'TMPL_CACHE_TIME' => 0, // 模板缓存有效期 0 为永久,(以数字为值,单位:秒) 'TMPL_LAYOUT_ITEM' => '{__CONTENT__}', // 布局模板的内容替换标识 'LAYOUT_ON' => false, // 是否启用布局 'LAYOUT_NAME' => 'layout', // 当前布局名称 默认为layout // Think模板引擎标签库相关设定 'TAGLIB_BEGIN' => '<', // 标签库标签开始标记 'TAGLIB_END' => '>', // 标签库标签结束标记 'TAGLIB_LOAD' => true, // 是否使用内置标签库之外的其它标签库,默认自动检测 'TAGLIB_BUILD_IN' => 'cx', // 内置标签库名称(标签使用不必指定标签库名称),以逗号分隔 注意解析顺序 'TAGLIB_PRE_LOAD' => '', // 需要额外加载的标签库(须指定标签库名称),多个以逗号分隔 /* URL设置 */ 'URL_CASE_INSENSITIVE' => true, // 默认false 表示URL区分大小写 true则表示不区分大小写 'URL_MODEL' => 1, // URL访问模式,可选参数0、1、2、3,代表以下四种模式: // 0 (普通模式); 1 (PATHINFO 模式); 2 (REWRITE 模式); 3 (兼容模式) 默认为PATHINFO 模式 'URL_PATHINFO_DEPR' => '/', // PATHINFO模式下,各参数之间的分割符号 'URL_PATHINFO_FETCH' => 'ORIG_PATH_INFO,REDIRECT_PATH_INFO,REDIRECT_URL', // 用于兼容判断PATH_INFO 参数的SERVER替代变量列表 'URL_REQUEST_URI' => 'REQUEST_URI', // 获取当前页面地址的系统变量 默认为REQUEST_URI 'URL_HTML_SUFFIX' => 'html', // URL伪静态后缀设置 'URL_DENY_SUFFIX' => 'ico|png|gif|jpg', // URL禁止访问的后缀设置 'URL_PARAMS_BIND' => true, // URL变量绑定到Action方法参数 'URL_PARAMS_BIND_TYPE' => 0, // URL变量绑定的类型 0 按变量名绑定 1 按变量顺序绑定 'URL_PARAMS_FILTER' => false, // URL变量绑定过滤 'URL_PARAMS_FILTER_TYPE'=> '', // URL变量绑定过滤方法 如果为空 调用DEFAULT_FILTER 'URL_ROUTER_ON' => false, // 是否开启URL路由 'URL_ROUTE_RULES' => array(), // 默认路由规则 针对模块 'URL_MAP_RULES' => array(), // URL映射定义规则 /* 系统变量名称设置 */ 'VAR_MODULE' => 'm', // 默认模块获取变量 'VAR_ADDON' => 'addon', // 默认的插件控制器命名空间变量 'VAR_CONTROLLER' => 'c', // 默认控制器获取变量 'VAR_ACTION' => 'a', // 默认操作获取变量 'VAR_AJAX_SUBMIT' => 'ajax', // 默认的AJAX提交变量 'VAR_JSONP_HANDLER' => 'callback', 'VAR_PATHINFO' => 's', // 兼容模式PATHINFO获取变量例如 ?s=/module/action/id/1 后面的参数取决于URL_PATHINFO_DEPR 'VAR_TEMPLATE' => 't', // 默认模板切换变量 'VAR_AUTO_STRING' => false, // 输入变量是否自动强制转换为字符串 如果开启则数组变量需要手动传入变量修饰符获取变量 'HTTP_CACHE_CONTROL' => 'private', // 网页缓存控制 'CHECK_APP_DIR' => true, // 是否检查应用目录是否创建 'FILE_UPLOAD_TYPE' => 'Local', // 文件上传方式 'DATA_CRYPT_TYPE' => 'Think', // 数据加密方式 ); >>>>>>> 98b56c4fd74d8c0bc5ebc0c352b176e8d8f7d926
Java
"use strict"; import {Vector2, Vector3, Matrix4, Vector4} from 'vectormath'; /* NOTE: this was originally a WebGL UI library I wrote. it's gone through several transitions since then, and is now a canvas2d UI library (bleh). the code is quite horrible. */ #include "src/utils/utildefine.js" //we keep track of any canvases with non-GC managed data, //(gl objects, TriListAlloc, TA_Alloc, etc) to avoid reference leaks //g_app_state.reset calls .destroy() on all canvases inside this list. //(then resets it back to {}). window.active_canvases = {}; window._canvas_draw_id = 1; //disable use of theoretically faster typed array allocator, //for now. //#ifdef NOCACHE #define F32ALLOC(verts) new Float32Array(verts); #define F32FREE(verts) verts = undefined; /*#else -#define F32ALLOC(verts123) f32_alloc.from_array(verts123); -#define F32FREE(verts123) if (verts123 != undefined) { f32_alloc.free(verts123); verts123 = undefined;} #endif */ // // //stupid statics var _trilist_n0 = new Vector3(); var _trilist_n1 = new Vector3() var _trilist_n2 = new Vector3(); var _trilist_n3 = new Vector3() var _trilist_v1 = new Vector3(); var _trilist_v2 = new Vector3() var _trilist_v3 = new Vector3(); var _trilist_v4 = new Vector3() var _trilist_c1 = new Vector4(); var _trilist_c2 = new Vector4() var _trilist_c3 = new Vector4(); var _trilist_c4 = new Vector4() var _trilist_v5 = new Vector3(); var _trilist_v6 = new Vector3(); var _trilist_v7 = new Vector3(); var _trilist_v8 = new Vector3(); var _trilist_v9 = new Vector3(); #define TRILIST_CACHE_SIZE 8192 /*I hate garbage collected languages. Bleh! This class is necessary to avoid object allocations within draw frames. evil!*/ export class TriListAlloc { constructor() { this.freelist = []; this.freecount = 0; this.usedcount = 0; this.peakcount = 0; } alloc(UICanvas canvas, Matrix4 transmat, Boolean use_small_icons=false) : TriList { this.peakcount = Math.max(this.peakcount, this.usedcount+1); #ifdef NOCACHE return new TriList(canvas, transmat, use_small_icons); #endif if (this.freecount == 0) { //ensure a saturated cache if (this.usedcount == 0) { for (var i=0; i<TRILIST_CACHE_SIZE; i++) { var tl = new TriList(canvas, transmat, use_small_icons); tl.cache_destroy(); this.freelist.push(tl); this.freecount++; } } this.usedcount++; return new TriList(canvas, transmat, use_small_icons); } else { //console.log("using cached trilist", this.freecount, this.freelist.length); var ret = this.freelist.pop(); ret.cache_init(canvas, transmat, use_small_icons); this.freecount--; this.usedcount++; return ret; } } free(TriList trilist) { this.usedcount--; #ifdef NOCACHE trilist.cache_destroy(); return; #endif //abandon trilist to the GC if (this.freecount >= TRILIST_CACHE_SIZE) return; trilist.cache_destroy(); this.freelist.push(trilist); this.freecount++; } } var _talloc = new TriListAlloc(); /* TriList is being refactored to make it more usable. vertex buffers will be reused, and transformation matrices will be passed in at draw time, not applied at vertex generation time. */ export class TriListRef { constructor(gl, TriList trilist, Matrix4 mat, UICanvas canvas) { this.trilist = trilist; this.mat = mat; this.workmat = new Matrix4(); this.gl = gl; this.canvas = canvas; } destroy() { } on_draw(WebGLRenderingContext gl) { this.workmat.load(this.mat); this.workmat.multiply(this.canvas.global_matrix); this.trilist.global_matrix = this.workmat; this.trilist.on_draw(gl); } } export class TriListCache { constructor(limit=100) { this.cache = {}; this.length = 0; this.limit = limit; } get(String key) : TriList { return this.cache[key]; } has(String key) : Boolean { return key in this.cache; } set(String key, TriList trilist) { if (!(key in this.cache)) { this.length++; } this.cache[key] = trilist; } remove(String key) { if (key in this.cache) { this.cache[key].destroy(); this.length--; delete this.cache[key]; } } destroy() { for (var k in this.cache) { var tl = this.cache[k]; tl.destroy(); } this.cache = {}; this.length = 0; } on_gl_lost() { this.length = 0; this.cache = {}; } } export class TriList { cache_destroy() { this._free_typed(); this.verts.length = 0; this.texcos.length = 0; this.colors.length = 0; this.tottri = 0; //this.canvas = undefined; //this.iconsheet = undefined; //this.viewport = undefined; this._dead = true; } _free_typed() { //f32free sets vertbuf/colorbuf/texbuf to undefined F32FREE(this.vertbuf); F32FREE(this.colorbuf); F32FREE(this.texbuf); } cache_init(UICanvas canvas, Matrix4 transmat, Boolean use_small_icons=false) { this._dead = false; this.transmat = transmat; this.global_matrix = canvas.global_matrix; this.use_tex = 1; this.tex = 0 : WebGLTexture; this.iconsheet = use_small_icons ? g_app_state.raster.iconsheet16 : g_app_state.raster.iconsheet; this.small_icons = use_small_icons; this.verts.length = 0; this.colors.length = 0; this.texcos.length = 0; this.recalc = 1 this.tottri = 0; this.canvas = canvas this.spos = undefined : Array<float>; this.ssize = undefined : Array<float>; this.gl_spos = undefined : Array<float>; this.gl_ssize = undefined : Array<float>; this.viewport = canvas != undefined ? canvas.viewport : undefined; } constructor(UICanvas canvas, Matrix4 transmat, Boolean use_small_icons=false) { this._id = _canvas_draw_id++; this.transmat = transmat; this.global_matrix = canvas.global_matrix; this.verts = []; this.colors = []; this.texcos = []; this._dead = false; this.vertbuf = undefined; this.colorbuf = undefined; this.texbuf = undefined; this.use_tex = 1; this.tex = 0 : WebGLTexture; this.iconsheet = use_small_icons ? g_app_state.raster.iconsheet16 : g_app_state.raster.iconsheet; this.small_icons = use_small_icons; this.recalc = 1 this.tottri = 0; this.canvas = canvas this.spos = undefined : Array<float>; this.ssize = undefined : Array<float>; this.gl_spos = undefined : Array<float>; this.gl_ssize = undefined : Array<float>; this.viewport = canvas != undefined ? canvas.viewport : undefined; } add_tri(Array<float> v1, Array<float> v2, Array<float> v3, Array<float> c1, Array<float> c2, Array<float> c3, Array<float> t1, Array<float> t2, Array<float> t3) { var vs = this.verts; this.tottri++; static v12 = new Vector3(); static v22 = new Vector3(); static v32 = new Vector3(); v12.loadxy(v1); v22.loadxy(v2); v32.loadxy(v3); v1 = v12; v2 = v22; v3 = v32; this.transform(v1); this.transform(v2); this.transform(v3); vs.push(v1[0]); vs.push(v1[1]); vs.push(v1[2]); vs.push(v2[0]); vs.push(v2[1]); vs.push(v2[2]); vs.push(v3[0]); vs.push(v3[1]); vs.push(v3[2]); var cs = this.colors if (c2 == undefined) { c2 = c1; c3 = c1; } cs.push(c1[0]); cs.push(c1[1]); cs.push(c1[2]); cs.push(c1[3]); cs.push(c2[0]); cs.push(c2[1]); cs.push(c2[2]); cs.push(c2[3]); cs.push(c3[0]); cs.push(c3[1]); cs.push(c3[2]); cs.push(c3[3]); if (this.use_tex) { if (t1 == undefined) { static negone = [-1, -1]; t1 = t2 = t3 = negone; } var ts = this.texcos ts.push(t1[0]); ts.push(t1[1]); ts.push(t2[0]); ts.push(t2[1]); ts.push(t3[0]); ts.push(t3[1]) } } add_quad(Vector3 v1, Vector3 v2, Vector3 v3, Vector3 v4, Array<float> c1,Array<float> c2,Array<float> c3, Array<float> c4,Array<float> t1,Array<float> t2, Array<float> t3,Array<float> t4) { this.add_tri(v1, v2, v3, c1, c2, c3, t1, t2, t3); this.add_tri(v1, v3, v4, c1, c3, c4, t1, t3, t4); } icon_quad(int icon, Vector3 pos, Array<Array<float>> cs) { static tcos = new Array(0); //var clr = [1, 1, 1, 1]; //var cs = [clr, clr, clr, clr]; var cw = this.iconsheet.cellsize[0], ch = this.iconsheet.cellsize[1]; var v1 = new Vector3([pos[0], pos[1], 0.0]); var v2 = new Vector3([pos[0], pos[1]+ch, 0.0]); var v3 = new Vector3([pos[0]+cw, pos[1]+ch, 0.0]); var v4 = new Vector3([pos[0]+cw, pos[1], 0.0]); tcos.length = 0; this.iconsheet.gen_tile(icon, tcos); var t1 = new Vector3([tcos[0], tcos[1], 0]); var t2 = new Vector3([tcos[2], tcos[3], 0]); var t3 = new Vector3([tcos[4], tcos[5], 0]); var t4 = new Vector3([tcos[6], tcos[7], 0]); var t5 = new Vector3([tcos[8], tcos[9], 0]); var t6 = new Vector3([tcos[10], tcos[11], 0]); this.add_tri(v1, v2, v3, cs[0], cs[1], cs[2], t1, t2, t3); this.add_tri(v1, v3, v4, cs[0], cs[2], cs[3], t4, t5, t6); } transform(v) { static transvec = new Vector3(); transvec[0] = v[0]; transvec[1] = v[1]; transvec[2] = 0.0; transvec.multVecMatrix(this.transmat); v[0] = (transvec[0]/this.viewport[1][0])*2.0 - 1.0; v[1] = (transvec[1]/this.viewport[1][1])*2.0 - 1.0; } line(v1, v2, c1, c2=undefined, width=undefined) { //c2 and width are optional if (c2 == undefined) { c2 = c1; } if (v1.length == 2) v1.push(0); if (v2.length == 2) v2.push(0); this.line_strip(CACHEARR2(CACHEARR2(v1, v2), CACHEARR2(c1, c2)), undefined, width); //this.line_strip(objcache.getarr(objcache.getarr(v1, v2), objcache.getarr(c1, c2)), undefined, width); } line_strip(lines, colors, texcos=undefined, width=2.0, half=false) { static black = new Vector4([0.0, 0.0, 0.0, 1.0]); static v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(); static v3 = new Vector3(), v4 = new Vector3(), n0 = new Vector3(); static n1 = new Vector3(), n2 = new Vector3(), c3 = new Vector3(); static c4 = new Vector3(); for (var i =0; i<lines.length; i++) { var lc1 = colors[i][0], lc2 = colors[i][1]; //if (lines[i][0].length == 2) lines[i][0].push(0); //if (lines[i][1].length == 2) lines[i][1].push(0); if (lc1 == undefined) lc1 = black; if (lc2 == undefined) lc2 = black; var z = 0.0; v1.loadxy(lines[i][0]) v2.loadxy(lines[i][1]) n0.zero(); n1.zero(); n2.zero(); v1.loadxy(lines[i][1]); v1.sub(lines[i][0]); v1.normalize(); n1[0] = v1[1]; n1[1] = -v1[0]; n1[2] = z; n1.normalize() if (i > 0) { v0.loadxy(lines[i-1][1]); v0.sub(lines[i-1][0]) v0.normalize(); n0[0] = v0[1]; n0[1] = -v0[0]; n0[2] = z; n0.normalize() } else { n0.load(n1); } v1.loadxy(lines[i][1]); v1.sub(lines[i][0]) if (i < lines.length-1) { v3.loadxy(lines[i+1][1]); v3.sub(lines[i+1][0]); v3.normalize(); n2[0] = v3[1]; n2[1] = -v3[0]; n2[2] = z; n2.normalize() } else { n2.load(n1); } /* n0.normalize(); n1.normalize(); n2.normalize(); n0.mulScalar(0.5); n1.mulScalar(0.5); n2.mulScalar(0.5); */ n2.add(n1).normalize(); n1.add(n0).normalize(); n1.mulScalar(width*0.5); n2.mulScalar(width*0.5); v0.loadxy(lines[i][0]); v1.loadxy(lines[i][1]); v2.loadxy(lines[i][1]); v2.add(n1); v3.loadxy(lines[i][0]); v3.add(n2); var c1 = _trilist_c1.load(lc1); var c2 = _trilist_c2.load(lc2); var c3 = _trilist_c3.load(lc2); var c4 = _trilist_c4.load(lc1); if (width >= 1.5) { c3[3] = 0.0; c4[3] = 0.0; } n1.mulScalar(2.0); n2.mulScalar(2.0); if (this.use_tex && texcos) { if (!half) this.add_quad(v0, v1, v2, v3, c1, c2, c3, c4, texcos[i][0], texcos[i][1], texcos[i][0], texcos[i][1]); this.add_quad(v1, v0, v3.sub(n1), v2.sub(n2), c2, c1, c3, c4, texcos[i][0], texcos[i][1], texcos[i][0], texcos[i][1]); } else { if (!half) this.add_quad(v0, v1, v2, v3, c1, c2, c3, c4); this.add_quad(v1, v0, v3.sub(n2), v2.sub(n1), c2, c1, c3, c4); } } } destroy(Boolean only_gl=false) { var gl = g_app_state.gl; if (this.vbuf) { gl.deleteBuffer(this.vbuf); gl.deleteBuffer(this.cbuf); } if (this.tbuf) { gl.deleteBuffer(this.tbuf); } this.vbuf = this.cbuf = this.tbuf = undefined; this.recalc = 1; this._free_typed(); if (!only_gl) { this._dead = true; _talloc.free(this); } } gen_buffers(gl) { if (this.verts.length == 0) return; this.destroy(true); this._free_typed(); this._dead = false; this.vertbuf = F32ALLOC(this.verts); //new Float32Array(this.verts) this.colorbuf = F32ALLOC(this.colors); //new Float32Array(this.colors) if (this.use_tex) this.texbuf = F32ALLOC(this.texcos); //new Float32Array(this.texcos); gl.enableVertexAttribArray(0); gl.enableVertexAttribArray(1); if (this.use_tex) gl.enableVertexAttribArray(2); else gl.disableVertexAttribArray(2); var vbuf = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, vbuf); gl.bufferData(gl.ARRAY_BUFFER, this.vertbuf, gl.STATIC_DRAW); gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 0, 0); gl.bindBuffer(gl.ARRAY_BUFFER, vbuf); var cbuf = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, cbuf); gl.bufferData(gl.ARRAY_BUFFER, this.colorbuf, gl.STATIC_DRAW); gl.vertexAttribPointer(1, 4, gl.FLOAT, false, 0, 0); gl.bindBuffer(gl.ARRAY_BUFFER, cbuf); if (this.use_tex) { var tbuf = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, tbuf); gl.bufferData(gl.ARRAY_BUFFER, this.texbuf, gl.STATIC_DRAW); gl.vertexAttribPointer(2, 2, gl.FLOAT, false, 0, 0); gl.bindBuffer(gl.ARRAY_BUFFER, tbuf); this.tbuf = tbuf } this.vbuf = vbuf; this.cbuf = cbuf; gl.disableVertexAttribArray(1); gl.disableVertexAttribArray(2); this.recalc = 0; } on_draw(gl) { if (!this.iconsheet.ready) return; //if (this._dead) // return; if (this.verts.length == 0) return; if (this.recalc || (this.tdrawbuf != undefined && this.tdrawbuf.is_dead)) { this.gen_buffers(gl); } if (this.ssize != undefined) { gl.enable(gl.SCISSOR_TEST); // g_app_state.raster.push_scissor(this.spos, this.ssize); } gl.disable(gl.DEPTH_TEST); gl.enable(gl.BLEND); gl_blend_func(gl); //gl.blendEquation(gl.BLEND_EQUATION); //gl.blendEquationSeparate(gl.BLEND_EQUATION, gl.BLEND_EQUATION); gl.enableVertexAttribArray(0); gl.enableVertexAttribArray(1); gl.disableVertexAttribArray(3); gl.disableVertexAttribArray(4); gl.bindBuffer(gl.ARRAY_BUFFER, this.vbuf); gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 0, 0); gl.bindBuffer(gl.ARRAY_BUFFER, this.vbuf); gl.bindBuffer(gl.ARRAY_BUFFER, this.cbuf); gl.vertexAttribPointer(1, 4, gl.FLOAT, false, 0, 0); gl.bindBuffer(gl.ARRAY_BUFFER, this.cbuf); if (this.use_tex) { gl.enableVertexAttribArray(2); gl.bindBuffer(gl.ARRAY_BUFFER, this.tbuf); gl.vertexAttribPointer(2, 2, gl.FLOAT, false, 0, 0); gl.bindBuffer(gl.ARRAY_BUFFER, this.tbuf); } else { gl.disableVertexAttribArray(2); } gl.activeTexture(gl.TEXTURE4); gl.bindTexture(gl.TEXTURE_2D, this.iconsheet.tex); gl.useProgram(gl.basic2d.program); this.global_matrix.setUniform(gl, gl.basic2d.uniformloc(gl, "mat")); gl.uniform1i(gl.basic2d.uniformloc(gl, "iconsampler"), 4); //console.log(this.verts); //console.log(this.tottri*3, this.verts.length/3, this.colors.length/4, this.verts[0], this.verts[1], this.verts[2]) gl.drawArrays(gl.TRIANGLES, 0,this.tottri*3); gl.disableVertexAttribArray(1); gl.disableVertexAttribArray(2); gl.enable(gl.DEPTH_TEST); if (this.ssize != undefined) { //g_app_state.raster.pop_scissor(); } } } /* var MAX_TRILIST_CACHE = 512; var _trilist_frame_counter = 0; var _trilist_template = {obj : new TriList(undefined, undefined), cachesize : MAX_TRILIST_CACHE}; function _reset_trilist_frame_counter() { _trilist_frame_counter = 0; } function _new_trilist(UICanvas canvas) { if (_trilist_frame_counter = 0 >= MAX_TRILIST_CACHE) { return new TriList(canvas); } else { var list = objcache.fetch(_trilist_template) TriList.call(list, canvas); } } function _save_trilist(TriList trilist) { if (objcache.is_cache_obj(trilist)) { objcache.cache_remove(trilist); } } */ export class TextDraw { constructor(pos, text, color, spos, ssize, viewport, size, scale, global_matrix, rot=0) { this._id = _canvas_draw_id++; this.rot = rot; this.global_matrix = global_matrix; this.text = text; this.pos = [pos[0], pos[1], pos[2]]; this.color = color; this.tdrawbuf = undefined : TextDrawBuffer; this.spos = spos; this.ssize = ssize; this.asp = viewport[1][1] / viewport[1][0]; this.viewport = viewport; this.scale = [scale[0], scale[1], 0]; this.size = size; this.raster = g_app_state.raster; var mat = new Matrix4(); mat.translate(this.pos[0], this.pos[1], 0.0); //denormalize to avoid squashed rotations mat.scale(1, 1.0/this.asp, 1); mat.rotate(0, 0, rot); mat.scale(this.scale); //norrmalize again mat.scale(1, this.asp, 1); this.mat = mat; } destroy() { /*don't destroy the gl buffers here, since I'm now caching them*/ /* if (this.tdrawbuf != undefined) this.tdrawbuf.destroy(); this.tdrawbuf = undefined; */ } toString() : String { return "TD" + this._id; } gen_buffers(gl) { this.tdrawbuf = this.raster.get_font(this.size).gen_text_buffers(gl, this.text, this.color, this.viewport); return this.tdrawbuf; } on_draw(gl) { static identitymat = new Matrix4(); gl.disableVertexAttribArray(4); if (this.tdrawbuf == undefined) this.gen_buffers(gl); var spos, ssize; if (this.ssize != undefined) { spos = CACHEARR3(this.spos[0], this.spos[1], 0); ssize = CACHEARR3(this.ssize[0], this.ssize[1], 0); // g_app_state.raster.push_scissor(spos, ssize); } static mat = new Matrix4(); mat.load(this.global_matrix); mat.multiply(this.mat); this.tdrawbuf.on_draw(gl, mat); if (this.ssize != undefined) { //g_app_state.raster.pop_scissor(); } } } var _ls_static_colors = {reallength: 0, length: 0}; window._box_process_clr = function _box_process_clr(default_cs, clr) { var cs = default_cs; static arr4 = [0, 0, 0, 0]; if (clr != undefined) { if (typeof clr == "number") { var cs2 = arr4; for (var i=0; i<4; i++) { cs2[i] = CACHEARR4(cs[i][0], cs[i][1], cs[i][2], cs[i][3]); for (var j=0; j<4; j++) { cs2[i] *= clr; } } cs = cs2; } else if (typeof clr[0] == "number") { var cs = arr4; cs[0] = clr; cs[1] = clr; cs[2] = clr; cs[3] = clr; } else { cs = clr; } } return cs; } //XXX XXX! export class UICanvas_ { constructor(viewport) { static _id = 1; this._id = _id++; this.global_matrix = new Matrix4(); this.iconsheet = g_app_state.raster.iconsheet; this.iconsheet16 = g_app_state.raster.iconsheet16; this.viewport = viewport; this.raster = g_app_state.raster; this.trilist = _talloc.alloc(this, this.transmat); this.textcache = {}; this.textcachelen = 0; this.max_textcache = 64; this.boxcache = new TriListCache(); this.trans_stack = [] this.transmat = new Matrix4() this.drawlists = [this.trilist] this.textlist = []; this.stack = [] this.cache = new hashtable(); this.oldcache = new hashtable(); this.uncached = new Array(); this.uncached.push(this.trilist); this.scissor_stack = new Array(); this.flag = 0; } ensure_trilist() { if (this.drawlists.length == 0 || !(this.drawlists[this.drawlists.length-1] instanceof TriList)) { this.new_trilist(); } } set_viewport(viewport) { var bad = false; for (var i=0; i<3; i++) { if (viewport[1][i] != this.viewport[1][i]) bad = true; } this.viewport = viewport; if (bad) { this.on_resize(viewport[1], viewport[1]); } } on_gl_lost(WebGLRenderingContext new_gl) { this.boxcache.on_gl_lost(); if (this.gl === new_gl) { console.trace(); console.log("Warning: uicanvas.on_gl_lost() called multiple times"); return; } this.gl = new_gl; this.drawlists = new Array(); this.iconsheet = g_app_state.raster.iconsheet; this.iconsheet16 = g_app_state.raster.iconsheet16; this.textcache = {}; this.textcachelen = 0; this.stack = [] this.raster = g_app_state.raster; this.cache = new hashtable(); this.oldcache = new hashtable(); this.boxcache = UICanvas.boxcache; this.new_trilist(); //now that gl data is destroyed, //call .reset to maintain data structure integrity this.reset(); } push_scissor(pos, size) { var oldpos = pos; pos = new Vector3([pos[0], pos[1], 0]); size = new Vector3([size[0], size[1], 0]); pos.multVecMatrix(this.transmat); size.multVecMatrix(this.transmat); var vx=this.viewport[0][0], vy=this.viewport[0][1] pos[0] += vx; pos[1] += vy; var dx = pos[0]-oldpos[0]-vx, dy = pos[1]-oldpos[1]-vy; size[0] -= dx; size[1] -= dy; for (var i=0; i<3; i++) { pos[i] = Math.floor(pos[i]); size[i] = Math.ceil(size[i]); } this.scissor_stack.push([pos, size]); this.new_trilist(); } pop_scissor() { this.scissor_stack.pop(); this.new_trilist(); } new_trilist(Boolean use_small_icons=false) { //flag canvas for memory leak detection, see active_canvases's definition active_canvases[this._id] = this; this.trilist = _talloc.alloc(this, this.transmat, use_small_icons); //new TriList(this, use_small_icons); if (this.scissor_stack.length > 0) { this.trilist.spos = this.scissor_stack[this.scissor_stack.length-1][0]; this.trilist.ssize = this.scissor_stack[this.scissor_stack.length-1][1]; } this.drawlists.push(this.trilist); return this.trilist; } translate(Array<float> off) { this.transmat.translate(off[0], off[1], 0.0); } push_transform(mat=undefined) { this.trans_stack.push(new Matrix4(this.transmat)); if (mat != undefined) this.transmat.multiply(mat); } pop_transform() { this.transmat.load(this.trans_stack.pop()); } frame_begin(Object item) { return;//XXX if (DEBUG.ui_canvas) { console.log("canvas start, stack length: ", this.stack.length); } this.new_trilist(); this.stack.push(this.drawlists.length-1); } frame_end(Object item) { return;//XXX var arr = new Array() var start = this.stack[this.stack.length-1]; this.stack.pop(); if (DEBUG.ui_canvas) console.log(start); for (var i=start; i<this.drawlists.length; i++) { arr.push(this.drawlists[i]); } this.cache.set(item, arr); this.new_trilist(); if (DEBUG.ui_canvas) { console.log("canvas end, stack length: ", this.stack.length); } return arr; } begin(Object item) { //okay, individual leaf element caching may not have been a good //idea. . . //-XXX return; if (DEBUG.ui_canvas) { console.log("canvas start, stack length: ", this.stack.length); } this.new_trilist(); this.stack.push(this.drawlists.length-1); } end(Object item) { //-XXX; return; var arr = new Array() var start = this.stack.pop(this.stack.length-1); if (DEBUG.ui_canvas) console.log(start); for (var i=start; i<this.drawlists.length; i++) { arr.push(this.drawlists[i]); } this.stack.pop(); this.cache.set(item, arr); this.new_trilist(); if (DEBUG.ui_canvas) { console.log("canvas end, stack length: ", this.stack.length); } return arr; } use_cache(Object item) { if (this.oldcache.has(item)) { var arr = this.oldcache.get(item); for (var i=0; i<arr.length; i++) { this.drawlists.push(arr[i]); if (arr[i] instanceof TextDraw) this.textlist.push(arr[i]); } this.oldcache.remove(item); this.cache.set(item, arr); this.new_trilist(); } } has_cache(Object item) { return this.oldcache.has(item); } remove_cache(Object item) { if (this.oldcache.has(item)) this.oldcache.remove(item); } textsize(text, size=default_ui_font_size) { var box = this.raster.get_font(size).calcsize(text); return [box[0], box[1]]; } line(v1, v2, c1, c2=c1, width=2.0) { this.ensure_trilist(); this.line_strip([[v1, v2]], [[c1, c2]], undefined, width); } line_strip(lines, colors, texcos, width, half) {//colors,texcos,width are optional this.ensure_trilist(); if (colors == undefined) { colors = uicolors["DefaultLine"]; } if (typeof(colors[0]) == "number") { var clr = colors; colors =_ls_static_colors; for (var i=0; i<lines.length; i++) { if (colors[i] == undefined) { colors[i] = [clr, clr]; } else { colors[i][0] = clr; colors[i][1] = clr; } } colors.reallength = Math.max(colors.reallength, i); colors.length = i; } this.trilist.line_strip(lines, colors, texcos, width, half); } line_loop(points, colors, texcos, width, half) { //colors,texcos,width are optional var lines = [] this.ensure_trilist(); if (colors == undefined) { colors = uicolors["DefaultLine"]; } var lcolors; if (typeof colors[0] != "number") lcolors = [] else lcolors = [] for (var i=0; i<points.length; i++) { var i2 = (i+1)%points.length; lines.push([points[i], points[i2]]); if (typeof(colors[0]) != "number") { lcolors.push([colors[i], colors[i2]]); } else { lcolors.push([colors, colors]); } } this.line_strip(lines, lcolors, undefined, width, half); } quad(v1, v2, v3, v4, c1, c2, c3, c4) { this.ensure_trilist(); if (v1.length == 2) v1.push(0); if (v2.length == 2) v2.push(0); if (v3.length == 2) v3.push(0); if (v4.length == 2) v4.push(0); this.trilist.add_quad(v1, v2, v3, v4, c1, c2, c3, c4); } quad_aa(v1, v2, v3, v4, c1, c2, c3, c4) { this.ensure_trilist(); if (v1.length == 2) v1.push(0); if (v2.length == 2) v2.push(0); if (v3.length == 2) v3.push(0); if (v4.length == 2) v4.push(0); if (c2 == undefined) { c2 = c3 = c4 = c1; } this.trilist.add_quad(v1, v2, v3, v4, c1, c2, c3, c4); var lines = [[v1, v4], [v4, v3], [v3, v2], [v2, v1]]; var colors = [[c1, c4], [c4, c3], [c3, c2], [c2, c1]]; this.trilist.line_strip(lines, colors, undefined, undefined, true) } tri(v1, v2, v3, c1, c2, c3) { this.ensure_trilist(); if (v1.length == 2) v1.push(0); if (v2.length == 2) v2.push(0); if (v3.length == 2) v3.push(0); this.trilist.add_tri(v1, v2, v3, c1, c2, c3); } on_draw(gl) { //Set the viewport and projection matrix for the scene gl.viewport(this.viewport[0][0], this.viewport[0][1], this.viewport[1][0], this.viewport[1][1]); var len = this.drawlists.length; for (var i=0; i<len; i++) { if (DEBUG.canvas_sep_text && this.drawlists[i] instanceof TextDraw) continue; this.drawlists[i].on_draw(gl); } if (DEBUG.canvas_sep_text) { var len = this.textlist.length; for (var i=0; i<len; i++) { this.textlist[i].on_draw(gl); } } } arc_points(pos, start, arc, r, steps) {//steps is optional if (steps == undefined) { steps = Math.floor(6*arc/Math.PI); } var f, df; var f = start; var df = arc / steps; var points = []; for (var i=0; i<steps+1; i++) { var x = pos[0] + Math.sin(f)*r; var y = pos[1] + Math.cos(f)*r; points.push([x, y, 0]); f += df; } return points; } arc(pos, start, arc, r, clr, half) { if (clr == undefined) { clr = [0.9, 0.8, 0.7, 0.6]; } var steps = 18/(2.0 - arc/(Math.PI*2)); var f, df; var f = start; var df = arc / steps; var points = []; for (var i=0; i<steps+1; i++) { var x = pos[0] + Math.sin(f)*r; var y = pos[1] + Math.cos(f)*r; points.push([x, y, 0]); f += df; } var lines = []; var colors = []; for (var i=0; i<points.length-1; i++) { lines.push([points[i], points[i+1]]) colors.push([clr, clr]) } colors[0][0] = [1.0, 1.0, 0.0, 1.0] colors[0][1] = [1.0, 1.0, 0.0, 1.0] this.trilist.line_strip(lines, colors, undefined, undefined, half); } destroy() { this.reset(); //get rid of any cache data, too for (var k in this.cache) { var arr = this.cache.get(k); for (var i=0; i<arr.length; i++) { arr[i].destroy(); arr[i] = undefined; } } this.boxcache.destroy(); this.cache = new hashtable(); if (this._id in active_canvases) { delete active_canvases[this._id]; } } reset() { /* for (var i=0; i<this.uncached.length; i++) { this.uncached[i].destroy(); this.uncached[i] = undefined; }*/ var dmap = {}; for (var k in this.cache) { var item = this.cache.get(k); for (var i=0; i<item.length; i++) { dmap[item[i]._id] = item[i]; } } var dl = this.drawlists; for (var i=0; i<dl.length; i++) { if (!(dl[i]._id in dmap)) { dl[i].destroy(); } } if (DEBUG.canvas_sep_text) { var tl = this.textlist; for (var i=0; i<tl.length; i++) { tl[i].destroy(); } this.textlist.length = 0; } this.uncached.length = 0; this.scissor_stack.length = 0; /*destroy old cache that was used in last draw cycle, then swap it with the new cache that was *built* last cycle.*/ for (var k in this.oldcache) { var arr = this.oldcache.get(k) for (var i=0; i<arr.length; i++) { arr[i].destroy(); arr[i] = undefined; } } this.oldcache = this.cache; this.cache = new hashtable(); this.drawlists.length = 0; if (this.trans_stack.length > 0) { this.trans_stack[0].makeIdentity(); this.trans_stack.length = 1; } else { this.trans_stack.length = 0; this.trans_stack.push(new Matrix4()); } this.transmat = this.trans_stack[0]; this.stack.length = 0; this.new_trilist(); } invbox(pos, size, clr, r) { var cs = uicolors["InvBox"] cs = _box_process_clr(cs, clr); this.box(pos, size, cs, r); } simple_box(pos, size, clr=undefined, r=2.0) { //clr is optional var cs = uicolors["SimpleBox"] cs = _box_process_clr(cs, clr); this.box(pos, size, cs, r); } hlightbox(pos, size, clr_mul, r) { //clr_mul is optional var cs = uicolors["HLightBox"] /*if (clr != undefined) { cs = [clr, clr, clr, clr] }*/ if (clr_mul != undefined) { cs = [new Vector4(cs[0]), new Vector4(cs[1]), new Vector4(cs[2]), new Vector4(cs[3])] for (var i=0; i<4; i++) { for (var j=0; j<4; j++) { cs[i][j] *= clr_mul; } } } this.box(pos, size, cs, r); } box_outline(pos, size, clr, rfac) { this.box(pos, size, clr, rfac, true); } shadow_box(pos, size, steps=6, margin=[6, 6], clr=uicolors["ShadowBox"]) { static neg1 = [-2, -2]; //arg, can't remember the correct formula to use here //x**steps = 0.1 //x = 0.1**(1.0/steps) var fac = (1.0/steps)*0.4; var clr = [clr[0], clr[1], clr[2], clr[3]*fac] pos = new Vector2(pos); size = new Vector2(size); expand_rect2d(pos, size, margin); for (var i=0; i<steps; i++) { this.box(pos, size, clr); expand_rect2d(pos, size, neg1); } } box(pos, size, clr, rfac, outline_only) { if (IsMobile || rfac == 0.0) return this.box2(pos, size, clr, rfac, outline_only); else //XXX return this.box1(pos, size, clr, rfac, outline_only); } /* I think this word is Dutch. it comes from photography, it means to dim the screen around a rectangle of interest. need to look up the english word. and no, I'm not Dutch. */ passpart(pos, size, clr=[0,0,0,0.5]) { this.ensure_trilist(); var p = this.viewport[0]; var s = this.viewport[1]; this.box2([p[0], p[1]], [pos[0], s[1]], clr); this.box2([p[0]+pos[0]+size[0], p[1]], [s[0]-pos[0]-size[0], s[1]], clr); this.box2([pos[0]+p[0], pos[1]+p[1]+size[1]], [size[0], s[1]-size[1]-p[1]], clr); this.box2([pos[0]+p[0], p[1]], [size[0], pos[1]], clr) } icon(int icon, Array<float> pos, float alpha=1.0, Boolean small=false, Array<float> clr=undefined) { static white = [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]; var cs = _box_process_clr(white, clr); for (var i=0; i<4; i++) { cs[i][3] = alpha; } this.ensure_trilist(); if (this.trilist.small_icons != small) { this.new_trilist(small); } this.trilist.icon_quad(icon, pos, cs); } box2(Array<float> pos, Array<float> size, Array<float> clr=undefined, float rfac=undefined, Boolean outline_only=false) { this.ensure_trilist(); var cs = uicolors["Box"]; cs = _box_process_clr(cs, clr); var x = pos[0], y=pos[1]; var w=size[0], h=size[1]; if (outline_only) { this.line([pos[0], pos[1]], [pos[0], pos[1]+size[1]], clr, clr, 1.0); this.line([pos[0], pos[1]+size[1]], [pos[0]+size[0], pos[1]+size[1]], clr, clr, 1.0); this.line([pos[0]+size[0], pos[1]+size[1]], [pos[0]+size[0], pos[1]], clr, clr, 1.0); this.line([pos[0]+size[0], pos[1]], [pos[0], pos[1]], clr, clr, 1.0); } else { this.trilist.add_quad(CACHEARR3(x, y, 0), CACHEARR3(x+w, y, 0), CACHEARR3(x+w, y+h, 0), CACHEARR3(x, y+h, 0), cs[0], cs[1], cs[2], cs[3]); } } gen_box_trilist(Array<float> size, Array<float> clr=undefined, float rfac=1, Boolean outline_only=false) { var w=size[0], h=size[1]; var start = 0, ang = Math.PI/2, r = 4; var cs = _box_process_clr(uicolors["Box"], clr); var trilist = new TriList(this, new Matrix4(), false); r /= rfac; var p1 = this.arc_points(CACHEARR3(0+r+2, 0+r+2, 0), Math.PI, ang, r); var p2 = this.arc_points(CACHEARR3(0+w-r-2, 0+r+2, 0), Math.PI/2, ang, r); var p3 = this.arc_points(CACHEARR3(0+w-r-2, 0+h-r-2, 0), 0, ang, r); var p4 = this.arc_points(CACHEARR3(0+r+2, 0+h-r-2, 0), -Math.PI/2, ang, r); var plen = p1.length; p4.reverse(); p3.reverse(); p2.reverse(); p1.reverse(); var points = []; for (var i=0; i<p1.length; i++) { points.push(p1[i]); } for (var i=0; i<p2.length; i++) { points.push(p2[i]); p1.push(p2[i]); } for (var i=0; i<p3.length; i++) { points.push(p3[i]); } p2 = p3; for (var i=0; i<p4.length; i++) { p2.push(p4[i]); points.push(p4[i]); } p2.reverse(); var plen = p1.length; function color(i) { if (i < plen) return cs[0]; else if (i < plen*2) return cs[1]; else if (i < plen*3) return cs[2]; else if (i <= plen*4+1) return cs[3]; } static v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3(), v4 = new Vector3(); #define LOAD_CLR(a, b) a[0] = b[0]; a[1] = b[1]; a[2] = b[2]; if (!outline_only) { for (var i=0; i<p1.length-1; i++) { var i1 = i; var i2 = i+plen*2; var i3 = i + 1+plen*2; var i4 = i+1; LOAD_CLR(v1, p1[i]); LOAD_CLR(v2, p2[i]); LOAD_CLR(v3, p2[i+1]); LOAD_CLR(v4, p1[i+1]); trilist.add_quad(v1, v2, v3, v4, color(i1), color(i2), color(i3), color(i4)); } } var lines = []; var colors = []; static pairs = []; for (var i=0; i<points.length; i++) { LOAD_CLR(v1, points[(i+1)%points.length]); LOAD_CLR(v2, points[i]); if (pairs.length <= i) { pairs.push([[0, 0], [0, 0]]); } pairs[i][0][0] = CACHEARR3(v1[0], v1[1], 0); pairs[i][0][1] = CACHEARR3(v2[0], v2[1], 0); lines.push(pairs[i][0]); pairs[i][1][0] = color((i+1)%points.length); pairs[i][1][1] = color(i); colors.push(pairs[i][1]); } #undef LOAD_CLR trilist.line_strip(lines, colors, undefined, outline_only ? 1.4 : 1.5, !outline_only); return trilist; } box1(Array<float> pos, Array<float> size, Array<float> clr=[0, 0, 0, 1], float rfac=1, Boolean outline_only=false) { var sclr = clr==undefined ? "u" : clr.toString(); var hash = size.toString()+sclr+rfac.toString()+(outline_only ? "|1" : "|0"); var cache = this.boxcache; if (!cache.has(hash)) { cache.set(hash, this.gen_box_trilist(size, clr, rfac, outline_only)); } static co = new Vector3(); co.loadxy(pos); co[2] = 0.0; co.multVecMatrix(this.transmat); var viewport = g_app_state.raster.viewport; var sx = viewport[1][0]; var sy = viewport[1][1]; co[0] = (Math.floor(co[0])/sx)*2.0;// - 1.0; co[1] = (Math.floor(co[1])/sy)*2.0;// - 1.0; var mat = new Matrix4(); mat.translate(co[0], co[1], 0.0); var ret = new TriListRef(this.gl, cache.get(hash), mat, this); this.drawlists.push(ret); return ret; } box1_old(Array<float> pos, Array<float> size, Array<float> clr=undefined, float rfac=undefined, Boolean outline_only=false) { var c1, c2, c3, c4; var cs = uicolors["Box"]; static cache = {}; if (outline_only == undefined) outline_only = false; cs = _box_process_clr(cs, clr); var x = Math.floor(pos[0]), y=Math.floor(pos[1]); var w=size[0], h=size[1]; var start = 0; var ang = Math.PI/2; var r = 4 //Math.sqrt(size[0]*size[1]) if (rfac == undefined) rfac = 1; var hash = size[0].toString() + " " + size[1] + " " + rfac; if (!(hash in cache)) { r /= rfac; var p1 = this.arc_points(CACHEARR3(0+r+2, 0+r+2, 0), Math.PI, ang, r); var p2 = this.arc_points(CACHEARR3(0+w-r-2, 0+r+2, 0), Math.PI/2, ang, r); var p3 = this.arc_points(CACHEARR3(0+w-r-2, 0+h-r-2, 0), 0, ang, r); var p4 = this.arc_points(CACHEARR3(0+r+2, 0+h-r-2, 0), -Math.PI/2, ang, r); var plen = p1.length; p4.reverse(); p3.reverse(); p2.reverse(); p1.reverse(); var points = [] for (var i=0; i<p1.length; i++) { points.push(p1[i]); } for (var i=0; i<p2.length; i++) { points.push(p2[i]); p1.push(p2[i]); } for (var i=0; i<p3.length; i++) { points.push(p3[i]); } p2 = p3; for (var i=0; i<p4.length; i++) { p2.push(p4[i]); points.push(p4[i]); } p2.reverse(); cache[hash] = [p1, p2, points]; } var cp = cache[hash]; var p1 = cp[0]; var p2 = cp[1]; var points = cp[2]; var plen = p1.length; function color(i) { if (i < plen) return cs[0]; else if (i < plen*2) return cs[1]; else if (i < plen*3) return cs[2]; else if (i <= plen*4+1) return cs[3]; } static v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3(), v4 = new Vector3(); #define LOAD_CLR(a, b) a[0] = b[0]+x; a[1] = b[1]+y; a[2] = b[2]; if (!outline_only) { for (var i=0; i<p1.length-1; i++) { var i1 = i; var i2 = i+plen*2; var i3 = i + 1+plen*2; var i4 = i+1; LOAD_CLR(v1, p1[i]); LOAD_CLR(v2, p2[i]); LOAD_CLR(v3, p2[i+1]); LOAD_CLR(v4, p1[i+1]); this.trilist.add_quad(v1, v2, v3, v4, color(i1), color(i2), color(i3), color(i4)); } } var lines = [] var colors = [] static pairs = []; for (var i=0; i<points.length; i++) { LOAD_CLR(v1, points[(i+1)%points.length]); LOAD_CLR(v2, points[i]); if (pairs.length <= i) { pairs.push([[0, 0], [0, 0]]); } pairs[i][0][0] = CACHEARR3(v1[0], v1[1], 0); pairs[i][0][1] = CACHEARR3(v2[0], v2[1], 0); lines.push(pairs[i][0]); pairs[i][1][0] = color((i+1)%points.length); pairs[i][1][1] = color(i); colors.push(pairs[i][1]); } #undef LOAD_CLR this.trilist.line_strip(lines, colors, undefined, 4, true); //this.box2(pos, size, clr, rfac, outline_only); return this.trilist } on_resize(newsize, oldsize) { this.boxcache.destroy(); //all cache entries with old size are now bad for (var k in this.textcache) { if (!this.textcache.hasOwnProperty(k)) continue; this.textcache[k].destroy(); } this.textcache = {}; this.textcachelen = 0; //clear entire cache this.destroy(); this.reset(); } text(Array<float> pos, String text, Array<float> color, float size, float scale, float rot, Array<float> scissor_pos, Array<float> scissor_size) { static loc = new Vector3(); if (rot == undefined) rot = 0.0; if (size == undefined) size = default_ui_font_size; if (scale == undefined) { scale = CACHEARR3(1.0, 1.0, 1.0); } else if (typeof(scale) == "number") { scale = CACHEARR3(scale, scale, scale); } if (color == undefined) { color = uicolors["DefaultText"] } if (scissor_pos == undefined) { if (this.scissor_stack.length > 0) { scissor_pos = this.scissor_stack[this.scissor_stack.length-1][0]; scissor_size = this.scissor_stack[this.scissor_stack.length-1][1]; } } else { scissor_pos = new Vector3([scissor_pos[0], scissor_pos[1], 0]); scissor_size = new Vector3([scissor_size[0], scissor_size[1], 0]); scissor_pos.multVecMatrix(this.transmat); } loc[0] = 0; loc[1] = 0; loc[2] = 0; loc.multVecMatrix(this.transmat); loc[0] += pos[0] loc[1] += pos[1] //yes, raster is supposed to be a nasty global var port = g_app_state.raster.viewport var sx = port[1][0] var sy = port[1][1] loc[0] = (Math.floor(loc[0])/sx)*2.0; //*2.0-1.0; loc[1] = (Math.floor(loc[1])/sy)*2.0; //*2.0-1.0; var textdraw = new TextDraw(loc, text, color, scissor_pos, scissor_size, this.viewport, size, scale, this.global_matrix, rot); var hash = text.toString() + ">>" + size + "|" + color + "|" + JSON.stringify(this.viewport); //XXX // /* if (!(hash in this.textcache)) { if (this.textcachelen > this.max_textcache) { var keys = Object.getOwnPropertyNames(this.textcache) for (i=0; i<keys.length; i++) { var k = keys[i]; this.textcache[k].destroy(); var users = this.textcache[k].users; //possible evil! for (var j=0; j<users.length; j++) { users[j].recalc = true; users[j].tdrawbuf = undefined; } delete this.textcache[k]; this.textcachelen--; //amortize cache destruction calls if (this.textcachelen < this.max_textcache/3) break; } } this.textcache[hash] = textdraw.gen_buffers(g_app_state.gl); this.textcachelen++; } else { textdraw.tdrawbuf = this.textcache[hash]; } this.textcache[hash].users.push(textdraw); //-XXX if (DEBUG.canvas_sep_text) { this.textlist.push(textdraw); this.drawlists.push(textdraw); if (this.stack.length == 0) { this.uncached.push(textdraw); } return loc; } else { if (this.drawlists[this.drawlists.length-1] == this.trilist) { this.drawlists.push(textdraw); this.new_trilist(); if (this.stack.length == 0) { this.uncached.push(textdraw); this.uncached.push(this.trilist); } } else { this.drawlists.push(textdraw); if (this.stack.length == 0) { this.uncached.push(textdraw); } } // */ return loc; } } }
Java
/* Copyright 2014 Jonathan Holland. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Wave { public interface IOutboundMessageFilter { bool OnMessagePublished(string routeKey, object message); } }
Java
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; namespace CJia.Health.Presenters.Web { public class MyPicturePresenter:CJia.Health.Tools.PresenterPage<Models.Web.MyPictureModel,Views.Web.IMyPictureView> { public MyPicturePresenter(Views.Web.IMyPictureView view) : base(view) { view.OnLoadPicture += view_OnLoadPicture; view.OnProjectChanged += view_OnProjectChanged; } void view_OnProjectChanged(object sender, Views.Web.MyPictureArgs e) { DataTable data = Model.GetMyPictureByProID(e.HealthID, e.ProjectID); View.ExeBindPictureByProjectID(data); } void view_OnLoadPicture(object sender, Views.Web.MyPictureArgs e) { DataTable project = Model.GetMyPictureProject(e.HealthID); DataTable picture = Model.GetMyPicture(e.HealthID); View.ExeBindPicture(picture); View.ExeBindProject(project); } } }
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>PowerShell - Rename-Index - Rivet</title> <link href="silk.css" type="text/css" rel="stylesheet" /> <link href="styles.css" type="text/css" rel="stylesheet" /> </head> <body> <ul id="SiteNav"> <li><a href="index.html">Get-Rivet</a></li> <!--<li><a href="about_Carbon_Installation.html">-Install</a></li>--> <li><a href="documentation.html">-Documentation</a></li> <!--<li><a href="about_Carbon_Support.html">-Support</a></li>--> <li><a href="releasenotes.html">-ReleaseNotes</a></li> <li><a href="http://pshdo.com">-Blog</a></li> </ul> <h1>Rename-Index</h1> <div class="Synopsis"> <p>Renames an index.</p> </div> <h2>Syntax</h2> <pre class="Syntax"><code>Rename-Index [-TableName] &lt;String&gt; [-Name] &lt;String&gt; [-NewName] &lt;String&gt; [-SchemaName &lt;String&gt;] [&lt;CommonParameters&gt;]</code></pre> <h2>Description</h2> <div class="Description"> <p>SQL Server ships with a stored procedure which is used to rename certain objects. This operation wraps that stored procedure.</p> <p>Use <code>Rename-Column</code> to rename a column. Use <code>Rename-DataType</code> to rename a data type. Use <code>Rename-Object</code> to rename an object.</p> </div> <h2>Related Commands</h2> <ul class="RelatedCommands"> <li><a href="http://technet.microsoft.com/en-us/library/ms188351.aspx">http://technet.microsoft.com/en-us/library/ms188351.aspx</a></li> <li><a href="Rename-Column.html">Rename-Column</a></li> <li><a href="Rename-DataType.html">Rename-DataType</a></li> <li><a href="Rename-Object.html">Rename-Object</a></li> </ul> <h2> Parameters </h2> <table id="Parameters"> <tr> <th>Name</th> <th>Type</th> <th>Description</th> <th>Required?</th> <th>Pipeline Input</th> <th>Default Value</th> </tr> <tr valign='top'> <td>TableName</td> <td><a href="http://msdn.microsoft.com/en-us/library/system.string.aspx">String</a></td> <td class="ParamDescription"><p>The name of the table of the index to rename.</p></td> <td>true</td> <td>false</td> <td></td> </tr> <tr valign='top'> <td>Name</td> <td><a href="http://msdn.microsoft.com/en-us/library/system.string.aspx">String</a></td> <td class="ParamDescription"><p>The current name of the index.</p></td> <td>true</td> <td>false</td> <td></td> </tr> <tr valign='top'> <td>NewName</td> <td><a href="http://msdn.microsoft.com/en-us/library/system.string.aspx">String</a></td> <td class="ParamDescription"><p>The new name of the index.</p></td> <td>true</td> <td>false</td> <td></td> </tr> <tr valign='top'> <td>SchemaName</td> <td><a href="http://msdn.microsoft.com/en-us/library/system.string.aspx">String</a></td> <td class="ParamDescription"><p>The schema of the table. Default is <code>dbo</code>.</p></td> <td>false</td> <td>false</td> <td>dbo</td> </tr> </table> <h2>EXAMPLE 1</h2> <pre><code>Rename-Index -TableName 'FooBar' -Name 'IX_Fizz' -NewName 'Buzz'</code></pre> <p>Changes the name of the <code>Fizz</code> index on the <code>FooBar</code> table to <code>Buzz</code>.</p> <h2>EXAMPLE 2</h2> <pre><code>Rename-Index -SchemaName 'fizz' -TableName 'FooBar' -Name 'IX_Buzz' -NewName 'Fizz'</code></pre> <p>Demonstrates how to rename an index on a table that is in a schema other than <code>dbo</code>.</p> <h2>EXAMPLE 3</h2> <pre><code>Rename-Index 'FooBar' 'IX_Fizz' 'Buzz'</code></pre> <p>Demonstrates how to use the short form to rename the <code>Fizz</code> index on the <code>FooBar</code> table to <code>Buzz</code>: table name is first, then existing index name, then new index name.</p> <div class="Footer"> Copyright 2013 - 2016 <a href="http://pshdo.com">Aaron Jensen</a>. </div> </body> </html>
Java
$.FAQ = function(){ $self = this; this.url = "/faq" this.send = function(inputs){ var params = new FormData(); // var csrf = $("#csrf").val(); // params.append("csrf_ID", csrf); $.each(inputs, function(key, val){ params.append(key,val); }); $.ajax({ url : $self.url, type: 'POST', async: true, processData: false, data: params, success: function(response){ response = JSON.parse(response); $self.fillQAs(response.qadata); $self.createPagination(response.metadata) }, }); }; this.fillQAs = function(data){ var qaBox = $("#faq-container .faq-item").clone(); $("#faq-container .faq-item").remove(); $.each(data, function(obj){ var $div = qaBox.clone(); $div.find(".faq-item-question h2").html(obj.question); $div.find(".faq-item-answer p").html(obj.answer); }); }; this.createPagination = function(metadata){ }; this.load = function(data){ var limit = (data.limit > 0) ? data.limit : 5; var offset = (data.page_num - 1)*limit; var inputs = { action : 'loadFaq', limit : limit, offset : offset }; $self.send(inputs); }; this.init = function(){ var inputs = { limit : 5, page_num : 1 }; $self.load(inputs); }; };
Java
# Lasiosphaeriopsis cephalodiorum (Rostr.) Alstrup SPECIES #### Status ACCEPTED #### According to Index Fungorum #### Published in in Alstrup, Christensen, Hansen & Svane, Fródskaparrit, Annales Societatis Scientiarium Færoensis 40: 92 (1994) #### Original name Sphaeria cephalodiorum Rostr. ### Remarks null
Java
# Doritis pulcherrima f. pulcherrima FORM #### Status ACCEPTED #### According to NUB Generator [autonym] #### Published in null #### Original name null ### Remarks null
Java
# Splanchnonema quinqueseptatum (M.E. Barr) Aptroot, 1998 SPECIES #### Status SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in Nova Hedwigia 66(1-2): 154 (1998) #### Original name Massarina quinqueseptata M.E. Barr, 1992 ### Remarks null
Java
/** * Copyright 2011-2017 Asakusa Framework Team. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.asakusafw.testdriver.rule; import java.math.BigDecimal; import java.text.MessageFormat; /** * Accepts iff actual decimal is in [ expected + lower-bound, expected + upper-bound ]. * @since 0.2.0 */ public class DecimalRange implements ValuePredicate<BigDecimal> { private final BigDecimal lowerBound; private final BigDecimal upperBound; /** * Creates a new instance. * @param lowerBound lower bound offset from expected value * @param upperBound upper bound offset from expected value */ public DecimalRange(BigDecimal lowerBound, BigDecimal upperBound) { this.lowerBound = lowerBound; this.upperBound = upperBound; } @Override public boolean accepts(BigDecimal expected, BigDecimal actual) { if (expected == null || actual == null) { throw new IllegalArgumentException(); } return expected.add(lowerBound).compareTo(actual) <= 0 && actual.compareTo(expected.add(upperBound)) <= 0; } @Override public String describeExpected(BigDecimal expected, BigDecimal actual) { if (expected == null) { return "(error)"; //$NON-NLS-1$ } return MessageFormat.format( "{0} ~ {1}", //$NON-NLS-1$ Util.format(expected.add(lowerBound)), Util.format(expected.add(upperBound))); } }
Java
/* * JBoss, Home of Professional Open Source. * Copyright 2015 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.security.sasl.util; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.Map; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.sasl.SaslException; import javax.security.sasl.SaslServer; import javax.security.sasl.SaslServerFactory; ; import org.wildfly.common.Assert; import org.wildfly.security.auth.callback.ServerCredentialCallback; import org.wildfly.security.credential.Credential; /** * A {@link SaslServerFactory} which sets the server's credential. * * @author <a href="mailto:fjuma@redhat.com">Farah Juma</a> */ public final class CredentialSaslServerFactory extends AbstractDelegatingSaslServerFactory { private final Credential credential; /** * Construct a new instance. * * @param delegate the delegate SASL server factory * @param credential the server credential to use */ public CredentialSaslServerFactory(final SaslServerFactory delegate, final Credential credential) { super(delegate); Assert.checkNotNullParam("credential", credential); this.credential = credential; } public SaslServer createSaslServer(final String mechanism, final String protocol, final String serverName, final Map<String, ?> props, final CallbackHandler cbh) throws SaslException { return delegate.createSaslServer(mechanism, protocol, serverName, props, callbacks -> { ArrayList<Callback> list = new ArrayList<>(Arrays.asList(callbacks)); final Iterator<Callback> iterator = list.iterator(); while (iterator.hasNext()) { Callback callback = iterator.next(); if (callback instanceof ServerCredentialCallback) { final ServerCredentialCallback credentialCallback = (ServerCredentialCallback) callback; if (credentialCallback.isCredentialSupported(credential)) { credentialCallback.setCredential(credential); iterator.remove(); } } } if (!list.isEmpty()) { cbh.handle(list.toArray(new Callback[list.size()])); } }); } }
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_79) on Sat Jan 09 21:52:40 PST 2016 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Uses of Class com.fasterxml.jackson.core.ObjectCodec (Jackson-core 2.7.0 API)</title> <meta name="date" content="2016-01-09"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class com.fasterxml.jackson.core.ObjectCodec (Jackson-core 2.7.0 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/fasterxml/jackson/core/class-use/ObjectCodec.html" target="_top">Frames</a></li> <li><a href="ObjectCodec.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class com.fasterxml.jackson.core.ObjectCodec" class="title">Uses of Class<br>com.fasterxml.jackson.core.ObjectCodec</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#com.fasterxml.jackson.core">com.fasterxml.jackson.core</a></td> <td class="colLast"> <div class="block">Main public API classes of the core streaming JSON processor: most importantly <a href="../../../../../com/fasterxml/jackson/core/JsonFactory.html" title="class in com.fasterxml.jackson.core"><code>JsonFactory</code></a> used for constructing JSON parser (<a href="../../../../../com/fasterxml/jackson/core/JsonParser.html" title="class in com.fasterxml.jackson.core"><code>JsonParser</code></a>) and generator (<a href="../../../../../com/fasterxml/jackson/core/JsonGenerator.html" title="class in com.fasterxml.jackson.core"><code>JsonGenerator</code></a>) instances.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#com.fasterxml.jackson.core.base">com.fasterxml.jackson.core.base</a></td> <td class="colLast"> <div class="block">Base classes used by concrete Parser and Generator implementations; contain functionality that is not specific to JSON or input abstraction (byte vs char).</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="#com.fasterxml.jackson.core.json">com.fasterxml.jackson.core.json</a></td> <td class="colLast"> <div class="block">JSON-specific parser and generator implementation classes that Jackson defines and uses.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#com.fasterxml.jackson.core.util">com.fasterxml.jackson.core.util</a></td> <td class="colLast"> <div class="block">Utility classes used by Jackson Core functionality.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="com.fasterxml.jackson.core"> <!-- --> </a> <h3>Uses of <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a> in <a href="../../../../../com/fasterxml/jackson/core/package-summary.html">com.fasterxml.jackson.core</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing fields, and an explanation"> <caption><span>Fields in <a href="../../../../../com/fasterxml/jackson/core/package-summary.html">com.fasterxml.jackson.core</a> declared as <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>protected <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></code></td> <td class="colLast"><span class="strong">JsonFactory.</span><code><strong><a href="../../../../../com/fasterxml/jackson/core/JsonFactory.html#_objectCodec">_objectCodec</a></strong></code> <div class="block">Object that implements conversion functionality between Java objects and JSON content.</div> </td> </tr> </tbody> </table> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../com/fasterxml/jackson/core/package-summary.html">com.fasterxml.jackson.core</a> that return <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>protected <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></code></td> <td class="colLast"><span class="strong">JsonParser.</span><code><strong><a href="../../../../../com/fasterxml/jackson/core/JsonParser.html#_codec()">_codec</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>abstract <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></code></td> <td class="colLast"><span class="strong">JsonParser.</span><code><strong><a href="../../../../../com/fasterxml/jackson/core/JsonParser.html#getCodec()">getCodec</a></strong>()</code> <div class="block">Accessor for <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core"><code>ObjectCodec</code></a> associated with this parser, if any.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>abstract <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></code></td> <td class="colLast"><span class="strong">JsonGenerator.</span><code><strong><a href="../../../../../com/fasterxml/jackson/core/JsonGenerator.html#getCodec()">getCodec</a></strong>()</code> <div class="block">Method for accessing the object used for writing Java object as JSON content (using method <a href="../../../../../com/fasterxml/jackson/core/JsonGenerator.html#writeObject(java.lang.Object)"><code>JsonGenerator.writeObject(java.lang.Object)</code></a>).</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></code></td> <td class="colLast"><span class="strong">JsonFactory.</span><code><strong><a href="../../../../../com/fasterxml/jackson/core/JsonFactory.html#getCodec()">getCodec</a></strong>()</code>&nbsp;</td> </tr> </tbody> </table> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../com/fasterxml/jackson/core/package-summary.html">com.fasterxml.jackson.core</a> with parameters of type <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>abstract void</code></td> <td class="colLast"><span class="strong">JsonParser.</span><code><strong><a href="../../../../../com/fasterxml/jackson/core/JsonParser.html#setCodec(com.fasterxml.jackson.core.ObjectCodec)">setCodec</a></strong>(<a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a>&nbsp;c)</code> <div class="block">Setter that allows defining <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core"><code>ObjectCodec</code></a> associated with this parser, if any.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>abstract <a href="../../../../../com/fasterxml/jackson/core/JsonGenerator.html" title="class in com.fasterxml.jackson.core">JsonGenerator</a></code></td> <td class="colLast"><span class="strong">JsonGenerator.</span><code><strong><a href="../../../../../com/fasterxml/jackson/core/JsonGenerator.html#setCodec(com.fasterxml.jackson.core.ObjectCodec)">setCodec</a></strong>(<a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a>&nbsp;oc)</code> <div class="block">Method that can be called to set or reset the object to use for writing Java objects as JsonContent (using method <a href="../../../../../com/fasterxml/jackson/core/JsonGenerator.html#writeObject(java.lang.Object)"><code>JsonGenerator.writeObject(java.lang.Object)</code></a>).</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../com/fasterxml/jackson/core/JsonFactory.html" title="class in com.fasterxml.jackson.core">JsonFactory</a></code></td> <td class="colLast"><span class="strong">JsonFactory.</span><code><strong><a href="../../../../../com/fasterxml/jackson/core/JsonFactory.html#setCodec(com.fasterxml.jackson.core.ObjectCodec)">setCodec</a></strong>(<a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a>&nbsp;oc)</code> <div class="block">Method for associating a <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core"><code>ObjectCodec</code></a> (typically a <code>com.fasterxml.jackson.databind.ObjectMapper</code>) with this factory (and more importantly, parsers and generators it constructs).</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../../com/fasterxml/jackson/core/JsonParser.html" title="class in com.fasterxml.jackson.core">JsonParser</a></code></td> <td class="colLast"><span class="strong">TreeNode.</span><code><strong><a href="../../../../../com/fasterxml/jackson/core/TreeNode.html#traverse(com.fasterxml.jackson.core.ObjectCodec)">traverse</a></strong>(<a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a>&nbsp;codec)</code> <div class="block">Same as <a href="../../../../../com/fasterxml/jackson/core/TreeNode.html#traverse()"><code>TreeNode.traverse()</code></a>, but additionally passes <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core"><code>ObjectCodec</code></a> to use if <a href="../../../../../com/fasterxml/jackson/core/JsonParser.html#readValueAs(java.lang.Class)"><code>JsonParser.readValueAs(Class)</code></a> is used (otherwise caller must call <a href="../../../../../com/fasterxml/jackson/core/JsonParser.html#setCodec(com.fasterxml.jackson.core.ObjectCodec)"><code>JsonParser.setCodec(com.fasterxml.jackson.core.ObjectCodec)</code></a> on response explicitly).</div> </td> </tr> </tbody> </table> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing constructors, and an explanation"> <caption><span>Constructors in <a href="../../../../../com/fasterxml/jackson/core/package-summary.html">com.fasterxml.jackson.core</a> with parameters of type <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colLast"><code><strong><a href="../../../../../com/fasterxml/jackson/core/JsonFactory.html#JsonFactory(com.fasterxml.jackson.core.JsonFactory,%20com.fasterxml.jackson.core.ObjectCodec)">JsonFactory</a></strong>(<a href="../../../../../com/fasterxml/jackson/core/JsonFactory.html" title="class in com.fasterxml.jackson.core">JsonFactory</a>&nbsp;src, <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a>&nbsp;codec)</code> <div class="block">Constructor used when copy()ing a factory instance.</div> </td> </tr> <tr class="rowColor"> <td class="colLast"><code><strong><a href="../../../../../com/fasterxml/jackson/core/JsonFactory.html#JsonFactory(com.fasterxml.jackson.core.ObjectCodec)">JsonFactory</a></strong>(<a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a>&nbsp;oc)</code>&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"><a name="com.fasterxml.jackson.core.base"> <!-- --> </a> <h3>Uses of <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a> in <a href="../../../../../com/fasterxml/jackson/core/base/package-summary.html">com.fasterxml.jackson.core.base</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing fields, and an explanation"> <caption><span>Fields in <a href="../../../../../com/fasterxml/jackson/core/base/package-summary.html">com.fasterxml.jackson.core.base</a> declared as <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>protected <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></code></td> <td class="colLast"><span class="strong">GeneratorBase.</span><code><strong><a href="../../../../../com/fasterxml/jackson/core/base/GeneratorBase.html#_objectCodec">_objectCodec</a></strong></code>&nbsp;</td> </tr> </tbody> </table> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../com/fasterxml/jackson/core/base/package-summary.html">com.fasterxml.jackson.core.base</a> that return <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></code></td> <td class="colLast"><span class="strong">GeneratorBase.</span><code><strong><a href="../../../../../com/fasterxml/jackson/core/base/GeneratorBase.html#getCodec()">getCodec</a></strong>()</code>&nbsp;</td> </tr> </tbody> </table> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../com/fasterxml/jackson/core/base/package-summary.html">com.fasterxml.jackson.core.base</a> with parameters of type <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../com/fasterxml/jackson/core/JsonGenerator.html" title="class in com.fasterxml.jackson.core">JsonGenerator</a></code></td> <td class="colLast"><span class="strong">GeneratorBase.</span><code><strong><a href="../../../../../com/fasterxml/jackson/core/base/GeneratorBase.html#setCodec(com.fasterxml.jackson.core.ObjectCodec)">setCodec</a></strong>(<a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a>&nbsp;oc)</code>&nbsp;</td> </tr> </tbody> </table> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing constructors, and an explanation"> <caption><span>Constructors in <a href="../../../../../com/fasterxml/jackson/core/base/package-summary.html">com.fasterxml.jackson.core.base</a> with parameters of type <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colLast"><code><strong><a href="../../../../../com/fasterxml/jackson/core/base/GeneratorBase.html#GeneratorBase(int,%20com.fasterxml.jackson.core.ObjectCodec)">GeneratorBase</a></strong>(int&nbsp;features, <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a>&nbsp;codec)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colLast"><code><strong><a href="../../../../../com/fasterxml/jackson/core/base/GeneratorBase.html#GeneratorBase(int,%20com.fasterxml.jackson.core.ObjectCodec,%20com.fasterxml.jackson.core.json.JsonWriteContext)">GeneratorBase</a></strong>(int&nbsp;features, <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a>&nbsp;codec, <a href="../../../../../com/fasterxml/jackson/core/json/JsonWriteContext.html" title="class in com.fasterxml.jackson.core.json">JsonWriteContext</a>&nbsp;ctxt)</code>&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"><a name="com.fasterxml.jackson.core.json"> <!-- --> </a> <h3>Uses of <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a> in <a href="../../../../../com/fasterxml/jackson/core/json/package-summary.html">com.fasterxml.jackson.core.json</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing fields, and an explanation"> <caption><span>Fields in <a href="../../../../../com/fasterxml/jackson/core/json/package-summary.html">com.fasterxml.jackson.core.json</a> declared as <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>protected <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></code></td> <td class="colLast"><span class="strong">UTF8StreamJsonParser.</span><code><strong><a href="../../../../../com/fasterxml/jackson/core/json/UTF8StreamJsonParser.html#_objectCodec">_objectCodec</a></strong></code> <div class="block">Codec used for data binding when (if) requested; typically full <code>ObjectMapper</code>, but that abstract is not part of core package.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>protected <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></code></td> <td class="colLast"><span class="strong">ReaderBasedJsonParser.</span><code><strong><a href="../../../../../com/fasterxml/jackson/core/json/ReaderBasedJsonParser.html#_objectCodec">_objectCodec</a></strong></code>&nbsp;</td> </tr> </tbody> </table> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../com/fasterxml/jackson/core/json/package-summary.html">com.fasterxml.jackson.core.json</a> that return <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></code></td> <td class="colLast"><span class="strong">UTF8StreamJsonParser.</span><code><strong><a href="../../../../../com/fasterxml/jackson/core/json/UTF8StreamJsonParser.html#getCodec()">getCodec</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></code></td> <td class="colLast"><span class="strong">ReaderBasedJsonParser.</span><code><strong><a href="../../../../../com/fasterxml/jackson/core/json/ReaderBasedJsonParser.html#getCodec()">getCodec</a></strong>()</code>&nbsp;</td> </tr> </tbody> </table> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../com/fasterxml/jackson/core/json/package-summary.html">com.fasterxml.jackson.core.json</a> with parameters of type <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../com/fasterxml/jackson/core/JsonParser.html" title="class in com.fasterxml.jackson.core">JsonParser</a></code></td> <td class="colLast"><span class="strong">ByteSourceJsonBootstrapper.</span><code><strong><a href="../../../../../com/fasterxml/jackson/core/json/ByteSourceJsonBootstrapper.html#constructParser(int,%20com.fasterxml.jackson.core.ObjectCodec,%20com.fasterxml.jackson.core.sym.ByteQuadsCanonicalizer,%20com.fasterxml.jackson.core.sym.CharsToNameCanonicalizer,%20int)">constructParser</a></strong>(int&nbsp;parserFeatures, <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a>&nbsp;codec, <a href="../../../../../com/fasterxml/jackson/core/sym/ByteQuadsCanonicalizer.html" title="class in com.fasterxml.jackson.core.sym">ByteQuadsCanonicalizer</a>&nbsp;rootByteSymbols, <a href="../../../../../com/fasterxml/jackson/core/sym/CharsToNameCanonicalizer.html" title="class in com.fasterxml.jackson.core.sym">CharsToNameCanonicalizer</a>&nbsp;rootCharSymbols, int&nbsp;factoryFeatures)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><span class="strong">UTF8StreamJsonParser.</span><code><strong><a href="../../../../../com/fasterxml/jackson/core/json/UTF8StreamJsonParser.html#setCodec(com.fasterxml.jackson.core.ObjectCodec)">setCodec</a></strong>(<a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a>&nbsp;c)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><span class="strong">ReaderBasedJsonParser.</span><code><strong><a href="../../../../../com/fasterxml/jackson/core/json/ReaderBasedJsonParser.html#setCodec(com.fasterxml.jackson.core.ObjectCodec)">setCodec</a></strong>(<a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a>&nbsp;c)</code>&nbsp;</td> </tr> </tbody> </table> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing constructors, and an explanation"> <caption><span>Constructors in <a href="../../../../../com/fasterxml/jackson/core/json/package-summary.html">com.fasterxml.jackson.core.json</a> with parameters of type <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colLast"><code><strong><a href="../../../../../com/fasterxml/jackson/core/json/JsonGeneratorImpl.html#JsonGeneratorImpl(com.fasterxml.jackson.core.io.IOContext,%20int,%20com.fasterxml.jackson.core.ObjectCodec)">JsonGeneratorImpl</a></strong>(<a href="../../../../../com/fasterxml/jackson/core/io/IOContext.html" title="class in com.fasterxml.jackson.core.io">IOContext</a>&nbsp;ctxt, int&nbsp;features, <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a>&nbsp;codec)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colLast"><code><strong><a href="../../../../../com/fasterxml/jackson/core/json/ReaderBasedJsonParser.html#ReaderBasedJsonParser(com.fasterxml.jackson.core.io.IOContext,%20int,%20java.io.Reader,%20com.fasterxml.jackson.core.ObjectCodec,%20com.fasterxml.jackson.core.sym.CharsToNameCanonicalizer)">ReaderBasedJsonParser</a></strong>(<a href="../../../../../com/fasterxml/jackson/core/io/IOContext.html" title="class in com.fasterxml.jackson.core.io">IOContext</a>&nbsp;ctxt, int&nbsp;features, <a href="http://docs.oracle.com/javase/7/docs/api/java/io/Reader.html?is-external=true" title="class or interface in java.io">Reader</a>&nbsp;r, <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a>&nbsp;codec, <a href="../../../../../com/fasterxml/jackson/core/sym/CharsToNameCanonicalizer.html" title="class in com.fasterxml.jackson.core.sym">CharsToNameCanonicalizer</a>&nbsp;st)</code> <div class="block">Method called when input comes as a <a href="http://docs.oracle.com/javase/7/docs/api/java/io/Reader.html?is-external=true" title="class or interface in java.io"><code>Reader</code></a>, and buffer allocation can be done using default mechanism.</div> </td> </tr> <tr class="altColor"> <td class="colLast"><code><strong><a href="../../../../../com/fasterxml/jackson/core/json/ReaderBasedJsonParser.html#ReaderBasedJsonParser(com.fasterxml.jackson.core.io.IOContext,%20int,%20java.io.Reader,%20com.fasterxml.jackson.core.ObjectCodec,%20com.fasterxml.jackson.core.sym.CharsToNameCanonicalizer,%20char[],%20int,%20int,%20boolean)">ReaderBasedJsonParser</a></strong>(<a href="../../../../../com/fasterxml/jackson/core/io/IOContext.html" title="class in com.fasterxml.jackson.core.io">IOContext</a>&nbsp;ctxt, int&nbsp;features, <a href="http://docs.oracle.com/javase/7/docs/api/java/io/Reader.html?is-external=true" title="class or interface in java.io">Reader</a>&nbsp;r, <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a>&nbsp;codec, <a href="../../../../../com/fasterxml/jackson/core/sym/CharsToNameCanonicalizer.html" title="class in com.fasterxml.jackson.core.sym">CharsToNameCanonicalizer</a>&nbsp;st, char[]&nbsp;inputBuffer, int&nbsp;start, int&nbsp;end, boolean&nbsp;bufferRecyclable)</code> <div class="block">Method called when caller wants to provide input buffer directly, and it may or may not be recyclable use standard recycle context.</div> </td> </tr> <tr class="rowColor"> <td class="colLast"><code><strong><a href="../../../../../com/fasterxml/jackson/core/json/UTF8JsonGenerator.html#UTF8JsonGenerator(com.fasterxml.jackson.core.io.IOContext,%20int,%20com.fasterxml.jackson.core.ObjectCodec,%20java.io.OutputStream)">UTF8JsonGenerator</a></strong>(<a href="../../../../../com/fasterxml/jackson/core/io/IOContext.html" title="class in com.fasterxml.jackson.core.io">IOContext</a>&nbsp;ctxt, int&nbsp;features, <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a>&nbsp;codec, <a href="http://docs.oracle.com/javase/7/docs/api/java/io/OutputStream.html?is-external=true" title="class or interface in java.io">OutputStream</a>&nbsp;out)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colLast"><code><strong><a href="../../../../../com/fasterxml/jackson/core/json/UTF8JsonGenerator.html#UTF8JsonGenerator(com.fasterxml.jackson.core.io.IOContext,%20int,%20com.fasterxml.jackson.core.ObjectCodec,%20java.io.OutputStream,%20byte[],%20int,%20boolean)">UTF8JsonGenerator</a></strong>(<a href="../../../../../com/fasterxml/jackson/core/io/IOContext.html" title="class in com.fasterxml.jackson.core.io">IOContext</a>&nbsp;ctxt, int&nbsp;features, <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a>&nbsp;codec, <a href="http://docs.oracle.com/javase/7/docs/api/java/io/OutputStream.html?is-external=true" title="class or interface in java.io">OutputStream</a>&nbsp;out, byte[]&nbsp;outputBuffer, int&nbsp;outputOffset, boolean&nbsp;bufferRecyclable)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colLast"><code><strong><a href="../../../../../com/fasterxml/jackson/core/json/UTF8StreamJsonParser.html#UTF8StreamJsonParser(com.fasterxml.jackson.core.io.IOContext,%20int,%20java.io.InputStream,%20com.fasterxml.jackson.core.ObjectCodec,%20com.fasterxml.jackson.core.sym.ByteQuadsCanonicalizer,%20byte[],%20int,%20int,%20boolean)">UTF8StreamJsonParser</a></strong>(<a href="../../../../../com/fasterxml/jackson/core/io/IOContext.html" title="class in com.fasterxml.jackson.core.io">IOContext</a>&nbsp;ctxt, int&nbsp;features, <a href="http://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html?is-external=true" title="class or interface in java.io">InputStream</a>&nbsp;in, <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a>&nbsp;codec, <a href="../../../../../com/fasterxml/jackson/core/sym/ByteQuadsCanonicalizer.html" title="class in com.fasterxml.jackson.core.sym">ByteQuadsCanonicalizer</a>&nbsp;sym, byte[]&nbsp;inputBuffer, int&nbsp;start, int&nbsp;end, boolean&nbsp;bufferRecyclable)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colLast"><code><strong><a href="../../../../../com/fasterxml/jackson/core/json/WriterBasedJsonGenerator.html#WriterBasedJsonGenerator(com.fasterxml.jackson.core.io.IOContext,%20int,%20com.fasterxml.jackson.core.ObjectCodec,%20java.io.Writer)">WriterBasedJsonGenerator</a></strong>(<a href="../../../../../com/fasterxml/jackson/core/io/IOContext.html" title="class in com.fasterxml.jackson.core.io">IOContext</a>&nbsp;ctxt, int&nbsp;features, <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a>&nbsp;codec, <a href="http://docs.oracle.com/javase/7/docs/api/java/io/Writer.html?is-external=true" title="class or interface in java.io">Writer</a>&nbsp;w)</code>&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"><a name="com.fasterxml.jackson.core.util"> <!-- --> </a> <h3>Uses of <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a> in <a href="../../../../../com/fasterxml/jackson/core/util/package-summary.html">com.fasterxml.jackson.core.util</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../com/fasterxml/jackson/core/util/package-summary.html">com.fasterxml.jackson.core.util</a> that return <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></code></td> <td class="colLast"><span class="strong">JsonParserDelegate.</span><code><strong><a href="../../../../../com/fasterxml/jackson/core/util/JsonParserDelegate.html#getCodec()">getCodec</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></code></td> <td class="colLast"><span class="strong">JsonGeneratorDelegate.</span><code><strong><a href="../../../../../com/fasterxml/jackson/core/util/JsonGeneratorDelegate.html#getCodec()">getCodec</a></strong>()</code>&nbsp;</td> </tr> </tbody> </table> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../com/fasterxml/jackson/core/util/package-summary.html">com.fasterxml.jackson.core.util</a> with parameters of type <a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><span class="strong">JsonParserDelegate.</span><code><strong><a href="../../../../../com/fasterxml/jackson/core/util/JsonParserDelegate.html#setCodec(com.fasterxml.jackson.core.ObjectCodec)">setCodec</a></strong>(<a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a>&nbsp;c)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code><a href="../../../../../com/fasterxml/jackson/core/JsonGenerator.html" title="class in com.fasterxml.jackson.core">JsonGenerator</a></code></td> <td class="colLast"><span class="strong">JsonGeneratorDelegate.</span><code><strong><a href="../../../../../com/fasterxml/jackson/core/util/JsonGeneratorDelegate.html#setCodec(com.fasterxml.jackson.core.ObjectCodec)">setCodec</a></strong>(<a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">ObjectCodec</a>&nbsp;oc)</code>&nbsp;</td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../com/fasterxml/jackson/core/ObjectCodec.html" title="class in com.fasterxml.jackson.core">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/fasterxml/jackson/core/class-use/ObjectCodec.html" target="_top">Frames</a></li> <li><a href="ObjectCodec.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2008-2016 <a href="http://fasterxml.com/">FasterXML</a>. All Rights Reserved.</small></p> </body> </html>
Java
package com.board; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; public class BoardDAO { private Connection conn; public BoardDAO(Connection conn){ this.conn = conn; } //1. num의 최대값 public int getMaxNum(){ int maxNum = 0; PreparedStatement pstmt = null; ResultSet rs = null; String sql; try { sql = "select nvl(max(num),0) from board"; pstmt = conn.prepareStatement(sql); rs = pstmt.executeQuery(); if(rs.next()){ maxNum = rs.getInt(1); } rs.close(); pstmt.close(); } catch (Exception e) { System.out.println(e.toString()); } return maxNum; } // 입력(created.jsp -> created_ok.jsp) public int insertData(BoardForm dto){ int result = 0; /* PreparedStatement pstmt = null; StringBuffer sql = new StringBuffer(); */ PreparedStatement pstmt = null; String sql; try { /* sql.append("insert into board"); sql.append("(num, name, pwd, email, subject, content,"); */ sql = "insert into board" + "(num, name, pwd, email, subject, content," + "ipAddr, hitCount, created) " + "values(?, ?, ?, ?, ?, ?, ?, 0, sysdate)"; pstmt = conn.prepareStatement(sql); pstmt.setInt(1, dto.getNum()); pstmt.setString(2, dto.getName()); pstmt.setString(3, dto.getPwd()); pstmt.setString(4, dto.getEmail()); pstmt.setString(5, dto.getSubject()); pstmt.setString(6, dto.getContent()); pstmt.setString(7, dto.getIpAddr()); result = pstmt.executeUpdate(); pstmt.close(); } catch (Exception e) { System.out.println("# insertData"); System.out.println(e.toString()); } return result; } // 전체데이터 가지고 올거야 public List<BoardForm> getList(int start, int end){ List<BoardForm> lists = new ArrayList<BoardForm>(); PreparedStatement pstmt = null; ResultSet rs = null; String sql; try { sql = "select * from ("; sql += "select rownum rnum,data.* " + " from (select num,name,subject,hitCount," + " to_char(created, 'YYYY-MM-DD') created" + " from board order by num desc) data )" + " where rnum >= ? and rnum <= ? "; pstmt = conn.prepareStatement(sql); pstmt.setInt(1, start); pstmt.setInt(2, end); rs = pstmt.executeQuery(); while(rs.next()){ BoardForm dto = new BoardForm(); dto.setNum(rs.getInt(2)); dto.setName(rs.getString(3)); dto.setSubject(rs.getString(4)); dto.setHitCount(rs.getInt(5)); dto.setCreated(rs.getString(6)); lists.add(dto); } rs.close(); pstmt.close(); } catch (Exception e) { System.out.println(e.toString()); } return lists; } //전체 데이터수 구하기 public int getDataCount(){ int result= 0; PreparedStatement pstmt = null; ResultSet rs = null; String sql; try { sql = "select nvl(count(*),0) from board"; pstmt = conn.prepareStatement(sql); rs = pstmt.executeQuery(); if(rs.next()){ result = rs.getInt(1); } rs.close(); pstmt.close(); } catch (Exception e) { System.out.println(e.toString()); } return result; } //조회수증가 public int updateHitCount(int num){ int result = 0; PreparedStatement pstmt = null; String sql; try { sql = "update board set hitCount=hitCount+1 where num=?" ; pstmt = conn.prepareStatement(sql); pstmt.setInt(1, num); result = pstmt.executeUpdate(); pstmt.close(); } catch (Exception e) { System.out.println(e.toString()); } return result; } // 한명의 데이터 출력 public BoardForm getReadData(int num){ BoardForm dto = null; PreparedStatement pstmt = null; ResultSet rs = null; String sql; try { // 제목, 작성자, 줄수, 등록일, 조회수, 내용, ip주소 sql = "select num, name, pwd, email, subject, content, ipaddr, created, hitCount " + "from board where num=?"; pstmt = conn.prepareStatement(sql); pstmt.setInt(1, num); rs = pstmt.executeQuery(); if(rs.next()){ dto = new BoardForm(); dto.setNum(rs.getInt("num")); dto.setName(rs.getString("name")); dto.setPwd(rs.getString("pwd")); dto.setEmail(rs.getString("email")); dto.setSubject(rs.getString("subject")); dto.setContent(rs.getString("content")); dto.setIpAddr(rs.getString("ipAddr")); dto.setHitCount(rs.getInt("hitCount")); dto.setCreated(rs.getString("created")); } rs.close(); pstmt.close(); } catch (Exception e) { System.out.println(e.toString()); } return dto; } // 삭제 public int deleteData(int num){ int result = 0; PreparedStatement pstmt = null; String sql; try { sql = "delete board where num=?"; pstmt = conn.prepareStatement(sql); pstmt.setInt(1, num); result = pstmt.executeUpdate(); pstmt.close(); } catch (Exception e) { System.out.println(e.toString()); } return result; } // 수정 public int updateData(BoardForm dto){ int result = 0; PreparedStatement pstmt = null; String sql; try { sql = "update board set name=?, pwd=?, subject=?, content=?, email=? where num=? "; pstmt = conn.prepareStatement(sql); pstmt.setString(1, dto.getName()); pstmt.setString(2, dto.getPwd()); pstmt.setString(3, dto.getSubject()); pstmt.setString(4, dto.getContent()); pstmt.setString(5, dto.getEmail()); pstmt.setInt(6, dto.getNum()); result = pstmt.executeUpdate(); pstmt.close(); } catch (Exception e) { System.out.println(e.toString()); } return result; } //검색된 데이터수 구하기 public int getDataCount(String searchKey, String searchValue){ int result= 0; PreparedStatement pstmt = null; ResultSet rs = null; String sql; try { searchValue = "%" + searchValue + "%"; sql = "select nvl(count(*),0) from board where "+searchKey + " like ?"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, searchValue); rs = pstmt.executeQuery(); if(rs.next()){ result = rs.getInt(1); } rs.close(); pstmt.close(); } catch (Exception e) { System.out.println(e.toString()); } return result; } // 검색데이터 가지고 올거야 public List<BoardForm> getList(int start, int end, String searchKey, String searchValue){ List<BoardForm> lists = new ArrayList<BoardForm>(); PreparedStatement pstmt = null; ResultSet rs = null; String sql; try { searchValue = "%" + searchValue + "%"; sql = "select * from ("; sql += "select rownum rnum,data.* " + " from (select num,name,subject,hitCount," + " to_char(created, 'YYYY-MM-DD') created" + " from board where "+searchKey + " like ? order by num desc) data )" + " where rnum >= ? and rnum <= ? "; pstmt = conn.prepareStatement(sql); pstmt.setString(1, searchValue); pstmt.setInt(2, start); pstmt.setInt(3, end); rs = pstmt.executeQuery(); while(rs.next()){ BoardForm dto = new BoardForm(); dto.setNum(rs.getInt(2)); dto.setName(rs.getString(3)); dto.setSubject(rs.getString(4)); dto.setHitCount(rs.getInt(5)); dto.setCreated(rs.getString(6)); lists.add(dto); } rs.close(); pstmt.close(); } catch (Exception e) { System.out.println(e.toString()); } return lists; } } /////////////////
Java
<html> <head> </head> <body> testf </body> </html>
Java
/* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.antennaesdk.common.messages; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.HashMap; import java.util.Map; import java.util.UUID; /** * <code>ServerRestMessage</code> carries a REST api call to the mobile-broker. * Broker executes this call, and returns the result via <code>ClientMessage</code>. * * @see ClientMessage */ public class ServerRestMessage { // from where the message originates. // it can be from a user or from a server (bot) private ClientAddress from; // rest resource path such as "/api/books" // another example would be "/api/books?id=383763" // another example would be "/api/books/383763" private String path; // represents the "protocol//host:port" such as "https://toys.company.com:8443" // or port can be optional such as "https://toys.company.com" private String host; // represents REST method such as "GET", "POST", "PUT", "DELETE" etc // TODO: use an enum instead of string private String method; // actual message ( this the payload if its POST/PUT call ) // this is optional private String payLoad; // the headers for a REST message private Map<String, String> headers = new HashMap<>(); // The name/value pairs of multipart entities. Implies a multipart request. private Map<String, String> multipartEntities; // unique identified to track the request on the client side. private String requestId; // TODO: use TypeAdapterFactory instead of passing the type. private String classType = ServerRestMessage.class.getName(); // getters and setters public ServerRestMessage(){ requestId = UUID.randomUUID().toString(); } public ServerRestMessage( String requestId ){ this.requestId = requestId; } public ClientAddress getFrom() { return from; } public void setFrom(ClientAddress from) { this.from = from; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getMethod() { return method; } public void setMethod(String method) { this.method = method; } public String getPayLoad() { return payLoad; } public void setPayLoad(String payLoad) { this.payLoad = payLoad; } public Map<String, String> getHeaders() { return headers; } public void setHeaders(Map<String, String> headers) { this.headers = headers; } public void setMultipartEntities(Map<String, String> multipartEntities) { this.multipartEntities = multipartEntities; } public Map<String, String> getMultipartEntities() { return multipartEntities; } public String getRequestId() { return requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } // utility methods public String toJson(){ Gson gson = new Gson(); String json = gson.toJson(this); return json; } public String toJsonPretty(){ Gson gson = new GsonBuilder().setPrettyPrinting().create(); String json = gson.toJson(this); return json; } public static ServerRestMessage fromJson(String json ){ Gson gson = new Gson(); ServerRestMessage result = gson.fromJson( json, ServerRestMessage.class); return result; } }
Java
<!-- $Id: package.html 35201 2011-07-22 14:58:48Z juergens $ @version $Rev: 35201 $ @ConQAT.Rating GREEN Hash: 92C5B8CDC35E818F72E381EA1A7E7CBE --> <body> Processors and nodes for analyzing ConQAT itself. </body>
Java
package io.quarkus.it.spring.data.jpa; import java.io.Serializable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.repository.NoRepositoryBean; @NoRepositoryBean public interface IntermediateRepository<T, ID extends Serializable> extends JpaRepository<T, ID> { default public void doNothing() { } default public T findMandatoryById(ID id) { return findById(id).orElseThrow(() -> new IllegalStateException("not found: " + id)); } }
Java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns.threadsafety; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.errorprone.VisitorState; import com.google.errorprone.annotations.CheckReturnValue; import com.google.errorprone.annotations.Immutable; import com.google.errorprone.annotations.ImmutableTypeParameter; import com.google.errorprone.annotations.concurrent.LazyInit; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.threadsafety.ThreadSafety.Purpose; import com.google.errorprone.bugpatterns.threadsafety.ThreadSafety.Violation; import com.google.errorprone.fixes.SuggestedFix; import com.google.errorprone.fixes.SuggestedFixes; import com.google.errorprone.matchers.Description; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ClassTree; import com.sun.source.tree.Tree; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.ClassSymbol; import com.sun.tools.javac.code.Symbol.TypeVariableSymbol; import com.sun.tools.javac.code.Symbol.VarSymbol; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.Type.ClassType; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.Predicate; import javax.lang.model.element.ElementKind; import javax.lang.model.element.Modifier; import javax.lang.model.type.TypeKind; /** Analyzes types for deep immutability. */ public class ImmutableAnalysis { private final BugChecker bugChecker; private final VisitorState state; private final WellKnownMutability wellKnownMutability; private final ThreadSafety threadSafety; ImmutableAnalysis( BugChecker bugChecker, VisitorState state, WellKnownMutability wellKnownMutability, ImmutableSet<String> immutableAnnotations) { this.bugChecker = bugChecker; this.state = state; this.wellKnownMutability = wellKnownMutability; this.threadSafety = ThreadSafety.builder() .setPurpose(Purpose.FOR_IMMUTABLE_CHECKER) .knownTypes(wellKnownMutability) .markerAnnotations(immutableAnnotations) .typeParameterAnnotation(ImmutableTypeParameter.class) .build(state); } public ImmutableAnalysis( BugChecker bugChecker, VisitorState state, WellKnownMutability wellKnownMutability) { this(bugChecker, state, wellKnownMutability, ImmutableSet.of(Immutable.class.getName())); } Violation isThreadSafeType( boolean allowContainerTypeParameters, Set<String> containerTypeParameters, Type type) { return threadSafety.isThreadSafeType( allowContainerTypeParameters, containerTypeParameters, type); } boolean hasThreadSafeTypeParameterAnnotation(TypeVariableSymbol sym) { return threadSafety.hasThreadSafeTypeParameterAnnotation(sym); } Violation checkInstantiation( Collection<TypeVariableSymbol> classTypeParameters, Collection<Type> typeArguments) { return threadSafety.checkInstantiation(classTypeParameters, typeArguments); } public Violation checkInvocation(Type methodType, Symbol symbol) { return threadSafety.checkInvocation(methodType, symbol); } /** Accepts {@link Violation violations} that are found during the analysis. */ @FunctionalInterface public interface ViolationReporter { Description.Builder describe(Tree tree, Violation info); @CheckReturnValue default Description report(Tree tree, Violation info, Optional<SuggestedFix> suggestedFix) { Description.Builder description = describe(tree, info); suggestedFix.ifPresent(description::addFix); return description.build(); } } /** * Check that an {@code @Immutable}-annotated class: * * <ul> * <li>does not declare or inherit any mutable fields, * <li>any immutable supertypes are instantiated with immutable type arguments as required by * their containerOf spec, and * <li>any enclosing instances are immutable. * </ul> * * requiring supertypes to be annotated immutable would be too restrictive. */ public Violation checkForImmutability( Optional<ClassTree> tree, ImmutableSet<String> immutableTyParams, ClassType type, ViolationReporter reporter) { Violation info = areFieldsImmutable(tree, immutableTyParams, type, reporter); if (info.isPresent()) { return info; } for (Type interfaceType : state.getTypes().interfaces(type)) { AnnotationInfo interfaceAnnotation = getImmutableAnnotation(interfaceType.tsym, state); if (interfaceAnnotation == null) { continue; } info = threadSafety.checkSuperInstantiation( immutableTyParams, interfaceAnnotation, interfaceType); if (info.isPresent()) { return info.plus( String.format( "'%s' extends '%s'", threadSafety.getPrettyName(type.tsym), threadSafety.getPrettyName(interfaceType.tsym))); } } if (!type.asElement().isEnum()) { // don't check enum super types here to avoid double-reporting errors info = checkSuper(immutableTyParams, type); if (info.isPresent()) { return info; } } Type mutableEnclosing = threadSafety.mutableEnclosingInstance(tree, type); if (mutableEnclosing != null) { return info.plus( String.format( "'%s' has mutable enclosing instance '%s'", threadSafety.getPrettyName(type.tsym), mutableEnclosing)); } return Violation.absent(); } private Violation checkSuper(ImmutableSet<String> immutableTyParams, ClassType type) { ClassType superType = (ClassType) state.getTypes().supertype(type); if (superType.getKind() == TypeKind.NONE || state.getTypes().isSameType(state.getSymtab().objectType, superType)) { return Violation.absent(); } if (WellKnownMutability.isAnnotation(state, type)) { // TODO(b/25630189): add enforcement return Violation.absent(); } AnnotationInfo superannotation = getImmutableAnnotation(superType.tsym, state); String message = String.format( "'%s' extends '%s'", threadSafety.getPrettyName(type.tsym), threadSafety.getPrettyName(superType.tsym)); if (superannotation != null) { // If the superclass does happen to be immutable, we don't need to recursively // inspect it. We just have to check that it's instantiated correctly: Violation info = threadSafety.checkSuperInstantiation(immutableTyParams, superannotation, superType); if (!info.isPresent()) { return Violation.absent(); } return info.plus(message); } // Recursive case: check if the supertype is 'effectively' immutable. Violation info = checkForImmutability( Optional.<ClassTree>empty(), immutableTyParams, superType, new ViolationReporter() { @Override public Description.Builder describe(Tree tree, Violation info) { return bugChecker .buildDescription(tree) .setMessage(info.plus(info.message()).message()); } }); if (!info.isPresent()) { return Violation.absent(); } return info.plus(message); } /** * Check a single class' fields for immutability. * * @param immutableTyParams the in-scope immutable type parameters * @param classType the type to check the fields of */ Violation areFieldsImmutable( Optional<ClassTree> tree, ImmutableSet<String> immutableTyParams, ClassType classType, ViolationReporter reporter) { ClassSymbol classSym = (ClassSymbol) classType.tsym; if (classSym.members() == null) { return Violation.absent(); } Predicate<Symbol> instanceFieldFilter = symbol -> symbol.getKind() == ElementKind.FIELD && !symbol.isStatic(); Map<Symbol, Tree> declarations = new HashMap<>(); if (tree.isPresent()) { for (Tree member : tree.get().getMembers()) { Symbol sym = ASTHelpers.getSymbol(member); if (sym != null) { declarations.put(sym, member); } } } // javac gives us members in reverse declaration order // handling them in declaration order leads to marginally better diagnostics List<Symbol> members = ImmutableList.copyOf(ASTHelpers.scope(classSym.members()).getSymbols(instanceFieldFilter)) .reverse(); for (Symbol member : members) { Optional<Tree> memberTree = Optional.ofNullable(declarations.get(member)); Violation info = isFieldImmutable( memberTree, immutableTyParams, classSym, classType, (VarSymbol) member, reporter); if (info.isPresent()) { return info; } } return Violation.absent(); } /** Check a single field for immutability. */ private Violation isFieldImmutable( Optional<Tree> tree, ImmutableSet<String> immutableTyParams, ClassSymbol classSym, ClassType classType, VarSymbol var, ViolationReporter reporter) { if (bugChecker.isSuppressed(var)) { return Violation.absent(); } if (!var.getModifiers().contains(Modifier.FINAL) && !ASTHelpers.hasAnnotation(var, LazyInit.class, state)) { Violation info = Violation.of( String.format( "'%s' has non-final field '%s'", threadSafety.getPrettyName(classSym), var.getSimpleName())); if (tree.isPresent()) { // If we have a tree to attach diagnostics to, report the error immediately instead of // accumulating the path to the error from the top-level class being checked state.reportMatch( reporter.report( tree.get(), info, SuggestedFixes.addModifiers(tree.get(), state, Modifier.FINAL))); return Violation.absent(); } return info; } Type varType = state.getTypes().memberType(classType, var); Violation info = threadSafety.isThreadSafeType( /* allowContainerTypeParameters= */ true, immutableTyParams, varType); if (info.isPresent()) { info = info.plus( String.format( "'%s' has field '%s' of type '%s'", threadSafety.getPrettyName(classSym), var.getSimpleName(), varType)); if (tree.isPresent()) { // If we have a tree to attach diagnostics to, report the error immediately instead of // accumulating the path to the error from the top-level class being checked state.reportMatch(reporter.report(tree.get(), info, Optional.empty())); return Violation.absent(); } return info; } return Violation.absent(); } /** * Gets the {@link Symbol}'s {@code @Immutable} annotation info, either from an annotation on the * symbol or from the list of well-known immutable types. */ AnnotationInfo getImmutableAnnotation(Symbol sym, VisitorState state) { String nameStr = sym.flatName().toString(); AnnotationInfo known = wellKnownMutability.getKnownImmutableClasses().get(nameStr); if (known != null) { return known; } return threadSafety.getInheritedAnnotation(sym, state); } /** * Gets the {@link Tree}'s {@code @Immutable} annotation info, either from an annotation on the * symbol or from the list of well-known immutable types. */ AnnotationInfo getImmutableAnnotation(Tree tree, VisitorState state) { Symbol sym = ASTHelpers.getSymbol(tree); return sym == null ? null : threadSafety.getMarkerOrAcceptedAnnotation(sym, state); } }
Java
package com.planet_ink.coffee_mud.Abilities.Songs; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2000-2014 Bo Zimmerman Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ public class Play_Organs extends Play_Instrument { @Override public String ID() { return "Play_Organs"; } private final static String localizedName = CMLib.lang()._("Organs"); @Override public String name() { return localizedName; } @Override protected int requiredInstrumentType(){return MusicalInstrument.TYPE_ORGANS;} @Override public String mimicSpell(){return "Prayer_ProtectHealth";} @Override protected int canAffectCode(){return 0;} private static Ability theSpell=null; @Override protected Ability getSpell() { if(theSpell!=null) return theSpell; if(mimicSpell().length()==0) return null; theSpell=CMClass.getAbility(mimicSpell()); return theSpell; } }
Java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.bookkeeper.mledger; public class ManagedLedgerFactoryConfig { private static final long MB = 1024 * 1024; private long maxCacheSize = 128 * MB; private double cacheEvictionWatermark = 0.90; public long getMaxCacheSize() { return maxCacheSize; } /** * * @param maxCacheSize * @return */ public ManagedLedgerFactoryConfig setMaxCacheSize(long maxCacheSize) { this.maxCacheSize = maxCacheSize; return this; } public double getCacheEvictionWatermark() { return cacheEvictionWatermark; } /** * The cache eviction watermark is the percentage of the cache size to reach when removing entries from the cache. * * @param cacheEvictionWatermark * @return */ public ManagedLedgerFactoryConfig setCacheEvictionWatermark(double cacheEvictionWatermark) { this.cacheEvictionWatermark = cacheEvictionWatermark; return this; } }
Java
<!DOCTYPE html > <html> <head> <title>Tables - ScalaTest 3.0.1 - org.scalatest.prop.Tables</title> <meta name="description" content="Tables - ScalaTest 3.0.1 - org.scalatest.prop.Tables" /> <meta name="keywords" content="Tables ScalaTest 3.0.1 org.scalatest.prop.Tables" /> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <link href="../../../lib/template.css" media="screen" type="text/css" rel="stylesheet" /> <link href="../../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" /> <script type="text/javascript" src="../../../lib/jquery.js" id="jquery-js"></script> <script type="text/javascript" src="../../../lib/jquery-ui.js"></script> <script type="text/javascript" src="../../../lib/template.js"></script> <script type="text/javascript" src="../../../lib/tools.tooltip.js"></script> <script type="text/javascript"> if(top === self) { var url = '../../../index.html'; var hash = 'org.scalatest.prop.Tables$'; var anchor = window.location.hash; var anchor_opt = ''; if (anchor.length >= 1) anchor_opt = '@' + anchor.substring(1); window.location.href = url + '#' + hash + anchor_opt; } </script> </head> <body class="value"> <!-- Top of doc.scalatest.org [javascript] --> <script type="text/javascript"> var rnd = window.rnd || Math.floor(Math.random()*10e6); var pid204546 = window.pid204546 || rnd; var plc204546 = window.plc204546 || 0; var abkw = window.abkw || ''; var absrc = 'http://ab167933.adbutler-ikon.com/adserve/;ID=167933;size=468x60;setID=204546;type=js;sw='+screen.width+';sh='+screen.height+';spr='+window.devicePixelRatio+';kw='+abkw+';pid='+pid204546+';place='+(plc204546++)+';rnd='+rnd+';click=CLICK_MACRO_PLACEHOLDER'; document.write('<scr'+'ipt src="'+absrc+'" type="text/javascript"></scr'+'ipt>'); </script> <div id="definition"> <a href="Tables.html" title="See companion trait"><img alt="Object/Trait" src="../../../lib/object_to_trait_big.png" /></a> <p id="owner"><a href="../../package.html" class="extype" name="org">org</a>.<a href="../package.html" class="extype" name="org.scalatest">scalatest</a>.<a href="package.html" class="extype" name="org.scalatest.prop">prop</a></p> <h1><a href="Tables.html" title="See companion trait">Tables</a></h1><h3><span class="morelinks"><div> Related Docs: <a href="Tables.html" title="See companion trait">trait Tables</a> | <a href="package.html" class="extype" name="org.scalatest.prop">package prop</a> </div></span></h3><span class="permalink"> <a href="../../../index.html#org.scalatest.prop.Tables$" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> </div> <h4 id="signature" class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">object</span> </span> <span class="symbol"> <span class="name">Tables</span><span class="result"> extends <a href="Tables.html" class="extype" name="org.scalatest.prop.Tables">Tables</a></span> </span> </h4> <div id="comment" class="fullcommenttop"><div class="comment cmt"><p>Companion object that facilitates the importing of <code>Tables</code> members as an alternative to mixing it in. One use case is to import <code>Tables</code> members so you can use them in the Scala interpreter:</p><p><pre> Welcome to Scala version 2.8.0.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_22). Type in expressions to have them evaluated. Type :help for more information. scala> import org.scalatest.prop.Tables._ import org.scalatest.prop.Tables._ scala> val examples = | Table( | ("a", "b"), | ( 1, 2), | ( 3, 4) | ) examples: org.scalatest.prop.TableFor2[Int,Int] = TableFor2((1,2), (3,4)) </pre> </p></div><dl class="attributes block"> <dt>Source</dt><dd><a href="https://github.com/scalatest/scalatest/tree/release-3.0.1/scalatest//scala/gentables/Tables.scala" target="_blank">Tables.scala</a></dd></dl><div class="toggleContainer block"> <span class="toggle">Linear Supertypes</span> <div class="superTypes hiddenContent"><a href="Tables.html" class="extype" name="org.scalatest.prop.Tables">Tables</a>, <span class="extype" name="scala.AnyRef">AnyRef</span>, <span class="extype" name="scala.Any">Any</span></div> </div></div> <div id="mbrsel"> <div id="textfilter"><span class="pre"></span><span class="input"><input id="mbrsel-input" type="text" accesskey="/" /></span><span class="post"></span></div> <div id="order"> <span class="filtertype">Ordering</span> <ol> <li class="alpha in"><span>Alphabetic</span></li> <li class="inherit out"><span>By Inheritance</span></li> </ol> </div> <div id="ancestors"> <span class="filtertype">Inherited<br /> </span> <ol id="linearization"> <li class="in" name="org.scalatest.prop.Tables"><span>Tables</span></li><li class="in" name="org.scalatest.prop.Tables"><span>Tables</span></li><li class="in" name="scala.AnyRef"><span>AnyRef</span></li><li class="in" name="scala.Any"><span>Any</span></li> </ol> </div><div id="ancestors"> <span class="filtertype"></span> <ol> <li class="hideall out"><span>Hide All</span></li> <li class="showall in"><span>Show All</span></li> </ol> </div> <div id="visbl"> <span class="filtertype">Visibility</span> <ol><li class="public in"><span>Public</span></li><li class="all out"><span>All</span></li></ol> </div> </div> <div id="template"> <div id="allMembers"> <div id="values" class="values members"> <h3>Value Members</h3> <ol><li name="scala.AnyRef#!=" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="!=(x$1:Any):Boolean"></a> <a id="!=(Any):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $bang$eq" class="name">!=</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#org.scalatest.prop.Tables$@!=(x$1:Any):Boolean" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef###" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="##():Int"></a> <a id="##():Int"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $hash$hash" class="name">##</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#org.scalatest.prop.Tables$@##():Int" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#==" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="==(x$1:Any):Boolean"></a> <a id="==(Any):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $eq$eq" class="name">==</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#org.scalatest.prop.Tables$@==(x$1:Any):Boolean" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="org.scalatest.prop.Tables.Table" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="Table"></a> <a id="Table:Table"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">object</span> </span> <span class="symbol"> <a href="Tables$Table$.html"><span class="name">Table</span></a> </span> </h4><span class="permalink"> <a href="../../../index.html#org.scalatest.prop.Tables@Table" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <p class="shortcomment cmt">Object containing one <code>apply</code> factory method for each <code>TableFor&lt;n&gt;</code> class.</code></code></p><div class="fullcomment"><div class="comment cmt"><p>Object containing one <code>apply</code> factory method for each <code>TableFor&lt;n&gt;</code> class.</p><p>For example, you could create a table of 5 rows and 2 colums like this:</p><p><pre class="stHighlighted"> <span class="stReserved">import</span> org.scalatest.prop.Tables._ <span class="stReserved">val</span> examples = <span class="stType">Table</span>( (<span class="stQuotedString">"a"</span>, <span class="stQuotedString">"b"</span>), ( <span class="stLiteral">1</span>, <span class="stLiteral">2</span>), ( <span class="stLiteral">2</span>, <span class="stLiteral">4</span>), ( <span class="stLiteral">4</span>, <span class="stLiteral">8</span>), ( <span class="stLiteral">8</span>, <span class="stLiteral">16</span>), ( <span class="stLiteral">16</span>, <span class="stLiteral">32</span>) ) </pre></p><p>Because you supplied 2 members in each tuple, the type you'll get back will be a <code>TableFor2</code>. If you wanted a table with just one column you could write this:</p><p><pre class="stHighlighted"> <span class="stReserved">val</span> moreExamples = <span class="stType">Table</span>( <span class="stQuotedString">"powerOfTwo"</span>, <span class="stLiteral">1</span>, <span class="stLiteral">2</span>, <span class="stLiteral">4</span>, <span class="stLiteral">8</span>, <span class="stLiteral">16</span> ) </pre></p><p>Or if you wanted a table with 10 columns and 10 rows, you could do this:</p><p><pre class="stHighlighted"> <span class="stReserved">val</span> multiplicationTable = <span class="stType">Table</span>( (<span class="stQuotedString">"a"</span>, <span class="stQuotedString">"b"</span>, <span class="stQuotedString">"c"</span>, <span class="stQuotedString">"d"</span>, <span class="stQuotedString">"e"</span>, <span class="stQuotedString">"f"</span>, <span class="stQuotedString">"g"</span>, <span class="stQuotedString">"h"</span>, <span class="stQuotedString">"i"</span>, <span class="stQuotedString">"j"</span>), ( <span class="stLiteral">1</span>, <span class="stLiteral">2</span>, <span class="stLiteral">3</span>, <span class="stLiteral">4</span>, <span class="stLiteral">5</span>, <span class="stLiteral">6</span>, <span class="stLiteral">7</span>, <span class="stLiteral">8</span>, <span class="stLiteral">9</span>, <span class="stLiteral">10</span>), ( <span class="stLiteral">2</span>, <span class="stLiteral">4</span>, <span class="stLiteral">6</span>, <span class="stLiteral">8</span>, <span class="stLiteral">10</span>, <span class="stLiteral">12</span>, <span class="stLiteral">14</span>, <span class="stLiteral">16</span>, <span class="stLiteral">18</span>, <span class="stLiteral">20</span>), ( <span class="stLiteral">3</span>, <span class="stLiteral">6</span>, <span class="stLiteral">9</span>, <span class="stLiteral">12</span>, <span class="stLiteral">15</span>, <span class="stLiteral">18</span>, <span class="stLiteral">21</span>, <span class="stLiteral">24</span>, <span class="stLiteral">27</span>, <span class="stLiteral">30</span>), ( <span class="stLiteral">4</span>, <span class="stLiteral">8</span>, <span class="stLiteral">12</span>, <span class="stLiteral">16</span>, <span class="stLiteral">20</span>, <span class="stLiteral">24</span>, <span class="stLiteral">28</span>, <span class="stLiteral">32</span>, <span class="stLiteral">36</span>, <span class="stLiteral">40</span>), ( <span class="stLiteral">5</span>, <span class="stLiteral">10</span>, <span class="stLiteral">15</span>, <span class="stLiteral">20</span>, <span class="stLiteral">25</span>, <span class="stLiteral">30</span>, <span class="stLiteral">35</span>, <span class="stLiteral">40</span>, <span class="stLiteral">45</span>, <span class="stLiteral">50</span>), ( <span class="stLiteral">6</span>, <span class="stLiteral">12</span>, <span class="stLiteral">18</span>, <span class="stLiteral">24</span>, <span class="stLiteral">30</span>, <span class="stLiteral">36</span>, <span class="stLiteral">42</span>, <span class="stLiteral">48</span>, <span class="stLiteral">54</span>, <span class="stLiteral">60</span>), ( <span class="stLiteral">7</span>, <span class="stLiteral">14</span>, <span class="stLiteral">21</span>, <span class="stLiteral">28</span>, <span class="stLiteral">35</span>, <span class="stLiteral">42</span>, <span class="stLiteral">49</span>, <span class="stLiteral">56</span>, <span class="stLiteral">63</span>, <span class="stLiteral">70</span>), ( <span class="stLiteral">8</span>, <span class="stLiteral">16</span>, <span class="stLiteral">24</span>, <span class="stLiteral">32</span>, <span class="stLiteral">40</span>, <span class="stLiteral">48</span>, <span class="stLiteral">56</span>, <span class="stLiteral">64</span>, <span class="stLiteral">72</span>, <span class="stLiteral">80</span>), ( <span class="stLiteral">9</span>, <span class="stLiteral">18</span>, <span class="stLiteral">27</span>, <span class="stLiteral">36</span>, <span class="stLiteral">45</span>, <span class="stLiteral">54</span>, <span class="stLiteral">63</span>, <span class="stLiteral">72</span>, <span class="stLiteral">81</span>, <span class="stLiteral">90</span>), ( <span class="stLiteral">10</span>, <span class="stLiteral">20</span>, <span class="stLiteral">30</span>, <span class="stLiteral">40</span>, <span class="stLiteral">50</span>, <span class="stLiteral">60</span>, <span class="stLiteral">70</span>, <span class="stLiteral">80</span>, <span class="stLiteral">90</span>, <span class="stLiteral">100</span>) ) </pre></p><p>The type of <code>multiplicationTable</code> would be <code>TableFor10</code>. You can pass the resulting tables to a <code>forAll</code> method (defined in trait <code>PropertyChecks</code>), to perform a property check with the data in the table. Or, because tables are sequences of tuples, you can treat them as a <code>Seq</code>.</p></div><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="Tables.html" class="extype" name="org.scalatest.prop.Tables">Tables</a></dd></dl></div> </li><li name="scala.Any#asInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="asInstanceOf[T0]:T0"></a> <a id="asInstanceOf[T0]:T0"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">asInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Any.asInstanceOf.T0">T0</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#org.scalatest.prop.Tables$@asInstanceOf[T0]:T0" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="scala.AnyRef#clone" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="clone():Object"></a> <a id="clone():AnyRef"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">clone</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.AnyRef">AnyRef</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#org.scalatest.prop.Tables$@clone():Object" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.CloneNotSupportedException]">...</span> </span>)</span> </dd></dl></div> </li><li name="scala.AnyRef#eq" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="eq(x$1:AnyRef):Boolean"></a> <a id="eq(AnyRef):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">eq</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#org.scalatest.prop.Tables$@eq(x$1:AnyRef):Boolean" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#equals" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="equals(x$1:Any):Boolean"></a> <a id="equals(Any):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">equals</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#org.scalatest.prop.Tables$@equals(x$1:Any):Boolean" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#finalize" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="finalize():Unit"></a> <a id="finalize():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">finalize</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#org.scalatest.prop.Tables$@finalize():Unit" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="symbol">classOf[java.lang.Throwable]</span> </span>)</span> </dd></dl></div> </li><li name="scala.AnyRef#getClass" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="getClass():Class[_]"></a> <a id="getClass():Class[_]"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">getClass</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.Class">Class</span>[_]</span> </span> </h4><span class="permalink"> <a href="../../../index.html#org.scalatest.prop.Tables$@getClass():Class[_]" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#hashCode" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="hashCode():Int"></a> <a id="hashCode():Int"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">hashCode</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#org.scalatest.prop.Tables$@hashCode():Int" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.Any#isInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="isInstanceOf[T0]:Boolean"></a> <a id="isInstanceOf[T0]:Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">isInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#org.scalatest.prop.Tables$@isInstanceOf[T0]:Boolean" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="scala.AnyRef#ne" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="ne(x$1:AnyRef):Boolean"></a> <a id="ne(AnyRef):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">ne</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#org.scalatest.prop.Tables$@ne(x$1:AnyRef):Boolean" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#notify" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="notify():Unit"></a> <a id="notify():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">notify</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#org.scalatest.prop.Tables$@notify():Unit" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#notifyAll" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="notifyAll():Unit"></a> <a id="notifyAll():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">notifyAll</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#org.scalatest.prop.Tables$@notifyAll():Unit" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#synchronized" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="synchronized[T0](x$1:=&gt;T0):T0"></a> <a id="synchronized[T0](⇒T0):T0"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">synchronized</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="params">(<span name="arg0">arg0: ⇒ <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>)</span><span class="result">: <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#org.scalatest.prop.Tables$@synchronized[T0](x$1:=&gt;T0):T0" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#toString" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="toString():String"></a> <a id="toString():String"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">toString</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.String">String</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#org.scalatest.prop.Tables$@toString():String" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait():Unit"></a> <a id="wait():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#org.scalatest.prop.Tables$@wait():Unit" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.InterruptedException]">...</span> </span>)</span> </dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait(x$1:Long,x$2:Int):Unit"></a> <a id="wait(Long,Int):Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>, <span name="arg1">arg1: <span class="extype" name="scala.Int">Int</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#org.scalatest.prop.Tables$@wait(x$1:Long,x$2:Int):Unit" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.InterruptedException]">...</span> </span>)</span> </dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait(x$1:Long):Unit"></a> <a id="wait(Long):Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4><span class="permalink"> <a href="../../../index.html#org.scalatest.prop.Tables$@wait(x$1:Long):Unit" title="Permalink" target="_top"> <img src="../../../lib/permalink.png" alt="Permalink" /> </a> </span> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">(<span> <span class="defval" name="classOf[java.lang.InterruptedException]">...</span> </span>)</span> </dd></dl></div> </li></ol> </div> </div> <div id="inheritedMembers"> <div class="parent" name="org.scalatest.prop.Tables"> <h3>Inherited from <a href="Tables.html" class="extype" name="org.scalatest.prop.Tables">Tables</a></h3> </div><div class="parent" name="scala.AnyRef"> <h3>Inherited from <span class="extype" name="scala.AnyRef">AnyRef</span></h3> </div><div class="parent" name="scala.Any"> <h3>Inherited from <span class="extype" name="scala.Any">Any</span></h3> </div> </div> <div id="groupedMembers"> <div class="group" name="Ungrouped"> <h3>Ungrouped</h3> </div> </div> </div> <div id="tooltip"></div> <div id="footer"> </div> </body> </html>
Java
// Copyright 2016 Pikkpoiss // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package gamejam type SceneID int type Scene interface { AddComponent(c Component) Load(r Resources) (err error) Unload(r Resources) (err error) Render() Update(mgr SceneManager) SetSceneID(id SceneID) SceneID() SceneID } type BaseScene struct { components map[ComponentID]Component id SceneID } func NewBaseScene() *BaseScene { return &BaseScene{ components: map[ComponentID]Component{}, } } func (s *BaseScene) AddComponent(c Component) { c.SetScene(s) s.components[c.GetID()] = c } func (s *BaseScene) Load(r Resources) (err error) { return } func (s *BaseScene) Render() { } func (s *BaseScene) SetSceneID(id SceneID) { s.id = id } func (s *BaseScene) SceneID() SceneID { return s.id } func (s *BaseScene) Unload(r Resources) (err error) { var ( id ComponentID c Component ) for id, c = range s.components { s.components[id] = nil c.Delete() } //s.DeleteObservers() return } func (s *BaseScene) Update(mgr SceneManager) { }
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_55) on Sun Oct 26 05:56:34 EDT 2014 --> <meta http-equiv="Content-Type" content="text/html" charset="utf-8"> <title>Uses of Class org.apache.solr.handler.component.FacetComponent.FacetBase (Solr 4.10.2 API)</title> <meta name="date" content="2014-10-26"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.solr.handler.component.FacetComponent.FacetBase (Solr 4.10.2 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/solr/handler/component/FacetComponent.FacetBase.html" title="class in org.apache.solr.handler.component">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/solr/handler/component/class-use/FacetComponent.FacetBase.html" target="_top">Frames</a></li> <li><a href="FacetComponent.FacetBase.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.apache.solr.handler.component.FacetComponent.FacetBase" class="title">Uses of Class<br>org.apache.solr.handler.component.FacetComponent.FacetBase</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../../org/apache/solr/handler/component/FacetComponent.FacetBase.html" title="class in org.apache.solr.handler.component">FacetComponent.FacetBase</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.apache.solr.handler.component">org.apache.solr.handler.component</a></td> <td class="colLast"> <div class="block"> <a href="../../../../../../org/apache/solr/handler/component/SearchComponent.html" title="class in org.apache.solr.handler.component"><code>SearchComponent</code></a> implementations for use in <a href="../../../../../../org/apache/solr/handler/component/SearchHandler.html" title="class in org.apache.solr.handler.component"><code>SearchHandler</code></a></div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.apache.solr.handler.component"> <!-- --> </a> <h3>Uses of <a href="../../../../../../org/apache/solr/handler/component/FacetComponent.FacetBase.html" title="class in org.apache.solr.handler.component">FacetComponent.FacetBase</a> in <a href="../../../../../../org/apache/solr/handler/component/package-summary.html">org.apache.solr.handler.component</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation"> <caption><span>Subclasses of <a href="../../../../../../org/apache/solr/handler/component/FacetComponent.FacetBase.html" title="class in org.apache.solr.handler.component">FacetComponent.FacetBase</a> in <a href="../../../../../../org/apache/solr/handler/component/package-summary.html">org.apache.solr.handler.component</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Class and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>static class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../org/apache/solr/handler/component/FacetComponent.DistribFieldFacet.html" title="class in org.apache.solr.handler.component">FacetComponent.DistribFieldFacet</a></strong></code> <div class="block"><b>This API is experimental and subject to change</b></div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>static class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../org/apache/solr/handler/component/FacetComponent.FieldFacet.html" title="class in org.apache.solr.handler.component">FacetComponent.FieldFacet</a></strong></code> <div class="block"><b>This API is experimental and subject to change</b></div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>static class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../org/apache/solr/handler/component/FacetComponent.QueryFacet.html" title="class in org.apache.solr.handler.component">FacetComponent.QueryFacet</a></strong></code> <div class="block"><b>This API is experimental and subject to change</b></div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>class&nbsp;</code></td> <td class="colLast"><code><strong><a href="../../../../../../org/apache/solr/handler/component/PivotFacet.html" title="class in org.apache.solr.handler.component">PivotFacet</a></strong></code> <div class="block">Models a single instance of a "pivot" specified by a <a href="../../../../../../../solr-solrj/org/apache/solr/common/params/FacetParams.html?is-external=true#FACET_PIVOT" title="class or interface in org.apache.solr.common.params"><code>FacetParams.FACET_PIVOT</code></a> param, which may contain multiple nested fields.</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/solr/handler/component/FacetComponent.FacetBase.html" title="class in org.apache.solr.handler.component">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/solr/handler/component/class-use/FacetComponent.FacetBase.html" target="_top">Frames</a></li> <li><a href="FacetComponent.FacetBase.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small> <i>Copyright &copy; 2000-2014 Apache Software Foundation. All Rights Reserved.</i> <script src='../../../../../../prettify.js' type='text/javascript'></script> <script type='text/javascript'> (function(){ var oldonload = window.onload; if (typeof oldonload != 'function') { window.onload = prettyPrint; } else { window.onload = function() { oldonload(); prettyPrint(); } } })(); </script> </small></p> </body> </html>
Java
package com.mygame; import java.util.Vector; import loon.geom.RectBox; public class StepSwitch extends Switch { StepSwitch(int x, int y, Vector<Thing> blocks) { this.x = x; this.y = y; this.blocks = blocks; orgblocks = new Vector<Thing>(); for(int i = 0; i < blocks.size(); i++) orgblocks.add((Thing)blocks.get(i)); height = 50; width = 50; active = false; col = new RectBox(x, y, width, height); } public void update(Player player, Vector<Thing> things) { boolean b = false; for(int i = 0; i < things.size(); i++) if(col.intersects((int)((Thing)things.get(i)).x, (int)((Thing)things.get(i)).y, ((Thing)things.get(i)).width, ((Thing)things.get(i)).height) && !b) { b = true; active = true; blocks.clear(); } if(col.intersects((int)player.x, (int)player.y, player.width, player.height)) { b = true; active = true; blocks.clear(); } if(!b) { active = false; if(blocks.isEmpty()) { for(int i = 0; i < orgblocks.size(); i++) blocks.add((Thing)orgblocks.get(i)); } } } }
Java
/* * DateAxisBuilder.java * * Created on March 17, 2007, 10:17 PM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package com.thecoderscorner.groovychart.axis; import java.beans.IntrospectionException; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import com.thecoderscorner.groovychart.chart.Buildable; import com.thecoderscorner.groovychart.chart.ChartBuilder; import com.thecoderscorner.groovychart.chart.BeanBuilder; import org.jfree.chart.axis.NumberAxis; /** * * @author jclarke */ public class NumberAxisBuilder extends BeanBuilder implements Buildable{ private static final Logger logger = Logger.getLogger(NumberAxisBuilder.class.getPackage().getName()); private NumberAxis axis = new NumberAxis(); private boolean domain; /** * Creates a new instance of DateAxisBuilder */ public NumberAxisBuilder() { try { setBeanClass(NumberAxis.class); } catch (IntrospectionException ex) { logger.log(Level.WARNING, ex.getMessage(), ex); } } public void setChartBuilder(ChartBuilder chartBuilder) { } public void processNode(Object name, Map map, Object value) throws Exception { String method = name.toString(); if(value != null) { this.axis = (NumberAxis)value; }else { if(logger.isLoggable(Level.FINEST)) logger.finest("processNode: method = " + method); if(method.equalsIgnoreCase("NumberAxis")) { this.setProperties(this.axis, map); } } } private Object parent; public Object getParent() { return parent; } public void setParent(Object parent) { this.parent = parent; } public void nodeCompleted(Object parent) { if(parent != null && parent instanceof AxisSettable) { logger.finest("Setting axis on parent"); ((AxisSettable)parent).setAxis(this.axis); } } private String name; public String getName() { return this.name; } public void setName(String name) { this.name = name; } public NumberAxis getAxis() { return axis; } }
Java
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.servicecatalog.model.transform; import java.util.Map; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.servicecatalog.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * UpdateServiceActionRequestMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class UpdateServiceActionRequestMarshaller { private static final MarshallingInfo<String> ID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Id").build(); private static final MarshallingInfo<String> NAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Name").build(); private static final MarshallingInfo<Map> DEFINITION_BINDING = MarshallingInfo.builder(MarshallingType.MAP).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Definition").build(); private static final MarshallingInfo<String> DESCRIPTION_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("Description").build(); private static final MarshallingInfo<String> ACCEPTLANGUAGE_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("AcceptLanguage").build(); private static final UpdateServiceActionRequestMarshaller instance = new UpdateServiceActionRequestMarshaller(); public static UpdateServiceActionRequestMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(UpdateServiceActionRequest updateServiceActionRequest, ProtocolMarshaller protocolMarshaller) { if (updateServiceActionRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(updateServiceActionRequest.getId(), ID_BINDING); protocolMarshaller.marshall(updateServiceActionRequest.getName(), NAME_BINDING); protocolMarshaller.marshall(updateServiceActionRequest.getDefinition(), DEFINITION_BINDING); protocolMarshaller.marshall(updateServiceActionRequest.getDescription(), DESCRIPTION_BINDING); protocolMarshaller.marshall(updateServiceActionRequest.getAcceptLanguage(), ACCEPTLANGUAGE_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
Java
#!/bin/bash rm -rf php-5.3.29 if [ ! -f php-5.3.29.tar.gz ];then wget http://zy-res.oss-cn-hangzhou.aliyuncs.com/php/php-5.3.29.tar.gz fi tar zxvf php-5.3.29.tar.gz cd php-5.3.29 ./configure --prefix=/alidata/server/php \ --with-config-file-path=/alidata/server/php/etc \ --with-mysql=mysqlnd \ --with-mysqli=mysqlnd \ --with-pdo-mysql=mysqlnd \ --enable-fpm \ --enable-fastcgi \ --enable-static \ --enable-maintainer-zts \ --enable-zend-multibyte \ --enable-inline-optimization \ --enable-sockets \ --enable-wddx \ --enable-zip \ --enable-calendar \ --enable-bcmath \ --enable-soap \ --with-zlib \ --with-iconv \ --with-gd \ --with-xmlrpc \ --enable-mbstring \ --without-sqlite \ --with-curl \ --enable-ftp \ --with-mcrypt \ --with-freetype-dir=/usr/local/freetype.2.1.10 \ --with-jpeg-dir=/usr/local/jpeg.6 \ --with-png-dir=/usr/local/libpng.1.2.50 \ --disable-ipv6 \ --disable-debug \ --with-openssl \ --disable-maintainer-zts \ --disable-safe-mode \ --disable-fileinfo CPU_NUM=$(cat /proc/cpuinfo | grep processor | wc -l) if [ $CPU_NUM -gt 1 ];then make ZEND_EXTRA_LIBS='-liconv' -j$CPU_NUM else make ZEND_EXTRA_LIBS='-liconv' fi make install cd .. cp ./php-5.3.29/php.ini-production /alidata/server/php/etc/php.ini #adjust php.ini sed -i 's#; extension_dir = \"\.\/\"#extension_dir = "/alidata/server/php/lib/php/extensions/no-debug-non-zts-20090626/"#' /alidata/server/php/etc/php.ini sed -i 's/post_max_size = 8M/post_max_size = 64M/g' /alidata/server/php/etc/php.ini sed -i 's/upload_max_filesize = 2M/upload_max_filesize = 64M/g' /alidata/server/php/etc/php.ini sed -i 's/;date.timezone =/date.timezone = PRC/g' /alidata/server/php/etc/php.ini sed -i 's/;cgi.fix_pathinfo=1/cgi.fix_pathinfo=1/g' /alidata/server/php/etc/php.ini sed -i 's/max_execution_time = 30/max_execution_time = 300/g' /alidata/server/php/etc/php.ini #adjust php-fpm cp /alidata/server/php/etc/php-fpm.conf.default /alidata/server/php/etc/php-fpm.conf sed -i 's,user = nobody,user=www,g' /alidata/server/php/etc/php-fpm.conf sed -i 's,group = nobody,group=www,g' /alidata/server/php/etc/php-fpm.conf sed -i 's,^pm.min_spare_servers = 1,pm.min_spare_servers = 5,g' /alidata/server/php/etc/php-fpm.conf sed -i 's,^pm.max_spare_servers = 3,pm.max_spare_servers = 35,g' /alidata/server/php/etc/php-fpm.conf sed -i 's,^pm.max_children = 5,pm.max_children = 100,g' /alidata/server/php/etc/php-fpm.conf sed -i 's,^pm.start_servers = 2,pm.start_servers = 20,g' /alidata/server/php/etc/php-fpm.conf sed -i 's,;pid = run/php-fpm.pid,pid = run/php-fpm.pid,g' /alidata/server/php/etc/php-fpm.conf sed -i 's,;error_log = log/php-fpm.log,error_log = /alidata/log/php/php-fpm.log,g' /alidata/server/php/etc/php-fpm.conf sed -i 's,;slowlog = log/$pool.log.slow,slowlog = /alidata/log/php/\$pool.log.slow,g' /alidata/server/php/etc/php-fpm.conf #self start install -v -m755 ./php-5.3.29/sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm /etc/init.d/php-fpm start sleep 5
Java
codeigniter ===========
Java
#!/usr/bin/env bash echo "STABLE_K8S_CLUSTER MyCluster" echo 'COMPLEX_JSON { nested: { secret: "top" } }'
Java
<pre style="word-wrap: break-word; white-space: pre-wrap;"> This corpus were recorded in silence in-door environment using cellphone. It has 10 speakers. Each speaker has about 350 utterances. All utterances were carefully transcribed and checked by human. Transcription accuracy is guaranteed. If there is any problems, we agree to correct them for you. Please cite the data as “ST-AEDS-20180100_1, Free ST American English Corpus”. The data set is a subset of a much bigger data set (about 1000hours) which was recorded in the same environment as this open source data. Please visit our website <a target="_Blank" href="https://www.surfing.ai/">www.surfing.ai</a> or contact us at contact@surfingtech.cn for details. </pre>
Java
$(document).ready(function(){ $('#datepickerDay1').hide(); $('#datepickerDay2').hide(); $('#datepickerMnd1').hide(); $('#datepickerMnd2').hide(); $('#datepickerYear1').hide(); $('#datepickerYear2').hide(); $('select').change(function(){ var index = $('select').val(); if(index == 0){ //day $('#datepickerDay1').show(); $('#datepickerDay2').show(); $('#datepickerMnd1').hide(); $('#datepickerMnd2').hide(); $('#datepickerYear1').hide(); $('#datepickerYear2').hide(); localStorage.setItem('type','0'); } else if(index == 1){ //month $('#datepickerMnd1').show(); $('#datepickerMnd2').show(); $('#datepickerDay1').hide(); $('#datepickerDay2').hide(); $('#datepickerYear1').hide(); $('#datepickerYear2').hide(); localStorage.setItem('type','1'); } else if(index == 2){ //year $('#datepickerYear1').show(); $('#datepickerYear2').show(); $('#datepickerDay1').hide(); $('#datepickerDay2').hide(); $('#datepickerMnd1').hide(); $('#datepickerMnd2').hide(); localStorage.setItem('type','2'); } }); $('#datepickerDay1').datepicker({ format: "yyyy-mm-dd", weekStart: 1, language: "no", todayHighlight: true }); $('#datepickerDay1').on('changeDate', function(ev){ $(this).datepicker('hide'); day1(); if ($('input[name=date2]').val() != "") { showChart1(); showChart2(); showChart3(); showChart4(); showChart5(); showChart6(); } }); $('#datepickerDay2').datepicker({ format: "yyyy-mm-dd", weekStart: 1, language: "no", todayHighlight: true }); $('#datepickerDay2').on('changeDate', function(ev){ $(this).datepicker('hide'); day2(); if ($('input[name=date]').val() != "") { showChart1(); showChart2(); showChart3(); showChart4(); showChart5(); showChart6(); } }); $('#datepickerYear1').datepicker({ format: "yyyy", weekStart: 1, startView: 1, minViewMode: 2, language: "no", todayHighlight: true }); $('#datepickerYear1').on('changeDate', function(ev){ $(this).datepicker('hide'); year1(); if ($('input[name=date6]').val() != "") { showChart1(); showChart2(); showChart3(); showChart4(); showChart5(); showChart6(); } }); $('#datepickerYear2').datepicker({ format: "yyyy", weekStart: 1, startView: 1, minViewMode: 2, language: "no", todayHighlight: true }); $('#datepickerYear2').on('changeDate', function(ev){ $(this).datepicker('hide'); year2(); if ($('input[name=date5]').val() != "") { showChart1(); showChart2(); showChart3(); showChart4(); showChart5(); showChart6(); } }); $('#datepickerMnd1').datepicker({ format: "yyyy-mm", weekStart: 1, startView: 0, minViewMode: 1, language: "no", todayHighlight: true }); $('#datepickerMnd1').on('changeDate', function(ev){ $(this).datepicker('hide'); mnd1(); if ($('input[name=date4]').val() != "") { showChart1(); showChart2(); showChart3(); showChart4(); showChart5(); showChart6(); } }); $('#datepickerMnd2').datepicker({ format: "yyyy-mm", weekStart: 1, startView: 0, minViewMode: 1, language: "no", todayHighlight: true }); $('#datepickerMnd2').on('changeDate', function(ev){ $(this).datepicker('hide'); mnd2(); if ($('input[name=date3]').val() != "") { showChart1(); showChart2(); showChart3(); showChart4(); showChart5(); showChart6(); } }); $('#backBtn').on('click', function(ev){ window.location.replace("../pages/stats.php"); }); function day1(){ var day = $('input[name=date]').val(); var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function(){ if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById("firstDate").innerHTML = xmlhttp.responseText; } } xmlhttp.open("GET", "../phpBackend/OrgStat/day.php?date=" + day, true); xmlhttp.send(); } function day2(){ var day = $('input[name=date2]').val(); var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function(){ if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById("lastDate").innerHTML = xmlhttp.responseText; } } xmlhttp.open("GET", "../phpBackend/OrgStat/day.php?date=" + day, true); xmlhttp.send(); } function mnd1(){ var day = $('input[name=date3]').val() + '-01'; var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function(){ if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById("firstDate").innerHTML = xmlhttp.responseText; } } xmlhttp.open("GET", "../phpBackend/OrgStat/month.php?date=" + day, true); xmlhttp.send(); } function mnd2(){ var day = $('input[name=date4]').val() + '-01'; var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function(){ if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById("lastDate").innerHTML = xmlhttp.responseText; } } xmlhttp.open("GET", "../phpBackend/OrgStat/month.php?date=" + day, true); xmlhttp.send(); } function year1(){ var day = $('input[name=date5]').val(); var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function(){ if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById("firstDate").innerHTML = xmlhttp.responseText; } } xmlhttp.open("GET", "../phpBackend/OrgStat/year.php?date=" + day, true); xmlhttp.send(); } function year2(){ var day = $('input[name=date6]').val(); var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function(){ if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById("lastDate").innerHTML = xmlhttp.responseText; } } xmlhttp.open("GET", "../phpBackend/OrgStat/year.php?date=" + day, true); xmlhttp.send(); } function showChart1(){ var data = [ { value: 1, color:"#1AA24C", highlight: "#1AD24C", label: "Valg 2" }, { value: 1, color: "#000000", highlight: "#333333", label: "Valg 1" } ] var ctx = $('#statistikk1').get(0).getContext("2d"); var myDoughnut = new Chart(ctx).Doughnut(data,{ animation:true, showTooltips: true, percentageInnerCutout : 0, segmentShowStroke : true }); var res1; var res2; var x = localStorage.getItem('type'); if(x == 0){ //day var date1 = $('input[name=date]').val(); var date2 = $('input[name=date2]').val(); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 1, success: function(data) { res1 = parseInt(data); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 1, success: function(data) { res2 = parseInt(data); myDoughnut.segments[0].value = res2; myDoughnut.segments[1].value = res1; myDoughnut.update(); $("#followersFirstDate").text(res1); $("#followersLastDate").text(res2); }, }); }, }); }else if(x == 1){ //month var date1 = $('input[name=date3]').val() + '-01'; var date2 = $('input[name=date4]').val() + '-01'; $.ajax({ url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 2, success: function(data) { res1 = parseInt(data); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 2, success: function(data) { res2 = parseInt(data); myDoughnut.segments[0].value = res2; myDoughnut.segments[1].value = res1; myDoughnut.update(); $("#followersFirstDate").text(res1); $("#followersLastDate").text(res2); }, }); }, }); }else if(x == 2){ //year var date1 = $('input[name=date5]').val(); var date2 = $('input[name=date6]').val(); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 3, success: function(data) { res1 = parseInt(data); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 3, success: function(data) { res2 = parseInt(data); myDoughnut.segments[0].value = res2; myDoughnut.segments[1].value = res1; myDoughnut.update(); $("#followersFirstDate").text(res1); $("#followersLastDate").text(res2); }, }); }, }); } } function showChart2(){ var data = [ { value: 1, color:"#1AA24C", highlight: "#1AD24C", label: "Valg 2" }, { value: 1, color: "#000000", highlight: "#333333", label: "Valg 1" } ] var ctx = $('#statistikk2').get(0).getContext("2d"); var myDoughnut = new Chart(ctx).Doughnut(data,{ animation:true, showTooltips: true, percentageInnerCutout : 0, segmentShowStroke : true }); var res1; var res2; var x = localStorage.getItem('type'); if(x == 0){ //day var date1 = $('input[name=date]').val(); var date2 = $('input[name=date2]').val(); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 4, success: function(data) { res1 = parseInt(data); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 4, success: function(data) { res2 = parseInt(data); myDoughnut.segments[0].value = res2; myDoughnut.segments[1].value = res1; myDoughnut.update(); $("#donationsFirstDate").text(res1); $("#donationsLastDate").text(res2); }, }); }, }); }else if(x == 1){ //month var date1 = $('input[name=date3]').val() + '-01'; var date2 = $('input[name=date4]').val() + '-01'; $.ajax({ url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 5, success: function(data) { res1 = parseInt(data); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 5, success: function(data) { res2 = parseInt(data); myDoughnut.segments[0].value = res2; myDoughnut.segments[1].value = res1; myDoughnut.update(); $("#donationsFirstDate").text(res1); $("#donationsLastDate").text(res2); }, }); }, }); }else if(x == 2){ //year var date1 = $('input[name=date5]').val(); var date2 = $('input[name=date6]').val(); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 6, success: function(data) { res1 = parseInt(data); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 6, success: function(data) { res2 = parseInt(data); myDoughnut.segments[0].value = res2; myDoughnut.segments[1].value = res1; myDoughnut.update(); $("#donationsFirstDate").text(res1); $("#donationsLastDate").text(res2); }, }); }, }); } } function showChart3(){ var data = [ { value: 1, color:"#1AA24C", highlight: "#1AD24C", label: "Valg 2" }, { value: 1, color: "#000000", highlight: "#333333", label: "Valg 1" } ] var ctx = $('#statistikk3').get(0).getContext("2d"); var myDoughnut = new Chart(ctx).Doughnut(data,{ animation:true, showTooltips: true, percentageInnerCutout : 0, segmentShowStroke : true }); var res1; var res2; var x = localStorage.getItem('type'); if(x == 0){ //day var date1 = $('input[name=date]').val(); var date2 = $('input[name=date2]').val(); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 7, success: function(data) { res1 = parseInt(data); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 7, success: function(data) { res2 = parseInt(data); myDoughnut.segments[0].value = res2; myDoughnut.segments[1].value = res1; myDoughnut.update(); $("#moneyDonatedFirstDate").text(res1 + ",-"); $("#moneyDonatedLastDate").text(res2 + ",-"); }, }); }, }); }else if(x == 1){ //month var date1 = $('input[name=date3]').val() + '-01'; var date2 = $('input[name=date4]').val() + '-01'; $.ajax({ url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 8, success: function(data) { res1 = parseInt(data); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 8, success: function(data) { res2 = parseInt(data); myDoughnut.segments[0].value = res2; myDoughnut.segments[1].value = res1; myDoughnut.update(); $("#moneyDonatedFirstDate").text(res1 + ",-"); $("#moneyDonatedLastDate").text(res2 + ",-"); }, }); }, }); }else if(x == 2){ //year var date1 = $('input[name=date5]').val(); var date2 = $('input[name=date6]').val(); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 9, success: function(data) { res1 = parseInt(data); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 9, success: function(data) { res2 = parseInt(data); myDoughnut.segments[0].value = res2; myDoughnut.segments[1].value = res1; myDoughnut.update(); $("#moneyDonatedFirstDate").text(res1 + ",-"); $("#moneyDonatedLastDate").text(res2 + ",-"); }, }); }, }); } } function showChart4(){ var data = [ { value: 1, color:"#1AA24C", highlight: "#1AD24C", label: "Valg 2" }, { value: 1, color: "#000000", highlight: "#333333", label: "Valg 1" } ] var ctx = $('#statistikk4').get(0).getContext("2d"); var myDoughnut = new Chart(ctx).Doughnut(data,{ animation:true, showTooltips: true, percentageInnerCutout : 0, segmentShowStroke : true }); var res1; var res2; var x = localStorage.getItem('type'); if(x == 0){ //day var date1 = $('input[name=date]').val(); var date2 = $('input[name=date2]').val(); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 10, success: function(data) { res1 = parseInt(data); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 10, success: function(data) { res2 = parseInt(data); myDoughnut.segments[0].value = res2; myDoughnut.segments[1].value = res1; myDoughnut.update(); $("#averageDonationFirstDate").text(res1 + ",-"); $("#averageDonationLastDate").text(res2 + ",-"); }, }); }, }); }else if(x == 1){ //month var date1 = $('input[name=date3]').val() + '-01'; var date2 = $('input[name=date4]').val() + '-01'; $.ajax({ url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 11, success: function(data) { res1 = parseInt(data); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 11, success: function(data) { res2 = parseInt(data); myDoughnut.segments[0].value = res2; myDoughnut.segments[1].value = res1; myDoughnut.update(); $("#averageDonationFirstDate").text(res1 + ",-"); $("#averageDonationLastDate").text(res2 + ",-"); }, }); }, }); }else if(x == 2){ //year var date1 = $('input[name=date5]').val(); var date2 = $('input[name=date6]').val(); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 12, success: function(data) { res1 = parseInt(data); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 12, success: function(data) { res2 = parseInt(data); myDoughnut.segments[0].value = res2; myDoughnut.segments[1].value = res1; myDoughnut.update(); $("#averageDonationFirstDate").text(res1 + ",-"); $("#averageDonationLastDate").text(res2 + ",-"); }, }); }, }); } } function showChart5(){ var data = [ { value: 1, color:"#1AA24C", highlight: "#1AD24C", label: "Valg 2" }, { value: 1, color: "#000000", highlight: "#333333", label: "Valg 1" } ] var ctx = $('#statistikk5').get(0).getContext("2d"); var myDoughnut = new Chart(ctx).Doughnut(data,{ animation:true, showTooltips: true, percentageInnerCutout : 0, segmentShowStroke : true }); var res1; var res2; var x = localStorage.getItem('type'); if(x == 0){ //day var date1 = $('input[name=date]').val(); var date2 = $('input[name=date2]').val(); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 13, success: function(data) { res1 = parseInt(data); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 13, success: function(data) { res2 = parseInt(data); myDoughnut.segments[0].value = res2; myDoughnut.segments[1].value = res1; myDoughnut.update(); $("#newsFirstDate").text(res1); $("#newsLastDate").text(res2); }, }); }, }); }else if(x == 1){ //month var date1 = $('input[name=date3]').val() + '-01'; var date2 = $('input[name=date4]').val() + '-01'; $.ajax({ url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 14, success: function(data) { res1 = parseInt(data); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 14, success: function(data) { res2 = parseInt(data); myDoughnut.segments[0].value = res2; myDoughnut.segments[1].value = res1; myDoughnut.update(); $("#newsFirstDate").text(res1); $("#newsLastDate").text(res2); }, }); }, }); }else if(x == 2){ //year var date1 = $('input[name=date5]').val(); var date2 = $('input[name=date6]').val(); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 15, success: function(data) { res1 = parseInt(data); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 15, success: function(data) { res2 = parseInt(data); myDoughnut.segments[0].value = res2; myDoughnut.segments[1].value = res1; myDoughnut.update(); $("#newsFirstDate").text(res1); $("#newsLastDate").text(res2); }, }); }, }); } } function showChart6(){ var data = [ { value: 1, color:"#1AA24C", highlight: "#1AD24C", label: "Valg 2" }, { value: 1, color: "#000000", highlight: "#333333", label: "Valg 1" } ] var ctx = $('#statistikk6').get(0).getContext("2d"); var myDoughnut = new Chart(ctx).Doughnut(data,{ animation:true, showTooltips: true, percentageInnerCutout : 0, segmentShowStroke : true }); var res1; var res2; var x = localStorage.getItem('type'); if(x == 0){ //day var date1 = $('input[name=date]').val(); var date2 = $('input[name=date2]').val(); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 16, success: function(data) { res1 = parseInt(data); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 16, success: function(data) { res2 = parseInt(data); myDoughnut.segments[0].value = res2; myDoughnut.segments[1].value = res1; myDoughnut.update(); $("#prosjectsFirstDate").text(res1); $("#prosjectsLastDate").text(res2); }, }); }, }); }else if(x == 1){ //month var date1 = $('input[name=date3]').val() + '-01'; var date2 = $('input[name=date4]').val() + '-01'; $.ajax({ url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 17, success: function(data) { res1 = parseInt(data); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 17, success: function(data) { res2 = parseInt(data); myDoughnut.segments[0].value = res2; myDoughnut.segments[1].value = res1; myDoughnut.update(); $("#prosjectsFirstDate").text(res1); $("#prosjectsLastDate").text(res2); }, }); }, }); }else if(x == 2){ //year var date1 = $('input[name=date5]').val(); var date2 = $('input[name=date6]').val(); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 18, success: function(data) { res1 = parseInt(data); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 18, success: function(data) { res2 = parseInt(data); myDoughnut.segments[0].value = res2; myDoughnut.segments[1].value = res1; myDoughnut.update(); $("#prosjectsFirstDate").text(res1); $("#prosjectsLastDate").text(res2); }, }); }, }); } } });
Java
/* The all pages that do not require authentication */ function UnAuthenticatedHandler() { "use strict"; this.displayAboutPage = function(req, res, next) { return res.render("about"); }; this.displayContactPage = function(req, res, next) { return res.render("contact"); }; this.displayHomePage = function(req, res, next) { return res.render("home"); }; this.displayChatPage = function(req, res, next) { return res.render("chat"); }; } module.exports = UnAuthenticatedHandler;
Java
# Pleurothallis tipuloides Luer SPECIES #### Status ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
Java
/* * Copyright (C) 2016 the original author or authors. * * This file is part of jGrades Application Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 */ package org.jgrades.lic.api.model; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; @Getter @Setter @AllArgsConstructor public class LicenceValidationResult { private boolean valid; private String errorMessage; public LicenceValidationResult() { valid = true; errorMessage = null; } }
Java