Code_Function
stringlengths
13
13.9k
Message
stringlengths
10
1.46k
private fun tryQueueCurrentBuffer(elapsedWaiting: Long): Boolean { if (currentBuffer.isEmpty()) return true return if (isOpen && neverPubQueue.size() < neverPubCapacity) { neverPubQueue.add(currentBuffer) totalQueuedRecords.addAndGet(currentBuffer.sizeRecords()) totalQueuedBuffers.incrementAndGet() onQueueBufferSuccess(currentBuffer, elapsedWaiting) currentBuffer = RecordBuffer(flow) true } else if (elapsedWaiting > 0) { onQueueBufferTimeout(currentBuffer, elapsedWaiting) false } else false }
Keep private . Call only when holding lock .
private fun writeKeysWithPrefix(prefix: String, exclude: String) { for (key in keys) { if (key.startsWith(prefix) && !key.startsWith(exclude)) { ps.println(key + "=" + prop.getProperty(key)) } } ps.println() }
writes all keys starting with the specified prefix and not starting with the exclude prefix in alphabetical order .
fun ProtocolInfo( name: String, connectionForms: Collection<Form?>, sharingProfileForms: Collection<Form?> ) { name = name connectionForms = connectionForms sharingProfileForms = sharingProfileForms }
Creates a new ProtocolInfo having the given name and forms . The given collections of forms are used to describe the parameters for connections and sharing profiles respectively .
fun prepare(sql: String?): Prepared? {val p: Prepared = parse(sql)p.prepare()if (currentTokenType !== END) {throw getSyntaxError()} return p }
Parse the statement and prepare it for execution .
fun logging(msg1: String?, msg2: String?, msg3: String?) { print(msg1) print(" ") print(msg2) print(" ") println(msg3)
Prints a log message .
fun initQueryStringHandlers() { this.transport = SimpleTargetedChain() this.transport.setOption("qs.list", "org.apache.axis.transport.http.QSListHandler") this.transport.setOption("qs.method", "org.apache.axis.transport.http.QSMethodHandler") this.transport.setOption("qs.wsdl", "org.apache.axis.transport.http.QSWSDLHandler") }
Initialize a Handler for the transport defined in the Axis server config . This includes optionally filling in query string handlers .
@DSGenerator( tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 13:00:42.071 -0500", hash_original_method = "236CE70381CAE691CF8D03F3D0A7E2E8", hash_generated_method = "34048EFAD324F63AAF648818713681BB" ) fun toUpperCase(string: String): String? { var changed = false val chars = string.toCharArray() for (i in chars.indices) { val ch = chars[i] if ('a' <= ch && 'z' >= ch) { changed = true chars[i] = (ch.code - 'a'.code + 'A'.code).toChar() } } return if (changed) { String(chars) } else string }
A locale independent version of toUpperCase .
fun HTMLForm(htmlC: HTMLComponent, action: String?, method: String?, encType: String) { htmlC = htmlC action = htmlC.convertURL(action) encType = encType if (htmlC.getHTMLCallback() != null) { val linkProps: Int = htmlC.getHTMLCallback().getLinkProperties(htmlC, action) if (linkProps and HTMLCallback.LINK_FORBIDDEN !== 0) { action = null } } this.isPostMethod = method != null && method.equals("post", ignoreCase = true) }
Constructs the HTMLForm
fun CurlInterceptor(logger: jdk.nashorn.internal.runtime.logging.Loggable, limit: Long) { logger = logger limit = limit }
Interceptor responsible for printing curl logs
override fun toString(): String? { return java.lang.String.valueOf(value) }
Returns the String value of this mutable .
fun unRegisterImpulseConstraint(con: ImpulseConstraint) { collisionResponseRows -= (con as ImpulseConstraint).GetCollisionResponseRows() collisions.remove(con) }
Un-registers an impulse constraint with the constraint engine
fun Index(node: Node<K?, V?>, down: Index<K?, V?>, right: Index<K?, V?>) { node = node down = down right = right }
Creates index node with given values .
fun isInBoundsX(x: Float): Boolean { return if (isInBoundsLeft(x) && isInBoundsRight(x)) true else false }
BELOW METHODS FOR BOUNDS CHECK
fun caseAnonymous_constraint_1_(`object`: Anonymous_constraint_1_?): T? { return null }
Returns the result of interpreting the object as an instance of ' < em > Anonymous constraint 1 < /em > ' . < ! -- begin-user-doc -- > This implementation returns null ; returning a non-null result will terminate the switch . < ! -- end-user-doc -- >
fun CProjectLoaderReporter(listeners: ListenerProvider<IProjectListener?>) { m_listeners = listeners }
Creates a new reporter object .
@Throws(InvalidArgument::class,NotFound::class,InvalidSession::class,StorageFault::class,NotImplemented::class) fun queryUniqueIdentifiersForLuns(arrayUniqueId: String): Array<String?>? { val methodName = "queryUniqueIdentifiersForLuns(): " log.info(methodName + "Entry with arrayUniqueId[" + arrayUniqueId + "]") sslUtil.checkHttpRequest(true, true) val sosManager: SOSManager = contextManager.getSOSManager() val ids: Array<String?> = sosManager.queryUniqueIdentifiersForLuns(arrayUniqueId) log.info(methodName + "Exit returning ids of size[" + ids.size + "]") return ids }
Returns unique identifiers for LUNs for the give array Id
fun onCreateOptionsMenu(menu: Menu): Boolean { mOpsOptionsMenu = menu val inflater: MenuInflater = getMenuInflater() inflater.inflate(R.menu.ops_options_menu, menu) return true }
Inflates the Operations ( `` Ops '' ) Option Menu .
protected fun PackageImpl() { super() }
< ! -- begin-user-doc -- > < ! -- end-user-doc -- >
fun fillAttributeSet(attrSet: MutableSet<*>) { attrSet.add("lang") }
Fills the given set with the attribute names found in this selector .
fun addColumn(columnFamily: String?, columnQualifier: String?) { var columns: MutableSet<String?> = this.columnFamilies.get(columnFamily) if (columns == null) { columns = HashSet() } columns.add(columnQualifier) this.columnFamilies.put(columnFamily, columns) }
Add column family and column qualifier to be extracted from tuple
fun ofString(name: String?, description: String?): Field<String?>? { return Field(name, String::class.java, description) }
Break down metrics by string . < p > Each unique string will allocate a new submetric . < b > Do not use user content as a field value < /b > as field values are never reclaimed .
fun OMPoint(lat: Double, lon: Double, radius: Int) { setRenderType(RENDERTYPE_LATLON) set(lat, lon) radius = radius }
Create an OMPoint at a lat/lon position , with the specified radius .
@Throws(GamaRuntimeException::class) private fun saveMicroAgents(scope: IScope, agent: IMacroAgent) { innerPopulations = THashMap<String, List<SavedAgent>>() for (microPop in agent.getMicroPopulations()) { val savedAgents: MutableList<SavedAgent> = ArrayList<SavedAgent>() val it: Iterator<IAgent?> = microPop.iterator() while (it.hasNext()) { savedAgents.add(SavedAgent(scope, it.next())) } innerPopulations.put(microPop.getSpecies().getName(), savedAgents) } }
Recursively save micro-agents of an agent .
fun GenerationResult( parent: jdk.nashorn.tools.Shell?, style: Int,location: IPath,target: IResource) {super(parent, style) location = location this.targetResource = target setText("EvoSuite Result") }
Create the dialog .
fun run() { ActivationLibrary.deactivate(this, getID()) }
Thread to deactivate object . First attempts to make object inactive ( via the inactive method ) . If that fails ( the object may still have pending/executing calls ) , then unexport the object forcibly .
private fun createImageLink( AD_Language: String, name: String, js_command: String, enabled: Boolean, pressed: Boolean ): a? { var js_command: String? = js_command val img = a("#", jdk.tools.jlink.internal.JlinkTask.createImage(AD_Language, name)) if (!pressed || !enabled) img.setID("imgButtonLink") else img.setID("imgButtonPressedLink") if (js_command == null) js_command = "'Submit'" if (js_command.length > 0 && enabled) { if (js_command.startsWith("startPopup")) img.setOnClick(js_command) else img.setOnClick( "SubmitForm('$name', $js_command,'toolbar');return false;" ) } img.setClass("ToolbarButton") img.setOnMouseOver("window.status='$name';return true;") img.setOnMouseOut("window.status='';return true;") img.setOnBlur("this.hideFocus=false") return img }
Create Image with name , id of button_name and set P_Command onClick
fun CassandraStatus(mode: CassandraMode,joined: Boolean,rpcRunning: Boolean,nativeTransportRunning: Boolean,gossipInitialized: Boolean,gossipRunning: Boolean,hostId: String,endpoint: String,tokenCount: Int,dataCenter: String,rack: String,version: String) {mode = mode joined = joined rpcRunning = rpcRunning nativeTransportRunning = nativeTransportRunning gossipInitialized = gossipInitialized gossipRunning = gossipRunning hostId = hostId endpoint = endpoint tokenCount = tokenCount dataCenter = dataCenter rack = rack version = version }
Constructs a CassandraStatus .
@Throws(GenericEntityException::class) fun checkDataSource( modelEntities: Map<String?, ModelEntity?>?, messages: List<String >?, addMissing: Boolean ) { genericDAO.checkDb(modelEntities, messages, addMissing) }
Check the datasource to make sure the entity definitions are correct , optionally adding missing entities or fields on the server
fun string2HashMap(paramString: String): HashMap<String, String>? { val params: HashMap<String, String> = HashMap() for (keyValue in paramString.split(" *& *".toRegex()).dropLastWhile { it.isEmpty() } .toTypedArray()) { val pairs = keyValue.split(" *= *".toRegex(), limit = 2).toTypedArray() params[pairs[0]] = if (pairs.size == 1) "" else pairs[1] } return params }
Convert key=value type String to HashMap < String , String >
@LargeTest @Throws(Exception::class) fun testMediaVideoItemRenderingModes() { val videoItemFileName: String = INPUT_FILE_PATH + "H263_profile0_176x144_15fps_256kbps_AACLC_32kHz_128kbps_s_0_26.3gp" val videoItemRenderingMode: Int = MediaItem.RENDERING_MODE_BLACK_BORDER var flagForException = false val mediaVideoItem1: MediaVideoItem = mVideoEditorHelper.createMediaItem( mVideoEditor, "mediaVideoItem1", videoItemFileName, videoItemRenderingMode ) mVideoEditor.addMediaItem(mediaVideoItem1) mediaVideoItem1.setRenderingMode(MediaItem.RENDERING_MODE_CROPPING) assertEquals( "MediaVideo Item rendering Mode", MediaItem.RENDERING_MODE_CROPPING, mediaVideoItem1.getRenderingMode() ) try { mediaVideoItem1.setRenderingMode(MediaItem.RENDERING_MODE_CROPPING + 911) } catch (e: IllegalArgumentException) { flagForException = true } assertTrue("Media Item Invalid rendering Mode", flagForException) flagForException = false try { mediaVideoItem1.setRenderingMode(MediaItem.RENDERING_MODE_BLACK_BORDER - 11) } catch (e: IllegalArgumentException) { flagForException = true } assertTrue("Media Item Invalid rendering Mode", flagForException) assertEquals( "MediaVideo Item rendering Mode", MediaItem.RENDERING_MODE_CROPPING, mediaVideoItem1.getRenderingMode() ) mediaVideoItem1.setRenderingMode(MediaItem.RENDERING_MODE_STRETCH) assertEquals( "MediaVideo Item rendering Mode", MediaItem.RENDERING_MODE_STRETCH, mediaVideoItem1.getRenderingMode() ) }
To test creation of Media Video Item with Set and Get rendering Mode
fun visitTree(tree: com.sun.tools.javac.tree.JCTree?) {}
Default member enter visitor method : do nothing
private fun createControls(): EventLogControlPanel? { val c = EventLogControlPanel() c.addHeading("connections") conUpCheck = c.addControl("up") conDownCheck = c.addControl("down") c.addHeading("messages") msgCreateCheck = c.addControl("created") msgTransferStartCheck = c.addControl("started relay") msgRelayCheck = c.addControl("relayed") msgDeliveredCheck = c.addControl("delivered") msgRemoveCheck = c.addControl("removed") msgDropCheck = c.addControl("dropped") msgAbortCheck = c.addControl("aborted") return c }
Creates a control panel for the log
fun type(): String? { return type }
Returns the type of document to get the term vector for .
fun `test_getIterator$Ljava_text_AttributedCharacterIterator$AttributeII`() { val test = "Test string" try { val hm: MutableMap<AttributedCharacterIterator.Attribute?, String> = HashMap<AttributedCharacterIterator.Attribute?, String>() val aci: Array<AttributedCharacterIterator.Attribute?> = arrayOfNulls<AttributedCharacterIterator.Attribute>(3) aci[0] = TestAttributedCharacterIteratorAttribute("att1") aci[1] = TestAttributedCharacterIteratorAttribute("att2") aci[2] = TestAttributedCharacterIteratorAttribute("att3") hm[aci[0]] = "value1" hm[aci[1]] = "value2" val attrString = AttributedString(test) attrString.addAttributes(hm, 2, 4) val it: AttributedCharacterIterator = attrString.getIterator(aci, 1, 5) assertTrue("Incorrect iteration on AttributedString", it.getAttribute(aci[0]) == null) assertTrue("Incorrect iteration on AttributedString", it.getAttribute(aci[1]) == null) assertTrue("Incorrect iteration on AttributedString", it.getAttribute(aci[2]) == null) it.next() assertTrue( "Incorrect iteration on AttributedString", it.getAttribute(aci[0]).equals("value1") ) assertTrue( "Incorrect iteration on AttributedString", it.getAttribute(aci[1]).equals("value2") ) assertTrue("Incorrect iteration on AttributedString", it.getAttribute(aci[2]) == null) try { attrString.getIterator(aci, -1, 5) fail("IllegalArgumentException is not thrown.") } catch (iae: IllegalArgumentException) { } }try { attrString.getIterator(aci, 6, 5) fail("IllegalArgumentException is not thrown.") } catch (iae: IllegalArgumentException) { } try { attrString.getIterator(aci, 3, 2) fail("IllegalArgumentException is not thrown.") } catch (iae: IllegalArgumentException) { } } catch (e: Exception) { fail("Unexpected exceptiption $e") } }
java.text.AttributedString # getIterator ( AttributedCharacterIterator.Attribute [ ] , int , int ) Test of method java.text.AttributedString # getIterator ( AttributedCharacterIterator.Attribute [ ] , int , int ) .
private fun newplan(plan: TransformationPlan) { if (plan.replaces(plan)) { plan = plan } }
Install a new plan iff it 's more drastic than the existing plan
private fun buildSmallContingencyTables(): SmallContingencyTables? { val allLabelSet: MutableSet<String> = TreeSet() for (outcome in id2Outcome.getOutcomes()) { allLabelSet.addAll(outcome.getLabels()) } val labelList: List<String> = ArrayList(allLabelSet) val numberOfLabels = labelList.size val counterIncreaseValue = 1.0 val smallContingencyTables = SmallContingencyTables(labelList) for (allLabelsClassId in 0 until numberOfLabels) { for (outcome in id2Outcome.getOutcomes()) { val localClassId: Int = outcome.getReverseLabelMapping(labelList).get(allLabelsClassId) val threshold: Double = outcome.getBipartitionThreshold() var goldValue: Double var predictionValue: Double if (localClassId == -1) { goldValue = 0.0 predictionValue = 0.0 } else { goldValue = outcome.getGoldstandard().get(localClassId) predictionValue = outcome.getPrediction().get(localClassId) } if (goldValue >= threshold) { if (predictionValue >= threshold) { smallContingencyTables.addTruePositives( allLabelsClassId, counterIncreaseValue ) } else { smallContingencyTables.addFalseNegatives( allLabelsClassId, counterIncreaseValue ) } } else { if (predictionValue >= threshold) { smallContingencyTables.addFalsePositives( allLabelsClassId, counterIncreaseValue ) } else { smallContingencyTables.addTrueNegatives( allLabelsClassId, counterIncreaseValue ) } } } } return smallContingencyTables }
build small contingency tables ( a small contingency table for each label ) from id2Outcome
fun commandTopic(command: String?): String? { var command = command if (command == null) { command = "+" } return cmdTopic.replace("{COMMAND}", command) }
Get the MQTT topic for a command .
fun hasExtension(extension: String?): Boolean { return if (TextUtils.isEmpty(extension)) { false } else extensionToMimeTypeMap.containsKey(extension) }
Returns true if the given extension has a registered MIME type .
@Before fun onBefore() { tut = TransportUnitType("TUT") loc1 = Location(LocationPK("AREA", "ASL", "X", "Y", "Z")) loc2 = Location(LocationPK("ARE2", "ASL2", "X2", "Y2", "Z2")) product = Product("tttt") entityManager.persist(product) entityManager.persist(tut) entityManager.persist(loc1) entityManager.persist(loc2) tu = TransportUnit("TEST") tu.setTransportUnitType(tut) tu.setActualLocation(loc1) entityManager.persist(tu) entityManager.flush() }
Setup some test data .
fun beforeRerunningIndexCreationQuery() {}
Asif : Called just before IndexManager executes the function rerunIndexCreationQuery . After this function gets invoked , IndexManager will iterate over all the indexes of the region making the data maps null & re running the index creation query on the region . The method of Index Manager gets executed from the clear function of the Region
fun buffered(): Float { return if (totalSize > 0) Futures.getUnchecked(response).cache.cacheSize() / totalSize as Float else -1 }
Returns the percentage that is buffered , or -1 , if unknown
fun accept(dir: File?, name: String?): Boolean { return accept(File(dir, name)) }
Returns true if the file in the given directory with the given name should be accepted .
@Throws(Exception::class) @JvmStatic fun main(a: Array<String>) { TestBase.createCaller().init().test() }
Run just this test .
fun isFieldPresent(field: String?): Boolean { return fields.containsKey(field) }
Checks if the given field is present in this extension because not every field is mandatory ( according to scim 2.0 spec ) .
fun mapToStr(map: Map<out Any?, Any?>?): String? { if (map == null) return null val buf = StringBuilder() var first = true for (entry in map.entrySet()) { val key: Any = entry.getKey() val value: Any = entry.getValue() if (key !is String || value !is String) continue var encodedName: String? = null try { encodedName = URLEncoder.encode(key, "UTF-8") } catch (e: UnsupportedEncodingException) { Debug.logError(e, module) } var encodedValue: String? = null try { encodedValue = URLEncoder.encode(value, "UTF-8") } catch (e: UnsupportedEncodingException) { Debug.logError(e, module) } if (first) first = false else buf.append("|") buf.append(encodedName) buf.append("=") buf.append(encodedValue) } return buf.toString() }
Creates an encoded String from a Map of name/value pairs ( MUST BE STRINGS ! )
@DSGenerator( tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2013-12-30 13:00:42.074 -0500", hash_original_method = "002C3CFFC816A38E005543BB54E228FD", hash_generated_method = "24D6A751F50FC61EC42FBA4D0FC608F4" ) fun toLowerCase(string: String): String? { var changed = false val chars = string.toCharArray() for (i in chars.indices) { val ch = chars[i] if ('A' <= ch && 'Z' >= ch) { changed = true chars[i] = (ch.code - 'A'.code + 'a'.code).toChar() } } return if (changed) { String(chars) } else string }
A locale independent version of toLowerCase .
fun numberToWords(num: Int): String? { var num = num if (num == 0) { return LESS_THAN_TWENTY.get(0) } var i = 0 val res = StringBuilder() while (num > 0) { if (num % 1000 != 0) { res.insert(0, " ") res.insert(0, THOUSANDS.get(i)) res.insert(0, helper(num % 1000)) } num /= 1000 i++ } return res.toString().trim { it <= ' ' } }
Math , String . Try to find the pattern first . The numbers less than 1000 , e.g . xyz , can be x Hundred y '' ty '' z . The numbers larger than 1000 , we need to add thousand or million or billion . Given a number num , we pronounce the least significant digits first . Then concat the result to the end to next three least significant digits . So the recurrence relation is : Next result of num = the pronunciation of least three digits + current result of num After that , remove those three digits from number . Stop when number is 0 .
fun hasLat(): Boolean { return super.hasAttribute(LAT) }
Returns whether it has the Latitude .
fun test_ConstructorIF() { val hs2 = HashSet<Any>(5, 0.5.toFloat()) assertEquals("Created incorrect HashSet", 0, hs2.size()) try { HashSet(0, 0) } catch (e: IllegalArgumentException) { return } fail("Failed to throw IllegalArgumentException for initial load factor <= 0") }
java.util.HashSet # HashSet ( int , float )
private fun emitCharMapArray(): Int { val cl: CharClasses = parser.getCharClasses() if (cl.getMaxCharCode() < 256) { emitCharMapArrayUnPacked() return 0 } intervals = cl.getIntervals() println("") println(" /** ") println(" * Translates characters to character classes") println(" */") println(" private static final String ZZ_CMAP_PACKED = ") var n = 0 print(" \"") var i = 0 var numPairs = 0 var count: Int var value: Int while (i < intervals.length) { count = intervals.get(i).end - intervals.get(i).start + 1 value = colMap.get(intervals.get(i).charClass) while (count > 0xFFFF) { printUC(0xFFFF) printUC(value) count -= 0xFFFF numPairs++ n++ } numPairs++ printUC(count) printUC(value) if (i < intervals.length - 1) { if (++n >= 10) { println("\"+") print(" \"") n = 0 } } i++ } println("\";") println() println(" /** ") println(" * Translates characters to character classes") println(" */") println(" private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED);") println() return numPairs }
Returns the number of elements in the packed char map array , or zero if the char map array will be not be packed . This will be more than intervals.length if the count for any of the values is more than 0xFFFF , since the number of char map array entries per value is ceil ( count / 0xFFFF )
fun size(): Int { return mSize }
Returns the number of key-value mappings that this SparseDoubleArray currently stores .
fun depends(parent: Int, child: Int) { dag.addNode(child) dag.addNode(parent) dag.addEdge(parent, child) }
Adds a dependency relation ship between two variables that will be in the network . The integer value corresponds the the index of the i'th categorical variable , where the class target 's value is the number of categorical variables .
fun DiscreteTransfer(tableValues: IntArray) { tableValues = tableValues this.n = tableValues.size }
The input is an int array which will be used later to construct the lut data
fun roundTo(`val`: Float, prec: Float): Float { return floor(`val` / prec + 0.5f) * prec }
Rounds a single precision value to the given precision .
fun <K, V> readKeyValues( topic: String?, consumerConfig: Properties?, maxMessages: Int ): List<KeyValue<K, V>>? { val consumer: KafkaConsumer<K, V> = KafkaConsumer(consumerConfig) consumer.subscribe(Collections.singletonList(topic)) val pollIntervalMs = 100 val maxTotalPollTimeMs = 2000 var totalPollTimeMs = 0 val consumedValues: MutableList<KeyValue<K, V>> = ArrayList() while (totalPollTimeMs < maxTotalPollTimeMs && continueConsuming( consumedValues.size, maxMessages ) ) { totalPollTimeMs += pollIntervalMs val records: ConsumerRecords<K, V> = consumer.poll(pollIntervalMs) for (record in records) { consumedValues.add(KeyValue(record.key(), record.value())) } } consumer.close() return consumedValues }
Returns up to ` maxMessages ` by reading via the provided consumer ( the topic ( s ) to read from are already configured in the consumer ) .
private fun segment(key: Any): Int { return Math.abs(key.hashCode() % size) }
This method performs the translation of the key hash code to the segment index within the list . Translation is done by acquiring the modulus of the hash and the list size .
private fun handleStateLeaving(endpoint: InetAddress) { val tokens: Collection<Token> = getTokensFor(endpoint) if (logger.isDebugEnabled()) logger.debug( "Node {} state leaving, tokens {}", endpoint, tokens ) if (!tokenMetadata.isMember(endpoint)) { logger.info("Node {} state jump to leaving", endpoint) tokenMetadata.updateNormalTokens(tokens, endpoint) } else if (!tokenMetadata.getTokens(endpoint).containsAll(tokens)) { logger.warn("Node {} 'leaving' token mismatch. Long network partition?", endpoint) tokenMetadata.updateNormalTokens(tokens, endpoint) } tokenMetadata.addLeavingEndpoint(endpoint) PendingRangeCalculatorService.instance.update() }
Handle node preparing to leave the ring
fun MAttributeInstance( ctx: Properties?, M_Attribute_ID: Int, M_AttributeSetInstance_ID: Int, BDValue: BigDecimal?, trxName: String? ) { super(ctx, 0, trxName) setM_Attribute_ID(M_Attribute_ID) setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID) setValueNumber(BDValue) }
Number Value Constructior
fun supportsPositionedUpdate(): Boolean { debugCodeCall("supportsPositionedUpdate") return true }
Returns whether positioned updates are supported .
private fun prepareMapping(index: String, defaultMappings: Map<String, Any>): Boolean { var success = true for (stringObjectEntry in defaultMappings.entrySet()) { val mapping = stringObjectEntry.getValue() as Map<String, Any> ?: throw RuntimeException("type mapping not defined") val putMappingRequestBuilder: PutMappingRequestBuilder = client.admin().indices().preparePutMapping().setIndices(index) putMappingRequestBuilder.setType(stringObjectEntry.getKey()) putMappingRequestBuilder.setSource(mapping) if (log.isLoggable(Level.FINE)) { log.fine("Elasticsearch create mapping for index '" + index + " and type '" + stringObjectEntry.getKey() + "': " + mapping) } val resp: PutMappingResponse = putMappingRequestBuilder.execute().actionGet() if (resp.isAcknowledged()) { if (log.isLoggable(Level.FINE)) { log.fine("Elasticsearch mapping for index '" + index + " and type '" + stringObjectEntry.getKey() + "' was acknowledged") } } else { success = false log.warning("Elasticsearch mapping creation was not acknowledged for index '" + index + " and type '" + stringObjectEntry.getKey() + "'") } } return success }
This method applies the supplied mapping to the index .
fun disableOcr() { if (!ocrDisabled) { excludeParser(TesseractOCRParser::class.java) ocrDisabled = true pdfConfig.setExtractInlineImages(false) } }
Disable OCR . This method only has an effect if Tesseract is installed .
fun eInverseRemove( otherEnd: InternalEObject?, featureID: Int, msgs: NotificationChain? ): NotificationChain? { when (featureID) { DatatypePackage.DICTIONARY_PROPERTY_TYPE__KEY_TYPE -> return basicSetKeyType(null, msgs) DatatypePackage.DICTIONARY_PROPERTY_TYPE__VALUE_TYPE -> return basicSetValueType( null, msgs ) } return super.eInverseRemove(otherEnd, featureID, msgs) }
< ! -- begin-user-doc -- > < ! -- end-user-doc -- >
@JvmStatic fun main(args: Array<String>) { Am().run(args)
Command-line entry point .
fun removeAllHighlights() { }
Removes all highlights .
fun init() { val p: Properties? p = try { System.getProperties() } catch (ace: AccessControlException) { Properties() } init(p) }
Initialize debugging from the system properties .
fun bySecond(vararg seconds: Int?): Builder? { return bySecond(Arrays.asList(seconds)) }
Adds one or more BYSECOND rule parts .
fun CakePHP3CustomizerPanel() { initComponents() init() }
Creates new form CakePHP3CustomizerPanel
private fun updateProgress(progressLabel: String, progress: Int) { if (myHost != null && (progress != previousProgress || progressLabel) != previousProgressLabel) { myHost.updateProgress(progressLabel, progress) } previousProgress = progress previousProgressLabel = progressLabel }
Used to communicate a progress update between a plugin tool and the main Whitebox user interface .
fun first(): Char { pos = 0 return current() }
Sets the position to getBeginIndex ( ) and returns the character at that position .
@Benchmark @Throws(IOException::class) fun test4_UsingKeySetAndForEach(): Long { var i: Long = 0 for (key in map.keySet()) { i += key + map.get(key) } return i }
4 . Using keySet and foreach
fun eUnset(featureID: Int) { when (featureID) { N4JSPackage.N4_FIELD_DECLARATION__DECLARED_TYPE_REF -> { setDeclaredTypeRef(null as TypeRef?) return } N4JSPackage.N4_FIELD_DECLARATION__BOGUS_TYPE_REF -> { setBogusTypeRef(null as TypeRef?) return } N4JSPackage.N4_FIELD_DECLARATION__DECLARED_NAME -> { setDeclaredName(null as LiteralOrComputedPropertyName?) return } N4JSPackage.N4_FIELD_DECLARATION__DEFINED_FIELD -> { setDefinedField(null as TField?) return } N4JSPackage.N4_FIELD_DECLARATION__EXPRESSION -> { setExpression(null as Expression?) return } } super.eUnset(featureID) }
< ! -- begin-user-doc -- > < ! -- end-user-doc -- >
private fun StringTextStore(text: String?) { super() fText = text ?: "" fCopyLimit = if (fText.length() > SMALL_TEXT_LIMIT) fText.length() / 2 else 0 }
Create a text store with initial content .
fun incompleteGammaP(a: Double, x: Double): Double { return incompleteGamma(x, a, lnGamma(a)) }
Incomplete Gamma function P ( a , x ) = 1-Q ( a , x ) ( a cleanroom implementation of Numerical Recipes gammp ( a , x ) ; in Mathematica this function is 1-GammaRegularized )
@Scheduled(fixedDelay = 60000) fun controlHerdJmsMessageListener() { try { val jmsMessageListenerEnabled: Boolean = java.lang.Boolean.valueOf(configurationHelper.getProperty(ConfigurationValue.JMS_LISTENER_ENABLED)) val registry: JmsListenerEndpointRegistry = ApplicationContextHolder.getApplicationContext().getBean( "org.springframework.jms.config.internalJmsListenerEndpointRegistry", JmsListenerEndpointRegistry::class.java ) val jmsMessageListenerContainer: MessageListenerContainer = registry.getListenerContainer(HerdJmsDestinationResolver.SQS_DESTINATION_HERD_INCOMING) LOGGER.debug( "controlHerdJmsMessageListener(): {}={} jmsMessageListenerContainer.isRunning()={}", ConfigurationValue.JMS_LISTENER_ENABLED.getKey(), jmsMessageListenerEnabled, jmsMessageListenerContainer.isRunning() ) if (!jmsMessageListenerEnabled && jmsMessageListenerContainer.isRunning()) { LOGGER.info("controlHerdJmsMessageListener(): Stopping the herd JMS message listener ...") jmsMessageListenerContainer.stop() LOGGER.info("controlHerdJmsMessageListener(): Done") } else if (jmsMessageListenerEnabled && !jmsMessageListenerContainer.isRunning()) { LOGGER.info("controlHerdJmsMessageListener(): Starting the herd JMS message listener ...") jmsMessageListenerContainer.start() LOGGER.info("controlHerdJmsMessageListener(): Done") } } catch (e: Exception) { LOGGER.error( "controlHerdJmsMessageListener(): Failed to control the herd Jms message listener service.", e ) } }
Periodically check the configuration and apply the action to the herd JMS message listener service , if needed .
@DSGenerator( tool_name = "Doppelganger", tool_version = "2.0", generated_on = "2014-08-13 13:14:13.408 -0400", hash_original_method = "FC36FCA077BB9356BFDFCA10D99D0311", hash_generated_method = "2430FCC224E47ADC0C94FB89530AAC4A" ) fun AnnotationTypeMismatchException(element: Method, foundType: String) { super("The annotation element $element doesn't match the type $foundType") element = element foundType = foundType }
Constructs an instance for the given type element and the type found .
@Throws(java.awt.dnd.InvalidDnDOperationException::class) fun startDrag( trigger: java.awt.dnd.DragGestureEvent?, dragCursor: Cursor?, transferable: java.awt.datatransfer.Transferable?, dsl: java.awt.dnd.DragSourceListener? ) { startDrag(trigger, dragCursor, null, null, transferable, dsl, null) }
Start a drag , given the < code > DragGestureEvent < /code > that initiated the drag , the initial < code > Cursor < /code > to use , the < code > Transferable < /code > subject data of the drag , and the < code > DragSourceListener < /code > . < P >
fun dynamicStartCache(){ }
Dynamically starts cache .
private fun createFieldMenu(): HtmlSelectOneMenu? { val field = HtmlSelectOneMenu() val children: MutableList<*> = field.getChildren() children.add(createSelectItem("Subject")) children.add(createSelectItem("Sender")) children.add(createSelectItem("Date")) children.add(createSelectItem("Priority")) children.add(createSelectItem("Status")) children.add(createSelectItem("To")) children.add(createSelectItem("Cc")) children.add(createSelectItem("To or Cc")) return field }
Creates the menu that allows the user to select a field .
public void close ( ) { synchronized ( mDiskCacheLock ) { if ( mDiskLruCache != null ) { try { if ( ! mDiskLruCache . isClosed ( ) ) { mDiskLruCache . close ( ) ; } } catch ( Throwable e ) { LogUtils . e ( e . getMessage ( ) , e ) ; } mDiskLruCache = null ; } } }
Closes the disk cache associated with this ImageCache object . Note that this includes disk access so this should not be executed on the main/UI thread .
fun close() { synchronized(mDiskCacheLock) { if (mDiskLruCache != null) { try { if (!mDiskLruCache.isClosed()) { mDiskLruCache.close() } } catch (e: Throwable) { LogUtils.e(e.message, e) } mDiskLruCache = null } } }
Common initialization code for new list entries .
public _ScheduleDays ( ) { super ( ) ; }
Constructs a _ScheduleDays with no flags initially set .
public int allocLow ( int size , int addrAlignment ) { for ( MemoryChunk memoryChunk = low ; memoryChunk != null ; memoryChunk = memoryChunk . next ) { if ( memoryChunk . isAvailable ( size , addrAlignment ) ) { return allocLow ( memoryChunk , size , addrAlignment ) ; } } return 0 ; }
Allocate a memory at the lowest address .
public double heapInit ( ) { return memory . getHeapMemoryUsage ( ) . getInit ( ) ; }
Returns the heap initial memory of the current JVM .
public final long size ( ) { int sum = 0 ; for ( int i = 0 ; i < this . sets . length ; i ++ ) { sum += this . sets [ i ] . size ( ) ; } return sum ; }
Returns the number of fingerprints in this set . Warning : The size is only accurate in single-threaded mode .
private static Location initLocation ( GlowSession session , PlayerReader reader ) { if ( reader . hasPlayedBefore ( ) ) { Location loc = reader . getLocation ( ) ; if ( loc != null ) { return loc ; } } return session . getServer ( ) . getWorlds ( ) . get ( 0 ) . getSpawnLocation ( ) ; }
Read the location from a PlayerReader for entity initialization . Will fall back to a reasonable default rather than returning null .
public fun performMessageAction(messageAction: MessageAction) { removeOverlay() when (messageAction) { is Resend -> resendMessage(messageAction.message)is ThreadReply -> { messageActions = messageActions + Reply(messageAction.message) loadThread(messageAction.message) } is Delete, is Flag -> {messageActions = messageActions + messageAction } is Copy -> copyMessage(messageAction.message)is MuteUser -> updateUserMute(messageAction.message.user)is React -> reactToMessage(messageAction.reaction, messageAction.message) is Pin -> updateMessagePin(messageAction.message)else -> {// no op, custom user action}}}
Triggered when the user selects a new message action, in the message overlay.
public fun dismissAllMessageActions() {this.messageActions = emptySet()}
Dismisses all message actions, when we cancel them in the rest of the UI.
public fun dismissMessageAction(messageAction: MessageAction) {this.messageActions = messageActions - messageAction}
Used to dismiss a specific message action, such as delete, reply, edit or something similar.
@Preview @Composable fun RotatingSquareComponentPreview() { RotatingSquareComponent() }
Android Studio lets you preview your composable functions within the IDE itself, instead of needing to download the app to an Android device or emulator. This is a fantastic feature as you can preview all your custom components(read composable functions) from the comforts of the IDE. The main restriction is, the composable function must not take any parameters. If your composable function requires a parameter, you can simply wrap your component inside another composable function that doesn't take any parameters and call your composable function with the appropriate params. Also, don't forget to annotate it with @Preview & @Composable annotations.
@Composable fun MyApp() { val backgroundColor by animateColorAsState(MaterialTheme.colors.background) Surface(color = backgroundColor) { NewtonsTimerScreen() } }
Start building your app here!
override suspend fun handleEvent(event: RootEvent) = when (event) { RootEvent.AppOpen -> handleAppOpen() }
region Event Handling
@Composable public fun BackButton( painter: Painter, onBackPressed: () -> Unit, modifier: Modifier = Modifier, ) { IconButton( modifier = modifier, onClick = onBackPressed ) { Icon( painter = painter, contentDescription = null, tint = ChatTheme.colors.textHighEmphasis, ) } }
Basic back button, that shows an icon and calls [onBackPressed] when tapped. @param painter The icon or image to show. @param onBackPressed Handler for the back action. @param modifier Modifier for styling.
@Composable public fun CancelIcon( modifier: Modifier = Modifier, onClick: () -> Unit, ) { Icon( modifier = modifier .background(shape = CircleShape, color = ChatTheme.colors.overlayDark). clickable( indication = null, interactionSource = remember { MutableInteractionSource() }, onClick = onClick ), painter = painterResource(id = R.drawable.stream_compose_ic_close), contentDescription = stringResource(id = R.string.stream_compose_cancel), tint = ChatTheme.colors.appBackground ) }
Represents a simple cancel icon that is used primarily for attachments. @param modifier Modifier for styling. @param onClick Handler when the user clicks on the icon.
@Composable public fun EmptyContent( text: String, painter: Painter, modifier: Modifier = Modifier, ) { Column( modifier = modifier.background(color = ChatTheme.colors.appBackground), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Icon( painter = painter, contentDescription = null, tint = ChatTheme.colors.disabled, modifier = Modifier.size(96.dp), ) Spacer(Modifier.size(16.dp)) Text( text = text,style = ChatTheme.typography.title3, color = ChatTheme.colors.textLowEmphasis, textAlign = TextAlign.Center ) } }
The view that's shown when there's no data available. Consists of an icon and a caption below it. @param text The text to be displayed. @param painter The painter for the icon. @param modifier Modifier for styling.
@Composable public fun LoadingFooter(modifier: Modifier = Modifier) { Box( modifier = modifier .background(color = ChatTheme.colors.appBackground) .padding(top = 8.dp, bottom = 48.dp) ) { LoadingIndicator( modifier = Modifier.size(16.dp).align(Alignment.Center)) } }
Shows the loading footer UI in lists. @param modifier Modifier for styling.
@Composable public fun LoadingIndicator(modifier: Modifier = Modifier) { Box( modifier, contentAlignment = Alignment.Center, ) { CircularProgressIndicator(strokeWidth = 2.dp, color = ChatTheme.colors.primaryAccent) } }
Shows the default loading UI. @param modifier Modifier for styling.
@Composable public fun NetworkLoadingIndicator( modifier: Modifier = Modifier, spinnerSize: Dp = 18.dp, textStyle: TextStyle = ChatTheme.typography.title3Bold, textColor: Color = ChatTheme.colors.textHighEmphasis, ) { Row( modifier, verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center ) { CircularProgressIndicator( modifier = Modifier .padding(horizontal = 8.dp) .size(spinnerSize), strokeWidth = 2.dp, color = ChatTheme.colors.primaryAccent, ) Text( text = stringResource(id = R.string.stream_compose_waiting_for_network), style = textStyle, color = textColor, ) } }
Represents the default network loading view for the header, in case the network is down. @param modifier Styling for the [Row]. @param spinnerSize The size of the spinner. @param textStyle The text style of the inner text. @param textColor The text color of the inner text.
@Composable public fun OnlineIndicator(modifier: Modifier = Modifier) { Box( modifier = modifier .size(12.dp).background(ChatTheme.colors.appBackground, CircleShape).padding(2.dp).background(ChatTheme.colors.infoAccent, CircleShape) ) }
Component that represents an online indicator to be used with [io.getstream.chat.android.compose.ui.components.avatar.UserAvatar]. @param modifier Modifier for styling.
@Composable internal fun DefaultSearchLabel() { Text( text = stringResource(id = R.string.stream_compose_search_input_hint),style = ChatTheme.typography.body,color = ChatTheme.colors.textLowEmphasis, ) }
Default search input field label.
@Composable internal fun RowScope.DefaultSearchLeadingIcon() { Icon( modifier = Modifier.weight(1f), painter = painterResource(id =R.drawable.stream_compose_ic_search), contentDescription = null, tint = ChatTheme.colors.textLowEmphasis, ) }
Default search input field leading "search" icon.