Using regex in Android logicat - android

I have a need at the app level to capture specific (2) logs. In the case below, the first regular expression is the only one that gets captured. I've confirmed by reversing the order of the regex's.
val regex = "*Filesize is larger than usual:*|*Data is synchronizing,*"
val command = "logcat -d --regex='$regex'"
val process = Runtime.getRuntime().exec(command)
I've been made aware that using the | operator isn't possible in this case (or is it?). Is there any other feasible/optimal path?
Full code
val regex = "*Filesize is larger than usual:*|*Data is synchronizing,*"
val command = "logcat -d --regex='$regex'"
val process = Runtime.getRuntime().exec(command)
val process = Runtime.getRuntime().exec(command)
process.inputStream.bufferedReader().useLines { lines ->
lines.forEach { output ->
}
}

Related

password validation no Character sequence ( kotlin android studio )

I have the task to create a password validation that has to consider some things. The only problem I have is that one of the criteria of the password validation is that the password must not contain any sequences, e.g. (12345), (abcdef), (asdfghjk). I have already searched a lot and do not know how to implement this. Can anyone help.
This is how I implemented it.
I also check that there is no sequence in backwards, for example (4321, dcba).
private fun noSequenzes(password: String) : Boolean {
val charRuns = listOf(
'0'..'9',
'a'..'z',
'A'..'Z',
"qwertzuiop".asIterable(),
"asdfghjklöä".asIterable(),
"yxcvbnm".asIterable()
)
var map = emptyMap<Char, MutableSet<Char?>>()
charRuns.forEach { run ->
run.forEach { char ->
val charsToAdd = mutableSetOf(run.elementAtOrNull(run.indexOf(char) + 1))
if (run is CharRange) {
charsToAdd.add(run.elementAtOrNull(run.indexOf(char) - 1))
}
if (map.contains(char)) {
map.get(char)!!.addAll(charsToAdd)
}
else {
map = map.plus(Pair(char, charsToAdd))
}
}
}
var sequenceCounter = 1
var recentChar: Char? = null
password.toCharArray().forEach { c ->
recentChar?.let { rc ->
val isSequence = map.any { me -> me.key == rc && me.value.contains(c) }
if (isSequence) {
sequenceCounter = sequenceCounter + 1
}
else {
sequenceCounter = 1
}
if (sequenceCounter >= 3) {
return false
}
}
recentChar = c
}
return true
}
Since you didn't give much detail into what code you already have and what you're stuck on about the logic, here's a very generalized description of a strategy you could use to do this:
Create a List<Iterable<Char>> that contains all the possible strings of characters that could be considered a range. For example:
val charRuns = listOf(
'0'..'9',
'a'..'z',
'A'..'Z',
"qwertyuiop".asIterable(),
//...
)
Iterate these runs to fill a MutableMap<Char, MutableSet<Char>>, where the keys are any of the characters from the runs, and the values are sets of all the chars that if they appear next in a string should be considered a consecutive sequence.
Iterate the potential password String, using the map to check the subsequent Char of each Char to see if it should be considered part of a sequence. Use a counter variable to count the current size of sequence found so far, and reset it whenever a non-sequence is found. If it ever rises above your threshold for allowable sequence size, reject the password immediately.

Simple inference example tflite + kotlin

I'm trying to adapt a simple example of tflite and android.
val inputArray = arrayOf(initInputArray(bitmap))
val outputMap = initOutputMap(getInterpreter())
getInterpreter().runForMultipleInputsOutputs(inputArray, outputMap)
Since my model only has one output. I change the outputMap into an outputArray
val inputArray = arrayOf(initInputArray(bitmap))
val outputArray = Array(1){ Array(height) { Array(width) { FloatArray( channels }}}
getInterpreter().run(inputArray, outputArray)
However when feeding it to the inference method I get:
DataType error: cannot resolve DataType of [Ljava.nio.ByteBuffer;
Any idea what's going wrong?
Found the error:
val inputArray = arrayOf(initInputArray(bitmap))
was the culprit. When using run instead of runForMultipleInputsOutputs this cannot be an array! So changing the line to
val inputArray = initInputArray(bitmap)
fixes the issue.
A good documentation of the required data formats would have helped...
run -> requires "DirectByteBuffer" as input
runForMultipleInputsOutputs -> requires "ByteBuffer" as input

I need to do faster the process that is getting content and managing flag from javaMail.Message type

I'm trying to slove this problem so long time.
First time , I got the javaMail.Message. I pull the content of mail message and other things in RecyclerView.Adapter -> OnBindViewHolder. But When I pulling content and managing flag , it take so long time.
this is main page
val props = Properties()
props.setProperty("mail.debug", "true")
props.setProperty("mail.imap.port", "143")
props.setProperty("mail.imap.ssl.enable", "true")
props.setProperty("mail.imap.socketFactory.port", "993")
val session = Session.getDefaultInstance(props, authenticator(mailBox.user, mailBox.pass))
val store = session.getStore("imaps")
store.connect(mailBox.mailHost,mailBox.user,mailBox.pass)
val fetchProfile = FetchProfile()
fetchProfile.add(FetchProfile.Item.CONTENT_INFO)
fetchProfile.add(FetchProfile.Item.ENVELOPE)
val emailFolder = store.getFolder("Inbox")
emailFolder.open(Folder.READ_WRITE)
val messages: Array<Message> = emailFolder.messages
emailFolder.fetch(messages,fetchProfile)
activityUiThread {
val adapter = testAdapter(this#MailBox,messages,this#MailBox)
allMail_recycler.adapter = adapter
dialog.dismiss()
}
this is adapter
override fun onBindViewHolder(holder : ViewHolder, position: Int) = runBlocking{
val message = receiveMessage[position]
/** visibility **/
// holder.itemView.d3p.visibility = INVISIBLE
holder.itemView.imV_attach.visibility = INVISIBLE
/** unChangeable **/
val bworker = GlobalScope.launch {
val from = message.from[0].toString().split("<")[0]
val sentDate= message.receivedDate
val subject = message.subject
val content = message.content.toString()
val recepient = message.allRecipients[0].toString()
val seen = message.flags.toString()
val attachent = message.isMimeType("multipart/mixed")
if (attachent){
holder.itemView.imV_attach.visibility = VISIBLE
}
holder.itemView.mailSender.text = from
holder.itemView.dateTimeTxt.text = SimpleDateFormat("MMM dd").format(sentDate)
holder.itemView.subjectTxt.text = subject
holder.itemView.bodyTxt.text = content
// mailBox.data.add(messageModel(from,recepient,subject,content,date,attachent,seen))
}
bworker.join()
holder.itemView.setOnClickListener {
notifyItemChanged(position)
eventChange.change(position)
}
}
this is my project
check this
Let's start by simplifying your code. Replace these lines:
props.setProperty("mail.debug", "true")
props.setProperty("mail.imap.port", "143")
props.setProperty("mail.imap.ssl.enable", "true")
props.setProperty("mail.imap.socketFactory.port", "993")
val session = Session.getDefaultInstance(props, authenticator(mailBox.user, mailBox.pass))
with these:
props.setProperty("mail.debug", "true")
props.setProperty("mail.imap.ssl.enable", "true")
val session = Session.getInstance(props)
This:
val from = message.from[0].toString().split("<")[0]
probably wants to be something like this:
val from = (InternetAddress)(message.from[0]).getAddress()
(Not sure if the cast is needed.)
I don't know why you're using the received data as the sent date, but that's wrong. Why aren't you just using the sent date?
Using message.content.toString is only going to work for a simple plain text message. Certainly any message with an attachment is not going to give you want you want. See the FAQ entry for
find the main message body.
That will also explain why you don't want to pull down the entire message content every time; it's horribly inefficient. You might also need to change your program so that any attachments are only downloaded when the user clicks on them. For debugging, try commenting out the access of message.content and replace it with an empty string and see if the performance is closer to what you're expecting.
If you're still not getting the desired performance, you should look at the other FetchProfile items you might use. You should also post the JavaMail debug output, ideally with a timestamp for each line, or with output from your program showing System.currentTimeMillis() around each one of the key statements in your program.

Split String in two Kotlin

I have one string that if have more than 35 characters have to been split in another string. Something like that var string1 = "1...38" into var result1= "1...35" and var result2 = "36...38". I thinking in using a split but i don't know if is the best option.
chunked is definitely ok if chunking into more then 2 pieces is ok for you too. But if you rather meant splitting it up into at most 2 pieces with the first being of a certain length and the second part only containing the remainder, you may want to use something like the following instead (similar to s1m0nw1s answer, but) using take and substring:
fun String.splitAtIndex(index : Int) = take(index) to substring(index)
Or if you want to play it safe, you can also add some convenience checks:
fun String.splitAtIndex(index: Int) = when {
index < 0 -> 0
index > length -> length
else -> index
}.let {
take(it) to substring(it)
}
or if you like exceptions more:
fun String.splitAtIndex(index: Int) = require(index in 0..length).let {
take(index) to substring(index)
}
All of those functions return you a Pair<String, String>, which you can handle as follows:
"someString".splitAtIndex(5).also { (atMost5Chars, remainder) ->
println("$atMost5Chars | remainder: $remainder")
}
"someOther".splitAtIndex(4).also {
(first) -> println(first) // discard the remainder... but then again you could have used also just take(4)
}
As you wrote that you thought of using split and if you have an appropriate delimiter at hand you may also want to use the following instead:
yourInputString.split(yourDelimiter, limit = 2)
This will split yourInputString into two pieces where the first piece is all the string up to the first occurrence of yourDelimiter. Example:
val yourInputString = "this is a string with a delimiter | and some more information that is not necessary | with some more delimiters | | |"
yourInputString.split('|', limit = 2).also {
(uptoFirstDelimiter, remainder) -> println("$uptoFirstDelimiter --- remainder: $remainder")
}
which will print:
this is a string with a delimiter --- remainder: and some more information that is not necessary | with some more delimiters | | |
You should rather use
drop and droplast (returns a String)
val chars = "abcdefghijklmnopqrstuvwxyzabcdefghijkl"
val result1 = chars.dropLast(3) // returns abcdefghijklmnopqrstuvwxyzabcdefghi
val result2 = chars.drop(35) // returns jkl
or chunked (returns a list of strings)
chars.chunked(35)) // returns [abcdefghijklmnopqrstuvwxyzabcdefghi, jkl]
that depends on your context
chunked(size: Int) will give you back your string split into a list:
"Hello There! This is a really long string that I want split".chunked(10)
Result
["Hello Ther", "e! This is", "a really" , "long strin", "g that I w", "ant split"]
This extension will give you a pair of the limited string associated to the rest:
fun String.limit(max: Int): Pair<String, String> =
if (length > max) {
take(max) to takeLast(length - max)
} else this to ""
Some examples:
val string1 = "onqweinalsdmuizqbwnöfasdkdasqwrwfeqewwqeweqewf" //more than 35
val string2 = "onqweinalsdmuizqbwnöfasdkdasqwrwfeq" //exactly 35
val string3= "asdqwe" //less than 35
println(string1.limit(35)) // -> (onqweinalsdmuizqbwnöfasdkdasqwrwfeq, ewwqeweqewf)
println(string2.limit(35)) // -> (onqweinalsdmuizqbwnöfasdkdasqwrwfeq, )
println(string3.limit(35)) // -> (asdqwe, )
Chunked method is what you need. Check this doc ->
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/chunked.html
I came across similar scenario in card payment where expiry month/year is needed to split for api and pass separate params to network repository and this is how it done.
The Solution:
var expiryMonth:String="12/2034"
expiryMonth.split("/").also {
(uptoFirstDelimiter, remainder) -> println("$uptoFirstDelimiter --- remainder: $remainder")
}

A way to remove specific characters from a string? (kotlin)

So I have a textField where you should enter your "coded" text and get it translated back to non-coded language by using .replace to remove certain characters. But I can't get it to work.
There is a kids "code-language" where you take a word, like cat and for every consonant you add an "o" and the consonant again. So a "b" would be "bob". With vowels they just stay as they are. Cat would be cocatot.
fun translateBack(view : View) {
val konsonanter = "bcdfghjklmnpqrstvwxzBCDFGHJKLMNPQRSTVWXZ"
var input = editText.text.toString()
var emptyString = ""
for(i in konsonanter) {
val find_text = i + "o" + i
var conso = i.toString()
textView.text = input.replace(find_text, conso, false)
}
}
Would like for it to remove the two following letters for every consonant (if possible). So if i enter "cocowow" I should get out "cow". Right now I just get back what I enter in the textField...
Use a forEach loop through the chars of input and replace:
konsonanter.forEach { input = input.replace("${it}o${it}", "${it}", false) }
textView.text = input
The issue is that you're setting the text in textView in every loop, and never updating input. So you're essentially only seeing the result of the replace call that happens with the "ZoZ" and "Z" parameters at the end of the loop, with input still being the original string.
Instead, you can keep updating input and then set the text when you're done:
val konsonanter = "bcdfghjklmnpqrstvwxzBCDFGHJKLMNPQRSTVWXZ"
var input = editText.text.toString()
var emptyString = ""
for (i in konsonanter) {
val find_text = i + "o" + i
val conso = i.toString()
input = input.replace(find_text, conso, false)
}
textView.text = input
If you use the replace function with a Regex and a transform function as parameters you can create a really concise completely self-containing extension function:
fun String.translateBack() = with(Regex("([bcdfghjklmnpqrstvwxz])o\\1", RegexOption.IGNORE_CASE)) {
replace(this) { "${it.value.first()}" }
}
Explanation:
The Regex will match all same consonants (no matter the case) around an "o".
To ensure that the consonant before and after the "o" are the same a backreference to the first group was used.
So, this will also work for cases like "coCatot".
Usage:
println("bob".translateBack()) // b
println("cocatot".translateBack()) // cat
println("coCatot".translateBack()) // cat

Categories

Resources